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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
thishzp/monitor | https://github.com/thishzp/monitor | 457f0bf658847396d4d9ec58780580fda790e437 | c9aae347ee76f9e47eabe1a2b0586afd8977a72d | cc58c15d74e1ed9a94e5c27ce2ea3de6a8ee2def | refs/heads/master | 2021-01-17T21:19:05.061664 | 2017-03-07T08:32:04 | 2017-03-07T08:32:04 | 83,817,566 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5316455960273743,
"alphanum_fraction": 0.6708860993385315,
"avg_line_length": 14.800000190734863,
"blob_id": "06072d816a7696026489e5df8ae526bb3492bfd6",
"content_id": "b38d08117a512b841fe404176e31fcb77454f3c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 79,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 5,
"path": "/webui/web.py",
"repo_name": "thishzp/monitor",
"src_encoding": "UTF-8",
"text": "#coding=utf-8\n#!/usr/bin/env python\n# by Zen\n# Time: 2017/3/7 16:27\nimport web\n"
}
] | 1 |
C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa | https://github.com/C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa | 1866bd8c9c7b168e62592e45090a6a6e303e7632 | ce6d201ae7ed5600db7219ae5e570e9d3f5543b2 | 269e26d76ab7e85a44c57aa273ed7e3e140fbee5 | refs/heads/main | 2023-08-12T04:57:03.012528 | 2021-10-08T06:39:19 | 2021-10-08T06:39:19 | 414,854,348 | 0 | 0 | null | 2021-10-08T05:13:10 | 2021-10-08T05:13:15 | 2021-10-08T05:13:15 | Python | [
{
"alpha_fraction": 0.44265592098236084,
"alphanum_fraction": 0.44668006896972656,
"avg_line_length": 23.850000381469727,
"blob_id": "d90866090f8097cf53a37fe665865f70c714e679",
"content_id": "de334b3355a8955f9ffffb8653abf6f61271d81e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 20,
"path": "/assignments/17MenoresANumero/src/exercise.py",
"repo_name": "C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa",
"src_encoding": "UTF-8",
"text": "def minus (x) :\n variable = []\n for i in range(len(x) ):\n for j in range(len(x[i])) :\n if x[i][j]<10 :\n variable.append(x[i][j])\n return(variable) \ndef main():\n listA = []\n row = int(input())\n column = int(input())\n for i in range (row) :\n listA.append([])\n for j in range (column) :\n n = int(input())\n listA[i].append(n)\n ans = minus (listA)\n print(ans)\nif __name__=='__main__':\n main()\n"
},
{
"alpha_fraction": 0.37843337655067444,
"alphanum_fraction": 0.4984740614891052,
"avg_line_length": 27.08571434020996,
"blob_id": "d19774776fb72db276a283d48de66d2e6a640b90",
"content_id": "9eb9456c005f44d3b7fbdfc07ab5bc2951adf729",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 983,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 35,
"path": "/assignments/09SerieFibonacciListas/tests/input_data.py",
"repo_name": "C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa",
"src_encoding": "UTF-8",
"text": "# IMPORTANT: The length of the lists has to be the same\n\n# List of lists, where each of the inner lists has all the inputs for a single test\ninput_values = [\n # Test case 1\n (\n [6],\n [\"\",\"[0, 1, 1, 2, 3, 5]\"],\n [\"La salida no cumple con el caso de prueba\\nDebe salir [0, 1, 1, 2, 3, 5].\"]\n ),\n # Test case 2\n (\n [10],\n [\"\",\"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\"],\n [\"La salida no cumple con el caso de prueba\\nDebe salir [0, 1, 1, 2, 3, 5, 8, 13, 21, 34].\"]\n ),\n # Test case 3\n (\n [-100, -200, 0],\n [\"\", \"\", \"\", \"[]\"],\n [\"La salida no cumple con el caso de prueba\\nDebe salir Error.\"]\n ),\n # Test case 4\n (\n [-100, -200, 2],\n [\"\", \"\", \"\", \"[0, 1]\"],\n [\"La salida no cumple con el caso de prueba\\nDebe salir [0, 1]].\"]\n ),\n # Test case 5\n (\n [-100, -200, 20],\n [\"\", \"\", \"\", \"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]\"],\n [\"La salida no cumple con el caso de prueba para 20\\n].\"]\n )\n]\n"
},
{
"alpha_fraction": 0.36313867568969727,
"alphanum_fraction": 0.3905109465122223,
"avg_line_length": 17.89655113220215,
"blob_id": "c4f8a9ee88d91741287791e33517e396786831fe",
"content_id": "1be7aab2c67706f72048680ed38ccc4b779aaebe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 548,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 29,
"path": "/assignments/09SerieFibonacciListas/src/exercise.py",
"repo_name": "C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa",
"src_encoding": "UTF-8",
"text": "def main():\n x = -1\n y = 0\n a = 1\n b = 1\n serie = []\n while x <= -1:\n x = int(input())\n if x == 0:\n print(serie)\n elif x==1:\n serie.append(0)\n print(serie)\n elif x==2:\n serie.append(0)\n serie.append(1)\n print(serie)\n else :\n serie.append(0)\n serie.append(1)\n serie.append(1)\n for i in range(x-3) :\n y = a + b\n b = a\n a = y\n serie.append(y)\n print(serie)\nif __name__=='__main__':\n main()\n"
},
{
"alpha_fraction": 0.6909307837486267,
"alphanum_fraction": 0.7034606337547302,
"avg_line_length": 30.037036895751953,
"blob_id": "d2e5f1aff0ee72824806a532c57506527f6790bd",
"content_id": "86a58838f7807fd6a6759b662d2409e584bebf56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1693,
"license_type": "no_license",
"max_line_length": 242,
"num_lines": 54,
"path": "/assignments/09SerieFibonacciListas/README.md",
"repo_name": "C-SON-TC1028-001-2113/listas---tarea-6-BryantOchoa",
"src_encoding": "UTF-8",
"text": "![Tec de Monterrey](../../images/logotecmty.png)\n# Serie Fibonacci usando listas\n## Tema: Listas\n\nModifica el programa que se encuentra en la carpeta `src` que se llama `exercise.py` y que contiene el siguiente código:\n\n```python\ndef main():\n #escribe tu código abajo de esta línea\n\nif __name__ == '__main__':\n main()\n```\n\nLa línea `#escribe tu código abajo de esta línea` es un comentario, el programa la va a ignorar al ejecutarse.\n\nDiseña y codifica un programa en Python que lea la cantidad de n elementos que desea tener en la lista.\nEl programa debe validar que n sea mayor o igual que 0, de lo contrario lo vuelve a solicitar. Como resultado, se debe desplegar la lista con los primeros n elementos de la serie de Fibonacci.\n\n## Entrada\nUn número entero positivo que corresponde al número de términos de la serie de Fibonacci que queremos en la lista. Si el dato recibido es menor que 0, se debe volver a solicitar.\n\n## Salidas\nLa lista con el número de términos de la serie de Fibonacci solicitados, uno por renglon. No uses letreros para solicitar los datos.\n\n## Ejemplos de ejecución del programa\n### Entrada\n```\n>>> 5\n```\n### Salida\n```\n[0, 1, 1, 2, 3]\n```\n### Entrada\n```\n>>> 9\n```\n### Salida\n```\n[0, 1, 1, 2, 3, 5, 8, 13, 21]\n```\n### Entrada\n```\n>>> 0\n```\n### Salida\n```\n[ ]\n```\n\n**Nota:** No te preocupes por esta parte del código `if __name__ == '__main__':` por el momento. No la vamos a necesitar para este programa, pero es una buena práctica incluirla y quedará más claro para que sirve en los siguientes ejercicios.\n\nUna vez que termines tu actividad y la hayas probado con `pytest`, subela a tu repositorio en GitHub, con el proceso de commit + push.\n"
}
] | 4 |
T-Kozikopoulos/todo-list | https://github.com/T-Kozikopoulos/todo-list | ae8fc69fce71dd005ec60af38636cb9adf556be4 | 729c03d68e54919f894899ff33d3456e2fa70314 | a60966be9d884ce15ee5747d393865706cbf3316 | refs/heads/master | 2021-06-28T03:07:11.091111 | 2020-09-24T18:14:54 | 2020-09-24T18:14:54 | 156,973,253 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.638634443283081,
"alphanum_fraction": 0.6677768230438232,
"avg_line_length": 24.9887638092041,
"blob_id": "4659d3daec333be28422dbc491b3d722fad49e4d",
"content_id": "7d06a457d210c113ca3aca0f5bbd032c8593935c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2402,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 89,
"path": "/frontend.py",
"repo_name": "T-Kozikopoulos/todo-list",
"src_encoding": "UTF-8",
"text": "from tkinter import *\r\nfrom backend import Database\r\n\r\n\r\ndatabase = Database(\"todo_list.db\")\r\n\r\n\r\nclass Window(object):\r\n\r\n\tdef __init__(self, window):\r\n\t\tself.window = window\r\n\t\tself.window.wm_title(\"// TODO\")\r\n\r\n\t\tl1 = Label(window, text='Entry')\r\n\t\tl1.grid(row=0)\r\n\r\n\t\tself.entry = StringVar()\r\n\t\tself.e1 = Entry(window, textvariable=self.entry)\r\n\t\tself.e1.grid(row=0, column=1)\r\n\r\n\t\t# List box and scroll bar for it.\r\n\t\tself.lb = Listbox(window, height=8, width=40)\r\n\t\tself.lb.grid(row=2, column=0, rowspan=10, columnspan=5)\r\n\r\n\t\tsb = Scrollbar(window)\r\n\t\tsb.grid(row=2, column=6, rowspan=8)\r\n\r\n\t\tself.lb.configure(yscrollcommand=sb.set)\r\n\t\tsb.configure(command=self.lb.yview)\r\n\r\n\t\tself.lb.bind('<<ListboxSelect>>', self.get_selected_row)\r\n\r\n\t\t# Buttons.\r\n\t\tb1=Button(window, text='Add New', width=14, command=self.add_command)\r\n\t\tb1.grid(row=0, column=7)\r\n\r\n\t\tb2=Button(window, text='Refresh / View All', width=14, command=self.view_command)\r\n\t\tb2.grid(row=7, column=7)\r\n\r\n\t\tb3=Button(window, text='Edit Selected', width=14, command=self.edit_command)\r\n\t\tb3.grid(row=8, column=7)\r\n\r\n\t\tb4=Button(window, text='Delete Selected', width=14, command=self.delete_command)\r\n\t\tb4.grid(row=9, column=7)\r\n\r\n\t\tb5=Button(window, text='Close', width=14, command=window.destroy)\r\n\t\tb5.grid(row=10, column=7)\r\n\r\n\t# Helper for when selecting items from the list is needed.\r\n\tdef get_selected_row(self, event):\r\n\t\ttry:\r\n\t\t\tindex = self.lb.curselection()[0]\r\n\t\t\tself.selected_tuple = self.lb.get(index)\r\n\t\t\tself.e1.delete(0, END)\r\n\t\t\tself.e1.insert(END, self.selected_tuple[1])\r\n\t\t\tself.e2.delete(0, END)\r\n\t\t\tself.e2.insert(END, self.selected_tuple[2])\r\n\t\t\tself.e3.delete(0, END)\r\n\t\t\tself.e3.insert(END, self.selected_tuple[3])\r\n\t\t\tself.e4.delete(0, END)\r\n\t\t\tself.e4.insert(END, self.selected_tuple[4])\r\n\t\t# Bypass useless index error.\r\n\t\texcept IndexError:\r\n\t\t\tpass\r\n\r\n\t# Adding functionality to the buttons.\r\n\tdef view_command(self):\r\n\t\tself.lb.delete(0 ,END)\r\n\t\tfor row in database.view():\r\n\t\t\tself.lb.insert(END,row)\r\n\r\n\tdef add_command(self):\r\n\t\tdatabase.insert(self.entry.get())\r\n\t\tself.lb.delete(0, END)\r\n\t\tself.lb.insert(END, (self.entry.get()))\r\n\r\n\tdef delete_command(self):\r\n\t\tdatabase.delete(self.selected_tuple[0])\r\n\r\n\tdef edit_command(self):\r\n\t\tdatabase.edit(self.selected_tuple[0], self.entry.get())\r\n\r\n\r\n# Creating the window object.\r\nwindow = Tk()\r\nWindow(window)\r\n\r\n# All done!\r\nwindow.mainloop()\r\n"
},
{
"alpha_fraction": 0.6441441178321838,
"alphanum_fraction": 0.6463963985443115,
"avg_line_length": 24.117647171020508,
"blob_id": "0d9dbcef757724ebe305a70dbc5a77357ab46ed9",
"content_id": "95014ea22fe90a4e93591f901a3fff194259986e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 888,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 34,
"path": "/backend.py",
"repo_name": "T-Kozikopoulos/todo-list",
"src_encoding": "UTF-8",
"text": "\"\"\"\r\nNo comments for this one since the function/method names\r\nand SQL commands read so much like English.\r\n\"\"\"\r\nimport sqlite3\r\n\r\n\r\nclass Database:\r\n\r\n\tdef __init__(self, db):\r\n\t\tself.conn = sqlite3.connect(db)\r\n\t\tself.cur = self.conn.cursor()\r\n\t\tself.cur.execute(\"CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, entry text)\")\r\n\t\tself.conn.commit()\r\n\r\n\tdef insert(self, entry):\r\n\t\tself.cur.execute(\"INSERT INTO book VALUES (NULL, ?)\", (entry,))\r\n\t\tself.conn.commit()\r\n\r\n\tdef view(self):\r\n\t\tself.cur.execute(\"SELECT * FROM book\")\r\n\t\trows = self.cur.fetchall()\r\n\t\treturn rows\r\n\r\n\tdef delete(self, id):\r\n\t\tself.cur.execute(\"DELETE FROM book WHERE id=?\", (id, ))\r\n\t\tself.conn.commit()\r\n\r\n\tdef update(self, id, entry):\r\n\t\tself.cur.execute(\"UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?\", (entry, id))\r\n\t\tself.conn.commit()\r\n\r\n\tdef __del__(self):\r\n\t\tself.conn.close()\r\n"
},
{
"alpha_fraction": 0.7775061130523682,
"alphanum_fraction": 0.7775061130523682,
"avg_line_length": 57.42856979370117,
"blob_id": "aef7f45c8d6f37b98597eb9d88947e0e8286408f",
"content_id": "691991bae10f3f7d216a284da18d8a7fda81c7a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 409,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 7,
"path": "/README.md",
"repo_name": "T-Kozikopoulos/todo-list",
"src_encoding": "UTF-8",
"text": "# todo-list\nA to-do list app that runs as script, plus another version that's been packed into an EXE file for easier use.\n\n\nIf you're interested in upgrading this app for personal use or making a similar one, but aren't familiar with the packages used,\ngo to my 'reading-list-database' repository. It was used as a template for this app, so it's a more detailed and better commented\nversion of similar code.\n"
}
] | 3 |
dsanchezEGC/prueba-xyz | https://github.com/dsanchezEGC/prueba-xyz | c45fea73245032d54a6c7546f466dc1ba1cfd7f0 | 543d7afe73a67fe430928c1c0892719a65ab7ad1 | 5f2f2e5cf83c666b30a7efac507a8b72f87a08a4 | refs/heads/master | 2021-01-10T12:21:44.854839 | 2015-11-13T12:52:52 | 2015-11-13T12:52:52 | 46,120,831 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 16.5,
"blob_id": "d95888bc08e0cb2d3808f1b7a53f019d55b8d44b",
"content_id": "a85d0ba7c0c21bad7433f6e820de26dc8d1c6e85",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 35,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 2,
"path": "/README.md",
"repo_name": "dsanchezEGC/prueba-xyz",
"src_encoding": "UTF-8",
"text": "# prueba-xyz\nprueba git contadores\n"
},
{
"alpha_fraction": 0.5111111402511597,
"alphanum_fraction": 0.5777778029441833,
"avg_line_length": 14,
"blob_id": "c45ef05fc0a7dd509c330e0d94a54a8ba88a82a9",
"content_id": "29a7e9ee96aac40e5998447fb02ed229f7b10ef4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 3,
"path": "/cuenta.java",
"repo_name": "dsanchezEGC/prueba-xyz",
"src_encoding": "UTF-8",
"text": "for(i=11,i>0,i--){\n\tSystem.out.println(i);\n}\n"
},
{
"alpha_fraction": 0.529411792755127,
"alphanum_fraction": 0.6470588445663452,
"avg_line_length": 11.75,
"blob_id": "11b1d8a90af34f897e5f5403f827f9498643b9e8",
"content_id": "c41b1fe645aa68399c9a010385dead96848b5491",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 4,
"path": "/cuenta.py",
"repo_name": "dsanchezEGC/prueba-xyz",
"src_encoding": "UTF-8",
"text": "#encoding:utf-8\n\nfor i in range(11,1,-1):\n\tprint 1\n"
}
] | 3 |
ichukai/chest | https://github.com/ichukai/chest | a3a038581b2a179307e26ed8f322d55d36d91fa6 | 3e969c050e06592045d381306400292a948f4b18 | 3a6bb947bc19e154357671ff8ddab77d2d01408a | refs/heads/master | 2020-05-09T09:57:36.447307 | 2019-04-13T14:11:02 | 2019-04-13T14:11:02 | 181,023,764 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5362409353256226,
"alphanum_fraction": 0.5524402856826782,
"avg_line_length": 40.33047103881836,
"blob_id": "368e1872e6646fd3a0e415d324279f4bb5f6a1c5",
"content_id": "2aa7f9059baad5f697dd8d11c13a9b9140978d42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11400,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 233,
"path": "/TotalSpider/lagou.py",
"repo_name": "ichukai/chest",
"src_encoding": "UTF-8",
"text": "\"\"\"\n抓取拉勾网“北京”“数据分析师”30页职位详情数据存入MySQL数据库\n@Author: Newyee\n@Python: 3.6.5\n@selenium: 3.141.0\n@Chrome: 72.0.3626.81\n\"\"\"\nimport os\nimport pickle\nimport random\nimport time\n\nfrom lxml import etree\n# 导入相关模块(未安装可执行 pip install xxx 命令安装)\nfrom selenium import webdriver\n\nfrom TotalSpider.settings import BASE_DIR\n\n\n# 创建类\nclass LagouSpider():\n\n def __init__(self):\n # 初始化类实例时打开谷歌浏览器(可查看测试过程)\n self.driver = webdriver.Chrome(executable_path=BASE_DIR + \"/chromedriver\")\n # 搜索页面的url\n self.urls = [\n \"https://www.lagou.com/jobs/list_AI%E4%BA%A7%E5%93%81%E7%BB%8F%E7%90%86?city=%E5%85%A8%E5%9B%BD\",\n ]\n # 存放所有职位详情页的url\n self.all_links = []\n\n def login(self):\n\n self.driver.execute_script(\"window.open('https://passport.lagou.com/login/login.html')\")\n time.sleep(2)\n self.driver.switch_to.window(self.driver.window_handles[1]) # 切换到新打开的窗口,即第2个--index==1\n self.driver.find_element_by_css_selector(\".form_body .input[type='text']\").send_keys(\"[email protected]\")\n self.driver.find_element_by_css_selector(\".form_body input[type='password']\").send_keys(\"34123\")\n self.driver.find_element_by_css_selector(\"div[data-view='passwordLogin'] input.btn_lg\").click()\n time.sleep(10)\n self.driver.close()\n self.switchMainWindow()\n\n def run2(self, ten_links):\n '''\n 每次对10个职位详情url请求并解析,保存职位详细信息,退出浏览器\n :param ten_links: 10个职位详情页url组成的list\n :return:\n '''\n # 遍历每个detail_url\n for link in ten_links:\n # 调用request_detail_page请求并解析\n self.request_detail_page(link)\n # 随机间隔3-6s,避免反爬\n time.sleep(random.randint(3, 6))\n # 获取10个职位信息后退出浏览器\n self.driver.quit()\n\n def run1(self):\n '''\n 打开搜索页面,并循环翻页至最后一页,解析html获得all_detail_links\n :return:\n '''\n self.login()\n for url in self.urls:\n # 在当前打开的浏览器中加载页面\n self.driver.execute_script(\"window.open('%s')\" % url)\n time.sleep(2)\n self.driver.switch_to.window(self.driver.window_handles[1]) # 切换到新打开的窗口,即第2个--index==1\n # 用于记录当前是第几页\n count_page = 1\n # 循环翻页直到最后一页\n while True:\n # 获取当前页的网页源代码\n source = self.driver.page_source\n # 利用xpath解析source获得detail_links并保存到\n self.get_all_detail_links(source)\n print('Fetched page %s.' % str(count_page))\n # 找到【下一页】按钮所在的节点\n next_btn = self.driver.find_element_by_xpath('//div[@class=\"pager_container\"]/span[last()]')\n if count_page >= 6:\n break\n # 判断【下一页】按钮是否可用\n if \"pager_next_disabled\" in next_btn.get_attribute(\"class\"):\n # if count_page==1:\n # 【下一页】按钮不可用时即达到末页,退出浏览器\n self.driver.close()\n self.switchMainWindow()\n break\n else:\n # 【下一页】按钮可用则点击翻页\n next_btn.click()\n count_page += 1\n time.sleep(random.randint(1, 3))\n self.driver.quit()\n # 返回所有职位详情页url列表(去重后的)\n return list(set(self.all_links))\n\n def switchMainWindow(self):\n self.driver.switch_to.window(self.driver.window_handles[0]) # 切换到主窗口(否则不能再次打开新窗口)\n\n def get_all_detail_links(self, source):\n '''\n 利用xpath解析source获得detail_links并保存到self.all_links\n :param source: 网页源代码html\n :return:\n '''\n try:\n html = etree.HTML(source)\n links = html.xpath('//a[@class=\"position_link\"]/@href')\n self.all_links += links\n except Exception:\n print(\"安全拦截,等待~\")\n time.sleep(3)\n self.get_all_detail_links(self.driver.page_source)\n\n def request_detail_page(self, url):\n '''\n 请求职位详情页面,并调用parse_detail_page函数\n :param url: 职位详情页url\n :return:\n '''\n\n # 在当前窗口中同步执行javascript\n self.driver.execute_script(\"window.open('%s')\" % url) # 执行后打开新页面(句柄追加一个新元素)\n time.sleep(2)\n # driver.switch_to.window:将焦点切换到指定的窗口\n # driver.window_handles:返回当前会话中所有窗口的句柄\n self.driver.switch_to.window(self.driver.window_handles[1]) # 切换到新打开的窗口,即第2个--index==1\n source = self.driver.page_source\n self.parse_detail_page(source)\n self.driver.close()\n self.switchMainWindow()\n\n def parse_detail_page(self, source):\n '''\n 解析详情页,用xpath提取出需要保存的职位详情信息并保存\n :param source: 职位详情页的网页源代码html\n :return:\n '''\n # 将source传入lxml.etree.HTML()解析得到etree.HTML文档\n html = etree.HTML(source)\n # 对html用xpath语法找到职位名称所在节点的文本,即position_name\n position_name = html.xpath(\"//span[@class='name']/text()\")[0]\n # 对html用xpath语法找到职位id所在的节点,提取获得position_id\n position_id = html.xpath(\"//link[@rel='canonical']/@href\")[0].split('/')[-1].replace('.html', '')\n\n # 找到职位标签,依次获取:薪资、城市、年限、受教育程度、全职or兼职\n job_request_spans = html.xpath('//dd[@class=\"job_request\"]//span')\n salary = job_request_spans[0].xpath('.//text()')[0].strip() # 列表索引0==xpath第1个节点\n city = job_request_spans[1].xpath('.//text()')[0].strip().replace(\"/\", \"\").strip()\n work_year = job_request_spans[2].xpath('.//text()')[0].strip(\"/\").strip()\n education = job_request_spans[3].xpath('.//text()')[0].strip(\"/\").strip()\n\n # 找到公司标签,获取company_short_name\n company_short_name = html.xpath('//dl[@class=\"job_company\"]//em/text()')[0].replace(\"\\n\", \"\").strip()\n # 找到公司标签中的industry_field和finance_stage\n company_infos = html.xpath('//dl[@class=\"job_company\"]//li') # 注意该节点下的text()索引0和2是空的\n industry_field = company_infos[0].xpath('.//text()')[1].replace(\"\\n\", \"\").strip()\n finance_stage = company_infos[1].xpath('.//text()')[1].replace(\"\\n\", \"\").strip()\n\n # 找到工作地址所在的区\n district = html.xpath('//div[@class=\"work_addr\"]/a[2]/text()')[0].strip()\n\n # 找到职位诱惑,获取position_advantage\n position_advantage = html.xpath('//dd[@class=\"job-advantage\"]//p/text()')[0].strip(\"/\").strip().replace(\",\",\n \",\")\n # 找到所有职位标签,用\",\"连接成字符串\n position_labels = \",\".join(html.xpath('//li[@class=\"labels\"]//text()')).strip()\n # 职位描述\n job_desc = \"\".join(html.xpath('//div[@class=\"job-detail\"]//p/text()')).replace(\"<br>\", \"\").strip()\n # 生成MySQL插入语句\n sql = \"INSERT INTO %s (position_name, work_year, education, finance_stage, company_short_name, \" \\\n \"industry_field, city, salary, position_id, position_advantage, district, position_labels \" \\\n \",job_desc) VALUES \" \\\n \"('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');\" % (\n table_name,\n position_name, work_year, education, finance_stage, company_short_name, industry_field,\n city, salary, position_id, position_advantage, district, position_labels, job_desc)\n # 以追加的方式打开table_name.sql文件,写入sql语句\n with open('%s.sql' % table_name, 'a', encoding='utf-8') as f:\n f.write(sql + '\\n')\n print('Saved position:', position_id)\n\n\nif __name__ == \"__main__\":\n # 记录项目开始时间\n start_time = time.time()\n # 数据库中将要创建的表名,可自行修改\n table_name = 'DataAnalyst_Beijing'\n # 数据库中创建表语句(字段类型设置请自行调整优化,作者目前在这方面经验不多)\n create_table_sql = \"CREATE TABLE IF NOT EXISTS %s ( \" \\\n \"id INT(5) NOT NULL AUTO_INCREMENT, \" \\\n \"position_name VARCHAR(512) DEFAULT NULL, \" \\\n \"work_year VARCHAR(64) DEFAULT NULL, \" \\\n \"education VARCHAR(64) DEFAULT NULL, \" \\\n \"finance_stage VARCHAR(1024) DEFAULT NULL, \" \\\n \"company_short_name VARCHAR(64) DEFAULT NULL, \" \\\n \"industry_field VARCHAR(1024) DEFAULT NULL, \" \\\n \"city VARCHAR(64) DEFAULT NULL, \" \\\n \"salary VARCHAR(64) DEFAULT NULL, \" \\\n \"position_id VARCHAR(64) DEFAULT NULL, \" \\\n \"position_advantage VARCHAR(1024) DEFAULT NULL, \" \\\n \"district VARCHAR(64) DEFAULT NULL, \" \\\n \"position_labels VARCHAR(1024) DEFAULT NULL,job_desc LONGTEXT, \" \\\n \"PRIMARY KEY (id) );\" % table_name\n # 创建table_name.sql文件,写入建表语句\n with open('%s.sql' % table_name, 'w', encoding='utf-8') as f:\n f.write(create_table_sql + '\\n')\n\n needed_all_links = []\n if os.path.exists(BASE_DIR + \"/urls/quanguo.urls\"):\n needed_all_links = pickle.load(open(BASE_DIR + \"/urls/quanguo.urls\", \"rb\"))\n if not needed_all_links:\n # 实例化LagouSpider类,调用run1方法获取所有职位详情页的url\n needed_all_links = LagouSpider().run1()\n pickle.dump(needed_all_links, open(BASE_DIR + \"/urls/quanguo.urls\", \"wb\"))\n # 将所有职位详情url以10位单位拆分成嵌套列表\n nested_all_links = [needed_all_links[i:i + 10] for i in range(0, len(needed_all_links), 10)]\n count = 10\n # 连续请求10个详情页就会弹出登录页,故每请求10个重启一次浏览器\n for ten_links in nested_all_links:\n # 每10个为一组,打开一次浏览器,调用run2方法保存职位详细信息\n LagouSpider().run2(ten_links)\n # count计数调整间隔时间,请求过多弹出登录\n count += 10\n print('-------------------------')\n print('Have fetched %s positions.' % str(count))\n\n # 记录项目结束时间\n end_time = time.time()\n print('\\n【项目完成】\\n【总共耗时:%.2f分钟】' % ((end_time - start_time) / 60))\n"
},
{
"alpha_fraction": 0.4522292912006378,
"alphanum_fraction": 0.5159235596656799,
"avg_line_length": 18.75,
"blob_id": "84df7b834f9853f71480d876e379c43f9fc1a776",
"content_id": "c3b71b077d0e0ce0eb31a1d093db4aac4bd93592",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 157,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 8,
"path": "/TotalSpider/test.py",
"repo_name": "ichukai/chest",
"src_encoding": "UTF-8",
"text": "def delRep(list1):\n list2=[]\n for i in list1:\n if i not in list2:\n list2.append(i)\n return list2\n\nprint(delRep([\"1\",\"1\",\"2\",\"2\"]))"
},
{
"alpha_fraction": 0.577102780342102,
"alphanum_fraction": 0.5817757248878479,
"avg_line_length": 31.923076629638672,
"blob_id": "8c4ffc83a3a856ba0fba6d12fcbed913cdc5518f",
"content_id": "459436badad2cb80ea16f6f3f3f9a98fbc295681",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 440,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 13,
"path": "/TotalSpider/TextParse.py",
"repo_name": "ichukai/chest",
"src_encoding": "UTF-8",
"text": "import re\n\nfrom TotalSpider.settings import BASE_DIR\n\nfiles = [\"/csv/spider_job_pd_ai_p6.csv\", \"/csv/spider_job_pd.csv\"]\noutput = \"/csv/spider_job_pd_ai_all.csv\"\nstr = [];\nfor file in files:\n with open(BASE_DIR + file, 'r') as file:\n for line in file.readlines():\n if re.search(\"ai|智能|机器学习\", line):\n with open(BASE_DIR + output, \"a\", encoding='utf-8') as f:\n f.write(line)\n"
},
{
"alpha_fraction": 0.7485714554786682,
"alphanum_fraction": 0.7599999904632568,
"avg_line_length": 19.52941131591797,
"blob_id": "cd419ab9cc890e508121728facda46370332082a",
"content_id": "b4f50c7cde6e95bcf6fd7230f04ac9b10065f4d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 350,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 17,
"path": "/TotalSpider/README.md",
"repo_name": "ichukai/chest",
"src_encoding": "UTF-8",
"text": "\nbrew install python3\nbrew install mysql-connector-c\nedit mysql_config (locate it: which mysql_config)\ncorrect this in mysql_config:\n\n# Create options \nlibs=\"-L$pkglibdir\"\nlibs=\"$libs -l \"\nIt shoud be:\n\n# Create options \nlibs=\"-L$pkglibdir\"\nlibs=\"$libs -lmysqlclient -lssl -lcrypto\"\n\npip3 install mysqlclient\npip3 install scrapy\npip3 install pandas "
}
] | 4 |
raylai/hymns-radio-lyrics | https://github.com/raylai/hymns-radio-lyrics | 9ee1710c49af384d7a4cd4952093563dacdc5a63 | bd9cd846e24585e5103e0063ee3d129349d0443b | af2d4be154731e7751cbe4723c05ac6f4c904a05 | refs/heads/master | 2020-04-20T10:07:45.465616 | 2019-02-02T01:39:42 | 2019-02-02T01:39:42 | 168,782,314 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5407155156135559,
"alphanum_fraction": 0.550255537033081,
"avg_line_length": 25.926605224609375,
"blob_id": "0503b47dbfa9408096de69546c0ab3b593895880",
"content_id": "8426c7faf22ba7b6d0ddf31c2a5d007d5d0e242e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2945,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 109,
"path": "/lyrics.py",
"repo_name": "raylai/hymns-radio-lyrics",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\nimport requests\nimport ssl\nimport sys\nimport time\nfrom bs4 import BeautifulSoup\nfrom functools import reduce\n\n\nutf8Map = {\n ('’', \"'\"), # single right quote\n ('“', '\"'), # double left quote\n ('”', '\"'), # double right quote\n}\n\ncp1252Map = {\n ('', \"`\"), # single left quote\n ('', \"'\"), # single right quote\n ('', '\"'), # double left quote\n ('', '\"'), # double right quote\n}\n\n\ndef tr(mapping, src):\n return reduce(lambda a, kv: a.replace(*kv), mapping, src)\n\ndef hget(hymnNum, hymnLetter):\n cat = {\n 'C': 'h/',\n 'B': 'lb/',\n 'N': 'ns/',\n 'T': 'nt/'\n }\n try:\n r = requests.get('https://www.hymnal.net/en/hymn/'\n + cat[hymnLetter] + hymnNum)\n except requests.exceptions.ConnectionError as e:\n return e\n\n soup = BeautifulSoup(r.text, 'html.parser')\n # There should only be one \"lyrics\" class.\n lyrics = soup.select('.lyrics')[0]\n # Each \"td\" is a stanza or stanza number. Join them with newlines.\n stanzas = ['\\n'.join(t.stripped_strings) for t in lyrics.select('td')]\n stanzas = [tr(utf8Map, s) for s in stanzas]\n\n return '\\n'.join(stanzas) + '\\n\\n' + r.url\n\ndef wget(hymnNum):\n try:\n r = requests.get('http://www.witness-lee-hymns.org/hymns/H'\n + hymnNum + '.html')\n except requests.exceptions.ConnectionError as e:\n return e\n\n soup = BeautifulSoup(r.text, 'html.parser')\n # Each \"text2\" class is a stanza.\n text = soup.select('.text2')\n stanzas = [''.join(t.stripped_strings) for t in text]\n # Remove blank sections.\n stanzas = filter(lambda x: len(x), stanzas)\n # Remove headers.\n headers = ('SUBJECT', 'METER', 'AUTHOR', 'COMPOSER')\n notHeader = lambda s: s.split(':')[0] not in headers\n stanzas = filter(notHeader, stanzas)\n stanzas = [tr(cp1252Map, s) for s in stanzas]\n\n return '\\n'.join(stanzas) + '\\n\\n' + r.url\n\ndef sget():\n r = requests.get('http://listen.hymnsradio.com:2199/external/rpc.php',\n params={'m': 'streaminfo.get', 'username': 'hymnsradio'})\n\n json = r.json()\n track = json['data'][0]['track']\n track['json'] = json\n return track\n\ndef loop():\n cur = None\n\n while True:\n try:\n track = sget()\n except requests.exceptions.ConnectionError as e:\n print(e)\n time.sleep(10)\n continue\n artist, title, stream = track['artist'], track['title'], track['json']\n if (artist, title) != cur:\n titleAscii = tr(utf8Map, title)\n print('\\n')\n print(titleAscii + '\\n')\n\n cat, num = artist[2], artist[3:]\n if cat == 'L':\n print(wget(num))\n elif cat in 'CBNT':\n print(hget(num, cat))\n\n cur = (artist, title)\n time.sleep(10)\n\nif __name__ == '__main__':\n try:\n loop()\n except KeyboardInterrupt:\n pass\n"
}
] | 1 |
AniketGurav/word_spotting | https://github.com/AniketGurav/word_spotting | fff159a392c927686f041d02b534c1df836e86c3 | df1ed0ccf5e2749a4cb67ecd8484674ea9137309 | 0721e86a66de73ce771910595f129844d5f825a3 | refs/heads/master | 2023-03-17T04:34:12.813268 | 2019-07-05T18:41:36 | 2019-07-05T18:41:36 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6671791076660156,
"alphanum_fraction": 0.676018476486206,
"avg_line_length": 29.9761905670166,
"blob_id": "8ce0eb4d14b316090f84cddbd34b2fabf34f7091",
"content_id": "1cb3a334651fbdfff2295a8094b3603355976563",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2602,
"license_type": "permissive",
"max_line_length": 138,
"num_lines": 84,
"path": "/misc/preprocess.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: tomas\n\"\"\"\nimport json\nimport os\nimport numpy as np\nimport misc.data_augmentation as da\nimport misc.db_utils as dbu\n\nroot_dir = 'data/washington/'\nfold = 1\ndb = 'washington'\ndata = dbu.load_washington(fold, root_dir)\n\ntexts = [datum['text'] for datum in data]\n\nvocab, indeces = np.unique(texts, return_index=True)\nprint \"size of vocabulary:\", len(vocab)\n\nitow = {i+1:w for i,w in enumerate(vocab)} # a 1-indexed vocab translation table\nwtoi = {w:i+1 for i,w in enumerate(vocab)} # inverse table\n\nfor datum, text in zip(data, texts):\n datum['label'] = wtoi[text]\n\ndb = root_dir + db\n\n# Write washington data to h5 database, needed for evaluation purposes\ndbu.write_to_db_full(data, db)\n\n#Write accompanying json data\njson_output = {}\njson_output['data'] = data\njson_output['image_db'] = db\n\nwith open('%s_preprocessed.json' % db, 'w') as f:\n json.dump(json_output, f)\n \ndb = db + '_fold_%d' % fold\npiece_size = 250000\n\n#Write data augmented washington to h5 data, for training.\naugmented_dir = os.path.join(root_dir, 'augmented/')\naugmented_data = da.augment_data(data, augmented_dir)\ndb += '_synth'\ninds = np.random.permutation(len(augmented_data))\naugmented_data = [augmented_data[i] for i in inds]\ndbu.write_to_db(augmented_data, db, piece_size)\n\n#%%\n#Write accompanying json data\njson_output = {}\njson_output['itow'] = itow\njson_output['wtoi'] = wtoi\njson_output['data'] = augmented_data\njson_output['image_db'] = db\njson_output['inds'] = inds.tolist()\njson_output['pieces'] = np.ceil(np.array(dbu.lens_by_split(augmented_data)).astype(np.float32) / piece_size).astype(np.int32).tolist()\n\nwith open('%s_preprocessed.json' % db, 'w') as f:\n json.dump(json_output, f)\n\n#Write embedding databases\nfor embedding in ['dct3', 'ngram', 'semantic', 'phoc']:\n we = np.load('embeddings/washington_%s_embeddings.npy' % (embedding))\n we = we[indeces, :]\n wtoe = {w:we[i] for i, w in enumerate(vocab)} #word embedding table\n embedding_db = db + '_' + embedding\n \n # Write embedding data to h5\n dbu.write_to_embedding_db(augmented_data, wtoe, embedding_db, piece_size)\n \n #Write accompanying json data\n json_output = {}\n json_output['itow'] = itow\n json_output['wtoi'] = wtoi\n json_output['data'] = data\n json_output['image_db'] = db\n json_output['embedding_db'] = embedding_db\n json_output['pieces'] = np.ceil(np.array(dbu.lens_by_split(augmented_data)).astype(np.float32) / piece_size).astype(np.int32).tolist()\n \n with open('%s_preprocessed.json' % embedding_db, 'w') as f:\n json.dump(json_output, f)\n"
},
{
"alpha_fraction": 0.6627960205078125,
"alphanum_fraction": 0.6778233051300049,
"avg_line_length": 34.41935348510742,
"blob_id": "4637e752af037d8e1b9be3cb5219ae97463e970f",
"content_id": "4b45bdbfd960bc69c0db93d9579eb6f29003bf19",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4392,
"license_type": "permissive",
"max_line_length": 132,
"num_lines": 124,
"path": "/misc/DataLoader_we.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'hdf5'\nlocal utils = require 'misc.utils'\nlocal npy4th = require 'npy4th'\nlocal DataLoaderWE = torch.class('DataLoaderWE')\n\nfunction DataLoaderWE:__init(opt)\n \n -- load the json file which contains additional information about the dataset\n print('DataLoaderWE loading json file: ', opt.root_dir .. opt.dataset .. '_preprocessed.json')\n self.json = utils.read_json(opt.root_dir .. opt.dataset .. '_preprocessed.json')\n \n self.data = {}\n self.data.splits = {}\n for i=1, #self.json.data do\n self.data.splits[i] = self.json.data[i].split \n end\n\n -- open the hdf5 file\n self.image_h5_file = hdf5.open(self.json.image_db .. '.h5', 'r')\n self.embedding_h5_file = hdf5.open(self.json.embedding_db .. '.h5', 'r')\n self.root_dir = opt.root_dir\n\n if opt.mode == 'train' then\n self.pieces = self.json.pieces[1]\n self.current_piece = 1\n \n --Load the first piece, or only piece if there is only one\n self.data.embeddings = self.embedding_h5_file:read('/train_embeddings_1'):all() \n self.data.labels = self.image_h5_file:read('/train_labels_1'):all()\n self.data.images = self.image_h5_file:read('/train_images_1'):all()\n\n -- normalize the data by mean subtraction\n self.stats = utils.get_stats(self.data.images)\n -- torch.save('stats.'.. opt.dataset..'.t7', stats)\n npy4th.savenpy(self.json.image_db .. '.mean.npy', torch.Tensor({self.stats.mi}))\n self.data.images:add(-self.stats.mi)\n\n -- extract image size from dataset\n local train_images_size = #self.data.images\n assert(#train_images_size == 4, '/train_images should be a 4D tensor')\n self.num_images = train_images_size[1]\n self.num_channels = train_images_size[2]\n self.image_height = train_images_size[3]\n self.image_width = train_images_size[4]\n print(string.format('read %d images of size %dx%dx%d', self.num_images, self.num_channels, self.image_height, self.image_width))\n\n self.embedding_size = (#self.data.embeddings)[2]\n self.ordered_data = utils.ArrangeByLabel(self.data)\n \n -- Initialize iterators, used for get_batch\n self.iterators = {}\n self.iterators['train'] = 1\n\n end\n self.image_h5_file:close()\n self.embedding_h5_file:close()\nend\n\nfunction DataLoaderWE:get_embedding_size()\n return self.embedding_size\nend\n\nfunction DataLoaderWE:get_data()\n return self.data\nend\n\nfunction DataLoaderWE:resetIterator(split)\n self.iterators[split] = 1\nend\n\nfunction DataLoaderWE:switch_data_piece(piece)\n print(\"switching to data piece \" .. piece)\n -- Load next data piece\n self.image_h5_file = hdf5.open(self.json.image_db .. '.h5', 'r')\n self.embedding_h5_file = hdf5.open(self.json.embedding_db .. '.h5', 'r')\n self.data.embeddings = self.embedding_h5_file:read('/train_embeddings_' .. piece):all() \n self.data.labels = self.image_h5_file:read('/train_labels_' .. piece):all()\n self.data.images = self.image_h5_file:read('/train_images_' .. piece):all()\n self.image_h5_file:close()\n self.embedding_h5_file:close()\n\n -- Subtract training mean and update some variables\n self.data.images:add(-self.stats.mi)\n local train_images_size = #self.data.images\n self.num_images = train_images_size[1]\n self.current_piece = piece\n self.ordered_data = utils.ArrangeByLabel(self.data)\nend\n\n--[[\n Returns a batch of data:\n - x (N, 1, 60, 160) containing the images\n - y (N, M) containing the embeddings of dimension M\n - z (N) Labels for whether or not pairs belong to same class, used for cosine embedding loss\n--]]\nfunction DataLoaderWE:getBatch(opt)\n local batch_size = utils.getopt(opt, 'batch_size') -- how many images get returned at one time \n\n -- Sample random pairs\n self.data.pairs = utils.generate_pairs(self.ordered_data, batch_size)\n\n local x=torch.zeros(batch_size,1,60,160):cuda() -- Images, hard coded size\n local y=torch.zeros(batch_size, self.embedding_size):cuda() -- Word embeddings\n local z=torch.zeros(batch_size):cuda() -- Labels, in {-1, 1}\n\n local split = 'train'\n local k = self.iterators[split]\n for i=1,batch_size do \n if self.pieces > 1 and k > self.num_images then \n self:switch_data_piece((self.current_piece % self.pieces) + 1) \n k = 1\n end\n local t = self.data.pairs\n x[i] = self.data.images[t[i][1]]\n y[i] = self.data.embeddings[t[i][2]]\n z[i] = t[i][3]\n k = k + 1\n end\n self.iterators[split] = k\n\n local data = {x, y, z}\n return data\n\nend\n"
},
{
"alpha_fraction": 0.644032895565033,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 24.13793182373047,
"blob_id": "4476b32b85713965bdf33426143fd6a5da7226d1",
"content_id": "43d91fe6f2c6935d2415dd167b96b40a5d184e07",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1458,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 58,
"path": "/misc/eval.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'cutorch'\nrequire 'cunn'\nrequire 'cudnn'\nrequire 'nn'\nrequire 'torch'\nrequire 'misc.DataLoader'\nnpy4th = require 'npy4th'\n\nopt = {}\nopt.dataset = 'washington'\nopt.mode = 'full'\nopt.root_dir = 'data/washington/'\n\nloader = DataLoader(opt)\ndata = loader:get_data()\nN = data.images:size(1)\nfolds = 1\nembeddings = {'triplet', 'dct3', 'ngram', 'semantic', 'phoc'}\n\nfor i = 1, #embeddings do\n\tembedding = embeddings[i]\n\titer = 30000\n\tfor fold = 1, folds do\n\t \tif embedding == 'triplet' then\n\t\t\titer = 50000\n\t\tend\n\t\t\n\t\tmodel = 'checkpoints/washington_' .. embedding .. '_fold_' .. fold .. '_iter_' .. iter .. '.t7'\n\t\t\n\t\tloaded_checkpoint = torch.load(model)\n\t\tprotos = loaded_checkpoint.protos\n protos.mlp:cuda()\n\n\t \tif embedding == 'triplet' then\n\t \t\tcnn = protos.mlp.modules[1].modules[1]\n\t \telse \n\t \t\tcnn = protos.mlp.modules[1]\n\t \tend\n\n\t\tprint('loaded network ' .. model)\n\t\t \n\t\t-- extract the cnn to get the descriptors from a network\n\t\tcnn:evaluate()\n\t\tds = #cnn:forward(torch.CudaTensor(1, 1, 60, 160))\n descriptor_size = ds[2]\n\n\t\tBatchSize = 128\n\t\tdescriptors = torch.CudaTensor(N, descriptor_size)\n\t\tdescriptor_split = descriptors:split(BatchSize)\n\t\tfor i,v in ipairs(data.images:split(BatchSize)) do\n\t\t\tdescriptor_split[i]:copy(cnn:forward(v:cuda()))\n\t\tend\n\n\t\t-- Save descriptors for further processing in python\n\t\tnpy4th.savenpy('descriptors/washington_' .. embedding .. '_fold_' .. fold .. '_descriptors.npy', descriptors)\n\n\tend\nend\n"
},
{
"alpha_fraction": 0.7345600128173828,
"alphanum_fraction": 0.7726361751556396,
"avg_line_length": 44.35537338256836,
"blob_id": "709f6e9085481055fbc8178e97d209ed027d3b97",
"content_id": "2553de32e989b0794cda03e5b0a5b9bdeb00afbb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5490,
"license_type": "permissive",
"max_line_length": 575,
"num_lines": 121,
"path": "/README.md",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "## Semantic and Verbatim Word Spotting using Deep Neural Networks\n![System Architecture](system.png)\n\nThis is a minimal implementation of the model from the paper [Semantic and Verbatim Word Spotting using Deep Neural Networks](http://www.diva-portal.org/smash/get/diva2:1044046/FULLTEXT01.pdf). The model allows you to embed word images into any general vector space in which you can perform query-by-example and query-by-string word spotting (image retrieval) and probably perform decent enough transcription of word images. The model is a [pre-activation ResNet](https://arxiv.org/pdf/1603.05027.pdf) followed by a small MLP that embeds an image into a word embedding space.\n\nThis space can be verbatim (distance corresponds to string similarity) and semantic (distance corresponds to string and semantic similarity). Two of the embeddings investigated in the paper are learned word embeddings extracted from the LSTM-char-large model from the paper [Character-Aware Neural Language Model](https://arxiv.org/pdf/1508.06615.pdf). Get authors' Torch implementation from [here](https://github.com/yoonkim/lstm-char-cnn).\n\nParts of this code is based on the PN-Net architecture for learning local image descriptors, available at https://github.com/vbalnt/pnnet.\n\nIf you make use of this code in a scientific context, please cite \n\n```\n@inproceedings{Wilkinson2016_WS,\n booktitle = {International Conference on Frontiers in Handwriting Recognition},\n author = {Wilkinson, Tomas and Brun, Anders.},\n title = {{Semantic and Verbatim Word Spotting using Deep Neural Networks}},\n year = {2016}\n}\n```\n\n#### Paper Errata\nWhen preparing my code for this release, I have discovered mistake in the paper. I accidentally write that I use the [original ResNet](https://arxiv.org/pdf/1512.03385v1.pdf) model but I actually used the [pre-activation ResNet](https://arxiv.org/pdf/1603.05027.pdf).\n\n### Requirements\nAs of now, the code requires an NVIDIA GPU with CUDA installed. The triplet network requires less than 6 GBs of memory while the embedding network requires less than 2 GBs. You can further reduce the memory footprint by using the [OptNet](https://github.com/fmassa/optimize-net) package. This could be useful if you have trouble fitting your models on your GPUs.\n\nThe code is written in Python and Lua, and requires Torch, which can be installed from [here](http://torch.ch/docs/getting-started.html). \n\nIt also requires the following Torch packages: \n - npy4th\n - hdf5\n\nwhich can be installed with \n```\nluarocks install npy4th\nluarocks install hdf5\n```\n\nIt also has the following python dependencies:\n - numpy\n - scipy\n - h5py\n - scikit-image\n\nwhich can be installed using the command \n```\npip install numpy scipy skimage h5py\n```\n\n### Data\nYou can download the Washington dataset from [this link](http://ciir.cs.umass.edu/downloads/gw/gw_20p_wannot.tgz) or using \n\n```\ncd data/washington\nwget http://ciir.cs.umass.edu/downloads/gw/gw_20p_wannot.tgz\ntar -xzf gw_20p_wannot.tgz\ncd ../../\n```\n\nYou also need to download the embeddings and put them in the embeddings folder\n\n```\nmkdir embeddings\ncd embeddings\nwget http://user.it.uu.se/~tomwi522/washington_embeddings.zip\nunzip washington_embeddings.zip\ncd ../\n```\n\nFinally, you need to download the model used to initialize the networks, trained on the [CVL](https://www.caa.tuwien.ac.at/cvl/research/cvl-databases/an-off-line-database-for-writer-retrieval-writer-identification-and-word-spotting/) dataset.You can find it [here](https://uppsala.box.com/s/bbc35q5a171qzpvshiqes670fhuke5ch). Save the model to the folder `pretrained´.\n\n### Pre-trained models \nYou can download some [pre-trained models](https://uppsala.box.com/s/o9y7oc05w98xvqttfjvse25vf3zzczng) for a fold 1 using the 4 embeddings. Trained using this code base. Note that these models are saved as CudaTensors and thus require cutorch and cudnn.\n\n### Training from scratch\nCode to setup the Washington dataset is suplied in misc/preprocess.py. Running\n```\npython misc/preprocess.py\n```\nwill load the Washington dataset, setup the necessary image and embedding hdf5 databases. \n\nMake sure to download the Washington dataset before running this\n\nThen run \n\n```\n./train_net.sh\n```\n\nTo train the triplet network and the 4 different embeddings. You can comment away some of the commands if you're only interested in one specific embedding.\n\nTo evaluate the models first run\n\n```\nth misc/eval.lua\n```\n\nto extract descriptors for each word image, then run \n\n```\npython eval_test.py\n```\n\nto get QbE and QbS MaP scores for the different. It should look something like this:\n\n```\ntriplet Washington QbE 94.0120767804 , QbS: -100.0\nsemantic Washington QbE 96.7435996072 , QbS: 71.2676505913\nngram Washington QbE 96.9961577901 , QbS: 82.7666758942\nphoc Washington QbE 97.7626788718 , QbS: 92.6989763255\ndct3 Washington QbE 97.3370356691 , QbS: 94.1436752847\n```\n\n### Training on new data\nTo train on a new dataset you need to create corresponding function in misc/db_utils.py that loads the dataset in question. The function should return a list of data where each entry is a dictionary with the following keys/values:\n\n - file: The absolute path to the word image\n - split: one of 'train'/'val'/'test'\n - text: the ground truth transcription.\n\nall values should be strings. Then you need to modify misc/preprocess.py to load your dataset instead and create your hdf5 databases. The rest of the process should just require minor changes to the existing scripts to train on a new dataset.\n\n"
},
{
"alpha_fraction": 0.4766521155834198,
"alphanum_fraction": 0.4944019615650177,
"avg_line_length": 34.1875,
"blob_id": "8a54eedd6d927376d8313e97de212985cc27c3b9",
"content_id": "a45ad70d5a304b8315452b0be050b28cab0dd870",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7324,
"license_type": "permissive",
"max_line_length": 121,
"num_lines": 208,
"path": "/misc/db_utils.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 24 12:37:46 2016\n\n@author: tomas\n\"\"\"\n\nimport os\nimport glob\nimport json\nimport string\n\nimport scipy as sp\nimport numpy as np\nfrom skimage.io import imread, imsave\nfrom skimage.color import rgb2gray\nfrom skimage.util import img_as_ubyte\nfrom skimage.transform import resize\nimport h5py\n\n########################################\n# Utilities for h5 dataset creation #\n######################################\n\ndef replace_tokens(text, tokens):\n for t in tokens:\n text = text.replace(t, '')\n \n return text\n \ndef lens_by_split(data):\n ntrain, nval, ntest = 0, 0, 0\n for datum in data:\n if datum['split'] == 'train':\n ntrain += 1\n elif datum['split'] == 'val':\n nval += 1\n elif datum['split'] == 'test':\n ntest += 1\n else:\n raise ValueError\n \n return (ntrain, nval, ntest)\n \ndef _prepare_img(f):\n img = rgb2gray(imread(f))\n try: \n img = img_as_ubyte(resize(img, (60, 160)))\n img = np.invert(img)\n \n except ValueError:\n img = img_as_ubyte(resize(img, (60, 160)))\n print \"failed to preprocess\", f.split('/')[-1]\n \n img = img[np.newaxis, :, :]\n return img\n\ndef write_to_db_full(data, db):\n print \"writing to %s.h5\" % db\n N = len(data)\n labels = [datum['label'] for datum in data]\n\n f = h5py.File(db + '.h5', \"w\")\n f.create_dataset(\"labels\", dtype='uint32', data=labels)\n dset = f.create_dataset(\"images\", (N,1,60,160), dtype='uint8') # space for resized images\n for i, datum in enumerate(data):\n img = _prepare_img(datum['file'])\n dset[i] = img\n \n f.close()\n print \"Wrote %d images to %s\" % (len(data) ,db + '.h5')\n\ndef write_to_db(data, db, piece_size=250000):\n f = h5py.File(db + '.h5', \"w\")\n \n for i, split in enumerate(['train', 'val', 'test']):\n split_data = [datum for datum in data if datum['split'] == split]\n l = len(split_data)\n pieces = int(np.ceil(float(l) / piece_size))\n for p in range(pieces):\n s = min(piece_size, l - p * piece_size)\n \n print \"creating\", split + \"_labels_%d out of %d\" % (p + 1, pieces)\n lset = f.create_dataset(split + \"_labels_%d\" % (p+1), (s,), dtype='uint32')\n \n print \"creating\", split + \"_images_%d out of %d\" % (p + 1, pieces)\n dset = f.create_dataset(split + \"_images_%d\" % (p+1), (s,1,60,160), dtype='uint8') # space for resized images\n \n j = 0 \n for datum in split_data[p * piece_size: (p + 1) * piece_size]:\n img = _prepare_img(datum['file'])\n dset[j] = img\n lset[j] = datum['label']\n j += 1\n \n f.close()\n \n print \"Wrote a total of %d images to %s\" % (len(data) ,db + '.h5')\n\n\ndef write_to_embedding_db(data, word_vectors, db, piece_size=250000):\n f = h5py.File(db + '.h5', \"w\")\n \n for i, split in enumerate(['train', 'val', 'test']):\n split_data = [datum for datum in data if datum['split'] == split]\n l = len(split_data)\n pieces = int(np.ceil(float(l) / piece_size))\n for p in range(pieces):\n s = min(piece_size, l - p * piece_size)\n \n print \"creating\", split + \"_labels_%d out of %d\" % (p + 1, pieces)\n lset = f.create_dataset(split + \"_labels_%d\" % (p+1), (s,), dtype='uint32')\n \n print \"creating\", split + \"_embeddings_%d out of %d\" % (p + 1, pieces)\n eset = f.create_dataset(split + \"_embeddings_%d\" % (p+1), (s, word_vectors.items()[0][1].shape[0]), \n dtype='float32')\n j = 0 \n for datum in split_data[p * piece_size: (p + 1) * piece_size]:\n eset[j] = word_vectors[datum['text']]\n lset[j] = datum['label']\n j += 1\n \n print \"Wrote %d %s embeddings to %s\" % (j, split ,db + '.h5')\n print \"Wrote a total of %d embeddings to %s\" % (len(data) ,db + '.h5')\n f.close()\n \n###############################################################################\n# data loading\n############################################################################### \n\ndef load_washington(fold=1, root=\"\"):\n \"\"\"\n Loads the washington dataset\n \n fold: which fold of the four washington dataset folds to load\n root: path to directory where data is stored and where some caching is done\n \"\"\"\n output_json = 'washington_fold_%d.json' % fold\n output_json = os.path.join(root, output_json)\n\n if not os.path.exists(output_json):\n files = sorted(glob.glob(os.path.join(root, 'gw_20p_wannot/*.tif')))\n\n #Directory to store segmented washington\n word_dir = os.path.join(root, 'words/')\n if not os.path.exists(word_dir):\n os.makedirs(word_dir)\n \n img_index = 0\n word_files = []\n for f in files:\n p, fi = os.path.split(f)\n bf = os.path.join(p, fi[:-4] + '_boxes.txt')\n\n #Segment washington and save to word_dir\n img = imread(f)\n h, w = img.shape\n with open(bf) as ff:\n boxes = ff.readlines()\n \n for b in boxes[1:]: #First line is not a box annotation\n b = [float(b) for b in b.split()]\n x1 = int(np.round(b[0] * (w-1) + 1))\n x2 = int(np.round(b[1] * (w-1) + 1))\n y1 = int(np.round(b[2] * (h-1) + 1))\n y2 = int(np.round(b[3] * (h-1) + 1))\n word = img[y1:y2, x1:x2]\n \n word_file = os.path.join(word_dir, 'word_%d.png' % img_index)\n word_files.append(word_file)\n \n imsave(word_file, word)\n img_index += 1\n\n #Load annotations \n with open(os.path.join(root, 'gw_20p_wannot/annotations.txt')) as ff: #Use our own, correct annotations\n lines = ff.readlines()\n \n # Normalize texts to [a-z0-9]\n alphabet = string.ascii_lowercase + string.digits\n texts = [l[:-1] for l in lines] \n ntexts = [replace_tokens(text.lower(), [t for t in text if t not in alphabet]) for text in texts]\n \n #Load folds supplied by almazan et al\n dic = sp.io.loadmat(os.path.join(root, \"GW_words_indexes_sets_fold%d.mat\" % fold))\n splits = {}\n splits['train'] = np.squeeze(dic['idxTrain'])\n splits['val'] = np.squeeze(dic['idxValidation'])\n splits['test'] = np.squeeze(dic['idxTest'])\n \n data = []\n for i, (f, text) in enumerate(zip(word_files, ntexts)):\n datum = {}\n datum['file'] = f\n datum['text'] = text\n datum['split'] = [k for k, v in splits.iteritems() if v[i] == 1][0]\n if datum['split'] == 'val': # Use all available data to train\n datum['split'] = 'train'\n data.append(datum)\n \n with open(output_json, 'w') as f:\n json.dump(data, f)\n \n else: #otherwise load the json\n with open(output_json) as f:\n data = json.load(f)\n \n return data \n\n"
},
{
"alpha_fraction": 0.6309523582458496,
"alphanum_fraction": 0.6489361524581909,
"avg_line_length": 26.234481811523438,
"blob_id": "ff43edd65f729babf5806dbed73c7117e9d58d33",
"content_id": "4e6c2ebedb6aac6da67ead4f622781baae93e9a8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 3948,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 145,
"path": "/misc/models.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'nn'\nrequire 'cunn'\nrequire 'cutorch'\nrequire 'cudnn'\nlocal createModel = require 'misc.presnet'\n\nlocal models = {}\n\nfunction models.load_presnet(descriptor_size)\n local opt = {}\n opt.dataset = 'imagenet'\n opt.depth = 34\n opt.descriptor_size = descriptor_size\n local model = createModel(opt)\n return model\nend\n\n\nfunction models.load_embedding_net(cnn, opt)\n local net = nn.Sequential()\n\n net:add(nn.Linear(opt.descriptor_size, opt.fc_size))\n net.modules[#net.modules].weight:normal(0, 0.01)\n net.modules[#net.modules].bias:fill(0.1)\n net:add(nn.BatchNormalization(opt.fc_size))\n net:add(nn.Tanh(true))\n\n net:add(nn.Linear(opt.fc_size, opt.fc_size))\n net.modules[#net.modules].weight:normal(0, 0.01)\n net.modules[#net.modules].bias:fill(0.1)\n net:add(nn.BatchNormalization(opt.fc_size))\n net:add(nn.Tanh(true))\n\n net:add(nn.Linear(opt.fc_size, opt.fc_size))\n net.modules[#net.modules].weight:normal(0, 0.01)\n net.modules[#net.modules].bias:fill(0.1)\n net:add(nn.BatchNormalization(opt.fc_size))\n net:add(nn.Tanh(true))\n\n net:add(nn.Linear(opt.fc_size, opt.embedding_size))\n net.modules[#net.modules].weight:normal(0, 0.01)\n net.modules[#net.modules].bias:fill(0.1)\n net:add(nn.Normalize(2))\n local mlp = nn.Sequential()\n mlp:add(cnn)\n mlp:add(net)\n local prl = nn.ParallelTable()\n prl:add(mlp)\n prl:add(nn.Identity())\n\n return prl\nend\n\nfunction models.load_triplet_net(cnn, opt)\n -- clone the other two networks in the triplet\n cnn2 = cnn:clone('weight', 'bias','gradWeight','gradBias', 'running_mean', 'running_var') -- for batch norm\n cnn3 = cnn:clone('weight', 'bias','gradWeight','gradBias', 'running_mean', 'running_var') -- for batch norm\n\n -- add them to a parallel table\n prl = nn.ParallelTable()\n prl:add(cnn)\n prl:add(cnn2)\n prl:add(cnn3)\n prl:cuda()\n\n mlp= nn.Sequential()\n mlp:add(prl)\n\n -- get feature distances \n cc = nn.ConcatTable()\n\n -- feats 1 with 2 \n cnn_left = nn.Sequential()\n cnnpos_dist = nn.ConcatTable()\n cnnpos_dist:add(nn.SelectTable(1))\n cnnpos_dist:add(nn.SelectTable(2))\n cnn_left:add(cnnpos_dist)\n if opt.use_metric_net then\n cnn_left:add(metric1) \n else\n cnn_left:add(nn.PairwiseDistance(2))\n end\n cnn_left:add(nn.View(opt.batch_size,1))\n cnn_left:cuda()\n cc:add(cnn_left)\n\n -- feats 2 with 3 \n cnn_left2 = nn.Sequential()\n cnnpos_dist2 = nn.ConcatTable()\n cnnpos_dist2:add(nn.SelectTable(2))\n cnnpos_dist2:add(nn.SelectTable(3))\n cnn_left2:add(cnnpos_dist2)\n if opt.use_metric_net then\n cnn_left2:add(metric1) \n else\n cnn_left2:add(nn.PairwiseDistance(2))\n end\n cnn_left2:add(nn.View(opt.batch_size,1))\n cnn_left2:cuda()\n cc:add(cnn_left2)\n\n -- feats 1 with 3 \n cnn_right = nn.Sequential()\n cnnneg_dist = nn.ConcatTable()\n cnnneg_dist:add(nn.SelectTable(1))\n cnnneg_dist:add(nn.SelectTable(3))\n cnn_right:add(cnnneg_dist)\n if opt.use_metric_net then\n cnn_right:add(metric1) \n else\n cnn_right:add(nn.PairwiseDistance(2))\n end\n cnn_right:add(nn.View(opt.batch_size,1))\n cnn_right:cuda()\n cc:add(cnn_right)\n cc:cuda()\n\n mlp:add(cc)\n\n last_layer = nn.ConcatTable()\n\n -- select min negative distance inside the triplet\n mined_neg = nn.Sequential()\n mining_layer = nn.ConcatTable()\n mining_layer:add(nn.SelectTable(1))\n mining_layer:add(nn.SelectTable(2))\n mined_neg:add(mining_layer)\n mined_neg:add(nn.JoinTable(2))\n mined_neg:add(nn.Min(2))\n mined_neg:add(nn.View(opt.batch_size,1))\n last_layer:add(mined_neg)\n -- add positive distance\n pos_layer = nn.Sequential()\n pos_layer:add(nn.SelectTable(3))\n pos_layer:add(nn.View(opt.batch_size,1))\n last_layer:add(pos_layer)\n\n mlp:add(last_layer)\n\n mlp:add(nn.JoinTable(2))\n mlp:cuda()\n return mlp\nend\n\nreturn models"
},
{
"alpha_fraction": 0.6073147058486938,
"alphanum_fraction": 0.6289701461791992,
"avg_line_length": 27.452054977416992,
"blob_id": "5eade19c13cd4bc49235d7d1ce16779ecf42abc1",
"content_id": "3649428d40a75a72372098b03f5ddefa05df0844",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4156,
"license_type": "permissive",
"max_line_length": 128,
"num_lines": 146,
"path": "/misc/utils.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "local cjson = require 'cjson'\nlocal npy4th = require 'npy4th'\n\nutils = {}\n\nfunction utils.file_exists(name)\n local f=io.open(name,\"r\")\n if f~=nil then io.close(f) return true else return false end\nend\n\nfunction utils.read_json(path)\n local file = io.open(path, 'r')\n local text = file:read()\n file:close()\n local info = cjson.decode(text)\n return info\nend\n\nfunction utils.write_json(path, j)\n -- API reference http://www.kyne.com.au/~mark/software/lua-cjson-manual.html#encode\n cjson.encode_sparse_array(true, 2, 10)\n local text = cjson.encode(j)\n local file = io.open(path, 'w')\n file:write(text)\n file:close()\nend\n\n-- get the stats\nfunction utils.get_stats(images)\n local tmp = images:type('torch.FloatTensor')\n local mi = tmp:mean()\n local sigma = tmp:std()\n local stats = {}\n stats.mi = mi\n stats.sigma = sigma\n return stats\nend\n\n-- following functions taken from Elad Hoffer's\n-- TripletNet https://github.com/eladhoffer\nfunction utils.ArrangeByLabel(data)\n local numClasses = data.labels:max()\n local Ordered = {}\n for i=1,data.labels:size(1) do\n -- print(i)\n if Ordered[data.labels[i]] == nil then\n Ordered[data.labels[i]] = {}\n end\n table.insert(Ordered[data.labels[i]], i)\n end\n return Ordered\nend\n\n\nfunction utils.generate_pairs(Ordered, num_pairs)\n local pairs = torch.IntTensor(num_pairs, 3)\n local used = {}\n local nClasses = #Ordered\n -- for key,value in pairs(Ordered) do nClasses = nClasses + 1 end --Have no idea why this is needed and #Ordered doesn't work\n for i=1, num_pairs do\n local c1 = math.random(nClasses)\n while Ordered[c1] == nil or #Ordered[c1] < 2 or used[c1] ~= nil do\n c1 = math.random(nClasses)\n end\n used[c1] = c1\n\n local c2 = math.random(nClasses)\n while c2 == c1 or Ordered[c2] == nil or #Ordered[c2] < 1 do\n c2 = math.random(nClasses)\n end\n\n local n1 = math.random(#Ordered[c1])\n local n2 = math.random(#Ordered[c2])\n\n -- Should pair be from same class or not 2:1 ratio\n lbl = math.random(0,2)\n if ((lbl==0) or (lbl==1)) then\n pairs[i][1] = Ordered[c1][n1]\n pairs[i][2] = Ordered[c2][n2]\n pairs[i][3] = -1\n else\n pairs[i][1] = Ordered[c1][n1]\n pairs[i][2] = Ordered[c1][n1]\n pairs[i][3] = 1\n end\n end\n\n return pairs\nend\n\nfunction utils.generate_triplets(Ordered, num_triplets)\n local list = torch.IntTensor(num_triplets, 3)\n local used = {}\n\n local nClasses = #Ordered\n -- for key,value in pairs(Ordered) do nClasses = nClasses + 1 end --Have no idea why this is needed and #Ordered doesn't work\n for i=1, num_triplets do\n local c1 = math.random(nClasses)\n while Ordered[c1] == nil or #Ordered[c1] < 2 or used[c1] ~= nil do\n c1 = math.random(nClasses)\n end\n used[c1] = c1\n\n local c2 = math.random(nClasses)\n while c2 == c1 or Ordered[c2] == nil or #Ordered[c2] < 1 do\n c2 = math.random(nClasses)\n end\n local n1 = math.random(#Ordered[c1])\n local n2 = math.random(#Ordered[c2])\n local n3 = math.random(#Ordered[c1])\n\n while n3 == n1 do\n n3 = math.random(#Ordered[c1])\n end\n\n list[i][1] = Ordered[c1][n1]\n list[i][2] = Ordered[c2][n2]\n list[i][3] = Ordered[c1][n3]\n end\n\n return list\nend\n\nfunction utils.getopt(opt, key, default_value)\n if default_value == nil and (opt == nil or opt[key] == nil) then\n error('error: required key ' .. key .. ' was not provided in an opt.')\n end\n if opt == nil then return default_value end\n local v = opt[key]\n if v == nil then v = default_value end\n return v\nend\n\n--Horrible solution, but can't be bothered to re-implement mAP evaluation in torch.\nfunction utils.map_eval(dataset, id, descrs, upper_bound, fold)\n upper_bound = upper_bound or -1\n npy4th.savenpy('tmp/' .. dataset .. '_' .. id..'_descriptors.npy', descrs)\n if dataset == 'washington' then\n os.execute('ipython misc/map_eval.py ' .. fold .. ' ' .. dataset .. '_' .. id .. ' ' .. upper_bound)\n end\n\n local result_struct = utils.read_json('tmp/' .. dataset .. '_' .. id .. '_ws_results.json') \n return result_struct\nend\n\nreturn utils\n\n\n"
},
{
"alpha_fraction": 0.6224289536476135,
"alphanum_fraction": 0.6334883570671082,
"avg_line_length": 35.787071228027344,
"blob_id": "2c7ead0da8215ade621b7d042462db7732ef2b41",
"content_id": "58272f150b15285c77df27003a5586386b76ccec",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 9675,
"license_type": "permissive",
"max_line_length": 156,
"num_lines": 263,
"path": "/train_we.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'torch'\nrequire 'nn'\nrequire 'math'\n-- local imports\nutils = require 'misc.utils'\nrequire 'misc.DataLoader'\nrequire 'misc.DataLoader_we'\n-- require 'misc.DistanceRatioCriterion'\nmodels = require 'misc.models'\nrequire 'optim'\n\n-------------------------------------------------------------------------------\n-- Input arguments and options\n-------------------------------------------------------------------------------\ncmd = torch.CmdLine()\ncmd:text()\ncmd:text('Train an Word Spotting model')\ncmd:text()\ncmd:text('Options')\n\n-- Data input settings\ncmd:option('-dataset','','path to the h5file containing the preprocessed images')\ncmd:option('-root_dir','data/washington/','path to data root directory')\ncmd:option('-weights', 'checkpoints/washington_triplet_fold_1_iter_50000.t7', 'path to a model checkpoint to initialize model weights from. Empty = don\\'t')\n\ncmd:option('-fold', 1,'Which fold of washington data to run')\ncmd:option('-val_upper_bound',1000,'number of examples to use for MAP evaluation')\ncmd:option('-val_dataset', 'washington','number of examples to use for MAP evaluation')\n\n-- Optimization:\ncmd:option('-max_iters', 30000, 'max number of iterations to run for (-1 = run forever)')\ncmd:option('-batch_size',128,'what is the batch size in number of images per batch?')\ncmd:option('-learning_rate',1e-2,'learning rate')\ncmd:option('-learning_rate_decay_every', 10000, 'every how many iterations thereafter to drop LR by learning_rate_decay_factor')\ncmd:option('-learning_rate_decay_factor', 0.1, 'how much to decay the learning rate with')\ncmd:option('-cosine_margin',0.1,'the margin for the cosine embedding loss')\n\n-- Evaluation/Checkpointing\ncmd:option('-save_checkpoint_every', 10000, 'how often to save a model checkpoint?')\ncmd:option('-checkpoint_path', 'checkpoints', 'folder to save checkpoints into (empty = this folder)')\ncmd:option('-losses_log_every', 100, 'How often do we snapshot losses, for inclusion in the progress dump? (0 = disable)')\ncmd:option('-print_train_loss_every', 500, 'How often do we print losses (0 = disable)')\n\n-- misc\ncmd:option('-backend', 'cudnn', 'nn|cudnn')\ncmd:option('-id', '', 'an id identifying this run/job. used in cross-val and appended when writing progress files')\ncmd:option('-seed', 123, 'random number generator seed to use')\ncmd:option('-gpuid', 0, 'which gpu to use. -1 = use CPU')\n\ncmd:text()\n\n-------------------------------------------------------------------------------\n-- Basic Torch initializations\n-------------------------------------------------------------------------------\nopt = cmd:parse(arg)\ntorch.manualSeed(opt.seed)\ntorch.setdefaulttensortype('torch.FloatTensor') -- for CPU\n\nif opt.gpuid >= 0 then\n require 'cutorch'\n require 'cunn'\n if opt.backend == 'cudnn' then \n require 'cudnn' \n cudnn.benchmark = true\n end\n cutorch.manualSeed(opt.seed)\n math.randomseed(opt.seed)\n cutorch.setDevice(opt.gpuid + 1) -- note +1 because lua is 1-indexed\nend\n\n-------------------------------------------------------------------------------\n-- Create the Data Loader instance\n-------------------------------------------------------------------------------\n\nprint(\"loading training database\")\nopt.mode = 'train'\nloader = DataLoaderWE(opt)\n\n-- load validation dataloader\nprint(\"Loading validation database\")\nval_opt = {}\nval_opt.root_dir = opt.root_dir\nval_opt.dataset = opt.val_dataset\nval_opt.mode = 'full'\nval_opt.upper_bound = opt.val_upper_bound\nval_loader = DataLoader(val_opt)\n\n-------------------------------------------------------------------------------\n-- Initialize the networks\n-------------------------------------------------------------------------------\nprotos = {}\ncp = {}\nopt.descriptor_size = 512\nopt.fc_size = 4096\nopt.embedding_size = loader:get_embedding_size()\nif string.len(opt.weights) > 0 then\n -- Load checkpoint\n print('initializing weights from ' .. opt.weights)\n lcp = torch.load(opt.weights)\n protos = lcp.protos\n \n protos.cnn = protos.mlp.modules[1].modules[1]\n protos.mlp = models.load_embedding_net(protos.cnn, opt)\n protos.mlp:cuda()\nelse\n -- create protos from scratch, intialize model\n protos.cnn = models.load_presnet(opt.descriptor_size)\n protos.mlp = models.load_embedding_net(protos.cnn, opt)\nend\n\n-- Load cosine embedding criterion\nprotos.crit = nn.CosineEmbeddingCriterion(opt.cosine_margin)\n\n-- ship everything to GPU, maybe\nif opt.gpuid >= 0 then\n for k,v in pairs(protos) do v:cuda() end\nend\n\n-- flatten and prepare all model parameters to a single vector. \nlocal params, grad_params = protos.mlp:getParameters()\nprint('total number of parameters in model: ', params:nElement())\nassert(params:nElement() == grad_params:nElement())\n\ncollectgarbage() -- \"yeah, sure why not\"\n-------------------------------------------------------------------------------\n-- Validation evaluation\n-------------------------------------------------------------------------------\nlocal function map_eval()\n protos.mlp:evaluate()\n local data = val_loader:get_data()\n local N = data.images:size(1)\n local descrs = torch.CudaTensor(N, loader:get_embedding_size())\n local descrs_split = descrs:split(opt.batch_size)\n for i,v in ipairs(data.images:split(opt.batch_size)) do\n descrs_split[i]:copy(protos.mlp.modules[1]:forward(v:cuda()))\n end\n\n local result = utils.map_eval(val_opt.dataset, opt.id, descrs, val_opt.upper_bound, opt.fold)\n return result\nend\n\n-------------------------------------------------------------------------------\n-- Main loop\n-------------------------------------------------------------------------------\n\noptimState = {\n learningRate = opt.learning_rate,\n weightDecay = 1e-4,\n momentum = 0.9,\n dampening = 0,\n nesterov = 1,\n}\n\n-- Define some variables to keep track of things\nlocal iter = opt.iter or 0\nlocal inputs\nlocal embeddings\nlocal targets\nlocal loss\nlocal loss_history = cp.loss_history or {}\nlocal map_qbe_history = cp.map_qbe_history or {}\nlocal map_qbs_history = cp.map_qbs_history or {}\nlocal epoch_count = 0\nlocal running_average_loss = 0\nlocal best_score\nlocal learning_rate = opt.learning_rate\nlocal finetune_cnn = 1\n\nmap_result = map_eval()\nprint('validation MaP qbe: ' .. map_result.MaP_qbe .. ', qbs: ' .. map_result.MaP_qbs)\nmap_qbe_history[iter] = map_result.MaP_qbe\nmap_qbs_history[iter] = map_result.MaP_qbs\n\nprint('starting main loop')\nwhile true do\n\n local feval = function(f)\n if f ~= params then params:copy(f) end\n grad_params:zero()\n\n --Load data\n protos.mlp:training()\n inputs, embeddings, targets = unpack(loader:getBatch{batch_size = opt.batch_size})\n\n local cnn_outputs = protos.mlp.modules[1].modules[1]:forward(inputs)\n local outputs = protos.mlp.modules[1].modules[2]:forward(cnn_outputs)\n loss = protos.crit:forward({outputs, embeddings}, targets) \n local df_do, dummy = unpack(protos.crit:backward({outputs, embeddings}, targets))\n local dcnn_outputs = protos.mlp.modules[1].modules[2]:backward(cnn_outputs, df_do) \n if finetune_cnn > 0 and iter > 500 then \n dx = protos.mlp.modules[1].modules[1]:backward(inputs, dcnn_outputs)\n end\n return loss, grad_params\n end\n\n optimState.learningRate = learning_rate\n optim.sgd(feval, params, optimState)\n\n -- Record loss in various ways\n running_average_loss = running_average_loss + loss\n \n -- Optional printing and logging of losses\n if iter % opt.losses_log_every == 0 then loss_history[iter] = loss end\n\n if opt.print_train_loss_every > 0 and iter % opt.print_train_loss_every == 0 then\n running_average_loss = running_average_loss / opt.print_train_loss_every\n print(string.format('iter %d: %f, lr=%f', iter, running_average_loss, learning_rate ))\n running_average_loss = 0\n end\n\n -- save checkpoint once in a while (or on final iteration)\n if (iter > 0 and iter % opt.save_checkpoint_every == 0 or iter == opt.max_iters) then\n\n -- do MaP eval\n local map_result = map_eval()\n\n print('validation MaP qbe: ' .. map_result.MaP_qbe .. ', qbs: ' .. map_result.MaP_qbs)\n map_qbe_history[iter] = map_result.MaP_qbe\n map_qbs_history[iter] = map_result.MaP_qbs\n\n local checkpoint_path = path.join(opt.checkpoint_path, opt.id .. '_iter_' .. iter)\n\n -- write a (thin) json report\n local checkpoint = {}\n checkpoint.opt = opt\n checkpoint.iter = iter\n checkpoint.loss_history = loss_history\n checkpoint.map_qbe_history = map_qbe_history\n checkpoint.map_qbs_history = map_qbs_history\n checkpoint.learning_rate = learning_rate\n\n utils.write_json(checkpoint_path .. '.json', checkpoint)\n print('wrote json checkpoint to ' .. checkpoint_path .. '.json')\n\n -- write the full model checkpoint as well if we did better than ever\n local current_score = (map_result.MaP_qbe + map_result.MaP_qbs) / 2\n -- if best_score == nil or current_score > best_score then\n best_score = current_score\n if iter > 0 then -- dont save on very first iteration\n\n protos.mlp:clearState()\n local save_protos = {}\n save_protos.mlp = protos.mlp\n checkpoint.protos = save_protos\n checkpoint.model_type = opt.model_type\n checkpoint.iter = iter\n torch.save(checkpoint_path .. '.t7', checkpoint)\n print('wrote checkpoint to ' .. checkpoint_path .. '.t7')\n\n end\n -- end\n end\n\n if iter % opt.learning_rate_decay_every == 0 and iter > 0 then\n learning_rate = learning_rate * opt.learning_rate_decay_factor -- set the decayed rate\n end\n \n -- stopping criterions\n iter = iter + 1\n if iter % 10 == 0 then collectgarbage() end -- good idea to do this once in a while, i think\n if opt.max_iters > 0 and iter > opt.max_iters then break end -- stopping criterion\n\nend\n"
},
{
"alpha_fraction": 0.5954198241233826,
"alphanum_fraction": 0.6076335906982422,
"avg_line_length": 32.67241287231445,
"blob_id": "06aeffb2b7a7aab5e79c9a4f0c012378567fa96e",
"content_id": "0c391dfbceb5fa6546693e7bc39cfefbf348bba2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1965,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 58,
"path": "/misc/util.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 28 11:35:01 2016\n\n@author: tomas\n\"\"\"\nimport numpy as np\nfrom scipy.spatial import distance as di\n\ndef average_precision(ils, t):\n '''\n Computes the average precision\n \n Thanks for a fast mAP implementation!\n https://github.com/ssudholt/phocnet/blob/master/src/phocnet/evaluation/retrieval.py\n '''\n \n ret_vec_relevance = ils == t\n ret_vec_cumsum = np.cumsum(ret_vec_relevance, dtype=float)\n ret_vec_range = np.arange(1, ret_vec_relevance.size + 1)\n ret_vec_precision = ret_vec_cumsum / ret_vec_range\n \n n_relevance = ret_vec_relevance.sum()\n\n if n_relevance > 0:\n ret_vec_ap = (ret_vec_precision * ret_vec_relevance).sum() / n_relevance\n else:\n ret_vec_ap = 0.0\n \n return ret_vec_ap\n \ndef MAP(queries, qtargets, db, itargets, metric='cosine'):\n APs = []\n for q, query in enumerate(queries):\n t = qtargets[q] #Get the label for the query\n count = np.sum(itargets == t) #Count the number of relevant retrievals in the database \n if count == 1:\n continue\n\n dists = np.squeeze(di.cdist(query.reshape(1, query.shape[0]), db, metric=metric)) \n I = np.argsort(dists)\n I = I[1:] #Don't count the query, distance is always zero to query\n ils = itargets[I] #Sort results after distance to query image\n ap = average_precision(ils, t)\n APs.append(ap) \n\n return np.mean(APs)\n \ndef MAP_qbs(queries, qtargets, db, itargets, metric='cosine'):\n APs = []\n for q, query in enumerate(queries):\n t = qtargets[q] #Get the label for the query\n dists = np.squeeze(di.cdist(query.reshape(1, query.shape[0]), db, metric=metric)) \n I = np.argsort(dists)\n ils = itargets[I] #Sort results after distance to query image\n ap = average_precision(ils, t)\n APs.append(ap) \n return np.mean(APs)#, qs \n "
},
{
"alpha_fraction": 0.48553192615509033,
"alphanum_fraction": 0.49659574031829834,
"avg_line_length": 31.19178009033203,
"blob_id": "78295897465404dbf0b896229ce320f99cb01360",
"content_id": "6170e8d34f746608a8db174f175ac878360d7f2a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2350,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 73,
"path": "/eval_test.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 5 11:10:44 2016\n\n@author: tomas\n\"\"\"\nimport json\nimport numpy as np\n\nimport misc.util as util\nembeddings = ['triplet', 'semantic', 'ngram', 'phoc', 'dct3']\n\nwith open(\"data/washington/washington_preprocessed.json\") as f:\n jdata = json.load(f)\n\nfolds = 1\nfor embedding in embeddings:\n qbe, qbs = [], []\n for fold in range(1, folds + 1):\n descr = np.load(\"descriptors/washington_%s_fold_%d_descriptors.npy\" % (embedding, fold))\n \n db = []\n itar = []\n texts = []\n for datum, desc in zip(jdata['data'], descr):\n if datum['split'] == 'test':\n db.append(desc)\n itar.append(datum['label'])\n texts.append(datum['text'])\n \n itar = np.array(itar)\n db = np.array(db)\n \n #Load word vectors\n if embedding == 'phoc':\n we = np.load('embeddings/washington_phoc_embeddings.npy')\n elif embedding == 'dct3':\n we = np.load(\"embeddings/washington_dct3_embeddings.npy\")\n elif embedding == 'semantic':\n we = np.load(\"embeddings/washington_semantic_embeddings.npy\")\n elif embedding == 'ngram':\n we = np.load(\"embeddings/washington_ngram_embeddings.npy\")\n else:\n \t we = None\n\n if we != None: \n queries = []\n qtargets = []\n qtrans = [] \n wtoe = {}\n for i, datum in enumerate(jdata['data']):\n if datum['split'] == 'test':\n if datum['text'] not in wtoe:\n wtoe[datum['text']] = we[i]\n queries.append(we[i])\n qtrans.append(datum['text'])\n qtargets.append(datum['label'])\n \n queries = np.array(queries) \n qtargets = np.array(qtargets) \n assert(len(qtargets) == np.unique(qtargets).shape[0])\n \n if embedding == 'triplet':\n mAP_qbs = -1\n else:\n mAP_qbs = util.MAP_qbs(queries, qtargets, db, itar)\n \n mAP_qbe = util.MAP(db, itar, db, itar)\n\n qbe.append(mAP_qbe)\n qbs.append(mAP_qbs)\n \n print embedding, \"Washington QbE \", np.mean(qbe) * 100, \", QbS:\", np.mean(qbs) * 100\n"
},
{
"alpha_fraction": 0.6258246898651123,
"alphanum_fraction": 0.6465598344802856,
"avg_line_length": 23.55813980102539,
"blob_id": "e853df74a661fb1e1179a886a9fe706eb2964aa9",
"content_id": "1a864be76369468e7fc23f9240a2dcecfd208001",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1061,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 43,
"path": "/misc/extract_dct_embedding.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 20 19:41:28 2016\n\n@author: tomas\n\"\"\"\n\nimport string\nimport numpy as np\nimport scipy.fftpack as sf\n\nimport db_utils as dbu\n\nalphabet = string.ascii_lowercase + string.digits\ndct_resolution = 3 #Resolution of dct to keep\n\ndef plain_dct(s, resolution, alphabet):\n im = np.zeros([len(alphabet),len(s)], 'single')\n F = np.zeros([len(alphabet),len(s)], 'single')\n for jj in range(0,len(s)):\n c = s[jj]\n im[string.find(alphabet, c), jj] = 1.0\n\n for ii in range(0,len(alphabet)):\n F[ii,:] = sf.dct(im[ii,:])\n\n A = F[:,0:resolution]\n B = np.zeros([len(alphabet),max(0,resolution-len(s))])\n\n return np.hstack((A,B))\n\nfold = 1\ndata = dbu.load_washington(fold, \"../data/washington\")\n\nembeddings = []\nfor datum in data:\n embedding = plain_dct(datum['text'], dct_resolution, alphabet)\n embedding = embedding.reshape(-1)\n embeddings.append(embedding)\n\nembeddings = np.array(embeddings)\n\nnp.save('../embeddings/washington_dct%d_embeddings.npy' % dct_resolution, embeddings)\n \n"
},
{
"alpha_fraction": 0.5203040838241577,
"alphanum_fraction": 0.5407009124755859,
"avg_line_length": 35.43918991088867,
"blob_id": "f9f7602ad8e5aa00af321d9fa13b83bd5a9f93f5",
"content_id": "d0989313431bdd072f290c7eb77a28f4eca218fe",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5393,
"license_type": "permissive",
"max_line_length": 123,
"num_lines": 148,
"path": "/misc/data_augmentation.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 15 14:57:40 2016\n\n@author: tomas\n\"\"\"\nimport os\nimport copy\nimport json\n\nimport numpy as np\nfrom skimage.io import imsave\nfrom skimage.io import imread\nfrom skimage.util import img_as_ubyte\nimport skimage.morphology as mor\nfrom skimage.filters import threshold_otsu\nfrom skimage.color import rgb2gray\nimport skimage.transform as tf\n\ndef close_crop(img, tparams):\n t_img = img < threshold_otsu(img)\n nz = t_img.nonzero()\n pad = np.random.randint(low = tparams['hpad'][0], high = tparams['hpad'][1], size=2) \n vpad = np.random.randint(low = tparams['vpad'][0], high = tparams['vpad'][1], size=2) \n b = [max(nz[1].min() - pad[0], 0), max(nz[0].min() - vpad[0], 0), \n min(nz[1].max() + pad[1], img.shape[1]), min(nz[0].max() + vpad[1], img.shape[0])]\n return img[b[1]:b[3], b[0]:b[2]]\n \ndef affine(img, tparams):\n phi = (np.random.uniform(tparams['shear'][0], tparams['shear'][1])/180) * np.pi\n theta = (np.random.uniform(tparams['rotate'][0], tparams['rotate'][1])/180) * np.pi\n t = tf.AffineTransform(shear=phi, rotation=theta, translation=(-25, -50))\n tmp = tf.warp(img, t, order=tparams['order'], mode='edge', output_shape=(img.shape[0] + 100, img.shape[1] + 100))\n return tmp\n\n \ndef morph(img, tparams):\n ops = [mor.grey.erosion, mor.grey.dilation]\n t = ops[np.random.randint(2)] \n if t == 0: \n selem = mor.square(np.random.randint(1, tparams['selem_size'][0]))\n else:\n selem = mor.square(np.random.randint(1, tparams['selem_size'][1]))\n return t(img, selem) \n \ndef augment(datum, tparams):\n img = imread(datum['file'])\n if img.ndim == 3:\n img = img_as_ubyte(rgb2gray(img))\n\n tmp = np.ones((img.shape[0] + 8, img.shape[1] + 8), dtype = img.dtype) * 250\n tmp[4:-4, 4:-4] = img\n img = tmp\n img = affine(img, tparams)\n img = close_crop(img, tparams) \n img = morph(img, tparams)\n img = img_as_ubyte(img)\n return img\n\n\ndef augment_data(data, out_directory, tparams=None, M=500000):\n \"\"\"\n Augments a dataset using basic affine and morphological transformations\n data: Data to augment\n out_directory: Directory to save the augmented training examples\n tparams: Dictionary of parameters for the augmentation transformations\n M: size of augmented dataset\n \"\"\"\n output_json = os.path.join(out_directory, 'data.json')\n if os.path.exists(output_json): #if augmentation already done, load\n with open(output_json) as f:\n new_data = json.load(f)\n \n else: #else, augment\n if tparams == None:\n tparams = {}\n tparams['shear'] = (-5, 30)\n tparams['rotate'] = (-5, 5)\n tparams['hpad'] = (3, 15)\n tparams['vpad'] = (3, 15)\n tparams['order'] = 1 #bilinear\n tparams['selem_size'] = (3, 4) #max size for square selem for erosion, dilation\n \n if not os.path.exists(out_directory):\n os.makedirs(out_directory)\n \n train_data = []\n texts = []\n for datum in data:\n if datum['split'] == 'train' or datum['split'] == 'val':\n texts.append(datum['text'])\n train_data.append(copy.deepcopy(datum))\n \n vocab = sorted(list(set(texts)))\n wtoi = {w:i for i,w in enumerate(vocab)} # inverse table\n data_by_class = [[] for v in vocab]\n for datum, text in zip(train_data, texts):\n data_by_class[wtoi[text]].append(datum)\n \n counts = [len(l) for l in data_by_class]\n mc = max(counts)\n \n print \"starting stage 1\"\n new_data = []\n k = 0\n #Stage 1: get an equal amount of each class\n for i in range(len(vocab)):\n n = mc - counts[i]\n if n > 0:\n for j in range(n):\n class_data = data_by_class[i]\n ind = np.random.randint(len(class_data))\n datum = copy.deepcopy(class_data[ind])\n img = augment(datum, tparams)\n f = os.path.join(out_directory, datum['file'].split('/')[-1][:-4] + '_%d_%s.png' % (k, datum['split']))\n imsave(f, img)\n datum['file'] = f\n new_data.append(datum)\n k += 1\n \n print \"stage 1 done\"\n \n #Append existing data to augmented data to get an equal distribution for each word\n new_data += train_data\n \n #Stage 2: Continue sampling new training data until we reach the desired amount\n N = len(new_data)\n lv = len(vocab)\n \n left = M - N\n if left > 0:\n for j in range(left):\n i = j % lv\n class_data = data_by_class[i]\n ind = np.random.randint(len(class_data))\n datum = copy.deepcopy(class_data[ind])\n img = augment(datum, tparams)\n f = os.path.join(out_directory, datum['file'].split('/')[-1][:-4] + '_%d_%s.png' % (k + j, datum['split']))\n imsave(f, img)\n datum['file'] = f\n new_data.append(datum)\n \n print \"stage 2 done\"\n \n with open(output_json, 'w') as f:\n json.dump(new_data, f)\n \n return new_data\n"
},
{
"alpha_fraction": 0.51972895860672,
"alphanum_fraction": 0.5312873721122742,
"avg_line_length": 28.081396102905273,
"blob_id": "3dc704cf09c86c322d287e942ef831740c449d4d",
"content_id": "79f10bf444b754fb5fa0d18e6317dc1f235254fb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2509,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 86,
"path": "/misc/map_eval.py",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 26 08:53:26 2016\n\n@author: tomas\n\"\"\"\nimport sys\nimport json\n\nimport numpy as np\n\nfrom util import MAP, MAP_qbs\n\nif __name__ == '__main__':\n fold = int(sys.argv[1])\n tmp_file = str(sys.argv[2])\n ub = int(sys.argv[3])\n \n with open('data/washington/washington_preprocessed.json', 'r') as f:\n json_data = json.load(f)\n \n data = json_data['data']\n labels, texts, splits = [], [], []\n for datum in data:\n labels.append(datum['label'])\n texts.append(datum['text'])\n splits.append(datum['split'])\n \n X = np.load('tmp/%s_descriptors.npy' % tmp_file)\n \n if tmp_file.find('dct3') > 0:\n we = np.load('embeddings/washington_dct3_embeddings.npy')\n elif tmp_file.find('phoc') > 0:\n we = np.load('embeddings/washington_phoc_embeddings.npy')\n we = (we > 0).astype(np.float32)\n elif tmp_file.find('ngram') > 0:\n we = np.load('embeddings/washington_ngram_embeddings.npy')\n elif tmp_file.find('semantic') > 0:\n we = np.load('embeddings/washington_semantic_embeddings.npy')\n else:\n we = None\n \n #only keep train & val splits\n db = []\n itargets = []\n targets = []\n qtargets = []\n queries = []\n used = []\n if we != None:\n for i, (x, w, label, text, split) in enumerate(zip(X, we, labels, texts, splits)):\n if split == 'val' or split == 'train':\n db.append(x)\n itargets.append(label)\n targets.append(text)\n if label not in used:\n queries.append(w)\n qtargets.append(label)\n used.append(label)\n else:\n for i, (x, label, text, split) in enumerate(zip(X, labels, texts, splits)):\n if split == 'val' or split == 'train':\n db.append(x)\n itargets.append(label)\n targets.append(text)\n \n db = np.array(db)\n itargets = np.array(itargets)\n targets = np.array(targets)\n \n if ub < 1:\n ub = db.shape[0] + 1\n \n #use entire db as query\n if we != None:\n mAP_qbs = MAP_qbs(queries[:ub], qtargets, db, itargets)\n else:\n mAP_qbs = -1\n mAP_qbe = MAP(db[:ub], itargets, db, itargets)\n \n jdata = {}\n jdata['MaP_qbe'] = mAP_qbe\n jdata['MaP_qbs'] = mAP_qbs\n #store results in a json file\n with open('tmp/' + tmp_file + '_ws_results.json', 'w') as f:\n json.dump(jdata, f) \n"
},
{
"alpha_fraction": 0.6140108108520508,
"alphanum_fraction": 0.624150276184082,
"avg_line_length": 33.995967864990234,
"blob_id": "69384552c6fc0c259d6614fb035a6c04d4779465",
"content_id": "bfcbe1daca88c78de8e43fabc6ada9aec53862f1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 8679,
"license_type": "permissive",
"max_line_length": 145,
"num_lines": 248,
"path": "/train.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'torch'\nrequire 'nn'\nrequire 'math'\nrequire 'optim'\n\n-- local imports\nlocal utils = require 'misc.utils'\nrequire 'misc.DataLoader'\nrequire 'misc.DistanceRatioCriterion'\nlocal models = require 'misc.models'\n\n-------------------------------------------------------------------------------\n-- Input arguments and options\n-------------------------------------------------------------------------------\ncmd = torch.CmdLine()\ncmd:text()\ncmd:text('Train an Word Spotting model')\ncmd:text()\ncmd:text('Options')\n\n-- Data input settings\ncmd:option('-dataset','','path to the h5file containing the preprocessed dataset')\ncmd:option('-root_dir','data/washington/','path to data root directory')\ncmd:option('-weights', 'pretrained/presnet_34_cvl_iter_185000.t7', 'path to a model checkpoint to initialize model weights from. Empty = don\\'t')\n\n-- Model settings\ncmd:option('-descriptor_size', 512,'the dimensionality of the descriptors (when applicable).')\ncmd:option('-fold', 1,'Which fold of washington data to run')\ncmd:option('-val_upper_bound',1000,'number of examples to use for MAP evaluation')\ncmd:option('-val_dataset', 'washington','Dataset to evaluate on')\n\n-- Optimization:\ncmd:option('-max_iters', 50000, 'max number of iterations to run for (-1 = run forever)')\ncmd:option('-batch_size',128,'what is the batch size in number of images per batch?')\ncmd:option('-learning_rate',1e-2,'learning rate')\ncmd:option('-learning_rate_decay_every', 20000, 'every how many iterations thereafter to drop LR by learning_rate_decay_factor')\ncmd:option('-learning_rate_decay_factor', 0.1, 'how much to decay the learning rate with')\n\n-- Evaluation/Checkpointing\ncmd:option('-save_checkpoint_every', 10000, 'how often to save a model checkpoint?')\ncmd:option('-checkpoint_path', 'checkpoints', 'folder to save checkpoints into (empty = this folder)')\ncmd:option('-losses_log_every', 100, 'How often do we snapshot losses, for inclusion in the progress dump? (0 = disable)')\ncmd:option('-print_train_loss_every', 500, 'How often do we print losses (0 = disable)')\n\n-- misc\ncmd:option('-backend', 'cudnn', 'nn|cudnn')\ncmd:option('-id', '', 'an id identifying this run/job. used in cross-val and appended when writing progress files')\ncmd:option('-seed', 123, 'random number generator seed to use')\ncmd:option('-gpuid', 0, 'which gpu to use. -1 = use CPU')\n\ncmd:text()\n\n-------------------------------------------------------------------------------\n-- Basic Torch initializations\n-------------------------------------------------------------------------------\nlocal opt = cmd:parse(arg)\ntorch.manualSeed(opt.seed)\ntorch.setdefaulttensortype('torch.FloatTensor') -- for CPU\n\nif opt.gpuid >= 0 then\n require 'cutorch'\n require 'cunn'\n if opt.backend == 'cudnn' then \n require 'cudnn' \n cudnn.benchmark = true\n end\n cutorch.manualSeed(opt.seed)\n math.randomseed(opt.seed)\n cutorch.setDevice(opt.gpuid + 1) -- note +1 because lua is 1-indexed\nend\n\n-------------------------------------------------------------------------------\n-- Initialize the networks\n-------------------------------------------------------------------------------\nlocal protos = {}\nif string.len(opt.weights) > 0 then\n -- Load checkpoint\n print('initializing weights from ' .. opt.weights)\n cp = torch.load(opt.weights)\n protos = cp.protos\nelse -- create protos from scratch\n\n -- intialize model\n protos.cnn = models.load_presnet(opt.descriptor_size)\n protos.mlp = models.load_triplet_net(protos.cnn, opt)\n cp = {}\nend\n\n-- Load criterion \nprotos.crit = nn.DistanceRatioCriterion()\n\n-- flatten and prepare all model parameters to a single vector. \nlocal params, grad_params = protos.mlp:getParameters()\nprint('total number of parameters in model: ', params:nElement())\nassert(params:nElement() == grad_params:nElement())\n\ncollectgarbage() -- \"yeah, sure why not\"\n\n-------------------------------------------------------------------------------\n-- Create the Data Loader instance\n-------------------------------------------------------------------------------\nopt.mode = 'train'\nprint(\"loading training database\")\nloader = DataLoader(opt)\n\n-- load validation dataloader\nprint(\"Loading validation database\")\nval_opt = {}\nval_opt.root_dir = opt.root_dir\nval_opt.mode = 'full'\nval_opt.dataset = opt.val_dataset\n\nlocal val_loader = DataLoader(val_opt)\n\n-- ship everything to GPU, maybe\nif opt.gpuid >= 0 then\n for k,v in pairs(protos) do v:cuda() end\nend\n\n-------------------------------------------------------------------------------\n-- Validation evaluation\n-------------------------------------------------------------------------------\nlocal function map_eval()\n protos.mlp:evaluate()\n local data = val_loader:get_data()\n local N = data.images:size(1)\n local cnn = protos.mlp.modules[1].modules[1]\n\n descrs = torch.CudaTensor(N, opt.descriptor_size)\n descrs_split = descrs:split(opt.batch_size)\n for i,v in ipairs(data.images:split(opt.batch_size)) do\n descrs_split[i]:copy(cnn:forward(v:cuda()))\n end\n\n result = utils.map_eval(val_opt.dataset, opt.id, descrs, opt.val_upper_bound, opt.fold)\n return result\nend\n\n-------------------------------------------------------------------------------\n-- Main loop\n-------------------------------------------------------------------------------\n\noptimState = {\n learningRate = opt.learning_rate,\n weightDecay = 1e-4,\n momentum = 0.9,\n dampening = 0,\n nesterov = 1,\n}\n\nlocal iter = opt.iter or 0\nlocal inputs\nlocal targets\nlocal loss\nlocal loss_history = cp.loss_history or {}\nlocal map_history = cp.map_history or {}\nlocal running_average_loss = 0\nlocal best_score\nlocal outputs\nlocal cnn_outputs\nlocal learning_rate = opt.learning_rate\n\nmap_result = map_eval()\nprint('validation desrc MaP: ' .. map_result.MaP_qbe)\nmap_history[iter] = map_result.MaP_qbe\n\nprint('starting main loop')\nwhile true do\n local feval = function(f)\n if f ~= params then params:copy(f) end\n grad_params:zero()\n\n protos.mlp:training()\n inputs = loader:getBatch{batch_size = opt.batch_size}\n\n outputs = protos.mlp:forward(inputs)\n loss = protos.crit:forward(outputs, 1)\n df_do = protos.crit:backward(outputs)\n protos.mlp:backward(inputs, df_do)\n return losses,grad_params\n end\n\n optimState.learningRate = learning_rate\n optim.sgd(feval, params, optimState)\n losses = {}\n losses.total_loss = loss\n\n -- Record loss in various ways\n running_average_loss = running_average_loss + losses.total_loss\n \n -- Optional printing and logging of losses\n if iter % opt.losses_log_every == 0 then loss_history[iter] = losses.total_loss end\n\n if opt.print_train_loss_every > 0 and iter % opt.print_train_loss_every == 0 then\n running_average_loss = running_average_loss / opt.print_train_loss_every\n print(string.format('iter %d: %f, lr=%f', iter, running_average_loss, learning_rate ))\n running_average_loss = 0\n end\n\n -- save checkpoint once in a while (or on final iteration)\n if (iter > 0 and iter % opt.save_checkpoint_every == 0 or iter == opt.max_iters) then\n\n -- do MaP eval\n map_result = map_eval()\n print('validation MaP: ' .. map_result.MaP_qbe)\n map_history[iter] = map_result.MaP_qbe\n\n local checkpoint_path = path.join(opt.checkpoint_path, opt.id .. '_iter_' .. iter)\n\n -- write a (thin) json report\n local checkpoint = {}\n checkpoint.opt = opt\n checkpoint.iter = iter\n checkpoint.loss_history = loss_history\n checkpoint.map_history = map_history\n checkpoint.learning_rate = learning_rate\n\n utils.write_json(checkpoint_path .. '.json', checkpoint)\n print('wrote json checkpoint to ' .. checkpoint_path .. '.json')\n\n -- write the full model checkpoint as well if we did better than ever\n local current_score = map_result.MaP_qbe\n -- if best_score == nil or current_score > best_score then\n best_score = current_score\n if iter > 0 then -- dont save on very first iteration\n -- include the protos (which have weights) and save to file\n \n protos.mlp:clearState()\n local save_protos = {}\n\t\t save_protos.mlp = protos.mlp\n checkpoint.protos = save_protos\n checkpoint.iter = iter\n torch.save(checkpoint_path .. '.t7', checkpoint)\n print('wrote checkpoint to ' .. checkpoint_path .. '.t7')\n end\n -- end\n end\n\n if iter % opt.learning_rate_decay_every == 0 and iter > 0 then\n learning_rate = learning_rate * opt.learning_rate_decay_factor -- set the decayed rate\n end\n\n -- stopping criterions\n iter = iter + 1\n if iter % 10 == 0 then collectgarbage() end -- good idea to do this once in a while, i think\n if opt.max_iters > 0 and iter > opt.max_iters then break end -- stopping criterion\n\nend\n"
},
{
"alpha_fraction": 0.6547397971153259,
"alphanum_fraction": 0.6703066825866699,
"avg_line_length": 33.158729553222656,
"blob_id": "1f0369a2c38ff7f52cfb0570abe5f067c424ad2e",
"content_id": "efbf5982dcb9bbe0b82114d91a9a914cd072c410",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4304,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 126,
"path": "/misc/DataLoader.lua",
"repo_name": "AniketGurav/word_spotting",
"src_encoding": "UTF-8",
"text": "require 'hdf5'\nlocal npy4th = require 'npy4th'\nlocal utils = require 'misc.utils'\nlocal DataLoader = torch.class('DataLoader')\n\nfunction DataLoader:__init(opt)\n \n -- load the json file which contains additional information about the dataset\n print('DataLoader loading json file: ', opt.root_dir .. opt.dataset .. '_preprocessed.json')\n self.json = utils.read_json(opt.root_dir .. opt.dataset .. '_preprocessed.json')\n \n self.data = {}\n self.data.splits = {}\n for i=1, #self.json.data do\n self.data.splits[i] = self.json.data[i].split \n end\n\n -- open the hdf5 file\n print('DataLoader loading h5 file: ', self.json.image_db .. '.h5')\n self.h5_file = hdf5.open(self.json.image_db .. '.h5', 'r')\n\n -- Copy some variables from opt\n self.root_dir = opt.root_dir\n\n if opt.mode == 'train' then\n self.pieces = self.json.pieces[1]\n self.current_piece = 1\n\n self.data.labels = self.h5_file:read('/train_labels_1'):all()\n self.data.images = self.h5_file:read('/train_images_1'):all()\n\n -- normalize the data by mean subtraction\n self.stats = utils.get_stats(self.data.images)\n -- torch.save('stats.'.. opt.dataset..'.t7', stats)\n npy4th.savenpy(self.json.image_db .. '.mean.npy', torch.Tensor({self.stats.mi}))\n self.data.images:add(-self.stats.mi)\n\n -- extract image size from dataset\n local images_size = #self.data.images\n print(images_size)\n assert(#images_size == 4, '/train_images should be a 4D tensor')\n self.num_images = images_size[1]\n self.num_channels = images_size[2]\n self.image_height = images_size[3]\n self.image_width = images_size[4]\n print(string.format('read %d images of size %dx%dx%d', self.num_images, \n self.num_channels, self.image_height, self.image_width))\n\n -- Some utilities for random triplet sampling\n self.ordered_data = utils.ArrangeByLabel(self.data)\n \n -- Initialize iterators, used for get_batch\n self.iterators = {}\n self.iterators['train'] = 1\n\n else\n self.data.labels = self.h5_file:read('/labels'):all()\n self.data.images = self.h5_file:read('/images'):all()\n local stats = utils.get_stats(self.data.images) -- slightly different mean from the training dataset, but shouldn't matter.\n self.data.images:add(-stats.mi)\n\n -- extract image size from dataset\n local images_size = #self.data.images\n print(images_size)\n assert(#images_size == 4, '/images should be a 4D tensor')\n self.num_images = images_size[1]\n self.num_channels = images_size[2]\n self.image_height = images_size[3]\n self.image_width = images_size[4]\n print(string.format('read %d images of size %dx%dx%d', self.num_images, \n self.num_channels, self.image_height, self.image_width))\n end\n\nend\n\nfunction DataLoader:get_data()\n return self.data\nend\n\nfunction DataLoader:resetIterator(split)\n self.iterators[split] = 1\nend\n\nfunction DataLoader:switch_data_piece(piece)\n print(\"switching to data piece \" .. piece)\n -- Load next data piece\n self.h5_file = hdf5.open(self.json.image_db .. '.h5', 'r')\n self.data.labels = self.h5_file:read('/train_labels_' .. piece):all()\n self.data.images = self.h5_file:read('/train_images_' .. piece):all()\n self.h5_file:close()\n\n -- Subtract training mean and update some variables\n self.data.images:add(-self.stats.mi)\n local images_size = #self.data.images\n self.num_images = images_size[1]\n self.current_piece = piece\n self.ordered_data = utils.ArrangeByLabel(self.data)\nend\n\nfunction DataLoader:getBatch(opt)\n local batch_size = utils.getopt(opt, 'batch_size') -- how many images get returned at one time (to go through CNN)\n\n -- Randomly sample triplets\n local t = utils.generate_triplets(self.ordered_data, batch_size)\n\n local x=torch.zeros(batch_size,1,60,160):cuda()\n local y=torch.zeros(batch_size,1,60,160):cuda()\n local z=torch.zeros(batch_size,1,60,160):cuda()\n\n local split = 'train'\n local k = self.iterators[split]\n for i=1,batch_size do \n if self.pieces > 1 and k > self.num_images then \n self:switch_data_piece((self.current_piece % self.pieces) + 1) \n k = 1\n end\n x[i] = self.data.images[t[i][1]]\n y[i] = self.data.images[t[i][2]]\n z[i] = self.data.images[t[i][3]]\n k = k + 1\n end\n self.iterators[split] = k\n\n local data = {x, y, z}\n return data\nend\n"
}
] | 15 |
KirillVladimirov/kayak | https://github.com/KirillVladimirov/kayak | 5ced38c96f98935491f6d232eac6848634244f3b | 93024b6ec652835c99a616a3585923f2ac2049c8 | df7a85379abe7a3b7e180fe2dbada98f4a5cb1ed | refs/heads/master | 2020-07-02T00:32:46.469482 | 2019-08-13T02:36:30 | 2019-08-13T02:36:30 | 201,361,450 | 0 | 0 | null | 2019-08-09T00:59:19 | 2019-08-13T02:36:37 | 2019-11-01T15:21:45 | Python | [
{
"alpha_fraction": 0.6959999799728394,
"alphanum_fraction": 0.7013333439826965,
"avg_line_length": 24,
"blob_id": "b4e02971efb848cf61e994f2073511f508ce8c84",
"content_id": "d635fbd148852c405e6b92ac4b85154261d7989e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 15,
"path": "/kayak/__main__.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import argparse\n\nfrom kayak.core import Engine\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-V\", \"--version\", help=\"show program version\", action=\"store_true\")\nparser.add_argument(\"-S\", \"--spider\", help=\"run spider\")\nargs = parser.parse_args()\n\nif args.version:\n print(\"version 0.1\")\n\nif args.spider:\n engine = Engine()\n engine.start_spider(args.spider)\n"
},
{
"alpha_fraction": 0.6053783893585205,
"alphanum_fraction": 0.6091306805610657,
"avg_line_length": 30.352941513061523,
"blob_id": "ad05ae174fc382aa65286e82b4b8ce9fb8b3d409",
"content_id": "a614c2f423cce04192c1675e3d66cf0b11bd1521",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1599,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 51,
"path": "/kayak/spiders/lenta.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import locale\nimport logging.config\nimport re\nfrom datetime import datetime\n\nfrom bs4 import BeautifulSoup\n\nfrom kayak import settings\nfrom kayak.core import Spider\nfrom kayak.models import Article\n\nlogging.config.dictConfig(settings.LOGGING)\nlog = logging.getLogger(__name__)\n\n\nclass Lenta(Spider):\n sitemap_urls = ['https://lenta.ru/sitemap.xml.gz']\n\n def __init__(self):\n pass\n\n def parse(self, response):\n locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')\n article = Article()\n soup = BeautifulSoup(response.content, features=\"html.parser\")\n headline = soup.find(itemprop=\"headline\")\n if headline:\n article.headline = headline.get_text()\n log.info(f\"Title: {headline.get_text()}\")\n\n article_body = soup.find(itemprop=\"articleBody\")\n if article_body:\n article.body = article_body.get_text()\n log.info(f\"Body: {article_body.get_text()[:100]}\")\n\n date_published = soup.find(itemprop=\"datePublished\")\n if date_published:\n date = date_published.get_text()\n article.date_published = datetime.strptime(date.strip(), \"%H:%M, %d %B %Y\")\n log.info(f\"Date published: {date_published.get_text()}\")\n\n pattern = re.compile(r\"\\s*slug: \\'([\\w]+)\\'\")\n script = soup.find(\"script\", text=pattern)\n if script:\n match = pattern.search(script.text)\n if match:\n category = match.group(1)\n article.category = category\n log.info(f\"Category: {category}\")\n\n return article\n"
},
{
"alpha_fraction": 0.5369085073471069,
"alphanum_fraction": 0.5526813864707947,
"avg_line_length": 33.83516311645508,
"blob_id": "cfc54b03651b5d0b24386f06843d2034f282983e",
"content_id": "a872bb246f7f06529357cadca1bfdbd443036a4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3318,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 91,
"path": "/alembic/versions/66f323ad87bb_.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: 66f323ad87bb\nRevises: b9a7431819ca\nCreate Date: 2019-08-10 21:44:12.498531\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '66f323ad87bb'\ndown_revision = 'b9a7431819ca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('article', 'body',\n existing_type=sa.VARCHAR(),\n comment='Текст статьи',\n existing_nullable=True)\n op.alter_column('article', 'category',\n existing_type=sa.VARCHAR(),\n comment='Категория статьи',\n existing_nullable=True)\n op.alter_column('article', 'created_at',\n existing_type=sa.DATE(),\n comment='',\n existing_nullable=True)\n op.alter_column('article', 'date_published',\n existing_type=sa.DATE(),\n comment='Дата обновления статьи',\n existing_nullable=True)\n op.alter_column('article', 'headline',\n existing_type=sa.VARCHAR(),\n comment='Заголовок статьи',\n existing_nullable=True)\n op.alter_column('article', 'updated_at',\n existing_type=sa.DATE(),\n comment='',\n existing_nullable=True)\n op.alter_column('article', 'url',\n existing_type=sa.VARCHAR(),\n nullable=False,\n comment='Адрес страницы')\n op.create_unique_constraint(None, 'article', ['url'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'article', type_='unique')\n op.alter_column('article', 'url',\n existing_type=sa.VARCHAR(),\n nullable=True,\n comment=None,\n existing_comment='Адрес страницы')\n op.alter_column('article', 'updated_at',\n existing_type=sa.DATE(),\n comment=None,\n existing_comment='',\n existing_nullable=True)\n op.alter_column('article', 'headline',\n existing_type=sa.VARCHAR(),\n comment=None,\n existing_comment='Заголовок статьи',\n existing_nullable=True)\n op.alter_column('article', 'date_published',\n existing_type=sa.DATE(),\n comment=None,\n existing_comment='Дата обновления статьи',\n existing_nullable=True)\n op.alter_column('article', 'created_at',\n existing_type=sa.DATE(),\n comment=None,\n existing_comment='',\n existing_nullable=True)\n op.alter_column('article', 'category',\n existing_type=sa.VARCHAR(),\n comment=None,\n existing_comment='Категория статьи',\n existing_nullable=True)\n op.alter_column('article', 'body',\n existing_type=sa.VARCHAR(),\n comment=None,\n existing_comment='Текст статьи',\n existing_nullable=True)\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.6057866215705872,
"alphanum_fraction": 0.6745027303695679,
"avg_line_length": 18.75,
"blob_id": "56602944a486a7e4f45dce06ee32fdd61ed7c292",
"content_id": "7d2d170da176b7e9c2305170b3c00f0c56a85d4f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 553,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 28,
"path": "/alembic/versions/b9a7431819ca_.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: b9a7431819ca\nRevises: c20c7790c1d6\nCreate Date: 2019-08-10 21:32:35.551634\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b9a7431819ca'\ndown_revision = 'c20c7790c1d6'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n pass\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n pass\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.7204782962799072,
"alphanum_fraction": 0.7204782962799072,
"avg_line_length": 21.299999237060547,
"blob_id": "b05991e65613a778b44a0671780e42b5729c4128",
"content_id": "676b0932da6984a3a8ef531e8a7de39875a8357f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 669,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 30,
"path": "/kayak/tests/conftest.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import os\n\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom kayak import settings\nfrom kayak.models import Base\n\n\[email protected]\ndef db_session():\n engine = create_engine(settings.DATABASE_URL_TEST)\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n yield Session()\n Session.close_all()\n Base.metadata.drop_all(bind=engine)\n\n\[email protected]\ndef remove_file():\n filename = os.path.abspath(os.path.join(os.path.curdir, \"test_scheduler.pickle\"))\n if os.path.exists(filename):\n os.remove(filename)\n\n yield\n\n if os.path.exists(filename):\n os.remove(filename)\n"
},
{
"alpha_fraction": 0.6474313735961914,
"alphanum_fraction": 0.6699507236480713,
"avg_line_length": 34.525001525878906,
"blob_id": "3fc2259a746f4e0b0c86bb89923115aecd4708ea",
"content_id": "a0766e981ef2467f1719fd2d3844f56eaf12810b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1421,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 40,
"path": "/alembic/versions/f4c52a51adb8_.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: f4c52a51adb8\nRevises: 1e217d2c6615\nCreate Date: 2019-08-10 19:23:48.546136\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f4c52a51adb8'\ndown_revision = '1e217d2c6615'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('article', sa.Column('body', sa.String(), nullable=True))\n op.add_column('article', sa.Column('created_at', sa.Date(), nullable=True))\n op.add_column('article', sa.Column('date_published', sa.Date(), nullable=True))\n op.add_column('article', sa.Column('headline', sa.String(), nullable=True))\n op.add_column('article', sa.Column('updated_at', sa.Date(), nullable=True))\n op.drop_column('article', 'title')\n op.drop_column('article', 'text')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('article', sa.Column('text', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('article', sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_column('article', 'updated_at')\n op.drop_column('article', 'headline')\n op.drop_column('article', 'date_published')\n op.drop_column('article', 'created_at')\n op.drop_column('article', 'body')\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.6081871390342712,
"alphanum_fraction": 0.640350878238678,
"avg_line_length": 28.037734985351562,
"blob_id": "075aa2a06119e4d89340c6e3620bf440214fd949",
"content_id": "1ad4448cf49283be79a85ab7d294b78969175856",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3078,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 106,
"path": "/kayak/tests/test_core.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import pickle\nfrom collections import deque\n\nfrom kayak import settings\nfrom kayak.core import Engine, Scheduler\nfrom kayak.models import Article\nfrom kayak.spiders.lenta import Lenta\n\n\ndef test_create_engine():\n engine = Engine()\n assert engine.VERSION == settings.APP_VERSION\n\n\ndef test_import_class_from_string():\n mod = __import__('kayak.spiders.lenta', fromlist=['Lenta'])\n klass = getattr(mod, 'Lenta')\n spider = klass()\n assert type(spider) == Lenta\n\n\ndef test_engine_find_spider_class():\n engine = Engine()\n spider_cls = engine.SPIDER_MODULES[\"lenta\"]\n _module, _class = spider_cls.rsplit(\".\", 1)\n mod = __import__(_module, fromlist=[_class])\n klass = getattr(mod, _class)\n spider = klass()\n assert type(spider) == Lenta\n\n\ndef test_create_article(db_session):\n article1 = Article(headline=\"title 1\", body=\"some text 1\", url=\"some url 1\")\n article2 = Article(headline=\"title 2\", body=\"some text 2\", url=\"some url 2\")\n db_session.add(article1)\n db_session.add(article2)\n db_session.commit()\n\n articles = db_session.query(Article).all()\n assert len(articles) == 2\n article = articles[0]\n assert (article.headline, article.body) == (\"title 1\", \"some text 1\")\n\n\ndef test_check_duplicates(db_session):\n url = \"some url 1\"\n article = Article(headline=\"title 1\", body=\"some text 1\", url=url)\n db_session.add(article)\n db_session.commit()\n\n engine = Engine()\n assert engine.check_exists(url)\n\n\ndef test_serialize_queue():\n queue = deque()\n queue.append(\"1\")\n filename = \"queue.pickle\"\n outfile = open(filename, 'wb')\n pickle.dump(queue, outfile)\n outfile.close()\n\n infile = open(filename, 'rb')\n new_queue = pickle.load(infile)\n infile.close()\n assert new_queue.pop() == \"1\"\n\n\ndef test_scheduler_get_next_request():\n engine = Engine()\n sch = Scheduler(engine.downloader)\n url = \"https://lenta.ru/news/2010/05/30/laws/\"\n sch.enqueue_request(url)\n new_url = sch.next_request()\n assert url == new_url\n\n\ndef test_scheduler_enqueue_sitemap():\n engine = Engine()\n sch = Scheduler(engine.downloader)\n urls = [\n \"https://lenta.ru/news/2010/05/29/murder/\",\n \"https://lenta.ru/news/2012/05/16/goodbyeabay/\",\n \"https://lenta.ru/news/2010/05/30/klitchko/\",\n \"https://lenta.ru/news/2011/05/20/wasted/\",\n ]\n sch.enqueue_sitemap(urls)\n new_request = sch.next_request()\n assert urls[0] == new_request\n\n\n# def test_scheduler_save_to_file(remove_file):\n# engine = Engine()\n# sch1 = Scheduler(engine.downloader, save_file=\"test_scheduler\")\n# urls = [\n# \"https://lenta.ru/news/2010/05/29/murder/\",\n# \"https://lenta.ru/news/2012/05/16/goodbyeabay/\",\n# \"https://lenta.ru/news/2010/05/30/klitchko/\",\n# \"https://lenta.ru/news/2011/05/20/wasted/\",\n# ]\n# sch1.enqueue_sitemap(urls)\n#\n# sch2 = Scheduler(engine.downloader, save_file=\"test_scheduler\")\n# assert len(urls) == len(sch2.queue)\n# new_request = sch2.next_request()\n# assert urls[0] == new_request\n"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 16.75,
"blob_id": "16f79f647ada756c8cb1bf7b6fb0677e1b6e09e3",
"content_id": "6f12e287f387e3dc5b452aa2b19ca2eac84e23de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 70,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 4,
"path": "/.flake8",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "[flake8]\nmax-line-length = 120\nexclude = alembic/\n# max-complexity = 7"
},
{
"alpha_fraction": 0.5850312113761902,
"alphanum_fraction": 0.5879417657852173,
"avg_line_length": 28.814048767089844,
"blob_id": "17ac92c9d6aa1b068dec69e6a7f8e70a85ce1c7b",
"content_id": "620c28c6d960e988719aa942c35c63ee07541332",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7314,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 242,
"path": "/kayak/core.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import logging.config\nimport pickle\nimport random\nimport time\nfrom collections import deque\nfrom gzip import GzipFile\nfrom io import BytesIO\nfrom typing import List\n\nimport requests\nimport sqlalchemy\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import RequestException\n\nfrom kayak import settings\nfrom kayak.models import Session, Article\n\nlogging.config.dictConfig(settings.LOGGING)\nlog = logging.getLogger(__name__)\n\n\nclass DownloadPageException(RequestException):\n pass\n\n\nclass GunzipException(RequestException):\n pass\n\n\nclass QueueEmptyException(RequestException):\n pass\n\n\nclass NotConfigured(Exception):\n \"\"\"Indicates a missing configuration situation\"\"\"\n\n pass\n\n\nclass IgnoreRequest(Exception):\n \"\"\"Indicates a decision was made not to process a request\"\"\"\n\n pass\n\n\nclass Engine:\n def __init__(self):\n self.initialize_settings()\n self.db_session = Session()\n self.scheduler = None\n self.spider = None\n self.is_running = False\n self.downloader = Downloader(self)\n\n def initialize_settings(self):\n prefix = \"APP_\"\n setting_names = [item for item in dir(settings) if item.startswith(prefix)]\n for key in setting_names:\n setattr(self, key.replace(prefix, ''), getattr(settings, key))\n\n def start_spider(self, spider_name):\n self.spider = self.create_spider(spider_name)\n self.scheduler = Scheduler(self.downloader, save_file=spider_name)\n self.scheduler.init(self.spider)\n self.is_running = True\n while self.is_running:\n self.is_running = self.processing()\n log.info(\"Stop processing. Url list is empty.\")\n\n def create_spider(self, spider_name):\n spider_cls = self.SPIDER_MODULES[spider_name]\n _module, _class = spider_cls.rsplit(\".\", 1)\n mod = __import__(_module, fromlist=[_class])\n klass = getattr(mod, _class)\n return klass()\n\n def processing(self):\n url = self.scheduler.next_request()\n if not url:\n return False\n if self.check_exists(url):\n log.error(f\"Extract duplicate url {url}.\")\n return True\n response = self.downloader.download(url)\n if not response:\n return True\n article = self.spider.parse(response)\n article.url = url\n try:\n self.db_session.add(article)\n self.db_session.commit()\n except sqlalchemy.exc.IntegrityError:\n self.db_session.rollback()\n log.error(f\"Try save duplicate article. Url {url}\")\n self.downloader.download_delay()\n return True\n\n def check_exists(self, url: str) -> bool:\n articles = self.db_session.query(Article) \\\n .filter(Article.url == url) \\\n .all()\n return bool(len(articles))\n\n\nclass Scheduler:\n def __init__(self, downloader, save_file=None):\n self.queue = deque()\n self.filename = f'{save_file}.pickle' if save_file else None\n downloader.set_scheduler(self)\n self.limit_without_save = 10\n self.count = 0\n\n def enqueue_request(self, request_url: str) -> None:\n self.queue.append(request_url)\n log.info(f\"Add request {request_url} to sheduler.\")\n\n def next_request(self) -> str:\n try:\n request_url = self.queue.popleft()\n self.count += 1\n if self.count > self.limit_without_save:\n self.save_queue()\n self.count = 0\n return request_url if request_url else None\n except IndexError:\n log.info(\"Final. Empty queue.\")\n\n def enqueue_sitemap(self, request_urls: List) -> None:\n for request_url in request_urls:\n self.enqueue_request(request_url)\n self.save_queue()\n log.info(f\"Save satemap.\")\n\n def init(self, spider):\n self.load_queue()\n if len(self.queue) == 0:\n if spider.urls:\n self.enqueue_sitemap(spider.urls)\n else:\n self.enqueue_sitemap(spider.sitemap_urls)\n\n def save_queue(self) -> None:\n if self.filename:\n with open(self.filename, 'wb') as file:\n pickle.dump(self.queue, file)\n log.info(f\"Save queue to file: {len(self.queue)} record(s).\")\n\n def load_queue(self) -> None:\n if self.filename:\n try:\n with open(self.filename, 'rb') as file:\n self.queue = pickle.load(file)\n log.info(f\"Size of loaded queue: {len(self.queue)} record(s).\")\n except FileNotFoundError:\n log.error(f\"File {self.filename} not found and queue is empty.\")\n\n\nclass Spider:\n urls = None\n sitemap_urls = None\n\n def parse(self, response):\n raise NotImplementedError\n\n\nclass Downloader(object):\n def __init__(self, engine):\n self.scheduler = None\n self.headers = engine.DEFAULT_REQUEST_HEADERS\n self.session = self.create_session()\n\n def create_session(self):\n session = requests.session()\n session.headers.update(self.headers)\n return session\n\n def download(self, url: str):\n response = self.get_page(url)\n if url.endswith(\"xml.gz\"):\n try:\n unziped_context = self.gunzip(response.content)\n self.scheduler.enqueue_sitemap(self.process_sitemap(unziped_context))\n response = None\n except (IOError, EOFError):\n raise GunzipException()\n return response\n\n def get_page(self, url: str):\n \"\"\"\n Скачать sitemap.xml\n \"\"\"\n for _ in range(3):\n try:\n response = self.session.get(url, timeout=10)\n break\n except:\n self.session = self.create_session()\n time.sleep(20)\n continue\n if response.status_code != 200:\n raise DownloadPageException(f\"Request GET {url} return status code {response.status_code}!\")\n log.info(f\"Download page {url} successfully.\")\n return response\n\n def gunzip(self, data):\n \"\"\"\n Распаковка gzip файла\n \"\"\"\n f = GzipFile(fileobj=BytesIO(data))\n output_list = []\n chunk = b\".\"\n while chunk:\n try:\n chunk = f.read(8196)\n output_list.append(chunk)\n except (IOError, EOFError):\n raise\n return b\"\".join(output_list)\n\n def extract_sitemap_licks(self, soup: BeautifulSoup) -> List[str]:\n links = []\n for loc in soup.findAll(\"loc\"):\n links.append(loc.text)\n return links\n\n def download_delay(self) -> None:\n \"\"\"\n Выполнить задержку перед загрузкой следующей страницы\n \"\"\"\n delays = [1]\n delay = random.choice(delays)\n time.sleep(delay)\n\n def process_sitemap(self, s: bytes) -> List[str]:\n \"\"\"\n Обработка sitemap, извлечение всех ссылок\n \"\"\"\n soup = BeautifulSoup(s, features=\"lxml\")\n return self.extract_sitemap_licks(soup)\n\n def set_scheduler(self, scheduler):\n self.scheduler = scheduler\n"
},
{
"alpha_fraction": 0.7275985479354858,
"alphanum_fraction": 0.7383512258529663,
"avg_line_length": 12,
"blob_id": "6df934bcaf8b98683862ecacc41a19a7151efcba",
"content_id": "00ef1caf479ca05709c5a4e9be5abe767c22f6d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 781,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 43,
"path": "/README.md",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "1. Установка\n\n```\npip install pip-tools\nmake install\n```\n\n\n2. Настройка окружения\n\nСоздать фаил .env в корне проекта с настройками переменных окружающей среды.\nПример такого файла .env.ptl\n\nВ файле alembic.ini прописать доступ к базе данных sqlalchemy.url \n\nВыполнить миграции\n```\nalembic upgrade head\n```\n\n\n3. Тестирование\n```\nmake test\n```\n\n\n4. Автоматическое создание миграций\n```\nalembic revision --autogenerate\n```\n\n\n5. Запуск паука\n```\npython kayak --spider lentaru\n```\n\n6. Создание миграций\n```\nalembic revision --autogenerate\nalembic upgrade head\n```"
},
{
"alpha_fraction": 0.6269350051879883,
"alphanum_fraction": 0.6702786087989807,
"avg_line_length": 22.071428298950195,
"blob_id": "8a8c475d1c0caae9165b778bc0e65e8c015c5925",
"content_id": "833b241a255e992526570b7283fd73c2c77df8f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 646,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 28,
"path": "/alembic/versions/c5369cde7126_.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: c5369cde7126\nRevises: f4c52a51adb8\nCreate Date: 2019-08-10 19:28:22.823390\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c5369cde7126'\ndown_revision = 'f4c52a51adb8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('article', sa.Column('category', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('article', 'category')\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.5931915044784546,
"alphanum_fraction": 0.6238297820091248,
"avg_line_length": 35.71875,
"blob_id": "fa53ef02ce7f4cac4dc6efd8de82c93d32da4173",
"content_id": "5032eddc7da605882864ae34a1f672f7b7fe20d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1175,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 32,
"path": "/kayak/settings.py",
"repo_name": "KirillVladimirov/kayak",
"src_encoding": "UTF-8",
"text": "import os\n\nfrom dotenv import find_dotenv, load_dotenv\n\nload_dotenv(find_dotenv())\n\n\nAPP_VERSION = os.getenv(\"VERSION\", \"0.1.0\")\n\nAPP_SPIDER_MODULES = {\"lenta\": \"kayak.spiders.lenta.Lenta\"}\n\nAPP_DEFAULT_REQUEST_HEADERS = {\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/56.0.2924.87 Safari/537.36\",\n \"referrer\": \"https://google.com\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n \"Pragma\": \"no-cache\",\n}\n\nDATABASE_URL = os.getenv(\"DATABASE_URL\", None)\nDATABASE_URL_TEST = os.getenv(\"DATABASE_URL_TEST\", None)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{'},\n 'simple': {'format': '{levelname} {asctime} [{module}] {message}', 'style': '{'},\n },\n 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple'}},\n 'loggers': {'': {'handlers': ['console'], 'level': 'INFO', 'propagate': False}},\n}\n"
}
] | 12 |
apitronics/WeatherBeacon-Sensor-Tests | https://github.com/apitronics/WeatherBeacon-Sensor-Tests | 9b243193005dac84993325d0bc3e9f03cbcf78bb | ff61b49fd99d5b4d80b8cf843ef131d83292c516 | 6db80dc995f59f57533c0f82294cdb73542b532d | refs/heads/master | 2021-01-13T10:28:52.989071 | 2016-03-11T00:53:43 | 2016-03-11T00:53:43 | 52,997,084 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6075268983840942,
"alphanum_fraction": 0.6623656153678894,
"avg_line_length": 23.5,
"blob_id": "aee60993b9aaa5d185f2d0e28703c5e173a04056",
"content_id": "f0c76b00755a9a7d047aefda0eb4936db7a5e301",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 932,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 38,
"path": "/SandBox/sandbox_cap1/sandbox_cap1.py",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 3 11:03:48 2016\n\n@author: Colin\n\"\"\"\n\n\nimport pandas as pd\n\nimport datetime\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('ggplot')\n\n#The timezone and UTC offset break our timedate, so just ignore them\nparser = lambda date: pd.datetime.strptime(date[:-9], '%Y-%m-%d %H:%M:%S') #2016-03-01 12:16:04\n\n\n#read csv file, index by timestamp, take only March 1st data\ndf = pd.read_csv('224-Cap 1.csv', index_col = 'Time', \n parse_dates = 'Time', date_parser=parser).loc['2016-03-01 08:00:00':]\n \n#find all the resets that occured\ndf_restarts = df.loc[df['Status ()']>0].index\n\n\n#take all from start last reset\ndf_am_slice = df.loc[:df_restarts[-1]]\n\n#take all from last reset to end\ndf_pm_slice = df.loc[df_restarts[-1]:]\n\n\ndf_am_slice['Solar Radiation (W/m²)'].plot()\ndf_pm_slice['Solar Radiation (W/m²)'].plot()"
},
{
"alpha_fraction": 0.5308219194412231,
"alphanum_fraction": 0.6061643958091736,
"avg_line_length": 28.9743595123291,
"blob_id": "6e13b88d2934632f79c538706330813d1eebc172",
"content_id": "820af776b1f42c59446d32962de6e2f2ff764ca3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1168,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 39,
"path": "/Caprica-Light-Tests/quick_sensors_plot.py",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 10 16:18:56 2016\n\n@author: Colin\n\"\"\"\n\n\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('ggplot')\nplt.close(\"all\")\n\n#The timezone and UTC offset break our timedate, so just ignore them\nparser = lambda date: pd.datetime.strptime(date[:-9], '%Y-%m-%d %H:%M:%S') #2016-02-25 16:42:28 PST-0800\n\ncsv_files = ['224-Cap 1.csv', '225-Cap 2.csv', '226-Cap 3.csv', '227-Cap 4.csv',\n '236-Cap 5.csv', '237-Cap 6.csv', '238-Cap 7.csv', '228-Cap 8.csv']\n\n\nfor csv_file in csv_files:\n #read csv file, index by timestamp, take only March 1st data\n df = pd.read_csv(csv_file, index_col = 'Time', \n parse_dates = 'Time', date_parser=parser).loc[\n '2016-03-01 08:00:00':]\n \n plt.subplot(3, 1, 1) \n df.loc[:,'Air Temperature (C)'].plot(sharex=True)\n plt.ylabel('Temp (C)');\n plt.subplot(3, 1, 2) \n df.loc[:,'Relative Humidity (%)'].plot(sharex=True)\n plt.ylabel('RH (%)');\n plt.subplot(3, 1, 3) \n df.loc[:,'Atmospheric Pressure (hPa)'].plot()\n plt.ylabel('Pressure (hPa)');"
},
{
"alpha_fraction": 0.6015384793281555,
"alphanum_fraction": 0.6553846001625061,
"avg_line_length": 26.125,
"blob_id": "83e3b4f33e140574702457964620487f2dc12757",
"content_id": "2ad929a8323b2567934704519dca0c8f4716c2a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 650,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 24,
"path": "/DS-MarkV/solar_watts_integrator.py",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 9 17:49:50 2016\n\n@author: Colin\n\"\"\"\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n#matplotlib.style.use('ggplot')\n\n#The timezone and UTC offset break our timedate, so just ignore them\nparser = lambda date: pd.datetime.strptime(date[:-9], '%Y-%m-%d %H:%M:%S') #2016-02-25 16:42:28 PST-0800\n\ncsv_file = '208-Mark V.csv'\n\n#read csv file, index by timestamp, take only March 1st data\ndf = pd.read_csv(csv_file, index_col = 'Time', \n parse_dates = 'Time', date_parser=parser).loc[:, 'Solar Watts (mW)']\n \ndf.plot()"
},
{
"alpha_fraction": 0.8428571224212646,
"alphanum_fraction": 0.8428571224212646,
"avg_line_length": 34,
"blob_id": "32adf28b8ed3853bd866b97c09176397ac9d24b1",
"content_id": "ebd40204c0228ed3e3db371b414a80f0eefbdbbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 70,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 2,
"path": "/README.md",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# WeatherBeacon-Sensor-Tests\nWeather Beacon Sensor tests and analysis\n"
},
{
"alpha_fraction": 0.5973943471908569,
"alphanum_fraction": 0.6234509348869324,
"avg_line_length": 35.8070182800293,
"blob_id": "001dcb67774ab00311da45cd08a76c03e3827e28",
"content_id": "1c2a0ba3aa953cd45c69e27d18ba1eecdd0e8513",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6294,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 171,
"path": "/Caprica-Light-Tests/solar_radiation_calc.py",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 6 16:07:17 2016\n\n@author: Colin\n\"\"\"\n\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('ggplot')\nplt.close(\"all\")\n\n\n#am data:\ncsv_file = 'df_am_all_sensors.csv'\n\ndf_am = pd.read_csv(csv_file, index_col = 'Time', parse_dates = 'Time')\n\n#slice the good data\ndf_am = df_am.loc['2016-03-01 11:00:00': '2016-03-01 12:50:00'] \n\ndf_am.to_csv('df_am_slice.csv')\ndf_stats = df_am.describe()\ndf_stats.to_csv('df_am_stats.csv')\n\n#print(df_stats)\n\n\n\n######## AM UNIT POSITIONS LOOKING SOUTH ############\n#EAST -- 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 - AG -- WEST#\n####################################################\nunit_positions = [1, 2, 3, 4, 5, 6, 7, 8]\n\ncol_titles = ['Cap 1 pyranometer (mV)','Cap 2 pyranometer (mV)','Cap 3 pyranometer (mV)', \\\n 'Cap 4 pyranometer (mV)','Cap 5 pyranometer (mV)','Cap 6 pyranometer (mV)', \\\n 'Cap 7 pyranometer (mV)', 'Cap 8 pyranometer (mV)']\n \ndelta_col_titles = [] \nposition_col_titles = [] \nerror_col_titles = [] \n\n#build new columns of calculated difference between pyranometers and Apogee\nitera = 0\nfor col_name in col_titles:\n delta_col_titles.append(col_name[:5]+' delta')\n df_am[delta_col_titles[-1]] = (df_am['Apogee pyranometer (mV)'] - df_am[col_name])\n #add error columns\n error_col_titles.append(col_name[:5]+' error')\n df_am[error_col_titles[-1]] = abs(df_am['Apogee pyranometer (mV)'] - df_am[col_name])/df_am['Apogee pyranometer (mV)'] \n #add positions columns\n position_col_titles.append(col_name[:5]+' position')\n df_am[position_col_titles[-1]] = unit_positions[itera]\n itera += 1\n \n#delta_col_titles.append('AG 5pcnt delta')\n#df_am['AG 5pcnt delta'] = df_am['Apogee pyranometer (mV)']* 0.05 \n\n##plot deltas to AG mV\n#df_am.plot(x=df_am['Apogee pyranometer (mV)'], y=delta_col_titles, title='pyranometer AM plot') \\\n# .legend(loc='best',prop={'size':8})\n# \n##plot error to AG mV\n#df_am.plot(x=df_am['Apogee pyranometer (mV)'], y=error_col_titles, title='pyranometer AM plot') \\\n# .legend(loc='best',prop={'size':8})\n\n#plot all pyranometer data\ndf_am.filter(regex = 'pyranometer').plot(title='AM Pyranometer slice').legend(loc='best',prop={'size':8})\nplt.ylabel('milliVolts')\n#plot all delta data\ndf_am.filter(regex='delta').plot(title='AM Pyranometer delta').legend(loc='best',prop={'size':8})\nplt.ylabel('milliVolts')\n#plot all error data\n#y_range = np.arange(-0.03, 0.11, 0.01)\ndf_am.filter(regex='error').plot(title='AM Pyranometer Error').legend(loc='best',prop={'size':8})\nplt.ylabel('Percent Error to Apogee')\n\n#######################################################\n############ same calc as above but for PM ############\n#######################################################\n\n#pm data:\ncsv_file = 'df_pm_all_sensors.csv'\n\ndf_pm = pd.read_csv(csv_file, index_col = 'Time', parse_dates = 'Time')\n\n#slice the good data\ndf_pm = df_pm.loc['2016-03-01 13:24:00': '2016-03-01 14:24:00'] \n\ndf_pm.to_csv('df_pm_slice.csv')\ndf_stats = df_pm.describe()\ndf_stats.to_csv('df_pm_stats.csv')\n\n#print(df_stats)\n\n######## PM UNIT POSITIONS LOOKING SOUTH ############\n#EAST -- 2 - 3 - 4 - 5 - 6 - 7 - 8 - 1 - AG -- WEST#\n####################################################\nunit_positions = [1, 8, 7, 6, 5, 4, 3, 2]\n\ncol_titles = ['Cap 1 pyranometer (mV)','Cap 2 pyranometer (mV)','Cap 3 pyranometer (mV)', \\\n 'Cap 4 pyranometer (mV)','Cap 5 pyranometer (mV)','Cap 6 pyranometer (mV)', \\\n 'Cap 7 pyranometer (mV)', 'Cap 8 pyranometer (mV)']\n \ndelta_col_titles = [] \nposition_col_titles = [] \nerror_col_titles = [] \n\n#build new columns of calculated difference between pyranometers and Apogee\nitera = 0\nfor col_name in col_titles:\n delta_col_titles.append(col_name[:5]+' delta')\n df_pm[delta_col_titles[-1]] = (df_pm['Apogee pyranometer (mV)'] - df_pm[col_name])\n #add error columns\n error_col_titles.append(col_name[:5]+' error')\n df_pm[error_col_titles[-1]] = abs(df_pm['Apogee pyranometer (mV)'] - df_pm[col_name])/df_pm['Apogee pyranometer (mV)'] \n #add positions columns\n position_col_titles.append(col_name[:5]+' position')\n df_pm[position_col_titles[-1]] = unit_positions[itera]\n itera += 1\n\n#delta_col_titles.append('AG 5pcnt delta')\n#df_pm['AG 5pcnt delta'] = df_pm['Apogee pyranometer (mV)']* 0.05 \n\n##plot delta to AG mV\n#df_pm.plot(x=df_pm['Apogee pyranometer (mV)'], y=delta_col_titles, title='pyranometer PM plot'). \\\n# legend(loc='best',prop={'size':8})\n#\n##plot error to AG mV\n#df_pm.plot(x=df_pm['Apogee pyranometer (mV)'], y=error_col_titles, title='pyranometer PM plot') \\\n# .legend(loc='best',prop={'size':8})\n\n#plot all pyranometer data\ndf_pm.filter(regex = 'pyranometer').plot(title='PM Pyranometer slice').legend(loc='best',prop={'size':8})\nplt.ylabel('milliVolts')\n#plot all delta data\ndf_pm.filter(regex='delta').plot(title='PM Pyranometer delta').legend(loc='best',prop={'size':8})\nplt.ylabel('milliVolts')\n#plot all error data\ndf_pm.filter(regex='error').plot(title='PM Pyranometer Error').legend(loc='best',prop={'size':8});\nplt.ylabel('Percent Error to Apogee');\n\n\n############ combine AM and PM ############\n#get stats on am error data\ndf_am_errstats = df_am.filter(regex='error').describe()\n#transpose data and rename columns\ndf_am_errstats = df_am_errstats.transpose()\ndf_am_errstats = df_am_errstats.rename(columns={'std': 'AM std'})\ndf_am_errstats = df_am_errstats.rename(columns={'mean': 'AM mean'})\n\n#get stats on pm error data\ndf_pm_errstats = df_pm.filter(regex='error').describe()\n#transpose data and rename columns\ndf_pm_errstats = df_pm_errstats.transpose()\ndf_pm_errstats = df_pm_errstats.rename(columns={'std': 'PM std'})\ndf_pm_errstats = df_pm_errstats.rename(columns={'mean': 'PM mean'})\n\n#combine AM and PM stats\ndf_all_errstats = pd.concat([df_pm_errstats, df_am_errstats],axis=1)\n\n\ndf_all_errstats.loc[:,['AM std', 'PM std']].plot(kind='bar',title='Pyranometers Error STD').legend(loc='best',prop={'size':8});\nplt.ylabel('Standard Deviation');\n\ndf_all_errstats.loc[:,['AM mean', 'PM mean']].plot(kind='bar',title='Pyranometers Error Mean').legend(loc='best',prop={'size':8});\nplt.ylabel('Mean');\n"
},
{
"alpha_fraction": 0.5883647799491882,
"alphanum_fraction": 0.6286163330078125,
"avg_line_length": 34.741573333740234,
"blob_id": "04d92912fb796ed4b63de92a653e120669273ae2",
"content_id": "579d1a74e534043750eb3e643bf4f29b8e6e230f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3191,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 89,
"path": "/Caprica-Light-Tests/solar_radiation_parse.py",
"repo_name": "apitronics/WeatherBeacon-Sensor-Tests",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 3 11:03:48 2016\n\n@author: Colin\n\"\"\"\n\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('ggplot')\nplt.close(\"all\")\n\n#The timezone and UTC offset break our timedate, so just ignore them\nparser = lambda date: pd.datetime.strptime(date[:-9], '%Y-%m-%d %H:%M:%S') #2016-02-25 16:42:28 PST-0800\n\ncsv_files = ['224-Cap 1.csv', '225-Cap 2.csv', '226-Cap 3.csv', '227-Cap 4.csv',\n '236-Cap 5.csv', '237-Cap 6.csv', '238-Cap 7.csv', '228-Cap 8.csv']\n\ncsv_file = csv_files[0]\n\n#read csv file, index by timestamp, take only March 1st data\ndf = pd.read_csv(csv_file, index_col = 'Time', \n parse_dates = 'Time', date_parser=parser).loc[\n '2016-03-01 08:00:00':]\n \n\n\n \n#find all the resets that occured\ndf_restarts = df.loc[df['Status ()']>0].index \n#take all from start to one before reset\ndf_am_all_sensors = df.loc[:df_restarts[-1],['Analog 3 (mV)','Solar Radiation (W/m²)']].iloc[:-1]\n#take all from last reset to end\ndf_pm_all_sensors = df.loc[df_restarts[-1]:,['Analog 3 (mV)','Solar Radiation (W/m²)']]\n\n\n#df_pm_all_sensors.loc[:,'Solar Radiation (W/m²)'].plot()\n\n#rename columns\ndf_am_all_sensors = df_am_all_sensors.rename(columns={'Analog 3 (mV)':'Apogee pyranometer (mV)',\n'Solar Radiation (W/m²)':csv_file[4:-4]+' pyranometer (mV)'})\ndf_pm_all_sensors = df_pm_all_sensors.rename(columns={'Analog 3 (mV)':'Apogee pyranometer (mV)',\n'Solar Radiation (W/m²)':csv_file[4:-4]+' pyranometer (mV)'})\n\n\nfor csv_file in csv_files[1:]:\n #read csv file, index by timestamp, take only March 1st data\n df = pd.read_csv(csv_file, index_col = 'Time', \n parse_dates = 'Time', date_parser=parser).loc[\n '2016-03-01 08:00:00':]\n \n \n \n #find all the resets that occured\n df_restarts = df.loc[df['Status ()']>0].index \n #take all from start to one before the last reset (when we moved all the units)\n df_am_slice = df.loc[:df_restarts[-1],['Solar Radiation (W/m²)']].iloc[:-1]\n #take all from last reset to end\n df_pm_slice = df.loc[df_restarts[-1]:,['Solar Radiation (W/m²)']]\n \n \n #df_pm_slice.loc[:,'Solar Radiation (W/m²)'].plot()\n #df_am_slice.loc[:,'Solar Radiation (W/m²)'].plot()\n \n #add data slices to all_sensors dataframe\n df_pm_all_sensors = pd.concat([df_pm_all_sensors, df_pm_slice], axis=1) \n df_pm_all_sensors = df_pm_all_sensors.rename(columns={'Solar Radiation (W/m²)':csv_file[4:-4]+' pyranometer (mV)'}) \n \n df_am_all_sensors = pd.concat([df_am_all_sensors, df_am_slice], axis=1) \n df_am_all_sensors = df_am_all_sensors.rename(columns={'Solar Radiation (W/m²)':csv_file[4:-4]+' pyranometer (mV)'}) \n \n\ndf_am_all_sensors = df_am_all_sensors.interpolate(method='time')\ndf_pm_all_sensors = df_pm_all_sensors.interpolate(method='time')\n\ndf_am_all_sensors.plot()\nplt.xlabel('Time')\nplt.ylabel('Raw Solar Radiation (mV)')\n\ndf_pm_all_sensors.plot()\n\n\n\ndf_am_all_sensors.to_csv('df_am_all_sensors.csv')\ndf_pm_all_sensors.to_csv('df_pm_all_sensors.csv')"
}
] | 6 |
negipon/soundmeter | https://github.com/negipon/soundmeter | c32e8c8541131940090fee424e91134910d7a9a5 | 18e7c918ba0ad4b8555eeebc91acfd7dfdd1b536 | d719a32f7727d061f94746c0cfab240dcf08219e | refs/heads/master | 2021-04-15T17:53:29.079278 | 2018-03-25T08:46:50 | 2018-03-25T08:46:50 | 126,319,452 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6946454644203186,
"alphanum_fraction": 0.7029666900634766,
"avg_line_length": 29.05434799194336,
"blob_id": "04bfb2baf6b6e7a5fd61c3ec62069ed0232a3bb0",
"content_id": "4982556c7bbb04bad40a17c17d709f30f519dc85",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2976,
"license_type": "permissive",
"max_line_length": 136,
"num_lines": 92,
"path": "/soundmeter.py",
"repo_name": "negipon/soundmeter",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding:utf-8\n\nfrom apiclient import discovery\nfrom datetime import date\nfrom datetime import datetime\nimport oauth2client\nimport httplib2\nimport argparse\nimport subprocess\nimport json\nimport re\nimport time\n\n# 変数定義\nSPREADSHEET_ID = '12EpkVFzSDWzqdPuknacmKCKH9vu4Cn-ZqkCrJswPVdg'\nMAJOR_DIMENSION = 'ROWS'\nTIME_STAMP = int(time.time())\nTODAY = str(datetime.fromtimestamp(TIME_STAMP)).split(' ')[0]\nSHEET_NAME = TODAY\nRANGE_NAME = 'A1'\nSHEET_FLAG = 0\nDURATION = '60'\n \nCLIENT_SECRET_FILE = './client_secret.json'\nCREDENTIAL_FILE = \"./credential.json\"\nAPPLICATION_NAME = 'Soundmeter Appender'\n\n# 認証\nstore = oauth2client.file.Storage(CREDENTIAL_FILE)\ncredentials = store.get()\nif not credentials or credentials.invalid:\n SCOPES = 'https://www.googleapis.com/auth/spreadsheets'\n flow = oauth2client.client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n args = '--auth_ht_name localht --logging_level INFO --noauth_local_webserver'\n flags = argparse.ArgumentParser(parents=[oauth2client.tools.argparser]).parse_args(args.split())\n credentials = oauth2client.tools.run_flow(flow, store, flags)\n \nhttp = credentials.authorize(httplib2.Http())\ndiscoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?' 'version=v4')\nservice = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)\nresource = service.spreadsheets().values()\n\n# シートの名前を取得して、有り無しフラグの変更\nsheet_meta = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()\nfor sheet in sheet_meta.get('sheets', ''):\n # sheet名取得\n SHEET_TAB = sheet.get('properties', {}).get('title', 0)\n if TODAY == SHEET_TAB:\n SHEET_FLAG = 1\n\n# シートがある場合は当日のシートで、ない場合はシート追加\nif SHEET_FLAG == 1:\n SHEET_NAME = SHEET_TAB\nelse:\n BATCH_UPDATE_SPREADSHEET_REQUEST_BODY = {\n 'requests': [\n {\n \"addSheet\": {\n \"properties\": {\n \"title\": TODAY\n }\n }\n }\n ]\n }\n service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=BATCH_UPDATE_SPREADSHEET_REQUEST_BODY).execute()\n\n# soundmeterをコマンド実行\ncmd = '/usr/local/bin/soundmeter -s' + DURATION\noutput = subprocess.getoutput(cmd)\njsonobj = {\"data\": []}\n\n# soundmeter実行で得られた結果をjson変換\nfor line in output.split('\\n'):\n m = line.split('\\r')\n for e in m:\n dB = re.sub('[\\s+]', '', e).replace('Timeout', '')\n if dB != '':\n jsonobj[\"data\"].append([str(datetime.fromtimestamp(TIME_STAMP)),dB])\n TIME_STAMP += 1\n\n# スプレッドシート追加データ形式に生成\nBODY = {\n \"range\": SHEET_NAME + '!' + RANGE_NAME,\n \"majorDimension\": MAJOR_DIMENSION,\n \"values\": jsonobj[\"data\"]\n}\n\n# スプレッドシートに追加\nresource.append(spreadsheetId=SPREADSHEET_ID, range=SHEET_NAME + '!' + RANGE_NAME, valueInputOption='USER_ENTERED', body=BODY).execute()"
},
{
"alpha_fraction": 0.6470588445663452,
"alphanum_fraction": 0.6629570722579956,
"avg_line_length": 10.666666984558105,
"blob_id": "b8b455b46c790d840b19d2bb6b67e27b70347dc7",
"content_id": "6ab758b0bb3ef6ba7eb5b5a6e1fc75dd1de18e2d",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 663,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 54,
"path": "/README.md",
"repo_name": "negipon/soundmeter",
"src_encoding": "UTF-8",
"text": "# SoundMeter\n## on Raspberry pi\n\nRaspbian 2018-3-13\n\n### 参考\nhttps://github.com/shichao-an/soundmeter\n\n\n### USBサウンドカードの優先度を上げる\n\n```\nsudo apt-get update\nsudo apt-get upgrade\n```\n\n#### soundmeter\n```\nsudo apt-get install portaudio19-dev python-dev alsa-utils -y\n```\n\n```\nsudo reboot\n```\n\n### python package install\n```\npip install soundmeter --allow-all-external --allow-unverified pyaudio\n```\n\n```\ngit clone https://github.com/shichao-an/soundmeter.git\n```\n\n```\ncd soundmeter/\n```\n\n### git install\n```\nsudo python setup.py install\n```\n\n```\nsudo apt-get install ffmpeg\n```\n### gain\n```\nalsamixer\n```\n\n```\n$ python3 soundmeter.py\n```"
},
{
"alpha_fraction": 0.6240652799606323,
"alphanum_fraction": 0.633582592010498,
"avg_line_length": 34.878047943115234,
"blob_id": "2e8d30fcca0cd765cb31b1865d17f8fab9113c6b",
"content_id": "337f1033a54f12cb3009de7c4fdfb9836c6b2126",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1471,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 41,
"path": "/soundmeter/settings.py",
"repo_name": "negipon/soundmeter",
"src_encoding": "UTF-8",
"text": "try:\n import configparser\nexcept ImportError:\n import ConfigParser as configparser\nimport os\nimport pyaudio\n\n\nPROG = 'soundmeter'\nUSER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)\nUSER_LOGFILE = os.path.join(USER_DIR, 'log')\nUSER_CONFIG = os.path.join(USER_DIR, 'config')\nUSER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')\n\nconfig = configparser.ConfigParser()\nconfig.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)\nitems = {}\n\nif config.has_section(PROG):\n items = dict(config.items(PROG))\n for name in items:\n try:\n if name in ['frames_per_buffer', 'format', 'channels', 'rate',\n 'input_device_index']:\n items[name] = int(items[name])\n elif name in ['audio_segment_length']:\n items[name] = float(items[name])\n elif name in ['rms_as_trigger_arg']:\n items[name] = bool(items[name])\n else:\n raise Exception('Unknown name \"%s\" in config' % name)\n except ValueError:\n raise Exception('Invalid value to \"%s\" in config' % name)\n\nFRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048\nFORMAT = items.get('format') or pyaudio.paInt16\nCHANNELS = items.get('channels') or 2\nINPUT_DEVICE_INDEX = items.get('input_device_index')\nRATE = items.get('rate') or 44100\nAUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5\nRMS_AS_TRIGGER_ARG = items.get('rms_as_trigger_arg') or False\n"
},
{
"alpha_fraction": 0.5499773025512695,
"alphanum_fraction": 0.5538391470909119,
"avg_line_length": 40.14018630981445,
"blob_id": "f636a2850380293a8db636f27c915d36737a698c",
"content_id": "7ebfd00acd933e871bc608a07f33305ec1244819",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4402,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 107,
"path": "/soundmeter/cli.py",
"repo_name": "negipon/soundmeter",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport argparse\nimport os\nimport sys\nfrom .settings import PROG, USER_LOGFILE, USER_SCRIPT, USER_DIR\nfrom .utils import get_file_path, create_executable\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(usage='%(prog)s [options]',\n prog=PROG)\n parser.add_argument('-c', '--collect', action='store_true',\n help='collect RMS values to determine thresholds')\n seconds_help = 'time in seconds to run the meter (default forever)'\n parser.add_argument('-s', '--seconds', type=float,\n help=seconds_help)\n parser.add_argument('-a', '--action',\n choices=['stop', 'exec-stop', 'exec'],\n help=\"triggered action\")\n trigger_help = 'trigger condition (threshold RMS and number of times)'\n parser.add_argument('-t', '--trigger', nargs='+',\n metavar=('[+|-]THRESHOLD', 'NUM'),\n help=trigger_help)\n parser.add_argument('-e', '--exec', dest='script',\n metavar='SCRIPT', type=argparse.FileType('r'),\n default=USER_SCRIPT,\n help='shell script to execute upon trigger')\n parser.add_argument('-d', '--daemonize', action='store_true',\n help='run the meter in the background')\n parser.add_argument('--log', nargs='?', metavar='LOGFILE',\n type=argparse.FileType('a'),\n const=USER_LOGFILE,\n help='log the meter (default to ~/.soundmeter/log)')\n parser.add_argument('-v', '--verbose', action='store_true',\n help='verbose mode')\n segment_help = 'audio segment length recorded in seconds (defaults to 0.5)'\n parser.add_argument('--segment', metavar='SECONDS', help=segment_help)\n\n # Extra validation of arguments\n args = parser.parse_args()\n if args.collect:\n if args.action or args.trigger:\n msg = ('-c/--collect should not be used with -a/--action '\n 'or -t/--trigger')\n raise parser.error(msg)\n if args.segment:\n try:\n segment = float(args.segment)\n except ValueError:\n msg = '--segment must be an integer or float'\n raise parser.error(msg)\n if segment < 0.05:\n msg = '--segment cannot be smaller than 0.05'\n raise parser.error(msg)\n if args.action:\n if not args.trigger:\n msg = 'must specify -t/--trigger when using -a/--action'\n raise parser.error(msg)\n if args.action == 'stop':\n args.script = None\n if len(args.trigger) == 1:\n args.trigger.append('1')\n elif len(args.trigger) > 2:\n trigger_msg = '-t/--trigger accepts at most two arguments'\n raise parser.error(trigger_msg)\n else:\n trigger_msg = ('the second argument NUM to -t/--trigger must be an'\n ' positive integer')\n if not args.trigger[1].isdigit():\n raise parser.error(trigger_msg)\n if args.trigger[1].isdigit() and int(args.trigger[1]) == 0:\n raise parser.error(trigger_msg)\n\n elif args.trigger:\n msg = 'must specify -a/--action when using -t/--trigger'\n raise parser.error(msg)\n\n elif args.script:\n if '-e' in sys.argv or '--exec' in sys.argv:\n msg = ('must specify -a/--action and -t/--trigger when using '\n '-e/--exec')\n raise parser.error(msg)\n else:\n args.script = None\n return args\n\n\ndef get_meter_kwargs():\n kwargs = dict(parse_args()._get_kwargs())\n # Convert `trigger' into `threshold' and `num'\n if kwargs['trigger'] is not None:\n kwargs['threshold'] = kwargs['trigger'][0]\n kwargs['num'] = int(kwargs['trigger'][1])\n del kwargs['trigger']\n kwargs['script'] = get_file_path(kwargs['script'])\n kwargs['log'] = get_file_path(kwargs['log'])\n kwargs['segment'] = float(kwargs['segment']) \\\n if kwargs['segment'] is not None else None\n return kwargs\n\n\ndef setup_user_dir():\n if not os.path.exists(USER_DIR):\n os.makedirs(USER_DIR)\n if not os.path.exists(USER_SCRIPT):\n content = '!/bin/sh\\n'\n create_executable(USER_SCRIPT, content)\n"
},
{
"alpha_fraction": 0.5349847674369812,
"alphanum_fraction": 0.5372955203056335,
"avg_line_length": 31.295522689819336,
"blob_id": "81e92911397cb2c87ea987ef8f6c250f7c4c4a39",
"content_id": "79a8572673c769bf0295264a5db5a4aad8de08bc",
"detected_licenses": [
"BSD-2-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10819,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 335,
"path": "/soundmeter/meter.py",
"repo_name": "negipon/soundmeter",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport daemon\nimport logging\nimport pyaudio\nimport pydub\nimport wave\nimport signal\nimport six\nimport subprocess\nimport sys\nimport time\nimport warnings\nif six.PY2:\n try:\n from cStringIO import StringIO\n except ImportError:\n from StringIO import StringIO\nelse:\n from io import BytesIO as StringIO\nfrom .settings import (FRAMES_PER_BUFFER, FORMAT, CHANNELS, RATE,\n INPUT_DEVICE_INDEX, AUDIO_SEGMENT_LENGTH,\n RMS_AS_TRIGGER_ARG)\nfrom .cli import get_meter_kwargs, setup_user_dir\nfrom .utils import noalsaerr, coroutine\n\n\n__all__ = ['Meter']\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n_soundmeter = None\n\n\nclass Meter(object):\n\n class StopException(Exception):\n pass\n\n def __init__(self, collect=False, seconds=None, action=None,\n threshold=None, num=None, script=None, log=None,\n verbose=False, segment=None, *args, **kwargs):\n \"\"\"\n :param bool collect: A boolean indicating whether collecting RMS values\n :param float seconds: A float representing number of seconds to run the\n meter (None for forever)\n :param str action: The action type ('stop', 'exec-stop' or 'exec')\n :param str threshold: A string representing threshold and bound type\n (e.g. '+252', '-144')\n :param int num: An integer indicating how many consecutive times the\n threshold is reached before triggering the action\n :param script: File object representing the script to be executed\n :param log: File object representing the log file\n :param bool verbose: A boolean for verbose mode\n :param float segment: A float representing `AUDIO_SEGMENT_LENGTH`\n \"\"\"\n\n global _soundmeter\n _soundmeter = self # Register this meter globally\n self.output = StringIO()\n with noalsaerr():\n self.audio = pyaudio.PyAudio()\n self.stream = self.audio.open(format=FORMAT,\n channels=CHANNELS,\n input_device_index=INPUT_DEVICE_INDEX,\n input=True,\n rate=RATE,\n frames_per_buffer=FRAMES_PER_BUFFER)\n self.collect = collect\n self.seconds = seconds\n self.action = action\n self.threshold = threshold\n self.num = num\n self.script = script\n self.log = log\n self.verbose = verbose\n self.segment = segment\n self.is_running = False\n self._graceful = False # Graceful stop switch\n self._timeout = False\n self._timer = None\n self._data = {}\n self._setup_logging()\n\n @coroutine\n def record(self):\n \"\"\"\n Record PyAudio stream into StringIO output\n\n This coroutine keeps stream open; the stream is closed in stop()\n \"\"\"\n\n while True:\n frames = []\n self.stream.start_stream()\n for i in range(self.num_frames):\n data = self.stream.read(FRAMES_PER_BUFFER)\n frames.append(data)\n self.output.seek(0)\n w = wave.open(self.output, 'wb')\n w.setnchannels(CHANNELS)\n w.setsampwidth(self.audio.get_sample_size(FORMAT))\n w.setframerate(RATE)\n w.writeframes(b''.join(frames))\n w.close()\n yield\n\n def start(self):\n segment = self.segment or AUDIO_SEGMENT_LENGTH\n self.num_frames = int(RATE / FRAMES_PER_BUFFER * segment)\n if self.seconds:\n signal.setitimer(signal.ITIMER_REAL, self.seconds)\n if self.verbose:\n self._timer = time.time()\n if self.collect:\n print('Collecting RMS values...')\n if self.action:\n # Interpret threshold\n self.get_threshold()\n\n try:\n self.is_running = True\n record = self.record()\n while not self._graceful:\n record.send(True) # Record stream `AUDIO_SEGMENT_LENGTH' long\n data = self.output.getvalue()\n segment = pydub.AudioSegment(data)\n rms = segment.rms\n if self.collect:\n self.collect_rms(rms)\n self.meter(rms)\n if self.action:\n if self.is_triggered(rms):\n self.execute(rms)\n self.monitor(rms)\n self.is_running = False\n self.stop()\n\n except self.__class__.StopException:\n self.is_running = False\n self.stop()\n\n def meter(self, rms):\n if not self._graceful:\n sys.stdout.write('\\r%10d ' % rms)\n sys.stdout.flush()\n if self.log:\n self.logging.info(rms)\n\n def graceful(self):\n \"\"\"Graceful stop so that the while loop in start() will stop after the\n current recording cycle\"\"\"\n self._graceful = True\n\n def timeout(self):\n msg = 'Timeout'\n print(msg)\n if self.log:\n self.logging.info(msg)\n self.graceful()\n\n def stop(self):\n \"\"\"Stop the stream and terminate PyAudio\"\"\"\n self.prestop()\n if not self._graceful:\n self._graceful = True\n self.stream.stop_stream()\n self.audio.terminate()\n msg = 'Stopped'\n self.verbose_info(msg, log=False)\n # Log 'Stopped' anyway\n if self.log:\n self.logging.info(msg)\n if self.collect:\n if self._data:\n print('Collected result:')\n print(' min: %10d' % self._data['min'])\n print(' max: %10d' % self._data['max'])\n print(' avg: %10d' % int(self._data['avg']))\n self.poststop()\n\n def get_threshold(self):\n \"\"\"Get and validate raw RMS value from threshold\"\"\"\n\n if self.threshold.startswith('+'):\n if self.threshold[1:].isdigit():\n self._threshold = int(self.threshold[1:])\n self._upper = True\n elif self.threshold.startswith('-'):\n if self.threshold[1:].isdigit():\n self._threshold = int(self.threshold[1:])\n self._upper = False\n else:\n if self.threshold.isdigit():\n self._threshold = int(self.threshold)\n self._upper = True\n if not hasattr(self, '_threshold'):\n raise ValueError('Invalid threshold')\n\n def is_triggered(self, rms):\n if self._upper and rms > self._threshold \\\n or not self._upper and rms < self._threshold:\n if 'triggered' in self._data:\n self._data['triggered'] += 1\n else:\n self._data['triggered'] = 1\n else:\n if 'triggered' in self._data:\n del self._data['triggered']\n t = self._data.get('triggered')\n if isinstance(t, int) and t >= self.num:\n return True\n return False\n\n def execute(self, rms):\n if self.action == 'stop':\n msg = 'Stop Action triggered'\n print(msg)\n if self.log:\n self.logging.info(msg)\n raise self.__class__.StopException('stop')\n\n elif self.action == 'exec-stop':\n msg = 'Exec-Stop Action triggered'\n print(msg)\n if self.log:\n self.logging.info(msg)\n v = 'Executing %s' % self.script\n self.verbose_info(v)\n self.popen(rms)\n raise self.__class__.StopException('exec-stop')\n\n elif self.action == 'exec':\n msg = 'Exec Action triggered'\n print(msg)\n if self.log:\n self.logging.info(msg)\n v = 'Executing %s' % self.script\n self.verbose_info(v)\n self.popen(rms)\n\n def popen(self, rms):\n self.prepopen()\n if self.script:\n try:\n cmd = [self.script]\n \"\"\"If configured as True, rms value is passed\n as an argument for the script\"\"\"\n if (RMS_AS_TRIGGER_ARG):\n cmd.append(str(rms))\n subprocess.Popen(cmd)\n except OSError as e:\n msg = 'Cannot execute the shell script: %s' % e\n print(msg)\n if self.log:\n self.logging.info(msg)\n self.postpopen()\n\n def collect_rms(self, rms):\n \"\"\"Collect and calculate min, max and average RMS values\"\"\"\n if self._data:\n self._data['min'] = min(rms, self._data['min'])\n self._data['max'] = max(rms, self._data['max'])\n self._data['avg'] = float(rms + self._data['avg']) / 2\n else:\n self._data['min'] = rms\n self._data['max'] = rms\n self._data['avg'] = rms\n\n def verbose_info(self, msg, log=True):\n if self.verbose:\n print(msg)\n if self.log and log:\n self.logging.info(msg)\n\n def _setup_logging(self):\n if self.log:\n self.logging = logging.basicConfig(\n filename=self.log, format='%(asctime)s %(message)s',\n level=logging.INFO)\n self.logging = logging.getLogger(__name__)\n\n def monitor(self, rms):\n \"\"\"This function is to be overridden\"\"\"\n pass\n\n def prepopen(self):\n \"\"\"Pre-popen hook\"\"\"\n pass\n\n def postpopen(self):\n \"\"\"Post-popen hook\"\"\"\n pass\n\n def prestop(self):\n \"\"\"Pre-stop hook\"\"\"\n pass\n\n def poststop(self):\n \"\"\"Post-stop hook\"\"\"\n pass\n\n def __repr__(self):\n u = self.action if self.action else 'no-action'\n return '<%s: %s>' % (self.__class__.__name__, u)\n\n\ndef main():\n setup_user_dir()\n kwargs = get_meter_kwargs()\n if kwargs.pop('daemonize'):\n daemon_context = daemon.DaemonContext()\n # python-daemon>=2.1 has initgroups=True by default but it requires\n # root privileges.\n # setting daemon_context.initgroups to False instead of passing\n # arguments to daemon.DaemonContext will not break older versions\n daemon_context.initgroups = False\n with daemon_context:\n m = Meter(**kwargs)\n m.start()\n else:\n m = Meter(**kwargs)\n m.start()\n\n\n# Signal handlers\ndef sigint_handler(signum, frame):\n sys.stdout.write('\\n')\n _soundmeter.graceful()\n\n\ndef sigalrm_handler(signum, frame):\n _soundmeter.timeout()\n\n\n# Register signal handlers\nsignal.signal(signal.SIGINT, sigint_handler)\nsignal.signal(signal.SIGALRM, sigalrm_handler)\n"
}
] | 5 |
morutole/University | https://github.com/morutole/University | 5020a194100d5394d659bd83962a2876b1e5a066 | d6c74e8242e61e0a289f710f3b5e3c34eb037871 | 720656e4899e690086b04dbda96df225e9943f2f | refs/heads/master | 2021-06-14T08:36:39.685467 | 2021-04-25T04:45:07 | 2021-04-25T04:45:07 | 194,790,427 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.50104820728302,
"alphanum_fraction": 0.599580705165863,
"avg_line_length": 13.9375,
"blob_id": "b72ba5bda4fddc2a5bd55bee6715201ca40888c4",
"content_id": "5ec60a68564231980b01fdafdd1503b601f17ed0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 477,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 32,
"path": "/AirplaneDynamics_three/report1/cal1.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\nm = 7500\nS = 27.9\ng = 9.8\nrho = 0.736423\nU = 180\nuhen = m*g*2/(rho*(U**2)*S)\nprint(uhen)\n\nC_lalpha = 4.30\nC_d0 = 0.0548\nK = 3.02\n\ndif = 1e-7\n\nalpha = 0\nwhile True:\n alpha += dif\n sahen = C_lalpha*alpha+C_d0*np.tan(alpha)+K*alpha**2*np.tan(alpha)\n if(sahen > uhen):\n break\n\nprint(alpha)\nprint(alpha/np.pi*180)\nprint(sahen)\n\nT = (m*g-rho*U**2*S*C_lalpha*alpha/2)/np.sin(alpha)\nprint(T)\n\nT= rho*U**2*S/2*(C_d0+K*alpha**2)/np.cos(alpha)\nprint(T)"
},
{
"alpha_fraction": 0.4942440390586853,
"alphanum_fraction": 0.5151573419570923,
"avg_line_length": 30.39759063720703,
"blob_id": "73e9e1934da83e3bc159e52d863213442fc8d1ad",
"content_id": "17d3460ef38ee86c070b56ddb40dae3079f6ae43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5490,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 166,
"path": "/PhenomenonMathmaticalModelTheory/simu2.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import heapq\nimport queue\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass MM1:\n mu = 1.0 # サービス確率\n Tstart = 1000000 # 記録開始タイムステップ\n Tend = 10000000 # 記録終了タイムステップ\n\n come = True\n go = False\n\n experiment_rho = []\n experiment_Lambds = [0.05 * i for i in range(1, 22)]\n experiment_Ns = []\n experiment_Ws = []\n\n def __init__(self):\n self.experiment_rho.clear()\n self.experiment_Lambds = [0.05 * i for i in range(1, 22)]\n self.experiment_Ns.clear()\n self.experiment_Ws.clear()\n\n def simulate(self):\n self.__init__()\n for Lambda in self.experiment_Lambds:\n n = 0 # 滞在人数\n nSum = 0 # 滞在人数の累積\n wSum = 0 # 来た人数が待った累計\n allmembers = 0 # 来た人数の累計\n t = 0\n t_before = -1\n\n come_count = 0\n go_count = 0\n\n pq = [] # イベント行列\n heapq.heappush(pq, (0, self.come))\n come_count += 1\n\n que = queue.Queue() # 待ち行列に入っている人間\n\n while True:\n top = heapq.heappop(pq)\n t = top[0]\n flag = top[1]\n\n # Nsについて記録\n if t >= self.Tstart:\n # 終わりの時間が来ていたら\n if t > self.Tend:\n nSum += n*(self.Tend - t_before)\n break\n else:\n # before がまだスタート前だったら\n if t_before < self.Tstart:\n nSum += n*(t - self.Tstart)\n else:\n nSum += n*(t - t_before)\n\n if flag == self.come:\n n += 1\n come_count -= 1\n que.put(t)\n # Wsについて記録\n if t >= self.Tstart and t < self.Tend:\n allmembers += 1\n else:\n n -= 1\n go_count -= 1\n come_time = que.get()\n # Ws について記録\n if t >= self.Tstart and t < self.Tend:\n wSum += t - come_time\n\n t_before = t\n\n # 次のイベントを計算\n if come_count == 0:\n heapq.heappush(pq, (t + self.calculate_next_come(Lambda), self.come))\n come_count += 1\n if n > 0 and go_count == 0:\n heapq.heappush(pq, (t + self.calculate_next_go(self.mu), self.go))\n go_count += 1\n\n rho = Lambda/self.mu\n self.experiment_rho.append(rho)\n self.experiment_Ns.append(nSum/(self.Tend - self.Tstart))\n self.experiment_Ws.append(wSum/allmembers)\n \n return self.experiment_Lambds, self.experiment_rho, self.experiment_Ns, self.experiment_Ws\n \n def calculate_next_come(self, Lambda):\n return np.random.exponential(1.0/Lambda)\n \n def calculate_next_go(self, mu):\n return np.random.exponential(1.0/mu)\n\n def calculate_theoritical_result(self):\n Lambda = np.linspace(0, 0.99, 9900)\n rho = Lambda/self.mu\n Ns = rho/(1 - rho)\n return rho, Ns\n \n def plot(self, ax):\n experiment_Lambds, experiment_rho, experiment_Ns, experiment_Ws = self.simulate()\n theoritical_rho, theoritical_Ns = self.calculate_theoritical_result()\n ax.plot(theoritical_rho, theoritical_Ns, c = \"Black\")\n ax.scatter(experiment_rho, experiment_Ns, c = \"Green\", marker=\"s\", label = \"S.D. = 1\")\n\nclass MG1(MM1):\n come_loc = 1.0\n come_scale = 0.0\n\n def calculate_next_go(self, Lambda):\n return np.random.normal(self.come_loc, self.come_scale)\n \n def calculate_theoritical_result(self):\n Lambda = np.linspace(0, 0.99, 9900)\n rho = Lambda/self.mu\n Cs = self.come_scale/self.come_loc\n Wq = (1 + Cs**2)/2*rho/(1 - rho)*self.come_loc # ポラチェック・ヒンチンの公式\n Ns = (Wq + self.come_loc)*Lambda\n return rho, Ns\n \n def plot(self, ax):\n experiment_Lambds, experiment_rho, experiment_Ns, experiment_Ws = self.simulate()\n theoritical_rho, theoritical_Ns = self.calculate_theoritical_result()\n ax.plot(theoritical_rho, theoritical_Ns, c = \"Black\")\n ax.scatter(experiment_rho, experiment_Ns, c = \"Blue\", marker=\"x\", label = \"S.D. = 0\")\n\nclass MG3(MG1):\n come_scale = 3.0\n\n def calculate_next_go(self, Lambda):\n theta = self.come_scale**2/self.come_loc\n k = self.come_loc**2/self.come_scale**2\n\n return np.random.gamma(k, theta)\n \n def plot(self, ax):\n experiment_Lambds, experiment_rho, experiment_Ns, experiment_Ws = self.simulate()\n theoritical_rho, theoritical_Ns = self.calculate_theoritical_result()\n ax.plot(theoritical_rho, theoritical_Ns, c = \"Black\")\n ax.scatter(experiment_rho, experiment_Ns, c = \"Red\", marker=\"o\", label = \"S.D. = 3\")\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.ylim(0, 6)\n\nmm1 = MM1()\nmm1.plot(ax)\n\nmg1 = MG1()\nmg1.plot(ax)\n\nmg3 = MG3()\nmg3.plot(ax)\n\nplt.legend(loc = \"upper left\")\nplt.xlabel(r\"$\\rho$\")\nplt.ylabel(r\"$N_s$\")\nplt.savefig(\"result2_2.png\", bbox_inches='tight')\nplt.show()\n"
},
{
"alpha_fraction": 0.4754142761230469,
"alphanum_fraction": 0.49741917848587036,
"avg_line_length": 29.941177368164062,
"blob_id": "1fbda32600e20658969d60b96551644218d4fc63",
"content_id": "f48bad1c8d3aeebbc53fd54bcd0b71863aee24fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3889,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 119,
"path": "/info_system_3/51.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nimport random\n\n#やりたいこと、まず適当にテストとtrainで分ける、\n#次に全部でAICを試す。\nyear = []\nprice = []\n\nwith open(\"mazdas.txt\") as f:\n lines = f.readlines()\n for line in lines:\n line = line.split()\n if len(line) == 2:\n year.append(line[0])\n price.append(line[1])\n\nyear.pop(0)\nprice.pop(0)\n\nyear = [float(each_year) for each_year in year]\nprice = [float(each_price) for each_price in price]\n\nn = len(year)\nyear = array(year)\nprice = array(price)\n\nm_max = 10\n\nflag = False\n\ndef only_test_train():\n test_size = int(n*0.3)\n train_size = n - test_size\n test_times = 100000\n Q = zeros(m_max-1)\n for i in range(3,m_max): \n m = i #何次の近似をするか選択\n temp_Q = 0 #Qに入れる前のぞそれぞれのQの計算場所\n for j in range(test_times): #randomで選ぶのでtest_times回試行\n random_index_list = list(range(n)) #testとtrainをそれぞれ選ぶ\n random_test_index_list = random.sample(random_index_list,test_size)\n train_year = []\n train_price = []\n test_year = []\n test_price = []\n for k in range(n):\n if k in random_test_index_list:\n test_year.append(year[k])\n test_price.append(price[k])\n else:\n train_year.append(year[k])\n train_price.append(price[k])\n test_year = array(test_year)\n test_price = array(test_price)\n train_year = array(train_year)\n train_price = array(train_price)\n \n X_m = empty((train_size,m+1))\n for k in range(m+1):\n X_m[:, k] = train_year**k\n y = train_price\n alp = la.solve(dot(X_m.T,X_m), dot(X_m.T,y))\n price_from_test_year = zeros_like(test_year)\n for k in range(len(alp)):\n price_from_test_year += alp[k]*test_year**k\n temp_Q += sum((test_price-price_from_test_year)**2)/test_size #まずtestの最小二乗和を入れる。\n\n if flag == False:\n plt.scatter(train_year,train_price,label = \"train\")\n plt.scatter(test_year,test_price,label = \"test\")\n x_v = arange(65,95,1e-2)\n y_v = zeros_like(x_v)\n for k in range(len(alp)):\n y_v += alp[k]*x_v**k\n plt.plot(x_v,y_v)\n plt.xlabel(\"year\")\n plt.ylabel(\"price\")\n plt.ylim(-5000,45000)\n plt.legend(loc = \"lower right\")\n plt.savefig(\"51_ot_3.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()\n return\n\n temp_Q /= test_times #test_timesで平均を取る。\n Q[i-1] = temp_Q #それぞれ入れていく。\n print(Q)\n\ndef only_AIC():\n AIC = zeros(m_max-1)\n for i in range(1,m_max):\n m = i\n X_m = empty((n,m+1))\n for j in range(m+1):\n X_m[:,j] = year**j\n y = price\n alp = la.solve(dot(X_m.T,X_m), dot(X_m.T,y))\n price_from_year = zeros_like(year)\n x_v = arange(65,95,1e-2)\n y_v = zeros_like(x_v)\n for k in range(len(alp)):\n y_v += alp[k]*x_v**k\n price_from_year += alp[k]*year**k\n if i == 8:\n plt.scatter(year,price)\n plt.plot(x_v,y_v)\n plt.ylim(-5000,45000)\n plt.xlabel(\"year\")\n plt.ylabel(\"price\")\n plt.ylim(-5000,45000)\n plt.savefig(\"51_oa_8.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()\n\n Q = sum((price - price_from_year)**2)\n AIC[i-1] = n*log(Q/n) + 2*(len(alp))\n print(AIC)\n\nonly_AIC()"
},
{
"alpha_fraction": 0.5845023393630981,
"alphanum_fraction": 0.6085504293441772,
"avg_line_length": 25.75,
"blob_id": "184b4fcbbb7cf4d095e5a4fa720ca862eafe81b9",
"content_id": "91f7f8b711e4c1de6e19ec3f331a2e25b1450a64",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1497,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 56,
"path": "/info_system_3/54.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nimport csv\n\ntemperature = []\nwith open(\"TokyoTemperatureSince2001.csv\") as f:\n reader = csv.reader(f)\n for row in reader:\n temperature.append(float(row[1]))\n\ntemperature = array(temperature)\nn = len(temperature)\ntest_n = int(n*0.7)\nmonth = arange(n)\n\nmodel_number = 20\n\nresults = empty(model_number)\n\nfor m in range(1,model_number+1):\n x = empty((test_n-m,m))\n y = empty(test_n-m)\n for i in range(test_n-m):\n y[i] = temperature[m+1+i-1]\n for j in range(m):\n x[i][j] = temperature[m+i-j-1]\n \n alpha = la.solve(dot(x.T,x),dot(x.T,y))\n temp = zeros_like(temperature)\n for i in range(m):\n temp[i] = temperature[i]\n for i in range(m,n):\n for j in range(len(alpha)):\n temp[i] += alpha[j]*temperature[i-j-1]\n if m == 12:\n print(alpha)\n plt.scatter(month,temperature)\n plt.plot(month,temp,color = \"C1\")\n plt.scatter(month,temp,color = \"C1\",marker = \"x\")\n plt.xlabel(\"month from begin\")\n plt.ylabel(\"temperature\")\n plt.savefig(\"540.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()\n \n\n results[m-1] = (n-test_n)*log(sum(((temp-temperature)**2)[test_n:])/(n-test_n)) + 2*m\n\nplt.scatter(range(1,model_number+1),results)\nplt.xlabel(\"model degree\")\nplt.ylabel(\"AIC\")\nplt.savefig(\"541.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\nprint(results)\nprint(n)\nprint(test_n)"
},
{
"alpha_fraction": 0.7910447716712952,
"alphanum_fraction": 0.7910447716712952,
"avg_line_length": 32.5,
"blob_id": "3267d4931b416fab426aff925d1da15795620bd6",
"content_id": "5aac7ab2caf47741d71c7fb96a75badcb88db675",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 2,
"path": "/Minesweeper/README.md",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "# Minesweeper\nMake Minesweeper by both C++ and Python for practice\n"
},
{
"alpha_fraction": 0.5252918004989624,
"alphanum_fraction": 0.5836575627326965,
"avg_line_length": 19.579999923706055,
"blob_id": "4cca6cf776389ec2f54e25cd6de201bfa2f22bd8",
"content_id": "e069a4e0d3cb4b1fb17c43b839b929f34d3135f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1028,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 50,
"path": "/info_system_3/44.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from scipy.stats import poisson\nimport matplotlib.pyplot as plt\nfrom numpy import *\n\ndef problem1():\n mu = 30/1000\n\n number = arange(0,11,1)\n\n poisson_result = poisson.pmf(number,mu)\n\n plt.plot(number,poisson_result)\n plt.show()\n\n poisson_sum = empty_like(poisson_result)\n poisson_sum[0] = poisson_result[0]\n for i in range(1,len(poisson_sum)):\n poisson_sum[i] = poisson_sum[i-1] + poisson_result[i]\n\n plt.plot(number,poisson_sum)\n plt.show()\n\n print(poisson_result[0])\n\ndef l_func(mu):\n p1 = mu*exp(-mu)\n p2 = mu**2*exp(-mu)/2\n p3 = mu**3*exp(-mu)/6\n return pow(p1,5)*pow(p2,4)*p3\n\ndef ll_func(mu):\n p1 = mu*exp(-mu)\n p2 = mu**2*exp(-mu)/2\n p3 = mu**3*exp(-mu)/6\n p1 = log(p1)\n p2 = log(p2)\n p3 = log(p3)\n return 5*p1 + 4*p2 + p3\n\ndef problem3():\n diff = 1e-4\n mu = arange(0,3,diff)\n plt.plot(mu,l_func(mu))\n plt.scatter(1.6,l_func(1.6))\n plt.show()\n plt.plot(mu,ll_func(mu))\n plt.scatter(1.6,ll_func(1.6))\n plt.show()\n\nproblem3()"
},
{
"alpha_fraction": 0.37213996052742004,
"alphanum_fraction": 0.4784656763076782,
"avg_line_length": 23.78333282470703,
"blob_id": "bc79fe4075ad8e43951b669bf639c97b6859dff0",
"content_id": "8ef32d75606393ece2681c86981d1545576ae0c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1488,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 60,
"path": "/blasius_shooting_method_bisection/blasius_shooting_method_bisection.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "def f(a,b,c):\n return b\ndef g(a,b,c):\n return c\ndef h(a,b,c):\n return (-1)*a*c/2\n\nsup = 1\ninf = 0\n\nwhile True:\n x = [0]\n y = [0]\n z = [(sup+inf)/2]\n\n delta_t = 0.0001\n cal_number = 100000\n\n for i in range(1,cal_number):\n k0 = delta_t*f(x[-1],y[-1],z[-1])\n l0 = delta_t*g(x[-1],y[-1],z[-1])\n m0 = delta_t*h(x[-1],y[-1],z[-1])\n k1 = delta_t*f(x[-1]+k0/2,y[-1]+l0/2,z[-1]+m0/2)\n l1 = delta_t*g(x[-1]+k0/2,y[-1]+l0/2,z[-1]+m0/2)\n m1 = delta_t*h(x[-1]+k0/2,y[-1]+l0/2,z[-1]+m0/2)\n k2 = delta_t*f(x[-1]+k1/2,y[-1]+l1/2,z[-1]+m1/2)\n l2 = delta_t*g(x[-1]+k1/2,y[-1]+l1/2,z[-1]+m1/2)\n m2 = delta_t*h(x[-1]+k1/2,y[-1]+l1/2,z[-1]+m1/2)\n k3 = delta_t*f(x[-1]+k2,y[-1]+l2,z[-1]+m2)\n l3 = delta_t*g(x[-1]+k2,y[-1]+l2,z[-1]+m2)\n m3 = delta_t*h(x[-1]+k2,y[-1]+l2,z[-1]+m2)\n x.append(x[-1]+(k0+2*k1+2*k2+k3)/6)\n y.append(y[-1]+(l0+2*l1+2*l2+l3)/6)\n z.append(z[-1]+(m0+2*m1+2*m2+m3)/6)\n \n if 0.999 <= y[cal_number-1] and y[cal_number-1] <= 1.001:\n break\n elif y[cal_number-1] > 1:\n sup = (sup+inf)/2\n elif y[cal_number-1] < 1:\n inf = (sup+inf)/2\n\nprint(\"f''(0)\")\nprint((sup+inf)/2)\nprint(\"f'(10)\")\nprint(y[cal_number-1])\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nt = []\nfor i in range(0,cal_number):\n t.append(i*delta_t)\np = np.array(t)\nq = np.array(y)\nplt.plot(q,p)\nplt.xlabel(\"f'(η)\")\nplt.ylabel(\"η\")\nplt.show()"
},
{
"alpha_fraction": 0.5117886662483215,
"alphanum_fraction": 0.5164864659309387,
"avg_line_length": 34.48113250732422,
"blob_id": "e229ffacdf4a37c410397b5d1cd1d7a62923de20",
"content_id": "13ba9ecd7c375c5e31adad372da3fc3cc2e2bc6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11366,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 318,
"path": "/Minesweeper/cpp/Minesweeper.cpp",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint input_linenumber();\nint input_columnnumber();\nint input_bombnumber();\n\nint know_digit(int); //桁を知る。\n\nvoid display_board(vector<vector<char>> &board, int linenumber, int columnnumber);\n\nvoid initialize_board(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int linenumber, int columnnumber, int bombnumber);\nvoid count_around_bomb(vector<vector<int>> &data_board_vector, int linenumber, int columnnumber);\n\nvoid find_blank_space(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int line_dig_point, int column_dig_point);\n\nbool judge_game_clear(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int linenumber, int columnnumber);\n\nint main()\n{\n const int linenumber = input_linenumber();\n const int columnnumber = input_columnnumber();\n const int bombnumber = input_bombnumber();\n\n int spare_bomb_number = bombnumber;\n \n vector<vector<char>> display_board_vector(linenumber,vector<char>(columnnumber,'o'));\n //旗はF、空は あるのは数字、まだ掘ってないのはoにする。\n vector<vector<int>> data_board_vector(linenumber,vector<int>(columnnumber,0));\n\n display_board(display_board_vector, linenumber, columnnumber);\n initialize_board(display_board_vector, data_board_vector, linenumber, columnnumber, bombnumber);\n\n char command;\n int line_dig_point,column_dig_point;\n while(true){\n if(judge_game_clear(display_board_vector, data_board_vector, linenumber,columnnumber)){\n display_board(display_board_vector, linenumber, columnnumber);\n cout << \"Conguratulation! Clear!\" << endl;\n break;\n }\n display_board(display_board_vector, linenumber, columnnumber);\n cout << \"spare mine number:\";\n cout << spare_bomb_number << endl;\n while(true){\n cout << \"d:dig, f:bulid a flag, c:cancel a flag\" << endl;\n cout << \"input command\" << endl;\n cin >> command;\n if(command == 'd'){\n cout << \"where to dig\" << endl;\n break;\n }else if(command == 'f'){\n cout << \"where to build a flag\" << endl;\n break;\n }else if(command == 'c'){\n cout << \"which flag cancel\" << endl;\n }else{\n cout << \"input is incorrect\" << endl;\n }\n }\n while(true){\n line_dig_point = input_linenumber();\n --line_dig_point;\n column_dig_point = input_columnnumber();\n --column_dig_point;\n try{\n if(display_board_vector.at(line_dig_point).at(column_dig_point)){\n break;\n }\n }catch(exception &e){\n cout << \"input is incorrect\" << endl;\n continue;\n }\n }\n if(command == 'd'){\n if(display_board_vector.at(line_dig_point).at(column_dig_point) == 'F'){\n cout << \"there is a flag!\" << endl;\n continue;\n }else if(display_board_vector.at(line_dig_point).at(column_dig_point) != 'o'){\n cout << \"there can't dig\" << endl;\n continue;\n }else if(data_board_vector.at(line_dig_point).at(column_dig_point) == -1){\n display_board_vector.at(line_dig_point).at(column_dig_point) = 'x';\n display_board(display_board_vector, linenumber, columnnumber);\n cout << \"there is a mine...\" << endl;\n cout << \"Game Over\" << endl;\n break;\n }else if(data_board_vector.at(line_dig_point).at(column_dig_point) == 0){\n find_blank_space(display_board_vector, data_board_vector, line_dig_point, column_dig_point);\n }else{\n display_board_vector.at(line_dig_point).at(column_dig_point) = '0' + data_board_vector.at(line_dig_point).at(column_dig_point);\n }\n }else if(command == 'f'){\n if(display_board_vector.at(line_dig_point).at(column_dig_point) != 'o'){\n cout << \"there can't build a flag\" << endl;\n continue;\n }else{\n display_board_vector.at(line_dig_point).at(column_dig_point) = 'F';\n --spare_bomb_number;\n }\n }else if(command == 'c'){\n if(display_board_vector.at(line_dig_point).at(column_dig_point) != 'F'){\n cout << \"there isn't a flag\" << endl;\n continue;\n }else{\n display_board_vector.at(line_dig_point).at(column_dig_point) = 'o';\n ++spare_bomb_number;\n }\n }else{\n cout << \"input is incorrect\" << endl;\n continue;\n }\n }\n return 0;\n}\n\nint input_linenumber()\n{\n int linenumber;\n cout << \"input number of line\" << endl;\n cin >> linenumber;\n return linenumber;\n}\n\nint input_columnnumber()\n{\n int columnnumber;\n cout << \"input number of column\" << endl;\n cin >> columnnumber;\n return columnnumber;\n}\n\nint input_bombnumber()\n{\n int bombnumber;\n cout << \"input number of mine\" << endl;\n cin >> bombnumber;\n return bombnumber;\n}\n\nvoid display_board(vector<vector<char>> &board, int linenumber, int columnnumber)\n{\n const int line_digit = know_digit(linenumber);\n const int column_digit = know_digit(columnnumber);\n int line,column,i;\n for(line = 0;line <= linenumber;++line){\n if(line == 0){\n for(i = 0;i < line_digit;++i){\n cout << ' ';\n }\n for(column = 1;column <= columnnumber;++column){\n cout << column;\n for(i = 0;i < column_digit - know_digit(column);++i){\n cout << ' ';\n }\n }\n cout << endl;\n }else{\n cout << line;\n for(i = 0;i < line_digit - know_digit(line);++i){\n cout << ' ';\n }\n for(column = 1;column <= columnnumber;++column){\n cout << board.at(line-1).at(column-1);\n for(i = 0;i < column_digit - 1;++i){\n cout << ' ';\n }\n }\n cout << endl;\n }\n }\n}\n\nvoid initialize_board(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int linenumber, int columnnumber, int bombnumber)\n{\n int line_dig_point,column_dig_point;\n cout << \"input first dig point\" << endl;\n while(true){\n line_dig_point = input_linenumber();\n --line_dig_point;\n column_dig_point = input_columnnumber();\n --column_dig_point;\n try{\n if(display_board_vector.at(line_dig_point).at(column_dig_point)){\n break;\n }\n }catch(exception &e){\n cout << \"input is incorrect\" << endl;\n continue;\n }\n }\n display_board_vector.at(line_dig_point).at(column_dig_point) = ' ';\n //爆弾を-1で表すことにする。\n vector<int> decide_where_is_bomb;\n int i,j;\n vector<int> around_the_first_dig_point;\n for(i = -1;i <=1;++i){\n for(j = -1;j <= 1;++j){\n try{\n if(data_board_vector.at(line_dig_point+i).at(column_dig_point+j) == 0){\n around_the_first_dig_point.push_back((line_dig_point+i)*columnnumber+column_dig_point+j);\n }\n }catch(exception& e){\n continue;\n }\n }\n }\n for(i = 0;i <= linenumber*columnnumber-1;++i){\n if(binary_search(around_the_first_dig_point.begin(),around_the_first_dig_point.end(),i)){\n continue;\n }else{\n decide_where_is_bomb.push_back(i);\n }\n }\n random_device seed_gen;\n mt19937 engine(seed_gen());\n shuffle(decide_where_is_bomb.begin(), decide_where_is_bomb.end(), engine);\n for(i = 0;i < bombnumber;++i){\n data_board_vector.at(decide_where_is_bomb.at(i)/columnnumber).at(decide_where_is_bomb.at(i)%columnnumber) = -1;\n }\n count_around_bomb(data_board_vector, linenumber, columnnumber);\n find_blank_space(display_board_vector, data_board_vector, line_dig_point, column_dig_point);\n}\n\nvoid count_around_bomb(vector<vector<int>> &data_board_vector, int linenumber, int columnnumber)\n{\n int line,column;\n int i,j;\n for(line = 0;line < linenumber;++line){\n for(column = 0;column < columnnumber;++column){\n if(data_board_vector.at(line).at(column) == -1){\n continue;\n }else{\n for(i = -1;i <=1;++i){\n for(j = -1;j <= 1;++j){\n if(i == 0 && j == 0){\n continue;\n }else{\n try{\n if(data_board_vector.at(line+i).at(column+j) == -1){\n ++data_board_vector.at(line).at(column);\n }\n }catch(exception& e){\n continue;\n }\n }\n }\n }\n } \n }\n }\n}\n\nvoid find_blank_space(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int line_dig_point, int column_dig_point)\n{\n queue<pair<int,int>> find_blank;\n int line,column;\n find_blank.emplace(line_dig_point,column_dig_point);\n int i,j;\n while(!find_blank.empty()){\n line = find_blank.front().first;\n column = find_blank.front().second;\n for(i = -1;i <= 1;++i){\n for(j = -1;j <= 1;++j){\n try{\n if(display_board_vector.at(line+i).at(column+j) == 'o'){\n if(data_board_vector.at(line+i).at(column+j) == 0){\n display_board_vector.at(line+i).at(column+j) = ' ';\n find_blank.emplace(line+i,column+j);\n }else{\n display_board_vector.at(line+i).at(column+j) = '0' + data_board_vector.at(line+i).at(column+j);\n }\n }else{\n continue;\n }\n }catch(exception &e){\n continue;\n }\n } \n }\n find_blank.pop();\n }\n}\n\nbool judge_game_clear(vector<vector<char>> &display_board_vector, vector<vector<int>> &data_board_vector, int linenumber, int columnnumber)\n{\n int line,column;\n for(line = 0;line < linenumber;++line){\n for(column = 0;column < columnnumber;++column){\n if(data_board_vector.at(line).at(column) != -1){\n if(display_board_vector.at(line).at(column) == 'o' || display_board_vector.at(line).at(column) == 'F'){\n return false;\n }else{\n continue;\n }\n }else{\n continue;\n }\n }\n }\n return true;\n}\n\nint know_digit(int number)\n{\n int digit = 0;\n while(number){\n number /= 10;\n ++digit;\n }\n return digit;\n}"
},
{
"alpha_fraction": 0.45431894063949585,
"alphanum_fraction": 0.49127906560897827,
"avg_line_length": 34.41543960571289,
"blob_id": "3de7b85efe443b065eb995a6e1906b48606b4507",
"content_id": "b370e008b8e7c2bdff7ac96ba134e50ef57cf809",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9976,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 272,
"path": "/AeroDynamics_C/dansa.cpp",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <utility>\n#include <fstream>\n#include <iomanip>\n#include <chrono>\nusing namespace std;\n\ntypedef long long ll;\n\nint main()\n{\n int n;\n int i,j;\n\n double rho = 1.225;\n double T = 293.0;\n double mu = 1.458e-6*pow(T,1.5)/(T+110.4);\n double widthx = 0.5; //単位m\n double u0 = 20.0;\n double Re = rho*u0*widthx/mu;\n double blt = widthx*5.3/sqrt(Re);\n\n cout << \"mu \" << mu << endl;\n cout << \"Re \" << Re << endl;\n \n int nx = 50000;\n int ny = 250;\n double dx = widthx/(double)nx;\n double y_max = 2.0*blt;\n double dy = y_max/(double)ny;\n cout << \"y_max \" << y_max << endl;\n double dpdx = 0.0; //圧力勾配\n\n vector<double> y(ny+1);\n for(i = 0;i <= ny;++i){\n y.at(i) = dy*(double)i;\n }\n\n vector<double> x(nx+1);\n for(i = 0;i <= nx;++i){\n x.at(i) = dx*(double)i;\n }\n\n vector<vector<double>> u(ny+1,vector<double>(nx+1,0)); //格子\n vector<vector<double>> v(ny+1,vector<double>(nx+1,0)); //格子\n for(i = 0;i <= ny;++i){\n if(i < ny/2){\n u.at(i).at(0) = 0; //はじめの一列初期化\n }else{\n u.at(i).at(0) = u0; //はじめの一列初期化\n }\n v.at(i).at(0) = 0.0; //はじめの一列初期化\n }\n double dudy1;\n double dudy2;\n double dudx;\n double dudx1;\n double dudx2;\n std::chrono::system_clock::time_point start, end; // 型は auto で可\n start = std::chrono::system_clock::now(); // 計測開始時間\n cout << \"for calculate start\" << endl;\n\n for(i = 0;i < nx/2;++i){\n for(j = ny/2;j < ny;++j){\n dudy1 = (u.at(j+1).at(i) - u.at(j-1).at(i))/(2.0*dy);\n dudy2 = (u.at(j+1).at(i) - 2*u.at(j).at(i) + u.at(j-1).at(i))/(dy*dy);\n dudx = (dudy2*mu/rho - v.at(j).at(i)*dudy1 - dpdx/rho)/u.at(j).at(i); //まぁそうか...。\n u.at(j).at(i+1) = u.at(j).at(i) + dx*dudx;\n }\n u.at(ny/2-1).at(i+1) = 0.0; \n u.at(ny).at(i+1) = u0; //境界条件\n v.at(ny/2-1).at(i+1) = 0;\n for(j = ny/2;j < ny;++j){ //端含まず\n dudx1 = (u.at(j).at(i+1) - u.at(j).at(i))/dx;\n dudx2 = (u.at(j+1).at(i+1) - u.at(j+1).at(i))/dx; //一つ上を取る?y_maxでのvは?不要らしい。\n v.at(j).at(i+1) = v.at(j-1).at(i+1) - (dudx1+dudx2)*dy/2.0; \n }\n v.at(j).at(i+1) = v.at(j-1).at(i+1); //最終行のみ\n if(i%1000 == 0){\n cout << i << endl;\n }\n }\n for(i = nx/2;i < nx;++i){\n for(j = 1;j < ny;++j){\n dudy1 = (u.at(j+1).at(i) - u.at(j-1).at(i))/(2.0*dy);\n dudy2 = (u.at(j+1).at(i) - 2*u.at(j).at(i) + u.at(j-1).at(i))/(dy*dy);\n if(u.at(j).at(i) != 0){\n dudx = (dudy2*mu/rho - v.at(j).at(i)*dudy1 - dpdx/rho)/u.at(j).at(i); //まぁそうか...。\n }else{\n dudx = 0;\n }\n u.at(j).at(i+1) = u.at(j).at(i) + dx*dudx;\n }\n\n u.at(0).at(i+1) = 0.0; \n u.at(ny).at(i+1) = u0; //境界条件\n v.at(0).at(i+1) = 0;\n\n for(j = 1;j < ny;++j){ //端含まず\n dudx1 = (u.at(j).at(i+1) - u.at(j).at(i))/dx;\n dudx2 = (u.at(j+1).at(i+1) - u.at(j+1).at(i))/dx; //一つ上を取る?y_maxでのvは?不要らしい。\n v.at(j).at(i+1) = v.at(j-1).at(i+1) - (dudx1+dudx2)*dy/2.0; \n }\n v.at(j).at(i+1) = v.at(j-1).at(i+1); //最終行のみ\n if(i%1000 == 0){\n cout << i << endl;\n } \n }\n\n end = std::chrono::system_clock::now(); // 計測終了時間\n double elapsed = std::chrono::duration_cast<std::chrono::seconds>(end-start).count(); //処理に要した時間をミリ秒に変換\n cout << \"for caluculate end\" << endl;\n cout << elapsed << endl;\n\n cout << \"thickness calculate start\" << endl;\n start = std::chrono::system_clock::now();\n /*\n vector<double> boundary_layer_thickness(nx+1);\n vector<double> displacement_thickness(nx+1);\n vector<double> momentum_thickness(nx+1);\n vector<double> energy_thickness(nx+1);\n vector<double> tauw(nx+1);\n vector<double> Cf(nx+1);\n \n for(i = 0;i <= nx;++i){\n for(j = 0;j <= ny;++j){\n if(u.at(j).at(i) >= u0*0.995){\n double temp = j;\n boundary_layer_thickness.at(i) = dy*temp;\n break;\n }\n }\n }\n cout << \"boundary end\" << endl;\n double temp1;\n double temp2;\n\n for(i = 0;i <= nx;++i){\n double sum = 0;\n for(j = 0;j < ny;++j){\n temp1 = 1.0-u.at(j).at(i)/u0; //下辺の長さ\n temp2 = 1.0-u.at(j+1).at(i)/u0; //上辺の長さ\n sum += (temp1+temp2)*dy/2.0;\n if(u.at(j+1).at(i) == u0){\n break;\n }\n }\n displacement_thickness.at(i) = sum;\n }\n cout << \"displacement end\" << endl;\n\n for(i = 0;i <= nx;++i){\n double sum = 0;\n for(j = 0;j < ny;++j){\n temp1 = u.at(j).at(i)/u0*(1.0-u.at(j).at(i)/u0); //下辺の長さ\n temp2 = u.at(j+1).at(i)/u0*(1.0-u.at(j+1).at(i)/u0); //上辺の長さ\n sum += (temp1+temp2)*dy/2.0;\n if(u.at(j+1).at(i) == u0){\n break;\n }\n }\n momentum_thickness.at(i) = sum;\n }\n cout << \"momentum end\" << endl;\n\n for(i = 0;i <= nx;++i){\n double sum = 0;\n for(j = 0;j < ny;++j){\n temp1 = u.at(j).at(i)/u0*(1.0-(u.at(j).at(i)/u0)*(u.at(j).at(i)/u0)); //下辺の長さ\n temp2 = u.at(j+1).at(i)/u0*(1.0-(u.at(j).at(i)/u0)*(u.at(j).at(i)/u0)); //上辺の長さ\n sum += (temp1+temp2)*dy/2.0;\n if(u.at(j+1).at(i) == u0){\n break;\n }\n }\n energy_thickness.at(i) = sum;\n }\n cout << \"energy_thickness end\" << endl;\n\n for(i = 0;i <= nx;++i){\n tauw.at(i) = mu*(u.at(1).at(i)-u.at(0).at(i))/dy;\n }\n cout << \"tauw end\" << endl;\n \n for(i = 0;i <= nx;++i){\n Cf.at(i) = tauw.at(i)/(rho*u0*u0/2.0);\n }\n cout << \"Cf end\" << endl;\n\n end = std::chrono::system_clock::now(); // 計測終了時間\n elapsed = std::chrono::duration_cast<std::chrono::seconds>(end-start).count();\n cout << elapsed << endl;\n cout << \"thickness calculate end\" << endl;\n\n vector<double> boundary_layer_thickness_height(nx+1,0);\n vector<double> displacement_thickness_height(nx+1,0);\n vector<double> momentum_thickness_hieght(nx+1,0);\n vector<double> energy_thickness_height(nx+1,0);\n vector<double> tauw_height(nx+1,0);\n vector<double> Cf_height(nx+1,0);\n for(i = 1;i <= nx;++i){\n boundary_layer_thickness_height.at(i) = boundary_layer_thickness.at(i)/x.at(i)*sqrt(Re/widthx*x.at(i));\n displacement_thickness_height.at(i) = displacement_thickness.at(i)/x.at(i)*sqrt(Re/widthx*x.at(i));\n momentum_thickness_hieght.at(i) = momentum_thickness.at(i)/x.at(i)*sqrt(Re/widthx*x.at(i));\n energy_thickness_height.at(i) = energy_thickness.at(i)/x.at(i)*sqrt(Re/widthx*x.at(i));\n Cf_height.at(i) = Cf.at(i)*sqrt(Re/widthx*x.at(i));\n }\n boundary_layer_thickness_height.at(0) = boundary_layer_thickness_height.at(1);\n displacement_thickness_height.at(0) = displacement_thickness_height.at(1);\n momentum_thickness_hieght.at(0) = momentum_thickness_hieght.at(1);\n energy_thickness_height.at(0) = energy_thickness_height.at(1);\n Cf_height.at(0) = Cf_height.at(1);\n */\n cout << \"csv start\" << endl;\n \n ofstream ofs(\"u.csv\");\n for(j = 0;j <= ny;++j){\n for(i = 0;i < nx;++i){\n ofs << std::setprecision(50) << u.at(j).at(i) << \",\";\n }\n ofs << std::setprecision(50) << u.at(j).at(i) << endl;\n if(j %10 == 0){\n cout << \"ofs u:\" << j << endl; \n }\n }\n\n ofstream ofs2(\"v.csv\");\n for(j = 0;j <= ny;++j){\n for(i = 0;i < nx;++i){\n ofs2 << std::setprecision(50) << v.at(j).at(i) << \",\";\n }\n ofs2 << std::setprecision(50) << v.at(j).at(i) << endl;\n if(j %10 == 0){\n cout << \"ofs2 v:\" << j << endl; \n }\n }\n /*\n ofstream ofs3(\"thickness.csv\");\n for(i = 0;i < nx;++i){\n ofs3 << std::setprecision(50) << boundary_layer_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << displacement_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << momentum_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << energy_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << tauw.at(i) << \",\";\n ofs3 << std::setprecision(50) << Cf.at(i) << \",\";\n ofs3 << std::setprecision(50) << boundary_layer_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << displacement_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << momentum_thickness_hieght.at(i) << \",\";\n ofs3 << std::setprecision(50) << energy_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << Cf_height.at(i) << endl;\n }\n ofs3 << std::setprecision(50) << boundary_layer_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << displacement_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << momentum_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << energy_thickness.at(i) << \",\";\n ofs3 << std::setprecision(50) << tauw.at(i) << \",\";\n ofs3 << std::setprecision(50) << Cf.at(i) << \",\";\n ofs3 << std::setprecision(50) << boundary_layer_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << displacement_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << momentum_thickness_hieght.at(i) << \",\";\n ofs3 << std::setprecision(50) << energy_thickness_height.at(i) << \",\";\n ofs3 << std::setprecision(50) << Cf_height.at(i) << endl;\n cout << \"csv end\" << endl;\n */\n return 0;\n}"
},
{
"alpha_fraction": 0.7777777910232544,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 8,
"blob_id": "2cdfac4a8b44404ebb3c4cc31dfd335fbc9755fd",
"content_id": "e5939b9f7548cacc1c6cef291b89c46514db6368",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 26,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 2,
"path": "/README.md",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "# University\n大学用の\n"
},
{
"alpha_fraction": 0.48255813121795654,
"alphanum_fraction": 0.5674418807029724,
"avg_line_length": 23.121496200561523,
"blob_id": "4d850dd182e089626dfda2fc9672234faec03c5f",
"content_id": "dcca1ec250bf79b58cb088dfa715dabd29df1d76",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2580,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 107,
"path": "/AirplaneDynamics_three/report1/gra2.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nm = 7500\nS = 27.9\ng = 9.8\nrho = 0.736423\nU = 180\n\nC_lalpha = 4.30\nC_d0 = 0.0548\nK = 3.02\nalpha = 0.050617000000425585\nL = rho*U**2*S/2*C_lalpha*alpha\nD = rho*U**2*S/2*(C_d0+K*alpha**2)\nT = (20841.80471039165+20842.199605483533)/2\n\nPhi_0 = 30/180*np.pi\nomega = 2*np.pi/40\n\ndif = 1e-3\nt = np.arange(0,80+dif,dif)\nPhi = np.empty_like(t)\n\nfor i in range(0,t.size):\n if t[i] <= 20:\n Phi[i] = 0\n elif t[i] > 20 and t[i] <= 60:\n Phi[i] = Phi_0*np.sin(omega*(t[i]-20))\n else:\n Phi[i] = 0\n\nx_E = np.empty((6,t.size))\nU_mat = np.empty((2,t.size))\nangle = np.empty((4,t.size))\nx_E.T[0] = 0\nx_E[5][0] = 5000\nU_mat[0][0] = 0\nU_mat[1][0] = U\n\nangle.T[0] = 0\nD_array = np.empty(t.size)\nL_array = np.empty(t.size)\nT_array = np.empty(t.size)\nalpha_array = np.empty(t.size)\nD_array[0] = D\nL_array[0] = L\nT_array[0] = T\nalpha_array[0] = alpha\n\nfor i in range(1, t.size):\n alpha_array[i] = np.arctan((g*m/np.cos(Phi[i])-L_array[i-1])/D_array[i-1])\n T_array[i] = np.sqrt(D_array[i-1]**2+(g*m/np.cos(Phi[i])-L_array[i-1])**2)\n U_mat[0][i] = (-D_array[i-1]+T_array[i]*np.cos(alpha_array[i]))/m-g*np.sin(angle[2][i-1])\n U_mat[1][i] = U_mat[1][i-1]+dif*U_mat[0][i-1]\n\n x_E[0][i] = U_mat[1][i-1]*np.cos(angle[2][i-1])*np.cos(angle[3][i-1])\n x_E[1][i] = U_mat[1][i-1]*np.cos(angle[2][i-1])*np.sin(angle[3][i-1])\n x_E[2][i] = U_mat[1][i-1]*np.sin(angle[2][i-1])\n for j in range(3,6):\n x_E[j][i] = x_E[j][i-1] + dif*x_E[j-3][i-1]\n\n angle[0][i] = ((L_array[i-1]+T_array[i]*np.sin(alpha_array[i]))/m*np.cos(Phi[i])-g*np.cos(angle[2][i-1]))/U_mat[1][i-1]\n angle[1][i] = (L_array[i-1]+T_array[i]*np.sin(alpha_array[i]))*np.sin(Phi[i])/m/np.cos(angle[2][i-1])/U_mat[1][i-1]\n angle[2][i] = angle[2][i-1] + dif*angle[0][i-1]\n angle[3][i] = angle[3][i-1] + dif*angle[1][i-1]\n D_array[i] = rho*U_mat[1][i-1]**2*S/2*(C_d0+K*alpha_array[i]**2)\n L_array[i] = rho*U_mat[1][i-1]**2*S/2*C_lalpha*alpha_array[i]\n \n\nplt.figure()\nplt.plot(t,U_mat[1])\nplt.title(\"U\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"U[m/s]\")\nplt.show()\n\nplt.figure()\nplt.plot(x_E[3],x_E[4])\nplt.title(\"x-y\")\nplt.xlabel(\"x_e[m]\")\nplt.ylabel(\"y_e[m]\")\nplt.show()\n\nplt.figure()\nplt.plot(t,x_E[5])\nplt.title(\"altitude\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"h[m]\")\nplt.show()\n\nalpha_array *= 180/np.pi\n\nplt.figure()\nplt.plot(t,)\nplt.title(\"alpha\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"alpha[deg]\")\nplt.show()\n\nplt.figure()\nplt.plot(t,T_array)\nplt.title(\"T\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"T[N]\")\nplt.show()"
},
{
"alpha_fraction": 0.3429906666278839,
"alphanum_fraction": 0.5331775546073914,
"avg_line_length": 21.408376693725586,
"blob_id": "a8353c9759c89f430b68f2f1028db736f4a4ce38",
"content_id": "1d00548035d1aa5d5a81f8e1e54ca0b28dd7287e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4280,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 191,
"path": "/system_experiment/aoyoko/plane_vibration/natural_vibration.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport numpy.linalg as LA\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.pyplot import *\n\na = 235*1e-3\nb = 182*1e-3\nh = 1.0*1e-3\nE = 67*1e9\nmu = 0.326\nrho = 2.66*1e3\nD = E*h**3/(12*(1-mu**2))\np = 5\nq = 7\nepsilon = np.empty(p)\nepsilon[0] = 1.8751041\nepsilon[1] = 4.6940911\nepsilon[2] = 7.8547574\nepsilon[3] = 10.9955407\nepsilon[4] = 14.1371684\n\nchi = np.empty(q)\nchi[0] = 0\nchi[1] = 0\nchi[2] = 4.7300408\nchi[3] = 7.8532046\nchi[4] = 10.9956078\nchi[5] = 14.1371655\nchi[6] = 17.2787596\n\nG = np.empty((p,q))\nfor i in range(p):\n for j in range(q):\n G[i][j] = b/a*epsilon[i]**4 + (a/b)**3*chi[j]**4\nE = np.empty((p,p))\nH = np.empty((p,p))\nF = np.zeros((q,q))\nK = np.zeros((q,q))\n\nE[0][0] = 0.85824\nE[0][1] = -11.74322\nE[0][2] = 27.45315\nE[0][3] = -37.39025\nE[0][4] = 51.95662\nE[1][0] = 1.87385\nE[1][1] = -13.29425\nE[1][2] = -9.04222\nE[1][3] = 30.40219\nE[1][4] = -33.70907\nE[2][0] = 1.56451\nE[2][1] = 3.22933\nE[2][2] = -45.90423\nE[2][3] = -8.33537\nE[2][4] = 36.38656\nE[3][0] = 1.08737\nE[3][1] = 5.54065\nE[3][2] = 4.25360\nE[3][3] = -98.91821\nE[3][4] = -7.82895\nE[4][0] = 0.91404\nE[4][1] = 5.71642\nE[4][2] = 11.23264\nE[4][3] = 4.73605\nE[4][4] = -171.58466\n\nH[0][0] = 4.64778\nH[0][1] = -7.37987\nH[0][2] = 3.94151\nH[0][3] = -6.59339\nH[0][4] = 4.59198\nH[1][1] = 32.41735\nH[1][2] = -22.35243\nH[1][3] = 13.58425\nH[1][4] = -22.83952\nH[2][2] = 77.29889\nH[2][3] = -35.64827\nH[2][4] = 20.16203\nH[3][3] = 142.90185\nH[3][4] = -48.71964\nfor i in range(p):\n for j in range(i):\n H[i][j] = H[j][i]\n\nF[0][2] = 18.58910\nF[0][4] = 43.98096\nF[0][6] = 69.11504\nF[1][3] = 40.59448\nF[1][5] = 84.08889\nF[2][2] = -12.30262\nF[2][4] = 52.58440\nF[2][6] = 101.62255\nF[3][3] = -46.05012\nF[3][5] = 55.50868\nF[4][2] = 1.80069\nF[4][4] = -98.90480\nF[4][6] = 60.12891\nF[5][3] = 5.28566\nF[5][5] = -171.58566\nF[6][2] = 0.57069\nF[6][4] = 9.86075\nF[6][6] = -263.99798\n\nK[1][1] = 12.00000\nK[1][3] = 13.85641\nK[1][5] = 13.85641\nK[2][2] = 49.48082\nK[2][4] = 35.37751\nK[2][6] = 36.60752\nK[3][3] = 108.92459\nK[3][5] = 57.58881\nK[4][4] = 186.86671\nK[4][6] = 78.10116\nK[5][5] = 284.68314\nF[6][6] = 402.22805\nfor i in range(1,q):\n for j in range(1,i):\n K[i][j] = K[j][i]\n\nC = np.empty((p,p,q,q))\nfor i in range(C.shape[0]):\n for m in range(C.shape[1]):\n for k in range(C.shape[2]):\n for n in range(C.shape[3]):\n C[i][m][k][n] = mu*a/b*(E[i][m]*F[n][k]+E[m][i]*F[k][n])+2*(1-mu)*a/b*H[i][m]*K[k][n]\n\nJ = np.zeros((p*q,p*q))\nN = np.empty((p*q,p*q))\nfor i in range(p*q):\n J[i][i] = G[i//q][i%q]\nfor i in range(p*q):\n for j in range(p*q):\n N[i][j] = C[i//q][j//q] [i%q][j%q]\nM = J+N\nlmd_list, v = LA.eig(M)\nv = v.T\n\nlmd_vector_list = []\nfor i in range(len(lmd_list)):\n lmd_vector_list.append((lmd_list[i],v[i]))\n\nlmd_vector_list.sort(key = lambda x:x[0])\n\nomega_list = []\nfor i in range(len(lmd_vector_list)):\n omega = sqrt(lmd_vector_list[i][0]*D/(rho*h*a**3*b))\n omega_list.append(omega)\n\na *= 1e3\nb *= 1e3\n\ndef Xm(x,m):\n alpha = (sinh(epsilon[m])-sin(epsilon[m]))/(cosh(epsilon[m])+cos(epsilon[m]))\n return cosh(epsilon[m]*x/a)-cos(epsilon[m]*x/a)-alpha*(sinh(epsilon[m]*x/a)-sin(epsilon[m]*x/a))\n\ndef Yn(y,n):\n if n == 0:\n return 1.0\n elif n == 1:\n return sqrt(3)*(1-2*y/b)\n else:\n beta = (sinh(chi[n])+sin(chi[n]))/(cosh(chi[n])-cos(chi[n]))\n return cosh(chi[n]*y/b)+cos(chi[n]*y/b)-beta*(sinh(chi[n]*y/b)+sin(chi[n]*y/b))\n\ndef W(x,y,i):\n W = 0\n for m in range(p):\n for n in range(q):\n W += lmd_vector_list[i][1][m*q+n]*Xm(x,m)*Yn(y,n)\n return W\n\nx = arange(0,a,a/100)\ny = arange(0,b,b/100)\nX,Y = meshgrid(x,y)\nfor i in range(p*q):\n Z = W(X,Y,i)\n fig = figure()\n ax = fig.add_subplot(111, projection = \"3d\")\n surf = ax.plot_surface(X,Y,Z, cmap = \"winter\")\n ax.contourf(X, Y, Z, zdir='z', offset=-10)\n ax.contour(X, Y, Z, zdir='x', offset=-30)\n ax.contour(X, Y, Z, zdir='y', offset=b+30)\n ax.set_xlabel(r\"$x$ [mm]\")\n ax.set_ylabel(r\"$y$ [mm]\")\n ax.set_zlabel('$W$')\n ax.set_xlim3d(-30,a)\n ax.set_ylim3d(0, b+30)\n ax.set_zlim3d(-10, 10)\n ax.set_title(r\"mode%d: $\\omega$=%s[Hz]\"%(i+1,omega_list[i]/(2*pi)))\n colorbar(surf)\n subplots_adjust(left=-0.08, right=1.03, bottom=0.03, top=0.97)\n show(surf)\n"
},
{
"alpha_fraction": 0.5443481206893921,
"alphanum_fraction": 0.5823345184326172,
"avg_line_length": 26.958763122558594,
"blob_id": "96c1c1898f928de31ffdea9d314b8bb27d631e5f",
"content_id": "32c040b7b5a459844e6138f6f20ba23fa3f8f500",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5423,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 194,
"path": "/info_system_3/46.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport csv\nfrom scipy.optimize import rosen, differential_evolution, minimize, basinhopping\nimport numpy.linalg as la\n\nwith open(\"satellite-temp.csv\") as f:\n reader = csv.reader(f)\n l = [row for row in reader]\n\nl = array(l).T\ntime = l[0]\ntemp = l[1]\ntime = [float(each_time) for each_time in time]\ntemp = [float(each_temp) for each_temp in temp]\ntime = array(time)\ntemp = array(temp)\n\ndiff = 1e-2\n\nT_0 = arange(12.5,12.8,diff)\na = arange(2.8,3.0,diff)\nomega = arange(1.0,1.2,diff)\ntheta = arange(-pi/10,pi/10,diff)\n\ne = empty((len(T_0), len(a), len(omega), len(theta)))\n\"\"\"\nfor i in range(len(T_0)):\n for j in range(len(a)):\n for k in range(len(omega)):\n for l in range(len(theta)):\n tempe = temp - T_0[i] - a[j]*sin(omega[k]*time + theta[l])\n tempe = tempe**2\n sume = sum(tempe)\n e[i][j][k][l] = sume\n\nprint(amin(e))\nmin_e = 1e3\nmin_i = 0\nmin_j = 0\nmin_k = 0\nmin_l = 0\nfor i in range(len(T_0)):\n for j in range(len(a)):\n for k in range(len(omega)):\n for l in range(len(theta)):\n if e[i][j][k][l] < min_e:\n min_e = e[i][j][k][l]\n min_i = i\n min_j = j\n min_k = k\n min_l = l\nprint(T_0[min_i])\nprint(a[min_j])\nprint(omega[min_k])\nprint(theta[min_l])\n\"\"\"\n\nT_0_def = 12.67\na_def = 2.92\nomega_def = 1.06\ntheta_def = -0.194\n\nomega_def /= 1000\ntime_v = arange(0,14000,10)\nsin_v = T_0_def + a_def*sin(omega_def*time_v + theta_def)\n\nfrom scipy.optimize import curve_fit\n\ndef func(t,T_0,a,omega,theta):\n return T_0 + a*sin(omega*t + theta)\n\nplt.scatter(time,temp)\nplt.plot(time_v,sin_v,label = \"LS\")\nplt.xlabel(\"time\")\nplt.ylabel(\"temperature\")\nplt.legend(loc = \"lower right\")\nplt.savefig(\"460.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\n\ntime /= 5000\npopt, pcov = curve_fit(func,time,temp)\n\npopt[2] /= 5000\ntime *= 5000\nplt.scatter(time,temp)\nplt.plot(time_v,sin_v,label = \"LS\")\nplt.plot(time_v,func(time_v, *popt),label = \"scipy\")\nprint(sum((temp - func(time, *popt))**2)/len(temp))\nplt.xlabel(\"time\")\nplt.ylabel(\"temperature\")\nplt.legend(loc = \"lower right\")\nplt.savefig(\"461.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\nprint(popt)\n\n\ngosa_list = []\ndef GD(time,temp,T_0,a,omega,theta):\n step_size = 200\n n = len(time)\n step = linspace(0,step_size,step_size + 1)\n step_dif = 1e-12\n for i in range(step_size):\n dE_dT_0 = sum(2*(a*sin(omega*time + theta) + T_0 - temp))\n dE_da = sum(2*sin(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n dE_domega = sum(2*time*a*cos(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n dE_dtheta = sum(2*a*cos(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n \n T_0 -= step_dif*dE_dT_0\n a -= step_dif*dE_da\n omega -= step_dif*dE_domega\n theta -= step_dif*dE_dtheta\n\n gosa = sum((temp - func(time,T_0, a, omega, theta))**2)\n gosa_list.append(gosa)\n return [T_0, a, omega, theta]\n\ninit = [12.5,3,1e-3,-0.3]\npopt2 = GD(time,temp,init[0],init[1],init[2],init[3])\ngosa_list = array(gosa_list)\niteration_number = empty_like(gosa_list)\nfor i in range(len(gosa_list)):\n iteration_number[i] = i+1\n\n\"\"\"\nplt.scatter(time,temp)\n#plt.plot(time_v,sin_v,label = \"LS\")\nplt.plot(time_v,func(time_v, *popt2),label = \"GD\")\nplt.plot(time_v,func(time_v, *popt),label = \"scipy\")\nplt.plot(time_v,func(time_v, *init), label = \"init\")\nplt.legend()\nplt.show()\n\"\"\"\n\ngosa_list_2 = []\ndef Adam(time,temp,T_0,a,omega,theta):\n iteration_number = 200\n n = len(time)\n #hyper parametar\n eta = 1e-4\n rho_1 = 0.9\n rho_2 = 0.999\n epsilon = 1e-8\n\n m = zeros(4)\n v = zeros(4)\n\n w = array([T_0, a, omega,theta])\n\n for i in range(1,iteration_number+1):\n T_0, a, omega,theta = w\n\n gosa = sum((temp - func(time,T_0, a, omega, theta))**2)\n gosa_list_2.append(gosa)\n\n dE_dT_0 = sum(2*(a*sin(omega*time + theta) + T_0 - temp))\n dE_da = sum(2*sin(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n dE_domega = sum(2*time*a*cos(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n dE_dtheta = sum(2*a*cos(omega*time + theta)*(a*sin(omega*time + theta) + T_0 - temp))\n \n g = array([dE_dT_0, dE_da, dE_domega, dE_dtheta])\n m = rho_1*m + (1 - rho_1)*g\n v = rho_2*v + (1 - rho_2)*la.norm(g)**2\n m_hat = m/(1 - rho_1**i)\n v_hat = v/(1 - rho_2**i)\n delta_w = - eta/sqrt(v_hat + epsilon)*m_hat\n w += delta_w\n \n return w\n\ninit = [12.5,3,1e-3,-0.3] \npopt3 = Adam(time,temp,init[0],init[1],init[2],init[3])\n\nplt.plot(iteration_number, gosa_list, label = \"GD\")\nplt.plot(iteration_number, gosa_list_2, label = \"Adam\")\nplt.xlabel(\"iteration number\")\nplt.ylabel(\"E\")\nplt.legend()\nplt.savefig(\"462.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\n\nplt.scatter(time,temp)\nplt.plot(time_v,func(time_v, *popt3),label = \"Adam\")\nplt.plot(time_v,func(time_v, *popt2),label = \"GD\")\nplt.plot(time_v,func(time_v, *popt),label = \"scipy\")\nplt.plot(time_v,func(time_v, *init), label = \"init\")\nplt.xlabel(\"time\")\nplt.ylabel(\"temperature\")\nplt.legend()\nplt.savefig(\"463.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\n\nprint(sum((temp - func(time, *popt3))**2)/len(temp))"
},
{
"alpha_fraction": 0.48542630672454834,
"alphanum_fraction": 0.5325524210929871,
"avg_line_length": 21.66666603088379,
"blob_id": "a6be8fb4f48e4f69457409f1e15434ae4fbbdc25",
"content_id": "81be6e7f2c6dbd8799e491432e807c050a041dd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3671,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 162,
"path": "/info_system_3/45.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nfrom scipy.stats import norm\nfrom mpl_toolkits.mplot3d import Axes3D\n\nx = [18.2,25.82,18.24,28.6,31.1,33.6,40.46,28.27,20.1,27.91,26.18,22.12]\ny = [17.05,19.8,15.98,22.07,22.83,24.55,27.27,23.57,13.58,22.8,20.3,16.59]\n\nX_m = empty((len(x),2))\nfor i in range(len(x)):\n X_m[i][0] = 1\n X_m[i][1] = x[i]\n\ny_v = array(y).T\n\nans = la.solve(dot(X_m.T,X_m),dot(X_m.T,y_v))\n\ndiff = 1e-2\n\nx_a = arange(0,50,diff)\ny_a = ans[0] + ans[1]*x_a\n\nprint(ans)\n\nplt.scatter(x,y)\nplt.plot(x_a,y_a, label = \"LS\")\nplt.xlim(0,50)\nplt.ylim(0,30)\nplt.xlabel(\"Smoking rate\")\nplt.ylabel(\"Death rate\")\nplt.legend()\nplt.show()\n\na = arange(0,1,diff)\nb = arange(4,6,diff)\naa,bb = meshgrid(a,b)\n\narg_max_aa = 0\narg_max_bb = 0\n\ndef plot_l_func():\n def l_func(a,b):\n x_lv = array(x)\n y_lv = array(y)\n e = y_lv - (a*x_lv+b)\n e = e**2\n p = 1/sqrt(2*pi)*exp(-e/2)\n cal_p = prod(p)\n return cal_p\n\n l = empty_like(aa)\n for i in range(aa.shape[0]):\n for j in range(aa.shape[1]):\n l[i][j] = l_func(aa[i][j],bb[i][j])\n print(l.max())\n i = argmax(l)//l.shape[1]\n j = argmax(l)%l.shape[1]\n print(i,j)\n print(aa[i][j],bb[i][j])\n global arg_max_aa\n arg_max_aa = aa[i][j]\n global arg_max_bb\n arg_max_bb = bb[i][j]\n \n fig = plt.figure()\n ax = Axes3D(fig)\n ax.plot_surface(aa,bb,l)\n ax.set_xlabel(\"a\")\n ax.set_ylabel(\"b\")\n ax.set_zlabel(\"L\")\n plt.show()\n\ndef plot_ll_func():\n def ll_func(a,b):\n x_lv = array(x)\n y_lv = array(y)\n e = y_lv - (a*x_lv+b)\n e = e**2\n sum_e = sum(e)\n p = -len(e)/2*(log(2*pi)) - 1/2*sum_e\n return p\n\n ll = empty_like(aa)\n for i in range(aa.shape[0]):\n for j in range(aa.shape[1]):\n ll[i][j] = ll_func(aa[i][j],bb[i][j])\n \n fig = plt.figure()\n ax = Axes3D(fig)\n ax.set_xlabel(\"a\")\n ax.set_ylabel(\"b\")\n ax.set_zlabel(\"L\")\n ax.plot_surface(bb,aa,ll)\n plt.show()\n print(ll.max())\n i = argmax(ll)//ll.shape[1]\n j = argmax(ll)%ll.shape[1]\n print(i,j)\n print(aa[i][j],bb[i][j])\n global arg_max_aa\n arg_max_aa = aa[i][j]\n global arg_max_bb\n arg_max_bb = bb[i][j]\n\nplot_l_func()\nplot_ll_func()\ny_a2 = x_a*arg_max_aa + arg_max_bb\n\nplt.scatter(x,y,color = \"C0\")\nplt.plot(x_a,y_a, label = \"LS\", color = \"C1\")\nplt.plot(x_a,y_a2, label = \"MLE\", color = \"C2\")\nplt.xlabel(\"Smoking rate\")\nplt.ylabel(\"Death rate\")\nplt.xlim(0,50)\nplt.ylim(0,30)\nplt.legend()\nplt.show()\n\ny_g = sum((array(y) - (ans[0] + ans[1]*array(x)))**2)\ny_g2 = sum((array(y) - (arg_max_bb + arg_max_aa*array(x)))**2)\nprint(\"e_ls\", y_g)\nprint(\"e_mle\", y_g2)\n\nsigma2 = arange(diff,5,1e-6)\n\ndef plot_sigma_l_func(a,b,sigma):\n x_lv = array(x)\n y_lv = array(y)\n e = y_lv - (a*x_lv+b)\n e = e**2\n p = empty_like(e)\n cal_p = ones_like(sigma)\n for j in range(len(sigma)):\n for i in range(len(p)):\n p[i] = 1/sqrt(2*pi*sigma[j])*exp(-e[i]/2/sigma[j])\n for i in range(len(p)):\n cal_p[j] *= p[i]\n plt.plot(sigma,cal_p)\n plt.xlabel(r\"$\\sigma^2$\")\n plt.ylabel(\"L\")\n plt.show()\n sigma2 = sigma[argmax(cal_p)]\n print(sigma2)\n print(sqrt(sigma2))\n\ndef plot_sigma_ll_func(a,b,sigma):\n x_lv = array(x)\n y_lv = array(y)\n e = y_lv - (a*x_lv+b)\n e = e**2\n sum_e = sum(e)\n p = -len(e)/2*(log(2*pi) + log(sigma)) - 1/2/sigma*sum_e\n plt.plot(sigma,p)\n plt.xlabel(r\"$\\sigma^2$\")\n plt.ylabel(\"LL\")\n plt.show()\n sigma2 = sigma[argmax(p)]\n print(sigma2)\n print(sqrt(sigma2))\n\nplot_sigma_ll_func(ans[1],ans[0],sigma2)"
},
{
"alpha_fraction": 0.5312010645866394,
"alphanum_fraction": 0.5560277104377747,
"avg_line_length": 29.630136489868164,
"blob_id": "101f17639860a06b4557d59193f2a31444d20642",
"content_id": "28f9c70e9c15f056b2734830f221be7e55c1dca6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4489,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 146,
"path": "/info_system_3/47.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nfrom scipy.optimize import rosen, differential_evolution, minimize, basinhopping\nfrom scipy.stats import norm\nimport csv\n\nwith open(\"ballthrow.csv\") as f:\n reader = csv.reader(f)\n l = []\n for row in reader:\n l.append(float(row[0]))\n\nl = array(l)\nl_min = min(l)\nl_max = max(l)\n\nn = len(l)\ndata = l\ndef dif_evo():\n def func(args):\n alpha_M, mu_M, sigma_M, mu_F, sigma_F = args\n man = alpha_M/sqrt(2*pi*sigma_M)*exp(-(l - mu_M)**2/(2*sigma_M))\n woman = (1-alpha_M)/sqrt(2*pi*sigma_F)*exp(-(l - mu_F)**2/(2*sigma_F))\n temp = sum(log(man + woman))\n return -temp\n\n bounds = [(0.05,0.95), (25,50), (1,1000),(10,30), (1,1000)]\n\n ret = differential_evolution(func, bounds)\n\n print(ret)\n\n param = ret[\"x\"]\n alpha_M, mu_M, sigma_M, mu_F, sigma_F = param\n diff = 1e-3\n x_v = arange(0,60,diff)\n a = 5\n man_v = a*n*alpha_M/sqrt(2*pi*sigma_M)*exp(-(x_v - mu_M)**2/(2*sigma_M))\n woman_v = a*n*(1-alpha_M)/sqrt(2*pi*sigma_F)*exp(-(x_v - mu_F)**2/(2*sigma_F))\n\n plt.plot(x_v,man_v,label = \"male\")\n plt.plot(x_v,woman_v,label = \"female\")\n plt.plot(x_v,man_v + woman_v,label = \"all\")\n plt.hist(l, bins = 16,color = \"gray\")\n plt.savefig(\"470.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.legend()\n plt.show()\n\ndef EM_algorithm():\n #alpha_M, mu_M, mu_F, sigma_M, sigma_F\n init_list = [0.65,35,10,100,10]\n args = init_list\n\n iteration_number = 10000\n\n def calculate_w(j,args): #iはどのdataか,jはmaleかfemaleか\n alpha_M, mu_M, mu_F, sigma_M, sigma_F = args\n temp_male = alpha_M*norm.pdf(x = data, loc = mu_M, scale = sqrt(sigma_M))\n temp_female = (1-alpha_M)*norm.pdf(x = data, loc = mu_F, scale = sqrt(sigma_F))\n\n if j == 0:\n return temp_male/(temp_male + temp_female)\n else:\n return temp_female/(temp_male + temp_female)\n \n def calculate_large_N_K(j,args):\n return sum(calculate_w(j,args))\n \n def calculate_new_mu(j,args):\n temp = sum(calculate_w(j,args)*data)\n temp /= calculate_large_N_K(j,args)\n return temp\n \n def calculate_new_sigma2(j,args):\n if j == 0:\n mu = args[1]\n else:\n mu = args[2]\n temp = sum(calculate_w(j,args)*(data - mu)**2)\n temp /= calculate_large_N_K(j,args)\n return temp\n\n def calculate_new_alpha_M(args):\n return calculate_large_N_K(0,args)/n\n\n def calculate_LL(args):\n alpha_M, mu_M, mu_F, sigma_M, sigma_F = args\n temp_male = alpha_M*norm.pdf(x = data, loc = mu_M, scale = sqrt(sigma_M))\n temp_female = (1-alpha_M)*norm.pdf(x = data, loc = mu_F, scale = sqrt(sigma_F))\n\n return sum(log(temp_male + temp_female))\n\n def iteration(old_args):\n LL_list = []\n args = old_args\n LL_list.append(calculate_LL(args))\n for i in range(iteration_number):\n new_alpha_M = calculate_new_alpha_M(args)\n new_mu_M = calculate_new_mu(0,args) #0がmale\n new_mu_F = calculate_new_mu(1,args) #1がfemale\n new_sigma_M = calculate_new_sigma2(0,args)\n new_sigma_F = calculate_new_sigma2(1,args)\n\n new_args = [new_alpha_M, new_mu_M, new_mu_F, new_sigma_M, new_sigma_F]\n\n LL_list.append(calculate_LL(new_args))\n\n if la.norm(array(args) - array(new_args)) < 1e-6:\n args = new_args\n print(i)\n break\n else:\n args = new_args\n \n return args,LL_list\n \n alp,LL = iteration(args) \n print(alp)\n LL_number = empty(len(LL))\n for i in range(len(LL)):\n LL_number[i] = i+1\n plt.plot(LL_number,LL)\n plt.xlabel(\"iteration\")\n plt.ylabel(\"LL\")\n plt.savefig(\"471.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()\n\n alpha_M, mu_M, mu_F, sigma_M, sigma_F = alp\n diff = 1e-3\n x_v = arange(0,60,diff)\n a = 5\n\n man_v = a*n*alpha_M*norm.pdf(x = x_v, loc = mu_M, scale = sqrt(sigma_M))\n woman_v = a*n*(1-alpha_M)*norm.pdf(x = x_v, loc = mu_F, scale = sqrt(sigma_F))\n\n plt.plot(x_v,man_v,label = \"male\")\n plt.plot(x_v,woman_v,label = \"female\")\n plt.plot(x_v,man_v + woman_v,label = \"all\")\n plt.hist(l, bins = 16,color = \"gray\")\n plt.savefig(\"472.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.legend()\n plt.show()\n\ndif_evo()\nEM_algorithm()"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7545787692070007,
"avg_line_length": 90.33333587646484,
"blob_id": "4065c53f48155877ef1a19b7956965b227f89630",
"content_id": "7268ec217b3c3629921ac2743ab13b195707243d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 553,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 3,
"path": "/PhenomenonMathmaticalModelTheory/README.md",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "### シミュレーションコードについて\n* 標準ライブラリより `heapq` と `queue` を使用, 外部ライブラリとして `numpy` と `matplotlib` を使用. Python, 各ライブラリについてバージョン指定は特に無し.\n* `simu1.py` は発展の 1. に対応, `simu2.py` は発展の2. に対応. `simu1.py` はシミュレーション時間が短いので直ぐに描画されるが `simu2.py` はシミュレーション時間が 10^7 と相当に長いのでそれなりの時間(~ 30分)が掛かると思われる."
},
{
"alpha_fraction": 0.5900570750236511,
"alphanum_fraction": 0.6267318725585938,
"avg_line_length": 19.46666717529297,
"blob_id": "a1f176cd4e9fc847f5dfd0bf92eadf8e7df96123",
"content_id": "69eb4710d1773b4323847872c911e4f2b752fb11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1227,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 60,
"path": "/info_system_3/53.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nimport csv\n\ndistance = []\nvelocity = []\n\nwith open(\"Hubbles_constant.csv\") as f:\n reader = csv.reader(f)\n for row in reader:\n distance.append(row[0])\n velocity.append(row[1])\n\ndistance.pop(0)\nvelocity.pop(0)\n\ndistance = [float(each) for each in distance]\nvelocity = [float(each) for each in velocity]\n\ndistance = array(distance)\nvelocity = array(velocity)\n\na_1 = sum(distance*velocity)/sum(distance**2)\n\nx_v = arange(-0.5,2.5,1e-4)\ny_v = a_1*x_v\n\nX_m = empty((len(distance),2))\nX_m[:,0] = 1\nX_m[:,1] = distance\n\nY = velocity\n\nalp = la.solve(dot(X_m.T,X_m), dot(X_m.T, Y))\n\ny_a = alp[0] + alp[1]*x_v\n\"\"\"\"\nplt.scatter(distance, velocity)\nplt.plot(x_v,y_v, label = r\"$y = ax$\")\nplt.plot(x_v,y_a, label = r\"$y = ax + b$\")\nplt.xlabel(\"distance\")\nplt.ylabel(\"velocity\")\nplt.legend(loc = \"lower right\")\nplt.savefig(\"53.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()\n\"\"\"\nAIC = empty(2)\n\nn = len(distance)\nprint(n)\n\nAIC[0] = sum((velocity - a_1*distance)**2)\nAIC[1] = sum((velocity - (alp[0] + alp[1]*distance))**2)\n\nAIC[0] = n*log(AIC[0]/n) + 2*n/(n-2-1)\nAIC[1] = n*log(AIC[1]/n) + 2*2*n/(n-2*2-1)\nprint(a_1)\nprint(alp)\nprint(AIC)"
},
{
"alpha_fraction": 0.5214194655418396,
"alphanum_fraction": 0.5549871921539307,
"avg_line_length": 22.177778244018555,
"blob_id": "ef3cb4769249ef386f7b1f945d1fc4190ac27edc",
"content_id": "70dd7eaa0fe66de0266b66325150030eb064fd8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3128,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 135,
"path": "/info_system_3/55.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport matplotlib.pyplot as plt\nimport numpy.linalg as la\nfrom scipy.optimize import rosen, differential_evolution, minimize, basinhopping\n\nyear = []\nprice = []\n\nwith open(\"mazdas_55.txt\") as f:\n lines = f.readlines()\n for line in lines:\n line = line.split()\n if len(line) == 2:\n year.append(line[0])\n price.append(line[1])\n\nyear.pop(0)\nprice.pop(0)\n\nyear = [float(each_year) for each_year in year]\nprice = [float(each_price) for each_price in price]\n\nn = len(year)\nyear = array(year)\nprice = array(price)\n\nm = 2\n\ndef IRLS():\n X = empty((n,m+1))\n for k in range(m+1):\n X[:,k] = year**k\n y = price\n\n alp = la.solve(dot(X.T,X),dot(X.T,y))\n first_alp = alp\n\n W = zeros((n,n))\n\n while True:\n gosa = 1/abs(y - dot(X,alp))\n for i in range(n):\n W[i][i] = gosa[i]\n new_alp = la.solve(dot(X.T,dot(W,X)),dot(dot(X.T,W),y))\n if la.norm(new_alp - alp) < 10:\n alp = new_alp\n break\n else:\n alp = new_alp\n\n x_v = arange(65,95,1e-2)\n y_iv = zeros_like(x_v)\n y_ev = zeros_like(x_v)\n for k in range(len(alp)):\n y_iv += first_alp[k]*x_v**k\n y_ev += alp[k]*x_v**k\n\n plt.scatter(year,price)\n plt.plot(x_v,y_iv,color = \"C1\",label = \"MSE\")\n plt.plot(x_v,y_ev,color = \"C2\",label = \"MAE\")\n plt.ylim(-5000,45000)\n plt.xlabel(\"year\")\n plt.ylabel(\"price\")\n plt.legend(loc = \"lower right\")\n #plt.savefig(\"550.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.savefig(\"552.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()\n\n print(first_alp)\n print(alp)\n return alp\n\ndef LP():\n X = empty((n,m+1))\n for k in range(m+1):\n X[:,k] = year**k\n y = price\n first_alp = la.solve(dot(X.T,X),dot(X.T,y))\n\n def f(args):\n e = abs(y-dot(X,args))\n return sum(e)\n \n bounds = [(-1e9,1e9), (-1e9,1e9), (-1e9,1e9)]\n\n ret = differential_evolution(f, bounds)\n alp = ret[\"x\"]\n\n x_v = arange(65,95,1e-2)\n y_iv = zeros_like(x_v)\n y_ev = zeros_like(x_v)\n for k in range(len(alp)):\n y_iv += first_alp[k]*x_v**k\n y_ev += alp[k]*x_v**k\n\n plt.scatter(year,price)\n plt.plot(x_v,y_iv,color = \"C1\")\n plt.plot(x_v,y_ev,color = \"C2\")\n plt.ylim(-5000,45000)\n plt.show()\n\n print(first_alp)\n print(alp)\n\n return alp\n\nX = empty((n,m+1))\nfor k in range(m+1):\n X[:,k] = year**k\ny = price\nalp = la.solve(dot(X.T,X),dot(X.T,y))\n\nIRLS_alp = IRLS()\nLP_alp = LP()\n\nx_v = arange(65,95,1e-2)\ny_iv = zeros_like(x_v)\ny_IRLS = zeros_like(x_v)\ny_LP = zeros_like(x_v)\nfor k in range(len(alp)):\n y_iv += alp[k]*x_v**k\n y_IRLS += IRLS_alp[k]*x_v**k\n y_LP += LP_alp[k]*x_v**k\n\nplt.scatter(year,price)\nplt.plot(x_v,y_iv,color = \"C1\",label = \"MSE\")\nplt.plot(x_v,y_IRLS,color = \"C2\",label = \"IRLS\")\nplt.plot(x_v,y_LP,color = \"C3\",label = \"differential evolution\")\nplt.xlabel(\"year\")\nplt.ylabel(\"price\")\nplt.legend()\n#plt.savefig(\"551.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.savefig(\"553.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.ylim(-5000,45000)\nplt.show()"
},
{
"alpha_fraction": 0.5731186270713806,
"alphanum_fraction": 0.620439887046814,
"avg_line_length": 38.97708511352539,
"blob_id": "ec7c3f61a2cbc60b0c580718ac1320b01cc1f4fe",
"content_id": "c1ec70bd7c48039c918958652c21ba3fa5718198",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 19788,
"license_type": "no_license",
"max_line_length": 428,
"num_lines": 480,
"path": "/sc_control/kalman.cpp",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <random>\n#include <vector>\n#include <utility>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nconst double I_x = 1.9;\nconst double I_y = 1.6;\nconst double I_z = 2.0;\n\nconst double diff = 1e-3;\n\nconst double omega_s = 17.0*2.0*M_PI/60.0;\n\nvoid normalize_q(Vector4d& quaternion); //クォータニオン正規化\nvoid true_value_func(vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector); //真値計算&格納\nvoid estimate_value_func(vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector, Matrix<double, 7, 7>& M, Matrix<double, 3, 3>& Q, const Matrix<double, 7, 3>& Gamma, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector); //推定値計算&格納\npair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> Runge_kutta(const Vector3d& initial_omega, const Vector4d& initial_q, bool noise_flag); //ルンゲクッタで数値積分\nVector3d calculate_omega_k(const Vector3d& omega, const Vector3d& noise_torque);\ndouble Euler_equation(const double& I_1, const double& I_2, const double& I_3, const double& omega_1, const double& omega_2, const double& noise); //omega計算\nMatrix<double, 4,3> calculate_quaternion_Matrix(const Vector4d& quaternion); //クォータニオン計算\nvoid update_M_matrix(Matrix<double, 7, 7>& M, Matrix<double, 3, 3>& Q, const Matrix<double, 7, 3>& Gamma, const pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector); //分散行列アップデート\nMatrix<double, 7, 7> Create_A_matrix(const Vector3d& omega, const Vector4d& quaternion);\nvoid store_value(pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value, vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector); //数値格納\nMatrix<double, 7, 1> Kalman_Filter(const Vector3d& omega_true, const Vector4d& quaternion_true, const Vector3d& omega_estimate, const Vector4d& quaternion_estimate, Matrix<double, 7, 7>& M, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector); //カルマンフィルター\nVector3d calculate_DCM_vector(const Vector4d& q, const int& flag);\nMatrix<double, 3, 7> calculate_H_matrix(const Vector4d& q, const int& flag);\nvoid write_csv(const vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector, const vector<Vector3d, aligned_allocator<Vector3d>>& omega_estimate_store_vector, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_estimate_store_vector, const vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector);\nvoid write_csv_for_omega_and_q(const vector<Vector3d, aligned_allocator<Vector3d>>& omega, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion, bool flag);\nvoid write_csv_for_M(const vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector);\n\nint main()\n{\n Vector4d initial_q;\n Vector3d initial_omega;\n initial_q << 1, 0, 0, 0;\n initial_omega << 0.1, omega_s + 0.1, 0;\n\n int end_time = 50; //end_times[s]秒後に終わる\n\n int i;\n\n random_device seed_gen;\n mt19937 mt(seed_gen());\n uniform_real_distribution<> dist(-0.1, 0.1);\n //一様乱数、推定値の初期値用\n\n Vector4d initial_q_estimate;\n initial_q_estimate << initial_q(0) + dist(mt), initial_q(1) + dist(mt), initial_q(2) + dist(mt), initial_q(3) + dist(mt);\n //initial_q_estimate << initial_q(0) + 0.2, initial_q(1) + 0.2, initial_q(2) + 0.2, initial_q(3) + 0.2;\n\n normalize_q(initial_q_estimate);\n \n Vector3d initial_omega_estimate;\n initial_omega_estimate << initial_omega(0) + dist(mt), initial_omega(1) + dist(mt), initial_omega(2) + dist(mt);\n //initial_omega_estimate << initial_omega(0) + 0.1, initial_omega(1) + 0.1, initial_omega(2) + 0.1;\n\n vector<Vector3d, aligned_allocator<Vector3d>> omega_store_vector(1,initial_omega); //真値が入る\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion_store_vector(1,initial_q); //真値が入る\n\n vector<Vector3d, aligned_allocator<Vector3d>> omega_estimate_store_vector(1,initial_omega_estimate); //推定値が入る\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion_estimate_store_vector(1,initial_q_estimate); //推定値が入る\n\n //推定分散行列\n Matrix<double, 7, 7> M = MatrixXd::Zero(7, 7);\n for(i = 0;i < 7;++i){\n M(i,i) = 1e-2;\n }\n\n vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>> M_store_vector(1,M);\n\n //外乱トルクの分散行列\n Matrix<double, 3, 3> Q = MatrixXd::Zero(3, 3);\n for(i = 0;i < 3;++i){\n Q(i,i) = 1e-4;\n }\n\n //状態方程式\n Matrix<double, 7, 3> B = MatrixXd::Zero(7, 3);\n B(4,0) = 1.0/I_x;\n B(5,1) = 1.0/I_y;\n B(6,2) = 1.0/I_z;\n\n //離散系の行列\n const Matrix<double, 7, 3> Gamma = diff*B;\n\n for(i = 0;i < end_time;++i){\n //1回あたり、1秒間の計算をする。\n\n //数値計算\n true_value_func(omega_store_vector, quaternion_store_vector);\n estimate_value_func(omega_estimate_store_vector, quaternion_estimate_store_vector, M, Q, Gamma, M_store_vector);\n\n Matrix<double, 7, 1> modify;\n modify = Kalman_Filter(omega_store_vector.back(), quaternion_store_vector.back(), omega_estimate_store_vector.back(), quaternion_estimate_store_vector.back(), M, M_store_vector);\n\n Vector4d modify_quaternion;\n modify_quaternion << modify(0), modify(1), modify(2), modify(3);\n Vector3d modify_omega;\n modify_omega << modify(4), modify(5), modify(6);\n //修正\n quaternion_estimate_store_vector.back() -= modify_quaternion;\n omega_estimate_store_vector.back() -= modify_omega;\n\n normalize_q(quaternion_estimate_store_vector.back());\n }\n\n write_csv(omega_store_vector, quaternion_store_vector, omega_estimate_store_vector, quaternion_estimate_store_vector, M_store_vector);\n\n return 0;\n}\n\nvoid normalize_q(Vector4d& quaternion)\n{\n double sum = 0;\n int i;\n for(i = 0;i < 4;++i){\n sum += pow(quaternion(i),2.0);\n }\n sum = sqrt(sum);\n for(i = 0;i < 4;++i){\n quaternion(i) /= sum;\n }\n return;\n}\n\nvoid true_value_func(vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector)\n{\n Vector3d initial_omega = omega_store_vector.back();\n Vector4d initial_q = quaternion_store_vector.back();\n\n //数値格納用\n pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> value;\n //真値なのでnoiseを入れる。\n value = Runge_kutta(initial_omega, initial_q, true);\n //数値格納\n store_value(value, omega_store_vector, quaternion_store_vector);\n\n return;\n}\n\nvoid estimate_value_func(vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector, Matrix<double, 7, 7>& M, Matrix<double, 3, 3>& Q, const Matrix<double, 7, 3>& Gamma, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector)\n{\n Vector3d initial_omega = omega_store_vector.back();\n Vector4d initial_q = quaternion_store_vector.back();\n\n //数値格納用\n pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> value;\n //推定値、noiseは入れない。\n value = Runge_kutta(initial_omega, initial_q, false);\n\n //推定分散行列の計算\n update_M_matrix(M, Q, Gamma, value, M_store_vector);\n\n //数値格納\n store_value(value, omega_store_vector, quaternion_store_vector);\n}\n\npair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> Runge_kutta(const Vector3d& initial_omega, const Vector4d& initial_q, bool noise_flag)\n{\n int iteration_number = 1.0/diff;\n\n Vector3d omega;\n omega << initial_omega(0), initial_omega(1), initial_omega(2);\n Vector4d quaternion;\n quaternion << initial_q(0), initial_q(1), initial_q(2), initial_q(3);\n \n int i;\n\n //random_device seed_gen;\n //mt19937 mt(seed_gen());\n mt19937 mt((int)(omega(0)*1e9)); //MinGWはクソ\n\n //外乱トルク\n normal_distribution<> dist(0.0, 0.01);\n Vector3d noise_torque;\n noise_torque = Vector3d::Zero();\n \n vector<Vector3d, aligned_allocator<Vector3d>> omega_store_vector;\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion_store_vector;\n\n for(i = 0;i < iteration_number;++i){\n if(noise_flag){\n noise_torque << dist(mt), dist(mt), dist(mt);\n }\n\n Vector3d k0 = calculate_omega_k(omega, noise_torque);\n Matrix<double, 4,3> A;\n A = calculate_quaternion_Matrix(quaternion);\n Vector4d l0 = A*omega/2.0*diff;\n\n Vector3d temp_omega = omega + k0/2.0;\n Vector4d temp_quaternion = quaternion + l0/2.0;\n\n Vector3d k1 = calculate_omega_k(temp_omega, noise_torque);\n A = calculate_quaternion_Matrix(temp_quaternion);\n Vector4d l1 = A*temp_omega/2.0*diff;\n\n temp_omega = omega + k1/2.0;\n temp_quaternion = quaternion + l1/2.0;\n\n Vector3d k2 = calculate_omega_k(temp_omega, noise_torque);\n A = calculate_quaternion_Matrix(temp_quaternion);\n Vector4d l2 = A*temp_omega/2.0*diff;\n\n temp_omega = omega + k2;\n temp_quaternion = quaternion + l2;\n\n Vector3d k3 = calculate_omega_k(temp_omega, noise_torque);\n A = calculate_quaternion_Matrix(temp_quaternion);\n Vector4d l3 = A*temp_omega/2.0*diff;\n\n Vector3d k = (k0 + 2.0*k1 + 2.0*k2 + k3)/6.0;\n Vector4d l = (l0 + 2.0*l1 + 2.0*l2 + l3)/6.0;\n\n omega += k;\n quaternion += l;\n omega_store_vector.push_back(omega);\n quaternion_store_vector.push_back(quaternion);\n //クォータニオン正規化するか?(しなくてもいいだろ)\n }\n\n pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> value = make_pair(omega_store_vector, quaternion_store_vector);\n return value;\n}\n\nVector3d calculate_omega_k(const Vector3d& omega, const Vector3d& noise_torque)\n{\n double k_x = Euler_equation(I_y, I_z, I_x, omega(1), omega(2), noise_torque(0));\n double k_y = Euler_equation(I_z, I_x, I_y, omega(2), omega(0), noise_torque(1));\n double k_z = Euler_equation(I_x, I_y, I_z, omega(0), omega(1), noise_torque(2));\n Vector3d k;\n k << k_x, k_y, k_z;\n return k*diff;\n}\n\ndouble Euler_equation(const double& I_1, const double& I_2, const double& I_3, const double& omega_1, const double& omega_2, const double& noise)\n{\n double k = (I_1 - I_2)/I_3*omega_1*omega_2 + noise/I_3;\n return k;\n}\n\nMatrix<double, 4,3> calculate_quaternion_Matrix(const Vector4d& quaternion)\n{\n Matrix<double, 4,3> A;\n A << -quaternion(1), -quaternion(2), -quaternion(3),\n quaternion(0), -quaternion(3), quaternion(2),\n quaternion(3), quaternion(0), -quaternion(1),\n -quaternion(2), quaternion(1), quaternion(0);\n return A;\n}\n\nvoid update_M_matrix(Matrix<double, 7, 7>& M, Matrix<double, 3, 3>& Q, const Matrix<double, 7, 3>& Gamma, const pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector)\n{\n vector<Vector3d, aligned_allocator<Vector3d>> omega = value.first;\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion = value.second;\n int n = omega.size(), m = quaternion.size();\n if(n != m){\n cout << \"something wrong\" << endl;\n }\n\n int i;\n\n for(i = 0;i < n;++i){\n Matrix<double, 7, 7> Phi;\n Phi = Create_A_matrix(omega.at(i), quaternion.at(i))*diff;\n Phi += MatrixXd::Identity(7,7);\n M = Phi*M*(Phi.transpose()) + Gamma*Q*(Gamma.transpose());\n\n M_store_vector.push_back(M); //分散行列保存\n }\n\n return;\n}\n\nMatrix<double, 7, 7> Create_A_matrix(const Vector3d& omega, const Vector4d& quaternion)\n{\n Matrix<double, 7, 7> A = MatrixXd::Zero(7, 7);\n\n A(0,0) = 0; A(0,1) = -0.5*omega(0); A(0,2) = -0.5*omega(1); A(0,3) = -0.5*omega(2); A(0,4) = -0.5*quaternion(1); A(0,5) = -0.5*quaternion(2); A(0,6) = -0.5*quaternion(3);\n A(1,0) = 0.5*omega(0); A(1,1) = 0; A(1,2) = 0.5*omega(2); A(1,3) = -0.5*omega(1); A(1,4) = 0.5*quaternion(0); A(1,5) = -0.5*quaternion(3); A(1,6) = 0.5*quaternion(2);\n A(2,0) = 0.5*omega(1); A(2,1) = -0.5*omega(2); A(2,2) = 0; A(2,3) = 0.5*omega(0); A(2,4) = 0.5*quaternion(3); A(2,5) = 0.5*quaternion(0); A(2,6) = -0.5*quaternion(1);\n A(3,0) = 0.5*omega(2); A(3,1) = 0.5*omega(1); A(3,2) = -0.5*omega(0); A(3,3) = 0; A(3,4) = -0.5*quaternion(2); A(3,5) = 0.5*quaternion(1); A(3,6) = 0.5*quaternion(0);\n\n A(4,5) = (I_y - I_z)/I_x*omega(2); A(4,6) = (I_y - I_z)/I_x*omega(1);\n A(5,4) = (I_z - I_x)/I_y*omega(2); A(5,6) = (I_z - I_x)/I_y*omega(0);\n A(6,4) = (I_x - I_y)/I_z*omega(1); A(6,5) = (I_x - I_y)/I_z*omega(0);\n\n return A;\n}\n\nvoid store_value(pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value, vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector)\n{\n vector<Vector3d, aligned_allocator<Vector3d>> omega = value.first;\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion = value.second;\n int n = omega.size();\n int m = quaternion.size();\n if(n != m){\n cout << \"something wrong\" << endl;\n }\n\n int i;\n\n for(i = 0;i < omega.size();++i){\n omega_store_vector.push_back(omega.at(i));\n }\n for(i = 0;i < quaternion.size();++i){\n quaternion_store_vector.push_back(quaternion.at(i));\n }\n return;\n}\n\nMatrix<double, 7, 1> Kalman_Filter(const Vector3d& omega_true, const Vector4d& quaternion_true, const Vector3d& omega_estimate, const Vector4d& quaternion_estimate, Matrix<double, 7, 7>& M, vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector)\n{\n Vector3d y_true; //観測ベクトル(true)\n Vector3d y_estimate; //観測ベクトル(estimate);\n\n mt19937 mt((int)(quaternion_true(0)*1e9));\n uniform_int_distribution<> dist_for_flag(0, 2);\n int observe_flag = dist_for_flag(mt); //どの列ベクトルを観測するか\n\n //観測ノイズ\n Vector3d noise;\n normal_distribution<> dist_for_noise(0.0, 1e-2);\n noise << dist_for_noise(mt), dist_for_noise(mt), dist_for_noise(mt);\n\n y_true = calculate_DCM_vector(quaternion_true, observe_flag);\n y_estimate = calculate_DCM_vector(quaternion_estimate, observe_flag);\n Vector3d z = y_estimate - y_true;\n\n z += noise; //ノイズを足す\n\n Matrix<double, 3, 7> H;\n H = calculate_H_matrix(quaternion_estimate, observe_flag);\n\n int i;\n\n Matrix3d R = MatrixXd::Zero(3, 3);\n for(i = 0;i < 3;++i){\n R(i,i) = 1e-4; //観測ノイズの分散\n }\n \n Matrix3d temp;\n temp = H*M*(H.transpose()) + R;\n\n Matrix<double, 7, 3> K; //カルマンゲイン\n K = M*(H.transpose())*(temp.inverse());\n\n Matrix<double, 7, 1> modify; //ずれ\n modify = K*z;\n\n M = (MatrixXd::Identity(7,7) - K*H)*M; //分散更新\n /*\n Matrix3d temp;\n temp = H*M*(H.transpose()) + R;\n\n Matrix<double, 7, 7> P;\n P = M - M*(H.transpose())*(temp.inverse())*H*M;\n\n Matrix<double, 7, 3> K;\n K = P*(H.transpose())*(R.inverse());\n\n Matrix<double, 7, 1> modify; //ずれ\n modify = K*z;\n\n M = P;\n */\n M_store_vector.back() = M; //保存\n\n return modify;\n}\n\nVector3d calculate_DCM_vector(const Vector4d& q, const int& flag)\n{ \n Vector3d y;\n if(flag == 0){\n y(0) = q(0)*q(0) + q(1)*q(1) - q(2)*q(2) - q(3)*q(3);\n y(1) = 2.0*(q(1)*q(2) + q(0)*q(3));\n y(2) = 2.0*(q(1)*q(3) - q(0)*q(2));\n }else if(flag == 1){\n y(0) = 2.0*(q(1)*q(2) - q(0)*q(3)); \n y(1) = q(0)*q(0) - q(1)*q(1) + q(2)*q(2) - q(3)*q(3);\n y(2) = 2.0*(q(2)*q(3) + q(0)*q(1));\n }else if(flag == 2){\n y(0) = 2.0*(q(1)*q(3) + q(0)*q(2)); \n y(1) = 2.0*(q(2)*q(3) - q(0)*q(1));\n y(2) = q(0)*q(0) - q(1)*q(1) - q(2)*q(2) + q(3)*q(3);\n }else{\n cout << \"flag something wrong\" << endl;\n }\n return y;\n}\n\nMatrix<double, 3, 7> calculate_H_matrix(const Vector4d& q, const int& flag)\n{\n Matrix<double, 3, 7> H = MatrixXd::Zero(3,7);\n if(flag == 0){\n H(0,0) = q(0); H(0,1) = q(1); H(0,2) = -q(2); H(0,3) = -q(3);\n H(1,0) = q(3); H(1,1) = q(2); H(1,2) = q(1); H(1,3) = q(0);\n H(2,0) = -q(2); H(2,1) = q(3); H(2,2) = -q(0); H(2,3) = q(1);\n }else if(flag == 1){\n H(0,0) = -q(3); H(0,1) = q(2); H(0,2) = q(1); H(0,3) = -q(0);\n H(1,0) = q(0); H(1,1) = -q(1); H(1,2) = q(2); H(1,3) = -q(3);\n H(2,0) = q(1); H(2,1) = q(0); H(2,2) = q(3); H(2,3) = q(2);\n }else if(flag == 2){\n H(0,0) = q(2); H(0,1) = q(3); H(0,2) = q(0); H(0,3) = q(1);\n H(1,0) = -q(1); H(1,1) = -q(0); H(1,2) = q(3); H(1,3) = q(2);\n H(2,0) = q(0); H(2,1) = -q(1); H(2,2) = -q(2); H(2,3) = q(3);\n }else{\n cout << \"flag something wrong\" << endl;\n }\n\n H *= 2.0;\n\n return H;\n}\n\nvoid write_csv(const vector<Vector3d, aligned_allocator<Vector3d>>& omega_store_vector, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_store_vector, const vector<Vector3d, aligned_allocator<Vector3d>>& omega_estimate_store_vector, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion_estimate_store_vector, const vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector)\n{\n write_csv_for_omega_and_q(omega_store_vector, quaternion_store_vector, true);\n write_csv_for_omega_and_q(omega_estimate_store_vector, quaternion_estimate_store_vector, false);\n write_csv_for_M(M_store_vector);\n\n return;\n}\n\nvoid write_csv_for_omega_and_q(const vector<Vector3d, aligned_allocator<Vector3d>>& omega, const vector<Vector4d, aligned_allocator<Vector4d>>& quaternion, bool flag)\n{\n int n = omega.size();\n int m = quaternion.size();\n if(n != m){\n cout << \"something wrong\" << endl;\n }\n\n string file_name;\n if(flag){\n file_name = \"omega_q_true.csv\";\n }else{\n file_name = \"omega_q_estimate.csv\";\n }\n\n ofstream ofs(file_name);\n int i,j;\n for(i = 0;i < 3;++i){\n for(j = 0;j < omega.size()-1;++j){\n ofs << setprecision(10) << omega.at(j)(i) << \",\";\n }\n ofs << setprecision(10) << omega.at(j)(i) << endl;\n }\n\n for(i = 0;i < 4;++i){\n for(j = 0;j < quaternion.size()-1;++j){\n ofs << setprecision(10) << quaternion.at(j)(i) << \",\";\n }\n ofs << setprecision(10) << quaternion.at(j)(i) << endl;\n }\n return;\n}\n\nvoid write_csv_for_M(const vector<Matrix<double, 7, 7>, aligned_allocator<Matrix<double, 7, 7>>>& M_store_vector)\n{\n int n = M_store_vector.size();\n\n ofstream ofs(\"M_diag.csv\");\n int i,j;\n for(i = 0;i < n;++i){\n for(j = 0;j < 6;++j){\n ofs << setprecision(10) << M_store_vector.at(i)(j,j) << ',';\n }\n ofs << setprecision(10) << M_store_vector.at(i)(j,j) << endl;\n }\n\n return;\n}"
},
{
"alpha_fraction": 0.47318610548973083,
"alphanum_fraction": 0.4915877878665924,
"avg_line_length": 30.966386795043945,
"blob_id": "95548f3974fce8f316ee58520b2bc650dca2b22a",
"content_id": "3a9cdb70f2787fe9ae0d43f9a392822ff639aebc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4054,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 119,
"path": "/PhenomenonMathmaticalModelTheory/simu1.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import heapq\nimport queue\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass simulation:\n mu = 1.0 # サービス確率\n Tstart = 1000 # 記録開始タイムステップ\n Tend = 11000 # 記録終了タイムステップ\n\n come = True\n go = False\n\n experiment_rho = []\n experiment_Lambds = [0.05 * i for i in range(1, 22)]\n experiment_Ns = []\n experiment_Ws = []\n\n def __init__(self):\n self.experiment_rho.clear()\n self.experiment_Lambds = [0.05 * i for i in range(1, 22)]\n self.experiment_Ns.clear()\n self.experiment_Ws.clear()\n\n def simulate(self):\n for Lambda in self.experiment_Lambds:\n n = 0 # 滞在人数\n nSum = 0 # 滞在人数の累積\n wSum = 0 # 来た人数が待った累計\n allmembers = 0 # 来た人数の累計\n t = 0\n t_before = -1\n\n come_count = 0\n go_count = 0\n\n pq = [] # イベント行列\n heapq.heappush(pq, (0, self.come))\n come_count += 1\n\n que = queue.Queue() # 待ち行列に入っている人間\n\n while True:\n top = heapq.heappop(pq)\n t = top[0]\n flag = top[1]\n\n # Nsについて記録\n if t >= self.Tstart:\n # 終わりの時間が来ていたら\n if t > self.Tend:\n nSum += n*(self.Tend - t_before)\n break\n else:\n # before がまだスタート前だったら\n if t_before < self.Tstart:\n nSum += n*(t - self.Tstart)\n else:\n nSum += n*(t - t_before)\n\n if flag == self.come:\n n += 1\n come_count -= 1\n que.put(t)\n # Wsについて記録\n if t >= self.Tstart and t < self.Tend:\n allmembers += 1\n else:\n n -= 1\n go_count -= 1\n come_time = que.get()\n # Ws について記録\n if t >= self.Tstart and t < self.Tend:\n wSum += t - come_time\n\n t_before = t\n\n # 次のイベントを計算\n if come_count == 0:\n heapq.heappush(pq, (t + self.calculate_next_come(Lambda), self.come))\n come_count += 1\n if n > 0 and go_count == 0:\n heapq.heappush(pq, (t + self.calculate_next_go(self.mu), self.go))\n go_count += 1\n\n rho = Lambda/self.mu\n self.experiment_rho.append(rho)\n self.experiment_Ns.append(nSum/(self.Tend - self.Tstart))\n self.experiment_Ws.append(wSum/allmembers)\n \n return self.experiment_Lambds, self.experiment_rho, self.experiment_Ns, self.experiment_Ws\n \n def calculate_next_come(self, Lambda):\n return np.random.exponential(1.0/Lambda)\n \n def calculate_next_go(self, mu):\n return np.random.exponential(1.0/mu)\n\n def calculate_theoritical_result(self):\n Lambda = np.linspace(0, 0.99, 9900)\n rho = Lambda/self.mu\n Ws = 1/(1 - rho)/self.mu\n return rho, Ws\n\nMM1 = simulation()\nexperiment_Lambds, experiment_rho, experiment_Ns, experiment_Ws = MM1.simulate()\ntheoritical_rho, theoritical_Ws = MM1.calculate_theoritical_result()\n\nplt.figure()\nplt.ylim(0, 20)\nplt.plot(theoritical_rho, theoritical_Ws, c = \"C0\", label = \"theoritical\")\nplt.scatter(experiment_rho, experiment_Ws, c = \"C2\", marker=\"s\", label = \"simulation\")\nplt.scatter(experiment_rho, np.array(experiment_Ns)/np.array(experiment_Lambds), c = \"C1\", marker=\"x\", label = \"Little's theorem\")\nplt.legend(loc = \"upper left\")\nplt.xlabel(r\"$\\rho$\")\nplt.ylabel(r\"$W_s$\")\nplt.savefig(\"result2_1.png\", bbox_inches='tight')\nplt.show()\n"
},
{
"alpha_fraction": 0.5615050792694092,
"alphanum_fraction": 0.6497828960418701,
"avg_line_length": 22.86206817626953,
"blob_id": "bc6099d994701a7f509f341963759b3214c1ab5c",
"content_id": "c36debb45fb5fbbd5d050af5f1b818325c5138d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 691,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 29,
"path": "/info_system_3/81.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "from numpy import *\nimport numpy.random as ra\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nmu = [20,10]\nmu = array(mu)\nsigma = [[30,20],[20,50]]\n\nn = 10000\n\nvalues = ra.multivariate_normal(mu,sigma,n)\n\nA = [[sqrt(sigma[0][0]),0],[sigma[0][1]/sqrt(sigma[0][0]),sqrt(sigma[1][1] - sigma[0][1]**2/sigma[0][0])]]\nA = array(A)\n\nvalues_2 = [ra.randn(n),ra.randn(n)]\nvalues_2 = array(values_2)\n\ntemp = dot(A,values_2)\n\nvalues_2[0] = temp[0] + mu[0]\nvalues_2[1] = temp[1] + mu[1]\n\nsns.jointplot(values[:,0],values[:,1])\nplt.savefig(\"810.png\",bbox_inches=\"tight\", pad_inches=0.05)\nsns.jointplot(values_2[0],values_2[1])\nplt.savefig(\"811.png\",bbox_inches=\"tight\", pad_inches=0.05)\nplt.show()"
},
{
"alpha_fraction": 0.4521739184856415,
"alphanum_fraction": 0.552173912525177,
"avg_line_length": 22.804597854614258,
"blob_id": "10a73c88df9efe0c2f714933167f8ee0586c81c0",
"content_id": "6a18f69519cf3cf6599efb2da152817d36e6ffdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2070,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 87,
"path": "/AirplaneDynamics_three/report1/gra1.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nm = 7500\nS = 27.9\ng = 9.8\nrho = 0.736423\nU = 180\n\nC_lalpha = 4.30\nC_d0 = 0.0548\nK = 3.02\nalpha = 0.050617000000425585\nL = rho*U**2*S/2*C_lalpha*alpha\nD = rho*U**2*S/2*(C_d0+K*alpha**2)\nT = (20841.80471039165+20842.199605483533)/2\n\nPhi_0 = 30/180*np.pi\nomega = 2*np.pi/40\n\ndif = 1e-3\nt = np.arange(0,80+dif,dif)\nPhi = np.empty_like(t)\n\nfor i in range(0,t.size):\n if t[i] <= 20:\n Phi[i] = 0\n elif t[i] > 20 and t[i] <= 60:\n Phi[i] = Phi_0*np.sin(omega*(t[i]-20))\n else:\n Phi[i] = 0\n\nx_E = np.empty((6,t.size))\nU_mat = np.empty((2,t.size))\nangle = np.empty((4,t.size))\nx_E.T[0] = 0\nx_E[5][0] = 5000\nU_mat[0][0] = 0\nU_mat[1][0] = U\n\nangle.T[0] = 0\n\nfor i in range(1,t.size):\n x_E[0][i] = U_mat[1][i-1]*np.cos(angle[2][i-1])*np.cos(angle[3][i-1])\n x_E[1][i] = U_mat[1][i-1]*np.cos(angle[2][i-1])*np.sin(angle[3][i-1])\n x_E[2][i] = U_mat[1][i-1]*np.sin(angle[2][i-1])\n for j in range(3,6):\n x_E[j][i] = x_E[j][i-1] + dif*x_E[j-3][i-1]\n D = rho*U_mat[1][i-1]**2*S/2*(C_d0+K*alpha**2)\n U_mat[0][i] = (-D+T*np.cos(alpha))/m-g*np.sin(angle[2][i-1])\n U_mat[1][i] = U_mat[1][i-1] + dif*U_mat[0][i-1]\n L = rho*U_mat[1][i-1]**2*S/2*C_lalpha*alpha\n angle[0][i] = ((L+T*np.sin(alpha))/m*np.cos(Phi[i])-g*np.cos(angle[2][i-1]))/U_mat[1][i-1]\n angle[1][i] = (L+T*np.sin(alpha))*np.sin(Phi[i])/m/np.cos(angle[2][i-1])/U_mat[1][i-1]\n angle[2][i] = angle[2][i-1] + dif*angle[0][i-1]\n angle[3][i] = angle[3][i-1] + dif*angle[1][i-1]\n\nplt.figure()\nplt.plot(t,U_mat[1])\nplt.title(\"U\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"U[m/s]\")\nplt.show()\n\nplt.figure()\nplt.plot(x_E[3],x_E[4])\nplt.title(\"x-y\")\nplt.xlabel(\"x_e[m]\")\nplt.ylabel(\"y_e[m]\")\nplt.show()\n\nplt.figure()\nplt.plot(t,x_E[5])\nplt.title(\"altitude\")\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"h[m]\")\nplt.show()\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot(x_E[3],x_E[4],x_E[5])\nplt.title(\"x-y-z\")\nax.set_xlabel('x_e[m]')\nax.set_ylabel('y_e[m]')\nax.set_zlabel('z_e[m]')\nplt.show()"
},
{
"alpha_fraction": 0.5931257605552673,
"alphanum_fraction": 0.6323555707931519,
"avg_line_length": 36.554054260253906,
"blob_id": "80439f27793b1bd976814a6c1215d3c27fec087f",
"content_id": "49f07d05db60e4d89e5ab199f0dad666280ba229",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5591,
"license_type": "no_license",
"max_line_length": 218,
"num_lines": 148,
"path": "/sc_control/simulation.cpp",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <cmath>\n#include <vector>\n#include <utility>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nconst double I_x = 1.9;\nconst double I_y = 1.6;\nconst double I_z = 2.0;\n\npair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> Runge_kutta(const double& diff, const int& iteration_number, const Vector3d& initial_omega, const Vector4d& initial_q);\nVector3d calculate_omega_k(const Vector3d& omega, const double& M_c, const double& M_n, const double& diff);\ndouble Euler_equation(const double& I_1, const double& I_2, const double& I_3, const double& omega_1, const double& omega_2, const double& M_c, const double& M_n);\nMatrix<double, 4,3> calculate_A(Matrix<double, 4,3>& A, const Vector4d& quaternion);\nvoid write_csv_omega_q(const pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value);\n\nint main()\n{\n Vector4d initial_q;\n Vector3d initial_omega;\n const double omega_s = 17.0*2.0*M_PI/60.0;\n initial_q << 1.0, 0.0, 0.0, 0.0;\n initial_omega << 0.1, omega_s + 0.1, 0.0;\n\n double diff = 1e-2;\n int iteration_number = 5e3;\n pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> value;\n\n value = Runge_kutta(diff, iteration_number, initial_omega, initial_q);\n write_csv_omega_q(value);\n\n return 0;\n}\n\npair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> Runge_kutta(const double& diff, const int& iteration_number, const Vector3d& initial_omega, const Vector4d& initial_q)\n{\n double t_end = diff*iteration_number;\n Vector3d omega;\n omega << initial_omega(0), initial_omega(1), initial_omega(2);\n Vector4d quaternion;\n quaternion << initial_q(0), initial_q(1), initial_q(2), initial_q(3);\n \n int i;\n\n vector<double> M_c(iteration_number+1,0); //制御トルク、全て0\n vector<double> M_n(iteration_number+1,0); //ノイズトルク、全て0\n\n vector<Vector3d, aligned_allocator<Vector3d>> omega_store_vector(1,initial_omega);\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion_store_vector(1,initial_q);\n\n for(i = 0;i < iteration_number;++i){\n Vector3d k0 = calculate_omega_k(omega, M_c.at(i), M_n.at(i), diff);\n Matrix<double, 4,3> A;\n A = calculate_A(A, quaternion);\n Vector4d l0 = A*omega/2.0*diff;\n\n Vector3d temp_omega = omega + k0/2.0;\n Vector4d temp_quaternion = quaternion + l0/2.0;\n\n Vector3d k1 = calculate_omega_k(temp_omega, M_c.at(i), M_n.at(i), diff);\n A = calculate_A(A, temp_quaternion);\n Vector4d l1 = A*temp_omega/2.0*diff;\n\n temp_omega = omega + k1/2.0;\n temp_quaternion = quaternion + l1/2.0;\n\n Vector3d k2 = calculate_omega_k(temp_omega, M_c.at(i), M_n.at(i), diff);\n A = calculate_A(A, temp_quaternion);\n Vector4d l2 = A*temp_omega/2.0*diff;\n\n temp_omega = omega + k2;\n temp_quaternion = quaternion + l2;\n\n Vector3d k3 = calculate_omega_k(temp_omega, M_c.at(i), M_n.at(i), diff);\n A = calculate_A(A, temp_quaternion);\n Vector4d l3 = A*temp_omega/2.0*diff;\n\n Vector3d k = (k0 + 2.0*k1 + 2.0*k2 + k3)/6.0;\n Vector4d l = (l0 + 2.0*l1 + 2.0*l2 + l3)/6.0;\n\n omega += k;\n quaternion += l;\n omega_store_vector.push_back(omega);\n quaternion_store_vector.push_back(quaternion);\n }\n\n pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>> value = make_pair(omega_store_vector, quaternion_store_vector);\n return value;\n}\n\nVector3d calculate_omega_k(const Vector3d& omega, const double& M_c, const double& M_n, const double& diff)\n{\n double k_x = Euler_equation(I_y, I_z, I_x, omega(1), omega(2), M_c, M_n);\n double k_y = Euler_equation(I_z, I_x, I_y, omega(2), omega(0), M_c, M_n);\n double k_z = Euler_equation(I_x, I_y, I_z, omega(0), omega(1), M_c, M_n);\n Vector3d k;\n k << k_x, k_y, k_z;\n return k*diff;\n}\n\ndouble Euler_equation(const double& I_1, const double& I_2, const double& I_3, const double& omega_1, const double& omega_2, const double& M_c, const double& M_n)\n{\n double k = (I_1 - I_2)/I_3*omega_1*omega_2 + (M_c + M_n)/I_3;\n return k;\n}\n\nMatrix<double, 4,3> calculate_A(Matrix<double, 4,3>& A, const Vector4d& quaternion)\n{\n A << -quaternion(1), -quaternion(2), -quaternion(3),\n quaternion(0), -quaternion(3), quaternion(2),\n quaternion(3), quaternion(0), -quaternion(1),\n -quaternion(2), quaternion(1), quaternion(0);\n return A;\n}\n\nvoid write_csv_omega_q(const pair<vector<Vector3d, aligned_allocator<Vector3d>>, vector<Vector4d, aligned_allocator<Vector4d>>>& value)\n{\n vector<Vector3d, aligned_allocator<Vector3d>> omega = value.first;\n vector<Vector4d, aligned_allocator<Vector4d>> quaternion = value.second;\n\n int n = omega.size();\n int m = quaternion.size();\n if(n != m){\n cout << \"something wrong\" << endl;\n }\n\n ofstream ofs(\"omega_q_simulation.csv\");\n int i,j;\n for(i = 0;i < 3;++i){\n for(j = 0;j < omega.size()-1;++j){\n ofs << setprecision(10) << omega.at(j)(i) << \",\";\n }\n ofs << setprecision(10) << omega.at(j)(i) << endl;\n }\n\n for(i = 0;i < 4;++i){\n for(j = 0;j < quaternion.size()-1;++j){\n ofs << setprecision(10) << quaternion.at(j)(i) << \",\";\n }\n ofs << setprecision(10) << quaternion.at(j)(i) << endl;\n }\n return;\n}"
},
{
"alpha_fraction": 0.5447845458984375,
"alphanum_fraction": 0.5508240461349487,
"avg_line_length": 36.00757598876953,
"blob_id": "169aba64f47a38fdbcaf910469f16f1f3b7fc4b8",
"content_id": "d81a48fef037799ef8c514120978a4450e97b53a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10499,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 264,
"path": "/Minesweeper/Python/minesweeper.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport copy\nimport random\nimport queue\n\ndef first_input_linenumber():\n while True:\n print(\"縦のマスの数を入れてください。大きすぎると上手く表示出来なくなります。\")\n temp = input(\"\")\n if temp.isdecimal() and temp[0] != \"0\":\n return int(temp)\n else:\n print(\"自然数を入れてください\")\n continue\n\ndef first_input_columnnumber():\n while True:\n print(\"横のマスの数を入れてください。大きすぎると上手く表示出来なくなります。\")\n temp = input(\"\")\n if temp.isdecimal() and temp[0] != \"0\":\n return int(temp)\n else:\n print(\"自然数を入れてください\")\n continue\ndef first_input_bombnumber(linenumber,columnnumber):\n while True:\n print(\"地雷の数を入れてください\")\n temp = input(\"\")\n if temp.isdecimal() and temp[0] != \"0\":\n if int(temp) >= linenumber*columnnumber-8:\n print(\"地雷の数が多すぎます\")\n continue\n else:\n return int(temp)\n else:\n print(\"自然数を入れてください\")\n continue\n\nlinenumber = first_input_linenumber()\ncolumnnumber = first_input_columnnumber()\nbombnumber = first_input_bombnumber(linenumber,columnnumber)\ndisplay_board_array = np.full((linenumber,columnnumber),\"o\")\ndata_board_array = np.zeros((linenumber,columnnumber))\n\ndef know_digit(number):\n digit = 0\n while number:\n number //= 10\n digit += 1\n return digit\n\ndef display_board_func(display_board_array,linenumber,columnnumber):\n line_digit = know_digit(linenumber)\n column_digit = know_digit(columnnumber)\n for line in range(linenumber+1):\n if line == 0:\n for i in range(line_digit):\n print(\" \",end=\"\")\n for column in range(1,columnnumber+1):\n print(column,end=\"\")\n for i in range(column_digit-know_digit(column)):\n print(\" \",end=\"\")\n print()\n else:\n print(line,end=\"\")\n for i in range(line_digit-know_digit(line)):\n print(\" \",end=\"\")\n for column in range(1,columnnumber+1):\n print(display_board_array[line-1][column-1],end=\"\")\n for i in range(column_digit-1):\n print(\" \",end=\"\")\n print()\n\ndisplay_board_func(display_board_array,linenumber,columnnumber)\n\ndef input_linenumber(linenumber):\n while True:\n print(\"マスの位置の縦の座標を入れてください\")\n temp = input(\"\")\n if temp.isdecimal() and temp[0] != \"0\":\n if int(temp) <= linenumber:\n return int(temp)\n else:\n print(\"そのマスはありません\")\n continue\n else:\n print(\"自然数を入れてください\")\n continue\n\ndef input_columnnumber(columnnumber):\n while True:\n print(\"マスの位置の横の座標を入れてください\")\n temp = input(\"\")\n if temp.isdecimal() and temp[0] != \"0\":\n if int(temp) <= columnnumber:\n return int(temp)\n else:\n print(\"そのマスはありません\")\n continue\n else:\n print(\"自然数を入れてください\")\n continue\n\ndef count_around_bomb(data_board_array,linenumber,columnnumber):\n threenumber = [-1,0,1]\n for line in range(linenumber):\n for column in range(columnnumber):\n if data_board_array[line][column] == -1:\n continue\n else:\n for i in threenumber:\n for j in threenumber:\n if i == 0 and j == 0:\n continue\n elif line+i < 0 or column+j < 0:\n continue\n else:\n try:\n if data_board_array[line+i][column+j] == -1:\n data_board_array[line][column] += 1\n except IndexError:\n continue\n\ndef find_blank_space(display_board_array,data_board_array,line_dig_point,column_dig_point):\n find_blank = queue.Queue()\n find_blank.put([line_dig_point,column_dig_point])\n while not find_blank.empty():\n temp = find_blank.get()\n line = temp[0]\n column = temp[1]\n threenumber = [-1,0,1]\n for i in threenumber:\n for j in threenumber:\n if line+i < 0 or column+j < 0:\n continue\n else:\n try:\n if display_board_array[line+i][column+j] == \"o\":\n if data_board_array[line+i][column+j] == 0:\n display_board_array[line+i][column+j] = \" \"\n find_blank.put([line+i,column+j])\n else:\n display_board_array[line+i][column+j] = str(data_board_array[line+i][column+j])\n else:\n continue\n except IndexError:\n continue\n\n\ndef initialize_board_func(display_board_array,data_board_array,linenumber,columnnumber,bombnumber):\n print(\"最初に掘るマスの場所を入れてください\")\n line_dig_point = input_linenumber(linenumber)\n line_dig_point -= 1\n column_dig_point = input_columnnumber(columnnumber)\n column_dig_point -= 1\n display_board_array[line_dig_point][column_dig_point] = \" \"\n decide_where_is_bomb = []\n around_the_first_dig_point = []\n threenumber = [-1,0,1]\n for i in threenumber:\n for j in threenumber:\n if line_dig_point+i < 0 or column_dig_point+j < 0:\n continue\n try:\n if data_board_array[line_dig_point+i][column_dig_point+j] == 0:\n around_the_first_dig_point.append((line_dig_point+i)*columnnumber+column_dig_point+j)\n except IndexError:\n continue\n for i in range(linenumber*columnnumber):\n if i in around_the_first_dig_point:\n continue\n else:\n decide_where_is_bomb.append(i)\n random.shuffle(decide_where_is_bomb)\n for i in range(bombnumber):\n data_board_array[decide_where_is_bomb[i]//columnnumber][decide_where_is_bomb[i]%columnnumber] = -1\n count_around_bomb(data_board_array,linenumber,columnnumber)\n find_blank_space(display_board_array,data_board_array,line_dig_point,column_dig_point)\n\ninitialize_board_func(display_board_array,data_board_array,linenumber,columnnumber,bombnumber)\n\ndef judge_game_clear(display_board_array,data_board_array,linenumber,columnnumber):\n for line in range(linenumber):\n for column in range(columnnumber):\n if data_board_array[line][column] != -1:\n if display_board_array[line][column] == \"o\" or display_board_array[line][column] == \"F\":\n return False\n else:\n continue\n else:\n continue\n return True\n\ndef display_bomb(display_board_array,data_board_array,linenumber,columnnumber):\n for line in range(linenumber):\n for column in range(columnnumber):\n if data_board_array[line][column] == -1:\n display_board_array[line][column] = \"x\"\n else:\n continue\n\nsparebombnumber = copy.deepcopy(bombnumber)\nwhile True:\n if judge_game_clear(display_board_array,data_board_array,linenumber,columnnumber):\n display_board_func(display_board_array,linenumber,columnnumber)\n print(\"おめでとうございます!ゲームクリアです!\")\n break\n display_board_func(display_board_array,linenumber,columnnumber)\n print(\"残りの地雷数:\",end=\"\")\n print(sparebombnumber)\n while True:\n print(\"d:掘る, f;旗を立てる, c:旗を消す\")\n command = input(\"行動を入力してください:\")\n if command == \"d\":\n print(\"どこを掘りますか?\")\n break\n elif command == \"f\":\n print(\"どこに旗を建てますか?\")\n break\n elif command == \"c\":\n print(\"どこの旗を消しますか?\")\n break\n else:\n print(\"入力が間違っています\")\n continue\n line_dig_point = input_linenumber(linenumber)\n line_dig_point -= 1\n column_dig_point = input_columnnumber(columnnumber)\n column_dig_point -= 1\n if command == \"d\":\n if display_board_array[line_dig_point][column_dig_point] == \"F\":\n print(\"旗があります!\")\n continue\n elif display_board_array[line_dig_point][column_dig_point] != \"o\":\n print(\"そこは掘れません\")\n continue\n elif data_board_array[line_dig_point][column_dig_point] == -1:\n display_board_array[line_dig_point][column_dig_point] = \"x\"\n display_board_func(display_board_array,linenumber,columnnumber)\n print(\"残念!地雷がありました...\")\n display_bomb(display_board_array,data_board_array,linenumber,columnnumber)\n display_board_func(display_board_array,linenumber,columnnumber)\n print(\"GAME OVER\")\n break\n elif data_board_array[line_dig_point][column_dig_point] == 0:\n find_blank_space(display_board_array,data_board_array,line_dig_point,column_dig_point)\n else:\n display_board_array[line_dig_point][column_dig_point] = str(data_board_array[line_dig_point][column_dig_point])\n elif command == \"f\":\n if display_board_array[line_dig_point][column_dig_point] != \"o\":\n print(\"そこに旗は立てられません\")\n continue\n else:\n display_board_array[line_dig_point][column_dig_point] = \"F\"\n sparebombnumber -= 1\n elif command == \"c\":\n if display_board_array[line_dig_point][column_dig_point] != \"F\":\n print(\"そこに旗はありません\")\n continue\n else:\n display_board_array[line_dig_point][column_dig_point] = \"o\"\n sparebombnumber += 1\n else:\n print(\"入力が間違っています\")"
},
{
"alpha_fraction": 0.4754672944545746,
"alphanum_fraction": 0.5097352266311646,
"avg_line_length": 24.949495315551758,
"blob_id": "2804913ebd96fd5b4e1ba2f9bd951b6781ae5888",
"content_id": "7616f2632ce1cfb084d2b5f4ee112919ce38a42f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2678,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 99,
"path": "/info_system_3/82.py",
"repo_name": "morutole/University",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nI_x = 1.9\nI_y = 1.6\nI_z = 2.0\nI = np.array([I_x, I_y, I_z])\ndiff = 1e-2\nsigma_w = 1e-2\nsigma_v = 4e-2\n\ndef Euler(u,noise_flag):\n x,y,z = u\n dxdt = (I_y - I_z)/I_x*y*z\n dydt = (I_z - I_x)/I_y*x*z\n dzdt = (I_x - I_y)/I_z*x*y\n if noise_flag:\n w = np.random.normal(loc = 0.0,scale = sigma_w, size = 3)\n else:\n w = np.zeros(3)\n return u + diff*(np.array([dxdt, dydt, dzdt]) + w/I)\n\nu_init = np.array([0.1, 17*2*np.pi/60 + 0.1, 0])\nu = [u_init]\n\nt = np.arange(0,40,diff)\n\nfor i in range(len(t)-1):\n u.append(Euler(u[-1],True))\n\nu = np.array(u)\n\nv = np.random.normal(loc = 0.0, scale = sigma_v, size = (u.shape[0], u.shape[1]))\n\ny = u + v\n\ndef Kalman_Filter(y_oberve):\n y_kalman = [y_oberve[0]]\n m = y_oberve[0]\n temp = np.full(3,sigma_w**2)\n V = np.diag(temp) #予測値の分散行列、テキトーに置いた\n temp = np.array([sigma_w**2/I_x**2, sigma_w**2/I_y**2, sigma_w**2/I_z**2]) #xにかかるノイズの分散行列\n Q = np.diag(temp)\n\n Ones = np.ones((3,3))\n Identity = np.identity(3)\n C = Identity #観測の行列\n temp = np.full(3,sigma_v**2)\n R = np.diag(temp) #観測ノイズの分散行列\n \n for i in range(1,u.shape[0]):\n #予測\n A = np.zeros((3,3))\n x,y,z = y_oberve[i]\n A[0][1] = (I_y - I_z)/I_x*z\n A[0][2] = (I_y - I_z)/I_x*y\n A[1][0] = (I_z - I_x)/I_y*z\n A[1][2] = (I_z - I_x)/I_y*x\n A[2][0] = (I_x - I_y)/I_z*y\n A[2][1] = (I_x - I_y)/I_z*x\n A *= diff\n A += Ones\n\n m = Euler(m,False)\n V = np.dot(A,np.dot(V,A.T)) + Q\n\n #修正\n P = la.inv(np.dot(C,np.dot(V, C.T) + R))\n K = np.dot(V,np.dot(C.T,P)) #カルマンゲイン\n m += np.dot(K,y_oberve[i] - np.dot(C,m))\n y_kalman.append(m)\n V = np.dot((Identity - C),V)\n \n y_kalman = np.array(y_kalman)\n return y_kalman\n\ny_kalman = Kalman_Filter(y)\n\nfor i in range(u.shape[1]):\n plt.plot(t,y[:,i], label = \"observe\")\n plt.plot(t,y_kalman[:,i], label = \"Kalman_Filter\")\n plt.plot(t,u[:,i], label = \"True\")\n plt.xlabel(\"t[s]\")\n if i == 0:\n plt.ylabel(r\"$\\omega_x$\")\n elif i == 1:\n plt.ylabel(r\"$\\omega_y$\")\n else:\n plt.ylabel(r\"$\\omega_z$\")\n plt.legend(loc = \"lower right\")\n if i == 0:\n plt.savefig(\"82x.png\",bbox_inches=\"tight\", pad_inches=0.05)\n elif i == 1:\n plt.savefig(\"82y.png\",bbox_inches=\"tight\", pad_inches=0.05)\n else:\n plt.savefig(\"82z.png\",bbox_inches=\"tight\", pad_inches=0.05)\n plt.show()"
}
] | 25 |
thejsa/fs3d-patch-kaeru-gallery | https://github.com/thejsa/fs3d-patch-kaeru-gallery | f3093d5b772b59d7ca1185ffbb917aa479bd4cc5 | 9ad97e442dd673e9d529e042ad92996649f0d3ed | 81db446793f42532e8f957012c27db74a575cbc3 | refs/heads/master | 2023-07-05T01:45:21.268820 | 2021-08-18T13:51:34 | 2021-08-18T13:51:34 | 332,282,548 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6920261979103088,
"alphanum_fraction": 0.6951078772544861,
"avg_line_length": 38.92307662963867,
"blob_id": "c2c075ca96d0a66895b410c6ba2c4cd8ec0006a6",
"content_id": "2cb6e0279a5fe443c90f3cda6fe78635b6492310",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5192,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 130,
"path": "/build.py",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "# Patch generator tool for Flipnote Studio 3D\n# Generates luma code patches which allow the app to connect to a custom server\n# Original patch written for Kaeru Gallery by Shutterbug2000\n# github.com/shutterbug2000\n# JPN support and Python tooling by Jaames\n# github.com/jaames | jamesdaniel.dev\n\nfrom sys import argv\nimport struct\nimport configparser\nimport pathlib\nimport shutil\nimport subprocess\n\nimport scripts.ips as Ips\nfrom scripts.darc import Darc\nfrom scripts.msbt import Msbt\n\nBLZ_PATH = './blz'\n\n# load config\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\n# check and load config data\n\nsections = config.sections()\nif 'SETUP' not in sections or 'EUR' not in sections or 'USA' not in sections or 'JPN' not in sections:\n exit('Config section missing, please check the project readme')\n\nCERT_A_SIZE_MAX = int(config['SETUP']['CERT_A_SIZE_MAX'])\nCERT_B_SIZE_MAX = int(config['SETUP']['CERT_B_SIZE_MAX'])\nGALLERY_URL_SIZE_MAX = int(config['SETUP']['GALLERY_URL_SIZE_MAX'])\n\nwith open(config['SETUP']['CERT_A_PATH'], 'rb') as f:\n cert_a_data = f.read()\n cert_a_size = len(cert_a_data)\n\nwith open(config['SETUP']['CERT_B_PATH'], 'rb') as f:\n cert_b_data = f.read()\n cert_b_size = len(cert_b_data)\n\ngallery_url = config['SETUP']['GALLERY_URL']\n\nif cert_a_size > CERT_A_SIZE_MAX:\n exit('Maximum filesize for cert A is', CERT_B_SIZE_MAX, 'bytes')\n\nif cert_b_size > CERT_B_SIZE_MAX:\n exit('Maximum filesize for cert B is', CERT_B_SIZE_MAX, 'bytes')\n\nif len(gallery_url) > GALLERY_URL_SIZE_MAX:\n exit('Gallery URL cannot exceed', GALLERY_URL_SIZE_MAX, 'characters')\n\ndef build_codebin(region_config, output_path):\n # Create new IPS patch file\n patch = Ips.IpsPatch()\n # Set cert sizes - these are both uint32\n patch.add_record(int(region_config['CERT_A_SIZE']), struct.pack('<I', cert_a_size))\n # not sure why this needs to be shorter than the actual cert size -- should investigate this\n # patch.add_record(region_config['CERT_B_SIZE'], struct.pack('<I', cert_b_size - 148))\n patch.add_record(int(region_config['CERT_B_SIZE']), struct.pack('<I', cert_b_size))\n # Null out the ARM branch-if-equal operation that jumps into the NASC check\n # This is necessary since Nintendo's NASC server no longer supports Flipnote Studio 3D\n patch.add_record(int(region_config['NASC_BRANCH']), bytes(4))\n # Patch SSL certs\n patch.add_record(int(region_config['CERT_A_DATA']), cert_a_data)\n patch.add_record(int(region_config['CERT_B_DATA']), cert_b_data)\n # Null out the rest of the old cert data\n patch.add_record(int(region_config['CERT_A_DATA']) + cert_a_size, bytes(CERT_A_SIZE_MAX - cert_a_size))\n patch.add_record(int(region_config['CERT_B_DATA']) + cert_b_size, bytes(CERT_B_SIZE_MAX - cert_b_size))\n # add url\n patch.add_record(int(region_config['GALLERY_URL']), gallery_url.encode('ascii'))\n # null out rest of the url\n patch.add_record(int(region_config['GALLERY_URL']) + len(gallery_url), bytes(GALLERY_URL_SIZE_MAX - len(gallery_url)))\n # Save to file\n patch.save(output_path)\n\ndef build_romfs_dir(src_path, output_path):\n # If the src is a file, copy it directly to the romfs output location\n if not src_path.is_dir():\n shutil.copy(str(src_path), str(output_path))\n # If the src directory name ends with .blz or .arc, compile its contents into an DARC file\n elif src_path.match('*.blz') or src_path.match('*.arc'): \n # Create a new DARC instance\n darc = Darc()\n # Loop through directory contents\n for child in src_path.iterdir():\n darc_entry = darc.root.add_entry()\n # If the file ends with .msbt.json, compile this to an .msbt\n if child.match('*.msbt.json'):\n print(child)\n msbt = Msbt.from_json(child)\n darc_entry.name = str(child.relative_to(src_path).with_suffix(''))\n darc_entry.data = msbt.write()\n # Else write the file as-is\n else:\n darc_entry.name = str(child.relative_to(src_path))\n darc_entry.data = child.read_bytes()\n darc.save(output_path)\n # If the directory name ends with .blz we also need to compress the resulting DARC archive\n if src_path.match('*.blz'):\n subprocess.call([BLZ_PATH, '-en', str(output_path)], stdout=subprocess.DEVNULL)\n # Otherwise make a new directory in the romfs output location\n else:\n output_path.mkdir(parents=True, exist_ok=True)\n # Recuresively repeat the process on all of its children\n for child in src_path.iterdir():\n build_romfs_dir(child, output_path / child.name)\n\nfor region in ['EUR', 'USA', 'JPN']:\n\n region_config = config[region]\n output_path = pathlib.Path('./luma/titles/%s' % region_config['TITLE_ID'])\n output_path.mkdir(parents=True, exist_ok=True)\n \n # Generate code.bin patches\n build_codebin(region_config, output_path / 'code.ips')\n\n # Create regional romfs files\n romfs_src_path = pathlib.Path('./%s/romfs' % region)\n romfs_output_path = output_path / 'romfs/'\n if romfs_src_path.exists():\n build_romfs_dir(romfs_src_path, romfs_output_path)\n\n # Add global romfs files\n romfs_src_path = pathlib.Path('./ALL/romfs')\n romfs_output_path = output_path / 'romfs/'\n if romfs_src_path.exists(): \n build_romfs_dir(romfs_src_path, romfs_output_path)\n\n\n"
},
{
"alpha_fraction": 0.5877034068107605,
"alphanum_fraction": 0.7459312677383423,
"avg_line_length": 25.33333396911621,
"blob_id": "ac68edb6a114b2d4eadd95eed55d360b3779879d",
"content_id": "96c9e62382adf0da02f3ed7c638de78de4ac99b6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 1106,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 42,
"path": "/config.ini",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "[SETUP]\n; This is the URL that the app will connect to instead of Flipnote Gallery World / DSi Gallery\nGALLERY_URL = https://gallery-ctr.kaeru.world\n; Paths to .DER format SSL certificate files for the Gallery server\n; You'll need to provide these yourself\nCERT_A_PATH = ./dst_root_ca_x3.der\n; CERT_B_PATH = ./digicert_global_root_ca.der\nCERT_B_PATH = ./aaa_certificate_services.der\n; Don't change these:\nCERT_A_SIZE_MAX = 969\nCERT_B_SIZE_MAX = 1239\nGALLERY_URL_SIZE_MAX = 36\n\n; The following section are offsets and titleIDs for patched code\n; Please don't edit these unless you really know what you're doing!\n\n[EUR]\nTITLE_ID = 00040000000c6700\nCERT_A_SIZE = 637956\nCERT_B_SIZE = 637964\nNASC_BRANCH = 2133192\nCERT_A_DATA = 2489456\nCERT_B_DATA = 2490425\nGALLERY_URL = 2728724\n\n[USA]\nTITLE_ID = 00040000000c6600\nCERT_A_SIZE = 637956\nCERT_B_SIZE = 637964\nNASC_BRANCH = 2133192\nCERT_A_DATA = 2489456\nCERT_B_DATA = 2490425\nGALLERY_URL = 2728724\n\n[JPN]\nTITLE_ID = 0004000000056c00\nCERT_A_SIZE = 727848\nCERT_B_SIZE = 727856\nNASC_BRANCH = 2229332\nCERT_A_DATA = 2588080\nCERT_B_DATA = 2589049\nGALLERY_URL = 2838432\n"
},
{
"alpha_fraction": 0.6988416910171509,
"alphanum_fraction": 0.7014157176017761,
"avg_line_length": 25.65517234802246,
"blob_id": "eda8ae230a8c21c2c09fb56ce8eb3c45e146b44c",
"content_id": "b9b307190c848ed7b43d531ee487b616c5b96547",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 777,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 29,
"path": "/extract_darc.py",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "# Small utility to extract a DARC file's contents to a folder\n# + Decompile .msbt translation files to an .msbt.json\n\nfrom scripts.darc import Darc\nfrom scripts.msbt import Msbt\n\nfrom sys import argv\nfrom pathlib import Path\nfrom io import BytesIO\nimport json\n\ndarc = Darc.Open(argv[1])\noutputDir = Path(argv[2])\noutputDir.mkdir(parents=True, exist_ok=True)\n\nfor entry in darc.root.entries:\n path = Path(entry.name)\n # If the file is an .msbt, convert it to .msbt.json\n if path.suffix == '.msbt':\n msbt = Msbt()\n msbt.read(BytesIO(entry.data))\n filepath = outputDir / path\n filepath = filepath.with_suffix('.msbt.json')\n msbt.dump_json(filepath)\n\n else:\n filepath = outputDir / path\n with filepath.open(mode='wb') as fp:\n fp.write(entry.data)\n "
},
{
"alpha_fraction": 0.5932203531265259,
"alphanum_fraction": 0.6201550364494324,
"avg_line_length": 30.84518814086914,
"blob_id": "2d99736fc422f613634a2c2914803815bc064f82",
"content_id": "43efc1958319b829eb024b518c8825c56b609fca",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7611,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 239,
"path": "/scripts/msbt.py",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "# MSBT lib\n# Compiles and decompiles .msbt text translation files\n# Written by Jaames\n# github.com/jaames | jamesdaniel.dev\n\n# Format (as used by Flipnote Studio 3D)\n# ======\n# Header\n# - char[8] magic 'MsgStdBn'\n# - uint16 byte order mark (0xFFFE = little endian)\n# - uint16 unknown1 (0)\n# - uint16 unknown2 (769)\n# - uint16 number of sections\n# - uint16 unknown3 (0)\n# - uint32 filesize\n# Section Header\n# - char[4] section type\n# - uint32 section size (this is rounded up to nearest multiple of 0x10 bytes)\n# - null[8] unused / padding\n# LBL1 Section\n# - uint32 number of groups\n# - label groups (8 bytes * number of groups)\n# - uint32 number of labels - this can be 0 if the group is empty\n# - uint32 label offset, relative to the start of this section\n# if there's more than one label in the group, the \n# - labels\n# - uint8 label size\n# - char[label size] label text\n# - uint32 string index for TXT2 section\n# TXT2 Section\n# - uint32 number of strings\n# - uint32[number of strings] - string offsets\n# - strings\n# - UTF-16 string terminated with a single null char (0x0000)\n# ATR1 Section\n# - uint32 number of non-empty groups\n# - uint32 - always 0\n\nimport struct\nimport json\n\nMAGIC = b'MsgStdBn'\n\nclass MsbtEntry:\n def __init__(self, label='', text=''):\n self.label = label\n self.text = text\n\nclass MsbtGroup:\n def __init__(self):\n self.entries = []\n\n def add_entry(self, label='', text=''):\n entry = MsbtEntry(label, text)\n self.entries.append(entry)\n return entry\n\nclass Msbt:\n def __init__(self):\n self.endian = '<'\n self.groups = []\n\n @classmethod\n def Open(cls, path):\n with open(path, 'rb') as fp:\n msbt = cls()\n msbt.read(fp)\n return msbt\n\n @classmethod\n def from_json(cls, path):\n msbt = cls()\n with open(path, 'r') as fp:\n data = json.loads(fp.read())\n for group in data['groups']:\n msbt_group = msbt.add_group()\n for entry in group:\n msbt_entry = msbt_group.add_entry()\n msbt_entry.label = entry['label']\n msbt_entry.text = entry['text']\n return msbt\n\n def save(self, path):\n with open(path, 'wb') as fp:\n fp.write(self.write())\n\n def add_group(self):\n group = MsbtGroup()\n self.groups.append(group)\n return group\n\n def read_string(self, buffer, offset):\n cur = buffer.tell()\n buffer.seek(offset)\n result = bytes()\n while True:\n char = buffer.read(2)\n if char != b'\\x00\\x00':\n result += char\n else:\n buffer.seek(cur)\n return result.decode('UTF-16' + 'LE' if self.endian == '<' else 'BE')\n \n def read(self, buffer):\n magic, byte_order_mark = struct.unpack('>8sH', buffer.read(10))\n if magic != MAGIC:\n print('invalid MSBT magic')\n exit()\n\n self.endian = '<' if byte_order_mark == 0xFFFE else '>'\n unknown1, unknown2, num_sections, unknown3, filesize = struct.unpack('%s4HI'%self.endian, buffer.read(12))\n\n buffer.seek(10, 1) # skip padding (?)\n\n lbl1_offset = 0\n atr1_offset = 0\n txt2_offset = 0\n\n for i in range(num_sections):\n magic, size, _ = struct.unpack('%s4sI8s'%self.endian, buffer.read(16))\n padded_size = size + (0x10 - (size % 0x10)) if size % 0x10 != 0 else size \n if magic == b'LBL1': lbl1_offset = buffer.tell()\n elif magic == b'ATR1': atr1_offset = buffer.tell()\n elif magic == b'TXT2': txt2_offset = buffer.tell()\n buffer.seek(padded_size, 1)\n\n strings = []\n buffer.seek(txt2_offset)\n num_strings = struct.unpack('%sI'%self.endian, buffer.read(4))[0]\n for i in range(num_strings):\n offset = struct.unpack('%sI'%self.endian, buffer.read(4))[0]\n strings.append(self.read_string(buffer, txt2_offset + offset))\n\n buffer.seek(lbl1_offset)\n num_groups = struct.unpack('%sI'%self.endian, buffer.read(4))[0]\n groups = [struct.unpack('%s2I'%self.endian, buffer.read(8)) for i in range(num_groups)]\n for num_labels, offset in groups:\n group = self.add_group()\n buffer.seek(lbl1_offset + offset)\n for i in range(num_labels):\n entry = group.add_entry()\n # read label\n label_size = ord(buffer.read(1))\n entry.label = buffer.read(label_size).decode('ascii')\n # get string index\n string_index = struct.unpack('%sI'%self.endian, buffer.read(4))[0]\n entry.text = strings[string_index]\n\n def dump_json(self, path):\n msbt_json = {\n 'groups': [],\n }\n for group in self.groups:\n group_json = []\n for entry in group.entries:\n group_json.append({\n 'label': entry.label,\n 'text': entry.text\n })\n msbt_json['groups'].append(group_json)\n with open(path, 'w') as fp:\n fp.write(json.dumps(msbt_json, ensure_ascii=False, indent=2, sort_keys=True))\n\n def write(self, little_endian=True):\n self.endian = '<' if little_endian else '>'\n\n # write txt2 section\n txt2 = bytes()\n strings = [entry.text for entry in sum([group.entries for group in self.groups], [])]\n num_strings = len(strings)\n # write number of strings\n txt2 += struct.pack('%sI'%self.endian, num_strings)\n # write string offsets\n # string offset is relative to the start of the txt2 section\n # so we account for the 4-byte num_strings and 4-byte offsets for each string\n offset = 4 + (num_strings * 4)\n for string in strings:\n txt2 += struct.pack('%sI'%self.endian, offset)\n # strings are 16-bits per char + 2 null bytes\n offset += (len(string) * 2) + 2\n # write strings\n for string in strings:\n txt2 += string.encode('UTF-16' + 'LE' if self.endian == '<' else 'BE')\n txt2 += bytes(2)\n txt2 = self.write_section(b'TXT2', txt2)\n\n # write atr1 section\n num_non_empty_groups = 0\n for group in self.groups:\n if len(group.entries) > 0:\n num_non_empty_groups += 1\n atr1 = self.write_section(b'ATR1', struct.pack('%sII'%self.endian, num_non_empty_groups, 0))\n\n # write lbl1 section\n # write number of groups\n lbl1 = bytes()\n num_groups = len(self.groups)\n lbl1 += struct.pack('%sI'%self.endian, num_groups)\n label_data = bytes()\n label_offset = 4 + (num_groups * 8)\n string_index = 0\n for group in self.groups:\n # write group\n lbl1 += struct.pack('%sII'%self.endian, len(group.entries), label_offset)\n # write group entries\n for entry in group.entries:\n # write label size\n label_size = len(entry.label)\n label_data += bytes([label_size])\n # write label\n label_data += entry.label.encode('ascii')\n # write string index\n label_data += struct.pack('%sI'%self.endian, string_index)\n label_offset += label_size + 5\n string_index += 1\n lbl1 += label_data\n lbl1 = self.write_section(b'LBL1', lbl1)\n\n filesize = 32 + len(lbl1) + len(atr1) + len(txt2)\n num_sections = 3\n # write header\n header = bytes()\n header += struct.pack('>8sH', MAGIC, 0xFFFE if little_endian else 0xFEFF)\n # pack unknown1, unknown2, num sections, unknown3, filesize\n header += struct.pack('%s4HI'%self.endian, 0, 769, num_sections, 0, filesize)\n header += bytes(10)\n return header + lbl1 + atr1 + txt2\n\n def write_section(self, section_magic, section_data):\n section_size = len(section_data)\n header = struct.pack('%s4sI'%self.endian, section_magic, section_size) + bytes(8)\n padding_size = (0x10 - (section_size % 0x10)) if section_size % 0x10 != 0 else 0\n return header + section_data + bytes([0xAB] * padding_size)\n\nif __name__ == '__main__':\n from sys import argv\n\n msbt = Msbt.Open(argv[1])\n msbt.save(argv[2])\n"
},
{
"alpha_fraction": 0.5966420769691467,
"alphanum_fraction": 0.6216216087341309,
"avg_line_length": 33.16083908081055,
"blob_id": "dfb0d37846aca486016e32cfa6f95848b80ecdb1",
"content_id": "ed7ff1a8109f1cd8e34618685b856e88f5ddc8fb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4884,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 143,
"path": "/scripts/darc.py",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "# DARC lib\n# Compiles and decompiles .darc file archives\n# Compiled files have 1:1 parity to the ones produced by Nintendo\n# Written by Jaames\n# github.com/jaames | jamesdaniel.dev\n\nimport struct\n\nclass DarcEntry:\n def __init__(self, name='', data=bytes(0)):\n self.name = name\n self.data = data\n\nclass DarcGroup:\n def __init__(self, name=''):\n self.name = name\n self.entries = []\n \n def add_entry(self, name='', data=bytes(0)):\n entry = DarcEntry(name=name, data=data)\n self.entries.append(entry)\n return entry\n\nclass Darc:\n def __init__(self):\n self.root = DarcGroup()\n self.endian = '<'\n\n @classmethod\n def Open(cls, path):\n darc = cls()\n with open(path, 'rb') as f:\n darc.read(f)\n return darc\n \n def save(self, path):\n with open(path, 'wb') as f:\n f.write(self.write())\n\n def read_label(self, buffer, offset):\n cur = buffer.tell()\n buffer.seek(offset)\n result = bytes()\n while True:\n char = buffer.read(2)\n if char != b'\\x00\\x00':\n result += char\n else:\n buffer.seek(cur)\n return result.decode('UTF-16' + 'LE' if self.endian == '<' else 'BE')\n\n def read(self, buffer):\n magic, byte_order_mark = struct.unpack('>4sH', buffer.read(6))\n self.endian = '<' if byte_order_mark == 0xFFFE else '>'\n header_size, version, darc_size = struct.unpack('%sH2I'%self.endian, buffer.read(10))\n table_offset, table_size, data_offset = struct.unpack('%s3I'%self.endian, buffer.read(12))\n\n total_entries = 0\n entry_index = 0\n while True:\n buffer.seek(table_offset + entry_index * 12)\n label_offset, entry_offset, entry_size = struct.unpack('%s3I'%self.endian, buffer.read(12))\n # upper 16 bits indicates whether this is for a folder entry\n is_folder = label_offset & 0xFF000000\n label_offset &= 0x00FFFFFF\n # if folder entry (there doesnt seem to be subfolders, just a single root folder)\n if is_folder:\n # get entry count from root node \n if label_offset == 0:\n self.root = DarcGroup()\n total_entries = entry_size\n # get root node label \n else:\n self.root.name = self.read_label(buffer, (table_offset + total_entries * 12) + label_offset)\n # if normal entry\n else:\n entry = self.root.add_entry()\n buffer.seek(entry_offset)\n entry.data = buffer.read(entry_size)\n entry.name = self.read_label(buffer, (table_offset + total_entries * 12) + label_offset)\n \n entry_index += 1\n if entry_index >= total_entries:\n break\n\n def write_label(self, label):\n return label.encode('UTF-16' + 'LE' if self.endian == '<' else 'BE') + bytes(2)\n \n def write(self, little_endian=True):\n self.endian = '<' if little_endian else '>'\n \n labels = bytes(2) # label data always begins with 2 empty bytes?\n label_offsets = []\n data = bytes()\n data_offsets = []\n # add root label, which is always '.'\n labels += self.write_label('.')\n # pack entry labels + data\n num_entries = len(self.root.entries) + 2\n # sort entries by alphabetical order\n for entry in sorted(self.root.entries, key=lambda entry: entry.name): \n label_offsets.append(len(labels))\n data_offset = len(data)\n # align data offset to a multiple of 0x80\n if data_offset % 0x80 != 0:\n align = 0x80 - data_offset % 0x80\n data += bytes(align)\n data_offset += align\n data_offsets.append(data_offset)\n labels += self.write_label(entry.name)\n data += entry.data\n\n # add padding to the label section so that the data section aligns to a multiple of 0x80\n table_size = (num_entries * 12) + len(labels)\n base_data_offset = 28 + table_size\n if base_data_offset % 0x80 != 0:\n align = 0x80 - base_data_offset % 0x80\n labels += bytes(align)\n base_data_offset += align\n\n # write entry table\n table = bytes()\n # add root node\n table += struct.pack('%s3I'%self.endian, 0x01000000, 0, num_entries)\n # add root label node\n table += struct.pack('%s3I'%self.endian, 0x01000002, 0, num_entries)\n # write entries\n for i in range(num_entries - 2):\n label_offset = label_offsets[i]\n data_offset = base_data_offset + data_offsets[i]\n data_size = len(self.root.entries[i].data)\n # pack table entry\n table += struct.pack('%s3I'%self.endian, label_offset, data_offset, data_size)\n\n # write header\n header = bytes()\n # pack magic + byte order mark\n header += struct.pack('>4sH', b'darc', 0xFFFE if little_endian else 0xFEFF)\n # pack headersize, version, filesize\n header += struct.pack('%sH2I'%self.endian, 28, 16777216, base_data_offset + len(data))\n # pack table offset, table size, data offset\n header += struct.pack('%s3I'%self.endian, 28, table_size, base_data_offset)\n return header + table + labels + data"
},
{
"alpha_fraction": 0.7403285503387451,
"alphanum_fraction": 0.7710651755332947,
"avg_line_length": 59.90322494506836,
"blob_id": "9d2de0a5663634994b56b0c68b6ae8442d437295",
"content_id": "582c81ff2c76c2762935d74b72f905da7f11fd66",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1887,
"license_type": "permissive",
"max_line_length": 271,
"num_lines": 31,
"path": "/readme.md",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "## FS3D Patch Tool\n\nGenerate [luma](https://github.com/AuroraWright/Luma3DS) code patches for Flipnote Studio 3D which allow the app to connect to a custom Flipnote Gallery World replacement server. Currently used to generate patches for [Kaeru Gallery](https://kaeru.world/kw).\n\n### Features\n\n* No source files necessary\n* Out-of-the-box support for the latest version of FS3D accross all regions (EUR/USA 1.0.1, JPN 1.3.3)\n* Translation file patches for text replacement, since Nintendo never finished translating strings for the online gallery feature.\n* Replaces the Flipnote Gallery World / DSi Gallery URL with a custom server URL\n* Patches out the NASC server check, since Nintendo's NASC server no longer officially supports FS3D\n* Replaces SSL certificates with your own .DER format certs\n\n### Usage\n\n1. Download this repo to your local machine.\n2. Install Python -- all scripts were tested on Python 3.7.1 but should work on 3.5 +\n3. Download and compile this [multiplatform version of `blz.c`](https://gist.github.com/thejsa/705a59a6c63989f752a32ce94b1849aa) and place it in the tool's root directory. You may need to adjust the `BLZ_PATH` variable on line 19 of `build.py` depending on your platform.\n4. Tweak `config.ini` to your needs, make sure you pay attention to the file comments.\n5. Generate the patch by running `python3 build.py`. This script will create a new `luma` folder which contains your patches\n6. Drop the `luma` folder into your 3DS' SD card root, [enable luma's game patching feature](https://github.com/AuroraWright/Luma3DS/wiki/Optional-features) and enjoy your patched version of Flipnote Studio 3D!\n\n### Todo\n\n* Tweak version strings, http headers, etc (?)\n* Texture replacements (?)\n\n### Credits\n\n* [Shutterbug2000](https://github.com/shutterbug2000) - Original code patch\n* [Jaames](https://github.com/jaames) - Japanese region port, Python tooling"
},
{
"alpha_fraction": 0.5995454788208008,
"alphanum_fraction": 0.6100000143051147,
"avg_line_length": 27.960525512695312,
"blob_id": "2cc83e3ec4793b184afd5b5075b27ce74f7c3375",
"content_id": "e5f9942e560fea235911e4dbdd42c97be069765d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2200,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 76,
"path": "/scripts/ips.py",
"repo_name": "thejsa/fs3d-patch-kaeru-gallery",
"src_encoding": "UTF-8",
"text": "# IPS lib\n# Allows .ips patch files to be generated without needing the target file, as long as you know your target offsets\n# Written by Jaames\n# github.com/jaames | jamesdaniel.dev\n\nclass IpsRecord:\n def __init__(self, offset=0, data=bytes(0)):\n self.offset = offset\n self.data = data\n\nclass IpsPatch:\n def __init__(self):\n self.records = []\n\n def add_record(self, offset=0, data=bytes(0)):\n record = IpsRecord(offset, data)\n self.records.append(record)\n\n def write(self):\n # Write \"PATCH\" header\n result = b'PATCH'\n # Write records\n for record in self.records:\n result += record.offset.to_bytes(3, byteorder='big')\n data = record.data\n\n # if all bytes are the same\n if len(data) > 3 and all(byte == data[0] for byte in data):\n result += bytes(2) \n result += len(data).to_bytes(2, byteorder='big')\n result += bytes([data[0]])\n \n else:\n result += len(record.data).to_bytes(2, byteorder='big')\n result += record.data\n # Write \"EOF\" end of file marker\n result += b'EOF'\n return result\n\n def read(self, buffer):\n header = buffer.read(5)\n while True:\n chunk = buffer.read(3)\n\n # Break loop if end of file (\"EOF\") marker is reached\n if chunk == b'EOF':\n break;\n\n record_offset = int.from_bytes(chunk, byteorder='big')\n record_size = int.from_bytes(buffer.read(2), byteorder='big')\n\n # RLE entry\n if record_size == 0:\n count = int.from_bytes(buffer.read(2), byteorder='big')\n value = int.from_bytes(buffer.read(1), byteorder='big')\n self.add_record(offset=record_offset, data=bytes([value] * count))\n\n else: \n self.add_record(offset=record_offset, data=buffer.read(record_size))\n\n def save(self, path):\n with open(path, 'wb') as buffer:\n buffer.write(self.write())\n\n def dump(self, dir):\n for record in self.records:\n path = dir + '/' + ('0x%08x_0x%04x.bin' % (record.offset, len(record.data)))\n with open(path, 'wb') as f:\n f.write(record.data)\n\n @classmethod\n def Open(cls, path):\n with open(path, 'rb') as buffer:\n patch = IpsPatch()\n patch.read(buffer)\n return patch"
}
] | 7 |
zhentaowang/tensorflow | https://github.com/zhentaowang/tensorflow | 359f79d05d4375e799a600d75c6d12aca116f6bd | bc69c4ceed6544c109be5693eb40ddcf3a4eb95d | 0d7f65dcf49e432c7d4023ca5e0d0631b8fad2c0 | refs/heads/master | 2021-05-09T01:31:34.996662 | 2018-02-01T06:41:17 | 2018-02-01T06:41:17 | 119,807,112 | 3 | 0 | null | 2018-02-01T08:36:14 | 2018-02-01T08:34:37 | 2018-02-01T08:25:32 | null | [
{
"alpha_fraction": 0.6742382049560547,
"alphanum_fraction": 0.6760388016700745,
"avg_line_length": 31.08888816833496,
"blob_id": "de7a39817ff089776e28d017c73d94233d43e5a8",
"content_id": "4b8cf0527ab9b7cc58bed3a73f1fbb59e064ec52",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7220,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 225,
"path": "/tensorflow/contrib/py2tf/impl/api.py",
"repo_name": "zhentaowang/tensorflow",
"src_encoding": "UTF-8",
"text": "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Public API.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom functools import wraps\n\nimport gast\nimport six\n\nfrom tensorflow.contrib.py2tf.impl import config\nfrom tensorflow.contrib.py2tf.impl import conversion\nfrom tensorflow.contrib.py2tf.pyct import compiler\nfrom tensorflow.contrib.py2tf.pyct import parser\nfrom tensorflow.python.util import tf_inspect\n\n# TODO(mdan): Properly document the type hints.\n# TODO(mdan): Reduce the type hint information to (module, type).\n# (currently we require (module + class name, type))\n\n\ndef graph_ready(f):\n \"\"\"No-op decorator that explicitly marks a function as graph-ready.\n\n Graph-ready functions are assumed to not need any conversion.\n\n Args:\n f: Any callable.\n Returns:\n f itself.\n \"\"\"\n setattr(f, '__pyct_is_compile_decorator', True)\n return f\n\n\ndef convert_inline(f, *args, **kwargs):\n \"\"\"Shorthand to convert and call a function.\n\n For example, the following two statements are equivalent:\n\n @convert()\n def foo():\n ...\n foo(bar)\n\n def foo():\n ...\n convert_inline(foo, bar)\n\n Args:\n f: Function to convert. Only this call will be converted.\n *args: Passed through to f.\n **kwargs: Passed through to f, with the following exceptions:\n * arg_value_hints: A dict mapping parameter names to objects that can\n hint at the type of those parameters.\n\n Returns:\n The result of the converted f applied to args and kwargs.\n \"\"\"\n if 'arg_value_hints' in kwargs:\n arg_value_hints = kwargs['arg_value_hints']\n del kwargs['arg_value_hints']\n else:\n arg_value_hints = None\n if tf_inspect.ismethod(f):\n # When converting methods, the result is still an unbound function.\n args = (f.__self__,) + args\n return convert(arg_value_hints)(f)(*args, **kwargs)\n\n\ndef convert(recursive=False, arg_types=None):\n \"\"\"Decorator that compiles a function to graph mode.\n\n The decorator is dynamic - invoking compilation whenever the decorated function\n is called. This means the parameter values are known at compilation.\n\n Args:\n recursive: Whether to recusrively convert any functions that the decorator\n function may call.\n arg_types: See to_graph.\n\n Returns:\n A decorator that compiles the given function to graph mode.\n\n Raises:\n ValueError: If any of the arguments are illegal.\n \"\"\"\n if arg_types is None:\n arg_types = {}\n\n def decorator(f):\n \"\"\"Decorator implementation.\"\"\"\n\n @wraps(f)\n def wrapper(*args, **kwargs):\n \"\"\"Wrapper that calls the compiled version of the wrapped function.\"\"\"\n partial_types = ()\n arg_values = {}\n arg_names = tf_inspect.getargspec(f)[0]\n for name, arg in zip(arg_names, args):\n arg_values[name] = arg\n arg_class = arg.__class__\n # If arg_value_hints specifies any name, use that instead.\n if name not in arg_types:\n arg_types[name] = (arg_class.__name__, arg_class)\n if name == 'self' and tf_inspect.isclass(arg_class):\n # Annotated methods need to specify that their owner type is partial,\n # otherwise other members they call will not be converted.\n partial_types = (arg_class,)\n wrapped = to_graph(\n f,\n recursive=recursive,\n arg_values=arg_values,\n arg_types=arg_types,\n partial_types=partial_types)\n return wrapped(*args, **kwargs)\n\n # Sometimes the decorator is just desugared, making it impossible to detect.\n # This attribute makes detection easier.\n setattr(wrapper, '__pyct_is_compile_decorator', True)\n return wrapper\n\n return decorator\n\n\ndef to_graph(e,\n recursive=True,\n arg_values=None,\n arg_types=None,\n partial_types=None):\n \"\"\"Compile a Python entity into equivalent TensorFlow code.\n\n Currently supported entities:\n * functions\n * classes\n\n Classes are handled by converting all their methods into a new class.\n\n Args:\n e: A Python entity.\n recursive: Whether to recusrively convert any functions that the decorator\n function may call.\n arg_values: A dict containing value hints for symbols like function\n parameters.\n arg_types: A dict containing type hints for symbols like function\n parameters.\n partial_types: A set of types (e.g. classes) that will not be converted\n entirely. Calls to member functions for these types will be renamed\n independently.\n\n Returns:\n A function with a signature identical to `o`, but which when executed it\n creates TF a graph that has the same functionality as the original entity.\n \"\"\"\n conversion_map = conversion.ConversionMap(\n recursive=recursive,\n nocompile_decorators=(convert, graph_ready, convert_inline),\n partial_types=partial_types)\n _, name = conversion.entity_to_graph(e, conversion_map, arg_values, arg_types)\n\n module = gast.Module([])\n for import_line in config.COMPILED_IMPORT_STATEMENTS:\n module.body.append(parser.parse_str(import_line))\n for dep in conversion_map.dependency_cache.values():\n module.body.append(dep)\n compiled_node = compiler.ast_to_object(module)\n\n # The compiled code should see everything the entry function saw.\n # TODO(mdan): This might not work well if the call tree spans modules?\n if tf_inspect.isfunction(e):\n compiled_node.__dict__.update(six.get_function_globals(e))\n\n compiled_fn = getattr(compiled_node, name)\n return compiled_fn\n\n\ndef to_code(e,\n recursive=True,\n arg_values=None,\n arg_types=None,\n partial_types=None,\n indentation=' '):\n \"\"\"Return the equivalent of an entity in TensorFlow code.\n\n See `to_graph` for more details.\n\n Args:\n e: A Python entity.\n recursive: See to_graph.\n arg_values: See to_graph.\n arg_types: See to_graph.\n partial_types: See to_graph.\n indentation: String, when to use for each level of indentation.\n\n Returns:\n String.\n \"\"\"\n conversion_map = conversion.ConversionMap(\n recursive=recursive,\n nocompile_decorators=(convert, graph_ready, convert_inline),\n partial_types=partial_types)\n conversion.entity_to_graph(e, conversion_map, arg_values, arg_types)\n\n imports = '\\n'.join(config.COMPILED_IMPORT_STATEMENTS)\n code = '\\n'.join(\n compiler.ast_to_source(dep, indentation)\n for dep in reversed(tuple(\n six.itervalues(conversion_map.dependency_cache))))\n\n return imports + '\\n\\n' + code\n"
}
] | 1 |
gennad/.ipython | https://github.com/gennad/.ipython | f41660e3b2e8f3b79cf1b26238a7a2886d95f980 | 622f8f5db8b5751a5fbfc52feb779a1d55ba25fd | 73c5c5a7139d4d109e4c8a691ffc9b33414338ce | refs/heads/master | 2021-01-10T18:22:26.111805 | 2012-10-29T21:12:49 | 2012-10-29T21:12:49 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7948718070983887,
"alphanum_fraction": 0.7948718070983887,
"avg_line_length": 22.399999618530273,
"blob_id": "76912221eb8d0cd4235a75b720988ec49bfdbe0d",
"content_id": "b6582f733f0d8a7390149fc880e62448ac720186",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 117,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 5,
"path": "/profile_default/startup/00-initial.py",
"repo_name": "gennad/.ipython",
"src_encoding": "UTF-8",
"text": "import datetime as dtt\nfrom datetime import date as d\nfrom datetime import time as t\nimport os, sys\nimport ipdb as i\n"
},
{
"alpha_fraction": 0.6761904954910278,
"alphanum_fraction": 0.6761904954910278,
"avg_line_length": 33.66666793823242,
"blob_id": "38e806b761ad9b51b5f1eb4299a438e7d5db8b84",
"content_id": "4356d3f4bc95638c976441dc13a9d52c6e76b25a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 105,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 3,
"path": "/profile_default/startup/01-aliases.py",
"repo_name": "gennad/.ipython",
"src_encoding": "UTF-8",
"text": "a = get_ipython()\na.alias_manager.define_alias('vim', 'vim')\na.alias_manager.define_alias('git', 'git')\n\n"
}
] | 2 |
Naimix/Python-AWS-Boto-Tools | https://github.com/Naimix/Python-AWS-Boto-Tools | e8090a23af804c185dca216635502185a1c22ca9 | c4229e17bac3bfd29dd27a563bebada2ac1e9991 | ee176147ba185d4dd28707499e570d24bdbfe454 | refs/heads/master | 2016-09-09T11:55:36.620788 | 2014-11-14T21:23:02 | 2014-11-14T21:23:02 | 24,272,341 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6820564270019531,
"alphanum_fraction": 0.6905415654182434,
"avg_line_length": 26.621429443359375,
"blob_id": "202c1b45040db7fa270a4bce03f6a9c5fdefe765",
"content_id": "86fac7d9d1968f6e01522f6791e2e565d76a590c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4007,
"license_type": "permissive",
"max_line_length": 206,
"num_lines": 140,
"path": "/README.md",
"repo_name": "Naimix/Python-AWS-Boto-Tools",
"src_encoding": "UTF-8",
"text": "# README #\r\n\r\nGain control of your AWS ec2 instances.\r\n\r\nThis script will allow you to stop/start, and check the status of your ec2 instances.\r\n\r\n**WARNING** These tools controls ec2 instance states.\r\n```\r\n WITH GREAT POWER COMES GREAT RESPONSIBILITY\r\n```\r\n\r\n\r\nPlease read, and make sure you understand this script, and what it does before using.\r\nI am not responsible if you accidentally shut down all your instances becuase you weren't paying attention.\r\n\r\n\r\nPre-requisits\r\n=======\r\nThis has only been tested on a Mac.\r\nPython 2.7 (Only tested in 2.7)\r\nAWS Boto module\r\n\r\n\r\nSet up\r\n=======\r\nPython versoin should be 2.7\r\n\r\n* Run the setup.py to set up a default region.\r\n\r\n* Ensure boto module is installed:\r\n\r\n* Ensure AWS keys are in a file in ~/.aws/credentials: in the following format:\r\n```\r\n [Credentials]\r\n aws_access_key_id = <your_access_key_here>\r\n aws_secret_access_key = <your_secret_key_here>\r\n \r\n```\r\n* Per [Boto Config detail guidelines](http://boto.readthedocs.org/en/latest/boto_config_tut.html#details).\r\n\r\n** Temporary Setup **\r\n* Until I get the setup sqared away, just make sure there's a \"settings.ini\" file in the libs/ directory. Example of settings.ini contents:\r\n```\r\n[default-region]\r\nregion = us-east-1\r\n\r\n[server-starting-order]\r\nservers = app,web\r\n\r\n```\r\n\r\nFilters included\r\n=======\r\n```\r\n-r|--reigion Specify region (other than default region).\r\n-n|--name Filter by tag:Name, if tag is used in your environment.\r\n-p|--project Filter by tag:Project PROJECT, if tag is used in your environment.\r\n-u|--usage Filter by tag:Usasge USAGE, if tag is used in your environment.\r\n-i|--instance-id Filter by Instance ID.\r\n-s|--state Filter by instance state.\r\n\r\n-d|--domain Specify a domain. If the domain is specified, the script will \r\n attempt to update route53 accordingly.\r\n\r\n```\r\n\r\n\r\nExamples\r\n=======\r\n```\r\npython SCRIPT -h\r\n-or-\r\n./SCRIPT --help\r\n Print help menu\r\n\r\n./ec2control.py\r\n Returns list of instances and instance information (from your default region).\r\n \r\n./ec2control.py -n prodweb01 stop\r\n Stop instance named prodweb01.\r\n\r\n./ec2control.py -P WebApp -U Staging start\r\n Start all instances with {tag:Project, WebApp}, and {tag:Usage, Staging}.\r\n\r\n./ec2control.py -s stopped\r\n Show all stopped instances (from your default region).\r\n\r\n./ec2control.py -r us-west-2 -s stopped\r\n Show all stopped instances from 'us-west-2' region.\r\n```\r\n\r\n\r\nNew Feature - Specify a startup order\r\n=======\r\nThe idea behind this, is to be able start groups of servers at a time, and account for dependancies in their starting order based on their hostname.\r\n\r\nTo do this, create a section called [server-starting-order] in the libs/settings.ini file.\r\nExample:\r\n```\r\n [servers]\r\n servers = app,web\r\n```\r\nIn the above example, if you were to run './ec2control.py -p NewProject -u Development start', the script will start all servers with a Project/Usage tag that match NewProject/Development respectively.\r\nWhile starting said hosts, any hosts with 'app' in their name will start first, followed by hosts with 'web' in their name. After those hosts start, the rest of the NewProject/Development hosts will start.\r\n\r\n\r\nContacts\r\n=======\r\n```\r\[email protected]\r\n\r\n```\r\n\r\nLicense\r\n=======\r\n```\r\nCopyright 2014 [email protected]\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\n```\r\n\r\n\r\nFuture Enhancements\r\n=======\r\n```\r\nIncreased Bug/Error handling\r\nRoute53 control (updating DNS on startup)\r\n\r\n```\r\n"
},
{
"alpha_fraction": 0.5610582232475281,
"alphanum_fraction": 0.5741248726844788,
"avg_line_length": 38.74359130859375,
"blob_id": "2a29410ee55064fd34bdfa8021f2efbe36b75d3e",
"content_id": "cbed5531ec7ede02ceed5a8eca565571aa0b8f34",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6199,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 156,
"path": "/libs/aws_connect.py",
"repo_name": "Naimix/Python-AWS-Boto-Tools",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n\"\"\"\nThis script uses boto module to create connector objects for AWS service management.\nCurrently works for\n ec2\n route53\n rds\n\nThis gets credentials based on a file in the executors home directory via:\n ~/.aws/credentials\nMore information on credentials can be found here:\n http://boto.readthedocs.org/en/latest/boto_config_tut.html \n\"\"\"\n__author__ = 'jeremymaldonado'\n\n\ntry:\n __import__('imp').find_module('boto')\nexcept ImportError:\n print \"Boto module not installed. Please make sure boto is installed before using these scripts.\"\n exit(1)\n\nfrom os import path, environ\nfrom ConfigParser import ConfigParser, NoSectionError, NoOptionError, ParsingError\nfrom boto import connect_ec2_endpoint, route53, exception, rds\nfrom sys import version_info\n\n\nclass AwsConnect(object):\n \"\"\"\n This class takes in a region as an argument, however is built to handle connections based on\n a default region in a settings file.\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n self.possible_regions = ['ap-northeast-1', 'ap-southeast-1',\n 'ap-southeast-2',\n 'eu-west-1',\n 'sa-east-1',\n 'us-east-1',\n 'us-west-1',\n 'us-west-2']\n self.credentials = None\n self.region = None\n\n def _get_credentials(self):\n \"\"\"\n Checking for AWS Credentials. Sets home environment then uses ConfigParser to check\n through credentials file. Use this to function to gather credentials.\n Using http://boto.readthedocs.org/en/latest/boto_config_tut.html as a guideline.\n\n @return: access_key, secret_key\n @rtype: list\n \"\"\"\n try:\n credentials_file = \"{0}/.aws/credentials\".format(environ['HOME'])\n if path.isfile(credentials_file):\n user_credentials = ConfigParser()\n section_credentials = user_credentials.read(credentials_file)\n user_credentials.read(section_credentials)\n self.credentials = [user_credentials.get('Credentials', 'aws_access_key_id'),\n user_credentials.get('Credentials', 'aws_secret_access_key')]\n else:\n print \"Error getting AWS Credentials.\\n{0} appears to be missing.\".format(credentials_file)\n exit(1)\n except NoSectionError, section_error:\n print \"\\nMissing [Credentials] section of the credentials file.\\nError: {0}\\n\".format(section_error)\n exit(1)\n except NoOptionError, option_error:\n print \"\\nMissing aws_access_key_id, and/or aws_secret_access_key in 'Credentials' section.\" \\\n \"Error: {0}\\n\".format(option_error)\n exit(1)\n except KeyError, home_var:\n print \"\\nError getting AWS Credentials. Missing $HOME variable.\\nError: {0}\\n\".format(home_var)\n exit(1)\n except ParsingError, parse_error:\n print \"\\nError parsing.\\nError: {0}\".format(parse_error)\n exit(1)\n\n def _get_default_region(self):\n region_parser = ConfigParser()\n settings_file = '{0}/settings.ini'.format(path.dirname(path.realpath(__file__)))\n try:\n region_parser.read(settings_file)\n self.region = region_parser.get('default-region', 'region')\n except NoOptionError:\n print \"\\nMissing settings file ({0}).\\n Please run the setup.py to set a default region.\\n\".format(\n settings_file)\n exit(1)\n except NoSectionError:\n print \"\\nMissing setting in file ({0}). Please run the setup.py to set a default region.\\n\".format(\n settings_file)\n exit(1)\n\n def connect_to_ec2(self, region=None):\n \"\"\"\n Connect to ec2, and return ec2 connect object\n @param region: str\n @return: ec2_conn\n \"\"\"\n self._get_credentials()\n if not region:\n self._get_default_region()\n if version_info[1] == 6:\n ec2_url = \"https://ec2.{0}.amazonaws.com\".format(self.region)\n else:\n ec2_url = \"https://{0}.ec2.amazonaws.com\".format(self.region)\n else:\n if version_info[1] == 6:\n ec2_url = \"https://ec2.{0}.amazonaws.com\".format(region)\n else:\n ec2_url = \"https://{0}.ec2.amazonaws.com\".format(region)\n try:\n return connect_ec2_endpoint(ec2_url, self.credentials[0], self.credentials[1])\n except exception.AWSConnectionError, conn_error:\n print \"\\nProblem connecting to AWS.\\nError: {0}\".format(conn_error)\n exit(1)\n\n def connect_to_r53_zone(self, domain):\n \"\"\"\n Connect to r53_zone, and return r53_zone connect object\n\n @param domain: str\n @return: r53_zone_conn\n \"\"\"\n self._get_credentials()\n try:\n r53conn = route53.connection.Route53Connection(aws_access_key_id=self.credentials[0],\n aws_secret_access_key=self.credentials[1])\n return r53conn.get_zone(domain)\n except exception.AWSConnectionError, conn_error:\n print \"Problem connecting to AWS.\\nError: {0}\".format(conn_error)\n\n def connect_to_rds(self, region=None):\n \"\"\"\n Connect to rds, and return rds connect object\n @param region: str\n @return: rds_conn\n \"\"\"\n self._get_credentials()\n if not region:\n self._get_default_region()\n region = self.region\n try:\n return rds.connect_to_region(region,\n aws_access_key_id=self.credentials[0],\n aws_secret_access_key=self.credentials[1])\n except exception.AWSConnectionError, conn_error:\n print \"\\nProblem connecting to AWS.\\nError: {0}\".format(conn_error)\n exit(1)\n\n\nif __name__ == '__main__':\n print(\"This file is not meant to be run directly.\")"
},
{
"alpha_fraction": 0.5964173078536987,
"alphanum_fraction": 0.6132771372795105,
"avg_line_length": 21.595237731933594,
"blob_id": "72d2d9b5956274aedfe913fa6ae7b48d779d62bc",
"content_id": "7a7b0d5ff0e00a655eefac9ca82cf2ea46a68971",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 949,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 42,
"path": "/get_r53_records.py",
"repo_name": "Naimix/Python-AWS-Boto-Tools",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\nThis script uses boto module to return r53 records.\n\"\"\"\n__author__ = 'jeremymaldonado'\n\nfrom libs.aws_connect import AwsConnect\nfrom sys import argv\nfrom os import path\n\n\ndef arguments():\n \"\"\"\n Parse arguments\n @return: str\n \"\"\"\n if not len(argv[1:]) == 1:\n print \"Incorrect arguments.\\n\\nUsage:\\n\\t{0} DOMAIN\\n\".format(path.basename(__file__))\n exit(1)\n else:\n return argv[1]\n\n\ndef get_cnames():\n \"\"\"\n Get domain name from arguments, and use AwsConnect() class to tap into route53 to retrieve records.\n @return print\n \"\"\"\n domain = arguments()\n r53 = AwsConnect().connect_to_r53_zone(domain)\n records = r53.get_records()\n #for record in records:\n # if record.type == 'CNAME':\n # print record\n #print [record for record in records]\n for record in records:\n print record\n\n\nif __name__ == '__main__':\n get_cnames()\n"
},
{
"alpha_fraction": 0.5762471556663513,
"alphanum_fraction": 0.5877739787101746,
"avg_line_length": 39.55172348022461,
"blob_id": "58a38438b45da6302d4509b841b3a12d1272732d",
"content_id": "c95cbea5884470d314ce55dea23538aa8d07c9d2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10584,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 261,
"path": "/ec2control.py",
"repo_name": "Naimix/Python-AWS-Boto-Tools",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\nThis script uses boto module to give user control to stop/start, or check the status if ec2 instances.\n\"\"\"\n__author__ = 'jeremymaldonado'\n\nfrom argparse import ArgumentParser as ArgParse, Namespace\nfrom os import path\nfrom libs.aws_connect import AwsConnect\nfrom ConfigParser import ConfigParser, NoSectionError, NoOptionError, ParsingError\nfrom time import sleep\n\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\n\ndef get_arguments():\n \"\"\"\n Parse arguments to be used in the remainder of the script.\n\n @return: User specified arguments.\n @rtype: Namespace\n \"\"\"\n description = \"\"\"\n python {0} [optional_flags] [optional_command]\n\n python {0} [-h|--help]\n\n\n Example:\n 'python {0} -r us-west-2 -n webhost01 status'\n 'python {0} -r us-east-1 -i i-1234abc start'\n \"\"\".format(path.basename(__file__))\n parser = ArgParse(usage=description)\n parser.add_argument(\"-r\", \"--region\", dest=\"region\",\n help=\"Filter by region\")\n parser.add_argument(\"-n\", \"--name\", dest=\"hostname\",\n help=\"Filter by hostname.\")\n parser.add_argument(\"-i\", \"--instance-id\", dest=\"iid\",\n help=\"Filter by instance-id.\")\n parser.add_argument(\"-p\", \"--project\", dest=\"project\",\n help=\"Filter by Project tag.\")\n parser.add_argument(\"-u\", \"--usage\", dest=\"usage\",\n help=\"Filter by Usage tag.\")\n parser.add_argument(\"-d\", \"--domain\", dest=\"domain\",\n help=\"Specify domain to add/remove CNAME using the hostname of each instance.\")\n parser.add_argument(\"-s\", \"--state\", dest=\"state\", choices=['running', 'stopped'],\n help=\"Filter by State.\")\n parser.add_argument(\"command\", default=\"status\", const=1, nargs='?', choices=['start', 'stop', 'status'],\n help=\"'status' is the assumed argument if none specified.\")\n arguments = vars(parser.parse_args())\n filter_dictionary = {}\n for item in arguments.keys():\n if arguments[item]:\n filter_dictionary.update({item: arguments[item]})\n return filter_dictionary\n\n\ndef connect_object(region=None):\n \"\"\"\n This creates the connection to AWS,and uses the libs.aws_connect.AwsConnect class.\n\n @param region: str\n @return: connection object\n \"\"\"\n possible_regions = ['ap-northeast-1',\n 'ap-southeast-1',\n 'ap-southeast-2',\n 'eu-west-1',\n 'sa-east-1',\n 'us-east-1',\n 'us-west-1',\n 'us-west-2']\n if region in possible_regions:\n return AwsConnect().connect_to_ec2(region)\n else:\n return AwsConnect().connect_to_ec2()\n\n\ndef get_starting_order():\n \"\"\"\n Check if there is a starting order section in the settings.ini file, and processing accordingly.\n Pay attention to detail when setting up a starting order. Any ConfigParser exceptions for this section\n are set to return None since this portion of the script is not required.\n @rtype : list\n @return:OrderedDict\n \"\"\"\n parser = ConfigParser()\n settings_file = '{0}/libs/settings.ini'.format(path.dirname(path.realpath(__file__)))\n try:\n parser.read(settings_file)\n server_list = [item.strip() for item in parser.get('server-starting-order', 'servers').split(',')]\n return server_list if server_list else None\n except (NoOptionError, NoSectionError, ParsingError):\n return None\n\n\ndef start_instances(conn, instance_ids, domain=None):\n \"\"\"\n Start instances\n\n If domain is provided, the script will attempt to create a CNAME record:\n Name_of_host.domain ==> Pub/Priv_DNS\n\n @param domain: Can contain domain name for CNAME Creation\n @param conn: connection object\n @param instance_ids: instance object\n @return: str\n \"\"\"\n item_dict = dict((instance.tags['Name'], instance.id) for instance in instance_ids)\n starting_order = get_starting_order()\n if domain:\n from boto.route53 import exception\n if starting_order:\n for string in starting_order:\n for server in item_dict.keys():\n if string in server:\n print \"Starting {0}\".format(server)\n conn.start_instances(instance_ids=item_dict[server])\n while conn.get_only_instances(item_dict[server])[0].state != 'running':\n print \"{0} status: {1}\".format(server, conn.get_only_instances(item_dict[server])[0].state)\n sleep(5)\n print \"{0} is up.\".format(server)\n if domain:\n r53_conn = AwsConnect().connect_to_r53_zone(domain)\n host_dns = conn.get_only_instances(item_dict[server])[0].public_dns_name if \\\n conn.get_only_instances(item_dict[server])[0].public_dns_name else \\\n conn.get_only_instances(item_dict[server])[0].private_dns_name\n try:\n print \"Creating CNAME record for {0}: {0}.{1} ==> {2}\".format(server, domain, host_dns)\n r53_conn.add_cname('{0}.{1}'.format(server, domain), host_dns)\n except AttributeError, exception.DNSServerError:\n print \"Error creating CNAME record for {0} on {1}\".format(server, domain)\n item_dict.pop(server)\n for server in item_dict.keys():\n print \"Starting {0}\".format(server, item_dict[server])\n conn.start_instances(instance_ids=item_dict[server])\n if domain:\n r53_conn = AwsConnect().connect_to_r53_zone(domain)\n host_dns = conn.get_only_instances(item_dict[server])[0].public_dns_name if \\\n conn.get_only_instances(item_dict[server])[0].public_dns_name else \\\n conn.get_only_instances(item_dict[server])[0].private_dns_name\n try:\n print \"Creating CNAME record for {0}: {0}.{1} ==> {2}\".format(server, domain, host_dns)\n r53_conn.add_cname('{0}.{1}'.format(server, domain), host_dns)\n except AttributeError, exception.DNSServerError:\n print \"Error creating CNAME record for {0} on {1}\".format(server, domain)\n\n\ndef stop_instances(conn, instance_ids, domain=None):\n \"\"\"\n Stop instances\n\n If domain is provided, the script will attempt to remove a CNAME record using:\n Name_of_host.domain ==> Pub/Priv_DNS\n\n @param domain: Can contain domain name for CNAME Creation\n @param conn: connection object\n @param instance_ids: instance object\n @return: str\n \"\"\"\n if domain:\n from boto.route53 import exception\n item_dict = dict((instance.tags['Name'], instance.id) for instance in instance_ids)\n for server in item_dict.keys():\n print \"Stopping {0}\".format(server, item_dict[server])\n if domain:\n r53_conn = AwsConnect().connect_to_r53_zone(domain)\n try:\n r53_conn.delete_cname('{0}.{1}'.format(server, domain))\n print \"Deleting CNAME record for: {0}.{1}\".format(server, domain)\n except AttributeError, exception.DNSServerError:\n print \"No CNAME record found for {0}.{1}\".format(server, domain)\n conn.stop_instances(instance_ids=item_dict[server])\n\n\ndef status_instances(instance_ids):\n \"\"\"\n Process isntance_ids and return a status of instances. This will show public IP/DNS if available,\n and show the private IP/DNS if not.\n\n @param instance_ids: instance object\n @return: str\n \"\"\"\n print \"{0:15s}{1:13s}{2:15s}{3:55s}{4:13s}{5:}\".format(\"Hostname\",\n \"InstanceID\",\n \"IP Address\",\n \"DNS\",\n \"Zone\",\n \"State\")\n for instance in instance_ids:\n print \"{0:15s}{1:13s}{2:15s}{3:55s}{4:13s}{5:}\".format(\n instance.tags['Name'],\n instance.id,\n instance.ip_address if instance.ip_address else instance.private_ip_address,\n instance.public_dns_name if instance.public_dns_name else instance.private_dns_name,\n instance.placement,\n instance.state)\n\n\ndef main():\n \"\"\"\n Get arguments, and process them into the ec2 filters, and act accordingly based on command\n\n @return: str\n \"\"\"\n # Get command, and region\n arguments = get_arguments()\n command = arguments.pop('command')\n if 'region' in arguments.keys():\n conn = connect_object(arguments.pop('region'))\n else:\n conn = connect_object()\n\n # Argument/Filter setup\n instance_filter = {}\n if 'hostname' in arguments.keys():\n instance_filter.update({'tag:Name': arguments['hostname']})\n if 'iid' in arguments.keys():\n instance_filter.update({'instance-id': arguments['iid']})\n if 'project' in arguments.keys():\n instance_filter.update({'tag:Project': arguments['project']})\n if 'usage' in arguments.keys():\n instance_filter.update({'tag:Usage': arguments['usage']})\n if 'state' in arguments.keys():\n instance_filter.update({'instance-state-name': arguments['state']})\n if 'domain' in arguments.keys():\n domain = arguments['domain']\n from boto.route53 import exception\n else:\n domain = None\n if not instance_filter:\n command = 'status'\n\n # Get instance_id objects using above instance_filter.\n instance_ids = conn.get_only_instances(filters=instance_filter)\n if not instance_ids:\n print \"No instances found with the specified filters.\"\n exit(1)\n\n # Process commands/instances\n if command == 'start':\n assert isinstance(instance_ids, object)\n start_instances(conn, instance_ids, domain)\n elif command == 'stop':\n assert isinstance(instance_ids, object)\n stop_instances(conn, instance_ids, domain)\n elif command == 'status':\n assert isinstance(instance_ids, object)\n status_instances(instance_ids)\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print \"\\nUser has exited the program.\"\n exit(0)\n"
},
{
"alpha_fraction": 0.6705882549285889,
"alphanum_fraction": 0.6705882549285889,
"avg_line_length": 20.25,
"blob_id": "bd2c57a2f1a12c674b860889eaaefb5a29b70b60",
"content_id": "f978f21e98d84db45f97a3d48cd31715b177e4ee",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 85,
"license_type": "permissive",
"max_line_length": 42,
"num_lines": 4,
"path": "/libs/__init__.py",
"repo_name": "Naimix/Python-AWS-Boto-Tools",
"src_encoding": "UTF-8",
"text": "#__all__ = ['aws_tools', 'starting_order']\n\n#import aws_tools\n#import starting_order\n"
}
] | 5 |
vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset | https://github.com/vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset | 855be67ffd23a4613bf575581cd55bb9d7155278 | 82d88d1c0dfe6d78bf57411800c985ad66d68a8d | 3f4bdf242c389acb11c53d359174c5b6979f22ca | refs/heads/master | 2022-07-27T04:30:31.113013 | 2019-08-02T08:08:23 | 2019-08-02T08:08:23 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5939849615097046,
"alphanum_fraction": 0.6265664100646973,
"avg_line_length": 36.40625,
"blob_id": "2fa088bb5284fea70b186856c3a438e6a66c333b",
"content_id": "08b2f90229af69f9e8c2df52e4f34f3e6321d5c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1197,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 32,
"path": "/05_kNN/kNN.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "from sklearn.cluster import KMeans\nfrom sklearn.neighbors import KNeighborsClassifier\nimport numpy as np\nimport pickle\n\n#=========================================== 01/ Import Input Data\nprint(\"\\n ==================================================================== IMPORT DATA...\")\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nseq_x = mnist.train.images #55000:784\nseq_y = mnist.train.labels #55000:10\nseq_x_test = mnist.test.images #10000:784\nseq_y_test = mnist.test.labels #10000:10\n\n#normalize input images\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nseq_x = scaler.fit_transform(seq_x)\nseq_x_test = scaler.fit_transform(seq_x_test)\n\n#tranfer input expected from one-hot format (2-D matrix) into one column vector\nseq_y = np.argmax(seq_y, axis=1)\nseq_y_test = np.argmax(seq_y_test, axis=1)\n\nprint(\"\\n ==================================================================== TRAINING...\")\nn_clusters = 10\nn_class = 10\nclassifier = KNeighborsClassifier(n_neighbors=n_clusters)\nclassifier.fit(seq_x, seq_y)\nacc = classifier.score(seq_x_test, seq_y_test)\nprint (acc)\n"
},
{
"alpha_fraction": 0.5942690968513489,
"alphanum_fraction": 0.6200166344642639,
"avg_line_length": 33.371429443359375,
"blob_id": "99962244e444448c0ebbb254b0ba8889a88a5d59",
"content_id": "9907b9a63a4bbad779f30ae9dfe805251718097d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2408,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 70,
"path": "/02_linear_SVM/svm_lin_grid_search.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport datetime as dt\n\nfrom sklearn import datasets, svm, metrics\nfrom sklearn.datasets import fetch_mldata\n#from mnist_helpers import *\n\n\n#=========================================== 01/ Import Input Data\nprint(\"\\n ==================================================================== IMPORT DATA...\")\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nseq_x = mnist.train.images #55000:784\nseq_y = mnist.train.labels #55000:10\nseq_x_test = mnist.test.images #10000:784\nseq_y_test = mnist.test.labels #10000:10\n\n#normalize input images energy from [0:255] into [0:1]\nseq_x = seq_x/255.0\nseq_x_test = seq_x_test/255.0\n\n#tranfer input expected from one-hot format (2-D matrix) into one column vector\nseq_y = np.argmax(seq_y, axis=1)\nseq_y_test = np.argmax(seq_y_test, axis=1)\n\n\n#=========================================== 02/ SVM setup with SKLEARN lib\nC_svm = np.outer(np.logspace(-1, 1, 3),np.array([1,5]))\nC_svm = C_svm.flatten()\nparameters = {'C':C_svm} #grid search only on C_svm para\n\nsvm_model = svm.LinearSVC()\n\nfrom sklearn.model_selection import GridSearchCV\nclassifier = GridSearchCV(estimator = svm_model,\n param_grid=parameters,\n n_jobs=1, \n verbose=2\n )\n\n#=========================================== 03/ Running SVM\nstart_time = dt.datetime.now()\nprint('Start learning at {}'.format(str(start_time)))\nclassifier.fit(seq_x, seq_y)\n\nend_time = dt.datetime.now() \nprint('Stop learning {}'.format(str(end_time)))\nelapsed_time= end_time - start_time\nprint('Elapsed learning {}'.format(str(elapsed_time)))\n\ngoal_classifier = classifier.best_estimator_\ngoal_paras = classifier.best_params_\n\n\nrange_C = classifier.cv_results_['param_C']\nave_score = classifier.cv_results_['mean_test_score']\nprint(range_C)\nprint(ave_score)\n#=========================================== 04/ Testing\nexpected = seq_y_test\npredicted = goal_classifier.predict(seq_x_test)\n\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\ncm = metrics.confusion_matrix(expected, predicted)\nprint(\"Confusion matrix:\\n%s\" % cm)\nprint(\"Accuracy={}\".format(metrics.accuracy_score(expected, predicted)))\n\n\n"
},
{
"alpha_fraction": 0.5410821437835693,
"alphanum_fraction": 0.5678022503852844,
"avg_line_length": 37.38461685180664,
"blob_id": "2bdf2ab1458811aabcb15458c675c6e4bfcc9d97",
"content_id": "4f9a8a9a91a66ef8acde6058c54f9bf7b647ac44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1497,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 39,
"path": "/04_Random_Forest/rf.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "from sklearn.ensemble import RandomForestClassifier\nimport numpy as np\nimport pickle\n\n#=========================================== 01/ Import Input Data\nprint(\"\\n ==================================================================== IMPORT DATA...\")\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nseq_x = mnist.train.images #55000:784\nseq_y = mnist.train.labels #55000:10\nseq_x_test = mnist.test.images #10000:784\nseq_y_test = mnist.test.labels #10000:10\n\n#normalize input images\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nseq_x = scaler.fit_transform(seq_x)\nseq_x_test = scaler.fit_transform(seq_x_test)\n\n#tranfer input expected from one-hot format (2-D matrix) into one column vector\nseq_y = np.argmax(seq_y, axis=1)\nseq_y_test = np.argmax(seq_y_test, axis=1)\n\n\nprint(\"\\n ==================================================================== TRAINING...\")\nclassifier = RandomForestClassifier(n_estimators=100, n_jobs=10,)\nclassifier.fit(seq_x,seq_y)\n\nprint(\"\\n ==================================================================== STORING PARA...\")\nwith open('RF_para','wb') as f:\n\tpickle.dump(classifier, f)\n\nprint(\"\\n ==================================================================== LOAD PARA & VERIFYING...\")\npickle_in = open('RF_para','rb')\ngoal_classifier = pickle.load(pickle_in)\n\nacc = goal_classifier.score(seq_x_test, seq_y_test)\nprint('RFC Score: ',acc)\n"
},
{
"alpha_fraction": 0.43882977962493896,
"alphanum_fraction": 0.48404255509376526,
"avg_line_length": 22.4375,
"blob_id": "d9cea9fb05494eaeafd8164343ed08e61bc8f405",
"content_id": "7e82123fa2fe8a5f34b6fca860ef85f1027a4f11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 376,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 16,
"path": "/01_softmax_regression/network/dnn_bl01_para.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport os\n\nclass dnn_bl01_para(object):\n \"\"\"\n define a class to store parameters\n \"\"\"\n\n def __init__(self):\n\n #=======Layer 01: Final layer\n self.l01_fc = 10 \n self.l01_is_act = False\n self.l01_act_func = 'RELU'\n self.l01_is_drop = False\n self.l01_drop_prob = 1\n\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.7126436829566956,
"avg_line_length": 19.076923370361328,
"blob_id": "fe08156be023b540cb90c8564875260e429c6f64",
"content_id": "5803db1761974bb7bbbfdeee4b1b8c5ef39cb7ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 261,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 13,
"path": "/README.md",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "# Basic Machine Learning Methods Applied on MNIST Handwritten Digit Dataset\n\n1/ Hierarchy:\n + 01_softmax_regression\t\n + 02_linear_SVM\n + 03_ker_svm\n + 04_Random_Forest\t\n + 05_kNN\t\n + README.md\n \n2/Notes:\n + All models base on SKLEARN library\n + Dataset : MNIST\n"
},
{
"alpha_fraction": 0.6139793395996094,
"alphanum_fraction": 0.6378077864646912,
"avg_line_length": 35.49275207519531,
"blob_id": "6e1a804c30cfb1d3fc1cbcbcecf20bd57d01ddd2",
"content_id": "65eb3ba9b6e6b9e328cb2006b2292e5583742b41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2518,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 69,
"path": "/02_linear_SVM/svm_lin.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport datetime as dt\n\nfrom sklearn import datasets, svm, metrics\nfrom sklearn.datasets import fetch_mldata\nfrom mnist_helpers import *\n\n\n#=========================================== 01/ Import Input Data\nprint(\"\\n ==================================================================== IMPORT DATA...\")\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nseq_x = mnist.train.images #55000:784\nseq_y = mnist.train.labels #55000:10\nseq_x_test = mnist.test.images #10000:784\nseq_y_test = mnist.test.labels #10000:10\n\n#scale input images energy from [0:255] into [0:1]\nseq_x = seq_x/255.0\nseq_x_test = seq_x_test/255.0\n\n#tranfer input expected from one-hot format (2-D matrix) into one column vector\nseq_y = np.argmax(seq_y, axis=1)\nseq_y_test = np.argmax(seq_y_test, axis=1)\n\n\n#=========================================== 02/ SVM setup with SKLEARN lib\nsvm_C = 5 #constant para\nclassifier = svm.LinearSVC(C=svm_C)\n\n#=========================================== 03/ Running SVM\nstart_time = dt.datetime.now()\nprint('Start learning at {}'.format(str(start_time)))\nclassifier.fit(seq_x, seq_y)\n\nend_time = dt.datetime.now() \nprint('Stop learning {}'.format(str(end_time)))\nelapsed_time= end_time - start_time\nprint('Elapsed learning {}'.format(str(elapsed_time)))\n\n#=========================================== 04/ Save SVM parameters\nfrom sklearn.externals import joblib\njoblib.dump(classifier, \"svm_linear_para.pkl\")\n\n#=========================================== 05/ Testing\nexpected = seq_y_test\npredicted = classifier.predict(seq_x_test)\n\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\ncm = metrics.confusion_matrix(expected, predicted)\nprint(\"Confusion matrix:\\n%s\" % cm)\nprint(\"Accuracy={}\".format(metrics.accuracy_score(expected, predicted)))\n\n#============================================= 06/ Loading saved parameters and verify again\nfrom sklearn.externals import joblib\nclassifier = joblib.load(\"svm_linear_para.pkl\")\n\nexpected = seq_y_test\npredicted = classifier.predict(seq_x_test)\n\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\ncm = metrics.confusion_matrix(expected, predicted)\nprint(\"Confusion matrix:\\n%s\" % cm)\nprint(\"Accuracy={}\".format(metrics.accuracy_score(expected, predicted)))\n"
},
{
"alpha_fraction": 0.592014491558075,
"alphanum_fraction": 0.6112522482872009,
"avg_line_length": 33.01234436035156,
"blob_id": "47b35924422865d6855a5a65a0fd065d7a57fb95",
"content_id": "8bf47c51c99e2d333555f536d4fd697bcc4f9eb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2755,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 81,
"path": "/03_ker_svm/svm_ker_grid_search.py",
"repo_name": "vinhnv27/Basic-Machine-Learning-Methods-Applied-on-MNIST-Handwritten-Digit-Dataset",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport time\nimport datetime as dt\n\nfrom sklearn import datasets, svm, metrics\nfrom sklearn.datasets import fetch_mldata\n\n\n#=========================================== 01/ Import Input Data\nprint(\"\\n ==================================================================== IMPORT DATA...\")\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nseq_x = mnist.train.images #55000:784\nseq_y = mnist.train.labels #55000:10\nseq_x_test = mnist.test.images #10000:784\nseq_y_test = mnist.test.labels #10000:10\n\n#normalize input images\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nseq_x = scaler.fit_transform(seq_x)\nseq_x_test = scaler.fit_transform(seq_x_test)\n\n#tranfer input expected from one-hot format (2-D matrix) into one column vector\nseq_y = np.argmax(seq_y, axis=1)\nseq_y_test = np.argmax(seq_y_test, axis=1)\n\n#=========================================== 02/ SVM setup with SKLEARN lib\ngamma_svm = np.outer(np.logspace(-3, 0, 4),np.array([1,5]))\ngamma_svm = gamma_svm.flatten()\nC_svm = np.outer(np.logspace(-1, 1, 3),np.array([1,5]))\nC_svm = C_svm.flatten()\n\nparameters = {'kernel': ['rbf'],\n 'C': C_svm,\n 'gamma': gamma_svm\n }\n\nsvm_model = svm.SVC()\n\nfrom sklearn.model_selection import GridSearchCV\nclassifier = GridSearchCV(estimator = svm_model,\n param_grid = parameters,\n n_jobs = 1, \n verbose = 2\n )\n\n#=========================================== 03/ Running SVM\nstart_time = dt.datetime.now()\nprint('Start learning at {}'.format(str(start_time)))\nclassifier.fit(seq_x, seq_y)\n\nend_time = dt.datetime.now() \nprint('Stop learning {}'.format(str(end_time)))\nelapsed_time= end_time - start_time\nprint('Elapsed learning {}'.format(str(elapsed_time)))\n\ngoal_classifier = classifier.best_estimator_\ngoal_params = classifier.best_params_\n\nfrom sklearn.externals import joblib\njoblib.dump(goal_classifier, \"svm_ker_grid_search_para.pkl\")\n\nrange_C = classifier.cv_results_['param_C']\nrange_gamma = classifier.cv_results_['param_gamma']\nscores = classifier.cv_results_['mean_test_score']\n\n#=========================================== 04/ Testing\nexpected = seq_y_test\npredicted = goal_classifier.predict(seq_x_test)\n\nprint(\"\\n Classification report for classifier: %s \\n\"\n % (goal_classifier))\nprint(\"\\n %s \\n\"\n % (metrics.classification_report(expected, predicted)))\nprint(\"\\n\")\ncm = metrics.confusion_matrix(expected, predicted)\nprint(\"Confusion matrix: \\n%s\" % cm)\nprint(\"\\n\")\nprint(\"Accuracy: {}\".format(metrics.accuracy_score(expected, predicted)))\n"
}
] | 7 |
lusoal/lamp_stack_poc | https://github.com/lusoal/lamp_stack_poc | 09447c67855e4e600c701dda47d95da87c0257ba | 16f37791dc013c602ea7b2436513d008d2f792e8 | 7b13f12261a1d4121a89c8d63908c3b274387483 | refs/heads/master | 2020-12-08T23:12:44.325501 | 2020-01-10T19:57:50 | 2020-01-10T19:57:50 | 233,120,778 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6225108504295349,
"alphanum_fraction": 0.656277060508728,
"avg_line_length": 27.875,
"blob_id": "5f7f797fbed8f1fd886c69b84a9144265c74bfbb",
"content_id": "7f75a81c12ae652a2ac446e940270d073975f8f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1155,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 40,
"path": "/locust/locustfile.py",
"repo_name": "lusoal/lamp_stack_poc",
"src_encoding": "UTF-8",
"text": "from locust import HttpLocust, TaskSet, task\n\n\n# GET https://wordpress.lucasduarte.club/\n# GET https://wordpress.lucasduarte.club/2020/01/07/teste/\n# GET https://wordpress.lucasduarte.club/2020/01/\n# GET https://wordpress.lucasduarte.club/category/uncategorized/\n# GET https://wordpress.lucasduarte.club/wp-login.php\n\nclass UserBehavior(TaskSet):\n def on_start(self):\n \"\"\" on_start is called when a Locust start before any task is scheduled \"\"\"\n \n @task(1) # Do not necessary need of the pipeline, just to orchestrate better\n def user_pipeline(self):\n self.index()\n self.get_categories()\n self.get_specific_post()\n self.get_wp_login()\n \n # Simulacao de Gets\n\n def index(self):\n self.client.get(\"/\")\n \n def get_specific_post(self):\n self.client.get(\"/2020/01/07/teste/\")\n \n def get_categories(self):\n self.client.get(\"/2020/01/02/hello-world/\")\n\n def get_wp_login(self):\n self.client.get(\"/wp-login.php\")\n\n # TODO: Criar fluxo de escrita de um novo post\n\nclass WebsiteUser(HttpLocust):\n task_set = UserBehavior\n min_wait = 5000\n max_wait = 9000\n"
}
] | 1 |
Intipy/spiking-neural-network | https://github.com/Intipy/spiking-neural-network | 948d41f633d5690cc3d0144d99d9be5c8b508f08 | cebe2f9ced20fd58d7d568f953b1198ce2b37122 | 5fbe895f91aafd52dbffc68ca35fd587ea6279eb | refs/heads/master | 2023-08-25T02:48:18.025116 | 2021-10-09T11:28:47 | 2021-10-09T11:28:47 | 400,960,042 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.38749998807907104,
"alphanum_fraction": 0.38749998807907104,
"avg_line_length": 10.571428298950195,
"blob_id": "2c50fea4047656ad451b822c985778069ac2e493",
"content_id": "7680a353765c08cc015bde2a00edb17452be8e8c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 80,
"license_type": "permissive",
"max_line_length": 20,
"num_lines": 7,
"path": "/SNN/__init__.py",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "__all__ = ['neuron',\n 'plot',\n 'model']\n\n\n\nfrom SNN import *"
},
{
"alpha_fraction": 0.5192677974700928,
"alphanum_fraction": 0.5269749760627747,
"avg_line_length": 41.61643981933594,
"blob_id": "8ed284ace3be2c21e35e44c0935f874cbc49a385",
"content_id": "52f895a42fc8f14b57b9a217c028edb367ac74ae",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3114,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 73,
"path": "/SNN/neuron.py",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\n\n\nclass LIF():\n def __init__(self, neuron_label = \"LIF\", debug=True):\n # Simulation config (may not all be needed!!)\n self.dt = 0.125 # simulation time step\n self.t_rest = 0 # initial refractory time\n\n # LIF Properties\n self.Vm = np.array([0]) # Neuron potential (mV)\n self.time = np.array([0]) # Time duration for the neuron (needed?)\n self.spikes = np.array([0]) # Output (spikes) for the neuron\n\n self.t = 0 # Neuron time step\n self.Rm = 1 # Resistance (kOhm)\n self.Cm = 10 # Capacitance (uF)\n self.tau_m = self.Rm * self.Cm # Time constant\n self.tau_ref = 4 # refractory period (ms)\n self.Vth = 0.75 # = 1 #spike threshold\n self.V_spike = 1 # spike delta (V)\n self.type = 'Leaky Integrate and Fire'\n self.neuron_label = neuron_label\n self.debug = debug\n if self.debug:\n print ('LIFNeuron({}): Created {} neuron starting at time {}'.format(self.neuron_label, self.type, self.t))\n\n def spike_generator(self, neuron_input):\n # Create local arrays for this run\n duration = len(neuron_input)\n Vm = np.zeros(duration) # len(time)) # potential (V) trace over time\n time = np.arange(int(self.t / self.dt), int(self.t / self.dt) + duration)\n spikes = np.zeros(duration) # len(time))\n\n # Seed the new array with previous value of last run\n Vm[-1] = self.Vm[-1]\n\n if self.debug:\n print ('LIFNeuron.spike_generator({}).initial_state(input={}, duration={}, initial Vm={}, t={}, debug={})'\n .format(self.neuron_label, neuron_input.shape, duration, Vm[-1], self.t, self.debug))\n\n for i in range(duration):\n if self.debug == 'INFO':\n print ('Index {}'.format(i))\n\n if self.t > self.t_rest:\n Vm[i] = Vm[i - 1] + (-Vm[i - 1] + neuron_input[i - 1] * self.Rm) / self.tau_m * self.dt\n\n if self.debug == 'INFO':\n print(\n 'spike_generator({}): i={}, self.t={}, Vm[i]={}, neuron_input={}, self.Rm={}, self.tau_m * self.dt = {}'\n .format(self.neuron_label, i, self.t, Vm[i], neuron_input[i], self.Rm, self.tau_m * self.dt))\n\n if Vm[i] >= self.Vth:\n spikes[i] += self.V_spike\n self.t_rest = self.t + self.tau_ref\n if self.debug:\n print ('*** LIFNeuron.spike_generator({}).spike=(self.t_rest={}, self.t={}, self.tau_ref={})'\n .format(self.neuron_label, self.t_rest, self.t, self.tau_ref))\n\n self.t += self.dt\n\n # Save state\n self.Vm = np.append(self.Vm, Vm)\n self.spikes = np.append(self.spikes, spikes)\n self.time = np.append(self.time, time)\n\n if self.debug:\n print ('LIFNeuron.spike_generator({}).exit_state(Vm={} at iteration i={}, time={})'\n .format(self.neuron_label, self.Vm.shape, i, self.t))\n\n # return time, Vm, output\n\n\n\n"
},
{
"alpha_fraction": 0.6255860924720764,
"alphanum_fraction": 0.6349631547927856,
"avg_line_length": 27.730770111083984,
"blob_id": "df8b9959abe5e8407609d2582e1990f2e1273e54",
"content_id": "48dada518ff05199f0f03bbcbc4c35ec2c87f89e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1493,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 52,
"path": "/SNN/plot.py",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\n\n\n\ndef plot_neuron_behaviour(time, data, neuron_type, neuron_id, y_title):\n plt.plot(time,data)\n plt.title('{} @ {}'.format(neuron_type, neuron_id))\n plt.ylabel(y_title)\n plt.xlabel('Time (msec)')\n # Autoscale y-axis based on the data (is this needed??)\n y_min = 0\n y_max = max(data)*1.2\n if y_max == 0:\n y_max = 1\n plt.ylim([y_min,y_max])\n plt.show()\n\n\n\ndef plot_membrane_potential(time, Vm, neuron_type, neuron_id=0):\n plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title='Membrane potential (V)')\n\n\n\ndef plot_spikes(time, Vm, neuron_type, neuron_id=0):\n plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title='Spike (V)')\n\n\n\ndef plot_neuron_behaviour(time, data, neuron_type, neuron_id, y_title):\n print('Drawing graph with time.shape={}, data.shape={}'.format(time.shape, data.shape))\n plt.plot(time,data)\n plt.title('{} @ {}'.format(neuron_type, neuron_id))\n plt.ylabel(y_title)\n plt.xlabel('Time (msec)')\n # Graph to the data with some headroom...\n y_min = 0\n y_max = max(data)*1.2\n if y_max == 0:\n y_max = 1\n plt.ylim([y_min,y_max])\n plt.show()\n\n\n\ndef plot_membrane_potential(time, Vm, neuron_type, neuron_id = 0):\n plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title = 'Membrane potential (V)')\n\n\n\ndef plot_spikes(time, Vm, neuron_type, neuron_id = 0):\n plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title = 'Spike (V)')"
},
{
"alpha_fraction": 0.6593176126480103,
"alphanum_fraction": 0.7007874250411987,
"avg_line_length": 34.24074172973633,
"blob_id": "9174ce42d2cdbc7fba8c7ac4bb54d8ae0479f3ad",
"content_id": "f9d6d290dcb821076a71509535434c0dfc51ab04",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1905,
"license_type": "permissive",
"max_line_length": 182,
"num_lines": 54,
"path": "/test.py",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport SNN\n\n\n\nT = 10 # total time to sumulate (msec)\ndt = 0.0125 # Simulation timestep\ntime = int(T / dt)\ninpt = 1.0 # Neuron input voltage\nneuron_input = np.full(time, inpt)\n\n\n\nneurons = SNN.model.create_neurons(num_layers=2, num_neurons=100, debug=False)\n\n\n\nstimulus_len = len(neuron_input)\nlayer = 0\nfor neuron in range(100):\n offset = random.randint(0, 100) # Simulates stimulus starting at different times\n stimulus = np.zeros_like(neuron_input)\n stimulus[offset:stimulus_len] = neuron_input[0:stimulus_len - offset]\n neurons[layer][neuron].spike_generator(stimulus)\n\n\n\nlayer_spikes = np.zeros_like(neurons[0][0].spikes)\nfor i in range(100):\n layer_spikes += neurons[0][i].spikes\nprint(layer_spikes[0:200])\n\n\n\nneurons[1][0] = SNN.neuron.LIF(debug=False) # Re-initialise this neuron in case of multiple runs\nneurons[1][0].spike_generator(layer_spikes)\n\n\n\nstart_time = 0\nend_time = len(neurons[1][0].time)\n\n\n\nSNN.plot.plot_membrane_potential(neurons[0][0].time, neurons[0][0].Vm, 'Membrane Potential {}'.format(neurons[0][0].type), neuron_id =\"0/0\")\nSNN.plot.plot_spikes(neurons[0][0].time, neurons[0][0].spikes, 'Output spikes for {}'.format(neurons[0][0].type), neuron_id =\"0/0\")\nSNN.plot.plot_spikes(neurons[0][0].time, layer_spikes, 'Output spikes for layer {}'.format(layer))\n\n\nSNN.plot.plot_spikes(neurons[0][0].time[start_time:end_time], layer_spikes[start_time:end_time], 'Input Spikes for {}'.format(neurons[1][0].type), neuron_id =\"1/0\")\nSNN.plot.plot_membrane_potential(neurons[1][0].time[start_time:end_time], neurons[1][0].Vm[start_time:end_time], 'Membrane Potential {}'.format(neurons[1][0].type), neuron_id =\"1/0\")\nSNN.plot.plot_spikes(neurons[1][0].time[start_time:end_time], neurons[1][0].spikes[start_time:end_time], 'Output spikes for {}'.format(neurons[1][0].type), neuron_id =\"1/0\")\n\n\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 24,
"blob_id": "55800dc42477f4c7c9732450ba395318af1bf799",
"content_id": "f51089eab89348f4a0951123c7ffa3d23dd289e0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 25,
"license_type": "permissive",
"max_line_length": 24,
"num_lines": 1,
"path": "/README.md",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "# Spiking Neural Network\n"
},
{
"alpha_fraction": 0.616136908531189,
"alphanum_fraction": 0.621026873588562,
"avg_line_length": 28.285715103149414,
"blob_id": "88fdc640f75aba6c6c6f97db0b4465ed0d43b97f",
"content_id": "4f17e52a1aa13ca6346bdab75b4492175a888573",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 409,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 14,
"path": "/SNN/model.py",
"repo_name": "Intipy/spiking-neural-network",
"src_encoding": "UTF-8",
"text": "from SNN import neuron\n\n\n\ndef create_neurons(num_layers=0, num_neurons=0, debug=True):\n neurons = []\n for layer in range(num_layers):\n if debug:\n print ('create_neurons(): Creating layer {}'.format(layer))\n neuron_layer = []\n for count in range(num_neurons):\n neuron_layer.append(neuron.LIF(debug=debug))\n neurons.append(neuron_layer)\n return neurons"
}
] | 6 |
AnwarFahad/tooWeaktooSlow | https://github.com/AnwarFahad/tooWeaktooSlow | d1940aa7176b90f7e78552ad3aeddbecee40d1e6 | 4604bd9aa97d9611c5388f5d3398bf2b5db7f1e4 | 977b7836b33bb83a4d16c8311526c1632314f4a9 | refs/heads/main | 2023-02-18T15:55:46.834831 | 2021-01-21T05:21:28 | 2021-01-21T05:21:28 | 301,785,845 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6519337296485901,
"alphanum_fraction": 0.689226508140564,
"avg_line_length": 23.85714340209961,
"blob_id": "9f831b8c90dd428879319b63712bd03fcc01b631",
"content_id": "3d3c273a959f6e5005820331b02ec6d7dd68ee5d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 724,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 28,
"path": "/tooWeaktooSlow.py",
"repo_name": "AnwarFahad/tooWeaktooSlow",
"src_encoding": "UTF-8",
"text": "# The purpose of this bot is to cick the first black pixel.\r\n# Testing a change here done by Git. \r\n# changes through branches\r\n\r\nimport pyautogui\r\nimport keyboard\r\nimport win32api\r\nimport win32con\r\nimport time\r\n\r\n# click function, with a 0.01 pause inorder to properly run the script\r\n\r\n\r\ndef click(x, y):\r\n win32api.SetCursorPos((x, y))\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)\r\n time.sleep(0.01)\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)\r\n\r\n\r\n# pressing 's' to stop the function\r\n\r\nwhile keyboard.is_pressed('s') == False:\r\n\r\n # If the pixel is black (0), click on that pixel\r\n\r\n if pyautogui.pixel(xPosition, yPosition)[0] == 0:\r\n click(xPosition, yPosition)\r\n"
}
] | 1 |
wenchangshou2/music_player | https://github.com/wenchangshou2/music_player | 569a25ae469012b902672fe2aaca941fb129555a | 50e26508c9680c8d272370d56b5a0453ac29162a | 8ace6da4f55df7e7466151788c5977ae98a8745d | refs/heads/master | 2020-12-24T20:24:05.665505 | 2016-05-21T06:01:56 | 2016-05-21T06:01:56 | 59,344,546 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6896551847457886,
"alphanum_fraction": 0.7011494040489197,
"avg_line_length": 21,
"blob_id": "f0adb6959ee004ae808e6617ca56326f131c1e42",
"content_id": "27bf23457a76692bdff460092b343c41c0582f06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 95,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 4,
"path": "/test.py",
"repo_name": "wenchangshou2/music_player",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\nfrom douban.exceptions import ApiError\n\nraise(ApiError('接口错误'))"
},
{
"alpha_fraction": 0.596670925617218,
"alphanum_fraction": 0.6222791075706482,
"avg_line_length": 21.985294342041016,
"blob_id": "b80eca564abf3f3107799d6e1d507be67848a011",
"content_id": "48c546903539b41d45c362142524e84c279f575b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1562,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 68,
"path": "/douban/api/login.py",
"repo_name": "wenchangshou2/music_player",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\nimport requests\n#import curses\nfrom PIL import Image\n\nfrom douban.exceptions import ApiError\n\n#screen=curses.initscr()\nHEADERS = {\"User-Agent\": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n'''\ndef get_parm(paompt_string):\n curses.clear()\n screen.border(0)\n screen.addstr(2,2,paompt_string)\n screen.refresh()\n input=screen.getstr(10,10,60)\n return input\n'''\ndef show_login():\n email=str(raw_input('user:'))\n password=str(raw_input('password'))\n\n captcha_id=get_captcha_id()\n get_captcha_pic(captcha_id)\n file_path='/tmp/yzm.jpg'\n img=Image.open(file_path)\n img.show()\n\n#def request_token():\n\n\ndef get_captcha_id():\n url='https://douban.fm/j/new_captcha'\n option={\n\n }\n try:\n r=requests.get(url).text\n return r.strip('\"')\n except Exception as e:\n raise(ApiError('get_captcha_id error'+e))\ndef get_captcha_pic(captcha_id):\n url='https://douban.fm/misc/captcha'\n options={\n 'size':'m',\n 'id':captcha_id\n }\n r=requests.get(url,headers=HEADERS,params=options)\n if r.status_code==200:\n path='/tmp/yzm.jpg'\n print 'DownLoad aptcha_pic'+path\n with open(path,'wb') as f:\n f.write(r.content)\n else:\n print('get Captcha_pic '+r.status_code)\n\n\n\nshow_login()\n'''\ndef test_get_captcha_id():\n print(get_captcha_id())\ndef test_get_captcha_pic():\n id=get_captcha_id()\n get_captcha_pic(id)\n\ntest_get_captcha_pic()\n'''"
},
{
"alpha_fraction": 0.6414566040039062,
"alphanum_fraction": 0.6442577242851257,
"avg_line_length": 24.571428298950195,
"blob_id": "416e1c3cd5dc49635abeee97e61b3d1f35210865",
"content_id": "e270f42fc9db2a55e40749b4548a2e14ffe35b0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 357,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 14,
"path": "/douban/exceptions.py",
"repo_name": "wenchangshou2/music_player",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\nfrom termcolor import colored\n\nclass GenericError(Exception):\n message = \"error class\"\n def __init__(self,message=None,**kwargs):\n self.kwargs=kwargs\n\n if not message:\n message=self.message%kwargs\n super(GenericError,self).__init__(colored(message,'red'))\n\nclass ApiError(GenericError):\n pass"
}
] | 3 |
mattyonweb/funlisp | https://github.com/mattyonweb/funlisp | ae3942d89d5a631cc73bc86ce965707e3ff8c14c | e6c01641a45fb0bcc5c224b9619259b9adfdcbc8 | 6c6b16ffe07074e0c66d708b3fce4978ffc9bdc0 | refs/heads/master | 2023-06-19T07:27:19.419829 | 2021-07-15T10:58:01 | 2021-07-15T10:58:01 | 386,257,755 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.48542654514312744,
"alphanum_fraction": 0.4925631880760193,
"avg_line_length": 30.497900009155273,
"blob_id": "3c30d9d760eec0b39ca5ac68eea225d0620ea429",
"content_id": "6e2a166568f48d289ddc6299954da1b5cb250fb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14998,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 476,
"path": "/lisp/compiler.py",
"repo_name": "mattyonweb/funlisp",
"src_encoding": "UTF-8",
"text": "from typing import List, Callable, Dict, Tuple, _CallableGenericAlias\nimport socket\nimport shlex\nimport threading\nimport os\nimport random\n\nfrom lisp.utils import *\n\nclass Symbol(str): pass\n\nNumber = (int, float) # A Scheme Number is implemented as a Python int or float\nAtom = (Symbol, Number) # A Scheme Atom is a Symbol or Number\nList = list # A Scheme List is implemented as a Python list\nExp = (Atom, List) # A Scheme expression is an Atom or List\nEnv = dict # A Scheme environment (defined below) \n # is a mapping of {variable: value}\n\nclass LispError(Exception): pass\nclass LispParseError(LispError): pass\nclass LispSymbolError(LispError): pass\n\ndef tokenize(chars: str) -> list:\n \"Convert a string of characters into a list of tokens.\"\n return shlex.split(\n replace_but_not_inside_quotes('(', ' ( ',\n replace_but_not_inside_quotes(')', ' ) ',\n replace_but_not_inside_quotes(\"'\", \" ` \", chars))),\n posix=False\n )\n \n\ndef parse(program: str) -> Exp:\n \"Read a Scheme expression from a string.\"\n return read_from_tokens(tokenize(program))\n\ndef read_from_tokens(tokens: list) -> Exp:\n \"Read an expression from a sequence of tokens.\"\n if len(tokens) == 0:\n raise LispParseError('unexpected EOF')\n\n token = tokens.pop(0)\n\n if token == \"`\":\n return [\"quote\", read_from_tokens(tokens)]\n if token.startswith(\"\\\"\"):\n return [\"string\", token[1:-1]]\n if token == '(':\n L = []\n while tokens[0] != ')':\n L.append(read_from_tokens(tokens))\n tokens.pop(0) # pop off ')'\n return L\n if token == ')':\n raise LispParseError('unexpected )')\n \n return atom(token)\n\n\ndef atom(token: str) -> Atom:\n \"Numbers become numbers; every other token is a symbol.\"\n try: return int(token)\n except ValueError:\n try: return float(token)\n except ValueError:\n # if token[0] == \"\\\"\":\n # return [\"string\", token] #TODO?\n # else:\n return Symbol(token)\n\n##################################\n\nclass Context(dict):\n def __init__(self, parms: list, args: list, outer=None):\n self.update(zip(parms, args))\n self.outer = outer\n\n def depth(self, acc=0):\n if self.outer is None:\n return acc\n return self.outer.depth(acc=acc+1)\n \n def add(self, k, v):\n self.update(zip([k], [v]))\n\n def outermost_add(self, k, v):\n if self.outer is None:\n self.add(k, v)\n else:\n self.outer.outermost_add(k, v)\n \n def find(self, var):\n \"Find the innermost Ctx where var appears.\"\n try:\n return self[var] if (var in self) else self.outer.find(var)\n except AttributeError as e:\n print(f\"Coulnd't find {var}\")\n raise LispSymbolError(str(e)) from e\n \nclass Procedure():\n \"A user-defined Scheme procedure.\"\n def __init__(self, parms, body, ctx, _help=None, debug=False):\n self.parms, self.body, self.ctx = parms, body, ctx\n self.help = None if _help is None else eval_free(_help, ctx, debug=debug)\n self.debug = debug\n def __call__(self, *args):\n return eval_free(self.body, Context(self.parms, args, outer=self.ctx), debug=self.debug)\n \n\n################################\nimport time\n\ndef print_help(foo: Union[Callable, Procedure]):\n if isinstance(foo, Procedure):\n if foo.help is None:\n return False\n\n return foo.help\n\n return False\n\ndef read_file(fpath: str) -> str:\n with open(fpath, \"r\") as f:\n return [\"string\", f.read()]\ndef write_file(fpath: str, data: str) -> str:\n with open(fpath, \"w\") as f:\n return f.write(data)\ndef append_to_file(fpath:str, data: str):\n with open(fpath, \"a\") as f:\n return f.write(data) \ndef import_func(fpath):\n pass # TODO\n \ndef get_type(obj):\n if isinstance(obj, (int, float)):\n return Symbol(\"number\")\n if isinstance(obj, Symbol):\n return Symbol(\"symbol\")\n if isinstance(obj, str):\n return Symbol(\"string\")\n if isinstance(obj, list):\n return Symbol(\"lst\")\n\ndef foldl(func, acc, l):\n for x in l:\n acc = func(x, acc)\n return acc\ndef repeat_until(func, acc, cond):\n while not cond(acc):\n acc = func(acc)\n return acc\n\nimport functools, operator as op\ncontext_base_simple = {\n \"t\": True,\n \"nil\": False,\n \"and\": (lambda x, y: x and y),\n \"or\": (lambda x, y: x or y),\n \"not\": (lambda x: not x),\n\n \"=\": (lambda x, y: x == y),\n \"!=\": (lambda x, y: x != y),\n \">=\": (lambda x, y: x >= y),\n \">\": (lambda x, y: x > y),\n \"<=\": (lambda x, y: x <= y),\n \"<\": (lambda x, y: x < y),\n\n # \"+\": (lambda *ns: sum(ns)),\n \"+\": (lambda *ns: functools.reduce(op.add, ns)),\n \"-\": (lambda x,y: x-y),\n \"*\": (lambda *ns: functools.reduce(op.mul, ns)),\n \"**\": (lambda x,y: x**y),\n \"++\": (lambda x: x+1),\n \"*2\": (lambda x: x*2),\n \"mod\": (lambda x,y: x % y),\n \"/\": (lambda x,y: x / y),\n\n \"cons\": lambda x,xs: [x] + xs,\n \"head\": lambda xs: Symbol(\"err-empty-list\") if len(xs) == 0 else xs[0],\n \"tail\": lambda xs: xs[1:],\n \"append\": lambda x,xs: xs + [x],\n \"nth\": lambda l, n: l[n] if 0 <= n <= len(l) else Symbol(\"err-empty-list\"),\n \"is-list?\": lambda x: isinstance(x, list),\n\n \"compose\": lambda f1, f2: lambda x: f1 ( f2 (x)),\n \n \"map\": lambda f,l: [f(x) for x in l],\n \"fold\": foldl,\n \"repeat-until\": repeat_until,\n \n \"time\": time.time,\n \"sleep\": time.sleep,\n \"random\": random.randint,\n \"help\": print_help,\n \"import\": import_func,\n \n \"read\": lambda s: parse(input(s)),\n \"read-with-macro\": lambda s, m: m(parse(input(s))),\n \"show\": lambda x: str(x),\n\n \"pwd\": os.getcwd(),\n \"read-file\": read_file,\n \"write-file\": write_file,\n \"append-to-file\": append_to_file,\n\n \"type?\": get_type,\n \"atom?\": lambda x: isinstance(x, (int, float, str, Symbol)) # TODO: str può essere stringa o simbolo!\n}\n\ncontext_base = Context(context_base_simple.keys(), context_base_simple.values())\n\n#######################################\n\ndef ast_to_str(ast: List) -> str:\n \"\"\"\n Converts an AST to string (basically upnarsing)\n \"\"\"\n if not isinstance(ast, list):\n return str(ast)\n\n return f\"({ast[0]} \" + \" \".join(ast_to_str(x) for x in ast[1:]) + \")\"\n\nimport logging\n\nlogger = logging.getLogger(\"[EVAL]\")\n\ndef eval_free(ast: List, context: dict, debug=False):\n while True:\n # print(ast)\n \n if debug:\n print(ast)\n\n if isinstance(ast, Symbol):\n return context.find(ast)\n\n if isinstance(ast, (int, float)): #TODO: ma era questo?\n return ast\n\n if isinstance(ast, str): #TODO: ma era questo?\n return ast\n\n if isinstance(ast, list):\n if len(ast) == 0: # '() o (list)\n return []\n\n # print(f\"DEPTH: {context.depth()}\")\n \n if ast[0] == \"quote\":\n return ast[1]\n\n if ast[0] == \"string\":\n return ast[1]\n\n elif ast[0] == \"list\":\n return [eval_free(el, context, debug=debug) for el in ast[1:]]\n \n if ast[0] == \"lambda\":\n if len(ast[1:]) == 3:\n variables = ast[1]\n _help = ast[2]\n body = ast[3]\n elif len(ast[1:]) == 2:\n _help = None\n variables = ast[1] \n body = ast[2]\n else:\n raise LispError(f\"lambda expects 2/3 arguments, were given {len(ast[1:])}\")\n\n return Procedure(variables, body, context, _help=_help, debug=debug)\n\n if ast[0] == \"define\":\n #funziona per non-ricorsive\n context.outermost_add(ast[1], eval_free(ast[2], context, debug=debug)) \n return ast[1]\n\n if ast[0] == \"cond\":\n for clause in ast[1:]:\n if eval_free(clause[0], context, debug=debug):\n ast = clause[1]\n break\n else:\n assert eval_free(ast[-1][0], context, debug=debug), f\"{ast[-1][0]} should evaluate to T!\"\n print(\"WARNING\")\n return \n\n elif ast[0] == \"if\":\n if eval_free(ast[1], context, debug=debug):\n ast = ast[2]\n else:\n ast = ast[3]\n\n elif ast[0] == \"begin\":\n for x in ast[1:-1]:\n eval_free(x, context, debug=debug)\n ast = ast[-1]\n\n elif ast[0] == \"curry\":\n ast = ast[1]\n \n num_declared_args = len(ast) - 1\n\n symbol_eval = eval_free(ast[0], context, debug=debug)\n function_arity = deduce_arity(\n symbol_eval\n )\n\n alfabeto = \"abcdefghij\"\n ast = [\n \"lambda\",\n [Symbol(c) for c in alfabeto[:function_arity-num_declared_args]],\n ast + [Symbol(c) for c in alfabeto[:function_arity-num_declared_args]]\n ]\n\n \n elif ast[0] == \"let\": \n # Per esempio, se ho\n # \n # (let foo (lambda (x) (if (= x 0) 0 (let-rec (- x 1)))))\n # \n # Il primo passo è fare EVAL sulla lambda:\n inner_ctx = Context([], [], context)\n\n MULTI_LET = len(ast) == 3\n\n if MULTI_LET:\n for let_clause in ast[1]:\n\n let_clause_body = eval_free(let_clause[1], inner_ctx, debug=debug)\n\n # Se il corpo del let-rec è effettivamente una procedura (e non\n # ad es. un numero), essa potrebbe essere ricorsiva.\n # Per cui, aggiungi nel contesto della procedura\n # un binding a sé stessa, aka. aggiungi al contesto della procedura\n # la coppia {foo : Procedure<foo, body=...,>}\n if isinstance(let_clause_body, Procedure):\n let_clause_body.ctx.add(let_clause[0], let_clause_body)\n\n inner_ctx.add(let_clause[0], let_clause_body)\n\n else:\n let_clause_body = eval_free(ast[2], inner_ctx, debug=debug)\n\n if isinstance(let_clause_body, Procedure):\n let_clause_body.ctx.add(ast[1], let_clause_body)\n\n inner_ctx.add(ast[1], let_clause_body)\n\n return eval_free(ast[2] if MULTI_LET else ast[3], inner_ctx, debug=debug)\n\n\n elif ast[0] == \"debug\":\n if ast[1] == \"ctx\":\n print(context)\n return \"ok\"\n if ast[1] == \"break\":\n breakpoint()\n return \"ok\"\n if ast[1] == \"stack\":\n i, temp = 0, context\n\n while temp != None:\n print(temp)\n temp = temp.outer\n i += 1\n breakpoint()\n print(i)\n return \"ok\"\n if ast[1] == \"t\":\n debug=True\n return \"ok\"\n if ast[1] == \"f\":\n debug=False\n return \"ok\"\n\n elif ast[0] == \"eval\":\n # ast = eval_free(ast[1], context, debug=debug)\n return eval_free(ast[1], context, debug=debug)\n \n elif ast[0] == \"evalS\":\n if ast[1][0] == \"string\":\n # ast = eval_free(parse(ast[1][1]), context, debug=debug)\n return eval_free(parse(ast[1][1]), context, debug=debug)\n else:\n s = eval_free(ast[1], context, debug=debug)\n ast = [\"evalS\", s]\n \n elif ast[0] == \"print\":\n eval_body = eval_free(ast[1], context, debug=debug)\n print(eval_body)\n return eval_body\n\n else:\n eval_exprs = [eval_free(piece, context, debug=debug) for piece in ast]\n # if debug:\n # breakpoint()\n eval_func = eval_exprs[0]\n\n if isinstance(eval_func, Procedure):\n ast = eval_func.body\n context = Context(eval_func.parms, eval_exprs[1:],\n Context(eval_func.ctx.keys(),\n eval_func.ctx.values(),\n context))\n else:\n return eval_func(*eval_exprs[1:])\n\n else:\n raise LispError(\"Unknwown type\")\n\n\ndef evalS(program, context=None, debug=False):\n ast = parse(program)\n if context is None:\n return eval_free(ast, context_base, debug=debug)\n return eval_free(ast, context, debug=debug)\n\n\ndef eval_program(program, ctx=None, what_to_print=Print.ALL, debug=False, returns=\"ctx\"):\n import copy\n\n lines = extract_expressions(program)\n ctx = copy.deepcopy(context_base) if ctx is None else ctx\n\n partial_results = list()\n for expr in lines:\n result = eval_free(parse(expr), ctx, debug=debug)\n\n if what_to_print == Print.ALL:\n print(expr)\n print(\" = \" + str(result) + \"\\n\")\n\n partial_results.append(result)\n\n if returns == \"ctx\":\n return ctx\n \n if returns == \"val\":\n if what_to_print.value > 0:\n print(partial_results[-1])\n return partial_results[-1]\n\n raise LispError(f\"`returns` parameter must be either ctx or val (given: {returns}\")\n\n############################################\n\nimport readline\n\ndef ev(program: str, what_to_print=Print.ALL, returns=\"ctx\"):\n user_library = open(\"lisp/stdlib.lisp\", \"r\").read()\n userctx = eval_program(user_library, what_to_print=what_to_print)\n return eval_program(program, userctx, what_to_print=what_to_print, returns=returns)\n \ndef repl(debug=False, fpath=None):\n import traceback\n\n if fpath is not None:\n with open(fpath, \"r\") as f:\n readed = f.read()\n else:\n readed = \"\"\n \n userctx = ev(readed, what_to_print=Print.FINAL)\n while (inp := input(\"λ \")) != \"q\":\n try:\n eval_program(inp, userctx, what_to_print=Print.ALL, debug=debug)\n except Exception as e:\n print(e)\n print(traceback.format_exc())\n\n\ndef mcirc():\n ev(\"(metacircular (list if-macro-checker for-macro-sub))\")\n \n# repl()\n# mcirc()\n"
},
{
"alpha_fraction": 0.4284275770187378,
"alphanum_fraction": 0.4655143618583679,
"avg_line_length": 29.829015731811523,
"blob_id": "66476fca5bed77147b5d71e1e9e668f991994f59",
"content_id": "c9c3f115a3564e973b54525d922d7941f075005e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5959,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 193,
"path": "/tests/test_basics.py",
"repo_name": "mattyonweb/funlisp",
"src_encoding": "UTF-8",
"text": "import unittest\nfrom lisp.compiler import *\nfrom lisp.utils import *\nimport random\n\nclass Basics(unittest.TestCase):\n with open(\"lisp/stdlib.lisp\", \"r\") as f:\n userctx = eval_program(\n f.read(),\n what_to_print=Print.NOTHING\n )\n\n def eval(self, expr: str, debug=False):\n return evalS(expr, context=Basics.userctx, debug=debug)\n\n \n def evto(self, expr: str, obj: Any, debug=False, note:str=None):\n res = self.eval(expr, debug=debug)\n self.assertEqual(res, obj)\n\n if note:\n print()\n print(f\"{expr} = {res}\")\n print(f\"Explanation: {note}\") \n\n return res\n\n \n def compileError(self, expr,\n exception_types: Union[Exception, Tuple]=None,\n note:str=None):\n try:\n evalS(expr, context=Basics.userctx)\n except Exception as e:\n if exception_types is None:\n self.assertTrue(True)\n elif isinstance(e, exception_types):\n self.assertTrue(True)\n else:\n raise e\n\n if note is not None:\n print()\n print(f\"{expr} raises {e}\")\n print(f\"Explanation: {note}\")\n \n def test_no_expressions(self):\n self.evto(\"()\", [])\n self.evto(\"1\", 1)\n self.evto(\"-1\", -1)\n\n def test_aritmethic_expressions(self):\n self.evto(\"(+ 1 2)\", 3)\n self.evto(\"(+ -1 2)\", 1)\n self.evto(\"(+ (- 1 10) 2)\", -7)\n self.evto(\"(* 2 (- 1 10))\", -18)\n self.evto(\"(* -2 (- 1 10))\", +18)\n\n def test_wrong_parser(self):\n pass #TODO\n\n def test_empty_lists(self):\n self.evto(\"()\", [])\n self.evto(\"'()\", [])\n self.evto(\"(list)\", [])\n\n def test_nested_empty_lists(self):\n # The best way to write nested empty lists\n self.evto(\"(list (list))\", [[]])\n self.evto(\"(list (list (list)))\", [[[]]])\n\n # () would be considered as a function name!\n self.compileError(\"(())\", TypeError)\n\n # `list` would be interpreted as a symbol\n # self.compileError(\"list\", TypeError)\n \n self.evto(\"'(())\", [[]])\n self.evto(\"'('())\", [[\"quote\", []]])\n\n \n def test_simple_lists(self):\n self.evto(\"'(1)\", [1])\n self.evto(\"(list 1)\", [1])\n\n self.evto(\"'(3 1 2)\", [3,1,2])\n self.evto(\"(list 3 1 2)\", [3,1,2])\n\n \n def test_nested_lists(self):\n # Whenever you deal with nested list, use `(list <...>)`.\n # Notation '(<...>) will not work because /EVERYTHING/ inside\n # parenthesis will be quoted!\n self.evto(\"(list 3 '(1 5) 2)\", [3,[1,5],2])\n\n # Most external quote will... quote everything internal\n self.evto(\"'(3 '(1 5) 2)\", [3, [\"quote\", [1,5]],2])\n\n # More nested\n self.evto(\"(list 3 (list 1 (list 5 4)) 2)\",\n [3, [1, [5,4]], 2])\n\n # Notation '(elem1 elem2 ...) is not the best idea, as elements\n # inside the list are not evaluated\n self.evto(\"'(1 '(2 3) 4)\",\n [1, [\"quote\", [2, 3]], 4])\n\n # Even more so, another example of why avoid quote notation for lists\n self.evto(\"'(1 (+ 2 3) 4)\",\n [1, [\"+\", 2, 3], 4])\n\n\n def test_equiv_quote_list(self):\n # For plain lists, '(1 2 3) and (list 1 2 3) are equal.\n import random\n \n for _ in range(50):\n l = [random.randint(-10, 10) for _ in range(random.randint(0, 11))]\n numbers = \" \".join([str(n) for n in l])\n\n self.evto(f\"(list {numbers})\", l)\n self.evto(f\"'({numbers})\", l)\n\n \n def test_higher_order_funcs_list(self):\n self.evto(\"(map ++ (list 1 2 3))\", [2,3,4])\n self.evto(\n \"(map (lambda (x) (map ++ x)) (list (list 1) (list 2 4) (list 3)))\",\n [[2], [3,5], [4]]\n )\n \n \n def test_basic_currying(self):\n self.evto(\n \"(map (curry (map ++)) (list (list 1) (list 2)))\",\n [[2],[3]]\n )\n\n # pseudo-python: `compose(lambda x:x+1)(lambda x:x*100)(1) = 101`\n # Composition compose as always from right to left\n self.evto(\"(((curry (compose ++)) (lambda (x) (* x 100))) 1)\", 101)\n\n def test_simple_eval(self):\n self.evto(\"(eval '())\", [])\n self.evto(\"(eval 1)\", 1)\n\n self.compileError(\n \"(eval (list 1 2 3))\", TypeError,\n \"The expression (1 2 3) reads 1 as a function!\"\n )\n self.compileError(\n \"(eval '(1 2 3))\", TypeError,\n \"The expression (1 2 3) reads 1 as a function!\"\n )\n \n self.evto(\"(eval (list 1 2 3))\", [1,2,3])\n\n # (eval (quote X)) = X\n # Attenzione: diverso da dire (eval (quote X)) = (eval X)!\n self.evto(\"(eval '(list 1 2 3))\", [\"list\", 1,2,3])\n self.evto(\"(eval (quote (list 1 2 3)))\", [\"list\", 1,2,3])\n\n self.evto(\"(eval (list 1 (+ 1 2) 4))\", [1,3,4])\n self.evto(\"(eval '(list 1 (+ 1 2) 4))\", [\"list\", 1, [\"+\", 1, 2], 4])\n\n \n def test_evalS(self):\n self.evto(\"\"\"(+ (evalS \"(+ 99 1)\") 1)\"\"\", 101)\n self.evto(\"\"\"(+ (evalS (read-file \"tests/sample.file\")) 1)\"\"\", 21)\n\n # TODO: PBT\n self.evto(\n \"\"\"(evalS \"(eval '(list 1 2 3))\")\"\"\",\n self.eval(\"(eval '(list 1 2 3))\")\n )\n\n \n def test_simple_let(self):\n self.evto(\"(let x 0 (+ x 1))\", 1, note=\"Single let\")\n\n # Multiple-let \n self.evto(\"(let ((x 0) (y 1)) (+ x y))\", 1, note=\"Multiple let\")\n\n self.evto(\"(let ((h (+ 1 2))) (list 1 2 h))\", [1,2,3])\n\n self.evto(\"(let ((h 1) (x (+ h 1))) x)\", 2, note=\"Mutually binding let\")\n\n \n def test_recursive_let(self):\n self.evto(\n \"(let foo (lambda (x) (if (< x 0) 0 (foo (- x 1)))) (foo 5))\",\n 0\n ) \n\n"
},
{
"alpha_fraction": 0.6744186282157898,
"alphanum_fraction": 0.6976743936538696,
"avg_line_length": 16,
"blob_id": "ef1fc4dd9773edb3b4f5f686e1b93e9660dd06ad",
"content_id": "73cc66d032004b77861572b0795db23c49d43f82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 5,
"path": "/README.md",
"repo_name": "mattyonweb/funlisp",
"src_encoding": "UTF-8",
"text": "# lisp\n\nMy own, personal lisp!\n\n![image generated with lisp in just 80sec!](out.png)\n\n"
},
{
"alpha_fraction": 0.4348122775554657,
"alphanum_fraction": 0.4416382312774658,
"avg_line_length": 22.629032135009766,
"blob_id": "7032090f5749bfb9c1b1e80bf9da9c0c3f060de2",
"content_id": "d5994610d38aabb7dbe7219dc3c00b5fb3a76f31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1465,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 62,
"path": "/lisp/utils.py",
"repo_name": "mattyonweb/funlisp",
"src_encoding": "UTF-8",
"text": "from typing import *\nimport regex # different from re!\n\nr = r\"\"\"^ *-?[0-9][0-9,\\.]* *$|^ *[A-z][A-z0-9-?\\/\\\\!]* *$|^(\\((?:[^()]++|(?1))*\\))$\"\"\"\n\"\"\" NUMBERS | LITERALS | S-EXPRS (even nested!) \"\"\"\n\nrex = regex.compile(r, regex.M)\n\ndef extract_expressions(s: str) -> List:\n \"\"\"\n Split a string, made up of multiple lines, into separate\n s-exprs.\n \"\"\"\n s = regex.sub(r';;.*', \"\", s.strip()) # rimuove i commenti\n\n exprs = list()\n for match in regex.finditer(rex, s):\n start, end = match.span()\n exprs.append(s[start:end].strip())\n\n return exprs\n\n#########################################\n\nimport enum\nclass Print(enum.Enum):\n NOTHING = 0\n FINAL = 1\n ALL = 2\n\n##########################################\nimport inspect\n\ndef deduce_arity(foo: Callable) -> int:\n if foo.__class__.__name__ == \"Procedure\":\n return len(foo.parms)\n \n sig = inspect.signature(foo)\n return len(sig.parameters)\n\n###########################################\n\ndef replace_but_not_inside_quotes(old: chr, new: chr, s: str) -> str:\n new_s = str()\n in_quotes = False\n \n for c in s:\n if c == \"\\\"\":\n in_quotes = not in_quotes\n new_s += c\n continue\n\n if c == old:\n if not in_quotes:\n new_s += new\n else:\n new_s += c\n continue\n\n new_s += c\n \n return new_s\n"
}
] | 4 |
JohnDoe02/ud120-projects | https://github.com/JohnDoe02/ud120-projects | dca0f8a41889fd0093bcba81ab8f027034a6529b | fcb88eded12b43e0092d9136697fa69a565dd89a | e16ff728843e29ed2af150e971bba9cb36d1bd6e | refs/heads/master | 2020-03-17T21:29:37.147213 | 2018-05-30T21:24:26 | 2018-05-30T21:24:26 | 133,960,944 | 0 | 0 | null | 2018-05-18T13:53:42 | 2018-05-18T02:56:33 | 2018-05-18T06:50:41 | null | [
{
"alpha_fraction": 0.5873827934265137,
"alphanum_fraction": 0.5924978852272034,
"avg_line_length": 27.609756469726562,
"blob_id": "7eee97f705f4a07d1c261eec888443d3580262f0",
"content_id": "9ce23163ae439174ded5078d2a6a40b6655153f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1173,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 41,
"path": "/final_project/my_prepdata.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\nfrom feature_format import featureFormat, targetFeatureSplit\nimport numpy as np\n\ndef remove_unkowns(data_dict, features_list):\n ### Remove non-feature poi if present\n if features_list[0] == \"poi\":\n features_list = features_list[1:]\n\n ### Remove entries, which have solely NaN's for all requested features\n keys = []\n for key in data_dict:\n cnt = 0\n for feature in features_list:\n if data_dict[key][feature] == \"NaN\":\n cnt += 1\n\n if cnt == len(features_list):\n keys.append(key)\n\n for key in keys:\n data_dict.pop(key)\n\n return len(keys)\n\ndef nan_to_mean(data_dict, features_list, prefix=\"my_\"): \n data = featureFormat(data_dict, features_list)\n poi, features = targetFeatureSplit(data)\n \n features_avg = sum(features) / len(features)\n for i, feature in enumerate(features_list[1:]):\n for key in data_dict:\n val = data_dict[key][feature]\n\n if val == \"NaN\":\n data_dict[key][prefix + feature] = features_avg[i]\n else:\n data_dict[key][prefix + feature] = val\n\n return data_dict\n"
},
{
"alpha_fraction": 0.6677190065383911,
"alphanum_fraction": 0.6771901845932007,
"avg_line_length": 29.85365867614746,
"blob_id": "1571803095e1f9e0eef1bbe429c45e2cfc6a3b1e",
"content_id": "bab445b47be401ba80a7771e68d58643610cbd19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1267,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 41,
"path": "/decision_tree/dt_author_id.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\n\"\"\" \n This is the code to accompany the Lesson 3 (decision tree) mini-project.\n\n Use a Decision Tree to identify emails from the Enron corpus by author: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\n\n### Note by JohnDoe02: The argument select_percentile is not available by default\nfeatures_train, features_test, labels_train, labels_test = preprocess(select_percentile = 1)\n#features_train, features_test, labels_train, labels_test = preprocess(select_percentile = 10)\n\n#########################################################\n### your code goes here ###\n\nfrom sklearn import tree\nfrom sklearn.metrics import accuracy_score\n\nprint \"Number of features: \", len(features_train[0])\n\nclf = tree.DecisionTreeClassifier(min_samples_split=40)\nclf.fit(features_train, labels_train)\n\nlabels_pred = clf.predict(features_test)\nacc = accuracy_score(labels_test, labels_pred)\n\nprint \"Accuracy: \", acc\n\n#########################################################\n\n\n"
},
{
"alpha_fraction": 0.6301980018615723,
"alphanum_fraction": 0.6386138796806335,
"avg_line_length": 27.45070457458496,
"blob_id": "74681fadfa11f8e18ae21cd1021b41e987eec528",
"content_id": "b2573205093493d75af1932a2cc1aee9ebf1ae6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2020,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 71,
"path": "/datasets_questions/explore_enron_data.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\n\"\"\"\n Starter code for exploring the Enron dataset (emails + finances);\n loads up the dataset (pickled dict of dicts).\n\n The dataset has the form:\n enron_data[\"LASTNAME FIRSTNAME MIDDLEINITIAL\"] = { features_dict }\n\n {features_dict} is a dictionary of features associated with that person.\n You should explore features_dict as part of the mini-project,\n but here's an example to get you started:\n\n enron_data[\"SKILLING JEFFREY K\"][\"bonus\"] = 5600000\n\n\"\"\"\n\nimport pickle\n\nenron_data = pickle.load(\n open(\"../final_project/final_project_dataset.pkl\", \"r\"))\n\nquestions = [\n (\"COLWELL WESLEY\", \"from_this_person_to_poi\"),\n (\"COLWELL WESLEY\", \"total_stock_value\"),\n (\"SKILLING JEFFREY K\", \"exercised_stock_options\"),\n (\"SKILLING JEFFREY K\", \"total_payments\"),\n (\"FASTOW ANDREW S\", \"total_payments\"),\n (\"LAY KENNETH L\", \"total_payments\"),\n]\n\nfor name, feature in questions:\n print name + \"[\" + feature + \"]:\", enron_data[name][feature]\n\nname = \"PRENTICE JAMES\"\nn_total = len(enron_data)\n\nprint\nprint \"Number of persons in the Enron dataset:\", n_total\nprint \"Features per person:\", len(enron_data[name])\n\nprint\nfor feature in [\"salary\", \"email_address\"]:\n cnt = 0\n for name in enron_data:\n if enron_data[name][feature] != \"NaN\":\n cnt += 1\n\n print \"Number of Folks with known \" + feature + \":\", cnt\n\nn_total_payments = 0\nfor name in enron_data:\n if enron_data[name][\"total_payments\"] == \"NaN\":\n n_total_payments += 1\n\nprint\nprint \"Number of total_payments NaNs:\", n_total_payments, \\\n \"(percentage: \" + str(n_total_payments/float(n_total)) + \")\"\n\nn_poi = 0\nn_poi_total_payments = 0\nfor name in enron_data:\n if enron_data[name][\"poi\"] == 1:\n n_poi += 1\n\n if enron_data[name][\"total_payments\"] == \"NaN\":\n n_poi_total_payments += 1\n\nprint \"Number of POIs: \", n_poi\nprint \"Number of POI total_payments NaNs:\", n_poi_total_payments, \\\n \"(percentage: \" + str(n_poi_total_payments/float(n_poi)) + \")\"\n"
},
{
"alpha_fraction": 0.625200629234314,
"alphanum_fraction": 0.6356340050697327,
"avg_line_length": 26.04347801208496,
"blob_id": "61a0802b6e15a26eba40a75c9c96f9a56bafc477",
"content_id": "cd08e90e04a9132f0ea11dba50d259f504195c7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1246,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 46,
"path": "/naive_bayes/nb_author_id.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\n\"\"\" \n This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. \n\n Use a Naive Bayes Classifier to identify emails by their authors\n \n authors and labels:\n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### your code goes here ###\nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\n\nt0 = time()\nclf.fit(features_train, labels_train)\nprint \"training time:\", round(time() - t0, 3), \"s\"\n\nprint \"features: \", len(features_train[0])\nprint \"max Sara: \", max(clf.sigma_[0])\nprint \"max Chris: \", max(clf.sigma_[1])\n\nt1 = time()\nclf.predict(features_test)\nprint \"prediction time:\", round(time() - t1, 3), \"s\"\n\nprint \"size of features_test: \", len(features_test)\nprint \"accuracy: \", clf.score(features_test, labels_test)\n#########################################################\n\n\n"
},
{
"alpha_fraction": 0.5345454812049866,
"alphanum_fraction": 0.5387012958526611,
"avg_line_length": 30.04838752746582,
"blob_id": "f934eb0d9c04e937020e6e661e0497bd34c8a979",
"content_id": "9bf954fc36240e16e7289eb538d615952686f965",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1925,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 62,
"path": "/final_project/my_draw.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\nimport matplotlib.pyplot as plt\nimport subprocess\nimport os\n\ndef draw(features, poi, features_list, mark_poi=True, \n name=\"image\", directory=\"./\"):\n \"\"\" Some plotting code based on lesson 9, i.e. clustering aka k_means\"\"\"\n\n ### clean plot matplotlib.pyplot in case it has been used before\n plt.clf()\n\n if len(features) < 2:\n print \"draw err: features must at least have len >= 2\"\n\n ### check if pdftk is installed\n try:\n devnull = open(os.devnull, \"w\")\n sb = subprocess.Popen([\"pdftk\"], stdout=devnull, stderr=devnull)\n sb.communicate()\n except:\n print \"draw err: pdftk must be installed\"\n return \n\n ### plot each cluster with a different color--add more colors for\n ### drawing more than five clusters\n colors = [\"b\", \"c\", \"k\", \"m\", \"g\"]\n\n pdftk = [\"pdftk\"]\n pdfclean = [\"rm\"]\n a_fl = range(0, len(features_list), 1)\n for i in a_fl:\n for j in a_fl:\n if i < j:\n for ii, pp in enumerate(features):\n plt.scatter(features[ii][i], features[ii][j])\n\n ### if you like, place red stars over points that are POIs \n if mark_poi:\n for ii, pp in enumerate(features):\n if poi[ii]:\n plt.scatter(features[ii][0], features[ii][1],\n color=\"r\", marker=\"*\")\n\n plt.xlabel(features_list[i])\n plt.ylabel(features_list[j])\n\n filename = directory + str(i) + str(j) + \"_\" + name + \".pdf\"\n pdftk.append(filename)\n pdfclean.append(filename)\n plt.savefig(filename)\n\n\n pdftk.append(\"cat\")\n pdftk.append(\"output\")\n pdftk.append(directory + name + \".pdf\")\n\n concat_pdfs = subprocess.Popen(pdftk)\n concat_pdfs.wait()\n\n subprocess.Popen(pdfclean)\n"
},
{
"alpha_fraction": 0.6790088415145874,
"alphanum_fraction": 0.6942136883735657,
"avg_line_length": 34.69346618652344,
"blob_id": "ecaadeadfc5b03289495e55c6c684ac4c00b4171",
"content_id": "8127b3cb9305ea6aa8322e154a39d2e3a2f0ff6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7103,
"license_type": "no_license",
"max_line_length": 273,
"num_lines": 199,
"path": "/final_project/poi_id.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\nimport os\nimport sys\nimport pickle\nimport sklearn\nsys.path.append(\"../tools/\")\n\nfrom feature_format import featureFormat, targetFeatureSplit\nfrom tester import dump_classifier_and_data\nfrom my_draw import draw\nfrom my_prepdata import remove_unkowns, nan_to_mean\n\nprint('The scikit-learn version is {}.'.format(sklearn.__version__))\n### A number of plots a created by this script. These are stored in\n### in the directory defined here\nplot_directory = \"plots/\"\ntry:\n os.stat(plot_directory)\nexcept:\n os.mkdir(plot_directory)\n\n### Load the dictionary containing the dataset\nwith open(\"final_project_dataset.pkl\", \"r\") as data_file:\n data_dict = pickle.load(data_file)\n\n### Task 1: Select what features you'll use.\n### features_list is a list of strings, each of which is a feature name.\n### The first feature must be \"poi\".\n#features_list_fin = ['salary', 'deferral_payments', 'total_payments', 'loan_advances', 'bonus', 'restricted_stock_deferred', 'deferred_income', 'total_stock_value', 'expenses', 'exercised_stock_options', 'other', 'long_term_incentive', 'restricted_stock', 'director_fees']\n\nfeatures_list_fin = ['salary', 'bonus', 'total_stock_value', 'exercised_stock_options']\nfeatures_list_mail = ['from_poi_to_this_person', 'from_this_person_to_poi', ]\n\nfeatures_list = ['poi'] \nfeatures_list.extend(features_list_fin)\nfeatures_list.extend(features_list_mail)\n\ndata_fin = featureFormat(data_dict, features_list)\npoi, finance_features = targetFeatureSplit(data_fin)\n\n### This plots all financial and email features against each other\n### The result is saved in plot_directory/pre_outlier_clean.pdf\ndraw(finance_features, poi, features_list_fin, \n directory=plot_directory, name=\"pre_outlier_clean\")\n\n### Task 2: Remove outliers\n### Remove \"TOTAL\" entry from database\n### Reread input data\ndata_dict.pop(\"TOTAL\")\ndata_dict.pop(\"THE TRAVEL AGENCY IN THE PARK\")\n\nremove_unkowns(data_dict, features_list)\n\ndata = featureFormat(data_dict, features_list)\npoi, finance_features = targetFeatureSplit(data)\n\ndraw(finance_features, poi, features_list_fin, \n directory=plot_directory, name=\"post_outlier_clean\")\n\n### Task 3: Create new feature(s)\n### Store to my_dataset for easy export below.\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.decomposition import PCA\n\nmy_dataset = nan_to_mean(data_dict, features_list)\n\nfeatures_list = [ \"my_\" + feature for feature in features_list ]\nfeatures_list[0] = \"poi\"\n\n### Extract features and labels from dataset for local testing\ndata = featureFormat(my_dataset, features_list, sort_keys = True)\nlabels, features = targetFeatureSplit(data)\n\nscaler = MinMaxScaler()\nscaler.fit(features)\n\nmy_features_list = [ \"scaled_\" + feature for feature in features_list ]\nmy_features_list[0] = \"poi\"\n\nrescaled_features = scaler.transform(features)\n\nfor ii,feature in enumerate(my_features_list[1:]):\n for i, key in zip(range(0,len(my_dataset)), sorted(my_dataset)):\n my_dataset[key][feature] = rescaled_features[i][ii]\n\n### Task 4: Try a varity of classifiers\n### Please name your classifier clf for easy export below.\n### Note that if you want to do PCA or other multi-stage operations,\n### you'll need to use Pipelines. For more info:\n### http://scikit-learn.org/stable/modules/pipeline.html\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import f1_score\nfrom sklearn.pipeline import Pipeline\nimport numpy as np\n\nn_data = len(rescaled_features)\nn_poi = poi.count(1.0)\nn_nonpoi = n_data - n_poi\n\nprint \"|| DATASET INFO\"\nprint \"|- size of dataset:\", n_data\nprint \"|- number of pois:\", n_poi\nprint \"|- number of non-pois:\", n_nonpoi\nprint \"|--> \" + str(n_nonpoi * 1.0/ n_poi) + \"x as many nonpois as pois\"\n\nprint\nprint\n\npipe = Pipeline([\n ('reduce_dim', PCA()),\n ('clf', SVC())\n ])\n\nclassifiers = [\n (pipe, \"Adaboost Pipeline\", \n dict(reduce_dim=[None, PCA(1), PCA(2)],\n clf=[AdaBoostClassifier()],\n clf__n_estimators=range(10, 40, 10),\n clf__learning_rate=np.arange(0.1, 0.2, 0.1))\n ),\n # SVC:\n # class_weight is really important, as the number of nonpois is ~4.0x\n # larger than the number of pois \n (pipe, \"SVC Pipeline (poly)\", \n dict(reduce_dim=[None, PCA(1), PCA(2), PCA(3)],\n clf=[SVC(kernel='poly')],\n clf__degree=[2,3,4],\n clf__C=[1000, 10000, 1000],\n clf__gamma=[1, 1e-1, 1e-2, 1e-3],\n clf__class_weight=[{1: weight} for weight in range(3, 10, 1)])\n ),\n (pipe, \"SVC Pipeline (rbf, sigmoid)\", \n dict(reduce_dim=[None, PCA(1), PCA(2), PCA(3)],\n clf=[SVC()],\n clf__kernel=['rbf', 'sigmoid'],\n clf__C=[1000, 10000, 1000],\n clf__gamma=[1, 1e-1, 1e-2, 1e-3],\n clf__class_weight=[{1: weight} for weight in range(3, 10, 1)])\n ),\n ]\n\nfrom sklearn.metrics import precision_score, recall_score, fbeta_score, f1_score\nscore_function = lambda clf, X, y : fbeta_score(y, clf.predict(X), 0.8) \n\nbest_clf = -1\nbest_f1 = 0.0\nbest_params = []\n\nfor cgsid, (cgs, clf_name, param) in enumerate(classifiers):\n print \"Using classifier\", clf_name\n \n gscv = GridSearchCV(cgs, param, scoring=score_function, refit=False)\n gscv.fit(rescaled_features, labels)\n\n print \"best score:\", gscv.best_score_\n print \"best params:\", gscv.best_params_\n if(gscv.best_score_ > best_f1):\n best_clf = cgsid\n best_params = gscv.best_params_\n best_f1 = gscv.best_score_\n\n print\n\n### Task 5: Tune your classifier to achieve better than .3 precision and recall \n### using our testing script. Check the tester.py script in the final project\n### folder for details on the evaluation method, especially the test_classifier\n### function. Because of the small size of the dataset, the script uses\n### stratified shuffle split cross validation. For more info: \n### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html\n\nfrom sklearn.model_selection import train_test_split\n\nfeatures_train, features_test, labels_train, labels_test = \\\n train_test_split(rescaled_features, labels, test_size=0.3, random_state=42)\n\nprint \"size of train set\", len(features_train)\nprint \"size of test set:\", len(features_test)\n\nclf = classifiers[best_clf][0]\nclf.set_params(**best_params)\nclf.fit(features_train, labels_train) \nlabels_pred = clf.predict(features_test)\n\nprint clf\nprint \"precision:\", precision_score(labels_test, labels_pred)\nprint \"recall:\", recall_score(labels_test, labels_pred)\nprint \"fbeta_score:\", fbeta_score(labels_test, labels_pred, 0.7)\n\n### Task 6: Dump your classifier, dataset, and features_list so anyone can\n### check your results. You do not need to change anything below, but make sure\n### that the version of poi_id.py that you submit can be run on its own and\n### generates the necessary .pkl files for validating your results.\n\ndump_classifier_and_data(clf, my_dataset, my_features_list)\n"
},
{
"alpha_fraction": 0.6159874796867371,
"alphanum_fraction": 0.6238244771957397,
"avg_line_length": 25.58333396911621,
"blob_id": "d6d02ac0931aea3dcb6f888084f2517088c6db6a",
"content_id": "e321f8b1b18f4655400b5249c4dae0997ee95045",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 638,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 24,
"path": "/outliers/outlier_cleaner.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n\ndef outlierCleaner(predictions, ages, net_worths):\n \"\"\"\n Clean away the 10% of points that have the largest\n residual errors (difference between the prediction\n and the actual net worth).\n\n Return a list of tuples named cleaned_data where\n each tuple is of the form (age, net_worth, error).\n \"\"\"\n\n dirty_data = []\n cleaned_data = []\n\n for pred, age, worth in zip(predictions, ages, net_worths):\n res = (pred - worth)**2\n\n dirty_data.append((age, worth, res))\n\n cleaned_data = sorted(dirty_data, key=lambda data: data[2])\n\n return cleaned_data[:-9]\n"
},
{
"alpha_fraction": 0.720288097858429,
"alphanum_fraction": 0.727491021156311,
"avg_line_length": 28.228069305419922,
"blob_id": "48a67c72de0a7280960b27427e1ba34f2609914b",
"content_id": "4d1b3ef1e1a049e3942c6a55f8ba033f2c690507",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1666,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 57,
"path": "/evaluation/evaluate_poi_identifier.py",
"repo_name": "JohnDoe02/ud120-projects",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python2\n\n\n\"\"\"\n Starter code for the evaluation mini-project.\n Start by copying your trained/tested POI identifier from\n that which you built in the validation mini-project.\n\n This is the second step toward building your POI identifier!\n\n Start by loading/formatting the data...\n\"\"\"\n\nimport pickle\nimport sys\nsys.path.append(\"../tools/\")\nfrom feature_format import featureFormat, targetFeatureSplit\n\ndata_dict = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\") )\n\n### add more features to features_list!\nfeatures_list = [\"poi\", \"salary\"]\n\ndata = featureFormat(data_dict, features_list)\nlabels, features = targetFeatureSplit(data)\n\n### your code goes here\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import precision_score, recall_score\nimport numpy as np\n\nfeatures_train, features_test, labels_train, labels_test = train_test_split(\n features, labels, test_size=0.3, random_state=42)\n\nclf = DecisionTreeClassifier()\nclf.fit(features_train, labels_train)\nlabels_pred = clf.predict(features_test)\n\nn_poi = (labels_pred == 1).sum()\nn_tot = len(labels_pred)\n\nprint \"accuracy:\", clf.score(features_test, labels_test)\nprint \"number of pois:\", n_poi\nprint \"number of people:\", n_tot\nprint \"accuracy if identifier would predict 0 for everybody:\", \\\n (n_tot - n_poi)*1.0/n_tot\n\ntp = 0\nfor lp, lt in zip(labels_pred, labels_test):\n if lp == lt and lp == 1:\n tp += 1\n\nprint \"number of true positives:\", tp\nprint \"precision_score:\", precision_score(labels_test, labels_pred)\nprint \"recall_score:\", recall_score(labels_test, labels_pred)\n"
}
] | 8 |
datokrat/fffusion | https://github.com/datokrat/fffusion | 246455c0b0fe23fed9bacb8b2f8df7597ac42f0d | e8b7e0f9687f0a39513019e2308eee78897e5a63 | 40fb6b4aecd5aa7c55c8256f33b79a0cee8f5d06 | refs/heads/master | 2020-06-15T12:10:09.556656 | 2019-07-07T18:29:42 | 2019-07-07T18:29:42 | 195,295,761 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5649202466011047,
"alphanum_fraction": 0.5865603685379028,
"avg_line_length": 27.322580337524414,
"blob_id": "874941225a7be1fad2d6b716741b06d98bd93f8a",
"content_id": "cdeda87844da2745edf7d782be003df86fc52329",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 878,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 31,
"path": "/core/migrations/0006_auto_20190705_1119.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2019-07-05 11:19\n\nfrom django.conf import settings\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('core', '0005_clipboarditem'),\n ]\n\n operations = [\n migrations.AlterUniqueTogether(\n name='clipboarditem',\n unique_together={('owner', 'item')},\n ),\n migrations.AlterUniqueTogether(\n name='moderatorsubscription',\n unique_together={('subscriber', 'moderator')},\n ),\n migrations.AlterUniqueTogether(\n name='reply',\n unique_together={('to_post', 'reply_post')},\n ),\n migrations.AlterUniqueTogether(\n name='replymoderation',\n unique_together={('moderator', 'reply')},\n ),\n ]\n"
},
{
"alpha_fraction": 0.667555570602417,
"alphanum_fraction": 0.6755555272102356,
"avg_line_length": 37.7931022644043,
"blob_id": "5fc0432511ceb46fe2d4beb78d4576a84c49e43e",
"content_id": "2a10fc9e1090417840414e1a07358224f0f95286",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1131,
"license_type": "no_license",
"max_line_length": 266,
"num_lines": 29,
"path": "/core/templates/fffusion/edit_post.html",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "{% extends \"fffusion/base.html\" %}\n\n{% block title %}Beitrag bearbeiten{% endblock %}\n\n{% block content %}\n<div class=\"container\">\n <h1>Beitrag bearbeiten: {{ post.title }}</h1>\n\n <p>{{ post.content }}\n\n <form method=\"post\">\n {% csrf_token %}\n\n <div class=\"form-group\">\n <label for=\"id_title\">Neue Überschrift:</label>\n <input type=\"text\" class=\"form-control\" name=\"title\" maxlength=\"255\" required value=\"{{post.title}}\" id=\"id_title\">\n <small class=\"text-muted\">Beschreibe kurz und prägnant, worum es dir geht.</small>\n </div>\n\n <div class=\"form-group\">\n <label for=\"id_content\">Neuer Text:</label>\n <textarea class=\"form-control\" name=\"content\" maxlength=\"1023\" required id=\"id_content\">{{post.content}}</textarea>\n </div>\n\n <input type=\"submit\" value=\"Beitrag aktualisieren\">\n <small class=\"text-muted\">Beachte, dass dein Beitrag inzwischen als Antwort auf mehrere Beiträge dienen könnte und auch schon Leute Antworten auf deinen Beitrag verfasst haben könnten. Deshalb solltest du die Bedeutung des Beitrags nicht stark verändern.</small>\n </form>\n</div>\n{% endblock %}\n"
},
{
"alpha_fraction": 0.629531979560852,
"alphanum_fraction": 0.6420567035675049,
"avg_line_length": 44.969696044921875,
"blob_id": "a1fec6719a07719e3e5c743e4b058f3186e6c7f6",
"content_id": "32b2764f91f7cfa862a766b1accf34b75c690e51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1517,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 33,
"path": "/core/migrations/0004_moderatorsubscription_replymoderation.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2019-07-03 22:09\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 ('core', '0003_post_creator'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ModeratorSubscription',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('moderator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='active_moderator_subscriptions', to=settings.AUTH_USER_MODEL)),\n ('subscriber', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='passive_moderator_subscriptions', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='ReplyModeration',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('appropriate', models.IntegerField()),\n ('moderator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reply_moderations', to=settings.AUTH_USER_MODEL)),\n ('reply', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='moderations', to='core.Reply')),\n ],\n ),\n ]\n"
},
{
"alpha_fraction": 0.6810217499732971,
"alphanum_fraction": 0.6860979199409485,
"avg_line_length": 36.92546463012695,
"blob_id": "a0eac7d4eb9455cba96b8ea305e769ce8a57090b",
"content_id": "7c1b39dc8bbf79f03e1f29dc2a4f145e777d740c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6107,
"license_type": "no_license",
"max_line_length": 160,
"num_lines": 161,
"path": "/core/models.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import User\nfrom django.db import models\n\nclass UserEx:\n def __init__(self, user, perspective_of_user):\n self.user = user\n self.perspective_of_user = perspective_of_user\n\n def false_positives(self):\n correct_moderated_replies = self.perspective_of_user.reply_moderations.filter(appropriate=-1).values_list(\"reply\", flat=True)\n my_moderated_replies = self.user.reply_moderations.filter(appropriate=1).values_list(\"reply\", flat=True)\n\n false_positives = my_moderated_replies.intersection(correct_moderated_replies)\n return false_positives\n\n def false_negatives(self):\n correct_moderated_replies = self.perspective_of_user.reply_moderations.filter(appropriate=1).values_list(\"reply\", flat=True)\n my_moderated_replies = self.user.reply_moderations.filter(appropriate=-1).values_list(\"reply\", flat=True)\n\n false_negatives = my_moderated_replies.intersection(correct_moderated_replies)\n return false_negatives\n\n def positive_moderations(self):\n return self.user.reply_moderations.filter(appropriate=1)\n\n def negative_moderations(self):\n return self.user.reply_moderations.filter(appropriate=-1)\n\n def common_moderations(self):\n return self.user.reply_moderations.exclude(appropriate=0).values_list(\"reply\", flat=True)\\\n .intersection(self.perspective_of_user.reply_moderations.exclude(appropriate=0).values_list(\"reply\", flat=True))\n\n def num_correlated_moderations(self):\n return self.common_moderations().count() - self.false_positives().count() - self.false_negatives().count()\n\n def all_moderations(self):\n return self.user.reply_moderations.exclude(appropriate=0)\n\n def does_moderate(self):\n return ModeratorSubscription.objects.filter(subscriber=self.perspective_of_user, moderator=self.user).exists()\n\nclass ModeratedPost:\n def __init__(self, post, user):\n self.post = post\n self.user = user\n\n def replies(self):\n return [ ModeratedReply(r, self.user) for r in self.post.replies.all() if r.get_collective_moderation(self.user) == 1 ]\n\n def id(self):\n return self.post.id\n\n def title(self):\n return self.post.title\n\n def content(self):\n return self.post.content\n\n def creator(self):\n return self.post.creator\n\n def is_in_clipboard(self):\n return ClipboardItem.objects.filter(owner=self.user, item=self.post).exists()\n\nclass ModeratedReply:\n def __init__(self, reply, user):\n self.reply = reply\n self.user = user\n\n def id(self):\n return self.reply.id\n\n def my_moderation(self):\n return self.moderation_of(self.user)\n\n def moderation_of(self, other_user):\n return self.reply.get_my_moderation(other_user)\n\n def to_post(self):\n return ModeratedPost(self.reply.to_post, self.user)\n\n def reply_post(self):\n return ModeratedPost(self.reply.reply_post, self.user)\n \n def moderate(self, value):\n if self.reply.moderations.filter(moderator=self.user).exists():\n moderation = self.reply.moderations.get(moderator=self.user)\n moderation.appropriate = value\n else:\n moderation = ReplyModeration(moderator=self.user, reply=self.reply, appropriate=value)\n\n moderation.full_clean()\n moderation.save()\n\n\n\nclass Post(models.Model):\n title = models.CharField(max_length=255)\n content = models.TextField(max_length=65535, blank=True)\n creator = models.ForeignKey(User, on_delete=models.SET_NULL, related_name=\"created_posts\", null=True)\n reply_posts = models.ManyToManyField(\"self\", related_name=\"is_reply_to\", symmetrical=False, through=\"Reply\")\n # TODO: versions\n\nclass Reply(models.Model):\n to_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=\"replies\")\n reply_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=\"reverse_replies\")\n\n def get_my_moderation(self, user):\n if self.moderations.filter(moderator=user).exists():\n return self.moderations.get(moderator=user).appropriate\n else:\n return 0\n\n def get_collective_moderation(self, user):\n if not user.is_authenticated:\n return 1\n\n if self.get_my_moderation(user) == -1:\n return -1\n\n moderators = user.passive_moderator_subscriptions.values_list(\"moderator\", flat=True) #.values_list(\"moderator\", flat=True).values_list(\"id\", flat=True)\n #positive_votes = self.moderations.in_bulk(moderators, field_name=\"moderator_id\").filter(appropriate=1).count()\n positive_votes = self.moderations.filter(moderator__in=moderators).filter(appropriate=1).count()\n #negative_votes = self.moderations.in_bulk(moderators, field_name=\"moderator_id\").filter(appropriate=-1).count()\n negative_votes = self.moderations.filter(moderator__in=moderators).filter(appropriate=-1).count()\n\n if negative_votes == 0:\n return 1\n elif positive_votes > 0:\n return 1\n else:\n return -1\n\n class Meta:\n unique_together = (\"to_post\", \"reply_post\")\n\n# Moderation\n\nclass ReplyModeration(models.Model):\n moderator = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"reply_moderations\")\n reply = models.ForeignKey(Reply, on_delete=models.CASCADE, related_name=\"moderations\")\n appropriate = models.IntegerField()\n\n class Meta:\n unique_together = (\"moderator\", \"reply\")\n\nclass ModeratorSubscription(models.Model):\n subscriber = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"passive_moderator_subscriptions\")\n moderator = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"active_moderator_subscriptions\")\n\n class Meta:\n unique_together = (\"subscriber\", \"moderator\")\n\n# Clipboard\n\nclass ClipboardItem(models.Model):\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n item = models.ForeignKey(Post, on_delete=models.CASCADE)\n\n class Meta:\n unique_together = (\"owner\", \"item\")\n\n"
},
{
"alpha_fraction": 0.5248000025749207,
"alphanum_fraction": 0.5343999862670898,
"avg_line_length": 34.71428680419922,
"blob_id": "5643e9f6d51a78eb79f9cbb1e75446ce551ecf04",
"content_id": "7331475485bc0ca4a9d43c1fadd7c83530865b82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 2503,
"license_type": "no_license",
"max_line_length": 160,
"num_lines": 70,
"path": "/core/templates/fffusion/moderator_detail.html",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "{% extends \"fffusion/base.html\" %}\n\n{% block title %}Moderator*innen-Details{% endblock %}\n{% block navtitle %}Moderator*innen-Details: {{ moderator.user.username }}{% endblock %}\n\n{% block content %}\n<div class=\"container\">\n <a href=\"{% url \"core:moderation_dashboard_moderators\" %}\" class=\"btn btn-light\">Zurück zum Moderationszentrum</a>\n\n <h1>Moderator*in: {{ moderator.user.username }}\n {% if moderator.user == request.user and false %}\n <!-- sich selbst abonnieren geht nicht... -->\n {% elif moderator.does_moderate %}\n <a class=\"btn btn-light\" href=\"{% url \"core:moderator_unsubscribe\" modid=moderator.user.id %}\">deabonnieren</a>\n {% else %}\n <a class=\"btn btn-light\" href=\"{% url \"core:moderator_subscribe\" modid=moderator.user.id %}\">abonnieren</a>\n {% endif %}\n </h1>\n\n <section>\n <h2>Unterschiedlich moderierte Beiträge</h2>\n\n {% if dissent_replies %}\n <ul class=\"card-list\">\n {% for r in dissent_replies %}\n <li>\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\"><a href=\"{% url \"core:post\" postid=r.0.reply_post.id %}\">{{r.0.reply_post.title}}</a></h5>\n <small>\n Als Antwort auf <a href=\"{% url \"core:post\" postid=r.0.to_post.id %}\">{{ r.0.to_post.title }}</a>\n als {% if r.1 == 1 %}angemessen markiert, von dir aber als unangemessen!{% else %}unangemessen markiert, von dir aber als angemessen!{% endif %}\n </small>\n <p>{{r.0.reply_post.content}}</p>\n </div>\n </div>\n </li>\n {% endfor %}\n </ul>\n {% else %}\n <p>keine...</p>\n {% endif %}\n </section>\n\n <section>\n <h2>Gleich moderierte Beiträge</h2>\n\n {% if consent_replies %}\n <ul class=\"card-list\">\n {% for r in consent_replies %}\n <li>\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\"><a href=\"{% url \"core:post\" postid=r.0.reply_post.id %}\">{{r.0.reply_post.title}}</a></h5>\n <small>\n Als Antwort auf <a href=\"{% url \"core:post\" postid=r.0.to_post.id %}\">{{ r.0.to_post.title }}</a>\n als {% if r.1 == 1 %}angemessen markiert{% else %}unangemessen markiert{% endif %}\n </small>\n <p>{{r.0.reply_post.content}}</p>\n </div>\n </div>\n </li>\n {% endfor %}\n </ul>\n {% else %}\n <p>keine...</p>\n {% endif %}\n </section>\n</div>\n{% endblock %}\n"
},
{
"alpha_fraction": 0.5977131128311157,
"alphanum_fraction": 0.6091476082801819,
"avg_line_length": 26.485713958740234,
"blob_id": "900ee4f1c8c7abe1ad93b3fd41706e7d43ee659a",
"content_id": "ff3b4844530fdd8e1c64c6222eb36a5b49f71f42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 964,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 35,
"path": "/core/templates/fffusion/create_post.html",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "{% extends 'fffusion/base.html' %}\n\n{% block title %}Neuer Beitrag{% endblock %}\n\n{% block content %}\n<div class=\"container\">\n {% if reply_to %}\n <h1>Antwort auf: {{ reply_to.title }}</h1>\n {{ reply_to.content }}\n {% endif %}\n <h1>Neuer Beitrag</h1>\n\n {% if request.user.is_authenticated %}\n <form method=\"post\">\n {% csrf_token %}\n\n <div class=\"form-group\">\n <label for=\"id_title\">Überschrift:</label>\n <input type=\"text\" class=\"form-control\" name=\"title\" maxlength=\"255\" required id=\"id_title\">\n <small class=\"text-muted\">Beschreibe kurz und prägnant, worum es dir geht.</small>\n </div>\n\n <div class=\"form-group\">\n <label for=\"id_content\">Text:</label>\n <textarea class=\"form-control\" name=\"content\" maxlength=\"1023\" required id=\"id_content\">\n </textarea>\n </div>\n\n <input type=\"submit\" value=\"Antwort posten\">\n </form>\n {% else %}\n Melde dich an, um zu antworten!\n {% endif %}\n</div>\n{% endblock %}\n"
},
{
"alpha_fraction": 0.7267165184020996,
"alphanum_fraction": 0.7267165184020996,
"avg_line_length": 65.86363983154297,
"blob_id": "1f7c2c27243a7d0716a206e1dfaeec5c6bc29598",
"content_id": "c28bc9b38e49240033f99804f15ab218fb9b7d6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1471,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 22,
"path": "/core/urls.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom . import views\n\napp_name=\"core\"\nurlpatterns = [\n path(\"\", views.dashboard, name=\"dashboard\"),\n path(\"post/<int:postid>\", views.post, name=\"post\"),\n path(\"edit_post/<int:postid>\", views.edit_post, name=\"edit_post\"),\n path(\"create_reply/to/<int:replytoid>\", views.create_reply, name=\"create_reply\"),\n path(\"reply_from_clipboard/<int:replytoid>\", views.reply_from_clipboard, name=\"reply_from_clipboard\"),\n path(\"link_reply/to/<int:replytoid>/reply/<int:replyid>\", views.link_reply, name=\"link_reply\"),\n path(\"moderation/reply/<int:repid>/value/<str:value>\", views.moderate_reply, name=\"moderate_reply\"),\n path(\"moderation/dashboard\", views.moderation_dashboard, name=\"moderation_dashboard\"),\n path(\"moderation/moderators\", views.moderation_dashboard_moderators, name=\"moderation_dashboard_moderators\"),\n path(\"moderation/posts\", views.moderation_dashboard_posts, name=\"moderation_dashboard_posts\"),\n path(\"moderation/moderator/<int:modid>\", views.moderator_detail, name=\"moderator_detail\"),\n path(\"moderation/subscribe/<int:modid>\", views.moderator_subscribe, name=\"moderator_subscribe\"),\n path(\"moderation/unsubscribe/<int:modid>\", views.moderator_unsubscribe, name=\"moderator_unsubscribe\"),\n path(\"clibpoard/new_item/<int:postid>\", views.add_clipboard_item, name=\"add_clipboard_item\"),\n path(\"clibpoard/remove_item/<int:postid>\", views.remove_clipboard_item, name=\"remove_clipboard_item\"),\n]\n"
},
{
"alpha_fraction": 0.49800798296928406,
"alphanum_fraction": 0.5358565449714661,
"avg_line_length": 19.91666603088379,
"blob_id": "234f48aa1919424d6ea441b15bb941e5fbb9691c",
"content_id": "e4811b7ca865a444e534332a00e1aba72ecfa169",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 502,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 24,
"path": "/core/migrations/0002_auto_20190703_2000.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2019-07-03 20:00\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='ontology',\n name='contained_replies',\n ),\n migrations.RemoveField(\n model_name='ontology',\n name='root',\n ),\n migrations.DeleteModel(\n name='Ontology',\n ),\n ]\n"
},
{
"alpha_fraction": 0.6911888718605042,
"alphanum_fraction": 0.6963577270507812,
"avg_line_length": 42.55497360229492,
"blob_id": "a336fbf6862ca22c821b41d4855f30a43288fa0a",
"content_id": "e49d582918a09e5f3099f0c66fb3d6a7d11640d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8321,
"license_type": "no_license",
"max_line_length": 212,
"num_lines": 191,
"path": "/core/views.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import User\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\n\nfrom .forms import CreatePostForm\nfrom .models import Post, Reply, ModeratedPost, ModeratedReply, UserEx, ReplyModeration, ModeratorSubscription, ClipboardItem\n\ndef dashboard(request):\n return render(request=request, template_name=\"fffusion/intro.html\")\n\ndef post(request, postid):\n post = ModeratedPost(get_object_or_404(Post.objects, id=postid), request.user)\n if request.user.is_authenticated:\n clipboard_items = ClipboardItem.objects.filter(owner=request.user).all()\n else:\n clipboard_items = False\n\n return render(request=request, template_name=\"fffusion/post.html\", context={\"post\": post, \"clipboard_items\": clipboard_items})\n\ndef create_reply(request, replytoid):\n reply_to = get_object_or_404(Post.objects, id=replytoid)\n\n if request.method == \"POST\":\n if request.user.is_authenticated:\n form = CreatePostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.creator = request.user\n post.full_clean()\n post.save()\n \n reply = Reply(to_post=reply_to, reply_post=post)\n reply.full_clean()\n reply.save()\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": post.id}))\n else:\n return HttpResponse(\"Du musst angemeldet sein, um Beiträge zu schreiben.\")\n return render(request=request, template_name=\"fffusion/create_post.html\", context={\"reply_to\": reply_to})\n\ndef reply_from_clipboard(request, replytoid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n reply_to = get_object_or_404(Post.objects, id=replytoid)\n\n clipboard_items = ClipboardItem.objects.filter(owner=request.user).all()\n\n return render(request=request, template_name=\"fffusion/reply_from_clipboard.html\", context={\"clipboard_items\": clipboard_items, \"reply_to\":reply_to})\n\ndef moderate_reply(request, repid, value):\n if request.user.is_authenticated:\n reply = ModeratedReply(Reply.objects.get(id=repid), request.user)\n\n if value == \"positive\":\n reply.moderate(1)\n elif value == \"negative\":\n reply.moderate(-1)\n elif value == \"neutral\":\n reply.moderate(0)\n else:\n return HttpResponse(\"Der Moderationswert ist ungültig!\")\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": reply.to_post().id()}))\n else:\n return HttpResponseRedirect(reverse(\"login\"))\n\ndef moderation_dashboard(request):\n return HttpResponseRedirect(reverse(\"core:moderation_dashboard_moderators\"))\n\ndef moderation_dashboard_moderators(request):\n # TODO: asymptotic performance\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n moderator_candidates = [ UserEx(u, request.user) for u in User.objects.all() if not UserEx(u, request.user).does_moderate() ]\n\n num_all = lambda u: u.common_moderations().count()\n num_fp = lambda u: u.false_positives().count()\n num_fn = lambda u: u.false_negatives().count()\n moderator_candidates.sort(key=lambda u: (num_all(u) * ((num_all(u) - num_fp(u) - 3 * num_fn(u)) / num_all(u))**3 if num_all(u) > 0 else -1))\n\n moderators = [ UserEx(s.moderator, request.user) for s in request.user.passive_moderator_subscriptions.all() ]\n\n return render(request=request, template_name=\"fffusion/moderation_dashboard.html\", context={\"moderator_candidates\": moderator_candidates, \"moderators\": moderators})\n\ndef moderation_dashboard_posts(request):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n me = UserEx(request.user, request.user)\n\n my_moderations = me.all_moderations().all()\n return render(request=request, template_name=\"fffusion/moderation_dashboard_posts.html\", context={\"my_moderations\": my_moderations})\n\ndef moderator_detail(request, modid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n moderator = UserEx(get_object_or_404(User.objects, id=modid), request.user)\n\n moderated_replies = [ ModeratedReply(moderation.reply, request.user) for moderation in moderator.all_moderations().all() ]\n dissent_replies = [ (reply, reply.moderation_of(moderator.user), reply.moderation_of(request.user)) for reply in moderated_replies if reply.moderation_of(request.user) != reply.moderation_of(moderator.user) ]\n consent_replies = [ (reply, reply.moderation_of(moderator.user), reply.moderation_of(request.user)) for reply in moderated_replies if reply.moderation_of(request.user) == reply.moderation_of(moderator.user) ]\n\n return render(request=request, template_name=\"fffusion/moderator_detail.html\", context={\"moderator\": moderator, \"dissent_replies\": dissent_replies, \"consent_replies\": consent_replies})\n\ndef moderator_subscribe(request, modid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n moderator = UserEx(get_object_or_404(User.objects, id=modid), request.user)\n\n if not moderator.does_moderate():\n subscription = ModeratorSubscription(subscriber=request.user, moderator=moderator.user)\n subscription.full_clean()\n subscription.save()\n\n return HttpResponseRedirect(reverse(\"core:moderator_detail\", kwargs={\"modid\":modid}))\n\ndef moderator_unsubscribe(request, modid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n moderator = UserEx(get_object_or_404(User.objects, id=modid), request.user)\n\n ModeratorSubscription.objects.filter(subscriber=request.user, moderator=moderator.user).delete()\n\n return HttpResponseRedirect(reverse(\"core:moderator_detail\", kwargs={\"modid\":modid}))\n\ndef edit_post(request, postid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n post = get_object_or_404(Post.objects, id=postid)\n \n if request.user.id != post.creator.id:\n return HttpResponseRedirect(reverse(\"login\"))\n\n if request.method == \"POST\":\n form = CreatePostForm(request.POST)\n if form.is_valid():\n ReplyModeration.objects.filter(reply__to_post=post).delete()\n ReplyModeration.objects.filter(reply__reply_post=post).delete()\n post.title = form.cleaned_data[\"title\"]\n post.content = form.cleaned_data[\"content\"]\n post.full_clean()\n post.save()\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": postid}))\n print(form)\n return HttpResponse(\"Fehler?\")\n\n return render(request=request, template_name=\"fffusion/edit_post.html\", context={\"post\": post})\n\ndef add_clipboard_item(request, postid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n post = get_object_or_404(Post.objects, id=postid)\n\n if not ClipboardItem.objects.filter(owner=request.user, item=post).exists():\n item = ClipboardItem(owner=request.user, item=post)\n item.full_clean()\n item.save()\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": postid}))\n\ndef remove_clipboard_item(request, postid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n post = get_object_or_404(Post.objects, id=postid)\n ClipboardItem.objects.filter(owner=request.user, item=post).delete()\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": postid}))\n\ndef link_reply(request, replytoid, replyid):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n\n to_post = get_object_or_404(Post.objects, id=replytoid)\n reply_post = get_object_or_404(Post.objects, id=replyid)\n\n if not Reply.objects.filter(to_post=to_post, reply_post=reply_post).exists():\n reply = Reply(to_post=to_post, reply_post=reply_post)\n reply.full_clean()\n reply.save()\n\n return HttpResponseRedirect(reverse(\"core:post\", kwargs={\"postid\": replytoid}))\n"
},
{
"alpha_fraction": 0.5560538172721863,
"alphanum_fraction": 0.569008469581604,
"avg_line_length": 36.867923736572266,
"blob_id": "1b3a172889eb27d1c995918b06b01bfef7dadf82",
"content_id": "33662efbdcc6eaeef640ec73493b3e1134781dee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2007,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 53,
"path": "/core/migrations/0001_initial.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2019-07-03 15:17\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Ontology',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255)),\n ('content', models.TextField(blank=True, max_length=65535)),\n ],\n ),\n migrations.CreateModel(\n name='Reply',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('reply_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reverse_replies', to='core.Post')),\n ('to_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='replies', to='core.Post')),\n ],\n ),\n migrations.AddField(\n model_name='post',\n name='reply_posts',\n field=models.ManyToManyField(related_name='is_reply_to', through='core.Reply', to='core.Post'),\n ),\n migrations.AddField(\n model_name='ontology',\n name='contained_replies',\n field=models.ManyToManyField(related_name='belongs_to_ontologies', to='core.Reply'),\n ),\n migrations.AddField(\n model_name='ontology',\n name='root',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Post'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.8416666388511658,
"alphanum_fraction": 0.8416666388511658,
"avg_line_length": 29,
"blob_id": "0d82c25615b9d0760f56151591bf08ae9430db87",
"content_id": "ade6854cc8f60a5651e4065125549fa494751773",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 8,
"path": "/core/admin.py",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import Post, Reply, ReplyModeration, ModeratorSubscription\n\nadmin.site.register(Post)\nadmin.site.register(Reply)\nadmin.site.register(ReplyModeration)\nadmin.site.register(ModeratorSubscription)\n"
},
{
"alpha_fraction": 0.594059407711029,
"alphanum_fraction": 0.5976597666740417,
"avg_line_length": 37.31034469604492,
"blob_id": "105e5be054d1ba85b1eb3b3c3f6e9d89e8606e32",
"content_id": "3f336f1260c7c8e7eb97f0aa3f937882357b67cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 2232,
"license_type": "no_license",
"max_line_length": 230,
"num_lines": 58,
"path": "/core/templates/fffusion/moderation_dashboard.html",
"repo_name": "datokrat/fffusion",
"src_encoding": "UTF-8",
"text": "{% extends \"fffusion/base.html\" %}\n\n{% block title %}Moderationszentrum{% endblock %}\n{% block navtitle %}Moderationszentrum{% endblock %}\n\n{% block content %}\n<div class=\"container\">\n <div class=\"toolbar-with-spacing\">\n <div class=\"btn-group\">\n <a class=\"btn btn-light\" href=\"{% url \"core:moderation_dashboard_posts\" %}\">Moderierte Beiträge</a>\n <a class=\"btn btn-light selected-button\" href=\"{% url \"core:moderation_dashboard_moderators\" %}\">Moderator*innen</a>\n </div>\n </div>\n\n <section>\n <h1>Abonnierte Moderator*innen</h1>\n {% if moderators %}\n <ul class=\"card-list\">\n {% for moderator in moderators %}\n <li>\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">{{moderator.user.username}} <a class=\"btn btn-light\" href=\"{% url \"core:moderator_detail\" modid=moderator.user.id %}\">Details</a></h5>\n \n <p>Moderierte Beiträge insgesamt: {{ moderator.all_moderations.count }}</p>\n <p>Übereinstimmung <small class=\"text-muted\">(gleich wie du moderierte Beiträge : gemeinsam mit dir moderierte Beiträge)</small>: {{ moderator.num_correlated_moderations }} : {{ moderator.common_moderations.count }}<p>\n </div>\n </div>\n </li>\n {% endfor %}\n </ul>\n {% else %}\n keine...\n {% endif %}\n </section>\n\n <section>\n <h1>Moderator*innenvorschläge</h1>\n {% if moderator_candidates %}\n <ul class=\"card-list\">\n {% for moderator in moderator_candidates %}\n <li>\n <div class=\"card\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">{{moderator.user.username}} <a class=\"btn btn-light\" href=\"{% url \"core:moderator_detail\" modid=moderator.user.id %}\">Details</a></h5>\n \n <p>Moderierte Beiträge insgesamt: {{ moderator.all_moderations.count }}</p>\n <p>Übereinstimmung <small class=\"text-muted\">(gleich wie du moderierte Beiträge : gemeinsam mit dir moderierte Beiträge)</small>: {{ moderator.num_correlated_moderations }} : {{ moderator.common_moderations.count }}<p>\n </div>\n </div>\n </li>\n {% endfor %}\n </ul>\n {% else %}\n keine...\n {% endif %}\n</div>\n{% endblock %}\n"
}
] | 12 |
pechdaniel/MyProjects | https://github.com/pechdaniel/MyProjects | ed609bc44bdec4bff6c539387add9793f8dd9595 | 4d55b6723d45e59bad432d5a2f415b6ac70c76b1 | 1aa599eaac8db3a794c66d0718cdd3aa8b0a6620 | refs/heads/master | 2020-04-13T02:46:02.610777 | 2019-01-22T15:55:39 | 2019-01-22T15:55:39 | 162,911,177 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5330983996391296,
"alphanum_fraction": 0.5338535308837891,
"avg_line_length": 30.05645179748535,
"blob_id": "6290579a56dfef8b65c74d8ff52aecfc57446884",
"content_id": "1137e06f2fa4c47a0b9a77e7848bce8c3f52ff5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3973,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 124,
"path": "/MyProjects/FP/FP/Assignment 5/domain.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Student:\r\n def __init__(self,id,name,group):\r\n self.__id=id\r\n self.__name=name\r\n self.__group=group\r\n def __str__(self):\r\n a='StudentID: '+str(self.__id)+', StudentName: '+str(self.__name)+', StudentGroup: '+str(self.__group)\r\n return a\r\n def setName(self,name):\r\n self.__name=name\r\n def setStudentID(self,id):\r\n self.__id=id\r\n def setGroup(self,group):\r\n self.__group=group\r\n def getStudentID(self):\r\n return self.__id\r\n def getName(self):\r\n return self.__name\r\n def getGroup(self):\r\n return self.__group\r\n def __eq__(self,z):\r\n if isinstance(z,Student):\r\n return self.__id==z.__id or self.__name==z.__name\r\n return False\r\n def __gt__(self,el):\r\n if self.__name>el.__name:\r\n return True\r\n return False\r\n def __lt__(self,el):\r\n if self.__name>el.__name:\r\n return False\r\n return True\r\n\r\nclass Assignment:\r\n def __init__(self,id,description,deadline):\r\n self.__id=id\r\n self.__description=description\r\n self.__deadline=deadline\r\n def __str__(self):\r\n a ='AssignmentID: '+str(self.__id)+', AssignmentDesc: '+str(self.__description)+', AssignmentDeadline: '+str(self.__deadline)\r\n return a\r\n def setAssignmentID(self,id):\r\n self.__id=id\r\n def setDescription(self,description):\r\n self.__description=description\r\n def setDeadline(self,deadline):\r\n self.__deadline=deadline\r\n def getAssignmentID(self):\r\n return self.__id\r\n def getDescription(self):\r\n return self.__description\r\n def getDeadline(self):\r\n return self.__deadline\r\n def __eq__(self,y):\r\n if isinstance(y,Assignment):\r\n return self.__id==y.__id or self.__description==y.__description\r\n return False\r\n\r\n\r\nclass Grade:\r\n def __init__(self,ida,ids,grade):\r\n self.__ida=ida\r\n self.__ids=ids\r\n self.__grade=grade\r\n def __str__(self):\r\n a = 'AssignmentID: '+str(self.__ida)+', StudentID: '+str(self.__ids)+', Grade: '+str(self.__grade)\r\n return a\r\n def __gt__(self,el):\r\n if self.__grade>el.__grade:\r\n return True\r\n return False\r\n def __lt__(self,el):\r\n if self.__grade>el.__grade:\r\n return False\r\n return True\r\n def setAssignmentID(self,ida):\r\n self.__ida=ida\r\n def setStudentID(self,ids):\r\n self.__ids=ids\r\n def setGrade(self,grade):\r\n self.__grade=grade\r\n def getAssignmentID(self):\r\n return self.__ida\r\n def getStudentID(self):\r\n return self.__ids\r\n def getGrade(self):\r\n return self.__grade\r\n def __eq__(self,x):\r\n if isinstance(x,Grade):\r\n return self.__grade==x.__grade\r\n return False\r\nclass StudentAssignments:\r\n def __init__(self,student):\r\n self.__student=student\r\n self.__assignment=[]\r\n def __str__(self):\r\n lst=''\r\n a=''\r\n for i in range(len(self.__assignment)):\r\n if i>0:\r\n lst=lst+'; ['+str(i+1)+']. '+str(self.__assignment[i])\r\n else:\r\n lst = lst+'['+str(i+1)+']. '+ str(self.__assignment[i])\r\n a=a+'['+str(self.__student)+'] '+': '+'['+lst+'] '\r\n return a\r\n def addTo(self,x):\r\n self.__assignment.append(x)\r\n def setStudent(self,student):\r\n self.__student=student\r\n def getStudent(self):\r\n return self.__student\r\n def getAssignment(self):\r\n return self.__assignment\r\n def getAssignmentIndex(self,index):\r\n return self.__assignment[index]\r\n def isFound(self,assignment):\r\n for i in range(len(self.__assignment)):\r\n if self.__assignment[i]==assignment:\r\n return True\r\n return False\r\n def studentIsFound(self,student):\r\n if self.__student==student:\r\n return True\r\n return False"
},
{
"alpha_fraction": 0.5230769515037537,
"alphanum_fraction": 0.5230769515037537,
"avg_line_length": 16.571428298950195,
"blob_id": "083bfe4209c5dcc7f97d4bde1e8db55970dc503f",
"content_id": "0d15e5e0142ece25403aef3d3d43451c36830f84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 130,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Written 2/OOP written ex1/ToDo.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"ToDo.h\"\r\n\r\nstd::ostream & operator<<(std::ostream & o, Activity & a)\r\n{\r\n\to << a.what << \" \" << a.time;\r\n\treturn o;\r\n}\r\n"
},
{
"alpha_fraction": 0.6773163080215454,
"alphanum_fraction": 0.6773163080215454,
"avg_line_length": 15.38888931274414,
"blob_id": "528e2b8b72a636da195d5987031da024b337a960",
"content_id": "dd47f8a387ee1ee8d9c7d70f50f56cc824ed9a51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 18,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <iostream>\r\n#include \"controller.h\"\r\n\r\nint Controller::addRepo(TElement & e)\r\n{\r\n\treturn this->repo.addPlayer(e);\r\n}\r\n\r\nvoid Controller::sortRepo()\r\n{\r\n\tthis->repo.sortList();\r\n}\r\n\r\nint Controller::totalGoals(const std::string country)\r\n{\r\n\treturn this->repo.total(country);\r\n}\r\n"
},
{
"alpha_fraction": 0.44965675473213196,
"alphanum_fraction": 0.45080092549324036,
"avg_line_length": 23.02857208251953,
"blob_id": "82a3771c7ef23143e72d1d41bf8437605f316415",
"content_id": "c79c7576ddb77f659b8f9132ae692ccde7f907c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 874,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 35,
"path": "/MyProjects/FP/FP/Practice Test 2/repository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from domain import *\r\nclass Repository:\r\n def __init__(self):\r\n self.__data=[]\r\n def add(self,el):\r\n '''\r\n Adds an element to the list\r\n in:param el:\r\n :return:\r\n '''\r\n self.__data.append(el)\r\n def getAll(self):\r\n '''\r\n Returns the list\r\n :return:\r\n '''\r\n return self.__data\r\n def get(self,index):\r\n '''\r\n Returns the element from that given index\r\n in:param index:\r\n :return:\r\n '''\r\n if index<len(self.__data):\r\n return self.__data[index]\r\n def findByID(self,id):\r\n '''\r\n Returns the index of the element with the given id\r\n in:param id:\r\n :return:\r\n '''\r\n for i in range(len(self.__data)):\r\n if self.__data[i].getID()==id:\r\n return i\r\n return -1"
},
{
"alpha_fraction": 0.5340604782104492,
"alphanum_fraction": 0.5430539846420288,
"avg_line_length": 24.261306762695312,
"blob_id": "9483c3a3f82c343ede34cd73a9e04308e28ae276",
"content_id": "0f5c37eeaea15f47088c6b671ca9c40229efcddd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5226,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 199,
"path": "/MyProjects/FP/FP/Assignment 4/functions.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from domain import *\r\nfrom copy import deepcopy\r\n\r\n\r\ndef copyList(myList): #makes a deepcopy from myList indo undoL\r\n '''\r\n\r\n int:param myList:\r\n out:return: undoL\r\n '''\r\n undoL=deepcopy(myList)\r\n return undoL\r\ndef undoCommand(undoL): #undoes the last modification of the list\r\n '''\r\n\r\n int:param undoL:\r\n out:return: the last element of undoL\r\n '''\r\n i=len(undoL)\r\n if i>1:\r\n undoL.pop(i-1)\r\n i=i-1\r\n return undoL[i-1]\r\ndef addToList(myList,nr): #adds complex numbers to the list\r\n '''\r\n\r\n int:param myList, nr\r\n out:return: myList\r\n '''\r\n myList.append(nr)\r\n return myList\r\ndef insertToList(myList,nr,poz): #inserts numbers in the list on a given position\r\n '''\r\n\r\n in:param myList,nr,poz\r\n out:return:myList\r\n '''\r\n n=len(myList)-1\r\n myList.append(myList[n])\r\n while n>poz:\r\n myList[n]=myList[n-1]\r\n n=n-1\r\n myList[poz]=nr\r\n return myList\r\ndef removePozFromList(myList,poz): #removes a number from the list from a given position\r\n '''\r\n\r\n in:param myList,poz\r\n out:return:myList\r\n '''\r\n myList.pop(poz)\r\n return myList\r\ndef removeFromFirstToLastFromList(myList,start,end): #removes elements from the list from a start point to an end point\r\n '''\r\n\r\n in:param myList,start,end\r\n out:return:myList\r\n '''\r\n i=end\r\n while i>=start:\r\n aux = myList[:]\r\n myList.pop(i)\r\n i=i-1\r\n return myList\r\ndef replaceOldWithNew(myList,old,new): #replaces all elements from the list equal to a given element with a new element\r\n '''\r\n\r\n in:param myList,old,new\r\n out:return:myList\r\n '''\r\n n=len(myList)-1\r\n for i in range(n):\r\n if myList[i]==old:\r\n myList[i]=new\r\n return myList\r\ndef writeList(myList): #prints the list of elements\r\n '''\r\n\r\n in:param myList\r\n out:prints myList\r\n '''\r\n print(myList)\r\ndef realList(myList,start,end): #prints the real elements from the list from a start point to an end point\r\n '''\r\n\r\n in:param myList,start,end\r\n out:prints aux\r\n '''\r\n i=start\r\n aux=[]\r\n while i<=end:\r\n if checkReal(myList[i])==True:\r\n aux.append(myList[i])\r\n i=i+1\r\n writeList(aux)\r\ndef showModuloFromList(myList,sign,md): #prints all the numbers that are < | > | = with a given value (md)\r\n '''\r\n\r\n in:param myList,sign,md\r\n out: prints the auxiliary list\r\n '''\r\n n=len(myList)-1\r\n aux=[]\r\n if sign=='<':\r\n for i in range(n):\r\n a=realPart(myList[i])\r\n b=imaginaryPart(myList[i])\r\n modulo=moduloComplex(a,b)\r\n if modulo<md:\r\n aux.append(myList[i])\r\n elif sign=='>':\r\n for i in range(n):\r\n a = realPart(myList[i])\r\n b = imaginaryPart(myList[i])\r\n modulo = moduloComplex(a, b)\r\n if modulo>md:\r\n aux.append(myList[i])\r\n elif sign=='=':\r\n for i in range(n):\r\n a = realPart(myList[i])\r\n b = imaginaryPart(myList[i])\r\n modulo = moduloComplex(a, b)\r\n if modulo==md:\r\n aux.append(myList[i])\r\n writeList(aux)\r\ndef filterRealCommand(myList): #filters the list for only real elements\r\n '''\r\n\r\n in:param myList:\r\n out:return: myList\r\n '''\r\n i=len(myList)-1\r\n while i>=0:\r\n if imaginaryPart(myList[i])!=0:\r\n removePozFromList(myList,i)\r\n i=i-1\r\n return myList\r\ndef filterModuloCommand(myList,sign,param): #filters the list for only elements that have the modulus <,>,= to a given number\r\n '''\r\n\r\n in:param myList,sign,param\r\n out:return:myList\r\n '''\r\n i=len(myList)-1\r\n if sign=='<':\r\n while i>=0:\r\n a=realPart(myList[i])\r\n b=imaginaryPart(myList[i])\r\n if not moduloComplex(a,b)<param:\r\n myList=removePozFromList(myList,i)\r\n i=i-1\r\n i=i-1\r\n elif sign=='>':\r\n while i >= 0:\r\n a = realPart(myList[i])\r\n b = imaginaryPart(myList[i])\r\n if not moduloComplex(a, b) > param:\r\n myList = removePozFromList(myList, i)\r\n i = i - 1\r\n i = i - 1\r\n elif sign=='=':\r\n while i >= 0:\r\n a = realPart(myList[i])\r\n b = imaginaryPart(myList[i])\r\n if not moduloComplex(a, b) == param:\r\n myList = removePozFromList(myList, i)\r\n i = i - 1\r\n i = i - 1\r\n return myList\r\ndef sumCommand(myList,start,end): #prints the sum of elements from a start pos to an end pos\r\n '''\r\n\r\n in:param myList,start,end\r\n out:return: k\r\n '''\r\n s1=0\r\n s2=0\r\n i=start\r\n while i<=end:\r\n s1=s1+realPart(myList[i])\r\n s2=s2+imaginaryPart(myList[i])\r\n i=i+1\r\n k=intToString(s1,s2)\r\n return k\r\ndef productCommand(myList,start,end): #prints the sum of elements from a start pos to an end pos\r\n '''\r\n\r\n in:param myList,start,end\r\n out:return:k\r\n '''\r\n s1 = 1\r\n s2 = 1\r\n i = start\r\n while i <= end:\r\n s1 = s1 * realPart(myList[i])\r\n s2 = s2 * imaginaryPart(myList[i])\r\n i = i + 1\r\n k = intToString(s1, s2)\r\n return k\r\n"
},
{
"alpha_fraction": 0.48374760150909424,
"alphanum_fraction": 0.48374760150909424,
"avg_line_length": 27.16666603088379,
"blob_id": "4bf3d044e85cfda12d97d384eb0828ff2f9f0eb1",
"content_id": "295c295f8d1a9bc73d20388b3e568adeef0b0994",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 523,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 18,
"path": "/MyProjects/FP/FP/Practice Test 2/domain.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Address:\r\n def __init__(self,id,name,x,y):\r\n self.__id=id\r\n self.__name=name\r\n self.__x=x\r\n self.__y=y\r\n def __str__(self):\r\n s=''\r\n s=s+'Address id: '+str(self.__id)+' Address name: '+str(self.__name)+' Address coordinates: '+str(self.__x)+', '+str(self.__y)\r\n return s\r\n def getID(self):\r\n return self.__id\r\n def getName(self):\r\n return self.__name\r\n def getX(self):\r\n return self.__x\r\n def getY(self):\r\n return self.__y"
},
{
"alpha_fraction": 0.6313636302947998,
"alphanum_fraction": 0.6359090805053711,
"avg_line_length": 29.884057998657227,
"blob_id": "4f33f39178ddd5d85d60c0828415b110ae4a1cf6",
"content_id": "a1e545ba83b7df3a17bebf03c1dea2168f8b286a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2200,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 69,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/GeneratedFiles/ui_Retake.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'Retake.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_RETAKE_H\r\n#define UI_RETAKE_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QMenuBar>\r\n#include <QtWidgets/QStatusBar>\r\n#include <QtWidgets/QToolBar>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_RetakeClass\r\n{\r\npublic:\r\n QMenuBar *menuBar;\r\n QToolBar *mainToolBar;\r\n QWidget *centralWidget;\r\n QStatusBar *statusBar;\r\n\r\n void setupUi(QMainWindow *RetakeClass)\r\n {\r\n if (RetakeClass->objectName().isEmpty())\r\n RetakeClass->setObjectName(QStringLiteral(\"RetakeClass\"));\r\n RetakeClass->resize(600, 400);\r\n menuBar = new QMenuBar(RetakeClass);\r\n menuBar->setObjectName(QStringLiteral(\"menuBar\"));\r\n RetakeClass->setMenuBar(menuBar);\r\n mainToolBar = new QToolBar(RetakeClass);\r\n mainToolBar->setObjectName(QStringLiteral(\"mainToolBar\"));\r\n RetakeClass->addToolBar(mainToolBar);\r\n centralWidget = new QWidget(RetakeClass);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n RetakeClass->setCentralWidget(centralWidget);\r\n statusBar = new QStatusBar(RetakeClass);\r\n statusBar->setObjectName(QStringLiteral(\"statusBar\"));\r\n RetakeClass->setStatusBar(statusBar);\r\n\r\n retranslateUi(RetakeClass);\r\n\r\n QMetaObject::connectSlotsByName(RetakeClass);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *RetakeClass)\r\n {\r\n RetakeClass->setWindowTitle(QApplication::translate(\"RetakeClass\", \"Retake\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class RetakeClass: public Ui_RetakeClass {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_RETAKE_H\r\n"
},
{
"alpha_fraction": 0.6469135880470276,
"alphanum_fraction": 0.6977072358131409,
"avg_line_length": 32.59756088256836,
"blob_id": "8605859bf3ab3c4404c3ac0a584b505c16f66e72",
"content_id": "3cb5be4942efe00c928423580d8b15ef97fd49d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 2839,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 82,
"path": "/MyProjects/DB/Lab 5/Lab5.sql",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "WINDOWS-1250",
"text": "use Lab5;\r\n\r\ncreate table Dogs(\r\nDID int primary key,\r\nDog_Name char(20),\r\nAge int\r\n);\r\n\r\ncreate table Person(\r\nPID int primary key,\r\nPerson_Name char(20),\r\nAge int\r\n);\r\n\r\ncreate table Shelter_Contract(\r\nSHID int primary key,\r\nDID int foreign key references Dogs(DID),\r\nPID int foreign key references Person(PID),\r\nDuration int\r\n);\r\n\r\ndelete from Shelter_Contract\r\ndelete from Person\r\ndelete from Dogs\r\n\r\ninsert into Dogs ([DID],[Dog_Name],[Age]) values (1,'Antiq',2),(2,'Ronnie',1),(3,'Max',0),(4,'Patty',3),(5,'Shimmi',5),(6,'Casper',7)\r\ninsert into Dogs ([DID],[Dog_Name],[Age]) values (7,'Army',2),(8,'Ronny',1),(9,'Maxy',0),(10,'Patt',3),(11,'Shanga',5),(12,'Craspy',7)\r\ninsert into Person ([PID],[Person_Name],[Age]) values (1,'Andy',30),(2,'Shannon',48),(3,'Mathew',29),(4,'Alex',70),(5,'Gunther',34),(6,'Paul',21)\r\ninsert into Person ([PID],[Person_Name],[Age]) values (7,'Andrew',30),(8,'Sharon',48),(9,'Matt',29),(10,'Alec',70),(11,'Gertrude',34),(12,'Penn',21)\r\ninsert into Shelter_Contract ([SHID],[DID],[PID],[Duration]) values (1,1,1,2),(2,2,4,2),(3,3,9,4),(4,5,8,3),(5,9,3,6),(6,7,7,3)\r\n\r\n-- a Write queries on Ta such that their corresponding execution plans contain the following operators\r\n-- clustered index scan\r\n\tselect Age from Dogs\r\n-- clustered index seek\r\n\tselect Age from Dogs\r\n\twhere Dog_Name like 'A%'\r\n-- nonclustered index scan\r\n\tcreate nonclustered index [myIndex1] on Dogs(Age)\r\n\tselect Age from Dogs\r\n\r\n\tdrop index myIndex1 on Dogs\r\n-- nonclustered index seek\r\n\tselect Age from Dogs where Age>=1\r\n-- key lookup\r\n\tselect * from Dogs with (index =MyIndex1) where Age>=1\r\n\r\n-- b Write a query on table Tb with a WHERE clause of the form WHERE b2 = value and analyze its execution plan. \r\n-- Create a nonclustered index that can speed up the query. \r\n-- Recheck the query’s execution plan (operators, SELECT’s estimated subtree cost)\r\n\t\r\n-- clustered 0.0032952\r\n\tselect Age from Person\r\n\twhere Age >=30\r\n\r\n-- nonclustered 0.0032908\r\n\tcreate nonclustered index myIndex2 on Person(Age)\r\n\tselect Age from Person\r\n\twhere Age >=30\r\n\r\n\tdrop index myIndex2 on Person\r\n\r\n-- c Create a view that joins at least 2 tables. Check whether existing indexes are helpful; \r\n-- if not, reassess existing indexes / examine the cardinality of the tables\r\ndrop view MyView\r\n\r\ncreate view MyView\r\nas\r\n-- selects the contract id's that are greater than 1 and in which the dog name and person mane start with the same letter\r\nselect distinct S.SHID from Shelter_Contract S\r\ninner join (select D.DID from Dogs D inner join Person P on (substring(D.Dog_Name,1,1)=substring(P.Person_Name,1,1))) M \r\non S.DID=M.DID\r\nwhere S.SHID>1\r\n\r\n-- clustered 0.00111683\r\nselect * from MyView\r\n\r\n-- nonclustered 0.00\r\ncreate nonclustered index [MyIndex3] on Shelter_Contract(SHID)\r\nselect * from MyView\r\n\r\ndrop index MyIndex3 on Shelter_Contract"
},
{
"alpha_fraction": 0.49601274728775024,
"alphanum_fraction": 0.49601274728775024,
"avg_line_length": 18.899999618530273,
"blob_id": "678059df1916d0898ac17558c122b189de0d9e1c",
"content_id": "755de32ca7231945cf19802100573b2a55f474e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 629,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 30,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/CompStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class CompStmt:IStmt\r\n {\r\n private IStmt first, second;\r\n\r\n public CompStmt(IStmt f, IStmt s)\r\n {\r\n first = f;\r\n second = s;\r\n }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n state.Stack.add(second);\r\n state.Stack.add(first);\r\n\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"(\" + first + \"; \" + second + \")\";\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6545265316963196,
"alphanum_fraction": 0.6605098843574524,
"avg_line_length": 32.94545364379883,
"blob_id": "630f8d92ee3e7bebb65753c86ebc94c4a8ca9f9b",
"content_id": "b16aae528063dcce2845e9fb9fbfc658f57f13e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3844,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 110,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_mode.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'mode.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_MODE_H\r\n#define UI_MODE_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_ModeWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout_2;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *QuestionLabel;\r\n QHBoxLayout *horizontalLayout;\r\n QPushButton *UserButton;\r\n QPushButton *AdminButton;\r\n QPushButton *ViewButton;\r\n\r\n void setupUi(QMainWindow *ModeWindow)\r\n {\r\n if (ModeWindow->objectName().isEmpty())\r\n ModeWindow->setObjectName(QStringLiteral(\"ModeWindow\"));\r\n ModeWindow->resize(382, 97);\r\n centralwidget = new QWidget(ModeWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout_2 = new QHBoxLayout(centralwidget);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout_2 = new QVBoxLayout();\r\n verticalLayout_2->setObjectName(QStringLiteral(\"verticalLayout_2\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n QuestionLabel = new QLabel(centralwidget);\r\n QuestionLabel->setObjectName(QStringLiteral(\"QuestionLabel\"));\r\n QFont font;\r\n font.setPointSize(12);\r\n QuestionLabel->setFont(font);\r\n\r\n verticalLayout->addWidget(QuestionLabel);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n UserButton = new QPushButton(centralwidget);\r\n UserButton->setObjectName(QStringLiteral(\"UserButton\"));\r\n\r\n horizontalLayout->addWidget(UserButton);\r\n\r\n AdminButton = new QPushButton(centralwidget);\r\n AdminButton->setObjectName(QStringLiteral(\"AdminButton\"));\r\n\r\n horizontalLayout->addWidget(AdminButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n\r\n verticalLayout_2->addLayout(verticalLayout);\r\n\r\n ViewButton = new QPushButton(centralwidget);\r\n ViewButton->setObjectName(QStringLiteral(\"ViewButton\"));\r\n\r\n verticalLayout_2->addWidget(ViewButton);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout_2);\r\n\r\n ModeWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(ModeWindow);\r\n\r\n QMetaObject::connectSlotsByName(ModeWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *ModeWindow)\r\n {\r\n ModeWindow->setWindowTitle(QApplication::translate(\"ModeWindow\", \"Mode\", nullptr));\r\n QuestionLabel->setText(QApplication::translate(\"ModeWindow\", \"Do you want to continue as an admin or as a user?\", nullptr));\r\n UserButton->setText(QApplication::translate(\"ModeWindow\", \"User\", nullptr));\r\n AdminButton->setText(QApplication::translate(\"ModeWindow\", \"Admin\", nullptr));\r\n ViewButton->setText(QApplication::translate(\"ModeWindow\", \"Neither, I just want to see the lists of movies.\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class ModeWindow: public Ui_ModeWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_MODE_H\r\n"
},
{
"alpha_fraction": 0.5312145352363586,
"alphanum_fraction": 0.5312145352363586,
"avg_line_length": 21.1842098236084,
"blob_id": "7026cdf76d97570db2beaaf0c8f091f9103101e7",
"content_id": "db3010aa12b8887c1a759efcc90ff79e8c53f9eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 883,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 38,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Controller/MyController.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model;\r\nusing Interpreter.Model.Statements;\r\nusing Interpreter.Repository;\r\n\r\nnamespace Interpreter.Controller\r\n{\r\n public class MyController\r\n {\r\n private myRepositorix repo;\r\n\r\n public MyController(myRepositorix r)\r\n {\r\n this.repo = r;\r\n }\r\n\r\n public void executeOneStep()\r\n {\r\n ProgramState p = repo.getCurrentPrgState();\r\n IStmt stmt = p.Stack.pop();\r\n\r\n stmt.execute(p);\r\n Console.WriteLine(p);\r\n }\r\n\r\n public void executeAllSteps()\r\n {\r\n ProgramState p = repo.getCurrentPrgState();\r\n while (!p.Stack.isEmpty())\r\n {\r\n this.executeOneStep();\r\n repo.logPrgState();\r\n }\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6738410592079163,
"alphanum_fraction": 0.6738410592079163,
"avg_line_length": 15.257143020629883,
"blob_id": "4533dd4dabbe4f25a138bc30fb7d73f02206aaad",
"content_id": "33fd183b8160820cf284f837e9ced779253db1f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 35,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/AstroWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_AstronomerWindow.h\"\r\n#include \"controller.h\"\r\n#include \"astronomer.h\"\r\n\r\nclass AWindow : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tAWindow(Controller& c, Astronomer a, QWidget *parent = Q_NULLPTR);\r\n\t~AWindow() {}\r\n\r\nprivate:\r\n\tUi::AstroWindow ui;\r\n\r\n\tController& contro;\r\n\tstd::vector<Star> stars;\r\n\tAstronomer astro;\r\n\tstd::vector<Star> filter;\r\n\tint ok;\r\n\t\r\n\tvoid connectSignalsAndSlots();\r\n\tint getSelectedIndex();\r\n\tvoid populate();\r\n\tvoid populateList();\r\n\r\n\tprivate slots:\r\n\tvoid add();\r\n\tvoid modify();\r\n\tvoid filterMe();\r\n\r\n};\r\n"
},
{
"alpha_fraction": 0.5979630351066589,
"alphanum_fraction": 0.604931652545929,
"avg_line_length": 20.487951278686523,
"blob_id": "737dd13149a5599f41e445732cf3d0b542a94948",
"content_id": "b1520f4a12b193ca48cabd5720895b08d956b2c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3731,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 166,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/studentRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <vector>\r\n#include \"student.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n#include <assert.h>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass StudentRepo\r\n{\r\nprivate:\r\n\tstd::vector<T> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tStudentRepo(std::string filename) :filename{ filename } { this->readFromFile(); this->sortMe(); }\r\n\tStudentRepo() :filename{ \"\" } {}\r\n\t~StudentRepo() {}\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\t\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\tvoid setElems(std::vector<T> v) { elems = v; }\r\n\t//Sets the grade of the student from the given position to be equal to gr\r\n\tvoid gradeStudent(int pos, double gr) { elems[pos].setGrade(gr); }\r\n\t//Sets the teacher name for the student, used after giving a grade\r\n\tvoid setTeacher(int pos, std::string name);\r\n\tint findByID(int id);\r\n\r\n\tvoid sortOne();\r\n\tvoid sortTwo();\r\n\tvoid sortMe();\r\n\tstd::vector<T> getByGroups(std::vector<int> gr);\r\n\r\n\t//Adds a new element to the repository\r\n\tvoid add(T e) { elems.push_back(e); }\r\n\t//Deletes the element on the given position\r\n\tvoid del(int pos) { elems.erase(elems.begin() + pos); }\r\n};\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tint id, group;\r\n\t\tstd::string name, teacher;\r\n\t\tdouble grade;\r\n\t\tid = stoi(v[0]);\r\n\t\tname = v[1];\r\n\t\tgroup = stoi(v[2]);\r\n\t\tgrade = stod(v[3]);\r\n\t\tteacher = v[4];\r\n\t\tStudent m{ id,name,group,grade,teacher };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\ntemplate <typename T>\r\nbool cmp(const T & e1, const T & e2) {\r\n\tif (e1.group != e2.group)\r\n\t\treturn (e1.group < e2.group);\r\n\treturn (e1.name < e2.name);\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::setTeacher(int pos, std::string name)\r\n{\r\n\telems[pos].setTeacher(name);\r\n}\r\n\r\ntemplate<typename T>\r\ninline int StudentRepo<T>::findByID(int id)\r\n{\r\n\tfor (int i = 0;i < elems.size();i++)\r\n\t\tif (elems[i].getID() == id)\r\n\t\t\treturn i;\r\n\treturn -1;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::sortOne()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\r\n\tfor (i = 0; i < this->getLenght() - 1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\t\tif (this->elems[j].getGroup() < this->elems[min_idx].getGroup())\r\n\t\t\t\tmin_idx = j;\r\n\r\n\t\tT a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::sortTwo()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\r\n\tfor (i = 0; i < this->getLenght() - 1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\tif(this->elems[j].getGroup()== this->elems[min_idx].getGroup()) \r\n\t\t{\r\n\t\t\tif (this->elems[j].getName() < this->elems[min_idx].getName())\r\n\t\t\t\tmin_idx = j;\r\n\t\t}\r\n\r\n\t\tT a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::sortMe()\r\n{\r\n\tthis->sortOne();\r\n\tthis->sortTwo();\r\n}\r\n\r\ntemplate<typename T>\r\ninline std::vector<T> StudentRepo<T>::getByGroups(std::vector<int> gr)\r\n{\r\n\tstd::vector<T> go;\r\n\tfor (auto i : elems)\r\n\t\tfor (auto j : gr)\r\n\t\t\tif (i.getGroup() == j)\r\n\t\t\t\tgo.push_back(i);\r\n\treturn go;\r\n}"
},
{
"alpha_fraction": 0.6692606806755066,
"alphanum_fraction": 0.6692606806755066,
"avg_line_length": 14.1875,
"blob_id": "4a8ab37db5ee645b03c696f7516157005ffdcb15",
"content_id": "bc218421dfa9f743f6ae18f708af0b8d58528be5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 16,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"dynamic.h\"\r\n#include <iostream>\r\n\r\nclass Repository\r\n{\r\nprivate:\r\n\tVector players;\r\npublic:\r\n\tint addPlayer(TElement& e);\r\n\tvoid sortList();\r\n\tint total(const std::string country);\r\n\tVector& getPlayers() {\r\n\t\treturn players;\r\n\t};\r\n};"
},
{
"alpha_fraction": 0.5779569745063782,
"alphanum_fraction": 0.5846773982048035,
"avg_line_length": 15.302325248718262,
"blob_id": "be2bb75f3057128d0945e4716dcec41f29fb2bd6",
"content_id": "1969e1ed922c40e73beadd8dceb990321544a564",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 744,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 43,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\ntemplate <typename T>\r\nbool Controller<T>::add(T s)\r\n{\r\n\tif (this->findByID(s.getID()) == -1)\r\n\t{\r\n\t\tthis->repo.add(s);\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\ntemplate <typename T>\r\nbool Controller<T>::del(int id)\r\n{\r\n\tint k = this->findByID(id);\r\n\tif (k == -1)\r\n\t\treturn false;\r\n\tthis->repo.del(k);\r\n\treturn true;\r\n}\r\n\r\ntemplate <typename T>\r\nbool Controller<T>::update(int id, std::string name, int age)\r\n{\r\n\tint k = this->findByID(id);\r\n\tif (k == -1)\r\n\t\treturn false;\r\n\tthis->repo.update(id, name, age);\r\n\treturn true;\r\n}\r\n\r\ntemplate <typename T>\r\nint Controller<T>::findByID(int id)\r\n{\r\n\tfor (int i = 0;i < this->repo.getLenght();i++)\r\n\t{\r\n\t\tif (this->repo[i].getID() == id)\r\n\t\t\treturn i;\r\n\t}\r\n\treturn -1;\r\n}\r\n"
},
{
"alpha_fraction": 0.5986219048500061,
"alphanum_fraction": 0.6055124998092651,
"avg_line_length": 19.924528121948242,
"blob_id": "42154a006eb19af7b7dc75e11bc4fdbc3beaa904",
"content_id": "bcc2c3123a1d601d09f1f99942671c8fd6d89fde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2322,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 106,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#pragma once\r\n#include \"domain.h\"\r\n#include <sstream>\r\n#include <string>\r\n#include <fstream>\r\n#include <assert.h>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass Repository\r\n{\r\nprivate:\r\n\tstd::vector<T> elems{};\r\n\tstd::string filename;\r\npublic:\r\n\tRepository() :filename{ \"\" } {}\r\n\tRepository(std::string file) :filename{ file } { this->readFromFile(); }\r\n\tRepository(std::string file, std::vector<T> el) :filename{ file }, elems{ el } { this->readFromFile(); }\r\n\t~Repository() {}\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\tT operator[](int pos) { return this->elems[pos]; }\r\n\r\n\tvoid add(T e) { this->elems.push_back(e); }\r\n\r\n\t//Sorts the elements from the repository in alphabetical order, by their family name.\r\n\tvoid sort();\r\n\t//Returns an integer that represents the overall duration of tasks with a given priority\r\n\tint calculateDuration(int prio);\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n};\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::sort()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\r\n\tfor (i = 0; i < this->getLenght() - 1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\t\tif (this->elems[j].getPriority() < this->elems[min_idx].getPriority())\r\n\t\t\t\tmin_idx = j;\r\n\r\n\t\tT a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\ninline int Repository<T>::calculateDuration(int prio)\r\n{\r\n\tint ok=0;\r\n\tfor (auto i : this->elems)\r\n\t{\r\n\t\tif (i.getPriority() == prio)\r\n\t\t\tok = ok + i.getDuration();\r\n\t}\r\n\treturn ok;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tstring f, n, p;\r\n\t\tf = v[0];\r\n\t\tn = v[1];\r\n\t\tp = v[2];\r\n\t\tint ok1, ok2;\r\n\t\tok1 = stoi(n);\r\n\t\tok2 = stoi(p);\r\n\t\tTask m{ f,ok1,ok2 };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}"
},
{
"alpha_fraction": 0.6719242930412292,
"alphanum_fraction": 0.6719242930412292,
"avg_line_length": 14.789473533630371,
"blob_id": "f47667be23ee3513ec5fe404621f3dbf716dc00b",
"content_id": "3694e5d50aeb49b1767963b93aebc0fabd19414d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include <iostream>\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tRepository repo;\r\npublic:\r\n\tController(const Repository& r) :repo{ r } {}\r\n\r\n\tRepository getRepo()const { return repo; };\r\n\r\n\tint addRepo(TElement& e);\r\n\r\n\tvoid sortRepo();\r\n\r\n\tint totalGoals(const std::string country);\r\n};"
},
{
"alpha_fraction": 0.6662125587463379,
"alphanum_fraction": 0.6716621518135071,
"avg_line_length": 23.789474487304688,
"blob_id": "19f33ddba0b395bd785763457b4e32e4a362217f",
"content_id": "0f2672617247b794329767dfad86a6bdc273c83f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1468,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 57,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/TeacherWindow.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"TeacherWindow.h\"\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nSepareteTeacher::SepareteTeacher(Repository<Student>* r,std::string name,std::vector<int> gr, QWidget *parent)\r\n\t:repo{ r }, name{ name }, groups{ gr }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->students = this->repo->getByGroups(gr);\r\n\tthis->populate();\r\n}\r\n\r\nvoid SepareteTeacher::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.GradeButton, SIGNAL(clicked()), this, SLOT(grade()));\r\n}\r\n\r\nint SepareteTeacher::getSelectedIndex()\r\n{\r\n\tif (ui.StudentList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.StudentList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid SepareteTeacher::populate()\r\n{\r\n\tif (ui.StudentList->count() != 0)\r\n\t\tui.StudentList->clear();\r\n\tfor (auto m : this->students)\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.StudentList->addItem(listItemWidget);\r\n\t}\r\n\tif (students.size() > 0)\r\n\t\tui.StudentList->setCurrentRow(0);\r\n}\r\n\r\nvoid SepareteTeacher::grade()\r\n{\r\n\tstring g = ui.GradeLine->text().toStdString();\r\n\tdouble gr = stod(g);\r\n\tint k = this->getSelectedIndex();\r\n\tint id = students[k].getID();\r\n\tstudents[k].setGrade(gr);\r\n\tint f = repo->findByID(id);\r\n\trepo->setGrade(f, gr);\r\n\tthis->populate();\r\n}"
},
{
"alpha_fraction": 0.4584076404571533,
"alphanum_fraction": 0.4641641080379486,
"avg_line_length": 38.71287155151367,
"blob_id": "55bfe01e6f4b0aa1ffdcf3da44b0ba094f87024d",
"content_id": "0438a19b129b78e023e0ce0dd28893644f55b2a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12334,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 303,
"path": "/MyProjects/FP/FP/Assignment 5/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from controller import *\r\nfrom domain import *\r\nfrom undocontroller import *\r\nclass UI:\r\n def __init__(self,StudentController=Controller(),AssignmentController=Controller(),GradeController=Controller()\r\n ,StudentAssignmentsController=Controller(),studentAverageGrade=Controller()):\r\n self.__sc=StudentController\r\n self.__ac=AssignmentController\r\n self.__gc=GradeController\r\n self.__sac=StudentAssignmentsController\r\n self.__sagc=studentAverageGrade\r\n self.__undoController=UndoController()\r\n def printMenu(self):\r\n '''\r\n Prints the menu:\r\n :return:\r\n '''\r\n menu=' The commands are:\\n'\r\n menu+='1. Add a student\\n'\r\n menu+='2. Add an assignment\\n'\r\n menu+='3. Remove a student\\n'\r\n menu+='4. Remove an assignment\\n'\r\n menu+='5. Update the data from a student\\n'\r\n menu+='6. Update the data from an assignment\\n'\r\n menu+='7. Print the list of students\\n'\r\n menu+='8. Print the list of assignments\\n'\r\n menu+='9. Give an assignment to a student\\n'\r\n menu+='10. Give an assignment to a group\\n'\r\n menu+='11. Grade a student for a given assignment\\n'\r\n menu+='12. Print the best students ordered by their average grade\\n'\r\n menu+='13. Print the students that did not finish their assignments in time\\n'\r\n menu+='14. Print all the students who received a given assignment ordered alphabetically\\n'\r\n menu+='15. Print all assignments for which there is at least one grade, sorted in decreasing order\\n'\r\n menu+='16. Undo the last operation\\n'\r\n menu+='17. Redo the operation that was undone\\n'\r\n menu+='18. Filter students that have an average grade greater than a given grade\\n'\r\n menu+='0. Exit\\n'\r\n print(menu)\r\n def printList(self,lst):\r\n '''\r\n Prints the list of classes\r\n in:param lst:\r\n :return:\r\n '''\r\n for i in range(len(lst)):\r\n print(lst[i])\r\n def readUpdateStudent(self):\r\n '''\r\n Reads the modification of the student\r\n :return:\r\n '''\r\n try:\r\n x=int(input('Give the student id:'))\r\n y=input(\"Give the student's new name:\")\r\n z=int(input(\"Give the student's new group:\"))\r\n a=Student(x,y,z)\r\n return a\r\n except ValueError:\r\n print(\"Invalid Student format!\")\r\n return\r\n def readUpdateAssignment(self):\r\n '''\r\n Reads the modification of the assignment\r\n :return:\r\n '''\r\n try:\r\n x=int(input('Give the assignment id:'))\r\n y=input(\"Give the assignment's new description:\")\r\n z=input(\"Give the assignment's new deadline:\")\r\n b = z\r\n b = b.split('.')\r\n if len(b) == 3:\r\n a = Assignment(x, y, z)\r\n return a\r\n else:\r\n raise ValueError\r\n except ValueError:\r\n print(\"Invalid Assignment format!\")\r\n return\r\n def readStudent(self):\r\n '''\r\n Reads the student and returns it if it has a valid format\r\n :return:\r\n '''\r\n try:\r\n x=int(input('Give the student id:'))\r\n y=input('Give the student name:')\r\n z=int(input('Give the group of the student:'))\r\n a=Student(x,y,z)\r\n return a\r\n except ValueError:\r\n print('Invalid student format!')\r\n return\r\n def readAssignment(self):\r\n '''\r\n Reads the assignment and returns it if it has a valid format\r\n :return:\r\n '''\r\n try:\r\n x=int(input('Give the assignment id:'))\r\n y=input('Give the assignment description:')\r\n z=input('Give the deadline:')\r\n b=z\r\n b=b.split('.')\r\n if len(b)==3:\r\n a=Assignment(x,y,z)\r\n return a\r\n else:\r\n raise ValueError\r\n except ValueError:\r\n print('Invalid assignment format!')\r\n return\r\n def readGrade(self):\r\n '''\r\n Reads the grade and returns it if it has a valid format\r\n :return:\r\n '''\r\n try:\r\n x=int(input('Give the assignment id:'))\r\n y=int(input('Give the student id:'))\r\n z=int(input('Give the grade:'))\r\n a=Grade(x,y,z)\r\n return a\r\n except ValueError:\r\n print('Invalid grade format!')\r\n return\r\n def start(self):\r\n '''\r\n Creates a loop where the problem is solved\r\n :return:\r\n '''\r\n self.printMenu()\r\n while True:\r\n read=input(\"\\nEnter the command ('help' for a list of commands):\")\r\n read = read.strip()\r\n if read=='0':\r\n print('\\nCYA LATER ALLIGATOR!')\r\n break\r\n elif read=='help':\r\n self.printMenu()\r\n elif read=='1':\r\n student=self.readStudent()\r\n self.__sc.add(student)\r\n redo=FunctionCall(self.__sc.add,student)\r\n undo=FunctionCall(self.__sc.remove,student)\r\n operation=Operation(redo,undo)\r\n self.__undoController.newOperation()\r\n self.__undoController.recordOperation(operation)\r\n\r\n elif read=='2':\r\n assignment=self.readAssignment()\r\n self.__ac.add(assignment)\r\n redo=FunctionCall(self.__ac.add,assignment)\r\n undo = FunctionCall(self.__ac.remove, assignment)\r\n operation=Operation(redo,undo)\r\n self.__undoController.recordOperation(operation)\r\n elif read=='3':\r\n x = int(input('Give The student id:'))\r\n a = self.__sc.findByStuID(x)\r\n c = self.__sc.get(a)\r\n self.__sc.removeIndex(a)\r\n self.__sac.deleteStudentAssignments(c)\r\n self.__gc.deleteStudent(x)\r\n undo = FunctionCall(self.__sc.add,c)\r\n redo = FunctionCall(self.__sc.remove,c)\r\n operation = Operation(redo, undo)\r\n self.__undoController.newOperation()\r\n self.__undoController.recordOperation(operation)\r\n elif read=='4':\r\n x = int(input('Give the assignment id:'))\r\n a = self.__ac.findByAssiID(x)\r\n b = self.__ac.get(a)\r\n self.__ac.removeIndex(a)\r\n self.__gc.deleteAssignment(x)\r\n undo = FunctionCall(self.__ac.add, b)\r\n redo = FunctionCall(self.__ac.remove, b)\r\n operation = Operation(redo, undo)\r\n self.__undoController.recordOperation(operation)\r\n elif read=='5':\r\n a=self.readStudent()\r\n b=self.readUpdateStudent()\r\n self.__sc.update(a,b)\r\n redo=FunctionCall(self.__sc.update,a,b)\r\n undo=FunctionCall(self.__sc.update,b,a)\r\n operation = Operation(redo, undo)\r\n self.__undoController.recordOperation(operation)\r\n elif read=='6':\r\n a=self.readAssignment()\r\n b=self.readUpdateAssignment()\r\n self.__ac.update(a,b)\r\n redo = FunctionCall(self.__ac.update, a, b)\r\n undo = FunctionCall(self.__ac.update, b, a)\r\n operation = Operation(redo, undo)\r\n self.__undoController.recordOperation(operation)\r\n elif read=='7':\r\n print(self.__sc)\r\n elif read=='8':\r\n print(self.__ac)\r\n elif read=='9':\r\n x=int(input('Give the assignment id:'))\r\n a=self.__ac.findByAssiID(x)\r\n b=self.__ac.get(a)\r\n x=int(input('Give the student id:'))\r\n a=self.__sc.findByStuID(x)\r\n c=self.__sc.get(a)\r\n self.__sac.giveAssignmentToStudent(c,b)\r\n print(self.__sac)\r\n elif read=='10':\r\n x = int(input('Give the assignment id:'))\r\n a = self.__ac.findByAssiID(x)\r\n b = self.__ac.get(a)\r\n c=int(input('Give a group:'))\r\n lst = self.__sc.groupList(c)\r\n self.__sac.giveAssignmentToGroup(c,b,lst)\r\n print(self.__sac)\r\n elif read=='11':\r\n x = int(input('Give the assignment id:'))\r\n a = self.__ac.findByAssiID(x)\r\n b = self.__ac.get(a)\r\n y = int(input('Give the student id:'))\r\n c = self.__sc.findByStuID(y)\r\n d = self.__sc.get(c)\r\n ok=1\r\n for i in range(len(self.__gc)):\r\n if self.__gc.get(i).getAssignmentID()==x:\r\n ok=0\r\n print('Assignment already graded!')\r\n l=self.__sac.findStudent(d)\r\n if l==-1:\r\n print('Student has no assignment!')\r\n ok=0\r\n m=self.__sac.get(l).isFound(b)\r\n if m==False:\r\n print(\"Student doesn't have this assignment!\")\r\n ok=0\r\n if ok==1:\r\n try:\r\n h=int(input('Give the grade:'))\r\n p=Grade(x,y,h)\r\n self.__gc.add(p)\r\n except ValueError:\r\n print('Invalid grade format!')\r\n print(self.__gc)\r\n elif read=='12':\r\n l=[]\r\n for i in range(len(self.__sac)):\r\n lst=self.__sac.assignmentList(i)\r\n student=self.__sac.get(i).getStudent()\r\n id1=student.getStudentID()\r\n grade=self.__gc.averageGrade(id1,lst)\r\n a=[]\r\n a.append(student)\r\n a.append(grade)\r\n l.append(a)\r\n combsort(l)\r\n for i in range(len(l)):\r\n print(l[i][0],'; with grade: ',l[i][1])\r\n elif read=='13':\r\n l=[]\r\n for i in range(len(self.__sac)):\r\n lst=self.__sac.assignmentList(i)\r\n id1=self.__sac.get(i).getStudent().getStudentID()\r\n g=self.__gc.averageGrade(id1,lst)\r\n if g==-1:\r\n l.append(self.__sac.get(i).getStudent())\r\n for i in range(len(l)):\r\n print(l[i])\r\n elif read=='14':\r\n x = int(input('Give the assignment id:'))\r\n a = self.__ac.findByAssiID(x)\r\n b = self.__ac.get(a)\r\n lst=[]\r\n for i in range(len(self.__sac)):\r\n if self.__sac.get(i).isFound(b)==True:\r\n student=self.__sac.get(i).getStudent()\r\n lst.append(student)\r\n combsort(lst)\r\n for i in range(len(lst)):\r\n print(lst[i])\r\n elif read=='15':\r\n lst=self.__gc.repoList()\r\n combsort(lst)\r\n for i in range(len(lst)):\r\n x=lst[i].getAssignmentID()\r\n a = self.__ac.findByAssiID(x)\r\n b = self.__ac.get(a)\r\n y=lst[i].getStudentID()\r\n c = self.__sc.findByStuID(x)\r\n d = self.__sc.get(a)\r\n print(b,'from student: ',d,' with the grade: ',lst[i].getGrade())\r\n elif read=='16':\r\n self.__undoController.undo()\r\n elif read=='17':\r\n self.__undoController.redo()\r\n elif read=='18': #filter students by average grade\r\n x=int(input(\"Enter the grade:\"))\r\n self.__gc.filterByGrade(x)\r\n lst=self.__gc.repoList()\r\n combsort(lst)\r\n print(lst)\r\n else:\r\n print(len(self.__sc))\r\n print('Invalid command!')"
},
{
"alpha_fraction": 0.49410223960876465,
"alphanum_fraction": 0.49934470653533936,
"avg_line_length": 33.53488540649414,
"blob_id": "ea8078261c5e288c28a5c299bfc0f3ebefeeaab2",
"content_id": "2b93a7acc07fdb47903ab6e3a5ecec49faae5eb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1526,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 43,
"path": "/MyProjects/FP/FP/Practice Test 2/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from controller import *\r\nfrom repository import *\r\nfrom domain import *\r\nclass UI:\r\n def __init__(self,addressController=Controller()):\r\n self.__ac=addressController\r\n def readAddress(self):\r\n x=int(input(\"Enter the address ID:\"))\r\n y=input(\"Enter the address name:\")\r\n z=int(input(\"Enter the x value:\"))\r\n t=int(input(\"Enter the y value:\"))\r\n a=Address(x,y,z,t)\r\n return a\r\n def printMenu(self):\r\n aMenu=\"1. Add an address to the list\\n\"\r\n aMenu+=\"2. List all addresses\\n\"\r\n aMenu+=\"3. List the addresses that are in the distance d of a given position\\n\"\r\n aMenu+=\"0. Exit\\n\"\r\n aMenu+=\"help\"\r\n print(aMenu)\r\n def printList(self,lst):\r\n for i in range(len(lst)):\r\n print(lst[i])\r\n def start(self):\r\n self.printMenu()\r\n while True:\r\n command=input(\"Enter the command:\")\r\n if command=='0':\r\n break\r\n elif command =='help':\r\n self.printMenu()\r\n elif command=='1':\r\n a=self.readAddress()\r\n self.__ac.add(a)\r\n elif command=='2':\r\n print(self.__ac)\r\n elif command=='3':\r\n d = int(input(\"Enter the maximum distance:\"))\r\n x = int(input(\"Enter the x value:\"))\r\n y = int(input(\"Enter the y value:\"))\r\n self.__ac.distanceAddress(d,x,y)\r\n else:\r\n print(\"Invalid command!\")"
},
{
"alpha_fraction": 0.6633866429328918,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 21.451923370361328,
"blob_id": "54b7b1306b61e63bfedc3b8091edad52b2059d92",
"content_id": "96fc5f14e5ed50315d62a9676058e96782130512",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2439,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 104,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/MainTeacher.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"MainTeacher.h\"\r\n#include <QMessageBox>\r\n#include <string>\r\n#include <QIcon>\r\n\r\nusing namespace std;\r\n\r\nMainTeacher::MainTeacher(Controller& c,QWidget *parent)\r\n\t:controller{ c }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populate();\r\n\tthis->showAll();\r\n}\r\n\r\nMainTeacher::~MainTeacher()\r\n{\r\n\tthis->controller.saveStudents();\r\n\tfor (auto i : allWindows)\r\n\t\tdelete i;\r\n}\r\n\r\nvoid MainTeacher::populate()\r\n{\r\n\tif (ui.listWidget->count() != 0)\r\n\t\tui.listWidget->clear();\r\n\tfor (auto m : this->controller.getStudents().getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.listWidget->addItem(listItemWidget);\r\n\t}\r\n\tif (this->controller.getStudents().getLenght() > 0)\r\n\t\tui.listWidget->setCurrentRow(0);\r\n\tthis->modifyAll();\r\n}\r\n\r\nvoid MainTeacher::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.AddButton, SIGNAL(clicked()), this, SLOT(add()));\r\n\tQObject::connect(ui.DeleteButton, SIGNAL(clicked()), this, SLOT(del()));\r\n}\r\n\r\nvoid MainTeacher::modifyAll()\r\n{\r\n\tfor (auto i : allWindows)\r\n\t{\r\n\t\ti->populate();\r\n\t}\r\n}\r\n\r\nvoid MainTeacher::showAll()\r\n{\r\n\tvector<string> names = controller.getTeachersNames();\r\n\r\n\tfor (auto i : names)\r\n\t{\r\n\t\tSomeTeacher* t = new SomeTeacher(controller.getStudents(), i, controller.getTeacherGroups(i));\r\n\t\tthis->allWindows.push_back(t);\r\n\t\tt->show();\r\n\t}\r\n}\r\n\r\nint MainTeacher::getSelectedIndex()\r\n{\r\n\tif (ui.listWidget->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.listWidget->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid MainTeacher::add()\r\n{\r\n\tstd::string name = ui.NameLine->text().toStdString();\r\n\tstd::string gr = ui.GroupLine->text().toStdString();\r\n\tint group = stoi(gr);\r\n\tint validID = controller.getValidID();\r\n\tStudent s{ validID, name,group };\r\n\tthis->controller.addStudent(s);\r\n\tcontroller.sortMe();\r\n\tthis->modifyAll();\r\n\tthis->populate();\r\n\tui.GroupLine->clear();\r\n\tui.NameLine->clear();\r\n}\r\n\r\nvoid MainTeacher::del()\r\n{\r\n\tQMessageBox msgBox;\r\n\tif (msgBox.question(this, \"Delete\", \"Do you want to delete the elements?\", QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel)\r\n\t\treturn;\r\n\r\n\tint k = this->getSelectedIndex();\r\n\tthis->controller.delStudent(k);\r\n\tthis->modifyAll();\r\n\tthis->populate();\r\n}\r\n"
},
{
"alpha_fraction": 0.5538277626037598,
"alphanum_fraction": 0.5885167717933655,
"avg_line_length": 18.390243530273438,
"blob_id": "2cc5c24e540eec0633062bd6da0fafe7544c5a32",
"content_id": "9ff9ba1e770548e3aced4de7c898b5177e29d4db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 836,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 41,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Time.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"domain.h\"\r\n#include \"repository.h\"\r\n#include <assert.h>\r\n\r\nusing namespace std;\r\n\r\nvoid testSort()\r\n{\r\n\tRepository<Task> r{};\r\n\tTask t1{ \"Ok\",1,3 }, t2{ \"Vasilica\",1,2 }, t3{ \"Uite\",1,1 };\r\n\tr.add(t1);\r\n\tr.add(t2);\r\n\tr.add(t3);\r\n\tr.sort();\r\n\tassert(r[0].getDescription() == \"Uite\");\r\n\tassert(r[1].getDescription() == \"Vasilica\");\r\n\tassert(r[2].getDescription() == \"Ok\");\r\n}\r\n\r\nvoid testCalculateDuration()\r\n{\r\n\tRepository<Task> r{};\r\n\tTask t1{ \"Ok\",1,1 }, t2{ \"Vasilica\",1,1 }, t3{ \"Uite\",1,1 };\r\n\tr.add(t1);\r\n\tr.add(t2);\r\n\tr.add(t3);\r\n\tassert(r.calculateDuration(1) == 3);\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\ttestSort();\r\n\ttestCalculateDuration();\r\n\tRepository<Task> r{ \"All.txt\" };\r\n\tTime w{ r };\r\n\tw.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.6621983647346497,
"alphanum_fraction": 0.6621983647346497,
"avg_line_length": 29.25,
"blob_id": "cd3151fd132ed5b1749c10c9e238384920fb6213",
"content_id": "ab76cd7f6ab825e983e2e99e8a214041d7b0a8ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 373,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 12,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/sportsman.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n\r\nclass Sportsman : public Student {\r\nprivate:\r\n\tstd::string sport;\r\npublic:\r\n\tSportsman(std::string _sport, int _id, std::string _name, int _age) :Student{ _id,_name,_age }, sport{ _sport } {}\r\n\tstd::string getSport() { return sport; }\r\n\tvoid setString(std::string sport) { this->sport = sport; }\r\n\tstd::string overString() override;\r\n};"
},
{
"alpha_fraction": 0.6473317742347717,
"alphanum_fraction": 0.6473317742347717,
"avg_line_length": 18.619047164916992,
"blob_id": "3451c75ca7d2bd752f45ba5f7f4f924958f76618",
"content_id": "82a4023718b78cab2e7ebea617fddd3e386cc09e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"Domain.h\"\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nclass Repository {\r\nprivate:\r\n\tvector<Pilot> elems{};\r\npublic:\r\n\tRepository() {};\r\n\tvector<Pilot> getAll() {\r\n\t\treturn elems;\r\n\t}\r\n\tPilot& operator[](int pos) { return elems[pos]; };\r\n\tvoid add(Pilot p);\r\n\tvoid del(int pos);\r\n\tvoid update(int id, string name, int age, int flights);\r\n\tint getLenght() { return elems.size(); }\r\n};"
},
{
"alpha_fraction": 0.5386792421340942,
"alphanum_fraction": 0.5386792421340942,
"avg_line_length": 21.04347801208496,
"blob_id": "43bbc9740807d53786824cd4f362c625bb8f1562",
"content_id": "0346a8234f1e5bafa9dfc5666d1587ab5bee9fdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1060,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 46,
"path": "/MyProjects/MAP/Practical Exam/Procedures/src/Model/Utilities/Stack.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Utilities;\r\n\r\nimport java.util.ArrayDeque;\r\nimport java.util.ArrayList;\r\nimport java.util.Deque;\r\nimport java.util.List;\r\n\r\npublic class Stack<T> implements IStack<T> {\r\n private Deque<T> elements=new ArrayDeque<T>();\r\n\r\n @Override\r\n public void add(T e){\r\n elements.push(e);\r\n }\r\n public Iterable<T> getElements(){\r\n return elements;\r\n }\r\n public boolean isEmpty(){\r\n return elements.isEmpty();\r\n }\r\n public T top(){\r\n return elements.peekFirst();\r\n }\r\n public T pop(){\r\n return elements.pop();\r\n }\r\n public List<T> getToList(){List<T> l=new ArrayList<T>();\r\n for(T e:elements) l.add(e); return l;}\r\n\r\n public String toString(){\r\n StringBuilder sb = new StringBuilder();\r\n\r\n for(T i : elements){\r\n sb.append(i).append(\" \");\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public IStack<T> copy(){\r\n IStack<T> s=new Stack<T>();\r\n for(T el:elements){\r\n s.add(el);\r\n }\r\n return s;\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.539393961429596,
"alphanum_fraction": 0.5454545617103577,
"avg_line_length": 9.928571701049805,
"blob_id": "3bbf1688114c56be486253e595166b7acfc6901c",
"content_id": "f9c327bd6d068b7384f0016f4f9c9f4359e67662",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 165,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 14,
"path": "/MyProjects/OOP/OOP/Assignment 1/Project1/a.c",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include<stdio.h>\r\n\r\n#include <stdlib.h>\r\n#include<Windows.h>\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tprintf(\"LOL%d\\n\",n);\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.541167676448822,
"alphanum_fraction": 0.5419161915779114,
"avg_line_length": 28.363636016845703,
"blob_id": "3049f0cb6081462511846bfe4a1d7ac5f8eba3e8",
"content_id": "c267048e391caa35c40034bd5d90b7bbb304416b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1336,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 44,
"path": "/MyProjects/OOP/OOP/Practice 3/New/html.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"html.h\"\r\n#include <fstream>\r\n#include \"repoException.h\"\r\n#include <Windows.h>\r\n#include <shellapi.h>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid HTML::setRepo(Repository r)\r\n{\r\n\tthis->repo = r;\r\n\tthis->writeToFile();\r\n}\r\n\r\nvoid HTML::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\tthrow FileExceptionF(\"Error opening file for writing!\");\r\n\tfile << \"<!DOCTYPE html> \\n <html> \\n \\t<head> \\n \\t\\t <title>MovieList</title> \\n\";\r\n\tfile << \"\\t</head> \\n \\t<body> \\n \\t\\t<table border=\\\"1\\\"> \\n \\t\\t<tr>\\n\";\r\n\tfile << \"\\t\\t\\t<td>Title</td> \\n \\t\\t\\t<td>Genre</td> \\n \\t\\t\\t<td>Year</td> \\n \\t\\t\\t <td>Likes</td>\\n\";\r\n\tfile << \"\\t\\t\\t<td>Link to trailer</td> \\n \\t\\t </tr>\\n\";\r\n\tfor (auto dog : this->repo.getAll())\r\n\t{\r\n\t\tfile << \"\\t\\t<tr>\\n\";\r\n\t\tfile << \"\\t\\t\\t<td>\" << dog.getTitle() << \"</td>\\n\";\r\n\t\tfile << \"\\t\\t\\t<td>\" << dog.getGenre() << \"</td>\\n\";\r\n\t\tfile << \"\\t\\t\\t<td>\" << dog.getYear() << \"</td>\\n\";\r\n\t\tfile << \"\\t\\t\\t<td>\" << dog.getLikes() << \"</td>\\n\";\r\n\t\tfile << \"\\t\\t\\t<td><a href=\" << dog.getTrailer() << \">Link</td>\\n\";\r\n\t\tfile << \"\\t\\t</tr>\\n\";\r\n\t}\r\n\tfile << \"\\t\\t</table>\\n\";\r\n\tfile << \"\\t</body>\\n\";\r\n\tfile << \"</html>\\n\";\r\n\tfile.close();\r\n}\r\n\r\nvoid HTML::displayHTML()\r\n{\r\n\tShellExecuteA(NULL, NULL, \"chrome.exe\", this->filename.c_str(), NULL, SW_SHOWMAXIMIZED);\r\n}\r\n"
},
{
"alpha_fraction": 0.5265486836433411,
"alphanum_fraction": 0.5265486836433411,
"avg_line_length": 21.789474487304688,
"blob_id": "3dbec954cdc20a1e0457378ff5c7ebc776add1f1",
"content_id": "b586c9339c3e38ef7a762f63d071b42a102956cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 452,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/student.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"student.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nstd::string Student::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"ID: \" << id << \", Name: \" << name << \", Group: \" << group << \", Grade: \" << grade << \", Teacher: \" << teacher;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Student::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << id << ',' << name << ',' << group << ',' << grade << ',' << teacher;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.6051158905029297,
"alphanum_fraction": 0.6067146062850952,
"avg_line_length": 19.568965911865234,
"blob_id": "07a52112b879cb4e045a7d673b2dc90ddf9a218e",
"content_id": "6ab1803903dec58fa9df4cc62c4ad24001c5e86a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1251,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 58,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/teacherRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <vector>\r\n#include <string>\r\n#include \"teacher.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass TeacherRepo\r\n{\r\nprivate:\r\n\tstd::vector<T> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tTeacherRepo(std::string filename) :filename{ filename } { this->readFromFile(); }\r\n\tTeacherRepo() :filename{ \"\" } {}\r\n\t~TeacherRepo() {}\r\n\r\n\tvoid readFromFile();\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\tvoid setElems(std::vector<T> v) { elems = v; }\r\n\r\n\tvoid add(T e) { elems.push_back(e); }\r\n\tvoid del(int pos) { elems.erase(elems.begin() + pos); }\r\n};\r\n\r\ntemplate<typename T>\r\ninline void TeacherRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ';'))\r\n\t\t\tv.push_back(t);\r\n\t\tstd::string f, p;\r\n\t\tf = v[0];\r\n\t\tp = v[1];\r\n\t\tstd::stringstream aici(p);\r\n\t\tstd::vector<int> y{};\r\n\t\twhile (getline(aici, t, ','))\r\n\t\t\ty.push_back(stoi(t));\r\n\t\tTeacher m{ f,y };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n"
},
{
"alpha_fraction": 0.44767969846725464,
"alphanum_fraction": 0.44949954748153687,
"avg_line_length": 24.214284896850586,
"blob_id": "b09d889cd8b8f3b790d9eb281fa3e1197703e360",
"content_id": "c4f80509ec881302bdea5a045e0ffaac02599b59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1099,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 42,
"path": "/MyProjects/FP/FP/Practice Test 1/repository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Repository:\r\n def __init__(self):\r\n self.__data=[]\r\n def add(self,element):\r\n '''\r\n Adds an element to the list\r\n in:param element:\r\n :return:\r\n '''\r\n self.__data.append(element)\r\n def __str__(self):\r\n '''\r\n Overwrites the str for this class\r\n :return:\r\n '''\r\n s=''\r\n for i in range(len(self.__data)):\r\n s=s+str(self.__data[i])+'; '\r\n return s\r\n def getAll(self):\r\n '''\r\n Returns the list from the repository\r\n :return:\r\n '''\r\n return self.__data\r\n def get(self,index):\r\n '''\r\n Returns an element from the list by index\r\n in:param index:\r\n :return:\r\n '''\r\n return self.__data[index]\r\n def findByID(self,id):\r\n '''\r\n Returns the index of an element with a specific id\r\n in:param id:\r\n :return:\r\n '''\r\n for i in range(len(self.__data)):\r\n if len(self.__data)!=0 and self.__data[i].getID()==id:\r\n return i\r\n return -1"
},
{
"alpha_fraction": 0.47633370757102966,
"alphanum_fraction": 0.49469685554504395,
"avg_line_length": 33.094444274902344,
"blob_id": "cf4ce3e1d28a9f20fd30e41b24d1d9927f8e99bd",
"content_id": "3af013d6fe915889205bae81adecc2a1b6e495a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6317,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 180,
"path": "/MyProjects/Graphs/Graphs/Graph 6 python/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Cost:\r\n def __init__(self):\r\n self._cost = {}\r\n\r\n def addCostToEdge(self, v1, v2, c):\r\n try:\r\n self._cost[(v1, v2)] = c\r\n except ValueError:\r\n print(\"No edge! \" + str(v1) + \" \" + str(v2) + \"\\n\")\r\n\r\n def getCostFromEdge(self, v1, v2):\r\n try:\r\n return self._cost[(v1, v2)]\r\n except ValueError:\r\n print(\"No edge! \" + str(v1) + \" \" + str(v2) + \"\\n\")\r\n\r\n def setCostOfEdge(self, v1, v2, newCost):\r\n try:\r\n self._cost[(v1, v2)] = newCost\r\n except ValueError:\r\n print(\"No edge! \" + str(v1) + \" \" + str(v2) + \"\\n\")\r\n\r\nclass DirectGraph:\r\n def __init__(self, n):\r\n self._verticeIn = {}\r\n self._verticeOut = {}\r\n for i in range(n):\r\n self._verticeIn[i] = []\r\n self._verticeOut[i] = []\r\n\r\n def parseDict(self):\r\n return self._verticeOut.keys()\r\n\r\n def length(self):\r\n return len(self._verticeOut.keys())\r\n\r\n def parseVerticeOut(self, vertice):\r\n if vertice in self._verticeOut.keys():\r\n return self._verticeOut[vertice]\r\n else:\r\n print(str(vertice) + \" is not a vertex\")\r\n\r\n def parseVerticeIn(self, vertice):\r\n if vertice in self._verticeIn.keys():\r\n return self._verticeIn[vertice]\r\n else:\r\n print(str(vertice) + \" is not a vertex\")\r\n\r\n def isEdge(self, v1, v2):\r\n if v1 in self._verticeOut.keys():\r\n return v2 in self._verticeOut[v1]\r\n else:\r\n print(\"No edge! \" + str(v1) + \" \" + str(v2) + \"\\n\")\r\n\r\n def addEdge(self, v1, v2):\r\n if not self.isEdge(v1, v2):\r\n self._verticeOut[v1].append(v2)\r\n self._verticeIn[v2].append(v1)\r\n else:\r\n print(\"Edge already there!\\n\")\r\n\r\n def inDegree(self, vertice):\r\n return len(self._verticeIn[vertice])\r\n\r\n def outDegree(self, vertice):\r\n return len(self._verticeOut[vertice])\r\n\r\ndef initGraph(DirectGraph):\r\n\r\n f = open(\"in\", \"r\")\r\n\r\n Line = f.readline().strip()\r\n\r\n Line = Line.split(\" \")\r\n n = int(Line[0])\r\n m = int(Line[1])\r\n\r\n graph = DirectGraph(n)\r\n cost = Cost()\r\n lines = f.readline().strip()\r\n\r\n while m > 0:\r\n lines = lines.split(\" \")\r\n\r\n v1 = int(lines[0])\r\n v2 = int(lines[1])\r\n c = int(lines[2])\r\n\r\n graph.addEdge(v1, v2)\r\n cost.addCostToEdge(v1, v2, c)\r\n\r\n lines = f.readline().strip()\r\n\r\n m -= 1\r\n f.close()\r\n return graph, cost\r\n\r\ndef menu():\r\n print(\"1. Print the graph\")\r\n print(\"2. Get the number of vertices\")\r\n print(\"3. Given two vertices, find out whether there is an edge from the first one to the second one, and retrieve \")\r\n print(\" the Edge_id if there is an edge (the latter is not required if an edge is represented simply as a pair of vertex identifiers)\")\r\n print(\"4. Get the in degree and the out degree of a specified vertex\")\r\n print(\"5. iterate through the set of outbound edges of a specified vertex (that is, provide an iterator). For each outbound edge,\")\r\n print(\" the iterator shall provide the Edge_id of the curren edge (or the target vertex, if no Edge_id is used)\")\r\n print(\"6. Iterate through the set of inbound edges of a specified vertex (as above)\")\r\n print(\"7. Get the endpoints of an edge specified by an Edge_id (if applicable)\")\r\n print(\"8. Retrieve or modify the information (the integer) attached to a specified edge\")\r\n print(\"0. Exit\")\r\n\r\ndef start():\r\n graph, cost = initGraph(DirectGraph)\r\n\r\n while True:\r\n menu()\r\n option = int(input(\"Choose: \"))\r\n if option < 0 or option > 8:\r\n print(\"Invalid command!\\n\")\r\n elif option == 0:\r\n break\r\n elif option == 1:\r\n for v1 in graph.parseDict():\r\n for v2 in graph.parseVerticeOut(v1):\r\n print(\"[\" + str(v1) + \" , \" + str(v2) + \"]\" + \" -> \" + str(cost.getCostFromEdge(v1, v2)))\r\n elif option == 2:\r\n vertices = graph.length()\r\n print(\"There are \" + str(vertices) + \" vertices!\\n\")\r\n elif option == 3:\r\n v1 = int(input(\"First vertex: \"))\r\n v2 = int(input(\"Second vertex: \"))\r\n if graph.isEdge(v1, v2) == 1:\r\n print(\"There's an edge from \" + str(v1) + \" to \" + str(v2))\r\n else:\r\n print(\"There's no edge from \" + str(v1) + \" to \" + str(v2))\r\n elif option == 4:\r\n v1 = int(input(\"Vertex: \"))\r\n if v1 in graph.parseDict():\r\n print(graph.inDegree(v1))\r\n print(graph.outDegree(v1))\r\n else:\r\n print(\"Invalid vertex! \")\r\n elif option == 5:\r\n ok = 1\r\n v1 = int(input(\"Vertex: \"))\r\n if v1 in graph.parseDict():\r\n for v2 in graph.parseVerticeOut(v1):\r\n print(\"[\" + str(v1) + \" , \" + str(v2) + \"]\")\r\n ok = 0\r\n if ok == 1:\r\n print(\"There are no outbound edges!\\n\")\r\n else:\r\n print(\"Invalid vertex! \")\r\n elif option == 6:\r\n ok = 1\r\n v1 = int(input(\"Vertex: \"))\r\n if v1 in graph.parseDict():\r\n for v2 in graph.parseVerticeIn(v1):\r\n print(\"[\" + str(v2) + \" , \" + str(v1) + \"]\")\r\n ok = 0\r\n if ok == 1:\r\n print(\"There are no inbound edges!\\n\")\r\n else:\r\n print(\"Invalid vertex! \")\r\n elif option == 7:\r\n v1 = int(input(\"First vertex: \"))\r\n v2 = int(input(\"Second vertex: \"))\r\n if v1 in graph.parseDict() and v2 in graph.parseDict():\r\n print(\"The cost is: \" + str(cost.getCostFromEdge(v1, v2)))\r\n else:\r\n print(\"Invalid vertexes! \")\r\n elif option == 8:\r\n v1 = int(input(\"First vertex: \"))\r\n v2 = int(input(\"Second vertex: \"))\r\n if v1 in graph.parseDict() and v2 in graph.parseDict():\r\n newCost = int(input(\"The new cost: \"))\r\n cost.setCostOfEdge(v1, v2, newCost)\r\n else:\r\n print(\"Invalid vertexes! \")\r\n\r\nstart()\r\n"
},
{
"alpha_fraction": 0.496614009141922,
"alphanum_fraction": 0.5045146942138672,
"avg_line_length": 30.88888931274414,
"blob_id": "c57418a850b7e3deb9cd40ba21ca25b8395a7e5e",
"content_id": "1f5a73e1e10a041b8eb27e3d21ff162b1c483aeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 886,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 27,
"path": "/MyProjects/FP/FP/FP Test 2/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nfrom controller import *\r\nfrom domain import *\r\nclass UI:\r\n def __init__(self,personController=Controller()):\r\n self.__pc=personController\r\n def printMenu(self):\r\n menu='The commands are:\\n'\r\n menu+='day (simulates a new day)\\n'\r\n menu+='vaccinate <person id>\\n'\r\n menu+='print\\n'\r\n menu+='exit'\r\n print(menu)\r\n def start(self):\r\n self.printMenu()\r\n while True:\r\n command=input(\"Enter the command:\")\r\n command=command.split()\r\n if command[0]=='day':\r\n self.__pc.newDay()\r\n elif command[0]=='vaccinate':\r\n command[1]=int(command[1])\r\n self.__pc.vaccinate(command[1])\r\n elif command[0]=='print':\r\n print(self.__pc)\r\n elif command[0]=='exit':\r\n break"
},
{
"alpha_fraction": 0.532903254032135,
"alphanum_fraction": 0.532903254032135,
"avg_line_length": 24.79310417175293,
"blob_id": "4c334549b83b8d8a098015d00e01491fd371e98f",
"content_id": "f4c3d6510e614bfd3d9a947facd26c7411c905bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 775,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 29,
"path": "/MyProjects/FP/FP/Assignment 5/exp.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import pickle\r\nimport unittest\r\nfrom repository import *\r\nclass Pickle(Repository):\r\n def __init__(self,fileName):\r\n Repository.__init__(self)\r\n self.__fileName=fileName\r\n self.__load()\r\n def add(self,lol):\r\n Repository.add(self,lol)\r\n self.__store()\r\n def __load(self):\r\n file=open(self.__fileName,\"rb\")\r\n try:\r\n self._data=pickle.load(file)\r\n except EOFError:\r\n self.__data=[]\r\n except Exception as exc:\r\n raise exc\r\n finally:\r\n file.close()\r\n def __store(self):\r\n file=open(self.__fileName,\"wb\")\r\n pickle.dump(self.__data,file)\r\n file.close()\r\n\r\nclass Test(unittest.TestCase):\r\n def testLol(self):\r\n a=Repository()"
},
{
"alpha_fraction": 0.6496865153312683,
"alphanum_fraction": 0.6512539386749268,
"avg_line_length": 30.769229888916016,
"blob_id": "33dc8f94813b5895bb6d120c831113fcdb010a55",
"content_id": "504f2b442cfb86574d6db834ea899539e5ad7490",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1276,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 39,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"movie.h\"\r\n#include <vector>\r\n\r\nclass Repository {\r\nprivate:\r\n\tstd::vector<Movie> elems{};\r\n\tstd::string filename;\r\n\tint current;\r\npublic:\r\n\tRepository() :filename{ \"\" }, current{ 0 } {}\r\n\tRepository(std::string filename) :filename{ filename }, current{ 0 } { this->readFromFile(); }\r\n\t~Repository() {}\r\n\tstd::string toString();\r\n\tstd::string getFile() { return filename; }\r\n\tMovie operator[](int pos) { return elems[pos]; }\r\n\tstd::vector<Movie> getAll() { return elems; }\r\n\tint getLenght() { return this->elems.size(); }\r\n\tint getCurrent() { return current; }\r\n\tvoid add(Movie m);\r\n\tvoid del(int pos);\r\n\tvoid update(std::string oTitle, std::string nTitle, std::string genre, int year, int likes, std::string trailer);\r\n\tvoid clr() { elems.clear(); }\r\n\tstd::vector<Movie> filterRepo(std::string s);\r\n\tvoid setFilename() { filename = \"\"; }\r\n\r\n\tint findByTitle(std::string title);\r\n\tstd::string next();\r\n\tvoid incLikes(int pos) { elems[pos].incLikes(); }\r\n\tvoid setElems(std::vector<Movie> v) { elems = v; }\r\n\tvoid operator=(Repository r);\r\n\tvoid setCurrent(int i) { current = i; }\r\n\tvoid Add(Movie m) { elems.push_back(m); }\r\n\tvoid Del(int pos) { elems.erase(elems.begin() + pos); }\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n\tvoid displayCSV();\r\n};"
},
{
"alpha_fraction": 0.6362732648849487,
"alphanum_fraction": 0.642236053943634,
"avg_line_length": 24.393442153930664,
"blob_id": "8a2e3a55751794ee72bf0ca65ecca37a4dc532d9",
"content_id": "50dbbccaa50c040fb9777ca366de2b5c672a4265",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8050,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 305,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/User.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"User.h\"\r\n#include \"repoException.h\"\r\n#include \"QtWidgets\\qmessagebox.h\"\r\n#include <sstream>\r\n#include <QShortcut>\r\n\r\nUser::User(Controller c,QWidget *parent)\r\n\t:contro{ c }, lastDeleted{ -1 }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populateWatchList();\r\n\tOperation* u1 = new Undo(contro.getList());\r\n\tOperation* u2 = new Redo(contro.getList());\r\n\tund = u1;\r\n\tred = u2;\r\n}\r\n\r\nvoid User::filterMovies()\r\n{\r\n\tthis->filter.clr();\r\n\tstd::string f = this->ui.FilterByTitleLine->text().toStdString();\r\n\tthis->ui.FilterByTitleLine->clear();\r\n\tthis->filter.setElems(this->contro.filterByGenre(f));\r\n\tthis->populateFilter();\r\n\tthis->filter.setCurrent(-1);\r\n}\r\n\r\nvoid User::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.MovieList, SIGNAL(itemSelectionChanged()), this, SLOT(listItemChanged()));\r\n\r\n\tQObject::connect(this->ui.AddButton, SIGNAL(clicked()), this, SLOT(addMovie()));\r\n\r\n\tQObject::connect(this->ui.DeleteButton, SIGNAL(clicked()), this, SLOT(delMovie()));\r\n\r\n\tQObject::connect(this->ui.NextButton, SIGNAL(clicked()), this, SLOT(nextMovie()));\r\n\r\n\tQObject::connect(this->ui.FilterButton, SIGNAL(clicked()), this, SLOT(filterMovies()));\r\n\r\n\tQObject::connect(this->ui.ShowCSVButton, SIGNAL(clicked()), this, SLOT(showCSV()));\r\n\r\n\tQObject::connect(this->ui.ShowHTMLButton, SIGNAL(clicked()), this, SLOT(showHTML()));\r\n\r\n\tQObject::connect(this->ui.LikeButton, SIGNAL(clicked()), this, SLOT(likeMovie()));\r\n\r\n\tQObject::connect(this->ui.FilterByTitleLine, SIGNAL(returnPressed()), this, SLOT(filterMovies()));\r\n\r\n\tQObject::connect(this->ui.UndoButton, SIGNAL(clicked()), this, SLOT(undoFct()));\r\n\r\n\tQObject::connect(this->ui.RedoButton, SIGNAL(clicked()), this, SLOT(redoFct()));\r\n\r\n\tQShortcut *shortcut3 = new QShortcut(QKeySequence(\"Ctrl+Z\"), this);\r\n\tQShortcut *shortcut4 = new QShortcut(QKeySequence(\"Ctrl+Y\"), this);\r\n\r\n\tQObject::connect(shortcut3, SIGNAL(activated()), this, SLOT(undoFct()));\r\n\tQObject::connect(shortcut4, SIGNAL(activated()), this, SLOT(redoFct()));\r\n}\r\n\r\nvoid User::populateWatchList()\r\n{\r\n\tif (ui.MovieList->count() != 0)\r\n\t\tui.MovieList->clear();\r\n\tfor (auto m : contro.getList().getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.MovieList->addItem(listItemWidget);\r\n\t}\r\n\tif (contro.getList().getLenght() > 0)\r\n\t\tui.MovieList->setCurrentRow(0);\r\n\tthis->contro.saveFile();\r\n}\r\n\r\nvoid User::populateFilter()\r\n{\r\n\tif (ui.FilteredList->count() != 0)\r\n\t\tui.FilteredList->clear();\r\n\tfor (auto m : filter.getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.FilteredList->addItem(listItemWidget);\r\n\t}\r\n\tif (filter.getLenght() > 0)\r\n\t\tui.FilteredList->setCurrentRow(0);\r\n\tthis->contro.getAll().writeToFile();\r\n}\r\n\r\nUser::~User()\r\n{\r\n\tdelete und;\r\n\tdelete red;\r\n}\r\n\r\nvoid User::readFromFile()\r\n{\r\n\tthis->contro.readFromList();\r\n\tthis->populateWatchList();\r\n}\r\n\r\nint User::getSelectedIndex()\r\n{\r\n\tif (ui.MovieList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.MovieList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid User::addMovie()\r\n{\r\n\ttry {\r\n\t\tif (this->filter.getLenght() == 0)\r\n\t\t{\r\n\t\t\tQMessageBox messageBox;\r\n\t\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"You have to filter by genre first!\"));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif(this->filter.getCurrent()==-1)\r\n\t\t{\r\n\t\t\tQMessageBox messageBox;\r\n\t\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"You have to watch the trailer first!\"));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (this->filter.getCurrent() == 0)\r\n\t\t{\r\n\t\t\tthis->contro.addList(this->filter[this->filter.getCurrent()]);\r\n\t\t\tund->setE(contro.getList().getAll());\r\n\t\t\tred->setE(contro.getList().getAll());\r\n\t\t\tOperationElement ope{ this->filter[this->filter.getCurrent()] ,this->filter[this->filter.getCurrent()] ,\"delete\" };\r\n\t\t\tthis->und->push(ope);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthis->contro.addList(this->filter[this->filter.getCurrent() - 1]);\r\n\t\t\tund->setE(contro.getList().getAll());\r\n\t\t\tred->setE(contro.getList().getAll());\r\n\t\t\tOperationElement ope{ this->filter[this->filter.getCurrent()-1] ,this->filter[this->filter.getCurrent() - 1] ,\"delete\" };\r\n\t\t\tthis->und->push(ope);\r\n\t\t}\r\n\t}\r\n\tcatch (FoundException e)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n\tthis->populateWatchList();\r\n}\r\n\r\nvoid User::delMovie()\r\n{\r\n\ttry {\r\n\t\tint i = this->getSelectedIndex();\r\n\t\tif (this->contro.getList().getLenght() == 0)\r\n\t\t{\r\n\t\t\tQMessageBox messageBox;\r\n\t\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"The list is empty!\"));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (i == -1 )\r\n\t\t\ti = 0;\r\n\t\tstd::string t = this->contro.getList()[i].getTitle();\r\n\t\tMovie m = this->contro.getList()[i];\r\n\t\tthis->lastDeleted = this->contro.findByTitle(t);\r\n\t\tthis->contro.delList(t);\r\n\t\tund->setE(contro.getList().getAll());\r\n\t\tred->setE(contro.getList().getAll());\r\n\t\tOperationElement ope{ m,m,\"add\" };\r\n\t\tund->push(ope);\r\n\t}\r\n\tcatch (NoMovieFoundException e)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n\tthis->populateWatchList();\r\n}\r\n\r\nvoid User::likeMovie()\r\n{\r\n\tif (this->lastDeleted == -1)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"You have to delete a movie first!\"));\r\n\t\treturn;\r\n\t}\r\n\tthis->contro.incLikes(this->lastDeleted);\r\n\tthis->contro.getAll().writeToFile();\r\n\tthis->lastDeleted = -1;\r\n}\r\n\r\nvoid User::showCSV()\r\n{\r\n\tthis->contro.displayCSV();\r\n}\r\n\r\nvoid User::showHTML()\r\n{\r\n\tthis->contro.saveFile();\r\n\tthis->contro.displayHTML();\r\n}\r\n\r\nvoid User::nextMovie()\r\n{\r\n\tif (this->filter.getLenght() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"You have to filter something first!\"));\r\n\t\treturn;\r\n\t}\r\n\tthis->filter.next();\r\n}\r\n\r\nvoid User::undoFct()\r\n{\r\n\tif (this->und->len() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Nothing to undo!\"));\r\n\t\treturn;\r\n\t}\r\n\tOperationElement e = this->und->get();\r\n\tif (e.getOperation() == \"add\")\r\n\t{\r\n\t\te.setOperation(\"delete\");\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\tcontro.setElems(und->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"delete\")\r\n\t{\r\n\t\te.setOperation(\"add\");\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\tcontro.setElems(und->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"update\")\r\n\t{\r\n\t\tMovie m = e.getMovie();\r\n\t\tMovie m1 = e.getMovieUpdate();\r\n\t\te.setMovie(m1);\r\n\t\te.setMovieUpdate(m);\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\tcontro.setElems(und->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\nvoid User::redoFct()\r\n{\r\n\tif (this->red->len() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Nothing to redo!\"));\r\n\t\treturn;\r\n\t}\r\n\tOperationElement e = this->red->get();\r\n\tif (e.getOperation() == \"add\")\r\n\t{\r\n\t\te.setOperation(\"delete\");\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\tcontro.setElems(red->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"delete\")\r\n\t{\r\n\t\te.setOperation(\"add\");\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\tcontro.setElems(red->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"update\")\r\n\t{\r\n\t\tMovie m = e.getMovie();\r\n\t\tMovie m1 = e.getMovieUpdate();\r\n\t\te.setMovie(m1);\r\n\t\te.setMovieUpdate(m);\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\tcontro.setElems(red->getRepo().getAll());\r\n\t\tthis->populateWatchList();\r\n\t\treturn;\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.7666666507720947,
"alphanum_fraction": 0.7666666507720947,
"avg_line_length": 28.5,
"blob_id": "a03ae5b7e168ea15b378a4b30cc2fa0eaa5d71b9",
"content_id": "259914023053476c80c48f9fc6ef2c2be462ecdb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 60,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 2,
"path": "/MyProjects/Graphs/README.txt",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "\tThis is a folder with graph problems and projects!\r\n\tEnjoy!"
},
{
"alpha_fraction": 0.6872727274894714,
"alphanum_fraction": 0.6872727274894714,
"avg_line_length": 23.090909957885742,
"blob_id": "83cc5c40bb1a1fc17d9eb7bffcab2e2abd39a624",
"content_id": "967a7eaa6d5a5f64c9be9457c22fa42be5bfd44a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 550,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 22,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"student.h\"\r\n#include \"teacher.h\"\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tRepository<Student>* students;\r\n\tRepository<Teacher>* teachers;\r\npublic:\r\n\tController(Repository<Student>* s, Repository<Teacher>* t) :students{ s }, teachers{ t } {}\r\n\tController() :students{}, teachers{} {}\r\n\t~Controller() {}\r\n\r\n\tRepository<Student>* getStudents() { return students; }\r\n\tRepository<Teacher>* getTeachers() { return teachers; }\r\n\r\n\tvoid addStudent(Student s);\r\n\tint findByID(int id);\r\n\tvoid delStudent(int pos);\r\n};"
},
{
"alpha_fraction": 0.7954545617103577,
"alphanum_fraction": 0.7954545617103577,
"avg_line_length": 43,
"blob_id": "30336d85b801cc995eedf6a450a0d1883ecfdc18",
"content_id": "32a511896da4ad5e7dcfc0f8f80c52cdc2038500",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 132,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 3,
"path": "/README.md",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "# MyProjects\nThis repository contains some projects that I made in faculty.\nThe folders are organised on faculty objects, enjoy! :)\n"
},
{
"alpha_fraction": 0.6857143044471741,
"alphanum_fraction": 0.6857143044471741,
"avg_line_length": 20.5,
"blob_id": "6beddf4ce6547396c2ef7450256d0d2b98f0f41b",
"content_id": "5941dd68ba52fbd282c88e065ef9437123ac250c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 14,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Repository/IRepo.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model;\r\n\r\nnamespace Interpreter.Repository\r\n{\r\n public interface IRepo\r\n {\r\n void addPrg(ProgramState prg);\r\n ProgramState getCurrentPrg();\r\n void logProgramStateExec(string logFilePath);\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6569506525993347,
"alphanum_fraction": 0.6569506525993347,
"avg_line_length": 24,
"blob_id": "37912da2381a924a13c235f68832fe9c89ee174b",
"content_id": "53122fb6de620b5a5575b95db594e52b72a085f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 17,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/view.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"view.h\"\r\n#include <QSortFilterProxyModel>\r\n\r\nView::View(Repository & r, Repository &l, QWidget * parent) :repo{ r }, list{ l }, QMainWindow{ parent }\r\n{\r\n\tui.setupUi(this);\r\n\tthis->wTable = new MovieTable(this->list );\r\n\tthis->mTable = new MovieTable(this->repo );\r\n\tthis->ui.MovieTable->setModel(this->mTable);\r\n\tthis->ui.WatchTable->setModel(this->wTable);\r\n}\r\n\r\nView::~View()\r\n{\r\n\tdelete this->wTable;\r\n\tdelete this->mTable;\r\n}\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5997357964515686,
"alphanum_fraction": 0.6235138773918152,
"avg_line_length": 24.10344886779785,
"blob_id": "5054b25608cbfe3e2574395dd5d0404eecc09b5c",
"content_id": "ae903dd0d1fff1f19cc7a79ac6166fc2b559c130",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 757,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 29,
"path": "/MyProjects/MAP/Practical Exam/ConditionalStmt/src/Model/Statements/CondAssignStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IStack;\r\n\r\npublic class CondAssignStmt implements IStmt {\r\n private String v;\r\n private IExpr exp1,exp2,exp3;\r\n\r\n public CondAssignStmt(String v,IExpr e1,IExpr e2,IExpr e3){\r\n this.v=v;\r\n this.exp1=e1;\r\n this.exp2=e2;\r\n this.exp3=e3;\r\n }\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IStack<IStmt> stack=state.getStack();\r\n IStmt s=new IfStmt(this.exp1,new AssignStmt(this.v,this.exp2),new AssignStmt(this.v,this.exp3));\r\n stack.add(s);\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return v+\"=\"+exp1+\"?\"+exp2+\":\"+exp3;\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5533230304718018,
"alphanum_fraction": 0.557959794998169,
"avg_line_length": 15.026315689086914,
"blob_id": "a4ef0d21242f5f0573457576aa7e143e6d8cf94c",
"content_id": "d2237380da9ffd9485a98c9d1fd66b48cca37cb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 647,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 38,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\nstd::vector<std::string> Controller::getTeachersNames()\r\n{\r\n\tstd::vector<std::string> vec;\r\n\tfor (auto i : teachers.getAll())\r\n\t\tvec.push_back(i.getName());\r\n\treturn vec;\r\n}\r\n\r\nstd::vector<int> Controller::getTeacherGroups(std::string name)\r\n{\r\n\tfor (auto i : teachers.getAll())\r\n\t{\r\n\t\tif (i.getName() == name)\r\n\t\t\treturn i.getGroups();\r\n\t}\r\n}\r\n\r\nint Controller::getValidID()\r\n{\r\n\tbool ok = false;\r\n\tint myID = 0;\r\n\twhile (ok == false)\r\n\t{\r\n\t\tok = true;\r\n\t\tint k = 0;\r\n\t\tfor (auto i : students.getAll())\r\n\t\t\tif (i.getID() == myID)\r\n\t\t\t{\r\n\t\t\t\tmyID++;\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\tif (k != 0)\r\n\t\t\tok = false;\r\n\t}\r\n\treturn myID;\r\n}\r\n"
},
{
"alpha_fraction": 0.6381322741508484,
"alphanum_fraction": 0.6381322741508484,
"avg_line_length": 13.235294342041016,
"blob_id": "6529f6a60bf6b2b97aceb21ed12b8bc7b1ef5807",
"content_id": "ef3f3afa614b8ca1f6c48566a7d3b3bea6c11d9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 17,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/domain.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <iostream>\r\n\r\nclass Concert\r\n{\r\nprivate:\r\n\tstd::string band;\r\n\tint likes;\r\npublic:\r\n\tConcert();\r\n\r\n\tConcert(const std::string band,const int likes);\r\n\r\n\tstd::string getBand() { return band; };\r\n\r\n\tint getLikes() { return likes; };\r\n};"
},
{
"alpha_fraction": 0.6713948249816895,
"alphanum_fraction": 0.6713948249816895,
"avg_line_length": 14.920000076293945,
"blob_id": "ef82ca939b002af45bd6253265410df5433712ef",
"content_id": "7cabe1c4924ff91a24ab0698efbe5612c7ab579e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 25,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/Time.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_Time.h\"\r\n#include \"repository.h\"\r\n#include \"domain.h\"\r\n\r\nclass Time : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tTime(Repository<Task> &r,QWidget *parent = Q_NULLPTR);\r\n\r\nprivate:\r\n\tUi::TimeClass ui;\r\n\tRepository<Task> &repo;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid populate();\r\n\tvoid sort();\r\n\tvoid blodIt();\r\n\tprivate slots:\r\n\tvoid showDuration();\r\n};\r\n"
},
{
"alpha_fraction": 0.49790793657302856,
"alphanum_fraction": 0.5271966457366943,
"avg_line_length": 25.837209701538086,
"blob_id": "2a720227e4d2e64eac00bbb4bc969a2b4707a62b",
"content_id": "6579f90efbc3d9721d0c287880aec377aa0426ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1195,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 43,
"path": "/MyProjects/FP/FP/Shapes - Exam/tests.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import unittest\r\nfrom repository import *\r\nfrom controller import *\r\nclass ControllerTest(unittest.TestCase):\r\n def testBlinker(self):\r\n a=Repository()\r\n b=Controller(a)\r\n b.blinkerV(0,0)\r\n self.assertEqual(b.get(1,0),1)\r\n def testBlock(self):\r\n a = Repository()\r\n b = Controller(a)\r\n b.block(0,0)\r\n self.assertEqual(b.get(0,0),1)\r\n def testTub(self):\r\n a = Repository()\r\n b = Controller(a)\r\n b.tub(0,0)\r\n self.assertEqual(b.get(0,1),1)\r\n def testBeacon(self):\r\n a = Repository()\r\n b = Controller(a)\r\n b.beacon1(0,0)\r\n self.assertEqual(b.get(0,0),1)\r\n def testTick(self):\r\n a = Repository()\r\n b = Controller(a)\r\n b.block(0,0)\r\n b.tick(1)\r\n self.assertEqual(b.get(7,7),0)\r\nclass RepoTest(unittest.TestCase):\r\n def testGet(self):\r\n a = Repository()\r\n a.add(1)\r\n self.assertEqual(a.get(0),1)\r\n def testAdd(self):\r\n a = Repository()\r\n a.add(1)\r\n self.assertEqual(a.get(0), 1)\r\n def testGetAll(self):\r\n a = Repository()\r\n a.add(1)\r\n self.assertEqual(a.getAll(), [1])"
},
{
"alpha_fraction": 0.6036475896835327,
"alphanum_fraction": 0.6266375780105591,
"avg_line_length": 56.98484802246094,
"blob_id": "9464ff54e9b68dfd2686d0d21ac1589d8be9c19e",
"content_id": "ff3091b450f1ed688cfb247d76185c29c7d11a29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7786,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 132,
"path": "/MyProjects/MAP/Assignment 2/src/View/View.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package View;\r\n\r\nimport Controller.Controller;\r\nimport Model.Utilities.*;\r\nimport Model.Statements.*;\r\nimport Model.Expressions.*;\r\nimport Model.ProgramState;\r\nimport Repository.*;\r\nimport View.Command.ExitCommand;\r\nimport View.Command.RunExample;\r\n\r\nimport java.io.BufferedReader;\r\n\r\npublic class View {\r\n public static void main(String[] args) {\r\n IStack<IStmt> ExeStack1 = new Stack<>();\r\n IDictionary<String, Integer> SymTable1 = new Dictionary<String, Integer>();\r\n IList<Integer> out1 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable1=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap1=new Dictionary<Integer, Integer>();\r\n IStmt expr1 = new CompStmt(new AssignStmt(\"v\", new ConstExpr(2)),\r\n new PrintStmt(new VarExpr(\"c\")));\r\n ExeStack1.add(expr1);\r\n ProgramState prgCurrent1 = new ProgramState(ExeStack1, SymTable1, out1,fileTable1,heap1);\r\n IRepo repo1 = new Repository();\r\n repo1.addPrg(prgCurrent1);\r\n Controller ctrl1 = new Controller(repo1);\r\n\r\n IStack<IStmt> ExeStack2 = new Stack<>();\r\n IDictionary<String, Integer> SymTable2 = new Dictionary<String, Integer>();\r\n IList<Integer> out2 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable2=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap2=new Dictionary<Integer, Integer>();\r\n IStmt expr2 = new CompStmt(new AssignStmt(\"a\", new ArithmExpr(\"+\", new ConstExpr(2),\r\n new ArithmExpr(\"*\", new ConstExpr(3), new ConstExpr(5)))), new CompStmt(new AssignStmt(\"b\",\r\n new ArithmExpr(\"+\", new VarExpr(\"a\"), new ConstExpr(1))), new PrintStmt(new VarExpr(\"b\"))));\r\n ExeStack2.add(expr2);\r\n ProgramState prgCurrent2 = new ProgramState(ExeStack2, SymTable2, out2,fileTable2,heap2);\r\n IRepo repo2 = new Repository();\r\n repo2.addPrg(prgCurrent2);\r\n Controller ctrl2 = new Controller(repo2);\r\n\r\n IStack<IStmt> ExeStack3 = new Stack<>();\r\n IDictionary<String, Integer> SymTable3 = new Dictionary<String, Integer>();\r\n IList<Integer> out3 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable3=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap3=new Dictionary<Integer, Integer>();\r\n IStmt expr3 = new CompStmt(new AssignStmt(\"a\", new ArithmExpr(\"-\", new ConstExpr(2), new ConstExpr(2))),\r\n new CompStmt(new IfStmt(new VarExpr(\"a\"), new AssignStmt(\"v\", new ConstExpr(2)), new AssignStmt(\"v\",\r\n new ConstExpr(3))), new PrintStmt(new VarExpr(\"v\"))));\r\n ExeStack3.add(expr3);\r\n ProgramState prgCurrent3 = new ProgramState(ExeStack3, SymTable3, out3,fileTable3,heap3);\r\n IRepo repo3 = new Repository();\r\n repo3.addPrg(prgCurrent3);\r\n Controller ctrl3 = new Controller(repo3);\r\n\r\n IStack<IStmt> ExeStack4 = new Stack<>();\r\n IDictionary<String, Integer> SymTable4 = new Dictionary<String, Integer>();\r\n IList<Integer> out4 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable4=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap4=new Dictionary<Integer, Integer>();\r\n IStmt expr4=new CompStmt(\r\n new OpenRFileStmt(\"var_f\",\"C:\\\\Users\\\\pechd\\\\IdeaProjects\\\\lab2\\\\Example.txt\"),new CompStmt(\r\n new ReadFileStmt(new VarExpr(\"var_f\"),\"var_c\"),new CompStmt(\r\n new PrintStmt(new VarExpr(\"var_c\")),new CompStmt(\r\n new IfStmt(new VarExpr(\"var_c\")\r\n ,new CompStmt(new ReadFileStmt(new VarExpr(\"var_f\"),\"var_c\"),new PrintStmt(new VarExpr(\"var_c\"))),new PrintStmt(new ConstExpr(0))),\r\n new CloseRFileStmt(new VarExpr(\"var_f\"))))));\r\n ExeStack4.add(expr4);\r\n ProgramState prgCurrent4=new ProgramState(ExeStack4,SymTable4,out4,fileTable4,heap4);\r\n IRepo repo4=new Repository();\r\n repo4.addPrg(prgCurrent4);\r\n Controller ctrl4=new Controller(repo4);\r\n\r\n IStack<IStmt> ExeStack5 = new Stack<>();\r\n IDictionary<String, Integer> SymTable5 = new Dictionary<String, Integer>();\r\n IList<Integer> out5 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable5=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap5=new Dictionary<Integer, Integer>();\r\n IStmt expr5 = new CompStmt(\r\n new AssignStmt(\"v\",new ConstExpr(10)), new CompStmt(\r\n new New(\"v\",new ConstExpr(20)),new CompStmt(\r\n new New(\"a\",new ConstExpr(22)),new CompStmt(\r\n new WH(\"a\",new ConstExpr(30)),new CompStmt(\r\n new PrintStmt(new VarExpr(\"a\")),new CompStmt(\r\n new PrintStmt(new RH(\"a\")),new AssignStmt(\"a\",new ConstExpr(0))\r\n ))))));\r\n ExeStack5.add(expr5);\r\n ProgramState prgCurrent5=new ProgramState(ExeStack5,SymTable5,out5,fileTable5,heap5);\r\n IRepo repo5=new Repository();\r\n repo5.addPrg(prgCurrent5);\r\n Controller ctrl5=new Controller(repo5);\r\n\r\n IStack<IStmt> ExeStack6 = new Stack<>();\r\n IDictionary<String, Integer> SymTable6 = new Dictionary<String, Integer>();\r\n IList<Integer> out6 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable6=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap6=new Dictionary<Integer, Integer>();\r\n IStmt expr6 = new CompStmt(new AssignStmt(\"v\",new ConstExpr(7)),\r\n new CompStmt(new WhileStmt(new ArithmExpr(\"-\",new VarExpr(\"v\"),new ConstExpr(4)),new CompStmt(\r\n new PrintStmt(new VarExpr(\"v\")),new AssignStmt(\"v\",new ArithmExpr(\"-\",new VarExpr(\"v\"),new ConstExpr(1)))\r\n )),new PrintStmt(new VarExpr(\"v\"))));\r\n ExeStack6.add(expr6);\r\n ProgramState prgCurrent6 = new ProgramState(ExeStack6, SymTable6, out6,fileTable6,heap6);\r\n IRepo repo6 = new Repository();\r\n repo6.addPrg(prgCurrent6);\r\n Controller ctrl6 = new Controller(repo6);\r\n\r\n IStack<IStmt> ExeStack7 = new Stack<>();\r\n IDictionary<String, Integer> SymTable7 = new Dictionary<String, Integer>();\r\n IList<Integer> out7 = new MyList<Integer>();\r\n IDictionary<Integer, BufferedReader> fileTable7=new Dictionary<Integer, BufferedReader>();\r\n IDictionary<Integer, Integer> heap7=new Dictionary<Integer, Integer>();\r\n IStmt expr7 = new OpenRFileStmt(\"var_f\",\"C:\\\\Users\\\\pechd\\\\IdeaProjects\\\\lab2\\\\Example.txt\");\r\n ExeStack7.add(expr7);\r\n ProgramState prgCurrent7 = new ProgramState(ExeStack7, SymTable7, out7,fileTable7,heap7);\r\n IRepo repo7 = new Repository();\r\n repo7.addPrg(prgCurrent7);\r\n Controller ctrl7 = new Controller(repo7);\r\n\r\n TextMenu menu = new TextMenu();\r\n menu.addCommand(new ExitCommand(\"0\", \"exit\"));\r\n menu.addCommand(new RunExample(\"1\",expr1.toString(),ctrl1));\r\n menu.addCommand(new RunExample(\"2\",expr2.toString(),ctrl2));\r\n menu.addCommand(new RunExample(\"3\",expr3.toString(),ctrl3));\r\n menu.addCommand(new RunExample(\"4\",expr4.toString(),ctrl4));\r\n menu.addCommand(new RunExample(\"5\",expr5.toString(),ctrl5));\r\n menu.addCommand(new RunExample(\"6\",expr6.toString(),ctrl6));\r\n menu.addCommand(new RunExample(\"7\",expr7.toString(),ctrl7));\r\n menu.show();\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6324582099914551,
"alphanum_fraction": 0.6324582099914551,
"avg_line_length": 19.049999237060547,
"blob_id": "817a707eb30910547c1c433e303a2f38e90b3ddc",
"content_id": "7c5fe7ca2404df4fdeb32ff1f229448fc9da048b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 419,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/astronomer.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <string>\r\n\r\nclass Astronomer\r\n{\r\nprivate:\r\n\tstd::string name;\r\n\tstd::string constellation;\r\npublic:\r\n\tAstronomer() :name{ \"\" }, constellation{ \"\" } {}\r\n\tAstronomer(std::string n, std::string c) :name{ n }, constellation{ c } {}\r\n\t~Astronomer() {}\r\n\r\n\tstd::string getName() { return name; }\r\n\tstd::string getConste(){ return constellation; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.3104308545589447,
"alphanum_fraction": 0.3358602821826935,
"avg_line_length": 34.44405746459961,
"blob_id": "8774ec930de13d76b7e11bcd0673006a6b7c7781",
"content_id": "c9b7da9e3280040c4c4931a0671c458f52ce4151",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10421,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 286,
"path": "/MyProjects/FP/FP/Shapes - Exam/controller.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nimport random\r\nclass Controller:\r\n def __init__(self,repo=Repository()):\r\n self.__repo=repo\r\n grid=[]\r\n for i in range(9):\r\n use=[]\r\n for j in range(9):\r\n use.append(0)\r\n grid.append(use)\r\n self.__grid=grid[:]\r\n self.__time=1\r\n self.__glider=[]\r\n self.__blinker=[]\r\n self.__beacon=[]\r\n def __str__(self):\r\n '''\r\n Overwrites the str function for this class\r\n :return:\r\n '''\r\n s=''\r\n for i in range(8):\r\n s+='|'\r\n for j in range(8):\r\n if self.__grid[i][j]==0:\r\n s+=' |'\r\n else:\r\n s+=' x |'\r\n s+='\\n'\r\n return s\r\n def blinkerH(self,i,j):\r\n '''\r\n Generates the blinker in horizontal position\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n self.__blinker.append([i,j])\r\n if self.__time%2==1:\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+3):\r\n for l in range(j,j+3):\r\n if k==i+1:\r\n if self.__grid[k][l]!=0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def blinkerV(self,i,j):\r\n '''\r\n Generates the blinker in vertical position\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n self.__blinker.append([i,j])\r\n if self.__time%2==0:\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+3):\r\n for l in range(j,j+3):\r\n if l==j+1:\r\n if self.__grid[k][l]!=0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def block(self,i,j):\r\n '''\r\n Generates the block\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+2):\r\n for l in range(j,j+2):\r\n if self.__grid[k][l]!=0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def tub(self,i,j):\r\n '''\r\n Generates the tub\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+3):\r\n for l in range(j,j+3):\r\n if k==i and l==j+1:\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n elif k==i+1 and (l==j or l==j+2):\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n elif k==i+2 and l==j+1:\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def beacon1(self,i,j):\r\n '''\r\n Generates the first beacon\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n self.__beacon.append([i,j])\r\n if self.__time % 2 == 1:\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+4):\r\n for l in range(j,j+4):\r\n if (k==i and l==j) or (k==i and l==j+1) or (k==i+1 and l==j) or (k==i+1 and l==j+1) or (k==i+2 and l==j+2) or\\\r\n (k==i+2 and l==j+3) or (k==i+3 and l==j+2) or (k==i+3 and l==+3):\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def beacon2(self,i,j):\r\n '''\r\n Generates the second beacon\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n self.__beacon.append([i,j])\r\n if self.__time % 2 == 0:\r\n if i<0 or j<0 or i>7 or j>7:\r\n raise ValueError\r\n for k in range(i,i+4):\r\n for l in range(j,j+4):\r\n if (k==i and l==j) or (k==i and l==j+1) or (k==i+1 and l==j) or\\\r\n (k==i+2 and l==j+3) or (k==i+3 and l==j+2) or (k==i+3 and l==+3):\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l]=1\r\n def beacon(self):\r\n '''\r\n Updates the beacon\r\n :return:\r\n '''\r\n for p in range(len(self.__beacon)):\r\n i=self.__beacon[p][0]\r\n j=self.__beacon[p][1]\r\n if self.__time % 2 == 1:\r\n if i < 0 or j < 0 or i > 7 or j > 7:\r\n raise ValueError\r\n for k in range(i, i + 4):\r\n for l in range(j, j + 4):\r\n if (k == i and l == j) or (k == i and l == j + 1) or (k == i + 1 and l == j) or (\r\n k == i + 1 and l == j + 1) or (k == i + 2 and l == j + 2) or \\\r\n (k == i + 2 and l == j + 3) or (k == i + 3 and l == j + 2) or (k == i + 3 and l == +3):\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l] = 1\r\n else:\r\n if i < 0 or j < 0 or i > 7 or j > 7:\r\n raise ValueError\r\n for k in range(i, i + 4):\r\n for l in range(j, j + 4):\r\n if (k == i and l == j) or (k == i and l == j + 1) or (k == i + 1 and l == j) or \\\r\n (k == i + 2 and l == j + 3) or (k == i + 3 and l == j + 2) or (k == i + 3 and l == +3):\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l] = 1\r\n def blinker(self):\r\n '''\r\n Updates the blinker\r\n :return:\r\n '''\r\n for p in range(len(self.__blinker)):\r\n i=self.__blinker[p][0]\r\n j=self.__blinker[p][1]\r\n if self.__time % 2 == 1:\r\n if i < 0 or j < 0 or i > 7 or j > 7:\r\n raise ValueError\r\n for k in range(i, i + 3):\r\n for l in range(j, j + 3):\r\n if k == i + 1:\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l] = 1\r\n else:\r\n if i < 0 or j < 0 or i > 7 or j > 7:\r\n raise ValueError\r\n for k in range(i, i + 3):\r\n for l in range(j, j + 3):\r\n if l == j + 1:\r\n if self.__grid[k][l] != 0:\r\n raise ValueError\r\n else:\r\n self.__grid[k][l] = 1\r\n def addGlider(self,i,j):\r\n '''\r\n Adds the position of the glider to the list of gliders\r\n :param i:\r\n :param j:\r\n :return:\r\n '''\r\n self.__glider.append([i,j])\r\n def changeGlider(self):\r\n '''\r\n Randomises the gliders of the list\r\n :return:\r\n '''\r\n if self.__time%4==0:\r\n for k in range(len(self.__glider)):\r\n i=self.__glider[k][0]\r\n j=self.__glider[k][1]\r\n for m in range(4):\r\n for n in range(4):\r\n self.__grid[m][n]=0\r\n for m in range(5):\r\n repeat=True\r\n n=None\r\n o=None\r\n while repeat==True:\r\n repeat=False\r\n n=random.randint(i,i+3)\r\n o=random.randint(j,j+3)\r\n if self.__grid[n][o]==1:\r\n repeat=True\r\n self.__grid[n][o]=1\r\n def store(self):\r\n '''\r\n Stores into the file\r\n :return:\r\n '''\r\n self.__repo=self.__grid\r\n def load(self):\r\n \"\"\"\r\n Loads from the file\r\n :return:\r\n \"\"\"\r\n self.__grid=self.__repo\r\n def tick(self,value):\r\n '''\r\n Simulates a generation\r\n :return:\r\n '''\r\n self.__time+=value\r\n for p in range(value+1):\r\n self.changeGlider()\r\n self.blinker()\r\n self.beacon()\r\n for i in range(8):\r\n count = 0\r\n for j in range(8):\r\n if self.__grid[i-1][j-1]==1 and i-1>=0 and i-1<8 and j-1>=0 and j-1<8:\r\n count+=1\r\n if self.__grid[i-1][j+1]==1 and i-1>=0 and i-1<8 and j+1>=0 and j+1<8:\r\n count+=1\r\n if self.__grid[i-1][j]==1 and i-1>=0 and i-1<8 and j>=0 and j<8:\r\n count+=1\r\n if self.__grid[i+1][j+1]==1 and i+1>=0 and i+1<8 and j+1>=0 and j+1<8:\r\n count+=1\r\n if self.__grid[i+1][j-1]==1 and i+1>=0 and i+1<8 and j-1>=0 and j-1<8:\r\n count+=1\r\n if self.__grid[i+1][j]==1 and i+1>=0 and i+1<8 and j>=0 and j<8:\r\n count+=1\r\n if self.__grid[i][j+1]==1 and i>=0 and i<8 and j+1>=0 and j+1<8:\r\n count+=1\r\n if self.__grid[i][j-1]==1 and i>=0 and i<8 and j-1>=0 and j-1<8:\r\n count+=1\r\n\r\n if count<2:\r\n self.__grid[i][j]=0\r\n elif count>3:\r\n self.__grid[i][j]=0\r\n elif count==3 and self.__grid[i][j]==0:\r\n self.__grid[i][j]=1\r\n def get(self,i,j):\r\n return self.__grid[i][j]"
},
{
"alpha_fraction": 0.6434426307678223,
"alphanum_fraction": 0.6434426307678223,
"avg_line_length": 15.571428298950195,
"blob_id": "e1a06971c726d4d9ad445d134dfb212131803450",
"content_id": "0fac4cfafb9be6292804a2b46d0e332c72278b17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 244,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 14,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/UI.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"controller.h\"\r\n\r\ntemplate <typename T>\r\nclass UI {\r\nprivate:\r\n\tController<T> contro;\r\npublic:\r\n\tUI<T>(Controller<T> c) :contro{ c } {}\r\n\tvoid printMenu();\r\n\tvoid printStudent(T s);\r\n\tvoid printRepo();\r\n\tvoid start();\r\n};"
},
{
"alpha_fraction": 0.6992481350898743,
"alphanum_fraction": 0.7218044996261597,
"avg_line_length": 17,
"blob_id": "5defc3dc10e2c432b4a5cebf34fd0ee3db955a61",
"content_id": "21a6424ad3ef6e3699ec4f8dd21135b5ebc60c0c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 133,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/OOPpracticalex1.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPpracticalex1.h\"\r\n\r\nOOPpracticalex1::OOPpracticalex1(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.6647468209266663,
"alphanum_fraction": 0.6729061603546143,
"avg_line_length": 33.313560485839844,
"blob_id": "7b04766ac641adfa80b3c792ca6688f48a18ab23",
"content_id": "72bffba372f54324909e329a8300e64473a9171f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4167,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 118,
"path": "/MyProjects/OOP/OOP/Practice - VegetablesProb/VegetablesProb/GeneratedFiles/ui_VegetablesProb.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'VegetablesProb.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_VEGETABLESPROB_H\r\n#define UI_VEGETABLESPROB_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_VegetablesProbClass\r\n{\r\npublic:\r\n QWidget *centralWidget;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *label;\r\n QListWidget *FamilyList;\r\n QHBoxLayout *horizontalLayout;\r\n QLineEdit *lineEdit;\r\n QPushButton *pushButton;\r\n QLabel *label_2;\r\n QListWidget *VegetableList;\r\n\r\n void setupUi(QMainWindow *VegetablesProbClass)\r\n {\r\n if (VegetablesProbClass->objectName().isEmpty())\r\n VegetablesProbClass->setObjectName(QStringLiteral(\"VegetablesProbClass\"));\r\n VegetablesProbClass->resize(600, 400);\r\n centralWidget = new QWidget(VegetablesProbClass);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n horizontalLayout_2 = new QHBoxLayout(centralWidget);\r\n horizontalLayout_2->setSpacing(6);\r\n horizontalLayout_2->setContentsMargins(11, 11, 11, 11);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setSpacing(6);\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n label = new QLabel(centralWidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout->addWidget(label);\r\n\r\n FamilyList = new QListWidget(centralWidget);\r\n FamilyList->setObjectName(QStringLiteral(\"FamilyList\"));\r\n\r\n verticalLayout->addWidget(FamilyList);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setSpacing(6);\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n lineEdit = new QLineEdit(centralWidget);\r\n lineEdit->setObjectName(QStringLiteral(\"lineEdit\"));\r\n\r\n horizontalLayout->addWidget(lineEdit);\r\n\r\n pushButton = new QPushButton(centralWidget);\r\n pushButton->setObjectName(QStringLiteral(\"pushButton\"));\r\n\r\n horizontalLayout->addWidget(pushButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n label_2 = new QLabel(centralWidget);\r\n label_2->setObjectName(QStringLiteral(\"label_2\"));\r\n\r\n verticalLayout->addWidget(label_2);\r\n\r\n VegetableList = new QListWidget(centralWidget);\r\n VegetableList->setObjectName(QStringLiteral(\"VegetableList\"));\r\n\r\n verticalLayout->addWidget(VegetableList);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout);\r\n\r\n VegetablesProbClass->setCentralWidget(centralWidget);\r\n\r\n retranslateUi(VegetablesProbClass);\r\n\r\n QMetaObject::connectSlotsByName(VegetablesProbClass);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *VegetablesProbClass)\r\n {\r\n VegetablesProbClass->setWindowTitle(QApplication::translate(\"VegetablesProbClass\", \"VegetablesProb\", nullptr));\r\n label->setText(QApplication::translate(\"VegetablesProbClass\", \"Family list:\", nullptr));\r\n pushButton->setText(QApplication::translate(\"VegetablesProbClass\", \"Search\", nullptr));\r\n label_2->setText(QApplication::translate(\"VegetablesProbClass\", \"Vegetable list:\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class VegetablesProbClass: public Ui_VegetablesProbClass {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_VEGETABLESPROB_H\r\n"
},
{
"alpha_fraction": 0.5694915056228638,
"alphanum_fraction": 0.5774011015892029,
"avg_line_length": 15.352941513061523,
"blob_id": "23fc44bc43674b349feca0bd6dcfd3594555cbd3",
"content_id": "7facaa43ec1184cad68b787658748bd57e147611",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 885,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 51,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Controller.h\"\r\n#include <iostream>\r\n\r\nint Controller::findByName(std::string name)\r\n{\r\n\tfor (int i = 0;i < this->repo.getLenght();i++)\r\n\t\tif (this->repo[i].getName() == name)\r\n\t\t\treturn i;\r\n\treturn -1;\r\n}\r\n\r\nint Controller::findbyID(const int id)\r\n{\r\n\tfor (int i = 0;i < this->repo.getLenght();i++)\r\n\t{\r\n\t\tif (this->repo[i].getID() == id)\r\n\t\t{\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nbool Controller::add(Pilot p)\r\n{\r\n\tif (this->findbyID(p.getID()) == -1)\r\n\t{\r\n\t\tthis->repo.add(p);\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool Controller::del(int id)\r\n{\r\n\tif (this->findbyID(id) == -1)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\tthis->repo.del(this->findbyID(id));\r\n\treturn true;\r\n}\r\n\r\nbool Controller::update(int id, std::string name, int age, int flights)\r\n{\r\n\tint k = this->findbyID(id);\r\n\tif (k == -1)\r\n\t\treturn false;\r\n\tthis->repo.update(id, name, age, flights);\r\n\treturn true;\r\n}\r\n"
},
{
"alpha_fraction": 0.6456310749053955,
"alphanum_fraction": 0.6456310749053955,
"avg_line_length": 14,
"blob_id": "87b2e13c260ced90ebd6cc5e0540a1deeded827d",
"content_id": "62faac74d515ef3a2d2435e4dbbc1bd3d3564005",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 206,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 13,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/UI.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"Controller.h\"\r\n\r\nclass UI {\r\nprivate:\r\n\tController contro;\r\npublic:\r\n\tUI(Controller c) :contro{ c }{}\r\n\tvoid printMenu();\r\n\tvoid printRepo();\r\n\tPilot readPilot();\r\n\tvoid start();\r\n};"
},
{
"alpha_fraction": 0.4808385968208313,
"alphanum_fraction": 0.4844454526901245,
"avg_line_length": 25.060976028442383,
"blob_id": "fa8c4ab1b6cef67e77e7f58a7b2f8b06600dedc2",
"content_id": "06cca941de12c83ac2f52d67465a9a0a7c736abd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4436,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 164,
"path": "/MyProjects/Graphs/Graphs/Graph 7 python/Graph.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "'''\r\nCreated on May 3, 2018\r\n\r\n@author: Ale\r\n'''\r\nimport math\r\nfrom EdgeCost import *\r\nfrom numpy import Inf\r\n\r\n\r\nclass Graph():\r\n def __init__(self, n):\r\n self._vertices = n\r\n self._dictIn = {}\r\n self._dictOut = {}\r\n self._matr = {}\r\n self._paths = {}\r\n self._generated = False\r\n for i in range(n):\r\n self._dictIn[i] = []\r\n self._dictOut[i] = []\r\n\r\n def fillPaths(self):\r\n for v in self.getVertices():\r\n self._paths[v] = {}\r\n for v2 in self.getVertices():\r\n if v != v2:\r\n self._paths[v][v2] = [(v, v2)]\r\n else:\r\n self._paths[v][v2] = []\r\n\r\n def getDictOut(self):\r\n return self._dictOut\r\n\r\n def getDictIn(self):\r\n return self._dictIn\r\n\r\n def getInForX(self, x):\r\n return self._dictIn[x]\r\n\r\n def getOutForX(self, x):\r\n return self._dictOut[x]\r\n\r\n def getEdge(self, a, b):\r\n if self.checkEdge(a, b):\r\n return True\r\n return False\r\n\r\n def checkEdge(self, a, b):\r\n if a in self._dictOut.keys():\r\n return b in self._dictOut[a]\r\n\r\n def setMatrix(self, matr):\r\n self._matr = matr\r\n\r\n def getMatrix(self):\r\n return self._matr\r\n\r\n def getPaths(self):\r\n return self._paths\r\n\r\n def setPaths(self, p):\r\n self._paths = p\r\n\r\n def getVertices(self):\r\n s = set()\r\n for v in self.getDictIn().keys():\r\n s.add(v)\r\n for v in self.getDictOut().keys():\r\n s.add(v)\r\n return s\r\n\r\n def getNumberOfEdges(self):\r\n res = 0\r\n for vertex in self._dictIn.keys():\r\n res += len(self._dictIn[vertex])\r\n return res\r\n\r\n def addEdge(self, startPoint, endPoint):\r\n if self.validVertex(startPoint) and self.validVertex(endPoint):\r\n if startPoint not in self._dictIn[endPoint]:\r\n self._dictIn[endPoint].append(startPoint)\r\n self._dictOut[startPoint].append(endPoint)\r\n else:\r\n raise ValueError('nope')\r\n else:\r\n raise ValueError('invalid vertices')\r\n\r\n def getGenerated(self):\r\n return self._generated\r\n\r\n def addVertex(self, vertex):\r\n if not self.validVertex(vertex):\r\n self.getDictIn()[vertex] = []\r\n self.getDictOut()[vertex] = []\r\n return 1\r\n\r\n def removeEdge(self, a, b):\r\n if self.checkEdge(a, b):\r\n self._dictIn[b].remove(a)\r\n self._dictOut[a].remove(b)\r\n else:\r\n return 1\r\n\r\n def removeVertex(self, vertex):\r\n if not self.validVertex(vertex):\r\n return 1\r\n if vertex in self._dictIn.keys():\r\n for v in self._dictIn[vertex]:\r\n self._dictOut[v].remove(vertex)\r\n del self._dictIn[vertex]\r\n if vertex in self._dictOut.keys():\r\n for v in self._dictOut[vertex]:\r\n self._dictIn[v].remove(vertex)\r\n del self._dictOut[vertex]\r\n\r\n def getminCostWalk(self, start, end):\r\n n = len(self.getVertices())\r\n mat = self.getMatrix()\r\n self.fillPaths()\r\n path = self.getPaths()\r\n\r\n for i in range(n + 1):\r\n res, path = multiply(mat, mat, path)\r\n mat = res\r\n\r\n self.setPaths(path)\r\n self.setMatrix(res)\r\n\r\n if res[start][start] < 0:\r\n raise ValueError(\"negative cost cycle detected\")\r\n\r\n return res[start][end], path[start][end]\r\n\r\n def validVertex(self, vertex):\r\n return vertex in self.getDictIn().keys() and vertex in self.getDictOut().keys()\r\n\r\n def getIsolatedVertices(self):\r\n l = []\r\n for vertex in self.getDictIn().keys():\r\n if self.getDictIn()[vertex] == [] and self.getDictOut()[vertex] == []:\r\n l.append(vertex)\r\n return l\r\n\r\n\r\ndef multiply(a, b, pathsA):\r\n res = {}\r\n for i in a.keys():\r\n res[i] = {}\r\n for j in b.keys():\r\n l = {}\r\n mini = Inf\r\n for k in a.keys():\r\n e = a[i][k] + b[k][j]\r\n if e < mini:\r\n mini = e\r\n s = k\r\n if mini == Inf:\r\n pathsA[i][j] = []\r\n\r\n pathsA[i][j] = pathsA[i][s] + pathsA[s][j]\r\n res[i][j] = mini\r\n\r\n return res, pathsA"
},
{
"alpha_fraction": 0.6932006478309631,
"alphanum_fraction": 0.6932006478309631,
"avg_line_length": 18.79310417175293,
"blob_id": "1e35077dcc0d2394bda7925e89b151621a25b03d",
"content_id": "393e0c89d9b7b4f26a97ac2c424ba5ba0ef313e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 603,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 29,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/SomeTeacher.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_OtherWindow.h\"\r\n#include \"teacher.h\"\r\n#include \"student.h\"\r\n#include \"studentRepo.h\"\r\n\r\nclass SomeTeacher : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tSomeTeacher(StudentRepo<Student>& s,std::string name, std::vector<int> gr, QWidget *parent = Q_NULLPTR);\r\n\t~SomeTeacher() {}\r\n\tvoid populate();\r\nprivate:\r\n\tUi::OtherWindow ui;\r\n\tStudentRepo<Student>& students;\r\n\tstd::vector<Student> flt;\r\n\tstd::vector<int> groups;\r\n\tstd::string name;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tint getSelectedIndex();\r\n\r\n\tprivate slots:\r\n\tvoid grade();\r\n};\r\n"
},
{
"alpha_fraction": 0.6039119958877563,
"alphanum_fraction": 0.6039119958877563,
"avg_line_length": 19.526315689086914,
"blob_id": "c8e400384974aa3cb01b2f6baf2c534515994331",
"content_id": "9379cd8dfe4bb74d7f855757b88c8674edff37f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 409,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/task.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"task.h\"\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Task::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Description: \" << description << \", Status: \" << status << \", ProgrammerID: \" << programmerid;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Task::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << description << \",\" << status << \",\" << programmerid;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.4733276963233948,
"alphanum_fraction": 0.4750211536884308,
"avg_line_length": 24.244443893432617,
"blob_id": "c96c7438bd0d9a3b37250e12aa00e7793ab0d8a8",
"content_id": "0da3bb151e709f90bac4c4e39f227542116be5a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1183,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 45,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Expressions/ArithmExpr.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing Interpreter.Exceptions;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Expressions\r\n{\r\n public class ArithmExpr:IExpr\r\n {\r\n private IExpr left, right;\r\n private string oper;\r\n\r\n public ArithmExpr(string op, IExpr l, IExpr r)\r\n {\r\n oper = op;\r\n left = l;\r\n right = r;\r\n }\r\n\r\n public int evaluate(Utilities.IDictionary<string, int> dic)\r\n {\r\n int left = this.left.evaluate(dic);\r\n int right = this.right.evaluate(dic);\r\n\r\n switch (oper){\r\n case \"+\":\r\n return left + right;\r\n case \"-\":\r\n return left - right;\r\n case \"*\":\r\n return left * right;\r\n case \"/\":\r\n if (right == 0)\r\n throw new DivisionByZero(\"Division by 0 is not allowed!\");\r\n return left / right;\r\n }\r\n throw new InvalidOperator(\"Invalid operator!\");\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"\" + left + oper +right;\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6099706888198853,
"alphanum_fraction": 0.6158357858657837,
"avg_line_length": 15.947368621826172,
"blob_id": "9bbb48e6291b3f42753650dfadefcdffc6557bdc",
"content_id": "c12c00d583139d75cdfa75c6ae0a8c070882d3b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\nvoid Controller::addStudent(Student s)\r\n{\r\n\tthis->students->add(s);\r\n}\r\n\r\nint Controller::findByID(int id)\r\n{\r\n\tfor (int i = 0;i < this->students->getLenght();i++)\r\n\t\tif (this->students->get(i).getID() == id)\r\n\t\t\treturn i;\r\n\treturn -1;\r\n}\r\n\r\nvoid Controller::delStudent(int pos)\r\n{\r\n\tthis->students->del(pos);\r\n}\r\n"
},
{
"alpha_fraction": 0.6545615792274475,
"alphanum_fraction": 0.6554473042488098,
"avg_line_length": 29.36111068725586,
"blob_id": "a78eb85144dce28b9c903c632df8d6e288461e0f",
"content_id": "909dd73db2e567ee7445957f053b4bce21ce005e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1129,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 36,
"path": "/MyProjects/MAP/Practical Exam/Countdown Latch/src/Model/Statements/AwaitStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Expressions.VarExpr;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\nimport Exception.VariableNotDefined;\r\n\r\npublic class AwaitStmt implements IStmt {\r\n private String var;\r\n\r\n public AwaitStmt(String s){var=s;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer, Integer> latch=state.getLatch();\r\n IStack<IStmt> stack=state.getStack();\r\n if(!dic.exists(var)) throw new VariableNotDefined(\"Variable '\"+var+\"' does not exist in the Symbol Table!\");\r\n IExpr e=new VarExpr(var);\r\n Integer ev=e.evaluate(dic,heap);\r\n\r\n if(!latch.exists(ev)) throw new VariableNotDefined(\"Index not found in the Latch Table!\");\r\n\r\n if(latch.getValue(ev)!=0){\r\n stack.add(this);\r\n }\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"await(\"+var+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6702568531036377,
"alphanum_fraction": 0.6710853576660156,
"avg_line_length": 30.62162208557129,
"blob_id": "6de86e4b7475891695f7056f085fc4a9fdc147f0",
"content_id": "45c816a99a8db022b3fbec3f898a750aa2a4f36d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1207,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 37,
"path": "/MyProjects/MAP/Practical Exam/Lock Table/src/Model/Statements/LockStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Expressions.VarExpr;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Exception.VariableNotDefined;\r\nimport Model.Utilities.IStack;\r\nimport java.io.IOException;\r\n\r\npublic class LockStmt implements IStmt {\r\n private String var;\r\n\r\n public LockStmt(String v){this.var=v;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state)throws IOException {\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer,Integer> lock=state.getLock();\r\n IStack<IStmt> stack=state.getStack();\r\n if(!dic.exists(var)) throw new VariableNotDefined(\"Variable '\"+var+\"' does not exist in the Symbol Table!\");\r\n IExpr e=new VarExpr(var);\r\n Integer ev=e.evaluate(dic,heap);\r\n\r\n if(!lock.exists(ev)) throw new VariableNotDefined(\"Index not found in the Lock Table!\");\r\n\r\n if(lock.getValue(ev)==-1) {lock.setValue(ev,state.getID());return null;}\r\n\r\n stack.add(this);\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"lock(\"+var+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5647059082984924,
"alphanum_fraction": 0.5703081488609314,
"avg_line_length": 17.19354820251465,
"blob_id": "0e9a79aea43fbcb3db71c5b9d4a6fa5f149ca26b",
"content_id": "c0130edb663b87061f37fead7695f084d4c9969d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1785,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 93,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid Repository::add(Vegetable v)\r\n{\r\n\tthis->elems.push_back(v);\r\n\tthis->writeToFile();\r\n}\r\n\r\nvoid Repository::Add(Vegetable v)\r\n{\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t\tif (this->elems[i].getFamily() == v.getFamily())\r\n\t\t\treturn;\r\n\tthis->elems.push_back(v);\r\n}\r\n\r\nvoid Repository::del(int pos)\r\n{\r\n\tthis->elems.erase(this->elems.begin() + pos);\r\n\tthis->writeToFile();\r\n}\r\n\r\nvoid Repository::sort()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\t\r\n\tfor (i = 0; i < this->getLenght()-1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\t\tif (this->elems[j].getFamily() < this->elems[min_idx].getFamily())\r\n\t\t\t\tmin_idx = j;\r\n\t\t\r\n\t\tVegetable a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\nstd::vector<Vegetable> Repository::filter(std::string family)\r\n{\r\n\tvector<Vegetable> v{};\r\n\tfor (auto i : this->elems)\r\n\t{\r\n\t\tif (i.getFamily() == family)\r\n\t\t\tv.push_back(i);\r\n\t}\r\n\treturn v;\r\n}\r\n\r\nvoid Repository::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\nvoid Repository::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ';'))\r\n\t\t\tv.push_back(t);\r\n\t\tstring f, n, p;\r\n\t\tf = v[0];\r\n\t\tn = v[1];\r\n\t\tp = v[2];\r\n\t\tstringstream aici(p);\r\n\t\tvector<string> y{};\r\n\t\twhile (getline(aici, t, ','))\r\n\t\t\ty.push_back(t);\r\n\t\tVegetable m{ f,n,y};\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n"
},
{
"alpha_fraction": 0.4065040647983551,
"alphanum_fraction": 0.4113081991672516,
"avg_line_length": 31.850000381469727,
"blob_id": "3987818a3c0dc655354ce6d5e6c5bcce9d33cb84",
"content_id": "e747024a2d3e69a51202cf1ae5dc929f47228e72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2706,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 80,
"path": "/MyProjects/FP/FP/FP Test 2/controller.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nclass Controller:\r\n def __init__(self,repo=Repository()):\r\n self.__repo=repo\r\n lst=[]\r\n for i in range(len(repo.getAll())):\r\n if repo.get(i).getStatus()=='ill':\r\n lst.append(repo.get(i))\r\n self.__ill=lst\r\n self.__day=0\r\n self.__index=-1\r\n self.__illDays = []\r\n for i in range(len(lst)):\r\n a=[]\r\n a.append(lst[i])\r\n a.append(0)\r\n self.__illDays.append(a)\r\n def __str__(self):\r\n '''\r\n Overwrites the str function for this class\r\n :return:\r\n '''\r\n s=''\r\n for i in range(len(self.__repo.getAll())):\r\n s=s+str(self.__repo.get(i))+', \\n'\r\n return s\r\n def vaccinate(self,id):\r\n '''\r\n Vaccinates a given person if possible\r\n in:param id:\r\n :return:\r\n '''\r\n x=self.__repo.findByID(id)\r\n if self.__repo.get(x).getIS()=='nonvaccinated' and self.__repo.get(x).getStatus()=='healthy':\r\n self.__repo.get(x).setIS('vaccinated')\r\n else:\r\n print(\"Person cannot be vaccinated!\")\r\n def newDay(self):\r\n '''\r\n An ill person will infect a healthy one\r\n :return:\r\n '''\r\n self.__index+=1\r\n self.__day+=1\r\n n=len(self.__ill)\r\n for i in range(n):\r\n ok = 1\r\n if self.__illDays[i][1]<3:\r\n self.__illDays[i][1]+=1\r\n else:\r\n self.__illDays.pop(i)\r\n self.__ill.pop(i)\r\n for j in range(len(self.__repo.getAll())):\r\n if self.__repo.get(j).getStatus()=='healthy' and ok==1:\r\n if self.__repo.get(j).getIS()=='nonvaccinated':\r\n self.__repo.get(j).setStatus('ill')\r\n self.__ill.append(self.__repo.get(j))\r\n a = []\r\n a.append(self.__repo.get(i))\r\n a.append(0)\r\n self.__illDays.append(a)\r\n ok=0\r\n for i in range(len(self.__ill)):\r\n j=self.__ill[i]\r\n j=j.getID()\r\n x=self.__repo.findByID(j)\r\n self.__repo.get(x).setStatus('ill')\r\n def getAll(self):\r\n '''\r\n Returns the repository\r\n :return:\r\n '''\r\n return self.__repo\r\n def get(self,index):\r\n '''\r\n Returns the element on the given index\r\n in:param index:\r\n :return:\r\n '''\r\n return self.__repo.get(index)"
},
{
"alpha_fraction": 0.45448625087738037,
"alphanum_fraction": 0.46151843667030334,
"avg_line_length": 28.839357376098633,
"blob_id": "2d5784028eeed11ca309edcace15edc194187d7d",
"content_id": "8d0fc3d3ac41ef5dd910482f4d7a1b26400c065f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7679,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 249,
"path": "/MyProjects/Graphs/Graphs/Graph 3 python/main.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import heapq\r\n\r\nclass Cost:\r\n def __init__(self):\r\n self._cost = {}\r\n\r\n def get(self):\r\n return self._cost\r\n def addCost(self, x, y, c):\r\n try:\r\n self._cost[(x, y)] = c\r\n except ValueError:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y) + \"\\n\")\r\n\r\n def removeCost(self, x, y):\r\n try:\r\n del self._cost[(x, y)]\r\n except ValueError:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y) + \"\\n\")\r\n\r\n def getCost(self, x, y):\r\n try:\r\n return self._cost[(x, y)]\r\n except ValueError:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y) + \"\\n\")\r\n\r\n def setCost(self, x, y, newC):\r\n try:\r\n self._cost[(x, y)] = newC\r\n except ValueError:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y) + \"\\n\")\r\n\r\nclass DirectGraph:\r\n def __init__(self, n):\r\n self._dictIn = {}\r\n self._dictOut = {}\r\n for i in range(n):\r\n self._dictIn[i] = []\r\n self._dictOut[i] = []\r\n\r\n def parseDict(self):\r\n return self._dictOut.keys()\r\n\r\n def length(self):\r\n return len(self._dictOut.keys())\r\n\r\n def parseOut(self, x):\r\n if x in self._dictOut.keys():\r\n return self._dictOut[x]\r\n else:\r\n print(str(x) + \" is not a vertex\")\r\n\r\n def parseIn(self, x):\r\n if x in self._dictIn.keys():\r\n return self._dictIn[x]\r\n else:\r\n print(str(x) + \" is not a vertex\")\r\n\r\n def isEdge(self, x, y):\r\n if x in self._dictOut.keys():\r\n return y in self._dictOut[x]\r\n else:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y) + \"\\n\")\r\n\r\n def addEdge(self, x, y):\r\n if not self.isEdge(x, y):\r\n self._dictOut[x].append(y)\r\n self._dictIn[y].append(x)\r\n else:\r\n print(\"Edge already exists!\\n\")\r\n\r\n def removeEdge(self, x, y):\r\n if self.isEdge(x, y):\r\n self._dictOut[x].remove(y)\r\n self._dictIn[y].remove(x)\r\n else:\r\n print(\"Edge does not exists!\\n\")\r\n\r\n def addVertex(self, x):\r\n if not x in self._dictOut.keys():\r\n self._dictIn[x] = []\r\n self._dictOut[x] = []\r\n else:\r\n print(\"Vertex already exists! \\n\")\r\n\r\n def removeVertex(self, x):\r\n if x in self._dictOut.keys():\r\n for y in self._dictOut[x]:\r\n self._dictIn[y].remove(x)\r\n del self._dictOut[x]\r\n for y in self._dictIn[x]:\r\n self._dictOut[y].remove(x)\r\n del self._dictIn[x]\r\n else:\r\n print(str(x) + \" is not a vertex! \\n\")\r\n\r\n def inDegree(self, x):\r\n return len(self._dictIn[x])\r\n\r\n def outDegree(self, x):\r\n return len(self._dictOut[x])\r\n\r\ndef initGraph(DirectGraph):\r\n\r\n f = open(\"input\", \"r\")\r\n\r\n initLine = f.readline().strip()\r\n\r\n initLine = initLine.split(\" \")\r\n n = int(initLine[0])\r\n m = int(initLine[1])\r\n\r\n graph = DirectGraph(n)\r\n cost = Cost()\r\n line = f.readline().strip()\r\n\r\n while m > 0:\r\n line = line.split(\" \")\r\n\r\n x = int(line[0])\r\n y = int(line[1])\r\n c = int(line[2])\r\n\r\n graph.addEdge(x, y)\r\n cost.addCost(x, y, c)\r\n\r\n line = f.readline().strip()\r\n\r\n m -= 1\r\n f.close()\r\n return graph, cost\r\n\r\ndef retrievePath(endVertex, parent):\r\n if endVertex not in parent.keys():\r\n return None\r\n list = []\r\n while endVertex is not None:\r\n list.append(endVertex)\r\n endVertex = parent[endVertex]\r\n list.reverse()\r\n return list\r\n\r\n\r\ndef MatrixMultiplication(graph, cost, start, end):\r\n queue = []\r\n heapq.heappush(queue, (0, start))\r\n dist = {start: 0}\r\n prev = {start: None}\r\n while queue:\r\n d, x = heapq.heappop(queue)\r\n for y in graph.parseOut(x):\r\n if y not in prev.keys() or dist[y] > dist[x] + cost[(x, y)]:\r\n prev[y] = x\r\n dist[y] = dist[x] + cost[(x, y)]\r\n heapq.heappush(queue, (dist[y], y))\r\n return retrievePath(end, prev), dist[end]\r\n\r\ndef menu():\r\n print(\"1. Add a edge\")\r\n print(\"2. Remove a edge\")\r\n print(\"3. Add a vertex\")\r\n print(\"4. Remove a vertex\")\r\n print(\"5. Print the graph\")\r\n #print(\"6. Get the number of vertices\")\r\n #print(\"7. Verify if there is an edge\")\r\n #print(\"8. In degree and out degree of a vertex\")\r\n #print(\"9. The outbound edges of a vertex\")\r\n #print(\"10. The inbound edges of a vertex\")\r\n #print(\"11. Get the cost of an edge\")\r\n #print(\"12. Modify the cost of an edge\")\r\n print(\"6. The lowest cost walk between two vertices.\")\r\n print(\"0. Exit\")\r\n\r\ndef start():\r\n graph, cost = initGraph(DirectGraph)\r\n\r\n while True:\r\n menu()\r\n option = int(input(\"Choose: \"))\r\n if option < 0 or option > 13:\r\n print(\"Invalid command!\\n\")\r\n elif option == 0:\r\n break\r\n elif option == 1:\r\n x = int(input(\"First vertex: \"))\r\n y = int(input(\"Second vertex: \"))\r\n c = int(input(\"The cost: \"))\r\n graph.addEdge(x, y)\r\n cost.addCost(x, y, c)\r\n elif option == 2:\r\n x = int(input(\"First vertex: \"))\r\n y = int(input(\"Second vertex: \"))\r\n graph.removeEdge(x, y)\r\n cost.removeCost(x, y)\r\n elif option == 3:\r\n x = int(input(\"Vertex: \"))\r\n graph.addVertex(x)\r\n elif option == 4:\r\n x = int(input(\"Vertex: \"))\r\n graph.removeVertex(x)\r\n elif option == 5:\r\n for x in graph.parseDict():\r\n for y in graph.parseOut(x):\r\n print(\"[\" + str(x) + \" , \" + str(y) + \"]\" + \" -> \" + str(cost.getCost(x, y)))\r\n elif option == 13:\r\n vertices = graph.length()\r\n print(\"There are \" + str(vertices) + \" vertices!\\n\")\r\n elif option == 7:\r\n x = int(input(\"First vertex: \"))\r\n y = int(input(\"Second vertex: \"))\r\n if graph.isEdge(x, y) == 1:\r\n print(\"There's an edge from \" + str(x) + \" to \" + str(y))\r\n else:\r\n print(\"There's no edge from \" + str(x) + \" to \" + str(y))\r\n elif option == 8:\r\n x = int(input(\"Vertex: \"))\r\n print(graph.inDegree(x))\r\n print(graph.outDegree(x))\r\n elif option == 9:\r\n ok = 1\r\n x = int(input(\"Vertex: \"))\r\n for y in graph.parseOut(x):\r\n print(\"[\" + str(x) + \" , \" + str(y) + \"]\")\r\n ok = 0\r\n if ok == 1:\r\n print(\"There are no outbound edges!\\n\")\r\n elif option == 10:\r\n ok = 1\r\n x = int(input(\"Vertex: \"))\r\n for y in graph.parseIn(x):\r\n print(\"[\" + str(y) + \" , \" + str(x) + \"]\")\r\n ok = 0\r\n if ok == 1:\r\n print(\"There are no inbound edges!\\n\")\r\n elif option == 11:\r\n x = int(input(\"First vertex: \"))\r\n y = int(input(\"Second vertex: \"))\r\n print(\"The cost is: \" + str(cost.getCost(x, y)))\r\n elif option == 12:\r\n x = int(input(\"First vertex: \"))\r\n y = int(input(\"Second vertex: \"))\r\n newC = int(input(\"The new cost: \"))\r\n cost.setCost(x, y, newC)\r\n elif option == 6:\r\n x = int(input(\"Start vertex: \"))\r\n y = int(input(\"End vertex: \"))\r\n print(MatrixMultiplication(graph, cost.get(), x, y))\r\n\r\nstart()\r\n"
},
{
"alpha_fraction": 0.5859872698783875,
"alphanum_fraction": 0.6178343892097473,
"avg_line_length": 27.074073791503906,
"blob_id": "70b0ae8f18cbd733605dc5b43bdf5f32d4443230",
"content_id": "4204bb0249bc571f54046a45cd4e5e2585238664",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1570,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 54,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_Again12.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'Again12.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_AGAIN12_H\r\n#define UI_AGAIN12_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_Again12Class\r\n{\r\npublic:\r\n QWidget *centralWidget;\r\n\r\n void setupUi(QMainWindow *Again12Class)\r\n {\r\n if (Again12Class->objectName().isEmpty())\r\n Again12Class->setObjectName(QStringLiteral(\"Again12Class\"));\r\n Again12Class->resize(600, 400);\r\n centralWidget = new QWidget(Again12Class);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n Again12Class->setCentralWidget(centralWidget);\r\n\r\n retranslateUi(Again12Class);\r\n\r\n QMetaObject::connectSlotsByName(Again12Class);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *Again12Class)\r\n {\r\n Again12Class->setWindowTitle(QApplication::translate(\"Again12Class\", \"Again12\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class Again12Class: public Ui_Again12Class {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_AGAIN12_H\r\n"
},
{
"alpha_fraction": 0.6325060129165649,
"alphanum_fraction": 0.6341072916984558,
"avg_line_length": 18.508195877075195,
"blob_id": "2ed6c775a05036729d852b650b4389d8ccb36681",
"content_id": "645fac8163a8157f26076d9788b85be4c8955b00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1249,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 61,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/ProgrammerRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"programmer.h\"\r\n#include <string>\r\n#include <vector>\r\n#include <sstream>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass ProgrammerRepo\r\n{\r\nprivate:\r\n\tstd::vector<T> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tProgrammerRepo(std::string f) :filename{ f } { this->readFromFile(); }\r\n\tProgrammerRepo() :filename{ \"\" } {}\r\n\t~ProgrammerRepo() {}\r\n\r\n\tvoid readFromFile();\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\r\n\tProgrammerRepo<T>& operator=(ProgrammerRepo<T>& p);\r\n};\r\n\r\ntemplate<typename T>\r\ninline void ProgrammerRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tint id;\r\n\t\tstring name;\r\n\t\tid = stoi(v[0]);\r\n\t\tname = v[1];\r\n\t\tProgrammer m{ id,name };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline ProgrammerRepo<T>& ProgrammerRepo<T>::operator=(ProgrammerRepo<T>& p)\r\n{\r\n\tthis->elems = p.elems;\r\n\tthis->filename = p.filename;\r\n\treturn *this;\r\n}"
},
{
"alpha_fraction": 0.5235546231269836,
"alphanum_fraction": 0.5246252417564392,
"avg_line_length": 23.243244171142578,
"blob_id": "ba4eb3f69870bf10de12755ad972f54b956dbdee",
"content_id": "aed1253dd1f35915d796506adec0f0eaf6df00e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 936,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 37,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/IfStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model.Expressions;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class IfStmt:IStmt\r\n {\r\n private IExpr expr;\r\n private IStmt thenStmt;\r\n private IStmt elseStmt;\r\n\r\n public IfStmt(IExpr expression, IStmt thenS, IStmt elseS)\r\n {\r\n expr = expression;\r\n thenStmt = thenS;\r\n elseStmt = elseS;\r\n }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n int val = expr.evaluate(state.SymbolTable);\r\n\r\n if (val != 0)\r\n state.Stack.add(thenStmt);\r\n else\r\n state.Stack.add(elseStmt);\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"if(\" + expr + \") then(\" + thenStmt + \")else(\" + elseStmt + \")\";\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6678832173347473,
"avg_line_length": 22.235294342041016,
"blob_id": "ec7d56b79a24cfb385ebb594701c7cbd52ad908d",
"content_id": "05162be1d1c0f850cb03f8d6fc5ead2f4e18663d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 822,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 34,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/password.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"password.h\"\r\n#include <QMessageBox>\r\n\r\nPassword::Password(Admin &a, QMainWindow *parent)\r\n\t:admin{ a },password{\"Leptop37\"},QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n}\r\n\r\nvoid Password::checkAndShow()\r\n{\r\n\tstd::string s = this->ui.lineEdit->text().toStdString();\r\n\tthis->ui.lineEdit->clear();\r\n\tif (s != this->password)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Incorrect password!\"));\r\n\t\treturn;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tthis->hide();\r\n\t\tthis->admin.show();\r\n\t}\r\n}\r\n\r\nvoid Password::connectSignalsAndSlots()\r\n{\r\n\tthis->ui.lineEdit->setEchoMode(QLineEdit::Password);\r\n\tQObject::connect(this->ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(checkAndShow()));\r\n\r\n\tQObject::connect(this->ui.pushButton, SIGNAL(clicked()), this, SLOT(checkAndShow()));\r\n}"
},
{
"alpha_fraction": 0.7135231494903564,
"alphanum_fraction": 0.7135231494903564,
"avg_line_length": 18.814815521240234,
"blob_id": "203583b13dee4d4ab8d31a4ef854a0886e3398fb",
"content_id": "7e4225bfed2e468a3ddea8db50ea6e8cde0cb383",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 562,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 27,
"path": "/MyProjects/OOP/OOP/Practice - VegetablesProb/VegetablesProb/VegetablesProb.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_VegetablesProb.h\"\r\n#include \"repository.h\"\r\n\r\nclass VegetablesProb : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tVegetablesProb(Repository<Vegetable> &r, QWidget *parent = Q_NULLPTR);\r\n\t~VegetablesProb() {}\r\nprivate:\r\n\tUi::VegetablesProbClass ui;\r\n\tRepository<Vegetable> &repo;\r\n\tvector<Vegetable> list;\r\n\tvector<Vegetable> flt;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid sort();\r\n\tvoid populateFamily();\r\n\tvoid populateVegetable();\r\n\tint getSelectedIndex();\r\n\tprivate slots:\r\n\tvoid filter();\r\n};\r\n"
},
{
"alpha_fraction": 0.39978790283203125,
"alphanum_fraction": 0.4065040647983551,
"avg_line_length": 26.595958709716797,
"blob_id": "ff3bfb830871a9a7b8eb49fdec4998add9978085",
"content_id": "4e0a69ea3a80aef7cddf413d46242e6eb0a09b09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2829,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 99,
"path": "/MyProjects/Graphs/Graphs/Graph 7 python/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "'''\r\nCreated on May 3, 2018\r\n\r\n@author: Ale\r\n'''\r\nfrom numpy import Inf\r\nfrom Graph import *\r\n\r\n\r\nclass UI():\r\n def __init__(self, g):\r\n self._graph = g\r\n self._costs = EdgeCost()\r\n\r\n def printMenu(self):\r\n print('1-load graph from file')\r\n print('2-get min cost walk')\r\n print('0-exit')\r\n\r\n def buildMatrix(self):\r\n m = {}\r\n p = {}\r\n vertices = self._graph.getVertices()\r\n costs = self._costs.getCostDict()\r\n for v in vertices:\r\n m[v] = {}\r\n p[v] = {}\r\n\r\n for i in vertices:\r\n for j in vertices:\r\n p[i][j] = j\r\n if (i, j) in costs.keys():\r\n m[i][j] = costs[(i, j)]\r\n elif i != j:\r\n m[i][j] = Inf\r\n elif i == j:\r\n m[i][j] = 0\r\n\r\n self._graph.setMatrix(m)\r\n\r\n def readFromFile(self, fname):\r\n try:\r\n f = open(fname, 'r')\r\n d = f.readline().strip().split(' ')\r\n n = int(d[0])\r\n m = int(d[1])\r\n self._graph = Graph(n)\r\n self._costs = EdgeCost()\r\n line = f.readline().strip()\r\n while line != '':\r\n data = line.split(' ')\r\n startPoint = int(data[0])\r\n endPoint = int(data[1])\r\n cost = int(data[2])\r\n self._graph.addEdge(startPoint, endPoint)\r\n self._costs.getCostDict()[startPoint, endPoint] = cost\r\n\r\n line = f.readline().strip()\r\n except:\r\n self._graph = Graph(0)\r\n raise ValueError('file could not be opened')\r\n finally:\r\n f.close()\r\n self.buildMatrix()\r\n\r\n def mainMenu(self):\r\n self.printMenu()\r\n while True:\r\n try:\r\n cmd = raw_input(\"Enter command: \")\r\n if cmd == '1':\r\n filename = raw_input(\"Enter filename: \")\r\n self.readFromFile(filename)\r\n\r\n elif cmd == '2':\r\n x = input(\"Enter first vertex: \")\r\n y = input(\"Enter second vertex: \")\r\n if not self._graph.validVertex(x) or not self._graph.validVertex(y):\r\n print(\"Vertices not valid\")\r\n\r\n length, path = self._graph.getminCostWalk(x, y)\r\n\r\n print(\"The total cost is \" + str(length))\r\n\r\n if length == Inf:\r\n print(\"Not accessible\")\r\n else:\r\n print(\"Path: \")\r\n print(path)\r\n\r\n elif cmd == '0':\r\n break\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ng = Graph(0)\r\nui = UI(g)\r\nui.mainMenu()"
},
{
"alpha_fraction": 0.5969331860542297,
"alphanum_fraction": 0.650602400302887,
"avg_line_length": 36.125,
"blob_id": "b7491737090d10f618cfd255d2c9f67dbce11669",
"content_id": "6922d77cfcc7d30d5d6956cc29117b1608bebc90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 913,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 24,
"path": "/MyProjects/FP/FP/Assignment 4/tests.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from domain import *\r\n\r\n\r\ndef testCheckReal(): #test run for function checkReal\r\n assert(checkReal(\"7-0i\")==True)\r\n assert(checkReal(\"-7+0i\")==True)\r\n assert(checkReal(\"-7+9i\")==False)\r\ndef testRealPart(): #test run for function realPart\r\n assert(realPart(\"7+9i\")==7)\r\n assert(realPart(\"-9-8i\")==-9)\r\n assert(realPart(\"0-7i\")==0)\r\ndef testImaginaryPart(): #test run for function imaginaryPart\r\n assert(imaginaryPart(\"-1-1i\")==-1)\r\n assert(imaginaryPart(\"7-9i\")==-9)\r\n assert(imaginaryPart(\"0+0i\")==0)\r\ndef testModuloComplex(): #test run for function moduloComplex\r\n assert(moduloComplex(0,0)==0)\r\n assert(moduloComplex(1,1)!=5)\r\n assert(moduloComplex(3,4)==5)\r\ndef testIntToString(): #test run for function intoToString\r\n assert(intToString(0,0)==\"0+0i\")\r\n assert(intToString(8,-1)==\"8-1i\")\r\n assert(intToString(-7,9)==\"-7+9i\")\r\n assert(intToString(-3,-4)==\"-3-4i\")"
},
{
"alpha_fraction": 0.6418786644935608,
"alphanum_fraction": 0.6418786644935608,
"avg_line_length": 19.375,
"blob_id": "0b31eac87294a84cdcb8cfd33645f5f774dd45db",
"content_id": "f8a4451661967c39fb30c6504d7553634bd4e25d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 511,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 24,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/AstroRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include \"astronomer.h\"\r\n#include <vector>\r\n\r\nclass AstroRepo\r\n{\r\nprivate:\r\n\tstd::vector<Astronomer> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tAstroRepo() :filename{ \"\" } {}\r\n\tAstroRepo(std::string n) :filename{ n } { this->readFromFile(); }\r\n\t~AstroRepo() {}\r\n\r\n\tvoid readFromFile();\r\n\r\n\tvoid add(Astronomer e) { elems.push_back(e); }\r\n\r\n\tstd::vector<Astronomer> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\r\n\tAstronomer operator[](int pos) { return elems[pos]; }\r\n};"
},
{
"alpha_fraction": 0.6288343667984009,
"alphanum_fraction": 0.6365030407905579,
"avg_line_length": 29.14285659790039,
"blob_id": "c38df7547311bb31c39e09c038f065bbd75d22c2",
"content_id": "ec62f0f87b48f2f10c188a923b1dd22a18f1ef80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 652,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Domain.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Pilot {\r\nprivate:\r\n\tstd::string name;\r\n\tint age;\r\n\tint flights;\r\n\tint id;\r\npublic:\r\n\tPilot();\r\n\tPilot(const std::string name, const int age, const int flights, const int id);\r\n\tstd::string getName() { return name; }\r\n\tint getAge() { return age; }\r\n\tint getFlights() { return flights; }\r\n\tint getID() { return id; }\r\n\tbool operator==(Pilot p1) { return (p1.name == this->name&&p1.age == this->age&&p1.flights == this->flights&&p1.id == this->id); }\r\n\tvoid setName(std::string name) { this->name = name; }\r\n\tvoid setAge(int age) { this->age = age; }\r\n\tvoid setFlights(int flights) { this->flights = flights; }\r\n};"
},
{
"alpha_fraction": 0.5074155926704407,
"alphanum_fraction": 0.5074155926704407,
"avg_line_length": 26.809091567993164,
"blob_id": "f0dfc6477bdcafe43a85b2a12d9525d20518e28e",
"content_id": "2e25e8ae9b82bcede16b6caeb0b4173e18b0912b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3171,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 110,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/ProgramState.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing Interpreter.Model.Utilities;\r\nusing Interpreter.Model.Statements;\r\nusing System.Text;\r\nusing System.IO;\r\nusing System.Linq;\r\n\r\nnamespace Interpreter.Model\r\n{\r\n public class ProgramState\r\n {\r\n private IStack<IStmt> stack;\r\n private Utilities.IDictionary<string, int> SymTable;\r\n private Utilities.IList<int> list;\r\n private Utilities.IDictionary<int, StreamReader> FileTable;\r\n\r\n\r\n public ProgramState(IStack<IStmt> stack, Utilities.IDictionary<string, int> symTable, Utilities.IList<int> list, Utilities.IDictionary<int, StreamReader> file)\r\n {\r\n this.stack = stack;\r\n this.SymTable = symTable;\r\n this.list = list;\r\n this.FileTable = file;\r\n }\r\n\r\n public Utilities.IDictionary<string, int> SymbolTable\r\n {\r\n get { return this.SymTable; }\r\n set { this.SymTable = value; }\r\n }\r\n\r\n public Utilities.IDictionary<int, StreamReader> FileTab\r\n {\r\n get { return this.FileTable; }\r\n set { this.FileTable = value; }\r\n }\r\n\r\n public Utilities.IStack<IStmt> Stack\r\n {\r\n get { return this.stack; }\r\n set { this.stack = value; }\r\n }\r\n\r\n public Utilities.IList<int> Output\r\n {\r\n get { return this.list; }\r\n set { this.list = value; }\r\n }\r\n\r\n //public IStack<IStmt> getStack()\r\n //{\r\n // return stack;\r\n //}\r\n //\r\n //public void setStack(IStack<IStmt> stack)\r\n //{\r\n // this.stack = stack;\r\n //}\r\n //\r\n //public Utilities.IDictionary<string, int> getSymTable()\r\n //{\r\n // return SymTable;\r\n //}\r\n //\r\n //public void setFileTable(Utilities.IDictionary<int, StreamReader> table)\r\n //{\r\n // FileTable = table;\r\n //}\r\n //\r\n //public Utilities.IDictionary<int, StreamReader> getFileTable()\r\n //{\r\n // return FileTable;\r\n //}\r\n //\r\n //public void setFileTableMap(Dictionary<int, StreamReader> table)\r\n //{\r\n // FileTable.setMap(table);\r\n //}\r\n //\r\n //public void setSymTable(Utilities.IDictionary<string, int> symTable)\r\n //{\r\n // SymTable = symTable;\r\n //}\r\n //\r\n //public Utilities.IList<int> getList()\r\n //{\r\n // return list;\r\n //}\r\n //\r\n //public void setList(Utilities.IList<int> list)\r\n //{\r\n // this.list = list;\r\n //}\r\n\r\n public override string ToString()\r\n {\r\n StringBuilder buff = new StringBuilder();\r\n buff.Append(\"\\nExeStack:\\n\");\r\n buff.Append(this.stack);\r\n buff.Append(\"\\nSymbolTable:\\n\");\r\n buff.Append(this.SymTable);\r\n buff.Append(\"\\nOutput:\\n\");\r\n buff.Append(this.list);\r\n buff.Append(\"\\nFile Table:\\n\");\r\n buff.Append(this.FileTable);\r\n return buff.ToString();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5953878164291382,
"alphanum_fraction": 0.597484290599823,
"avg_line_length": 16.346153259277344,
"blob_id": "dca5fd9ecf78edc11c9fa479feac7252a124a3e9",
"content_id": "a72516445ae3d796d300b11da8d414dbddd2f3b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 477,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n\r\ntemplate <typename T>\r\nvoid Repository<T>::add(T s)\r\n{\r\n\tthis->elems.push_back(s);\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Repository<T>::del(int pos)\r\n{\r\n\tthis->elems.erase(elems.begin() + pos);\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Repository<T>::update(int id, std::string name, int age)\r\n{\r\n\tfor (int i=0;i<this->elems.size();i++)\r\n\t{\r\n\t\tif (this->elems[i].getID() == id)\r\n\t\t{\r\n\t\t\tthis->elems[i].setAge(age);\r\n\t\t\tthis->elems[i].setName(name);\r\n\t\t}\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.7183098793029785,
"alphanum_fraction": 0.7394366264343262,
"avg_line_length": 18.285715103149414,
"blob_id": "bacbaf593c9b5c2410a06a1d64e0c78462b70db3",
"content_id": "dcf5929f44dda96b50b341596ea25537e1966234",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 142,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/OOPotherpractical1.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPotherpractical1.h\"\r\n\r\nOOPotherpractical1::OOPotherpractical1(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.6752827167510986,
"alphanum_fraction": 0.6752827167510986,
"avg_line_length": 12.785714149475098,
"blob_id": "c5d49613fa1fb81b3c852c932341510e36711e4a",
"content_id": "2f594bacb6fa01096933f7dc048efe3d90662b56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 619,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 42,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/repoException.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n\r\nclass RepoException : public std::exception\r\n{\r\nprotected:\r\n\tstd::string message;\r\n\r\npublic:\r\n\tRepoException();\r\n\r\n\tRepoException(const std::string& msg);\r\n\r\n\tvirtual ~RepoException() {}\r\n\r\n\tvirtual const char* what();\r\n\r\n};\r\n\r\nclass FoundException : public RepoException\r\n{\r\npublic:\r\n\tconst char* what();\r\n};\r\n\r\nclass NoMovieFoundException : public RepoException\r\n{\r\npublic:\r\n\tconst char* what();\r\n};\r\n\r\nclass FileExceptionF : public std::exception\r\n{\r\nprotected:\r\n\tstd::string message;\r\n\r\npublic:\r\n\r\n\tFileExceptionF(const std::string& msg);\r\n\r\n\tvirtual const char* what();\r\n};"
},
{
"alpha_fraction": 0.6538727879524231,
"alphanum_fraction": 0.6664819121360779,
"avg_line_length": 33.3774528503418,
"blob_id": "efdac60b5b9e3b296e90fd0b55e49740fc6b7ea6",
"content_id": "279f7791a3473aaaa0a1bf2b65f3d195f3ad812f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7217,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 204,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/GeneratedFiles/ui_AstronomerWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'AstronomerWindow.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_ASTRONOMERWINDOW_H\r\n#define UI_ASTRONOMERWINDOW_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QCheckBox>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_AstroWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout_5;\r\n QVBoxLayout *verticalLayout_4;\r\n QVBoxLayout *verticalLayout_3;\r\n QLabel *label;\r\n QListWidget *StarsTable;\r\n QLabel *label_5;\r\n QListWidget *FilterList;\r\n QHBoxLayout *horizontalLayout_3;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout_2;\r\n QLabel *label_2;\r\n QLabel *label_3;\r\n QLabel *label_4;\r\n QHBoxLayout *horizontalLayout;\r\n QVBoxLayout *verticalLayout;\r\n QLineEdit *NameLine;\r\n QLineEdit *LuminosityLine;\r\n QLineEdit *TemperatureLine;\r\n QPushButton *AddButton;\r\n QCheckBox *checkBox;\r\n QHBoxLayout *horizontalLayout_4;\r\n QLabel *label_6;\r\n QLineEdit *FilterLine;\r\n\r\n void setupUi(QMainWindow *AstroWindow)\r\n {\r\n if (AstroWindow->objectName().isEmpty())\r\n AstroWindow->setObjectName(QStringLiteral(\"AstroWindow\"));\r\n AstroWindow->resize(561, 566);\r\n centralwidget = new QWidget(AstroWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout_5 = new QHBoxLayout(centralwidget);\r\n horizontalLayout_5->setObjectName(QStringLiteral(\"horizontalLayout_5\"));\r\n verticalLayout_4 = new QVBoxLayout();\r\n verticalLayout_4->setObjectName(QStringLiteral(\"verticalLayout_4\"));\r\n verticalLayout_3 = new QVBoxLayout();\r\n verticalLayout_3->setObjectName(QStringLiteral(\"verticalLayout_3\"));\r\n label = new QLabel(centralwidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout_3->addWidget(label);\r\n\r\n StarsTable = new QListWidget(centralwidget);\r\n StarsTable->setObjectName(QStringLiteral(\"StarsTable\"));\r\n\r\n verticalLayout_3->addWidget(StarsTable);\r\n\r\n label_5 = new QLabel(centralwidget);\r\n label_5->setObjectName(QStringLiteral(\"label_5\"));\r\n\r\n verticalLayout_3->addWidget(label_5);\r\n\r\n FilterList = new QListWidget(centralwidget);\r\n FilterList->setObjectName(QStringLiteral(\"FilterList\"));\r\n\r\n verticalLayout_3->addWidget(FilterList);\r\n\r\n horizontalLayout_3 = new QHBoxLayout();\r\n horizontalLayout_3->setObjectName(QStringLiteral(\"horizontalLayout_3\"));\r\n horizontalLayout_2 = new QHBoxLayout();\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout_2 = new QVBoxLayout();\r\n verticalLayout_2->setObjectName(QStringLiteral(\"verticalLayout_2\"));\r\n label_2 = new QLabel(centralwidget);\r\n label_2->setObjectName(QStringLiteral(\"label_2\"));\r\n\r\n verticalLayout_2->addWidget(label_2);\r\n\r\n label_3 = new QLabel(centralwidget);\r\n label_3->setObjectName(QStringLiteral(\"label_3\"));\r\n\r\n verticalLayout_2->addWidget(label_3);\r\n\r\n label_4 = new QLabel(centralwidget);\r\n label_4->setObjectName(QStringLiteral(\"label_4\"));\r\n\r\n verticalLayout_2->addWidget(label_4);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout_2);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n NameLine = new QLineEdit(centralwidget);\r\n NameLine->setObjectName(QStringLiteral(\"NameLine\"));\r\n\r\n verticalLayout->addWidget(NameLine);\r\n\r\n LuminosityLine = new QLineEdit(centralwidget);\r\n LuminosityLine->setObjectName(QStringLiteral(\"LuminosityLine\"));\r\n\r\n verticalLayout->addWidget(LuminosityLine);\r\n\r\n TemperatureLine = new QLineEdit(centralwidget);\r\n TemperatureLine->setObjectName(QStringLiteral(\"TemperatureLine\"));\r\n\r\n verticalLayout->addWidget(TemperatureLine);\r\n\r\n\r\n horizontalLayout->addLayout(verticalLayout);\r\n\r\n AddButton = new QPushButton(centralwidget);\r\n AddButton->setObjectName(QStringLiteral(\"AddButton\"));\r\n\r\n horizontalLayout->addWidget(AddButton);\r\n\r\n\r\n horizontalLayout_2->addLayout(horizontalLayout);\r\n\r\n\r\n horizontalLayout_3->addLayout(horizontalLayout_2);\r\n\r\n checkBox = new QCheckBox(centralwidget);\r\n checkBox->setObjectName(QStringLiteral(\"checkBox\"));\r\n\r\n horizontalLayout_3->addWidget(checkBox);\r\n\r\n\r\n verticalLayout_3->addLayout(horizontalLayout_3);\r\n\r\n\r\n verticalLayout_4->addLayout(verticalLayout_3);\r\n\r\n horizontalLayout_4 = new QHBoxLayout();\r\n horizontalLayout_4->setObjectName(QStringLiteral(\"horizontalLayout_4\"));\r\n label_6 = new QLabel(centralwidget);\r\n label_6->setObjectName(QStringLiteral(\"label_6\"));\r\n\r\n horizontalLayout_4->addWidget(label_6);\r\n\r\n FilterLine = new QLineEdit(centralwidget);\r\n FilterLine->setObjectName(QStringLiteral(\"FilterLine\"));\r\n\r\n horizontalLayout_4->addWidget(FilterLine);\r\n\r\n\r\n verticalLayout_4->addLayout(horizontalLayout_4);\r\n\r\n\r\n horizontalLayout_5->addLayout(verticalLayout_4);\r\n\r\n AstroWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(AstroWindow);\r\n\r\n QMetaObject::connectSlotsByName(AstroWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *AstroWindow)\r\n {\r\n AstroWindow->setWindowTitle(QApplication::translate(\"AstroWindow\", \"MainWindow\", nullptr));\r\n label->setText(QApplication::translate(\"AstroWindow\", \"Stars:\", nullptr));\r\n label_5->setText(QApplication::translate(\"AstroWindow\", \"Filtered:\", nullptr));\r\n label_2->setText(QApplication::translate(\"AstroWindow\", \"Name:\", nullptr));\r\n label_3->setText(QApplication::translate(\"AstroWindow\", \"Luminosity:\", nullptr));\r\n label_4->setText(QApplication::translate(\"AstroWindow\", \"Temperature:\", nullptr));\r\n AddButton->setText(QApplication::translate(\"AstroWindow\", \"Add\", nullptr));\r\n checkBox->setText(QApplication::translate(\"AstroWindow\", \"Filter by constellation\", nullptr));\r\n label_6->setText(QApplication::translate(\"AstroWindow\", \"Search for\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class AstroWindow: public Ui_AstroWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_ASTRONOMERWINDOW_H\r\n"
},
{
"alpha_fraction": 0.6887966990470886,
"alphanum_fraction": 0.6887966990470886,
"avg_line_length": 15.851851463317871,
"blob_id": "80c675f6766318c013d9df426ba7e5fe0f5fd5b8",
"content_id": "8b725d84305abb9265be70dfe47d49245bf55a39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 482,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 27,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/Vegetables.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_Vegetables.h\"\r\n#include \"repository.h\"\r\n\r\nclass Vegetables : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tVegetables(Repository &r,QWidget *parent = Q_NULLPTR);\r\n\t~Vegetables() {}\r\nprivate:\r\n\tUi::VegetablesWindow ui;\r\n\tRepository &repo;\r\n\tRepository flt;\r\n\r\n\t\r\n\tvoid populateFam();\r\n\tvoid populateVeg();\r\n\tint getSelectedIndex();\r\n\tvoid sort();\r\n\tprivate slots:\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid filterR();\r\n};\r\n"
},
{
"alpha_fraction": 0.4878803491592407,
"alphanum_fraction": 0.4878803491592407,
"avg_line_length": 22.54430389404297,
"blob_id": "b037cf59c8b6bc66c673880d772bbf593e5a2c66",
"content_id": "c56430ad2793c57d1581c39a2e25f80f69ffe1b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1941,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 79,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Utilities/MyDictionary.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Collections;\r\nusing System.Text;\r\nusing Interpreter.Exceptions;\r\n\r\nnamespace Interpreter.Model.Utilities\r\n{\r\n public class MyDictionary<K, V> : IDictionary<K, V>\r\n {\r\n private Dictionary<K, V> elements = new Dictionary<K, V>();\r\n\r\n public MyDictionary()\r\n {\r\n this.elements = new Dictionary<K, V>();\r\n }\r\n\r\n public IEnumerator GetEnumerator()\r\n {\r\n return elements.GetEnumerator();\r\n }\r\n\r\n public void setValue(K key, V value)\r\n {\r\n elements.Add(key, value);\r\n }\r\n\r\n public void delete(K key)\r\n {\r\n elements.Remove(key);\r\n }\r\n\r\n public bool exists(K key)\r\n {\r\n return elements.ContainsKey(key);\r\n }\r\n\r\n public V getValue(K key)\r\n {\r\n if (!exists(key))\r\n throw new VariableNotDefined(\"Variable is missing!\");\r\n return elements[key];\r\n }\r\n\r\n public void clear()\r\n {\r\n this.elements.Clear();\r\n }\r\n\r\n public List<V> getValues()\r\n {\r\n return elements.Values.ToList();\r\n }\r\n\r\n public void setMap(Dictionary<K, V> m) { elements = m; }\r\n\r\n public List<K> getElements()\r\n {\r\n return elements.Keys.ToList();\r\n }\r\n\r\n public Dictionary<K, V> getMap() { return this.elements; }\r\n\r\n public override string ToString()\r\n {\r\n StringBuilder buff = new StringBuilder();\r\n foreach (KeyValuePair<K, V> pair in this.elements)\r\n {\r\n buff.Append(pair.Key);\r\n buff.Append(\":\");\r\n buff.Append(pair.Value);\r\n buff.Append(\"\\n\");\r\n }\r\n buff.Append(\"\\n\");\r\n return buff.ToString();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.47840073704719543,
"alphanum_fraction": 0.4788602888584137,
"avg_line_length": 28.22222137451172,
"blob_id": "6ffd631cf087e7df2ce85ebd93de4a80addc4b9f",
"content_id": "90f06e9edbc2a224511a1f089b2a5a9b30d8ecb2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2178,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 72,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Repository/Repository.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model;\r\nusing Interpreter.Model.Statements;\r\nusing System.IO;\r\n\r\nnamespace Interpreter.Repository\r\n{\r\n public class Repository:IRepo\r\n {\r\n private List<ProgramState> listPrg = new List<ProgramState>();\r\n private int current = 0;\r\n\r\n public Repository() { }\r\n\r\n public void addPrg(ProgramState prg)\r\n {\r\n listPrg.Add(prg);\r\n }\r\n public ProgramState getCurrentPrg()\r\n {\r\n return listPrg[current];\r\n }\r\n\r\n public void logProgramStateExec(string logFilePath)\r\n {\r\n //StreamWriter logFile=new StreamWriter(logFilePath,true);\r\n //logFile.WriteLine(this.getCurrentPrg().ToString());\r\n //logFile.WriteLine(\"------------------\");\r\n //logFile.Close();\r\n ProgramState p = this.getCurrentPrg();\r\n using (StreamWriter log = File.AppendText(\"C:\\\\Users\\\\pechd\\\\source\\\\repos\\\\Interpreter\\\\Interpreter\\\\log.txt\"))\r\n {\r\n\r\n log.WriteLine(\"Stack:\\n\");\r\n foreach (IStmt st in p.Stack)\r\n {\r\n log.WriteLine(st);\r\n }\r\n log.WriteLine(\"SymTable:\\n\");\r\n foreach (KeyValuePair<string, int> v in p.SymbolTable)\r\n {\r\n log.WriteLine(v.Key + \"->\" + v.Value);\r\n }\r\n\r\n log.WriteLine(\"Out:\");\r\n foreach (int v in p.Output)\r\n {\r\n log.WriteLine(v);\r\n }\r\n log.WriteLine(\"FileTable:\");\r\n foreach (KeyValuePair<int, StreamReader> kvp in p.FileTab)\r\n {\r\n log.WriteLine(kvp.Key + \"->\" + kvp.Value);\r\n }\r\n\r\n }\r\n }\r\n\r\n public override string ToString()\r\n {\r\n StringBuilder sb = new StringBuilder();\r\n\r\n foreach (ProgramState state in listPrg)\r\n {\r\n sb.Append(state).Append(\"\\n\");\r\n }\r\n return sb.ToString();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5693780183792114,
"alphanum_fraction": 0.5693780183792114,
"avg_line_length": 14.076923370361328,
"blob_id": "0b0294bb798894be3b6e01b4016fcb5001931fc4",
"content_id": "89bfbfb4d69d84640ae2201a5cef6ffa85936008",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 209,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 13,
"path": "/MyProjects/MAP/Practical Exam/Semaphore/src/Model/Pair.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model;\r\n\r\nimport java.util.List;\r\n\r\npublic class Pair{\r\n public Integer nr;\r\n public List<Integer> list;\r\n\r\n public Pair(Integer a,List<Integer> l){\r\n nr=a;\r\n list=l;\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6590527296066284,
"alphanum_fraction": 0.66805100440979,
"avg_line_length": 34.77454376220703,
"blob_id": "14b2a74039faa0ca49bab7058b7d0783f6383612",
"content_id": "680c21a9f49d63715c63664d7b5c5e5e205327ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 10113,
"license_type": "no_license",
"max_line_length": 183,
"num_lines": 275,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_admin.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'admin.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_ADMIN_H\r\n#define UI_ADMIN_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_AdminWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout_6;\r\n QVBoxLayout *verticalLayout_6;\r\n QHBoxLayout *horizontalLayout_5;\r\n QLabel *MovieListLabel;\r\n QPushButton *UndoButton;\r\n QPushButton *RedoButton;\r\n QVBoxLayout *verticalLayout_5;\r\n QListWidget *MovieList;\r\n QHBoxLayout *horizontalLayout_4;\r\n QHBoxLayout *horizontalLayout;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *TitleLabel;\r\n QLabel *GenrLabel;\r\n QLabel *YearLabel;\r\n QLabel *LikesLabel;\r\n QLabel *TrailerLabel;\r\n QVBoxLayout *verticalLayout_2;\r\n QLineEdit *TitleLine;\r\n QLineEdit *GenreLine;\r\n QLineEdit *YearLine;\r\n QLineEdit *LikesLine;\r\n QLineEdit *TrailerLine;\r\n QVBoxLayout *verticalLayout_4;\r\n QVBoxLayout *verticalLayout_3;\r\n QHBoxLayout *horizontalLayout_2;\r\n QPushButton *AddButton;\r\n QPushButton *DeleteButton;\r\n QPushButton *UpdateButton;\r\n QHBoxLayout *horizontalLayout_3;\r\n QLabel *UpdateTitleLabel;\r\n QLineEdit *UpdateTitleLine;\r\n QLabel *label;\r\n QLineEdit *FilterLine;\r\n\r\n void setupUi(QMainWindow *AdminWindow)\r\n {\r\n if (AdminWindow->objectName().isEmpty())\r\n AdminWindow->setObjectName(QStringLiteral(\"AdminWindow\"));\r\n AdminWindow->resize(591, 390);\r\n centralwidget = new QWidget(AdminWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout_6 = new QHBoxLayout(centralwidget);\r\n horizontalLayout_6->setObjectName(QStringLiteral(\"horizontalLayout_6\"));\r\n verticalLayout_6 = new QVBoxLayout();\r\n verticalLayout_6->setObjectName(QStringLiteral(\"verticalLayout_6\"));\r\n horizontalLayout_5 = new QHBoxLayout();\r\n horizontalLayout_5->setObjectName(QStringLiteral(\"horizontalLayout_5\"));\r\n MovieListLabel = new QLabel(centralwidget);\r\n MovieListLabel->setObjectName(QStringLiteral(\"MovieListLabel\"));\r\n QFont font;\r\n font.setPointSize(10);\r\n MovieListLabel->setFont(font);\r\n\r\n horizontalLayout_5->addWidget(MovieListLabel);\r\n\r\n UndoButton = new QPushButton(centralwidget);\r\n UndoButton->setObjectName(QStringLiteral(\"UndoButton\"));\r\n\r\n horizontalLayout_5->addWidget(UndoButton);\r\n\r\n RedoButton = new QPushButton(centralwidget);\r\n RedoButton->setObjectName(QStringLiteral(\"RedoButton\"));\r\n\r\n horizontalLayout_5->addWidget(RedoButton);\r\n\r\n\r\n verticalLayout_6->addLayout(horizontalLayout_5);\r\n\r\n verticalLayout_5 = new QVBoxLayout();\r\n verticalLayout_5->setObjectName(QStringLiteral(\"verticalLayout_5\"));\r\n MovieList = new QListWidget(centralwidget);\r\n MovieList->setObjectName(QStringLiteral(\"MovieList\"));\r\n QFont font1;\r\n font1.setPointSize(11);\r\n MovieList->setFont(font1);\r\n\r\n verticalLayout_5->addWidget(MovieList);\r\n\r\n horizontalLayout_4 = new QHBoxLayout();\r\n horizontalLayout_4->setObjectName(QStringLiteral(\"horizontalLayout_4\"));\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n TitleLabel = new QLabel(centralwidget);\r\n TitleLabel->setObjectName(QStringLiteral(\"TitleLabel\"));\r\n\r\n verticalLayout->addWidget(TitleLabel);\r\n\r\n GenrLabel = new QLabel(centralwidget);\r\n GenrLabel->setObjectName(QStringLiteral(\"GenrLabel\"));\r\n\r\n verticalLayout->addWidget(GenrLabel);\r\n\r\n YearLabel = new QLabel(centralwidget);\r\n YearLabel->setObjectName(QStringLiteral(\"YearLabel\"));\r\n\r\n verticalLayout->addWidget(YearLabel);\r\n\r\n LikesLabel = new QLabel(centralwidget);\r\n LikesLabel->setObjectName(QStringLiteral(\"LikesLabel\"));\r\n\r\n verticalLayout->addWidget(LikesLabel);\r\n\r\n TrailerLabel = new QLabel(centralwidget);\r\n TrailerLabel->setObjectName(QStringLiteral(\"TrailerLabel\"));\r\n\r\n verticalLayout->addWidget(TrailerLabel);\r\n\r\n\r\n horizontalLayout->addLayout(verticalLayout);\r\n\r\n verticalLayout_2 = new QVBoxLayout();\r\n verticalLayout_2->setObjectName(QStringLiteral(\"verticalLayout_2\"));\r\n TitleLine = new QLineEdit(centralwidget);\r\n TitleLine->setObjectName(QStringLiteral(\"TitleLine\"));\r\n\r\n verticalLayout_2->addWidget(TitleLine);\r\n\r\n GenreLine = new QLineEdit(centralwidget);\r\n GenreLine->setObjectName(QStringLiteral(\"GenreLine\"));\r\n\r\n verticalLayout_2->addWidget(GenreLine);\r\n\r\n YearLine = new QLineEdit(centralwidget);\r\n YearLine->setObjectName(QStringLiteral(\"YearLine\"));\r\n\r\n verticalLayout_2->addWidget(YearLine);\r\n\r\n LikesLine = new QLineEdit(centralwidget);\r\n LikesLine->setObjectName(QStringLiteral(\"LikesLine\"));\r\n\r\n verticalLayout_2->addWidget(LikesLine);\r\n\r\n TrailerLine = new QLineEdit(centralwidget);\r\n TrailerLine->setObjectName(QStringLiteral(\"TrailerLine\"));\r\n\r\n verticalLayout_2->addWidget(TrailerLine);\r\n\r\n\r\n horizontalLayout->addLayout(verticalLayout_2);\r\n\r\n\r\n horizontalLayout_4->addLayout(horizontalLayout);\r\n\r\n verticalLayout_4 = new QVBoxLayout();\r\n verticalLayout_4->setObjectName(QStringLiteral(\"verticalLayout_4\"));\r\n verticalLayout_3 = new QVBoxLayout();\r\n verticalLayout_3->setObjectName(QStringLiteral(\"verticalLayout_3\"));\r\n horizontalLayout_2 = new QHBoxLayout();\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n AddButton = new QPushButton(centralwidget);\r\n AddButton->setObjectName(QStringLiteral(\"AddButton\"));\r\n\r\n horizontalLayout_2->addWidget(AddButton);\r\n\r\n DeleteButton = new QPushButton(centralwidget);\r\n DeleteButton->setObjectName(QStringLiteral(\"DeleteButton\"));\r\n\r\n horizontalLayout_2->addWidget(DeleteButton);\r\n\r\n\r\n verticalLayout_3->addLayout(horizontalLayout_2);\r\n\r\n UpdateButton = new QPushButton(centralwidget);\r\n UpdateButton->setObjectName(QStringLiteral(\"UpdateButton\"));\r\n\r\n verticalLayout_3->addWidget(UpdateButton);\r\n\r\n horizontalLayout_3 = new QHBoxLayout();\r\n horizontalLayout_3->setObjectName(QStringLiteral(\"horizontalLayout_3\"));\r\n UpdateTitleLabel = new QLabel(centralwidget);\r\n UpdateTitleLabel->setObjectName(QStringLiteral(\"UpdateTitleLabel\"));\r\n UpdateTitleLabel->setFont(font);\r\n\r\n horizontalLayout_3->addWidget(UpdateTitleLabel);\r\n\r\n UpdateTitleLine = new QLineEdit(centralwidget);\r\n UpdateTitleLine->setObjectName(QStringLiteral(\"UpdateTitleLine\"));\r\n\r\n horizontalLayout_3->addWidget(UpdateTitleLine);\r\n\r\n\r\n verticalLayout_3->addLayout(horizontalLayout_3);\r\n\r\n\r\n verticalLayout_4->addLayout(verticalLayout_3);\r\n\r\n label = new QLabel(centralwidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout_4->addWidget(label);\r\n\r\n FilterLine = new QLineEdit(centralwidget);\r\n FilterLine->setObjectName(QStringLiteral(\"FilterLine\"));\r\n\r\n verticalLayout_4->addWidget(FilterLine);\r\n\r\n\r\n horizontalLayout_4->addLayout(verticalLayout_4);\r\n\r\n\r\n verticalLayout_5->addLayout(horizontalLayout_4);\r\n\r\n\r\n verticalLayout_6->addLayout(verticalLayout_5);\r\n\r\n\r\n horizontalLayout_6->addLayout(verticalLayout_6);\r\n\r\n AdminWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(AdminWindow);\r\n\r\n QMetaObject::connectSlotsByName(AdminWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *AdminWindow)\r\n {\r\n AdminWindow->setWindowTitle(QApplication::translate(\"AdminWindow\", \"Admin\", nullptr));\r\n MovieListLabel->setText(QApplication::translate(\"AdminWindow\", \"Movie list: \", nullptr));\r\n UndoButton->setText(QApplication::translate(\"AdminWindow\", \"Undo\", nullptr));\r\n RedoButton->setText(QApplication::translate(\"AdminWindow\", \"Redo\", nullptr));\r\n TitleLabel->setText(QApplication::translate(\"AdminWindow\", \"Title:\", nullptr));\r\n GenrLabel->setText(QApplication::translate(\"AdminWindow\", \"Genre:\", nullptr));\r\n YearLabel->setText(QApplication::translate(\"AdminWindow\", \"Year:\", nullptr));\r\n LikesLabel->setText(QApplication::translate(\"AdminWindow\", \"Likes:\", nullptr));\r\n TrailerLabel->setText(QApplication::translate(\"AdminWindow\", \"Trailer:\", nullptr));\r\n AddButton->setText(QApplication::translate(\"AdminWindow\", \"Add\", nullptr));\r\n DeleteButton->setText(QApplication::translate(\"AdminWindow\", \"Delete\", nullptr));\r\n UpdateButton->setText(QApplication::translate(\"AdminWindow\", \"Update\", nullptr));\r\n UpdateTitleLabel->setText(QApplication::translate(\"AdminWindow\", \"Update title:\", nullptr));\r\n label->setText(QApplication::translate(\"AdminWindow\", \"Type anything to filter:\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class AdminWindow: public Ui_AdminWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_ADMIN_H\r\n"
},
{
"alpha_fraction": 0.6736401915550232,
"alphanum_fraction": 0.6736401915550232,
"avg_line_length": 14.066666603088379,
"blob_id": "3580662bf6eff5fb7a4ff5f879928634ab8be9c8",
"content_id": "e62d489b0370c023883af04db59d79fef872916f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 239,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 15,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/tests.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n#include \"repository.h\"\r\n#include \"controller.h\"\r\n#include \"dynamic.h\"\r\n#include <assert.h>\r\n\r\n\r\nclass Test\r\n{\r\npublic:\r\n\tstatic void Tests();\r\n\tstatic void TestRepo();\r\n\tstatic void TestController();\r\n};"
},
{
"alpha_fraction": 0.6079027652740479,
"alphanum_fraction": 0.6089159250259399,
"avg_line_length": 24.675676345825195,
"blob_id": "7896b80e085c2e0ba478533d11d29060c8674de6",
"content_id": "9029ed104535e9c8ceebc1c829289e38a4c5ecb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 987,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 37,
"path": "/MyProjects/MAP/Practical Exam/Countdown Latch/src/Model/Statements/NewLatchStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\n\r\npublic class NewLatchStmt implements IStmt {\r\n private String var;\r\n private IExpr expr;\r\n\r\n public NewLatchStmt(String s,IExpr e){var=s;expr=e;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer, Integer> latch=state.getLatch();\r\n IStack<IStmt> stack=state.getStack();\r\n\r\n Integer number=expr.evaluate(dic,heap);\r\n\r\n int i=1;\r\n while(true){\r\n if(latch.exists(i))\r\n i++;\r\n else break;\r\n }\r\n latch.setValue(i,number);\r\n dic.setValue(var,i);\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"newLatch(\"+var+\",\"+expr+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5876288414001465,
"alphanum_fraction": 0.5931271314620972,
"avg_line_length": 20.213741302490234,
"blob_id": "fc781bf8c6cda4b2e2fee971bb2a28b29961149f",
"content_id": "d392c17d4c06540b956a05da0507f274b06c38cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2910,
"license_type": "no_license",
"max_line_length": 214,
"num_lines": 131,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <sstream>\r\n#include <fstream>\r\n#include <string>\r\n#include <iostream>\r\n#include \"repoException.h\"\r\n#include <Windows.h>\r\n#include <shellapi.h>\r\n\r\nusing namespace std;\r\n\r\nstd::string Repository::toString()\r\n{\r\n\tstd::stringstream buff;\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t{\r\n\t\tbuff << this->elems[i].toString() << '\\n' << '\\n';\r\n\t}\r\n\treturn buff.str();\r\n}\r\n\r\nvoid Repository::add(Movie m)\r\n{\r\n\tthis->elems.push_back(m);\r\n\tthis->writeToFile();\r\n}\r\n\r\nvoid Repository::del(int pos)\r\n{\r\n\tif (pos < 0 || pos >= this->getLenght())\r\n\t\treturn;\r\n\tthis->elems.erase(this->elems.begin() + pos);\r\n\tthis->writeToFile();\r\n}\r\n\r\nvoid Repository::update(std::string oTitle, std::string nTitle, std::string genre, int year, int likes, std::string trailer)\r\n{\r\n\tint k = this->findByTitle(oTitle);\r\n\tMovie m = this->elems[k];\r\n\tm.setTitle(nTitle);\r\n\tm.setGenre(genre);\r\n\tm.setYear(year);\r\n\tm.setLikes(likes);\r\n\tm.setTrailer(trailer);\r\n\tthis->elems[k] = m;\r\n\tthis->writeToFile();\r\n}\r\n\r\nstd::vector<Movie> Repository::filterRepo(std::string s)\r\n{\r\n\tvector<Movie> r{};\r\n\tfor (auto i : this->elems)\r\n\t{\r\n\t\tif (i.getGenre().find(s) != std::string::npos || i.getTitle().find(s) != std::string::npos || std::to_string(i.getYear()).find(s) != std::string::npos || std::to_string(i.getLikes()).find(s) != std::string::npos)\r\n\t\t\tr.push_back(i);\r\n\t}\r\n\treturn r;\r\n}\r\n\r\n\r\n\r\nint Repository::findByTitle(std::string title)\r\n{\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t{\r\n\t\tif (this->elems[i].getTitle() == title)\r\n\t\t\treturn i;\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nstd::string Repository::next()\r\n{\r\n\tif (this->current == this->getLenght() || this->current == -1)\r\n\t\tthis->current = 0;\r\n\tthis->elems[current].watch();\r\n\tthis->current++;\r\n\treturn this->elems[current - 1].toString();\r\n}\r\n\r\nvoid Repository::operator=(Repository r)\r\n{\r\n\tfor (int i = this->elems.size() - 1;i >= 0;i--)\r\n\t\tthis->del(i);\r\n\tfor (int i = 0;i < r.getLenght();i++)\r\n\t\tthis->add(r[i]);\r\n}\r\n\r\nvoid Repository::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\tthrow FileExceptionF(\"This file can not be opened!\");\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\nvoid Repository::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\tthrow FileExceptionF(\"This file can not be opened!\");\r\n\t\t//return;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tstring t, g, tr;\r\n\t\tint y, l;\r\n\t\tt = v[0];\r\n\t\tg = v[1];\r\n\t\ty = stoi(v[2]);\r\n\t\tl = stoi(v[3]);\r\n\t\ttr = v[4];\r\n\t\tMovie m{ t,g,y,l,tr };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\nvoid Repository::displayCSV()\r\n{\r\n\tstring aux = \"\\\"\" + this->getFile() + \"\\\"\";\r\n\tShellExecuteA(NULL, NULL, \"notepad.exe\", aux.c_str(), NULL, SW_SHOWMAXIMIZED);\r\n}\r\n"
},
{
"alpha_fraction": 0.5865352153778076,
"alphanum_fraction": 0.5912954807281494,
"avg_line_length": 20.9921875,
"blob_id": "2bb38f350c2ddba28a78d25027ff36bd81f3b738",
"content_id": "f5a5ec7356958ff94415cb0af28ca13e5bf27978",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2941,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 128,
"path": "/MyProjects/OOP/OOP/Practice - VegetablesProb/VegetablesProb/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"vegetable.h\"\r\n#include <sstream>\r\n#include <string>\r\n#include <fstream>\r\n#include <assert.h>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass Repository\r\n{\r\nprivate:\r\n\tstd::vector<T> elems{};\r\n\tstd::string filename;\r\npublic:\r\n\tRepository() :filename{ \"\" } {}\r\n\tRepository(std::string file) :filename{ file } { this->readFromFile(); }\r\n\tRepository(std::string file, std::vector<T> el) :filename{ file }, elems{ el } { this->readFromFile(); }\r\n\t~Repository() {}\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\tvoid add(T e) { this->elems.push_back(e); this->writeToFile(); }\r\n\tvoid Add(T e) { this->elems.push_back(e); }\r\n\tvoid del(int pos) { this->elems.erase(this->elems.begin() + pos); this->writeToFile(); }\r\n\tvoid Del(int pos) { this->elems.erase(this->elems.begin() + pos); }\r\n\tvector<T> getOnly();\r\n\tT operator[](int pos) { return this->elems[pos]; }\r\n\r\n\t//Sorts the elements from the repository in alphabetical order, by their family name.\r\n\tvoid sort();\r\n\t//Returns all the elements that are part of a given family\r\n\tstd::vector<T> filter(std::string family);\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n};\r\n\r\ntemplate<typename T>\r\ninline vector<T> Repository<T>::getOnly()\r\n{\r\n\tvector<T> el{};\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t{\r\n\t\tint ok = 1;\r\n\t\tfor (int j = 0;j < el.size();j++)\r\n\t\t\tif (el[j].getFamily() == this->elems[i].getFamily())\r\n\t\t\t{\r\n\t\t\t\tok = 0;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\tif (ok == 1)\r\n\t\t\tel.push_back(this->elems[i]);\r\n\t}\r\n\treturn el;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::sort()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\r\n\tfor (i = 0; i < this->getLenght() - 1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\t\tif (this->elems[j].getFamily() < this->elems[min_idx].getFamily())\r\n\t\t\t\tmin_idx = j;\r\n\r\n\t\tT a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\ninline std::vector<T> Repository<T>::filter(std::string family)\r\n{\r\n\tvector<T> v{};\r\n\tfor (auto i : this->elems)\r\n\t{\r\n\t\tif (i.getFamily() == family)\r\n\t\t\tv.push_back(i);\r\n\t}\r\n\treturn v;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ';'))\r\n\t\t\tv.push_back(t);\r\n\t\tstring f, n, p;\r\n\t\tf = v[0];\r\n\t\tn = v[1];\r\n\t\tp = v[2];\r\n\t\tstringstream aici(p);\r\n\t\tvector<string> y{};\r\n\t\twhile (getline(aici, t, ','))\r\n\t\t\ty.push_back(t);\r\n\t\tVegetable m{ f,n,y };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}"
},
{
"alpha_fraction": 0.6097561120986938,
"alphanum_fraction": 0.6158536672592163,
"avg_line_length": 13.733333587646484,
"blob_id": "112646525161864da459fa41fb60b15ee84a0ad8",
"content_id": "5304eb3739b3e4b138369c20d72ad206e84cb251",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 492,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 30,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/dynamic.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#pragma once\r\n#include \"domain.h\"\r\n#include <iostream>\r\n\r\ntypedef Player TElement;\r\n\r\nclass Vector\r\n{\r\nprivate:\r\n\tTElement * elems;\r\n\tint len;\r\n\tint cap;\r\npublic:\r\n\tVector(int cap = 10);\r\n\tVector(const Vector& v);\r\n\t~Vector();\r\n\r\n\tVector& operator=(const Vector& v);\r\n\r\n\tTElement& operator[](int pos);\r\n\r\n\tvoid add(const TElement& e);\r\n\tint getLenght() const;\r\n\r\n\tPlayer get(int pos);\r\n\tTElement* getAll() const;\r\nprivate:\r\n\tvoid resize(int times = 2);\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6070261597633362,
"alphanum_fraction": 0.6078431606292725,
"avg_line_length": 24.042552947998047,
"blob_id": "1d131b42f5c0f20dd8c05d33775efcd24eaa66cb",
"content_id": "450e04b9868e94af2ed1e231fea4b9e639ea7ee7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1224,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 47,
"path": "/MyProjects/MAP/Practical Exam/Cyclic Barrier/src/Model/Statements/NewBarrierStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Pair;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\npublic class NewBarrierStmt implements IStmt {\r\n private String var;\r\n private IExpr expr;\r\n\r\n public NewBarrierStmt(String s,IExpr e){var=s;expr=e;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer, Pair> barrier=state.getBarrier();\r\n IStack<IStmt> stack=state.getStack();\r\n\r\n Integer number=expr.evaluate(dic,heap);\r\n\r\n state.getMylock().lock();\r\n int i=1;\r\n while(true){\r\n if(barrier.exists(i))\r\n i++;\r\n else break;\r\n }\r\n\r\n\r\n List<Integer> l=new ArrayList<>();\r\n Pair p=new Pair(number,l);\r\n barrier.setValue(i,p);\r\n state.getMylock().unlock();\r\n dic.setValue(var,i);\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"newBarrier(\"+var+\",\"+expr+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5900382995605469,
"alphanum_fraction": 0.5900382995605469,
"avg_line_length": 22.85714340209961,
"blob_id": "587583b1fef22bcd7dff2db3d158c86af84bb40c",
"content_id": "b096561dd9cae2951b3aa3f70314b1b27138e506",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 524,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Utilities/IDictionary.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Utilities\r\n{\r\n public interface IDictionary<K, V> : IEnumerable\r\n {\r\n void setValue(K key, V value);\r\n Dictionary<K, V> getMap();\r\n void delete(K key);\r\n V getValue(K key);\r\n void clear();\r\n void setMap(Dictionary<K, V> m);\r\n List<V> getValues();\r\n bool exists(K key);\r\n List<K> getElements();\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.46080759167671204,
"alphanum_fraction": 0.4673396646976471,
"avg_line_length": 15.541666984558105,
"blob_id": "52b5411ffaee2d275a568ee013ae22d27775ab73",
"content_id": "1c6fa480bdcc428ecf98e0c82811a13b22abe37c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1684,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 96,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/UI.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include <string>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nvoid UI<T>::printMenu()\r\n{\r\n\tcout << \"0. Exit\" << endl;\r\n\tcout << \"1. Add\" << endl;\r\n\tcout << \"2. Delete\" << endl;\r\n\tcout << \"3. Update\" << endl;\r\n\tcout << \"4. Print\" << endl;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid UI<T>::printStudent(T s)\r\n{\r\n\tcout << \"ID: \" << s.getID() << \", Name: \" << s.getName() << \", Age: \" << s.getAge();\r\n}\r\n\r\ntemplate <typename T>\r\nvoid UI<T>::printRepo()\r\n{\r\n\tif (this->contro.getAll().getLenght() == 0)\r\n\t{\r\n\t\tcout << \"Empty\";\r\n\t\treturn;\r\n\t}\r\n\tfor (auto i : this->contro.getAll().getAll())\r\n\t{\r\n\t\tcout<<i.overString();\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\ntemplate <typename T>\r\nvoid UI<T>::start()\r\n{\r\n\twhile (true)\r\n\t{\r\n\t\tint command;\r\n\t\tUI<T>::printMenu();\r\n\t\tcout << \"command: \";\r\n\t\tcin >> command;\r\n\t\tif (command == 0)\r\n\t\t\tbreak;\r\n\t\twhile (true)\r\n\t\t{\r\n\t\t\tif (command == 1)\r\n\t\t\t{\r\n\t\t\t\tint id, age;\r\n\t\t\t\tstring name;\r\n\t\t\t\tcout << \"ID: Name: Age:\";\r\n\t\t\t\tcin >> id>> name>> age;\r\n\t\t\t\tT s{ id,name,age };\r\n\t\t\t\tif (this->contro.add(s) == false)\r\n\t\t\t\t\tcout << \"Nope\";\r\n\t\t\t\telse\r\n\t\t\t\t\tcout << \"Ok\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (command == 2)\r\n\t\t\t{\r\n\t\t\t\tint id;\r\n\t\t\t\tcout << \"ID: \";\r\n\t\t\t\tcin >> id;\r\n\t\t\t\tif (this->contro.del(id) == false)\r\n\t\t\t\t\tcout << \"Nope\";\r\n\t\t\t\telse\r\n\t\t\t\t\tcout << \"Ok\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (command == 3)\r\n\t\t\t{\r\n\t\t\t\tint id, age;\r\n\t\t\t\tstring name;\r\n\t\t\t\tcout << \"ID: Name: Age:\";\r\n\t\t\t\tcin >> id>> name>> age;\r\n\t\t\t\tif (this->contro.update(id, name, age) == false)\r\n\t\t\t\t\tcout << \"Nope\";\r\n\t\t\t\telse\r\n\t\t\t\t\tcout << \"Ok\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (command == 4)\r\n\t\t\t{\r\n\t\t\t\tUI<T>::printRepo();\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcout << '\\n';\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.6229507923126221,
"alphanum_fraction": 0.6229507923126221,
"avg_line_length": 22.399999618530273,
"blob_id": "6cd36df2a2d5fadd84f75d6b81071a4f418f8a43",
"content_id": "e43e7de911abf65cc80dbfaf6e664013552dc46e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 488,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Controller::addStar(Star s)\r\n{\r\n\tfor (auto i : stars.getAll())\r\n\t\tif (i.getName() == s.getName())\r\n\t\t\tthrow Exception(\"There is a star with the same name in the repository!\");\r\n\tstars.add(s);\r\n}\r\n\r\nstd::vector<Star> Controller::search(std::string word)\r\n{\r\n\tvector<Star> v{};\r\n\tfor (auto i : stars.getAll())\r\n\t\tif (i.getName().find(word) != std::string::npos || i.getTemp() != std::string::npos)\r\n\t\t\tv.push_back(i);\r\n\treturn v;\r\n}\r\n"
},
{
"alpha_fraction": 0.6481481194496155,
"alphanum_fraction": 0.6481481194496155,
"avg_line_length": 14.399999618530273,
"blob_id": "2f29eb4309d330a37510e1060568f1bdcebb1cf4",
"content_id": "2db2a4fa0ee94122d0c6fdb6e6a681d13f731514",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 10,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/redo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"operation.h\"\r\n\r\nclass Redo :public Operation\r\n{\r\npublic:\r\n\tRedo(Repository r) :Operation(r) {}\r\n\t~Redo() {}\r\n\tvoid execute() override;\r\n};"
},
{
"alpha_fraction": 0.5765672922134399,
"alphanum_fraction": 0.6382322907447815,
"avg_line_length": 25.799999237060547,
"blob_id": "9eec2e76287ab03315e8c7515da30235013dc991",
"content_id": "5b2814f3f89dc6b1583949d2747e0b242eecf380",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 973,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 35,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/appstart.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"domain.h\"\r\n#include \"UI.h\"\r\n#include \"Windows.h\"\r\n#include \"tests.h\"\r\n#include <crtdbg.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\t{\r\n\t\tTest::Tests();\r\n\t\tsystem(\"color 0D\");\r\n\t\tRepository repo{};\r\n\t\tMovie m1{ \"DeadPool\", \"Comedy\", 2016, 1234, \"https://www.youtube.com/watch?v=Xithigfg7dA\" };\r\n\t\tMovie m2{ \"The Greatest Showman\", \"Drama\", 2017, 312, \"https://www.youtube.com/watch?v=AXCTMGYUg9A\" };\r\n\t\tMovie m3{ \"Me Before You\", \"Romance\", 2016, 3534, \"https://www.youtube.com/watch?v=Eh993__rOxA\" };\r\n\t\tMovie m4{ \"The Wolf Of Wall Street\", \"Comedy\", 2013, 43432, \"https://www.youtube.com/watch?v=iszwuX1AK6A\" };\r\n\t\tMovie m5{ \"The Silence of the Lambs\", \"Thriller\", 1991, 324, \"https://www.youtube.com/watch?v=RuX2MQeb8UM\" };\r\n\r\n\t\trepo.addMovie(m1);\r\n\t\trepo.addMovie(m2);\r\n\t\trepo.addMovie(m3);\r\n\t\trepo.addMovie(m4);\r\n\t\trepo.addMovie(m5);\r\n\r\n\t\tController controller{ repo };\r\n\t\tUI ui{ controller };\r\n\t\tui.start();\r\n\t}\r\n\t_CrtDumpMemoryLeaks();\r\n\r\n\treturn 0;\r\n\r\n}\r\n"
},
{
"alpha_fraction": 0.6368715167045593,
"alphanum_fraction": 0.6368715167045593,
"avg_line_length": 9.54838752746582,
"blob_id": "9ca3fdaba4bad38fe4f2e3ae80ea32c4021adda2",
"content_id": "7d06c7d40b3b1cdbc1ff49f68412d5050c2e8c52",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 358,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 31,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPPracticalExam.h\"\r\n#include <QtWidgets/QApplication>\r\n#include <assert.h>\r\n\r\nvoid testDelRepo()\r\n{\r\n\r\n}\r\n\r\nvoid testDelContro()\r\n{\r\n\r\n}\r\n\r\nvoid testUpdateStatusRepo()\r\n{\r\n\r\n}\r\n\r\nvoid testUpdateStatusController()\r\n{\r\n\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\tOOPPracticalExam w;\r\n\tw.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.6376470327377319,
"alphanum_fraction": 0.6376470327377319,
"avg_line_length": 20.473684310913086,
"blob_id": "38d90dc10aa845f8d0ba0697f81ac6115b6f5b92",
"content_id": "828f98b795fc345dedfac276d37b4c40f2cc3ef8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 425,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/teacher.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <vector>\r\n\r\nclass Teacher\r\n{\r\nprivate:\r\n\tstd::string name;\r\n\tstd::vector<int> groups;\r\npublic:\r\n\tTeacher(std::string name,std::vector<int> groups) :name{ name }, groups{ groups } {}\r\n\t~Teacher() {}\r\n\r\n\tbool operator==(Teacher t) { return name == t.getName(); }\r\n\r\n\tstd::string getName() { return name; }\r\n\tstd::vector<int> getGroups() { return groups; }\r\n\tstd::string toString();\r\n};"
},
{
"alpha_fraction": 0.7068965435028076,
"alphanum_fraction": 0.7068965435028076,
"avg_line_length": 22,
"blob_id": "cb6c2dfce5d4c723130c67564c5a3ae1cfcd0792",
"content_id": "82eaaa6f80abbddfb04a7b78567888adf34bdd96",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 406,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 17,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"dynamic.h\"\r\n#include <iostream>\r\n\r\nclass Repository\r\n{\r\nprivate:\r\n\tVector concerts;\r\npublic:\r\n\tRepository() {}\r\n\tint addConcert(const Concert& c);\r\n\tint delConcert(const std::string& band);\r\n\tint updateConcert(const std::string& oldBand, const std::string& newBand, int likes);\r\n\tConcert findByBand(const std::string& band);\r\n\tint find(const Concert& c);\r\n\tVector getConcerts();\r\n};"
},
{
"alpha_fraction": 0.5274930000305176,
"alphanum_fraction": 0.5330848097801208,
"avg_line_length": 18.245283126831055,
"blob_id": "0a0c71806cf1a360418da6b902f26cca2d5b9e1e",
"content_id": "f1e5a05e0dca487028260300cbe3ca8396f544ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1073,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 53,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/csv.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"csv.h\"\r\n#include <fstream>\r\n#include <string>\r\n#include <sstream>\r\n#include \"repoException.h\"\r\n#include <Windows.h>\r\n#include <shellapi.h>\r\n\r\nusing namespace std;\r\n\r\nvoid CSV::writeToFile()\r\n{\r\n\tstd::ofstream file(this->getFile());\r\n\tif (!file.is_open())\r\n\t\tthrow FileExceptionF(\"This file can not be opened!\");\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->getAll()[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\nvoid CSV::display()\r\n{\r\n\tstring aux = \"\\\"\" + this->getFile() + \"\\\"\";\r\n\tShellExecuteA(NULL, NULL, \"notepad.exe\", aux.c_str(), NULL, SW_SHOWMAXIMIZED);\r\n}\r\n\r\n//void CSV::readFromFile()\r\n//{\r\n//\tifstream f(this->getFilename());\r\n//\tif (!f.is_open())\r\n//\t\treturn;\r\n//\r\n//\tstd::string t, i;\r\n//\r\n//\twhile (getline(f, i))\r\n//\t{\r\n//\t\tstd::vector<string> v;\r\n//\t\tstd::stringstream line(i);\r\n//\t\twhile (getline(line, t, ','))\r\n//\t\t\tv.push_back(t);\r\n//\t\tstring t, g, tr;\r\n//\t\tint y, l;\r\n//\t\tt = v[0];\r\n//\t\tg = v[1];\r\n//\t\ty = stoi(v[2]);\r\n//\t\tl = stoi(v[3]);\r\n//\t\ttr = v[4];\r\n//\t\tMovie m{ t,g,y,l,tr };\r\n//\t\tthis->add(m);\r\n//\t}\r\n//\tf.close();\r\n//}\r\n"
},
{
"alpha_fraction": 0.6867749691009521,
"alphanum_fraction": 0.689095139503479,
"avg_line_length": 16.826086044311523,
"blob_id": "ffa264c2f6a640b62fe80940269a86f31aa9f5c8",
"content_id": "b59cc8f4f73b2ce6e96233a144fdd45bc5b7d909",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 23,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/view.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ui_view.h\"\r\n#include <QtWidgets\\QMainWindow>\r\n#include \"repository.h\"\r\n#include \"table.h\"\r\n\r\nclass View :public QMainWindow\r\n{\r\n\tQ_OBJECT\r\nprivate:\r\n\tRepository & repo;\r\n\tRepository & list;\r\n\tMovieTable* mTable;\r\n\tMovieTable* wTable;\r\n\tUi::ViewWindow ui;\r\n\r\npublic:\r\n\tView(Repository &r,Repository &l, QWidget *parent = Q_NULLPTR);\r\n\t~View();\r\nprivate:\r\n\tvoid setupTableView();\r\n\tvoid setupTableView1();\r\n};"
},
{
"alpha_fraction": 0.6216897964477539,
"alphanum_fraction": 0.6229507923126221,
"avg_line_length": 27.44444465637207,
"blob_id": "3c3f9e53eecc99b9b0bd8a991d8738cb5dc6b8d6",
"content_id": "e19a455f7fe46cd056aa9b68470f3af6da2b6816",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 793,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 27,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/student.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Student\r\n{\r\nprivate:\r\n\tint id;\r\n\tstd::string name;\r\n\tint group;\r\n\tdouble grade;\r\n\tstd::string teacher;\r\npublic:\r\n\tStudent(int id, std::string name, int group) :id{ id }, name{ name }, group{ group }, grade{ 1 }, teacher { \"\" } {}\r\n\tStudent(int id, std::string name, int group, double grade,std::string teacher) :id{ id }, name{ name }, group{ group }, grade{ grade }, teacher { teacher } {}\r\n\t~Student() {}\r\n\r\n\tbool operator==(Student t) { return id == t.getID(); }\r\n\r\n\tint getID() { return id; }\r\n\tstd::string getName() { return name; }\r\n\tint getGroup() { return group; }\r\n\tdouble getGrade() { return grade; }\r\n\tvoid setGrade(double gr) { grade = gr; }\r\n\tstd::string getTeacher() { return teacher; }\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.4722374975681305,
"alphanum_fraction": 0.4854315519332886,
"avg_line_length": 23.619718551635742,
"blob_id": "67671cf6fe078eaae5242dd8e01b819f2cf5a45c",
"content_id": "706ceb647136fb4c37115641d287b74f9f0167d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1819,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 71,
"path": "/MyProjects/FP/FP/Assignment 4/domain.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "def checkReal(nr): #checks if the element is a real number\r\n '''\r\n\r\n in:param nr\r\n out:return:True if the element is real or False if it is not\r\n '''\r\n poz=nr.find('i')\r\n if not poz==-1:\r\n if (nr[poz-2]==' ' or nr[poz-2]=='+' or nr[poz-2]=='-') and nr[poz-1]=='0':\r\n return True\r\n elif poz==-1:\r\n return True\r\n return False\r\nfrom math import sqrt\r\ndef moduloComplex(a,b): #returns the modulus of the complex number\r\n '''\r\n\r\n in:param a,b\r\n out:return: the modulus of a and b\r\n '''\r\n return sqrt(a*a+b*b)\r\ndef realPart(nr): #return the real part of nr (nr is complex)\r\n '''\r\n\r\n in:param nr:\r\n out:return: the real part of nr\r\n '''\r\n nr = nr.strip()\r\n x=-1\r\n real=0\r\n aux=nr[1:]\r\n if nr[0]=='-':\r\n if aux.find('+')==-1:\r\n real=int(aux[:aux.find('-')])\r\n elif aux.find('-')==-1:\r\n real=int(aux[:aux.find('+')])\r\n real=real*x\r\n else:\r\n if nr.find('+')==-1:\r\n real=int(nr[:nr.find('-')])\r\n elif nr.find('-')==-1:\r\n real=int(nr[:nr.find('+')])\r\n return real\r\ndef imaginaryPart(nr): #return the imaginary part of nr (nr is complex)\r\n '''\r\n\r\n in:param nr:\r\n out:return: the imaginary part of nr\r\n '''\r\n nr=nr.strip()\r\n if nr[0]=='-' or nr[0]=='+':\r\n aux=nr[1:]\r\n else:\r\n aux=nr[0:]\r\n if aux.find('+')!=-1:\r\n aux=aux[aux.find('+')+1:aux.find('i')]\r\n if aux.find('-')!=-1:\r\n aux=aux[aux.find('-'):aux.find('i')]\r\n img=int(aux)\r\n return img\r\ndef intToString(a,b): #converts 2 intiger numbers into a complex number (string type)\r\n '''\r\n\r\n in:param a,b\r\n out:return: string u\r\n '''\r\n if b<0:\r\n u=str(a)+str(b)+'i'\r\n else:\r\n u = str(a) + '+' + str(b) + 'i'\r\n return u\r\n"
},
{
"alpha_fraction": 0.650943398475647,
"alphanum_fraction": 0.650943398475647,
"avg_line_length": 13.142857551574707,
"blob_id": "9734511d2b9a948389561031f52f1abce958015f",
"content_id": "2135038264691041c3549492fc816bcc1f85f884",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/Retake.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Retake.h\"\r\n\r\nRetake::Retake(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.5166666507720947,
"alphanum_fraction": 0.5444444417953491,
"avg_line_length": 28.018518447875977,
"blob_id": "a4cb5fc2fae7ef8fb980c61b861ebb3ab4375d74",
"content_id": "389d0cb85327b55e6a90c571d6d3a3344a37e4f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3240,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 108,
"path": "/MyProjects/FP/FP/FP Test 1/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from functions import *\r\nfrom tests import *\r\ndef addFlight(myList):\r\n '''\r\n adds a flight to the list\r\n in:param myList:\r\n out:myList\r\n '''\r\n ok=1\r\n aux=[]\r\n x=input(\"Enter the flight code:\")\r\n if len(x)<=3:\r\n ok=0\r\n aux.append(x)\r\n x=int(input(\"Enter the duration:\"))\r\n if x<=20:\r\n ok=0\r\n aux.append(x)\r\n x=input(\"Enter the departure city:\")\r\n if len(x)<=3:\r\n ok=0\r\n aux.append(x)\r\n x=input(\"Enter the destination city:\")\r\n if len(x)<=3:\r\n ok=0\r\n aux.append(x)\r\n if ok==1:\r\n myList.append(aux)\r\n else:\r\n print(\"Input correct values for the flights!\")\r\ndef modifyFlight(myList):\r\n '''\r\n modifies the list of flights at the destination\r\n in:param myList:\r\n '''\r\n code=input(\"Enter the code:\")\r\n duration=int(input(\"Enter the destination:\"))\r\n modifyDuration(myList,code,duration)\r\ndef rerouteMod(myList):\r\n '''\r\n reroutes the flight to a new destination\r\n in:myList\r\n '''\r\n oldDest=input(\"Enter the old destination:\")\r\n newDest=input(\"Enter the new destination:\")\r\n if len(newDest)>3:\r\n flightReroute(myList,oldDest,newDest)\r\n else:\r\n print(\"The new destination is not valid!\")\r\ndef showFlights(myList):\r\n '''\r\n shows the flights that are to a given city increasingly by their duration\r\n in:param myList:\r\n in:param city:\r\n out:myList\r\n '''\r\n city=input(\"Enter the departure city:\")\r\n aux=[]\r\n for i in range(len(myList)-1):\r\n if myList[i][2]==city:\r\n aux.append(myList[i])\r\n sortFlights(aux)\r\n print(aux)\r\ndef showMenu():\r\n '''\r\n shows the menu of the application\r\n '''\r\n fMenu=\"1. Adds a flight with a code, duration, departure city and destination city to the list\\n\"\r\n fMenu+=\"2. Modifies the duration of a given flight\\n\"\r\n fMenu+=\"3. For a given destination city all flights a re rerouted\\n\"\r\n fMenu+=\"4. Shows all flights with a given departure city, increasingly by their duration\\n\"\r\n fMenu+=\"5. Help\\n\"\r\n fMenu+=\"6. Prints the list\\n\"\r\n fMenu+=\"0. Exit\\n\"\r\n print(fMenu)\r\ndef start():\r\n '''\r\n runs the application in the asked way\r\n '''\r\n myList = [[\"0001\", 40, \"Mamaia\", \"Brasov\"], [\"0002\", 45, \"Mamaia\", \"Luxemburg\"],\r\n [\"0003\", 120, \"Cluj Napoca\", \"Alberta\"], [\"0004\", 80, \"Jobou\", \"Baia Mare\"],\r\n [\"0005\", 38, \"Satu Mare\", \"Constanta\"], [\"0006\", 87, \"Tokyo\", \"Bucuresti\"],\r\n [\"0007\", 76, \"Bucuresti\", \"Valcea\"], [\"0008\", 50, \"Brasov\", \"Mamaia\"],\r\n [\"0009\", 90, \"Cluj Napoca\", \"Bucuresti\"], [\"0010\", 100, \"Satu Mare\", \"Bacau\"]]\r\n showMenu()\r\n while True:\r\n print(\">>\")\r\n testFlightReroute()\r\n testModifyDuration()\r\n testSortFlights()\r\n x=int(input(\"Type in a number:\"))\r\n if x==1:\r\n addFlight(myList)\r\n elif x==2:\r\n modifyFlight(myList)\r\n elif x==3:\r\n rerouteMod(myList)\r\n elif x==4:\r\n showFlights(myList)\r\n elif x==5:\r\n showMenu()\r\n elif x==6:\r\n print(myList)\r\n elif x==0:\r\n break\r\n else:\r\n print(\"What was that? Type a number from help!\")\r\nstart()"
},
{
"alpha_fraction": 0.6332518458366394,
"alphanum_fraction": 0.6332518458366394,
"avg_line_length": 13.807692527770996,
"blob_id": "2a0c7eada472aafd0b16fcf312508eea9e394b84",
"content_id": "3778fa439256e39aea3753643191096aa9210252",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 409,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/dynamic.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n\r\n\r\ntypedef Concert TElement;\r\nclass Vector\r\n{\r\nprivate:\r\n\tTElement * elems;\r\n\tint len;\r\n\tint cap;\r\npublic:\r\n\tVector();\r\n\tVector(const Vector& v);\r\n\t~Vector();\r\n\r\n\tVector& operator=(const Vector& v);\r\n\tTElement& operator[](int pos);\r\n\r\n\tvoid add(const TElement& e);\r\n\tvoid del(int pos);\r\n\tint getLenght() { return len; };\r\n\tTElement* getAll();\r\nprivate:\r\n\tvoid resize();\r\n};"
},
{
"alpha_fraction": 0.6054421663284302,
"alphanum_fraction": 0.6054421663284302,
"avg_line_length": 21.210525512695312,
"blob_id": "d7da5f95036c35423bacf968045dd8d7a2b392da",
"content_id": "e63556fe00fe06a3fb4ca586d5004f0aefd38b55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 441,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/domain.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"domain.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nstd::string Task::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Description: \" << this->description << \", Duration: \" << this->duration << \", Priority: \" << this->priority;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Task::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << this->description << ',' << this->duration << ',' << this->priority;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.8220338821411133,
"alphanum_fraction": 0.8220338821411133,
"avg_line_length": 57.5,
"blob_id": "f97cfbfa0472705ddd17db20a7b57e41ad8ca793",
"content_id": "8741454151510a4e237da196bba28f7c34cc8b45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 118,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 2,
"path": "/MyProjects/SDA/README.txt",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "\tThis folder contains my SDA practical project including the documentation and the actual abstract data type.\r\n\tEnjoy!"
},
{
"alpha_fraction": 0.5235008001327515,
"alphanum_fraction": 0.5235008001327515,
"avg_line_length": 27.4761905670166,
"blob_id": "4486c702fc1bfc1ab0c708922cff88d0df311d9d",
"content_id": "abf6b3dc373227e26d44d54a4245b13428a7dc2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 617,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 21,
"path": "/MyProjects/FP/FP/FP Test 2/domain.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Person:\r\n def __init__(self,id,immus,status):\r\n self.__id=id\r\n self.__is=immus\r\n self.__status=status\r\n def __str__(self):\r\n s=''\r\n s=s+'Person ID: '+str(self.__id)+' Immunization status: '+str(self.__is)+' Status: '+str(self.__status)\r\n return s\r\n def getID(self):\r\n return self.__id\r\n def getIS(self):\r\n return self.__is\r\n def getStatus(self):\r\n return self.__status\r\n def setIS(self,status):\r\n self.__is=status\r\n def setStatus(self,status):\r\n self.__status=status\r\n def setID(self,id):\r\n self.__id=id"
},
{
"alpha_fraction": 0.4706205427646637,
"alphanum_fraction": 0.4832509756088257,
"avg_line_length": 21.21019172668457,
"blob_id": "9eeb68fcec50352ebb5bf46b11065d9d450709d8",
"content_id": "826f424a29191f4fb7e424b12f428607f66fe992",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3642,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 157,
"path": "/MyProjects/FP/FP/Assignment 1/proj1.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "def readList():\r\n '''\r\n\r\n in: reads a list of integer numbers\r\n out: return: myList\r\n '''\r\n myList=[]\r\n stop=False\r\n nr=input(\"Enter a value ('end' to terminate):\")\r\n while stop==False:\r\n myList.append(int(nr))\r\n nr=input(\"Enter a value ('end' to terminate):\")\r\n if(nr==\"end\"):\r\n stop=True\r\n return myList\r\ndef printList(myList):\r\n '''\r\n\r\n int: param myList:\r\n out: prints on screen the list\r\n '''\r\n print(myList)\r\n return\r\ndef mountainL(myList):\r\n '''\r\n\r\n int: param myList (list)\r\n out: True if myList is a mountain formation\r\n '''\r\n n=len(myList)\r\n i=1\r\n ok=1\r\n while i<n:\r\n if ok==1 and myList[i]<myList[i-1]:\r\n if i==1:\r\n return False\r\n else:\r\n ok=0\r\n if ok==0 and myList[i]>myList[i-1]:\r\n return False\r\n i=i+1\r\n if ok==1:\r\n return False\r\n return True\r\ndef sortList(myList):\r\n '''\r\n\r\n in: param myList\r\n out: sorts my list in decreasing order\r\n '''\r\n for i in range(len(myList)-1):\r\n ma=myList[i]\r\n poz=i\r\n j=i+1\r\n while j<len(myList):\r\n if(myList[j]>ma):\r\n ma=myList[j]\r\n poz=j\r\n j=j+1\r\n if j!=i:\r\n a=myList[poz]\r\n b=myList[i]\r\n myList[poz]=b\r\n myList[i]=a\r\n return\r\ndef distVal(myList):\r\n '''\r\n\r\n in: param myList\r\n out: True if myList has at most 3 distinct elements, False otherwise\r\n '''\r\n n=len(myList)\r\n count=0\r\n auxList=myList[:]\r\n sortList(auxList)\r\n i=1\r\n while i<n:\r\n a=auxList[i]\r\n b=auxList[i-1]\r\n if a==b:\r\n count=count+1\r\n i=i+1\r\n if n-count>3:\r\n return False\r\n return True\r\ndef printMenu():\r\n '''\r\n\r\n Shows the menu of the application\r\n '''\r\n sMenu=\"1.Read a list from the keyboard\\n\"\r\n sMenu+=\"2.Print the list on the screen\\n\"\r\n sMenu+=\"3.Print the longest sequence from the list that has the mountain property\\n\"\r\n sMenu+=\"4.Print the longest sequence from the list that has at most 3 distinct values\\n\"\r\n sMenu+=\"0.Exit\"\r\n print(sMenu)\r\ndef showSmountain(myList):\r\n '''\r\n\r\n in: param myList\r\n out: prints the longest sequence of a mountain\r\n '''\r\n n = len(myList)\r\n l = 0\r\n show = []\r\n for i in range(n - 3):\r\n j = i + 1\r\n while j in range(n):\r\n aux = myList[i:j + 1]\r\n if mountainL(aux) == True and j + 1 - i > l:\r\n l = j + 1 - i\r\n show = aux[:]\r\n j = j + 1\r\n printList(show)\r\n return\r\ndef showSdist(myList):\r\n '''\r\n\r\n in: param myList\r\n out: prints the longest sequence of numbers with at most 3 distinct values from myList\r\n '''\r\n n=len(myList)\r\n l=0\r\n show=[]\r\n for i in range(n-3):\r\n j=i+1\r\n while j in range(n):\r\n aux=myList[i:j+1]\r\n if distVal(aux)==True and j+1-i>l:\r\n l=j+1-i\r\n show=aux[:]\r\n j=j+1\r\n printList(show)\r\n return\r\ndef start():\r\n '''\r\n\r\n out: starts and runs the application\r\n '''\r\n stop=False\r\n while stop==False:\r\n printMenu()\r\n comm=int(input(\"Input option:\"))\r\n if comm==0:\r\n stop=True\r\n elif comm==1:\r\n myList=readList()\r\n elif comm==2:\r\n printList(myList)\r\n elif comm==3:\r\n showSmountain(myList)\r\n elif comm==4:\r\n showSdist(myList)\r\n else:\r\n print(\"Give a valid option!\")\r\n return\r\nstart()"
},
{
"alpha_fraction": 0.6978798508644104,
"alphanum_fraction": 0.6978798508644104,
"avg_line_length": 24.952381134033203,
"blob_id": "aa613b8f9aa8e786a6848ec6736cfdf087918f5c",
"content_id": "a6bc4d2c05e3bbf51da7ddff99cce7e90faeedf9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 566,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPPracticalex.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"MainTeacher.h\"\r\n#include \"controller.h\"\r\n#include \"repository.h\"\r\n#include \"TeacherWindow.h\"\r\n#include \"student.h\"\r\n#include \"teacher.h\"\r\n#include \"studentRepo.h\"\r\n#include \"teacherRepo.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\tRepository<Student>* st=new StudentRepo<Student>{ \"Students.txt\" };\r\n\tRepository<Teacher>* te=new TeacherRepo<Teacher>{ \"Teachers.txt\" };\r\n\tController c{ st,te };\r\n\tHeadTeacher teacher{ c };\r\n\tteacher.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.6382978558540344,
"alphanum_fraction": 0.6393110156059265,
"avg_line_length": 20.953489303588867,
"blob_id": "65f300c44b55e4a98d709182e93b7da72df2d00c",
"content_id": "79b56f404bcfd85f4a7d64bc01ef4994be23e9ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 987,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 43,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <vector>\r\n\r\ntemplate <typename T>\r\nclass Repository\r\n{\r\nprivate:\r\n\tstd::vector<T> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tRepository(std::string filename) :filename{ filename } {}\r\n\tRepository() : filename{ \"\" } {}\r\n\t~Repository() {}\r\n\r\n\tvirtual void writeToFile() {}\r\n\tvirtual void readFromFile() {}\r\n\r\n\tvirtual void sorted() {}\r\n\r\n\tvoid add(T e);\r\n\tvoid del(int pos);\r\n\t\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\tT get(int pos) { return elems[pos]; }\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\tvoid setElems(std::vector<T> v) { elems = v; }\r\n\tvirtual int findByID(int id) { return 0; }\r\n\tvirtual void setGrade(int pos, int gr) {}\r\n\tvirtual std::vector<T> getByGroups(std::vector<int> gr) { return elems; }\r\n};\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::add(T e)\r\n{\r\n\telems.push_back(e);\r\n}\r\n\r\ntemplate<typename T>\r\ninline void Repository<T>::del(int pos)\r\n{\r\n\telems.erase(elems.begin() + pos);\r\n}\r\n"
},
{
"alpha_fraction": 0.6471518874168396,
"alphanum_fraction": 0.6518987417221069,
"avg_line_length": 23.795917510986328,
"blob_id": "52348a351d9040e581a35f751bbae2d212cf3705",
"content_id": "f13bf85ffd68ca8e1cb785469a312924033eb5f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2528,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 98,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/AstroWindow.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"AstroWindow.h\"\r\n#include <QMessageBox>\r\n\r\nusing namespace std;\r\n\r\nAWindow::AWindow(Controller& c, Astronomer a, QWidget *parent)\r\n\t:contro{ c }, astro{ a }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->setWindowTitle(QString::fromStdString(a.getName()));\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->stars = this->contro.getStars().getAll();\r\n\tthis->populate();\r\n\tok = 1;\r\n}\r\n\r\nvoid AWindow::add()\r\n{\r\n\ttry {\r\n\t\tif (ui.NameLine->text().toStdString().length() == 0)\r\n\t\t\tthrow Exception(\"There is no name for the star!\");\r\n\t\tstring con = astro.getConste();\r\n\t\tstring name = ui.NameLine->text().toStdString();\r\n\t\tdouble lum = ui.LuminosityLine->text().toDouble();\r\n\t\tdouble tem = ui.TemperatureLine->text().toDouble();\r\n\r\n\t\tStar s{ name,con,lum,tem };\r\n\t\tthis->contro.addStar(s);\r\n\t\tthis->populate();\r\n\t}\r\n\tcatch (Exception& e)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n\tui.NameLine->clear();\r\n\tui.TemperatureLine->clear();\r\n\tui.LuminosityLine->clear();\r\n}\r\n\r\nvoid AWindow::modify()\r\n{\r\n\tif (ok == 1)\r\n\t{\r\n\t\tthis->stars = this->contro.filter(this->astro.getConste());\r\n\t\tok = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tthis->stars = this->contro.getStars().getAll();\r\n\t\tok = 1;\r\n\t}\r\n\tthis->populate();\r\n}\r\n\r\nvoid AWindow::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(this->ui.AddButton, SIGNAL(clicked()), this, SLOT(add()));\r\n\tQObject::connect(this->ui.checkBox, SIGNAL(clicked(bool)), this, SLOT(modify()));\r\n\tQObject::connect(this->ui.FilterLine, SIGNAL(textChanged(const QString&)), this, SLOT(filterMe()));\r\n}\r\n\r\nvoid AWindow::populate()\r\n{\r\n\tvector<Star> aici = this->contro.getStars().getAll();\r\n\tif (ui.StarsTable->count() != 0)\r\n\t\tui.StarsTable->clear();\r\n\tfor (auto m : stars)\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.StarsTable->addItem(listItemWidget);\r\n\t}\r\n\tif (stars.size() > 0)\r\n\t\tui.StarsTable->setCurrentRow(0);\r\n\tthis->contro.save();\r\n}\r\n\r\nvoid AWindow::populateList()\r\n{\r\n\tif (ui.FilterList->count() != 0)\r\n\t\tui.FilterList->clear();\r\n\tfor (auto m : this->filter)\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.FilterList->addItem(listItemWidget);\r\n\t}\r\n\tif (this->filter.size() > 0)\r\n\t\tui.FilterList->setCurrentRow(0);\r\n}\r\n\r\nvoid AWindow::filterMe()\r\n{\r\n\tstring w = ui.FilterLine->text().toStdString();\r\n\tthis->filter = this->contro.search(w);\r\n\tthis->populateList();\r\n}\r\n"
},
{
"alpha_fraction": 0.7924528121948242,
"alphanum_fraction": 0.7924528121948242,
"avg_line_length": 51,
"blob_id": "51506d162ec66cd47ea8e780b833b0bb367bf2e7",
"content_id": "81a58ebd08ef3ea722cd509c1495c9c94ec8c8cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 53,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 1,
"path": "/MyProjects/README.txt",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "\tThese are the faculty objects that I have attached.\n"
},
{
"alpha_fraction": 0.5475372076034546,
"alphanum_fraction": 0.5578464865684509,
"avg_line_length": 13.909090995788574,
"blob_id": "65c91f42d0f5ee917aebf53724fb1edb9ac185af",
"content_id": "e16d8e8f6a4564acad7fab4acd6998cec9a8f728",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 873,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 55,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/list.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"list.h\"\r\n\r\nList::List()\r\n{\r\n\tthis->current = 0;\r\n}\r\n\r\nvoid List::add(const Movie & m)\r\n{\r\n\tthis->movie.add(m);\r\n}\r\n\r\nMovie List::getCurrent()\r\n{\r\n\tif (this->current == this->movie.getLenght())\r\n\t\tthis->current = 0;\r\n\tMovie* m = this->movie.getAll();\r\n\tif (m != NULL)\r\n\t\treturn m[this->current];\r\n\treturn Movie{};\r\n}\r\n\r\nvoid List::watch()\r\n{\r\n\tif (this->movie.getLenght() == 0)\r\n\t\treturn;\r\n\tthis->current = 0;\r\n\tMovie m = this->getCurrent();\r\n\tm.video();\r\n}\r\n\r\nvoid List::next()\r\n{\r\n\tif (this->movie.getLenght() == 0)\r\n\t\treturn;\r\n\tthis->current++;\r\n\tMovie m = this->getCurrent();\r\n\tm.video();\r\n}\r\n\r\nbool List::empty()\r\n{\r\n\treturn this->movie.getLenght() == 0;\r\n}\r\n\r\nint List::del(const std::string & title)\r\n{\r\n\tfor (int i = 0;i<this->movie.getLenght();i++)\r\n\t\tif (this->movie[i].getTitle() == title)\r\n\t\t{\r\n\t\t\tthis->movie.del(i);\r\n\t\t\treturn 1;\r\n\t\t}\r\n\treturn -1;\r\n}"
},
{
"alpha_fraction": 0.67136150598526,
"alphanum_fraction": 0.67136150598526,
"avg_line_length": 12.199999809265137,
"blob_id": "a4cb584e0b7bb377ad1e9b789696e59ff7cc0fa7",
"content_id": "c7636224e324909e4b716fdd29d0d4018713c9c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 213,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 15,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/Retake.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_Retake.h\"\r\n\r\nclass Retake : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tRetake(QWidget *parent = Q_NULLPTR);\r\n\r\nprivate:\r\n\tUi::RetakeClass ui;\r\n};\r\n"
},
{
"alpha_fraction": 0.6607142686843872,
"alphanum_fraction": 0.6641929745674133,
"avg_line_length": 23.82036018371582,
"blob_id": "8f84bd4722905be7dcda4acee4efd5bf6ae5b2da",
"content_id": "015469d3bca8a87ac392d6286f4f474d24d8d7d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4312,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 167,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/ProgrammerWindow.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"ProgrammerWindow.h\"\r\n#include <string>\r\n#include <QMessageBox>\r\n\r\nusing namespace std;\r\n\r\nProgrammerWindow::ProgrammerWindow(Controller& c, Programmer p, std::vector<ProgrammerWindow*> v, QWidget *parent)\r\n\t:controller{ c }, prog{ p }, allWindows{ v }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->setWindowTitle(QString::fromStdString(p.getName()));\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populate();\r\n}\r\n\r\nProgrammerWindow::ProgrammerWindow(Controller& c, Programmer p, QWidget *parent)\r\n\t:controller{ c }, prog{ p }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->setWindowTitle(QString::fromStdString(p.getName()));\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populate();\r\n}\r\n\r\nProgrammerWindow::ProgrammerWindow(QWidget *parent)\r\n\t:controller{Controller()}, prog{ }, allWindows{ }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n}\r\n\r\nProgrammerWindow::~ProgrammerWindow()\r\n{\r\n\tcontroller.saveTasks();\r\n}\r\n\r\nvoid ProgrammerWindow::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.AddButton, SIGNAL(clicked()), this, SLOT(add()));\r\n\tQObject::connect(ui.DeleteButton, SIGNAL(clicked()), this, SLOT(del()));\r\n\tQObject::connect(ui.StartButton, SIGNAL(clicked()), this, SLOT(start()));\r\n\tQObject::connect(ui.DoneButton, SIGNAL(clicked()), this, SLOT(done()));\r\n\t//QObject::connect(ui.TaskList, SIGNAL(itemSelectionChanged()), SLOT(checkDel()));\r\n}\r\n\r\nint ProgrammerWindow::getSelectedIndex()\r\n{\r\n\tif (ui.TaskList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.TaskList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid ProgrammerWindow::populate()\r\n{\r\n\tthis->controller.sortTasks();\r\n\r\n\tif (ui.TaskList->count() != 0)\r\n\t\tui.TaskList->clear();\r\n\tfor (auto m : this->controller.getTasks().getAll())\r\n\t{\r\n\t\tif (m.getID() == -1)\r\n\t\t{\r\n\t\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\t\tthis->ui.TaskList->addItem(listItemWidget);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tQString listItem = QString::fromStdString(m.toString1());\r\n\t\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\t\tthis->ui.TaskList->addItem(listItemWidget);\r\n\t\t}\r\n\t}\r\n\tif (this->controller.getTasks().getLenght() > 0)\r\n\t\tui.TaskList->setCurrentRow(0);\r\n\t//this->modifyAll();\r\n}\r\n\r\nvoid ProgrammerWindow::showIt()\r\n{\r\n\tthis->setWindowTitle(QString::fromStdString(prog.getName()));\r\n\tthis->populate();\r\n\tthis->show();\r\n}\r\n\r\nvoid ProgrammerWindow::modifyAll()\r\n{\r\n\tfor (auto i : allWindows)\r\n\t\ti->populate();\r\n}\r\n\r\nvoid ProgrammerWindow::add()\r\n{\r\n\tstring s = ui.TaskLine->text().toStdString();\r\n\tui.TaskLine->clear();\r\n\tTask t{ s };\r\n\tthis->controller.addTask(t);\r\n\tthis->populate();\r\n\tcontroller.saveTasks();\r\n}\r\n\r\nvoid ProgrammerWindow::start()\r\n{\r\n\ttry {\r\n\t\tint k = this->getSelectedIndex();\r\n\t\tint n = prog.getID();\r\n\t\tstring na = prog.getName();\r\n\t\tcontroller.startTask(k, n, na);\r\n\t\tthis->populate();\r\n\t\tcontroller.saveTasks();\r\n\t}\r\n\tcatch (exception& e)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n}\r\n\r\nvoid ProgrammerWindow::done()\r\n{\r\n\ttry {\r\n\t\tint k = this->getSelectedIndex();\r\n\t\tif (controller.getTasks()[k].getID() != prog.getID())\r\n\t\t{\r\n\t\t\tthrow Exception{ \"Task status is not 'in progress' or you are not the one who started the task!\" };\r\n\t\t}\r\n\t\tcontroller.finishTask(k);\r\n\t\tthis->populate();\r\n\t\tcontroller.saveTasks();\r\n\t}\r\n\tcatch (exception& e)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n}\r\n\r\nvoid ProgrammerWindow::del()\r\n{\r\n\ttry {\r\n\t\tint k = this->getSelectedIndex();\r\n\t\tif (controller.getTasks()[k].getIntStat() != 0 || controller.getTasks()[k].getID() != prog.getID())\r\n\t\t\tthrow Exception{ \"You cannot delete this item!\" };\r\n\t\tcontroller.delTask(k);\r\n\t\tthis->populate();\r\n\t\tcontroller.saveTasks();\r\n\t}\r\n\tcatch (exception& e)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(e.what()));\r\n\t}\r\n}\r\n\r\nvoid ProgrammerWindow::checkDel()\r\n{\r\n\tint k = this->getSelectedIndex();\r\n\tif (controller.getTasks()[k].getIntStat() == 0 && controller.getTasks()[k].getID() == prog.getID())\r\n\t\tui.DeleteButton->setEnabled(true);\r\n\telse\r\n\t\tui.DeleteButton->setDisabled(true);\r\n}\r\n"
},
{
"alpha_fraction": 0.6983758807182312,
"alphanum_fraction": 0.6983758807182312,
"avg_line_length": 18.619047164916992,
"blob_id": "157f5478561947bcfb0e6d8d4e5820c2a35ec158",
"content_id": "9a17c16ffd73b9d9c402e19dff8acc9392371637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/password.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ui_password.h\"\r\n#include <QtWidgets\\QMainWindow>\r\n#include <Admin.h>\r\n\r\nclass Password :public QMainWindow\r\n{\r\n\tQ_OBJECT\r\npublic:\r\n\tPassword(Admin &a, QMainWindow *parent=Q_NULLPTR);\r\n\t~Password() {}\r\n\tvoid readFromFile() { this->admin.readFromFile(); }\r\nprivate:\r\n\tUi::PasswordWindow ui;\r\n\tAdmin& admin;\r\n\tstd::string password;\r\n\r\n\tprivate slots:\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid checkAndShow();\r\n};"
},
{
"alpha_fraction": 0.5828877091407776,
"alphanum_fraction": 0.5909090638160706,
"avg_line_length": 24.785715103149414,
"blob_id": "0798c77d0a01e01ee301ff2f0a320d91a1da9ba6",
"content_id": "60035e9942fba856b9551adb4b27b0cde767a4f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 748,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 28,
"path": "/MyProjects/FP/FP/FP Test 1/functions.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "def modifyDuration(myList,code,duration):\r\n '''\r\n modifies the duration of a flight with a given code\r\n in:param myList:\r\n in:param code:\r\n out:myList\r\n '''\r\n for i in range(len(myList)):\r\n if myList[i][0]==code:\r\n myList[i][1]=duration\r\ndef flightReroute(myList,oldDest,newDest):\r\n '''\r\n reroutes the flight to a new destination\r\n in:param myList:\r\n in:param oldDest:\r\n in:param newDest:\r\n out:myList\r\n '''\r\n for i in range(len(myList)-1):\r\n if myList[i][3]==oldDest:\r\n myList[i][3]=newDest\r\ndef sortFlights(myList):\r\n '''\r\n sorts the flights increasingly by their duration\r\n in:param myList:\r\n :return:\r\n '''\r\n myList.sort(key=lambda elem:elem[1])"
},
{
"alpha_fraction": 0.6743420958518982,
"alphanum_fraction": 0.6809210777282715,
"avg_line_length": 19.85714340209961,
"blob_id": "7d2fb270497290368670e18939b2c2039da03c38",
"content_id": "b2563306f6ad8d86ee92ead9f378612464e641e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 304,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 14,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/watchFile.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n\r\nclass MovieFile :public Repository {\r\nprotected:\r\n\tstd::string filename;\r\npublic:\r\n\tMovieFile() :Repository{}, filename(\"\"){}\r\n\tvirtual ~MovieFile() {}\r\n\r\n\tvoid setFilename(std::string filename);\r\n\tvirtual void writeToFile() = 0;\r\n\tvirtual void display() = 0;\r\n};"
},
{
"alpha_fraction": 0.5757575631141663,
"alphanum_fraction": 0.581818163394928,
"avg_line_length": 31,
"blob_id": "68daee3280558985bb2298e3199f0c7f38be94e7",
"content_id": "21a0874ebbfe6913434a241fbb78d80116cbaafb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 330,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 10,
"path": "/MyProjects/Graphs/Graphs/Graph 1 python/graph.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Graph:\r\n '''\r\n A directed graph, represented as two maps,\r\n one from each vertex to the set of outbound neighbours,\r\n the other from each vertex to the set of inbound neighbours\r\n '''\r\n def __init__(self,n):\r\n '''\r\n Creates a graph with n vertices (from 0 to n-1), no edges\r\n '''\r\n"
},
{
"alpha_fraction": 0.7083333134651184,
"alphanum_fraction": 0.7083333134651184,
"avg_line_length": 30.909090042114258,
"blob_id": "794a5ac387616fa4949736cfc263a08a80b2ff3b",
"content_id": "d785133785e924039e82a417ce4dad29cc29f028",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 360,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 11,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/node.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\ntemplate <typename TElem>\r\nclass Node\r\n{\r\npublic:\r\n\tTElem data;\t\t// data contains the value of type TElem of the node\r\n\tNode* parent;\t// parent is a pointer to the parent of the current node\r\n\tNode* left;\t\t// left is a pointer to the left child of the current node\r\n\tNode* right;\t// right is a pointer to the right child of the current node\r\n};"
},
{
"alpha_fraction": 0.5487465262413025,
"alphanum_fraction": 0.5487465262413025,
"avg_line_length": 21.161291122436523,
"blob_id": "c5970de519a876ccffe02d3e763a68bb321402cb",
"content_id": "aabc32a1c39ee40da8f73e5a7b4233912f8a186e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 720,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 31,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/AssignStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing Interpreter.Model.Expressions;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class AssignStmt:IStmt\r\n {\r\n private string id;\r\n private IExpr expr;\r\n\r\n public AssignStmt(string key, IExpr expression)\r\n {\r\n id = key;\r\n expr = expression;\r\n }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n int val = expr.evaluate(state.SymbolTable);\r\n state.SymbolTable.setValue(id, val);\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return id + \"=\" + expr;\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.48275861144065857,
"alphanum_fraction": 0.4889655113220215,
"avg_line_length": 16.58974266052246,
"blob_id": "5a204b0f5b2b21150011a2c56ae8078dbda8c72f",
"content_id": "3e66176368b73c817d467d169f6f7871066fb5da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1450,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 78,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/UI.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid UI::printMenu()\r\n{\r\n\tcout << \"1. Add\" << endl;\r\n\tcout << \"2. Delete\" << endl;\r\n\tcout << \"3. Update\" << endl;\r\n}\r\n\r\nvoid UI::printRepo()\r\n{\r\n\tRepository r = this->contro.getRepo();\r\n\tfor (auto i : r.getAll())\r\n\t\tcout << \"ID: \" << i.getID() << \" Name: \" << i.getName() << \" Age: \" << i.getAge() << \" Flights: \" << i.getFlights() << endl;\r\n}\r\n\r\nPilot UI::readPilot()\r\n{\r\n\tstring name;\r\n\tint age, flights, id;\r\n\tcout << \"Name, Age, Flights, ID:\" << endl;\r\n\tcin >> name >> age >> flights >> id;\r\n\tPilot p{ name,age,flights,id };\r\n\treturn p;\r\n}\r\n\r\nvoid UI::start()\r\n{\r\n\tint command;\r\n\twhile (true)\r\n\t{\r\n\t\tUI::printMenu();\r\n\t\tcout << \"command: \";\r\n\t\tcin >> command;\r\n\t\tif (command == 0)\r\n\t\t\tbreak;\r\n\t\twhile (true)\r\n\t\t{\r\n\t\t\tif (command == 1)\r\n\t\t\t{\r\n\t\t\t\tPilot p=UI::readPilot();\r\n\t\t\t\tthis->contro.add(p);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (command == 2)\r\n\t\t\t{\r\n\t\t\t\tint pos;\r\n\t\t\t\tcout << \"id: \";\r\n\t\t\t\tcin >> pos;\r\n\t\t\t\tthis->contro.del(pos);\r\n\t\t\t}\r\n\t\t\tif (command == 3)\r\n\t\t\t{\r\n\t\t\t\tcout << \"id: name: age: flights: \" << endl;\r\n\t\t\t\tint age, flights,id;\r\n\t\t\t\tstring name;\r\n\t\t\t\tcin >> id >> name >> age >> flights;\r\n\t\t\t\tthis->contro.update(id, name, age, flights);\r\n\t\t\t}\r\n\t\t\tif (command == 4)\r\n\t\t\t{\r\n\t\t\t\tif (this->contro.getRepo().getLenght() == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"nem\" << endl;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tUI::printRepo();\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.6850865483283997,
"alphanum_fraction": 0.6857523322105408,
"avg_line_length": 22.655736923217773,
"blob_id": "5bb4998e6cb28f28935a767c6c5167894b85b99d",
"content_id": "25e6a47dd6b09089555b29d31cac086237668a82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1502,
"license_type": "no_license",
"max_line_length": 160,
"num_lines": 61,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"dynamic.h\"\r\n#include \"domain.h\"\r\n\r\n\r\nclass Repository\r\n{\r\nprivate:\r\n\tVector<Movie> movie;\r\n\tint current;\r\npublic:\r\n\t/*\r\n\tConstructor for repository\r\n\t*/\r\n\tRepository() {}\r\n\t/*\r\n\tAdds a movie to the repository\r\n\tin: the movie\r\n\tout: return true if the movie was added, false otherwise\r\n\t*/\r\n\tbool addMovie(const Movie& m);\r\n\t/*\r\n\tDeletes a movie from the repository by its position\r\n\tin: index\r\n\tout: return true if the movie was deleted, false otherwise\r\n\t*/\r\n\tbool delMovie(const std::string& title);\r\n\t/*\r\n\tUpdates a movie with new stats\r\n\tin: old title, new title, new genre, new year, new likes, new trailer\r\n\tout: return true if the movie was updated, false otherwise\r\n\t*/\r\n\tbool updateMovie(const std::string& oldTitle, const std::string& title, const std::string& genre, const int year, const int likes, const std::string& trailer);\r\n\t/*\r\n\tReturns the movies with a given genre\r\n\tin: genre\r\n\tout: returns the movies that have the given genre\r\n\t*/\r\n\tMovie findByGenre(const std::string& genre);\r\n\t/*\r\n\tReturns the movie that has a specific title\r\n\tin: title\r\n\tout: return movie with the title [title]\r\n\t*/\r\n\tMovie findByTitle(const std::string& title);\r\n\t/*\r\n\tReturns all the movies from the repository\r\n\tout: return all movies\r\n\t*/\r\n\tVector<Movie> getMovies()const { return movie; }\r\n\r\n\tMovie getCurrentM() { return movie[current]; };\r\n\r\n\tvoid setCurrentM() { current = 0; };\r\n\r\n\tvoid nextM();\r\n\r\n\tint findP(const std::string& title);\r\n\r\n\tvoid incLikesMovie(int pos);\r\n};"
},
{
"alpha_fraction": 0.6793248653411865,
"alphanum_fraction": 0.6793248653411865,
"avg_line_length": 19.545454025268555,
"blob_id": "efc0c374b727426f96aa0642445d3a62fcf14bed",
"content_id": "a344aed714d8086b5f549a7c7970c1856e780b31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 239,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Exceptions/FileAlreadyExists.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Exceptions\r\n{\r\n public class FileAlreadyExists : Exception\r\n {\r\n public FileAlreadyExists(String msg) : base(msg) { }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.7149876952171326,
"alphanum_fraction": 0.7248157262802124,
"avg_line_length": 22.058822631835938,
"blob_id": "5089daf966722d932e41ade3bed8f46e3a1f3020",
"content_id": "3b000d3d7f064d43ca4f808fcbbd1db6dc5228c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 407,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 17,
"path": "/MyProjects/FP/FP/FP Test 2/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from UI import *\r\nfrom controller import *\r\nfrom CSVRepository import *\r\nfrom repository import *\r\nfrom domain import *\r\nrepo=Repository()\r\nel=Person(1,'nonvaccinated','ill')\r\nrepo.add(el)\r\nel=Person(2,'nonvaccinated','healthy')\r\nrepo.add(el)\r\nel=Person(3,'vaccinated','healthy')\r\nrepo.add(el)\r\nel=Person(4,'nonvaccinated','healthy')\r\nrepo.add(el)\r\ncontroller=Controller(repo)\r\nui=UI(controller)\r\nui.start()"
},
{
"alpha_fraction": 0.5687204003334045,
"alphanum_fraction": 0.5687204003334045,
"avg_line_length": 25.672130584716797,
"blob_id": "4d2bc26dd4aa826fb2c11a7662174e9be08421a8",
"content_id": "c7f1f2206250ac6d238a598801b95ad6467bde20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1688,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 61,
"path": "/MyProjects/MAP/Practical Exam/Cyclic Barrier/src/Model/Statements/AwaitStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Expressions.VarExpr;\r\nimport Model.Pair;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\nimport Exception.VariableNotDefined;\r\n\r\nimport java.util.List;\r\n\r\npublic class AwaitStmt implements IStmt {\r\n private String var;\r\n\r\n public AwaitStmt(String s){var=s;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer, Pair> barrier=state.getBarrier();\r\n IStack<IStmt> stack=state.getStack();\r\n if(!dic.exists(var)) throw new VariableNotDefined(\"Variable '\"+var+\"' does not exist in the Symbol Table!\");\r\n IExpr e=new VarExpr(var);\r\n Integer ev=e.evaluate(dic,heap);\r\n\r\n if(!barrier.exists(ev)) throw new VariableNotDefined(\"Index not found in the Barrier Table!\");\r\n\r\n Pair p=barrier.getValue(ev);\r\n Integer len=p.list.size();\r\n Integer n=p.nr;\r\n Integer id=state.getID();\r\n\r\n state.getMylock().lock();\r\n boolean yes=false;\r\n for(Integer i:p.list)\r\n if(i.equals(id)){\r\n yes=true;\r\n break;\r\n }\r\n\r\n\r\n if(n>len){\r\n if(yes){\r\n stack.add(this);\r\n }\r\n else\r\n {\r\n p.list.add(id);\r\n stack.add(this);\r\n }\r\n }\r\n state.getMylock().unlock();\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"await(\"+var+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5835987329483032,
"alphanum_fraction": 0.5839968323707581,
"avg_line_length": 31.052631378173828,
"blob_id": "617cda4fc9b5d68bf9e876eaf16a69397815ad5c",
"content_id": "6e6c1a69bc62d007e13e28d21957b36574af3ef1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2512,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 76,
"path": "/MyProjects/MAP/Assignment 2/src/Controller/Controller.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Controller;\r\n\r\nimport Model.ProgramState;\r\nimport Model.Statements.IStmt;\r\nimport Model.Utilities.Dictionary;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\nimport Repository.IRepo;\r\nimport Exception.EmptyStack;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.util.Collection;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.stream.*;\r\n\r\npublic class Controller {\r\n private IRepo repo;\r\n\r\n public Controller(IRepo repo) {\r\n this.repo = repo;\r\n }\r\n\r\n public ProgramState oneStep(ProgramState state){\r\n try{\r\n IStack<IStmt> stack = state.getStack();\r\n if(stack.isEmpty())\r\n throw new EmptyStack(\"The stack is empty!\");\r\n IStmt currentStmt = stack.pop();\r\n return currentStmt.execute(state);}\r\n catch (IOException e){\r\n System.out.println(e.getMessage());\r\n System.exit(0);\r\n }\r\n return null;\r\n }\r\n public Map<Integer,Integer> conservativeGarbageCollector(List<Integer> symTableValues,\r\n Map<Integer,Integer> heap){\r\n return heap.entrySet().stream()\r\n .filter(e->symTableValues.contains(e.getKey()))\r\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));}\r\n\r\n public ProgramState closeAllOpenFiles(ProgramState prg){\r\n prg.clearFileFromSym();\r\n List<BufferedReader> myList=prg.getFileTable().getValues();\r\n myList.stream().forEach(el->{try{el.close();}catch(IOException e){System.out.println(e.getMessage());}});\r\n prg.clearFileTable();\r\n return prg;\r\n }\r\n\r\n public void allSteps(){\r\n ProgramState prg = repo.getCurrentPrg();\r\n try{\r\n while(!prg.getStack().isEmpty()){\r\n oneStep(prg);\r\n prg.setHeapMap(conservativeGarbageCollector(prg.getSymTable().getValues(),prg.getHeap().getMap()));\r\n this.repo.logProgramStateExec(\"log\");\r\n System.out.println(\"-----------\");\r\n System.out.println(prg);\r\n }}\r\n catch(IOException e){\r\n System.out.println(e.getMessage());\r\n }\r\n finally {\r\n prg=this.closeAllOpenFiles(prg);\r\n System.out.println(\"-----------\");\r\n System.out.println(prg);\r\n }\r\n }\r\n\r\n @Override\r\n public String toString(){\r\n return \"Controller: \" + repo.toString();\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5908256769180298,
"alphanum_fraction": 0.5908256769180298,
"avg_line_length": 26.789474487304688,
"blob_id": "fa21c6f2669a4449274312b1315ab59814bf7ad4",
"content_id": "d6056a31ade51c6fec12aaedabc8c46907a89ad2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 545,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/domain.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Student {\r\nprivate:\r\n\tint id;\r\n\tstd::string name;\r\n\tint age;\r\npublic:\r\n\tStudent() :id(), name(\"\"), age() {}\r\n\tStudent(int _id, std::string _name, int _age) :id{ _id }, name{ _name }, age{ _age } { }\r\n\tint getID() { return id; };\r\n\tstd::string getName() { return name; }\r\n\tint getAge() { return age; }\r\n\tvoid setName(std::string name);\r\n\tvoid setAge(int age);\r\n\tbool operator==(Student s) { return (s.id == this->id && s.name == this->name && s.age == this->age); }\r\n\tvirtual std::string overString();\r\n};"
},
{
"alpha_fraction": 0.6820083856582642,
"alphanum_fraction": 0.6820083856582642,
"avg_line_length": 19.727272033691406,
"blob_id": "96538ac31462b260fb49f82c1e7184911a4571f6",
"content_id": "a960f3f62091c08e2226e7706c3b2f2964119018",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 241,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Exceptions/VariableNotDefined.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Exceptions\r\n{\r\n public class VariableNotDefined : Exception\r\n {\r\n public VariableNotDefined(String msg) : base(msg) { }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.645892322063446,
"alphanum_fraction": 0.645892322063446,
"avg_line_length": 27.58333396911621,
"blob_id": "ba0836cbd1898e06fc45df441ba8a5dacf478deb",
"content_id": "c20eec2aabb492ba055e7d39fb257a44d99ee05d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 353,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 12,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/gamer.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n\r\nclass Gamer :public Student {\r\nprivate:\r\n\tstd::string game;\r\npublic:\r\n\tGamer(std::string _game, int _id, std::string _name, int _age) :Student{ _id,_name,_age }, game{ _game } {}\r\n\tstd::string getGame() { return game; }\r\n\tvoid setGame(std::string game) { this->game = game; }\r\n\tstd::string overString() override;\r\n};"
},
{
"alpha_fraction": 0.5748987793922424,
"alphanum_fraction": 0.5789473652839661,
"avg_line_length": 15.642857551574707,
"blob_id": "6650173dbdbc4177f66bb7a06ff473db6e1a896e",
"content_id": "5768018fd12d133ff7211b0111ae9b56144cb32b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 494,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 28,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/AstroRepo.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"AstroRepo.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nvoid AstroRepo::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tstring f, n;\r\n\t\tdouble p, lo;\r\n\t\tf = v[0];\r\n\t\tn = v[1];\r\n\t\tAstronomer m{ f,n };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n"
},
{
"alpha_fraction": 0.6441000699996948,
"alphanum_fraction": 0.6517128944396973,
"avg_line_length": 30.839284896850586,
"blob_id": "c74bf6eb9d3be679022aeba02df7d75d8f4c7fd0",
"content_id": "2c10f71b318f188e2b9228227ec2cfbab879519b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3678,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 112,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/GeneratedFiles/ui_Time.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'Time.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_TIME_H\r\n#define UI_TIME_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_TimeClass\r\n{\r\npublic:\r\n QWidget *centralWidget;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *label;\r\n QListWidget *listWidget;\r\n QLabel *ShowLabel;\r\n QHBoxLayout *horizontalLayout;\r\n QLineEdit *lineEdit;\r\n QPushButton *pushButton;\r\n\r\n void setupUi(QMainWindow *TimeClass)\r\n {\r\n if (TimeClass->objectName().isEmpty())\r\n TimeClass->setObjectName(QStringLiteral(\"TimeClass\"));\r\n TimeClass->resize(599, 394);\r\n centralWidget = new QWidget(TimeClass);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n horizontalLayout_2 = new QHBoxLayout(centralWidget);\r\n horizontalLayout_2->setSpacing(6);\r\n horizontalLayout_2->setContentsMargins(11, 11, 11, 11);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setSpacing(6);\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n label = new QLabel(centralWidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout->addWidget(label);\r\n\r\n listWidget = new QListWidget(centralWidget);\r\n listWidget->setObjectName(QStringLiteral(\"listWidget\"));\r\n\r\n verticalLayout->addWidget(listWidget);\r\n\r\n ShowLabel = new QLabel(centralWidget);\r\n ShowLabel->setObjectName(QStringLiteral(\"ShowLabel\"));\r\n\r\n verticalLayout->addWidget(ShowLabel);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setSpacing(6);\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n lineEdit = new QLineEdit(centralWidget);\r\n lineEdit->setObjectName(QStringLiteral(\"lineEdit\"));\r\n\r\n horizontalLayout->addWidget(lineEdit);\r\n\r\n pushButton = new QPushButton(centralWidget);\r\n pushButton->setObjectName(QStringLiteral(\"pushButton\"));\r\n\r\n horizontalLayout->addWidget(pushButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout);\r\n\r\n TimeClass->setCentralWidget(centralWidget);\r\n\r\n retranslateUi(TimeClass);\r\n\r\n QMetaObject::connectSlotsByName(TimeClass);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *TimeClass)\r\n {\r\n TimeClass->setWindowTitle(QApplication::translate(\"TimeClass\", \"Time\", nullptr));\r\n label->setText(QApplication::translate(\"TimeClass\", \"Tasks:\", nullptr));\r\n ShowLabel->setText(QString());\r\n pushButton->setText(QApplication::translate(\"TimeClass\", \"Show duration\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class TimeClass: public Ui_TimeClass {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_TIME_H\r\n"
},
{
"alpha_fraction": 0.4386381506919861,
"alphanum_fraction": 0.4687252640724182,
"avg_line_length": 23.816326141357422,
"blob_id": "7566a525378347252a5ae639a671cd294687f696",
"content_id": "49d902abd2b62e70dc73de05918f08ff03258d62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1263,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 49,
"path": "/MyProjects/Graphs/Graphs/Graph 4 python/threadsMy.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from _thread import *\r\n\r\nimport socket\r\nimport struct\r\n\r\ndef common(a1,a2):\r\n l=[]\r\n for i in a1:\r\n for j in a2:\r\n if i==j:\r\n l.append(i)\r\n break\r\n return l\r\n\r\nmySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nmySocket.bind(('127.0.0.1', 1234))\r\nmySocket.listen(10)\r\n\r\ndef clientthread(conn):\r\n a1 = []\r\n a2 = []\r\n while True:\r\n data = conn.recv(2)\r\n data = struct.unpack('!H', data)\r\n l1 = data[0]\r\n for i in range(l1):\r\n data = conn.recv(2)\r\n data = struct.unpack('!H', data)\r\n a1.append(data[0])\r\n data = conn.recv(2)\r\n data = struct.unpack('!H', data)\r\n l2 = data[0]\r\n for i in range(l2):\r\n data = conn.recv(2)\r\n data = struct.unpack('!H', data)\r\n a2.append(data[0])\r\n a3 = common(a1, a2)\r\n print('Data recieved and transfered back!')\r\n conn.send(struct.pack('!H', len(a3)))\r\n for i in a3:\r\n conn.send(struct.pack('!H', i))\r\n conn.close()\r\n\r\nwhile 1:\r\n conn, addr = mySocket.accept()\r\n\r\n start_new_thread(clientthread, (conn,))\r\n\r\nmySocket.close()"
},
{
"alpha_fraction": 0.6656976938247681,
"alphanum_fraction": 0.6656976938247681,
"avg_line_length": 17.16666603088379,
"blob_id": "745bdb3b5b0516658baa96d1a26846d6128c5e9c",
"content_id": "579ffcedac07f9cf25567907e87774c7cc0188b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 688,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 36,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Mode.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets\\QMainWindow>\r\n#include \"ui_mode.h\"\r\n#include \"controller.h\"\r\n#include \"Admin.h\"\r\n#include \"User.h\"\r\n#include \"password.h\"\r\n#include \"view.h\"\r\n#include \"table.h\"\r\n\r\nclass Mode :public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tMode(Admin &a,User &u,Repository &r,Repository &l, QWidget *parent = Q_NULLPTR);\r\n\t~Mode() { delete this->table; }\r\nprivate:\r\n\tUi::ModeWindow ui;\r\n\tAdmin *adm;\r\n\tUser *usr;\r\n\tView *table;\r\n\tRepository &r;\r\n\tRepository &l;\r\n\tPassword password;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid setAdmin(Admin &a);\r\n\tvoid setUser(User &u);\r\n\tprivate slots:\r\n\tvoid AdminMode();\r\n\tvoid UserMode();\r\n\tvoid passwordShow();\r\n\tvoid viewAll();\r\n};"
},
{
"alpha_fraction": 0.60550457239151,
"alphanum_fraction": 0.6605504751205444,
"avg_line_length": 13.571428298950195,
"blob_id": "45703d6f547d23e3096c00a312446b7f6c718e13",
"content_id": "93e268572535e4546af516d2cd8ada7a5ed840cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 109,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Again12.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Again12.h\"\r\n\r\nAgain12::Again12(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.659652054309845,
"alphanum_fraction": 0.6638608574867249,
"avg_line_length": 31.62264060974121,
"blob_id": "60653972a28b51b14b021831364097d664970f2c",
"content_id": "ed66f58c0e18d2815e562675a15ee3dfb6760223",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3564,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 106,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/GeneratedFiles/ui_OtherWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'OtherWindow.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_OTHERWINDOW_H\r\n#define UI_OTHERWINDOW_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QStatusBar>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_OtherWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *label;\r\n QListWidget *StudentList;\r\n QHBoxLayout *horizontalLayout;\r\n QLineEdit *GradeLine;\r\n QPushButton *GradeButton;\r\n QStatusBar *statusbar;\r\n\r\n void setupUi(QMainWindow *OtherWindow)\r\n {\r\n if (OtherWindow->objectName().isEmpty())\r\n OtherWindow->setObjectName(QStringLiteral(\"OtherWindow\"));\r\n OtherWindow->resize(573, 381);\r\n centralwidget = new QWidget(OtherWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout_2 = new QHBoxLayout(centralwidget);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n label = new QLabel(centralwidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout->addWidget(label);\r\n\r\n StudentList = new QListWidget(centralwidget);\r\n StudentList->setObjectName(QStringLiteral(\"StudentList\"));\r\n\r\n verticalLayout->addWidget(StudentList);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n GradeLine = new QLineEdit(centralwidget);\r\n GradeLine->setObjectName(QStringLiteral(\"GradeLine\"));\r\n\r\n horizontalLayout->addWidget(GradeLine);\r\n\r\n GradeButton = new QPushButton(centralwidget);\r\n GradeButton->setObjectName(QStringLiteral(\"GradeButton\"));\r\n\r\n horizontalLayout->addWidget(GradeButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout);\r\n\r\n OtherWindow->setCentralWidget(centralwidget);\r\n statusbar = new QStatusBar(OtherWindow);\r\n statusbar->setObjectName(QStringLiteral(\"statusbar\"));\r\n OtherWindow->setStatusBar(statusbar);\r\n\r\n retranslateUi(OtherWindow);\r\n\r\n QMetaObject::connectSlotsByName(OtherWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *OtherWindow)\r\n {\r\n OtherWindow->setWindowTitle(QApplication::translate(\"OtherWindow\", \"TeacherWindow\", nullptr));\r\n label->setText(QApplication::translate(\"OtherWindow\", \"Students:\", nullptr));\r\n GradeButton->setText(QApplication::translate(\"OtherWindow\", \"Grade\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class OtherWindow: public Ui_OtherWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_OTHERWINDOW_H\r\n"
},
{
"alpha_fraction": 0.6005733609199524,
"alphanum_fraction": 0.6082178950309753,
"avg_line_length": 18.93000030517578,
"blob_id": "311f6f6267bd7b00a7ee8be10fa953084a910ec8",
"content_id": "70a1e55cafcc2736fff8e8116d8c05c82ec7adcb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2093,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 100,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/studentRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"student.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass StudentRepo :public Repository<T>\r\n{\r\npublic:\r\n\tStudentRepo(std::string filename) :Repository<T>(filename) { this->readFromFile(); this->sorted(); }\r\n\tStudentRepo() :Repository<T>() {}\r\n\t~StudentRepo() {}\r\n\r\n\tvoid writeToFile() override;\r\n\tvoid readFromFile() override;\r\n\r\n\tvoid sorted() override;\r\n\r\n\tvoid setGrade(int pos, double gr) { elems[pos].setGrade(gr); }\r\n\tstd::vector<T> getByGroups(std::vector<int> gr);\r\n\r\n\tint findByID(int id) override\r\n\t{\r\n\t\tfor (int i = 0;this->elems.size();i++)\r\n\t\t\tif (i.getID() == id)\r\n\t\t\t\treturn i;\r\n\t\treturn -1;\r\n\t}\r\n};\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tint id, group;\r\n\t\tstd::string name, teacher;\r\n\t\tdouble grade;\r\n\t\tid = stoi(v[0]);\r\n\t\tname = v[1];\r\n\t\tgroup = stoi(v[2]);\r\n\t\tgrade = stod(v[3]);\r\n\t\tteacher = v[4];\r\n\t\tStudent m{ id,name,group,grade,teacher };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\ntemplate <typename T>\r\nbool cmp(const T & e1, const T & e2) {\r\n\tif (e1.group != e2.group)\r\n\t\treturn (e1.group < e2.group);\r\n\treturn (e1.name < e2.name);\r\n}\r\n\r\ntemplate<typename T>\r\ninline void StudentRepo<T>::sorted()\r\n{\r\n\tsort(this->elems.begin(), this->elems.end(), cmp);\r\n}\r\n\r\ntemplate<typename T>\r\ninline std::vector<T> StudentRepo<T>::getByGroups(std::vector<int> gr)\r\n{\r\n\tstd::vector<T> vec;\r\n\tfor (auto i : elems)\r\n\t\tfor (auto j : gr)\r\n\t\t\tif (i.getGroup() == j)\r\n\t\t\t{\r\n\t\t\t\tvec.push_back(i);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\treturn vec;\r\n}\r\n"
},
{
"alpha_fraction": 0.61524498462677,
"alphanum_fraction": 0.61524498462677,
"avg_line_length": 16.433332443237305,
"blob_id": "05b155459b17611d620c168d9dfbb74e15aeb6c4",
"content_id": "730a58516f0ea9d6bc001cd470ef1d2d69a84e65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 551,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 30,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/StarRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include \"star.h\"\r\n#include <vector>\r\n\r\n\r\nclass StarRepo\r\n{\r\nprivate:\r\n\tstd::vector<Star> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tStarRepo() :filename{ \"\" } {}\r\n\tStarRepo(std::string n) :filename{ n } { this->readFromFile(); }\r\n\t~StarRepo() {}\r\n\r\n\tvoid readFromFile();\r\n\tvoid writeToFile();\r\n\r\n\tvoid add(Star e) { elems.push_back(e); }\r\n\r\n\tstd::vector<Star> filter(std::string co);\r\n\r\n\tstd::vector<Star> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\r\n\r\n\tStar operator[](int pos) { return elems[pos]; }\r\n\r\n};"
},
{
"alpha_fraction": 0.5989795923233032,
"alphanum_fraction": 0.6030611991882324,
"avg_line_length": 19.07526969909668,
"blob_id": "a0aa96f3c77566f46a65940011215699ef923a7a",
"content_id": "ae3e47de08ff28b494596750017000529c66a25b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1960,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 93,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <assert.h>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nbool Repository::addMovie(const Movie & m)\r\n{\r\n\tMovie* mo = this->movie.getAll();\r\n\tfor (int i = 0;i < this->movie.getLenght();i++)\r\n\t\tif (mo[i].getTitle() == m.getTitle())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\tthis->movie =m+ this->movie;\r\n\treturn true;\r\n}\r\n\r\nbool Repository::delMovie(const string & title)\r\n{\r\n\tMovie* mo = this->movie.getAll();\r\n\tfor (int i = 0;i < this->movie.getLenght();i++)\r\n\t\tif (mo[i].getTitle() == title)\r\n\t\t{\r\n\t\t\tthis->movie.del(i);\r\n\t\t\treturn true;\r\n\t\t}\r\n\treturn false;\r\n}\r\n\r\nbool Repository::updateMovie(const string & oldTitle, const string & title, const string & genre, const int year, const int likes, const string & trailer)\r\n{\r\n\tMovie m = findByTitle(oldTitle);\r\n\tif (m.getTitle() == \"\")\r\n\t\treturn false;\r\n\tdelMovie(oldTitle);\r\n\tMovie mov{ title,genre,year,likes,trailer };\r\n\taddMovie(mov);\r\n\treturn true;\r\n}\r\n\r\nMovie Repository::findByGenre(const string & genre)\r\n{\r\n\tMovie* m = this->movie.getAll();\r\n\tif (m == NULL)\r\n\t\treturn Movie{};\r\n\r\n\tfor (int i = 0;i < this->movie.getLenght();i++)\r\n\t{\r\n\t\tMovie mo = m[i];\r\n\t\tif (mo.getGenre() == genre)\r\n\t\t\treturn mo;\r\n\t}\r\n\treturn Movie{};\r\n}\r\n\r\nMovie Repository::findByTitle(const string & title)\r\n{\r\n\tMovie* mov = this->movie.getAll();\r\n\tif (mov == NULL)\r\n\t\treturn Movie{};\r\n\r\n\tfor (int i = 0; i < this->movie.getLenght(); i++) {\r\n\t\tMovie m = mov[i];\r\n\t\tif (m.getTitle() == title)\r\n\t\t\treturn m;\r\n\t}\r\n\treturn Movie{};\r\n}\r\n\r\nvoid Repository::nextM()\r\n{\r\n\tif (this->current == this->movie.getLenght())\r\n\t\tthis->current = 0;\r\n\tif (this->movie.getLenght() == 0)\r\n\t\treturn;\r\n\tMovie m = this->getCurrentM();\r\n\tm.video();\r\n\tthis->current++;\r\n}\r\n\r\nint Repository::findP(const std::string & title)\r\n{\r\n\tfor (int i = 0;i < this->movie.getLenght();i++)\r\n\t\tif (this->movie.get(i).getTitle() == title)\r\n\t\t\treturn i;\r\n\treturn -1;\r\n}\r\n\r\nvoid Repository::incLikesMovie(int pos)\r\n{\r\n\tthis->movie.incLikes(pos);\r\n}\r\n"
},
{
"alpha_fraction": 0.6462264060974121,
"alphanum_fraction": 0.6462264060974121,
"avg_line_length": 17.454545974731445,
"blob_id": "622e6ee98915875fb13065b92d4ead1e85f6400e",
"content_id": "67ae8b21aa826c72bbead7b484002b887899f89a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 11,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/domain.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"domain.h\"\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nConcert::Concert() :band(\"\"), likes() {}\r\n\r\nConcert::Concert(const string band, const int likes)\r\n{\r\n\tthis->band = band;\r\n\tthis->likes = likes;\r\n}"
},
{
"alpha_fraction": 0.4698314070701599,
"alphanum_fraction": 0.4764862358570099,
"avg_line_length": 33.80952453613281,
"blob_id": "fc86ae5b82508dc820304e868d6019dcaf86e660",
"content_id": "19d2ede668813c69390182a415c8f37e328c8505",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2254,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 63,
"path": "/MyProjects/FP/FP/Practice Test 1/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from controller import *\r\nfrom domain import *\r\nfrom repository import *\r\nclass UI:\r\n def __init__(self,driverController=Controller(),orderController=Controller(),incomeController=Controller()):\r\n self.__dc=driverController\r\n self.__oc=orderController\r\n self.__ic=incomeController\r\n def readDriver(self):\r\n x=int(input(\"Enter the driver's id:\"))\r\n y=input(\"Enter the driver's name:\")\r\n a=Driver(x,y)\r\n return a\r\n def readOrder(self):\r\n x = int(input(\"Enter the driver's id:\"))\r\n y=int(input(\"Enter the distance:\"))\r\n a=Order(x,y)\r\n return a\r\n def printMenu(self):\r\n dMenu=''\r\n dMenu+='The current commands are:\\n'\r\n dMenu+=\"1. Add a driver\\n\"\r\n dMenu+=\"2. Add an order\\n\"\r\n dMenu+=\"3. List the drivers\\n\"\r\n dMenu+=\"4. List the orders\\n\"\r\n dMenu+=\"5. List the income of a driver\\n\"\r\n dMenu+=\"6. Print the income from an order of a driver\\n\"\r\n dMenu+=\"0. Exit\\n\"\r\n dMenu+=\"help\\n\"\r\n print(dMenu)\r\n def start(self):\r\n self.printMenu()\r\n while True:\r\n command=input(\"Enter a command:\")\r\n if command=='0':\r\n break\r\n elif command=='help':\r\n self.printMenu()\r\n elif command=='1':\r\n x=self.readDriver()\r\n y=DriverOrders(x.getID())\r\n self.__ic.add(y)\r\n self.__dc.add(x)\r\n elif command=='2':\r\n x=self.readOrder()\r\n y=x.getID()\r\n z=x.getDistance()\r\n self.__ic.addOrder(y,z)\r\n self.__oc.add(x)\r\n elif command=='3':\r\n print(self.__dc)\r\n elif command=='4':\r\n print(self.__oc)\r\n elif command=='5':\r\n x=int(input(\"Enter the driver's id:\"))\r\n y=self.__ic.idIncome(x)\r\n print('The income is: ',y)\r\n elif command=='6':\r\n x=int(input(\"Enter the driver's id:\"))\r\n y=int(input(\"Enter the number of the order:\"))\r\n y=y+1\r\n z=self.__ic.idOderValue(x,y)\r\n print('The income is: ',z)"
},
{
"alpha_fraction": 0.6753246784210205,
"alphanum_fraction": 0.6818181872367859,
"avg_line_length": 21.69230842590332,
"blob_id": "0e50dadceb9e0c20ca5ead2c74eed0da9d595029",
"content_id": "6012112d5729e931888182e08fa8fb74efaee6ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 308,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 13,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/operation.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"operation.h\"\r\n\r\nvoid Operation::push(OperationElement o)\r\n{\r\n\tthis->operation.push_back(o);\r\n}\r\n\r\nOperationElement Operation::pop()\r\n{\r\n\tOperationElement e = this->operation[this->operation.size() - 1];\r\n\tthis->operation.erase(this->operation.begin() + this->operation.size() - 1);\r\n\treturn e;\r\n}\r\n"
},
{
"alpha_fraction": 0.6770538091659546,
"alphanum_fraction": 0.6770538091659546,
"avg_line_length": 21.66666603088379,
"blob_id": "5ab498d17bc7702bc359807ff9ef708512f1d24e",
"content_id": "595082ada3a831f03d7193b30b5f1eca6364a173",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 353,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 15,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"Repository.h\"\r\n\r\nclass Controller {\r\nprivate:\r\n\tRepository repo;\r\npublic:\r\n\tController(const Repository& r) :repo{ r } {}\r\n\tRepository getRepo() { return repo; }\r\n\tint findByName(std::string name);\r\n\tint findbyID(int id);\r\n\tbool add(Pilot p);\r\n\tbool del(int id);\r\n\tbool update(int id, std::string name, int age, int flights);\r\n};"
},
{
"alpha_fraction": 0.6814159154891968,
"alphanum_fraction": 0.6814159154891968,
"avg_line_length": 18.545454025268555,
"blob_id": "569815a306145432503332bc155408ac277ad953",
"content_id": "d6be3e15771db2a551c27d4e3ede89336625a211",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 228,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Expressions/IExpr.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Expressions\r\n{\r\n public interface IExpr\r\n {\r\n int evaluate(Utilities.IDictionary<string , int> dic);\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6007905006408691,
"alphanum_fraction": 0.6007905006408691,
"avg_line_length": 21,
"blob_id": "a39894aec7abc2dc53327532079f6cd525105967",
"content_id": "b6d93e853151e4ddfa1c47021c03e209bbc29a7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 253,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 11,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Domain.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Domain.h\"\r\n\r\nPilot::Pilot() :name(\"\"), age(), flights(), id() {}\r\n\r\nPilot::Pilot(const std::string name, const int age, const int flights,const int id)\r\n{\r\n\tthis->name = name;\r\n\tthis->age = age;\r\n\tthis->flights = flights;\r\n\tthis->id = id;\r\n}\r\n"
},
{
"alpha_fraction": 0.6676136255264282,
"alphanum_fraction": 0.6676136255264282,
"avg_line_length": 16.526315689086914,
"blob_id": "7690de5e095d4b17ca67860670ac37d5638ad1a5",
"content_id": "c13aa5c705f324f0455b312f35e7ef9b3127ab46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 352,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\nvoid Controller::startTask(int pos, int id,std::string n)\r\n{\r\n\ttasks.setThisProgress(pos);\r\n\ttasks.setThisID(pos, id,n);\r\n}\r\n\r\nvoid Controller::finishTask(int pos)\r\n{\r\n\ttasks.setThisClosed(pos);\r\n}\r\n\r\nController & Controller::operator=(Controller & c)\r\n{\r\n\tthis->progs = c.progs;\r\n\tthis->tasks = c.tasks;\r\n\treturn *this;\r\n}\r\n"
},
{
"alpha_fraction": 0.5586510300636292,
"alphanum_fraction": 0.5623167157173157,
"avg_line_length": 14.2380952835083,
"blob_id": "3a1754cb1a559e90940a7874e9fd8ba52b924b08",
"content_id": "bac6e2048f4583ba21fe03ead059ded6463e48ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1364,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 84,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/dynamic.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"dynamic.h\"\r\n\r\nVector::Vector(int cap)\r\n{\r\n\tthis->len = 0;\r\n\tthis->cap = cap;\r\n\tthis->elems = new TElement[cap];\r\n}\r\n\r\nVector::Vector(const Vector & v)\r\n{\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t{\r\n\t\tthis->elems[i] = v.elems[i];\r\n\t}\r\n}\r\n\r\nVector::~Vector()\r\n{\r\n\tdelete[] this->elems;\r\n}\r\n\r\nVector & Vector::operator=(const Vector & v)\r\n{\r\n\tif (this == &v)\r\n\t\treturn *this;\r\n\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\tthis->elems[i] = v.elems[i];\r\n\r\n\treturn *this;\r\n}\r\n\r\nTElement & Vector::operator[](int pos)\r\n{\r\n\treturn this->elems[pos];\r\n}\r\n\r\n\r\n\r\nvoid Vector::add(const TElement & e)\r\n{\r\n\tif (this->len == this->cap)\r\n\t\tthis->resize();\r\n\tthis->elems[this->len] = e;\r\n\tthis->len++;\r\n}\r\n\r\nint Vector::getLenght() const\r\n{\r\n\treturn this->len;\r\n}\r\n\r\nPlayer Vector::get(int pos)\r\n{\r\n\tif (pos < 0 || pos >= this->getLenght())\r\n\t\treturn Player{};\r\n\treturn this->elems[pos];\r\n}\r\n\r\nTElement * Vector::getAll() const\r\n{\r\n\treturn this->elems;\r\n}\r\n\r\nvoid Vector::resize(int times)\r\n{\r\n\tthis->cap *= static_cast<int>(times);\r\n\r\n\tTElement* e = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\te[i] = this->elems[i];\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n}\r\n"
},
{
"alpha_fraction": 0.5534759163856506,
"alphanum_fraction": 0.5588235259056091,
"avg_line_length": 15.809523582458496,
"blob_id": "dbd27cd908035371563692ece3bd98cc6345ceba",
"content_id": "cbc02e6f06b9e118c84662758eedf0feb2b6b5b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 374,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/teacher.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"teacher.h\"\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Teacher::toString()\r\n{\r\n\tint i;\r\n\tstringstream buff;\r\n\tbuff << \"Name: \" << name << \"; Groups: \";\r\n\tfor (i = 0;i < groups.size() - 1;i++)\r\n\t\tbuff << groups[i] << \", \";\r\n\tbuff << groups[i];\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Teacher::stri()\r\n{\r\n\treturn std::string();\r\n}\r\n"
},
{
"alpha_fraction": 0.6585186719894409,
"alphanum_fraction": 0.6668296456336975,
"avg_line_length": 32.669490814208984,
"blob_id": "4c98b85c20a725cd4c42dd68f706cc9e14f77cce",
"content_id": "106e46fba6ddc47dde562dc714572059f63b1a86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4091,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 118,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/GeneratedFiles/ui_Vegetables.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'Vegetables.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_VEGETABLES_H\r\n#define UI_VEGETABLES_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_VegetablesWindow\r\n{\r\npublic:\r\n QWidget *centralWidget;\r\n QHBoxLayout *horizontalLayout_2;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *label_2;\r\n QListWidget *FamilyList;\r\n QHBoxLayout *horizontalLayout;\r\n QLineEdit *lineEdit;\r\n QPushButton *pushButton;\r\n QLabel *label;\r\n QListWidget *VegetableList;\r\n\r\n void setupUi(QMainWindow *VegetablesWindow)\r\n {\r\n if (VegetablesWindow->objectName().isEmpty())\r\n VegetablesWindow->setObjectName(QStringLiteral(\"VegetablesWindow\"));\r\n VegetablesWindow->resize(552, 282);\r\n centralWidget = new QWidget(VegetablesWindow);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n horizontalLayout_2 = new QHBoxLayout(centralWidget);\r\n horizontalLayout_2->setSpacing(6);\r\n horizontalLayout_2->setContentsMargins(11, 11, 11, 11);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setSpacing(6);\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n label_2 = new QLabel(centralWidget);\r\n label_2->setObjectName(QStringLiteral(\"label_2\"));\r\n\r\n verticalLayout->addWidget(label_2);\r\n\r\n FamilyList = new QListWidget(centralWidget);\r\n FamilyList->setObjectName(QStringLiteral(\"FamilyList\"));\r\n\r\n verticalLayout->addWidget(FamilyList);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setSpacing(6);\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n lineEdit = new QLineEdit(centralWidget);\r\n lineEdit->setObjectName(QStringLiteral(\"lineEdit\"));\r\n\r\n horizontalLayout->addWidget(lineEdit);\r\n\r\n pushButton = new QPushButton(centralWidget);\r\n pushButton->setObjectName(QStringLiteral(\"pushButton\"));\r\n\r\n horizontalLayout->addWidget(pushButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n label = new QLabel(centralWidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout->addWidget(label);\r\n\r\n VegetableList = new QListWidget(centralWidget);\r\n VegetableList->setObjectName(QStringLiteral(\"VegetableList\"));\r\n\r\n verticalLayout->addWidget(VegetableList);\r\n\r\n\r\n horizontalLayout_2->addLayout(verticalLayout);\r\n\r\n VegetablesWindow->setCentralWidget(centralWidget);\r\n\r\n retranslateUi(VegetablesWindow);\r\n\r\n QMetaObject::connectSlotsByName(VegetablesWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *VegetablesWindow)\r\n {\r\n VegetablesWindow->setWindowTitle(QApplication::translate(\"VegetablesWindow\", \"Veggies\", nullptr));\r\n label_2->setText(QApplication::translate(\"VegetablesWindow\", \"Family list:\", nullptr));\r\n pushButton->setText(QApplication::translate(\"VegetablesWindow\", \"Search\", nullptr));\r\n label->setText(QApplication::translate(\"VegetablesWindow\", \"Vegetables list:\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class VegetablesWindow: public Ui_VegetablesWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_VEGETABLES_H\r\n"
},
{
"alpha_fraction": 0.691374659538269,
"alphanum_fraction": 0.691374659538269,
"avg_line_length": 26.538461685180664,
"blob_id": "e70760a6317506f500d88ed7188b1eebcdb5b9e8",
"content_id": "1df4b955bed6b19919bd9abc50a82a8d6f7809af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"studentRepo.h\"\r\n#include \"teacherRepo.h\"\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tStudentRepo<Student>& students;\r\n\tTeacherRepo<Teacher>& teachers;\r\npublic:\r\n\tController(StudentRepo<Student>& st, TeacherRepo<Teacher>& te) :students{ st }, teachers{ te } {}\r\n\t~Controller() {}\r\n\r\n\tStudentRepo<Student>& getStudents() { return students; }\r\n\tTeacherRepo<Teacher>& getTeachers() { return teachers; }\r\n\tstd::vector<std::string> getTeachersNames();\r\n\r\n\tvoid addStudent(Student s) { students.add(s); }\r\n\tvoid delStudent(int pos) { students.del(pos); }\r\n\tstd::vector<int> getTeacherGroups(std::string name);\r\n\r\n\tvoid saveStudents() { students.writeToFile(); }\r\n\tvoid sortMe() { this->students.sortMe(); }\r\n\r\n\tint getValidID();\r\n};\r\n"
},
{
"alpha_fraction": 0.5471406579017639,
"alphanum_fraction": 0.5471406579017639,
"avg_line_length": 19.566667556762695,
"blob_id": "517b002341fb4e54d99b8ace018808c510917b51",
"content_id": "5fa89c6eeb8249fdd2a9053bec555c665f321009",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 649,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 30,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/PrintStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model.Expressions;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class PrintStmt:IStmt\r\n {\r\n\r\n private IExpr expr;\r\n\r\n public PrintStmt(IExpr expression)\r\n {\r\n expr = expression;\r\n }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n int val = expr.evaluate(state.SymbolTable);\r\n state.Output.add(val);\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"print(\" + expr + \")\";\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6653061509132385,
"alphanum_fraction": 0.6653061509132385,
"avg_line_length": 13.4375,
"blob_id": "ec84d6c865e6756de8fe24c85f2887e180c86907",
"content_id": "cc29865077ba9a5a7c2cbfea6676f6ddea5c50e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 16,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/UI.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"controller.h\"\r\n\r\nclass UI\r\n{\r\nprivate:\r\n\tController controller;\r\npublic:\r\n\tUI(const Controller& c) :controller(c) {}\r\n\r\n\tvoid start();\r\n\tvoid printRepo();\r\n\tvoid addMovieToRepo();\r\nprivate:\r\n\tstatic void printMenu();\t\r\n};"
},
{
"alpha_fraction": 0.5403226017951965,
"alphanum_fraction": 0.5833333134651184,
"avg_line_length": 26.11320686340332,
"blob_id": "4869e80b8e99875b6c3638682319113a5db3a709",
"content_id": "d76be5d189f5921c7dc3d9e3b38a8c9391b8e26e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1488,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 53,
"path": "/MyProjects/OOP/OOP/Practice 3/New/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include \"controller.h\"\r\n#include \"repository.h\"\r\n#include <crtdbg.h>\r\n#include \"csv.h\"\r\n#include \"watchFile.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\t{\r\n\t\tRepository a{ \"All.txt\" };\r\n\t\tRepository l{ \"List.txt\" };\r\n\t\t/*\r\n\t\tMovie m1{ \"DeadPool\", \"Comedy\", 2016, 1234, \"https://www.youtube.com/watch?v=Xithigfg7dA\" };\r\n\t\tMovie m2{ \"The Greatest Showman\", \"Drama\", 2017, 312, \"https://www.youtube.com/watch?v=AXCTMGYUg9A\" };\r\n\t\tMovie m3{ \"Me Before You\", \"Romance\", 2016, 3534, \"https://www.youtube.com/watch?v=Eh993__rOxA\" };\r\n\t\tMovie m4{ \"The Wolf Of Wall Street\", \"Comedy\", 2013, 43432, \"https://www.youtube.com/watch?v=iszwuX1AK6A\" };\r\n\t\tMovie m5{ \"The Silence of the Lambs\", \"Thriller\", 1991, 324, \"https://www.youtube.com/watch?v=RuX2MQeb8UM\" };\r\n\t\ta.add(m2);\r\n\t\ta.add(m3);\r\n\t\ta.add(m4);\r\n\t\ta.add(m5);\r\n\t\ta.add(m1);\r\n\t\t*/\r\n\t\tController c{ a,l };\r\n\t\twhile (1)\r\n\t\t{\r\n\t\t\tint opt;\r\n\t\t\tcout << \"Input the way that you want to store the data:\" << endl;\r\n\t\t\tcout << \"\\t1. CSV file.\" << endl;\r\n\t\t\tcout << \"\\t2. HTML file.\" << endl;\r\n\t\t\tcout << \"\\t0. Exit\" << endl << \"option: \";\r\n\t\t\tcin >> opt;\r\n\t\t\tif (opt == 0)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t\t// I'll sing the night into the morning\r\n\t\t\t\t// I'll sing my fear into Your praise\r\n\t\t\t\t// I'll sing my soul into Your presence\r\n\t\t\t\t// Whenever I say Your Name\r\n\t\t\t\t// Let the devil know not today\r\n\t\t\t}\r\n\t\t\tcout << endl << endl;\r\n\t\t\tUI ui{ c ,opt };\r\n\t\t\tui.start();\r\n\t\t}\r\n\t}\r\n\t_CrtDumpMemoryLeaks();\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.6780303120613098,
"alphanum_fraction": 0.6780303120613098,
"avg_line_length": 16.85714340209961,
"blob_id": "1152c1a261f5f34961274d52a73ff0da81e565b0",
"content_id": "55fb31d3f7c93c2bce2feeb889fa45aaca73c02d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 266,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 14,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Repository/myRepositorix.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model;\r\n\r\nnamespace Interpreter.Repository\r\n{\r\n public interface myRepositorix\r\n {\r\n ProgramState getCurrentPrgState();\r\n\r\n void logPrgState();\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.4956638514995575,
"alphanum_fraction": 0.49945035576820374,
"avg_line_length": 27.996337890625,
"blob_id": "7089478fc4649fd2367e21931b6c9156f7ce44d7",
"content_id": "485a43d9902df490ac8b58003b942c79eb4e82aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8187,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 273,
"path": "/MyProjects/FP/FP/Assignment 5/controller.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nfrom domain import *\r\nimport unittest\r\nclass Controller:\r\n def __init__(self,repo=Repository()):\r\n self.__repo=repo\r\n def __str__(self):\r\n '''\r\n Returns the string of the controller\r\n :return:\r\n '''\r\n s=''\r\n for i in range(len(self.__repo.getAll())):\r\n s+='['+str(i+1)+']. '+str(self.__repo.get(i))+'\\n'\r\n return s\r\n def __len__(self):\r\n return len(self.__repo.getAll())\r\n def getAll(self):\r\n '''\r\n Returns the repository\r\n :return:\r\n '''\r\n return self.__repo\r\n def get(self,index):\r\n '''\r\n Returns the element from the given index\r\n in:param index:\r\n :return:\r\n '''\r\n return self.__repo.get(index)\r\n def add(self,el):\r\n '''\r\n Adds an element to the controller repository\r\n :return:\r\n '''\r\n self.__repo.add(el)\r\n def remove(self,element):\r\n '''\r\n Removes an element from the controller repository\r\n :param element:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i)==element:\r\n self.__repo.remove(element)\r\n def removeIndex(self,index):\r\n '''\r\n Removes an index from the controller repository\r\n :param index:\r\n :return:\r\n '''\r\n self.__repo.removeIndex(index)\r\n def update(self,old,new):\r\n '''\r\n Updates an element from the controller repo with a new one\r\n in:param old:\r\n in:param new:\r\n :return:\r\n '''\r\n self.__repo.update(old,new)\r\n def findByAssiID(self,id):\r\n '''\r\n Returns the index of the element with the given id, -1 if it doesn't exist\r\n in:param id:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getAssignmentID()==id:\r\n return i\r\n return -1\r\n def findByStuID(self,id):\r\n '''\r\n Returns the index of the element with the given id, -1 if it doesn't exist\r\n in:param id:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getStudentID()==id:\r\n return i\r\n return -1\r\n def groupList(self,group):\r\n '''\r\n Returns a list of the entire group\r\n in:param group:\r\n out:return:lst\r\n '''\r\n lst=self.__repo.groupList(group)\r\n return lst\r\n def giveAssignmentToStudent(self,student,assignment):\r\n '''\r\n Gives an assignment to a student\r\n in:param student:\r\n in:param assignment:\r\n :return:\r\n '''\r\n self.__repo.giveAssignmentToStudent(student,assignment)\r\n def giveAssignmentToGroup(self,group,assignment,lst):\r\n '''\r\n Gives an assignment to an entire group\r\n in:param group:\r\n in:param assignment:\r\n :return:\r\n '''\r\n self.__repo.giveAssignmentToGroup(group,assignment,lst)\r\n def deleteStudentAssignments(self,student):\r\n '''\r\n Deletes the assignments along the student\r\n in:param student:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getStudent()==student:\r\n self.__repo.removeIndex(i)\r\n def findStudent(self,student):\r\n '''\r\n Returns the index of the student, -1 if it is not found\r\n in:param student:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).studentIsFound(student)==True:\r\n return i\r\n return -1\r\n def deleteStudent(self,id):\r\n '''\r\n Deletes the student from the grade repository\r\n in:param student:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getStudentID()==id:\r\n self.__repo.removeIndex(i)\r\n def deleteAssignment(self,id):\r\n '''\r\n Deletes the assignment from the grade repository\r\n in:param assignment:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getAssignmentID()==id:\r\n self.__repo.removeIndex(i)\r\n def assignmentList(self,index):\r\n '''\r\n Returns the list of assignments of an index\r\n in:param index:\r\n :return:\r\n '''\r\n lst=[]\r\n for i in range(len(self.__repo.get(index).getAssignment())):\r\n lst.append(self.__repo.get(index).getAssignmentIndex(i))\r\n return lst\r\n def averageGrade(self,id1,lst):\r\n '''\r\n Returns the average grade, -1 if not all the assignments are graded\r\n in:param student:\r\n in:param lst:\r\n :return:\r\n '''\r\n s=0\r\n for i in range(len(lst)):\r\n id2=lst[i].getAssignmentID()\r\n k=0\r\n for j in range(len(self.__repo.getAll())):\r\n if id1==self.__repo.get(j).getStudentID() and id2==self.__repo.get(j).getAssignmentID():\r\n k=1\r\n s+=self.__repo.get(j).getGrade()\r\n if k==0:\r\n return -1\r\n return s/(len(lst))\r\n def notInTimeID(self):\r\n '''\r\n Returns a list with all the student ids that didn't finish in time\r\n :return:\r\n '''\r\n lst=[]\r\n i=0\r\n while i<len(self.__repo.getAll()):\r\n if self.__repo.get(i).getGrade()==-1:\r\n lst.append(self.__repo.get(i).getStudentID())\r\n i+=1\r\n return lst\r\n def notInTime(self,lst):\r\n '''\r\n Returns a list of all the student that didn't finish in time\r\n in:param lst:\r\n :return:\r\n '''\r\n l=[]\r\n for i in range(len(lst)):\r\n for j in range(len(self.__repo.getAll())):\r\n if self.__repo.get(j).getStudentID()==lst[i]:\r\n l.append(self.__repo.get(i))\r\n return l\r\n def repoList(self):\r\n '''\r\n Returns a list of the repository\r\n :return:\r\n '''\r\n lst=[]\r\n for i in range(len(self.__repo.getAll())):\r\n lst.append(self.__repo.get(i))\r\n return lst\r\n def filterByGrade(self,grade):\r\n '''\r\n Filters the controller so only the grades that are greater or equal than the given grade.\r\n in:param grade:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if self.__repo.get(i).getGrade()<grade:\r\n self.__repo.removeIndex(i)\r\n\r\n\r\n\r\nclass Data:\r\n def __init__(self, data):\r\n self._data = data\r\n self._idx = 0\r\n def __iter__(self):\r\n return self\r\n def __next__(self):\r\n try:\r\n item = self._data[self._idx]\r\n except IndexError:\r\n raise StopIteration()\r\n self._idx += 1\r\n return item\r\n def __setitem__(self, key, value):\r\n self._data[key] = value\r\n def __delitem__(self, key):\r\n del self._data[key]\r\n def __len__(self):\r\n return len(self._data)\r\n def __getitem__(self, idx):\r\n return self._data[idx]\r\n def append(self, value):\r\n self._data.append(value)\r\n\r\ndef sort(myList, key = lambda x: x, reverse = False ):\r\n '''\r\n Gnome sort\r\n :return:\r\n '''\r\n pos = 0\r\n while pos < len(myList):\r\n if pos == 0 or key(myList[pos]) >= key(myList[pos - 1]):\r\n pos = pos + 1\r\n else:\r\n myList[pos], myList[pos - 1] = myList[pos - 1], myList[pos]\r\n pos = pos - 1\r\n if reverse == True:\r\n myList = reversed(myList)\r\n\r\n return myList\r\n\r\ndef filter(myList, condition):\r\n '''\r\n myList is an iterable data structure\r\n condition is a function\r\n :param myList:\r\n :param condition:\r\n :return:\r\n '''\r\n result = []\r\n for i in myList:\r\n if condition(i):\r\n result.append(i)\r\n return result\r\n\r\ndef test(item):\r\n if item % 2 == 0:\r\n return True\r\n return False"
},
{
"alpha_fraction": 0.6332703232765198,
"alphanum_fraction": 0.6332703232765198,
"avg_line_length": 24.450000762939453,
"blob_id": "ba89f148bc6494ed1fc73508e493890f14ff87b1",
"content_id": "3a4bbd82e0e2dfb0a5441ca8d04538211f7c3fdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 529,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/domain.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"domain.h\"\r\n#include <Windows.h>\r\n#include <shellapi.h>\r\n\r\nusing namespace std;\r\nMovie::Movie() : title(\"\"), genre(\"\"), year(), likes(), trailer(\"\") {}\r\n\r\nMovie::Movie(const string & title, const string & genre, const int & year, const int & likes, const string & trailer)\r\n{\r\n\tthis->title = title;\r\n\tthis->genre = genre;\r\n\tthis->year = year;\r\n\tthis->likes = likes;\r\n\tthis->trailer = trailer;\r\n}\r\n\r\nvoid Movie::video()\r\n{\r\n\tShellExecute(NULL, NULL, \"chrome.exe\", this->getTrailer().c_str(), NULL, SW_SHOWMAXIMIZED);\r\n}\r\n"
},
{
"alpha_fraction": 0.5903614163398743,
"alphanum_fraction": 0.5903614163398743,
"avg_line_length": 15.473684310913086,
"blob_id": "d8806ff86bbaa321f75c2107d6ebf340198df6ad",
"content_id": "8bdb216e8996fe68c422ec30a50d006061b1c81b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 332,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/programmer.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"programmer.h\"\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Programmer::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"ID: \" << id << \", Name: \" << name;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Programmer::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << id << \",\" << name;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.599179208278656,
"alphanum_fraction": 0.600547194480896,
"avg_line_length": 24.178571701049805,
"blob_id": "f56c750b0d8e453012b05d872a4cd2860971d7d0",
"content_id": "31713d675f2cfc9b02c6df7f23b9a6ee6666a730",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 731,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 28,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/redo.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"redo.h\"\r\n\r\nvoid Redo::execute()\r\n{\r\n\tint n = this->operation.size() - 1;\r\n\tif (this->operation[n].getOperation() == \"add\")\r\n\t{\r\n\t\tthis->repo.add(this->operation[n].getMovie());\r\n\t\tthis->pop();\r\n\t\treturn;\r\n\t}\r\n\tif (this->operation[n].getOperation() == \"delete\")\r\n\t{\r\n\t\tint k = this->repo.findByTitle(this->operation[n].getMovie().getTitle());\r\n\t\tthis->repo.del(k);\r\n\t\tthis->pop();\r\n\t\treturn;\r\n\t}\r\n\tif (this->operation[n].getOperation() == \"update\")\r\n\t{\r\n\t\t{\r\n\t\t\tOperationElement m = this->operation[n];\r\n\t\t\tthis->repo.update(m.getMovieUpdate().getTitle(), m.getMovie().getTitle(), m.getMovie().getGenre(), m.getMovie().getYear(), m.getMovie().getLikes(), m.getMovie().getTrailer());\r\n\t\t\tthis->pop();\r\n\t\t}\r\n\t\treturn;\r\n\t}\r\n}"
},
{
"alpha_fraction": 0.6667993664741516,
"alphanum_fraction": 0.681130588054657,
"avg_line_length": 34.40579605102539,
"blob_id": "e631848c4c5f7328750922146dbbe4ddb568d99b",
"content_id": "50a618ec93988d80011603f65a533a9d4f42e3ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2512,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 69,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/GeneratedFiles/ui_OOPotherpractical1.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'OOPotherpractical1.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_OOPOTHERPRACTICAL1_H\r\n#define UI_OOPOTHERPRACTICAL1_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QMenuBar>\r\n#include <QtWidgets/QStatusBar>\r\n#include <QtWidgets/QToolBar>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_OOPotherpractical1Class\r\n{\r\npublic:\r\n QMenuBar *menuBar;\r\n QToolBar *mainToolBar;\r\n QWidget *centralWidget;\r\n QStatusBar *statusBar;\r\n\r\n void setupUi(QMainWindow *OOPotherpractical1Class)\r\n {\r\n if (OOPotherpractical1Class->objectName().isEmpty())\r\n OOPotherpractical1Class->setObjectName(QStringLiteral(\"OOPotherpractical1Class\"));\r\n OOPotherpractical1Class->resize(600, 400);\r\n menuBar = new QMenuBar(OOPotherpractical1Class);\r\n menuBar->setObjectName(QStringLiteral(\"menuBar\"));\r\n OOPotherpractical1Class->setMenuBar(menuBar);\r\n mainToolBar = new QToolBar(OOPotherpractical1Class);\r\n mainToolBar->setObjectName(QStringLiteral(\"mainToolBar\"));\r\n OOPotherpractical1Class->addToolBar(mainToolBar);\r\n centralWidget = new QWidget(OOPotherpractical1Class);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n OOPotherpractical1Class->setCentralWidget(centralWidget);\r\n statusBar = new QStatusBar(OOPotherpractical1Class);\r\n statusBar->setObjectName(QStringLiteral(\"statusBar\"));\r\n OOPotherpractical1Class->setStatusBar(statusBar);\r\n\r\n retranslateUi(OOPotherpractical1Class);\r\n\r\n QMetaObject::connectSlotsByName(OOPotherpractical1Class);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *OOPotherpractical1Class)\r\n {\r\n OOPotherpractical1Class->setWindowTitle(QApplication::translate(\"OOPotherpractical1Class\", \"OOPotherpractical1\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class OOPotherpractical1Class: public Ui_OOPotherpractical1Class {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_OOPOTHERPRACTICAL1_H\r\n"
},
{
"alpha_fraction": 0.5560439825057983,
"alphanum_fraction": 0.5615384578704834,
"avg_line_length": 16.200000762939453,
"blob_id": "d0b09921b1c88765f1a24621dd8583199f91c174",
"content_id": "e7edecbdbb7f992db9461ea8c6cc2a3ad6fe5f28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 910,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 50,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/StarRepo.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"StarRepo.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nvoid StarRepo::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tstring f, n;\r\n\t\tdouble p, lo;\r\n\t\tf = v[0];\r\n\t\tn = v[1];\r\n\t\tp = stod(v[2]);\r\n\t\tlo = stod(v[3]);\r\n\t\tStar m{ f,n,p,lo };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\nvoid StarRepo::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->getLenght();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\nstd::vector<Star> StarRepo::filter(std::string co)\r\n{\r\n\tstd::vector<Star> s;\r\n\tfor (auto i : elems)\r\n\t\tif (i.getConste() == co)\r\n\t\t\ts.push_back(i);\r\n\treturn s;\r\n}\r\n"
},
{
"alpha_fraction": 0.5974358916282654,
"alphanum_fraction": 0.6213675141334534,
"avg_line_length": 21,
"blob_id": "a2ad0c771676475698ed1eac17eef21110940a2c",
"content_id": "851603ca0e01a7d8850f2a281073b91bca096043",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1170,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 51,
"path": "/MyProjects/OOP/OOP/Written 2/OOP written ex1/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Stack.h\"\r\n#include <assert.h>\r\n#include <cstring>\r\n#include \"ToDo.h\"\r\n#include <iostream>\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nvoid testStack()\r\n{\r\n\tStack<std::string> s{ 2 };\r\n\tassert(s.getMaxCapacity() == 2);\r\n\ttry {\r\n\t\ts = s + \"examination\";\r\n\t\ts = s + \"oop\";\r\n\t\ts = s + \"test\";\r\n\t}\r\n\tcatch (std::exception& e) {\r\n\t\tassert(strcmp(e.what(), \"Stack is full!\") == 0);\r\n\t}\r\n\tassert(s.pop() == \"oop\");\r\n\tassert(s.pop() == \"examination\");\r\n}\r\n\r\nvoid ToDoList()\r\n{\r\n\tToDo<Activity> todo{};\r\n\tActivity tiff{ \"go to TIFF movie\", \"20:00\" };\r\n\ttodo += tiff;\r\n\tActivity project{ \"present project assignment\", \"09.20\" };\r\n\ttodo += project;\r\n\t// iterates through the activities and prints them as follows:\r\n\t// Activity present project assignment will take place at 09.20.\r\n\t// Activity go to TIFF movie will take place at 20.00.\r\n\tfor (auto a : todo)\r\n\t\tstd::cout << a << '\\n';\r\n\t// Prints the activities as follows:\r\n\t// Activity go to TIFF movie will take place at 20.00.\r\n\t// Activity present project assignment will take place at 09.20.\r\n\ttodo.reversePrint(std::cout);\r\n}\r\r\n\r\nint main()\r\n{\r\n\tToDoList();\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.6567638516426086,
"alphanum_fraction": 0.666106104850769,
"avg_line_length": 32.98039245605469,
"blob_id": "4ace604b4d847928a9569cba3cd009d54f17cdbb",
"content_id": "4fe20b23e1fc3aabc24904535a23f49c3d50eb60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5352,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 153,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/GeneratedFiles/ui_ProgrammerWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'ProgrammerWindow.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_PROGRAMMERWINDOW_H\r\n#define UI_PROGRAMMERWINDOW_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_MyWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout_5;\r\n QVBoxLayout *verticalLayout_2;\r\n QLabel *label;\r\n QListWidget *TaskList;\r\n QHBoxLayout *horizontalLayout_4;\r\n QHBoxLayout *horizontalLayout_3;\r\n QLabel *label_2;\r\n QLineEdit *TaskLine;\r\n QVBoxLayout *verticalLayout;\r\n QHBoxLayout *horizontalLayout_2;\r\n QPushButton *AddButton;\r\n QPushButton *DeleteButton;\r\n QHBoxLayout *horizontalLayout;\r\n QPushButton *StartButton;\r\n QPushButton *DoneButton;\r\n\r\n void setupUi(QMainWindow *MyWindow)\r\n {\r\n if (MyWindow->objectName().isEmpty())\r\n MyWindow->setObjectName(QStringLiteral(\"MyWindow\"));\r\n MyWindow->resize(597, 342);\r\n centralwidget = new QWidget(MyWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout_5 = new QHBoxLayout(centralwidget);\r\n horizontalLayout_5->setObjectName(QStringLiteral(\"horizontalLayout_5\"));\r\n verticalLayout_2 = new QVBoxLayout();\r\n verticalLayout_2->setObjectName(QStringLiteral(\"verticalLayout_2\"));\r\n label = new QLabel(centralwidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout_2->addWidget(label);\r\n\r\n TaskList = new QListWidget(centralwidget);\r\n TaskList->setObjectName(QStringLiteral(\"TaskList\"));\r\n\r\n verticalLayout_2->addWidget(TaskList);\r\n\r\n horizontalLayout_4 = new QHBoxLayout();\r\n horizontalLayout_4->setObjectName(QStringLiteral(\"horizontalLayout_4\"));\r\n horizontalLayout_3 = new QHBoxLayout();\r\n horizontalLayout_3->setObjectName(QStringLiteral(\"horizontalLayout_3\"));\r\n label_2 = new QLabel(centralwidget);\r\n label_2->setObjectName(QStringLiteral(\"label_2\"));\r\n\r\n horizontalLayout_3->addWidget(label_2);\r\n\r\n TaskLine = new QLineEdit(centralwidget);\r\n TaskLine->setObjectName(QStringLiteral(\"TaskLine\"));\r\n\r\n horizontalLayout_3->addWidget(TaskLine);\r\n\r\n\r\n horizontalLayout_4->addLayout(horizontalLayout_3);\r\n\r\n verticalLayout = new QVBoxLayout();\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n horizontalLayout_2 = new QHBoxLayout();\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n AddButton = new QPushButton(centralwidget);\r\n AddButton->setObjectName(QStringLiteral(\"AddButton\"));\r\n\r\n horizontalLayout_2->addWidget(AddButton);\r\n\r\n DeleteButton = new QPushButton(centralwidget);\r\n DeleteButton->setObjectName(QStringLiteral(\"DeleteButton\"));\r\n\r\n horizontalLayout_2->addWidget(DeleteButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout_2);\r\n\r\n horizontalLayout = new QHBoxLayout();\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n StartButton = new QPushButton(centralwidget);\r\n StartButton->setObjectName(QStringLiteral(\"StartButton\"));\r\n\r\n horizontalLayout->addWidget(StartButton);\r\n\r\n DoneButton = new QPushButton(centralwidget);\r\n DoneButton->setObjectName(QStringLiteral(\"DoneButton\"));\r\n\r\n horizontalLayout->addWidget(DoneButton);\r\n\r\n\r\n verticalLayout->addLayout(horizontalLayout);\r\n\r\n\r\n horizontalLayout_4->addLayout(verticalLayout);\r\n\r\n\r\n verticalLayout_2->addLayout(horizontalLayout_4);\r\n\r\n\r\n horizontalLayout_5->addLayout(verticalLayout_2);\r\n\r\n MyWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(MyWindow);\r\n\r\n QMetaObject::connectSlotsByName(MyWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *MyWindow)\r\n {\r\n MyWindow->setWindowTitle(QApplication::translate(\"MyWindow\", \"Programmer\", nullptr));\r\n label->setText(QApplication::translate(\"MyWindow\", \"Tasks:\", nullptr));\r\n label_2->setText(QApplication::translate(\"MyWindow\", \"Description:\", nullptr));\r\n AddButton->setText(QApplication::translate(\"MyWindow\", \"Add\", nullptr));\r\n DeleteButton->setText(QApplication::translate(\"MyWindow\", \"Delete\", nullptr));\r\n StartButton->setText(QApplication::translate(\"MyWindow\", \"Start\", nullptr));\r\n DoneButton->setText(QApplication::translate(\"MyWindow\", \"Done\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class MyWindow: public Ui_MyWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_PROGRAMMERWINDOW_H\r\n"
},
{
"alpha_fraction": 0.5953488349914551,
"alphanum_fraction": 0.6139534711837769,
"avg_line_length": 17.545454025268555,
"blob_id": "bec4ff083408fd006e3a64747e2155b1dfc6f67f",
"content_id": "308ec006a92f5db24daa3b5436a6d5d7a638c711",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 430,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 22,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Again12.h\"\r\n#include \"Admin.h\"\r\n#include \"User.h\"\r\n#include \"Mode.h\"\r\n#include <QtWidgets/QApplication>\r\n\r\n#include \"movie.h\"\r\n#include \"repository.h\"\r\n#include \"controller.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\tRepository r{ \"All.txt\" };\r\n\tRepository l{ \"List.txt\" };\r\n\tController c{ r,l };\r\n\tAdmin w2{ r };\r\n\tUser w3{ c };\r\n\tMode w1{ w2,w3,r,l };\r\n\tw1.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.5914285778999329,
"alphanum_fraction": 0.5914285778999329,
"avg_line_length": 16.526315689086914,
"blob_id": "773e4abf592f8f56c3cce938f836d82dbb5261b4",
"content_id": "255bbaba45c391c123be41fc34224031c19fce5d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 350,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 19,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/programmer.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Programmer\r\n{\r\nprivate:\r\n\tint id;\r\n\tstd::string name;\r\npublic:\r\n\tProgrammer() :id{}, name{ \"\" } {}\r\n\tProgrammer(int id, std::string name) :id{ id }, name{ name } {}\r\n\t~Programmer() {}\r\n\r\n\tint getID() { return id; }\r\n\tstd::string getName() { return name; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.6620739698410034,
"alphanum_fraction": 0.6635242700576782,
"avg_line_length": 27.382978439331055,
"blob_id": "0fe626e8ddd02ecc7596c00db51c906288253fdd",
"content_id": "5b9ef8467a8f3085797bf11cceca557fcfe5c4f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1379,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 47,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/operation.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <vector>\r\n#include <string>\r\n#include \"movie.h\"\r\n#include \"repository.h\"\r\n\r\nclass OperationElement\r\n{\r\nprivate:\r\n\tMovie movie;\r\n\tMovie movieUpdate;\r\n\tstd::string operation;\r\npublic:\r\n\tOperationElement(Movie m, Movie mo, std::string o) :movie{ m }, movieUpdate{ mo }, operation{ o } {}\r\n\t~OperationElement() {}\r\n\tMovie getMovie() { return movie; }\r\n\tstd::string getOperation() { return operation; }\r\n\tMovie getMovieUpdate() { return movieUpdate; }\r\n\tvoid setMovie(Movie m) { movie = m; }\r\n\tvoid setMovieUpdate(Movie m) { movieUpdate = m; }\r\n\tvoid setOperation(std::string o) { operation = o; }\r\n};\r\n\r\nclass Operation\r\n{\r\nprotected:\r\n\tstd::vector<OperationElement> operation{};\r\n\tRepository repo;\r\npublic:\r\n\tOperation(Repository r) :repo{ r } { }\r\n\t~Operation() {}\r\n\t\r\n\t\r\n\tvirtual void execute() = 0;\r\n\t\r\n\t\r\n\tvoid push(OperationElement o);\r\n\tOperationElement pop();\r\n\tOperationElement get() { return operation[operation.size() - 1]; }\r\n\tOperationElement operator[](int pos) { return operation[pos]; }\r\n\tint len() { return operation.size(); }\r\n\tRepository getRepo() { return repo; }\r\n\tvoid addRepo(Movie m) { repo.add(m); }\r\n\tvoid delRepo(int pos) { repo.del(pos); }\r\n\tvoid updateRepo(std::string ot, std::string nt, std::string g, int y, int l, std::string tr) { repo.update(ot, nt, g, y, l, tr); }\r\n\tvoid setE(std::vector<Movie> r) { repo.setElems(r); }\r\n};"
},
{
"alpha_fraction": 0.6235294342041016,
"alphanum_fraction": 0.6282352805137634,
"avg_line_length": 19.25,
"blob_id": "4c7044a618b72d52bc4d91535f4470b200faf306",
"content_id": "29effac24838c32e5c5520660ff889ca70fe22fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 425,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Retake.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"AstroWindow.h\"\r\n#include \"controller.h\"\r\n#include \"AstroRepo.h\"\r\n#include \"StarRepo.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\tStarRepo sr{ \"Stars.txt\" };\r\n\tAstroRepo ar{ \"Astronomers.txt\" };\r\n\tController c{ sr,ar };\r\n\tfor (auto i : ar.getAll())\r\n\t{\r\n\t\tAWindow* a1 = new AWindow(c, i);\r\n\t\ta1->show();\r\n\t}\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.6542207598686218,
"alphanum_fraction": 0.6558441519737244,
"avg_line_length": 16.66666603088379,
"blob_id": "a93f2c285f64aa2c08f301602e0cf28e3ef0c071",
"content_id": "876d38e88da0c26bcc2f4e2f64a63e486257d8f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 616,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 33,
"path": "/MyProjects/OOP/OOP/Practice 3/New/repoException.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repoException.h\"\r\n\r\nRepoException::RepoException():exception {}, message{ \"\" }\r\n{\r\n}\r\n\r\nRepoException::RepoException(const std::string & msg) : message{ msg }\r\n{\r\n}\r\n\r\nconst char * RepoException::what()\r\n{\r\n\treturn this->message.c_str();\r\n}\r\n\r\nconst char * FoundException::what()\r\n{\r\n\treturn \"There cannot be 2 movies with the same title!\\n\";\r\n}\r\n\r\nconst char * NoMovieFoundException::what()\r\n{\r\n\treturn \"There is no movie with that title!\\n\";\r\n}\r\n\r\nFileExceptionF::FileExceptionF(const std::string & msg) :message{ msg }\r\n{\r\n}\r\n\r\nconst char * FileExceptionF::what()\r\n{\r\n\treturn this->message.c_str();\r\n}\r\n"
},
{
"alpha_fraction": 0.6297208666801453,
"alphanum_fraction": 0.6313629150390625,
"avg_line_length": 19.034482955932617,
"blob_id": "295c2200c15b22c84d53a4012cbd8ad1111e97cd",
"content_id": "33a1c0059a14f3058f7d03d9543d566b7abd7631",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1218,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 58,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/teacherRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"teacher.h\"\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass TeacherRepo :public Repository<T>\r\n{\r\npublic:\r\n\tTeacherRepo(std::string filename) :Repository<T>(filename) { this->readFromFile(); }\r\n\tTeacherRepo() :Repository<T>() {}\r\n\t~TeacherRepo() {}\r\n\r\n\tvoid writeToFile() override {}\r\n\tvoid readFromFile() override;\r\n\r\n\tvoid sorted() override;\r\n\r\n\tint findByID(int id) override {}\r\n\tvoid setGrade(int pos, int gr) override {}\r\n\tstd::vector<T> getByGroups(std::vector<int> gr) override {}\r\n};\r\n\r\ntemplate<typename T>\r\ninline void TeacherRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ';'))\r\n\t\t\tv.push_back(t);\r\n\t\tstd::string f, p;\r\n\t\tf = v[0];\r\n\t\tp = v[1];\r\n\t\tstd::stringstream aici(p);\r\n\t\tstd::vector<int> y{};\r\n\t\twhile (getline(aici, t, ','))\r\n\t\t\ty.push_back(stoi(t));\r\n\t\tTeacher m{ f,y };\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TeacherRepo<T>::sorted()\r\n{\r\n}"
},
{
"alpha_fraction": 0.6082473993301392,
"alphanum_fraction": 0.6082473993301392,
"avg_line_length": 14.166666984558105,
"blob_id": "7ec2d9412a4443242a3b8022ada42e0841b3863c",
"content_id": "690d2205e57628b2944fa5944cf48e5c3e2b813c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 12,
"path": "/MyProjects/MAP/Practical Exam/Procedures/src/Model/Utilities/IList.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Utilities;\r\n\r\nimport java.util.List;\r\n\r\npublic interface IList<T> {\r\n void add(T x);\r\n\r\n Iterable<T> getElements();\r\n List<T> getElementsL();\r\n\r\n void remove(T x);\r\n}\r\n"
},
{
"alpha_fraction": 0.5885528922080994,
"alphanum_fraction": 0.5950323939323425,
"avg_line_length": 23.77777862548828,
"blob_id": "c8a19ea995a059433cd4a08221bb8a1a5980626b",
"content_id": "de5578f2cd3e9a4b36d84524abefa0d87c4a2c1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 926,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 36,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/task.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Task\r\n{\r\nprivate:\r\n\tstd::string description;\r\n\tint stat;\r\n\tstd::string status;\r\n\tint programmerid;\r\npublic:\r\n\tTask() :stat{}, status{ \"\" }, programmerid{}, description{ \"\" } {}\r\n\tTask(std::string descr) :stat{ -1 }, status{ \"open\" }, programmerid{}, description{ descr } {}\r\n\tTask(std::string descr, int s, int id) :stat{ s }, description{ descr }, programmerid{ id }\r\n\t{\r\n\t\tif (s == -1)\r\n\t\t\tstatus = \"open\";\r\n\t\tif (s == 0)\r\n\t\t\tstatus = \"in progress\";\r\n\t\tif (s == 1)\r\n\t\t\tstatus = \"closed\";\r\n\t}\r\n\t~Task() {}\r\n\r\n\tint getIntStat() { return stat; }\r\n\tstd::string getStat() { return status; }\r\n\tstd::string getDescr() { return description; }\r\n\tint getID() { return programmerid; }\r\n\r\n\tvoid setProgress() { stat = 0; status = \"in progress\"; }\r\n\tvoid setClosed() { stat = 1;status = \"closed\"; }\r\n\tvoid setID(int id) { programmerid = id; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.6310679316520691,
"alphanum_fraction": 0.6310679316520691,
"avg_line_length": 16.176469802856445,
"blob_id": "42a8079b3ea202e6ce456c3e110c54845cb70158",
"content_id": "5632bef1e4caf2da3b8a8b0c164e4662ae4773df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 311,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 17,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Utilities/IList.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Text;\r\nusing System.Linq;\r\n\r\nnamespace Interpreter.Model.Utilities\r\n{\r\n public interface IList<T>:IEnumerable\r\n {\r\n void add(T x);\r\n\r\n List<T> getElements();\r\n\r\n void remove(T x);\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6591928005218506,
"alphanum_fraction": 0.6591928005218506,
"avg_line_length": 18.272727966308594,
"blob_id": "2d9096274db15aae7b25a6a390750889d8f862db",
"content_id": "025b11ebfdd18ca84ba5098fd02a8c4fd5789ede",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 225,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Exceptions/EmptyStack.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Exceptions\r\n{\r\n public class EmptyStack : Exception\r\n {\r\n public EmptyStack(String msg) : base(msg) { }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.4574951231479645,
"alphanum_fraction": 0.4587929844856262,
"avg_line_length": 22.078125,
"blob_id": "43350f6c120f9d570398a483037c04e69c761207",
"content_id": "5840c76d3999db4f130852a3d9f642eb6ad332cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1541,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 64,
"path": "/MyProjects/FP/FP/Shapes - Exam/repository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import pickle\r\nclass Repository:\r\n def __init__(self):\r\n self._data=[]\r\n\r\n def get(self,index):\r\n '''\r\n Returns the element from the index position, -1 if it does not exist\r\n :param index:\r\n :return:\r\n '''\r\n if index>=len(self._data):\r\n return -1\r\n return self._data[index]\r\n def getAll(self):\r\n '''\r\n Returns self._data\r\n :return:\r\n '''\r\n return self._data\r\n def add(self,el):\r\n '''\r\n Adds an element to the list\r\n :param el:\r\n :return:\r\n '''\r\n self._data.append(el)\r\n\r\n\r\nclass PickleRepository(Repository):\r\n def __init__(self,fileName):\r\n Repository.__init__(self)\r\n self.__fileName=fileName\r\n self.__load()\r\n def add(self,el):\r\n '''\r\n Adds an element to the file\r\n :param el:\r\n :return:\r\n '''\r\n Repository.add(self,el)\r\n self.__store()\r\n def __load(self):\r\n '''\r\n Loads the file into self._data\r\n :return:\r\n '''\r\n file=open(self.__fileName,\"rb\")\r\n try:\r\n self._data=pickle.load(file)\r\n except EOFError:\r\n self._data=[]\r\n except Exception as exc:\r\n raise exc\r\n finally:\r\n file.close()\r\n def __store(self):\r\n '''\r\n Stores self._data into the file\r\n :return:\r\n '''\r\n file=open(self.__fileName,\"wb\")\r\n pickle.dump(self._data,file)\r\n file.close()\r\n"
},
{
"alpha_fraction": 0.7846890091896057,
"alphanum_fraction": 0.7846890091896057,
"avg_line_length": 68,
"blob_id": "4c7db717761da21a7d3085046c9296d5e779c21e",
"content_id": "c06e3df4e61292f4ca9de45dbf67c078370f4236",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 209,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 3,
"path": "/MyProjects/ASC/README.txt",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "\tThis file contains ASC lab problems and practice problems that I made during the first semester.\r\n\tNote! The names on the projects are not correctly coresponding to what some of them actually are.\r\n\tEnjoy! :)"
},
{
"alpha_fraction": 0.7663043737411499,
"alphanum_fraction": 0.7663043737411499,
"avg_line_length": 18.44444465637207,
"blob_id": "89f7d74039c709f33a2ea5601e0662badac99402",
"content_id": "5bd81f37aba6b00011a9151605cd2ff02fa4c20e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 9,
"path": "/MyProjects/MAP/Practical Exam/ConditionalStmt/src/Model/Statements/IStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.ProgramState;\r\n\r\nimport java.io.IOException;\r\n\r\npublic interface IStmt {\r\n ProgramState execute(ProgramState state)throws IOException;\r\n}\r\n"
},
{
"alpha_fraction": 0.6574074029922485,
"alphanum_fraction": 0.6574074029922485,
"avg_line_length": 19.733333587646484,
"blob_id": "d180f197b739cd1efd9bd22ca522d7aef8aff012",
"content_id": "6a780acc97d047886c3424ef91fd77c9977e843e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 324,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 15,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n\r\ntemplate <typename T>\r\nclass Controller {\r\nprivate:\r\n\tRepository<T> repo;\r\npublic:\r\n\tController(Repository<T> r) :repo{ r } {}\r\n\tbool add(T s);\r\n\tbool del(int id);\r\n\tbool update(int id, std::string name, int age);\r\n\tint findByID(int id);\r\n\tRepository<T> getAll() { return repo; }\r\n};"
},
{
"alpha_fraction": 0.648409903049469,
"alphanum_fraction": 0.6545936465263367,
"avg_line_length": 33.010311126708984,
"blob_id": "50b07380ec1b14d2bff393763316a2529cc9258a",
"content_id": "adf7ae53f4a14a36899c5bf3958d73923a8d03b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3396,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 97,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_view.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'view.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_VIEW_H\r\n#define UI_VIEW_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QTabWidget>\r\n#include <QtWidgets/QTableView>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_ViewWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QHBoxLayout *horizontalLayout;\r\n QTabWidget *tabWidget;\r\n QWidget *MovieList;\r\n QHBoxLayout *horizontalLayout_2;\r\n QTableView *MovieTable;\r\n QWidget *WatchList;\r\n QHBoxLayout *horizontalLayout_3;\r\n QTableView *WatchTable;\r\n\r\n void setupUi(QMainWindow *ViewWindow)\r\n {\r\n if (ViewWindow->objectName().isEmpty())\r\n ViewWindow->setObjectName(QStringLiteral(\"ViewWindow\"));\r\n ViewWindow->resize(605, 369);\r\n centralwidget = new QWidget(ViewWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n horizontalLayout = new QHBoxLayout(centralwidget);\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n tabWidget = new QTabWidget(centralwidget);\r\n tabWidget->setObjectName(QStringLiteral(\"tabWidget\"));\r\n MovieList = new QWidget();\r\n MovieList->setObjectName(QStringLiteral(\"MovieList\"));\r\n horizontalLayout_2 = new QHBoxLayout(MovieList);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n MovieTable = new QTableView(MovieList);\r\n MovieTable->setObjectName(QStringLiteral(\"MovieTable\"));\r\n\r\n horizontalLayout_2->addWidget(MovieTable);\r\n\r\n tabWidget->addTab(MovieList, QString());\r\n WatchList = new QWidget();\r\n WatchList->setObjectName(QStringLiteral(\"WatchList\"));\r\n horizontalLayout_3 = new QHBoxLayout(WatchList);\r\n horizontalLayout_3->setObjectName(QStringLiteral(\"horizontalLayout_3\"));\r\n WatchTable = new QTableView(WatchList);\r\n WatchTable->setObjectName(QStringLiteral(\"WatchTable\"));\r\n\r\n horizontalLayout_3->addWidget(WatchTable);\r\n\r\n tabWidget->addTab(WatchList, QString());\r\n\r\n horizontalLayout->addWidget(tabWidget);\r\n\r\n ViewWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(ViewWindow);\r\n\r\n tabWidget->setCurrentIndex(1);\r\n\r\n\r\n QMetaObject::connectSlotsByName(ViewWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *ViewWindow)\r\n {\r\n ViewWindow->setWindowTitle(QApplication::translate(\"ViewWindow\", \"View\", nullptr));\r\n tabWidget->setTabText(tabWidget->indexOf(MovieList), QApplication::translate(\"ViewWindow\", \"Movie list\", nullptr));\r\n tabWidget->setTabText(tabWidget->indexOf(WatchList), QApplication::translate(\"ViewWindow\", \"Watch list\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class ViewWindow: public Ui_ViewWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_VIEW_H\r\n"
},
{
"alpha_fraction": 0.6242774724960327,
"alphanum_fraction": 0.6242774724960327,
"avg_line_length": 17.22222137451172,
"blob_id": "c51ce07217335eee382da4ce9a0a2022a7e196a7",
"content_id": "644ac9cdac52610079ae32e3bb984a8e23d78b01",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 18,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/astronomer.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"astronomer.h\"\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Astronomer::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Name: \" << name << \", Constellation: \" << constellation;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Astronomer::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << name << \",\" << constellation;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.6481481194496155,
"alphanum_fraction": 0.6481481194496155,
"avg_line_length": 14.399999618530273,
"blob_id": "350e2d8be08c72565399de901c69ce3a9117bcf5",
"content_id": "f8de43da1a25d653dc5ba31e368ed236481f53f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 10,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/undo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"operation.h\"\r\n\r\nclass Undo :public Operation\r\n{\r\npublic:\r\n\tUndo(Repository r) :Operation{r} {}\r\n\t~Undo() {}\r\n\tvoid execute() override;\r\n};"
},
{
"alpha_fraction": 0.6184107065200806,
"alphanum_fraction": 0.6184107065200806,
"avg_line_length": 17.25757598876953,
"blob_id": "88a6a00631e6b8487ca4e60828693e9b5b9cf809",
"content_id": "cd74fa984725196d01d26fa028bec2d8438af1c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1271,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 66,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Mode.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Mode.h\"\r\n#include \"Admin.h\"\r\n#include \"User.h\"\r\n\r\nMode::Mode(Admin &a,User &u,Repository &r, Repository &l,QWidget *parent)\r\n\t:password{ a }, r{ r }, l{ l }, QMainWindow(parent)\r\n{\r\n\tthis->table = new View(r, l);\r\n\tthis->setAdmin(a);\r\n\tthis->setUser(u);\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n}\r\n\r\nvoid Mode::AdminMode()\r\n{\r\n\r\n\tthis->adm->show();\r\n\r\n}\r\n\r\nvoid Mode::UserMode()\r\n{\r\n\r\n\tthis->usr->readFromFile();\r\n\tthis->usr->show();\r\n\r\n}\r\n\r\nvoid Mode::passwordShow()\r\n{\r\n\tthis->password.readFromFile();\r\n\tthis->password.show();\r\n}\r\n\r\nvoid Mode::viewAll()\r\n{\r\n\tdelete this->table;\r\n\tthis->r.clr();\r\n\tthis->l.clr();\r\n\tthis->r.readFromFile();\r\n\tthis->l.readFromFile();\r\n\tthis->table = new View(this->r, this->l);\r\n\tthis->table->show();\r\n}\r\n\r\nvoid Mode::connectSignalsAndSlots()\r\n{\r\n\t//QObject::connect(this->ui.AdminButton, SIGNAL(clicked()), this, SLOT(AdminMode()));\r\n\r\n\tQObject::connect(this->ui.AdminButton, SIGNAL(clicked()), this, SLOT(passwordShow()));\r\n\r\n\tQObject::connect(this->ui.UserButton, SIGNAL(clicked()), this, SLOT(UserMode()));\r\n\r\n\tQObject::connect(this->ui.ViewButton, SIGNAL(clicked()), this, SLOT(viewAll()));\r\n}\r\n\r\nvoid Mode::setAdmin(Admin & a)\r\n{\r\n\tthis->adm = &a;\r\n}\r\n\r\nvoid Mode::setUser(User & u)\r\n{\r\n\tthis->usr = &u;\r\n}\r\n"
},
{
"alpha_fraction": 0.6381611227989197,
"alphanum_fraction": 0.6450815796852112,
"avg_line_length": 21.546510696411133,
"blob_id": "8633ed46dfe707cfe5202ba5a02690990b7b8c0f",
"content_id": "3e3c8be536482eb4f8e42e47d0b0d3d8991561bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2023,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 86,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/Vegetables.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Vegetables.h\"\r\n#include <QMessageBox>\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nVegetables::Vegetables(Repository &r,QWidget *parent)\r\n\t:repo{ r }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->sort();\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populateFam();\r\n\tRepository rw{};\r\n\tthis->flt = rw;\r\n}\r\n\r\nvoid Vegetables::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.FamilyList, SIGNAL(itemSelectionChanged()), this, SLOT(filterR()));\r\n\r\n}\r\n\r\nvoid Vegetables::populateFam()\r\n{\r\n\tthis->sort();\r\n\tif (ui.FamilyList->count() != 0)\r\n\t\tui.FamilyList->clear();\r\n\tfor (auto m : repo.getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.getFamily());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.FamilyList->addItem(listItemWidget);\r\n\t}\r\n\tif (repo.getLenght() > 0)\r\n\t\tui.FamilyList->setCurrentRow(-1);\r\n}\r\n\r\nvoid Vegetables::populateVeg()\r\n{\r\n\tif (ui.VegetableList->count() != 0)\r\n\t\tui.VegetableList->clear();\r\n\tfor (auto m : flt.getAll())\r\n\t{\r\n\t\tint hi;\r\n\t\tstringstream buff;\r\n\t\tbuff << \"Name: \" << m.getName() << \", Parts: \";\r\n\t\tfor (hi = 0;hi < m.getParts().size()-1;hi++)\r\n\t\t\tbuff << m.getParts()[hi]<<', ';\r\n\t\tbuff << m.getParts()[hi];\r\n\t\tQString listItem = QString::fromStdString(buff.str());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.VegetableList->addItem(listItemWidget);\r\n\t}\r\n\tif (flt.getLenght() > 0)\r\n\t\tui.VegetableList->setCurrentRow(0);\r\n}\r\n\r\nint Vegetables::getSelectedIndex()\r\n{\r\n\tif (ui.FamilyList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.FamilyList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid Vegetables::sort()\r\n{\r\n\tthis->repo.sort();\r\n}\r\n\r\nvoid Vegetables::filterR()\r\n{\r\n\tint i = this->getSelectedIndex();\r\n\tif (i == -1)\r\n\t\treturn;\r\n\tstd::string fam = this->repo[i].getFamily();\r\n\tthis->flt.setElems(this->repo.filter(fam));\r\n\tthis->populateVeg();\r\n}"
},
{
"alpha_fraction": 0.6563745141029358,
"alphanum_fraction": 0.6613546013832092,
"avg_line_length": 21.904762268066406,
"blob_id": "674cf4b2007f9c1e24c741cd8a6c276713c95a5d",
"content_id": "c723f22316a5055e555c2a07728361d7b4ad13bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2008,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 84,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/MainTeacher.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"MainTeacher.h\"\r\n#include \"TeacherWindow.h\"\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nHeadTeacher::HeadTeacher(Controller& c, QWidget *parent)\r\n\t:controller{ c }, currentID{ 20 }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->showAll();\r\n\tthis->populate();\r\n\tthis->modifyAll();\r\n}\r\n\r\nvoid HeadTeacher::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.AddButton, SIGNAL(clicked()), this, SLOT(add()));\r\n\tQObject::connect(ui.DeleteButton, SIGNAL(clicked()), this, SLOT(del()));\r\n}\r\n\r\nint HeadTeacher::getSelectedIndex()\r\n{\r\n\tif (ui.listWidget->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.listWidget->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid HeadTeacher::populate()\r\n{\r\n\tif (ui.listWidget->count() != 0)\r\n\t\tui.listWidget->clear();\r\n\tfor (auto m : this->controller.getStudents()->getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.listWidget->addItem(listItemWidget);\r\n\t}\r\n\tif (this->controller.getStudents()->getLenght() > 0)\r\n\t\tui.listWidget->setCurrentRow(0);\r\n}\r\n\r\nvoid HeadTeacher::modifyAll()\r\n{\r\n\tfor (auto i : this->all)\r\n\t\ti->populate();\r\n}\r\n\r\nvoid HeadTeacher::showAll()\r\n{\r\n\tfor (auto i : controller.getTeachers()->getAll())\r\n\t{\r\n\t\tSepareteTeacher* t = new SepareteTeacher(controller.getStudents(), i.getName(), i.getGroups());\r\n\t\tall.push_back(t);\r\n\t\tt->show();\r\n\t}\r\n}\r\n\r\nvoid HeadTeacher::add()\r\n{\r\n\tstd::string name = ui.NameLine->text().toStdString();\r\n\tstd::string gr = ui.GroupLine->text().toStdString();\r\n\tint group = stoi(gr);\r\n\tStudent s{currentID, name,group };\r\n\tcurrentID++;\r\n\tthis->controller.addStudent(s);\r\n\tthis->populate();\r\n\tthis->modifyAll();\r\n}\r\n\r\nvoid HeadTeacher::del()\r\n{\r\n\tint k = this->getSelectedIndex();\r\n\tthis->controller.delStudent(k);\r\n\tthis->populate();\r\n\tthis->modifyAll();\r\n}\r\n"
},
{
"alpha_fraction": 0.6430920958518982,
"alphanum_fraction": 0.6430920958518982,
"avg_line_length": 24.521739959716797,
"blob_id": "c6b469f610b2d733a1d484c057337822ccb6e642",
"content_id": "401bc24784232b9c0bc8126368f6585267f4590c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 608,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 23,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/star.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Star\r\n{\r\nprivate:\r\n\tstd::string name;\r\n\tstd::string constellation;\r\n\tdouble luminosity;\r\n\tdouble temperature;\r\npublic:\r\n\tStar() :name{ \"\" }, constellation{ \"\" }, luminosity{}, temperature{} { }\r\n\tStar(std::string n, std::string c, double l, double t) :name{ n }, constellation{ c }, luminosity{ l }, temperature{ t } { }\r\n\t~Star() {}\r\n\r\n\tstd::string getName() { return name; }\r\n\tstd::string getConste() { return constellation; }\r\n\tdouble getLumi() { return luminosity; }\r\n\tdouble getTemp() { return temperature; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.5032740831375122,
"alphanum_fraction": 0.5042095184326172,
"avg_line_length": 25.41025733947754,
"blob_id": "f066b549328b7427c569ee125429c0bfbe113712",
"content_id": "5945e6f6e3d644a54e6c72ed16dbbfa0f8213196",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1071,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 39,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/OpenRFileStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.IO;\r\nusing Interpreter.Exceptions;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class OpenRFileStmt:IStmt\r\n {\r\n private string var;\r\n private string path;\r\n\r\n public OpenRFileStmt(string v, string s) { var = v; path = s; }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n StreamReader b = new StreamReader(path,true);\r\n\r\n if(!state.SymbolTable.exists(var)) {\r\n int i = 0;\r\n while(true){\r\n if(state.FileTab.exists(i))\r\n i++;\r\n else break;\r\n }\r\n state.SymbolTable.setValue(var, i);\r\n state.FileTab.setValue(i, b);\r\n }\r\n else throw new FileAlreadyExists(\"File already exists!\");\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"OpenFile(\" + var + \",\" + path + \")\";\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5408435463905334,
"alphanum_fraction": 0.54458087682724,
"avg_line_length": 14.008546829223633,
"blob_id": "9335541cbb132743ffa78806e8d594f6001ceb50",
"content_id": "98b6cc451f2458ba777cfd4f1c0702bc4e77d272",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1873,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 117,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/dynamic.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"dynamic.h\"\r\n\r\nVector::Vector(int cap)\r\n{\r\n\tthis->len = 0;\r\n\tthis->cap = cap;\r\n\tthis->elems = new TElement[cap];\r\n}\r\n\r\nVector::Vector(const Vector & v)\r\n{\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t{\r\n\t\tthis->elems[i] = v.elems[i];\r\n\t}\r\n}\r\n\r\nVector::~Vector()\r\n{\r\n\tdelete[] this->elems;\r\n}\r\n\r\nVector & Vector::operator=(const Vector & v)\r\n{\r\n\tif (this == &v)\r\n\t\treturn *this;\r\n\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\tthis->elems[i] = v.elems[i];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\r\n\r\nvoid Vector::add(const TElement & e)\r\n{\r\n\tif (this->len == this->cap)\r\n\t\tthis->resize();\r\n\tthis->elems[this->len] = e;\r\n\tthis->len++;\r\n}\r\n\r\nvoid Vector::del(int pos)\r\n{\r\n\tTElement* e = new TElement[this->cap];\r\n\tint k = 0;\r\n\tfor(int i=0;i<this->len;i++)\r\n\t\tif (i != pos)\r\n\t\t{\r\n\t\t\te[i] = this->elems[i];\r\n\t\t\tk++;\r\n\t\t}\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n\tthis->len--;\r\n}\r\n\r\nint Vector::getLenght() const\r\n{\r\n\treturn this->len;\r\n}\r\n\r\nMovie Vector::get(int pos)\r\n{\r\n\tif (pos < 0 || pos >= this->getLenght())\r\n\t\treturn Movie{};\r\n\treturn this->elems[pos];\r\n}\r\n\r\nTElement * Vector::getAll() const\r\n{\r\n\treturn this->elems;\r\n}\r\n\r\nvoid Vector::resize(int times)\r\n{\r\n\tthis->cap *= static_cast<int>(times);\r\n\r\n\tTElement* e = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\te[i] = this->elems[i];\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n}\r\n\r\nvoid Vector::incLikes(int pos)\r\n{\r\n\tthis->elems[pos].incL();\r\n}\r\n\r\nVector & operator+(Vector & v, const Movie & m)\r\n{\r\n\tif (v.len == v.cap)\r\n\t\tv.resize();\r\n\tv.elems[v.len] = m;\r\n\tv.len++;\r\n\treturn v;\r\n}\r\n\r\nVector & operator+(const Movie & m, Vector & v)\r\n{\r\n\tif (v.len == v.cap)\r\n\t\tv.resize();\r\n\tv.elems[v.len] = m;\r\n\tv.len++;\r\n\treturn v;\r\n}\r\n"
},
{
"alpha_fraction": 0.5171717405319214,
"alphanum_fraction": 0.5171717405319214,
"avg_line_length": 17.038461685180664,
"blob_id": "28c24a2a7eac07c6d49cb357919a63cd57e4001b",
"content_id": "2bd401e834ea33825ab82b3a863e2f0fcc2c4cff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 26,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Expressions/VarExpr.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Expressions\r\n{\r\n public class VarExpr:IExpr\r\n {\r\n private string id;\r\n\r\n public VarExpr(string v)\r\n {\r\n id = v;\r\n }\r\n\r\n public int evaluate(Utilities.IDictionary<string, int> dic)\r\n {\r\n return dic.getValue(id);\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return id;\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.45748117566108704,
"alphanum_fraction": 0.466092586517334,
"avg_line_length": 32.48147964477539,
"blob_id": "88403e7c047859b9b215da8207d8afb57879ef6c",
"content_id": "55f5c8b1ac1e7cf3dc6f466d81d59667cb4aeb92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 27,
"path": "/MyProjects/FP/FP/FP Test 2/CSVRepository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nclass CSVRepo(Repository):\r\n def __init__(self,fileName):\r\n Repository.__init__(self)\r\n self.__fileName=fileName\r\n self.__loadFromFile()\r\n def __loadFromFile(self):\r\n try:\r\n f = open(self.__fileName, \"r\")\r\n line = f.readline().strip()\r\n while line != \"\":\r\n attrs = line.split(\",\")\r\n person = [attrs[0], attrs[1], attrs[2], attrs[3]]\r\n Repository.add(self, person)\r\n line = f.readline().strip()\r\n except IOError:\r\n print(\"Error\")\r\n finally:\r\n self.__fileName.close()\r\n\r\n def __storeToFile(self):\r\n f = open(self.__fileName, \"w\")\r\n books = Repository.getAll(self)\r\n for book in books:\r\n strf = str(book[0] + \",\" + book[1] + \",\" + book[2] + \",\" + book[3] + \"\\n\")\r\n f.write(strf)\r\n f.close()"
},
{
"alpha_fraction": 0.717391312122345,
"alphanum_fraction": 0.717391312122345,
"avg_line_length": 18,
"blob_id": "d23d35da01fa959a08a6f100aa635c797e2d98ae",
"content_id": "d54490b3fbf56cda09ca156f184032b30e7b2fd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 138,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 7,
"path": "/MyProjects/FP/FP/Shapes - Exam/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from UI import *\r\nfrom controller import *\r\nfrom repository import *\r\nr=PickleRepository('text.txt')\r\nc=Controller()\r\nui=UI(c)\r\nui.start()"
},
{
"alpha_fraction": 0.644752025604248,
"alphanum_fraction": 0.6467704772949219,
"avg_line_length": 28.02597427368164,
"blob_id": "af056f29648a49c4cbbcad86a503c485fbda08fb",
"content_id": "fa16b325f9a6c3b5cfd740808cde35dcec99ac38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6936,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 231,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/bst.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"node.h\"\r\n#include \"iterator.h\"\r\n#include <iostream>\r\n#include <string>\r\n\r\ntemplate <typename TElem>\r\nclass SortedBag\r\n{\r\nprivate:\r\n\tNode<TElem>* root;\t\t// root is a pointer to a node\r\n\tstd::string relation;\t// relation is a string that will consist in comparing two values\r\n\t\r\n\t//\tComparison function between two values, this function uses the relation\r\n\tbool cmp(TElem e1, TElem e2);\r\n\r\n\t// Adds a new node to the tree, returns the pointer to the node.\r\n\tNode<TElem>* add(Node<TElem>* parent, Node<TElem>* root, TElem data);\r\n\r\n\t// Searches the value in the tree and returns a pointer to the node if the value is found.\r\n\tNode<TElem>* find(Node<TElem>* root, TElem data);\r\n\r\n\t// Recursively deletes a node from the tree\r\n\tNode<TElem>* del(Node<TElem>* root, TElem data);\r\n\r\n\t// Returns a pointer to the most left node.\r\n\tNode<TElem>* FindMin(Node<TElem>* root);\r\n\t// Destroies the children along with their children of the root, after which the root itself is destroyed.\r\n\tvoid destroy(Node<TElem>* root);\r\n\t// Counts and returns the number of elements from the sorted bag recursively.\r\n\tvoid count(Node<TElem>* root, int &contor);\r\npublic:\r\n\t//int cnt;\r\n\t// Constructor for the sorted bag, initializes the root to NULL and the relation to a string\r\n\tSortedBag(std::string relation) :relation{ relation } { root = NULL; }\r\n\r\n\t// Deconstructor for the sorted bag\r\n\t~SortedBag() { destroy(root); }\r\n\r\n\t\r\n\r\n\t// Inserts a new element into the tree.\r\n\tvoid insert(TElem data);\r\n\r\n\t// Removes a node with a given value from the tree.\r\n\tbool remove(TElem data);\r\n\r\n\t// Searches the given value in the tree, if it finds it then returns true, false otherwise.\r\n\tbool search(TElem data);\r\n\r\n\r\n\t// Returns the number of elements from the sorted bag.\r\n\tint size();\r\n\r\n\t// Returns the iterator for the binary tree.\r\n\tIterator<TElem> iterator() { return Iterator<TElem>{ root }; }\r\n};\r\n\r\ntemplate<typename TElem>\r\ninline bool SortedBag<TElem>::cmp(TElem e1, TElem e2)\r\n{\r\n\tif (relation == \">\")\r\n\t\treturn e1 > e2;\r\n\treturn e1< e2;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline Node<TElem>* SortedBag<TElem>::add(Node<TElem>* parent,Node<TElem>* root, TElem data)\r\n{\r\n\tif (root == NULL) {\t\t// sets up the root to be the first node\r\n\t\troot = new Node<TElem>();\t// allocates new memory for the root\r\n\t\troot->data = data;\t\t\t// data from the root becomes the given parameter\r\n\t\troot->parent = parent;\t\t// the parent is going to be a pointer to the parent node\r\n\t\troot->left = NULL;\t\t\t// both left and right childs are set to null\r\n\t\troot->right = NULL;\t\r\n\t}\r\n\telse if (!cmp(data, root->data))\t// compares the two values using the given relation\r\n\t\troot->left = add(root, root->left, data);\r\n\t// checks if the given value is greater than the one in the current node \r\n\t// and makes a decision based on the relation wether it should be a left or a right child\r\n\telse\r\n\t\troot->right = add(root, root->right, data);\r\n\treturn root;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline Node<TElem>* SortedBag<TElem>::find(Node<TElem>* root, TElem data)\r\n{\r\n\tif (root != NULL) {\r\n\r\n\t\tif (data == root->data)\r\n\t\t\treturn root;\r\n\r\n\t\tif (!cmp(data, root->data))\r\n\t\t\treturn find(root->left, data);\r\n\t\telse\r\n\t\t\treturn find(root->right, data);\r\n\r\n\t}\r\n\telse\r\n\t\treturn NULL;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline Node<TElem>* SortedBag<TElem>::del(Node<TElem>* root, TElem data)\r\n{\r\n\tif (root == NULL) return root;\r\n\telse if (data < root->data) root->left = del(root->left, data);\r\n\telse if (data > root->data) root->right = del(root->right, data);\r\n\telse {\r\n\t\t// case 1: no child\r\n\t\tif (root->left == NULL && root->right == NULL) {\r\n\t\t\tdelete root;\t// easily frees the memory allocated to the leaf\r\n\t\t\troot = NULL;\t// sets the root to null\r\n\t\t}\r\n\t\t// case 2: one child (right child)\r\n\t\telse if (root->left == NULL) {\r\n\r\n\t\t\tNode<TElem> *temp = root->right;\t// saving the pointer to the right child\r\n\t\t\t\r\n\t\t\troot->data = root->right->data;\t\t// replaces the current node pointer with its right child\r\n\t\t\troot->left = root->right->left;\r\n\t\t\troot->right = root->right->right;\r\n\t\t\t\r\n\t\t\tif (root->left != NULL &&root->left->right != NULL )\r\n\t\t\t\troot->left->right->parent = root->left;\r\n\t\t\tif (root->left != NULL && root->left->left != NULL)\r\n\t\t\t\troot->left->left->parent = root->left;\r\n\t\t\tif (root->right != NULL&&root->right->left != NULL )\r\n\t\t\t\troot->right->left->parent = root->right;\r\n\t\t\tif (root->right != NULL && root->right->right != NULL)\r\n\t\t\t\troot->right->right->parent = root->right;\r\n\t\t\t\r\n\t\t\tdelete temp;\t\t\t\t\t\t// frees the memory allocated for the right child\r\n\t\t}\r\n\t\t// case 2: one child (left child)\r\n\t\telse if (root->right == NULL) { \r\n\t\t\tNode<TElem> *temp = root->left;\t\t// saving the pointer to the left child\r\n\t\t\t\r\n\t\t\troot->data = root->left->data;\t\t// replaces the current node pointer with its left child\r\n\t\t\troot->right = root->left->right;\r\n\t\t\troot->left = root->left->left;\r\n\r\n\t\t\tif (root->left != NULL && root->left->right != NULL)\r\n\t\t\t\troot->left->right->parent = root->left;\r\n\t\t\tif (root->left != NULL && root->left->left != NULL)\r\n\t\t\t\troot->left->left->parent = root->left;\r\n\t\t\tif (root->right != NULL && root->right->left != NULL)\r\n\t\t\t\troot->right->left->parent = root->right;\r\n\t\t\tif (root->right != NULL && root->right->right != NULL)\r\n\t\t\t\troot->right->right->parent = root->right;\r\n\t\t\tdelete temp;\t\t\t\t\t\t// frees the memory alocated for the left child\r\n\t\t}\r\n\t\t// case 3: two children\r\n\t\telse {\r\n\t\t\tNode<TElem> *temp = FindMin(root->right);\r\n\t\t\troot->data = temp->data;\r\n\t\t\troot->right = del(root->right, temp->data);\t\t// recursively replaces the nodes one by one so that the old node can be freed \r\n\t\t}\r\n\t}\r\n\treturn root;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline Node<TElem>* SortedBag<TElem>::FindMin(Node<TElem>* root)\r\n{\r\n\twhile (root->left != NULL)\r\n\t\troot = root->left;\r\n\treturn root;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline void SortedBag<TElem>::destroy(Node<TElem>* root)\r\n{\r\n\t// frees the memory allocated to all the nodes below 'root', after which frees the memory allocated for 'root'\r\n\tif (root != NULL)\r\n\t{\r\n\t\tdestroy(root->left);\r\n\t\tdestroy(root->right);\r\n\t\tdelete root;\r\n\t}\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline void SortedBag<TElem>::insert(TElem data)\r\n{\r\n\t\r\n\troot = add(NULL,root, data);\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline bool SortedBag<TElem>::remove(TElem data)\r\n{\r\n\tif (search(data) == false)\r\n\t\treturn false;\r\n\t\r\n\troot = del(root, data);\r\n\treturn true;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline bool SortedBag<TElem>::search(TElem data)\r\n{\r\n\tNode<TElem>* x = find(root, data);\r\n\r\n\tif (x == NULL)\r\n\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline void SortedBag<TElem>::count(Node<TElem>* root,int &contor)\r\n{\r\n\tif (root == NULL)\r\n\t\treturn;\r\n\r\n\tcontor += 1;\r\n\r\n\tif (root->left != NULL)\r\n\t\tcount(root->left, contor);\r\n\tif (root->right != NULL)\r\n\t\tcount(root->right, contor);\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline int SortedBag<TElem>::size()\r\n{\r\n\tint c = 0;\r\n\tcount(root, c);\r\n\treturn c;\r\n}\r\n"
},
{
"alpha_fraction": 0.46095237135887146,
"alphanum_fraction": 0.46095237135887146,
"avg_line_length": 20.826086044311523,
"blob_id": "9db2b2621d6091c485a5b7ee9af52d718bdd5baa",
"content_id": "dfcffcdba620f744190f4084259f46ca0a3bd801",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1052,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 46,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Utilities/MyList.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Collections;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Utilities\r\n{\r\n public class MyList<T>:IList<T>\r\n {\r\n private List<T> elements = new List<T>();\r\n\r\n public MyList()\r\n {\r\n this.elements = new List<T>();\r\n }\r\n\r\n public void add(T e)\r\n {\r\n elements.Add(e);\r\n }\r\n public List<T> getElements()\r\n {\r\n return elements;\r\n }\r\n public void remove(T e)\r\n {\r\n elements.Remove(e);\r\n }\r\n\r\n public override string ToString()\r\n {\r\n StringBuilder buff = new StringBuilder();\r\n foreach (T el in this.elements)\r\n {\r\n buff.Append(el);\r\n buff.Append(\", \");\r\n }\r\n buff.Append(\"\\n\");\r\n return buff.ToString();\r\n }\r\n public IEnumerator GetEnumerator()\r\n {\r\n return elements.GetEnumerator();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5049116015434265,
"alphanum_fraction": 0.5140798687934875,
"avg_line_length": 29.83333396911621,
"blob_id": "c069264d7b48f907b8a038f3541854691e4fad1b",
"content_id": "b42a8bb68717e9a03bb2e47aa313817b0262b882",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3054,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 96,
"path": "/MyProjects/Graphs/Graphs/Graph 4 python/main.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import sys\r\ndef populateTheGraph():\r\n '''\r\n Constructs and returns a undirected graph\r\n '''\r\n f = open(\"test.txt\", \"r\")\r\n line = f.readline().strip()\r\n attrs = line.split(\" \")\r\n n = int(attrs[0])\r\n m = int(attrs[1])\r\n graf = Graph(n)\r\n line = f.readline().strip()\r\n while m != 0:\r\n attrs = line.split(\" \")\r\n v1 = int(attrs[0])\r\n v2 = int(attrs[1])\r\n cost = int(attrs[2])\r\n graf.graph[v1][v2] = cost\r\n graf.graph[v2][v1] = cost\r\n line = f.readline().strip()\r\n m = m - 1\r\n f.close()\r\n return graf\r\n\r\ndef start():\r\n graf = populateTheGraph()\r\n graf.PRIM()\r\nclass Graph():\r\n\r\n def __init__(self, n):\r\n self.Vertices = n\r\n self.graph = [[0 for column in range(n)] for row in range(n)]\r\n\r\n def existMinPath(self, pathTree):\r\n for i in range(1, self.Vertices):\r\n if (pathTree[i] == None):\r\n return 0\r\n return 1\r\n\r\n def printMST(self, pathTree):\r\n if (self.existMinPath(pathTree) == 0):\r\n print(\"Doesn`t exist a minimal tree path in the graf\")\r\n else:\r\n print (\"Muchie Cost\")\r\n for i in range(1, self.Vertices):\r\n print (pathTree[i], \"-\", i, \" \", self.graph[i][pathTree[i]])\r\n\r\n def printGraf(self):\r\n for i in range(0, self.Vertices):\r\n for j in range(0, self.Vertices):\r\n print(self.getItem(i, j), ' ')\r\n print(\"\\n\")\r\n\r\n def getItem(self, i, j):\r\n return self.graph[i][j]\r\n\r\n\r\n def minKey(self, costMin, inPathTree):\r\n '''\r\n Gaseste distanta cu costul minim dintre muchiile care nu au\r\n fost inca adaugate in shortest path tree\r\n '''\r\n min = sys.maxsize\r\n min_index = -1\r\n for v in range(self.Vertices):\r\n if costMin[v] < min and inPathTree[v] == False:\r\n min = costMin[v]\r\n min_index = v\r\n\r\n return min_index\r\n\r\n def PRIM(self):\r\n\r\n costMin = [sys.maxsize] * self.Vertices\r\n pathTree = [None] * self.Vertices\r\n costMin[0] = 0\r\n inPathTree = [False] * self.Vertices\r\n pathTree[0] = -1\r\n for cout in range(self.Vertices):\r\n # Pick the minimum distance vertex from the set of vertices not\r\n minVertex = self.minKey(costMin, inPathTree)\r\n # Put the minimum distance vertex in the shortest path tree\r\n inPathTree[minVertex] = True\r\n for v in range(self.Vertices):\r\n '''\r\n Daca graph[minVertex][v] nu este 0 doar daca este muchie intre minVertex si v\r\n inPathTree[v] este false pentru muchiile care nu sunt incluse inca \r\n in path\r\n '''\r\n if self.graph[minVertex][v] > 0 and inPathTree[v] == False and costMin[v] > self.graph[minVertex][v]:\r\n costMin[v] = self.graph[minVertex][v]\r\n pathTree[v] = minVertex\r\n\r\n self.printMST(pathTree)\r\n\r\nstart()"
},
{
"alpha_fraction": 0.7868020534515381,
"alphanum_fraction": 0.7868020534515381,
"avg_line_length": 22.875,
"blob_id": "b8c7d9c258e414ba06820b5ad12055c936181a3e",
"content_id": "5869749e58bc6025c432f452ad5289f8e79f6a2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 197,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 8,
"path": "/MyProjects/FP/FP/Practice Test 2/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from UI import *\r\nfrom repository import *\r\nfrom controller import *\r\nfrom domain import *\r\naddressRepo=Repository()\r\naddressController=Controller(addressRepo)\r\nui=UI(addressController)\r\nui.start()"
},
{
"alpha_fraction": 0.6079404354095459,
"alphanum_fraction": 0.6079404354095459,
"avg_line_length": 17.190475463867188,
"blob_id": "44e4283af3daa78b4dc3a0c4fc868bd29cc69cc0",
"content_id": "56d09e21df22152b9256ad7af50f15a1dd4bf455",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/domain.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"domain.h\"\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nvoid Student::setName(std::string name)\r\n{\r\n\tthis->name = name;\r\n}\r\n\r\nvoid Student::setAge(int age)\r\n{\r\n\tthis->age = age;\r\n}\r\n\r\nstd::string Student::overString()\r\n{\r\n\tstringstream ohYeah;\r\n\tohYeah << \"Aiesta are numele \" << this->getName() << \" cu ID \" << this->getID() << \" si varsta de \" << this->getAge();\r\n\treturn ohYeah.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.5888158082962036,
"alphanum_fraction": 0.5888158082962036,
"avg_line_length": 25.636363983154297,
"blob_id": "e9b5f530748c679047ec35b60ef0c4c26d7e27b4",
"content_id": "3da9c05747417bc861ab518958cc7f418381d499",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 304,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 11,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/gamer.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"gamer.h\"\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Gamer::overString()\r\n{\r\n\tstringstream ioi;\r\n\tioi << \"Aiesta are numele \" << this->getName() << \" cu ID \" << this->getID() << \" si varsta de \" << this->getAge() << \" si se joaca si \" << this->getGame();\r\n\treturn ioi.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.6292775869369507,
"alphanum_fraction": 0.6292775869369507,
"avg_line_length": 29.939393997192383,
"blob_id": "46aa4d54f164c4e385be1e4418242998bfdd7061",
"content_id": "a96d244ba82062e0fdc2a4eee820d57e820dd988",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1052,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 33,
"path": "/MyProjects/OOP/OOP/Practice 3/New/movie.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Movie {\r\nprivate:\r\n\tstd::string title;\r\n\tstd::string genre;\r\n\tint year;\r\n\tint likes;\r\n\tstd::string trailer;\r\npublic:\r\n\tMovie() :title{ \"\" }, genre{ \"\" }, year{}, likes{}, trailer{ \"\" } {}\r\n\tMovie(std::string title, std::string genre, int year, int likes, std::string trailer) :title{ title }, genre{ genre }, year{ year }, likes{ likes }, trailer{ trailer } {}\r\n\t~Movie() {}\r\n\tstd::string getTitle() { return title; }\r\n\tstd::string getGenre() { return genre; }\r\n\tint getYear() { return year; }\r\n\tint getLikes() { return likes; }\r\n\tstd::string getTrailer() { return trailer; }\r\n\tvoid setTitle(std::string title);\r\n\tvoid setGenre(std::string genre);\r\n\tvoid setYear(int year);\r\n\tvoid setLikes(int likes);\r\n\tvoid setTrailer(std::string trailer);\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n\r\n\tbool operator==(Movie m) { return (title == m.title && genre == m.genre && year == m.year && likes == m.likes && trailer == m.trailer); }\r\n\tvoid operator=(Movie m);\r\n\tvoid incLikes() { likes++; }\r\n\r\n\tvoid watch();\r\n};"
},
{
"alpha_fraction": 0.4135614037513733,
"alphanum_fraction": 0.5381795763969421,
"avg_line_length": 66.20833587646484,
"blob_id": "dc92cc8d199d7b94fc5075483392bf395d43dcd4",
"content_id": "8daf317414352e9a8ebbb795604c3fed532e4ee8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1637,
"license_type": "no_license",
"max_line_length": 327,
"num_lines": 24,
"path": "/MyProjects/FP/FP/FP Test 1/tests.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from functions import *\r\ndef testModifyDuration():\r\n myList=[[\"0001\",40,\"Mamaia\",\"Brasov\"],[\"0002\",45,\"Mamaia\",\"Luxemburg\"],[\"0003\",120,\"Cluj Napoca\",\"Alberta\"],[\"0004\",80,\"Jobou\",\"Baia Mare\"],[\"0005\",38,\"Satu Mare\",\"Constanta\"],[\"0006\",87,\"Tokyo\",\"Bucuresti\"],[\"0007\",76,\"Bucuresti\",\"Valcea\"],[\"0008\",50,\"Brasov\",\"Mamaia\"],[\"0009\",90,\"Cluj Napoca\",\"Bucuresti\"],[\"0010\",100,\"Satu Mare\",\"Bacau\"]]\r\n modifyDuration(myList,\"0001\",90)\r\n modifyDuration(myList, \"0003\", 60)\r\n modifyDuration(myList, \"0008\", 20)\r\ndef testFlightReroute():\r\n myList = [[\"0001\", 40, \"Mamaia\", \"Brasov\"], [\"0002\", 45, \"Mamaia\", \"Luxemburg\"],\r\n [\"0003\", 120, \"Cluj Napoca\", \"Alberta\"], [\"0004\", 80, \"Jobou\", \"Baia Mare\"],\r\n [\"0005\", 38, \"Satu Mare\", \"Constanta\"], [\"0006\", 87, \"Tokyo\", \"Bucuresti\"],\r\n [\"0007\", 76, \"Bucuresti\", \"Valcea\"], [\"0008\", 50, \"Brasov\", \"Mamaia\"],\r\n [\"0009\", 90, \"Cluj Napoca\", \"Bucuresti\"], [\"0010\", 100, \"Satu Mare\", \"Bacau\"]]\r\n flightReroute(myList, \"Cluj Napoca\", \"Amsterdam\")\r\n flightReroute(myList, \"Bucuresti\", \"Luxemburg\")\r\n flightReroute(myList, \"Satu Mare\", \"Hunedoara\")\r\ndef testSortFlights():\r\n myList = [[\"0001\", 40, \"Mamaia\", \"Brasov\"], [\"0002\", 45, \"Mamaia\", \"Luxemburg\"],\r\n [\"0003\", 120, \"Cluj Napoca\", \"Alberta\"], [\"0004\", 80, \"Jobou\", \"Baia Mare\"],\r\n [\"0005\", 38, \"Satu Mare\", \"Constanta\"], [\"0006\", 87, \"Tokyo\", \"Bucuresti\"],\r\n [\"0007\", 76, \"Bucuresti\", \"Valcea\"], [\"0008\", 50, \"Brasov\", \"Mamaia\"],\r\n [\"0009\", 90, \"Cluj Napoca\", \"Bucuresti\"], [\"0010\", 100, \"Satu Mare\", \"Bacau\"]]\r\n sortFlights(myList)\r\n sortFlights(myList)\r\n sortFlights(myList)\r\n"
},
{
"alpha_fraction": 0.6964285969734192,
"alphanum_fraction": 0.6964285969734192,
"avg_line_length": 16.66666603088379,
"blob_id": "62ae96af1b00dc070ffa7993475c9bb56dc8b90a",
"content_id": "fc6b01a90797dd9c3ee3e66efd91babaf8dc2ed0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 112,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 6,
"path": "/MyProjects/OOP/OOP/Practice 3/New/watchFile.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"watchFile.h\"\r\n\r\nvoid MovieFile::setFilename(std::string filename)\r\n{\r\n\tthis->filename = filename;\r\n}\r\n"
},
{
"alpha_fraction": 0.5596755743026733,
"alphanum_fraction": 0.5724217891693115,
"avg_line_length": 19.04878044128418,
"blob_id": "6a1e514a4399228333761f1f7ab1dc2ed0118ba1",
"content_id": "7fd45e6668c2f44243a4496b465ffa579a62b7ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 863,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 41,
"path": "/MyProjects/OOP/OOP/Practice - VegetablesProb/VegetablesProb/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"VegetablesProb.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"repository.h\"\r\n#include \"vegetable.h\"\r\n\r\nvoid testSort()\r\n{\r\n\tRepository<Vegetable> r{};\r\n\tVegetable v1{ \"Pot\",\"Pota\",{ \"ok\" } };\r\n\tVegetable v2{ \"Beet\",\"Pota\",{ \"ok\" } };\r\n\tr.Add(v1);\r\n\tr.Add(v2);\r\n\tr.sort();\r\n\tassert(r[0].getFamily() == \"Beet\");\r\n}\r\n\r\nvoid testFilter()\r\n{\r\n\tRepository<Vegetable> r{};\r\n\tVegetable v1{ \"Beet\",\"Pota\",{ \"ok\" } };\r\n\tVegetable v2{ \"Beet\",\"Nii\",{ \"ok\" } };\r\n\tr.Add(v1);\r\n\tr.Add(v2);\r\n\tvector<Vegetable> v = r.filter(\"Beet\");\r\n\tassert(v[0].getName() == \"Pota\");\r\n\tassert(v[1].getName() == \"Nii\");\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\ttestSort();\r\n\ttestFilter();\r\n\tRepository<Vegetable> r{ \"All.txt\" };\r\n\t\r\n\t//Vegetable v{ \"fbsaf\",\"fsabf\",{\"das\"} };\r\n\t//r.add(v);\r\n\tVegetablesProb w{ r };\r\n\tw.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.6886792182922363,
"alphanum_fraction": 0.6886792182922363,
"avg_line_length": 17.272727966308594,
"blob_id": "921274865e17eb8e4611f14168f1e01d11ba26e8",
"content_id": "750c9dc2e92ca1daab82bb0579a522915cbccd0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 214,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/IStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public interface IStmt\r\n {\r\n ProgramState execute(ProgramState state);\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6871945261955261,
"alphanum_fraction": 0.6871945261955261,
"avg_line_length": 28.147058486938477,
"blob_id": "083bcc761522cdcb926c468072ed9499876e50a4",
"content_id": "45937b70bee8a9d639f2351c2ef80d8e5f07a31e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1023,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 34,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ProgrammerRepo.h\"\r\n#include \"TaskRepo.h\"\r\n#include \"task.h\"\r\n#include \"programmer.h\"\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tProgrammerRepo<Programmer>& progs;\r\n\tTaskRepo<Task>& tasks;\r\npublic:\r\n\tController(ProgrammerRepo<Programmer>& p, TaskRepo<Task>& t) :progs{ p }, tasks{ t } {}\r\n\tController() :progs{ ProgrammerRepo<Programmer>() }, tasks{ TaskRepo<Task>() } {}\r\n\t~Controller() {}\r\n\r\n\tProgrammerRepo<Programmer>& getProgs() { return progs; }\r\n\tTaskRepo<Task>& getTasks() { return tasks; }\r\n\r\n\tvoid addTask(Task t) { tasks.add(t); }\r\n\t//Deletes an element from the given position from the task repository\r\n\t//in: int pos, the position of the element\r\n\t//out: the element from position pos was deleted from the task repository\r\n\tvoid delTask(int pos) { tasks.del(pos); }\r\n\r\n\tvoid saveTasks() { tasks.writeToFile(); }\r\n\tvoid sortTasks() { tasks.sortMe(); }\r\n\r\n\t//Updates the programmer id for\r\n\tvoid startTask(int pos, int id);\r\n\tvoid finishTask(int pos);\r\n\r\n\tController& operator=(Controller& c);\r\n};"
},
{
"alpha_fraction": 0.47251462936401367,
"alphanum_fraction": 0.4771929681301117,
"avg_line_length": 27.494253158569336,
"blob_id": "9ab5c346c375edd12449414e0c3019ff0f4cf72f",
"content_id": "e624e6ef9849da0eb891ae274351364ed8a0959e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5130,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 174,
"path": "/MyProjects/FP/FP/Assignment 5/repository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import pickle\r\n\r\nfrom domain import *\r\nclass Repository:\r\n def __init__(self):\r\n self._data=[]\r\n def __str__(self):\r\n '''\r\n\r\n out:return: the string of the repository\r\n '''\r\n s=''\r\n for i in range(len(self._data)):\r\n s+='['+str(i+1)+']. '+str(self._data[i]) + '\\n'\r\n return s\r\n def add(self,element):\r\n '''\r\n Adds an element to the repository\r\n in:param element:\r\n '''\r\n self._data.append(element)\r\n def remove(self,element):\r\n '''\r\n Removes an elemen from the repository\r\n in:param element:\r\n '''\r\n for i in range(len(self._data)):\r\n if self._data[i]==element:\r\n self._data.pop(i)\r\n def removeIndex(self,index):\r\n '''\r\n Removes an index from the repository\r\n in:param index:\r\n '''\r\n if index>=0 or index <len(self._data):\r\n self._data.pop(index)\r\n def getAll(self):\r\n '''\r\n Returns the repository\r\n out :return:self.__data\r\n '''\r\n return self._data\r\n def get(self,index):\r\n '''\r\n Returns the element from the given index\r\n in:param index:\r\n out:return:element\r\n '''\r\n return self._data[index]\r\n def findElement(self,element):\r\n '''\r\n Returns the index of the element, -1 if not found\r\n in:param element:\r\n out:return: index\r\n '''\r\n for i in range(len(self._data)):\r\n if self._data[i]==element:\r\n return i\r\n return -1\r\n\r\n def update(self,old,new):\r\n '''\r\n Updates the old element with the new element\r\n :param old:\r\n :param new:\r\n :return:\r\n '''\r\n for i in range(len(self._data)):\r\n if self._data[i]==old:\r\n self._data[i]=new\r\n def groupList(self,group):\r\n '''\r\n Returns a list of the entire group\r\n in:param group:\r\n out:return:lst\r\n '''\r\n lst=[]\r\n for i in range(len(self._data)):\r\n if self._data[i].getGroup()==group:\r\n lst.append(self._data[i])\r\n return lst\r\n def giveAssignmentToStudent(self,student,assignment):\r\n '''\r\n Gives an assignment to a student\r\n in:param student:\r\n in:param assignment:\r\n :return:\r\n '''\r\n ok=0\r\n for i in range(len(self._data)):\r\n ok=1\r\n if self._data[i].getStudent()==student and self._data[i].isFound(assignment)==False:\r\n self._data[i].addTo(assignment)\r\n else:\r\n a = StudentAssignments(student)\r\n a.addTo(assignment)\r\n self._data.append(a)\r\n if ok==0:\r\n a=StudentAssignments(student)\r\n a.addTo(assignment)\r\n self._data.append(a)\r\n def giveAssignmentToGroup(self,group,assignment,lst):\r\n '''\r\n Gives an assignment to an entire group\r\n in:param group:\r\n in:param assignment:\r\n :return:\r\n '''\r\n for i in range(len(lst)):\r\n ok=-1\r\n for j in range(len(self._data)):\r\n if self._data[j].getStudent==lst[i]:\r\n ok=j\r\n if self._data[ok].isFound(assignment)==False:\r\n ok=-1\r\n if ok!=-1:\r\n self._data[ok].addTo(assignment)\r\n elif self._data[ok].isFound(assignment)==False:\r\n a=StudentAssignments(lst[i])\r\n a.addTo(assignment)\r\n self._data.append(a)\r\n if len(self._data)==0:\r\n for i in range(len(lst)):\r\n a = StudentAssignments(lst[i])\r\n a.addTo(assignment)\r\n self._data.append(a)\r\n\r\nclass PickleRepository(Repository):\r\n def __init__(self,fileName):\r\n Repository.__init__(self)\r\n self.__fileName=fileName\r\n self.__load()\r\n def add(self,el):\r\n Repository.add(self,el)\r\n self.__store()\r\n def remove(self,index):\r\n Repository.removeIndex(self,index)\r\n self.__store()\r\n def update(self,old,new):\r\n Repository.update(self,old,new)\r\n self.__store()\r\n def __load(self):\r\n file=open(self.__fileName,\"rb\")\r\n try:\r\n self._data=pickle.load(file)\r\n except EOFError:\r\n self._data=[]\r\n except Exception as exc:\r\n raise exc\r\n finally:\r\n file.close()\r\n def __store(self):\r\n file=open(self.__fileName,\"wb\")\r\n pickle.dump(self._data, file)\r\n file.close()\r\n\r\ndef update_gap(gap):\r\n gap = (gap * 10) / 13\r\n if gap == 9 or gap == 10:\r\n gap = 11\r\n return int(max(1, gap))\r\n\r\ndef combsort(x):\r\n gap = len(x)\r\n swapped = True\r\n if gap < 2:\r\n return\r\n while gap > 1 or swapped:\r\n gap = update_gap(gap)\r\n swapped = False\r\n for i in range(0, len(x) - gap):\r\n if x[i] > x[i + gap]:\r\n x[i], x[i + gap] = x[i + gap], x[i]\r\n swapped = True"
},
{
"alpha_fraction": 0.6687023043632507,
"alphanum_fraction": 0.6687023043632507,
"avg_line_length": 15.289473533630371,
"blob_id": "86b94acdb4cfa201a22089071df274a611573eb4",
"content_id": "70d803e31917adda724c0cf741087224697e3996",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 655,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 38,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Admin.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets\\QMainWindow>\r\n#include \"ui_admin.h\"\r\n#include \"controller.h\"\r\n#include \"repository.h\"\r\n#include \"movie.h\"\r\n#include \"operation.h\"\r\n#include \"redo.h\"\r\n#include \"undo.h\"\r\n\r\nclass Admin :public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tAdmin(Repository r,QWidget *parent = Q_NULLPTR);\r\n\t~Admin();\r\n\tvoid readFromFile();\r\nprivate:\r\n\tRepository repo;\r\n\tRepository flt;\r\n\tUi::AdminWindow ui;\r\n\tOperation* und;\r\n\tOperation* red;\r\n\r\n\r\n\tvoid populate();\r\n\tint getSelectedIndex();\r\n\tprivate slots:\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid add();\r\n\tvoid del();\r\n\tvoid update();\r\n\tvoid filter();\r\n\tvoid undoFcT();\r\n\tvoid redoFcT();\r\n};"
},
{
"alpha_fraction": 0.6912028789520264,
"alphanum_fraction": 0.6912028789520264,
"avg_line_length": 16.566667556762695,
"blob_id": "eb1dd92131e6c10ae074e7216b08c43295fdd491",
"content_id": "f81e9f6d7f85ed80b6805baed2a83bd541e217da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 557,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 30,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/MainTeacher.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_HeadWindow.h\"\r\n#include \"SomeTeacher.h\"\r\n#include \"controller.h\"\r\n#include <vector>\r\n\r\nclass MainTeacher : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tMainTeacher(Controller& c,QWidget *parent = Q_NULLPTR);\r\n\t~MainTeacher();\r\nprivate:\r\n\tUi::HeadWindow ui;\r\n\tController& controller;\r\n\tstd::vector<SomeTeacher*> allWindows;\r\n\r\n\tvoid populate();\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid modifyAll();\r\n\tvoid showAll();\r\n\tint getSelectedIndex();\r\n\r\n\tprivate slots:\r\n\tvoid add();\r\n\tvoid del();\r\n};\r\n"
},
{
"alpha_fraction": 0.682087779045105,
"alphanum_fraction": 0.682087779045105,
"avg_line_length": 18.119047164916992,
"blob_id": "e8ba5ac548c811b00341ed0c877b34b2367948d6",
"content_id": "9f0db81e03ab6787e0329c052e66e56c63c235de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 843,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 42,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/User.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets\\QMainWindow>\r\n#include \"ui_user.h\"\r\n#include \"controller.h\"\r\n#include \"operation.h\"\r\n#include \"redo.h\"\r\n#include \"undo.h\"\r\n\r\nclass User :public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tUser(Controller c,QWidget *parrent = Q_NULLPTR);\r\n\t~User();\r\n\tRepository getRepo() { return contro.getAll(); }\r\n\tRepository getList() { return contro.getList(); }\r\n\tvoid readFromFile();\r\nprivate:\r\n\tUi::UserWindow ui;\r\n\tController contro;\r\n\tRepository filter{};\r\n\tOperation* und;\r\n\tOperation* red;\r\n\tint lastDeleted;\r\n\r\n\tint getSelectedIndex();\r\n\tvoid connectSignalsAndSlots();\r\n\tvoid populateWatchList();\r\n\tvoid populateFilter();\r\n\tprivate slots:\r\n\tvoid filterMovies();\r\n\tvoid addMovie();\r\n\tvoid delMovie();\r\n\tvoid likeMovie();\r\n\tvoid showCSV();\r\n\tvoid showHTML();\r\n\tvoid nextMovie();\r\n\tvoid undoFct();\r\n\tvoid redoFct();\r\n};"
},
{
"alpha_fraction": 0.6200510859489441,
"alphanum_fraction": 0.6206896305084229,
"avg_line_length": 28.705883026123047,
"blob_id": "7d2e5b993d206856388984e2347b80afe9d67639",
"content_id": "7b5439bcc547ac8a1f17da5745352b23b5a8b761",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1566,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 51,
"path": "/MyProjects/MAP/Practical Exam/Procedures/src/Model/Statements/Call.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Pair;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.Dictionary;\r\nimport Model.Utilities.IDictionary;\r\n\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport Exception.VariableNotDefined;\r\nimport Model.Utilities.IStack;\r\n\r\npublic class Call implements IStmt {\r\n private String fname;\r\n private List<IExpr> vars;\r\n private IStmt stmt;\r\n\r\n public Call(String name,List<IExpr> v){fname=name;vars=v;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state)throws IOException {\r\n if(!state.getProc().exists(fname)) throw new VariableNotDefined(\"Procedure '\"+fname+\"' does not exist!\");\r\n IStack<IDictionary<String, Integer>> dic=state.getSyms();\r\n IStack<IStmt> stack=state.getStack();\r\n IDictionary<Integer, Integer> heap=state.getHeap();\r\n Pair pr =state.getProc().getValue(fname);\r\n stmt=pr.stmt;\r\n List<String> v=pr.list;\r\n List<Integer> val=new ArrayList<>();\r\n for(IExpr exp:vars){\r\n val.add(exp.evaluate(dic,heap));\r\n }\r\n IDictionary<String, Integer> sym = new Dictionary<String, Integer>();\r\n int i=0;\r\n for(String stg:v){\r\n sym.setValue(stg,val.get(i));\r\n i++;\r\n }\r\n dic.add(sym);\r\n IStmt ret=new Return();\r\n stack.add(ret);\r\n stack.add(stmt);\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"call \"+fname+\"(\"+vars+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6561216115951538,
"alphanum_fraction": 0.6709120869636536,
"avg_line_length": 33.27536392211914,
"blob_id": "bb5a94d9375f07986c0ec6b48db55544d2f0ccd4",
"content_id": "65bc591ee1f0a2fa58bc5e42a71dd2c8bfea412a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2434,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 69,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/GeneratedFiles/ui_OOPpracticalex1.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'OOPpracticalex1.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_OOPPRACTICALEX1_H\r\n#define UI_OOPPRACTICALEX1_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QMenuBar>\r\n#include <QtWidgets/QStatusBar>\r\n#include <QtWidgets/QToolBar>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_OOPpracticalex1Class\r\n{\r\npublic:\r\n QMenuBar *menuBar;\r\n QToolBar *mainToolBar;\r\n QWidget *centralWidget;\r\n QStatusBar *statusBar;\r\n\r\n void setupUi(QMainWindow *OOPpracticalex1Class)\r\n {\r\n if (OOPpracticalex1Class->objectName().isEmpty())\r\n OOPpracticalex1Class->setObjectName(QStringLiteral(\"OOPpracticalex1Class\"));\r\n OOPpracticalex1Class->resize(600, 400);\r\n menuBar = new QMenuBar(OOPpracticalex1Class);\r\n menuBar->setObjectName(QStringLiteral(\"menuBar\"));\r\n OOPpracticalex1Class->setMenuBar(menuBar);\r\n mainToolBar = new QToolBar(OOPpracticalex1Class);\r\n mainToolBar->setObjectName(QStringLiteral(\"mainToolBar\"));\r\n OOPpracticalex1Class->addToolBar(mainToolBar);\r\n centralWidget = new QWidget(OOPpracticalex1Class);\r\n centralWidget->setObjectName(QStringLiteral(\"centralWidget\"));\r\n OOPpracticalex1Class->setCentralWidget(centralWidget);\r\n statusBar = new QStatusBar(OOPpracticalex1Class);\r\n statusBar->setObjectName(QStringLiteral(\"statusBar\"));\r\n OOPpracticalex1Class->setStatusBar(statusBar);\r\n\r\n retranslateUi(OOPpracticalex1Class);\r\n\r\n QMetaObject::connectSlotsByName(OOPpracticalex1Class);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *OOPpracticalex1Class)\r\n {\r\n OOPpracticalex1Class->setWindowTitle(QApplication::translate(\"OOPpracticalex1Class\", \"OOPpracticalex1\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class OOPpracticalex1Class: public Ui_OOPpracticalex1Class {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_OOPPRACTICALEX1_H\r\n"
},
{
"alpha_fraction": 0.6098518371582031,
"alphanum_fraction": 0.6182094216346741,
"avg_line_length": 23.639610290527344,
"blob_id": "f7f0ae817e4a397360fad77912f7008c63463c97",
"content_id": "0792c1f4568955bbad8542a955ad22d96f859a40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7897,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 308,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Admin.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Admin.h\"\r\n#include <QtWidgets\\qmessagebox.h>\r\n#include <vector>\r\n#include <QKeySequence>\r\n#include <QShortcut>\r\n#include <QtWidgets\\QLineEdit>\r\n\r\n\r\nAdmin::Admin(Repository r,QWidget *parent)\r\n\t:repo{ r }, flt{ r }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populate();\r\n\tOperation* u1 = new Undo(r);\r\n\tOperation* u2 = new Redo(r);\r\n\tund = u1;\r\n\tred = u2;\r\n}\r\n\r\nAdmin::~Admin()\r\n{\r\n\tdelete und;\r\n\tdelete red;\r\n}\r\n\r\nvoid Admin::readFromFile()\r\n{\r\n\tthis->repo.clr();\r\n\tthis->repo.readFromFile();\r\n\tthis->flt = this->repo;\r\n\tthis->populate();\r\n}\r\n\r\nvoid Admin::populate()\r\n{\r\n\tif (ui.MovieList->count() != 0)\r\n\t\tui.MovieList->clear();\r\n\tfor (auto m : flt.getAll())\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.MovieList->addItem(listItemWidget);\r\n\t}\r\n\tif (flt.getLenght() > 0)\r\n\t\tui.MovieList->setCurrentRow(0);\r\n}\r\n\r\nint Admin::getSelectedIndex()\r\n{\r\n\tif (ui.MovieList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.MovieList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\tui.TitleLine->clear();\r\n\t\tui.GenreLine->clear();\r\n\t\tui.YearLine->clear();\r\n\t\tui.LikesLine->clear();\r\n\t\tui.TrailerLine->clear();\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid Admin::add()\r\n{\r\n\tint t1 = ui.TitleLine->text().length();\r\n\tint g1 = ui.GenreLine->text().length();\r\n\tint y1 = ui.YearLine->text().length();\r\n\tint l1 = ui.LikesLine->text().length();\r\n\tint tr1 = ui.TrailerLine->text().length();\r\n\r\n\tstd::string t = ui.TitleLine->text().toStdString();\r\n\tstd::string g = ui.GenreLine->text().toStdString();\r\n\tint y = ui.YearLine->text().toInt();\r\n\tint l = ui.LikesLine->text().toInt();\r\n\tstd::string tr = ui.TrailerLine->text().toStdString();\r\n\tMovie m{ t,g,y,l,tr };\r\n\r\n\tui.TitleLine->clear();\r\n\tui.GenreLine->clear();\r\n\tui.YearLine->clear();\r\n\tui.LikesLine->clear();\r\n\tui.TrailerLine->clear();\r\n\r\n\tif (t1 == 0 || g1 == 0 || y1 == 0 || l1 == 0 || tr1 == 0)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"Fill in the text lines to add a movie!\"));\r\n\t\treturn;\r\n\t}\r\n\r\n\tint f = this->repo.findByTitle(m.getTitle());\r\n\tif (f != -1)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"You cannot have 2 movies with the same title!\"));\r\n\t\treturn;\r\n\t}\r\n\r\n\trepo.add(m);\r\n\tflt.add(m);\r\n\tund->setE(repo.getAll());\r\n\tred->setE(repo.getAll());\r\n\tthis->populate();\r\n\tOperationElement ope{ m,m,\"delete\" };\r\n\tthis->und->push(ope);\r\n}\r\n\r\nvoid Admin::del()\r\n{\r\n\tif (this->repo.getLenght() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Nothing to delete!\"));\r\n\t\treturn;\r\n\t}\r\n\tint i = this->getSelectedIndex();\r\n\tstd::string s = this->flt[i].getTitle();\r\n\tflt.del(i);\r\n\tint k = this->repo.findByTitle(s);\r\n\tOperationElement ope{ this->repo[k],this->repo[k],\"add\" };\r\n\trepo.del(k);\r\n\tund->setE(repo.getAll());\r\n\tred->setE(repo.getAll());\r\n\tthis->populate();\r\n\tthis->und->push(ope);\r\n}\r\n\r\nvoid Admin::update()\r\n{\r\n\tstd::string t = ui.TitleLine->text().toStdString();\r\n\tstd::string g = ui.GenreLine->text().toStdString();\r\n\tint y = ui.YearLine->text().toInt();\r\n\tint l = ui.LikesLine->text().toInt();\r\n\tstd::string tr = ui.TrailerLine->text().toStdString();\r\n\tstd::string ot = ui.UpdateTitleLine->text().toStdString();\r\n\r\n\tint t1 = ui.TitleLine->text().length();\r\n\tint g1 = ui.GenreLine->text().length();\r\n\tint y1 = ui.YearLine->text().length();\r\n\tint l1 = ui.LikesLine->text().length();\r\n\tint tr1 = ui.TrailerLine->text().length();\r\n\tint ot1 = ui.UpdateTitleLine->text().length();\r\n\r\n\tui.TitleLine->clear();\r\n\tui.GenreLine->clear();\r\n\tui.YearLine->clear();\r\n\tui.LikesLine->clear();\r\n\tui.TrailerLine->clear();\r\n\tui.UpdateTitleLine->clear();\r\n\r\n\tif (t1 == 0 || g1 == 0 || y1 == 0 || l1 == 0 || tr1 == 0)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"Fill in the text lines to update a movie!\"));\r\n\t\treturn;\r\n\t}\r\n\r\n\tint f = this->repo.findByTitle(ot);\r\n\tif (f == -1)\r\n\t{\r\n\t\tQMessageBox messageBox;\r\n\t\tmessageBox.critical(0, \"error\", QString::fromStdString(\"No movie found with that title!\"));\r\n\t\treturn;\r\n\t}\r\n\r\n\tMovie m{ t,g,y,l,tr };\r\n\tMovie m1 = this->repo[this->repo.findByTitle(ot)];\r\n\tOperationElement ope{ m1, m, \"update\" };\r\n\tthis->und->push(ope);\r\n\r\n\trepo.update(ot, t, g, y, l, tr);\r\n\tund->setE(repo.getAll());\r\n\tred->setE(repo.getAll());\r\n\tflt.update(ot, t, g, y, l, tr);\r\n\tthis->populate();\r\n}\r\n\r\nvoid Admin::filter()\r\n{\r\n\tund->setE(repo.getAll());\r\n\tred->setE(repo.getAll());\r\n\tthis->flt = this->repo;\r\n\tstd::string t = ui.FilterLine->text().toStdString();\r\n\tstd::vector<Movie> r=this->flt.filterRepo(t);\r\n\tthis->flt.setElems(r);\r\n\tthis->populate();\r\n}\r\n\r\nvoid Admin::undoFcT()\r\n{\r\n\tif (this->und->len() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Nothing to undo!\"));\r\n\t\treturn;\r\n\t}\r\n\tOperationElement e = this->und->get();\r\n\tif (e.getOperation() == \"add\")\r\n\t{\r\n\t\te.setOperation(\"delete\");\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\trepo.setElems(und->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"delete\")\r\n\t{\r\n\t\te.setOperation(\"add\");\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\trepo.setElems(und->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"update\")\r\n\t{\r\n\t\tMovie m = e.getMovie();\r\n\t\tMovie m1 = e.getMovieUpdate();\r\n\t\te.setMovie(m1);\r\n\t\te.setMovieUpdate(m);\r\n\t\tthis->red->push(e);\r\n\t\tthis->und->execute();\r\n\t\tred->setE(und->getRepo().getAll());\r\n\t\trepo.setElems(und->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\nvoid Admin::redoFcT()\r\n{\r\n\tif (this->red->len() == 0)\r\n\t{\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"Nothing to redo!\"));\r\n\t\treturn;\r\n\t}\r\n\tOperationElement e = this->red->get();\r\n\tif (e.getOperation() == \"add\")\r\n\t{\r\n\t\te.setOperation(\"delete\");\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\trepo.setElems(red->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"delete\")\r\n\t{\r\n\t\te.setOperation(\"add\");\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\trepo.setElems(red->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n\tif (e.getOperation() == \"update\")\r\n\t{\r\n\t\tMovie m = e.getMovie();\r\n\t\tMovie m1 = e.getMovieUpdate();\r\n\t\te.setMovie(m1);\r\n\t\te.setMovieUpdate(m);\r\n\t\tthis->und->push(e);\r\n\t\tthis->red->execute();\r\n\t\tund->setE(red->getRepo().getAll());\r\n\t\trepo.setElems(red->getRepo().getAll());\r\n\t\tthis->flt = this->repo;\r\n\t\tthis->populate();\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\nvoid Admin::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.MovieList, SIGNAL(itemSelectionChanged()), this, SLOT(listItemChanged()));\r\n\r\n\tQObject::connect(this->ui.AddButton, SIGNAL(clicked()), this, SLOT(add()));\r\n\r\n\tQObject::connect(this->ui.DeleteButton, SIGNAL(clicked()), this, SLOT(del()));\r\n\r\n\tQObject::connect(this->ui.UpdateButton, SIGNAL(clicked()), this, SLOT(update()));\r\n\r\n\tQObject::connect(this->ui.UndoButton, SIGNAL(clicked()), this, SLOT(undoFcT()));\r\n\r\n\tQObject::connect(this->ui.RedoButton, SIGNAL(clicked()), this, SLOT(redoFcT()));\r\n\t\r\n\tQObject::connect(this->ui.FilterLine, SIGNAL(textChanged(const QString&)), this, SLOT(filter()));\r\n\r\n\tQShortcut *shortcut1 =new QShortcut(QKeySequence(\"Ctrl+Z\"),this);\r\n\tQShortcut *shortcut2 = new QShortcut(QKeySequence(\"Ctrl+Y\"), this);\r\n\t\r\n\tQObject::connect(shortcut1, SIGNAL(activated()), this, SLOT(undoFcT()));\r\n\tQObject::connect(shortcut2, SIGNAL(activated()), this, SLOT(redoFcT()));\r\n}\r\n"
},
{
"alpha_fraction": 0.5801281929016113,
"alphanum_fraction": 0.5811966061592102,
"avg_line_length": 12.369231224060059,
"blob_id": "e4e5eb172c030b37289789a79e055b2db5728a64",
"content_id": "393d3cd1fc89fcd543db7a8b11e09901894c07b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 936,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 65,
"path": "/MyProjects/OOP/OOP/Written 2/OOP written ex1/Stack.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <exception>\r\n#include <sstream>\r\n\r\ntemplate <typename T>\r\nclass Stack\r\n{\r\nprivate:\r\n\tint cap;\r\n\tint len;\r\n\tT* elems;\r\npublic:\r\n\tStack(int c);\r\n\t~Stack();\r\n\r\n\tint getMaxCapacity() { return cap; }\r\n\r\n\tStack& operator=(T* v);\r\n\tT* operator+(T e);\r\n\r\n\tT pop();\r\n};\r\n\r\ntemplate<typename T>\r\ninline Stack<T>::Stack(int c)\r\n{\r\n\tlen = 0;\r\n\tcap = c;\r\n\telems = new T[c];\r\n}\r\n\r\ntemplate<typename T>\r\ninline Stack<T>::~Stack()\r\n{\r\n\tdelete[] elems;\r\n}\r\n\r\ntemplate<typename T>\r\ninline Stack<T> & Stack<T>::operator=(T * v)\r\n{\r\n\tthis->elems = v;\r\n\treturn *this;\r\n}\r\n\r\ntemplate<typename T>\r\ninline T * Stack<T>::operator+(T e)\r\n{\r\n\tif (len == cap)\r\n\t{\r\n\t\tstd::stringstream errMsg;\r\n\t\terrMsg << \"Stack is full!\";\r\n\t\tthrow std::exception(errMsg.str().c_str());\r\n\t}\r\n\tthis->elems[len] = e;\r\n\tlen++;\r\n\treturn this->elems;\r\n}\r\n\r\ntemplate<typename T>\r\ninline T Stack<T>::pop()\r\n{\r\n\tlen--;\r\n\treturn elems[len];\r\n}\r\n\r\n"
},
{
"alpha_fraction": 0.5835095047950745,
"alphanum_fraction": 0.5877378582954407,
"avg_line_length": 16.920000076293945,
"blob_id": "c455404cd0484a88fb2b32bf7b084b80c2b08166",
"content_id": "c3cc70987dcc6d3511fcc47c114e7e49a9c15c88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 473,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 25,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/Repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Repository.h\"\r\n\r\nvoid Repository::add(Pilot p)\r\n{\r\n\tthis->elems.push_back(p);\r\n}\r\n\r\nvoid Repository::del(int pos)\r\n{\r\n\tif (pos < 0 || pos >= elems.size())\r\n\t\treturn;\r\n\tthis->elems.erase(elems.begin() + pos);\r\n}\r\n\r\nvoid Repository::update(int id, string name, int age, int flights)\r\n{\r\n\tfor (int i=0;i<elems.size();i++)\r\n\t\tif (elems[i].getID() == id)\r\n\t\t{\r\n\t\t\telems[i].setAge(age);\r\n\t\t\telems[i].setName(name);\r\n\t\t\telems[i].setFlights(flights);\r\n\t\t\tbreak;\r\n\t\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.43788301944732666,
"alphanum_fraction": 0.44958215951919556,
"avg_line_length": 29.526315689086914,
"blob_id": "51ee2985c4027b1dbb03c8eec6d3460486bdb466",
"content_id": "d2878256b59132a72a4395afa3e93501dc109a13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1795,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 57,
"path": "/MyProjects/FP/FP/Practice Test 2/controller.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nfrom math import sqrt\r\nclass Controller:\r\n def __init__(self,repo=Repository()):\r\n self.__repo=repo\r\n def __str__(self):\r\n '''\r\n Overwrites the str function for this class\r\n :return:\r\n '''\r\n s=''\r\n for i in range(len(self.__repo.getAll())):\r\n s=s+str(self.__repo.get(i))+'\\n'\r\n return s\r\n def add(self,el):\r\n '''\r\n Adds an element to the list if it is valid\r\n in:param el:\r\n :return:\r\n '''\r\n ok=1\r\n for i in range(len(self.__repo.getAll())):\r\n if len(self.__repo.getAll()) and self.__repo.get(i).getID()==el.getID():\r\n print(\"ID already exists!\")\r\n ok=0\r\n\r\n if int(el.getID())==el.getID() and el.GetID()<=0:\r\n print(\"ID is not valid!\")\r\n ok=0\r\n if len(el.getName())<3:\r\n print(\"Name is too short!\")\r\n ok=0\r\n if el.getX()<0 and el.getX()>100:\r\n print(\"Coordinate not valid!\")\r\n ok=0\r\n if el.getY()<0 and el.getY()>100:\r\n print(\"Coordinate not valid!\")\r\n ok = 0\r\n if ok ==1:\r\n self.__repo.add(el)\r\n def distanceAddress(self,d,x,y):\r\n '''\r\n Returns a list with all the addresses that are far from the given position by d\r\n in:param d:\r\n in:param x:\r\n in:param y:\r\n :return:\r\n '''\r\n lst=[]\r\n for i in range(len(self.__repo.getAll())):\r\n m=(self.__repo.get(i).getX()-x)**2\r\n n=(self.__repo.get(i).getY()-y)**2\r\n d1=sqrt(m)+sqrt(n)\r\n if d1<=d:\r\n lst.append(self.__repo.get(i))\r\n for i in range(len(lst)):\r\n print(lst[i])"
},
{
"alpha_fraction": 0.7020833492279053,
"alphanum_fraction": 0.7020833492279053,
"avg_line_length": 23.3157901763916,
"blob_id": "df7ec47ed22b7f4ac60bc0486a4af756770981e5",
"content_id": "7740f8c147d6e8c31954cec1f15414cb30a0d2bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 960,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 38,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/ProgrammerWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ui_ProgrammerWindow.h\"\r\n#include <QtWidgets\\QMainWindow>\r\n#include \"controller.h\"\r\n#include <vector>\r\n\r\nclass ProgrammerWindow : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tProgrammerWindow(Controller& c, Programmer p, std::vector<ProgrammerWindow*> v, QWidget *parent = Q_NULLPTR);\r\n\tProgrammerWindow(Controller& c, Programmer p, QWidget *parent = Q_NULLPTR);\r\n\tProgrammerWindow(QWidget *parent = Q_NULLPTR);\r\n\t~ProgrammerWindow();\r\n\tvoid populate();\r\n\tvoid showIt();\r\n\r\n\tvoid setContro(Controller& c) { controller = c; }\r\n\tvoid setProg(Programmer p) { prog = p; }\r\n\tvoid setAll(std::vector<ProgrammerWindow*> v) { allWindows = v; }\r\nprivate:\r\n\tUi::MyWindow ui;\r\n\tController& controller;\r\n\tProgrammer prog;\r\n\tstd::vector<ProgrammerWindow*> allWindows;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tint getSelectedIndex();\r\n\tvoid modifyAll();\r\n\r\n\tprivate slots:\r\n\tvoid add();\r\n\tvoid start();\r\n\tvoid done();\r\n\tvoid del();\r\n\tvoid checkDel();\r\n};"
},
{
"alpha_fraction": 0.5271637439727783,
"alphanum_fraction": 0.6028475165367126,
"avg_line_length": 25.255102157592773,
"blob_id": "c2b6b82f4f04442926d0cbecba20b66d21c849b4",
"content_id": "a36a7007e3d28f62ffab2c998e2724e0b4136503",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2669,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 98,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/tests.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"tests.h\"\r\n#include <assert.h>\r\n\r\nvoid TestAddDyn()\r\n{\r\n\tVector v{};\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tv.add(m);\r\n\tassert(v.get(0).getTitle()== \"Film\");\r\n\tassert(v.get(0).getGenre() == \"awesome\");\r\n\tassert(v.get(0).getYear() == 2018);\r\n\tassert(v.get(0).getLikes() == 20000);\r\n}\r\n\r\nvoid TestAddRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m);\r\n\tassert(r.getMovies().get(0).getYear() == 2018);\r\n\tassert(r.getMovies().get(0).getLikes() == 20000);\r\n}\r\n\r\nvoid TestDelRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m);\r\n\tassert(r.getMovies().get(0).getYear() == 2018);\r\n\tassert(r.getMovies().get(0).getLikes() == 20000);\r\n\tr.addMovie(m);\r\n\tr.getMovies().del(0);\r\n\tassert(r.getMovies().getLenght() == 1);\r\n}\r\n\r\nvoid TestUpdateRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m1);\r\n\tassert(r.getMovies().get(0).getYear() == 2018);\r\n\tassert(r.getMovies().get(0).getLikes() == 20000);\r\n\tr.updateMovie(\"Film\", \"Film\", \"awesome\", 2018, 20000, \"more\");\r\n}\r\n\r\nvoid TestAddController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies().get(0).getYear() == 2018);\r\n\tassert(c.getRepo().getMovies().get(0).getLikes() == 20000);\r\n}\r\n\r\nvoid TestDelController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies().get(0).getYear() == 2018);\r\n\tassert(c.getRepo().getMovies().get(0).getLikes() == 20000);\r\n\tc.delMovieFromRepo(\"Film\");\r\n}\r\n\r\nvoid TestUpdateController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tMovie m2{ \"Film\",\"awesome\",2018,20000,\"more\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies().get(0).getYear() == 2018);\r\n\tassert(c.getRepo().getMovies().get(0).getLikes() == 20000);\r\n\tc.updateMovieToRepo(\"Film\", \"Film\", \"awesome\", 2018, 20000, \"more\");\r\n}\r\n\r\nvoid Test::Tests()\r\n{\r\n\tTest::TestController();\r\n\tTest::TestRepo();\r\n}\r\n\r\nvoid Test::TestRepo()\r\n{\r\n\tTestAddDyn();\r\n\tTestAddRepo();\r\n\tTestDelRepo();\r\n\tTestUpdateRepo();\r\n}\r\n\r\nvoid Test::TestController()\r\n{\r\n\tTestAddController();\r\n\tTestDelController();\r\n\tTestUpdateController();\r\n}"
},
{
"alpha_fraction": 0.5411173701286316,
"alphanum_fraction": 0.5775266885757446,
"avg_line_length": 16.33333396911621,
"blob_id": "6c066dd5730310a98b79ebf1128c3f5d431c6914",
"content_id": "40e88b6d98af057ad8adb7fda90a9c53840fab4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1593,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 87,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/tests.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"tests.h\"\r\n#include <iostream>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\nvoid Tests::testSearch() {\r\n\tSortedBag<int> bag{ \">\" };\r\n\r\n\tbag.insert(5);\r\n\tbag.insert(10);\r\n\tbag.insert(3);\r\n\tbag.insert(4);\r\n\tbag.insert(1);\r\n\tbag.insert(11);\r\n\tassert(bag.search(5) == true);\r\n\tassert(bag.search(4) == true);\r\n\tassert(bag.search(2) == false);\r\n\tassert(bag.search(1) == true);\r\n\tassert(bag.search(12) == false);\r\n}\r\n\r\nvoid Tests::testRemove() {\r\n\r\n\tSortedBag<int> bag{ \">\" };\r\n\r\n\tbag.insert(5);\r\n\tbag.insert(10);\r\n\tbag.insert(3);\r\n\tbag.insert(4);\r\n\tbag.insert(1);\r\n\tbag.insert(11);\r\n\tassert(bag.remove(5) == true);\r\n\tassert(bag.remove(123) == false);\r\n\tassert(bag.remove(12) == false);\r\n\tassert(bag.remove(1) == true);\r\n\tassert(bag.remove(11) == true);\r\n}\r\n\r\nvoid Tests::testSize() {\r\n\r\n\tSortedBag<int> bag{ \">\" };\r\n\r\n\tbag.insert(5);\r\n\tbag.insert(10);\r\n\tbag.insert(3);\r\n\tbag.insert(4);\r\n\tbag.insert(1);\r\n\tbag.insert(11);\r\n\tassert(bag.size() == 6);\r\n\tassert(bag.remove(5) == true);\r\n\tassert(bag.size() == 5);\r\n\tassert(bag.remove(10) == true);\r\n\tassert(bag.remove(3) == true);\r\n\tassert(bag.remove(4) == true);\r\n\tassert(bag.size() == 2);\r\n}\r\n\r\nvoid Tests::testIterator()\r\n{\r\n\tSortedBag<int> bag{ \">\" };\r\n\r\n\tbag.insert(5);\r\n\tbag.insert(10);\r\n\tbag.insert(3);\r\n\tbag.insert(4);\r\n\tbag.insert(1);\r\n\tbag.insert(11);\r\n\tIterator<int> it = bag.iterator();\r\n\tit.next();\r\n\tassert(it.getValue()==3);\r\n\tint k = 0;\r\n\twhile (k < bag.size() - 1)\r\n\t{\r\n\t\tk++;\r\n\t\tit.next();\r\n\t}\r\n\tif (it.isValid() == NULL)\r\n\t\tk++;\r\n}\r\n\r\nvoid Tests::testAll() {\r\n\ttestSearch();\r\n\ttestRemove();\r\n\ttestSize();\r\n\ttestIterator();\r\n}"
},
{
"alpha_fraction": 0.6236363649368286,
"alphanum_fraction": 0.6236363649368286,
"avg_line_length": 24.285715103149414,
"blob_id": "b0cb4f4dd5d30906e2f8d2634a3089fcdccbd67f",
"content_id": "050db8baa46f6d911b7607244362fe8b080d2e6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 550,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 21,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/vegetable.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <vector>\r\n#include <string>\r\n\r\nclass Vegetable {\r\nprivate:\r\n\tstd::string family;\r\n\tstd::string name;\r\n\tstd::vector<std::string> parts{};\r\npublic:\r\n\tVegetable() :family{ \"\" }, name{ \"\" } {}\r\n\tVegetable( std::string fam,std::string nam, std::vector<std::string> par ) : family{ fam }, name{ nam }, parts{ par } {}\r\n\t~Vegetable() {}\r\n\r\n\tstd::string getFamily() { return family; }\r\n\tstd::string getName() { return name; }\r\n\tstd::vector<std::string> getParts() { return parts; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.6425120830535889,
"alphanum_fraction": 0.6425120830535889,
"avg_line_length": 21.11111068725586,
"blob_id": "1aa978cdff21320df78712b8ad1b9a1e9801de48",
"content_id": "a0255383357121347f2d5003545a243216796d7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 414,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 18,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n#include <vector>\r\n#include <algorithm>\r\n\r\ntemplate <typename T>\r\nclass Repository {\r\nprivate:\r\n\tstd::vector<T> elems{};\r\npublic:\r\n\tRepository() {}\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return this->elems.size(); }\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\tvoid add(T s);\r\n\tvoid del(int pos);\r\n\tvoid update(int id, std::string name, int age);\r\n};"
},
{
"alpha_fraction": 0.47691407799720764,
"alphanum_fraction": 0.47749853134155273,
"avg_line_length": 25.59677505493164,
"blob_id": "7fd6a445e5c5acdd1ef8dae9ceb2e1c4ae573234",
"content_id": "aa7eeee5f0a587748d5b9c29161efa0c7fe34523",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1713,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 62,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Controller/Controller.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Repository;\r\nusing Interpreter.Model.Statements;\r\nusing Interpreter.Model;\r\nusing Interpreter.Exceptions;\r\nusing Interpreter.Model.Utilities;\r\n\r\nnamespace Interpreter.Controller\r\n{\r\n public class Controller\r\n {\r\n private IRepo repo;\r\n\r\n public Controller(IRepo repo)\r\n {\r\n this.repo = repo;\r\n }\r\n\r\n public ProgramState oneStep(ProgramState state)\r\n {\r\n try\r\n {\r\n if (state.Stack.isEmpty())\r\n throw new EmptyStack(\"The stack is empty!\");\r\n IStmt currentStmt = state.Stack.pop();\r\n return currentStmt.execute(state);\r\n }\r\n catch (Exception e)\r\n {\r\n Console.WriteLine(e.ToString());\r\n Environment.Exit(0);\r\n }\r\n return state;\r\n }\r\n\r\n public void allSteps()\r\n {\r\n ProgramState prg = repo.getCurrentPrg();\r\n try\r\n {\r\n while (!prg.Stack.isEmpty())\r\n {\r\n prg=oneStep(prg);\r\n this.repo.logProgramStateExec(\"C:\\\\Users\\\\pechd\\\\source\\\\repos\\\\Interpreter\\\\Interpreter\\\\log.txt\");\r\n Console.WriteLine(\"-----------\");\r\n Console.WriteLine(prg.ToString());\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n Console.WriteLine(e.ToString());\r\n }\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"Controller: \" + repo.ToString();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.8197183012962341,
"alphanum_fraction": 0.8197183012962341,
"avg_line_length": 27.75,
"blob_id": "ad7a9282ed00778eb77781e79a316fb193a347de",
"content_id": "2e3f907aa3904214b7922a5d18124a2f86f41711",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 355,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 12,
"path": "/MyProjects/FP/FP/Practice Test 1/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from UI import *\r\nfrom controller import *\r\nfrom repository import *\r\nfrom domain import *\r\ndriverRepo=Repository()\r\norderRepo=Repository()\r\nincomeRepo=Repository()\r\ndriverController=Controller(driverRepo)\r\norderController=Controller(orderRepo)\r\nincomeController=Controller(incomeRepo)\r\nui=UI(driverController,orderController,incomeController)\r\nui.start()"
},
{
"alpha_fraction": 0.5784016251564026,
"alphanum_fraction": 0.5806778073310852,
"avg_line_length": 17.11111068725586,
"blob_id": "ad3d59cbd13c4fbaaad6b0cea51314f9693e1e43",
"content_id": "55067e52b72aa8fb942b4b0d05d9cb75730d83b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3954,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 207,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/dynamic.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <iterator>\r\n\r\n\r\ntemplate <typename T>\r\nclass Vector\r\n{\r\nprivate:\r\n\tT * elems;\r\n\tint len;\r\n\tint cap;\r\npublic:\r\n\t/* \r\n\tConstructor for the dynamic vector\r\n\t*/\r\n\tVector(int cap = 10);\r\n\t/*\r\n\tSecond constructor for the dynamic vector\r\n\t*/\r\n\tVector(const Vector& v);\r\n\t/*\r\n\tDestructor for the dynamic vector\r\n\t*/\r\n\t~Vector();\r\n\t/*\r\n\tOverwrites the = operator for the dynamic vector\r\n\t*/\r\n\tVector& operator=(const Vector& v);\r\n\t/*\r\n\tOverwrites the + operator for the dynamic vector\r\n\t*/\r\n\t//friend Vector & operator+(Vector& v, const Movie & m);\r\n\t//friend Vector & operator+(const Movie & m, Vector& v);\r\n\t/*\r\n\tOverloading the subscript operator\r\n\tInput: pos - a valid position within the vector.\r\n\tOutput: a reference to the element o position pos.\r\n\t*/\r\n\tT& operator[](int pos);\r\n\t/*\r\n\tAdds a movie to the dynamic vector\r\n\t*/\r\n\tvoid add(const T& e);\r\n\t/*\r\n\tDeletes a movie from the dynamic vector, by position\r\n\t*/\r\n\tvoid del(int pos);\r\n\t/*\r\n\tReturns the lenght of the lenght of the dynamic vector\r\n\t*/\r\n\tint getLenght() const;\r\n\tT* getAll() const;\r\n\tvoid incLikes(int pos);\r\n\r\n\t/*\r\n\tResizes the vector, doubleing it's capacity\r\n\t*/\r\n\tvoid resize(int times = 2);\r\npublic:\r\n\tclass iterator : public std::iterator<std::forward_iterator_tag, T>\r\n\t{\r\n\tprivate:\r\n\t\tT * ptr;\r\n\tpublic:\r\n\t\titerator(T* p) : ptr{ p } { }\r\n\t\titerator operator++() { this->ptr++; return *this; }\r\n\t\titerator operator++(int) { iterator i = *this; this->ptr++; return i; }\r\n\t\tT& operator*() { return *this->ptr; }\r\n\t\tT* operator->() { return this->ptr; }\r\n\t\tbool operator!=(const iterator& it) { return this->ptr != it.ptr; }\r\n\t\tbool operator==(const iterator& it) { return this->ptr == it.ptr; }\r\n\t};\r\n\titerator begin()\r\n\t{\r\n\t\treturn iterator{ this->elems };\r\n\t}\r\n\r\n\titerator end()\r\n\t{\r\n\t\treturn iterator{ this->elems + this->size };\r\n\t}\r\n};\r\n\r\ntemplate <typename T>\r\nVector<T>::Vector(int cap)\r\n{\r\n\tthis->len = 0;\r\n\tthis->cap = cap;\r\n\tthis->elems = new T[cap];\r\n}\r\n\r\ntemplate <typename T>\r\nVector<T>::Vector(const Vector<T>& v)\r\n{\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\tthis->elems = new T[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t{\r\n\t\tthis->elems[i] = v.elems[i];\r\n\t}\r\n}\r\n\r\ntemplate <typename T>\r\nVector<T>::~Vector()\r\n{\r\n\tdelete[] this->elems;\r\n}\r\n\r\ntemplate <typename T>\r\nVector<T> & Vector<T>::operator=(const Vector<T> & v)\r\n{\r\n\tif (this == &v)\r\n\t\treturn *this;\r\n\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = new T[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\tthis->elems[i] = v.elems[i];\r\n\r\n\treturn *this;\r\n}\r\n\r\ntemplate <typename T>\r\nT& Vector<T>::operator[](int pos)\r\n{\r\n\treturn this->elems[pos];\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Vector<T>::add(const T& e)\r\n{\r\n\tif (this->len == this->cap)\r\n\t\tthis->resize();\r\n\tthis->elems[this->len] = e;\r\n\tthis->len++;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Vector<T>::del(int pos)\r\n{\r\n\tT* e = new T[this->cap];\r\n\tint k = 0;\r\n\tfor (int i = 0;i<this->len;i++)\r\n\t\tif (i != pos)\r\n\t\t{\r\n\t\t\te[i] = this->elems[i];\r\n\t\t\tk++;\r\n\t\t}\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n\tthis->len--;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Vector<T>::resize(int times)\r\n{\r\n\tthis->cap *= static_cast<int>(times);\r\n\r\n\tT* e = new T[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\te[i] = this->elems[i];\r\n\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n}\r\n/*\r\n//template <typename T>\r\n//Vector<T> & operator+(Vector<T> & v, const Movie & m)\r\n//{\r\n//\tif (v.len == v.cap)\r\n//\t\tv.resize();\r\n//\tv.elems[v.len] = m;\r\n//\tv.len++;\r\n//\treturn v;\r\n//}\r\n//\r\n//template <typename T>\r\n//Vector<T> & operator+(const Movie & m, Vector<T> & v)\r\n//{\r\n//\tif (v.len == v.cap)\r\n//\t\tv.resize();\r\n//\tv.elems[v.len] = m;\r\n//\tv.len++;\r\n//\treturn v;\r\n//}\r\n*/\r\ntemplate <typename T>\r\nint Vector<T>::getLenght() const\r\n{\r\n\treturn this->len;\r\n}\r\n\r\ntemplate <typename T>\r\nT * Vector<T>::getAll() const\r\n{\r\n\treturn this->elems;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid Vector<T>::incLikes(int pos)\r\n{\r\n\tthis->elems[pos].incL();\r\n}"
},
{
"alpha_fraction": 0.5918367505073547,
"alphanum_fraction": 0.5918367505073547,
"avg_line_length": 22.61111068725586,
"blob_id": "5d91f821de33b1ab916b33c2f3974104cf869eb4",
"content_id": "5123192fbbe2d250f01838a5d0e4e1ace20c5216",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 441,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 18,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/star.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"star.h\"\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Star::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Name: \" << name << \", Constellation: \" << constellation << \", Luminosity: \" << luminosity << \", Temperature: \" << temperature;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Star::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff << name << \",\" << constellation << \",\" << luminosity << \",\" << temperature;\r\n\treturn buff.str();\r\n}"
},
{
"alpha_fraction": 0.6213389039039612,
"alphanum_fraction": 0.6213389039039612,
"avg_line_length": 19.81818199157715,
"blob_id": "41d4cd5c5c9e77e529963c974d8e8805241ed7df",
"content_id": "623800225978161c16dda22a3626c21d250df94f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 478,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 22,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/teacher.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <vector>\r\n\r\nclass Teacher\r\n{\r\nprivate:\r\n\tstd::string name;\r\n\tstd::vector<int> groups;\r\npublic:\r\n\tTeacher(std::string name, std::vector<int> gr) :name{ name }, groups{ gr } {}\r\n\t~Teacher() {}\r\n\r\n\tstd::string getName() { return name; }\r\n\tstd::vector<int> getGroups() { return groups; }\r\n\r\n\tvoid setGroups(std::vector<int> v) { groups = v; }\r\n\tvoid setName(std::string n) { name = n; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.6477611660957336,
"alphanum_fraction": 0.6477611660957336,
"avg_line_length": 16.72222137451172,
"blob_id": "60be9809fdf3c2dc391693f38b0c66b34543262e",
"content_id": "a614a0696e7b7cad023379d01db06445af7aa7cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 335,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 18,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/domain.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <iostream>\r\n\r\n\r\nclass Player\r\n{\r\nprivate:\r\n\tstd::string name;\r\n\tstd::string nationality;\r\n\tstd::string team;\r\n\tint goals;\r\npublic:\r\n\tstd::string getName() { return name; };\r\n\tstd::string getNationality() { return nationality; };\r\n\tstd::string getTeam() { return team; };\r\n\tint getGoals() { return goals; };\r\n\r\n};"
},
{
"alpha_fraction": 0.522587239742279,
"alphanum_fraction": 0.581108808517456,
"avg_line_length": 19.88763999938965,
"blob_id": "fff3e2cd19d980ce6f8335c4b531ecf05b1f2839",
"content_id": "90c4366f5bf9dfcbb6c67b74e7aef7555bfa1fc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1948,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 89,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPpracticalex1.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"student.h\"\r\n#include \"teacher.h\"\r\n#include \"studentRepo.h\"\r\n#include \"teacherRepo.h\"\r\n#include \"controller.h\"\r\n#include \"MainTeacher.h\"\r\n#include \"SomeTeacher.h\"\r\n\r\nvoid testAdd()\r\n{\r\n\tStudentRepo<Student> s{};\r\n\tStudent s1{ 1,\"Ni\",1,10,\"Teacher\" };\r\n\tStudent s2{ 2,\"Ion\",1,10,\"Hiji\" };\r\n\tStudent s3{ 3,\"Wai\",1,10,\"Yoi\" };\r\n\tStudent s4{ 4,\"Uite\",1,10,\"Kiwi\" };\r\n\ts.add(s1);\r\n\ts.add(s2);\r\n\ts.add(s3);\r\n\ts.add(s4);\r\n\tassert(s[0].getGrade() == 10);\r\n\tassert(s[1].getName() == \"Ion\");\r\n\tassert(s[3].getTeacher() == \"Kiwi\");\r\n}\r\nvoid testDel()\r\n{\r\n\tStudentRepo<Student> s{};\r\n\tStudent s1{ 1,\"Ni\",1,10,\"Teacher\" };\r\n\tStudent s2{ 2,\"Ion\",1,10,\"Hiji\" };\r\n\tStudent s3{ 3,\"Wai\",1,10,\"Yoi\" };\r\n\tStudent s4{ 4,\"Uite\",1,10,\"Kiwi\" };\r\n\ts.add(s1);\r\n\ts.add(s2);\r\n\ts.add(s3);\r\n\ts.add(s4);\r\n\tassert(s.getLenght() == 4);\r\n\ts.del(2);\r\n\tassert(s[2].getName() == \"Uite\");\r\n\tassert(s.getLenght() == 3);\r\n}\r\nvoid testSetTeacher()\r\n{\r\n\tStudentRepo<Student> s{};\r\n\tStudent s1{ 1,\"Ni\",1,10,\"Teacher\" };\r\n\tStudent s2{ 2,\"Ion\",1,10,\"Hiji\" };\r\n\tStudent s3{ 3,\"Wai\",1,10,\"Yoi\" };\r\n\tStudent s4{ 4,\"Uite\",1,10,\"Kiwi\" };\r\n\ts.add(s1);\r\n\ts.add(s2);\r\n\ts.add(s3);\r\n\ts.add(s4);\r\n\ts.setTeacher(2, \"Ionci\");\r\n\tassert(s[2].getTeacher() == \"Ionci\");\r\n}\r\nvoid testGradeStudent()\r\n{\r\n\tStudentRepo<Student> s{};\r\n\tStudent s1{ 1,\"Ni\",1,10,\"Teacher\" };\r\n\tStudent s2{ 2,\"Ion\",1,10,\"Hiji\" };\r\n\tStudent s3{ 3,\"Wai\",1,10,\"Yoi\" };\r\n\tStudent s4{ 4,\"Uite\",1,10,\"Kiwi\" };\r\n\ts.add(s1);\r\n\ts.add(s2);\r\n\ts.add(s3);\r\n\ts.add(s4);\r\n\ts.gradeStudent(2, 9.5);\r\n\tassert(s[2].getGrade() == 9.5);\r\n}\r\n\r\nvoid testAll()\r\n{\r\n\ttestAdd();\r\n\ttestDel();\r\n\ttestSetTeacher();\r\n\ttestGradeStudent();\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\ttestAll();\r\n\tStudentRepo<Student> s{ \"Students.txt\" };\r\n\tTeacherRepo<Teacher> t{ \"Teachers.txt\" };\r\n\tController c{ s,t };\r\n\tMainTeacher m{ c };\r\n\tm.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.7279411554336548,
"alphanum_fraction": 0.7279411554336548,
"avg_line_length": 17.428571701049805,
"blob_id": "ef2f7c2f9037a234daac0cc2a3836848a240e6fe",
"content_id": "051df59e2f7f303dcc11bc52ab7bdb03d156fe7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 136,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Practical 4/OOP Practical Exam/OOPPracticalExam.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPPracticalExam.h\"\r\n\r\nOOPPracticalExam::OOPPracticalExam(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.5815279483795166,
"alphanum_fraction": 0.5883694291114807,
"avg_line_length": 23,
"blob_id": "7729a1a1e2f710928df3ed0ebc12e741512ce786",
"content_id": "9fd2c777c2585fe6844e9b922ed6f9e123bc1a39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 877,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 35,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <iostream>\r\n\r\nint Repository::addPlayer(TElement& e)\r\n{\r\n\tfor (int i;i < this->players.getLenght();i++)\r\n\t\tif (this->players.get(i).getName() == e.getName())\r\n\t\t\treturn 0;\r\n\tthis->players.add(e);\r\n}\r\n\r\nvoid Repository::sortList()\r\n{\r\n\tTElement m;\r\n\tint p;\r\n\tfor (int i = 0; i < this->players.getLenght()-1; i++)\r\n\t{\r\n\t\tp = i;\r\n\t\tfor (int j = i + 1; j < this->players.getLenght(); j++)\r\n\t\t\tif (this->players.get(j).getGoals() < this->players.get(p).getGoals())\r\n\t\t\t\tp = j;\r\n\t\tm = this->players.get(p);\r\n\t\tthis->players.getAll()[p] = this->players.get(i);\r\n\t\tthis->players.getAll()[i] = m;\r\n\t}\r\n}\r\n\r\nint Repository::total(const std::string country)\r\n{\r\n\tint sum = 0;\r\n\tfor (int i = 0;i < this->players.getLenght();i++)\r\n\t\tif (this->players.getAll()[i].getNationality() == country)\r\n\t\t\tsum += this->players.get(i).getGoals();\r\n\treturn sum;\r\n}\r\n\r\n"
},
{
"alpha_fraction": 0.7091836929321289,
"alphanum_fraction": 0.7091836929321289,
"avg_line_length": 20.69230842590332,
"blob_id": "8bc7cf5153698c55ea60d2ccaf27dfc40c47dc24",
"content_id": "1b6ba8baaf20162118e401af4db67bba7ef078dc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 588,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/TeacherWindow.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ui_TeacherWindow.h\"\r\n#include <QtWidgets/QMainWindow>\r\n#include \"student.h\"\r\n#include \"repository.h\"\r\n\r\nclass SepareteTeacher : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tSepareteTeacher(Repository<Student>* r,std::string name,std::vector<int> gr, QWidget *parent = Q_NULLPTR);\r\n\t~SepareteTeacher() {}\r\n\tvoid populate();\r\nprivate:\r\n\tUi::TeacherWindow ui;\r\n\tstd::vector<Student> students;\r\n\tRepository<Student>* repo;\r\n\tstd::string name;\r\n\tstd::vector<int> groups;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tint getSelectedIndex();\r\n\tprivate slots:\r\n\tvoid grade();\r\n};"
},
{
"alpha_fraction": 0.6473175287246704,
"alphanum_fraction": 0.6499560475349426,
"avg_line_length": 16.983333587646484,
"blob_id": "f86d168353b810c531ba877dde3dc4760600ad39",
"content_id": "edc5b08bcafbd7e912d28f58de1c44e5ace603ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1137,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 60,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/dynamic.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"domain.h\"\r\n#include <iostream>\r\n\r\ntypedef Movie TElement;\r\n\r\nclass Vector\r\n{\r\nprivate:\r\n\tTElement * elems;\r\n\tint len;\r\n\tint cap;\r\npublic:\r\n\t/*\r\n\tConstructor for the dynamic vector\r\n\t*/\r\n\tVector(int cap = 10);\r\n\t/*\r\n\tSecond constructor for the dynamic vector\r\n\t*/\r\n\tVector(const Vector& v);\r\n\t/*\r\n\tDestructor for the dynamic vector\r\n\t*/\r\n\t~Vector();\r\n\t/*\r\n\tOverwrites the = operator for the dynamic vector\r\n\t*/\r\n\tVector& operator=(const Vector& v);\r\n\t/*\r\n\tOverwrites the + operator for the dynamic vector\r\n\t*/\r\n\tfriend Vector & operator+(Vector& v, const Movie & m);\r\n\tfriend Vector & operator+(const Movie & m, Vector& v);\r\n\t/*\r\n\tAdds a movie to the dynamic vector\r\n\t*/\r\n\tvoid add(const TElement& e);\r\n\t/*\r\n\tDeletes a movie from the dynamic vector, by position\r\n\t*/\r\n\tvoid del(int pos);\r\n\t/*\r\n\tReturns the lenght of the lenght of the dynamic vector\r\n\t*/\r\n\tint getLenght() const;\r\n\r\n\tMovie get(int pos);\r\n\t/*\r\n\tReturns the elements of the dynamic vector\r\n\t*/\r\n\tTElement* getAll() const;\r\n\r\n\tvoid incLikes(int pos);\r\nprivate:\r\n\t/*\r\n\tResizes the vector, doubleing it's capacity\r\n\t*/\r\n\tvoid resize(int times = 2);\r\n};"
},
{
"alpha_fraction": 0.5444043278694153,
"alphanum_fraction": 0.5501804947853088,
"avg_line_length": 14.5119047164917,
"blob_id": "ce6d0dc180eb7c2f7d97591bb499c6cc156d6de2",
"content_id": "8931f9db2c420004ff471c24f83b19df6e0a51b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1385,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 84,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/dynamic.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"dynamic.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nVector::Vector()\r\n{\r\n\tint cap = 2;\r\n\tthis->cap = cap;\r\n\tthis->len = 0;\r\n\tthis->elems = new TElement[cap];\r\n}\r\n\r\nVector::Vector(const Vector& v)\r\n{\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i=0;i < this->len;i++)\r\n\t{\r\n\t\tthis->elems[i] = v.elems[i];\r\n\t}\r\n}\r\n\r\nVector::~Vector()\r\n{\r\n\tdelete[] this->elems;\r\n}\r\n\r\nVector& Vector::operator=(const Vector& v)\r\n{\r\n\tthis->len = v.len;\r\n\tthis->cap = v.cap;\r\n\tthis->elems = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t{\r\n\t\tthis->elems[i] = v.elems[i];\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\nTElement& Vector::operator[](int pos)\r\n{\r\n\treturn this->elems[pos];\r\n}\r\n\r\nvoid Vector::add(const TElement& e)\r\n{\r\n\tif (this->len == this->cap)\r\n\t\tthis->resize();\r\n\tthis->elems[len] = e;\r\n\tthis->len++;\r\n}\r\n\r\nvoid Vector::del(int pos)\r\n{\r\n\tTElement* e = new TElement[this->cap];\r\n\tint k = 0;\r\n\tfor(int i=0;i<this->len;i++)\r\n\t\tif (i != pos)\r\n\t\t{\r\n\t\t\te[k] = this->elems[i];\r\n\t\t\tk++;\r\n\t\t}\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n\tthis->len--;\r\n}\r\n\r\nvoid Vector::resize()\r\n{\r\n\tint t = 2;\r\n\tthis->cap *= static_cast<int>(t);\r\n\tTElement* e = new TElement[this->cap];\r\n\tfor (int i = 0;i < this->len;i++)\r\n\t\te[i] = this->elems[i];\r\n\tdelete[] this->elems;\r\n\tthis->elems = e;\r\n}\r\n\r\nTElement* Vector::getAll()\r\n{\r\n\treturn this->elems;\r\n}"
},
{
"alpha_fraction": 0.6259739995002747,
"alphanum_fraction": 0.6259739995002747,
"avg_line_length": 17.350000381469727,
"blob_id": "3447b04078caf26503269224f7660525ac300281",
"content_id": "47061065259e0df069908a26ecb1f040fa7597f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Practice 3/New/UI.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"controller.h\"\r\n#include \"csv.h\"\r\n#include \"html.h\"\r\n\r\nclass UI {\r\nprivate:\r\n\tController contro;\r\n\t//CSV csv;\r\n\t//HTML html;\r\n\tint option;\r\npublic:\r\n\tUI(Controller c, int opt) :contro{ c }, option{ opt } {}\r\n\t~UI() {}\r\n\tvoid printMenuAdmin();\r\n\tvoid printMenuUser();\r\n\tvoid displayFile();\r\n\t//void saveFile() { html.setContro(this->contro); }\r\n\tvoid start();\r\n};"
},
{
"alpha_fraction": 0.651343584060669,
"alphanum_fraction": 0.6708498001098633,
"avg_line_length": 41.636905670166016,
"blob_id": "e7cb31599a08f72e0f2fe890fe119f5a951d13bc",
"content_id": "e64b24371db546e00a1cbadb5836fbff20425447",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7331,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 168,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_user.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'user.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_USER_H\r\n#define UI_USER_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHBoxLayout>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QListWidget>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QSplitter>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_UserWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QSplitter *splitter;\r\n QWidget *layoutWidget;\r\n QHBoxLayout *horizontalLayout;\r\n QPushButton *NextButton;\r\n QPushButton *AddButton;\r\n QPushButton *DeleteButton;\r\n QPushButton *FilterButton;\r\n QListWidget *FilteredList;\r\n QPushButton *LikeButton;\r\n QWidget *layoutWidget_2;\r\n QHBoxLayout *horizontalLayout_2;\r\n QPushButton *ShowCSVButton;\r\n QPushButton *ShowHTMLButton;\r\n QLabel *MovieListLabel;\r\n QLabel *FilteredLabel;\r\n QLineEdit *FilterByTitleLine;\r\n QLabel *FilterLabel;\r\n QListWidget *MovieList;\r\n QPushButton *UndoButton;\r\n QPushButton *RedoButton;\r\n\r\n void setupUi(QMainWindow *UserWindow)\r\n {\r\n if (UserWindow->objectName().isEmpty())\r\n UserWindow->setObjectName(QStringLiteral(\"UserWindow\"));\r\n UserWindow->resize(591, 510);\r\n centralwidget = new QWidget(UserWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n splitter = new QSplitter(centralwidget);\r\n splitter->setObjectName(QStringLiteral(\"splitter\"));\r\n splitter->setGeometry(QRect(310, 390, 239, 48));\r\n splitter->setOrientation(Qt::Vertical);\r\n layoutWidget = new QWidget(splitter);\r\n layoutWidget->setObjectName(QStringLiteral(\"layoutWidget\"));\r\n horizontalLayout = new QHBoxLayout(layoutWidget);\r\n horizontalLayout->setObjectName(QStringLiteral(\"horizontalLayout\"));\r\n horizontalLayout->setContentsMargins(0, 0, 0, 0);\r\n NextButton = new QPushButton(layoutWidget);\r\n NextButton->setObjectName(QStringLiteral(\"NextButton\"));\r\n\r\n horizontalLayout->addWidget(NextButton);\r\n\r\n AddButton = new QPushButton(layoutWidget);\r\n AddButton->setObjectName(QStringLiteral(\"AddButton\"));\r\n\r\n horizontalLayout->addWidget(AddButton);\r\n\r\n DeleteButton = new QPushButton(layoutWidget);\r\n DeleteButton->setObjectName(QStringLiteral(\"DeleteButton\"));\r\n\r\n horizontalLayout->addWidget(DeleteButton);\r\n\r\n splitter->addWidget(layoutWidget);\r\n FilterButton = new QPushButton(splitter);\r\n FilterButton->setObjectName(QStringLiteral(\"FilterButton\"));\r\n splitter->addWidget(FilterButton);\r\n FilteredList = new QListWidget(centralwidget);\r\n FilteredList->setObjectName(QStringLiteral(\"FilteredList\"));\r\n FilteredList->setGeometry(QRect(10, 220, 571, 141));\r\n LikeButton = new QPushButton(centralwidget);\r\n LikeButton->setObjectName(QStringLiteral(\"LikeButton\"));\r\n LikeButton->setGeometry(QRect(240, 450, 75, 23));\r\n layoutWidget_2 = new QWidget(centralwidget);\r\n layoutWidget_2->setObjectName(QStringLiteral(\"layoutWidget_2\"));\r\n layoutWidget_2->setGeometry(QRect(420, 480, 163, 25));\r\n horizontalLayout_2 = new QHBoxLayout(layoutWidget_2);\r\n horizontalLayout_2->setObjectName(QStringLiteral(\"horizontalLayout_2\"));\r\n horizontalLayout_2->setContentsMargins(0, 0, 0, 0);\r\n ShowCSVButton = new QPushButton(layoutWidget_2);\r\n ShowCSVButton->setObjectName(QStringLiteral(\"ShowCSVButton\"));\r\n\r\n horizontalLayout_2->addWidget(ShowCSVButton);\r\n\r\n ShowHTMLButton = new QPushButton(layoutWidget_2);\r\n ShowHTMLButton->setObjectName(QStringLiteral(\"ShowHTMLButton\"));\r\n\r\n horizontalLayout_2->addWidget(ShowHTMLButton);\r\n\r\n MovieListLabel = new QLabel(centralwidget);\r\n MovieListLabel->setObjectName(QStringLiteral(\"MovieListLabel\"));\r\n MovieListLabel->setGeometry(QRect(10, 20, 61, 16));\r\n QFont font;\r\n font.setPointSize(10);\r\n MovieListLabel->setFont(font);\r\n FilteredLabel = new QLabel(centralwidget);\r\n FilteredLabel->setObjectName(QStringLiteral(\"FilteredLabel\"));\r\n FilteredLabel->setGeometry(QRect(10, 200, 71, 16));\r\n FilteredLabel->setFont(font);\r\n FilterByTitleLine = new QLineEdit(centralwidget);\r\n FilterByTitleLine->setObjectName(QStringLiteral(\"FilterByTitleLine\"));\r\n FilterByTitleLine->setGeometry(QRect(50, 410, 191, 20));\r\n FilterLabel = new QLabel(centralwidget);\r\n FilterLabel->setObjectName(QStringLiteral(\"FilterLabel\"));\r\n FilterLabel->setGeometry(QRect(50, 390, 201, 16));\r\n FilterLabel->setFont(font);\r\n MovieList = new QListWidget(centralwidget);\r\n MovieList->setObjectName(QStringLiteral(\"MovieList\"));\r\n MovieList->setGeometry(QRect(10, 40, 571, 151));\r\n UndoButton = new QPushButton(centralwidget);\r\n UndoButton->setObjectName(QStringLiteral(\"UndoButton\"));\r\n UndoButton->setGeometry(QRect(420, 10, 75, 23));\r\n RedoButton = new QPushButton(centralwidget);\r\n RedoButton->setObjectName(QStringLiteral(\"RedoButton\"));\r\n RedoButton->setGeometry(QRect(500, 10, 75, 23));\r\n UserWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(UserWindow);\r\n\r\n QMetaObject::connectSlotsByName(UserWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *UserWindow)\r\n {\r\n UserWindow->setWindowTitle(QApplication::translate(\"UserWindow\", \"User\", nullptr));\r\n NextButton->setText(QApplication::translate(\"UserWindow\", \"Next >>\", nullptr));\r\n AddButton->setText(QApplication::translate(\"UserWindow\", \"Add\", nullptr));\r\n DeleteButton->setText(QApplication::translate(\"UserWindow\", \"Delete\", nullptr));\r\n FilterButton->setText(QApplication::translate(\"UserWindow\", \"Filter\", nullptr));\r\n LikeButton->setText(QApplication::translate(\"UserWindow\", \"Like\", nullptr));\r\n ShowCSVButton->setText(QApplication::translate(\"UserWindow\", \"Show CSV file\", nullptr));\r\n ShowHTMLButton->setText(QApplication::translate(\"UserWindow\", \"Show HTML file\", nullptr));\r\n MovieListLabel->setText(QApplication::translate(\"UserWindow\", \"Movie list:\", nullptr));\r\n FilteredLabel->setText(QApplication::translate(\"UserWindow\", \"Filtered list:\", nullptr));\r\n FilterLabel->setText(QApplication::translate(\"UserWindow\", \"Filter by genre (\\\"empty\\\" to get all):\", nullptr));\r\n UndoButton->setText(QApplication::translate(\"UserWindow\", \"Undo\", nullptr));\r\n RedoButton->setText(QApplication::translate(\"UserWindow\", \"Redo\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class UserWindow: public Ui_UserWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_USER_H\r\n"
},
{
"alpha_fraction": 0.646532416343689,
"alphanum_fraction": 0.646532416343689,
"avg_line_length": 20.350000381469727,
"blob_id": "a8f6b1b8a7e8c9ff7271c61c2dc4e2b6da4671ee",
"content_id": "c980915d714973dfc996983d569162eeffeab0d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 447,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 20,
"path": "/MyProjects/MAP/Practical Exam/Procedures/src/Model/Statements/Return.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IStack;\r\n\r\npublic class Return implements IStmt {\r\n public Return(){}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IStack<IDictionary<String, Integer>> dic=state.getSyms();\r\n dic.pop();\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"return\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6810431480407715,
"alphanum_fraction": 0.6810431480407715,
"avg_line_length": 30.225807189941406,
"blob_id": "255706da61e14cd70f1420a97535453eb2cf0f63",
"content_id": "8ee44fb8eb843dd8f54d1f3f28e2e625d79ad1d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 997,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 31,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"html.h\"\r\n\r\nclass Controller {\r\nprivate:\r\n\tRepository repo;\r\n\tRepository list;\r\n\tHTML html;\r\npublic:\r\n\tController(Repository repo, Repository list) :repo{ repo }, list{ list }, html{ list } {}\r\n\t~Controller() {}\r\n\tRepository getAll() { return repo; }\r\n\tRepository getList() { return list; }\r\n\tint findByTitle(std::string title);\r\n\r\n\tbool add(Movie m);\r\n\tbool del(std::string title);\r\n\tbool addList(Movie m);\r\n\tbool delList(std::string title);\r\n\tbool update(std::string oTitle, std::string nTitle, std::string genre, int year, int likes, std::string trailer);\r\n\tvoid incLikes(int pos) { repo.incLikes(pos); }\r\n\tvoid operator=(Controller c);\r\n\tvoid saveFile() { html.setRepo(this->getList()); }\r\n\tvoid setElems(std::vector<Movie> m) { list.setElems(m); }\r\n\tvoid readFromList() { this->list.clr(); this->list.readFromFile(); }\r\n\r\n\tstd::vector<Movie> filterByGenre(std::string genre);\r\n\tvoid displayCSV() { list.displayCSV(); }\r\n\tvoid displayHTML();\r\n};"
},
{
"alpha_fraction": 0.5645161271095276,
"alphanum_fraction": 0.5860214829444885,
"avg_line_length": 19.538461685180664,
"blob_id": "645533c5b509afe9d764f71590d7c7ae35a95097",
"content_id": "16d4c5edeb833b4f97aed85f0b4a6f4246711e6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include \"controller.h\"\r\n#include \"repository.h\"\r\n#include \"domain.h\"\r\n#include \"sportsman.h\"\r\n#include \"gamer.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\t{\r\n\t\tStudent s{ 1,\"Jambon\",15 };\r\n\t\tSportsman s1{ \"inot\",2,\"Artemis\",18 };\r\n\t\tGamer g{ \"minecraft\",3,\"Iulius\",15 };\r\n\t\tcout<<s.overString();\r\n\t\tcout << endl << s1.overString();\r\n\t\tcout << endl << g.overString() << endl;\r\n\t\tsystem(\"pause\");\r\n\t\t//Repository<Student> r{};\r\n\t\t//Controller<Student> c{ r };\r\n\t\t//UI<Student> ui{ c };\r\n\t\t//ui.start();\r\n\t}\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.59375,
"alphanum_fraction": 0.6015625,
"avg_line_length": 26.850000381469727,
"blob_id": "7a004b3490e97df9f36109569b07677b26d5337d",
"content_id": "143696e4a5e04edbba3867a732a5b4986324cf58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1152,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 40,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/task.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Task\r\n{\r\nprivate:\r\n\tstd::string description;\r\n\tint stat;\r\n\tstd::string status;\r\n\tint programmerid;\r\n\tstd::string progName;\r\npublic:\r\n\tTask() :stat{}, status{ \"\" }, programmerid{ -1 }, description{ \"\" }, progName{ \" \" } {}\r\n\tTask(std::string descr) :stat{ -1 }, status{ \"open\" }, programmerid{ -1 }, description{ descr }, progName{ \" \" } {}\r\n\tTask(std::string descr, int s, int id, std::string pn) :stat{ s }, description{ descr }, programmerid{ id }, progName{ pn }\r\n\t{\r\n\t\tif (s == -1)\r\n\t\t\tstatus = \"open\";\r\n\t\tif (s == 0)\r\n\t\t\tstatus = \"in progress\";\r\n\t\tif (s == 1)\r\n\t\t\tstatus = \"closed\";\r\n\t}\r\n\t~Task() {}\r\n\r\n\tint getIntStat() { return stat; }\r\n\tstd::string getStat() { return status; }\r\n\tstd::string getDescr() { return description; }\r\n\tint getID() { return programmerid; }\r\n\tstd::string getProgName() { return progName; }\r\n\r\n\tvoid setProgress() { stat = 0; status = \"in progress\"; }\r\n\tvoid setClosed() { stat = 1;status = \"closed\"; }\r\n\tvoid setID(int id) { programmerid = id; }\r\n\tvoid setProgName(std::string n) { progName = n; }\r\n\r\n\tstd::string toString();\r\n\tstd::string toString1();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.5892443060874939,
"alphanum_fraction": 0.5971256494522095,
"avg_line_length": 18.941747665405273,
"blob_id": "3bf5242bdeead6a776bf4b2b39d0bba86852bb8b",
"content_id": "2d0b25f751b08c9fd7a387bf93cd6e78832b15e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2157,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 103,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n#include \"repoException.h\"\r\n\r\nint Controller::findByTitle(std::string title)\r\n{\r\n\tfor (int i = 0;i < this->repo.getLenght();i++)\r\n\t\tif (this->repo[i].getTitle() == title)\r\n\t\t\treturn i;\r\n\treturn -1;\r\n}\r\n\r\nbool Controller::add(Movie m)\r\n{\r\n\tif (this->findByTitle(m.getTitle()) != -1)\r\n\t{\r\n\t\tthrow FoundException();\r\n\t\treturn false;\r\n\t}\r\n\tthis->repo.add(m);\r\n\treturn true;\r\n}\r\n\r\nbool Controller::del(std::string title)\r\n{\r\n\tint pos = this->findByTitle(title);\r\n\tif (pos < 0 || pos >= this->repo.getLenght())\r\n\t{\r\n\t\tthrow NoMovieFoundException();\r\n\t\treturn false;\r\n\t}\r\n\tthis->repo.del(pos);\r\n\treturn true;\r\n}\r\n\r\nbool Controller::addList(Movie m)\r\n{\r\n\tint pos = this->list.findByTitle(m.getTitle());\r\n\tif (pos != -1)\r\n\t{\r\n\t\tthrow FoundException();\r\n\t\treturn false;\r\n\t}\r\n\tthis->list.add(m);\r\n\treturn true;\r\n}\r\n\r\nbool Controller::delList(std::string title)\r\n{\r\n\tint k = this->list.findByTitle(title);\r\n\tif (k == -1)\r\n\t{\r\n\t\tthrow NoMovieFoundException();\r\n\t\treturn false;\r\n\t}\r\n\tthis->list.del(k);\r\n\treturn true;\r\n}\r\n\r\nbool Controller::update(std::string oTitle, std::string nTitle, std::string genre, int year, int likes, std::string trailer)\r\n{\r\n\tint pos = this->findByTitle(oTitle);\r\n\tif (pos < 0 || pos >= this->repo.getLenght())\r\n\t\treturn false;\r\n\tthis->repo.update(oTitle, nTitle, genre, year, likes, trailer);\r\n\treturn true;\r\n}\r\n\r\nvoid Controller::operator=(Controller c)\r\n{\r\n\tfor (int i = this->repo.getLenght() - 1;i >= 0;i--)\r\n\t\tthis->repo.del(i);\r\n\tfor (int i = this->list.getLenght() - 1;i >= 0;i--)\r\n\t\tthis->list.del(i);\r\n\tfor (int i = 0;i < c.repo.getLenght();i++)\r\n\t\tthis->repo.add(c.getAll()[i]);\r\n\tfor (int i = 0;i < c.list.getLenght();i++)\r\n\t\tthis->list.add(c.getList()[i]);\r\n}\r\n\r\nstd::vector<Movie> Controller::filterByGenre(std::string genre)\r\n{\r\n\tint ok = 0;\r\n\tstd::vector<Movie> e{};\r\n\tif (genre == \"empty\")\r\n\t\tok = 1;\r\n\tfor (int i = 0;i < this->getAll().getLenght();i++)\r\n\t{\r\n\t\tif (ok == 0)\r\n\t\t{\r\n\t\t\tMovie m = this->getAll()[i];\r\n\t\t\tif (m.getGenre() == genre)\r\n\t\t\t\te.push_back(m);\r\n\t\t}\r\n\t\telse\r\n\t\t\te.push_back(this->getAll()[i]);\r\n\t}\r\n\treturn e;\r\n}\r\n\r\nvoid Controller::displayHTML()\r\n{\r\n\tthis->html.displayHTML();\r\n}\r\n"
},
{
"alpha_fraction": 0.7250354886054993,
"alphanum_fraction": 0.7841930985450745,
"avg_line_length": 48.30952453613281,
"blob_id": "2d1f57df2886a525d212a714b3c240d50d2b495c",
"content_id": "8e8cabb2050a8afa806354d409724bebc3d746cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2113,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 42,
"path": "/MyProjects/FP/FP/Assignment 5/appstart.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from UI import *\r\nfrom controller import *\r\nfrom repository import *\r\n\r\nstudentRepo=PickleRepository(\"studentRepo.txt\")\r\nassignmentRepo=PickleRepository(\"assignmentRepo.txt\")\r\ngradeRepo=PickleRepository(\"gradeRepo.txt\")\r\nstudentAssignmentsRepo=Repository()\r\nstudentController=Controller(studentRepo)\r\nassignmentController=Controller(assignmentRepo)\r\ngradeController=Controller(gradeRepo)\r\nstudentAssignmentsController=Controller(studentAssignmentsRepo)\r\n'''\r\nstudentController.add(Student(1,'Marian',1))\r\nstudentController.add(Student(2,'George',1))\r\nstudentController.add(Student(3,'Raluca',2))\r\nstudentController.add(Student(4,'Georgiana',3))\r\nstudentController.add(Student(5,'Lucian',3))\r\nstudentController.add(Student(6,'Vasile',2))\r\nstudentController.add(Student(7,'Maria',1))\r\nstudentController.add(Student(8,'Veronica',3))\r\nstudentController.add(Student(9,'Sonia',3))\r\nstudentController.add(Student(10,'Lucica',2))\r\nstudentController.add(Student(11,'Rebeca',1))\r\nstudentController.add(Student(12,'Mircea',2))\r\nstudentController.add(Student(13,'Janina',4))\r\nassignmentController.add(Assignment(1,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(2,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(3,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(4,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(5,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(6,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(7,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(8,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(9,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(10,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(11,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(12,'Solve the problem','7.7.2017'))\r\nassignmentController.add(Assignment(13,'Solve the problem','7.7.2017'))\r\n'''\r\nui=UI(studentController,assignmentController,gradeController,studentAssignmentsController)\r\nui.start()\r\n"
},
{
"alpha_fraction": 0.6006389856338501,
"alphanum_fraction": 0.6006389856338501,
"avg_line_length": 26.454545974731445,
"blob_id": "4b6d08fa4ab7ceef8c40d2e02d2a2bad596318cb",
"content_id": "218e286eea3b55e87dcf81b3713c98fc8719a662",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 11,
"path": "/MyProjects/OOP/OOP/Practice 1/Fast/sportsman.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"sportsman.h\"\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nstd::string Sportsman::overString()\r\n{\r\n\tstringstream lol;\r\n\tlol << \"Aiesta are numele \" << this->getName() << \" cu ID \" << this->getID() << \" si varsta de \" << this->getAge() << \" si mai face si \" << this->getSport();\r\n\treturn lol.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.43036913871765137,
"alphanum_fraction": 0.4467281997203827,
"avg_line_length": 15.939849853515625,
"blob_id": "21e03bd6f88444423c6ef4765d6739ede3b8ba07",
"content_id": "eac5f3a73b823b4586ef41e672120c243896d2ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2384,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 133,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include <iostream>\r\n#include <string>\r\n#include \"node.h\"\r\n#include \"bst.h\"\r\n#include \"iterator.h\"\r\n#include \"tests.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid printMenu()\r\n{\r\n\tcout << \"> Select a command: \\n\";\r\n\tcout << \" 1. Insert a value \\n\";\r\n\tcout << \" 2. Search if a value exists \\n\";\r\n\tcout << \" 3. Remove a value \\n\";\r\n\tcout << \" 4. Print inorder traversal \\n\";\r\n\tcout << \" 0. Exit \\n\";\r\n}\r\n\r\nbool validInput(string command)\r\n{\r\n\tint c;\r\n\tc = stoi(command);\r\n\tif (c < 0 || c>4)\r\n\t{\r\n\t\tcout << \"> Invalid input! \\n\";\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid start()\r\n{\r\n\tTests tes;\r\n\ttes.testAll();\r\n\r\n\tSortedBag<int> bag{ \">\" };\r\n\tbag.insert(5);\r\n\tbag.insert(10);\r\n\tbag.insert(11);\r\n\tbag.insert(7);\r\n\tbag.insert(3);\r\n\tbag.insert(1);\r\n\tbag.insert(4);\r\n\tbag.insert(8);\r\n\t/*\r\n\t\t\t\t 5\r\n\t\t\t / \\\r\n\t\t / \\\r\n\t\t / \\\r\n 3 10\r\n / \\ / \\\r\n\t\t / \\ / \\\r\n\t\t 1 4 7 11\r\n\t\t \\\r\n\t\t\t\t\t \\\r\n\t\t\t\t\t 8\r\n\t*/\r\n\r\n\twhile (true)\r\n\t{\r\n\t\tprintMenu();\r\n\t\tstring command;\r\n\t\tcout << \"> \";\r\n\t\tcin >> command;\r\n\t\twhile (!validInput(command))\r\n\t\t{\r\n\t\t\tcout << \"> \";\r\n\t\t\tcin >> command;\r\n\t\t}\t\r\n\t\tif (command == \"0\")\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse if (command == \"1\")\r\n\t\t{\r\n\t\t\tint in;\r\n\t\t\tcout << \"> Type the value: \";\r\n\t\t\tcin >> in;\r\n\t\t\tbag.insert(in);\r\n\t\t\tcout << \"> Element successfully added!\\n\";\r\n\t\t}\r\n\t\telse if (command == \"2\")\r\n\t\t{\r\n\t\t\tint in;\r\n\t\t\tcout << \"> Type the value: \";\r\n\t\t\tcin >> in;\r\n\t\t\tif (bag.search(in) == true)\r\n\t\t\t\tcout << \"> Element was found!\\n\";\r\n\t\t\telse\r\n\t\t\t\tcout << \"> Element was not found!\\n\";\r\n\t\t}\r\n\t\telse if (command == \"3\")\r\n\t\t{\r\n\t\t\tint in;\r\n\t\t\tcout << \"> Type the value to be removed: \";\r\n\t\t\tcin >> in;\r\n\t\t\tbool ms = bag.remove(in);\r\n\t\t\tif (ms == false)\r\n\t\t\t\tcout << \"> Value not found! \\n\";\r\n\t\t\telse\r\n\t\t\t\tcout << \"> Value deleted! \\n\";\r\n\t\t}\r\n\t\telse if (command == \"4\")\r\n\t\t{\r\n\t\t\tif (bag.size() != 0)\r\n\t\t\t{\r\n\t\t\t\tIterator<int> it = bag.iterator();\r\n\t\t\t\tif (bag.size() == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"Value: \" << it.getValue() << endl;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tint ok1 = 0;\r\n\t\t\t\t\twhile (ok1<bag.size()) {\r\n\t\t\t\t\t\tok1++;\r\n\t\t\t\t\t\tcout << \"Value: \" << it.getValue() << endl;\r\n\t\t\t\t\t\tit.next();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcout << \"There is a total of \" << bag.size() << \" elements. \\n\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tcout << \"> No elements in the bag! \\n\";\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tstart();\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.6405529975891113,
"alphanum_fraction": 0.6774193644523621,
"avg_line_length": 12.466666221618652,
"blob_id": "f9845376b87939a0043f36cddc70629f1394af59",
"content_id": "50fe8a8d4636e446bff34ad3442eab7e8f3af382",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 217,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 15,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/Again12.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_Again12.h\"\r\n\r\nclass Again12 : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tAgain12(QWidget *parent = Q_NULLPTR);\r\n\r\nprivate:\r\n\tUi::Again12Class ui;\r\n};\r\n"
},
{
"alpha_fraction": 0.6366850137710571,
"alphanum_fraction": 0.6692851781845093,
"avg_line_length": 27.61046600341797,
"blob_id": "b36188cce34e89d3b3e1c96ec06e111f9c0eba0a",
"content_id": "94aeb4170215f2e2af6da8c72c3f9f260a8b7d05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 10184,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 344,
"path": "/MyProjects/DB/Lab 2/Lab2.sql",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "use Lab1bun;\r\n\r\ndelete from Parking_Place\r\ndelete from Manager\r\ndelete from Employees\r\ndelete from Shops_Customers\r\ndelete from Customers\r\ndelete from Shops\r\ndelete from Mall\r\ndelete from Helicopter_Pad\r\ndelete from Floors\r\ndelete from Bathrooms\r\n\r\ninsert into Helicopter_Pad values('HP3',35)\r\ninsert into Helicopter_Pad values('HP5',32)\r\ninsert into Mall values('Ma5','Ionci Mall','Satucul Mic street',50,'HP5')\r\ninsert into Bathrooms values('B2',10)\r\ninsert into Bathrooms values('B4',null)\r\n\r\nupdate Helicopter_Pad\r\nset Altitude=30\r\nwhere Altitude>34\r\n\r\nupdate Mall\r\nset Shop_count=47\r\nwhere MaID='Ma5'\r\n\r\nupdate Bathrooms\r\nset Nr_Toilets=20\r\nwhere BID='B4'\r\n\r\ndelete from Mall where MaID='Ma5'\r\ndelete from Bathrooms where BID='B2'\r\n\r\ndelete from Parking_Place\r\ndelete from Manager\r\ndelete from Employees\r\ndelete from Shops_Customers\r\ndelete from Customers\r\ndelete from Shops\r\ndelete from Mall\r\ndelete from Helicopter_Pad\r\ndelete from Floors\r\ndelete from Bathrooms\r\n\r\ninsert into Helicopter_Pad values('HP1',10)\r\ninsert into Helicopter_Pad values('HP1',10)\r\ninsert into Helicopter_Pad values('HP2',null)\r\ninsert into Helicopter_Pad values('HP3',35)\r\ninsert into Helicopter_Pad values('HP4',49)\r\ninsert into Helicopter_Pad values('HP5',32)\r\ninsert into Helicopter_Pad values('HP6',50)\r\n\r\ninsert into Mall values('Ma1','Iulus Mall','Iulius street',70,'HP1')\r\ninsert into Mall values('Ma2','Polus Mall','Gradinarilor street',150,'HP2')\r\ninsert into Mall values('Ma3','Gold Plaza','b-dul Bucuresti',80,'HP3')\r\ninsert into Mall values('Ma4','City Mall','Mamaia street',200,'HP4')\r\ninsert into Mall values('Ma5','Ionci Mall','Satucul Mic street',50,'HP5')\r\ninsert into Mall values('Ma6','RoMall','Sesamy street',190,'HP6')\r\ninsert into Mall values('Ma7','Ricola Mall','Urubentilor street',70,'HP6')\r\n\r\ninsert into Bathrooms values('B1',7)\r\ninsert into Bathrooms values('B2',10)\r\ninsert into Bathrooms values('B3',2)\r\ninsert into Bathrooms values('B4',null)\r\ninsert into Bathrooms values('B5',17)\r\n\r\ninsert into Floors values('F1',37,'B1')\r\ninsert into Floors values('F2',70,'B2')\r\ninsert into Floors values('F3',59,'B3')\r\ninsert into Floors values('F4',39,'B4')\r\ninsert into Floors values('F5',40,'B5')\r\n\r\ninsert into Shops values('Sh1','Armani','Clothing','F1','Ma1')\r\ninsert into Shops values('Sh2','H&M','Clothing','F2','Ma1')\r\ninsert into Shops values('Sh3','NewYorker','Clothing','F1','Ma1')\r\ninsert into Shops values('Sh4','Subway','FastFood','F1','Ma2')\r\ninsert into Shops values('Sh5','KFC','FastFood','F3','Ma2')\r\ninsert into Shops values('Sh6','Amanet','Exchange','F2','Ma3')\r\n\r\ninsert into Customers values('C1','Vladov',200)\r\ninsert into Customers values('C2','Vladimir',270)\r\ninsert into Customers values('C3','Vladovik',480)\r\ninsert into Customers values('C4','Vlad',370)\r\ninsert into Customers values('C5','Klaus',209)\r\ninsert into Customers values('C6','Omi',500)\r\ninsert into Customers values('C7','Iulian Mures',189)\r\ninsert into Customers values('C8','Marian Goga',900)\r\n\r\ninsert into Shops_Customers values('Sh1','C1',20)\r\ninsert into Shops_Customers values('Sh1','C2',19)\r\ninsert into Shops_Customers values('Sh1','C3',23)\r\ninsert into Shops_Customers values('Sh2','C4',21)\r\ninsert into Shops_Customers values('Sh4','C5',40)\r\ninsert into Shops_Customers values('Sh4','C6',28)\r\ninsert into Shops_Customers values('Sh3','C7',30)\r\ninsert into Shops_Customers values('Sh2','C8',20)\r\n\r\ninsert into Manager values('M1','Maria',28,2,'Ma3')\r\ninsert into Manager values('M3','Julian',32,4,'Ma2')\r\ninsert into Manager values('M2','Klaus',26,1,'Ma4')\r\ninsert into Manager values('M4','Irinel',27,0,'Ma3')\r\n\r\ninsert into Employees values('E1','Marian Goga',2998,'Sh3')\r\ninsert into Employees values('E2','Irinescu Ioan',3484,'Sh2')\r\ninsert into Employees values('E3','Iulian Mures',7284,'Sh2')\r\ninsert into Employees values('E4','Junike Lucian',2642,'Sh3')\r\ninsert into Employees values('E5','Oriandru Kuronda',3614,'Sh1')\r\n\r\ninsert into Parking_Place values('PP1','Amsterdam street','Ma2')\r\ninsert into Parking_Place values('PP2','Logika street','Ma3')\r\ninsert into Parking_Place values('PP3','Bucuresti street','Ma1')\r\ninsert into Parking_Place values('PP4','Iubireni street','Ma3')\r\ninsert into Parking_Place values('PP5','Lucescu street','Ma4')\r\n\r\n--a)___________________________________________________________________\r\n\r\n-- prints the name of the customers and the name of the shops\r\nselect Customer_Name from Customers\r\nunion all\r\nselect Shop_Name from Shops\r\n\r\n-- prints the name of the customers that ends with r or starts with Vlad\r\nselect Customer_Name from Customers\r\nwhere Customer_Name like '%r' or Customer_Name like 'Vlad%'\r\n\r\n\r\n--b)____________________________________________________________________\r\n\r\n-- prints the employee names that are the same as the custommers names\r\n\r\nselect Customer_Name from Customers\r\nintersect\r\nselect Employee_Name from Employees\r\nselect *\r\nfrom Employees\r\nselect *\r\nfrom Customers\r\n-- prints the malls having 70, 50 or 80 shops\r\n\r\nselect Mall_Name,Shop_count from Mall\r\nwhere Shop_count in (50,70,80)\r\n\r\n\r\n--c)____________________________________________________________________\r\n\r\n-- prints the mall shops are different than 70, 50 and 80\r\n\r\nselect Mall_Name, Shop_Count from Mall\r\nwhere Shop_count not in (50,70,80)\r\n\r\n-- prints the names of employees that are not customers\r\n\r\nselect Employee_Name from Employees\r\nexcept\r\nselect Customer_Name from Customers\r\n\r\n\r\n--d)_____________________________________________________________________\r\n\r\n-- prints the shops that are the same for the employees and the customers\r\n\r\nselect distinct S.Shop_Name,S.ShID\r\nfrom ((Shops S\r\ninner join Employees E on E.ShID=S.ShID)\r\ninner join Shops_Customers SC on SC.ShID=S.ShID)\r\n\r\n-- prints all the shops and any employees they might have \r\n\r\nselect distinct S.Shop_Name,E.Employee_Name\r\nfrom Shops S\r\nleft outer join Employees e on S.ShID=E.ShID\r\n\r\n-- prints the first 5 employees that might work where customers go\r\n-- in decreasing order\r\n\r\nselect top 5 S.ShID, E.Employee_Name\r\nfrom Shops_Customers S\r\nright outer join Employees E on E.ShID=S.ShID\r\norder by ShID desc\r\n\r\n-- prints all floors with bathrooms in decreasing order\r\n-- by the FID\r\n\r\nselect F.FID,B.BID\r\nfrom Floors F\r\nfull outer join Bathrooms B on B.BID=F.BID\r\norder by F.FID desc\r\n\r\n--e)_________________________________________________________________\r\n\r\n-- prints the first two shopIDs from Shops that had custommers \r\n-- with a budget above 300\r\n\r\nselect ShID\r\nfrom Shops\r\nwhere ShID in (select ShID\r\n\t\tfrom Shops_Customers S\r\n\t\twhere S.CID in(select C.CID\r\n\t\t\t\tfrom Customers C\r\n\t\t\t\twhere C.Budget>300))\r\nselect *\r\nfrom Customers\r\nselect *\r\nfrom Shops_Customers\r\n\r\n-- for every mall, prints the helicopter pad that has an altitude\r\n-- between 32 and 50\r\n-- ordered deacrisingly by MaID\r\n\r\nselect MaID\r\nfrom Mall M\r\nwhere M.HPID in(select HPID\r\n\t\t\t\tfrom Helicopter_Pad\r\n\t\t\t\twhere Altitude>32 and Altitude<50)\r\norder by MaID desc\r\nselect *\r\nfrom Helicopter_Pad\r\n\r\n--f)_____________________________________________________________________\r\n\r\n-- prints the name of the mall which has a manager older than 27\r\n\r\nselect Mall_Name,MaID\r\nfrom Mall\r\nwhere exists(select MID\r\n\t\t\tfrom Manager\r\n\t\t\twhere Manager.MaID=Mall.MaID and Age>27)\r\nselect *\r\nfrom Manager\r\n-- prints the floors that have bathrooms with the number of toilets smaller\r\n-- than 10\r\n\r\nselect FID\r\nfrom Floors\r\nwhere exists (select BID\r\n\t\t\tfrom Bathrooms\r\n\t\t\twhere Bathrooms.BID=Floors.BID and Nr_Toilets<10)\r\nselect *\r\nfrom Bathrooms\r\nselect *\r\nfrom Floors\r\n--g)____________________________________________________________________\r\n\r\n-- prints the shopID from Shops_Customers for a customer \r\n-- that is older than 29\r\n\r\nselect distinct H.ShID\r\nfrom(select *\r\n\tfrom Shops_Customers\r\n\twhere Shops_Customers.Age>29) H\r\n\r\n-- prints the shopID from Shops that have employees with salary more than\r\n-- 3000\r\n\r\nselect distinct H.ShID\r\nfrom(select *\r\n\tfrom Employees\r\n\twhere Salary>3000) H\r\nselect *\r\nfrom Employees\r\n\r\n--h)___________________________________________________________________\r\n\r\n-- prints the shops that had at least 2 customers\r\n\r\nselect S.ShID,S.Shop_Name\r\nfrom Shops S\r\ninner join Shops_Customers SC on S.ShID=SC.ShID\r\ngroup by S.ShID,S.Shop_Name\r\nhaving count(*)>1\r\n-- prints the average budget of every customer older than 20\r\n\r\nselect AVG(C.Budget) as 'Average salary'\r\nfrom Customers C\r\nwhere C.Budget in (select H.Budget\r\n\t\t\t\t\tfrom Customers H\r\n\t\t\t\t\twhere H.CID in\r\n\t\t\t\t\t(select CID\r\n\t\t\t\t\tfrom Shops_Customers\r\n\t\t\t\t\twhere Age>29))\r\n\r\n-- prints the total number of toilets on a floor \r\n-- with an area greater than 20\r\n\r\nselect SUM(Nr_Toilets) as 'Total toilets'\r\nfrom Bathrooms\r\nwhere BID in (select F.BID\r\n\t\t\t\tfrom Floors F\r\n\t\t\t\twhere F.Area>20)\r\n\r\n-- prints the minimum budget of any customer older than 30\r\n\r\nselect MIN(C.Budget) as 'Minimum salary'\r\nfrom Customers C\r\nwhere C.Budget in (select H.Budget\r\n\t\t\t\t\tfrom Customers H\r\n\t\t\t\t\twhere H.CID in\r\n\t\t\t\t\t(select CID\r\n\t\t\t\t\tfrom Shops_Customers\r\n\t\t\t\t\twhere Age>30))\r\n\r\n\r\n--i)___________________________________________________________________\r\n\r\n-- prints the mall with it's address of some malls with Helli pad at \r\n-- at an altitude over 40\r\n\r\nselect concat(M.Mall_Name,' on ',M.Mall_Address) as 'Location'\r\nfrom Mall M\r\nwhere M.HPID = any(select H.HPID\r\n\t\t\t\t\tfrom Helicopter_Pad H\r\n\t\t\t\t\twhere H.HPID=M.HPID and H.Altitude>40)\r\n\r\n-- prints the mall with it's address of all malls with Helli pad at \r\n-- at an altitude over 30\r\n\r\nselect concat(M.Mall_Name,' on ',M.Mall_Address) as 'Location'\r\nfrom Mall M\r\nwhere M.HPID = all(select H.HPID\r\n\t\t\t\t\tfrom Helicopter_Pad H\r\n\t\t\t\t\twhere H.HPID=M.HPID and H.Altitude>30)\r\n\r\n-- prints all from shops_custoomers, for a custommer with the name that\r\n-- starts with V\r\n\r\nselect *\r\nfrom Shops_Customers SC\r\nwhere SC.Age=any(select Age\r\n\t\t\t\tfrom Shops_Customers\r\n\t\t\t\twhere CID in(select H.CID\r\n\t\t\t\t\t\t\tfrom Customers H\r\n\t\t\t\t\t\t\twhere H.Customer_Name like 'V%'))\r\n\r\n-- prints all from shops_custoomers, for a custommer with the name that\r\n-- does not start with V\r\n\r\nselect *\r\nfrom Shops_Customers SC\r\nwhere SC.Age=any(select Age\r\n\t\t\t\tfrom Shops_Customers\r\n\t\t\t\twhere CID not in(select H.CID\r\n\t\t\t\t\t\t\tfrom Customers H\r\n\t\t\t\t\t\t\twhere H.Customer_Name like 'V%'))"
},
{
"alpha_fraction": 0.5688073635101318,
"alphanum_fraction": 0.5733944773674011,
"avg_line_length": 11.75,
"blob_id": "e79a3a97080924e0023c6ae72c0e4e29b1576513",
"content_id": "b9eb1ce6ed1ab540326b4745b89162b8d1439a1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 16,
"path": "/MyProjects/OOP/OOP/Practice 2/DoNow/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include <iostream>\r\n#include \"UI.h\"\r\n#include \"Controller.h\"\r\n#include \"Repository.h\"\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\t{\r\n\t\tRepository r{};\r\n\t\tController c{ r };\r\n\t\tUI u{ c };\r\n\t\tu.start();\r\n\t}\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.6887186765670776,
"alphanum_fraction": 0.6887186765670776,
"avg_line_length": 34.871795654296875,
"blob_id": "3e4fc3209406d5bdef3b3e7a0f2047310d7f5b40",
"content_id": "9fcd29bb420f01b97d0baa598393953c720509a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1436,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 39,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"ProgrammerRepo.h\"\r\n#include \"TaskRepo.h\"\r\n#include \"task.h\"\r\n#include \"programmer.h\"\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tProgrammerRepo<Programmer>& progs;\r\n\tTaskRepo<Task>& tasks;\r\npublic:\r\n\tController(ProgrammerRepo<Programmer>& p, TaskRepo<Task>& t) :progs{ p }, tasks{ t } {}\r\n\tController() :progs{ProgrammerRepo<Programmer>()}, tasks{ TaskRepo<Task> ()} {}\r\n\t~Controller() {}\r\n\r\n\tProgrammerRepo<Programmer>& getProgs() { return progs; }\r\n\tTaskRepo<Task>& getTasks() { return tasks; }\r\n\r\n\tvoid addTask(Task t) { tasks.add(t); }\r\n\t//Deletes an element from position 'pos'\r\n\t//in: int pos, the position\r\n\t//out: the element on position pos was deleted\r\n\tvoid delTask(int pos) { tasks.del(pos); }\r\n\r\n\tvoid saveTasks() { tasks.writeToFile(); }\r\n\tvoid sortTasks() { tasks.sortMe(); }\r\n\r\n\t//Sets the status of an element from the position 'pos' to 'closed'\r\n\t//in: int pos, the position of the element\r\n\t//out: the status of an element from the position 'pos' has been set to 'closed'\r\n\tvoid startTask(int pos, int id,std::string n);\r\n\t//Sets the status of an element from the position 'pos' to 'in progress' and the programmerID of the task to be the 'id'\r\n\t//in: int pos, int id, the position of the element and the new id\r\n\t//out: the status of an element from the position 'pos' has been set to 'in progress' and the programmerID is 'id'\r\n\tvoid finishTask(int pos);\r\n\r\n\tController& operator=(Controller& c);\r\n};"
},
{
"alpha_fraction": 0.5209580659866333,
"alphanum_fraction": 0.5259481072425842,
"avg_line_length": 15.578947067260742,
"blob_id": "b9935084e5703186921c618380ab7758bd73eb0f",
"content_id": "e884e9601330dacde129814f15d8ddf32866e97f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1002,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 57,
"path": "/MyProjects/OOP/OOP/Written 1/OOP written/Stack.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <exception>\r\n#include <assert.h>\r\n#include <vector>\r\n\r\ntemplate <typename T>\r\nclass Stack\r\n{\r\nprivate:\r\n\tint cap;\r\n\tint len;\r\n\tT* st;\r\npublic:\r\n\tStack(int c){\r\n\t\tlen = 0;\r\n\t\tcap = c;\r\n\t\tst = new T[c];\r\n\t}\r\n\t~Stack() { delete[] this->st; }\r\n\tStack& operator+(const T& s)\r\n\t{\r\n\t\tif (len == cap)\r\n\t\t\t//throw exception(\"Stack is full!\");\r\n\t\tthis->st[this->len] = s;\r\n\t\tthis->len++;\r\n\t\treturn *this;\r\n\t}\r\n\tT pop()\r\n\t{\r\n\t\tlen--;\r\n\t\treturn st[len];\r\n\t}\r\n\tint getMaxCapacity() { return cap; }\r\n\tStack& operator=(const Stack& s)\r\n\t{\r\n\t\tfor (int i = 0;i < s.cap;i++)\r\n\t\t\tthis->st[i] = s.st[i];\r\n\t\treturn *this;\r\n\t}\r\n\tT operator[](int pos) { return st[pos]; }\r\n};\r\nvoid testStack()\r\n{\r\n\tStack<std::string> s{ 2 };\r\n\tassert(s.getMaxCapacity() == 2);\r\n\ttry {\r\n\t\ts = s + \"examination\";\r\n\t\ts = s + \"oop\";\r\n\t\ts = s + \"test\";\r\n\t}\r\n\tcatch (std::exception& e) {\r\n\t\tassert(strcmp(e.what(), \"Stack is full!\") == 0);\r\n\t}\r\n\tassert(s.pop() == \"test\");\r\n\tassert(s.pop() == \"oop\");\r\n}\r\n"
},
{
"alpha_fraction": 0.5369424819946289,
"alphanum_fraction": 0.5437936782836914,
"avg_line_length": 22.247556686401367,
"blob_id": "798baf29c46eb4ab40967c3579d88fce626b7698",
"content_id": "f2bc4bfc5af70e0f6f0824a343f5c22033540902",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7444,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 307,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/UI.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid UI::start()\r\n{\r\n\twhile (true)\r\n\t{\r\n\t\tUI::printMenu();\r\n\t\tint command{ 0 };\r\n\t\tcout << \"Please enter the command: \";\r\n\t\tcin >> command;\r\n\t\tcin.ignore();\r\n\t\tif (command == 0)\r\n\t\t\tbreak;\r\n\r\n\t\tif (command == 1)\r\n\t\t{\r\n\t\t\twhile (true)\r\n\t\t\t{\r\n\t\t\t\tUI::printRepo();\r\n\t\t\t\tint commandRepo{ 0 };\r\n\t\t\t\tdo\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"Input your command: \";\r\n\t\t\t\t\tcin >> commandRepo;\r\n\t\t\t\t\tcin.ignore();\r\n\t\t\t\t} while (commandRepo < 0 || commandRepo > 4);\r\n\t\t\t\tif (commandRepo == 0)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tswitch (commandRepo)\r\n\t\t\t\t{\r\n\t\t\t\tcase 1:\r\n\t\t\t\t\tthis->addMovieToRepo();\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\tthis->delMovieFromRepo();\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\tthis->updateMovieInRepo();\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 4:\r\n\t\t\t\t\tthis->printAllMovies();\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (command == 2)\r\n\t\t{\r\n\t\t\twhile (true)\r\n\t\t\t{\r\n\t\t\t\tUI::printList();\r\n\t\t\t\tint commandWatchList{ 0 };\r\n\t\t\t\tdo\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"Input your command: \";\r\n\t\t\t\t\tcin >> commandWatchList;\r\n\t\t\t\t\tcin.ignore();\r\n\t\t\t\t} while (commandWatchList < 0 || commandWatchList > 4);\r\n\t\t\t\tcout << endl;\r\n\t\t\t\tif (commandWatchList == 0)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t{\r\n\t\t\t\t\tif (commandWatchList == 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tthis->addMovieToList();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (commandWatchList == 2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << \"Type the genre that you want to filter (empty if not specified): \";\r\n\t\t\t\t\t\tstring k;\r\n\t\t\t\t\t\tcin >> k;\r\n\t\t\t\t\t\tRepository re = this->controller.getGenreRepo(k);\r\n\t\t\t\t\t\tprintAllMoviesR(re.getMovies());\r\n\t\t\t\t\t\tstring maybe;\r\n\t\t\t\t\t\tre.setCurrentM();\r\n\t\t\t\t\t\tre.nextM();\r\n\t\t\t\t\t\tint stp = 0;\r\n\t\t\t\t\t\twhile (true)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (int i = 0;i < re.getMovies().getLenght();i++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcout << \"Do you want to watch the next trailer (type 'yes' or 'no')? \";\r\n\t\t\t\t\t\t\t\tcin >> maybe;\r\n\t\t\t\t\t\t\t\tif (maybe == \"yes\")\r\n\t\t\t\t\t\t\t\t\tre.nextM();\r\n\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tstp = 1;\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif (stp == 1)\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (commandWatchList == 3)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstring ttl;\r\n\t\t\t\t\t\tcout << \"Type the name of the movie that you want to delete: \";\r\n\t\t\t\t\t\tcin >> ttl;\r\n\t\t\t\t\t\tint okk1 = this->controller.getRepo().findP(ttl);\r\n\t\t\t\t\t\tthis->controller.delL(ttl);\r\n\t\t\t\t\t\tif (okk1 != -1)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tcout << \"Would you like to rate this movie ('yes' or 'no')?\";\r\n\t\t\t\t\t\t\tstring mby;\r\n\t\t\t\t\t\t\tcin >> mby;\r\n\t\t\t\t\t\t\tif (mby == \"yes\")\r\n\t\t\t\t\t\t\t\tthis->controller.incLike(okk1);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tcout << \"The movie was not found!\" << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (commandWatchList == 4)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tthis->printAllMoviesList();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid UI::printMenu()\r\n{\r\n\tcout << endl;\r\n\tcout << \"1 - You the admin or nah, if not why are you here?\" << endl;\r\n\tcout << \"2 - User menu, blah, boooring.\" << endl;\r\n\tcout << \"0 - You wouldn't dare.\" << endl;\r\n}\r\n\r\nvoid UI::printRepo()\r\n{\r\n\tcout <<endl<< \"Possible things to happen on this beautiful day: \" << endl;\r\n\tcout << \"\\t 1 - Add movie, come on, I know you want to.\" << endl;\r\n\tcout << \"\\t 2 - Remove movie, man, why would you do that?\" << endl;\r\n\tcout << \"\\t 3 - Update movie, why didn't you like the first one??\" << endl;\r\n\tcout << \"\\t 4 - Display all, can't you choose just one?\" << endl;\r\n\tcout << \"\\t 0 - That's a no no!\" << endl;\r\n}\r\n\r\nvoid UI::printList()\r\n{\r\n\tcout <<endl<< \"Possible activities that you would like to do on this day: \" << endl;\r\n\tcout << \"\\t 1 - Add movie, what, where, when?\" << endl;\r\n\tcout << \"\\t 2 - Sort by genre, well, if you really want to...\" << endl;\r\n\tcout << \"\\t 3 - Delete a movie, muhahahha\" << endl;\r\n\tcout << \"\\t 4 - Display all movies, why though?\" << endl;\r\n\tcout << \"\\t 0 - Don't make me call you something bad\" << endl;\r\n}\r\n\r\nvoid UI::addMovieToRepo()\r\n{\r\n\tcout << \"Enter the title:\";\r\n\tstring title;\r\n\tgetline(cin, title);\r\n\tcout << \"Enter the genre:\";\r\n\tstring genre;\r\n\tgetline(cin, genre);\r\n\tint year = 0;\r\n\tcout << \"Enter the year:\";\r\n\tcin >> year;\r\n\tint likes = 0;\r\n\tcout << \"Enter the likes:\";\r\n\tcin >> likes;\r\n\tcin.ignore();\r\n\tcout << \"Trailer:\";\r\n\tstring link;\r\n\tgetline(cin, link);\r\n\r\n\tbool ok = this->controller.addMovieToRepo(title, genre, year, likes, link);\r\n\tif (ok)\r\n\t\tcout << \"The movie was succesfully added!\\n\";\r\n\telse\r\n\t\tcout << \"Error! The movie is already in the list!\\n\";\r\n\treturn;\r\n}\r\n\r\nvoid UI::delMovieFromRepo()\r\n{\r\n\tcout << \"Enter the title of the movie that you want removed: \";\r\n\tstring title;\r\n\tgetline(cin, title);\r\n\tbool ok = this->controller.delMovieFromRepo(title);\r\n\tif(ok)\r\n\t\tcout << \"The movie was successfully removed!\\n\";\r\n\telse\r\n\t\tcout << \"Error! No movie was found with the given title!\";\r\n\treturn;\r\n}\r\n\r\nvoid UI::updateMovieInRepo()\r\n{\r\n\tcout << \"Enter the name of the movie that you want updated: \";\r\n\tstring title;\r\n\tgetline(cin, title);\r\n\tcout << \"Enter a new name for the movie: \";\r\n\tstring newTitle;\r\n\tgetline(cin, newTitle);\r\n\tcout << \"Enter the genre for the movie: \";\r\n\tstring newGenre;\r\n\tgetline(cin, newGenre);\r\n\tint newYear = 0;\r\n\tcout << \"Enter the year for the movie: \";\r\n\tcin >> newYear;\r\n\tcin.ignore();\r\n\tint newLikes = 0;\r\n\tcout << \"Enter the likes for the movie: \";\r\n\tcin >> newLikes;\r\n\tcin.ignore();\r\n\tcout << \"Enter the link for the movie: \";\r\n\tstring newLink;\r\n\tgetline(cin, newLink);\r\n\tbool ok = this->controller.updateMovieToRepo(title, newTitle, newGenre, newYear, newLikes, newLink);\r\n\tif(ok)\r\n\t\tcout << \"The movie was successfully updated!\\n\";\r\n\telse\r\n\t\tcout << \"Error! No movie was found with the given title!\";\r\n\treturn;\r\n}\r\n\r\nvoid UI::printAllMovies()\r\n{\r\n\tVector v = this->controller.getRepo().getMovies();\r\n\tMovie* mov = v.getAll();\r\n\tif (mov == NULL)\r\n\t\treturn;\r\n\tif (v.getLenght() == 0)\r\n\t{\r\n\t\tcout << \"There are no movies in the repository!\" << endl;\r\n\t\treturn;\r\n\t}\r\n\tfor (int i = 0; i < v.getLenght(); i++) {\r\n\t\tMovie m = mov[i];\r\n\t\tcout << \"Title: \" << m.getTitle() << endl;\r\n\t\tcout << \"Genre: \" << m.getGenre() << endl;\r\n\t\tcout << \"Year: \" << m.getYear() << endl;\r\n\t\tcout << \"Likes: \" << m.getLikes() << endl;\r\n\t\tcout << \"Link: \" << m.getTrailer() << endl;\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\nvoid UI::printAllMoviesList()\r\n{\r\n\tVector v = this->controller.getList().getM();\r\n\tMovie* mov = v.getAll();\r\n\tif (mov == NULL)\r\n\t\treturn;\r\n\tif (v.getLenght() == 0)\r\n\t{\r\n\t\tcout << \"There are no movies in the repository!\" << endl;\r\n\t\treturn;\r\n\t}\r\n\tfor (int i = 0; i < v.getLenght(); i++) {\r\n\t\tMovie m = mov[i];\r\n\t\tcout << \"Title: \" << m.getTitle() << endl;\r\n\t\tcout << \"Genre: \" << m.getGenre() << endl;\r\n\t\tcout << \"Year: \" << m.getYear() << endl;\r\n\t\tcout << \"Likes: \" << m.getLikes() << endl;\r\n\t\tcout << \"Link: \" << m.getTrailer() << endl;\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\nvoid UI::printAllMoviesR(Vector v)\r\n{\r\n\tMovie* mov = v.getAll();\r\n\tif (mov == NULL)\r\n\t\treturn;\r\n\tif (v.getLenght() == 0)\r\n\t{\r\n\t\tcout << \"There are no movies in the repository!\" << endl;\r\n\t\treturn;\r\n\t}\r\n\tfor (int i = 0; i < v.getLenght(); i++) {\r\n\t\tMovie m = mov[i];\r\n\t\tcout << \"Title: \" << m.getTitle() << endl;\r\n\t\tcout << \"Genre: \" << m.getGenre() << endl;\r\n\t\tcout << \"Year: \" << m.getYear() << endl;\r\n\t\tcout << \"Likes: \" << m.getLikes() << endl;\r\n\t\tcout << \"Link: \" << m.getTrailer() << endl;\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\nvoid UI::addMovieToList()\r\n{\r\n\tcout << \"Please enter the title: \";\r\n\tstring title;\r\n\tgetline(cin, title);\r\n\r\n\tMovie m = this->controller.getRepo().findByTitle(title);\r\n\tif (m.getTitle() == \"\") \r\n\t{\r\n\t\tcout << \"There are no movies of that title in the repository!\" << endl;\r\n\t\treturn;\r\n\t}\r\n\tthis->controller.addMovieToList(m);\r\n}\r\n"
},
{
"alpha_fraction": 0.6575342416763306,
"alphanum_fraction": 0.6575342416763306,
"avg_line_length": 19,
"blob_id": "f0ce9010b43bfd443ea8723989c22bc5f33440ce",
"content_id": "f134560e9e8d1374e4324066856836220042bc63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 14,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/html.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n\r\nclass HTML {\r\nprivate:\r\n\tRepository repo;\r\n\tstd::string filename;\r\npublic:\r\n\tHTML(Repository r) :repo{ r }, filename{ \"HTMLfile.html\" } { this->writeToFile(); }\r\n\t~HTML() {}\r\n\tvoid setRepo(Repository r);\r\n\tvoid writeToFile();\r\n\tvoid displayHTML();\r\n};"
},
{
"alpha_fraction": 0.4844246804714203,
"alphanum_fraction": 0.4901462197303772,
"avg_line_length": 24.694915771484375,
"blob_id": "9fc3cd543f1c35c05f2eda8cd7016dfa3a1680bb",
"content_id": "29753aef173ed367deb033a2387e91a9c2b1732a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1573,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 59,
"path": "/MyProjects/FP/FP/Practice Test 1/domain.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Driver:\r\n def __init__(self,id,name):\r\n self.__id=id\r\n self.__name=name\r\n def __str__(self):\r\n s=''\r\n s=s+'ID: '+str(self.__id)+' Name: '+str(self.__name)\r\n return s\r\n def setID(self,id):\r\n self.__id=id\r\n def setName(self,name):\r\n self.__name=name\r\n def getID(self):\r\n return self.__id\r\n def getName(self):\r\n return self.__name\r\n\r\nclass Order:\r\n def __init__(self,driverID,dist):\r\n self.__id=driverID\r\n self.__distance=dist\r\n def __str__(self):\r\n s=''\r\n s=s+'Driver ID: '+str(self.__id)+' Distance traveled: '+str(self.__distance)\r\n return s\r\n def setID(self,id):\r\n self.__id=id\r\n def setDistance(self,dist):\r\n self.__distance=dist\r\n def getID(self):\r\n return self.__id\r\n def getDistance(self):\r\n return self.__distance\r\n\r\nclass DriverOrders:\r\n def __init__(self,id):\r\n self.__orders=[]\r\n self.__id=id\r\n def add(self,el):\r\n if el<1:\r\n print(\"Distance not valid!\")\r\n else:\r\n self.__orders.append(el)\r\n def getOrders(self):\r\n return self.__orders\r\n def getID(self):\r\n return self.__id\r\n def income(self):\r\n s=0\r\n if len(self.__orders)==0:\r\n return 0\r\n for i in range(len(self.__orders)):\r\n s=s+self.__orders[i]\r\n return s*2.5\r\n def orderValue(self,index):\r\n if index <len(self.__orders):\r\n s=self.__orders[index]\r\n return s*2.5\r\n return -1"
},
{
"alpha_fraction": 0.640816330909729,
"alphanum_fraction": 0.640816330909729,
"avg_line_length": 22.600000381469727,
"blob_id": "664179ac8d975c4bb3c4e24178974e01b2d9f09d",
"content_id": "64a3374e615039f58838988dfb0e9dc67edb445f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 490,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 20,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/domain.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n\r\nclass Task\r\n{\r\nprivate:\r\n\tstd::string description;\r\n\tint duration;\r\n\tint priority;\r\npublic:\r\n\tTask() :description{ \"\" }, duration{ }, priority{ } {}\r\n\tTask(std::string des, int dur, int prio) :description{ des }, duration{ dur }, priority{ prio } {}\r\n\t~Task() {}\r\n\tstd::string getDescription() { return description; }\r\n\tint getDuration() { return duration; }\r\n\tint getPriority() { return priority; }\r\n\r\n\tstd::string toString();\r\n\tstd::string stri();\r\n};"
},
{
"alpha_fraction": 0.5170778036117554,
"alphanum_fraction": 0.5246679186820984,
"avg_line_length": 15.566666603088379,
"blob_id": "275c4e2e256ad13dda06d9da8ef212e3be21a3e9",
"content_id": "2f14ff7666cd282d5b912f48b91907af0988ed84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1054,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 60,
"path": "/MyProjects/OOP/OOP/OOP Test/Test/UI.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\n\r\nvoid UI::printMenu()\r\n{\r\n\tcout << \"The menu is:\" << endl;\r\n\tcout << \"1. add a player to the list\" << endl;\r\n\tcout << \"2. print all players\" << endl;\r\n\tcout << \"3. total goals from a country\" << endl;\r\n}\r\n\r\n\r\n\r\nvoid UI::start()\r\n{\r\n\twhile (true)\r\n\t{\r\n\t\tUI::printMenu();\r\n\t\tint command{ 0 };\r\n\t\tcout << \"Please enter the command: \";\r\n\t\tcin >> command;\r\n\t\tcin.ignore();\r\n\t\tif (command == 0)\r\n\t\t\tbreak;\r\n\t\twhile (true)\r\n\t\t{\r\n\t\t\tif(command==1)\r\n\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid UI::printRepo()\r\n{\r\n\tVector v = this->controller.getRepo().getPlayers();\r\n\tPlayer* p = v.getAll();\r\n\tif (p == NULL)\r\n\t\treturn;\r\n\tif (v.getLenght() == 0)\r\n\t{\r\n\t\tcout << \"There are no players in the repository!\" << endl;\r\n\t\treturn;\r\n\t}\r\n\tfor (int i = 0; i < v.getLenght(); i++) {\r\n\t\tPlayer m = p[i];\r\n\t\tcout << \"Name: \" << m.getName();\r\n\t\tcout << \", Nationality: \" << m.getNationality();\r\n\t\tcout << \", Team: \" << m.getTeam();\r\n\t\tcout << \", Goals: \" << m.getGoals();\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n\r\nvoid UI::addMovieToRepo()\r\n{\r\n\t\r\n}\r\n"
},
{
"alpha_fraction": 0.5968309640884399,
"alphanum_fraction": 0.5985915660858154,
"avg_line_length": 19.846153259277344,
"blob_id": "bb7049751ec6d8ada93fc4961c0163f037c3f535",
"content_id": "745c8c596169b2765e3eb940307d803a4d60a8a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 568,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 26,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/task.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"task.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nstd::string Task::toString()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Description: \" << description << \", Status: \" << status;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Task::toString1()\r\n{\r\n\tstringstream buff;\r\n\tbuff << \"Description: \" << description << \", Status: \" << status << \", ProgrammerName: \" << progName;\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Task::stri()\r\n{\r\n\tstringstream buff;\r\n\tbuff<<description << \",\" << stat << \",\" << programmerid<<\",\"<<progName;\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.5491606593132019,
"alphanum_fraction": 0.5539568066596985,
"avg_line_length": 13.55555534362793,
"blob_id": "aeef3e0c1aa636f983ea332a223bf4b1c780af4c",
"content_id": "507df0e09dc39dbb7fab0c428a88336ae5e1711a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 417,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 27,
"path": "/MyProjects/OOP/OOP/Written 1/OOP written/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include <iostream>\r\n#include \"2.h\"\r\n#include <deque>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tstd::deque<std::string> d;\r\n\td.push_back(\"A\");\r\n\td.push_front(\"B\");\r\n\td.push_back(\"C\");\r\n\td.push_front(\"D\");\r\n\tauto itBegin = d.begin();\r\n\tauto itEnd = d.end();\r\n\titBegin++;\r\n\titEnd--;\r\n\twhile (itBegin != itEnd)\r\n\t{\r\n\t\tstd::cout << *itBegin << \" \";\r\n\t\titBegin++;\r\n\t}\r\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}"
},
{
"alpha_fraction": 0.562601625919342,
"alphanum_fraction": 0.5788617730140686,
"avg_line_length": 25.954545974731445,
"blob_id": "1059091b769d85ad4fbafc74072921cd486a4643",
"content_id": "b411b1d7133c5e690da49a6cdeb3a124428935fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 615,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 22,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Vegetables.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"repository.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\tRepository r{ \"All.txt\" };\r\n\t//Vegetable v1{ \"Potato family\", \"Potato\",{ \"fruit\" } };\r\n\t//Vegetable v2{ \"Potato family\", \"Tomato\",{ \"fruit\" } };\r\n\t//Vegetable v3{ \"Beetroot family\", \"Spinach\",{ \"leaves\" } };\r\n\t//Vegetable v4{ \"Marrow family\", \"Melon\",{ \"fruit\" } };\r\n\t//Vegetable v5{ \"Onion family\", \"Onion\",{ \"stem\",\"root\" } };\r\n\t//r.add(v1);\r\n\t//r.add(v2);\r\n\t//r.add(v3);\r\n\t//r.add(v4);\r\n\t//r.add(v5);\r\n\tVegetables w{ r };\r\n\tw.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.4560260474681854,
"alphanum_fraction": 0.4560260474681854,
"avg_line_length": 19.928571701049805,
"blob_id": "8d3856dbaee4d638c83f67faafd466e1f7506d9d",
"content_id": "4aadaa16d34ea55f0db998b72f1604cc072076ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 56,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Utilities/MyStack.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Utilities\r\n{\r\n public class MyStack<T>:IStack<T>\r\n {\r\n private Stack<T> elements = new Stack<T>();\r\n\r\n public MyStack()\r\n {\r\n this.elements = new Stack<T>();\r\n }\r\n\r\n public void add(T e)\r\n {\r\n elements.Push(e);\r\n }\r\n public List<T> getElements()\r\n {\r\n return elements.ToList();\r\n }\r\n public bool isEmpty()\r\n {\r\n return elements.Any();\r\n }\r\n public T top()\r\n {\r\n return elements.First();\r\n }\r\n public T pop()\r\n {\r\n return elements.Pop();\r\n }\r\n\r\n public IEnumerator GetEnumerator()\r\n {\r\n return elements.GetEnumerator();\r\n }\r\n public override string ToString()\r\n {\r\n StringBuilder buff = new StringBuilder();\r\n\r\n foreach (T el in this.elements)\r\n {\r\n buff.Append(el + \"\\n\");\r\n\r\n }\r\n buff.Append(\"\\n\");\r\n return buff.ToString();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.641192615032196,
"alphanum_fraction": 0.6518163084983826,
"avg_line_length": 32.738094329833984,
"blob_id": "29a45947afc837bdca0a0b98a063e7044378f410",
"content_id": "16186d4943fba9d062fb64325b17f90f1168c247",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2918,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 84,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/GeneratedFiles/ui_password.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "/********************************************************************************\r\n** Form generated from reading UI file 'password.ui'\r\n**\r\n** Created by: Qt User Interface Compiler version 5.10.1\r\n**\r\n** WARNING! All changes made in this file will be lost when recompiling UI file!\r\n********************************************************************************/\r\n\r\n#ifndef UI_PASSWORD_H\r\n#define UI_PASSWORD_H\r\n\r\n#include <QtCore/QVariant>\r\n#include <QtWidgets/QAction>\r\n#include <QtWidgets/QApplication>\r\n#include <QtWidgets/QButtonGroup>\r\n#include <QtWidgets/QHeaderView>\r\n#include <QtWidgets/QLabel>\r\n#include <QtWidgets/QLineEdit>\r\n#include <QtWidgets/QMainWindow>\r\n#include <QtWidgets/QPushButton>\r\n#include <QtWidgets/QVBoxLayout>\r\n#include <QtWidgets/QWidget>\r\n\r\nQT_BEGIN_NAMESPACE\r\n\r\nclass Ui_PasswordWindow\r\n{\r\npublic:\r\n QWidget *centralwidget;\r\n QPushButton *pushButton;\r\n QWidget *layoutWidget;\r\n QVBoxLayout *verticalLayout;\r\n QLabel *label;\r\n QLineEdit *lineEdit;\r\n\r\n void setupUi(QMainWindow *PasswordWindow)\r\n {\r\n if (PasswordWindow->objectName().isEmpty())\r\n PasswordWindow->setObjectName(QStringLiteral(\"PasswordWindow\"));\r\n PasswordWindow->resize(334, 64);\r\n centralwidget = new QWidget(PasswordWindow);\r\n centralwidget->setObjectName(QStringLiteral(\"centralwidget\"));\r\n pushButton = new QPushButton(centralwidget);\r\n pushButton->setObjectName(QStringLiteral(\"pushButton\"));\r\n pushButton->setGeometry(QRect(250, 30, 75, 23));\r\n layoutWidget = new QWidget(centralwidget);\r\n layoutWidget->setObjectName(QStringLiteral(\"layoutWidget\"));\r\n layoutWidget->setGeometry(QRect(11, 11, 191, 41));\r\n verticalLayout = new QVBoxLayout(layoutWidget);\r\n verticalLayout->setObjectName(QStringLiteral(\"verticalLayout\"));\r\n verticalLayout->setContentsMargins(0, 0, 0, 0);\r\n label = new QLabel(layoutWidget);\r\n label->setObjectName(QStringLiteral(\"label\"));\r\n\r\n verticalLayout->addWidget(label);\r\n\r\n lineEdit = new QLineEdit(layoutWidget);\r\n lineEdit->setObjectName(QStringLiteral(\"lineEdit\"));\r\n\r\n verticalLayout->addWidget(lineEdit);\r\n\r\n PasswordWindow->setCentralWidget(centralwidget);\r\n\r\n retranslateUi(PasswordWindow);\r\n\r\n QMetaObject::connectSlotsByName(PasswordWindow);\r\n } // setupUi\r\n\r\n void retranslateUi(QMainWindow *PasswordWindow)\r\n {\r\n PasswordWindow->setWindowTitle(QApplication::translate(\"PasswordWindow\", \"Password\", nullptr));\r\n pushButton->setText(QApplication::translate(\"PasswordWindow\", \"Log in\", nullptr));\r\n label->setText(QApplication::translate(\"PasswordWindow\", \"Enter the password:\", nullptr));\r\n } // retranslateUi\r\n\r\n};\r\n\r\nnamespace Ui {\r\n class PasswordWindow: public Ui_PasswordWindow {};\r\n} // namespace Ui\r\n\r\nQT_END_NAMESPACE\r\n\r\n#endif // UI_PASSWORD_H\r\n"
},
{
"alpha_fraction": 0.4453999996185303,
"alphanum_fraction": 0.45239999890327454,
"avg_line_length": 20.421524047851562,
"blob_id": "53fd325ca99425b5a4eef5235528ab262746ac81",
"content_id": "4213b999b85f6bf6624df147fffac01686f0f880",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5000,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 223,
"path": "/MyProjects/OOP/OOP/Practice 3/New/UI.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"UI.h\"\r\n#include <iostream>\r\n#include \"repoException.h\"\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid UI::printMenuAdmin()\r\n{\r\n\tcout << \"1. Add a movie.\" << endl;\r\n\tcout << \"2. Delete a movie.\" << endl;\r\n\tcout << \"3. Update a movie.\" << endl;\r\n\tcout << \"4. Print the movies\" << endl;\r\n\tcout << \"0. Exit\" << endl;\r\n}\r\n\r\nvoid UI::printMenuUser()\r\n{\r\n\tcout << \"1. See the movies with a given genre.\" << endl;\r\n\tcout << \"2. Delete a movie.\" << endl;\r\n\tcout << \"3. Print the watch list.\" << endl;\r\n\tcout << \"4. Display in the selected way.\" << endl;\r\n\tcout << \"0. Exit\" << endl;\r\n}\r\n\r\nvoid UI::displayFile()\r\n{\r\n\tif (this->option == 1)\r\n\t\tthis->contro.displayCSV();\r\n\telse\r\n\t\tif (this->option == 2)\r\n\t\t\tthis->contro.displayHTML();\r\n}\r\n\r\nvoid UI::start()\r\n{\r\n\twhile (1)\r\n\t{\r\n\t\tint startup;\r\n\t\tcout << \"1. Admin menu.\" << endl;\r\n\t\tcout << \"2. User menu.\" << endl;\r\n\t\tcout << \"0. Exit\" << endl;\r\n\t\tcout << \"command: \";\r\n\t\tcin >> startup;\r\n\t\tif (startup == 0)\r\n\t\t\tbreak;\r\n\t\tif(startup==1)\r\n\t\t\twhile (1)\r\n\t\t\t{\r\n\t\t\t\tthis->printMenuAdmin();\r\n\t\t\t\tint command;\r\n\t\t\t\tcout << \"Enter the command: \";\r\n\t\t\t\tcin >> command;\r\n\t\t\t\tif (command == 0)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tif (command == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry{\r\n\t\t\t\t\tstring t, g, tr;\r\n\t\t\t\t\tint y, l;\r\n\t\t\t\t\tcout << \"Title: \";\r\n\t\t\t\t\tcin >> t;\r\n\t\t\t\t\tcout << \"Genre: \";\r\n\t\t\t\t\tcin >> g;\r\n\t\t\t\t\tcout << \"Year: \";\r\n\t\t\t\t\tcin >> y;\r\n\t\t\t\t\tcout << \"Likes: \";\r\n\t\t\t\t\tcin >> l;\r\n\t\t\t\t\tcout << \"Trailer: \";\r\n\t\t\t\t\tcin >> tr;\r\n\t\t\t\t\tMovie m{ t,g,y,l,tr };\r\n\t\t\t\t\tbool k = this->contro.add(m);\r\n\t\t\t\t\tif (k == true)\r\n\t\t\t\t\t\tcout << \"Movie successfully added!\" << endl;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcout << \"Movie could not be added!\" << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (FoundException e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << e.what();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tcout << \"Movie title: \";\r\n\t\t\t\t\t\tstring t,h;\r\n\t\t\t\t\t\tcin.clear();\r\n\t\t\t\t\t\tgetline(cin, h);\r\n\t\t\t\t\t\tgetline(cin, t);\r\n\t\t\t\t\t\tbool k = this->contro.del(t);\r\n\t\t\t\t\t\tif (k == true)\r\n\t\t\t\t\t\t\tcout << \"Movie was successfully deleted!\" << endl;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tcout << \"Movie could not be deleted!\" << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (NoMovieFoundException e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << e.what();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 3)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring ot, nt, g, tr;\r\n\t\t\t\t\tint y, l;\r\n\t\t\t\t\tcout << \"Old title: \";\r\n\t\t\t\t\tcin >> ot;\r\n\t\t\t\t\tcout << \"New title: \";\r\n\t\t\t\t\tcin >> nt;\r\n\t\t\t\t\tcout << \"Genre: \";\r\n\t\t\t\t\tcin >> g;\r\n\t\t\t\t\tcout << \"Year: \";\r\n\t\t\t\t\tcin >> y;\r\n\t\t\t\t\tcout << \"Lieks: \";\r\n\t\t\t\t\tcin >> l;\r\n\t\t\t\t\tcout << \"Trailer: \";\r\n\t\t\t\t\tcin >> tr;\r\n\t\t\t\t\tbool k = this->contro.update(ot, nt, g, y, l, tr);\r\n\t\t\t\t\tif (k == true)\r\n\t\t\t\t\t\tcout << \"Movie was successfully updated!\" << endl;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcout << \"Movie could not be updated!\" << endl;\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 4)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (this->contro.getAll().getLenght() == 0)\r\n\t\t\t\t\t\tcout << \"No movies in the list!\" << endl;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcout << this->contro.getAll().toString();\r\n\t\t\t\t}\r\n\t\t\t\tcout << endl;\r\n\t\t\t}\r\n\t\tif (startup == 2)\r\n\t\t\twhile (1)\r\n\t\t\t{\r\n\t\t\t\tthis->printMenuUser();\r\n\t\t\t\tint command;\r\n\t\t\t\tcout << \"Enter the command: \";\r\n\t\t\t\tcin >> command;\r\n\t\t\t\tif (command == 0)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tif (command == 1)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tstring genre;\r\n\t\t\t\t\t\tcout << \"Genre ('empty' to get all): \";\r\n\t\t\t\t\t\tcin >> genre;\r\n\t\t\t\t\t\tRepository r{};\r\n\t\t\t\t\t\tr.setElems(this->contro.filterByGenre(genre));\r\n\t\t\t\t\t\twhile (1)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tcout << r.next();\r\n\t\t\t\t\t\t\tcout << endl << \"Add the movie to the watch list? (yes or no): \";\r\n\t\t\t\t\t\t\tstring s;\r\n\t\t\t\t\t\t\tcin >> s;\r\n\t\t\t\t\t\t\tif (s == \"yes\")\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\tbool k = this->contro.addList(r[r.getCurrent() - 1]);\r\n\t\t\t\t\t\t\t\t\tif (k == true)\r\n\t\t\t\t\t\t\t\t\t\tcout << \"Movie added!\" << endl;\r\n\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\tcout << \"Movie could not be added!\" << endl;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tcatch (FoundException e)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tcout << e.what();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcout << \"next (yes or no): \";\r\n\t\t\t\t\t\t\tcin >> s;\r\n\t\t\t\t\t\t\tif (s == \"no\")\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (FileExceptionF e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << e.what();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry{\r\n\t\t\t\t\tstring t,h;\r\n\t\t\t\t\tcout << \"Title: \";\r\n\t\t\t\t\tcin.clear();\r\n\t\t\t\t\tgetline(cin, h);\r\n\t\t\t\t\tgetline(cin, t);\r\n\t\t\t\t\tbool k = this->contro.delList(t);\r\n\t\t\t\t\tif (k == true)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstring s;\r\n\t\t\t\t\t\tcout << \"Would you like to rate this movie? (yes or no): \";\r\n\t\t\t\t\t\tcin >> s;\r\n\t\t\t\t\t\tif (s == \"yes\")\r\n\t\t\t\t\t\t\tthis->contro.incLikes(this->contro.findByTitle(t));\r\n\t\t\t\t\t\tcout << \"Movie successfully deleted!\" << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcout << \"Movie could not be deleted!\" << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (NoMovieFoundException e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcout << e.what();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 3)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (this->contro.getList().getLenght() == 0)\r\n\t\t\t\t\t\tcout << \"No movies in the watch list!\" << endl;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcout << this->contro.getList().toString();\r\n\t\t\t\t}\r\n\t\t\t\tif (command == 4)\r\n\t\t\t\t{\r\n\t\t\t\t\tthis->contro.saveFile();\r\n\t\t\t\t\tthis->displayFile();\r\n\t\t\t\t}\r\n\t\t\t\tcout << endl;\r\n\t\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.6242235898971558,
"alphanum_fraction": 0.6242235898971558,
"avg_line_length": 14.149999618530273,
"blob_id": "29599189949a01c7132e5f5ad3671e7c5877181b",
"content_id": "81b663f365a24aa9e3dee6c91638769931d99fbe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 40,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/list.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"dynamic.h\"\r\n\r\nclass List\r\n{\r\nprivate:\r\n\tVector movie;\r\n\tint current;\r\npublic:\r\n\t/*\r\n\tConstructor for the watch list\r\n\t*/\r\n\tList();\r\n\t/*\r\n\tAdds a movie to the watch list\r\n\t*/\r\n\tvoid add(const Movie& m);\r\n\t/*\r\n\tReturns the current movie\r\n\tout: current\r\n\t*/\r\n\tMovie getCurrent();\r\n\t/*\r\n\tPlays the trailer for the current movie\r\n\t*/\r\n\tvoid watch();\r\n\t/*\r\n\tJumps to the next movie from the watch list\r\n\t*/\r\n\tvoid next();\r\n\t/*\r\n\tChecks if the watch list is empty\r\n\tout: return true if the watch list is empty, false otherwise\r\n\t*/\r\n\tbool empty();\r\n\r\n\tint del(const std::string& title);\r\n\r\n\tVector getM() { return movie; };\r\n};"
},
{
"alpha_fraction": 0.6432432532310486,
"alphanum_fraction": 0.6432432532310486,
"avg_line_length": 12.384614944458008,
"blob_id": "76e78729d4912ac8f1d995e690ad8ccb68cb1da4",
"content_id": "b923d970da44773292ca9053c00662ae62cdf40d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 13,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/tests.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <iostream>\r\n\r\n#include \"bst.h\"\r\n\r\nclass Tests {\r\npublic:\r\n\tvoid testSearch();\r\n\tvoid testRemove();\r\n\tvoid testSize();\r\n\tvoid testIterator();\r\n\tvoid testAll();\r\n};"
},
{
"alpha_fraction": 0.7894737124443054,
"alphanum_fraction": 0.7894737124443054,
"avg_line_length": 74.33333587646484,
"blob_id": "e2468218b8c9a5f0bcf047f99ca527ba9cd692e4",
"content_id": "c4852aaecc2eef3a146e9b0bc063ae974080179c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 228,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 3,
"path": "/MyProjects/OOP/README.txt",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "\tThis is a file with my object oriented projects (practice, testing, practical, written projects).\r\n\tNote! The projects might have different names that the ones on the folders, I renamed them for organisatory purpouses.\r\n\tEnjoy!"
},
{
"alpha_fraction": 0.6670061349868774,
"alphanum_fraction": 0.6670061349868774,
"avg_line_length": 24.594594955444336,
"blob_id": "63895ca28b4820fb8b2912c5280b6f83a372a262",
"content_id": "d00d1631541473e736e187901dd57e3a697e5ead",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 982,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 37,
"path": "/MyProjects/OOP/OOP/Practical 5/Retake/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"StarRepo.h\"\r\n#include \"AstroRepo.h\"\r\n#include <exception>\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tStarRepo& stars;\r\n\tAstroRepo& astros;\r\npublic:\r\n\tController(StarRepo& s, AstroRepo& a) :stars{ s }, astros{ a } {}\r\n\t~Controller() {}\r\n\r\n\t// Adds a new star to the stars repository\r\n\t// in: Star s, is the star that is added\r\n\t// out: 's' has been added to the stars repository\r\n\tvoid addStar(Star s);\r\n\t// Filters the star repository by a given word by returning the filtered vector\r\n\t// in: word, the sequence that needs to be found\r\n\t// out: returns the filtered vector\r\n\tstd::vector<Star> search(std::string word);\r\n\r\n\tstd::vector<Star> filter(std::string co) { return stars.filter(co); }\r\n\r\n\tvoid save() { stars.writeToFile(); }\r\n\tStarRepo getStars() { return stars; }\r\n};\r\n\r\nclass Exception :public std::exception\r\n{\r\nprivate:\r\n\tstd::string mess;\r\npublic:\r\n\tException(std::string m) :mess{ m }, exception(m.c_str()) {}\r\n\tstd::string what() { return mess; }\r\n};"
},
{
"alpha_fraction": 0.531889021396637,
"alphanum_fraction": 0.6063777804374695,
"avg_line_length": 25.7702693939209,
"blob_id": "a9dddabbae2f43420acccfa7c8756e96701bd959",
"content_id": "b62855dd755c054df838b6d52d9c67f1b3efdd4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4108,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 148,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/tests.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"tests.h\"\r\n#include <assert.h>\r\n\r\nvoid TestAddDyn()\r\n{\r\n\tVector<Movie> v;\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tv.add(m);\r\n\tassert(v[0].getTitle()== \"Film\");\r\n\tassert(v[0].getGenre() == \"awesome\");\r\n\tassert(v[0].getYear() == 2018);\r\n\tassert(v[0].getLikes() == 20000);\r\n}\r\n\r\nvoid TestAddRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m);\r\n\tassert(r.getMovies()[0].getYear()== 2018);\r\n\tassert(r.getMovies()[0].getLikes() == 20000);\r\n}\r\n\r\nvoid TestDelRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m);\r\n\tassert(r.getMovies()[0].getYear() == 2018);\r\n\tassert(r.getMovies()[0].getLikes() == 20000);\r\n\tr.addMovie(m);\r\n\tr.getMovies().del(0);\r\n\tassert(r.getMovies().getLenght() == 1);\r\n}\r\n\r\nvoid TestUpdateRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m1);\r\n\tassert(r.getMovies()[0].getYear() == 2018);\r\n\tassert(r.getMovies()[0].getLikes() == 20000);\r\n\tr.updateMovie(\"Film\", \"Film\", \"awesome\", 2018, 20000, \"more\");\r\n}\r\n\r\nvoid TestFindByTitleRepo()\r\n{\r\n\tRepository r{};\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m1);\r\n\tassert(r.getMovies()[0].getYear() == 2018);\r\n\tassert(r.getMovies()[0].getLikes() == 20000);\r\n\tassert(r.findByTitle(\"Film\").getTitle() == \"Film\");\r\n\tassert(r.findByTitle(\"Film\").getYear() == 2018);\r\n\tassert(r.findByTitle(\"Film\").getLikes() == 20000);\r\n}\r\n\r\nvoid TestFindByGenreRepo()\r\n{\r\n\tRepository r{};\r\n\tr.nextM();\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tr.addMovie(m1);\r\n\tassert(r.getMovies()[0].getYear() == 2018);\r\n\tassert(r.getMovies()[0].getLikes() == 20000);\r\n\tassert(r.findByGenre(\"awesome\").getTitle() == \"Film\");\r\n\tassert(r.findByGenre(\"awesome\").getYear() == 2018);\r\n\tassert(r.findByGenre(\"awesome\").getLikes() == 20000);\r\n\tMovie ji = Movie{};\r\n\tr.incLikesMovie(0);\r\n\tint fd = r.findP(\"kdaem\");\r\n\tr.setCurrentM();\r\n}\r\n\r\nvoid TestAddController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies()[0].getYear() == 2018);\r\n\tassert(c.getRepo().getMovies()[0].getLikes() == 20000);\r\n}\r\n\r\nvoid TestDelController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies()[0].getYear() == 2018);\r\n\tassert(c.getRepo().getMovies()[0].getLikes() == 20000);\r\n\tc.delMovieFromRepo(\"Film\");\r\n\tVector<Movie> ve{};\r\n\tve.resize();\r\n\tm=r.getMovies()[0];\r\n}\r\n\r\nvoid TestUpdateController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tMovie m2{ \"Film\",\"awesome\",2018,20000,\"more\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tassert(c.getRepo().getMovies()[0].getYear() == 2018);\r\n\tassert(c.getRepo().getMovies()[0].getLikes() == 20000);\r\n\tc.updateMovieToRepo(\"Film\", \"Film\", \"awesome\", 2018, 20000, \"more\");\r\n}\r\n\r\nvoid TestListController()\r\n{\r\n\tRepository r{};\r\n\tController c{ r };\r\n\tMovie m1{ \"Film\",\"awesome\",2018,20000,\"t.h.i.s.i.s.a.w.e.s.o.m.e.\" };\r\n\tMovie m2{ \"Film\",\"awesome\",2018,20000,\"more\" };\r\n\tc.addMovieToRepo(\"Film\", \"awesome\", 2018, 20000, \"t.h.i.s.i.s.a.w.e.s.o.m.e.\");\r\n\tc.getList();\r\n\tc.getRepo();\r\n\tc.nextMovieList();\r\n\tc.startList();\r\n\tassert(c.getRepo().getMovies()[0].getYear() == 2018);\r\n\tassert(c.getRepo().getMovies()[0].getLikes() == 20000);\r\n}\r\n\r\nvoid Test::Tests()\r\n{\r\n\tTest::TestController();\r\n\tTest::TestRepo();\r\n}\r\n\r\nvoid Test::TestRepo()\r\n{\r\n\tTestAddDyn();\r\n\tTestAddRepo();\r\n\tTestDelRepo();\r\n\tTestUpdateRepo();\r\n\tTestFindByGenreRepo();\r\n\tTestFindByTitleRepo();\r\n}\r\n\r\nvoid Test::TestController()\r\n{\r\n\tTestAddController();\r\n\tTestDelController();\r\n\tTestUpdateController();\r\n\tTestListController();\r\n}"
},
{
"alpha_fraction": 0.49841269850730896,
"alphanum_fraction": 0.49841269850730896,
"avg_line_length": 19.724138259887695,
"blob_id": "6d284d7af3a78c29bc5b9fecc519b0f4b0fa6e9c",
"content_id": "bee244786c458e1c9492754c88f7fc5d438ea087",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 632,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 29,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/View/RunExample.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.View\r\n{\r\n public class RunExample : Command\r\n {\r\n private Controller.MyController ctrl;\r\n public RunExample(string key, string desc, Controller.MyController ctr) : base(key, desc)\r\n {\r\n this.ctrl = ctr;\r\n }\r\n\r\n public override void execute()\r\n {\r\n\r\n try\r\n {\r\n ctrl.executeAllSteps();\r\n }\r\n catch (SystemException e)\r\n {\r\n Console.WriteLine(e.Message);\r\n }\r\n }\r\n\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5655375719070435,
"alphanum_fraction": 0.5940108299255371,
"avg_line_length": 20.88763999938965,
"blob_id": "6ab73130a1bab1b21bc2675b1c67ce6b26ed8474",
"content_id": "165bace60e1f30d91210d71b43d614be7030aace",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4074,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 178,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/main.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPotherpractical1.h\"\r\n#include <QtWidgets/QApplication>\r\n#include \"programmer.h\"\r\n#include \"task.h\"\r\n#include \"ProgrammerRepo.h\"\r\n#include \"TaskRepo.h\"\r\n#include \"controller.h\"\r\n#include \"ProgrammerWindow.h\"\r\n#include <vector>\r\n#include <assert.h>\r\n\r\nusing namespace std;\r\n\r\nvoid testDelRepo()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tt.del(2);\r\n\tassert(t.getLenght() == 2);\r\n\tassert(t[t.getLenght() - 1].getDescr() == \"Merge bine\");\r\n}\r\n\r\nvoid testDelContro()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tController co{ p,t };\r\n\tco.delTask(2);\r\n\tassert(t.getLenght() == 2);\r\n\tassert(t[t.getLenght() - 1].getDescr() == \"Merge bine\");\r\n}\r\n\r\nvoid testUpdateStatusInProgressRepo()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tt.updateStatusProgress(1, p1.getID());\r\n\tassert(t[1].getID() == p1.getID());\r\n\tassert(t[1].getStat() == \"in progress\");\r\n}\r\n\r\nvoid testUpdateStatusInProgressContro()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tController co{ p,t };\r\n\tco.startTask(1, p1.getID(),p1.getName());\r\n\tassert(t[1].getID() == p1.getID());\r\n\tassert(t[1].getStat() == \"in progress\");\r\n}\r\n\r\nvoid testUpdateStatusClosedRepo()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tt.updateStatusProgress(1, p1.getID());\r\n\tt.setThisClosed(1);\r\n\tassert(t[1].getID() == p1.getID());\r\n\tassert(t[1].getStat() == \"closed\");\r\n}\r\n\r\nvoid testUpdateStatusClosedContro()\r\n{\r\n\tProgrammer p1{ 1,\"Eu\" }, p2{ 2,\"Celalalt\" };\r\n\tProgrammerRepo<Programmer> p{};\r\n\tp.add(p1);\r\n\tp.add(p2);\r\n\tassert(p.getLenght() == 2);\r\n\tTask t1{ \"Facem asa\" }, t2{ \"Merge bine\" }, t3{ \"Uite ca face\" };\r\n\tTaskRepo<Task> t{};\r\n\tt.add(t1);\r\n\tt.add(t2);\r\n\tt.add(t3);\r\n\tassert(t.getLenght() == 3);\r\n\tController co{ p,t };\r\n\tco.startTask(1, p1.getID(),p1.getName());\r\n\tco.finishTask(1);\r\n\tassert(t[1].getID() == p1.getID());\r\n\tassert(t[1].getStat() == \"closed\");\r\n}\r\n\r\nvoid testAll()\r\n{\r\n\ttestDelRepo();\r\n\ttestDelContro();\r\n\ttestUpdateStatusInProgressRepo();\r\n\ttestUpdateStatusInProgressContro();\r\n\ttestUpdateStatusClosedRepo();\r\n\ttestUpdateStatusClosedContro();\r\n}\r\n\r\nclass Here\r\n{\r\nprivate:\r\n\tvector<ProgrammerWindow*> hm;\r\npublic:\r\n\tHere(vector<ProgrammerWindow*> h) :hm{ h } {}\r\n\t~Here() {\r\n\t\tfor (auto i : hm)\r\n\t\t\tdelete i;\r\n\t}\r\n\tvoid show() {\r\n\t\tfor (auto i : hm)\r\n\t\t\ti->show();\r\n\t}\r\n};\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tQApplication a(argc, argv);\r\n\ttestAll();\r\n\tProgrammerRepo<Programmer> p{ \"Programmers.txt\" };\r\n\tTaskRepo<Task> t{ \"Tasks.txt\" };\r\n\tController c{ p,t };\r\n\tstd::vector<ProgrammerWindow*> v;\r\n\tvector<Programmer> names;\r\n\tfor (auto i : p.getAll())\r\n\t{\r\n\t\tnames.push_back(i);\r\n\t\tProgrammerWindow* pr = new ProgrammerWindow(c,i);\r\n\t\tv.push_back(pr);\r\n\t}\r\n\tfor (auto j : names)\r\n\t{\r\n\t\tfor (int i = 0;i < names.size();i++)\r\n\t\t{\r\n\t\t\tv[i]->setAll(v);\r\n\t\t}\r\n\t}\r\n\tHere h{ v };\r\n\th.show();\r\n\treturn a.exec();\r\n}\r\n"
},
{
"alpha_fraction": 0.4823996126651764,
"alphanum_fraction": 0.4833911657333374,
"avg_line_length": 28.590909957885742,
"blob_id": "16aa725e2bb3896bf90af5612474b0b6fed41033",
"content_id": "eb7056fe0d7dc05f9195c52b2a6d74ed13456589",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2017,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 66,
"path": "/MyProjects/FP/FP/Practice Test 1/controller.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nclass Controller:\r\n def __init__(self,repo=Repository()):\r\n self.__repo=repo\r\n def __str__(self):\r\n '''\r\n Overwrites the str for this class\r\n :return:\r\n '''\r\n s = ''\r\n for i in range(len(self.__repo.getAll())):\r\n s = s + str(self.__repo.get(i)) + '\\n'\r\n return s\r\n def add(self,element):\r\n '''\r\n Adds an element to the controller\r\n in:param element:\r\n :return:\r\n '''\r\n found=False\r\n for i in range(len(self.__repo.getAll())):\r\n if len(self.__repo.getAll())!=0 and self.__repo.get(i)==element:\r\n print(\"Element already added!\")\r\n found=True\r\n if found==False:\r\n self.__repo.add(element)\r\n def getAll(self):\r\n '''\r\n Returns the repository\r\n :return:\r\n '''\r\n return self.__repo.getAll()\r\n def get(self,index):\r\n '''\r\n Returns the element from that position\r\n in:param index:\r\n :return:\r\n '''\r\n return self.__repo.get(index)\r\n def idIncome(self,id):\r\n '''\r\n Returns the income of a given id\r\n in:param id:\r\n :return:\r\n '''\r\n for i in range(len(self.__repo.getAll())):\r\n if len(self.__repo.getAll())!=0 and self.__repo.get(i).getID()==id:\r\n return self.__repo.get(i).income()\r\n def idOderValue(self,id,orderDistance):\r\n '''\r\n Returns the order price of a given distance from an id\r\n in:param id:\r\n in:param orderDistance:\r\n :return:\r\n '''\r\n x=self.__repo.findByID(id)\r\n return self.__repo.get(x).orderValue(orderDistance)\r\n def addOrder(self,id,distance):\r\n '''\r\n Adds an order distance to the class\r\n in:param id:\r\n in:param distance:\r\n :return:\r\n '''\r\n x=self.__repo.findByID(id)\r\n self.__repo.get(x).add(distance)"
},
{
"alpha_fraction": 0.6094734072685242,
"alphanum_fraction": 0.619299590587616,
"avg_line_length": 20.68000030517578,
"blob_id": "7270a694d270da8d830f2c3735e4ee8938c983a3",
"content_id": "e2759c3a5187042f96944c8c8e56f1c01856aaa0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3969,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 175,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/table.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"table.h\"\r\n#include <vector>\r\n#include <string>\r\n#include <QFont>\r\n#include <QBrush>\r\n\r\nMovieTable::MovieTable(Repository & r, QObject * parent) :QAbstractTableModel{ parent },repo{ r }\r\n{\r\n}\r\n\r\nMovieTable::~MovieTable()\r\n{\r\n}\r\n\r\nint MovieTable::rowCount(const QModelIndex & parent) const\r\n{\r\n\tint nr = this->repo.getLenght();\r\n\treturn nr + 1;\r\n}\r\n\r\nint MovieTable::columnCount(const QModelIndex & parent) const\r\n{\r\n\treturn 5;\r\n}\r\n\r\nQVariant MovieTable::data(const QModelIndex & index, int role) const\r\n{\r\n\tint row = index.row();\r\n\tint column = index.column();\r\n\r\n\tstd::vector<Movie> mov = this->repo.getAll();\r\n\r\n\tif (row == mov.size())\r\n\t{\r\n\t\treturn QVariant();\r\n\t}\r\n\tMovie m = mov[row];\r\n\tif (role == Qt::DisplayRole || role == Qt::EditRole)\r\n\t{\r\n\t\tswitch (column)\r\n\t\t{\r\n\t\tcase 0:\r\n\t\t\treturn QString::fromStdString(m.getTitle());\r\n\t\tcase 1:\r\n\t\t\treturn QString::fromStdString(m.getGenre());\r\n\t\tcase 2:\r\n\t\t\treturn QString::fromStdString(std::to_string(m.getYear()));\r\n\t\tcase 3:\r\n\t\t\treturn QString::fromStdString(std::to_string(m.getLikes()));\r\n\t\tcase 4:\r\n\t\t\treturn QString::fromStdString(m.getTrailer());\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (role = Qt::FontRole)\r\n\t{\r\n\t\tQFont font(\"Times\", 10, 10, true);\r\n\t\tfont.setItalic(false);\r\n\t\treturn font;\r\n\t}\r\n\tif (role == Qt::BackgroundRole)\r\n\t{\r\n\t\tif (row % 2 == 1)\r\n\t\t{\r\n\t\t\treturn QBrush{ QColor{ 0, 250, 154 } };\r\n\t\t}\r\n\t}\r\n\treturn QVariant{};\r\n}\r\n\r\nQVariant MovieTable::headerData(int section, Qt::Orientation orientation, int role) const\r\n{\r\n\tif (role == Qt::DisplayRole)\r\n\t{\r\n\t\tif (orientation == Qt::Horizontal)\r\n\t\t{\r\n\t\t\tswitch (section)\r\n\t\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\treturn QString{ \"Title\" };\r\n\t\t\tcase 1:\r\n\t\t\t\treturn QString{ \"Genre\" };\r\n\t\t\tcase 2:\r\n\t\t\t\treturn QString{ \"Year\" };\r\n\t\t\tcase 3:\r\n\t\t\t\treturn QString{ \"Likes\" };\r\n\t\t\tcase 4:\r\n\t\t\t\treturn QString{ \"Trailer\" };\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (role == Qt::FontRole)\r\n\t{\r\n\t\tQFont font(\"Times\", 10, 10, true);\r\n\t\tfont.setBold(true);\r\n\t\tfont.setItalic(false);\r\n\t\treturn font;\r\n\t}\r\n\r\n\treturn QVariant{};\r\n}\r\n\r\nbool MovieTable::setData(const QModelIndex & index, const QVariant & value, int role)\r\n{\r\n\tif (!index.isValid() || role != Qt::EditRole)\r\n\t\treturn false;\r\n\r\n\t// set the new data to the gene\r\n\tint geneIndex = index.row();\r\n\r\n\t// get the genes\r\n\tstd::vector<Movie> genes = this->repo.getAll();\r\n\r\n\t// Allow adding in the table\r\n\t//if the index is >= number of genes => a new gene is added\r\n\tif (geneIndex == genes.size())\r\n\t{\r\n\t\tthis->beginInsertRows(QModelIndex{}, geneIndex, geneIndex);\r\n\r\n\t\tswitch (index.column())\r\n\t\t{\r\n\t\tcase 0:\r\n\t\t\tthis->repo.add(Movie{ value.toString().toStdString(), \"\",{} ,{} ,\"\" });\r\n\t\t\tbreak;\r\n\t\tcase 1:\r\n\t\t\tthis->repo.add(Movie{\"\", value.toString().toStdString(),{} ,{} ,\"\"});\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\tthis->repo.add(Movie{\"\",\"\", stoi(value.toString().toStdString()),{} ,\"\" });\r\n\t\t\tbreak;\r\n\t\tcase 3:\r\n\t\t\tthis->repo.add(Movie{ \"\",\"\",{}, stoi(value.toString().toStdString()) ,\"\" });\r\n\t\t\tbreak;\r\n\t\tcase 4:\r\n\t\t\tthis->repo.add(Movie{ \"\",\"\",{},{}, value.toString().toStdString() });\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\tthis->endInsertRows();\r\n\t\treturn true;\r\n\t}\r\n\r\n\tMovie currentGene = genes[geneIndex];\r\n\tswitch (index.column())\r\n\t{\r\n\tcase 0:\r\n\t\tcurrentGene.setTitle(value.toString().toStdString());\r\n\t\tbreak;\r\n\tcase 1:\r\n\t\tcurrentGene.setGenre(value.toString().toStdString());\r\n\t\tbreak;\r\n\tcase 2:\r\n\t\tcurrentGene.setYear(stoi(value.toString().toStdString()));\r\n\t\tbreak;\r\n\tcase 3:\r\n\t\tcurrentGene.setLikes(stoi(value.toString().toStdString()));\r\n\t\tbreak;\r\n\tcase 4:\r\n\t\tcurrentGene.setTrailer(value.toString().toStdString());\r\n\t}\r\n\tthis->repo.update(genes[geneIndex].getTitle(), currentGene.getTitle(),currentGene.getGenre(),currentGene.getYear(),currentGene.getLikes(),currentGene.getTrailer());\r\n\r\n\t// emit the dataChanged signal\r\n\temit dataChanged(index, index);\r\n\r\n\treturn true;\r\n}\r\n\r\nQt::ItemFlags MovieTable::flags(const QModelIndex & index) const\r\n{\r\n\treturn Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;\r\n}\r\n"
},
{
"alpha_fraction": 0.6655290126800537,
"alphanum_fraction": 0.6655290126800537,
"avg_line_length": 23.91176414489746,
"blob_id": "b44583508267dc86b5842072404c5204d613d842",
"content_id": "dbf53a60a50e87d2e38a1add3542cc68c22287d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 879,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 34,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/repository.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"vegetable.h\"\r\n#include <string>\r\n\r\nclass Repository {\r\nprivate:\r\n\tstd::vector<Vegetable> elems{};\r\n\tstd::string filename;\r\npublic:\r\n\tRepository() :filename{ \"\" } {}\r\n\tRepository(std::string file) :filename{ file } { this->readFromFile(); }\r\n\t~Repository() {}\r\n\tint getLenght() { return elems.size(); }\r\n\tstd::vector<Vegetable> getAll() { return elems; }\r\n\r\n\tvoid add(Vegetable v);\r\n\tvoid Add(Vegetable v);\r\n\tvoid del(int pos);\r\n\r\n\t/*\r\n\tSorts the elements from the repository in alphabetical order, by the family of the elements.\r\n\t*/\r\n\tvoid sort();\r\n\t/*\r\n\tReturns a vector only with elements that contain a given family.\r\n\t*/\r\n\tstd::vector<Vegetable> filter(std::string family);\r\n\r\n\tVegetable operator[](int pos) { return this->elems[pos]; }\r\n\tvoid setElems(std::vector<Vegetable> r) { this->elems = r; }\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n};"
},
{
"alpha_fraction": 0.6588628888130188,
"alphanum_fraction": 0.6602006554603577,
"avg_line_length": 20.313432693481445,
"blob_id": "f53d837e3244fc72bcf34777e0126a36ada23547",
"content_id": "563087f1b515e3df23f8a2c54b0ade2b60ab210d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1495,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 67,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Dynamic/Lab 5-6 Dyn/controller.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"controller.h\"\r\n\r\nusing namespace std;\r\n\r\nbool Controller::addMovieToRepo(const string & title, const string & genre, const int year, const int likes, const string & trailer)\r\n{\r\n\tMovie m{ title,genre,year,likes,trailer };\r\n\treturn this->repo.addMovie(m);\r\n}\r\n\r\nbool Controller::delMovieFromRepo(const string & title)\r\n{\r\n\treturn this->repo.delMovie(title);\r\n}\r\n\r\nbool Controller::updateMovieToRepo(string oldTitle, string title, string genre, int year, int likes, string trailer)\r\n{\r\n\treturn this->repo.updateMovie(oldTitle, title, genre, year, likes, trailer);\r\n}\r\n\r\nvoid Controller::addMovieToList(const Movie & m)\r\n{\r\n\tthis->list.add(m);\r\n}\r\n\r\nvoid Controller::addMovieByGenre(const string & genre)\r\n{\r\n\tVector v = this->repo.getMovies();\r\n\tMovie* mo = v.getAll();\r\n\tfor (int i = 0;i < v.getLenght();i++)\r\n\t{\r\n\t\tMovie m = mo[i];\r\n\t\tif (m.getGenre() == genre)\r\n\t\t\tthis->list.add(m);\r\n\t}\r\n}\r\n\r\nRepository Controller::getGenreRepo(const std::string genre)\r\n{\r\n\tRepository r{};\r\n\tif (genre == \"empty\")\r\n\t\treturn this->repo;\r\n\tfor (int i = 0;i < this->repo.getMovies().getLenght();i++)\r\n\t\tif (this->repo.getMovies().get(i).getGenre()==genre)\r\n\t\t\tr.addMovie(this->repo.getMovies().get(i));\r\n\treturn r;\r\n}\r\n\r\nvoid Controller::startList()\r\n{\r\n\tthis->list.watch();\r\n}\r\n\r\nvoid Controller::nextMovieList()\r\n{\r\n\tthis->list.next();\r\n}\r\n\r\nvoid Controller::delL(const std::string & title)\r\n{\r\n\tthis->list.del(title);\r\n}\r\n\r\nvoid Controller::incLike(int pos)\r\n{\r\n\tthis->repo.incLikesMovie(pos);\r\n}\r\n"
},
{
"alpha_fraction": 0.7153846025466919,
"alphanum_fraction": 0.7153846025466919,
"avg_line_length": 16.571428298950195,
"blob_id": "7e055cb7a6026ebd2c8ed99d3693d1486ef5aca0",
"content_id": "e59284e76b02515746f299d2c87e2141441e2c46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 130,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 7,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/OOPPracticalex.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"OOPPracticalex.h\"\r\n\r\nOOPPracticalex::OOPPracticalex(QWidget *parent)\r\n\t: QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n}\r\n"
},
{
"alpha_fraction": 0.6203866600990295,
"alphanum_fraction": 0.6221441030502319,
"avg_line_length": 22.826086044311523,
"blob_id": "19c6c5b1b6166772166bc82e13288ebb3584258e",
"content_id": "c780072da3219b779885892edb3bf0fa5ad39609",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 569,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 23,
"path": "/MyProjects/OOP/OOP/Practice 3/New/csv.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"watchFile.h\"\r\n\r\nclass CSV :public MovieFile {\r\npublic:\r\n\tCSV() :MovieFile{} { this->filename = this->getFile(); }\r\n\tvoid writeToFile() override;\r\n\tvoid display() override;\r\n};\r\n\r\n//class CSV1 {\r\n//private:\r\n//\tRepository repo;\r\n//\tstd::string filename;\r\n//public:\r\n//\tCSV() :repo{}, filename{ \"\" } {}\r\n//\tCSV(Repository repo, std::string filename) :repo{ repo }, filename{ filename } { this->readFromFile(); }\r\n//\t~CSV() {}\r\n//\tvoid writeToFile();\r\n//\tvoid readFromFile();\r\n//\tRepository getRepo() { return repo; }\r\n//};"
},
{
"alpha_fraction": 0.5723270177841187,
"alphanum_fraction": 0.5763293504714966,
"avg_line_length": 20.139240264892578,
"blob_id": "33ef69c9f16d682475e3449ae40a50c629ae4f39",
"content_id": "c24b2f8fd5824e7ace916d3a85cee150c4467739",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1749,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 79,
"path": "/MyProjects/OOP/OOP/Written 2/OOP written ex1/ToDo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <iterator>\r\n#include <sstream>\r\n\r\nclass Activity\r\n{\r\nprivate:\r\n\tstd::string what;\r\n\tstd::string time;\r\npublic:\r\n\tActivity() :what{ \"\" }, time{ \"\" } {}\r\n\tActivity(std::string w, std::string t) :what{ w }, time{ t } {}\r\n\t~Activity() {}\r\n\r\n\tstd::string getWhat() { return what; }\r\n\tstd::string getTime() { return time; }\r\n\r\n\tfriend std::ostream& operator<<(std::ostream& o, Activity& a);\r\n};\r\n\r\nstd::ostream& operator<<(std::ostream& o, Activity& a);\r\n\r\ntemplate <typename T>\r\nclass ToDo\r\n{\r\nprivate:\r\n\tT * elems;\r\n\tint cap;\r\n\tint len;\r\npublic:\r\n\tToDo(int c, int l) :len{ l }, cap{ c } { elems = new T[c]; }\r\n\tToDo() :len{ 0 }, cap{ 10 } { elems = new T[10]; }\r\n\t~ToDo() { delete[] elems; }\r\n\r\n\tToDo& operator+=(T e);\r\n\r\n\tvoid reversePrint(std::ostream& s);\r\n\r\n\tclass iterator :public std::iterator<std::forward_iterator_tag, T>\r\n\t{\r\n\tprivate:\r\n\t\tT * ptr;\r\n\tpublic:\r\n\t\titerator(T* p) :ptr{ p } {}\r\n\t\titerator operator++() { this->ptr++; return this->ptr; }\r\n\t\titerator operator++(int) { iterator i{ this->ptr }; this->ptr++; return i; }\r\n\t\tbool operator!=(const iterator& it) { return this->ptr != it.ptr; }\r\n\t\tbool operator==(const iterator& it) { return this->ptr == it.ptr; }\r\n\t\tT& operator*() { return *this->ptr; }\r\n\t\tT& operator->() { return this->ptr; }\r\n\t};\r\n\titerator begin()\r\n\t{\r\n\t\treturn iterator{ this->elems };\r\n\t}\r\n\titerator end()\r\n\t{\r\n\t\treturn iterator(this->elems + this->len);\r\n\t}\r\n};\r\n\r\ntemplate<typename T>\r\ninline ToDo<T> & ToDo<T>::operator+=(T e)\r\n{\r\n\tif (len == cap)\r\n\t\treturn *this;\r\n\telems[len] = e;\r\n\tlen++;\r\n\treturn *this;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void ToDo<T>::reversePrint(std::ostream& s)\r\n{\r\n\tfor (int i = len - 1;i >= 0l;i--)\r\n\t\ts << elems[i] << \" \";\r\n\ts << \"\\n\";\r\n}\r\n"
},
{
"alpha_fraction": 0.6321004033088684,
"alphanum_fraction": 0.6367239356040955,
"avg_line_length": 21.323076248168945,
"blob_id": "dad4f0205b1fb2e132fe9b2bb33e7bd7a94d0020",
"content_id": "1aac4080b60df4f082783b5391c84904a967cdc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1514,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 65,
"path": "/MyProjects/OOP/OOP/Practice 5/Time/Time.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"Time.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nTime::Time(Repository<Task> &r,QWidget *parent)\r\n\t:repo{ r }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->sort();\r\n\tthis->populate();\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->blodIt();\r\n}\r\n\r\nvoid Time::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(showDuration()));\r\n}\r\n\r\nvoid Time::populate()\r\n{\r\n\tthis->sort();\r\n\tif (ui.listWidget->count() != 0)\r\n\t\tui.listWidget->clear();\r\n\tfor (auto m : this->repo.getAll())\r\n\t{\r\n\t\tstringstream buffer;\r\n\t\tbuffer << \"Description: \" << m.getDescription() << \", Priority: \" << m.getPriority();\r\n\t\tQString listItem = QString::fromStdString(buffer.str());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.listWidget->addItem(listItemWidget);\r\n\t}\r\n\tif (this->repo.getLenght() > 0)\r\n\t\tui.listWidget->setCurrentRow(-1);\r\n}\r\n\r\nvoid Time::sort()\r\n{\r\n\tthis->repo.sort();\r\n}\r\n\r\nvoid Time::blodIt()\r\n{\r\n\tfor (int k = 0;k < repo.getLenght();k++)\r\n\t{\r\n\t\tthis->ui.listWidget->setCurrentRow(k);\r\n\t\tif (repo[k].getPriority() == 1)\r\n\t\t{\r\n\t\t\tQListWidgetItem *it = this->ui.listWidget->currentItem();\r\n\t\t\tQFont f = it->font();\r\n\t\t\tf.setBold(1);\r\n\t\t\tit->setFont(f);\r\n\t\t}\r\n\t}\r\n\tthis->ui.listWidget->setCurrentRow(0);\r\n}\r\n\r\nvoid Time::showDuration()\r\n{\r\n\tint s = this->ui.lineEdit->text().toInt();\r\n\tthis->ui.lineEdit->clear();\r\n\tthis->ui.ShowLabel->setText(QString::fromStdString(to_string(this->repo.calculateDuration(s))));\r\n}"
},
{
"alpha_fraction": 0.6509207487106323,
"alphanum_fraction": 0.6525220274925232,
"avg_line_length": 29.225000381469727,
"blob_id": "76a1d823119a6ddfbee667a500391ea9eeb59261",
"content_id": "9f80449346c5886f3c3145186df7626e91d7194d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1249,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 40,
"path": "/MyProjects/MAP/Practical Exam/Countdown Latch/src/Model/Statements/CountdownStmt.java",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "package Model.Statements;\r\n\r\nimport Model.Expressions.IExpr;\r\nimport Model.Expressions.VarExpr;\r\nimport Model.ProgramState;\r\nimport Model.Utilities.IDictionary;\r\nimport Model.Utilities.IList;\r\nimport Model.Utilities.IStack;\r\nimport Exception.VariableNotDefined;\r\n\r\nimport java.util.List;\r\n\r\npublic class CountdownStmt implements IStmt {\r\n private String var;\r\n\r\n public CountdownStmt(String s){var=s;}\r\n\r\n @Override\r\n public ProgramState execute(ProgramState state){\r\n IDictionary<String,Integer> dic=state.getSymTable();\r\n IDictionary<Integer,Integer> heap=state.getHeap();\r\n IDictionary<Integer, Integer> latch=state.getLatch();\r\n IList<Integer> list=state.getList();\r\n IStack<IStmt> stack=state.getStack();\r\n if(!dic.exists(var)) throw new VariableNotDefined(\"Variable '\"+var+\"' does not exist in the Symbol Table!\");\r\n IExpr e=new VarExpr(var);\r\n Integer ev=e.evaluate(dic,heap);\r\n\r\n if(!latch.exists(ev)) {return null;}\r\n if(latch.getValue(ev)>0){\r\n latch.setValue(ev,latch.getValue(ev)-1);\r\n list.add(state.getID());\r\n }\r\n return null;\r\n }\r\n\r\n public String toString(){\r\n return \"countdwon(\"+var+\")\";\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5487288236618042,
"alphanum_fraction": 0.5826271176338196,
"avg_line_length": 21.700000762939453,
"blob_id": "232d8dfd39820a0024ca9c0f62bb68198fb08a4a",
"content_id": "afa013f6331877fcc6108cb6eef228e516be30a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 472,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 20,
"path": "/MyProjects/FP/FP/FP Test 2/tests.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import unittest\r\nfrom controller import *\r\nfrom domain import *\r\nfrom domain import *\r\n\r\nclass Test(unittest.TestCase):\r\n\r\n def testControllerFindByAssiID(self):\r\n r = Repository()\r\n a1 = Person(1, 'Do this', '7.7.7')\r\n a2 = Person(2, 'Do this', '7.7.1')\r\n r.add(a1)\r\n r.add(a2)\r\n c = Controller(r)\r\n self.assertEqual(c.(1),0)\r\n self.assertEqual(c.findByAssiID(2), 1)\r\n\r\n\r\na=Test()\r\na.testControllerFindByAssiID()"
},
{
"alpha_fraction": 0.624365508556366,
"alphanum_fraction": 0.6335025429725647,
"avg_line_length": 19.45652198791504,
"blob_id": "c1dab2dcb038cb14633ae808d2c4236750aed5b3",
"content_id": "31f951a4665646b55599b7d77a0903a6f188c78d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 985,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 46,
"path": "/MyProjects/OOP/OOP/Practice 4/Me/repository.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"repository.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint Repository::addConcert(const Concert& c)\r\n{\r\n\tif (this->find(c) != -1)\r\n\t\treturn 0;\r\n\tthis->concerts.add(c);\r\n\treturn 1;\r\n}\r\n\r\nint Repository::delConcert(const string& band)\r\n{\r\n\tConcert* co = this->concerts.getAll();\r\n\tfor(int i=0;i<this->concerts.getLenght();i++)\r\n\t\tif (co[i].getBand() == band)\r\n\t\t{\r\n\t\t\tthis->concerts.del(i);\r\n\t\t\treturn 1;\r\n\t\t}\r\n\treturn 0;\r\n}\r\n\r\nint Repository::updateConcert(const string& oldBand, const string& newBand, const int likes)\r\n{\r\n\tConcert c = findByBand(oldBand);\r\n\tif (c.getBand() == \"\")\r\n\t\treturn 0;\r\n\tdelConcert(oldBand);\r\n\tConcert co{ newBand,likes };\r\n\taddConcert(co);\r\n\treturn 1;\r\n}\r\n\r\nConcert Repository::findByBand(const string& band)\r\n{\r\n\tif (this->concerts.getAll() == NULL)\r\n\t\treturn Concert{};\r\n\r\n\tfor (int i = 0;i < this->concerts.getLenght();i++)\r\n\t\tif (this->concerts.getAll()[i].getBand() == band)\r\n\t\t\treturn this->concerts.getAll()[i];\r\n\treturn Concert{};\r\n}"
},
{
"alpha_fraction": 0.29859718680381775,
"alphanum_fraction": 0.3151302635669708,
"avg_line_length": 35.58490753173828,
"blob_id": "8093ec3e23f59d964cbc1cf995f2fa8420733412",
"content_id": "7f8d53495bd7a72a3c7a0bbdb6d62c4cbb3a1d25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1996,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 53,
"path": "/MyProjects/FP/FP/Shapes - Exam/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from repository import *\r\nfrom controller import *\r\n\r\nclass UI:\r\n def __init__(self,controller=Controller()):\r\n self.__c=controller\r\n def printMenu(self):\r\n menu=''\r\n menu+='place <pattern> <x,y>\\n'\r\n menu+='tick [n]\\n'\r\n menu+='save filename\\n'\r\n menu+='load filename\\n'\r\n print(menu)\r\n def start(self):\r\n self.printMenu()\r\n while True:\r\n try:\r\n while True:\r\n x=None\r\n print(self.__c)\r\n repeat=True\r\n while repeat==True:\r\n repeat=False\r\n x=input('Enter the command:')\r\n x=x.strip()\r\n x=x.split()\r\n if len(x)==3 and x[0]!='place':\r\n repeat=True\r\n if x[0]=='place':\r\n a=x[2].split(',')\r\n a[0]=int(a[0])\r\n a[1]=int(a[1])\r\n if x[1]=='block':\r\n self.__c.block(a[0],a[1])\r\n elif x[1]=='tub':\r\n self.__c.tub(a[0],a[1])\r\n elif x[1]=='blinker':\r\n self.__c.blinkerH(a[0],a[1])\r\n self.__c.blinkerV(a[0], a[1])\r\n elif x[1]=='beacon':\r\n self.__c.beacon1(a[0],a[1])\r\n self.__c.beacon2(a[0],a[1])\r\n elif x[1]=='glider':\r\n self.__c.addGlider(a[0],a[1])\r\n elif x[0]=='tick':\r\n a=int(x[1])\r\n self.__c.tick(a)\r\n elif x[0]=='store':\r\n self.__c.store()\r\n elif x[0]=='load':\r\n self.__c.load()\r\n except:\r\n print('Invalid input!')\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6710875034332275,
"alphanum_fraction": 0.6710875034332275,
"avg_line_length": 26.560606002807617,
"blob_id": "fd057f9f8c8ac8991a070484e1d1ee2596215a5b",
"content_id": "30ca9cdb5b0177f2c3c0eaf903bb57742b901df7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1885,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 66,
"path": "/MyProjects/SDA/SDA/SortedBagBST SDA/SortedBagBST SDA/iterator.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"node.h\"\r\n#include <iostream>\r\n\r\ntemplate <typename TElem>\r\nclass Iterator\r\n{\r\n\tNode<TElem>* root = NULL;\t// root is a pointer to the node that is the start of the tree, this pointer will cange as the inorder traversal is started\r\n\r\n\t// Modifies the root of the iterator so that it starts from the most left node of the tree.\r\n\t// returns false if the pointer to the node is null, true otherwise.\r\n\tbool DeeperToLeft(Node<TElem>* here)\r\n\t{\r\n\t\tif (here == NULL) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (!DeeperToLeft(here->left)) {\r\n\t\t\troot = here;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\npublic:\r\n\t// Init function for the iterator given as parameter the first node (the root).\r\n\t// the root of the iterator becomes the most left node of the tree\r\n\tIterator(Node<TElem>* root) :root{ root } { DeeperToLeft(root->left); }\r\n\t\r\n\t// Validator function for the current node.\r\n\t// returns true if the current node is valid (different from null), false otherwise.\r\n\tbool isValid();\r\n\r\n\t// Retruns the value from the current node.\r\n\tTElem getValue();\r\n\r\n\t// Iterates to the next node from the tree.\r\n\tvoid next();\r\n};\r\n\r\ntemplate<typename TElem>\r\ninline bool Iterator<TElem>::isValid()\r\n{\r\n\treturn root != NULL;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline TElem Iterator<TElem>::getValue()\r\n{\r\n\treturn root->data;\r\n}\r\n\r\ntemplate<typename TElem>\r\ninline void Iterator<TElem>::next()\r\n{\r\n\t// Performs the inorder traversal through the binary tree\r\n\tif (!DeeperToLeft(root->right))\t// goes to the most left node of the right child\r\n\t{\r\n\t\tif (root->parent != NULL)\r\n\t\t{\r\n\t\t\twhile (root->parent != NULL && root == root->parent->right)\t// checks if the root is equal to the right child of the parent of the root\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and goes to the right child of parent of the current node repetitively\r\n\t\t\t\troot = root->parent;\r\n\t\t\troot = root->parent;\t// the root becomes its parent\r\n\t\t}\r\n\t}\r\n}\r\n"
},
{
"alpha_fraction": 0.5371248126029968,
"alphanum_fraction": 0.5434439182281494,
"avg_line_length": 21.44444465637207,
"blob_id": "ff8844bfa8fc7faada4e205e1de2594709434da6",
"content_id": "b8facd567d6aee0e1d9eca650246402692bb48de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 633,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 27,
"path": "/MyProjects/OOP/OOP/Practice - Vegetables/Vegetables/vegetable.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"vegetable.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nstd::string Vegetable::toString()\r\n{\r\n\tstringstream buff;\r\n\tint i;\r\n\tbuff << \"Family: \" << this->getFamily() << \"; Name: \" << this->getName() << \"; Parts: \";\r\n\tfor (i = 0;i < this->parts.size()-1;i++)\r\n\t\tbuff << this->parts[i] << \", \";\r\n\tbuff << this->parts[i];\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Vegetable::stri()\r\n{\r\n\tstringstream buff;\r\n\tint i;\r\n\tbuff << this->getFamily() << ';' << this->getName() << ';';\r\n\tfor (i = 0;i < this->parts.size()-1;i++)\r\n\t\tbuff << this->parts[i] << ',';\r\n\tbuff << this->parts[i];\r\n\treturn buff.str();\r\n}\r\n"
},
{
"alpha_fraction": 0.5382674336433411,
"alphanum_fraction": 0.5553686618804932,
"avg_line_length": 35.56842041015625,
"blob_id": "00df0c280709bb0b12378b4a3d76cfb76e6b2f35",
"content_id": "d3975b3353cdf7ec440799f30760825f574a89fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3567,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 95,
"path": "/MyProjects/FP/FP/Assignment 4/UI.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "from tests import *\r\nfrom functions import *\r\ndef readCommand(): #rads the command and splits it into a command and parameters\r\n x=input(\">>\")\r\n if x.find(' ')==-1:\r\n command=x\r\n params=[]\r\n return (command,params)\r\n command=x[0:x.find(' ')]\r\n params=x[x.find(' '):]\r\n params = params.split()\r\n for i in range(len(params)):\r\n params[i] = params[i].strip()\r\n return (command,params)\r\n\r\ndef showMenu(): #prints the menu of commands\r\n sMenu=\"The current commands are (use them carefully):\\n\"\r\n sMenu+=\"add <number>\\n\"\r\n sMenu+=\"insert <number> at <position>\\n\"\r\n sMenu+=\"remove <position>\\n\"\r\n sMenu+=\"remove <start position> to <end position>\\n\"\r\n sMenu+=\"replace <old number> with <new number>\\n\"\r\n sMenu+=\"list\\n\"\r\n sMenu+=\"list real <start position> to <end position>\\n\"\r\n sMenu+=\"list modulo [< | = | >] <number>\\n\"\r\n sMenu+=\"sum <start position> to <end position>\\n\"\r\n sMenu+=\"product <start position> to <end position>\\n\"\r\n sMenu+=\"filter real\\n\"\r\n sMenu+=\"filter modulo [< | = | >] <number>\\n\"\r\n sMenu+=\"undo\\n\"\r\n sMenu+=\"exit\\n\"\r\n print(sMenu)\r\n\r\ndef start(): #resolves the problem in the asked way\r\n undoL = []\r\n myList=[]\r\n testCheckReal()\r\n testImaginaryPart()\r\n testIntToString()\r\n testModuloComplex()\r\n testRealPart()\r\n showMenu()\r\n while True:\r\n j=0\r\n aux=myList[:]\r\n cmd=readCommand()\r\n command=cmd[0]\r\n params=cmd[1]\r\n if command==\"add\":\r\n addToList(myList,params[0])\r\n elif command==\"insert\":\r\n params[2]=int(params[2])\r\n insertToList(myList,params[0],params[2])\r\n elif command==\"remove\" and len(params)==1:\r\n params[0]=int(params[0])\r\n myList=removePozFromList(myList,params[0])\r\n elif command==\"remove\" and len(params)>1 and params[1]=='to':\r\n params[0]=int(params[0])\r\n params[2]=int(params[2])\r\n myList=removeFromFirstToLastFromList(myList,params[0],params[2])\r\n elif command==\"replace\":\r\n replaceOldWithNew(myList,params[0],params[2])\r\n elif command==\"list\" and len(params)==0:\r\n writeList(myList)\r\n elif command==\"list\" and len(params)>3 and params[0]==\"real\":\r\n params[1]=int(params[1])\r\n params[3]=int(params[3])\r\n realList(myList,params[1],params[3])\r\n elif command==\"list\" and len(params)>3 and params[0]==\"modulo\":\r\n params[2]=int(params[2])\r\n showModuloFromList(myList,params[1],params[2])\r\n elif command==\"sum\" and len(params)>0:\r\n params[0]=int(params[0])\r\n params[2]=int(params[2])\r\n print(sumCommand(myList,params[0],params[2]))\r\n elif command==\"product\":\r\n params[0] = int(params[0])\r\n params[2] = int(params[2])\r\n print(productCommand(myList,params[0],params[2]))\r\n elif command==\"filter\" and len(params)>0 and params[0]==\"real\":\r\n myList=filterRealCommand(myList)\r\n elif command==\"filter\" and len(params)==3:\r\n params[2]=int(params[2])\r\n myList=filterModuloCommand(myList,params[1],params[2])\r\n elif command==\"undo\":\r\n j=1\r\n myList=undoCommand(undoL)\r\n elif command==\"exit\":\r\n break\r\n elif command==\"help\":\r\n showMenu()\r\n else:\r\n print(\"Type a valid command! LOL\")\r\n if aux!=myList and j==0:\r\n undoL.append(deepcopy(myList))"
},
{
"alpha_fraction": 0.519920289516449,
"alphanum_fraction": 0.519920289516449,
"avg_line_length": 17.30769157409668,
"blob_id": "f03fd59bbf116411e6030f49acfb00b61b25a0e5",
"content_id": "83b313c59814749db87900459b23a61997a60617",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 504,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 26,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Expressions/ConstExpr.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Expressions\r\n{\r\n public class ConstExpr:IExpr\r\n {\r\n private int number;\r\n\r\n public ConstExpr(int nr)\r\n {\r\n number = nr;\r\n }\r\n\r\n public int evaluate(Utilities.IDictionary<string, int> dic)\r\n {\r\n return number;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"\" + number;\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.6899441480636597,
"alphanum_fraction": 0.6899441480636597,
"avg_line_length": 23.239437103271484,
"blob_id": "f5253fe3d6256cd6d309e953c419f757ed271d78",
"content_id": "cc4c04bce3e26a5ec242a4249dce42d5bb4b1883",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1790,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 71,
"path": "/MyProjects/OOP/OOP/Assignment 5-6 Template/Lab 5-6 Template/controller.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"repository.h\"\r\n#include \"list.h\"\r\n\r\n\r\nclass Controller\r\n{\r\nprivate:\r\n\tRepository repo;\r\n\tList list;\r\npublic:\r\n\t/*\r\n\tConstructor for the controller\r\n\tinitializes the controller\r\n\t*/\r\n\tController(const Repository& r) : repo{ r } {}\r\n\t/*\r\n\tReturns the repository from the controller\r\n\tout: repo\r\n\t*/\r\n\tRepository getRepo()const { return repo; }\r\n\t/*\r\n\tReturns the list from WatchList for the user\r\n\tout: list\r\n\t*/\r\n\tList getList() const { return list; }\r\n\t/*\r\n\tAdds a movie to the controller\r\n\tin: title, genre, year, likes, trailer\r\n\tout: return true if the movie was added, false otherwise\r\n\t*/\r\n\tbool addMovieToRepo(const std::string& title, const std::string& genre, const int year, const int likes, const std::string& trailer);\r\n\t/*\r\n\tDeletes a movie by title from the controller\r\n\tin: title\r\n\tout: return true if the movie was deleted, false otherwise\r\n\t*/\r\n\tbool delMovieFromRepo(const std::string& title);\r\n\t/*\r\n\tUpdates a movie in the controller\r\n\tin: old title, new title, new genre, new year, new likes, new trailer\r\n\tout: return true if the movie was updated, false otherwiese\r\n\t*/\r\n\tbool updateMovieToRepo(std::string oldTitle, std::string title, std::string genre, int year, int likes, std::string trailer);\r\n\t/*\r\n\tAdds a movie to the watch list\r\n\tin: movie\r\n\tout: adds the movie to the watch list\r\n\t*/\r\n\tvoid addMovieToList(const Movie& m);\r\n\t/*\r\n\tAdds a movie by genre to the watch list\r\n\tin: genre\r\n\tout: adds the movie to the watch list\r\n\t*/\r\n\tvoid addMovieByGenre(const std::string& genre);\r\n\t/*\r\n\tPlays the trailers for the movies\r\n\t*/\r\n\tvoid startList();\r\n\t/*\r\n\tJumps to the next movie trailer\r\n\t*/\r\n\tvoid nextMovieList();\r\n\r\n\tRepository getGenreRepo(const std::string genre);\r\n\r\n\tvoid delL(const std::string& title);\r\n\r\n\tvoid incLike(int pos);\r\n};"
},
{
"alpha_fraction": 0.5529131889343262,
"alphanum_fraction": 0.5529131889343262,
"avg_line_length": 24.28125,
"blob_id": "ca56b46e583861bd6ce8c2ef7f07cf67c874dd28",
"content_id": "60fe3c2f1bee6a13d5a1feb2a2d17aff560e7b8a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 843,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 32,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/CloseRFileStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing Interpreter.Model.Expressions;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class CloseRFileStmt:IStmt\r\n {\r\n private IExpr id;\r\n\r\n public CloseRFileStmt(IExpr e) { id = e; }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n int val = id.evaluate(state.SymbolTable);\r\n if(state.FileTab.exists(val)) {\r\n StreamReader b = state.FileTab.getValue(val);\r\n b.Close();\r\n state.FileTab.delete(val);\r\n }\r\n else throw new FileNotFoundException(\"File not found!\");\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"close(\" + id + \")\";\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.463971883058548,
"alphanum_fraction": 0.46572935581207275,
"avg_line_length": 26.549999237060547,
"blob_id": "106681343fd795fc96f4c007c066ec54c8729a65",
"content_id": "43cf28627b6ca93adcb74d8ebfee1e494a7d5a9f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 569,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 20,
"path": "/MyProjects/FP/FP/FP Test 2/repository.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "class Repository:\r\n def __init__(self):\r\n self.__data=[]\r\n def __str__(self):\r\n s=''\r\n for i in range(len(self.__data)):\r\n s=s+str(self.__data[i])+', '\r\n return s\r\n def getAll(self):\r\n return self.__data\r\n def get(self,index):\r\n return self.__data[index]\r\n def findByID(self,id):\r\n for i in range(len(self.__data)):\r\n if self.__data[i].getID()==id:\r\n return i\r\n return -1\r\n def add(self,el):\r\n el.setID(int(el.getID()))\r\n self.__data.append(el)"
},
{
"alpha_fraction": 0.5313283205032349,
"alphanum_fraction": 0.5401002764701843,
"avg_line_length": 22.24242401123047,
"blob_id": "27dfe85bd4b79f720153518c115b7be534daf97e",
"content_id": "07a3fce426f3cecf255f2794af3f012816b0c36c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 798,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 33,
"path": "/MyProjects/Graphs/Graphs/Graph 7 python/EdgeCost.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "'''\r\nCreated on May 3, 2018\r\n\r\n@author: Ale\r\n'''\r\n\r\n\r\nclass EdgeCost():\r\n def __init__(self):\r\n self.__costDict = {}\r\n\r\n def getCostDict(self):\r\n return self.__costDict\r\n\r\n def getCostForVertex(self, start, end):\r\n return self.__costDict[(start, end)]\r\n\r\n def addCost(self, start, end, cost):\r\n self.__costDict[(start, end)] = cost\r\n\r\n def changeCost(self, end, start, newCost):\r\n self.__costDict[(start, end)] = newCost\r\n\r\n def removeCost(self, start, end):\r\n del self.__costDict[(start, end)]\r\n\r\n def removeCostOfVertex(self, vertex):\r\n l = []\r\n for edge in self.getCostDict().keys():\r\n l.append(edge)\r\n for edge in l:\r\n if vertex in edge:\r\n self.removeCost(edge[0], edge[1])"
},
{
"alpha_fraction": 0.582186222076416,
"alphanum_fraction": 0.582186222076416,
"avg_line_length": 19.66666603088379,
"blob_id": "1e943d90e641308e4ec324822eabdb7bc961bf54",
"content_id": "1d9d0fc1aaa3aa87619505e92bbfb2046ee993a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1235,
"license_type": "no_license",
"max_line_length": 205,
"num_lines": 57,
"path": "/MyProjects/OOP/OOP/Practice 3/New/movie.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"movie.h\"\r\n#include <Windows.h>\r\n#include <shellapi.h>\r\n#include <sstream>\r\n\r\nvoid Movie::setTitle(std::string title)\r\n{\r\n\tthis->title = title;\r\n}\r\n\r\nvoid Movie::setGenre(std::string genre)\r\n{\r\n\tthis->genre = genre;\r\n}\r\n\r\nvoid Movie::setYear(int year)\r\n{\r\n\tthis->year = year;\r\n}\r\n\r\nvoid Movie::setLikes(int likes)\r\n{\r\n\tthis->likes = likes;\r\n}\r\n\r\nvoid Movie::setTrailer(std::string trailer)\r\n{\r\n\tthis->trailer = trailer;\r\n}\r\n\r\nstd::string Movie::toString()\r\n{\r\n\tstd::stringstream buff;\r\n\tbuff << \"Title: \" << this->getTitle() << '\\n' << \"Genre: \" << this->getGenre() << '\\n' << \"Year: \" << this->getYear() << '\\n' << \"Likes: \" << this->getLikes() << '\\n' << \"Trailer: \" << this->getTrailer();\r\n\treturn buff.str();\r\n}\r\n\r\nstd::string Movie::stri()\r\n{\r\n\tstd::stringstream buff;\r\n\tbuff << this->getTitle() << ',' << this->getGenre() << ',' << this->getYear() << ',' << this->getLikes() << ',' << this->getTrailer();\r\n\treturn buff.str();\r\n}\r\n\r\nvoid Movie::operator=(Movie m)\r\n{\r\n\tthis->title = m.title;\r\n\tthis->genre = m.genre;\r\n\tthis->year = m.year;\r\n\tthis->likes = m.likes;\r\n\tthis->trailer = m.trailer;\r\n}\r\n\r\nvoid Movie::watch()\r\n{\r\n\tShellExecute(NULL, NULL, \"chrome.exe\", this->getTrailer().c_str(), NULL, SW_SHOWMAXIMIZED);\r\n}\r\n"
},
{
"alpha_fraction": 0.6741230487823486,
"alphanum_fraction": 0.7051347494125366,
"avg_line_length": 17.88888931274414,
"blob_id": "7ea858684f04097c480c95f2dc4b359284cca261",
"content_id": "c84b3213e28880d466ad8a29c76b10e8324815a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 1967,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 99,
"path": "/MyProjects/DB/Lab 1/Lab1.sql",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "use Lab1bun;\r\nCREATE TABLE Helicopter_Pad(\r\nHPID CHAR(20) NOT NULL,\r\nAltitude INT,\r\nPRIMARY KEY(HPID)\r\n);\r\n\r\nCREATE TABLE Mall(\r\nMaID CHAR(20) NOT NULL,\r\nMall_Name VARCHAR(20),\r\nMall_Address CHAR(20),\r\nShop_count INT,\r\nHPID CHAR(20) NOT NULL,\r\nPRIMARY KEY(MaID),\r\nFOREIGN KEY(HPID) REFERENCES Helicopter_Pad(HPID),\r\n);\r\n\r\ncreate table Agency(\r\nAID CHAR(20) not null,\r\nAgency_Name VARCHAR(20),\r\nEmployee_Count int,\r\nPrimary key(AID)\r\n);\r\n\r\ncreate table Agency_Mall(\r\nMaID CHAR(20),\r\nAID char(20),\r\nPrimary key(MaID,AID),\r\nForeign key(MaID) references Mall(MaID),\r\nforeign key(AID) references Agency(AID)\r\n);\r\n\r\nCREATE TABLE Bathrooms(\r\nBID CHAR(20) NOT NULL,\r\nNr_Toilets INT,\r\nPRIMARY KEY(BID)\r\n);\r\n\r\nCREATE TABLE Floors(\r\nFID CHAR(20) NOT NULL,\r\nArea INT,\r\nBID CHAR(20) NOT NULL,\r\nPRIMARY KEY(FID),\r\nFOREIGN KEY(BID) REFERENCES Bathrooms(BID)\r\n);\r\n\r\nCREATE TABLE Shops(\r\nShID CHAR(20) NOT NULL,\r\nShop_Name VARCHAR(20),\r\nShop_Type VARCHAR(20),\r\nFID CHAR(20) NOT NULL,\r\nMaID CHAR(20) NOT NULL,\r\nPRIMARY KEY(ShID),\r\nFOREIGN KEY(FID) REFERENCES Floors(FID),\r\nFOREIGN KEY(MaID) REFERENCES Mall(MaID)\r\n);\r\n\r\nCREATE TABLE Customers(\r\nCID CHAR(20) NOT NULL,\r\nCustomer_Name VARCHAR(20),\r\nBudget INT,\r\nPRIMARY KEY(CID)\r\n);\r\n\r\nCREATE TABLE Shops_Customers(\r\nShID CHAR(20) NOT NULL,\r\nCID CHAR(20) NOT NULL,\r\nAge INT,\r\nPRIMARY KEY(ShID,CID),\r\nFOREIGN KEY(ShID) REFERENCES Shops(ShID),\r\nFOREIGN KEY(CID) REFERENCES Customers(CID)\r\n);\r\n\r\nCREATE TABLE Manager(\r\nMID CHAR(20) NOT NULL,\r\nManager_Name VARCHAR(20),\r\nAge INT,\r\nExperience INT,\r\nMaID CHAR(20) NOT NULL,\r\nPRIMARY KEY(MID),\r\nFOREIGN KEY(MaID) REFERENCES Mall(MaID)\r\n);\r\n\r\nCREATE TABLE Employees(\r\nEID CHAR(20) NOT NULL,\r\nEmployee_Name VARCHAR(20),\r\nSalary INT,\r\nShID CHAR(20) NOT NULL,\r\nPRIMARY KEY(EID),\r\nFOREIGN KEY(ShID) REFERENCES Shops(ShID)\r\n);\r\n\r\nCREATE TABLE Parking_Place(\r\nPPID CHAR(20) NOT NULL,\r\nParking_Location CHAR(20),\r\nMaID CHAR(20) NOT NULL,\r\nPRIMARY KEY(PPID),\r\nFOREIGN KEY(MaID) REFERENCES Mall(MaID)\r\n);"
},
{
"alpha_fraction": 0.6580201387405396,
"alphanum_fraction": 0.6627845168113708,
"avg_line_length": 24.26388931274414,
"blob_id": "8cc344c3b6de56743774136bc8982b466f63424b",
"content_id": "064cbc5bb316b12955745c63fd3205debf66d07e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1889,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 72,
"path": "/MyProjects/OOP/OOP/Practical 3/OOP practical ex1/SomeTeacher.cpp",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#include \"SomeTeacher.h\"\r\n#include <QMessageBox>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nSomeTeacher::SomeTeacher(StudentRepo<Student>& s, std::string name, std::vector<int> gr, QWidget *parent)\r\n\t:students{ s }, groups{ gr }, name{ name }, QMainWindow(parent)\r\n{\r\n\tui.setupUi(this);\r\n\tthis->flt = s.getByGroups(gr);\r\n\tthis->setWindowTitle(QString::fromStdString(name));\r\n\r\n\tthis->connectSignalsAndSlots();\r\n\tthis->populate();\t\r\n}\r\n\r\nvoid SomeTeacher::populate()\r\n{\r\n\tflt = students.getByGroups(groups);\r\n\tif (ui.StudentList->count() != 0)\r\n\t\tui.StudentList->clear();\r\n\tfor (auto m : this->flt)\r\n\t{\r\n\t\tQString listItem = QString::fromStdString(m.toString());\r\n\t\tQListWidgetItem * listItemWidget = new QListWidgetItem(listItem);\r\n\t\tthis->ui.StudentList->addItem(listItemWidget);\r\n\t}\r\n\tif (flt.size() > 0)\r\n\t\tui.StudentList->setCurrentRow(0);\r\n}\r\n\r\nvoid SomeTeacher::connectSignalsAndSlots()\r\n{\r\n\tQObject::connect(ui.GradeButton, SIGNAL(clicked()), this, SLOT(grade()));\r\n}\r\n\r\nint SomeTeacher::getSelectedIndex()\r\n{\r\n\tif (ui.StudentList->count() == 0)\r\n\t\treturn -1;\r\n\tQModelIndexList indexList = this->ui.StudentList->selectionModel()->selectedIndexes();\r\n\tif (indexList.size() == 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint index = indexList.at(0).row();\r\n\treturn index;\r\n}\r\n\r\nvoid SomeTeacher::grade()\r\n{\r\n\tint k = this->getSelectedIndex();\r\n\tint id = flt[k].getID();\r\n\tstring l = flt[k].getTeacher();\r\n\tif (l != name && l!=\" \" && l!=\"\")\r\n\t{\r\n\t\tui.GradeLine->clear();\r\n\t\tQMessageBox m;\r\n\t\tm.critical(0, \"error\", QString::fromStdString(\"You cannot grade a student that was graded by another teacher!\"));\r\n\t\treturn;\r\n\t}\r\n\tint it = students.findByID(id);\r\n\tstring f = ui.GradeLine->text().toStdString();\r\n\tdouble grade = stod(f);\r\n\tstudents.gradeStudent(it, grade);\r\n\tstudents.setTeacher(it, name);\r\n\tflt[k].setGrade(grade);\r\n\tflt[k].setTeacher(name);\r\n\tthis->populate();\r\n\tui.GradeLine->clear();\r\n}"
},
{
"alpha_fraction": 0.5292439460754395,
"alphanum_fraction": 0.5396372675895691,
"avg_line_length": 55.72941207885742,
"blob_id": "3262a51042a53e2538037f937a895d5b9e610f8b",
"content_id": "f1eea29ceb089e3c722aa12bfed32eecbca4d9ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 4909,
"license_type": "no_license",
"max_line_length": 187,
"num_lines": 85,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Program.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing Interpreter.Model.Statements;\r\nusing Interpreter.Model.Expressions;\r\nusing Interpreter.Model.Utilities;\r\nusing Interpreter.Model;\r\nusing Interpreter.Repository;\r\nusing Interpreter.Controller;\r\nusing System.IO;\r\nusing Interpreter.View;\r\n\r\nnamespace Interpreter\r\n{\r\n class Program\r\n {\r\n static void Main(string[] args)\r\n {\r\n IStack<IStmt> ExeStack4 = new MyStack<IStmt>();\r\n Interpreter.Model.Utilities.IDictionary<string, int> SymTable4 = new MyDictionary<string, int>();\r\n IList<int> out4 = new MyList<int>();\r\n Model.Utilities.IDictionary<int, StreamReader> fileTable4 = new MyDictionary<int, StreamReader>();\r\n IStmt expr4 = new CompStmt(\r\n new OpenRFileStmt(\"var_f\", \"C:\\\\Users\\\\pechd\\\\source\\\\repos\\\\Interpreter\\\\Interpreter\\\\Example.txt\"), new CompStmt(\r\n new ReadFileStmt(new VarExpr(\"var_f\"), \"var_c\"), new CompStmt(\r\n new PrintStmt(new VarExpr(\"var_c\")), new CompStmt(\r\n new IfStmt(new VarExpr(\"var_c\")\r\n , new CompStmt(new ReadFileStmt(new VarExpr(\"var_f\"), \"var_c\"), new PrintStmt(new VarExpr(\"var_c\"))), new PrintStmt(new ConstExpr(0))),\r\n new CloseRFileStmt(new VarExpr(\"var_f\"))))));\r\n ExeStack4.add(expr4);\r\n ProgramState prgCurrent4 = new ProgramState(ExeStack4, SymTable4, out4, fileTable4);\r\n myRepositorix repo4 = new PrgRepo(prgCurrent4);\r\n Controller.MyController ctrl4 = new Controller.MyController(repo4);\r\n //IRepo repo4 = new Repository.Repository();\r\n //repo4.addPrg(prgCurrent4);\r\n //Controller.Controller ctrl4 = new Controller.Controller(repo4);\r\n\r\n TextMenu menu = new TextMenu();\r\n menu.addCommand(new ExitCommand(\"0\", \"exit\"));\r\n menu.addCommand(new RunExample(\"1\", expr4.ToString(), ctrl4));\r\n menu.show();\r\n\r\n //IExeStack<Statement> exeStack = new Stack<Statement>();\r\n //Model.ADT.IDictionary<string, int> symbolTable = new DictionaryC<string, int>();\r\n //IOutput<int> messages = new Output<int>();\r\n //IFileTable<int, FileData> fd = new FileTable<int, FileData>();\r\n\r\n //Statement s = new CompoundStatement(new AssignStatement(\"v\", new ConstantExpression(2)), new PrintStatement(new VariableExpression(\"v\")));\r\n //exeStack.Push(s);\r\n //PrgState state = new PrgState(symbolTable, exeStack, messages, fd);\r\n //IPrgRepository repo = new PrgRepository(state);\r\n //Controller.Controller ctrl = new Controller.Controller(repo);\r\n\r\n //IExeStack<Statement> exeStack1 = new Stack<Statement>();\r\n //Model.ADT.IDictionary<string, int> symbolTable1 = new DictionaryC<string, int>();\r\n //IOutput<int> messages1 = new Output<int>();\r\n //IFileTable<int, FileData> fd1 = new FileTable<int, FileData>();\r\n\r\n //Statement s1 = new CompoundStatement(\r\n // new CompoundStatement(\r\n // new CompoundStatement(\r\n // new OpenFileStatement(\"var_f\", \"C:\\\\Users\\\\pechd\\\\source\\\\repos\\\\Lab7\\\\Lab7\\\\Example.txt\"),\r\n\r\n // new ReadFileStatement(new VariableExpression(\"var_f\"), \"var_c\")\r\n // ),\r\n // new CompoundStatement(\r\n // new PrintStatement(new VariableExpression(\"var_c\")),\r\n // new IfStatement(\r\n // new VariableExpression(\"var_c\"),\r\n // new PrintStatement(new ConstantExpression(0))\r\n // , new CompoundStatement(\r\n // new ReadFileStatement(new VariableExpression(\"var_f\"), \"var_c\"),\r\n // new PrintStatement(new VariableExpression(\"var_c\")))))), new CloseFileStatement(new VariableExpression(\"var_f\")));\r\n\r\n //exeStack1.Push(s1);\r\n //PrgState state1 = new PrgState(symbolTable1, exeStack1, messages1, fd1);\r\n //IPrgRepository repo1 = new PrgRepository(state1);\r\n //Controller.Controller ctrl1 = new Controller.Controller(repo1);\r\n\r\n //TextMenu menu = new TextMenu();\r\n //menu.addCommand(new ExitCommand(\"0\", \"exit\"));\r\n //menu.addCommand(new RunExample(\"1\", s.ToString(), ctrl));\r\n //menu.addCommand(new RunExample(\"2\", s1.ToString(), ctrl1));\r\n //menu.show();\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.49689868092536926,
"alphanum_fraction": 0.4975878596305847,
"avg_line_length": 27.020000457763672,
"blob_id": "595bb9f6b92a23509523c4392ea9e67a70588a8b",
"content_id": "ff59991b7427becf00a0a48337ebfab88e762abb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1453,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 50,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Model/Statements/ReadFileStmt.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model.Expressions;\r\nusing System.IO;\r\nusing Interpreter.Exceptions;\r\nusing System.Linq;\r\n\r\nnamespace Interpreter.Model.Statements\r\n{\r\n public class ReadFileStmt:IStmt\r\n {\r\n\r\n private IExpr id;\r\n private string var;\r\n public ReadFileStmt(IExpr e, string s) { id = e; var = s; }\r\n\r\n public ProgramState execute(ProgramState state)\r\n {\r\n int val = this.id.evaluate(state.SymbolTable);\r\n if (state.FileTab.exists(val))\r\n {\r\n StreamReader b = state.FileTab.getValue(val);\r\n string line = b.ReadLine();\r\n int myValue;\r\n if (line == null)\r\n myValue = 0;\r\n else\r\n myValue = int.Parse(line);\r\n if (state.SymbolTable.exists(this.var))\r\n {\r\n state.SymbolTable.delete(this.var);\r\n state.SymbolTable.setValue(this.var, myValue);\r\n }\r\n else\r\n state.SymbolTable.setValue(this.var, myValue);\r\n\r\n }\r\n else\r\n throw new FileNotFoundException(\"File not found!\");\r\n return state;\r\n }\r\n\r\n public override string ToString()\r\n {\r\n return \"ReadFile(\" + id + \",\" + var + \")\";\r\n }\r\n }\r\n \r\n}\r\n"
},
{
"alpha_fraction": 0.4985058307647705,
"alphanum_fraction": 0.5460472702980042,
"avg_line_length": 30.57522201538086,
"blob_id": "ff8152bc74e96519a1cbedf25d023bbd68c06763",
"content_id": "8023657963b5febb52f3ad2fbf5852ccb4876e5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3681,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 113,
"path": "/MyProjects/FP/FP/Assignment 5/tests.py",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "import unittest\r\nfrom controller import *\r\nfrom domain import *\r\nfrom domain import *\r\n\r\nclass Test(unittest.TestCase):\r\n def testGetStudentID(self):\r\n s1=Student(1,'Marian',1)\r\n s2=Student(2,'Maria',3)\r\n self.assertEqual(s1.getStudentID(),1)\r\n self.assertEqual(s2.getStudentID(),2)\r\n def testGetName(self):\r\n s1 = Student(1, 'Marian', 1)\r\n s2 = Student(2, 'Maria', 3)\r\n self.assertEqual(s1.getName(), 'Marian')\r\n self.assertEqual(s2.getName(), 'Maria')\r\n def testGetGroup(self):\r\n s1 = Student(1, 'Marian', 1)\r\n s2 = Student(2, 'Maria', 3)\r\n self.assertEqual(s1.getName(), 1)\r\n self.assertEqual(s2.getName(), 3)\r\n def testGetAssignmentID(self):\r\n a1=Assignment(1,'Do this','7.7.7')\r\n a2=Assignment(2,'Make that happen','10.10.2017')\r\n self.assertEqual(a1.getAssignmentID(),1)\r\n self.assertEqual(a2.getAssignmentID(), 2)\r\n def testGetAssignmentDescription(self):\r\n a1 = Assignment(1, 'Do this', '7.7.7')\r\n a2 = Assignment(2, 'Make that happen', '10.10.2017')\r\n self.assertEqual(a1.getDescription(), 'Do this')\r\n self.assertEqual(a2.getDescription(), 'Make that happen')\r\n def testGetAssignmentDeadline(self):\r\n a1 = Assignment(1, 'Do this', '7.7.7')\r\n a2 = Assignment(2, 'Make that happen', '10.10.2017')\r\n self.assertEqual(a1.getDeadline(), '7.7.7')\r\n self.assertEqual(a2.getDeadline(), '10.10.2017')\r\n\r\n\r\n\r\n def testRepositoryAdd(self):\r\n r=Repository()\r\n a1 = Assignment(1, 'Do this', '7.7.7')\r\n a2 = Assignment(2, 'Do this', '7.7.1')\r\n r.add(a1)\r\n r.add(a2)\r\n self.assertEqual(r.get(0),a1)\r\n self.assertEqual(r.get(1),a2)\r\n def testRepositoryRemoveIndex(self):\r\n r = Repository()\r\n a1 = Assignment(1, 'Do this', '7.7.7')\r\n r.add(a1)\r\n r.add(a1)\r\n r.removeIndex(1)\r\n self.assertEqual(r.get(0), a1)\r\n self.assertEqual(len(r.getAll()), 1)\r\n\r\n\r\n\r\n def testControllerFindByAssiID(self):\r\n r = Repository()\r\n c=Controller(r)\r\n a1 = Assignment(1, 'Do this', '7.7.7')\r\n a2 = Assignment(2, 'Do this', '7.7.1')\r\n c.add(a1)\r\n c.add(a2)\r\n self.assertEqual(c.findByAssiID(1),0)\r\n self.assertEqual(c.findByAssiID(2), 1)\r\nclass TestData(unittest.TestCase):\r\n # def __init__(self):\r\n # self.data = Data()\r\n # for i in range(100):\r\n # self.data.append(i)\r\n def test1(self):\r\n data = []\r\n for i in range(100):\r\n data.append(i)\r\n data = Data(data)\r\n j = 0\r\n for i in data:\r\n self.assertEqual(j, i)\r\n j += 1\r\n def test2(self):\r\n list = [2, 1, 4, 3, 16, 6, 100]\r\n sort(list, lambda x: x)\r\n for i in range(0, len(list) - 1):\r\n self.assertLessEqual(list[i], list[i + 1])\r\n def test3(self):\r\n data = Data()\r\n for i in range(100):\r\n data.append(i)\r\n result = filter(data, test)\r\n for i in result:\r\n if i % 2 == 1:\r\n self.assertEqual(True, False)\r\n def test4(self):\r\n data = Data([])\r\n data.append(1)\r\n self.assertEqual(len(data), 1)\r\n data[0] = 10\r\n self.assertEqual(data[0], 10)\r\n del data[0]\r\n self.assertEqual(len(data), 0)\r\n if _name_ == '_main_':\r\n unittest.main()\r\n\r\na=Test()\r\na.testGetStudentID()\r\na.testGetAssignmentID()\r\na.testGetAssignmentDescription()\r\na.testGetAssignmentDeadline()\r\na.testRepositoryAdd()\r\na.testRepositoryRemoveIndex()\r\na.testControllerFindByAssiID()\r\n"
},
{
"alpha_fraction": 0.6287797093391418,
"alphanum_fraction": 0.6320194602012634,
"avg_line_length": 22.529800415039062,
"blob_id": "4bd8529b404d4ddd144433737390589b09de33db",
"content_id": "5059cd98a3ce6f55f1e32243223a9039a2e40d4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3704,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 151,
"path": "/MyProjects/OOP/OOP/Practical 1/OOP other practical 1/TaskRepo.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <vector>\r\n#include \"task.h\"\r\n#include <sstream>\r\n#include <fstream>\r\n#include <exception>\r\n\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nclass TaskRepo\r\n{\r\nprivate:\r\n\tstd::vector<T> elems;\r\n\tstd::string filename;\r\npublic:\r\n\tTaskRepo(std::string f) :filename{ f } { this->readFromFile(); this->sortMe(); }\r\n\tTaskRepo() :filename{ \"\" } {}\r\n\t~TaskRepo() {}\r\n\r\n\tvoid writeToFile();\r\n\tvoid readFromFile();\r\n\r\n\tvoid sortMe();\r\n\r\n\tstd::vector<T> getAll() { return elems; }\r\n\tint getLenght() { return elems.size(); }\r\n\r\n\tvoid add(T e) { elems.push_back(e); }\r\n\t//Deletes an element from position 'pos'\r\n\t//in: int pos, the position\r\n\t//out: the element on position pos was deleted\r\n\tvoid del(int pos) { elems.erase(elems.begin() + pos); }\r\n\r\n\tT operator[](int pos) { return elems[pos]; }\r\n\tTaskRepo<T>& operator=(TaskRepo<T>& p);\r\n\t\r\n\tvoid setThisProgress(int pos);\r\n\tvoid setThisID(int pos, int id, std::string n) { elems[pos].setID(id); elems[pos].setProgName(n); }\r\n\t//Sets the status of an element from the position 'pos' to 'closed'\r\n\t//in: int pos, the position of the element\r\n\t//out: the status of an element from the position 'pos' has been set to 'closed'\r\n\tvoid setThisClosed(int pos);\r\n\t//Sets the status of an element from the position 'pos' to 'in progress' and the programmerID of the task to be the 'id'\r\n\t//in: int pos, int id, the position of the element and the new id\r\n\t//out: the status of an element from the position 'pos' has been set to 'in progress' and the programmerID is 'id'\r\n\tvoid updateStatusProgress(int pos, int id);\r\n};\r\n\r\nclass Exception :public exception\r\n{\r\nprivate:\r\n\tstring mess;\r\npublic:\r\n\tException(string m) :mess{ m },exception(m.c_str()) {}\r\n\tstd::string what() { return mess; }\r\n};\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::writeToFile()\r\n{\r\n\tstd::ofstream file(this->filename);\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\tfor (int i = 0;i < this->elems.size();i++)\r\n\t\tfile << this->elems[i].stri() << '\\n';\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::readFromFile()\r\n{\r\n\tstd::ifstream file(this->filename);\r\n\tstd::string t, i;\r\n\tif (!file.is_open())\r\n\t\treturn;\r\n\r\n\twhile (getline(file, i))\r\n\t{\r\n\t\tstd::vector<std::string> v;\r\n\t\tstd::stringstream line(i);\r\n\t\twhile (getline(line, t, ','))\r\n\t\t\tv.push_back(t);\r\n\t\tint id, stat;\r\n\t\tid = stoi(v[2]);\r\n\t\tstat = stoi(v[1]);\r\n\t\tstring desc = v[0];\r\n\t\tstring progn = v[3];\r\n\t\tTask m{ desc,stat,id,progn};\r\n\t\tthis->elems.push_back(m);\r\n\t}\r\n\tfile.close();\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::sortMe()\r\n{\r\n\tint i, j, min_idx;\r\n\r\n\r\n\tfor (i = 0; i < this->getLenght() - 1; i++)\r\n\t{\r\n\t\tmin_idx = i;\r\n\t\tfor (j = i + 1; j < this->getLenght(); j++)\r\n\t\t\tif (this->elems[j].getIntStat() < this->elems[min_idx].getIntStat())\r\n\t\t\t\tmin_idx = j;\r\n\r\n\t\tT a1 = this->elems[min_idx];\r\n\t\tthis->elems[min_idx] = this->elems[i];\r\n\t\tthis->elems[i] = a1;\r\n\t}\r\n}\r\n\r\ntemplate<typename T>\r\ninline TaskRepo<T>& TaskRepo<T>::operator=(TaskRepo<T>& p)\r\n{\r\n\tthis->elems = p.elems;\r\n\tthis->filename = p.filename;\r\n\treturn *this;\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::setThisProgress(int pos)\r\n{\r\n\tif (elems[pos].getIntStat() == -1)\r\n\t{\r\n\t\telems[pos].setProgress();\r\n\t}\r\n\telse\r\n\t\tthrow Exception{ \"Task status is not 'open'!\" };\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::setThisClosed(int pos)\r\n{\r\n\tif (elems[pos].getIntStat() == 0)\r\n\t{\r\n\t\telems[pos].setClosed();\r\n\t}\r\n\telse\r\n\t\tthrow Exception{ \"Task status is not 'in progress' or you are not the one who started the task!\" };\r\n}\r\n\r\ntemplate<typename T>\r\ninline void TaskRepo<T>::updateStatusProgress(int pos, int id)\r\n{\r\n\tthis->setThisProgress(pos);\r\n\tthis->setThisID(pos, id,\"name\");\r\n}\r\n"
},
{
"alpha_fraction": 0.4578947424888611,
"alphanum_fraction": 0.45921051502227783,
"avg_line_length": 25.636363983154297,
"blob_id": "dce26fa85036e7459d51b1c1ec5774e80e38e781",
"content_id": "6036adc8d198a3494ba1ec352d461e0d249eec94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1522,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 55,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Repository/PrgRepo.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing Interpreter.Model;\r\nusing Interpreter.Model.Statements;\r\nusing System.IO;\r\n\r\nnamespace Interpreter.Repository\r\n{\r\n public class PrgRepo:myRepositorix\r\n {\r\n private ProgramState p;\r\n public PrgRepo(ProgramState p)\r\n {\r\n this.p = p;\r\n }\r\n\r\n public ProgramState getCurrentPrgState()\r\n {\r\n return this.p;\r\n }\r\n public void logPrgState()\r\n {\r\n ProgramState p = this.getCurrentPrgState();\r\n\r\n using (StreamWriter log = File.AppendText(\"C:\\\\Users\\\\pechd\\\\source\\\\repos\\\\Lab7\\\\Lab7\\\\log.txt\"))\r\n {\r\n\r\n log.WriteLine(\"Stack:\\n\");\r\n foreach (IStmt st in p.Stack)\r\n {\r\n log.WriteLine(st);\r\n }\r\n log.WriteLine(\"SymbolTable:\\n\");\r\n foreach (KeyValuePair<string, int> v in p.SymbolTable)\r\n {\r\n log.WriteLine(v.Key + \"->\" + v.Value);\r\n }\r\n\r\n log.WriteLine(\"Output list:\");\r\n foreach (int v in p.Output)\r\n {\r\n log.WriteLine(v);\r\n }\r\n log.WriteLine(\"File Table:\");\r\n foreach (KeyValuePair<int, StreamReader> kvp in p.FileTab)\r\n {\r\n log.WriteLine(kvp.Key + \"->\" + kvp.Value);\r\n }\r\n\r\n }\r\n\r\n }\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.7382022738456726,
"alphanum_fraction": 0.7382022738456726,
"avg_line_length": 28.758621215820312,
"blob_id": "b974fb5b90d3bda05d3dee9c7621347fb6969123",
"content_id": "4872f575d1bfedcd7399202378b47b4c0b9eaf15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 890,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 29,
"path": "/MyProjects/OOP/OOP/Assignment 14/Again 12/table.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <QAbstractTableModel>\r\n#include \"repository.h\"\r\n\r\nclass MovieTable :public QAbstractTableModel\r\n{\r\nprivate:\r\n\tRepository& repo;\r\n\r\npublic:\r\n\tMovieTable(Repository& r, QObject* parent = Q_NULLPTR);\r\n\t~MovieTable();\r\n\r\n\tint rowCount(const QModelIndex & parent = QModelIndex{})const override;\r\n\r\n\tint columnCount(const QModelIndex & parent = QModelIndex{})const override;\r\n\r\n\t//Value at a given pos\r\n\tQVariant data(const QModelIndex & index, int role = Qt::DisplayRole)const override;\r\n\r\n\t//add header data\r\n\tQVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole)const override;\r\n\r\n\t//will be called when a cell is edited\r\n\tbool setData(const QModelIndex & index, const QVariant &value, int role = Qt::EditRole)override;\r\n\r\n\t//used to set certain properties of a cell\r\n\tQt::ItemFlags flags(const QModelIndex & index)const override;\r\n};"
},
{
"alpha_fraction": 0.6768559217453003,
"alphanum_fraction": 0.6768559217453003,
"avg_line_length": 19,
"blob_id": "ef504c20a557cdbf907cd3c2ef9196254715eec4",
"content_id": "bbd6cf9f1f29b79a8c164cb9b262409d1f0fd39a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 231,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 11,
"path": "/MyProjects/MAP/Assignment 7/Interpreter/Exceptions/DivisionByZero.cs",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\n\r\nnamespace Interpreter.Exceptions\r\n{\r\n public class DivisionByZero : Exception\r\n {\r\n public DivisionByZero(String msg) : base(msg) { }\r\n }\r\n}"
},
{
"alpha_fraction": 0.6912028789520264,
"alphanum_fraction": 0.6912028789520264,
"avg_line_length": 17.20689582824707,
"blob_id": "e99078186b04011034c41ecf318d3d63c1f38ef0",
"content_id": "e8e5f8e3714cb5dc4d832d7dbc160797f7757c5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 557,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 29,
"path": "/MyProjects/OOP/OOP/Practical 2/OOP Practical ex/MainTeacher.h",
"repo_name": "pechdaniel/MyProjects",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n\r\n#include <QtWidgets/QMainWindow>\r\n#include \"ui_MainTeacher.h\"\r\n#include \"controller.h\"\r\n#include \"TeacherWindow.h\"\r\n\r\nclass HeadTeacher : public QMainWindow\r\n{\r\n\tQ_OBJECT\r\n\r\npublic:\r\n\tHeadTeacher(Controller& c,QWidget *parent = Q_NULLPTR);\r\n\t~HeadTeacher() {}\r\nprivate:\r\n\tController & controller;\r\n\tUi::MainTeacher ui;\r\n\tstd::vector<SepareteTeacher*> all;\r\n\tint currentID;\r\n\r\n\tvoid connectSignalsAndSlots();\r\n\tint getSelectedIndex();\r\n\tvoid populate();\r\n\tvoid modifyAll();\r\n\tvoid showAll();\r\n\tprivate slots:\r\n\tvoid add();\r\n\tvoid del();\r\n};\r\n"
}
] | 290 |
iamcaleberic/challenge-cave | https://github.com/iamcaleberic/challenge-cave | 15cf65d97921d162a053a026c77bd1c4b3526ca0 | 6222fd406b4be34aade23fb7a1f4184e6fc176ff | 710b259bfb79926e6692dc649a5a9ba3d08ef03b | refs/heads/master | 2020-03-27T10:54:47.409066 | 2019-07-30T20:37:38 | 2019-07-30T20:37:38 | 146,453,220 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5607028603553772,
"alphanum_fraction": 0.6166134476661682,
"avg_line_length": 31.947368621826172,
"blob_id": "1b5cd323585c166e8209b9eefac73c5eaaa50b59",
"content_id": "7d363c7eb8e193ed2e4ba589aeb0eb059b2506b3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 626,
"license_type": "permissive",
"max_line_length": 121,
"num_lines": 19,
"path": "/ordinal-dates.py",
"repo_name": "iamcaleberic/challenge-cave",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# output the dates in a format\n # YYYY - MM - D\n # challenge is ordinal dates are not supported in some languages\n # and you are not allowed to use libraries so we use the python stdlib\n \nimport re\nfrom datetime import datetime\n\ndef main():\n d_array = [\"30th May 2019\", \"12th June 2012\", \"14th July 1993\", \"30th July 1994\", \"1st January 2020\", \"2nd May 1912\"]\n for d_ in d_array:\n date_string = re.sub(r'(th|nd|st)', \"\", d_)\n parsed_date = datetime.strptime(date_string, \"%d %B %Y\")\n print(parsed_date.strftime(\"%Y-%m-%d\")\n)\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5373737215995789,
"alphanum_fraction": 0.539393961429596,
"avg_line_length": 18.038461685180664,
"blob_id": "27b902ab1f312ff9801c819721ceaf9cbedd469c",
"content_id": "4f6caca6aae92f58fddae0cb36eaf3ea197e2492",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 495,
"license_type": "permissive",
"max_line_length": 39,
"num_lines": 26,
"path": "/linked.py",
"repo_name": "iamcaleberic/challenge-cave",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\nclass LinkedList:\n def _init_(self):\n self.nodes = []\n\n def append(self, node):\n self.nodes.append(node)\n\n def get(self, value):\n for node in self.nodes:\n if node.get() == value:\n return node\n\n return None\n\nclass Node:\n def _init_(self, value, next=None):\n self.value = value\n self.next = next\n\n def get(self):\n return self.value\n\n def next_node(self):\n return self.next\n"
},
{
"alpha_fraction": 0.6012526154518127,
"alphanum_fraction": 0.6096033453941345,
"avg_line_length": 21.809524536132812,
"blob_id": "644c58b0466945de4496801352f762d628f5f718",
"content_id": "1384a17b3e0215cff242870603cbe35b77e47144",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 479,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 21,
"path": "/balanced_parantheses.rb",
"repo_name": "iamcaleberic/challenge-cave",
"src_encoding": "UTF-8",
"text": "# The expression contains parentheses: ( and ) \n# The expression does not contain any other symbols \n# Return true if the parentheses are balanced \n# Otherwise, return false \n# Examples: # () => true # (()()) => true # ( => false # )( => false \n\ndef balance_parentheses(expression) \n \n counter = 0 \n\n expression.each_char do |pr|\n counter+=1 if pr == \"(\"\n counter-=1 if pr == \")\"\n\n end\n\n return counter == 0 ? true : false\n \nend\n\nbalance_parentheses(\"())()()()(((((\")\n"
},
{
"alpha_fraction": 0.8205128312110901,
"alphanum_fraction": 0.8205128312110901,
"avg_line_length": 18,
"blob_id": "03b4ac54fe282d1777b636394ebb12f7af493366",
"content_id": "621810c579bfe5cc5c6d006dd395f534b000f480",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 39,
"license_type": "permissive",
"max_line_length": 20,
"num_lines": 2,
"path": "/README.md",
"repo_name": "iamcaleberic/challenge-cave",
"src_encoding": "UTF-8",
"text": "# challenge-cave\nInterview challenges \n"
},
{
"alpha_fraction": 0.5349854230880737,
"alphanum_fraction": 0.556851327419281,
"avg_line_length": 22.65517234802246,
"blob_id": "25ccc401e72fe262965d2b82e0b96d607ae4bd09",
"content_id": "052d12e771f3ff9195b8d9830e686d44d46ecd8c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 686,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 29,
"path": "/combine-strings.py",
"repo_name": "iamcaleberic/challenge-cave",
"src_encoding": "UTF-8",
"text": "# you have two strings merge them letter after letter and if one is shorter add it to the rest\n#[WIP]\n\ndef main():\n str1 = \"challenge\"\n str2 = \"cave\"\n\n new_word = []\n if len(str1) > len(str2):\n longest = str1\n shortest = list(str2)\n elif len(str2) > len(str1):\n longest = str2\n shortest = list(str1)\n elif len(str1) == len(str2):\n longest = str1\n shortest = list(str2)\n\n shortest.reverse()\n for letter in list(longest):\n new_word.append(letter)\n if len(shortest) != 0:\n new_word.append(shortest.pop())\n\n # return new_word\n print(''.join(new_word))\n\nif __name__ == '__main__':\n main()\n"
}
] | 5 |
yeonghoey/github-collector | https://github.com/yeonghoey/github-collector | b6c57d7d92677eaece4c48115c27624b8768687d | 3233b9a0577f4ffe29b32fab1589ad1b2511ed23 | cb050c74e00dc9bca786a0dee18858485b8b929f | refs/heads/master | 2021-01-20T15:39:19.750884 | 2016-05-30T16:45:21 | 2016-05-30T16:45:21 | 59,902,011 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.717277467250824,
"alphanum_fraction": 0.7476440072059631,
"avg_line_length": 18.489795684814453,
"blob_id": "4c987668a10dd7f77d18c72548ab498daf560a5c",
"content_id": "1531b0c03e0a4e1570c65c169eb7a8e32bffafb1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 955,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 49,
"path": "/README.md",
"repo_name": "yeonghoey/github-collector",
"src_encoding": "UTF-8",
"text": "# ghcollector\n\n## Usage\n\n```shell\n$ python stars.py [personal_access_token]\n$ python stars.py [personal_access_token] | tee stars.tsv\n```\n\n`personal_access_token` only requires public access.\n\nif `personal_access_token` is not specified, works as an unauthorized user,\nwhich is not recommended.\n\n## Output\n\nPrint Recent 100 starred repos of all users to stdout\nformatted in `<user>\\t<repo>`\n\n```\nmojombo crystal-lang/crystal\nmojombo mojombo/jquery\n...\ndefunkt gillesdemey/Cumulus\ndefunkt apple/swift\ndefunkt nylas/N1\n...\n```\n\n## Rate Limiting\n\n[Rating Limiting](https://developer.github.com/v3/#rate-limiting)\n\nit waits for reset when it reaches `rate limit`\n\n\n```\n# These are printed to stderr\n...\nwait for reset: 469s remaining\nwait for reset: 468s remaining\nwait for reset: 467s remaining\nwait for reset: 466s remaining\nwait for reset: 465s remaining\nwait for reset: 464s remaining\nwait for reset: 463s remaining\nwait for reset: 462s remaining\n...\n```\n"
},
{
"alpha_fraction": 0.5274451375007629,
"alphanum_fraction": 0.5384231805801392,
"avg_line_length": 23.439023971557617,
"blob_id": "5ea9f4fef52586a1bb890ab10e6643f1c9e34bcf",
"content_id": "77eb530e17fa318102b274192bb1b5801047a6ed",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2004,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 82,
"path": "/stars.py",
"repo_name": "yeonghoey/github-collector",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\n\nimport sys\nimport time\nfrom pprint import pprint\n\nimport requests\n\nGITHUB = 'https://api.github.com'\n\ndef G(uri):\n return '{0}/{1}'.format(GITHUB, uri)\n\ndef main(getter, since):\n if since:\n url = G('users?since=%s&per_page=100' % since)\n else:\n url = G('users?per_page=100')\n while True:\n us, url = users(getter, url)\n for u in us:\n for r in starred(getter, u):\n print('%s\\t%s' % (u, r))\n\ndef users(getter, url):\n r = getter(url)\n names = [ u['login'] for u in r.json() ]\n nexturl = r.links.get('next', {}).get('url', '')\n return (names, nexturl)\n\ndef starred(getter, user):\n r = getter(G('users/%s/starred?sort=created&per_page=100' % user))\n return [repo['full_name'] for repo in r.json()]\n\ndef rate_limit(getter):\n r = getter(G('rate_limit'))\n core = r.json()['resources']['core']\n return (core['limit'], core['remaining'], core['reset'])\n\n\ndef new_getter(token = None):\n headers = {}\n if token:\n headers = { 'Authorization': 'token %s' % token }\n\n def getter(url):\n return requests.get(url, headers=headers)\n\n def getter_with_wait(url):\n r = getter(url)\n try:\n r.raise_for_status()\n except:\n if r.status_code == 403:\n wait(r.headers['X-RateLimit-Reset'])\n r = getter(url)\n r.raise_for_status()\n else:\n raise\n return r\n\n return getter_with_wait\n\ndef wait(reset):\n reset = int(reset)\n while True:\n now = int(time.time() - 1)\n secs = max(reset - now, 0)\n if secs == 0: break\n print('wait for reset: %ss remaining' % secs, file=sys.stderr)\n time.sleep(1)\n\n\nif __name__ == '__main__':\n token = ''\n since = None\n if len(sys.argv) >= 2:\n token = sys.argv[1]\n if len(sys.argv) == 3:\n since = sys.argv[2]\n getter = new_getter(token)\n main(getter, since)\n"
}
] | 2 |
liamtbb/netdevr | https://github.com/liamtbb/netdevr | 96eed58a17483b7b8f19eb9b499a77a1a2eec959 | 46326d238b6a5e309aba2dcdc94b8145a0383ce7 | 06b1177ad2c43f10b0bbe08d294b06ae4dd55b9c | refs/heads/master | 2023-08-31T08:50:08.454748 | 2021-11-01T17:43:05 | 2021-11-01T17:43:05 | 260,737,487 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5587273240089417,
"alphanum_fraction": 0.5599541664123535,
"avg_line_length": 35.9395751953125,
"blob_id": "c1c40cda43945931fdeecfb91dab54e107b9d2ef",
"content_id": "92af8de45e857251128c379c99a9e33173144f25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12226,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 331,
"path": "/netdevr.py",
"repo_name": "liamtbb/netdevr",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3.7\nfrom netmiko.ssh_exception import NetMikoTimeoutException, NetmikoAuthenticationException\n# from netdevr_functions import host_compile, host_separator\nfrom netdevr_config import hostlist_conf, command_conf\nfrom datetime import date, timedelta\nfrom keyring import get_password\nfrom progress.bar import ShadyBar\nfrom PyInquirer import prompt, Separator\nimport os, logging, sys, time, argparse, ast, netmiko, getpass\n\n# inline functions #####################################################################################\n########################################################################################################\ndef host_compile(hostlist_undict, hostlist_active):\n\n hostlist_complete = []\n\n for host in hostlist_active:\n if any(s in hostlist_undict for s in (str(host), 'ALL HOSTS')):\n key_list = list(hostlist_active[str(host)])\n hostlist_complete = hostlist_complete + key_list\n\n # print(hostlist_complete)\n # exit()\n\n return hostlist_complete\n\n\ndef host_separator(hostlist_active):\n\n separator_autopop = \"\"\n\n for host in hostlist_active:\n separator_autopop = separator_autopop + \",\\n\\t\\t\\t{\\n\\t\\t\\t'name': '\" + host + \"'\\n\\t\\t\\t}\"\n\n separator_autopop = separator_autopop + \",\\n\\t\\t\\t{\\n\\t\\t\\t'name': '\" + \"ALL HOSTS\" + \"'\\n\\t\\t\\t}\"\n\n separator_provision_head = '''\nhostlist_select = [\n {\n 'type': 'checkbox',\n 'name': 'hostlist_options',\n 'message': \"Select 1 or more hostlists with [space], continue with [enter]\",\n 'choices': [\n Separator('= Vancouver =')'''\n\n separator_provision_tail = '''\n ],\n 'validate': lambda answer: 'You must choose at least one hostlist.' \\\\\n if len(answer) == 0 else True\n }\n]'''\n\n separator_provision = separator_provision_head + separator_autopop + separator_provision_tail\n\n return(separator_provision)\n\n\n########################################################################################################\n########################################################################################################\n\n# argument parsing\nparser = argparse.ArgumentParser(description = \"Options for network_config\")\nparser.add_argument(\"-v\", \"--verbose\", help = \"enables verbose output\", action=\"store_true\")\nparser.add_argument(\"-o\", \"--output\", help = \"writes output to file\", action=\"store\", dest=\"output\")\nparser.add_argument(\"-s\", \"--silence\", help = \"silences console output\", action=\"store_true\")\nparser.add_argument(\"-u\", \"--username\", help = \"sets username\", action=\"store\", dest=\"username_inline\")\nparser.add_argument(\"-p\", \"--password\", help = \"sets password\", action=\"store\", dest=\"password_inline\")\nparser.add_argument(\"-c\", \"--command\", help = \"sets command\", action=\"store\", dest=\"command_inline\")\nparser.add_argument(\"-e\", \"--edit\", help = \"sets edit mode, use at own risk\", action=\"store_true\")\nparser.add_argument(\"-d\", \"--destination\", help = \"sets destination hostlist(s), separate multiple lists with ',' e.g. <list1>,<list2>\", action=\"store\", dest=\"destination_inline\")\nparser.add_argument(\"-l\", \"--list\", help = \"list all available destination hostlists\", action=\"store_true\")\nparser.add_argument(\"-a\", \"--autodetect\", help = \"autodetects device type of specified host\", action=\"store\", dest=\"autodetect\")\n\nargs = parser.parse_args()\n\nif args.list:\n print(\"Configured hostlists:\\n\")\n for key in hostlist_conf():\n print(key + \":\\n\" + str(hostlist_conf()[key]) + \"\\n\")\n exit(\"\\n\")\n\n\n# directory management\ndate = str(date.today())\n#last_date = date.today() - timedelta(days=1)\n#root_dir = \"/usr/home/astutebackups/backups/network_backups/\"\n#save_dir = os.path.join(root_dir, str(date))\n#log_dir = (root_dir + \"network_backups_\" + str(date) + \".log\")\n#last_log_dir = (root_dir + \"network_backups_\" + str(last_date) + \".log\")\n\n#if not os.path.exists(save_dir):\n# os.mkdir(save_dir)\n\n\nif args.output is None:\n if args.silence:\n filename = (\"netconf_output_\" + date + \"_0.txt\")\n i=0\n while os.path.isfile(filename):\n filename = (\"netconf_output_\" + date + \"_\" + str(i) + \".txt\")\n i+=1\n elif args.silence is False:\n filename = args.output\nelif args.output is not None:\n filename = args.output\n\n\n# logging setup\n# create logger with 'network_backups'\nlogger = logging.getLogger('network_backups')\nlogger.setLevel(logging.DEBUG)\n\n# create file handler which logs even debug messages\n#fh = logging.FileHandler(log_dir)\n#fh.setLevel(logging.DEBUG)\n\n# create console handler with it's own log level\nch = logging.StreamHandler()\nch.setLevel(logging.WARNING)\n\n# create formatter and add it to the handlers\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n#fh.setFormatter(formatter)\nch.setFormatter(formatter)\n\n# add the handlers to the logger\n#logger.addHandler(fh)\nlogger.addHandler(ch)\n\n# set time monitor\nstart_time = time.time()\ncurrent_time = time.strftime(\"%H:%M:%S\", time.localtime())\n\nif args.verbose:\n ch.setLevel(logging.DEBUG)\n logger.info(\"Verbose mode enabled.\")\n loader_visual = False\nelse:\n ch.setLevel(logging.WARNING)\n loader_visual = True\n\n#logger.info(\"Backup directory set as: \" + save_dir)\n#logger.info(\"Log file(s) can be found at \" + log_dir)\n\n\n# credentials acquisition\nif args.username_inline is not None:\n username = args.username_inline\nelse:\n username = input(\"Enter username: \")\n\nif args.password_inline is not None:\n password = args.password_inline\nelse:\n password = getpass.getpass(prompt=\"Enter password: \", stream=None)\n\n\n# autodetector\nif args.autodetect:\n host = args.autodetect\n print(\"Autodetecting device type for host \" + host + \"...\\n\")\n device = {\n \"device_type\": \"autodetect\",\n \"host\": host,\n \"username\": username,\n \"password\": password,\n \"global_delay_factor\": 2,\n }\n\n try:\n guesser = netmiko.SSHDetect(**device)\n except (NetMikoTimeoutException):\n print(\"Timed out while attempting connection to \" + host + \".\")\n logger.warning(\"Timed out connecting to \" + host + \".\")\n exit()\n except (NetmikoAuthenticationException):\n print(\"Failed to authenticate, please check username/password and try again.\")\n logger.warning(\"Failed to authenticate, incorrect login credentials.\")\n exit()\n\n guesser = netmiko.SSHDetect(**device)\n best_match = guesser.autodetect()\n guesses = guesser.potential_matches\n if best_match is not None:\n print(\"Best match: \" + best_match + \"\\nAll potential matches: \", end='') # Name of the best device_type to use further\n for match in guesses:\n print(match + \" \") # Dictionary of the whole matching result\n else:\n print(\"Failed to autodetect device type for host.\")\n\n exit()\n\n\n# command input\nif args.command_inline is not None:\n command = args.command_inline\n if args.edit:\n edit_mode = True\n elif args.edit == False:\n edit_mode = False\nelse:\n command = input(\"Enter command or type 'list' for preset options, or 'edit' to make config change: \")\n\n if command == \"list\":\n command_options = [\n {\n 'type': 'list',\n 'name': 'command_options',\n 'message': 'Select a command with [enter]',\n 'choices': command_conf(),\n },\n ]\n\n command_dict = prompt(command_options)\n command = command_dict.get(\"command_options\")\n edit_mode = False\n\n logger.info(\"Command has been set as: \" + command)\n elif command == \"edit\":\n edit_mode = True\n command = input(\"Enter edit command: \")\n\n logger.info(\"Edit command has been set as: \" + command)\n else:\n edit_mode = False\n\n# hostlist compiling and dynamic list creation\nhostlist_active = hostlist_conf()\n\nif args.destination_inline is None:\n separator_autopop = host_separator(hostlist_active)\n\n exec(separator_autopop)\n\n hostlist_selected = prompt(hostlist_select)\n hostlist_undict = hostlist_selected[\"hostlist_options\"]\nelse:\n hostlist_undict = list(args.destination_inline.split(\",\"))\n\nhostlist_complete = host_compile(hostlist_undict, hostlist_active)\n\nlogger.info(\"Outputting to selected hostlist(s)...\")\nlogger.info(hostlist_undict)\nlogger.info(\"Outputting to selected host(s)...\")\nlogger.info(hostlist_complete)\n\n\n# initiate progress bar\nif args.silence:\n bar = ShadyBar('Processing', max=(len(hostlist_complete)))\n\nfor host in hostlist_complete:\n\n # for key in hostlist_active:\n # if host in hostlist_active[key]:\n # device_type = \"juniper_junos\"\n\n if host == 'juniper':\n device_type = \"juniper_junos\"\n print(\"The device type has been set to: \" + device_type)\n continue\n if host == 'cisco':\n device_type = \"cisco_ios\"\n print(\"The device type has been set to: \" + device_type)\n continue\n if host == 'linux':\n device_type = \"linux\"\n print(\"The device type has been set to: \" + device_type)\n continue\n\n device = {\n \"device_type\": \"autodetect\",\n \"host\": host,\n \"username\": username,\n \"password\": password,\n \"global_delay_factor\": 2,\n }\n\n # guesser = netmiko.SSHDetect(**device)\n # best_match = guesser.autodetect()\n # print(best_match) # Name of the best device_type to use further\n # print(guesser.potential_matches) # Dictionary of the whole matching result\n # exit()\n #\n # device[\"device_type\"] = best_match\n device[\"device_type\"] = device_type\n try:\n net_connect = netmiko.Netmiko(**device)\n except (NetMikoTimeoutException):\n print(\"\\n-------=====================-------\\n\")\n print (\"Timed out while attempting connection to \" + host + \", moving to next host...\")\n logger.warning(\"Timed out connecting to \" + host + \".\")\n except (NetmikoAuthenticationException):\n print(\"\\n-------=====================-------\\n\")\n print(\"Failed to authenticate, please check username/password and try again.\")\n logger.warning(\"Failed to authenticate, incorrect login credentials.\")\n exit()\n\n if edit_mode is False:\n output = net_connect.send_command(command)\n elif edit_mode is True:\n output = net_connect.send_config_set(command)\n output = net_connect.send_config_set(\"commit and-quit\")\n\n if args.silence:\n bar.next()\n else:\n print(\"\\n-------=====================-------\\n\")\n\n print(net_connect.find_prompt())\n print(\"> \" + command)\n print(output)\n\n if filename is not None:\n with open(filename, \"a\") as f:\n print(file=f)\n print(\"-------=====================-------\", file=f)\n print(file=f)\n print(net_connect.find_prompt(), file=f)\n print(\"> \" + command, file=f)\n print(output, file=f)\n net_connect.disconnect()\n\nif filename is not None:\n logger.info(\"Output written to \" + filename)\n\nif args.silence:\n bar.finish()\n\n# calculate and output run time\nlogger.info(\"Task completed in %.2f minutes!\" % ((time.time() - start_time)/60))"
},
{
"alpha_fraction": 0.5971676111221313,
"alphanum_fraction": 0.5987411737442017,
"avg_line_length": 28.581396102905273,
"blob_id": "7a7a1cf4241fd0325089b95e7213a72ce727ecc8",
"content_id": "c64bd272a8a664eda862a60f7862310852b07d12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1271,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 43,
"path": "/netdevr_functions.py",
"repo_name": "liamtbb/netdevr",
"src_encoding": "UTF-8",
"text": "def host_compile(hostlist_undict, hostlist_active):\n\n hostlist_complete = []\n\n for host in hostlist_active:\n if any(s in hostlist_undict for s in (str(host), 'ALL HOSTS')):\n key_list = list(hostlist_active[str(host)])\n hostlist_complete = hostlist_complete + key_list\n\n # print(hostlist_complete)\n # exit()\n\n return hostlist_complete\n\n\ndef host_separator(hostlist_active):\n\n separator_autopop = \"\"\n\n for host in hostlist_active:\n separator_autopop = separator_autopop + \",\\n\\t\\t\\t{\\n\\t\\t\\t'name': '\" + host + \"'\\n\\t\\t\\t}\"\n\n separator_autopop = separator_autopop + \",\\n\\t\\t\\t{\\n\\t\\t\\t'name': '\" + \"ALL HOSTS\" + \"'\\n\\t\\t\\t}\"\n\n separator_provision_head = '''\nhostlist_select = [\n {\n 'type': 'checkbox',\n 'name': 'hostlist_options',\n 'message': \"Select 1 or more hostlists with [space], continue with [enter]\",\n 'choices': [\n Separator('= Vancouver =')'''\n\n separator_provision_tail = '''\n ],\n 'validate': lambda answer: 'You must choose at least one hostlist.' \\\\\n if len(answer) == 0 else True\n }\n]'''\n\n separator_provision = separator_provision_head + separator_autopop + separator_provision_tail\n\n return(separator_provision)"
},
{
"alpha_fraction": 0.5150827169418335,
"alphanum_fraction": 0.5935776829719543,
"avg_line_length": 70.72093200683594,
"blob_id": "82dc90c233b7f9274ed20fad9cb18e17e56fe6e3",
"content_id": "93f7614fdd45beede78c24adb177ec5538c63925",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3083,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 43,
"path": "/netdevr_config.py",
"repo_name": "liamtbb/netdevr",
"src_encoding": "UTF-8",
"text": "# Configure hostlists:\ndef hostlist_conf():\n\n hostlist_dict = {}\n\n # hostlist_dict[\"van-dv1\"] = ['van-dv1-dis-1a.ahsv.net', 'van-dv1-dis-1b.ahsv.net', 'van-dv1-dis-2a.ahsv.net',\n # 'van-dv1-dis-2b.ahsv.net', 'van-dv1-dis-3b.ahsv.net', 'van-dv1-ge2-1a.ahsv.net',\n # 'van-dv1-ge2-3a.ahsv.net', 'van-dv1-ge2-5a.ahsv.net', 'van-dv1-ge2-5b.ahsv.net',\n # 'van-dv1-ge2-7a.ahsv.net', 'van-dv1-ge2-8a.ahsv.net', 'van-dv1-ge2-9a.ahsv.net']\n # hostlist_dict[\"van-hc21n\"] = ['van-hc21n-dis-1a.ahsv.net', 'van-hc21n-dis-1b.ahsv.net', 'van-hc21n-ge2-1a.ahsv.net',\n # 'van-hc21n-ge2-2a.ahsv.net']\n # hostlist_dict[\"van-hc6b\"] = ['van-hc6b-dis-1a.ahsv.net', 'van-hc6b-dis-2a.ahsv.net']\n # hostlist_dict[\"van-wf375\"] = ['van-wf375-dis-1a.ahsv.net', 'van-wf375-dis-1b.ahsv.net', 'van-wf375-ge2-1b.ahsv.net',\n # 'van-wf375-ge2-2b.ahsv.net', 'van-wf375-ge2-3a.ahsv.net']\n # hostlist_dict[\"sea-wb701\"] = ['sea-wb701-dis-1a.ahsv.net', 'sea-wb701-dis-1b.ahsv.net', 'sea-wb701-ge2-1a.ahsv.net',\n # 'sea-wb701-ge2-2a.ahsv.net', 'sea-wb701-ge2-7a.ahsv.net', 'sea-wb701-ge2-7b.ahsv.net',\n # 'sea-wb701-ge2-8a.ahsv.net', 'sea-wb701-ge2-9a.ahsv.net', 'sea-wb701-ge2-10a.ahsv.net',\n # 'sea-wb701-ge2priv-10a.ahsv.net', 'sea-wb701-ge2-13a.ahsv.net', 'sea-wb701-ge2priv-13a.ahsv.net']\n # hostlist_dict[\"sea-wb912\"] = ['sea-wb912-ge2-1a.ahsv.net', 'sea-wb912-ge2priv-1a.ahsv.net']\n # hostlist_dict[\"tor-fr802\"] = ['tor-fr802-dis-1a.ahsv.net', 'tor-fr802-dis-1b.ahsv.net', 'tor-fr802-ge2-1a.ahsv.net',\n # 'tor-fr802-ge2-2a.ahsv.net']\n # hostlist_dict[\"mia-89p\"] = ['mia-89p-dis-1a.ahsv.net', 'mia-89p-dis-1b.ahsv.net', 'mia-89p-ge2-1a.ahsv.net',\n # 'mia-89p-ge2-2a.ahsv.net']\n # hostlist_dict[\"la-dr425\"] = ['la-dr425-dis-1a.ahsv.net', 'la-dr425-dis-1b.ahsv.net', 'la-dr425-ge2-1a.ahsv.net',\n # 'la-dr425-ge2-1b.ahsv.net']\n # hostlist_dict[\"van-cor\"] = ['van-pav-cor-1.ahsv.net', 'van-pav-cor-2.ahsv.net', 'van-val-cor-1.ahsv.net']\n # hostlist_dict[\"sea-cor\"] = ['sea-pav-cor-1.ahsv.net', 'sea-pav-cor-2.ahsv.net', 'sea-prm-ed3-1.ahsv.net',\n # 'sea-val-ed3-1.ahsv.net']\n # hostlist_dict[\"tor-cor\"] = ['tor-pav-cor-1.ahsv.net', 'tor-pav-cor-2.ahsv.net', 'tor-val-vmx-2.ahsv.net']\n hostlist_dict[\"misc\"] = ['juniper', 'cgy-arr-dis-1a.ahsv.net', 'van-wf375-ge2ipay1.ahsv.net', 'van-wg401-ge2-1a.ahsv.net',\n 'sea-infocube-vmx.ahsv.net', 'sea-infocube-sw1.ahsv.net', 'sea-bluespan-vmx.ahsv.net']\n hostlist_dict[\"hostlist_dynamic_test\"] = ['juniper', 'van-test-dis-1a.ahsv.net', 'linux', 'van-dv1-mon-1.ahsv.net']\n\n return hostlist_dict\n\n\n# Configure common commands:\ndef command_conf():\n\n commands = ['show interfaces descriptions', 'show interfaces terse', 'show bgp summary', 'show spanning-tree interface',\n 'show arp no-resolve', 'show config', 'show system uptime']\n\n return commands"
},
{
"alpha_fraction": 0.647391140460968,
"alphanum_fraction": 0.6540378928184509,
"avg_line_length": 31.673913955688477,
"blob_id": "9d1f797fa9feee739b181a0dba60cd3c5ec3b9bd",
"content_id": "6d47d1d95f02f9d6a59bf4c01c81c7809e6197a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3009,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 92,
"path": "/README.md",
"repo_name": "liamtbb/netdevr",
"src_encoding": "UTF-8",
"text": "# netdevr\nAn expanded version of netbackup with improved functionality for batch commands and backups.\n\n---\n\n### Install\n```\nnetDevr requires Python3.5+\n```\n- Download and extract netDevr package to local directory.\n\n- Install pip3 dependencies in Powershell: `pip3 install progress pyinquirer pyinstaller keyring netmiko` \n\n- Navigate to netDevr directory and execute with `python netdevr`\n\n---\n#### Help [netdevr -h]\n\nusage: netdevr.py [-h] [-v] [-o OUTPUT] [-s] [-u USERNAME_INLINE] [-p PASSWORD_INLINE] [-c COMMAND_INLINE] [-e]\n [-d DESTINATION_INLINE] [-l] [-a AUTODETECT]\n\nOptions for network_config\n\noptional arguments:\n **-h, --help** show this help message and exit \n **-v, --verbose** enables verbose output \n **-o OUTPUT, --output OUTPUT**\n writes output to file \n **-s, --silence** silences console output \n **-u USERNAME_INLINE, --username USERNAME_INLINE**\n sets username \n **-p PASSWORD_INLINE, --password PASSWORD_INLINE**\n sets password \n **-c COMMAND_INLINE, --command COMMAND_INLINE**\n sets command \n **-e, --edit** sets edit mode, use at own risk \n **-d DESTINATION_INLINE, --destination DESTINATION_INLINE**\n sets destination hostlist(s), separate multiple lists with ',' \n **-l, --list** list all available destination hostlists \n **-a AUTODETECT, --autodetect AUTODETECT**\n autodetects device type of specified host \n\n\n\n#### Supported platforms:\na10: A10SSH, \naccedian: AccedianSSH, \nalcatel_aos: AlcatelAosSSH, \nalcatel_sros: AlcatelSrosSSH, \narista_eos: AristaSSH, \naruba_os: ArubaSSH, \navaya_ers: AvayaErsSSH, \navaya_vsp: AvayaVspSSH, \nbrocade_fastiron: BrocadeFastironSSH, \nbrocade_netiron: BrocadeNetironSSH, \nbrocade_nos: BrocadeNosSSH, \nbrocade_vdx: BrocadeNosSSH, \nbrocade_vyos: VyOSSSH, \ncheckpoint_gaia: CheckPointGaiaSSH, \nciena_saos: CienaSaosSSH, \ncisco_asa: CiscoAsaSSH, \ncisco_ios: CiscoIosBase, \ncisco_nxos: CiscoNxosSSH, \ncisco_s300: CiscoS300SSH, \ncisco_tp: CiscoTpTcCeSSH, \ncisco_wlc: CiscoWlcSSH, \ncisco_xe: CiscoIosBase, \ncisco_xr: CiscoXrSSH, \ndell_force10: DellForce10SSH, \ndell_powerconnect: DellPowerConnectSSH, \neltex: EltexSSH, \nenterasys: EnterasysSSH, \nextreme: ExtremeSSH, \nextreme_wing: ExtremeWingSSH, \nf5_ltm: F5LtmSSH, \nfortinet: FortinetSSH, \ngeneric_termserver: TerminalServerSSH, \nhp_comware: HPComwareSSH, \nhp_procurve: HPProcurveSSH, \nhuawei: HuaweiSSH, \njuniper: JuniperSSH, \njuniper_junos: JuniperSSH, \nlinux: LinuxSSH, \nmellanox_ssh: MellanoxSSH, \nmrv_optiswitch: MrvOptiswitchSSH, \novs_linux: OvsLinuxSSH, \npaloalto_panos: PaloAltoPanosSSH, \npluribus: PluribusSSH, \nquanta_mesh: QuantaMeshSSH, \nubiquiti_edge: UbiquitiEdgeSSH, \nvyatta_vyos: VyOSSSH, \nvyos: VyOSSSH \n"
}
] | 4 |
bpiotr/zipped-timetable-archiver | https://github.com/bpiotr/zipped-timetable-archiver | 7e44a748de74058d2dd1d04c3c74b0644a9e13a0 | 3e51158a31dcb1db7c58ea59f325fbf888f61fec | 8c796872bb06621166d842167e53a1ab3bbc4ad1 | refs/heads/master | 2020-12-30T09:27:11.098600 | 2018-01-01T12:28:15 | 2018-01-01T12:28:15 | 100,417,365 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6509914994239807,
"alphanum_fraction": 0.6542776226997375,
"avg_line_length": 34.86991882324219,
"blob_id": "29ea68db84567620ee15638d451b7ab0ec84bf07",
"content_id": "a0b7e4798ca2d2d192d8bbe5f5832e83f8de1630",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8826,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 246,
"path": "/mpk_archiver.py",
"repo_name": "bpiotr/zipped-timetable-archiver",
"src_encoding": "UTF-8",
"text": "import datetime\nimport hashlib\nimport logging\nimport pathlib\nimport sched\nimport tempfile\nimport time\n\nimport ckanapi\n\n\ndef configure_logging():\n l = logging.getLogger(\"mpk_archiver\")\n l.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n l.addHandler(ch)\n return l\n\n\nlogger = configure_logging()\n\nARCHIVER_SSH_KEY = \"ARCHIVER_SSH_KEY\"\n\ntry:\n import urllib.request as request\nexcept ImportError:\n import urllib as request\nfrom argparse import ArgumentParser\nimport zipfile\n\nimport os\nfrom collections import namedtuple\nfrom dateutil.parser import parse as parse_date_string\nfrom git import Repo\n\nUpdateLogEntry = namedtuple(\"UpdateLogEntry\", [\"registered\", \"checksum\", \"commit\"])\n\nSCRIPT_PATH = os.path.realpath(__file__)\nSCRIPT_DIR = os.path.dirname(SCRIPT_PATH)\nKEY_PATH = os.path.join(SCRIPT_DIR, \"ssh_key\")\nSSH_WRAPPER_PATH = os.path.join(SCRIPT_DIR, \"ssh_wrapper.sh\")\n\n\nclass PeriodicScheduler(object):\n def __init__(self):\n self.scheduler = sched.scheduler(time.time, time.sleep)\n\n def setup(self, interval, action, actionargs=()):\n try:\n action(*actionargs)\n finally:\n self.scheduler.enter(interval, 1, self.setup,\n (interval, action, actionargs))\n\n def run(self):\n self.scheduler.run()\n\n\ndef main(local_git_path, remote_git_url, ckan_url, package_name):\n logger.info(\"Updating local repository at %s from %s.\", local_git_path, remote_git_url)\n local_repo = update_local_git_repo(local_git_path, remote_git_url)\n logger.info(\"Done.\")\n\n logger.info(\"Looking for newest log entry...\")\n latest_log_entry = get_newest_log_entry(local_git_path)\n logger.info(\"Done: '%s'.\", latest_log_entry)\n\n logger.info(\"Getting package url from CKAN...\")\n ckan = ckanapi.RemoteCKAN(ckan_url)\n package_info = ckan.call_action('package_show', {\"id\": package_name})\n logger.info(\"Done: %s\", package_info)\n\n timetable_url = package_info['resources'][0]['url']\n logger.info(\"Downloading %s...\", timetable_url)\n temp_file_path, http_message = request.urlretrieve(timetable_url)\n logger.info(\"Done: %s, HTTP message: %s.\", temp_file_path, http_message)\n\n logger.info(\"Calculating checksum of the downloaded file...\")\n new_checksum = calculate_checksum(temp_file_path)\n logger.info(\"Done: '%s'.\", new_checksum)\n\n if not latest_log_entry or new_checksum != latest_log_entry.checksum:\n logger.info(\"NEW TIMETABLE DETECTED. Checksum of the downloaded data is different than the newest log entry.\")\n logger.info(\"Extracting downloaded archive...\")\n files_extracted = extract_new_file(temp_file_path, local_git_path)\n logger.info(\"Done: %s\", files_extracted)\n\n current_utc_time = datetime.datetime.utcnow()\n local_repo.index.add(files_extracted)\n\n for now_missing_file in pathlib.Path(local_git_dir).rglob(\"*.txt\").filter(lambda p: str(p) not in files_extracted):\n local_repo.index.remove(str(now_missing_file))\n\n logger.info(\"Committing extracted files...\")\n new_files_commit = local_repo.index.commit(\"Nowy rozkład: {}\".format(current_utc_time))\n logger.info(\"Done: %s.\", new_files_commit)\n\n logger.info(\"Inserting and committing new log entry...\")\n new_log_entry = UpdateLogEntry(current_utc_time, new_checksum, new_files_commit.hexsha)\n insert_log_entry_in_table(local_git_path, new_log_entry)\n local_repo.index.add([os.path.join(local_git_path, \"README.md\")])\n log_modification_commit = local_repo.index.commit(\"Nowy wpis w logu {}\".format(current_utc_time))\n logger.info(\"Done: %s.\", log_modification_commit)\n\n logger.info(\"Pushing changes to %s...\", remote_git_url)\n local_repo.remote().push()\n logger.info(\"Done\")\n else:\n logger.info(\"Checksum of the downloaded data is the same as the newest log entry. No action made.\")\n\n\ndef _read_ssh_key_from_env_and_save():\n ssh_key = os.getenv(ARCHIVER_SSH_KEY)\n if not ssh_key:\n logger.info(\"'ARCHIVER_SSH_KEY; is not specified. Using user's default SSH config.\")\n return\n logger.info(\"Saving $ARCHIVER_SSH_KEY to {}\".format(KEY_PATH))\n\n try:\n if os.path.exists(KEY_PATH):\n os.chmod(KEY_PATH, 0o600)\n with open(KEY_PATH, \"w\") as f:\n f.write(ssh_key)\n finally:\n os.chmod(KEY_PATH, 0o400)\n\n\ndef _parse_cli_args():\n arg_parser = ArgumentParser()\n arg_parser.add_argument(\"-url\", \"--remote_git_url\", help=\"URL to remote git repo.\")\n arg_parser.add_argument(\"-d\", \"--delay\", help=\"Interval of waiting between checks.\", type=int)\n arg_parser.add_argument(\"ckan_url\", help=\"URL to CKAN API.\")\n arg_parser.add_argument(\"package_name\", help=\"Name of the package in CKAN\")\n\n args = arg_parser.parse_args()\n return args.remote_git_url, args.ckan_url, args.package_name, args.delay\n\n\ndef cleanup(temp_file):\n if temp_file and os.path.exists(temp_file):\n os.chmod(temp_file, 0o500)\n os.remove(temp_file)\n request.urlcleanup()\n\n\ndef calculate_checksum(file_path):\n def hash_bytestr_iter(bytesiter, hasher):\n for block in bytesiter:\n hasher.update(block)\n return hasher.hexdigest()\n\n def file_as_blockiter(file_path, blocksize=65536):\n with open(file_path, \"rb\") as afile:\n block = afile.read(blocksize)\n while len(block) > 0:\n yield block\n block = afile.read(blocksize)\n\n return hash_bytestr_iter(file_as_blockiter(file_path), hashlib.sha256())\n\n\ndef extract_new_file(path_to_zip, destination_dir):\n with zipfile.ZipFile(path_to_zip, 'r') as zip_ref:\n all_members = zip_ref.infolist()\n non_dir_members = filter(lambda info: not info.filename.endswith(\"/\"), all_members)\n files_in_zip = map(lambda info: os.path.join(destination_dir, info.filename), non_dir_members)\n zip_ref.extractall(destination_dir)\n return list(files_in_zip)\n\n\ndef get_newest_log_entry(local_git_path):\n log_file_content = _get_all_logfile_contents(local_git_path)\n\n log_table_lines = filter(lambda s: s.startswith(\"|\"), log_file_content)\n log_table_lines = list(map(lambda s: s.strip(\"|\").split(\"|\"), list(log_table_lines)[2:]))\n\n log_entries = []\n for row in log_table_lines:\n registered = parse_date_string(row[0].strip())\n checksum = row[1].strip()\n commit_hash = row[2].strip()\n log_entries.append(UpdateLogEntry(registered, checksum, commit_hash))\n\n return max(log_entries, key=lambda e: e.registered) if log_entries else None\n\n\ndef insert_log_entry_in_table(local_git_path, new_log_entry):\n log_file_content = _get_all_logfile_contents(local_git_path)\n table_at = 0\n for i in range(len(log_file_content)):\n if log_file_content[i].startswith(\"|\"):\n table_at = i\n break\n log_file_content.insert(table_at + 2, log_entry_to_text(new_log_entry))\n\n with open(os.path.join(local_git_path, \"README.md\"), \"w\") as file:\n for line in log_file_content:\n file.write(line)\n\n\ndef log_entry_to_text(log_entry: UpdateLogEntry):\n return \"| {} | {} | {} |\\n\".format(log_entry.registered, log_entry.checksum, log_entry.commit)\n\n\ndef _get_all_logfile_contents(local_git_path):\n log_file_name = os.path.join(local_git_path, \"README.md\")\n with open(log_file_name) as file:\n log_file_content = file.readlines()\n return log_file_content\n\n\ndef update_local_git_repo(local_repo_path, remote_repo_url=None):\n env = {\"GIT_SSH\": SSH_WRAPPER_PATH}\n if not os.path.exists(os.path.join(local_repo_path, \".git\")):\n if not remote_repo_url:\n raise Exception(\"You must pass remote GIT URL if the local repo does not exist.\")\n logger.info(\"Cloning repo from %s to %s ...\", remote_git_url, local_repo_path)\n local_repo = Repo.clone_from(remote_repo_url, local_repo_path, env=env)\n else:\n local_repo = Repo(local_repo_path)\n\n local_repo.git.update_environment(**env)\n origin = local_repo.remote()\n origin.pull()\n return local_repo\n\n\nif __name__ == '__main__':\n _read_ssh_key_from_env_and_save()\n\n remote_git_url, ckan_url, package_name, delay = _parse_cli_args()\n local_git_dir = tempfile.TemporaryDirectory(\"_mpk\")\n\n try:\n s = PeriodicScheduler()\n s.setup(delay, main, (local_git_dir.name, remote_git_url, ckan_url, package_name))\n s.run()\n finally:\n logger.info(\"Cleaning %s\", KEY_PATH)\n cleanup(KEY_PATH)\n logger.info(\"Cleaning %s\", local_git_dir.name)\n local_git_dir.cleanup()\n logger.info(\"Done.\")\n\n"
},
{
"alpha_fraction": 0.7455268502235413,
"alphanum_fraction": 0.7554671764373779,
"avg_line_length": 28.647058486938477,
"blob_id": "842a713a8e18e8c87a42d572960a8c55db3c2459",
"content_id": "e5e3763e0d9fb6f95bea1260966575d47cec0ac6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 503,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 17,
"path": "/Dockerfile",
"repo_name": "bpiotr/zipped-timetable-archiver",
"src_encoding": "UTF-8",
"text": "FROM python:3.6\n\nRUN apt-get update && apt-get install -y git\n\nCOPY requirements.txt /workspace/requirements.txt\n\nRUN pip install -r /workspace/requirements.txt\n\nRUN chown -R nobody /workspace\n\nUSER nobody\n\nCOPY mpk_archiver.py /workspace/mpk_archiver.py\nCOPY ssh_wrapper.sh /workspace/ssh_wrapper.sh\n\nENTRYPOINT [\"python\", \"/workspace/mpk_archiver.py\"]\nCMD [\"-d\", \"600\", \"-url\", \"[email protected]:bpiotr/rozklad-mpk-wroclaw.git\", \"https://www.wroclaw.pl/open-data\", \"rozkladjazdytransportupublicznegoplik_data\"]"
},
{
"alpha_fraction": 0.7891891598701477,
"alphanum_fraction": 0.7891891598701477,
"avg_line_length": 61,
"blob_id": "9df116be060b5bb821e371b822ffa90b80e273e6",
"content_id": "87ed834bc55fd14e077806529786045fc0e536c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 3,
"path": "/app.sh",
"repo_name": "bpiotr/zipped-timetable-archiver",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\npython mpk_archiver.py -g /tmp/timetable -url [email protected]:bpiotr/rozklad-mpk-wroclaw.git http://www.wroclaw.pl/open-data/opendata/rozklady/OtwartyWroclaw_rozklad_jazdy_GTFS.zip"
},
{
"alpha_fraction": 0.8837209343910217,
"alphanum_fraction": 0.8837209343910217,
"avg_line_length": 9.75,
"blob_id": "ef032b8bb20e0094ce4496cdbb59163afc2c2ced",
"content_id": "e98d48a2dd67b3e742feb7fb8111826c4adba7e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 43,
"license_type": "no_license",
"max_line_length": 15,
"num_lines": 4,
"path": "/requirements.txt",
"repo_name": "bpiotr/zipped-timetable-archiver",
"src_encoding": "UTF-8",
"text": "python-dateutil\nGitPython\nrequests\nckanapi\n"
}
] | 4 |
qaz734913414/MaskInsightface | https://github.com/qaz734913414/MaskInsightface | 353546589c42e0aa4e4510f3b4465ef1d4d6f343 | 42e603a28ddb2ed5f3705231c89a1f8d2f3e9e90 | 1a51a3a7624d7018dacfc47f84223be79fc49b0f | refs/heads/master | 2020-07-08T19:03:38.640703 | 2020-01-13T02:10:49 | 2020-01-13T02:10:49 | 203,751,119 | 0 | 0 | Apache-2.0 | 2019-08-22T08:39:26 | 2019-09-29T07:58:04 | 2020-01-13T02:10:50 | Python | [
{
"alpha_fraction": 0.8035714030265808,
"alphanum_fraction": 0.8035714030265808,
"avg_line_length": 26.75,
"blob_id": "5cb999e3ed8ee7bf2b761147c4b0390aab070eb7",
"content_id": "348051b8ccc07728684fa1745c54cbc698fe94d9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 126,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 4,
"path": "/SSH/README.md",
"repo_name": "qaz734913414/MaskInsightface",
"src_encoding": "UTF-8",
"text": "SSH, single stage face detector\n\n预训练模型参见\nhttps://github.com/bleakie/mxnet-ssh-face-detection/tree/master/model\n\n"
},
{
"alpha_fraction": 0.2936953604221344,
"alphanum_fraction": 0.5561895966529846,
"avg_line_length": 52.004878997802734,
"blob_id": "0cd67b729bde47df65f1fb55c9e3a63dcac99e9b",
"content_id": "1aa23af79ba8b81c438a27c247f37677b1792992",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10937,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 205,
"path": "/face_align_util.py",
"repo_name": "qaz734913414/MaskInsightface",
"src_encoding": "UTF-8",
"text": "import os\nimport cv2\nimport numpy as np\nfrom skimage import transform as trans\n\nclass ARC_FACE:\n def __init__(self, image_size=112):\n arcface_src = np.array([\n [38.2946, 51.6963],\n [73.5318, 51.5014],\n [56.0252, 71.7366],\n [41.5493, 92.3655],\n [70.7299, 92.2041]], dtype=np.float32)\n self.arcface_src = np.expand_dims(arcface_src, axis=0)\n self.image_size = image_size\n\n # lmk is prediction; src is template\n def estimate_norm(self, lmk):\n assert lmk.shape == (5, 2)\n tform = trans.SimilarityTransform()\n lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1)\n min_M = []\n min_index = []\n min_error = float('inf')\n src = self.arcface_src\n\n for i in np.arange(src.shape[0]):\n tform.estimate(lmk, src[i])\n M = tform.params[0:2, :]\n results = np.dot(M, lmk_tran.T)\n results = results.T\n error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2, axis=1)))\n # print(error)\n if error < min_error:\n min_error = error\n min_M = M\n min_index = i\n return min_M, min_index\n\n def norm_crop(self, img, landmark):\n M, pose_index = self.estimate_norm(landmark)\n warped = cv2.warpAffine(img, M, (self.image_size, self.image_size), borderValue=0.0)\n return warped\n\n\nclass DLIB_FACE:\n def __init__(self, image_size=112):\n self.image_size = image_size\n TEMPLATE = np.float32([\n (0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),\n (0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),\n (0.168687863544, 0.800341263616), (0.239789390707, 0.895732504778),\n (0.325662452515, 0.977068762493), (0.422318282013, 1.04329000149),\n (0.531777802068, 1.06080371126), (0.641296298053, 1.03981924107),\n (0.738105872266, 0.972268833998), (0.824444363295, 0.889624082279),\n (0.894792677532, 0.792494155836), (0.939395486253, 0.681546643421),\n (0.96111933829, 0.562238253072), (0.970579841181, 0.441758925744),\n (0.971193274221, 0.322118743967), (0.163846223133, 0.249151738053),\n (0.21780354657, 0.204255863861), (0.291299351124, 0.192367318323),\n (0.367460241458, 0.203582210627), (0.4392945113, 0.233135599851),\n (0.586445962425, 0.228141644834), (0.660152671635, 0.195923841854),\n (0.737466449096, 0.182360984545), (0.813236546239, 0.192828009114),\n (0.8707571886, 0.235293377042), (0.51534533827, 0.31863546193),\n (0.516221448289, 0.396200446263), (0.517118861835, 0.473797687758),\n (0.51816430343, 0.553157797772), (0.433701156035, 0.604054457668),\n (0.475501237769, 0.62076344024), (0.520712933176, 0.634268222208),\n (0.565874114041, 0.618796581487), (0.607054002672, 0.60157671656),\n (0.252418718401, 0.331052263829), (0.298663015648, 0.302646354002),\n (0.355749724218, 0.303020650651), (0.403718978315, 0.33867711083),\n (0.352507175597, 0.349987615384), (0.296791759886, 0.350478978225),\n (0.631326076346, 0.334136672344), (0.679073381078, 0.29645404267),\n (0.73597236153, 0.294721285802), (0.782865376271, 0.321305281656),\n (0.740312274764, 0.341849376713), (0.68499850091, 0.343734332172),\n (0.353167761422, 0.746189164237), (0.414587777921, 0.719053835073),\n (0.477677654595, 0.706835892494), (0.522732900812, 0.717092275768),\n (0.569832064287, 0.705414478982), (0.635195811927, 0.71565572516),\n (0.69951672331, 0.739419187253), (0.639447159575, 0.805236879972),\n (0.576410514055, 0.835436670169), (0.525398405766, 0.841706377792),\n (0.47641545769, 0.837505914975), (0.41379548902, 0.810045601727),\n (0.380084785646, 0.749979603086), (0.477955996282, 0.74513234612),\n (0.523389793327, 0.748924302636), (0.571057789237, 0.74332894691),\n (0.672409137852, 0.744177032192), (0.572539621444, 0.776609286626),\n (0.5240106503, 0.783370783245), (0.477561227414, 0.778476346951)])\n # this shape is reference from dlib implement.\n self.mean_shape_x = [0.000213256, 0.0752622, 0.18113, 0.29077, 0.393397, 0.586856, 0.689483, 0.799124,\n 0.904991, 0.98004, 0.490127, 0.490127, 0.490127, 0.490127, 0.36688, 0.426036,\n 0.490127, 0.554217, 0.613373, 0.121737, 0.187122, 0.265825, 0.334606, 0.260918,\n 0.182743, 0.645647, 0.714428, 0.793132, 0.858516, 0.79751, 0.719335, 0.254149,\n 0.340985, 0.428858, 0.490127, 0.551395, 0.639268, 0.726104, 0.642159, 0.556721,\n 0.490127, 0.423532, 0.338094, 0.290379, 0.428096, 0.490127, 0.552157, 0.689874,\n 0.553364, 0.490127, 0.42689] # 17-67\n self.mean_shape_y = [0.106454, 0.038915, 0.0187482, 0.0344891, 0.0773906, 0.0773906, 0.0344891,\n 0.0187482, 0.038915, 0.106454, 0.203352, 0.307009, 0.409805, 0.515625, 0.587326,\n 0.609345, 0.628106, 0.609345, 0.587326, 0.216423, 0.178758, 0.179852, 0.231733,\n 0.245099, 0.244077, 0.231733, 0.179852, 0.178758, 0.216423, 0.244077, 0.245099,\n 0.780233, 0.745405, 0.727388, 0.742578, 0.727388, 0.745405, 0.780233, 0.864805,\n 0.902192, 0.909281, 0.902192, 0.864805, 0.784792, 0.778746, 0.785343, 0.778746,\n 0.784792, 0.824182, 0.831803, 0.824182] # 17-67\n self.padding = 0.2 # change yourself\n # add padding\n new_template = []\n for item in TEMPLATE:\n new_item = (\n (item[0] + self.padding) / (2 * self.padding + 1),\n (item[1] + self.padding) / (2 * self.padding + 1))\n new_template.append(new_item)\n\n self.dlib_src = np.float32(new_template)\n\n def align_dlib_cpp(self, rgbImg, landmarks=None):\n '''\n @brief: 与dlib C++版本实现的裁剪对齐方法一致。\n @attention\n '''\n assert rgbImg is not None\n\n npLandmarks = np.array(landmarks)[:, :2]\n shape_x = [npLandmarks[i][0] for i in range(68)]\n shape_y = [npLandmarks[i][1] for i in range(68)]\n from_points = []\n to_points = []\n for i in range(17, 68):\n # 忽略掉低于嘴唇的部分\n if i >= 55 and i <= 59:\n continue\n # 忽略眉毛部分\n if i >= 17 and i <= 26:\n continue\n # 上下左右都padding\n new_ref_x = (self.padding + self.mean_shape_x[i - 17]) / (2 * self.padding + 1)\n new_ref_y = (self.padding + self.mean_shape_y[i - 17]) / (2 * self.padding + 1)\n\n from_points.append((shape_x[i], shape_y[i]))\n to_points.append((self.image_size * new_ref_x, self.image_size * new_ref_y))\n\n source = np.array(from_points).astype(np.int)\n target = np.array(to_points, ).astype(np.int)\n source = np.reshape(source, (1, 36, 2))\n target = np.reshape(target, (1, 36, 2))\n H = cv2.estimateRigidTransform(source, target, False)\n if H is None:\n return None\n else:\n aligned_face = cv2.warpAffine(rgbImg, H, (self.image_size, self.image_size))\n return aligned_face\n\nclass GH_FACE:\n def __init__(self, image_size=112):\n self.front_size = (318, 361)\n self.image_size = image_size\n self.canonical_vertices = np.load(os.path.join(os.path.dirname(__file__), \"canonical_vertices_male.npy\"))\n\n def align_face_gh(self, input, preds):\n # get (x,y) coordinates\n canonical_vertices = self.canonical_vertices[:, :2]\n preds = preds[:, :2]\n front_vertices = canonical_vertices # front_vertices[:,:2]\n\n # get (x,y,1) coordinates\n pts0, pts1, pts2 = canonical_vertices, preds, front_vertices\n pts0_homo = np.hstack((pts0, np.ones([pts0.shape[0], 1]))) # n x 4\n pts1_homo = np.hstack((pts1, np.ones([pts1.shape[0], 1]))) # n x 4\n pts2_homo = np.hstack((pts2, np.ones([pts2.shape[0], 1]))) # n x 4\n # get 3D transform parameters\n AM_68 = np.linalg.lstsq(pts1_homo, pts2_homo)[0].T # Affine matrix. 3 x 3\n pts1_homo_5 = np.float32([np.mean(pts1_homo[[17, 36]], axis=0), np.mean(pts1_homo[[26, 45]], axis=0),\n np.mean(pts1_homo[[30]], axis=0), np.mean(pts1_homo[[48, 60]], axis=0),\n np.mean(pts1_homo[[54, 64]], axis=0)])\n pts2_homo_5 = np.float32([np.mean(pts2_homo[[17, 36]], axis=0), np.mean(pts2_homo[[26, 45]], axis=0),\n np.mean(pts2_homo[[30]], axis=0), np.mean(pts2_homo[[48, 60]], axis=0),\n np.mean(pts2_homo[[54, 64]], axis=0)])\n AM_5 = np.linalg.lstsq(pts1_homo_5, pts2_homo_5)[0].T # Affine matrix. 3 x 3\n pts1_homo_eye = np.float32(\n [np.mean(pts1_homo[[36]], axis=0), np.mean(pts1_homo[[39]], axis=0), np.mean(pts1_homo[[8]], axis=0),\n np.mean(pts1_homo[[42]], axis=0), np.mean(pts1_homo[[45]], axis=0)])\n pts2_homo_eye = np.float32(\n [np.mean(pts2_homo[[36]], axis=0), np.mean(pts2_homo[[39]], axis=0), np.mean(pts2_homo[[8]], axis=0),\n np.mean(pts2_homo[[42]], axis=0), np.mean(pts2_homo[[45]], axis=0)])\n AM_eye = np.linalg.lstsq(pts1_homo_eye, pts2_homo_eye)[0].T # Affine matrix. 3 x 3\n # AM = np.median([AM_68,AM_5,AM_eye],axis=0)\n AM = (1.0 * AM_68 + 2.0 * AM_5 + 3.0 * AM_eye) / (1.0 + 2.0 + 3.0)\n\n # get affine transformed image\n dst = cv2.warpPerspective(input, AM, self.front_size, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)\n\n # # border landmark indices\n # x0_index_src = np.where(pts0[:, 0] == np.amin(pts0[:, 0]))[0][0]\n # x1_index_src = np.where(pts0[:, 0] == np.amax(pts0[:, 0]))[0][0]\n # y0_index_src = np.where(pts0[:, 1] == np.amin(pts0[:, 1]))[0][0]\n # y1_index_src = np.where(pts0[:, 1] == np.amax(pts0[:, 1]))[0][0]\n #\n # # (x,y) limits\n # x0 = pts0_homo[x0_index_src][0]\n # x1 = pts0_homo[x1_index_src][0]\n # y0 = pts0_homo[y0_index_src][1]\n # y1 = pts0_homo[y1_index_src][1]\n # # crop transformed image\n # x0 = max(0, int(x0))\n # x1 = min(dst.shape[1], int(x1)) + 1\n # y0 = max(0, int(y0))\n # y1 = min(dst.shape[0], int(y1)) + 1\n # dst_crop = dst[y0:y1, x0:x1, :]\n\n aligned_face = cv2.resize(dst, (self.image_size, self.image_size), cv2.INTER_AREA)\n return aligned_face"
}
] | 2 |
BerniceKUO/python | https://github.com/BerniceKUO/python | b89b783d81adb79f516d3dad13ea6dc13a424852 | 5daf391b7609d0da4483713908d33f82b1d352cb | f25345b411c522cf141b6e8a22f04185a64b9257 | refs/heads/master | 2020-03-25T01:05:18.812891 | 2019-05-28T00:48:38 | 2019-05-28T00:48:38 | 143,221,418 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6784631013870239,
"alphanum_fraction": 0.6875631809234619,
"avg_line_length": 41.08695602416992,
"blob_id": "1539c0fede4020a36d80235d14524d77db17f57c",
"content_id": "967e7979e7c03013d80df2079d1c4e170d7c22e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 995,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 23,
"path": "/SeleniumG.py",
"repo_name": "BerniceKUO/python",
"src_encoding": "UTF-8",
"text": "import time\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\ndriver = webdriver.Chrome('D:\\\\chromedriver.exe') # Optional argument, if not specified will search path.\r\ndriver.get('https://feebee.com.tw/');\r\ntime.sleep(3) # Let the user actually see something!\r\nsearch_box = driver.find_element_by_name('q')\r\nsearch_box.send_keys('50吋電視')\r\nsearch_box.submit()\r\ntime.sleep(2)\r\nfor page in range(1,10):\r\n\tdriver.get(driver.current_url+\"&page=\"+str(page))\r\n\t#print(driver.current_url)\r\n\tsoup = BeautifulSoup(driver.page_source, 'html.parser')\r\n\t#print(soup)\r\n\tfor span in soup.find_all('span',{\"class\": \"pure-u items_container\"}):\r\n\t\t\tprint(span.find('h3',{\"class\": \"large\"}).get_text())\r\n\t\t\tif span.find('span',{\"class\": \"price ellipsis xlarge\"}) is not None:\r\n\t\t\t\tprint(span.find('span',{\"class\": \"price ellipsis xlarge\"}).get_text())\r\n\t\t\telse:\r\n\t\t\t\tprint(span.find('li',{\"class\": \"price ellipsis xlarge\"}).get_text())\r\n\t # Let the user actually see something!\r\ndriver.quit()"
},
{
"alpha_fraction": 0.5300227403640747,
"alphanum_fraction": 0.5771574974060059,
"avg_line_length": 40.254573822021484,
"blob_id": "e21850ba28bdf25b7c30e1f0e64ce0a9a7882e86",
"content_id": "9b976e0764f2feff060ef039a99b09296fc04775",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 28105,
"license_type": "no_license",
"max_line_length": 264,
"num_lines": 656,
"path": "/UserConnQ.py",
"repo_name": "BerniceKUO/python",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# GUI module generated by PAGE version 4.18\r\n# in conjunction with Tcl version 8.6\r\n# Nov 27, 2018 12:10:42 PM +0800 platform: Windows NT\r\n\r\nimport os\r\nimport requests\r\nimport sys\r\nimport xlrd\r\n#import easygui\r\nimport re\r\ntry:\r\n import Tkinter as tk\r\nexcept ImportError:\r\n import tkinter as tk\r\n\r\ntry:\r\n import ttk\r\n py3 = False\r\nexcept ImportError:\r\n import tkinter.ttk as ttk\r\n py3 = True\r\n\r\nimport UserConnQ\r\n'''\r\nimport pymssql\r\nimport uuid\r\nimport _mssql\r\nimport decimal\r\ndecimal.__version__\r\n_mssql.__version__'''\r\n\r\n\r\ndef vp_start_gui():\r\n '''Starting point when module is the main routine.'''\r\n global val, w, root\r\n root = tk.Tk()\r\n root.title('味全公司');\r\n top = Toplevel1 (root)\r\n \"UserConnQ.init(root, top)\"\r\n root.mainloop()\r\n\r\nw = None\r\ndef create_Toplevel1(root, *args, **kwargs):\r\n '''Starting point when module is imported by another program.'''\r\n global w, w_win, rt\r\n rt = root\r\n w = tk.Toplevel (root)\r\n top = Toplevel1 (w)\r\n UserConnQ.init(w, top, *args, **kwargs)\r\n return (w, top)\r\n\r\ndef destroy_Toplevel1():\r\n global w\r\n w.destroy()\r\n w = None\r\n\r\n \r\nclass Toplevel1():\r\n def OpenFile(self):\r\n os.startfile(\"\\\\\\\\10.10.1.36\\\\ManagementApproach\\\\總公司暨各事業單位電話_Portal.xls\")\r\n def __init__(self, top=None):\r\n autocompleteList=[]\r\n '''conn = pymssql.connect(server=\"10.10.1.XXX\", user=\"XXXXX\", password=\"XX\", database=\"NXXa\", timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, host='', appname=None, port='22507', conn_properties=None, autocommit=False, tds_version=None)\r\n cursor = conn.cursor()\r\n cursor.execute(\"select u2.id,u2.userName,u2.mailAddress,ou2.organizationUnitName,fd.functionDefinitionName from \"+ \r\n \"OrganizationUnit as ou2 \"+ \r\n \"join Functions as f2 with (nolock) on f2.organizationUnitOID=ou2.OID and f2.isMain=1 \"+ \r\n \"join Users as u2 with (nolock) on u2.OID=f2.occupantOID \"+ \r\n \"join FunctionDefinition as fd on fd.OID=f2.definitionOID \"+\r\n \"where ou2.organizationOID='1c5b85fcc42410048f6cef01866cc71b' order by id\")\r\n row = cursor.fetchall()'''\r\n workbookN = xlrd.open_workbook(r'\\\\10.10.1.36\\ManagementApproach\\UserData.xlsx')\r\n sheet1N = workbookN.sheet_by_index(0)\r\n nrows = sheet1N.nrows\r\n ncols = sheet1N.ncols\r\n for i in range(0,nrows):\r\n \t #for j in range(0,ncols):\r\n \t autocompleteList.append(sheet1N.cell(i,0).value+'_'+sheet1N.cell(i,1).value)\r\n\r\n #for values in row:\r\n # autocompleteList.append(values[0]+'_'+values[1])\r\n \r\n \r\n _bgcolor = '#d9d9d9' # X11 color: 'gray85'\r\n _fgcolor = '#000000' # X11 color: 'black'\r\n _compcolor = '#d9d9d9' # X11 color: 'gray85'\r\n _ana1color = '#d9d9d9' # X11 color: 'gray85' \r\n _ana2color = '#d9d9d9' # X11 color: 'gray85' \r\n self.style = ttk.Style()\r\n if sys.platform == \"win32\":\r\n self.style.theme_use('winnative')\r\n self.style.configure('.',background=_bgcolor)\r\n self.style.configure('.',foreground=_fgcolor)\r\n self.style.configure('.',font=\"TkDefaultFont\")\r\n self.style.map('.',background=\r\n [('selected', _compcolor), ('active',_ana2color)])\r\n\r\n top.geometry(\"700x338+526+233\")\r\n top.title(\"味全公司\")\r\n top.configure(background=\"#d9d9d9\")\r\n top.configure(highlightbackground=\"#d9d9d9\")\r\n top.configure(highlightcolor=\"black\")\r\n\r\n self.Label1 = tk.Label(top)\r\n self.Label1.place(relx=0.414, rely=0.03, height=38, width=132)\r\n self.Label1.configure(activebackground=\"#f9f9f9\")\r\n self.Label1.configure(activeforeground=\"black\")\r\n self.Label1.configure(background=\"#d9d9d9\")\r\n self.Label1.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label1.configure(foreground=\"#000000\")\r\n self.Label1.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label1.configure(highlightcolor=\"black\")\r\n self.Label1.configure(text='''員工分機查詢''')\r\n\r\n self.Label2 = tk.Label(top)\r\n self.Label2.place(relx=0.057, rely=0.237, height=18, width=52)\r\n self.Label2.configure(activebackground=\"#f9f9f9\")\r\n self.Label2.configure(activeforeground=\"black\")\r\n self.Label2.configure(background=\"#d9d9d9\")\r\n self.Label2.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label2.configure(foreground=\"#000000\")\r\n self.Label2.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label2.configure(highlightcolor=\"black\")\r\n self.Label2.configure(text='''姓名:''')\r\n\r\n self.Label3 = tk.Label(top)\r\n self.Label3.place(relx=0.414, rely=0.237, height=18, width=42)\r\n self.Label3.configure(activebackground=\"#f9f9f9\")\r\n self.Label3.configure(activeforeground=\"black\")\r\n self.Label3.configure(background=\"#d9d9d9\")\r\n self.Label3.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label3.configure(foreground=\"#000000\")\r\n self.Label3.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label3.configure(highlightcolor=\"black\")\r\n self.Label3.configure(text='''部門:''')\r\n\r\n self.Entry2 = tk.Entry(top)\r\n self.Entry2.place(relx=0.486, rely=0.237,height=17, relwidth=0.477)\r\n self.Entry2.configure(background=\"#d9d9d9\")\r\n self.Entry2.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry2.configure(font=\"TkFixedFont\")\r\n self.Entry2.configure(foreground=\"#000000\")\r\n self.Entry2.configure(highlightbackground=\"#d9d9d9\")\r\n self.Entry2.configure(highlightcolor=\"black\")\r\n self.Entry2.configure(insertbackground=\"black\")\r\n self.Entry2.configure(selectbackground=\"#c4c4c4\")\r\n self.Entry2.configure(selectforeground=\"black\")\r\n self.Entry2.configure(width=334)\r\n\r\n self.Label4 = tk.Label(top)\r\n self.Label4.place(relx=0.4, rely=0.296, height=38, width=62)\r\n self.Label4.configure(activebackground=\"#f9f9f9\")\r\n self.Label4.configure(activeforeground=\"black\")\r\n self.Label4.configure(background=\"#d9d9d9\")\r\n self.Label4.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label4.configure(foreground=\"#000000\")\r\n self.Label4.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label4.configure(highlightcolor=\"black\")\r\n self.Label4.configure(text='''員編:''')\r\n self.Label4.configure(width=62)\r\n\r\n self.Entry3 = tk.Entry(top)\r\n self.Entry3.place(relx=0.486, rely=0.325,height=17, relwidth=0.206)\r\n self.Entry3.configure(background=\"#d9d9d9\")\r\n self.Entry3.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry3.configure(font=\"TkFixedFont\")\r\n self.Entry3.configure(foreground=\"#000000\")\r\n self.Entry3.configure(highlightbackground=\"#d9d9d9\")\r\n self.Entry3.configure(highlightcolor=\"black\")\r\n self.Entry3.configure(insertbackground=\"black\")\r\n self.Entry3.configure(selectbackground=\"#c4c4c4\")\r\n self.Entry3.configure(selectforeground=\"black\")\r\n\r\n self.TProgressbar1 = ttk.Progressbar(top)\r\n self.TProgressbar1.place(relx=0.057, rely=0.473, relwidth=0.914\r\n , relheight=0.0, height=17)\r\n self.TProgressbar1.configure(length=\"640\")\r\n\r\n #self.TButton1 = ttk.Button(top,command=self.QueryUser)\r\n #self.TButton1.place(relx=0.298, rely=0.154, height=23, width=77)\r\n #self.TButton1.configure(takefocus=\"\")\r\n #self.TButton1.configure(text='''查詢''')\r\n\r\n self.Label5 = tk.Label(top)\r\n self.Label5.place(relx=0.057, rely=0.621, height=18, width=52)\r\n self.Label5.configure(activebackground=\"#f9f9f9\")\r\n self.Label5.configure(activeforeground=\"black\")\r\n self.Label5.configure(background=\"#d9d9d9\")\r\n self.Label5.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label5.configure(foreground=\"#000000\")\r\n self.Label5.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label5.configure(highlightcolor=\"black\")\r\n self.Label5.configure(text='''分機:''')\r\n\r\n self.Entry4 = tk.Entry(top)\r\n self.Entry4.place(relx=0.143, rely=0.621,height=17, relwidth=0.206)\r\n self.Entry4.configure(background=\"#d9d9d9\")\r\n self.Entry4.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry4.configure(font=\"TkFixedFont\")\r\n self.Entry4.configure(foreground=\"#000000\")\r\n self.Entry4.configure(highlightbackground=\"#d9d9d9\")\r\n self.Entry4.configure(highlightcolor=\"black\")\r\n self.Entry4.configure(insertbackground=\"black\")\r\n self.Entry4.configure(selectbackground=\"#c4c4c4\")\r\n self.Entry4.configure(selectforeground=\"black\")\r\n\r\n self.Label6 = tk.Label(top)\r\n self.Label6.place(relx=0.414, rely=0.621, height=18, width=52)\r\n self.Label6.configure(activebackground=\"#f9f9f9\")\r\n self.Label6.configure(activeforeground=\"black\")\r\n self.Label6.configure(background=\"#d9d9d9\")\r\n self.Label6.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label6.configure(foreground=\"#000000\")\r\n self.Label6.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label6.configure(highlightcolor=\"black\")\r\n self.Label6.configure(text='''信箱:''')\r\n\r\n self.Entry5 = tk.Entry(top)\r\n self.Entry5.place(relx=0.486, rely=0.621,height=17, relwidth=0.334)\r\n self.Entry5.configure(background=\"#d9d9d9\")\r\n self.Entry5.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry5.configure(font=\"TkFixedFont\")\r\n self.Entry5.configure(foreground=\"#000000\")\r\n self.Entry5.configure(highlightbackground=\"#d9d9d9\")\r\n self.Entry5.configure(highlightcolor=\"black\")\r\n self.Entry5.configure(insertbackground=\"black\")\r\n self.Entry5.configure(selectbackground=\"#c4c4c4\")\r\n self.Entry5.configure(selectforeground=\"black\")\r\n \r\n \r\n self.Label7 = tk.Label(top)\r\n self.Label7.place(relx=0.057, rely=0.74, height=18, width=52)\r\n self.Label7.configure(activebackground=\"#f9f9f9\")\r\n self.Label7.configure(activeforeground=\"black\")\r\n self.Label7.configure(background=\"#d9d9d9\")\r\n self.Label7.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label7.configure(foreground=\"#000000\")\r\n self.Label7.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label7.configure(highlightcolor=\"black\")\r\n self.Label7.configure(text='''位置:''')\r\n\r\n\r\n\r\n self.Label8 = tk.Label(top)\r\n self.Label8.place(relx=0.7, rely=0.325, height=18, width=42)\r\n self.Label8.configure(activebackground=\"#f9f9f9\")\r\n self.Label8.configure(activeforeground=\"black\")\r\n self.Label8.configure(background=\"#d9d9d9\")\r\n self.Label8.configure(disabledforeground=\"#a3a3a3\")\r\n self.Label8.configure(foreground=\"#000000\")\r\n self.Label8.configure(highlightbackground=\"#d9d9d9\")\r\n self.Label8.configure(highlightcolor=\"black\")\r\n self.Label8.configure(text='''職稱:''')\r\n\r\n self.Entry6 = tk.Entry(top)\r\n self.Entry6.place(relx=0.757, rely=0.325,height=17, relwidth=0.206)\r\n self.Entry6.configure(background=\"#d9d9d9\")\r\n self.Entry6.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry6.configure(font=\"TkFixedFont\")\r\n self.Entry6.configure(foreground=\"#000000\")\r\n self.Entry6.configure(highlightbackground=\"#d9d9d9\")\r\n self.Entry6.configure(highlightcolor=\"black\")\r\n self.Entry6.configure(insertbackground=\"black\")\r\n self.Entry6.configure(selectbackground=\"#c4c4c4\")\r\n self.Entry6.configure(selectforeground=\"black\")\r\n\r\n\r\n self.Entry1 = tk.Entry(top)\r\n # self.entry1 = tk.Entry(top)\r\n self.Entry1.place(relx=0.129, rely=0.237,height=17, relwidth=0.206)\r\n self.Entry1.configure(background=\"white\")\r\n self.Entry1.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry1.configure(font=\"TkFixedFont\")\r\n self.Entry1.configure(foreground=\"#000000\")\r\n self.Entry1.configure(insertbackground=\"black\")\r\n \r\n # self.Label9 = tk.Label(top)\r\n # self.Label9.place(relx=0.011, rely=0.01, height=50, width=50)\r\n #self.Label8.configure(background=\"#d9d9d9\")\r\n #photo = tk.PhotoImage(file='LOGO.png')\r\n #self.Label9.configure(image=photo)\r\n #self.Label9.image =photo\r\n \r\n \r\n # self.Label9.configure(background=\"#d9d9d9\")\r\n # self.Label9.configure(disabledforeground=\"#a3a3a3\")\r\n #self.Label9.configure(foreground=\"#000000\")\r\n # self.Label9.configure(text='''Image''')\r\n\r\n self.Button1 = tk.Button(top,command=self.OpenFile)\r\n self.Button1.place(relx=0.143, rely=0.828, height=19, width=81)\r\n self.Button1.configure(activebackground=\"#d9d9d9\")\r\n self.Button1.configure(activeforeground=\"#000000\")\r\n self.Button1.configure(background=\"#d9d9d9\")\r\n self.Button1.configure(disabledforeground=\"#a3a3a3\")\r\n self.Button1.configure(foreground=\"#000000\")\r\n self.Button1.configure(highlightbackground=\"#d9d9d9\")\r\n self.Button1.configure(highlightcolor=\"black\")\r\n self.Button1.configure(pady=\"0\")\r\n self.Button1.configure(text='''開啟座位表''')\r\n self.Button1.configure(width=81)\r\n \r\n\r\n\r\n self.Entry7 = tk.Entry(top)\r\n self.Entry7.place(relx=0.143, rely=0.74,height=17, relwidth=0.677)\r\n self.Entry7.configure(background=\"#d9d9d9\")\r\n self.Entry7.configure(disabledforeground=\"#a3a3a3\")\r\n self.Entry7.configure(font=\"TkFixedFont\")\r\n self.Entry7.configure(foreground=\"#000000\")\r\n self.Entry7.configure(insertbackground=\"black\")\r\n self.Entry7.configure(width=474)\r\n\r\n self.val1 = tk.StringVar(root, value='')\r\n self.val1.trace('w', autocomplate(autocompleteList,self.Entry1,self.Entry3,self.Entry2,self.Entry6,self.Entry5,self.Entry4,self.Entry7))\r\n self.entry1 = tk.Entry(textvariable=self.val1)\r\n self.entry1.place(relx=0.129, rely=0.296, relheight=0.001\r\n , relwidth=0.01)\r\n self.entry1.configure(background=\"#d9d9d9\")\r\n self.entry1.configure(disabledforeground=\"#a3a3a3\")\r\n self.entry1.configure(font=\"TkFixedFont\")\r\n self.entry1.configure(foreground=\"#000000\")\r\n self.entry1.configure(width=144)\r\n self.addrow =ttk.Button(top,text=\"Test\", width=12, command=self.addrow)\r\n\r\n \r\n\r\n \r\n\r\n \r\n \r\n #tk.Entry.__init__(self, *args, **kwargs)\r\n #self.focus()\r\n \r\n def addrow(self):\r\n print( self.entry.get() + \", \" + self.val1.get() )\r\n self.art.set(\"\")\r\n\r\nclass autocomplate(tk.Entry):\r\n def __init__(self, autocompleteList,entryAuto,entryUserid,entryDept,entryTitle,entryMail,entryExt,entryLocal):\r\n \r\n self.autocompleteList = autocompleteList\r\n self.var = entryAuto[\"textvariable\"]\r\n self.entryAuto=entryAuto\r\n self.entryUserid=entryUserid\r\n self.entryDept=entryDept\r\n self.entryTitle=entryTitle\r\n self.entryMail=entryMail\r\n self.entryExt=entryExt\r\n self.entryLocal=entryLocal\r\n #self.entryImage=entryImage\r\n #print('bernice',self.var)\r\n if self.var == '':\r\n self.var =entryAuto[\"textvariable\"] = tk.StringVar()\r\n self.var.trace('w', self.changed)\r\n entryAuto.bind(\"<Return>\",self.selection)\r\n entryAuto.bind(\"<Right>\", self.selection)\r\n entryAuto.bind(\"<Up>\", self.moveUp)\r\n entryAuto.bind(\"<Down>\", self.moveDown)\r\n entryAuto.listboxUp = False\r\n def changed(self, name, index, mode):\r\n if self.var.get() == '':\r\n if self.entryAuto.listboxUp:\r\n self.listbox.destroy()\r\n self.entryAuto.listboxUp = False\r\n else:\r\n \r\n words = self.comparison()\r\n if words:\r\n if not self.entryAuto.listboxUp:\r\n self.listbox = tk.Listbox(width=23, height=8)\r\n #print( dir(self.listbox))\r\n self.listbox.bind(\"<Return>\", self.selection)\r\n self.listbox.bind(\"<Button-1>\", self.selection)\r\n self.listbox.bind(\"<Right>\", self.selection)\r\n self.listbox.place(x=self.entryAuto.winfo_x(), y=self.entryAuto.winfo_y() + self.entryAuto.winfo_height())\r\n self.entryAuto.listboxUp = True\r\n\r\n self.listbox.delete(0, tk.END)\r\n for w in words:\r\n self.listbox.insert(tk.END,w)\r\n else:\r\n if self.entryAuto.listboxUp:\r\n self.listbox.destroy()\r\n self.entryAuto.listboxUp = False\r\n\r\n def selection(self, event):\r\n if self.entryAuto.listboxUp:\r\n lb_sty_cur = self.listbox.curselection()\r\n lb_sty_get=''\r\n if lb_sty_cur:\r\n lb_sty_get = self.listbox.get(lb_sty_cur)\r\n self.var.set(lb_sty_get)\r\n #透過員編及姓名再去找其他的值\r\n self.findAllValue(self.var.get().split(\"_\")[0],self.var.get().split(\"_\")[1])\r\n self.var.set(self.var.get().split(\"_\")[1])\r\n self.listbox.destroy()\r\n self.entryAuto.listboxUp = False\r\n self.entryAuto.icursor(tk.END)\r\n self.QueryUser()\r\n def moveUp(self, event):\r\n if self.entryAuto.listboxUp:\r\n if self.listbox.curselection() == ():\r\n index = '0'\r\n else:\r\n index = self.listbox.curselection()[0]\r\n\r\n if index != '0':\r\n self.listbox.selection_clear(first=index)\r\n index = str(int(index) - 1)\r\n\r\n self.listbox.see(index) # Scroll!\r\n self.listbox.selection_set(first=index)\r\n self.listbox.activate(index)\r\n\r\n def moveDown(self, event):\r\n if self.entryAuto.listboxUp:\r\n if self.listbox.curselection() == ():\r\n index = '0'\r\n else:\r\n index = self.listbox.curselection()[0]\r\n\r\n if index != tk.END:\r\n self.listbox.selection_clear(first=index)\r\n index = str(int(index) + 1)\r\n\r\n self.listbox.see(index) # Scroll!\r\n self.listbox.selection_set(first=index)\r\n self.listbox.activate(index)\r\n\r\n def comparison(self):\r\n #print(\"Bernice2=>\",self.var.get())\r\n return [ w for w in self.autocompleteList if self.matches(self.var.get(), w) ]\r\n def matches(self,fieldValue, acListEntry):\r\n return re.compile(fieldValue.encode(\"utf8\"), re.IGNORECASE).findall(acListEntry.encode(\"utf8\"))#正規表示式的規則 模組,escape 在正規表示式中用到保留字 就不用用反斜線\r\n\r\n def findAllValue(self,userid,username):\r\n #print(dir(Toplevel1))\r\n '''conn = pymssql.connect(server=\"10.XX.1.XXX\", user=\"XXXX\", password=\"XXXX\", database=\"XXXX\", timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, host='', appname=None, port='22507', conn_properties=None, autocommit=False, tds_version=None)\r\n cursor = conn.cursor()\r\n cursor.execute(\"select u2.id,u2.userName,u2.mailAddress,ou2.organizationUnitName,fd.functionDefinitionName from \"+ \r\n \"OrganizationUnit as ou2 \"+ \r\n \"join Functions as f2 with (nolock) on f2.organizationUnitOID=ou2.OID and f2.isMain=1 \"+ \r\n \"join Users as u2 with (nolock) on u2.OID=f2.occupantOID \"+ \r\n \"join FunctionDefinition as fd on fd.OID=f2.definitionOID \"+\r\n \"where ou2.organizationOID='1c5b85fcc42410048f6cef01866cc71b' and u2.id='\"+userid+\"' and u2.userName='\"+username+\"' order by id\")\r\n row = cursor.fetchall()'''\r\n\r\n workbookR = xlrd.open_workbook(r'\\\\10.10.1.36\\ManagementApproach\\UserData.xlsx')\r\n sheet1R = workbookR.sheet_by_index(0)\r\n nrows = sheet1R.nrows\r\n ncols = sheet1R.ncols\r\n for i in range(0,nrows):\r\n \t #for j in range(0,ncols):\r\n # print(sheet1R.cell(i,0).value)\r\n # print(sheet1R.cell(i,1).value)\r\n if(str(sheet1R.cell(i,0).value).strip()==userid and str(sheet1R.cell(i,1).value).strip()==username):\r\n self.entryUserid.delete(0, tk.END)\r\n self.entryUserid.insert(10,sheet1R.cell(i,0).value)\r\n self.entryDept.delete(0, tk.END)\r\n self.entryDept.insert(10,sheet1R.cell(i,3).value)\r\n self.entryTitle.delete(0, tk.END)\r\n self.entryTitle.insert(10,sheet1R.cell(i,4).value)\r\n self.entryMail.delete(0, tk.END)\r\n self.entryMail.insert(10,sheet1R.cell(i,2).value)\r\n break\r\n '''\r\n for values in row:\r\n self.entryUserid.delete(0, tk.END)\r\n self.entryUserid.insert(10,values[0])\r\n self.entryDept.delete(0, tk.END)\r\n self.entryDept.insert(10,values[3])\r\n self.entryTitle.delete(0, tk.END)\r\n self.entryTitle.insert(10,values[4])\r\n self.entryMail.delete(0, tk.END)\r\n self.entryMail.insert(10,values[2])'''\r\n \r\n\r\n def QueryUser(self):\r\n workbook = xlrd.open_workbook(r'\\\\10.10.1.36\\ManagementApproach\\總公司暨各事業單位電話_Portal.xls')\r\n print(self.var.get())\r\n\r\n\r\n sheet1 = workbook.sheet_by_index(0)\r\n nrows = sheet1.nrows\r\n ncols = sheet1.ncols\r\n Extension=''\r\n localName=''\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet1.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='總公司11樓'\r\n \t \t\t if(sheet1.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet1.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet1.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \r\n sheet2 = workbook.sheet_by_index(1)\r\n nrows = sheet2.nrows\r\n ncols = sheet2.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet2.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='總公司10樓'\r\n \t \t\t if(sheet2.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet2.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet2.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n sheet3 = workbook.sheet_by_index(2)\r\n nrows = sheet3.nrows\r\n ncols = sheet3.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet3.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='總公司9樓'\r\n \t \t\t if(sheet3.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet3.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet3.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n sheet4 = workbook.sheet_by_index(3)\r\n nrows = sheet4.nrows\r\n ncols = sheet4.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet4.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='總公司8樓'\r\n \t \t\t if(sheet4.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet4.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet4.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n #中央研究所\r\n sheet5= workbook.sheet_by_index(4)\r\n nrows = sheet5.nrows\r\n ncols = sheet5.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet5.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='中央研究所'\r\n \t \t\t Extension=sheet5.cell(i-1,j).value\r\n \t \t\t break;\r\n #林鳳營牧場\t \t\t \r\n sheet7 = workbook.sheet_by_index(7)\r\n nrows = sheet7.nrows\r\n ncols = sheet7.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet7.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='林鳳營牧場 電話:06-6994646'\r\n \t \t\t if(sheet7.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet7.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet7.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n #台中廠\t \t\t \r\n sheet8 = workbook.sheet_by_index(8)\r\n nrows = sheet8.nrows\r\n ncols = sheet8.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet8.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='台中廠 電話:04-2339-6002'\r\n \t \t\t if(sheet8.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet8.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet8.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n #斗六廠\t \t\t \r\n sheet9 = workbook.sheet_by_index(9)\r\n nrows = sheet9.nrows\r\n ncols = sheet9.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet9.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='斗六廠 電話:05-5325004'\r\n \t \t\t if(sheet9.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet9.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet9.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n #高雄廠\t \t\t \r\n sheet10 = workbook.sheet_by_index(10)\r\n nrows = sheet10.nrows\r\n ncols = sheet10.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet10.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='高雄廠 電話:07-6976716'\r\n \t \t\t if(sheet10.cell(i+1,j).value==''):\r\n \t \t\t \tExtension=sheet10.cell(i+2,j).value\r\n \t \t\t \tbreak;\r\n \t \t\t \t\r\n \t \t\t else:\r\n \t \t\t \tExtension=sheet10.cell(i+1,j).value\r\n \t \t\t \tbreak;\r\n #五股\t \t\t \r\n sheet19 = workbook.sheet_by_index(19)\r\n nrows = sheet19.nrows\r\n ncols = sheet19.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet19.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='五股 電話:02-22901716'\r\n \t \t\t #if(sheet19.cell(i+1,j).value==''):\r\n \t \t\t Extension=sheet19.cell(i,j+1).value\r\n \t \t\t break;\r\n \t \t\t \t\r\n \t \t\t #else:\r\n \t \t\t \t#Extension=sheet19.cell(i+1,j).value\r\n \t \t\t \t#break;\r\n #南港 \t\t \r\n sheet20 = workbook.sheet_by_index(20)\r\n nrows = sheet20.nrows\r\n ncols = sheet20.ncols\r\n for i in range(0,nrows):\r\n \t for j in range(0,ncols):\r\n \t \tif(str(sheet20.cell(i,j).value).strip()==self.var.get()):\r\n \t \t\t localName='南港 電話:02-27863332'\r\n \t \t\t #if(sheet19.cell(i+1,j).value==''):\r\n \t \t\t Extension=sheet20.cell(i,j+1).value\r\n \t \t\t break;\r\n \t \t\t \t\r\n \t \t\t #else:\r\n \t \t\t \t#Extension=sheet19.cell(i+1,j).value\r\n \t \t\t \t#break;\r\n\r\n\r\n self.entryExt.delete(0, tk.END)\r\n self.entryLocal.delete(0, tk.END)\r\n if Extension !='' :\r\n self.entryExt.insert(10,str(int(Extension)))\r\n self.entryLocal.insert(10, localName)\r\n #photo = tk.PhotoImage(file='31.png')\r\n #self.entryImage.configure(image=photo)\r\n #self.entryImage.image =photo\r\n\r\nif __name__ == '__main__':\r\n vp_start_gui()\r\n\r\n\r\n\r\n\r\n\r\n"
}
] | 2 |
parapente/AoC2015 | https://github.com/parapente/AoC2015 | 35baacb2b1c03e6694f9c2f1e6edf13ed3789dbf | 69eca3d32a6c28e302a71231cd2930c0f7262929 | c2b9665a8dc64d1fc98eb943ce3a58a0353fd2f0 | refs/heads/master | 2022-07-18T17:28:03.174069 | 2022-06-09T10:02:56 | 2022-06-09T10:02:56 | 171,339,474 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.3766157329082489,
"alphanum_fraction": 0.4148060977458954,
"avg_line_length": 38.58139419555664,
"blob_id": "8a69f64837e8e3fa508dcbfcc93ad378f58ce1bd",
"content_id": "456d4871828ae878bb0da4d59721ca0c87e57278",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1702,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 43,
"path": "/15a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\nwith open('15.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nregex = r\"(\\w+): \\w+ (-*\\d+), \\w+ (-*\\d+), \\w+ (-*\\d), \\w+ (-*\\d+), \\w+ (-*\\d+)\"\ningredient = list()\nfor line in lines:\n m = re.match(regex, line)\n ingredient.append((m.group(1), int(m.group(2)), int(m.group(3)),\n int(m.group(4)), int(m.group(5)), int(m.group(6))))\n# print(ingredient)\nbest = 0\nbest_ratio = list()\nfor i in range(100):\n for j in range(100):\n for k in range(100):\n for l in range(100):\n if (i + j + k + l) == 100:\n capacity = i * ingredient[0][1] + j * ingredient[1][1] +\\\n k * ingredient[2][1] + l * ingredient[3][1]\n durability = i * ingredient[0][2] + j * ingredient[1][2] +\\\n k * ingredient[2][2] + l * ingredient[3][2]\n flavor = i * ingredient[0][3] + j * ingredient[1][3] +\\\n k * ingredient[2][3] + l * ingredient[3][3]\n texture = i * ingredient[0][4] + j * ingredient[1][4] +\\\n k * ingredient[2][4] + l * ingredient[3][4]\n if capacity < 0:\n capacity = 0\n if durability < 0:\n durability = 0\n if flavor < 0:\n flavor = 0\n if texture < 0:\n texture = 0\n score = capacity * durability * flavor * texture\n if score > best:\n best = score\n best_ratio = [i, j, k, l]\nprint(best, best_ratio)\n"
},
{
"alpha_fraction": 0.5313618183135986,
"alphanum_fraction": 0.5430479645729065,
"avg_line_length": 37.11818313598633,
"blob_id": "d968fd3bf4b6a9ac8673a929f7736cc2f54ca246",
"content_id": "b6a0a8cba3013883c7a8c6b1786f62e00c523040",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8386,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 220,
"path": "/22b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nfrom copy import copy, deepcopy\n\nclass Person:\n def __init__(self):\n self.name = \"\"\n self.hp = 0\n self.damage = 0\n self.mana = 0\n self.armor = 0\n self.total_armor = 0\n self.active_spells = []\n\n def __init__(self, name: str):\n self.name = name\n self.hp = 0\n self.damage = 0\n self.mana = 0\n self.armor = 0\n self.total_armor = 0\n self.active_spells = []\n\n def __repr__(self):\n active_spells = \",\".join([i.name for i in self.active_spells])\n return f\"{self.name}: HP={self.hp}, DAMAGE={self.damage}, MANA={self.mana}, ARMOR={self.armor}, TOTAL_ARMOR={self.total_armor}, ACTIVE_SPELLS[{active_spells}]\"\n \n\nclass Spell:\n def __init__(self):\n self.name = \"\"\n self.cost = 0\n self.health = 0\n self.damage = 0\n self.armor = 0\n self.mana = 0\n self.effect = 0\n\n def __init__(self, data: list):\n self.name = data[0]\n self.cost, self.health, self.damage, self.armor, self.mana, self.effect = [int(i) for i in data[1:]]\n\n def __repr__(self):\n return f\"Spell: {self.name}, {self.cost}, {self.health}, {self.damage}, {self.armor}, {self.mana}, {self.effect}\"\n\n\ndef init() -> tuple[Person, Person, list[Spell]]:\n with open('22.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n boss = Person(\"Boss\")\n boss.hp = int(lines[0].split(': ')[1])\n boss.damage = int(lines[1].split(': ')[1])\n\n hero = Person(\"Hero\")\n hero.hp = 50\n hero.mana = 500\n\n with open('22.spells') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n lines.pop(0)\n spells = list()\n for line in lines:\n line = \" \".join(line.split())\n spells.append(Spell(line.split()))\n return hero, boss, spells\n\n\ndef spell_check(active_spells: list[Spell]) -> None:\n for spell in active_spells:\n if spell.name == \"Shield\":\n print(f\"Shield's timer is now {spell.effect - 1}.\")\n if spell.name == \"Poison\":\n print(f\"Poison's deals {spell.damage} damage; its timer is now {spell.effect - 1}.\")\n if spell.name == \"Recharge\":\n print(f\"Recharge provides {spell.mana} mana; its timer is now {spell.effect - 1}.\")\n if spell.effect == 1:\n print(f\"{spell.name} wears off.\")\n\ndef replay_fight(hero: Person, boss: Person, spells: list[Spell], solution: str) -> None:\n turn = 0\n mana_spend = 0\n max_mana_spend = 100000\n while hero.hp > 0 and boss.hp > 0:\n if turn % 2:\n # Boss's turn\n print(\"\")\n print(\"-- Boss turn --\")\n print(f\"- Player has {hero.hp} hit points, {hero.total_armor} armor, {hero.mana} mana\")\n print(f\"- Boss has {boss.hp} hit points\")\n spell_check(hero.active_spells)\n hero, boss, mana_spend = calc_solution(hero, boss, mana_spend, max_mana_spend, spells, \"-\")\n if boss.hp > 0:\n if hero.total_armor:\n print(f\"Boss attacks for {boss.damage} - {hero.total_armor} = {boss.damage - hero.total_armor} damage!\")\n else:\n print(f\"Boss attacks for {boss.damage} damage!\")\n else:\n # Hero's turn\n print(\"\")\n print(\"-- Player turn --\")\n print(f\"- Player has {hero.hp} hit points, {hero.total_armor} armor, {hero.mana} mana\")\n print(f\"- Boss has {boss.hp} hit points\")\n spell_check(hero.active_spells)\n hero, boss, mana_spend = calc_solution(hero, boss, mana_spend, max_mana_spend, spells, solution[turn])\n spell_name = spells[int(solution[turn])].name\n if spell_name == \"MagicMissile\":\n print(f\"Player casts {spells[int(solution[turn])].name}, dealing {spells[int(solution[turn])].damage} damage.\")\n elif spell_name == \"Shield\":\n print(f\"Player casts {spells[int(solution[turn])].name}, increasing armor by {spells[int(solution[turn])].armor}.\")\n else:\n print(f\"Player casts {spells[int(solution[turn])].name}\")\n turn += 1\n if boss.hp <= 0:\n print(\"This kills the boss and the player wins.\")\n else:\n print(\"This kills the player...\")\n\n\ndef calc_solution(hero: Person, boss: Person, mana_spend: int, max_mana_spend: int|None, spells: list[Spell], seed: str) -> tuple[Person, Person, int]:\n if seed != \"-\": # Hero's turn\n hero.hp -= 1\n if hero.hp > 0:\n # Apply previous effects\n for prev_spell in hero.active_spells:\n if prev_spell.effect != 1:\n if prev_spell.name == \"Shield\":\n hero.total_armor = hero.armor + prev_spell.armor\n else:\n if prev_spell.name == \"Shield\":\n hero.total_armor = hero.armor\n boss.hp -= prev_spell.damage\n hero.mana += prev_spell.mana\n prev_spell.effect -= 1\n if seed != \"-\": # Hero's turn\n spell = spells[int(seed)]\n mana_spend += spell.cost\n if mana_spend > max_mana_spend:\n hero.hp = -1\n hero.mana -= spell.cost\n if spell.effect == -1: # Immediate effect\n boss.hp -= spell.damage\n hero.hp += spell.health\n else:\n hero.active_spells.append(copy(spell))\n if spell.name == \"Shield\":\n hero.total_armor = hero.armor + spell.armor\n else: # Boss' turn\n if boss.hp > 0:\n total_damage = boss.damage - hero.total_armor\n if total_damage <= 0:\n total_damage = 1\n hero.hp -= total_damage\n\n hero.active_spells = [copy(spell) for spell in hero.active_spells if spell.effect > 0]\n return hero, boss, mana_spend\n\n\ndef find_solution(hero: Person, boss: Person, spells: list[Spell]) -> tuple[int, str]:\n solution_min_mana = 100000\n solution_sequence = \"\"\n max_mana_spend = 100000\n solution = \"\"\n branches = [str(i) for i in range(len(spells))]\n comb = dict()\n min_mana = 10000 # minimum amount of mana needed to cast a spell\n for spell in spells:\n if spell.cost < min_mana:\n min_mana = spell.cost\n\n # Calculate all possible spell combinations\n while (branches):\n branch = branches.pop()\n solution = branch\n hero_check = None\n boss_check = None\n if len(solution) == 1:\n hero_check = deepcopy(hero)\n boss_check = deepcopy(boss)\n mana_spend = 0\n else:\n hero_check, boss_check, mana_spend = comb[solution[:-1]]\n comb[solution] = calc_solution(deepcopy(hero_check), deepcopy(boss_check), mana_spend, max_mana_spend, spells, solution[-1])\n if comb[solution][0].hp > 0 and comb[solution][2] < solution_min_mana: # if solution doesn't lead to player losing\n if comb[solution][1].hp <= 0: # if player wins\n # print(\"Player wins! Solution: \" + solution + \" cost: \" + str(comb[solution][2]))\n if solution_min_mana > comb[solution][2]:\n solution_min_mana = comb[solution][2]\n solution_sequence = solution\n elif len(solution) % 2: # Boss' turn\n branches.append(solution + '-')\n elif not (len(comb[solution][0].active_spells) == 0 and comb[solution][0].mana < min_mana): # if you can still cast a spell\n # Hero's turn\n if comb[solution][0].active_spells:\n active = [i.name for i in comb[solution][0].active_spells if i.effect > 1]\n else:\n active = []\n #print(active)\n for i in range(len(spells)):\n if spells[i].name not in active and comb[solution][0].mana >= spells[i].cost:\n branches.append(solution + str(i))\n\n return solution_min_mana, solution_sequence\n\n\ndef main():\n hero, boss, spells = init()\n min_mana, solution = find_solution(deepcopy(hero), deepcopy(boss), spells)\n print(min_mana, solution)\n if solution:\n replay_fight(hero, boss, spells, solution)\n else:\n print(\"No solution found\")\n\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5267050266265869,
"alphanum_fraction": 0.5554642677307129,
"avg_line_length": 21.537036895751953,
"blob_id": "d98bec954d51f752f8951fcd2dbceb5eb3e46bdd",
"content_id": "e182ea757e48f6ecdb544981a82fa84fde0bee71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1217,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 54,
"path": "/23b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nregister_pos = {'a': 0, 'b': 1}\n\ndef hlf(pc: int, reg: list[int], args: list[str]) -> int:\n\treg[register_pos[args[0]]] //= 2\n\treturn pc + 1\n\ndef tpl(pc: int, reg: list[int], args: list[str]) -> int:\n\treg[register_pos[args[0]]] *= 3\n\treturn pc + 1\n\ndef inc(pc: int, reg: list[int], args: list[str]) -> int:\n\treg[register_pos[args[0]]] += 1\n\treturn pc + 1\n\ndef jmp(pc: int, reg: list[int], args: list[str]) -> int:\n\toffset = int(args[0])\n\treturn pc + offset\n\ndef jie(pc: int, reg: list[int], args: list[str]) -> int:\n\tif (int(reg[register_pos[args[0]]]) % 2) == 0:\n\t\treturn jmp(pc, reg, args[1:])\n\telse:\n\t\treturn pc + 1\n\ndef jio(pc: int, reg: list[int], args: list[str]) -> int:\n\tif int(reg[register_pos[args[0]]]) == 1:\n\t\treturn jmp(pc, reg, args[1:])\n\telse:\n\t\treturn pc + 1\n\ndef main():\n\twith open('23.dat') as f:\n\t\tdata = f.read()\n\tlines = data.split('\\n')\n\tlines.pop()\n\n\top = []\n\tpc = 0\n\treg = [1, 0]\n\n\tfor line in lines:\n\t\tline = line.replace( ',', '').split()\n\t\top.append(line)\n\n\twhile pc >= 0 and pc < len(op):\n\t\tprint(f\"{pc}: {op[pc][0]} {', '.join(op[pc][1:])} [a={reg[0]}, b={reg[1]}]\")\n\t\tpc = globals()[op[pc][0]](pc, reg, op[pc][1:])\n\t\n\tprint(reg[1])\n\n\nif __name__ == \"__main__\":\n\tmain()\n"
},
{
"alpha_fraction": 0.41025641560554504,
"alphanum_fraction": 0.4235897362232208,
"avg_line_length": 16.410715103149414,
"blob_id": "2d662939a147a042af930ea705fbf1215171bb31",
"content_id": "7d960c37b94e7e5a0cb8b8a0138d92e9688d20c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 975,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 56,
"path": "/3b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\nclass Point\n{\n public $x;\n public $y;\n\n public function __construct()\n {\n $this->x = 0;\n $this->y = 0;\n }\n}\n\n$fin = fopen(\"3.dat\", \"r\");\n$data = fread($fin, filesize(\"3.dat\"));\n$datalen = strlen($data);\n$house = array();\n$x = 0;\n$y = 0;\n$santa = new Point();\n$robosanta = new Point();\n$house[\"0x0\"] = 1;\nfor ($i = 0; $i < $datalen; $i++) {\n if (($i % 2) == 0) {\n $santa_ref = $santa;\n } else {\n $santa_ref = $robosanta;\n }\n switch ($data[$i]) {\n case '>':\n $santa_ref->x++;\n break;\n case '<':\n $santa_ref->x--;\n break;\n case '^':\n $santa_ref->y++;\n break;\n case 'v':\n $santa_ref->y--;\n break;\n }\n $x = $santa_ref->x;\n $y = $santa_ref->y;\n $key = strval($x).'x'.strval($y);\n if (!array_key_exists($key, $house)) {\n $house[$key] = 1;\n } else {\n $house[$key]++;\n }\n}\necho count($house) . \"\\n\";\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.4757536053657532,
"alphanum_fraction": 0.48361730575561523,
"avg_line_length": 22.84375,
"blob_id": "0e0cf9f4fb606e58f51ced711e894a29f1b459e2",
"content_id": "93f3eaa5f979161937f1e906df5635eddd706871",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 763,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 32,
"path": "/12b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport json\nimport sys\n\ndef dosum(obj):\n localsum = 0\n keep = list()\n if isinstance(obj, dict):\n for k, v in obj.items():\n if isinstance(v, str):\n if v == \"red\":\n return 0\n if isinstance(v, int):\n localsum += v\n if isinstance(v, (list, dict)):\n keep.append(v)\n else:\n for v in obj:\n if isinstance(v, int):\n localsum += v\n if isinstance(v, (list, dict)):\n keep.append(v)\n for x in keep:\n localsum += dosum(x)\n return localsum\n\nwith open('12.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ndata = json.loads(lines[0])\nprint(dosum(data))\n"
},
{
"alpha_fraction": 0.4868154227733612,
"alphanum_fraction": 0.4929006099700928,
"avg_line_length": 19.54166603088379,
"blob_id": "d071bcc8e0065d91f7439d7f68f62c5f2c01f030",
"content_id": "7f90fc7c2966390b0c5f10aa4b11273183fcf72b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 493,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 24,
"path": "/8b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"8.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n$total = 0;\n\nforeach ($lines as $line) {\n $total -= strlen($line);\n /* echo strlen($line).\" \".$line.\" - \"; */\n $line = str_replace(\"\\\\\", \"\\\\\\\\\", $line);\n $line = str_replace(\"\\\"\", \"\\\\\\\"\", $line);\n $line = \"\\\"\".$line.\"\\\"\";\n $total += strlen($line);\n /* echo $line.PHP_EOL; */\n}\necho $total.PHP_EOL;\n\nfclose($fin);\n\n\n?>\n"
},
{
"alpha_fraction": 0.5375552177429199,
"alphanum_fraction": 0.5581737756729126,
"avg_line_length": 25.115385055541992,
"blob_id": "b6c6a44659ab7daec0c41ca42edf1f6d40596cd7",
"content_id": "13088f30bf8d0b654b7d02ddebb3e4c55f8f2cfe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 679,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 26,
"path": "/19a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\nwith open('19.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nmolecule = str(lines.pop())\nlines.pop()\nreplacements = list()\nfor line in lines:\n m = re.match(r\"(\\w+) => (\\w+)\", line)\n replacements.append((m.group(1), m.group(2)))\nprint(replacements)\nmols = set()\nfor replacement in replacements:\n i = 0\n idx = molecule.find(replacement[0], i)\n while idx != -1:\n newmol = molecule[0:i] + molecule[i:].replace(replacement[0],\n replacement[1], 1)\n mols.add(newmol)\n i = idx + 1\n idx = molecule.find(replacement[0], i)\nprint(len(mols))\n"
},
{
"alpha_fraction": 0.47136563062667847,
"alphanum_fraction": 0.49559471011161804,
"avg_line_length": 20.619047164916992,
"blob_id": "0bc7a3b22a06c2bfed8580357a2a4f227fcfaa0a",
"content_id": "ccc088c21397024622c9a35920f75f437b8cfe87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 454,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 21,
"path": "/5b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"5.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\n$dblletters = \"/(..).*\\\\1/\";\n$dblletters2 = \"/(.).\\\\1/\";\n$nice = 0;\nfor ($i=0; $i<count($lines)-1; $i++) {\n $dbl = preg_match($dblletters, $lines[$i]);\n $dbl2 = preg_match($dblletters2, $lines[$i]);\n echo $dbl . ' ' . $dbl2 . PHP_EOL;\n if ($dbl && $dbl2) {\n $nice++;\n }\n}\necho $nice.PHP_EOL;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.33743351697921753,
"alphanum_fraction": 0.36402925848960876,
"avg_line_length": 39.64864730834961,
"blob_id": "a47364eaf965ff441bb0912796aba2ef08e22781",
"content_id": "1b58c0b84ebba547d5a5b73e0609fb72e808b7c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3008,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 74,
"path": "/15b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n\nint main(void)\n{\n std::string line;\n std::ifstream fin;\n std::smatch sm;\n std::vector<std::tuple<std::string, int, int, int, int, int>>\n ingredient;\n std::regex re(\"(\\\\w+): \\\\w+ (-*\\\\d+), \\\\w+ (-*\\\\d+), \\\\w+ (-*\\\\d), \\\\w+ (-*\\\\d+), \\\\w+ (-*\\\\d+)\");\n\n fin.open(\"15.dat\");\n std::getline(fin, line);\n while (!fin.eof())\n {\n if (std::regex_match(line, sm, re))\n {\n ingredient.push_back(\n std::make_tuple(sm[1],\n std::stoi(sm[2]),\n std::stoi(sm[3]),\n std::stoi(sm[4]),\n std::stoi(sm[5]),\n std::stoi(sm[6])));\n }\n std::getline(fin, line);\n }\n\n long best = 0;\n\n std::array<long, 4> best_ratio;\n for (int i = 0; i < 100; i++)\n for (int j = 0; j < 100; j++)\n for (int k = 0; k < 100; k++)\n for (int l = 0; l < 100; l++)\n if ((i + j + k + l) == 100)\n {\n long capacity = i * std::get<1>(ingredient[0]) + j * std::get<1>(ingredient[1]) +\n k * std::get<1>(ingredient[2]) + l * std::get<1>(ingredient[3]);\n long durability = i * std::get<2>(ingredient[0]) + j * std::get<2>(ingredient[1]) +\n k * std::get<2>(ingredient[2]) + l * std::get<2>(ingredient[3]);\n long flavor = i * std::get<3>(ingredient[0]) + j * std::get<3>(ingredient[1]) +\n k * std::get<3>(ingredient[2]) + l * std::get<3>(ingredient[3]);\n long texture = i * std::get<4>(ingredient[0]) + j * std::get<4>(ingredient[1]) +\n k * std::get<4>(ingredient[2]) + l * std::get<4>(ingredient[3]);\n long calories = i * std::get<5>(ingredient[0]) + j * std::get<5>(ingredient[1]) +\n k * std::get<5>(ingredient[2]) + l * std::get<5>(ingredient[3]);\n if (capacity < 0)\n capacity = 0;\n if (durability < 0)\n durability = 0;\n if (flavor < 0)\n flavor = 0;\n if (texture < 0)\n texture = 0;\n long score = capacity * durability * flavor * texture;\n if (calories == 500 && score > best)\n {\n best = score;\n best_ratio = {i, j, k, l};\n }\n }\n std::cout << best << \" [ \";\n for (auto item : best_ratio)\n {\n std::cout << item << ' ';\n }\n std::cout << ']' << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.4078061878681183,
"alphanum_fraction": 0.4226110279560089,
"avg_line_length": 17.575000762939453,
"blob_id": "adf1d54aac60e056d1eb5618418cfe5913dd55ca",
"content_id": "84e316858b35be3001ea9b13daf5e64fb66be677",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 743,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 40,
"path": "/10a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\nfunction readnum($n)\n{\n $prev = '';\n $count = 0;\n $newnum = \"\";\n for ($j=0; $j<strlen($n); $j++) {\n if ($prev === '') {\n $prev = $n[$j];\n $count = 1;\n } else if ($prev === $n[$j]) {\n $count++;\n } else {\n $newnum .= strval($count).$prev;\n $prev = $n[$j];\n $count = 1;\n }\n }\n $newnum .= strval($count).$prev;\n return($newnum);\n}\n\n$fname = \"10.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n\n$num = $lines[0];\nfor ($i=0; $i<40; $i++) {\n $nextnum = readnum($num);\n $num = $nextnum;\n}\necho strlen($num).PHP_EOL;\n\nfclose($fin);\n\n\n?>\n"
},
{
"alpha_fraction": 0.4887983798980713,
"alphanum_fraction": 0.507807195186615,
"avg_line_length": 20.042856216430664,
"blob_id": "130c662dce9c062008659f414fc0f7f5537a4059",
"content_id": "af84e94ad2277d146d09d1bb1f15f4d2bade63e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1473,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 70,
"path": "/11b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\n\ndef incr(passwd):\n i = 7\n remainder = 1\n while i > 0:\n if remainder:\n if ord(passwd[i]) == ord('z'):\n passwd[i] = 'a'\n else:\n passwd[i] = chr(ord(passwd[i])+1)\n remainder = 0\n i -= 1\n\n\ndef chkpass(tstpass):\n stage2pass = True\n for x in tstpass:\n if x in ('i', 'o', 'l'):\n stage2pass = False\n if stage2pass is False:\n # print('Stage2 failure')\n return False\n num = [ord(x) for x in tstpass]\n prev = 0\n stage1pass = False\n count = 0\n for x in num:\n if (x-prev) == 1:\n count += 1\n else:\n count = 0\n if count == 2:\n stage1pass = True\n prev = x\n if stage1pass is False:\n # print('Stage1 failure')\n return False\n stage3pass = False\n prev = ''\n pairs = set()\n for x in tstpass:\n if x == prev:\n pairs.add(x)\n prev = x\n if len(pairs) > 1:\n stage3pass = True\n return stage3pass\n\n\ndef find_next_passwd(cpasswd):\n lpass = list(cpasswd)\n incr(lpass)\n # print(lpass)\n while not chkpass(lpass):\n incr(lpass)\n # print(lpass)\n newpasswd = ''.join(lpass)\n return newpasswd\n\n\nwith open('11.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ncurpass = lines[0]\nnewpass = find_next_passwd(curpass)\nnewpass = find_next_passwd(newpass)\nprint(newpass)\n"
},
{
"alpha_fraction": 0.47310343384742737,
"alphanum_fraction": 0.4855172336101532,
"avg_line_length": 23.16666603088379,
"blob_id": "b96d7dd1c45e8dca38b552729555d467b9f7d028",
"content_id": "c0c34c9fdce7d866caf3bf05d26c0334245e7bf2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 725,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 30,
"path": "/8a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"8.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n$total = 0;\n\nforeach ($lines as $line) {\n $total += strlen($line);\n /* echo strlen($line).\" \".$line.\" - \"; */\n $line = substr($line, 1, strlen($line)-2);\n if (preg_match_all(\"/\\\\\\\\x[0-9a-f]{2}/\", $line, $matches)) {\n /* print_r($matches); */\n foreach ($matches[0] as $m) {\n $line = str_replace($m, chr(hexdec($m)), $line);\n }\n }\n $line = str_replace(\"\\\\\\\\\", \"\\\\\", $line);\n $line = str_replace(\"\\\\\\\"\", \"\\\"\", $line);\n $total -= strlen($line);\n /* echo $line.PHP_EOL; */\n}\necho $total.PHP_EOL;\n\nfclose($fin);\n\n\n?>\n"
},
{
"alpha_fraction": 0.29770606756210327,
"alphanum_fraction": 0.3221578001976013,
"avg_line_length": 23.189023971557617,
"blob_id": "04f2c6b013955fb0f2800fb57e6a4555109aad47",
"content_id": "dba845ece95c0d607e6e94711043421ab6d637d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3967,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 164,
"path": "/7a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\nfunction repush(&$dq, &$cmd)\n{\n /* echo \"Pushing back...\"; */\n /* print_r($cmd); */\n $dq->reverse();\n $dq->push($cmd);\n $dq->reverse();\n}\n\n$fname = \"7.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\n$val = array();\n\n$dq = new \\Ds\\Deque();\nfor ($i=0; $i<count($lines)-1; $i++) {\n $ops = array();\n $ops = explode(\" \", $lines[$i]);\n $dq->push($ops);\n}\n$dq->reverse();\n\nwhile ($dq->count()) {\n $cmd = array();\n $cmd = $dq->pop();\n /* echo \"Trying...\"; */\n /* print_r($cmd); */\n if ($cmd[1] == \"->\") {\n $res = 0;\n if (is_numeric($cmd[0])) {\n $res = intval($cmd[0]);\n } else {\n if (isset($val[$cmd[0]])) {\n $res = $val[$cmd[0]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[2]] = $res;\n }\n if ($cmd[0] == \"NOT\") {\n $res = 0;\n if (is_numeric($cmd[1])) {\n $res = intval($cmd[1]);\n } else {\n if (isset($val[$cmd[1]])) {\n $res = $val[$cmd[1]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[3]] = ~$res;\n }\n if ($cmd[1] == \"AND\") {\n $res1 = 0;\n if (is_numeric($cmd[0])) {\n $res1 = intval($cmd[0]);\n } else {\n if (isset($val[$cmd[0]])) {\n $res1 = $val[$cmd[0]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $res2 = 0;\n if (is_numeric($cmd[2])) {\n $res2 = intval($cmd[2]);\n } else {\n if (isset($val[$cmd[2]])) {\n $res2 = $val[$cmd[2]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[4]] = $res1 & $res2;\n }\n if ($cmd[1] == \"OR\") {\n $res1 = 0;\n if (is_numeric($cmd[0])) {\n $res1 = intval($cmd[0]);\n } else {\n if (isset($val[$cmd[0]])) {\n $res1 = $val[$cmd[0]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $res2 = 0;\n if (is_numeric($cmd[2])) {\n $res2 = intval($cmd[2]);\n } else {\n if (isset($val[$cmd[2]])) {\n $res2 = $val[$cmd[2]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[4]] = $res1 | $res2;\n }\n if ($cmd[1] == \"LSHIFT\") {\n $res1 = 0;\n if (is_numeric($cmd[0])) {\n $res1 = intval($cmd[0]);\n } else {\n if (isset($val[$cmd[0]])) {\n $res1 = $val[$cmd[0]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $res2 = 0;\n if (is_numeric($cmd[2])) {\n $res2 = intval($cmd[2]);\n } else {\n if (isset($val[$cmd[2]])) {\n $res2 = $val[$cmd[2]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[4]] = $res1 << $res2;\n }\n if ($cmd[1] == \"RSHIFT\") {\n $res1 = 0;\n if (is_numeric($cmd[0])) {\n $res1 = intval($cmd[0]);\n } else {\n if (isset($val[$cmd[0]])) {\n $res1 = $val[$cmd[0]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $res2 = 0;\n if (is_numeric($cmd[2])) {\n $res2 = intval($cmd[2]);\n } else {\n if (isset($val[$cmd[2]])) {\n $res2 = $val[$cmd[2]];\n } else {\n repush($dq, $cmd);\n continue;\n }\n }\n $val[$cmd[4]] = $res1 >> $res2;\n }\n}\necho $val[\"a\"].PHP_EOL;\nfclose($fin);\n\n\n?>\n"
},
{
"alpha_fraction": 0.4954337775707245,
"alphanum_fraction": 0.5251141786575317,
"avg_line_length": 23.33333396911621,
"blob_id": "001370044798259214bce9c71312f3b37629a7a4",
"content_id": "c00756948d9370dd85f985398d13f66e3602d52b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 438,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 18,
"path": "/8a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nwith open('8.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ntotal = 0\nfor line in lines:\n tr = line[1:-1]\n matches = re.findall(r'\\\\x[0-9a-f]{2}', line)\n for m in matches:\n tr = tr.replace(m, chr(int(\"0\"+m[1:4], 16)))\n tr = tr.replace(\"\\\\\\\\\", \"\\\\\")\n tr = tr.replace(\"\\\\\\\"\", \"\\\"\")\n # print(len(line), len(tr), line)\n total += len(line) - len(tr)\nprint(total)\n"
},
{
"alpha_fraction": 0.5026064515113831,
"alphanum_fraction": 0.5065160989761353,
"avg_line_length": 27.419754028320312,
"blob_id": "07cf2a6f5067f7479f0da0656c5064a08e63299e",
"content_id": "e7eb6e40ca89c839d60363494187e0de7b46cd94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2302,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 81,
"path": "/24b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nfrom functools import reduce\n\n\ndef combinations(package: list[int], group: list[int], options: dict, result: list[list[int]]) -> None:\n if group:\n if sum(group) > options[\"target\"]:\n return\n if sum(group) == options[\"target\"]:\n options[\"max_length\"] = len(group)\n result.append(group[:])\n return\n\n while package:\n item = package.pop()\n group.append(item)\n combinations(package[:], group, options, result)\n group.pop()\n else:\n while package:\n item = package.pop()\n group.append(item)\n combinations(package[:], group, options, result)\n group.pop()\n\n\ndef find_group(package: list[int], target: int) -> list[int]:\n done = False\n result = []\n options = {'target': target, 'max_length': len(package)}\n combinations(package[:], [], options, result)\n result.sort(key=lambda x: (len(x), reduce(lambda a, b: a*b, x)), reverse=True)\n while result and not done:\n test_item = result.pop()\n rest = [item for item in package if item not in test_item]\n subgroup = [test_item[:], [], [], []]\n i = 1\n tmp = []\n first_seen = None\n while not done:\n if sum(tmp) > target:\n rest.insert(0, tmp.pop())\n elif sum(tmp) == target:\n subgroup[i] = tmp[:]\n i += 1\n tmp = []\n else:\n item = rest.pop()\n if first_seen == item:\n break\n if not tmp:\n first_seen = item\n tmp.append(item)\n if i == 4:\n done = True\n return subgroup\n\n\ndef get_groups(package: list[int], target: int) -> list[int]:\n package_copy = package[:]\n package_copy.sort()\n return find_group(package_copy, target)\n\n\ndef main():\n with open('24.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n\n package = [int(weight) for weight in lines]\n target = sum(package) // 4\n print(f\"Target weight: {target}\")\n group = get_groups(package, target)\n qe = reduce(lambda x, y: x*y, group[0])\n print(f\"{qe}\")\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.4533769488334656,
"alphanum_fraction": 0.4641271233558655,
"avg_line_length": 28.108842849731445,
"blob_id": "256f0b3b515667dddb02f9c9d0bc5ab53278e562",
"content_id": "243409704d4516151b1674c426be0f1b4e3f20b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4279,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 147,
"path": "/13b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n#include <set>\n#include <nlohmann/json.hpp>\n#include <iomanip>\n\nstruct string_pair_hash\n{\n std::size_t operator () (std::pair<std::string, std::string> const &v) const\n {\n return std::hash<std::string>()(v.first + v.second);\n }\n};\n\nstd::vector<std::vector<std::string>> find_perms(std::vector<std::string> persons_v)\n{\n std::vector<std::vector<std::string>> new_perms;\n\n if (persons_v.size() == 2) {\n new_perms.push_back(std::vector<std::string> {persons_v[0], persons_v[1]});\n new_perms.push_back(std::vector<std::string> {persons_v[1], persons_v[0]});\n } else {\n for (auto person : persons_v) {\n std::vector<std::string> remain = persons_v;\n std::vector<std::string>::iterator it_rem;\n for (auto it = remain.begin(); it != remain.end(); ++it) {\n if (*it == person) {\n it_rem = it;\n break;\n }\n }\n remain.erase(it_rem);\n auto results = find_perms(remain);\n for (auto r : results) {\n std::vector<std::string> sublist;\n sublist.push_back(person);\n sublist.insert(sublist.end(), r.begin(), r.end());\n new_perms.push_back(sublist);\n }\n }\n }\n \n return new_perms;\n}\n\nint main(void) {\n std::string line, person1, person2, status;\n int factor;\n std::ifstream fin;\n std::smatch sm;\n std::set<std::string> persons;\n std::regex re(\"(\\\\w+) would (\\\\w+) (\\\\d+) happiness units by sitting next to (\\\\w+).\");\n std::unordered_map<\n std::pair<std::string,std::string>,\n int,\n string_pair_hash\n > dist;\n std::vector<std::string> persons_v;\n\n fin.open(\"13.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n if (std::regex_match(line, sm, re)) {\n person1 = sm[1];\n person2 = sm[4];\n status = sm[2];\n if (status == \"gain\") {\n factor = stol(sm[3]);\n } else {\n factor = -stol(sm[3]);\n }\n\n persons.emplace(person1);\n persons.emplace(person2);\n if (person1 < person2) {\n auto it = dist.find(std::make_pair(person1, person2));\n if (it != dist.end()) {\n dist[make_pair(person1, person2)] += factor;\n } else {\n dist[make_pair(person1, person2)] = factor;\n }\n } else {\n auto it = dist.find(std::make_pair(person2, person1));\n if (it != dist.end()) {\n dist[make_pair(person2, person1)] += factor;\n } else {\n dist[make_pair(person2, person1)] = factor;\n }\n }\n }\n std::getline(fin, line);\n }\n\n persons.emplace(\"Me\");\n for (auto person : persons) {\n dist[make_pair(person, \"Me\")] = 0;\n }\n\n for (auto it : persons) {\n persons_v.push_back(it);\n }\n\n auto perms = find_perms(persons_v);\n\n int max_happy = -999999999;\n int total;\n std::string prev;\n std::vector<std::string> max_seats;\n for (auto item : perms) {\n total = 0;\n prev = \"\";\n\n for (auto person : item) {\n if (prev != \"\") {\n if (person < prev) {\n total += dist[make_pair(person, prev)];\n } else {\n total += dist[make_pair(prev, person)];\n }\n } else {\n if (person < item.at(item.size() - 1)) {\n total += dist[make_pair(person, item.at(item.size() - 1))];\n } else {\n total += dist[make_pair(item.at(item.size() - 1), person)];\n }\n }\n prev = person;\n }\n\n if (total > max_happy) {\n max_happy = total;\n max_seats = std::vector<std::string>(item);\n }\n }\n\n std::cout << \"Max: \" << max_happy << std::endl;\n\n std::cout << \"Seats: \";\n for (auto it : max_seats) {\n std::cout << it << \" \";\n }\n std::cout << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.2998760938644409,
"alphanum_fraction": 0.3382899761199951,
"avg_line_length": 24.619047164916992,
"blob_id": "2ad653cb073adac1bfe46273324c8c9b6f0862f3",
"content_id": "89009b0a0ad0daa820c2c51dd131f1f920ab8a53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1614,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 63,
"path": "/6b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::regex re(\"(^.+) (\\\\d+),(\\\\d+) through (\\\\d+),(\\\\d+)\");\n std::smatch sm;\n std::string s;\n std::string cmd;\n int x1, y1, x2, y2;\n int grid[1000][1000];\n int cnt = 0;\n\n fin.open(\"6.dat\");\n std::getline(fin, line);\n for (int x=0; x<1000; x++) {\n for (int y=0; y<1000; y++) {\n grid[x][y] = 0;\n }\n }\n while(!fin.eof()) {\n s = line;\n std::regex_match(s, sm, re);\n cmd = sm[1];\n x1 = stoi(sm[2]);\n y1 = stoi(sm[3]);\n x2 = stoi(sm[4]);\n y2 = stoi(sm[5]);\n /* std::cout << cmd << \" : \" << x1 << \",\" << y1 << \" - \" << x2 << \",\" << y2 << std::endl; */\n if (cmd == \"turn on\") {\n for (int x=x1; x<=x2; x++) {\n for (int y=y1; y<=y2; y++) {\n grid[x][y]++;\n }\n }\n }\n else if (cmd == \"turn off\") {\n for (int x=x1; x<=x2; x++) {\n for (int y=y1; y<=y2; y++) {\n if (grid[x][y] > 0)\n grid[x][y]--;\n }\n }\n }\n else {\n for (int x=x1; x<=x2; x++) {\n for (int y=y1; y<=y2; y++) {\n grid[x][y] += 2;\n }\n }\n }\n std::getline(fin, line);\n }\n for (int x=0; x<1000; x++) {\n for (int y=0; y<1000; y++) {\n cnt += grid[x][y];\n }\n }\n std::cout << cnt << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.4455958604812622,
"alphanum_fraction": 0.4546632170677185,
"avg_line_length": 23.125,
"blob_id": "071d7434593fde31f7a4348c4043c54a3971e4eb",
"content_id": "ae87521ec90ade1ce72a0d84739dc69521d6dbbe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 772,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 32,
"path": "/2a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <algorithm>\n#include <vector>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::regex e(\"(\\\\d+)x(\\\\d+)x(\\\\d+)\");\n int l, w, h;\n int paper = 0;\n\n fin.open(\"2.dat\");\n while (!fin.eof()) {\n std::getline(fin, line);\n std::smatch sm;\n std::regex_match(line, sm, e);\n if (sm.size() > 0) {\n l = stoi(sm[1]);\n w = stoi(sm[2]);\n h = stoi(sm[3]);\n std::vector<int> sides{l*w, w*h, h*l};\n paper += *min_element(std::begin(sides), std::end(sides));\n for (auto el : sides) {\n paper += 2*el;\n }\n }\n }\n fin.close();\n std::cout << paper << std::endl;\n}\n"
},
{
"alpha_fraction": 0.5532859563827515,
"alphanum_fraction": 0.5657193660736084,
"avg_line_length": 25.809524536132812,
"blob_id": "9c0e9a83eb066bf0fe9664c7ffb29b5e86b59f32",
"content_id": "e3e6c5d3a33f7c1c7a875741f3aef07e32df99d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1126,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 42,
"path": "/17a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\n\ndef find_comb(cont, quant):\n if len(cont) == 1:\n if cont[0][0] == quant:\n return cont\n return False\n solutions = list()\n for item in cont:\n newquant = quant - item[0]\n if newquant == 0:\n solutions.append([item])\n elif newquant > 0:\n newcont = list(cont)\n newcont.remove(item)\n result = find_comb(newcont, newquant)\n if result:\n for i in result:\n newitem = [item]\n newitem.extend(i)\n solutions.append(newitem)\n if not solutions:\n return False\n return solutions\n\n\nwith open('17.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ncontainer = [(int(x), i) for i, x in enumerate(lines)]\ncontainer.sort(reverse=True)\n# print(container)\ncombinations = find_comb(container, 150)\nfor sol in combinations:\n sol.sort()\ncombinations.sort()\n# print(combinations)\ndedup = [val for key, val in enumerate(combinations)\n if key == 0 or combinations[key] != combinations[key - 1]]\nprint(len(dedup))\n"
},
{
"alpha_fraction": 0.50212162733078,
"alphanum_fraction": 0.5091937780380249,
"avg_line_length": 25.185184478759766,
"blob_id": "d3c5ed3dfde8adfc945588d0f4bebbbd0ceba10f",
"content_id": "d660a27645f5d36c2144494ef95c6f0960885396",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 707,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 27,
"path": "/12a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::smatch sm;\n std::regex re(\"(-*\\\\d+)\");\n int total = 0;\n\n fin.open(\"12.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n std::string::const_iterator searchStart( line.cbegin() );\n while(std::regex_search(searchStart, line.cend(), sm, re)) {\n std::cout << sm[0] << \" + \";\n total += std::stoi(sm[0]);\n searchStart = sm.suffix().first;\n }\n std::cout << std::endl;\n std::getline(fin, line);\n }\n std::cout << \"Total: \" << total << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.30708661675453186,
"alphanum_fraction": 0.34359341859817505,
"avg_line_length": 30.75,
"blob_id": "09bfe1f5cbeb2e764809f8380b7bfc1c05ad825b",
"content_id": "565aab791028b9002726bcb58022475bb35d7246",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1397,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 44,
"path": "/18a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\n\ndef step(grid):\n newgrid = [[0]*100 for x in range(100)]\n for x in range(100):\n for y in range(100):\n if grid[x][y] == '#':\n counton = 0\n for nx in [x-1, x, x+1]:\n for ny in [y-1, y, y+1]:\n if not (nx == x and ny == y):\n if (nx >= 0 and ny >= 0 and nx < 100 and ny < 100):\n if grid[nx][ny] == '#':\n counton += 1\n if counton in (2, 3):\n newgrid[x][y] = '#'\n else:\n newgrid[x][y] = '.'\n else:\n counton = 0\n for nx in [x-1, x, x+1]:\n for ny in [y-1, y, y+1]:\n if not (nx == x and ny == y):\n if (nx >= 0 and ny >= 0 and nx < 100 and ny < 100):\n if grid[nx][ny] == '#':\n counton += 1\n if counton == 3:\n newgrid[x][y] = '#'\n else:\n newgrid[x][y] = '.'\n return newgrid\n\n\nwith open('18.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nfor i in range(100):\n lines = step(lines)\nlightson = 0\nfor line in lines:\n lightson += line.count('#')\nprint(lightson)\n"
},
{
"alpha_fraction": 0.5802469253540039,
"alphanum_fraction": 0.5925925970077515,
"avg_line_length": 19.25,
"blob_id": "5e3b4fc9ae41be5776065128636e6e62952c3028",
"content_id": "8e4ba233c19dda472170931dbf9ad6d4082c4826",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 243,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 12,
"path": "/12a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nwith open('12.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nfor line in lines:\n m = re.findall(r\"(-*\\d+)\", line)\n nums = [int(x) for x in m]\n sumofnums = sum(nums)\nprint(sumofnums)\n"
},
{
"alpha_fraction": 0.4134560227394104,
"alphanum_fraction": 0.4289821684360504,
"avg_line_length": 19.220930099487305,
"blob_id": "8552e6a92ee9575644e9677144a1d86bdf18d13a",
"content_id": "a7b92ba37aca5e70c1d099e59a351772420f06a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1739,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 86,
"path": "/11a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\nfunction incr(&$curpass)\n{\n $i = 7;\n $remainder = 1;\n while ($i > 0) {\n if ($remainder) {\n if ($curpass[$i] == 'z') {\n $curpass[$i] = 'a';\n } else {\n $curpass[$i] = chr(ord($curpass[$i]) + 1);\n $remainder = 0;\n }\n }\n $i--;\n }\n}\n\nfunction chkpass($curpass)\n{\n $stage2pass = true;\n for ($i=0; $i<strlen($curpass); $i++) {\n if ($curpass[$i] == 'i' || $curpass[$i] == 'o' || $curpass[$i] == 'l') {\n $stage2pass = false;\n }\n }\n if (!$stage2pass) {\n return false;\n }\n\n $prev = 0;\n $stage1pass = false;\n $count = 0;\n for ($i=0; $i<strlen($curpass); $i++) {\n if ((ord($curpass[$i]) - ord($prev)) === 1) {\n $count++;\n } else {\n $count = 0;\n }\n if ($count === 2) {\n $stage1pass = true;\n }\n $prev = $curpass[$i];\n }\n if (!$stage1pass) {\n return false;\n }\n\n $stage3pass = false;\n $prev = '';\n $pairs = new \\Ds\\Set();\n for ($i=0; $i<strlen($curpass); $i++) {\n if ($curpass[$i] === $prev) {\n $pairs->add($curpass[$i]);\n }\n $prev = $curpass[$i];\n }\n if ($pairs->count() > 1) {\n $stage3pass = true;\n }\n return $stage3pass;\n}\n\nfunction find_next_passwd($curpass)\n{\n incr($curpass);\n while (!chkpass($curpass)) {\n incr($curpass);\n }\n return $curpass;\n}\n\n$fname = \"11.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n\n$curpass = $lines[0];\n$newpass = find_next_passwd($curpass);\necho $newpass.PHP_EOL;\n\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.40334728360176086,
"alphanum_fraction": 0.41338911652565,
"avg_line_length": 20.727272033691406,
"blob_id": "2d609d5d2b70d88c4ab51c5da36590bd551cea22",
"content_id": "bd811c111595f0c742b3e21bc3bc2257725fd527",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1195,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 55,
"path": "/3b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <utility>\n#include <map>\n\nclass Point {\n public:\n int x;\n int y;\n Point() : x {0}, y {0} {}\n};\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n int x = 0;\n int y = 0;\n int i = 0;\n Point santa;\n Point robosanta;\n Point *santa_ptr;\n std::map<std::pair<int,int>,int> house;\n\n fin.open(\"3.dat\");\n std::getline(fin, line);\n house[std::make_pair(0,0)] = 1;\n for (auto c : line) {\n if ((i % 2) == 0)\n santa_ptr = &santa;\n else\n santa_ptr = &robosanta;\n switch(c) {\n case '>':\n santa_ptr->x++;\n break;\n case '<':\n santa_ptr->x--;\n break;\n case '^':\n santa_ptr->y++;\n break;\n case 'v':\n santa_ptr->y--;\n }\n x = santa_ptr->x;\n y = santa_ptr->y;\n if (house.count(std::make_pair(x,y)))\n house[std::make_pair(x,y)]++;\n else\n house[std::make_pair(x,y)] = 1;\n i++;\n }\n fin.close();\n std::cout << house.size() << std::endl;\n}\n"
},
{
"alpha_fraction": 0.3994845449924469,
"alphanum_fraction": 0.49054983258247375,
"avg_line_length": 21.592233657836914,
"blob_id": "9b8d22be204e7cbc1b42795afc1796cce60a01ae",
"content_id": "18ed23c0d12e337531a8f8ee4e27061884ac6d3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 2328,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 103,
"path": "/Makefile",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "CXX=clang++\nLIBCXX=-lstdc++\nOPT=-g -pedantic -Wall -Wfatal-errors\nSTD=-std=c++17\nPROGS=1a.c++ 1b.c++ 2a.c++ 2b.c++ 3a.c++ 3b.c++ 4a.c++ 4b.c++ \\\n 5a.c++ 5b.c++ 6a.c++ 6b.c++ 7a.c++ 7b.c++ 8a.c++ 8b.c++ \\\n 9a.c++ 9b.c++ 10a.c++ 10b.c++ 11a.c++ 11b.c++ 12a.c++ \\\n 12b.c++ 13a.c++ 13b.c++ 14a.c++ 14b.c++ 15a.c++ 15b.c++\n\nall: $(PROGS)\n\n1a.c++: 1a.cc\n\t$(CXX) 1a.cc $(LIBCXX) $(OPT) $(STD) -o 1a.c++\n\n1b.c++: 1b.cc\n\t$(CXX) 1b.cc $(LIBCXX) $(OPT) $(STD) -o 1b.c++\n\n2a.c++: 2a.cc\n\t$(CXX) 2a.cc $(LIBCXX) $(OPT) $(STD) -o 2a.c++\n\n2b.c++: 2b.cc\n\t$(CXX) 2b.cc $(LIBCXX) $(OPT) $(STD) -o 2b.c++\n\n3a.c++: 3a.cc\n\t$(CXX) 3a.cc $(LIBCXX) $(OPT) $(STD) -o 3a.c++\n\n3b.c++: 3b.cc\n\t$(CXX) 3b.cc $(LIBCXX) $(OPT) $(STD) -o 3b.c++\n\n4a.c++: 4a.cc\n\t$(CXX) 4a.cc $(LIBCXX) $(OPT) $(STD) -lcrypto -o 4a.c++\n\n4b.c++: 4b.cc\n\t$(CXX) 4b.cc $(LIBCXX) $(OPT) $(STD) -lcrypto -o 4b.c++\n\n5a.c++: 5a.cc\n\t$(CXX) 5a.cc $(LIBCXX) $(OPT) $(STD) -o 5a.c++\n\n5b.c++: 5b.cc\n\t$(CXX) 5b.cc $(LIBCXX) $(OPT) $(STD) -o 5b.c++\n\n6a.c++: 6a.cc\n\t$(CXX) 6a.cc $(LIBCXX) $(OPT) $(STD) -o 6a.c++\n\n6b.c++: 6b.cc\n\t$(CXX) 6b.cc $(LIBCXX) $(OPT) $(STD) -o 6b.c++\n\n7a.c++: 7a.cc\n\t$(CXX) 7a.cc $(LIBCXX) $(OPT) $(STD) -o 7a.c++\n\n7b.c++: 7b.cc\n\t$(CXX) 7b.cc $(LIBCXX) $(OPT) $(STD) -o 7b.c++\n\n8a.c++: 8a.cc\n\t$(CXX) 8a.cc $(LIBCXX) $(OPT) $(STD) -o 8a.c++\n\n8b.c++: 8b.cc\n\t$(CXX) 8b.cc $(LIBCXX) $(OPT) $(STD) -o 8b.c++\n\n9a.c++: 9a.cc\n\t$(CXX) 9a.cc $(LIBCXX) $(OPT) $(STD) -o 9a.c++\n\n9b.c++: 9b.cc\n\t$(CXX) 9b.cc $(LIBCXX) $(OPT) $(STD) -o 9b.c++\n\n10a.c++: 10a.cc\n\t$(CXX) 10a.cc $(LIBCXX) $(OPT) $(STD) -o 10a.c++\n\n10b.c++: 10b.cc\n\t$(CXX) 10b.cc $(LIBCXX) $(OPT) $(STD) -o 10b.c++\n\n11a.c++: 11a.cc\n\t$(CXX) 11a.cc $(LIBCXX) $(OPT) $(STD) -o 11a.c++\n\n11b.c++: 11b.cc\n\t$(CXX) 11b.cc $(LIBCXX) $(OPT) $(STD) -o 11b.c++\n\n12a.c++: 12a.cc\n\t$(CXX) 12a.cc $(LIBCXX) $(OPT) $(STD) -o 12a.c++\n\n12b.c++: 12b.cc\n\t$(CXX) 12b.cc $(LIBCXX) $(OPT) $(STD) -o 12b.c++\n\n13a.c++: 13a.cc\n\t$(CXX) 13a.cc $(LIBCXX) $(OPT) $(STD) -o 13a.c++\n\n13b.c++: 13b.cc\n\t$(CXX) 13b.cc $(LIBCXX) $(OPT) $(STD) -o 13b.c++\n\n14a.c++: 14a.cc\n\t$(CXX) 14a.cc $(LIBCXX) $(OPT) $(STD) -o 14a.c++\n\n14b.c++: 14b.cc\n\t$(CXX) 14b.cc $(LIBCXX) $(OPT) $(STD) -o 14b.c++\n\n15a.c++: 15a.cc\n\t$(CXX) 15a.cc $(LIBCXX) $(OPT) $(STD) -o 15a.c++\n\n15b.c++: 15b.cc\n\t$(CXX) 15b.cc $(LIBCXX) $(OPT) $(STD) -o 15b.c++\n\nclean:\n\trm -f *.c++\n\n"
},
{
"alpha_fraction": 0.5167381763458252,
"alphanum_fraction": 0.5218884348869324,
"avg_line_length": 23.27083396911621,
"blob_id": "5266d976af96a6a0b3c2a529d8afeec4e83c91ee",
"content_id": "639fac71d9256ed338a6c1604f42526633af69f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1165,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 48,
"path": "/12b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n#include <nlohmann/json.hpp>\n#include <iomanip>\n\nusing json = nlohmann::json;\n\nint dosum(json jobj) {\n int subtotal = 0;\n std::vector<json> jlist;\n\n for (auto& el : jobj.items()) {\n if (el.value().is_number()) {\n subtotal += el.value().get<int>();\n }\n if (el.value().is_string() && (el.value().get<std::string>() == \"red\") && jobj.is_object())\n return 0;\n if (el.value().is_structured()) {\n jlist.push_back(el.value());\n }\n }\n for (auto i : jlist) {\n subtotal += dosum(i);\n }\n return subtotal;\n}\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::smatch sm;\n std::regex re(\"(-*\\\\d+)\");\n int total = 0;\n\n fin.open(\"12.dat\");\n std::getline(fin, line);\n json j_complete;\n while(!fin.eof()) {\n j_complete = json::parse(line.begin(), line.end());\n /* std::cout << std::setw(4) << j_complete << std::endl; */\n std::getline(fin, line);\n }\n total = dosum(j_complete);\n std::cout << \"Total: \" << total << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.4484492838382721,
"alphanum_fraction": 0.4735959768295288,
"avg_line_length": 32.13888931274414,
"blob_id": "5601f24889f8c760193ae73994c03c148b85ce90",
"content_id": "196453aefd547417bba6a7ac714a97f89afc00b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1193,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 36,
"path": "/16b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nticket = [('children', 3), ('cats', 7), ('samoyeds', 2), ('pomeranians', 3),\n ('akitas', 0), ('vizslas', 0), ('goldfish', 5), ('trees', 3),\n ('cars', 2), ('perfumes', 1)]\nwith open('16.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nregex = r\".*: (\\w+): (\\d+), (\\w+): (\\d+), (\\w+): (\\d+)\"\nsue = list()\nsue_score = [0] * 500\nfor line in lines:\n m = re.match(regex, line)\n sue.append([(m.group(1), int(m.group(2))),\n (m.group(3), int(m.group(4))),\n (m.group(5), int(m.group(6)))])\nfor item in ticket:\n (name, quant) = item\n for i in range(500):\n score = sue_score[i]\n for clue in sue[i]:\n (cname, cquant) = clue\n if name in ['cats', 'trees']:\n if cname == name and cquant > quant:\n score += 1\n elif name in ['pomeranians', 'goldfish']:\n if cname == name and cquant < quant:\n score += 1\n elif item == clue:\n score += 1\n sue_score[i] = score\nmaxscore = max(sue_score)\n# print(sue_score)\nprint('Sue: ', str(sue_score.index(maxscore) + 1))\n"
},
{
"alpha_fraction": 0.4304511249065399,
"alphanum_fraction": 0.4498746991157532,
"avg_line_length": 23.18181800842285,
"blob_id": "c38931a148cbe21722d4efefb468a8ae5292a4da",
"content_id": "87762496de98bb7cf0e005526dbf19213e2a0547",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1596,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 66,
"path": "/20b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport math\nimport itertools\nimport sys\n\n\ndef primeFactors(n):\n result = list()\n while n % 2 == 0:\n result.append(2)\n n = n // 2\n\n # n must be odd at this point\n # so a skip of 2 ( i = i + 2) can be used\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n while n % i == 0:\n result.append(i)\n n = n // i\n\n if n > 2:\n result.append(n)\n return result\n\n\ndef main():\n with open('20.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n maxpresents = int(lines[0])\n counter = dict()\n\n house = 1\n housepresents = 0\n while housepresents < maxpresents:\n primes = primeFactors(house)\n elves = set()\n elves.add(1)\n for i, _ in enumerate(primes):\n if i == 0:\n elves.update(primes)\n else:\n c = set(itertools.combinations(primes, i+1))\n # print('Comb:', c, 'i:', i+1)\n for e in c:\n prod = 1\n for num in e:\n prod *= num\n elves.add(prod)\n # print(house, primes)\n # print(elves)\n presents = 0\n for e in elves:\n if e not in counter:\n counter[e] = 0\n counter[e] += 1\n if counter[e] <= 50:\n presents += e * 11\n if presents > maxpresents:\n print('House:', house, 'presents:', presents, 'elves:', elves)\n sys.exit(0)\n house += 1\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.4501510560512543,
"alphanum_fraction": 0.45619335770606995,
"avg_line_length": 17.38888931274414,
"blob_id": "fef5c6a8eedfda2a2e1d4b0de89cb87dcf0706b0",
"content_id": "f45c8d144817932e8e60afb7964d49aa785ab957",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 331,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 18,
"path": "/1a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n int floor = 0;\n\n fin.open(\"1.dat\");\n std::getline(fin, line);\n for (auto c : line) {\n if (c == '(')\n floor++;\n if (c == ')')\n floor--;\n }\n std::cout << floor << std::endl;\n}\n"
},
{
"alpha_fraction": 0.41224488615989685,
"alphanum_fraction": 0.44489794969558716,
"avg_line_length": 15.333333015441895,
"blob_id": "f9281448a86209b54f33c1cd09dd35a698c32580",
"content_id": "f9a591439865b55c48d6a27026d0df5c91edfa5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 15,
"path": "/1b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('1.dat') as f:\n data = f.read()\nfloor = 0\npos = 1\nfor char in data:\n if char == '(':\n floor += 1\n if char == ')':\n floor -= 1\n if floor == -1:\n print(pos)\n break\n pos += 1\n"
},
{
"alpha_fraction": 0.5193871259689331,
"alphanum_fraction": 0.526891827583313,
"avg_line_length": 30.04854393005371,
"blob_id": "331b0ccee5e3bc36821cf2d239835453304df047",
"content_id": "2472484e70edd0bc7a4d1145a8bd54c4219cafd7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3198,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 103,
"path": "/9b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <vector>\n#include <deque>\n#include <regex>\n#include <unordered_map>\n#include <unordered_set>\n#include <tuple>\n\nstruct KeyHash {\n std::size_t operator()(const std::tuple<std::string, std::string>& k) const\n {\n return std::hash<std::string>()(std::get<0>(k) + std::get<1>(k));\n }\n};\n\nstruct KeyEqual {\n bool operator()(const std::tuple<std::string, std::string>& lhs,\n const std::tuple<std::string, std::string>& rhs) const\n {\n return std::get<0>(lhs) == std::get<0>(rhs) &&\n std::get<1>(lhs) == std::get<1>(rhs);\n }\n};\n\nvoid permute(std::vector<std::vector<std::string>>& perm, std::vector<std::string>& usetvector, int l, int r)\n{\n if (l == r) {\n std::vector<std::string> newperm(usetvector.begin(), usetvector.end());\n /*for (auto i=usetvector.begin(); i!=usetvector.end(); i++) {\n std::cout << *i << \" \";\n }\n std::cout << std::endl;*/\n perm.push_back(newperm);\n }\n else {\n for (int i=l; i<=r; i++) {\n std::iter_swap(usetvector.begin()+l, usetvector.begin()+i);\n permute(perm, usetvector, l+1, r);\n std::iter_swap(usetvector.begin()+l, usetvector.begin()+i);\n }\n }\n}\n\nvoid find_longest(std::vector<std::vector<std::string>> perm, std::unordered_map<std::tuple<std::string,std::string>, int, KeyHash, KeyEqual> dist)\n{\n int maxdist = 0;\n std::vector<std::string> maxpath;\n\n for (auto p : perm) {\n int pathdist = 0;\n std::string prevnode;\n for (auto node : p) {\n int tmp;\n tmp = dist[std::make_tuple(prevnode, node)];\n if (tmp == 0)\n pathdist += dist[std::make_tuple(node, prevnode)];\n else\n pathdist += tmp;\n prevnode = node;\n }\n if (pathdist > maxdist) {\n maxdist = pathdist;\n maxpath = p;\n }\n }\n std::cout << \"Path with maximum distance: \";\n for (auto n : maxpath)\n std::cout << n << \" \";\n std::cout << \": \" << maxdist << std::endl;\n}\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::vector<std::vector<std::string>> perm;\n std::string tmp;\n std::smatch sm;\n std::regex re(\"(\\\\w+) to (\\\\w+) = (\\\\d+)\");\n std::unordered_map<std::tuple<std::string,std::string>, int, KeyHash, KeyEqual> dist;\n std::unordered_set<std::string> uset;\n\n fin.open(\"9.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n if (std::regex_match(line, sm, re)) {\n dist[std::make_tuple(sm[1], sm[2])] = stol(sm[3]);\n dist[std::make_tuple(sm[2], sm[1])] = stol(sm[3]);\n }\n uset.emplace(sm[1]);\n uset.emplace(sm[2]);\n std::cout << sm[1] << \" -> \" << sm[2] << \" = \" << sm[3] << std::endl;\n std::getline(fin, line);\n }\n std::vector<std::string> usetvector(uset.begin(), uset.end());\n\n std::cout << std::endl << uset.size() << \" unique destinations\" << std::endl;\n\n permute(perm, usetvector, 0, usetvector.size()-1);\n //std::cout << perm.size() << std::endl;\n find_longest(perm, dist);\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.49130433797836304,
"alphanum_fraction": 0.5347825884819031,
"avg_line_length": 15.428571701049805,
"blob_id": "f28f3278ce4eb9dc4eb26d2bfa43dc613b7cbcbe",
"content_id": "35850b0c4e140492c7f3ce5150e97419a95d177b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 14,
"path": "/4a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"4.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$datalen = strlen($data);\n$i = 1;\nwhile (substr(md5($data.strval($i)), 0, 5) !== \"00000\") {\n $i++;\n}\necho $i.PHP_EOL;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.5064724683761597,
"alphanum_fraction": 0.5210356116294861,
"avg_line_length": 21.071428298950195,
"blob_id": "efb19ffb8b2a3bc3bc97614fa6e9110ec230f29c",
"content_id": "5510fe810064440a2868f853c7c222a98083bccb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 618,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 28,
"path": "/5b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::regex dblletter(\"(..).*\\\\1\");\n std::regex dblletter2(\"(.).\\\\1\");\n std::smatch sm;\n std::string s;\n bool dbl;\n bool dbl2;\n int nice = 0;\n\n fin.open(\"5.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n s = line;\n dbl = std::regex_search(line, dblletter);\n dbl2 = std::regex_search(line, dblletter2);\n if (dbl && dbl2)\n nice++;\n std::getline(fin, line);\n }\n std::cout << nice << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.5097744464874268,
"alphanum_fraction": 0.5323308110237122,
"avg_line_length": 23.036144256591797,
"blob_id": "c27bf340cdf442ddc4cc6771ade3fa09d7e4801d",
"content_id": "2b8e694462408a54e731924eda719a742c157d13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1995,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 83,
"path": "/13b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\ndef find_perms(objs):\n # print(objs)\n newperms = list()\n if len(objs) == 2:\n newperms = [[objs[0], objs[1]], [objs[1], objs[0]]]\n else:\n for obj in objs:\n remain = list(objs)\n remain.remove(obj)\n results = find_perms(remain)\n for r in results:\n sublist = [obj]\n sublist.extend(r)\n newperms.append(sublist)\n return newperms\n\n\nwith open('13.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ndist = dict()\npersons = set()\nfor line in lines:\n m = re.match(r\"(\\w+) would (\\w+) (\\d+) happiness units by sitting next to (\\w+)\", line)\n person1 = m.group(1)\n person2 = m.group(4)\n status = m.group(2)\n factor = m.group(3)\n if status == \"gain\":\n factor = int(factor)\n else:\n factor = -int(factor)\n persons.add(person1)\n persons.add(person2)\n if person1 < person2:\n if (person1, person2) in dist:\n dist[(person1, person2)] += factor\n else:\n dist[(person1, person2)] = factor\n else:\n if (person2, person1) in dist:\n dist[(person2, person1)] += factor\n else:\n dist[(person2, person1)] = factor\n\n# Add myself\npersons.add('Me')\nfor p in persons:\n dist[(p, 'Me')] = 0\n\ndistc = dict(dist)\nfor k, v in distc.items():\n (key1, key2) = k\n dist[(key2, key1)] = v\n\n# for k, v in dist.items():\n# print(k)\n# print(v)\nperms = find_perms(list(persons))\n# print(perms)\nmaxhappy = -99999999\nmaxseats = list()\nfor item in perms:\n total = 0\n prev = ''\n for person in item:\n if prev != '':\n total += dist[(person, prev)]\n else:\n total += dist[(person, item[len(item)-1])]\n prev = person\n if total > maxhappy:\n maxhappy = total\n maxseats = list(item)\n # print(maxhappy)\n # print(maxseats)\nprint('Max: ', maxhappy)\nprint('Seats: ', maxseats)\n"
},
{
"alpha_fraction": 0.49520766735076904,
"alphanum_fraction": 0.504792332649231,
"avg_line_length": 21.35714340209961,
"blob_id": "cf016448285f1287f33ed8b0abc31c532c133ef0",
"content_id": "87f9e6baec96048e2d6b1abb0f0e619879e217de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 14,
"path": "/8b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('8.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ntotal = 0\nfor line in lines:\n tr = line.replace(\"\\\\\", \"\\\\\\\\\")\n tr = tr.replace(\"\\\"\", \"\\\\\\\"\")\n tr = '\"' + tr + '\"'\n # print(len(line), len(tr), line, tr)\n total += len(tr) - len(line)\nprint(total)\n"
},
{
"alpha_fraction": 0.5315315127372742,
"alphanum_fraction": 0.5585585832595825,
"avg_line_length": 22.785715103149414,
"blob_id": "899107d18aa1c301bc07ca76dfc50c1862b4e030",
"content_id": "9ec7bab26dd773a976fe7f98772aa77d512bf58e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 333,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 14,
"path": "/2b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('2.dat') as f:\n data = f.read()\npresents = data.split('\\n')\npresents.pop() # Remove last empty line\nribbon = 0\nfor p in presents:\n l, w, h = p.split('x')\n l, w, h = int(l), int(w), int(h)\n sides = [2*l+2*w, 2*w+2*h, 2*h+2*l]\n mside = min(sides)\n ribbon += mside + l*w*h\nprint(ribbon)\n"
},
{
"alpha_fraction": 0.5692307949066162,
"alphanum_fraction": 0.5835897326469421,
"avg_line_length": 29.46875,
"blob_id": "ff984711be6663eba5e1fd73fc9e0c0be4c13ee6",
"content_id": "2e46a099600fe28650eec0c7acff0715a56a1b68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 975,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 32,
"path": "/14b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\nwith open('14.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nsecs = 2503\nregex = r\"(\\w+) can fly (\\d+) km/s for (\\d+) seconds, but then must rest for (\\d+) seconds.\"\nrein_data = list()\nfor line in lines:\n m = re.match(regex, line)\n rein_data.append((m.group(1), int(m.group(2)), int(m.group(3)), int(m.group(4))))\nrein_score = [0]*len(rein_data)\nfor sec in range(secs):\n cursec = sec + 1\n reindist = list()\n for r in rein_data:\n (name, speed, runsecs, restsecs) = r\n reinruns = cursec // (runsecs + restsecs)\n if (cursec - reinruns * (runsecs + restsecs)) > runsecs:\n remain = runsecs\n else:\n remain = cursec - reinruns * (runsecs + restsecs)\n reindist.append((reinruns * runsecs + remain) * speed)\n\n maxdist = max(reindist)\n for i, dist in enumerate(reindist):\n if dist == maxdist:\n rein_score[i] += 1\nprint(max(rein_score))\n"
},
{
"alpha_fraction": 0.34310850501060486,
"alphanum_fraction": 0.36070382595062256,
"avg_line_length": 14.5,
"blob_id": "8c61788d525d85724b5f59c567fa2dbd9230f698",
"content_id": "fa368c8fac696819422242e6dbbb774f0c7c8b3e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 22,
"path": "/1b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fin = fopen(\"1.dat\", \"r\");\n$data = fread($fin, filesize(\"1.dat\"));\n$floor = 0;\n$pos = 1;\nfor ($i = 0; $i < strlen($data); $i++) {\n if ($data[$i] === \"(\") {\n $floor++;\n }\n if ($data[$i] === \")\") {\n $floor--;\n }\n if ($floor === -1) {\n echo $pos;\n break;\n }\n $pos++;\n}\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.46195653080940247,
"alphanum_fraction": 0.489130437374115,
"avg_line_length": 15.727272987365723,
"blob_id": "a270922cf66baa7dcc935ea5d5517e282b0c7e7a",
"content_id": "ce52254c5fb8a700e44d820bc981bcd3df72576f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 11,
"path": "/1a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('1.dat') as f:\n data = f.read()\nfloor = 0\nfor char in data:\n if char == '(':\n floor += 1\n if char == ')':\n floor -= 1\nprint(floor)\n"
},
{
"alpha_fraction": 0.4214736819267273,
"alphanum_fraction": 0.4391579031944275,
"avg_line_length": 30.66666603088379,
"blob_id": "e95bf3f9b8d5c8ff6110d70bfca16716d42d23d8",
"content_id": "326f8267e7b762fa096f2180a2f3626d6affe891",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2375,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 75,
"path": "/19b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\nimport sys\nimport blist\n\n\ndef findsol(mol, target, steps, maxlen, replacements):\n branches = [(mol, steps)]\n # print(branches)\n index = blist.sorteddict()\n i = 0\n solution = -1\n while branches:\n i += 1\n # print(branch)\n if i % 100000 == 0:\n print(len(index), len(branches), end='\\r')\n branch = branches.pop()\n steps = branch[1] + 1\n # if i == 500000:\n # for key, val in index.items():\n # print(key, val)\n # If no other branch reached here first\n if branch[0] not in index or (index[branch[0]] > branch[1]):\n index[branch[0]] = branch[1]\n for rep in replacements:\n done = False\n off = 0\n while not done:\n done = True\n pos = branch[0].find(rep[1], off)\n # print(rep)\n # If found\n if pos != -1:\n done = False\n newmol = branch[0][:pos] + rep[0] +\\\n branch[0][pos+len(rep[1]):]\n if newmol == target:\n # print('Target reached in', steps, 'steps!')\n if solution == -1 or solution > steps:\n solution = steps\n print('Solution:', solution)\n sys.exit(0)\n else:\n if rep[0] != 'e':\n branches.append((newmol, steps))\n off = pos + len(rep[1])\n # print(branches)\n # input()\n return solution\n\n\ndef main():\n with open('19.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n targetmolecule = str(lines.pop())\n lines.pop()\n replacements = list()\n for line in lines:\n m = re.match(r\"(\\w+) => (\\w+)\", line)\n replacements.append((m.group(1), m.group(2)))\n replacements.sort(key=lambda x: x[1])\n # print(replacements)\n # print(len(targetmolecule))\n steps = 0\n molecule = 'e'\n minsol = findsol(targetmolecule, molecule, steps, len(targetmolecule),\n replacements)\n print(minsol)\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5224913358688354,
"alphanum_fraction": 0.5536332130432129,
"avg_line_length": 18.266666412353516,
"blob_id": "fd6c4a5bd3481859ceedeeceba614b542c8f3325",
"content_id": "85a7a2cdb51b9f5cf5cfa5e276f9b17dc78aee46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 15,
"path": "/5b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nwith open('5.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nnice = 0\nfor word in lines:\n dbl = re.search(r\"(..).*\\1\", word)\n dbl2 = re.search(r\"(.).\\1\", word)\n print(dbl, dbl2)\n if dbl and dbl2:\n nice += 1\nprint(nice)\n"
},
{
"alpha_fraction": 0.5145348906517029,
"alphanum_fraction": 0.5377907156944275,
"avg_line_length": 18.11111068725586,
"blob_id": "53f2351440b5a7886d79e4fb6d7cff514bf5fd8e",
"content_id": "8b903191f16694187cdd5400ec78804c8bdf5ecb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 18,
"path": "/12a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"12.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n\n$total = 0;\npreg_match_all(\"/(-*\\\\d+)/\", $lines[0], $matches);\nfor ($i=0; $i<count($matches[0]); $i++) {\n $total += $matches[0][$i];\n}\n\necho \"Total: \".$total.PHP_EOL;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.3817863464355469,
"alphanum_fraction": 0.3922942280769348,
"avg_line_length": 15.79411792755127,
"blob_id": "14dcb681b6a9e91b612c38c99134068038a1e37c",
"content_id": "785ab2bb448b1129edb566cb6fa31ba7efa2095c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 571,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 34,
"path": "/3a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fin = fopen(\"3.dat\", \"r\");\n$data = fread($fin, filesize(\"3.dat\"));\n$datalen = strlen($data);\n$house = array();\n$x = 0;\n$y = 0;\nfor ($i = 0; $i < $datalen; $i++) {\n switch ($data[$i]) {\n case '>':\n $x++;\n break;\n case '<':\n $x--;\n break;\n case '^':\n $y++;\n break;\n case 'v':\n $y--;\n break;\n }\n $key = strval($x).'x'.strval($y);\n if (!array_key_exists($key, $house)) {\n $house[$key] = 1;\n } else {\n $house[$key]++;\n }\n}\necho count($house) . \"\\n\";\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.449438214302063,
"alphanum_fraction": 0.4681648015975952,
"avg_line_length": 16.799999237060547,
"blob_id": "376aa1cd5c667377dec72a9ca50fd966030d2bc9",
"content_id": "4f9ba3ee1d89cfb60fd9c6ac853b2c5d01011d97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 534,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 30,
"path": "/10a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\n\ndef readnum(n):\n prev = ''\n count = 0\n newnum = ''\n for c in n:\n if prev == '':\n prev = c\n count = 1\n elif prev == c:\n count += 1\n else:\n newnum += str(count)+prev\n prev = c\n count = 1\n newnum += str(count)+prev\n return newnum\n\n\nwith open('10.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nnum = lines[0]\nfor x in range(40):\n nextnum = readnum(num)\n num = nextnum\nprint(len(num))\n"
},
{
"alpha_fraction": 0.31044214963912964,
"alphanum_fraction": 0.36218249797821045,
"avg_line_length": 22.10869598388672,
"blob_id": "77ace09c3edde8a8338a3fb260a40aa1eaffcbc5",
"content_id": "ac113266aff0864f93ffe14d6bc752126b5065d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1063,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 46,
"path": "/6b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nwith open('6.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ngrid = [[0] * 1000 for i in range(1000)]\nfor line in lines:\n m = re.match(r\"(^.+) (\\d+),(\\d+) through (\\d+),(\\d+)\", line)\n cmd = m.group(1)\n x1, y1, x2, y2 = int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5))\n if cmd == \"turn on\":\n x = x1\n while x <= x2:\n y = y1\n while y <= y2:\n grid[x][y] += 1\n y += 1\n x += 1\n if cmd == \"turn off\":\n x = x1\n while x <= x2:\n y = y1\n while y <= y2:\n if grid[x][y] > 0:\n grid[x][y] -= 1\n y += 1\n x += 1\n if cmd == \"toggle\":\n x = x1\n while x <= x2:\n y = y1\n while y <= y2:\n grid[x][y] += 2\n y += 1\n x += 1\ncount = 0\nx = 0\nwhile x < 1000:\n y = 0\n while y < 1000:\n count += grid[x][y]\n y += 1\n x += 1\nprint(count)\n"
},
{
"alpha_fraction": 0.39225807785987854,
"alphanum_fraction": 0.39741936326026917,
"avg_line_length": 19.945945739746094,
"blob_id": "f550c96c437e068524f578c450d09a20b93805d0",
"content_id": "b60d774448718d02c9a8521f319b22252e74b2c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 775,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 37,
"path": "/3a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <utility>\n#include <map>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n int x = 0;\n int y = 0;\n std::map<std::pair<int,int>,int> house;\n\n fin.open(\"3.dat\");\n std::getline(fin, line);\n for (auto c : line) {\n switch(c) {\n case '>':\n x++;\n break;\n case '<':\n x--;\n break;\n case '^':\n y++;\n break;\n case 'v':\n y--;\n }\n if (house.count(std::make_pair(x,y)))\n house[std::make_pair(x,y)]++;\n else\n house[std::make_pair(x,y)] = 1;\n\n }\n fin.close();\n std::cout << house.size() << std::endl;\n}\n"
},
{
"alpha_fraction": 0.28473997116088867,
"alphanum_fraction": 0.3273657262325287,
"avg_line_length": 21.132076263427734,
"blob_id": "320782a9d15142e3bb6df23fb6ffe91b87d48cb3",
"content_id": "a22d4154a3f6d10d4be32482b44dc75d7de0a4fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1173,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 53,
"path": "/6a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"6.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\n$re = \"/(^.+) (\\\\d+),(\\\\d+) through (\\\\d+),(\\\\d+)/\";\n$grid = array();\nfor ($x=0; $x<1000; $x++) {\n for ($y=0; $y<1000; $y++) {\n $grid[$x][$y] = 0;\n }\n}\nfor ($i=0; $i<count($lines)-1; $i++) {\n preg_match($re, $lines[$i], $matches);\n $cmd = $matches[1];\n $x1 = $matches[2];\n $y1 = $matches[3];\n $x2 = $matches[4];\n $y2 = $matches[5];\n\n if ($cmd == \"turn on\") {\n for ($x=$x1; $x<=$x2; $x++) {\n for ($y=$y1; $y<=$y2; $y++) {\n $grid[$x][$y] = 1;\n }\n }\n } else if ($cmd == \"turn off\") {\n for ($x=$x1; $x<=$x2; $x++) {\n for ($y=$y1; $y<=$y2; $y++) {\n $grid[$x][$y] = 0;\n }\n }\n } else {\n for ($x=$x1; $x<=$x2; $x++) {\n for ($y=$y1; $y<=$y2; $y++) {\n $grid[$x][$y] ^= 1;\n }\n }\n }\n}\n$cnt = 0;\nfor ($x=0; $x<1000; $x++) {\n for ($y=0; $y<1000; $y++) {\n if ($grid[$x][$y] == 1) {\n $cnt++;\n }\n }\n}\necho $cnt . PHP_EOL;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.3382352888584137,
"alphanum_fraction": 0.36764705181121826,
"avg_line_length": 15.190476417541504,
"blob_id": "df1e4c9abba9c733877fcebbf799abbd5c5c8784",
"content_id": "05f1dd08ce4b2dea812c2e061a249bd3bb51df89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 340,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 21,
"path": "/3a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('3.dat') as f:\n data = f.read()\nhouse = dict()\nx = 0\ny = 0\nfor c in data:\n if c == '>':\n x += 1\n if c == '<':\n x -= 1\n if c == '^':\n y += 1\n if c == 'v':\n y -= 1\n if (x, y) in house:\n house[(x, y)] += 1\n else:\n house[(x, y)] = 1\nprint(len(house))\n"
},
{
"alpha_fraction": 0.464550256729126,
"alphanum_fraction": 0.4730158746242523,
"avg_line_length": 24.54054069519043,
"blob_id": "1fd304561783db31cb2d439e6bc6df78676106e7",
"content_id": "79356c5b8cc30bcd0b0de6a080644429a20c8de3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 945,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 37,
"path": "/5a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::regex vowels(\"[aeiou]\");\n std::regex dblletter(\"(.)\\\\1\");\n std::smatch sm;\n std::string s;\n int vows;\n bool dbl;\n bool req3;\n int nice = 0;\n\n fin.open(\"5.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n s = line;\n vows = 0;\n while(std::regex_search(s, sm, vowels)) {\n vows++;\n s = sm.suffix().str();\n }\n dbl = std::regex_search(line, dblletter);\n req3 = (line.find(\"ab\") != std::string::npos) |\n (line.find(\"cd\") != std::string::npos) |\n (line.find(\"pq\") != std::string::npos) |\n (line.find(\"xy\") != std::string::npos);\n if (vows > 2 && dbl && !req3)\n nice++;\n std::getline(fin, line);\n }\n std::cout << nice << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.48057714104652405,
"alphanum_fraction": 0.523862361907959,
"avg_line_length": 20.975608825683594,
"blob_id": "aa98ee616775201a1329992dbf83f11ffdd94cc7",
"content_id": "a28e70e56a21f94c5f9be8c830cb1cdf852dbb49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 901,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 41,
"path": "/25.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\ndef next_position(row: int, column: int) -> list[int, int]:\n if row == 1:\n row = column + 1\n column = 1\n else:\n row -= 1\n column += 1\n return [row, column]\n\n\ndef generate_code(row: int, column: int) -> int:\n code = 20151125\n cur_row = 1\n cur_column = 1\n done = False\n while not done:\n code = (code * 252533) % 33554393\n cur_row, cur_column = next_position(cur_row, cur_column)\n if cur_row == row and cur_column == column:\n done = True\n return code\n\n\ndef main() -> None:\n with open('25.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n m = re.match(r\".+ row ([0-9]+), column ([0-9]+).\", lines[0])\n row = int(m.group(1))\n column = int(m.group(2))\n code = generate_code(row, column)\n print(code)\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.48732009530067444,
"alphanum_fraction": 0.4962303042411804,
"avg_line_length": 23.316667556762695,
"blob_id": "10c326161d1d7bda4c6328b8cee5f9ae49d864ee",
"content_id": "4ad411ec7b88a6deaa73d4c6c004a0606770003b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1459,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 60,
"path": "/14a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n\nint main(void)\n{\n std::string line;\n std::ifstream fin;\n std::smatch sm;\n std::vector<std::tuple<std::string, int, int, int>> rein_data;\n std::vector<int> rein_dist;\n std::regex re(\"(\\\\w+) can fly (\\\\d+) km/s for (\\\\d+) seconds, but then must rest for (\\\\d+) seconds.\");\n int secs = 2503;\n\n fin.open(\"14.dat\");\n std::getline(fin, line);\n while (!fin.eof())\n {\n if (std::regex_match(line, sm, re))\n {\n rein_data.push_back(std::make_tuple(sm[1], std::stoi(sm[2]), std::stoi(sm[3]), std::stoi(sm[4])));\n }\n std::getline(fin, line);\n }\n\n for (auto r : rein_data)\n {\n int remain;\n auto [name, speed, runsecs, restsecs] = r;\n int rein_runs = secs / (runsecs + restsecs);\n if ((secs - rein_runs * (runsecs + restsecs)) > runsecs)\n {\n remain = runsecs;\n }\n else\n {\n remain = secs - rein_runs * (runsecs + restsecs);\n }\n\n rein_dist.push_back((rein_runs * runsecs + remain) * speed);\n }\n\n int maxdist = 0;\n int i = 0;\n std::string maxrein = \"\";\n for (auto el : rein_data)\n {\n if (maxdist < rein_dist[i])\n {\n maxdist = rein_dist[i];\n maxrein = std::get<0>(el);\n }\n i++;\n }\n\n std::cout << maxrein << ' ' << maxdist << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.5480226278305054,
"alphanum_fraction": 0.5593220591545105,
"avg_line_length": 22.600000381469727,
"blob_id": "643621004071ac8ed6e9ae0d17a72cf259595287",
"content_id": "7cdda326541300dd39a622462630b659e1da0c97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 354,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 15,
"path": "/2a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nwith open('2.dat') as f:\n data = f.read()\npresents = data.split('\\n')\npresents.pop() # Remove last empty line\npaper = 0\nfor p in presents:\n l, w, h = p.split('x')\n l, w, h = int(l), int(w), int(h)\n sides = [l*w, w*h, h*l]\n mside = min(sides)\n area = sum([2*i for i in sides])\n paper += area + mside\nprint(paper)\n"
},
{
"alpha_fraction": 0.4026402533054352,
"alphanum_fraction": 0.42592594027519226,
"avg_line_length": 29.132596969604492,
"blob_id": "10549ab9b2c4c8be5dbaf3a32a60521b63775e69",
"content_id": "c2a751bbdc9e8c638c282132c9fe81e4790adb30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5454,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 181,
"path": "/21a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport copy\n\n\nclass Person:\n hp = 0\n damage = 0\n armor = 0\n\n\ndef fight(hero, boss):\n turn = 0\n while hero.hp > 1 and boss.hp > 1:\n if turn % 2:\n # Boss's turn\n damage = boss.damage - hero.armor\n if damage < 1:\n damage = 1\n hero.hp -= damage\n else:\n # Hero's turn\n damage = hero.damage - boss.armor\n if damage < 1:\n damage = 1\n boss.hp -= damage\n turn += 1\n if hero.hp < 1:\n return False\n return True\n\n\ndef main():\n with open('21.dat') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n boss = Person()\n boss.hp = int(lines[0].split(': ')[1])\n boss.damage = int(lines[1].split(': ')[1])\n boss.armor = int(lines[2].split(': ')[1])\n\n hero = Person()\n hero.hp = 100\n hero.damage = 0\n hero.armor = 0\n\n with open('21.weapons') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n lines.pop(0)\n weapons = list()\n for line in lines:\n line = \" \".join(line.split())\n weapons.append(line.split())\n\n with open('21.armor') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n lines.pop(0)\n armor = list()\n for line in lines:\n line = \" \".join(line.split())\n armor.append(line.split())\n\n with open('21.rings') as f:\n data = f.read()\n lines = data.split('\\n')\n lines.pop()\n lines.pop(0)\n rings = list()\n for line in lines:\n line = line.replace(' +', '+')\n line = \" \".join(line.split())\n rings.append(line.split())\n\n # Calculate all possible equipment combinations and their prices\n comb = list()\n for weapon in weapons:\n mode = 0\n armortype = 0\n ring1type = 0\n ring2type = 0\n skip = False\n equipment = list()\n # We need at least a weapon...\n # We then have 4 modes:\n # * No armor or rings\n # * No rings\n # * No armor\n # * Armor and rings\n while mode < 4:\n price = 0\n equipment = list()\n if mode == 0:\n equipment = [weapon]\n price += int(weapon[1])\n mode += 1\n elif mode == 1:\n equipment = [weapon, armor[armortype]]\n price += int(weapon[1]) + int(armor[armortype][1])\n armortype += 1\n if armortype == len(armor):\n armortype = 0\n mode += 1\n ring1type = 0\n elif mode == 2:\n if ring1type == ring2type:\n skip = True\n else:\n if ring2type == -1:\n price += int(weapon[1]) + int(rings[ring1type][1])\n equipment = [weapon, rings[ring1type]]\n else:\n price += int(weapon[1]) + int(rings[ring1type][1]) +\\\n int(rings[ring2type][1])\n equipment = [weapon, rings[ring1type],\n rings[ring2type]]\n ring1type += 1\n if ring1type == len(rings):\n ring2type += 1\n ring1type = 0\n if ring2type == len(rings):\n mode += 1\n armortype = 0\n ring1type = 0\n ring2type = -1\n else:\n if ring1type == ring2type:\n skip = True\n else:\n if ring2type == -1:\n price += int(weapon[1]) + int(armor[armortype][1]) +\\\n int(rings[ring1type][1])\n equipment = [weapon, armor[armortype],\n rings[ring1type]]\n else:\n price += int(weapon[1]) + int(rings[ring1type][1]) +\\\n int(rings[ring2type][1]) + int(armor[armortype][1])\n equipment = [weapon, armor[armortype],\n rings[ring1type], rings[ring2type]]\n ring1type += 1\n if ring1type == len(rings):\n ring2type += 1\n ring1type = 0\n if ring2type == len(rings):\n armortype += 1\n ring1type = 0\n ring2type = -1\n if armortype == len(armor):\n mode += 1\n if not skip:\n comb.append([price, equipment])\n else:\n skip = False\n comb.sort(key=lambda x: x[0])\n # print(comb)\n\n done = False\n i = 0\n while not done:\n hero.damage = 0\n hero.armor = 0\n print('Boss -- HP:', boss.hp, 'Damage:', boss.damage,\n 'Armor:', boss.armor)\n print('After visiting the shop our hero has:')\n for e in comb[i][1]:\n print(e[0])\n hero.damage += int(e[2])\n hero.armor += int(e[3])\n print(\"spending\", comb[i][0], \"gold coins.\")\n print('Hero -- HP:', hero.hp, 'Damage:', hero.damage,\n 'Armor:', hero.armor)\n done = fight(copy.copy(hero), copy.copy(boss))\n i += 1\n print('Hero wins!')\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.4316326677799225,
"alphanum_fraction": 0.43775510787963867,
"avg_line_length": 21.272727966308594,
"blob_id": "1f86df3adaa7d09d44909af8929489c2caf04a61",
"content_id": "57ebc2b3f5b623ddf1136a8a6e89661672f32f9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 980,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 44,
"path": "/12b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\nfunction dosum($json)\n{\n $subtotal = 0;\n\n if (is_object($json)) {\n foreach ($json as $key => $value) {\n if (is_int($value)) {\n $subtotal += $value;\n }\n if (is_string($value) && ($value === \"red\"))\n return 0;\n if (is_array($value) || is_object($value)) {\n $subtotal += dosum($value);\n }\n }\n }\n if (is_array($json)) {\n foreach ($json as $value) {\n if (is_int($value)) {\n $subtotal += $value;\n }\n if (is_array($value) || is_object($value)) {\n $subtotal += dosum($value);\n }\n }\n }\n return $subtotal;\n}\n\n$fname = \"12.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n\n$json = json_decode($lines[0]);\n$total = dosum($json);\necho \"Total: \".$total.PHP_EOL;\n\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.5083277821540833,
"alphanum_fraction": 0.5196535587310791,
"avg_line_length": 29.020000457763672,
"blob_id": "db93c9d746d73b4465c7e1a17d4b3c17013bde23",
"content_id": "c812b6832330c707e780a8c96959454c654e559b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1501,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 50,
"path": "/8a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <regex>\n#include <cstdlib>\n\nvoid replaceAll(std::string& str, const std::string& from, const std::string& to) {\n if(from.empty())\n return;\n size_t start_pos = 0;\n while((start_pos = str.find(from, start_pos)) != std::string::npos) {\n str.replace(start_pos, from.length(), to);\n start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'\n }\n}\n\nint main(void) {\n std::string line;\n std::string tmp;\n std::ifstream fin;\n std::smatch sm;\n std::regex e(\"(\\\\\\\\x[0-9a-f]{2})\");\n std::stringstream sstream;\n int total = 0;\n\n fin.open(\"8.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n /* std::cout << line << \" -> \"; */\n total += line.length();\n line = line.substr(1, line.length()-2);\n while (std::regex_search(line, sm, e)) {\n int c;\n tmp = sm[1];\n replaceAll(tmp, std::string(\"\\\\\"), std::string(\"0\"));\n\n c = strtol(tmp.c_str(), NULL, 16);\n std::string tmp2(1, (char)c);\n line.replace(sm.position(1), 4, tmp2);\n }\n replaceAll(line, std::string(\"\\\\\\\"\"), std::string(\"\\\"\"));\n replaceAll(line, std::string(\"\\\\\\\\\"), std::string(\"\\\\\"));\n total -= line.length();\n /* std::cout << line << std::endl; */\n std::getline(fin, line);\n }\n fin.close();\n std::cout << total << std::endl;\n}\n"
},
{
"alpha_fraction": 0.4159663915634155,
"alphanum_fraction": 0.4432772994041443,
"avg_line_length": 24.052631378173828,
"blob_id": "08ee84732cccedfc5fd3b93e9e3b18309cfd566e",
"content_id": "723a0032d4f978f97ea7c799c20efdac959594cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 476,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 19,
"path": "/2b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fin = fopen(\"2.dat\", \"r\");\n$data = fread($fin, filesize(\"2.dat\"));\n$presents = explode(\"\\n\", $data);\n$ribbon = 0;\nfor ($i = 0; $i < count($presents); $i++) {\n if (preg_match(\"/(\\\\d+)x(\\\\d+)x(\\\\d+)/\", $presents[$i], $match)) {\n $l = intval($match[1]);\n $w = intval($match[2]);\n $h = intval($match[3]);\n $box = array(2*$l+2*$w, 2*$w+2*$h, 2*$h+2*$l);\n $ribbon += min($box) + $l*$w*$h;\n }\n}\necho $ribbon . \"\\n\";\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.5393356680870056,
"alphanum_fraction": 0.5419580340385437,
"avg_line_length": 28.33333396911621,
"blob_id": "72b71022aec9e84674f501e3d10d84cfefebb945",
"content_id": "4fa60edc5a50529148153a8ddb9ea87be4e40c3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1144,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 39,
"path": "/8b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <regex>\n#include <cstdlib>\n\nvoid replaceAll(std::string& str, const std::string& from, const std::string& to) {\n if(from.empty())\n return;\n size_t start_pos = 0;\n while((start_pos = str.find(from, start_pos)) != std::string::npos) {\n str.replace(start_pos, from.length(), to);\n start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'\n }\n}\n\nint main(void) {\n std::string line;\n std::string tmp;\n std::ifstream fin;\n std::stringstream sstream;\n int total = 0;\n\n fin.open(\"8.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n /* std::cout << line << \" -> \"; */\n total -= line.length();\n replaceAll(line, std::string(\"\\\\\"), std::string(\"\\\\\\\\\"));\n replaceAll(line, std::string(\"\\\"\"), std::string(\"\\\\\\\"\"));\n line = std::string(\"\\\"\") + line + std::string(\"\\\"\");\n total += line.length();\n /* std::cout << line << std::endl; */\n std::getline(fin, line);\n }\n fin.close();\n std::cout << total << std::endl;\n}\n"
},
{
"alpha_fraction": 0.4654088020324707,
"alphanum_fraction": 0.473794549703598,
"avg_line_length": 24.105262756347656,
"blob_id": "86361242768d7dcb0668015081fb114e7cdf10e0",
"content_id": "483fb7697ccb8057ea5d7f2ae5999844327bf120",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1908,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 76,
"path": "/14b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n\nint main(void)\n{\n std::string line;\n std::ifstream fin;\n std::smatch sm;\n std::vector<std::tuple<std::string, int, int, int>> rein_data;\n std::regex re(\"(\\\\w+) can fly (\\\\d+) km/s for (\\\\d+) seconds, but then must rest for (\\\\d+) seconds.\");\n int secs = 2503;\n int maxdist;\n std::string maxrein;\n std::vector<int> rein_score;\n\n fin.open(\"14.dat\");\n std::getline(fin, line);\n while (!fin.eof())\n {\n if (std::regex_match(line, sm, re))\n {\n rein_data.push_back(std::make_tuple(sm[1], std::stoi(sm[2]), std::stoi(sm[3]), std::stoi(sm[4])));\n }\n std::getline(fin, line);\n }\n\n for (int i = 0; i < rein_data.size(); i++)\n {\n rein_score.push_back(0);\n }\n\n for (int sec = 0; sec < secs; sec++)\n {\n int cursec = sec + 1;\n std::vector<int> rein_dist;\n\n for (auto r : rein_data)\n {\n int remain;\n auto [name, speed, runsecs, restsecs] = r;\n int rein_runs = cursec / (runsecs + restsecs);\n if ((cursec - rein_runs * (runsecs + restsecs)) > runsecs)\n {\n remain = runsecs;\n }\n else\n {\n remain = cursec - rein_runs * (runsecs + restsecs);\n }\n\n rein_dist.push_back((rein_runs * runsecs + remain) * speed);\n }\n\n maxdist = 0;\n int i = 0;\n maxrein = \"\";\n auto it = max_element(std::begin(rein_dist), std::end(rein_dist));\n maxdist = *it;\n\n for (auto dist : rein_dist)\n {\n if (dist == maxdist)\n {\n rein_score[i]++;\n }\n i++;\n }\n }\n\n auto it = max_element(std::begin(rein_score), std::end(rein_score));\n std::cout << *it << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.37827715277671814,
"alphanum_fraction": 0.3932584226131439,
"avg_line_length": 14.70588207244873,
"blob_id": "47e3a2944f19281efa3a22c6009e75d8179e9077",
"content_id": "174f77ef0206768722a8bf887727ba916afdd28f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 267,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 17,
"path": "/1a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fin = fopen(\"1.dat\", \"r\");\n$data = fread($fin, filesize(\"1.dat\"));\n$floor = 0;\nfor ($i = 0; $i < strlen($data); $i++) {\n if ($data[$i] === \"(\") {\n $floor++;\n }\n if ($data[$i] === \")\") {\n $floor--;\n }\n}\necho $floor;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.47826087474823,
"alphanum_fraction": 0.4962884485721588,
"avg_line_length": 24.486486434936523,
"blob_id": "6ba0959fb46885e5eccd2a5ee5b81aad58b73569",
"content_id": "608f2448fe07ca416f5bb95b764670ef14b05ea7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 943,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 37,
"path": "/4a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <openssl/md5.h>\n\nint main(void) {\n std::string line;\n std::string tmp;\n std::ifstream fin;\n unsigned char hash[MD5_DIGEST_LENGTH];\n int i;\n int len;\n bool done;\n\n fin.open(\"4.dat\");\n std::getline(fin, line);\n i = 1;\n done = false;\n do {\n tmp = line + std::to_string(i);\n len = tmp.length();\n MD5((const unsigned char *)tmp.data(), len, hash);\n std::ostringstream sstr;\n sstr << std::hex << std::setfill('0');\n for (long long c: hash)\n {\n sstr << std::setw(2) << (long long) c;\n }\n if (sstr.str().substr(0,5) == std::string(\"00000\"))\n done = true;\n /* std::cout << sstr.str().substr(0,5) << \" - \" << sstr.str() << \" - \" << i << std::endl; */\n i++;\n } while (!done);\n std::cout << i-1 << std::endl;\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.33883386850357056,
"alphanum_fraction": 0.37293729186058044,
"avg_line_length": 17.18000030517578,
"blob_id": "8d7df8999002c560ea720e560a6364e8abdec6f3",
"content_id": "925f82ef103f0d22642c8d506819430b87543da3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 909,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 50,
"path": "/3b.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n\nclass Point:\n def __init__(self):\n self.x = 0\n self.y = 0\n\n\nwith open('3.dat') as f:\n data = f.read()\nhouse = dict()\nhouse[(0, 0)] = 1\ni = 0\nx = 0\ny = 0\nsanta = Point()\nrobosanta = Point()\nfor c in data:\n if c == '>':\n if i % 2 == 0:\n santa.x += 1\n else:\n robosanta.x += 1\n if c == '<':\n if i % 2 == 0:\n santa.x -= 1\n else:\n robosanta.x -= 1\n if c == '^':\n if i % 2 == 0:\n santa.y += 1\n else:\n robosanta.y += 1\n if c == 'v':\n if i % 2 == 0:\n santa.y -= 1\n else:\n robosanta.y -= 1\n if i % 2 == 0:\n x = santa.x\n y = santa.y\n else:\n x = robosanta.x\n y = robosanta.y\n if (x, y) in house:\n house[(x, y)] += 1\n else:\n house[(x, y)] = 1\n i += 1\nprint(len(house))\n"
},
{
"alpha_fraction": 0.4045542776584625,
"alphanum_fraction": 0.41375967860221863,
"avg_line_length": 23.867469787597656,
"blob_id": "f13b9944676e3072ea95f00a594d4d2724b384fd",
"content_id": "7736ea447bbe3f1c08725d59bad42df1a5c3c60a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2064,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 83,
"path": "/9b.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"9.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\nunset($lines[count($lines)-1]);\n$dist = array();\n$perms = array();\n$uniq = new \\Ds\\Set();\n\nfunction perm(&$p, $dest, $l, $r)\n{\n if ($l == $r) {\n $row = count($p);\n $i = 0;\n foreach ($dest as $d) {\n $p[$row][$i] = $d;\n $i++;\n }\n } else {\n for ($i=$l; $i<=$r; $i++) {\n [$dest[$l], $dest[$i]] = [$dest[$i], $dest[$l]];\n perm($p, $dest, $l+1, $r);\n [$dest[$l], $dest[$i]] = [$dest[$i], $dest[$l]];\n }\n }\n}\n\nfunction find_longest($perms, $dist)\n{\n $max = 0;\n $maxpath = array();\n\n foreach ($perms as $p) {\n $distance = 0;\n $prevnode = \"\";\n foreach ($p as $node) {\n $tmp = 0;\n if (array_key_exists($prevnode, $dist)) {\n if (array_key_exists($node, $dist[$prevnode])) {\n $tmp = $dist[$prevnode][$node];\n $distance += $tmp;\n }\n }\n if (array_key_exists($node, $dist)) {\n if (array_key_exists($prevnode, $dist[$node])) {\n $tmp = $dist[$node][$prevnode];\n $distance += $tmp;\n }\n }\n $prevnode = $node;\n }\n if ($distance > $max) {\n $max = $distance;\n $maxpath = $p;\n }\n }\n foreach ($maxpath as $node) {\n echo $node.\" \";\n }\n echo \": \".$max.PHP_EOL;\n}\n\nforeach ($lines as $line) {\n if (preg_match_all(\"/(\\\\w+) to (\\\\w+) = (\\\\d+)/\", $line, $matches)) {\n /* print_r($matches); */\n $dist[$matches[1][0]][$matches[2][0]] = $matches[3][0];\n $uniq->add($matches[1][0]);\n $uniq->add($matches[2][0]);\n }\n /* echo $line.PHP_EOL; */\n}\n/* print_r($uniq); */\n$destinations = $uniq->toArray();\nperm($perms, $destinations, 0, count($destinations)-1);\n/* echo count($perms).PHP_EOL; */\nfind_longest($perms, $dist);\n\nfclose($fin);\n\n\n?>\n"
},
{
"alpha_fraction": 0.36679843068122864,
"alphanum_fraction": 0.39920949935913086,
"avg_line_length": 24.299999237060547,
"blob_id": "1b1a9a3cdc15b8ca96568c870d2ce4f6d87620d6",
"content_id": "89ec692cf6649394c1855f333e611755b6f5f536",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1265,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 50,
"path": "/7a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nfrom collections import deque\n\nwith open('7.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ndq = deque()\nval = dict()\nfor cmd in lines:\n ops = list()\n ops = cmd.split(' ')\n dq.append(ops)\n\nwhile dq:\n op = list()\n op = dq.popleft()\n try:\n # print('Trying', op)\n if op[1] == '->':\n if op[0].isdigit():\n val[op[2]] = int(op[0])\n else:\n val[op[2]] = val[op[0]]\n if op[0] == 'NOT':\n if op[1].isdigit():\n val[op[3]] = ~int(op[1])\n else:\n val[op[3]] = ~val[op[1]]\n if len(op) == 5:\n if op[0].isdigit():\n val1 = int(op[0])\n else:\n val1 = val[op[0]]\n if op[2].isdigit():\n val2 = int(op[2])\n else:\n val2 = val[op[2]]\n if op[1] == 'AND':\n val[op[4]] = val1 & val2\n if op[1] == 'OR':\n val[op[4]] = val1 | val2\n if op[1] == 'LSHIFT':\n val[op[4]] = val1 << val2\n if op[1] == 'RSHIFT':\n val[op[4]] = val1 >> val2\n except KeyError:\n # print('KeyError, pushing back')\n dq.append(op)\nprint(val['a'])\n"
},
{
"alpha_fraction": 0.4532966911792755,
"alphanum_fraction": 0.4670329689979553,
"avg_line_length": 27,
"blob_id": "6f5abdbf1f8dd38deb75026ceae97554d7c0bd60",
"content_id": "e98e90751d210874c93fa9d63608f96c76a96da6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 728,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 26,
"path": "/5a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fname = \"5.dat\";\n$fin = fopen($fname, \"r\");\n$data = fread($fin, filesize($fname));\n$lines = explode(\"\\n\", $data);\n$vowels = \"/[aeiou]/\";\n$dblletters = \"/(.)\\\\1/\";\n$nice = 0;\nfor ($i=0; $i<count($lines)-1; $i++) {\n preg_match_all($vowels, $lines[$i], $matches);\n $vows = count($matches[0]);\n $dbl = preg_match($dblletters, $lines[$i]);\n $req3 = strpos($lines[$i], \"ab\") !== false ||\n strpos($lines[$i], \"cd\") !== false ||\n strpos($lines[$i], \"pq\") !== false ||\n strpos($lines[$i], \"xy\") !== false;\n echo $vows . ' ' . $dbl . ' ' . ($req3?\"True\":\"False\") . PHP_EOL;\n if (($vows > 2) && $dbl && !$req3) {\n $nice++;\n }\n}\necho $nice.PHP_EOL;\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.49166667461395264,
"alphanum_fraction": 0.517307698726654,
"avg_line_length": 21.941177368164062,
"blob_id": "d63f45d34fe6ce542aff71580d71fa6928919275",
"content_id": "5cf5b24daf2a641228a1380104d327287bf02eb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1560,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 68,
"path": "/9a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\n\ndef perm(wayp):\n if len(wayp) == 1:\n return [wayp[0]]\n i = 0\n perms = list()\n while i < len(wayp):\n ret = list()\n ret = perm(wayp[0:i]+wayp[i+1:])\n j = 0\n while j < len(ret):\n if isinstance(ret[j], list):\n ret[j] = [wayp[i]] + ret[j]\n else:\n ret[j] = [wayp[i]] + [ret[j]]\n j += 1\n i += 1\n perms.extend(ret)\n # print(wayp, \"-\", perms)\n return perms\n\n\ndef calc_dist(way, dist_dic):\n i = 0\n ret = 0\n while i < (len(way) - 1):\n ret += dist_dic[(way[i], way[i+1])]\n i += 1\n return ret\n\n\nwith open('9.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\ndist = dict()\ndests = set()\nfor line in lines:\n tr = line[1:-1]\n m = re.match(r'(\\w+) to (\\w+) = (\\d+)', line)\n dist[(m.group(1), m.group(2))] = int(m.group(3))\n dist[(m.group(2), m.group(1))] = int(m.group(3))\n dests.add(m.group(1))\n dests.add(m.group(2))\n print(m.group(1), \"->\", m.group(2), \":\", m.group(3))\n\nprint('')\nprint(len(dests), \"unique destinations:\")\nfor d in dests:\n print(d)\nprint('')\nprint(\"Generating waypoints...\")\nwaypoints = perm(list(dests))\n# print(waypoints, len(waypoints))\nprint(\"Calculating distances...\")\nmindist = 999999999\nminidx = -1\nz = 0\nwhile z < len(waypoints):\n distance = calc_dist(waypoints[z], dist)\n if distance < mindist:\n mindist = distance\n minidx = z\n z += 1\nprint(\"Shortest:\", waypoints[minidx], \"distance:\", mindist)\n"
},
{
"alpha_fraction": 0.47637248039245605,
"alphanum_fraction": 0.4878387749195099,
"avg_line_length": 27.49505043029785,
"blob_id": "4e548a78a9410ea5f095566f60965847b691dcb3",
"content_id": "6f3f3ea19dff25dac0b11717a751d1fc22b4be00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2878,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 101,
"path": "/7a.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <exception>\n#include <vector>\n#include <deque>\n#include <sstream>\n\nbool is_number(const std::string& s) {\n return !s.empty() && s.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\nint iget(std::string& s, std::unordered_map<std::string, int>& val) {\n if (is_number(s))\n return stoi(s);\n else\n return val.at(s);\n}\n\nvoid op_set(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[2]] = iget(cmd[0], val);\n}\n\nvoid op_not(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[3]] = ~iget(cmd[1], val);\n}\n\nvoid op_and(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[4]] = iget(cmd[0], val) & iget(cmd[2], val);\n}\n\nvoid op_or(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[4]] = iget(cmd[0], val) | iget(cmd[2], val);\n}\n\nvoid op_lshift(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[4]] = iget(cmd[0], val) << iget(cmd[2], val);\n}\n\nvoid op_rshift(std::vector<std::string>& cmd, std::unordered_map<std::string, int>& val) {\n val[cmd[4]] = iget(cmd[0], val) >> iget(cmd[2], val);\n}\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::deque<std::vector<std::string>> dq;\n std::string tmp;\n std::unordered_map<std::string, int> val;\n\n fin.open(\"7.dat\");\n std::getline(fin, line);\n while(!fin.eof()) {\n std::stringstream check(line);\n std::vector<std::string> tokens;\n\n while (getline(check, tmp, ' ')) {\n tokens.push_back(tmp);\n }\n dq.push_back(tokens);\n std::getline(fin, line);\n }\n\n /* for (auto cmd : dq) { */\n /* for (auto op : cmd) { */\n /* std::cout << op << \" \"; */\n /* } */\n /* std::cout << std::endl; */\n /* } */\n\n while (dq.size()) {\n std::vector<std::string> cmd;\n cmd = dq.front();\n dq.pop_front();\n try {\n /* std::cerr << \"Trying: \"; */\n /* for (auto op : cmd) { */\n /* std::cerr << op << \" \"; */\n /* } */\n /* std::cerr << std::endl; */\n if (cmd[1] == \"->\")\n op_set(cmd, val);\n if (cmd[0] == \"NOT\")\n op_not(cmd, val);\n if (cmd[1] == \"AND\")\n op_and(cmd, val);\n if (cmd[1] == \"OR\")\n op_or(cmd, val);\n if (cmd[1] == \"LSHIFT\")\n op_lshift(cmd, val);\n if (cmd[1] == \"RSHIFT\")\n op_rshift(cmd, val);\n }\n catch(std::out_of_range e) {\n /* std::cerr << \"KeyError!\" << std::endl; */\n dq.push_back(cmd);\n }\n }\n fin.close();\n std::cout << val[\"a\"] << std::endl;\n}\n"
},
{
"alpha_fraction": 0.41333332657814026,
"alphanum_fraction": 0.4285714328289032,
"avg_line_length": 22.863636016845703,
"blob_id": "ca2ebefd60e1a381772ab674310ba70de50c7e55",
"content_id": "3214d200f8d9e32a25286f0d5c40c1aeea2f0547",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 525,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 22,
"path": "/2a.php",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "<?php\n\n$fin = fopen(\"2.dat\", \"r\");\n$data = fread($fin, filesize(\"2.dat\"));\n$presents = explode(\"\\n\", $data);\n$paper = 0;\nfor ($i = 0; $i < count($presents); $i++) {\n if (preg_match(\"/(\\\\d+)x(\\\\d+)x(\\\\d+)/\", $presents[$i], $match)) {\n $l = intval($match[1]);\n $w = intval($match[2]);\n $h = intval($match[3]);\n $box = array($l*$w, $w*$h, $h*$l);\n $paper += min($box);\n foreach ($box as $side) {\n $paper += 2*$side;\n }\n }\n}\necho $paper . \"\\n\";\nfclose($fin);\n\n?>\n"
},
{
"alpha_fraction": 0.5671641826629639,
"alphanum_fraction": 0.6218905448913574,
"avg_line_length": 19.100000381469727,
"blob_id": "2948514e4778e08f53225e95c5a1cc6cf5dc0deb",
"content_id": "eb0b7b86f1fe7d6e07c89f959237c6c7a571378f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 201,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 10,
"path": "/4a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport hashlib\nimport re\n\nwith open('4.dat') as f:\n data = f.read()\ni = 1\nwhile not re.match(\"00000\", hashlib.md5((data+str(i)).encode('utf-8')).hexdigest()):\n i += 1\nprint(i)\n"
},
{
"alpha_fraction": 0.6395348906517029,
"alphanum_fraction": 0.6686046719551086,
"avg_line_length": 23.714284896850586,
"blob_id": "5d961aa2af978290a57c18eede6a2e15f3e1ecd5",
"content_id": "b85fecfed2cf18c92103908dc245056fd71397ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 172,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 7,
"path": "/README.md",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "# Advent of Code 2015 Solutions in c++, php, python\n\n## Notes:\n### C++\nRequirements:\n - clang++\n - [nlohmann json](https://json.nlohmann.me/) (nlohmann-json3-dev in ubuntu)"
},
{
"alpha_fraction": 0.4621710479259491,
"alphanum_fraction": 0.47478070855140686,
"avg_line_length": 19.494382858276367,
"blob_id": "a59c4de860d066474933255d41c551f89e495e12",
"content_id": "6c72fc0ee05c0408250b362d6ae924658cc81f1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1824,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 89,
"path": "/11b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n#include <set>\n\nvoid inc(std::string& curpass)\n{\n int i = 7;\n int remain = 1;\n\n while (i > 0) {\n if (remain) {\n if (curpass[i] == 'z') {\n curpass[i] = 'a';\n }\n else {\n curpass[i] = curpass[i]+1;\n remain = 0;\n }\n }\n i--;\n }\n}\n\nbool chkpass(std::string curpass)\n{\n bool stage2pass = true;\n for (char c : curpass) {\n if (c == 'i' || c == 'o' || c == 'l')\n stage2pass = false;\n }\n if (!stage2pass)\n return false;\n\n char cprev = 0;\n bool stage1pass = false;\n int ccount = 0;\n for (char c : curpass) {\n if ((c-cprev) == 1) {\n ccount++;\n }\n else {\n ccount = 0;\n }\n if (ccount == 2) {\n stage1pass = true;\n }\n cprev = c;\n }\n if (!stage1pass)\n return false;\n\n bool stage3pass = false;\n cprev = 0;\n std::set<char> pairs;\n for (char c : curpass) {\n if (c == cprev)\n pairs.insert(c);\n cprev = c;\n }\n if (pairs.size() > 1)\n stage3pass = true;\n return stage3pass;\n}\n\nstd::string find_next_passwd(std::string curpass)\n{\n inc(curpass);\n while (!chkpass(curpass)) {\n inc(curpass);\n }\n return curpass;\n}\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::string curpass, nextpass;\n\n fin.open(\"11.dat\");\n std::getline(fin, line);\n curpass = line;\n std::cout << \"Current password: \" << curpass << std::endl;\n nextpass = find_next_passwd(curpass);\n std::cout << \"Next password: \" << nextpass << std::endl;\n nextpass = find_next_passwd(nextpass);\n std::cout << \"Next password: \" << nextpass << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.451977401971817,
"alphanum_fraction": 0.4655367136001587,
"avg_line_length": 19.581396102905273,
"blob_id": "6edbe2d8a87a8bf0a41e56e8c6f8505601b1d7d7",
"content_id": "b50fbe04d14b2f0ac0babf45fdafd9cf3e31a33e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 885,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 43,
"path": "/10b.cc",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <iostream>\n\nstd::string readnum(std::string num) {\n char prev = 0;\n int count = 0;\n std::string newnum;\n\n for (char c : num) {\n if (prev == 0) {\n prev = c;\n count = 1;\n }\n else if (prev == c) {\n count++;\n }\n else {\n newnum += std::to_string(count) + std::string(1, prev);\n prev = c;\n count = 1;\n }\n }\n newnum += std::to_string(count) + std::string(1, prev);\n return(newnum);\n}\n\nint main(void) {\n std::string line;\n std::ifstream fin;\n std::string num, nextnum;\n\n fin.open(\"10.dat\");\n std::getline(fin, line);\n num = line;\n for(int i=0; i<50; i++) {\n nextnum = readnum(num);\n num = nextnum;\n }\n std::cout << num << std::endl;\n std::cout << num.size() << std::endl;\n\n fin.close();\n}\n"
},
{
"alpha_fraction": 0.5135135054588318,
"alphanum_fraction": 0.5405405163764954,
"avg_line_length": 21.904762268066406,
"blob_id": "05002b5c2884c276702e9964df382493ecb0577e",
"content_id": "45ac74c8be9f7bd3600283bb2b9ae23127df7025",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 21,
"path": "/5a.py",
"repo_name": "parapente/AoC2015",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nimport re\n\nwith open('5.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nnice = 0\nfor word in lines:\n vows = len(re.findall('[aeiou]', word))\n dbl = re.search(r\"(.)\\1\", word)\n req3 = False\n for x in [\"ab\", \"cd\", \"pq\", \"xy\"]:\n req3 = req3 or x in word\n if dbl is None:\n print(vows, 0, req3)\n else:\n print(vows, len(dbl.groups()), req3)\n if vows > 2 and dbl and not req3:\n nice += 1\nprint(nice)\n"
}
] | 72 |
kepy909/wuhuboy | https://github.com/kepy909/wuhuboy | c03cf84e70f685e6afed03884d471aaf5657944c | f52def2bf73ee1e4a53f90c1058f6d92d8924c3b | 3b07c9f6e55463cf16db5c97674886e4e67440f5 | refs/heads/master | 2021-04-09T13:15:17.789606 | 2018-04-13T15:39:34 | 2018-04-13T15:39:34 | 125,488,652 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.782608687877655,
"alphanum_fraction": 0.782608687877655,
"avg_line_length": 10.5,
"blob_id": "e8c37adec109009d4ec679180417692d3dcdf1f5",
"content_id": "d225719b9e0e9b1572ad2ebdcac00198751b9511",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 2,
"path": "/README.md",
"repo_name": "kepy909/wuhuboy",
"src_encoding": "UTF-8",
"text": "# wuhuboy\n芜湖小青年的消息发布地。\n"
},
{
"alpha_fraction": 0.469696968793869,
"alphanum_fraction": 0.5098484754562378,
"avg_line_length": 32,
"blob_id": "a3754a90bba88b72ab0c8e71b863706c4416ea9a",
"content_id": "e0f25300e7f571937b26ead44b816625270f2007",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2898,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 80,
"path": "/wuhuboy/apps/index/views.py",
"repo_name": "kepy909/wuhuboy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.http import JsonResponse, HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom django.shortcuts import render\n\n\ndef index(request):\n return render(request, \"index.html\")\n\n\n@csrf_exempt\ndef get_baidu(request):\n if request.method == 'GET':\n return render(request, 'index.html')\n else:\n import requests\n usrnames = [\"a9t6w5\", \"tkg1vq\"]\n usrpwds = [\"qr6yn\", \"ehc12\"]\n docinfo = request.POST.get(\"docinfo\")\n \"\"\"\n 用户:a9t6w5密码:qr6yn 剩余2000+点(提示用户名不存在就是今天下载超过5次了)\n 用户:tkg1vq 密码:ehc12 剩余9000+点\n \"\"\"\n result = None\n for usrname, usrpwd in zip(usrnames, usrpwds):\n cookies = {\n 'usrname': usrname,\n 'usrpwd': usrpwd,\n }\n\n \"\"\"\n 用户:a9t6w5密码:qr6yn 剩余2000+点(提示用户名不存在就是今天下载超过5次了)\n 用户:tkg1vq 密码:ehc12 剩余9000+点\n (付费的无法下载)\n 每个ip每天限制5次。如果拨号上网请重启路由器还能继续下载。如果固定ip用完五次可以使用备用方法。\"\"\"\n\n headers = {\n 'Origin': 'http://139.224.236.108',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-HK;q=0.6',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Accept': '*/*',\n 'Referer': 'http://139.224.236.108/mobile.html',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Connection': 'keep-alive',\n }\n\n data = [\n ('usrname', usrname),\n ('usrpass', usrpwd),\n ('docinfo', docinfo),\n ('taskid', 'up_down_doc'),\n ]\n\n response = requests.post('http://139.224.236.108/post.php', headers=headers, cookies=cookies, data=data)\n result = response.content\n if result == \"up_doc_fail\":\n continue\n elif result == \"no_this_doc\":\n continue\n elif result == \"down_failed\":\n continue\n elif result == \"usr_not_exist\":\n continue\n elif result == \"pass_error\":\n continue\n elif result == \"wealth_not_enough\":\n continue\n elif result == \"rmb_doc\":\n continue\n else:\n break\n\n r = HttpResponse(result)\n\n return r\n"
}
] | 2 |
tincher/lesti | https://github.com/tincher/lesti | 45c05ae3e259966969efc96ee980acae24181321 | 9e7eb89261fcb89653c8fcb14ec4d54518bbcaaf | 37d1838774f97a0afbb3f0ce7282357e87a02caf | refs/heads/master | 2020-03-19T11:43:06.924194 | 2018-07-12T13:44:22 | 2018-07-12T13:44:22 | 136,472,173 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7083333134651184,
"alphanum_fraction": 0.7083333134651184,
"avg_line_length": 18.200000762939453,
"blob_id": "f94ebd80b2d28f9306309d4660669208d1537856",
"content_id": "63a61169b44917efced3ebe473c98051ca737105",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 192,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 10,
"path": "/main.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "from api_layer import riot_api as rapi\nfrom api_layer import training_data as td\n\n\ndef main():\n challengers = td.load_challenger_data()\n print(rapi.get_account_id('EPiC majo'))\n\n\nmain()\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6729069352149963,
"avg_line_length": 31.049999237060547,
"blob_id": "16d2f0b7aee944943a067e04fc3038c05bf2049c",
"content_id": "6dbd156d78a4648385167b57763e5755fe129379",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1923,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 60,
"path": "/estimator.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "import argparse\n\nimport tensorflow as tf\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--batch_size', default=100, type=int, help='batch size')\nparser.add_argument('--train_steps', default=1000, type=int,\n help='number of training steps')\n\n\ndef my_model(features, labels, mode, params):\n # input layer of the net\n net = tf.feature_column.input_layer(features, params['feature_columns'])\n\n # hidden layers\n for units in params['hidden_units']:\n net = tf.layers.dense(net, units=units, activation=tf.nn.relu)\n\n # output layer\n logits = tf.layers.dense(net, params['n_classes'], activation=None)\n\n # prediction mode\n predicted_classes = tf.argmax(logits, 1)\n if mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n 'class_ids': predicted_classes[:, tf.newaxis],\n 'probabilities': tf.nn.softmax(logits),\n 'logits': logits\n }\n return tf.estimator.EstimatorSpec(mode, predictions=predictions)\n\n # loss\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n # accuracy\n accuracy = tf.metrics.accuracy(labels=labels, predictions=predicted_classes, name='acc_op')\n metrics = {'accuracy': accuracy}\n tf.summary.scalar('accuracy', accuracy[1])\n\n # eval mode\n if mode == tf.estimator.ModeKeys.EVAL:\n return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)\n\n # training\n assert mode == tf.estimator.ModeKeys.TRAIN\n\n optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)\n train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)\n\n\ndef main(argv):\n # todo\n # specify columns and which to use (hash for big ranges)\n # delete??? useless data (try with and without - better rate wins)\n\n\n\n\n args = parser.parse_args(argv[1])\n"
},
{
"alpha_fraction": 0.6067415475845337,
"alphanum_fraction": 0.629915714263916,
"avg_line_length": 25.370370864868164,
"blob_id": "6b4d56ee3f5a22b734863788428622682859e40d",
"content_id": "e1c366f078e5f74b3da149c64e8f668c3958918f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1424,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 54,
"path": "/api_layer/riot_api.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "import time\nfrom time import sleep\n\nimport requests\n\nfrom api_layer import url_builder\n\nheaders = {'X-Riot-Token': 'RGAPI-9db58bc2-97b2-42f9-a9cc-f28569151042'}\n\n\ndef get_match(match_id):\n return get_request(url_builder.match(match_id))\n\n\ndef get_match_ids(name):\n return list(map(lambda x: x['gameId'], get_matches_from_last_months(name, 6)))\n\n\ndef get_matches_from_last_months(name, months):\n start_time = int((time.time() - (60 * 60 * 24 * 30 * months)) * 1000)\n account_id = get_account_id(name)\n return get_match_list_from_last_months(account_id, start_time)\n\n\ndef get_match_list_from_last_months(account_id, start_time):\n end, begin_index = -1, 0\n result = []\n while begin_index > end:\n r = get_request(url_builder.match_list(account_id, start_time, begin_index))\n end = r['totalGames']\n begin_index = r['endIndex']\n result += r['matches']\n return result\n\n\ndef get_challengers():\n return get_request(url_builder.get_challenger_url())\n\n\ndef get_account_id(name):\n return get_request(url_builder.account_url(name))['accountId']\n\n\ndef get_request(url):\n status_code = 0\n i = 0\n while status_code != 200:\n r = requests.get(url, headers=headers)\n status_code = r.status_code\n if r.reason == 'Too Many Requests':\n i += 1\n print('sleeping due to too many requests for ' + (120 - 110 / i))\n sleep(120 - 110 / i)\n return r.json()\n"
},
{
"alpha_fraction": 0.6740412712097168,
"alphanum_fraction": 0.6740412712097168,
"avg_line_length": 20.1875,
"blob_id": "9ee01022f8c1ce1cdad4efa0f300e50db8cfe557",
"content_id": "54d1c75b9b5bc9797486c75c7879abf95a947101",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 678,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 32,
"path": "/api_layer/training_data.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "from api_layer import gamepedia_api\nfrom api_layer import riot_api\n\n\ndef load_train_data():\n train_x = []\n train_y = []\n return\n\n\ndef load_train_data_only_player(name):\n match_ids = riot_api.get_match_ids(name)\n return list(map(lambda m_id: riot_api.get_match(m_id), match_ids))\n\n\ndef load_train_data_whole_game():\n return\n\n\ndef load_challenger_data():\n challenger = riot_api.get_challengers()\n return challenger\n\n\ndef load_current_lcs_players():\n lcs_players = gamepedia_api.get_current_lcs()\n return lcs_players\n\n# tmp = load_train_data_only_player('bigmcjoe')\n# with open('data.json', 'w') as outfile:\n# json.dump(tmp, outfile)\n# print(tmp)\n"
},
{
"alpha_fraction": 0.695652186870575,
"alphanum_fraction": 0.698369562625885,
"avg_line_length": 29.66666603088379,
"blob_id": "89195f40afbac80988e1622c9477c1c1397e9c2c",
"content_id": "ecd02eccb0d9d7fd0f9e21a28f1bd44991be367e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 368,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 12,
"path": "/api_layer/gamepedia_api.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\n\ngp_base_url = 'https://lol.gamepedia.com/'\ngp_current_players = gp_base_url + 'LCS_Players/Current'\n\n\ndef get_current_lcs():\n content = requests.get(gp_current_players).text\n soup = BeautifulSoup(content, 'html.parser')\n ls = soup.find_all('td', class_='field_ID')\n return list(map(lambda pro: pro.text, ls))\n"
},
{
"alpha_fraction": 0.7018150091171265,
"alphanum_fraction": 0.7294727563858032,
"avg_line_length": 34.06060791015625,
"blob_id": "d3fea1fbb6af04a199b57b059fcfacca19a0ceba",
"content_id": "a52190141b50a04620522d6eb5b6eb79defb901b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1157,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 33,
"path": "/api_layer/url_builder.py",
"repo_name": "tincher/lesti",
"src_encoding": "UTF-8",
"text": "from string import Template\n\nbase_url = 'https://euw1.api.riotgames.com/lol/'\n\nraw_url_summoner_id = Template(base_url + 'summoner/v3/summoners/by-name/$name?')\nraw_url_match_list = Template(base_url + 'match/v3/matchlists/by-account/$id?')\nraw_url_match = Template(base_url + 'match/v3/matches/$id?')\n\nchallenger_url = base_url + 'league/v3/challengerleagues/by-queue/RANKED_SOLO_5x5'\n\n# https://euw1.api.riotgames.com/lol/match/v3/matches/3228724210\nranked_extension = 'queue=4&queue=6&queue=42&queue=410&queue=420&queue=440&'\nstart_time_extension = Template('beginTime=$stime&')\nbegin_index_extension = Template('beginIndex=$bindex&')\nend_index_extension = Template('endIndex=&eindex&')\n\n\ndef get_challenger_url():\n return challenger_url\n\n\ndef match(match_id):\n return raw_url_match.substitute(id=match_id)\n\n\ndef match_list(account_id, start_time, begin_index):\n return raw_url_match_list.substitute(id=account_id) \\\n + ranked_extension + start_time_extension.substitute(stime=start_time) \\\n + begin_index_extension.substitute(bindex=begin_index)\n\n\ndef account_url(name):\n return raw_url_summoner_id.substitute(name=name)\n"
}
] | 6 |
Aragogs/spider | https://github.com/Aragogs/spider | 7a5ab9fc676b66de47fecb9f131f78b4d97e4952 | cd1904d7735866080c9352091c512ea32399b63e | 57fc5e3267cdf458b25648a7c56241f06e4be6d1 | refs/heads/master | 2020-03-06T21:51:09.823371 | 2018-05-18T08:36:38 | 2018-05-18T08:36:38 | 127,088,250 | 1 | 2 | null | null | null | null | null | [
{
"alpha_fraction": 0.765625,
"alphanum_fraction": 0.765625,
"avg_line_length": 20.16666603088379,
"blob_id": "769c3b70b295c6b45cda714ab7b4de406c5a011f",
"content_id": "36a0f8bfa751fcc1625340256cd2efe31152e17d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 128,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 6,
"path": "/spider-demo/baoxian/baoxian_spider/pingan/spider/verify_code.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "import pytesseract\nfrom PIL import Image\n\nimage = Image.open('data.png')\ncode = pytesseract.image_to_string(image)\nprint(code)\n\n"
},
{
"alpha_fraction": 0.5122969746589661,
"alphanum_fraction": 0.5656612515449524,
"avg_line_length": 40.44230651855469,
"blob_id": "7c7dfe687a6344d5f7b9eb824fc08a7df77d1ed2",
"content_id": "b6655f9d2520d2488efbdc2016ea0d2c754fc747",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4358,
"license_type": "permissive",
"max_line_length": 217,
"num_lines": 104,
"path": "/spider-demo/baoxian/baoxian_spider/pingan/spider/baoxian.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "import requests\nimport pytesseract\nfrom PIL import Image\nimport time\n\n\n'''平安寿险测试'''\n\ndef get_cookie():\n\n url = 'http://property.pingan.com/property_insurance/pa18AutoInquiry/validatePolicy/guaran_check2.jsp?actionType=1&policyNo=10127003900409594150&validateNo=vPVX8b56vtv8ZgT97H'\n\n headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-CN,zh;q=0.9',\n 'Cache-Control':'max-age=0',\n 'Host':'property.pingan.com',\n 'Proxy-Connection':'keep-alive',\n 'Upgrade-Insecure-Requests':'1',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}\n\n data = requests.get(url,headers = headers)\n cookie = data.headers['Set-Cookie']\n fin_cookie = cookie.replace('; path=/', '').replace('HttpOnly, ', '')\n print(fin_cookie)\n\n return fin_cookie\n\n'''得到验证码'''\n\ndef get_verify_code(fin_cookie):\n\n\n verify_code_url = 'http://property.pingan.com/property_insurance/pa18AutoInquiry/rand.do'\n\n verify_headers = {'Accept':'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-CN,zh;q=0.9',\n 'Host':'property.pingan.com',\n 'Proxy-Connection':'keep-alive',\n 'Referer':'http://property.pingan.com/property_insurance/pa18AutoInquiry/validatePolicy/guaran_check2.jsp?actionType=1&policyNo=10127003900409594150&validateNo=vPVX8b56vtv8ZgT97H',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n 'Cookie':'%s' % fin_cookie\n }\n\n pic_data = requests.get(verify_code_url,headers = verify_headers)\n pic_info = pic_data.content\n\n file_name = 'data' +'.jpg '\n\n with open(file_name, 'wb') as file:\n file.write(pic_data.content)\n\n image = Image.open('data.jpg')\n code = pytesseract.image_to_string(image)\n print(code)\n\n return code\n\n\n'''测试能否行得通'''\n\ndef test_code (fin_cookie,code):\n\n # verify_code = input('请输入验证码:', )\n\n post_url = 'http://property.pingan.com/property_insurance/pa18AutoInquiry/validatePolicy/validatePolicy.do?action=validateInfoAsh'\n\n verify_code_test_headers = { 'Host': 'property.pingan.com',\n 'Proxy-Connection': 'keep-alive',\n 'Content-Length': '122',\n 'Cache-Control': 'max-age=0',\n 'Origin': 'http://property.pingan.com',\n 'Upgrade-Insecure-Requests': '1',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Referer': 'http://property.pingan.com/property_insurance/pa18AutoInquiry/validatePolicy/guaran_check2.jsp?actionType=1&policyNo=10127003900409594150&validateNo=vPVX8b56vtv8ZgT97H',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Cookie': '%s' % fin_cookie\n }\n\n post_info = 'inputType=0&inputType_2=4.0&policyNo=10127003900409594150&appCertNo=&certNo=&validateNo=vPVX8b56vtv8ZgT97H&verifyCode=%s' % code\n\n tested_data = requests.post(post_url, post_info, headers=verify_code_test_headers)\n print(tested_data.text)\n\n return tested_data.text\n\nif __name__ == '__main__':\n\n def main():\n\n fin_cookie = get_cookie()\n time.sleep(1)\n\n code = get_verify_code(fin_cookie)\n time.sleep(1)\n\n test_code(fin_cookie, code)\n\n\n main()\n"
},
{
"alpha_fraction": 0.6551172733306885,
"alphanum_fraction": 0.6823027729988098,
"avg_line_length": 29.274192810058594,
"blob_id": "1261d4e4576e937abf8f8246faaff6d786e8f00f",
"content_id": "9a27065e6737a1d6580de789247caacdd9a7bc9a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2338,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 62,
"path": "/spider-env/爬虫开发环境说明.md",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "Author:袁浪/齐向阳\nDate:2018/4/2\nVersion: 1.0\n--\n#爬虫开发环境说明\n1. anaconda安装\n\t* Anaconda 官网下载地址:https://www.continuum.io/downloads \n\t* 下载anaconda稳定版本 Anaconda3- 4.2.0\n\n2. python安装\n\t* 创建一个名为python的环境,指定Python版本是3.5\n\t> conda create --name python python=3.5\n\n\t* 安装好后,使用activate激活某个环境\n\t> activate python #for windows\n\t> source activate python # for Linux & Mac\n\n\t* 切换pyhon版本环境\n\t> deactivate python # for Windows\n\t> source deactivate python # for Linux & Mac\n\t* 删除一个已有的环境\n\t> conda remove --name python --all\n3. ide环境安装\n\tpycharm下载地址:https://www.jetbrains.com/pycharm/download/#section=windows\n\n3. 爬虫所需环境安装\n * python安装模块 scrapy(爬虫框架) scrapy_redis(分布式爬虫) mongopy pymysql openpyxl(excel操作模块) 等等模块 ...\n\n4. scrapy api文档\n\thttp://scrapy-chs.readthedocs.io/zh_CN/latest/intro/tutorial.html\n\t\n5. html Parser\n Parser: from lxml import etree dom_tree = etree.HTML(response) data = dom_tree.xpath('')\n \n6. 数据存储、抽取、清洗流程需要用到的工具:\n\n MongoDB\n * MongoDB 下载地址:https://www.mongodb.com/download-center#community #Version: MongoDB 3.6\n * MongoDB GUI:Studio 3T Non-commercial\n \n Kettle-Spoon(ETL)\n * 下载地址:https://sourceforge.net/projects/pentaho/files/Data%20Integration/7.0/\n * Spoon Version :7.0.0.0\n * 安装注意事项:\n 1. 安装:解压缩到任意本地路径即可\n 2. 环境:需要JDK,需要mysql的驱动jar包 下载地址:http://mvnrepository.com/artifact/mysql/mysql-connector-java Version ava-5.1.41\n \n Mysql\n * Mysql 下载地址:http://rj.baidu.com/soft/detail/12585.html?ald\n * Mysql GUI:Navicat Premium Version 12.0.18 \n \n Redis\n * Redis 下载地址:https://github.com/MicrosoftArchive/redis/releases\n * Redis 安装配置方式:http://www.runoob.com/redis/redis-install.html\n * Redis GUI:RedisDesktopManager 下载地址:https://redisdesktop.com/download \n \n 7. 其他常用工具:\n \n 文本编辑器:notepad++\n 终端模拟器:Xshell\n FTP:Xftp\n Markdown编辑器:Typora"
},
{
"alpha_fraction": 0.5322580933570862,
"alphanum_fraction": 0.6290322542190552,
"avg_line_length": 6.875,
"blob_id": "62880b16d6d17cfd89e1f0e73070f095ba2a331a",
"content_id": "437d53820b38f9fc834a404691075768165847ed",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 110,
"license_type": "permissive",
"max_line_length": 14,
"num_lines": 8,
"path": "/README.md",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "### Python爬虫内容\n\n1. 分布式框架\n2. 代理池\n3. 验证码\n4. 数据加解密\n5. 数据存储\n6. ETL"
},
{
"alpha_fraction": 0.4307692348957062,
"alphanum_fraction": 0.6461538672447205,
"avg_line_length": 14.5,
"blob_id": "2aeb5c1a72d87b8bd7cb5170bfd720d090f26a93",
"content_id": "f6f00efd97138d5859c19b83c625f32c3b153887",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 65,
"license_type": "permissive",
"max_line_length": 18,
"num_lines": 4,
"path": "/spider-tool/proxy_pool-master/requirements.txt",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "APScheduler==3.2.0\nFlask==0.11.1\nrequests==2.11.0\nlxml==3.7.1\n\n\n\n"
},
{
"alpha_fraction": 0.5861597657203674,
"alphanum_fraction": 0.7338621616363525,
"avg_line_length": 69.21154022216797,
"blob_id": "9a49dbd293000e8e444abae517ca96f54ab6617f",
"content_id": "a7f26c1edd5ab1dacfabbfc741e5f52ce4bac5bd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3742,
"license_type": "permissive",
"max_line_length": 423,
"num_lines": 52,
"path": "/spider-demo/wechat_demo/test.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "\n'''\n通过接口访问北京拆哪公众号\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nimport time\n\nwhile True:\n url=\"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTYxNTg3NA==&scene=124&devicetype=android-22&version=26051633&lang=zh_CN&nettype=WIFI&a8scene=1&pass_ticket=Q8Q1WRz0SHnytsBiee6vhbrTwMxLU8WxBW6qguRY12i1EQ727rP%2Ffy8DCAm1JnGN&wx_header=1\"\n headers={\n \"Host\":\"mp.weixin.qq.com\",\n \"Connection\":\"keep-alive\",\n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 5.1; MX4 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/043909 Mobile Safari/537.36 MicroMessenger/6.5.22.1160 NetType/WIFI Language/zh_CN\",\n #\"x-wechat-key\": \"195f5369276b3268a517c533661e87df71e44a00121f29e421ba75588fbef43fa9a4530b19b0cf0d2d705d5dff54d31f21fea325c1816927b927ca3bb6538e1bf6230bc1752e3b96549488600ea8eb4f\",\n \"x-wechat-key\": \"b3aaf236e5f9a333a1b35c83bff9665db4976a56d07c8a421297df77158ebeeb50e821bca0fff99c7c5df96c1913d0caf310a2dcd863b3628dde84021d5154d7a531984221ecb83bb7b67705dd2014dd\",\n \"x-wechat-uin\": \"MjUxODExNDYzMQ%3D%3D\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,image/wxpic,image/sharpp,image/apng,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,en-US;q=0.8\",\n #\"Cookie\":\"rewardsn=; wxuin=2518114631; devicetype=android-22; version=26051633; lang=zh_CN; pass_ticket=Q8Q1WRz0SHnytsBiee6vhbrTwMxLU8WxBW6qguRY12i1EQ727rP/fy8DCAm1JnGN; wap_sid2=CMfC3bAJElxaZzRuNjN6bW53OU1ZSDI4OWdNTlpzQlFhc1FVaUFmTjJGUHVjazVYbFFQRS0tdk9vLUsxU2NWTGtmVEVldXVzV1ZEY2dBd1JsNTViTW45cFdVRGlEcmNEQUFBfjCTvqHWBTgNQAE=; wxtokenkey=777\",\n \"Cookie\": \"rewardsn=; wxuin=2518114631; devicetype=android-22; version=26051633; lang=zh_CN; pass_ticket=Q8Q1WRz0SHnytsBiee6vhbrTwMxLU8WxBW6qguRY12i1EQ727rP/fy8DCAm1JnGN; wap_sid2=CMfC3bAJElxQTnNYdzdXdU1WdTF6UHA5MXh1cVVDbGZGc19vb3NkTUJCQmVMZnZQSndEMGxrVVc1ejdTQVM1QkZCWkNlX2QwTmpPaVByeGFNdDdTX3lqNHg5TTRXYmNEQUFBfjCWmKHWBTgNQAE=; wxtokenkey=777\",\n \"Q-UA2\": \"QV=3&PL=ADR&PR=WX&PP=com.tencent.mm&PPVN=6.5.22&TBSVC=43602&CO=BK&COVC=043909&PB=GE&VE=GA&DE=PHONE&CHID=0&LCID=9422&MO= MX4 &RL=1152*1920&OS=5.1&API=22\",\n \"Q-GUID\": \"56bb6324d5fcb44d8dcdaff613b788cb\",\n \"Q-Auth\": \"31045b957cf33acf31e40be2f3e71c5217597676a9729f1b\"\n }\n response=requests.get(url=url,headers=headers,verify=False)\n if \"操作频繁\" in response.text:\n print(\"操作频繁,等会试一试\")\n break\n if \"验证\" in response.text:\n print(\"x-wechat-key 已失效,需要重新获取\")\n break\n else:\n list_str = re.search(\"var msgList =.*'(.*?)';\", response.text).group(1).replace(\""\", \"\\\"\")\n # print(list_str)\n # print(response.headers)\n json = json.loads(list_str)\n for item in json[\"list\"]:\n # print(item[\"app_msg_ext_info\"][\"cover\"].replace(\"\\\\\",\"\"))\n print(item[\"app_msg_ext_info\"][\"content_url\"].replace(\"\\\\\", \"\"))\n\n urll = \"https://mp.weixin.qq.com/s?__biz=MzI2MTYxNTg3NA==&mid=2247484248&idx=1&sn=16968437d177a24cebb3f55669856193&chksm=ea56fb35dd21722392ed13506aaf6495165dbe9a4587dacc4274c5060fb8e3dde63b0923377e&scene=38&ascene=0&devicetype=android-22&version=26051633&nettype=WIFI&abtest_cookie=BQABAAgACgALAAwADQALAJ6GHgCdih4ApYoeAD6LHgDUix4A5IseABCMHgCljB4AuoweAL6MHgDQjB4AAAA%3D&lang=zh_CN&pass_ticket=Q8Q1WRz0SHnytsBiee6vhbrTwMxLU8WxBW6qguRY12i1EQ727rP%2Ffy8DCAm1JnGN&wx_header=1\"\n response2 = requests.get(url=urll, headers=headers, verify=False)\n html = BeautifulSoup(response2.text)\n activity_name = html.find(\"h2\", {\"id\": \"activity-name\"}).text\n print(\"解析成功--------》\" + activity_name)\n\n\n print(time.localtime(time.time()))\n time.sleep(5)\n\n\n\n\n"
},
{
"alpha_fraction": 0.7947266101837158,
"alphanum_fraction": 0.8131672739982605,
"avg_line_length": 25.650861740112305,
"blob_id": "0081fc235905dc4beb4c03441885ef33f52e622d",
"content_id": "5a9366280bd22c7e255ab97a891e398d20196e08",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 11508,
"license_type": "permissive",
"max_line_length": 151,
"num_lines": 232,
"path": "/spider-file/Python 爬虫的工具列表.md",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "#Python 爬虫的工具列表\n这个列表包含与网页抓取和数据处理的Python库\n网络\n网络爬虫框架\nHTML/XML解析器\n文本处理\n特定格式文件处理\n自然语言处理\n浏览器自动化与仿真\n多重处理\n异步\n队列\n云计算\n电子邮件\n网址和网络地址操作\n网页内容提取\nWebSocket\nDNS解析\n计算机视觉\n代理服务器\n其他Python工具列表\n\n原文地址:http://mp.weixin.qq.com/s?__biz=MzA3MDg5MTA4NQ==&mid=404864725&idx=2&sn=0707c43cb81d9748e42785c0bac33802&scene=1&srcid=0214k4lF1SBbnjIPknNR7LRz#rd\n\n###1.网络\n通用\nurllib -网络库(stdlib)。\nrequests -网络库。\ngrab – 网络库(基于pycurl)。\npycurl – 网络库(绑定libcurl)。\nurllib3 – Python HTTP库,安全连接池、支持文件post、可用性高。\nhttplib2 – 网络库。\nRoboBrowser – 一个简单的、极具Python风格的Python库,无需独立的浏览器即可浏览网页。\nMechanicalSoup -一个与网站自动交互Python库。\nmechanize -有状态、可编程的Web浏览库。\nsocket – 底层网络接口(stdlib)。\nUnirest for Python – Unirest是一套可用于多种语言的轻量级的HTTP库。\nhyper – Python的HTTP/2客户端。\nPySocks – SocksiPy更新并积极维护的版本,包括错误修复和一些其他的特征。作为socket模块的直接替换。\n异步\ntreq – 类似于requests的API(基于twisted)。\naiohttp – asyncio的HTTP客户端/服务器(PEP-3156)。\n###2.网络爬虫框架\n功能齐全的爬虫\ngrab – 网络爬虫框架(基于pycurl/multicur)。\nscrapy – 网络爬虫框架(基于twisted),不支持Python3。\npyspider – 一个强大的爬虫系统。\ncola – 一个分布式爬虫框架。\n其他\nportia – 基于Scrapy的可视化爬虫。\nrestkit – Python的HTTP资源工具包。它可以让你轻松地访问HTTP资源,并围绕它建立的对象。\ndemiurge – 基于PyQuery的爬虫微框架。\n###3.HTML/XML解析器\n通用\nlxml – C语言编写高效HTML/ XML处理库。支持XPath。\ncssselect – 解析DOM树和CSS选择器。\npyquery – 解析DOM树和jQuery选择器。\nBeautifulSoup – 低效HTML/ XML处理库,纯Python实现。\nhtml5lib – 根据WHATWG规范生成HTML/ XML文档的DOM。该规范被用在现在所有的浏览器上。\nfeedparser – 解析RSS/ATOM feeds。\nMarkupSafe – 为XML/HTML/XHTML提供了安全转义的字符串。\nxmltodict – 一个可以让你在处理XML时感觉像在处理JSON一样的Python模块。\nxhtml2pdf – 将HTML/CSS转换为PDF。\nuntangle – 轻松实现将XML文件转换为Python对象。\n清理\nBleach – 清理HTML(需要html5lib)。\nsanitize – 为混乱的数据世界带来清明。\n###4.文本处理\n用于解析和操作简单文本的库。\n通用\ndifflib – (Python标准库)帮助进行差异化比较。\nLevenshtein – 快速计算Levenshtein距离和字符串相似度。\nfuzzywuzzy – 模糊字符串匹配。\nesmre – 正则表达式加速器。\nftfy – 自动整理Unicode文本,减少碎片化。\n转换\nunidecode – 将Unicode文本转为ASCII。\n字符编码\nuniout – 打印可读字符,而不是被转义的字符串。\nchardet – 兼容 Python的2/3的字符编码器。\nxpinyin – 一个将中国汉字转为拼音的库。\npangu.py – 格式化文本中CJK和字母数字的间距。\nSlug化\nawesome-slugify – 一个可以保留unicode的Python slugify库。\npython-slugify – 一个可以将Unicode转为ASCII的Python slugify库。\nunicode-slugify – 一个可以将生成Unicode slugs的工具。\npytils – 处理俄语字符串的简单工具(包括pytils.translit.slugify)。\n通用解析器\nPLY – lex和yacc解析工具的Python实现。\npyparsing – 一个通用框架的生成语法分析器。\n人的名字\npython-nameparser -解析人的名字的组件。\n电话号码\nphonenumbers -解析,格式化,存储和验证国际电话号码。\n用户代理字符串\npython-user-agents – 浏览器用户代理的解析器。\nHTTP Agent Parser – Python的HTTP代理分析器。\n###5.特定格式文件处理\n解析和处理特定文本格式的库。\n通用\ntablib – 一个把数据导出为XLS、CSV、JSON、YAML等格式的模块。\ntextract – 从各种文件中提取文本,比如 Word、PowerPoint、PDF等。\nmessytables – 解析混乱的表格数据的工具。\nrows – 一个常用数据接口,支持的格式很多(目前支持CSV,HTML,XLS,TXT – 将来还会提供更多!)。\nOffice\npython-docx – 读取,查询和修改的Microsoft Word2007/2008的docx文件。\nxlwt / xlrd – 从Excel文件读取写入数据和格式信息。\nXlsxWriter – 一个创建Excel.xlsx文件的Python模块。\nxlwings – 一个BSD许可的库,可以很容易地在Excel中调用Python,反之亦然。\nopenpyxl – 一个用于读取和写入的Excel2010 XLSX/ XLSM/ xltx/ XLTM文件的库。\nMarmir – 提取Python数据结构并将其转换为电子表格。\nPDF\nPDFMiner – 一个从PDF文档中提取信息的工具。\nPyPDF2 – 一个能够分割、合并和转换PDF页面的库。\nReportLab – 允许快速创建丰富的PDF文档。\npdftables – 直接从PDF文件中提取表格。\nMarkdown\nPython-Markdown – 一个用Python实现的John Gruber的Markdown。\nMistune – 速度最快,功能全面的Markdown纯Python解析器。\nmarkdown2 – 一个完全用Python实现的快速的Markdown。\nYAML\nPyYAML – 一个Python的YAML解析器。\nCSS\ncssutils – 一个Python的CSS库。\nATOM/RSS\nfeedparser – 通用的feed解析器。\nSQL\nsqlparse – 一个非验证的SQL语句分析器。\nHTTP\nHTTP\nhttp-parser – C语言实现的HTTP请求/响应消息解析器。\n微格式\nopengraph – 一个用来解析Open Graph协议标签的Python模块。\n可移植的执行体\npefile – 一个多平台的用于解析和处理可移植执行体(即PE)文件的模块。\nPSD\npsd-tools – 将Adobe Photoshop PSD(即PE)文件读取到Python数据结构。\n###6.自然语言处理\n处理人类语言问题的库。\nNLTK -编写Python程序来处理人类语言数据的最好平台。\nPattern – Python的网络挖掘模块。他有自然语言处理工具,机器学习以及其它。\nTextBlob – 为深入自然语言处理任务提供了一致的API。是基于NLTK以及Pattern的巨人之肩上发展的。\njieba – 中文分词工具。\nSnowNLP – 中文文本处理库。\nloso – 另一个中文分词库。\ngenius – 基于条件随机域的中文分词。\nlangid.py – 独立的语言识别系统。\nKorean – 一个韩文形态库。\npymorphy2 – 俄语形态分析器(词性标注+词形变化引擎)。\nPyPLN – 用Python编写的分布式自然语言处理通道。这个项目的目标是创建一种简单的方法使用NLTK通过网络接口处理大语言库。\n###7.浏览器自动化与仿真\nselenium – 自动化真正的浏览器(Chrome浏览器,火狐浏览器,Opera浏览器,IE浏览器)。\nGhost.py – 对PyQt的webkit的封装(需要PyQT)。\nSpynner – 对PyQt的webkit的封装(需要PyQT)。\nSplinter – 通用API浏览器模拟器(selenium web驱动,Django客户端,Zope)。\n###8.多重处理\nthreading – Python标准库的线程运行。对于I/O密集型任务很有效。对于CPU绑定的任务没用,因为python GIL。\nmultiprocessing – 标准的Python库运行多进程。\ncelery – 基于分布式消息传递的异步任务队列/作业队列。\nconcurrent-futures – concurrent-futures 模块为调用异步执行提供了一个高层次的接口。\n###9.异步\n异步网络编程库\nasyncio – (在Python 3.4 +版本以上的 Python标准库)异步I/O,时间循环,协同程序和任务。\nTwisted – 基于事件驱动的网络引擎框架。\nTornado – 一个网络框架和异步网络库。\npulsar – Python事件驱动的并发框架。\ndiesel – Python的基于绿色事件的I/O框架。\ngevent – 一个使用greenlet 的基于协程的Python网络库。\neventlet – 有WSGI支持的异步框架。\nTomorrow – 异步代码的奇妙的修饰语法。\n###10.队列\ncelery – 基于分布式消息传递的异步任务队列/作业队列。\nhuey – 小型多线程任务队列。\nmrq – Mr. Queue – 使用redis & Gevent 的Python分布式工作任务队列。\nRQ – 基于Redis的轻量级任务队列管理器。\nsimpleq – 一个简单的,可无限扩展,基于Amazon SQS的队列。\npython-gearman – Gearman的Python API。\n###11.云计算\npicloud – 云端执行Python代码。\ndominoup.com – 云端执行R,Python和matlab代码。\n###12.电子邮件\n电子邮件解析库\nflanker – 电子邮件地址和Mime解析库。\nTalon – Mailgun库用于提取消息的报价和签名。\n###13.网址和网络地址操作\n解析/修改网址和网络地址库。\nURL\nfurl – 一个小的Python库,使得操纵URL简单化。\npurl – 一个简单的不可改变的URL以及一个干净的用于调试和操作的API。\nurllib.parse – 用于打破统一资源定位器(URL)的字符串在组件(寻址方案,网络位置,路径等)之间的隔断,为了结合组件到一个URL字符串,并将“相对URL”转化为一个绝对URL,称之为“基本URL”。\ntldextract – 从URL的注册域和子域中准确分离TLD,使用公共后缀列表。\n网络地址\nnetaddr – 用于显示和操纵网络地址的Python库。\n\n###14.网页内容提取\n提取网页内容的库。\nHTML页面的文本和元数据\nnewspaper – 用Python进行新闻提取、文章提取和内容策展。\nhtml2text – 将HTML转为Markdown格式文本。\npython-goose – HTML内容/文章提取器。\nlassie – 人性化的网页内容检索工具\nmicawber – 一个从网址中提取丰富内容的小库。\nsumy -一个自动汇总文本文件和HTML网页的模块\nHaul – 一个可扩展的图像爬虫。\npython-readability – arc90 readability工具的快速Python接口。\nscrapely – 从HTML网页中提取结构化数据的库。给出了一些Web页面和数据提取的示例,scrapely为所有类似的网页构建一个分析器。\n视频\nyoutube-dl – 一个从YouTube下载视频的小命令行程序。\nyou-get – Python3的YouTube、优酷/ Niconico视频下载器。\n维基\nWikiTeam – 下载和保存wikis的工具。\n###15.WebSocket\n用于WebSocket的库。\nCrossbar – 开源的应用消息传递路由器(Python实现的用于Autobahn的WebSocket和WAMP)。\nAutobahnPython – 提供了WebSocket协议和WAMP协议的Python实现并且开源。\nWebSocket-for-Python – Python 2和3以及PyPy的WebSocket客户端和服务器库。\n###16.DNS解析\ndnsyo – 在全球超过1500个的DNS服务器上检查你的DNS。\npycares – c-ares的接口。c-ares是进行DNS请求和异步名称决议的C语言库。\n###17.计算机视觉\nOpenCV – 开源计算机视觉库。\nSimpleCV – 用于照相机、图像处理、特征提取、格式转换的简介,可读性强的接口(基于OpenCV)。\nmahotas – 快速计算机图像处理算法(完全使用 C++ 实现),完全基于 numpy 的数组作为它的数据类型。\n###18.代理服务器\nshadowsocks – 一个快速隧道代理,可帮你穿透防火墙(支持TCP和UDP,TFO,多用户和平滑重启,目的IP黑名单)。\ntproxy – tproxy是一个简单的TCP路由代理(第7层),基于Gevent,用Python进行配置。\n###19.其他Python工具列表\nawesome-python\npycrumbs\npython-github-projects\npython_reference\npythonidae"
},
{
"alpha_fraction": 0.5507672429084778,
"alphanum_fraction": 0.5609974265098572,
"avg_line_length": 30.035715103149414,
"blob_id": "a2cd61fd47562cf18bee146efbfa04c4e67e17fe",
"content_id": "8f47b2f88ccd26e7ed0fb81f2878456f0cd05873",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9420,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 252,
"path": "/spider-demo/wechat_demo/test2.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n# coding: utf-8\n\n''''' \nPhantomJS+selenimu访问微信公众号\n通过搜狗搜索中的微信搜索入口来爬取 \n2017-04-12 by lang \n'''\nfrom urllib.parse import quote\nfrom pyquery import PyQuery as pq\nfrom selenium import webdriver\nfrom openpyxl import Workbook\n\nimport requests\nimport time\nimport re\nimport json\nimport os\n\n\nclass weixin_spider:\n def __init__(self, keywords):\n ' 构造函数 '\n self.keywords = keywords\n # 搜狐微信搜索链接入口\n # self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_=' % quote(self.keywords)\n self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=' % quote(\n self.keywords)\n\n # 爬虫伪装头部设置\n self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}\n\n # 设置操作超时时长\n self.timeout = 5\n\n # 爬虫模拟在一个request.session中完成\n self.s = requests.Session()\n\n # excel 第一行数据\n self.excel_data = [u'编号', u'时间', u'文章标题', u'文章地址', u'文章简介']\n # 定义excel操作句柄\n self.excle_w = Workbook()\n\n\n # 搜索入口地址,以公众为关键字搜索该公众号\n\n def get_search_result_by_keywords(self):\n self.log('搜索地址为:%s' % self.sogou_search_url)\n return self.s.get(self.sogou_search_url, headers=self.headers, timeout=self.timeout).content\n\n # 获得公众号主页地址\n\n def get_wx_url_by_sougou_search_html(self, sougou_search_html):\n doc = pq(sougou_search_html)\n # print doc('p[class=\"tit\"]')('a').attr('href')\n # print doc('div[class=img-box]')('a').attr('href')\n # 通过pyquery的方式处理网页内容,类似用beautifulsoup,但是pyquery和jQuery的方法类似,找到公众号主页地址\n return doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')\n\n # 使用webdriver 加载公众号主页内容,主要是js渲染的部分\n\n def get_selenium_js_html(self, url):\n browser = webdriver.PhantomJS(executable_path='D:\\\\system\\\\phantomjs-2.1.1-windows\\\\bin\\\\phantomjs.exe')\n browser.get(url)\n time.sleep(3)\n # 执行js得到整个页面内容\n html = browser.execute_script(\"return document.documentElement.outerHTML\")\n return html\n # 获取公众号文章内容\n\n def parse_wx_articles_by_html(self, selenium_html):\n doc = pq(selenium_html)\n print\n '开始查找内容msg'\n return doc('div[class=\"weui_media_box appmsg\"]')\n\n # 有的公众号仅仅有10篇文章,有的可能多一点\n # return doc('div[class=\"weui_msg_card\"]')#公众号只有10篇文章文章的\n\n # 将获取到的文章转换为字典\n def switch_arctiles_to_list(self, articles):\n # 定义存贮变量\n articles_list = []\n i = 1\n\n # 以当前时间为名字建表\n excel_sheet_name = time.strftime('%Y-%m-%d')\n excel_content = self.excle_w.create_sheet(excel_sheet_name)\n\n # 遍历找到的文章,解析里面的内容\n if articles:\n for article in articles.items():\n self.log(u'开始整合(%d/%d)' % (i, len(articles)))\n # 处理单个文章\n articles_list.append(self.parse_one_article(article, i, excel_content))\n i += 1\n return articles_list\n # 解析单篇文章\n\n def parse_one_article(self, article, i, excel_content):\n article_dict = {}\n\n # 获取标题\n title = article('h4[class=\"weui_media_title\"]').text()\n self.log('标题是: %s' % title)\n # 获取标题对应的地址\n url = 'http://mp.weixin.qq.com' + article('h4[class=\"weui_media_title\"]').attr('hrefs')\n self.log('地址为: %s' % url)\n # 获取概要内容\n summary = article('.weui_media_desc').text()\n self.log('文章简述: %s' % summary)\n # 获取文章发表时间\n date = article('.weui_media_extra_info').text()\n self.log('发表时间为: %s' % date)\n # 获取封面图片\n pic = self.parse_cover_pic(article)\n # 获取文章内容\n content = self.parse_content_by_url(url).html()\n # 存储文章到本地\n contentfiletitle = self.keywords + '/' + title + '_' + date + '.html'\n self.save_content_file(contentfiletitle, content)\n\n # 将这些简单的信息保存成excel数据\n cols = 0\n tempContent = [i, date, title, url, summary]\n for data in self.excel_data:\n # excel_content.append(0, cols, data)\n # excel_content.append(i, cols, tempContent[cols])\n excel_content.append(tempContent)\n\n cols += 1\n self.excle_w.save(self.keywords + '/' + self.keywords + '.xls')\n\n # 返回字典数据\n return {\n 'title': title,\n 'url': url,\n 'summary': summary,\n 'date': date,\n 'pic': pic,\n 'content': content\n }\n\n # 查找封面图片,获取封面图片地址\n\n def parse_cover_pic(self, article):\n pic = article('.weui_media_hd').attr('style')\n\n p = re.compile(r'background-image:url(.∗?)')\n rs = p.findall(pic)\n self.log('封面图片是:%s ' % rs[0] if len(rs) > 0 else '')\n\n return rs[0] if len(rs) > 0 else ''\n # 获取文章页面详情\n\n def parse_content_by_url(self, url):\n page_html = self.get_selenium_js_html(url)\n return pq(page_html)('#js_content')\n\n # 存储文章到本地\n\n def save_content_file(self, title, content):\n print(title)\n print(content)\n # with open(title, 'w') as f:\n # f.write(content)\n\n # 存贮json数据到本地\n\n def save_file(self, content):\n ' 数据写入文件 '\n with open(self.keywords + '/' + self.keywords + '.txt', 'w') as f:\n f.write(content)\n # 自定义log函数,主要是加上时间\n\n def log(self, msg):\n print(u'%s: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), msg))\n # 验证函数\n\n def need_verify(self, selenium_html):\n ' 有时候对方会封锁ip,这里做一下判断,检测html中是否包含id=verify_change的标签,有的话,代表被重定向了,提醒过一阵子重试 '\n return pq(selenium_html)('#verify_change').text() != ''\n # 创建公众号命名的文件夹\n\n def create_dir(self):\n if not os.path.exists(self.keywords):\n os.makedirs(self.keywords)\n\n # 爬虫主函数\n\n def run(self):\n ' 爬虫入口函数 '\n # Step 0 : 创建公众号命名的文件夹\n self.create_dir()\n\n # Step 1:GET请求到搜狗微信引擎,以微信公众号英文名称作为查询关键字\n self.log(u'开始获取,微信公众号英文名为:%s' % self.keywords)\n self.log(u'开始调用sougou搜索引擎')\n sougou_search_html = self.get_search_result_by_keywords()\n\n # Step 2:从搜索结果页中解析出公众号主页链接\n self.log(u'获取sougou_search_html成功,开始抓取公众号对应的主页wx_url')\n wx_url = self.get_wx_url_by_sougou_search_html(sougou_search_html)\n self.log(u'获取wx_url成功,%s' % wx_url)\n\n # Step 3:Selenium+PhantomJs获取js异步加载渲染后的html\n self.log(u'开始调用selenium渲染html')\n selenium_html = self.get_selenium_js_html(wx_url)\n\n # Step 4: 检测目标网站是否进行了封锁\n if self.need_verify(selenium_html):\n self.log(u'爬虫被目标网站封锁,请稍后再试')\n else:\n # Step 5: 使用PyQuery,从Step 3获取的html中解析出公众号文章列表的数据\n self.log(u'调用selenium渲染html完成,开始解析公众号文章')\n articles = self.parse_wx_articles_by_html(selenium_html)\n self.log(u'抓取到微信文章%d篇' % len(articles))\n\n # Step 6: 把微信文章数据封装成字典的list\n self.log(u'开始整合微信文章数据为字典')\n articles_list = self.switch_arctiles_to_list(articles)\n\n # Step 7: 把Step 5的字典list转换为Json\n self.log(u'整合完成,开始转换为json')\n data_json = json.dumps(articles_list)\n\n # Step 8: 写文件\n self.log(u'转换为json完成,开始保存json数据到文件')\n self.save_file(data_json)\n\n self.log(u'保存完成,程序结束')\n\n # main\n\n\n# 几个可供参考的公众号\n# DataBureau\n# python6359\n# ArchNotes\nif __name__ == '__main__':\n print(\n ''''' \n ***************************************** \n ** Welcome to Spider of 公众号 ** \n ** Created on 2018-04-12 ** \n ** @author: yuanlang ** \n ***************************************** \n ''')\n gongzhonghao = input(u'输入要爬取的公众号')\n if not gongzhonghao:\n gongzhonghao = 'python6359'\n weixin_spider(gongzhonghao).run()"
},
{
"alpha_fraction": 0.5127245783805847,
"alphanum_fraction": 0.6152694821357727,
"avg_line_length": 39.51515197753906,
"blob_id": "1f56884ff4f4beeccff055a3fb4829957e0f305e",
"content_id": "acbab0e2d0e56e5a80fa3ccf0cd8e6b31e2185d7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1336,
"license_type": "permissive",
"max_line_length": 210,
"num_lines": 33,
"path": "/spider-tool/proxy_pool-master/ProxyGetter/test_proxy_get.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "import requests\nfrom lxml import etree\nimport time\n\n\n\nheaders = {\n 'Cache-Control': 'max-age=0',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Referer': 'https://www.google.com.hk/',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'cookie': 'openState=false; UM_distinctid=1627052fd32c62-0153f8cfac08b8-3a614f0b-144000-1627052fd3348f; CNZZDATA1272080165=773347913-1522299211-https%253A%252F%252Fwww.baibianip.com%252F%7C1522299211'\n }\ndef test(headers):\n url = \"http://www.kxdaili.com/dailiip/1/{page}.html#ip\"\n for page in range(1, 10):\n page_url = url.format(page=page)\n\n data = requests.get(page_url,headers = headers)\n html = etree.HTML(data.text)\n # print(data.text)\n ip_data_list = html.xpath('//table[@class=\"ui table segment\"]/tbody/tr')\n # print(ip_data_list)\n for tr in ip_data_list:\n print(':'.join(tr.xpath('td/text()')[0:2]))\n # yield ':'.join(tr.xpath('td/text()')[0:2])\n time.sleep(1)\n\n\nprint(test(headers))"
},
{
"alpha_fraction": 0.6540880799293518,
"alphanum_fraction": 0.6582809090614319,
"avg_line_length": 14.933333396911621,
"blob_id": "21e7f2aa0fe3832f75bf33e072969367ba1837c2",
"content_id": "14ad19f87e20242f80edb1a3a0f70c12a2697a3a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 477,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 30,
"path": "/spider-demo/baoxian/baoxian_spider/pingan/verify_code/recogize_pic.py",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "import os\nimport pytesseract\nfrom PIL import Image\nimport os\nimport os.path\nimport re\nimport sys\nimport codecs\n\npath ='C:\\\\Users\\\\think5\\\\PycharmProjects\\\\dongxu\\\\baoxian\\\\get_verify_pic(pingan)\\\\pics'\nfiles = os.listdir(path)\n\nfor i in range(0,len(files)):\n\n pic_path = path+'\\\\'+files[i]\n\n\n image = Image.open(pic_path)\n\n code = pytesseract.image_to_string(image)\n\n print(code)\n\n try:\n\n os.rename(pic_path, str(code)+'.png')\n\n except:\n\n next()"
},
{
"alpha_fraction": 0.7014925479888916,
"alphanum_fraction": 0.7632293105125427,
"avg_line_length": 20.376811981201172,
"blob_id": "dc3f8604cb773c0d6cb6723647db1b3c778d60c7",
"content_id": "f3bf4be8fdf105cb35804a0835dae864bcc07948",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3610,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 69,
"path": "/spider-file/work_arrangement/爬虫工作规范及接下来的任务.md",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "# 爬虫工作任务总结\n---\n\n## 工作内容简述\n---\n日常工作中,爬虫除了满足业务的日常数据需求之外,还需着力提升爬虫工作的规范性,使得整个爬虫工作由循可依,方便后续的维护和开发。为此,本文档对爬虫工作的要点做出一些说明,并且设定相应的完成时间。\n\n工作规范:\n\n- 统一爬虫开发环境\n 负责人:齐向阳\n 完成时间:2018-03-30前\n 交付物:开发环境说明文档\n 交付内容:开发环境、工具介绍,安装方式介绍,环境变量配置介绍,测试程序,其他注意事项。\n\n- GItHub账号开设及日代码、文档维护\n负责人:袁浪/齐向阳\n完成时间:账号开通2018-03-30前完成,根据工作完成的情况,随时更新代码和文档\n交付物:项目地址、代码及说明文档\n交付内容:项目地址、GitHub配置文档\n\n- Gitlab代码、文档维护\n负责人:齐向阳/袁浪\n完成时间:根据工作完成的情况,随时更新代码和文档\n交付物:代码及说明文档\n交付内容:Gitlab配置文档\n\n具体业务:\n\n- IP代理池\n 要求:定期自动获取代理IP、验证代理有效性、提供IP代理调用接口\n 负责人:齐向阳\n 完成时间:2018-03-29\n 交付物:代码及说明文档\n 交付内容:浏览github相关项目,选定1-2个项目进行测试,根据代码健壮性及和业务契合和程度选定一个项目进行改造(代理IP高可用、自动更新、自动删除、随用随取)。\n 时间安排:\n 3.28 开源项目阅读、项目测试、选定项目、免费IP资源搜索\n 3.29 项目改造、IP来源拓展、拓展结果测试\n- APP抓包/微信公众号抓包\n 要求:完成目前常用的链家/我爱我家/保险APP/微信公众号请求分析\n 负责人:齐向阳/袁浪\n 完成时间:2018-04-10\n 交付物:代码及说明文档\n 交付内容:抓包工具及配置流程(包含监听HTTPS请求配置方法)、被监听设备说明(设备类 型:虚拟机OR手机,操作系统:安卓OR苹果,操作系统版本、APP版本)、未严格防范情况下抓包流程、严格防范抓包流程。\n 注:微信公众号抓包和APP抓包一样,交付内容一样。微信公众号是内嵌浏览器,公众号内容走HTTP协议\n 时间安排:\n 3.29-30 微信公众号抓包研究--袁浪\n 3.30 常规抓包流程总结 --齐向阳\n- 保单抓取\n 要求:完成目前主流的保险公司保单信息获取\n 保险公司名称:中国人寿保险、中国平安保险、中国人民保险、中国太平洋保险、新华人寿保险、安邦保险集团、中国太平保险、泰康人寿保险、阳光保险、友邦保险\n 负责人:齐向阳\n 完成时间:2018-04-11\n 交付物:代码及说明文档\n 交付内容:代码及说明文档\n 交付内容:请求结构、验证码破解、MongoDB建库、结果存储、请求接口。\n 时间安排:\n 4.02-4.04 完成各个网站保单信息获取代码\n 4.06 建库、存储\n 4.07-4.10 api接口设计、开发\n 4.10-412 api功能测试、bug修改\n\n- 爬虫框架\n 要求:选定一款适用于自身业务特点的开源爬虫框架\n 负责人:齐向阳/袁浪\n 完成时间:2018-04-04\n 交付物:不同框架优劣性分析(结合业务特点、数据特点、开发环境、代码健壮性、上手难度等角度分析),代码实例及说明文档\n 时间安排:\n 4.02-4.04 调研各个开源爬虫框架的应用情况,结合自身业务需求,选择最适合目前业务需求的框架。"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7192118167877197,
"avg_line_length": 12.533333778381348,
"blob_id": "728c9cc5f888297515f9d844c71cf73e24feb862",
"content_id": "0ce5d680d30b504b9e19ddb11d548c9a850ed4d6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 397,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 15,
"path": "/spider-demo/wechat_demo/微信公众号破解说明.md",
"repo_name": "Aragogs/spider",
"src_encoding": "UTF-8",
"text": "#微信公众号破解\n\n###准备工作\n* 手机连接WiFi设置代理\n* fiddler安装ssl证书\n\n###抓包演示(’北京拆哪‘公众号)\n* 点击北京拆哪公众号菜单\n* 查看fiddle截获的数据\n\t![avatar](img/1.png)\n* 模拟数据报发送,返回响应\n> 代码在test.py中\n\n###遇到的难点\n* test.py数据报中x-wechat-key具有有效期,未找到生成该参数方法\n"
}
] | 12 |
tarunkarthick/P2P-file-transfer | https://github.com/tarunkarthick/P2P-file-transfer | 78f438e68c3815108da6570e1ec73c10bf5cc6bb | 3b05a7f314823a9629d580fe99ff9d007ab3eb70 | 7f45ff6aeebc33f37a8f89e467bd4e9903c48ce7 | refs/heads/master | 2022-04-24T14:16:14.954176 | 2020-04-21T17:30:25 | 2020-04-21T17:30:25 | 257,665,494 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5078427195549011,
"alphanum_fraction": 0.5123242735862732,
"avg_line_length": 31.636985778808594,
"blob_id": "67c7b6400208fd95ef6cc69bbbfaf84fadf90850",
"content_id": "cb2fc6a255984ec77871ae5b29b92d186b0adb60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4909,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 146,
"path": "/server.py",
"repo_name": "tarunkarthick/P2P-file-transfer",
"src_encoding": "UTF-8",
"text": "import socket\r\nimport uuid\r\n#generating 4-bytes random ids\r\nimport pickle\r\n#for serializing and deserializing python object structure\r\nimport threading\r\n#creating multiple threads\r\nimport sys\r\n\r\nport=9300\r\nmax_chunk=1024\r\n\r\nclass server:\r\n def __init__(self,port,no_of_connections):\r\n self.port=port #portno of this machine\r\n self.host=socket.gethostbyname(socket.gethostname()) #ip of this machine\r\n self.no_of_connections=no_of_connections#no.of connections\r\n self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.file={}#list of files registered\r\n self.peers={}#list of peers connected\r\n\r\n x=True\r\n while x:\r\n try:\r\n self.sock.bind((self.host,self.port))\r\n except OverflowError:\r\n self.port=input(\"Enter new port(>3000)\")#alternative portno\r\n else:\r\n x=False\r\n\r\n print(\"listening through [\",self.host,\":\",self.port,\"]\")\r\n\r\n\r\n\r\n\r\n def peer_threads(self,client,addr):\r\n\r\n peer_id=uuid.uuid4().int>>115\r\n #generates unique id for each peer\r\n\r\n self.peers[peer_id]=addr\r\n #appending peer spacifications to list of peers\r\n\r\n client.send(pickle.dumps((peer_id,addr[1])))\r\n #sending peerid to the recipient and also the portno for connection\r\n\r\n\r\n while True: \r\n method=pickle.loads(client.recv(max_chunk)) \r\n\r\n print(\"Method opted by peer_id-\",peer_id,\" is \",method)\r\n\r\n if(method==\"search\"):\r\n #searching a file in the centralized directory\r\n client.send(pickle.dumps(\"ok\"))\r\n file_name=pickle.loads(client.recv(max_chunk))\r\n #loading up the name of the file needed for searching\r\n\r\n if(file_name in self.file):\r\n client.send(pickle.dumps('found'))\r\n reply=pickle.loads(client.recv(max_chunk))\r\n #getting reply from the peer whether to send or not\r\n\r\n if(reply=='send'):#peer asks to send\r\n content=pickle.dumps(self.file[file_name])\r\n client.send(content)\r\n\r\n #In case of files contained by many peers\r\n #selection of file from which peer is needed\r\n peerno=pickle.loads(client.recv(max_chunk))\r\n client.send(pickle.dumps(self.peers[peerno]))\r\n else:\r\n \"only search is done..\"\r\n else:\r\n #file not found(invalid one)\r\n client.send(pickle.dumps(\"not found\"))\r\n \r\n\r\n elif(method=='register'):\r\n #registering files to the server by peers\r\n #in order to access\r\n client.send(pickle.dumps('ok'))\r\n file_name=pickle.loads(client.recv(max_chunk))\r\n print(\"For registering file by peer_id-\",peer_id)\r\n\r\n if file_name in self.file:\r\n self.file[file_name].append(peer_id)\r\n #in case of file contained only the peerids are noted for \r\n #the file\r\n else:\r\n self.file[file_name]=[]\r\n self.file[file_name].append(peer_id)\r\n #new file list created and peerids are appended\r\n client.send(pickle.dumps('success'))\r\n\r\n elif(method=='bye'):\r\n client.send(pickle.dumps('ok'))\r\n\r\n list1=[]\r\n\r\n #peerids present in the files are deleted in file list\r\n #if file[file_name] is empty\r\n #then file_name should be deleted in register\r\n\r\n for i in self.file:\r\n try:\r\n self.file[i].remove(peer_id)\r\n if(self.file[i]==[]):\r\n list1.append(i)\r\n except ValueError:\r\n continue\r\n \r\n\r\n #peerids are deleted in peers list\r\n del self.peers[peer_id]\r\n sys.exit(0)\r\n\r\n\r\n\r\n def connections(self):\r\n thread_id=[]\r\n self.sock.listen(self.no_of_connections)\r\n \r\n while True:\r\n client,addr=self.sock.accept() #accepting connections\r\n print(\"Connected with \",addr)\r\n\r\n\r\n #thread creation for each peer\r\n try:\r\n t=threading.Thread(target=self.peer_threads,args=(client,addr))\r\n #creating threads and passing arguments\r\n t.start()\r\n #starting the thread\r\n print(\"thread started\")\r\n\r\n\r\n except:\r\n print(\"Thread didn't start\")\r\n\r\n self.sock.close()\r\n\r\n\r\nif __name__=='__main__':\r\n s=server(port,5)\r\n s.connections()"
},
{
"alpha_fraction": 0.827309250831604,
"alphanum_fraction": 0.8353413939476013,
"avg_line_length": 248,
"blob_id": "430f4b74e560df4c09793c3f1da52f40a33348c3",
"content_id": "e6cdc455663aec7f1f9f763d5df1acff9abbe0e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 248,
"num_lines": 1,
"path": "/README.md",
"repo_name": "tarunkarthick/P2P-file-transfer",
"src_encoding": "UTF-8",
"text": "P2P file transfer, a peer to peer file sharing application built using socket programming in python.Here it allows the peers to access multimedia files like videos,images and mp3 etc.The architecture used here is Centralized Directory architecture.\n"
},
{
"alpha_fraction": 0.49129512906074524,
"alphanum_fraction": 0.4954352378845215,
"avg_line_length": 34.32432556152344,
"blob_id": "64f5ee6836d6579e94ba5fc452e497e38d784de9",
"content_id": "31f053bf12ec3dc68e66a917c8533d7cbb515940",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9420,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 259,
"path": "/peer2/peer.py",
"repo_name": "tarunkarthick/P2P-file-transfer",
"src_encoding": "UTF-8",
"text": "import socket\r\nimport sys\r\nimport threading\r\nimport pickle\r\nimport traceback\r\nimport re\r\nimport queue\r\n\r\nmax_chunk=1024\r\n\r\nclass peer:\r\n def __init__(self,host,port,no_of_connections):\r\n self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.host=host#ip address of the server\r\n self.port=port#portno of the server\r\n print(\"\\n\")\r\n print(self.host,\":\",self.port)\r\n self.no_of_connections=no_of_connections#maximum no.of.connections\r\n\r\n try:\r\n self.s.connect((self.host,self.port))\r\n #trying for connection with the server\r\n except(ConnectionRefusedError):\r\n print(\"Failed to establish connetion with server\\n\")\r\n sys.exit()\r\n except(TimeoutError):\r\n print('\\npeer not responding connection failed\\n')\r\n sys.exit()\r\n else:\r\n #receiving peerid and port of the peer\r\n a=self.s.recv(max_chunk)\r\n a=pickle.loads(a)\r\n print(\"\\nConnection Established:\\nPeer_ID:\",a[0])\r\n self.peerport=a[1]#port available for this peer machine\r\n\r\n\r\n\r\n def download(self,addr,file_name):\r\n try:\r\n #downloading the file\r\n #creating a client mode\r\n self.s2=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.s2.connect(addr)\r\n self.s2.send(pickle.dumps(file_name))\r\n a=pickle.loads(self.s2.recv(max_chunk))\r\n var=False\r\n if(a=='filefound'):\r\n print(\"filefound\")\r\n self.s2.send(pickle.dumps('send'))\r\n #opening the output file\r\n file=open(file_name,'wb')\r\n txt='sent'\r\n data=self.s2.recv(max_chunk)\r\n #writing into the file\r\n while True:\r\n file.write(data)\r\n data=self.s2.recv(max_chunk)\r\n a=re.findall(txt,str(data))\r\n if(a):\r\n break\r\n file.close()\r\n self.s2.send(pickle.dumps('received'))\r\n var=True\r\n elif(a=='filenotfound'):\r\n var=False\r\n self.s2.close()\r\n except(ConnectionRefusedError):\r\n print(\"\\nConnection not able to establish with server\\n\")\r\n var=False\r\n except(TimeoutError):\r\n print(\"\\npeer not responding connection failed\")\r\n var=False\r\n return var\r\n\r\n\r\n def sendfile(self,client,addr,que):\r\n try:\r\n print(\"Preparing for sending to peer\")\r\n #sending the file from the peer\r\n #containing it\r\n file_name=client.recv(max_chunk)\r\n file_name=pickle.loads(file_name)\r\n f=open(file_name,'rb')\r\n msg='filefound'\r\n client.send(pickle.dumps(msg))\r\n acknowledge=pickle.loads(client.recv(max_chunk))\r\n if(acknowledge=='send'):\r\n #reading the file\r\n #reading max_chunk from file\r\n a=f.read(max_chunk)\r\n while(a):\r\n client.send(a)\r\n a=f.read(max_chunk)\r\n f.close()\r\n client.send(pickle.dumps('sent'))\r\n data=pickle.loads(client.recv(max_chunk))\r\n #if reply is received file is sent\r\n if(data=='received'):\r\n print(file_name+' sent')\r\n client.close()\r\n except(FileNotFoundError):\r\n a=\"Filenotfound\"\r\n client.send(pickle.dumps(a))\r\n que.put(False)\r\n except:\r\n print(\"File transfer failed\")\r\n que.put(False)\r\n else:\r\n que.put('okay')\r\n\r\n\r\n def search(self,file_name):\r\n #searching for the file in the centralized directory\r\n self.s.send(pickle.dumps('search'))\r\n a=False\r\n reply=self.s.recv(max_chunk)\r\n #reply from directory\r\n if(pickle.loads(reply)=='ok'):\r\n self.s.send(pickle.dumps(file_name))\r\n data=self.s.recv(max_chunk)\r\n data=pickle.loads(data)\r\n if(data=='found'):\r\n #asking for downloading the file\r\n proceed=input(\"\\nFile Found\\nProceed further to download(y/n)\\n\")\r\n if(proceed=='y'):\r\n self.s.send(pickle.dumps('send'))\r\n data=self.s.recv(max_chunk)\r\n data=pickle.loads(data)\r\n if(len(data)==1):\r\n #only one peer contains the file\r\n self.s.send(pickle.dumps(data[0]))\r\n else:\r\n #In case of many peers\r\n #from which peer file should be extracted \r\n #must be specified\r\n print(\"select the peer from which the file can be extracted\\n\")\r\n for i in range(len(data)):\r\n print(i+1,\"-> \",data[i])\r\n choice=int(input(\"Enter the choice of the peer:\\n\"))\r\n self.s.send(pickle.dumps(data[choice-1]))\r\n print(\"Sending the address of the peer having file\")\r\n addr=pickle.loads(self.s.recv(max_chunk))\r\n a=self.download(addr,file_name)\r\n elif(proceed=='n'):\r\n self.s.send(pickle.dumps('n'))\r\n a='sch'#only search successful\r\n elif(data=='not found'):\r\n print(\"File not found with any peer\\n\")\r\n a=False\r\n return a\r\n\r\n\r\n def seed(self):\r\n try:\r\n #making the peer for seeding\r\n self.s1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.host1=socket.gethostbyname(socket.gethostname())#host of the peer\r\n self.s1.bind((self.host1,self.peerport))\r\n self.s1.listen(self.no_of_connections)\r\n\r\n while True:\r\n #accepting clients\r\n client,addr=self.s1.accept()\r\n print(\"Connected with \"+str(addr[0]),\":\",addr[1])\r\n\r\n try:\r\n que=queue.Queue()\r\n #creating of threads for peers individually\r\n t=threading.Thread(target=self.sendfile,args=(client,addr,que))\r\n t.start()\r\n var=que.get()\r\n self.s1.close()\r\n return var\r\n except:\r\n print(\"Thread did not start\")\r\n #tracing back to normal state without halting\r\n traceback.print_exc()\r\n except(KeyboardInterrupt):\r\n print(\"seeding stopped\")\r\n return True\r\n\r\n\r\n def register(self,file_name):\r\n #for registering the file\r\n self.s.send(pickle.dumps('register'))\r\n reply=pickle.loads(self.s.recv(max_chunk))\r\n #asking for reply\r\n if(reply=='ok'):\r\n self.s.send(pickle.dumps(file_name))\r\n reply=pickle.loads(self.s.recv(max_chunk))\r\n if(reply=='success'):\r\n #asking for seeding \r\n #conformation is acknowledged\r\n proceed=input(\"File registered.\\nproceed to seed(y/n)\\n\")\r\n if(proceed=='y'):\r\n print(\"seeding mode\\n\")\r\n var=self.seed()\r\n return var\r\n else:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n\r\n def quit(self):\r\n self.s.send(pickle.dumps('bye'))\r\n if(pickle.loads(self.s.recv(max_chunk))=='ok'):\r\n self.s.close()\r\n sys.exit(0)\r\n\r\n\r\n#Entering the ip address and portno of the server\r\nip_address=input(\"\\n\\nEnter the ip address of the server\\n\")\r\nport_no=int(input(\"Enter the portno of the server\\n\"))\r\n\r\np=peer(ip_address,port_no,5)\r\n\r\n\r\nwhile True:\r\n #methods which can be done\r\n #select any one of the below\r\n print(\"\\n\\n1.Register and Seed\\n\")\r\n print(\"2.Search and Download\\n\")\r\n print(\"3.Quit\\n\")\r\n\r\n choice=int(input(\"Enter your choice(1/2/3):\\n\"))\r\n if(choice==1):\r\n #for registering the file\r\n file_name=input(\"\\n\\nEnter the filename to register:\\n\")\r\n try:\r\n #try opening the file\r\n file=open(file_name,'r')\r\n except(FileNotFoundError):\r\n print(\"File not found in this directory\\n\")\r\n else:\r\n file.close()\r\n a=p.register(file_name)\r\n #result of registering the file to the centralized directory\r\n if(a=='okay'):\r\n print(\"\\nRegistration and seeding successful\")\r\n else:\r\n if(a):\r\n print(\"\\nRegistration successful but seeding failed\")\r\n else:\r\n print(\"\\nRegistration and seeding failed\")\r\n elif(choice==2):\r\n file_name=input(\"Enter the filename to search:\\n\")\r\n b=p.search(file_name)\r\n if(b=='sch'):\r\n print(\"Only search successful\")\r\n else:\r\n if(b):\r\n print(\"search and download successful\")\r\n else:\r\n print(\"search and download failed\")\r\n elif(choice==3):\r\n p.quit()\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
}
] | 3 |
sorXCode/Avina-API | https://github.com/sorXCode/Avina-API | 0b790bfd8ac8b9c84d1db45db0819e0585d954b9 | 7687ba7434b77d6c33944c65fff0409459a9d5ce | 2b115f9c5929fedd06d4dd6969100ab2df484adf | refs/heads/master | 2023-04-11T01:17:35.570752 | 2021-04-14T15:01:45 | 2021-04-14T15:01:45 | 342,429,666 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.7623762488365173,
"alphanum_fraction": 0.7623762488365173,
"avg_line_length": 29.399999618530273,
"blob_id": "c61d44bcc8be1346b3b1a8bb2742d5847838cc8a",
"content_id": "9903187e19c8320adcd0f81ea319f70a102f44a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 303,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 10,
"path": "/messenger/urls.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom .views import StartMessaging, Conversation\n\nurlpatterns = [\n path('', StartMessaging.as_view()),\n path('<str:product_uid>', Conversation.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)"
},
{
"alpha_fraction": 0.7510040402412415,
"alphanum_fraction": 0.763052225112915,
"avg_line_length": 22.162790298461914,
"blob_id": "7797982315b5dec816f0ecad5dc0f06ebbc4ab8e",
"content_id": "640bdad22c31b9333fcab80c2d1bd03ee798be0c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 996,
"license_type": "no_license",
"max_line_length": 188,
"num_lines": 43,
"path": "/README.md",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "# AVINA API\n\n## Create and Activate Virtual Environment\n\n```shell\npython3 -m venv venv\nsource venv/bin/activate\n```\n\n## Install dependencies\n\n```shell\npip install -r requirements.txt\n```\n\n## .env file\n\nThe .env file contains the environment variables and values needed to run the application. This can be created from the .env.example file by substituting for the actual environment values.\n\nNOTE: To run website, create a local `.env` file from the `.env.example` file at the application root.\n\n## Database Requirement\n\nA PostgreSQL database is required for this project.\n\n### Run application\n\n```shell\npython3 manange.py runserver\n```\n\n### **ps: Perform databases migration**\n\nTo run application for the first time, perform database migration using the commands below at the root folder\n\n```shell\npython3 manage.py makemigrations\npython3 manage.py migrate\n```\n\n### Endpoints\n\nAll available endpoints are documented and published [here](https://documenter.getpostman.com/view/11647149/TWDdiDAF)\n"
},
{
"alpha_fraction": 0.7098821401596069,
"alphanum_fraction": 0.7207615375518799,
"avg_line_length": 38.39285659790039,
"blob_id": "f8839b3e94f38f2a179f6f7ed791d3d3d5d18b3e",
"content_id": "1f37148ab4ae08254e4ac7f56f2b6534f81eab8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1103,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 28,
"path": "/products/models.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from django.db import models\n# from avina.storage import select_storage\nfrom avina.settings import AUTH_USER_MODEL\nfrom django.db.models.deletion import CASCADE, RESTRICT\nfrom uuid import uuid4\n\n\ndef generate_uid():\n return uuid4().hex\n\n\nclass Product(models.Model):\n uid = models.CharField(default=generate_uid, unique=True, max_length=255)\n name = models.CharField(max_length=255, null=False)\n category = models.ForeignKey(\n \"categories.Category\", on_delete=RESTRICT, related_name=\"products\")\n photo1 = models.ImageField(upload_to=\"products\")\n photo2 = models.ImageField(upload_to=\"products\")\n photo3 = models.ImageField(upload_to=\"products\")\n photo4 = models.ImageField(upload_to=\"products\")\n description = models.TextField()\n added_at = models.DateTimeField(auto_now_add=True)\n added_by = models.ForeignKey(\n AUTH_USER_MODEL, on_delete=RESTRICT, related_name=\"products\")\n sold = models.BooleanField(default=False)\n\n def __repr__(self):\n return \"Product:\\t{}\\nDescription:\\t{}\\nStatus:\\t{}\".format(self.name, self.description, self.status)\n"
},
{
"alpha_fraction": 0.7732142806053162,
"alphanum_fraction": 0.7732142806053162,
"avg_line_length": 42.07692337036133,
"blob_id": "073054737e15f3fdaff2c33db540f391c6ec7e0c",
"content_id": "05a57d822db2b99ed189710d4c90fee4da778e6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 560,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 13,
"path": "/products/serializers.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\nfrom .models import Product\nfrom categories.models import Category\nfrom users.models import User\nfrom rest_framework import serializers\n\nclass ProductSerializer(serializers.ModelSerializer):\n category = serializers.SlugRelatedField(read_only=False, queryset=Category.objects.all(), slug_field=\"name\")\n added_by = serializers.PrimaryKeyRelatedField(read_only=False, queryset=User.objects.all(), default=serializers.CurrentUserDefault())\n\n class Meta:\n model = Product\n exclude = (\"id\", \"added_at\",)\n"
},
{
"alpha_fraction": 0.6895999908447266,
"alphanum_fraction": 0.6944000124931335,
"avg_line_length": 30.149999618530273,
"blob_id": "206fa8b141b166778c96519ec0f908ae04db584d",
"content_id": "e3a80769efc564ebf9e259053b4000da9027cb66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 625,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 20,
"path": "/users/models.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom cuser.models import AbstractCUser\n\n# Create your models here.\n\n\nclass User(AbstractCUser):\n school = models.CharField(max_length=255, null=True)\n REQUIRED_FIELDS = [\"first_name\", \"last_name\"]\n \n\n def get_messages(self):\n from messenger.models import Message\n messages = Message.get_user_messages(user_id=self.id)\n return messages\n \n def get_messages_for_product(self, product_uid):\n from messenger.models import Message\n messages = Message.get_user_messages_for_product(user_id=self.id, product_uid=product_uid)\n return messages\n\n\n"
},
{
"alpha_fraction": 0.6702702641487122,
"alphanum_fraction": 0.6702702641487122,
"avg_line_length": 25.571428298950195,
"blob_id": "3d003cd53c775082f0c0035761c14bd8c47fdbff",
"content_id": "920645437de91733042c6d005fcc46722d77927f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 7,
"path": "/users/urls.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from .views import UserActivationView\nfrom django.conf.urls import url\n\n\nurlpatterns = [\n url(r'^users/activate/(?P<uid>[\\w-]+)/(?P<token>[\\w-]+)/$', UserActivationView.as_view()),\n]"
},
{
"alpha_fraction": 0.6561242341995239,
"alphanum_fraction": 0.6566992402076721,
"avg_line_length": 31.037036895751953,
"blob_id": "3071d66642df799dc2f61ee8beb5a0d34dfaa94d",
"content_id": "36d435acca40d5176be50734869ab240fb1ad1e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1739,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 54,
"path": "/messenger/serializers.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\nfrom .models import Message\nfrom products.models import Product\nfrom users.models import User\nfrom djoser.utils import settings\nfrom rest_framework import serializers\nfrom datetime import datetime\nimport json\nfrom rest_framework.exceptions import NotAcceptable\n\n\nclass InitializeMessageSerializer(serializers.ModelSerializer):\n sender = serializers.PrimaryKeyRelatedField(\n read_only=False, queryset=Product.objects.all(), default=serializers.CurrentUserDefault())\n product = serializers.SlugRelatedField(\n read_only=False, queryset=Product.objects.all(), slug_field=\"uid\")\n messages = serializers.CharField()\n\n class Meta:\n model = Message\n exclude = ('parties', 'id')\n\n def save(self, **kwargs):\n\n sender = self.validated_data[\"sender\"]\n product = self.validated_data[\"product\"]\n \n kwargs[\"parties\"] = [sender.id, product.added_by.id]\n\n # if parties conversation about product exists, simly update messages\n messages = [json.dumps({\n \"sender\": sender.id,\n \"message\": self.validated_data[\"messages\"],\n \"sent_at\": f\"{datetime.now()}\"\n }), ]\n \n del self.validated_data[\"sender\"]\n \n self.validated_data[\"messages\"] = messages\n\n message = Message.objects.filter(product=product, parties=kwargs[\"parties\"]).first()\n\n if message:\n message.messages.append(self.validated_data['messages'][0])\n message.save()\n return message\n return super().save(**kwargs)\n\n\n\nclass MessageSerializer(serializers.ModelSerializer):\n class Meta:\n model = Message\n exclude = (\"id\", \"parties\",)\n \n "
},
{
"alpha_fraction": 0.7439271211624146,
"alphanum_fraction": 0.7439271211624146,
"avg_line_length": 34,
"blob_id": "290d2a997feab0df1b80a52dd1a09fce400db05a",
"content_id": "6d85ae9b35cd69e8c2056102137395c0c55158de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 988,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 28,
"path": "/products/views.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from rest_framework import generics\nfrom .models import Product\nfrom .serializers import ProductSerializer\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.exceptions import PermissionDenied\n\nclass ProductList(ModelViewSet):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n permission_classes = [IsAuthenticated, ]\n\n\nclass ProductDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n permission_classes = [IsAuthenticated, ]\n\n\n def perform_destroy(self, instance):\n if self.request.user == instance.added_by:\n return super().perform_destroy(instance)\n raise PermissionDenied()\n\n def perform_update(self, serializer):\n if self.request.user == serializer.instance.added_by:\n return super().perform_update(serializer)\n raise PermissionDenied()\n "
},
{
"alpha_fraction": 0.7680798172950745,
"alphanum_fraction": 0.7680798172950745,
"avg_line_length": 29.884614944458008,
"blob_id": "c031bb540c728a262b27ea65c16493afd86892a0",
"content_id": "7c9faf4e0f4677e06822d894b120928a71f5a2e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 802,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 26,
"path": "/messenger/views.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from rest_framework import generics\nfrom .models import Message\nfrom .serializers import InitializeMessageSerializer, MessageSerializer\n\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.exceptions import PermissionDenied\n\nclass StartMessaging(generics.CreateAPIView):\n queryset = Message.objects.all()\n serializer_class = InitializeMessageSerializer\n permission_classes = [IsAuthenticated]\n\n\nclass Conversation(generics.RetrieveAPIView):\n serializer_class = MessageSerializer\n permission_classes = [IsAuthenticated]\n lookup_field = [\"product_uid\",]\n \n \n def get_object(self):\n user = self.request.user\n return user.get_messages_for_product(product_uid=self.kwargs[\"product_uid\"])\n\n\nclass AllMessages(generics.ListAPIView):\n pass"
},
{
"alpha_fraction": 0.6925675868988037,
"alphanum_fraction": 0.6936936974525452,
"avg_line_length": 39.40909194946289,
"blob_id": "bc482cb2487b27b3d62b4625a595aa15a31883d1",
"content_id": "26de1a1ae33383ef19ccff58cc954bf12c50a3e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 888,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 22,
"path": "/messenger/models.py",
"repo_name": "sorXCode/Avina-API",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.db.models.deletion import SET_NULL\nfrom django.contrib.postgres.fields import ArrayField\n# Create your models here.``\n\nclass Message(models.Model):\n product = models.ForeignKey(\"products.Product\", on_delete=SET_NULL, related_name=\"messages\", null=True)\n messages = ArrayField(models.JSONField())\n parties = ArrayField(models.IntegerField(), size=2)\n\n @classmethod\n def get_user_messages(cls, user_id):\n msgs = cls.objects.filter(parties__contains=[user_id,]).all()\n return msgs\n \n @classmethod\n def get_user_messages_for_product(cls, user_id, product_uid):\n msgs = cls.objects.filter(parties__contains=[user_id,], product__uid=product_uid).first()\n return msgs\n\n def __repr__(self):\n return \"product:\\t{}\\nmessages:\\t{}\\nparties:\\t{}\".format(self.product, self.messages, self.parties)"
}
] | 10 |
polarbergpotato/music | https://github.com/polarbergpotato/music | 47bf8a4c58ee8ad6539d2c232fae76cea377aae8 | e1d5dd861178d1e27f7ed2a14b3c2aa410286704 | 9990ae2ad65a1312d4262e0b499fac063f65857a | refs/heads/main | 2023-08-19T22:07:15.854716 | 2021-10-21T16:42:01 | 2021-10-21T16:42:01 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5869041681289673,
"alphanum_fraction": 0.5974963903427124,
"avg_line_length": 31.984127044677734,
"blob_id": "17869ea8e2c9ac770dcd9a2d7dd07a240df7aa74",
"content_id": "9d2c8b0623cb8cf58df6ff97a25fb88042fc168e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2077,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 63,
"path": "/music-rsync.py",
"repo_name": "polarbergpotato/music",
"src_encoding": "UTF-8",
"text": "# ---------------------------------------\n# ADB:\n# adb root\n#\n# Delete files and copy new ones:\n# from phone to pc (you rather deleted and created files on phone)\n# adb-sync -dfR sdcard/Music/Media/ /mnt/Backup/owncloud/Music/ --dry-run\n# from pc to phone (you rather deleted and created files on pc)\n# adb-sync -df /mnt/Backup/owncloud/Music/ sdcard/Music/Media/ --dry-run\n#\n# Than update only modified files with this script, both directions are ok:\n# ---------------------------------------\nimport subprocess\nimport datetime\n\n# ------------------------------------\n# USER VALUES CHANGE HERE\n# ----------------\ndirSd = \"sdcard/Music/Media/\"\ndirL = \"/mnt/Backup/owncloud/Music/\"\ndateString = \"2021-08-17 16:30:58\"\nsd2L = 1 # Direction sd to linux\n# -----------------------------------\n\ndateFormat = \"%Y-%m-%d %H:%M:%S\"\ndateOld = datetime.datetime.strptime(dateString, dateFormat)\ndateNew = datetime.datetime.now()\ndateDif = dateNew - dateOld\nprint(\"DateDif: \", dateDif)\ndateDif = dateDif.total_seconds()\nif dateDif < 0:\n print(\"date negative\")\n quit()\ndateDif = (dateDif / -60).__int__() # convert to minutes from seconds\n\nif sd2L:\n cmd = [\"adb\", \"shell\", \"find\", dirSd, \"-type\", \"f\", \"-mmin\", str(dateDif)]\nelse:\n cmd = [\"find\", dirL, \"-type\", \"f\", \"-mmin\", str(dateDif)]\nprocess = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\nfiles = process.stdout\nfiles = files.splitlines()\nprint(\"FILES \" + str(files.__len__())+ \" :\")\nprint(process.stdout)\n\nprint(\"\\nSTART:\")\nfor f in files:\n if sd2L:\n fSd = f\n fName = fSd.replace(dirSd, '')\n fL = dirL + fName\n cmd = [\"adb\", \"pull\", fSd, fL]\n else:\n fL = f\n fName = fL.replace(dirL, '')\n fSd = dirSd + fName\n cmd = [\"adb\", \"push\", fL, fSd]\n # print(cmd)\n process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n outputMessage = (process.stdout.splitlines())[-1]\n print(process.stderr + outputMessage + \"\\n\")\nprint(\"Finished! COPY NEW DATE!!!!\")\nprint(dateNew.strftime(dateFormat))"
},
{
"alpha_fraction": 0.38138478994369507,
"alphanum_fraction": 0.39354628324508667,
"avg_line_length": 21.507299423217773,
"blob_id": "9fd0540ac56b7a0de1d27998df6a4739c6eb52a2",
"content_id": "8e06183985c782795259c1740437d43c50466d28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6167,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 274,
"path": "/music-retag.py",
"repo_name": "polarbergpotato/music",
"src_encoding": "UTF-8",
"text": "# ---------------------------------------\n# ---------------------------------------\nimport mutagen\nfrom mutagen.id3 import ID3\nfrom mutagen.easyid3 import EasyID3\nfrom mutagen.mp3 import MP3\nimport subprocess\n\n# ------------------------------------\n# USER VALUES CHANGE HERE\ndirL = \"/mnt/Backup/owncloud/Music/\"\n# -----------------------------------\n\ncmd = [\"find\", dirL, \"-type\", \"f\", \"-name\", \"*.mp3\"]\nprocess = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\nfiles = process.stdout\nfiles = files.splitlines()\nprint(len(files))\n\n\n\n# # start tracknumber in album and non albums\n# print(\"\\nStart:\")\n# l = {}\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"])\n# try:\n# album = str(m[\"album\"])\n# try:\n# if album in l:\n# l[album] += 1\n# else:\n# l[album] = 1\n# except:\n# print(title)\n# except:\n# pass\n#\n# print(\"\\nStartWriting:\")\n# for f in files:\n# mn = MP3(f, EasyID3)\n# titlen = str(mn[\"title\"])\n# try:\n# albumn = str(mn[\"album\"])\n# try:\n# if l[albumn] <= 1:\n# try:\n# trackn = mn[\"tracknumber\"]\n# except:\n# mn[\"tracknumber\"] = ['01']\n# else:\n# pass\n# except:\n# print(titlen)\n# a = 1\n# except:\n# try:\n# mn.pop(\"albumartist\")\n# print(titlen)\n# a = 1\n# except:\n# pass\n# try:\n# mn.pop(\"tracknumber\")\n# print(titlen)\n# a = 1\n# except:\n# pass\n# # mn.save()\n# print(\"done\")\n\n\n\n\n\n\n\n\n\n\n\n\n# # start rename albums with only one song to unknown and album interpret also away\n# print(\"\\nStart:\")\n# l = {}\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"])\n# try:\n# album = str(m[\"album\"])\n# try:\n# if album in l:\n# l[album] += 1\n# else:\n# l[album] = 1\n# except:\n# print(title)\n# except:\n# pass\n# # for key, value in l.items():\n# # print(key, \" : \", value)\n#\n# print(\"\\nStartWriting:\")\n# for f in files:\n# mn = MP3(f, EasyID3)\n# titlen = str(mn[\"title\"])\n# try:\n# albumn = str(mn[\"album\"])\n# try:\n# if l[albumn] <= 1:\n# trackn = 1\n# try:\n# trackn = mn[\"tracknumber\"]\n# if trackn == ['01/01'] or trackn == ['01']:\n# trackn = 1\n# else:\n# trackn = 2\n# except:\n# pass\n# if trackn == 1:\n#\n# if (titlen.lower().find(albumn.lower()) != -1) or (albumn.lower().find(titlen.lower()) != -1):\n# pass\n# else:\n# print(titlen, \" : \", albumn, \"\\n\")\n# mn.pop(\"album\")\n# try:\n# mn.pop(\"albumartist\")\n# except:\n# pass\n# # mn.save()\n#\n# # mn.pop(\"album\")\n# # try:\n# # mn.pop(\"albumartist\")\n# # print(\"poped\", titlen)\n# # except:\n# # mn.save()\n# # pass\n# # # mn.save()\n#\n# else:\n# pass\n# except:\n# print(titlen)\n# except:\n# pass\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# # start search album with unknown\n# print(\"\\nStart:\")\n# a=0\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"])\n# if title.find(\"hatta\") != -1:\n# print(title)\n# pass\n# try:\n# album = str(m[\"album\"])\n# # if album.find(\"Unknown\") != -1:\n# # print(title)\n# # m.pop(\"album\")\n# # m.save()\n# except:\n# pass\n# a += 1\n# print(title)\n# print(a)\n\n\n\n\n\n\n# # start search unknown artists\n# print(\"\\nStart:\")\n# a=0\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"])\n# try:\n# artist = str(m[\"artist\"])\n# # if artist.find(\"Unknown\") != -1:\n# # print(title)\n# # m.pop(\"artist\")\n# # m.save()\n#\n# except:\n# pass\n# a += 1\n# print(title)\n# print(a)\n\n\n\n\n\n\n\n\n\n\n\n# # Convert m4a to mp3\n# a = 0\n# for f in files:\n# try:\n# out = f.replace(\".m4a\", \".mp3\")\n# cm = [\"ffmpeg\", \"-v\", \"5\", \"-y\", \"-i\", f, \"-acodec\", \"libmp3lame\", \"-ac\", \"2\", \"-ab\", \"192k\", out]\n# p = subprocess.run(cm, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n# a += 1\n# print(out)\n# if p.stderr != \"\":\n# print(\"\\n\\n\\n\\nERRIR\"+out)\n# except:\n# print(\"\\n\\n\\n\\nERRIR\"+out)\n# print(a)\n\n\n# # start search title split but no art\n# print(\"\\nStart:\")\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"][0])\n# titleSplit = title.split(\" - \")\n# if len(titleSplit) <= 1:\n# continue\n# try:\n# artist = str(m[\"artist\"][0])\n# if title.find(artist) != -1:\n# continue\n# print(\"Art: \" + artist)\n# except:\n# pass\n# print(\"Title: \" + title + \"\\n\")\n\n\n\n\n\n# # start title to new title and art\n# for f in files:\n# m = MP3(f, EasyID3)\n# title = str(m[\"title\"][0])\n# try:\n# artist = str(m[\"artist\"][0])\n# preTitle = title.split(\" - \")\n# if preTitle.__len__() <= 1:\n# continue\n# postTitle = preTitle[1]\n# preTitle = preTitle[0]\n# if preTitle.find(artist) != -1:\n# m[\"artist\"] = [preTitle]\n# m[\"title\"] = [postTitle]\n# print(\"Title: \" + title + \"\\n\" + \"Art: \" + artist)\n# m.save()\n# print(\"NewTitle: \" + postTitle + \"\\n\" + \"NewArt: \" + preTitle + \"\\n\")\n# except:\n# pass\n"
},
{
"alpha_fraction": 0.4908827841281891,
"alphanum_fraction": 0.5251808762550354,
"avg_line_length": 29.04347801208496,
"blob_id": "9c297f774ccce4e661edfa1b8e03075262fb0449",
"content_id": "98dfc8fa892952970ceb24c69ce7af780cbea3fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6917,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 230,
"path": "/main.py",
"repo_name": "polarbergpotato/music",
"src_encoding": "UTF-8",
"text": "import time\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nfrom pydub.silence import split_on_silence\nimport numpy as np\nfrom pydub.utils import mediainfo\nfrom os import walk\nfrom os import listdir\nfrom mutagen.easyid3 import EasyID3\nfrom mutagen.mp3 import MP3\n\n# --------------------------------------\n# Say if first song is already saved\nfirstSave = 0 # 0 if stopped and proceed\ngenreName = \"AlternativeFM02\"\n# --------------------------------------\n\n# get all file names\ndir = \"/home/freddy/Downloads/ripperOld\"\ndirNew = \"/home/freddy/Downloads/ripperNew\"\nfiles = [f for f in listdir(dir)]\nfiles.sort()\n\n# Constants\ntimeOffSetSecond = 10000\ntimeOffSet = -15000 - timeOffSetSecond\ntimeCut = 1000\ntimeCutSecond = 200\nstop = 0\n# Loop though songs\nsong2 = AudioSegment.from_mp3(dir + \"/\" + files[0])\nfor index in range(len(files)):\n # import song\n song1 = song2\n if index + 1 < len(files):\n song2 = AudioSegment.from_mp3(dir + \"/\" + files[index + 1])\n song1 = song1 + song2[:timeOffSetSecond]\n song2 = song2[timeOffSetSecond + 1:]\n\n # Loop variables\n repeat = 1\n timeOffSetNew = timeOffSet\n # play song and safe time\n while repeat:\n try:\n timeTic = time.time()\n play(song1[timeOffSetNew:])\n timeToc = time.time()\n time.sleep(0.5)\n except KeyboardInterrupt:\n pass\n # Calculate new times for end\n dif = (timeToc - timeTic) * 1000\n timeEnd = timeOffSetNew + dif - timeCut\n if timeEnd >= 0:\n timeEnd = -25\n # create new song\n songNew = (song1[:timeEnd] + AudioSegment.silent(1000, song1.frame_rate)).fade_out(2000)\n # calculate new time for start second\n timeStartSecond = timeOffSetNew + dif - timeCutSecond\n if timeStartSecond >= 0:\n timeStartSecond = -1\n\n # check if repeat sequence\n try:\n cmd1 = input(\"\\n'ö':repeat; 'p':cut middle; 'o':play new end;\\n 'l':change start; 'k':end; other:continue\")\n if cmd1 == 'ö':\n repeat = 1\n elif cmd1 == 'p':\n # Loop variables\n middleRep = 1\n # Loop for middle Cut\n while middleRep:\n repeat = 0\n # play cut sequence\n timeTic = time.time()\n play(song1[timeEnd:])\n timeToc = time.time()\n dif = (timeToc - timeTic) * 1000\n # calculate new time for start second\n timeStartSecond = timeEnd + dif - timeCutSecond\n if timeStartSecond >= 0:\n timeStartSecond = -1\n # check if repeat\n cmd2 = input(\"\\n'ö':repeat; 'p':repeat all; other:continue\")\n if cmd2 == 'ö':\n middleRep = 1\n elif cmd2 == 'p':\n middleRep = 0\n repeat = 1\n else:\n middleRep = 0\n elif cmd1 == 'o':\n # play firsts song end\n play(songNew[-4000:])\n # play second song beginning\n if timeStartSecond + 4000 < 0:\n play(song1[timeStartSecond:timeStartSecond+4000])\n else:\n play(song1[timeStartSecond:])\n # check user input\n cmd2 = input(\"\\n'ö':repeat; other:continue\")\n if cmd2 == 'ö':\n repeat = 1\n else:\n repeat = 0\n elif cmd1 == 'l':\n timeOffSetNew = input(\"\\nEnter new offset: (-15000)\")\n timeOffSetNew = int(timeOffSetNew) - timeOffSetSecond\n repeat = 1\n elif cmd1 == 'k':\n stop = 1\n repeat = 0\n else:\n repeat = 0\n except:\n repeat = 1\n\n # all finished and save new song\n newName = files[index]\n newName = newName[30:]\n newTags = newName.replace('.mp3', '')\n newTags = newTags.replace(' (1)', '')\n newTags = newTags.replace(' (2)', '')\n newTags = newTags.split(\" - \")\n newArtist = newTags[0]\n newArtist = newArtist.title()\n if len(newTags) > 1:\n newTitle = newTags[1]\n newTitle = newTitle.title()\n newName = newArtist + \" - \" + newTitle + \".mp3\"\n else:\n newTitle = 'NoTitle'\n\n # if stopped mark this last song to be used next time as start\n if stop:\n newName = \"000_CONT_HERE_RENAME_\" + newName\n # Save song\n if firstSave:\n songNew.export(dirNew + \"/\" + newName, format = \"mp3\", tags = {'title': newTitle, 'artist': newArtist})\n m = MP3(dirNew + \"/\" + newName, EasyID3)\n m[\"title\"] = newTitle\n m[\"artist\"] = newArtist\n m[\"genre\"] = genreName\n m.save()\n print(\"\\n--------------------\\n%s\\n--------------------\\n\" %newName)\n else:\n firstSave = 1\n\n # break if stopped\n if stop:\n break\n\n # create next song and append data\n if index + 1 < len(files):\n song2 = song1[timeStartSecond:] + song2\n\n# ------\n# OLD\n# -------\n# amp = [0] * 5\n# m = [0] * 5\n\n# song = AudioSegment.from_mp3(\"05 - Kann mich irgendjemand hören.mp3\")\n# id = 0\n# min = 4\n# sec = 21.15\n# time = 1000 * (min * 60 + sec)\n# timeEnd = time + 1 * 1000\n# songA = song[time:timeEnd]\n# amp[id] = songA.dBFS\n# seq = songA.get_array_of_samples()\n# m[id] = np.mean(seq)\n# # play(songA)\n#\n# song = AudioSegment.from_mp3(\"AlternativeFM - rockt. - THE LUKA STATE - GIRL.mp3\")\n# id = 1\n# min = 2\n# sec = 34.8\n# time = 1000 * (min * 60 + sec)\n# timeEnd = time + 1 * 1000\n# songA = song[time:timeEnd]\n# amp[id] = songA.dBFS\n# seq = songA.get_array_of_samples()\n# m[id] = np.mean(seq)\n# # play(songA)\n#\n# song = AudioSegment.from_mp3(\"AlternativeFM - rockt. - BEATSTEAKS - 40 DEGREES.mp3\")\n# id = 2\n# min = 2\n# sec = 20.2\n# time = 1000 * (min * 60 + sec)\n# timeEnd = time + 1 * 1000\n# songA = song[time:timeEnd]\n# amp[id] = songA.dBFS\n# seq = songA.get_array_of_samples()\n# m[id] = np.mean(seq)\n# # play(songA)\n#\n# song = AudioSegment.from_mp3(\"AlternativeFM - rockt. - 30 SECONDS TO MARS - THIS IS WAR.mp3\")\n# id = 3\n# min = 4\n# sec = 44.7\n# time = 1000 * (min * 60 + sec)\n# timeEnd = time + 1 * 1000\n# songA = song[time:timeEnd]\n# amp[id] = songA.dBFS\n# seq = songA.get_array_of_samples()\n# m[id] = np.mean(seq)\n# # play(songA)\n#\n# song = AudioSegment.from_mp3(\"AlternativeFM - rockt. - TOOL - SOBER.mp3\")\n# id = 4\n# min = 4\n# sec = 53.5\n# time = 1000 * (min * 60 + sec)\n# timeEnd = time + 1 * 1000\n# songA = song[time:timeEnd]\n# amp[id] = songA.dBFS\n# seq = songA.get_array_of_samples()\n# m[id] = np.mean(seq)\n# # play(songA)\n#\n# print(\"AMP:\\n\")\n# for a in amp:\n# print(a,\"\\n\")\n#\n# print(\"MEAN:\\n\")\n# for n in m:\n# print(n, \"\\n\")\n"
}
] | 3 |
BlueCocoa/netease | https://github.com/BlueCocoa/netease | f6a22b8cdf96dde405a371151795af56df05460d | 88d085e5b483b8ced027070648fd25b4b0337258 | 0c97f2d78eab6bf1832328b3ec541ff64ac12d88 | refs/heads/master | 2020-02-13T13:31:59.923207 | 2017-12-23T04:47:03 | 2017-12-23T04:47:03 | 115,170,780 | 2 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6273291707038879,
"alphanum_fraction": 0.695652186870575,
"avg_line_length": 11.384614944458008,
"blob_id": "11999ca45852ea9957641794b04cad2ac52935d7",
"content_id": "0da597e72ffe09505f2114dfb7c0c0a2f71db911",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 161,
"license_type": "permissive",
"max_line_length": 35,
"num_lines": 13,
"path": "/README.md",
"repo_name": "BlueCocoa/netease",
"src_encoding": "UTF-8",
"text": "# netease\nJust a tiny tool for demonstration.\n\n### Usage\n```bash\npython3 netease.py [id of playlist]\n```\n\nfor example,\n\n```bash\npython3 netease.py 329088315\n```\n"
},
{
"alpha_fraction": 0.5731415152549744,
"alphanum_fraction": 0.5995203852653503,
"avg_line_length": 34.27118682861328,
"blob_id": "e08db4aae2daead1514f167a2ca9a058c2f66343",
"content_id": "1e5400af35ab9f202e5c863a96e752a843f5741c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2085,
"license_type": "permissive",
"max_line_length": 148,
"num_lines": 59,
"path": "/netease.py",
"repo_name": "BlueCocoa/netease",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom Crypto.Cipher import AES\nimport binascii\nimport json\nfrom hashlib import md5\nimport re\nimport requests\nimport sys\nimport urllib\n\ndef netease_encrypt(body):\n BLOCK_SIZE = 16\n pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)\n unpad = lambda s: s[:-ord(s[len(s) - 1:])]\n body = json.dumps(body)\n raw = pad(body)\n cipher = AES.new('\\x72\\x46\\x67\\x42\\x26\\x68\\x23\\x25\\x32\\x3F\\x5E\\x65\\x44\\x67\\x3A\\x51', AES.MODE_ECB)\n return {'eparams' : binascii.hexlify(cipher.encrypt(raw)).upper()}\n \n\ndef download_playlist(playlist):\n print(\"retriving playlist...\")\n r = requests.get(playlist)\n arr = r.json()['result']['tracks']\n ids = []\n names = {}\n print(\"enumerating tracks...\")\n for i in range(len(arr)):\n name = str(i + 1) + ' ' + arr[i]['name'] + '.mp3'\n songid = arr[i]['id']\n names[str(songid)] = arr[i]['name']\n ids.append(songid)\n print(\"%d tracks found...\" % (len(ids)))\n print(\"encrypting messages...\")\n post = netease_encrypt({'method' : 'POST', 'params' : {'ids' : ids, 'br' : 320000}, 'url' : 'http://music.163.com/api/song/enhance/player/url'})\n print(\"forwarding messages to netease...\")\n songs = requests.post('http://music.163.com/api/linux/forward', post)\n songs = songs.json()['data']\n print(\"obtaining download URLs...\")\n for song in songs:\n url = song['url']\n name = names[str(song['id'])] + '.mp3'\n urllib.request.urlretrieve(url, name)\n print(\"- completed: %s\" % (name))\n\n\nif __name__ == \"__main__\":\n playlist_regex = re.compile('^(?:\\d+)$')\n playlist = None\n if len(sys.argv) == 2:\n playlist = sys.argv[1].strip()\n else:\n playlist = input(\"Please type the id of the netease playlist:\\n\").strip()\n while not playlist_regex.match(playlist):\n playlist = input(\"Wrong URL, please type the id of the netease playlist:\\n\").strip()\n \n download_playlist(\"http://music.163.com/api/playlist/detail?id=%s\" % (playlist))\n "
}
] | 2 |
sfono96/python | https://github.com/sfono96/python | 2a3ba5abea76e3929bc64c4563b0bd36c517091d | c0ffc8903744908931c626c4d9f0c94dd7f437f4 | b48d5fd29e23d9b627d07d1a45794ceae4f580d4 | refs/heads/master | 2021-01-18T14:01:31.567145 | 2014-09-04T12:24:09 | 2014-09-04T12:24:09 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6894423961639404,
"alphanum_fraction": 0.7102376818656921,
"avg_line_length": 49.872093200683594,
"blob_id": "ff883b25afd26768382a392544fcc574b36e4839",
"content_id": "01e52517622787eac921853fb6bf74f47fe5b5eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4376,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 86,
"path": "/ela.py",
"repo_name": "sfono96/python",
"src_encoding": "UTF-8",
"text": "import urllib2, re, csv\nfrom stripHTML import strip_tags # function to clean a string from HTML\n\n\n# url = 'http://www.uen.org/core/core.do?courseNum=4200' # kindergarten\n# url = \"http://www.uen.org/core/core.do?courseNum=4210\" # 1st\n# url = 'http://www.uen.org/core/core.do?courseNum=4220' # 2nd\n# url = 'http://www.uen.org/core/core.do?courseNum=4230' # 3rd\n# url = 'http://www.uen.org/core/core.do?courseNum=4240' # 4th\n# url = 'http://www.uen.org/core/core.do?courseNum=4250' # 5th\n# url = 'http://www.uen.org/core/core.do?courseNum=4260' # 6th\n# url = 'http://www.uen.org/core/core.do?courseNum=4270' # 7th\nurl = 'http://www.uen.org/core/core.do?courseNum=4280' # 8th\n\ncontent = urllib2.urlopen(url).read()\n# content = content\n\ndef clean_newlines_and_tabs(text):\n\treturn text.replace('\\n','').replace('\\t','').rstrip().lstrip()\n\ncl = '<span class=\"big-bold\">(.*?)</span>' # cluster\nst = '<span class=\"paratitle\">.*?</a>(.*?)</span>' # standard name\nd1 = '<span class=\"paratitle\">.*?<br />(.*?)</p>' # standard description\nsc = '<span class=\"bold\">.*?</a>(.*?)</span>' # standard sub component name (a,b,c,d ...)\nd2 = '<span class=\"bold\">.*?<br />(.*?)</p>' # standard sub component description\n\n# go through the html and look for the\n# 1) DOMAIN NAME (IGNORE BECAUSE IT IS PART OF THE STANDARD NAME)\n# 2) CLUSTER NAME (<span class=\"big-bold\"></span>)\n# 3) STANDARD NAME (<span class=\"paratitle\"></span>)\n# 4) STANDARD SUB COMPONENT IF ANY (<span class=\"bold\"></span>) THIS WILL BE a., b., c., d., etc. \n# 5) STANDARD DESCRIPTION\n\nstarting_point_text = '<p class=\"big-bold\">Core Standards of the Course</p>'\nnot_finished = True\nidx = content.index(starting_point_text)\ncluster_idx = 0\nstandard_idx = 0\nsub_standard_idx = 0\ncluster = None\nstandard = None\nstandard_description = None\ncomplete_standards = []\n\nwhile not_finished:\n\tsearched_content = content[idx:]\n\t\n\tnext_cluster = strip_tags(clean_newlines_and_tabs(re.findall(cl,searched_content,re.DOTALL|re.MULTILINE)[0])) if len(re.findall(cl,searched_content,re.DOTALL|re.MULTILINE)) > 0 else ''\n\tnext_standard = strip_tags(clean_newlines_and_tabs(re.findall(st,searched_content,re.DOTALL|re.MULTILINE)[0])) if len(re.findall(st,searched_content,re.DOTALL|re.MULTILINE)) > 0 else ''\n\tnext_standard_description = strip_tags(clean_newlines_and_tabs(re.findall(d1,searched_content,re.DOTALL|re.MULTILINE)[0])) if len(re.findall(d1,searched_content,re.DOTALL|re.MULTILINE)) > 0 else ''\n\tnext_sub_standard = strip_tags(clean_newlines_and_tabs(re.findall(sc,searched_content,re.DOTALL|re.MULTILINE)[0])) if len(re.findall(sc,searched_content,re.DOTALL|re.MULTILINE)) > 0 else ''\n\tnext_sub_standard_description = strip_tags(clean_newlines_and_tabs(re.findall(d2,searched_content,re.DOTALL|re.MULTILINE)[0])) if len(re.findall(d2,searched_content,re.DOTALL|re.MULTILINE)) > 0 else ''\n\n\t# get current indexes of next cluster, standard, \n\tnext_cluster_idx = searched_content.index('<span class=\"big-bold\">')+23 if '<span class=\"big-bold\">' in searched_content else 99999\n\tnext_standard_idx = searched_content.index('<span class=\"paratitle\">')+23 if '<span class=\"paratitle\">' in searched_content else 99999\n\tnext_sub_standard_idx = searched_content.index('<span class=\"bold\">')+23 if '<span class=\"bold\">' in searched_content else 99999\n\t# print next_cluster_idx, next_standard_idx, next_sub_standard_idx\n\n\t# check to see if next standard or sub standard - if none then quit else continue\n\tif next_standard == '' and next_sub_standard == '':\n\t\tnot_finished = False\n\telse:\n\t\t# assign cluster (new only if next cluster is closer than next standard and sub standard)\n\t\tif next_cluster_idx < next_standard_idx and next_cluster_idx < next_sub_standard_idx:\n\t\t\tcluster = next_cluster\n\n\t\t# assign standard \n\t\tif next_standard_idx < next_sub_standard_idx:\n\t\t\tstandard = next_standard\n\t\t\tstandard_description = next_standard_description\n\t\telse:\n\t\t\tstandard = next_sub_standard\n\t\t\tstandard_description = next_sub_standard_description\n\n\trow = [cluster, standard, standard_description]\n\tcomplete_standards.append(row)\n\tidx += min([next_cluster_idx,next_standard_idx,next_sub_standard_idx])\n\t# not_finished = False\n\n\n# now we can write it to file\nwrite_path = '/Users/samfonoimoana/Documents/Standards Stuff/ELA-standards-clean.csv'\nwith open(write_path, 'w') as fp:\n a = csv.writer(fp, delimiter=',')\n a.writerows(complete_standards)\n\n"
},
{
"alpha_fraction": 0.7328358292579651,
"alphanum_fraction": 0.7343283295631409,
"avg_line_length": 38.29411697387695,
"blob_id": "ebedbb06ac5ec55b26efb9df6293353bfceb5c92",
"content_id": "5d61bed2edf1935db759fe9d05a4eca454907b19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 670,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 17,
"path": "/clean_standards.py",
"repo_name": "sfono96/python",
"src_encoding": "UTF-8",
"text": "import csv\nfrom stripHTML import strip_tags # function to clean a string from HTML\n\nread_path = '/Users/samfonoimoana/Documents/Standards Stuff/math-standards-html.csv'\nwrite_path = '/Users/samfonoimoana/Documents/Standards Stuff/math-standards-clean.csv'\n\n# let's go ahead and open the csv and clean the data (single-column)\ncleaned_standards = []\nwith open(read_path,'rU') as f:\n\treader = csv.reader(f, dialect=csv.excel_tab)\n\tfor row in reader:\n\t\tcleaned_standards.append([strip_tags(row[0])]) # single column (first and only)\n\n# now we can write it to file\nwith open(write_path, 'w') as fp:\n a = csv.writer(fp, delimiter=',')\n a.writerows(cleaned_standards)\n\n\n"
}
] | 2 |
Vidhya2192-Shinde/GIT-Practice | https://github.com/Vidhya2192-Shinde/GIT-Practice | 87422517dce413094f61edf785c7ef50582332f1 | 2eb97b10e2e7fac1049932fb2bcd5ccd005a4f2c | 9ec84780ea1fc941722d5099daf0a58cade8b07d | refs/heads/master | 2023-04-30T18:28:54.631247 | 2021-05-10T04:11:33 | 2021-05-10T04:11:33 | 291,456,316 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5363184213638306,
"alphanum_fraction": 0.5547263622283936,
"avg_line_length": 40.875,
"blob_id": "11f6a735203c1c2b894d13295294ddaab76c15ea",
"content_id": "488b568fd1a828b133a7bf46bec75119ba01d387",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2010,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 48,
"path": "/SaleProducts/appone/migrations/0001_initial.py",
"repo_name": "Vidhya2192-Shinde/GIT-Practice",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2.7 on 2021-04-14 06:29\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Product',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('productName', models.CharField(max_length=100)),\n ('description', models.TextField()),\n ('price', models.FloatField()),\n ('image', models.ImageField(blank=True, null=True, upload_to='img')),\n ('quantity', models.IntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(100)])),\n ('created_date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'db_table': 'PRODUCT_INFO',\n },\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fullname', models.CharField(max_length=30)),\n ('username', models.CharField(max_length=30, unique=True)),\n ('password', models.CharField(max_length=30, unique=True)),\n ('active', models.BooleanField(default='Y', max_length=30)),\n ('role', models.CharField(default='admin', max_length=100)),\n ('mobileNo', models.BigIntegerField(blank=True, default='0', null=True)),\n ('email', models.EmailField(blank=True, max_length=254, null=True)),\n ('created_date', models.DateTimeField(auto_now_add=True)),\n ('updated_date', models.DateTimeField(auto_now=True)),\n ],\n options={\n 'db_table': 'User_INFO',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.5530332922935486,
"alphanum_fraction": 0.5530332922935486,
"avg_line_length": 28.034090042114258,
"blob_id": "0631b0f0ceb23bbdd34b3d98e0b52cef898bbc50",
"content_id": "4a326422a9db17ce0aa68489def3621cfddb0a8a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2555,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 88,
"path": "/SaleProducts/appone/views.py",
"repo_name": "Vidhya2192-Shinde/GIT-Practice",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom appone.models import User,Product\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect\n# Create your views here.\n\n\n\ndef auth_user(req):\n msg = \" \"\n if req.method == \"POST\":\n formdata = req.POST\n # user=formdata.cleaned_data['username'],\n #pwd=formdata.get('password'),\n instance= User.objects.filter(username=user,password=pwd).first()\n if instance:\n return render(req, 'home.html', {'user: instance'})\n msg = 'Invalid Login Credentials.......!'\n return render(req, 'login.html', {'resp': msg})\n\n\n\ndef register_user(req):\n msg=\" \"\n if req.method==\"POST\":\n formdata = req.POST\n login= User(fullname=formdata.get('fullname'),\n username=formdata.get('username'),\n password=formdata.get('password'),\n email=formdata.get('email'))\n\n login.save()\n msg='User Registration Successfully.......!'\n return render(req,'register.html',{'resp':msg})\n\n\n\n\n\n\n\n\ndef add_or_update_Product(req):\n msg = \"\"\n if req.method == \"POST\":\n data = req.POST\n pid = data.get('id')\n prod = Product.objects.filter(id=pid).first()\n pro = Product(name=data.get('productName'), desc=data.get('description'),\n price=data.get('price'))\n if prod:\n prod.name = pro.name\n prod.desc = pro.desc\n prod.price = pro.price\n prod.save()\n msg = f\"Product ({prod.id}) record Updated..\"\n else:\n pro.save()\n msg = f\"Product ({pro.id}) record Added..\"\n return render(request=req, template_name='home.html',\n context={\n 'prodlist': Product.objects.all(),\n\n 'message': msg\n })\n\n\ndef edit_product(req,pid):\n return render(request=req, template_name='home.html',\n context={\n 'prodlist':Product.objects.all(),\n 'pro': Product.objects.filter(id=pid).first(),\n 'message' : ''\n })\n\n\ndef delete_product(req,pid):\n prod = Product.objects.filter(id=pid).first()\n msg = ''\n if prod:\n prod.delete()\n msg = f'Product({pid}) record removed..!'\n return render(request=req, template_name='employee.html', context={\n 'prodlist': Product.objects.all(),\n\n 'message' : msg\n })\n"
},
{
"alpha_fraction": 0.708381175994873,
"alphanum_fraction": 0.719288170337677,
"avg_line_length": 36.085105895996094,
"blob_id": "008292bbd2a9222ea0ba9bded76f79bd2c4869d4",
"content_id": "7186f76d916ca67d90a4d5f1385694d18f3f5491",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1742,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 47,
"path": "/SaleProducts/appone/models.py",
"repo_name": "Vidhya2192-Shinde/GIT-Practice",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.core.validators import MinValueValidator,MaxValueValidator\n# Create your models here.\n\n\n# Create your models here.\n# (id,fullName,Password(Encrepted form), Active, Role,MobileNo, Email (Optional), createdDate, UpdatedDate)\nclass User(models.Model):\n # id=models.IntegerField()\n fullname = models.CharField(max_length=30)\n username=models.CharField(max_length=30,unique=True)\n password=models.CharField(max_length=30,unique=True)\n active = models.BooleanField(max_length=30,default=True)\n role = models.CharField(max_length=100,default=\"admin\")\n mobileNo= models.BigIntegerField(blank=True, null=True, default='0')\n email = models.EmailField(blank=True, null=True)\n created_date = models.DateTimeField(auto_now_add=True)\n updated_date = models.DateTimeField(auto_now=True)\n # products = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='customers')\n\n class Meta:\n db_table = 'User_INFO'\n\n\n#(Id, ProductName, Description, price, curency,images,createdDate, salerId(User having role saler), QTY)\nclass Product(models.Model):\n # id=models.IntegerField()\n productName = models.CharField(max_length=100)\n description = models.TextField()\n price = models.FloatField()\n #curency=\n image = models.ImageField(upload_to='img', blank=True, null=True)\n quantity = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(100)])\n created_date = models.DateTimeField(auto_now_add=True)\n #salerId=\n\n class Meta:\n db_table = \"PRODUCT_INFO\"\n\n#(id, RoleName(Admin,User,Saler,Buyer), isActive)\n'''''class Role(models.Model):\n Id=\n roleName=\n isActive=\n\n class Meta:\n db_table = \"Role_INFO\"'''"
}
] | 3 |
alebarsotti/movies-recommendations-bot | https://github.com/alebarsotti/movies-recommendations-bot | 4ea3b373bcf368a42548fb069a2cf0cc89d32df0 | cdcc4548ba4bd949f76f8f1eecf60aa1d95a7bb7 | 8d9f299a7aa11d7d79b5561c2a84ca55c64bfdbf | refs/heads/master | 2020-03-20T22:07:03.917668 | 2018-07-21T22:18:11 | 2018-07-21T22:18:11 | 137,780,015 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8571428656578064,
"alphanum_fraction": 0.8571428656578064,
"avg_line_length": 28,
"blob_id": "77af7079992987174e91f2b7a0b4246b922e5b43",
"content_id": "68d5f278a088151f08424843e675d7b854b30379",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 28,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 1,
"path": "/README.md",
"repo_name": "alebarsotti/movies-recommendations-bot",
"src_encoding": "UTF-8",
"text": "# movies-recommendations-bot"
},
{
"alpha_fraction": 0.6491975784301758,
"alphanum_fraction": 0.6494483351707458,
"avg_line_length": 32.24166488647461,
"blob_id": "034a90d684bd7ebc041c612e97eab56a56b852bc",
"content_id": "90acbddd94e7117b60d219db3fbac543a2deca6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4021,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 120,
"path": "/movies-recommendations-bot.py",
"repo_name": "alebarsotti/movies-recommendations-bot",
"src_encoding": "UTF-8",
"text": "import tweepy\nimport pandas as pd\nimport os\n\nCSV_URL = os.environ.get('CSV_URL', None)\nCONSUMER_KEY = os.environ.get('CONSUMER_KEY', None)\nCONSUMER_SECRET = os.environ.get('CONSUMER_SECRET', None)\nACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', None)\nACCESS_TOKEN_SECRET = os.environ.get('ACCESS_TOKEN_SECRET', None)\nIMDB_URL = os.environ.get('IMDB_URL', None)\nBOT_SCREEN_NAME = os.environ.get('BOT_SCREEN_NAME', None)\nBOT_USERNAME = f'@{BOT_SCREEN_NAME}'\n\nGENRES = {\n 'accion': 'Acción',\n 'acción': 'Acción',\n 'Accion': 'Acción',\n 'Acción': 'Acción',\n 'aventura': 'Aventura',\n 'Aventura': 'Aventura',\n 'Animación': 'Animación',\n 'Animacion': 'Animación',\n 'animación': 'Animación',\n 'animacion': 'Animación',\n 'Comedia': 'Comedia',\n 'comedia': 'Comedia',\n 'Crimen': 'Crimen',\n 'crimen': 'Crimen',\n 'Documental': 'Documental',\n 'documental': 'Documental',\n 'Drama': 'Drama',\n 'drama': 'Drama',\n 'Familia': 'Familia',\n 'familia': 'Familia',\n 'Fantasía': 'Fantasía',\n 'fantasía': 'Fantasía',\n 'Fantasia': 'Fantasía',\n 'fantasia': 'Fantasía',\n 'Historia': 'Historia',\n 'historia': 'Historia',\n 'Terror': 'Terror',\n 'terror': 'Terror',\n 'Música': 'Música',\n 'Musica': 'Música',\n 'música': 'Música',\n 'musica': 'Música',\n 'Misterio': 'Misterio',\n 'misterio': 'Misterio',\n 'Romance': 'Romance',\n 'romance': 'Romance',\n 'Scifi': 'Ciencia ficción',\n 'scifi': 'Ciencia ficción',\n 'CienciaFicción': 'Ciencia ficción',\n 'cienciaficción': 'Ciencia ficción',\n 'CienciaFiccion': 'Ciencia ficción',\n 'cienciaficcion': 'Ciencia ficción',\n 'Suspense': 'Suspense',\n 'suspense': 'Suspense',\n 'Guerra': 'Guerra',\n 'guerra': 'Guerra',\n 'Western': 'Western',\n 'western': 'Western',\n}\n\ndef init_dataset():\n dataset = pd.read_csv(CSV_URL)\n dataset.set_index('imdb_id', inplace=True)\n return dataset\n\ndef get_movie_recommendation(username, hashtags):\n recommendation = dataset[dataset.genres.str.contains('|'.join(hashtags))].sample(1)\n for row in recommendation.itertuples():\n tweet = f'Hola, {username}! Te recomiendo: \\n'\n tweet += f'{row.title} ({row.year}) [{row.spanish_title}] \\n'\n tweet += f'{row.genres} \\n' \n tweet += f'Puntuación: {row.rating} ({row.votes} votos) \\n'\n tweet += f'{IMDB_URL}{row.Index}'\n return tweet\n\ndef process_status(status):\n # Verify that the status isn't a quote.\n if status.is_quote_status:\n return\n\n # If the status is a reply to a recommendation, reply with another one. If not, ignore.\n if status.in_reply_to_status_id and status.in_reply_to_screen_name != BOT_SCREEN_NAME:\n return\n\n # If the status is a reply to a recommendation, but the authors differ, ignore the tweet.\n if status.in_reply_to_status_id and status.in_reply_to_screen_name == BOT_SCREEN_NAME:\n previous_tweet = api.get_status(status.in_reply_to_status_id_str)\n if previous_tweet.in_reply_to_screen_name != status.author.screen_name:\n return\n\n # Retrieve hashtags from the tweet. Discard any that doesn't exist in the genre list.\n hashtag_list = [GENRES[x['text']] for x in status.entities['hashtags'] if x['text'] in GENRES.keys()]\n\n username = f'@{status.author.screen_name}'\n tweet_id = status.id\n recommendation = get_movie_recommendation(username, hashtag_list)\n\n api.update_status(recommendation, tweet_id)\n\ndef init_tweepy_api():\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n api = tweepy.API(auth)\n return api\n\nclass MentionsStreamListener(tweepy.StreamListener):\n\n def on_status(self, status):\n process_status(status)\n\ndataset = init_dataset()\napi = init_tweepy_api()\n\nmentionsStreamListener = MentionsStreamListener()\nmyStream = tweepy.Stream(auth=api.auth, listener=mentionsStreamListener)\nmyStream.filter(track=[BOT_USERNAME])"
}
] | 2 |
Youssef-ZaGhloul/NetworksProject | https://github.com/Youssef-ZaGhloul/NetworksProject | 0506945ec6bc557a867e0f6a465611d6db916615 | e0d37f4e1c130021146cd5ca06edb73f850c6c70 | a93a50343a992124b386b0a8872540861c34e90e | refs/heads/master | 2020-03-11T15:16:43.489273 | 2018-04-19T16:17:04 | 2018-04-19T16:17:04 | 130,079,627 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6465116143226624,
"alphanum_fraction": 0.6790697574615479,
"avg_line_length": 19.700000762939453,
"blob_id": "31baec84701f3d124502f5214acd1ffb3cbbce9d",
"content_id": "e4d89194a352143a252965e72d8e2cb766032d1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 215,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 10,
"path": "/Server.py",
"repo_name": "Youssef-ZaGhloul/NetworksProject",
"src_encoding": "UTF-8",
"text": "import socket\r\nUDP_PORT = 8080\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\ns.bind(('', UDP_PORT))\r\n\r\nwhile True:\r\n message, ClientAddress = s.recvfrom(500)\r\n print ClientAddress\r\n print message"
},
{
"alpha_fraction": 0.5564285516738892,
"alphanum_fraction": 0.5621428489685059,
"avg_line_length": 32.09756088256836,
"blob_id": "aa6ab79a9494a530ab3eee0159fed2a463aef579",
"content_id": "3c2194526e9af11b589d32f70c690efba805dbf4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1400,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 41,
"path": "/Test.py",
"repo_name": "Youssef-ZaGhloul/NetworksProject",
"src_encoding": "UTF-8",
"text": "# define the function to split the file into smaller chunks\r\ndef splitFile(inputFile,chunkSize):\r\n # read the contents of the file\r\n f = open(inputFile, 'rb')\r\n data = f.read() # read the entire content of the file\r\n f.close()\r\n # get the length of data, ie size of the input file in bytes\r\n bytes = len(data)\r\n\r\n # calculate the number of chunks to be created\r\n noOfChunks = bytes / chunkSize\r\n if (bytes % chunkSize):\r\n noOfChunks += 1\r\n # create a info.txt file for writing metadata\r\n f = open('info.txt', 'w')\r\n f.write(inputFile + ',' + 'chunk,' + str(noOfChunks) + ',' + str(chunkSize))\r\n f.close()\r\n chunkNames = []\r\n\r\n for i in range(0, bytes + 1, chunkSize):\r\n fn1 = \"chunk%s\" % i\r\n chunkNames.append(fn1)\r\n f = open(fn1, 'wb')\r\n f.write(data[i:i + chunkSize])\r\n f.close()\r\n\r\n return noOfChunks\r\n\r\n# define the function to join the chunks of files into a single file\r\ndef joinFiles(fileName, noOfChunks, chunkSize):\r\n dataList = []\r\n for i in range(0, noOfChunks, 1):\r\n chunkNum = i * chunkSize\r\n chunkName = fileName + '%s' % chunkNum\r\n f = open(chunkName, 'rb')\r\n dataList.append(f.read())\r\n f.close()\r\n f = open(fileName +'.jpeg', 'wb')\r\n for data in dataList:\r\n f.write(data)\r\n f.close()\r\n\r\n"
},
{
"alpha_fraction": 0.5920826196670532,
"alphanum_fraction": 0.6213425397872925,
"avg_line_length": 19.518518447875977,
"blob_id": "1a4ba77cbf64ad439c24a7be197cce36a3708025",
"content_id": "c01bcae6f1818385c974d423141e617006d58417",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 581,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 27,
"path": "/Client.py",
"repo_name": "Youssef-ZaGhloul/NetworksProject",
"src_encoding": "UTF-8",
"text": "import socket\r\nimport Test\r\nimport packets\r\n\r\nUDP_IP = \"127.0.0.1\"\r\nUDP_PORT = 8080\r\nMESSAGE = \"Dexter says hai !\"\r\n\r\nprint \"UDP target IP:\", UDP_IP\r\nprint \"UDP target port:\", UDP_PORT\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\nchunkSize = 500\r\ncount = 0\r\nChunksNo = Test.splitFile('image.jpeg', chunkSize)\r\n\r\nfor i in range(0, ChunksNo, 1):\r\n chunkNum = i * chunkSize\r\n count += 1\r\n chunkName = 'chunk' + '%s' % chunkNum\r\n f = open(chunkName, 'rb')\r\n p = packets.dataPacket(count, f.read())\r\n\r\n s.sendto(str(p), (UDP_IP, UDP_PORT))\r\n\r\ns.close()\r\n"
},
{
"alpha_fraction": 0.5147929191589355,
"alphanum_fraction": 0.5384615659713745,
"avg_line_length": 13.545454978942871,
"blob_id": "d18cae9dac6f2ea8e5cb3bf93e5881fb714b952a",
"content_id": "9c64adaa0ce6b0d4c13fc83762a732e9cc3b0064",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 169,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 11,
"path": "/packets.py",
"repo_name": "Youssef-ZaGhloul/NetworksProject",
"src_encoding": "UTF-8",
"text": "class dataPacket:\r\n length = 512\r\n\r\n def __init__(self, seqno, data):\r\n self.seqNo = seqno\r\n self.data = data\r\n\r\n\r\n\r\nclass AckPacket:\r\n length = 8"
}
] | 4 |
mmackay03/PiTected-2.0-Hardware | https://github.com/mmackay03/PiTected-2.0-Hardware | 7957e44fed631fe291ba2a68570d292d2d67f18f | 47467195864bb537139adbddd296cade7d2d3a37 | 48a1b5a593e242984eff3ed554bd8d303e1258aa | refs/heads/master | 2017-12-04T17:44:10.981046 | 2016-04-28T00:17:38 | 2016-04-28T00:17:38 | 52,503,796 | 0 | 0 | null | 2016-02-25T06:57:03 | 2016-04-26T00:05:50 | 2016-04-26T00:19:23 | Java | [
{
"alpha_fraction": 0.7344992160797119,
"alphanum_fraction": 0.7519872784614563,
"avg_line_length": 24.15999984741211,
"blob_id": "3d3d550c94c1f0c9ccbd6e46e1b9dc27956ca2a8",
"content_id": "268095a80ae22901e995ff9db13945bcc06e0240",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 629,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 25,
"path": "/PiTectedPython/powerSwitch.py",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "#Author: Margo Mac Kay\n#July 2015\n#Intended to safely power off the Pi\n#Added \"sudo python /opt/pi4j/PiTected/powerSwitch.py &\" to rc.local to run on boot\n#Allow GPIO pin calls\nimport RPi.GPIO as GPIO\n#import os for linux commands\nimport os\n#import time for sleep\nimport time\n\n#set mode for Broadcom SOC channel\nGPIO.setmode(GPIO.BCM)\n#use gpio21 for input\nINPUT_PIN=26\nGPIO.setup(INPUT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n#loop\nwhile True:\n\t#wait for button to be pushed\n\tGPIO.wait_for_edge(INPUT_PIN, GPIO.FALLING)\n\t#halt command\n\tos.system('sudo shutdown -h now')\n\t#sleep for 1 second in case button is hit twice\n\ttime.sleep(1)\n"
},
{
"alpha_fraction": 0.504011332988739,
"alphanum_fraction": 0.5125058889389038,
"avg_line_length": 34.0247917175293,
"blob_id": "596a37a667876866a38874624570600b45024b50",
"content_id": "a4559ddc5da20182507b91a656861fa3ba29899c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8476,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 242,
"path": "/PiTectedJava/AlarmSystem.java",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "//Author: Margo Mac Kay\n// 19 November 2015\n/*\n * PiTected Project\n * This class is meant to be implemented in classes involving the system.\n * Addition methods/variables are to be added.\n */\nimport com.pi4j.component.lcd.LCD;\nimport com.pi4j.component.lcd.LCDBase;\nimport com.pi4j.component.lcd.impl.I2CLcdDisplay;\nimport com.pi4j.component.lcd.LCDTextAlignment;\nimport com.pi4j.io.i2c.I2CBus;\nimport com.pi4j.io.i2c.I2CDevice;\nimport com.pi4j.io.i2c.I2CFactory;\nimport com.pi4j.io.i2c.*;\nimport com.pi4j.component.*;\n\nimport com.pi4j.system.NetworkInfo;\nimport com.pi4j.system.SystemInfo;\n\nimport com.pi4j.component.lcd.LCDTextAlignment;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.io.*;\nimport java.net.*;\nimport java.nio.charset.Charset;\nimport org.json.*;\n\nimport java.util.*;\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\npublic class AlarmSystem\n{\n //create a new object of database connection class\n static DBConnection db = new DBConnection();\n //create a new object of the user class\n private static User currUser = new User();\n //Creates an int called status\n public static int status;\n public static int rsStatus;\n public static String previousStatus = \"\";\n public static String lcdStars = \"\";\n\n \n //check that the user is Authorized and call the armDisarm method\n //NEEDS TO BE UPDATED TO NOT INCLUDE RFID\n public void getCheckCode(String attribute, String attributeValue)\n {\n try {\n InputStream is = new URL(\"http://127.0.0.1/PiTected-Web-App/php/getKeys.php?pin=\" +attributeValue).openStream();\n try {\n BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName(\"UTF-8\")));\n String result = readAll(rd);\n System.out.println(result);\n JSONObject obj = new JSONObject(result);\n String key = obj.getString(\"id\");\n\n if(!key.equals(\"-1\"))\n {//If authorized user\n currUser.setUserID(Integer.parseInt(key));\n armDisarm();//Update the status of the system\n \n } else {\n System.out.println(\"NO MATCH\");\n }\n\n } finally {\n is.close();\n }\n \n \n } catch (Exception ex) {\n ex.printStackTrace();\n }\n \n \n }\n private static String readAll(Reader rd) throws IOException {\n StringBuilder sb = new StringBuilder();\n int cp;\n while ((cp = rd.read()) != -1) {\n sb.append((char) cp);\n }\n return sb.toString();\n }\n \n\n //change the status of the system and log the change\n public static void armDisarm()\n {\n int systemStatus = changeStatus();\n String[] toBeFixed = checkSensors(false);\n if (toBeFixed.length == 1 || systemStatus==0){\n try {\n // System.out.println(\"the status should be \" + status); //Debug\n db.dbConnection();\n if (systemStatus == 1){\n try { Thread.sleep(9000); } catch (Exception ex) {}\n }\n\n String updateSensors = \"UPDATE `sensors` SET `status`=\" + systemStatus + \" WHERE `type`=0;\";\n db.getStatement().executeUpdate(updateSensors);\n \n //log the system status change in table system_log\n String log = \"INSERT INTO `system_logs` (`sensor_id`, `user_id`, `status`) VALUES (0,\"\n + currUser.getUserID() + \", \" + systemStatus +\");\";\n db.getStatement().executeUpdate(log);\n\n if (status == 1){\n // System.out.println(\"System armed.\"); //Debug\n Thread arm = new Thread(new ExecuteCommand(\"omxplayer armingSound.mp3\"));\n arm.start();\n }else if (status == 0){\n // System.out.println(\"System disarmed.\"); //Debug\n\n }\n \n \n db.conClose();//close connection to not effect future connection\n } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n\n \n }\n public static int checkStatus()\n {\n try \n {\n db.dbConnection();\n //Grabs the system info from the database\n ResultSet rset = db.getStatement().executeQuery(\"SELECT `status` FROM `sensors` WHERE `type` =0;\");\n while (rset.next())\n {\n //Gets the TinyInt status value from the database and assigns it to the rsStatus variable\n rsStatus = rset.getInt(1);\n //DEBUG\n // System.out.println(\"WHILE \" + rsStatus); \n }\n \n }\n catch (ClassNotFoundException | InstantiationException| IllegalAccessException | SQLException e) \n {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return rsStatus;\n }\n public static int changeStatus()\n {\n //DEBUG\n //System.out.println(\"TEST !\"); DEBUG\n checkStatus();\n //Checks if the System is armed or disarmed\n if (rsStatus == 1)\n {\n //Changes the status to 0\n status = 0;\n // System.out.println(\"CHANGE STATUS\" + status); //Debug\n }\n else if (rsStatus == 0)\n {\n //Changes the status to 1\n status = 1;\n // System.out.println(\"CHANGE STATUS\" + status); //Debug\n }\n return status;\n }\n\n public static String sysStatus(){\n checkStatus();\n \n \n String sysStatus = \"\";\n if(rsStatus == 1){\n sysStatus = \" System Armed \";\n }else if (rsStatus == 0){\n sysStatus = \"System Disarmed\";\n }\n previousStatus = sysStatus;\n return sysStatus;\n }\n\n public static String[] checkSensors(boolean sensorType){\n List<String> toFix = new ArrayList<String>();\n String fixSensor = \"\";\n String sensorName;\n int sensorStatus;\n int numOpen = 0;\n int systemStatus = changeStatus();\n try{\n db.dbConnection();\n //Grabs the system info from the database\n ResultSet rset;\n if(sensorType == true){\n rset = db.getStatement().executeQuery(\"SELECT `name`, `status` FROM `sensors` where id != 0;\");\n }else{\n rset = db.getStatement().executeQuery(\"SELECT `name`, `status` FROM `sensors` where type=1;\");\n }\n while (rset.next()){\n //Gets the TinyInt status value from the database and assigns it to the rsStatus variable\n sensorName = rset.getString(1);\n sensorStatus = rset.getInt(2);\n \n // System.out.println(sensorStatus); //Debug \n if(sensorStatus == 1){\n\n fixSensor = sensorName;\n toFix.add(fixSensor);\n // System.out.println(\"Check \" + fixSensor); //Debug\n \n numOpen++;\n // System.out.println(\"NUMBER OPEN \" + numOpen); //Debug\n }\n\n }\n \n }catch (ClassNotFoundException | InstantiationException| IllegalAccessException | SQLException e) {\n\n }\n if (numOpen == 0){\n // System.out.println(\"ARM\");\n // armDisarm();\n toFix.add(\" READY \");\n // System.out.println(checkStatus()==1); //Debug\n }else if ((numOpen > 0) && (checkStatus()==1)){\n toFix.add(\" WARNING \");\n \n }else{\n toFix.add(\"NOT READY\");\n }\n String[] fix = new String[ toFix.size() ];\n toFix.toArray( fix );\n return fix;\n }\n\n\n \n \n}\n"
},
{
"alpha_fraction": 0.5895386338233948,
"alphanum_fraction": 0.6196886897087097,
"avg_line_length": 31.557077407836914,
"blob_id": "0c6cfab8f6188f6d3ad93f10287801d6453279c5",
"content_id": "ce2c05c2f597e1eae83710ab63386f563c165e99",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7131,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 219,
"path": "/rf24lib/RF24Network/examples/sendDataSleep_tx/sendDataSleep_tx.ino",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "/*\n Copyright (C) 2012 James Coliz, Jr. <[email protected]>\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n version 2 as published by the Free Software Foundation.\n \n Update 2014 - TMRh20\n */\n\n/**\n * Simplest possible example of using RF24Network \n *\n * TRANSMITTER NODE\n * Every 2 seconds, send a payload to the receiver node.\n */\n\n#include <RF24Network.h>\n#include <RF24.h>\n#include <SPI.h>\n#include <avr/interrupt.h>\n#include <avr/sleep.h>\n\nRF24 radio(7,8); // nRF24L01(+) radio attached using Getting Started board \nconst int sensorPin = 2;\n// variables will change:\nint lastcurSensorState = 0;\nint curSensorState = 1;\n//int wakePin = 2; // active LOW, ground this pin momentary to wake up\nint sleepStatus = 0; \n\n// the following variables are long's because the time, measured in miliseconds,\n// will quickly become a bigger number than can be stored in an int.\nlong lastDebounceTime = 0; // the last time the output pin was toggled\nlong debounceDelay = 50; // the debounce time; increase if the output flickers\n\nRF24Network network(radio); // Network uses that radio\n\nconst uint16_t this_node = 02; // Address of our node in Octal format\nconst uint16_t other_node = 00; // Address of the other node in Octal format\n\n//const unsigned long interval = 2000; //ms // How often to send 'hello world to the other unit\n\n//unsigned long last_sent; // When did we last send?\n//unsigned long packets_sent; // How many have we sent already\n\n\nstruct payload_t { // Structure of our payload\n unsigned long currState;\n unsigned long batPcnt;\n};\nint MIN_V = 1800;\n int MAX_V = 3200;\n\n//This is for sleep mode. It is not really required, as users could just use the number 0 through 10\ntypedef enum { wdt_16ms = 0, wdt_32ms, wdt_64ms, wdt_128ms, wdt_250ms, wdt_500ms, wdt_1s, wdt_2s, wdt_4s, wdt_8s } wdt_prescalar_e;\n\nbool dataFail = false;\nint batPcnt = 0;\nint lastBatPcnt = 0;\n\nvoid wakeUpNow() // here the interrupt is handled after wakeup\n{\n radio.powerUp(); \n // execute code here after wake-up before returning to the loop() function\n // timers and code using timers (serial.print and more...) will not work here.\n // we don't really need to execute any special functions here, since we\n // just want the thing to wake up\n// if(dataFail){\n// payload_t payload = {lastcurSensorState, lastBatPcnt};\n// RF24NetworkHeader header(/*to node*/ other_node);\n// bool ok = network.write(header,&payload,sizeof(payload));\n// Serial.println(\"state 2: \" + lastcurSensorState);\n// if (ok){\n// Serial.println(\"ok.\");\n// dataFail = false;\n// }else{\n//// network.setup_watchdog(10);\n// radio.powerDown();\n// network.sleepNode(2, 0);\n// dataFail = true;\n// Serial.println(\"failed.\");\n// }\n// }\n \n}\n\nvoid setup(void)\n{\n // initialize the pushbutton pin as an input:\n pinMode(sensorPin, INPUT_PULLUP);\n \n Serial.begin(9600);\n Serial.println(\"RF24Network/examples/sendData_tx/\");\n \n SPI.begin();\n radio.begin();\n// radio.setPALevel(RF24_PA_LOW);\n network.begin(/*channel*/ 90, /*node address*/ this_node);\n// attachInterrupt(0, wakeUpNow, CHANGE);\n// network.setup_watchdog(2);\n curSensorState = digitalRead(sensorPin);\n RF24NetworkHeader header(/*to node*/ other_node);\n float batteryV = readVcc();\n Serial.println(batteryV);\n batPcnt = (min(map(batteryV, MIN_V, MAX_V, 0, 100), 100));\n payload_t payload2 = {curSensorState, batPcnt};\n bool setOnBoot = network.write(header,&payload2,sizeof(payload2));\n Serial.println(\"state2: \" + curSensorState);\n if(setOnBoot){\n Serial.println(\"ok--.\");\n \n }else{\n Serial.println(\"failed--.\");\n }\n}\n\nvoid sleepNow() // here we put the arduino to sleep\n{\n \n set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here\n sleep_enable();\n attachInterrupt(0,wakeUpNow, CHANGE);\n sleep_mode(); // here the device is actually put to sleep!!\n // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP\n\n sleep_disable(); // first thing after waking from sleep:\n // disable sleep...\n detachInterrupt(0); \n\n \n \n}\n\nvoid loop() {\n radio.powerUp();\n network.update(); // Check the network regularly\n \n int sensorState = digitalRead(sensorPin);\n if (curSensorState != lastcurSensorState){\n // reset the debouncing timer\n lastDebounceTime = millis();\n }\n\n if ((millis() - lastDebounceTime) > debounceDelay) {\n if(sensorState != curSensorState){\n curSensorState = sensorState;\n float batteryV = readVcc();\n Serial.println(batteryV);\n batPcnt = (min(map(batteryV, MIN_V, MAX_V, 0, 100), 100));\n Serial.println(batPcnt);\n payload_t payload = {curSensorState, batPcnt};\n RF24NetworkHeader header(/*to node*/ other_node);\n bool ok = network.write(header,&payload,sizeof(payload));\n Serial.println(\"state: \" + sensorState);\n if (ok){\n Serial.println(\"ok.\");\n dataFail = false;\n }else{\n// network.setup_watchdog(10);\n Serial.println(\"failed.\");\n dataFail = true;\n int count = 0;\n bool ok2 = false;\n while(count < 10 && ok2 == false){\n network.update();\n// radio.powerDown();\n delay(4000);\n radio.powerUp();\n int curState = digitalRead(sensorPin);\n payload_t payload2 = {curState, batPcnt};\n ok2 = network.write(header,&payload2,sizeof(payload2));\n Serial.println(\"state2: \" + sensorState);\n if(ok2){\n Serial.println(\"ok2.\");\n ok2 = true;\n }else{\n Serial.println(\"failed2.\");\n }\n count++;\n radio.powerDown();\n }\n \n }\n }\n }\n delay(100);\n lastcurSensorState = sensorState;\n lastBatPcnt = batPcnt;\n// radio.powerDown();\n// sleepNow();\n\n}\n\n\nlong readVcc() {\n // Read 1.1V reference against AVcc\n // set the reference to Vcc and the measurement to the internal 1.1V reference\n #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)\n ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);\n #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)\n ADMUX = _BV(MUX5) | _BV(MUX0);\n #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)\n ADMUX = _BV(MUX3) | _BV(MUX2);\n #else\n ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);\n #endif \n \n delay(2); // Wait for Vref to settle\n ADCSRA |= _BV(ADSC); // Start conversion\n while (bit_is_set(ADCSRA,ADSC)); // measuring\n \n uint8_t low = ADCL; // must read ADCL first - it then locks ADCH \n uint8_t high = ADCH; // unlocks both\n \n long result = (high<<8) | low;\n \n result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000\n return result; // Vcc in millivolts\n}\n\n"
},
{
"alpha_fraction": 0.5766571760177612,
"alphanum_fraction": 0.6118340492248535,
"avg_line_length": 25.29946517944336,
"blob_id": "9d7f532e8104319f92a2af8a5824b554781ab61d",
"content_id": "651101b504863b4a783f2128607ea57a0298192c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 4918,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 187,
"path": "/pitected4.24.sql",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "-- phpMyAdmin SQL Dump\n-- version 4.0.4.1\n-- http://www.phpmyadmin.net\n--\n-- Host: 127.0.0.1\n-- Generation Time: Apr 25, 2016 at 05:25 AM\n-- Server version: 5.5.32\n-- PHP Version: 5.4.16\n\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\nSET time_zone = \"+00:00\";\n\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!40101 SET NAMES utf8 */;\n\n--\n-- Database: `pitected`\n--\nCREATE DATABASE IF NOT EXISTS `pitected` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\nUSE `pitected`;\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `camera`\n--\n\nCREATE TABLE IF NOT EXISTS `camera` (\n `picture_id` int(11) NOT NULL AUTO_INCREMENT,\n `location` varchar(64) DEFAULT NULL,\n `date_taken` date DEFAULT NULL,\n PRIMARY KEY (`picture_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `sensors`\n--\n\nCREATE TABLE IF NOT EXISTS `sensors` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(20) NOT NULL,\n `type` int(11) NOT NULL DEFAULT '0',\n `status` int(1) DEFAULT NULL,\n `batPcnt` int(11) NOT NULL,\n `nodeID` varchar(2) DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `sensor_typeFK_idx` (`type`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;\n\n--\n-- RELATIONS FOR TABLE `sensors`:\n-- `type`\n-- `sensor_type` -> `id`\n--\n\n--\n-- Dumping data for table `sensors`\n--\n\nINSERT INTO `sensors` (`id`, `name`, `type`, `status`, `batPcnt`, `nodeID`) VALUES\n(0, 'System', 0, 0, 0, '00'),\n(1, 'Front Door', 1, 0, 70, '2');\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `sensor_type`\n--\n\nCREATE TABLE IF NOT EXISTS `sensor_type` (\n `id` int(11) NOT NULL,\n `name` varchar(45) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n--\n-- Dumping data for table `sensor_type`\n--\n\nINSERT INTO `sensor_type` (`id`, `name`) VALUES\n(0, 'System'),\n(1, 'Door'),\n(2, 'Motion Sensor'),\n(3, 'Camera');\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `system`\n--\n\nCREATE TABLE IF NOT EXISTS `system` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `staticIP` varchar(15) NOT NULL,\n `passphrase` char(32) NOT NULL,\n `status` int(1) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;\n\n--\n-- Dumping data for table `system`\n--\n\nINSERT INTO `system` (`id`, `staticIP`, `passphrase`, `status`) VALUES\n(1, '', '', 1);\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `system_logs`\n--\n\nCREATE TABLE IF NOT EXISTS `system_logs` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `sensor_id` int(11) NOT NULL,\n `user_id` int(11) NOT NULL,\n `status` int(1) NOT NULL,\n `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n KEY `user_idFK_idx` (`user_id`),\n KEY `sensor_idFK_idx` (`sensor_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;\n\n--\n-- RELATIONS FOR TABLE `system_logs`:\n-- `sensor_id`\n-- `sensors` -> `id`\n-- `user_id`\n-- `users` -> `id`\n--\n\n--\n-- Dumping data for table `system_logs`\n--\n\nINSERT INTO `system_logs` (`id`, `sensor_id`, `user_id`, `status`, `timestamp`) VALUES\n(3, 1, 0, 1, '2016-04-01 18:56:49');\n\n-- --------------------------------------------------------\n\n--\n-- Table structure for table `users`\n--\n\nCREATE TABLE IF NOT EXISTS `users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `username` varchar(30) NOT NULL,\n `password` varchar(64) NOT NULL,\n `pin` varchar(64) NOT NULL,\n `session` varchar(64) NOT NULL,\n `privileges` varchar(3) DEFAULT NULL,\n `gcm_token` varchar(64) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;\n\n--\n-- Dumping data for table `users`\n--\n\nINSERT INTO `users` (`id`, `username`, `password`, `pin`, `session`, `privileges`, `gcm_token`) VALUES\n(0, 'rob', 'ab64a4d1fbde4abfc7243c25e253eb08c9ddc557be914b29302b171dd676c2f5', '9d9f9088239acd0ae359a8e1d7bf8535f7a6418a528c8847e1fc116726560b3a', '5717ce039df07', NULL, NULL);\n\n--\n-- Constraints for dumped tables\n--\n\n--\n-- Constraints for table `sensors`\n--\nALTER TABLE `sensors`\n ADD CONSTRAINT `sensor_typeFK` FOREIGN KEY (`type`) REFERENCES `sensor_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;\n\n--\n-- Constraints for table `system_logs`\n--\nALTER TABLE `system_logs`\n ADD CONSTRAINT `sensor_idFK` FOREIGN KEY (`sensor_id`) REFERENCES `sensors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,\n ADD CONSTRAINT `user_idFK` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;\n\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n"
},
{
"alpha_fraction": 0.7169811129570007,
"alphanum_fraction": 0.7358490824699402,
"avg_line_length": 16.75,
"blob_id": "e8b65f8d8e2966dec47774423e870445bf2a2152",
"content_id": "b4653229eef847b1f1a70b71c1316da70df151e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 12,
"path": "/rf24lib/RF24Network/examples_RPi/dbConnection.h",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "#ifndef DBCONNECTION_H\n#define DBCONNECTION_H\n\nclass db{\npublic:\n\tvoid setUpDB(void);\n\tvoid sensorLog(uint16_t n, int status);\n\tvoid updateSensor(uint16_t n, int batPcnt, int status);\n\tint sysStatus();\n\n};\n#endif"
},
{
"alpha_fraction": 0.5851966142654419,
"alphanum_fraction": 0.599845826625824,
"avg_line_length": 27.217391967773438,
"blob_id": "0cfc602b2f8936f199215c32078b425bfcf724a4",
"content_id": "e7244bb45fd20737133d83554d5adbb966fbba09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1297,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 46,
"path": "/PiTectedJava/Notification.java",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "import java.io.*;\nimport java.net.*;\nimport java.util.*;\npublic class Notification{\n\tpublic static AlarmSystem sys = new AlarmSystem();\n\tpublic static int notificationCount = 0;\n\n\tpublic static void main(String[] args){\n\t\twhile(true){\n\t\t\tString[] toBeFixed = sys.checkSensors(true);\n\t\t\tif ((toBeFixed.length > 1) && (sys.checkStatus() == 1)){\n\t\t\t\ttry { Thread.sleep(9000); } catch (Exception ex) {}\n\t\t\t\tif (sys.checkStatus() == 1){\n\t\t\t\t\tif(notificationCount == 0){\n\t\t\t\t\t\tsendNotification();\n\t\t\t\t\t}\n\t\t\t\t\tThread alert = new Thread(new ExecuteCommand(\"omxplayer alertSound2.mp3\"));\n\t\t\t\t\talert.start();\n\t\t\t\t\tnotificationCount++;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif (sys.checkStatus() == 0){\n\t\t\t\t\t// System.out.println(\"reset notificationCount\");\n\t\t\t\t\tnotificationCount = 0;\n\t\t\t}\n\n\t\t}\n\t}\n\t\n\n\tpublic static void sendNotification(){\n // System.out.println(\"Sending notification\");\n\n try {\n URL url = new URL(\"http://127.0.0.1/PiTected-Web-App/php/sendNotifications.php\");\n BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));\n String strTemp = \"\";\n while (null != (strTemp = br.readLine())) {\n System.out.println(strTemp);\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n}"
},
{
"alpha_fraction": 0.5887130498886108,
"alphanum_fraction": 0.621616005897522,
"avg_line_length": 27.730539321899414,
"blob_id": "e3650b4179bea22bdde28dec2d3aa8220e04bd19",
"content_id": "35e566dde76bdf8b44981d267254fd11ad29ae88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4802,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 167,
"path": "/rf24lib/RF24Network/examples/motionVCC/motionVCC.ino",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "/*\n Copyright (C) 2012 James Coliz, Jr. <[email protected]>\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n version 2 as published by the Free Software Foundation.\n \n Update 2014 - TMRh20\n */\n\n/**\n * Simplest possible example of using RF24Network \n *\n * TRANSMITTER NODE\n * Every 2 seconds, send a payload to the receiver node.\n */\n\n#include <RF24Network.h>\n#include <RF24.h>\n#include <SPI.h>\n#include <avr/interrupt.h>\n#include <avr/sleep.h>\n\nRF24 radio(7,8); // nRF24L01(+) radio attached using Getting Started board \n\n\nRF24Network network(radio); // Network uses that radio\n\n//MY NEED TO UPDATE DEPENDING ON OTHER NODES\n//NO NODES SHOULD HAVE THE SAME ADDRESS - range 01-06\nconst uint16_t this_node = 03; // Address of our node in Octal format\nconst uint16_t other_node = 00; // Address of the other node in Octal format\n\n\n/////////////////////////////\n//VARS\n//the time we give the sensor to calibrate (10-60 secs according to the datasheet)\nint calibrationTime = 30; \n\n//the time when the sensor outputs a low impulse\nlong unsigned int lowIn; \n\n//the amount of milliseconds the sensor has to be low \n//before we assume all motion has stopped\nlong unsigned int pause = 5000; \n\nboolean lockLow = true;\nboolean takeLowTime; \n\nint pirPin = 2; //the digital pin connected to the PIR sensor's output\n\n\nstruct payload_t { // Structure of our payload\n unsigned long currState;\n unsigned long batPcnt;\n};\nint MIN_V = 1900;\n int MAX_V = 3200;\n \nvoid wakeUpNow() // here the interrupt is handled after wakeup\n{\n // execute code here after wake-up before returning to the loop() function\n // timers and code using timers (serial.print and more...) will not work here.\n // we don't really need to execute any special functions here, since we\n // just want the thing to wake up\n \n}\n\nvoid setup(void)\n{\n Serial.begin(9600);\n \n pinMode(pirPin, INPUT);\n// digitalWrite(pirPin, LOW);\n\n //give the sensor some time to calibrate\n Serial.print(\"calibrating sensor \");\n for(int i = 0; i < calibrationTime; i++){\n Serial.print(\".\");\n delay(1000);\n }\n Serial.println(\" done\");\n Serial.println(\"SENSOR ACTIVE\");\n delay(50);\n\n \n \n Serial.println(\"RF24Network/examples/sendData_tx/\");\n \n SPI.begin();\n radio.begin();\n// radio.setPALevel(RF24_PA_LOW);\n network.begin(/*channel*/ 90, /*node address*/ this_node);\n// attachInterrupt(0, wakeUpNow, CHANGE);\n}\n\nvoid sleepNow() // here we put the arduino to sleep\n{\n \n set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here\n sleep_enable();\n attachInterrupt(0,wakeUpNow, CHANGE);\n sleep_mode(); // here the device is actually put to sleep!!\n // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP\n\n sleep_disable(); // first thing after waking from sleep:\n // disable sleep...\n detachInterrupt(0); \n\n \n \n}\n\nvoid loop() {\n radio.powerUp(); \n\n\n payload_t payload;\n\n\nbool tripped = digitalRead(pirPin) == HIGH;\n float batteryV = readVcc();\n Serial.println(batteryV);\n int batPcnt = (min(map(batteryV, MIN_V, MAX_V, 0, 100), 100));\n Serial.println(batPcnt);\n if (tripped == true){\n payload = {1, batPcnt};\n }else if (tripped == false){\n payload = {0, batPcnt};\n }\n \n RF24NetworkHeader header(/*to node*/ other_node);\n bool ok = network.write(header,&payload,sizeof(payload));\n if (ok)\n Serial.println(\"ok.\");\n else\n Serial.println(\"failed.\");\n \n \n radio.powerDown();\n sleepNow();\n}\n\nlong readVcc() {\n // Read 1.1V reference against AVcc\n // set the reference to Vcc and the measurement to the internal 1.1V reference\n #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)\n ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);\n #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)\n ADMUX = _BV(MUX5) | _BV(MUX0);\n #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)\n ADMUX = _BV(MUX3) | _BV(MUX2);\n #else\n ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);\n #endif \n \n delay(2); // Wait for Vref to settle\n ADCSRA |= _BV(ADSC); // Start conversion\n while (bit_is_set(ADCSRA,ADSC)); // measuring\n \n uint8_t low = ADCL; // must read ADCL first - it then locks ADCH \n uint8_t high = ADCH; // unlocks both\n \n long result = (high<<8) | low;\n \n result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000\n return result; // Vcc in millivolts\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.5872923135757446,
"alphanum_fraction": 0.5945788621902466,
"avg_line_length": 25.190839767456055,
"blob_id": "214e2bb554251763f264e89149e15e0466f32aad",
"content_id": "5b4bed4347e04000911b0596f84d3d8b74e89757",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3431,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 131,
"path": "/rf24lib/RF24Network/examples_RPi/dbConnection.cpp",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "/*Author: by Margo Mac Kay\nSpring 2016\nTo be used on the PiTected 2.0 project.\nTo be implemented in receiveData.cpp to update the database with the current status of the sensors\n*/\n\n\n\n/* Standard C++ includes */\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <stdio.h>\n#include \"mysql_connection.h\"\n\n#include <cppconn/driver.h>\n#include <cppconn/exception.h>\n#include <cppconn/resultset.h>\n#include <cppconn/statement.h>\n#include <cppconn/prepared_statement.h>\n#include \"dbConnection.h\"\n\nusing namespace std;\nsql::Connection *con;\n\n//connect with the database\nvoid db::setUpDB(void){\n\ttry {\n\tsql::Driver *driver;\n\t//sql::Connection *con;\n\tdriver = get_driver_instance();\n\n\tcon = driver->connect(\"tcp://127.0.0.1:3306\", \"root\", \"Tected\");\n\t/* Connect to the MySQL test database */\n\tcon->setSchema(\"pitected\");\n\t}\n\tcatch (sql::SQLException &e) {\n\t\tcout << \"# ERR: SQLException in \" << __FILE__;\n\t\tcout << \"(\" << __FUNCTION__ << \") on line \" << __LINE__ << endl;\n\t\tcout << \"# ERR: \" << e.what();\n\t\tcout << \" (MySQL error code: \" << e.getErrorCode();\n\t\tcout << \", SQLState: \" << e.getSQLState() << \" )\" << endl;\n\t}\n\n}\n\n\n\n//update the sensor status in the database\nvoid db::sensorLog(uint16_t n, int status){\n\t//int sysStatus = sysStatus();\n\t//int sensorType = sensorType(n);\n\ttry {\n\t\tsql::ResultSet *res;\n\t\tsql::PreparedStatement *pstmt;\n\n\t\t\n\t\t\tstd::string query = \"INSERT INTO `system_logs`(`sensor_id`, `user_id`, `status`) VALUES ((SELECT `id` FROM `sensors` where `nodeID`= \" + std::to_string(n) + \") , 0 ,\" + std::to_string(status) + \");\";\n\t\t\tpstmt = con->prepareStatement(query.c_str());\n\t\t\tres = pstmt->executeQuery();\n\t\t\n\n\t\tdelete pstmt;\n\t\tdelete res;\n\t}\n\tcatch (sql::SQLException &e) {\n\t\tcout << \"# ERR: SQLException in \" << __FILE__;\n\t\tcout << \"(\" << __FUNCTION__ << \") on line \" << __LINE__ << endl;\n\t\tcout << \"# ERR: \" << e.what();\n\t\tcout << \" (MySQL error code: \" << e.getErrorCode();\n\t\tcout << \", SQLState: \" << e.getSQLState() << \" )\" << endl;\n\t}\n\n\tcout << endl;\n}\n\nvoid db::updateSensor(uint16_t n, int batPcnt, int status){\n\ttry {\n\t\tsql::ResultSet *res;\n\t\tsql::PreparedStatement *pstmt;\n\n\t\tstd::string query = \"UPDATE `sensors` SET `batPcnt`= \" + std::to_string(batPcnt) + \", `status` = \" + std::to_string(status) + \" where `nodeID`= \" + std::to_string(n) + \"; \";\n\t\tpstmt = con->prepareStatement(query.c_str());\n\t\tres = pstmt->executeQuery();\n\t\tdelete pstmt;\n\t\tdelete res;\n\n\t\tif (sysStatus() == 1){\n\t\t\tsensorLog(n, status);\n\t\t}\n\t\t\n\t}\n\tcatch (sql::SQLException &e) {\n\t\tcout << \"# ERR: SQLException in \" << __FILE__;\n\t\tcout << \"(\" << __FUNCTION__ << \") on line \" << __LINE__ << endl;\n\t\tcout << \"# ERR: \" << e.what();\n\t\tcout << \" (MySQL error code: \" << e.getErrorCode();\n\t\tcout << \", SQLState: \" << e.getSQLState() << \" )\" << endl;\n\t}\n\n\tcout << endl;\n}\n\nint db::sysStatus(){\n\tint sysStatus = 0;\n\ttry {\n\t\tsql::ResultSet *res;\n\t\tsql::PreparedStatement *pstmt;\n\n\t\tpstmt = con->prepareStatement(\"SELECT `status` FROM `system` WHERE `id` = 1;\");\n\t\tres = pstmt->executeQuery();\n\n\t\twhile (res->next()) {\n\t\t\tsysStatus = res->getInt(1);\n\t\t}\n\n\t\tdelete pstmt;\n\t\tdelete res;\n\t}\n\n\tcatch (sql::SQLException &e) {\n\t\tcout << \"# ERR: SQLException in \" << __FILE__;\n\t\tcout << \"(\" << __FUNCTION__ << \") on line \" << __LINE__ << endl;\n\t\tcout << \"# ERR: \" << e.what();\n\t\tcout << \" (MySQL error code: \" << e.getErrorCode();\n\t\tcout << \", SQLState: \" << e.getSQLState() << \" )\" << endl;\n\t}\n\n\treturn sysStatus;\n}\n"
},
{
"alpha_fraction": 0.6581876277923584,
"alphanum_fraction": 0.6618971824645996,
"avg_line_length": 33.30908966064453,
"blob_id": "51b7817c70552964008ad8b1b2dd0612e24efd91",
"content_id": "df9c1db5f97147e424f4f12d463d25eec5e464c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1887,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 55,
"path": "/PiTectedJava/Keypad.java",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "//Author: Margo Mac Kay\n//November 2015\n/*\n * PiTected Project\n * Implements KeyboardController class\n * This class is meant to accept user input on the keypad and compare the code entered with the user codes within the pitected\n * database. * will be used to disarm the system and # will be used to arm the system.\n */\n\npublic class Keypad{\n\n\t//initiate variables\n\tstatic String enteredCode = \"\";\n\tstatic String stars = \"\";\n\tstatic char armDisarm = '#';\n\tpublic static int status;\n\tstatic AlarmSystem sys = new AlarmSystem();//create a new object of the AlarmSystem class\n\t// static DisplayDate display = new DisplayDate();\n\t//main\n\tpublic static void main(String[] args) {\n\n\t\t//create new keyboard object\n\t\tKeyboardController kbc = new KeyboardController();\n\t\t\n\t\t//continuous while loop. Ensures the keypad will continue to accept characters being pressed even after code is entered\n\t\t//or an incorrect code is entered\n\t\twhile(true){\n\t\t\t//variable to control the while loop\n\t\t boolean go = true;\n\t\t while (go){\n\t\t char inputChar = kbc.getKey();\n\t\t if (armDisarm == inputChar){//if # button is entered end the loop and arm the system is authorized user\n\t\t \t go = false;//end loop\n\t\t \t // System.out.println(\"STATUS: \" + status);\n\t\t }else{//continuously add each character pressed (Except * and # characters)\n\t\t \t enteredCode += inputChar;\n\t\t }\n\t\t // System.out.println(\"Char: \" + inputChar);//debugging: show key pressed\n\t\t \n\t\t try { Thread.sleep(200L); } catch (Exception ex) {}\n\t\t }\n\t\t // System.out.println(\"Entered: \" + enteredCode);\n\t\t // System.out.println(\"STATUS AFTER: \" + status);\n\t\t // System.out.println(getStars());\n\t\t sys.getCheckCode(\"keyCode\", enteredCode);\n\t\t enteredCode =\"\";//reset the entered code for future entries\n\t\t // display.stars = \"\";\n\t\t kbc.shutdown();//gpio shutdown\n\t\t}\n\t \n\t}\n\n\t\n\n}\n"
},
{
"alpha_fraction": 0.6367713212966919,
"alphanum_fraction": 0.6771300435066223,
"avg_line_length": 30.85714340209961,
"blob_id": "42869c4cf246eeda3232ceecb8cb3aceeec3624a",
"content_id": "58fe1b30e026b63b216208b394c32877d5c4a19b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 223,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 7,
"path": "/PiTectedJava/picam.sh",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "#! /bin/bash\nps -ef | grep -c \"/opt/pi4j/PiTected-2.0-Hardware/PiTectedPython/pitectedCam.py\"\nif [ $? -gt 0 ]; then\n sudo python /opt/pi4j/PiTected-2.0-Hardware/PiTectedPython/pitectedCam.py\n exit 1\nfi\nexit 1\n"
},
{
"alpha_fraction": 0.6602451801300049,
"alphanum_fraction": 0.7054290771484375,
"avg_line_length": 25.91509437561035,
"blob_id": "39f45ea081b805859aeb1b8de4f8927b352ff9dd",
"content_id": "c6418dc5fd7c7108618cab4822774122488dfb12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2855,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 106,
"path": "/rf24lib/RF24Network/examples_RPi/receiveData.cpp",
"repo_name": "mmackay03/PiTected-2.0-Hardware",
"src_encoding": "UTF-8",
"text": "/*Author: Margo Mac Kay\nSpring 2016\nTo be used on the PiTected 2.0 project.\nReceives data from the sensors then implements dbConnection.cpp to update the database with the current sensor status.\nImplements the RF24Network library from TMRh20 off github: https://github.com/TMRh20/RF24Network\n\tRF24Network documentation page: http://tmrh20.github.io/RF24Network/index.html\n\nUses NRF240l1 radio modules to transmit data from the sensors (which use Arduino micro controlers) to send data to the Raspberry Pi\n\n*/\n\n//RF24Network library includes\n#include <RF24/RF24.h>\n#include <RF24Network/RF24Network.h>\n#include <RF24Network/Sync.h>\n#include <ctime>\n#include <stdio.h>\n#include <time.h>\n\n/* Standard C++ includes */\n#include <stdlib.h>\n#include <iostream>\n//database connection\n#include \"dbConnection.h\"\n\n\n//using namespace std;\n\n/**\n * g++ -L/usr/lib main.cc -I/usr/include -o main -lrrd\n **/\n//using namespace std;\n\n// CE Pin, CSN Pin, SPI Speed\n\n// Setup for GPIO 22 CE and GPIO 25 CSN with SPI Speed @ 1Mhz\n//RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_18, BCM2835_SPI_SPEED_1MHZ);\n\n// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 4Mhz\n//RF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_4MHZ); \n\n// Setup for GPIO 22 CE and CE1 CSN with SPI Speed @ 8Mhz\nRF24 radio(RPI_V2_GPIO_P1_15, BCM2835_SPI_CS0, BCM2835_SPI_SPEED_8MHZ); \n\n//start radio network\t\nRF24Network network(radio);\n\n\n// Address of our node in Octal format\nconst uint16_t this_node = 00;\n\n\n// Address of the other node in Octal format (01,021, etc)\n//const uint16_t other_node = 02;\n\nunsigned int status;\n\n\n//Structure payload to receive the status of the sensor as well as the battery percentage\nstruct payload_Sensor { // Structure of our payload\n\tunsigned long currState;\n\tunsigned long batPcnt;\n};\n\n\nint main(int argc, char** argv) \n{\n\t// Refer to RF24.h or nRF24L01 DS for settings\n\tradio.begin();\n\t\n\tdelay(5);\n\tnetwork.begin(/*channel*/ 90, /*node address*/ this_node);\n\n\tradio.printDetails();\n\tdb sensor;\t\n\tsensor.setUpDB();\n\twhile(1)\n\t{\n\t\t\n\t\t//status = sensor.sysStatus(); //get rid of sysStatus method???\n\t\t network.update();\n\n\t\t \n \t\t while ( network.available() ) {\t// Is there anything ready for us?\n \t\t\t\n\t\t\t//initalize the header and payload\n\t\t \tRF24NetworkHeader header; \n\t\t\tpayload_Sensor payload;\n\t\t\t //receive the payload\n \t\t\tnetwork.read(header,&payload,sizeof(payload));\n\n\t\t\tsensor.updateSensor(header.from_node, payload.batPcnt, payload.currState);//update the battery percentage in the database\n\t\t\t\n\t\t\t//debug - print out the node, sensor state, and battery percentage\n\t\t\tprintf(\"Unknown message received from node %i\\n\", header.from_node);\n\t\t\tprintf(\"Updated sensor status: %lu\\n\", payload.currState);\n\t\t\tprintf(\"Battery percent: %lu\\n\", payload.batPcnt);\n\t\t\t \n\t\t\n\t\t}\t\t \n\t\t //sleep(2);\n\t\t delay(2000);\n\t}\n\n\treturn 0;\n}\n\n\n"
}
] | 11 |
mrlio/TestR | https://github.com/mrlio/TestR | cae3f6dcf82ec5ab0d5bd7d02e8dcab928e2f6b6 | 97df9b9c54c515deaf9d3231ffe244c9e89f24f8 | 6aba08afb009f5c6ead8368d19ac6ccb73d83d62 | refs/heads/master | 2021-02-13T19:14:10.171265 | 2020-03-03T19:44:45 | 2020-03-03T19:44:45 | 244,723,463 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4615384638309479,
"alphanum_fraction": 0.4615384638309479,
"avg_line_length": 11.333333015441895,
"blob_id": "23d130b1a84598b428c10ea67027c11a36fddaa2",
"content_id": "7752f834982afd3f7aa45cf54253f0bac9a6d252",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 39,
"license_type": "no_license",
"max_line_length": 13,
"num_lines": 3,
"path": "/myClass101.py",
"repo_name": "mrlio/TestR",
"src_encoding": "UTF-8",
"text": "\n\nclass Meo:\n def meo():\n pass\n"
}
] | 1 |
ING559/Syllabus-2020-2 | https://github.com/ING559/Syllabus-2020-2 | 1f94ba2df98cdc26d8e8bc1312d6a577f19bb0ef | e958fb1550cac971a1b88952457d74e7c9d457e1 | e120cc3f491a9b43b743fa7cd4983f24f2380040 | refs/heads/master | 2023-06-28T03:04:13.806802 | 2021-07-26T16:37:58 | 2021-07-26T16:37:58 | 286,086,179 | 12 | 19 | null | null | null | null | null | [
{
"alpha_fraction": 0.7333333492279053,
"alphanum_fraction": 0.7587301731109619,
"avg_line_length": 44,
"blob_id": "dee33c176a655e3a667409991ce8837035aa10e9",
"content_id": "cee501874298a91a88b61a7b2e011332f94f9d26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 7,
"path": "/Material Complementario/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Material complementario\n\nAquí hay una lista de recursos que pueden ser útiles durante el curso:\n\n- [Crash Course de la Terminal](https://www.youtube.com/watch?v=vaaiNE9BH5c&feature=emb_logo)\n- [Git parte 1](https://www.youtube.com/watch?v=NE5DtjniO8A)\n- [Git parte 2](https://www.youtube.com/watch?v=UwZD0DekZP4)\n"
},
{
"alpha_fraction": 0.6935279369354248,
"alphanum_fraction": 0.7404822111129761,
"avg_line_length": 53.344825744628906,
"blob_id": "29c9361479edf99a218f8d63843bab39eaf90764",
"content_id": "099ce44b98604755e6df67d9238f285de13f11cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1592,
"license_type": "no_license",
"max_line_length": 198,
"num_lines": 29,
"path": "/Clases Online/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Clases Online\n\nPuedes descargar las clases desde la siguiente [carpeta compartida](https://alumnosuaicl-my.sharepoint.com/:f:/g/personal/adrian_soto_uai_cl/ElcGwgiqYltBoaQvrmRn9n8By7YuxCbZFfQFOgAk6tbAOw?e=2UGUIb).\n\nTambién te dejo el listado a los links a YouTube para que puedas ver a 1.5x las clases del curso.\n\n- [Clase 01 - Introducción](https://youtu.be/CLEKffXS6Vs)\n- [Clase 02 - Python y Numpy](https://youtu.be/hLtnnEsqJbI)\n- [Clase 03 - Pandas y Scikit Learn](https://youtu.be/wiqScM1qZ0I)\n- [Clase 04 - Clasificación y medidas de desempeño pt. 1](https://youtu.be/u7pFKW47hEI)\n- [Clase 05 - Desempeño pt. 2 - Clasificación Multiclase - Naive Bayes](https://youtu.be/CdfBznWYdwk)\n- [Clase 06 - Regresión Lineal y Gradient Descent](https://youtu.be/HblwS9uQ808)\n- [Clase 07 - Regresión Logística y Softmax](https://youtu.be/_AwjhBK1D40)\n- [Clase 08 - Análisis Teórico del Error](https://youtu.be/XNkyzlx4r7M)\n- [Clase 09 - KNN, Features y SVM](https://youtu.be/fRjZFvt_8VU)\n- [Clase 10 - SVM y Kernel](https://youtu.be/BDjIe1dbp-A)\n- [Clase 11 - Árboles de Decisión](https://youtu.be/ZyI03fTafak)\n- [Clase 12 - Random Forests](https://youtu.be/ALivu-yHeQk)\n- [Clase 13 - Reducción de Dimensionalidad y Clustering](https://youtu.be/2kx1DP-BxxA)\n- [Clase 14 - Redes Neuronales](https://youtu.be/hbzXwpJgsKc)\n- [Clase 15 - CNN](https://youtu.be/18Us3gl8mhc) \n\n# Talleres\n\n- [Taller 01 - Terminal y Servidores](https://youtu.be/L93BPUL1Hv8)\n\n# Otros\n- [Consultas Naive Bayes](https://youtu.be/rCbxiBiI4vI)\n- [Consultas Regresión Logística](https://youtu.be/LS3WB8M3fMI)\n"
},
{
"alpha_fraction": 0.7487684488296509,
"alphanum_fraction": 0.7660098671913147,
"avg_line_length": 49.75,
"blob_id": "a7cfce058439158d0f294f799942a7feb067239f",
"content_id": "20872b664bafc45c144af68f0e53bf4b597086dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 409,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 8,
"path": "/Jupyter y Apuntes/C09 - SVM/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Algunos recursos extra para estudiar SVM\n\n- [Video introductorio](https://www.youtube.com/watch?v=Y6RRHw9uN9o)\n- [Video más avanzado sobre SVM en general](https://www.youtube.com/watch?v=efR1C6CvhmE)\n- [Video sobre Kernel Polinomial](https://www.youtube.com/watch?v=Toet3EiSFcM)\n- [Clase del MIT sobre SVM](https://www.youtube.com/watch?v=_PwhiWxHK8o)\n\nAdemás les subí en esta carpeta el paper original.\n"
},
{
"alpha_fraction": 0.5916115045547485,
"alphanum_fraction": 0.6136865615844727,
"avg_line_length": 17.91666603088379,
"blob_id": "ad47de8b20670dd7a2d7640c26048c111ed2ef96",
"content_id": "5d5536cb94031874ab7579c0f1f39ec3bffa2cf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 453,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 24,
"path": "/Actividades/Actividad 00 (Bonus) - Introducción a Python/generate_data.py",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "import random\nimport csv\n\ndates = range(1, 6)\n\ndata = []\nfor i in dates:\n scored = set()\n for j in range(20):\n scored.add(random.randint(1,30))\n for player in scored:\n goals = random.randint(1,4)\n t = (f'Jugador {player}', i, goals)\n data.append(t)\n\nrandom.shuffle(data)\n\ndata_file = open('data.csv', 'w', encoding='utf-8')\nwriter = csv.writer(data_file)\n\nfor row in data:\n writer.writerow(row)\n\ndata_file.close()"
},
{
"alpha_fraction": 0.7568230628967285,
"alphanum_fraction": 0.7743023633956909,
"avg_line_length": 74.83721160888672,
"blob_id": "38b4d141df4b4c3a96a84c5dc1b6adcbd119ec9b",
"content_id": "c44737cbc1e48f8b812cac5a566c2f0c253ea60f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3312,
"license_type": "no_license",
"max_line_length": 311,
"num_lines": 43,
"path": "/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# ING559 - Métodos de Aprendizaje de Máquinas en Data Science\n\n## Notas\n\nSi eres alumno del curso puedes encontrar tus notas [aquí](https://docs.google.com/spreadsheets/d/1NUkfwFQvWtoB6-i3suTd8MaxqtGHhTekOHkSIsHvocs/edit?usp=sharing) :smile:.\n\n## Descripción del curso\n\nDurante el curso el alumno aprenderá el flujo de trabajo que debe seguir un _data scientist_ al involucrarse en un proyecto de _Machine Learning_. También se espera que el alumno obtenga conocimiento de los modelos y técnicas más famosas del área tanto a nivel teórico como práctico:\n\n- Desde el punto de vista teórico, el alumno aprenderá la formalización del problema de aprendizaje desde el punto de vista estadístico. Además, el alumno será capaz de entender los fundamentos teóricos de los modelos vistos en este curso.\n- Desde el punto de vista práctico, el curso contempla el estudio de _frameworks_ y liberías ampliamente utilizados en entornos de producción de proyectos de _Machine Learning_.\n\nFinalmente, también se contempla estudiar técnicas para medir el desempeño de estos algoritmos y optimizar su funcionamiento. Al final del curso el alumno conocerá en qué contexto usar cada uno de los modelos, entendiendo sus ventajas y desventajes. Además podrá desarrollar algunos de estos modelos desde cero.\n\n## Evaluaciones\n| Evaluación | Fecha de publicación | Contenido |\n|---|---|---|\n| Actividad 00 | 19 de agosto | Introducción a Python |\n| Actividad 01 | 26 de agosto | Pandas y Scikit Learn |\n| Actividad 02 | 09 de septiembre | Clasificación y Naive Bayes |\n| Control 01 | 16 de septiembre | Regresión Lineal, Polinomial y Gradient Descent |\n| Actividad 03 | 30 de septiembre | Regresión Logística |\n| Actividad 04 | 28 de octubre | SVM y Kernels |\n| Control (Bonus) | 04 de noviembre | Árboles de Decisión |\n| Actividad 05 | 11 de noviembre | Random Forest y Boosting |\n| Actividad (Bonus) | 18 de noviembre | Reducción de Dimensionalidad y Clustering |\n| Control 02 | 25 de noviembre | Introducción a Redes Neuronales |\n| Actividad 06 | 02 de diciembre | Redes Convolucionales |\n\n## Foro\n\nLa página de [_Issues_](https://github.com/ING559/Syllabus-2020-2/issues) se utilizará como foro para preguntas. Notar que las etiquetas ya se encuentran definidas. **Este es el único canal oficial para formular preguntas**.\n\nTanto al publicar como comentar, debes atenerte a las **normas**, que consisten en:\n\n- Primero revisa las _issues_, ya que la pregunta que vas a hacer puede haber sido respondida antes.\n- Dar un nombre descriptivo a tu _issue_. Recuerda que la respuesta a tu duda le puede servir a alguien más, así que un nombre descriptivo es lo más fácil para que tus compañeros sepan que se discutió en cada una.\n- Asignar a tu _issue_ la etiqueta que le corresponde.\n- No mostrar/adjuntar todo tu código, sino del fragmento en el que tienes un problema o duda.\n- Dentro de lo posible, usar [Markdown](https://docs.github.com/en/free-pro-team@latest/github/writing-on-github/basic-writing-and-formatting-syntax) para lo que escribas.\n\n**Importante**: El equipo docente puede tardar mas de 24 horas en contestar una _issue_, aunque normalmente el tiempo de respuesta debería ser menor. Por lo mismo, se recomienda **no publicar _issues_ el mismo día de alguna entrega**.\n"
},
{
"alpha_fraction": 0.7513061761856079,
"alphanum_fraction": 0.769070029258728,
"avg_line_length": 72.61538696289062,
"blob_id": "79ce04269b54bb469d5e46f5bebe37548e0cc261",
"content_id": "72a48abed2a5d89d10d459069fcf6366ff249629",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 965,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 13,
"path": "/Videos Proyecto/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Link a los videos\n\n- [Estimación de precios de inmuebles en Santiago](https://www.youtube.com/watch?v=sGgnwkhXv6k&feature=youtu.be)\n- [Pokemon vs Magic](https://youtu.be/venm1BC-VkE)\n- [Predicción éxito de videojuegos](https://www.youtube.com/watch?v=HZyvtrX4CBQ)\n- [Musicalize](https://www.youtube.com/watch?v=Z_5ay0BM58Q&ab_channel=SebastianGutierrez)\n- [Sistema de recomendación de animé](https://youtu.be/Bkla5-PGqMg)\n- [Predictor de popularidad de canciones](https://www.youtube.com/watch?v=4R9MYVh88SQ&feature=youtu.be)\n- [Análisis de rendimiento escolar](https://www.youtube.com/watch?v=iJM3HjD4KRQ&feature=youtu.be)\n- [Predictor rendimiento de alumnos](https://youtu.be/nSvPab_jRNc)\n- [Predicción tipo de cáncer en base a biopsias](https://www.youtube.com/watch?v=1iqn0W-isYg&feature=youtu.be)\n- [Fairness en Machine Learning](https://www.youtube.com/watch?v=RpZTJhfufug&feature=youtu.be)\n- [Predictor de peleas UFC](https://youtu.be/EZQtR7dbsJo)\n"
},
{
"alpha_fraction": 0.7578475475311279,
"alphanum_fraction": 0.7802690863609314,
"avg_line_length": 54.75,
"blob_id": "1cc1bc946c44284b91fbb6a1e238048bc8425489",
"content_id": "52ce775ee67d129bff315061c6eebedcd00d34a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 229,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 4,
"path": "/Jupyter y Apuntes/C10 - Árboles de Decisión/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Algunos recursos extra para estudiar Árboles de Decisión\n\n- [Video sobre árboles de decisión](https://www.youtube.com/watch?v=7VeUPuFGJHk)\n- [Video sobre árboles de regresión](https://www.youtube.com/watch?v=g9c66TUylZ4)\n"
},
{
"alpha_fraction": 0.7492537498474121,
"alphanum_fraction": 0.7671641707420349,
"avg_line_length": 54.83333206176758,
"blob_id": "6aeba16f2ac07d5857906110a5f40246fe70282e",
"content_id": "483f6592d5bff904f6325abcd2d305119041841d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 6,
"path": "/Jupyter y Apuntes/C12 - Reducción de Dimensionalidad y Clustering/README.md",
"repo_name": "ING559/Syllabus-2020-2",
"src_encoding": "UTF-8",
"text": "# Recursos extra sobre Reducción de Dimensionalidad y Clustering\n\n- [PCA](https://www.youtube.com/watch?v=FgakZw6K1QQ)\n- [T-SNE](https://www.youtube.com/watch?v=NEaUSP4YerM)\n- [K-Means](https://www.youtube.com/watch?v=4b5d3muPQmA)\n- [Clustering Jerárquico](https://stackabuse.com/hierarchical-clustering-with-python-and-scikit-learn/)\n"
}
] | 8 |
tanviruni/dummy-project- | https://github.com/tanviruni/dummy-project- | 46cd8832e4bb1d613272bd727cc4473aba2ed2f1 | 3468e2fa5ec69da8a132736a08ae37e72f8bdb85 | ac12e0156e2ebb2497c7ca90b369ce98c8caaba1 | refs/heads/master | 2020-04-07T00:05:35.824688 | 2018-11-16T16:09:53 | 2018-11-16T16:09:53 | 157,891,020 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5008665323257446,
"alphanum_fraction": 0.5615251064300537,
"avg_line_length": 19.44444465637207,
"blob_id": "58ec1736d4d7c1dd9602053c7546a976582e7989",
"content_id": "0950110c273ebfdc66fd9fe9aff06d16314a8c88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 577,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 27,
"path": "/test_basic.py",
"repo_name": "tanviruni/dummy-project-",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 9 11:18:53 2018\r\n\r\n@author: z003zxsz\r\n\"\"\"\r\n\r\nimport unittest\r\nimport basic\r\n\r\nclass TestCalc(unittest.TestCase):\r\n \r\n def test_add(self):\r\n self.assertEqual(basic.add(20,5), 25)\r\n \r\n def test_subtract(self):\r\n self.assertEqual(basic.subtract(20,5), 15)\r\n \r\n def test_multiply(self):\r\n self.assertEqual(basic.multiply(20,5), 100)\r\n \r\n def test_division(self):\r\n self.assertEqual(basic.division(20,5), 4)\r\n \r\n\r\nif __name__ == '__main__':\r\n unittest.main()"
}
] | 1 |
vicendev/WebAIPTAFlipBookJS | https://github.com/vicendev/WebAIPTAFlipBookJS | a5d98c1ebac1aaeeccd20c9bd284e0aaa4d64628 | c574809363f89452a76713f6cf8b3373f96508f2 | 0e6d03c7cae98f604939375459eb38adb94e96e6 | refs/heads/master | 2020-05-25T16:57:12.159227 | 2019-05-22T03:27:17 | 2019-05-22T03:27:17 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.40734875202178955,
"alphanum_fraction": 0.41748496890068054,
"avg_line_length": 53.44827651977539,
"blob_id": "695f8104295ff13eed8affb866a44733982909ed",
"content_id": "6d427d65219c4be8757d15b927ad02a179d0cdb2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 3175,
"license_type": "no_license",
"max_line_length": 331,
"num_lines": 58,
"path": "/core/templates/core/magazine.html",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "{% extends 'core/base.html' %}\n{% load static %}\n\n{% block title %}Revista - El Caballo Azul{% endblock title %}\n\n{% block content %}\n <section class=\"page-section about-heading\">\n <div class=\"container\">\n <div class=\"about-heading-content mt-5\">\n <div class=\"row\">\n <div class=\"col-xl-9 col-lg-10 mx-auto\">\n <div class=\"bg-faded rounded p-5 text-center\">\n <h2 class=\"section-heading mb-4\">\n <span class=\"section-heading-upper\">Revista El Caballo Azul</span>\n </h2>\n <p>La Revista <b><i>El Caballo azul</i></b> es uno de los medios de expresión y difusión de los integrantes de la Asociación Internacional Psicoanálisis a Través del Arte, organización abierta y relacionada con distintas Escuelas Psicoanalíticas, desde la visión que éstas tienen de la cultura. </p>\n <p>Su difusión <b><i>on líne</i></b> es internacional y su acceso libre. En sus páginas, se publican contribuciones de profesionales de diverso origen y que adhieran al psicoanálisis como teoría de base y en lo posible dentro del paradigma de la complejidad o del Psicoanálisis de conceptos ampliados. </p><br/>\n <p><a href=\"{% url 'publish'%}\" style=\"color:green;\">Acceda a las revistas desde aquí</a></p><br/>\n <table>\n <tbody>\n <tr>\n <td>\n <label for=\"P242\">Nombre: </label>\n </td>\n <td>\n <input name=\"name\" id=\"P242\" type=\"text\" class=\"form-control mt-1\" placeholder=\"Ingrese su nombre\">\n </td>\n </tr>\t\t\n <tr>\n <td>\n <label for=\"P246\">Mail: </label>\n </td>\n <td>\n <input name=\"email\" id=\"P246\" type=\"email\" class=\"form-control mt-1\" placeholder=\"Ingrese su email\">\n </td>\n </tr>\n <tr>\n <td>\n <label for=\"P250\">Teléfono: </label>\n </td>\n <td>\n <input name=\"name\" id=\"P250\" type=\"tel\" class=\"form-control mt-1\" placeholder=\"Ingrese su número\">\n </td>\n </tr>\n <tr>\n <td align=\"center\" colspan=\"2\">\n <button type=\"submit\" class=\"btn btn-primary btn-block py-2 mt-2\">Enviar</button>\n </td>\n </tr>\n </tbody>\n </table> \n </div>\n </div>\n </div>\n </div>\n </div>\n </section>\n{% endblock %}"
},
{
"alpha_fraction": 0.6582278609275818,
"alphanum_fraction": 0.6582278609275818,
"avg_line_length": 21.714284896850586,
"blob_id": "49a8108bbd5b6e93aa74f4499d50bddd3145128d",
"content_id": "ffd890dabba32a921681d71ec538ce3945e68aa2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 7,
"path": "/publish/urls.py",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.publish, name=\"publish\"),\n path('pdf/', views.flipbook, name=\"pdf\"),\n]"
},
{
"alpha_fraction": 0.7085307836532593,
"alphanum_fraction": 0.7132701277732849,
"avg_line_length": 43.47368240356445,
"blob_id": "e0840c2c7cc62748333e0a39f9e6354c120ff26e",
"content_id": "e013cc318d891f9aa28c5acc5d1978a0f7d20b35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 847,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 19,
"path": "/publish/models.py",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom publish.validators import validate_file_extension\n\n# Create your models here.\nclass PDFPublish(models.Model):\n title = models.CharField(verbose_name=\"Título\", max_length=200)\n image = models.ImageField(verbose_name=\"Imagen\", upload_to=\"pdfImagen\", null=True, blank=True)\n filepdf = models.FileField(verbose_name=\"Archivo PDF\", upload_to=\"pdfpublish\", validators=[validate_file_extension])\n order = models.SmallIntegerField(verbose_name=\"Orden\", default=0)\n created = models.DateTimeField(auto_now_add=True, verbose_name=\"Fecha creación\")\n updated = models.DateTimeField(auto_now=True, verbose_name=\"Fecha edición\")\n\n class Meta:\n verbose_name = \"revista\"\n verbose_name_plural = \"revistas\"\n ordering = ['order','title']\n\n def __str__(self):\n return self.title"
},
{
"alpha_fraction": 0.5703063607215881,
"alphanum_fraction": 0.5852317214012146,
"avg_line_length": 38.78125,
"blob_id": "5d6a1ec01143bf77bdc93611e844e2e673bbefe4",
"content_id": "8be71eb9fdb4b45c3f1a92962cedade8e130475f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1276,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 32,
"path": "/publish/migrations/0001_initial.py",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-05-22 01:45\n\nfrom django.db import migrations, models\nimport publish.validators\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='PDFPublish',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=200, verbose_name='Título')),\n ('image', models.ImageField(blank=True, null=True, upload_to='pdfImagen', verbose_name='Imagen')),\n ('filepdf', models.FileField(upload_to='pdfpublish', validators=[publish.validators.validate_file_extension], verbose_name='Archivo PDF')),\n ('order', models.SmallIntegerField(default=0, verbose_name='Orden')),\n ('created', models.DateTimeField(auto_now_add=True, verbose_name='Fecha creación')),\n ('updated', models.DateTimeField(auto_now=True, verbose_name='Fecha edición')),\n ],\n options={\n 'verbose_name': 'revista',\n 'verbose_name_plural': 'revistas',\n 'ordering': ['order', 'title'],\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.7966101765632629,
"alphanum_fraction": 0.7966101765632629,
"avg_line_length": 28.625,
"blob_id": "b9281a97eb693d61308a8d5410036e1fb03fdd95",
"content_id": "a3e0c51979f2003833665e2aa2ebedee2aa68243",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 236,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 8,
"path": "/publish/admin.py",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom publish.models import PDFPublish\n\n# Register your models here.\nclass PDFPublishAdmin(admin.ModelAdmin):\n readonly_fields = ('created', 'updated')\n\nadmin.site.register(PDFPublish, PDFPublishAdmin)"
},
{
"alpha_fraction": 0.4509018063545227,
"alphanum_fraction": 0.4562458395957947,
"avg_line_length": 36.45000076293945,
"blob_id": "c311a5fc1539e67e43c2864a9ed2e3f4f1ec305f",
"content_id": "9b52d7be8b537c0c29a6bdc1b3856fac0871e243",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1497,
"license_type": "no_license",
"max_line_length": 228,
"num_lines": 40,
"path": "/publish/templates/publish/publish.html",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "{% extends 'core/base.html' %}\n{% load static %}\n\n{% block title %}Publicaciones{% endblock title %}\n\n{% block content %}\n <section class=\"page-section cta\">\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-xl-9 mx-auto\">\n <div class=\"cta-inner text-center rounded\">\n <h2 class=\"section-heading mb-5\">\n <span class=\"section-heading-upper\">Publicaciones</span>\n <span class=\"section-heading-lower\">Descargalos gratis</span>\n </h2>\n {{documents.title}}\n {% if documents %}\n {% for document in documents %}\n <ul class=\"list-unstyled list-hours mb-5 text-left mx-auto\">\n <li class=\"list-unstyled-item list-hours-item d-flex\">\n <p class=\"mb-0\">\n <img class=\"flipbook-img mx-auto d-flex rounded img-fluid mb-3 mb-lg-0\" src=\"{% if document.image %}{{document.image.url}} {% else %} {% static 'publish\\no-image.png' %} {% endif %}\" alt=\"{{document.title}}\">\n </p>\n </li>\n <li>\n <p>\n <a href=\"{% url 'pdf' %}\">{{document.title}}</a>\n </p>\n </li>\n </ul>\n {% endfor %}\n {% else %}\n <p>No hay documentos</p>\n {% endif %}\n </div>\n </div>\n </div>\n </div>\n </section>\n{% endblock content %}"
},
{
"alpha_fraction": 0.7454068064689636,
"alphanum_fraction": 0.7454068064689636,
"avg_line_length": 30.83333396911621,
"blob_id": "25e80316f04f7c67c0d278f578916c8923fa4841",
"content_id": "12ad90e3cc8b8a14395f6332c52cff06d24d3ef4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 381,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 12,
"path": "/publish/views.py",
"repo_name": "vicendev/WebAIPTAFlipBookJS",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom publish.models import PDFPublish\n\n# Create your views here.\n\ndef flipbook(request):\n documents = PDFPublish.objects.all()\n return render(request, 'publish/index.html', {'documents': documents})\n\ndef publish(request):\n documents = PDFPublish.objects.all()\n return render(request, 'publish/publish.html', {'documents': documents})"
}
] | 7 |
redb0/compiler-on-python | https://github.com/redb0/compiler-on-python | 31f0935feacedd63de895a3f93b5091fef6639f4 | 1b43498f03f70ec7c71cfd2beb7700a01b069653 | 4d06ed5f1e90981feee68399ed1f19bbfd054850 | refs/heads/master | 2021-04-15T04:02:42.881546 | 2018-05-24T11:41:51 | 2018-05-24T11:41:51 | 126,833,603 | 4 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5545721650123596,
"alphanum_fraction": 0.55723637342453,
"avg_line_length": 31.1875,
"blob_id": "5c3d6acbab89b858677ab6611c322c8858a97ead",
"content_id": "9f56d34d519bcf0163a76bf5529bc5e8e1357b14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 23008,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 688,
"path": "/ast.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "import llvm\nimport llvm.core\n\nimport my_token\nfrom code_generator import get_type\n\n\n# базовый класс\nclass BaseAST:\n reserved_names = {\"print\": None}\n\n def __init__(self, parent=None):\n self.parent = parent\n self.names = {}\n # self.reserved_names = {\"print\": None}\n\n def code_gen(self, module):\n pass\n\n def get_names(self, name: str):\n try:\n obj = self.names[name]\n return obj\n except KeyError:\n return self.parent.get_names(name) if self.parent is not None else None\n # if self.parent is not None:\n # obj = self.parent.get_names(name)\n # return obj\n # else:\n # try:\n # return self.reserved_names[name]\n # except KeyError:\n # return None\n\n def is_reserved_name(self, name: str) -> bool:\n return name in self.reserved_names.keys()\n # try:\n # obj = self.reserved_names[name]\n # return True\n # except KeyError:\n # return False\n\n def add_name(self, name: str, obj) -> None:\n self.names[name] = obj\n\n def set_parent(self, value):\n self.parent = value\n\n\n# Определение переменной \"var x int\"\nclass VarDecAST(BaseAST):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.name = \"\"\n self.type = None\n self.value = None\n\n self._ptr = None\n\n def set_name(self, value: str) -> None:\n self.name = value\n\n def set_type(self, value) -> None:\n self.type = value\n\n def set_value(self, value):\n self.value = value\n\n def get_ptr(self):\n return self._ptr\n\n def code_gen(self, module, builder=None):\n t = get_type(self.type)\n v = builder.alloca(t, name=self.name)\n self._ptr = v\n # gv = module.add_global_variable(t, self.name)\n return v\n\n def get_type(self):\n return self.type\n\n\nclass VarDefAST(BaseAST):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.var_dec = None\n self.value = None\n\n def set_declaration(self, obj: VarDecAST) -> None:\n self.var_dec = obj\n\n def set_value(self, value) -> None:\n self.value = value\n\n def get_type(self):\n return self.var_dec.type\n\n def code_gen(self, module, builder=None):\n if type(self.var_dec._ptr) == llvm.core.Argument:\n return self.var_dec._ptr\n else:\n tmp = builder.load(self.var_dec._ptr, name=self.var_dec.name)\n return tmp # self.var_dec._ptr\n\n\nclass IntNumericAST(BaseAST):\n \"\"\"Целое число\"\"\"\n def __init__(self, value: int, parent=None):\n super().__init__(parent)\n self.value = value\n\n def code_gen(self, module, builder=None):\n # тип - 32-bit целое число\n int_type = llvm.core.Type.int()\n const = llvm.core.Constant.int(int_type, self.value)\n return const\n\n def get_type(self):\n return 30\n\n\nclass DoubleNumericAST(BaseAST):\n \"\"\"Число с плавающей запятой\"\"\"\n def __init__(self, value: float, parent=None):\n super().__init__(parent)\n self.value = value\n\n def code_gen(self, module, builder=None):\n # тип - 64-bit число с плавающей запятой\n double_type = llvm.core.Type.double()\n const = llvm.core.Constant.real(double_type, self.value)\n return const\n\n def get_type(self):\n return my_token.DOUBLE\n\n\nclass BoolConstAST(BaseAST):\n def __init__(self, value: int, parent=None):\n super().__init__(parent=parent)\n if type(value) in [int, float]:\n if value == 0:\n self.value = 0\n else:\n self.value = 1\n elif type(value) is str:\n if value == \"true\":\n self.value = 1\n elif value == \"false\":\n self.value = 0\n\n def code_gen(self, module, builder=None):\n bool_type = llvm.core.Type.int(1)\n const = llvm.core.Constant.int(bool_type, self.value)\n return const\n\n def get_type(self):\n return my_token.BOOL\n\n\n# составное выражение, им является базовый узел, и тело функций\nclass CompoundExpression(BaseAST):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.order_operations = []\n\n def set_child(self, obj: BaseAST) -> None:\n obj.set_parent(self)\n self.order_operations.append(obj)\n\n def get_var_def(self, name: str):\n for i in range(len(self.order_operations) - 1, 0, -1):\n # if self.order_operations[i].__class__ == VarDefAST:\n # if self.order_operations[i].var_dec.name == name:\n # return self.order_operations[i]\n # if self.order_operations[i].__class__ == BinaryAST:\n # if (self.order_operations[i].operator == 12) and (self.order_operations[i].lhs.__class__ == VarDefAST):\n # if self.order_operations[i].lhs.var_dec.name == name:\n # return self.order_operations[i]\n if self.order_operations[i].__class__ == BinaryAST:\n if (self.order_operations[i].operator == 12) and (self.order_operations[i].lhs.__class__ == VarDefAST):\n if self.order_operations[i].lhs.var_dec.name == name:\n return self.order_operations[i].lhs\n return None\n\n def code_gen(self, module, bb=None):\n # bb = module.append_basic_block(name_bb)\n # builder = llvm.core.Builder.new(bb)\n for op in self.order_operations:\n op.code_gen(module, bb)\n return module\n\n\n# функция\nclass FunctionDefAST(CompoundExpression):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.name = \"\"\n self.args = []\n self.return_values = []\n self.type = -1\n self.body = None\n\n self.func = None\n\n def set_name(self, value):\n self.name = value\n\n def set_body(self, obj):\n self.body = obj\n\n def set_type(self, t):\n self.type = t\n\n def add_arg(self, arg):\n self.args.append(arg)\n self.add_name(arg.name, arg)\n\n def add_return_value(self, obj):\n self.return_values.append(obj)\n\n def print_code_gen(self, module, name_bb='entry'):\n \"\"\"Print Function\"\"\"\n # fn_type = llvm.core.Type.function(llvm.core.Type.void(), [llvm.core.Type.pointer(llvm.core.Type.int(8))], True)\n fn_type = llvm.core.Type.function(llvm.core.Type.int(), [llvm.core.Type.pointer(llvm.core.Type.int(8))], True)\n my_print = module.add_function(fn_type, \"print\")\n\n bb = my_print.append_basic_block(name_bb) # ???\n builder = llvm.core.Builder.new(bb)\n builder.printf(\"%s\\n\", builder.args[0])\n builder.ret()\n\n def code_gen(self, module, name_bb='entry'):\n # получаем возвращаемый функцией тип\n ret_type = get_type(self.type)\n\n # составляем список типов аргуметнов\n args_type = []\n for arg in self.args:\n t = get_type(arg.type)\n args_type.append(t)\n\n # составляем сигнатуру функции\n ty_func = llvm.core.Type.function(ret_type, args_type)\n\n # добавляем функцию к модулю\n func = module.add_function(ty_func, self.name)\n\n self.func = func\n\n # называем аргументы функции\n for i in range(len(self.args)):\n func.args[i].name = self.args[i].name\n self.args[i]._ptr = func.args[i]\n\n # Задаем базовый блок функции (\"basic block\") -\n # набор инструций, заканчивающийся return\n # По соглашению первый блок называется «запись».\n bb = func.append_basic_block(\"entry\")\n\n # Добавление инструкций в блок\n builder = llvm.core.Builder.new(bb)\n\n # Созднание инструкций в базовом блоке.\n for op in self.order_operations:\n op.code_gen(func, builder)\n\n # print(module)\n\n def print_func_cg(self, module, name_bb=''):\n # кодогенераци для функции вывода print\n pass\n\n\nclass ReturnAst(BaseAST):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.values = []\n\n def add_values(self, value):\n self.values.append(value)\n\n def code_gen(self, func, builder=None):\n for obj in self.values:\n if isinstance(obj, VarDefAST):\n tmp = obj.var_dec.get_ptr()\n else:\n tmp = obj.code_gen(func, builder)\n builder.ret(tmp)\n\n\n# class Body(BaseAST):\n# def __init__(self, parent=None):\n# super().__init__(parent)\n# self.expr = []\n#\n# def set_parent(self, value):\n# self.parent = value\n#\n# def add_expr(self, expr):\n# self.expr.append(expr)\n#\n# def code_gen(self, module):\n# pass\n\n\n# вызов функции\nclass FunctionCallAST(BaseAST):\n def __init__(self, func, args, parent=None):\n super().__init__(parent)\n self.func_callee = func\n self.args = args\n\n self.ret = None\n\n def set_parent(self, value):\n self.parent = value\n\n def set_ret_name(self, name):\n self.ret = name\n\n def code_gen(self, module, builder=None):\n # ret_type = get_type(self.func_callee.type)\n\n args = []\n for a in self.args:\n args.append(a.code_gen(module, builder))\n\n tmp = builder.call(self.func_callee.func, args, name=\"tmp\")\n print(module)\n return tmp\n\n def get_type(self):\n t = self.func_callee.type\n if t in [\"int\", my_token.INT]:\n return my_token.INT\n elif t in [\"double\", my_token.DOUBLE]:\n return my_token.DOUBLE\n else:\n return None\n\n\nclass BinaryAST(BaseAST):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.operator = -1\n self.lhs = None\n self.rhs = None\n\n def set_lhs(self, value: BaseAST) -> None:\n self.lhs = value\n\n def set_rhs(self, value: BaseAST) -> None:\n self.rhs = value\n\n def set_op(self, value: int) -> None:\n self.operator = value\n\n def is_valid(self) -> bool:\n if (self.operator >= 0) and (self.lhs is not None) and (self.rhs is not None):\n return True\n else:\n return False\n\n def get_type(self):\n t1 = self.lhs.get_type()\n t2 = self.rhs.get_type()\n if t1 == t2 and my_token.is_arithmetic_operator(self.operator):\n return t1\n elif t1 == t2 and my_token.is_logic_operator(self.operator):\n return my_token.BOOL\n # if t1 == t2:\n # return t1\n else:\n return None\n\n def code_gen(self, module, builder=None):\n if self.operator != my_token.ASSIGN:\n code_lhs = self.lhs.code_gen(module, builder)\n code_rhs = self.rhs.code_gen(module, builder)\n if code_lhs is None or code_rhs is None:\n return None\n t = self.get_type()\n if t is None:\n return None\n # if code_lhs is None or code_rhs is None:\n # return None\n if self.operator == my_token.PLUS:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT: # == self.rhs.get_type()\n tmp = builder.add(code_lhs, code_rhs, 'addtmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE: # == self.rhs.get_type()\n tmp = builder.fadd(code_lhs, code_rhs, 'addtmp')\n return tmp\n elif self.operator == my_token.MINUS:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT: # == self.rhs.get_type()\n tmp = builder.sub(code_lhs, code_rhs, 'subtmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE: # == self.rhs.get_type()\n tmp = builder.fsub(code_lhs, code_rhs, 'subtmp')\n return tmp\n elif self.operator == my_token.OPERATOR_DIV:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT: # == self.rhs.get_type()\n tmp = builder.udiv(code_lhs, code_rhs, 'divtmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE: # == self.rhs.get_type()\n tmp = builder.fdiv(code_lhs, code_rhs, 'divtmp')\n return tmp\n elif self.operator == my_token.OPERATOR_MUL:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT: # == self.rhs.get_type()\n tmp = builder.mul(code_lhs, code_rhs, 'multmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE: # == self.rhs.get_type()\n tmp = builder.fmul(code_lhs, code_rhs, 'multmp')\n return tmp\n # не нашел есть ли в llvmpy операция возведения в степень\n elif self.operator == my_token.OPERATOR_POWER:\n # TODO: доделать\n pass\n\n elif self.operator == my_token.LESS:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL: # == self.rhs.get_type()\n tmp = builder.icmp(llvm.core.IPRED_SLT, code_lhs, code_rhs, 'lttmp')\n return tmp\n elif self.lhs.get_type() == my_token.DOUBLE: # == self.rhs.get_type()\n # elif t == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_OLT, code_lhs, code_rhs, 'lttmp')\n return tmp\n elif self.operator == my_token.LESS_OR_EQUAL:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL:\n tmp = builder.icmp(llvm.core.IPRED_SLE, code_lhs, code_rhs, 'letmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_OLE, code_lhs, code_rhs, 'letmp')\n return tmp\n elif self.operator == my_token.LARGER:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL: # == self.rhs.get_type()\n # SLE или ULE, чем отличаются???\n tmp = builder.icmp(llvm.core.IPRED_SGT, code_lhs, code_rhs, 'gttmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_OGT, code_lhs, code_rhs, 'gttmp')\n return tmp\n elif self.operator == my_token.LARGER_OR_EQUAL:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL:\n # SLE или ULE, чем отличаются???\n tmp = builder.icmp(llvm.core.IPRED_SGE, code_lhs, code_rhs, 'getmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_OGE, code_lhs, code_rhs, 'getmp')\n return tmp\n elif self.operator == my_token.EQUAL:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL:\n tmp = builder.icmp(llvm.core.IPRED_EQ, code_lhs, code_rhs, 'eqtmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_OEQ, code_lhs, code_rhs, 'eqtmp')\n return tmp\n elif self.operator == my_token.NOT_EQUAL:\n # if t == my_token.INT:\n if self.lhs.get_type() == my_token.INT or self.lhs.get_type() == my_token.BOOL:\n tmp = builder.icmp(llvm.core.IPRED_NE, code_lhs, code_rhs, 'netmp')\n return tmp\n # elif t == my_token.DOUBLE:\n elif self.lhs.get_type() == my_token.DOUBLE:\n tmp = builder.fcmp(llvm.core.RPRED_ONE, code_lhs, code_rhs, 'netmp')\n return tmp\n\n elif self.operator == my_token.ASSIGN:\n code_rhs = self.rhs.code_gen(module, builder)\n builder.store(code_rhs, self.lhs.var_dec._ptr)\n return self.lhs.var_dec._ptr\n else:\n return None\n\n\n# условие if ... {...} else {...}\nclass ExprIfAST(CompoundExpression):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.expression = None\n self.body = None\n self.else_body = None\n\n def set_expression(self, expr):\n self.expression = expr\n\n def set_body(self, obj):\n self.body = obj\n\n def set_else(self, expr):\n self.else_body = expr\n\n def code_gen(self, module, builder=None):\n # булево выражение, базовый блок для if, базовый блок для else.\n expr = self.expression.code_gen(module, builder)\n\n func = builder.basic_block.function\n\n # Создание базовых блоков the и else.\n # Последовательная вставка блоков в конец текущего блока.\n then_block = func.append_basic_block('then')\n else_block = func.append_basic_block('else')\n merge_block = func.append_basic_block('ifcond')\n\n builder.cbranch(expr, then_block, else_block)\n\n # Добавить then блок в конец текущего.\n builder.position_at_end(then_block)\n then_value = self.body.code_gen(module, builder)\n builder.branch(merge_block)\n\n # Codegen of 'Then' can change the current block; update then_block\n # for the PHI node.\n then_block = builder.basic_block\n\n # Добавить else блок в конец текущего.\n builder.position_at_end(else_block)\n if self.else_body:\n else_value = self.else_body.code_gen(module, builder)\n builder.branch(merge_block)\n\n # Codegen of 'Else' can change the current block, update else_block\n # for the PHI node.\n else_block = builder.basic_block\n\n # Добалвение блока слияния\n builder.position_at_end(merge_block)\n phi = builder.phi(llvm.core.Type.double(), 'iftmp')\n\n phi.add_incoming(then_value, then_block)\n if self.else_body:\n phi.add_incoming(else_value, else_block)\n\n return phi\n\n\n# цикл while ... {...}\nclass ExprWhileAST(CompoundExpression):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.expression = None\n self.body = None\n\n def set_expression(self, expr):\n self.expression = expr\n\n def set_body(self, obj):\n self.body = obj\n\n def code_gen(self, module, builder=None):\n # expr = self.expression.code_gen(module, builder)\n\n func = builder.basic_block.function\n\n expr_block = func.append_basic_block('expr')\n body_loop = func.append_basic_block('loop')\n after_block = func.append_basic_block('after')\n\n builder.branch(expr_block)\n\n builder.position_at_end(expr_block)\n expr = self.expression.code_gen(module, builder)\n print(expr)\n # end_condition_bool = builder.fcmp(\n # llvm.core.RPRED_ONE, expr, llvm.core.Constant.real(llvm.core.Type.double(), 0),\n # 'loopcond')\n # print(end_condition_bool)\n builder.cbranch(expr, body_loop, after_block)\n\n expr_block = builder.basic_block\n\n builder.position_at_end(body_loop)\n body_code = self.body.code_gen(module, builder)\n builder.branch(expr_block)\n\n body_loop = builder.basic_block\n\n builder.position_at_end(after_block)\n # phi = builder.phi(llvm.core.Type.double(), 'looptmp')\n\n # phi.add_incoming(then_value, then_block)\n # if self.else_body:\n # phi.add_incoming(else_value, else_block)\n\n after_block = builder.basic_block\n\n return after_block\n\n\n# цикл do {...} while ...\nclass ExprDoWhileAST(CompoundExpression):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self.expression = None\n self.body = None\n\n def set_expression(self, expr):\n self.expression = expr\n\n def set_body(self, obj):\n self.body = obj\n\n def code_gen(self, module, builder=None):\n func = builder.basic_block.function\n\n body_loop = func.append_basic_block('loop')\n expr_block = func.append_basic_block('expr_block')\n before_loop = func.append_basic_block('before')\n\n builder.branch(body_loop)\n\n builder.position_at_end(body_loop)\n body_code = self.body.code_gen(module, builder)\n builder.branch(expr_block)\n\n body_loop = builder.basic_block\n\n builder.position_at_end(expr_block)\n expr = self.expression.code_gen(module, builder)\n builder.cbranch(expr, body_loop, before_loop)\n\n expr_block = builder.basic_block\n\n builder.position_at_end(before_loop)\n\n before_loop = builder.basic_block\n\n return before_loop\n\n\ndef is_valid_type(v1, v2):\n t1 = None\n t2 = None\n if v1.__class__ == VarDecAST:\n t1 = v1.type\n elif v1.__class__ == IntNumericAST:\n t1 = \"int\"\n elif v1.__class__ == DoubleNumericAST:\n t1 = \"double\"\n if v2.__class__ == VarDecAST:\n t2 = v2.type\n elif v2.__class__ == IntNumericAST:\n t2 = \"int\"\n elif v2.__class__ == DoubleNumericAST:\n t2 = \"double\"\n if (t1 == t2) and all([t1, t2]):\n return t1\n else:\n return None\n\n\ndef is_type(token):\n \"\"\"\n Функция проверки на допустимый тип.\n :param token: токен, представлен в виде целого числа.\n :return: True - если допустимый тип, False - в противном случае.\n \"\"\"\n t = [my_token.INT, my_token.DOUBLE, my_token.BOOL]\n if token in t:\n return True\n else:\n return False\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.6084656119346619,
"alphanum_fraction": 0.6111111044883728,
"avg_line_length": 22.625,
"blob_id": "92ef308834070776234223d27af4014f414fc3d6",
"content_id": "7f0c80e550620505b286b020b048d0bc7da74551",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 378,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 16,
"path": "/code_generator.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "from typing import Union\n\nimport llvm.core\n\nfrom my_token import INT, DOUBLE, BOOL\n\n\ndef get_type(t: Union[str, int]):\n llvm_type = None\n if t in [\"int\", INT]:\n llvm_type = llvm.core.Type.int()\n elif t in [\"double\", DOUBLE]:\n llvm_type = llvm.core.Type.double()\n elif t in ['bool', BOOL]:\n llvm_type = llvm.core.Type.int(1)\n return llvm_type\n"
},
{
"alpha_fraction": 0.6186107397079468,
"alphanum_fraction": 0.6225426197052002,
"avg_line_length": 20.11111068725586,
"blob_id": "ccebb81eb524468414198740bf26c1dbff9ff2d7",
"content_id": "999baff7ae836fa913d06e8fb7f783f3182e68ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 763,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 36,
"path": "/main.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "# /usr/local/bin/charm\nimport sys\n\nimport llvm\nimport llvm.core\nimport os\n\nimport parser\nfrom tokenizer import get_token\n\n\ndef main():\n # examples/example1.txt\n # examples/functions.txt\n # examples/cycle.txt\n # examples/expr.txt\n script_path = os.path.dirname(os.path.abspath(__file__))\n file_name = sys.argv[1]\n abs_path = os.path.join(script_path, file_name)\n\n with open(abs_path, 'r', encoding='utf-8') as f:\n code = f.read()\n\n tokens_str, tokens_type = get_token(code)\n root, i, error = parser.base_parse(tokens_str, tokens_type)\n if error != \"\":\n print(error)\n return\n\n module = llvm.core.Module.new('my_module')\n root.code_gen(module)\n print(module)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n"
},
{
"alpha_fraction": 0.6413043737411499,
"alphanum_fraction": 0.6875,
"avg_line_length": 12.592592239379883,
"blob_id": "b09049c9d0d59005d4c96227a018bd9b9e0353ab",
"content_id": "12fb6b9c4cea6d44e950e38075b528097c857995",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 27,
"path": "/priorities.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "# арифметические операции\n# OPERATOR_UP = 1\nfrom my_token import AND\n\nOPERATOR_UM = 1\nOPERATOR_POWER = 2\nOPERATOR_MUL = 3\nOPERATOR_DIV = 3\nOPERATOR_ADD = 4\nOPERATOR_SUB = 4\n\n# операции сравнения\nLARGER = 5\nLARGER_OR_EQUAL = 5\nLESS = 5\nLESS_OR_EQUAL = 5\n\nEQUAL = 6\nNOT_EQUAL = 6\n\n# оператор присваивания\nASSIGN = 7\n\n# логические операторы\n# AND = 8\n# OR = 8\n# NOT = 8\n\n"
},
{
"alpha_fraction": 0.43666285276412964,
"alphanum_fraction": 0.44508227705955505,
"avg_line_length": 37.39706039428711,
"blob_id": "0e22f1eaef5ac25a1ba8d596254eacf65c156376",
"content_id": "7518e72b96545e7a0c049c1dcdca31cb014b539f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2695,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 68,
"path": "/rpn.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "import my_token\n\n\ndef get_rpn(i: int, tokens_type):\n res = []\n stack_idx = []\n error = \"\"\n while tokens_type[i] != my_token.SEMI:\n if tokens_type[i] == my_token.INT_NUMBER or tokens_type[i] == my_token.DOUBLE_NUMBER or tokens_type[i] in [my_token.FALSE, my_token.TRUE]:\n res.append(i)\n i += 1\n continue\n elif tokens_type[i] == my_token.IDENTIFIER:\n res.append(i)\n if tokens_type[i + 1] == my_token.LPAR:\n i += 1\n while tokens_type[i] != my_token.RPAR:\n i += 1\n # if tokens_type[i] == my_token.LPAR:\n # i += 1\n i += 1\n continue\n elif my_token.is_operator(tokens_type[i]):\n if tokens_type[i] == my_token.OPERATOR_POWER: # оператор возведения в степень правоассоциативна\n if len(stack_idx) == 0:\n stack_idx.append(i)\n else:\n while my_token.get_priority(tokens_type[i]) > my_token.get_priority(tokens_type[stack_idx[-1]]):\n res.append(stack_idx.pop())\n if len(stack_idx) == 0:\n break\n stack_idx.append(i)\n else:\n if len(stack_idx) == 0:\n stack_idx.append(i)\n else:\n while (tokens_type[stack_idx[-1]] != my_token.LPAR) and \\\n (my_token.get_priority(tokens_type[i]) >= my_token.get_priority(tokens_type[stack_idx[-1]])):\n res.append(stack_idx.pop())\n if len(stack_idx) == 0:\n break\n stack_idx.append(i)\n i += 1\n continue\n elif tokens_type[i] == my_token.LPAR:\n stack_idx.append(i)\n i += 1\n continue\n elif tokens_type[i] == my_token.RPAR:\n # if len(stack_idx) != 0:\n while tokens_type[stack_idx[-1]] != my_token.LPAR:\n res.append(stack_idx.pop())\n if len(stack_idx) == 0:\n break\n # else:\n # stack_idx.append(i)\n if tokens_type[stack_idx[-1]] == my_token.LPAR:\n stack_idx.pop()\n else:\n error = \"В выражжении неправельно расставлены скобки\"\n i += 1\n continue\n else:\n break\n if len(stack_idx) != 0:\n while len(stack_idx) != 0:\n res.append(stack_idx.pop())\n return i, res, error\n\n\n"
},
{
"alpha_fraction": 0.5000638365745544,
"alphanum_fraction": 0.5036396980285645,
"avg_line_length": 38.613826751708984,
"blob_id": "2db8936c604160e7eddf1ab2ac2ae66f73b67599",
"content_id": "847c6e70fef09d6b9bed715469a7dc687deadbc4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 24411,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 593,
"path": "/parser.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "from typing import Tuple, Union, List\n\nimport llvm\nimport llvm.core\nimport llvm_cbuilder\n\nimport ast\nimport my_token\n\nfrom rpn import get_rpn\nfrom tokenizer import get_token\n\n\ndef var_parse(i: int, tokens_str, tokens_type, parent) -> Tuple[Union[ast.VarDecAST, None], int, str]:\n \"\"\"\n Функция парсинга объявления переменной.\n Переменная объявляется следующим образом:\n var имя_переменной тип_переменной;\n Пример:\n var x int;\n :param i: \n :param tokens_str: \n :param tokens_type: \n :param parent: \n :return: \n \"\"\"\n v = ast.VarDecAST()\n v.set_parent(parent)\n if tokens_type[i] == my_token.DEF_VAR:\n i += 1\n if tokens_type[i] == my_token.IDENTIFIER:\n obj = parent.get_names(tokens_str[i])\n if obj is not None:\n error = \"Переменная с именем \" + tokens_str[i] + \" существует.\"\n print(error)\n return None, i, error\n else:\n parent.add_name(tokens_str[i], v)\n v.set_name(tokens_str[i])\n else:\n error = \"Ошибка объявления переменной. Не указано имя.\"\n print(error)\n return None, i, error\n i += 1\n if ast.is_type(tokens_type[i]):\n v.set_type(tokens_type[i])\n else:\n error = \"Ошибка объявления переменной. Некорректно указан тип.\"\n print(error)\n return None, i, error\n i += 1\n if tokens_type[i] == my_token.SEMI:\n # i += 1\n return v, i, \"\"\n else:\n error = \"Ошибка. Нет точки с запятой.\"\n print(error)\n return None, i, error\n\n\ndef var_def_parse(i: int, tokens_str, tokens_type, parent: ast.CompoundExpression) -> Tuple[Union[ast.VarDefAST, None], int, str]:\n error = \"\"\n var_def = None\n if (tokens_type[i] == my_token.IDENTIFIER) and (tokens_type[i + 1] == my_token.ASSIGN):\n obj = parent.get_names(tokens_str[i])\n if obj is None:\n error = \"Переменная с именем \" + tokens_str[i] + \" не объявлена.\"\n print(error)\n return None, i, error\n var_def = ast.VarDefAST(parent)\n var_def.set_declaration(obj)\n i += 2\n if (tokens_type[i] == my_token.IDENTIFIER) or my_token.is_number(tokens_type[i]):\n if my_token.is_operator(tokens_type[i + 1]):\n obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None, i, error\n var_def.set_value(obj)\n # elif tokens_type[i + 1] == my_token.SEMI:\n elif tokens_type[i + 1] == my_token.LPAR:\n j = i + 1\n while tokens_type[j] != my_token.RPAR:\n j += 1\n if tokens_type[j] == my_token.RPAR:\n j += 1\n if my_token.is_operator(tokens_type[j + 1]):\n obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None, i, error\n var_def.set_value(obj)\n else:\n if (tokens_type[i] == my_token.INT_NUMBER) and (var_def.var_dec.type == 'int'):\n var_def.set_value(int(tokens_str[i]))\n elif (tokens_type[i] == my_token.DOUBLE_NUMBER) and (var_def.var_dec.type == 'double'):\n var_def.set_value(float(tokens_str[i]))\n elif tokens_type[i] == my_token.IDENTIFIER:\n obj = parent.get_var_def(tokens_str[i])\n if obj is not None:\n error = \"Переменная с именем \" + tokens_str[i] + \" не инициализирована.\"\n print(error)\n return None, i, error\n var_def.set_value(obj)\n return var_def, i, error\n\n\ndef func_parse(i: int, tokens_str, tokens_type, parent: ast.BaseAST) \\\n -> Tuple[Union[ast.FunctionDefAST, None], int, str]:\n pass\n\n\ndef func_call_parse(i: int, tokens_str, tokens_type, parent) -> Tuple[Union[ast.FunctionCallAST, None], int, str]:\n error = \"\"\n name = \"\"\n args = []\n if tokens_type[i] == my_token.IDENTIFIER:\n name = tokens_str[i]\n i += 1\n if tokens_type[i] == my_token.LPAR:\n i += 1\n while tokens_type[i] != my_token.RPAR:\n if my_token.is_number(tokens_type[i]):\n if tokens_type[i] == my_token.INT_NUMBER:\n numb = ast.IntNumericAST(int(tokens_str[i]))\n args.append(numb)\n elif tokens_type[i] == my_token.DOUBLE_NUMBER:\n numb = ast.DoubleNumericAST(float(tokens_str[i]))\n args.append(numb)\n elif tokens_type[i] == my_token.IDENTIFIER:\n obj = parent.get_names(tokens_str[i])\n if obj is None:\n error = \"Переменная с имененем \" + tokens_str[i] + \" не объявлена.\"\n print(error)\n return None, i, error\n args.append(tokens_str[i])\n i += 1\n\n if name != \"\":\n obj = parent.get_names(name)\n if obj is not None:\n f = ast.FunctionCallAST(obj, args)\n f.set_parent(parent)\n return f, i, error\n else:\n if parent.is_reserved_name(name):\n obj = parent.reserved_names[name]\n if parent.reserved_names[name] is None:\n f = ast.FunctionDefAST()\n f = ast.FunctionCallAST(obj, args)\n f.set_parent(parent)\n return f, i, error\n else:\n error = \"Не объявлена функция с именем \" + name\n print(error)\n return None, i, error\n else:\n error = \"Не корректное объявление функции\"\n print(error)\n return None, i, error\n\n\ndef bin_op_parse(i: int, tokens_str, tokens_type, parent: ast.BaseAST) -> Tuple[Union[ast.BinaryAST, None], int, str]:\n error = \"\"\n root = None\n\n j, rpn, error = get_rpn(i, tokens_type)\n if error != \"\":\n print(error)\n return None, i, error\n\n stack = []\n for k in range(len(rpn)):\n if tokens_type[rpn[k]] == my_token.INT_NUMBER:\n hs = ast.IntNumericAST(int(tokens_str[rpn[k]]))\n stack.append(hs)\n continue\n elif tokens_type[rpn[k]] == my_token.DOUBLE_NUMBER:\n hs = ast.DoubleNumericAST(float(tokens_str[rpn[k]]))\n stack.append(hs)\n continue\n elif tokens_type[rpn[k]] in [my_token.TRUE, my_token.FALSE]:\n hs = ast.BoolConstAST(tokens_str[rpn[k]])\n stack.append(hs)\n continue\n elif tokens_type[rpn[k]] == my_token.IDENTIFIER:\n obj = parent.get_names(tokens_str[rpn[k]])\n if obj is None:\n error = \"Переменная с именем \" + tokens_str[rpn[k]] + \" не объявлена.\"\n print(error)\n return None, rpn[k], error\n else:\n if tokens_type[rpn[k] + 1] == my_token.LPAR:\n func_call_obj, i, error = func_call_parse(rpn[k], tokens_str, tokens_type, parent)\n if func_call_obj is None:\n # error = \"Функция с именем \" + tokens_str[i] + \" вызвана некорректно.\"\n print(error)\n return None, i, error\n else:\n stack.append(func_call_obj)\n else:\n var_def_obj = ast.VarDefAST(parent)\n var_def_obj.set_declaration(obj)\n stack.append(var_def_obj)\n elif my_token.is_operator(tokens_type[rpn[k]]):\n bin_op = ast.BinaryAST()\n bin_op.set_op(tokens_type[rpn[k]])\n rhs = stack.pop()\n lhs = stack.pop()\n rhs.set_parent(bin_op)\n lhs.set_parent(bin_op)\n bin_op.set_rhs(rhs)\n bin_op.set_lhs(lhs)\n stack.append(bin_op)\n if len(stack) == 1:\n root = stack.pop()\n root.set_parent(parent)\n return root, j, error\n\n\ndef base_parse(tokens_str: List[str], tokens_type):\n base = ast.CompoundExpression(None) # базовый узел\n i = 0\n error = \"\"\n while i < len(tokens_type):\n base, i, error = compound_expression_parse(i, tokens_str, tokens_type, base)\n if error != \"\":\n print(error)\n return None, i, error\n i += 1\n return base, i, error\n\n\ndef func_def_parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n dunc_obj = ast.FunctionDefAST(parent)\n error = \"\"\n while tokens_type[i] != my_token.RBRACE:\n if tokens_type[i] == my_token.DEF_FUNC:\n i += 1\n continue\n elif tokens_type[i] == my_token.IDENTIFIER:\n obj = parent.get_names(tokens_str[i])\n if obj is not None:\n error = \"Переменная с именем \" + tokens_str[i] + \" уже объявлена.\"\n print(error)\n return None, i, error\n parent.add_name(tokens_str[i], dunc_obj)\n dunc_obj.set_name(tokens_str[i])\n i += 1\n elif tokens_type[i] == my_token.LPAR:\n i += 1\n while tokens_type[i] != my_token.RPAR:\n if tokens_type[i] == my_token.IDENTIFIER:\n a = parent.get_names(tokens_str[i])\n if a is not None:\n error = \"Переменная с именем \" + tokens_str[i] + \" уже объявлена во внешней области видимости.\"\n print(error)\n return None, i, error\n a = ast.VarDecAST(dunc_obj)\n a.set_name(tokens_str[i])\n dunc_obj.add_arg(a)\n i += 1\n if ast.is_type(tokens_type[i]):\n a.set_type(tokens_type[i])\n else:\n error = \"Не указан тип у переменной с именем \" + tokens_str[i] + \".\"\n print(error)\n return None, i, error\n i += 1\n i += 1\n continue\n elif tokens_type[i] == my_token.ARROW:\n i += 1\n if ast.is_type(tokens_type[i]):\n dunc_obj.set_type(tokens_type[i])\n i += 1\n continue\n else:\n error = \"Не указан возвращаемый тип у функции с именем \" + dunc_obj.name + \".\"\n print(error)\n return None, i, error\n elif tokens_type[i] == my_token.LBRACE:\n i += 1\n # compound_expression = ast.CompoundExpression(dunc_obj)\n while tokens_type[i] != my_token.RBRACE:\n compound_expression, i, error = compound_expression_parse(i, tokens_str, tokens_type, dunc_obj)\n # if tokens_type[i] == my_token.RBRACE:\n # break\n i += 1\n if error != \"\":\n print(error)\n return None, i, error\n # elif tokens_type[i] == my_token.RETURN:\n # i += 1\n # obj, i, error = expr_parse(i, tokens_str, tokens_type, parent)\n # if obj is None:\n # print(error)\n # return None\n # if parent.__class__ == ast.FunctionDefAST:\n # parent.add_return_value(obj)\n # else:\n # error = \"Недопустимая конструкция: return в \" + parent.__class__.__name__\n # print(error)\n # return None\n return dunc_obj, i, error\n\n\ndef compound_expression_parse(i: int, tokens_str: List[str], tokens_type, compound_expression):\n obj, i, error = parse(i, tokens_str, tokens_type, parent=compound_expression)\n if error != \"\":\n print(error)\n return None, i, error\n compound_expression.set_child(obj)\n return compound_expression, i, error\n\n\ndef expr_parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n if (tokens_type[i] == my_token.IDENTIFIER) or my_token.is_number(tokens_type[i]) or my_token.is_bool(tokens_type[i]):\n if my_token.is_operator(tokens_type[i + 1]):\n obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None, i, error\n return obj, i, \"\"\n if tokens_type[i] == my_token.IDENTIFIER:\n # if my_token.is_operator(tokens_type[i + 1]):\n # obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n # if obj is not None:\n # print(error)\n # return None, i, error\n # return obj, i, \"\"\n if tokens_type[i + 1] == my_token.RPAR:\n j = i + 1\n while tokens_type[j] != my_token.LPAR:\n j += 1\n if tokens_type[j] == my_token.LPAR:\n j += 1\n if my_token.is_operator(tokens_type[j]):\n obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None, i, error\n return obj, i, \"\"\n else:\n obj, i, error = func_call_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None, i, error\n return obj, i, \"\"\n else:\n var_def_obj = parent.get_var_def(tokens_str[i])\n if var_def_obj is None:\n error = \"Переменная с именем \" + tokens_str[i] + \" не инициализирована.\"\n print(error)\n return None, i, error\n # var_def_obj = ast.VarDefAST(parent)\n # var_def_obj.set_declaration(obj)\n return var_def_obj, i, \"\"\n elif tokens_type[i] == my_token.INT_NUMBER:\n obj = ast.IntNumericAST(int(tokens_str[i]))\n return obj, i, \"\"\n elif tokens_type[i] == my_token.DOUBLE_NUMBER:\n obj = ast.DoubleNumericAST(float(tokens_str[i]))\n return obj, i, \"\"\n elif tokens_type[i] == my_token.TRUE:\n obj = ast.BoolConstAST(1)\n return obj, i, \"\"\n elif tokens_type[i] == my_token.FALSE:\n obj = ast.BoolConstAST(0)\n return obj, i, \"\"\n\n\ndef parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n obj = None\n error = \"\"\n if tokens_type[i] == my_token.DEF_VAR:\n obj, i, error = var_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None\n elif tokens_type[i] == my_token.SEMI:\n i += 1\n elif tokens_type[i] == my_token.DEF_FUNC:\n obj, i, error = func_def_parse(i, tokens_str, tokens_type, parent)\n if error != \"\":\n print(error)\n return None\n elif tokens_type[i] == my_token.IDENTIFIER:\n if tokens_type[i + 1] == my_token.RPAR:\n obj, i, error = func_call_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None\n elif my_token.is_operator(tokens_type[i + 1]):\n obj, i, error = bin_op_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None\n elif tokens_type[i] == my_token.IF:\n obj, i, error = expr_if_parse(i, tokens_str, tokens_type, parent)\n elif tokens_type[i] == my_token.DO:\n # вызов разбора do while\n obj, i, error = expr_do_while_parse(i, tokens_str, tokens_type, parent)\n elif tokens_type[i] == my_token.WHILE:\n # вызок разбора while\n obj, i, error = expr_while_parse(i, tokens_str, tokens_type, parent)\n elif tokens_type[i] == my_token.RETURN:\n i += 1\n obj, i, error = expr_parse(i, tokens_str, tokens_type, parent)\n if obj is None:\n print(error)\n return None\n if parent.__class__ == ast.FunctionDefAST:\n if obj.get_type() == parent.type:\n parent.add_return_value(obj)\n ret_obj = ast.ReturnAst(parent)\n ret_obj.add_values(obj)\n if tokens_str[i] != ';':\n i += 1\n return ret_obj, i, error\n else:\n error = \"Ожидается возвращаемый тип \" + str(parent.type) + \" актуальный тип - \" + str(obj.get_type())\n print(error)\n return None\n else:\n error = \"Недопустимая конструкция: return в \" + parent.__class__.__name__\n print(error)\n return None\n elif tokens_type[i] == my_token.PRINT:\n obj, i, error = func_call_parse(i, tokens_str, tokens_type, parent)\n return obj, i, error\n\n\ndef expr_if_parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n error = \"\"\n if tokens_type[i] == my_token.IF:\n if_ast = ast.ExprIfAST(parent=parent)\n i += 1\n if (tokens_type[i] == my_token.IDENTIFIER) or \\\n (tokens_type[i] == my_token.INT_NUMBER) or (tokens_type[i] == my_token.DOUBLE_NUMBER) \\\n or (tokens_type[i] == my_token.BOOL):\n obj, i, error = expr_parse(i, tokens_str, tokens_type, parent)\n if_ast.set_expression(obj)\n else:\n error = \"Ожидается выражение\"\n print(error)\n return None, i, error\n if tokens_type[i] == my_token.LBRACE:\n i += 1\n # разбор тела\n if_body = ast.CompoundExpression(parent=if_ast)\n while tokens_type[i] != my_token.RBRACE:\n if_body, i, error = compound_expression_parse(i, tokens_str, tokens_type, if_body)\n i += 1\n if error != \"\":\n print(error)\n return None, i, error\n if_ast.set_body(if_body)\n if tokens_type[i] == my_token.RBRACE:\n i += 1\n if tokens_type[i] == my_token.ELSE:\n i += 1\n if tokens_type[i] == my_token.LBRACE:\n i += 1\n else_body = ast.CompoundExpression(parent=if_ast)\n while tokens_type[i] != my_token.RBRACE:\n else_body, i, error = compound_expression_parse(i, tokens_str, tokens_type, else_body)\n i += 1\n if error != \"\":\n print(error)\n return None, i, error\n if_ast.set_else(else_body)\n else:\n error = \"Ожидается открывающая фигурная скобка\"\n print(error)\n return None, i, error\n else:\n i -= 1\n return if_ast, i, error\n\n\ndef expr_while_parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n while_expr = None\n error = \"\"\n while tokens_type[i] != my_token.RBRACE:\n if tokens_type[i] == my_token.WHILE:\n while_expr = ast.ExprWhileAST(parent)\n i += 1\n continue\n elif (tokens_type[i] == my_token.IDENTIFIER) or \\\n (tokens_type[i] == my_token.INT_NUMBER) or (tokens_type[i] == my_token.DOUBLE_NUMBER):\n # выражение TODO: разбор условия\n expr = ast.BinaryAST(while_expr)\n expr, i, error = bin_op_parse(i, tokens_str, tokens_type, expr)\n # expr = ast.CompoundExpression(while_expr)\n # expr, i, error = compound_expression_parse(i, tokens_str, tokens_type, expr)\n if error != \"\":\n print(error)\n return None, i, error\n while_expr.set_expression(expr)\n\n elif tokens_type[i] == my_token.LBRACE:\n i += 1\n # разбор тела\n compound_expression = ast.CompoundExpression(parent=while_expr)\n while tokens_type[i] != my_token.RBRACE:\n compound_expression, i, error = compound_expression_parse(i, tokens_str,\n tokens_type, compound_expression)\n i += 1\n # if tokens_type[i] == my_token.RBRACE:\n # i += 1\n if error != \"\":\n print(error)\n return None, i, error\n while_expr.set_body(compound_expression)\n return while_expr, i, error\n\n\ndef expr_do_while_parse(i: int, tokens_str: List[str], tokens_type, parent=None):\n error = \"\"\n expr_do = None\n while tokens_type[i] != my_token.WHILE:\n if tokens_type[i] == my_token.DO:\n expr_do = ast.ExprDoWhileAST(parent)\n i += 1\n continue\n # elif tokens_type[i] == my_token.RBRACE:\n # i += 1\n # continue\n elif tokens_type[i] == my_token.LBRACE:\n i += 1\n # разбор тела цыкла\n compound_expression = ast.CompoundExpression(parent=expr_do)\n while tokens_type[i] != my_token.RBRACE:\n compound_expression, i, error = compound_expression_parse(i, tokens_str,\n tokens_type, compound_expression)\n i += 1\n i += 1\n if error != \"\":\n print(error)\n return None, i, error\n expr_do.set_body(compound_expression)\n\n if tokens_type[i] == my_token.WHILE:\n i += 1\n # разбор условия (выражение)\n # expr = ast.CompoundExpression(expr_do)\n expr = ast.BinaryAST(expr_do)\n expr, i, error = bin_op_parse(i, tokens_str, tokens_type, expr)\n # expr, i, error = compound_expression_parse(i, tokens_str, tokens_type, expr)\n if error != \"\":\n print(error)\n return None, i, error\n expr_do.set_expression(expr)\n\n return expr_do, i, error\n\n\n# rename func\ndef parse_constr(i: int, tokens_str: List[str], tokens_type, parent=None):\n if tokens_type[i] == my_token.PRINT:\n pass\n\n\ndef main():\n # with open(\"examples/example1.txt\", 'r', encoding='utf-8') as f:\n with open(\"examples/code.txt\", 'r', encoding='utf-8') as f: # не работает этот случай\n # with open(\"examples/functions.txt\", 'r', encoding='utf-8') as f:\n # with open(\"examples/cycle.txt\", 'r', encoding='utf-8') as f:\n # with open(\"examples/expr.txt\", 'r', encoding='utf-8') as f:\n code = f.read()\n # print(code)\n tokens_str, tokens_type = get_token(code)\n # print(tokens_str)\n # print(tokens_type)\n\n root, i, error = base_parse(tokens_str, tokens_type)\n # print(root)\n if error != \"\":\n print(error)\n return\n module = llvm.core.Module.new('my_module')\n root.code_gen(module)\n print(module)\n\n# TODO: Сделать функцию вывода print\n# https://stackoverflow.com/questions/18583642/how-do-i-pass-an-array-pointer-to-a-function-in-llvm-llvmpy\n# https://github.com/llvmpy/llvmpy/blob/master/www/src/userguide.txt\n# https://stackoverflow.com/questions/30234027/how-to-call-printf-in-llvm-through-the-module-builder-system\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.4573208689689636,
"alphanum_fraction": 0.4847351908683777,
"avg_line_length": 18.33734893798828,
"blob_id": "25fcab725c05f1f3d29b54be0be338ff8841e7dc",
"content_id": "6d95fd86f91e9c1dd4f82e17a971544cc321adef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3288,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 166,
"path": "/my_token.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "# арифметические операции\n# OPERATOR_UP = 1\nOPERATOR_UM = 0 # '-'\nOPERATOR_POWER = 1 # '**'\nOPERATOR_MUL = 2 # '*'\nOPERATOR_DIV = 3 # '/'\nPLUS = 4 # '+'\nMINUS = 5 # '-'\n\n# операции сравнения\nLARGER = 6 # '>'\nLARGER_OR_EQUAL = 7 # '>='\nLESS = 8 # '<'\nLESS_OR_EQUAL = 9 # '<='\n\nEQUAL = 10 # '=='\nNOT_EQUAL = 11 # '!='\n\n# оператор присваивания\nASSIGN = 12 # '='\n\n# логические операторы\nAND = 13 # 'and'\nOR = 14 # 'or'\nNOT = 15 # 'not'\n\nIDENTIFIER = 16\nNUMBER = 17\n\nDEF_FUNC = 18 # \"def\"\n# DEC_FUNC = 19\n\n# DEF_VAR = 20\n# DEC_VAR = 21\n\nIF = 19 # 'if'\nELSE = 20 # 'else'\n\nWHILE = 21 # 'while'\nDO = 22 # 'do'\n\nLPAR = 23 # '('\nRPAR = 24 # ')'\n\nLBRACE = 25 # '{'\nRBRACE = 26 # '}'\n\nCOMMA = 27 # ','\nSEMI = 28 # ';'\n\nDEF_VAR = 29 # 'var'\n\nINT = 30\nDOUBLE = 31\nBOOL = 32\nRETURN = 33\nARROW = 34\n\nINT_NUMBER = 35\nDOUBLE_NUMBER = 36\n\nPRINT = 37\n\nTRUE = 38\nFALSE = 39\n\nEND_OF_STR = 49\nEND_OF_FILE = 50\n\ntokens = {\"def\": DEF_FUNC,\n \"print\": PRINT,\n \"if\": IF,\n \"else\": ELSE,\n \"while\": WHILE,\n \"do\": DO,\n \"and\": AND,\n \"or\": OR,\n \"not\": NOT,\n \"(\": LPAR,\n \")\": RPAR,\n \"{\": LBRACE,\n \"}\": RBRACE,\n \",\": COMMA,\n \";\": SEMI,\n \"\\n\": END_OF_STR,\n \"-\": MINUS,\n \"+\": PLUS,\n \"*\": OPERATOR_MUL,\n \"/\": OPERATOR_DIV,\n \"**\": OPERATOR_POWER,\n \">\": LARGER,\n \">=\": LARGER_OR_EQUAL,\n \"<\": LESS,\n \"<=\": LESS_OR_EQUAL,\n \"==\": EQUAL,\n \"=\": ASSIGN,\n \"!=\": NOT_EQUAL,\n \"var\": DEF_VAR,\n \"int\": INT,\n \"double\": DOUBLE,\n \"bool\": BOOL,\n \"return\": RETURN,\n \"->\": ARROW,\n \"true\": TRUE,\n \"false\": FALSE,\n }\n\n\ndef get_priority(t: int) -> int:\n if t in [AND, OR, NOT]:\n return 8\n elif t in [MINUS, PLUS]:\n return 4\n elif t in [OPERATOR_MUL, OPERATOR_DIV]:\n return 3\n elif t in [OPERATOR_POWER]:\n return 2\n elif t in [LARGER, LARGER_OR_EQUAL, LESS, LESS_OR_EQUAL]:\n return 5\n elif t in [ASSIGN]:\n return 7\n elif t in [NOT_EQUAL, EQUAL]:\n return 6\n\n\ndef is_number(token: int) -> bool:\n number = [INT_NUMBER, DOUBLE_NUMBER]\n if token in number:\n return True\n return False\n\n\ndef is_bool(token: int) -> bool:\n number = [TRUE, FALSE]\n if token in number:\n return True\n return False\n\n\ndef is_operator(token: int) -> bool:\n op = [OPERATOR_UM, OPERATOR_POWER, OPERATOR_MUL, OPERATOR_DIV,\n PLUS, MINUS,\n LARGER, LARGER_OR_EQUAL, LESS, LESS_OR_EQUAL, EQUAL, NOT_EQUAL,\n ASSIGN,\n AND, OR, NOT]\n if token in op:\n return True\n else:\n return False\n\n\ndef is_arithmetic_operator(token: int) -> bool:\n op = [OPERATOR_UM, OPERATOR_POWER, OPERATOR_MUL, OPERATOR_DIV,\n PLUS, MINUS,\n ASSIGN]\n if token in op:\n return True\n return False\n\n\ndef is_logic_operator(token: int) -> bool:\n op = [LARGER, LARGER_OR_EQUAL, LESS, LESS_OR_EQUAL, EQUAL, NOT_EQUAL,\n AND, OR, NOT]\n if token in op:\n return True\n return False\n"
},
{
"alpha_fraction": 0.4113219976425171,
"alphanum_fraction": 0.41524869203567505,
"avg_line_length": 26.285715103149414,
"blob_id": "31b68f509ace6618dc3f0d8422156b1dc766d253",
"content_id": "5ac85fdcad29e5053573b974e81fcc4e85a1f170",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3124,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 112,
"path": "/tokenizer.py",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "import re\n\nfrom my_token import tokens, NUMBER, IDENTIFIER, SEMI, INT_NUMBER, DOUBLE_NUMBER\n\n\ncomment = re.compile(r\"[/]{2}.*[\\n]?\")\noperators = \"+-*/!=<>\"\nbrackets = \"(){}\"\n\n\ndef get_token(code: str):\n code = comment.sub('', code)\n # print(code)\n tokens_str = []\n tokens_type = []\n token = \"\"\n error = \"\"\n i = 0\n while i < len(code):\n # print(i)\n c = code[i]\n if (c == ' ') or (c == '\\n') or (c == ','):\n i += 1\n continue\n if c == ';':\n tokens_str.append(c)\n token = \"\"\n tokens_type.append(SEMI)\n i += 1\n continue\n if c.isdigit() or (c == '.'):\n while code[i].isdigit() or (code[i] == '.'):\n if code[i].isdigit():\n token += code[i]\n i += 1\n continue\n if (code[i] == '.') and ('.' not in token):\n token += code[i]\n i += 1\n else:\n error = \"Ошибка\"\n return [], error\n if token.find('.') != -1:\n tokens_type.append(DOUBLE_NUMBER)\n else:\n tokens_type.append(INT_NUMBER)\n tokens_str.append(token)\n token = \"\"\n continue\n if c.isalnum() or (c == '_'):\n if (token == \"\") and c.isdigit():\n error = \"Ошибка! Идентификатор не может начинаться с цыфры.\"\n return [], error\n else:\n while code[i].isalnum() or (code[i] == '_'):\n token += code[i]\n i += 1\n tokens_str.append(token)\n if token in tokens:\n tokens_type.append(tokens.get(token))\n else:\n tokens_type.append(IDENTIFIER)\n token = \"\"\n continue\n if c in brackets:\n if token == \"\":\n tokens_str.append(c)\n tokens_type.append(tokens.get(c))\n token = \"\"\n i += 1\n continue\n if c in operators:\n while code[i] in operators:\n token += code[i]\n i += 1\n if token in tokens:\n tokens_str.append(token)\n tokens_type.append(tokens.get(token))\n token = \"\"\n continue\n else:\n error = \"Некорректный оператор\"\n return [], error\n return tokens_str, tokens_type\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\n# def lexer(tokens_str, tokens_type):\n# i = 0\n# while i < len(tokens_type):\n# t = tokens_type[i]\n# if t ==\n\n\ndef main():\n with open(\"code.txt\", 'r', encoding='utf-8') as f:\n code = f.read()\n print(code)\n tokens_str, tokens_type = get_token(code)\n print(tokens_str)\n print(tokens_type)\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5939257740974426,
"alphanum_fraction": 0.6186726689338684,
"avg_line_length": 11.191781044006348,
"blob_id": "8b48cd8a4b6054643c57ebc20978d2775d49c8a9",
"content_id": "0c8d839300078670a169cb908b3de826af5dac2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1219,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 73,
"path": "/README.md",
"repo_name": "redb0/compiler-on-python",
"src_encoding": "UTF-8",
"text": "# Компилятор на языке Python с использование LLVM\n\n## Синтаксис\n\nТипы данных: int, double, bool.\n```\nvar x int;\nx = 1;\n//-------------\nvar y double;\nvar y1 double;\nvar y2 double;\ny = 0.;\ny1 = .1;\ny2 = 1.5;\n//-------------\nvar t boot;\nvar f bool;\nt = true;\nf = false;\n```\n\nОбъявление переменной:\n```\nvar тип имя_переменной;\n```\n\nОбъявление функции:\n```\ndef function() -> возвращаемый_тип {\n //тело фунции\n}\n```\n\nКлючевое слово для возврата значения из функции: return.\n\nУсловия:\n```\nif выражение {\n //тело1\n} else {\n //тело2\n}\n```\nЦиклы:\n```\nwhile условное_выражение {\n //тело\n}\n\ndo {\n //тело\n} условное_выражение;\n```\n\nОднострочные комментарии:\n```\n//комментарий\n```\n\nПримеры приведены в `./examples/`\n\n## Uses\n\nВозможно понадобиться:\n1) llvm 3.3\n2) python 3.5\n3) llvmpy 0.12.7 [(ссылка)](http://www.llvmpy.org/)\n\nГенерация llvm кода:\n```\npython main.py example/code.txt\n```"
}
] | 9 |
davemasse/django-openrov | https://github.com/davemasse/django-openrov | 4a1f572c18fd1107c3ccc52e207465f2cf99af49 | 927f2283ad6ba4326cd74b7ed6eee14ef9d79f0e | 9e3bd66abd727b5c56e722cc840802dc2b2b11e2 | refs/heads/master | 2021-06-05T09:04:42.773166 | 2017-08-01T23:03:23 | 2017-08-01T23:03:23 | 4,932,498 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5393258333206177,
"alphanum_fraction": 0.5548421740531921,
"avg_line_length": 38.76595687866211,
"blob_id": "0a3c41be0ce0894ea79cafd97c3e95037704113f",
"content_id": "a0e0fd503579758c78b0e0dd72131b95b6de25d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1869,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 47,
"path": "/openrov/migrations/0001_initial.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.3 on 2017-07-22 17:47\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Location',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('remote_id', models.CharField(max_length=100, unique=True)),\n ('remote_text', models.TextField(blank=True, null=True)),\n ('remote_date_created', models.DateTimeField(blank=True, null=True)),\n ('remote_date_modified', models.DateTimeField()),\n ('description', models.TextField(blank=True, null=True)),\n ('lat', models.DecimalField(decimal_places=8, max_digits=10, null=True, verbose_name='latitude')),\n ('lng', models.DecimalField(decimal_places=8, max_digits=11, null=True, verbose_name='longitude')),\n ],\n options={\n 'verbose_name': 'location',\n 'verbose_name_plural': 'locations',\n 'ordering': ('-remote_date_created',),\n },\n ),\n migrations.CreateModel(\n name='Video',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('video_id', models.CharField(blank=True, max_length=100, null=True)),\n ('location', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='openrov.Location')),\n ],\n options={\n 'verbose_name': 'videos',\n 'ordering': ('video_id',),\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6263955235481262,
"alphanum_fraction": 0.6371610760688782,
"avg_line_length": 34.323944091796875,
"blob_id": "c15719f849e151f312abeaedbef13a4352976f21",
"content_id": "a7a15b5247ba8c72e59cce31eedd08d1348ba672",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2508,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 71,
"path": "/openrov/static/openrov/js/openrov.js",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "function OpenROV(options) {\n this.datetime_format = options.datetime_format || '';\n this.infowindow = null;\n this.map_icon = options.map_icon || new google.maps.MarkerImage(options.static_url + 'openrov/images/openrov_marker.png',\n new google.maps.Size(79, 79),\n new google.maps.Point(0, 0),\n new google.maps.Point(0, 0),\n new google.maps.Size(32, 32));\n this.map_id = options.map_id || 'map_canvas';\n this.map_options = options.map_options || {\n mapTypeId: google.maps.MapTypeId.TERRAIN,\n maxZoom: 18\n };\n this.marker_info = options.marker_info || [];\n this.markers = [];\n this.map_shadow = options.map_shadow || new google.maps.MarkerImage(options.static_url + 'openrov/images/openrov_shadow.png',\n new google.maps.Size(119, 79),\n new google.maps.Point(0, 0),\n new google.maps.Point(0, 0),\n new google.maps.Size(48, 32));\n this.map = options.map || new google.maps.Map(document.getElementById(this.map_id), this.map_options);\n}\n\nOpenROV.prototype.initialize = function() {\n var bounds = new google.maps.LatLngBounds();\n \n for (i in this.marker_info) {\n (function (instance, i) {\n var lat_lng = new google.maps.LatLng(instance.marker_info[i].lat, instance.marker_info[i].lng);\n var marker = new google.maps.Marker({\n icon: instance.map_icon,\n map: instance.map,\n position: lat_lng,\n shadow: instance.map_shadow,\n title: instance.marker_info[i].title\n });\n instance.markers.push(marker);\n google.maps.event.addListener(marker, 'click', function() {\n // Close any open infowindow\n if (instance.infowindow) {\n instance.infowindow.close();\n }\n instance.infowindow = new google.maps.InfoWindow({\n content: instance.marker_info[i].infowindow\n });\n instance.infowindow.open(instance.map, this);\n google.maps.event.addListener(instance.infowindow, 'domready', function() {\n $('.date').each(function() {\n var $this = $(this),\n datetime = moment($this.text()).format(instance.datetime_format);\n\n $this.text(datetime);\n });\n });\n });\n bounds.extend(lat_lng);\n instance.map.fitBounds(bounds);\n })(this, i);\n }\n};\n\nOpenROV.prototype.addMarker = function(marker_info) {\n this.marker_info.push(marker_info);\n}\n\nfunction MarkerInfo(options) {\n this.infowindow = options.infowindow;\n this.lat = options.lat;\n this.lng = options.lng;\n this.title = options.title;\n};\n"
},
{
"alpha_fraction": 0.7951807379722595,
"alphanum_fraction": 0.7951807379722595,
"avg_line_length": 21.636363983154297,
"blob_id": "f2bfa3ba7aee666ae125f271e49dbf98eeb65064",
"content_id": "3f48e8836a830c63fc88386c931dd342e54a340d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 11,
"path": "/openrov/admin.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import Location, Video\n\nclass LocationAdmin(admin.ModelAdmin):\n pass\n\nclass VideoAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Location, LocationAdmin)\nadmin.site.register(Video, VideoAdmin)\n"
},
{
"alpha_fraction": 0.6459330320358276,
"alphanum_fraction": 0.6459330320358276,
"avg_line_length": 22.22222137451172,
"blob_id": "923f4ad065057e16a5aff86c36e85915e78bd3e7",
"content_id": "9385852a353b9b56298763a7cf1ac6237e0b6cc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 209,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 9,
"path": "/openrov/urls.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import include, url\n\nfrom . import views\n\napp_name = 'openrov'\nurlpatterns = [\n url(r'^$', views.index, {}, 'index'),\n url(r'^add-location$', views.add_location, {}, 'add_location'),\n]\n"
},
{
"alpha_fraction": 0.696383535861969,
"alphanum_fraction": 0.7089991569519043,
"avg_line_length": 33.97058868408203,
"blob_id": "8839324dbe4f8b8bfacd365bd773b77bfd36dec8",
"content_id": "09f3fd8fa52ab97f473788b5afd5121db9bff6d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1189,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 34,
"path": "/openrov/models.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from __future__ import unicode_literals\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\n\n@python_2_unicode_compatible\nclass Location(models.Model):\n title = models.CharField(max_length=255)\n description = models.TextField(null=True, blank=True)\n date_created = models.DateTimeField(auto_now_add=True)\n date_modified = models.DateTimeField(auto_now=True)\n lat = models.DecimalField(max_digits=10, decimal_places=8, null=True, verbose_name='latitude')\n lng = models.DecimalField(max_digits=11, decimal_places=8, null=True, verbose_name='longitude')\n \n class Meta:\n ordering = ('-date_created',)\n verbose_name = _('location')\n verbose_name_plural = _('locations')\n\n def __str__(self):\n return '%s (%s,%s)' % (self.title, self.lat, self.lng,)\n\n@python_2_unicode_compatible\nclass Video(models.Model):\n location = models.ForeignKey(Location)\n video_id = models.CharField(max_length=100, null=True, blank=True)\n \n class Meta:\n ordering = ('video_id',)\n verbose_name = _('video')\n verbose_name_plural = _('videos')\n \n def __str__(self):\n return self.video_id\n"
},
{
"alpha_fraction": 0.60812908411026,
"alphanum_fraction": 0.6112317442893982,
"avg_line_length": 35.6363639831543,
"blob_id": "5646440aa17c002bb80457390d3c61f6f87472ec",
"content_id": "d7ad9ef13245b2479468ee9f222fd8f2ee7b6736",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3223,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 88,
"path": "/openrov/management/commands/importlocations.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "import datetime\nimport re\nimport requests\nimport time\nfrom optparse import make_option\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nfrom openrov.models import Location, Video\n\nPAGE_SIZE = 10\nTAG_REGEX = re.compile(r' *#[^ ]+')\nVIDEO_REGEX = re.compile(r'(?P<video_url>http://(?:www\\.)?youtube.com/watch\\?\\S*?v=(?P<video_id>[^&\\s]+))')\n\nclass Command(BaseCommand):\n help = 'Collects remote text via Catch API'\n option_list = BaseCommand.option_list + (\n make_option('-d', '--delete',\n action='store_true',\n dest='delete',\n default=False,\n help='Delete any local Location objects that don\\'t exist on the remote side.'),\n )\n \n def handle(self, *args, **options):\n offset = 0\n \n # Get into the loop\n count = PAGE_SIZE\n page_num = 0\n \n while count == PAGE_SIZE:\n params = {\n 'full': True,\n 'limit': PAGE_SIZE,\n 'offset': PAGE_SIZE * page_num,\n 'q': '#openrov',\n 'sort': 'modified_desc',\n }\n r = requests.get('https://api.catch.com/v2/search.json', params=params, auth=(settings.CATCH_USERNAME, settings.CATCH_PASSWORD))\n data = r.json\n \n count = data['count']\n remote_ids = []\n \n for note in data.get('notes', []):\n remote_id = note['id']\n remote_ids.append(remote_id)\n remote_date_modified = note['server_modified_at']\n remote_date_modified = datetime.datetime.strptime(remote_date_modified, '%Y-%m-%dT%H:%M:%S.%fZ')\n remote_date_modified = remote_date_modified.replace(tzinfo=timezone.utc)\n \n try:\n location = Location.objects.get(remote_id=remote_id)\n # Don't process pre-existing locations that are already up-to-date\n if location.remote_date_modified >= remote_date_modified:\n print '[N] %s' % (remote_id,)\n continue\n else:\n print '[U] %s' % (remote_id,)\n except Location.DoesNotExist:\n location = Location(remote_id=remote_id, remote_date_modified=remote_date_modified)\n print '[C] %s' % (remote_id,)\n \n location.remote_date_created = note['server_created_at']\n location.remote_date_modified = note['server_modified_at']\n location.lat = note['location']['features'][0]['geometry']['coordinates'][1]\n location.lng = note['location']['features'][0]['geometry']['coordinates'][0]\n location.save()\n \n remote_text = note['text'].strip()\n for matches in VIDEO_REGEX.finditer(remote_text):\n Video.objects.get_or_create(location=location, video_id=matches.group('video_id'))\n remote_text = remote_text.replace(' %s' % matches.group('video_url'), '')\n \n location.remote_text = remote_text\n location.description = location.description = TAG_REGEX.sub('', remote_text)\n location.save()\n \n page_num += 1\n \n # Delete Location objects that don't exist remotely\n if options.get('delete') == True:\n to_delete = Location.objects.exclude(remote_id__in=remote_ids)\n 'Deleting %s oudated Location objects' % (to_delete.count(),)\n to_delete.delete()"
},
{
"alpha_fraction": 0.6871795058250427,
"alphanum_fraction": 0.6974359154701233,
"avg_line_length": 23.375,
"blob_id": "d070135cca00851b3b223f1d0687a2e9392a442a",
"content_id": "c52ee716bdd9bb30e30b1989dd6b9e4b8e911162",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 195,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 8,
"path": "/setup.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from distutils.core import setup\n\nsetup(name='openrov',\n version='0.2',\n url='https://github.com/davemasse/django-openrov',\n packages=['openrov'],\n install_requires=['Django', 'requests'],\n)\n"
},
{
"alpha_fraction": 0.70652174949646,
"alphanum_fraction": 0.70652174949646,
"avg_line_length": 22,
"blob_id": "ea766e5ad24062cc0cc5f4a5f7a25083b484318c",
"content_id": "82955f6e9eafabe0637bf12e8adc6fff7bc63076",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 8,
"path": "/openrov/forms.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from django.forms import ModelForm\n\nfrom .models import Location\n\nclass LocationForm(ModelForm):\n class Meta:\n model = Location\n fields = ['title', 'description', 'lat', 'lng']\n"
},
{
"alpha_fraction": 0.736952006816864,
"alphanum_fraction": 0.736952006816864,
"avg_line_length": 28.030303955078125,
"blob_id": "6251e9af5052a2af27ab06383041a51e05b80d1e",
"content_id": "f7cccf0160581b87ceffa37f7f08483566cc33d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 958,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 33,
"path": "/openrov/views.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "from django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse\n\nfrom .forms import LocationForm\nfrom .models import Location\n\ndef index(request):\n locations = Location.objects.all()\n \n return render(request, 'openrov/index.html', {\n 'MOMENT_DATETIME_FORMAT': settings.MOMENT_DATETIME_FORMAT,\n 'locations': locations,\n })\n\n@login_required\ndef add_location(request):\n if request.method == 'POST':\n location_form = LocationForm(request.POST)\n\n if location_form.is_valid():\n location_form.save()\n\n messages.add_message(request, messages.SUCCESS, \"The new location record was added successfully.\")\n return redirect(reverse('openrov:add_location'))\n else:\n location_form = LocationForm()\n\n return render(request, 'openrov/add_location.html', {\n 'location_form': location_form,\n })\n"
},
{
"alpha_fraction": 0.8088235259056091,
"alphanum_fraction": 0.8088235259056091,
"avg_line_length": 24.625,
"blob_id": "54b27fce4657c93fb79a35aaca34c8a1d2443d9d",
"content_id": "d07e72bd8b59a21b76874205cf37049450a114f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 204,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 8,
"path": "/openrov/signals.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "django.db.models.signals import post_save\n\nfrom openrov.models import Location\n\ndef process_remote_text(sender, instance, signal):\n print instance\n\npost_save.connect(process_remote_text, sender=Location)"
},
{
"alpha_fraction": 0.5219869613647461,
"alphanum_fraction": 0.5390879511833191,
"avg_line_length": 28.238094329833984,
"blob_id": "dd8d0fcfaffe82e54bd28ea10da30c2dbc6f398c",
"content_id": "68b6f8a39b3c7b8e6f5fd56c944e5d97c55c056c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1228,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 42,
"path": "/openrov/migrations/0002_auto_20170728_2339.py",
"repo_name": "davemasse/django-openrov",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.3 on 2017-07-28 23:39\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('openrov', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='location',\n options={'ordering': ('-date_created',), 'verbose_name': 'location', 'verbose_name_plural': 'locations'},\n ),\n migrations.AlterModelOptions(\n name='video',\n options={'ordering': ('video_id',), 'verbose_name': 'video', 'verbose_name_plural': 'videos'},\n ),\n migrations.RenameField(\n model_name='location',\n old_name='remote_date_created',\n new_name='date_created',\n ),\n migrations.RenameField(\n model_name='location',\n old_name='remote_date_modified',\n new_name='date_modified',\n ),\n migrations.RenameField(\n model_name='location',\n old_name='remote_text',\n new_name='text',\n ),\n migrations.RemoveField(\n model_name='location',\n name='remote_id',\n ),\n ]\n"
}
] | 11 |
ElvisaAlibasic/ouiSem | https://github.com/ElvisaAlibasic/ouiSem | f8f15d5421ef6a01de4e28b06a65217fab6a9af7 | 281a7493bf6c7820e2a607cf4f4047d4117f62cb | fd99a62a01116b2393cb7497e9a75cebc655e38a | refs/heads/master | 2020-04-04T23:28:23.762598 | 2019-01-05T23:49:50 | 2019-01-05T23:49:50 | 156,360,112 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6778860092163086,
"alphanum_fraction": 0.6837909817695618,
"avg_line_length": 33.65262985229492,
"blob_id": "936b60978213927cb593fc473d4beab32052d992",
"content_id": "648e2a5acfe37b6b4e5c510ceb6547a9e3ca06ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3387,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 95,
"path": "/c++/include/rbsim2d/robot.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"body.h\"\r\n#include \"path.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IRobot : public IBody\r\n\t{\r\n\tpublic:\r\n\t\tclass PIDProfile\r\n\t\t{\r\n\t\tpublic:\r\n\t\t\tPIDProfile(double kp, double ki, double kd) : kp(kp), ki(ki), kd(kd) {}\r\n\t\t\t~PIDProfile() {}\r\n\t\t\tdouble kp, ki, kd;\r\n\t\t};\r\n\r\n\t\tvirtual Position frontPoint() const = 0;\r\n\t\tvirtual double headingAngle() const = 0;\r\n\t\tvirtual double angleTo(Position position) const = 0;\r\n\t\tvirtual double angleTo(IBody *body) const = 0;\r\n\t\tvirtual double steeringRadius() const = 0;\r\n\t\tvirtual Position steeringGrip() const = 0;\r\n\t\tvirtual void setWheels(double left, double right) = 0;\r\n\t\tvirtual void moveTo(Position position, double tolerance, PIDProfile &pidProfile) = 0;\r\n\t\tvirtual void rotateTo(double angle, double tolerance, PIDProfile &pidProfile) = 0;\r\n virtual void rotateBy(double angle, double tolerance, PIDProfile &pidProfile) = 0;\r\n\t\tvirtual void follow(IPath *path, double trackWidth = 1) = 0;\r\n\t\tvirtual double findTrackWidth() = 0;\r\n\t\tvirtual bool busy() = 0;\r\n\t\tvirtual void stop() = 0;\r\n\t\tvirtual void waitTask() = 0;\r\n\t\tvirtual bool waitTask(int time) = 0;\r\n\t\tvirtual void enableVisualization(\r\n\t\t\tICanvas *canvas,\r\n\t\t\tICanvas::Color lineColor = ICanvas::Color::white,\r\n\t\t\tICanvas::Color dotColor = ICanvas::Color::red) = 0;\r\n\t\tvirtual void disableVisualization() = 0;\r\n\t};\r\n\r\n\r\n\tclass CRobot : public CBody\r\n\t{\r\n\t\tfriend class CPlayground;\r\n\t\tfriend class CPathfinder;\r\n\r\n\tpublic:\r\n\t\ttypedef IRobot::PIDProfile PIDProfile;\r\n\r\n\t\tCRobot(const CRobot &cRobot) : iRobot(cRobot.iRobot) {}\r\n\t\t~CRobot() {}\r\n\r\n\t\tCRobot &operator=(const CRobot &cRobot) {\r\n\t\t\tiRobot = cRobot.iRobot;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tPosition frontPoint() const { return iRobot->frontPoint(); }\r\n\t\tdouble headingAngle() const { return iRobot->headingAngle(); }\r\n\t\tdouble angleTo(Position position) const { return iRobot->angleTo(position); }\r\n\t\tdouble angleTo(const CBody &body) const { return iRobot->angleTo(body.iBody); }\r\n\t\tdouble steeringRadius() const { return iRobot->steeringRadius(); }\r\n\t\tPosition steeringGrip() const { return iRobot->steeringGrip(); }\r\n\t\tvoid setWheels(double left, double right) { iRobot->setWheels(left, right); }\r\n\t\tvoid moveTo(Position position, double tolerance, PIDProfile &pidProfile) {\r\n\t\t\tiRobot->moveTo(position, tolerance, pidProfile);\r\n\t\t}\r\n\t\tvoid rotateTo(double angle, double tolerance, PIDProfile &pidProfile) {\r\n\t\t\tiRobot->rotateTo(angle, tolerance, pidProfile);\r\n\t\t}\r\n void rotateBy(double angle, double tolerance, PIDProfile &pidProfile) {\r\n\t\t\tiRobot->rotateBy(angle, tolerance, pidProfile);\r\n\t\t}\r\n\t\tvoid follow(const CPath &path, double trackWidth = 1) {\r\n\t\t\tiRobot->follow(path.iPath, trackWidth);\r\n\t\t}\r\n\t\tdouble findTrackWidth() { return iRobot->findTrackWidth(); }\r\n\t\tbool busy() { return iRobot->busy(); }\r\n\t\tvoid stop() { iRobot->stop(); }\r\n\t\tvoid waitTask() { iRobot->waitTask(); }\r\n\t\tbool waitTask(int time) { return iRobot->waitTask(time); }\r\n\t\tvoid enableVisualization(\r\n\t\t\tCCanvas canvas,\r\n\t\t\tCCanvas::Color lineColor = CCanvas::Color::white,\r\n\t\t\tCCanvas::Color dotColor = CCanvas::Color::red)\r\n\t\t{\r\n\t\t\tiRobot->enableVisualization(canvas.iCanvas, lineColor, dotColor);\r\n\t\t}\r\n\t\tvoid disableVisualization() { iRobot->disableVisualization(); }\r\n\r\n\tprotected:\r\n\t\tIRobot *iRobot;\r\n\t\tCRobot() : CBody(), iRobot(nullptr) {}\r\n\t\tCRobot(IRobot *iRobot) : CBody(iRobot), iRobot(iRobot) {}\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.8586956262588501,
"alphanum_fraction": 0.8586956262588501,
"avg_line_length": 45,
"blob_id": "2f04ed5ecc1cad39ba3eb7c3b58f8b3820ecdb91",
"content_id": "7452572cde8ace67e99cc6a995fcdab55457440c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 92,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 2,
"path": "/README.md",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "# ouiSem\nProjekt namenjen izdelavi seminarske naloge pri predmetu Osnove Umetne Inteligence\n"
},
{
"alpha_fraction": 0.6990259885787964,
"alphanum_fraction": 0.7022727131843567,
"avg_line_length": 26.256879806518555,
"blob_id": "92f8bc49080ba602330364694608b00adc39e372",
"content_id": "fec0300cfe42d147193b5a9604922453f0c35ff2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3080,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 109,
"path": "/c++/include/rbsim2d/pathfinder.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"body.h\"\r\n#include \"robot.h\"\r\n#include \"path.h\"\r\n#include \"canvas.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IPathfinder\r\n\t{\r\n\tpublic:\r\n\t\tstatic IPathfinder *create();\r\n\t\tstatic IPathfinder *clone(IPathfinder *iPathfinder);\r\n\t\tstatic void dispose(IPathfinder *pathfinder);\r\n\t\tvirtual void clearObstacles() = 0;\r\n\t\tvirtual void addObstacle(IBody *body) = 0;\r\n\t\tvirtual void removeObstacle(IBody *body) = 0;\r\n\t\tvirtual void setSpacing(double spacing) = 0;\r\n\r\n\t\tvirtual IPath *find(\r\n\t\t\tconst Position &startPosition,\r\n\t\t\tdouble startOrientation,\r\n\t\t\tconst Position &goalPosition,\r\n\t\t\tdouble goalOrientation) = 0;\r\n\r\n\t\tvirtual IPath *find(\r\n\t\t\tconst Position &startPosition,\r\n\t\t\tdouble startOrientation,\r\n\t\t\tconst Position &goalPosition) = 0;\r\n\r\n\t\tvirtual IPath *find(\r\n\t\t\tIRobot *robot,\r\n\t\t\tconst Position &goalPosition,\r\n\t\t\tdouble goalOrientation) = 0;\r\n\r\n\t\tvirtual IPath *find(\r\n\t\t\tIRobot *robot,\r\n\t\t\tconst Position &goalPosition) = 0;\r\n\r\n\t\tvirtual void enableVisualization(\r\n\t\t\tICanvas *canvas,\r\n\t\t\tICanvas::Color lineColor = ICanvas::Color::white,\r\n\t\t\tICanvas::Color dotColor = ICanvas::Color::red) = 0;\r\n\t\tvirtual void disableVisualization() = 0;\r\n\t};\r\n\r\n\r\n\tclass CPathfinder\r\n\t{\r\n\tpublic:\r\n\t\tCPathfinder() { iPathfinder = IPathfinder::create(); }\r\n\t\tCPathfinder(const CPathfinder &cPathfinder) { iPathfinder = IPathfinder::clone(cPathfinder.iPathfinder); }\r\n\t\t~CPathfinder() { IPathfinder::dispose(iPathfinder); }\r\n\r\n\t\tCPathfinder &operator=(const CPathfinder &cPathfinder) {\r\n\t\t\tIPathfinder::dispose(iPathfinder);\r\n\t\t\tiPathfinder = IPathfinder::clone(cPathfinder.iPathfinder);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvoid clearObstacles() { iPathfinder->clearObstacles(); }\r\n\t\tvoid addObstacle(CBody &body) { iPathfinder->addObstacle(body.iBody); }\r\n\t\tvoid removeObstacle(CBody &body) { iPathfinder->removeObstacle(body.iBody); }\r\n\t\tvoid setSpacing(double spacing) { iPathfinder->setSpacing(spacing); }\r\n\r\n\t\tCPath find(\r\n\t\t\tconst Position &startPosition,\r\n\t\t\tdouble startOrientation,\r\n\t\t\tconst Position &goalPosition,\r\n\t\t\tdouble goalOrientation)\r\n\t\t{\r\n\t\t\treturn CPath(iPathfinder->find(startPosition, startOrientation, goalPosition, goalOrientation));\r\n\t\t}\r\n\r\n\t\tCPath find(\r\n\t\t\tconst Position &startPosition,\r\n\t\t\tdouble startOrientation,\r\n\t\t\tconst Position &goalPosition)\r\n\t\t{\r\n\t\t\treturn CPath(iPathfinder->find(startPosition, startOrientation, goalPosition));\r\n\t\t}\r\n\r\n\t\tCPath find(\r\n\t\t\tCRobot &robot,\r\n\t\t\tconst Position &goalPosition,\r\n\t\t\tdouble goalOrientation)\r\n\t\t{\r\n\t\t\treturn CPath(iPathfinder->find(robot.iRobot, goalPosition, goalOrientation));\r\n\t\t}\r\n\r\n\t\tCPath find(\r\n\t\t\tCRobot robot,\r\n\t\t\tconst Position &goalPosition)\r\n\t\t{\r\n\t\t\treturn CPath(iPathfinder->find(robot.iRobot, goalPosition));\r\n\t\t}\r\n\r\n\t\tvoid enableVisualization(\r\n\t\t\tCCanvas &canvas,\r\n\t\t\tCCanvas::Color lineColor = CCanvas::Color::white,\r\n\t\t\tCCanvas::Color dotColor = CCanvas::Color::red)\r\n\t\t{\r\n\t\t\tiPathfinder->enableVisualization(canvas.iCanvas, lineColor, dotColor);\r\n\t\t}\r\n\t\tvirtual void disableVisualization() { iPathfinder->disableVisualization(); }\r\n\r\n\tprotected:\r\n\t\tIPathfinder *iPathfinder;\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.7029703259468079,
"alphanum_fraction": 0.7079207897186279,
"avg_line_length": 31.66666603088379,
"blob_id": "02b4f7112a782159cb7c5d300650259d2b307144",
"content_id": "01a428fe3df261bcdddc0ba1c6ed358444c801db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3030,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 90,
"path": "/c++/include/rbsim2d/mouse.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"position.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IMouse\r\n\t{\r\n\tpublic:\r\n\t\tenum class ButtonType { undefined, left, right };\r\n\t\tenum class ButtonState { released, pressed };\r\n\r\n\t\tclass ClickEvent {\r\n\t\tpublic:\r\n\t\t\tClickEvent() :\r\n\t\t\t\tmousePosition(Position(0, 0)),\r\n\t\t\t\tmouseButtonType(IMouse::ButtonType::undefined),\r\n\t\t\t\tmouseButtonState(IMouse::ButtonState::released) {}\r\n\t\t\tClickEvent(const ClickEvent &clickEvent) :\r\n\t\t\t\tmousePosition(clickEvent.mousePosition),\r\n\t\t\t\tmouseButtonType(clickEvent.mouseButtonType),\r\n\t\t\t\tmouseButtonState(clickEvent.mouseButtonState) {}\r\n\t\t\t~ClickEvent() {}\r\n\r\n\t\t\tClickEvent &operator=(const ClickEvent &clickEvent) {\r\n\t\t\t\tmousePosition = clickEvent.mousePosition;\r\n\t\t\t\tmouseButtonType = clickEvent.mouseButtonType;\r\n\t\t\t\tmouseButtonState = clickEvent.mouseButtonState;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tPosition position() const { return mousePosition; }\r\n\t\t\tButtonType buttonType() const { return mouseButtonType; }\r\n\t\t\tButtonState buttonState() const { return mouseButtonState; }\r\n\r\n\t\tprotected:\r\n\t\t\tPosition mousePosition;\r\n\t\t\tButtonType mouseButtonType;\r\n\t\t\tButtonState mouseButtonState;\r\n\t\t};\r\n\r\n\t\tvirtual Position position() const = 0;\r\n\t\tvirtual ButtonState buttonState(ButtonType buttonType) const = 0;\r\n\t\tvirtual int wheelPosition() const = 0;\r\n\t\tvirtual void resetWheelPosition() = 0;\r\n\t\tvirtual bool clickEventsPending() const = 0;\r\n\t\tvirtual ClickEvent popClickEvent() = 0;\r\n\t\tvirtual void flushClickEvents() = 0;\r\n\t\tvirtual void waitEvent() = 0;\r\n\t\tvirtual bool waitEvent(int time) = 0;\r\n\t\tvirtual ClickEvent waitClickEvent(int time) = 0;\r\n\t\tvirtual ClickEvent waitClickEvent(ButtonState buttonState = ButtonState::released, int time = 0) = 0;\r\n\t};\r\n\r\n\r\n\tclass CMouse\r\n\t{\r\n\t\tfriend class CPlayground;\r\n\r\n\tpublic:\r\n\t\ttypedef IMouse::ButtonType ButtonType;\r\n\t\ttypedef IMouse::ButtonState ButtonState;\r\n\t\ttypedef IMouse::ClickEvent ClickEvent;\r\n\t\t\r\n\t\tCMouse(const CMouse &cMouse) : iMouse(cMouse.iMouse) {}\r\n\t\t~CMouse() {}\r\n\r\n\t\tCMouse &operator=(const CMouse &cMouse) {\r\n\t\t\tiMouse = cMouse.iMouse;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tPosition position() const { return iMouse->position(); }\r\n\t\tButtonState buttonState(ButtonType buttonType) const { return iMouse->buttonState(buttonType); }\r\n\t\tint wheelPosition() const { return iMouse->wheelPosition(); }\r\n\t\tvoid resetWheelPosition() { iMouse->resetWheelPosition(); }\r\n\t\tbool clickEventsPending() const { return iMouse->clickEventsPending(); }\r\n\t\tClickEvent popClickEvent() { return iMouse->popClickEvent(); }\r\n\t\tvoid flushClickEvents() { iMouse->flushClickEvents(); }\r\n\t\tvoid waitEvent() { iMouse->waitEvent(); }\r\n\t\tbool waitEvent(int time) { return iMouse->waitEvent(time); }\r\n\t\tClickEvent waitClickEvent(int time) { return iMouse->waitClickEvent(time); }\r\n\t\tClickEvent waitClickEvent(ButtonState buttonState = ButtonState::released, int time = 0) {\r\n\t\t\treturn iMouse->waitClickEvent(buttonState, time);\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tCMouse() : iMouse(nullptr) {}\r\n\t\tCMouse(IMouse *iMouse) : iMouse(iMouse) {}\r\n\t\tIMouse *iMouse;\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.6977196931838989,
"alphanum_fraction": 0.7035595178604126,
"avg_line_length": 38.40449523925781,
"blob_id": "826bd68453a66c6db5fdcdb4747bc8f4b9ee11e1",
"content_id": "b2d5c9bfae7b737174e66bba51323f1e6e1f250c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3596,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 89,
"path": "/c++/include/rbsim2d/body.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include \"canvas.h\"\r\n#include \"position.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IBody\r\n\t{\r\n\tpublic:\r\n\t\tvirtual std::string name() const = 0;\r\n\t\tvirtual double radius() const = 0;\r\n\t\tvirtual Position position() const = 0;\r\n\t\tvirtual double orientation() const = 0;\r\n\t\tvirtual double speed() const = 0;\r\n\t\tvirtual double rotationalSpeed() const = 0;\r\n\t\tvirtual bool occupies(Position position) const = 0;\r\n\t\tvirtual int countEdges() const = 0;\r\n\t\tvirtual double edgeLength(int edge) const = 0;\r\n\t\tvirtual double edgeDirection(int edge) const = 0;\r\n\t\tvirtual Position borderPoint(int edge, double tau) const = 0;\r\n\t\tvirtual Position borderPoint(double direction) const = 0;\r\n\t\tvirtual double distanceByCenter(Position position) const = 0;\r\n\t\tvirtual double distanceByCenter(IBody *body) const = 0;\r\n\t\tvirtual double distanceByBorder(Position position) const = 0;\r\n\t\tvirtual double distanceByBorder(IBody *body) const = 0;\r\n\t\tvirtual bool project(const Position position, double direction,\r\n\t\t\tPosition &projection, int &edge, double &tau) const = 0;\r\n\t\tvirtual void place(Position position, double orientation) = 0;\r\n\t\tvirtual void waitEvent() = 0;\r\n\t\tvirtual bool waitEvent(int time) = 0;\r\n\t\tvirtual void drawBorder(\r\n\t\t\tICanvas *canvas,\r\n\t\t\tICanvas::Color lineColor = ICanvas::Color::white,\r\n\t\t\tICanvas::Color dotColor = ICanvas::Color::red) const = 0;\r\n\t};\r\n\r\n\r\n\tclass CBody\r\n\t{\r\n\t\tfriend class CPlayground;\r\n\t\tfriend class CRobot;\r\n\t\tfriend class CPathfinder;\r\n\r\n\tpublic:\r\n\t\tCBody(const CBody &cBody) : iBody(cBody.iBody) {}\r\n\t\t~CBody() {}\r\n\r\n\t\tCBody &operator=(const CBody &cBody) {\r\n\t\t\tiBody = cBody.iBody;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tstd::string name() const { return iBody->name(); }\r\n\t\tdouble radius() const { return iBody->radius(); }\r\n\t\tPosition position() const { return iBody->position(); }\r\n\t\tdouble orientation() const { return iBody->orientation(); }\r\n\t\tdouble speed() const { return iBody->speed(); }\r\n\t\tdouble rotationalSpeed() const { return iBody->rotationalSpeed(); }\r\n\t\tbool occupies(Position position) const { return iBody->occupies(position); }\r\n\t\tint countEdges() const { return iBody->countEdges(); }\r\n\t\tdouble edgeLength(int edge) const { return iBody->edgeLength(edge); }\r\n\t\tdouble edgeDirection(int edge) const { return iBody->edgeDirection(edge); }\r\n\t\tPosition borderPoint(int edge, double tau) const { return iBody->borderPoint(edge, tau); }\r\n\t\tPosition borderPoint(double direction) const { return iBody->borderPoint(direction); }\r\n\t\tdouble distanceByCenter(Position position) const { return iBody->distanceByCenter(position); }\r\n\t\tdouble distanceByCenter(CBody &body) const { return iBody->distanceByCenter(body.iBody); }\r\n\t\tdouble distanceByBorder(Position position) const { return iBody->distanceByBorder(position); }\r\n\t\tdouble distanceByBorder(CBody &body) const { return iBody->distanceByBorder(body.iBody); }\r\n\t\tbool project(const Position position, double direction, Position &projection, int &edge, double &tau) const\r\n\t\t{\r\n\t\t\treturn iBody->project(position, direction, projection, edge, tau);\r\n\t\t}\r\n\t\tvoid place(Position position, double orientation) { iBody->place(position, orientation); }\r\n\t\tvoid waitEvent() { iBody->waitEvent(); }\r\n\t\tbool waitEvent(int time) { return iBody->waitEvent(time); }\r\n\t\tvoid drawBorder(\r\n\t\t\tCCanvas canvas,\r\n\t\t\tCCanvas::Color lineColor = CCanvas::Color::white,\r\n\t\t\tCCanvas::Color dotColor = CCanvas::Color::red) const\r\n\t\t{\r\n\t\t\tiBody->drawBorder(canvas.iCanvas, lineColor, dotColor);\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tCBody() : iBody(nullptr) {}\r\n\t\tCBody(IBody *iBody) : iBody(iBody) {}\r\n\t\tIBody *iBody;\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.685029923915863,
"alphanum_fraction": 0.6902195811271667,
"avg_line_length": 33.81428527832031,
"blob_id": "d71e5e2c0be6e9ef02b53e94d752046035fc17b9",
"content_id": "ca6a5df5b2394fa7f672432f01b1f2e6d8545500",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2505,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 70,
"path": "/c++/include/rbsim2d/path.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include \"canvas.h\"\r\n#include \"position.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IPath\r\n\t{\r\n\tpublic:\r\n\t\tstatic IPath *create();\r\n\t\tstatic IPath *clone(IPath *iPath);\r\n\t\tstatic void dispose(IPath *iPath);\r\n\t\tvirtual void clear() = 0;\r\n\t\tvirtual void appendStart(const Position &position) = 0;\r\n\t\tvirtual void appendGoal(const Position &position) = 0;\r\n\t\tvirtual void appendStartSmooth(const Position &position) = 0;\r\n\t\tvirtual void appendGoalSmooth(const Position &position) = 0;\r\n\t\tvirtual bool empty() const = 0;\r\n\t\tvirtual double length() const = 0;\r\n\t\tvirtual Position startPosition() const = 0;\r\n\t\tvirtual Position goalPosition() const = 0;\r\n\t\tvirtual Position position(double distance) const = 0;\r\n\t\tvirtual Position position(double distance, const Position &reference) const = 0;\r\n\t\tvirtual double travelDistance(const Position &position) const = 0;\r\n\t\tvirtual void draw(\r\n\t\t\tICanvas *canvas,\r\n\t\t\tICanvas::Color lineColor = ICanvas::Color::yellow,\r\n\t\t\tICanvas::Color dotColor = ICanvas::Color::red) const = 0;\r\n\t};\r\n\r\n\r\n\tclass CPath\r\n\t{\r\n\t\tfriend class CRobot;\r\n\t\tfriend class CPathfinder;\r\n\r\n\tpublic:\r\n\t\tCPath() { iPath = IPath::create(); }\r\n\t\tCPath(const CPath &cPath) { iPath = IPath::clone(cPath.iPath); }\r\n\t\t~CPath() { IPath::dispose(iPath); }\r\n\t\t\r\n\t\tCPath &operator=(const CPath &cPath) {\r\n\t\t\tIPath::dispose(iPath);\r\n\t\t\tiPath = IPath::clone(cPath.iPath);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvoid clear() { iPath->clear(); }\r\n\t\tvoid appendStart(const Position &position) { iPath->appendStart(position); }\r\n\t\tvoid appendGoal(const Position &position) { iPath->appendGoal(position); }\r\n\t\tvoid appendStartSmooth(const Position &position) { iPath->appendStartSmooth(position); }\r\n\t\tvoid appendGoalSmooth(const Position &position) { iPath->appendGoalSmooth(position); }\r\n\t\tbool empty() const { return iPath->empty(); }\r\n\t\tdouble length() const { return iPath->length(); }\r\n\t\tPosition startPosition() const { return iPath->startPosition(); }\r\n\t\tPosition goalPosition() const { return iPath->goalPosition(); }\r\n\t\tPosition position(double distance) const { return iPath->position(distance); }\r\n\t\tPosition position(double distance, const Position &reference) const { return iPath->position(distance, reference); }\r\n\t\tvoid draw(\r\n\t\t\tCCanvas &canvas,\r\n\t\t\tCCanvas::Color lineColor = CCanvas::Color::yellow,\r\n\t\t\tCCanvas::Color dotColor = CCanvas::Color::red) const\r\n\t\t{\r\n\t\t\tiPath->draw(canvas.iCanvas, lineColor, dotColor);\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tCPath(IPath *iPath) : iPath(iPath) {}\r\n\t\tIPath *iPath;\r\n\t};\r\n}"
},
{
"alpha_fraction": 0.5699999928474426,
"alphanum_fraction": 0.5872222185134888,
"avg_line_length": 19.68674659729004,
"blob_id": "d7caacd6e30b0ae02be65fb22a2f5c6eb47646b4",
"content_id": "6c5e8929ce08008117fe61a2405856d29d59e513",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1800,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 83,
"path": "/c++/include/rbsim2d/position.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <cmath>\r\n\r\n#define PI 3.14159265358979323846\r\n\r\nnamespace rbsim {\r\n\tclass Position\r\n\t{\r\n\tpublic:\r\n\t\tdouble x;\r\n\t\tdouble y;\r\n\r\n\t\tPosition() : x(0), y(0) {}\r\n\t\tPosition(double x, double y) : x(x), y(y) {}\r\n\t\tPosition(const Position &position) : x(position.x), y(position.y) {}\r\n\t\t~Position() {}\r\n\r\n\t\tbool operator==(const Position &position) const {\r\n\t\t\treturn x == position.x && y == position.y;\r\n\t\t}\r\n\r\n\t\tbool operator!=(const Position &position) const {\r\n\t\t\treturn x != position.x || y != position.y;\r\n\t\t}\r\n\r\n\t\tPosition &operator=(const Position &position) {\r\n\t\t\tx = position.x; y = position.y; return *this;\r\n\t\t}\r\n\r\n\t\tPosition &operator=(const double value) {\r\n\t\t\tx = value; y = value; return *this;\r\n\t\t}\r\n\r\n\t\tPosition operator+(const Position &position) {\r\n\t\t\treturn Position(x + position.x, y + position.y);\r\n\t\t}\r\n\r\n\t\tPosition &operator+=(const Position &position) {\r\n\t\t\tx += position.x;\r\n\t\t\ty += position.y;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tPosition operator-() {\r\n\t\t\treturn Position(-x, -y);\r\n\t\t}\r\n\r\n\t\tPosition operator-(const Position &position) {\r\n\t\t\treturn Position(x - position.x, y - position.y);\r\n\t\t}\r\n\r\n\t\tPosition &operator-=(const Position &position) {\r\n\t\t\tx -= position.x;\r\n\t\t\ty -= position.y;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tPosition operator*(double factor) {\r\n\t\t\treturn Position(factor * x, factor * y);\r\n\t\t}\r\n\r\n\t\tPosition &operator*=(double factor) {\r\n\t\t\tx *= factor;\r\n\t\t\ty *= factor;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tPosition operator/(double divisor) {\r\n\t\t\treturn Position(x / divisor, y / divisor);\r\n\t\t}\r\n\r\n\t\tPosition &operator/=(double divisor) {\r\n\t\t\tx /= divisor;\r\n\t\t\ty /= divisor;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvoid move(double angle, double distance) {\r\n\t\t\tx += std::cos(angle * PI / 180.0) * distance;\r\n\t\t\ty += std::sin(angle * PI / 180.0) * distance;\r\n\t\t}\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.5833055973052979,
"alphanum_fraction": 0.5969404578208923,
"avg_line_length": 28.683673858642578,
"blob_id": "7875b2e0dce81ef054cb6455fe45e7cffec9028d",
"content_id": "66166823af2a767de7fedb4ebb1a77ff01cc995d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3007,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 98,
"path": "/python3/64bit/robot.py",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "import rbsim2d\r\nimport random\r\nimport math\r\n\r\ndef position_at_box(playground, robot, box, edge, tau):\r\n # Check input parameters.\r\n if edge < 0 or edge >= box.count_edges() or tau < 0 or tau > 1:\r\n return\r\n\r\n # Compute where the center of the robot should be.\r\n (x, y) = box.border_point(edge, tau)\r\n angle = box.edge_direction(edge)\r\n x += math.cos((angle - 180.0) * math.pi / 180.0) * robot.radius()\r\n y += math.sin((angle - 180.0) * math.pi / 180.0) * robot.radius()\r\n\r\n # Find a path.\r\n pathfinder = rbsim2d.Pathfinder()\r\n pathfinder.add_obstacle(box)\r\n pathfinder.set_spacing(1.1 * robot.radius())\r\n path = pathfinder.find(robot, (x, y), angle);\r\n\r\n # Draw the path.\r\n canvas_path = playground.get_canvas(\"path\");\r\n path.draw(canvas_path);\r\n\r\n # Follow the path.\r\n canvas_follow = playground.get_canvas(\"follow\");\r\n robot.enable_visualization(canvas_follow);\r\n robot.follow(path, 10);\r\n\r\n # Wait until task finished or user clicks the mouse.\r\n while (robot.busy() and not playground.get_mouse().click_events_pending()):\r\n pass\r\n\r\n # Clear all drawings.\r\n canvas_path.clear();\r\n canvas_follow.clear();\r\n robot.disable_visualization();\r\n\r\n\r\ndef push_by(robot, distance):\r\n # Move forward by the given distance.\r\n pathfinder = rbsim2d.Pathfinder()\r\n (x, y) = robot.position();\r\n x += math.cos(robot.heading_angle() * math.pi / 180.0) * distance\r\n y += math.sin(robot.heading_angle() * math.pi / 180.0) * distance\r\n path = pathfinder.find(robot, (x, y));\r\n robot.follow(path);\r\n\r\n # Wait until finished. Because of short duration we don't check the mouse.\r\n robot.wait_task();\r\n \r\n\r\ndef main():\r\n # Connect to simulator.\r\n playground = rbsim2d.Playground()\r\n if not playground.connect():\r\n print(playground.get_error())\r\n exit()\r\n\r\n # Get the robot and other objects.\r\n robot = playground.get_robot(\"robot\")\r\n box = playground.get_body(\"box\")\r\n goal = playground.get_body(\"goal\")\r\n\r\n # Get the mouse.\r\n mouse = playground.get_mouse()\r\n\r\n # Push randomly until user clicks the mouse.\r\n run = True\r\n while run:\r\n # Choose randomly where and how to push.\r\n edge = random.randint(0, 3)\r\n tau = random.uniform(0, 1)\r\n dist = random.uniform(0, 5)\r\n print(\"edge =\", edge, \"tau =\", tau, \"distance =\", dist)\r\n\r\n # Move there.\r\n position_at_box(playground, robot, box, edge, tau)\r\n\r\n # If mouse was not clicked during positioning, proceed with pushing.\r\n if not mouse.click_events_pending():\r\n push_by(robot, dist);\r\n\r\n # If user clicked, stop.\r\n if mouse.click_events_pending():\r\n mouse.flush_click_events(); # Remove all click events from queue.\r\n run = False;\r\n\r\n # Stop the robot.\r\n robot.stop();\r\n\r\n # Disconnect from simulator\r\n playground.disconnect()\r\n print(\"Goodbye!\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
},
{
"alpha_fraction": 0.6703973412513733,
"alphanum_fraction": 0.6765528917312622,
"avg_line_length": 29.35087776184082,
"blob_id": "61d7d5505b38c7558d5c4281673b0dc9d8347b88",
"content_id": "0cd44790afdbc390cfee00fce35ed9de685460e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1787,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 57,
"path": "/c++/include/rbsim2d/canvas.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include \"position.h\"\r\n\r\nnamespace rbsim {\r\n\tclass ICanvas\r\n\t{\r\n\tpublic:\r\n\t\tenum class Color { none, white, black, red, green, blue, cyan, yellow, magenta };\r\n\r\n\t\tvirtual void clear() const = 0;\r\n\t\tvirtual void drawDot(const Position &p, Color color = Color::white) const = 0;\r\n\t\tvirtual void drawLine(const Position &p1, const Position &p2, Color color = Color::white) const = 0;\r\n\t\tvirtual void drawCircle(const Position ¢er, double radius, Color color = Color::white) const = 0;\r\n\t\tvirtual void drawArc(const Position ¢er, double radius, double alpha, double beta, Color color = Color::white) const = 0;\r\n\t};\r\n\r\n\r\n\tclass CCanvas\r\n\t{\r\n\t\tfriend class CPlayground;\r\n\t\tfriend class CBody;\r\n\t\tfriend class CRobot;\r\n\t\tfriend class CPath;\r\n\t\tfriend class CPathfinder;\r\n\r\n\tpublic:\r\n\t\ttypedef ICanvas::Color Color;\r\n\r\n\t\tCCanvas(const CCanvas &cCanvas) : iCanvas(cCanvas.iCanvas) {}\r\n\t\t~CCanvas() {}\r\n\r\n\t\tCCanvas &operator=(const CCanvas &cCanvas) {\r\n\t\t\tiCanvas = cCanvas.iCanvas;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvoid clear() const { iCanvas->clear(); }\r\n\t\tvoid drawDot(const Position &p, Color color = Color::white) const {\r\n\t\t\tiCanvas->drawDot(p, color);\r\n\t\t}\r\n\t\tvoid drawLine(const Position &p1, const Position &p2, Color color = Color::white) const {\r\n\t\t\tiCanvas->drawLine(p1, p2, color);\r\n\t\t}\r\n\t\tvoid drawCircle(const Position ¢er, double radius, Color color = Color::white) const {\r\n\t\t\tiCanvas->drawCircle(center, radius, color);\r\n\t\t}\r\n\t\tvoid drawArc(const Position ¢er, double radius, double alpha, double beta, Color color = Color::white) const {\r\n\t\t\tiCanvas->drawArc(center, radius, alpha, beta, color);\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tCCanvas() : iCanvas(nullptr) {}\r\n\t\tCCanvas(ICanvas *iCanvas) : iCanvas(iCanvas) {}\r\n\t\tICanvas *iCanvas;\r\n\t};\r\n}\r\n"
},
{
"alpha_fraction": 0.6866071224212646,
"alphanum_fraction": 0.692559540271759,
"avg_line_length": 35.78651809692383,
"blob_id": "fb7c35fda3dfd8a3efe45f091017aa99fb1b07ed",
"content_id": "68f7bf73ffd16da620673f449037e1c998f68be6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3360,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 89,
"path": "/c++/include/rbsim2d/playground.h",
"repo_name": "ElvisaAlibasic/ouiSem",
"src_encoding": "UTF-8",
"text": "#pragma once\r\n#include <string>\r\n#include <vector>\r\n#include \"body.h\"\r\n#include \"robot.h\"\r\n#include \"canvas.h\"\r\n#include \"mouse.h\"\r\n\r\nnamespace rbsim {\r\n\tclass IPlayground\r\n\t{\r\n\t\tfriend class CPlayground;\r\n\r\n\tpublic:\r\n\t\tstatic double getProtocolVersion();\r\n\t\tstatic IPlayground *create();\r\n\t\tstatic IPlayground *create(const std::string &host);\r\n\t\tstatic IPlayground *create(const std::string &host, const std::string &port);\r\n\t\tstatic void dispose(IPlayground *iPlayground);\r\n\t\tvirtual bool connect() = 0;\r\n\t\tvirtual void disconnect() = 0;\r\n\t\tvirtual bool connected() const = 0;\r\n\t\tvirtual std::string getError() const = 0;\r\n\t\tvirtual void stopAllActivities() = 0;\r\n\t\tvirtual void waitEvent() = 0;\r\n\t\tvirtual bool waitEvent(int time) = 0;\r\n\t\tvirtual void waitAllTasks() = 0;\n\t\tvirtual bool waitAllTasks(int time) = 0;\n\t\tvirtual bool bodyExists(const std::string &name) const = 0;\r\n\t\tvirtual bool robotExists(const std::string &name) const = 0;\r\n\t\tvirtual std::vector<std::string> listBodies() const = 0;\r\n\t\tvirtual std::vector<std::string> listRobots() const = 0;\r\n\t\tvirtual std::vector<std::string> listItems() const = 0;\r\n\t\tvirtual IBody *getBody(const std::string &name) const = 0;\r\n\t\tvirtual IRobot *getRobot(const std::string &name) const = 0;\r\n\t\tvirtual ICanvas *getCanvas(const std::string &name) = 0;\r\n\t\tvirtual IMouse *getMouse() const = 0;\r\n\r\n\tprotected:\r\n\t\tint ref_count;\r\n\t};\r\n\r\n\r\n\tclass CPlayground\r\n\t{\r\n\tpublic:\r\n\t\tstatic double getProtocolVersion() { return IPlayground::getProtocolVersion(); }\r\n\t\t\r\n\t\tCPlayground() { iPlayground = IPlayground::create(); }\r\n\t\tCPlayground(const CPlayground &cPlayground) : iPlayground(cPlayground.iPlayground) {\r\n\t\t\tiPlayground->ref_count++;\r\n\t\t}\r\n\t\t~CPlayground() {\r\n\t\t\tif (--iPlayground->ref_count == 0)\r\n\t\t\t\tIPlayground::dispose(iPlayground);\r\n\t\t}\r\n\r\n\t\tCPlayground &operator=(const CPlayground &cPlayground) {\r\n\t\t\tif (--iPlayground->ref_count == 0)\r\n\t\t\t\tIPlayground::dispose(iPlayground);\r\n\t\t\tiPlayground = cPlayground.iPlayground;\r\n\t\t\tiPlayground->ref_count++;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tbool connect() { return iPlayground->connect(); }\r\n\t\tvoid disconnect() { iPlayground->disconnect(); }\r\n\t\tbool connected() const { return iPlayground->connected(); }\r\n\t\tstd::string getError() const { return iPlayground->getError(); }\r\n\t\tvoid stopAllActivities() { iPlayground->stopAllActivities(); }\r\n\t\tvoid waitEvent() { iPlayground->waitEvent(); }\r\n\t\tbool waitEvent(int time) { return iPlayground->waitEvent(time); }\r\n\t\tvoid waitAllTasks() { iPlayground->waitAllTasks(); }\r\n\t\tbool waitAllTasks(int time) { return iPlayground->waitAllTasks(time); }\n\t\tstd::vector<std::string> listBodies() const { return iPlayground->listBodies(); }\r\n\t\tstd::vector<std::string> listRobots() const { return iPlayground->listRobots(); }\r\n\t\tstd::vector<std::string> listItems() const { return iPlayground->listItems(); }\r\n\t\tCBody getBody(const std::string &name) const { return CBody(iPlayground->getBody(name)); }\r\n\t\tCRobot getRobot(const std::string &name) const { return CRobot(iPlayground->getRobot(name)); }\r\n\t\tCCanvas getCanvas(const std::string &name) { return CCanvas(iPlayground->getCanvas(name)); }\r\n\t\tCMouse getMouse() const { return CMouse(iPlayground->getMouse()); }\r\n\r\n\tprotected:\r\n\t\tCPlayground(IPlayground *iPlayground) : iPlayground(iPlayground) {\r\n\t\t\tiPlayground->ref_count++;\r\n\t\t}\r\n\t\tIPlayground *iPlayground;\r\n\t};\r\n}\r\n"
}
] | 10 |
skye/flax_bert | https://github.com/skye/flax_bert | 644b9b04fec2956b6a996ea148e2110400df5f10 | 3b40f4b978f16d3dde18547e1cd4aeaf71a76ee6 | 88fb3f497f950fcbb60dd986f22ef9c36b2e118d | refs/heads/master | 2023-01-22T19:02:18.542195 | 2020-12-06T02:29:09 | 2020-12-06T02:29:09 | 318,933,964 | 0 | 0 | null | 2020-12-06T02:28:26 | 2020-12-04T23:42:10 | 2020-12-04T23:42:08 | null | [
{
"alpha_fraction": 0.6110740303993225,
"alphanum_fraction": 0.6197465062141418,
"avg_line_length": 37.34418487548828,
"blob_id": "fdc4008da53141995c9815f75cbe7ce3992d1883",
"content_id": "f9d3e2c5593a09cff3daeed403d726ff7a7db8b5",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16489,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 430,
"path": "/data.py",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "# Copyright 2020 The FlaxBERT 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\"\"\"Huggingface input pipelines.\"\"\"\n\nimport datasets\nimport numpy as np\nimport random\nimport torch\nimport jax\n\n\nclass DataPipeline:\n def __init__(self, dataset):\n self.dataset = dataset\n\n def get_inputs(self, batch_size, split=None, training=False):\n dataloader = torch.utils.data.DataLoader(\n self.dataset[split],\n collate_fn=self.collate,\n batch_size=batch_size,\n drop_last=training,\n shuffle=training,\n num_workers=64,\n )\n if training:\n while True:\n for batch in iter(dataloader):\n yield dict(batch) # The dict-like types from huggingface datasets are not pytrees\n else:\n for batch in iter(dataloader):\n yield dict(batch) # The dict-like types from huggingface datasets are not pytrees\n\n def collate(self, examples):\n raise NotImplementedError(\"DataPipeline subclasess must define a collate function.\")\n\n\nclass ClassificationDataPipeline(DataPipeline):\n def __init__(self, dataset, tokenizer):\n self.tokenizer = tokenizer\n\n # shard train here already to avoid unnecessary tokenization.\n dataset['train'] = dataset['train'].shard(jax.host_count(), jax.host_id())\n\n if isinstance(dataset, dict):\n single_split = dataset['train']\n else:\n single_split = dataset\n\n name_a, *names_other = [\n name for name, feature in single_split.features.items()\n if feature.dtype=='string']\n assert len(names_other) <= 1, (\n 'Only single sentences and sentence pairs allowed.')\n if names_other:\n name_b = names_other[0]\n tokenize = lambda example: self.tokenizer(\n example[name_a], example[name_b], truncation=True)\n else:\n tokenize = lambda example: self.tokenizer(\n example[name_a], truncation=True)\n \n mapped_dataset = dataset.map(tokenize, batched=True)\n mapped_dataset.set_format('numpy', columns=[\n 'idx', 'input_ids', 'token_type_ids', 'attention_mask', 'label'])\n super().__init__(mapped_dataset)\n\n def collate(self, examples):\n return self.tokenizer.pad(\n examples,\n padding='max_length',\n max_length=self.tokenizer.model_max_length,\n return_tensors='np',\n )\n\n\nclass PretrainingDataPipeline(DataPipeline):\n FEATURE_NAMES = [\n 'attention_mask',\n 'input_ids',\n 'token_type_ids',\n 'next_sentence_label'\n ]\n\n def __init__(self, dataset, tokenizer,\n short_seq_prob=0.1,\n max_predictions_per_seq=80):\n self.tokenizer = tokenizer\n self.short_seq_prob = short_seq_prob\n self.max_predictions_per_seq = max_predictions_per_seq\n\n cache_file_name=(\n f\"cache/\"\n f\"pretrain_new_l{self.tokenizer.model_max_length}\"\n f\"_s{self.short_seq_prob}\"\n f\"_p{self.max_predictions_per_seq}\"\n f\".arrow\")\n\n mapped_dataset = dataset.map(\n self.examples_from_documents, batched=True,\n remove_columns=dataset.column_names,\n cache_file_name=cache_file_name,\n num_proc=32,\n features=datasets.Features(\n attention_mask=datasets.features.Sequence(\n datasets.features.Value(dtype='int8'), length=-1),\n input_ids=datasets.features.Sequence(\n datasets.features.Value(dtype='int16'), length=-1),\n token_type_ids=datasets.features.Sequence(\n datasets.features.Value(dtype='int8'), length=-1),\n next_sentence_label=datasets.features.Value(dtype='int8'),\n ),\n fn_kwargs=dict(\n rng=random.Random(0),\n ))\n mapped_dataset.set_format('numpy')\n\n super().__init__(mapped_dataset)\n\n def collate(self, examples):\n examples = self.tokenizer.pad(\n examples,\n padding='max_length',\n max_length=self.tokenizer.model_max_length,\n return_tensors='np',\n )\n\n ignore_ids = np.array([\n self.tokenizer.cls_token_id,\n self.tokenizer.sep_token_id,\n self.tokenizer.pad_token_id\n ], dtype=np.int64)[:, None]\n\n batch_size = examples['input_ids'].shape[0]\n examples['input_ids'] = examples['input_ids'].copy()\n examples['masked_lm_positions'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.int64)\n examples['masked_lm_ids'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.int64)\n examples['masked_lm_weights'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.float32)\n for i in range(batch_size):\n prediction_mask = np.all(examples['input_ids'][i] != ignore_ids, axis=0)\n num_tokens = np.sum(examples['attention_mask'][i]).item()\n cand_indexes = np.arange(\n prediction_mask.shape[0], dtype=np.int32)[prediction_mask]\n num_to_predict = min(\n self.max_predictions_per_seq, max(1, int(num_tokens * 0.15)))\n\n masked_lm_positions = np.random.choice(\n cand_indexes, num_to_predict, replace=False)\n masked_lm_positions = np.sort(masked_lm_positions)\n input_ids = examples['input_ids'][i].copy()\n masked_lm_ids = input_ids[masked_lm_positions]\n\n input_ids[masked_lm_positions] = np.where(\n np.random.random(len(masked_lm_ids)) < 0.8,\n # 80% of the time, replace with [MASK]\n self.tokenizer.mask_token_id,\n np.where(np.random.random(len(masked_lm_ids)) < 0.5,\n # 10% of the time, keep original\n masked_lm_ids,\n # 10% of the time, replace with random word\n np.random.randint(0, self.tokenizer.vocab_size, masked_lm_ids.shape)))\n examples['input_ids'][i, :] = input_ids\n\n examples['masked_lm_positions'][i, :num_to_predict] = masked_lm_positions\n examples['masked_lm_ids'][i, :num_to_predict] = masked_lm_ids\n examples['masked_lm_weights'][i, :num_to_predict] = 1.0\n\n return examples\n\n def examples_from_documents(self, documents, rng):\n max_seq_length = self.tokenizer.model_max_length\n # Account for [CLS], [SEP], [SEP]\n max_num_tokens = max_seq_length - 3\n\n instances = []\n for text in documents['document']:\n document = [\n self.tokenizer.encode(line, add_special_tokens=False)\n for line in text\n ]\n\n # We *usually* want to fill up the entire sequence since we are padding\n # to `max_seq_length` anyways, so short sequences are generally wasted\n # computation. However, we *sometimes*\n # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter\n # sequences to minimize the mismatch between pre-training and fine-tuning.\n # The `target_seq_length` is just a rough target however, whereas\n # `max_seq_length` is a hard limit.\n target_seq_length = max_num_tokens\n if rng.random() < self.short_seq_prob:\n target_seq_length = rng.randint(2, max_num_tokens)\n\n # We DON'T just concatenate all of the tokens from a document into a long\n # sequence and choose an arbitrary split point because this would make the\n # next sentence prediction task too easy. Instead, we split the input into\n # segments \"A\" and \"B\" based on the actual \"sentences\" provided by the user\n # input.\n current_chunk = []\n current_length = 0\n i = 0\n while i < len(document):\n segment = document[i]\n current_chunk.append(segment)\n current_length += len(segment)\n if i == len(document) - 1 or current_length >= target_seq_length:\n if current_chunk:\n # `a_end` is how many segments from `current_chunk` go into the `A`\n # (first) sentence.\n a_end = 1\n if len(current_chunk) >= 2:\n a_end = rng.randint(1, len(current_chunk) - 1)\n\n tokens_a = []\n for j in range(a_end):\n tokens_a.extend(current_chunk[j])\n\n tokens_b = []\n # Random next\n is_random_next = False\n if len(current_chunk) == 1:\n continue # XXX\n elif rng.random() < 0.5:\n is_random_next = True\n for j in range(a_end, len(current_chunk)):\n tokens_b.extend(current_chunk[j])\n # Note(mingdachen): in this case, we just swap tokens_a and tokens_b\n tokens_a, tokens_b = tokens_b, tokens_a\n # Actual next\n else:\n is_random_next = False\n for j in range(a_end, len(current_chunk)):\n tokens_b.extend(current_chunk[j])\n\n tokens_a, tokens_b, _ = self.tokenizer.truncate_sequences(\n tokens_a, tokens_b, max(0, len(tokens_a) + len(tokens_b) - max_num_tokens))\n instance = self.tokenizer.prepare_for_model(tokens_a, tokens_b)\n if any(token not in self.tokenizer.all_special_ids for token in instance['input_ids']):\n # Don't add instances that consist entirely of UNK tokens\n instances.append(instance)\n instance['next_sentence_label'] = int(is_random_next)\n current_chunk = []\n current_length = 0\n i += 1\n\n return {k: [instance[k] for instance in instances] for k in self.FEATURE_NAMES}\n\n\nclass PretrainingDataPipelineV1(DataPipeline):\n FEATURE_NAMES = [\n 'attention_mask',\n 'input_ids',\n 'token_type_ids',\n 'next_sentence_label'\n ]\n\n def __init__(self, dataset, tokenizer,\n short_seq_prob=0.1,\n max_predictions_per_seq=80):\n self.tokenizer = tokenizer\n self.short_seq_prob = short_seq_prob\n self.max_predictions_per_seq = max_predictions_per_seq\n\n cache_file_name=(\n f\"cache/\"\n f\"pretrain_l{self.tokenizer.model_max_length}\"\n f\"_s{self.short_seq_prob}\"\n f\"_p{self.max_predictions_per_seq}\"\n f\".arrow\")\n\n mapped_dataset = dataset.map(\n self.examples_from_documents, batched=True,\n remove_columns=dataset.column_names,\n cache_file_name=cache_file_name,\n num_proc=32,\n features=datasets.Features(\n attention_mask=datasets.features.Sequence(\n datasets.features.Value(dtype='int8'), length=-1),\n input_ids=datasets.features.Sequence(\n datasets.features.Value(dtype='int16'), length=-1),\n token_type_ids=datasets.features.Sequence(\n datasets.features.Value(dtype='int8'), length=-1),\n next_sentence_label=datasets.features.Value(dtype='int8'),\n ),\n fn_kwargs=dict(\n rng=random.Random(0),\n ))\n mapped_dataset.set_format('numpy')\n\n super().__init__(mapped_dataset)\n\n def collate(self, examples):\n examples = self.tokenizer.pad(\n examples,\n padding='max_length',\n max_length=self.tokenizer.model_max_length,\n return_tensors='np',\n )\n\n ignore_ids = np.array([\n self.tokenizer.cls_token_id,\n self.tokenizer.sep_token_id,\n self.tokenizer.pad_token_id\n ], dtype=np.int64)[:, None]\n\n batch_size = examples['input_ids'].shape[0]\n examples['input_ids'] = examples['input_ids'].copy()\n examples['masked_lm_positions'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.int64)\n examples['masked_lm_ids'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.int64)\n examples['masked_lm_weights'] = np.zeros((batch_size, self.max_predictions_per_seq), dtype=np.float32)\n for i in range(batch_size):\n prediction_mask = np.all(examples['input_ids'][i] != ignore_ids, axis=0)\n num_tokens = np.sum(examples['attention_mask'][i]).item()\n cand_indexes = np.arange(\n prediction_mask.shape[0], dtype=np.int32)[prediction_mask]\n num_to_predict = min(\n self.max_predictions_per_seq, max(1, int(num_tokens * 0.15)))\n\n masked_lm_positions = np.random.choice(\n cand_indexes, num_to_predict, replace=False)\n masked_lm_positions = np.sort(masked_lm_positions)\n input_ids = examples['input_ids'][i].copy()\n masked_lm_ids = input_ids[masked_lm_positions]\n\n input_ids[masked_lm_positions] = np.where(\n np.random.random(len(masked_lm_ids)) < 0.8,\n # 80% of the time, replace with [MASK]\n self.tokenizer.mask_token_id,\n np.where(np.random.random(len(masked_lm_ids)) < 0.5,\n # 10% of the time, keep original\n masked_lm_ids,\n # 10% of the time, replace with random word\n np.random.randint(0, self.tokenizer.vocab_size, masked_lm_ids.shape)))\n examples['input_ids'][i, :] = input_ids\n\n examples['masked_lm_positions'][i, :num_to_predict] = masked_lm_positions\n examples['masked_lm_ids'][i, :num_to_predict] = masked_lm_ids\n examples['masked_lm_weights'][i, :num_to_predict] = 1.0\n\n return examples\n\n def examples_from_documents(self, documents, rng):\n max_seq_length = self.tokenizer.model_max_length\n # Account for [CLS], [SEP], [SEP]\n max_num_tokens = max_seq_length - 3\n\n instances = []\n for text in documents['text']:\n document = [\n self.tokenizer.encode(\n line.strip().replace(\"\\n\", \" \").replace(\"()\",\"\"),\n add_special_tokens=False)\n for line in text.splitlines()\n if line.strip() and len(line) >= 80\n ]\n\n # We *usually* want to fill up the entire sequence since we are padding\n # to `max_seq_length` anyways, so short sequences are generally wasted\n # computation. However, we *sometimes*\n # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter\n # sequences to minimize the mismatch between pre-training and fine-tuning.\n # The `target_seq_length` is just a rough target however, whereas\n # `max_seq_length` is a hard limit.\n target_seq_length = max_num_tokens\n if rng.random() < self.short_seq_prob:\n target_seq_length = rng.randint(2, max_num_tokens)\n\n # We DON'T just concatenate all of the tokens from a document into a long\n # sequence and choose an arbitrary split point because this would make the\n # next sentence prediction task too easy. Instead, we split the input into\n # segments \"A\" and \"B\" based on the actual \"sentences\" provided by the user\n # input.\n current_chunk = []\n current_length = 0\n i = 0\n while i < len(document):\n segment = document[i]\n current_chunk.append(segment)\n current_length += len(segment)\n if i == len(document) - 1 or current_length >= target_seq_length:\n if current_chunk:\n # `a_end` is how many segments from `current_chunk` go into the `A`\n # (first) sentence.\n a_end = 1\n if len(current_chunk) >= 2:\n a_end = rng.randint(1, len(current_chunk) - 1)\n\n tokens_a = []\n for j in range(a_end):\n tokens_a.extend(current_chunk[j])\n\n tokens_b = []\n # Random next\n is_random_next = False\n if len(current_chunk) == 1:\n continue # XXX\n elif rng.random() < 0.5:\n is_random_next = True\n for j in range(a_end, len(current_chunk)):\n tokens_b.extend(current_chunk[j])\n # Note(mingdachen): in this case, we just swap tokens_a and tokens_b\n tokens_a, tokens_b = tokens_b, tokens_a\n # Actual next\n else:\n is_random_next = False\n for j in range(a_end, len(current_chunk)):\n tokens_b.extend(current_chunk[j])\n\n tokens_a, tokens_b, _ = self.tokenizer.truncate_sequences(\n tokens_a, tokens_b, max(0, len(tokens_a) + len(tokens_b) - max_num_tokens))\n instance = self.tokenizer.prepare_for_model(tokens_a, tokens_b)\n if any(token not in self.tokenizer.all_special_ids for token in instance['input_ids']):\n # Don't add instances that consist entirely of UNK tokens\n instances.append(instance)\n instance['next_sentence_label'] = int(is_random_next)\n current_chunk = []\n current_length = 0\n i += 1\n\n return {k: [instance[k] for instance in instances] for k in self.FEATURE_NAMES}\n\n"
},
{
"alpha_fraction": 0.6059701442718506,
"alphanum_fraction": 0.7402985095977783,
"avg_line_length": 26.91666603088379,
"blob_id": "871ebb18dbcdab4eaace6a9dfb34c794c495e244",
"content_id": "5fd41a256458033cd8ad26953397593beda1d7c9",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 335,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 12,
"path": "/requirements_tpu.txt",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "datasets==1.1.2\nflax==0.2.2\njax==0.2.6\nml-collections==0.1.0\ntokenizers==0.9.3\ntransformers==3.5.1\njupyter==1.0.0\nhttps://storage.googleapis.com/jax-releases/tpu/jaxlib-0.1.55+tpu-cp36-none-manylinux2010_x86_64.whl\n--find-links https://download.pytorch.org/whl/torch_stable.html\ntorch==1.6.0+cpu\ntensorflow==2.3.1\nscikit-learn==0.23.2\n"
},
{
"alpha_fraction": 0.6929949522018433,
"alphanum_fraction": 0.6992893218994141,
"avg_line_length": 29.583850860595703,
"blob_id": "8eaeb0190c71352f5db7d6920917e2ac019cbc53",
"content_id": "161911309053b22e1203768d902148675039631a",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4925,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 161,
"path": "/demo_lib.py",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "import os\nimport jax\nimport jax.numpy as jnp\nimport flax\n\n# We use HuggingFace's tokenizer and input pipeline.\nimport transformers\nimport datasets\nimport numpy as np\n\n# We use the Flax model.\nimport data\nimport modeling as flax_models\nimport training\n\nos.environ['TOKENIZERS_PARALLELISM'] = 'true'\n\nimport ml_collections\n\nimport transformers\n\nimport import_weights\nfrom flax import nn\nfrom flax import optim\n\n# from tensorflow.io import gfile\n\nfrom transformers import BertTokenizerFast\n\nimport time\n\nimport functools\n\ndef get_config(init_checkpoint, dataset):\n hf_config = transformers.AutoConfig.from_pretrained(init_checkpoint)\n model_config = ml_collections.ConfigDict({\n 'vocab_size': hf_config.vocab_size,\n 'hidden_size': hf_config.hidden_size,\n 'num_hidden_layers': hf_config.num_hidden_layers,\n 'num_attention_heads': hf_config.num_attention_heads,\n 'hidden_act': hf_config.hidden_act,\n 'intermediate_size': hf_config.intermediate_size,\n 'hidden_dropout_prob': hf_config.hidden_dropout_prob,\n 'attention_probs_dropout_prob': hf_config.attention_probs_dropout_prob,\n 'max_position_embeddings': hf_config.max_position_embeddings,\n 'type_vocab_size': hf_config.type_vocab_size,\n })\n is_regression_task = (\n dataset['train'].features['label'].dtype == 'float32')\n if is_regression_task:\n num_classes = 1\n else:\n num_classes = dataset['train'].features['label'].num_classes\n config = ml_collections.ConfigDict({\n 'init_checkpoint': init_checkpoint,\n 'tokenizer': init_checkpoint,\n 'model': model_config,\n 'warmup_proportion': 0.1,\n 'max_seq_length': 128,\n 'num_classes': num_classes\n })\n return config\n\n\ndef import_pretrained_params(config):\n return import_weights.load_params(\n init_checkpoint=config.init_checkpoint,\n hidden_size=config.model.hidden_size,\n num_attention_heads=config.model.num_attention_heads,\n num_classes=config.num_classes)\n\n\ndef create_model(config, initial_params):\n model_kwargs = dict(\n config=config.model,\n n_classes=config.num_classes,\n )\n model_def = flax_models.BertForSequenceClassification.partial(**model_kwargs)\n model = nn.Model(model_def, initial_params)\n return model\n\n\ndef create_optimizer(config, model, initial_params):\n \"\"\"Create a model, starting with a pre-trained checkpoint.\"\"\"\n common_kwargs = dict(\n learning_rate=config.learning_rate,\n beta1=0.9,\n beta2=0.999,\n eps=1e-6,\n )\n optimizer_decay_def = optim.Adam(\n weight_decay=0.01, **common_kwargs)\n optimizer_no_decay_def = optim.Adam(\n weight_decay=0.0, **common_kwargs)\n decay = optim.ModelParamTraversal(lambda path, _: 'bias' not in path)\n no_decay = optim.ModelParamTraversal(lambda path, _: 'bias' in path)\n optimizer_def = optim.MultiOptimizer(\n (decay, optimizer_decay_def), (no_decay, optimizer_no_decay_def))\n # TODO(marcvanzee): MultiOptimizer triggers double XLA compilation on TPU so\n # we use Adam here, but we should investigate why this happens.\n optimizer_def = optim.Adam(learning_rate=config.learning_rate)\n optimizer = optimizer_def.create(model)\n optimizer = optimizer.replicate()\n del model # don't keep a copy of the initial model\n return optimizer\n\n\ndef get_num_train_steps(config, data_pipeline):\n num_train_examples = len(data_pipeline.dataset['train'])\n print(f'Num train examples: {num_train_examples}')\n num_train_steps = int(\n num_train_examples * config.num_train_epochs // config.train_batch_size)\n return num_train_steps\n\n\ndef get_learning_rate_fn(config, num_train_steps):\n warmup_steps = int(config.warmup_proportion * num_train_steps)\n cooldown_steps = num_train_steps - warmup_steps\n learning_rate_fn = training.create_learning_rate_scheduler(\n factors='constant * linear_warmup * linear_decay',\n base_learning_rate=config.learning_rate,\n warmup_steps=warmup_steps,\n steps_per_cycle=cooldown_steps,\n )\n return learning_rate_fn\n\n\ndef compute_loss_and_metrics(model, batch, rng):\n \"\"\"Compute cross-entropy loss for classification tasks.\"\"\"\n with nn.stochastic(rng):\n metrics = model(\n batch['input_ids'],\n (batch['input_ids'] > 0).astype(np.int32),\n batch['token_type_ids'],\n batch['label'])\n return metrics['loss'], metrics\n\n\ndef compute_classification_stats(model, batch):\n with nn.stochastic(jax.random.PRNGKey(0)):\n y = model(\n batch['input_ids'],\n (batch['input_ids'] > 0).astype(np.int32),\n batch['token_type_ids'],\n deterministic=True)\n return {\n 'idx': batch['idx'],\n 'label': batch['label'],\n 'prediction': y.argmax(-1)\n }\n\n\ndef get_validation_splits(dataset_name):\n if dataset_name == 'mnli':\n return ['validation_matched', 'validation_mismatched']\n else:\n return ['validation']\n\n\ndef get_prefix(split):\n return 'eval_mismatched' if split == 'validation_mismatched' else 'eval' \n"
},
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.6971153616905212,
"avg_line_length": 16.25,
"blob_id": "57e86aec9d1fb5e130875c54ed6117406634de0b",
"content_id": "1dde9fb39490f6f66fbbb45b767b505c3f693604",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 208,
"license_type": "permissive",
"max_line_length": 40,
"num_lines": 12,
"path": "/test.py",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "# General imports.\nimport os\nimport time\nimport jax\nimport jax.profiler\nserver = jax.profiler.start_server(9999)\nprint('started profiler')\n\ny = 9\nfor _ in range(200):\n for x in range(300000):\n y = x * 2\n\n"
},
{
"alpha_fraction": 0.5102040767669678,
"alphanum_fraction": 0.6938775777816772,
"avg_line_length": 15.5,
"blob_id": "a7e66739da4e9a4373b872e3fd51bf8bd00ccd64",
"content_id": "94e577d2e14101b7e89c99d84004e62c49b22e33",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 98,
"license_type": "permissive",
"max_line_length": 21,
"num_lines": 6,
"path": "/requirements_gpu.txt",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "datasets==1.1.2\nflax==0.2.2\njax==0.2.6\nml-collections==0.1.0\ntokenizers==0.9.3\ntransformers==3.5.1"
},
{
"alpha_fraction": 0.7637240290641785,
"alphanum_fraction": 0.7741097807884216,
"avg_line_length": 61.69767379760742,
"blob_id": "0ef8a527442d9ee606f874848ce0eb25c9c6dbd8",
"content_id": "8c6f5d21acdb0d7ef7c9b739b14d954babcec2e8",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2696,
"license_type": "permissive",
"max_line_length": 351,
"num_lines": 43,
"path": "/README.md",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "# BERT in Flax\n\n***NOTE: This implementation is work in progress!***\n\nAn implementation of BERT in JAX+Flax. Runs on CPU, GPU, and TPU (single-host only for now, e.g. `TPUv3-8`).\n\n## Fine-tuning on GLUE\n\nSample command for fine-tuning on GLUE:\n\n```sh\npython3 run_classifier.py --config=configs/classifier.py:bert-base-uncased --config.dataset_name=\"cola\"\n```\n\nThe `dataset_name` should be one of: `cola`, `mrpc`, `qqp`, `sst2`, `stsb`, `mnli`, `qnli`, `rte`. WNLI is not supported because BERT accuracy on WNLI is below the baseline, unless a special training recipe is used.\n\nA pre-trained BERT model hosted via the [transformers](https://github.com/huggingface/transformers) model hub may be selected by replacing `bert-base-uncased` with another name, e.g. `--config=configs/classifier.py:bert-large-uncased`.\n\nYou may also specify the tokenizer and checkpoint location separately. Use this method to load JAX checkpoints pre-trained using this codebase, as well as HuggingFace PyTorch checkpoints saved via `save_pretrained`:\n```\n--config=configs/classifier.py \n--config.tokenizer=\"bert-base-uncased\"\n--config.init_checkpoint=\"/path/to/model/dir\"\n```\n\n## Pre-training\n\nTo pre-train BERT, first modify `run_pretraining.py` (around line 213) to point to the location of BERT training data in text format.\n\nThen run a command like:\n```sh\npython3 run_pretraining.py --config=configs/pretraining.py:bert-base-uncased --config.init_checkpoint=\"\"\n```\n\n***Remember to specify a blank initial checkpoint as a hyperparameter. Otherwise, pre-training will resume from the already-trained bert-base-uncased checkpoint.***\n\nIf you do not have your own BERT training data, you can edit `run_pretraining.py` to comment out the data pipeline around lines 211-217, and uncomment lines 198-201 instead. This will switch to a reproducible data pipeline based on public data sources (Wikipedia), but we provide no guarantees that this pipeline will lead to good pre-trained models.\n\nKnown differences from the original BERT code:\n* There is no publicly-available data pipeline for replicating BERT. I hope to eventually use the HuggingFace datasets library to provide an at least somewhat reasonable approximation.\n* The next-sentence prediction (NSP) task from BERT is replaced with a sentence order prediction (SOP) from ALBERT. This is to make the data pipeline simpler and more parallelizable.\n* BERT's Adam optimizer departs from the Adam paper in that it omits bias correction terms. This codebase uses Flax's implementation of Adam, which includes bias correction.\n* Pre-training uses a fixed maximum sequence length of 128, and does not increase the sequence length to 512 for the last 10% of training.\n"
},
{
"alpha_fraction": 0.7341597676277161,
"alphanum_fraction": 0.7396694421768188,
"avg_line_length": 34.85185241699219,
"blob_id": "a040fcac51d8d1faea30babe691c0adf1cd7b2fd",
"content_id": "5a9b2f41fc95e98ca61addc478c4ae7cd17a0e9d",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2904,
"license_type": "permissive",
"max_line_length": 167,
"num_lines": 81,
"path": "/demo.py",
"repo_name": "skye/flax_bert",
"src_encoding": "UTF-8",
"text": "# General imports.\nimport os\nimport jax\nimport jax.numpy as jnp\nimport flax\n\n# Huggingface datasets and transformers libraries.\nimport datasets\nfrom transformers import BertTokenizerFast\n\n# flax_bert-specific imports.\nfrom flax import optim\nimport data\nimport modeling as flax_models\nimport training\nfrom demo_lib import get_config, get_validation_splits, get_prefix, import_pretrained_params, create_model, create_optimizer, get_num_train_steps, get_learning_rate_fn\n\nos.environ['TOKENIZERS_PARALLELISM'] = 'true'\n\ntrain_settings = {\n 'train_batch_size': 32,\n 'eval_batch_size': 8,\n 'learning_rate': 5e-5,\n 'num_train_epochs': 3,\n 'dataset_path': 'glue',\n 'dataset_name': 'mrpc' # ['cola', 'mrpc', 'sst2', 'stsb', 'qnli', 'rte']\n}\n\n# Load the GLUE task.\ndataset = datasets.load_dataset('glue', train_settings['dataset_name'])\n\n# Get pre-trained config and update it with the train configuration.\nconfig = get_config('bert-base-uncased', dataset)\nconfig.update(train_settings)\n\n# Load HuggingFace tokenizer and data pipeline.\ntokenizer = BertTokenizerFast.from_pretrained(config.tokenizer)\ndata_pipeline = data.ClassificationDataPipeline(dataset, tokenizer)\n\n# Create Flax model and optimizer.\npretrained_params = import_pretrained_params(config)\nmodel = create_model(config, pretrained_params)\noptimizer = create_optimizer(config, model, pretrained_params)\n\n# Setup tokenizer, train step function and train iterator.\ntokenizer.model_max_length = config.max_seq_length\nnum_train_steps = get_num_train_steps(config, data_pipeline)\n\nlearning_rate_fn = get_learning_rate_fn(config, num_train_steps)\ntrain_history = training.TrainStateHistory(learning_rate_fn)\ntrain_state = train_history.initial_state()\n\ntrain_step_fn = training.create_train_step(clip_grad_norm=1.0)\ntrain_iter = data_pipeline.get_inputs(\n split='train', batch_size=config.train_batch_size, training=True)\n\n# Run training.\nprint(f'\\nStarting training on {config.dataset_name} for {num_train_steps} '\n f'steps ({config.num_train_epochs:.0f} epochs)...\\n')\n\nfor step, batch in zip(range(0, num_train_steps), train_iter):\n optimizer, train_state = train_step_fn(optimizer, batch, train_state)\n if step % 10 == 0:\n print(f'step {step}/{num_train_steps}')\n\nprint('\\nTraining finished! Running eval...\\n')\n\n# Run eval.\neval_step = training.create_eval_fn()\n\nfor split in get_validation_splits(config.dataset_name):\n eval_iter = data_pipeline.get_inputs(\n split='validation', batch_size=config.eval_batch_size, training=False)\n eval_stats = eval_step(optimizer, eval_iter)\n eval_metric = datasets.load_metric(config.dataset_path, config.dataset_name)\n eval_metric.add_batch(\n predictions=eval_stats['prediction'],\n references=eval_stats['label'])\n eval_metrics = eval_metric.compute()\n for name, val in sorted(eval_metrics.items()):\n print(f'{get_prefix(split)}_{name} = {val:.06f}', flush=True)\n"
}
] | 7 |
lexanne-online/csv-to-md-personal | https://github.com/lexanne-online/csv-to-md-personal | fd081ac7b399b18194de38f7d81c2b321799030d | 6de08f951b8e75357669f14c4b16234b064ac6eb | 06e1296af8661378c872f3aad9e9a4ebfa8fc89c | refs/heads/main | 2023-04-28T07:06:54.809990 | 2021-05-15T20:50:09 | 2021-05-15T20:50:09 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5349401235580444,
"alphanum_fraction": 0.5388224124908447,
"avg_line_length": 39.940399169921875,
"blob_id": "424122b6856495f97fd090cd3cf6c22f7afbc8eb",
"content_id": "f47bacc29375386d56a46cad24b03ebbd81708be",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6182,
"license_type": "permissive",
"max_line_length": 196,
"num_lines": 151,
"path": "/settings.py",
"repo_name": "lexanne-online/csv-to-md-personal",
"src_encoding": "UTF-8",
"text": "import pprint\n\n# this class is for setting the default settings\nclass Settings:\n\n def __init__(self):\n self.current_settings = {}\n self.availableSettings = \"\"\"\n n = no formatting\n wl = wikilink\n ml = markdown link\n hl = highlight\n it = italics\n bo = bold\n st = strike-through\n co = inline code\n cb = code block\n h1 = heading 1\n h2 = heading 2\n h3 = heading 3\n h4 = heading 4\n h5 = heading 5\n h6 = heading 6\n wlem = wiki link embed\n mlem = markdown link embed\n ul = unordered list\n ol = ordered list\n bq = block quote\n ut = unchecked task\n ct = checked task\n ma = inline math\n mb = math block\n oc = obsidian comments\n ta = tag\n \"\"\"\n\n self.availableSettingsList = [\"n\", \"wl\", \"ml\", \"hl\", \"it\", \"bo\", \"st\", \"co\", \"cb\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"wlem\", \"mlem\", \"ul\", \"ol\", \"bq\", \"ut\", \"ct\", \"ma\", \"mb\", \"oc\", \"ta\"]\n\n\n def setGeneralSettings(self):\n\n print(\"\"\"\nIf you choose to add frontmatter YAML, you cannot add inline YAML.\\n\\\nYour choice for inline YAML will have now effect in that case.\\n\\\nIf you only want to have inline YAML, select no for fronmatter YAML and yes for inline YAML.\\n\\\nWhen you select yes for inline YAML, only inline YAML will be added to the file (but the values\\n\\\nwill be with Markdown formatting).\n \"\"\")\n\n # checks if the user wants to add the contents as YAML metadata\n while True: \n addYAML = input(\"Do you want to have all the entries as frontmatter YAML metadata? Enter \\\"y\\\" for yes and \\\"n\\\" for no: \")\n addYAML = addYAML.lower().strip()\n if addYAML != \"y\" and addYAML != \"n\":\n print(\"You didn't enter \\\"y\\\" or \\\"n\\\"\")\n elif addYAML == \"y\":\n self.current_settings[\"addYAML\"] = \"y\"\n break\n elif addYAML == \"n\":\n self.current_settings[\"addYAML\"] = \"n\"\n break\n \n # checks if the user wants to add the contents as inline YAML\n while True: \n inlineYAML = input(\"Do you want to have all the entries as inline YAML? Enter \\\"y\\\" for yes and \\\"n\\\" for no: \")\n inlineYAML = inlineYAML.lower().strip()\n if inlineYAML != \"y\" and inlineYAML != \"n\":\n print(\"You didn't enter \\\"y\\\" or \\\"n\\\"\")\n elif inlineYAML == \"y\":\n self.current_settings[\"inlineYAML\"] = \"y\"\n break\n elif inlineYAML == \"n\":\n self.current_settings[\"inlineYAML\"] = \"n\"\n break\n \n # set the delimiter\n while True: \n delimiter = input(\"What delimiter do your CSV files have? (tab, comma, semicolon, colon, pipe, space) \")\n delimiter = delimiter.lower().strip()\n if delimiter != \"tab\" and delimiter != \"comma\" and delimiter != \"semicolon\" and delimiter != \"colon\" and delimiter != \"pipe\" and delimiter != \"space\":\n print(\"You didn't enter a valid delimiter\")\n elif delimiter == \"tab\":\n self.current_settings[\"delimiter\"] = \"\\t\"\n break\n elif delimiter == \"comma\":\n self.current_settings[\"delimiter\"] = \",\"\n break\n elif delimiter == \"semicolon\":\n self.current_settings[\"delimiter\"] = \";\"\n break\n elif delimiter == \"colon\":\n self.current_settings[\"delimiter\"] = \":\"\n break\n elif delimiter == \"pipe\":\n self.current_settings[\"delimiter\"] = \"|\"\n break\n elif delimiter == \"space\":\n self.current_settings[\"delimiter\"] = \" \"\n break\n\n while True: \n fileNameLength = input(\"How long should the file name be at maximum? Please enter a number. This excludes the .md ending. \")\n fileNameLength = fileNameLength.strip()\n try:\n fileNameLength = int(fileNameLength)\n self.current_settings[\"fileNameLength\"] = fileNameLength\n break\n except:\n print(\"The length was not an integer. Please try again.\")\n\n while True: \n print(\"\"\"\nFrom which column should the file name be generated?\\n\\\nThe program will prompt you for multiple columns. Input all the columns you wish to choose as file name.\\n\\\nWhen you want to stop, just input \\\"n\\\". If you entered multiple columns, it will then prompt you for a separator.\\n\\\n(The first column has the number 1)\n\"\"\")\n fileNameCol:list = []\n colCounter:int = 1\n while True:\n col:str = input(f\"Please enter the {colCounter}. column from which the file name should be generated \")\n try:\n col = int(col)\n colCounter += 1\n fileNameCol.append(col - 1)\n except:\n if col.lower().strip() == \"n\":\n break\n else:\n print(\"You did not enter a valid column number. Please try again.\")\n\n self.current_settings[\"fileNameCol\"] = fileNameCol\n\n fileNameColSeparator:str = \"\"\n if len(fileNameCol) > 1:\n fileNameColSeparator = input(\"Please enter the separator (including spaces; any illegal characters will be removed) \")\n self.current_settings[\"fileNameColSeparator\"] = fileNameColSeparator\n break\n \n # to this the formattings of each column will be added\n self.current_settings[\"column\"] = {}\n \n # returns the inputted settings so that they can be loaded by .choices() of GetInput class\n return self.current_settings\n\n\n\n def saveSettings(self, settings):\n name = input(\"Which name should your saved settings have? \")\n with open(\"saved_settings.py\", \"a\", encoding='utf-8') as f:\n f.write(f\"{name.lower()} = \" + pprint.pformat(settings) + \"\\n\\n\")\n"
},
{
"alpha_fraction": 0.4813971519470215,
"alphanum_fraction": 0.4832864999771118,
"avg_line_length": 51.92820358276367,
"blob_id": "f68d8df5f026b0688de854c1f3ea5cd419d0fe75",
"content_id": "b25e62b4d72970b36b9271bf92d440054605eaf3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20642,
"license_type": "permissive",
"max_line_length": 159,
"num_lines": 390,
"path": "/csv_to_md-file.py",
"repo_name": "lexanne-online/csv-to-md-personal",
"src_encoding": "UTF-8",
"text": "\nimport csv\nimport re\nfrom settings import Settings\nimport os\n\nif os.path.isfile(\"saved_settings.py\"):\n print(\"saved_settings.py is already present\")\nelse:\n with open(\"saved_settings.py\", \"w\", encoding='utf-8') as f:\n f.write( \"\\\"\\\"\\\"This is your settings file.\\\"\\\"\\\"\\n\\n\")\n\nfrom saved_settings import *\n\nclass GetInput:\n def __init__(self):\n self.settings:dict = {}\n\n\n def choices(self):\n # check if the user wants to load settings\n self.loadSettings:str = \"\"\n while True:\n self.loadSettings = input(\"Do you want to load saved settings? Enter \\\"y\\\" for yes and \\\"n\\\" for no: \")\n self.loadSettings = self.loadSettings.lower().strip()\n if self.loadSettings == \"y\":\n choice = input(\"Which settings do you want to choose? Please enter the name of the dictionary in saved_settings.py: \")\n choice = choice.lower().strip()\n # this will load the dictionary from saved_settings.py to the current settings\n # this works because we import everything from saved_settings\n self.settings = eval(choice)\n print(f\"These are your selected settings: {self.settings}\")\n break\n elif self.loadSettings == \"n\":\n instantiateSettings = Settings()\n # set the settings and load them\n # it calls the setGeneralSettings method in settings.py and lets the user choose all\n # the settings which are not related to the formatting of the content\n generalSettings = instantiateSettings.setGeneralSettings()\n self.settings = generalSettings\n print(f\"These are your current general settings: {self.settings}\")\n break\n self.mdChoices()\n\n\n def mdChoices(self):\n if self.settings[\"addYAML\"] == \"y\":\n # instantiate ReadCreate for reading the CSV files\n instanceFile = ReadCreate(self.settings, True)\n if self.loadSettings == \"n\":\n print(\"Now you will set the formatting for all of the columns one by one.\")\n instanceFile.getCellSettings()\n instanceFile.getYamlKeys()\n # creates the md files\n instanceFile.makeMdFiles()\n elif self.settings[\"inlineYAML\"] == \"y\":\n # instantiate ReadCreate for reading the CSV files\n instanceFile = ReadCreate(self.settings, False, True)\n if self.loadSettings == \"n\":\n print(\"Now you will set the formatting for all of the columns one by one.\")\n instanceFile.getCellSettings()\n instanceFile.getYamlKeys()\n # creates the md files\n instanceFile.makeMdFiles()\n else:\n # instantiates the ReadCreate class and finds the csv files\n instanceFile = ReadCreate(self.settings, False)\n if self.loadSettings == \"n\":\n print(\"Now you will set the formatting for all of the columns one by one.\")\n instanceFile.getCellSettings()\n # creates the md files\n instanceFile.makeMdFiles()\n \n\nclass ReadCreate:\n\n def __init__(self, settings:dict, yaml:bool=False, inlineyaml:bool=False):\n # will be populated with the contents of the first row of the first csv file as the values\n # the key is `yaml_keys`\n self.keyList:list = []\n self.yaml:bool = yaml\n self.inlineyaml:bool = inlineyaml\n self.csvFiles:list= [] \n # instantiate appSettings with the GetInput class to get access to the user settings\n self.settings = settings\n\n\n # find the csv files in the current working directory\n for dirpath, dirnames, files in os.walk(\".\"):\n #print(f\"Found directory: {dirnames}, located here:{dirpath}\")\n for file_name in files:\n if file_name.endswith(\".csv\"):\n normalised_path = os.path.normpath(dirpath + \"/\" + file_name)\n print(f\"Found file: {file_name}\")\n # append each found csv file to the list of csv files\n self.csvFiles.append(normalised_path)\n\n\n def getYamlKeys(self):\n self.keys:list = []\n with open(self.csvFiles[0], \"r\", encoding='utf-8') as csvFile:\n csvFileReader = csv.reader(csvFile, delimiter=self.settings[\"delimiter\"])\n for row in csvFileReader:\n # puts all of the keys for each file in a list\n # checks for the first row because that contains the names of the columns\n # should be redundant because I break after the first row anyway\n if csvFileReader.line_num == 1:\n # is needed to make sure that the list of all available options is only shown for the first column of the first row\n for el in range(len(row)):\n self.keys.append(row[el].replace(\" \", \"_\"))\n # break so that it doesn't loop again\n break\n\n def getCellSettings(self):\n # this method will add a key to self.settings \n # the key is \"column\", the value is a dictionary that contains the column in index form as its key\n # and the formatting as its value in a list\n # the first value is the formatting; if the cell in the csv file contains a list (multiple values that should get the\n # formatting individually), the second element is \"y\" for yes and the third the separator for the list\n\n # needed for showing and checking the chosen formatting option for each cell\n # needed for saving the entered settings\n addMdSetting = Settings()\n with open(self.csvFiles[0], \"r\", encoding='utf-8') as csvFile:\n csvFileReader = csv.reader(csvFile, delimiter=self.settings[\"delimiter\"])\n for row in csvFileReader:\n # checks for the first row because that contains the names of the columns\n # should be redundant because the first row is the first in the iterator and I break after the first row\n if csvFileReader.line_num == 1:\n # is needed to make sure that the list of all available options is only shown for the first column of the first row\n showOptions:int = 0\n for el in range(len(row)):\n\n # this indented part gets the settings for all of the columns\n # only set the settings for the first csv file (assume that the others follow the same scheme)\n cellFormatting:str = \"\"\n inCellList:str = \"\"\n separator:str = \"\"\n # only show the options for the first element\n if showOptions == 0:\n print(addMdSetting.availableSettings)\n print(f\"The file used for setting the format for all csv files in the current working directory is \\\"{self.csvFiles[0]}\\\".\")\n showOptions += 1\n\n # set the formatting of each cell\n while True:\n cellFormatting = input(f\"How should the column \\\"{row[el]}\\\" be formatted? \")\n cellFormatting = cellFormatting.lower().strip()\n # check if the chosen formatting is valid\n if cellFormatting in addMdSetting.availableSettingsList:\n break\n # asks whether a cell contains multiple elements that should be separately formatted\n while True:\n # don't ask whether the cell contains multiple values if there's no formatting to be applied\n if cellFormatting == \"n\":\n break\n inCellList = input(\"Does this cell contain multiple values which should be separately formatted? \\\"y\\\" for yes and \\\"n\\\" for no: \")\n if inCellList.lower() == \"n\":\n break\n elif inCellList.lower() == \"y\":\n separator = input(\"How is your list separated? Please enter the character: \")\n break\n \n # adds the formatting to self.settings with \"column\" as key\n # the value is a dictionary, whose key is the index of the column and the cell formatting as string in a list as its value\n if len(inCellList) > 0 and len(separator) > 0:\n self.settings[\"column\"][el] = [cellFormatting, inCellList, separator]\n else:\n self.settings[\"column\"][el] = [cellFormatting]\n\n # ask the user whether they want to save their settings in saved_settings.py\n while True:\n save_settings = input(\"Do you want to save these settings? Enter \\\"y\\\" for yes and \\\"n\\\" for no: \")\n if save_settings.lower().strip() == \"y\":\n addMdSetting.saveSettings(self.settings)\n break\n elif save_settings.lower().strip() == \"n\":\n break\n \n # stop after the first row, so that it doesn't keep checking all the other rows after it\n break\n \n\n def makeMdFiles(self):\n # create the data subdirectory to create the .md files there\n try:\n if not os.path.exists(\"./data/\"):\n os.makedirs(\"./data/\")\n except OSError:\n print (\"Error: Creating directory.: ./data/\")\n\n # loop through all of the csv files in the current directory and subdirectories\n for file in self.csvFiles:\n # open the current file in read mode\n with open(file, \"r\", encoding='utf-8') as currentFile:\n fileReader = csv.reader(currentFile, delimiter=self.settings[\"delimiter\"])\n # goes through each row in the currently open file and applies the md settings, creates a md file for each row\n for row in fileReader:\n # exlude the first row as it only includes the heading names\n if fileReader.line_num != 1:\n # contains all the formatted text which will be written to the md file\n lst:list= []\n # needed if YAML frontmatter is chosen to be written to the md files\n unformattedLst:list = []\n for el in range(len(row)):\n # append the unformatted values to the list so that they can become \n # the YAML values\n if self.yaml == True:\n unformattedLst.append(row[el].strip(\"\\\"'\"))\n\n # retrieve the formatted strings for the main text\n # checks if the current cell contains multiple values\n if len(self.settings[\"column\"][el]) > 1:\n # split the list at the given separator and return their unique values\n sublist:list = row[el].split(self.settings[\"column\"][el][2])\n # apply the formatting to each unique element\n splitSublist:str = self.splitSubList(sublist, self.settings[\"column\"][el][0])\n lst.append(splitSublist)\n else:\n formattedText:list = self.returnFormatting(row[el], self.settings[\"column\"][el][0])\n # only append \"null\" to the list of formatted content when there is no content when self.inlineyaml is True\n # this will mean that the inline YAML keys can all be matched in enumerate and that it doesn't fail\n if formattedText != None:\n lst.append(formattedText)\n elif formattedText == None and self.inlineyaml == True:\n lst.append(\"null\")\n\n\n # accesses the column(s) that was/were selected for the file name\n fileName:str = \"\"\n if len(self.settings[\"fileNameCol\"]) > 1:\n for idx, el in enumerate(self.settings[\"fileNameCol\"]):\n if len(self.settings[\"fileNameCol\"]) - 1 == idx:\n fileName += row[el]\n else:\n fileName += row[el] + self.settings[\"fileNameColSeparator\"]\n else:\n fileName = row[int(*self.settings[\"fileNameCol\"],)]\n\n # limit the file name to the specified length \n fileName = fileName[:self.settings[\"fileNameLength\"]]\n fileName = fileName.strip()\n # create the final file name\n fileName = \"./data/\" + re.sub(r\"<|>|:|\\\"|/|\\\\|\\||\\?|\\*|\\[|\\]\", \"\", fileName)\n \n # checks whether there is already a file with the same file name\n # if so, then it will append _{counter} to it\n if os.path.isfile(fileName + \".md\"):\n counter:int = 1\n while True:\n if os.path.isfile(fileName + \"_\" + str(counter) + \".md\"):\n counter += 1\n else:\n fileName += \"_\" + str(counter)\n break\n fileName += \".md\"\n\n # string which will be written to the file\n strToWrite:str = \"\"\n\n # make the string which will be written to the file\n try:\n if self.yaml == True:\n yamlLst:list = []\n for idx, key in enumerate(self.keys):\n # replace UTF-8 BOM, should be handled better/perhaps with user option to specify the encoding of the csv file\n key = key.replace(\"\\ufeff\", \"\")\n # unpack if list and make separate values for the key in the YAML\n if len(self.settings[\"column\"][idx]) > 1:\n yamlSubLst:list = unformattedLst[idx].split(self.settings[\"column\"][idx][2])\n yamlSubStr:str = \"\"\n for el in yamlSubLst:\n if len(el) == 0:\n continue\n else:\n yamlSubStr += f\"\\\"{el.strip()}\\\", \"\n yamlSubStr = yamlSubStr.strip(\", \")\n yamlLst.append(f\"{key}: [{yamlSubStr}]\")\n else:\n # make value null if there is no value for the key\n if len(unformattedLst[idx]) == 0:\n yamlLst.append(f\"{key}: null\")\n else:\n yamlLst.append(f\"{key}: [\\\"{unformattedLst[idx]}\\\"]\")\n strToWrite += \"---\\n\"\n strToWrite += \"\\n\".join(yamlLst)\n strToWrite += \"\\n---\\n\"\n # append the rest of the file\n strToWrite += \"\\n\\n\".join(lst)\n # for inline yaml append key and formatted values to list\n elif self.inlineyaml == True:\n inlineyamlLst:list = []\n for idx, key in enumerate(self.keys):\n key = key.replace(\"\\ufeff\", \"\")\n value = lst[idx].replace(\"\\n\", \" \")\n inlineyamlLst.append(f\"{key}:: {value}\")\n strToWrite += \"\\n\".join(inlineyamlLst)\n # if neither YAML nor inline YAML is selected to be written, only the main content will be written\n else:\n strToWrite += \"\\n\\n\".join(lst) \n \n # creates a .md file in the data folder with the string from above\n with open (fileName, \"w\", encoding='utf-8') as f:\n f.write(strToWrite)\n \n except:\n # remove the file that was erroneously created\n # shouldn't happen anymore unless there was an error when opening/writing to the file\n if os.path.isfile(fileName):\n os.remove(fileName)\n # log the error to log.txt\n with open(\"log.txt\", \"a\", encoding='utf-8') as m:\n m.write(fileName + \" -- Error.\\n\")\n\n def splitSubList(self, sublist, formatting):\n sublist_str:str = \"\"\n for el in sublist:\n if len(el) == 0:\n continue\n else:\n sublist_str += self.returnFormatting(el.strip(\"\\\"' \"), formatting) + \"\\n\"\n return sublist_str.strip(\"\\n\")\n\n\n def returnFormatting(self, string, formatting):\n if len(string) > 0:\n if formatting == \"n\":\n return f\"{string}\"\n elif formatting == \"wl\":\n return f\"[[{string}]]\"\n elif formatting == \"ml\":\n return f\"[{string}]({string})\" \n elif formatting == \"hl\":\n return f\"=={string}==\"\n elif formatting == \"it\":\n return f\"*{string}*\"\n elif formatting == \"bo\":\n return f\"**{string}**\"\n elif formatting == \"st\":\n return f\"~~{string}~~\"\n elif formatting == \"co\":\n return f\"`{string}`\"\n elif formatting == \"cb\":\n return f\"```\\n{string}\\n```\"\n elif formatting == \"h1\":\n return f\"# {string}\"\n elif formatting == \"h2\":\n return f\"## {string}\"\n elif formatting == \"h3\":\n return f\"### {string}\"\n elif formatting == \"h4\":\n return f\"#### {string}\"\n elif formatting == \"h5\":\n return f\"##### {string}\"\n elif formatting == \"h6\":\n return f\"###### {string}\"\n elif formatting == \"wlem\":\n return f\"![[{string}]]\"\n elif formatting == \"mlem\":\n return f\"![{string}]({string})\"\n elif formatting == \"ul\":\n return f\"- {string}\"\n elif formatting == \"ol\":\n return f\"1. {string}\"\n elif formatting == \"bq\":\n return f\">{string}\"\n elif formatting == \"ut\":\n return f\"- [ ] {string}\"\n elif formatting == \"ct\":\n return f\"- [x] {string}\"\n elif formatting == \"ma\":\n return f\"${string}$\"\n elif formatting == \"mb\":\n return f\"$$\\n{string}\\n$$\"\n elif formatting == \"oc\":\n return f\"%%{string}%%\"\n elif formatting == \"ta\":\n return f\"#{string}\"\n # return None if the passed cell value is empty\n else:\n return None\n\n\n\n\n\n# instantiate GetInput class to start the script\n\nstartScript = GetInput()\nstartScript.choices()\nprint(\"The program has now finished. Check log.txt to see if there are any errors.\")"
},
{
"alpha_fraction": 0.7303761839866638,
"alphanum_fraction": 0.7397260069847107,
"avg_line_length": 45,
"blob_id": "6368eded0e06e137e671e3c597612cd553493a3e",
"content_id": "9fbfbeccc6d4afc36af1de6524905a1e44aaf7d4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4599,
"license_type": "permissive",
"max_line_length": 256,
"num_lines": 100,
"path": "/README.md",
"repo_name": "lexanne-online/csv-to-md-personal",
"src_encoding": "UTF-8",
"text": "# CSV to Markdown converter\n\nThis script converts every row of all CSV files in the working directory and subdirectories into Markdown files according to the formatting settings you choose per column.\n\nThis will ***not*** create a Markdown table.\n\n**It is still in early alpha, so please have backups!** At this stage I may still introduce features that will break existing saved settings. When you update, you may need to update them/do the configuration again.\n\n**The encoding with which the files will be opened is UTF-8. Make sure that your CSV files are in that encoding, otherwise they might get screwed up. Again, please have backups**.\n\nI have tested it with Python 3.9.4. (Because I use typing the Python version needs to be at least 3.5, I haven't checked for the other imported packages.)\n\nThe Markdown syntax is supposed to support the full range of Markdown formatting which is available within Obsidian. Therefore, it supports some non-standard formatting, which may not work with every Markdown editor.\n\n## Usage\n\nClone this repo and put the CSV files you want to convert in the same directory.\n\nRun `csv_to_md-file.py` in the terminal *from the directory in which these files are located*.\n\nIt will prompt you for your choices.\n\n![GIF showing usage](./example/csv-md-YAML.gif)\n\nThe outputted Markdown files will appear in the `./data/` subdirectory. (No need to create it, the program takes care of it.)\n\nAs example one of the outputted Markdown files (with the example CSV file and settings from the GIF) looks like this:\n\n![example of output](./example/result.png)\n\nIf you choose \"no\" for frontmatter YAML and \"yes\" for inline YAML, the result will look like this:\n\n![example of output -- inline YAML](./example/result2.png)\n\nYou can try it out with different settings with the example CSV file. (Not included so that you don't have to delete it every time you pull again to update, just copy the contents below in a CSV file and run the script.)\n\n```csv\nSeries,Season,Watch_Time,Status,Current_Episode,Rating\nHow I met your Mother,2,20 hours,unfinished,2,good\nThe Big Bang Theory,4,30 hours,unfinished,12,great\nBlack Mirror,2,10 hours,unfinished,1,fantastic\n```\n\n## Options\n\nYou can:\n\n- add everything as YAML frontmatter\n- only write the contens of the CSV files as inline YAML (instead of having the contents as frontmatter YAML and/or Markdown)\n- choose the delimiter of your CSV files\n- the maximum file name length\n- from which column the file name should be generated\n- choose the Markdown formatting for each column\n- write the chosen settings to `saved_settings.py`\n- read settings you set before.\n\nFile name collisions are handled by appending `_<number>` to the file name.\n\n## How it works\n\nIt will let you choose the settings for the first file in the list of CSV files the program creates, so all the CSV files you run it on have to have\nthe same columns if you want the settings to be applied consistently/if you want it not to fail. (This means that you should only run the script on CSV files with the same number of rows/formatting at once and choose different settings for the next batch.)\n\n`saved_settings.py` is not yet created, but will be. That way your settings won't be overwritten when you `pull` to update. All subsequent saved settings will be appended to this file.\n\n## Example settings\n\nBreaking change 2021/05/13: If you have existing settings from before this version, you will need to surround the corresponding value of 'fileNameCol' with square brackets.\n\nIf you choose to add frontmatter YAML, you cannot add inline YAML.\nYour choice for inline YAML will have now effect in that case.\nIf you only want to have inline YAML, select no for fronmatter YAML and yes for inline YAML.\nWhen you select yes for inline YAML, only inline YAML will be added to the file\n(but the values will be with Markdown formatting).\n\n```python\nsave2 = {'addYAML': 'n',\n 'column': {0: ['h2'],\n 1: ['ul'],\n 2: ['ta'],\n 3: ['ta', 'y', ','],\n 4: ['oc'],\n 5: ['ml'],\n 6: ['ta'],\n 7: ['ut'],\n 8: ['ut']},\n 'delimiter': ',',\n 'fileNameCol': [0, 1],\n 'fileNameColSeparator': ' -- ',\n 'fileNameLength': 50,\n 'inlineYAML': 'y'}\n```\n\n\n## Remarks for manually editing the settings\n\nYou can create them manually as well/edit them after using the script.\n\n'fileNameColSeparator' is not needed, if there is only one element in 'fileNameCol'. 'inlineYAML' is only needed when you\ndon't choose to add frontmatter YAML. If you let the script take care of everything, you don't need to worry about it."
}
] | 3 |
cimox/Rectilinear-Crossing-Number-using-simulated-annealing | https://github.com/cimox/Rectilinear-Crossing-Number-using-simulated-annealing | 95615c4e326622fc8dfa816a9d48e09d16f2ec26 | 5a74e691ec5cc98739c9dc1436075facab5b9df1 | b0e88eb56ccb7f0df8d7b30dcaaae12d8db2df1a | refs/heads/master | 2016-08-11T16:31:45.882397 | 2016-04-12T07:50:14 | 2016-04-12T07:50:14 | 55,456,215 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5848101377487183,
"alphanum_fraction": 0.5898734331130981,
"avg_line_length": 27.285715103149414,
"blob_id": "3aeb1b5e3f374e53b6cff23f7bc6891fdb43390b",
"content_id": "0ca7a74eae16a0285aad2df92163e70466be3b29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 395,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 14,
"path": "/edge.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "class Edge:\n 'Common base class for edges'\n edges_count = 0\n\n def __init__(self, A, B):\n self.A = A # point A as [x,y] cartesian coordinates\n self.B = B # point B as [x,y] cartesian coordinates\n Edge.edges_count += 1\n\n def get_count(self):\n return Edge.edges_count\n\n def get_count_HRF(self):\n print \"> Total number of edges: \" % Edge.edges_count"
},
{
"alpha_fraction": 0.5129087567329407,
"alphanum_fraction": 0.5160068869590759,
"avg_line_length": 37.733333587646484,
"blob_id": "8824312c0736a30364f47e531c08579e91f3ad43",
"content_id": "5460571328b04bd37526cc0846aa4660fcf6f910",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2905,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 75,
"path": "/main.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\nfrom Properties import Properties\nfrom Utility import Utility\nfrom Graph import Graph\n\n\ndef normalize(x, min, max):\n return (x - min) / (max - min)\n\n\ndef main():\n utils = Utility()\n f = open('data.csv', 'w')\n f.write('vertices,penalization,stddev,avg\\n')\n\n # run experimens\n for Kn in range(Properties.Kn_min, Properties.Kn_max):\n all_costs = []\n for i in range(2): # 0 - without penalization, 1 - with penalization\n for experiment in range(Properties.experiment_limit):\n print \"[START] experiment\", experiment, \"for N\", Kn\n\n # simulated annealing initialization\n total_iterations = 1\n T = Properties.Tmax\n vertices = utils.generate_initial_vertices(Kn)\n edges = utils.generate_edges(Kn)\n g = Graph(vertices, edges) # g is initial randomly generated graph\n all_costs.append(g.crossingNumber)\n print \"> init crossing number\", g.crossingNumber\n\n # utils.draw_graph(g)\n\n # 3. step: loop until stop condition is met\n # stop condition:\n # - temperature is cooled\n # - good-enough solution has been found\n temperatures = []\n intersections = [] # aka fitnesses\n while T > Properties.Tmin:\n # temperatures.append(T)\n # intersections.append(g.get_crossing_number())\n\n if g.get_crossing_number() == Properties.Min_CrossingNumber[Kn]:\n break # end if solution has been found\n total_iterations += Properties.Kmax\n\n # simulated annealing core\n if i == 0: # not penalized\n metropol = utils.metropolis_algorithm(g, Properties.Kmax, T, False)\n else: # penalized\n metropol = utils.metropolis_algorithm(g, Properties.Kmax, T, True)\n g = metropol[0] # save new graph\n metr_run_costs = metropol[1]\n all_costs.extend(metr_run_costs)\n\n T = Properties.alpha * T # cooldown system - slowly cooling down the system\n\n if Properties.debug:\n print \"[INFO] temp\", T, \"iter\", total_iterations, \"cross\", g.get_crossing_number()\n\n print \"> final crossing number\", g.get_crossing_number()\n print \"[END] total iterations\", total_iterations, \"\\n----------------------------\\n\"\n\n f.write(str(Kn) + ',')\n if i == 0:\n f.write('FALSE,')\n else:\n f.write('TRUE,')\n f.write(str(np.std(all_costs)) + ',' + str(np.average(all_costs)) + '\\n')\n f.close()\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5772594809532166,
"alphanum_fraction": 0.5830903649330139,
"avg_line_length": 23.35714340209961,
"blob_id": "17e3eb99df70b14137ee8b7b4aa0d80419d002f6",
"content_id": "70c93e6b02798a099bcfbc740bd35679be716609",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 343,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/vertex.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "class Vertex:\n 'Common base class for vertices'\n vertices_count = 0\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n Vertex.vertices_count += 1\n\n def get_count(self):\n return Vertex.vertices_count\n\n def get_count_HRF(self):\n return \"> Total number of vertices: \" % Vertex.vertices_count\n\n\n"
},
{
"alpha_fraction": 0.573283851146698,
"alphanum_fraction": 0.5828695297241211,
"avg_line_length": 32.01020431518555,
"blob_id": "6c48c6e0b4d9bc1b2a3a22bd9fce795a53a2e4a7",
"content_id": "c98edd6f6615c815415044dbc99d644956aeb3a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3234,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 98,
"path": "/graph.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "import random as rand\nimport copy\nimport itertools\nfrom Utility import Utility\nfrom Properties import Properties\n\nclass Graph:\n 'Common base class for graphs'\n utils = Utility()\n\n def __init__(self, vertices, edges):\n self.vertices = vertices\n self.edges = edges\n self.crossingNumber = self.get_crossing_number()\n\n def clone(self):\n # creates clone of current graph\n clone_vertices = copy.deepcopy(self.vertices)\n clone_edges = itertools.tee(self.edges)[0]\n clone = Graph(clone_vertices,clone_edges)\n\n return clone\n\n\n def get_crossing_number(self):\n # returns count of intersections in graph (self)\n cnt = 0 # counter of intersections\n edges = itertools.combinations(range(len(self.vertices)),2) # copy edges generator so we keep them in graph\n\n # iterate over all edges\n for p1,q1 in edges:\n v=[]\n for i in range(len(self.vertices)): # generate vertices pairs (edges) to check\n if i != p1 and i != q1:\n v.append(i)\n edges_to_check=itertools.combinations(v,2)\n\n for p2,q2 in edges_to_check:\n if p1 == p2 and q1 == q2:\n # do nothing\n print \"[WARN] same positions\",p1,q1,p2,q2\n else:\n if self.utils.do_intersect(self.vertices[p1],self.vertices[q1],\n self.vertices[p2],self.vertices[q2]):\n cnt += 1 # they do intersect\n\n return cnt/2\n\n def new_edges(edges,last=None):\n if last is None:\n return itertools.combinations(edges)\n\n def get_vertex(self,pos):\n # returns vertex from specific position\n if pos < self.number_vertices():\n return self.vertices[pos]\n return 1\n\n def get_vertices(self):\n return self.vertices\n\n def get_copy_vertices(self):\n # returns copy of vertices\n return copy.copy(self.vertices)\n\n def number_vertices(self):\n # returns amount of vertices\n return len(self.vertices)\n\n def mutate(self,debug):\n # pick random vertex and mutate it\n randPos = rand.randint(0, self.number_vertices()-1)\n if debug:\n print \"[INFO] mutating\"\n print \"> vertex:\", randPos\n print \"> position:\", self.vertices[randPos].x, self.vertices[randPos].y\n\n diff_x = round(rand.gauss(0,Properties.sigma),Properties.decimal_points)\n diff_y = round(rand.gauss(0,Properties.sigma), Properties.decimal_points)\n\n # self.vertices[randPos].x += diff_x\n # self.vertices[randPos].y += diff_x\n\n self.vertices[randPos].x = round(1-diff_x * self.vertices[randPos].x, Properties.decimal_points)\n self.vertices[randPos].y = round(1-diff_y * self.vertices[randPos].y, Properties.decimal_points)\n\n def print_HRF(self, vertices, edges):\n # prints graph attributes in human readable format\n\n if vertices:\n print \"Vertices: \"\n for v in self.vertices:\n print v.x, v.y\n\n if edges:\n print \"Edges: \"\n for e in self.edges:\n print e"
},
{
"alpha_fraction": 0.48492431640625,
"alphanum_fraction": 0.4994637072086334,
"avg_line_length": 31.78125,
"blob_id": "1a7b7130471fe70eaa5e2731bab068cb1a6190e9",
"content_id": "05eeae7522192b005c8323b75ddc849744df1229",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8391,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 256,
"path": "/Utility.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "import plotly\nimport plotly.graph_objs as go\n\nimport random as rand\nimport itertools\nimport math\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom Vertex import Vertex\nfrom Properties import Properties\nfrom plotly.graph_objs import *\n\nclass Utility:\n 'Class w/ utility functions'\n # plt.show()\n\n def __init__(self):\n self = self\n\n def generate_initial_vertices(self, Kn):\n # generate random vertices at position X,Y\n vertices = []\n\n for i in range(Kn):\n vertices.append(Vertex(\n round(rand.uniform(0,1),Properties.decimal_points),\n round(rand.uniform(0,1),Properties.decimal_points))) # X,Y\n\n return vertices\n\n def generate_edges(self, n):\n # returns edges as a dictionary generator of combinations\n\n if n > 1:\n edges=itertools.combinations(range(n),2)\n\n return edges\n\n def metropolis_algorithm(self,Xinit,Kmax,T,penalization=False):\n # implementation of metropolis algorithm\n accepted_costs = []\n\n x = Xinit.clone()\n k=0\n while k < Kmax:\n newX=x.clone()\n newX.mutate(False)\n #self.draw_graph(newX) #TODO: animate graph lifecycle\n\n #P = min(1.0,math.exp(-(self.f(newX) - self.f(x))/T))\n if penalization == True:\n P = min(1.0, math.exp((self.energy(x,True) - self.energy(newX,True)) / T))\n else:\n P = min(1.0, math.exp((self.energy(x) - self.energy(newX)) / T))\n if rand.uniform(0,1) < P:\n x = newX\n accepted_costs.append(x.get_crossing_number())\n k += 1\n return [x,accepted_costs]\n\n def penalization(self,x):\n # returns penalization for graph x if coord not in (0,1)\n penalization = 0\n for v in x.get_vertices():\n if (v.x > 1 and v.y > 1) or (v.x < 0 and v.y < 0):\n penalization += 1\n return penalization\n\n def energy(self, x, penalization=False):\n # fitness (penalization) function for a given graph = crossing number of x (graph)\n\n crossing_number = x.get_crossing_number()\n if penalization == True:\n crossing_number += self.penalization(x)\n\n return crossing_number + Properties.f_const\n\n def on_segment(self,p,q,r):\n # for given colinear points p, q, r, the function evaluates if point\n # q lies on line segment p-r\n if q.x<=max(p.x,r.x) and q.x>=min(p.x,r.x) and q.y<=max(p.y,r.y) and q.y>=min(p.y,r.y):\n return True\n return False\n\n def get_orientation(self,p,q,r):\n # returns orientation of ordered triplet of points p, q, r\n # 0 = p, q and r are colinear\n # 1 = clockwise\n # -1 = counterclockwise\n val = (q.y-p.y) * (r.x-q.x) - (q.x-p.x) * (r.y-q.y)\n if val == 0:\n return 0\n return 1 if val > 0 else -1\n\n def do_intersect(self,p1,q1,p2,q2):\n # returns true if line segment p1-q1 and p2-q2 intersect\n\n # gets orientation\n o1 = self.get_orientation(p1,q1,p2)\n o2 = self.get_orientation(p1,q1,q2)\n o3 = self.get_orientation(p2,q2,p1)\n o4 = self.get_orientation(p2,q2,q1)\n\n # general case - intersects in some point on line\n if o1 != o2 and o3 != o4: # TODO: vychadzanie z rovnakeho bodu\n return True\n\n # special cases\n if o1 == 0 and self.on_segment(p1,p2,q1):\n return True\n if o2 == 0 and self.on_segment(p1,q2,q1):\n return True\n if o3 == 0 and self.on_segment(p2,p1,q2):\n return True\n if o3 == 0 and self.on_segment(p2,q1,q2):\n return True\n\n def draw_graph(self,g,Kn):\n # draws graph based on graph g from parameter\n # g - graph\n # Kn - graph degree\n\n initialGraph = nx.complete_graph(Kn)\n fixed_pos = {}\n vertices = g.get_vertices()\n for i in range(len(vertices)):\n fixed_pos[i] = (vertices[i].x, vertices[i].y)\n fixed_nodes = fixed_pos.keys()\n pos = nx.spring_layout(initialGraph, pos=fixed_pos, fixed=fixed_nodes)\n nx.draw_networkx(initialGraph, pos)\n plt.show()\n\n def print_to_graph(self, x_axis, y_T, y_1, y_2, y_vars, y_3, x_range, y_range,\n name, xlab='Generations', ylab='Normalized to (0,1)',\n ln1_title='Temperature', ln2_title='Standard deviation', title=None,\n url=None, normalization=True):\n # prints graph with x-y data to file\n # x_axis - data on x axis\n # y_T - first Y data\n # y_intersections - intersections data or somethings else\n # x_range - x axis range, same w/ y_range\n # name - title of graph\n # xlab,ylab - x/y axis text label\n # ln1/2_label - line 1 and 2 label\n # title - title of graph\n # url - sends to plot.ly\n\n\n # Create a trace\n\n # normalized\n if normalization:\n norm = min(y_T,y_1,y_2,y_3)\n y_T = go.Scatter(\n x=x_axis, y=[float(i) / max(norm) for i in y_T], # normalized\n name=ln1_title\n )\n y_1 = go.Scatter(\n x=x_axis, y=[float(i) / max(norm) for i in y_1], # normalized\n name=ln2_title\n )\n y_2 = go.Scatter(\n x=x_axis, y=[float(i) / max(norm) for i in y_2], # normalized\n name='Average'\n )\n y_3 = go.Scatter(\n x=x_axis, y=[float(i) / max(norm) for i in y_3], # normalized\n name='Fitness'\n )\n\n else:\n y_T = go.Scatter(\n x=x_axis, y=y_T, name=ln1_title\n )\n y_1 = go.Scatter(\n x=x_axis, y=y_1, name=ln2_title\n )\n y_2 = go.Scatter(\n x=x_axis, y=y_2, name='Average'\n )\n y_3 = go.Scatter(\n x=x_axis, y=y_3, name='Fitness'\n )\n y_vars = go.Scatter(\n x=x_axis, y=y_vars, name='Variance',\n mode='markers'\n )\n\n data = [y_T, y_1, y_2, y_3, y_vars]\n\n if title == None:\n title = str.split(name, '-')[2] + ' Vertices'\n if normalization:\n title = title + ' Normalized'\n layout = go.Layout(\n title=title,\n xaxis=dict(\n title=xlab,\n titlefont=dict(\n family='Arial, sans-serif',\n size=18,\n color='darkgrey'\n ),\n showticklabels=True,\n tickfont=dict(\n family='Old Standard TT, serif',\n size=14,\n color='black'\n ),\n exponentformat='e',\n showexponent='All',\n range=x_range,\n ),\n yaxis=dict(\n title=ylab,\n titlefont=dict(\n family='Arial, sans-serif',\n size=18,\n color='darkgrey'\n ),\n showticklabels=True,\n tickfont=dict(\n family='Old Standard TT, serif',\n size=14,\n color='black'\n ),\n exponentformat='e',\n showexponent='All'\n #,range=y_range\n )\n )\n fig = go.Figure(data=data, layout=layout)\n if normalization:\n name = name + '-normalized'\n plotly.offline.plot(fig,filename=name)\n # if url == True:\n # plot_url = plotly.plot(fig, filename=name)\n\n def vis_stats(self,x_axis,t,all_costs,name):\n y_t = []\n for i in range(len(t)): # sample temperature over x-axis\n for j in range(len(x_axis) / len(t)):\n y_t.append(t[i])\n avg = np.average(all_costs) # calculate average of all costs (fitness)\n avgs = []\n for i in range(len(x_axis)): # sample avgs over x-axis\n avgs.append(avg)\n\n\n\n\n self.print_to_graph(x_axis,y_t,avgs,avgs,avgs,avgs,\n [min(x_axis),max(x_axis)], None, name,\n normalization=False)"
},
{
"alpha_fraction": 0.5610640645027161,
"alphanum_fraction": 0.645707368850708,
"avg_line_length": 38.42856979370117,
"blob_id": "b03162f1b89253a6063607b8475310ef5525034f",
"content_id": "77b46af66cb644ab9cc01ea02db7a94399b4a3e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 827,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 21,
"path": "/Properties.py",
"repo_name": "cimox/Rectilinear-Crossing-Number-using-simulated-annealing",
"src_encoding": "UTF-8",
"text": "class Properties:\n 'Class containing all properties of program'\n debug = False\n\n Tmax = 2.0 # maximum temperature\n # Tmax = 200000.0 # maximum temperature\n Tmin = 0.01 # minimum temperature\n alpha = 0.998 # cooling rate\n Kn_max = 12 # max vertices in graph\n Kn_min = 5 # min vertices in graph\n Min_CrossingNumber = {5:1,6:3,7:9,8:19,9:36,10:62,\n 11:102,12:153,13:229,14:324,15:447} # optimal solution for n vertices graph : crossing number\n sigma = 0.1 # gaussian sigma\n decimal_points = 5 # float decimal points rounding used in program\n draw_graph = False\n Kmax = 10 # K-max iterations in metropolis alg.\n f_const = 0.048 # penalization constant\n experiment_limit = 1 # how many experiments should be executed\n\n def __init__(self):\n self = self"
}
] | 6 |
hertogp/vimdir | https://github.com/hertogp/vimdir | 88c00457257bc805e152d7ef05a2eb9675bd970b | 5046ee03bc973fe8432fac3b1de4d2c6a712af44 | 1fed32efc905d8d413bfcdc3e02e8eb55c2bb6d5 | refs/heads/master | 2021-01-17T14:51:23.677868 | 2017-11-16T15:43:43 | 2017-11-16T15:43:43 | 48,550,180 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5851724147796631,
"alphanum_fraction": 0.5962069034576416,
"avg_line_length": 43.61538314819336,
"blob_id": "240725b76d1de73f209cc8a1181d7c8caf6e50b0",
"content_id": "942955049a1d8e0ec31d90518d15e42000d407f5",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2900,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 65,
"path": "/pylib/voom/voom_mode_css.py",
"repo_name": "hertogp/vimdir",
"src_encoding": "UTF-8",
"text": "# voom_mode_wiki.py\n# VOoM (Vim Outliner of Markers): two-pane outliner and related utilities\n# plugin for Python-enabled Vim version 7.x\n# Website: http://www.vim.org/scripts/script.php?script_id=2657\n# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)\n# License: This program is free software. It comes without any warranty,\n# to the extent permitted by applicable law. You can redistribute it\n# and/or modify it under the terms of the Do What The Fuck You Want To\n# Public License, Version 2, as published by Sam Hocevar.\n# See http://sam.zoy.org/wtfpl/COPYING for more details.\n\n\"\"\"\nVOoM markup mode for css files.\n\"\"\"\n\n### Voom functions called\n#-- voom.vim: Voom_BodyCheckTicks\n# s:voom_bodies[a:body].tick_!=b:changedtick\n# - calls Voom_BodyUpdateTree()\n# - Voom_ErrorMsg('VOom: wrong ticks for Body buffer <n>. Updated outline\n\n# Outline puts global commands on level 1, subsequent global commands in the\n# same category are on level 2 (so you can fold them). For interfaces and\n# access-lists (you can easily add more), it actually looks at 2 keywords.\n\ndef hook_makeOutline(VO, blines):\n \"\"\"Return (tlines, bnodes, levels) for list of Body lines.\n blines can also be Vim buffer object.\n \"\"\"\n tlines, bnodes, levels = [], [], []\n tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append\n seen = {} # seen previousely on an input line\n sig_ = ''\n for i,L in enumerate(blines):\n if not L: continue # skip empty\n elif L.startswith('<!-- '): L = L.replace('<!--','>>') # HEADLINE\n elif not L[0].isalpha(): continue # skip indents\n elif L[0] == '}': continue # skip block closers\n else: L = L.rsplit('{')[0].rstrip() # cleanup line\n if len(L) < 1: continue # skip really short lines\n L = L.lower() # outline will be lower cased\n W = L.split()[0:4] # use only first 5 words\n if not W: continue\n\n # assign level 1 when seeing a glob cmd for the 1st time, else 2\n sig = ' '.join(W[0:2]) # sig = first 3 words\n L = ' '.join(W[0:4])\n lev = 2 if sig in seen else seen.setdefault(sig,1)\n lev = 2 if sig == sig_ else 1\n sig_ = sig\n levels_add(lev)\n tlines_add(' {0}|{1}'.format(' .'*(lev-1), L))\n bnodes_add(i+1)\n\n return (tlines, bnodes, levels)\n\ndef hook_newHeadline(VO, level, blnum, tlnum):\n \"\"\"Return (tree_head, bodyLines).\n tree_head is new headline string in Tree buffer (text after |).\n bodyLines is list of lines to insert in Body buffer.\n # column is cursor position in new headline in Body buffer.\n \"\"\"\n tree_head = 'NewHeadline'\n bodyLines = ['! NewHeadline']\n return (tree_head, bodyLines)\n"
},
{
"alpha_fraction": 0.5370722413063049,
"alphanum_fraction": 0.5543409585952759,
"avg_line_length": 33.774105072021484,
"blob_id": "c6ac4a308103a8f57f849690ec89a5ed539e8196",
"content_id": "43a0a0f6633a3692ec29bd2a681a03b99b7fa5ed",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12624,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 363,
"path": "/pylib/voom/voom_mode_sanfran.py",
"repo_name": "hertogp/vimdir",
"src_encoding": "UTF-8",
"text": "# voom_mode_wiki.py\n# VOoM (Vim Outliner of Markers): two-pane outliner and related utilities\n# plugin for Python-enabled Vim version 7.x\n# Website: http://www.vim.org/scripts/script.php?script_id=2657\n# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)\n# License: This program is free software. It comes without any warranty,\n# to the extent permitted by applicable law. You can redistribute it\n# and/or modify it under the terms of the Do What The Fuck You Want To\n# Public License, Version 2, as published by Sam Hocevar.\n# See http://sam.zoy.org/wtfpl/COPYING for more details.\n\n\"\"\"\nVOoM markup mode for Cisco confg files. See |voom_mode_cisco|.\n\"\"\"\n\n### Howto add to the outline\n# - supply head_match rgx\n# - supply make_vheadline\n# - supply make_headline\n# - virtual or not\n#\n# Idea is to use a rgx to match a series of repeating statements\n# and turn that into a single virtual headline pointing to a comment line just\n# above the first match (creating one if needed).\n# The rgx matches two parts:\n# - start_ignore\n# - \n# Examples:\n#\n# interface fastethernet1/0/1\n# ^--match-replace-----^\n# ^--match-unique----------^\n#\n# - replace -> fa\n# - vhead_line := fa1/0/..\n# which allows for folding f1/0/1..48 into 1 tree headline entry\n#\n# access-list 1 permit ..\n# ^-replace-^\n# ^-unique----^\n#\n# - replace -> acl\n# - vhead_line := acl 1...\n#\n# snmp-server view ...\n# ^-replace-^\n# ^-unique--^\n#\n# - nothing will be replaced\n# - vhead_line := snmp-server...\n\n\n\n# can access main module voom.py, including global outline data\nimport sys\nif 'voom' in sys.modules:\n voom = sys.modules['voom']\n VOOMS = voom.VOOMS\nimport vim\n\nprint 'vim attrs'\nfor a in dir(vim):\n print a, getattr(vim,a)\n\nprint 'voom attrs'\nfor a in dir(voom):\n print a, getattr(voom,a)\n\n\n\nimport re\n# re to substitute comments. use comment_tag_sub('new text', line)\ncomment_tag_sub = re.compile('!.*$').sub\n# re to recognize a headline\nheadline_match = re.compile(r'^(interface|router|access-list|dialer-list|line)').match\n\n\n\nVHEADS = [#(r\"((interface\\s+fastethernet\\s*).*?)\\d+$\",\"int fa\",\"...\",'!'),\n #(r\"((interface\\s+gigabitethernet\\s*).*?)\\d+$\", \"int gi\",\"...\",\"!\"),\n #(r\"((interface\\s+vlan\\s*).*?)\\d+$\", \"int vlan\",\"...\",\"!\"),\n #(r\"((access-list\\s+)\\d+).*$\",\"acl \",\"...\",\"!\"),\n #(r\"((snmp-server)\\s+).*$\", \"snmp-server \",'','!'),\n #(r\"((line\\s+con)\\s+).*$\", \"line con \",'','!'),\n #(r\"((line\\s+vty)\\s+).*$\", \"line vty \",'','!'),\n (r\"((ntp\\s+)).*$\", \"ntp \",'...','!'),\n ]\nRHEADS = [(re.compile(r).match,s,t,c) for r,s,t,c in VHEADS]\n\ndef get_level2(L,his=['']):\n '''return (level,vgrp), where\n level - tree outline level for L, and\n vgrp - virtual outline header text (if any)\n '''\n if L is None:\n del his[:] # clear sense of history\n his[0]=''\n return (1,'')\n\n w = L.lower().split()\n vgrp = ''\n if len(w)<2: return 1,''\n fst = w[0] if w[0] != 'no' else w[1]\n if fst == 'interface':\n vgrp = 'int %s..'%w[-1].rstrip('0123456789')\n vgrp = vgrp.replace('fastethernet','f')\n vgrp = vgrp.replace('gigabitethernet','g')\n elif fst in 'access-list dialer-list':\n vgrp = ' '.join(w[0:2])\n else:\n if his[0] == fst: \n return 2,''\n else: \n his[0] = fst\n return 1,''\n\n if his[0] == vgrp: return 2,''\n his[0] = vgrp\n return 2,vgrp\n\ndef get_level3(L,his=['']):\n '''return (level,vgrp), where\n level - tree outline level for L, and\n vgrp - virtual outline header text (if any)\n '''\n if L is None:\n del his[:] # clear sense of history\n his[0]=''\n return (1,'')\n\n w = L.lower().split()\n vgrp = ''\n if len(w)<2: return 1,''\n fst = w[0] if w[0] != 'no' else w[1]\n if fst == 'interface':\n vgrp = 'int %s..'%w[-1].rstrip('0123456789')\n vgrp = vgrp.replace('fastethernet','f')\n vgrp = vgrp.replace('gigabitethernet','g')\n elif fst in 'access-list dialer-list':\n vgrp = ' '.join(w[0:2])\n else:\n if his[0] == fst: \n return 2,''\n else: \n his[0] = fst\n return 1,''\n\n if his[0] == vgrp: return 2,''\n his[0] = vgrp\n return 1,''\n### Voom functions called\n#-- voom.vim: Voom_BodyCheckTicks\n# s:voom_bodies[a:body].tick_!=b:changedtick\n# - calls Voom_BodyUpdateTree()\n# - Voom_ErrorMsg('VOom: wrong ticks for Body buffer <n>. Updated outline\n#-- two\n\ndef hook_makeOutline(VO, blines):\n \"\"\"Return (tlines, bnodes, levels) for list of Body lines.\n blines can also be Vim buffer object.\n \"\"\"\n Z = len(blines)\n tlines, bnodes, levels = [], [], []\n tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append\n seen = {'':''} # Seen HEADS\n after = []\n b_delta = 0\n Lp=''\n if blines != VO.Body:\n print >> sys.stdout, 'blines != VO.Body'\n print >> sys.stdout, 'blines\\n','\\n'.join(blines)\n print >> sys.stdout, '\\n\\nBody\\n', '\\n'.join(VO.Body)\n for i,L in enumerate(blines): \n Lp = blines[i-1] if i else ''\n b = i + 1 # b refers to 1-based buffer line nr\n L = L.rstrip() # clean the body line\n if not L: continue # skip empty line\n if not L[0].isalpha(): continue # skip indents,comments and garbage\n if len(L) == 1: continue # skip single char lines too\n L_comment = L.find('!')\n if L_comment > 0: L = L[0:L_comment] # strip comment\n lev,vgrp = get_level3(L) # get_level(seen,L)\n if vgrp:\n if not Lp.startswith('!'):\n after.append((i+b_delta,vgrp))\n b_delta += 1\n levels_add(1)\n tlines_add(' {0}|{1}'.format('', vgrp))\n bnodes_add(i+b_delta)\n\n levels_add(lev)\n tlines_add(' {0}|{1}'.format(' .'*(lev-1), L))\n bnodes_add(b+b_delta)\n\n for n,t in after: VO.Body[n:n]=['!!'] #blines[n:n] = ['!!']\n\n return (tlines, bnodes, levels)\n\n\n\ndef hook_newHeadline(VO, level, blnum, tlnum):\n \"\"\"Return (tree_head, bodyLines).\n tree_head is new headline string in Tree buffer (text after |).\n bodyLines is list of lines to insert in Body buffer.\n # column is cursor position in new headline in Body buffer.\n \"\"\"\n tree_head = 'NewHeadline'\n bodyLines = ['NewHeadline']\n return (tree_head, bodyLines)\n\ndef update_bnodes(VO, tlnum, delta):\n \"\"\"Update VO.bnodes by adding/substracting delta to each bnode\n starting with bnode at tlnum and to the end.\n \"\"\"\n bnodes = VO.bnodes\n for i in xrange(tlnum, len(bnodes)+1):\n bnodes[i-1] += delta\n\n#def hook_changeLevBodyHead(VO, h, levDelta):\n# DO NOT CREATE THIS HOOK\n\n# copy/paste from voom_mode_rest.py\ndef hook_doBodyAfterOop(VO, oop, levDelta, blnum1, tlnum1, blnum2, tlnum2, blnumCut, tlnumCut):\n # this is instead of hook_changeLevBodyHead()\n #print oop, levDelta, blnum1, tlnum1, blnum2, tlnum2, tlnumCut, blnumCut\n print 'hook_doBodyAfterOop', oop, levDelta,blnum1,blnum2\n Body = VO.Body\n Z = len(Body)\n bnodes, levels = VO.bnodes, VO.levels\n\n # blnum1 blnum2 is first and last lnums of Body region pasted, inserted\n # during up/down, or promoted/demoted.\n if blnum1:\n assert blnum1 == bnodes[tlnum1-1]\n if tlnum2 < len(bnodes):\n assert blnum2 == bnodes[tlnum2]-1\n else:\n assert blnum2 == Z\n\n # blnumCut is Body lnum after which a region was removed during 'cut',\n # 'up', 'down'. We need to check if there is blank line between nodes\n # used to be separated by the cut/moved region to prevent headline loss.\n if blnumCut:\n if tlnumCut < len(bnodes):\n assert blnumCut == bnodes[tlnumCut]-1\n else:\n assert blnumCut == Z\n\n # Total number of added lines minus number of deleted lines.\n b_delta = 0\n\n ### After 'cut' or 'up': insert blank line if there is none\n # between the nodes used to be separated by the cut/moved region.\n if (oop=='cut' or oop=='up') and (0 < blnumCut < Z) and Body[blnumCut-1].strip():\n Body[blnumCut:blnumCut] = ['']\n update_bnodes(VO, tlnumCut+1 ,1)\n b_delta+=1\n\n if oop=='cut':\n return\n\n ### Prevent loss of headline after last node in the region:\n # insert blank line after blnum2 if blnum2 is not blank, that is insert\n # blank line before bnode at tlnum2+1.\n if blnum2 < Z and Body[blnum2-1].strip():\n Body[blnum2:blnum2] = ['']\n update_bnodes(VO, tlnum2+1 ,1)\n b_delta+=1\n\n ### Change levels and/or styles of headlines in the affected region.\n # Always do this after Paste, even if level is unchanged -- adornments can\n # be different when pasting from other outlines.\n # Examine each headline, from bottom to top, and change adornment style.\n # To change from underline to overline style:\n # insert overline.\n # To change from overline to underline style:\n # delete overline if there is blank before it;\n # otherwise change overline to blank line;\n # remove inset from headline text.\n # Update bnodes after inserting or deleting a line.\n if levDelta or oop=='paste':\n ads_levels = VO.ads_levels\n levels_ads = dict([[v,k] for k,v in ads_levels.items()])\n # Add adornment styles for new levels. Can't do this in the main loop\n # because it goes backwards and thus will add styles in reverse order.\n for i in xrange(tlnum1, tlnum2+1):\n lev = levels[i-1]\n if not lev in levels_ads:\n ad = get_new_ad(levels_ads, ads_levels, lev)\n levels_ads[lev] = ad\n ads_levels[ad] = lev\n for i in xrange(tlnum2, tlnum1-1, -1):\n # required level (VO.levels has been updated)\n lev = levels[i-1]\n # required adornment style\n ad = levels_ads[lev]\n\n # deduce current adornment style\n bln = bnodes[i-1]\n L1 = Body[bln-1].rstrip()\n L2 = Body[bln].rstrip()\n if bln+1 < len(Body):\n L3 = Body[bln+1].rstrip()\n else:\n L3 = ''\n ad_ = deduce_ad_style(L1,L2,L3)\n\n # change adornment style\n # see deduce_ad_style() for diagram\n if ad_==ad:\n continue\n elif len(ad_)==1 and len(ad)==1:\n Body[bln] = ad*len(L2)\n elif len(ad_)==2 and len(ad)==2:\n Body[bln-1] = ad[0]*len(L1)\n Body[bln+1] = ad[0]*len(L3)\n elif len(ad_)==1 and len(ad)==2:\n # change underline if different\n if not ad_ == ad[0]:\n Body[bln] = ad[0]*len(L2)\n # insert overline; current bnode doesn't change\n Body[bln-1:bln-1] = [ad[0]*len(L2)]\n update_bnodes(VO, i+1, 1)\n b_delta+=1\n elif len(ad_)==2 and len(ad)==1:\n # change underline if different\n if not ad_[0] == ad:\n Body[bln+1] = ad*len(L3)\n # remove headline inset if any\n if not len(L2) == len(L2.lstrip()):\n Body[bln] = L2.lstrip()\n # check if line before overline is blank\n if bln >1:\n L0 = Body[bln-2].rstrip()\n else:\n L0 = ''\n # there is blank before overline\n # delete overline; current bnode doesn't change\n if not L0:\n Body[bln-1:bln] = []\n update_bnodes(VO, i+1, -1)\n b_delta-=1\n # there is no blank before overline\n # change overline to blank; only current bnode needs updating\n else:\n Body[bln-1] = ''\n bnodes[i-1]+=1\n\n ### Prevent loss of first headline: make sure it is preceded by a blank line\n blnum1 = bnodes[tlnum1-1]\n if blnum1 > 1 and Body[blnum1-2].strip():\n Body[blnum1-1:blnum1-1] = ['']\n update_bnodes(VO, tlnum1 ,1)\n b_delta+=1\n\n ### After 'down' : insert blank line if there is none\n # between the nodes used to be separated by the moved region.\n if oop=='down' and (0 < blnumCut < Z) and Body[blnumCut-1].strip():\n Body[blnumCut:blnumCut] = ['']\n update_bnodes(VO, tlnumCut+1 ,1)\n b_delta+=1\n\n assert len(Body) == Z + b_delta\n\n"
},
{
"alpha_fraction": 0.5504322648048401,
"alphanum_fraction": 0.5946205854415894,
"avg_line_length": 31.5,
"blob_id": "3d365411ad1e606540ddbde6704645f080ab0482",
"content_id": "5de5cb4ecaed64e98b696ac7172047a4bb52d1ed",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1041,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 32,
"path": "/pylib/snippet_helpers.py",
"repo_name": "hertogp/vimdir",
"src_encoding": "UTF-8",
"text": "\"\"\"\nNormally this would go into ~/.vim/pythonx directory, but for some reason\nthis dir is not on my sys.path at the moment (see :py import sys; print\nsys.path<CR>). However, directory ~/.vim/pylib is present on the path, so the\nsnippets_helper.py (note: in snippets file do \"from snippet_helpers import *\")\nto import all functions defined here.\n\n\"\"\"\nfrom datetime import date, timedelta\n\ndef ywd_isodate(year, week, dow):\n try:\n year, week, dow = int(year), int(week), int(dow)\n y0, w0, d0 = date(year, 1, 1).isocalendar()\n return (date(year, 1, 1) + timedelta(weeks=week-w0, days=dow-d0)).isoformat()\n except Exception, e:\n return \"YYYY-MM-DD?\"\n\nADDR = {'PHE.cell': '06-10111001',\n 'PHE.mail1': '[email protected]',\n 'PHE.mail2': '[email protected]',\n 'QHE1': '123123123',\n 'QRE1': '567567567567'\n }\n\ndef addr(t):\n if t:\n o = [k for k in ADDR.keys() if k.startswith(t)]\n else:\n o = ADDR.keys()\n if len(o) == 1: return ADDR[o[0]]\n return \"(\" + '\\n'.join(o) + \")\"\n\n"
}
] | 3 |
RichealYoung/myutil | https://github.com/RichealYoung/myutil | 05212da5a9ef20f48df9bcf1261cfcf8f7095ca4 | 6803e213c69b9f20307dbdf835c8293d5ec7a45f | b7a5a42eac71f9fa06970c2a995e963fe5733fc1 | refs/heads/main | 2023-05-03T13:56:57.606232 | 2021-05-22T02:23:38 | 2021-05-22T02:23:38 | 329,536,938 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.614506185054779,
"alphanum_fraction": 0.6342592835426331,
"avg_line_length": 35.264366149902344,
"blob_id": "5c5507182fe4e54196db7ee069a888994dee6a41",
"content_id": "ff8a6f5686de68b53c9a3220973bb69ed203b6bf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3240,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 87,
"path": "/io_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport cv2\r\nfrom multiprocessing import Pool\r\nimport os\r\nfrom os.path import join as opj\r\ndef gen_pathlist_fromimgdir(imgdir)->list:\r\n imgnamelist=os.listdir(imgdir)\r\n imgpathlist=[opj(imgdir,imgname) for imgname in imgnamelist]\r\n imgpathlist.sort()\r\n return imgpathlist\r\ndef gen_pathlist_fromimgdirdir(imgdirdir)->list:\r\n imgpathlist=[]\r\n imgdirnamelist=os.listdir(imgdirdir)\r\n imgdirlist=[opj(imgdirdir,imgdirname) for imgdirname in imgdirnamelist]\r\n imgdirlist.sort()\r\n for imgdir in imgdirlist:\r\n imgnamelist=os.listdir(imgdir)\r\n imgpathlist_=[opj(imgdir,imgname) for imgname in imgnamelist]\r\n imgpathlist_.sort()\r\n imgpathlist.extend(imgpathlist_)\r\n return imgpathlist\r\ndef read_any8img(imgpath)->np.ndarray:\r\n img=cv2.imdecode(np.fromfile(imgpath,dtype=np.uint8),-1)\r\n return img\r\ndef read_raw16img(imgpath)->np.ndarray:\r\n # return np.uint16\r\n with open(imgpath, 'rb') as fid:\r\n data_chunk = fid.read()\r\n img = np.frombuffer(data_chunk, dtype=np.uint16)\r\n return img\r\ndef read_raw12img(imgpath)->np.ndarray:\r\n # return np.uint16\r\n with open(imgpath, 'rb') as fid:\r\n data_chunk = fid.read()\r\n data = np.frombuffer(data_chunk, dtype=np.uint8)\r\n fst_uint8, mid_uint8, lst_uint8 = np.reshape(data, (data.shape[0] // 3, 3)).astype(np.uint16).T\r\n fst_uint12 = (fst_uint8 << 4) + (mid_uint8 >> 4)\r\n snd_uint12 = ((mid_uint8 % 16) << 8) + lst_uint8\r\n img = np.reshape(np.concatenate((fst_uint12[:, None], snd_uint12[:, None]), axis=1), 2 * fst_uint12.shape[0])\r\n return img\r\ndef read_multiproc(imgdir,proc_count,read_func,save_func,img_count=None):\r\n '''\r\n You have to write your own read_func and save_func in the \"main\" function like below:\r\n def read_func(i,imgpath):\r\n img=io_util.read_raw16img(imgpath)\r\n return [i,img]\r\n def save_func(i_img):\r\n global img_data,img_shape\r\n i=i_img[0]\r\n img=i_img[1]\r\n img_data[:,:,i]=img.reshape((*img_shape))\r\n '''\r\n pool = Pool(proc_count)\r\n imglist=os.listdir(imgdir)\r\n if img_count!=None:\r\n imgpath_list=[opj(imgdir,img) for img in imglist][0:img_count]\r\n else:\r\n imgpath_list=[opj(imgdir,img) for img in imglist]\r\n for i,imgpath in enumerate(imgpath_list):\r\n pool.apply_async(read_func, args=(i,imgpath),callback=save_func)\r\n pool.close()\r\n pool.join()\r\ndef read_multiproc_from_imgpath_list(imgpath_list,proc_count,read_func,save_func):\r\n '''\r\n You have to write your own read_func and save_func in the \"main\" function like below:\r\n def read_func(i,imgpath):\r\n img=io_util.read_raw16img(imgpath)\r\n return [i,img]\r\n def save_func(i_img):\r\n global img_data,img_shape\r\n i=i_img[0]\r\n img=i_img[1]\r\n img_data[:,:,i]=img.reshape((*img_shape))\r\n '''\r\n pool = Pool(proc_count)\r\n for i,imgpath in enumerate(imgpath_list):\r\n pool.apply_async(read_func, args=(i,imgpath),callback=save_func)\r\n pool.close()\r\n pool.join()\r\ndef save_any8img(img,imgpath):\r\n \"\"\"save 8bit img\r\n\r\n Args:\r\n img : 0-255\r\n imgpath\r\n \"\"\"\r\n cv2.imencode('.png', img.astype(np.uint8))[1].tofile(imgpath)"
},
{
"alpha_fraction": 0.6557231545448303,
"alphanum_fraction": 0.6743566989898682,
"avg_line_length": 28.405405044555664,
"blob_id": "8fac975113610be3823acff80bcdab413f7483ff",
"content_id": "bc4b84e3fa5b6da40a2dd9f7f4ef8b3031fb5f91",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1167,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 37,
"path": "/optic_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport matplotlib.pylab as plt\r\nimport cv2\r\nfrom skimage.metrics import structural_similarity as ssim\r\nfrom skimage.metrics import peak_signal_noise_ratio as psnr\r\nimport os\r\nfrom os.path import join as opj\r\nfrom os.path import dirname as opd\r\nfrom tqdm import tqdm\r\ndef set_ap(scene,ap):\r\n scene=scene.astype(np.float64)\r\n H,W=scene.shape\r\n photon_count=ap*H*W\r\n grey_count=scene.sum()\r\n photon_per_grey=photon_count/grey_count\r\n scene_ptn=scene*photon_per_grey\r\n return scene_ptn\r\ndef ptn2u_mag(ptn,alpha):#TODO 未从理论上验证准确性\r\n # ptn \\propto u2, assume ptn=alpha*u2\r\n # u2 =u_mag**2\r\n u2=ptn/alpha\r\n u_mag=np.sqrt(u2)\r\n return u_mag\r\ndef u2ptn(u,alpha):#TODO 未从理论上验证准确性\r\n # ptn \\propto u2, assume ptn=alpha*u2\r\n # u2 =u_mag**2\r\n u_mag=np.abs(u)\r\n u2=u_mag**2\r\n ptn=u2*alpha\r\n return ptn\r\ndef op2fp(op_u):\r\n # simulate the fourier plane's complex amplitude from the object plane's complex amplitude\r\n fp_u=np.fft.fftshift(np.fft.fft2(op_u))\r\n cor_factor=1/np.sqrt(fp_u.size)\r\n # energy consistent\r\n fp_u=fp_u*cor_factor\r\n return fp_u\r\n\r\n"
},
{
"alpha_fraction": 0.5965388417243958,
"alphanum_fraction": 0.6202918291091919,
"avg_line_length": 31.89655113220215,
"blob_id": "79f0f089fa08b6a484e19cd99a380b72f80e7957",
"content_id": "04d6c01894a550f9cbe39c8141b515635a731977",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2947,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 87,
"path": "/plot_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport matplotlib.pylab as plt\r\nimport cv2\r\nfrom skimage.metrics import structural_similarity as ssim\r\nfrom skimage.metrics import peak_signal_noise_ratio as psnr\r\nimport os\r\nfrom os.path import join as opj\r\nfrom os.path import dirname as opd\r\nfrom tqdm import tqdm\r\ndef plot(img,title=\"\",savename=\"\",savedir=None):\r\n plt.figure()\r\n plt.title(title)\r\n plt.imshow(img,vmax=img.max(),vmin=0)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()\r\ndef plot12(img1,img2,title1=\"\",title2=\"\",title=\"\",savename=\"\",savedir=None):\r\n fig = plt.figure()\r\n fig.suptitle(title)\r\n plt.subplot(121)\r\n plt.title(title1)\r\n plt.imshow(img1,vmax=img1.max(),vmin=0)\r\n plt.subplot(122)\r\n plt.title(title2)\r\n plt.imshow(img2,vmax=img2.max(),vmin=0)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()\r\ndef plot_hist(array,bins=None,title='',savename=\"\",savedir=None):\r\n plt.figure()\r\n plt.title(title)\r\n if bins!=None:\r\n plt.hist(array,bins=bins)\r\n else:\r\n plt.hist(array)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()\r\ndef plot_matrix(matrix,cmap='viridis_r',vmin=None,vmax=None,text=False,title='',savename=\"\",savedir=None):\r\n plt.figure(figsize=(20,20))\r\n plt.title(title)\r\n if vmin!=None and vmax!=None:\r\n plt.imshow(matrix,cmap=cmap,vmin=vmin,vmax=vmax)\r\n else:\r\n plt.imshow(matrix,cmap=cmap)\r\n plt.colorbar(shrink=0.8)\r\n if text:\r\n for i in range(matrix.shape[0]):\r\n for j in range(matrix.shape[1]):\r\n plt.text(j, i, \"{:.2f}\".format(matrix[i, j]),\r\n ha=\"center\", va=\"center\", color=\"w\",size=8)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()\r\ndef plot_boxplot(array,showfliers=True,whis=1.5,flierprops=None,title='',savename=\"\",savedir=None):\r\n plt.figure()\r\n plt.title(title)\r\n plt.boxplot(array,showfliers=showfliers,whis=whis,flierprops=flierprops)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()\r\n\r\ndef plot12_boxplot(array1,array2,showfliers=True,whis=1.5,flierprops=None,\r\n title1=\"\",title2=\"\",title=\"\",savename=\"\",savedir=None):\r\n fig = plt.figure()\r\n fig.suptitle(title)\r\n plt.subplot(121)\r\n plt.title(title1)\r\n plt.boxplot(array1,showfliers=showfliers,whis=whis,flierprops=flierprops)\r\n plt.subplot(122)\r\n plt.title(title2)\r\n plt.boxplot(array2,showfliers=showfliers,whis=whis,flierprops=flierprops)\r\n if savedir!=None:\r\n plt.savefig(opj(savedir,savename+'.png'),dpi=200)\r\n else:\r\n plt.show()\r\n plt.close()"
},
{
"alpha_fraction": 0.6527777910232544,
"alphanum_fraction": 0.6527777910232544,
"avg_line_length": 31.05555534362793,
"blob_id": "64bd2ee8a1ca730e56a11cf4c6dba1ebc8f413c8",
"content_id": "93255141c000174f9fa8d993495284554752ce2b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 576,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 18,
"path": "/quality_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom skimage.metrics import structural_similarity as ssim\nfrom skimage.metrics import peak_signal_noise_ratio as psnr\ndef cal_psnrssim(img_gt,img_hat):\n \"\"\"[summary]\n\n Args:\n img_gt ([type]): H W C\n img_hat ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n # img_hat=img_hat*img_gt.mean()/img_hat.mean()\n H,W,C=img_gt.shape\n img_hat_psnr=psnr(img_gt,img_hat,data_range=img_gt.max())\n img_hat_ssim = ssim(img_gt,img_hat,data_range=img_gt.max(),multichannel=True)\n return img_hat_psnr,img_hat_ssim"
},
{
"alpha_fraction": 0.6161107420921326,
"alphanum_fraction": 0.626809298992157,
"avg_line_length": 32.82978820800781,
"blob_id": "611194c427fe32f1a8adb1133464653c26042a33",
"content_id": "2e0404a032bab93e876d94231d6e1761df5fb597",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1589,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 47,
"path": "/probability_statistics_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom multiprocessing import Pool\nimport dcor\ndef cal_R2(y,yhat):\n #https://en.wikipedia.org/wiki/Coefficient_of_determination\n SStot=np.sum((y-y.mean(0))**2,0)\n SSres=np.sum((yhat-y)**2,0)\n R2=1-SSres/SStot\n return R2\ndef cal_dCor(x,y):\n #https://github.com/vnmabus/dcor\n return dcor.distance_correlation(x,y, method='AVL')\ndef cal_KL(sample1,sample2):\n return 0 #TODO\ndef cal_list_multiproc(x,y_list,proc_count,cal_func,save_func):\n '''\n You have to write your own cal_func and save_func in the \"main\" function like below:\n def cal_func(i,x,y):\n value=probability_statistics_util.cal_dCor(x,y)\n return [i,value]\n def save_func(i_value):\n global value_list\n value_list[i_value[0]]]=i_value[1]\n '''\n pool = Pool(proc_count)\n for i,y in enumerate(y_list):\n pool.apply_async(cal_func, args=(i,x,y),callback=save_func)\n pool.close()\n pool.join()\ndef cal_matrix_multiproc(x,y_matrix,proc_count,cal_func,save_func):\n '''\n You have to write your own cal_func and save_func in the \"main\" function like below:\n def cal_func(i,j,x,y):\n value=probability_statistics_util.cal_dCor(x,y)\n return [i,j,value]\n def save_func(i_j_value):\n global value_matrix\n value_matrix[i_j_value[0],i_j_value[1]]]=i_j_value[2]\n '''\n pool = Pool(proc_count)\n _,H,W=y_matrix.shape\n for i in range(H):\n for j in range(W):\n y=y_matrix[:,i,j]\n pool.apply_async(cal_func, args=(i,j,x,y),callback=save_func)\n pool.close()\n pool.join()"
},
{
"alpha_fraction": 0.5520667433738708,
"alphanum_fraction": 0.558690071105957,
"avg_line_length": 35.23555374145508,
"blob_id": "a40aa97c40b477ea159dde40e0d564061491de68",
"content_id": "e6dcc46fb002215d31b0e0a3b5d145458620d184",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8153,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 225,
"path": "/transform_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import cv2\nimport numpy as np\nimport random\nimport torch\nfrom einops import rearrange\nclass Transform:\n def __init__(self,operator_list,args_list):\n self.operator_instance_list=[]\n assert len(operator_list)==len(args_list)\n for operator,args in zip(operator_list,args_list):\n operator_instance=operator(**args)\n if operator_instance.check():\n self.operator_instance_list.append(operator_instance)\n def __call__(self,img_list):\n for operator_instance in self.operator_instance_list:\n img_list = operator_instance(img_list)\n return img_list\nclass Crop:\n def __init__(self,crop_h,crop_w,crop_h_start,crop_w_start,mod_by=0):\n self.crop_h=crop_h\n self.crop_w=crop_w\n self.crop_h_start=crop_h_start\n self.crop_w_start=crop_w_start\n self.mod_by=mod_by\n def check(self):\n if (self.crop_h and self.crop_w) or self.mod_by:\n return True\n else:\n print('not crop')\n return False\n def __call__(self,img_list,):\n \"\"\" crop every imgs in img_list\n\n Args:\n img_list (list): every imgs in img_list must have shape=[H,W,C]\n\n Returns:\n list: a list containing all imgs which are cropped\n \"\"\"\n img_list_cropped=[]\n H, W, C = img_list[0].shape\n if self.crop_h and self.crop_w:\n crop_h = min(self.crop_h, H - self.crop_h_start)\n crop_w = min(self.crop_w, W - self.crop_w_start) \n for img in img_list:\n if self.mod_by:\n crop_h = (crop_h // self.mod_by) * self.mod_by\n crop_w = (crop_w // self.mod_by) * self.mod_by\n img_list_cropped.append(img[self.crop_h_start:self.crop_h_start + crop_h,\n self.crop_w_start:self.crop_w_start + crop_w, :])\n elif self.mod_by:\n for img in img_list:\n if self.mod_by:\n crop_h = (H // self.mod_by) * self.mod_by\n crop_w = (W // self.mod_by) * self.mod_by\n img_list_cropped.append(img[0:0 + crop_h,\n 0:0 + crop_w, :])\n else:\n img_list_cropped = img_list\n return img_list_cropped\nclass RandomCrop:\n def __init__(self,randomcrop):\n self.randomcrop=randomcrop\n def check(self):\n if self.randomcrop:\n return True\n else:\n print('not randomcrop')\n return False\n def __call__(self,img_list,):\n \"\"\" randomcrop every imgs in img_list\n\n Args:\n img_list (list): every imgs in img_list must have shape=[H,W,C]\n\n Returns:\n list: a list containing all imgs which are randomcropped\n \"\"\"\n H, W, C = img_list[0].shape\n randomcrop_h_start = random.randint(0, max(0, H - self.randomcrop))\n randomcrop_w_start = random.randint(0, max(0, W - self.randomcrop))\n randomcrop=Crop(self.randomcrop,self.randomcrop,randomcrop_h_start,randomcrop_w_start)\n return randomcrop(img_list)\nclass Resize:\n def __init__(self,resize_h,resize_w):\n self.resize_h=resize_h\n self.resize_w=resize_w\n def check(self):\n if self.resize_h and self.resize_w:\n return True\n else:\n print('not resize')\n return False\n def __call__(self,img_list,):\n \"\"\" resize every imgs in img_list\n\n Args:\n img_list (list):\n\n Returns:\n list: a list containing all imgs which are resized\n \"\"\"\n \n img_list_resized = [cv2.resize(img, dsize=(self.resize_w, self.resize_h)) for img in img_list]\n # if an img's shape=[H,W,1], then cropped img's shape will be [H,W]\n img_list_resized = [img[...,np.newaxis] for img in img_list_resized if len(img.shape)==2]\n return img_list_resized\n\nclass AtleastResize:\n def __init__(self,atleast_h,atleast_w):\n self.atleast_h=atleast_h\n self.atleast_w=atleast_w\n def check(self):\n if self.atleast_h and self.atleast_w:\n return True\n else:\n print('not atleastresize')\n return False\n def __call__(self,img_list,):\n \"\"\" resize every imgs in img_list if img_h < atleast_h or img_w < atleast_w\n\n Args:\n img_list (list):\n\n Returns:\n list: a list containing all imgs which are resized or not\n \"\"\"\n def atleastresize(img):\n H,W,_=img.shape\n if H>=self.atleast_h and W>=self.atleast_w:\n return img\n elif H>=self.atleast_h and W<self.atleast_w:\n return cv2.resize(img, dsize=(self.atleast_w,H))\n elif H<self.atleast_h and W>=self.atleast_w:\n return cv2.resize(img, dsize=(W,self.atleast_h))\n elif H<self.atleast_h and W<self.atleast_w:\n return cv2.resize(img, dsize=(self.atleast_w,self.atleast_h))\n def check(img):\n if len(img.shape)==2:\n return img[...,np.newaxis]\n else:\n return img\n img_list_resized = list(map(atleastresize,img_list))\n # if an img's shape=[H,W,1], then cropped img's shape will be [H,W]\n img_list_resized = list(map(check,img_list_resized))\n return img_list_resized\nclass FlipRoat:\n def __init__(self,fliprot):\n self.fliprot=fliprot\n def check(self):\n if self.fliprot:\n return True\n else:\n print('not fliproat')\n return False\n def __call__(self,img_list,):\n hflip = random.random() < 0.5\n vflip = random.random() < 0.5\n rot90 = random.random() < 0.5\n return [fliproat_img(img, hflip,vflip,rot90) for img in img_list]\ndef fliproat_img(img, hflip,vflip, rot90):\n if hflip:\n img = img[:, ::-1, :]\n if vflip:\n img = img[::-1, :, :]\n if rot90:\n img = img.transpose(1, 0, 2)\n return img\nclass Normalize:\n def __init__(self,mean,std,range):\n self.mean=mean\n self.std=std\n self.range=range\n def check(self):\n if self.mean==0 and self.std==1 and self.range==1:\n print('not normalize')\n return False\n else:\n return True\n def __call__(self,img_list,):\n return [(img.astype(np.float64)/self.range-self.mean)/self.std for img in img_list]\nclass Ratio:\n def __init__(self,ratio):\n self.ratio=ratio\n def check(self):\n if self.ratio==1:\n print('not ratio')\n return False\n else:\n return True\n def __call__(self,img_list,):\n return [img.astype(np.float64)*self.ratio for img in img_list]\nclass ToTensor:\n def __init__(self,layout=None):\n self.layout=layout\n def check(self):\n return True\n def __call__(self,img_list,):\n if self.layout == None:\n return [torch.from_numpy(img).type(torch.FloatTensor) for img in img_list]\n else:\n return [torch.from_numpy(rearrange(img,self.layout)).type(torch.FloatTensor) for img in img_list]\nclass ListToTensor:\n def __init__(self,layout=None):\n self.layout=layout\n def check(self):\n return True\n def __call__(self,img_list,):\n if self.layout == None:\n return torch.cat([torch.from_numpy(img).type(torch.FloatTensor).unsqueeze(0) for img in img_list])\n else:\n return rearrange(torch.cat([torch.from_numpy(img).type(torch.FloatTensor).unsqueeze(0) for img in img_list]),self.layout)\n\ndef crop2batch(img_list,cropsize=3):\n imgbatch_list=[]\n pad_size=cropsize//2\n for img in img_list:\n H,W,_=img.shape\n img_pad=np.pad(img,[[pad_size,pad_size],[pad_size,pad_size],[0,0]])\n for h in range(pad_size,H+pad_size):\n for w in range(pad_size,W+pad_size):\n imgcrop=img_pad[h-pad_size:h-pad_size+cropsize,w-pad_size:w-pad_size+cropsize,:]\n imgcrop=imgcrop.flatten()\n imgbatch_list.append(imgcrop)\n return imgbatch_list\n"
},
{
"alpha_fraction": 0.8024691343307495,
"alphanum_fraction": 0.8024691343307495,
"avg_line_length": 26,
"blob_id": "4ac89cf7534a3c7e5c125e6e9918d52b8a09ff3c",
"content_id": "9026829dbf44d6ba172aab8a866d7c766742cdf7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 81,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 3,
"path": "/README.md",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "# myutil\nThe collection of common use functions in my scientific research\n# test\n"
},
{
"alpha_fraction": 0.5375970005989075,
"alphanum_fraction": 0.5573989748954773,
"avg_line_length": 34.656864166259766,
"blob_id": "d7ae0528584876d6e1096fc173abb49add1aecb7",
"content_id": "59bd04a3df01a4dfb9d576e74db8d7b35b081bfe",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3801,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 102,
"path": "/phase_retrieval_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport matplotlib.pylab as plt\r\ndef fienup_phase_retrieval(mag, mask=None, beta=0.8, \r\n steps=200, mode='hybrid', verbose=True):\r\n #TODO 算法缺点,傅里叶面成像会造成精度损失,fienup无法在精度较低的幅值上重建\r\n \"\"\"\r\n Implementation of Fienup's phase-retrieval methods. This function\r\n implements the input-output, the output-output and the hybrid method.\r\n \r\n Note: Mode 'output-output' and beta=1 results in \r\n the Gerchberg-Saxton algorithm.\r\n \r\n Parameters:\r\n mag: Measured magnitudes of Fourier transform\r\n mask: Binary array indicating where the image should be\r\n if padding is known\r\n beta: Positive step size\r\n steps: Number of iterations\r\n mode: Which algorithm to use\r\n (can be 'input-output', 'output-output' or 'hybrid')\r\n verbose: If True, progress is shown\r\n \r\n Returns:\r\n x: Reconstructed image\r\n \r\n Author: Tobias Uelwer\r\n Date: 30.12.2018\r\n \r\n References:\r\n [1] E. Osherovich, Numerical methods for phase retrieval, 2012,\r\n https://arxiv.org/abs/1203.4756\r\n [2] J. R. Fienup, Phase retrieval algorithms: a comparison, 1982,\r\n https://www.osapublishing.org/ao/abstract.cfm?uri=ao-21-15-2758\r\n [3] https://github.com/cwg45/Image-Reconstruction\r\n \"\"\"\r\n \r\n assert beta > 0, 'step size must be a positive number'\r\n assert steps > 0, 'steps must be a positive number'\r\n assert mode == 'input-output' or mode == 'output-output'\\\r\n or mode == 'hybrid',\\\r\n 'mode must be \\'input-output\\', \\'output-output\\' or \\'hybrid\\''\r\n \r\n if mask is None:\r\n mask = np.ones(mag.shape)\r\n \r\n assert mag.shape == mask.shape, 'mask and mag must have same shape'\r\n \r\n # sample random phase and initialize image x \r\n y_hat = mag*np.exp(1j*2*np.pi*np.random.rand(*mag.shape))\r\n x = np.zeros(mag.shape)\r\n \r\n # previous iterate\r\n x_p = None\r\n \r\n # main loop\r\n for i in range(1, steps+1):\r\n # show progress\r\n if i % 100 == 0 and verbose: \r\n print(\"step\", i, \"of\", steps)\r\n \r\n # inverse fourier transform\r\n y = np.real(np.fft.ifft2(y_hat))\r\n \r\n # previous iterate\r\n if x_p is None:\r\n x_p = y\r\n else:\r\n x_p = x \r\n \r\n # updates for elements that satisfy object domain constraints\r\n if mode == \"output-output\" or mode == \"hybrid\":\r\n x = y\r\n \r\n # find elements that violate object domain constraints \r\n # or are not masked\r\n indices = np.logical_or(np.logical_and(y<0, mask), \r\n np.logical_not(mask))\r\n \r\n # updates for elements that violate object domain constraints\r\n if mode == \"hybrid\" or mode == \"input-output\":\r\n x[indices] = x_p[indices]-beta*y[indices] \r\n elif mode == \"output-output\":\r\n x[indices] = y[indices]-beta*y[indices] \r\n \r\n # fourier transform\r\n x_hat = np.fft.fft2(x)\r\n \r\n # satisfy fourier domain constraints\r\n # (replace magnitude with input magnitude)\r\n y_hat = mag*np.exp(1j*np.angle(x_hat))\r\n return x\r\ndef recbyphaseretrival(image):\r\n image_padded = np.pad(image, 256, 'constant')\r\n magnitudes_oversampled = np.abs(np.fft.fft2(image_padded))\r\n mask = np.pad(np.ones((512,512)), 256, 'constant')\r\n result_oversampled = fienup_phase_retrieval(magnitudes_oversampled,\r\n steps=1000,\r\n mask=mask,\r\n verbose=True)\r\n plt.figure()\r\n plt.imshow(result_oversampled)\r\n plt.show()"
},
{
"alpha_fraction": 0.6364902257919312,
"alphanum_fraction": 0.6601671576499939,
"avg_line_length": 33.14285659790039,
"blob_id": "1192ee2465150b8b73c365c6e903d7b508956916",
"content_id": "b7e32ccf8b0ed324b25f1181fb4c08a033a8021e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 718,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 21,
"path": "/calibrate_sensor_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom myutil.probability_statistics_util import cal_R2\n\ndef calibrate_alpha_beta(t,X):\n '''\n Use Least Square method to applying \"point estimate\" on alpha and beta,\n where X[k]=alpha*L*t[k]+beta\n '''\n cal_t_count=t.shape[0]\n _,H,W=X.shape\n t=t.reshape(-1,1)\n A=np.concatenate([t,np.ones((cal_t_count,1))],1)\n ls_estimation=np.linalg.inv(A.T@A)@[email protected](cal_t_count,-1)\n ls_estimation=ls_estimation.reshape(2,H,W)\n alpha_L=ls_estimation[0]\n beta=ls_estimation[1]\n # calculate the Coefficient_of_determination\n X_hat=alpha_L.reshape(1,H,W)*t.reshape(cal_t_count,1,1)+beta.reshape(1,H,W)\n R2=cal_R2(X,X_hat) \n alpha=alpha_L\n return alpha,beta,R2\n\n"
},
{
"alpha_fraction": 0.5959252715110779,
"alphanum_fraction": 0.6112054586410522,
"avg_line_length": 38.33333206176758,
"blob_id": "0e5c6053bd04a3b9ae86209803a1918c8c30e67d",
"content_id": "6cfbfd52fc6a067e51599d47fba671f988c90a03",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 589,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 15,
"path": "/loss_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import torch\ndef tv_loss(img, tv_weight=5e-2):\n \"\"\"\n Compute total variation loss.\n Inputs:\n - img: PyTorch Variable of shape (1, C, H, W) holding an input image.\n - tv_weight: Scalar giving the weight w_t to use for the TV loss.\n Returns:\n - loss: PyTorch Variable holding a scalar giving the total variation loss\n for img weighted by tv_weight.\n \"\"\"\n w_variance = torch.sum(torch.pow(img[:,:,:,:-1] - img[:,:,:,1:], 2))\n h_variance = torch.sum(torch.pow(img[:,:,:-1,:] - img[:,:,1:,:], 2))\n loss = tv_weight * (h_variance + w_variance)\n return loss"
},
{
"alpha_fraction": 0.5663667321205139,
"alphanum_fraction": 0.6001124978065491,
"avg_line_length": 32.90196228027344,
"blob_id": "63c79f31fcc2349c56d28babe74a79150f74555e",
"content_id": "6f57a06f07a7ba243f6c3c020bae58a884824db1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1916,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 51,
"path": "/isp_util.py",
"repo_name": "RichealYoung/myutil",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\ndef gen_img_ptn(img,ap):\r\n \"\"\"generate img_ptn from given image and average photon number\r\n\r\n Args:\r\n img : image\r\n ap :average photon number, img_ptn will have #ap photons per pixel\r\n\r\n Returns:\r\n img_ptn will have #ap photons per pixel\r\n \"\"\"\r\n img_ptn = img/img.mean()*ap\r\n return img_ptn\r\ndef emccd_isp(img_ptn,EMgain=300,addnoise=True,damp=False,clip=True):\r\n #### 1. config\r\n QE = 0.9\r\n readout = 139\r\n c = 0.00145 # spurious charge\r\n e_per_edu = 0.1866\r\n baseline = 500\r\n EMgain = 300\r\n ptn_max=((65535-baseline)/(e_per_edu*EMgain)-c)/QE\r\n #TODO 确保只有零频分量可以饱和,其余值必须被准确测量,即不能饱和,但是由于受噪声影响,也不能完全保证\r\n if damp:\r\n damp_ratio=np.sort(img_ptn.flatten())[-2]/ptn_max*1.1\r\n img_ptn=img_ptn/damp_ratio\r\n #### 2. add noise (related to ptn)\r\n if addnoise:\r\n img_ptn_electric = QE * img_ptn + c\r\n img_ptn_electric[img_ptn_electric<1e-6] = 1e-6\r\n n_ie = np.random.poisson(lam=img_ptn_electric, size=img_ptn.shape)\r\n n_oe = np.random.gamma(shape=n_ie, scale=EMgain, size=img_ptn.shape)\r\n #### 3. add noise (readout)\r\n n_oe = n_oe + np.random.normal(loc=0, scale=readout, size=img_ptn.shape)\r\n else:\r\n n_oe=(QE * img_ptn + c)*EMgain\r\n #### 4. ptn --> value\r\n ADU_out = np.floor(np.dot(n_oe, e_per_edu) + baseline)\r\n ADU_out = np.dot(n_oe, e_per_edu) + baseline\r\n #### 5. clip\r\n # print(ADU_out[ADU_out>65535])\r\n if clip:\r\n ADU_out=ADU_out.clip(0,65535)\r\n return ADU_out\r\n\r\ndef inv_emccd_isp(ADU_out,error_baseline=0):#TODO 与photon保持相同的比值即可,因此偏置一定要准确知道\r\n baseline = 500\r\n baseline=(1-error_baseline)*baseline\r\n img_ptn=ADU_out-baseline\r\n img_ptn=img_ptn.clip(0,np.inf)\r\n return img_ptn"
}
] | 11 |
pushkar201851095/django3todo | https://github.com/pushkar201851095/django3todo | 602f2c5e9e45d570dac4e0747db68a495e0da57f | 55307bd3fc6189882d51eb95ea39940ee78258cb | 8b87943e137007b2ff230d1fa5165a2aa0ee2c96 | refs/heads/master | 2022-12-21T15:26:12.769688 | 2020-09-28T05:52:50 | 2020-09-28T05:52:50 | 296,399,236 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4820936620235443,
"alphanum_fraction": 0.5674931406974792,
"avg_line_length": 19.16666603088379,
"blob_id": "e42bc8e175a8dcdd5b486e6119ece779e48de00a",
"content_id": "19263ca60ea4521c710ad44de663a785bac9dcff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 18,
"path": "/td/migrations/0003_auto_20200924_2344.py",
"repo_name": "pushkar201851095/django3todo",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.7 on 2020-09-24 18:14\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('td', '0002_auto_20200923_2136'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='todo',\n old_name='importanat',\n new_name='important',\n ),\n ]\n"
}
] | 1 |
joji-harada/TechReview | https://github.com/joji-harada/TechReview | e709926b4cb950743bf751378cf302df41d23933 | a24a2ae76e3215aafa81ffaaa04c19aa0452a950 | 5527dd889e3aab5a7e29ddd5ae15703a16a5aa21 | refs/heads/master | 2020-05-04T23:46:14.795345 | 2019-04-28T21:52:03 | 2019-04-28T21:52:03 | 179,554,698 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6944444179534912,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 17,
"blob_id": "4e56bcdca74a72fc4e0f55bfc977ccb7a62a6a9e",
"content_id": "f2d2e0e4fe0b573b0895fb42e2d713d0422ab20c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 36,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 2,
"path": "/README.md",
"repo_name": "joji-harada/TechReview",
"src_encoding": "UTF-8",
"text": "# TechReview\nClass work for ITC 172\n"
},
{
"alpha_fraction": 0.7130434513092041,
"alphanum_fraction": 0.7130434513092041,
"avg_line_length": 27.625,
"blob_id": "ca29361dbbb3083332c8160609387c748be35c0d",
"content_id": "6b34fbbc03d8254e14d41c7dd3863a425e299908",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 8,
"path": "/techreviewproj/techapp/urls.py",
"repo_name": "joji-harada/TechReview",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views\n\n#takes proj urls include and transfers it to the views render request\nurlpatterns=[\n path('', views.index, name='index'),\n path('getTypes/', views.getTypes, name='types')\n]\n\n"
},
{
"alpha_fraction": 0.7359550595283508,
"alphanum_fraction": 0.7359550595283508,
"avg_line_length": 28.75,
"blob_id": "4988097420325f1bc0e92c7f4701da48e8f6a771",
"content_id": "a85bb2e19c323f2830e658b6aab9712d5aa75b84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 356,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 12,
"path": "/techreviewproj/techapp/views.py",
"repo_name": "joji-harada/TechReview",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom .models import ProductType, Product, Review\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'techapp/index.html')\n\ndef getTypes(request):\n types_list = ProductType.objects.all()\n context = {'types_list' : types_list}\n return render(request, 'techapp/types.html', context=context)"
}
] | 3 |
Travis-Simmons/plyworker_recreation | https://github.com/Travis-Simmons/plyworker_recreation | 5494568137d069738e07ba1ad1f677af87fd830f | 5d3e6e102ac4ff424feec7c764e7ac077d456f34 | e71eb922a95910e0e49204b91e26a0cc0be91d6f | refs/heads/main | 2023-08-21T18:00:55.538713 | 2021-10-10T02:20:33 | 2021-10-10T02:20:33 | 415,466,080 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6514598727226257,
"alphanum_fraction": 0.6833941340446472,
"avg_line_length": 23.863636016845703,
"blob_id": "b91eba172c0cb81d35b9aa621643b04626dfc8ee",
"content_id": "cfaa8dce85801411923e6b4015fb9c1b917f137d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1096,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 44,
"path": "/plyworkerfoo.py",
"repo_name": "Travis-Simmons/plyworker_recreation",
"src_encoding": "UTF-8",
"text": "\nimport emcee\n\n# (A) ydata = read plyworker pointcloud\n\n\ndef lnprior(p):\n return 0\n\ndef lnlike(p, xdata, ydata):\n\t# (1) run command line with fx = [0] etc.\n # (2) ymodel = read in new point cloud\n lnlikelihood = (-0.5 * ((ymodel - ydata))**2).sum()\n return lnlikelihood\n\ndef lnprob(p):\n lp = lnprior(p)\n if not np.isfinite(lp):\n return -np.inf\n return lp + lnlike(p)\n\n\nndim, nwalkers, nsteps = 4, 14, 10000\n\n\"\"\"\nparameters\n\nfx\nfy\ncx\ncy\n\"\"\"\ninitial_pos_fx = [np.random.uniform(0,1000) for i in range(nwalkers)]\ninitial_pos_fy = [np.random.uniform(0,1000) for i in range(nwalkers)]\ninitial_pos_cx = [np.random.uniform(0,1000) for i in range(nwalkers)]\ninitial_pos_cy = [np.random.uniform(0,1000) for i in range(nwalkers)]\n\npos = [initial_pos_fx, initial_pos_fy, initial_pos_cx, initial_pos_cy]\n\n#xdata = np.asarray(commandline_pointcloud.points)\n#ydata = np.asarray(plyworker_pointcloud.points)\n\n#sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(xdata, ydata))\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=())\nsampler.run_mcmc(pos, nsteps)\n\n"
}
] | 1 |
jmidiri/Coding-Samples | https://github.com/jmidiri/Coding-Samples | 44dcd8975642f4ea795ce79d74f365c40499adb6 | 213b63c9e89b5bf17198088e904ca5936894ed37 | b05cba5f8f03abdae876183ca1926938704994c6 | refs/heads/master | 2020-04-19T21:41:36.725755 | 2019-01-31T02:37:11 | 2019-01-31T02:37:11 | 168,448,946 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5859040021896362,
"alphanum_fraction": 0.6008171439170837,
"avg_line_length": 36.64615249633789,
"blob_id": "92fe2f3078e879af14e98a2982290c12926176db",
"content_id": "f92b60c7675344b2b8d8bf0c894147d5dd7fbc69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4895,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 130,
"path": "/Examples with Python/cf.py",
"repo_name": "jmidiri/Coding-Samples",
"src_encoding": "UTF-8",
"text": "import argparse\nimport re\nimport os\nimport csv\nimport math\nimport collections as coll\n\n\ndef parse_argument():\n \"\"\"\n Code for parsing arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Parsing a file.')\n parser.add_argument('--train', nargs=1, required=True)\n parser.add_argument('--test', nargs=1, required=True)\n args = vars(parser.parse_args())\n return args\n\n\ndef parse_file(filename):\n \"\"\"\n Given a filename outputs user_ratings and movie_ratings dictionaries\n \n The files have the format: MovieID, CustomerID, Rating\n\n Input: filename\n\n Output: user_ratings, movie_ratings\n where:\n user_ratings[user_id] = {movie_id: rating}\n movie_ratings[movie_id] = {user_id: rating}\n \"\"\"\n user_ratings = {}\n movie_ratings = {}\n with open(filename, 'r') as csvfile:\n info_row = csv.reader(csvfile)\n for row in info_row:\n if int(row[1]) in user_ratings:\n user_ratings[int(row[1])][int(row[0])] = float(row[2])\n else:\n user_ratings[int(row[1])] = {int(row[0]): float(row[2])}\n if int(row[0]) in movie_ratings:\n movie_ratings[int(row[0])][int(row[1])] = float(row[2])\n else:\n movie_ratings[int(row[0])] = {int(row[1]): float(row[2])}\n return user_ratings, movie_ratings\n\n\ndef compute_average_user_ratings(user_ratings):\n \"\"\" Given a the user_rating dict compute average user ratings\n\n Input: user_ratings (dictionary of user, movies, ratings)\n Output: ave_ratings (dictionary of user and ave_ratings)\n \"\"\"\n ave_ratings = {}\n for user_key in user_ratings:\n avg = sum(user_ratings[user_key].values())/len(user_ratings[user_key].values())\n ave_ratings[user_key] = avg\n return ave_ratings\n\n\ndef compute_user_similarity(d1, d2, ave_rat1, ave_rat2):\n \"\"\" Computes similarity between two users\n\n Input: d1, d2, (dictionary of user ratings per user) \n ave_rat1, ave_rat2 average rating per user (float)\n Ouput: user similarity (float)\n \"\"\"\n intersect = list(set(d1.keys()).intersection(d2.keys()))\n if len(intersect) == 0:\n return 0.0\n else:\n numerator = 0\n denominator_d1 = 0\n denominator_d2 = 0\n for movieId in intersect:\n numerator += (d1[movieId]-ave_rat1)*(d2[movieId]-ave_rat2)\n denominator_d1 += (d1[movieId]-ave_rat1)**2\n denominator_d2 += (d2[movieId]-ave_rat2)**2\n if ((denominator_d1 * denominator_d2) ** 0.5) != 0:\n return numerator / ((denominator_d1 * denominator_d2) ** 0.5)\n else:\n return 0.0\n\ndef main():\n \"\"\"\n This function is called from the command line via\n \n python cf.py --train [path to filename] --test [path to filename]\n \"\"\"\n args = parse_argument()\n train_file = args['train'][0]\n test_file = args['test'][0]\n print train_file, test_file\n train_user, train_movie = parse_file(train_file)\n test_user, test_movie = parse_file(test_file)\n predicted_movie_user_ratings = []\n avg_user_ratings = compute_average_user_ratings(train_user)\n for user in test_user: # will grab the user id from the test set\n for movie in test_user[user].keys():\n user_avg = avg_user_ratings[user]\n user_sim_sum = 0\n user_sim_ratdiff_sum = 0\n for sim_user in train_movie[movie].keys(): # all the users who saw that movie\n user_sim_value = compute_user_similarity(train_user[user], train_user[sim_user], avg_user_ratings[user],\n avg_user_ratings[sim_user])\n user_sim_sum += abs(user_sim_value)\n user_sim_ratdiff_sum += user_sim_value * (train_user[sim_user][movie] - avg_user_ratings[sim_user])\n if user_sim_sum != 0:\n predicted_rating = user_avg + (user_sim_ratdiff_sum) / (user_sim_sum)\n else:\n predicted_rating = user_avg\n predicted_movie_user_ratings.append([movie, user, test_movie[movie][user], predicted_rating])\n # generating the output file\n with open(\"predictions.txt\", \"w\") as output_file: # generates the output csv\n writer = csv.writer(output_file)\n writer.writerows(predicted_movie_user_ratings)\n # calculating the rmse and mae\n sum_squared_error = 0\n sum_abs_error = 0\n for predicates in predicted_movie_user_ratings:\n sum_squared_error += (predicates[3] - test_movie[predicates[0]][predicates[1]]) ** 2\n sum_abs_error += abs(predicates[3] - test_movie[predicates[0]][predicates[1]])\n rmse = (sum_squared_error / len(predicted_movie_user_ratings)) ** 0.5\n mae = sum_abs_error / len(predicted_movie_user_ratings)\n print \"RMSE\", rmse\n print \"MAE\", mae\n\nif __name__ == '__main__':\n main()\n\n"
},
{
"alpha_fraction": 0.8166666626930237,
"alphanum_fraction": 0.8166666626930237,
"avg_line_length": 58.5,
"blob_id": "03d854595c0ebc13ec07a7c2d30c72c8b9a4ced8",
"content_id": "3f2ef0b58ed323ff4969f5955ab0f06672c6ed63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 120,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 2,
"path": "/README.md",
"repo_name": "jmidiri/Coding-Samples",
"src_encoding": "UTF-8",
"text": "# Coding-Samples\nThis repository contains some examples of my programming in different languages such as Python and R. \n"
},
{
"alpha_fraction": 0.6235755085945129,
"alphanum_fraction": 0.6331908702850342,
"avg_line_length": 34.099998474121094,
"blob_id": "d4dcb6646a7fcb6741d89e462da8ad02ed255f07",
"content_id": "c71741073069a51769ce3034a5fc4e4b9e25edcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 2808,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 80,
"path": "/Examples with R/Monty Hall and Backward Elim.R",
"repo_name": "jmidiri/Coding-Samples",
"src_encoding": "UTF-8",
"text": "############################\n## The Monty Hall Problem ##\n############################\n\nmonty_hall_sim <- function(num_samp, num_sim){\n # Simulate the probability of winning based on tracking the number of times\n # the contestant wins if they were to switch and the number of times the\n # contestant wins if they didn't switch\n winning.outcome.probs <- c()\n \n # Door Options\n doors <- c(\"1\",\"2\",\"3\")\n \n for (i in 1:num_samp){ # Number of Samples to Run\n winning.outcomes <- c()\n for (j in 1:num_sim){ # Number of Simulations to Conduct in Each Sample\n # Randomly Assign Which Door The Car Is Behind\n car.door <- sample(doors, 1)\n \n # Contestant Randomly Chooses A Door\n contestant.door <- sample(doors, 1)\n \n # Determine The Winning Scenario\n # switch -> If The Contestant Would Have Won By Switching\n # no.switch -> If The Contestant Would Have Won By Not Switching\n outcome <- ifelse(car.door == contestant.door, \"no.switch\", \"switch\")\n winning.outcomes <- append(winning.outcomes, outcome)\n }\n winning.outcome.probs <- append(winning.outcome.probs, \n (sum(winning.outcomes == \"switch\")/length(winning.outcomes)))\n }\n \n avg.prob <- mean(winning.outcome.probs)\n return(avg.prob)\n}\n\n# Example call to function\nmonty_hall_sim(1000, 1000)\n\n##########################\n## Backward Elimination ##\n##########################\n\n# Function to check if a package is installed\nisInstalled <- function(package_name) package_name %in% rownames(installed.packages())\n\nif (!isInstalled(\"car\")) install.packages(\"car\")\n\n# Load the necessary package\nlibrary(car)\n\nbackward_elimination <- function(df, response) {\n i <- ncol(df) - 1\n while (i > 1) {\n # Generate the equation to regress the dependent variable on all the independent variables\n eq <- paste(response, \"~.\", sep = \"\")\n # Run multiple linear regression model with all the independent variables\n mlr <- lm(eq, data = df)\n # Generate a Type II Anova table with associated p-values\n mlr_anova <- Anova(mlr)\n # Access the p-values from the Anova table\n pvalues <- mlr_anova[, 4][1:(ncol(df) - 1)]\n if (max(pvalues) < 0.05 | i == 2) {\n break \n } else {\n removeVar <- rownames(mlr_anova)[which(pvalues == max(pvalues))]\n # Remove the independent variable column that has the highest p-value\n # and run the complete mlr without that column\n df <- df[-which(colnames(df) == removeVar)]\n }\n i <- i - 1 }\n # Return the name(s) of the independent variable(s) to include in the model\n return(colnames(df[-which(colnames(df) == response)]))\n}\n\n# Read in the data\nstartups <- read.csv(\"~/Desktop/50-Startups.csv\", header = TRUE)\n\n# Example call to function\nbackward_elimination(startups, \"Profit\")\n"
}
] | 3 |
nanyangrenfei/RenFei | https://github.com/nanyangrenfei/RenFei | 3d468e77cf35680774c577fc08fd5d8f849ed37c | c093cf9a050697fb23a4813db00c364fd37e3599 | 0d460b68386d68db4fc0b704365a55844ba4367e | refs/heads/master | 2021-07-13T17:09:25.625827 | 2021-06-26T03:43:13 | 2021-06-26T03:43:13 | 224,389,067 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5557515621185303,
"alphanum_fraction": 0.559985876083374,
"avg_line_length": 26.918367385864258,
"blob_id": "bbfd9b2275ac5f6c54e9be724bb924964b4a770a",
"content_id": "1e8cab4bf23ae3d5beda20d206a08f3f9d0867f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5668,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 196,
"path": "/RBDClear.py",
"repo_name": "nanyangrenfei/RenFei",
"src_encoding": "UTF-8",
"text": "#coding:utf8\r\nimport paramiko,logging #Must install paramiko\r\nhost_ip = \"10.121.133.101\" #Any storage node IP\r\nusername = \"root\"\r\npasswd = \"root\"\r\npool = \"ucpool\"\r\nflatten_rbd_file_path = \"/home/rbd_list\" #Write all rbd into the rbd_list\r\n\r\ndef LogOutput(mes):\r\n \"\"\"\r\n\r\n :param mes: Log message!\r\n :return: None\r\n \"\"\"\r\n logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\n logger = logging.getLogger(__name__)\r\n logger.info(mes)\r\n\r\ndef CLIClient():\r\n \"\"\"\r\n\r\n :return: Get SSH client\r\n \"\"\"\r\n ssh_client = paramiko.SSHClient()\r\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh_client.connect(host_ip, 22, username, passwd, timeout=120)\r\n return ssh_client\r\n\r\n\r\ndef RunCMD(cmd,client):\r\n \"\"\"\r\n :param cmd: shell cli command\r\n :param client: SSH client\r\n :return:\r\n \"\"\"\r\n LogOutput(\"Running CLi: \"+cmd)\r\n std_in, std_out, std_err = client.exec_command(cmd)\r\n output = std_out.read().decode()\r\n return output\r\n\r\n\r\ndef GetRBDParent(rbd_id,all_parent_rbd,client):\r\n \"\"\"\r\n\r\n :param rbd_id: rbd id to be deleted!\r\n :param all_parent_rbd:List,recored all parent rbd\r\n :param client:SSH client\r\n :return:None\r\n \"\"\"\r\n\r\n\r\n cmd = \"rbd info \" + pool + \"/\" + rbd_id + \"|grep parent\"\r\n rbd_parent = RunCMD(cmd,client)\r\n if not rbd_parent:\r\n pass\r\n else:\r\n LogOutput(rbd_id + \" has parent:\" + rbd_parent.strip())\r\n parent_rbd_id = rbd_parent.split(\":\")[1].split(\"@\")[0].split(\"/\")[1]\r\n all_parent_rbd.append(parent_rbd_id)\r\n GetRBDParent(parent_rbd_id,all_parent_rbd,client)\r\n\r\n\r\ndef GetRBDSnapshot(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param client:\r\n :return:\r\n \"\"\"\r\n cmd = r\"rbd snap ls \" + pool + \"/\" + rbd_id + \"|grep -v NAME|awk '{print $2}'\"\r\n snapshot = RunCMD(cmd,client)\r\n return snapshot\r\n\r\ndef GetChildrenBySnap(rbd_id,snap_id,client):\r\n \"\"\"\r\n\r\n :param snap_id:\r\n :param client:\r\n :return:\r\n \"\"\"\r\n cmd = \"rbd children \" + pool + \"/\" + rbd_id + \"@\" + snap_id\r\n children = None\r\n try:\r\n children = RunCMD(cmd, client).split(\"/\")[1]\r\n except IndexError:\r\n LogOutput(\"There is no clone children from the \" + snap_id + \"of the volume \"+ rbd_id )\r\n return children\r\n\r\ndef GetRBDChildren(rbd_id,all_chilren_rbd,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param all_chilren_rbd:\r\n :param client:\r\n :return:\r\n \"\"\"\r\n snapshot = GetRBDSnapshot(rbd_id, client).splitlines()\r\n children_in_a_rbd = list()\r\n children_dict = dict()\r\n if snapshot:\r\n LogOutput(str(snapshot) + \" is got snapshot from \" + rbd_id)\r\n for snap in snapshot:\r\n children = GetChildrenBySnap(rbd_id, snap, client)\r\n if not children:\r\n pass\r\n else:\r\n children = str(children).replace(\"\\n\", \"\")\r\n children_in_a_rbd.append(children)\r\n children_dict[rbd_id] = children_in_a_rbd\r\n LogOutput(\"Clone rbds \" + str(children_in_a_rbd) + \" base on \" + rbd_id)\r\n all_chilren_rbd.append(children_dict)\r\n for child in children_in_a_rbd:\r\n GetRBDChildren(child, all_chilren_rbd, client)\r\n else:\r\n LogOutput(rbd_id + \" is the bottom clone rbd\")\r\n\r\n\r\n return all_chilren_rbd\r\n\r\ndef GetTopParent(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param client:\r\n :return:\r\n \"\"\"\r\n\r\n all_parent_rbd = list()\r\n top_parent = None\r\n GetRBDParent(rbd_id, all_parent_rbd, client)\r\n\r\n if all_parent_rbd:\r\n top_parent = all_parent_rbd[-1]\r\n LogOutput(\"Top parent of the RBD '\" + rbd_id + \"' is \" + top_parent)\r\n else:\r\n top_parent = rbd_id\r\n LogOutput(rbd_id + \" itself is at the top!\")\r\n return top_parent\r\n\r\ndef ExecuteFlatten(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id: rbd id to be deleted!\r\n :param client: SSH client\r\n :return: None\r\n \"\"\"\r\n chilren_rbd = list()\r\n top_parent = GetTopParent(rbd_id, client)\r\n all_chilren_rbd = GetRBDChildren(top_parent, chilren_rbd, client)\r\n all_chilren_rbd_reverse = all_chilren_rbd[::-1]\r\n if all_chilren_rbd_reverse:\r\n for chilren in all_chilren_rbd_reverse:\r\n for child in chilren.values():\r\n for vol in child:\r\n LogOutput(vol + \"will be flatten\")\r\n cmd = \"rbd flatten \" + pool + \"/\" + vol\r\n print(cmd)\r\n RunCMD(cmd,client)\r\n\r\n\r\ndef FlattenAllRBD():\r\n \"\"\"\r\n Read rbd id to be deleted from the file,batch execute!\r\n :return: None\r\n \"\"\"\r\n client = CLIClient()\r\n cmd = \"cat \" + flatten_rbd_file_path\r\n all_rbd = RunCMD(cmd,client)\r\n all_rbd_list = all_rbd.splitlines()\r\n for volume in all_rbd_list:\r\n ExecuteFlatten(volume,client)\r\n client.close()\r\n\r\ndef DeleteRBD():\r\n client = CLIClient()\r\n cmd = \"cat \" + flatten_rbd_file_path\r\n all_rbd = RunCMD(cmd, client)\r\n all_rbd_list = all_rbd.splitlines()\r\n for volume in all_rbd_list:\r\n snapshot = GetRBDSnapshot(volume, client).splitlines()\r\n if snapshot:\r\n for snap in snapshot:\r\n cmd = \"rbd snap unprotect \" + pool + \"/\" + volume + \"@\" + snap\r\n RunCMD(cmd,client)\r\n cmd = \"rbd snap rm \" + pool + \"/\" + volume + \"@\" + snap\r\n RunCMD(cmd, client)\r\n LogOutput(volume + \" will be deleted!\")\r\n cmd = \"rbd rm \" + pool + \"/\" + volume\r\n RunCMD(cmd, client)\r\n client.close()\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n FlattenAllRBD()\r\n DeleteRBD()\r\n"
},
{
"alpha_fraction": 0.5744985938072205,
"alphanum_fraction": 0.5799108743667603,
"avg_line_length": 28.643901824951172,
"blob_id": "2baca33743becd1d0ee3d723d7c80b804c00b6ac",
"content_id": "d4ea1e932d6eff4a4c9736ca9f5accb73dc24d38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6282,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 205,
"path": "/GetRBDCloneTree.py",
"repo_name": "nanyangrenfei/RenFei",
"src_encoding": "UTF-8",
"text": "#coding:utf8\r\nimport paramiko,yaml,logging#Must install paramiko,yaml\r\nhost_ip = \"10.121.133.101\" #Any storage node IP\r\nusername = \"root\" #Host user name\r\npasswd = \"root\" #Host user password\r\npool = \"ucpool\" #Ceph storage pool name\r\n\r\ndef LogOutput(mes):\r\n \"\"\"\r\n\r\n :param mes: Log message!\r\n :return: None\r\n \"\"\"\r\n logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\n logger = logging.getLogger(__name__)\r\n logger.info(mes)\r\n\r\n\r\ndef CLIClient():\r\n \"\"\"\r\n :return: Get SSH client\r\n \"\"\"\r\n ssh_client = paramiko.SSHClient()\r\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh_client.connect(host_ip, 22, username, passwd, timeout=120)\r\n return ssh_client\r\n\r\n\r\ndef RunCMD(cmd,client):\r\n \"\"\"\r\n :param cmd: shell cli command\r\n :param client: SSH client\r\n :return: execute Cli output\r\n \"\"\"\r\n LogOutput(\"Running CLi: \"+cmd)\r\n std_in, std_out, std_err = client.exec_command(cmd)\r\n output = std_out.read().decode()\r\n return output\r\n\r\n\r\ndef GetRBDParent(rbd_id,all_parent_rbd,client):\r\n \"\"\"\r\n\r\n :param rbd_id: rbd id to be deleted!\r\n :param all_parent_rbd:List,recored all parent rbd\r\n :param client:SSH client\r\n :return:None\r\n \"\"\"\r\n\r\n\r\n cmd = \"rbd info \" + pool + \"/\" + rbd_id + \"|grep parent\"\r\n rbd_parent = RunCMD(cmd,client)\r\n if not rbd_parent:\r\n pass\r\n else:\r\n LogOutput(rbd_id + \" has parent:\" + rbd_parent.strip())\r\n parent_rbd_id = rbd_parent.split(\":\")[1].split(\"@\")[0].split(\"/\")[1]\r\n all_parent_rbd.append(parent_rbd_id)\r\n GetRBDParent(parent_rbd_id,all_parent_rbd,client)\r\n\r\n\r\ndef GetRBDSnapshot(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param client:ssh client\r\n :return: all snapshots of the rbd\r\n \"\"\"\r\n cmd = r\"rbd snap ls \" + pool + \"/\" + rbd_id + \"|grep -v NAME|awk '{print $2}'\"\r\n snapshot = RunCMD(cmd,client)\r\n return snapshot\r\n\r\ndef GetChildrenBySnap(rbd_id,snap_id,client):\r\n \"\"\"\r\n\r\n :param snap_id:\r\n :param client: ssh client\r\n :return: children of the snapshot\r\n \"\"\"\r\n cmd = \"rbd children \" + pool + \"/\" + rbd_id + \"@\" + snap_id\r\n children = list()\r\n try:\r\n all_children = str(RunCMD(cmd, client)).splitlines()#split(\"/\")[1]\r\n for child in all_children:\r\n children.append(child.split(\"/\")[1])\r\n except IndexError:\r\n LogOutput(\"There is no clone children from the \" + snap_id + \"of the volume \"+ rbd_id )\r\n return children\r\n\r\ndef GetRBDChildren(rbd_id,all_chilren_rbd,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param all_chilren_rbd: storage all children\r\n :param client: ssh client\r\n :return: storage all children\r\n \"\"\"\r\n snapshot = GetRBDSnapshot(rbd_id, client).splitlines()\r\n children_in_a_rbd = list()\r\n children_dict = dict()\r\n if snapshot:\r\n LogOutput(str(snapshot) + \" is got snapshot from \" + rbd_id)\r\n for snap in snapshot:\r\n children = GetChildrenBySnap(rbd_id, snap, client)\r\n if not children:\r\n pass\r\n else:\r\n for child in children:\r\n #children = str(children).replace(\"\\n\", \"\")\r\n child = str(child).replace(\"\\n\", \"\")\r\n children_in_a_rbd.append(child)\r\n children_dict[rbd_id] = children_in_a_rbd\r\n LogOutput(\"Clone rbds \" + str(children_in_a_rbd) + \" base on \" + rbd_id)\r\n all_chilren_rbd.append(children_dict)\r\n for child in children_in_a_rbd:\r\n GetRBDChildren(child, all_chilren_rbd, client)\r\n else:\r\n LogOutput(rbd_id + \" is the bottom clone rbd\")\r\n return all_chilren_rbd\r\n\r\ndef GetTopParent(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param client:ssh client\r\n :return: top parent rbd id\r\n \"\"\"\r\n\r\n all_parent_rbd = list()\r\n top_parent = None\r\n GetRBDParent(rbd_id, all_parent_rbd, client)\r\n\r\n if all_parent_rbd:\r\n top_parent = all_parent_rbd[-1]\r\n LogOutput(\"Top parent of the RBD '\" + rbd_id + \"' is \" + top_parent)\r\n else:\r\n top_parent = rbd_id\r\n LogOutput(rbd_id + \" itself is at the top!\")\r\n return top_parent\r\n\r\ndef GetCloneChain(rbd_id,client):\r\n \"\"\"\r\n\r\n :param rbd_id:\r\n :param client:ssh client\r\n :return: type:list,Complete clone chain\r\n \"\"\"\r\n\r\n chilren_rbd = list()\r\n top_parent = GetTopParent(rbd_id, client)\r\n all_clone_chain = GetRBDChildren(top_parent, chilren_rbd, client)\r\n return all_clone_chain\r\n\r\n\r\ndef WriteFile(rbd_clone_tree):\r\n \"\"\"\r\n\r\n :param rbd_clone_tree: type:dict\r\n :return: write clone dict into yaml file\r\n \"\"\"\r\n with open('rbd_clone_tree.yaml', 'w+', encoding=\"utf-8\") as f:\r\n yaml.dump(rbd_clone_tree, f)\r\n\r\n\r\ndef CreateTree(tree,all_clone_chain):\r\n \"\"\"\r\n\r\n :param tree: init clone tree,type:dict\r\n :param all_clone_chain: type:list,Complete clone chain\r\n :return: clone tree\r\n \"\"\"\r\n for key,value in tree.items():\r\n for i in range(0,len(value)):\r\n for one in all_clone_chain[1:]:\r\n if isinstance(value[i],dict):\r\n CreateTree(value[i],all_clone_chain)\r\n else:\r\n if value[i] in list(one.keys()):\r\n tree[key][i] = {value[i]:one.get(value[i])}\r\n return tree\r\n\r\ndef main(rbd_id):\r\n \"\"\"\r\n main function,program entry\r\n :param rbd_id:\r\n :return: None\r\n \"\"\"\r\n LogOutput(\"Step 1:Ceate ssh client and SSH login!\")\r\n client = CLIClient()\r\n LogOutput(\"Step 2:Get top parent rbd of the \" + rbd_id)\r\n top_parent = GetTopParent(rbd_id,client)\r\n LogOutput(\"Step 3:Get complete clone relationship of the \" + rbd_id)\r\n all_clone_chain = GetCloneChain(top_parent,client)\r\n LogOutput(\"Step 4:Create clone tree of the \" + rbd_id + \",and write clone tree into yaml file!\")\r\n try:\r\n init_tree = all_clone_chain[0]\r\n tree = CreateTree(init_tree,all_clone_chain)\r\n WriteFile(tree)\r\n except IndexError:\r\n LogOutput(rbd_id + \"has not clone rbd!\") #if rbd has not clone rbd,don't write yaml file\r\n LogOutput(\"Step 5:Close ssh connection!\")\r\n client.close()\r\n\r\nif __name__==\"__main__\":\r\n main(\"B_1\")\r\n"
},
{
"alpha_fraction": 0.5789616107940674,
"alphanum_fraction": 0.6062736511230469,
"avg_line_length": 53.149253845214844,
"blob_id": "dee816a026406e3515bf340e82d273c648c5e771",
"content_id": "6a380a9973c8d5657a5a13f84a7d1a56a46f7ac0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7396,
"license_type": "no_license",
"max_line_length": 169,
"num_lines": 134,
"path": "/GetBuild.py",
"repo_name": "nanyangrenfei/RenFei",
"src_encoding": "UTF-8",
"text": "#coding:utf8\r\nimport paramiko\r\nimport unittest\r\nimport json\r\nimport requests\r\nimport urllib\r\nimport re\r\nimport time\r\nimport os\r\nfrom SSHLibrary import SSHLibrary\r\nimport sys\r\nsys.getdefaultencoding()\r\n\r\n\r\nclass GetBuild(object):\r\n def __init__(self):\r\n\r\n self.host = [\"10.121.138.102\"]\r\n self.port = 8100\r\n self.timeout = 30\r\n self.user = \"root\"\r\n self.password = \"111111\"\r\n self.base_path = 'http://10.120.16.212/build/ThinkCloud-SDS/release-2.5/'\r\n\r\n def get_build_path(self):\r\n response = urllib.urlopen(self.base_path)\r\n html = response.read()\r\n html = html.decode(\"utf-8\")\r\n build_name = re.findall(\">ThinkCloud-SDS-.+.tar.gz\", html)[-1]\r\n build_name = build_name.replace(\">\",\"\")\r\n #print(build_name)\r\n #print(self.base_path + build_name)\r\n return self.base_path + build_name,build_name\r\n\r\n def ExecuteCMD(self, host_ip, username,password,CMD_content):\r\n ssh_client = paramiko.SSHClient()\r\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh_client.connect(host_ip, 22, username, password, timeout=self.timeout)\r\n std_in, std_out, std_err = ssh_client.exec_command(CMD_content)\r\n output = std_out.read().decode()\r\n ssh_client.close()\r\n return output\r\n\r\n def get_ssh_client(self,host_ip, username,password,timeout=300):\r\n sshlibary = SSHLibrary()\r\n sshlibary.open_connection(host_ip, timeout=timeout)\r\n sshlibary.login(username,password)\r\n return sshlibary\r\n\r\n def write_and_read(self,sshlibary,command,expect=\"#\",timeout=None):\r\n sshlibary.write(command)\r\n output = sshlibary.read_until(expect)\r\n return output\r\n\r\n def down_build(self,host_ip, username,password):\r\n ssh_client = self.get_ssh_client(host_ip, username,password)\r\n output = self.write_and_read(ssh_client,\"rm -rf /home/packege/\")\r\n output = self.write_and_read(ssh_client, \"mkdir -p /home/packege\")\r\n output = self.write_and_read(ssh_client, \"cd /home/packege\")\r\n path, build_name = self.get_build_path()\r\n output = self.write_and_read(ssh_client, \"wget \"+path)\r\n time.sleep(5)\r\n ssh_client.close_connection()\r\n def delete_target_node_packege(self,dist_ip,dist_username,dist_password):\r\n ssh_client = self.get_ssh_client(dist_ip, dist_username, dist_password)\r\n output = self.write_and_read(ssh_client, \"rm -rf /home/packege/\")\r\n output = self.write_and_read(ssh_client, \"mkdir -p /home/packege\")\r\n ssh_client.close_connection()\r\n\r\n def clear_env(self,node_ip,node_username,node_password):\r\n ssh_client = self.get_ssh_client(node_ip, node_username, node_password)\r\n clear_cmd =\"rm /etc/ceph/ceph.* -rf;rm /opt/ceph/* -rf;rm /Ceph/Meta/* -rf;find / -name zabbix | xargs rm -rf;rpm -qa |grep glus |xargs rpm -e\"\r\n output = self.write_and_read(ssh_client, clear_cmd)\r\n ssh_client.close_connection()\r\n return output\r\n\r\n def copy_packege_distance_node(self,host_ip, username,password,dist_ip,dist_username,dist_password):\r\n self.delete_target_node_packege(dist_ip, dist_username, dist_password)\r\n ssh_client = self.get_ssh_client(host_ip, username, password)\r\n output = self.write_and_read(ssh_client, \"cd /home/packege\")\r\n path, build_name = self.get_build_path()\r\n copy_command = \"scp %s %s@%s:/home/packege/\"%(build_name,dist_username,dist_ip)\r\n print(copy_command)\r\n output = self.write_and_read(ssh_client, copy_command,expect=\"password:\",timeout=20)\r\n print(output)\r\n if \"yes/no\" in output:\r\n output = self.write_and_read(ssh_client, \"yes\", expect=\"password:\")\r\n if \"password:\" in output:\r\n output = self.write_and_read(ssh_client, \"root\")\r\n else:\r\n raise Exception(\"copy packege failed\")\r\n\r\n def install_packege(self,exe_host_info = {},node1_info = {},node2_info = {},node3_info ={},\r\n vip = '',netmask = '',filepath = '',clusterscope =''):\r\n sds_env_list = [node1_info,node2_info,node3_info]\r\n print(sds_env_list)\r\n for env in sds_env_list:\r\n output = self.clear_env(env['nodeip'],env['username'],env['password'])\r\n print(output)\r\n ssh_client = self.get_ssh_client(node1_info[\"nodeip\"], node1_info[\"username\"], node1_info[\"password\"],\r\n timeout=7200)\r\n output = self.write_and_read(ssh_client, \"cd /home/packege;tar -zxf \"+filepath)\r\n install_cmd = \"/home/packege/deployment/install.sh -s yes -f 3 --localip %s --node2ip %s --node3ip %s --vip %s --localnodehostname controller-1 \" \\\r\n \"--node2hostname controller-2 --node3hostname controller-3 --netmask %s --node2rootpassword %s --node3rootpassword %s --deploymentTarFilePath %s\" \\\r\n \" --clusterscope %s\"%(node1_info[\"nodeip\"],node2_info[\"nodeip\"],node3_info[\"nodeip\"],vip,netmask,node2_info[\"password\"],node3_info[\"password\"],\\\r\n filepath,clusterscope)\r\n print(\"nohup \"+install_cmd+\" > /home/install.log 2>&1 &\")\r\n output = self.write_and_read(ssh_client,\"ls /home/packege/deployment/\")\r\n if \"install.sh\" in output:\r\n output = self.write_and_read(ssh_client, \"nohup \"+install_cmd+\" > /home/install.log 2>&1 &\")\r\n print(output)\r\n\r\n def install_process(self,exe_host_info = {},node1_info = {},node2_info = {},node3_info ={},\r\n vip = '',netmask = '',filepath = '',clusterscope =''):\r\n print(exe_host_info)\r\n self.down_build(exe_host_info[\"nodeip\"],exe_host_info[\"username\"],exe_host_info[\"password\"])\r\n self.delete_target_node_packege(node1_info[\"nodeip\"],node1_info[\"username\"],node1_info[\"password\"])\r\n self.copy_packege_distance_node(exe_host_info[\"nodeip\"],exe_host_info[\"username\"],exe_host_info[\"password\"],\r\n node1_info[\"nodeip\"], node1_info[\"username\"], node1_info[\"password\"])\r\n self.install_packege(exe_host_info = exe_host_info,node1_info = node1_info,node2_info = node2_info,node3_info =node3_info,\r\n vip = vip,netmask = netmask,filepath = filepath,clusterscope =clusterscope)\r\nif __name__==\"__main__\":\r\n #path = GetBuild().get_build_path()\r\n #GetBuild().down_build(\"10.121.138.124\",\"root\",\"root\")\r\n #GetBuild().delete_target_node_packege(\"10.121.137.162\",\"root\",\"root\")\r\n #GetBuild().copy_packege_distance_node(\"10.121.138.124\",\"root\",\"root\",\"10.121.137.162\",\"root\",\"root\")\r\n path,build_name = GetBuild().get_build_path()\r\n filepath = \"/home/packege/\" + build_name\r\n install_para_config = {\"exe_host_info\":{'nodeip':\"10.121.137.166\",\"username\":\"root\",\"password\":\"root\"},\r\n \"node1_info\":{'nodeip':\"10.121.137.162\",\"username\":\"root\",\"password\":\"root\"},\r\n \"node2_info\": {'nodeip': \"10.121.137.163\", \"username\": \"root\", \"password\": \"root\"},\r\n \"node3_info\":{'nodeip':\"10.121.137.164\",\"username\":\"root\",\"password\":\"root\"},\r\n \"vip\":\"10.121.137.169\",\"netmask\":\"23\",\"filepath\":filepath,\"clusterscope\":\"10.121.137.0/23\"}\r\n GetBuild().install_process(**install_para_config)\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6144842505455017,
"alphanum_fraction": 0.6271031498908997,
"avg_line_length": 41.72800064086914,
"blob_id": "542471e9745d67908008ff9609a4203cdf3fc5b1",
"content_id": "ae2e4d9b40da45851e09093c5b04e9df866e0a41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5598,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 125,
"path": "/PandasTest2.py",
"repo_name": "nanyangrenfei/RenFei",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\r\nimport math\r\nimport csv,os,chardet,json\r\nimport time,re\r\nfrom pandas import DataFrame\r\nimport pandas as pd\r\nfrom concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, ALL_COMPLETED,as_completed\r\n\r\ntarget_distance = 1000\r\ntarget_filepath = r\"D:\\testfile\\SiteFile\\SiteList.csv\"\r\nbase_write_path = r\"D:\\testfile\"\r\nbase_original_filepath = r\"D:\\testfile\\GridFile\"\r\nlocal_time = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))\r\nall_original_file = os.listdir(base_original_filepath)\r\n\r\n\r\ndef disten_lon_lat(lona,lata,lonb,latb):\r\n\ta=math.floor(math.sqrt(math.pow((6.37 * 1000000 * math.pi* (lata - latb) / 180),2)+math.pow((6.37 * 1000000 *\r\n math.cos((latb + lata) / 2 * math.pi / 180) * math.pi * (lonb - lona) / 180),2)))\r\n\treturn(a)\r\ndef get_file_code(file_name):\r\n f3 = open(file=file_name, mode='rb')\r\n data = f3.read()\r\n f3.close()\r\n result = chardet.detect(data)\r\n return result.get(\"encoding\")\r\ndef abc():\r\n with open(file=base_write_path+\"\\\\a.txt\", mode='r') as f:\r\n data = f.read()\r\n data = str(data).replace(\"nan\",\"00\")\r\n print(type(data))\r\n for one in eval(data):\r\n with open(file=base_write_path+\"\\\\b.txt\", mode='a') as f:\r\n f.write(str(one[0:5])+\"\\n\")\r\n\r\n\r\n\r\ndef get_dataframe_from_csv(path):\r\n #table = pd.read_csv(path, encoding='gbk', header=0, index_col=None)\r\n encoding = get_file_code(path)\r\n table = pd.read_csv(path,encoding=encoding,header=0, index_col=None)\r\n column_headers = list(table.columns.values)\r\n table_content = list()\r\n for row in table.itertuples():\r\n table_content.append(list(row)[1:])\r\n # with open(base_write_path+\"\\\\a.txt\",mode='w') as f:\r\n # f.write(str(table_content))\r\n # print(table_content)\r\n # print(column_headers)\r\n return column_headers,table_content\r\n\r\ndef get_temp_dataframe(headers_big_csv,row_original,headers_small_csv,row_target,distance=0):\r\n #创建源始表单行的DataFrame,如果表头与每行数据不对齐,抛出异常\r\n big_row_data = {}\r\n if len(headers_big_csv) == len(row_original):\r\n for i in range(len(headers_big_csv)):\r\n big_row_data[headers_big_csv[i]] = [row_original[i]]\r\n else:\r\n raise ValueError(\"table header counts error\")\r\n\r\n big_row_dataframe = DataFrame(big_row_data)\r\n # 创建目标表单行的DataFrame,如果表头与每行数据不对齐,抛出异常\r\n small_row_data = {}\r\n if len(headers_small_csv) == len(row_target):\r\n for i in range(len(headers_small_csv)):\r\n small_row_data[str(headers_small_csv[i])+\"-target\"] = [row_target[i]]\r\n else:\r\n raise ValueError(\"table header counts error\")\r\n\r\n small_row_data[\"distance\"] = [distance]\r\n small_row_datafrom = DataFrame(small_row_data)\r\n #合并两个DataFrame\r\n merge_dateframe = big_row_dataframe.join(small_row_datafrom)\r\n return merge_dateframe\r\n\r\ndef write_date_into_csv(**kwargs):\r\n base_path = kwargs.get(\"base_write_path\")\r\n dataframe = kwargs.get(\"result_dataframe\")\r\n csv_name = kwargs.get(\"csv_name\")\r\n csv_pre = str(csv_name).split(\".\")[0]\r\n #合成写文件绝对路径\r\n file_name = base_path + \"\\\\\" + csv_pre + \"_result\" + local_time + \".csv\"\r\n dataframe.to_csv(file_name, index=None,mode='a',encoding=\"utf_8_sig\")\r\n\r\ndef recycle_calculation(headers_big_csv,rows_big_csv,headers_small_csv,rows_small_csv,csv = None):\r\n result_dataframe = pd.DataFrame()\r\n for row_original in rows_big_csv:\r\n for row_target in rows_small_csv:\r\n try:\r\n distance = disten_lon_lat(float('%.6f' % float(row_original[0])),float('%.6f' % float(row_original[1])),\r\n float('%.6f' % float(row_target[1])),float('%.6f' % float(row_target[2])))\r\n except IndexError as e:\r\n print (\"lat and lon are abnalmal,big csv:{},small csv:{}\".format(row_original[0:2],row_target[0:2]))\r\n if distance < target_distance:\r\n single_dataframe = get_temp_dataframe(headers_big_csv,row_original,headers_small_csv,row_target,distance=distance)\r\n print(\"big csv:{},small csv:{},their distance is:{}\".format(row_original[0:2],row_target[0:2],distance))\r\n result_dataframe = result_dataframe.append(single_dataframe)\r\n return result_dataframe,csv\r\n\r\ndef main():\r\n pool = ThreadPoolExecutor(max_workers=len(all_original_file))\r\n headers_small_csv, rows_small_csv = get_dataframe_from_csv(target_filepath)\r\n all_task = list()\r\n for csv in all_original_file:\r\n print(\"The position is calculating in {} file\".format(csv))\r\n headers_big_csv, rows_big_csv = get_dataframe_from_csv(base_original_filepath + \"\\\\\" + csv)\r\n task = pool.submit(recycle_calculation,headers_big_csv,rows_big_csv,headers_small_csv,rows_small_csv,csv = csv)\r\n all_task.append(task)\r\n for future in as_completed(all_task):\r\n result_dataframe,csv = future.result()\r\n if not result_dataframe.empty:\r\n write_date_into_csv(base_write_path = base_write_path,result_dataframe = result_dataframe ,csv_name = csv)\r\n else:\r\n print(\"All position less than set distance {} csv\".format(csv))\r\n\r\n wait(all_task, timeout=None, return_when=ALL_COMPLETED)\r\n pool.shutdown()\r\n\r\nif __name__==\"__main__\":\r\n # = time.time()\r\n #recycle_calculation()\r\n main()\r\n #abc()\r\n #get_dataframe_from_csv(r\"D:\\testfile\\GridFile\\Area01GridCoverageGeo.csv\")\r\n #print(time.time() - time1)\r\n\r\n"
}
] | 4 |
davehcker/passauth-app-arch | https://github.com/davehcker/passauth-app-arch | 536a97ac235962993d250b5fb51909490d5da76a | 6f33ef7fea369d59a15055264007170950df2bfc | 2861192d5d67c664d2720708e899d9fddf769bf9 | refs/heads/master | 2020-05-03T09:36:42.001550 | 2019-03-30T12:53:55 | 2019-03-30T12:53:55 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6569525599479675,
"alphanum_fraction": 0.6669442057609558,
"avg_line_length": 24.553192138671875,
"blob_id": "50bfe56ad4b2bee487a60840304221c81367075e",
"content_id": "bb36da79371ef338a24f25fce500ce3d98737a4a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1201,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 47,
"path": "/app.py",
"repo_name": "davehcker/passauth-app-arch",
"src_encoding": "UTF-8",
"text": "from flask import Flask, redirect, url_for, request\nfrom flask import render_template\nimport os, time\n\napp = Flask(__name__)\n\ncommon_unames_file = open('./data/common_unames.txt', 'r')\ncommon_unames = common_unames_file.read().split()\n\nattempts = {}\n\[email protected]('/')\ndef index():\n\treturn render_template('index.html')\n\[email protected]('/submission')\[email protected]('/submission/<int:attempts>', methods = ['GET'])\ndef submission(attempts=None):\n\treturn render_template('index.html', attempts=attempts)\n\[email protected]('/submit', methods = ['POST', 'GET'])\ndef post():\n\tif request.method == 'POST':\n\t\tcontent = request.get_json(silent=True)\n\n\t\tif content['username'] in common_unames:\n\t\t\treturn url_for('submission', attempts=1000)\n\n\t\tcontent['headers'] = request.headers\n\t\tcontent['time'] = int(time.time())\n\t\twith open('./data/' + content['username'] + '.txt', 'a+') as f:\n\t\t\tf.write(str(content))\n\n\t\tif content['username'] in attempts:\n\t\t\tattempts[content['username']] += 1\n\t\telse:\n\t\t\tattempts[content['username']] = 1\n\n\t\treturn url_for('submission', attempts=attempts[content['username']])\n\n\telse:\n\t\treturn redirect(url_for('index'))\n\n\nif __name__ == '__main__':\n\n\tapp.run(debug=True, host='0.0.0.0', port=80)\n"
},
{
"alpha_fraction": 0.6533648371696472,
"alphanum_fraction": 0.6975584030151367,
"avg_line_length": 29.461334228515625,
"blob_id": "89616483229aaf92dc6119bad24cbc0b0dbb304d",
"content_id": "7943a0ce0a3cd63f2685399fcae077f9dbfe5be5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 11427,
"license_type": "no_license",
"max_line_length": 231,
"num_lines": 375,
"path": "/analysis/mouse_movements/capstone.md",
"repo_name": "davehcker/passauth-app-arch",
"src_encoding": "UTF-8",
"text": "\n\n```python\nfrom os import listdir\nfrom os.path import isfile, join\nimport ast\nimport json\nimport re\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\n%matplotlib inline\n```\n\n\n```python\nmypath = '/Users/admin/Downloads/entries/data/'\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\nonlyfiles.remove('common_unames.txt')\n```\n\n\n```python\ndef separateFields(entry:str)->list:\n \"Separates the entry into 6 fields\"\n entry = entry.split(', \"')\n res = entry[0:5]\n res.append(''.join(entry[5:-1]))\n res.append(entry[-1])\n return res\n\ndef getFields(entry:str)->dict:\n \"\"\"Returns username, passHash, usernameFieldLogs and Headers from the entry\"\"\"\n entry = separateFields(entry)\n return { \n \"user\": entry[0].split(':')[-1].strip().replace('\"', ''),\n \"pass\": int(entry[1].split(':')[-1]),\n \"usernameFieldLogs\": ast.literal_eval(entry[2].split(':')[-1].strip()),\n \"passwordFieldLogs\": ast.literal_eval(entry[3].split(':')[-1].strip()),\n \"mouseMovements\": ast.literal_eval(entry[4].split(':')[-1].strip()),\n \"headers\": parseHTTPHeaders(entry[5].split('\":')[-1].strip()),\n \"time\": int(entry[6].split(\":\")[-1].replace('}', '').strip())\n }\n\ndef parseHTTPHeaders(header_str:str)->dict:\n header_str = re.findall(r'\\(\"[^)]*\"\\)', header_str)\n header_str = [[_.replace('\"', '') for _ in re.findall(r'(?=(\"[^\"]+)\")', each)[0:2]] for each in header_str]\n return dict(header_str)\n```\n\n\n```python\ndef getUserData(user : int) -> [dict]:\n with open(mypath+onlyfiles[user], 'r') as f:\n content = f.read().replace(\"\\'\", '\"').replace('}{', '}#{').split('#')\n return [getFields(_) for _ in content]\n```\n\n\n```python\ndef plotUserMouse3D(mouseMovement):\n fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')\n ax = plt.subplot(2,2,1, projection='3d')\n #ax.scatter3D(user1_mouseMovement[0], user1_mouseMovement[1], user1_mouseMovement[2], c=user1_mouseMovement[2], cmap='Greens');\n ax.plot3D(mouseMovement[0], mouseMovement[1], mouseMovement[2])\n\n```\n\n\n```python\ndef plotUserMouseScatter(mouseMovements, figno):\n color = mouseMovements[2]/max(mouseMovements[2])\n fig = plt.figure(figsize=(10,10), dpi=80)\n plt.subplot(*figno)\n plt.ylim([0,500])\n plt.xlim([0,1200])\n plt.scatter(mouseMovements[0], mouseMovements[1], c=color, s=color*500, alpha=0.3)\n\n \ndef plotUserMouseScatterMultiple(user, n=5):\n for i in range(n):\n plotUserMouseScatter(pd.DataFrame(user[i]['mouseMovements']), (10,1,i+1))\n\n```\n\n## Plotting user behavior\n\nWhen we try to draw a picture of the user behavior, we can clearly see a unique pattern to two users.\n\n\n\n```python\n# Plot user 1\nuser1 = getUserData(1)\nplotUserMouseScatterMultiple(user1, n=6)\n```\n\n\n![png](output_7_0.png)\n\n\n\n![png](output_7_1.png)\n\n\n\n![png](output_7_2.png)\n\n\n\n![png](output_7_3.png)\n\n\n\n![png](output_7_4.png)\n\n\n\n![png](output_7_5.png)\n\n\n\n```python\n# Plot user 2\nuser2 = getUserData(2)\nplotUserMouseScatterMultiple(user2, n=6)\n```\n\n\n![png](output_8_0.png)\n\n\n\n![png](output_8_1.png)\n\n\n\n![png](output_8_2.png)\n\n\n\n![png](output_8_3.png)\n\n\n\n![png](output_8_4.png)\n\n\n\n![png](output_8_5.png)\n\n\n## Time for some Machine Learning\n\n'After some failed attempts at one-shot learning using deep NNs'\n\n\n```python\ndef pad(arr, n):\n \"\"\"\n If arr is not equal to n in length, fill it with zero\n \n >>>pad([1, 1], 5)\n [1, 1, 1, 1, 1]\n \"\"\"\n assert n >= len(arr)\n return arr + (n-len(arr)) * [[0, 0, 0]]\n\n# Read all the files backed up from the server\n\ndata = []\nfor i in range(len(onlyfiles)):\n data.append(getUserData(i))\n\n```\n\n\n```python\n# Filter all files that have at least 20 login attempts\ndata = list(filter(lambda x: len(x) >= 20, data))\n```\n\n\n```python\n# Wrangle and extract the mouse movements\n\ndata = [[pad(each['mouseMovements'],n=500), user] for user in range(len(data))\n for each in data[user]]\n```\n\n\n```python\n# Separate training cases and class labels\ndataX = []\ndataY = []\n\nfor each in data:\n dataX.append(each[0])\n dataY.append(each[1])\n\n```\n\n\n```python\n# numpy is much better for remainder of the steps than python lists\ndataX = np.array(dataX)\ndataX = dataX.reshape(161, 1500)\ndataY = np.array(dataY)\ndataY = dataY.reshape(len(dataY),1)\n```\n\n### Multiple ML algorithm results\n\n\n```python\nimport sklearn as sk\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\n\n# training set = 63% and testing set = 33%\nX_train, X_test, y_train, y_test = train_test_split(\n dataX, dataY, test_size=0.33, random_state=30)\n\n```\n\n### SUPPORT VECTOR MACHINES\n\n\n```python\nSVM = svm.LinearSVC()\nSVM = SVM.fit(X_train, y_train)\nprint(f\"Simple SVM: {SVM.score(X_test, y_test)}\")\n```\n\n Simple SVM: 0.3148148148148148\n\n\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n\n\n\n```python\n# One versus one is actually giving very poor performance. Why?\n# Probably the classes themselves are not very different o vs o\nclf = svm.SVC(gamma='auto', decision_function_shape='ovo')\nclf = clf.fit(X_train, y_train)\nclf.score(X_test, y_test)\n```\n\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n\n\n\n\n\n 0.1111111111111111\n\n\n\nSome engineering with SVM actually gives a very good performance.\n\n\n```python\n# Implement binary discriminator\nfor each in range(len(np.unique(y_train))):\n _SVM = svm.LinearSVC()\n _y_train = y_train.copy()\n _y_test = y_test.copy()\n _SVM.fit(X_train, np.where(_y_train != each, -1, each))\n print(f\"Score for User {each}:{_SVM.score(X_test, np.where(_y_test != each, -1, each))}\")\n```\n\n Score for User 0:0.7777777777777778\n Score for User 1:0.7777777777777778\n Score for User 2:0.7037037037037037\n Score for User 3:0.7592592592592593\n Score for User 4:0.6851851851851852\n Score for User 5:0.8148148148148148\n Score for User 6:0.8518518518518519\n\n\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n /anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n\n\n## DECISION TREES\nPerformance above 0.5 without any feature engineering is actually great. Random guessing would give only 0.15\n\n\n```python\ndecision_tree = tree.DecisionTreeClassifier()\ndecision_tree = decision_tree.fit(X_train, y_train)\ndecision_tree.score(X_test, y_test)\n```\n\n\n\n\n 0.5740740740740741\n\n\n\n## RANDOM FOREST\nAn ensemble random forest (without any feature engineering) is improving upon the decision tree results- a good sign that things can be improved.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=40)\nrf.fit(X_train, y_train)\nrf.score(X_test, y_test)\n```\n\n /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:4: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n after removing the cwd from sys.path.\n\n\n\n\n\n 0.6666666666666666\n\n\n\n### GRADIENT BOOS CLASSIFIER \ngood for hypothesis testing :)\n\n\n```python\nfrom sklearn.ensemble import GradientBoostingClassifier\ngbc = GradientBoostingClassifier(n_estimators=40,\n learning_rate=1.0)\ngbc.fit(X_train, y_train)\ngbc.score(X_test, y_test)\n```\n\n /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:761: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n\n\n\n\n\n 0.5555555555555556\n\n\n"
}
] | 2 |
thomasccp/project-euler | https://github.com/thomasccp/project-euler | 9777cfe1cc6ff2fcc9ff68b9e6c7cece83e7e0b8 | ed3f37a64a433d4cdb338da00d55dc9fb593a764 | 54dd2f620838d9bfbac84fbe5308117f3c200fc6 | refs/heads/master | 2016-09-06T15:56:57.028364 | 2013-11-27T22:17:30 | 2013-11-27T22:17:30 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5113402009010315,
"alphanum_fraction": 0.5628865957260132,
"avg_line_length": 19.20833396911621,
"blob_id": "8986ac886fa71356ade429ebd04b097fcbd8ab30",
"content_id": "002d87f27be6f283749232f4d9d9ed4d816604a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 485,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 24,
"path": "/Python/14.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "limit = 1000000\nbiggestCnt = 1\nbiggestIdx = 1\ncache = []\n\nfor i in range(limit+1):\n cache.append(-1)\n\ncache[1] = 1\nfor start in range(2,limit+1):\n cnt=1\n num=start\n while num!=1 and num>=start:\n if num%2==0:\n num = num/2\n else:\n num = 3*num+1\n cnt = cnt+1\n cache[start] = cnt+cache[num]\n if cache[start]>biggestCnt:\n biggestCnt = cache[start]\n biggestIdx = start\n\nprint '{0} {1}'.format(biggestCnt,biggestIdx)\n"
},
{
"alpha_fraction": 0.4987834692001343,
"alphanum_fraction": 0.540145993232727,
"avg_line_length": 12.258064270019531,
"blob_id": "4eda44cfae6b381c82d6555251ab0d3f6f19fb1d",
"content_id": "45049c698bfef846aca5eb13249ec9418bbe071c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 411,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 31,
"path": "/Python/10b.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\nlimit=2000001\ncrosslimit=floor(sqrt(limit-1))+1\nsieve=[]\n\nfor i in range(limit):\n sieve.append('false')\n\ni=4\nwhile i<limit:\n sieve[i]='true'\n i=i+2\n\ni=3\nwhile i<crosslimit:\n if sieve[i]=='false':\n j=i*i\n while j<limit:\n sieve[j]='true'\n j=j+2*i\n i=i+2\n\nsum=0\ni=2\nwhile i<limit:\n if sieve[i]=='false':\n sum+=i\n i=i+1\n\nprint sum\n"
},
{
"alpha_fraction": 0.42954856157302856,
"alphanum_fraction": 0.4651162922382355,
"avg_line_length": 17.743589401245117,
"blob_id": "e8d69790a43ba2354623fe40858fe5f88338bf2f",
"content_id": "b54d4d402e84c1e6e909124a17cee1e32c300770",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 731,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 39,
"path": "/Python/5.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "import math\n\ndef prime_factor(n):\n if n%2==0:\n lastFactor=2\n while n%2==0:\n n/=2\n else:\n lastFactor=1\n factor=3\n factorSqrt=factor*factor\n while n>1 and factorSqrt<=n:\n if n%factor==0:\n lastFactor=factor\n while n%factor==0:\n n/=factor\n factor+=2\n factorSqrt=factor*factor\n if n==1:\n return lastFactor\n else:\n return n\n\na=20\nb=a-1\n\nwhile b>=1:\n if a%b!=0:\n test=prime_factor(b)\n if test==1:\n a=a*b\n print 'Testing {0}: {0} {1}'.format(b,a,b)\n else:\n a=a*test\n print 'Testing {0}: {0} {1}'.format(b,a,test)\n else:\n b=b-1\n\nprint a\n"
},
{
"alpha_fraction": 0.579023003578186,
"alphanum_fraction": 0.6408045887947083,
"avg_line_length": 21.45161247253418,
"blob_id": "fefad65d48a52a56b2611a31b92eb24201853dcb",
"content_id": "92fa9cf5862a157122f5c3fe2092bf7c48ad22e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 696,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 31,
"path": "/Python/4.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "#def reverseInt(num):\n# return int(str(num)[::-1])\ndef reverseInt(num):\n reversed=0\n while num>0:\n reversed=reversed*10+num%10\n num/=10\n return reversed\n\ndef test(dividend,divisor):\n quotient = dividend/divisor\n if dividend%divisor==0 and quotient>99 and quotient<1000:\n #print '{0} {1}'.format(divisor, dividend/divisor)\n return 1\n else:\n return 0\n\npattern=989\nupper=pattern\nlower=reverseInt(pattern)\ndivisor=999\nwhile test(upper*1000+lower,divisor)==0:\n if(divisor>=501): \n divisor=divisor-1\n else:\n pattern=pattern-1\n upper=pattern\n lower=reverseInt(pattern)\n divisor=999\n\nprint upper*1000+lower\n"
},
{
"alpha_fraction": 0.5552017092704773,
"alphanum_fraction": 0.5849257111549377,
"avg_line_length": 29.387096405029297,
"blob_id": "a78cb277433b879cb2594840f315fb2fddd634f1",
"content_id": "60e53c705a41e3b8395c79f71a568440acf35994",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 942,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 31,
"path": "/Python/18.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "f = open(\"18.txt\",\"r\").readlines();\ndata = []\nlevel = 0\nfor line in f:\n for token in line.split(' '):\n data.append(int(token))\n level += 1\n\ntotalNum = (1+level-1)*(level-1)/2\n\nsum = []\nfor i in range(totalNum):\n sum.append(0);\n\ncurrLevel = level\nwhile currLevel>1:\n startIdx = (1+currLevel-1)*(currLevel-1)/2\n for i in range(currLevel-1):\n if currLevel==level:\n if data[startIdx+i]>data[startIdx+i+1]:\n sum[startIdx+i-currLevel+1] = data[startIdx+i]+data[startIdx+i-currLevel+1]\n else:\n sum[startIdx+i-currLevel+1] = data[startIdx+i+1]+data[startIdx+i-currLevel+1]\n else:\n if sum[startIdx+i]>sum[startIdx+i+1]:\n sum[startIdx+i-currLevel+1] = sum[startIdx+i]+data[startIdx+i-currLevel+1]\n else:\n sum[startIdx+i-currLevel+1] = sum[startIdx+i+1]+data[startIdx+i-currLevel+1]\n currLevel -= 1\n\nprint sum\n"
},
{
"alpha_fraction": 0.42038217186927795,
"alphanum_fraction": 0.47133758664131165,
"avg_line_length": 14.699999809265137,
"blob_id": "f2fd9802d6256f27f4751b005030e193575cb140",
"content_id": "5a3da1b7e6b3601af7da02d6d616a9d6da302231",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 471,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 30,
"path": "/Python/10a.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\ndef isPrime(num):\n if num%3==0:\n return 0\n elif num<9:\n return 1\n else:\n i=5\n rootNum=floor(sqrt(num))\n while i<=rootNum:\n if num%i==0 or num%(i+2)==0:\n return 0\n else:\n i=i+6\n return 1\n\nnum=5\nsum=2+3\nlimit=2000000\n\nwhile num<limit:\n if isPrime(num):\n sum+=num\n num=num+2\n if isPrime(num):\n sum+=num\n num=num+4\n\nprint sum\n"
},
{
"alpha_fraction": 0.5811688303947449,
"alphanum_fraction": 0.6525974273681641,
"avg_line_length": 13.666666984558105,
"blob_id": "ccd6dd28ee718ac5aacc77011bccaf54f39b3d3c",
"content_id": "f14dc38faed83977f64efb419904c4fbc7508247",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 308,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 21,
"path": "/Python/2.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "limit=4000000\nfirst=2\nsecond=8\nsum=first\nwhile(second<limit):\n sum+=second\n temp=second\n second=4*second+first\n first=temp\nprint sum\n\n#sum=0\n#first=1\n#second=1\n#while(second<4000000):\n# if(second%2==0):\n# sum+=second\n# temp=second\n# second=first+second\n# first=temp\n#print sum\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5371428728103638,
"avg_line_length": 16.5,
"blob_id": "f397bb877007b42ba64098d8670fd6a88f21ef49",
"content_id": "d65c72a21f66a4879fc8c20b17e084b935cd810c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 350,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 20,
"path": "/Python/16.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from sys import *\n\n#def sumofDigits(num):\n# ln = len(str(num))\n# temp = 0\n# for i in str(ln):\n# temp += num%10\n# num /= 10\n# return temp\ndef sumofDigits(num):\n sum = 0\n for i in str(num):\n sum += int(i)\n return sum\n\nif len(argv)>1:\n limit = int(argv[1])\nelse:\n limit = 1000\nprint sumofDigits(2**limit)\n"
},
{
"alpha_fraction": 0.7979381680488586,
"alphanum_fraction": 0.8041236996650696,
"avg_line_length": 96,
"blob_id": "18771dced9d3d1f1ee192df9763522036fb9581d",
"content_id": "74d91761784d2e955bb038168f4567c789925437",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 485,
"license_type": "no_license",
"max_line_length": 268,
"num_lines": 5,
"path": "/README.md",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "## Solving the problems on ProjectEuler.net\n\n[Project Euler](http://projecteuler.net/) is a series of mathematical and computer programming problems. There are more than 440 problems and are continuously expanding.\n\nI am trying to solve the problems to train my mathematics and programming skills. Right now I am coding in Python because of Python's rich libraries, high-level data types and dynamic typing. I can focus on the problem itself and produce very clean and readable codes.\n"
},
{
"alpha_fraction": 0.3813333213329315,
"alphanum_fraction": 0.5653333067893982,
"avg_line_length": 24,
"blob_id": "3c67c7e8a7b80aba22619e16495905e2d5080b95",
"content_id": "aac6af76e9a5ea882ef17557b299d0ac7b877939",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 15,
"path": "/Python/19.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "days = [31,28,31,30,31,30,31,31,30,31,30,31]\ndaysLeap = [31,29,31,30,31,30,31,31,30,31,30,31]\n\ndayCount = 0\nsunCount = 0\nfor year in range(1901,2000):\n for month in range(12):\n if dayCount%7==6:\n sunCount += 1\n if year%400!=0 and year%4==0:\n dayCount += daysLeap[month]\n else:\n dayCount += days[month]\n\nprint sunCount\n"
},
{
"alpha_fraction": 0.5505181550979614,
"alphanum_fraction": 0.5867875814437866,
"avg_line_length": 22.363636016845703,
"blob_id": "277d84b5d8bac24ef2253b45e281f11f85615921",
"content_id": "745283073bc16ccb038c1dcb67aa72742c368ffe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 772,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 33,
"path": "/Python/15.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "# Recursion is way too slow\n#xLimit = 21\n#yLimit = 21\n#\n#def addBranch(x,y):\n# if x==xLimit-1 and y==yLimit-1:\n# return 0\n# elif x<xLimit-1 and y<yLimit-1:\n# sum = addBranch(x+1,y)\n# sum += addBranch(x,y+1)\n# sum += 1\n# elif x==xLimit-1 and y<yLimit-1:\n# sum = addBranch(x,y+1)\n# elif x<xLimit-1 and y==yLimit-1:\n# sum = addBranch(x+1,y)\n# return sum\n# \n#sum = 1+addBranch(0,0)\n#print sum\n\n# Counting Lattice Paths\n# Amount m+n steps, choose m of them that are to the left, or n of them to the south\n# Central Binomial Coefficients\n\nlimit = 20\ntemp = 1\nfor i in range(1,2*limit+1):\n temp *=i\n if i==limit:\n singleN = temp\n if i==2*limit:\n doubleN = temp\nprint doubleN/singleN/singleN\n\n"
},
{
"alpha_fraction": 0.4515151381492615,
"alphanum_fraction": 0.5494949221611023,
"avg_line_length": 32,
"blob_id": "2c01c1db68d48fc353deb9f969f4cea7513e6220",
"content_id": "ef8353438c1270bfcec5d968defa5d780fe5c8f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 990,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 30,
"path": "/Python/17.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "#singleCount = ['one','two','three','four','five','six','seven','eight','nine']\n#specialCount = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']\n#tenCount = ['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']\nsingleCount = [3,3,5,4,4,3,5,5,4]\nspecialCount = [3,6,6,8,8,7,7,9,8,8]\ntenCount = [6,6,5,5,5,7,6,6]\n\ncount = 0\nfor i in range(1000):\n if i>=100:\n #print '{0} {1}'.format(singleCount[i/100-1],'hundred'),\n count += singleCount[i/100-1]\n count += 7\n if i%100!=0:\n #print 'and',\n count += 3\n if i%100>=10 and i%100<20:\n #print specialCount[i%100-10]\n count += specialCount[i%100-10]\n else:\n if i%100>19:\n #print tenCount[i/10%10-2],\n count += tenCount[i/10%10-2]\n if i%10!=0:\n #print singleCount[i%10-1]\n count += singleCount[i%10-1]\n\n#print 'one thousand'\ncount += 11\nprint count\n"
},
{
"alpha_fraction": 0.5229358077049255,
"alphanum_fraction": 0.6100917458534241,
"avg_line_length": 18.81818199157715,
"blob_id": "72be003bc20002f432bdea2813c5ada1a9de82cd",
"content_id": "d6e1cbe8a104b33f1d8f9678aff8108ff657e21f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 11,
"path": "/Python/1.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "def divisibleby(num):\n bound = 999/num\n return num*(1+bound)*bound/2\n\nprint divisibleby(3)+divisibleby(5)-divisibleby(15)\n\n#sum = 0\n#for i in range(1,1000):\n# if i%3==0 or i%5==0:\n# sum += i\n#print sum\n"
},
{
"alpha_fraction": 0.44052863121032715,
"alphanum_fraction": 0.5242290496826172,
"avg_line_length": 14.133333206176758,
"blob_id": "8f823636326c8a18c85362998e3da57c6588e639",
"content_id": "6eb053b9dde3994a9cf5c671a33a43d70a9171f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 227,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 15,
"path": "/Python/25.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "#fib = lambda n: n if n<2 else fib(n-1)+fib(n-2)\n\n#i = 1\n#while len(str(fib(i))) <1000:\n# i = i+1\n\n#print fib(i-1)\n\na,b,cnt = 1,1,1\nwhile True:\n a,b,cnt = b,a+b,cnt+1\n if len(str(b))>=1000:\n break\n\nprint cnt+1\n"
},
{
"alpha_fraction": 0.369767427444458,
"alphanum_fraction": 0.4062015414237976,
"avg_line_length": 25.32653045654297,
"blob_id": "9a8037c7371a5d49628b5168a7ddbffa7d997935",
"content_id": "2ef500c46db26c0a3f57d38102b0889162280cd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1290,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 49,
"path": "/Python/11.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "f = open(\"11.txt\",'r').readlines();\ndata = []\nfor line in f:\n for token in line.split(' '):\n data.append(int(token))\n\n#print data\n\nmax = 1\nfor y in range(20):\n for x in range(20):\n if x<17:\n rightNum = 1\n for i in range(4):\n rightNum *= data[y*20+x+i]\n if rightNum>max:\n max = rightNum\n if y<17:\n downNum = 1\n for i in range(4):\n downNum *= data[(y+i)*20+x]\n if downNum>max:\n max = downNum\n if x<17 and y<17:\n diagNum = 1\n for i in range(4):\n diagNum *= data[(y+i)*20+x+i]\n if diagNum>max:\n max = diagNum\n if x<17 and y>3:\n diagNum = 1\n for i in range(4):\n diagNum *= data[(y-i)*20+x+i]\n if diagNum>max:\n max = diagNum\n if x>3 and y>3:\n diagNum = 1\n for i in range(4):\n diagNum *= data[(y-i)*20+x-i]\n if diagNum>max:\n max = diagNum\n if x>3 and y<17:\n diagNum = 1\n for i in range(4):\n diagNum *= data[(y+i)*20+x-i]\n if diagNum>max:\n max = diagNum\n\nprint max\n"
},
{
"alpha_fraction": 0.3685636818408966,
"alphanum_fraction": 0.4444444477558136,
"avg_line_length": 17.450000762939453,
"blob_id": "7d1a95b553221750bee6c8538b501c9b81d03588",
"content_id": "f31d786133baf08eb35ba2a52c743075d1ab3f67",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 369,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 20,
"path": "/Python/9.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "def test(a,sum):\n b=1\n while b<=(sum-a)/2:\n c=1000-a-b\n if a*a+b*b!=c*c:\n b=b+1\n else:\n return b\n return 0\n \na=1\nsum=1000\nwhile a<=(sum-3)/3:\n value=test(a,sum)\n if value==0:\n a=a+1\n else:\n #print '{0} {1} {2}'.format(a,value,1000-a-value)\n print a*value*(1000-a-value)\n break\n"
},
{
"alpha_fraction": 0.5656877756118774,
"alphanum_fraction": 0.5865533351898193,
"avg_line_length": 23.41509437561035,
"blob_id": "e9b8dde65e58a5904427aeee3ee5d0dc8a46560d",
"content_id": "62098bbb6fbfdc78cd75937b7af871a391b40fa7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1294,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 53,
"path": "/Python/23.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\ndef checkAbundant(n):\n if n==1:\n return False\n sum = 1\n # Only need to count up to sqrt(n)\n bound = int(floor(sqrt(n)))\n # Deal with perfect square\n if bound**2==n:\n sum = sum+bound\n bound = bound-1\n # Deal with odd number which is not divisible by even numbers\n if n%2==0:\n start = 2\n step = 1\n else:\n start = 3\n step = 2\n # Add all the proper divisors\n for i in xrange(start,bound+1,step):\n if n%i==0:\n sum = sum+i+n/i\n if sum>n:\n return True\n break\n return False\n\nbound = 28123\n\n# Generate the list of abundant numbers\n#abundantList = []\n#for i in range(12,bound+1):\n# if checkAbundant(i)==True:\n# abundantList.append(i)\nabundantList = [i for i in range(12,bound+1) if checkAbundant(i)==True]\n\n# Generate the check list\ncheckList = [False for i in range(bound)]\n\n# Cross out the numbers that can be written as the sum of two abundant numbers\nfor i in range(len(abundantList)):\n for j in range(i,len(abundantList)):\n sum = abundantList[i]+abundantList[j]\n if sum<bound+1:\n checkList[sum-1] = True\n\nsum = 0\nfor i in range(bound):\n if checkList[i]==False:\n sum = sum+i+1\n\nprint sum\n"
},
{
"alpha_fraction": 0.44834306836128235,
"alphanum_fraction": 0.4775828421115875,
"avg_line_length": 18.730770111083984,
"blob_id": "242befc14be9492d591c3e4123e11b40e2613c4b",
"content_id": "35881a3772e182673dd0646c796b2264670ed0c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1026,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 52,
"path": "/Python/12b.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\ndef genPrimeTable():\n sieve=[]\n crosslimit=floor(sqrt(limit-1))+1\n\n for i in range(limit+1):\n sieve.append('false')\n\n i=4\n while i<limit:\n sieve[i]='true'\n i=i+2\n\n i=3\n while i<crosslimit:\n if sieve[i]=='false':\n j=i*i\n while j<limit:\n sieve[j]='true'\n j=j+2*i\n i=i+2\n\n return sieve\n\ndef getNumDivisor(num):\n cnt = 1\n for i in range(2,limit+1):\n if sieve[i]=='false':\n if i*i>num:\n cnt = 2*cnt\n break\n exponent = 1\n while num%i==0:\n exponent = exponent+1\n num = num/i\n #print '{0} {1}'.format(num,i)\n cnt = cnt*exponent\n if num==1:\n break\n return cnt\n\nlimit=10000\nsieve = genPrimeTable()\nnumDivisor = 0\ntriNum=0\ncnt = 1\nwhile numDivisor<500:\n triNum = triNum+cnt\n numDivisor = getNumDivisor(triNum)\n cnt = cnt+1\nprint triNum\n"
},
{
"alpha_fraction": 0.6095238327980042,
"alphanum_fraction": 0.6952381134033203,
"avg_line_length": 10.666666984558105,
"blob_id": "1014d5ce9c2a661a4035d0f53233e57845d0b7bd",
"content_id": "004e293db7dfd06ed6b44d2be9f336ecef63d0c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 105,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 9,
"path": "/Python/6.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "k=100\n\nsum=k*(1+k)/2\nsquareSum=sum*sum\nsumSquare=k*(k+1)*(2*k+1)/6\n\ndiff=squareSum-sumSquare\n\nprint diff\n"
},
{
"alpha_fraction": 0.43358394503593445,
"alphanum_fraction": 0.4862155318260193,
"avg_line_length": 16.34782600402832,
"blob_id": "2e0ac9e0c16c7641b2327f959726c4e574314194",
"content_id": "b20c968f587c714fc0dac1d5c8091333a68f6fd7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 399,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 23,
"path": "/Python/7.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "import math\n\ndef isPrime(num):\n if num%3==0:\n return 0\n else:\n i=5\n rootNum = math.floor(math.sqrt(num))\n while i<=rootNum:\n if num%i==0 or num%(i+2)==0:\n return 0\n else:\n i=i+6\n return 1\n\ncount=2\nnum=5\nlimit=10001\nwhile count<limit:\n if isPrime(num)==1:\n count=count+1\n num=num+2\nprint num-2\n"
},
{
"alpha_fraction": 0.5759162306785583,
"alphanum_fraction": 0.6099476218223572,
"avg_line_length": 18.100000381469727,
"blob_id": "0a7cc54411b9a6847c41c74e5a5aa3e57b9a2fce",
"content_id": "42df9fa783caf3d2954ee1926812c698a654e262",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 20,
"path": "/Python/12a.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\ndef getNumDivisor(num):\n cnt = 0\n sqrtNum = int(sqrt(num))\n for factor in range(1,sqrtNum+1):\n if num%factor==0:\n cnt = cnt+2\n if factor*factor==num:\n cnt = cnt-1\n return cnt\n\nnumDivisor = 0\ntriNum=0\ncnt = 1\nwhile numDivisor<500:\n triNum = triNum+cnt\n numDivisor = getNumDivisor(triNum)\n cnt = cnt+1\nprint triNum\n"
},
{
"alpha_fraction": 0.5870445370674133,
"alphanum_fraction": 0.6275303363800049,
"avg_line_length": 21.454545974731445,
"blob_id": "456618c89fb90cdc01442ac1eb30852006234807",
"content_id": "17ccc810f1ced51560805be3432ec2fd012c2a81",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 247,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 11,
"path": "/Python/20.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "#factorial = 1\n#for i in range(1,101):\n# factorial *= i\nfactorial = reduce(lambda x,y: x*y, range(1,101))\n\n#sum = 0\n#for digit in str(factorial):\n# sum += int(digit)\nsum = reduce(lambda x,y: x+y, [int(i) for i in str(factorial)])\n\nprint sum\n"
},
{
"alpha_fraction": 0.5871687531471252,
"alphanum_fraction": 0.6792189478874207,
"avg_line_length": 25.55555534362793,
"blob_id": "57800e238c7e0779227065c3aec4c85b5b80048d",
"content_id": "97c13e61878874e66434100db6ecb01e93ee74f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 717,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 27,
"path": "/Python/24.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\n# For number start with 0, i.e. 0XXXXXXXXXX\n# There are 9!=362881 permutations\n# 0XXXXXXXXXX is the 1st to the 362881st numbers\n# 1XXXXXXXXXX is the 362882nd to 725760th numbers\n# The 1000000th number should start with 2\n\nlevel = 9\nbound = 1000000\nvalue = 0\ndigitList = [0,1,2,3,4,5,6,7,8,9]\nwhile level>=0:\n print digitList\n \n numOfPerm = factorial(level)\n idx = int((bound-1)/numOfPerm)\n startDigit = digitList[idx]\n print \"numOfPerm: {0} idx: {1} startDigit: {2} bound: {3}\".format(numOfPerm, idx, startDigit, bound)\n \n value = value+startDigit*10**level\n digitList.remove(startDigit)\n level = level-1\n bound = bound%numOfPerm\n print \"=====\"\n\nprint value\n"
},
{
"alpha_fraction": 0.5469387769699097,
"alphanum_fraction": 0.5755102038383484,
"avg_line_length": 21.272727966308594,
"blob_id": "c53c011af9f591fc5052e8f6ff024aa61cd1be9d",
"content_id": "d11b1f581d2e8106328ba3c97a5f63dcde63e040",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 11,
"path": "/Python/22.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "content = open(\"22.txt\", 'r').read()\nnames = sorted(content.replace(\"\\\"\",\"\").split(','), key=str.upper)\n\ntotal = 0\nfor count,str in enumerate(names):\n sum = 0\n for c in str:\n sum += ord(c)-64\n total += (count+1)*sum\n\nprint total\n"
},
{
"alpha_fraction": 0.4543209969997406,
"alphanum_fraction": 0.5061728358268738,
"avg_line_length": 18.285715103149414,
"blob_id": "cc52f6a8235247fb375c5119fee7cc6e5c78bc8f",
"content_id": "fbb3d4d3db669b0b96a28c1f93c3281de593a560",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 810,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 42,
"path": "/Python/3.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "#def prime_factors(n):\n# factors=[]\n# d=2\n# while n>1:\n# while n%d==0:\n# n/=d\n# d=d+1\n# if d*d>n:\n# if n>1: \n# factors.append(n)\n# break\n# return factors\n\n#num=600851475143\n#prime_factor_list = prime_factors(num)\n#print max(prime_factor_list)\n\nimport math\n\ndef prime_factor(n):\n if n%2==0:\n lastFactor=2\n while n%2==0:\n n/=2\n else:\n lastFactor=1\n factor=3\n factorSqrt=factor*factor\n while n>1 and factorSqrt<=n:\n if n%factor==0:\n lastFactor=factor\n while n%factor==0:\n n/=factor\n factor+=2\n factorSqrt=factor*factor\n if n==1:\n return lastFactor\n else:\n return n\n\nnum=600851475143\nprint prime_factor(num)\n"
},
{
"alpha_fraction": 0.5126760601997375,
"alphanum_fraction": 0.5408450961112976,
"avg_line_length": 20.515151977539062,
"blob_id": "eee24ff3d7cfd5a3483cb2bf2fc68ba7a36142ca",
"content_id": "fda470078e9d2dc236351836b3c9a3e46e63c827",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 710,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 33,
"path": "/Python/21.py",
"repo_name": "thomasccp/project-euler",
"src_encoding": "UTF-8",
"text": "from math import *\n\ndef sumOfProperDivisors(n):\n if n==1:\n return 0\n sum = 1\n # Only need to count up to sqrt(n)\n bound = int(floor(sqrt(n)))\n # Deal with perfect square\n if bound**2==n:\n sum = sum+bound\n bound = bound-1\n # Deal with odd number which is not divisible by even numbers\n if n%2==0:\n start = 2\n step = 1\n else:\n start = 3\n step = 2\n # Add all the proper divisors\n for i in xrange(start,bound+1,step):\n if n%i==0:\n sum = sum+i+n/i\n return sum\n\nsum = 0\nfor a in range(1,10000):\n b = sumOfProperDivisors(a)\n if b>a:\n if a==sumOfProperDivisors(b):\n sum = sum+a+b\n\nprint sum\n"
}
] | 26 |
nwelter1/Flask-Wk5Day1-HW | https://github.com/nwelter1/Flask-Wk5Day1-HW | f4f54e5e05f508598497c9a02064314831a059e7 | fa086a2d58c7215b8f385efa7c28e0042ac26a85 | 9b63ca01700a574ab1734d784b9c0ff449dab518 | refs/heads/master | 2023-01-07T21:46:46.332847 | 2020-10-26T18:19:28 | 2020-10-26T18:19:28 | 286,614,485 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6497461795806885,
"alphanum_fraction": 0.6624365448951721,
"avg_line_length": 29.384614944458008,
"blob_id": "2e3603e128de0b6108a611884de5c0ed26265ced",
"content_id": "29857bc33a9ab4afe33dc206eb206ae13f77bb1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 394,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 13,
"path": "/first_five/routes.py",
"repo_name": "nwelter1/Flask-Wk5Day1-HW",
"src_encoding": "UTF-8",
"text": "from first_five import app\nfrom flask import render_template\n\n#Athlete page route\[email protected]('/myfive')\ndef myfive():\n athlete_dict = {1:'Tony Hawk', 2:'Sage Kotsenberg', 3: 'Michael Jordan', 4: 'Peyton Manning', 5:'Patrick Kane'}\n return render_template('myfive.html', athlete_dict=athlete_dict)\n#home page route\[email protected]('/')\ndef home():\n name = 'Top Five Athletes'\n return render_template('home.html',name=name)"
}
] | 1 |
7410abhi/Distribute-the-weights | https://github.com/7410abhi/Distribute-the-weights | 3e439d99e76ce3b4d61f8535155046deb431779d | 34df2ba07fa9767f73496074080382b2090a61f2 | b47f66a1450fa4e2eb3db5ee38471b208ed9ff73 | refs/heads/master | 2021-05-16T21:08:32.662722 | 2020-03-27T07:36:34 | 2020-03-27T07:36:34 | 250,470,024 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.36835747957229614,
"alphanum_fraction": 0.37922704219818115,
"avg_line_length": 19.210525512695312,
"blob_id": "5e01a2faccf8738243983a46d0cb3582e6c43750",
"content_id": "ca442e989cee4fe8ab35ad46acb45cf86b3229d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 828,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 38,
"path": "/distributes_the_weights 1.py",
"repo_name": "7410abhi/Distribute-the-weights",
"src_encoding": "UTF-8",
"text": "def possible(arr,m,k):\r\n subset = 1\r\n curr_sub = arr[0]\r\n flag = True\r\n for i in range(1, len(arr)):\r\n if curr_sub + arr[i]>k:\r\n curr_sub = arr[i]\r\n subset = subset +1\r\n else:\r\n curr_sub = curr_sub + arr[i]\r\n\r\n if subset > m:\r\n flag = False\r\n break\r\n return(flag) \r\n\r\nT = int(input())\r\nfor _ in range(T):\r\n inp = list(map(int, input().split()))\r\n m = inp[1]\r\n arr = list(map(int, input().split()))\r\n \r\n\r\n L = max(arr)\r\n U = sum(arr)\r\n mid = L+U//2\r\n ans = []\r\n \r\n while (L<=U):\r\n if (possible(arr,m,mid):\r\n ans.append(mid)\r\n U = mid - 1\r\n else:\r\n L = mid + 1\r\n \r\n mid = L+U//2 \r\n \r\n print(min(ans)) \r\n \r\n"
}
] | 1 |
juanbretti/gmbd_python_group1 | https://github.com/juanbretti/gmbd_python_group1 | 57e21e41ac6b794a08a071272fcec0207865ed83 | 0392b4dba72f746cf86bbb01923c6caa16e42e11 | 2c6781242538c82cfc0d018ac304a6274f98e16b | refs/heads/master | 2022-12-12T16:53:13.730289 | 2020-09-14T17:18:18 | 2020-09-14T17:18:18 | 283,447,613 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6764507293701172,
"alphanum_fraction": 0.709176778793335,
"avg_line_length": 25.711711883544922,
"blob_id": "1c9c93690745726eeb38910b38cbefe3b2373293",
"content_id": "12e0356869b1af11e9fe9927eba4c3e6fd069190",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2964,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 111,
"path": "/OLD/individual/columns_jp.py",
"repo_name": "juanbretti/gmbd_python_group1",
"src_encoding": "UTF-8",
"text": "#%%\n# General usage\nimport math\nimport numpy as np\nimport pandas as pd\n\n# Reporting\nfrom pandas_profiling import ProfileReport\n\n# Preprocessing\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer, SimpleImputer\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\n\n# Modeling\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.metrics import accuracy_score, f1_score, recall_score, matthews_corrcoef, confusion_matrix, precision_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\n# https://dateutil.readthedocs.io/en/stable/relativedelta.html\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta, MO\n\n# Plotting\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\n\n#%%\n# df.to_pickle('storage\\RBA_KYC_Accounts_ALL_Ids.pkl')\ndf = pd.read_pickle('storage/RBA_KYC_Accounts_ALL_Ids.pkl')\n\n#%%\n# Columns allocation\n\nprint('\\n'*2)\nprint('Alek')\nprint(df.columns[0:9])\nprint('\\n'*2)\nprint('Addison')\nprint(df.columns[9:18])\nprint('\\n'*2)\nprint('Esperanza')\nprint(df.columns[18:27])\nprint('\\n'*2)\nprint('Aziz')\nprint(df.columns[27:36])\nprint('\\n'*2)\nprint('Bretti')\nprint(df.columns[36:])\n\n#%%\ndf2 = df.iloc[:, 18:27]\n\nprofile = ProfileReport(df2, title=\"RBA_KYC_Accounts >> Before >> JP\", minimal=False)\nprofile.to_file(\"storage/df_report_before_esperanza.html\")\n\n#%%\ndf['score_card_Desc'].value_counts()\n\n# %%\n# Remove highly correlated columns\n\n# https://stackoverflow.com/a/60882164/3780957\ncorr = df.corr()\n\nkot = corr[corr>=.9]\nplt.figure(figsize=(30,10))\nsns.heatmap(kot, cmap=\"Greens\")\n#%%\n# https://stackoverflow.com/a/63536382/3780957\n\ndef corrFilter(x: pd.DataFrame, bound: float):\n xCorr = x.corr()\n xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]\n xFlattened = xFiltered.unstack().sort_values().drop_duplicates()\n return xFlattened\n\ncor_ = corrFilter(df, .8)\ncor_\n#%%\n# https://stackoverflow.com/a/25733562/3780957\ndf.drop(cor_.reset_index()['level_1'], axis=1, inplace=True)\n\n\n#%% [mark down]\n#Imputation\n\n#%%\n## Mode fills for missing values\ncat_columns = df.select_dtypes(include=['object', 'datetime64']).columns\ncat_feats = df.loc[:, cat_columns]\n\nfor var in cat_columns:\n if sum(1*cat_feats[var].isnull()):\n print(var, 'has missings')\n mode_ = cat_feats[var].mode().iloc[0]\n cat_feats.loc[cat_feats[var].isnull(), var] = mode_\n cat_feats[var+'_missing'] = 1*cat_feats[var].isna()\n\n#%% \nnum_columns = df.select_dtypes(include=['int64', 'float64']).columns\nnum_feats = df.loc[:, num_columns]\n\nfor var in num_columns:\n if sum(1*num_feats[var].isnull()):\n print(var, 'has missings')\n num_feats.loc[num_feats[var].isnull(), var] = 0\n num_feats[var+'_missing'] = 1*num_feats[var].isnull()"
},
{
"alpha_fraction": 0.6987654566764832,
"alphanum_fraction": 0.7209876775741577,
"avg_line_length": 47.599998474121094,
"blob_id": "37519adf6e4c97a3d19ec7487008592dd77c74d4",
"content_id": "d5f38ee13d49dda47e349bbeb31a3cfd0ad76296",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1215,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 25,
"path": "/Group_F_TTS.py",
"repo_name": "juanbretti/gmbd_python_group1",
"src_encoding": "UTF-8",
"text": "# %%\n# https://pypi.org/project/pyttsx3/\n\nimport pyttsx3\nengine = pyttsx3.init() # object creation\n\n\"\"\" RATE\"\"\"\nrate = engine.getProperty('rate') # getting details of current speaking rate\nengine.setProperty('rate', 150) # setting up new voice rate\n\"\"\"VOLUME\"\"\"\nvolume = engine.getProperty('volume') #getting to know current volume level (min=0 and max=1)\nengine.setProperty('volume',1.0) # setting up volume level between 0 and 1\n\"\"\"VOICE\"\"\"\nvoices = engine.getProperty('voices') #getting details of current voice\nengine.setProperty('voice', voices[1].id) #changing index, changes voices. 1 for female\n\n\"\"\"Saving Voice to a file\"\"\"\nengine.save_to_file('Clean and develop using Python. This is the presentation from group F. Abdulaziz, Juan Pedro, Jacob, Aleksandar, Esperanza and Addison', 'storage/slide_1.mp3')\nengine.save_to_file('EXPLORATORY DATA ANALYSIS, or EDA for short.', 'storage/slide_5.mp3')\nengine.save_to_file(\"DATA PREPARATION. Let's talk about data quality and how to fix.\", 'storage/slide_11.mp3')\nengine.save_to_file(\"Modelling. We are going to create and evaluate linear regression models.\", 'storage/slide_21.mp3')\nengine.save_to_file(\"Thank you.\", 'storage/slide_28.mp3')\nengine.runAndWait()\n\n# %%\n"
},
{
"alpha_fraction": 0.7076435089111328,
"alphanum_fraction": 0.7213807702064514,
"avg_line_length": 47.965518951416016,
"blob_id": "350ecfaed9e1286a2823e905531a8a8ba3615b0f",
"content_id": "215f8ad851bd57c09cab71dfab7ba39a32b47622",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2867,
"license_type": "no_license",
"max_line_length": 181,
"num_lines": 58,
"path": "/OLD/Group_F_TTS - Copy.py",
"repo_name": "juanbretti/gmbd_python_group1",
"src_encoding": "UTF-8",
"text": "# %%\n# https://pypi.org/project/pyttsx3/\n\nimport pyttsx3\nengine = pyttsx3.init() # object creation\n\n\"\"\" RATE\"\"\"\nrate = engine.getProperty('rate') # getting details of current speaking rate\nprint (rate) #printing current voice rate\nengine.setProperty('rate', 125) # setting up new voice rate\n\n\n\"\"\"VOLUME\"\"\"\nvolume = engine.getProperty('volume') #getting to know current volume level (min=0 and max=1)\nprint (volume) #printing current volume level\nengine.setProperty('volume',1.0) # setting up volume level between 0 and 1\n\n\"\"\"VOICE\"\"\"\nvoices = engine.getProperty('voices') #getting details of current voice\n#engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male\nengine.setProperty('voice', voices[1].id) #changing index, changes voices. 1 for female\n\nengine.say(\"Hello World!\")\nengine.say('My current speaking rate is ' + str(rate))\nengine.say('My current speaking rate is ' + str(rate) + ', this is a demo using TTS. Please consider saying Juan Pedro.')\nengine.runAndWait()\nengine.stop()\n\n\"\"\"Saving Voice to a file\"\"\"\n# On linux make sure that 'espeak' and 'ffmpeg' are installed\nengine.save_to_file('Hello World', 'test.mp3')\nengine.runAndWait()\n\n# %%\n# https://pypi.org/project/gTTS/\n\nfrom gtts import gTTS\nimport os \n\n# tts = gTTS('There is a particular case in our dataset, that the column “birthplace”. This column has missing values in another way. We addressed this column in a particular way.')\ntts = gTTS('Let’s do a quick exploratory description of the column.\\\n Using “value_counts()” we get in descending order so that the first element is the most frequently-occurring element.\\\n It’s evident that the cells that contain “?” are not valid inputs in our data.\\\n To fix it, we did a for loop that is controlled with the .find().')\n# tts = gTTS('There is a particular case in our dataset, that the column “birthplace”. This column has missing values in another way. We addressed this column in a particular way.')\n# tts = gTTS('There is a particular case in our dataset, that the column “birthplace”. This column has missing values in another way. We addressed this column in a particular way.')\n# tts = gTTS('There is a particular case in our dataset, that the column “birthplace”. This column has missing values in another way. We addressed this column in a particular way.')\ntts.save('jp_slide_3.mp3')\n\n# os.system(\"mpg321 hello.mp3\") \n# %%\n# https://stackoverflow.com/questions/58614450/is-there-a-module-that-allows-me-to-make-python-say-things-as-audio-through-the\n# https://stackoverflow.com/questions/1614059/how-to-make-python-speak\n\nimport win32com.client as wincl\nspeaker = wincl.Dispatch(\"SAPI.SpVoice\")\nspeaker.Speak('My current speaking rate is, this is a demo using TTS. Please consider saying Juan Pedro.')\n# %%"
}
] | 3 |
hanhouchao/hello-world | https://github.com/hanhouchao/hello-world | c29f83356c95b230c06cfeaccfa3c5059d2f0d94 | 6751f814c5fb3d2c14e1b23aa6ea72f5eb0fa316 | 0fc403c73ad4bf73a640c9bf61a118954db7ec65 | refs/heads/master | 2021-07-11T04:22:51.826589 | 2020-07-10T07:29:09 | 2020-07-10T07:29:09 | 128,864,371 | 0 | 1 | null | 2018-04-10T02:51:07 | 2020-07-10T07:11:54 | 2020-07-10T07:29:09 | Python | [
{
"alpha_fraction": 0.8103896379470825,
"alphanum_fraction": 0.8233765959739685,
"avg_line_length": 24.66666603088379,
"blob_id": "49db80001ea61bded1e8e229c253c1a5a5fc7622",
"content_id": "ef4984ce48015be2865f1f6874af0425ff1a3a36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 743,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 15,
"path": "/README.md",
"repo_name": "hanhouchao/hello-world",
"src_encoding": "UTF-8",
"text": "### 提供http服务 访问80端口返回页面信息\n\n页面信息包含:\n\n1. Hello World 作为校验访问服务是否正确,同时会输出容器的hostname\n\n2. 如果设置了环境变量text 会在页面返回这个环境变量的value 作为校验环境变量是否生效,以及做LB规则匹配时使用\n\n3. 如果设置了COOKIE环境变量,会在浏览器访问时塞入以该环境变量的value为key的cookie,cookie的value为<cookie_value>-<container_hostname>\n\n### 同时在启动容器时会打印日志:logglogloglog 生成日志文件/var/hchan.txt\n\n### 在容器启动后会持续生成日志 每秒钟一条 且会吧日志输出到/var/hehe.txt文件中\n\n### 容器内包含命令 vim curl,没有bash只有sh\n"
},
{
"alpha_fraction": 0.6905965805053711,
"alphanum_fraction": 0.730030357837677,
"avg_line_length": 37.03845977783203,
"blob_id": "eacf5af0fe549e78d731c4dc30b00041863f6b6b",
"content_id": "3527064f75f5cdd62e8aeef5a2dfc678f7402464",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 989,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 26,
"path": "/Dockerfile",
"repo_name": "hanhouchao/hello-world",
"src_encoding": "UTF-8",
"text": "FROM alpine:3.11\n\nRUN apk update && apk add -u nginx php7-fpm curl wget vim python-dev py-pip && \\\n mkdir -p /run/nginx\nADD default.conf /etc/nginx/conf.d/\nADD 443.conf /etc/nginx/conf.d/\nADD nginx.conf /etc/nginx/\nADD php-fpm.conf /etc/php7/php-fpm.conf\nADD cert /cert\nCOPY . /\nRUN chmod -R 777 /var\nRUN chmod -R 777 /etc/nginx/conf.d/\nRUN chmod 777 /run.sh\nRUN pip install --upgrade pip -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com\nRUN pip install flask -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com\nRUN adduser -h /home/norootuser -s /bin/sh -D norootuser\nRUN adduser -h /home/nopasswduser -s /bin/sh -u 2001 -D nopasswduser\nRUN sed -ie 's/^nopasswduser:x:2001/nopasswduser:x:0/' /etc/passwd\nRUN adduser -h /home/mynewuser -s /bin/sh -u 2002 -D mynewuser\nRUN echo -e \"mynewpassword\\nmynewpassword\"|passwd mynewuser\nRUN sed -ie 's/^mynewuser:x:2002/mynewuser:x:0/' /etc/passwd\n\nENV LISTEN_PORT=80\n\nEXPOSE 80\nCMD /run.sh\n"
},
{
"alpha_fraction": 0.6888889074325562,
"alphanum_fraction": 0.6933333277702332,
"avg_line_length": 24,
"blob_id": "33ff559ab065df8b181f359b80ac97bb100ee9fb",
"content_id": "eef14ef3013bc6770a8f9b028bc7254485c1ec0f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 450,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 18,
"path": "/run.sh",
"repo_name": "hanhouchao/hello-world",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\necho \"logglogloglog\"\necho \"aaaaaaa\" > /var/hchan.txt\necho \"logglogloglog\"\necho \"logglogloglog\"\necho \"logglogloglog\"\nCONF_FILE=/etc/nginx/conf.d/default.conf\nmkdir -p /var/lib/nginx/logs\nmkdir -p /var/lib/nginx/tmp\nsed -i \"s/#LISTEN_PORT#/${LISTEN_PORT}/\" ${CONF_FILE}\n\nnohup php-fpm7 -d variables_order=\"EGPCS\" && exec nginx -g \"daemon off;\" &\nwhile true\ndo\n echo \"`hostname`: `date`\" >> /var/hehe.txt\n sleep 1\n ls -l /var/hehe.txt\ndone\n"
},
{
"alpha_fraction": 0.6022552251815796,
"alphanum_fraction": 0.6355714797973633,
"avg_line_length": 35.79245376586914,
"blob_id": "a76d9eded53e3e54f9cf324300679c0372578c31",
"content_id": "0092b98fe69b54d13d3cde8055d7dd65014f5a89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1951,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 53,
"path": "/alb_metrics_server.py",
"repo_name": "hanhouchao/hello-world",
"src_encoding": "UTF-8",
"text": "from flask import Response, Flask, request\n\n\napp = Flask(__name__)\n\n\[email protected]('/1xx')\ndef rsp_1xx():\n rsp_code = '100'\n if request.args.get('code') and str(request.args.get('code')).isdigit() and int(request.args.get('code')) > 99 and int(request.args.get('code')) < 102:\n rsp_code = request.args.get('code')\n return Response(\"Response Code: {rsp_code}\".format(rsp_code=rsp_code), int(rsp_code))\n\n\[email protected]('/2xx')\ndef rsp_2xx():\n rsp_code = '200'\n if request.args.get('code') and str(request.args.get('code')).isdigit() and int(request.args.get('code')) > 199 and int(request.args.get('code')) < 207:\n rsp_code = request.args.get('code')\n return Response(\"Response Code: {rsp_code}\".format(rsp_code=rsp_code), int(rsp_code))\n\n\[email protected]('/3xx')\ndef rsp_3xx():\n rsp_code = '300'\n if request.args.get('code') and str(request.args.get('code')).isdigit() and int(request.args.get('code')) > 299 and int(request.args.get('code')) < 309:\n rsp_code = request.args.get('code')\n return Response(\"Response Code: {rsp_code}\".format(rsp_code=rsp_code), int(rsp_code))\n\n\[email protected]('/4xx')\ndef rsp_4xx():\n rsp_code = '400'\n if request.args.get('code') and str(request.args.get('code')).isdigit() and int(request.args.get('code')) > 399 and int(request.args.get('code')) < 418:\n rsp_code = request.args.get('code')\n return Response(\"Response Code: {rsp_code}\".format(rsp_code=rsp_code), int(rsp_code))\n\n\[email protected]('/5xx')\ndef rsp_5xx():\n rsp_code = '500'\n if request.args.get('code') and str(request.args.get('code')).isdigit() and int(request.args.get('code')) > 499 and int(request.args.get('code')) < 506:\n rsp_code = request.args.get('code')\n return Response(\"Response Code: {rsp_code}\".format(rsp_code=rsp_code), int(rsp_code))\n\n\[email protected]('/')\ndef index():\n return Response(\"alb metrics test\", 200)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n\n"
},
{
"alpha_fraction": 0.6241135001182556,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 41.29999923706055,
"blob_id": "df61a3f013556848f88de6fc04a021022473f971",
"content_id": "bc841f2e30f727f63e803615df408a146e2c729e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 10,
"path": "/entrypoint.py",
"repo_name": "hanhouchao/hello-world",
"src_encoding": "UTF-8",
"text": "import random, os, time\nexit_code = random.randint(1, 100)\nsuccess_percent = int(os.getenv(\"SUCCESS_PERCENT\", \"100\"))\nsleep_second = int(os.getenv(\"SLEEP_SECOND\", \"60\"))\nprint(\"exit code: %s\"%({True:0,False:1}[exit_code <= success_percent]))\nprint(\"sleep %s second\"%sleep_second)\nfor i in range(sleep_second):\n print(\"+\"*30+\"cronjob\"+\"+\"*30)\n time.sleep(1)\nos._exit(({True:0,False:1}[exit_code <= success_percent]))\n"
}
] | 5 |
Tangdongle/bottlepi | https://github.com/Tangdongle/bottlepi | cb58f0c42462cb09e9b841c7d832ef37ac71d63d | ed3eaef36a5af9fa84588a49ffa7eba7a3082524 | 6247a7e3a8cf9f86c8d76781bddd2835a3b430d4 | refs/heads/master | 2020-12-25T00:50:52.930297 | 2016-04-19T07:31:49 | 2016-04-19T07:31:49 | 56,574,800 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6351791620254517,
"alphanum_fraction": 0.6400651335716248,
"avg_line_length": 30.487178802490234,
"blob_id": "a588fc5ef71db9eba1ad5cb0235fa520f1f430ba",
"content_id": "77350f11f26c9dae37ba1a80f3ce9fbe2f99b8c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1228,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 39,
"path": "/bot.py",
"repo_name": "Tangdongle/bottlepi",
"src_encoding": "UTF-8",
"text": "from bottle import Bottle, route, run, template, request\nimport os\nimport uuid\n\npi = Bottle()\n\[email protected]('/switch/<pin:int>/<state:re:(On|Off)>')\ndef switch(pin=None, state='On'):\n #switch on/off a pin here\n return template('switch_template', pin=pin, state=state)\n\[email protected]('/send/<pin:int>/<data>')\ndef send(pin=None, data=''):\n if not pin or not data:\n return template(\"Fail\");\n #Send data through pin here\n return template('send_template', pin=pin, data=data)\n\[email protected]('/upload', method=\"GET\")\ndef upload():\n return template('upload_form')\n\[email protected]('/do_upload', method=\"POST\")\ndef do_upload():\n upload = request.files.get('upload')\n name, ext = os.path.splitext(upload.filename)\n save_path = \"/home/pi/uploads\"\n if not os.path.exists(save_path):\n if os.path.exists(os.path.expanduser(\"~/uploads\")):\n save_path = os.path.expanduser(\"~/uploads\")\n else:\n save_path = os.makedirs(os.path.expanduser(\"~/uploads\"))\n i = 1\n while os.path.exists(os.path.join(save_path, upload.filename)):\n upload.filename = upload.filename + str(i)\n i += 1\n upload.save(save_path)\n\nrun(pi, host='localhost', port=8080, debug=True, reloader=True)\n"
}
] | 1 |
jaxoncreed/sklearn-experiments | https://github.com/jaxoncreed/sklearn-experiments | 086cd2631117280ba1b18f0694c082de9dc94f1e | 11b65d9670f42b62f6ce4a89644b1052d4cb7bb3 | c6df09ee024df7c94f218b8a0f035dcf8cb8cab0 | refs/heads/master | 2021-09-15T23:46:45.727273 | 2018-06-13T01:31:53 | 2018-06-13T01:31:53 | 104,154,198 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6563002467155457,
"alphanum_fraction": 0.6798927783966064,
"avg_line_length": 25.28169059753418,
"blob_id": "ec655c27c3311a24bb9fb6e58cb972cefe611fdb",
"content_id": "4cd3d2e6705b89980aa8445aef05f2686ef659f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1865,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 71,
"path": "/candidate_neural_net.py",
"repo_name": "jaxoncreed/sklearn-experiments",
"src_encoding": "UTF-8",
"text": "import csv\nimport random\nfrom sklearn.neural_network import MLPClassifier\n\nIMPORTANT_COLUMNS = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\nEXAMPLE_COLUMN = 21\n\nallData = []\n\nallInput = []\nallOutput = []\n\nwith open('CandidateSummary.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n allData.append(row)\nallData.pop(0)\n\nrandom.seed(1000)\nrandom.shuffle(allData)\n\nfor row in allData:\n allOutput.append(row[EXAMPLE_COLUMN])\n rowData = []\n for colNum in IMPORTANT_COLUMNS:\n float(row[colNum])\n rowData.append(float(row[colNum]))\n allInput.append(rowData)\n\n\nsetSizes = []\npercentageCorrect = []\ntrainingPercentageCorrect = []\n\nfor setSize in range(5, len(allData), 5):\n splitIndex = int(round(setSize * 0.7) - 1)\n\n trainingInput = allInput[:splitIndex]\n trainingOutput = allOutput[:splitIndex]\n testInput = allInput[splitIndex:setSize]\n testOutput = allOutput[splitIndex:setSize]\n\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 10), random_state=1)\n clf = clf.fit(trainingInput, trainingOutput)\n\n\n totalCorrect = 0\n for index, inputRow in enumerate(testInput):\n if testOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n\n setSizes.append(setSize)\n percentageCorrect.append(float(totalCorrect) / len(testInput))\n\n totalCorrect = 0\n for index, inputRow in enumerate(trainingInput):\n if trainingOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n\n setSizes.append(setSize)\n trainingPercentageCorrect.append(float(totalCorrect) / len(trainingInput))\n\n\nfor size in setSizes:\n print(size)\nprint('================')\nfor percentage in percentageCorrect:\n print(percentage)\nprint('================')\nfor percentage in trainingPercentageCorrect:\n print(percentage)"
},
{
"alpha_fraction": 0.7567067742347717,
"alphanum_fraction": 0.7641072869300842,
"avg_line_length": 37.60714340209961,
"blob_id": "b7c239b7b2a08f2070ab4b7a24aeca895da8ad64",
"content_id": "a92d520c7d9b533ca82fc312b58f2fbd21fd9a40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 1081,
"license_type": "no_license",
"max_line_length": 216,
"num_lines": 28,
"path": "/README.txt",
"repo_name": "jaxoncreed/sklearn-experiments",
"src_encoding": "UTF-8",
"text": "# Set Up\nInstall sklearn:\n```bash\npip install -U scikit-learn\n```\n\nEdit lines 78 and 79 of \"run_all.py\" to dictate the classifier and data set you'd like to test\n\nRun the program:\n```bash\npython run_all.py\n```\n\nIf you want, you can also check out the other python files which are very similar to run_all.py which is a unified file I made after realizing the tasks that needed to be done between each algorithm are very similar.\n\nResources:\n - https://www.kaggle.com/danerbland/electionfinance\n - https://www.kaggle.com/annavictoria/speed-dating-experiment\n\nTutorials:\n - http://scikit-learn.org/stable/install.html\n - https://docs.python.org/2/library/csv.html\n - http://scikit-learn.org/stable/modules/tree.html\n - http://scikit-learn.org/stable/modules/neural_networks_supervised.html\n - http://scikit-learn.org/stable/modules/ensemble.html\n - http://scikit-learn.org/stable/modules/svm.html\n - http://scikit-learn.org/stable/modules/neighbors.html\n - https://stats.stackexchange.com/questions/181/how-to-choose-the-number-of-hidden-layers-and-nodes-in-a-feedforward-neural-netw\n"
},
{
"alpha_fraction": 0.624544620513916,
"alphanum_fraction": 0.6429872512817383,
"avg_line_length": 32.03007507324219,
"blob_id": "d178fc04b973547d9e667238578139b71361865d",
"content_id": "12f6349fe1b9e6bfe147ca7a877ebebbaa17c455",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4392,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 133,
"path": "/run_all.py",
"repo_name": "jaxoncreed/sklearn-experiments",
"src_encoding": "UTF-8",
"text": "import csv\nimport random\nfrom sklearn import tree\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom datetime import datetime\nfrom sklearn import svm\nfrom sklearn.neighbors import KNeighborsRegressor\n\n\ndef getOutputAndInputByColumnList(IMPORTANT_COLUMNS, EXAMPLE_COLUMN, fileLocation):\n allData = []\n allInput = []\n allOutput = []\n\n with open(fileLocation, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n allData.append(row)\n allData.pop(0)\n\n random.seed(1000)\n random.shuffle(allData)\n\n for row in allData:\n allOutput.append(float(row[EXAMPLE_COLUMN]))\n rowData = []\n for colNum in IMPORTANT_COLUMNS:\n float(row[colNum])\n rowData.append(float(row[colNum]))\n allInput.append(rowData)\n return (allInput, allOutput)\n\ndef getOutputAndInputByColumnRange(IMPORTANT_COLUMNS_RANGE, EXAMPLE_COLUMN, fileLocation):\n allData = []\n allInput = []\n allOutput = []\n\n with open('SpeedDating.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n allData.append(row)\n allData.pop(0)\n\n random.seed(1000)\n random.shuffle(allData)\n\n for rowNumber, row in enumerate(allData):\n allOutput.append(float(row[EXAMPLE_COLUMN]))\n rowData = []\n for colNum in IMPORTANT_COLUMNS_RANGE:\n try:\n float(row[colNum])\n rowData.append(float(row[colNum]))\n except:\n pass\n allInput.append(rowData)\n return (allInput, allOutput)\n\n# ==================================================================\n# Modify dynamic data\n\ndatingData = getOutputAndInputByColumnRange(range(12, 82), 11, 'SpeedDating.csv')\ncandidateData = getOutputAndInputByColumnList([11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 21, 'CandidateSummary.csv')\n\ndecisionTreeClassifier = tree.DecisionTreeClassifier()\nneuralNetClassifier1 = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 10), random_state=1)\nneuralNetClassifier2 = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)\nadaBoostClf = AdaBoostClassifier(n_estimators=10)\nsvmClassifier = svm.SVC()\nsvmClassifier2 = svm.SVC(kernel='linear')\nkNeighbors2 = KNeighborsRegressor(n_neighbors=2)\nkNeighbors4 = KNeighborsRegressor(n_neighbors=4)\nkNeighbors8 = KNeighborsRegressor(n_neighbors=8)\nkNeighbors16 = KNeighborsRegressor(n_neighbors=16)\n\n\ndataSets = [candidateData, datingData]\nclassifiers = [svmClassifier2]\n\n# ==================================================================\n\nfor dataIndex, dataSet in enumerate(dataSets):\n for classifierIndex, clf in enumerate(classifiers):\n startTime= datetime.now()\n\n setSizes = []\n percentageCorrect = []\n trainingPercentageCorrect = []\n\n for setSize in range(5, len(dataSet[0]), 5):\n splitIndex = int(round(setSize * 0.7) - 1)\n\n trainingInput = dataSet[0][:splitIndex]\n trainingOutput = dataSet[1][:splitIndex]\n testInput = dataSet[0][splitIndex:setSize]\n testOutput = dataSet[1][splitIndex:setSize]\n\n try:\n clf = clf.fit(trainingInput, trainingOutput)\n\n\n totalCorrect = 0\n for index, inputRow in enumerate(testInput):\n if testOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n\n percentageCorrect.append(float(totalCorrect) / len(testInput))\n\n totalCorrect = 0\n for index, inputRow in enumerate(trainingInput):\n if trainingOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n trainingPercentageCorrect.append(float(totalCorrect) / len(trainingInput))\n except:\n percentageCorrect.append('-')\n trainingPercentageCorrect.append('-')\n\n setSizes.append(setSize)\n\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print('DataIndex: {} - ClassifierIndex: {}'.format(dataIndex, classifierIndex))\n for size in setSizes:\n print(size)\n print('================')\n for percentage in percentageCorrect:\n print(percentage)\n print('================')\n for percentage in trainingPercentageCorrect:\n print(percentage)\n timeElapsed=datetime.now()-startTime\n print('Time elpased (hh:mm:ss.ms) {}'.format(timeElapsed))\n print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')"
},
{
"alpha_fraction": 0.6588541865348816,
"alphanum_fraction": 0.6729166507720947,
"avg_line_length": 24.95945930480957,
"blob_id": "dc92cd9536d6a3e71702e5810a83a7e29525f68c",
"content_id": "0e06e48f7a6c71fa1a1609f96a6cc1892921f479",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1920,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 74,
"path": "/dating_neural_net.py",
"repo_name": "jaxoncreed/sklearn-experiments",
"src_encoding": "UTF-8",
"text": "import csv\nimport random\nfrom sklearn.neural_network import MLPClassifier\n\nIMPORTANT_COLUMNS_RANGE = range(12, 82)\nEXAMPLE_COLUMN = 11\n\nallData = []\n\nallInput = []\nallOutput = []\n\nwith open('SpeedDating.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n allData.append(row)\nallData.pop(0)\n\nrandom.seed(1000)\nrandom.shuffle(allData)\n\nfor rowNumber, row in enumerate(allData):\n allOutput.append(row[EXAMPLE_COLUMN])\n rowData = []\n for colNum in IMPORTANT_COLUMNS_RANGE:\n try:\n float(row[colNum])\n rowData.append(float(row[colNum]))\n except:\n pass\n allInput.append(rowData)\n\n\nsetSizes = []\npercentageCorrect = []\ntrainingPercentageCorrect = []\n\nfor setSize in range(5, len(allData), 5):\n splitIndex = int(round(setSize * 0.7) - 1)\n\n trainingInput = allInput[:splitIndex]\n trainingOutput = allOutput[:splitIndex]\n testInput = allInput[splitIndex:setSize]\n testOutput = allOutput[splitIndex:setSize]\n\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)\n clf = clf.fit(trainingInput, trainingOutput)\n\n\n totalCorrect = 0\n for index, inputRow in enumerate(testInput):\n if testOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n\n setSizes.append(setSize)\n percentageCorrect.append(float(totalCorrect) / len(testInput))\n\n totalCorrect = 0\n for index, inputRow in enumerate(trainingInput):\n if trainingOutput[index] == clf.predict([inputRow])[0]:\n totalCorrect += 1\n\n setSizes.append(setSize)\n trainingPercentageCorrect.append(float(totalCorrect) / len(trainingInput))\n\n\nfor size in setSizes:\n print(size)\nprint('================')\nfor percentage in percentageCorrect:\n print(percentage)\nprint('================')\nfor percentage in trainingPercentageCorrect:\n print(percentage)"
}
] | 4 |
codefish-yu/web-fresh-store | https://github.com/codefish-yu/web-fresh-store | eb7c1ab59cb906d5fb6353ad0bc3ffb1256efa4c | 92cdc931adf266b1f2dfe1f55376581ead101817 | 7a839cefcf336058a92f36d29bdf59790bf0fc1a | refs/heads/master | 2021-01-13T18:48:31.313940 | 2020-03-11T08:50:40 | 2020-03-11T08:50:40 | 242,461,695 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8145695328712463,
"alphanum_fraction": 0.8145695328712463,
"avg_line_length": 20.285715103149414,
"blob_id": "c18548d467b02275a841950810f63631f7ef83ce",
"content_id": "ac5f3a12ca41813dea453f49419eb0f93676474c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 169,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 7,
"path": "/apps/goods/admin.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import GoodsType\n\n# Register your models here.\n\n#将该模型类GoodType注册到admin中\nadmin.site.register(GoodsType)\n\n\n"
},
{
"alpha_fraction": 0.7221095561981201,
"alphanum_fraction": 0.7626774907112122,
"avg_line_length": 18.719999313354492,
"blob_id": "f3dfa9b36b666d8b4a8badf5f57fa036452680ef",
"content_id": "c2b4a14bd0ecb763f4a2c020ae4b5d1f61ba5bbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 629,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 25,
"path": "/tiantianxiansheng/celery.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "'''\ncelery的配置文件\n'''\nimport os\nfrom django.conf import settings\nfrom celery import Celery\n\n#为celery设置环境变量,告诉celery,jdaong的配置文件在哪\nos.environ.setdefault('DJANGO_SETTINGS_MODULE','tiantianxiansheng.settings')\n\n\n#创建应用\n#创建celery类的实例对象\n#Celery('name',broker='redis://你想用的redis服务端的ip地址/数据库号')\napp = Celery('celery_tasks.tasks')\n\n\n#配置应用\napp.conf.update(\n #配置broker\n BROKER_URL ='redis://:[email protected]:6379/1',\n)\n\n#设置celery的应用app自动去找工人(任务函数)\napp.autodiscover_tasks(settings.INSTALLED_APPS)\n"
},
{
"alpha_fraction": 0.6323613524436951,
"alphanum_fraction": 0.6500857472419739,
"avg_line_length": 35.375,
"blob_id": "79dda491e2ad2f9ebd6d37d28be2eea671c52f1c",
"content_id": "10c5b8e5a6801ece73601ad559bc50ed81c7893b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1931,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 48,
"path": "/apps/order/models.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\n# Create your models here.\nfrom db.base_model import BaseModel\n\n\nclass OrderInfo(BaseModel):\n '''订单模型类'''\n PAY_METHOD_CHOICES = (\n (1,'货到支付'),\n (2,'微信支付'),\n (3,'支付宝'),\n (4,'银联支付')\n )\n ORDER_STATUS_CHOICES = (\n (1,'待支付'),\n (2,'待支付'),\n (3,'待收据'),\n (4,'待评价'),\n (5,'已完成')\n )\n order_id = models.CharField(max_length=128,primary_key=True,verbose_name='订单id')\n user = models.ForeignKey('user.User',verbose_name='用户')\n addr = models.ForeignKey('user.Address',verbose_name='地址')\n pay_method = models.SmallIntegerField(choices=PAY_METHOD_CHOICES,default=3,verbose_name='支付方式')\n total_count = models.IntegerField(default=1,verbose_name='商品数量')\n total_price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='总金额')\n transit_price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='商品运费')\n order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES,default=1,verbose_name='订单状态')\n trade_no = models.CharField(max_length=128,verbose_name='支付编号')\n\n class Meta:\n db_table = 'df_order_info'\n verbose_name = '订单'\n verbose_name_plural = verbose_name\n\nclass OrderGoods(BaseModel):\n '''订单商品模型类'''\n order = models.ForeignKey('OrderInfo',verbose_name='订单')\n sku = models.ForeignKey('goods.GoodsSKU',verbose_name='商品SKU')\n count = models.IntegerField(default=1,verbose_name='商品数目')\n price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='商品价格')\n comment = models.CharField(max_length=256,verbose_name='评论')\n\n class Meta:\n db_table = 'df_order_goods'\n verbose_name = '订单商品'\n verbose_name_plural = verbose_name\n\n\n\n"
},
{
"alpha_fraction": 0.6011344194412231,
"alphanum_fraction": 0.6127996444702148,
"avg_line_length": 32.433692932128906,
"blob_id": "968de80ca04fc7a79a627065c5b56b8575d5e94b",
"content_id": "8c8d5c6f9345bf6ce4a7dd631c3b0605c4cbb1e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12286,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 279,
"path": "/apps/user/views.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "import re\n\nfrom django.core import mail\nfrom django.core.urlresolvers import reverse #url反向解析\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import View\n\nfrom apps.goods.models import GoodsSKU #这里尽然不用加apps.goods.models\nfrom tiantianxiansheng import settings\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer #加密用\nfrom itsdangerous import SignatureExpired #用于过期时异常处理\nfrom celery_tasks.tasks import send_register_active_email\nfrom .models import User, Address\nfrom django.contrib.auth import authenticate, login, logout # django内置的用户系统的用户登录认证等\nfrom utils.mixin import LoginRequiredMixin\nfrom django_redis import get_redis_connection\n\n# Create your views here.\n\n\n#/user/register\n#类视图\nclass RegisterView(View):\n #显示注册页面\n def get(self,request):\n return render(request,'register.html')\n\n #注册\n def post(self,request):\n # 接收数据\n username = request.POST.get('user_name') # user_name为前端该标签的name\n password = request.POST.get('pwd')\n email = request.POST.get('email')\n # 用户协议\n allow = request.POST.get('allow')\n\n # 数据校验\n # 1. 判断用户是否都填了,不完整重新返回注册页面并提示:数据不完整\n if not all([username, password, email]):\n return render(request, 'register.html', {'errmsg': '数据不完整'})\n # 2. 校验传来的邮箱格式是否正确\n if not re.match(r'^[a-z0-9][\\w.\\-]*@[a-z0-9\\-]+(\\.[a-z]{2,5}){1,2}$', email):\n return render(request, 'register.html', {'errmsg': '邮箱格式不正确'})\n\n # 3. 校验用户是否勾选同意协议,当用户勾选checkbox时,前端传过来的是:on\n if allow != 'on':\n return render(request, 'register.html', {'errmsg': '请同意协议'})\n # 4. 校验用户名是否重复\n try:\n user = User.objects.get(username=username)\n # 如果用户名不存在,说明该用户名可用\n except User.DoesNotExist:\n user = None\n # 如果用户名已存在\n if user:\n return render(request, 'register.html', {'errmsg': '用户名已存在'})\n\n # 业务处理:进行用户注册\n # django提供的用户认证系统创建用户需要用:create_user()\n user = User.objects.create_user(username, email, password)\n # 将刚创建的用户都置于不激活\n user.is_active = 0\n user.save()\n\n #发送用户激活的邮件,包含激活链接(激活链接还总需要包含用户的省份信息):http://127.0.0.1:8000/user/active/用户mysql_id\n #用户mysql_id需要加密(身份信息)\n #1. 使用itsdangerous模块加密用户的身份信息,生成激活token\n serializer = Serializer(settings.SECRET_KEY,3600) #将settings.py中的secret_key引进来当作现成的密钥,3600为国企时间\n info = {'confirm':user.id}\n token = serializer.dumps(info).decode() #加密返回的是bytes,需要decode()\n\n #发邮件,\n #经过app.task装饰之后就有了delay()方法\n #使用delay()就可以将任务放入任务队列\n send_register_active_email.delay(email,username,token)\n\n # 注册完跳转到首页\n return redirect(reverse('goods:index')) # 反向解析:reverse('主路由中name:分路由中name')\n\n#激活用户\nclass ActiveView(View):\n #激活用户\n def get(self,request,token): #token这个参数从re捕获的Url中传来,是用户的mysql数据表id\n #解密,获取用户信息info,并激活该用户,激活后跳转到登录页面\n serializer = Serializer(settings.SECRET_KEY,3600)\n try:\n info = serializer.loads(token)\n user_id = info['confirm']\n\n #激活\n user = User.objects.get(id=user_id)\n user.is_active = 1\n user.save()\n\n #跳转到登录页面,使用url反向解析\n return redirect(reverse('user:login'))\n\n #用于处理激活链接已过期的情况\n except SignatureExpired as e:\n return HttpResponse('激活链接已过期')\n\n#登录\n#url:http://127.0.0.1:8000/user/login\nclass LoginView(View):\n #显示登录页面\n def get(self,request):\n #判断是否勾选记住用户名\n if 'username' in request.COOKIES:\n username = request.COOKIES.get('username')\n checked = 'checked'\n else:\n username = ''\n checked = ''\n\n return render(request,'login.html',{'username':username,'checked':checked})\n\n #登录\n def post(self,request):\n '''登录校验'''\n #接收数据\n username = request.POST.get('username')\n password = request.POST.get('pwd')\n\n\n #校验数据\n #校验用户是否都输了\n if not all([username,password]):\n return render(request,'login.html',{'errmsg':'数据不完整'})\n\n\n #业务处理:登录校验\n #使用django内置的用户认证系统时,有一个函数authenticate(),可以校验用户名和密码\n #帮我们省略了password解码的步骤\n user = authenticate(username=username,password=password)\n if user is not None:\n #如果用户已激活,记录下用户的会话状态,并跳转到首页\n if user.is_active:\n #django内置的用户认证系统的login()已经封装了session\n login(request,user) #login(reqeust,user)将user.id保存到session中\n\n #获取登录后要跳转到的地址,默认跳转到首页\n #用login_required()装饰器之后,目标地址会跟在查询字符串中:?next=xxx,可以使用get('next')取出\n #前端登录表单中没有设置action,当没有设置action时,表单数据会提交到浏览器地址栏中的地址\n next_url = request.GET.get('next',reverse('goods:index')) #reverse('goods:index')为默认值\n\n #跳转到登录后的目标地址,并判断用户是否勾选记住用户名\n response = redirect(next_url)#redirect返回的是httpResponseRedirect类的对象\n remember = request.POST.get('remember')\n #勾选则记住cookies:set_cookie('cookie名',cookie值,过期时间=xxx)\n if remember == 'on':\n response.set_cookie('username',username,max_age=7*24*3600)\n #否则删除cookies\n else:\n response.delete_cookie('username')\n\n #跳转\n return response\n\n\n else:\n return render(request,'login.html',{'errmsg':'帐号未激活'})\n else:\n return render(request,'login.html',{'errmsg':'用户名或密码错误'})\n\n#url:http://127.0.0.1:8000/user/logout\nclass LogoutView(View):\n # 退出登录,也使用django的用户认证系统\n def get(self,request):\n #清除用户的session信息,logout()为django认证系统函数\n logout(request)\n\n #跳转到首页\n return redirect(reverse('goods:index'))\n\n\n#用户中心信息页面:http://127.0.0.1.:8000/user\n#需要先判断是否已经登录,在url中套用装饰器:login_required()\nclass UserInfoView(LoginRequiredMixin,View):\n #显示用户中心信息页面\n def get(self,request):\n #请求过来后,模板层会先根据用户登录状态显示不同的网页欢迎信息,详见模板层\n\n #获取用户的个人信息\n user = request.user\n default_addr = Address.objects.get_default_address(user)\n # default_addr = {user:xxx,phone:xxx,addr:xxx.....}\n\n #获取用户的历史浏览记录\n #用户历史浏览记录存在redis数据库中(缓存),流程是在用户访问商品详情页时存,在访问个人信息页时取(显示)\n con = get_redis_connection('default')\n\n #用户id,从redis中取出的数据格式为:history_用户id:[1,2,3]\n #拼接历史浏览记录的key\n history_key = 'history_%d' %user.id\n\n #获取用户最新浏览的5条商品id\n #lrange是Python操作redis的list的方法\n sku_ids = con.lrange(history_key,0,4)\n\n #遍历用户浏览的商品id,从商品表:GoodSKU中查询用户浏览的商品的具体信息\n #数据库返回给你的数据顺序是按照他存的顺序给你返回,和用户访问页面的顺序不一样\n goods_li = []\n for id in sku_ids:\n goods = GoodsSKU.objects.get(id=id)\n goods_li.append(goods)\n\n #组织传给模板的数据\n context = {'page':'user',\n 'address':default_addr,\n 'goods_li':goods_li}\n\n #给模板中传个标记:page='user',代表拿的是信息页面,然后在页面中做点渲染\n #将数据库中的默认收件地址信息传入模板\n return render(request,'user_center_info.html',context)\n\n\n# 用户中心信息页面:http://127.0.0.1:8000/user/order\n#需要先判断是否已经登录,在url中套用装饰器:login_required()\nclass UserOrderView(LoginRequiredMixin,View): #多继承,使用到了LoginRequired类的as_view()\n # 显示用户中心订单页面\n def get(self, request):\n # 给模板中传个标记:page='order',代表拿的是信息页面,然后在页面中做点渲染\n return render(request, 'user_center_order.html',{'page':'order'})\n\n\n# 用户中心信息页面:http://127.0.0.1:8000/user/address\n#需要先判断是否已经登录,在url中套用装饰器:login_required()\nclass AddressView(LoginRequiredMixin,View):\n # 显示用户中心地址页面\n def get(self, request):\n #获取登录的用户对象\n user = request.user\n #获取用户的默认收获地址\n #这里使用自定义模型管理器类中的方法\n default_addr = Address.objects.get_default_address(user)\n\n # 给模板中传个标记:page='address',代表拿的是信息页面,然后在页面中做点渲染\n #将default_addr传过去,用于判断显示地址\n return render(request, 'user_center_site.html',{'page':'address','address':default_addr})\n\n #添加地址\n def post(self,request):\n #接收前端传来的表单数据:receiver,zip_code,addr,phone\n receiver = request.POST.get('receiver')\n addr = request.POST.get('addr')\n zip_code = request.POST.get('zip_code')\n phone = request.POST.get('phone')\n\n #校验数据\n if not all([receiver,addr,phone]): #不校验邮编,因为现在基本不用邮编了\n return render(request,'user_center_site.html',{'errmsg':'数据不完整'})\n\n #校验手机号\n if not re.match(r'^1[3|4|5|7|8][0-9]{9}$',phone):\n return render(request,'user_center_site.html',{'errmsg':'手机格式不正确'})\n\n #业务处理:添加地址\n #如果用户已存在默认收获地址,添加的地址不作为默认收获地址,否则作为默认收获地址\n #获取登录用户,这里user是Address表的外键,关联User表\n user = request.user\n #判断该用户是否有默认地址\n #这里使用自定义模型管理器类中的方法(在models层自定义了一个模型管理器类,就是对objects进行了重写,让他有了新的方法)\n default_addr = Address.objects.get_default_address(user)\n\n #Address表中字段:user,receiver,addr,zip_code,phone,is_default\n if default_addr:\n is_default = False\n else:\n is_default = True\n Address.objects.create(user=user,\n receiver=receiver,\n addr=addr,\n zip_code=zip_code,\n phone=phone,\n is_default=is_default)\n\n #返回应答,刷新地址页面,redirect()是get方式,触发上面的get(request)\n return redirect(reverse('user:address'))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7567567825317383,
"alphanum_fraction": 0.7567567825317383,
"avg_line_length": 33.42856979370117,
"blob_id": "2c03b4dcfce8f836eaf5566eabd0f331398828e0",
"content_id": "0b02baf4bb217600aa9393f16a05988b1d8041fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 633,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 14,
"path": "/utils/mixin.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.decorators import login_required\n\n\n#工具类视图\n#用于当项目中用到装饰器login_required()非常多时,不用在url中一个个套login_required()\n#直接在这个工具类中使用login_required()装饰下as_view()\n#然后在url层引入该新写的修改了性能的as_view()\nclass LoginRequiredMixin(object):\n @classmethod\n def as_view(cls, **initkwargs):\n #调用父类的as_view,返回一个值\n #super(LoginRequiredMixin,cls)表示调用LoginRequiredMixin类的父类\n view = super(LoginRequiredMixin,cls).as_view(**initkwargs)\n return login_required(view)"
},
{
"alpha_fraction": 0.73617023229599,
"alphanum_fraction": 0.73617023229599,
"avg_line_length": 25.11111068725586,
"blob_id": "23a86c95896947b53def956b2f4db523786356af",
"content_id": "1d11d76e2f1ba4592030b8f3643de2880dbcd1d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 632,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 18,
"path": "/apps/goods/search_indexes.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "'''定义搜索引擎的索引类'''\nfrom haystack import indexes\n#导入你的模型类\nfrom apps.goods.models import GoodsSKU\n\n#定义对于GoodsSKU模型类的索引类\n#索引类名格式:模型类名+Index\nclass GoodsSKUIndex(indexes.SearchIndex,indexes.Indexable):\n #use_template指定根据表中的哪些字段建立索引文件的说明放在一个文件中\n text = indexes.CharField(document=True,use_template=True)\n\n def get_model(self):\n #返回你的模型类\n return GoodsSKU\n\n #建立索引的数据\n def index_queryset(self,using=None):\n return self.get_model().objects.all()\n"
},
{
"alpha_fraction": 0.6767346858978271,
"alphanum_fraction": 0.7036734819412231,
"avg_line_length": 22.538461685180664,
"blob_id": "aa2f698f7f5aa2f81f6ac08b44f585fe7f6b1fde",
"content_id": "dc290d969f41c737f2ba40256ac33a0e00519d2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2645,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 52,
"path": "/README.md",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "## 架构设计\n1. 用户模块\n 1. 注册页面\n 注册时校验用户名是否\n 2. 登录页面\n 3. 用户中心\n 4. 其他\n2. 商品模块\n 1. 首页信息显示(种类信息,商品信息)\n 2. 商品详情信息\n 3. 商品列表信息及分页\n 4. 商品新品信息\n 5. 商品搜索\n3. 购物车模块\n 1. 用户购物车信息\n 2. 购物信息的编辑(更新,删除)\n 3. 详情页和列表页加入商品到购物车\n4. 订单模块\n 1. 展示用户选择的商品信息\n 2. 订单创建\n 3. 订单支付\n\n前端: 用户相关 商品相关 购物车相关 订单相关 后端管理(这里使用dajngo提供的,实际前端会自己做)\n后端: 用户模块 商品模块 购物车模块 订单模块 后台管理模块\n\n数据库:mysql\nsession & 缓存服务器:redis:同时保存用户浏览记录\n异步任务处理:celery(用于发邮件)\n图片存储系统:分布式文件存储系统fastdis(替代django本身的图片存储功能)\n\n\n## 数据表设计\n1. 用户相关表\n 1. 用户表:id,用户名,密码,邮箱,isActive,权限标识(是否有管理员权限,可以登录后台管理系统)\n 2. 收件人地址表(和用户表一对多):id,收件人,地址,邮编,联系方式,是否是默认地址,用户id(外键)\n2. 商品相关表\n 1. 商品种类表:Id,种类名称,种类logo,图片\n 2. 商品sku表:Id,名称,商品简介,价格,销量(按照人气排序),单位,isActive,库存,商品图片(只记录一张,其余的放在商品图片表中,以空间换时间),spu_id(关联商品spu表)\n 3. 商品图片表(一个商品不知一张图片):id,图片,商品sku_id(外键,关联商品sku表)\n 4. 商品spu表:id,商品名称,详情\n 5. 首页轮播商品表:sku_id(外键),图片,Index(用于控制轮播展示图片顺序)\n 6. 首页促销活动表:id,活动图片,活动页面url,index(控制展示顺序)\n 7. 首页分类商品展示表:id,sku_id(关联商品sku表),种类id(关联商品种类表),展示标识(指明展示图片还是文字),index\n3. 购物车相关表(购物车中增加商品数量:很平凡,所以这个表再redis中实现)\n 1. 订单信息表:订单id,收获地址id(外键),支付方式,商品,总金额,运费,支付状态,订单创建时间,总数目\n 2. 订单商品表:id,订单id,sku_id(外键),商品数量,商品价格,评论\n\n\n\n\n首页促销活动表:id,图片,活动url,index(控制图片显示顺序)\n首页分类商品展示表:id,sku_id,种类id,index(展示顺序),展示标识(以文字形式还是图片展示)\n\n"
},
{
"alpha_fraction": 0.6255580186843872,
"alphanum_fraction": 0.6328125,
"avg_line_length": 31.545454025268555,
"blob_id": "505b04b08166d9aa9ac5fd3e932e13856a42d968",
"content_id": "d425faa66e3f2494ac56bd1070ee5957f48749e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2332,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 55,
"path": "/apps/goods/views.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom django_redis import get_redis_connection\n\nfrom .models import GoodsType, IndexGoodsBanner, IndexTypeGoodsBanner\n\n# Create your views here.\n\n#首页:http://127.0.0.:8000\nfrom django.views import View\n\n\nclass IndexView(View):\n def get(self,request):\n '''显示首页'''\n #获取商品的种类信息:新鲜水果,海鲜水产等\n types = GoodsType.objects.all()\n\n #获取首页轮播商品信息:商品轮播表\n goods_banners = IndexGoodsBanner.objects.all().order_by('index')\n\n #获取首页促销活动信息:商品促销表\n promotion_banners = IndexTypeGoodsBanner.objects.all().order_by('index')\n\n #获取首页分类商品展示信息:各分类下商品的具体信息\n for type in types:\n #获取所有以图片展示的type种类的首页分类商品展示信息\n image_banners = IndexTypeGoodsBanner.objects.filter(type=type,display_type=1)\n #获取所有以文字展示的type种类的首页分类商品的展示信息\n title_banners = IndexTypeGoodsBanner.objects.filter(type=type,display_type=0)\n\n #动态给type增加属性,分别保存以图片展示和以文字展示的首页分类商品的信息\n #type是GoodsType类的实例,通过在类的外面给实例添加属性的方式给该种类的商品添加信息\n type.image_banners = image_banners\n type.title_banners = title_banners\n\n #获取用户购物车中商品的数目\n user = request.user\n cart_count = 0\n #使用django用户认证系统的is_authenticated()判断用户是否已登陆\n if user.is_authenticated():\n #购物车中信息是以散列形式存储在redis缓存中,连接redis\n conn = get_redis_connection('default')\n #拼该用户的购物车的key\n cart_key = 'cart_%d'%user.id\n #hlen返回该key的值的个数\n cart_count = conn.hlen(cart_key)\n\n #组织传给模板的信息\n context = {'type':types,\n 'goods_banners':goods_banners,\n 'promotion_banners':promotion_banners,\n 'cart_count':cart_count}\n\n #渲染模板\n return render(request,'index1.html',context)\n\n\n"
},
{
"alpha_fraction": 0.6660919785499573,
"alphanum_fraction": 0.6741379499435425,
"avg_line_length": 28.440677642822266,
"blob_id": "83e47206c9c46920de1c802bd7cb82a4b2f33e8e",
"content_id": "70c34dcc8a57fca58a68a45cae276b5eea9f7607",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2088,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 59,
"path": "/apps/user/models.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.conf import settings\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom db.base_model import BaseModel\n# Create your models here.\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n\n\nclass User(AbstractUser,BaseModel):\n '''用户表'''\n\n #生成用户签名字符串\n def generate_active_token(self):\n serializer = Serializer(settings.SECRET_KEY,3600)\n info = {'confirm':self.id}\n token = serializer.dumps(info)\n return token.decode()\n\n class Meta:\n db_table = 'df_user'\n verbose_name = '用户'\n verbose_name_plural = verbose_name\n\nclass AddressManager(models.Manager):\n '''自定义地址模型管理器类'''\n #作用:\n #1. 改变原有查询的结果集:all()\n #2. 封装方法:让用户操作模型类对应的数据表(增删改查)\n\n #自定义获取用户默认收获地址的功能\n def get_default_address(self,user):\n try:\n #self.model:该属性获得实例化的对象所在的模型类(哪个模型类中实例化就是哪个模型类)\n default_addr = self.get(user=user,is_default=True)\n #当没有默认地址时,返回None\n except self.model.DoesNotExist:\n default_addr = None\n\n return default_addr\n\n\nclass Address(BaseModel):\n '''收件人地址类'''\n user = models.ForeignKey('User',verbose_name='所属账户')\n receiver = models.CharField(max_length=20,verbose_name='收件人')\n addr = models.CharField(max_length=256,verbose_name='收件地址')\n zip_code = models.CharField(max_length=6,null=True,verbose_name='邮政编码')\n phone = models.CharField(max_length=11,verbose_name='联系电话')\n is_default = models.BooleanField(default=False,verbose_name='是否默认')\n\n #实例化地址管理器模型类,这样就可以在Address中使用AddressManager中的方法了\n objects = AddressManager()\n\n\n\n class Meta:\n db_table = 'df_address'\n verbose_name = '地址'\n verbose_name_plural = verbose_name\n\n\n\n"
},
{
"alpha_fraction": 0.68784099817276,
"alphanum_fraction": 0.6995323300361633,
"avg_line_length": 29.176469802856445,
"blob_id": "9eae04e394b46a12e5acd6ab690324df0861e512",
"content_id": "dcbf5645a7b5d87b5a781bdd4b87ac53bbae68c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3334,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 85,
"path": "/celery_tasks/tasks.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "'''\n celery_tasks\n'''\nimport time\nfrom celery import Celery\nfrom django.http import request\nfrom django.shortcuts import render\nfrom django_redis import get_redis_connection\n# from goods.models import GoodsType, IndexGoodsBanner, IndexTypeGoodsBanner\nfrom django.template import loader, RequestContext\nfrom tiantianxiansheng.celery import app\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom apps.goods.models import GoodsType, IndexGoodsBanner, IndexTypeGoodsBanner\nimport os\nimport django\n\n\n\n\n#定义celery的任务函数(worker)\[email protected]\ndef send_register_active_email(to_email,username,token):\n '''发送激活邮件'''\n #组织邮件信息\n subject = '天天生鲜欢迎信息' # 标题\n # 邮件内容\n message = ''\n # 传html格式内容\n html_message = '<h1>%s,欢迎您成为天天生鲜注册会员</h1>请点击下面链接激活您的账户<br/><a href=\"http://127.0.0.1:8000/user/active/%s\">http://127.0.0.1:8000/user/active/%s</a>' % (\n username, token, token)\n # 发件人\n sender = settings.EMAIL_FROM\n # 收件人\n receiver = [to_email]\n send_mail(subject, message, sender, receiver, html_message=html_message)\n #测试使用celery处理第三方io不用等待5秒\n time.sleep(5)\n\[email protected]\ndef generate_static_index_html():\n '''\n 产生首页静态页面\n 用户未登录状态下,首页的访问次数较多,但页面变化不大,使用celery将首页设置为静态页面\n '''\n # 获取商品的种类信息:新鲜水果,海鲜水产等\n types = GoodsType.objects.all()\n\n # 获取首页轮播商品信息:商品轮播表\n goods_banners = IndexGoodsBanner.objects.all().order_by('index')\n\n # 获取首页促销活动信息:商品促销表\n promotion_banners = IndexTypeGoodsBanner.objects.all().order_by('index')\n\n # 获取首页分类商品展示信息:各分类下商品的具体信息\n for type in types:\n # 获取所有以图片展示的type种类的首页分类商品展示信息\n image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1)\n # 获取所有以文字展示的type种类的首页分类商品的展示信息\n title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0)\n\n # 动态给type增加属性,分别保存以图片展示和以文字展示的首页分类商品的信息\n # type是GoodsType类的实例,通过在类的外面给实例添加属性的方式给该种类的商品添加信息\n type.image_banners = image_banners\n type.title_banners = title_banners\n\n # 组织传给模板的信息\n context = {'type': types,\n 'goods_banners': goods_banners,\n 'promotion_banners': promotion_banners\n }\n\n #使用模板\n #1. 使用django_templates模块加载templates文件夹下的static_index.html模板文件\n temp = loader.get_template('static_index.html')\n #2. 渲染模板\n static_index_html = temp.render(context)\n\n #生成首页对应的静态文件\n #1. 设置生成文件的路径:是生成在celery任务这里的static文件夹下(腾讯云)\n save_path = os.path.join(settings.BASE_DIR,'static/static_index.html')\n #2. 生成文件\n with open(save_path,'w') as f:\n f.write(static_index_html)\n\n"
},
{
"alpha_fraction": 0.6005692481994629,
"alphanum_fraction": 0.6005692481994629,
"avg_line_length": 27.486486434936523,
"blob_id": "9a72dd9b498cb90af90d27557dfcc4496d0bd7d0",
"content_id": "450ee88bdbd3a08222241246a7e9ab26101ceac1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2824,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 74,
"path": "/utils/fdfs/storage.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "'''\n自定义静态文件存储类,将django默认的文件存储行为(默认存储到MEDIA_ROOT指定的路径下)修改为存储到远程fastDFS中去\n需要在django+nginx+fastdfs业务逻辑基础之上理解喜爱面的代码\n'''\nfrom django.core.files.storage import Storage #重写文件存储类,必须继承自该类\nfrom fdfs_client.client import Fdfs_client\n\nfrom tiantianxiansheng import settings\n\n\nclass FDFSStorage(Storage):\n '''fastdfs文件存储类'''\n\n def __init__(self,client_conf=None,base_url=None):\n '''初始化'''\n #给用户自己传fastdfs客户端配置文件的选择,如果用户没传,就用我们的\n if client_conf is None:\n client_conf = settings.FDFS_CLIENT_CONF\n self.client_conf = client_conf\n\n #给用户自己传他的nginx路由的选择,如果用户没传,就用我们的\n if base_url is None:\n base_url = settings.FDFS_URL\n self.base_url = base_url\n\n\n #重写_open()方法,用于打开文件,规定必须重写,但是我们这里用不到,这届pass\n def _open(self,name,mode='rb'):\n pass\n\n def _save(self, name, content):\n '''\n :param name:你选择的上传文件的名字\n :param content:File类的对象,包含你上传的文件内容,有了这个对象就可以获取文件内容\n :return:\n '''\n # 创建一个fdfs_client对象\n client = Fdfs_client(self.client_conf)\n\n # 上传文件到fastdfs系统中\n # upload_by_buffer()方法是根据文件内容上传文件,回值格式为:\n #dict {\n # 'Group name' : group_name,\n # 'Remote file_id' : remote_file_id,\n # 'Status' : 'Upload successed.',\n # 'Local file name' : '',\n # 'Uploaded size' : upload_size,\n # 'Storage IP' : storage_ip\n # }\n res = client.upload_by_buffer(content.read())\n print(res)\n\n #判断是否上传成功\n if res.get('Status') != 'Upload successed.':\n #上传失败\n raise Exception('上传文件到fastdfs失败')\n\n #获取返回的文件id\n filename = res.get('Remote file_id')\n return filename\n\n # django在上传文件之前,会先调用该方法,用于判断文件名是否可用(但文件其实保存在fastdfs中,所以这里直接返回false就行)\n def exists(self,name):\n return False\n\n\n #该方法用于向nginx和fastdfs请求拿保存的静态文件\n #返回你要访问文件的url路径\n def url(self,name):\n '''\n :param name:django保存文件到fastdfs后fastdfs返回给django的文件id:groupxxxx...\n :return 你要访问的文件在nginx中的url\n '''\n return self.base_url + name\n"
},
{
"alpha_fraction": 0.6166666746139526,
"alphanum_fraction": 0.6722221970558167,
"avg_line_length": 19.11111068725586,
"blob_id": "6de65f8e36c36c0bd2753acc30d173922aef1cc8",
"content_id": "2751145d8a6a10593cbd0d81abf69f013010aeb0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 186,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 9,
"path": "/apps/goods/urls.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom .views import IndexView\n\nfrom . import views\n\nurlpatterns = [\n #首页:http://127.0.0.1:8000\n url(r'^$',IndexView.as_view(),name='index'),\n]"
},
{
"alpha_fraction": 0.6174812316894531,
"alphanum_fraction": 0.6832706928253174,
"avg_line_length": 45.30434799194336,
"blob_id": "a9623f34bb317c15cd6cb513ab98415728a93b6a",
"content_id": "9214043baa55064f62cfba8da23cfb59ef7bdf16",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1226,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 23,
"path": "/apps/user/urls.py",
"repo_name": "codefish-yu/web-fresh-store",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\nfrom .views import RegisterView, ActiveView, LoginView, UserInfoView, UserOrderView, AddressView, LogoutView\n\nurlpatterns = [\n #http://127.0.0.1:8000/user/register\n #使用类视图的方式注册,as_view()是从view类中继承来的方法\n url(r'^register$',RegisterView.as_view(),name='register'),\n #该url就是用户激活的链接,需要用re将该用户在Mysql中user_id捕获给后端\n #http://127.0.0.1:8000/user/active/user_id\n url(r'^active/(?P<token>.*)$',ActiveView.as_view(),name='active'),\n #登录:http://127.0.0.1:8000/user/login\n url(r'^login$',LoginView.as_view(),name='login'),\n #退出:http://127.0.0.1:8000/user/logout\n url(r'^logout$',LogoutView.as_view(),name='logout'),\n #用户中心-用户信息页:http://127.0.0.1:8000/user\n url(r'^$',UserInfoView.as_view(),name='user'), #UserInfoView.as_view():类.类方法\n #用户中心-订单页http://127.0.0.1:8000/user/order\n url(r'^order',UserOrderView.as_view(),name='order'),\n #用户中心-地址页,http://127.0.0.1:8000/user/address\n url(r'^address',AddressView.as_view(),name='address'),\n\n]"
}
] | 13 |
elgalu/taupage | https://github.com/elgalu/taupage | 78461af88803b9576104cb608201fcba212b06b0 | b3d9ae36c72f14f69c82e634de02b8208d27123f | 28f780efdb585ac595dcca45d5cff29426f93e55 | refs/heads/master | 2020-04-05T23:19:20.329039 | 2015-06-12T11:05:11 | 2015-06-12T11:05:11 | 35,494,402 | 0 | 0 | null | 2015-05-12T14:53:03 | 2015-05-08T12:05:08 | 2015-05-12T10:17:23 | null | [
{
"alpha_fraction": 0.6183689832687378,
"alphanum_fraction": 0.6215360164642334,
"avg_line_length": 24.775510787963867,
"blob_id": "f4e49a521c54547174b910802dd002e0e4b7b8a3",
"content_id": "5e0baf0b45561030da880ef210e325fa556eb906",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2526,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 98,
"path": "/runtime/usr/local/lib/python3.4/dist-packages/taupage/__init__.py",
"repo_name": "elgalu/taupage",
"src_encoding": "UTF-8",
"text": "import json\nimport logging\nimport os\nimport time\nimport yaml\nimport zign.api\n\n\nCREDENTIALS_DIR = '/meta/credentials'\n\n\ndef configure_logging():\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n logging.getLogger('urllib3.connectionpool').setLevel(logging.WARN)\n\n\ndef is_sensitive_key(k):\n '''\n >>> is_sensitive_key(1)\n False\n\n >>> is_sensitive_key('foo')\n False\n\n >>> is_sensitive_key('DB_PASSWORD')\n True\n '''\n lower = str(k).lower()\n return 'pass' in lower or \\\n 'private' in lower or \\\n 'secret' in lower\n\n\ndef mask_dictionary(d: dict):\n '''\n >>> mask_dictionary({'a': 'b'})\n {'a': 'b'}\n\n >>> mask_dictionary({'priVaTe': 'b'})\n {'priVaTe': 'MASKED'}\n '''\n masked_dict = {}\n for key, val in d.items():\n if is_sensitive_key(key):\n val = 'MASKED'\n if isinstance(val, dict):\n val = mask_dictionary(val)\n masked_dict[key] = val\n return masked_dict\n\n\ndef get_config():\n with open('/etc/taupage.yaml') as fd:\n config = yaml.safe_load(fd)\n return config\n\n\ndef get_token(config: dict, token_name: str, scopes: list):\n token_url = config.get('token_service_url')\n\n if not token_url:\n logging.warning('No token service URL configured in Taupage YAML (\"token_service_url\" property)')\n return\n\n if not config.get('mint_bucket'):\n # berry will only be started if a mint bucket is configured,\n # skip OAuth token retrieval if this is not the case\n logging.warning('No mint bucket configured in Taupage YAML (\"mint_bucket\" property)')\n return\n\n path = os.path.join(CREDENTIALS_DIR, 'user.json')\n\n while not os.path.exists(path):\n logging.info('Waiting for berry to download OAuth credentials to {}..'.format(path))\n time.sleep(5)\n\n with open(path) as fd:\n credentials = json.load(fd)\n\n user = credentials.get('application_username')\n passwd = credentials.get('application_password')\n\n if not user or not passwd:\n logging.warning('Invalid OAuth credentials: application user and/or password missing in %s', path)\n return\n\n token = zign.api.get_named_token(scopes, 'services', token_name, user, passwd, url=token_url, use_keyring=False)\n return token\n\n\ndef get_boot_time():\n with open('/run/taupage-init-ran/date') as fd:\n boot_time = fd.read().strip()\n\n if boot_time.endswith('+0000'):\n boot_time = boot_time[:-5] + 'Z'\n\n return boot_time\n"
}
] | 1 |
MedyG/MyScrapy3 | https://github.com/MedyG/MyScrapy3 | 8aa6b860c4c5c39907a470eed98d8d984019eabb | 2e1cc74cca43f56c7f0b91e4e3b4e1e82f343677 | 345b0a656d6c98d1146b013e01aee13013e09761 | refs/heads/master | 2020-04-14T02:33:49.274846 | 2017-07-13T03:40:10 | 2017-07-13T03:40:10 | 61,731,860 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6405383944511414,
"alphanum_fraction": 0.6674584150314331,
"avg_line_length": 25.851064682006836,
"blob_id": "157f9284d6b9baf840bb2e19edadef370107d904",
"content_id": "89d12b41a9c69f1f74ca5942091d46cd7a566404",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1309,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 47,
"path": "/MyScrapy/crewler_ex02.py",
"repo_name": "MedyG/MyScrapy3",
"src_encoding": "UTF-8",
"text": "\"\"\"\n爬虫闯关第三题\nhttp://www.heibanke.com/lesson/crawler_ex02/\n黑板客记账模拟登陆\n\"\"\"\nimport bs4\nfrom bs4 import BeautifulSoup\nimport requests\nimport urllib.request\nimport re\n\nurl = \"http://www.heibanke.com/lesson/crawler_ex02/\"\nlogin_url = \"http://www.heibanke.com/accounts/login/?next=/lesson/crawler_ex02/\"\n \ndata = { 'username': 'medyg', 'password': '19931122bihu'}\ndata2 = {'username':'medyg', 'password': 1}\n\nr = requests.get(login_url)\nif r.status_code == 200:\n cookie = r.cookies\n print(\"Get login_url success.\")\nelse:\n print(\"cannot access \" + login_url)\ndata['csrfmiddlewaretoken'] = cookie['csrftoken']\nprint(data)\n\nr2 = requests.post(login_url, data = data, allow_redirects=False, cookies = cookie) #重定向post\nif r2.status_code == 302:\n cookie2 = r2.cookies\n print(\"Post login_url data success.\")\nelse:\n print(\"post login_url falied\")\ndata2['csrfmiddlewaretoken'] = cookie2['csrftoken']\nprint(data2)\n\nfor num in range(0, 31):\n data2['password'] = num\n r3 = requests.post(url, data2, cookies = cookie2)\n print(\"try \" + str(num))\n result = re.findall(r'密码错误', r3.text)\n print(result)\n #soup = BeautifulSoup(r3.text, \"lxml\")\n #print(soup.body.h3.string)\n if not result: \n print(num)\n print(r3.text)\n break\n\n"
},
{
"alpha_fraction": 0.5874755382537842,
"alphanum_fraction": 0.6438356041908264,
"avg_line_length": 30.170732498168945,
"blob_id": "45adf372feb3b2893a1a01c34d81afecabc540dd",
"content_id": "8f056144823091dbe36d9f7d9ba41a1f282ca305",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2631,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 82,
"path": "/MyScrapy/crawler_ex03.py",
"repo_name": "MedyG/MyScrapy3",
"src_encoding": "UTF-8",
"text": "\"\"\"\n爬虫闯关第四题\nhttp://www.heibanke.com/lesson/crawler_ex03/\n黑板客爬虫之寻找长密码\nanswer is : 1490163668774566288173618538253675264972338183086744513535774895069524432954894613647990394874326048\n\"\"\"\n\nimport bs4\nfrom bs4 import BeautifulSoup\nimport requests\nimport urllib.request\nimport re\nimport threading\nimport queue\n\nurl = \"http://www.heibanke.com/lesson/crawler_ex03/\"\nlogin_url = \"http://www.heibanke.com/accounts/login/?next=/lesson/crawler_ex03/\"\npw_url = \"http://www.heibanke.com/lesson/crawler_ex03/pw_list/?page=\"\npages = range(1,14)\ndata={'username': 'medyg', 'password': '19931122bihu', 'csrfmiddlewaretoken': ''}\n\n\"\"\" 打开登陆页面 \"\"\"\nloginr = requests.get(login_url)\nif loginr.status_code == 200:\n cookie = loginr.cookies\n print(\"get login_url success, csrftoken is :\" + cookie['csrftoken'])\nelse:\n print(\"get login_url failed\")\ndata['csrfmiddlewaretoken'] = cookie['csrftoken']\n\n\"\"\" 登陆 \"\"\"\npwr = requests.post(login_url, data = data, allow_redirects = False, cookies = cookie)\nif pwr.status_code == 302:\n cookie2 = pwr.cookies\n print(\"post login_url success, csrftoken is :\" + cookie2['csrftoken'])\nelse:\n print(\"post login_url failed, status_code is \" + str(pwr.status_code))\n\n\"\"\" 第四关闯关 \"\"\"\npw_list = [-1]*101\ncount = 0\nq = queue.Queue()\nfor i in range(3):\n q.put('finish')\n\"\"\" 检索密码 \"\"\"\ndef retrivePw(page):\n global count\n global threadCount\n global q\n print(\"retriving page: \" + str(page))\n pwg = requests.get(pw_url + str(num), cookies = cookie2)\n soup = BeautifulSoup(pwg.text, \"lxml\")\n pos_list = soup.find_all('td', title='password_pos')\n val_list = soup.find_all('td', title='password_val')\n for i in range(len(pos_list)):\n if pw_list[int(pos_list[i].text)] == -1:\n pw_list[int(pos_list[i].text)] = int(val_list[i].text)\n count += 1\n q.put('finish')\n print(\"now queue lenth is \" + str(q.qsize()))\n print(\"page: \" + str(page) + \" retrived. \" + \"Now has \" + str(count) + \" positions\")\n threadCount -= 1\n #print(pw_list)\n\"\"\" 多线程 \"\"\"\nthreadCount = 0\nwhile count != 100:\n for num in range(14):\n if q.get():\n print(\"now queue lenth is \" + str(q.qsize()))\n threading.Thread(target = retrivePw, args=(num,)).start()\n threadCount += 1\n print(threadCount)\n if count >= 100:\n break;\npw = \"\"\nfor num in range(1, len(pw_list)):\n pw+=str(pw_list[num])\nprint(pw)\ndata['password'] = pw\ndata['csrfmiddlewaretoken'] = cookie2['csrftoken']\nr = requests.post(url, data=data, cookies = cookie2)\nprint(r.text)"
},
{
"alpha_fraction": 0.5569394826889038,
"alphanum_fraction": 0.5800711512565613,
"avg_line_length": 22.45833396911621,
"blob_id": "e6ac0f04f4811fbafa8622aa3b404f5c726edfb9",
"content_id": "e92de735154a8522f4bbfce92dd92274ef6d7dd9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 562,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 24,
"path": "/MyScrapy/crawler_ex00.py",
"repo_name": "MedyG/MyScrapy3",
"src_encoding": "UTF-8",
"text": "import urllib.request\nimport bs4\nfrom bs4 import BeautifulSoup\n\nurl_head = \"http://www.heibanke.com/lesson/crawler_ex00/\"\ntail = \"\"\nwhile(True):\n data = urllib.request.urlopen(url_head + tail).read();\n data = data.decode('UTF-8')\n soup = BeautifulSoup(data, \"lxml\")\n h3_str = soup.body.h3.string\n tail = \"\"\n for s in h3_str:\n if not s.isdigit():\n continue\n else:\n tail+=s\n #tail = h3_str[11:len(h3_str)]\n if tail.isdigit():\n print(tail)\n else:\n print(h3_str)\n break\n#print(data)"
},
{
"alpha_fraction": 0.6514438986778259,
"alphanum_fraction": 0.6823371648788452,
"avg_line_length": 32.11111068725586,
"blob_id": "2ba8678440dd3a9ea67ac50b4649a8e7a1ec4e20",
"content_id": "63a8f41ded6c76dd75ada23f019689503cf53641",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1549,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 45,
"path": "/MyScrapy/crewler_ex01.py",
"repo_name": "MedyG/MyScrapy3",
"src_encoding": "UTF-8",
"text": "import bs4\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport string\nimport re\nimport http.cookiejar\n\nurl = \"http://www.heibanke.com/lesson/crawler_ex01/\"\ncj = http.cookiejar.LWPCookieJar()\ncookie_support = urllib.request.HTTPCookieProcessor(cj)\nopener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)\nurllib.request.install_opener(opener)\n\ndata = urllib.request.urlopen(url).read()\ndata = data.decode('utf-8')\n# headers和postData分析自抓包\nheaders = {\n 'Accept': 'text/html, application/xhtml+xml, image/jxr',\n 'Referer': 'http://www.heibanke.com/lesson/crawler_ex01/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'\n }\npassword = 0\nwhile True:\n postData = {\n 'csrfmiddlewaretoken' : 'sczCT2OaFZ5BAxTXR0rBNSFuqummuY2y',\n 'username' : 'medyg',\n 'password' : password \n }\n postData = urllib.parse.urlencode(postData)\n postData = postData.encode('utf-8') #进行编码,否则会报POST data should be bytes or an iterable of bytes. It cannot be str.错误.\n req = urllib.request.Request(url, postData, headers)\n print(req)\n response = urllib.request.urlopen(req)\n text = response.read().decode('utf-8')\n #print(text)\n soup = BeautifulSoup(text, \"lxml\")\n msg = soup.body.h3.string\n if msg == \"您输入的密码错误, 请重新输入\":\n password+=1\n continue\n else:\n print(msg)\n print(\"password is : \" + str(password))\n break\n #print(data)"
},
{
"alpha_fraction": 0.6896551847457886,
"alphanum_fraction": 0.7931034564971924,
"avg_line_length": 8.666666984558105,
"blob_id": "de048cb7af822b266f52d11d55c3546d58a6948d",
"content_id": "d2bd11781d5d9cf6e45638427d33c036a39aaba2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 11,
"num_lines": 3,
"path": "/README.md",
"repo_name": "MedyG/MyScrapy3",
"src_encoding": "UTF-8",
"text": "# MyScrapy3\n我的爬虫学习实践\nby py36\n"
}
] | 5 |
hir-gbsl/Cryto-Demo | https://github.com/hir-gbsl/Cryto-Demo | 0b88691d6fa3d8403088489fb40c137078c1a326 | 8d64a4cbb002349049391d3b07a65e514c5deb58 | fe180e48f0ee5b4eeddc37c3bfa10d3d7199e835 | refs/heads/main | 2023-03-12T06:45:23.356269 | 2020-12-12T13:19:37 | 2020-12-12T13:19:37 | 320,835,010 | 1 | 1 | null | 2020-12-12T13:17:15 | 2020-12-15T18:23:57 | 2020-12-12T13:19:38 | Python | [
{
"alpha_fraction": 0.6010953783988953,
"alphanum_fraction": 0.6412596702575684,
"avg_line_length": 30.701492309570312,
"blob_id": "1e7cd828d3a1563842d3305180a06a249c684659",
"content_id": "91dd57390227df46497530fe297d29f784794aee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2201,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 67,
"path": "/Demoprogramm Kryptofunktionen v2.py",
"repo_name": "hir-gbsl/Cryto-Demo",
"src_encoding": "UTF-8",
"text": "# Demoprogramm Kryptofunktionen hir, 10.12.2020\r\n\r\ndef byte_xor(ba1, ba2): # XOR für List of Bytes\r\n return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])\r\n\r\ndef convert(s): # List of Bytes to string (binary encoded)\r\n str1 = \"\" \r\n return(str1.join(s)) \r\n\r\n\r\n# einen Key mit pbkdf2 aus einem Passwort erzeugen\r\n\r\nfrom passlib.hash import pbkdf2_sha256\r\n\r\npassword = input (\"Gib den Schlüssel ein:\")\r\n\r\nkey = pbkdf2_sha256.hash(password, rounds=200000, salt_size=0) \r\nkey2 = pbkdf2_sha256.hash(password, rounds=200000, salt_size=0) # ohne salt gibt es immer das Gleiche\r\n\r\nprint(\"ohne Salt\")\r\nprint(\"Die ersten zwei abgeleiteten Schlüssel sind nun:\", key, key2)\r\n\r\n# und mit salt\r\nkey = pbkdf2_sha256.hash(password, rounds=200000, salt_size=16) \r\nkey2 = pbkdf2_sha256.hash(password, rounds=200000, salt_size=16) \r\nprint(\"mit Salt\")\r\nprint(\"Die ersten zwei abgeleiteten Schlüssel sind nun:\", key, key2) # der salt steht im Output\r\n\r\n\r\n# Neuer: Scrypt statt pbkdf2 (Memory-hard) dazu verwenden\r\nimport pyscrypt\r\n\r\nsalt = b'aa1f2d3f4d23ac44e9c5a6c3d8f9ee8c'\r\npasswd = password.encode('utf-8')\r\n\r\nskey = pyscrypt.hash(passwd, salt, N = 2048, r = 8, p = 1, dkLen = 32)\r\nprint(\"Scrypt-abgeleiteter Schlüssel:\", skey.hex()) # key ist nicht druckbar, nur als hex\r\n\r\n# XOR nur demo\r\nklartext = b\"abcdefghijkl01234567890123456789\" # 32 bytes\r\nkey = b\"bacdefghijkl01234567890123456789\" # 32 bytes\r\n\r\ncryptotext = byte_xor(klartext, key)\r\nprint (\"Demo für XOR\")\r\nprint (\"Klartext:\", klartext, \"key: \", key, \"Cryptotext\", cryptotext) # cryptotext ist nicht druckbar\r\n\r\n# und wieder entschlüsseln\r\nklartext = cryptotext # 32 bytes\r\ndecryptotext = byte_xor(klartext, key)\r\nprint(\"Wieder entschlüsselt: \", decryptotext)\r\n\r\n# XOR mit key aus scrypt\r\nprint (\"und jetzt mit dem scrypt-key\")\r\n\r\nklartext = \"abcdefghijkl01234567890123456789\" # 32 bytes\r\nkey = skey\r\nklartext = klartext.encode(\"utf-8\")\r\n\r\ncryptotext = byte_xor(klartext, key)\r\n\r\nprint (\"Klartext:\", klartext, \"key: \", key, \"Cryptotext\", cryptotext) # cryptotext ist nicht druckbar\r\n\r\n# und wieder entschlüsseln\r\n\r\nklartext = byte_xor(cryptotext, key)\r\n\r\nprint (\"Entschlüsselt: \", klartext)\r\n"
},
{
"alpha_fraction": 0.7969924807548523,
"alphanum_fraction": 0.8045112490653992,
"avg_line_length": 65.5,
"blob_id": "f2dae8599bb831af4d1f52ff8063ad2dcc3e975b",
"content_id": "78505d5c4e9096cb2d560226e35ffb6124a0f86c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 133,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 2,
"path": "/README.md",
"repo_name": "hir-gbsl/Cryto-Demo",
"src_encoding": "UTF-8",
"text": "# Crypto-Demo\nEin Demoprogramm, das zeigt wie man aus einem Passwort einen beliebig langen Key generiert, mit pbkdf2 und mit scrypt.\n"
}
] | 2 |
zhangyimufasa9116/test1 | https://github.com/zhangyimufasa9116/test1 | 42e1554508fd7209bb2df8a16c617a3d89ca7374 | 6b8fa2c97cefc3eb444ce763fb1f3dd0aaffdc9e | 297d499ffda932119c19ce49c5c216d8ab4a84c3 | refs/heads/master | 2021-01-01T21:08:33.662615 | 2020-09-28T15:15:57 | 2020-09-28T15:15:57 | 239,339,902 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7037037014961243,
"alphanum_fraction": 0.7037037014961243,
"avg_line_length": 12.5,
"blob_id": "d1dd6179e40d4c2b9c2b6c261112cb1cac24cf3c",
"content_id": "cc688a5e915840e8fcb937550682fe0ac4cba4a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 27,
"license_type": "no_license",
"max_line_length": 15,
"num_lines": 2,
"path": "/lasti/print.py",
"repo_name": "zhangyimufasa9116/test1",
"src_encoding": "UTF-8",
"text": "may i help you.\nthank you.\n"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 6,
"blob_id": "73134b88d1be6bd8fcc5c47a042ae88c64f7851a",
"content_id": "97e0f963285126c2ef4bc70f51eec00fcdc58e1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 14,
"license_type": "no_license",
"max_line_length": 7,
"num_lines": 2,
"path": "/README.md",
"repo_name": "zhangyimufasa9116/test1",
"src_encoding": "UTF-8",
"text": "# test1\nsssss\n"
}
] | 2 |
xvanick1/fit-vut-ipp2019 | https://github.com/xvanick1/fit-vut-ipp2019 | dd3942d7057ea0c5e949139df92e403104aa4aae | db114ca34bd2155cebb91d7ad07ad07f83baf07e | 018e6479e9798a15a6a0b015629ad97724382e7d | refs/heads/master | 2022-12-31T06:32:32.348430 | 2020-10-21T17:31:47 | 2020-10-21T17:31:47 | 171,359,554 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5887314677238464,
"alphanum_fraction": 0.6039502620697021,
"avg_line_length": 41.93041229248047,
"blob_id": "b6f276aa5b5292206692779d0e7ba35217464330",
"content_id": "5bdbe4fd03ce5bf9502b7140c18b8cb2ef3b25f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 33390,
"license_type": "no_license",
"max_line_length": 426,
"num_lines": 776,
"path": "/interpret.py",
"repo_name": "xvanick1/fit-vut-ipp2019",
"src_encoding": "UTF-8",
"text": "# Created by PyCharm.\n# Author: Jozef Vanický\n# VUT Login: xvanic09\n# Date: 2019-04-06\n# Author's comment: Tento skript je upravenou kópiou kódu, ktorý som napísal pred rokom k projektu z predmetu IPP 2017/2018 k jazyku IPPcode18.\n# Verze Pythonu 3.6\n\nimport sys\nimport argparse\nimport xml.etree.ElementTree as XMLElemTree\nimport re\nimport copy\n\n## Pole inštrukcií jazyka IPPcode19\ninstructionList = [\"MOVE\", \"CREATEFRAME\", \"PUSHFRAME\", \"POPFRAME\", \"DEFVAR\", \"CALL\", \"RETURN\", \"PUSHS\", \"POPS\", \"ADD\",\n \"SUB\", \"MUL\", \"IDIV\", \"LT\", \"GT\", \"EQ\", \"AND\", \"OR\", \"NOT\", \"INT2CHAR\", \"STRI2INT\", \"READ\", \"WRITE\",\n \"CONCAT\", \"STRLEN\", \"GETCHAR\", \"SETCHAR\", \"TYPE\", \"LABEL\", \"JUMP\", \"JUMPIFEQ\", \"JUMPIFNEQ\", \"EXIT\",\n \"DPRINT\", \"BREAK\"]\n\n\n## Regulárne výrazy použité pri spracovaní argumentov jednotlivých inštrukcií\nclass Regex:\n var = r\"^(GF|LF|TF)@([A-Za-z\\-\\_\\*\\$%&][\\w\\-\\*\\_\\$%&]*)$\"\n integer = r\"^[+-]?\\d+$\"\n boolean = r\"^(true|false)$\"\n label = r\"^[A-Za-z\\-\\_\\*\\$%&][\\w\\-\\_\\*\\$%&]*$\"\n string = r\"^((\\x5C\\d{3})|[^\\x23\\s\\x5C])*$\"\n symb = r\"var|string|bool|int|nil\"\n type = r\"int|string|bool\"\n nil = r\"nil\"\n order = r\"^[0-9]+$\"\n\n\n##Nahradi escape sekvenciu za tisknutelný znak\ndef replaceEscapeSequence(match):\n number = int(match.group(1))\n return chr(number)\n\n\n## Kontrola typu argumentu inštrukcie\ndef checkvar(argtype, value):\n if argtype != 'var':\n err_xml_structure(\"Error: Argument type is not var!\")\n if not re.match(Regex.var, value):\n err_xml_structure(\"Error: Argument var lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checkint(argtype, value):\n if argtype != 'int':\n err_xml_structure(\"Error: Argument type is not int!\")\n if not re.match(Regex.integer, value):\n err_xml_structure(\"Error: Argument int lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checkbool(argtype, value):\n if argtype != 'bool':\n err_xml_structure(\"Error: Argument type is not bool!\")\n if not re.match(Regex.boolean, value):\n err_xml_structure(\"Error: Argument bool lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checklabel(argtype, value):\n if argtype != 'label':\n err_xml_structure(\"Error: Argument type is not label!\")\n if not re.match(Regex.label, value):\n err_xml_structure(\"Error: Argument label lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checkstring(argtype, value):\n if argtype != 'string':\n err_xml_structure(\"Error: Argument type is not symb!\")\n if not re.match(Regex.string, value):\n err_xml_structure(\"Error: Argument symb lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checknil(argtype, value):\n if argtype != 'nil':\n err_xml_structure(\"Error: Argument type is not nil!\")\n if not re.match(Regex.nil, value):\n err_xml_structure(\"Error: Argument nil lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checktype(argtype, value):\n if argtype != 'type':\n err_xml_structure(\"Error: Argument type is not type!\")\n if not re.match(Regex.type, value):\n err_xml_structure(\"Error: Argument type lexical error!\")\n\n\n## Kontrola typu argumentu inštrukcie\ndef checksymb(argtype, value):\n if argtype == 'var':\n checkvar(argtype, value)\n elif argtype == 'string':\n checkstring(argtype, value)\n elif argtype == 'bool':\n checkbool(argtype, value)\n elif argtype == 'int':\n checkint(argtype, value)\n elif argtype == 'nil':\n checknil(argtype, value)\n else:\n err_xml_structure(\"Error: Argument type lexical error: expected symb!\")\n\n\n## Kontrola neprázdnosti argumentu inštrukcie\ndef checkempty(argtype, value):\n if argtype is not None:\n err_xml_structure(\"Error: Instruction has too many arguments\")\n if value is not None:\n err_xml_structure(\"Error: Instruction has too many arguments\")\n\n\n## Vráti hodnotu argumentu\ndef parse_argument_value(argtype, value):\n if argtype == 'string' and value is None:\n return \"\"\n else:\n return value\n\n\n## Pomocné metody jednotlivých chybových kodov\ndef err_script_argument(text):\n print(text, file=sys.stderr)\n exit(10)\n\n\ndef err_input_file(text):\n print(text, file=sys.stderr)\n exit(11)\n\n\ndef err_well_formated_xml():\n print(\"Error: XML is not well formatted!\", file=sys.stderr)\n exit(31)\n\n\ndef err_xml_structure(text):\n print(text, file=sys.stderr)\n exit(32)\n\n\ndef err_semantic():\n print(\"Error: Semantic error!\", file=sys.stderr)\n exit(52)\n\n\ndef err_bad_operand():\n print(\"Error: Wrong operand type!\", file=sys.stderr)\n exit(53)\n\n\ndef err_variable_existance():\n print(\"Error: Variable doesn't exist!\", file=sys.stderr)\n exit(54)\n\n\ndef err_frame_existance():\n print(\"Error: Frame doesn't exist!\", file=sys.stderr)\n exit(55)\n\n\ndef err_missing_value():\n print(\"Error: Missing value!\", file=sys.stderr)\n exit(56)\n\n\ndef err_operand_value():\n print(\"Error: Wrong operand value!\", file=sys.stderr)\n exit(57)\n\n\ndef err_string():\n print(\"Error: Bad string!\", file=sys.stderr)\n exit(58)\n\n\n## Trieda inštrukcie kódu IPPcode19\nclass Instruction:\n order: int = 0\n opcode: str = None\n arg1type: str = None\n arg2type: str = None\n arg3type: str = None\n arg1value: str = None\n arg2value: str = None\n arg3value: str = None\n\n\n## Trieda premennej argumentu\nclass Variable:\n name: str\n type = None\n value = None\n\n\n## Trieda rámca\nclass Frame:\n arrayOfVariables = []\n\n ### Zadefinovanie premennej\n def def_var(self, name):\n\n for variable in self.arrayOfVariables:\n if variable.name == name:\n err_semantic()\n\n variable = Variable()\n variable.name = name\n variable.type = None\n variable.type = None\n self.arrayOfVariables.append(variable)\n\n ### Nastavenie hodnoty premennej\n def set_var_value(self, name, type, value):\n tempvar = None\n\n for variable in self.arrayOfVariables:\n if variable.name == name:\n tempvar = variable\n break\n if tempvar is None:\n err_variable_existance()\n\n tempvar.type = type\n tempvar.value = value\n\n ### Získanie hodnoty premennej\n def get_var_value(self, name):\n for variable in self.arrayOfVariables:\n if variable.name == name:\n return variable\n err_variable_existance()\n\n\n## Interprét\nclass Interpret:\n def __init__(self):\n ## Spracovanie vstupných argumentov\n self.sourceFile = sys.stdin\n self.inputFile = sys.stdin\n self.parse_arguments()\n\n ## Načítanie inštrukcií z XML reprezentácie\n self.xml_read()\n self.instructions = []\n self.parse_instructions()\n self.instructions.sort(key=self.sort_order)\n\n ## Inicializacie struktur\n self.frameStack = []\n self.tempframe = None\n self.localframe = None\n self.globalframe: Frame = Frame()\n self.stack = []\n self.pc_counter = 0\n self.pc_stack = []\n self.labels = {}\n\n ## Interpretacie inštrukcií\n self.interpret_labels()\n self.pc_counter = 0\n while self.pc_counter < len(self.instructions):\n self.interpret_instruction(self.instructions[self.pc_counter])\n self.pc_counter += 1\n\n ### Spracovanie vstupných argumentov\n def parse_arguments(self):\n parser = argparse.ArgumentParser(\n description=\"Napoveda k intepret.py. Interpret jazyka IPPcode19, vstupni format XML.\",\n epilog=\"Musi byt zadan alespon jeden z techto argumentu.\")\n parser.add_argument('-s', '--source', help='zdrojovy soubor ve formatu XML (jinak stdin)', metavar=\"sourceFile\",\n required=False)\n parser.add_argument('-i', '--input', help='vstupni soubor (jinak stdin)', metavar='inputFile', required=False)\n\n if (\"--help\" in sys.argv) and len(sys.argv) > 2:\n err_script_argument(\"Error: Wrong input!\")\n try:\n args = parser.parse_args()\n except:\n if (\"--help\" in sys.argv) and len(sys.argv) == 2:\n exit(0)\n else:\n exit(10) # no print !!!\n\n if not args.source and not args.input:\n err_script_argument(\"Error: --input or --source required!\")\n else:\n if args.source:\n self.sourceFile = args.source\n if args.input:\n try:\n self.inputFile = open(args.input)\n except:\n err_input_file(\"Error: Input file not found or insufficient permissions!\")\n\n ### Načítanie XML reprezentácie zo vstupu\n def xml_read(self):\n try:\n xmlObject = XMLElemTree.parse(self.sourceFile)\n self.root = xmlObject.getroot()\n except FileNotFoundError:\n err_input_file(\"Error: Source file not found!\")\n except:\n err_well_formated_xml()\n\n ### Parsovanie inštrukcií z XML reprezentácie\n def parse_instructions(self):\n instructionOrderList = []\n xmlProgramAttribs = ['language', 'name', 'description']\n for attrib in self.root.attrib:\n if attrib not in xmlProgramAttribs:\n err_xml_structure(\"Error: Unknown attribute \" + attrib + \" in Program!\")\n if self.root.tag != 'program' or self.root.get('language') != 'IPPcode19':\n err_xml_structure(\"Error: Not valid XML for IPPcode19!\")\n for elem in self.root:\n instruction = Instruction()\n if elem.tag != 'instruction':\n err_xml_structure(\"Error: Not instruction element - found: \" + elem.tag)\n if elem.get('order') is None:\n err_xml_structure(\"Error: Order not defined\")\n if re.match(Regex.order, elem.get('order')) is None:\n err_xml_structure(\"Error: Order is not number\")\n if elem.get('opcode') is None:\n err_xml_structure(\"Error: Opcode not defined\")\n instruction.opcode = str(elem.get('opcode')).upper()\n if not instruction.opcode in instructionList:\n err_xml_structure(\"Error: Unknown instruction: \" + instruction.opcode)\n if int(elem.get('order')) in instructionOrderList:\n err_xml_structure(\"Error: Duplicate order\")\n instruction.order = int(elem.get('order'))\n self.instructions.append(instruction)\n self.parse_instruction_arguments(instruction, elem)\n instructionOrderList.append(instruction.order)\n self.identify_instruction(instruction)\n\n ### Získanie hodnoty orderu inštrukcie\n def sort_order(self, instruction):\n return instruction.order\n\n ### Parsovanie argumentov inštrukcie z XML\n def parse_instruction_arguments(self, instruction, arguments):\n for argument in arguments:\n if argument.tag == 'arg1':\n if instruction.arg1type is not None or argument.get('type') is None:\n err_xml_structure(\"Error: arg1 error\")\n instruction.arg1type = argument.get('type')\n instruction.arg1value = parse_argument_value(instruction.arg1type, argument.text)\n elif argument.tag == 'arg2':\n if instruction.arg2type is not None or argument.get('type') is None:\n err_xml_structure(\"Error: arg2 error\")\n instruction.arg2type = argument.get('type')\n instruction.arg2value = parse_argument_value(instruction.arg2type, argument.text)\n elif argument.tag == 'arg3':\n if instruction.arg3type is not None or argument.get('type') is None:\n err_xml_structure(\"Error: arg3 error\")\n instruction.arg3type = argument.get('type')\n instruction.arg3value = parse_argument_value(instruction.arg3type, argument.text)\n else:\n err_xml_structure(\"Error: invalid xml instruction argument - arg4+\")\n\n ### Syntaktická a lexikálná analýza inštrukcie\n def identify_instruction(self, instruction):\n if instruction.opcode == 'MOVE' or instruction.opcode == 'INT2CHAR' or instruction.opcode == 'STRLEN' or instruction.opcode == 'TYPE' or instruction.opcode == 'NOT':\n checkvar(instruction.arg1type, instruction.arg1value)\n checksymb(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'CREATEFRAME' or instruction.opcode == 'PUSHFRAME' or instruction.opcode == 'POPFRAME' or instruction.opcode == 'RETURN' or instruction.opcode == 'BREAK':\n checkempty(instruction.arg1type, instruction.arg1value)\n checkempty(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'DEFVAR' or instruction.opcode == 'POPS':\n checkvar(instruction.arg1type, instruction.arg1value)\n checkempty(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'PUSHS' or instruction.opcode == 'WRITE' or instruction.opcode == 'EXIT' or instruction.opcode == 'DPRINT':\n checksymb(instruction.arg1type, instruction.arg1value)\n checkempty(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'CALL' or instruction.opcode == 'LABEL' or instruction.opcode == 'JUMP':\n checklabel(instruction.arg1type, instruction.arg1value)\n checkempty(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'READ':\n checkvar(instruction.arg1type, instruction.arg1value)\n checktype(instruction.arg2type, instruction.arg2value)\n checkempty(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'ADD' or instruction.opcode == 'SUB' or instruction.opcode == 'MUL' or instruction.opcode == 'IDIV' or instruction.opcode == 'AND' or instruction.opcode == 'OR' or instruction.opcode == 'LT' or instruction.opcode == 'GT' or instruction.opcode == 'EQ' or instruction.opcode == 'STRI2INT' or instruction.opcode == 'CONCAT' or instruction.opcode == 'GETCHAR' or instruction.opcode == 'SETCHAR':\n checkvar(instruction.arg1type, instruction.arg1value)\n checksymb(instruction.arg2type, instruction.arg2value)\n checksymb(instruction.arg3type, instruction.arg3value)\n elif instruction.opcode == 'JUMPIFEQ' or instruction.opcode == 'JUMPIFNEQ':\n checklabel(instruction.arg1type, instruction.arg1value)\n checksymb(instruction.arg2type, instruction.arg2value)\n checksymb(instruction.arg3type, instruction.arg3value)\n\n ### Sémantická kontrola symbolu\n def check_same_symb(self, symb1value, symb2value):\n if symb1value is None and symb2value is not None:\n err_bad_operand()\n if symb1value is not None and symb2value is None:\n err_bad_operand()\n if type(symb1value) is not type(symb2value):\n err_bad_operand()\n\n ### Sémantická kontrola integeru\n def check_same_int(self, symb1value, symb2value):\n if symb1value is None:\n err_bad_operand()\n if symb2value is None:\n err_bad_operand()\n if type(symb1value) is not type(symb2value):\n err_bad_operand()\n if type(symb1value) is not int or type(symb2value) is not int:\n err_bad_operand()\n\n ### Sémantická kontrola reťazca\n def check_same_str(self, symb1value, symb2value):\n if symb1value is None:\n err_bad_operand()\n if symb2value is None:\n err_bad_operand()\n if type(symb1value) is not type(symb2value):\n err_bad_operand()\n if type(symb1value) is not str or type(symb2value) is not str:\n err_bad_operand()\n\n ### Sémantická kontrola boolu\n def check_same_bool(self, symb1value, symb2value):\n if symb1value is None:\n err_bad_operand()\n if symb2value is None:\n err_bad_operand()\n if type(symb1value) is not type(symb2value):\n err_bad_operand()\n if type(symb1value) is not bool or type(symb2value) is not bool:\n err_bad_operand()\n\n ### Identifikácia typu symbolu a získanie hodnoty\n def get_symb_value(self, symbtype, symbvalue):\n if symbtype == 'var':\n localvar = symbvalue[3:]\n tempvar = None\n if symbvalue[0] == 'L':\n if self.localframe is None:\n err_frame_existance()\n else:\n tempvar = self.localframe.get_var_value(localvar)\n elif symbvalue[0] == 'G':\n if self.globalframe is None:\n err_frame_existance()\n else:\n tempvar = self.globalframe.get_var_value(localvar)\n elif symbvalue[0] == 'T':\n if self.tempframe is None:\n err_frame_existance()\n else:\n tempvar = self.tempframe.get_var_value(localvar)\n if tempvar.value is None and tempvar.type is None:\n err_missing_value()\n return tempvar.value\n elif symbtype == 'string':\n if symbvalue is None:\n return \"\"\n else:\n regex = re.compile(r\"\\\\(\\d{3})\")\n return regex.sub(replaceEscapeSequence, symbvalue)\n elif symbtype == 'bool':\n if symbvalue == 'true':\n return True\n else:\n return False\n elif symbtype == 'int':\n return int(symbvalue)\n elif symbtype == 'nil':\n return None\n\n ### Nastavenie hodnoty premennej\n def set_var(self, varname, symbvalue):\n symbtype = type(symbvalue)\n localvar = varname[3:]\n if varname[0] == 'L':\n if self.localframe is None:\n err_frame_existance()\n else:\n self.localframe.set_var_value(name=localvar, type=symbtype, value=symbvalue)\n elif varname[0] == 'G':\n if self.globalframe is None:\n err_frame_existance()\n else:\n self.globalframe.set_var_value(name=localvar, type=symbtype, value=symbvalue)\n elif varname[0] == 'T':\n if self.tempframe is None:\n err_frame_existance()\n else:\n self.tempframe.set_var_value(name=localvar, type=symbtype, value=symbvalue)\n\n ### Interpretácia labelu\n def interpret_labels(self):\n for instruction in self.instructions:\n if instruction.opcode == 'LABEL':\n if instruction.arg1value in self.labels:\n err_semantic()\n self.labels.setdefault(instruction.arg1value)\n self.labels[instruction.arg1value] = self.pc_counter\n self.pc_counter += 1\n\n ### Interpretácia inštrukcie - Sémantická analýza inštrukcie (detaily k nahliadnutiu v dokumentácii: ipp19spec.pdf str:11-14)\n def interpret_instruction(self, instruction):\n if instruction.opcode == 'MOVE':\n symbvalue = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n self.set_var(instruction.arg1value, symbvalue)\n elif instruction.opcode == 'CREATEFRAME':\n self.tempframe = Frame()\n self.tempframe.arrayOfVariables = []\n elif instruction.opcode == 'PUSHFRAME':\n if self.tempframe is None:\n err_frame_existance()\n if self.localframe is not None:\n self.frameStack.append(self.localframe)\n self.localframe = self.tempframe\n self.tempframe = None\n elif instruction.opcode == 'POPFRAME':\n if self.localframe is None:\n err_frame_existance()\n else:\n self.tempframe = self.localframe\n self.localframe = None\n if len(self.frameStack) > 0:\n self.localframe = self.frameStack.pop()\n elif instruction.opcode == 'DEFVAR':\n localvar = instruction.arg1value[3:]\n if instruction.arg1value[0] == 'L':\n if self.localframe is None:\n err_frame_existance()\n else:\n self.localframe.def_var(name=localvar)\n elif instruction.arg1value[0] == 'G':\n if self.globalframe is None:\n err_frame_existance()\n else:\n self.globalframe.def_var(name=localvar)\n elif instruction.arg1value[0] == 'T':\n if self.tempframe is None:\n err_frame_existance()\n else:\n self.tempframe.def_var(name=localvar)\n elif instruction.opcode == 'DPRINT':\n symbvalue = self.get_symb_value(instruction.arg1type, instruction.arg1value)\n print(symbvalue, file=sys.stderr)\n elif instruction.opcode == 'WRITE':\n symbvalue = self.get_symb_value(instruction.arg1type, instruction.arg1value)\n if symbvalue is None:\n print('', end='')\n elif type(symbvalue) is not bool:\n print(symbvalue, end='')\n else:\n if symbvalue == True:\n print('true', end='')\n else:\n print('false', end='')\n elif instruction.opcode == 'TYPE':\n if instruction.arg1type != 'var':\n val = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n else:\n localvar = instruction.arg2value[3:]\n if instruction.arg2value[0] == 'L':\n if self.localframe is None:\n err_frame_existance()\n else:\n val = self.localframe.get_var_value(localvar)\n elif instruction.arg2value[0] == 'G':\n if self.globalframe is None:\n err_frame_existance()\n else:\n val = self.globalframe.get_var_value(localvar)\n elif instruction.arg2value[0] == 'T':\n if self.tempframe is None:\n err_frame_existance()\n else:\n val = self.tempframe.get_var_value(localvar)\n if val.value is None and val.type is None:\n self.set_var(instruction.arg1value, \"\")\n return\n else:\n val = val.value\n symbvalue = type(val)\n if val is None:\n symbvalue = \"nil\"\n elif symbvalue is str:\n symbvalue = \"string\"\n elif symbvalue is int:\n symbvalue = \"int\"\n elif symbvalue is bool:\n symbvalue = \"bool\"\n self.set_var(instruction.arg1value, symbvalue)\n elif instruction.opcode == 'PUSHS':\n symbvalue = self.get_symb_value(instruction.arg1type, instruction.arg1value)\n self.stack.append(symbvalue)\n elif instruction.opcode == 'POPS':\n if len(self.stack) == 0:\n err_missing_value()\n symbvalue = self.stack.pop()\n self.set_var(instruction.arg1value, symbvalue)\n elif instruction.opcode == 'ADD':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_int(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value + symb2value)\n elif instruction.opcode == 'SUB':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_int(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value - symb2value)\n elif instruction.opcode == 'MUL':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_int(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value * symb2value)\n elif instruction.opcode == 'IDIV':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_int(symb1value, symb2value)\n if symb2value == 0:\n err_operand_value()\n self.set_var(instruction.arg1value, symb1value // symb2value)\n elif instruction.opcode == 'LT':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_symb(symb1value, symb2value)\n if symb1value is None or symb2value is None:\n err_bad_operand()\n self.set_var(instruction.arg1value, symb1value < symb2value)\n elif instruction.opcode == 'GT':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_symb(symb1value, symb2value)\n if symb1value is None or symb2value is None:\n err_bad_operand()\n self.set_var(instruction.arg1value, symb1value > symb2value)\n elif instruction.opcode == 'EQ':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n if symb1value is None and symb2value is not None:\n self.set_var(instruction.arg1value, False)\n return\n elif symb1value is not None and symb2value is None:\n self.set_var(instruction.arg1value, False)\n return\n self.check_same_symb(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value == symb2value)\n elif instruction.opcode == 'AND':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_bool(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value and symb2value)\n elif instruction.opcode == 'OR':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_bool(symb1value, symb2value)\n self.set_var(instruction.arg1value, symb1value or symb2value)\n elif instruction.opcode == 'NOT':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n self.check_same_bool(symb1value, True)\n self.set_var(instruction.arg1value, not symb1value)\n elif instruction.opcode == 'INT2CHAR':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n self.check_same_int(symb1value, 0)\n if symb1value < 0 or symb1value > 1114111:\n err_string()\n self.set_var(instruction.arg1value, chr(symb1value))\n elif instruction.opcode == 'STRI2INT':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_str(symb1value, \"\")\n self.check_same_int(symb2value, 0)\n if symb2value < 0 or symb2value >= len(symb1value):\n err_string()\n self.set_var(instruction.arg1value, ord(symb1value[symb2value]))\n elif instruction.opcode == 'READ':\n symb1value = self.inputFile.readline()\n if not symb1value:\n symb1value = ''\n if len(symb1value) > 0 and symb1value[len(symb1value) - 1] == '\\n':\n symb1value = symb1value[:-1]\n if instruction.arg2value == \"bool\":\n if symb1value.upper() == \"TRUE\":\n symb1value = True\n else:\n symb1value = False\n elif instruction.arg2value == \"int\":\n try:\n symb1value = int(symb1value)\n except:\n symb1value = 0\n self.set_var(instruction.arg1value, symb1value)\n elif instruction.opcode == 'CONCAT':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_str(symb1value, \"\")\n self.check_same_str(symb2value, \"\")\n self.set_var(instruction.arg1value, symb1value + symb2value)\n elif instruction.opcode == 'GETCHAR':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_str(symb1value, \"\")\n self.check_same_int(symb2value, 0)\n if symb2value < 0 or symb2value >= len(symb1value):\n err_string()\n self.set_var(instruction.arg1value, symb1value[symb2value])\n elif instruction.opcode == 'SETCHAR':\n varvalue = self.get_symb_value(instruction.arg1type, instruction.arg1value)\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_str(varvalue, \"\")\n self.check_same_int(symb1value, 0)\n self.check_same_str(symb2value, \"\")\n if symb1value < 0 or symb1value >= len(varvalue) or len(symb2value) == 0:\n err_string()\n if symb1value > 0:\n varvalue = varvalue[:symb1value] + symb2value[0] + varvalue[1 + symb1value:]\n else:\n varvalue = symb2value[0] + varvalue[1 + symb1value:]\n self.set_var(instruction.arg1value, varvalue)\n elif instruction.opcode == 'STRLEN':\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n self.check_same_str(symb1value, \"\")\n self.set_var(instruction.arg1value, len(symb1value))\n elif instruction.opcode == 'EXIT':\n symb1value = self.get_symb_value(instruction.arg1type, instruction.arg1value)\n self.check_same_int(symb1value, 0)\n if symb1value < 0 or symb1value > 49:\n err_operand_value()\n exit(symb1value)\n elif instruction.opcode == 'BREAK':\n print('PC counter: ' + str(self.pc_counter), file=sys.stderr)\n elif instruction.opcode == 'LABEL':\n return\n elif instruction.opcode == 'CALL':\n if instruction.arg1value not in self.labels:\n err_semantic()\n self.pc_stack.append(self.pc_counter)\n self.pc_counter = self.labels[instruction.arg1value]\n elif instruction.opcode == 'RETURN':\n if len(self.pc_stack) == 0:\n err_missing_value()\n self.pc_counter = self.pc_stack.pop()\n elif instruction.opcode == 'JUMP':\n if instruction.arg1value not in self.labels:\n err_semantic()\n self.pc_counter = self.labels[instruction.arg1value]\n elif instruction.opcode == 'JUMPIFEQ':\n if instruction.arg1value not in self.labels:\n err_semantic()\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_symb(symb1value, symb2value)\n if symb1value == symb2value:\n self.pc_counter = self.labels[instruction.arg1value]\n elif instruction.opcode == 'JUMPIFNEQ':\n if instruction.arg1value not in self.labels:\n err_semantic()\n symb1value = self.get_symb_value(instruction.arg2type, instruction.arg2value)\n symb2value = self.get_symb_value(instruction.arg3type, instruction.arg3value)\n self.check_same_symb(symb1value, symb2value)\n if symb1value != symb2value:\n self.pc_counter = self.labels[instruction.arg1value]\n\n\nInterpret()\n"
},
{
"alpha_fraction": 0.7681465148925781,
"alphanum_fraction": 0.7809953093528748,
"avg_line_length": 53.87894821166992,
"blob_id": "22b431206ee9768676c19667516405e588a0ebd3",
"content_id": "b1cc6cf767bc424ea5be8ad0688cfa17eb4e5a7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 11432,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 190,
"path": "/readme.md",
"repo_name": "xvanick1/fit-vut-ipp2019",
"src_encoding": "UTF-8",
"text": "# Hodnotenie\n\n## 1. časť\n##### Zisk bodov: 7/7b\n\n### Komentár učiteľa k hodnoteniu prvej časti\nJelikož jste odevzdal 1. úlohu projektu do IPP 2018/2019,\nzasíláme Vám automaticky generované detaily vyhodnocení včetně individuálních připomínek cvičících.\n\nLogin hodnoceného studenta: xvanic09\n\nNásledující procentuální hodnocení je FINÁLNÍ hodnocení Vaší úlohy č. 1.\n\nProjekt byl nejdříve rozbalen a následně spuštěn s řadou hodnotících testů.\nTesty jsou rozděleny do několika kategorií. Podle výsledků\njednotlivých testů byla stanovena procentuální úspěšnost Vašeho skriptu\nv jednotlivých kategoriích a z těchto hodnot odvozeny body. \nDo WIS se importují body zaokrouhlené na jedno desetinné místo.\nTestovací příklady nebudou uveřejněny. \n\nHodnocení je individuálně vygenerováno pro každého studenta, doplněno o ručně vložené připomínky a následně \nautomaticky rozesláno na školní email.\n\nHodnocené části (nehodnocené části jsou vynechány):\n1)Automatické testy parse.php - základní.\n2)Automatické testy parse.php - registrovaná rozšíření.\n3)Automatické testy test.php, pokud byl součástí archivu: včetně ručního zhodnocení kvalit vytvořených HTML reportů.\n4)Případné malusy a bonusy (pozdní odevzdání, příspěvky na fóru, ...).\n5)Hodnocení dokumentace readme1(.pdf/.md) a štábní kultury zdrojových kódů (především komentářů).\n\n Následuje seznam zkratek, které se mohou vyskytnout v komentářích k hodnocení test.php:\n OK = výstupy byly v pořádku\n NO = žádné smysluplné výsledky\n NODIFF = špatné porovnání výstupů\n NOSTOP = nezastavení po chybě v parse.php a následný pokus interpretace nevalidního XML\n NOUTF = chybí podpora Unicode znaků (např. v názvech adresářů a souborů)\n NODETAILS = schází informace o (jednotlivých) testech či jejich počtech\n PARSEONLY = funguje jen --parse-only (výsledky pro ostatní testy jsou většinou špatně)\n WRONG = neodpovídající výsledky testů\n ERRORS = jiné chyby zpracování (např. nenalezení/nezobrazení všech testů)\n\n Následuje seznam zkratek, které se mohou vyskytnout v komentářích k hodnocení dokumentace a štábní kultury skriptů:\nVysvětlivky zkratek v dokumentaci:\n CH = pravopisné chyby, překlepy\n FORMAT = špatný formát vzhledu dokumentu (nedodrženy požadavky)\n SHORT = nesplňuje minimální požadavky na délku či obsah\n STRUCT = nevhodně strukturováno (např. bez nadpisů)\n MISSING = dokumentace nebyla odevzdána\n STYLE = stylizace vět, nečitelnost, nesrozumitelnost\n COMMENT = chybějící nebo nedostatečné komentáře ve zdrojovém textu\n FILO = nedostatečná filosofie návrhu (abstraktní popis struktury programu, co následuje za čím)\n JAK = technicky nedostatečný popis řešení\n SRCFORMAT = opravdu velmi špatná štábní kultura zdrojového kódu\n SPACETAB (jen pro informaci) = kombinování mezer a tabelátorů k odsazování zdrojového textu\n LANG = míchání jazyků (většinou anglické termíny v českém textu)\n HOV = hovorové nebo nevhodné slangové výrazy\n FORM = nepěkná úprava, nekonzistentní velikost a typ písma apod.\n TERM = problematická terminologie (neobvyklá, nepřesná či přímo špatná)\n IR = nedostatečně popsaná vnitřní reprezentace (např. pro paměť, sekvenci instrukcí apod.)\n PRED (jen pro informaci) = pozor na osamocené neslabičné předložky na konci řádků\n BLOK (jen pro informaci) = chybí zarovnaní do bloku místo méně pěkného zarovnání na prapor (doleva)\n KAPTXT (jen pro informaci) = mezi nadpisem a jeho podnadpisem by měl být vždy nějaký text\n MEZ (jen pro informaci) = za otevírající nebo před zavírající závorku mezera nepatří\n ICH (jen pro informaci) = ich-forma (psaní v první osobě jednotného čísla) není většinou vhodná pro programovou dokumentaci\n SAZBA (jen pro informaci) = alespoň identifikátory proměnných a funkcí se patří sázet písmem s jednotnou šířkou písmen (např. font Courier)\n OK = k dokumentaci byly maximálně minoritní připomínky\n\n\nV případě nějakých problémů s hodnocením je přiložen\nlog dekomprimace odevzdáného archivu.\n\nTermíny reklamací budou vypsány ve WIS.\n\n###### Vaše hodnocení části 1): 6,00 bodů\n###### Vaše hodnocení části 2): 0,00 bodů\n###### Vaše hodnocení části 5): 1,00 bodů\n- Komentář hodnocení části 5) (sražka uváděny v minibodech, 1 bod = 100 minibodů): OK\n\nPokud jste obdrželi výsledek částí 1) mimo hodnotící interval, tak\nbude oříznut, tak že získáte za implementaci alespoň 0 a ne více jak maximum bodů za daný skript.\n\n##### Procentuální hodnocení jednotlivých kategorií skriptu parse.php: \n###### Lexikální analýza: 94%\n###### Syntaktická analýza: 100%\n###### Zpracování instrukcí: 100%\n###### Zpracování programů: 100%\n###### Rozšíření STATP 0%\n###### Celkem bez rozšíření: 99%\n\n \n## 2. časť\n##### Zisk bodov: 12,9/13b\n\n### Komentár učiteľa k hodnoteniu 2. časti\njelikož jste odevzdal 2. úlohu projektu do IPP 2018/2019,\nzasíláme Vám automaticky generované detaily vyhodnocení včetně individuálních připomínek cvičících.\n\nLogin hodnoceného studenta: xvanic09\n\nNásledující procentuální hodnocení je FINÁLNÍ hodnocení Vaší úlohy č. 2.\n\nProjekt byl nejdříve rozbalen a následně spuštěn s řadou hodnotících testů.\nTesty jsou rozděleny do několika kategorií. Podle výsledků\njednotlivých testů byla stanovena procentuální úspěšnost Vašeho skriptu\nv jednotlivých kategoriích a z těchto hodnot odvozeny body. \nDo WIS se importují body zaokrouhlené na jedno desetinné místo.\nTestovací příklady nebudou uveřejněny. \n\nHodnocení je individuálně vygenerováno pro každého studenta, doplněno o ručně vložené připomínky a následně \nautomaticky rozesláno na školní email.\n\nHodnocené části (nehodnocené části jsou vynechány):\n1)Automatické testy interpret.py - základní.\n2)Automatické testy interpret.py - registrovaná rozšíření.\n3)Automatické testy test.php (základní a registrovaná rozšíření) včetně ručního zhodnocení kvalit vytvořených HTML reportů.\n4)Případné malusy a bonusy (pozdní odevzdání, příspěvky na fóru, ...).\n5)Hodnocení dokumentace readme2(.pdf/.md) a štábní kultury zdrojových kódů (především komentářů).\n\n Následuje seznam zkratek, které se mohou vyskytnout v komentářích k hodnocení test.php:\n OK = výstupy byly v pořádku\n EMPTY = prázdný nebo téměř prázdný HTML soubor\n INTONLY = fungují vesměs pouze testy s parametrem --int-only (ostatní vesměs nefungují)\n JExamXML = podezření, že výstup při --parse-only nebyl porovnáván pomocí nástroje JExamXML (či se špatným nastavením), ale pouze nástrojem diff\n NO = žádné smysluplné výsledky\n NOINT = nefunguje testování interpretu\n NODIFF = špatné porovnání výstupů\n NODIR/DIRS = v rekurzivním výpisu testů (--recursive) není poznat, který test je z jaké složky\n NOPRE = nefunguje dogenerování souborů s implicitním obsahem\n NOSTOP = nezastavení po chybě v parse.php a následný pokus interpretace nevalidního XML\n NOUTF = chybí podpora Unicode znaků (např. v názvech adresářů a souborů), nebo nefunguje vyhodnocování testů s Unicode znaky v názvech testů/adresářů\n NODETAILS = schází informace o (jednotlivých) testech či jejich počtech\n PARSEONLY = funguje jen vesměs --parse-only (výsledky pro ostatní testy jsou většinou špatně)\n STATS = chybí nejdůležitější statistiky jako například počet provedených testů a počet úspěšných nebo neúspěšných testů\n WARNINGS = varování PHP/Python vložené přímo do výstupního HTML (často nepřehledně)\n WRONG = neodpovídající výsledky testů\n ERRORS = jiné chyby zpracování (např. nenalezení/nezobrazení všech testů nebo nalezení i těch, které se nalézt neměly)\n\n Následuje seznam zkratek, které se mohou vyskytnout v komentářích k hodnocení dokumentace a štábní kultury skriptů:\nVysvětlivky zkratek v dokumentaci:\n CH = pravopisné chyby, překlepy\n FORMAT = špatný formát vzhledu dokumentu (nedodrženy požadavky)\n SHORT = nesplňuje minimální požadavky na délku či obsah\n STRUCT = nevhodně strukturováno (např. bez nadpisů)\n MISSING = dokumentace nebyla odevzdána\n STYLE = stylizace vět, nečitelnost, nesrozumitelnost\n COMMENT = chybějící nebo nedostatečné komentáře ve zdrojovém textu\n FILO = nedostatečná filosofie návrhu (abstraktní popis struktury programu, co následuje za čím)\n JAK = technicky nedostatečný popis řešení\n SRCFORMAT = opravdu velmi špatná štábní kultura zdrojového kódu\n SPACETAB (jen pro informaci) = kombinování mezer a tabelátorů k odsazování zdrojového textu\n LANG = míchání jazyků (většinou anglické termíny v českém textu)\n HOV = hovorové nebo nevhodné slangové výrazy\n FORM = nepěkná úprava, nekonzistentní velikost a typ písma apod.\n TERM = problematická terminologie (neobvyklá, nepřesná či přímo špatná)\n IR = nedostatečně popsaná vnitřní reprezentace (např. pro paměť, sekvenci instrukcí apod.)\n PRED (jen pro informaci) = pozor na osamocené neslabičné předložky na konci řádků\n BLOK (jen pro informaci) = chybí zarovnaní do bloku místo méně pěkného zarovnání na prapor (doleva)\n KAPTXT (jen pro informaci) = mezi nadpisem a jeho podnadpisem by měl být vždy nějaký text\n MEZ (jen pro informaci) = za otevírající nebo před zavírající závorku mezera nepatří\n ICH (jen pro informaci) = ich-forma (psaní v první osobě jednotného čísla) není většinou vhodná pro programovou dokumentaci\n SAZBA (jen pro informaci) = alespoň identifikátory proměnných a funkcí se patří sázet písmem s jednotnou šířkou písmen (např. font Courier)\n OK = k dokumentaci byly maximálně minoritní připomínky\n\n\nTermíny reklamací budou vypsány ve WIS (viz termín 'Reklamace hodnocení 2. úlohy').\n\n\n###### Vaše hodnocení části 1): 8,19 bodů\n###### Vaše hodnocení části 2): 0,00 bodů\n###### Vaše hodnocení části 3): 2,95 bodů\n- Komentář hodnocení části 3): STATS (matoucí počet neúšpěšných testů), OK\n###### Body za rozšíření k části 3): 0,00 bodů\n###### Vaše hodnocení části 5): 1,80 bodů\n- Komentář hodnocení části 5) (sražka uváděny v minibodech, 1 bod = 100 minibodů): CH (-10), CONTENT (-10) – popis návratových kódů\n\nPokud jste obdrželi výsledek částí 1) mimo hodnotící interval, tak\nbude oříznut, tak že získáte za implementaci alespoň 0 a ne více jak maximum bodů za daný skript.\n\n###### Dekomprimace archivu proběhla úspěšně.\n###### Procentuální hodnocení jednotlivých kategorií skriptu interpret.py: \n###### Lexikální analýza: 100%\n###### Syntaktická analýza: 100%\n###### Sémantická analýza (detekce chyb): 100%\n###### Běhové chyby (detekce): 100%\n###### Interpretace instrukcí: 98%\n###### Interpretace programů: 100%\n###### Rozšíření FLOAT 0%\n###### Rozšíření STACK 0%\n###### Rozšíření STATI 0%\n###### Celkem bez rozšíření: 99%\n\n\n"
},
{
"alpha_fraction": 0.5475929975509644,
"alphanum_fraction": 0.5683807730674744,
"avg_line_length": 19.539325714111328,
"blob_id": "f234af06f79e98c4215ee574d8c1403809474639",
"content_id": "7c5adafb6c08a6d1d8f02347ef583ccd4ba31800",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1828,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 89,
"path": "/test.sh",
"repo_name": "xvanick1/fit-vut-ipp2019",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nshopt -s expand_aliases\nsource ~/.bash_profile\n\nTESTS_DIR=\".\"\n\nif [ \"$1\" = \"\" ] ; then\n path=\"./\"\nelse\n path=$1\nfi\n\n# Output settings\nTEXT_BOLD=`tput bold`\nTEXT_RED=`tput setaf 1`\nTEXT_GREEN=`tput setaf 2`\nTEXT_BROWN=`tput setaf 3`\nTEXT_BLUE=`tput setaf 4`\nTEXT_RESET=`tput sgr0`\n\nproj=\"parse.php\"\n\nclear\necho \"Running tests for parse.php\"\necho \"-------------------------\"\n\nfunction green() {\n printf %s \"${TEXT_GREEN}$1${TEXT_RESET}\"\n}\n\nfunction red() {\n printf %s \"${TEXT_RED}$1${TEXT_RESET}\"\n}\n\ncount=0\ntestuj() {\n export count=$((count+1))\n echo \"#$count:\"\n echo \"php7.3 $proj < $TESTS_DIR/$1.src > $TESTS_DIR/$1.parse.out\"\n php7.3 $proj < $TESTS_DIR/$1.src 2>&1 > $TESTS_DIR/$1.parse.out\n result=$?\n if [ ${result} = `cat $TESTS_DIR/$1.rc` ] ; then\n echo \" CODE: `green OK`\"\n else \n printf \" EXPECTED CODE: \"\n green `cat $TESTS_DIR/$1.rc`\n echo \"\"\n printf \" RETURNED CODE: \"\n red \"${result}\"\n echo \"\"\n fi\n\n if [ ${result} = 0 ]; then\n java -jar jexamxml.jar $TESTS_DIR/$1.parse.out $TESTS_DIR/$1.out $TESTS_DIR/$1.delta.xml ./options > /dev/null 2>/dev/null\n #diff -c tests/$1.parse.out tests/$1.out > /dev/null 2>/dev/null\n result=$?\n if [ ${result} = 0 ] ; then\n echo \" DIFF: `green OK`\"\n else \n echo \" DIFF: `red ERROR`\"\n fi\n else \n diff -c $TESTS_DIR/$1.parse.out $TESTS_DIR/$1.out > /dev/null 2>/dev/null\n result=$?\n if [ ${result} = 0 ] ; then\n echo \" DIFF: `green OK`\"\n else \n echo \" DIFF: `red ERROR`\"\n fi\n fi\n echo \"-------------------------\"\n}\n\n# testuj \"basic/EmptyProgram\"\n\nFILES=./parse-only/*/*.rc\nFILES2=./parse-only/*/*/*.rc\nfor f in $FILES; do\n testuj ${f%.*}\ndone\n\nfor f in $FILES2; do\n testuj ${f%.*}\ndone\n\nrm -rf $TESTS_DIR/*.parse.out\nrm -rf $TESTS_DIR/*.delta.xml\nrm -rf $TESTS_DIR/*.parse.out.log\n"
},
{
"alpha_fraction": 0.44487592577934265,
"alphanum_fraction": 0.45789414644241333,
"avg_line_length": 42.1244010925293,
"blob_id": "719237e99f0da9c096587a4e45fa554699c1fad3",
"content_id": "bfbc5fec9b5b7e1b2b2975dfcc46c01616e1e3f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 27191,
"license_type": "no_license",
"max_line_length": 270,
"num_lines": 627,
"path": "/parse.php",
"repo_name": "xvanick1/fit-vut-ipp2019",
"src_encoding": "UTF-8",
"text": "<?php\n/**\n * Created by PhpStorm.\n * Author: Jozef Vanický\n * VUT Login: xvanic09\n * Date: 2019-02-18\n * Author's comment: Tento skript je upravenou kópiou kódu, ktorý som napísal pred rokom k projektu z predmetu IPP 2017/2018 k jazyku IPPcode18.\n **/\n\n/*Regulárne výrazy použité pri spracovaní argumentov jednotlivých funkcií*/\n//symb = var, int, bool, string, nil\n//type = int, bool, string\n$var = \"/^(?:GF|LF|TF)@[\\p{L}|\\-\\_\\*\\!\\?\\$%&][\\w\\-\\*\\_\\!\\?\\$%&]*$/u\";\n$int = \"/^int@[+-]?\\d+$/\";\n$bool = \"/^bool@(?:true|false)$/\";\n$string = '/^string@([^\\\\\\\\]*(\\\\\\\\\\p{N}{3}(?!\\p{N}))*)*$/u';\n$label = \"/^[\\p{L}|\\-\\_\\*\\$%&!?][\\w\\-\\_\\*\\$%&!?]*$/\";\n$nil = \"/^nil@nil$/\";\n\n/*Kontrola vstupných argumentov*/\nif ($argc > 2) {\n fwrite(STDERR, \"Error: Too many arguments!\\n\");\n exit(10);\n} elseif ($argc == 2) {\n if ($argv[1] == \"--help\") {\n echo \"--help\\n\";\n echo \"Skript typu filtr (parse.php v jazyce PHP 7.3) nacte ze standardniho vstupu zdrojovy kod v IPPcode19 (viz sekce 6), zkontroluje lexikalni a syntaktickou spravnost kodu a vypise na standardni vystup XML reprezentaci programu dle specifikace v sekci 3.1.\\n\";\n exit(0);\n } else {\n fwrite(STDERR, \"Error: Wrong input!\\n\");\n exit(10);\n }\n}\n\n/*Načítanie vstupného súboru*/\n$InputControl = @fopen('php://stdin', \"r\"); //Vráti false ak nastane chyba pri otváraní vstupného súboru, alebo ak súbor neexistuje\nif (!$InputControl) {\n fwrite(STDERR, \"Error: Reading input file failed!\\n\");\n exit(11);\n}\n\n$fileNotEmpty = false;\n$head = false;\n$instrCounter = 0;\n\n/*Spracovanie vstupného súboru riadok po riadku*/\nwhile ($line = fgets($InputControl)) {\n $fileNotEmpty = true;\n\n /*Detekcia komentárov a ich následné odstránenie*/\n $pos = strpos($line, '#');\n if ($line[0] == '#') {\n $line = \" \";\n }\n elseif (($line[0] != '#') && ($pos != false)) {\n $line = stristr($line, '#', true);\n }\n\n /*Odstránenie bielych znakov na začiatku a konci riadku*/\n $line = trim($line);\n\n /*Kontrola hlavičky*/\n if ($head == false) {\n if (preg_match('/^\\.IPPCODE19\\s*$/i', $line)) {\n $head = true;\n\n /*Generovanie XML hlavičky*/\n $dom = new DomDocument(\"1.0\", \"UTF-8\");\n $progElem = $dom->createElement('program');\n $progElem->SetAttribute('language', 'IPPcode19');\n\n continue;\n } else {\n fwrite(STDERR, \"Error: Head is incorrect or missing!\\n\");\n exit(21);\n }\n }\n\n /*Rozdelenie riadku do poľa na základe bielych znakov medzi parametrami*/\n if (!preg_match(\"/^\\s*$/\", $line)) {\n $SavedArray = array_filter(preg_split(\"/\\s+/\", $line));\n\n $Temp = $SavedArray[0]; //Pomocná premenná k výpisu chyby\n\n /*Identifikácia inštrukcie jazyka IPPcode19*/\n $SavedArray[0] = strtoupper($SavedArray[0]);\n switch ($SavedArray[0]) {\n case 'MOVE':\n case 'INT2CHAR':\n case 'STRLEN':\n case 'TYPE':\n case 'NOT':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Variable is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($var, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $arg1Elem->SetAttribute('type', 'var');\n $instrElem->appendChild($arg1Elem);\n }\n\n /*---Druhý operand inštrukcie---*/\n\n if (!isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: Symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[2])) || (preg_match($int, $SavedArray[2])) || (preg_match($bool, $SavedArray[2])) || (preg_match($string, $SavedArray[2]) || (preg_match($nil, $SavedArray[2]))))) {\n fwrite(STDERR, \"Error: $SavedArray[2] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[2], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars(substr($SavedArray[2], $ArgLeng, strlen(htmlspecialchars($SavedArray[2])))));\n } else {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars($SavedArray[2]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg2Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg2Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg2Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg2Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg2Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg2Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[3])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n\n /*---Koniec inštrukcie---*/\n\n case 'CREATEFRAME':\n case 'PUSHFRAME':\n case 'POPFRAME':\n case 'RETURN':\n case 'BREAK':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'DEFVAR': //<var>\n case 'POPS':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Variable is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($var, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $arg1Elem->SetAttribute('type', 'var');\n $instrElem->appendChild($arg1Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'ADD':\n case 'SUB':\n case 'MUL':\n case 'IDIV':\n case 'LT':\n case 'GT':\n case 'EQ':\n case 'AND':\n case 'OR':\n case 'STRI2INT':\n case 'CONCAT':\n case 'GETCHAR':\n case 'SETCHAR':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Variable is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($var, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $arg1Elem->SetAttribute('type', 'var');\n $instrElem->appendChild($arg1Elem);\n }\n\n /*---Druhý operand inštrukcie---*/\n\n if (!isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: First symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[2])) || (preg_match($int, $SavedArray[2])) || (preg_match($bool, $SavedArray[2])) || (preg_match($string, $SavedArray[2]) || (preg_match($nil, $SavedArray[2]))))) {\n fwrite(STDERR, \"Error: $SavedArray[2] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[2], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars(substr($SavedArray[2], $ArgLeng, strlen(htmlspecialchars($SavedArray[2])))));\n } else {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars($SavedArray[2]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg2Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg2Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg2Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg2Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg2Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg2Elem);\n }\n\n /*---Tretí operand inštrukcie---*/\n\n if (!isset($SavedArray[3])) {\n fwrite(STDERR, \"Error: Second symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[3])) || (preg_match($int, $SavedArray[3])) || (preg_match($bool, $SavedArray[3])) || (preg_match($string, $SavedArray[3]) || (preg_match($nil, $SavedArray[3]))))) {\n fwrite(STDERR, \"Error: $SavedArray[3] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[3], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg3Elem = $dom->createElement('arg3', htmlspecialchars(substr($SavedArray[3], $ArgLeng, strlen(htmlspecialchars($SavedArray[3])))));\n } else {\n $Arg3Elem = $dom->createElement('arg3', htmlspecialchars($SavedArray[3]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg3Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg3Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg3Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg3Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg3Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg3Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[4])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'PUSHS':\n case 'WRITE':\n case 'EXIT':\n case 'DPRINT':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[1])) || (preg_match($int, $SavedArray[1])) || (preg_match($bool, $SavedArray[1])) || (preg_match($string, $SavedArray[1]) || (preg_match($nil, $SavedArray[1]))))) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[1], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg1Elem = $dom->createElement('arg1', htmlspecialchars(substr($SavedArray[1], $ArgLeng, strlen(htmlspecialchars($SavedArray[1])))));\n } else {\n $Arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg1Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg1Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg1Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg1Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg1Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg1Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'LABEL':\n case 'JUMP':\n case 'CALL':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Label is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($label, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $Arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $Arg1Elem->SetAttribute('type', 'label');\n $instrElem->appendChild($Arg1Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'JUMPIFEQ':\n case 'JUMPIFNEQ':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Label is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($label, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $Arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $Arg1Elem->SetAttribute('type', 'label');\n $instrElem->appendChild($Arg1Elem);\n //ak áno tak generujeme (pomocou SaveArray1) ďalej do xml arg1 do instruction\n }\n\n /*---Druhý operand inštrukcie---*/\n\n if (!isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: First symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[2])) || (preg_match($int, $SavedArray[2])) || (preg_match($bool, $SavedArray[2])) || (preg_match($string, $SavedArray[2]) || (preg_match($nil, $SavedArray[2]))))) {\n fwrite(STDERR, \"Error: $SavedArray[2] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[2], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars(substr($SavedArray[2], $ArgLeng, strlen(htmlspecialchars($SavedArray[2])))));\n } else {\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars($SavedArray[2]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg2Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg2Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg2Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg2Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg2Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg2Elem);\n }\n\n /*---Tretí operand inštrukcie---*/\n\n if (!isset($SavedArray[3])) {\n fwrite(STDERR, \"Error: Second symbol is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!((preg_match($var, $SavedArray[3])) || (preg_match($int, $SavedArray[3])) || (preg_match($bool, $SavedArray[3])) || (preg_match($string, $SavedArray[3]) || (preg_match($nil, $SavedArray[3]))))) {\n fwrite(STDERR, \"Error: $SavedArray[3] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n $ArgType = strstr($SavedArray[3], '@', true);\n $ArgLeng = strlen($ArgType) + 1;\n\n /*Generovanie XML operandu inštrukcie*/\n if (!($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF')) {\n $Arg3Elem = $dom->createElement('arg3', htmlspecialchars(substr($SavedArray[3], $ArgLeng, strlen(htmlspecialchars($SavedArray[3])))));\n } else {\n $Arg3Elem = $dom->createElement('arg3', htmlspecialchars($SavedArray[3]));\n }\n\n if ($ArgType == 'GF' || $ArgType == 'LF' || $ArgType == 'TF') {\n $Arg3Elem->SetAttribute('type', 'var');\n } elseif ($ArgType == 'int') {\n $Arg3Elem->SetAttribute('type', 'int');\n } elseif ($ArgType == 'bool') {\n $Arg3Elem->SetAttribute('type', 'bool');\n } elseif ($ArgType == 'string') {\n $Arg3Elem->SetAttribute('type', 'string');\n } elseif ($ArgType == 'nil') {\n $Arg3Elem->SetAttribute('type', 'nil');\n }\n $instrElem->appendChild($Arg3Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[4])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n case 'READ':\n $instrCounter += 1;\n\n /*Generovanie XML, inštrukcie*/\n $instrElem = $dom->createElement('instruction');\n $instrElem->setAttribute('order', $instrCounter);\n $instrElem->setAttribute('opcode', $SavedArray[0]);\n $progElem->appendChild($instrElem);\n\n /*---Prvý operand inštrukcie---*/\n\n if (!isset($SavedArray[1])) {\n fwrite(STDERR, \"Error: Variable is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!preg_match($var, $SavedArray[1])) {\n fwrite(STDERR, \"Error: $SavedArray[1] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n /*Generovanie XML operandu inštrukcie*/\n $arg1Elem = $dom->createElement('arg1', htmlspecialchars($SavedArray[1]));\n $arg1Elem->SetAttribute('type', 'var');\n $instrElem->appendChild($arg1Elem);\n }\n\n /*---Druhý operand inštrukcie---*/\n\n if (!isset($SavedArray[2])) {\n fwrite(STDERR, \"Error: Type is missing!\\n\");\n exit(23);\n }\n\n /*Identifikácia operandu*/\n if (!($SavedArray[2] == 'int' || $SavedArray[2] == 'bool' || $SavedArray[2] == 'string')) {\n fwrite(STDERR, \"Error: $SavedArray[2] is not a valid operand of instruction: $Temp !\\n\");\n exit(23);\n } else {\n\n /*Generovanie XML operandu inštrukcie*/\n $Arg2Elem = $dom->createElement('arg2', htmlspecialchars($SavedArray[2]));\n\n if ($SavedArray[2] == 'int') {\n $Arg2Elem->SetAttribute('type', 'type');\n } elseif ($SavedArray[2] == 'bool') {\n $Arg2Elem->SetAttribute('type', 'type');\n } elseif ($SavedArray[2] == 'string') {\n $Arg2Elem->SetAttribute('type', 'type');\n }\n $instrElem->appendChild($Arg2Elem);\n }\n\n /*---Dosiahnutý maximálny počet operandov inštrukcie---*/\n if (isset($SavedArray[3])) {\n fwrite(STDERR, \"Error: Instruction $Temp has too many arguments!\\n\");\n exit(23);\n }\n break;\n /*---Koniec inštrukcie---*/\n\n /*Zadaná neznáma inštrukcia*/\n default:\n fwrite(STDERR, \"Error: $Temp is not an instruction!\\n\");\n exit(22);\n break;\n }\n }\n}\n\n/*Uzatvorenie načítania súboru*/\nfclose($InputControl);\n\n/*Kontrola či je vstupný súbor prázdny*/\nif ($fileNotEmpty == false) {\n exit(21);\n}\n\n/*Generovanie konca XML*/\n$dom->appendChild($progElem);\n$dom->formatOutput = true;\n\n/*Výpis XML*/\n$xmlString = $dom->saveXML();\necho $xmlString;\nexit(0);\n"
},
{
"alpha_fraction": 0.5783158540725708,
"alphanum_fraction": 0.5872970223426819,
"avg_line_length": 44.93399429321289,
"blob_id": "d5b5889eb6f40244d16531380ddf29c1398dd0af",
"content_id": "28dc29fcdfcc6257134c33dffed11b38ca41df56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 14011,
"license_type": "no_license",
"max_line_length": 284,
"num_lines": 303,
"path": "/test.php",
"repo_name": "xvanick1/fit-vut-ipp2019",
"src_encoding": "UTF-8",
"text": "<?php\n/**\n * Created by PhpStorm.\n * Author: Jozef Vanický\n * VUT Login: xvanic09\n * Date: 2019-03-30\n * Author's comment: Tento skript je upravenou kópiou kódu, ktorý som napísal pred rokom k projektu z predmetu IPP 2017/2018 k jazyku IPPcode18.\n **/\n\n$arrayOfArguments = array(\"recursive\", \"directory::\", \"parse-script::\", \"int-script::\", \"parse-only\", \"int-only\"); //Pole povolených argumentov skriptu mimo argument help\n$dir = getcwd();\n$defaultParserFile = \"parse.php\";\n$defaultInterpretFile = \"interpret.py\";\n$src = array();\n$argument = getopt(NULL, $arrayOfArguments);\n$countOfParsedArguments = 1;\n\n/* Pomocné flagy */\n$rec_flag = false;\n$dir_flag = false;\n$parse_flag = false;\n$in_flag = false;\n$parse_only_flag = false;\n$int_only_flag = false;\n\n/* --- Vypíše nápovedu k skriptu v prípade zadaného argumentu help skriptu --- */\nfunction help()\n{\n $help = \"Script \\\"test.php\\\" written in PHP 7.3\" . PHP_EOL . PHP_EOL;\n $help .= \"Script is automatics testing tool for the apps \\\"parse.php\\\" and \\\"interpret.py\\\".\" . PHP_EOL;\n $help .= \"Script loads the files containing tests and runs them to check\" . PHP_EOL;\n $help .= \"the correctness of both programs. Generates the output written in HTML5 to stdout.\" . PHP_EOL . PHP_EOL;\n $help .= \"Possible arguments:\" . PHP_EOL;\n $help .= \"\\t--help\" . PHP_EOL;\n $help .= \"\\t--directory=path\" . PHP_EOL;\n $help .= \"\\t--recursive\" . PHP_EOL;\n $help .= \"\\t--parse-script=file\" . PHP_EOL;\n $help .= \"\\t--int-script=file\" . PHP_EOL;\n $help .= \"\\t--parse-only\" . PHP_EOL;\n $help .= \"\\t--int-only\" . PHP_EOL;\n\n echo $help . PHP_EOL;\n}\n\n/* --- Kontrola existencie priečinku alebo súboru --- */\nfunction existenceErr($existenceArgument)\n{\n fprintf(STDERR, \"Error: $existenceArgument doesn't exist or insufficient permissions to $existenceArgument\\n\");\n exit(11);\n}\n\n/* --- Kontrola cesty k priečinku alebo súboru --- */\nfunction pathErr($existenceArgument)\n{\n fprintf(STDERR, \"Error: $existenceArgument path wasn't entered correctly!\\n\");\n exit(10);\n}\n\n/* --- Vypíše html hlavičku --- */\nfunction generateHeader()\n{\n $header = \"<!DOCTYPE html>\" . PHP_EOL;\n $header .= \"<html lang=\\\"en\\\" xml:lang=\\\"en\\\">\" . PHP_EOL;\n $header .= \"<head>\" . PHP_EOL;\n $header .= \"<meta charset=\\\"UTF - 8\\\">\" . PHP_EOL;\n $header .= \"<title>IPPcode19 - Souhrn vysledku testovani</title>\" . PHP_EOL;\n $header .= \"<style>\" . PHP_EOL;\n $header .= \"body{padding-bottom: 60px;padding-left:60px;}h1{text-align: center;}h2{text-align: center;padding: 20px;}h3{text-align: center;padding-top: 20px;padding-bottom: 30px;}p{padding-left: 60px;}\" . PHP_EOL;\n $header .= \"</style>\" . PHP_EOL;\n $header .= \"</head>\" . PHP_EOL;\n $header .= \"<body>\" . PHP_EOL;\n $header .= \"<h1>Summary of the IPP2019 test result</h1>\" . PHP_EOL;\n $header .= \"<h2>Individual tests</h2>\" . PHP_EOL;\n\n echo $header . PHP_EOL;\n}\n\n/* --- Vypíše súhrn testov na štandardný výstup --- */\nfunction generateSummaryOfTests($testsCount, $failTestsCount, $succTestsCount, $procentual)\n{\n\n $testsSummary = \"<h2>Summary of tests</h2>\" . PHP_EOL;\n $testsSummary .= \"<p><b>Total number of tests: $testsCount </b></p>\" . PHP_EOL;\n $testsSummary .= \"<p><font color=\\\"red\\\"><b>Total number of unsuccessful tests: $failTestsCount </b></font></p>\" . PHP_EOL;\n $testsSummary .= \"<p><font color=\\\"green\\\"><b>Total number of successful tests: $succTestsCount </b></font></p>\" . PHP_EOL;\n $testsSummary .= \"<p><b>Percentage of success: $procentual %</b></p></body></html>\" . PHP_EOL;\n\n echo $testsSummary . PHP_EOL;\n}\n\n\n/* --- Kontrola vstupných argumentov --- */\n\nif ($argc > 5) { //Kontrola počtu vstupných argumentov\n fprintf(STDERR, \"Error: Too many arguments!\\n\");\n exit(10);\n} elseif ($argc == 2 && $argv[1] == \"--help\") { //Identifikácia argumentu --help na vstupe\n help();\n exit(0);\n} else {\n /* --- Identifikácia ďalších povolených argumentov na vstupe --- */\n if (array_key_exists(\"recursive\", $argument)) {\n $rec_flag = true;\n $countOfParsedArguments++;\n }\n if (array_key_exists(\"parse-only\", $argument)) {\n $parse_only_flag = true;\n $countOfParsedArguments++;\n }\n if (array_key_exists(\"int-only\", $argument)) {\n $int_only_flag = true;\n $countOfParsedArguments++;\n }\n if (array_key_exists(\"directory\", $argument)) {\n $dir_flag = true;\n $countOfParsedArguments++;\n $existenceArgument = \"Directory\";\n if ($argument[\"directory\"]) {\n $dir = $argument[\"directory\"];\n if (is_dir($dir) == false) {\n existenceErr($existenceArgument);\n }\n } else {\n pathErr($existenceArgument);\n }\n }\n if (array_key_exists(\"parse-script\", $argument)) {\n $parse_flag = true;\n $countOfParsedArguments++;\n $existenceArgument = \"File\";\n if ($argument[\"parse-script\"]) {\n $defaultParserFile = $argument[\"parse-script\"];\n if (!is_file($defaultParserFile)) {\n existenceErr($existenceArgument);\n }\n } else {\n pathErr($existenceArgument);\n }\n }\n if (array_key_exists(\"int-script\", $argument)) {\n $in_flag = true;\n $countOfParsedArguments++;\n $existenceArgument = \"File\";\n if ($argument[\"int-script\"]) {\n $defaultInterpretFile = $argument[\"int-script\"];\n if (!is_file($defaultInterpretFile)) {\n existenceErr($existenceArgument);\n }\n } else {\n pathErr($existenceArgument);\n }\n }\n\n /* --- V prípade neznámeho argumentu, alebo nepovolenej kombinácie argumentov skončí s chybou --- */\n if (($argument == false && $argc > 1) || $countOfParsedArguments != $argc) {\n fprintf(STDERR, \"Error: Unknown argument used!\\n\");\n exit(10);\n } elseif ((array_key_exists(\"parse-only\", $argument) && array_key_exists(\"int-only\", $argument)) || (array_key_exists(\"parse-only\", $argument) && ($in_flag == true)) || (array_key_exists(\"int-only\", $argument) && ($parse_flag == true))) { //Zadaná nepovolená kombinácia argumentov\n fprintf(STDERR, \"Error: Unauthorized combination of arguments\\n\");\n exit(10);\n }\n\n}\n\ngenerateHeader(); //Volanie funkcie na generovanie html hlavičky\n\n/* --- Vyhľadá všetky súbory s testami v zadanom priečinku --- */\nif ($rec_flag == false) {\n foreach (new DirectoryIterator($dir) as $fileInfo) {\n if ($fileInfo->isDot()) {\n continue;\n }\n if ($fileInfo->getExtension() == \"src\") {\n $src[] = $fileInfo->getPathname();\n }\n }\n} else { //Vyhľadá všetky súbory s testami v zadanom priečinku a rekurzívne aj v podpriečinkoch\n $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));\n foreach ($objects as $fileInfo) {\n if ($fileInfo->getExtension() == \"src\") {\n $src[] = $fileInfo->getPathname();\n }\n }\n}\n\n$succTestsCounter = 0;\n$failTestsCounter = 0;\n\n/* --- Načítanie jednotlivých testovacích súborov --- */\nforeach ($src as $run_test) {\n if (!($TemporaryParser = tmpfile()) || !($TemporaryInterpret = tmpfile())) {\n fprintf(STDERR, \"Internal Error: Failed to create temporary file.\\n\");\n exit(99);\n }\n\n $existenceArgument = \"File\";\n /* --- Pokiaľ jeden zo súborov typu in, rc alebo out neexistuje, bude vytvorený. V prípade neúspešného vytvorenia súboru, alebo nedostatočných oprávnení k vytvoreniu či otvoreniu súboru sa skript ukončí s chybou. --- */\n if (!($in = fopen(substr($run_test, 0, -3) . \"in\", \"c+\")) || !($rc = fopen(substr($run_test, 0, -3) . \"rc\", \"c+\"))) {\n existenceErr($existenceArgument);\n } elseif (!($out = fopen(substr($run_test, 0, -3) . \"out\", \"c+\"))) {\n fprintf(STDERR, \"Error: Failed opening output file, maybe insufficient permissions to file.\\n\");\n exit(12);\n }\n\n /* --- Nastavenie návratového kódu testu --- */\n if (filesize(substr($run_test, 0, -3) . \"rc\") == 0) {\n fwrite($rc, \"0\\n\");\n $ret_code = 0;\n } else {\n $ret_code = intval(fread($rc, filesize(substr($run_test, 0, -3) . \"rc\")));\n }\n /* --- Uzatvorenie testovacích súborov --- */\n fclose($in);\n fclose($rc);\n fclose($out);\n\n /* --- Spustenie skriptov pre jednotlivé testovacie súbory a vypísanie html reprezentácie výsledku testu pre skript parser --- */\n if ($int_only_flag == false) {\n exec(\"php7.3 $defaultParserFile < $run_test > \" . stream_get_meta_data($TemporaryParser)[\"uri\"] . \" 2>/dev/null \", $output_parser, $return_parser);\n\n $run_test_path = str_replace('/^.*\\/$/', \" \", $run_test);\n $xml_ref_input_file = substr($run_test, 0, -3) . \"out\";\n if ($return_parser != $ret_code && $parse_only_flag == true) {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"red\\\"><b> $return_parser </b></font>(Expected code: $ret_code)</p>\";\n $failTestsCounter++;\n } else if ($return_parser == $ret_code && $parse_only_flag == true && $return_parser != 0) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> $return_parser </b></font></p>\";\n $succTestsCounter++;\n } else if ($return_parser == $ret_code && $parse_only_flag == true) {\n exec(\"java -jar /pub/courses/ipp/jexamxml/jexamxml.jar \" . stream_get_meta_data($TemporaryParser)[\"uri\"] . \" $xml_ref_input_file /dev/null /pub/courses/ipp/jexamxml/options > /dev/null 2>/dev/null\", $output_java, $return_java);\n if ($return_java == 0) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> 0 </b></font></p>\";\n $succTestsCounter++;\n } else {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Parse test <i>$run_test_path</i> ended with <font color=\\\"red\\\"><b>diff error </b></font></p>\";\n $failTestsCounter++;\n }\n } else if ($return_parser == $ret_code) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> $return_parser </b></font></p>\";\n } else if ($return_parser != $ret_code && $ret_code < 29) {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"red\\\"><b> $return_parser </b></font>(Expected code: $ret_code)</p>\";\n $failTestsCounter++;\n } else if ($return_parser == 0 && $ret_code > 30) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> $return_parser </b></font></p>\";\n } else {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Parse test <i>$run_test_path</i> ended with return code:<font color=\\\"red\\\"><b> $return_parser </b></font>(Expected code: 0)</p>\";\n $failTestsCounter++;\n }\n }\n\n /* --- Spustenie skriptov pre jednotlivé testovacie súbory a vypísanie html reprezentácie výsledku testu pre skript interpret --- */\n if ($int_only_flag) {\n $return_parser = 0;\n }\n if ($parse_only_flag == false && $return_parser == 0) {\n $input_name = substr($run_test, 0, -3) . \"in\";\n $output_name = substr($run_test, 0, -3) . \"out\";\n $output_int = stream_get_meta_data($TemporaryInterpret)[\"uri\"];\n if ($int_only_flag == true) {\n exec(\"python3.6 $defaultInterpretFile --source=\" . $run_test . \" < $input_name > $output_int 2>/dev/null \", $output_interpret, $return_interpret);\n } else {\n exec(\"python3.6 $defaultInterpretFile --source=\" . stream_get_meta_data($TemporaryParser)[\"uri\"] . \" < $input_name > $output_int 2>/dev/null \", $output_interpret, $return_interpret);\n }\n\n $run_test_path = str_replace('/^.*\\/$/', \" \", $run_test);\n if ($return_interpret == $ret_code && $return_interpret == 0) { // diff output\n exec(\"diff $output_name $output_int 2>/dev/null\", $out_diff, $ret_diff);\n if ($ret_diff == 0) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Interpret <i>test $run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> $return_interpret </b></font></p>\";\n $succTestsCounter++;\n } else {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Interpret test <i>$run_test_path</i> ended with <font color=\\\"red\\\"><b>diff error </b></font></p>\";\n $failTestsCounter++;\n }\n } else if ($return_interpret == $ret_code) {\n echo \"<p><font color=\\\"green\\\"><b>SUCC</b></font> Interpret <i>test $run_test_path</i> ended with return code:<font color=\\\"green\\\"><b> $return_interpret </b></font></p>\";\n $succTestsCounter++;\n } else {\n echo \"<p><font color=\\\"red\\\"><b>FAIL</b></font> Interpret test <i>$run_test_path</i> ended with <font color=\\\"red\\\"><b>$return_interpret </b></font>(Expected code: $ret_code)</p>\";\n $failTestsCounter++;\n }\n }\n fclose($TemporaryParser);\n fclose($TemporaryInterpret);\n}\n\n/* --- Výpočet hodnot pre súhrn testov --- */\nif ($src != NULL) {\n $percent = (($succTestsCounter / count($src)) * 100);\n $testsCounter = count($src);\n generateSummaryOfTests($testsCounter, $failTestsCounter, $succTestsCounter, $percent);\n exit(0);\n} else {\n $testsCounter = 0;\n $failTestsCounter = 0;\n $succTestsCounter = 0;\n $percent = 0;\n echo \"<p style=\\\"color:red\\\"><b> No tests were found. </b></p>\";\n generateSummaryOfTests($testsCounter, $failTestsCounter, $succTestsCounter, $percent);\n exit(0);\n}\n\n?>\n"
}
] | 5 |
vincentmuya/Tech | https://github.com/vincentmuya/Tech | 86e486044eb968b25cb53edf003acde391936900 | 239dbab12a6f6324eec4c55223c331a3871375aa | df1d49839642d5dd9d3232e550b448ff813b298e | refs/heads/master | 2023-01-05T17:16:48.434239 | 2020-10-29T15:23:20 | 2020-10-29T15:23:20 | 308,339,499 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6565688848495483,
"alphanum_fraction": 0.6642219424247742,
"avg_line_length": 32.01052474975586,
"blob_id": "caaf4ccebcb3ba7f983a331caf4ad962fa4a6d16",
"content_id": "306db91f56748d4caa305010dbd3aabd34ee5383",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3136,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 95,
"path": "/project/app/models.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom slugify import slugify\nfrom django.urls import reverse\n\n# Create your models here.\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=200, db_index=True, null=True)\n slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'category'\n verbose_name_plural = 'categories'\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('article_list_by_category', args=[self.slug])\n\n\nclass Article(models.Model):\n category = models.ForeignKey(Category, related_name='products', null=True, on_delete=models.CASCADE)\n title = models.CharField(max_length=200, db_index=True)\n slug = models.SlugField(max_length=200, db_index=True, null=True)\n image = models.ImageField(upload_to=\"posts/\", blank=True, null=True)\n description = models.TextField(blank=True)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('title',)\n index_together = (('id', 'slug'),)\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super(Article, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse('article_detail', args=[self.id, self.slug])\n\n @classmethod\n def search_by_name(cls, search_term):\n search_result = cls.objects.filter(name__icontains=search_term)\n return search_result\n\n\nclass AccessoriesCategory(models.Model):\n name = models.CharField(max_length=200, db_index=True, null=True)\n slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'accesscategory'\n verbose_name_plural = 'accessories_categories'\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('article_list_by_category', args=[self.slug])\n\n\nclass Accessories(models.Model):\n accessoriescategory = models.ForeignKey(AccessoriesCategory, related_name='products', null=True, on_delete=models.CASCADE)\n name = models.CharField(max_length=200, db_index=True)\n slug = models.SlugField(max_length=200, db_index=True, null=True)\n image = models.ImageField(upload_to=\"posts/\", blank=True, null=True)\n description = models.TextField(blank=True)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('name',)\n index_together = (('id', 'slug'),)\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.name)\n super(Accessories, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('accessories_detail', args=[self.id, self.slug])\n\n @classmethod\n def search_by_name(cls, search_term):\n search_result = cls.objects.filter(name__icontains=search_term)\n return search_result\n"
},
{
"alpha_fraction": 0.5380459427833557,
"alphanum_fraction": 0.5515533685684204,
"avg_line_length": 38.66071319580078,
"blob_id": "266a68ec8caf07c1288f70212c29f3625abf2ddd",
"content_id": "2c1dbf576a539cf8b3b1cc3d41769723be2a9a83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2221,
"license_type": "no_license",
"max_line_length": 170,
"num_lines": 56,
"path": "/project/app/migrations/0002_auto_20201029_1819.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.2 on 2020-10-29 15:19\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AccessoriesCategory',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(db_index=True, max_length=200, null=True)),\n ('slug', models.SlugField(max_length=200, null=True, unique=True)),\n ],\n options={\n 'verbose_name': 'accesscategory',\n 'verbose_name_plural': 'accessories_categories',\n 'ordering': ('name',),\n },\n ),\n migrations.AddField(\n model_name='article',\n name='created',\n field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='article',\n name='updated',\n field=models.DateTimeField(auto_now=True),\n ),\n migrations.CreateModel(\n name='Accessories',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(db_index=True, max_length=200)),\n ('slug', models.SlugField(max_length=200, null=True)),\n ('image', models.ImageField(blank=True, null=True, upload_to='posts/')),\n ('description', models.TextField(blank=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('accessoriescategory', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='products', to='app.AccessoriesCategory')),\n ],\n options={\n 'ordering': ('name',),\n 'index_together': {('id', 'slug')},\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6946826577186584,
"alphanum_fraction": 0.7058318853378296,
"avg_line_length": 37.900001525878906,
"blob_id": "14a3f575b5d1179fb70236f8ab9467dca7c98683",
"content_id": "5da92b411202983706e0c0dcfabfe7aa2c32f995",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1166,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 30,
"path": "/project/app/views.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Article, Category\n\n# Create your views here.\n\n\ndef index(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n articles = Article.objects.all()[:4]\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n articles = articles.filter(category=category)\n return render(request, 'index.html', {'category': category, 'categories': categories, 'articles': articles})\n\n\ndef article_detail(request, id, slug):\n article = get_object_or_404(Article, id=id, slug=slug)\n categories = Category.objects.all()\n return render(request, 'article_detail.html', {'article':article, 'categories': categories})\n\n\ndef all_news(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n articles = Article.objects.all()\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n articles = articles.filter(category=category)\n return render(request, 'all_news.html', {'category': category, 'categories': categories, 'articles': articles})"
},
{
"alpha_fraction": 0.8358209133148193,
"alphanum_fraction": 0.8358209133148193,
"avg_line_length": 32.5,
"blob_id": "ed3f56d35d77e4d6c8ccc0e2dd6a639198fb9297",
"content_id": "6e29966a4ea58e1fe29e88fd89e4653167dbc0f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 8,
"path": "/project/app/admin.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import Article, Category, AccessoriesCategory, Accessories\n\n# Register your models here.\nadmin.site.register(Article)\nadmin.site.register(Category)\nadmin.site.register(AccessoriesCategory)\nadmin.site.register(Accessories)\n"
},
{
"alpha_fraction": 0.7183908224105835,
"alphanum_fraction": 0.7356321811676025,
"avg_line_length": 33.79999923706055,
"blob_id": "9a3a5ea7bce94259698e14c2b6b18e8d5b182c6e",
"content_id": "a31767fe61520aed7c05942aa20efa17925848a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 174,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 5,
"path": "/virtual/bin/django-admin.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "#!/home/v1nc3n7/Documents/Projects/Projects/blog/virtual/bin/python\nfrom django.core import management\n\nif __name__ == \"__main__\":\n management.execute_from_command_line()\n"
},
{
"alpha_fraction": 0.682758629322052,
"alphanum_fraction": 0.682758629322052,
"avg_line_length": 32.46154022216797,
"blob_id": "1c7cd4a44bc0a558cc29b27dea810d06f5c5e361",
"content_id": "dbacb08fda16640a0ed7c688169b024fcddc6789",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 13,
"path": "/project/app/urls.py",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P<id>\\d+)/(?P<slug>[-\\w]+)/$', views.article_detail, name='article_detail'),\n url(r'^news$', views.all_news, name='all_news'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n"
},
{
"alpha_fraction": 0.5362775921821594,
"alphanum_fraction": 0.7192429304122925,
"avg_line_length": 17.705883026123047,
"blob_id": "2393caff60d3cc4db94436a6d4d9cf891ff92111",
"content_id": "9c61b6633ad11b588d5a047924d6b724a5692373",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 17,
"path": "/requirements.txt",
"repo_name": "vincentmuya/Tech",
"src_encoding": "UTF-8",
"text": "Django==2.2\npytz==2020.1\nsqlparse==0.4.1\ndj-database-url==0.5.0\ndjango-bootstrap4==2.3.1\ndjango-tinymce==3.1.0\ndjango-model-utils==4.0.0\ngunicorn==20.0.4\nPillow==8.0.1\npsycopg2==2.8.6\npsycopg2-binary==2.8.6\npython-decouple==3.3\npython-slugify==4.0.1\nrequests==2.24.0\nurllib3==1.25.11\nwebsockets==8.1\nwhitenoise==3.3.1"
}
] | 7 |
vedu90/Logistic-Regression-and-SVM | https://github.com/vedu90/Logistic-Regression-and-SVM | 6a6575131235fcbbf195b29d630f31f4c5ac6e8e | 616cf34f03a34b0d692b93a6c58ec2e33f2bccb5 | bb656d404749b6083a50858230ff81176037aa6e | refs/heads/master | 2021-01-20T05:20:58.655616 | 2017-08-25T19:45:16 | 2017-08-25T19:45:16 | 101,436,567 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.584697961807251,
"alphanum_fraction": 0.6007981300354004,
"avg_line_length": 31.957944869995117,
"blob_id": "c6e695fa71df47d5b79feec4ce43c5c14e414712",
"content_id": "00b3613f662a83ab8469c5dae1cc971593b662ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14534,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 428,
"path": "/script_final.py",
"repo_name": "vedu90/Logistic-Regression-and-SVM",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport math\r\nfrom scipy.io import loadmat\r\nfrom scipy.optimize import minimize\r\nfrom sklearn.svm import SVC\r\nimport time\r\nimport pickle\r\n\r\n\r\ndef preprocess():\r\n \"\"\" \r\n Input:\r\n Although this function doesn't have any input, you are required to load\r\n the MNIST data set from file 'mnist_all.mat'.\r\n\r\n Output:\r\n train_data: matrix of training set. Each row of train_data contains \r\n feature vector of a image\r\n train_label: vector of label corresponding to each image in the training\r\n set\r\n validation_data: matrix of training set. Each row of validation_data \r\n contains feature vector of a image\r\n validation_label: vector of label corresponding to each image in the \r\n training set\r\n test_data: matrix of training set. Each row of test_data contains \r\n feature vector of a image\r\n test_label: vector of label corresponding to each image in the testing\r\n set\r\n \"\"\"\r\n\r\n mat = loadmat('mnist_all.mat') # loads the MAT object as a Dictionary\r\n\r\n n_feature = mat.get(\"train1\").shape[1]\r\n n_sample = 0\r\n for i in range(10):\r\n n_sample = n_sample + mat.get(\"train\" + str(i)).shape[0]\r\n n_validation = 1000\r\n n_train = n_sample - 10 * n_validation\r\n\r\n # Construct validation data\r\n validation_data = np.zeros((10 * n_validation, n_feature))\r\n for i in range(10):\r\n validation_data[i * n_validation:(i + 1) * n_validation, :] = mat.get(\"train\" + str(i))[0:n_validation, :]\r\n\r\n # Construct validation label\r\n validation_label = np.ones((10 * n_validation, 1))\r\n for i in range(10):\r\n validation_label[i * n_validation:(i + 1) * n_validation, :] = i * np.ones((n_validation, 1))\r\n\r\n # Construct training data and label\r\n train_data = np.zeros((n_train, n_feature))\r\n train_label = np.zeros((n_train, 1))\r\n temp = 0\r\n for i in range(10):\r\n size_i = mat.get(\"train\" + str(i)).shape[0]\r\n train_data[temp:temp + size_i - n_validation, :] = mat.get(\"train\" + str(i))[n_validation:size_i, :]\r\n train_label[temp:temp + size_i - n_validation, :] = i * np.ones((size_i - n_validation, 1))\r\n temp = temp + size_i - n_validation\r\n\r\n # Construct test data and label\r\n n_test = 0\r\n for i in range(10):\r\n n_test = n_test + mat.get(\"test\" + str(i)).shape[0]\r\n test_data = np.zeros((n_test, n_feature))\r\n test_label = np.zeros((n_test, 1))\r\n temp = 0\r\n for i in range(10):\r\n size_i = mat.get(\"test\" + str(i)).shape[0]\r\n test_data[temp:temp + size_i, :] = mat.get(\"test\" + str(i))\r\n test_label[temp:temp + size_i, :] = i * np.ones((size_i, 1))\r\n temp = temp + size_i\r\n\r\n # Delete features which don't provide any useful information for classifiers\r\n sigma = np.std(train_data, axis=0)\r\n index = np.array([])\r\n for i in range(n_feature):\r\n if (sigma[i] > 0.001):\r\n index = np.append(index, [i])\r\n train_data = train_data[:, index.astype(int)]\r\n validation_data = validation_data[:, index.astype(int)]\r\n test_data = test_data[:, index.astype(int)]\r\n\r\n # Scale data to 0 and 1\r\n train_data /= 255.0\r\n validation_data /= 255.0\r\n test_data /= 255.0\r\n\r\n return train_data, train_label, validation_data, validation_label, test_data, test_label\r\n\r\n\r\ndef sigmoid(z):\r\n return 1.0 / (1.0 + np.exp(-z))\r\n\r\n\r\ndef blrObjFunction(initialWeights, *args):\r\n \"\"\"\r\n blrObjFunction computes 2-class Logistic Regression error function and\r\n its gradient.\r\n\r\n Input:\r\n initialWeights: the weight vector (w_k) of size (D + 1) x 1 \r\n train_data: the data matrix of size N x D\r\n labeli: the label vector (y_k) of size N x 1 where each entry can be either 0 or 1 representing the label of corresponding feature vector\r\n\r\n Output: \r\n error: the scalar value of error function of 2-class logistic regression\r\n error_grad: the vector of size (D+1) x 1 representing the gradient of\r\n error function\r\n \"\"\"\r\n \r\n train_data, labeli = args\r\n\r\n n_data = train_data.shape[0]\r\n n_features = train_data.shape[1]\r\n error = 0\r\n error_grad = np.zeros((n_features + 1, 1))\r\n \r\n\r\n ##################\r\n # YOUR CODE HERE #\r\n ##################\r\n # HINT: Do not forget to add the bias term to your input data\r\n \r\n initialWeights = initialWeights.reshape(n_features+1,1)\r\n train_data = np.insert(train_data, 0, 1, axis = 1)\r\n y_sig = sigmoid(np.dot(train_data,initialWeights))\r\n y = np.multiply(labeli,np.log(y_sig)) + np.multiply((1.0-labeli),np.log(1.0-y_sig))\r\n \r\n ## Error ##\r\n\r\n error = np.sum(y)/n_data\r\n \r\n error*=-1\r\n \r\n #error_grad = np.multiply((y_sig - labeli),train_data)\r\n error_grad = np.dot(train_data.T,(y_sig-labeli))/n_data\r\n error_grad = error_grad.flatten()\r\n \r\n return error, error_grad\r\n\r\ndef blrPredict(W, data):\r\n \"\"\"\r\n blrObjFunction predicts the label of data given the data and parameter W \r\n of Logistic Regression\r\n \r\n Input:\r\n W: the matrix of weight of size (D + 1) x 10. Each column is the weight \r\n vector of a Logistic Regression classifier.\r\n X: the data matrix of size N x D\r\n \r\n Output: \r\n label: vector of size N x 1 representing the predicted label of \r\n corresponding feature vector given in data matrix\r\n\r\n \"\"\"\r\n label = np.zeros((data.shape[0], 1))\r\n\r\n ##################\r\n # YOUR CODE HERE #\r\n ##################\r\n # HINT: Do not forget to add the bias term to your input data\r\n \r\n data = np.insert(data, 0, 1, axis = 1)\r\n \r\n y_sig = sigmoid(np.dot(data,W)) \r\n label = np.argmax(y_sig,axis=1) \r\n label = label.reshape((data.shape[0],1))\r\n return label\r\n\r\n\r\ndef mlrObjFunction(params, *args):\r\n \"\"\"\r\n mlrObjFunction computes multi-class Logistic Regression error function and\r\n its gradient.\r\n\r\n Input:\r\n initialWeights: the weight vector of size (D + 1) x 1\r\n train_data: the data matrix of size N x D\r\n labeli: the label vector of size N x 1 where each entry can be either 0 or 1\r\n representing the label of corresponding feature vector\r\n\r\n Output:\r\n error: the scalar value of error function of multi-class logistic regression\r\n error_grad: the vector of size (D+1) x 10 representing the gradient of\r\n error function\r\n \"\"\"\r\n w = params\r\n train_data, labeli = args\r\n n_data = train_data.shape[0]\r\n n_feature = train_data.shape[1]\r\n error = 0\r\n error_grad = np.zeros((n_feature + 1, n_class))\r\n #print(\"Data len : \",n_data,len(train_data[0]))\r\n ##################\r\n # YOUR CODE HERE #\r\n ##################\r\n # HINT: Do not forget to add the bias term to your input data\r\n \r\n w = w.reshape(n_feature+1 , n_class)\r\n train_data = np.insert(train_data,0,1,axis=1)\r\n y_in = np.exp(np.dot(train_data,w))\r\n y_in_den = np.sum(y_in,axis=1)\r\n y_soft = y_in / np.matrix(y_in_den).T\r\n #print(y_in_den.shape)\r\n\r\n ## Error ##\r\n \r\n error = - np.sum(np.multiply(labeli,np.log(y_soft)))\r\n #print(error)\r\n error_grad = np.dot(train_data.T,(y_soft-labeli))\r\n error_grad = np.array(error_grad).flatten()\r\n\r\n return error, error_grad\r\n\r\n\r\ndef mlrPredict(W, data):\r\n \"\"\"\r\n mlrObjFunction predicts the label of data given the data and parameter W\r\n of Logistic Regression\r\n\r\n Input:\r\n W: the matrix of weight of size (D + 1) x 10. Each column is the weight\r\n vector of a Logistic Regression classifier.\r\n X: the data matrix of size N x D\r\n\r\n Output:\r\n label: vector of size N x 1 representing the predicted label of\r\n corresponding feature vector given in data matrix\r\n\r\n \"\"\"\r\n label = np.zeros((data.shape[0], 1))\r\n\r\n ##################\r\n # YOUR CODE HERE #\r\n ##################\r\n # HINT: Do not forget to add the bias term to your input data\r\n data = np.insert(data, 0, 1, axis = 1)\r\n y_in = np.exp(np.dot(data,W))\r\n y_in_den = np.sum(y_in,axis=1)\r\n y_soft = y_in / np.matrix(y_in_den).T\r\n\r\n label = np.argmax(y_soft, axis = 1)\r\n #label = label.reshape((n_data,1))\r\n return label\r\n\r\n\r\n\"\"\"\r\nScript for Logistic Regression\r\n\"\"\"\r\ntrain_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()\r\n\r\nst = time.time()\r\n\r\n# number of classes\r\nn_class = 10\r\n\r\n# number of training samples\r\nn_train = train_data.shape[0]\r\n\r\n# number of features\r\nn_feature = train_data.shape[1]\r\n\r\nY = np.zeros((n_train, n_class))\r\nfor i in range(n_class):\r\n Y[:, i] = (train_label == i).astype(int).ravel()\r\n\r\n# Logistic Regression with Gradient Descent\r\nW = np.zeros((n_feature + 1, n_class))\r\ninitialWeights = np.zeros((n_feature + 1, 1))\r\nopts = {'maxiter': 100}\r\nfor i in range(n_class):\r\n labeli = Y[:, i].reshape(n_train, 1)\r\n args = (train_data, labeli)\r\n nn_params = minimize(blrObjFunction, initialWeights, jac=True, args=args, method='CG', options=opts)\r\n W[:, i] = nn_params.x.reshape((n_feature + 1,))\r\n\r\net = time.time()\r\n\r\n#print(\"Learning time for BLR \",et-st)\r\n\r\n# Find the accuracy on Training Dataset\r\npredicted_label = blrPredict(W, train_data)\r\nprint('\\n Training set Accuracy:' + str(100 * np.mean((predicted_label == train_label).astype(float))) + '%')\r\n\r\n# Find the accuracy on Validation Dataset\r\npredicted_label = blrPredict(W, validation_data)\r\nprint('\\n Validation set Accuracy:' + str(100 * np.mean((predicted_label == validation_label).astype(float))) + '%')\r\n\r\n# Find the accuracy on Testing Dataset\r\npredicted_label = blrPredict(W, test_data)\r\nprint('\\n Testing set Accuracy:' + str(100 * np.mean((predicted_label == test_label).astype(float))) + '%')\r\n\r\n\"\"\"\r\nScript for Support Vector Machine\r\n\"\"\"\r\n\r\nst = time.time()\r\nprint('\\n\\n--------------SVM-------------------\\n\\n')\r\n##################\r\n# YOUR CODE HERE #\r\n##################\r\n\r\nprint('\\n\\n--------------SVM linear-------------------\\n\\n')\r\nclf = SVC(kernel = 'linear')\r\n#train_label = train_label.ravel()\r\n#print(type((train_label)))\r\nclf.fit(train_data, train_label.ravel())\r\nprint(\"After svc\")\r\nres = clf.predict(train_data)\r\nprint(\"res :\" + str(res))\r\nprint (\"train accuracy : \"+ str(100 * clf.score(train_data, train_label)) + \"%\")\r\n#print (\"train accuracy : \"+ str(100 * np.mean(res == train_label).astype(float)) + \"%\")\r\nprint (\"validation accuracy : \"+ str(100 * clf.score(validation_data, validation_label)) + \"%\")\r\nprint (\"test accuracy : \"+ str(100 * clf.score(test_data, test_label)) + \"%\")\r\n#print (\"accuracy : \"+ str(accuracy_score(train_label., res)))\r\n\r\n\r\nprint('\\n\\n--------------SVM rbf with gamma one-------------------\\n\\n')\r\nclf = SVC(kernel='rbf',gamma=1.0)\r\n#train_label = \r\n#print(type((train_label)))\r\nclf.fit(train_data, train_label.ravel())\r\nprint(\"After svc\")\r\n#res = clf.predict(train_data)\r\n#print(\"res :\" + str(res))\r\nprint (\"train accuracy : \"+ str(100 * clf.score(train_data, train_label)) + \"%\")\r\nprint (\"validation accuracy : \"+ str(100 * clf.score(validation_data, validation_label)) + \"%\")\r\nprint (\"test accuracy : \"+ str(100 * clf.score(test_data, test_label)) + \"%\")\r\n\r\nprint('\\n\\n--------------SVM rbf with gamma as default-------------------\\n\\n')\r\n\r\nclf = SVC(kernel='rbf')\r\n#train_label = train_label.ravel()\r\n#print(type((train_label)))\r\nclf.fit(train_data, train_label.ravel())\r\nprint(\"After svc\")\r\n\r\nprint (\"train accuracy : \"+ str(100 * clf.score(train_data, train_label)) + \"%\")\r\nprint (\"valildation accuracy : \"+ str(100 * clf.score(validation_data, validation_label)) + \"%\")\r\nprint (\"test accuracy : \"+ str(100 * clf.score(test_data, test_label)) + \"%\")\r\n\r\nprint('\\n\\n--------------SVM with different C-------------------\\n\\n')\r\nclf = SVC(kernel='rbf',C = 1.0)\r\n#train_label = train_label.ravel()\r\n#print(type((train_label)))\r\nclf.fit(train_data, train_label.ravel())\r\nprint('\\n\\n--------------SVM with different C = 1-------------------\\n\\n')\r\n\r\nCArr = [1.0]\r\ntrainAccArr = []\r\nvalidationAccArr = [] \r\ntestAccArr = []\r\n\r\ntemp = 100 * clf.score(train_data, train_label)\r\nprint (\"train accuracy : \"+ str(temp) + \"%\")\r\ntrainAccArr.append(temp)\r\ntemp = 100 * clf.score(validation_data, validation_label)\r\nprint (\"validation accuracy : \"+ str(temp) + \"%\")\r\nvalidationAccArr.append(temp)\r\ntemp = 100 * clf.score(test_data, test_label)\r\nprint (\"test ccuracy : \"+ str(temp) + \"%\")\r\ntestAccArr.append(temp)\r\n \r\nfor i in range(10,101,10) :\r\n CArr.append(float(i))\r\n clf = SVC(C = float(i),kernel='rbf')\r\n clf.fit(train_data, train_label.ravel())\r\n print('\\n\\n--------------SVM with different C = ' +str(i)+'-------------------\\n\\n')\r\n temp = 100 * clf.score(train_data, train_label)\r\n print (\"train accuracy : \"+ str(temp) + \"%\")\r\n trainAccArr.append(temp)\r\n temp = 100 * clf.score(validation_data, validation_label)\r\n print (\"validation accuracy : \"+ str(temp) + \"%\")\r\n validationAccArr.append(temp)\r\n temp = 100 * clf.score(test_data, test_label)\r\n print (\"test accuracy : \"+ str(temp) + \"%\")\r\n testAccArr.append(temp)\r\n \r\n#print(\"array\" + str(trainAccArr))\r\n#print(\"array\" + str(validationAccArr))\r\n#print(\"array\" + str(testAccArr))\r\n\r\n\r\n\r\net = time.time()\r\n\r\n#print(\"Time taken for SVM \",et-st)\r\n\r\n\"\"\"\r\nScript for Extra Credit Part\r\n\"\"\"\r\n\r\n# FOR EXTRA CREDIT ONLY\r\nW_b = np.zeros((n_feature + 1, n_class))\r\ninitialWeights_b = np.zeros((n_feature + 1, n_class))\r\nopts_b = {'maxiter': 100}\r\nst = time.time()\r\nargs_b = (train_data, Y)\r\nnn_params = minimize(mlrObjFunction, initialWeights_b, jac=True, args=args_b, method='CG', options=opts_b)\r\nW_b = nn_params.x.reshape((n_feature + 1, n_class))\r\n\r\net = time.time()\r\n\r\n#print(\"Learning time for MLR \",et-st)\r\n\r\n\r\n# Find the accuracy on Training Dataset\r\npredicted_label_b = mlrPredict(W_b, train_data)\r\nprint('\\n Training set Accuracy:' + str(100 * np.mean((predicted_label_b == train_label).astype(float))) + '%')\r\n\r\n# Find the accuracy on Validation Dataset\r\npredicted_label_b = mlrPredict(W_b, validation_data)\r\nprint('\\n Validation set Accuracy:' + str(100 * np.mean((predicted_label_b == validation_label).astype(float))) + '%')\r\n\r\n# Find the accuracy on Testing Dataset\r\npredicted_label_b = mlrPredict(W_b, test_data)\r\nprint('\\n Testing set Accuracy:' + str(100 * np.mean((predicted_label_b == test_label).astype(float))) + '%')\r\n\r\n\r\n'''\r\nf1 = open('params.pickle', 'wb') \r\npickle.dump(W, f1) \r\nf1.close()\r\n\r\nf2 = open('params_bonus.pickle', 'wb')\r\npickle.dump(W_b, f2)\r\nf2.close()\r\n'''\r\n"
},
{
"alpha_fraction": 0.8211538195610046,
"alphanum_fraction": 0.8211538195610046,
"avg_line_length": 51,
"blob_id": "9ab06f70243be7bc55160552536d4e885f7c5de4",
"content_id": "7a110f04d299f20d410e1749e0587a7a2fb3ca2f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 520,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 10,
"path": "/README.md",
"repo_name": "vedu90/Logistic-Regression-and-SVM",
"src_encoding": "UTF-8",
"text": "# Logistic-Regression-and-SVM\nIn this assignment, we will extend the \frst programming assignment in solving the problem of handwritten\ndigit classi\fcation. In particular, your task is to implement Logistic Regression and use the Support Vector\nMachine tool in sklearn.svm.SVM to classify handwritten digit images and compare the performance of\nthese methods.\nTo get started with the exercise. you will need to download the supporting \fles. Unzip its contents to the\ndirectory where you want to complete this assignment.\n"
}
] | 2 |
csanvesh/POS-Tagging | https://github.com/csanvesh/POS-Tagging | f38c99e85114f3611ee3d43c350d2551eb4ba0f2 | 8e9fc4ce35ab051f0de347e943404d835a1cc97f | edcff777f8cd5d97ac057bebffca38e6a4d0437d | refs/heads/master | 2021-05-09T19:56:11.746145 | 2018-01-23T20:32:02 | 2018-01-23T20:32:02 | 118,665,546 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6074578166007996,
"alphanum_fraction": 0.6237538456916809,
"avg_line_length": 36.25714111328125,
"blob_id": "02554ab1d7b4b42577a49cfd4368111b08d76548",
"content_id": "f04dc2905d541ca52bf17577c3545b0d54264852",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10432,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 280,
"path": "/trigram_penn.py",
"repo_name": "csanvesh/POS-Tagging",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nfrom optparse import OptionParser\nimport os, logging\nimport utils_penn\nimport collections\nimport re\n\ndef create_model(sentences):\n\tword_count=collections.defaultdict(lambda : collections.defaultdict(int)) #house noun 10\n\tpos_count= collections.defaultdict(int) # total nouns: 2k\n\tword_frequency=collections.defaultdict(int)\n\tpos_seqcount=collections.defaultdict(lambda : collections.defaultdict(int))\n\tpos_seqcount_trigram=collections.defaultdict(lambda : collections.defaultdict(lambda : collections.defaultdict(int)))\n\tword_posprob=collections.defaultdict(lambda : collections.defaultdict(int))\n\twordtypes=[]\n\ttagset=[]\n\ttotal_words=0\n\tsingle_words=0\n\tprob_single_word=0.0\n\tmodel=[pos_seqcount_trigram,word_posprob,tagset,word_count]\n\tfor sentence in sentences:\n\t\t#print(sentence)\n\t\tpos_count[\"<s>\"]+=1\n\t\t#print(sentence)\n\t\tpos_seqcount[\"<s>\"][\"<s>\"] += 1\n\t\tpos_seqcount[\"<s>\"][sentence[0].tag] += 1\n\t\tpos_seqcount_trigram[\"<s>\"][\"<s>\"][sentence[0].tag] += 1\n\t\tpos_seqcount_trigram[\"<s>\"][sentence[0].tag][sentence[1].tag] += 1\n\t\t#print(pos_seqcount[\"<s>\"][sentence[0].tag])\n\t\tfor token in sentence:\n\t\t\ttoken.word=token.word.lower()\n\t\t\ttotal_words+=1\n\t\t\tword_frequency[token.word]+=1\n\t\t\t#print(token.word,word_frequency[token.word] )\n\t\t\tword_count[token.word][token.tag]+=1\n\t\t\tif(token.word not in wordtypes):\n\t\t\t\twordtypes.append(token.word)\n\t\t\tif(token.tag not in tagset):\n\t\t\t\ttagset.append(token.tag)\n\t\t\tpos_count[token.tag] += 1\n\t\tfor index in range(0,len(sentence)-1):\n\t\t\tpos_seqcount[sentence[index].tag][sentence[index + 1].tag] += 1\n\t\tfor index in range(0,len(sentence)-2):\n\t\t\tpos_seqcount_trigram[sentence[index].tag][sentence[index + 1].tag][sentence[index + 2].tag] += 1\n\tdummy_tagset=[\"<s>\"] + tagset\n\t#print(\"Tagset:\")\n\t#print(tagset)\n\t'''print(\"Dummytagset\")\n\tprint(dummy_tagset)'''\n\t'''print(\"wordtypes:\")\n\tprint(wordtypes)\n\tprint(\"Prior prob values:\")'''\n\t#print(len(tagset))\n\t#for tag1 in dummy_tagset:\n\t#\tfor tag2 in tagset:\n\t#\t\t'''if(pos_seqcount[tag1][tag2]== 0):\n\t#\t\t\tpos_seqcount[tag1][tag2] = float(1.0/(pos_count[tag1] + len(tagset)))\n\t#\t\telse:'''\n\t#\t\tpos_seqcount[tag1][tag2] = float((pos_seqcount[tag1][tag2] + 1.0)/(pos_count[tag1] + len(tagset)))\n\t\t\t#print(tag1,tag2,pos_seqcount[tag1][tag2])\n\t#print(len(tagset))\n\t#print(\"printing trigrams\")\n\tfor tag3 in tagset:\n\t\t#print(tag3,pos_seqcount_trigram[\"<s>\"][\"<s>\"][tag3])\n\t\tpos_seqcount_trigram[\"<s>\"][\"<s>\"][tag3]= float((pos_seqcount_trigram[\"<s>\"][\"<s>\"][tag3] + 1.0)/(pos_seqcount[\"<s>\"][\"<s>\"] + (len(tagset) * len(tagset))))\n\t\t#print(tag3,pos_seqcount_trigram[\"<s>\"][\"<s>\"][tag3])\n\tfor tag1 in dummy_tagset:\n\t\tfor tag2 in tagset:\n\t\t\tfor tag3 in tagset:\n\t\t\t\t#print(\"count:\")\n\t\t\t\t#print(tag1,tag2,tag3,pos_seqcount_trigram[tag1][tag2][tag3])\n\t\t\t\t#print(\"value:\")\n\t\t\t\tpos_seqcount_trigram[tag1][tag2][tag3]= float((pos_seqcount_trigram[tag1][tag2][tag3] + 1.0)/(pos_seqcount[tag1][tag2] + (len(tagset) * len(tagset))))\n\t\t\t\t#print(tag1,tag2,tag3,pos_seqcount_trigram[tag1][tag2][tag3])\n\t\n\t#print(\"2nd matrix\")\n\tfor tag in tagset:\n\t\tfor word in wordtypes:\n\t\t\tword_posprob[tag][word]= float((word_count[word][tag] + 0.0) / pos_count[tag])\n\t\t\t#print(tag,word,word_posprob[tag][word])\n\tfor wrd,freq in word_frequency.iteritems():\n\t\t#print(word,freq)\n\t\tif(freq==1):\n\t\t\t#print(\"incrementing by 1\")\n\t\t\tsingle_words+=1\n\t\n\tprob_single_word= float(single_words)/total_words\n\t#print(prob_single_word)\n\t\t\t\n\t'''word_count=collections.defaultdict(lambda : collections.defaultdict(int))\n\tfor sentence in sentences:\n\t\tfor token in sentence:\n\t\t\tword_count[token.word][token.tag]+=1\n\t\n\tfor word,tag_set in word_count.iteritems():\n\t\tcount=0\n\t\tfor pos,freq in tag_set.iteritems():\n\t\t\tif(count < freq):\n\t\t\t\t#print(\"updated\")\n\t\t\t\tcount=freq\n\t\t\t\tpos_name=pos\n\t\tmodel[word]=pos_name'''\n\t#print model\n\tmodel.append(prob_single_word)\n\treturn model\n ## YOUR CODE GOES HERE: create a model\n\n #return model\ndef getPossbileTagForUnknownWord(word):\n if(word == \".\"):\n tag=\".\"\n elif(re.compile(\"^[a-z]+ly$\").match(word)):\n tag=\"RB\"\n elif(re.compile(\"^[a-z]+ing$\").match(word)):\n tag=\"VBG\"\n elif(re.compile(\"^[a-z]+ed$\").match(word)):\n tag=\"VBD\"\n elif(re.compile(\"^[A-Z]+[a-z]*can$\").match(word)):\n tag = \"JJ\"\n elif(re.compile(\"^[A-Z]+[a-z]*$\").match(word)):\n tag = \"NNP\"\n elif(re.compile(\"^[A-Z]+[a-z]*s$\").match(word)):\n tag = \"NNPS\"\n elif(re.compile(\"^[0-9]+$\").match(word)):\n tag=\"CD\" \n elif(re.compile(\"^[a-z]+ize$\").match(word)):\n tag=\"VB\" \n elif(re.compile(\"^[a-z]+ized\").match(word)):\n tag=\"VBD\" \n elif(re.compile(\"^[a-z]+al$\").match(word)):\n tag=\"JJ\"\n elif(re.compile(\"^[a-z]+-[a-z]+$\").match(word)):\n tag=\"JJ\" \n elif(re.compile(\"^[a-z]+al$\").match(word)):\n tag=\"JJ\"\n elif(re.compile(\"^[a-z]+es$\").match(word)):\n tag=\"NNS\"\n elif(re.compile(\"^[a-z]+ation$\").match(word)):\n tag=\"NN\"\n elif(re.compile(\"^[a-z]+ations$\").match(word)):\n tag=\"NNS\"\n elif(re.compile(\"a|an|the\").match(word)):\n tag=\"DT\"\n else:\n if(str.startswith(word,\"un\")):\n newWord = re.sub(\"un\",\"\",word)\n subTag = getPossbileTagForUnknownWord(newWord)\n if(subTag == \"VB\"):\n tag=\"VB\"\n else:\n tag=\"JJ\"\n elif(str.startswith(word,\"dis\")):\n newWord = re.sub(\"dis\",\"\",word)\n subTag = getPossbileTagForUnknownWord(newWord)\n if(subTag == \"VB\"):\n tag=\"VB\"\n else:\n tag=\"JJ\"\n else:\n if(str.endswith(word,\"s\")):\n tag=\"NNS\"\n else:\n tag=\"NN\"\n return tag\ndef predict_tags(sentences, model):\n ## YOU CODE GOES HERE: use the model to predict tags for sentences\n\tprior=model[0]\n\tlikehood= model[1]\n\ttagset=model[2]\n\t#print(tagset)\n\tword_count=model[3]\n\tgoodtuned_value=model[4]\n\t#print(goodtuned_value)\n\tcounts=0\n\t#viterbi2=[]\n\tfor sentence in sentences:\n\t\t#print(counts)\n\t\t#counts+=1\n\t\tviterbi=[[0.0 for j in range(len(tagset))] for i in range(len(sentence))]\n\t\tviterbi2=[[[0 for z in range(2)] for j in range(len(tagset))] for i in range(len(sentence))]\n\t\tfor word_index in range(0,len(sentence)):\n\t\t\tfor tag_index in range(0,len(tagset)):\n\t\t\t\tsentence[word_index].word=sentence[word_index].word.lower()\n\t\t\t\tprsnt_tag= tagset[tag_index]\n\t\t\t\t#print(\"Present tag\")\n\t\t\t\t#print(prsnt_tag)\n\t\t\t\tprsnt_word= sentence[word_index].word\n\t\t\t\tif(word_count.has_key(sentence[word_index].word)):\n\t\t\t\t\tlikehood_value= likehood[prsnt_tag][prsnt_word]\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tnew_tag=getPossbileTagForUnknownWord(prsnt_word)\n\t\t\t\t\t#if(new_tag==\"VB\" or new_tag==\"VBD\" or new_tag==\"VBG\" or new_tag==\"VBN\" or new_tag==\"VBP\" or new_tag==\"VBZ\"):\n\t\t\t\t\t#\tnew_tag=\"VERB\"\n\t\t\t\t\t#if(new_tag == \"NN\" or new_tag==\"NNS\" or new_tag==\"NNP\" or new_tag==\"NNPS\"):\n\t\t\t\t\t#\tnew_tag=\"NOUN\"\n\t\t\t\t\tif(prsnt_tag == new_tag):\n\t\t\t\t\t\tlikehood_value=goodtuned_value\n\t\t\t\t\t\t#likehood_value=0.00000000001\n\t\t\t\t\t\t#likehood_value=0.0\n\t\t\t\t\telse:\n\t\t\t\t\t\tlikehood_value=0.0\n\t\t\t\t\t#likehood_value=0.00000000001\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\ttag_winner=\"<s>\"\n\t\t\t\tif(word_index == 0):\n\t\t\t\t\tviterbi[word_index][tag_index]= (likehood_value)*(prior[\"<s>\"][\"<s>\"][prsnt_tag])\n\t\t\t\t\t#viterbi[word_index][tag_index]= (likehood[prsnt_tag][prsnt_word])*(prior[\"<s>\"][prsnt_tag])\n\t\t\t\t\tviterbi2[word_index][tag_index]=[0,0]\n\t\t\t\telse:\n\t\t\t\t\tviterbi[word_index][tag_index]=0\n\t\t\t\t\t\n\t\t\t\t\t#print(word_index,prsnt_tag,tag_winner)\n\t\t\t\t\tfor index_before in range(0,len(tagset)):\n\t\t\t\t\t\ttag_winner_loc=viterbi2[word_index -1][index_before]\n\t\t\t\t\t\ttag_winner=tagset[tag_winner_loc[1]]\n\t\t\t\t\t\tif(word_index == 1):\n\t\t\t\t\t\t\tcurrent_viterbi_value = (viterbi[word_index - 1][index_before]) * ( likehood_value) * (prior[\"<s>\"][tagset[index_before]][prsnt_tag])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcurrent_viterbi_value = (viterbi[word_index - 1][index_before]) * ( likehood_value) * (prior[tag_winner][tagset[index_before]][prsnt_tag])\n\t\t\t\t\t\t#current_viterbi_value = (viterbi[word_index - 1][index_before]) * ( likehood[prsnt_tag][prsnt_word]) * (prior[tagset[index_before]][prsnt_tag])\n\t\t\t\t\t\tif(current_viterbi_value >= viterbi[word_index][tag_index]):\n\t\t\t\t\t\t\tviterbi[word_index][tag_index]=current_viterbi_value\n\t\t\t\t\t\t\tprior_word_index=word_index - 1\n\t\t\t\t\t\t\tprior_tag_index= index_before\n\t\t\t\t\t\t\tviterbi2[word_index][tag_index]= [prior_word_index,prior_tag_index]\n\t\tmax=0\n\t\tfor last_tagindex in range(0,len(tagset)):\n\t\t\tif(viterbi[len(sentence)-1][last_tagindex] >= max):\n\t\t\t\tmax=viterbi[len(sentence)-1][last_tagindex]\n\t\t\t\tlast_tag=tagset[last_tagindex]\n\t\t\t\ttemp=viterbi2[len(sentence)-1][last_tagindex]\n\t\tsentence[len(sentence)-1].tag=last_tag\n\t\tfor token_index in range(len(sentence)-2,-1,-1):\n\t\t\tsentence[token_index].tag= tagset[temp[1]]\n\t\t\ttemp= viterbi2[temp[0]][temp[1]]\n\t\t'''for row in range(len(sentence)):\n\t\t\tfor column in range(len(tagset)):\n\t\t\t\tprint(viterbi[row][column])'''\n\t\t'''for token in sentence:\n\t\t\tprint(token.word,token.tag)'''\n\treturn sentences\n\nif __name__ == \"__main__\":\n usage = \"usage: %prog [options] GOLD TEST\"\n parser = OptionParser(usage=usage)\n\n parser.add_option(\"-d\", \"--debug\", action=\"store_true\",\n help=\"turn on debug mode\")\n\n (options, args) = parser.parse_args()\n if len(args) != 2:\n parser.error(\"Please provide required arguments\")\n\n if options.debug:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.CRITICAL)\n\ttraining_file = args[0]\n\ttraining_sents = utils_penn.read_tokens(training_file)\n\ttest_file = args[1]\n\ttest_sents = utils_penn.read_tokens(test_file)\n\t#create_model(training_sents)\n\n model = create_model(training_sents)\n\t\n\n ## read sentences again because predict_tags(...) rewrites the tags\n sents = utils_penn.read_tokens(training_file)\n predictions = predict_tags(sents, model)\n accuracy = utils_penn.calc_accuracy(training_sents, predictions)\n print \"Accuracy in training [%s sentences]: %s\" % (len(sents), accuracy)\n\n ## read sentences again because predict_tags(...) rewrites the tags\n sents = utils_penn.read_tokens(test_file)\n predictions = predict_tags(sents, model)\n accuracy = utils_penn.calc_accuracy(test_sents, predictions)\n print \"Accuracy in training [%s sentences]: %s\" % (len(sents), accuracy)\n"
}
] | 1 |
tonmoy18/tamarisc | https://github.com/tonmoy18/tamarisc | d25afc1f993ec4de1c3ba01fa85e5487df309170 | 8de284c6343f39dcac3470c2196fb2923e09450d | 596e7fcb88a8b8c7c070524fd7b9670e8636cb72 | refs/heads/master | 2020-09-22T17:19:26.342934 | 2020-03-26T15:14:47 | 2020-03-26T15:14:47 | 225,283,513 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5597015023231506,
"alphanum_fraction": 0.6268656849861145,
"avg_line_length": 21.16666603088379,
"blob_id": "abc2b6b4118bfe65bd50911b5d428dafcc12a6cd",
"content_id": "9bc647be07632b69a00de108860292e992c69489",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 134,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 6,
"path": "/vsim/riscv-tests/scripts/convert_all.sh",
"repo_name": "tonmoy18/tamarisc",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nfor f in \"$@\"\ndo\n python ./scripts/dump2hex.py $f 80000000 > hexfiles/$(basename $(echo $f) | sed s/dump/hex/g)\ndone\n\n"
},
{
"alpha_fraction": 0.5600000023841858,
"alphanum_fraction": 0.5745454430580139,
"avg_line_length": 26.5,
"blob_id": "3f6abb43cfabf6e8fecb76111e16ea26fee7de75",
"content_id": "40eaf69bf5c9d2733b95ff5cad9a5de9daec1d5f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 275,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 10,
"path": "/vsim/run_all.sh",
"repo_name": "tonmoy18/tamarisc",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nfor text_hex in riscv-tests/hexfiles/text/rv32ui-p*hex\ndo\n data_hex=$(echo $text_hex | sed \"s%/text/\\([^/]*\\)\\.hex$%/data/\\1.data.hex%g\")\n if [[ -f $data_hex ]]; then\n make HEX=$text_hex HEX2=$data_hex\n else\n make HEX=$text_hex\n fi\ndone\n"
},
{
"alpha_fraction": 0.4688524603843689,
"alphanum_fraction": 0.5147541165351868,
"avg_line_length": 24.25,
"blob_id": "b788a2d4c8df4b23c82f3dd12f7dfc97ea508772",
"content_id": "d6bf150ecefb4ea2a6ef42ee7ae8f0643bab6b0b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 305,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 12,
"path": "/vsim/riscv-tests/scripts/dump2hex.py",
"repo_name": "tonmoy18/tamarisc",
"src_encoding": "UTF-8",
"text": "\nimport sys\nimport re\n\nfilename = sys.argv[1]\noffset_addr = sys.argv[2]\n\nwith open(filename) as f:\n for line in f:\n m = re.match('^([0-9A-Fa-f]{8}):\\t([0-9A-Fa-f]{8}).*', line.rstrip())\n if m:\n if int(m.group(1), 16) >= int(offset_addr, 16):\n print(m.group(2))\n\n"
},
{
"alpha_fraction": 0.7910690307617188,
"alphanum_fraction": 0.7989174723625183,
"avg_line_length": 91.375,
"blob_id": "48f42e277fe5ed7d01e198b8b993753330756673",
"content_id": "55696d000d7462bb3ba23e8575f1413cb743fbc6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3695,
"license_type": "permissive",
"max_line_length": 853,
"num_lines": 40,
"path": "/README.md",
"repo_name": "tonmoy18/tamarisc",
"src_encoding": "UTF-8",
"text": "# tamarisc\n\n![Image of Tamarisc Architecture](https://raw.githubusercontent.com/tonmoy18/tamarisc/master/docs/images/architecture.png)\n\nTamarisc is a six stage CPU core implementing the RV32I subset of the [RISCV](https://riscv.org/specifications/) instruction set architecture in machine mode only. The implementation is done using SystemVerilog hardware definition language. The architecture assumes either two separate memory for instruction or data, or the same memory with two different ports for instruction and data. The design implements a simple always un-taken branch predictor. Conflict is resolved by stalling the instruction on the fetch stage until the conflict is resolved. Multiple jump or branch instructions on the pipeline at the same time stalls the later instruction on the fetch stage as well. This implementation has most of the machine mode SYSTEM instructions except for CSR*I and all of the machine mode CSR registers except for the counter related CSR registers.\n\n## Getting started\n\nThe src directory holds the RTL files for the core and should be usable as is. A cycle accurate simulation using [verilator](https://www.veripool.org/wiki/verilator) is used for the development and can be used to run programs converted to verilog friendly hex format. A few tests are taken from riscv-tests repository. These tests are kept in vsim/riscv-tests directory for quick simulation during development.\n\n### Running Simulations\nPrerequisite for running the simulation is to install [verilator](https://www.veripool.org/wiki/verilator). Then to run a particular program run the following commands:\n```bash\ncd vsim\nmake HEX=<im_hexfile> HEX2=<dm_hexfile>\n```\n\nThe simulation will run until the core writes a data to `tohost` memory address, which is currently set to `0x80001000`. If the written value is 1, then the test is considers a \"PASS\". For example, to run the rv32i-p-add test, run the following commands:\n\n```bash\ncd vsim\nmake HEX=riscv-tests/hexfiles/rv32ui-p-add.hex\n```\n\n### Generating Hex file from Assembly\n\nPrerequisite for generation hex from assebmly is to install [riscv-gnu-toolchain](https://github.com/riscv/riscv-gnu-toolchain). Using the toolchain a .S assembly file can be assembled into a ELF file, which can finally be dumped using the readelf command. If the generated output is kept into a file, then the python script in vsim/riscv-tests/scripts/dump2hex.py can be run with the dump file as a command line argument to generate the .hex file for the instruction memory. The .hex file for the data still needs to be hand crafted as the python script does not support conversion of data less than 4 bytes in a single line.\n\n## Architecture Description\n\nThe implementation features a six stage pipeline which consists of the stages: (1) address, (2) fetch, (3) decode, (4) execute, (5) memory, and (6) write back. The regfile has dual read and single write port. The design has separate arithmetic, logic and shift units. Both the arithmetic and the logic units can be active simultaneously on the execute step only for the branch instruction. The current versions of the instruction \"cache\" and data \"cache\" modules are very rudimentary latching the address values until memory busy signals become low. All muxes that select different sources of data reside in the datapath module.\n\n## Future Improvements\n* Implement the remaining CSR registers\n* Implement CSR*I instruction (currently CSRRW, CSRRS and CSRRC are implemented)\n* Implement better instruction and data cache modules\n* Implement more intelligent branch predictor\n* Implement full suite of riscv benchmark tests for RV32MI\n* Fix synthesis related issues\n* Add assertions for formal proof\n"
}
] | 4 |
dfour001/GEOG-575-Lab-2 | https://github.com/dfour001/GEOG-575-Lab-2 | 239908a257da05199490dd6e6a2003a1446a4ccd | 3070e8ec8583426d557f5499170cee769dabbe3e | e013ef0eca816b615de880d051e16acfcbfd3990 | refs/heads/master | 2021-04-09T22:59:16.064805 | 2020-05-14T20:55:02 | 2020-05-14T20:55:02 | 248,889,552 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.49119555950164795,
"alphanum_fraction": 0.5152919292449951,
"avg_line_length": 26.66666603088379,
"blob_id": "602464faafcb4525ad99371f7b461e74ba36d8f3",
"content_id": "5c6a677c9ea383d99a72cbf441bb2bd838e8d0f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1079,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 39,
"path": "/js/selectClassButtons.js",
"repo_name": "dfour001/GEOG-575-Lab-2",
"src_encoding": "UTF-8",
"text": "function set_class_buttons(csvData) {\n // Class color palette\n let colors = {\n 'BA': '#fec424',\n 'BC': '#817b00',\n 'BP': '#fe0000',\n 'BS': '#00859c',\n 'S': '#d2be57',\n 'default': '#989898'\n };\n \n // Class dictionary\n let classDict = {\n 'BA': 'BodyAttack',\n 'BC': 'BodyCombat',\n 'BP': 'BodyPump',\n 'BS': 'BodyStep',\n 'S': 'Sprint'\n }\n\n // Animate button when clicked and change attribute\n $('.button').on('click', function () {\n // Return all buttons to non-active state\n $('.button').removeClass('active');\n $('.button, .button-container').css('color', colors['default']);\n\n\n // Set selected button to active state\n $(this).addClass('active');\n\n // Set text color\n $(this).parent().css('color', 'white');\n $(this).css('color', colors[$(this).attr('data-class')]);\n\n // Change selected attribute\n let attribute = classDict[$(this).attr('data-class')];\n changeAttribute(attribute, csvData);\n })\n}\n"
},
{
"alpha_fraction": 0.5563124418258667,
"alphanum_fraction": 0.5653951168060303,
"avg_line_length": 30.884057998657227,
"blob_id": "1a62fe2ac3bfbd3be6a7ecd10869fd1fb6ecefe9",
"content_id": "901468321abcd4518a538be1fd7ef82ac7c1d22e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2202,
"license_type": "no_license",
"max_line_length": 315,
"num_lines": 69,
"path": "/ParseGymLocationData.py",
"repo_name": "dfour001/GEOG-575-Lab-2",
"src_encoding": "UTF-8",
"text": "import xml.etree.ElementTree as ET\nfrom collections import Counter\n\nfieldList = ['Class', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY']\ninputPath = r'C:\\Users\\danie\\Desktop\\GEOG 575\\GEOG-575-Lab-2\\data'\nfiles = ['AllClasses.txt', 'BodyAttack.txt', 'BodyCombat.txt', 'BodyPump.txt', 'BodyStep.txt', 'Sprint.txt']\noutputPath = r'C:\\Users\\danie\\Desktop\\GEOG 575\\GEOG-575-Lab-2\\data'\noutputFileName = 'classes.csv'\n\ndef get_state_from_address(text):\n input = text.split(\",\")\n cityStateZip = input[-2]\n state = cityStateZip.split(\" \")[-2]\n return state\n\n\ndef get_count(path, filename): \n\n file = open(r'{}\\{}'.format(path, filename), 'r')\n data = file.read()\n file.close()\n\n root = ET.fromstring(data)\n\n states = []\n addressList = [] # To check for duplicate addresses\n\n for li in root:\n for item in li:\n if item.tag == \"address\" and item.text.endswith(\"United States\"):\n address = item.text\n if address not in addressList:\n addressList.append(address)\n state = get_state_from_address(item.text)\n states.append(str.upper(str(state)))\n\n c = Counter(states)\n\n countDict = dict(c)\n print(countDict)\n return countDict\n\n\ndef create_output_line(countDict, filename):\n className = filename.split('.')[0]\n output = className + ','\n countValues = []\n for state in fieldList[1:]:\n if state in countDict.keys():\n curValue = countDict[state]\n output += str(curValue) + ','\n else:\n output += '0,'\n output += '\\n'\n return output\n\noutput = ''\nfor field in fieldList:\n output += field + ','\noutput = output[:-1] + '\\n'\n\nfor file in files:\n countDict = get_count(inputPath, file)\n record = create_output_line(countDict, file)\n output += record\n \n\nwith open('{}\\{}'.format(outputPath, outputFileName), 'w') as file:\n file.write(output)\n\n\n"
},
{
"alpha_fraction": 0.49658992886543274,
"alphanum_fraction": 0.5070332288742065,
"avg_line_length": 32.27659606933594,
"blob_id": "28ea2fa64c52361eb3b0ac37fffb156a0d23a3a7",
"content_id": "1dbf09acd6743627ace62e0b2edd1e72f80131a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 9384,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 282,
"path": "/js/main - Copy.js",
"repo_name": "dfour001/GEOG-575-Lab-2",
"src_encoding": "UTF-8",
"text": "(function () {\n var attrArray = ['AllClasses', 'BodyAttack', 'BodyCombat', 'BodyPump', 'BodyStep', 'Sprint']; // List of attributes\n var expressed = attrArray[0]; // Initial attribute\n\n // Chart frame dimensions\n var chartWidth = window.innerWidth * 0.425,\n chartHeight = 460,\n leftPadding = 28,\n rightPadding = 2,\n chartInnerWidth = chartWidth - leftPadding - rightPadding,\n topBottomPadding = 5,\n chartInnerHeight = chartHeight - topBottomPadding * 2,\n translate = 'translate(' + leftPadding + ',' + topBottomPadding + ')';\n\n\n\n // Create a scale to size bars proportionally to frame\n var yScale = d3.scaleLinear()\n .range([463, 0])\n .domain([0, 500]);\n\n var yAxisScale = d3.scaleLinear()\n .range([chartInnerHeight, 0])\n .domain([0, 500]);\n\n\n // Begin script when window loads\n window.onload = setMap();\n\n\n // Set up choropleth map\n function setMap() {\n // Map frame dimensions\n let width = window.innerWidth * 0.5,\n height = 460;\n\n // Create new svg container for the map\n let map = d3.select('body')\n .append('svg')\n .attr('class', 'map')\n .attr('width', width)\n .attr('height', height);\n\n // Create Albers equal area conic projection centered on United States\n let projection = d3.geoAlbers()\n .center([0, 33.6])\n .rotate([99, 0, 0])\n .parallels([43, 62])\n .scale(705)\n .translate([width / 2, height / 2]);\n\n let path = d3.geoPath()\n .projection(projection);\n\n // Use queue to parrallelize asynchronous data loading\n d3.queue()\n .defer(d3.csv, 'data/ClassesByState.csv')\n .defer(d3.json, 'data/states.topojson')\n .await(callback);\n\n function callback(error, csvData, states) {\n // Set up graticule\n add_graticule(map, path);\n\n\n // Use topojson to translate topojson to geojson\n let dataStates = topojson.feature(states, states.objects.states).features;\n\n // Join topojson with csv data\n dataStates = join_data(dataStates, csvData)\n\n\n let colorScale = make_color_scale(csvData);\n\n let lyrStates = map.selectAll('.states')\n .data(dataStates)\n .enter()\n .append('path')\n .attr('class', function (d) {\n return 'states ' + d.properties.postal;\n })\n .attr('d', path)\n .style('fill', function (d) {\n return colorScale(d.properties[expressed])\n });\n\n // Add coordinated visualization to the map\n setChart(csvData, colorScale);\n\n createDropdown(csvData);\n }\n\n\n function add_graticule(map, path) {\n // Create graticule generator\n let graticule = d3.geoGraticule()\n .step([10, 10]); // Place graticule lines every 5* of lat/lng\n\n // Create graticule lines\n let gatLines = map.selectAll('.gratLines') // Select graticule elements that will be created\n .data(graticule.lines()) // Bind graticule lines to each element to be created\n .enter() // Create an element for each datum\n .append('path') // Append each element to the svg as a path element\n .attr('class', 'gratLines')\n .attr('d', path) // Project graticule lines\n }\n\n\n function join_data(dataStates, csvData) {\n // Join dataStates and csvData by postal code\n\n // Loop through csv to assign each set of csv ttribute values to geojson state\n for (let i = 0; i < csvData.length; i++) {\n let csvState = csvData[i]; // The curent state\n let csvKey = csvState.State; // The CSV primary key\n\n // Loop through geoson states to find correct state\n for (let a = 0; a < dataStates.length; a++) {\n let geojsonProps = dataStates[a].properties; // The current state geojson properties\n let geojsonKey = geojsonProps.postal; // The geojson primary key\n\n // Assign all attributes and values\n if (geojsonKey == csvKey) {\n attrArray.forEach(function (attr) {\n let val = parseFloat(csvState[attr]); // Get csv attribute value\n geojsonProps[attr] = val; // Assign attribute and value to geojson properties\n });\n };\n };\n };\n\n return dataStates\n }\n\n\n }\n\n function make_color_scale(data) {\n let colorClasses = [\n \"#D4B9DA\",\n \"#C994C7\",\n \"#DF65B0\",\n \"#DD1C77\",\n \"#980043\"\n ];\n\n // Create color scale generator\n let colorScale = d3.scaleQuantile()\n .range(colorClasses);\n\n // Build array of all values of the expressed attribute\n let domainArray = [];\n for (let i = 0; i < data.length; i++) {\n let val = parseFloat(data[i][expressed]);\n domainArray.push(val);\n }\n\n // Assign array of epxressed values as scale domain\n colorScale.domain(domainArray);\n\n return colorScale\n }\n\n function setChart(csvData, colorScale) {\n // Create a second svg element to hold the bar chart\n var chart = d3.select('body')\n .append('svg')\n .attr('width', chartWidth)\n .attr('height', chartHeight)\n .attr('class', 'chart');\n\n // Set bars for each state\n var bars = chart.selectAll('.bars')\n .data(csvData)\n .enter()\n .append('rect')\n .sort(function (a, b) {\n return b[expressed] - a[expressed]\n })\n .attr('class', function (d) {\n return 'bars ' + d.postal;\n })\n .attr('width', chartInnerWidth / csvData.length - 1)\n .attr('x', function (d, i) {\n return i * (chartInnerWidth / csvData.length);\n })\n .attr('height', function (d) {\n return yScale(parseFloat(d[expressed]));\n })\n .attr('y', function (d) {\n return yScale(parseFloat(d[expressed])) + topBottomPadding;\n })\n .style('fill', function (d) {\n return colorScale(d[expressed])\n })\n .attr('transform', translate);\n\n //create vertical axis generator\n var yAxis = d3.axisLeft()\n .scale(yAxisScale)\n\n //place axis\n var axis = chart.append(\"g\")\n .attr(\"class\", \"axis\")\n .attr(\"transform\", translate)\n .call(yAxis);\n\n // Chart title\n var chartTitle = chart.append('text')\n .attr('x', 20)\n .attr('y', 40)\n .attr('class', 'chartTitle')\n .text('Number of Variable ' + expressed + ' in each state');\n }\n\n function createDropdown(csvData) {\n let dropdown = d3.select('body')\n .append('select')\n .attr('class', 'dropdown')\n .on('change', function () {\n changeAttribute(this.value, csvData)\n });\n\n //add initial option\n let titleOption = dropdown.append('option')\n .attr('class', 'titleOption')\n .attr('disabled', 'true')\n .text('Select Attribute');\n\n // Add attribute name options\n let attrOptions = dropdown.selectAll('attrOptions')\n .data(attrArray)\n .enter()\n .append('option')\n .attr('value', function (d) {\n return d\n })\n .text(function (d) {\n return d\n });\n }\n\n // Called when new attribute is selected\n function changeAttribute(attribute, csvData) {\n expressed = attribute;\n\n var colorScale = make_color_scale(csvData)\n\n var states = d3.selectAll('.states')\n .transition()\n .duration(500)\n .style('fill', function (d) {\n return colorScale(d.properties[expressed])\n });\n\n // Re-sort, resize, and recolor bars\n var bars = d3.selectAll('.bars')\n //re-sort bars\n .sort(function (a, b) {\n return b[expressed] - a[expressed];\n })\n .transition()\n .attr('x', function (d, i) {\n return i * (chartInnerWidth / csvData.length);\n })\n .attr('height', function (d) {\n return yScale(parseFloat(d[expressed]));\n })\n .attr('y', function (d) {\n return chartHeight - yScale(parseFloat(d[expressed])) + topBottomPadding;\n })\n .style('fill', function (d) {\n return colorScale(d[expressed])\n });\n \n // Update chart title \n var chartTitle = d3.select('.chartTitle')\n .text('Number of Variable ' + expressed + ' in each state');\n \n console.log(expressed);\n }\n})();\n"
},
{
"alpha_fraction": 0.7764227390289307,
"alphanum_fraction": 0.7967479825019836,
"avg_line_length": 81,
"blob_id": "f0ad86b6aab427e6394bf5fcb709d415d2bd9203",
"content_id": "bdb79a1f4035304aeae4334a4e3d795d3a333562",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 246,
"license_type": "no_license",
"max_line_length": 227,
"num_lines": 3,
"path": "/README.md",
"repo_name": "dfour001/GEOG-575-Lab-2",
"src_encoding": "UTF-8",
"text": "# GEOG575: Lab-2\n\nThis lab uses D3 to display a coordinated data visualization between a choropleth map and a bar chart. The data visualized is the number of gyms offering various Les Mills classes per million residents of each state in the US.\n"
}
] | 4 |
hhslepicka/travistest | https://github.com/hhslepicka/travistest | 883fc82df82d6d6f8450e8db3892b75ab284151c | a2e0a41a483ea62b016521ff8c91b802cf45c054 | 1dd71176ea8a3083008dbb1db0b11c0bc77a6993 | refs/heads/master | 2016-06-06T12:57:18.846504 | 2015-10-30T02:30:20 | 2015-10-30T02:30:20 | 45,220,147 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5764331221580505,
"alphanum_fraction": 0.5764331221580505,
"avg_line_length": 18.6875,
"blob_id": "64dec7ec9ce43bc7751e1da0e181804e81bb4695",
"content_id": "eb45682da062559c953f1cfcf48330bd5c565455",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 314,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 16,
"path": "/travistest/test/test_package.py",
"repo_name": "hhslepicka/travistest",
"src_encoding": "UTF-8",
"text": "from nose.tools import assert_true\n\n\ndef test_import():\n ret = False\n try:\n import travistest\n ret = True\n except ImportError as e:\n print(\"Error: \", e.msg)\n\n assert_true(ret)\n\nif __name__ == \"__main__\":\n import nose\n nose.runmodule(argv=['-s', '--with-doctest'], exit=False)"
},
{
"alpha_fraction": 0.6527196764945984,
"alphanum_fraction": 0.6582984924316406,
"avg_line_length": 25.592592239379883,
"blob_id": "bc39a4e3a058780d771403034d2472a36e054f2a",
"content_id": "9b62328751e4fa648450f69ddbc5b8ae611f3768",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 717,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 27,
"path": "/setup.py",
"repo_name": "hhslepicka/travistest",
"src_encoding": "UTF-8",
"text": "from __future__ import (absolute_import, division, print_function)\nimport versioneer\n\ntry:\n from setuptools import setup\nexcept ImportError:\n try:\n from setuptools.core import setup\n except ImportError:\n from distutils.core import setup\n\nsetup(\n name='travistest',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n author='hhslepicka',\n author_email=None,\n license=\"BSD (3-clause)\",\n url=\"https://github.com/hhslepicka/travistest\",\n packages=['travistest', 'travistest.test'],\n package_data={},\n install_requires=['nose'],\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Programming Language :: Python :: 3.4\",\n ],\n)"
},
{
"alpha_fraction": 0.6529850959777832,
"alphanum_fraction": 0.6529850959777832,
"avg_line_length": 23.454545974731445,
"blob_id": "76f2a83007273007d748ef0e3838a151deb99191",
"content_id": "ac4a9cbb6e2191af3b7a1682c0686fedf76407fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 11,
"path": "/travistest/test/test_function.py",
"repo_name": "hhslepicka/travistest",
"src_encoding": "UTF-8",
"text": "import travistest.utils as ttu\nfrom nose.tools import assert_equal\n\n\ndef test_simple_function():\n ret = ttu.simple_function(\"abc\")\n assert_equal(\"abc\", ret)\n\nif __name__ == \"__main__\":\n import nose\n nose.runmodule(argv=['-s', '--with-doctest'], exit=False)"
},
{
"alpha_fraction": 0.6276595592498779,
"alphanum_fraction": 0.6276595592498779,
"avg_line_length": 17.899999618530273,
"blob_id": "837df7f26b9c0c30111e6d3bb66c4f42f1df5ee0",
"content_id": "f769b10ad2d1febda0da467b0039e29070a9b5ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 188,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 10,
"path": "/travistest/utils.py",
"repo_name": "hhslepicka/travistest",
"src_encoding": "UTF-8",
"text": "__author__ = 'hugoslepicka'\n\nimport numpy\n\ndef simple_function(val):\n \"\"\" Returns the same object in the parameter.\n :param val: `object`\n :return: `object`\n \"\"\"\n return val"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 27,
"blob_id": "99d7f72ae3b252c3cd3a311108b06ace506b1145",
"content_id": "98b02a67b5a2b3faeb5af93dafa347d7fc0439d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 28,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 1,
"path": "/travistest/test/__init__.py",
"repo_name": "hhslepicka/travistest",
"src_encoding": "UTF-8",
"text": "__author__ = 'hugoslepicka'\n"
}
] | 5 |
rmusser01/pynessus | https://github.com/rmusser01/pynessus | a406758576ddbd3b0547cfd6c331dfe107f41f72 | 3daf7dbceb899f9ee6c290103df6eec1ab996def | 9cdf38da8589e88f6c673c2fcf77f300cda043b1 | refs/heads/master | 2021-01-22T01:38:22.109922 | 2014-07-28T08:15:16 | 2014-07-28T08:15:16 | 35,648,842 | 1 | 0 | null | 2015-05-15T02:30:19 | 2015-05-15T02:30:15 | 2014-07-28T08:15:16 | null | [
{
"alpha_fraction": 0.6729775071144104,
"alphanum_fraction": 0.6769191026687622,
"avg_line_length": 32.42548751831055,
"blob_id": "8f5bce96da3815d86d4ef8b80f220434f06a5fae",
"content_id": "d7eb3a3c435ad899a03626552a492547782c901f",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15476,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 463,
"path": "/pynessus/nessus.py",
"repo_name": "rmusser01/pynessus",
"src_encoding": "UTF-8",
"text": "\"\"\"Library to talk with a remote Nessus 5 server that via its xmlrpc interface,\n\nMethods mirror what is in the official API at\nhttp://static.tenable.com/documentation/nessus_5.0_XMLRPC_protocol_guide.pdf\n\nExample usage:\n with Nessus('127.0.0.1:8443') as nes:\n nes.Login('admin', 'pass$%&(#'%#[]@:')\n logging.info('Feeds: %s', nes.Feed())\n\nAll calls can be done asynchronously:\n\n with Nessus('127.0.0.1:8443') as nes:\n def LoginCallback(result, error=None):\n if error:\n logging.warning('Error while logging: %s', error)\n return\n logging.info('Correcty logged in: %s', result)\n\n future = nes.Login('admin', 'pass$%&(#'%#[]@:', callback=LoginCallback)\n futures.wait([future])\n # At this point the LoginCallback is sure to have been called.\n\"\"\"\n\nfrom concurrent import futures\nfrom urllib import request\nimport functools\nimport json\nimport logging\nimport os\nimport random\nimport urllib\n\n_MAX_SEQ = 2 ** 31 - 1\n\n\nclass NessusError(Exception):\n pass\n\n\ndef FutureCallback(fn):\n @functools.wraps(fn)\n def wrapper(callback, future):\n if not future.done():\n raise NessusError('Future callback called before the future was finished.')\n try:\n contents = future.result()\n except (\n futures.CancelledError,\n futures.TimeoutError,\n Exception) as e:\n if callback:\n callback(None, error=NessusError(e))\n return\n else:\n raise NessusError(e)\n return fn(callback, contents)\n return wrapper\n\ndef SelfFutureCallback(fn):\n @functools.wraps(fn)\n def wrapper(self, callback, future):\n if not future.done():\n raise NessusError('Future callback called before the future was finished.')\n try:\n contents = future.result()\n except (\n futures.CancelledError,\n futures.TimeoutError,\n Exception) as e:\n raise NessusError(e)\n return fn(self, callback, contents)\n return wrapper\n\n\nclass Nessus(object):\n \"\"\"Class to communicate with the remote nessus 5 instance.\n All methods support both synchronous and asynchronous calls.\n If synchronous calls are made, the returned values are the values from Nessus.\n If asynchronous cals are made, the returned value is a future that should be\n waited for using futures.wait([returned_future]) and the callback passed to\n the functions all have the same parameters:\n def Callback(result, error=None):\n pass\n If an error happened during the future execution, then result will be None\n and error will be an Exception (most likely a NessusError instance).\n \"\"\"\n\n def __init__(self, host, executor=None, dump_path=None):\n \"\"\"Initializes the Nessus instance.\n Does not connect on creation, this is a dumb constructor only,\n to connect call Login(...).\n\n Args:\n host: The host:port to connect to.\n executor: A concurrent.futures.Executor to use, if left unspecified a default\n ThreadPoolExecutor will be used with 5 parallel workers.\n dump_path: If specified all responses from nessus will be dumped to this\n path.\n \"\"\"\n self._host = host\n self._session_token = None\n self._executor = executor or futures.ThreadPoolExecutor(max_workers=5)\n self._dump_path = dump_path\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Exits a with: statement, automatically log out of nessus if connected.\"\"\"\n if self._session_token:\n self.Logout()\n\n def _BuildRequest(self, path, data=None):\n request = urllib.request.Request(self._host + path + '?json=1')\n request.add_header('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')\n request.add_header('Accept', 'application/json')\n if data:\n data = urllib.parse.urlencode(data)\n data = data.encode('utf-8')\n request.data = data\n if self._session_token:\n # We are getting the header from nessus, so we should be fine against\n # header splitting attacks.\n request.add_header('Cookie', 'token=%s' % self._session_token)\n return request\n\n @staticmethod\n def _SendRequest(request, dump_path=None):\n logging.debug('Sending request to %s with data %s',\n request.get_full_url(), request.data)\n resp = urllib.request.urlopen(request)\n url_info = resp.info()\n encoding = url_info.get('Content-Encoding', 'utf-8')\n raw_json = resp.read().decode(encoding)\n logging.debug('urlopen returned \\n%s\\n', raw_json)\n if dump_path:\n with open(os.path.join(\n dump_path,\n request.selector[1:request.selector.find('?')].replace('/', '_') + '.json'),\n 'w') as dump:\n dump.write(raw_json)\n json_resp = json.loads(raw_json)['reply']\n status = json_resp.get('status', '')\n if status != 'OK':\n raise NessusError('Status was not OK: %s: %s' % (status, json_resp['contents']))\n if 'contents' not in json_resp:\n return ''\n return json_resp['contents']\n\n @staticmethod\n def _SendRawRequest(request, dump_path=None):\n logging.debug('Sending request to %s with data %s',\n request.get_full_url(), request.data)\n resp = urllib.request.urlopen(request)\n url_info = resp.info()\n encoding = url_info.get('Content-Encoding', 'utf-8')\n decoded_raw = resp.read().decode(encoding)\n logging.debug('urlopen returned \\n%s\\n', decoded_raw)\n if dump_path:\n with open(os.path.join(\n dump_path,\n request.selector[1:request.selector.find('?')].replace('/', '_') + '.raw'),\n 'w') as dump:\n dump.write(decoded_raw)\n return decoded_raw\n\n def Login(self, login, password, callback=None):\n data = {\n 'login': login,\n 'password': password,\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/login', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._LoginDone)\n\n def _ProcessFutureCallback(self, future, user_callback, self_callback):\n if user_callback:\n future.add_done_callback(functools.partial(self_callback, user_callback))\n return future\n else:\n futures.wait([future])\n return self_callback(user_callback, future)\n\n @SelfFutureCallback\n def _LoginDone(self, callback, contents):\n self._session_token = contents['token']\n logging.debug('Token is %s', self._session_token)\n if callback:\n callback('Successully connected to Nessus')\n\n @staticmethod\n @FutureCallback\n def _SimpleReturnCB(callback, result):\n if callback:\n callback(result)\n else:\n return result\n\n def Logout(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/logout', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._LogoutDone)\n\n @SelfFutureCallback\n def _LogoutDone(self, callback, content):\n self._session_token = None\n if callback:\n callback('Logout from Nessus successful')\n \n @property\n def is_logged_in(self):\n return self._session_token is not None\n\n def Feed(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/feed', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._SimpleReturnCB)\n\n def ListServerSettings(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/server/securesettings/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListServerSettingsDone)\n\n @staticmethod\n @FutureCallback\n def _ListServerSettingsDone(callback, contents):\n settings = contents.get('securesettings')\n if callback:\n callback(settings)\n else:\n return settings\n\n def PluginsDescriptions(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/plugins/descriptions', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._SimpleReturnCB)\n \n def ListPreferences(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/server/preferences/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListPreferencesDone)\n\n @staticmethod\n @FutureCallback\n def _ListPreferencesDone(callback, contents):\n return {\n pref['name']: pref['value'] for pref in contents[\n 'serverpreferences']['preference']}\n\n def ServerLoad(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/server/load', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ServerLoadDone)\n\n @staticmethod\n @FutureCallback\n def _ServerLoadDone(callback, contents):\n return contents['load'], contents['platform']\n\n def ServerUUID(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/uuid', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ServerUUIDDone)\n\n @staticmethod\n @FutureCallback\n def _ServerUUIDDone(callback, contents):\n return contents['uuid']\n\n def ServerCert(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/getcert', data)\n future = self._executor.submit(self._SendRawRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ServerCertDone)\n\n @staticmethod\n @FutureCallback\n def _ServerCertDone(callback, contents):\n return contents\n\n def ListPlugins(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/plugins/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListPluginsDone)\n\n @staticmethod\n @FutureCallback\n def _ListPluginsDone(callback, contents):\n return {\n family['familyname']: int(family['numfamilymembers'])\n for family in contents['pluginfamilylist']['family']}\n\n def ListPluginsAttributes(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/plugins/attributes/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListPluginsAttributesDone)\n\n @staticmethod\n @FutureCallback\n def _ListPluginsAttributesDone(callback, contents):\n return contents['pluginsattributes']['attribute']\n\n def ListPluginsInFamily(self, family, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'family': family,\n }\n request = self._BuildRequest('/plugins/list/family', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListPluginsInFamilyDone)\n\n @staticmethod\n @FutureCallback\n def _ListPluginsInFamilyDone(callback, contents):\n if contents['pluginlist']:\n return contents['pluginlist']['plugin']\n return []\n\n def AddUser(self, login, password, admin=False, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'login': login,\n 'password': password,\n 'admin': 1 if admin else 0,\n }\n request = self._BuildRequest('/users/add', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._AddUserDone)\n\n @staticmethod\n @FutureCallback\n def _AddUserDone(callback, contents):\n return contents['user']\n\n def DeleteUser(self, login, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'login': login,\n }\n request = self._BuildRequest('/users/delete', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._DeleteUserDone)\n\n @staticmethod\n @FutureCallback\n def _DeleteUserDone(callback, contents):\n return contents['user']['name']\n\n def EditUser(self, login, password, admin=False, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'login': login,\n 'password': password,\n 'admin': 1 if admin else 0,\n }\n request = self._BuildRequest('/users/edit', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._EditUserDone)\n\n @staticmethod\n @FutureCallback\n def _EditUserDone(callback, contents):\n return contents['user']\n\n def ListPolicies(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/policy/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListPoliciesDone)\n\n @staticmethod\n @FutureCallback\n def _ListPoliciesDone(callback, contents):\n return contents['policies']\n\n def NewScan(self, targets, policy_id, scan_name, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'target': ','.join(targets),\n 'policy_id': policy_id,\n 'scan_name': scan_name,\n }\n request = self._BuildRequest('/scan/new', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._NewScanDone)\n\n @staticmethod\n @FutureCallback\n def _NewScanDone(callback, contents):\n return contents['scan']\n\n def ListReports(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/report/list', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ListReportsDone)\n\n @staticmethod\n @FutureCallback\n def _ListReportsDone(callback, contents):\n return contents['reports']\n\n def GetReport(self, uuid, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n 'report': uuid,\n }\n request = self._BuildRequest('/file/report/download', data)\n future = self._executor.submit(self._SendRawRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._GetReportDone)\n\n @staticmethod\n @FutureCallback\n def _GetReportDone(callback, contents):\n return contents\n\n def ServerUpdate(self, callback=None):\n data = {\n 'seq': random.randint(1, _MAX_SEQ),\n }\n request = self._BuildRequest('/server/update', data)\n future = self._executor.submit(self._SendRequest, request, self._dump_path)\n return self._ProcessFutureCallback(future, callback, self._ServerUpdateDone)\n\n @staticmethod\n @FutureCallback\n def _ServerUpdateDone(callback, contents):\n return contents\n"
},
{
"alpha_fraction": 0.6630923748016357,
"alphanum_fraction": 0.6764628291130066,
"avg_line_length": 35.84878158569336,
"blob_id": "3f40da94ac02007ef355579f1f9ddb155f15bc9e",
"content_id": "d5cbfb119204d7664112ba48254dbca255e3b157",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7554,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 205,
"path": "/pynessus/test/test_nessus.py",
"repo_name": "rmusser01/pynessus",
"src_encoding": "UTF-8",
"text": "from concurrent import futures\nfrom unittest import mock\nfrom urllib import response\nimport io\nimport json\nimport logging\nimport os\nimport unittest\nimport urllib\n\nfrom pynessus import nessus\n\[email protected](urllib.request, 'urlopen')\nclass TestNessus(unittest.TestCase):\n\n def setUp(self):\n self._nessus = nessus.Nessus('hostname:port')\n\n @staticmethod\n def _GetResp(data, status_code=200):\n return response.addinfourl(\n io.BytesIO(data.encode('utf-8')),\n {'Content-Encoding': 'utf-8'},\n '',\n status_code)\n\n @staticmethod\n def _ExpectResponseFromFile(filename, status_code=200):\n with open(os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n 'testdata',\n filename + '.json')) as f:\n return response.addinfourl(\n io.BytesIO(f.read().encode('utf-8')),\n {'Content-Encoding': 'utf-8'},\n '',\n status_code)\n\n def test_login(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('login_ok')\n self._nessus.Login('test', 'pass')\n self.assertTrue(self._nessus.is_logged_in)\n\n def test_login_async(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('login_ok')\n callback = mock.Mock(return_value=None)\n future = self._nessus.Login('test', 'pass', callback)\n futures.wait([future])\n self.assertTrue(self._nessus.is_logged_in)\n self.assertTrue(future.done())\n callback.assert_called_once_with(mock.ANY)\n\n def test_invalid_login(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('invalid_login')\n self.assertRaises(\n nessus.NessusError,\n self._nessus.Login, 'test', 'wrongpass')\n self.assertFalse(self._nessus.is_logged_in)\n\n def test_login_raises(self, mock_urlopen):\n mock_urlopen.side_effect = Exception('something went wrong')\n self.assertRaises(\n nessus.NessusError,\n self._nessus.Login, 'test', 'wrongpass')\n self.assertFalse(self._nessus.is_logged_in)\n\n def test_with_logout(self, mock_urlopen):\n mock_urlopen.side_effect = [\n self._ExpectResponseFromFile('login_ok'),\n self._ExpectResponseFromFile('logout_ok')]\n with nessus.Nessus('host:port') as nes:\n nes.Login('user', 'pass')\n self.assertEqual(2, mock_urlopen.call_count)\n\n def test_list_serversettings(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile(\n 'server_securesettings_list_ok')\n settings = self._nessus.ListServerSettings()\n self.assertEqual({\n 'proxysettings': {\n 'custom_host': None,\n 'proxy': None,\n 'proxy_password': None,\n 'proxy_port': None,\n 'proxy_username': None,\n 'user_agent': None\n }\n }, settings)\n\n def test_feed(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('feed_ok')\n feed = self._nessus.Feed()\n self.assertEqual({\n 'diff': 'on',\n 'expiration': '1548009584',\n 'expiration_time': '1814',\n 'feed': 'HomeFeed',\n 'loaded_plugin_set': '201401211115',\n 'msp': 'FALSE',\n 'nessus_type': 'Nessus Home',\n 'nessus_ui_version': '2.1.0',\n 'plugin_rules': 'on',\n 'report_email': 'on',\n 'server_version': '5.2.5',\n 'tags': 'on',\n 'web_server_version': '5.0.0 (Build H20130829A)',\n }, feed)\n\n def test_list_server_preferences(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile(\n 'server_preferences_ok')\n preferences = self._nessus.ListPreferences()\n self.assertEqual(41, len(preferences), preferences)\n\n def test_server_load(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('server_load_ok')\n load, platform = self._nessus.ServerLoad()\n self.assertEqual('WINDOWS', platform)\n self.assertEqual(5, len(load), load)\n\n def test_server_uid(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('server_uuid_ok')\n uuid = self._nessus.ServerUUID()\n self.assertEqual(\"90936cf4-e94d-833c-c5d6-b50d941a2fb86bfbd6059081a72c\", uuid)\n\n def test_server_cert(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('server_cert')\n cert = self._nessus.ServerCert()\n self.assertTrue('CERTIFICATE' in cert, cert)\n\n def test_list_plugins(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('list_plugins_ok')\n plugins = self._nessus.ListPlugins()\n self.assertEqual(47, len(plugins), plugins)\n\n def test_list_plugins_attributes(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile(\n 'plugins_attributes_list')\n plugins = self._nessus.ListPluginsAttributes()\n self.assertEqual(37, len(plugins), plugins)\n\n def test_list_plugins_in_family(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile(\n 'plugins_list_family_general')\n plugins = self._nessus.ListPluginsInFamily('General')\n self.assertEqual(164, len(plugins), plugins)\n\n def test_list_plugins_in_familly_async_fails(self, mock_urlopen):\n mock_urlopen.side_effect = Exception('something went wrong')\n callback = mock.Mock(return_value=None)\n future = self._nessus.ListPluginsInFamily('General', callback)\n futures.wait([future])\n self.assertTrue(future.done())\n callback.assert_called_once_with(None, error=mock.ANY)\n\n def test_list_plugins_in_family_wrong_family(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile(\n 'plugins_list_family_null')\n plugins = self._nessus.ListPluginsInFamily('I am not a valid family')\n self.assertEqual([], plugins)\n\n def test_add_user(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('users_add')\n user = self._nessus.AddUser('username', 'pass', True)\n self.assertTrue('admin' in user)\n self.assertTrue('name' in user)\n\n def test_delete_user(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('users_delete')\n user = self._nessus.DeleteUser('username')\n self.assertTrue('username' in user, user)\n\n def test_edit_user(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('users_edit')\n user = self._nessus.EditUser('username', 'newpass', True)\n self.assertEqual('username', user['name'], user)\n self.assertFalse('newpass' in user, user)\n self.assertTrue('admin' in user, user)\n\n def test_list_policies(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('policy_list')\n policies = self._nessus.ListPolicies()\n self.assertEqual(1, len(policies), policies)\n\n def test_new_scan(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('scan_new')\n scan = self._nessus.NewScan(['target1', 'target2'], '42', 'scan name')\n self.assertTrue('uuid' in scan, scan)\n\n def test_list_reports(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('report_list')\n reports = self._nessus.ListReports()\n self.assertTrue('report' in reports)\n\n def test_get_report(self, mock_urlopen):\n mock_urlopen.return_value = self._ExpectResponseFromFile('file_report_download')\n self.assertTrue(self._nessus.GetReport(uuid='some uuid'))\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n level=logging.ERROR,\n format='[%(levelname)s] (%(threadName)-10s) %(message)s',\n )\n unittest.main()\n"
},
{
"alpha_fraction": 0.5670454502105713,
"alphanum_fraction": 0.5738636255264282,
"avg_line_length": 24.14285659790039,
"blob_id": "04000f4c562e672d7f702c78a68a65037d2724b3",
"content_id": "29766f3d5df1d0f10a9e9e7db62d8627ff735a22",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 880,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 35,
"path": "/setup.py",
"repo_name": "rmusser01/pynessus",
"src_encoding": "UTF-8",
"text": "try:\n from setuptools import setup\n test_extras = {\n 'test_suite': 'pynessus.test',\n }\nexcept ImportError:\n from distutils.core import setup\n test_extras = {}\n\n\nsetup(\n name='pynessus',\n version='0.9.1',\n author='attwad',\n author_email='[email protected]',\n description=(\n 'Library to talk to a remote Nessus 5 server that via its xmlrpc '\n 'interface.'),\n long_description=open('README.rst').read(),\n url='https://github.com/attwad/pynessus',\n platforms='any',\n packages=[\n 'pynessus',\n 'pynessus.test',\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 3',\n 'Topic :: Security',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: System :: Networking',\n ],\n **test_extras\n)\n"
},
{
"alpha_fraction": 0.6516854166984558,
"alphanum_fraction": 0.6689138412475586,
"avg_line_length": 27.404254913330078,
"blob_id": "1d83b10b73b1d7d63b167a967a433747c6449eab",
"content_id": "e2b623b78ea1e08185817c85fea1ea5e98379fde",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1335,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 47,
"path": "/README.rst",
"repo_name": "rmusser01/pynessus",
"src_encoding": "UTF-8",
"text": "========\npynessus\n========\n\nClient for the xml rpc interface of the Nessus vulnerability scanner v5+.\n\nMethods mirror what is in the official API at\nhttp://static.tenable.com/documentation/nessus_5.0_XMLRPC_protocol_guide.pdf\nin a pythonic way so that you don't have to care about json or xml.\n\n.. image:: https://travis-ci.org/attwad/pynessus.svg?branch=master\n :target: https://travis-ci.org/attwad/pynessus\n\nOngoing work\n------------\nFeatures are being added, not all the API is mapped yet.\nAs all the api calls kind of look the same, it is braindead work so pull\nrequests are more than welcome.\n\nExample usage\n-------------\n\n.. code-block:: python\n\n with Nessus('127.0.0.1:8443') as nes:\n nes.Login('admin', 'pass$%&(#'%#[]@:')\n logging.info('Feeds: %s', nes.Feed())\n\nAll calls can also be done asynchronously if needed:\n\n.. code-block:: python\n\n with Nessus('127.0.0.1:8443') as nes:\n def LoginCallback(result, error=None):\n if error:\n logging.warning('Error while logging: %s', error)\n return\n logging.info('Correcty logged in: %s', result)\n\n future = nes.Login('admin', 'pass$%&(#\\'%#[]@:', callback=LoginCallback)\n futures.wait([future])\n # At this point the LoginCallback is sure to have been called.\n\nLicense\n-------\n\nUnlicensed, do what you want. (http://unlicense.org/)\n"
}
] | 4 |
Rediskas/rozklad1 | https://github.com/Rediskas/rozklad1 | 1d40c037ef5ba46ca31812dff280adb55d853edc | 3f4fa8044e394f5cd684423cdff29df26872a234 | a6cf6ed5a6c9c584b5e1e609021103c889d708bd | refs/heads/master | 2020-09-07T04:20:07.822521 | 2019-11-09T14:27:46 | 2019-11-09T14:27:46 | 220,653,520 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6802816987037659,
"alphanum_fraction": 0.7154929637908936,
"avg_line_length": 43.40625,
"blob_id": "0242c32a437bc18c66c49c68c6bae006cf995366",
"content_id": "bd7851ac05bea4293e3829c164859da155a59b57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1769,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 32,
"path": "/rozklad1.py",
"repo_name": "Rediskas/rozklad1",
"src_encoding": "UTF-8",
"text": "import telebot\n\nbot = telebot.TeleBot('767651930:AAFFQ13qaZuN7SoRKcUGVZ5bPImCWVGIPKs')\nkeyboard1 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)\nkeyboard1.row('Понеділок', 'Вівторок', 'Середа','Четвер',\"П'ятниця\")\n\[email protected]_handler(commands=['start'])\ndef start_message(message):\n if message.text == '/start':\n bot.send_message(message.chat.id, 'Бота створив:\\nInstagram:@denysdovg\\nTelegram:@denysdovg', reply_markup=keyboard1)\n\[email protected]_handler(content_types=['text'])\ndef send_text(message):\n if message.text.lower() == 'понеділок':\n bot.send_message(message.chat.id, '1.Фіз-ра\\n2.Укр.мова\\n3.Інформатика\\n4.Зарубіжна\\n5.Укр.літ\\n6.Англійська\\n7.Мистецтво')\n \n elif message.text.lower() == 'вівторок':\n bot.send_message(message.chat.id, \"1.Німецька\\n2.Фіз-ра\\n3.Укр.мова\\n4.Геометрія\\n5.Укр.літ\\n6.Англійська\\n7.Основи Здоров'я\")\n \n elif message.text.lower() == 'середа':\n bot.send_message(message.chat.id,\n'1.Анлійська\\n2.Історія\\n3.Німецька\\n4.Інформатика\\n5.Правознавство\\n6.Алгебра\\n7.Фіз-ра')\n \n elif message.text.lower() == 'четвер':\n bot.send_message(message.chat.id,\n'1.Геометрія\\n2.Біологія\\n3.Укр.літ\\n4.Фізика\\n5.Хімія\\n6.Георафія') \n \n elif message.text.lower() == \"п'ятниця\":\n bot.send_message(message.chat.id,\n'1.Історія\\n2.Агебра\\n3.Фізика\\n4.Географія\\n5.Зарубіжка\\n6.Хімія\\n7.Трудове')\n\nbot.polling(none_stop=True)"
}
] | 1 |
code-she/python-problems | https://github.com/code-she/python-problems | 4a5357b121af8929e4ebe4135a8f5e06f4af0f56 | 2ae92a60f6a42671b00f03448e587c77c393e0c0 | 5ef5182accbd00fa2928dea2b63d07735c857cd3 | refs/heads/main | 2023-06-23T12:51:11.149405 | 2021-07-13T23:22:52 | 2021-07-13T23:22:52 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6133333444595337,
"alphanum_fraction": 0.6299999952316284,
"avg_line_length": 31.33333396911621,
"blob_id": "ef744c39487ff3f1ab08cd8a1dac5f254235aa3e",
"content_id": "efdcd60b3bb5433598a38caea3774c4000c3b3bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 300,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 9,
"path": "/problem7.py",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "#The included code stub will read an integer,n , from STDIN.\r\n#Without using any string methods, try to print the following: 1,2,3,..n\r\n#Note that \"...\" represents the consecutive values in between.\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n\r\nfor i in range(1,n+1):\r\n print (i,end='')\r\n"
},
{
"alpha_fraction": 0.6684350371360779,
"alphanum_fraction": 0.6684350371360779,
"avg_line_length": 60.83333206176758,
"blob_id": "e2ea0eaba003c73c0d5dfc991506899f138fae94",
"content_id": "10ea051e42d40d000f91dc6338afcd1c61853b1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 377,
"license_type": "no_license",
"max_line_length": 270,
"num_lines": 6,
"path": "/problem4.py",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "#The provided code stub reads two integers, a and b , from STDIN.Add logic to print two lines. The first line should contain the result of integer division, a//b . The second line should contain the result of float division,a /b.No rounding or formatting is necessary.\r\nif __name__ == '__main__':\r\n a = int(input())\r\n b = int(input())\r\n print(a//b)\r\n print(a/b)\r\n"
},
{
"alpha_fraction": 0.7368420958518982,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 34,
"blob_id": "a838df1533a5b135107e1dd4d99761798f88ea4b",
"content_id": "4530a19eba23481431b422c60a175469775e03c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 2,
"path": "/README.md",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "# github-upload\r\nJust a repository for the python questions i'll solve\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6478873491287231,
"alphanum_fraction": 0.7007042169570923,
"avg_line_length": 28.947368621826172,
"blob_id": "dadb7ca9edccf474d6a2f47a5f5680464b599d83",
"content_id": "d6db22036053498c60730f82241140b5ad6809da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 568,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 19,
"path": "/problem8.py",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "#Given two integer numbers return their product. If the product is greater than 1000, then return their sum\n\ndef multiplication_or_sum(num1, num2):\n # calculate product of two number\n product = num1 * num2\n # check if product is less then 1000\n if product <= 1000:\n return product\n else:\n # product is greater than 1000 calculate sum\n return num1 + num2\n\n# first condition\nresult = multiplication_or_sum(20, 30)\nprint(\"The result is\", result)\n\n# Second condition\nresult = multiplication_or_sum(40, 30)\nprint(\"The result is\", result)"
},
{
"alpha_fraction": 0.6563706398010254,
"alphanum_fraction": 0.6833977103233337,
"avg_line_length": 49.400001525878906,
"blob_id": "398071f58598c5453df7698bc0c21e9b05d44c1a",
"content_id": "e5027145cdee5d308c70bc431613124d076c2f54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 777,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 15,
"path": "/problem 5.py",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "#The provided code stub reads and integer, , from STDIN. For all non-negative integers i<n, print i^2 .\r\n #The range() function\r\n\r\n#The range function is a built in function that returns a series of numbers. At a minimum, it needs one integer parameter.\r\n\r\n#Given one parameter,n , it returns integer values from 0 to n-1 . For example, range(5) returns the numbers 0 through 4 in sequence.\r\n#Finally, you can add an increment value as the third argument. For example, range(5, -1, -1) produces the descending sequence from 5 through 0 and range(0, 5, 2) produces 0,2 ,4\r\n #. If you are going to provide a step value, you must also include a start value.\r\n\r\n if __name__ == '__main__':\r\n n = int(input())\r\n n<=1 and n>=20\r\n\r\nfor i in range(0,n):\r\n print(i*i)\r\n \r\n"
},
{
"alpha_fraction": 0.5169082283973694,
"alphanum_fraction": 0.5410627722740173,
"avg_line_length": 18.700000762939453,
"blob_id": "718479b7166955863fd5008d0053192f695f0512",
"content_id": "5dbc574d34f3f3886f30e8a05e13989162abe7fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 10,
"path": "/box.py",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "def boxprint(symbol, width, height):\r\n print(symbol*width)\r\n\r\n\r\n for i in range(height - 2):\r\n print(symbol + (' ' * (width - 2)) + symbol)\r\n\r\n print(symbol * width)\r\n\r\nboxprint('*', 15, 5)\r\n"
},
{
"alpha_fraction": 0.4066390097141266,
"alphanum_fraction": 0.48547717928886414,
"avg_line_length": 19.909090042114258,
"blob_id": "f1aa1781b133c2aac7830f1b938c6ad5119e9108",
"content_id": "eb5180418a545368cc16d711ff9298f41500d494",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 241,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 11,
"path": "/PROBLEM2.PY",
"repo_name": "code-she/python-problems",
"src_encoding": "UTF-8",
"text": "n = int(input(\"\"))\r\nn>=100 and n<=1\r\n\r\nif (n % 2) > 0:\r\n print(\"Weird\")\r\nelif(n % 2)==0 and 2<=n and 5>=n:\r\n print(\"Not Weird\")\r\nelif(n % 2)==0 and 6<=n and 20>=n:\r\n print(\"Weird\")\r\nelif(n % 2)==0 and n>20:\r\n print(\"Not Weird\")\r\n"
}
] | 7 |
Hentai-Gradient/python_demo | https://github.com/Hentai-Gradient/python_demo | 36023514499cc09db22c7f865ea0363ca4955c16 | 5739bb533dbb7d2060f570b1f613536d5311eb20 | 350c1543cdbfb94901e04e1a574cfe7c1896d940 | refs/heads/master | 2020-12-01T04:12:17.736153 | 2016-09-06T16:31:34 | 2016-09-06T16:31:34 | 67,525,213 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6113074421882629,
"alphanum_fraction": 0.6289752721786499,
"avg_line_length": 21.639999389648438,
"blob_id": "3037c8fbb6bf414b0a4149a642dee9ddb4db5a36",
"content_id": "d49e2b9d0e8282305ddc94ce319ede7d231655af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 578,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 25,
"path": "/fileIO.py",
"repo_name": "Hentai-Gradient/python_demo",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# 打开一个文件\nimport time\n\nfo = open(\"/Users/maxiaoshi/PycharmProjects/untitled/foo.txt\", \"r+\")\nstring = fo.readline()\nfindCount = {}\nlines = 0\nprint time.localtime(time.time())\nwhile 1:\n line = fo.readline()\n lines += 1\n lines += 1\n if not line:\n break\n if line.find(\"select\") < 0:\n continue\n keyword = line[line.index(\"from\") + 5:][:line[line.index(\"from\") + 5:].index(\" \")]\n count = findCount.get(keyword, 0)\n findCount[keyword] = count + 1\n\nprint findCount\nprint lines\nprint time.localtime(time.time())\nfo.close()\n"
},
{
"alpha_fraction": 0.6376811861991882,
"alphanum_fraction": 0.6521739363670349,
"avg_line_length": 16.25,
"blob_id": "ab5b95892c2abe69a81b64c1bc1c99a12f97f952",
"content_id": "fe822cd69c9d9ed4ca615bd46381616c71a3ed85",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 91,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 4,
"path": "/inputIO.py",
"repo_name": "Hentai-Gradient/python_demo",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n\nstring = raw_input(\"请输入:\")\nprint \"你输入的内容是: \", string\n"
}
] | 2 |
pritamps/Swiss-Tournament-Simulator | https://github.com/pritamps/Swiss-Tournament-Simulator | 60fd30883fb8fb826899c264df7218f2c430a6be | a2417e84553314f8eec37dddaf2b3d123ad06a0d | f4aa0b58cad4cec2e26610c7c463c3fd60a30404 | refs/heads/master | 2020-05-23T18:39:02.021211 | 2017-03-13T13:37:52 | 2017-03-13T13:37:52 | 84,779,753 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5811764597892761,
"alphanum_fraction": 0.5811764597892761,
"avg_line_length": 40.36585235595703,
"blob_id": "8dc7e9b962b179cb56af40000f6f1558add91339",
"content_id": "691e4084d76487ef705251bfd283de27415b5ef0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 1700,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 41,
"path": "/tournament.sql",
"repo_name": "pritamps/Swiss-Tournament-Simulator",
"src_encoding": "UTF-8",
"text": "-- Table definitions for the tournament project.\n\n-- Connect to the tournaments database. \n\nDROP DATABASE IF EXISTS tournaments;\nCREATE DATABASE tournaments;\n\\c tournaments;\n\n-- Create players database\nCREATE TABLE players ( id SERIAL PRIMARY KEY,\n name TEXT );\n\n-- Table of all tournaments. \nCREATE TABLE tournaments ( id SERIAL PRIMARY KEY,\n name TEXT,\n sport TEXT,\n year TEXT, \n UNIQUE ( name, year ) );\n\n-- Create matches database\nCREATE TABLE matches ( id SERIAL PRIMARY KEY,\n winner INTEGER references players(id),\n loser INTEGER references players(id),\n tournament_id SERIAL references tournaments(id),\n round SMALLINT );\n\n-- Create view for wins and losses for players\nCREATE VIEW player_wins AS \n ( SELECT players.name as name, players.id as id, count(matches.winner) AS wins \n FROM players LEFT JOIN matches ON players.id=matches.winner \n GROUP by players.id );\n\nCREATE VIEW player_matches AS \n ( SELECT players.name as name, players.id as id, count(matches.winner) AS matches \n FROM players LEFT JOIN matches ON ( players.id=matches.winner OR players.id=matches.loser )\n GROUP by players.id );\n\nCREATE VIEW player_standings AS \n ( SELECT player_wins.id, player_wins.name, wins, matches \n FROM (player_wins INNER JOIN player_matches ON player_wins.id=player_matches.id) \n ORDER BY wins DESC);\n\n\n\n\n"
},
{
"alpha_fraction": 0.739506185054779,
"alphanum_fraction": 0.749382734298706,
"avg_line_length": 23.545454025268555,
"blob_id": "482678b256782b5f74746cf851397d0d954b9929",
"content_id": "ca3d1d60803be36a3619d94a5c0ad5a2928c8692",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 810,
"license_type": "no_license",
"max_line_length": 168,
"num_lines": 33,
"path": "/README.md",
"repo_name": "pritamps/Swiss-Tournament-Simulator",
"src_encoding": "UTF-8",
"text": "# Swiss-Tournament-Simulator\n\nProject to simulate a swiss style sports tournament.\n\n## Running the code \n\n### Dependencies\n\n1. To run, you will need PostGreSQL installed on your system. \n2. Python is needed\n3. Python Dependencies: bleach, psycopg2\n\n## Running the code\n\n1. To initialize the database, at a command line prompt, type:\n\n```\n$ psql\npsqlPrompt => \\i tournament.sql\n```\n\n2. To run the tests now, simply type:\n\n```\n$ python tournament_test.py\n```\n\n## Issues\n\nThe following issues exist (where I say that I did not do the extra credit portions):\n\n1. Multiple tournaments are not supported. There is preliminary support in that matches are linked to a tournament ID, but this is not reflected in the player standings\n2. Only even numbers of players are supported. Nothing has been done in this regard.\n"
},
{
"alpha_fraction": 0.61654132604599,
"alphanum_fraction": 0.6218386888504028,
"avg_line_length": 29.47916603088379,
"blob_id": "86510fb1408014e38fdeb982dc05f459c92abcfd",
"content_id": "0caf2a40cff45c75c63f5c57b1865a8b4b20edb6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5852,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 192,
"path": "/tournament.py",
"repo_name": "pritamps/Swiss-Tournament-Simulator",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#\n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\nimport bleach\nimport math\n\nDB_NAME = \"tournaments\"\nTOURNAMENT_NAME = \"Wimbledon\"\nTOURNAMENT_YEAR = \"2017\"\nTOURNAMENT_SPORT = \"TENNIS\"\n\n\ndef connect(database_name=\"tournaments\"):\n \"\"\"\n Connects to DB and returns DB and cursor\n \"\"\"\n try:\n db = psycopg2.connect(\"dbname={}\".format(database_name))\n cursor = db.cursor()\n return db, cursor\n except:\n print(\"Could not connect to database. Aborting!\")\n\n\ndef createTournament(tournament_name=TOURNAMENT_NAME,\n year=TOURNAMENT_YEAR, sport=TOURNAMENT_SPORT):\n \"\"\"Creates a new tournament and returns its ID\"\"\"\n DB, c = connect()\n # Safe insert into DB. USE QUERY PARAMETERS INSTEAD OF STRING SUBSTITUTION\n c.execute(\"INSERT INTO tournaments (name, year, sport ) VALUES (%s, %s, %s) \\\n RETURNING id\", (bleach.clean(tournament_name),\n bleach.clean(year),\n bleach.clean(sport), ))\n tournament_id = c.fetchone()\n DB.commit()\n DB.close()\n return tournament_id\n\n\ndef getTournamentID(tournament_name=TOURNAMENT_NAME,\n year=TOURNAMENT_YEAR, sport=TOURNAMENT_SPORT):\n\n DB, c = connect()\n c.execute(\"SELECT id from tournaments WHERE name=%s AND year=%s\",\n (tournament_name, TOURNAMENT_YEAR))\n rows = c.fetchone()\n if rows is None:\n return None\n else:\n return rows[0]\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n DB, c = connect()\n c.execute(\"TRUNCATE matches\")\n DB.commit()\n DB.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n DB, c = connect()\n c.execute(\"TRUNCATE players CASCADE\")\n DB.commit()\n DB.close()\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n DB, c = connect()\n c.execute(\"SELECT count(*) FROM players\")\n count = c.fetchone()[0]\n DB.close()\n\n return count\n\n\ndef registerPlayer(name, tournament_name=TOURNAMENT_NAME,\n year=TOURNAMENT_YEAR):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n DB, c = connect()\n\n # Get tournament ID for given tournament. If it doesn't exist, create it\n c.execute(\"SELECT id from tournaments WHERE name=%s AND year=%s\",\n (tournament_name, TOURNAMENT_YEAR))\n rows = c.fetchone()\n if rows is None:\n tournament_id = createTournament()[0]\n else:\n tournament_id = rows[0]\n\n # Add new player (if they don't exist already) and get their ID\n c.execute(\"INSERT into players (name) VALUES (%s) RETURNING id\",\n (bleach.clean(name),))\n player_id = c.fetchone()[0]\n\n DB.commit()\n DB.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place,\n or a player tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n list_of_tuples = []\n DB, c = connect()\n c.execute(\"SELECT * FROM player_standings\")\n rows = c.fetchall()\n tournament_id = getTournamentID(tournament_name=TOURNAMENT_NAME,\n year=TOURNAMENT_YEAR,\n sport=TOURNAMENT_SPORT)\n for row in rows:\n list_of_tuples.append(row)\n DB.close()\n return list_of_tuples\n\n\ndef reportMatch(winner, loser,\n tournament_name=TOURNAMENT_NAME,\n year=TOURNAMENT_YEAR,\n round=-1):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n DB = psycopg2.connect(\"dbname=\" + DB_NAME)\n c = DB.cursor()\n\n # Get tournament ID for given tournament. If it doesn't exist, create it\n c.execute(\"SELECT id from tournaments WHERE name=%s AND year=%s\",\n (tournament_name, TOURNAMENT_YEAR))\n rows = c.fetchone()\n\n if rows is None:\n tournament_id = createTournament()[0]\n else:\n tournament_id = rows[0]\n\n c.execute(\"INSERT INTO matches (winner, loser, tournament_id, round) VALUES \\\n (%s, %s, %s, %s)\", (winner, loser, tournament_id, round))\n\n DB.commit()\n DB.close()\n\n\ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n\n DB, c = connect()\n standings = playerStandings()\n\n list_of_tuples = []\n for i in range(0, len(standings), 2):\n list_of_tuples.append((standings[i][0], standings[i][1],\n standings[i+1][0], standings[i+1][1]))\n\n return list_of_tuples\n"
}
] | 3 |
Dylan-halls/Remote-shell-quiry | https://github.com/Dylan-halls/Remote-shell-quiry | 2b807bc2097a830c739a4bb1c31b426ac353a6a4 | 31b938d9eb47bdb11516e50849db7d89a3a5ab16 | 2f32c5d86250d7e1fcf60d59e2ea9fd5ff2657a8 | refs/heads/master | 2016-09-16T22:27:22.789749 | 2016-06-17T13:29:35 | 2016-06-17T13:29:35 | 61,375,024 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7931769490242004,
"alphanum_fraction": 0.7931769490242004,
"avg_line_length": 233.5,
"blob_id": "824e5c8dc8904e0e7a42f218771207b6e6830c50",
"content_id": "3d3221f9a8785459cddd107d4726d43a25d33a23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 469,
"license_type": "no_license",
"max_line_length": 447,
"num_lines": 2,
"path": "/README.md",
"repo_name": "Dylan-halls/Remote-shell-quiry",
"src_encoding": "UTF-8",
"text": "# Remote-shell-quiry\nThis is a tool that is kind of like the well known SSH protocol but it establishes the communication via to tcp servers (one server and one client.) You start the the tcp server running on the target machine then on the host machine you will run the tcp client which will show a shell prompt then what ever you enter in to that will be sent to the server, the server will then run the command via subprosess the send the result back to the client.\n"
},
{
"alpha_fraction": 0.5525773167610168,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 21.045454025268555,
"blob_id": "26783644eabc30ebbca1a2e890398ddee2c5eb03",
"content_id": "26c6e2618490aab4941422e3a7e64a45f58f5b76",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 485,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 22,
"path": "/Client_tcp.py",
"repo_name": "Dylan-halls/Remote-shell-quiry",
"src_encoding": "UTF-8",
"text": "import socket, subprocess, os, sys\n\nsocket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)\n\ntarget = '10.0.57.111'\nport = 50007\ncmd = 0\n\nwhile True:\n socket.connect((target, port))\n\n def Mainshell():\n cmd = input(\"\\n[SHELL]@\"+\"{}:{}\".format(target, port)+\" >>\")\n exe_cmd = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n return (exe_cmd)\n\n \nelse:\n print(\"\\033[45m[*] Connection ended [*]\\033[0m\")\n \n\n Mainshell()\n"
}
] | 2 |
cclauss/prometheus | https://github.com/cclauss/prometheus | b5461517ac7a061d0f32947a93b07885faa4b10a | aabd432bbf4841a9876ab0d5721b4c67ff917d77 | ddaf6db7fc81ed15989b1e32da115318f390226b | refs/heads/master | 2020-03-30T03:24:52.743473 | 2018-09-26T17:17:56 | 2018-09-26T17:17:56 | 150,687,864 | 0 | 0 | MIT | 2018-09-28T04:57:49 | 2018-09-28T04:55:32 | 2018-09-26T17:17:57 | null | [
{
"alpha_fraction": 0.5811719298362732,
"alphanum_fraction": 0.5922189950942993,
"avg_line_length": 31.03076934814453,
"blob_id": "13c3fae87db1ca1e28c0ab1bdebbea2b82534ef2",
"content_id": "097f23f6f0aa3ae96a220f18b6c4036cee674a9e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2082,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 65,
"path": "/losses/unet.py",
"repo_name": "cclauss/prometheus",
"src_encoding": "UTF-8",
"text": "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport numpy as np\n\n\ndef cuda(x):\n return x.cuda(async=True) if torch.cuda.is_available() else x\n\n\nclass LossBinary:\n \"\"\"\n Loss defined as BCE - log(soft_jaccard)\n\n Vladimir Iglovikov, Sergey Mushinskiy, Vladimir Osin,\n Satellite Imagery Feature Detection\n using Deep Convolutional Neural Network: A Kaggle Competition\n arXiv:1706.06169\n \"\"\"\n\n def __init__(self, jaccard_weight=0):\n self.nll_loss = nn.BCEWithLogitsLoss()\n self.jaccard_weight = jaccard_weight\n\n def __call__(self, outputs, targets):\n loss = self.nll_loss(outputs, targets)\n\n if self.jaccard_weight:\n eps = 1e-15\n jaccard_target = (targets == 1).float()\n jaccard_output = F.sigmoid(outputs)\n\n intersection = (jaccard_output * jaccard_target).sum()\n union = jaccard_output.sum() + jaccard_target.sum()\n\n loss -= self.jaccard_weight * torch.log(\n (intersection + eps) / (union - intersection + eps))\n return loss\n\n\nclass LossMulti:\n def __init__(self, jaccard_weight=0, num_classes=1, class_weights=None):\n if class_weights is not None:\n nll_weight = cuda(\n torch.from_numpy(class_weights.astype(np.float32)))\n else:\n nll_weight = None\n self.nll_loss = nn.NLLLoss2d(weight=nll_weight)\n self.jaccard_weight = jaccard_weight\n self.num_classes = num_classes\n\n def __call__(self, outputs, targets):\n nll_loss = self.nll_loss(outputs, targets)\n jaccard_loss = []\n if self.jaccard_weight:\n eps = 1e-15\n for cls in range(self.num_classes):\n jaccard_target = (targets == cls).float()\n jaccard_output = outputs[:, cls].exp()\n\n intersection = (jaccard_output * jaccard_target).sum()\n union = jaccard_output.sum() + jaccard_target.sum() + eps\n jaccard_loss.append(1 - intersection / (union - intersection))\n\n return nll_loss, jaccard_loss\n"
},
{
"alpha_fraction": 0.6040403842926025,
"alphanum_fraction": 0.6040403842926025,
"avg_line_length": 14,
"blob_id": "d7972cced9b160fe50134756ae44683b2b36f3f8",
"content_id": "7e84e1b17ed3e6f3b8a659dfee129719f64243fa",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 495,
"license_type": "permissive",
"max_line_length": 50,
"num_lines": 33,
"path": "/docker/README.md",
"repo_name": "cclauss/prometheus",
"src_encoding": "UTF-8",
"text": "## How to build\n\n\n### CPU only\n\n```bash\ndocker build -t pro-cpu -f ./Dockerfile.cpu .\n```\n\n### GPU\n\n```bash\ndocker build -t pro-gpu -f ./Dockerfile.gpu .\n```\n\n\n### GPU + extentions\n\n```bash\ndocker build -t pro-ext -f ./Dockerfile.ext .\n```\n\n\n## How to use\n\n```bash\nexport LOGDIR=...\ndocker run -it --rm \\\n -v $(pwd):/src -v $LOGDIR:/logdir/ \\\n -e CUDA_VISIBLE_DEVICES= -e PYTHONPATH=. \\\n pro-gpu python prometheus/dl/scripts/train.py \\\n --config=./configs/train.yml --logdir=/logdir\n```\n"
},
{
"alpha_fraction": 0.6105826497077942,
"alphanum_fraction": 0.612366259098053,
"avg_line_length": 23.376811981201172,
"blob_id": "c768af947f1fb10b1ebb127be525203d2d2fcbd3",
"content_id": "9699c61ceb7a25c9058463deee212b6777077007",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1682,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 69,
"path": "/scripts/tag2label.py",
"repo_name": "cclauss/prometheus",
"src_encoding": "UTF-8",
"text": "import argparse\nimport json\nimport pandas as pd\n\nfrom prometheus.utils.data import create_dataset, create_dataframe, \\\n prepare_dataset_labeling, separate_tags\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--in-csv\",\n type=str, default=None)\n parser.add_argument(\n \"--in-dirs\",\n type=str, default=None)\n\n parser.add_argument(\n \"--out-dataset\",\n type=str, default=None)\n parser.add_argument(\n \"--out-labeling\",\n type=str, default=None, required=True)\n\n parser.add_argument(\n \"--tag-column\",\n type=str, default=None, required=True)\n parser.add_argument(\n \"--tag-delim\",\n type=str, default=None)\n\n args = parser.parse_args()\n return args\n\n\ndef prepare_df_from_dirs(dirs, class_column_name):\n dataset = create_dataset(dirs)\n df = create_dataframe(dataset, columns=[class_column_name, \"filepath\"])\n return df\n\n\ndef main(args):\n if args.in_csv is not None:\n df = pd.read_csv(args.in_csv)\n elif args.in_dirs is not None:\n df = prepare_df_from_dirs(args.in_dirs, args.class_column)\n else:\n raise Exception\n\n if args.tag_delim is not None:\n df = separate_tags(\n df,\n tag_column=args.tag_column,\n tag_delim=args.tag_delim)\n\n tag2lbl = prepare_dataset_labeling(df, args.tag_column)\n print(\"Num classes: \", len(tag2lbl))\n\n with open(args.out_labeling, \"w\") as fout:\n json.dump(tag2lbl, fout)\n\n if args.out_dataset is not None:\n df.to_csv(args.out_dataset, index=False)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n"
},
{
"alpha_fraction": 0.6893857717514038,
"alphanum_fraction": 0.6950430870056152,
"avg_line_length": 24.424657821655273,
"blob_id": "88bde4cae835805e59b03abfe374331a926003e3",
"content_id": "fd72b13e77a5d78994fc3cf5e24a5989c1980c3d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3714,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 146,
"path": "/README.md",
"repo_name": "cclauss/prometheus",
"src_encoding": "UTF-8",
"text": "# Prometheus\nHigh-level utils for PyTorch DL/RL research.\nIt was developed with a focus on reproducibility, fast experimentation and code/ideas/models reusing.\nBeing able to research/develop something new, rather then write another regular train loop.\nBest coding practices included.\n\n## Features\n\n- Universal train/inference loop.\n- Key-values storages.\n- Data and model usage standardization.\n- Configuration files - yaml for model/data hyperparameters.\n- Loggers and Tensorboard support.\n- Reproducibility - even source code will be saved to logs.\n- OneCycle lr scheduler and LRFinder support.\n- FP16 support for any model.\n- Corrected weight decay (AdamW).\n- N-best-checkpoints saving (SWA).\n- Training stages support - run whole experiment by one command.\n- Logdir autonaming based on hyperparameters - make hyperopt search easy again.\n- Callbacks - reusable train/inference pipeline parts (and you can write your own if needed).\n- Well structed, so you can just grab a part to your project.\n- Lots of reusable code for different purposes: losses, optimizers, models, knns, embeddings projector.\n\nPrometheus is compatible with: Python 3.6. In development.\n\n## How it works\n\n### Deep learning\n\n#### Train\n```bash\nCUDA_VISIBLE_DEVICES=\"{gpus}\" PYTHONPATH=. \\\n python prometheus/dl/scripts/train.py \\\n --config=/path/to/config-file\n```\n\n#### Inference\n```bash\nCUDA_VISIBLE_DEVICES=\"{gpus}\" PYTHONPATH=. \\\n python prometheus/dl/scripts/inference.py \\\n --config=/path/to/config-file,/path/to/inference-config-file \\\n --resume=/path/to/checkpoint\n```\n\n\n### Reinforcement learning [WIP]\n\nWaiting for NIPS end. Release date - December 2018.\n\n#### Redis server\n\n```bash\nredis-server --port 12000\n```\n\n#### Trainer\n\n```bash\nCUDA_VISIBLE_DEVICES=\"{gpus}\" PYTHONPATH=. \\\n python prometheus/rl/offpolicy/scripts/run_trainer.py \\\n --config=/path/to/config-file\n```\n\n#### Samplers\n\n```bash\nCUDA_VISIBLE_DEVICES=\"\" PYTHONPATH=. \\\n python prometheus/rl/offpolicy/scripts/run_samplers.py \\\n --config=/path/to/config-file\n```\n\n## Dependencies\n```bash\npip install git+https://github.com/pytorch/tnt.git@master \\\n tensorboardX jpeg4py albumentations\n```\n\n\n## Docker\n\nSee `./docker` for more information and examples.\n\n\n## Usage\n```bash\ngit submodule add https://github.com/Scitator/prometheus.git prometheus\n```\n\n## Examples\n\nhttps://github.com/Scitator/prometheus-examples\n\n## Better to use with\n\nCV augmentations – https://github.com/albu/albumentations\n\n## Contribution guide\n\n##### Autoformatting code\n\nWe use [yapf](https://github.com/google/yapf) for linting,\nand the config file is located at `.style.yapf`.\nWe recommend running `yapf.sh` prior to pushing to format changed files.\n\n\n##### Linter\n\nTo run the Python linter on a specific file,\nrun something like `flake8 dl/scripts/train.py`.\nYou may need to first run `pip install flake8`.\n\n##### Codestyle\n\ntl;dr:\n- right margin - 80\n- double quotes\n- full names: \n - `model`, `criterion`, `optimizer`, `scheduler` - okay \n - `mdl`,`crt`, `opt`, `scd` - not okay\n- long names solution\n - okay:\n ```bash\n def my_pure_long_name(\n self,\n model, criterion=None, optimizer=None, scheduler=None,\n debug=True):\n \"\"\"code\"\"\"\n ```\n - not okay:\n ```bash\n def my_pure_long_name(self,\n model, criterion=None, optimizer=None, scheduler=None,\n debug=True):\n \"\"\"code\"\"\"\n ```\n - why? name refactoring. with first one solution, \n there are no problems with pep8 codestyle check.\n- \\* in funcs for force key-value args\n\n\n## Future features\n\n- prometheus pic\n- distributed training (with fp16 support)\n- Horovod support\n"
},
{
"alpha_fraction": 0.5536585450172424,
"alphanum_fraction": 0.5597561001777649,
"avg_line_length": 22.428571701049805,
"blob_id": "72e7dfbacddad5d5469ce4161bec7f0e58eb2040",
"content_id": "c98cba25f4d6645c123d4fc4d2170d2512dffa18",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 820,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 35,
"path": "/dl/state.py",
"repo_name": "cclauss/prometheus",
"src_encoding": "UTF-8",
"text": "from collections import defaultdict\nfrom prometheus.utils.misc import FrozenClass\n\n\nclass RunnerState(FrozenClass):\n \"\"\"\n An object that is used to pass internal state during train/valid/infer.\n \"\"\"\n\n def __init__(self, **kwargs):\n # data\n self.device = None\n self.input = None\n self.output = None\n self.loader = None\n self.loader_mode = None\n\n # counters\n self.bs = 0\n self.step = 0\n self.epoch = 0\n\n # metrics\n self.lr = defaultdict(lambda: 0)\n self.momentum = defaultdict(lambda: 0)\n self.loss = None\n self.epoch_metrics = None\n self.best_metrics = None\n\n # other\n self.is_train = False\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n self._freeze()\n"
}
] | 5 |
adMenon/Competetive-programing-codes | https://github.com/adMenon/Competetive-programing-codes | d03a5f3a8111b87897e9d24f29d2d92a79b301dd | c0b34556da5092151426784f2f9f1d03d2837736 | 44036fb20e2a7242588bc09771a13395266c408f | refs/heads/master | 2021-04-06T08:36:50.005676 | 2018-03-16T02:34:52 | 2018-03-16T02:34:52 | 125,392,087 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4010416567325592,
"alphanum_fraction": 0.5243055820465088,
"avg_line_length": 17.03125,
"blob_id": "6bd4d6c7862563ed3c0546c9a4b63625004a1ca8",
"content_id": "b657155fba1b2d54bf6966f8822ac5a0a8f1a677",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 576,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 32,
"path": "/SPOJ/ZSUM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int power(long long int x, long long int y,long long int p)\n{\n int res = 1;\n x = x % p;\n while (y > 0)\n {\n if (y & 1)\n res = (res*x)%10000007;\n y = y>>1; \n x = (x*x)%p; \n }\n return res;\n}\nint main()\n{\n\t\n\twhile(1)\n\t{\n\t\tlong long int n,k;\n\t\tcin>>n>>k;\n\t\tif(n==0&&k==0)\n\t\t\tbreak;\n\t\tlong long int t=power(n,k,10000007)+power(n,n,10000007)+2*(power(n-1,n-1,10000007)+power(n-1,k,10000007))%10000007;\n\t\tcout<<t%10000007<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.42965203523635864,
"alphanum_fraction": 0.4826021194458008,
"avg_line_length": 15.146341323852539,
"blob_id": "7ee68422a574851ef790035984b3dd5783f6b061",
"content_id": "598d9ba004305a976478f108f7ba5ec6a77512a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 661,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 41,
"path": "/SPOJ/PIGBANK.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nint dp(int w,int a[][2],int n)\n{\n\tint dp[w+1];\n\tdp[0]=0;\n\tfor(int i=1;i<=w;i++)\n\t{\n\t\tdp[i]=-1;\n\t\tfor(int j=0;j<n;j++)\n\t\t{\n\t\t\tif(i>=a[j][1]&&dp[i-(a[j][1])]!=-1&&(dp[i]==-1||a[j][0]+dp[i-a[j][1]]<=dp[i]))\n\t\t\t\tdp[i]=a[j][0]+dp[i-a[j][1]];\n\t\t}\n\t}\n\treturn dp[w];\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint w1,w2;\n\t\tcin>>w1>>w2;\n\t\tint n;\n\t\tcin>>n;\n\t\tint a[10000][2];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>a[i][0]>>a[i][1];\n\t\tint m=dp(w2-w1,a,n);\n\t\tif(m>=0)\n\t\t\tcout<<\"The minimum amount of money in the piggy-bank is \"<<m<<\".\\n\";\n\t\telse\n\t\t\tcout<<\"This is impossible.\\n\";\n\t}\n}"
},
{
"alpha_fraction": 0.49367088079452515,
"alphanum_fraction": 0.5352622270584106,
"avg_line_length": 24.090909957885742,
"blob_id": "17940b2f024bdcbf0c1d539815187163bf3e9ccb",
"content_id": "25d2b329d6073f9e0a95fd9c81ec2f369d140eb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 553,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 22,
"path": "/Codechef/ZCO14003.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n long long int n;\n cin>>n;\n vector<long long int> a(n); \n for(long long int i=0;i<n;i++)\n cin>>a[i];\n sort(a.begin(),a.end());\n long long int m=-9999999999999999;\n for(vector<long long int>::iterator i=a.end()-1;i>=a.begin();)\n {\n vector <long long int>::iterator j=lower_bound(a.begin(),a.end(),*i);\n m=max(m,(*i)*(long long int)(a.size()-(j-a.begin())));\n i=j-1;\n }\n cout<<m<<endl;\n} "
},
{
"alpha_fraction": 0.42281877994537354,
"alphanum_fraction": 0.47203579545021057,
"avg_line_length": 9.181818008422852,
"blob_id": "d31d807df49a0b977e9ffcafc99ecf1c0410203d",
"content_id": "c3fd5eabc61b0d386ca8c7539faf6162cc27a546",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 447,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 44,
"path": "/SPOJ/DIEHARD.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nvoid val(long long int h,long long int a)\n{\n\tlong long int t=1;\n\th+=3;\n\ta+=2;\n\twhile(1)\n\t{\n\t\tif(h>20&&a<=10)\n\t\t{\n\t\t\th-=17;\n\t\t\ta+=7;\n\t\t\tt+=2;\n\t\t}\n\t\telse if(h>5&&a>10)\n\t\t{\n\t\t\th-=2;\n\t\t\ta-=8;\n\t\t\tt+=2;\n\t\t}\n\t\t \n\t\telse\n\t\t{\n\t\t\tcout<<t<<endl;\n\t\t\tbreak;\n\t\t}\n\t}\n}\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int h,a;\n\t\tcin>>h>>a;\n\t\tval(h,a);\n\t}\n}"
},
{
"alpha_fraction": 0.3494318127632141,
"alphanum_fraction": 0.38352271914482117,
"avg_line_length": 20.9375,
"blob_id": "80ae7c0b20d7fdfb1cf3f37177183eb39d8076d7",
"content_id": "c224182e3e74e55614edf135ccb212d91f31e09d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 352,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 16,
"path": "/Codechef/EXTRAN.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Codechef id - ad2411\n'''\nt=int(input())\nwhile t!=0:\n n=int(input())\n l=list(map(int,input().split()))\n l.sort()\n for i in range(len(l)-1):\n if l[i+1]-l[i]!=1:\n if l[i]-l[i-1]==1:\n print(l[i+1])\n else:\n print(l[i]) \n break\n t-=1 "
},
{
"alpha_fraction": 0.3361110985279083,
"alphanum_fraction": 0.3481481373310089,
"avg_line_length": 20.19607925415039,
"blob_id": "3389a60d1b1cdd0b78910008663935cf4ae1966a",
"content_id": "8f4463570acd8f937b08ac6fb1ad8c6bc9875789",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1080,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 51,
"path": "/SPOJ/ARMY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t\n\t// your code here\n int t;\n cin>>t;\n while(t--)\n {\n long long int g,m,k=0,j=0;\n cin>>g>>m;\n long long int *ng=new long long int[g];\n long long int *nm=new long long int[m];\n for(long long int i=0;i<g;i++)\n cin>>ng[i];\n for(long long int i=0;i<m;i++)\n cin>>nm[i];\n sort(ng,ng+g);\n sort(nm,nm+m);\n if(ng[g-1]>nm[m-1]) cout<<\"Godzilla\\n\";\n else if(ng[g-1]<nm[m-1]) cout<<\"MechaGodzilla\\n\";\n else\n {\n while(g&&m)\n {\n if(ng[j]>=nm[k]) \n {\n m--;\n k++;\n }\n else\n {\n g--;\n j++;\n }\n }\n if(g) cout<<\"Godzilla\\n\";\n else cout<<\"MechaGodzilla\\n\";\n \n }\n }\n return 0;\n \n \n }"
},
{
"alpha_fraction": 0.4474327564239502,
"alphanum_fraction": 0.47921761870384216,
"avg_line_length": 13.642857551574707,
"blob_id": "51eff1023383813b639cbefa6f372a943a84c498",
"content_id": "10c17b1f7aeca3b0d61e5c20060526d9ffa8a7c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 409,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 28,
"path": "/SPOJ/VENOM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\t{\n\t\tlong long int h,p,A;\n\t\tdouble a,b,c,d;\n\t\tlong long int v;\n\t\tscanf(\"%lld %lld %lld\",&h,&p,&A);\n\t\tif(h<=p) printf(\"1\\n\");\n\t\telse\n\t\t{\n\t\t\tb=(p-2*A);\n\t\t\ta=p;\n\t\t\tc=2*(A-h);\n\t\t\td=sqrt((b*b)-(4*a*c));\n\t\t\tv=ceil((-1*b+d)/(2*a));\n\t\t\tprintf(\"%d\\n\",2*v-1);\n\t\t}\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.42899850010871887,
"alphanum_fraction": 0.46188339591026306,
"avg_line_length": 10.964285850524902,
"blob_id": "97965969ba396f7df5f0b4e4f60262ce2e5a3bc0",
"content_id": "6710a7aa6e1912f0b6578b705bfed6de2f8d114a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 669,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 56,
"path": "/SPOJ/BAT3.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n\n#include <bits/stdc++.h>\nusing namespace std;\nint bat(int a[],int n,int m)\n{\n\tint dp[1001]={0};\n\tdp[n-1]=1;\n\tint M=1,mx;\n\tfor(int i=n-2;i>m;i--)\n\t{\n\t\tmx=1;\n\t\tfor(int j=i+1;j<n;j++)\n\t\t{\n\t\t\tif(a[i]>a[j])\n\t\t\t\tmx=max(mx,1+dp[j]);\n\t\t}\n\t\tdp[i]=mx;\n\t\t//cout<<mx<<endl;\n\t\tM=max(mx,M);\n\t}\n\t//cout<<M<<endl;\n\tdp[m]=++M;\n\tfor(int i=m-1;i>=0;i--)\n\t{\n\t\tmx=1;\n\t\tfor(int j=i+1;j<=m;j++)\n\t\t{\n\t\t\tif(a[i]>a[j])\n\t\t\t\tmx=max(mx,1+dp[j]);\n\t\t}\n\t\tdp[i]=mx;\n\t\tM=max(mx,M);\n\n\t}\n\n\treturn M;\n\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,m;\n\t\tcin>>n>>m;\n\t\tint *a=new int[n];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tcout<<bat(a,n,m)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.550000011920929,
"alphanum_fraction": 0.596666693687439,
"avg_line_length": 11.541666984558105,
"blob_id": "a0e93a7fba56618d629893c1234ca44a31032434",
"content_id": "4ddf6c5c9d37e5baf866c4b06802d9515176696a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 300,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 24,
"path": "/SPOJ/CORDS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\nusing namespace std;\nlong long int rec(long long int n)\n{\n\tlong long int c=(3*n*n+n)/2;\n\treturn c;\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\tcout<<rec(n)%1000007<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4518987238407135,
"alphanum_fraction": 0.4683544337749481,
"avg_line_length": 19.763158798217773,
"blob_id": "04d98dc1d89e4bf77bd6e418b32828b3cbfff647",
"content_id": "860a03b19dd8768d77480d2a805332376dba390e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 790,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 38,
"path": "/Codechef/ALEXTASK.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <iostream>\n#include<algorithm>\nusing namespace std;\nlong long int gcd(long long int a,long long int b)\n{\n if(b==0) return a;\n return gcd(b,a%b);\n}\nlong long int lcm(long long int a,long long int b)\n{\n return a*b/gcd(a,b);\n}\nint main() {\n // your code goes here\n int t;\n cin>>t;\n while(t--)\n {\n int n,i,j,flag=1;\n cin>>n;\n long long int *a=new long long int[n];\n for(i=0;i<n;i++)\n cin>>a[i];\n sort(a,a+n);\n long long int min=lcm(a[0],a[1]);\n for(int i=0;i<n-1;i++)\n for(int j=i+1;j<n;j++)\n if(min>lcm(a[j],a[i])) min=lcm(a[j],a[i]);\n cout<<min<<endl;\n \n \n \n }\n return 0;\n}\n "
},
{
"alpha_fraction": 0.5020080208778381,
"alphanum_fraction": 0.5461847186088562,
"avg_line_length": 10.904762268066406,
"blob_id": "443d2fbeff8c4f4dc4e85899b06e24c2f9e018bf",
"content_id": "0ea4fbcfdcc921d565f3b5747f8c25abc37ca79d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 21,
"path": "/SPOJ/SAMER08F.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\nusing namespace std;\nint main()\n{\n\tint n,flag=1;\n\tdo\n\t{\n\t\tcin>>n;\n\t\tif(n)\n\t\t{\n\t\t\tlong long int ans=(n*(2*n+1)*(n+1))/6;\n\t\t\tcout<<ans<<endl;\n\t\t}\n\t\telse flag=0;\n\t}while(flag);\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.28811660408973694,
"alphanum_fraction": 0.3262331783771515,
"avg_line_length": 20.238094329833984,
"blob_id": "f8a8fe5428d5d4baa94edeae7bfdbc23c5f32854",
"content_id": "e258b04ca2dbacadd83dff996d6b0bab2050f022",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 892,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 42,
"path": "/Codechef/TALAZY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include<iostream>\nusing namespace std;\n//long long int time(int N,int b,int c,int a=0)\n//{ if(N==a) return 0;\n// if((N%2==0&&a==N/2)||(N%2!=0&&a==(N+1)/2)) return b+time(N-a,b,2*c);\n// return c+time(N,b,c,a+1);\n//}\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n { long long int time=0;\n long long int N,B,M,a=0;\n cin>>N>>B>>M;\n while(N!=a)\n {\n if((N%2==0&&a==N/2)||(N%2!=0&&a==(N+1)/2))\n {\n time+=B;\n M*=2;\n N-=a;\n a=0;\n continue;\n }\n if(N%2==0)\n {\n time+=(N/2)*M;\n a=N/2;\n }\n else\n {\n time+=((N+1)/2)*M;\n a=(N+1)/2;\n }\n }\n cout<<time<<endl;\n }\n} "
},
{
"alpha_fraction": 0.3961164951324463,
"alphanum_fraction": 0.477669894695282,
"avg_line_length": 11,
"blob_id": "ee2dd9e0bd006017bb382fb961539f8110c31f0c",
"content_id": "93e7e6ad134cde8a5080761cc0155db5e74d503e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 515,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 43,
"path": "/SPOJ/EGYPIZZA.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint n,count=0;\n\tcin>>n;\n\tfloat *ar=new float[n];\n\tint a1=0,a2=0,a3=0;\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tint a,b;\n\t\tchar c;\n\t\tcin>>a>>c>>b;\n\t\tif(a==1&&b==4)\n\t\t\ta1++;\n\t\telse if(b==2)\n\t\t\ta2++;\n\t\telse\n\t\t\ta3++;\n\t}\n\t//cout<<a1<<\" \"<<a2<<\" \"<<a3<<endl;\n\tcount+=a3;\n\ta1=a1-a3;\n\tcount+=(a2-a2%2)/2;\n\tif(a2%2)\n\t{\n\t\tcount++;\n\t\ta1-=2;\n\t}\n\tif(a1>0)\n\t{\n\t\tcount+=(a1-a1%4)/4;\n\t\tif(a1%4)\n\t\t{\n\t\t\tcount++;\n\t\t}\n\t}\n\tcout<<count+1<<endl;\n}"
},
{
"alpha_fraction": 0.50368732213974,
"alphanum_fraction": 0.5265486836433411,
"avg_line_length": 16.855262756347656,
"blob_id": "103c6b8007c56b6a354dc4c5638b4fa0c5956eeb",
"content_id": "865f52ca91a85c0319e1e17d69e5f617706ed2ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1356,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 76,
"path": "/SPOJ/INVCNT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\nlong long int merge(long long int a[],long long int l,long long int m,long long int h)\n{\n\tlong long int *A=new long long int[m-l+1],*B=new long long int[h-m],i,j,count=0;\n\tfor(i=0;i<m-l+1;i++)\n\t\tA[i]=a[l+i];\n\tfor(i=0;i<h-m;i++)\n\t\tB[i]=a[m+i+1];\n\ti=0;j=0;\n\tlong long int k=l;\n//\tfor(i=0;i<m-l+1;i++)\n//\t\tcout<<A[i]<<\" \";\n//\t\tcout<<endl;\n//\tfor(i=0;i<h-m;i++)\n//\t\tcout<<B[i]<<\" \";\n//\t\tcout<<endl;\n//\ti=0;\n\twhile(i<m-l+1&&j<h-m)\n\t{\n\t\tif(A[i]<=B[j])\n\t\t{\n\t\t\ta[k++]=A[i++];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcount+=m-l+1-i;\n\t\t\ta[k++]=B[j++];\n\t\t}\n\t}\n\twhile(i<m-l+1)\n\t{\n\t\ta[k++]=A[i++];\n\t\t//count++;\n\t}\n\twhile(j<h-m)\n\t\ta[k++]=B[j++];\n\treturn count;\n}\nlong long int mergesort(long long int a[],long long int l,long long int h)\n{\n//\tcout<<\"TEST 1\\n\";\n\n\tlong long int count=0;\n\tif(l<h)\n\t{//\tcout<<\"test1\"<<endl;\n\t\tcount+=mergesort(a,l,(l+h)/2);\n\t\tcount+=mergesort(a,(l+h)/2+1,h);\n\t\tcount+=merge(a,l,(l+h)/2,h);\n\t//\tcout<<\"hello\"<<count<<endl;\n\t}\n\treturn count;\n}\nint main() {\n\t// your code goes here\n\tlong long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tlong long int j=mergesort(a,0,n-1);\n\t\tcout<<j<<endl;\n\t//\tfor(int i=0;i<n;i++)\n\t//\t\tcout<<a[i]<<\" \";\n\t//\tcout<<endl<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5540540814399719,
"alphanum_fraction": 0.6097972989082336,
"avg_line_length": 14.179487228393555,
"blob_id": "08d5a5b1af3ca073c700ab790abb9b7c9ec3a3c0",
"content_id": "ca7a9287ba0cc8ae309277e3d5f309f419018867",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 592,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 39,
"path": "/SPOJ/AFS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nstd::vector<unsigned long long int> value(1000000,0);\nvoid seive(unsigned long long int n=1000000)\n{\n\n\tvalue[0]=0;\n\tvalue[1]=0;\t\n\tfor(unsigned long long int i=1;i<=n;i++)\n\t{\n\t\tvalue[i]+=value[i-1];\n\t\t\tfor(unsigned long long int j=i*2;j<=n;j+=i)\n\t\t\t{\n\t\t\t\t\tvalue[j]+=i;\n\t\t\t}\n\t}\n\t\n}\nunsigned long long int aps(unsigned long long int n)\n{\n\treturn value[n];\n}\nint main()\n{\n\tseive(1000000);\n\tunsigned long long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tunsigned long long int n;\n\t\tcin>>n;\n\t\tcout<<aps(n)<<endl;\n\t\n\t}\n}\n"
},
{
"alpha_fraction": 0.42619746923446655,
"alphanum_fraction": 0.5043988227844238,
"avg_line_length": 14.058823585510254,
"blob_id": "b3adddff2ba89f675d40d264981459e1d25b67c6",
"content_id": "0a43a763055ea93d4c97cbcb7c85d70ef8918e0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1023,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 68,
"path": "/SPOJ/FIBOSUM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvoid multiply(long long int a[2][2],long long int b[2][2])\n{\n\tlong long int c[2][2];\n\tfor(int i=0;i<2;i++)\n\t{\n\t\tfor(int j=0;j<2;j++)\n\t\t{\n\t\t\tc[i][j]=0;\n\t\t\tfor(int k=0;k<2;k++)\n\t\t\t{\n\t\t\t\tc[i][j]+=((a[i][k])*(b[k][j]))%1000000007;\n\t\t\t}\n\t\t\tc[i][j]=c[i][j]%1000000007;\n\t\t}\n\t}\n\tfor(int i=0;i<2;i++)\n\t{\n\t\tfor(int j=0;j<2;j++)\n\t\t\ta[i][j]=c[i][j];\n\t}\n}\t\nvoid power(long long int a[2][2],unsigned long long int y)\n{\n\tlong long int val[2][2]={{1,0},{0,1}};\n\twhile(y>0)\n\t{\n\t\tif(y&1)\n\t\t\tmultiply(val,a);\n\t\ty=y/2;\n\t\tmultiply(a,a);\n\t}\n\t\n\tfor(int i=0;i<2;i++)\n\t{\tfor(int j=0;j<2;j++)\n\t\t{\n\t\t\ta[i][j]=val[i][j];\n\t\t}\n\t\t//cout<<endl;\n\t}\n}\t\nlong long int fibo(long long int n)\n{\n\tlong long int a[2][2]={{1,1},{1,0}};\n\tif(n==1||n==0)\n\t\treturn n;\n\tpower(a,n-1);\n\treturn a[0][0];\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,m;\n\t\tcin>>n>>m;\n\t\tlong long int ans=fibo(m+2)-fibo(n+1);\n\t\tif(ans<=0)\n\t\t\tans+=1000000007;\n\t\tcout<<ans<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4369085133075714,
"alphanum_fraction": 0.5173501372337341,
"avg_line_length": 14.487804412841797,
"blob_id": "37ac423a7445d8ebf729190ac92f5febb2e199a1",
"content_id": "eee29bd5f683cceb29a5c7a251a1becfe3d7584c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 634,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 41,
"path": "/SPOJ/EDIST.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nint dp[2001][2001];\nint min(int a,int b,int c)\n{\n\treturn min(min(a,b),c);\n}\n\nint dpTable(char s1[],char s2[],int s1_l,int s2_l)\n{\n\n\tfor(int i=0;i<=s1_l;i++)\n\t{\n\t\tfor(int j=0;j<=s2_l;j++)\n\t\t{\n\t\t\tif(i==0)\tdp[i][j]=j;\n\t\t\telse if(j==0)\tdp[i][j]=i;\n\t\t\telse if(s1[i-1]==s2[j-1])\n\t\t\t\tdp[i][j]=dp[i-1][j-1];\n\t\t\telse\n\t\t\t\tdp[i][j]=1+min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);\t\t\t\t\n\t\t}\n\t}\n\treturn dp[s1_l][s2_l];\n\t\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tchar s1[2001],s2[2001];\n\t\tcin>>s1>>s2;\n\t\tcout<<dpTable(s1,s2,strlen(s1),strlen(s2))<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.49707603454589844,
"alphanum_fraction": 0.5438596606254578,
"avg_line_length": 11.703703880310059,
"blob_id": "7d30d62bbe8f1a86ca352ffe14d61cc9bb31991f",
"content_id": "fcaf151d98e2545dd36bda5a0343feaed188df4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 342,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 27,
"path": "/SPOJ/LASTDIG.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int a,b;\n\t\tcin>>a>>b;\n\t\tlong long int z;\n\t\tif(b%4)\n\t\tz=pow((a%10),(b%4));\n\t\telse if(b==0)\n\t\tz=1;\n\t\telse\n\t\tz=pow((a%10),4);\n\t\tcout<<z%10<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.34246575832366943,
"alphanum_fraction": 0.35494673252105713,
"avg_line_length": 29.99056625366211,
"blob_id": "05b44de7b9f6bc5533d83830241711162d6acd52",
"content_id": "81aa190b26132b01fccb2522c0c9d03102877672",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3285,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 106,
"path": "/Codechef/CLIQUED.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\n# define INF 999999999999999999\nusing namespace std;\nmap <long long int,int> m;\nclass graph{\n long long int n;\n list<pair<long long int,long long int> > *adj;\n public:\n graph(int N)\n {\n n=N;\n adj=new list< pair<long long int,long long int> >[n+1];\n }\n void addEdge(long long int a,long long int b,long long int wt)\n {\n adj[a].push_back(make_pair(b, wt));\n adj[b].push_back(make_pair(a, wt));\n }\n void shortestPath(long long int src,long long int k,long long int x)\n {\n m.clear();\n priority_queue< pair<long long int,long long int>, vector <pair<long long int,long long int> >, greater<pair<long long int,long long int> > > pq;\n vector<long long int> dist(100001, INF);\n pq.push(make_pair(0, src));\n dist[src] = 0;\n /*if(src<=k)\n {\n for(long long int i=1;i<=k;i++)\n if(i!=src)\n dist[i]=x;\n else\n dist[i]=0; \n }*/\n while (!pq.empty())\n {\n long long int u = pq.top().second;\n /*if(u<=k)\n for(long long int i=1;i<=k;i++)\n {\n if(u!=i)\n adj[u].push_back(make_pair(i,x));\n }*/\n m[u]=1;\n pq.pop();\n list< pair<long long int, long long int> >::iterator i;\n for (i = adj[u].begin(); i != adj[u].end(); ++i)\n {\n long long int v = (*i).first;\n long long int weight = (*i).second;\n if (dist[v] > dist[u] + weight&&m.find(v)==m.end())\n {\n dist[v] = dist[u] + weight;\n pq.push(make_pair(dist[v], v));\n }\n }\n if(u<=k&&dist[k]>dist[u]+x)\n {\n for(long long int j=1;j<=k;j++)\n if (dist[j] > dist[u] + x&&m.find(j)==m.end())\n {\n dist[j] = dist[u] + x;\n pq.push(make_pair(dist[j], j));\n } \n }\n /*if(u<=k&&src<=k)\n {\n if(dist[u]>x)\n dist[u]=x;\n }\n */\n }\n for (long long int i = 1; i <=n; ++i)\n {\n // if(i<=k&&src<=k&&dist[i]>x)\n // dist[i]=x;\n cout<<dist[i]<<\" \";\n }\n cout<<endl;\n }\n};\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n long long int n,k,x,m,s,a,b,c;\n cin>>n>>k>>x>>m>>s;\n graph g(n);\n // for(long long int i=1;i<=k;i++)\n // for(long long int j=i+1;j<=k;j++)\n // {\n // g.addEdge(i,j,x);\n // }\n // cout<<\"t1\\n\";\n for(long long int i=0;i<m;i++)\n {\n cin>>a>>b>>c;\n g.addEdge(a,b,c);\n }\n g.shortestPath(s,k,x);\n }\n} "
},
{
"alpha_fraction": 0.4479166567325592,
"alphanum_fraction": 0.4791666567325592,
"avg_line_length": 13.788461685180664,
"blob_id": "60d601f62cc367b37650444c3fc84a043e5e37c7",
"content_id": "da2617e6b5d2efd1ceaa3dce7080c4393b4509c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 768,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 52,
"path": "/SPOJ/PT07Y.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvector<int> parent(1000000,-1);\nint find(int i)\n{\n if (parent[i] == -1)\n return i;\n return find(parent[i]);\n}\nvoid Union(int x, int y)\n{\n int xset = find(x);\n int yset = find(y);\n parent[xset] = yset;\n}\nvoid isCycle(vector<int> v[],int n)\n{\n for(int i=0;i<n;i++)\n {\n int x=find(v[i][0]);\n\t\tint y=find(v[i][1]);\n if (x == y)\n {\n \tcout<<\"NO\\n\";\n \treturn;\n\t\t}\n \t \tUnion( x, y);\t\n }\n\tcout<<\"YES\\n\";\n}\nint main()\n{\n\tint n,m,a,b;\n\tcin>>n>>m;\n\tvector <int> v[20001];\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tcin>>a>>b;\n\t\tv[i].push_back(a);\n\t\tv[i].push_back(b);\n\t}\n\tif(n!=m+1)\n\t{\n\t\tcout<<\"NO\\n\";\n\t\treturn 0;\n\t}\n\tisCycle(v,m);\n}"
},
{
"alpha_fraction": 0.5213068127632141,
"alphanum_fraction": 0.5553977489471436,
"avg_line_length": 17.076923370361328,
"blob_id": "3f46bd4aabddf1fbc8bed14811ec4e2de2e0b469",
"content_id": "37547cc2571028ec7caff68d92c26d84baa8b95f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 704,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 39,
"path": "/SPOJ/FARIDA.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int dp[100000];\nlong long int coins(long long int a[],long long int n)\n{\n\tfor(long long int j=0;j<n;j++)\n\t\tdp[j]=0;\n\tdp[0]=a[0];\n\tdp[1]=a[1];\n\tfor(long long int j=2;j<n;j++)\n\t\tfor(long long int k=0;k<j-1;k++)\n\t\t{\n\t\t\tif(dp[j]<dp[k]+a[j])\n\t\t\t\tdp[j]=dp[k]+a[j];\n\t\t}\n\tlong long int max=0;\n\tfor(long long int i=0;i<n;i++)\n\t\tif(max<dp[i])\n\t\t\tmax=dp[i];\n\treturn max;\n}\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\tfor(long long int i=0;i<t;i++)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int j=0;j<n;j++)\n\t\t\tcin>>a[j];\n\t\tcout<<\"Case \"<<i+1<<\": \"<<coins(a,n)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4692690968513489,
"alphanum_fraction": 0.4908638000488281,
"avg_line_length": 14.0625,
"blob_id": "e27e9d89d85a346266ab8bf639c29ebbf70c8971",
"content_id": "d5758c9f9172183e3f72e8b3ace92d36e3c3347b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1204,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 80,
"path": "/SPOJ/DQUERY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvector <int> m(1000001,-1);\nint BLOCK;\nbool cmp(pair<pair<int,int>,int> a,pair<pair<int,int>,int> b)\n{\n\tint A=a.first.first/BLOCK,B=b.first.first/BLOCK;\n\tif(A!=B)\n\t\treturn A<B;\n\treturn a.first.second<b.first.second;\n}\nint main()\n{\n\tios_base::sync_with_stdio(false); \n\tint n,c=0;\n\tcin>>n;\n\tint *a=new int[n];\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tcin>>a[i];\n\t\tif(m[a[i]]==-1)\n\t\t\tc++,m[a[i]]++;\n\t\tm[a[i]]++;\n\t}\n\tint q;\n\tcin>>q;\n\tint l=0,r=n-1;\n\tpair<pair<int,int>,int > *Q=new pair<pair<int,int>,int >[q];\n\t\n\tint *ans=new int[q];\n\tfor(int i=0;i<q;i++)\n\t{\n\t\t//cout<<\"test\\n\";\n\t\tint f,s;\n\t\tcin>>f>>s;\n\t\tQ[i]=make_pair(make_pair(f-1,s-1),i);\n\t}\n\tBLOCK=ceil(sqrt(n));\n\tsort(Q,Q+q,cmp);\n\tfor(int i=0;i<q;i++)\n\t{\twhile(l<Q[i].first.first)\n\t\t{\n\t\t\tm[a[l]]--;\n\t\t\tif(m[a[l]]==0)\n\t\t\t\tc--;\n\t\t\tl++;\n\t\t}\n\t\twhile(l>Q[i].first.first)\n\t\t{\n\t\t\tl--;\n\t\t\tm[a[l]]++;\n\t\t\tif(m[a[l]]==1)\n\t\t\t\tc++;\n\t\t\t\n\t\t}\n\t\twhile(r>Q[i].first.second)\n\t\t{\n\t\t\tm[a[r]]--;\n\t\t\tif(m[a[r]]==0)\n\t\t\t\tc--;\n\t\t\tr--;\n\t\t}\n\t\twhile(r<Q[i].first.second)\n\t\t{\n\t\t\tr++;\n\t\t\tm[a[r]]++;\n\t\t\tif(m[a[r]]==1)\n\t\t\t\tc++;\n\t\t\t\n\t\t}\n\t\tans[Q[i].second]=c;\n\t}\n\tfor(int i=0;i<q;i++)\n\t\tcout<<ans[i]<<\"\\n\";\t\n\n}"
},
{
"alpha_fraction": 0.49250534176826477,
"alphanum_fraction": 0.5235546231269836,
"avg_line_length": 18.081632614135742,
"blob_id": "c42e071a5adaab2377c6a8bc85012d158f6582b1",
"content_id": "4768949d062186c2e869c1007cb3cc503f42c367",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 934,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 49,
"path": "/SPOJ/ALSTEQ.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n//long long int absol(long long int a)\t{return a<0?-a:a;}\n//long long int maximum(long long int a, long long int b)\t{return a>b?a:b;}\nlong long int fun(long long int a[],long long int size)\n{\n\tlong long int dp[5001]={0},M=1;\n\tdp[size-1]=1;\n\t\n\tfor(long long int i=size-2;i>=0;i--)\n\t{\n\t\tlong long int m=1;\n\t\tfor(long long int j=i+1;j<size;j++)\n\t\t{\n\t\t\tif(abs(a[i])<abs(a[j]))\n\t\t\t{\n\t\t\t\tif((a[j]<0&&a[i]>0)||(a[j]>0&&a[i]<0))\n\t\t\t\t{\n\t\t\t\t\tm=max(m,1+dp[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdp[i]=m;\n\t\tM=max(dp[i],M);\n\t\t//cout<<m<<endl;\n\t\t//for(long long int k=0;k<i;k++)\n\t\t//\tcout<<dp[k]<<\"<->\"<<a[k]<<\"\\t\";\n\t\t//cout<<endl;\n\t\t\n\t}\n\t//for(long long int k=0;k<size;k++)\n\t//\t\tcout<<dp[k]<<\"<->\"<<a[k]<<\"\\t\";\n\t//\tcout<<endl;\n\treturn M;\n}\nint main()\n{\n\tlong long int n;\n\tcin>>n;\n\tlong long int a[5001];\n\tfor(long long int i=0;i<n;i++)\n\t\tcin>>a[i];\n\tcout<<fun(a,n)<<endl;\n\n}"
},
{
"alpha_fraction": 0.3903394341468811,
"alphanum_fraction": 0.4738903343677521,
"avg_line_length": 18.64102554321289,
"blob_id": "5f9b0f398037f689ea1d34909420cb158e76e437",
"content_id": "b207af60d40537ac0c366c8f50594346c43af450",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 766,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 39,
"path": "/Codechef/CHEFCOUN.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nunsigned long int lim=4294967295;\n#define MX 4294900000\nvector <unsigned int> v;\nvoid findVal(int n)\n{\n long long int k=(lim-MX)/(n-42949);\n for(int i=0;i<42949;i++)\n v.push_back(100000);\n //v.push_back(10000);\n //cout<<(((lim-MX)-(k*(n-42949)))/2)<<\" \";\n v.push_back(((lim-MX)-(k*(n-42949)))/2);\n for(int i=42950;i<n;i++)\n {\n v.push_back(k);\n //cout<<k<<\" \";\n }\n cout<<endl;\n}\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n v.clear();\n int n;\n cin>>n;\n findVal(n);\n //cout<<v.size()<<endl;\n for(int i=0;i<n;i++)\n cout<<v[i]<<\" \";\n cout<<endl;\n }\n} "
},
{
"alpha_fraction": 0.5111111402511597,
"alphanum_fraction": 0.5472221970558167,
"avg_line_length": 12.884614944458008,
"blob_id": "c0abcc86e720469fb1bda38e6bc16a58bafd4082",
"content_id": "06eb367f15c03421c96a19d36301f85161403668",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 360,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 26,
"path": "/SPOJ/NSTEPS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\nusing namespace std;\nint find_no(int x,int y)\n{\n\tif(x!=y&&x!=y+2)\treturn -1;\n\tif(x%2==0&&y%2==0)\treturn x+y;\n\telse\treturn x+y-1;\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint x,y;\n\t\tcin>>x>>y;\n\t\tint z=find_no(x,y);\n\t\tif(z!=-1)\tcout<<z<<endl;\n\t\telse\t\tcout<<\"No Number\"<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.47843137383461,
"alphanum_fraction": 0.5117647051811218,
"avg_line_length": 16.620689392089844,
"blob_id": "4649d50cd5a08a20c46a9f56836bfd30ab02a39b",
"content_id": "85057975d693742b893485436ec407576005d4a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 510,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 29,
"path": "/SPOJ/OFFSIDE.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint a,d;\n\tcin>>a>>d;\n\twhile(a&&d)\n\t{\n\t\tif(!(a&&d))\tbreak;\n\t\tint *A=new int[a];\n\t\tint *D=new int[d];\n\t\tfor(int i=0;i<a;i++)\tcin>>A[i];\n\t\tfor(int i=0;i<d;i++)\tcin>>D[i];\n\t\tsort(A,A+a);sort(D,D+d);\n\t\tif(A[0]<D[0])\tcout<<\"Y\\n\";\n\t\telse if(A[0]==D[0]&&A[0]<D[1])\tcout<<\"Y\\n\";\n\t\telse if(A[0]>D[0]&&A[0]<D[1])\tcout<<\"Y\\n\";\n\t\telse\tcout<<\"N\\n\";\n\t\tcin>>a>>d;\n\t\t\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4124999940395355,
"alphanum_fraction": 0.5074999928474426,
"avg_line_length": 9.837838172912598,
"blob_id": "0830518b8a1ddd86acf9614b6dec0af725fafdeb",
"content_id": "c9a0c8419211211307e446e8c608131b32194f1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 400,
"license_type": "no_license",
"max_line_length": 20,
"num_lines": 37,
"path": "/SPOJ/ADDREV.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<string>\n#include<string.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\tint t1=0,t2=0;\n\t\twhile(a)\n\t\t{\n\t\t\tt1=t1*10+a%10;\n\t\t\ta/=10;\n\t\t}\n\t\twhile(b)\n\t\t{\n\t\t\tt2=t2*10+b%10;\n\t\t\tb/=10;\n\t\t}\n\t\tint t3=t1+t2,c=0;\n\t\twhile(t3)\n\t\t{\n\t\t\tc=c*10+t3%10;\n\t\t\tt3/=10;\n\t\t}\n\t\tcout<<c<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.48500001430511475,
"alphanum_fraction": 0.5199999809265137,
"avg_line_length": 13.357142448425293,
"blob_id": "8027bba85e9b848cdf05637b9743a57212804cdf",
"content_id": "2564264e6bfd882b96742848410737d7f6d9748c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 200,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 14,
"path": "/SPOJ/GCD.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n'''\t\nt=int(input())\nwhile t != 0:\n\ta, b = map(int, input().split())\n\tdef gcd(x,y):\n\t\tif x==0:\n\t\t\treturn y\n\t\telse:\n\t\t\treturn gcd(y%x,x)\n\tprint (gcd(a,b))\n\tt=t-1"
},
{
"alpha_fraction": 0.43565890192985535,
"alphanum_fraction": 0.4728682041168213,
"avg_line_length": 13.355555534362793,
"blob_id": "082d6aa0f2887752538121b9a2103b6e9d54aa0d",
"content_id": "e692d1cdd5ed15e4d9997611cf0e9c0a7951ff4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 645,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 45,
"path": "/SPOJ/TOANDFRO.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<string>\n#include<string.h>\nusing namespace std;\nint main()\n{\n\tint t,flag=1;\n\tdo{\n\t\tcin>>t;\n\tif(t)\n\t{\n\t\tstring str;\n\t\tcin>>str;\n\t\tint k=str.length()/t;\n\t\tchar p[100][100];\n\t\tfor(int i=0,l=0;i<k&&str[l]!=0;i++)\n\t\t{\tif(i%2)\n\t\t\tfor(int j=t-1;j>=0&&str[l]!=0;j--)\n\t\t\t{//\tcout<<\"j=\"<<j;\n\t\t\t\tp[i][j]=str[l++];\n\t\t\t}\n\t\t\telse\n\t\t\tfor(int j=0;j<t;j++)\n\t\t\t{//\tcout<<\"j=\"<<j;\n\t\t\t\tp[i][j]=str[l++];\n\t\t\t}\n\t\t\t\n\t//\tp[i][t]='\\0';\n\t//cout<<t;\n\t\t}\n\t\tfor(int j=0;j<t;j++)\n\t\t{\n\t\t\tfor(int i=0;i<k;i++)\n\t\t{cout<<p[i][j];\n\t\t\t}\t//cout<<endl;\n\t}cout<<endl;}\n\telse \n\tflag=0;\n\t}while(flag);\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4794520437717438,
"alphanum_fraction": 0.5189363360404968,
"avg_line_length": 15.783783912658691,
"blob_id": "18f8fea8c432e20e62ef9f2a9115e0ca4b556a9d",
"content_id": "3b1b054ed608efc0ca6ccd0828f41a2d21697b50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1241,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 74,
"path": "/SPOJ/BAT1.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n#define inf 999999999999\nvector <int> bc(25);\nvector<vector<int> >cost(25,(vector<int>(25))),rating(25,(vector<int>(25)));\nint N,m,k;\nint dp[25][1001][2];\nint knapsack(int n,int val,bool flag)\n{\n\tif(n==0)\n\t\treturn 0;\n\t//cout<<\"test\\n\";\n\tif(dp[n][val][flag]!=-1)\n\t\treturn dp[n][val][flag];\n\tint v=0;\n\tint withOut=knapsack(n-1,val,0);\n\tif(flag==false&&val>=bc[n])\n\t{\n\t\tval-=bc[n];\n\t\tfor(int i=1;i<=m;i++)\n\t\t{\n\t\t\tif(val>=cost[n][i])\n\t\t\t{\n\t\t\t\tv=max(v,knapsack(n,val-cost[n][i],true)+rating[n][i]);\n\t\t\t}\n\t\t}\n\t\tval+=bc[n];\n\t}\n\telse if(flag)\n\t{\n\t\tfor(int i=1;i<=m;i++)\n\t\t{\n\t\t\tif(val>=cost[n][i])\n\t\t\t{\n\t\t\t\tv=max(v,knapsack(n,val-cost[n][i],flag)+rating[n][i]);\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[n][val][flag]=max(v,withOut);\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\t//ios_base::sync_with_stdio(false);\n\t\tcin>>N>>m>>k;\n\t\tfor(int i=1;i<=N;i++)\n\t\t\tcin>>bc[i];\n\t\t\n\t\tfor(int i=1;i<=N;i++)\n\t\t{\n\t\t\tfor(int j=1;j<=m;j++)\n\t\t\t\tcin>>cost[i][j];\n\t\t}\n\t\tfor(int i=1;i<=N;i++)\n\t\t{\n\t\t\tfor(int j=1;j<=m;j++)\n\t\t\t\tcin>>rating[i][j];\n\t\t}\n\t\tmemset(dp,-1,sizeof(dp));\n\t\t//for(int i=0;i<n*m;i++)\n\t\t//{\n\t\t//\tcout<<cost[i]<<\"\\t\";\n\t\t//}\n\t\t//cout<<endl;\n\t\tcout<<knapsack(N,k,0)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4058919847011566,
"alphanum_fraction": 0.4811784029006958,
"avg_line_length": 19.366666793823242,
"blob_id": "cc18321c66ec40fd67a314c5ca3764874530f778",
"content_id": "50aad26b431fdf6cf2cf63b39e05664de25465a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 611,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 30,
"path": "/Codechef/ZCO12004.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint minCost(vector<int> a, int n)\n{\n vector<int> dp1(n),dp2(n);\n dp1[0]=a[0];\n dp1[1]=a[1]+a[0];\n dp1[2]=a[2]+a[0];\n for(int i=3;i<n;i++)\n dp1[i]=a[i]+min(dp1[i-1],dp1[i-2]);\n int t1=min(dp1[n-1],dp1[n-2]);\n dp2[0]=a[0];\n dp2[1]=a[1];\n for(int i=2;i<n;i++)\n dp2[i]=a[i]+min(dp2[i-1],dp2[i-2]);\n int t2=dp2[n-1];\n return min(t1,t2);\n}\nint main()\n{\n int n;\n cin>>n;\n vector <int> a(n);\n for(int i=0;i<n;i++)\n cin>>a[i];\n cout<<minCost(a,n)<<endl;\n} "
},
{
"alpha_fraction": 0.3296296298503876,
"alphanum_fraction": 0.3481481373310089,
"avg_line_length": 18.7560977935791,
"blob_id": "9e4eacbd485fab3db2605196c5c67680f43748c0",
"content_id": "08308fd0d41d872969110ec72268f9d6bc717453",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 810,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 41,
"path": "/Codechef/SIMDISH.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nmap<string,int> item;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n item.clear();\n string s[4];\n for(int i=0;i<4;i++)\n {\n cin>>s[i];\n item[s[i]]=1;\n }\n for(int i=0;i<4;i++)\n {\n cin>>s[i];\n if(item.find(s[i])!=item.end())\n item[s[i]]++;\n }\n int c=0,f=0;\n for(map<string,int>::iterator i=item.begin();i!=item.end();i++)\n {\n if(i->second>1)\n c++;\n if(c>=2)\n {\n f=1;\n break;\n }\n }\n if(f) cout<<\"similar\\n\";\n else\n cout<<\"dissimilar\\n\";\n }\n} "
},
{
"alpha_fraction": 0.379474937915802,
"alphanum_fraction": 0.4105011820793152,
"avg_line_length": 16.41666603088379,
"blob_id": "42056f127256dd1f8275434baa240e37317e8cbe",
"content_id": "0b3c2aac781ce3e3698e166b01da0b7639d12a65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 419,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 24,
"path": "/Codechef/BANDMATR.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Codechef id - ad2411\n'''\nt=int(input())\nwhile t!=0:\n l=[]\n zero=0\n n=int(input())\n for i in range(n):\n k=list(map(int,input().split()))\n l.append(k)\n zero+=k.count(0)\n # print(l,zero)\n bw=0\n while True:\n if n==0:\n break\n if zero>=n*(n-1):\n break\n else:\n n-=1\n bw+=1\n print(bw)\n t-=1\n "
},
{
"alpha_fraction": 0.5017668008804321,
"alphanum_fraction": 0.5388692617416382,
"avg_line_length": 14.324324607849121,
"blob_id": "6cc3add051a88cb785009c02d6383df399d9bbf8",
"content_id": "264e9cb0d4080ebe76c988560329432387bac635",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 566,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 37,
"path": "/SPOJ/ ANARC05H.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n\nint rec(string s,int p,int prev,int l,vector< vector<int> > dp )\n{\n\tif(p==l)\n\t\treturn 1;\n\tif(dp[p][prev]!=-1)\n\t\treturn dp[p][prev];\n\tint sum=0;\n\tdp[p][prev]=0;\n\tfor(int i=p;i<l;i++)\n\t{\n\t\tsum+=s[i]-48;\n\t\tif(sum>=prev)\n\t\t\tdp[p][prev]+=rec(s,i+1,sum,l,dp);\n\t}\n\treturn dp[p][prev];\n}\nint main()\n{\n\tint i=1;\n\twhile(i++)\n\t{\n\t\tvector< vector<int> > dp(25,vector<int>(226,-1)); \t\n\t\tstring s;\n\t\tcin>>s;\n\t\tif(s==\"bye\")\n\t\t\tbreak;\n\t\tcout<<i-1<<\". \"<<rec(s,0,0,s.length(),dp)<<endl;\n\t}\n\n}"
},
{
"alpha_fraction": 0.5468483567237854,
"alphanum_fraction": 0.5894378423690796,
"avg_line_length": 17.375,
"blob_id": "0f793800ca47a814559e39be1137bd5b5c35f064",
"content_id": "1952be2c192a5b917bb5329c606a7fc282d8419c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 587,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 32,
"path": "/SPOJ/BLCONE.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ndouble bS(int r, int h,double low,double high)\n{\t\n\tdouble mid=low+(high-low)/2;\n\tif(high-low<0.000001)\n\t\treturn mid;\n\t//cout<<mid<<\" \"<<low<<\" \"<<high<<endl;\n\tdouble l=sqrt(r*r+h*h);\n\tif(r*pow(mid,3)+3*mid*mid*l-6*h*h*l<0)\n\t\treturn bS(r,h,mid,high);\n\telse if(r*pow(mid,3)+3*mid*mid*l-6*h*h*l>0)\n\t\treturn bS(r,h,low,mid);\n\telse\n\t\treturn mid;\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint r,h;\n\t\tcin>>r>>h;\n\t\tdouble ans=bS(r,h,0,100);\n\t\tcout<<fixed<<setprecision(6)<<(ans>h?h:ans)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4976378083229065,
"alphanum_fraction": 0.5196850299835205,
"avg_line_length": 14.142857551574707,
"blob_id": "665d71ebeb71da9fc95b734278c117a8e9788d32",
"content_id": "713a7868afaca467892ca2a5c03f2a69594851d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 635,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 42,
"path": "/SPOJ/MAJOR.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include <algorithm>\n#include <stdio.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,count=1,flag=0;\n\t\tscanf(\"%lld\",&n);\n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int i=0;i<n;i++)\n\t\t\tscanf(\"%lld\",&a[i]);\n\t\tsort(a,a+n);\n\t\tfor(long long int i=0;i<n-1;i++)\n\t\t{\n\t\t\tif(a[i]==a[i+1])\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\telse\tcount=1;\n\t\t\tif(count>n/2)\n\t\t\t\t{\n\t\t\t\t\tflag=1;\n\t\t\t\t\tprintf(\"YES %lld\\n\",a[i]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\n\t\t//\tcout<<count<<\" \"<<flag<<endl;\n\t\t}\n\t\tif(!flag)\tprintf(\"NO\\n\");\n\t\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.511904776096344,
"alphanum_fraction": 0.5654761791229248,
"avg_line_length": 13.083333015441895,
"blob_id": "488e46ec4c2d492b0d26bffd2f1109efe12f07f6",
"content_id": "97875e4594067585c3f2ae674a7b4c0b25bd6d30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 168,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 12,
"path": "/SPOJ/FCTRL2.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n'''\t\n# your code goes here\na=int(input())\nfor j in range(1,a+1):\n\tf=1\n\tb=int(input())\n\tfor i in range(1,b+1):\n\t\tf=f*i\n\tprint(f)"
},
{
"alpha_fraction": 0.5190839767456055,
"alphanum_fraction": 0.5534350872039795,
"avg_line_length": 14.411765098571777,
"blob_id": "64709212871164c61035010554efb0dfd1b03263",
"content_id": "b7fddb6d9dd3cf3aa728f47474543b1fec542450",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 524,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 34,
"path": "/SPOJ/BALLSUM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint gcd(long long int a,long long int b)\n{\n\tif(a==0)\n\t\treturn b;\n\treturn gcd(b%a,a);\n}\nvoid ballSum(long long int n,long long int k)\n{\n\tlong long int dm=n*(n-1),nm;\n\tnm=k%2==0?(k-2)*k/2:(k-1)*(k-1)/2;\n\tint g=gcd(nm,dm);\n\tif(nm!=0&&nm!=dm)\n\t\tcout<<nm/g<<\"/\"<<dm/g<<endl;\n\telse if(nm==dm)\n\t\tcout<<\"1\"<<endl;\n\telse cout<<\"0\"<<endl;\n}\nint main()\n{\n\twhile(1)\n\t{\n\t\tlong long int n,k;\n\t\tcin>>n>>k;\n\t\tif(n==-1)\n\t\t\tbreak;\n\t\tballSum(n,k);\n\t}\n}\n"
},
{
"alpha_fraction": 0.4855072498321533,
"alphanum_fraction": 0.5,
"avg_line_length": 9.921052932739258,
"blob_id": "678b2a0ab94df74a15bf63dc9fa11f72f1effc3c",
"content_id": "7ef1ca2720bcd5feeb5521dfca9e2ce90e60c734",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 414,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 38,
"path": "/SPOJ/TWOSQRS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvoid twoSq(long long int n)\n{\n\tlong long int i=sqrt(n),j=0;\n\twhile(i>0)\n\t{\n\t\tif(j*j>n)\n\t\t{\n\t\t\tcout<<\"No\\n\";\n\t\t\tbreak;\n\t\t}\n\t\tif(i*i+j*j==n)\n\t\t{\n\t\t\tcout<<\"Yes\\n\";\n\t\t\tbreak;\n\t\t}\n\t\telse if(i*i+j*j<n)\n\t\t\tj++;\n\t\telse\n\t\t\ti--;\n\t}\n}\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\ttwoSq(n);\n\t}\n}"
},
{
"alpha_fraction": 0.4259740114212036,
"alphanum_fraction": 0.4675324559211731,
"avg_line_length": 12.310344696044922,
"blob_id": "deb44896fa05514079a76e147af5554403fb2d3f",
"content_id": "bb2cb1e6b246e67119b76f4333f8fc4fa5010287",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 29,
"path": "/SPOJ/CANTON.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,i=0,k;\n\t\tcin>>n;\n\t\twhile(1)\n\t\t{\n\t\t\tif(2*n<=i*(i+1))\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tlong long int ul=i*(i+1)/2,ll=i*(i-1)/2+1;\n\t\tif(i%2==0)\n\t\t\tk=abs(ll-n);\n\t\telse\n\t\t\tk=abs(ul-n);\n\t\tcout<<\"TERM \"<<n<<\" IS \"<<(1+k)<<\"/\"<<(i-k)<<endl;\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.3161592483520508,
"alphanum_fraction": 0.37704917788505554,
"avg_line_length": 18.363636016845703,
"blob_id": "6e03aa2a2fb49886e818c5d7f5f5f9b4375b8cb1",
"content_id": "c9c7c7fb94d32641f46692afc25c704deaf2a55a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 427,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 22,
"path": "/Codechef/CHEFAPAR.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Codechef id - ad2411\n'''\nt=int(input())\nwhile t!=0:\n n=int(input())\n sum=0\n a=list(input().split())\n flag=1\n for i in range(0,n):\n if flag==1 and a[i]=='0':\n flag=0\n if flag==0:\n if a[i]=='1':\n sum+=100\n else:\n sum+=1100\n else:\n if a[i]=='0':\n sum+=1000\n print(sum)\n t-=1\n "
},
{
"alpha_fraction": 0.47689464688301086,
"alphanum_fraction": 0.5064694881439209,
"avg_line_length": 14.05555534362793,
"blob_id": "bb15891ac8132f2a13397f564c036d8f4e1bbbef",
"content_id": "4ae284f07a1eba2260a52dc1847ec1e695361c41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 541,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 36,
"path": "/SPOJ/DBALLZ.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint distractTime(int e,int b[],int t[],int n)\n{\n\tvector<int> dp(1000001,0);\n\tfor(int i=0;i<=e;i++)\n\t{\n\t\tfor(int j=0;j<n;j++)\n\t\t{\n\t\t\tif(b[j]<=i)\n\t\t\t\tdp[i]=max(t[j]+dp[i-b[j]],dp[i]);\n\t\t}\n\t\t//cout<<dp[i]<<\"\\t\";\n\t}\n\treturn dp[e];\n}\nint main()\n{\n\tint tc;\n\tcin>>tc;\n\twhile(tc--)\n\t{\n\t\tint e,n;\n\t\tcin>>e>>n;\n\t\tint *b=new int[n],*t=new int[n];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>b[i];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>t[i];\n\t\tcout<<distractTime(e,b,t,n)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.2610441744327545,
"alphanum_fraction": 0.2871485948562622,
"avg_line_length": 21.133333206176758,
"blob_id": "ddeac28eda8bf2cbcf64c7cbb2956cac7c475ca7",
"content_id": "d74f080183acb652fa59fe0e1bf25be25c7274f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 996,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 45,
"path": "/Codechef/CHSQR.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n \nint main() {\n // your code goes here\n int t;\n cin>>t;\n while(t--)\n {\n int n;\n cin>>n;\n int a[500][500];\n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++)\n { if(i>j)\n {\n if(i-j==n/2) a[i][j]=1;\n else if(i-j==n-1) a[i][j]=n/2+1;\n else\n a[i][j]=n-(i-j);\n \n }\n else if(j>i)\n {\n if(j-i==(n+1)/2) a[i][j]=1;\n else if(j-i==1) a[i][j]=n/2+1;\n else a[i][j]=j-i;\n }\n else a[i][j]=n;\n \n } for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n \n }\n }\n \n return 0;\n} "
},
{
"alpha_fraction": 0.467048704624176,
"alphanum_fraction": 0.5300859808921814,
"avg_line_length": 13,
"blob_id": "3f10af1918345297219c288dbbd91cd19447943f",
"content_id": "51cdc14240d630f2a7641aa448e059e1aaf740c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 349,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 25,
"path": "/SPOJ/TRICOUNT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint m;\n\tcin>>m;\n\twhile(m--)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\tlong long int t;\n\t\tif(n%2)\n\t\tt=n*(n+1)*(n+2)/6+(n*n-1)*(2*n+3)/24;\n\t\telse\n\t\tt=n*(n+1)*(n+2)/6+n*(n+2)*(2*n-1)/24;\n\t\tcout<<t<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5033783912658691,
"alphanum_fraction": 0.525337815284729,
"avg_line_length": 14.20512866973877,
"blob_id": "4c71086274d2fb255993a83b3d1617163857eebf",
"content_id": "05e6eeb255cb07dda519e290ec0532c28d968469",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 592,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 39,
"path": "/SPOJ/CANDY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\twhile(cin>>t)\n\t{\tif(t==-1)\tbreak;\n\t\tint *a=new int[t];\n\t\tfloat sum=0;\n\t\tint count=0;\n\t\tfor(int i=0;i<t;i++)\n\t\t{\t\n\t\t\tcin>>a[i];\n\t\t\tsum+=a[i];\n\t\t}\n\t\tfloat avg=sum/t;\n\t\tif(floor(avg)==avg)\n\t\t{\n\t\t\tint temp=0;\n\t\t\tsort(a,a+t);\n\t\t\tfor(int i=t-1;i>=0;i--)\n\t\t\t{\n\t\t\t\tif(a[i]>avg)\t{temp+=a[i]-avg;a[i]=avg;}\n\t\t\t\telse\t\t\t{count+=avg-a[i];temp-=avg-a[i];a[i]=avg;}\n\t\t\t}\n\t\tcout<<count<<endl;\n\t\t}\n\t\telse\n\t\tcout<<\"-1\"<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.40730592608451843,
"alphanum_fraction": 0.4630137085914612,
"avg_line_length": 16.125,
"blob_id": "c563b65310010791973a587b9bff86d4250ade59",
"content_id": "21ed78a4a493b72d239faf15b583f56608a3ec2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1095,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 64,
"path": "/SPOJ/BISHOPS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<string.h>\nusing namespace std;\nvoid swap(char &a,char &b)\n{\n\t//cout<<\"test\";\n\tchar temp=a;\n\ta=b;\n\tb=temp;\n\t//cout<<a<<\" \"<<b<<endl;\n}\nint main() {\n\t// your code goes here\n//\tint t;\n//\tcin>>t;\n\n\t\tchar s[500],a[500];\n\t\twhile(cin>>s)\n\t\t{\n\t\t\t\tif(!strcmp(s,\"0\"))\t{cout<<\"18\"<<endl;continue;}\n\t\t\t\tif(!strcmp(s,\"1\"))\t{cout<<\"1\"<<endl;continue;}\n\t\t\t\tint p,j=0,c=0;\n\t\tfor(int i=strlen(s)-1;i>=0;i--)\n\t\t{\ta[j]=0;\n\t\t\tp=2*(s[i]-48);\n\t\t//\tcout<<p<<endl;\n\t\t\ta[j++]=(p+c)%10+48;\n\t\t\tc=(p+c)/10;\n\t\t}\n\t\tif(c)\ta[j++]=c+48;\n\t\ta[j]='\\0';\n\t\t//cout<<\"j=\"<<j<<endl;\n\t\t//cout<<a<<endl;\n\t//\tcout<<strlen(a)<<endl;\n\tint x=a[0]-48,i=1;\n\t\tif(x-2>=0)\ta[0]=x-2+48;\n\t\telse\n\t\t{\n\t\t\ta[0]=a[0]+10-2;\n\t\twhile(1)\n\t\t{\tif(a[i]==48)\t{a[i++]='9';continue;}\n\t\t\tif(!a[i])\tbreak;\n\t\t\ta[i]-=1;\n\t\t\tif(a[i]>=48)\tbreak;\n\t\t\ti++;\n\t\t}\n\t\ti=strlen(a)-1;\n\t\twhile(a[i]==48)\n\t\t\ta[i--]='\\0';\n\t\t}\n\t\t//cout<<a<<endl;\n\t\tfor(int i=strlen(a)-1,k=0;k<=i;i--,k++)\n\t\t{//\tcout<<a[i]<<\" \"<<a[k]<<endl;\n\t\t\tswap(a[i],a[k]);\n\t\t//\tcout<<a[i]<<\" \"<<a[k]<<endl;\n\t\t}\n\tcout<<a<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.409030556678772,
"alphanum_fraction": 0.4515272378921509,
"avg_line_length": 13.216980934143066,
"blob_id": "8aabd1a7d064134b59d3b503acf0e28884871d76",
"content_id": "e505e7d6ba4268a35ce51cb16ebfe3e5768851c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1506,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 106,
"path": "/SPOJ/ADAGAME.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint origi;\nint dp[10000][101];\nint fun(string s,int n,int player)\t//1->vint,0->ada\n{\n\t\n\t//cout<<s<<endl;\n\t\n\tif(dp[stoi(s)][n]!=-1)\n\t\treturn dp[stoi(s)][n];\n\tstring str=s;\n\tif(n==1)\n\t{\n\t\tif(player==1)\n\t\t{\n\t\t\tfor(int i=0;i<4;i++)\n\t\t\t{\n\t\t\t\t\n\t\t\t\ts[i]=s[i]!='9'?s[i]+1:'0';\n\n\t\t\t\tif(stoi(s)<=origi)\n\t\t\t\t{\n\t\t\t\t\tdp[stoi(s)][n]=1;\n\t\t\t\t\treturn dp[stoi(s)][n];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ts=str;\n\t\t\t}\n\t\t\tdp[stoi(s)][n]=0;\n\t\t\treturn dp[stoi(s)][n];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i=0;i<4;i++)\n\t\t\t{\n\t\t\t\ts[i]=s[i]!='9'?s[i]+1:'0';\n\t\t\t\tif(stoi(s)>origi)\n\t\t\t\t{\n\t\t\t\t\tdp[stoi(s)][n]=0;\n\t\t\t\t\treturn dp[stoi(s)][n];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ts=str;\n\t\t\t}\n\t\t\tdp[stoi(s)][n]=1;\n\t\t\treturn dp[stoi(s)][n];\n\t\t}\n\t}\n\tif(player==1)\n\t{\n\t\tfor(int i=0;i<4;i++)\n\t\t{\n\t\t\ts[i]=s[i]!='9'?s[i]+1:'0';\n\t\t\tif(fun(s,n-1,0)==1)\n\t\t\t{\n\t\t\t\tdp[stoi(s)][n]=1;\n\t\t\t\treturn dp[stoi(s)][n];\n\t\t\t}\n\t\t\telse\n\t\t\t\ts=str;\n\t\t}\n\t\tdp[stoi(s)][n]=0;\n\t\treturn dp[stoi(s)][n];\n\t}\n\tfor(int i=0;i<4;i++)\n\t{\n\t\ts[i]=s[i]!='9'?s[i]+1:'0';\n\t\tif(fun(s,n-1,1)==0)\n\t\t{\n\t\t\tdp[stoi(s)][n]=0;\n\t\t\treturn dp[stoi(s)][n];\n\t\t}\n\t\telse\n\t\t\ts=str;\n\t}\n\tdp[stoi(s)][n]=1;\n\treturn dp[stoi(s)][n];\n\n}\nint main()\n{\n\tios::sync_with_stdio(false);\n\tint x;\n\tcin>>x;\n\twhile(x--)\n\t{\n\t\tmemset(dp,-1,sizeof(dp));\n\t\tstring a;\n\t\tint n;\n\t\tcin>>a>>n;\n\t\torigi=0;\n\t\tfor(int i=0;i<4;i++)\n\t\t\torigi+=(a[i]-48)*pow(10,3-i);\n\t\t//cout<<origi<<endl;\n\t\tif(n==0)\n\t\t\tcout<<\"Vinit\"<<'\\n';\n\t\telse\n\t\t\tcout<<(fun(a,n,0)==1?\"Vinit\":\"Ada\")<<'\\n';\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.47713005542755127,
"alphanum_fraction": 0.5228699445724487,
"avg_line_length": 17.295082092285156,
"blob_id": "202c6c543c7da60caa055420561e68152c74c2c1",
"content_id": "a7ec91f02e4a3630d68cb67f81e45fd44d1926b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1115,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 61,
"path": "/SPOJ/BYTESM2.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int dp[1000][1000];\nlong long int max(long long int a, long long int b,long long int c)\n{\n\treturn max(max(a,b),c);\n}\nvoid initVal(int a[][100],int h,int w)\n{\n\tfor(int i=0;i<h;i++)\n\t\tfor(int j=0;j<w;j++)\n\t\t{\n\t\t\tif(i==0)\n\t\t\t\tdp[i][j]=a[i][j];\n\t\t\telse\n\t\t\t\tdp[i][j]=-1;\n\t\t}\n}\nlong long int stones(int a[][100],int i,int j,int h,int w)\n{\n\tif(i==h)\n\t\treturn 0;\n\tif(dp[i][j]!=-1)\n\t\treturn dp[i][j];\n\telse\n\t{\n\t\tif(j==0)\n\t\t\tdp[i][j]=a[i][j]+max(stones(a,i-1,j,h,w),stones(a,i-1,j+1,h,w));\n\t\telse if(j==w-1)\n\t\t\tdp[i][j]=a[i][j]+max(stones(a,i-1,j,h,w),stones(a,i-1,j-1,h,w));\n\t\telse\n\t\t\tdp[i][j]=a[i][j]+max(stones(a,i-1,j-1,h,w),stones(a,i-1,j,h,w),stones(a,i-1,j+1,h,w));\n\t}\n\treturn dp[i][j];\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint h,w;\n\t\tcin>>h>>w;\n\t\tint a[100][100];\n\t\tfor(int i=0;i<h;i++)\n\t\t\tfor(int j=0;j<w;j++)\n\t\t\t\tcin>>a[i][j];\n\t\tinitVal(a,h,w);\n\t\tfor(int i=0;i<w;i++)\n\t\t\tstones(a,h-1,i,h,w);\n\t\tlong long int max=0;\n\t\tfor(int i=0;i<w;i++)\n\t\t\tif(max<dp[h-1][i])\n\t\t\t\tmax=dp[h-1][i];\n\t\tcout<<max<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4559386968612671,
"alphanum_fraction": 0.48275861144065857,
"avg_line_length": 12.410256385803223,
"blob_id": "a0aed4a94daac510c05d4eb9b5d9ed45fd0835a7",
"content_id": "ab11114bed7bf996726c8f749e800015b93d7bfd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 522,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 39,
"path": "/SPOJ/ONP.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include <stack>\n#include <string>\n#include <ctype.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring s;\n\t\tstack<char> s1;\n\t\tcin>>s;\n\t\tfor(int i=0;s[i]!='\\0';i++)\n\t\t{\n\t\t\tif(isalpha(s[i]))\tcout<<s[i];\n\t\t\telse if(s[i]!=')')\ts1.push(s[i]);\n\t\t\telse\n\t\t\t\twhile(1)\n\t\t\t\t{\n\t\t\t\t\tif(s1.top()=='(')\t\n\t\t\t\t\t{\n\t\t\t\t\t\ts1.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcout<<s1.top();\n\t\t\t\t\ts1.pop();\n\t\t\t\t}\n\t\t}\n\t\tcout<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5324074029922485,
"alphanum_fraction": 0.5509259104728699,
"avg_line_length": 12.967741966247559,
"blob_id": "439edd442c5e3690e3d8716dfc010512b1235a05",
"content_id": "80f5b2e1545430e58fc33498c9a76e0574c3b7c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 432,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 31,
"path": "/SPOJ/CANDY3.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\n#include<cmath>\nusing namespace std;\n\nint main() {\n\t// your code goes hereint t;\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,i;\n\t\tlong long int sum=0;\n\t\tcin>>n;\n\t\tlong long int *a=new long long int[n];\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>a[i];\n\t\t\tsum+=a[i];\n\t\t\tsum%=n;\n\t\t}\n\t\tif(sum==0)\t\tcout<<\"YES\"<<endl;\n\t\telse\t\t\t\tcout<<\"NO\"<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.46504560112953186,
"alphanum_fraction": 0.5197568535804749,
"avg_line_length": 10.379310607910156,
"blob_id": "e688c5c91ca286209b82e945a8f485cb4204f618",
"content_id": "9be69c94b9ba0c96020811fa12ebfc6deb992a3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 329,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 29,
"path": "/SPOJ/HANGOVER.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\nusing namespace std;\nint main()\n{\n\tfloat t;\n\tint flag=1;\n\tdo\n\t{\t\n\t\tcin>>t;\n\t\tif(t!=0.00)\n\t\t{\n\t\t\tfloat sum=0.00;\n\t\t\tint i=1;\n\t\t\twhile(sum<t)\n\t\t\t{\n\t\t\t\tsum+=1.00/++i;\n\t\t\t}\n\t\t\tcout<<i-1<<\" card(s)\"<<endl;\n\t\t}\n\t\telse\n\t\tflag=0;\n\t}while(flag);\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.28671327233314514,
"alphanum_fraction": 0.3188811242580414,
"avg_line_length": 17.33333396911621,
"blob_id": "53c8df0746a2afdcc53b7eb12b506be8f1912d92",
"content_id": "67428986b60f7625a12f09b0d8d39da11219ddb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 715,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 39,
"path": "/Codechef/ZCO12001.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n,temp,p1=1,M1=0,M=0,flag=0,pos=1,m=0;\n cin>>n;\n vector<int> a(n+1);\n for(int i=1;i<=n;i++)\n cin>>a[i];\n int i=1;\n stack<int> s;\n while(i<=n)\n {\n if(a[i]==1)\n {\n M++;\n if(M>M1)\n M1=M,p1=i;\n s.push(i);\n \n }\n else\n {\n M--;\n if(m<i-s.top()+1)\n {\n //cout<<\"i=\"<<i<<endl;\n m=i-s.top()+1;\n pos=s.top();\n }\n s.pop();\n }\n i++;\n }\n cout<<M1<<\" \"<<p1<<\" \"<<m<<\" \"<<pos<<endl;\n} "
},
{
"alpha_fraction": 0.5210792422294617,
"alphanum_fraction": 0.5531197190284729,
"avg_line_length": 17,
"blob_id": "bad78377e70b0f2f02e07c23e2ea5233e5c51317",
"content_id": "b1f2b55551e1e02c097d5440f86ccbcfa904f667",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 593,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 33,
"path": "/SPOJ/TRT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef vector <long long int> row;\ntypedef vector <row> dp;\nlong long int treatsForCows(long long int a[],int n)\n{\n\tdp d(n+1,row(n+1,0));\n\tlong long int age=1,m=0;\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tfor(int j=0;j<=i;j++)\n\t\t{\n\t\t\tint r=j;\n\t\t\tint c=i-j;\n\t\t\td[r][c]=max(c>0?d[r][c-1]+(i)*a[n-(c)]:0,r>0?d[r-1][c]+(i)*a[r-1]:0);\n\t\t\tm=max(m,d[r][c]);\n\t\t}\n\t}\n\treturn m;\n}\nint main()\n{\n\tint n,val;\n\tcin>>n;\n\tlong long int *a=new long long int[n];\t\n\tfor(int i=0;i<n;i++)\n\t\tcin>>a[i];\n\tcout<<treatsForCows(a,n)<<endl;\n}"
},
{
"alpha_fraction": 0.5433962345123291,
"alphanum_fraction": 0.5660377144813538,
"avg_line_length": 12.300000190734863,
"blob_id": "c9fe64e6c63b7696fcd1fb53bfd99f149e664b1c",
"content_id": "ee355cf39f650e3d5eab590f759cea504e203f91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 20,
"path": "/SPOJ/HUBULLU.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\tif(b==0)\tcout<<\"Airborne wins.\\n\";\n\t\telse\t\tcout<<\"Pagfloyd wins.\\n\";\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5352941155433655,
"alphanum_fraction": 0.5847058892250061,
"avg_line_length": 15.34615421295166,
"blob_id": "daaf5cb4fc0bd04b6f9cdb415d89ad02b21212d9",
"content_id": "c88edc5964a37de15bbe5e9a3e08ca4770fbb2c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 850,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 52,
"path": "/SPOJ/APS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nstd::vector<unsigned long long int> value(10000000,0);\nvoid seive(unsigned long long int n=10000000)\n{\n\n\tvalue[0]=0;\n\tvalue[1]=0;\t\n\tstd::vector<bool> p(n+1,true);\n\tfor(unsigned long long int i=2;i<=sqrt(n);i++)\n\t{\n\t\tif(p[i])\n\t\t{\n\t\t\tvalue[i]=i+value[i-1];\n\t\t\tfor(unsigned long long int j=i*2;j<=n;j+=i)\n\t\t\t{\n\t\t\t\t\tp[j]=false;\n\t\t\t\t\tvalue[j]=(value[j]==0?i:value[j]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tvalue[i]+=value[i-1];\n\t}\n\tfor(unsigned long long int i=sqrt(n)+1;i<=n;i++)\n\t{\n\t\tif(p[i])\tvalue[i]=i+value[i-1];\n\t\telse\n\t\t\t\t\tvalue[i]+=value[i-1];\n\t\t\n\t}\n}\nunsigned long long int aps(unsigned long long int n)\n{\n\treturn value[n];\n}\nint main()\n{\n\tseive(10000000);\n\tunsigned long long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tunsigned long long int n;\n\t\tcin>>n;\n\t\tcout<<aps(n)<<endl;\n\t\n\t}\n}\n"
},
{
"alpha_fraction": 0.5232558250427246,
"alphanum_fraction": 0.5406976938247681,
"avg_line_length": 12.269230842590332,
"blob_id": "e1bf06461912cd8389cb172ff2aa82b2d1a046c2",
"content_id": "a3f3384b69d99e14a2f0d92c3ab73769145dfc6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 26,
"path": "/SPOJ/ENIGMATH.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\nint gcd(int a,int b)\n{\n\tif(a==0)\treturn b;\n\tif(b>a)\t\treturn gcd(b%a,a);\n\telse \t\treturn gcd(a%b,b);\n}\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\tint k=gcd(a,b);\n\t\tcout<<b/k<<\" \"<<a/k<<endl;\n\t\t\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.458781361579895,
"alphanum_fraction": 0.5035842061042786,
"avg_line_length": 12.634146690368652,
"blob_id": "9556546a2721fd874e7299dbca945e638f31c4da",
"content_id": "c73a97a83717942716ac82f65d081e045a19a1da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 41,
"path": "/SPOJ/HPYNOS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\n#include<map>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t,sum=0,count=0,flag=0;\n\tcin>>t;\n\tint t1=t;\n\tmap <int,int> a;\n\ta.clear();\n\twhile(1)\n\t{\t\n\t\tif(a.find(t1)!=a.end())\tbreak;\n\t\tsum+=(t%10)*(t%10);\n\t\tt/=10;\n\t\t//cout<<t<<\" \";\n\t\tif(t==0)\n\t\t{//\tcout<<sum<<\"\\n\";\n\t\t\tif(sum==1)\n\t\t\t{\tcount++;\n\t\t\t\tflag=1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\tcount++;\n\t\t\t\ta[t1]=t1;\n\t\t\t\tt=t1=sum;\n\t\t\t\tsum=0;\n\t\t\t}\n\t\t}\n\t}\n\tif(flag)\tcout<<count<<endl;\n\telse\t\tcout<<\"-1\"<<endl;\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4897959232330322,
"alphanum_fraction": 0.545918345451355,
"avg_line_length": 13.035714149475098,
"blob_id": "f8d15ab0e59109882b88b306c95292a3762f23cf",
"content_id": "1110f9828ed7d597aeb70fc3609348ae3ae463b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 392,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 28,
"path": "/SPOJ/LASTDIG2.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\n#include<string>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring a;\n\t\tlong long int z,b;\n\t\tcin>>a>>b;\n\t\tif(b%4)\n\t\tz=pow(((a[a.length()-1]-48)%10),((b%4)));\n\t\telse if(b==0)\n\t\tz=1;\n\t\telse\n\t\tz=pow(((a[a.length()-1]-48)%10),4);\n\t\tcout<<z%10<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5206286907196045,
"avg_line_length": 13.352112770080566,
"blob_id": "fd4a9097857e1da3731cda1e9b6eacffd97e7bc1",
"content_id": "41db67c385b5d2f89c1c7a0bb1cb09eb83b1731a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1018,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 71,
"path": "/SPOJ/CODESPTB.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\nll merge(ll ar[],ll low,ll high)\n{\n\tll inv=0;\n\tll mid=low+(high-low)/2;\n\tll *l=new ll[mid-low+1];\n\tll *r=new ll[high-mid];\n\tll i=0;\n\tfor(ll j=low;j<=mid;j++,i++)\n\t\tl[i]=ar[j];\n\ti=mid+1;\n\tfor(ll j=0;i<=high;j++,i++)\n\t\tr[j]=ar[i];\n\t\n\tll k=low;\n\tll j=0;\n\ti=0;\n\twhile(i<mid-low+1&&j<high-mid)\n\t{\n\t\tif(r[j]<l[i])\n\t\t{\n\t\t\tar[k++]=r[j++];\n\t\t\tinv+=mid-low+1-i;\n\t\t}\n\t\telse\n\t\t\tar[k++]=l[i++];\n\t}\n\twhile(j<high-mid)\n\t{\n\t\tar[k++]=r[j++];\n\t\t\n\t}\n\twhile(i<mid-low+1){\n\t\tar[k++]=l[i++];\n\t\t\n\t}\n\t//cout<<low<<\" \"<<high<<\" \"<<inv<<endl;\n\treturn inv;\n\n}\nll mergeSort(ll ar[],ll low,ll high)\n{\n\tif(low<high)\n\t{//cout<<\"test\\n\";\n\t\tll mid=low+(high-low)/2;\n\t\tll inv=mergeSort(ar,low,mid)+mergeSort(ar,mid+1,high);\n\t\tinv+=merge(ar,low,high);\n\t\treturn inv;\n\t}\n\treturn 0;\n}\nint main()\n{\n\tll t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tll n;\n\t\tcin>>n;\n\t\tll *a=new ll[n];\n\t\tfor(ll i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tcout<<mergeSort(a,0,n-1)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4575342535972595,
"alphanum_fraction": 0.4917808175086975,
"avg_line_length": 21.8125,
"blob_id": "629d58484351c6bd285eb0aa6cea0d8afab734cc",
"content_id": "294cc946e660de40c477c26264404e5a9cc877c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 730,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 32,
"path": "/Codechef/ZCO14004.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int findVal(vector <long long int> v,long long int n)\n{\n vector <long long int> dp(n,0);\n dp[n-1]=v[n-1],dp[n-2]=v[n-2]+v[n-1];\n dp[n-3]=max(v[n-1]+v[n-3],max(dp[n-2],v[n-2]+v[n-3]));\n long long int m=dp[n-3];\n for(long long int i=n-4;i>=0;i--)\n {\n dp[i]=max(v[i]+v[i+1]+dp[i+3],max(v[i]+dp[i+2],dp[i+1]));\n m=max(m,dp[i]);\n }\n /*for(int i=0;i<n;i++)\n {\n cout<<dp[i]<<\" \";\n }*/\n cout<<endl;\n return m;\n}\nint main()\n{\n long long int n;\n cin>>n;\n vector<long long int> v(n);\n for(long long int i=0;i<n;i++)\n cin>>v[i];\n cout<<findVal(v,n)<<endl;\n} "
},
{
"alpha_fraction": 0.394779771566391,
"alphanum_fraction": 0.4551386535167694,
"avg_line_length": 14.531645774841309,
"blob_id": "c61ade52aabd585984cabf25fb995eed5d3b60ac",
"content_id": "62937b4a0051a6991d5b55602f02fb6284f4a5bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1226,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 79,
"path": "/SPOJ/ADFRUITS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvoid lcs(string s1,string s2)\n{\n\t\n\tint dp[s1.length()+1][s2.length()+1];\n\tdp[0][0]=0;\n\tfor (int i=0;i<=s1.length();i++)\n\t\tfor(int j=0;j<=s2.length();j++)\n\t\t{\n\t\t\tif(i==0||j==0)\n\t\t\t\tdp[i][j]=0;\n\t\t\telse if(s1[i-1]==s2[j-1])\n\t\t\t{\n\t\t\t\tdp[i][j]=1+dp[i-1][j-1];\n\t\t\t}\n\t\t\telse\n\t\t\t\tdp[i][j]=max(dp[i-1][j],dp[i][j-1]);\n\t\t}\n\t\t\n\t\tint length=dp[s1.length()][s2.length()];\n\t\t//cout<<length<<endl;\n\t\tchar s[length];\n\t\ts[length]='\\0';\n\t\tint i=s1.length(),j=s2.length();\n\t\twhile(i>0&&j>0)\n\t\t{\n\t\t\tif(s1[i-1]==s2[j-1])\n\t\t\t{\n\t\t\t\ts[--length]=s1[i-1];\n\t\t\t\ti--;\n\t\t\t\tj--;\n\t\t\t}\n\t\t\telse if(dp[i-1][j]>dp[i][j-1])\n\t\t\t\ti--;\n\t\t\telse\n\t\t\t\tj--;\n\t\t}\n\t\t//cout<<s<<endl;\n\t\tchar S[10000];\n\t\tint k=0,l=0;\n\t\ti=0,j=0;\n\t\twhile(i<s1.length()||j<s2.length())\n\t\t{\n\t\t\tif(i<s1.length()&&s1[i]!=s[k])\n\t\t\t{\n\t\t\t\tS[l++]=s1[i++];\n\t\t\t}\n\t\t\telse if(j<s2.length()&&s2[j]!=s[k])\n\t\t\t{\n\t\t\t\tS[l++]=s2[j++];\n\t\t\t}\n\t\t\telse if(i<s1.length()&&j<s2.length()&&s1[i]==s[k]&&s2[j]==s[k])\n\t\t\t{\n\t\t\t\tS[l++]=s[k++];\n\t\t\t\ti++;j++;\n\t\t\t}\n\n\t\t}\n\t\tS[l]='\\0';\n\t\tcout<<S<<endl;\n\n}\nint main(int argc, char const *argv[])\n{\n\t/* code */\n\tstring s1,s2;\n\twhile(cin>>s1>>s2)\n\t{\n\n\t\t//cout<<s2;\n\t\tlcs(s1,s2);\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5272108912467957,
"alphanum_fraction": 0.5467687249183655,
"avg_line_length": 20.01785659790039,
"blob_id": "aaf5f40eabf5ed6061750483ed25cc78121a9445",
"content_id": "ee881bc6490786892cdf6f07edeaf75be3ec710b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1176,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 56,
"path": "/SPOJ/ABCDEF.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n//map<long long int,long long int> lhs,rhs;\nlong long int calVal(int a[],int n)\n{\n\tlong long int count=0;\n\tvector <long long int> LHS,RHS;\n\tfor(int i=0;i<n;i++)\n\t\tfor(int j=0;j<n;j++)\n\t\t\tfor(int k=0;k<n;k++)\n\t\t\t{\t\n\t\t\t\tlong long int l=a[i]*a[j]+a[k];\n\t\t\t\tLHS.push_back(l);\n\t\t\t\tif(a[k]!=0)\n\t\t\t\t{\t\n\t\t\t\t\tlong long int r=(a[i]+a[j])*a[k];\t\n\t\t\t\t\tRHS.push_back(r);\n\t\t\t\t}\t\n\t\t\t\t//lhs[l]++;\n\t\t\t\t//rhs[r]++;\n\t\t\t\t\n\t\t\t}\n\tsort(LHS.begin(),LHS.end());\n\tsort(RHS.begin(),RHS.end());\n\tfor(vector<long long int >::iterator i=LHS.begin();i!=LHS.end();)\n\t{\n\t\tvector<long long int>::iterator u1,u2,l2=lower_bound(RHS.begin(),RHS.end(),*i);\n\t\tu1=upper_bound(LHS.begin(),LHS.end(),*i);\n\t\tif(l2!=RHS.end()){\n\t\t\tu2=upper_bound(RHS.begin(),RHS.end(),*i);\n\t\t\tcount+=(u1-i)*(u2-l2);\n\t\t\t//cout<<count<<endl;\n\t\t\t//cout<<u1-i<<\" \"<<u2-l2<<endl;\n\t\t}\n\t\ti=u1;\n\t}\n\t/*for(map<long long int,long long int>::iterator i=rhs.begin();i!=rhs.end();i++)\n\t{\n\t\t\tcount+=lhs[i->first]*(i->second);\n\t}*/\n\treturn count;\n\n}\nint main()\n{\n\tint n;\n\tcin>>n;\n\tint *a=new int[n];\n\tfor(int i=0;i<n;i++)\n\t\tcin>>a[i];\n\tcout<<calVal(a,n)<<endl;\n}"
},
{
"alpha_fraction": 0.35742443799972534,
"alphanum_fraction": 0.40735873579978943,
"avg_line_length": 19.594594955444336,
"blob_id": "626c2820fd2fe2b9a96ce086c4af00e2941693fe",
"content_id": "543f6e3f68b42985fe9afb38ef91884b95e2f6f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 761,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 37,
"path": "/SPOJ/NY10A.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,a[8];\n\t\tcin>>n;\n\t\tchar s[40];\n\t\tcin>>s;\n\t\tfor(int i=0;i<8;i++)\n\t\t\ta[i]=0;\n\t\tfor(int i=0;i<=37;i++)\n\t\t{\n\t\t\tif(s[i]=='T'&&s[i+1]=='T'&&s[i+2]=='T')\ta[0]++;\n\t\t\telse if(s[i]=='T'&&s[i+1]=='T'&&s[i+2]=='H')\ta[1]++;\n\t\t\telse if(s[i]=='T'&&s[i+1]=='H'&&s[i+2]=='T')\ta[2]++;\n\t\t\telse if(s[i]=='T'&&s[i+1]=='H'&&s[i+2]=='H')\ta[3]++;\n\t\t\telse if(s[i]=='H'&&s[i+1]=='T'&&s[i+2]=='T')\ta[4]++;\n\t\t\telse if(s[i]=='H'&&s[i+1]=='T'&&s[i+2]=='H')\ta[5]++;\n\t\t\telse if(s[i]=='H'&&s[i+1]=='H'&&s[i+2]=='T')\ta[6]++;\n\t\t\telse a[7]++;\n\t\t}\n\t\tcout<<n<<\" \";\n\t\tfor(int i=0;i<8;i++)\n\t\t\tcout<<a[i]<<\" \";\n\t\tcout<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5567423105239868,
"alphanum_fraction": 0.5887850522994995,
"avg_line_length": 17.292682647705078,
"blob_id": "49a675bf5ddac18ad0e9adc8142d5b1f3bd3bcd7",
"content_id": "c981ce6c8386172954b3cb8aec86026223df6896",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 749,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 41,
"path": "/SPOJ/ALCATRAZ2.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int makeTruce(long long int a[],long long int sum,vector< pair<int,int> > v,int i=0)\n{\n\tif(i==v.size())\n\t\treturn sum;\n\tint temp=a[v[i].first-1];\n\ta[v[i].first-1]=0;\n\tint m1=makeTruce(a,sum-temp,v,i+1);\n\ta[v[i].first-1]=temp;\n\ttemp=a[v[i].second-1];\n\ta[v[i].second-1]=0;\n\tint m2=makeTruce(a,sum-temp,v,i+1);\n\ta[v[i].second-1]=temp;\n\treturn max(m1,m2);\n\n}\nint main()\n{\n\tlong long int inp[8],sum=0;\n\tfor(int i=0;i<8;i++)\n\t{\t\n\t\tcin>>inp[i];\n\t\tsum+=inp[i];\n\t}\n\tint p;\n\tcin>>p;\n\tvector < pair<int,int> > list;\n\tfor(int i=0;i<p;i++)\n\t{\n\t\tint m,n;\n\t\tcin>>m>>n;\n\t\tlist.push_back(make_pair(m,n));\n\t}\n\t//cout<<sum<<endl;\n\tcout<<makeTruce(inp,sum,list)<<endl;\n}"
},
{
"alpha_fraction": 0.3851381838321686,
"alphanum_fraction": 0.4154961407184601,
"avg_line_length": 24.367816925048828,
"blob_id": "f04750c82682a2b7ef31b7ad2827e9d417258e7b",
"content_id": "11b2c52b0c0308d910a62a150c833c3d9310d558",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2207,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 87,
"path": "/Codechef/MARRAYS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\n#define INF -9999999999999\nlong long int findval(vector<vector <long long int> > a,long long int n)\n{\n if(n==1)\n return 0;\n long long int M=INF;\n vector <vector<long long int> > dp;\n vector<long long> temp;\n for(int i=0;i<n-1;i++)\n dp.push_back(temp);\n sort(a[n-1].begin(),a[n-1].end());\n for(long long int i=0;i<a[n-2].size();i++)\n {\n //cout<<\"test\\n\";\n long long int m= INF;\n // for(long long int j=0;j<a[n-1].size();j++)\n // {\n // m=max(abs(a[n-1][j]-a[n-2][i])*(n-1),m);\n // }\n // M=max(m,M);\n // dp[n-2].push_back(m);\n //cout<<m<<\" \";\n \n m=max(abs(a[n-1][0]-a[n-2][i])*(n-1),abs(a[n-1][a[n-1].size()-1]-a[n-2][i])*(n-1));\n dp[n-2].push_back(m);\n M=max(m,M);\n }\n //cout<<endl;\n dp[n-2].push_back(M);\n M=INF;\n for(long long int k=n-3;k>=0;k--)\n {\n \n long long int l1=a[k].size(),l2=a[k+1].size();\n for(long long int i=0;i<l1;i++)\n { \n long long int m=INF;\n for(long long int j=0;j<l2;j++)\n {\n long long int s=abs(a[k][i]-a[k+1][j])*(k+1);\n s+=(j==0?dp[k+1][l2-1]:dp[k+1][j-1]);\n \n m=max(m,s);\n //cout<<\"m=\"<<m<<endl;\n }\n \n M=max(m,M);\n dp[k].push_back(m);\n }\n dp[k].push_back(M);\n }\n //for(long long int i=0;i<n-1;i++){\n // for(long long int j=0;j<dp[i].size();j++)\n // cout<<dp[i][j]<<\" \";\n // cout<<endl;\n //}\n \n return dp[0][dp[0].size()-1];\n}\nint main()\n{\n long long int t;\n cin>>t;\n while(t--)\n {\n long long int n,size;\n cin>>n;\n vector <vector<long long int> > dish;\n for(long long int i=0;i<n;i++)\n { vector<long long> x;\n cin>>size;\n //dish[i].resize(size);\n for(long long int j=0;j<size;j++){\n int a;\n cin>>a;\n x.push_back(a);\n }\n dish.push_back(x);\n }\n cout<<findval(dish,n)<<endl;\n }\n} "
},
{
"alpha_fraction": 0.5127272605895996,
"alphanum_fraction": 0.5381818413734436,
"avg_line_length": 13.5,
"blob_id": "40dc7f0a79298a9470b5c8a76dd397683e3e86ac",
"content_id": "f41e0da887b1fcb36e862baea33e904193e6cf95",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 550,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 38,
"path": "/SPOJ/STAMPS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\n#include<string>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t,j=1;\n\tcin>>t;\n\twhile(t--)\n\t{\n\tint a,b,sum=0,k=0,flag=1;\n\tcin>>a>>b;\n\tint *p=new int[b];\n\tfor(int i=0;i<b;i++)\n\t\tcin>>p[i];\n\tsort(p,p+b);\n\tfor(int i=b-1;i>=0;i--,k++)\n\t{\t\n\t\tsum+=p[i];\n\t\tif(sum>=a)\t\n\t\t{\n\t\t\tflag=0;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!flag)\n\tcout<<\"Scenario #\"<<j++<<\":\\n\"<<k+1<<endl<<endl;\n\telse\n\tcout<<\"Scenario #\"<<j++<<\":\\nimpossible\"<<endl<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.3893919885158539,
"alphanum_fraction": 0.4243208169937134,
"avg_line_length": 13.07272720336914,
"blob_id": "1310c9b5d7bffe4d75f497e4c8923e5f5b0be5cc",
"content_id": "6e580e1dfa08b38fc228bbc88d722569bb19a637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 773,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 55,
"path": "/SPOJ/PRIME1.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int m,n,x,k;\n\t\tcin>>m>>n;\n\t\tif(m>n)\tx=m-n;\n\t\telse\t\tx=n-m;\n\t\tk=x;\n\t long long int *p=new long long int[x+1];\n\t\tfor(int i=0;i<=x;i++)\n\t\t{\n\t\t\t//if(m>n)\n\t\t//\tp[i]=n+i;\n\t\t//\telse\n\t\t\tp[i]=m+i;\n\t\t\tif(p[i]==1)\tp[i]=-1;\n\t\t\tif(!(p[i]%6==1||p[i]%6==5)&&p[i]>3)\tp[i]=-1;\n\t\t}\n\t///\tfor(int i=0;i<=x;i++)\n\t//\tcout<<p[i]<<\" \";\n\t//\tcout<<\"\\n\";\n\t\twhile(k>=0)\n\t\t{\n\t\t\tif(p[k]!=-1)\n\t\t{\tfor(long long int i=5;i<=sqrt(p[k]);)\n\t\t\t{\n\t\t\t\tif(p[k]%i==0)\n\t\t\t\t{\n\t\t\t\t\tp[k]=-1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif(i%6==5)\ti+=2;\n\t\t\telse\ti+=4;\n\t\t\t}\n\t\t}\n\t\t\tk--;\n\t\t}\n\t\tfor(int i=0;i<=x;i++)\n\t\t\tif(p[i]!=-1)\n\t\t\t\tcout<<p[i]<<endl;\n\t\t\tcout<<endl;\n\t}\n\t\treturn 0;\n}"
},
{
"alpha_fraction": 0.3244353234767914,
"alphanum_fraction": 0.41067761182785034,
"avg_line_length": 14.21875,
"blob_id": "eb0d8ba588450beaa968c82976af87621c6860be",
"content_id": "c04ae3f08ef8e1858df489b263ef8cdfc0ba7845",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 32,
"path": "/Codechef/CPERM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <iostream>\n#include<math.h>\nusing namespace std;\n \nint main() {\n // your code goes here\n int t;\n cin>>t;\n while(t--)\n {\n long long int n,i=2,f=2;\n cin>>n;\n n-=1;\n if(n) f=1;\n while(n)\n {\n n%=1000000007;\n if(n%2)\n {\n f=(f*i)%1000000007;\n \n }\n n/=2;\n i=(i*i)%1000000007;\n }\n cout<<f-2<<endl;\n } \n return 0;\n} "
},
{
"alpha_fraction": 0.4124999940395355,
"alphanum_fraction": 0.45249998569488525,
"avg_line_length": 12.366666793823242,
"blob_id": "60aceabf8bde0066dbf196a33aa4d85fde129b2b",
"content_id": "e15a6a00d19e9f6cb33c566e0e32589e566f54ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 400,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 30,
"path": "/SPOJ/ICANDIES.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t,x=1;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,i=1,flag=1;\n\t\tcin>>n;\n\t\twhile(flag&&(n-5*i)>0)\n\t\t{\n\t\t\t\tif(((n-5*i)%3)==0)\n\t\t\t\t{\t\n\t\t\t\t\tflag=0;\n\t\t\t\t\tcout<<\"Case \"<<x++<<\": \"<<n-5*i<<endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ti++;\n\t\t\t\n\t\t}\n\t\tif(flag)\tcout<<\"Case \"<<x++<<\": \"<<-1<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.49226006865501404,
"alphanum_fraction": 0.5263158082962036,
"avg_line_length": 11.125,
"blob_id": "0c2b23c2b422cf06fcd8c30135b03e07581eb51c",
"content_id": "90ce619bf4ceb3c49a33c6f90757ab4f8688d94d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 969,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 80,
"path": "/SPOJ/PON.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef unsigned long long int ll;\nll mulmod(ll a,ll b,ll c)\n{\n\tll x=0,y = a%c;\n\t\n\twhile(b>0)\n\t{\n\t\tif(b&1) \n\t\t\tx=(x+y)%c;\n\t\ty=(y<<1)%c;\n\t\tb=b>>1;\n\t}\n\treturn x;\n}\n\nll power(ll x,ll y,ll p)\n{\n\tll res=1;\n\tx=x%p;\n\twhile(y>0)\n\t{\n\t\tif(y&1)\n\t\t\tres=mulmod(res,x,p);\n\t\ty=y>>1;\n\t\tx=mulmod(x,x,p);\n\t}\n\treturn res;\n}\nbool millerRabin(ll d,ll n)\n{\n\tll a=2+rand()%(n-4);\n\tll x=power(a,d,n);\n\tif(x==1||x==n-1)\n\t\treturn true;\n\twhile(d!=n-1)\n\t{\n\t\tx=mulmod(x,x,n);\n\t\td*=2;\n\t\tif(x==1)\n\t\t\treturn false;\n\t\tif(x==n-1)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\nbool isPrime(ll x)\n{\n\tif(x==2||x==3)\n\t\treturn true;\n\tif(x==1||x==0)\n\t\treturn false;\n\tif(x%2==0)\n\t\treturn false;\n\tll temp=x-1;\n\twhile(temp%2==0)\n\t\ttemp/=2;\n\tfor(ll i=0;i<2;i++)\n\t{\n\t\tif(!millerRabin(temp,x))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\nint main()\n{\n\tll t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tll n;\n\t\tcin>>n;\n\t\tcout<<((isPrime(n))?\"YES\\n\":\"NO\\n\");\n\t}\n}"
},
{
"alpha_fraction": 0.43958333134651184,
"alphanum_fraction": 0.4583333432674408,
"avg_line_length": 14.483870506286621,
"blob_id": "48f52f57652d16ddbbf222574b2b68e7b56805c8",
"content_id": "65c5461ecd45b1e51ad3623d08eb0881298d0a4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 480,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 31,
"path": "/SPOJ/AMR10G.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t long int n,k,i,min,d;\n\t cin>>n>>k;\n\t long int *p=new long int[n];\n\t for(i=0;i<n;i++)\n\t cin>>p[i];\n\t sort(p,p+n); \n\t min=p[k-1]-p[0];\n\t for(int i=1,j=k;j<n;j++,i++)\n\t {\n\t d=p[j]-p[i];\n\t if(d<min) min=d;\n\t }\n\t cout<<min<<endl;\n\t \n\t}\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.4867052137851715,
"alphanum_fraction": 0.5156069397926331,
"avg_line_length": 13.661017417907715,
"blob_id": "34e53734229f51e0ba1ede48fe45c6e9aab62251",
"content_id": "5a8c399b1381515f7fb9da0a1719af7fb4befcad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 865,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 59,
"path": "/SPOJ/CUBNUM.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n#define SIZ 100000\n#define INF INT_MAX\n//typedef vector<int> cols;\nvector <int> croot;\nvoid cr()\n{\n\tfor(int i=1;i*i*i<=SIZ;i++)\n\t{\n\t\tcroot.push_back(i);\n\t}\n\t//cout<<croot.size()<<endl;\n\n}\nvector<vector<int> > dp(47,vector<int>(SIZ+1,INF));\nvoid cube()\n{\n\n\tint l=croot.size();\n\t//cout<<l<<endl;\n\tfor(int i=0;i<=l;i++)\n\t{\n\n\t\tint p=croot[i-1]*croot[i-1]*croot[i-1];\n\t\tfor(int j=0;j<=SIZ;j++)\n\t\t{\n\t\t\t//cout<<\"a\";\n\t\t\t\n\t\t\tif(i==0||j==0)\n\t\t\t\tdp[i][j]=INF;\n\t\t\telse if(p==j)\n\t\t\t\tdp[i][j]=1;\n\t\t\telse if(p<j)\n\t\t\t\tdp[i][j]=min(dp[i][p]+dp[i][j-p],dp[i-1][j]);\n\t\t\telse\n\t\t\t\tdp[i][j]=dp[i-1][j];\n\t\t}\n\t\t//cout<<i<<\"\\n\";\n\t}\n\n}\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tint n;\n\n\tcr();\n\tcube();\n\tint i=0;\n\twhile(cin>>n)\n\t{\n\t\tcout<<\"Case #\"<<++i<<\": \"<<dp[round(cbrt(n))][n]<<endl;\n\t}\t\n}\n"
},
{
"alpha_fraction": 0.43784528970718384,
"alphanum_fraction": 0.45303866267204285,
"avg_line_length": 10.15384578704834,
"blob_id": "83599176647912b06610b1901899ca440a2ec96e",
"content_id": "90ee1a5244dc4f9e978279243fa5d144f674f0c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 724,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 65,
"path": "/SPOJ/STPAR.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nvoid parade(int a[],int n)\n{\n\tqueue<int> q;\n\tstack<int> s;\n\tint j=1;\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tif(a[i]==j)\n\t\t{\t\n\t\t\tq.push(a[i]);\n\t\t\tj++;\n\t\t}\n\t\telse if(s.empty()==0&&s.top()==j)\n\t\t{\n\t\t\tq.push(s.top());\n\t\t\ts.pop();\n\t\t\tj++;\n\t\t\ti--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ts.push(a[i]);\n\t\t}\n\t}\n\twhile(!s.empty())\n\t{\n\t\tq.push(s.top());\n\t\ts.pop();\n\t}\n\tint i=q.front();\n\t\n\twhile(q.front()!=q.back())\n\t{\n\t\tq.pop();\n\t\tint j=q.front();\n\t\tif(j-i>1)\n\t\t{\n\t\t\tcout<<\"no\"<<endl;\n\t\t\treturn;\n\t\t}\n\t\ti=j;\n\t}\n\tcout<<\"yes\"<<endl;\n\t\n}\nint main()\n{\n\tint t=1;\n\twhile(t)\n\t{\n\t\tcin>>t;\n\t\tif(t==0)\tbreak;\n\t\tint *a=new int[t];\n\t\tfor(int i=0;i<t;i++)\n\t\t\tcin>>a[i];\n\t\tparade(a,t);\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.5179283022880554,
"alphanum_fraction": 0.5776892304420471,
"avg_line_length": 12.263157844543457,
"blob_id": "a2745c5cbd056d15e965d21a7c205a0b86f370dd",
"content_id": "6392202f39821baf454bae234d2e19796c4d6939",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 251,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 19,
"path": "/SPOJ/FENCE1.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include <stdio.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\twhile(cin>>t)\n\t{\n\t\tif(t==0)\tbreak;\n\t\tfloat d=t*t/(2*3.14159);\n\t\tprintf(\"%.02f\\n\",d);\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5073947906494141,
"alphanum_fraction": 0.5585892796516418,
"avg_line_length": 18.55555534362793,
"blob_id": "6c534b86c786bed43f94dc3bedc2b83d7bd68daf",
"content_id": "f3f1c0a56bf4ec2cee8cbd916e08304ef8536a47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 879,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 45,
"path": "/SPOJ/ACTIV.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\nint activ(ll n,vector <pair<ll,ll> > cl)\n{\n\tvector<ll> dp(n,0);\n\tdp[n-1]=1;\n\tfor(ll i=n-2;i>=0;i--)\n\t{\t\n\t\tdp[i]=(dp[i]+1+dp[i+1])%100000000;\n\t\tvector<pair<ll,ll> >::iterator j;\n\t\tj=lower_bound(cl.begin()+i,cl.end(),make_pair(cl[i].second,cl[i].second));\n\t\tif(j-cl.begin()<n)\n\t\t\tdp[i]=(dp[i]+dp[j-cl.begin()])%100000000;\n\t}\n\treturn dp[0];\n}\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\twhile(1)\n\t{\n\t\tll n;\n\t\tcin>>n;\n\t\tif(n==-1)\n\t\t\tbreak;\n\t\tvector <pair<ll,ll> > cl;\n\t\tfor(ll i=0;i<n;i++)\n\t\t{\n\t\t\tll a,b;\n\t\t\tcin>>a>>b;\n\t\t\tcl.push_back(make_pair(a,b));\n\t\t}\n\t\tsort(cl.begin(),cl.end());\n\t//\tvector <int> sec;\n\t//\tfor(ll i=0;i<n;i++)\n\t//\t\tsec.push_back(cl[i].second);\n\t//\tsort(sec.begin(),sec.end());\n\t\tcout<<setw(8)<<setfill('0')<<activ(n,cl)%100000000<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.384892076253891,
"alphanum_fraction": 0.4118705093860626,
"avg_line_length": 14.885714530944824,
"blob_id": "87e24fae9d9efc087de0130550fd39ae4c4eda4e",
"content_id": "d19fc1ffe771ec86f5d602924bdaf20f6c708586",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 556,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 35,
"path": "/SPOJ/PERMUT2.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint n;\n\twhile(1)\n\t{\n\t cin>>n;\n\t if(!n) break;\n\t int flag=1;\n\t int *p=new int[n+1];\n\t int *p1=new int[n+1];\n\t for(int i=1;i<=n;i++)\n\t {\n\t cin>>p[i];\n\t p1[p[i]]=i;\n\t }\n\t for(int i=1;i<=n;i++)\n\t {\n\t if(p[i]!=p1[i]) \n\t {\n\t flag=0;\n\t break;\n\t }\n\t }\n\t if(!flag) cout<<\"not ambiguous\\n\";\n\t else cout<<\"ambiguous\\n\";\n\t}\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.42829644680023193,
"alphanum_fraction": 0.47353222966194153,
"avg_line_length": 16.04918098449707,
"blob_id": "7dfee0ca2fabc9db83ed43342a188506bbae19b8",
"content_id": "cbecc636f33e613831c20faa00aaa13d9dfa413a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1039,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 61,
"path": "/SPOJ/ASSIGN.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nlong long dp[21][1<<20];\nlong long assign(int a[][20],int i,int mask,int n)\n{\n\tif(dp[i][mask]!=-1)\n\t\treturn dp[i][mask];\n\tif(i==n||mask==((1<<n)-1))\n\t{\n\t\t//cout<<\"terminated\\n\";\n\t\treturn 1;\n\t}\n\tdp[i][mask]=0;\n\tfor(int j=0;j<n;j++)\n\t{\n\t\tif(a[i][j]&&((mask&(1<<j))==0))\n\t\t\tdp[i][mask]+=assign(a,i+1,mask|(1<<j),n);\n\t\t\t//cout<<i<<\"\\t\"<<mask<<'\\t'<<dp[i][mask]<<endl;\n\t}\n\treturn dp[i][mask];\n\t/*dp[0][0]=1;\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tfor(int j=0;j<pow(2,n);j++)\n\t\t{\n\t\t\tfor(int k=0;k<n;k++)\n\t\t\t{\t\t\t\n\t\t\t\tif(a[i-1][k]==1&&(j&(1<<k)))\n\t\t\t\t\tdp[i][j]+=dp[i-1][j^(1<<k)];\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0;i<=n;i++)\n\t{\n\t\tfor(int j=0;j<pow(2,n);j++)\n\t\t\tcout<<dp[i][j]<<\"\\t\";\n\t\tcout<<endl;\n\t}*/\n\t//return dp[n][int(pow(2,n))-1];\n}\nint main()\n{\n\tios::sync_with_stdio(false);\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint s[20][20];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tfor(int j=0;j<n;j++)\n\t\t\t\tcin>>s[i][j];\n\t\tmemset(dp,-1,sizeof(dp));\n\t\tcout<<assign(s,0,0,n)<<'\\n';\n\t}\n}"
},
{
"alpha_fraction": 0.8387096524238586,
"alphanum_fraction": 0.8387096524238586,
"avg_line_length": 30,
"blob_id": "4dfa57543471142f491a612d36bb78bc83e0188a",
"content_id": "8baf02dc5bda7f90106a5edc536412a7e5a9a6f3",
"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": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "# Competetive-programing-codes\n"
},
{
"alpha_fraction": 0.3682539761066437,
"alphanum_fraction": 0.38730159401893616,
"avg_line_length": 14,
"blob_id": "2dac08399dd2c2b7ae962e5263ed0698cec27830",
"content_id": "0b093c729cc45e8c4c7d6a933309248b14432a88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 315,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 21,
"path": "/Codechef/UNICOURS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n,a,m=0;\n cin>>n;\n for(int i=1;i<=n;i++)\n {\n cin>>a;\n m=max(m,a);\n }\n cout<<n-m<<endl;\n }\n} "
},
{
"alpha_fraction": 0.5019959807395935,
"alphanum_fraction": 0.5349301099777222,
"avg_line_length": 14.196969985961914,
"blob_id": "8688a1182b05c35636aebf820a34c59e79ae9f91",
"content_id": "f344912f4cb508ad24a90e5034c319a5081a3b35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1002,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 66,
"path": "/SPOJ/AMR11E.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvector <long long int> primes;\nvector<long long int> list2;\nvoid sieve(int n)\n{\n\tvector <bool> check(n,true);\n\tfor(int i=2;i<sqrt(n);i++)\n\t{\n\t\tif(check[i])\n\t\t{\n\t\t\tprimes.push_back(i);\n\t\t\tfor(int j=i*i;j<n;j+=i)\n\t\t\t\tcheck[j]=false;\n\t\t}\n\t}\n\tfor(int i=sqrt(n);i<n;i++)\n\t\tif(check[i])\n\t\t\tprimes.push_back(i);\n\t//for(int i=0;i<primes.size();i++)\n\t//\tcout<<primes[i]<<\"\\t\";\n}\nvoid luckyNumber(int n)\n{\t\n\tfor(int i=30;i<2665;i++)\n\t{\n\t\tint temp=i;\n\t\tint j=0,k=0;\n\t\twhile(temp!=1&&k<3)\n\t\t{\n\t\t\tif(temp%primes[j]==0)\n\t\t\t{\t\n\t\t\t\tk++;\n\t\t\t\twhile(temp%primes[j]==0)\n\t\t\t\t\ttemp/=primes[j];\n\t\t\t}\n\t\t\telse\n\t\t\t\tj++;\n\t\t}\n\t\tif(k==3)\n\t\t\tlist2.push_back(i);\n\t}\n\t//cout<<\"test\\n\";\n\t//cout<<list.top()<<'\\n';\n\t//for (vector<long long int >::iterator i=list2.begin();i!=list2.end();i++)\n\t//\tcout<<*i<<endl;\n\n}\nint main()\n{\n\tsieve(2665);\n\tluckyNumber(1000);\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tcout<<list2[n-1]<<\"\\n\";\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.3035019338130951,
"alphanum_fraction": 0.32684823870658875,
"avg_line_length": 16.133333206176758,
"blob_id": "43444c03d3f3210b7e6da7ed0da406538fb64215",
"content_id": "35b69e6758cdc5de9ab3c94c97c3478650c8ffdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 514,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 30,
"path": "/Codechef/PERFCONT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n,p;\n int c=0,h=0;\n cin>>n>>p;\n int *a=new int[n];\n for(int i=0;i<n;i++)\n {\n cin>>a[i];\n if(a[i]<=p/10)\n h++;\n else if(a[i]>=p/2)\n c++;\n }\n if(c==1&&h==2)\n cout<<\"yes\\n\";\n else\n cout<<\"no\\n\";\n \n }\n} "
},
{
"alpha_fraction": 0.5202311873435974,
"alphanum_fraction": 0.5462427735328674,
"avg_line_length": 12.84000015258789,
"blob_id": "cfe6d2511609fec1be6251eb0f6f61806261c2bd",
"content_id": "e11430152da5c63f4105ef02ac12ce423e51857f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 25,
"path": "/SPOJ/ABSP1.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,sum=0;\n\t\tcin>>n; \n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>a[i];\n\t\t\tsum+=(2*i+1-n)*a[i];\n\t\t}\n\t\tcout<<sum<<endl;\n\t}\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.32345014810562134,
"alphanum_fraction": 0.3396226465702057,
"avg_line_length": 19.61111068725586,
"blob_id": "85975e0f592e996a0f13d1ba5c1e0e2ecbb70b9c",
"content_id": "651ebd3a2648cd5659a685da5388b80bf68cc922",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 36,
"path": "/Codechef/MEX.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n long long int t;\n cin>>t;\n while(t--)\n {\n long long int n,k,j=0;\n cin>>n>>k;\n vector <long long int> a(n),b;\n for(long long int i=0;i<n;i++)\n cin>>a[i];\n sort(a.begin(),a.end());\n for(long long int i=0;i<=a[n-1]+k+1;i++)\n {\n if(b.size()==k+1)\n break;\n if(i!=a[j])\n {\n b.push_back(i);\n }\n else\n {\n j++;\n if(j>0&&a[j]==a[j-1])\n i--;\n }\n }\n cout<<b[k]<<endl;\n //cout<<\"t\"<<endl;\n }\n} "
},
{
"alpha_fraction": 0.517241358757019,
"alphanum_fraction": 0.5615763664245605,
"avg_line_length": 10.333333015441895,
"blob_id": "0842d214d142e763a873af8322ac3b5202bda975",
"content_id": "a95da9cff5c38db80832f5709e7ce2ce392fd808",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 203,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 18,
"path": "/SPOJ/TEST.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\twhile(t!=42)\n\t{\n\t\tcin>>t;\n\t\tif(t!=42)\n\t\tcout<<t<<endl;\n\t}\n\t\treturn 0;\n}"
},
{
"alpha_fraction": 0.328102707862854,
"alphanum_fraction": 0.35663339495658875,
"avg_line_length": 17.945945739746094,
"blob_id": "98d7d6f11a843e1d32bbd0385013a185721ded95",
"content_id": "4bc44d72d9801e0909812d16dcc4ddb87996418d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 701,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 37,
"path": "/Codechef/XENTASK.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n \nint main() {\n // your code goes here\n int t;\n cin>>t;\n while(t--)\n {\n int n,sum1=0,sum2=0;\n cin>>n;\n int *x=new int[n],*y=new int[n];\n for(int i=0;i<n;i++)\n cin>>x[i];\n for(int i=0;i<n;i++)\n cin>>y[i];\n for(int i=0;i<n;i++)\n {\n if(i%2==0)\n {\n sum1+=x[i];\n sum2+=y[i];\n }\n else\n {\n sum1+=y[i];\n sum2+=x[i];\n }\n }\n cout<<min(sum1,sum2)<<endl;\n }\n return 0;\n} "
},
{
"alpha_fraction": 0.5808903574943542,
"alphanum_fraction": 0.6047773957252502,
"avg_line_length": 14.114753723144531,
"blob_id": "00c222b18ac32e4f88d96cf108a1a32ae44a2143",
"content_id": "367f42bdd324f2f2e0361feed22199ee1e23ab1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 921,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 61,
"path": "/SPOJ/DIVFACT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nstd::vector<unsigned long long int> allPrimes;\nvoid seive(unsigned long long int n)\n{\n\tallPrimes.clear();\n\tstd::vector<bool> p(n+1,true);\n\tfor(unsigned long long int i=2;i<=sqrt(n);i++)\n\t{\n\t\tif(p[i])\n\t\t{\n\t\t\tfor(unsigned long long int j=i*2;j<=n;j+=i)\n\t\t\t\tp[j]=false;\n\t\t}\n\t}\n\tfor(unsigned long long int i=2;i<=n;i++)\n\t\tif(p[i])\n\t\t{\n\t\t\tallPrimes.push_back(i);\n\t\t}\n}\nvoid countDivisors(unsigned long long int n)\n{\n\tseive(n);\n\tunsigned long long int total=1;\n\tunsigned long long int i=0;\n\n\twhile(i<allPrimes.size())\n\t{\n\t\t\n\t\tunsigned long long int exp=0,p=allPrimes[i];\n\t\tlong double m=n/p;\n\t\n\t\twhile(floor(m))\n\t\t{\n\t\t\texp+=floor(m);\n\t\t\tm/=p;\n\n\t\t}\n\t\ttotal*=(exp+1);\n\t\ttotal%=1000000007;\n\t\ti++;\n\t}\n\tcout<<total<<endl;\n}\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tunsigned long long int n;\n\t\tcin>>n;\n\t\tcountDivisors(n);\n\t\n\t}\n}"
},
{
"alpha_fraction": 0.5096011757850647,
"alphanum_fraction": 0.5302806496620178,
"avg_line_length": 13.125,
"blob_id": "292c1f03f393056032fa1cb87c4bef29740aa1dd",
"content_id": "d98241e3e009c409cf40d6ba263ed9755a0ce60a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 677,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 48,
"path": "/SPOJ/ABA12C.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<algorithm>\n#include<map>\n#include<limits.h>\nusing namespace std;\nmap <int,int> X;\nint buyingApples(int a[],int size)\n{\n\tint *val=new int[size+1];\n\tval[0]=0;\n\tfor(int i=1;i<=size;i++)\n\t{\n\t\tint v=INT_MAX;\n\t\tfor(int j=0;j<i;j++)\n\t\t{\n\t\t\tif(X.find(j)==X.end())\n\t\t\t\tv=min(v,a[j]+val[i-j-1]);\n\t\t}\n\t\t\tval[i]=v;\n\t\t//\tcout<<val[i]<<endl;\n\n}\n\treturn val[size];\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,k;\n\t\tcin>>n>>k;\n\t\tX.clear();\n\t\tint *a=new int[k];\n\t\tfor(int i=0;i<k;i++)\n\t\t{\n\t\t\tcin>>a[i];\n\t\t\tif(a[i]==-1)\n\t\t\t\tX[i]=i;\n\t\t}\n\t\tint val=buyingApples(a,k);\n\t\tcout<<(val<0||val==INT_MAX?-1:val)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.259782612323761,
"alphanum_fraction": 0.280434787273407,
"avg_line_length": 18.14583396911621,
"blob_id": "bb6ac506603d354fac414c89d6b9fb4c80185fe5",
"content_id": "b691d989f362bbbc4c64403898869ed03b5dd6d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 920,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 48,
"path": "/Codechef/DISHLIFE.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nmap<int,int> a;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n a.clear();\n int n,k,f,i,f2=1,flag=0;\n cin>>n>>k;\n for(i=0;i<n;i++)\n {\n cin>>f;\n int flag2=0;\n int *ar=new int[f];\n for(int j=0;j<f;j++)\n {\n cin>>ar[j];\n if(a.find(ar[j])==a.end())\n { flag2=1;\n a[ar[j]]=i+1;\n }\n }\n if(!flag2)\n {\n f2=0;\n }\n if(a.size()==k)\n {\n flag=1;\n }\n }\n if(flag)\n {\n if(f2)\n cout<<\"all\\n\";\n else\n cout<<\"some\\n\";\n }\n else\n cout<<\"sad\\n\";\n }\n}\n "
},
{
"alpha_fraction": 0.5101123452186584,
"alphanum_fraction": 0.5258427262306213,
"avg_line_length": 12.9375,
"blob_id": "83e33bd7b22d286ebc0b4629a9a5d17f3b17b23d",
"content_id": "dc838c14b953b0869758dcfc06a61fae87d6e5eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 445,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 32,
"path": "/SPOJ/SBANK.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nmap<string,int> acc;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tacc.clear();\n\t\tint n;\n\t\tcin>>n;\n\t\tstring s;\n\t\tgetchar();\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tgetline(cin,s);\n\t\t\tif(acc.find(s)!=acc.end())\n\t\t\t\tacc[s]+=1;\n\t\t\telse\n\t\t\t\tacc[s]=1;\n\t\t}\n\tfor(map<string,int>::iterator i=acc.begin();i!=acc.end();i++)\n\t{\n\t\tcout<<i->first<<\" \"<<i->second<<endl;\n\t}\n\t}\n}"
},
{
"alpha_fraction": 0.40094900131225586,
"alphanum_fraction": 0.42941874265670776,
"avg_line_length": 20.64102554321289,
"blob_id": "b04c06de1d5fa121281676e1aff48d972391a17e",
"content_id": "bc12bfe9143219b524f79019e0c7971bcfd38985",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 843,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 39,
"path": "/SPOJ/ETF.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\n#include<cmath>\n#include<algorithm>\nusing namespace std;\nint gcd(int a, int b)\n{ // cout<<\"min of\"<<a<<\" \"<<b<<\"=\"<<min(a,b)<<endl;\n if(b%a==0) return min(a,b);\n return gcd(b%a,min(a,b));\n}\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n,count=0;\n cin>>n;\n float etf=n;\n for(int i=2;i<=sqrt(n);i++)\n { //cout<<\"gcd=\"<<gcd(i,n)<<endl;\n // if(gcd(i,n)==1) count++;\n if(n%i==0)\n \t{\twhile(n%i==0)\n \t\tn/=i;//cout<<endl<<(1.0-1.0/(float)i)<<endl;// cout<<etf<<endl<<i<<endl;\n \t\tetf*=(1.0-1.0/(float)i);}\n \t//\tcout<<n<<endl<<endl;\n }\n if(n>1)\n etf*=(1.0-1.0/(float)n);\n cout<<etf<<endl;\n \n }\n return 0;\n}"
},
{
"alpha_fraction": 0.5441176295280457,
"alphanum_fraction": 0.5661764740943909,
"avg_line_length": 12.649999618530273,
"blob_id": "c0ed339c8460223a738b2f153874dcc1e42462bc",
"content_id": "9318fb7bbe73efbbb0bab262cad94ab5b8da7202",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 272,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 20,
"path": "/SPOJ/ROOTCIPH.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include <stdio.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\t\tlong long int a,b,c;\n\t\tscanf(\"%lld %lld %lld\",&a,&b,&c);\n\t\tcout<<a*a-2*b<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5283364057540894,
"alphanum_fraction": 0.5630713105201721,
"avg_line_length": 12.365853309631348,
"blob_id": "a5b45dac22c4a85c74fc5523f1987494e33afb19",
"content_id": "dba29761e40bd90d483902fbbdd788ce20bcad68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 547,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 41,
"path": "/SPOJ/COINS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<map>\nusing namespace std;\nmap<long long int,long long int> b;\nlong long int coin(long long int a)\n{\n\tif(a==0)\treturn 0;\n\tif(a==1)\treturn 1;\n\tif(a==2)\treturn 2;\n\tif(a==3)\treturn 3;\n\tif(b.find(a)!=b.end())\treturn b[a];\n\n//if(a>=(a/2+a/3+a/4))\n//return a;\n\tlong long int x=coin(a/2)+coin(a/3)+coin(a/4);\n\tif(x<a)\n\t\t{\n\t\tb[a]=a;\n\t\treturn a;\n\t\t}\n\telse\t\n\t\t{b[a]=x;\n\t\treturn b[a];\n\t}\n}\nint main()\n{\n\tint t;\n\tlong long int a;\n\twhile(cin>>a)\n\t{\n\t\n\n\tcout<<coin(a)<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4955116808414459,
"alphanum_fraction": 0.5314183235168457,
"avg_line_length": 22.20833396911621,
"blob_id": "6d53ffc541c91bfc5dd3dd5663dc3f4f8244bea6",
"content_id": "a7eb2ab5f23da092b115bff4280d3fa0d7261f32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 557,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 24,
"path": "/Codechef/ZCO14002.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int findVal(vector <long long int> v,long long int n)\n{\n vector <long long int> dp(n,0);\n dp[n-1]=v[n-1],dp[n-2]=v[n-2],dp[n-3]=v[n-3];\n for(long long int i=n-4;i>=0;i--)\n {\n dp[i]=v[i]+min(dp[i+1],min(dp[i+2],dp[i+3]));\n }\n return min(dp[0],min(dp[1],dp[2]));\n}\nint main()\n{\n long long int n;\n cin>>n;\n vector<long long int> v(n);\n for(long long int i=0;i<n;i++)\n cin>>v[i];\n cout<<findVal(v,n)<<endl;\n} "
},
{
"alpha_fraction": 0.26428571343421936,
"alphanum_fraction": 0.28928571939468384,
"avg_line_length": 16.47916603088379,
"blob_id": "c93e2f19ee1aa61acc20de7f0cb76a44ed1ba896",
"content_id": "419f58f466c34cbe304bb224cb94bf3604306e9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 840,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 48,
"path": "/Codechef/ZCO14001.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int n,h;\n cin>>n>>h;\n vector<long long int> a(n);\n for(int i=0;i<n;i++)\n cin>>a[i];\n int j=0,m,flag=0;\n while(1)\n {\n cin>>m;\n if(m==0) break;\n else if(m==2)\n {\n if(j!=n-1)\n j++;\n }\n else if(m==1)\n {\n if(j!=0)\n j--;\n }\n else if(m==3)\n {\n if(a[j]!=0&&flag==0)\n {\n a[j]--;\n flag=1;\n }\n }\n else if(m==4)\n {\n if(a[j]!=h&&flag==1)\n {\n a[j]++;\n flag=0;\n }\n }\n }\n for(int i=0;i<n;i++)\n cout<<a[i]<<\" \";\n cout<<endl;\n} \n"
},
{
"alpha_fraction": 0.43370166420936584,
"alphanum_fraction": 0.469613254070282,
"avg_line_length": 16.285715103149414,
"blob_id": "57010284c427bbfe91508c8309f9e075a91c2430",
"content_id": "10c668de56095d930209a3aac003bf33fb6f1aa9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 362,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 21,
"path": "/SPOJ/BEENUMS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\n#include<cmath>\nusing namespace std;\nint main()\n{\n long long int t;\n while(1)\n {\n cin>>t;\n if(t==-1) break;\n long double k=(-3+sqrt(9+12*(t-1)))/6;\n if(floor(k)==k) cout<<\"Y\\n\";\n else cout<<\"N\\n\";\n }\n return 0;\n}"
},
{
"alpha_fraction": 0.39928486943244934,
"alphanum_fraction": 0.46007150411605835,
"avg_line_length": 12.54838752746582,
"blob_id": "16595f9740a11838e6733d47a1b72773fdad483f",
"content_id": "d5b862edcd89cd401c291da3d1e154579250ae6b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 839,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 62,
"path": "/SPOJ/AE2A.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef vector<float> rows;\nvector <rows> checkProb(int a, int b)\n{\n\tvector<rows> dp(546,rows(1909,0.0));\n\tfor(int i=0;i<=a;i++)\n\t{\n\t\tfor(int j=0;j<=b;j++)\n\t\t{\n\t\t\tif(i==0||j<i||j==0)\n\t\t\t\tdp[i][j]=0;\n\t\t\telse if(i==1&&j<=6&&j>0)\n\t\t\t{\n\t\t\t\tdp[i][j]=1/6.0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat prob=0;\n\t\t\t\tfor(int k=1;k<min(7,j);k++)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tprob+=dp[i-1][j-k]*1/6.0;\n\t\t\t\t}\n\t\t\t\tdp[i][j]=prob;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//for(int i=1;i<=a;i++)\n\t//{\t\n\t//\tfor(int j=1;j<=b;j++)\n\t//\t{\n\t//\t\tcout<<dp[i][j]<<\"\\t\";\n\t//\t}\n\t//\tcout<<\"\\n\";\n\t//}\n\treturn dp;\n}\nint main()\n{\n\tint t;\n\tvector<rows> dp;\n\tdp=checkProb(545,1909);\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,k;\n\t\tcin>>n>>k;\n\t\tif(n>545||k>1908)\n\t\t{\n\t\t\tcout<<\"0\"<<endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tcout<<floor(dp[n][k]*100)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4593749940395355,
"alphanum_fraction": 0.48124998807907104,
"avg_line_length": 12.956521987915039,
"blob_id": "7320bfc8766b6a5abf590608ab1e20f91c92fbea",
"content_id": "dcb17f55379c9e5e7f06f79e1b85dcfa69eed618",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 320,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 23,
"path": "/SPOJ/ACPC10A.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\nusing namespace std;\nint main()\n{\n\tint a,b,c,flag=1;\n\tdo\n\t{\n\t\tcin>>a>>b>>c;\n\t\tif((a||b||c))\n\t\t{\n\t\t\tif((a!=b)&&(b!=c)&&(c!=a)){\n\t\t\tif(b-a==c-b)\tcout<<\"AP \"<<c+(b-a)<<endl;\n\t\t\telse\t\t\tcout<<\"GP \"<<c*b/a<<endl;\n\t\t}\n\t\t}\n\t\telse flag=0;\n\t}while(flag);\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5068027377128601,
"alphanum_fraction": 0.5204081535339355,
"avg_line_length": 20.740739822387695,
"blob_id": "620d077af3620e29ed5b7aa366cb8db72c1fcd8c",
"content_id": "b0d204516b7916afa85c8444f561321444a7fdd6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 588,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 27,
"path": "/Codechef/ZCO13003.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nlong long int find(vector<long long int> &a,int n,int k)\n{\n sort(a.begin(),a.end());\n long long int sum=0;\n for(long long int i=0;i<n;i++)\n {\n long long int m=lower_bound(a.begin(),a.end(),k-a[i])-a.begin();\n //cout<<m<<endl;\n if(m>i)\n sum+=(m-i-1);\n }\n return sum;\n}\nint main()\n{\n long long int n,k;\n cin>>n>>k;\n vector<long long int> ori(n);\n for(long long int i=0;i<n;i++)\n cin>>ori[i];\n cout<<find(ori,n,k)<<endl;\n}\n "
},
{
"alpha_fraction": 0.4793926179409027,
"alphanum_fraction": 0.4967462122440338,
"avg_line_length": 17.399999618530273,
"blob_id": "a8089d598f48fcd238d4c49421770c975963ed07",
"content_id": "a6b3fe4fcecb4ffefbff56e429a3f47a10e1e48b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 461,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 25,
"path": "/Codechef/ZCO15002.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint find(vector<int> &a,int n,int k)\n{\n sort(a.begin(),a.end());\n int sum=0;\n for(int i=0;i<n-1;i++)\n {\n int m=lower_bound(a.begin(),a.end(),a[i]+k)-a.begin();\n sum+=n-m;\n }\n return sum;\n}\nint main()\n{\n int n,k;\n cin>>n>>k;\n vector<int> ori(n);\n for(int i=0;i<n;i++)\n cin>>ori[i];\n cout<<find(ori,n,k)<<endl;\n}\n "
},
{
"alpha_fraction": 0.44897958636283875,
"alphanum_fraction": 0.5170068144798279,
"avg_line_length": 12.454545021057129,
"blob_id": "bf3f3c212934869e7da656907ce4fe3b702a2d91",
"content_id": "499aec37935df36ba80c9179a2c184d65f7ce213",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 147,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 11,
"path": "/SPOJ/JULKA.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n'''\ni=0\nwhile i<10:\n\ta=int(input())\n\tb=int(input())\n\tprint (a-int((a-b)//2))\n\tprint (int((a-b)//2))\n\ti=i+1"
},
{
"alpha_fraction": 0.5723221302032471,
"alphanum_fraction": 0.5926505327224731,
"avg_line_length": 15.8421049118042,
"blob_id": "c85d422f04c22f418a5875f748a49946e963f768",
"content_id": "5c959b46822fef43bf61e0fffb3b0cc4923ed36f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1279,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 76,
"path": "/SPOJ/AKVQLD03.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nstruct tree{\n\tpair<int,int> range;\n\tint val;\n\ttree *left;\n\ttree *right;\n};\ntree *makeTree(int low,int high)\n{\n\ttree *t=new tree;\n\tt->range=make_pair(low,high);\n\tt->val=0;\n\tt->left=NULL;\n\tt->right=NULL;\n\tif(low==high)\n\t\treturn t;\n\tint mid=(low+high)/2;\n\tt->left=makeTree(low,mid);\n\tt->right=makeTree(mid+1,high);\n\treturn t;\n}\nvoid updateVal(tree* t,int pos,int v)\n{\n\tif(t!=NULL)\n\t{\n\t\tif(t->range.first<=pos&&t->range.second>=pos)\n\t\t{\n\t\t\tt->val+=v;\n\t\t\tupdateVal(t->left,pos,v);\n\t\t\tupdateVal(t->right,pos,v);\n\t\t}\n\t}\n}\nint quant(tree *t,int p1,int p2)\n{\n\tif(t==NULL)\n\t\treturn 0;\n\tif(t->range==make_pair(p1,p2))\n\t\treturn t->val;\n\tint v=0;\n\tif(t->left->range.second>=p1&&t->left->range.second>=p2)\n\t\tv+=quant(t->left,p1,p2);\n\telse if(t->left->range.second>=p1)\n\t\tv+=quant(t->left,p1,t->left->range.second);\n\tif(t->right->range.first<=p2&&t->right->range.first<=p1)\n\t\tv+=quant(t->right,p1,p2);\n\telse if(t->right->range.first<=p2)\n\t\tv+=quant(t->right,t->right->range.first,p2);\n\treturn v;\n}\nint main()\n{\n\tint n,q;\n\tcin>>n>>q;\n\ttree *T=makeTree(1,n);\n\twhile(q--)\n\t{\n\t\tstring s;\n\t\tint a,b;\n\t\tcin>>s>>a>>b;\n\t\tif(s==\"add\")\n\t\t{\n\t\t\tupdateVal(T,a,b);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout<<quant(T,a,b)<<endl;\n\t\t}\n\n\t}\n}"
},
{
"alpha_fraction": 0.39381444454193115,
"alphanum_fraction": 0.4309278428554535,
"avg_line_length": 15.199999809265137,
"blob_id": "9d5d089de77cc7050dbaff0277653d9ba2176bab",
"content_id": "dc05328b940208e664afdf3224eaef3eef04b042",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 485,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 30,
"path": "/SPOJ/AP2.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t\n\t// your code here\n int t;\n cin>>t;\n while(t--)\n {\n long long int a3,an3,sum,n,a,d;\n cin>>a3>>an3>>sum;\n n=2*sum/(a3+an3);\n d=(an3-a3)/(n-5);\n a=a3-2*d;\n cout<<n<<endl;\n for(long long int i=0;i<n;i++)\n cout<<a+i*d<<\" \";\n cout<<endl;\n \n }\n return 0;\n \n \n }"
},
{
"alpha_fraction": 0.511040985584259,
"alphanum_fraction": 0.539432168006897,
"avg_line_length": 10.357142448425293,
"blob_id": "bf004d6f02241603a9cacacf3b2ae77b8a51ad9f",
"content_id": "0444bf8b1c5ce435e29318d2320b0fd3669afb17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 28,
"path": "/SPOJ/FCTRL.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<math.h>\nusing namespace std;\n\nint main() {\n\t\n\t// your code here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int k,i=1;\n\t\tcin>>k;\n\t\tlong long int sum=0;\n\t\twhile(pow(5,i)<=k)\n\t\t{\n\t\t\tsum+=k/pow(5,i);\n\t\t\ti++;\n\t\t}\n\t\tcout<<sum<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4773083031177521,
"alphanum_fraction": 0.5477308034896851,
"avg_line_length": 13.222222328186035,
"blob_id": "a7a6de3b1cef5588968f5e784e109f5a57a4fe3d",
"content_id": "eb1a377f3e36ef67756df5a6c522012dcf61e688",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 639,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 45,
"path": "/SPOJ/TDKPRIME.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\n#define MAX 100000000\n#define LIM 10000\nll lis[MAX>>6];\n#define ifComp(x) (lis[x>>6]&(1<<((x>>1)&31)))\n#define isComp(x) (lis[x>>6]|=(1<<((x>>1)&31)))\nvector<ll> primes;\nvoid sieve()\n{\n\tregister ll i,j,k;\n\tprimes.push_back(2);\n\tfor(i=3;i<LIM;i+=2)\n\t{\n\t\tif(!ifComp(i))\n\t\t{\n\t\t\tfor(j=i*i,k=i<<1;j<MAX;j+=k)\n\t\t\t\tisComp(j);\n\t\t}\n\t}\n\tfor(i=3,j=0;j<=50000000&&i<MAX;i+=2)\n\t{\n\t\tif(!ifComp(i))\n\t\t\tprimes.push_back(i),j++;\n\t}\n}\nint main()\n{\n\tsieve();\n\tll t;\n\tcin>>t;\n\t\n\twhile(t--)\n\t{\n\t\tll n;\n\t\tcin>>n;\n\t\tcout<<primes[n-1]<<endl;\n\n\t}\n}"
},
{
"alpha_fraction": 0.5150501728057861,
"alphanum_fraction": 0.5518394708633423,
"avg_line_length": 12.636363983154297,
"blob_id": "8beeba81be530cbcf220b753782e8889a13e8ae2",
"content_id": "59991a88569c6debc065e2750c817478cea05d51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 299,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 22,
"path": "/SPOJ/MAXLN.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<stdio.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t,i=1;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong double n;\n\t\tcin>>n;\n\t\tlong double s=4*n*n+1/4.0;\n\t\tcout<<\"Case \"<<i++<<\": \";\n\t\tprintf(\"%.2Lf\\n\",s);\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4957983195781708,
"alphanum_fraction": 0.5462185144424438,
"avg_line_length": 11.526315689086914,
"blob_id": "cb621b6247bfecc919670977cd75af32777645dc",
"content_id": "86b6f5f217b8ff8062b2fa086953a7f9d685191e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 238,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 19,
"path": "/SPOJ/EIGHTS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t long long int n;\n\t cin>>n;\n\t cout<<(n-1)*250+192<<endl;\n\t}\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.39614561200141907,
"alphanum_fraction": 0.4211277663707733,
"avg_line_length": 21.190475463867188,
"blob_id": "f393e1655cf50a000047ba737975964edcd80903",
"content_id": "d8575cad7b32fdd5373f491d9c115e36844c9b94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1401,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 63,
"path": "/Codechef/C00K0FF.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nbool binarySearch(string s[],int low,int high,string s1)\n{\n if(low==high)\n return s[low]==s1?true:false;\n if(low>high)\n return false;\n int mid=(low+high)/2;\n return binarySearch(s,low,mid,s1)+binarySearch(s,mid+1,high,s1);\n}\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n,flag=0;\n cin>>n;\n string *s=new string[n];\n for(int i=0;i<n;i++)\n cin>>s[i];\n if(n<5)\n { cout<<\"No\\n\";\n continue;\n }\n if(binarySearch(s,0,n-1,\"easy\")==0)\n { flag++;\n cout<<\"No\\n\";\n continue;\n }\n if(binarySearch(s,0,n-1,\"cakewalk\")==0)\n {\n flag++;\n cout<<\"No\\n\";\n continue;\n }\n if(binarySearch(s,0,n-1,\"simple\")==0)\n {\n flag++;\n cout<<\"No\\n\";\n continue;\n }\n if(binarySearch(s,0,n-1,\"easy-medium\")==0&&binarySearch(s,0,n-1,\"medium\")==0)\n {\n flag++;\n cout<<\"No\\n\";\n continue;\n }\n if(binarySearch(s,0,n-1,\"medium-hard\")==0&&binarySearch(s,0,n-1,\"hard\")==0)\n {\n flag++;\n cout<<\"No\\n\";\n continue;\n } \n if(flag!=5)\n cout<<\"Yes\\n\";\n \n }\n} "
},
{
"alpha_fraction": 0.44485750794410706,
"alphanum_fraction": 0.4869888424873352,
"avg_line_length": 15.833333015441895,
"blob_id": "f611f2a866d0e47f66a21ad6b682e5cff2e212f4",
"content_id": "2c56f1fc1f77d0d2686d49b4fb13b519b88a3a12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 807,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 48,
"path": "/SPOJ/BORW.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\n\nint bOrW(vector<int> a,int n)//black->increasing\n{\n\t//cout<<\"test\\n\";\n\tvector <vector<vector<int> > > dp(202,vector<vector<int> >(202,vector<int>(202,0)));\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tfor(int u=i+1;u<=n+1;u++)\n\t\t{\n\t\t\tfor(int l=i+1;l<=n+1;l++)\n\t\t\t{\n\t\t\t\tdp[i][u][l]=1+dp[i-1][u][l];\n\t\t\t\tif(l>n||a[l-1]<a[i-1])\n\t\t\t\t\tdp[i][u][l]=min(dp[i][u][l],dp[i-1][u][i]);\n\t\t\t\tif(u>n||a[u-1]>a[i-1])\n\t\t\t\t\tdp[i][u][l]=min(dp[i][u][l],dp[i-1][i][l]);\n\t\t\t}\t\n\t\t}\n\t}\n\treturn dp[n][n+1][n+1];\n\n}\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\twhile(1)\n\t{\t\n\t\t\n\t\tint n;\n\t\tcin>>n;\n\t\tif(n==-1)\n\t\t\tbreak;\n\t\tvector <int> ar(n+2);\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>ar[i];\n\t\t}\n\t\tar[n]=INT_MIN;\n\t\tar[n+1]=INT_MAX;\n\t\tcout<<bOrW(ar,n)<<\"\\n\";\n\t}\n}"
},
{
"alpha_fraction": 0.3206568658351898,
"alphanum_fraction": 0.35177183151245117,
"avg_line_length": 18.94827651977539,
"blob_id": "1e09f0ef30a33e002de880e74766ce91c2a9f02c",
"content_id": "7038e0c0ba24fe90d0a8789507a62d456f9c4a98",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1157,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 58,
"path": "/SPOJ/ABSYS.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include<string.h>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t string a,b,e;\n\t char c,d;\n\t int A=0,B=0,E=0,i=0;\n\t cin>>a>>c>>b>>d>>e;\n\t if(a.find(\"machula\")!=a.npos)\n\t {\n\t while(i<b.length()||i<e.length())\n\t {\n\t // cout<<\"t1\\n\";\n\t if(i<b.length()) B=B*10+(b[i]-48);\n\t if(i<e.length()) E=E*10+(e[i]-48);\n\t i++;\n\t \n\t }\n\t \n\t A=E-B;\n\t \n\t }\n\t \n\t else if(b.find(\"machula\")!=b.npos)\n\t {\n while(i<a.length()||i<e.length())\n\t { //cout<<\"t2\\n\";\n\t if(i<a.length()) A=A*10+(a[i]-48);\n\t if(i<e.length()) E=E*10+(e[i]-48);\n\t i++;\n\t }\n\t B=E-A;\n\t }\n\t else\n\t {\n\t while(i<b.length()||i<a.length())\n\t { // cout<<\"t3\\n\";\n\t if(i<b.length()) B=B*10+(b[i]-48);\n\t if(i<a.length()) A=A*10+(a[i]-48);\n\t i++;\n\t }\n\t E=A+B;\n \n\t }\n\t cout<<A<<\" + \"<<B<<\" = \"<<E<<endl;\n\t}\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.47179487347602844,
"alphanum_fraction": 0.5012820363044739,
"avg_line_length": 16.35555648803711,
"blob_id": "3dc4e7dafcc66ae4d5e7377c5088bb5f3c119114",
"content_id": "e296bbd92b31765b59ee952de5eb299e1c26cf5d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 780,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 45,
"path": "/SPOJ/PARTY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint b;\nvoid optimus(int fee[],int joy[],int budget,int size)\n{\n\tint **a=new int*[size+1];\n\tfor(int t=0;t<=size;t++)\n\t\ta[t]=new int[budget+1];\n\tfor(int i=0;i<=size;i++)\n\t\tfor(int j=0;j<=budget;j++)\n\t\t{\n\t\t\tif(i==0||j==0)\n\t\t\t\ta[i][j]=0;\n\t\t\telse if(fee[i-1]<=j)\n\t\t\t\ta[i][j]=max(a[i-1][j-fee[i-1]]+joy[i-1],a[i-1][j]);\n\t\t\telse\n\t\t\t\ta[i][j]=a[i-1][j];\n\t\t}\n\t//return a[size][budget];\n\t\tfor(int j=0;j<=budget;j++)\n\t\t\tif(a[size][j]==a[size][budget])\n\t\t\t{\n\t\t\t\tcout<<j<<\" \"<<a[size][budget]<<endl;\n\t\t\t\tbreak;\n\t\t\t}\n}\nint main()\n{\n\twhile(1)\n\t{\n\t\tint n,j;\n\t\tcin>>n>>j;\n\t\tif(n==0&&j==0)\n\t\t\tbreak;\n\t\tint *a=new int[j];\n\t\tint *b=new int[j];\n\t\tfor(int i=0;i<j;i++)\n\t\t\tcin>>a[i]>>b[i];\n\t\toptimus(a,b,n,j);\n\t}\n}"
},
{
"alpha_fraction": 0.5563689470291138,
"alphanum_fraction": 0.5754026174545288,
"avg_line_length": 15.682927131652832,
"blob_id": "56e01825f77ef98f4a61e4533a69b47e32748c91",
"content_id": "d8fe39b70a3ffc86e1c7cc29b57bbcddeac41789",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 683,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 41,
"path": "/SPOJ/AGGRCOW.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<algorithm>\nusing namespace std;\nlong long int kcows(long long int l,long long int h,long long int k, long long int a[],long long int size)\n{\n\tif(l>=h)\n\t\treturn l-1;\n\tlong long int med=l+(h-l)/2;\n\tlong long int n=1,p=0;\n\tfor(long long int i=1;i<size;i++)\n\t{\n\t\tif(a[i]-a[p]>=med)\n\t\t{\n\t\t\tn++;\n\t\t\tp=i;\n\t\t}\n\t}\n\tif(n>=k)\n\t\tkcows(med+1,h,k,a,size);\n\telse\n\t\tkcows(l,med,k,a,size);\n}\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n,k;\n\t\tcin>>n>>k;\n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tsort(a,a+n);\n\t\tcout<<kcows(a[0],a[n-1],k,a,n)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5191637873649597,
"alphanum_fraction": 0.5470383167266846,
"avg_line_length": 12.090909004211426,
"blob_id": "40ea681aebe25d9b7ae082745a83e8b87741d323",
"content_id": "b410989c348b045909b8957f6a67a115ba8ca4a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 22,
"path": "/SPOJ/OLOLO.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<stdio.h>\nusing namespace std;\nint main()\n{\n\tint n;\n\tcin>>n;\n\tint *a=new int[n];\n\tfor(int i=0;i<n;i++)\n\t\tscanf(\"%d\",&a[i]);\n\tint temp=a[0];\n\tfor(int i=1;i<n;i++)\n\t{\n\t\ttemp^=a[i];\n\t}\n\tprintf(\"%d\\n\",temp);\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5701219439506531,
"alphanum_fraction": 0.5838414430618286,
"avg_line_length": 17.77142906188965,
"blob_id": "ecd7a814bd34e26f840d45d4c76120694971b6b5",
"content_id": "996499ee316de9c648739a4a7efa945d5798bf35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 656,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 35,
"path": "/SPOJ/ACPC11B.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <iostream>\n#include <limits.h>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n\t// your code goes here\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long int n;\n\t\tcin>>n;\n\t\tlong long int *a=new long long int[n];\n\t\tfor(long long int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tlong long int m;\n\t\tcin>>m;\n\t\tlong long int *b=new long long int[m];\n\t\tfor(long long int i=0;i<m;i++)\n\t\t\tcin>>b[i];\n\t\tsort(a,a+n);sort(b,b+m);\n\t\tlong long int minimum=INT_MAX;\n\t\tfor(long long int i=0;i<n;i++)\n\t\t\tfor(long long int j=0;j<m;j++)\n\t\t\t\tif(abs(a[i]-b[j])<minimum)\n\t\t\t \t\tminimum=abs(a[i]-b[j]);\n\t\tcout<<minimum<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.35232508182525635,
"alphanum_fraction": 0.4080435633659363,
"avg_line_length": 19.947368621826172,
"blob_id": "adeab020d823ccbc94fee1d5050b4b1f7cc817dc",
"content_id": "042cee504e8ec0c1d310b819763ea152ebba9130",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2387,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 114,
"path": "/SPOJ/BITMAP.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,m;\n\t\tqueue<pair<int,int> > q;\n\t\tcin>>n>>m;\n\t\tchar c[200][200];\n\t\tint a[200][200],A[200][200];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>c[i];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tfor(int j=0;j<m;j++)\n\t\t\t{\n\t\t\t\tA[i][j]=-1;\n\t\t\t\ta[i][j]=c[i][j]-48;\n\t\t\t\tif(a[i][j])\n\t\t\t\t{\n\t\t\t\t\tA[i][j]=0;\n\t\t\t\t\tq.push(make_pair(i,j));\n\t\t\t\t}\n\t\t\t}\n\t\twhile(!q.empty())\n\t\t{\n\t\t\tpair<int,int> p=q.front();\n\t\t\tq.pop();\n\t\t\t//cout<<p.first<<\" \"<<p.second<<endl;\n\t\t\tif(p.first>0&&p.first<n-1&&p.second>0&&p.second<m-1)\n\t\t\t{\n\t\t\t\tint b[4][2]={{1,0},{0,1},{-1,0},{0,-1}};\n\t\t\t\tfor(int i=0;i<4;i++)\n\t\t\t\t{\n\t\t\t\t\tif(A[p.first+b[i][0]][p.second+b[i][1]]==-1)\n\t\t\t\t\t{\n\t\t\t\t\t//\tcout<<p.first+b[i][0]<<\" \"<<p.second+b[i][1]<<endl;\n\t\t\t\t\t\tq.push(make_pair(p.first+b[i][0],p.second+b[i][1]));\n\t\t\t\t\t\tA[p.first+b[i][0]][p.second+b[i][1]]=1+A[p.first][p.second];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(p.first>0&&p.first<n-1)\n\t\t\t\t{\n\t\t\t\t\tif(p.second>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint b[3][2]={{1,0},{-1,0},{0,-1}};\n\t\t\t\t\t\tfor(int i=0;i<3;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(A[p.first+b[i][0]][p.second+b[i][1]]==-1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push(make_pair(p.first+b[i][0],p.second +b[i][1]));\n\t\t\t\t\t\t\t\tA[p.first+b[i][0]][p.second+b[i][1]]=1+A[p.first][p.second];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tint b[3][2]={{1,0},{-1,0},{0,-1}};\n\t\t\t\t\t\tfor(int i=0;i<3;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(A[p.first+b[i][0]][p.second+b[i][1]]==-1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push(make_pair(p.first+b[i][0],p.second +b[i][1]));\n\t\t\t\t\t\t\t\tA[p.first+b[i][0]][p.second+b[i][1]]=1+A[p.first][p.second];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(p.first>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint b[3][2]={{0,1},{-1,0},{0,-1}};\n\t\t\t\t\t\tfor(int i=0;i<3;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(A[p.first+b[i][0]][p.second+b[i][1]]==-1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push(make_pair(p.first+b[i][0],p.second +b[i][1]));\n\t\t\t\t\t\t\t\tA[p.first+b[i][0]][p.second+b[i][1]]=1+A[p.first][p.second];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tint b[3][2]={{1,0},{0,1},{0,-1}};\n\t\t\t\t\t\tfor(int i=0;i<3;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(A[p.first+b[i][0]][p.second+b[i][1]]==-1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tq.push(make_pair(p.first+b[i][0],p.second +b[i][1]));\n\t\t\t\t\t\t\t\tA[p.first+b[i][0]][p.second+b[i][1]]=1+A[p.first][p.second];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tfor(int j=0;j<m;j++)\n\t\t\t\tcout<<A[i][j]<<\" \";\n\t\t\tcout<<endl;\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.5708333253860474,
"alphanum_fraction": 0.5958333611488342,
"avg_line_length": 13.176470756530762,
"blob_id": "237c891666cb11ae613d1674df554cc8bdf49424",
"content_id": "c2e276f27ab6062cb5e218b43e37621ec2683b3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 17,
"path": "/SPOJ/WILLITST.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<cmath>\nusing namespace std;\nint main()\n{\n\tlong long int t;\n\tcin>>t;\n\tdouble k=log(t)/log(2);\n\tint x=floor(k);\n\tif(x!=k)\t\tcout<<\"NIE\";\n\telse\t\t\t\tcout<<\"TAK\";\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4468664824962616,
"alphanum_fraction": 0.46866485476493835,
"avg_line_length": 17.350000381469727,
"blob_id": "95a91bc3ec62ea474d6b89cf67dbe278abf2a77d",
"content_id": "70cb2be9817ad73734b740d90d885c687766d016",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 367,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 20,
"path": "/Codechef/ZCO13001.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n long long int n,sum=0;\n cin>>n;\n long long int *a=new long long int[n];\n for(int i=0;i<n;i++)\n cin>>a[i];\n sort(a,a+n);\n for(int i=0;i<n;i++)\n {\n sum+=i*a[i];\n sum-=(n-1-i)*a[i];\n }\n cout<<sum<<endl;\n} "
},
{
"alpha_fraction": 0.5203620195388794,
"alphanum_fraction": 0.5520362257957458,
"avg_line_length": 13.800000190734863,
"blob_id": "4987f625f3fcd7e2e970522eadaa60b5266741bc",
"content_id": "32185ef8930b995cbc8b7f117e7b1fb81dc88b3d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 221,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 15,
"path": "/SPOJ/ATOMS.py",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "''' Author - Aditya Haridas Menon\n \t Spoj id - ad2411\n'''\n\t\nimport math\nt=int(input())\nwhile t!=0:\n\tn,k,m=map(int,input().split())\n\tif n>m:\n\t\tprint (0)\n\telse:\n\t\tp=int(m/n)\n\t\ta=math.floor(math.log(p)/math.log(k))\n\t\tprint (a)\n\tt=t-1"
},
{
"alpha_fraction": 0.4242857098579407,
"alphanum_fraction": 0.4642857015132904,
"avg_line_length": 11.745454788208008,
"blob_id": "441109fece332acb329cf2b27067737a7cd91e47",
"content_id": "b19dc6c509242285ce8852c7434bc2580178b2f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 700,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 55,
"path": "/SPOJ/CODERE3.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint cdr(int a[],int n)\n{\n\tint lis[1001],lds[1001];\n\tlis[0]=lds[n-1]=1;\n\tfor(int i=n-2;i>=0;i--)\n\t{\n\t\tint mx=1;\n\t\tfor(int j=i+1;j<n;j++)\n\t\t{\n\t\t\tif(a[i]>a[j])\n\t\t\t{\n\t\t\t\tmx=max(mx,1+lds[j]);\n\t\t\t}\n\t\t}\n\t\tlds[i]=mx;\n\t}\n\tfor(int i=1;i<n;i++)\n\t{\n\t\tint mx=1;\n\t\tfor(int j=0;j<i;j++)\n\t\t{\n\t\t\tif(a[i]>a[j])\n\t\t\t{\n\t\t\t\tmx=max(mx,1+lis[j]);\n\t\t\t}\n\t\t}\n\t\tlis[i]=mx;\n\t}\n\tint M=1;\n\tfor(int i=0;i<n;i++)\n\t\tM=max(M,lis[i]+lds[i]-1);\n\t\t//cout<<lis[i]<<\"\\t\"<<lds[i]<<endl;\n\treturn M;\n\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint *a=new int[n];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tcout<<cdr(a,n)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4534161388874054,
"alphanum_fraction": 0.49534162878990173,
"avg_line_length": 13.659090995788574,
"blob_id": "0c5bab1a89ebc089e3cf3931fc60359ccac3aa09",
"content_id": "89676cc84e52792e8ebb3f33ee70be63ec4b54d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 44,
"path": "/SPOJ/BEHAPPY.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint findVal(int a[],int b[],int n,int m)\n{\n\tvector <int> dp1,dp2;\n\tfor(int i=a[0];i<=b[0];i++)\n\t\tdp1.push_back(i);\n\tfor(int i=1;i<n;i++)\n\t{\n\t\tdp2.clear();\n\t\tfor(int j=a[i];j<=b[i];j++)\n\t\t{\n\t\t\tfor(int k=0;k<dp1.size();k++)\n\t\t\t{\n\t\t\t\tdp2.push_back(dp1[k]+j);\n\t\t\t}\n\t\t}\n\t\tdp1=dp2;\n\t}\n\tint c=0;\n\tfor(int i=0;i<dp1.size();i++)\n\t\tc+=(dp1[i]==m)?1:0;\n\treturn c;\n}\nint main()\n{\n\twhile(1)\n\t{\n\t\tint n,m;\n\t\tcin>>n>>m;\n\t\tif(n==0&&m==0)\n\t\t\tbreak;\n\t\tint *a=new int[n],*b=new int[n];\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>a[i]>>b[i];\n\t\t}\n\t\tcout<<findVal(a,b,n,m)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.29205021262168884,
"alphanum_fraction": 0.3698744773864746,
"avg_line_length": 31.283782958984375,
"blob_id": "349ee79f9639a886efccffc6269454893f88b79e",
"content_id": "aece898b3f9b6afeabfd5f772ddeb85eda09c9a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2390,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 74,
"path": "/Codechef/CHEFCCYL.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n ll n,q,v,e;\n cin>>n>>q;\n vector<vector<ll> > g(n+1);\n vector<ll> G(2*(n+1),0);\n for(ll i=1;i<=n;i++)\n {\n cin>>v;\n g[i].resize(v+2,0);\n g[i][1]=0;\n for(ll j=1;j<=v;j++)\n {\n cin>>e;\n g[i][j+1]=g[i][j]+e;\n }\n // cout<<g[i].size()<<endl;\n }\n vector<ll> v1(n+1),v2(n+1),E(n+1);\n for(ll i=1;i<=n;i++)\n { \n cin>>v1[i]>>v2[i]>>E[i];\n }\n G[1]=0;\n G[2]=min(abs(g[1][v1[1]]-g[1][v2[n]]),g[1][g[1].size()-1]-abs(g[1][v1[1]]-g[1][v2[n]]));\n //cout<<abs(g[1][v1[1]]-g[1][v2[n]])<<\" \"<<g[1][g[1].size()-1]<<endl;\n for(ll i=3,j=1;j<n;i+=2,j++)\n {\n //cout<<j<<endl;\n G[i]=G[i-1]+E[j];\n G[i+1]=G[i]+min(abs(g[j+1][v1[j+1]]-g[j+1][v2[j]]),g[j+1][g[j+1].size()-1]-abs(g[j+1][v1[j+1]]-g[j+1][v2[j]]));\n }\n G[2*n+1]=G[2*n]+E[n];\n \n //for(ll i=1;i<=2*n;i+=2)\n //{\n // cout<<G[i]<<\" \"<<G[i+1]<<endl;\n //}\n //cout<<G[2*n+1];\n for(ll i=0;i<q;i++)\n {\n int V1,V2,C1,C2;\n cin>>V1>>C1>>V2>>C2;\n if(n==1||C1==C2||C1>n||C2>n||V1>g[C1].size()-1||V2>g[C2].size()-1)\n {\n cout<<0<<endl;\n break;\n }\n if(C1>C2)\n swap(C1,C2),swap(V1,V2);\n ll dcw=min(abs(g[C1][V1]-g[C1][v1[C1]]),g[C1][g[C1].size()-1]-abs(g[C1][V1]-g[C1][v1[C1]]));\n ll cdcw=dcw+abs(G[C2*2-1]-G[C1*2]);\n ll D1=cdcw+min(abs(g[C2][V2]-g[C2][(C2==1)?v2[n]:v2[C2-1]]),g[C2][g[C2].size()-1]-abs(g[C2][V2]-g[C2][(C2==1)?v2[n]:v2[C2-1]]));\n //cout<<dcw<<\" \"<<cdcw<<\" \"<<D1<<endl;\n ll dacw=min(abs(g[C1][V1]-g[C1][(C1==1)?v2[n]:v2[C1-1]]),g[C1][g[C1].size()-1]-abs(g[C1][V1]-g[C1][(C1==1)?v2[n]:v2[C1-1]]));\n ll acdacw=dacw+abs(G[G.size()-1]-abs(G[C1*2-1]-G[C2*2]));\n ll D2=acdacw+min(abs(g[C2][V2]-g[C2][v1[C2]]),g[C2][g[C2].size()-1]-abs(g[C2][V2]-g[C2][v1[C2]]));\n //cout<<dacw<<\" \"<<acdacw<<\" \"<<D2<<endl;\n cout<<min(D1,D2)<<endl;\n }\n \n \n }\n} \n"
},
{
"alpha_fraction": 0.5317559242248535,
"alphanum_fraction": 0.5628891587257385,
"avg_line_length": 14.169811248779297,
"blob_id": "816f561b955caac471f6ce921b246b5a631d808d",
"content_id": "5a4d33aa2bbc9fa2b80b7e07c5c02938bee784d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 803,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 53,
"path": "/SPOJ/PT07Z.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nvector<bool> a(10001,false);\nvector<bool> b(10001,false);\nint length=0,maximum=0;\nint t1;\nvoid dfsVal(vector<int> v[],int val)\n{\n\tif(length>maximum)\n\t{\n\t\tt1=val;\n\t\tlength=maximum;\n\t}\n\ta[val]=true;\n\tfor(vector<int>::iterator i=v[val].begin();i!=v[val].end();i++)\n\t{\n\t\tif(!a[*i])\n\t\t{\n\t\t\tlength++;\n\t\t\tdfsVal(v,*i);\n\t\t\tlength--;\n\t\t}\n\t}\n}\nint dfs(vector<int> v[],int val)\n{\n\tb[val]=true;\n\tint count=-1;\n\tfor(vector<int>::iterator i=v[val].begin();i!=v[val].end();i++)\n\t{\n\t\tif(!b[*i])\n\t\t\t\tcount=max(dfs(v,*i),count);\n\t}\n\treturn count+1;\n}\nint main()\n{\n\tint n,a,b;\n\tcin>>n;\n\tvector <int> v[n+1];\n\tfor(int i=0;i<n-1;i++)\n\t{\n\t\tcin>>a>>b;\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t}\n\tdfsVal(v,1);\n\tcout<<dfs(v,t1)<<endl;\n}"
},
{
"alpha_fraction": 0.2782694101333618,
"alphanum_fraction": 0.3136676549911499,
"avg_line_length": 11.253011703491211,
"blob_id": "53bec356d067e330acc1f53239861231a16b800b",
"content_id": "2203e1875d116a747484dc63e6506beb95e4f80c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1017,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 83,
"path": "/Codechef/ROWSOLD.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n \n{\n \n int t;\n \n cin>>t;\n \n while(t--)\n \n {\n \n string s;\n \n cin>>s;\n \n long long int trig=-1,count0=0,count1=0;\n long long int time=0;\n \n for(int i=0;i<s.length();i++)\n \n {\n \n if(trig==-1&&s[i]=='1')\n \n {\n \n trig=0;\n \n count1++;\n \n }\n \n else if(trig==0&&s[i]=='0')\n \n {\n \n trig=1;\n \n count0++;\n \n }\n \n else if(trig==1&&s[i]=='1')\n \n {\n \n time+=(count0+1)*count1;\n \n trig=0;\n \n count1++;\n \n count0=0;\n \n }\n \n else if(trig==0)\n \n count1++;\n \n else if(trig==1)\n \n count0++;\n \n }\n \n if(trig==1)\n \n time+=(count0+1)*count1;\n \n cout<<time<<endl;\n \n }\n \n} "
},
{
"alpha_fraction": 0.4216027855873108,
"alphanum_fraction": 0.44947734475135803,
"avg_line_length": 9.285714149475098,
"blob_id": "9bdddceea19d42115da4d87d1cc2354a72f2efef",
"content_id": "fc86acbe01ab263ba103112035d4c73b32009add",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 28,
"path": "/SPOJ/ACMT.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint a,b,c=0;\n\t\tcin>>a>>b;\n\t\twhile(a&&b)\n\t\t{\n\t\t\tif(a==1&&b==1)\n\t\t\t\tbreak;\n\t\t\tif(a<b)\n\t\t\t\tswap(a,b);\n\t\t\tc++;\n\t\t\ta-=2;\n\t\t\tb--;\n\t\t}\n\t\tcout<<c<<endl;\n\t}\n\n}"
},
{
"alpha_fraction": 0.49336549639701843,
"alphanum_fraction": 0.5392038822174072,
"avg_line_length": 16.659574508666992,
"blob_id": "46b0f1fcc353ecf1ddc4bfbf9ad3616f751d9be9",
"content_id": "27f815650cca4c742d21839d4e5ef92bd1b8b0ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 829,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 47,
"path": "/SPOJ/ACODE.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<string.h>\n#include<map>\nusing namespace std;\nmap <long long int,long long int> a;\nlong long int rec(char str[],int i=0)\n{\t\n\tif(i>=strlen(str)-1&&str[i]!=48)\treturn 1;\n\tif(a.find(i)!=a.end())\n\treturn a[i];\n\tint t;\n\t{\n\tif(str[i]!=48) t=rec(str,i+1);\n\telse\n\t\tt=0;\n\t//\tcout<<\"t1=\"<<t<<endl;\n\t}\n\tint k=(str[i]-48)*10,o=(str[i+1]-48);\n\tint s=k+o;\n\t//cout<<s<<endl;\n\tif(s>0&&s<=26 && str[i]!='0') \n\t{\n\t//\tcout<<\"check1 \"<<rec(str,i+1)+rec(str,i+2)<<\"\\n\";\n\t\tt+=rec(str,i+2);\n\t}\n\t//cout<<\"t=\"<<t<<endl;\n\ta[i]=t;\n\treturn t;\n}\nint main()\n{\n\t\n\twhile(1)\n\t{ a.clear();\n\t\tchar str[6000];\n\t\tcin>>str;\n\t\tif(str[0]==48)\tbreak;\n\t\tcout<<rec(str)<<endl;\n\t//\tfor(map<long long int,long long int>::iterator i=a.begin();i!=a.end();i++)\n\t//\tcout<< i->second;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4217067062854767,
"alphanum_fraction": 0.4722452461719513,
"avg_line_length": 13.380952835083008,
"blob_id": "b90ebc4112c7680dae80ec52ef888838b1636b77",
"content_id": "c7b0db6d1efdce732a644b5e7c96e670443b0a42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1207,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 84,
"path": "/SPOJ/UOFTAE.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll findVal(ll a[],ll b[],ll n,ll m)\n{\n\tvector <ll> dp1,dp2;\n\tif(n==1)\n\t{\n\t\tif(a[0]<=m&&b[0]>=m)\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\tfor(ll i=a[0];i<=min(m,b[0]);i++)\n\t{\n\t\tdp1.push_back(i);\n\t}\n\t\n\tfor(ll i=1;i<n-1;i++)\n\t{\n\t\t//cout<<dp1.size()<<endl;\n\t\tdp2.clear();\n\t\tfor(ll j=0;j<dp1.size();j++)\n\t\t{\n\t\t\tfor(ll k=a[i];k+dp1[j]<m&&k<=b[i];k++)\n\t\t\t\tdp2.push_back(k+dp1[j]);\n\t\t}\n\t\tdp1=dp2;\n\t}\n\tdp2.clear();\n\t//for(ll i=0;i<dp1.size();i++)\n\t//\tcout<<dp1[i]<<\" \";\n\t//cout<<endl;\n\tll c=0;\n\t//cout<<dp1.size()<<endl;\n\tfor(ll i=0;i<dp1.size();i++)\n\t{\n\t\tif(m-dp1[i]>=a[n-1]&&m-dp1[i]<=b[n-1])\n\t\t\tc++;\n\t}\n\t/*\n\tfor(i=2;i<n;i++)\n\t{\n\t\tdp2.clear();\n\t\tif(a[i]+dp1[0]>m)\n\t\t\tbreak;\n\t\tfor(ll j=a[i];j<=min(b[i],m);j++)\n\t\t{\n\t\t\tfor(ll k=0;k<dp1.size() && dp1[k]+j<=m;k++)\n\t\t\t{\n\t\t\t\tdp2.push_back(dp1[k]+j);\n\t\t\t\tif(i==n-1&&dp1[k]+j==m)\n\t\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\t\tdp1=dp2;\n\t\t\n\t}\n\t*/\n\t\n\t\n\treturn c;\n}\nint main()\n{\n\tios::sync_with_stdio(false);\n\tll t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tll n,m;\n\t\tcin>>n>>m;\n\t\tll *a=new ll[n],*b=new ll[n];\n\t\tfor(ll i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>a[i]>>b[i];\n\t\t}\n\t\tcout<<findVal(a,b,n,m)%1000000007<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.38967740535736084,
"alphanum_fraction": 0.4606451690196991,
"avg_line_length": 14.215685844421387,
"blob_id": "70ada0c1c816fed45da4f16c3319f7c0fc48e289",
"content_id": "94cb359d0ac826bf4808423e69ca0b918a9f3fa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 775,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 51,
"path": "/SPOJ/ANARC05B.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\nmap<ll,ll> m;\nint main()\n{\n\twhile(1)\n\t{\n\t\tm.clear();\n\t\tll n1,n2;\n\t\tcin>>n1;\n\t\tif(n1==0) break;\n\t\tvector<ll> v1(n1);\n\t\tfor(ll i=0;i<n1;i++)\n\t\t{\n\t\t\tcin>>v1[i];\n\t\t\tm[v1[i]]++;\n\t\t}\n\t\tcin>>n2;\n\t\tvector<ll> v2(n2),l;\n\t\tfor(ll i=0;i<n2;i++)\n\t\t{\n\t\t\tcin>>v2[i];\n\t\t\tm[v2[i]]++;\n\t\t\tif(m[v2[i]]==2)\n\t\t\t\tl.push_back(v2[i]);\n\t\t}\n\t\tll k=0,j=0,S=0,S1=0,S2=0;\n\t\tfor(vector<ll>::iterator i=l.begin();i!=l.end();i++)\n\t\t{\n\t\t\tll s1=0,s2=0;\n\t\t\tfor(;v1[k]!=*i&&k<n1;k++)\n\t\t\t\ts1+=v1[k];\n\t\t\tfor(;v2[j]!=*i&&j<n2;j++)\n\t\t\t\ts2+=v2[j];\n\t\t\t//cout<<s\n\t\t\tS+=max(s1,s2)+(*i);\n\t\t\tk++;j++;\n\t\t}\n\t\tfor(;k<n1;k++)\n\t\t\tS1+=v1[k];\n\t\tfor(;j<n2;j++)\n\t\t\tS2+=v2[j];\n\t\tS+=max(S1,S2);\n\t\tcout<<S<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5023584961891174,
"alphanum_fraction": 0.5235849022865295,
"avg_line_length": 12.709677696228027,
"blob_id": "c7703cf0cd7cb76ff7b56d1dea30dffe7f35b302",
"content_id": "6efe302d5e5d3e81e4dc6800b7ca06a14c843d56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 424,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 31,
"path": "/SPOJ/FASHION.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<iostream>\n#include<math.h>\n#include<algorithm>\nusing namespace std;\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint *m=new int[n];\n\t\tint* w=new int [n];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>m[i];\n\t\tfor(int i=0;i<n;i++)\n\t\t\tcin>>w[i];\n\t\tsort(m,m+n);\n\t\tsort(w,w+n);\n\t\tint sum=0;\n\t\tfor(int i=0;i<n;i++)\n\t\t\t\tsum+=m[i]*w[i];\n\t\t\t\tcout<<sum<<endl;\n\t}\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.3098360598087311,
"alphanum_fraction": 0.3360655605792999,
"avg_line_length": 16.428571701049805,
"blob_id": "c86cd3b8770816789d06a6bb1ad4efb361bced89",
"content_id": "2fc30db833eb7f9cc81f1cb1ef0bb31affd87e5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 610,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 35,
"path": "/Codechef/MXMEDIAN.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n;\n cin>>n;\n int *a=new int[2*n],*b=new int[2*n];\n for(int i=0;i<2*n;i++)\n cin>>a[i];\n sort(a,a+2*n);\n int i=0,j=0;\n while(1)\n {\n b[j]=a[i];\n b[j+1]=a[n+i];\n j+=2;\n i++;\n if(i>=n)\n break;\n }\n cout<<b[n]<<endl;\n for(int i=0;i<2*n;i++)\n cout<<b[i]<<\" \";\n cout<<endl;\n }\n \n \n} "
},
{
"alpha_fraction": 0.37622377276420593,
"alphanum_fraction": 0.4363636374473572,
"avg_line_length": 17.842105865478516,
"blob_id": "28f41ac0b3c0f1811badbb0e7cfdcb1a8f7b7be5",
"content_id": "c577d665a2f93f3d373db5cfda3611b25b67bd00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 715,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 38,
"path": "/SPOJ/AIBOHP.cpp",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Spoj id - ad2411\n\n*/\t\n#include<bits/stdc++.h>\nusing namespace std;\nint lcs(char s1[],int s1_l,char s2[],int s2_l)\n{ \n\tint L[s1_l+1][s2_l+1];\n \tfor (int i=0; i<=s1_l; i++)\n \t{\n \tfor (int j=0; j<=s2_l; j++)\n \t{\n \t\tif (i == 0 || j == 0)\n \t\tL[i][j] = 0;\n \t\telse if (s1[i-1] == s2[j-1])\n \t\tL[i][j] = L[i-1][j-1] + 1; \n \t\telse\n \t\tL[i][j] = max(L[i-1][j], L[i][j-1]);\n \t }\n \t}\n\treturn L[s1_l][s2_l];\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tchar s[6101];\n\t\tcin>>s;\n\t\tchar *s1=new char[strlen(s)];\n\t\tfor(int i=strlen(s)-1,j=0;i>=0;i--)\n\t\t\ts1[j++]=s[i];\n\t\ts1[strlen(s)]='\\0';\n\t\tcout<<strlen(s)-lcs(s,strlen(s),s1,strlen(s1))<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.31525424122810364,
"alphanum_fraction": 0.3423728942871094,
"avg_line_length": 11.333333015441895,
"blob_id": "9bc4e7e3f5b6466c291f7a90882d29c94542c00e",
"content_id": "f7419e04f376044847c169171f38a2aab61517c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 295,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 24,
"path": "/Codechef/FCTRL.c",
"repo_name": "adMenon/Competetive-programing-codes",
"src_encoding": "UTF-8",
"text": "/* Author - Aditya Haridas Menon\n Codechef id - ad2411\n */\n#include <stdio.h>\n \n \n \n \nint main(){\n \nint n,v,c;\n scanf(\"%d\",&n);\n while(n--){\n scanf(\"%d\",&v);\n c=0;\n while(v>=5){\n v /= 5;\n c += v;\n }\n printf(\"%d\\n\",c);\n }\n \n return 0;\n}"
}
] | 130 |
yosiat/yfs | https://github.com/yosiat/yfs | cfb86ee88d0bea43557585dea7ce17bbe645705f | 8b436c8c5a83830d712d26fb6665dcebb28e9f63 | ea59d48638ac7c664ab5cef70a3d20c4100bbadf | refs/heads/master | 2016-09-11T08:23:11.119994 | 2014-04-20T18:56:21 | 2014-04-20T18:56:21 | 18,945,133 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4285714328289032,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 13,
"blob_id": "ba5e51ab280b9140b11716032f29cb1765e16c10",
"content_id": "a59f0d79ac9145d2b4cf5c17ec300274c70b6d24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 28,
"license_type": "no_license",
"max_line_length": 13,
"num_lines": 2,
"path": "/requirements.txt",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "pytest==2.5.2\nthrift==0.9.1\n"
},
{
"alpha_fraction": 0.5384615659713745,
"alphanum_fraction": 0.6703296899795532,
"avg_line_length": 16.799999237060547,
"blob_id": "02ab386c4bb11df526e4b9fac6389d56364a27b5",
"content_id": "9fdc2da205e5bad9ec00227b9b82533ca1bc76ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 91,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 5,
"path": "/yfs/masterserver/__init__.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "\n\nKiB = 1024\nMiB = 1024 * KiB\n\nDEFAULT_CHUNK_SIZE = 64\nDEFAULT_CHUNK_SIZE_BYTES = 64 * MiB\n"
},
{
"alpha_fraction": 0.7196261882781982,
"alphanum_fraction": 0.7943925261497498,
"avg_line_length": 35,
"blob_id": "ef506cad0664f1027430cc32ad3d4c2e2178dff4",
"content_id": "68057fc101ad7b45272dea05a0f31c3a7f45cf3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 107,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 3,
"path": "/yfs/__init__.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "DEFAULT_MASTER_SERVER_PORT = 9090\nDEFAULT_MASTER_SERVER_HOST = 'localhost'\nDEFAULT_CHUNK_SERVER_PORT = 9092"
},
{
"alpha_fraction": 0.7837837934494019,
"alphanum_fraction": 0.7837837934494019,
"avg_line_length": 17.5,
"blob_id": "e9bf4ccaae3f51b5834cb6b530ee97a9375287f9",
"content_id": "de8e61d5fc85b143a62a5f2cf859b049a34c51b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 37,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 2,
"path": "/pytest.ini",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "[pytest]\nnorecursedirs = lib include\n"
},
{
"alpha_fraction": 0.6118577122688293,
"alphanum_fraction": 0.6150197386741638,
"avg_line_length": 35.07143020629883,
"blob_id": "6cfef8dd7d8872913a5f8e4fe20551eb83443fb3",
"content_id": "e102c715b6deb8a41026e1187f8ed656ca926944",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2530,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 70,
"path": "/yfs/masterserver/handler.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from yfs.Protocol.ttypes import FileNotFoundException\nfrom yfs.masterserver import DEFAULT_CHUNK_SIZE_BYTES\nimport logging\n\n\nclass MasterServerHandler:\n def __init__(self):\n self.file_name_to_file_info = dict()\n self.logger = logging.getLogger('MasterServerHandler')\n\n def up(self, ip, port):\n self.logger.info('MasterServer is serving requests')\n\n def newChunkServer(self, request):\n \"\"\"\n When a new chunk server is going up, he will send the master,\n that he comes up and will send him information he have\n\n :rtype : object\n :param request:\n Parameters:\n - request\n \"\"\"\n self.logger.info(\n \"newChunkServer: {0}:{1} with files - {2}\".format(request.chunkServerIP, request.chunkServerPort,\n request.fileNameToChunkHandles.keys()))\n\n chunk_server_location = request.chunkServerIP, request.chunkServerPort\n\n for file_name, chunk_handles in request.fileNameToChunkHandles.viewitems():\n file_info = self.file_name_to_file_info.get(file_name)\n if file_info is None:\n # We should probably, throw error? or create this file?\n continue\n\n chunks = [file_info.get_chunk_by_handle(handle) for handle in chunk_handles]\n\n for chunk in chunks:\n chunk.locations.update([chunk_server_location])\n\n def getChunkLocations(self, fileIdentifier, length, offset):\n \"\"\"\n Parameters:\n - fileIdentifier\n - length\n - offset\n \"\"\"\n file_info = self.file_name_to_file_info.get(fileIdentifier, None)\n if file_info is None:\n raise FileNotFoundException(fileIdentifier=fileIdentifier)\n\n chunks = file_info.find_chunks_for(length, offset)\n chunks_locations = [chunk.create_chunk_locations() for chunk in chunks]\n chunks_locations = reduce(list.__add__, chunks_locations)\n\n self.logger.info(\n \"getChunkLocations: file identifier: {0}, length: {1}, offset: {2} - return {3} chunk locations\".format(\n fileIdentifier, length, offset, len(chunks_locations)))\n\n return chunks_locations\n\n\n def getDefaultChunkSize(self):\n \"\"\"\n Returns the default chunk size\n :rtype : int\n :return: chunk size\n \"\"\"\n self.logger.info(\"getDefaultChunkSize: {0}\".format(DEFAULT_CHUNK_SIZE_BYTES))\n return DEFAULT_CHUNK_SIZE_BYTES\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.682539701461792,
"alphanum_fraction": 0.6904761791229248,
"avg_line_length": 23.65217399597168,
"blob_id": "4447ea5499d1f8b74e715765fa80000bd0c5b166",
"content_id": "f88fb93486e57a804e6cf26b3ee44bcab3dae583",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1134,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 46,
"path": "/tests/masterserver/metadata/test_Chunk.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from uuid import UUID\nfrom yfs.Protocol.ttypes import ChunkLocation\nfrom yfs.masterserver.metadata.Chunk import Chunk\n\n\ndef test_generate_uuid_if_not_given_Chunk_init():\n # Arrange\n chunk = Chunk()\n\n # Act\n\n # Assert\n assert isinstance(chunk.handle, UUID)\n\n\ndef test_no_locations_create_chunk_locations():\n # Arrange\n chunk = Chunk()\n\n # Act\n locations = chunk.locations\n\n # Assert\n assert len(locations) == 0\n\n\ndef test_create_chunk_locations():\n # Arrange\n first_location = (\"ip1\", \"port1\")\n second_location = (\"ip2\", \"port2\")\n locations = list([first_location, second_location])\n chunk = Chunk(locations=locations)\n\n expected_locations = list()\n expected_locations.append(\n ChunkLocation(chunkHandle=chunk.handle, chunkServerIP=first_location[0], chunkServerPort=first_location[1])\n )\n expected_locations.append(\n ChunkLocation(chunkHandle=chunk.handle, chunkServerIP=second_location[0], chunkServerPort=second_location[1])\n )\n\n # Act\n chunk_locations = chunk.create_chunk_locations()\n\n # Assert\n assert expected_locations == chunk_locations\n"
},
{
"alpha_fraction": 0.7297297120094299,
"alphanum_fraction": 0.7297297120094299,
"avg_line_length": 17.5,
"blob_id": "918f20a6e2297fde05afb44f8e7db29a7d00cb00",
"content_id": "323365430b3ffcbbcfe0f64c0f401e345cfc4162",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 111,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 6,
"path": "/Makefile",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "generate-thrift:\n\trm -rf yfs/Protocol\n\tthrift --gen py -out yfs/ thrift/Protocol.thrift\n\ntest:\n\tpy.test tests/\n"
},
{
"alpha_fraction": 0.5857740640640259,
"alphanum_fraction": 0.5857740640640259,
"avg_line_length": 18.91666603088379,
"blob_id": "f4014410932bd06b7c5a0d3dfbd159c7e1a383b1",
"content_id": "b3737114f88c4d9fbeeda0a3e9eba2204917e225",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 239,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 12,
"path": "/setup.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from distutils.core import setup\n\nsetup(\n name='yfs',\n version='',\n packages=['yfs', 'yfs.Protocol', 'yfs.chunkserver', 'yfs.masterserver'],\n url='',\n license='',\n author='Yosi',\n author_email='',\n description=''\n)\n"
},
{
"alpha_fraction": 0.680284857749939,
"alphanum_fraction": 0.6862818598747253,
"avg_line_length": 27.148935317993164,
"blob_id": "8b08bfc1f4f6d851c9568e607e78a091ad55dbe9",
"content_id": "ee01c848c2a665f2446c519317c167b664013ef9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2668,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 94,
"path": "/tests/masterserver/metadata/test_FileInfo.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from random import randint\nimport uuid\nfrom tests.helper import get_length_by_handles_count\nimport yfs.masterserver\nfrom yfs.masterserver.metadata.Chunk import Chunk\nfrom yfs.masterserver.metadata.FileInfo import FileInfo\n\n\ndef test_exact_chunk_handles_conversion():\n # Arrange\n expected_chunk_handles_count = 10\n length = expected_chunk_handles_count * yfs.masterserver.DEFAULT_CHUNK_SIZE_BYTES\n file_info = FileInfo(\"name\", length)\n\n # Act\n chunk_handles_count = len(file_info.chunks)\n\n # Assert\n assert expected_chunk_handles_count == chunk_handles_count\n\n\n\n\n\ndef test_chunk_handles_conversion():\n # Arrange\n expected_chunk_handles_count = 8\n file_info = FileInfo(\"name\", get_length_by_handles_count(expected_chunk_handles_count))\n\n # Act\n chunk_handles_count = len(file_info.chunks)\n\n # Assert\n assert expected_chunk_handles_count == chunk_handles_count\n\n\ndef test_zero_offset_find_handles():\n # Arrange\n length = randint(3, 100)\n file_info = FileInfo(\"name\", get_length_by_handles_count(length))\n\n expected_handles_count = 2\n expected_chunk_handles = file_info.chunks[:expected_handles_count]\n\n # Act\n handles = file_info.find_chunks_for(expected_handles_count * yfs.masterserver.DEFAULT_CHUNK_SIZE_BYTES)\n\n\n # Assert\n assert expected_handles_count == len(handles)\n assert expected_chunk_handles == handles\n\n\ndef test_given_offset_find_handles():\n # Arrange\n file_length = 24\n file_info = FileInfo(\"name\", get_length_by_handles_count(file_length))\n\n expected_handles_count = 3\n find_offset = 2\n expected_chunk_handles = file_info.chunks[find_offset:find_offset + expected_handles_count]\n\n # Act\n handles = file_info.find_chunks_for(expected_handles_count * yfs.masterserver.DEFAULT_CHUNK_SIZE_BYTES,\n offset=find_offset * yfs.masterserver.DEFAULT_CHUNK_SIZE_BYTES)\n\n # Assert\n assert expected_handles_count == len(handles)\n assert expected_chunk_handles == handles\n\ndef test_find_handles():\n # Arrange\n CHUNK_LENGTH = 2\n chunks = [Chunk() for _ in range(CHUNK_LENGTH)]\n file_info = FileInfo(\"name\", get_length_by_handles_count(CHUNK_LENGTH), chunks)\n\n expected_chunk = chunks[1]\n\n # Act\n chunk = file_info.get_chunk_by_handle(expected_chunk.handle)\n\n # Assert\n assert expected_chunk == chunk\n\ndef test_not_exist_chunk_find_handle():\n # Arrange\n file_info = FileInfo(\"name\", get_length_by_handles_count(8))\n expected_chunk = None\n\n # Act\n found_chunk = file_info.get_chunk_by_handle(uuid.uuid4())\n\n # Assert\n assert expected_chunk == found_chunk\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7849462628364563,
"alphanum_fraction": 0.7849462628364563,
"avg_line_length": 23.866666793823242,
"blob_id": "639502ad0c22629c26b3fb5879425fd54d605240",
"content_id": "9855691ff3152383701120bf263d16131852d526",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 372,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 15,
"path": "/scripts/master",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nfrom yfs import DEFAULT_MASTER_SERVER_PORT, DEFAULT_MASTER_SERVER_HOST\nfrom yfs.utils.server_factory import ServerFactory\n\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nlogging.info('Running master server - %s:%s' % (DEFAULT_MASTER_SERVER_HOST, DEFAULT_MASTER_SERVER_PORT))\nserver = ServerFactory.create_master_server()\n\nserver.serve()"
},
{
"alpha_fraction": 0.8158844709396362,
"alphanum_fraction": 0.8158844709396362,
"avg_line_length": 45.16666793823242,
"blob_id": "c764e00e996a9c91590fd611be9c346bf46e43bf",
"content_id": "50e6960c1501ec06122fe4ade9ebfe76291ab00c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 6,
"path": "/tests/masterserver/server/MasterServerHandler/test_MasterServerHandler_getDefaultChunkSize.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from yfs.masterserver.handler import MasterServerHandler\nfrom yfs.masterserver import DEFAULT_CHUNK_SIZE_BYTES\n\ndef test_getDefaultChunkSize():\n master_server_handler = MasterServerHandler()\n assert DEFAULT_CHUNK_SIZE_BYTES == master_server_handler.getDefaultChunkSize()\n"
},
{
"alpha_fraction": 0.7699386477470398,
"alphanum_fraction": 0.7699386477470398,
"avg_line_length": 20.733333587646484,
"blob_id": "74154a5c92dd81f6d3be0668dd2fbf73c693cfde",
"content_id": "ba508f598c4aa543ce0d9f1d0d73a63f4575e211",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 326,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 15,
"path": "/scripts/chunkserver",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport logging\n\nfrom yfs import DEFAULT_CHUNK_SERVER_PORT\nfrom yfs.utils.server_factory import ServerFactory\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nlogging.info('Running chunk server - %s:%s' % ('localhost', DEFAULT_CHUNK_SERVER_PORT))\nserver = ServerFactory.create_chunk_server()\n\nserver.serve()\n"
},
{
"alpha_fraction": 0.7031915187835693,
"alphanum_fraction": 0.7031915187835693,
"avg_line_length": 26.676469802856445,
"blob_id": "fc395a283b75fe8f62343ba0aeac66dfb1602d81",
"content_id": "3d9c0221a077f4c5497925802ac79232684ab44b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 940,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 34,
"path": "/yfs/chunkserver/master_client_provider.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from thrift.protocol import TBinaryProtocol\nfrom thrift.transport import TSocket, TTransport\nfrom yfs import DEFAULT_MASTER_SERVER_PORT, DEFAULT_MASTER_SERVER_HOST\nfrom yfs.Protocol import MasterService\n\n\n\"\"\"\n MasterClientProivder - finds the current master, and returns a client\n connected to this master\n\"\"\"\n\n\nclass MasterClientProvider:\n def __init__(self):\n pass\n\n def _find_connection_info(self):\n return DEFAULT_MASTER_SERVER_HOST, DEFAULT_MASTER_SERVER_PORT\n\n def create(self):\n host, port = self._find_connection_info()\n transport = TSocket.TSocket(host, port)\n\n transport = TTransport.TBufferedTransport(transport)\n protocol = TBinaryProtocol.TBinaryProtocol(transport)\n client = MasterService.Client(protocol)\n transport.open()\n return client\n\n\n @staticmethod\n def get():\n provider = MasterClientProvider()\n return provider.create()"
},
{
"alpha_fraction": 0.7345678806304932,
"alphanum_fraction": 0.7592592835426331,
"avg_line_length": 26.16666603088379,
"blob_id": "6296829f3a38a69b75e2fa90cc3784a5c2f1cd22",
"content_id": "754b9d320d83d60941e2e8a1761f6b2941aa84ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 6,
"path": "/tests/helper.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from random import randint\nimport yfs\n\n\ndef get_length_by_handles_count(length):\n return (length * yfs.masterserver.DEFAULT_CHUNK_SIZE_BYTES) + randint(1, 100)"
},
{
"alpha_fraction": 0.6247113347053528,
"alphanum_fraction": 0.6252886652946472,
"avg_line_length": 31.69811248779297,
"blob_id": "64a36400d6106a9d4aa75f63c513246dd34bbfd4",
"content_id": "cd6c42a477346ad0fd583956f0be3193526242a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1732,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 53,
"path": "/yfs/masterserver/metadata/FileInfo.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "import math\nfrom yfs.masterserver import DEFAULT_CHUNK_SIZE_BYTES\nfrom yfs.masterserver.metadata.Chunk import Chunk\n\n\nclass FileInfo(object):\n def __init__(self, name, length, chunks=None):\n \"\"\"\n name - file name\n length - the length of the file in bytes\n chunks - set of chunk handles associated with this file\n \"\"\"\n self.name = name\n self.length = length\n self.chunks = chunks or self._create_chunk_handles()\n\n def _create_chunk_handles(self):\n \"\"\"\n Create chunk handles\n\n :return: list of Chunk\n \"\"\"\n chunk_handles_count = self._calculate_chunks_count(self.length)\n handles = [Chunk() for _ in range(chunk_handles_count)]\n return handles\n\n def _calculate_chunks_count(self, length):\n \"\"\"\n Calculate the chunks count using default chunk size and length\n :param length: length of blob/file in bytes\n :return: chunks count as integer\n \"\"\"\n return int(math.ceil(length / DEFAULT_CHUNK_SIZE_BYTES))\n\n def find_chunks_for(self, length, offset=0):\n \"\"\"\n Given a length and optional offset, the relevant handles will be returned\n\n :rtype : list of Chunk\n :param length: how to much to read in bytes\n :param offset: bytes count to skip\n \"\"\"\n length_handles_count = self._calculate_chunks_count(length)\n\n offset_handles_count = self._calculate_chunks_count(offset)\n return self.chunks[offset_handles_count:offset_handles_count + length_handles_count]\n\n def get_chunk_by_handle(self, handle):\n for chunk in self.chunks:\n if chunk.handle == handle:\n return chunk\n\n return None"
},
{
"alpha_fraction": 0.6174183487892151,
"alphanum_fraction": 0.6205287575721741,
"avg_line_length": 28.18181800842285,
"blob_id": "63a73b3859f5c98ef8d3e85268febf8650cc47f6",
"content_id": "d079e1ff1635bbda1b6462bcd558ecd0975e1ad9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 643,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 22,
"path": "/yfs/masterserver/metadata/Chunk.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from uuid import uuid4\nfrom yfs.Protocol.ttypes import ChunkLocation\n\n\nclass Chunk(object):\n def __init__(self, handle=None, checksum=None, locations=None):\n \"\"\"\n Chunk\n\n :param handle: UUID\n :param checksum: string of checksum\n :param locations: list of tuples (host, port)\n \"\"\"\n self.handle = handle or uuid4()\n self.checksum = checksum\n self.locations = locations or set()\n\n def create_chunk_locations(self):\n return [\n ChunkLocation(chunkHandle=self.handle, chunkServerIP=ip, chunkServerPort=port)\n for ip, port in self.locations\n ]\n\n"
},
{
"alpha_fraction": 0.7305483222007751,
"alphanum_fraction": 0.7357702255249023,
"avg_line_length": 36.92079162597656,
"blob_id": "4b385ca652bd10ea240abf2cbe2f21e1d577ad38",
"content_id": "90c5f9ae9e362f502f7cf1e174239fbd468b2457",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3830,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 101,
"path": "/tests/masterserver/server/MasterServerHandler/test_MasterServerHandler_newChunkServer.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "\nfrom random import randint\nfrom tests.helper import get_length_by_handles_count\nfrom yfs.Protocol.ttypes import NewChunkServerRequest\nfrom yfs.masterserver.metadata.Chunk import Chunk\nfrom yfs.masterserver.metadata.FileInfo import FileInfo\nfrom yfs.masterserver.handler import MasterServerHandler\n\n\ndef create_file(name, handles_count):\n return FileInfo(name, get_length_by_handles_count(handles_count))\n\n\ndef test_file_dosent_exist_newChunkServer():\n # Arrange\n master_server_handler = MasterServerHandler()\n\n chunk_handle = Chunk().handle\n file_name = randint(1, 100)\n\n # - create the request\n fake_request = NewChunkServerRequest(fileNameToChunkHandles=dict())\n fake_request.fileNameToChunkHandles[file_name] = [chunk_handle]\n\n # Act\n master_server_handler.newChunkServer(fake_request)\n\n # Assert\n assert file_name not in master_server_handler.file_name_to_file_info\n\n\ndef test_add_location_to_matching_chunk_and_file_newChunkServer():\n # Arrange\n master_server_handler = MasterServerHandler()\n\n\n # - create two files\n first_file = create_file(\"first\", 3)\n second_file = create_file(\"second\", 5)\n\n # - populate each files with locations\n dummy_first_location = (\"ip1\", \"port1\")\n dummy_second_location = (\"ip2\", \"port2\")\n\n first_file_chunk_handle = first_file.chunks[2].handle\n second_file_chunk_handle = second_file.chunks[4].handle\n\n first_file.chunks[2].locations.update([dummy_first_location])\n second_file.chunks[4].locations.update([dummy_second_location])\n\n\n # - add the files\n master_server_handler.file_name_to_file_info[first_file.name] = first_file\n master_server_handler.file_name_to_file_info[second_file.name] = second_file\n\n # - create the request\n fake_request = NewChunkServerRequest(fileNameToChunkHandles=dict())\n fake_request.chunkServerIP, fake_request.chunkServerPort = dummy_first_location\n fake_request.fileNameToChunkHandles[first_file.name] = [first_file_chunk_handle]\n fake_request.fileNameToChunkHandles[second_file.name] = [second_file_chunk_handle]\n\n # Act\n master_server_handler.newChunkServer(fake_request)\n first_first_after = master_server_handler.file_name_to_file_info[first_file.name]\n second_first_after = master_server_handler.file_name_to_file_info[second_file.name]\n\n first_chunk_locations = first_first_after.get_chunk_by_handle(first_file_chunk_handle).locations\n second_chunk_locations = second_first_after.get_chunk_by_handle(second_file_chunk_handle).locations\n\n # Assert\n assert set([dummy_first_location]) == first_chunk_locations\n assert set([dummy_first_location, dummy_second_location]) == second_chunk_locations\n\ndef test_dont_add_location_twice_newChunkServer():\n # Arrange\n master_server_handler = MasterServerHandler()\n\n # - create two files\n first_file = create_file(\"first\", 3)\n\n # - populate each files with locations\n dummy_first_location = (\"ip1\", \"port1\")\n first_file_chunk_handle = first_file.chunks[2].handle\n\n first_file.chunks[2].locations.update([dummy_first_location])\n\n # - add the files\n master_server_handler.file_name_to_file_info[first_file.name] = first_file\n\n # - create the request\n fake_request = NewChunkServerRequest(fileNameToChunkHandles=dict())\n fake_request.chunkServerIP, fake_request.chunkServerPort = dummy_first_location\n fake_request.fileNameToChunkHandles[first_file.name] = [first_file_chunk_handle]\n\n # Act\n master_server_handler.newChunkServer(fake_request)\n first_first_after = master_server_handler.file_name_to_file_info[first_file.name]\n first_chunk_locations = first_first_after.get_chunk_by_handle(first_file_chunk_handle).locations\n\n # Assert\n assert set([dummy_first_location]) == first_chunk_locations\n assert 1 == len(first_chunk_locations)"
},
{
"alpha_fraction": 0.7255616188049316,
"alphanum_fraction": 0.7395263910293579,
"avg_line_length": 38.238094329833984,
"blob_id": "0a4de83a6ff32d24adfb9c3a08c6079fad2c17aa",
"content_id": "64ce4c243174adf4c28adcdf5ab890d5c94fe723",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1647,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 42,
"path": "/tests/masterserver/server/MasterServerHandler/test_MasterServerHandler_getChunkLocations.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "\"\"\"\n Tests:\n 1. Should raise FileNotFound (test with populated)\n 2. Should find the correct chunk handles\n 3. Should specify the correct location\n\"\"\"\nfrom random import randint\nfrom _pytest.python import raises\nfrom yfs.Protocol.ttypes import FileNotFoundException\nfrom yfs.masterserver.metadata.FileInfo import FileInfo\nfrom yfs.masterserver.handler import MasterServerHandler\nfrom tests.helper import get_length_by_handles_count\n\ndef test_raise_FileNotFound_getChunkLocations():\n # Arrange\n master_server_handler = MasterServerHandler()\n master_server_handler.file_name_to_file_info[\"kabuk\"] = FileInfo(\"kabuk\", get_length_by_handles_count(23))\n\n with raises(FileNotFoundException):\n master_server_handler.getChunkLocations(\"shnitzel\", randint(0, 100), randint(0, 100))\n\n\ndef test_find_correct_chunks_and_locations_getChunkLocations():\n # Arrange\n master_server_handler = MasterServerHandler()\n file = FileInfo(\"name\", get_length_by_handles_count(28))\n expected_location = (\"ip1\", \"port1\")\n expected_chunk_handle = file.chunks[2].handle\n\n file.chunks[2].locations = set([expected_location])\n master_server_handler.file_name_to_file_info[file.name] = file\n\n\n # Act\n chunk_locations = master_server_handler.getChunkLocations(\"name\", get_length_by_handles_count(1), offset=get_length_by_handles_count(2))\n\n # Assert\n assert 1 == len(chunk_locations)\n\n first_chunk_location = chunk_locations[0]\n assert expected_chunk_handle == first_chunk_location.chunkHandle\n assert expected_location == (first_chunk_location.chunkServerIP, first_chunk_location.chunkServerPort)"
},
{
"alpha_fraction": 0.641791045665741,
"alphanum_fraction": 0.641791045665741,
"avg_line_length": 66,
"blob_id": "995951b1a15f0ca3dc1f42749c839e04ba788128",
"content_id": "818f2406aad02b75ffda86ead10c1aebec5de6c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 1,
"path": "/yfs/Protocol/__init__.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "__all__ = ['ttypes', 'constants', 'MasterService', 'ChunkService']\n"
},
{
"alpha_fraction": 0.6336842179298401,
"alphanum_fraction": 0.6336842179298401,
"avg_line_length": 22.799999237060547,
"blob_id": "a1c3adc80001bddd6b0db0df7d9345cdd0b31c5d",
"content_id": "ee1e6985e531a303ada9fa66a2e4df84670dda6b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 475,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 20,
"path": "/yfs/utils/TCallbackSimpleServer.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "import socket\n\n\n'''\n This simple wrapper, is just invoke the handler \"up\" method and say -\n \"We are serving requests.. on this ip and port\"\n'''\n\n\nclass TCallbackSimpleServer:\n def __init__(self, server, handler):\n self._server = server\n self._handler = handler\n\n def serve(self):\n ip = socket.gethostbyname(socket.gethostname())\n port = self._server.serverTransport.port\n\n self._handler.up(ip, port)\n self._server.serve()"
},
{
"alpha_fraction": 0.7067039012908936,
"alphanum_fraction": 0.7067039012908936,
"avg_line_length": 27.639999389648438,
"blob_id": "ccc5d7a6cf66708344b1c5d16ab24ef89097e19a",
"content_id": "a448c45173b480940bed545997d7fdec479f4251",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 716,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 25,
"path": "/yfs/chunkserver/handler.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "import logging\nfrom yfs.Protocol.ttypes import NewChunkServerRequest\nfrom yfs.chunkserver.master_client_provider import MasterClientProvider\n\n\nclass ChunkServerHandler:\n def __init__(self):\n self.master = MasterClientProvider.get()\n self.logger = logging.getLogger('ChunkServerHandler')\n\n\n\n def up(self, ip, port):\n self.logger.info('ChunkServer is serving requests')\n self.logger.info('Sending NewChunkServerRequest to the master')\n\n request = NewChunkServerRequest()\n request.chunkServerIP = ip\n request.chunkServerPort = port\n\n request.fileNameToChunkHandles = dict()\n self.master.newChunkServer(request)\n\n def heartbeat(self):\n pass\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5,
"avg_line_length": 19,
"blob_id": "723f71606ffaf8db81dcffe427ab716131222b4a",
"content_id": "13c763e57cf421cf0f6994acdaa97b8d59c43182",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 1,
"path": "/yfs/masterserver/metadata/__init__.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "__author__ = 'yosy'\n"
},
{
"alpha_fraction": 0.7218543291091919,
"alphanum_fraction": 0.7373068332672119,
"avg_line_length": 25.58823585510254,
"blob_id": "b6b6b9b9a67b36d331b88a75fc7f9d39ccdc2fdb",
"content_id": "7d0ea1a017cde15d7e637cf9569964c0081c5e89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 453,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 17,
"path": "/README.md",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "yfs\n===\n\nYosi File System - Learning clone of Google File System\n\n[![Build\nStatus](https://travis-ci.org/yosiat/yfs.png)](https://travis-ci.org/yosiat/yfs)\n\n\n## To Do\n1. Chunk server\n 1. call to master newChunkServer\n 2. support for read protocol\n2. Meta server support heartbeat\n3. Extract to configuration the default chunk size\n4. Service discovery - simple one, for dynamic master discovery\n5. File creation (will be filled in the future :))\n\n"
},
{
"alpha_fraction": 0.7701674103736877,
"alphanum_fraction": 0.7701674103736877,
"avg_line_length": 38.84848403930664,
"blob_id": "fd4bae1511100457f4f569225bf1ed013891f692",
"content_id": "26ab7f0753cbe02c5df60331b9596622bc2ccbb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1314,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 33,
"path": "/yfs/utils/server_factory.py",
"repo_name": "yosiat/yfs",
"src_encoding": "UTF-8",
"text": "from thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer\nfrom thrift.transport import TSocket, TTransport\n\nfrom yfs import DEFAULT_MASTER_SERVER_PORT, DEFAULT_CHUNK_SERVER_PORT\nfrom yfs.Protocol import ChunkService, MasterService\nfrom yfs.chunkserver.handler import ChunkServerHandler\nfrom yfs.masterserver.handler import MasterServerHandler\nfrom yfs.utils.TCallbackSimpleServer import TCallbackSimpleServer\n\n\nclass ServerFactory(object):\n @staticmethod\n def create_chunk_server():\n handler = ChunkServerHandler()\n processor = ChunkService.Processor(handler)\n return ServerFactory.create_server(handler, processor, DEFAULT_CHUNK_SERVER_PORT)\n\n @staticmethod\n def create_master_server():\n handler = MasterServerHandler()\n processor = MasterService.Processor(handler)\n return ServerFactory.create_server(handler, processor, DEFAULT_MASTER_SERVER_PORT)\n\n\n @staticmethod\n def create_server(handler, processor, port):\n transport = TSocket.TServerSocket(port=port)\n tfactory = TTransport.TBufferedTransportFactory()\n pfactory = TBinaryProtocol.TBinaryProtocolFactory()\n simple_server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)\n\n return TCallbackSimpleServer(simple_server, handler)"
}
] | 24 |
kraemerd17/webpage | https://github.com/kraemerd17/webpage | 03748e44479c6a575909735952a3006a6b135ba9 | b438bbd1f25e565168acca4259df6ab831cdcd0a | 1f1496941d018669e310e1de6d63c60f8f752024 | refs/heads/master | 2016-12-13T13:23:37.140610 | 2016-05-03T03:10:48 | 2016-05-03T03:10:48 | 43,904,609 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7432432174682617,
"alphanum_fraction": 0.7486486434936523,
"avg_line_length": 34.80644989013672,
"blob_id": "61e38409b803d3e2e333ef3a8b9e312e3ac8a242",
"content_id": "ce7c2f17131238931377015250abab5d57c0bcc3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1110,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 31,
"path": "/blog/_posts/2014-11-16-hello.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\nsubheadline: Announcements\ntitle: \"My Blog!\"\nteaser: '<code>printf (\"Hello, World\\n\");</code>'\ndate: November 16, 2014\nbreadcrumb: true\ncategories:\n - blog\ntags:\n - blog\n - announcements\nauthor: David Kraemer\n---\n\nHello and welcome to the first post of my new blog! After some\nconsiderable time, I've finally gotten my MathLAN webpage up and running\nto an extent that I can deem workable. It turns out that HTML scripting\nis a gross ordeal, and it can be an incredibly frustrating process. Of\ncourse, I'm a total HTML noob, and I'll keep messing with this site's\nstructure as I learn new ways of improving it. At some point I'm sure\nthat I will pick up JavaScript, and I'll be sure to include whatever pet\nproject I am working on.\n\nIn the meantime, when my courseload happens to find lulls I will try to\nfind time to write thoughts, ideas, problems, code, research, and other\nrandom insights that I think need to be scribbled down. I am also a\ntotal believer in the MathJax \\\\( \\LaTeX \\\\) plugin, even though it takes a\nbit longer to render the pages.\n\nAnyway, stay tuned for future posts!\n"
},
{
"alpha_fraction": 0.6398823857307434,
"alphanum_fraction": 0.7104360461235046,
"avg_line_length": 39.81999969482422,
"blob_id": "d4193f1229a6e477b102ce211c91880f6f2bec0a",
"content_id": "dcae883526434e85e107c195c13c81bd68e8f0cd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2041,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 50,
"path": "/research/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\nshow_meta: false\ntitle: \"Research\"\npermalink: \"/research/\"\nheader:\n image_fullwidth: 48.jpg\n---\n\n## Current interests\n\n- Rainbow Ramsey Theory on the Integers (equivalent Rainbow statement of Rado's Theorem)\n- Convex optimization\n- Macroeconomic models\n- Forecasting evaluation of the Capital Asset Pricing Model\n- Financial data software development\n- Algorithmic trading and strategy evaluation\n\n## Published papers\n\n- Sidky E. Y., Kraemer D. N., Roth E. G., Ullberg C., Reiser I. S.,\n Pan X.; *Analysis of iterative region-of-interest image\n reconstruction for x-ray computed tomography.* J. Med. Imag.\n 0001;1(3):031007. doi:10.1117/1.JMI.1.3.031007.\n [Link][1]\n- David N. Kraemer ; Erin G. Roth ; Emil Y. Sidky ; Ingrid S. Reiser ; \n Xiaochuan Pan; *Robust iterative image reconstruction for breast CT \n by use of projection differentiation*. Proc. SPIE 9412, Medical Imaging \n 2015: Physics of Medical Imaging, 94123I (March 18, 2015); \n doi:10.1117/12.2082444. [Link][2] \n- Erin G. Roth ; David N. Kraemer ; Emil Y. Sidky ; Ingrid S. Reiser ; \n Xiaochuan Pan; *Improving depth resolution in digital breast tomosynthesis \n by iterative image reconstruction*. Proc. SPIE 9412, Medical Imaging 2015: \n Physics of Medical Imaging, 941258 (March 18, 2015); doi:10.1117/12.2082429. [Link][3]\n \n## Miscellaneous work\n\n- COMAP Modeling Competiton: \"First conclusions to a probalistic\n approach to finding airplane debris at sea\" (February 9, 2014).\n Co-authors: Logan Goldberg and Tan Jimin. **Awarded Honorable Mention (45th US Team for problem B)**. [Link.][4]\n- \"Compromise sans consensus: Mitterrand, Kohl, and the politics of\n the Maastricht treaty\" (May 14, 2014). [Link.][5]\n- Retirement-savings exercise. [Link.][6]\n\n[1]: http://medicalimaging.spiedigitallibrary.org/article.aspx?articleid=1915338\n[2]: http://proceedings.spiedigitallibrary.org/proceeding.aspx?articleid=2210205 \n[3]: http://proceedings.spiedigitallibrary.org/proceeding.aspx?articleid=2210313\n[4]: mcm-competition-submission.pdf\n[5]: maastricht.pdf\n[6]: retirement.pdf\n"
},
{
"alpha_fraction": 0.7857251167297363,
"alphanum_fraction": 0.8019053339958191,
"avg_line_length": 55.521366119384766,
"blob_id": "921e03af0672e53df57686a704f2735265a5653a",
"content_id": "34b4888c4ca03d3084f933a58c2cf8d906b6fc6d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6617,
"license_type": "permissive",
"max_line_length": 176,
"num_lines": 117,
"path": "/blog/_posts/2014-11-19-european-spring.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'European Spring'\nsubheadline: 'Book Review'\nteaser: \"A fiery critique of European policymakers\\' handling of the Euro crisis.\"\nlayout: page\nauthor: David Kraemer\nbook_author: \"Phillippe Legrain\"\ndate: November 19, 2014\ncategories:\n - blog\ntags:\n - 'Euro crisis'\n - 'book reviews'\n - 'political economy'\nauthor: David Kraemer\n---\n\n[*European Spring: Why our economies and politics are in a mess - and how to put them right*][1], by Phillippe Legrain (April 23, 2014)\n\nExhaustive, authoritative, and in well-written prose, this text serves\nas a great survey of all that is rotten in Europe while managing to\nremain upbeat for its future. Legrain is clearly familiar with the\npolitical bargaining, the institutional lags, and inherent structural\nweaknesses of European policy. For anyone interested in understanding\nthe evolution of the 'post' Euro crisis continent, this is a must read.\n\nLegrain, a policy wonk who has advised such Eurocrats as Jose Manuel\nBarroso, is intimately aware of the political machinery in Brussels. He\ndiagnosed the Euro crisis early as a product of political and economic\nfactors far beyond the simplistic narrative of unruly periphery\ngovernments. Indeed, now that more of the economic mainstream begins to\ntire of the Austerian rectitude that has so dominated European\ndiscussion, Legrain's underlying thesis assumes a more powerful\nresonance. His main argument, that the institutional influence of German\nordoliberalism is just as much to blame as Greek profligacy for the Euro\ncrisis, dovetails with the continued evidence that Europe's leaders\nresponded poorly and ineffectually to the crisis. As [Germany narrowly\navoids a double- dip recession][2], Eurocrats might do well to consider \nLegrain's case, again.\n\nStart with the banks. Since Maastricht, a vocal minority has repeatedly\ncalled for a European banking union, which is not only a basic feature\nof currency unions worldwide but helped to prevent a financial\ndepression in the United States after a host of high-profile failures.\nAmerica had the ability and moreover the economic authority to step in\nand bail out AIG and broker deals for the restructuring of the many\nworthless banks. Europe has no such authority. The 'bail-ins' that\nserved as the brunt of Europe's crisis policy were timid and ineffectual\nin comparison. Legrain argues that a proper banking union would at least\ngive the Euro zone a fighting chance against insolvency in its joint\nfinancial sector.\n\nRegarding Greece, Legrain does not deny that the country suffered for\nits government's profligacy. The distinction he makes, however, is\nbetween Greece and the rest of the so-called Euro zone 'periphery,' many\nof whom held respectable public finances (especially compared to\nGermany) prior to the crisis. These countries, with low debts and tame\ninstitutions, only veered towards insolvency after the collapsing\nfinancial environment forced their governments to backstop failing\nbanks—obligations that Legrain believes is inherently unfair for\nnational governments. Seeing the least benefits from the foreign\nadventurism of national banks, the periphery was nevertheless forced by\nthe strictures of the Euro zone to deal with their crises nationally,\nnot continentally. This was the primary fuel that ignited a relatively\nlow-priority spat between Greece and its debtholders into the Euro\ncrisis.\n\nWhy was this permitted? Germany, which had only recently seen the\npayoffs of hard years of structural reforms and was otherwise\ndisinclined to deal with the periphery's problems outright, is the\nanswer. Legrain is little less than scathing in his critique of the\nGermans who, from Angela Merkel to Wolfgang Schauble, brutally enforced\nausterity at the expense of the Euro zone's health. The great disciple\nof German monetary ordoliberalism, the European Central Bank, is the\nbiggest culprit, says Legrain. By failing to pursue quantitative\neasing—or any easing for that matter, it seriously aggravated the crisis\nand is primarily responsible for the sclerotic growth the continent has\nseen ever since.\n\nWhile he is certainly correct that the ECB ought to have become more\naccommodative than the simple assurances that it 'would do whatever it\ntakes to save the Euro,' Legrain takes almost personal offense to the\nECB's policies, which is suspicious. As for Mrs. Merkel, Legrain is too\nharsh; Mrs. Merkel is a reflection of her public. Even were she willing\nto buck the domestic consensus and advocate for a Keynesian response to\nthe crisis (let us not understate: this would imply a rejection of\nnearly fifty years of well-ingrained ordoliberalism), she has not the\npersonality Helmut Kohl or Conrad Adenaeur to stick through it, or the\nwillingness to be booted from office because of it.\n\nHis most critical points, however, are aimed at Britain, and in these he\nhas a much stronger justification. Britain's adoption of German\nausterity measures poured salt onto the wounds of the financial crisis,\naggravated unemployment, and made it economically worse off because of\nit. By failing to address the changing demographic nature of the\ncountry, Britain's governing Tories are very much responsible for the\nrise of the UK Independence Party. UKIP, a rather nasty variety of\nBritish populism, is not only anti-Europe, but against the world,\nseeking to promote an insular society of shopkeepers over the modern\nexample of effective, open, and fair democracy that Britain has become.\nAnd Legrain is correct: this is due to the lack of foresight by the\nlikes of David Cameron and George Osbourne. But the country will\ncontinue to suffer from such populism because of it.\n\nLegrain has compiled a significant list of sources from which he derives\nhis argument. He does not shy from reminding the reader of this\nthroughout the text. Legrain also tends to push his own previous work a\nbit more than the reader may like, though such annoyances do not detract\nfrom the overall analysis. He provides an outline for structural and\nconstitutional reforms needed to produce a more liberal Europe, and\nexplains why his objectives are worthy. Much of it is very reasonable,\nand the continent would benefit from his expertise. However, the\nlikelihood for such an eventuality is slim. It is encouraging, then,\nthat much of the mainstream in economics, at least, is beginning to\nthink more like him.\n\n[1]: http://www.amazon.com/European-Spring-Economies-Politics-Right/dp/1782924809/ref=sr_1_1?ie=UTF8&qid%0A%20%20%20%20%20%20%20%20=1416443967&sr=8-1&keywords=phillipe+legrain\\\n[2]: http://www.bloomberg.com/news/2014-11%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20-18/german-investor-confidence-rebounds-as-recession-averted.html\n"
},
{
"alpha_fraction": 0.7701404094696045,
"alphanum_fraction": 0.7738358974456787,
"avg_line_length": 49.11111068725586,
"blob_id": "b351639f904be8c675c1ead14aaa467dd498e246",
"content_id": "bfddceadc7a285efa0016fc77fd8b6978bd92b7b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4059,
"license_type": "permissive",
"max_line_length": 291,
"num_lines": 81,
"path": "/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\n#layout: frontpage\nlayout: page\nshow_meta: false\ntitle: \"David Kraemer\"\nsubheadline: \"Personal site\"\nheader:\n image_fullwidth: gameofclones.jpg\n caption: <a href=\"http://trendswallpapers.com/wallpaper/wallpaper-3011665\">Image credit</a>\n#widget-1:\n# title: \"Courses\"\n# url: 'courses/'\n# text: 'Courses taught at Grinnell College through the Experimental College (ExCo) program, including courses on data analysis with Python and professional typesetting with LaTeX.'\n#widget-2:\n# title: \"IPython Notebooks\"\n# url: 'ipython/'\n# text: \"I use the IPython Notebook as a tool for prototyping functions and object code before staging them into standalone files. I also will from time to time demo something neat I've stumbled upon in a more formal writeup with a notebook. When I do, I like to post them onto the site.\"\n#widget-3:\n# title: \"Current Interests\"\n# url: 'research/'\n# text: \"This summer I worked on problems with a Ramsey theoretic flavor, studying the solutions to integer systems of linear equations under various \\\"colorings\\\" of the natural numbers. I also enjoy optimization problems and computational finance.\"\n# \n---\n\nI'm a third year mathematics and computer science student at Grinnell College.\nOver the course of the years, I've done some stuffs, and I have accumulated some\nof them here on this website. I have (always unintentionally) rambly blog posts,\nusually about the latest book I read or a technology I'm playing with.\n\n\n## [Courses](courses/)\nI have co-taught two courses at Grinnell through the Grinnell Experimental\nCollege with Caleb Leedy. Basically, we sign up to teach a special-interest\ntopic over a semester and build lessons for a class of interested students. So\nfar, we have taught a course on typesetting with \\\\( \\LaTeX \\\\) as well as a\ncourse on data analysis with Python. I post the course materials for each class\non this site. This spring, we will be leading a financial modeling seminar, so\nstay tuned!\n\n## [Current interests](research/)\n\nLast summer I worked on problems with a Ramsey theoretic flavor, studying the\nsolutions to integer systems of linear equations under various \"colorings\" of\nthe natural numbers. Before that I worked on recovering image data from CT\nscans, particularly in low-dosage environments. I also enjoy optimization\nproblems, modeling and computational finance.\n\nThis semester I am working on two major software projects. One is a grant\napplication management program that my team in CSC 322 is building for the\n[Greater Poweshiek Community Foundation](http://greaterpcf.org/). The other is a\nnew section of the [L-Functions and Modular Forms\nDatabase](http://beta.lmfdb.org), specifically for higher-genus curves. The GPCF\nproject is based on the Ruby on Rails framework, while the LMFDB project uses\nPython's Flask framework. This is all very new for me, but I am excited to learn\nmore!\n\n## [Jupyter notebooks](ipython/)\n\nI am a big proponent of Python and the tools/ecosystem that is developing around\nit. If you have not tried out the [Jupyter notebook][1] yet, you definitely need\nto spend some time with it! It will boost your workflow a ton, but it also is on\nthe vanguard of research reproducibility—prominent journals like Nature now\nhost notebooks for anyone to explore the data of paper submissions.\n\nI use the Jupyter Notebook as a tool for prototyping functions and object code\nbefore staging them into standalone files. I also will from time to time demo\nsomething neat I've stumbled upon in a more formal writeup with a notebook. When\nI do, I like to post them onto the site.\n\n## Useless tidbits\n\n\nBesides studying math and programming, you can regularly catch me reading *The\nEconomist* or playing the viola. I am a big *Simpsons* fan, and I also enjoy\nrunning (the snowier, the better). For some reason, I am particularly interested\nin European integration and economic policy, especially within the context of\nthe Euro crisis. Frankly, I don't know why, but I find the topic quite thrilling\nto study.\n\n\n[1]: http://jupyter.org/\n"
},
{
"alpha_fraction": 0.6805825233459473,
"alphanum_fraction": 0.6960445642471313,
"avg_line_length": 42.86119842529297,
"blob_id": "d633c36f4ee956af8b27aa3627f833ae1d92e5c4",
"content_id": "ca78f751da866da5fc29b5b8b0d71af9158ac402",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 27810,
"license_type": "permissive",
"max_line_length": 519,
"num_lines": 634,
"path": "/_site/ipython/files/solow-growth.py",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "\n# coding: utf-8\n\n# In[1]:\n\nimport scipy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[2]:\n\n# comment this out if running file as a script\nget_ipython().magic('matplotlib inline')\n\n\n# In[3]:\n\n# Plot style customization\nsns.set_style(\"white\")\nsns.set_context(\"talk\")\n\n# use \"colorblind\" if you don't want reds and greens together\nsns.set_color_codes(\"muted\") \ncolors = ['b','g','r']\n\n\n# # Economic growth\n# \n# How can we account for the fact that national economies systematically continue to grow? The macroeconomics that describe boom-recession cycles don't show that the overall trend is upward. In fact, when one thinks about the macroeconomy in the short run it is not obvious at all that the economy should rise above some static equilibrium level. \n# \n# Growth theory tries to fill in the gaps. It considers the aggregate economy in the long run, where it is reasonable to apply so-called \"Kaldor facts\" which summarize the empirical evidence:\n# \n# * Output per worker and capital per worker tends to grow over time\n# * They also grow at similar rates\n# * The return to capital (the interest rate) over time is fixed\n# * The return to labor (the wage) seems to grow over time\n# * Labor's share of output is stable\n# \n# Out of these facts emerge some incredibly robust results of macroeconomic theory. We consider the implications of these stylized facts by studying the baseline version of the famous Solow model, first published in 1956.\n\n# # The Solow model\n# \n# The Solow growth model assumes that output $Y$ is a function of labor $N$ and the capital stock $K$ satisfying\n# \n# \\begin{align}\n# \\frac{\\partial Y}{\\partial N} &> 0 \\qquad\n# \\frac{\\partial Y}{\\partial K} > 0& \\\\\n# \\frac{\\partial^2 Y}{\\partial N^2} &< 0 \\qquad\n# \\frac{\\partial^2 Y}{\\partial K^2} < 0&\n# \\end{align}\n# \n# The first pair of relations denotes that $Y$ is increasing in the level of labor and in the level of capital, while the second pair of relations implies that $Y$ experiences diminishing marginal returns to both labor and capital.\n# \n# We also require that\n# \n# \\begin{align}\n# Y(0,K) = Y(N,0) = 0\n# \\end{align}\n# \n# for all $N$ and $K$, implying that some quantity of labor and capital is required to produce any output. In the limit that $N$ or $K$ approaches 0, we assume that\n# \n# \\begin{align}\n# \\lim_{N \\to 0} \\frac{\\partial Y}{\\partial N} =\n# \\lim_{K \\to 0} \\frac{\\partial Y}{\\partial K} = \\infty,\n# \\end{align}\n# \n# so the incentives to add labor or capital when none is present are tremendous. Finally, using the rationale that doubling _both_ labor and capital ought to double output, we impose the condition\n# \n# \\begin{align}\n# Y(z\\cdot N, z \\cdot K) &= z \\cdot Y(N,K)\n# \\end{align}\n# \n# for all $z > 0$. (For the mathematically inclined, functions $f$ satisfying the above relation are said to have **first-degree homogeneity**.)\n\n# ## Cobb-Douglas Production\n# \n# A simple but classical output function family is \n# \n# \\begin{align*}\n# Y(N,K) &= K^{\\alpha}N^{1 - \\alpha}\n# \\end{align*}\n# \n# with $\\alpha \\in [0,1]$. Functions of this form are called **Cobb-Douglas** production functions. It is easy to verify that Cobb-Douglas production functions satisfy the conditions of the Solow model. You should try this out on your own to convince yourself.\n# \n# We will consider production functions of this form in our simulations.\n\n# # _Per Capita_ Output\n# \n# The mathematics of the Solow model can be simplified by converting output into _per capita_ units. Denote\n# \n# \\begin{align}\n# y(N,K) &= \\frac{1}{N}\\cdot Y(N,K)\n# \\end{align}\n# \n# the _per capita_ level of output in the economy, and let $k = \\frac{K}{N}$ denote the _per capita_ level of capital. By first-degree homogeneity, we have\n# \n# \\begin{align}\n# y(N,K) &= Y(\\frac{N}{N}, \\frac{K}{N}) \\\\\n# &= Y(1, k).\n# \\end{align}\n# \n# Notice that _per capita_ output no longer depends on the level of employment, so we rewrite $y(N,K)$ as $y(k)$.\n\n# ## Cobb-Douglas _Per Capita_ Output\n# \n# Given $Y(N,K) = K^{\\alpha} N^{1-\\alpha}$, it follows that\n# \n# \\begin{align}\n# y(k) &= \\frac{1}{N} \\cdot (K^{\\alpha} N^{1-\\alpha}) \\\\\n# &= K^{\\alpha} N^{-\\alpha}\\\\\n# &= \\left(\\frac{K}{N}\\right)^{\\alpha} \\\\\n# &= k^{\\alpha},\n# \\end{align}\n# \n# so using the Cobb-Douglas production function we obtain a _much_ simpler definition of _per capita_ output. We now can also put the functions to code with the following definition.\n\n# In[4]:\n\ndef cobb_douglas(alpha):\n return lambda k: k**alpha\n\n\n# Two important notes about how we've defined the function `cobb_douglas`. The first is that we take advantage of Python's support for **lambda functions**. If you're not familiar with lambda functions, you should check them out [here][1], though if you have never dabbled in Lisp (or one of its many derivatives), consider dropping everything you're doing now and go learn one! (I personally like Scheme, which was taught in my introduction to computer science class at school.)\n# \n# The quick-and-dirty explanation is that the `lambda` keyword is functionally equivalent to a function definition. As an example, note that the variable `square_1` given by\n# \n# ```Python\n# square_1 = lambda x: x * x\n# ```\n# \n# can be used in the same manner as the function `square_2` given by\n# \n# ```Python\n# def square_2(x):\n# return x*x\n# ```\n# \n# with a formal definition. One advantage of lambda functions is they can be passed anonymously (i.e. without giving them a specific name) as variables in procedures.\n# \n# The second point I want to make is that `cobb_douglas` is a function which itself returns a function! This means that the expression\n# \n# ```Python\n# cobb_douglas(0.5)\n# ```\n# \n# is **not** a \"variable\" in the traditional sense. Rather, it is a function that is equivalent to\n# \n# ```Python\n# def cd_1(k):\n# return k**0.5\n# ```\n# \n# In this sense, `cobb_douglas` is a **higher-order** function that takes a parameter $\\alpha$ and returns a production function. \n# \n# Play around with `cobb_douglas` to make sure that you have a feel for how it works!\n# \n# [1]: http://www.secnetix.de/olli/Python/lambda_functions.hawk\n\n# # Investment\n# \n# General equilibrium in macroeconomics tends to mean the following condition holds:\n# \n# \\begin{align}\n# \\text{Production} = \\text{Income} = \\text{Output} = \\text{Demand}.\n# \\end{align}\n# \n# We will use these terms interchangeably (tacitly assuming that equilibrium holds).\n# \n# Income $Y$ is either consumed or saved, so \n# \n# \\begin{align}\n# Y &= C + S.\n# \\end{align}\n# \n# Suppose $s \\in [0,1]$ is the fraction of income that is saved. Then \n# \n# \\begin{align}\n# S &= sY \\\\\n# C &= (1-s)Y.\n# \\end{align}\n# \n# In this economy, everything that is saved is immediately invested; hence, investment $I$ is given by $I(N,K)=s \\cdot Y(N,K)$. Letting $i = \\frac{I}{N}$, we have the _per capita_ level of investment $$i(k)=s \\cdot y(k).$$ Similarly, _per capita_ consumption is $$c(k) = (1-s) y(k).$$ \n# \n# ## Depreciation\n# \n# Investment directly increases the capital stock. However, the quality of the capital stock decays over time. Factories get old, machines get rusty, and other exogenous factors can reduce the level of capital stock. Suppose that the rate of capital depreciation is given by $\\delta \\in (0,1]$. Then we can express the so-called **equation of motion** for capital by\n# \n# \\begin{align}\n# \\frac{dk}{dt} &= i - \\delta k \\\\\n# &= s \\cdot y(k) - \\delta k\n# \\end{align}\n# \n# in continuous time. Since $y(k)$ is concave and increasing, there exists a single $k^* > 0$ satisfying\n# \n# \\begin{align}\n# \\frac{dk^*}{dt} &= 0.\n# \\end{align}\n# \n# This is called the **steady-state level of capital**, because at this point investment into capital is completely negated by natural depreciation.\n# \n# This is conceptually easier to understand in the continuous case, but for simulation we discretize time, and our differential equation becomes a difference equation with the form\n# \n# \\begin{align}\n# k_{t+1} - k_t &= s \\cdot y(k_t) - \\delta k_t.\n# \\end{align}\n# \n# The steady-state condition for the discrete-time version is simply \n# \n# \\begin{align}\n# k^*_{t+1} - k^*_t &= 0.\n# \\end{align}\n# \n# For both continuous and discrete-time versions of the equation of motion, we obtain a steady-state level of capital $k^*$ satisfying\n# \n# \\begin{align}\n# k^* &= \\tfrac{s}{\\delta} \\cdot y(k^*) \\\\\n# &= y(\\tfrac{s}{\\delta} \\cdot k^*)\n# \\end{align}\n\n# In[5]:\n\ndef equation_of_motion(production_function, s, delta):\n return lambda k: s * production_function(k) - delta * k\n\n\n# Using the `scipy.optimize` module, we can also get a general solution to the steady state in the following function.\n\n# In[6]:\n\ndef steady_state(production_function, s, delta):\n return float(scipy.optimize.newton_krylov(\n equation_of_motion(production_function, s, delta), \n 1.\n ))\n\n\n# ## Cobb-Douglas Equation of Motion\n# \n# In the Cobb-Douglas case, recall that $y(k)=k^{\\alpha}$. Then we have\n# \n# \\begin{align*}\n# \\frac{dk}{dt} &= s k^{\\alpha} - \\delta k.\n# \\end{align*}\n# \n# We can obtain an algebraically closed-form steady-state $k^*$ satisfying \n# \n# \\begin{align*}\n# \\frac{dk^*}{dt} &= s(k^*)^{\\alpha} - \\delta k^* \\\\\n# 0 &= s(k^*)^{\\alpha} - \\delta k^* \\\\\n# \\delta k^* &= s(k^*)^{\\alpha} \\\\\n# (k^*)^{1 - \\alpha} &= \\tfrac{s}{\\delta} \\\\\n# k^* &= \\left(\\tfrac{s}{\\delta} \\right)^{\\frac{1}{1-\\alpha}},\n# \\end{align*}\n# \n# which is a lovely result. Using the Cobb-Douglas function as a base, we can visualize what is \"intuitively\" going on in the mathematics:\n\n# In[7]:\n\ncapital = np.arange(0,3,0.002)\nalpha = 0.5; s = 0.6; delta = 0.4\n\nsteady = (s / delta) ** (1 / (1 - alpha))\n\ncdp = cobb_douglas(alpha)\neqm = equation_of_motion(cdp, s, delta)\n\nfig, (ax0, ax1, ax2) = plt.subplots(3,1, figsize=(10,15), sharex=True)\n\nax0.plot(capital, s * cdp(capital), colors[0], label=\"Investment: $s \\cdot y(k_t)$\")\nax0.plot(capital, delta * capital, colors[1], label=\"Depreciation: $\\delta \\cdot k_t$\")\nax0.plot([steady], [s * cdp(steady)], colors[2], marker='o')\nax0.set_title(\"Investment & Depreciation\")\nax0.legend(loc=5)\n\nax1.plot(capital, eqm(capital), colors[0], label=\"$k_{t+1} - k_t$\")\nax1.plot(capital, [0]*capital, 'k--')\nax1.plot([steady], [0], colors[2], marker='o')\nax1.set_title(\"Equation of Motion\")\nax1.legend(loc=5)\n\nax2.plot(capital, cdp(capital), colors[0], label=\"$y(k_t)$\")\nax2.plot([steady], [cdp(steady)], colors[2], marker='o')\nax2.set_title(\"Aggregate Production\")\nax2.legend(loc=5)\nax2.set_xlabel(\"$k_t$\")\n\nsns.despine()\n\n\n# At the red dot, the level of capital investment and the level of capital depreciation are the same, so the change in capital determined in the equatino of motion is negligible. This means that the level of output is fixed once the steady state is achieved.\n# \n# Here we use the algebraic solution in `steady`. The relative error between `steady` and the numerically computed solution in our function is given below:\n\n# In[8]:\n\nprint (abs(steady - steady_state(cdp, s, delta))/steady)\n\n\n# In other words, the numerical solution provided by `scipy.optimize` does pretty well for itself!\n\n# # Shocks\n# \n# ## Savings shocks\n# \n# Let us now consider an economy which has reached its steady state. One key variable which determines the steady state level of output is the savings rate. The more an economy saves, the larger fraction of total income is devoted to investment. Since investment increases the capital stock, it would be reasonable to expect that an increase in the savings rate increases capital stock in the short run and the long run. But what about the effect on consumption and investment?\n# \n# To visualize these effects, we can write a Python function to simulate these kinds of shocks:\n\n# In[9]:\n\ndef savings_shock(production_function, s0, s1, delta, periods, grain=4):\n capital = np.empty(periods*grain)\n capital[0] = steady_state(production_function, s0, delta)\n for i in range(1, periods*grain):\n capital[i] = capital[i-1] + equation_of_motion(\n production_function, \n s1, \n delta\n )(capital[i-1])\n \n output = production_function(capital)\n investment = s1 * output\n investment[0] = s0 * output[0]\n consumption = output - investment\n return [capital, output, consumption, investment] \n\n\n# Using a Cobb-Douglas production function with $\\alpha = 0.5$ as the basic framework, let us calibrate steady-state equilibrium for an economy with a savings rate of $s_0=0.6$ and a depreciation rate $\\delta = 0.4$. \n# \n# We will then apply a shock to the economy by adjusting the savings rate $s$ upwards to $s_1 = 0.7$ and downwards to $s_1 = 0.5$. By using the function `savings_shock` which we have just wrote, we can simulate the effects of the savings shock on the economy.\n\n# In[10]:\n\ngrain = 5\ntime = np.arange(0,10,1/grain)\n[kup, yup, cup, iup] = savings_shock(cdp, s, 0.7, delta, 10, grain=grain)\n[kdn, ydn, cdn, idn] = savings_shock(cdp, s, 0.5, delta, 10, grain=grain)\n\n\nfig, axes = plt.subplots(2,2, sharex=True, figsize=(15,15))\n\naxes[0,0].plot(time, kup, colors[0])\naxes[0,0].plot(time, kdn, colors[1])\naxes[0,0].set_ylabel(\"Capital\")\n\naxes[0,1].plot(time, yup, colors[0], label=\"$s_1 > s_0$\")\naxes[0,1].plot(time, ydn, colors[1], label=\"$s_1 < s_0$\")\naxes[0,1].set_ylabel(\"Output\")\naxes[0,1].legend()\n\naxes[1,0].plot(time, cup, colors[0])\naxes[1,0].plot(time, cdn, colors[1])\naxes[1,0].set_ylabel(\"Consumption\")\naxes[1,0].set_xlabel(\"Time (periods)\")\n\naxes[1,1].plot(time, iup, colors[0])\naxes[1,1].plot(time, idn, colors[1])\naxes[1,1].set_ylabel(\"Investment\")\naxes[1,1].set_xlabel(\"Time (periods)\")\n\nsns.despine()\n\n\n# The surprising result here is consumption. While the initial effects of the shock are quite significant, in both cases the level of consumption returns quite close to the original level. How can this be the case if the savings rate determines the fraction of income is consumed? The explanation is that raising the savings rate raises the level of output in the long run, which in turn raises the total amount of income available to be consumed. \n# \n# This is true even if the fraction of income has fallen, so the long run level of consumption is barely affected. You can construct a similar argument for why decreasing the savings rate leads to only a modest increase in consumption in the long run.\n\n# ## Depreciation shocks\n\n# We can perform the same type of analysis on shocks to depreciation $\\delta$. First, let us write a similar function for depreciation shocks:\n\n# In[11]:\n\ndef depreciation_shock(production_function, s, delta0, delta1, periods, grain=4):\n capital = np.empty(periods*grain)\n capital[0] = steady_state(production_function, s, delta0)\n for i in range(1, periods*grain):\n capital[i] = capital[i-1] + equation_of_motion(\n production_function, \n s, \n delta1\n )(capital[i-1])\n \n output = production_function(capital)\n investment = s * output\n consumption = output - investment\n return [capital, output, consumption, investment] \n\n\n# We use the same Cobb-Douglas production function as before (with $\\alpha = 0.5$) as the basic framework, calibrating the steady-state equilibrium for an economy with a savings rate of $s=0.6$ and a depreciation rate $\\delta_0 = 0.4$. \n# \n# We then apply a shock to the economy by adjusting the depreciation rate $\\delta$ upwards to $\\delta_1 = 0.5$ and downwards to $\\delta_1 = 0.3$. By using the function `depreciation_shock` which we have just wrote, we can simulate the effects of the savings shock on the economy.\n\n# In[12]:\n\ngrain = 5\ntime = np.arange(0,10,1/grain)\n[kup, yup, cup, iup] = depreciation_shock(cdp, s, delta, 0.5, 10, grain=grain)\n[kdn, ydn, cdn, idn] = depreciation_shock(cdp, s, delta, 0.3, 10, grain=grain)\n\n\nfig, axes = plt.subplots(2,2, sharex=True, figsize=(15,15))\n\naxes[0,0].plot(time, kup, colors[0])\naxes[0,0].plot(time, kdn, colors[1])\naxes[0,0].set_ylabel(\"Capital\")\n\naxes[0,1].plot(time, yup, colors[0], label=\"$\\delta_1 > \\delta_0$\")\naxes[0,1].plot(time, ydn, colors[1], label=\"$\\delta_1 < \\delta_0$\")\naxes[0,1].set_ylabel(\"Output\")\naxes[0,1].legend()\n\naxes[1,0].plot(time, cup, colors[0])\naxes[1,0].plot(time, cdn, colors[1])\naxes[1,0].set_ylabel(\"Consumption\")\naxes[1,0].set_xlabel(\"Time (periods)\")\n\naxes[1,1].plot(time, iup, colors[0])\naxes[1,1].plot(time, idn, colors[1])\naxes[1,1].set_ylabel(\"Investment\")\naxes[1,1].set_xlabel(\"Time (periods)\")\n\nsns.despine()\n\n\n# Here, the results are much less surprising across the board. Increasing the depreciation rate means that capital is being depleted faster than before, so the long run level of output, consumption, and investment all shrink to their new steady states. Similarly, a decrease in the depreciation rate allows capital to remain functioning for longer, increasing the total productive capacity of the economy. \n\n# # The Golden Rule\n# \n# In the Solow model policymakers deal with an additional task: optimizing overall consumption in the steady state. As consumption and happiness are highly related, the benevolent social planner will desire to maximize the total quantity of consumption in the economy. However, the maximal level of consumption (with savings rate $s=0$) would imply an economy with no capital generation and therefore no income. So, there has to be some savings rate which provides the right mix between growth and consumption.\n# \n# Such an optimal savings rate is called the **golden rule of savings** in the Solow model. We can actually derive the conditions for which the golden rule occurs.\n# \n# Recall that \n# \\begin{align}\n# y &= c + i \\\\ \n# c &= y - i\n# \\end{align}\n# The steady-state level of _per capita_ consumption is quantity of consumption $c^*$ which coincides with the steady-state level of capital $k^*$. Now, $y=f(k)$, and $i=\\delta k^*$ in the steady state. Thus,\n# \\begin{align}\n# c^* &= f(k^*) - \\delta k^*.\n# \\end{align}\n# Optimizing the above equation with respect to $k^*$, we obtain\n# \\begin{align}\n# \\frac{dc^*}{dk^*} &= 0 \\\\\n# f'(k^*) - \\delta &= 0 \\\\\n# f'(k^*) &= \\delta.\n# \\end{align}\n# In other words, steady-state consumption is maximized when the marginal product of capital equals the depreciation rate!\n\n# ## Cobb-Douglas Optimal Consumption\n# \n# Suppose thta $y=k^{\\alpha}$ is a Cobb-Douglas production function. Recall that $k^* = \\left( \\frac{s}{\\delta} \\right)^{\\frac{1}{1 - \\alpha}}$. To find maximal $c^*$, we simply compute $\\frac{dy}{dk^*}$ and equate it with $\\delta$:\n# \\begin{align}\n# \\frac{dy}{dk^*} &= \\delta \\\\\n# \\frac{d}{dk^*} (k^*)^{\\alpha} &= \\delta \\\\\n# \\alpha (k^*)^{\\alpha - 1} &= \\delta \\\\\n# \\alpha \\left( \\left( \\frac{s}{\\delta} \\right)^{\\frac{1}{1 - \\alpha}} \\right)^{\\alpha - 1} &= \\delta \\\\\n# \\alpha \\left(\\frac{\\delta}{s} \\right) &= \\delta \\\\\n# \\alpha &= s.\n# \\end{align}\n# Thus, the golden rule level of $k^*$ and $c^*$ is achieved when $s = \\alpha$.\n\n# We can implement a function to compute the golden rule savings rate in the general case using more functions from `scipy`. In this function, we use `scipy.misc.derivative` to compute a numerical derivative of the production function (i.e. $f'(k)$), and use `scipy.optimize.brentq` to find a root of the function $f'(k)-\\delta$, which coincides with the golden rule level of savings. Finally, by noting that \n# \\begin{align}\n# \\frac{dk}{dt} &= s \\cdot y(k) - \\delta k \\\\\n# 0 &= s \\cdot y(k) - \\delta k \\\\\n# s &= \\frac{\\delta k}{y(k)},\n# \\end{align}\n# we can compute the golden rule level of savings by plugging in the root of $f'(k) - \\delta$ into the expression $\\frac{\\delta k}{y(k)}$.\n\n# In[13]:\n\ndef golden_rule(production_function, delta, error=1e-5):\n f = lambda k: scipy.misc.derivative(production_function, \n k, \n dx=error) - delta\n k = scipy.optimize.brentq(f,error,1000.) \n s = delta * k / production_function(k)\n \n return s\n\n\n# This works reasonably well for most production functions (because of the numerical nature of the solution, certain edge cases will lead to issues) that you will encounter. For example, let's compare the savings rate $s=\\alpha$ hypothesized in the Cobb Douglas case with our `golden_rule` estimate:\n\n# In[14]:\n\n# Cobb Douglas Example\nalpha = 0.6\ndelta = 0.8\ncd_savings = alpha\n\nprint(abs(golden_rule(cobb_douglas(alpha), delta)-cd_savings))\n\n\n# Not bad!\n# \n# ## Consequences in the steady-state\n# \n# We have shown mathematically that the Golden Rule level of savings maximizes consumption in the steady state. However, what does this mean for output and investment? To investigate this, we simulate a Cobb-Douglas economy and graph the results.\n# \n# Feel free to fiddle with the parameters to see how they effect the underlying economy.\n\n# In[15]:\n\n# Cobb Douglas parameters\nalpha = 0.34\ndelta = 0.5\n\n# Different savings rates\nsopt = golden_rule(cobb_douglas(alpha),delta)\nslow = 0.2\nshigh = 0.6\n\nk = np.linspace(0,1/delta,100)\noutput = cobb_douglas(alpha)(k)\n\n# Golden-Rule optimized levels of investment and consumption\ngr_investment = sopt * output\ngr_consumption = output - gr_investment\n\n# Suboptimal levels of investment and consumption\nsublow_investment = slow * output\nsublow_consumption = output - sublow_investment\n\nsubhigh_investment = shigh * output\nsubhigh_consumption = output - subhigh_investment\n\n# Steady state calculations\nss_opt = steady_state(cobb_douglas(alpha), sopt, delta)\nss_low = steady_state(cobb_douglas(alpha), slow, delta)\nss_high = steady_state(cobb_douglas(alpha), shigh, delta)\n\n# Savings rate plot\ns_rates = np.linspace(0,1,100)\ndef consumption_from_savings(savings, delta, alpha):\n k = np.power(savings/delta,1./(1.-alpha))\n y = cobb_douglas(alpha)(k)\n return (1-savings) * y\n \nss_consumption = consumption_from_savings(s_rates, delta, alpha)\n\nfig, axes = plt.subplots(2,2, sharex=False, sharey=True, figsize=(15,15))\n\nlabels = [\"Golden Rule\", \"Low Savings\", \"High Savings\"]\nsteady_states = [ss_opt, ss_low, ss_high]\nsavings = [sopt, slow, shigh]\nconsumptions = [consumption_from_savings(i,delta,alpha) for i in savings]\n\naxes[0,0].set_title(\"Production function\")\naxes[0,0].plot(k,output,'k')\naxes[0,0].set_ylabel(\"Output\")\naxes[0,0].set_xlabel(\"Capital\")\n\naxes[0,1].set_title(\"Investment\")\naxes[0,1].plot(k,gr_investment, colors[0])\naxes[0,1].plot(k, sublow_investment, colors[1])\naxes[0,1].plot(k, subhigh_investment, colors[2])\naxes[0,1].set_ylabel(\"Investment\")\naxes[0,1].set_xlabel(\"Capital\")\n\n\naxes[1,0].set_title(\"Consumption versus capital\")\naxes[1,0].plot(k, gr_consumption, colors[0])\naxes[1,0].plot(k, sublow_consumption, colors[1])\naxes[1,0].plot(k, subhigh_consumption, colors[2])\naxes[1,0].set_ylabel(\"Consumption\")\naxes[1,0].set_xlabel(\"Capital\")\n\n\naxes[1,1].set_title(\"Consumption versus savings rate\")\naxes[1,1].plot(s_rates, ss_consumption, 'k')\naxes[1,1].set_ylabel(\"Consumption\")\naxes[1,1].set_xlabel(\"Savings Rate\")\n\n\n# Identify the steady state levels of output, investment, and consumption \n# for each level of savings\nfor i in range(3):\n axes[0,0].plot(steady_states[i],\n cobb_douglas(alpha)(steady_states[i]),\n 'o', color=colors[i], label=labels[i])\n axes[0,1].plot(steady_states[i],\n savings[i] * cobb_douglas(alpha)(steady_states[i]),\n 'o', color=colors[i], label=labels[i])\n axes[1,0].plot(steady_states[i],\n (1. - savings[i]) * cobb_douglas(alpha)(steady_states[i]),\n 'o', color=colors[i], label=labels[i])\n axes[1,1].plot(savings[i],\n (1. - savings[i]) * cobb_douglas(alpha)(steady_states[i]),\n 'o', color=colors[i], label=labels[i])\n \naxes[1,0].set_xlim([0,max(k)])\naxes[0,1].set_xlim([0,max(k)])\naxes[1,0].set_xlim([0,max(k)])\n \naxes[0,0].legend(loc=4)\naxes[0,1].legend()\naxes[1,0].legend()\naxes[1,1].legend()\n\nplt.subplots_adjust(hspace=0.4)\nsns.despine()\n\n\n# As the plots demonstrate, a higher savings rate leads to a higher steady-state level of output and invesment. Moreover, a high-saving economy has more capital in the steady state. But investment is simply a means to an end: savings will eventually be used for consumption. In this respect, we see that the high savings rate has the _lowest_ level of consumption. The Golden Rule level of savings produces the highest steady-state level of consumption, which is what the social planner actually cares about maximizing.\n# \n# There are important policy implications for this result. The benevolent dictator goes out into the world and likely sees that the current savings rate $s_t$ is less than the golden rule level of savings $s^*$. In order to maximize everyone's consumption (and by extension utility) in the steady state, she will want to enact policy encouraging higher savings.\n# \n# But this will **decrease** consumption in the short run, lowering everyone's utility. People will complain!\n# \n# Maybe the benevolent dictator won't care, but myopic politicians certainly will. Thus, the issue of optimal savings is a tricky dilemma for policymakers in democracies like the U.S.\n\n# # Expanding the model\n# \n# This notebook was designed to serve as an introduction to the basic description of the Solow growth model. We introduced the notion of steady-state levels of output and explored the implications of \"shocks\" to the economy. Finally, we covered and solved an interesting policy problem to maximize consumption in the steady state. However, there is still much to consider.\n# \n# First, the Solow model thus discussed implies that an economy that reaches a steady state will stop growing. But as we said at the beginning, there is no evidence to suggest this is true. How can the model explain this? It turns out that there are two natural ways to extend the model to allow for systematic growth:\n# \n# * Population growth\n# * Technological growth\n# \n# Including these will allow us to model an economy whose growth is solely determined by population and technological changes. The modifications needed are simple, but they have profound implications.\n# \n# Second, we have not studied the issue of \"catch-up\" growth. Why is it that some countries (like Japan in the 1980s or China in the 2000s) can grow so rapidly that they catch up to other industrialized countries, when others (take your pick in the Middle-East or Africa) seem to languish in poverty? The Solow model provides a natural explanation:\n# \n# > Countries with low capital stocks should experience rapid growth as they make large strides towards the steady state. As they amass capital, countries find that their economies naturally slow. So rich countries have high capital stocks with low growth because they are already close to the steady state. \n# \n# > However, this requires that countries share **underlying** factors (such as the savings rate, the depreciation rate, population growth, and technological growth). Two countries with different exogenous variables will arrive at different steady-states. In reality, this translates to institutions. Countries with strong bureaucracies, rule of law, good governance, emphasis on education, and effective management will **consistently outperform** countries without these institutions.\n# \n# Again, this has profound policy implications, but simply falls out of the model.\n# \n# Finally, there are more recent additions to growth theory that seek to understand just exactly how innovation and population actually affect long term growth. At their core, all new models rely on the Solow model, since its simplicity and depth are both mathematically attractive and economically compelling. Quite amazing for a sixty year-old model! \n"
},
{
"alpha_fraction": 0.8071163296699524,
"alphanum_fraction": 0.8107104301452637,
"avg_line_length": 55.02013397216797,
"blob_id": "3cd74313285e513fe69a131823a7562df5c453bb",
"content_id": "5e0374fbc661037d62569b9fccdf3f7b2cb79572",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 8356,
"license_type": "permissive",
"max_line_length": 176,
"num_lines": 149,
"path": "/blog/_posts/2015-01-25-in-response-to-dr-mazzucato.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'In Response to Dr. Mazzucato'\nsubheadline: 'Review'\nteaser: 'A <i>Foreign Affairs</i> contributor is right to argue that states can do more to foster innovation, but unfairly criticizes her opponents as antiquated neo-liberals.'\nlayout: page\nauthor: David Kraemer\ndate: January 25, 2015\ncategories:\n - blog\ntags:\n - 'Foreign Affairs'\n - 'review'\n - 'political economy'\n - 'innovation'\nauthor: David Kraemer\n---\n\n[\"The Innovative State: governments should make markets, not just fix them\"][1], by Mariana Mazzucato (January 2015)\n\nI am in the process of reading the latest edition of *Foreign Affairs,*\nwhich is primarily focused on understanding the importance of\nentrepreneurs in the American economy, what hinders their success, and\nhow to improve the political environment to spur more entrepreneurial\ninnovation. All of which are laudable, as it has long been known that\ninnovation is the secret ingredient for growth and prosperity.\n\nDr. Mariana Mazzucato adds to this mix of commentary by arguing that the\nstate ought not to take a backseat to markets; instead, it should be an\nactive market maker beyond its role of regulator. Her underlying\nargument is sound, as she rightly points out that long-term research and\ndevelopment projects are more suited to public investment and that the\nstate should focus on forging public-private partnerships in places\nwhere cooperation can reduce moral hazard.\n\nMy issue with Dr. Mazzucato is less to do with big-picture ideas as with\nthe faulty bits of reasoning she uses to take her there. She is highly\ncritical of notions that the state ought to stay its investment arm in\nany fashion, arguing instead that the great success stories of modern\ninvention owe their geneses to a state eager to support research. She\nderides critics of government as neo-classical whacks for missing this\nobvious insight.\n\nThis is a singular failure to understand the motivations for skeptics of\nan \"intrusive\" government. I am no adherent to neo-classical economic\ntheory, but it is easy to see that she misses the point here.\nGovernments operate on fundamentally different axioms than firms. Firms\npursue investment projects for future profit, making their decision\nmaking structures highly comprehensible (if meiopic). Government\nmotivations for embarking on projects are not so easily discerned. They\ncan range from securing partisan support to countering the moves made by\ninternational actors. Every once in a while, they can arise from a\ngenuine interest to pursue the public good, but this is obviously a\nrarity. Moreover, the amount of funding that is allocated simply due to\n\"mission creep\" of various government agencies is astounding.\n\nAre these not problems of firms? Nothing inherently prevents such\ncharacteristics to develop in private R&D until the conditions of market\ndiscipline are applied. Under market equilibrium, firms are forced to\ninvest efficiently or go bust. But these constraints fundamentally do\nnot apply to governments. One might complain that firms easily secure\nasymmetric privileges through political lobbying, hence negating market\ndiscipline. This is certainly true, but the issue of the size of\npolitical interests also implicates the state—as is the cliché: it takes\ntwo to tango. All this does not imply the inherent superiority of\nprivate investment, nor should it be read as a libertarian tirade\nagainst government. Rather, I am simply trying to point out that there\nare key differences in the rules by which firms and governments play,\nand the lack of direct forms of accountability on governments reduces\nthe effectiveness of public investment when comparable projects can be\nundertaken privately.\n\nMy point is that the state should be careful in embarking on\ninvestments. There are, as Dr. Mazzucato argues, places in which public\ninvestment is a more desirable alternative than private investment. An\neasy case involves long term research projects such as that of the\nManhattan Project, vaccination research, Fermilab, and the Internet.\nHere the public good calculably preferences the state to firms.\n\nAnother clarification: when Dr. Mazzucato bemoans that governments are\nheld responsible only for fixing market failure at the expense of, say,\n\"external costs companies may impose on the public, such as pollution,\"\nshe forgets that market failure by definition includes such\nexternalities. A responsible analysis of the costs and benefits of\nenergy investment must include the environmental costs—implicit or\notherwise—when determining the optimal supply/demand equilibrium. As is\noften the case, due to the damage carbon causes to the environment,\nmarkets fail to reach this adjusted equilibrium. Thus, even for the\ngovernment \"skeptics\" Dr. Mazzucato decries, governments absolutely\nought to intervene to fix such market failures (by a carbon tax,\nideally). Rather than being a limit to what Dr. Mazzucato sees as\neffective government, preventing market failure, interpreted properly,\ngives government an immense agency in directing investment policy for\nboth public and private actors.\n\nFinally, I want to address a slight snipe that Dr. Mazzucato takes at\nthe debate over debt. She says,\n\n> \"Across the globe, policymakers have targeted public debt (never mind\n> that it was private debt that led to the meltdown), arguing that\n> cutting government spending will spur private investment.\"\n\nPerhaps she has a point in America, as private debt from subprime\nmortgages to CDOs provided the catalysts for the financial crisis. Of\ncourse, America's public deficits have accumulated throughout the\ndecades, but that does not somehow detract from the correct policy of\nfiscal and monetary stimulus engaged throughout the dark days of 2008\nand 2009. There is a serious question about when deficit spending ought\nto have ended, and it is quite possible that it ended too soon (alas,\nfiscal policy is decided not by experts but partisans).\n\nBut I suspect that Dr. Mazzucato has her eyes fixed on the Euro zone\nwhen she makes such accusations. There, it is much more complicated.\nCertainly, European banks failed with their American counterparts on\nfaulty private debt. The Euro crisis sparked, however, from a crisis of\nsovereign default. Regardless of the political intricacies that helped\nto fuel the Greek debt crisis, it is undeniable that public insolvency\nis a *much* scarier prospect than private bankruptcy. The effect of\ninsolvency on interest rates only perpetuates the insolvency, and this\nphenomenon has real, rippling, and deadly consequences on public and\nprivate investment.\n\nThis is another reason for governments to be cautious. On one hand,\ntheir first priority ought to be to prevent private-sector crises like\nthe 2008 financial meltdown (in this instance, by enforcing higher\ncapital ratios, floors on minimum mortgage down-payments, and\nreintroducing some form of the Glass-Steagall Act to prevent contagion).\nThen, it needs to be prepared to manage crises when they inevitably\nerupt, a task requiring its own type of public investment. Finally, if\nthe state has a grip on these two prospects, governments can dabble in\npublic investment. Otherwise, states can construct unsustainable\nspending policies (a la Greek or Illinois public sector pensions)\nwithout a genuine plan to follow through on them in times of crisis.\n\nDr. Mazzucato's case for an increased role of government investment\ncertainly needs to be heard, as such arguments are falling on deaf ears\nof late, but her zeal for public prowess needs a bit of tempering. There\nare real and hard limitations for what a government ought to do, owing\nto a combination of complex mandates and unpredictable motivations.\nGiven all that governments are responsible for, public investment should\ntarget specific niches of R&D that do not fit easily with the MOs of\nprivate firms. Public-private partnerships can do much good in this\narena, helping to mitigate the problems of moral hazard. And we\nobviously have to thank the state both for long-sighted inventions like\nthe Internet and the mundane investments on infrastructure—both of which\nneed continued public support. But beware an overstretched state,\nbecause however much pain private-debt crises inflict, they are orders\nof magnitude gentler than public insolvency.\n\n[1]: http://www.foreignaffairs.com/articles/142496/mariana-mazzucato/the-innovative-state\n"
},
{
"alpha_fraction": 0.7776671051979065,
"alphanum_fraction": 0.7802028656005859,
"avg_line_length": 52.6019401550293,
"blob_id": "708f58c48069e29e2121349a5054d680413ad52f",
"content_id": "aee7c5bd93adee0d48599359693c29bc4150a885",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 11042,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 206,
"path": "/blog/_posts/2015-07-14-site-restructuring.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\nsubheadline: Announcements\ntitle: \"Site Restructuring\"\nteaser: 'Thoughts about the transition to the Jekyll web framework.'\ndate: July 14 2015\ncategories:\n - blog\ntags:\n - blog\n - announcements\nauthor: David Kraemer\n---\n\nYou may not have noticed, but as of July 11 2015, my website has gotten a major\nupdate. It turns out that writing HTML pages by hand is a horrible punishment \nthat I wouldn't want to wish on my worst enemy. First of all, the language is\njust a mess of unintuitive formatting. I'm fine with using code to structure a\ndocument. I love \\\\(\\LaTeX\\\\), and that's basically how you make beautiful \ndocuments: with code. The problem is that HTML is an arcane jumbling of rules,\nexceptions, and exceptions to exceptions. A true HTML master can tell you \nexactly the correct contexts under which it is acceptable to use `<center>` on a `<div>` \nand actually see the results you\nexpect, but I have no desire to become one. There was also the issue of scale. \nIt's possible to manually produce a blog with just an understanding of HTML, \nbut if you want your navigation to update properly with each additional post,\ngood luck.\n\n## Discovering Jekyll\n###### Or: how I discovered how to hyde the HTML\n\nMy hack during the school year was a little Python script that performed basic\nregular expressions. Effectively, it would iterate through each blog entry, search\nfor a particular pattern (the navigation bar), and update the locations of the \"top\"\npost. That started becoming problematic with the growing \ncomplexity of the site, so I started looking for alternatives. I had also learned\nabout the language Markdown during the school year, from my experiences with the IPython Notebook\nand the README files of a GitHub repository. To me, Markdown is a breath of \nfresh air. Yes, eventually the Markdown I write will be converted into HTML, \nbut I never have to see it while I produce content. To me, finding a platform that \nlets me create Markdown content without having to dive into the details of web\nmarkup languages was worth the initial startup costs of \nlearning a new technology. I started researching a number of potential choices,\nfrom having my site generated for me by a WYSIWYG-style WordPress environment \nto deploying a full stack Django site. Then I stumbled upon Jekyll.\n\nFor those of you who have never heard of [Jekyll][0] before, here is its \n[Wikipedia description][1]:\n\n> Jekyll is an open source program, written in Ruby by Tom Preston-Werner, \nGitHub's co-founder. Jekyll is a simple, blog-aware, static site generator \nfor personal, project, or organization sites. Instead of using databases, \nJekyll takes the content, renders Markdown or Textile and Liquid templates, \nand produces a complete, static website ready to be served by Apache HTTP \nServer, Nginx or another web server. Jekyll is the engine behind GitHub \nPages, a GitHub feature that allows users to host websites based on their \nGitHub repositories.\n\nYou build a directory with a number of specified subdirectories, and you design\na set of HTML templates, to which you can assign content written in Markdown. \nWhen you build the site, Jekyll organizes the content, formats it to the\ntemplates, and constructs a site directory which can be viewed from a browser.\nI think it's an ideal solution for programmers. It doesn't hide anything, and\nlets you customize as many aspects of the design process as you like. It feels closer to the code than the \nWordPress alternative, and it also works great with GitHub, which is valuable\nto me (although I haven't built a GitHub webpage yet).\n\nJekyll also has a nice open source community budding around it. A number of \ngreat site templates can be found [here][2]. I ended up going with *Feeling\nResponsive*, a template developed by [Phlow][3]. I think it looks quite good \non desktop and mobile screens alike. \n\n## The Restructuring \n\nThe first challenge was getting used to the templates that are provided with \n*Feeling Responsive*. They are quite different from the Jekyll defaults and\ncome with considerably more configuration options. I had used the `pandoc` \nutility to convert all of the pages on my old site to Markdown earlier, so I \nstarted merging them into the existing Jekyll directory. This ended up being\nmore complicated than I expected, because I had initially wanted to keep the\ntemplate blog posts in a separate blog than mine own. You can customize your\nJekyll directory to support multiple blogs, but it's not nearly as intuitive as\na beginner might hope.\n\nJekyll does provide a `_drafts` directory where you can place content that need\nnot be rendered in the final site build. This is what I ended up doing with the\nblog templates. After moving all of the blog posts to the new site and updating\ntheir meta information (tags, headlines, captions, etc.) I started migrating \nthe other components of the site, including course material and IPython posts.\nThis proved to be more straightforward than the blog, because I didn't need to \nproduce a blog index or archive along with them.\n\n### Customizing Style\n\n*Feeling Responsive* uses a logo for the site, but I felt awkward about \nbroadcasting my name in 72pt font on every page. Plus, logo design requires either\nmore GIMP skills than I possess, or cash to dole out for an online service. As such,\nI'm going without a personal logo for the time being. I found a neat collection of \ngeometric-style patterns somewhere online (I can't seem to find the link... \nwhen I find it I will edit this part), which I'm using as a masthead for the \nmajority of the header pages, and I'm quite happy with their look and feel.\n\nStoring images on the site is not entirely intuitive with Jekyll. The framework\nprovides an `assets` directory where you can place certain common types of \nimages, such as favicons and headers. It also takes customized CSS and SASS\nfiles and places them inside `assets` when it builds the site. Initially, I\nthought it might be ideal to keep all site images in that directory, even from\nblog posts and other pages. However, when it came to build time, this became\ncumbersome, as the links to the images specified in the blog files all stopped\nworking. There is probably a \"correct\" way of handling images in the `assets`\ndirectory for the entire site, but I personally find it easier to place special\nsubdirectories dedicated to storing images inside of the `blog` and `courses`\ndirectories.\n\n### Building the Site\n\nOne nice feature of Jekyll is you can test a \"work-in-progress\" site, without\npushing it out live to the internet, by initializing a local server from which\nthe site can be hosted. This is a fantastic tool, and I took considerable\nadvantage of it throughout the transition. If you're not careful, though, it\ncan make moving towards actually building the live site quite tedious. The\nreason comes down to broken links. In the `_config.yml` file, you can specify\nthe base url on which your site is hosted, but if you haven't been consistent\nin using links throughout the site, they will suddenly start pointing to the \nwrong locations.\n\nFor example, in my case the full url of my site is\n\n```\nhttp://www.math.grinnell.edu/~kraemerd17/\n```\n\nso if I build everything to my `public_html` directory on MathLAN, where will\nmy links point to? Specifically, suppose I have a blog post that references \nanother post. In the Markdown links, I might have a line like this:\n\n```\n[Link](/blog/other-blog)\n```\n\nIt turns out (after much trial-and-error-and-cursing) that if the \"base url\"\nfield in the configuration file is left blank, then the link above will send\nthe user to \n\n```\nhttp://www.math.grinnell.edu/blog/other-blog\n```\n\nwhich is a dud. To make matters worse, the *Feeling Responsive* template employs\nnot only a \"base url\" field, but also a generic \"url\" field, which are used in\ndifferent contexts in the site HTML files. I eventually figured out what went\nwrong with the various url locations, so the site works properly now. Quite painful,\nall in all.\n\nAfter sorting out all of that, I was very happy to build my final version of the \nsite to the MathLAN directory. It all seemed to work! It was a huge effort, but\nI was finally done.\n\n...and then the site's main page decided to break. I still can't figure out the \nexact causes of the issue. The main page's design relies on a template that provides\nfor three column \"widgets\". The default content inside the widgets worked just fine,\nand because they seemed pretty minor, I didn't modify them until the rest of the \nsite was working. In one of the widgets, I wanted to format an unordered list, \nand that required some manual HTML. Which is fine. If I'm exposed to that much\nHTML in an entire site this size, I will accept the dosage willingly. \n\nFor whatever reason, the HTML does _not_ like to play nice with the other two widgets.\nExcept, as it turned out, if the unordered list widget was the last widget. So, if\nyou go to the main page, you'll see my \"Current Interests\" column on the right side\nof the page, because that's the only place I can get it to not break. You might\nalso notice that the header is slightly below vertically the other two columns. I \nhave absolutely no idea why that is, but I'm too burnt out from the restructuring\nto try and fix it at the moment. Another day, perhaps.\n\n## Concluding thoughts\n\nYes, the site restructuring had its harrowing moments, but in all honesty I am quite\npleased with the final result of the site. It looks good, feels responsive on an\nassortment of different devices, and seems to be fully functional. I think I might\nhave one floating lorem ipsum hanging around somewhere, but I'll be sure to fix that\nsoon. \n\nAs I write this new post, I am amazed with how little effort it takes to work out \nthe formatting and technical aspects of the content. The Markdown feels as good as\nI could have hoped, and it is making my experience _significantly_ easier. I can\nspend much more time worried about producing good material without any concern of\nthe site suddenly breaking for no reason. Plus, the built-in draft staging area is\na lovely bonus, and I'm finding myself actually revising the posts that I am putting\ntogether! \n\nThis leaves me feeling very hopeful about the Jekyll framework and this site in the\nfuture. I convinced myself of the necessity to throw the countless hours into the\nrestructuring of the site in no small part because I believed it would completely\nstreamline the process going forward. So far, that seems to be paying off handsomly,\nand I couldn't be happier.\n\nI definitely recommend making the switch to Jekyll if you are considering it. If \nyou're comfortable around a terminal window, if you like working with ease in \nMarkdown, and if you don't foresee a need to go full-stack dynamic content, then\nthe Jekyll framework is really solid. Just be prepared for a steep learning curve\nat the outset!\n\n[0]: http://jekyllrb.com/\n[1]: https://en.wikipedia.org/wiki/Jekyll_%28software%29\n[2]: http://jekyllthemes.org/\n[3]: http://phlow.github.io/feeling-responsive/\n"
},
{
"alpha_fraction": 0.7699210047721863,
"alphanum_fraction": 0.7731514573097229,
"avg_line_length": 51.566036224365234,
"blob_id": "9c548279a131b11fbea6b3f2f5be4560ac08f4c2",
"content_id": "fae3ec16d20f3adaf19053bb817319815edbb2f4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2786,
"license_type": "permissive",
"max_line_length": 150,
"num_lines": 53,
"path": "/pages/info.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\ntitle: \"About\"\nsubheadline: \"Was it really necessary to do this huge rebuild?\"\nshow_meta: false\nteaser: \"I learned how to make HTML files a year ago. I decided that now that I am a real programmer, I can build real websites. You know, with code.\"\npermalink: \"/info/\"\nheader:\n image_fullwidth: \"23.jpg\"\n---\n\nIt turns out that manually writing `<div>`s and `<p>`s is a terrible existence.\nI started building a blog, and it became obvious very quickly that real bloggers\ndon't go into their HTML and manually alter hyperlink references every time they\nadd a new post. I thought that I could script my way past all of those problems,\nbut it turns out that even Python has its limits. \n\nInstead, I discovered Jekyll, which is awesome and exactly what I needed. I know\nhow to handle myself with basic programming, I'm already converted to the cult of\nMarkdown, and I like tinkering with my builds. I also don't have any need for a\ndynamic, full stack website. After all, I host web pages, and maybe some files. \nNothing so serious that I need to design a real backend framework. Jekyll does the\nstatic website thing really well, and coming from a mere 8-10 months of writing\nHTML manually has made me appreciate just the gem that I'm working with here.\n\nThe other nice thing about Jekyll is the budding community that is driving its\necosystem. That's where *Feeling Responsive* comes in. It's a theme developed by\nthe GitHub user [phlow][0] which is free to use under the MIT license. It's a \nvery robust theme, and as the name suggests, is mobile-responsive. All in all,\nI thought it was attractive enough to warrant digging through the dozens of \ntemplate files to try and scrap together all of the content I want to customize.\n\nSo here's to another 12 months of me working with Jekyll and *Feeling Responsive*,\nand hopefully no big changes will come in the nearby future!\n\n## Content on this site\n\nI use this webpage for a number of different ends. The first is to blog. I like\nto organize my thoughts by writing, and a blog seems like the natural fit for the\ndigital age. Of course, I hardly expect anyone to read it, so I see it as more of \na public journal for me to explore ideas. \n\nBy contrast, some of my extracurricular activities involve teaching courses, so \nmy webpage will host all of the relevant course material from current (and prior)\ncourses. This is the same functionality as my old site posessed (more or less),\nbut I expect that it will improve with the greater flexibility of the Jekyll \nframework.\n\nFinally, I expect to continue to use this site as a means to organize a professional\nportfolio of research, software, and other projects. It served as a good reference\nlast year, and I think it will continue to do so.\n\n[0]: http://github.com/phlow/\n"
},
{
"alpha_fraction": 0.45560407638549805,
"alphanum_fraction": 0.4695778787136078,
"avg_line_length": 41.37036895751953,
"blob_id": "30c6ed7cbbf732a5f8e81da4ebef1c910110ae8c",
"content_id": "d46782f2d558ad7edcffabd32fee3798ecbc26bc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3435,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 81,
"path": "/misc/derivatives.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Table of Derivatives\"\nAuthor: \"David Kraemer\"\nlayout: page\nshow_meta: false\npermalink: misc/derivatives/\n---\n\nList of useful derivative formulas.\n\\\\(\n\\newcommand{\\diffx}[1]{\\dfrac{d}{dx}\\left(#1\\right)}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\sech}{\\mathrm{sech}}\n\\\\)\n\\\\( \\DeclareMathOperator{\\csch}{\\mathrm{csch}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arcsec}{\\mathrm{arcsec}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arccsc}{\\mathrm{arccsc}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arccot}{\\mathrm{arccot}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arcsech}{\\mathrm{arcsech}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arccsch}{\\mathrm{arccsch}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arccoth}{\\mathrm{arccoth}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arcsinh}{\\mathrm{arcsinh}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arccosh}{\\mathrm{arccosh}}\n\\\\)\n\\\\(\n \\DeclareMathOperator{\\arctanh}{\\mathrm{arctanh}}\n\\\\)\n\n| Function | Derivative | \n|:---------|:-----------| \n| \\\\(\\diffx{c}\\\\) | \\\\(\\displaystyle 0\\\\)| \n| \\\\(\\diffx{x^n}\\\\) | \\\\(\\displaystyle n x^{n-1}\\\\)| \n| \\\\(\\diffx{f(x) + g(x)}\\\\) | \\\\(\\displaystyle f'(x) + g'(x)\\\\)| \n| \\\\(\\diffx{f(x)\\cdot g(x)}\\\\) | \\\\(\\displaystyle f'(x) g(x) + f(x) g'(x)\\\\)| \n| \\\\(\\diffx{(g \\circ f)(x)}\\\\) | \\\\(\\displaystyle (g' \\circ f)(x) \\cdot f'(x)\\\\)| \n| \\\\(\\diffx{\\frac{f(x)}{g(x)}}\\\\) | \\\\(\\displaystyle \\frac{g(x) f'(x) - f(x) g'(x)}{[f(x)]^2}\\\\)| \n| \\\\(\\diffx{a^x}\\\\) | \\\\(\\displaystyle a^x \\ln(a)\\\\)| \n| \\\\(\\diffx{e^x}\\\\) | \\\\(\\displaystyle e^x\\\\)| \n| \\\\(\\diffx{\\log_a x}\\\\) | \\\\(\\displaystyle \\frac{1}{x \\ln(a)}\\\\)| \n| \\\\(\\diffx{\\ln x}2\\\\) | \\\\(\\displaystyle \\frac{1}{x}\\\\)| \n| \\\\(\\diffx{\\sin x}\\\\) | \\\\(\\displaystyle \\cos x\\\\)| \n| \\\\(\\diffx{\\cos x}\\\\) | \\\\(\\displaystyle -\\sin x\\\\)| \n| \\\\(\\diffx{\\tan x}\\\\) | \\\\(\\displaystyle \\sec^2 x\\\\)| \n| \\\\(\\diffx{\\sec x}\\\\) | \\\\(\\displaystyle \\sec x \\tan x\\\\)| \n| \\\\(\\diffx{\\csc x}\\\\) | \\\\(\\displaystyle - \\csc x \\cot x\\\\)| \n| \\\\(\\diffx{\\cot x}\\\\) | \\\\(\\displaystyle - \\csc^2 x\\\\)| \n| \\\\(\\diffx{\\arcsin x}\\\\) | \\\\(\\displaystyle \\frac{1}{\\sqrt{1-x^2}}\\\\)| \n| \\\\(\\diffx{\\arccos x}\\\\) | \\\\(\\displaystyle -\\frac{1}{\\sqrt{1-x^2}}\\\\)| \n| \\\\(\\diffx{\\arctan x}\\\\) | \\\\(\\displaystyle \\frac{1}{1+x^2}\\\\)| \n| \\\\(\\diffx{\\arccsc x}\\\\) | \\\\(\\displaystyle -\\frac{1}{x\\sqrt{x^2-1}}\\\\)| \n| \\\\(\\diffx{\\arcsec x}\\\\) | \\\\(\\displaystyle \\frac{1}{x\\sqrt{x^2-1}}\\\\)| \n| \\\\(\\diffx{\\arccot x}\\\\) | \\\\(\\displaystyle -\\frac{1}{1+x^2}\\\\)| \n| \\\\(\\diffx{\\sinh x}\\\\) | \\\\(\\displaystyle \\cosh x\\\\)| \n| \\\\(\\diffx{\\cosh x}\\\\) | \\\\(\\displaystyle \\sinh x\\\\)| \n| \\\\(\\diffx{\\tanh x}\\\\) | \\\\(\\displaystyle \\sech^2 x\\\\)| \n| \\\\(\\diffx{\\sech x}\\\\) | \\\\(\\displaystyle -\\sech x \\tanh x\\\\)| \n| \\\\(\\diffx{\\csch x}\\\\) | \\\\(\\displaystyle -\\csch x \\coth x\\\\)| \n| \\\\(\\diffx{\\coth x}\\\\) | \\\\(\\displaystyle - \\csch^2 x\\\\)| \n| \\\\(\\diffx{\\arcsinh x}\\\\) | \\\\(\\displaystyle \\frac{1}{\\sqrt{1+x^2}}\\\\)| \n| \\\\(\\diffx{\\arccosh x}\\\\) | \\\\(\\displaystyle -\\frac{1}{\\sqrt{x^2-1}}\\\\)| \n| \\\\(\\diffx{\\arctanh x}\\\\) | \\\\(\\displaystyle \\frac{1}{1-x^2}\\\\)| \n| \\\\(\\diffx{\\arccsch x}\\\\) | \\\\(\\displaystyle -\\frac{1}{|x|\\sqrt{x^2+1}}\\\\)| \n| \\\\(\\diffx{\\arcsech x}\\\\) | \\\\(\\displaystyle \\frac{1}{|x|\\sqrt{x^2-1}}\\\\)| \n| \\\\(\\diffx{\\arccoth x}\\\\) | \\\\(\\displaystyle \\frac{1}{1-x^2}\\\\)| \n\n\n"
},
{
"alpha_fraction": 0.5350000262260437,
"alphanum_fraction": 0.5350000262260437,
"avg_line_length": 35.3636360168457,
"blob_id": "4ea8cfc861c48cd81199931c85fcad16a6f87c43",
"content_id": "e75600dda7187b2286ee8765f6454757812f29d9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 400,
"license_type": "permissive",
"max_line_length": 172,
"num_lines": 11,
"path": "/book-reviews/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Book Reviews\"\nAuthor: \"David Kraemer\"\nlayout: page\nshow_meta: false\npermalink: book-reviews/\n---\n\n|Title|Author|Date|\n|:---|:---|:---| {% for post in site.posts %} {% for tag in post.tags %} {% if tag == \"book reviews\" %}\n|[**{{ post.title }}**]({{ site.url }}{{ site.baseurl }}{{ post.url }})| {{ post.book_author }} | {{ post.date | date: \"%B %d, %Y\" }} |{% endif %} {% endfor %} {% endfor %}\n"
},
{
"alpha_fraction": 0.8006219267845154,
"alphanum_fraction": 0.8115968704223633,
"avg_line_length": 54.78571319580078,
"blob_id": "ac77f370791de7452f9b0513fc294f35f8171512",
"content_id": "8378638546066d3ab8e2303b5ff44910a797eb33",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5467,
"license_type": "permissive",
"max_line_length": 132,
"num_lines": 98,
"path": "/_drafts/liberalism.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Liberalism'\nsubheadline: 'Book Review'\nteaser: \"A candid view of two centuries of liberalism's development.\"\nlayout: page\nauthor: David Kraemer\nbook_author: Edmund Fawcett\ncategories:\n - blog\ntags:\n - 'book reviews'\n - 'nonfiction'\n - 'political theory'\n - 'economics' \n---\n\n[*Liberalism: The Life of an Idea*][1], by Edmund Fawcett (September 22 2015)\n\nThat \"liberal\" in its American connotation is synonymous with the political left\nconflicts with its broader understanding in European politics. In Britain,\nGermany, and the Netherlands, for example, the liberal parties of each\nrespective country historically play kingmaker in forming governments, choosing\nbetween but ultimately remaining separate from the country's conservative and\nsocialist flagbearers. This flexibility reflects an internal diversity within\nEuropean liberal parties. In 2010, for example, the British Liberal Democrat\nNick Clegg led a party of both business-minded reformers and fervent\nenvironmentalist campaigners into coalition with the Tories. \n\nIn America's two-party framework, liberals used to cross partisan lines. The New\nDeal established the Democrats as the natural liberal party (though not without\nits contradictions: conservative segregationist Democrats persisted against the\ncivil rights movement well into the 1960s). Yet the liberal wing of the GOP,\ndating back from the Lincoln presidency, helped cooperate in enacting Lyndon\nJohnson's social reforms. It was in a major political shift in the second half\nof the 20th century that produced the bifurcated ideological battlefield we\nobserve today.\n\nIt is within this context that \"liberal\" refers to the political left in\nAmerica, opposed to conservative right. Not so, says Edmund Fawcett, author of\n*Liberalism: The Life of an Idea*, a thoughtful history of the political movement.\nLiberals come from both left and right to rest at some amorphous center,\noffering a political theory opposed fundamentally to both the reactionary\nimpulse of conservatism and the destructive radicalism of the socialist\nmovement. Acknowledging its roots within the natural rights theorists of the\nEnlightenment, Fawcett begins his account of liberalism with the 1789 French\nRevolution and goes on to explore the ideology's thinkers and leaders throughout\nthe next two centuries.\n\nThe reader may be forgiven for inferring a negative definition of liberalism\nfrom Fawcett. Indeed, at times throughout the arc of liberalism's history the\nliberal creed seems to retain any coherency at all only through clearly\nidentifying what it is not. The conservative ideal memorialized by the\nhierarchical society of the French ancien regime defines the illiberal bound on\nthe right, just as the classless socialist utopia makes for the left. \n\nIn between is a mess: jumbled, inconsistent philosophical foundations combined\nwith damnably hypocritical politics. But this strikes at the core beliefs shared\nby all liberals. According to Fawcett, they understood (and to some extent\nrelished) the inevitability of conflict. Whereas conservatives and socialists\nboth share the notion of a steady-state utopia---hierarchical social order for\nthe former and classlessness for the latter---the liberal rejects any prospect\nfor an end to conflict as fiction. \n\nCoupled with a basic respect for every individual and a healthy skepticism of\nauthority, the concept of conflict defines the liberal mindset. For many,\nliberalism also entails the belief and support of human progress. Liberals,\nunabashedly, share these basic values. The claim that such dichotomous\npersonalities as Herbert Hoover and Franklin Roosevelt, John Stuart Mill and\nAlexander von Humboldt, Lyndon Johnson and Ronald Reagan, and Friedrich Hayek\nand John Maynard Keynes belong within the same movement is quite bold, yet\nFawcett makes this case convincingly. All wholeheartedly rejected socialism and\npromoted---in markedly distinct flavors---his ideal paradigm based in the basic\nvalues of liberalism. \n\nAs it evolved, liberalism manifested itself through distinct policy frameworks.\nConstitutionalism served as the liberal response to unfettered authority.\nInstitutionalizing property rights ensured that individuals could be secure to\npursue their own ends. Yet just as these broadly beneficial developments took\nroot, uglier patterns began to form. It soon became clear that some form of\ncapitalism was a necessary condition in order to uphold the positive values of\nthe movement. Liberals long held out against universal suffrage. They resisted\nthe need for social security and often neglected the plight of the poor. And the\nzealous liberal too often overlapped with the ruthless imperialist. \n\nThese were not contradictions of liberalism, says Fawcett, but were rather \nnatural products of its values. The same instinct which led to the development\nof checks on the extent of government led 19th century liberals to oppose\nextending the franchise to citizens without property. Respect for individual\nrights to self-determination, in the extreme, meant perpetuating the\nentrenchment of newly-acquired wealth. Though liberals predominantly abandoned\nlaissez-faire capitalism by the mid 20th century, they took much longer to\nacknowledge the damage of imperialism. Here, belief in human progress worked\nperversely by rationalizing the subjugation of native inhabitants across the\ndeveloping world. \n\nFawcett pulls no punches. As a liberal, he p\n\n[1]: http://www.amazon.com/gp/product/0691168393?keywords=liberalism%20the%20life%20of%20an%20idea&qid=1452028830&ref_=sr_1_1&sr=8-1\n"
},
{
"alpha_fraction": 0.6109660863876343,
"alphanum_fraction": 0.6266318559646606,
"avg_line_length": 17.238094329833984,
"blob_id": "e1094129ef0557e1757ae905387cfb88a6534df6",
"content_id": "02a5115e5d8d2f333a50581ef12f757c9ee34618",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 384,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 21,
"path": "/pages/404.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\ntitle: \"Alas — Here Be Dragons!\"\nsubheadline: \"HC SVNT DRACONES\"\nteaser: \"404: Not Found\"\npermalink: \"/404.html\"\n---\n## No problem!\n\nTry... \n...my [home page]({{ site.url }}). \n...or, **search**.\n\n\n### Search and Find\n\n{% include google_search.html %}\n\n<form onsubmit=\"google_search()\" >\n <input type=\"text\" id=\"google-search\" placeholder=\"Search\">\n</form>\n"
},
{
"alpha_fraction": 0.7071291208267212,
"alphanum_fraction": 0.7225433588027954,
"avg_line_length": 32.48387145996094,
"blob_id": "6e5d323f3dce471f6cdb1c0e8f6ba7d078143edd",
"content_id": "96923bcc4918b12499074d45b4e25091e8a8642d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1038,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 31,
"path": "/pages/contact.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\ntitle: \"Contact\"\nshow_meta: false\nsidebar: right\nsidebar-title: \"\"\nsidebar-content: <img src=\"/images/profile.jpg\">\nsidebar-social: true\nteaser: \"Need to get in touch with me? Here's how you can reach me.\"\npermalink: \"/contact/\"\nheader:\n image_fullwidth: \"36.jpg\"\n---\n\nThis spring I am working part time on [LMFDB][0] with professor Jennifer Paulhus in\nthe math department. The best way to get in touch with me is via email, which I\ncheck several times per day. You can reach me at [[email protected]][1].\n\nOn social media, you can contact me on LinkedIn, though I'm not very active on the site. \nYou can find my profile [here][2].\n\nI also have a GitHub profile, where I have a number of repositories that make up various\nprojects from work or from my spare time tinkering. My account is [kraemerd17][3].\n\nFinally, I can be reached on Twitter at [@david_kraemer][4].\n\n[0]: http://beta.lmfdb.org\n[1]: mailto:[email protected]\n[2]: https://www.linkedin.com/in/davidnkraemer\n[3]: https://github.com/kraemerd17\n[4]: https://twitter.com/david_kraemer\n"
},
{
"alpha_fraction": 0.8150245547294617,
"alphanum_fraction": 0.8183372616767883,
"avg_line_length": 55.715152740478516,
"blob_id": "42c857b8aa5ac543a84c8331477bdf1c462fb46c",
"content_id": "39a22522e8adc81ea4afc9fcfc17845d368f9a2d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 9364,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 165,
"path": "/blog/_posts/2015-03-16-world-order.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'World Order'\nsubheadline: 'Book Review'\nteaser: \"Henry Kissinger's new treatise is admirable, if revealing.\"\nlayout: page\nauthor: David Kraemer\nbook_author: Henry Kissinger\ndate: March 16, 2015\ncategories:\n - blog\ntags:\n - 'political theory'\n - 'book reviews'\n - 'nonfiction'\nauthor: David Kraemer\n---\n\n[*World Order*][1], by Henry Kissinger (September 9 2014)\n\nThe United States has enjoyed a unipolar international climate for two\ndecades, allowing it to propagate its notions of world order across the\nglobe. It is a mistake, however, to believe that as the dominant power\nfor twenty years, it presented the sole interpretation of what world\norder means. With the rise of China as an international superpower, it\nis again becoming clear that the axioms that provide the basis for\nAmerican foreign relations are not universally shared. Into this\ndissonance thrusts Henry Kissinger, the (at times, controversial) Nobel\nPrize winning US Secretary of State under President Nixon, with his new\nwork, aptly named *World Order*, with the goal of examining the\ndifferent conceptions of world order in order better to understand the\nnature of modern international relations.\n\nThough Kissinger is the sole author of *World Order*, he presents three\ndistinct personalities throughout the text. The first is the scholar.\nThe detail and prose of a historian uniquely aware of the context\nregarding his subject is a prominent motif. Kissinger is thoughtful when\ndiscussing the origins of modern geopolitics in the Middle East, quite\nbrilliant in tracing the roots of European international relations\nthroughout its history, and nothing short of masterful in his account of\nthe Chinese conception of global political reality.\n\nThe source of dissonance between these three traditions, Kissinger\nargues, originates from a profoundly disjoint set of axioms of world\norder. Modern European relations, within the continent and across the\nglobe, is defined by the vision of statehood developed during the series\nof treaties culminating in the 1648 Peace of Westphalia, ending the\nThirty Years' War. According to this understanding, individual\nstates—regardless of their size—deserve international recognition as\nindependent sovereigns. The total domination of the continent by a\nsingle authority, politically or militarily, must be prevented at all\ncosts. Instead, states seek international security through\nbalance-of-power politics. Alliances are impermanent and notoriously\nanti-ideological, the cost of preventing a continental superpower.\n\nThis conception clashes with the Islamic and Chinese conceptions of\ninternational political authority. Throughout much of the Islamic world\nbefore the world wars, disparate ethnicities and races submitted\nsovereignty to the religiously-legitimated Caliphate. Unity in the face\nof conflicting world religious beliefs maintained this legitimacy, which\nserved as the basis for such military victories as the conquest of Spain\nand the expansion into Africa and Asia Minor. Legitimacy of this kind\ncrumbled with the collapse of the Ottoman Caliphate in the twentieth\ncentury. As part of the terms of its defeat, enshrined in the Versailles\nTreaty, the Ottomans were forced to acknowledge the sovereignty of its\nforeign victors—thus contradicting the notion of universalism that\nsupported its claim to represent all Muslims. Along with the subsequent\nimposition of Westphalian notions of statehood to arbitrarily drawn\nborders, this fractured the Middle East into the instability that so\ntragically characterizes it today.\n\nFor China, world order develops from an entirely separate set of beliefs\nfrom those of the European or Islamic tradition. Barring the ideological\nupheavals of Maoism, the Chinese conception of order has always rested\non the belief in the universal supremacy of its nation. The Emperor\nserved as the embodiment of order both in the mundane world and in the\nspiritual realm, as prescribed by the doctrine of the Mandate of Heaven.\nIf the Emperor were the demonstrably legitimate ruler of the Middle\nKingdom, then his sovereignty over the lesser-kingdoms of the world was\nself-evident. All other rulers must submit to the supremacy of the\nChinese State, as a military power but, more importantly, as a beacon of\ncultural perfection to be distilled and learned from.\n\nIn this sense, the power of the Chinese order was not in its military\nprowess; indeed, the state was subject to conquest from the Mongols,\nBritish, and Japanese. However, the Chinese nation defeated all of its\nconquerors. Far from imposing Mongolian political culture onto China,\nthe Yuan emperors were subject to immense cultural assimilation into\ntheir subjects. The British succeeded in wresting China open to world\nmarkets, but they failed to dominate China politically as they could\nwith their other colonies. And the Imperial Japanese thoroughly\nunderestimated the resilience of the Chinese people, a mistake that has\npermanently damaged their geopolitical relations.\n\nInto this conflict joins the doctrine of American international\nrelations, brought about by the diminished dominance of the European\nconception of order at the end of the second world war. Here, the second\nnarrator of *World Order* presents himself: the arch-realist. Kissinger\nis the Otto von Bismarck of our time. While Secretary of State,\nKissinger brokered the critical deals between the United States and\nChina, ushering in a normalization of relations between the two powers.\nWe see the arch-realist in full glory throughout Kissinger's analysis of\nthe precepts of United States foreign policy, characterized primarily in\nterms of the dichotomy between American idealism and geopolitical\nnecessity.\n\nIn pursuing the former, the United States has sought to temper the\noften-vicious quality of Westphalian order through the establishment of\nlegitimate international institutions, such as the League of Nations\n(and its successor, the United Nations), the International Monetary\nFund, and the World Bank, which are designed to uphold legal norms while\nsimultaneously fostering an environment of international cooperation.\nThis is the school of foreign policy exemplified by Woodrow Wilson and\nJimmy Carter. Though he respects their intentions, Kissinger has little\nsympathy for idealism in foreign-policy, especially when it flounders\nagainst international recalcitrance. Instead he turns to the competing\nschool figureheaded by Theodore Roosevelt, Harry Truman, Richard Nixon,\nand George H. W. Bush, which values the advancement of American\ninterests and the preservation of geopolitical stability over the spread\nof American ideals. Ultimately, Kissinger believes that global\nWestphalianism is an order worth maintaining, even at the expense of\nmutual cooperation between states.\n\nWhether one finds the arguments of international realpolitik compelling\nis immaterial; it is worth understanding Kissinger's position for its\nown sake, as the arch-realist provides much-needed clarity at a time in\nwhich Americans are generally unsure of their country's proper role\nabroad. Moreover, the reality of foreign policy almost always involves a\ndilemma of values against interests. Any regional or global power in the\nposition of the United States faces repeated contradictions along this\ndilemma within its own policy: consistency is the price of hegemony.\nTherefore, it is prudent that one heeds Kissinger, even for those who\nprefer the advancement of America's values. As the Chinese conception of\norder, which often does not adhere to the premise of cooperation,\nasserts itself on the global stage, Kissinger's thoughts on realpolitik\nbecome more important.\n\nThe third narrator of *World Order* is the recalcitrant. Without\nquestion, the political tenure of Henry Kissinger is permeated with\ncontroversy. He notoriously supported (if not endorsed outright) the\noverthrow of democratically elected governments in Latin America, and\nshowed little concern for the violation of human rights in the secret\nbombings of Cambodia during the Vietnam War. We have yet to learn the\nfull story regarding Kissinger's role in advising the administration of\nGeorge W. Bush throughout the 2003 escalation into Iraq, but history\nwill almost certainly question the merit of his consulting. These ghosts\ndo not appear explicitly in the text, yet one senses an internal\nconflict between the man and his decisions. When the aforementioned\ntopics do surface, we witness an individual who has yet to come to terms\nwith his ghosts. This is especially pronounced when Kissinger writes of\nthe decisions leading to and actions taken during the Iraq War: too much\nis simply left unsaid.\n\nThat Kissinger is human and thus falls prey to human nature of this sort\nmay surprise his harshest critics. For the rest of us, it merely dampens\nan otherwise superb demonstration of personal intellect and diplomatic\nwisdom. The book in its entirety more than makes up for Kissinger's\nshortcomings. A chapter dedicated to the peril of technological\ninterconnectedness aside, this is a thoughtful account, which succeeds\nin striving to explain the preponderant conflict of international\npolitics. Whatever his flaws, Kissinger's impact on American foreign\nrelations has been profound, and more often than not, genuinely\nbeneficial. This book should be seen in this light; *World Order* is\nworth reading, for idealists and realists alike.\n\n[1]: http://www.amazon.com/World-Order-Henry-Kissinger/dp/1594206147\n"
},
{
"alpha_fraction": 0.6824754476547241,
"alphanum_fraction": 0.689994215965271,
"avg_line_length": 27.344263076782227,
"blob_id": "f227a6596e9a55115a7169191a8234f10cdb304a",
"content_id": "b6a6aab35ad4c2ca04175c603c2ed7c71759508b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1729,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 61,
"path": "/blog/_posts/2015-03-13-a-c-file-to-print-backwards-strings.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'A C file to print backwards strings'\nsubheadline: 'Programming'\nteaser: 'How to write a simple script to reverse your terminal inputs.'\nlayout: page\nauthor: David Kraemer\ndate: March 13, 2015\ncategories:\n - blog\ntags:\n - 'C'\n - 'programming'\nauthor: David Kraemer\n---\n\nOut of boredom on an airplane, I decided I would try a challenge with C\nand string pointers. The problem: write a program that takes arbitrary\ncommand-line arguments and prints the arguments backwards in reverse\norder. I have provided my code to my solution below. My idea was to\ncycle backwards through the character array defined by each argument and\nprint out the character at every location in reverse order. I\ndemonstrate this approach with ` *(str-- + len - 1)` in the\n` bw`procedure. Similarly, to get the command line\narguments to print in reverse order, I use a parallel trick by starting\nat the end of the list of arguments and working my back to the start.\n\n```C\n#include <stdio.h>\n#include <string.h>\n\nvoid bw(char * str) {\n int i = 0, len = strlen(str);\n while (i++ < len)\n printf(\"%c\", *(str-- + len - 1));\n printf(\" \");\n}\n\nint main(int argc, char ** argv)\n{\n int i = 0;\n while (i++ < argc - 1) \n bw(*(argv-- + argc - 1) );\n printf(\"\\n\"); \n return 0;\n}\n```\n\nAfter compiling, I moved this program (I called it `bw`) into my `/bin`\ndirectory, so now I can run this program from anywhere on my machine.\nThe added bonus is that I have the program spit out the results to\nstandard output, so I can pipe it to anywhere I desire. For example, the\nline\n\n bw Hello, this is a test!\n\ngives the output of\n\n !tset a si siht ,olleH\n\nAnyways, just a fun application with fairly concise and efficient C\ncode!\n"
},
{
"alpha_fraction": 0.67836594581604,
"alphanum_fraction": 0.6921749114990234,
"avg_line_length": 40.380950927734375,
"blob_id": "34e52e954b0fe6b2c6492c752ce8764f2753c24e",
"content_id": "e1fbc733c9a2af7b593354d5dfec272f853d916e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1738,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 42,
"path": "/ipython/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"IPython Notebooks\"\nAuthor: \"David Kraemer\"\nlayout: page\nshow_meta: false\npermalink: ipython/\n---\n\nThis page is dedicated to hosting interesting projects and activities that I have \ncompiled together into IPython notebooks. If you haven't experienced the wondrous\nopen-source technology that is [IPython][ipython-link], you definitely have to \ncheck it out. The IPython interpreter is a huge improvement on the default Python\nshell, and the notebook greatly increases development productivity. I have a list\nof notebooks that I have created for school or other activities which you can \ndownload and play with on your own.\n\nNote: nowadays the IPython notebook goes by the name \"Jupyter,\" because recent \nprogress on the technology has included making notebooks language agnostic. So\nfar, Julia, Python, and R are supported by the notebook.\n\n| Notebook | IPython File | Printable | Script |\n|:---------+:-------------+:----------+:-------|\n| [Vector Space Operations in Python][1-html] | [`.ipynb`][1-ipynb] | [`.pdf`][1-pdf] | [`.py`][1-py] |\n| [Abstract Algebra Visualization with Python][2-html] | [`.ipynb`][2-ipynb] | [`.pdf`][2-pdf] | [`.py`][2-py] |\n| [The Solow Growth Model][3-html] | [`.ipynb`][3-ipynb] | [`.pdf`][3-pdf] | [`.py`][3-py] | \n\n[ipython-link]: http://www.ipython.org\n\n[1-html]: files/gram-schmidt.html\n[1-ipynb]: files/gram-schmidt.ipynb\n[1-pdf]: files/gram-schmidt.pdf\n[1-py]: files/gram-schmidt.py\n\n[2-html]: files/modn-times-table.html\n[2-ipynb]: files/modn-times-table.ipynb\n[2-pdf]: files/modn-times-table.pdf\n[2-py]: files/modn-times-table.py\n\n[3-html]: files/solow-growth.html\n[3-ipynb]: files/solow-growth.ipynb\n[3-pdf]: files/solow-growth.pdf\n[3-py]: files/solow-growth.py\n"
},
{
"alpha_fraction": 0.6604584455490112,
"alphanum_fraction": 0.6750238537788391,
"avg_line_length": 46.05617904663086,
"blob_id": "73338aa9ceedc41856f5e101a172d9ff17c95ce0",
"content_id": "6dc4b2db7b7e3e94dff43ab937791f328421a782",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4188,
"license_type": "permissive",
"max_line_length": 146,
"num_lines": 89,
"path": "/blog/_posts/2014-11-17-quotient-groups.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Quotient Groups'\nsubheadline: 'Mathematics'\nteaser: 'Discovering the circle group in unlikely places.'\nlayout: page\nauthor: David Kraemer\ndate: November 17, 2014\ncategories:\n - blog\ntags:\n - math\n - 'abstract algebra'\nauthor: David Kraemer\n---\n\n## What does \\\\(\\mathbb{R}/\\mathbb{Z}\\\\) look like?\n\nDuring our study of groups in my abstract algebra class, our discussion\nof quotient groups led to a fun moment of considering what the quotient\ngroups of common infinite sets resemble: specifically, the quotient\ngroups \\\\(\\mathbb{R}/\\mathbb{Z}\\\\). Now, by the definition of the\nquotient group, this describes all of the cosets of \\\\(\\mathbb{Z}\\\\)\n(under addition) within the larger set of \\\\(\\mathbb{R}\\\\), in other\nwords:\n\n\\\\[ \\mathbb{R}/\\mathbb{Z} = \\{ x + \\mathbb{Z} : x \\in \\mathbb{R} \\} \\\\]\n\nThis is the simple definition that can be actually improved quite a bit.\nTo get a stronger definition, one might ask how\n\\\\(\\mathbb{R}/\\mathbb{Z}\\\\) operates conceptually. One important thing\nto notice is that \\\\(0+\\mathbb{Z}=1+\\mathbb{Z}\\\\), and in general we\nhave that \\\\(x+\\mathbb{Z}=(x+n)+\\mathbb{Z}\\\\). So, we can equivalently\ncharacterize this quotient group by the cosets of \\\\(\\mathbb{Z}\\\\) over\njust the set \\\\([0,1)\\\\). It turns out that \\\\(\\mathbb{R}/\\mathbb{Z}\\\\)\n[is isomorphic to](https://en.wikipedia.org/wiki/Circle_group#Isomorphisms)\n\\\\(\\mathbb{T}_1\\\\), the circle group defined by \n\n\\\\[ \n\\mathbb{T}_1 = \\\\{z\\in \\mathbb{C} \\mid |z|=1 \\\\} \n\\\\]\n\nWhy is this the case? Every element\n\\\\( z \\in \\mathbb{T}\\_1 \\\\) \ngiven by \\\\(z=a+ib\\\\) with the condition that\n\\\\(|z|=1\\\\) represents a point on the unit circle. In the complex form, we\nalso have the condition that \\\\(a^2 + b^2 = 1\\\\). Remember that each\nelement \\\\(x\\\\) that defines a distinct coset of \\\\(\\mathbb{Z}\\\\),are\nelements in \\\\([0,1)\\\\). To get a bjiective mapping, we can think of \\\\(x\\\\)\nas a fractional distance along the unit circle's circumference. For\nexample, if \\\\(x=\\frac{1}{4}\\\\), we would want our bijection to send\n\\\\(x\\\\) to the location on the unit circle that represents one quarter of\na (counterclockwise) rotation around it, i.e. the point corresponding to\nthe location of \\\\(\\frac{\\pi}{2}\\\\) radians. Specifically, we let\n\\\\(\\phi(x):[0,1)\\to \\mathbb{T}\\_1\\\\) by \n\\\\[ \\phi(x)= \\cos\\left(\\frac{\\pi}{2}x\\right) + i\\sin\\left(\\frac{\\pi}{2}x\\right) \\\\]\nWe know that \\\\(\\phi\\\\) is\nwell-defined as the Pythagorean identity \\\\(\\cos^2(A)+\\sin^2(A)=1\\\\)\nholds no matter what \\\\(A\\\\) is. It is also easy to see that every \\\\( z \\in \\mathbb{T}\\_1 \\\\) \nis hit by \\\\(\\phi\\\\). Finally, if we are given \\\\(x_1\\\\)\nand \\\\(x_2\\\\) in \\\\([0,1)\\\\) with\n\n\n\\\\[ \n\\cos\\left(\\frac{\\pi}{2} x\\_1\\right) +i\\sin\\left(\\frac{\\pi}{2}x\\_1\\right) = \\cos\\left(\\frac{\\pi}{2}x\\_2\\right)+i\\sin\\left(\\frac{\\pi}{2}x\\_2\\right) \n\\\\]\n\nit follows that \\\\(x\\_1=x\\_2\\\\) because the domain of \\\\(\\phi\\\\) is\n\\\\([0,1)\\\\). Of course, \\\\(\\frac{\\pi}{2}=\\frac{5\\pi}{2}\\\\) on the\ncircle, because rotating past \\\\(2\\pi\\\\) radians simply begins the\nprocess anew. This ties very neatly into the elements of\n\\\\(\\mathbb{R}/\\mathbb{Z}\\\\), as now we can consider a point as the set\nof all *rotations* around a point. For example, \\\\(0+\\mathbb{Z}\\\\) gives\nall possible representations of the point \\\\(1 + i0\\\\) on the unit circle.\nThus, \\\\(\\mathbb{R}/\\mathbb{Z}\\\\) gives a thorough representation of the\nunit circle by incorporating the cyclic nature of its rotations.\n\nI find \\\\(\\mathbb{R}/\\mathbb{Z}\\\\) very neat and satisfying in this\nregard. But maybe it's also a little boring. What if we stepped it up a\nnotch and inquired about the next logical quotient group:\n\\\\(\\mathbb{R}/\\mathbb{Q}\\\\)? It turns out, sadly, that\n\\\\(\\mathbb{R}/\\mathbb{Q}\\\\) has no such simple characterization. In\nfact, there's an interesting [StackExchange\npost](http://math.stackexchange.com/questions/182247/visualizing-quotient-groups-mathbbr-q)\nthat explains why \\\\(\\mathbb{R}/\\mathbb{Z}\\\\) gives none of the flavor\nof results as \\\\(\\mathbb{R}/\\mathbb{Z}\\\\). If you're interested, though,\nit does motivate the construction of [Vitali\nsets](http://en.wikipedia.org/wiki/Vitali_set), which are notable\nbecause they are immeasurable! In the meanwhile, I'll stick to my\ncircles.\n"
},
{
"alpha_fraction": 0.6896551847457886,
"alphanum_fraction": 0.6896551847457886,
"avg_line_length": 11.88888931274414,
"blob_id": "3be33ba7acc48f56e78d943e60a73380782dcc86",
"content_id": "81bdbd570b2f5c849e8963ea16b540e4cb327fdd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 116,
"license_type": "permissive",
"max_line_length": 28,
"num_lines": 9,
"path": "/misc/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Miscellaneous Stuff\"\nAuthor: \"David Kraemer\"\nlayout: page\nshow_meta: false\npermalink: misc/\n---\n\nRandom stuff.\n"
},
{
"alpha_fraction": 0.6643670201301575,
"alphanum_fraction": 0.6814419031143188,
"avg_line_length": 43.25190734863281,
"blob_id": "fc84f72bb6c6efa0145f42bbf6b3c2270f68f098",
"content_id": "af629171a7706151a9e0ff92e2427d0efa4de68c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5798,
"license_type": "permissive",
"max_line_length": 521,
"num_lines": 131,
"path": "/_site/ipython/files/gram-schmidt.py",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "\n# coding: utf-8\n\n## Some useful linear algebra functions\n\n# I was working on a linear algebra problem set for my representation theory class, which required some extensive uses of projections in $\\mathbb{R}^n$. After some horrible attempts manually backfired miserably with arithmetic errors, I turned to Python for a hand.\n# \n# Initially, I thought _Mathematica_ might provide an easier set of functions to deal with projections and orthogonality, but as it happens I find that Python's programming environment is more conducive to custom funcions than _Mathematica_.\n\n# #### Projections in $\\mathbb{R}^n$\n# Projections simply require a vector space $V$ over a field $\\mathbb{K}$ equipped with an inner product $\\langle\\,,\\rangle: V\\times V \\to \\mathbb{K}$. It is not too difficult to generalize the operations presented here to different inner product spaces, but we will only consider the vector spaces $V=\\mathbb{R}^n$ over $\\mathbb{R}$ with the standard dot product, defined\n# \n# > $\\langle u,v \\rangle = \\sum_{i=1}^{n} u_iv_i$.\n# \n# Start with <code>sympy</code>, which will provide us with the symbolic algebra backend we will need for vector and matrix operations.\n\n# In[1]:\n\nfrom sympy import *\nimport matplotlib.pyplot as plt # for visualization\nget_ipython().magic(u'matplotlib inline')\ninit_printing()\n\n\n# With <code>sympy</code>, the <code>Matrix</code> class is the primary means that we will use to do computations. As opposed to the <code>numpy.ndarray</code>, <code>sympy</code> is picky about how you do dot products. We will essentially use the formula $\\langle u,v \\rangle = u^Tv$, which needs to be specified properly in <code>sympy</code>. The first function I'll write is a simple projection from one vector to another, which will form the basis for more complex procedures later. The general projection is defined\n# \n# > $\\textrm{proj}_{v}(u) = \\frac{\\langle u,v \\rangle}{\\langle v,v\\rangle}v$\n# \n# and it is useful to have a function that performs this computation, as we shall soon see.\n\n# In[2]:\n\n# returns the projection of the vector u onto the line \n# defined by the vector v\ndef proj(u, v):\n return ((u.T * v)[0] / (v.T * v)[0]) * v\n\n\n# This works as you might expect. The projection formula is discussed thoroughly in calculus and linear algebra classes, which I won't add to.\n\n# In[3]:\n\nu = Matrix([2,4])\nv = Matrix([5.,3.])\np = proj(u,v)\nd = u - p\nplt.arrow(0, 0, float(u[0]),float(u[1]), head_width=0.15, fc='w')\nplt.arrow(0, 0, float(v[0]), float(v[1]), head_width=0.15, fc='w')\nplt.arrow(0, 0, float(p[0]), float(p[1]), head_width=0.15, fc='k')\nplt.arrow(float(p[0]), float(p[1]), float(d[0]), float(d[1]), head_width=0.15, linestyle='dashed', fc='k')\n\nplt.xlim([0,6])\nplt.ylim([0,5])\n\n\n# Another simple tool is normalization. Sometimes you want a vector to have unit length, so here's a procedure to encapsulate the underlying <code>numpy</code> process.\n\n# In[4]:\n\n# returns a normalized version of v\ndef normalize(v):\n return v / sqrt((v.T * v)[0])\n\n\n# #### The Gram Schmidt algorithm and orthogonalization\n# Suppose you have a basis $B=\\{v_1,v_2,\\cdots,v_n\\}$ for some vector space (it can be a subspace). In many circumstances, it is desirable to ensure that such a basis is orthogonal. \n# \n# > Two vectors $u$ and $v$ in $V$ are _orthogonal_ if $\\langle u,v \\rangle = 0$.\n# \n# The Gram Schmidt algorithm provides a means for taking any basis $B$ and returning an \"orthogonalized\" basis $\\tilde{B}=\\{u_1, u_2, \\cdots, u_n\\}$. It works according to the following inductive definition:\n# \n# > 1. $u_1 = v_1$, and\n# 2. $\\displaystyle u_{k} = v_k - \\sum_{i=1}^{k-1}\\textrm{proj}_{u_{i}}(v_k)$\n# \n# We now give a function to compute an orthogonal basis.\n\n# In[5]:\n\n# returns a list of pairwise orthogonal vectors \"ortho_basis\"\n# that serves as a basis for the space defined by \"basis\".\n# the \"normal\" optional argument allows the procedure to\n# return an orthonormal basis if desired\ndef gram_schmidt(basis, normal=False):\n ortho_basis = []\n u = zeros(len(basis[0]), 1) # dummy vector that gets carved out\n for i in range(len(basis)):\n u = basis[i]\n # handles the inductive case\n if i > 0:\n for j in range(i):\n u -= proj(basis[i], ortho_basis[j]) # proj procedure\n if normal:\n ortho_basis.append(normalize(u)) # normalize procedure\n else:\n ortho_basis.append(u)\n return ortho_basis\n\n\n# As an example, suppose you are considering the subspace $W$ in $\\mathbb{R}^3$ defined by all $(x_1,x_2,x_3)^T$ satisfying $x_1 - x_2 - x_3 = 0$. A simple basis for $W$ is\n# \n# > $B = \\{ (1, 1, 0)^T, (1, 0, 1)^T \\}$,\n# \n# which is not orthogonal, as $\\langle (1,1,0)^T, (1,0,1)^T\\rangle = 1$. We can construct an orthonormal basis for $W$ with the following function call:\n\n# In[6]:\n\nv1 = Matrix([1,1,0])\nv2 = Matrix([1,0,1])\n\n[u1, u2] = gram_schmidt([v1,v2], normal=True)\n\n(u1, u2)\n\n\n\n# #### Projecting a vector onto a subspace\n# Finally, let's write a function to project an arbitrary vector $v$ in $\\mathbb{R}^n$ to a subspace $W$. For this, we will take as an input a basis $B=\\{b_1,\\cdots, b_n \\}$ for $W$, though it not necessarily need be an orthogonal one. The formula for the projection is\n# \n# > $\\displaystyle\\textrm{proj}_W(v) = \\sum_{i=1}^n \\textrm{proj}_{b_i}(v)$,\n# \n# which we implement below.\n\n# In[7]:\n\ndef project_onto_subspace(v, basis):\n p = zeros(len(v))\n for b in basis:\n p += proj(v,b) # proj procedure\n return p\n\n\n# And that's all for this post! I'm working on a few more useful functions for projections in linear algebra, but I'll hold off on them until they are a bit more polished. Hopefully you find this useful in your computational adventures, especially if your arithmetic prowess is as legendary as mine... happy computing!\n"
},
{
"alpha_fraction": 0.7407209277153015,
"alphanum_fraction": 0.7519629001617432,
"avg_line_length": 39.91240692138672,
"blob_id": "e97263ee2e369ca660e355c7f186b5b4c0984e46",
"content_id": "8a02fb12ab9e06597048d1e26e214908506e6bd1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5604,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 137,
"path": "/blog/_posts/2014-11-22-python-installation.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Python installation'\nsubheadline: 'Programming'\nteaser: 'Getting started with Python programming'\nlayout: page\nauthor: David Kraemer\ndate: November 22, 2014\nsubheadline: Announcements\nbreadcrumb: true\ncategories:\n - blog\ntags:\n - Python\n - programming\n - installation\nauthor: David Kraemer\n---\n\n### Installing and using Python\n\nIf you have ever had to solve a linear system involving a 10 by 10\nmatrix by hand, then you have firsthand experience with the types of\ncomputations that drive mathematicians, scientists, and developers\ninsane. Luckily, computers are the perfect solution for problems that\nare conceptually simple but computationally difficult. In fact, many of\nthe original software packages implemented for computers (and are still\nwidely considered a baseline for testing computational speed) deal with\nperforming difficult computations in linear algebra, such as inversion,\ndeterminants, and decomposition.\n\nThe problem is that there are many different types of software, each\nwith its respective strengths and drawbacks. For computational and\nsymbolic algebra, *Wolfram Mathematica* I believe is the clear standout.\nIn specific fields such as computer vision, it is *Matlab* which has the\nupper hand. Both do the simple tasks of linear algebra effectively (I\nwould give the nod to *Mathematica* for user friendliness).\nUnfortunately, both are also proprietary, and if you can't get a license\nfrom an organization, it can be quite expensive.\n\nEnter open-source. The dominant open-source language of choice for\nresearch is Python. R may arguably give it a run for its money, but\nwhile R is a good language to script statistical computations, Python\nhas the advantage of being a genuine programming language in addition to\nits scientific data analysis tools. Regardless, the best part of\nopen-source is that it costs you nothing to try it out and see what you\nlike! This post will give instructions for installing Python to your\ncomputer, and later posts will give a brief tutorial on using its\nscientific programming capabilities under the framework of the user\ninterface *iPython*.\n\nNote: throughout this tutorial, I will be relying heavily on Chapter 1\nof Wes McKinney's [*Python for Data\nAnalysis*](http://www.amazon.com/Python-Data-Analysis-Wrangling-IPython/dp/1449319793)\ntext, so I want to give credit where it is due.\n\n#### Installation on *Windows*\n\nFirst, you want to go to ` http:/www.enthought.com/downloads`, make sure\nthat the 'Windows' tab is selected, and download \"Canopy Express.\" The\nfile being downloaded should be an `MSI` file and after launching should\nproduce an installation wizard. You should keep the default installation\nat `C:\\Python27` for simplicity. Now, run `cmd.exe` and enter `python`.\nIf everything worked correctly, you should see a window open that looks\nlike\n\n```Bash\n C:\\Users\\usrname>python\n Python 2.7.3 |EPD_free 7.3.-1 (32-bit)| (default, Nov 22 2014, 12:12:12) on win32\n Type \"credits\", \"demo\" or \"enthought\" for more information.\n >>>\n```\n\nIf you did not see this, search for \"environment variables\" and select\n`Edit environment variables for your account`. In the ensuing window,\nlook for the `Path` variable, and verify that\n`C:\\Python27;C:\\Python27\\Scripts` is there. If there are other things\nthere, delete them. Restart `cmd.exe` and you should be good to go!\n\nFor more installation instructions, visit the\n[`Enthought Installation Documentation Page`][1].\n\n#### Installation on Mac\n\nFirst, verify that `Xcode` is installed on your computer. If not, you\ncan install it from the ` Xcode developer ` page. Then, download the\n`.dmg` file found at ` http:/www.enthought.com/downloads`. Double-click\nthe `.dmg` file to mount it, and then double-click the `.mpkg` file\ninside of it to install the program.\n\nNow you should be able to run ` ipython --pylab` from a terminal window,\nand you should get an output looking like:\n\n```Bash\n Type \"copyright\", \"credits\" or \"license\" for more information.\n\n IPython 1.2.1 -- An enhanced Interactive Python.\n ? -> Introduction and overview of IPython's features.\n %quickref -> Quick reference.\n help -> Python's own help system.\n object? -> Details about 'object', use 'object??' for extra details.\n\n In [1]:\n```\n\nIf this isn't quite working, visit\n[`Enthought Installation Documentation Page`][2].\n\n#### Installation on Linux\n\nGo to `.dmg` file found at ` http:/www.enthought.com/downloads` and\ninstall the correct Linux version for your OS and architecture. You\nshould now have a `.sh` file downloaded. Use ` bash filename.sh ` in a\nterminal window to install and execute the script. You should probably\nsave this in the directory `/home/username/epd`. Now, edit the `.bashrc`\nfile at the end to include the line\n`export PATH=/home/username/epd/bin:$PATH` and rerun `.bashrc`. Then if\nyou now type `ipython --pylab` into a terminal window, you should see\noutput that looks like:\n\n```Bash\n Type \"copyright\", \"credits\" or \"license\" for more information.\n\n IPython 1.2.1 -- An enhanced Interactive Python.\n ? -> Introduction and overview of IPython's features.\n %quickref -> Quick reference.\n help -> Python's own help system.\n object? -> Details about 'object', use 'object??' for extra details.\n\n In [1]:\n```\n\nIf you're still encountering issues, check out\n[` Enthought Installation Documentation Page`][3].\n\n[1]: http://docs.enthought.com/canopy/quick-start/install_windows.html\n[2]: http://docs.enthought.com/canopy/quick-start/install_macos.html\n[3]: http://docs.enthought.com/canopy/quick-start/install_linux.html"
},
{
"alpha_fraction": 0.5742455124855042,
"alphanum_fraction": 0.6512345671653748,
"avg_line_length": 30.701086044311523,
"blob_id": "6beb5e971e981e8a6bfd0aa64a3d733226502d69",
"content_id": "cf12ba433115c0046cdf0714166b026a3ef468c8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5832,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 184,
"path": "/blog/_posts/2014-11-23-linear-algebra.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Linear Algebra in Python'\nsubheadline: 'Programming'\nteaser: 'Getting started with basic linear algebra functionality and <code>NumPy</code>.'\nlayout: page\nauthor: David Kraemer\ndate: November 23, 2014\ncategories:\n - blog\ntags:\n - Python\n - programming\n - math\n - NumPy\nauthor: David Kraemer\n---\nPython offers a great set of linear algebra-related packages that let\nyou do computations very quickly. This post will highlight a few\nimportant cases. For more information, go to\n[`SciPy's Linear algebra documentation`][1].\n\n### Declaring matrices and vectors\n\nOpen a terminal window and run `ipython --pylab`. The `--pylab` flag\ntells the iPython interface to include a host of scientific packages,\nincluding [`NumPy`][2] (with the prefix `np` ) and\n[`MatPlotLib`][3]'s `pyplot` packages (with the prefix\n`plt` ). In the interactions window, enter the code\n\n```Python\n In [1]: import scipy.linalg as linalg\n```\n\nThis gives you quick access to all of SciPy's built in linear algebra\nmethods. The complete list of methods can be found in the above link.\nNext, we need to initialize a matrix \\\\(A\\\\). While there are a host of\nclasses that have matrix operations associated with them, we will use\nNumPy's `array` class. It's a very robust class to\nwork with, and as we shall see gives the user considerable lee-way in\nterms of input.\n\n```Python\n In [2]: A = np.array([[1, 2, 3], [4, 0, 6], [7, 8, 9]])\n```\n\nThis is effectively a \"list of lists,\" where each sub-list represents a\nrow. Alternatively, you can see something closer to the traditional\narrangement for a matrix by typing\n\n```Python\n In [3]: A\n Out[3]:\n array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n```\n\nNow, let's initialize a vector \\\\(\\vec{x}\\\\). Vectors are initialized\nsimilarly to matrices, except that they are only involve a single list:\n\n```Python\n In [4]: x = np.array([-1, 3, 2])\n```\n\nNotice that this does not specify whether \\\\(\\vec{x}\\\\) is a row vector\nor a column vector. One of the nice things about the NumPy array class\nis that it does not distinguish between the two, so you don't need to\nworry about taking transposes!\n\n### Simple operations\n\nA natural operation that we need to learn is how to obtain the product\n\\\\(A\\vec{x}\\\\). To do so, we will use the `dot()` \nmethod, and store this into a new vector, \\\\(\\vec{b}\\\\).\n\n```Python\n In [5]: b = A.dot(x)\n```\n\nTo see what this result was, just type\n\n```Python\n In [6]: b\n Out[6]: array([11, 8, 35])\n```\n\nNow, if you're skeptical, we can verify that this is, in fact, the\ncorrect value for \\\\(\\vec{b}\\\\). Given some *arbitrary* \\\\(\\vec{x}\\\\), if\n\\\\(A\\vec{x}=\\vec{b}\\\\), then \\\\(\\vec{x}\\\\) should equal the vector we\noriginally declared. So, let's use `linalg.solve` to verify the results.\n\n```Python\n In [7]: linalg.solve(A,b)\n Out[22]: array([-1., 3., 2.])\n```\n\nAnother useful computations is inversion. If \\\\(A\\\\) is invertible (ours\nis), then `linalg.inv(A)` will return a unique inverse\nmatrix. Let's set \\\\(B=A^{-1}\\\\) by\n\n```Python\n In [8]: B = linalg.inv(A)\n```\n\nWe can easily verify that this method works properly by using matrix\nmultiplication, which also uses the `dot()` method.\n\n```Python\n In [9]: B.dot(A)\n Out[9]:\n array([[ 1.00000000e+00, 0.00000000e+00, 2.22044605e-16],\n [ -1.11022302e-16, 1.00000000e+00, -1.11022302e-16],\n [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])\n```\n\nThis is a very, very close approximation of the identity matrix, so\n\\\\(B\\\\) must be a good inverse! Also, if \\\\(A\\\\) is invertible, then\n\\\\(\\det(A)\\ne 0\\\\). We can verify this by typing\n\n```Python\n In [9]: B = linalg.det(A)\n Out[9]: 59.999999999999986\n```\n\n### Eigenvalues, eigenvectors, and decompositions\n\nMany applications of linear algebra require decompositions of matrices.\nThe simplest way to do this is with eigenvector decomposition. SciPy\noffers a very simple way to extract this information. We will start with\n`linalg.eig` .\n\n```Python\n In [10]: d, P = linalg.eig(A)\n In [11]: D = np.diag(d)\n```\n\nHere, `d` is a vector containing the eigenvalues of\n\\\\(A\\\\). NumPy's `diag()` function will code a vector\ninto the diagonal entries of a matrix. In addition,\n`P` is the matrix encoding each eigenvector of \\\\(A\\\\).\nThen, we can verify the \\\\(A=PDP^{-1}\\\\) decomposition with the following\ncode:\n\n```Python\n In [12]: P.dot(D.dot(linalg.inv(P)))\n Out[12]:\n array([[ 1.00000000e+00+0.j, 2.00000000e+00+0.j, 3.00000000e+00+0.j],\n [ 4.00000000e+00+0.j, -2.66453526e-15+0.j, 6.00000000e+00+0.j],\n [ 7.00000000e+00+0.j, 8.00000000e+00+0.j, 9.00000000e+00+0.j]])\n``` \n\nAnother common decomposition is the Singular Value Decomposition. This\ndecomposition is neat because it generalizes the eigenvector\ndecomposition to \\\\(m\\times n\\\\) matrices. So, let's initialize a new\nmatrix \\\\(X\\in\\mathbb{R}^{3\\times 4}\\\\) that can take advantage of\nSVD.\n\n```Python\n In [13]: X = np.array([[1, 2, 3, 4], [1, 0, 1, 0], [-2, 4, 10, 0]])\n In [14]: U, s, Vt = linalg.svd(X)\n In [15]: S = np.diag(s)\n```\n\nNow, we write `Vt` because SVD gives a decomposition\n\\\\(U\\\\), \\\\(S\\\\), and \\\\(V\\\\), such that \\\\(X=USV^T\\\\). We can verify that this\nholds by giving\n\n```Python\n In [16]: U.dot(S.dot(Vt))\n Out[16]:\n array([[ 1.00000000e+00, 2.00000000e+00, 3.00000000e+00,\n 4.00000000e+00],\n [ 1.00000000e+00, -2.77555756e-16, 1.00000000e+00,\n 3.88578059e-16],\n [ -2.00000000e+00, 4.00000000e+00, 1.00000000e+01,\n -1.02175213e-15]])\n```\n\nI hope this gives you a taste for the computational potential of Python\nand SciPy!\n\n[1]: http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html\n[2]: http://docs.scipy.org/doc/numpy/reference/\n[3]: http://matplotlib.org/"
},
{
"alpha_fraction": 0.7340930700302124,
"alphanum_fraction": 0.7445394396781921,
"avg_line_length": 34.099998474121094,
"blob_id": "566a1b73db9a62c6af149312d53ff907efd5380f",
"content_id": "ff0e9275091f6aae79820e23b8d9ed7961808980",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1055,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 30,
"path": "/blog/_posts/2015-02-02-new-ipython-posts-location.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'IPython blog migration'\nsubheadline: 'Announcements'\nlayout: page\nauthor: David Kraemer\ndate: February 2, 2015\ncategories:\n - blog\ntags:\n - announcements\n - ipython\nauthor: David Kraemer\n---\n\nAs it turns out, dealing with IPython's notebook, however nice it is to\nplay with, is a massive headache when trying to incorporate it into\ncustom HTML pages. Thus, from now on, I will have a [separate page][1] \ndedicated to the posts in which I use the IPython\nnotebook. I think it will be a glorified list with updates at the top,\nbut formatted in such a way that you can view the notebook file as HTML,\nin PDF form with \\\\(\\LaTeX\\\\), and download the actual `.ipynb` files.\n\nSpeaking of which, I have a new [post about vector space projections with `sympy`, so check it out!][2]\n(Disclaimer: my motivation for creating that post was for my\nrepresentation theory homework—we're doing a review/crash course of\nlinear algebra). Anyway, stay tuned for more (non-IPython notebook)\nmaterial on this blog!\n\n[1]: /ipython/\n[2]: /ipython/files/Kraemer-01.html\n"
},
{
"alpha_fraction": 0.6648990511894226,
"alphanum_fraction": 0.6810116171836853,
"avg_line_length": 54.70454406738281,
"blob_id": "80345615fc0ec506959e72cfb281f7369622678e",
"content_id": "5a0b2e1fdf930270650dacacdf87692942b0a3a5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4903,
"license_type": "permissive",
"max_line_length": 648,
"num_lines": 88,
"path": "/ipython/files/modn-times-table.py",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "\n# coding: utf-8\n\n# # Visualizing Rings of Integers Modulo $n$\n# \n# I saw a [StackExchange](http://math.stackexchange.com/a/743542/224759) post that gave a simple way to visualize rings of integers modulo $n$, but his link was broken, so I thought I'd give it a shot. \n\n# ## Ring Axioms\n# For those of you who may not know, a _ring_ is a mathematical object $(R,+,\\cdot)$ with the following properties:\n# \n# 1. $(R,+)$ is an _abelian group_, that is,\n# \n# 1. for every $x,y \\in R$, we have $x+y \\in R$,\n# 2. for every $x,y,z \\in R$, we have $x+(y+z)=(x+y)+z$,\n# 3. there exists an element in $R$, denoted $0$, satisfying $$0+x = x+ 0 = 0$$ for every $x \\in R$,\n# 4. for every $x \\in R$ there exists $y \\in R$ satisfying $$x + y = y + x = 0$$ (these are the group axioms),\n# 5. for every $x,y \\in R$ one has $x+y=y+x$ (abelian property)\n# \n# 2. for every $x,y \\in R$ we have $x\\cdot y \\in R$,\n# 3. for every $x,y,c \\in R$, we have $$c\\cdot(x+y) = c\\cdot x + c\\cdot y$$ and simultaneously $$(x+y)\\cdot c = x \\cdot c + y \\cdot c$$ (these are the distributive properties).\n# \n# If this is your first exposure to rings, then this might be confusing. There is a general motivation for this definition: **rings are designed to have all of the properties of integers!$^{1}$** (If you want more details, check out the [Wikipedia][1]).\n# \n# $^{1}$Technically, commutative rings with no divisors of zero are abstractions of the notion of integers, but I digress. A better motivation is probably the ring of square matrices.\n# \n# [1]: https://en.wikipedia.org/wiki/Ring_(mathematics)\n\n# ## Modular Arithmetic\n# Specifically, the ring of integers modulo $n$, $\\mathbb{Z}/n\\mathbb{Z}$, is the set $$\\{0,1,2,\\cdots, n-1\\}$$ where addition $\\oplus$ is _defined_ to be $$ x \\oplus y \\equiv (x + y) \\bmod{n}$$\n# and multiplication $\\odot$ is _defined_ to be $$ x \\odot y \\equiv (x \\cdot y) \\bmod{n}$$\n# \n# You can check that $\\mathbb{Z}/n\\mathbb{Z}$ is indeed a ring, according to the axioms above. Addition is a bit tricky to think about at first, but there's a great, intuitive example that almost everyone is familiar with: telling time. Say it's 10:00AM and you sleep for 6 hours. What time is it now? Well of course it's 4:00PM, you retort, everyone knows that. But how did you come up with 4:00PM? You actually just did modular arithmetic in your head, by observing that $$10 + 6 \\cong 4 \\bmod{12}$$\n# \n# And, if you think you're funny and reply that it's actually 16:00 military time, then I can retort that you are simply observing time in a different integer ring, specifically in modulo 24.\n\n# ## Multiplication $\\bmod{n}$\n# \n# After some time, you might get used to the thought of addition mod $n$. But I still hadn't come up with a good way of understanding multiplication mod $n$. Enter the StackExchange post. Instead of trying to think about the products and try to come up with some impossible rule, why not just visualize them?\n# \n# I wrote some `Python` code to do just that!\n\n# In[1]:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().magic(u'matplotlib inline')\n\n\n# The main idea is very simple: build a times table, just like in elementary school. However, instead of normal multiplication, we use multiplication mod $n$. So, I have a `multiplication_map` function that generates an $N\\times N$ square matrix $A=(a_{i,j})$ satisfying\n# $$(a_{i,j}) = (i\\cdot j) \\bmod{n} $$ for all $0\\leq i,j < n$.\n# \n# I then do some formatting with `matplotlib.pyplot.imshow`, produce the plot, and save the figure and the corresponding grid to my computer.\n\n# In[69]:\n\ndef multiplication_map(N, save=False):\n # Generating the matrix\n grid = np.empty((N,N))\n for i in range(N):\n for j in range(N):\n grid[i,j] = (i*j) % N\n\n # Formatting and plotting\n plt.figure(figsize=(10,10))\n plt.axis('off')\n plt.imshow(grid, cmap='winter', interpolation='sinc')\n plt.title('Multiplication table for $\\mathbb{Z}/%i\\mathbb{Z}$' % N,\n fontsize=16)\n # Saving (optional)\n if save:\n plt.savefig(\"Z_%d.png\" % N, bbox_inches='tight')\n np.savetxt(\"Z_%d.csv\" % N, grid) \n\n\n# Voila! Now you can visualize the multiplication table for $\\mathbb{Z}/n\\mathbb{Z}$. It's really interesting to see the patterns that seem to appear with different choices of $n$. If you choose a composite $n$, you see a bit more structure and repeated patterns. If you choose $n=p$ where $p$ is prime, then the structures become immensely more complicated and \"random\" looking. I don't know the exact details for why this happens, but my suspicion is that this is due to the fact that $\\mathbb{Z}/p\\mathbb{Z}$ is not just a commutative ring, but it is also a _field_ (hence, an integral domain as well), which has important additional properties.\n\n# In[68]:\n\nN = 4096\nmultiplication_map(N)\n\n\n# In[71]:\n\nM = 5501\nmultiplication_map(M)\n\n\n# Enjoy!\n"
},
{
"alpha_fraction": 0.7033602595329285,
"alphanum_fraction": 0.720582902431488,
"avg_line_length": 31.94841194152832,
"blob_id": "addd91c621da568e174702a9ad50032db311d48d",
"content_id": "dfa72bc7bf7ab7131f7457c5ce1c4b658095ed53",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 8303,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 252,
"path": "/blog/_posts/2015-11-05-brownian-motion-in-python.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\nheader:\n background-color: \"#280914\"\nsubheadline: Statistical computing\ntitle: \"Simulating and visualizing Brownian motion in Python\"\nteaser: How to quickly set up a script to generate Brownian motion with minimal effort.\ndate: July 22 2015\ncategories:\n - blog\ntags:\n - mathematics\n - statistics\n - finance\n - Python\nauthor: David Kraemer\n---\n\nTime was that mathematicians took for granted the equivalence of continuity\nand differentiability of real-valued functions. It isn't difficult to show that\na differentiable function \\\\(f : \\mathbb{R} \\to \\mathbb{R}\\\\) is continuous,\nand since _most_ functions considered through the 18th century were \nparticularly friendly-looking, it went without saying in the mathematics \ncommunity that the converse was obviously true as well.\n\nThe only problem is that it's false. One can construct a continuous function \nthat fails to be differentiable at a point—take \\\\(f(x) = |x|\\\\) for\nexample, since its derivative is undefined at 0. Better yet, the \n[Weierstrass function][1] is an example of a continuous-everywhere, \ndifferentiable-_nowhere_ function. These revelations shook the world of math\nquite profoundly, helping to complete the separation of calculus from its\nphysics and engineering applications and launch the field of analysis, which\naimed to formalize calculus on rigorous footing.\n\n# Brownian motion\n\nA Brownian motion is another type of continuous-everywhere, \ndifferentiable-nowhere class of functions. A function \\\\(B(t)\\\\) is said to be\na Brownian motion if \\\\(B(0)=0\\\\) and for all \\\\(u > t \\\\), one has\n\\\\[\n\tB(u) - B(t) \\sim \\mathcal{N}(0, u-t),\n\\\\]\nwhere \\\\(\\mathcal{N}(0,u-t)\\\\) denotes a normal distribution with mean 0 and\nvariance \\\\(u-t\\\\). Unlike differentiable functions, whose behavior as\n\\\\(u \\to t \\\\) become more and more linear, Brownian motions retain their \nchaotic nature even as the difference between \\\\(u\\\\) and \\\\(t\\\\) shrinks. They\nalso happen to be excellent models for the interactions of tiny particles and\nfor stock prices. \n\n## Generating Brownian motion simulations\n\nUsing `numpy`, `scipy`, and `matplotlib`, it is ridiculously easy to simulate\nBrownian motions with Python. For the remainder of the post, I will describe\nsome basic functions to get yourself started with Brownian motion. We import \nthem at the top of the script:\n\n```Python\nimport numpy as np\nfrom scipy.stats import gaussian_kde \nimport matplotlib.pyplot as plt\n```\n\nFirst, let's discretize our motion \\\\(B(t)\\\\) in the following way: consider \n\\\\(N\\\\) even partitions of the interval \\\\([0,T]\\\\) as\n\\\\[\n\t0 = t\\_0 < t\\_1 < t\\_2 < \\cdots < t\\_{N-1} < t\\_{N} = T,\n\\\\]\nwith the fixed distance \\\\(t\\_i - t\\_{i-1} = \\Delta t = \\frac{T}{N} \\\\)\nNotice that there are \\\\(N+1\\\\) such \\\\(t\\_i\\\\), and since for each interval \n\\\\( t\\_i - t\\_{i} \\\\) we need to take a new sample from \n\\\\(\\mathcal{N}(0,\\Delta t) \\\\), we need a total of \\\\(N\\\\) samples. This can be\nachieved with the `np.random.randn()` function, which given a length `N` will \nproduce an `N`-element `ndarray` of samples from \\\\(\\mathcal{N}(0,1)\\\\). To \nchange the variance on the samples, we can simply compute\n\n```Python\ndt * np.random.randn(N)\n```\n\nwhere `dt = T/N`. But since\n\\\\[\n\tB(T) = \\sum\\_{i=1}^{N} (t\\_{i} - t\\_{i-1})\n\\\\]\nwe actually need the cumulative sum of the sample normal values in order to\nsimulate the sequence. In other languages, you might need to loop through the\narray to compute the new sum. With Python, this process has already been \nimplemented (and optimized) with `np.cumsum`. Our Brownian motion can therefore\nbe simulated with the line\n\n```Python\ndt * np.cumsum(np.random.randn(N))\n```\n\nLet's wrap this up with a simple function call to make it easier in the future\nto generate a Brownian motion:\n\n```Python\ndef brownian_motion(T, N):\n\tdt = T/N\n\treturn dt * np.cumsum(np.random.randn(N))\n```\n\n## Visualization\n\nNow that we can generate \\\\(B(t)\\\\) as needed, let's see how to visualize the\nsequences. Simply writing\n\n```Python\nplt.plot(brownian_motion(10,1000))\nplt.show()\n```\n\nproduces something like this:\n\n![][simple-bm]\n\nWe can see a _distribution_ of similar Brownian motions by looping a number of\ntimes and generating new plots\n\n```Python\nfor i in range(100):\n\tplt.plot(brownian_motion(10,1000))\nplt.show()\n```\n\n![][simple-bm-dist]\n\nNow things are starting to look cool! Let's turn it up a notch. Notice how it\nappears that the majority of the sequences are very close to where they started\nby the end of the simulation? Let's see if that's actually the case. For this\nmore complicated visualization, let's switch from the `plt` paradigm (designed\nin part to mollify MATLAB converts) to the more robust `fig, ax` paradigm.\nWe generate a list of final locations called `finals` after simulating each\nBrownian motion. At the end, we plot a histogram of `finals` and include a\nKDE plot of the distribution. We'll use a standard Gaussian KDE provided in the\nmodule `scipy.stats`, which we imported earlier.\n\n```Python\n# set up the figure\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10), sharey=True)\n\nT, N = 1, 10000\t\t# model parameters\ntime = np.linspace(0, T, N)\nfinals = [] # empty list, will store computed final values here\nfor i in range(100):\n bn = brownian_motion(T, N)\n ax1.plot(time, bn, linewidth=1)\n finals.append(bn)[-1]) # append final value\n\n# y-axis formatting \nlower, upper = ax1.get_ylim()\nplot_padding = (upper - lower)/10\nxc = np.linspace(lower - plot_padding, upper + plot_padding, 100)\n\n# calculate the KDE\nkde = gaussian_kde(finals)\n\n# plot the histogram and the KDE\nax2.hist(finals, normed=True, bins=10, orientation='horizontal')\nax2.plot(kde(xc), xc, color=\"#ff0000\", linewidth=5)\nplt.show()\n```\n\n![][bm-with-hist]\n\nUnsurprisingly, the histogram appears roughly normally distributed, as does the\nKDE plot. Pretty neat!\n\nI don't know about you, but I think `matplotlib` has ugly default colors. Let's\nspruce them up by adding a few lines of `seaborn` imports.\n\n```Python\nimport seaborn as sns\nsns.set_style(\"white\")\nsns.set_palette(\"Blues_r\")\n```\n\nIf we run the code again, we get more aesthetically pleasing graphs.\n\n![][simple-bm-clean]\n![][simple-bm-dist-clean]\n![][bm-with-hist-clean]\n\nNow you have some tools to play with Brownian motion. A complete listing of \nthis blog can be found [here][listing]. Happy coding!\n\n```Python\n# tools for numerical computation and basic plotting\nimport numpy as np\nfrom scipy.stats import gaussian_kde \nimport matplotlib.pyplot as plt\n\n# seaborn is for improving the aesthetic of matplotlib's default \n# plotting it's also a pretty powerful statistical plotting \n# library, which we do not take advantage of here\nimport seaborn as sns\nsns.set_style(\"white\")\nsns.set_palette(\"Blues_r\")\n\n# simulate a Brownian motion with N steps and variance T/N\ndef brownian_motion(T, N):\n\tdt = T/N\n\treturn dt * np.cumsum(np.random.randn(N))\n\n# plot one simulation\nplt.plot(brownian_motion(10,1000))\nplt.show()\n\n# plot 100 simulations!\nfor i in range(100):\n\tplt.plot(brownian_motion(10,1000))\nplt.show()\n\n# plot 100 simulations and a histogram/KDE of the final \n# values of the sequences\n\n# set up the figure\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10), sharey=True)\n\nT, N = 1, 10000\t\t# model parameters\ntime = np.linspace(0, T, N)\nfinals = [] # empty list, will store computed final values here\nfor i in range(100):\n bn = brownian_motion(T, N)\n ax1.plot(time, bn, linewidth=1)\n finals.append(bn[-1]) # append final value\n\n# y-axis formatting \nlower, upper = ax1.get_ylim()\nplot_padding = (upper - lower)/10\nxc = np.linspace(lower - plot_padding, upper + plot_padding, 100)\n\n# calculate the KDE\nkde = gaussian_kde(finals)\n\n# plot the histogram and the KDE\nax2.hist(finals, normed=True, bins=10, orientation='horizontal')\nax2.plot(kde(xc), xc, color=\"#ff0000\", linewidth=5)\nplt.show()\n```\n\n\n[1]: https://en.wikipedia.org/wiki/Weierstrass_function\n\n[simple-bm]: ../files/brownian/simple-brownian.jpg\n[simple-bm-dist]: ../files/brownian/simple-brownian-dist.jpg\n[bm-with-hist]: ../files/brownian/hist.jpg\n\n[simple-bm-clean]: ../files/brownian/simple-brownian-clean.jpg\n[simple-bm-dist-clean]: ../files/brownian/simple-brownian-dist-clean.jpg\n[bm-with-hist-clean]: ../files/brownian/hist-clean.jpg\n[listing]: ../files/brownian/brownian.py\n"
},
{
"alpha_fraction": 0.8036959171295166,
"alphanum_fraction": 0.8195197582244873,
"avg_line_length": 58.84768295288086,
"blob_id": "36026e72653629a6b87b7ee82e97d3cc5240e3b8",
"content_id": "64833a78fb6f22b7936352a52913cfc4518c1629",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 9048,
"license_type": "permissive",
"max_line_length": 343,
"num_lines": 151,
"path": "/blog/_posts/2015-01-15-political-order-and-political-decay.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Political Order and Political Decay'\nsubheadline: 'Book Review'\nteaser: 'A masterful tome on the construction — and dismantlement — of modern democracy.'\nlayout: page\nauthor: David Kraemer\nbook_author: Francis Fukuyama\ndate: January 15, 2015\ncategories:\n - blog\ntags:\n - 'book reviews'\n - 'political theory'\n - 'political economy'\nauthor: David Kraemer\n---\n\n[*Political Order and Political Decay*][1], by Francis Fukuyama (September 30, 2014)\n\nIn a monumental work of political theory, Francis Fukuyama presents a\nclear and effective case regarding the nature of the modern state, its\ndevelopment, and its subsequent decay. In doing so, he provides a\nconsistent narrative for understanding fundamental differences between\nthe states we see today: what separates the efficient German civil\nservice from its middling American or outright corrupt Nigerian\ncontemporaries? Why has the rule of law become so readily adopted in\ncountries like Japan and South Korea but effectively rejected by China?\n\nThe modern state, Fukuyama argues, rests on three institutions:\neffective bureaucracy, rule of law, and democratic accountability. While\nintertwined, these institutions are at their essence independent of each\nother, and can thus mature at entirely different paces within a state.\nThe adoption of a merit-based and independent civil service allows a\nstate to administer public services and enforce the policies of the\nexecutive. Rule of law aims to constrain the political elite to the\nstatutes it demands others follow. This is in contrast to rule *by* law,\nin which the law serves as a tool to entrench the interests of the elite\nat the expense of the governed. Finally, democratic accountability\nrequires that channels exist through which the polity can direct the\npolicy and the policymakers of the state.\n\nThis motivates a narrative of development upon which Fukuyama expands\nthroughout the text. Germany, for example, developed a strong\nbureaucracy long before it adopted constitutionalism or modern forms of\naccountability. This bureaucracy evolved out of the established feudal\norder out of necessity: the autonomous and highly skilled Prussian army\nbecame so because the old system of patronage and nepotistic\nappointments severely hampered the ability of the military to win in its\nnumerous conflicts. It only slowly adopted the rule of law, and when it\ndid it served to mollify a restive working class. Democratic\naccountability, after the failures of the Weimar republic, took even\nlonger to develop. Yet because its state administrators remained strong\nand independent throughout the turmoil of world war, when the Allied\nstatebuilders began forging the Federal republic, they found a\nfunctioning bureaucracy with which they could administer policy.\n\nThus, by developing a strong civil service early, the German state\nenjoyed a high degree of legitimacy that contrasted with its\ncounterparts in Greece and the United States. Greece never enjoyed an\neffective administration, so the advent of democracy only nationalized a\nstrong distrust of the state and its meddlings; corruption and patronage\nremain ripe and has aggravated its economic crisis. The United States,\nby contrast, developed early on strong foundations of rule of law and\ndemocratic accountability. In fact, the Jacksonian America was the first\nto grant universal (non-slave) male suffrage in the West. But from an\nintrinsically American suspicion of the state and its reach, it took\ncenturies to develop a modern bureaucracy. The vacuum present in the\nmeanwhile essentially allowed America to reinvent clientalism on a\nmassive scale. Though America was eventually able to come to terms with\nan effective civil service, it took decades of political battles to do\nso, and the specter of corruption has never left.\n\nFukuyama also applies this theory to the development problems in Latin\nAmerica, Africa, and Asia. In the former two, colonialism played a\ndistinctive role in establishing the basis for the states present in\nthose regions today, though in profoundly different ways. Latin American\ncolonialism was characteristically extractive, that is, occupying\nEuropean powers sought to obtain and control resources for mercantilist\nends, requiring that they play an active role in governing the\nterritories they wished to exploit. This led to the development of\nstrong Latin American notions of state and, more importantly, of nation.\nWhen revolutionaries finally cast their occupiers out of their homes, a\nstrong bureaucratic system and state institutions favoring autocracy\nremained. Thus, the personalized dictatorships frequenting Mexico,\nBrazil, Argentina, and others can be explained from this perspective.\n\nSuch \"active\" colonialism was not present in Africa, in which the\nunderlying logic for territorial expansion by the European powers was\npredominantly strategic and balance-of-power oriented. Whereas the\nSpanish in Latin America created powerful Viceroyalties to oversee the\nextraction of resources and labor, the British and French took a more\nblasé approach to development in Africa. When the colonists left, after\nbouts of revolution, the weak civil services and state institutions they\nleft behind crumbled quickly, leaving a power vacuum waiting to be\nfilled by tribal strongmen and corrupt autocrats. The harsh colonial\nauthority which fused disparate Latin American tribes towards a\nconception of nationhood was also absent in Africa, leading to the\nfactitious rivalries of local spheres of political influence within\nstates, such as those in Nigeria, Sudan, and Libya today.\n\nAsian states were unique with respect to their contemporaries in that\nthe notion of statehood developed before the other Weberian notions of a\nstate—rule of law and accountability— took root. Fukuyama argues that\nthis is characteristic of societies in which the notion of\ntranscendental faith is absent: when the emperor is the symbol of order\nunder Heaven, the moral underpinnings needed for the rule of law to\ndevelop are much harder to justify. In China, the rule of law has never\ngenuinely been implemented, although this partly reflects philosophical\nobjections to explicit law presented by Confucianism. Its surrounding\nneighbors only really began to develop into the modern states present\ntoday at the behest of military necessity following the opening of the\nEast to Western powers. Thus, South Korea's and Japan's route to\nmodernization closely parallels that of Germany, in which a strong state\npredates a strong democratic pulse. This lends itself nicely to\nunderstanding why these two countries have become so successful so\nquickly in the postwar era.\n\nThe final parts of the book are spent dealing with the notion of\npolitical decay — characterized by the failure of institutions to comply\nto their designated roles within a state. Here one can easily sense\nFukuyama's frustration with American politics: Congress is too powerful\nfor executive authority to pursue responsive policy, but too weak to\nfend off the influence of political lobbyists. The American bureaucracy,\nwith some gems of autonomous administration such as the Federal Reserve\nand NASA, is weighed down by the scleroticism of other agencies like the\nFederal Trade Commission and the National Forestry Service (the latter\nof which experienced a regrettable decline in quality after its peak in\nthe first decades of the twentieth century) and by the exuberance of\nagencies like the National Security Agency. Fukuyama makes apt\nobservations regarding the inherent tendencies towards low-quality\n\"equilibria\" rooted in the checks and balances system placed into the\nConstitution. He is doubtful that the necessary reforms could be enacted\nfor an overhaul of this system, but believes that some modest changes\nmay do good in their stead. He makes a point of not delving into\nspecific policy recommendation, but he does offer a few worthy\nsuggestions from independent commissions deciding district borders to\nnixing the electoral college system.\n\n*Political Order and Political Decay* is a tome of significant breadth\nand depth. Historical considerations are insightful, and the\nimplications of the evolution of various states are made clear\nthroughout. Fukuyama also does an excellent job surveying the\nintellectual discourse surrounding these developmental topics, sifting\nthrough existing political theory and offering a compelling rationale\nfor or against them. Throughout, Fukuyama presents himself a centrist on\nthe divisive issues of development, a refreshing change from the\nacademic wars fought over democracy, capitalism, colonialism, and\ndevelopment. For anyone seriously concerned about the nature of\ndevelopment over the next century, this is a must read.\n\n[1]: http://www.amazon.com/Political-Order-Decay-Industrial-Globalization/dp/%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%200374227357/ref=sr_1_1?s=books&ie=UTF8&qid=1421356308&sr=1-1&keywords=political+order+%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20and+political+decay&pebp=1421356311291&peasin=374227357\n"
},
{
"alpha_fraction": 0.7727922797203064,
"alphanum_fraction": 0.792820930480957,
"avg_line_length": 52.034481048583984,
"blob_id": "3c866a6eef5c115ae0e193f1c72459f364ca9ab7",
"content_id": "d43170ce6c6b2cb3c5444078b509cc319602dad9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 7689,
"license_type": "permissive",
"max_line_length": 136,
"num_lines": 145,
"path": "/_drafts/us-recovery.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\nsubheadline: Economics\ntitle: \"The US Economy: A Review\"\nteaser: A review of the US economic recovery, from 2009 onwards.\ndate: July 22 2015\ncategories:\n - blog\ntags:\n - economics\n - data\nauthor: David Kraemer\n---\n\nSince 1947 the US has experienced 10 real recessions. The National Bureau of \nEconomic Research defines a recession as a period of sustained declining \neconomic activity, characterized by at least two consecutive quarters of \nnegative output growth. When I say \"real\" recession, I am considering negative \nreal output growth and not \"nominal\" output growth. The distinction is slight\nbut important. Nominal output reflects the total value of goods and services\nproduced in a given year, with the dollars of that year. This means that changes\nin the price level can in turn aggravate or mute underlying changes in output. To\nget around this issue, real output measures total activity in price-adjusted\nterms, often by fixing dollars to a specific year. This measure does a \nbetter job sifting the meaningful data from inflationary noise.\n\nIn practice does this distinction matter? I wasn't sure when I began playing\nwith the data. It turns out that by measuring output in real terms reveals\n10 recessions, while the same calculation in nominal terms yields 11. Which\nrecession is left out? Interestingly, the \"Dotcom\" bubble of the late 1990s\nand its ensuing market crash does not meet the criterion of a real recession,\nthough it is widely considered a nominal one.\n\n## Output growth\n\nSince 2009, when the most recent recession bottomed out, the macroeconomy has\ngrown at an average pace of 2.1% annually. This is a far cry from the average\nrecovery growth rate that the US has experienced in the past. Since 1947, over\nthe course of 10 recoveries, the US has averaged a growth rate of 4.2% in the\nfour years succeeding a recession trough. The gap between the current recovery\nand the sample mean is almost two full standard deviations wide. \n\n![][graph-1]\n\nWe're growing at half-speed compared to the average recovery. And the worst part about \nthis fact is that the growth deficit compounds relentlessly. To see why, consider\ntwo economies who both start out with $100. With an average growth rate of 2%,\nCountry A is sitting on $108 dollars after four years. Country B is at $117.\nBy the time that Country A has reached Country B's level of output in year four\n(which takes another four years), Country B has amassed a full $137.\n\nYet while the country's growth remains feeble, it also displays a remarkable\nresilience. I examined the distribution of growth rates in the 16 quarters \nfollowing each of the postwar recessions. The widths of the distributions are\nconsiderably wide, implying that while output growth on average has performed\nwell in the past, the growth rate at any given quarter in the recovery has been\nhistorically volatile.\n\nNot so for the 2009 recovery. Almost without exception, the economy has chugged\nalong contentedly at 2.1%. There are a few quarters that escape this trend, but\nmany of these outliers have been labelled extraneous by economists. Most of these\noutliers show slower growth due to [weather-related factors][art-1] (we have had some of\nthe wildest winters on record in the last few years).\n\n![][graph-2]\n\nMore surprisingly, the recovery has given no serious hints of ebbing. Almost \nlike clockwork, previous recoveries have lasted no more than five years before\nslipping back to recession. Since the 1990s, this recurrence has subsided however.\nBetween 1992 and 2007, growth was such a mainstay that a number of commentators\ndubbed the period the \"[Great Moderation][art-2],\" in which central bankers understood\nexactly how to turn the knobs of the economy to keep it up and running. The only\nhitch throughout those 15 years was the Dotcom bust, but as I mentioned earlier\nthe effects of the stock market crash on the macroeconomy was so minor that it\nfails the criterion for a real recession.\n\nThe Great Moderation is now a classic example of the dangers of economic hubris.\n\n## Unemployment\n\nOnly in a handful of circumstances before 2009 did the national unemployment\nrate top 10%. Of course, peak unemployment during the Great Depression was 25%,\na blight that thankfully has not returned since. Yet 10% is destructive in its \nown right. As an aggregate figure, it masks a good deal of tragedy. Women and \nminorities have found it particularly difficult to re-enter the workforce. Youth\nunemployment has remained stubbornly high. Though fears of a lost generation\nof millenials appear to be exaggerated, the experience has left a collective\nmark on people my age.\n\nThe unemployment rate represents the fraction of the labor force that is \nunemployed. In other words, \"unemployment\" only counts workers who are actively\nseeking a job, but cannot find one. This excludes the much trickier demographic\nof discouraged workers, who have given up searching for a job. Evidence suggests\nthat the ranks of this group are still abnormally swollen, though it is difficult\nto filter the structural costs of the recession from the swelling ranks of the\nbaby-boomer retirees (and of course, these two groups need not be disjoint). The\nBureau of Labor Statistics [estimates][bls] that in January 2015 the unemployment rate\nstood at 5.7% of the labor force; adding discouraged workers to the mix raises \nthat rate to 7% (depending on how you qualify \"discouraged workers\"). With \npart-time workers, who would otherwise choose to work full-time, the figure tops\n11%.\n\n![][graph-3]\n\nSince 2009 the unemployment rate has slowly but surely tapered down to 5.3% in July 2015,\nwhich brings it close to the Federal Reserve's estimate of the natural rate of\nunemployment. After 48 months of recovery, the average unemployment rate over \nthe 10 recessions has been 5.9% (6.3% excluding the outlier in 1947), whereas \nafter four years the 2009 recovery saw unemployment remain at a stubborn 7.5%.\nEven after excluding the 1947 outlier, which recorded a red-hot unemployment\nrate of 2.5% after four years, this last recovery remains outside of one \nstandard deviation from the mean.\n\nSome evidence suggests that this is a reflection of the high unemployment present\nat the recovery's onset. The annualized rate of change of unemployment over the \nfour years of recovery has been remarkably stable and not unlike the rates of\nthe previous recoveries. Like with output growth, the changes in unemployment\nsince 2009 have proven less volatile, though less modest in comparison to changes\nin prior recoveries. This points the conclusion that the high unemployment\nfour years on might simply be due to even higher unemployment at the recession's\ntrough.\n\n![Test][graph-4]\n\nThe return to growth and full employment following the 2009 recession has come\nsignificantly slower than in past recoveries. However, from the above data it\nis not obvious that the _quality_ of the recovery has altered in any fundamental\nway. That is, while growth has been unusually slow and labor market slack has \ntaken unusually long to tighten, it may be simply a slow and steady recovery. \nNothing so far has given cause to suggest that the character of the American\neconomy has changed.\n\n## Okun's Law \n\nFor the t\n\n[graph-1]: /blog/files/us-recovery/us-gdp-recovery.jpg\n[graph-2]: /blog/files/us-recovery/us-gdp-kde.jpg\n[graph-3]: /blog/files/us-recovery/us-unr-recovery.jpg\n[graph-4]: /blog/files/us-recovery/us-unr-kde.jpg\n\n[art-1]: http://www.economist.com/news/finance-and-economics/21653682-economists-debate-meaning-contraction-first-quarter-blip-or-blight\n[art-2]: https://en.wikipedia.org/wiki/Great_Moderation\n\n[bls]: http://www.bls.gov/lau/stalt.htm"
},
{
"alpha_fraction": 0.6117647290229797,
"alphanum_fraction": 0.6399999856948853,
"avg_line_length": 20.25,
"blob_id": "2209afb3a8ac109991f4071cb1602bdef9372592",
"content_id": "5a903e969c8ba26918f3e32c05a686c84937500c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 425,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 20,
"path": "/courses/index.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Courses\"\nAuthor: \"David Kraemer\"\nlayout: page\nshow_meta: false\npermalink: courses/\n---\n\nHere are a list of current and previous courses taught through Grinnell\nCollege's Experimental College (ExCo) program.\n\n## Past Courses\n\n| **Date** | **Course Title** |\n|:-----|:-------------|\n| Fall 2014 | [Professional Typesetting with \\\\(\\LaTeX\\\\)][1] |\n| Spring 2015 | [Data Analysis with Python][2] |\n\n[1]: latex/\n[2]: python/\n"
},
{
"alpha_fraction": 0.792873740196228,
"alphanum_fraction": 0.7996901869773865,
"avg_line_length": 52.79166793823242,
"blob_id": "3f542362e44fd045d3ff3aab8fd1ed906bfc9fbb",
"content_id": "1fed9f873574296d9e1cdc096f63f7e63e384fed",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6463,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 120,
"path": "/blog/_posts/2015-01-18-unhappy-union.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: 'Unhappy Union'\nsubheadline: 'Book Review'\nteaser: 'Two journalists detail the hubris and tragedy of the Euro crisis.'\nlayout: page\nauthor: David Kraemer\nbook_author: \"John Peet, Anton La Guardia\"\ndate: January 18, 2015\ncategories:\n - blog\ntags: \n - 'Economist'\n - 'book reviews'\n - 'Euro crisis'\n - 'political economy'\nauthor: David Kraemer\n---\n\n[*Unhappy Union: How the euro crisis – and Europe – can be fixed*][1], by John Peet and Anton La Guardia (June 24, 2014)\n\nThe Euro crisis is by no means over. With populist parties featuring\nextremes of both Left and Right gaining political ground across the\nUnited Kingdom and the Continent, the threat of institutional decay and\ndissolution is real. And as of the writing of this post, the Leftist\nSyriza party is [the leading party in parliamentary elections in Greece][2],\nthreatening to resurrect the tumultuous months surrounding the 2010\nbailout.\n\nA great deal of work has been done to disentangle the mess that led to\nthe Euro crisis, including one book which I [previously reviewed][3]\non this blog. *Unhappy Union*, jointly written by John Peet and Anton La\nGuardia, is a useful addition to this mix. The authors share a great\ndeal of insight from the events surrounding the crisis, which are on\ngood display in this text.\n\nThe general diagnosis of Europe's woes is sound: Greek public sector\nprofligacy (and in many instances, downright fraud) combined with a\nreversal of economic convergence between the German-led north and the\nEuro zone periphery planted the explosives, and the global recession and\nhousing collapse beset by the American financial crisis provided a\nparticularly powerful spark. Given this, the surprise of the Greek\nsovereign-debt crisis was not its massive scope, but rather that it had\nnot occurred before.\n\nAs Mr. Peet and Mr. La Guardia point out, correctly, Europe's leaders\nmisdiagnosed Greece's solvency crisis for a liquidity one. In the\nlatter, the problem is that a sovereign cannot quickly enough transfer\nits assets into cash to fund its outstanding liabilities; in the former,\nthe sovereign simply does not have sufficient assets to start. This\nmistake, in which the IMF partook, proved deadly, as the first bailout\nprogram failed to end the crisis in Greece and moreover allowed the\ncontagion to spread to otherwise responsible members.\n\nThe authors go to great pains to recreate the decision making process\naround the crisis, paying close attention to rival institutional blocs\nlike the inflation-hating Bundesbank and the subsidiary-minded\nperipheral leaders. They also reconstruct the critical relationship\nbetween German chancellor Angela Merkel and French president Nicolas\nSarkozy and its role in shaping the crisis' policy. The so-called\n\"Merkozy\" duo crafted the contingency plans for a Greek withdrawal from\nthe Euro and the avenues through which such a Grexit might be avoided in\nisolation from other players. Merkozy were also responsible for the\npressure to ouster foreign heads of government like George Papandreou\nand Silvio Berlusconi in the midst of the crisis.\n\nDue consideration of the role of the European Central Bank and its\ncrisis — Jean-Claude Trichet and Mario Draghi — is also given. On whole,\nMr. Peet and Mr. La Guardia are more forgiving of Mr. Trichet than\nPhillipe Legrain was in *European Spring*, though the jury is still out\non that debate, in my opinion. Certainly, Trichet as president of the\nECB before the crisis ought to have seen it approaching, though the same\ncriticism can be levied at Ben Bernanke at the Federal Reserve.\nUltimately, history's final assessment of the central bankers' of the\ncrisis may put less weight on their respective divination abilities than\ntheir crisis-management prowess. Here, even Trichet with his push for\nexpansionary policy will be seen favorably.\n\nOne important question answered unsatisfactorily in *Unhappy Union*\nconcerns why economic divergence between Germany and the periphery has\nbecome a hard reality in the last decade. Here, the authors simply pass\nof Greece and Co.'s woes as the result of a failure to implement\nparallel labor market reforms with Germany to improve the\n\"competitiveness\" of their countries. While this is certainly true, a\nbetter answer would have considered both the motivations for and\nconsequences of flexible labor markets in a currency union, and whether\nGermany's export machine built from high-skilled manufacturing is a\nworthwhile model to replicate in the south. *The Economist*, for whom\nboth authors write, has begun to add doubt to this idea.\n\nWhether German economic policy amounts to mere modern mercantilism that\nis unsustainable to export remains to be seen. The only other criticism\nI have of the authors' analysis is their tendency not to get their hands\ndirty with policy when it is clear that they have much valuable insight\nto offer. I would have liked a more detailed description of their\nproposed banking union, from the joint Eurobonds they argue to create to\nthe new roles a continental financial supervisor ECB must undertake. Yet\nthese are minor complaints, owing to the overall high-quality reasoning\nbehind the policy prescriptions they support.\n\nThe other topic discussed in *Unhappy Union*, and one of the authors'\nstrengths, concerns the political ramifications of the crisis, from the\nrise of populism to the failure of a federalism model to become a\nserious contender for future integration. The authors stand firmly, and\nin my opinion rightly, in the federalist camp, favoring some sort of\nsupranational authority to raise revenue in order (for example) to issue\njoint-Eurobonds with less moral hazard. Federalism might also solve the\nproblems of democratic legitimacy, espoused by the growing power of\nunelected technocrats to dictate policy decisions for the continent.\n\nThey also fret quite reasonably that European disunity harms its image\nabroad and more importantly its political clout against an increasingly\nczarist Russia. The messy affair with Ukraine last (and this) year\nserves as a potent reminder of the inherent weakness of a political\nunion which fails to rally around its basic ideals, such as the respect\nof human rights and national sovereignty (the irony here is noted). All\nconsidered, this is a concise, worthy read for those concerned with the\nfuture of the Union.\n\n[1]: http://www.amazon.com/Unhappy-Union-crisis-Europe-Economist/dp/1610394496\n[2]: http://www.wsj.com/articles/greeces-syriza-leads-in-polls-as-general-election-looms-1421592527\n[3]: ~kraemerd17/blog/european-spring\n"
},
{
"alpha_fraction": 0.5719940662384033,
"alphanum_fraction": 0.6185057163238525,
"avg_line_length": 35.05356979370117,
"blob_id": "da441fc694ddb0a71e711c87cda1520ce1dae8e9",
"content_id": "0821531e7c931f8c9b17f99bdb5515f61b90faec",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2021,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 56,
"path": "/courses/latex/material.md",
"repo_name": "kraemerd17/webpage",
"src_encoding": "UTF-8",
"text": "---\ntitle: Course Material\nsuppress-title: false\nauthor: David Kraemer & Caleb Leedy\ndate: March 01, 2015 \nlayout: page\nshow_meta: false\nsidebar: right\nsidebar-title: Course Links\nsidebar-content: |\n <ul> \n <li> <a href=\"../\">Main page</a> </li> \n <li> <a href=\"https://en.wikibooks.org/wiki/LaTeX\">Wikibooks page</a> </li>\n <li> <a href=\"latex-wikibook.pdf\">Wikibooks PDF</a> </li>\n <li> <a href=\"http://www.xm1math.net/texmaker/download.html\">TexMaker</a> </li>\n <li> <a href=\"http://www.sharelatex.com\">ShareLaTeX</a> </li>\n <li> <a href=\"http://www.overleaf.com\">Overleaf</a> </li>\n </ul>\n\n <h3> Useful Links </h3>\n <ul>\n <li> <a href=\"http://faculty.cbu.ca/srodney/ShortSymbInd.pdf\">Big list of math symbols</a> </li> \t\n <li> <a href=\"http://detexify.kirelabs.org/classify.html\">Detexify</a> </li> \t\n <li> <a href=\"http://tex.stackexchange.com/\">LaTeX StackExchange</a> </li> \t\n <li> <a href=\"http://www.latextemplates.com/\">Free templates</a> </li> \t\n <li> <a href=\"https://www.sharelatex.com/learn\">ShareLaTeX written guides</a> </li> \t\n <li> <a href=\"https://www.youtube.com/user/ShareLaTeX/playlists\">ShareLaTeX Youtube channel</a> </li> \t\n </ul>\npermalink: courses/latex/material/\n...\n\nEach week's lecture slides (produced using Beamer) are given in the table below.\n\n<!-- <center> -->\n\n| | Lecture | Date |\n|-------|:--------|-----:|\n|1|[Introduction and Installation][1]|October 9 2014|\n|2|[Math Mode, Environments, and Commands][2]|October 16 2014|\n|3|[Document Structure][3]|October 30 2014|\n|4|[Packages and the Header][4]|November 6 2014|\n|5|[Graphics Integration][5]|November 13 2014|\n|6|[Building a Resume][6]|November 27 2014|\n|7|[BibLaTeX][7]|December 4 2015|\n|8|[Beamer Presentations][8]|December 11 2015|\n\n<!-- </center> -->\n\n[1]: lecture-01.pdf\n[2]: lecture-02.pdf\n[3]: lecture-03.pdf\n[4]: lecture-04.pdf\n[5]: lecture-05.pdf\n[6]: lecture-06.pdf\n[7]: lecture-07.pdf\n[8]: lecture-08.pdf\n\n\n"
}
] | 29 |
franklinobasy/VoiceToText_App | https://github.com/franklinobasy/VoiceToText_App | e103359b8378b2d55da8f1b9dcda8643beae26e1 | cf1fcd2e79ef8daf1bfb992b15651181281ce331 | aa5d04a02021490623c5afb5f968ea0603a4824a | refs/heads/master | 2023-05-06T16:58:16.809844 | 2021-05-27T11:04:54 | 2021-05-27T11:04:54 | 371,343,027 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6340956091880798,
"alphanum_fraction": 0.6403326392173767,
"avg_line_length": 19.95652198791504,
"blob_id": "85baa6bf6ee868f96591126e6fbbdebd1ce87fb7",
"content_id": "17cddcfe33bd77a3f61873d498d6b35210aa2e26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 23,
"path": "/Voice2Text/main.py",
"repo_name": "franklinobasy/VoiceToText_App",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom PyQt5.QtWidgets import QApplication\n\nfrom .views import Window\ndef main():\n '''App main's function'''\n #load style sheet\n with open('Voice2Text/stylesheet.css') as file:\n stylesheet = file.read()\n file.close()\n # create the application\n app = QApplication(sys.argv)\n app.setStyleSheet(stylesheet)\n\n # create window\n window = Window()\n window.show()\n\n #Run the event loop\n sys.exit(app.exec())"
},
{
"alpha_fraction": 0.6691176295280457,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 23.81818199157715,
"blob_id": "28426a004b583b3732e650bedce43321fdaa1045",
"content_id": "41f5a3f674a3f1970da34f58355cbf5bc587a240",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 272,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 11,
"path": "/Voice2Text/properties.py",
"repo_name": "franklinobasy/VoiceToText_App",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*- \n\n'''This module contain all properties of the app'''\n\nTITLE = 'Voice-to-Text App'\nWINDOW_WIDTH = 400\nWINDOW_HEIGHT = 500\n\nred_image = 'Voice2Text/images/red.png'\nblue_image = 'Voice2Text/images/blue.png'\ngreen_image = 'Voice2Text/images/green.png'"
},
{
"alpha_fraction": 0.5988296270370483,
"alphanum_fraction": 0.6077698469161987,
"avg_line_length": 30.608247756958008,
"blob_id": "4108fb244eb65bea57f00bdf9e0b1338af8ae497",
"content_id": "e6050adf8969b86b454b7341dd6a4b292af5a8f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6152,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 194,
"path": "/Voice2Text/views.py",
"repo_name": "franklinobasy/VoiceToText_App",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n'''This module provides views for app'''\nimport speech_recognition as sr\n\nfrom PyQt5.QtCore import (\n Qt, \n QSize, \n QThread,\n pyqtSignal\n)\n\nfrom PyQt5.QtWidgets import (\n QFileDialog,\n QGroupBox,\n QHBoxLayout,\n QLabel,\n QLineEdit,\n QMainWindow,\n QMessageBox,\n QPushButton, \n QVBoxLayout,\n QWidget,\n)\nfrom PyQt5.QtGui import (\n QPixmap, \n QIcon\n)\n\nfrom .properties import *\n\nclass Window(QMainWindow):\n ''' The Main Window '''\n def __init__(self, parent = None):\n super().__init__(parent)\n self.setWindowTitle(TITLE)\n self.resize(WINDOW_WIDTH, WINDOW_HEIGHT)\n self.centralWidget = QWidget()\n self.setCentralWidget(self.centralWidget)\n self.layout = QVBoxLayout()\n self.centralWidget.setLayout(self.layout)\n\n self.status = \"Inactive\"\n\n self.setUpUi()\n \n def setUpUi(self):\n self.text_output = TextOutput(self)\n self.listen_button = ListenButton(self, self.text_output)\n self.audio_read = ReadAudio(self, self.text_output)\n \n\n self.layout.addWidget(self.listen_button, alignment= Qt.AlignCenter, )\n self.layout.addStretch()\n self.layout.addWidget(self.audio_read, alignment= Qt.AlignLeft)\n self.layout.addWidget(self.text_output, alignment= Qt.AlignCenter, )\n \n\nclass ListenButton(QPushButton):\n def __init__(self, parent= None, label_object = None):\n super().__init__(parent)\n \n self.pixmap = QPixmap(blue_image)\n self.parent = parent\n self.label_object = label_object\n\n self.setMinimumHeight(200)\n self.setMinimumWidth(200)\n self.setIcon(QIcon(self.pixmap))\n self.setIconSize(QSize(200, 200))\n self.setMouseTracking(True)\n self.clicked.connect(self.press)\n self.setObjectName('Listen')\n \n def leaveEvent(self, event):\n self.setIconSize(QSize(200, 200))\n\n def enterEvent(self, event):\n self.setIconSize(QSize(225, 225))\n \n def press(self):\n if self.parent.status == 'OFF':\n self.parent.status = 'ON'\n self.pixmap = QPixmap(green_image)\n elif self.parent.status == 'ON':\n self.parent.status = 'OFF'\n self.pixmap = QPixmap(red_image)\n elif self.parent.status == 'Inactive':\n self.parent.status = 'ON'\n self.pixmap = QPixmap(green_image)\n \n self.setIcon(QIcon(self.pixmap))\n self.label_object.setText(f'>>>& STATUS : {self.parent.status}')\n print(self.parent.status)\n \n\nclass TextOutput(QLabel):\n def __init__(self, parent= None):\n super().__init__(parent)\n\n self.setMinimumHeight(100)\n self.setMinimumWidth(WINDOW_WIDTH)\n self.setObjectName('TextOut')\n self.setText(f'>>>& STATUS : {parent.status}')\n self.setAlignment(Qt.AlignLeft | Qt.AlignTop)\n self.setWordWrap(True)\n\n\nclass ReadAudio(QGroupBox):\n def __init__(self, parent= None, label_object= None):\n super().__init__(parent)\n self.setObjectName('AudioContainer')\n self.label_object = label_object\n\n self.setMinimumHeight(60)\n self.setMinimumWidth(WINDOW_WIDTH)\n\n self.initialize_elements()\n\n def initialize_elements(self):\n button = QPushButton('input audio')\n go_button = QPushButton(' Go ')\n self.path = QLineEdit()\n layout = QHBoxLayout()\n\n button.resize(12, 4)\n button.setObjectName('AudioButton')\n button.clicked.connect(self.openAudio)\n button.setToolTip('Click here to choose audio from local directory')\n\n go_button.resize(12, 4)\n go_button.setMinimumWidth(12)\n go_button.setObjectName('AudioButton')\n go_button.clicked.connect(self.startReadAudioFile)\n go_button.setToolTip('Convert audio to text')\n\n self.path.resize(250, 20)\n self.path.setMinimumWidth(250)\n self.path.setObjectName('AudioButton')\n self.path.setPlaceholderText('Type file path here...')\n\n layout.addWidget(button, alignment= Qt.AlignLeft)\n layout.addWidget(self.path, alignment=Qt.AlignCenter)\n layout.addWidget(go_button, alignment= Qt.AlignRight)\n\n self.setLayout(layout)\n \n def openAudio(self):\n file_name, _ = QFileDialog.getOpenFileName(self, \"Open File\", \"\", \"WAV Files (*.wav)\")\n if file_name:\n self.path.setText(file_name)\n else:\n QMessageBox.information(self, 'Error', 'Unable to find file, try again!', QMessageBox.Ok)\n \n def startReadAudioFile(self):\n file_path = self.path.text()\n try:\n if not file_path:\n QMessageBox.information(self, 'Error', 'Must enter a file path', QMessageBox.Ok)\n self.path.setFocus()\n else:\n self.label_object.setText('>>> TRANSLATING...')\n self.worker = AudioReadingThread(file_path)\n self.worker.readAudioSignal.connect(self.displayReadAudioFile)\n self.worker.start()\n except sr.RequestError:\n QMessageBox.information(self, 'Error', 'Internet Connection problem, \\nEnsure You have a stable internet connection', QMessageBox.Ok)\n \n def displayReadAudioFile(self, output):\n self.label_object.setText(output)\n\n\nclass AudioReadingThread(QThread):\n readAudioSignal = pyqtSignal(str)\n\n def __init__(self, file_path):\n super().__init__()\n self.file_path = file_path\n\n def run(self):\n r = sr.Recognizer()\n audio_file = sr.AudioFile(self.file_path)\n with audio_file as source:\n r.adjust_for_ambient_noise(source, duration=0.5)\n audio = r.record(source)\n text = r.recognize_google(audio)\n # output = r.recognize_google(audio, show_all=True)\n # output = list(output.values())[0]\n # text = ''\n # for item in output:\n # item = str(item)\n # item = item[16:-2]\n # text = text + str(item) + '\\n'\n self.readAudioSignal.emit(text)\n \n \n\n\n"
}
] | 3 |
mstoure/LE-TULSI-PEI | https://github.com/mstoure/LE-TULSI-PEI | d09b3a302536bbb0e1318649e64fce39857dc573 | 55800387c8413bf193bfd1648aa148363abc90d6 | 59452f84b3f761ca8708e873d98a7556f98b9a52 | refs/heads/master | 2023-05-30T12:27:08.416201 | 2021-06-16T01:10:19 | 2021-06-16T01:10:19 | 377,324,394 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7318840622901917,
"alphanum_fraction": 0.7318840622901917,
"avg_line_length": 22,
"blob_id": "d3b6b6b2331b2fee60b495ffe751ea61c52ad023",
"content_id": "20b54890c8f9c8f31ada7b8ac88f4f2972fdd5b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 6,
"path": "/peï/apps.py",
"repo_name": "mstoure/LE-TULSI-PEI",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\n\n\nclass PeïConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'peï'\n"
},
{
"alpha_fraction": 0.7352941036224365,
"alphanum_fraction": 0.7352941036224365,
"avg_line_length": 21.83333396911621,
"blob_id": "0ac92f0d2fe678432278483898066c230ed4be53",
"content_id": "6742ebe88a9597f184f7e5b1f67c22dcb4f4be6b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 137,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 6,
"path": "/peï/views.py",
"repo_name": "mstoure/LE-TULSI-PEI",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\n\n# Create your views here.\n\ndef onepage(request):\n return render(request, 'peï/onepage.html', {})"
}
] | 2 |
tramee/flaskapp | https://github.com/tramee/flaskapp | a36c27a39a073e64de28726de65d2a68a411fc07 | cde8ac743e6aed337f808d0ce36048d130bef334 | 2e408f1aeaa6e86bf7b09e4a0562e27cad1ede48 | refs/heads/master | 2021-01-20T11:14:30.051126 | 2017-03-05T11:09:44 | 2017-03-05T11:09:44 | 83,945,169 | 0 | 1 | null | 2017-03-05T04:39:43 | 2017-03-05T04:55:03 | 2017-03-05T11:10:24 | Python | [
{
"alpha_fraction": 0.5731261372566223,
"alphanum_fraction": 0.5831809639930725,
"avg_line_length": 27.05128288269043,
"blob_id": "9dcc9d99e0e889a0b26c7331be8ddb739850209f",
"content_id": "4f99f2156ae9af6900be189a70281860eee9b422",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1094,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 39,
"path": "/static/roller.js",
"repo_name": "tramee/flaskapp",
"src_encoding": "UTF-8",
"text": "function upload_roller(){\n $.getJSON($SCRIPT_ROOT + '/rollers/_add_roller', {\n\trol_id: $('div[name=\"rol_id\"]')[0].innerText,\n\ttype: $('div[name=\"type\"]')[0].innerText,\n\tmnfr: $('div[name=\"mnfr\"]')[0].innerText,\n\tpart_number: $('div[name=\"p_n\"]')[0].innerText,\n\tbearing: $('div[name=\"bear\"]')[0].innerText,\n\tsealing: $('div[name=\"cont\"]')[0].innerText\n }, function(data) {\n\t// console.log(data)\n\tif (data.Status === 'SUCCESS') {\n\t window.location.reload();\n\t}\n });\n}\n\nfunction new_event(){\n $.getJSON($SCRIPT_ROOT + '/history/_add_event', {\n\tdate_string: $('input[name=\"date_string\"]')[0].value,\n\trol_id: $('select[name=\"r_id\"]')[0].value,\n\trig_name: $('select[name=\"rig_name\"]')[0].value,\n\tst_id: $('div[name=\"st_id\"]')[0].innerText,\n\taction: $('div[name=\"action\"]')[0].innerText\n }, function(data) {\n\t// console.log(data)\n\tif (data.Status === 'SUCCESS') {\n\t window.location.reload();\n\t}\n });\n}\n\nfunction update_history(_var){\n console.log(_var)\n $.getJSON($SCRIPT_ROOT + '/history', {\n\trig_id: _var.value,\n }, function() {\n\twindow.location.reload();\n });\n}\n"
},
{
"alpha_fraction": 0.681506872177124,
"alphanum_fraction": 0.681506872177124,
"avg_line_length": 16.25,
"blob_id": "991d073fec3c2c9b779dcbb615d157a3f6b2bcbf",
"content_id": "a5be90c7bf79b5b96ec890df9ccc3e4738c1e9d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 16,
"path": "/README.md",
"repo_name": "tramee/flaskapp",
"src_encoding": "UTF-8",
"text": "# First Flask App\r\n\r\n## Goal\r\n\r\nProvide a first implementaion of:\r\n* Flask\r\n* Pandas\r\n* Bokeh\r\n\r\nThis app renders CSV data into an HTML page using Bokey\r\n\r\n## Features\r\nThis app (will) provide:\r\n* TODO - Data visualization;\r\n* TODO - Report generation;\r\n* TODO - Sending graphs to the user.\r\n"
},
{
"alpha_fraction": 0.4752252399921417,
"alphanum_fraction": 0.4797297418117523,
"avg_line_length": 19.136363983154297,
"blob_id": "b912dca3b3cda12c4af10657188ce4d4feb266e7",
"content_id": "e4719d09490a481a6b6688f46666d1620d30f225",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 444,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 22,
"path": "/templates/form.html",
"repo_name": "tramee/flaskapp",
"src_encoding": "UTF-8",
"text": "<html>\n <head>\n <title>wtf form test</title>\n </head>\n <body>\n <h1> First test with WTF forms on Flask </h1>\n <form method=\"POST\">\n {{ form.csrf_token }}\n <p>\n\t{% for option in form.answer %}\n\t {{ option }} {{ option.label }}<br>\n\t{% endfor %}\n </p>\n <p>\n\t{% for option in form.other %}\n\t {{ option }} {{ option.label }}<br>\n\t{% endfor %}\n </p>\n {{ form.submit }}\n </form>\n </body>\n</html>\n\n"
},
{
"alpha_fraction": 0.5858662724494934,
"alphanum_fraction": 0.5927051901817322,
"avg_line_length": 24.038461685180664,
"blob_id": "04d19aa4b7373cc267a491da332286c557fd5cef",
"content_id": "7f357a9f5150a1f6762c8d220a96fe957a67d4d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1316,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 52,
"path": "/__init__.py",
"repo_name": "tramee/flaskapp",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, redirect, url_for\nfrom os import urandom\nfrom module1 import *\n\n\napp = Flask(__name__)\napp.config['CSRF_ENABLED'] = True\n\[email protected]('/')\ndef homepage():\n return 'Site in construction; come again soon.'\n\[email protected]('/result/')\ndef result():\n return render_template('result.html')\n\[email protected]('/rollers/')\ndef rollers_summary():\n return render_template('rollers.html',roller=None)\n\[email protected]('/rollers/<int:r_id>')\ndef rollers(r_id):\n if r_id not in [24, 25]:\n r_id = None\n return render_template('rollers.html',roller=r_id)\n\[email protected]('/form/', methods=['GET','POST'])\ndef renderForm():\n form = testForm()\n status = False\n if form.is_submitted():\n print \"submitted\"\n if form.validate():\n print \"valid\"\n status = True\n else:\n print (form.errors)\n\n if status:\n # status = {'status': 'SUCCESS',\n # 'answer': form.answer.data,\n # 'other': form.other.data}\n return redirect(url_for('result'))\n try: \n return render_template('form.html', form=form)\n except Exception as e:\n return str(e)\n \nif __name__ == '__main__':\n app.run(debug=True)\n #app.run(ssl_context=context)\n #app.run(host='0.0.0.0', ssl_context=context)\n \n \n"
},
{
"alpha_fraction": 0.5694444179534912,
"alphanum_fraction": 0.5777778029441833,
"avg_line_length": 38.88888931274414,
"blob_id": "2eb2b9b0dd14265feb8918a0cef9503d28f7d981",
"content_id": "2d8c2d3e9ddb422664a0ce4d921be356ae1c0b4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 360,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 9,
"path": "/module1.py",
"repo_name": "tramee/flaskapp",
"src_encoding": "UTF-8",
"text": "from flask_wtf import FlaskForm\nfrom wtforms.fields import RadioField, SubmitField\n\nclass testForm(FlaskForm):\n answer =RadioField('First field',\n choices=[('yes','Yes'),('no','No')])\n other = RadioField('Second field',\n choices=[('1','Pink'),('2','Blue'),('3','Black')])\n submit = SubmitField('Submit')\n\n"
}
] | 5 |
frhana/tugas-akhir | https://github.com/frhana/tugas-akhir | 9978ac4a3cd3fb05b4ae6912c90006884bdf0b86 | c578bf3ce75f3e82c67f7d1c8c8ce72c3466e23a | 45f7f34d40e7af412a2c95ee795ee08bb5879b18 | refs/heads/main | 2023-01-14T03:39:51.747435 | 2020-11-18T14:40:52 | 2020-11-18T14:40:52 | 312,291,985 | 1 | 1 | CC0-1.0 | 2020-11-12T13:54:58 | 2020-11-18T14:40:56 | 2020-11-18T14:41:05 | Python | [
{
"alpha_fraction": 0.43842729926109314,
"alphanum_fraction": 0.4621661603450775,
"avg_line_length": 30.878047943115234,
"blob_id": "b96626dc5b319f27662567c881bfd03f66e9bb30",
"content_id": "8b732c558ee48eb738ff7983adcc369d9002971d",
"detected_licenses": [
"CC0-1.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1348,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 41,
"path": "/Tugas_Akhir.py",
"repo_name": "frhana/tugas-akhir",
"src_encoding": "UTF-8",
"text": "print(\"RENTAL MOBIL ABCD\")\r\n\r\nprint(\"-------------------------------\")\r\n\r\n#Input\r\nnama = input(\"Masukkan Nama Anda : \")\r\numur = int(input(\"Masukkan Umur Anda : \"))\r\n\r\nif umur < 18:\r\n print(\"Maaf\", nama, \"anda belum bisa meminjam kendaraan\")\r\nelse:\r\n ktp = int(input(\"Masukkan Nomor KTP Anda : \"))\r\n k_mobil = input(\"Kategori Mobil [4/6/8 orang] : \")\r\n if k_mobil == \"4\" :\r\n kapasitasmobil = \"4 orang\"\r\n harga = 300000\r\n elif k_mobil == \"6\" :\r\n kapasitasmobil = \"6 orang\"\r\n harga = 350000\r\n else:\r\n kapasitasmobil = \"8 orang\"\r\n harga = 500000\r\n jam = int(input(\"Masukkan Durasi Peminjaman (dalam hari): \"))\r\n if jam > 6:\r\n diskon = (jam*harga)*0.1\r\n else:\r\n diskon = 0\r\n\r\n total = (jam*harga)\r\n\r\n print(\"-------------------------------\")\r\n print(\"RENTAL MOBIL ABCD\")\r\n print(\"-------------------------------\")\r\n print(\"Masukkan Nama Anda : \"+str(nama))\r\n print(\"Masukkan Umur Anda : \"+str(umur))\r\n print(\"Masukkan Nomor KTP Anda : \"+str(ktp))\r\n print(\"Kapasitas Mobil : \"+str(k_mobil))\r\n print(\"Harga : \",+(harga))\r\n print(\"Potongan yang didapat : \",+(diskon))\r\n print(\"-------------------------------\")\r\n print(\"Total Bayar : \",+(total))\r\n"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 11,
"blob_id": "cf7062e9a746e17494b19f42a5b357c336eafdec",
"content_id": "0e6c9e0681b6fbe5b29ae1dd7bda73c3e072ed47",
"detected_licenses": [
"CC0-1.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 24,
"license_type": "permissive",
"max_line_length": 13,
"num_lines": 2,
"path": "/README.md",
"repo_name": "frhana/tugas-akhir",
"src_encoding": "UTF-8",
"text": "# tugas-akhir\nTugas DPG\n"
}
] | 2 |
haluk/bayes | https://github.com/haluk/bayes | 6032c04a9e198a67f18b38bced349a754e1e132b | 9267d3415c91fdd466184e3b7f1d331a538999d3 | 32637f89174a4af6d2f77ed6b38c8ceb23054169 | refs/heads/master | 2016-08-04T08:19:17.613004 | 2015-03-20T17:57:42 | 2015-03-20T17:57:42 | 32,562,670 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7127071619033813,
"alphanum_fraction": 0.72444748878479,
"avg_line_length": 31.155555725097656,
"blob_id": "0410d63a8dde159131b613570f05e00cad022b42",
"content_id": "5ddcff7a4257f1544620d3166ffa78417244abb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 1448,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 45,
"path": "/src/CMakeLists.txt",
"repo_name": "haluk/bayes",
"src_encoding": "UTF-8",
"text": "project(BNP)\ncmake_minimum_required(VERSION 2.8)\n\ninclude(CheckCXXCompilerFlag)\nCHECK_CXX_COMPILER_FLAG(\"-std=c++11\" COMPILER_SUPPORTS_CXX11)\nCHECK_CXX_COMPILER_FLAG(\"-std=c++0x\" COMPILER_SUPPORTS_CXX0X)\nif(COMPILER_SUPPORTS_CXX11)\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\nelseif(COMPILER_SUPPORTS_CXX0X)\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++0x\")\nelse()\n message(STATUS \"The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.\")\nendif()\n\n# do not forget to change this line if needed (\"act install -d...\")\nset(AGRUM_INSTALLATION_DIRECTORY \"/Users/hd/usr\")\nset(aGrUM_DIR \"${AGRUM_INSTALLATION_DIRECTORY}/lib/cmake/aGrUM/\")\n\nfind_package(aGrUM)\n\nif (aGrUM_FOUND)\n include_directories(${AGRUM_INCLUDE_DIR})\n link_directories(${AGRUM_LIB_DIR})\nelse (aGrUM_FOUND)\n message(FATAL_ERROR \"Please install aGrUM\")\nendif (aGrUM_FOUND)\n\n# cmake -DCMAKE_BUILD_TYPE=DEBUG\n# or\n# cmake -DCMAKE_BUILD_TYPE=RELEASE\n# RELEASE is the default option (thanks to the next 3 lines)\nif( NOT CMAKE_BUILD_TYPE )\n set( CMAKE_BUILD_TYPE Release)\nendif()\n\nfile(GLOB_RECURSE BNP_SOURCE ${BNP_SOURCE_DIR}/*.cpp)\nfile(GLOB_RECURSE BNP_INCLUDE ${BNP_SOURCE_DIR}/*.h)\n\nadd_executable (bnp ${BNP_SOURCE})\n\nif ($CMAKE_BUILD_TYPE STREQUAL \"RELEASE\") # release : act install release\n target_link_libraries(bnp agrum)\nelse() # debug : act install debug\n target_link_libraries(bnp agrum-dbg)\nendif()\n\n"
},
{
"alpha_fraction": 0.5795763731002808,
"alphanum_fraction": 0.5915279984474182,
"avg_line_length": 33.25388717651367,
"blob_id": "7ba921ca08a6715d3eb852dbd3bac58c52e7eaf3",
"content_id": "af2c4e2ce2498132ab369f06be05a9a753d27ad6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6610,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 193,
"path": "/src/app.cpp",
"repo_name": "haluk/bayes",
"src_encoding": "UTF-8",
"text": "/* \n* @Author: hd\n* @Date: 2015-02-28 14:20:39\n* @Last Modified by: hd\n* @Last Modified time: 2015-03-20 01:53:03\n*/\n\n#define GUM_TRACE_ON\n\n#include <iostream>\n#include <random>\n#include <agrum/BN/BayesNet.h>\n\n#include <agrum/learning/database/databaseVectInRAM.h>\n#include <agrum/learning/database/databaseFromCSV.h>\n\n#include <agrum/learning/database/DBCellTranslators/cellTranslatorCompactIntId.h>\n\n#include <agrum/learning/database/filteredRowGenerators/rowGeneratorIdentity.h>\n\n#include <agrum/learning/scores_and_tests/scoreBDeu.h>\n\n#include <agrum/learning/aprioris/aprioriSmoothing.h>\n\n#include <agrum/learning/constraints/structuralConstraintDiGraph.h>\n#include <agrum/learning/constraints/structuralConstraintDAG.h>\n\n#include <agrum/learning/structureUtils/graphChangesSelector4DiGraph.h>\n#include <agrum/learning/structureUtils/graphChangesGenerator4DiGraph.h>\n\n#include <agrum/learning/paramUtils/paramEstimatorML.h>\n#include <agrum/learning/greedyHillClimbing.h>\n\n#include <agrum/BN/inference/GibbsInference.h>\n#include <agrum/BN/inference/lazyPropagation.h>\n\n#include \"spdlog/spdlog.h\"\n\nusing namespace std;\nusing namespace gum::learning;\n\n\nstd::vector<int> kfoldcv(const int n, const int k) {\n std::vector<int> indexes(n);\n int i(0);\n std::generate(indexes.begin(), indexes.end(), [&]{ return i++; });\n\n std::random_device rd;\n std::mt19937 g(rd());\n\n std::shuffle(indexes.begin(), indexes.end(), g);\n\n\n int foldSize = n / k;\n for(int fold = 0; fold < k; fold++) {\n\n std::vector<int> test_idx;\n std::vector<int> training_idx;\n\n int foldBegin = foldSize * fold;\n int foldEnd = foldBegin + foldSize; \n \n for(int i = 0; i < n; i++) {\n\n if(i >= foldBegin && i < foldEnd) { \n test_idx.push_back(indexes[i]); \n }\n else {\n training_idx.push_back(indexes[i]); \n }\n }\n\n }\n\n return indexes;\n}\n\n\nint main(int argc, char* argv[]) {\n \n namespace spd = spdlog; \n\n try {\n //Create console, multithreaded logger\n auto console = spd::stdout_logger_mt(\"console\");\n console->info(\"Bayesian Network Build\");\n\n int k = atoi(argv[2]);\n\n gum::learning::DatabaseFromCSV database(argv[1]);\n console->info(\"Number of rows: {}\", database.content().size());\n console->info(\"Number of variables: {}\", database.variableNames().size());\n\n // K-fold Cross Validation Start\n int n = database.content().size();\n std::vector<int> indexes(n);\n int i(0);\n std::generate(indexes.begin(), indexes.end(), [&] { return i++; });\n\n std::random_device rd;\n std::mt19937 g(rd());\n std::shuffle(indexes.begin(), indexes.end(), g);\n\n const int nbCol = 8;\n auto translators = gum::learning::make_translators(gum::learning::Create<gum::learning::CellTranslatorCompactIntId,gum::learning::Col<0>, nbCol>());\n auto generators = gum::learning::make_generators(gum::learning::RowGeneratorIdentity());\n auto filter = gum::learning::make_DB_row_filter(database, translators, generators);\n std::vector<unsigned int> modalities = filter.modalities();\n gum::learning::AprioriSmoothing<> apriori;\n gum::learning::StructuralConstraintSetStatic<gum::learning::StructuralConstraintDAG> struct_constraint;\n gum::learning::GraphChangesGenerator4DiGraph<decltype(struct_constraint)>op_set(struct_constraint);\n\n gum::learning::GreedyHillClimbing search;\n\n int foldSize = database.content().size() / k;\n for (int fold = 0; fold < k; fold++) {\n unsigned int fold_deb = fold * foldSize;\n unsigned int fold_end = fold_deb + foldSize - 1;\n console->info(\"LEARNING [{},{}]\", fold_deb, fold_end);\n\n // LEARNING\n filter.handler().setRange(fold_deb, fold_end);\n gum::learning::ScoreBDeu<> score(filter, modalities, apriori);\n gum::learning::ParamEstimatorML<> estimator(filter, modalities, apriori,score.internalApriori());\n gum::learning::GraphChangesSelector4DiGraph<decltype(score), decltype(struct_constraint), decltype(op_set)>selector(score, struct_constraint, op_set);\n gum::Timer timer;\n gum::BayesNet<float> bn = search.learnBN(selector, estimator, database.variableNames(), modalities, filter.translatorSet());\n console->info(\"{}s\", timer.step());\n console->info(\"{} arcs\", bn.arcs().size());\n\n // Testing\n double LL = 0.0;\n console->info(\"Gibbs Inference\");\n gum::GibbsInference<float> inf(bn);\n inf.makeInference();\n const gum::Potential<float>& prb = inf.posterior(bn.idFromName(\"positive_XraY?\"));\n gum::Instantiation itr ( prb );\n for(itr.setFirst(); !itr.end(); ++itr)\n console->info(\"Before Evidence: {}\", prb[itr]);\n\n gum::Instantiation I;\n for (auto &name : filter.variableNames())\n I.add(bn.variableFromName(name));\n\n \n \n if (fold_deb != 0) {\n console->info(\"[0,{}]\", fold_deb - 1);\n filter.handler().setRange(0, fold_deb - 1);\n filter.reset();\n\n while (filter.hasRows()) {\n int i = 0; \n auto rows = filter.row().row();\n for (int j = 0; j < rows.size()-1; j++) {\n I.chgVal(i++, rows.at(j)); \n }\n\n // std::cout << I.toString() << std::endl; // prints Instatition vector\n\n LL += bn.log2JointProbability(I); \n }\n }\n\n if (fold_end + 1 < database.content().size() - 1) {\n console->info(\"[{},{}]\", fold_end + 1, database.content().size() - 1);\n filter.handler().setRange(fold_end + 1, database.content().size() - 1);\n filter.reset();\n\n while (filter.hasRows()) {\n int i = 0;\n auto rows = filter.row().row();\n for (int j = 0; j < rows.size()-1; j++) { \n I.chgVal(i++, rows.at(j)); \n } \n LL += bn.log2JointProbability(I);\n\n }\n }\n\n console->info(\"LL = {}\", LL);\n\n inf.makeInference();\n const gum::Potential<float>& prbE = inf.posterior(bn.idFromName(\"positive_XraY?\"));\n gum::Instantiation itr2 (prbE);\n for (itr2.setFirst(); ! itr2.end(); ++itr2)\n console->info(\"After Evidence: {}\", prbE[itr2]);\n }\n } catch (const spd::spdlog_ex& ex) {\n std::cout << \"Log failed: \" << ex.what() << std::endl;\n }\n return 0;\n}"
},
{
"alpha_fraction": 0.7354651093482971,
"alphanum_fraction": 0.7529069781303406,
"avg_line_length": 18.05555534362793,
"blob_id": "0f365c4750fe3fb14bbe9cfa875298070cf9dab7",
"content_id": "c8b1a49e3f3597eafb15fb6b52146d6e5aba45b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 18,
"path": "/agrum_test.py",
"repo_name": "haluk/bayes",
"src_encoding": "UTF-8",
"text": "import sys\nimport numpy as np\nimport pyAgrum as gum\n\nimport pdb\n\nfrom gumLib.bn2roc import showROC\n\n\n# Learning a BN from the database\nlearner=gum.BNLearner(sys.argv[1])\n\n# # Hill-Climbing\nlearner.useGreedyHillClimbing()\nbn=learner.learnBN()\nprint(\"Learned in {0}s\".format(learner.currentTime()))\n\nshowROC(bn,sys.argv[2],'SAO2','1',True,True) \n"
}
] | 3 |
XinchenVincent/practice_git | https://github.com/XinchenVincent/practice_git | 027a2006dd075c02ac961f77fd8257477fe99a64 | 3949c58ad6172a38c91e6662fac6a6e8743c4e98 | 4c024eb9498188e04560d6902ff4dc6edbb69f14 | refs/heads/master | 2021-04-28T13:49:48.940610 | 2018-02-18T12:41:11 | 2018-02-18T12:41:11 | 121,946,845 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5614035129547119,
"alphanum_fraction": 0.5614035129547119,
"avg_line_length": 10.600000381469727,
"blob_id": "817bd737fb06e0176b31623b3f28f89989c94165",
"content_id": "91a16992983df2cc1bd962fa464f1edccc828bbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 5,
"path": "/play1.py",
"repo_name": "XinchenVincent/practice_git",
"src_encoding": "UTF-8",
"text": "def sum(a,b):\n return a + b\n\ndef min(a,b):\n return a-b"
}
] | 1 |
GBNP5000/REGEX1 | https://github.com/GBNP5000/REGEX1 | 312012fe2a1ebe754e254ad012aa6a1c472205fe | 1a65a70221291958b35aacfda6b770878a823ab2 | 58debb5627ab08f0a35657e72b337c94fc90906b | refs/heads/main | 2023-01-11T13:02:11.762751 | 2020-11-11T09:32:27 | 2020-11-11T09:32:27 | 311,920,599 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5865479707717896,
"alphanum_fraction": 0.6073194742202759,
"avg_line_length": 41.125,
"blob_id": "89e57a2ec1f254dfaecf00c2a7cb18eb66dde52f",
"content_id": "8b7206a5133a742324d051eee35ce18c3546d9f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1011,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 24,
"path": "/regex1.py",
"repo_name": "GBNP5000/REGEX1",
"src_encoding": "UTF-8",
"text": "# coding=utf8\n# the above tag defines encoding for this document and is for Python 2.x compatibility\n\nimport re\n\nregex = r\"(?<=>|\\()[0-9\\.,-]+\"\n\ntest_str = (\"<span class=\\\"span_price_wrap stprh grn_hilight grnclr\\\">1770.00</span>'\\n\"\n \"b'<span class=\\\"span_price_arrow green_arwup\\\"></span>'\\n\"\n \"b'<span class=\\\"span_price_change_prcnt grnpc1\\\">11.25 <em>(-0.64%)</em></\")\n\nmatches = re.finditer(regex, test_str, re.MULTILINE)\nprint(matches)\n\nfor matchNum, match in enumerate(matches, start=1):\n\n print(\"Match {matchNum} was found at {start}-{end}: {match}\".format(\n matchNum=matchNum, start=match.start(), end=match.end(), match=match.group()))\n\n for groupNum in range(0, len(match.groups())):\n groupNum = groupNum + 1\n\n print(\"Group {groupNum} found at {start}-{end}: {group}\".format(groupNum=groupNum,\n start=match.start(groupNum), end=match.end(groupNum), group=match.group(groupNum)))\n"
}
] | 1 |
deiscc/workflow-release | https://github.com/deiscc/workflow-release | e87a6a86f67d7f5ef447b14f2fafd63fbe40fd24 | 2bf55cadcfd2b57be94e61275f8fae1a3330e69a | f34671b3902aeccab84a8c28820719dc4efe2431 | refs/heads/master | 2020-04-11T00:17:17.878395 | 2018-12-28T08:28:04 | 2018-12-28T08:56:17 | 161,382,155 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7101604342460632,
"alphanum_fraction": 0.7112299203872681,
"avg_line_length": 18.288660049438477,
"blob_id": "9a8252e886d400b6aef7f7935463dee7cc49f538",
"content_id": "85da7cae3e16c1eec52a2e7609aae42d42746bb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1870,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 97,
"path": "/workflow_release/scripts/build_workflow.sh",
"repo_name": "deiscc/workflow-release",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\nset -eo pipefail\n\nexport DEIS_REGISTY=\"\"\n\ndeis_repo_path=\"$1\"\n\nbuilder(){\n cd $deis_repo_path/builder\n make bootstrap docker-build docker-immutable-push\n}\n\nredis(){\n cd $deis_repo_path/redis\n make docker-build docker-immutable-push\n}\n\nworkflow-manager(){\n cd $deis_repo_path/workflow-manager\n make bootstrap build docker-build docker-immutable-push\n}\n\ncontroller(){\n cd $deis_repo_path/controller\n make build docker-immutable-push\n}\n\ndockerbuilder(){\n cd $deis_repo_path/dockerbuilder\n make docker-build docker-immutable-push\n}\n\nfluentd(){\n cd $deis_repo_path/fluentd\n make build docker-immutable-push\n}\n\nlogger(){\n cd $deis_repo_path/logger\n make bootstrap build docker-immutable-push\n}\n\nminio(){\n cd $deis_repo_path/minio\n make docker-build docker-immutable-push\n}\n\nmonitor(){\n cd $deis_repo_path/monitor/grafana\n make build docker-immutable-push\n cd $deis_repo_path/monitor/influxdb\n make build docker-immutable-push\n cd $deis_repo_path/monitor/telegraf\n make build docker-immutable-push\n}\n\nnsq(){\n cd $deis_repo_path/nsq\n make build docker-immutable-push\n}\n\ndatabase(){\n cd $deis_repo_path/database\n make docker-build docker-immutable-push\n}\n\nregistry(){\n cd $deis_repo_path/registry\n make docker-build docker-immutable-push\n}\n\nregistry-proxy(){\n cd $deis_repo_path/registry-proxy\n make build docker-immutable-push\n}\n\nregistry-token-refresher(){\n cd $deis_repo_path/registry-token-refresher\n make bootstrap docker-build docker-immutable-push\n}\n\nrouter(){\n cd $deis_repo_path/router\n make bootstrap docker-build docker-immutable-push\n}\n\nslugbuilder(){\n cd $deis_repo_path/slugbuilder\n make build docker-build docker-immutable-push\n}\n\nslugrunner(){\n cd $deis_repo_path/slugrunner\n make build docker-build docker-immutable-push\n}\n\n\"$2\""
},
{
"alpha_fraction": 0.715855598449707,
"alphanum_fraction": 0.7378336191177368,
"avg_line_length": 29.380952835083008,
"blob_id": "21c59619a6f25e28202d0bec930515a229ddeaaa",
"content_id": "4d61957984138d767b957d816c2b26cce0d51ba0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 21,
"path": "/README.md",
"repo_name": "deiscc/workflow-release",
"src_encoding": "UTF-8",
"text": "# Requirements\n\n* python>=3.5.0\n* docker>=1.13\n\n# Install\n\n```\ngit clone https://github.com/deiscc/workflow-release\ncd workflow-release & python3 -m venv .venv\nsource .venv/bin/active && python3 setup.py develop\n```\n\n# Environment\n\n* `GETHUB_ORG` Organization of GitHub, default `deiscc`\n* `GETHUB_AUTH` Github's account, like `username:password`\n* `VERSION` Workflow version to be released, like `v2.8.0`\n* `PRE_VERSION` Workflow version number of the last release, like `v2.7.0`\n* `IMAGE_PREFIX` Image prefix of docker registry, default `deiscc`\n* `DEIS_REGISTRY` The address of docker registry, use docker official registry by default"
},
{
"alpha_fraction": 0.583069920539856,
"alphanum_fraction": 0.5860555171966553,
"avg_line_length": 35.26751708984375,
"blob_id": "a10a004fdc8bfb25b4459e12b88c0065da07ab4e",
"content_id": "75190ccbda47248eb8fbc113c243b81472fd4b00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5694,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 157,
"path": "/workflow_release/cmd.py",
"repo_name": "deiscc/workflow-release",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport re\nimport sys\nimport json\nimport shutil\nimport datetime\n\nfrom ruamel import yaml\n\nfrom .utils import WorkflowUtils\n\nBASE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)))\nSCRIPTS_PATH = os.path.join(BASE_PATH, \"scripts\")\n\nbuild_repo_path = os.path.join(\"build\", \"repo\")\nbuild_charts_path = os.path.join(\"build\", \"charts\")\nos.system(\"mkdir -p %s %s\" % (build_repo_path, build_charts_path))\n\ndeis_registry = \"\"\nworkflow_util = None\nbuild_settings = None\nchartmuseum_api = \"http://charts.deis.cc/api/stable/charts\"\nchartmuseum_user = \"admin:admin\"\n\ndef _init_env():\n if not os.path.exists(\"templates\"):\n shutil.copytree(os.path.join(BASE_PATH, \"templates\"), \"templates\")\n if len(sys.argv) < 2:\n print(\"Missing parameters: deis-release {action} {args}\")\n else:\n global build_settings, deis_registry, workflow_util, \\\n chartmuseum_api, chartmuseum_user\n workflow_util = _get_workflow_util()\n deis_registry = os.getenv(\"DEIS_REGISTRY\", deis_registry)\n with open(os.path.join(\"templates\", \"settings.json\")) as f:\n build_settings = json.load(f)\n chartmuseum_api = os.getenv(\"CHARTMUSEUM_API\", chartmuseum_api)\n chartmuseum_user = os.getenv(\"CHARTMUSEUM_USER\", chartmuseum_user)\n os.environ['DEIS_REGISTRY'] = deis_registry\n return True\n return False\n\ndef _change_yaml(name, filename):\n if not os.path.exists(filename): return\n with open(filename) as f:\n data = yaml.round_trip_load(f)\n if \"version\" in data:\n data[\"version\"] = workflow_util.get_version(name)\n if \"docker_tag\" in data:\n data[\"docker_tag\"] = workflow_util.get_version(name)\n if \"docker_registry\" in data:\n data[\"docker_registry\"] = deis_registry\n with open(filename, \"w\") as f:\n yaml.round_trip_dump(\n data,\n f,\n allow_unicode=True,\n )\n\ndef _get_workflow_util():\n github_org = os.getenv(\"GETHUB_ORG\", \"deiscc\")\n github_auth = os.getenv(\"GETHUB_AUTH\", \":\").split(\":\")\n version = os.getenv(\"VERSION\", \"v0.0.0\")\n pre_version = os.getenv(\"PRE_VERSION\", \"v0.0.0\")\n return WorkflowUtils(org=github_org, user=github_auth,\n version=version, pre_version=pre_version)\n\ndef build_workflow(*args):\n name_list = build_settings.keys() if len(args) == 0 else args\n for name in name_list:\n export_script = \"export VERSION={version}\".format(\n version=workflow_util.get_version(name)\n )\n script = \"{script} {repo_path} {build_name}\".format(\n script=os.path.join(SCRIPTS_PATH, \"build_workflow.sh\"),\n repo_path=build_repo_path,\n build_name=name\n )\n os.system(\"%s && %s\" % (export_script, script))\n\ndef git(*args):\n name_list = build_settings.keys()\n for name in name_list:\n cmd_args = list(args)\n if cmd_args[0] in (\"push\", \"clone\", \"pull\", \"push\", \"fetch\"):\n repo_url = build_settings[name]['repo']\n cmd_args.append(repo_url)\n if cmd_args[0] == \"clone\":\n cmd_args.append(\".\")\n repo_path = os.path.join(build_repo_path, name)\n if not os.path.exists(repo_path): os.makedirs(repo_path)\n git_script = \"cd %s && git %s\" % (repo_path, \" \".join(cmd_args))\n print(git_script)\n os.system(git_script)\n\ndef build_charts(*args):\n tar_version_script_tpl = \"tar zcvf {name}-{version}.tgz {name}\"\n name_list = build_settings.keys() if len(args) == 0 else args\n for key in name_list:\n chart_path = os.path.join(build_charts_path, key)\n repo_charts_path = os.path.join(build_repo_path, key, \"charts\", key)\n if not os.path.exists(repo_charts_path): continue\n copy_script = \"cp -rf %s %s\" % (repo_charts_path, chart_path)\n os.system(copy_script)\n chart_yaml = os.path.join(chart_path, \"Chart.yaml\")\n values_yaml = os.path.join(chart_path, \"values.yaml\")\n requirements_yaml = os.path.join(chart_path, \"requirements.yaml\")\n _change_yaml(key, chart_yaml)\n _change_yaml(key, values_yaml)\n _change_yaml(key, requirements_yaml)\n os.system(\"%s && %s\" % (\n \"cd %s\" % build_charts_path,\n tar_version_script_tpl.format(\n name=key,\n version=workflow_util.get_version(key)\n )\n )\n )\n os.system(\"rm -rf %s\" % chart_path)\n\ndef upload_charts(*args):\n script = \"curl -u {user} -F 'chart=@{name}' {url}\"\n name_list = build_settings.keys() if len(args) == 0 else args\n for name in name_list:\n tar_file = os.path.join(\n build_charts_path,\n \"{name}-{version}.tgz\".format(\n name=name, version=workflow_util.get_version(name))\n )\n if not os.path.exists(tar_file): continue\n upload_script = \"%s && %s\" % (\n \"cd %s\" % build_charts_path,\n script.format(\n user=chartmuseum_user,\n name=tar_file,\n url=chartmuseum_api,\n ),\n )\n os.system(upload_script)\n\ndef main():\n if not _init_env(): return\n command = sys.argv[1]\n command_args = sys.argv[2:]\n if command == 'workflow':\n build_workflow(*command_args)\n elif command == 'charts':\n sub_command = command_args[0]\n if sub_command == \"build\":\n build_charts(*command_args[1:])\n elif sub_command == \"upload\":\n upload_charts(*command_args[1:])\n elif command == \"git\":\n git(*command_args)\n else:\n print(\"Unsupported operation types\")\n"
}
] | 3 |
brianweber2/project8_filtering_and_searching_mineral_catalog | https://github.com/brianweber2/project8_filtering_and_searching_mineral_catalog | 38878cd6e852c36aacf7d09a58598546e18ca62e | f17fd79f76779c8101fa32a3b27e929ff952d813 | 6387e3cc3941aab807aaeabd9fce83d13323d067 | refs/heads/master | 2021-01-19T09:32:27.669676 | 2017-03-08T19:19:44 | 2017-03-08T19:19:44 | 82,125,951 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.5279502868652344,
"alphanum_fraction": 0.6024844646453857,
"avg_line_length": 23.149999618530273,
"blob_id": "3bd8946f6bd0f04979079a9e7ea265b97f223cdf",
"content_id": "4f61861cf894acc66bad81cdee5c89c9614ce7d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 483,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 20,
"path": "/mineral_catalog/minerals/migrations/0003_auto_20170215_2021.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.5 on 2017-02-16 04:21\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('minerals', '0002_auto_20170215_2020'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='mineral',\n name='img_caption',\n field=models.TextField(blank=True, default='', max_length=255),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5775147676467896,
"alphanum_fraction": 0.5957396626472473,
"avg_line_length": 37.06306457519531,
"blob_id": "a020b4dbc3fd8d102e57d239382a17a480b22255",
"content_id": "8d893f00dc0479f2f1fb8078b20b37abcf5cf2f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4236,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 111,
"path": "/mineral_catalog/minerals/tests.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.core.management import call_command\nfrom django.utils.six import StringIO\n\nfrom .models import Mineral\n\n\nmineral_data = {\n \"name\": \"Abelsonite\",\n \"img_filename\": \"Abelsonite.jpg\",\n \"img_caption\": \"Abelsonite from the Green River Formation, Uintah County, Utah, US\",\n \"category\": \"Organic\",\n \"formula\": \"C<sub>31</sub>H<sub>32</sub>N<sub>4</sub>Ni\",\n \"strunz_classification\": \"10.CA.20\",\n \"crystal_system\": \"Triclinic\",\n \"unit_cell\": \"a = 8.508 Å, b = 11.185 Åc=7.299 Å, α = 90.85°β = 114.1°, γ = 79.99°Z = 1\",\n \"color\": \"Pink-purple, dark greyish purple, pale purplish red, reddish brown\",\n \"crystal_symmetry\": \"Space group: P1 or P1Point group: 1 or 1\",\n \"cleavage\": \"Probable on {111}\",\n \"mohs_hardness\": \"2–3\",\n \"luster\": \"Adamantine, sub-metallic\",\n \"streak\": \"Pink\",\n \"diaphaneity\": \"Semitransparent\",\n \"group\": \"Organic Minerals\",\n}\nmineral_data2 = {\n \"name\": \"Bhurite\",\n \"img_filename\": \"Bhurite.jpg\",\n \"img_caption\": \"Brownish tabular crystals of abhurite from Shipwreck \\\"Hydra\\\", South coast of Norway\",\n \"category\": \"Halide\",\n \"formula\": \"Sn<sub>21</sub>O<sub>6</sub>(OH)<sub>14</sub>Cl<sub>16</sub>\",\n \"strunz_classification\": \"03.DA.30\",\n \"crystal_symmetry\": \"Trigonal\",\n \"group\": \"Other\",\n}\n\n\n################################\n########## View Tests ##########\n################################\nclass MineralViewsTest(TestCase):\n def setUp(self):\n self.mineral = Mineral.objects.create(**mineral_data)\n self.mineral2 = Mineral.objects.create(**mineral_data2)\n\n def test_mineral_list_view(self):\n resp = self.client.get(reverse('minerals:list'))\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertNotIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_list.html')\n self.assertContains(resp, self.mineral.name)\n\n def test_mineral_detail_view(self):\n resp = self.client.get(\n reverse('minerals:detail', kwargs={'pk': self.mineral.pk})\n )\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(self.mineral, resp.context['mineral'])\n self.assertTemplateUsed(resp, 'minerals/mineral_detail.html')\n\n def test_mineral_list_letter_filter_view(self):\n resp = self.client.get(\n reverse('minerals:letter_filter', kwargs={'letter': 'A'})\n )\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertNotIn(self.mineral2, resp.context['minerals'])\n\n def test_mineral_search_view(self):\n resp = self.client.get(reverse('minerals:search'), {'q': 'Bhur'})\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral2, resp.context['result'])\n self.assertTemplateUsed(resp, 'minerals/search.html')\n\n def test_mineral_group_filter_view(self):\n resp = self.client.get(\n reverse(\n 'minerals:group_filter',\n kwargs={'group': 'Organic Minerals'}\n )\n )\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertNotIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_group_filter.html')\n\n\n#################################\n########## Model Tests ##########\n#################################\nclass MineralModelTest(TestCase):\n def test_mineral_creation(self):\n mineral = Mineral.objects.create(**mineral_data)\n self.assertEqual(mineral.name, 'Abelsonite')\n\n\n###############################################\n########## Management Commands Tests ##########\n###############################################\nclass CommandsTests(TestCase):\n def test_load_mineral_data(self):\n args = []\n opts = {}\n out = StringIO()\n call_command('load_mineral_data', stdout=out, *args, **opts)\n self.assertIn(\n 'Mineral data has been successfully uploaded!',\n out.getvalue()\n )\n"
},
{
"alpha_fraction": 0.6247544288635254,
"alphanum_fraction": 0.6247544288635254,
"avg_line_length": 35.35714340209961,
"blob_id": "a97ab0176800bfa28bac7bb533f6796ed8054041",
"content_id": "4812cad2ddd3c1dbfe99007f10fc711062e2e125",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 509,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 14,
"path": "/mineral_catalog/minerals/urls.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url, include\n\nfrom . import views\n\nurlpatterns = [\n url(r'^group_results/(?P<group>\\w+)$', views.mineral_group_filter,\n name='group_filter'),\n url(r'^search/', include('haystack.urls')),\n url(r'^search_results$', views.mineral_search, name='search'),\n url(r'^$', views.mineral_list, name='list'),\n url(r'(?P<letter>[a-zA-Z]+)$', views.mineral_list_letter_filter,\n name='letter_filter'),\n url(r'(?P<pk>\\d+)$', views.mineral_detail, name='detail')\n]\n"
},
{
"alpha_fraction": 0.5668176412582397,
"alphanum_fraction": 0.5679501891136169,
"avg_line_length": 38.24444580078125,
"blob_id": "85051c99666f6695938d4f5c943babf26b0fa291",
"content_id": "7f1d6ccfefd0f318ff2eaea17550e2ecc6ff87c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1766,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 45,
"path": "/mineral_catalog/minerals/management/commands/load_mineral_data.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.core.management.base import BaseCommand, CommandError\nfrom minerals.models import Mineral\n\nimport json\n\nfilename = 'data/minerals3.json'\n\n\nclass Command(BaseCommand):\n \"\"\"Adds all minerals from JSON file to database.\"\"\"\n help = 'Prepopulates JSON data provided by Team Treehouse.'\n\n def add_arguments(self, parser):\n pass\n\n def handle(self, *args, **options):\n with open(filename, encoding='utf-8') as file:\n minerals = json.load(file)\n\n for mineral in minerals:\n Mineral(\n name = mineral['name'],\n img_filename = mineral['image filename'],\n img_caption = mineral['image caption'],\n category = mineral['category'],\n formula = mineral['formula'],\n group = mineral['group'],\n strunz_classification = mineral['strunz classification'],\n crystal_system = mineral['crystal system'],\n unit_cell = mineral['unit cell'],\n color = mineral['color'],\n crystal_symmetry = mineral['crystal symmetry'],\n cleavage = mineral['cleavage'],\n mohs_hardness = mineral['mohs scale hardness'],\n luster = mineral['luster'],\n streak = mineral['streak'],\n diaphaneity = mineral['diaphaneity'],\n optical_properties = mineral['optical properties'],\n refractive_index = mineral['refractive index'],\n crystal_habit = mineral['crystal habit'],\n specific_gravity = mineral['specific gravity']\n ).save()\n self.stdout.write(self.style.SUCCESS(\n '\\nMineral data has been successfully uploaded!'\n ))\n"
},
{
"alpha_fraction": 0.7124394178390503,
"alphanum_fraction": 0.7124394178390503,
"avg_line_length": 35.411766052246094,
"blob_id": "8ddee035fdb9625c4652ffb71f1ea1ed73e07780",
"content_id": "786b67595558e3b5d73e243fc31a88dc681fffa2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 619,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 17,
"path": "/mineral_catalog/minerals/search_indexes.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from haystack import indexes\nfrom minerals.models import Mineral\n\n\nclass MineralIndex(indexes.SearchIndex, indexes.Indexable):\n text = indexes.CharField(document=True, use_template=True)\n name = indexes.CharField(model_attr='name')\n category = indexes.CharField(model_attr='category')\n group = indexes.CharField(model_attr='group')\n color = indexes.CharField(model_attr='color')\n\n def get_model(self):\n return Mineral\n\n def index_queryset(self, using=None):\n \"\"\"Used when the entire index for model is updated.\"\"\"\n return self.get_model().objects.filter(name__istartswith='A')\n"
},
{
"alpha_fraction": 0.5963084101676941,
"alphanum_fraction": 0.5983923673629761,
"avg_line_length": 27.95689582824707,
"blob_id": "540f24a23f65ac385dec81be9a9a6e9b8f59abea",
"content_id": "65e605f297d2978b971937d2340dbfa6a64f4ad6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3359,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 116,
"path": "/mineral_catalog/minerals/views.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n\nfrom .models import Mineral\nfrom . import forms\n\nimport random\nimport string\n\n\n# Constants\nletters = string.ascii_uppercase\nletter_start = letters[0]\ngroups = ['silicates', 'oxides', 'sulfates', 'sulfides', 'carbonates',\n 'halides', 'sulfosalts', 'phosphates', 'borates',\n 'Organic Minerals', 'asenates', 'Native Elements', 'other']\n\ndef mineral_list(request):\n \"\"\"Returns a list of all minerals.\"\"\"\n # minerals = Mineral.objects.all()\n minerals = Mineral.objects.filter(name__istartswith=letter_start).values(\n 'name', 'pk')\n random_mineral = random.choice(minerals)\n\n return render(\n request,\n 'minerals/mineral_list.html',\n {\n 'minerals': minerals,\n 'random_mineral': random_mineral,\n 'letters': letters,\n 'active_letter': letter_start,\n 'mineral_groups': groups\n }\n )\n\ndef mineral_detail(request, pk):\n \"\"\"Returns a single mineral.\"\"\"\n mineral = get_object_or_404(Mineral, pk=pk)\n minerals = Mineral.objects.all()\n random_mineral = random.choice(minerals)\n\n return render(\n request,\n 'minerals/mineral_detail.html',\n {\n 'mineral': mineral,\n 'random_mineral': random_mineral,\n 'letters': letters,\n 'mineral_groups': groups\n }\n )\n\ndef mineral_list_letter_filter(request, letter):\n \"\"\"Returns a list of all minerals that begin with letter.\"\"\"\n all_minerals = Mineral.objects.all()\n random_mineral = random.choice(all_minerals)\n minerals = Mineral.objects.filter(name__istartswith=letter)\n\n return render(\n request,\n 'minerals/mineral_list.html',\n {\n 'minerals': minerals,\n 'random_mineral': random_mineral,\n 'letters': letters,\n 'active_letter': letter,\n 'mineral_groups': groups\n }\n )\n\ndef mineral_search(request):\n \"\"\"Returns a list of minerals that match the search query.\"\"\"\n result = []\n query = request.GET.get('q', None)\n\n minerals = Mineral.objects.all().values('name', 'pk')\n random_mineral = random.choice(minerals)\n\n if query:\n result = Mineral.objects.filter(name__icontains=query)\n return render(\n request,\n 'minerals/search.html',\n {\n 'query': query,\n 'result': result,\n 'random_mineral': random_mineral,\n 'letters': letters,\n 'mineral_groups': groups\n }\n )\n\ndef mineral_group_filter(request, group):\n \"\"\"Returns a list of all minerals in a specified group.\"\"\"\n if group == 'organic_minerals':\n group = 'Organic Minerals'\n elif group == 'native_elements':\n group = 'Native Elements'\n\n all_minerals = Mineral.objects.all().values('name', 'pk')\n random_mineral = random.choice(all_minerals)\n minerals = all_minerals.filter(group__iexact=group)\n\n return render(\n request,\n 'minerals/mineral_group_filter.html',\n {\n 'minerals': minerals,\n 'random_mineral': random_mineral,\n 'letters': letters,\n 'active_group': group,\n 'mineral_groups': groups\n }\n )\n"
},
{
"alpha_fraction": 0.5708333253860474,
"alphanum_fraction": 0.5833333134651184,
"avg_line_length": 20.81818199157715,
"blob_id": "22ee9048f348ec4c61001e57558e6d48b9ca6d59",
"content_id": "3cc5160cdc296adfb6407261bdc59e8527393a33",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 11,
"path": "/mineral_catalog/minerals/forms.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django import forms\n\n\nclass MineralSearchForm(forms.Form):\n q = forms.CharField(\n label='',\n max_length=100,\n widget=forms.TextInput(\n attrs={'placeholder': 'Search minerals by name'}\n )\n )\n"
},
{
"alpha_fraction": 0.6638591289520264,
"alphanum_fraction": 0.7098008990287781,
"avg_line_length": 41.129032135009766,
"blob_id": "79daa13b76017ee827253b218ba2ed97a0515aa7",
"content_id": "9c833a04e4ae80debe38bf8e78cf78336c544406",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1306,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 31,
"path": "/mineral_catalog/minerals/models.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\n\nclass Mineral(models.Model):\n name = models.CharField(max_length=255)\n img_filename = models.CharField(max_length=255)\n img_caption = models.TextField(max_length=255, blank=True, default='')\n category = models.CharField(max_length=255)\n group = models.CharField(max_length=255, default='')\n formula = models.CharField(max_length=255)\n strunz_classification = models.CharField(max_length=255)\n crystal_system = models.CharField(max_length=255)\n unit_cell = models.CharField(max_length=255)\n color = models.CharField(max_length=255)\n crystal_symmetry = models.CharField(max_length=255, blank=True, default='')\n cleavage = models.CharField(max_length=255)\n mohs_hardness = models.CharField(max_length=255)\n luster = models.CharField(max_length=255)\n streak = models.CharField(max_length=255)\n diaphaneity = models.CharField(max_length=255)\n optical_properties = models.CharField(max_length=255)\n refractive_index = models.CharField(max_length=255, blank=True, default='')\n crystal_habit = models.CharField(max_length=255, blank=True, default='')\n specific_gravity = models.CharField(max_length=255, blank=True, default='')\n\n class Meta:\n ordering = ['name']\n\n\n def __str__(self):\n return self.name\n"
},
{
"alpha_fraction": 0.6934426426887512,
"alphanum_fraction": 0.6934426426887512,
"avg_line_length": 20.785715103149414,
"blob_id": "9b5cbd6aa5da048db9e9823cbabaead640e429a6",
"content_id": "23da06e5318075e7577d31c9da76c55fa5ba994d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 610,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 28,
"path": "/mineral_catalog/minerals/templatetags/mineral_extras.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django import template\n\nfrom ..models import Mineral\nfrom ..forms import MineralSearchForm\nfrom ..views import groups\n\nimport random\n\n\nregister = template.Library()\n\[email protected]_tag\ndef search_form():\n \"\"\"Returns search form.\"\"\"\n form = MineralSearchForm()\n return form\n\n# @register.simple_tag\n# def random_mineral():\n# \"\"\"Returns a random mineral from the database.\"\"\"\n# minerals = Mineral.objects.all()\n# random_mineral = random.choice(minerals)\n# return random_mineral\n\n# @register.simple_tag\n# def mineral_groups():\n# \"\"\"Return mineral groups.\"\"\"\n# return groups\n"
},
{
"alpha_fraction": 0.7627118825912476,
"alphanum_fraction": 0.7627118825912476,
"avg_line_length": 16.700000762939453,
"blob_id": "dc66cf13f64d595e531cad623550cfcddc5899ce",
"content_id": "cc2d86c58aee1a6952f6b6d1a9d9049cf0208b65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 177,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 10,
"path": "/mineral_catalog/minerals/admin.py",
"repo_name": "brianweber2/project8_filtering_and_searching_mineral_catalog",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import Mineral\n\n\nclass MineralAdmin(admin.ModelAdmin):\n search_fields = ('name',)\n\n\nadmin.site.register(Mineral, MineralAdmin)\n"
}
] | 10 |
trubbish/python-stuff | https://github.com/trubbish/python-stuff | ea6878c983ae4fffb33a2309b8fae54b6867e042 | 691be4c1d7b7265ed02de1e4286e1aed2b9ec071 | c459bfdd36bde9c4f10461ca3c0ae404b9227586 | refs/heads/master | 2021-05-04T21:08:32.947536 | 2018-05-17T18:38:22 | 2018-05-17T18:38:22 | 119,867,482 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6611111164093018,
"alphanum_fraction": 0.6611111164093018,
"avg_line_length": 34.400001525878906,
"blob_id": "3397e16267130485ac56784935c29463a6d97a4e",
"content_id": "354b7a91f6f1312c4851652828243d8dcd2ee9c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 180,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 5,
"path": "/magic.py",
"repo_name": "trubbish/python-stuff",
"src_encoding": "UTF-8",
"text": "print(\"I am the magic .py file. I can guess any number you can think!\")\r\nprint()\r\nnum = input(\"What number are you thinking of?\\n\")\r\nprint(\"Aha! Your number is\", num, \"!\")\r\ninput()"
},
{
"alpha_fraction": 0.41826921701431274,
"alphanum_fraction": 0.4759615361690521,
"avg_line_length": 13.857142448425293,
"blob_id": "526d1001f3293c2272a6305fa818b3ec45c79406",
"content_id": "b5fe1752970acc4ce296ed58fbefb55a760491ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 14,
"path": "/euler5.py",
"repo_name": "trubbish/python-stuff",
"src_encoding": "UTF-8",
"text": "def checkvar(n):\n for i in range(2, 21):\n if n % i == 0:\n continue\n else:\n return False\n return True\n\nx = 2520\n\nwhile checkvar(x) = False\n x += 2520\n\nprint(x)\n"
},
{
"alpha_fraction": 0.78125,
"alphanum_fraction": 0.78125,
"avg_line_length": 15,
"blob_id": "e3d892cc1f4eedd23e8875ff05d2b6719b98dcfe",
"content_id": "84fc9886fa977162cd22a344098a231ff8bec038",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 32,
"license_type": "no_license",
"max_line_length": 16,
"num_lines": 2,
"path": "/README.md",
"repo_name": "trubbish/python-stuff",
"src_encoding": "UTF-8",
"text": "# python-stuff\nStuff for python\n"
},
{
"alpha_fraction": 0.5833333134651184,
"alphanum_fraction": 0.5916666388511658,
"avg_line_length": 28,
"blob_id": "b737a441b5adc614c94aa3c6d5401c0189b50da3",
"content_id": "45c02fee60f9c17e82ce85ce3354dc6ba92e9a80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1440,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 48,
"path": "/lil text adventure.py",
"repo_name": "trubbish/python-stuff",
"src_encoding": "UTF-8",
"text": "import random\r\nimport time\r\n\r\ndef displayIntro():\r\n print()\r\n print(\"You're hiking in the woods, and you come across\")\r\n print(\"a fork in the road. One path will kill you while the\")\r\n print(\"other path with lead to treasure beyond your wildest\")\r\n print(\"dreams. Good luck!\")\r\n print()\r\n\r\ndef choosePath():\r\n path = \"\"\r\n while path not in [\"1\", \"2\"]:\r\n path = input(\"Which path will you choose? (1 or 2): \")\r\n if path not in [\"1\", \"2\"]:\r\n print(\"That is not a valid input.\")\r\n print()\r\n return path\r\n\r\ndef checkPath(chosenPath):\r\n print()\r\n print(\"You head down the path cautiously.\")\r\n time.sleep(2)\r\n print(\"You don't see anything deadly, so you keep going.\")\r\n print()\r\n time.sleep(2)\r\n\r\n correctPath = random.randint(1, 2)\r\n\r\n if chosenPath == str(correctPath):\r\n print(\"You find a pile of gold resting next to a priceless artifact.\")\r\n print(\"You're rich!\")\r\n time.sleep(2)\r\n else:\r\n print(\"You step on a plate that sinks into the ground.\")\r\n print(\"Dart traps go off in every direction and you\")\r\n print(\"are hit repeatedly. Your body is never found.\")\r\n time.sleep(2)\r\n\r\nplayAgain = \"yes\"\r\n\r\nwhile playAgain.lower() == \"yes\" or playAgain.lower() == \"y\":\r\n displayIntro()\r\n choice = choosePath()\r\n checkPath(choice)\r\n print()\r\n playAgain = input(\"Do you want to play again?: \")\r\n"
}
] | 4 |