', methods=['DELETE'])\n def del_question(id):\n error = False\n try:\n question = Question.query.filter_by(id=id).delete()\n db.session.commit()\n except:\n db.session.rollback()\n abort(404)\n finally:\n db.session.close()\n return jsonify({\n 'success': True\n })\n\n @app.route('/questions', methods=['POST'])\n def searchQuestion():\n search = request.get_json()[\"searchTerm\"]\n if search:\n get_questions = Question.query.filter(\n Question.question.ilike(f'%{search}%')).all()\n questions = []\n for q in get_questions:\n questions.append({\n 'id': q.id,\n 'question': q.question,\n 'category': q.category,\n 'answer': q.answer,\n 'difficulty': q.difficulty,\n 'type': Category.query.filter_by(id=q.category)\n .first().type\n })\n total_questions = len(get_questions)\n return jsonify({\n 'success': True,\n 'questions': questions,\n 'total_questions': total_questions\n })\n abort(404)\n\n @app.route('/questions/add', methods=['POST'])\n def addQuestion():\n error = False\n try:\n question = request.get_json()[\"question\"]\n answer = request.get_json()[\"answer\"]\n difficulty = request.get_json()[\"difficulty\"]\n category = request.get_json()[\"category\"]\n add = Question(\n question = question,\n answer = answer,\n category = category,\n difficulty =difficulty\n )\n print(question)\n add.insert()\n except:\n error = True\n finally:\n return jsonify({\n 'success': True,\n 'question': question,\n 'answer': answer,\n 'difficulty': difficulty,\n 'category': category\n })\n # abort(422)\n\n @app.route('/quizzes', methods=['POST'])\n def start_quiz():\n error = False\n try:\n category = request.get_json()[\"quiz_category\"]\n previousQuestions = request.get_json()[\"previous_questions\"]\n get_questions = ''\n print(category['id'])\n if category['id'] == 0:\n get_questions = Question.query.all()\n else:\n get_questions = Question.query.filter_by(\n category=category['id']).all()\n questions = []\n for n in get_questions:\n questions.append({\n 'id': n.id,\n 'question': n.question,\n 'answer': n.answer\n })\n total_questions = len(questions)\n except:\n abort(422)\n finally:\n db.session.close()\n return jsonify({\n 'success': True,\n 'question': random.choice(questions),\n 'previousQuestions': previousQuestions\n })\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Not found\"\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n @app.errorhandler(400)\n def bad_request(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n\n return app\n","repo_name":"shaimaaseyam/trivia","sub_path":"backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10056778893","text":"'''Print a map of the National Grid, optionally with an index of OS maps'''\nfrom __future__ import division, print_function\n\nimport argparse\nimport math\nimport os\nimport pkgutil\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\n\nimport osgb\n\n\ndef does_not_overlap_parent(key):\n \"See if an inset overlaps the parent sheet\"\n inset = osgb.map_locker[key]\n parent = osgb.map_locker[inset.parent]\n return (inset.bbox[0][0] > parent.bbox[1][0]\n or inset.bbox[1][0] < parent.bbox[0][0]\n or inset.bbox[1][1] < parent.bbox[0][1]\n or inset.bbox[0][1] > parent.bbox[1][1])\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='plot_maps',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"Toby Thurston -- August 2021\",\n description=textwrap.dedent('''\n plot_maps - make a nice index sheet for a map series.\n\n If you have a working TeXLive installation with MetaPost and GhostScript installed,\n you can use it to produce PDF index maps of the various map series included.'''))\n\n parser.add_argument('--series', type=str, choices='ABCHJ', help='Show map series')\n parser.add_argument('--paper', type=str.upper, choices=('A0', 'A1', 'A2', 'A3', 'A4'),\n default='A3', help='Output paper size')\n parser.add_argument('--pdf', type=str, help=\"Write to this file\")\n parser.add_argument('--towns', action='store_true', help=\"Show some town names\")\n parser.add_argument('--tests', action='store_true', help=\"Show the OSGB test locations\")\n parser.add_argument('--error', action='store_true', help=\"Show an indication of the round trip error\")\n parser.add_argument('--nogrid', action='store_true', help=\"Don't show the grid\")\n parser.add_argument('--nograt', action='store_true', help=\"Don't show the latitude / longitude graticule\")\n parser.add_argument('--nocoast', action='store_true', help=\"Don't show the coast lines\")\n parser.add_argument('--nomp', action='store_true', help=\"Don't try to run MP\")\n args = parser.parse_args()\n\n # Where shall we put the output?\n if args.pdf:\n pdffile = args.pdf\n else:\n if args.series:\n pdffile = \"Index_for_map_series_{}.pdf\".format(args.series)\n else:\n pdffile = \"National_grid.pdf\"\n\n # Set the scale according to the chosen paper size\n scale = {'A4': 1680, 'A3': 1189, 'A2': 840, 'A1': 597, 'A0': 420}[args.paper]\n\n # gather all the paths we will need from the map locker polygons\n path_for = dict() # a list of the actual MP maps\n sides = list() # a list of keys to path_for\n insets = list() # another list of (different) keys to path_for\n if args.series:\n for k, sheet in osgb.map_locker.items():\n # Skip maps not wanted\n if k[:1] not in args.series:\n continue\n\n # make the polygon into an MP path\n path_for[k] = '--'.join('({:.1f}, {:.1f})'.format(x[0]/scale, x[1]/scale)\n for x in sheet.polygon[:-1]) + '--cycle'\n # append the key to the appropriate list\n if sheet.parent == '':\n sides.append(k)\n else:\n insets.append(k)\n\n # MP rgbcolor tuples\n color_for = {\n 'A': '(224/255, 36/255, 114/255)', # Landranger pink\n 'B': '(221/255, 61/255, 31/255)', # Explorer orange\n 'C': '(228/255, 0, 28/255)', # Seventh series red\n 'H': '(128/255, 4/255, 36/255)', # Harvey dark red\n 'J': '(128/255, 4/255, 36/255)', # Harvey dark red\n }\n\n # open a tempory file for MP\n plotter = tempfile.NamedTemporaryFile(mode='wt', prefix='plot_maps_', suffix='.mp', dir='.', delete=False)\n\n # Starting making the MP file\n print('prologues := 3; outputtemplate := \"%j.eps\"; beginfig(1); defaultfont := \"phvr8r\";', file=plotter)\n\n # sides and insets will have anything in if we chose one or more series\n for k in sides + insets:\n print(\"fill {} withcolor (0.98, 0.906, 0.71);\".format(path_for[k]), file=plotter)\n\n if args.error:\n for x in range(70):\n e = x * 10000 + 5000\n for y in range(125):\n n = y * 10000 + 5000\n (ee, nn) = osgb.ll_to_grid(*osgb.grid_to_ll(e, n))\n h = math.sqrt((e-ee)**2+(n-nn)**2)\n if h > 0:\n print('drawdot ({:.1f}, {:.1f})'.format(e/scale, n/scale), file=plotter)\n print(' withpen pencircle scaled 4 withcolor {:.2f}[white, red];'.format(h*100), file=plotter)\n\n print('label.rt(\"Round trip error (mm)\" infont defaultfont scaled 0.6,', file=plotter)\n print('({:.1f}, {:.1f}));'.format(-176500/scale, 1255000/scale), file=plotter)\n for i in range(6):\n e = -120000 - i * 10000\n n = 1245000\n print('drawdot ({:.1f}, {:.1f})'.format(e/scale, n/scale), file=plotter)\n print(' withpen pencircle scaled 4 withcolor {:.2f}[white, red];'.format(i/5), file=plotter)\n print('label.bot(\"{}\" infont defaultfont scaled 0.6,'.format(2*i), file=plotter)\n print('({:.1f}, {:.1f}));'.format(e/scale, n/scale-2), file=plotter)\n\n if not args.nograt:\n print(\"drawoptions(withpen pencircle scaled 0.4);\", file=plotter)\n for lon in range(-10, 3):\n points = []\n for decilat in range(496, 613):\n e, n = osgb.ll_to_grid(decilat/10, lon)\n points.append('({:.1f}, {:.1f})'.format(e/scale, n/scale))\n\n print('draw ' + '--'.join(points) + ' withcolor .7[.5 green, white];', file=plotter)\n print('label.bot(\"{}\" & char 176, {}) withcolor .4 green;'.format(lon, points[0]), file=plotter)\n\n for lat in range(50, 62):\n points = []\n for decilon in range(-102, 23):\n e, n = osgb.ll_to_grid(lat, decilon/10)\n points.append('({:.1f}, {:.1f})'.format(e/scale, n/scale))\n\n print('draw ' + '--'.join(points) + ' withcolor .7[.5 green, white];', file=plotter)\n print('label.lft(\"{}\" & char 176, {}) withcolor .4 green;'.format(lat, points[0]), file=plotter)\n\n if not args.nogrid:\n print('drawoptions(withcolor .7 white);', file=plotter)\n print('z0=({:g}, {:g});'.format(700000/scale, 1250000/scale), file=plotter)\n print('label.llft(\"0\", origin) withcolor .5 white;', file=plotter)\n\n for i in range(8):\n e = i*100000\n print('t:={:g};draw (t, 0) -- (t, y0);'.format(e/scale), file=plotter)\n if i > 0:\n print('label.bot(\"{:d}\", (t, 0)) withcolor .5 white;'.format(i*100), file=plotter)\n for j in range(13):\n n = j*100000\n if i == 0:\n print('t:={:g};draw (0, t) -- (x0, t);'.format(n/scale), file=plotter)\n if j > 0:\n print('label.lft(\"{:d}\", (0, t)) withcolor .5 white;'.format(j*100), file=plotter)\n\n if i < 7 and j < 12:\n sq = osgb.format_grid(e, n, form='SS')\n print('label(\"{}\" infont \"phvr8r\" scaled {},'.format(sq, 3600/scale), file=plotter)\n print('({:.1f}, {:.1f})) withcolor 3/4;'.format((e+50000)/scale, (n+50000)/scale), file=plotter)\n # add HP as well\n print('label(\"HP\" infont \"phvr8r\" scaled {},'.format(3600/scale), file=plotter)\n print('({:.1f}, {:.1f})) withcolor 3/4;'.format((450000)/scale, (1250000)/scale), file=plotter)\n\n if not args.nocoast:\n coast_shapes = pkgutil.get_data('osgb', 'gb_coastline.shapes')\n if coast_shapes:\n print(\"drawoptions(withpen pencircle scaled 0.2 withcolor (0, 172/255, 226/255));\", file=plotter)\n poly_path = list()\n for line in coast_shapes.split(b'\\n'):\n if line.startswith(b'#'):\n print('draw ' + '--'.join(poly_path) + ';', file=plotter)\n del poly_path[:]\n elif line:\n try:\n (lon, lat) = (float(x) for x in line.split())\n except ValueError:\n print('????', line)\n (e, n) = osgb.ll_to_grid(lat, lon)\n poly_path.append('({:.1f}, {:.1f})'.format(e/scale, n/scale))\n\n assert not poly_path\n\n if args.towns:\n towns = {\n 'Aberdeen': (392500, 806500),\n 'Birmingham': (409500, 287500),\n 'Bristol': (360500, 175500),\n 'Cambridge': (546500, 258500),\n 'Canterbury': (614500, 157500),\n 'Cardiff': (318500, 176500),\n 'Carlisle': (339500, 555500),\n 'Edinburgh': (327500, 673500),\n 'Glasgow': (259500, 665500),\n 'Inverness': (266500, 845500),\n 'Leeds': (430500, 434500),\n 'Liverpool': (337500, 391500),\n 'London': (531500, 181500),\n 'Manchester': (383500, 398500),\n 'Newcastle': (425500, 564500),\n 'Oxford': (451500, 206500),\n 'Plymouth': (247500, 56500),\n 'Portsmouth': (465500, 101500),\n 'Salisbury': (414500, 130500),\n 'Sheffield': (435500, 387500),\n 'Worcester': (385500, 255500),\n }\n\n print(\"drawoptions(withcolor .7 white);defaultscale := 1/2;\", file=plotter)\n for t in towns:\n e, n = towns[t]\n print('dotlabel.top(\"{}\", ({:.1f}, {:.1f}));'.format(t, e/scale, n/scale), file=plotter)\n\n if args.tests:\n points = {\n 'TP01': (91492.146, 11318.803, \"St Mary's, Scilly\"),\n 'TP02': (170370.718, 11572.405, \"Lizard Point Lighthouse\"),\n 'TP03': (250359.811, 62016.569, \"Plymouth\"),\n 'TP04': (449816.371, 75335.861, \"St Catherine's Point Lighthouse\"),\n 'TP05': (438710.92, 114792.25, \"Former OSHQ\"),\n 'TP06': (292184.87, 168003.465, \"Nash Point Lighthouse\"),\n 'TP07': (639821.835, 169565.858, \"North Foreland Lighthouse\"),\n 'TP08': (362269.991, 169978.69, \"Brislington\"),\n 'TP09': (530624.974, 178388.464, \"Lambeth\"),\n 'TP10': (241124.584, 220332.641, \"Carmarthen\"),\n 'TP11': (599445.59, 225722.826, \"Colchester\"),\n 'TP12': (389544.19, 261912.153, \"Droitwich\"),\n 'TP13': (474335.969, 262047.755, \"Northampton\"),\n 'TP14': (562180.547, 319784.995, \"King's Lynn\"),\n 'TP15': (454002.834, 340834.943, \"Nottingham\"),\n 'TP16': (357455.843, 383290.436, \"STFC, Daresbury\"),\n 'TP17': (247958.971, 393492.909, \"Point Lynas Lighthouse, Anglesey\"),\n 'TP18': (247959.241, 393495.583, \"Point Lynas Lighthouse, Anglesey\"),\n 'TP19': (331534.564, 431920.794, \"Blackpool Airport\"),\n 'TP20': (422242.186, 433818.701, \"Pudsey\"),\n 'TP21': (227778.33, 468847.388, \"Isle of Man airport\"),\n 'TP22': (525745.67, 470703.214, \"Flamborough Head\"),\n 'TP23': (244780.636, 495254.887, \"Ramsey, Isle of Man\"),\n 'TP24': (339921.145, 556034.761, \"Carlisle\"),\n 'TP25': (424639.355, 565012.703, \"Newcastle University\"),\n 'TP26': (256340.925, 664697.269, \"Glasgow\"),\n 'TP27': (319188.434, 670947.534, \"Sighthill, Edinburgh\"),\n 'TP28': (167634.202, 797067.144, \"Mallaig Lifeboat Station\"),\n 'TP29': (397160.491, 805349.736, \"Girdle Ness Lighthouse\"),\n 'TP30': (267056.768, 846176.972, \"Inverness\"),\n 'TP31': (9587.909, 899448.986, \"Hirta, St Kilda\"),\n 'TP32': (71713.132, 938516.4, \"at sea, 7km S of Flannan\"),\n 'TP33': (151968.652, 966483.779, \"Butt of Lewis lighthouse\"),\n 'TP34': (299721.891, 967202.992, \"Dounreay Airfield\"),\n 'TP35': (330398.323, 1017347.016, \"Orkney Mainland\"),\n 'TP36': (261596.778, 1025447.602, \"at sea, 1km NW of Sule Skerry\"),\n 'TP37': (180862.461, 1029604.114, \"at sea, 3km south of Rona\"),\n 'TP38': (421300.525, 1072147.239, \"Fair Isle\"),\n 'TP39': (440725.073, 1107878.448, \"Sumburgh Head\"),\n 'TP40': (395999.668, 1138728.951, \"Foula\"),\n }\n\n print(\"drawoptions(withcolor .5[red, white]);\", file=plotter)\n for t in points:\n e, n, name = points[t]\n print(\"draw unitsquare shifted -(1/2, 1/2) rotated 45 scaled 3\", file=plotter)\n print(\"shifted ({:.1f}, {:.1f});\".format(e/scale, n/scale), file=plotter)\n\n if args.series and sides: # sides will be empty if none of the maps matched series_wanted\n\n print(\"drawoptions(withpen pencircle scaled 0.2);defaultscale:={:.2f};\".format(666/scale), file=plotter)\n\n for k in sides:\n series = k[:1]\n map_color = color_for[series] if series in color_for else 'black'\n print(\"draw {} withcolor {};\".format(path_for[k], map_color), file=plotter)\n\n sheet = osgb.map_locker[k]\n x = (sheet.bbox[0][0] + sheet.bbox[1][0]) / 2 / scale\n y = (sheet.bbox[0][1] + sheet.bbox[1][1]) / 2 / scale\n\n if sheet.number.startswith('OL'):\n map_color = '(.5, .5, 1)'\n y += 3\n\n print('label(\"{}\", ({}, {})) withcolor .76[white, {}];'.format(sheet.number, x, y, map_color), file=plotter)\n\n print('path p, q;', file=plotter)\n for k in insets:\n series = k[:1]\n map_color = color_for[series] if series in color_for else 'black'\n print(\"p:={};\".format(path_for[k]), file=plotter)\n parent_key = osgb.map_locker[k].parent\n if does_not_overlap_parent(k):\n print('q:={};'.format(path_for[parent_key]), file=plotter)\n print(\"draw center p -- center q cutbefore p cutafter q\", file=plotter)\n print(\"dashed evenly scaled 1/3 withcolor {};\".format(map_color), file=plotter)\n print(\"draw p withcolor {};\".format(map_color), file=plotter)\n\n y = 1300000/scale\n for s in args.series:\n color = color_for[s] if s in color_for else 'black'\n title = 'label.rt(\"{} sheet index\" infont defaultfont scaled {:.1f}, (0, {:.1f})) withcolor {};'.format(\n osgb.name_for_map_series[s], 2000/scale, y, color)\n print(title, file=plotter)\n y -= 24\n\n # add sheet names for Harvey maps\n if args.series in 'HJ':\n print(\"defaultscale:={:.1f};\".format(2000/scale), file=plotter)\n x = 510000/scale\n y = 515000/scale\n print('fill unitsquare xscaled {:.1f}'.format(200000/scale), file=plotter)\n print('yscaled {:.1f}'.format((12000*len(sides)+4000)/scale), file=plotter)\n print('shifted ({:.1f}, {:.1f}) withcolor background;'.format(x-5, y-3), file=plotter)\n for k in sorted(sides, reverse=True):\n sheet = osgb.map_locker[k]\n print('draw \"{} {}\"'.format(sheet['number'], sheet['title']), file=plotter)\n print('infont defaultfont shifted ({:.1f}, {:.1f});'.format(x, y), file=plotter)\n y += 12000/scale\n\n # Add a margin\n print('z1 = center currentpicture;', file=plotter)\n print('setbounds currentpicture to bbox currentpicture shifted -z1 scaled 1.05 shifted z1;', file=plotter)\n\n # Finish the MP input and close the file\n print(\"endfig;end.\", file=plotter)\n plotter.close()\n\n # Now deal with MP (unless asked not to)\n if not args.nomp:\n try:\n subprocess.check_call(['mpost', plotter.name])\n except subprocess.CalledProcessError as e:\n print('Metapost failed', file=sys.stderr)\n raise e\n\n epsfile = plotter.name[:-2] + 'eps'\n logfile = plotter.name[:-2] + 'log'\n\n try:\n subprocess.check_call(['epstopdf', \"-o={}\".format(pdffile), epsfile])\n except subprocess.CalledProcessError as e:\n print('epdtopdf failed', file=sys.stderr)\n raise e\n try:\n os.unlink(epsfile)\n except OSError as e:\n print(\"Failed to delete temporary file: {}\".format(epsfile), file=sys.stderr)\n raise e\n\n try:\n os.unlink(logfile)\n except OSError as e:\n print(\"Failed to delete temporary file: {}\".format(logfile), file=sys.stderr)\n raise e\n\n try:\n os.unlink(plotter.name)\n except OSError as e:\n print('Failed to delete MP file', file=sys.stderr)\n raise e\n\n print(\"Created \" + pdffile)\n else:\n print(\"MP source written to \" + plotter.name)\n","repo_name":"thruston/grid-banger","sub_path":"scripts/plot_maps.py","file_name":"plot_maps.py","file_ext":"py","file_size_in_byte":16837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"9388004483","text":"# -*- coding: utf-8 -*-\r\n\r\nimport boto3\r\n#from config import S3_KEY, S3_SECRET, S3_BUCKET\r\n\r\ns3 = boto3.client(\r\n 's3',\r\n aws_access_key_id=\"AKIATXCWEQVALA7AD5QM\",\r\n aws_secret_access_key=\"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\"\r\n)\r\n\r\ndef upload_file_s3(file,bucket_name,acl=\"public-read\"):\r\n try:\r\n s3.upload_fileobj(\r\n file,\r\n bucket_name,\r\n file.filename,\r\n ExtraArgs={\r\n \"ACL\":acl,\r\n \"ContentType\":file.content_type\r\n }\r\n )\r\n objs=s3.list_objects(Bucket=bucket_name)\r\n all_files=objs[\"Contents\"]\r\n return all_files\r\n except Exception as e:\r\n print(\"Something happened :\",e)\r\n return e\r\n #return \"{}{}\".format(\"https://textractpython.s3.amazonaws.com/\",file.filename)\r\n \r\n\r\n\r\n\r\n","repo_name":"pravee2667/idcpascan","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34271176977","text":"import json\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport sys\n\nsys.path.append(r\"/home/patrik/projects/Pandas-Bokeh\")\nimport pandas_bokeh\nimport os\n\ndirectory = os.path.dirname(__file__)\ntest_sets_directory = os.path.join(\n os.path.dirname(directory), \"Documentation\", \"Testdata\"\n)\nos.makedirs(os.path.join(directory, \"Plots\"), exist_ok=True)\n\n\ndef test_geolayers_simple():\n \"Tests for simple\"\n\n # Read in GeoJSON from URL:\n df_states = gpd.read_file(\n r\"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/states/states.geojson\"\n )\n\n figure = df_states.plot_bokeh(simplify_shapes=10000, show_figure=False)\n\n with open( # +ä\n os.path.join(directory, \"Plots\", \"Geolayers_Simple.html\"), \"w\"\n ) as f:\n f.write(pandas_bokeh.embedded_html(figure))\n\n assert True\n\n\ndef test_geolayers_slider():\n \"Tests for mutiple geolayers\"\n\n # Read in GeoJSON from URL:\n df_states = gpd.read_file(\n os.path.join(test_sets_directory, \"states\", \"states.geojson\")\n )\n df_cities = gpd.read_file(\n os.path.join(\n test_sets_directory,\n \"populated places\",\n \"ne_10m_populated_places_simple_bigcities.geojson\",\n )\n )\n df_cities[\"size\"] = df_cities.pop_max / 400000\n\n # Calculate change of population relative to 2010:\n for i in range(8):\n df_states[\"Delta_Population_201%d\" % i] = (\n (df_states[\"POPESTIMATE201%d\" % i] / df_states[\"POPESTIMATE2010\"]) - 1\n ) * 100\n\n # Specify slider columns:\n slider_columns = [\"Delta_Population_201%d\" % i for i in range(8)]\n\n # Specify slider-range (Maps \"Delta_Population_2010\" -> 2010,\n # \"Delta_Population_2011\" -> 2011, ...):\n slider_range = range(2010, 2018)\n\n # Make slider plot:\n\n # Plot shapes of US states (pass figure options to this initial plot):\n figure = df_states.plot_bokeh(\n figsize=(900, 600),\n simplify_shapes=5000,\n slider=slider_columns,\n slider_range=slider_range,\n slider_name=\"Year\",\n colormap=\"Inferno\",\n hovertool_columns=[\"STATE_NAME\"] + slider_columns,\n title=\"Change of Population [%]\",\n show_figure=False,\n )\n\n # Plot cities as points on top of the US states layer by passing the figure:\n html_multilayer_slider = df_cities.plot_bokeh(\n figure=figure, # <== pass figure here!\n category=\"pop_max\",\n colormap=\"Viridis\",\n colormap_uselog=True,\n size=\"size\",\n hovertool_string=\"\"\"@name
\n Population: @pop_max
\"\"\",\n marker=\"inverted_triangle\",\n legend=\"Cities\",\n show_figure=False,\n return_html=True,\n )\n\n with open(\n os.path.join(directory, \"Plots\", \"Multiple_Geolayers_Slider.html\"), \"w\"\n ) as f:\n f.write(html_multilayer_slider)\n\n\n# assert False # ASSERT IS FALSE BECAUSE SLIDER IS NOT VISIBLE RIGHT NOW:\n","repo_name":"CloudBreadPaPa/Pandas-Bokeh","sub_path":"Tests/test_GeoPandasBokeh.py","file_name":"test_GeoPandasBokeh.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"17078001592","text":"import copy\n\nfrom .plot import BackendBase\nimport ipyvolume.pylab as p3\nimport ipyvolume.examples\nimport traitlets\nimport vaex.dataset\nimport ipywidgets as widgets\nfrom IPython.display import HTML, display_html, display_javascript, display\nimport numpy as np\nfrom .utils import debounced\n\n\ndef xyz(shape=128, limits=[-3, 3], spherical=False, sparse=True, centers=False):\n dim = 3\n try:\n shape[0]\n except:\n shape = [shape] * dim\n try:\n limits[0][0]\n except:\n limits = [limits] * dim\n if centers:\n v = [slice(vmin + (vmax - vmin) / float(N) / 2, vmax - (vmax - vmin) / float(N) / 4, (vmax - vmin) / float(N)) for (vmin, vmax), N in zip(limits, shape)]\n else:\n v = [slice(vmin, vmax + (vmax - vmin) / float(N) / 2, (vmax - vmin) / float(N - 1)) for (vmin, vmax), N in zip(limits, shape)]\n if sparse:\n x, y, z = np.ogrid.__getitem__(v)\n else:\n x, y, z = np.mgrid.__getitem__(v)\n if spherical:\n r = np.linalg.norm([x, y, z])\n theta = np.arctan2(y, x)\n phi = np.arccos(z / r)\n return x, y, z, r, theta, phi\n else:\n return x, y, z\n\n\nclass IpyvolumeBackend(BackendBase):\n dim = 3\n\n @staticmethod\n def wants_colors():\n return False\n\n # def __init__(self):\n # self._first_time = Tr\n def create_widget(self, output, plot, dataset, limits):\n self.output = output\n self.plot = plot\n self.dataset = dataset\n self.limits = np.array(limits).tolist()\n self._first_time = True\n self._first_time_vector = True\n self.figure = p3.figure()\n self.widget = p3.gcc()\n\n self.figure.observe(self._update_limits, 'xlim ylim zlim'.split())\n\n def _update_limits(self, *args):\n with self.output:\n # self._progressbar.cancel()\n limits = copy.deepcopy(self.limits)\n limits[0] = self.figure.xlim\n limits[1] = self.figure.ylim\n limits[2] = self.figure.zlim\n self.limits = limits\n\n\n @debounced(0.1, method=True)\n def update_image(self, intensity_image):\n with self.output:\n with self.figure:\n limits = copy.deepcopy(self.limits)\n if self._first_time:\n self.volume = p3.volshow(intensity_image.T, controls=self._first_time, extent=limits)\n if 1: #hasattr(self.figure, 'extent_original'): # v0.5 check\n self.volume.data_original = None\n self.volume.data = intensity_image.T\n self.volume.extent = copy.deepcopy(self.limits)\n self.volume.data_min = np.nanmin(intensity_image)\n self.volume.data_max = np.nanmax(intensity_image)\n self.volume.show_min = self.volume.data_min\n self.volume.show_max = self.volume.data_max\n\n self._first_time = False\n self.figure.xlim = limits[0]\n self.figure.ylim = limits[1]\n self.figure.zlim = limits[2]\n # p3.xlim(*self.limits[0])\n # p3.ylim(*self.limits[1])\n # p3.zlim(*self.limits[2])\n\n def update_vectors(self, vcount, vgrids, vcount_limits):\n vx, vy, vz = vgrids[:3]\n if vx is not None and vy is not None and vz is not None and vcount is not None:\n vcount = vcount[-1] # no multivolume render, just take the last selection\n vx = vx[-1]\n vy = vy[-1]\n vz = vz[-1]\n ok = np.isfinite(vx) & np.isfinite(vy) & np.isfinite(vz)\n vcount_min = None\n vcount_max = None\n if vcount_limits is not None:\n try:\n vcount_min, vcount_max = vcount_limits\n except:\n vcount_min = self.vcount_limits\n if vcount_min is not None:\n ok &= (vcount > vcount_min)\n if vcount_max is not None:\n ok &= (vcount < vcount_max)\n # TODO: we assume all dimensions are equal length\n x, y, z = xyz(vx.shape[0], limits=self.limits, sparse=False, centers=True)\n v1d = [k[ok] for k in [x, y, z, vx, vy, vz]]\n vsize = 5\n vcolor = \"grey\"\n if self._first_time_vector:\n self._first_time_vector = False\n self.quiver = p3.quiver(*v1d, size=vsize, color=vcolor)\n else:\n with self.quiver.hold_trait_notifications():\n self.quiver.x = x[ok]\n self.quiver.y = y[ok]\n self.quiver.z = z[ok]\n self.quiver.vx = vx[ok]\n self.quiver.vy = vy[ok]\n self.quiver.vz = vz[ok]\n\n # def show(self):\n # container = p3.gcc()\n # vbox = widgets.VBox([container, self.progress, widgets.VBox(self.tools), self.output])\n # display(vbox)\n #\n # def create_tools(self):\n # self.tools = []\n #\n # callback = self.dataset.signal_selection_changed.connect(lambda *x: self.update_grid())\n #\n # def cleanup(callback=callback):\n # self.dataset.signal_selection_changed.disconnect(callback=callback)\n #\n # self._cleanups.append(cleanup)\n #\n # def get_binby(self):\n # return [self.x, self.y, self.z]\n","repo_name":"vaexio/vaex","sub_path":"packages/vaex-jupyter/vaex/jupyter/ipyvolume.py","file_name":"ipyvolume.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","stars":8057,"dataset":"github-code","pt":"53"}
+{"seq_id":"25413908199","text":"\"\"\"\nProblem 2\n\nTake a string user input and using a for loop\nprint all the vowels in the string\n\"\"\"\n\nuser_word = input(\"Give me a word. >> \")\nvowels = \"aeiou\"\n\n\"\"\"\nfor i in user_word:\n if i in vowels:\n print(i)\n\"\"\"\n\"\"\"\nProblem 3\n\nTake a string user input and using a for loop print all consonants in the string\n\n\"\"\"\nfor k in user_word:\n if k not in vowels:\n print(k)\n","repo_name":"SummerLyn/devcamp_2016","sub_path":"python/day8/warm_up.py","file_name":"warm_up.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"581022447","text":"import argparse\nfrom output_viewer import index as viewer\nfrom output_viewer.build import build_viewer\nimport os\nimport glob\nimport datetime\nimport json\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"image_directory\", default=os.getcwd(), nargs=\"?\", help=\"Path to the directory containing output. Defaults to current directory.\")\nparser.add_argument(\"--separator\", default=\"_\", help=\"Character that separates relevant components of the filename\")\nparser.add_argument(\"--order\", default=None, help=\"Order of filename components to group the output\")\nparser.add_argument(\"--group\", default=None, help=\"Components to combine\")\nparser.add_argument(\"--suffix_sep\", default=\".\", help=\"Character that separates suffixes (multiple files for one col)\")\nparser.add_argument(\"--suffix\", default=None, help=\"Suffix to use as the default output file for a given column.\")\nparser.add_argument(\"--title\", default=None, help=\"Title of package (defaults to directory name)\")\nparser.add_argument(\"--dataset\", default=None, help=\"Input dataset name; defaults to current date.\")\nargs = parser.parse_args()\n\nfiles = [f for f in os.listdir(args.image_directory) if f[0] != '.' and not f.endswith(\".html\") and f != \"index.json\" and not os.path.isdir(os.path.join(args.image_directory, f))]\nindexed = {}\nfor f in files:\n parts = f.split(args.separator)\n c = parts[-1].split(args.suffix_sep)\n parts[-1] = c[0]\n\n if args.group and len(parts) > 4:\n group = [int(i) for i in args.group.split(\",\")]\n p = [parts[g] for g in group]\n p = \" \".join(p)\n merged = []\n for i in range(len(parts)):\n if i not in group:\n merged.append(parts[i])\n elif p is not None:\n merged.append(p)\n p = None\n parts = merged\n\n if args.order:\n order = [int(i) for i in args.order.split(\",\")]\n fix = []\n for o in order:\n while o >= len(parts):\n o -= 1\n fix.append(o)\n order = fix\n reordered = [parts[i] for i in order]\n for i in range(len(parts)):\n if i not in order:\n reordered.append(parts[i])\n parts = reordered\n\n subdict = indexed\n for p in parts[:-1]:\n d = subdict.get(p, {})\n subdict[p] = d\n subdict = d\n files = subdict.get(parts[-1], [])\n files.append(f)\n subdict[parts[-1]] = files\n\ntitle = args.title\nif title is None:\n title = os.path.basename(os.path.abspath(args.image_directory))\n\ndataset = args.dataset\nif dataset is None:\n d = datetime.date.today()\n dataset = \"%d-%d-%d\" % (d.year, d.month, d.day)\n\nindex = viewer.OutputIndex(title, version=dataset)\nfor page, groups in list(indexed.items()):\n p = viewer.OutputPage(page)\n index.addPage(p)\n for group, rows in list(groups.items()):\n g = viewer.OutputGroup(group)\n group_ind = len(p.groups)\n p.addGroup(g)\n for row, columns in list(rows.items()):\n cols = []\n for col, files in list(columns.items()):\n default_file = None\n for f in files:\n if args.suffix:\n if f.endswith(args.suffix):\n default_file = f\n break\n else:\n if default_file is None or len(f) < len(default_file):\n default_file = f\n f = viewer.OutputFile(default_file, title=col, other_files=[{\"url\": f} for f in files if f != default_file])\n cols.append(f)\n r = viewer.OutputRow(row, cols)\n p.addRow(r, group_ind)\n\nindex_path = os.path.abspath(args.image_directory + \"/index.json\")\nindex.toJSON(index_path)\nbuild_viewer(index_path)\nshould_open = input(\"Open viewer in browser? [y]/n: \")\nif should_open != \"n\":\n import webbrowser\n webbrowser.open(\"file://\" + os.path.abspath(args.image_directory + \"/index.html\"))\n","repo_name":"ESGF/output_viewer","sub_path":"scripts/quick_view.py","file_name":"quick_view.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39150904233","text":"from os import system, name \n\nclass ListElement:\n def __init__(self, text=\"\", done = False):\n self.done = False\n self.text = text\n\nclass List:\n\n def __init__(self):\n self.elementArr = [];\n\n def push(self, element):\n self.elementArr.append(element)\n\n def pop(self, index = 0):\n self.elementArr.pop(index)\n \n def show(self):\n index = 1\n state = {\n True: \"wykonano\",\n False: \"do zrobienia\"\n }\n for element in self.elementArr:\n print(str(index) + \".\", element.text + \":\" , state[element.done])\n index += 1\n\n def showElement(self, index):\n state = {\n True: \"wykonano\",\n False: \"do zrobienia\"\n }\n print(str(index+1) + \".\", self.elementArr[index].text + \":\", state[self.elementArr[index].done])\n\n def setText(self, index, text):\n self.elementArr[index].text = text\n\n def setDone(self, index, done=True):\n self.elementArr[index].done = done\n\n def addElement(self, text = \"\", done = False):\n self.push(ListElement(text,done))\n\n def getLength(self):\n return len(self.elementArr)\n\nlista = List()\n\ndef cls():\n if name == 'nt':\n system('cls')\n else:\n system('clear')\n\ndef create():\n text = input(\">>Podaj nazwę zadania: \")\n lista.addElement(text);\n print(\"Dodano nowy element!\")\n input(\"Naciśnij Enter aby kontnuować...\")\n\ndef show():\n cls()\n print(\"---Lista Zadań---\")\n lista.show()\n print(\"\")\n print(\"-----------------\")\n\ndef delete():\n show()\n print(str(lista.getLength()+1)+\". Powrót\")\n while True:\n inp = input(\">>Wybierz element do usunięcia: \")\n if inp.isdigit():\n index = int(inp)\n else:\n index = -1\n index += -1\n if index >= 0 and index <= lista.getLength():\n break\n print(\"Brak opcji o numerze\",index+1)\n if index == lista.getLength():\n return\n lista.pop(index)\n print(\"Pomyślnie usunięto\", str(index+1), \"element!\")\n input(\">>Naciśnij Enter aby kontynuować...\")\n\ndef edit():\n if lista.getLength() == 0:\n return\n show()\n print(str(lista.getLength()+1)+\". Powrót\")\n while True:\n inp = input(\">>Wybierz element do modyfikacji: \")\n if inp.isdigit():\n index = int(inp)\n else:\n index = -1\n index += -1\n if index >= 0 and index <= lista.getLength():\n break\n print(\"Brak elementu o numerze\",index+1)\n if index == lista.getLength():\n return\n cls()\n print(\"Edytowany element:\")\n lista.showElement(index);\n editMenu(lista.elementArr[index].done == False)\n choise = input(\">>Wybierz akcję: \")\n if choise == '1':\n text = input(\">>Nowa nazwa: \")\n lista.setText(index, text)\n\n elif choise == '2':\n lista.setDone(index, lista.elementArr[index].done == False)\n\ndef menu():\n print(\"Dostępne akcje:\")\n print(\"1. Dodawanie Nowego Elementu\")\n print(\"2. Usuwanie Elementu\")\n print(\"3. Edytuj Element\")\n print(\"4. Zakończ Program\")\n\ndef editMenu(state):\n print(\"\")\n print(\"Dostępne modyfikacje:\")\n print(\"1. Edycja nazwy\")\n print(\"2. Zmień stan na \\\"\" + {\n True: \"wykonany\",\n False: \"do zrobienia\"}[state == True] + \"\\\"\")\n print(\"3. Powrót\")\n \n\nwhile True:\n show()\n menu()\n choise = input(\">>Twój wybór: \")\n if choise == '1':\n create()\n\n elif choise == '2':\n delete()\n\n elif choise == '3':\n edit()\n elif choise == '4':\n break\n\n\n\n","repo_name":"tad1/repozytorium","sub_path":"Sprawozdanie 2/ToDoList.py","file_name":"ToDoList.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"3815529669","text":"import random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nimport scipy.stats as st\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\nimport k_means_and_GMM as kg\n\nK = 3\nn = 50\n\n\ndef iris_data():\n # 处理数据 拿出数据和标签\n column = [\"s_length\", \"s_width\", \"p_length\", \"p_width\", \"class\"]\n data = pd.read_csv(\"data/iris.data.csv\", engine='python', names=column)\n std = StandardScaler()\n X = std.fit_transform(np.array(data[column[0:4]]))\n y = np.array(data[column[4]])\n return X, y\n\n\ndef k_means(X):\n print(\"k_means:\")\n mean, X_flag = kg.k_means(X, K)\n print(mean)\n X = np.hstack((X, X_flag.reshape(-1, 1)))\n kg.cal_accuracy(X, K)\n return mean\n\n\ndef gmm(X):\n print(\"GMM:\")\n X, y_z, mean = kg.gmm(X, K)\n label = np.zeros(X.shape[0])\n for i in range(K):\n label[i * n: (i + 1) * n] = i\n X = np.hstack((X, label.reshape(-1, 1)))\n for i in range(X.shape[0]):\n X[i, -1] = np.argmax(y_z[i, :])\n print(mean)\n kg.cal_accuracy(X, K)\n\n\ndef main():\n X, y = iris_data()\n k_means(X)\n gmm(X)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"1190200610/mechine_learning","sub_path":"iris_data.py","file_name":"iris_data.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27942847138","text":"from django.shortcuts import render,redirect\nfrom django import views\nfrom django.views import View\nfrom django.contrib import messages\n\n# TESTING \nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom .models import *\n\n# Create your views here.\nclass Home(View):\n def get(self, request):\n return render(request, 'Home/home.html')\n \nclass OrderEntry(View):\n def get(self, request):\n buyers = LibBuyer.objects.all()\n styles = LibStyle.objects.all()\n company = LibCompany.objects.all()\n departments = LibDepartment.objects.all()\n sub_department = LibSubDepartment.objects.all()\n prod_cate = LibProductCate.objects.all()\n seasons = LibSeason.objects.all()\n regions = LibRegion.objects.all()\n agents= LibAgent.objects.all()\n clients = LibClient.objects.all()\n units = LibUnit.objects.all()\n employee = HRmEmployee.objects.all()\n currency = LibCurrency.objects.all()\n all_orders = OrderEntryInfo.objects.all()\n\n context = {\n 'buyers':buyers,\n 'styles':styles,\n 'company':company,\n 'departments':departments,\n 'sub_department':sub_department,\n 'prod_cate':prod_cate,\n 'seasons':seasons,\n 'regions':regions,\n 'agents':agents,\n 'clients':clients,\n 'units':units,\n 'employee':employee,\n 'currency':currency,\n 'all_orders':all_orders\n }\n return render(request, 'Order_Entry/order_entry_form.html', context)\n\n def post(self, request):\n job_no = request.POST['job_no']\n\n buyer_name = request.POST['buyer_name']\n style_name = request.POST['style_name']\n order_repeat_no = request.POST['order_repeat_no']\n\n company_name = request.POST['company_name']\n working_company_location = request.POST['working_company_location']\n file_no = request.POST['file_no']\n\n projected_job_no = request.POST['projected_job_no']\n department_name = request.POST['department_name']\n\n sub_department_name = request.POST['sub_department_name']\n product_cate = request.POST['product_cate']\n season_name = request.POST['season_name']\n region_name = request.POST['region_name']\n agent_name = request.POST['agent_name']\n client_name = request.POST['client_name']\n quality_label = request.POST['quality_label']\n unit_name = request.POST['unit_name']\n\n smv = request.POST['smv']\n buying_house_merchandiser = request.POST['buying_house_merchandiser']\n ship_mode = request.POST['ship_mode']\n emp_code = request.POST['emp_code']\n\n ready_for_bom = request.POST['ready_for_bom']\n copy_from_job_no = request.POST['copy_from_job_no']\n file_name_link = request.POST['file_name_link']\n internal_ref_no = request.POST['internal_ref_no']\n currency_code = request.POST['currency_code']\n order_type = request.POST['order_type']\n\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n remarks = request.POST['remarks']\n\n order_info = OrderEntryInfo(\n job_no = job_no,\n buyer_name = LibBuyer.objects.get(buyer_name=buyer_name),\n style_name = LibStyle.objects.get(style_name=style_name),\n order_repeat_no = order_repeat_no,\n company_name = LibCompany.objects.get(company_name=company_name),\n working_company_location = working_company_location,\n file_no = file_no,\n projected_job_no = projected_job_no,\n department_name = LibDepartment.objects.get(department_name=department_name),\n sub_department_name = LibSubDepartment.objects.get(sub_department_name=sub_department_name),\n product_cate = LibProductCate.objects.get(product_cate=product_cate),\n season_name = LibSeason.objects.get(season_name=season_name),\n region_name = LibRegion.objects.get(region_name=region_name),\n agent_name = LibAgent.objects.get(agent_name=agent_name),\n client_name = LibClient.objects.get(client_name=client_name),\n quality_label = quality_label,\n unit_name = LibUnit.objects.get(unit_name=unit_name),\n smv = smv,\n buying_house_merchandiser = buying_house_merchandiser,\n ship_mode = ship_mode,\n emp_code = HRmEmployee.objects.get(emp_code=emp_code),\n ready_for_bom = ready_for_bom,\n copy_from_job_no = copy_from_job_no,\n file_name_link = file_name_link,\n internal_ref_no = internal_ref_no,\n currency_code = LibCurrency.objects.get(currency_code=currency_code),\n order_type = order_type,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n remarks = remarks\n )\n\n order_info.save()\n messages.success(request, 'Congratulations! Order information has been Added Successfully...')\n buyers = LibBuyer.objects.all()\n styles = LibStyle.objects.all()\n company = LibCompany.objects.all()\n departments = LibDepartment.objects.all()\n sub_department = LibSubDepartment.objects.all()\n prod_cate = LibProductCate.objects.all()\n seasons = LibSeason.objects.all()\n regions = LibRegion.objects.all()\n agents= LibAgent.objects.all()\n clients = LibClient.objects.all()\n units = LibUnit.objects.all()\n employee = HRmEmployee.objects.all()\n currency = LibCurrency.objects.all()\n all_orders = OrderEntryInfo.objects.all()\n\n context = {\n 'buyers':buyers,\n 'styles':styles,\n 'company':company,\n 'departments':departments,\n 'sub_department':sub_department,\n 'prod_cate':prod_cate,\n 'seasons':seasons,\n 'regions':regions,\n 'agents':agents,\n 'clients':clients,\n 'units':units,\n 'employee':employee,\n 'currency':currency,\n 'all_orders':all_orders\n }\n return render(request, 'Order_Entry/order_entry_form.html', context)\n\nclass PoDetails(View):\n def get(self, request):\n numbers = OmPoBreakDown.objects.all()\n po_job = WoPOCountryDetails.objects.all()\n po_info = OmPoDetailsMaster.objects.all()\n context = {\n 'numbers':numbers,\n 'po_job':po_job,\n 'po_info': po_info\n }\n return render(request, 'Order_Entry/po_details.html', context)\n def post(self, request):\n job_no_mst = request.POST['job_no_mst']\n breakdown_type = request.POST['breakdown_type']\n round_type = request.POST['round_type']\n copy_from = request.POST['copy_from']\n po_number = request.POST['po_number']\n job_no = request.POST['job_no']\n po_received_date = request.POST['po_received_date']\n po_quantity = request.POST['po_quantity']\n unit_price = request.POST['unit_price']\n set_pc_rate = request.POST['set_pc_rate']\n set_quantity = request.POST['set_quantity']\n set_total_quantity = request.POST['set_total_quantity']\n po_total_price = request.POST['po_total_price']\n shipment_date = request.POST['shipment_date']\n original_shipment_date = request.POST['original_shipment_date']\n avg_fob = request.POST['avg_fob']\n up_charge = request.POST['up_charge']\n ctn = request.POST['ctn']\n projected_po_number = request.POST['projected_po_number']\n actual_po_number = request.POST['actual_po_number']\n t_year = request.POST['t_year']\n t_month = request.POST['t_month']\n is_deleted = request.POST['is_deleted']\n is_countable = request.POST['is_countable']\n is_projected = request.POST['is_projected']\n remarks = request.POST['remarks']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_locked = request.POST['is_locked']\n po_status = request.POST['po_status']\n\n po_details_info = OmPoDetailsMaster(\n job_no_mst = job_no_mst,\n breakdown_type = breakdown_type,\n round_type = round_type,\n copy_from = copy_from,\n po_number = OmPoBreakDown.objects.get(po_number=po_number),\n job_no = WoPOCountryDetails.objects.get(job_no=job_no),\n\n \n po_received_date = po_received_date,\n po_quantity = po_quantity,\n unit_price = unit_price,\n set_pc_rate = set_pc_rate,\n\n set_quantity = set_quantity,\n set_total_quantity = set_total_quantity,\n po_total_price = po_total_price,\n shipment_date = shipment_date,\n original_shipment_date = original_shipment_date,\n avg_fob = avg_fob,\n up_charge = up_charge,\n ctn = ctn,\n projected_po_number = projected_po_number,\n actual_po_number = actual_po_number,\n t_year = t_year,\n t_month = t_month,\n \n is_deleted = is_deleted,\n is_countable = is_countable,\n is_projected = is_projected,\n remarks = remarks,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_locked = is_locked,\n po_status = po_status\n\n )\n po_details_info.save()\n messages.success(request, 'Congratulations! Po Detail information has been Added Successfully...')\n numbers = OmPoBreakDown.objects.all()\n po_job = WoPOCountryDetails.objects.all()\n po_info = OmPoDetailsMaster.objects.all()\n context = {\n 'numbers':numbers,\n 'po_job':po_job,\n 'po_info': po_info\n }\n return render(request, 'Order_Entry/po_details.html', context)\n\nclass POBreakdownInfo(View):\n def get(self, request):\n po_breakdown = OmPoBreakDown.objects.all()\n context = {\n 'po_breakdown': po_breakdown\n }\n return render(request, 'Order_Entry/po_breakdown.html', context)\n \n def post(self, request):\n job_no_mst = request.POST['job_no_mst']\n po_number = request.POST['po_number']\n po_quantity = request.POST['po_quantity']\n plan_quantity = request.POST['plan_quantity']\n shipped_date = request.POST['shipped_date']\n po_status = request.POST['po_status']\n is_deleted = request.POST['is_deleted']\n is_countable = request.POST['is_countable']\n is_projected = request.POST['is_projected']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_locked = request.POST['is_locked']\n remarks = request.POST['remarks']\n\n po_breakdown_info = OmPoBreakDown(\n job_no_mst = job_no_mst,\n po_number = po_number,\n po_quantity = po_quantity,\n plan_quantity = plan_quantity,\n shipped_date = shipped_date,\n po_status = po_status,\n is_deleted = is_deleted,\n is_countable = is_countable,\n is_projected = is_projected,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_locked = is_locked,\n remarks = remarks\n\n )\n po_breakdown_info.save()\n messages.success(request, 'Congratulations! Po Breakdown information has been Added Successfully...')\n po_breakdown = OmPoBreakDown.objects.all()\n context = {\n 'po_breakdown': po_breakdown\n }\n return render(request, 'Order_Entry/po_breakdown.html', context)\n\nclass PoCountryInfo(View):\n def get(self, request):\n po_numbers = OmPoBreakDown.objects.all()\n country_ids = LibCountry.objects.all()\n product_ids = InvProductInfo.objects.all()\n country_info = WoPOCountryDetails.objects.all()\n context = {\n 'po_numbers': po_numbers,\n 'country_ids': country_ids,\n 'product_ids': product_ids,\n 'country_info': country_info\n }\n return render(request, 'Order_Entry/po_country_details.html', context)\n\n def post(self, request):\n job_no = request.POST['job_no']\n po_number = request.POST['po_number']\n country_code = request.POST['country_code']\n code = request.POST['code']\n product_code = request.POST['product_code']\n cut_off = request.POST['cut_off']\n po_quantity = request.POST['po_quantity']\n plan_quantity = request.POST['plan_quantity']\n shipped_date = request.POST['shipped_date']\n is_projected = request.POST['is_projected']\n projected_id = request.POST['projected_id']\n agent_name = request.POST['agent_name']\n exporting_item_catg = request.POST['exporting_item_catg']\n is_deleted = request.POST['is_deleted']\n status_active = request.POST['status_active']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n\n po_country_info = WoPOCountryDetails(\n job_no = job_no,\n po_number = OmPoBreakDown.objects.get(po_number=po_number) ,\n country_code = LibCountry.objects.get(country_code=country_code),\n code = code,\n product_code = InvProductInfo.objects.get(product_code=product_code) ,\n cut_off = cut_off,\n po_quantity = po_quantity,\n plan_quantity = plan_quantity,\n shipped_date = shipped_date,\n is_projected = is_projected,\n projected_id = projected_id,\n agent_name = agent_name,\n exporting_item_catg = exporting_item_catg,\n is_deleted = is_deleted,\n status_active = status_active,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date\n )\n po_country_info.save()\n messages.success(request, 'Congratulations! Po country details has been Added Successfully...')\n po_numbers = OmPoBreakDown.objects.all()\n country_ids = LibCountry.objects.all()\n product_ids = InvProductInfo.objects.all()\n country_info = WoPOCountryDetails.objects.all()\n context = {\n 'po_numbers': po_numbers,\n 'country_ids': country_ids,\n 'product_ids': product_ids,\n 'country_info': country_info\n }\n \n return render(request, 'Order_Entry/po_country_details.html', context)\n\nclass CostInfo(View):\n def get(self, request):\n products = InvProductInfo.objects.all()\n all_cost = OmPoCostDetail.objects.all()\n context = {\n 'products': products,\n 'all_cost':all_cost\n }\n return render(request, 'Order_Entry/cost_info.html', context)\n\n def post(self, request):\n job_no_cost_mst = request.POST['job_no_cost_mst']\n product_name_short = request.POST['product_name_short']\n unit_price = request.POST['unit_price']\n set_pc_rate = request.POST['set_pc_rate']\n set_quantity = request.POST['set_quantity']\n set_total_quantity = request.POST['set_total_quantity']\n sewing_smv = request.POST['sewing_smv']\n cutting_smv = request.POST['cutting_smv']\n finishing_smv = request.POST['finishing_smv']\n fabric_cost_total = request.POST['fabric_cost_total']\n fabric_cost_percent = request.POST['fabric_cost_percent']\n trims_cost_total = request.POST['trims_cost_total']\n trims_cost_percent = request.POST['trims_cost_percent']\n embellish_cost_total = request.POST['embellish_cost_total']\n embellish_cost_percent = request.POST['embellish_cost_percent']\n commercial_cost_total = request.POST['commercial_cost_total']\n commercial_cost_percent = request.POST['commercial_cost_percent']\n commision_cost_total = request.POST['commision_cost_total']\n commission_cost_percent = request.POST['commission_cost_percent']\n testing_cost_total = request.POST['testing_cost_total']\n testing_cost_percent = request.POST['testing_cost_percent']\n freight_cost_total = request.POST['freight_cost_total']\n freight_cost_percent = request.POST['freight_cost_percent']\n inspection_cost = request.POST['inspection_cost']\n inspection_cost_per = request.POST['inspection_cost_per']\n courier_cost = request.POST['courier_cost']\n courier_cost_per = request.POST['courier_cost_per']\n total_cost = request.POST['total_cost']\n total_cost_per = request.POST['total_cost_per']\n cm_per_unit = request.POST['cm_per_unit']\n price_per_unit = request.POST['price_per_unit']\n price_per_pc = request.POST['price_per_pc']\n bep_cm_per = request.POST['bep_cm_per']\n asking_cm_per = request.POST['asking_cm_per']\n cm_from_ie = request.POST['cm_from_ie']\n profit_loss = request.POST['profit_loss']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n is_deleted = request.POST['is_deleted']\n status_active = request.POST['status_active']\n\n po_cost_info = OmPoCostDetail(\n job_no_cost_mst = job_no_cost_mst,\n product_name_short = InvProductInfo.objects.get(product_name_short=product_name_short),\n unit_price = unit_price,\n set_pc_rate = set_pc_rate,\n set_quantity = set_quantity,\n set_total_quantity = set_total_quantity,\n sewing_smv = sewing_smv,\n cutting_smv = cutting_smv,\n finishing_smv = finishing_smv,\n fabric_cost_total = fabric_cost_total,\n fabric_cost_percent = fabric_cost_percent,\n trims_cost_total = trims_cost_total,\n trims_cost_percent = trims_cost_percent,\n embellish_cost_total = embellish_cost_total,\n embellish_cost_percent = embellish_cost_percent,\n commercial_cost_total = commercial_cost_total,\n commercial_cost_percent = commercial_cost_percent,\n commision_cost_total = commision_cost_total,\n commission_cost_percent = commission_cost_percent,\n testing_cost_total = testing_cost_total,\n testing_cost_percent = testing_cost_percent,\n freight_cost_total = freight_cost_total,\n freight_cost_percent = freight_cost_percent,\n inspection_cost = inspection_cost,\n inspection_cost_per = inspection_cost_per,\n courier_cost = courier_cost,\n courier_cost_per = courier_cost_per,\n total_cost = total_cost,\n total_cost_per = total_cost_per,\n cm_per_unit = cm_per_unit,\n price_per_unit = price_per_unit,\n price_per_pc = price_per_pc,\n bep_cm_per = bep_cm_per,\n asking_cm_per = asking_cm_per,\n cm_from_ie = cm_from_ie,\n profit_loss = profit_loss,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n is_deleted = is_deleted,\n status_active = status_active\n )\n po_cost_info.save()\n messages.success(request, 'Congratulations! Po country details has been Added Successfully...')\n products = InvProductInfo.objects.all()\n all_cost = OmPoCostDetail.objects.all()\n context = {\n 'products': products,\n 'all_cost':all_cost\n }\n return render(request, 'Order_Entry/cost_info.html', context)\n\n\n\n\n\n\nclass MainFabric(View):\n def get(self, request):\n return render(request, 'Order_Entry/main_fabric.html')\n\nclass ListView(View):\n def get(self, request):\n data = OmPoDetailsMaster.objects.all()\n context = {\n 'data':data\n }\n return render(request, 'Order_Entry/list_view.html', context)\n\nclass CountryView(View):\n def get(self, request, id):\n d = WoPOCountryDetails.objects.get(id=id)\n print(d.id)\n context = {\n 'd':d\n }\n return render(request, 'Order_Entry/country_view.html', context)\n\nclass KnittDying(View):\n def get(self, request):\n return render(request, 'Order_Entry/knitt_dying.html')\n\nclass SampleInfo(View):\n def get(self, request):\n samples = OmPoSampleInfo.objects.all()\n context = {\n 'samples':samples\n }\n return render(request, 'Order_Entry/sample_info.html', context)\n \n def post(self, request):\n job_no_mst = request.POST['job_no_mst']\n po_no_mst_id = request.POST['po_no_mst_id']\n po_number_mst = request.POST['po_number_mst']\n sample_type = request.POST['sample_type']\n target_ap_date = request.POST['target_ap_date']\n sent_to_sample = request.POST['sent_to_sample']\n submission_to_buyer = request.POST['submission_to_buyer']\n status_update_date = request.POST['status_update_date']\n approval_reject_date = request.POST['approval_reject_date']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n comment = request.POST['comment']\n\n sample_info = OmPoSampleInfo(\n job_no_mst = job_no_mst,\n po_no_mst_id = po_no_mst_id,\n po_number_mst = po_number_mst,\n sample_type = sample_type,\n target_ap_date = target_ap_date,\n sent_to_sample =sent_to_sample,\n submission_to_buyer = submission_to_buyer,\n status_update_date = status_update_date,\n approval_reject_date = approval_reject_date,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n comment = comment\n )\n sample_info.save()\n messages.success(request, 'Congratulations! Po sample info has been Added Successfully...')\n samples = OmPoSampleInfo.objects.all()\n context = {\n 'samples':samples\n }\n return render(request, 'Order_Entry/sample_info.html', context)\n \nclass OrderUpdate(View):\n def get(self, request):\n return render(request, 'Order_Entry/order_update.html')\n \nclass LapdipInfo(View):\n def get(self, request):\n colors = LibColor.objects.all()\n lapdip = OmPoLabdipInfo.objects.all()\n context = {\n 'colors':colors,\n 'lapdip':lapdip\n } \n return render(request, 'Order_Entry/lapdip_info.html', context)\n \n def post(self, request):\n job_no_mst = request.POST['job_no_mst']\n po_no_mst_id = request.POST['po_no_mst_id']\n po_number_mst = request.POST['po_number_mst']\n color_name = request.POST['color_name']\n lapdip_no = request.POST['lapdip_no']\n target_ap_date = request.POST['target_ap_date']\n sent_to_sample = request.POST['sent_to_sample']\n submission_to_buyer = request.POST['submission_to_buyer']\n status_update_date = request.POST['status_update_date']\n approval_reject_date = request.POST['approval_reject_date']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n comment = request.POST['comment']\n\n lapdip_info = OmPoLabdipInfo(\n job_no_mst = job_no_mst,\n po_no_mst_id = po_no_mst_id,\n po_number_mst = po_number_mst,\n color_name = LibColor.objects.get(color_name=color_name),\n lapdip_no = lapdip_no,\n target_ap_date = target_ap_date,\n sent_to_sample =sent_to_sample,\n submission_to_buyer = submission_to_buyer,\n status_update_date = status_update_date,\n approval_reject_date = approval_reject_date,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n comment = comment\n )\n lapdip_info.save()\n messages.success(request, 'Congratulations! Po labdip info has been Added Successfully...')\n colors = LibColor.objects.all()\n lapdip = OmPoLabdipInfo.objects.all()\n context = {\n 'colors':colors,\n 'lapdip':lapdip\n } \n return render(request, 'Order_Entry/lapdip_info.html', context)\n\nclass ColorSizeBreakdown(View):\n def get(self, request):\n colors = LibColor.objects.all()\n sizes = LibSize.objects.all()\n breakdown = OmPoColorSizeBreakDown.objects.all()\n context = {\n 'colors':colors,\n 'sizes':sizes,\n 'breakdown':breakdown\n } \n return render(request, 'Order_Entry/color_size_breakdown.html', context)\n \n def post(self, request):\n po_break_down_id = request.POST['po_break_down_id']\n job_no_mst = request.POST['job_no_mst']\n po_no_mst = request.POST['po_no_mst']\n size_name = request.POST['size_name']\n color_name = request.POST['color_name']\n prod_quantity = request.POST['prod_quantity']\n po_total = request.POST['po_total']\n is_deleted = request.POST['is_deleted']\n is_used = request.POST['is_used']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_locked = request.POST['is_locked']\n\n color_size_breakdown = OmPoColorSizeBreakDown(\n po_break_down_id = po_break_down_id,\n job_no_mst = job_no_mst,\n po_no_mst = po_no_mst,\n size_name = LibSize.objects.get(size_name=size_name),\n color_name = LibColor.objects.get(color_name=color_name),\n prod_quantity = prod_quantity,\n po_total = po_total,\n is_deleted = is_deleted,\n is_used = is_used,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_locked = is_locked\n )\n color_size_breakdown.save()\n messages.success(request, 'Congratulations! Color Size Breakdown info has been Added Successfully...')\n colors = LibColor.objects.all()\n sizes = LibSize.objects.all()\n breakdown = OmPoColorSizeBreakDown.objects.all()\n context = {\n 'colors':colors,\n 'sizes':sizes,\n 'breakdown':breakdown\n } \n return render(request, 'Order_Entry/color_size_breakdown.html', context)\n \nclass QuotationEnquiry(View):\n def get(self, request):\n return render(request, 'Order_Entry/quote_enquiry.html')\n \nclass AccessoriesInfo(View):\n def get(self, request):\n return render(request, 'Order_Entry/access_info.html')\n \n def post(self, request):\n job_no_mst = request.POST['job_no_mst']\n po_no_mst_id = request.POST['po_no_mst_id']\n po_number_mst = request.POST['po_number_mst']\n accesories_name = request.POST['accesories_name']\n target_ap_date = request.POST['target_ap_date']\n sent_to_sample = request.POST['sent_to_sample']\n submission_to_buyer = request.POST['submission_to_buyer']\n supplier_name = request.POST['supplier_name']\n status_update_date = request.POST['status_update_date']\n approval_reject_date = request.POST['approval_reject_date']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n comment = request.POST['comment']\n\n accessories_info = OmPoAccesoriesInfo(\n job_no_mst = job_no_mst,\n po_no_mst_id = po_no_mst_id,\n po_number_mst = po_number_mst,\n accesories_name = accesories_name,\n target_ap_date = target_ap_date,\n sent_to_sample =sent_to_sample,\n submission_to_buyer = submission_to_buyer,\n supplier_name = supplier_name,\n status_update_date = status_update_date,\n approval_reject_date = approval_reject_date,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n comment = comment\n )\n accessories_info.save()\n messages.success(request, 'Congratulations! Po accessories info has been Added Successfully...')\n return render(request, 'Order_Entry/access_info.html')\n\n\n############ Related Table View ############\n\n\nclass RelatedLibBuyer(View):\n def get(self, request):\n lib_buyer = LibBuyer.objects.all()\n context = {\n 'lib_buyer':lib_buyer\n }\n return render(request, 'Order_Entry/lib_buyer.html', context)\n \n def post(self, request):\n buyer_name = request.POST['buyer_name']\n contact_person = request.POST['contact_person']\n buyer_email = request.POST['buyer_email']\n contact_no = request.POST['contact_no']\n website = request.POST['website']\n address = request.POST['address']\n subcontract_party = request.POST['subcontract_party']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n remark = request.POST['remark']\n\n lib_buyer_info = LibBuyer(\n buyer_name = buyer_name,\n contact_person = contact_person,\n buyer_email = buyer_email,\n contact_no = contact_no,\n website = website,\n address = address,\n subcontract_party = subcontract_party,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n remark = remark\n )\n\n lib_buyer_info.save()\n messages.success(request, 'Congratulations! Lib buyer information has been Added Successfully...')\n lib_buyer = LibBuyer.objects.all()\n context = {\n 'lib_buyer':lib_buyer\n }\n return render(request, 'Order_Entry/lib_buyer.html', context)\n\n\nclass RelatedLibStyle(View):\n def get(self, request):\n style = LibStyle.objects.all()\n context = {\n 'style':style\n }\n return render(request, 'Order_Entry/lib_style.html', context)\n \n def post(self, request):\n style_name = request.POST['style_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n \n\n lib_style_info = LibStyle(\n style_name = style_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_style_info.save()\n messages.success(request, 'Congratulations! Lib style information has been Added Successfully...')\n style = LibStyle.objects.all()\n context = {\n 'style':style\n }\n return render(request, 'Order_Entry/lib_style.html', context)\n\nclass HrEmployeeForm(View):\n def get(self, request):\n employee = HRmEmployee.objects.all()\n context = {\n 'employee':employee\n }\n return render(request, 'Order_Entry/hrm_employee.html', context)\n \n def post(self, request):\n emp_code = request.POST['emp_code']\n first_name = request.POST['first_name']\n middle_name = request.POST['middle_name']\n last_name = request.POST['last_name']\n full_name_bangla = request.POST['full_name_bangla']\n id_card_no = request.POST['id_card_no']\n punch_card_no = request.POST['punch_card_no']\n date_of_birth = request.POST['date_of_birth']\n father_name = request.POST['father_name']\n father_name_bangla = request.POST['father_name_bangla']\n mother_name = request.POST['mother_name']\n mother_name_bangla = request.POST['mother_name_bangla']\n birth_place = request.POST['birth_place']\n religion = request.POST['religion']\n blood_group = request.POST['blood_group']\n marital_status = request.POST['marital_status']\n sex = request.POST['sex']\n nationality = request.POST['nationality']\n national_id = request.POST['national_id']\n passport_no = request.POST['passport_no']\n designation_id = request.POST['designation_id']\n designation_level = request.POST['designation_level']\n joining_date = request.POST['joining_date']\n confirmation_date = request.POST['confirmation_date']\n service_benifit_from = request.POST['service_benifit_from']\n category = request.POST['category']\n functional_superior = request.POST['functional_superior']\n admin_superior = request.POST['admin_superior']\n salary_grade = request.POST['salary_grade']\n salary_rule = request.POST['salary_rule']\n gross_salary = request.POST['gross_salary']\n bank_gross = request.POST['bank_gross']\n status_active = request.POST['status_active']\n status_suspension = request.POST['status_suspension']\n status_attendance = request.POST['status_attendance']\n status_salary = request.POST['status_salary']\n ot_entitled = request.POST['ot_entitled']\n holiday_allowance_entitled = request.POST['holiday_allowance_entitled']\n pf_entitled = request.POST['pf_entitled']\n gi_entitled = request.POST['gi_entitled']\n overtime_policy = request.POST['overtime_policy']\n holiday_incentive_policy = request.POST['holiday_incentive_policy']\n duty_roster_policy = request.POST['duty_roster_policy']\n leave_policy = request.POST['leave_policy']\n maternity_leave_policy = request.POST['maternity_leave_policy']\n attendance_bonus_policy = request.POST['attendance_bonus_policy']\n absent_deduction_policy = request.POST['absent_deduction_policy']\n late_deduction_policy = request.POST['late_deduction_policy']\n bonus_policy = request.POST['bonus_policy']\n tax_policy = request.POST['tax_policy']\n shift_policy = request.POST['shift_policy']\n company_id = request.POST['company_id']\n location_id = request.POST['location_id']\n division_id = request.POST['division_id']\n department_id = request.POST['department_id']\n section_id = request.POST['section_id']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n is_deleted = request.POST['is_deleted']\n is_locked = request.POST['is_locked']\n remark = request.POST['remark']\n \n hr_employee_info = HRmEmployee(\n emp_code = emp_code,\n first_name = first_name,\n middle_name = middle_name,\n last_name = last_name,\n full_name_bangla = full_name_bangla,\n id_card_no = id_card_no,\n punch_card_no = punch_card_no,\n date_of_birth = date_of_birth,\n father_name = father_name,\n father_name_bangla = father_name_bangla,\n mother_name = mother_name,\n mother_name_bangla = mother_name_bangla,\n birth_place = birth_place,\n religion = religion,\n blood_group = blood_group,\n marital_status = marital_status,\n sex = sex,\n nationality = nationality,\n national_id = national_id,\n passport_no = passport_no,\n designation_id = designation_id,\n designation_level = designation_level,\n joining_date = joining_date,\n confirmation_date = confirmation_date,\n service_benifit_from = service_benifit_from,\n category =category,\n functional_superior = functional_superior,\n admin_superior = admin_superior,\n salary_grade = salary_grade,\n salary_rule = salary_rule,\n gross_salary = gross_salary,\n bank_gross = bank_gross,\n status_active = status_active,\n status_suspension = status_suspension,\n status_attendance = status_attendance,\n status_salary = status_salary,\n ot_entitled = ot_entitled,\n holiday_allowance_entitled = holiday_allowance_entitled,\n pf_entitled = pf_entitled,\n gi_entitled = gi_entitled,\n overtime_policy = overtime_policy,\n holiday_incentive_policy = holiday_incentive_policy,\n duty_roster_policy = duty_roster_policy,\n leave_policy = leave_policy,\n maternity_leave_policy = maternity_leave_policy,\n attendance_bonus_policy = attendance_bonus_policy,\n absent_deduction_policy = absent_deduction_policy,\n late_deduction_policy = late_deduction_policy,\n bonus_policy = bonus_policy,\n tax_policy = tax_policy,\n shift_policy = shift_policy,\n company_id = company_id,\n location_id = location_id,\n division_id = division_id,\n department_id = department_id,\n section_id = section_id,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n is_deleted = is_deleted,\n is_locked = is_locked,\n remark = remark\n\n )\n\n hr_employee_info.save()\n messages.success(request, 'Congratulations! Hr Employee information has been Added Successfully...')\n employee = HRmEmployee.objects.all()\n context = {\n 'employee':employee\n }\n return render(request, 'Order_Entry/hrm_employee.html', context)\n \n \nclass LibCompanyInfo(View):\n def get(self, request):\n company = LibCompany.objects.all()\n context = {\n 'company':company\n }\n return render(request, 'Order_Entry/lib_company.html', context)\n\n def post(self, request):\n group_id = request.POST['group_id']\n company_name = request.POST['company_name']\n company_short_name = request.POST['company_short_name']\n service_cost_allocation = request.POST['service_cost_allocation']\n posting_pre_year = request.POST['posting_pre_year']\n statutory_account = request.POST['statutory_account']\n contact_person = request.POST['contact_person']\n cfo = request.POST['cfo']\n company_nature = request.POST['company_nature']\n location = request.POST['location']\n core_business = request.POST['core_business']\n email = request.POST['email']\n website = request.POST['website']\n ac_code_length = request.POST['ac_code_length']\n profit_center_affected = request.POST['profit_center_affected']\n plot_no = request.POST['plot_no']\n level_no = request.POST['level_no']\n road_no = request.POST['road_no']\n block_no = request.POST['block_no']\n country_id = request.POST['country_id']\n province = request.POST['province']\n city = request.POST['city']\n zip_code = request.POST['zip_code']\n trade_license_no = request.POST['trade_license_no']\n incorporation_no = request.POST['incorporation_no']\n erc_no = request.POST['erc_no']\n irc_no = request.POST['irc_no']\n tin_number = request.POST['tin_number']\n vat_number = request.POST['vat_number']\n epb_reg_no = request.POST['epb_reg_no']\n trade_license_renewal = request.POST['trade_license_renewal']\n erc_expiry_date = request.POST['erc_expiry_date']\n irc_expiry_date = request.POST['irc_expiry_date']\n bangladesh_bank_reg_no = request.POST['bangladesh_bank_reg_no']\n graph_color = request.POST['graph_color']\n logo_location = request.POST['logo_location']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n is_locked = request.POST['is_locked']\n \n lib_company_info = LibCompany(\n group_id = group_id,\n company_name = company_name,\n company_short_name = company_short_name,\n service_cost_allocation = service_cost_allocation,\n posting_pre_year = posting_pre_year,\n statutory_account = statutory_account,\n contact_person = contact_person,\n cfo = cfo,\n company_nature = company_nature,\n location = location,\n core_business = core_business,\n email = email,\n website = website,\n ac_code_length = ac_code_length,\n profit_center_affected = profit_center_affected,\n plot_no = plot_no,\n level_no = level_no,\n road_no = road_no,\n block_no = block_no,\n country_id = country_id,\n province = province,\n city = city,\n zip_code = zip_code,\n trade_license_no = trade_license_no,\n incorporation_no = incorporation_no,\n erc_no = erc_no,\n irc_no = irc_no,\n tin_number = tin_number,\n vat_number = vat_number,\n epb_reg_no = epb_reg_no,\n trade_license_renewal = trade_license_renewal,\n erc_expiry_date = erc_expiry_date,\n irc_expiry_date = irc_expiry_date,\n bangladesh_bank_reg_no = bangladesh_bank_reg_no,\n graph_color = graph_color,\n logo_location = logo_location,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n is_locked = is_locked\n \n )\n\n lib_company_info.save()\n messages.success(request, 'Congratulations! Lib Company information has been Added Successfully...')\n company = LibCompany.objects.all()\n context = {\n 'company':company\n }\n return render(request, 'Order_Entry/lib_company.html', context)\n\n \nclass LibDepartmentInfo(View):\n def get(self, request):\n department = LibDepartment.objects.all()\n context = {\n 'department':department\n }\n return render(request, 'Order_Entry/lib_department.html', context)\n \n def post(self, request):\n department_name = request.POST['department_name']\n department_id = request.POST['department_id']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n is_locked = request.POST['is_locked']\n remark = request.POST['remark']\n\n lib_department_info = LibDepartment(\n department_name = department_name,\n department_id = department_id,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n is_locked = is_locked,\n remark = remark\n )\n\n lib_department_info.save()\n messages.success(request, 'Congratulations! Lib Department information has been Added Successfully...')\n department = LibDepartment.objects.all()\n context = {\n 'department':department\n }\n return render(request, 'Order_Entry/lib_department.html', context)\n\n \nclass LibDivisionInfo(View):\n def get(self, request):\n division = LibDivision.objects.all()\n context = {\n 'division': division\n }\n return render(request, 'Order_Entry/lib_division.html', context)\n \n def post(self, request):\n division_name = request.POST['division_name']\n location_id = request.POST['location_id']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n is_locked = request.POST['is_locked']\n remark = request.POST['remark']\n\n lib_division_info = LibDivision(\n division_name = division_name,\n location_id = location_id,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n is_locked = is_locked,\n remark = remark\n )\n\n lib_division_info.save()\n messages.success(request, 'Congratulations! Lib sub department information has been Added Successfully...')\n division = LibDivision.objects.all()\n context = {\n 'division': division\n }\n return render(request, 'Order_Entry/lib_division.html', context)\n \nclass LibSubDept(View):\n def get(self, request):\n sub_department = LibSubDepartment.objects.all()\n context = {\n 'sub_department':sub_department\n }\n return render(request, 'Order_Entry/lib_sub_dept.html', context)\n \n def post(self, request):\n sub_department_name = request.POST['sub_department_name']\n department_id = request.POST['department_id']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n is_locked = request.POST['is_locked']\n remark = request.POST['remark']\n\n lib_sub_division_info = LibSubDepartment(\n sub_department_name = sub_department_name,\n department_id = department_id,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n is_locked = is_locked,\n remark = remark\n )\n\n lib_sub_division_info.save()\n messages.success(request, 'Congratulations! Lib sub department information has been Added Successfully...')\n sub_department = LibSubDepartment.objects.all()\n context = {\n 'sub_department':sub_department\n }\n return render(request, 'Order_Entry/lib_sub_dept.html', context)\n \nclass LibProdCat(View):\n def get(self, request):\n prod_cate = LibProductCate.objects.all()\n context = {\n 'prod_cate':prod_cate\n }\n return render(request, 'Order_Entry/lib_prod_cat.html', context)\n \n def post(self, request):\n product_cate = request.POST['product_cate']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_product_cat_info = LibProductCate(\n product_cate = product_cate,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted,\n \n )\n\n lib_product_cat_info.save()\n messages.success(request, 'Congratulations! Lib product cate information has been Added Successfully...')\n prod_cate = LibProductCate.objects.all()\n context = {\n 'prod_cate':prod_cate\n }\n return render(request, 'Order_Entry/lib_prod_cat.html', context)\n \nclass LibSeasonInfo(View):\n def get(self, request):\n seasons = LibSeason.objects.all()\n context = {\n 'seasons':seasons\n }\n return render(request, 'Order_Entry/libseason.html', context)\n \n def post(self, request):\n season_name = request.POST['season_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_season_info = LibSeason(\n season_name = season_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_season_info.save()\n messages.success(request, 'Congratulations! Lib season information has been Added Successfully...')\n seasons = LibSeason.objects.all()\n context = {\n 'seasons':seasons\n }\n return render(request, 'Order_Entry/libseason.html', context)\n \nclass LibRegionInfo(View):\n def get(self, request):\n regions = LibRegion.objects.all()\n context = {\n 'regions':regions\n }\n return render(request, 'Order_Entry/lib_region.html', context)\n \n def post(self, request):\n region_name = request.POST['region_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_region_info = LibRegion(\n region_name = region_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_region_info.save()\n messages.success(request, 'Congratulations! Lib region information has been Added Successfully...')\n regions = LibRegion.objects.all()\n context = {\n 'regions':regions\n }\n return render(request, 'Order_Entry/lib_region.html', context)\n \nclass LibAgentInfo(View):\n def get(self, request):\n agents = LibAgent.objects.all()\n context = {\n 'agents': agents\n }\n return render(request, 'Order_Entry/lib_agent.html', context)\n \n def post(self, request):\n agent_name = request.POST['agent_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_agent_info = LibAgent(\n agent_name = agent_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_agent_info.save()\n messages.success(request, 'Congratulations! Lib agent information has been Added Successfully...')\n agents = LibAgent.objects.all()\n context = {\n 'agents': agents\n }\n return render(request, 'Order_Entry/lib_agent.html', context)\n \nclass LibClientInfo(View):\n def get(self, request):\n clients = LibClient.objects.all()\n context = {\n 'clients': clients\n }\n return render(request, 'Order_Entry/lib_client.html', context)\n \n def post(self, request):\n client_name = request.POST['client_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_client_info = LibClient(\n client_name = client_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_client_info.save()\n messages.success(request, 'Congratulations! Lib client information has been Added Successfully...')\n clients = LibClient.objects.all()\n context = {\n 'clients': clients\n }\n return render(request, 'Order_Entry/lib_client.html', context)\n \nclass LibUnitInfo(View):\n def get(self, request):\n units = LibUnit.objects.all()\n context = {\n 'units': units\n }\n return render(request, 'Order_Entry/lib_unit.html', context)\n \n def post(self, request):\n unit_name = request.POST['unit_name']\n description = request.POST['description']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_unit_info = LibUnit(\n unit_name = unit_name,\n description = description,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_unit_info.save()\n messages.success(request, 'Congratulations! Lib unit information has been Added Successfully...')\n units = LibUnit.objects.all()\n context = {\n 'units': units\n }\n return render(request, 'Order_Entry/lib_unit.html', context)\n \nclass LibCurrencyInfo(View):\n def get(self, request):\n currency = LibCurrency.objects.all()\n context = {\n 'currency': currency\n } \n return render(request, 'Order_Entry/lib_currency.html', context)\n\n def post(self, request):\n currency_code = request.POST['currency_code']\n description = request.POST['description']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_currency_info = LibCurrency(\n currency_code = currency_code,\n description = description,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_currency_info.save()\n messages.success(request, 'Congratulations! Lib currency information has been Added Successfully...')\n currency = LibCurrency.objects.all()\n context = {\n 'currency': currency\n } \n return render(request, 'Order_Entry/lib_currency.html', context)\n \nclass INV(View):\n def get(self, request):\n inventory_product= InvProductInfo.objects.all()\n context = {\n 'inventory_product': inventory_product\n }\n return render(request, 'Order_Entry/inv_prod_info.html', context)\n\n def post(self, request):\n product_code = request.POST['product_code']\n product_name_details = request.POST['product_name_details']\n item_group = request.POST['item_group']\n product_name_short = request.POST['product_name_short']\n item_category = request.POST['item_category']\n vat_per_unit = request.POST['vat_per_unit']\n rate_per_unit = request.POST['rate_per_unit']\n current_stock = request.POST['current_stock']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n inv_product_info = InvProductInfo(\n product_code = product_code,\n product_name_details = product_name_details,\n item_group = item_group,\n product_name_short = product_name_short,\n item_category = item_category,\n vat_per_unit = vat_per_unit,\n rate_per_unit = rate_per_unit,\n current_stock = current_stock,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n inv_product_info.save()\n messages.success(request, 'Congratulations! Inv Product information has been Added Successfully...')\n inventory_product= InvProductInfo.objects.all()\n context = {\n 'inventory_product': inventory_product\n }\n return render(request, 'Order_Entry/inv_prod_info.html', context)\n \n \nclass LibColorInfo(View):\n def get(self, request):\n colors = LibColor.objects.all()\n context = {\n 'colors':colors\n }\n return render(request, 'Order_Entry/lib_color.html', context)\n \n def post(self, request):\n color_name = request.POST['color_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_color_info = LibColor(\n color_name = color_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_color_info.save()\n messages.success(request, 'Congratulations! Lib color information has been Added Successfully...')\n colors = LibColor.objects.all()\n context = {\n 'colors':colors\n }\n return render(request, 'Order_Entry/lib_color.html', context)\n \nclass LibSizeInfo(View):\n def get(self, request):\n sizes = LibSize.objects.all()\n context = {\n 'sizes':sizes\n }\n return render(request, 'Order_Entry/lib_size.html', context)\n\n def post(self, request):\n size_name = request.POST['size_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_size_info = LibSize(\n size_name = size_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_size_info.save()\n messages.success(request, 'Congratulations! Lib size information has been Added Successfully...')\n sizes = LibSize.objects.all()\n context = {\n 'sizes':sizes\n }\n return render(request, 'Order_Entry/lib_size.html', context) \n \nclass LibCountryInfo(View):\n def get(self, request):\n return render(request, 'Order_Entry/lib_country.html')\n \n def post(self, request):\n country_code = request.POST['country_code']\n country_name = request.POST['country_name']\n inserted_by = request.POST['inserted_by']\n insert_date = request.POST['insert_date']\n updated_by = request.POST['updated_by']\n update_date = request.POST['update_date']\n status_active = request.POST['status_active']\n is_deleted = request.POST['is_deleted']\n\n lib_country_info = LibCountry(\n country_code = country_code,\n country_name = country_name,\n inserted_by = inserted_by,\n insert_date = insert_date,\n updated_by = updated_by,\n update_date = update_date,\n status_active = status_active,\n is_deleted = is_deleted\n \n )\n\n lib_country_info.save()\n messages.success(request, 'Congratulations! Lib country information has been Added Successfully...')\n return render(request, 'Order_Entry/lib_country.html')\n \n \n \n \n\n","repo_name":"mamunkhan405/LAKSHMA_ERP","sub_path":"Lakshma_ERP_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":64675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5411942442","text":"from flask import Flask, request\r\nfrom flask_restplus import Resource, Api\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport joblib\r\nimport numpy as np\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\nmodel = joblib.load('redwinemodel.joblib')\r\n@app.route('/api/quality', methods=['GET'])\r\n# http://[ip_addr:5000]/api/quality?volacid=0.7&citacid=0.5&chl=0.1&sul=0.7&alc=9.5\r\n\r\ndef get():\r\n print(\"start of get()\")\r\n volacid = request.args.get('volacid', type = float)\r\n citacid = request.args.get('citacid', type = float)\r\n chl = request.args.get('chl', type = float)\r\n sul = request.args.get('sul', type = float)\r\n alc = request.args.get('alc', type = float)\r\n print(\"volacid=\" + str(volacid) + \", citacid=\" + str(citacid) + \", chl=\" + str(chl) + \", sul=\" + str(sul) + \", alc=\" + str(alc))\r\n # array passed to the model has the same order as cols in the orignal dataset\r\n # result rounded to nearest integer\r\n #qual = model.predict(np.array([0.7, 0.5, 0.1, 0.1, 9.5]).reshape(-1, 5))[0]\r\n qual = model.predict(np.array([volacid, citacid, chl, sul, alc]).reshape(-1, 5))[0]\r\n print(\"model returned \" + str(qual))\r\n return {'predicted quality': qual}\r\n\r\nif __name__ == '__main__':\r\n app.run(host=\"0.0.0.0\", debug=True)\r\n","repo_name":"conormccormick885/redwinemodel","sub_path":"redwine.py","file_name":"redwine.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"40210199394","text":"#!python3.7\n\nimport os\nimport re\n\npath = 'files/'\n\ndef deleteContent(pfile):\n pfile.seek(0)\n pfile.truncate()\n\nfor r, d, f in os.walk(path):\n for folder in d:\n path_base = path + folder + '/'\n files = [os.path.join(path_base,f) for f in os.listdir(path_base) if os.path.isfile(os.path.join(path_base,f))]\n number_files = len(files)\n if number_files > 1:\n linesToAdd = ['Table of Contents
\\n','\\n']\n for x in range(number_files):\n linesToAdd.append('Chapter ' + str(x) + '
\\n')\n \n # read contents of file\n with open(path_base + 'Chapter0.html', 'r+') as chapter0:\n lines = chapter0.readlines()\n deleteContent(chapter0)\n for i in range(len(lines)):\n line = lines[i]\n\n if '' in line:\n print(line)\n line += '\\n\\n'\n for line0 in linesToAdd:\n line += line0\n line += '\\n\\n'\n lines[i] = line\n\n chapter0.writelines(lines)\n chapter0.close()\n\n","repo_name":"NadiaCarvalho/JAFF_Downloader","sub_path":"add_index.py","file_name":"add_index.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34991158168","text":"# pylint: disable=too-many-arguments, unused-argument\n# pylint: disable=logging-fstring-interpolation\n\n\"\"\"\nUtility Functions for scripts\n\nWe provide functions that help testing and\nbasic validation of the algorithm.\n\n\"\"\"\nimport logging\n\nimport dask\nimport numpy\nfrom distributed import Lock\n\nfrom ska_sdp_exec_swiftly import single_write_hdf5_task\n\nlog = logging.getLogger(\"fourier-logger\")\nlog.setLevel(logging.INFO)\n\n\ndef sum_and_finish_subgrid(\n distr_fft, base_arrays, i0, i1, facet_ixs, NMBF_NMBFs\n):\n \"\"\"\n Combined function with Sum and Generate Subgrid\n\n :param distr_fft: StreamingDistributedFFT class object\n :param base_arrays: BaseArrays class object\n :param facet_ixs: facet index list\n :param i0: i0 index\n :param i1: i1 index\n :param facet_ixs: facet index list\n :param NMBF_NMBFs: list of NMBF_NMBF graph\n\n :return: i0,i1 index, the shape of approx_subgrid\n \"\"\"\n # Initialise facet sum\n summed_facet = numpy.zeros(\n (distr_fft.xM_size, distr_fft.xM_size), dtype=complex\n )\n # Add contributions\n # Combined two functions (i.e., Sum and Generate Subgrid)\n # and run them in serial when use_dask = false\n for (j0, j1), NMBF_NMBF in zip(facet_ixs, NMBF_NMBFs):\n summed_facet += distr_fft.add_facet_contribution(\n distr_fft.add_facet_contribution(\n NMBF_NMBF,\n distr_fft.facet_off[j0],\n axis=0,\n use_dask=False,\n nout=1,\n ),\n distr_fft.facet_off[j1],\n axis=1,\n use_dask=False,\n )\n\n # Finish\n approx_subgrid = distr_fft.finish_subgrid(\n summed_facet,\n use_dask=False,\n nout=1,\n )\n\n return approx_subgrid\n\n\ndef wait_for_tasks(work_tasks, timeout=None, return_when=\"ALL_COMPLETED\"):\n \"\"\"\n Simple function for waiting for tasks to finish.\n Logs completed tasks, and returns list of still-waiting tasks.\n\n :param work_tasks: task list\n :param timeout: timeout for waiting a task finshed\n :param return_when: return string\n\n :return: unfinshed task\n \"\"\"\n\n # Wait for any task to finish\n dask.distributed.wait(work_tasks, timeout, return_when)\n\n # Remove finished tasks from work queue, return\n new_work_tasks = []\n for task in work_tasks:\n if task.done():\n log.info(f\"Finished:{task.result()}\")\n elif task.cancelled():\n log.info(\"Cancelled\")\n else:\n new_work_tasks.append(task)\n return new_work_tasks\n\n\ndef batch_all_i1_NMBF_NMBF(NMBF_BF, distr_fft, base_arrays, batch_i1_list):\n \"\"\"\n compute NMBF_NMBF with all i1 axis in one task\n\n :param NMBF_BF: NMBF_BF graph\n :param distr_fft: StreamingDistributedFFT class object\n :param base_arrays: BaseArrays class object\n\n :param i1_batch: batch i1 index list\n\n :return a batch of NMBF_NMBF\n \"\"\"\n batch_all = []\n for i1_batch in batch_i1_list:\n NMBF_NMBF_list = []\n for i1 in i1_batch:\n NMBF_NMBF = distr_fft.extract_facet_contrib_to_subgrid(\n NMBF_BF,\n distr_fft.subgrid_off[i1],\n base_arrays.facet_m0_trunc,\n base_arrays.Fn,\n axis=1,\n use_dask=False,\n nout=1,\n )\n NMBF_NMBF_list.append(NMBF_NMBF)\n batch_all.append(NMBF_NMBF_list)\n return batch_all\n\n\n@dask.delayed\ndef batch_NMBF_NMBF_sum_finish_subgrid(\n nfacet_ni1_batch_list,\n distr_fft,\n base_arrays,\n facet_ixs,\n i0,\n i1_batch,\n check=False,\n):\n \"\"\"\n Barch Compute NMBF_NMBF and subgrid of i0's in a dask task\n\n :param NMBF_BF_tasks: NMBF_BF graph\n :param distr_fft: StreamingDistributedFFT class object\n :param base_arrays: BaseArrays class object\n :param facet_ixs: facet index list\n :param i0: i0 index\n :param i1_batch: batch i1 index list\n\n :return: approx subgrid index list and shape\n \"\"\"\n ni1_batch_nfacet_list = list(map(list, zip(*nfacet_ni1_batch_list)))\n approx_subgrid_i0_list = []\n for idx, i1 in enumerate(i1_batch):\n approx_subgrid = sum_and_finish_subgrid(\n distr_fft,\n base_arrays,\n i0,\n i1,\n facet_ixs,\n ni1_batch_nfacet_list[idx],\n )\n if check:\n approx_subgrid_i0_list.append((i0, i1, approx_subgrid))\n else:\n approx_subgrid_i0_list.append((i0, i1, approx_subgrid.shape))\n return approx_subgrid_i0_list\n\n\n@dask.delayed\ndef write_approx_subgrid(approx_subgrid_list, base_arrays, hdf5_path):\n \"\"\"\n write a batch of approx_subgrid to hdf5\n\n :param approx_subgrid_list: a batch of approx_subgrid\n :param base_arrays: BaseArrays class object\n :param hdf5_path: approx G hdf5 file path\n\n :return List of i0,i1 and shape of approx_subgrid\n \"\"\"\n res_list = []\n for i0, i1, approx_subgrid in approx_subgrid_list:\n lock = Lock(hdf5_path)\n lock.acquire()\n _ = single_write_hdf5_task(\n hdf5_path,\n \"G_data\",\n base_arrays,\n i0,\n i1,\n approx_subgrid,\n use_dask=False,\n nout=1,\n )\n lock.release()\n res_list.append((i0, i1, approx_subgrid.shape))\n return res_list\n\n\n@dask.delayed\ndef write_network_transfer_info(path, info):\n \"\"\"\n write the network transfer info\n\n :param path: file path\n :param info: info as config1, data_incoming, data_outgoing\n\n :return info\n \"\"\"\n lock = Lock(path)\n lock.acquire()\n with open(path, \"a+\", encoding=\"utf-8\") as f:\n f.write(info + \"\\n\")\n lock.release()\n return info\n\n\ndef human_readable_size(size, decimal_places=3):\n \"\"\"\n convert human readable bytes size\n\n :param size: bytes\n :param decimal_places: decimal_places\n\n :return readable bytes size in str\n \"\"\"\n for unit in [\"B\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\"]:\n if size < 1024.0:\n break\n size /= 1024.0\n return f\"{size:.{decimal_places}f}{unit}\"\n\n\ndef get_and_write_transfer(dask_client, key):\n \"\"\"get transfer\n\n :param dask_client: client\n :param key: key for write csv\n \"\"\"\n dict_outgoing = dask_client.run(\n lambda dask_worker: dask_worker.outgoing_transfer_log\n )\n dict_incoming = dask_client.run(\n lambda dask_worker: dask_worker.incoming_transfer_log\n )\n\n sum_getitem_incoming = 0.0\n for di_key in dict_incoming.keys():\n for di_key2 in dict_incoming[di_key]:\n # if \"getitem\" in str(di_key2[\"keys\"]):\n sum_getitem_incoming += di_key2[\"total\"]\n log.info(f\"sum_getitem_incoming transfer bytes: {sum_getitem_incoming}\")\n sum_getitem_outgoing = 0.0\n for do_key in dict_outgoing.keys():\n for do_key2 in dict_outgoing[do_key]:\n # if \"getitem\" in str(do_key2[\"keys\"]):\n sum_getitem_outgoing += do_key2[\"total\"]\n log.info(f\"sum_getitem_outgoing transfer bytes: {sum_getitem_outgoing}\")\n tmp_size_1 = human_readable_size(sum_getitem_incoming)\n tmp_size_2 = human_readable_size(sum_getitem_outgoing)\n write_task = write_network_transfer_info(\n \"transfer_info_full_step.txt\",\n f\"{key},{tmp_size_1},{tmp_size_2}\",\n )\n dask_client.compute(write_task, sync=True)\n","repo_name":"ska-telescope/ska-sdp-distributed-fourier-transform","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31104347538","text":"import asyncio\n\nfrom .exceptions import NoEventLoopDefined\n\n\nclass Flow:\n def __init__(self, data, loop=None):\n self._loop = loop\n self._data = data\n\n @staticmethod\n def from_enumerable(data, loop=None):\n return Flow(data, loop=loop)\n\n @property\n def event_loop(self):\n return self._loop\n\n @event_loop.setter\n def event_loop(self, loop):\n self._loop = loop\n\n def __rshift__(self, method):\n if asyncio.iscoroutinefunction(method):\n if self._loop is None:\n raise NoEventLoopDefined()\n\n f = self._loop.run_until_complete(method(self._data))\n\n else:\n f = method(self._data)\n\n if isinstance(f, Flow):\n f.event_loop = self._loop\n\n return f\n","repo_name":"LordFeratum/DataFlow","sub_path":"dataflow/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"18983145777","text":"# 카운터에는 거스름돈으로 사용할 500, 100, 50, 10 동전 무한히 존재한다 가정,\n# 손님에게 거슬러줘야할 돈이 N원 일때, 거슬러 주어야 할 동전의 최소개수를 구하시오.\n# 단, 거슬러줘야 할 돈 N은 항상 10배수 입니다.\n# 가장 큰 단위의 돈부터 거슬러주면 된다.\n# N = 1260원 일 경우 예시를 확인해보자.\n\ndef greedy(array, count, n):\n for coin in array:\n count += n // coin\n n = n % coin\n\n return count\n\nn = int(input())\ncount = 0\narray = [500, 100, 50, 10]\n\nprint(greedy(array, count, n))","repo_name":"kkojae91/algorithm_prac","sub_path":"python_algorithm/greedy/greedy-01.py","file_name":"greedy-01.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"32171034797","text":"\"\"\"\n Task: Sort by frequency\n Context: general coding interview\n Category: String manipulation\n Problem statement:\n The characters in the string should be sorted based on the following conditions.\n 1 - Sort the characters in the string by their frequency of occurrences \n (the number of times characters have occurred in the string).\n 2 - If the two different characters have the same frequency, these \n letters should be sorted based on their alphabetical order.\n\"\"\"\n\ndef sort_by_freq(msg):\n char_freq = {}\n for c in msg:\n if c in char_freq:\n char_freq[c] += 1\n else:\n char_freq[c] = 1\n sorted_chars = sorted(char_freq.items(), key=lambda x: x[1])\n return ''.join([char * freq for char, freq in sorted_chars])\n\nout = sort_by_freq(\"aabbccdddddeeeee\")\nprint(f\"String sorted by char frequency: {out}\")\n\n\n\"\"\"\nOutput>>>\n\n String sorted by char frequency: aabbccdddddeeeee\n\"\"\"","repo_name":"umer-r/Python-Competitive-Coding","sub_path":"String Manipulation/sort_by_frequency/MyAttempt.py","file_name":"MyAttempt.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"14754689043","text":"'''\n [문제]\n 철수는 게임을 만들고 있다.\n game리스트는 이차원으로 되어있다.\n game리스트 안에 block리스트의 숫자를 채워 넣는 게임이다.\n\n 리스트의 값1은 block이 차 있는 것을 의미한다.\n 리스트의 값0은 block이 비어있는 것을 의미한다.\n [조건1] \n block은 이번에 제시된 모양이다. \n block의 모양을 game 리스트에 넣을 수 있다면 채워 넣고,\n 넣을 수 없다면 \"gameover\"를 출력하시오.\n [조건2]\n block을 채워 넣었을 때 가로로 1이 연속 5개이거나, \n 세로로 1이 연속 5개이면 그 줄은 전부 숫자 2로 변경하시오.\n [정답]\n\n'''\ngame = [\n [0,1,0,1,0],\n [1,1,0,1,1],\n [0,1,1,1,1],\n [1,1,0,1,0],\n [0,0,0,0,0]\n]\n\n# 1을 발견했을때 0을 기준으로 \n# x += 1 \n# y += 1\n# x += 1 and y += 1\n# 위 조건들이 0인지 확인 \n\nblock = [\n [0,1],\n [1,1]\n]\n\nfor i in range(len(game)-1):\n\n for j in range(len(game[i])-1):\n count = 0\n if game[i][j+1] == 0 :\n count += 1\n if game[i+1][j] == 0 :\n count += 1\n if game[i+1][j+1] == 0:\n count += 1\n print(count)\n \n if count == 3 :\n game[i][j+1] = 1\n game[i+1][j] = 1\n game[i+1][j+1] = 1\n break\n \n if i == len(game)-1 : print('gameOver')\n \n \nfor i in range(len(game)):\n print(game[i])\nprint()\n\nwidthCount = 0\nlengthCount = 0\nfor i in range(len(game)):\n for j in range(len(game[i])):\n if game[i][j] == 1 :\n widthCount += 1\n else :\n widthCount = 0\n if game[j][i] == 1 :\n lengthCount += 1\n else :\n lengthCount = 0\n \n if widthCount == 5 :\n for j in range(len(game[i])):\n game[i][j] = 2\n \n if lengthCount == 5 :\n for j in range(len(game[i])):\n game[j][i] = 2\n \n\nfor i in range(len(game)):\n print(game[i])","repo_name":"jomira0220/study","sub_path":"jomira/00_문법총정리/Python_문제풀기/이차배열/이차배열5/이차배열5_문제07_퍼즐게임.py","file_name":"이차배열5_문제07_퍼즐게임.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34332683828","text":"import datetime\nimport json\nimport threading\nimport time\nimport typing\n\nimport sqlalchemy\nimport twitchirc\nfrom sqlalchemy.orm import reconstructor\nfrom twitchirc import ChannelMessage\n\nfrom util_bot.utils import deprecated\nimport util_bot\n\nCACHE_EXPIRE_TIME = 15 * 60\n\n\ndef _is_pleb(msg: twitchirc.ChannelMessage) -> bool:\n # print(msg.flags['badges'])\n for i in (msg.flags['badges'] if isinstance(msg.flags['badges'], list) else [msg.flags['badges']]):\n # print(i)\n if i.startswith('subscriber'):\n return False\n return True\n\n\nmodified_users: typing.Dict[int, typing.Dict[str, typing.Union[datetime.datetime, int, ChannelMessage]]] = {\n # base_id\n # 123: {\n # 'last_active': datetime.datetime.now(),\n # 'msg': twitchirc.ChannelMessage(),\n # 'expire_time': time.time() + CACHE_EXPIRE_TIME\n # }\n}\n\n\n# noinspection PyPep8Naming\ndef get(Base, session_scope, log):\n class UserMeta(Base.__class__):\n cache: typing.Dict[int, typing.Dict[str, typing.Union[float, typing.Any]]] = {\n # 123: {\n # 'expires': time.time() +CACHE_EXPIRE_TIME,\n # 'obj': User\n # }\n }\n\n def expire_caches(self):\n # print('expire caches')\n current_time = time.time()\n for obj_id, obj_data in self.cache.copy().items():\n if obj_data['expires'] < current_time:\n # print(obj_id, 'expired', obj_data)\n del self.cache[obj_id]\n\n def add_to_cache(self, obj):\n if obj.id in self.cache:\n print(f'[failed] Add to cache {obj}')\n return\n # print(f'Add to cache {obj}')\n # print(self.cache)\n self.cache[obj.id] = {\n 'expires': time.time() + CACHE_EXPIRE_TIME,\n 'obj': obj\n }\n\n def empty_cache(self):\n self.cache.clear()\n\n\n class User(Base, metaclass=UserMeta):\n __tablename__ = 'users'\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n twitch_id = sqlalchemy.Column(sqlalchemy.Integer, unique=True)\n discord_id = sqlalchemy.Column(sqlalchemy.Integer, unique=True) # unused\n last_known_username = sqlalchemy.Column(sqlalchemy.Text)\n\n mod_in_raw = sqlalchemy.Column(sqlalchemy.Text) # deprecated\n sub_in_raw = sqlalchemy.Column(sqlalchemy.Text)\n\n # last_active = sqlalchemy.Column(sqlalchemy.DateTime)\n # last_message = sqlalchemy.Column(sqlalchemy.UnicodeText)\n # last_message_channel = sqlalchemy.Column(sqlalchemy.Text)\n\n first_active = sqlalchemy.Column(sqlalchemy.DateTime, nullable=True)\n permissions_raw = sqlalchemy.Column(sqlalchemy.Text, default='[]')\n permissions = []\n\n def import_permissions(self):\n self.permissions = json.loads(self.permissions_raw)\n\n def export_permissions(self):\n self.permissions_raw = json.dumps(self.permissions)\n\n @reconstructor\n def _reconstructor(self):\n # print(f'reconstructor for {self!r}')\n self.import_permissions()\n User.add_to_cache(self)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.first_active = datetime.datetime.now()\n\n @staticmethod\n def _get_by_message(msg, no_create, session):\n User.expire_caches()\n # print(f'get by message {msg}')\n # if (hasattr(msg, 'platform') and msg.platform.name == 'TWITCH') or not hasattr(msg, 'platform'):\n if isinstance(msg, (util_bot.StandardizedMessage,\n util_bot.StandardizedWhisperMessage)) and msg.platform == util_bot.Platform.TWITCH:\n for obj_id, obj_data in User.cache.items():\n if obj_data['obj'].twitch_id == int(msg.flags['user-id']):\n # print(f'load from cache {obj_data}')\n return obj_data['obj']\n\n user: User = (session.query(User)\n .filter(User.twitch_id == msg.flags['user-id'])\n .first())\n elif isinstance(msg, (util_bot.StandardizedMessage,\n util_bot.StandardizedWhisperMessage)) and msg.platform == util_bot.Platform.IRC:\n return None # can't make a user on irc yet\n elif isinstance(msg, (util_bot.StandardizedMessage, util_bot.StandardizedWhisperMessage)):\n raise RuntimeError('this shouldn\\'t happen: bad message, fetching user')\n\n if user is None and not no_create:\n if (hasattr(msg, 'platform') and msg.platform.name == 'TWITCH') or not hasattr(msg, 'platform'):\n user = User(twitch_id=msg.flags['user-id'], last_known_username=msg.user, mod_in_raw='',\n sub_in_raw='')\n else:\n raise RuntimeError('this shouldn\\'t happen: bad message, fetching user')\n session.add(user)\n session.commit()\n session.expunge(user)\n return user\n\n @staticmethod\n def get_by_message(msg, no_create=False, session=None):\n if session is None:\n with session_scope() as s:\n return User._get_by_message(msg, no_create, s)\n else:\n return User._get_by_message(msg, no_create, session)\n\n @staticmethod\n def _get_by_twitch_id(id_: int, session):\n user: User = session.query(User).filter(User.twitch_id == id_).first()\n if user is not None:\n session.refresh(user)\n return user\n\n @staticmethod\n def get_by_twitch_id(id_: int, session=None):\n User.expire_caches()\n for obj_id, obj_data in User.cache.items():\n if obj_data['obj'].twitch_id == id_:\n return obj_data['obj']\n\n if session:\n return User._get_by_twitch_id(id_, session)\n else:\n with session_scope() as s:\n return User._get_by_twitch_id(id_, s)\n\n @staticmethod\n def _get_by_local_id(id_: int, session=None):\n user: User = session.query(User).filter(User.id == id_).first()\n if user is not None:\n session.refresh(user)\n return user\n\n @staticmethod\n def get_by_local_id(id_: int, s=None):\n User.expire_caches()\n if id_ in User.cache:\n return User.cache[id_]['obj']\n\n if s is None:\n with session_scope() as session:\n return User._get_by_local_id(id_, session)\n else:\n return User._get_by_local_id(id_, s)\n\n @staticmethod\n def _get_by_name(name: str, session):\n users: typing.List[User] = session.query(User).filter(User.last_known_username == name).all()\n for user in users:\n session.refresh(user)\n return users\n\n @staticmethod\n def get_by_name(name: str, s=None) -> typing.List[typing.Any]:\n if s is None:\n with session_scope() as session:\n return User._get_by_name(name, session)\n else:\n return User._get_by_name(name, s)\n\n def _update(self, update, session):\n session.add(self)\n msg = update['msg']\n if hasattr(msg, 'platform') and msg.platform.name != 'TWITCH': # don't update names outside of Twitch.\n return\n\n if msg.user != self.last_known_username:\n other_users = User.get_by_name(msg.user)\n for user in other_users:\n user: User\n user.last_known_username = ''\n session.add(user)\n\n def update(self, update, s=None):\n if s is None:\n with session_scope() as session:\n self._update(update, session)\n else:\n self._update(update, s)\n\n def schedule_update(self, msg: twitchirc.ChannelMessage):\n global modified_users\n has_state_change = False\n was_changed = False\n\n if msg.user != self.last_known_username:\n was_changed = True\n\n old_perms = self.permissions_raw\n self.export_permissions()\n if old_perms != self.permissions_raw:\n was_changed = True\n has_state_change = True\n if was_changed:\n modified_users[self.id] = {\n 'last_active': datetime.datetime.now(),\n 'msg': msg,\n 'expire_time': (time.time() + 10) if has_state_change else (time.time() + CACHE_EXPIRE_TIME)\n }\n\n @property\n @deprecated()\n def mod_in(self):\n return [] if self.mod_in_raw == '' else self.mod_in_raw.replace(', ', ',').split(',')\n\n @property\n @deprecated()\n def sub_in(self):\n return [] if self.sub_in_raw == '' else self.sub_in_raw.replace(', ', ',').split(',')\n\n def __repr__(self):\n return f''\n\n\n def _update_users(to_update):\n try:\n with session_scope() as session:\n for db_id, update in to_update.copy().items():\n log('debug', db_id, 'updating dankCircle')\n if db_id is None:\n log('debug', 'create new')\n user = User.get_by_message(update['msg'])\n user.update(update, session)\n continue\n\n user = User.get_by_local_id(db_id)\n user.update(update, session)\n log('debug', 'Deleting to_updates.')\n for db_id in to_update:\n del modified_users[db_id]\n finally:\n log('debug', 'release lock.')\n users_lock.release()\n\n def flush_users():\n if users_lock.locked():\n return\n users_lock.acquire()\n current_time = int(time.time())\n to_update = {}\n for db_id, user in modified_users.copy().items():\n if user['expire_time'] <= current_time:\n log('debug', f'flush user {db_id}')\n to_update[db_id] = user\n if to_update:\n log('debug', f'users cache is of length {len(modified_users)}, {len(to_update)} are going to be '\n f'removed from the cache.')\n\n t = threading.Thread(target=_update_users, args=(to_update,), kwargs={})\n t.start()\n else:\n users_lock.release()\n\n return User, flush_users\n\n\nusers_lock = threading.Lock()\n","repo_name":"Mm2PL/MmsUtilityBot","sub_path":"plugins/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":10950,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"53"}
+{"seq_id":"3628122680","text":"import packet_sniffer as ps\nimport socket\nimport time\n\nstart = time.time()\narp = {}\n\ns = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))\nwhile True: \n time.sleep(1)\n raw_data, addr = s.recvfrom(1518)\n eth = ps.ethernet_head(raw_data)\n if eth[2] == 8:\n ipv4 = ps.ipv4_head(eth[3])\n\n if ipv4[4] not in arp:\n arp.update({ipv4[4] : eth[1]})\n if ipv4[5] not in arp:\n arp.update({ipv4[5] : eth[0]})\n \n \n end = time.time()\n if (end - start) > 60:\n print(\"IP\\t\\t\\t\\tMAC\")\n for ip in arp.keys():\n print(\"{}\\t->\\t{}\".format(ip, arp[ip]))\n break","repo_name":"mattebernini/my-packets-sniffer","sub_path":"ARP-like.py","file_name":"ARP-like.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29133863462","text":"import re\nimport tempfile\n\nfrom canrevan import DEFAULT_USER_AGENT_STRING\nfrom canrevan.crawling import Crawler\n\n_dummy_urls = [\n f\"https://news.naver.com/main/list.nhn?mode=LSD&mid=shm\"\n f\"&sid1=100&date=20200501&page={page}\"\n for page in range(1, 3)\n]\n\n\ndef _get_current_page_from_html(content: str) -> int:\n content = content[content.find('') :]\n content = content[: content.find(\"
\")]\n\n return int(re.search(r\"(.*?)\", content).group(1))\n\n\ndef test_crawl_reduce_array():\n crawler = Crawler(\n concurrent_tasks=500,\n request_headers={\"user-agent\": DEFAULT_USER_AGENT_STRING},\n request_timeout=1,\n )\n current_pages = crawler.reduce_to_array(\n _dummy_urls, parse_fn=_get_current_page_from_html\n )\n\n for page in current_pages:\n # Note that we only crawled up to 3 pages from each category and date.\n assert isinstance(page, int)\n assert page < 3\n\n\ndef test_crawl_reduce_file():\n crawler = Crawler(\n concurrent_tasks=500,\n request_headers={\"user-agent\": DEFAULT_USER_AGENT_STRING},\n request_timeout=1,\n )\n\n with tempfile.TemporaryDirectory() as tdir:\n written = crawler.reduce_to_file(\n _dummy_urls,\n filename=f\"{tdir}/crawled.txt\",\n parse_fn=_get_current_page_from_html,\n )\n\n # With a high probability, there must be successfully crawled data.\n assert written > 0\n\n with open(f\"{tdir}/crawled.txt\", \"r\") as fp:\n for page in fp:\n page = int(page.strip())\n\n # Note that we only crawled up to 3 pages from each category\n # and date.\n assert page < 3\n","repo_name":"affjljoo3581/canrevan","sub_path":"tests/test_crawling.py","file_name":"test_crawling.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"53"}
+{"seq_id":"19273991265","text":"# encoding: utf-8\n'''\nModified from https://gist.github.com/barneygale/1209061\n'''\n\nfrom random import choice\nfrom struct import pack, unpack\nfrom string import ascii_lowercase, digits\n\nfrom Crypto.Hash import SHA\n\ndef pack_short(h):\n return pack('>H', h)\n\ndef unpack_short(h):\n return unpack('>H', h)[0]\n\ndef unpack_varint(s):\n d = 0\n for i in range(5):\n b = s[i]\n d |= (b & 0x7F) << 7*i\n if not b & 0x80:\n break\n return d, i+1\n\ndef unpack_varint_fromstring(s):\n d = 0\n for i in range(5):\n b = ord(s[i])\n d |= (b & 0x7F) << 7*i\n if not b & 0x80:\n break\n return d, i+1\n\ndef pack_varint(d):\n o = \"\"\n while True:\n b = d & 0x7F\n d >>= 7\n o += chr(b | (0x80 if d > 0 else 0))\n if d == 0:\n break\n return o\n\ndef pack_data(d):\n return pack_varint(len(d)) + d\n\ndef pseudorandom_string(l):\n s = ''\n selection = ascii_lowercase + '_' + digits\n while l:\n s += choice(selection)\n l -= 1\n return s\n\ndef login_hash(server_id, shared_secret, public_key):\n \"\"\"\n Returns the server id which is then used for joining a server.\n https://github.com/sadimusi/mc4p/blob/master/mc4p/authentication.py\n \"\"\"\n sha = SHA.new()\n sha.update(server_id)\n sha.update(shared_secret)\n sha.update(public_key)\n d = long(sha.hexdigest(), 16)\n if d >> 39 * 4 & 0x8:\n return \"-%x\" % ((-d) & (2 ** (40 * 4) - 1))\n return \"%x\" % d\n","repo_name":"mcnz/authserv","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21454930225","text":"# -*- coding: utf-8 -*-\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nimport collections\nclass Solution(object):\n def verticalTraversal(self, root):\n \"\"\"\n Perf: Runtime: 16 ms, faster than 97.54% / Memory Usage: 12.1 MB, less than 46.51%\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n _res = collections.defaultdict(list)\n\n def _traversal(node):\n stack = [(node, 0)]\n while stack:\n _tmp = collections.defaultdict(list)\n for i in range(len(stack)):\n _node, column = stack.pop(0)\n _tmp[column].append(_node.val)\n if _node.left:\n stack.append((_node.left, column - 1))\n if _node.right:\n stack.append((_node.right, column + 1))\n for k, v in _tmp.iteritems():\n _res[k] += sorted(v)\n\n _traversal(root)\n min_k = min(_res.keys())\n max_k = max(_res.keys())\n res = []\n for k in range(min_k, max_k + 1):\n res.append(_res[k])\n return res\n","repo_name":"jerrt2003/leetcode-in-python","sub_path":"Interview_Feedback/Facebook/4-6/987. Vertical Order Traversal of a Binary Tree/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17999493411","text":"from mathhelper import matrix,permutecomb,graph\n\n\nprint(\"Welcome!!\")\nprint(\"Mathhelper is an efficient module to solve your doubts and homework problems, quickly and always correctly.\")\n\nprint(\"\"\"Currently available prompts:\n1. Matrices\n2. Determinants\n2. Permutations\n3. Combinations\n4. Plot Graph\"\"\")\nwhile True:\n cmd=input(\"What do you need help with today?\\n\")\n\n if cmd=='menu':\n print()\n print(\"\"\"Currently available prompts:\n1. Matrices\n2. Determinants\n2. Permuations\n3. Combinations\n4. Plot Graph\"\"\")\n print()\n\n elif cmd.lower() == 'matrices':\n print(\"Currently available operations:\",\"1. Addition\",\"2. Subtraction\",\"3. Multiplication\",sep=\"\\n\")\n type = input(\"Enter Operation: \")\n \n if type.lower()=='addition':\n order=input(\"Enter order of matrices: \")\n rows=int(order.partition('x')[0])\n cols=int(order.partition('x')[2])\n print(\"rows1, cols1 =\",rows, cols)\n print(\"rows2, cols2 =\",rows, cols)\n matrix.matrix1(matrix,rows,cols)\n matrix.matrix2(matrix,rows,cols)\n print()\n t=input(\"Press Enter to continue: \")\n matrix.add(matrix)\n elif type.lower()=='subtraction':\n order=input(\"Enter order of matrices: \")\n rows=int(order.partition('x')[0])\n cols=int(order.partition('x')[2])\n print(\"rows1, cols1 =\",rows, cols)\n print(\"rows2, cols2 =\",rows, cols)\n matrix.matrix1(matrix,rows,cols)\n matrix.matrix2(matrix,rows,cols)\n print()\n t=input(\"Press Enter to continue: \")\n matrix.subtract(matrix)\n elif type.lower()=='multiplication':\n while True:\n order1=input(\"Enter order of matrix A: \")\n order2=input(\"Enter order of matrix B: \")\n rows1=int(order1.partition('x')[0])\n cols1=int(order1.partition('x')[2])\n rows2=int(order2.partition('x')[0])\n cols2=int(order2.partition('x')[2])\n if cols1!=rows2:\n print(\"Matrix order invalid\")\n else:\n break\n print(\"rows1, cols1 =\",rows1, cols1)\n print(\"rows2, cols2 =\",rows2, cols2)\n matrix.matrix1(matrix,rows1,cols1)\n matrix.matrix2(matrix,rows2,cols2)\n print()\n t=input(\"Press Enter to continue: \")\n matrix.product(matrix)\n\n elif cmd.lower()=='determinants':\n order=input(\"Enter order of matrix: \")\n rows=int(order.partition('x')[0])\n cols=int(order.partition('x')[2])\n print(\"rows, cols =\",rows, cols)\n matrix.matrix1(matrix,rows,cols)\n print()\n t=input(\"Press Enter to continue: \")\n matrix.determinant(matrix)\n\n\n elif cmd.lower() =='permutations':\n quest=input(\"Question: \")\n quest=quest.split()\n num1=int(quest[quest.index('from')+1])\n num2=int(quest[quest.index('select')+1])\n permutecomb.permutation(permutecomb,num1,num2)\n elif cmd.lower() =='combinations':\n quest=input(\"Question: \")\n quest=quest.split()\n num1=int(quest[quest.index('from')+1])\n num2=int(quest[quest.index('select')+1])\n permutecomb.combination(permutecomb,num1,num2)\n elif cmd.lower()=='plot graph':\n print(\"Graphs currently available:\",\"1. sine graph\",\"2. cosine graph\",\"3. tan graph\",\"4. cot graph\",\"5. cosec graph\",\"6. sec graph\",\"7. sine inverse graph\",\"8. cosine inverse graph\",\"9. bar graph\",\"10. line graph\",sep=\"\\n\") \n print()\n type=input(\"Enter Graph Type: \")\n if type.lower()=='sine graph':\n graph.sine()\n elif type.lower()=='cosine graph':\n graph.cosine()\n elif type.lower()=='tan graph':\n graph.tan()\n elif type.lower()=='cot graph':\n graph.cot()\n elif type.lower()=='cosec graph':\n graph.cosec()\n elif type.lower()=='sec graph':\n graph.sec()\n elif type.lower()=='sine inverse graph':\n graph.sineinvere()\n elif type.lower()=='bar graph':\n graph.bar()\n elif type.lower()=='line graph':\n graph.line()\n else:\n break\n\n","repo_name":"natharyan/Mathhelper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17519691566","text":"from xerial.OracleDBSession import OracleDBSession\nfrom xerial.AsyncDBSessionBase import AsyncDBSessionBase\nfrom xerial.AsyncRoundRobinConnector import AsyncRoundRobinConnector\n\nimport logging, traceback, time\n\ntry :\n\timport cx_Oracle_async\n\timport cx_Oracle\nexcept :\n\tlogging.warning(\"Module cx_Oracle_async cannot be imported.\")\n\nclass AsyncOracleDBSession (OracleDBSession, AsyncDBSessionBase) :\n\tasync def createConnection(self):\n\t\tself.pool = await cx_Oracle_async.create_pool(\n\t\t\thost=self.config['host'],\n\t\t\tport=self.config['port'],\n\t\t\tuser=self.config['user'],\n\t\t\tpassword=self.config['password'],\n\t\t\tservice_name=self.config['domain'],\n\t\t)\n\t\tself.connection = await self.pool.acquire()\n\t\tself.connection.autocommit = True\n\t\tself.cursor = await self.connection.cursor()\n\n\tasync def closeConnection(self) :\n\t\tdel self.cursor\n\t\tdel self.connection\n\n\tasync def executeRoundRobinRead(self, query, parameter=None) :\n\t\tself.queryCount += 1\n\t\tcursor = self.connection.getNextReadCursor()\n\t\ttry :\n\t\t\tif parameter is None :\n\t\t\t\tawait cursor.execute(query)\n\t\t\telse :\n\t\t\t\tawait cursor.execute(query, parameter)\n\t\t\treturn await cursor.fetchall()\n\t\texcept Exception as error :\n\t\t\tlogging.error(query)\n\t\t\tlogging.error(parameter)\n\t\t\tawait self.closeConnection()\n\t\t\tawait self.connect()\n\t\t\traise error\n\t\n\tasync def executeRoundRobinWrite(self, query, parameter=None) :\n\t\tself.queryCount += 1\n\t\tcursor = self.connection.writerCursor\n\t\ttry :\n\t\t\tif parameter is None :\n\t\t\t\tawait cursor.execute(query)\n\t\t\telse :\n\t\t\t\tawait cursor.execute(query, parameter)\n\t\texcept Exception as error :\n\t\t\tlogging.error(query)\n\t\t\tlogging.error(parameter)\n\t\t\tawait self.closeConnection()\n\t\t\tawait self.connect()\n\t\t\traise error\n\n\tasync def executeRegularRead(self, query, parameter=None) :\n\t\tself.queryCount += 1\n\t\ttry :\n\t\t\tif parameter is None :\n\t\t\t\tawait self.cursor.execute(query)\n\t\t\telse :\n\t\t\t\tawait self.cursor.execute(query, parameter)\n\t\t\treturn await self.cursor.fetchall()\n\t\texcept Exception as error :\n\t\t\tlogging.error(query)\n\t\t\tawait self.closeConnection()\n\t\t\tawait self.connect()\n\t\t\traise error\n\t\n\tasync def executeRegularWrite(self, query, parameter=None):\n\t\tself.queryCount += 1\n\t\ttry :\n\t\t\tif parameter is None :\n\t\t\t\tawait self.cursor.execute(query)\n\t\t\telse :\n\t\t\t\tawait self.cursor.execute(query, parameter)\n\t\texcept Exception as error :\n\t\t\tlogging.error(query)\n\t\t\tawait self.closeConnection()\n\t\t\tawait self.connect()\n\t\t\traise error\n\t\n\tasync def insert(self, record, isAutoID=True):\n\t\tmodelClass = record.__class__\n\t\tquery = self.generateInsert(modelClass, isAutoID)\n\t\tif modelClass.__backup__ :\n\t\t\tnow = time.time()\n\t\t\trecord.__insert_time__ = now\n\t\t\trecord.__update_time__ = -1.0\n\t\tparameter = self.getRawValue(record, isAutoID)\n\t\tif modelClass.__insert_parameter__ :\n\t\t\tinsertedID = self.cursor._cursor.var(cx_Oracle.NUMBER)\n\t\t\tparameter.append(insertedID)\n\t\tawait self.executeWrite(query, parameter)\n\t\tif not isAutoID :\n\t\t\tif len(modelClass.children) :\n\t\t\t\tawait self.insertChildren(record, modelClass)\n\t\telif modelClass.__is_increment__ :\n\t\t\tlastRow = insertedID.values[0][0]\n\t\t\tsetattr(record, modelClass.primary, lastRow)\n\t\t\tif len(modelClass.children) :\n\t\t\t\tawait self.insertChildren(record, modelClass)\n\t\t\treturn lastRow\n\t\telif len(modelClass) > 0 :\n\t\t\tlogging.warning(f\"Primary key of {modelClass.__tablename__} is not auto generated. Children cannot be inserted.\")\n\t\n\tasync def insertMultiple(self, recordList, isAutoID=True, isReturningID=False) :\n\t\tif len(recordList) == 0 : return\n\t\tif isAutoID and isReturningID :\n\t\t\tkeyList = []\n\t\t\tfor record in recordList :\n\t\t\t\tkeyList.append(await self.insert(record))\n\t\t\treturn keyList\n\t\tvalueList = []\n\t\tmodelClass = None\n\t\thasChildren = False\n\t\tfor record in recordList :\n\t\t\tif modelClass is None :\n\t\t\t\tmodelClass = record.__class__\n\t\t\t\tquery = self.generateInsert(modelClass, isAutoID, isMultiple=True)\n\t\t\t\tisBackup = modelClass.__backup__\n\t\t\t\tnow = time.time()\n\t\t\t\tif len(modelClass.children) :\n\t\t\t\t\thasChildren = True\n\t\t\t\t\tbreak\n\t\t\tif isBackup :\n\t\t\t\trecord.__insert_time__ = now\n\t\t\t\trecord.__update_time__ = -1.0\n\t\t\tvalueList.append(self.getRawValue(record, isAutoID))\n\t\t\t\n\t\tif hasChildren :\n\t\t\tfor record in recordList :\n\t\t\t\tawait self.insert(record)\n\t\t\treturn\n\n\t\tquery = self.generateInsert(modelClass, isAutoID, isMultiple=True)\n\t\tfor value in valueList :\n\t\t\tawait self.executeWrite(query, value)\n\t\n\tasync def insertMultipleDirect(self, modelClass, rawList) :\n\t\tvalueList = [self.toTuple(modelClass, raw) for raw in rawList]\n\t\tquery = self.generateInsert(modelClass, isAutoID=False, isMultiple=True)\n\t\tfor value in valueList :\n\t\t\tawait self.executeWrite(query, value)\n\t\n\tasync def update(self, record) :\n\t\tmodelClass = record.__class__\n\t\tif modelClass.__backup__ :\n\t\t\trecord.__update_time__ = time.time()\n\t\tvalue = self.getRawValue(record)\n\t\tawait self.executeWrite(self.generateUpdate(record), value)\n\t\tif len(modelClass.children) :\n\t\t\tawait self.updateChildren(record, modelClass)\n\t\n\tasync def updateDirect(self, modelClass, raw) :\n\t\tvalue = self.toTuple(modelClass, raw)\n\t\tquery = self.generateRawUpdate(modelClass, raw)\n\t\tawait self.executeWrite(query, value)\n\t\n\tasync def drop(self, record) :\n\t\tawait self.dropChildren(record, record.__class__)\n\t\ttable = record.__fulltablename__\n\t\tquery = \"DELETE FROM %s WHERE %s\"%(table, self.getPrimaryClause(record))\n\t\tawait self.executeWrite(query)\n\t\n\tasync def dropByID(self, modelClass, ID) :\n\t\tif not hasattr(modelClass, 'primaryMeta') :\n\t\t\tlogging.warning(f\"*** Warning {modelClass.__fulltablename__} has not primary key and cannot be dropped by ID.\")\n\t\t\treturn\n\t\tawait self.dropChildrenByID(ID, modelClass)\n\t\ttable = modelClass.__fulltablename__\n\t\tmeta = modelClass.primaryMeta\n\t\tID = meta.setValueToDB(ID)\n\t\tquery = \"DELETE FROM %s WHERE %s=%s\"%(table, modelClass.primary, ID)\n\t\tawait self.executeWrite(query)\n\t\n\tasync def dropByCondition(self, modelClass, clause) :\n\t\ttable = modelClass.__fulltablename__\n\t\tparentQuery = f\"SELECT {modelClass.primary} FROM {table} {clause}\"\n\t\tfor child in modelClass.children :\n\t\t\tchildTable = child.model.__fulltablename__\n\t\t\tquery = f\"DELETE FROM {childTable} WHERE {child.column} IN ({parentQuery})\"\n\t\t\tawait self.executeWrite(query)\n\t\tquery = \"DELETE FROM %s WHERE %s\"%(table, clause)\n\t\tawait self.executeWrite(query)\n\t\n\tasync def createTable(self) :\n\t\tawait self.getExistingTable()\n\t\tfor model in self.model.values() :\n\t\t\tif hasattr(model, '__skip_create__') and getattr(model, '__skip_create__') : continue\n\t\t\tif model.__tablename__.upper() in self.existingTable : continue\n\t\t\tself.generateCreatTable(model)\n\t\t\tquery = self.generateCreatTable(model)\n\t\t\tlogging.info(f\"Creating Table {model.__tablename__}\")\n\t\t\tawait self.executeWrite(query)\n\t\tawait self.getExistingTable()\n\n\t\tfor model in self.model.values() :\n\t\t\tif hasattr(model, '__skip_create__') and getattr(model, '__skip_create__') : continue\n\t\t\tif model.__tablename__.upper() in self.existingTable :\n\t\t\t\tawait self.createIndex(model)\n\t\n\tasync def createIndex(self, model) :\n\t\tresult = await self.executeRead(self.generateIndexQuery(model))\n\t\texistingIndex = {i[0].upper() for i in result}\n\t\tfor name, column in model.meta :\n\t\t\tname = name.upper()\n\t\t\tif column.isIndex and name not in existingIndex:\n\t\t\t\tawait self.executeWrite(self.generateCreateIndex(model, name))\n\t\n\tasync def getExistingTable(self) :\n\t\tresult = await self.executeRead(self.generateCheckTable())\n\t\tself.owner = {row[0]:row[1] for row in result}\n\t\tself.existingTable = list(self.owner.keys())\n\t\tfor model in self.model.values() :\n\t\t\ttableName = model.__tablename__.upper()\n\t\t\towner = self.owner.get(tableName)\n\t\t\tif owner is not None :\n\t\t\t\tmodel.__fulltablename__ = f\"{owner}.{tableName}\"\n\t\t\telse :\n\t\t\t\tmodel.__fulltablename__ = tableName\n\t\treturn self.existingTable","repo_name":"Piyawanno/Xerial","sub_path":"xerial/AsyncOracleDBSession.py","file_name":"AsyncOracleDBSession.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"2316615827","text":"__author__ = \"Valentin Giannini\"\n__copyright__ = \"Copyright 2016, LAMA\"\n__credits__ = [\"\"]\n__license__ = \"GPL\"\n__version__ = \"3\"\n__maintainer__ = \"Valentin Giannini - CSE Team\"\n__email__ = \"cse.contact -at- post.lu\"\n__status__ = \"Production\"\n\n\nimport jsbeautifier\nimport json\nimport base64\n\nresult_dict = dict()\n\ntry:\n res = jsbeautifier.beautify_file('/lama/sample')\n res = res.encode('utf-8')\n result_dict['code'] = base64.b64encode(res)\nexcept (UnicodeDecodeError, UnicodeEncodeError) as e:\n result_dict['error'] = base64.b64encode(str(e))\nexcept Exception as e:\n result_dict['error'] = base64.b64encode(str(e))\n\nprint(json.dumps(result_dict))\n","repo_name":"post-cyberlabs/lama","sub_path":"lama/docker/jsbeautifier/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"12746708847","text":"print(\"usuario porfavor digite su capital en la consola porfavor\")\n\nCapital = float(input(\"Capital : \"))\nprint(\"por cada mes la capital auenta 1.2%\")\n\nMes = int(input(\"ingrese cuantos meses desear guardar su capital : \"))\n\nporcentaje = float(Mes*1.2)\nGanancia =(Capital * porcentaje)\n\nif float(Capital) :\n print(f\"las ganancias esperadas son de {Ganancia}$\")\nelse:\n print(\"ese valor no es calculable\")\n","repo_name":"Heindelf/Primero","sub_path":"ejerciciosChristian/PYTHON/inicio2.py","file_name":"inicio2.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10305447809","text":"\"\"\"\nHelper tool for reverse engineering steps\n\n Written by Daniel Sungju Kwon\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom pykdump.API import *\n\nimport sys\nimport os\nfrom optparse import OptionParser\n\n\narch_register_list = {}\ninstruction_list = {}\n\ndef show_register_details(arch):\n arch = arch.lower()\n for arch_list_str in arch_register_list:\n arch_list = arch_list_str.split()\n if (arch in arch_list):\n register_details = arch_register_list[arch_list_str]\n print(\"%s\" % (register_details))\n\n\ndef show_asm_details( asm_inst ):\n asm_inst = asm_inst.lower()\n for inst_list_str in instruction_list:\n inst_list = inst_list_str.split()\n if (asm_inst in inst_list):\n inst_man = instruction_list[inst_list_str]\n print (\"%s\" % (inst_man))\n return\n\n return\n\n\ndef show_asm_list():\n for inst_list_str in instruction_list:\n print(\"%s\" % (inst_list_str.strip()))\n\ndef show_registers():\n arch = sys_info.machine\n if (arch in (\"x86_64\", \"i386\", \"i686\", \"athlon\")):\n show_register_details(arch)\n if (sys_info.machine.startswith(\"arm\")):\n show_register_details(\"arm\")\n if (arch in (\"aarch64\")):\n show_register_details(\"aarch64\")\n if (sys_info.machine.startswith(\"ppc\")):\n show_register_details(\"ppc\")\n if (sys_info.machine.startswith(\"s390\")):\n show_register_details(\"s390\")\n\n\ndef load_asm_set():\n read_database(\"revs.data\")\n\n arch = sys_info.machine\n if (arch in (\"x86_64\", \"i386\", \"i686\", \"athlon\")):\n read_database(\"x86asm.data\")\n if (sys_info.machine.startswith(\"arm\")):\n read_database(\"armasm.data\")\n if (arch in (\"aarch64\")):\n read_database(\"armasm.data\")\n\n\ndef is_arch_match(arch, arch_list_str):\n arch_list = arch_list_str.split()\n for arch_entry in arch_list:\n if arch.startswith(arch_entry):\n return True\n return False\n\n\ndef read_database(filename):\n file_lines = []\n try:\n cmd_path_list = os.environ[\"PYKDUMPPATH\"]\n path_list = cmd_path_list.split(':')\n source_file = \"\"\n for path in path_list:\n if os.path.exists(path + (\"/%s\" % filename)):\n source_file = path + (\"/%s\" % filename)\n break\n\n arch = sys_info.machine\n arch_total_msg = \"\"\n with open(source_file, 'r', encoding=\"utf-8\") as f:\n for line in f:\n words = line.split(\":\")\n if words[0] == \"ARCHITECTURE\":\n arch_list = words[1]\n if is_arch_match(arch, arch_list) == False:\n continue\n\n for detail_line in f:\n if detail_line == \"END_\" + line:\n break\n arch_total_msg = arch_total_msg + detail_line\n\n\n inst_set = [\"REGISTERS\", \"INSTRUCTION\"]\n cur_mode = 0\n cur_data_line = \"\"\n arch_list = \"\"\n total_line = \"\"\n\n for line in arch_total_msg.splitlines():\n words = line.split(\":\")\n if words[0] in inst_set:\n cur_data_line = line\n if words[0] == \"REGISTERS\":\n arch_list = words[1].lower() # don't split yet\n total_line = \"\"\n cur_mode = 1\n elif words[0] == \"INSTRUCTION\":\n inst_list = words[1].lower() # don't split yet\n total_line = \"\"\n cur_mode = 2\n elif line == \"END_\" + cur_data_line:\n if cur_mode == 1: # register\n arch_register_list[arch_list] = total_line\n elif cur_mode == 2: # instruction\n instruction_list[inst_list] = total_line\n\n cur_data_line = \"\"\n arch_list = \"\"\n inst_list = \"\"\n total_line = \"\"\n cur_mode = 0\n else:\n total_line = total_line + line + \"\\n\"\n\n except Exception as e:\n print(e)\n print(\"Failed to read file %s\" % (source_file))\n return\n\n\ndef revs():\n op = OptionParser()\n op.add_option(\"-r\", \"--regs\", dest=\"Regs\", default=0,\n action=\"store_true\",\n help=\"Registers used for argument passing\")\n\n op.add_option(\"-a\", '--asm', dest='Asm', default=\"\",\n action=\"store\",\n help=\"Simple manual for GNU assembly\")\n\n op.add_option(\"-l\", '--list', dest='List', default=0,\n action=\"store_true\",\n help=\"Shows the list of instructions you can check details\")\n\n (o, args) = op.parse_args()\n\n\n load_asm_set()\n if (o.Asm != \"\"):\n show_asm_details(o.Asm)\n sys.exit(0)\n\n if (o.Regs):\n show_registers()\n sys.exit(0)\n\n\n if (o.List):\n show_asm_list()\n sys.exit(0)\n\n show_registers()\n\n\n return\n\nif ( __name__ == '__main__'):\n revs()\n","repo_name":"sungju/pycrashext","sub_path":"source/revs.py","file_name":"revs.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"53"}
+{"seq_id":"5914958934","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 25 23:05:53 2020\r\n\r\n@author: Unnat Antani\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nimport math\r\n\r\n\r\nxdata_1 = []\r\nxdata_2 = []\r\n\r\nydata_1 = []\r\nydata_2 = []\r\n\r\nplt.show()\r\n \r\naxes = plt.gca()\r\naxes.set_xlim(-500, 500)\r\naxes.set_ylim(-500, 500)\r\n\r\nline1, = axes.plot(xdata_1, ydata_1, 'ro', markersize = 50) \r\nline2, = axes.plot(xdata_2, ydata_2, 'bo')\r\n\r\npos_y_1= 0\r\npos_x_1= 0-200\r\nm1 = 10e15 #mass of left dot\r\n\r\npos_y_2 = 0\r\npos_x_2 = 200\r\nm2 = 10 #mass of right dot\r\n\r\nG = 6.67428e-11\r\n\r\ngrav_force = G*m1*m2/((pos_x_2 - pos_x_1)**2 + (pos_y_2 - pos_y_1)**2)\r\na1 = grav_force/m1\r\na2 = grav_force/m2\r\n\r\ni = 0\r\ntime.sleep(10)\r\nwhile True:\r\n \r\n pos_x_1 = pos_x_1 + 0.5*a1*(i**2)\r\n pos_x_2 = pos_x_2 - 0.5*a2*(i**2)\r\n \r\n pos_x = [pos_x_1,pos_x_2]\r\n pos_y = [pos_y_1,pos_y_2]\r\n i = i + 0.1\r\n if (pos_x_2-pos_x_1) <= 0:\r\n\r\n break\r\n else:\r\n xdata_1.append(pos_x_1)\r\n ydata_1.append(pos_y_1)\r\n xdata_2.append(pos_x_2)\r\n ydata_2.append(pos_y_2)\r\n line1.set_xdata(xdata_1)\r\n line1.set_ydata(ydata_1)\r\n line2.set_xdata(xdata_2)\r\n line2.set_ydata(ydata_2)\r\n \r\n plt.xlabel(\"t = {}\".format(i-0.1))\r\n plt.draw()\r\n plt.pause(0.01)\r\n time.sleep(0.1)\r\n \r\n \r\nplt.show()\r\n\r\n","repo_name":"unnat42/Physics","sub_path":"Gravity.py","file_name":"Gravity.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"27052790590","text":"from pprint import pformat\n\nfrom dq0.sdk.data.metadata.interface.interface import Interface\nfrom dq0.sdk.data.metadata.specification.dataset.v1.specification_v1 import SpecificationV1 as DatasetSpecificationV1\nfrom dq0.sdk.data.metadata.structure.metadata import Metadata\n\n\ndef output_metadata(m_interface, request_uuids, step, full=False):\n step += 1\n out_object = pformat(m_interface.to_dict(request_uuids=request_uuids, full=full)) if full else m_interface.__str__(request_uuids=request_uuids)\n print(\"-------------------------------------------------------------------------------------\\n\"\n f\"Metadata after step {step}:\" \"\\n\"\n \"----------------------\\n\"\n f\"{out_object}\" \"\\n\"\n \"-------------------------------------------------------------------------------------\")\n return step\n\n\ndef test_metadata_build():\n step = 0\n\n # define uuids for rights management.\n # use None to set default role rights and perform requests in 'god mode'.\n role_uuids = None\n request_uuids = None\n\n # define specifications that you would like to be used in the new Metadata.\n specifications = {\n 'dataset': DatasetSpecificationV1(role_uuids=role_uuids),\n }\n\n # STEP 1\n # define the empty Metadata.\n metadata = Metadata(nodes={}, specifications=specifications)\n\n # as usual, obtain the interface from the metadata.\n # role_uuids are used for default permissions on new meta elements.\n m_interface = Interface(metadata=metadata, role_uuids=role_uuids)\n\n # the metadata is empty\n assert len(metadata) == 0\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 2\n # get new dataset object\n m_dataset = m_interface.dataset(name='test_dataset')\n\n # at this point you may call create() on the dataset or write any attribute field to create it.\n # however, one may also continue without directly creating it.\n # creation will happen automatically once the first dependent element is created.\n\n # get new database and connector attribute group objects.\n connector = m_dataset.database(name='test_database').connector\n\n # the metadata is still empty, as no element has been created yet.\n assert len(metadata) == 0\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 3\n # set the first attribute on connector (must be type_name as other fields only work if this one is present).\n connector.type_name = 'csv'\n\n # setting the attribute field forced creation of all underlying meta elements.\n assert len(metadata) == 1\n assert len(metadata.get_node(root_key='dataset')) == 1\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 4\n # set the csv's uri=filepath and you have created a useful minimal metadata\n connector.uri = '../dq0-sdk/dq0/examples/census/_data/adult_with_rand_names.csv'\n\n # the resulting metadata\n assert metadata.get_node(root_key='dataset').get_child_node(index=0).get_attribute(key='connector').get_attribute(\n key='uri').get_value() == '../dq0-sdk/dq0/examples/census/_data/adult_with_rand_names.csv'\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 5\n # continue until the first column\n m_column = m_dataset.database().schema(name='test_schema').table(name='test_table').column(name='test_column_a')\n\n # observe that database can be called without arguments, which is equivalent to calling with index=0 and which\n # works here, because database already exists. all other elements must be called by their new name.\n\n # there are no changes yet, as you have not created the column yet.\n assert len(metadata.get_node(root_key='dataset').get_child_node(index=0)) == 0\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 6\n # similar to connector depending on its type_name, many attribute groups of column depend on its data_type_name.\n # thus, you should set it early on.\n m_column.data.data_type_name = 'int'\n\n # again, setting the attribute forced creation.\n assert len(metadata.get_node(root_key='dataset').get_child_node(index=0)) == 1\n assert len(metadata.get_node(root_key='dataset').get_child_node(index=0).get_child_node(index=0)) == 1\n assert len(metadata.get_node(root_key='dataset').get_child_node(index=0).get_child_node(index=0).get_child_node(index=0)) == 1\n column = metadata.get_node(root_key='dataset').get_child_node(index=0).get_child_node(index=0).get_child_node(index=0).get_child_node(index=0)\n assert column.get_attribute(key='data').get_attribute(key='name').get_value() == 'test_column_a'\n assert column.get_attribute(key='data').get_attribute(key='data_type_name').get_value() == 'int'\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 7\n # Try changing connector type (this action is not allowed, as other connector fields depend on the type)\n try:\n connector.type_name = 'postgresql'\n except Exception as e:\n print(\"Step 7: Trying to set 'connector.type_name' to 'postgresql'\\n\"\n f\" correctly raised Exception '{e}'.\"\n \"\\n One may delete the whole connector, though.\")\n\n # however, one may delete the whole connector. [del only works if called with the accessor of the parent,\n # i.e., 'del m_database.connector' works, just 'del connector' does not work.]\n del m_dataset.database().connector\n\n # the connector is gone.\n assert metadata.get_node(root_key='dataset').get_child_node(index=0).get_attribute(key='connector') is None\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 8\n # create a different connector. The same 'connector' object continues to work, however, it is empty after\n # we deleted the previous connector.\n connector.type_name = 'postgresql'\n\n # the new connector appears.\n assert metadata.get_node(root_key='dataset').get_child_node(index=0).get_attribute(key='connector').get_attribute(\n key='type_name').get_value() == 'postgresql'\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 9\n # set the remaining attributes, to make it a useful connector.\n connector.host = 'postgresql1.dq0.io'\n connector.port = 5432\n connector.username = 'db_user'\n connector.password = 'super_secret_dp_password_that_noone_may_ever_even_imagine'\n\n # again, a useful metadata.\n assert metadata.get_node(root_key='dataset').get_child_node(index=0).get_attribute(key='connector').get_attribute(\n key='password').get_value() == 'super_secret_dp_password_that_noone_may_ever_even_imagine'\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 10\n # to produce a valid metadata dataset requires not only a name but also a privacy level.\n m_interface.dataset().differential_privacy.privacy_level = 2\n\n # this is now a valid metadata\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 11\n # to prove validity we use the appropriate functionality\n m_interface = m_interface.apply_defaults_and_verify()\n\n # note, that m_interface is a different object after this operation.\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step)\n\n # STEP 12\n # to see all the default permissions, we print the full format\n step = output_metadata(m_interface=m_interface, request_uuids=request_uuids, step=step, full=True)\n\n # finish test\n print(\"\\nTEST SUCCESSFUL!\")\n\n\nif __name__ == \"__main__\":\n test_metadata_build()\n","repo_name":"gradientzero/dq0-sdk","sub_path":"tests/test_metadata/test_metadata_build.py","file_name":"test_metadata_build.py","file_ext":"py","file_size_in_byte":7848,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"74502803687","text":"class Solution():\n def isUnique(self, string: str):\n '''Checks whether a given string has unique characters only\n \n Inputs\n ------\n string: str\n string to be checked for unique chars\n\n Assumptions\n ------------\n Whitespace ' ' is a character\n String is in ASCII-128\n\n Returns\n -------\n bool\n whether string has unique chars only\n\n '''\n if len(string) > 128: \n return False\n \n seen_chars = set()\n for char in string:\n if char in seen_chars:\n return False\n seen_chars.add(char)\n return True\n\nprint(Solution().isUnique('the quick brown'))\n# False\nprint(Solution().isUnique('the quickbrown'))\n# True\n","repo_name":"linminhtoo/algorithms","sub_path":"ArraysStrings/isUnique.py","file_name":"isUnique.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"641972573","text":"'''\n1283. Find the Smallest Divisor Given a Threshold\nhttps://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/\n'''\n\nclass Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n left, right = 1, max(nums)\n \n def check(k):\n return sum([(x-1) // k + 1 for x in nums]) <= threshold\n \n while left < right:\n mid = (left + right) // 2\n if check(mid):\n right = mid\n else:\n left = mid + 1\n return left","repo_name":"supawichable/leetcode","sub_path":"1283_find_the_smallest_divisor_given_a_threshold.py","file_name":"1283_find_the_smallest_divisor_given_a_threshold.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70181836969","text":"import os\r\nimport pyttsx3\r\nprint('===================================================================================')\r\nprint(' Chat Bot ')\r\nprint('===================================================================================')\r\npyttsx3.speak('Hello User,Please enter your name')\r\nname=input('Enter your name here : ')\r\n\r\npyttsx3.speak('Hey '+name+' , What can I do for you')\r\ncommand=input('What do you want to do : ')\r\n\r\nif(\"chrome\" in command):\r\n pyttsx3.speak('Enter URL for chrome')\r\n chrome=input('Enter URL for chrome : ')\r\n os.system('start chrome '+chrome)\r\n\r\nelif(\"notepad\" in command):\r\n pyttsx3.speak('Enter file name')\r\n notepad=input('Enter the filename (with extension) which you want to open with Notepad : ')\r\n os.system('notepad '+notepad)\r\n\r\nelif(\"date\" in command):\r\n pyttsx3.speak('You requested for date')\r\n os.system('date /t')\r\n\r\nelif(\"time\" in command):\r\n pyttsx3.speak('You requested for time')\r\n os.system('time /t')\r\n\r\nelif(\"cls\" in command or \"clear screen\" in command):\r\n pyttsx3.speak('Clearing the Screen')\r\n os.system('cls')\r\n\r\nelif(command=='Clear Screen And Run Bot'):\r\n pyttsx3.speak('You entered Clear Screen And Run Bot ')\r\n os.system('cls')\r\n os.system('python task1.py')\r\n\r\nelif(\"my ip\" in command):\r\n pyttsx3.speak('I P will be displayed shortly')\r\n os.system('ipconfig')\r\n\r\nelif(command=='Sleep System'):\r\n pyttsx3.speak('Enter Amount of time')\r\n amt=input('Enter amount of time : ')\r\n os.system('timeout '+amt)\r\nelse:\r\n print('Wrong Choice')\r\n pyttsx3.speak('You had entered wrong choice');","repo_name":"arushi09-hub/task1-python","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7568862394","text":"import codecs\nimport logging\nimport os\n\nimport pandas as pd\nfrom pandas import DataFrame\n\n\ndef encode_csv(csv_file_path: str, encoding: str = \"utf-8\") -> tuple[str, DataFrame]:\n \"\"\"\n Определяет кодировку CSV-файла и преобразует его в указанную кодировку. Возвращает путь к обработанному файлу и\n DataFrame с его содержимым.\n\n :param csv_file_path: путь к CSV-файлу.\n :param encoding: кодировка, в которую нужно преобразовать файл.\n :return: кортеж из пути к обработанному файлу и DataFrame с его содержимым.\n \"\"\"\n logging.info(f\"Определяем кодировку файла '{csv_file_path}'...\")\n with codecs.open(csv_file_path, \"r\", \"utf-8\") as f:\n detected_encoding = f.encoding\n\n if not detected_encoding or detected_encoding.lower().startswith(encoding):\n df = pd.read_csv(csv_file_path, encoding=encoding)\n else:\n logging.info(f\"Преобразуем файл '{detected_encoding}' в файл с кодировкой '{encoding}'...\")\n df = pd.read_csv(csv_file_path, encoding=detected_encoding)\n obj_cols = df.select_dtypes(include=[\"object\"]).columns\n df[obj_cols] = df[obj_cols].apply(lambda x: x.str.encode(encoding, \"ignore\").str.decode(encoding))\n os.remove(csv_file_path)\n csv_file_path = csv_file_path[:-4] + \"_\" + encoding + \".csv\"\n df.to_csv(csv_file_path, encoding=encoding, index=False)\n\n return csv_file_path, df\n","repo_name":"redboo/pancakeswap-scraper","sub_path":"utils/encode_csv.py","file_name":"encode_csv.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27014151430","text":"import copy\n\nfrom authlib.common.encoding import json_loads\n\nfrom didcomm.core.utils import parse_base64url_encoded_json\nfrom didcomm.unpack import unpack, Metadata\nfrom tests.test_vectors.common import TTestVector\nfrom tests.test_vectors.didcomm_messages.messages import TEST_MESSAGE\n\n\ndef decode_and_remove_jws_signatures(jws: str) -> dict:\n jws = json_loads(jws)\n jws[\"payload\"] = parse_base64url_encoded_json(jws[\"payload\"])\n for s in jws[\"signatures\"]:\n s[\"protected\"] = parse_base64url_encoded_json(s[\"protected\"])\n del s[\"signature\"]\n return jws\n\n\ndef decode_jwe_headers(jwe: str) -> dict:\n jwe = json_loads(jwe)\n protected = parse_base64url_encoded_json(jwe[\"protected\"])\n del protected[\"epk\"]\n recipients = jwe[\"recipients\"]\n for r in recipients:\n del r[\"encrypted_key\"]\n return {\"protected\": protected, \"recipients\": recipients}\n\n\ndef remove_signed_msg(metadata: Metadata) -> Metadata:\n metadata = copy.deepcopy(metadata)\n metadata.signed_message = None\n return metadata\n\n\nasync def check_unpack_test_vector(test_vector: TTestVector, resolvers_config):\n unpack_result = await unpack(resolvers_config, test_vector.value)\n assert unpack_result.message == TEST_MESSAGE\n assert unpack_result.metadata == test_vector.metadata\n","repo_name":"sicpa-dlab/didcomm-python","sub_path":"tests/unit/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"53"}
+{"seq_id":"20149072414","text":"def twosum(x, y, data):\n answer = []\n for i in range(x-1, y):\n answer.append(data[i])\n return sum(answer)\n\nif __name__ == '__main__':\n a, b = map(int, input().split())\n data = list(map(int, input().split()))\n result = []\n for i in range(b):\n c, d = map(int, input().split())\n ans = twosum(c, d, data)\n result.append(ans)\n for i in range(len(result)):\n print(result[i])\n","repo_name":"jason2133/data_structure_and_algorithm","sub_path":"Assignment_1/assignment_1.py","file_name":"assignment_1.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9312122228","text":"from collections import Counter\nfrom typing import List, Optional\n\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\nfrom ruse.bio.bio_data_table_helper import data_table_column_to_sequence, sequence_to_genbank_base64_str\nfrom ruse.bio.bio_util import is_genbank_column\nfrom ruse.util.data_table import DataTable\n\n\ndef add_consensus_sequence_to_data_table(data_table: DataTable, sequence_column: int,\n min_frequency: Optional[float] = .0,\n id_column: Optional[int] = None) -> None:\n sequences = data_table_column_to_sequence(data_table, sequence_column)\n consensus_sequence = determine_consensus_sequence(sequences, min_frequency=min_frequency)\n column_def = data_table.columns[sequence_column]\n genbank_format = is_genbank_column(column_def)\n encoded_sequence = sequence_to_genbank_base64_str(consensus_sequence) if genbank_format \\\n else str(consensus_sequence.seq)\n\n new_row = [None] * len(data_table.columns)\n new_row[sequence_column] = encoded_sequence\n if id_column:\n new_row[id_column] = consensus_sequence.name\n data_table.data.append(new_row)\n\n\ndef determine_consensus_sequence(sequences: List[SeqRecord], min_frequency: float = .0) -> SeqRecord:\n size = max(len(s) for s in sequences)\n consensus_items = [_most_common_item_at_position(sequences, p, min_frequency) for p in range(size)]\n\n name = \"consensus\"\n if min_frequency == 1.0:\n name = \"conserved\"\n consensus_seq = SeqRecord(Seq(''.join(consensus_items)), id=name, name=name)\n return consensus_seq\n\n\ndef _most_common_item_at_position(sequences: List[SeqRecord], position: int, min_frequency: float) -> str:\n def value_at_position(seq):\n if len(seq) > position:\n return seq[position]\n else:\n return '-'\n\n items = [value_at_position(s) for s in sequences]\n items = [i for i in items if i != '-']\n counts = Counter(items).most_common(1)\n if not counts:\n return '-'\n (item, count) = counts[0]\n\n n_sequences = len(sequences)\n if min_frequency == .0:\n return item\n elif min_frequency == 1.0:\n if count == n_sequences:\n return item\n else:\n return '-'\n else:\n freq = float(count) / float(n_sequences)\n if freq >= min_frequency:\n return item\n else:\n return '-'\n","repo_name":"Glysade/DataFxnPylib","sub_path":"pylib_3.9.7/ruse/bio/consensus_sequence.py","file_name":"consensus_sequence.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16785136013","text":"\nfrom pprint import pprint\nimport re\nimport sys\n\nregex = r'\\w+'\n\n\ndef main():\n args = sys.argv\n args.remove(__file__)\n\n if len(args) < 1:\n print('requires at least one input argument')\n exit(1)\n\n success = {}\n for i in range(0, len(args)):\n result = re.match(regex, args[i])\n if result:\n success.update({result.string: result.group()})\n print('.', end='')\n continue\n\n print('x', end='')\n else:\n print('\\n\\r')\n\n print(f'matched {len(success):02d}/{len(args):02d}')\n\n excluded = set(args).difference(success.keys())\n if (excluded):\n print(f'failed to match {excluded}')\n\n if success:\n print('\\n\\rresults')\n for key in success:\n print(f'{key}: {success[key]}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"OPVL/python-rest-stuff","sub_path":"regex-test.py","file_name":"regex-test.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24582827252","text":"#!/usr/bin/python3\n\"\"\"\nCreate views for City objects\n\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, request, abort\nfrom models import storage\nfrom models.city import City\nfrom models.state import State\n\n\n@app_views.route(\"/states//cities\", methods=[\"GET\", \"POST\"])\ndef state_cities(state_id):\n \"\"\"Retrieves the list of all City objects of a State and\n Creates a City object\"\"\"\n state = storage.get(\"State\", state_id)\n if state is None:\n abort(404)\n if request.method == \"GET\":\n cities = [city.to_dict() for city in state.cities]\n return jsonify(cities)\n if request.method == \"POST\":\n data = request.get_json()\n if data is None:\n abort(400, \"Not a JSON\")\n if \"name\" not in data:\n abort(400, \"Missing name\")\n data[\"state_id\"] = state_id\n city = City(**data)\n city.save()\n return jsonify(city.to_dict()), 201\n\n\n@app_views.route(\"/cities/\", methods=[\"GET\", \"DELETE\", \"PUT\"])\ndef city(city_id):\n \"\"\"Retrieves, Updates and Deletes a City object\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n if request.method == \"GET\":\n return jsonify(city.to_dict())\n if request.method == \"DELETE\":\n storage.delete(city)\n storage.save()\n return jsonify({}), 200\n if request.method == \"PUT\":\n data = request.get_json()\n if data is None:\n abort(400, \"Not a JSON\")\n for key, value in data.items():\n if key not in [\"id\", \"state_id\", \"created_at\", \"updated_at\"]:\n setattr(city, key, value)\n storage.save()\n return jsonify(city.to_dict()), 200\n","repo_name":"CipherPhantom/AirBnB_clone_v3","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2582148417","text":"s = input()\ns1 = [i for i in s]\nc = 0\n\nfor i in range(len(s) - 1):\n if s[i] == 'W' and s[i + 1] == 'B':\n c += 2\n s1.remove('W')\n s1.remove('B')\n\nwhile True:\n flag1, flag2 = False, False\n for i in s1:\n if i == 'W':\n flag1 = True\n if flag1 and i == 'B':\n flag2 = True\n if flag2:\n c += 2\n s1.remove('B')\n s1.remove('W')\n else:\n break\n\nif len(s) == 0:\n print(f'{c}\\nНИКОГО НЕ ОСТАЛОСЬ')\nelse:\n print(f'{c}\\n{\"\".join(s1)}')\n","repo_name":"HeraldOfWar/algos","sub_path":"lab_8/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70315752167","text":"import pytest\nimport numpy as np\n\nimport torch\n\nimport pytorch_quantization.nn.functional as QF\n\nnp.random.seed(1234)\ntorch.manual_seed(1234)\n\n# pylint:disable=missing-docstring, no-self-use\n\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\n\n\nclass TestClip():\n\n def test_simple_run(self):\n x_np = np.random.rand(1023).astype(np.float32)\n x_torch = torch.Tensor(x_np)\n clip_x_np = np.clip(x_np, 0.3, 0.7)\n clip_x_torch = QF.clip(x_torch, torch.tensor(0.3), torch.tensor(0.7))\n np.testing.assert_array_equal(clip_x_torch.cpu().numpy(), clip_x_np)\n\n def test_raise(self):\n x = torch.randn(3, 7, requires_grad=True)\n\n min_value = torch.Tensor(3, 7)\n max_value = torch.Tensor(3, 7)\n min_value.requires_grad = True\n max_value.requires_grad = True\n clip_x = QF.clip(x, min_value, max_value)\n\n labels = torch.randint(6, (3,)).type(torch.LongTensor).cuda()\n criterion = torch.nn.CrossEntropyLoss()\n loss = criterion(clip_x, labels)\n with pytest.raises(ValueError, match=\"can only be scalar\"):\n loss.backward()\n\n def test_broadcast(self):\n \"\"\"Test broadcast behavior by randomly picked shuffling of np.random.rand\"\"\"\n x_np = np.random.rand(1023, 4, 5, 6).astype(np.float32) - 0.5\n x_torch = torch.Tensor(x_np)\n min_value = np.random.rand(1, 4, 1, 1).astype(np.float32) * 0.1 - 0.2\n max_value = np.random.rand(1, 4, 1, 1).astype(np.float32) * 10 + 0.5\n clip_x_np = np.clip(x_np, min_value, max_value)\n clip_x_torch = QF.clip(x_torch, torch.tensor(min_value), torch.tensor(max_value))\n np.testing.assert_array_equal(clip_x_torch.cpu().numpy(), clip_x_np)\n\n def test_backward(self):\n x = torch.randn(3, 1025, requires_grad=True)\n x.retain_grad()\n\n min_value = torch.tensor(0.3)\n max_value = torch.tensor(0.7)\n min_value.requires_grad = True\n max_value.requires_grad = True\n min_value.retain_grad()\n max_value.retain_grad()\n clip_x = QF.clip(x, min_value, max_value)\n clip_x.retain_grad()\n\n labels = torch.randint(6, (3,)).type(torch.LongTensor).cuda()\n criterion = torch.nn.CrossEntropyLoss()\n loss = criterion(clip_x, labels)\n loss.backward()\n\n np.testing.assert_array_almost_equal(\n clip_x.grad[x < min_value].sum().cpu().numpy(), min_value.grad.cpu().numpy(), decimal=6)\n np.testing.assert_array_almost_equal(\n clip_x.grad[x > max_value].sum().cpu().numpy(), max_value.grad.cpu().numpy(), decimal=6)\n assert x.grad.cpu()[x.cpu() < min_value.cpu()].sum() == 0\n assert x.grad.cpu()[x.cpu() > max_value.cpu()].sum() == 0\n assert torch.equal(clip_x.grad[(x > min_value) & (x < max_value)], x.grad[(x > min_value) & (x < max_value)])\n","repo_name":"NVIDIA/TensorRT","sub_path":"tools/pytorch-quantization/tests/functional_test.py","file_name":"functional_test.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":8187,"dataset":"github-code","pt":"53"}
+{"seq_id":"35081862280","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nfrom time import sleep\n######################################################################################################################################\npath = os.path.abspath(\"./\")\npath_reqairement = path + \"/\" + \"reqairement.txt\"\n# обновляем пакеты\nos.system(\"sudo apt-get update\")\n# Устанавливаем pip'ы необходимые для работы скрипта get_my_ip.py\nos.system(\"sudo -H pip3 install -r \" + str(path_reqairement))\n# Устанавливаем supervisor\nos.system(\"sudo apt-get install supervisor -y\")\n# Редактируем файлы supervisor'a\nos.system(\"sudo touch /etc/supervisor/conf.d/get_my_ip.conf\")\nsleep(2)\nd_1 = [\n\"[program:get_my_ip]\"\n]\nd_2 = [\n\"\\ncommand=sudo python3 get_my_ip.py\"\n]\nd_3 = [\n\"\\ndirectory=\" + str(path)\n]\nd_4 = [\n\"\\nstdout_logfile=\" + str(path) + \"/\" + \"get_my_ip.log\"\n]\nd_5 = [\n\"\\nautostart=true\"\n]\nd_6 = [\n\"\\nautorestart=true\"\n]\nd_7 = [\n\"\\nredirect_stderr=true\"\n]\ndata = d_1 + d_2 + d_3 + d_4 + d_5 + d_6 + d_7\nwith open(\"/etc/supervisor/conf.d/get_my_ip.conf\", \"w\") as f:\n for d in data:\n f.write(str(d))\nsleep(2)\nos.system(\"sudo systemctl enable supervisor.service\")\nos.system(\"sudo service supervisor restart\")\n","repo_name":"hulumulu801/get_my_ip","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"37518316393","text":"import tkinter as tk\nimport string\nfrom tkinter.ttk import *\n\n\n\n\nclass Application(tk.Frame):\n # constructor for the Application\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n\n # makes all the widgets by calling their respective functions\n def create_widgets(self):\n self.create_output(\"\")\n self.create_tail()\n self.create_cipher_choices()\n self.create_quit()\n self.create_decrypt()\n\n # creates tail label\n def create_tail(self):\n lbl = tk.Label(self, text=\"Please select a cipher and key, then press decrypt to test your key!\\nYour decrypted message will be displayed above!\")\n lbl.pack()\n\n # creates display box for text\n def create_output(self, txt):\n self.display = tk.Text(self)\n self.display.insert(\"end\", txt)\n self.display.pack()\n self.display.config(state=\"disabled\")\n\n # creates the decrypt button\n def create_decrypt(self):\n decrypt_style = Style()\n decrypt_style.configure('decrypt.TButton', font=('georgia', 10), foreground='green')\n\n def clicked():\n self.display.config(state='normal')\n self.display.delete('1.0', \"end\")\n self.display.insert(\"end\", \"\\n\" + self.decode_cipher(self.selected.get()))\n self.display.config(state=\"disabled\")\n\n btn = Button(self, text=\"Decrypt!\", style='decrypt.TButton', command=\n clicked)\n btn.pack(side=\"left\")\n\n # creates the quit button\n def create_quit(self):\n quit_style = Style()\n quit_style.configure('quit.TButton', font=('georgia', 10), foreground='red')\n\n quit = Button(self, text=\"Quit\", style='quit.TButton', command=self.master.destroy)\n quit.pack(side=\"right\")\n\n # creates radio buttons with the cipher choice\n def create_cipher_choices(self):\n # assigns three radio buttons, one for each cipher text\n self.selected = tk.IntVar()\n rad1 = tk.Radiobutton(self, text=\"Cipher 1\", value=1, variable=self.selected)\n rad2 = tk.Radiobutton(self, text=\"Cipher 2\", value=2, variable=self.selected)\n rad3 = tk.Radiobutton(self, text=\"Cipher 3\", value=3, variable=self.selected)\n\n # packs the buttons\n rad1.pack()\n rad2.pack()\n rad3.pack()\n\n # decodes cipher\n def decode_cipher(self, num_cipher):\n #reads data in the key file\n with open('key.txt', 'r') as file1:\n text_data = file1.read()\n\n # removes punctuation from text\n punc = string.punctuation\n for j in range(len(punc)):\n text_data = text_data.replace(punc[j], \"\")\n\n # if no cipher is chosen then prompt user\n if num_cipher not in [1,2,3]:\n return \"Please choose a cipher!\"\n\n # read cipher text specified if cipher is chosen\n with open('cipher{}.txt'.format(int(num_cipher), 'r')) as file2:\n number_data = file2.read()\n\n # split data from read files\n words = str(text_data).split()\n numbers = str(number_data).split(\",\")\n\n # define return string and max variable\n result = \"\"\n max = 0\n\n # find highest number in the cipher text\n for k in range(len(numbers)):\n cur_num = int(numbers[k])\n if cur_num > max:\n max = cur_num\n\n # checks if the number of words in key is greater than the highest number\n # if not, return a message indicating so\n if len(words) > max:\n for i in range(len(numbers)):\n word_index = int(numbers[i])\n result += words[word_index][0]\n else:\n return \"The number of words in this text are not enough for it to qualify as the key.\"\n\n # returns the decrypted message along with a display msg\n return \"Here's your decrypted message!\\n\\n\" + result.upper()\n\nroot = tk.Tk()\nroot.title('Beale Cipher Decoder')\nroot.geometry('960x540')\n\napp = Application(master=root)\napp.mainloop()\n","repo_name":"AlChemE/bealecipher","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"73030208489","text":"from itertools import permutations\n\ndef solution(k, dungeons):\n answer = -1\n candidates = list(permutations([x for x in range(len(dungeons))], len(dungeons)))\n\n for candidate in candidates:\n temp, cnt = k, 0\n for idx in candidate:\n if temp >= dungeons[idx][0]:\n temp -= dungeons[idx][1]\n cnt += 1\n answer = max(answer, cnt)\n\n return answer\n\n## BFS\nfrom collections import deque\n\ndef solution(k, dungeons):\n answer = -1\n queue = deque()\n queue.append((k, []))\n\n while queue:\n k, route = queue.popleft()\n for i in range(len(dungeons)):\n a, b = dungeons[i]\n if k >= a and i not in route:\n temp = route + [i]\n queue.append((k - b, temp))\n else:\n answer = max(answer, len(route))\n\n return answer","repo_name":"CHOSIYEON/Algorithms","sub_path":"PROGRAMMERS/Level 2/record/피로도.py","file_name":"피로도.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"16215130290","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n'''\r\nSample Input\r\n5 1\r\n3 4 7 6 5\r\n\r\nSample Output\r\n4\r\n6\r\n3\r\n7\r\n5\r\n\r\n# Complete the 'waiter' function below.\r\n#\r\n# The function is expected to return an INTEGER_ARRAY.\r\n# The function accepts following parameters:\r\n# 1. INTEGER_ARRAY number\r\n# 2. INTEGER q\r\n'''\r\n\r\ndef SieveOfEratosthenes(n) :\r\n lower = 2\r\n upper = 10000\r\n return [i for i in range(lower, upper + 1) if all(i % j != 0 for j in range(2, i))]\r\n \r\ndef waiter(number, q):\r\n # Write your code here\r\n primes = SieveOfEratosthenes(10000)\r\n ans = []\r\n a = []\r\n b = []\r\n \r\n # iterations\r\n for i in range(q):\r\n # transfer to Ai or Bi depending on i'th prime\r\n while(number):\r\n topStack = number.pop()\r\n if topStack % primes[i] == 0:\r\n b.append(topStack)\r\n else:\r\n a.append(topStack)\r\n # transfer Bi to ans, top to bottom\r\n while(b):\r\n e = b.pop()\r\n ans.append(e)\r\n # update with new Ai\r\n number = a\r\n a = []\r\n # remaining values in Ai\r\n while(number):\r\n ans.append(number.pop())\r\n return(ans)\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n first_multiple_input = input().rstrip().split()\r\n\r\n n = int(first_multiple_input[0])\r\n\r\n q = int(first_multiple_input[1])\r\n\r\n number = list(map(int, input().rstrip().split()))\r\n\r\n result = waiter(number, q)\r\n\r\n fptr.write('\\n'.join(map(str, result)))\r\n fptr.write('\\n')\r\n\r\n fptr.close()\r\n","repo_name":"adnaneaabbar/HackerRankOneMonthPrepKit","sub_path":"week3/waiter.py","file_name":"waiter.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"53"}
+{"seq_id":"20283926","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\ndef sigmoid(z):\r\n \r\n s = 1.0 / (1.0 + np.exp(-z))\r\n \r\n return s\r\n\r\n\r\ndef model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):\r\n \"\"\"\r\n 逻辑回归模型\r\n \r\n 参数:\r\n X_train -- np数组(num_px * num_px, m_train)\r\n Y_train -- np数组(1, m_train)\r\n X_test -- np数组(num_px * num_px, m_test)\r\n Y_test -- np数组(1, m_test)\r\n num_iterations -- 超参数 迭代次数\r\n learning_rate -- 超参数 学习率\r\n print_cost -- True:每100次迭代打印cost\r\n \r\n \"\"\"\r\n\r\n # 训练集样本数\r\n m_train = X_train.shape[1]\r\n # 测试集样本数\r\n m_test = X_test.shape[1]\r\n\r\n # 初始化w和b为0\r\n # w 权重, np数组(num_px * num_px, 1)\r\n w = np.zeros((X_train.shape[0], 1))\r\n b = 0\r\n\r\n # 新建一个数组,实时记录损失函数(我们的优化目标),后面可以画出来看看梯度下降的效果\r\n costs = []\r\n # 进行num_iterations次迭代,每次迭代算一次梯度下降\r\n for i in range(num_iterations):\r\n \r\n # 首先求出线性部分和激活函数\r\n A = sigmoid(np.dot(w.T, X_train) + b)\r\n # 计算损失函数\r\n cost = -1.0 / m_train * np.sum(Y_train * np.log(A) + (1 - Y_train) * np.log(1 - A)) \r\n cost = np.squeeze(cost)\r\n \r\n # 求梯度\r\n dw = 1.0 / m_train * np.dot(X_train, (A - Y_train).T)\r\n db = 1.0 / m_train * np.sum(A - Y_train)\r\n \r\n # 梯度下降\r\n w = w - learning_rate * dw\r\n b = b - learning_rate * db\r\n\r\n # 记录一下损失\r\n if i % 100 == 0:\r\n costs.append(cost)\r\n \r\n # 每一百次迭代打印一次损失\r\n \r\n if print_cost and i % 100 == 0:\r\n print(\"Cost after iteration %i: %f\" % (i, cost))\r\n\r\n w = w.reshape(-1, 1)\r\n \r\n # 训练集上的预测置信度predict y_hat\r\n y_hat_train = sigmoid(np.dot(w.T, X_train) + b)\r\n # 测试集上的预测置信度 y_hat\r\n y_hat_test = sigmoid(np.dot(w.T, X_test) + b)\r\n # 训练集上的预测类别\r\n y_prediction_train = np.zeros((1, m_train))\r\n y_prediction_train[y_hat_train > 0.5] = 1\r\n # 测试集上的预测类别\r\n y_prediction_test = np.zeros((1, m_test))\r\n y_prediction_test[y_hat_test > 0.5] = 1\r\n\r\n d = {\"costs\": costs,\r\n \"Y_prediction_test\": y_prediction_test,\r\n \"Y_prediction_train\": y_prediction_train,\r\n \"Y_hat_test\": y_hat_test,\r\n \"Y_hat_train\": y_hat_train,\r\n \"w\": w,\r\n \"b\": b,\r\n \"learning_rate\" : learning_rate,\r\n \"num_iterations\": num_iterations}\r\n \r\n return d\r\n","repo_name":"bywmm/Logistic-Regression-on-MNIST-dataset","sub_path":"LR_model.py","file_name":"LR_model.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"7946215658","text":"#!/usr/bin/python\n#搬运自:https://www.xj123.info/6890.html\n#树莓派1602驱动\nfrom time import sleep\n \nclass lcd1602:\n LCD_CLEARDISPLAY = 0x01\n LCD_RETURNHOME = 0x02\n LCD_ENTRYMODESET = 0x04\n LCD_DISPLAYCONTROL = 0x08\n LCD_CURSORSHIFT = 0x10\n LCD_FUNCTIONSET = 0x20\n LCD_SETCGRAMADDR = 0x40\n LCD_SETDDRAMADDR = 0x80\n \n LCD_ENTRYRIGHT = 0x00\n LCD_ENTRYLEFT = 0x02\n LCD_ENTRYSHIFTINCREMENT = 0x01\n LCD_ENTRYSHIFTDECREMENT = 0x00\n \n LCD_DISPLAYON = 0x04\n LCD_DISPLAYOFF = 0x00\n LCD_CURSORON = 0x02\n LCD_CURSOROFF = 0x00\n LCD_BLINKON = 0x01\n LCD_BLINKOFF = 0x00\n \n LCD_DISPLAYMOVE = 0x08\n LCD_CURSORMOVE = 0x00\n \n LCD_DISPLAYMOVE = 0x08\n LCD_CURSORMOVE = 0x00\n LCD_MOVERIGHT = 0x04\n LCD_MOVELEFT = 0x00\n \n LCD_8BITMODE = 0x10\n LCD_4BITMODE = 0x00\n LCD_2LINE = 0x08\n LCD_1LINE = 0x00\n LCD_5x10DOTS = 0x04\n LCD_5x8DOTS = 0x00\n\n def __init__(self, pin_rs=14, pin_e=15, pins_db=[17, 18, 27, 22], GPIO = None):\n if not GPIO:\n import RPi.GPIO as GPIO\n self.GPIO = GPIO\n self.pin_rs = pin_rs\n self.pin_e = pin_e\n self.pins_db = pins_db\n \n self.GPIO.setmode(GPIO.BCM)\n self.GPIO.setwarnings(False)\n self.GPIO.setup(self.pin_e, GPIO.OUT)\n self.GPIO.setup(self.pin_rs, GPIO.OUT)\n \n for pin in self.pins_db:\n self.GPIO.setup(pin, GPIO.OUT)\n \n self.write4bits(0x33)\n self.write4bits(0x32)\n self.write4bits(0x28)\n self.write4bits(0x0C)\n self.write4bits(0x06)\n \n self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF\n \n self.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTS\n self.displayfunction |= self.LCD_2LINE\n\n self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT\n self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)\n \n self.clear()\n \n def begin(self, cols, lines):\n \n if (lines > 1):\n self.numlines = lines\n self.displayfunction |= self.LCD_2LINE\n self.currline = 0\n \n def home(self):\n \n self.write4bits(self.LCD_RETURNHOME)\n self.delayMicroseconds(3000)\n \n def clear(self):\n \n self.write4bits(self.LCD_CLEARDISPLAY)\n self.delayMicroseconds(3000)\n \n def setCursor(self, col, row):\n \n self.row_offsets = [ 0x00, 0x40, 0x14, 0x54 ]\n \n if ( row > self.numlines ): \n row = self.numlines - 1\n \n self.write4bits(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row]))\n \n def noDisplay(self): \n \n self.displaycontrol &= ~self.LCD_DISPLAYON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def display(self):\n \n self.displaycontrol |= self.LCD_DISPLAYON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def noCursor(self):\n \n self.displaycontrol &= ~self.LCD_CURSORON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def cursor(self):\n \n self.displaycontrol |= self.LCD_CURSORON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def noBlink(self):\n \n self.displaycontrol &= ~self.LCD_BLINKON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def noBlink(self):\n \n self.displaycontrol &= ~self.LCD_BLINKON\n self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)\n \n def DisplayLeft(self):\n \n self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT)\n \n def scrollDisplayRight(self):\n \n self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT);\n \n def leftToRight(self):\n \n self.displaymode |= self.LCD_ENTRYLEFT\n self.write4bits(self.LCD_ENTRYMODESET | self.displaymode);\n \n def rightToLeft(self):\n \n self.displaymode &= ~self.LCD_ENTRYLEFT\n self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)\n \n def autoscroll(self):\n \n self.displaymode |= self.LCD_ENTRYSHIFTINCREMENT\n self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)\n \n def noAutoscroll(self): \n \n self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT\n self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)\n \n def write4bits(self, bits, char_mode=False):\n \n self.delayMicroseconds(1000)\n \n bits=bin(bits)[2:].zfill(8)\n \n self.GPIO.output(self.pin_rs, char_mode)\n \n for pin in self.pins_db:\n self.GPIO.output(pin, False)\n \n for i in range(4):\n if bits[i] == \"1\":\n self.GPIO.output(self.pins_db[::-1][i], True)\n \n self.pulseEnable()\n \n for pin in self.pins_db:\n self.GPIO.output(pin, False)\n \n for i in range(4,8):\n if bits[i] == \"1\":\n self.GPIO.output(self.pins_db[::-1][i-4], True)\n \n self.pulseEnable()\n \n def delayMicroseconds(self, microseconds):\n seconds = microseconds / float(1000000)\n sleep(seconds)\n \n def pulseEnable(self):\n self.GPIO.output(self.pin_e, False)\n self.delayMicroseconds(1) \n self.GPIO.output(self.pin_e, True)\n self.delayMicroseconds(1)\n self.GPIO.output(self.pin_e, False)\n self.delayMicroseconds(1)\n \n def message(self, text):\n \n for char in text:\n if char == '\\n':\n self.write4bits(0xC0)\n else:\n self.write4bits(ord(char),True)\n \nif __name__ == '__main__':\n \n lcd = lcd1602()\n lcd.clear()\n lcd.message(\"hello world!\")","repo_name":"Sch-ray/raspberry-pi","sub_path":"LCD1602驱动.PY","file_name":"LCD1602驱动.PY","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"11071613566","text":"from station_geometry import station_geometry\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport math\nfrom math import sin, cos\nfrom mpl_toolkits.mplot3d import Axes3D\n#import sys\n\n#Initialize station_geometry\nstation = station_geometry(2)\n\n#Station information\nstation2_x = np.empty((5,4), dtype = float)\nstation2_y = np.empty((5,4), dtype = float)\nstation2_z = np.empty((5,4), dtype = float)\nstation3_strings = []\n\n#Gets the location for every antenna\n#loops through strings\nfor i in range(5):\n\t#loops through antennas\n\tfor j in range(4):\n\t\tstation2_x[i][j] = station.get_string_coordinates(2,i+1, j)[0]\n\t\tstation2_y[i][j] = station.get_string_coordinates(2,i+1, j)[1]\n\t\tstation2_z[i][j] = station.get_string_coordinates(2,i+1, j)[2]\n\n#Surface for visualization\n#Initialize figure and 3D plot\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.set_zlim3d(-200,10)\nax.set_ylim3d(-50,50)\nax.set_xlim3d(-50,50)\n\n#Loop through each detector and set color\n#Then plots the event vertex and direction\n#Lines are plotted connecting the detectors to the vertex for visualization\nfor i in range(4):\n\t#conditionals plot detectors\n\t#Sets legend entry once\n\tif i == 0:\n\t\tax.scatter(station2_x[i][0], station2_y[i][0], station2_z[i][0], c='r', label='Verticle Antenna')\n\t\tax.scatter(station2_x[i][2], station2_y[i][2], station2_z[i][2], c='r')#, marker=\"|\")\n\t\tax.scatter(station2_x[i][1], station2_y[i][1], station2_z[i][1], c='g', label='Horizontal Antenna')\n\t\tax.scatter(station2_x[i][3], station2_y[i][3], station2_z[i][3], c='g')#, marker=\"_\")\n\telse:\n\t\tax.scatter(station2_x[i][0], station2_y[i][0], station2_z[i][0], c='r')#, marker=\"|\")\n\t\tax.scatter(station2_x[i][2], station2_y[i][2], station2_z[i][2], c='r')#, marker=\"|\")\n\t\tax.scatter(station2_x[i][1], station2_y[i][1], station2_z[i][1], c='g')#, marker=\"_\")\n\t\tax.scatter(station2_x[i][3], station2_y[i][3], station2_z[i][3], c='g')#, marker=\"_\")\n\t#Connect the detectors to the vertex\n\tax.plot((station2_x[i][0], station2_x[i][0]), (station2_y[i][0], station2_y[i][0]), (0, station2_z[i][0]), c='r')#, marker=\"|\")\n\tax.plot((station2_x[i][2],station2_x[i][2]), (station2_y[i][2],station2_y[i][2]), (0,station2_z[i][2]), c='r')#, marker=\"|\")\n\tax.plot((station2_x[i][1],station2_x[i][1]), (station2_y[i][1],station2_y[i][1]), (0,station2_z[i][1]), c='g')#, marker=\"_\")\n\tax.plot((station2_x[i][3],station2_x[i][3]), (station2_y[i][3],station2_y[i][3]), (0,station2_z[i][3]), c='g')#, marker=\"_\")\n#Plot pulsers\nax.scatter(station2_x[4][0], station2_y[4][0], station2_z[4][0], c='g')#, marker=\"|\")\nax.scatter(station2_x[4][1], station2_y[4][1], station2_z[4][1], c='r')#, marker=\"_\")\nax.scatter(station2_x[4][2], station2_y[4][2], station2_z[4][2], c='g')#, marker=\"|\")\nax.scatter(station2_x[4][3], station2_y[4][3], station2_z[4][3], c='r')#, marker=\"_\")\n\nax.plot((station2_x[4][0],station2_x[4][0]), (station2_y[4][0], station2_y[4][0]), (0,station2_z[4][0]), c='g', label='Antenna String')#, marker=\"|\")\nax.plot((station2_x[4][1], station2_x[4][1]), (station2_y[4][1], station2_y[4][1]), (0,station2_z[4][1]), c='r', label='Calibration String')#, marker=\"_\")\nax.plot((station2_x[4][2],station2_x[4][2]), (station2_y[4][2], station2_y[4][2]), (0,station2_z[4][2]), c='g')#, marker=\"|\")\nax.plot((station2_x[4][3], station2_x[4][3]), (station2_y[4][3], station2_y[4][3]), (0,station2_z[4][3]), c='r')#, marker=\"_\")\n\n#Plotting and labeling\n#Vertex and direction vector\nX = Y = np.arange(-50,50)\nx,y = np.meshgrid(X,Y)\nz = 0\nax.plot_surface(x,y,z)\n#ax.text(0, 0, 10, \"Surface\", color='red')\nax.set_zlabel('Depth (m)')\nax.set_xlabel('Position From Center (m)')\nax.set_ylabel('Position From Center (m)')\nax.legend()\nax.set_title('ARA02')\nplt.show()\n#plt.savefig('Images/Plots/Cone0' + sys.argv[1] + '.png')\n","repo_name":"kkirchhoff01/ARA-Simulation","sub_path":"plot_station_geometry.py","file_name":"plot_station_geometry.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"69992156007","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom watbot import WABot\n\n#---\n#CREDENCIAIS\n#Aqui são as API's que estamos usando\nscope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\n#Credenciais que você consegue na sua pagina principal do google\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'synoromes.json', scope)\n\n#Solicitando autorização\ngc = gspread.authorize(credentials)\n\n#---\n#SELECIONANDO A PLANILHA\nwks = gc.open_by_key('ID PLAN')\n\n#---\n#SELECIONANDO A ABA DA PLANILHA\n\n#a) aqui pegamos pelo index da planilha\nworksheet = wks.get_worksheet(1)\n\n#b) aqui pegamos pelo nome da planilha\n# worksheet = wks.worksheet(\"January\")\n\n#---\n#SELECIONANDO DADOS\n\n#a) Pela célula\nval = worksheet.acell('A1').value\n\n#b) Pelo numero da linha e coluna\nval = worksheet.cell(1, 2).value\n\n#Acessar uma célula pelo nome dela\ncell = worksheet.find(\"Telefone\")\n\n#Podemos assim chamar uma linha ou coluna\nprint(cell.row)\nprint(cell.col)\n\n#ACHANDO O TELEFONE\n#a) Pegando a linha e a coluna de ontem temos o telefone\nphone = worksheet.find(\"Telefone\")\nrow_phone = phone.row\ncol_phone = phone.col\n\n\n#b) Pegando o primeiro telefone\ntelefone_cliente = worksheet.cell(row_phone+1, col_phone).value #aqui estou usando \"+1\" mas o ideal é fazer mais i\nprint(telefone_cliente)\n\n#ACHANDO O CORPO DA MENSAGEM\n#a) Pegando a linha e a coluna do corpo da mensagem\nbody_mes = worksheet.find(\"Mensagem\")\nrow_mes = body_mes.row\ncol_mes = body_mes.col\n\n#b) Pegando a primeira mensagem\nmensagem_cliente = worksheet.cell(row_mes+1, col_mes).value #aqui estou usando \"+1\" mas o ideal é fazer mais i\n\n#MANDANDO A MENSAGEM\nteste = WABot()\nteste.send_message(telefone_cliente, mensagem_cliente)\n\n#MUDANDO O TELEFONE PARA O NOSSO PADRÃO\ntelefone_cliente = telefone_cliente.replace('(', '').replace(')', '').replace('-', '')\ntelefone_cliente = f'55{telefone_cliente}'\n\n#MARCAR CHECK NA FLAG CASO A MENSAGEM TENHA SIDO ENVIADA\n#a) achando onde está a flag\nflag = worksheet.find(\"Flag\")\nrow_flag = flag.row\ncol_flag = flag.col\n\n#b) Pegando a primeira mensagem\nflag_body = worksheet.cell(row_flag+1, col_flag).value #aqui estou usando \"+1\" mas o ideal é fazer mais i\n\n#c) Atualizando a celula\n# worksheet.update_cell(row_flag+1,col_flag , 'Notcheck')\n\n#MANDANDO A MENSAGEM E ATUALIZANDO A PLANILHA\ntelefone_cliente = telefone_cliente.replace('(', '').replace(')', '').replace('-', '')\ntelefone_cliente = f'55{telefone_cliente}'\n\n\nif teste.send_message(telefone_cliente, mensagem_cliente)['sent'] == True:\n worksheet.update_cell(row_flag+1,col_flag , 'Voila')\nelse:\n print('ops')\n\n\n#DEIXANDO DE MANDAR MENSAGEM CASO JÁ TENHAMOS UM PREENCHIMENTO\ntelefone_cliente = telefone_cliente.replace('(', '').replace(')', '').replace('-', '')\ntelefone_cliente = f'55{telefone_cliente}'\n\n\nflag_body = worksheet.cell(row_flag+1,col_flag).value\n\n\nif flag_body == '':\n if teste.send_message(telefone_cliente, mensagem_cliente)['sent'] == True:\n worksheet.update_cell(row_flag+1,col_flag , 'Voila')\n else:\n print('ops')\nelif flag_body == 'Voila':\n print('ja ta preenchido')\nelse:\n print('algo estranho...')\n\n","repo_name":"jsobralgitpush/Portfolio","sub_path":"Estágio Synoro/google sheets API + wabot/google_sheets_test.py","file_name":"google_sheets_test.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14779229915","text":"from django.shortcuts import render_to_response\nfrom datetime import datetime\nfrom helper import *\nfrom forms import UploadFileForm\nfrom models import Patient\n\ndef index(request):\n return render_to_response('patients/index.html', {})\n\ndef upload(request):\n return render_to_response('patients/upload.html', {})\n\ndef uploader(request):\n result = 'Upload failed.'\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n result = handle_uploaded_file(request.FILES['file'])\n return render_to_response('patients/uploader.html', {'result': result})\n\ndef data(request):\n patients = Patient.objects.all()\n return render_to_response('patients/data.html', {'patients': patients})\n\ndef select_chart(request):\n context = {}\n year = datetime.now().date().year\n years = []\n for i in range(0, 5):\n years.append(year-i)\n context[\"years\"] = years\n charts = ['starting_by_stakeholder', 'percentage_initiations']\n context[\"charts\"] = charts\n return render_to_response('patients/select_chart.html', {'context': context})\n\ndef charts(request):\n chart = ''\n if request:\n for item in request.POST.items():\n if item[0] == 'chart':\n chart = item[1]\n if chart == 'starting_by_stakeholder':\n url = get_starting_by_stakeholder(request)\n if chart == 'percentage_initiations':\n url = get_percentage_initiations(request)\n return render_to_response('patients/charts.html', {'url': url})\n","repo_name":"dimagi/arvtracker","sub_path":"patients/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"24241054642","text":"from django.conf.urls import url\nfrom django.urls import path\n\nfrom quiz import views\n\nurlpatterns = [\n url(r'^$', views.first_question, name=\"first_question\"),\n path('question//?', views.quiz, name=\"quiz\"),\n url(r'^contact/?$', views.contact_quiz, name=\"contact_quiz\"),\n url(r'^error/?$', views.error, name=\"error\"),\n path('answer//?', views.answer, name=\"answer\"),\n]\n","repo_name":"aniquiz/aniquiz","sub_path":"aniquiz/quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36486779302","text":"import os\n\nimport requests\nfrom flask import Flask, json, render_template\nfrom flask.logging import default_handler\nfrom flask_cors import CORS\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nfrom flask_compress import Compress\n\nfrom items.items import Items\nfrom logger import RequestFormatter\n\nCOMPRESS_MIMETYPES = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript']\nCOMPRESS_LEVEL = 6\nCOMPRESS_MIN_SIZE = 500\n\napp = Flask(__name__, static_folder='./public', template_folder=\"./static\")\nCORS(app)\nCompress(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nlimiter = Limiter(key_func=get_remote_address)\nlimiter.init_app(app)\n\nformatter = RequestFormatter('[%(asctime)s] %(levelname)s in %(method)s %(path)s: %(message)s')\ndefault_handler.setFormatter(formatter)\nbase_api = 'https://api.warframe.market/v1'\nwarframestat_api = 'https://api.warframestat.us/items/search'\nitems_url = f'{base_api}/items'\n\nitems = None\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('base.html', data=items)\n\n\ndef get_relics():\n global items\n\n with open(os.path.join(\"./static\", \"data\", \"items_categories.json\"), \"r\") as test_file:\n items = Items(json.load(test_file))\n\n for relic in items.void_relics.all:\n tmp_list = set()\n try:\n json_response_stat = requests.get(f'{warframestat_api}/{relic}').json()\n except requests.exceptions.RetryError as e:\n print(e)\n except requests.exceptions.BaseHTTPError as e:\n print(e)\n\n for relic_obj in json_response_stat:\n if relic_obj['category'] == 'Relics':\n name = relic_obj['name'].lower().split()[1]\n tmp_list.add(name)\n\n items.void_relics.relics.append({\"era\": relic, \"names\": list(tmp_list)})\n\n\nget_relics()\n\nfrom templates.getItems.views import get_items_blueprint\n\napp.register_blueprint(get_items_blueprint)\n","repo_name":"Mangiang/warframe-market-proto","sub_path":"templates/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"21080764672","text":"\n#By ##\n\nimport feedparser, os, sys, time, datetime, subprocess\n\ndata = time.strftime('%d%m%Y')\narq = open(data+'.txt', 'rw')\n\n#Get feeds just title\nurl = feedparser.parse('http://www.wordpressexploit.com/feed/')\nwith open(data+'.txt', 'rw') as outfile:\n\tfor e in url['entries']:\n #print e.get('title', '')\n\t\ttitle = e.get('title', '')\n\t\tsummary = e.get('summary', '') \n\t\tlink = e.get('link', '')\n\t\toutfile.write(title)\n\n\n\t\n\n\n \n \n\n\n\n","repo_name":"nino-/scripts","sub_path":"getrss.py","file_name":"getrss.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24871857056","text":"import os, copy\nimport numpy as np\nfrom gym import utils, spaces, error\nfrom gym.envs.mujoco import mujoco_env\nimport time, math\nfrom sklearn.neighbors.kde import KernelDensity\n\ntry:\n import mujoco_py\nexcept ImportError as e:\n raise error.DependencyNotInstalled(\"{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)\".format(e))\nfrom envs.yumi.yumi_env_mocap import YumiMocapXYZGEnv, GoalProposeYumiMocapXYZGEnv\n\nclass YumiDoorEnv(GoalProposeYumiMocapXYZGEnv, utils.EzPickle):\n \"\"\"\n Mujoco yumi environment for door opening task.\n The robot needs to fully open the door.\n The extrinsic reward will be given when the door is fully openned.\n\n :param xml_name: xml file of the robot model and the environment\n :param goal_dim: the dimension of the goal state\n :param reward_type: the type for reward computing. The reward type can be \"dense\", \"sparse\", \"density\" and \"rnd\" \n :param mocap_high: the up-limit of the mocap position\n :param mocap_low: the low-limit of the mocap position\n :param mocap_init_pos: the initial position of mocap\n :param mocap_init_quat: the initial orientation of mocap\n \"\"\" \n def __init__(self, reward_type='sparse', goal_dim=5, xml_name='yumi_door.xml', \n mocap_high=np.hstack((0.0, 0.03, 0.3)), mocap_low=np.hstack((-0.1, -0.08, 0.2)),\n mocap_init_pos=None, mocap_init_quat=None):\n\n GoalProposeYumiMocapXYZGEnv.__init__(self, xml_name=xml_name, reward_type=reward_type, \n goal_dim=goal_dim, mocap_high=mocap_high, mocap_low=mocap_low,\n mocap_init_pos=mocap_init_pos, mocap_init_quat=mocap_init_quat)\n utils.EzPickle.__init__(self)\n x_scale, y_scale, z_scale, gripper_scale = 0.005, 0.005, 0.005, 3000\n self.action_scale = np.array([x_scale, y_scale, z_scale, gripper_scale])\n self.always_render = False\n\n # the threshold used to identifly if the goal state has been reached. \n # only used for training goal conditioned policy\n self.distance_threshold = 0.05\n self.ep_length = 1000\n\n obs = self.get_current_obs()\n self.obs_mean = np.zeros_like(obs) \n self.obs_std = np.ones_like(obs)\n self.density_estimator = None\n self.use_global_density = False\n self.use_extrinsic_reward = False\n\n def set_density_estimator(self, density_estimator):\n self.density_estimator = density_estimator\n\n def update_reward_scale(self, mean, std):\n self.obs_mean = mean \n self.obs_std = std \n print('update reward norm', self.obs_mean, self.obs_std)\n\n def reset_goal(self):\n # Visualize target.\n print('reset goal')\n render_goal = self.selected_goal/self.obs_scale\n sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy()\n site_id = self.sim.model.site_name2id('goal')\n self.sim.model.site_pos[site_id] = render_goal[0:3] - sites_offset[0]\n\n def set_args_params(self, args):\n self.args = args \n self.use_index = self.args.use_index\n self.reward_type = self.args.reward_type\n self.ep_length = self.args.ep_length\n self.always_render = self.args.render\n self.use_global_density = self.args.use_global_density\n self.use_extrinsic_reward = self.args.use_extrinsic_reward\n\n self.kde_goal = KernelDensity(kernel='gaussian', bandwidth=self.args.goal_bandwidth)\n self.kde_tra = KernelDensity(kernel='gaussian', bandwidth=self.args.trajectory_bandwidth)\n \n self.set_observation_space() \n print('use index', self.use_index)\n print('reward_type', self.reward_type)\n print('ep_length', self.ep_length)\n\n if self.always_render:\n self.viewer = self._get_viewer('human')\n self.viewer._run_speed = 100\n # self.viewer._paused = True\n def set_extra_task_params(self):\n \"\"\"\n Thsi function is used for reading any task-related information from xml fills.(i.e. requires element id in xml file.)\n \"\"\"\n self.initial_state = copy.deepcopy(self.sim.get_state())\n\n self.end_effector = 'gripper_r_base'\n # self.gripper_joints = [self.sim.model.get_joint_qpos_addr('gripper_r_joint'), self.sim.model.get_joint_qpos_addr('gripper_r_joint_m')]\n self.gripper_joints = [self.sim.model.get_joint_qpos_addr('gripper_r_joint')]\n self.door_joint = [self.sim.model.get_joint_qpos_addr('door_l_joint')]\n \n xyz_range = self.mocap_high - self.mocap_low\n\n #finger_range = self.sim.model.jnt_qposadr('gripper_r_joint')\n gripper_r_joint_id = self.sim.model.joint_name2id('gripper_r_joint')\n left_limit = self.sim.model.jnt_range[gripper_r_joint_id]\n\n gripper_r_joint_id_m = self.sim.model.joint_name2id('gripper_r_joint_m')\n right_limit = self.sim.model.jnt_range[gripper_r_joint_id_m]\n\n # gripper_range = np.array([left_limit[1] - left_limit[0],\n # right_limit[1] - right_limit[0]])\n gripper_range = [left_limit[1] - left_limit[0]]\n\n doorjoint_id = self.sim.model.joint_name2id('door_l_joint')\n door_limit = self.sim.model.jnt_range[doorjoint_id]\n door_range = [door_limit[1] - door_limit[0]]\n\n # if self.args.use_auto_scale:\n self.obs_scale = np.ones(self.goal_dim)\n # else:\n # self.obs_scale = np.concatenate(([1,1,1,], np.max(xyz_range)/gripper_range, np.max(xyz_range)/door_range))\n\n self.xyz_start = self.mocap_low * self.obs_scale[0:3]\n self.xyz_end = self.mocap_high * self.obs_scale[0:3]\n self.gripper_start = left_limit[0] * self.obs_scale[3]\n self.gripper_end = left_limit[1] * self.obs_scale[3]\n self.door_start = door_limit[0] * self.obs_scale[4]\n self.door_end = door_limit[1] * self.obs_scale[4]\n\n def get_current_obs(self):\n # print('in get current_obs')\n # 5 dim observation space: x, y, z, gripper_l, door opening\n # get x, y, z\n ee_pos = self.data.get_body_xpos(self.end_effector)\n # get gripper opening\n grip_angles = self.sim.data.qpos[self.gripper_joints]\n door_angle = self.sim.data.qpos[self.door_joint]\n obs = np.concatenate((ee_pos, grip_angles, door_angle))\n return obs *self.obs_scale\n\n def get_achieved_goal(self):\n return self.get_current_obs()\n\n def compute_reward(self, achieved_goal, desired_goal, trajectory, info):\n goal_mse = np.linalg.norm((achieved_goal - desired_goal))\n reward = 0\n # sparse and dense reward types are used for goal conditioned policy training, \n # density reward type is used for goal distribution conditioned policy training\n # assert self.reward_type in ['sparse', 'dense', 'density'], \"reward type must be one of three types. ['sparse', 'dense', 'density']\"\n if self.reward_type == 'sparse':\n if goal_mse < self.distance_threshold:\n reward = -1\n else:\n reward = 0\n elif self.reward_type == 'dense':\n reward = -goal_mse\n\n elif self.reward_type == 'density':\n achieved_goal_norm = (achieved_goal-self.obs_mean)/self.obs_std\n desired_goal_norm = (desired_goal-self.obs_mean)/self.obs_std \n # achieved_goal_norm_clip = np.clip(achieved_goal_norm, -5, 5)\n # desired_goal_norm_clip = np.clip(desired_goal_norm, -5, 5)\n\n self.kde_goal.fit([desired_goal_norm])\n\n if self.use_index:\n tra = np.array(trajectory)[:,:-1]\n else:\n tra = np.array(trajectory)\n\n tra_norm = (tra-self.obs_mean)/self.obs_std\n self.kde_tra.fit(tra_norm)\n\n log_g_density = self.kde_goal.score_samples([desired_goal_norm])\n log_density_from_g = self.kde_goal.score_samples([achieved_goal_norm])\n log_density_from_t = self.kde_tra.score_samples([achieved_goal_norm])\n\n if self.density_estimator is not None and self.use_global_density:\n log_global_density = self.density_estimator.score_samples([achieved_goal_norm])\n else:\n log_global_density = 0\n\n # log_density_from_g = np.clip(log_density_from_g, -np.abs(log_g_density)*5, 100)\n log_density_from_g = np.clip(log_density_from_g, -20, 100)\n log_density_from_t = np.clip(log_density_from_t, -50, 100)\n log_global_density = np.clip(log_global_density, -50, 100)\n\n if self.use_global_density:\n reward = ((log_density_from_g - (log_density_from_t*0.9 + log_global_density*0.1))[0]) * 0.005\n else:\n reward = ((log_density_from_g - log_density_from_t)[0]) * 0.005\n\n else:\n pass\n\n if self.use_extrinsic_reward:\n task_reward = self.compute_extrinsic_reward(achieved_goal)\n else:\n task_reward = 0\n\n # if info is not None and self.reward_type == 'density':\n # # print(desired_goal, desired_goal_norm)\n # # print(achieved_goal, achieved_goal_norm) \n # print(task_reward, log_density_from_g, log_density_from_t, log_global_density, (log_density_from_g - log_density_from_t), log_g_density, achieved_goal[-2:])\n return reward + task_reward\n\n def compute_extrinsic_reward(self, achieved_goal):\n task_angle = -0.304 * 4\n task_weight = 10.0\n x = achieved_goal[-1] - task_angle\n delta_alpha = 0.5\n if np.abs(x) < 0.035:\n task_reward = np.exp(-(x/delta_alpha)**2)/(np.abs(delta_alpha)*np.sqrt(np.pi))\n else:\n task_reward = 0\n \n return task_reward * task_weight \n\n def get_extrinsic_reward(self, achieved_goal_list):\n task_rewards = []\n print('achieved_goal_list size', achieved_goal_list.shape)\n for achieved_goal in achieved_goal_list:\n task_reward = self.compute_extrinsic_reward(achieved_goal)\n task_rewards.append(task_reward)\n\n return np.array(task_rewards)","repo_name":"pcchenxi/skew-explore","sub_path":"envs/yumi/yumi_door_env.py","file_name":"yumi_door_env.py","file_ext":"py","file_size_in_byte":10282,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"23435152205","text":"\"\"\"empty message\n\nRevision ID: 61ad805be946\nRevises: 14285570b537\nCreate Date: 2023-07-24 17:50:25.976024\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '61ad805be946'\ndown_revision = '14285570b537'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('characters',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=20), nullable=False),\n sa.Column('height', sa.String(length=20), nullable=False),\n sa.Column('mass', sa.String(length=20), nullable=False),\n sa.Column('home', sa.String(length=20), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('height'),\n sa.UniqueConstraint('mass'),\n sa.UniqueConstraint('name')\n )\n op.create_table('favorites',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('favorite_id', sa.Integer(), nullable=True),\n sa.Column('favorite_type', sa.String(length=100), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('user_id')\n )\n op.create_table('planets',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=25), nullable=False),\n sa.Column('gravity', sa.String(length=25), nullable=False),\n sa.Column('population', sa.String(length=25), nullable=True),\n sa.Column('climate', sa.String(length=25), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('starships',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=50), nullable=False),\n sa.Column('model', sa.String(length=50), nullable=False),\n sa.Column('length', sa.Numeric(precision=25, scale=0), nullable=True),\n sa.Column('pilots', sa.String(length=50), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('firstname', sa.String(length=25), nullable=False))\n batch_op.add_column(sa.Column('lastname', sa.String(length=25), nullable=False))\n batch_op.alter_column('email',\n existing_type=sa.VARCHAR(length=120),\n type_=sa.String(length=25),\n existing_nullable=False)\n batch_op.drop_constraint('user_email_key', type_='unique')\n batch_op.drop_column('password')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('password', sa.VARCHAR(length=80), autoincrement=False, nullable=False))\n batch_op.create_unique_constraint('user_email_key', ['email'])\n batch_op.alter_column('email',\n existing_type=sa.String(length=25),\n type_=sa.VARCHAR(length=120),\n existing_nullable=False)\n batch_op.drop_column('lastname')\n batch_op.drop_column('firstname')\n\n op.drop_table('starships')\n op.drop_table('planets')\n op.drop_table('favorites')\n op.drop_table('characters')\n # ### end Alembic commands ###\n","repo_name":"4GeeksAcademy/r-moore-StarWars-REST-API","sub_path":"migrations/versions/61ad805be946_.py","file_name":"61ad805be946_.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71742737767","text":"import numpy as np\nimport scipy.spatial\n\n\ndef reconstruction_error(ground_truth, inferred):\n \"\"\"|ground_truth - inferred|_2.\"\"\"\n return np.sqrt(np.sum((inferred - ground_truth)**2, axis=-1))\n\n\ndef _procrustes(ground_truth, inferred):\n nj = ground_truth.shape[0]\n invalid = np.logical_or(\n np.any(np.isnan(ground_truth), axis=-1),\n np.any(np.isnan(inferred), axis=-1))\n\n valid = np.logical_not(invalid)\n ground_truth = ground_truth[valid]\n inferred = inferred[valid]\n\n if len(ground_truth) < 2:\n return np.nan\n gt = ground_truth - np.mean(ground_truth, 0)\n norm = np.linalg.norm(gt)\n assert(norm != 0)\n p3, p3_i, l2 = scipy.spatial.procrustes(gt, inferred)\n p3_i *= norm\n p3 *= norm\n err = reconstruction_error(p3, p3_i)\n\n ret_p3 = np.empty((nj, 3))\n ret_p3_i = np.empty((nj, 3))\n ret_err = np.empty((nj,))\n\n for ret in [ret_p3, ret_p3_i, ret_err]:\n ret[invalid] = np.nan\n\n ret_p3[valid] = p3\n ret_p3_i[valid] = p3_i\n ret_err[valid] = err\n\n return ret_err, ret_p3, ret_p3_i\n\n\ndef procrustes(ground_truth, inferred):\n \"\"\"\n Get the procruste error between ground_truth and inferred.\n\n The Procruste error is the minimum reconstruction loss over all rigid\n transformations T of (T(inferred) - ground_truth).\n\n Arguments:\n ground_truth: data label, shape (n, m, 3) (batched) or (m, 3)\n inferred: inferred value, same shape as ground truth\n\n Returns:\n error: error value, or array of length n if batched\n p3: transformed ground_truth\n p3i: transformed inference\n \"\"\"\n if ground_truth.shape != inferred.shape:\n raise Exception(\n 'Shapes must be same but got %s, %s' %\n (str(ground_truth.shape), str(inferred.shape)))\n if len(ground_truth.shape) > 2:\n orig_shape = ground_truth.shape\n ground_truth_flat = np.reshape(ground_truth, (-1,) + orig_shape[-2:])\n inferred_flat = np.reshape(inferred, (-1,) + orig_shape[-2:])\n\n p3 = np.empty_like(inferred_flat)\n p3_i = np.empty_like(inferred_flat)\n err = np.empty(inferred_flat.shape[:-1], dtype=p3_i.dtype)\n for i, (gt, inf) in enumerate(zip(ground_truth_flat, inferred_flat)):\n err[i], p3[i], p3_i[i] = _procrustes(gt, inf)\n err = np.reshape(err, orig_shape[:-1])\n p3 = np.reshape(p3, orig_shape)\n p3_i = np.reshape(p3_i, orig_shape)\n return err, p3, p3_i\n else:\n return _procrustes(ground_truth, inferred)\n\n\ndef procrustes_error(ground_truth, inferred):\n \"\"\"Get the error component of `procrustes`.\"\"\"\n return procrustes(ground_truth, inferred)[0]\n\n\ndef sequence_procrustes(ground_truth, inferred):\n \"\"\"\n Get the procruste error for a sequence.\n\n Uses the same optimal transform for all poses.\n\n Args:\n ground_truth: (n, m, 3)\n inferred: (n, m, 3)\n\n Returns:\n error: (n,)\n p3: (n, m, 3)\n p3i: (n, m, 3)\n \"\"\"\n n, m = ground_truth.shape[:2]\n assert(ground_truth.shape == (n, m, 3))\n assert(ground_truth.shape == inferred.shape)\n err, p3, p3i = procrustes(\n ground_truth.reshape(-1, 3), inferred.reshape(-1, 3))\n p3 = p3.reshape(n, m, 3)\n p3i = p3i.reshape(n, m, 3)\n err = reconstruction_error(p3, p3i)\n return err, p3, p3i\n\n\ndef sequence_procrustes_error(ground_truth, inferred):\n \"\"\"Get the error component of `sequence_procrustes`.\"\"\"\n return sequence_procrustes(ground_truth, inferred)[0]\n","repo_name":"jackd/human_pose_util","sub_path":"human_pose_util/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"53"}
+{"seq_id":"25361342796","text":"#!/usr/bin/env python3\n \ndef rvs(s):\n if s == \"\":\n return s\n else:\n return rvs(s[1:])+s[0]\n# print(rvs(\"hello\"))\n\ndef f(n):\n if n ==1 or n == 2:\n return 1\n else:\n return f(n-1) + f(n - 2)\n\ncount = 0\ndef hanoi(n, src, dst, mid):\n global count\n if n == 1:\n count += 1\n print(\"{:2d} {}: {}->{}\".format(count, 1, src, dst))\n else:\n hanoi(n-1, src, mid, dst)\n count += 1\n print(\"{:2d} {}: {}->{}\".format(count, n, src, dst))\n hanoi(n-1, mid, dst, src)\n\nhanoi(6, 'A', 'C', 'B')\n","repo_name":"fanghsiaohui/foobar","sub_path":"python/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18654040309","text":"__author__ = 'zhengyangqiao'\n\"\"\"\nThe image converter will convert png or jpg to grey scale matrix\nfor handwritten digits recognition.\n\"\"\"\nimport numpy as np\nfrom PIL import Image\n\n# set element in matrix to two digits\n# float_formatter = lambda x: \"%.1f\" % x\n# np.set_printoptions(formatter={'float_kind':float_formatter})\nx = Image.open('handwritten_number.png', 'r')\nx = x.convert('L') # make it greyscale\ny = np.asarray(x.getdata(), dtype=np.int16).reshape((x.size[1], x.size[0]))\n\nlength = x.size[1] / 28\nwidth = x.size[0] / 28\nprint(length, width)\n\ncleanedMatrix = [[]]\ncleanedMatrix = [[0 for i in range(0, 28)] for j in range(0, 28)]\nfor i in range(0 , 28):\n for j in range(0, 28):\n ii = i * length\n jj = j * width\n cleanedMatrix[i][j] = np.sum(y[ii : ii + length, jj : jj + width]) / (length * width)\n\n\n# final = np.round(y, 2)\n# print(y)\n# print(cleanedMatrix)\n\nprint(cleanedMatrix)","repo_name":"BridgeNB/Neuron_Network","sub_path":"handwritten digits recognizer/ImageConverter.py","file_name":"ImageConverter.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"75115442728","text":"import hashlib\nimport io\nimport json\nimport operator\nfrom pathlib import Path\nimport pickle\nimport random\nimport requests\nfrom typing import Iterable, Optional\n\nimport cv2\nimport numpy as np\nfrom logzero import logger\n\nfrom rekall.bounds import Bounds3D\nfrom stsearch.op import Filter, Flatten, FromIterable, Graph, Map, Op\nfrom stsearch.parallel import ParallelMap\nfrom stsearch.videolib import ImageInterval\n\nDEFAULT_DETECTION_KEY = 'CVLIB_DETECTION_KEY'\n\nclass Detection(Graph):\n \"\"\"Detection result is written to input interval *in-place*.\n\n \"\"\"\n\n def __init__(\n self, \n server='localhost', port=5000, \n server_list: Optional[Iterable[str]]=None,\n result_key=DEFAULT_DETECTION_KEY,\n parallel=1,\n name=None):\n\n super().__init__()\n\n self.server_list = list(server_list or [f\"{server}:{port}\", ])\n self.result_key = result_key\n self.name = name\n self.parallel = parallel\n\n\n def call(self, instream):\n name = self.name or f\"{self.__class__.__name__}:{self.result_key}\"\n\n def map_fn(intrvl):\n assert isinstance(intrvl, ImageInterval)\n\n max_try = 5\n while max_try > 0:\n try:\n server = random.choice(self.server_list)\n detect_url = f\"http://{server}/detect\"\n r = requests.post(detect_url, files={'image': io.BytesIO(intrvl.jpeg)})\n assert r.ok\n break\n except Exception as e:\n logger.exception(e)\n max_try -= 1\n if max_try <= 0:\n raise\n\n result = r.json()\n if result['success']:\n intrvl.payload[self.result_key] = result\n # logger.debug(result)\n else:\n raise RuntimeError(str(result))\n \n return intrvl\n\n if self.parallel == 1:\n return Map(map_fn, name=name)(instream)\n else:\n return ParallelMap(map_fn, name=name, max_workers=self.parallel)(instream)\n\n \nclass DetectionVisualize(Graph):\n\n def __init__(self, targets=None, confidence=0.9, result_key=DEFAULT_DETECTION_KEY, color=(0, 255, 0), black_list=False):\n \"\"\"[summary]\n\n Args:\n targets ([type], optional): [description]. Defaults to None.\n confidence (float, optional): [description]. Defaults to 0.9.\n result_key ([type], optional): [description]. Defaults to DEFAULT_DETECTION_KEY.\n color (tuple, optional): [description]. Defaults to (0, 255, 0).\n black_list (bool, optional): If True, `targets` is interprested as a black list. Classes NOT in targets will be visualized. Defaults to False.\n\n Raises:\n KeyError: [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n super().__init__()\n\n assert iter(targets)\n self.targets = targets\n self.confidence = confidence\n self.result_key = result_key\n self.color = color\n self.black_list = black_list\n \n def map_fn(intrvl):\n try:\n detections = intrvl.payload[self.result_key]\n except KeyError:\n raise KeyError( f\"Cannot find {self.result_key} in input payload. Did you run object detection on the input stream?\")\n\n rgb = np.copy(intrvl.rgb)\n for box, score, class_name in zip(detections['detection_boxes'], detections['detection_scores'], detections['detection_names']):\n if score < self.confidence:\n break\n\n if (not self.black_list and class_name in self.targets) or (self.black_list and class_name not in self.targets):\n top, left, bottom, right = box # TF return between 0~1\n H, W = intrvl.rgb.shape[:2]\n top, left, bottom, right = int(top*H), int(left*W), int(bottom*H), int(right*W) # to pixels\n rgb = cv2.rectangle(rgb, (left, top), (right, bottom), self.color, 3)\n \n new_intrvl = intrvl.copy()\n new_intrvl.rgb = rgb\n return new_intrvl\n\n self.map_fn = map_fn\n\n def call(self, instream):\n return Map(self.map_fn)(instream)\n\n\nclass DetectionFilter(Graph):\n \n def __init__(self, targets, confidence=0.9, result_key=DEFAULT_DETECTION_KEY):\n super().__init__()\n\n assert iter(targets)\n self.targets = targets\n self.confidence = confidence\n self.result_key = result_key\n\n def call(self, instream):\n \n def pred_fn(intrvl):\n try:\n detections = intrvl.payload[self.result_key]\n except KeyError:\n raise KeyError( f\"Cannot find {self.result_key} in input payload. Did you run object detection on the input stream?\")\n\n for box, score, class_name in zip(detections['detection_boxes'], detections['detection_scores'], detections['detection_names']):\n if score < self.confidence:\n return False\n for t in self.targets:\n if t in class_name:\n return True\n return False\n\n return Filter(pred_fn)(instream)\n\n\nclass DetectionFilterFlatten(Graph):\n\n def __init__(self, targets, confidence=0.9, result_key=DEFAULT_DETECTION_KEY, name=None, black_list=False):\n super().__init__()\n assert iter(targets)\n self.targets = targets\n self.confidence = confidence\n self.result_key = result_key\n self.name = name or self.__class__.__name__\n self.black_list = black_list\n\n def call(self, instream):\n\n def flatten_fn(intrvl):\n rv = []\n try:\n detections = intrvl.payload[self.result_key]\n except KeyError:\n raise KeyError( f\"Cannot find {self.result_key} in input payload. Did you run object detection on the input stream?\")\n\n for box, score, class_name in zip(detections['detection_boxes'], detections['detection_scores'], detections['detection_names']):\n if score < self.confidence:\n break\n\n if (not self.black_list and class_name in self.targets) or (self.black_list and class_name not in self.targets):\n # create new patch\n top, left, bottom, right = box # TF return between 0~1\n # the following arithmetic should be correct even if `intrvl` is not full frame.\n new_bounds = Bounds3D(\n intrvl['t1'], intrvl['t2'],\n intrvl['x1'] + intrvl.bounds.width() * left,\n intrvl['x1'] + intrvl.bounds.width() * right,\n intrvl['y1'] + intrvl.bounds.height() * top,\n intrvl['y1'] + intrvl.bounds.height() * bottom\n )\n new_patch = ImageInterval(new_bounds, root=intrvl.root)\n rv.append(new_patch)\n rv.sort(key=lambda i: i.bounds)\n return rv\n\n return Flatten(flatten_fn, name=self.name)(instream)\n\n\nclass CachedVIRATDetection(Graph):\n def __init__(self, path, cache_dir=\"/root/cache\", result_key=DEFAULT_DETECTION_KEY):\n\n # load cache file and sort by t1, so that we can direct access by indexing\n h = hashlib.md5()\n with open(path, 'rb') as f:\n h.update(f.read())\n digest = str(h.hexdigest())\n cache_path = str(Path(cache_dir) / (digest+'.json'))\n with open(cache_path, 'rt') as f:\n C = json.load(f)\n\n cached_detection = C['detection'] # list of dict\n cached_detection = sorted(cached_detection, key=operator.itemgetter('t1')) \n self.C = cached_detection\n\n self.result_key = result_key\n\n def call(self, instream):\n\n def map_fn(intrvl):\n t1 = int(intrvl['t1'])\n intrvl.payload[self.result_key] = self.C[t1]['detection']\n return intrvl\n\n return Map(map_fn)(instream)\n\n\nclass CachedOkutamaDetection(Graph):\n def __init__(self, path, cache_dir):\n # load cache file and sort by t1, so that we can direct access by indexing\n h = hashlib.md5()\n with open(path, 'rb') as f:\n h.update(f.read())\n digest = str(h.hexdigest())\n cache_path = str(Path(cache_dir) / (digest+'.pkl'))\n with open(cache_path, 'rb') as f:\n L = pickle.load(f)\n\n self.L = L\n\n def call(self):\n def map_fn(intrvl):\n return ImageInterval(intrvl.bounds.copy(), intrvl.payload)\n return Map(map_fn)(FromIterable(self.L)())\n\n \n","repo_name":"fzqneo/stsearch","sub_path":"stsearch/cvlib/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":8804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8435093463","text":"\"\"\"\n@author : Shrikanth N C (nc.shrikanth@gmail.com)\nDate: 15 Dec 2019\nScript to assess belief 1 Corbat ́o’s law\nLicense: See LICENSE file\n\"\"\"\n\nfrom data.pspdata import *\nimport math\n\n\nMINIMUM_SAMPLE_SIZE = 50\nMAX_SAMPLE_SIZE = math.inf #100\n\n\nPROGRAM_ASSIGNMENT_LIST_ALL = [ str(x)+'A' for x in range(1,11)]\n\nPROGRAM_ASSIGNMENT_LIST_LEVEL0 = [ str(x)+'A' for x in range(1,4)]\nPROGRAM_ASSIGNMENT_LIST_LEVEL1 = [ str(x)+'A' for x in range(4,7)]\nPROGRAM_ASSIGNMENT_LIST_LEVEL2 = [ str(x)+'A' for x in range(7,11)]\n\nPROGRAMMING_LANGUAGES = ['C', 'C++', 'C#', 'JAVA', 'VB']\n\n\nSTATSCOURSE_COLNAME = 'StatsCourse'\nPROGRAMMINGLANGUAGE_COLNAME = 'ProgrammingLanguage'\nYEARSPROGRAMMINGEXPERIENCE_COLNAME = 'YearsProgrammingExperience'\nPSPASSGTDATAID_COLNAME = 'PSPAssgtDataID'\nPSPSTUDATAID_COLNAME = 'PSPStuDataID'\nASSGTSTATUSID_COLNAME = 'AssgtStatusID'\nPSPLEVEL_COLNAME = 'PSPLevel'\nASSGTSEQUENCE_COLNAME = 'AssgtSequence'\nPROGRAMASSIGNMENT_COLNAME = 'ProgramAssignment'\nESTLOC_COLNAME = 'EstLOC'\nACTLOC_COLNAME = 'ActLOC'\nESTMIN_COLNAME = 'EstMin'\nACTMIN_COLNAME = 'ActMin'\nESTDEFREM_COLNAME = 'EstDefRem'\nACTDEFREM_COLNAME = 'ActDefRem'\nESTMINPLAN_COLNAME = 'EstMinPlan'\nACTMINPLAN_COLNAME = 'ActMinPlan'\nESTMINDSGN_COLNAME = 'EstMinDsgn'\nACTMINDSGN_COLNAME = 'ActMinDsgn'\nESTMINDLDR_COLNAME = 'EstMinDLDR'\nACTMINDLDR_COLNAME = 'ActMinDLDR'\nESTMINCODE_COLNAME = 'EstMinCode'\nACTMINCODE_COLNAME = 'ActMinCode'\nESTMINCR_COLNAME = 'EstMinCR'\nACTMINCR_COLNAME = 'ActMinCR'\nESTMINCOMPILE_COLNAME = 'EstMinCompile'\nACTMINCOMPILE_COLNAME = 'ActMinCompile'\nESTMINTEST_COLNAME = 'EstMinTest'\nACTMINTEST_COLNAME = 'ActMinTest'\nESTMINPM_COLNAME = 'EstMinPM'\nACTMINPM_COLNAME = 'ActMinPM'\nESTDEFINJPLAN_COLNAME = 'EstDefInjPlan'\nESTDEFINJDSGN_COLNAME = 'EstDefInjDsgn'\nESTDEFINJDLDR_COLNAME = 'EstDefInjDLDR'\nESTDEFINJCODE_COLNAME = 'EstDefInjCode'\nESTDEFINJCR_COLNAME = 'EstDefInjCR'\nESTDEFINJCOMPILE_COLNAME = 'EstDefInjCompile'\nESTDEFINJTEST_COLNAME = 'EstDefInjTest'\nESTDEFREMPLAN_COLNAME = 'EstDefRemPlan'\nESTDEFREMDSGN_COLNAME = 'EstDefRemDsgn'\nESTDEFREMDLDR_COLNAME = 'EstDefRemDLDR'\nESTDEFREMCODE_COLNAME = 'EstDefRemCode'\nESTDEFREMCR_COLNAME = 'EstDefRemCR'\nESTDEFREMCOMPILE_COLNAME = 'EstDefRemCompile'\nESTDEFREMTEST_COLNAME = 'EstDefRemTest'\nACTDEFINJPLAN_COLNAME = 'ActDefInjPlan'\nACTDEFINJDSGN_COLNAME = 'ActDefInjDsgn'\nACTDEFINJDLDR_COLNAME = 'ActDefInjDLDR'\nACTDEFINJCODE_COLNAME = 'ActDefInjCode'\nACTDEFINJCR_COLNAME = 'ActDefInjCR'\nACTDEFINJCOMPILE_COLNAME = 'ActDefInjCompile'\nACTDEFINJTEST_COLNAME = 'ActDefInjTest'\nACTDEFREMPLAN_COLNAME = 'ActDefRemPlan'\nACTDEFREMDSGN_COLNAME = 'ActDefRemDsgn'\nACTDEFREMDLDR_COLNAME = 'ActDefRemDLDR'\nACTDEFREMCODE_COLNAME = 'ActDefRemCode'\nACTDEFREMCR_COLNAME = 'ActDefRemCR'\nACTDEFREMCOMPILE_COLNAME = 'ActDefRemCompile'\nACTDEFREMTEST_COLNAME = 'ActDefRemTest'\nDDTEST_COLNAME = 'DDTest'\nACTPRODRATE_COLNAME = 'ActProdRate'\nRELSIZEERROR_COLNAME = 'RelSizeError'\nABSRELSIZEERROR_COLNAME = 'absRelSizeError'\nRELEFFORTERROR_COLNAME = 'RelEffortError'\nABSRELEFFORTERROR_COLNAME = 'absRelEffortError'\nACTMINPROD_COLNAME = 'ActMinProd'\nESTMINOH_COLNAME = 'EstMinOH'\nESTMINCONST_COLNAME = 'EstMinConst'\nESTMINAPR_COLNAME = 'EstMinApr'\nESTMINFAIL_COLNAME = 'EstMinFail'\nACTMINOH_COLNAME = 'ActMinOH'\nACTMINCONST_COLNAME = 'ActMinConst'\nACTMINAPR_COLNAME = 'ActMinApr'\nACTMINFAIL_COLNAME = 'ActMinFail'\nCONSTPRODRATIO_COLNAME = 'ConstProdRatio'\nAPRPRODRATIO_COLNAME = 'AprProdRatio'\nFAILPRODRATIO_COLNAME = 'FailProdRatio'\nRATIO_DSGNCODE_COLNAME = 'Ratio_DsgnCode'\nRATIO_CRCODE_COLNAME = 'Ratio_CRCode'\nRATIO_DLDRDSGN_COLNAME = 'Ratio_DLDRDsgn'\nRATIO_APRCONST_COLNAME = 'Ratio_AprConst'\nDDCOMPILE_COLNAME = 'DDCompile'\nRATECR_COLNAME = 'RateCR'\nDEFESCDSGN_COLNAME = 'DefEscDsgn'\nDEFESCDLDR_COLNAME = 'DefEscDLDR'\nDEFESCCODE_COLNAME = 'DefEscCode'\nDEFESCCR_COLNAME = 'DefEscCR'\nDEFESCCOMPILE_COLNAME = 'DefEscCompile'\nYIELDDLDR_COLNAME = 'YieldDldr'\nYIELDCR_COLNAME = 'YieldCR'\nYIELDCOMPILE_COLNAME = 'YieldCompile'\nPROCESSYIELD_COLNAME = 'ProcessYield'\nDEFREMRATEDLDR_COLNAME = 'DefRemRateDLDR'\nDEFREMRATECR_COLNAME = 'DefRemRateCR'\nDEFREMRATECOMPILE_COLNAME = 'DefRemRateCompile'\nDEFREMRATETEST_COLNAME = 'DefRemRateTest'\nDEVELOPER_LOC_COLNAME = 'Developer LOC'\nDEVELOPERCONSTMIN_COLNAME = 'DeveloperConstMin'\nDEVELOPERPRODMIN_COLNAME = 'DeveloperProdMin'\nDEVELOPERPRODRATE_COLNAME = 'DeveloperProdRate'\nDEVELOPERDEFECTS_COLNAME = 'DeveloperDefects'\nDEVELOPERTESTDEFECTS_COLNAME = 'DeveloperTestDefects'\nDEVELOPERDD_COLNAME = 'DeveloperDD'\nDEVELOPERDEFINJRATE_COLNAME = 'DeveloperDefInjRate'\nCALC_ACTDEFINJ_COLNAME = 'Calc_ActDefInj'\nCALC_ACTDEFREM_COLNAME = 'calc_ActDefRem'\nMATCH_DEFREM_INJ_COLNAME = 'Match_DefRem_Inj'\nPL_GEN_COLNAME = 'PL_Gen'\nPL_CATEGORY_COLNAME = 'PL_Category'\nONED_CATEGORY_COLNAME = '1D_Category'\nPL_LEVEL_COLNAME = 'PL_Level'\nPL_LEVEL_BIN_COLNAME = 'PL_Level_Bin'\nLOC_MIN_COLNAME = 'LOC/Min'\nTASK_COLNAME = 'Task'\n\n\ndef normalize(samples, minVal, maxVal):\n\n\n\n normCol = []\n\n for v in samples:\n\n normalizedValue = (v - minVal) / ((maxVal - minVal) + 0.000000001)\n\n normCol.append(normalizedValue * 100)\n\n\n return normCol\n\n\n\n# if __name__ == '__main__':\n#\n# df = getPSPDF()\n#\n# for c in df.columns:\n# print(c.upper()+\"_COLNAME\", \" = \", \"'\"+c+\"'\")","repo_name":"snaraya7/SE_Beliefs","sub_path":"PSPConstants.py","file_name":"PSPConstants.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14430552005","text":"from urllib.parse import urlencode\nfrom urllib.request import urlopen, Request\nimport json\nfrom urllib.request import urlopen\nimport json\nimport requests\n\n\n\ndef test1():\n j = json.loads('{\"one\" : \"1\", \"two\" : \"2\", \"three\" : \"3\"}')\n\n html = urlopen(\"http://www.czce.com.cn/portal/DFSStaticFiles/Future/2017/20171026/FutureDataDaily.xls\")\n data = html.read()\n print(data)\n return\ndef test2():\n session = requests.Session()\n # params = {'username': 'username', 'password': 'password'}\n s = session.post(\"http://www.ine.cn/bourseService/summary/?name=currinstrumentprop\")\n\n print(s.cookies.get_dict())\n print(\"-----------\")\n print(\"Going to profile page...\")\n # s = session.get(\"http://www.czce.com.cn/portal/DFSStaticFiles/Future/2018/20180309/FutureDataHolding.htm\")\n # http://www.czce.com.cn/portal/DFSStaticFiles/Future/2017/20171026/FutureDataDaily.xls\n s = session.get(\"http://www.ine.cn/data/instrument/ContractBaseInfo20180326.dat?rnd=0.7176823465048681\")\n print(s.text)\n ans = s.json()\n # json.loads(json_str)\n return\n\ndef main():\n test2()\n return\nif __name__ == '__main__':\n main()","repo_name":"niejn/selenium_test","sub_path":"能源交易所.py","file_name":"能源交易所.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8819620927","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom pyhdf.SD import SD, SDC\r\nimport os\r\n#%%\r\n#print(file.info())\r\n# for idx, sds in enumerate(datasest_dic.keys()):\r\n# print(idx, sds)\r\n# datasest_dic = file.datasets()\r\n\r\ndirs = next(os.walk('.'))[1]\r\ndata = []\r\nfor dir in dirs:\r\n dirs1 = next(os.walk('./'+dir))[1]\r\n for dir1 in dirs1:\r\n archs = [x for x in os.listdir('./'+dir+'./'+dir1) if x.endswith('.hdf')]\r\n #data = np.zeros((len(archs), 203, 135))\r\n for ar in archs:\r\n file = SD('./'+dir+'/'+dir1+'/'+ar, SDC.READ)\r\n sds_obj = file.select('Optical_Depth_Land_And_Ocean')\r\n dat = sds_obj.get()\r\n data.append(dat)\r\n ODLO = np.array(data)\r\n ODLO_mean = np.mean(ODLO, axis=0)\r\n np.savetxt('./'+dir+'/'+'promedio_'+archs[0][10:17]+'.txt', ODLO_mean)\r\n\r\n#%%\r\n# plt.imshow(ODLO_mean)\r\n# #plt.gca().invert_yaxis()\r\n# plt.savefig('promedio_001.pdf', dpi=480)\r\n#plt.show()\r\n\r\n# plt.imshow(ODLO[0])\r\n# plt.gca().invert_yaxis()\r\n# plt.show()\r\n#\r\n# plt.imshow(ODLO[1])\r\n# plt.gca().invert_yaxis()\r\n# plt.show()\r\n#\r\n# plt.imshow(ODLO[2])\r\n# plt.gca().invert_yaxis()\r\n# plt.show()\r\n","repo_name":"juanitopereza/HDF","sub_path":"prom_dia.py","file_name":"prom_dia.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3227979865","text":"input_file = open('input.txt', 'r')\nLines = input_file.readlines()\n\ndef split(word):\n return [char for char in word]\n\ndef get_common(list, column):\n\tline_count= len(list)\n\thalf_count = line_count/2\n\tbit_counts = 0\n\n\tfor line in list:\n\t\treport = split(line.strip())\n\t\tbit_counts += int(report[column])\n\n\tif bit_counts >= half_count:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\ndef filter_list(list,column,filter):\n\tfiltered_list = []\n\tfor line in list:\n\t\treport = split(line.strip())\n\t\tvalue = int(report[column])\n\t\tif value == filter:\n\t\t\tfiltered_list.append(line.strip())\n\treturn filtered_list\n\n\ncolumns = len(Lines[0].strip())\n\noxygen_list = Lines\nco2_list = Lines\nfor i in range(columns):\n\tif len(oxygen_list) > 1:\n\t\tcommon = get_common(oxygen_list,i)\n\t\toxygen_list = filter_list(oxygen_list,i,common)\n\n\n\t#CO2 scrubber rating\n\tif len(co2_list) > 1:\n\t\tcommon = get_common(co2_list,i)\n\t\tif common:\n\t\t\tcommon = 0\n\t\telse:\n\t\t\tcommon = 1\n\t\tco2_list = filter_list(co2_list,i,common)\n\nprint(\"Oxygen generator rating:{}({})\".format(oxygen_list[0],int(oxygen_list[0],2)))\t\nprint(\"CO2 scrubber rating:{}({})\".format(co2_list[0],int(co2_list[0],2)))\nprint(\"life support rating:{}\".format(int(oxygen_list[0],2)*int(co2_list[0],2)))\t\t","repo_name":"cyberphilia/adventofcode2021","sub_path":"day03/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"19688243134","text":"# ABC-152 B - Comparing Strings\r\n# https://atcoder.jp/contests/abc152/tasks/abc152_b\r\n#\r\ndef getIntMap():\r\n return map(int, input().split())\r\n\r\n\r\ndef main():\r\n a, b = getIntMap()\r\n\r\n s = [\"\".join([str(a) for _ in range(b)]),\r\n \"\".join([str(b) for _ in range(a)])]\r\n s.sort()\r\n\r\n print(s[0])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"hyperdb/AtCoderPy","sub_path":"ABC/101-200/151-160/ABC-152-B.py","file_name":"ABC-152-B.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2358117195","text":"import requests\n\nfrom jose import jwt, jwk\nfrom jose.utils import base64url_decode\n\n\ndef get_hmac_key(token: str, jwks):\n kid = jwt.get_unverified_header(token).get(\"kid\")\n for key in jwks.get(\"keys\", []):\n if key.get(\"kid\") == kid:\n return key\n\n\ndef verify_jwt(token: str, jwks) -> bool:\n hmac_key = get_hmac_key(token, jwks)\n\n if not hmac_key:\n raise ValueError(\"No pubic key found!\")\n\n hmac_key = jwk.construct(get_hmac_key(token, jwks))\n\n message, encoded_signature = token.rsplit(\".\", 1)\n\n decoded_signature = base64url_decode(encoded_signature.encode())\n\n return hmac_key.verify(message.encode(), decoded_signature)\n\n\ndef get_jwks(jwks_url):\n resp = requests.get(\n jwks_url\n ).json()\n\n return resp\n","repo_name":"antonigudesman/health-care-lambda-proxy","sub_path":"jwt_utils.py","file_name":"jwt_utils.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"23551664131","text":"import copy\nfrom functools import partial\nimport json\nimport logging\nimport os\nimport json\nimport pickle\nfrom typing import Optional, Sequence\nimport random\n\nimport ml_collections as mlc\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom torch.nn.functional import pad\nfrom torch.utils.data import RandomSampler, Dataset, random_split\nfrom ipa_refine.utils import refinement_utils as Utils\nfrom ipa_refine.data.pipeline import RefinementDataPipeline\nfrom ipa_refine.data.feature_pipeline import FeaturePipeline\nfrom ipa_refine.np import residue_constants, protein\nfrom ipa_refine.utils.tensor_utils import tensor_tree_map, dict_multimap\nfrom ipa_refine.data.refinement_features import get_features\n\n\n# def save_split(train, val, test):\n# split_dict = {\n# 'train_paths': train,\n# 'val_paths': val,\n# 'test_paths': test\n# }\n# with open(split_path, 'w') as convert_file:\n# convert_file.write(json.dumps(split_dict))\n\n\n# The Function Used in Dataloader\ndef get_filtered_train_set(data_list_file, limit=-1):\n f = open(data_list_file, 'r')\n mapping = json.load(f)\n f.close()\n mapping = mapping[\"train\"]\n random.shuffle(mapping)\n mapping = mapping[:limit]\n return mapping\n\n\nclass RefinementSingleDataset(Dataset):\n\n def __init__(self,\n data_paths: [],\n mode: str,\n config: mlc.ConfigDict,\n adj_type='Cb1-Cb2',\n adj_cutoff=10,\n ):\n\n self.config = config\n self.adj_type = adj_type\n self.adj_cutoff = adj_cutoff\n self.mapping = data_paths\n self.data_len = len(self.mapping)\n self.data_pipeline = RefinementDataPipeline()\n self.feature_pipeline = FeaturePipeline(self.config)\n\n def __len__(self):\n return self.data_len\n\n def __getitem__(self, idx):\n ref_pdb_file = self.mapping[idx]['x']\n gt_pdb_file = self.mapping[idx]['y']\n feature_tensor = get_features(ref_pdb_file)\n gt_features = self.data_pipeline.process_pdb(pdb_path=gt_pdb_file)\n gt_feats = self.feature_pipeline.process_features(gt_features)\n sample = {\n 'x_features': feature_tensor,\n 'y_features': gt_feats\n }\n return sample\n\n\nclass RefinementBatchCollator:\n\n def __init__(self, config, generator, stage=\"train\"):\n self.config = config\n self.generator = generator\n self.stage = stage\n\n def __call__(self, raw_batch):\n processed_batch = []\n max_len = max([len(p['x_features']['node']) for p in raw_batch])\n for prot in raw_batch:\n processed_prot = {}\n seq_size = len(prot['x_features']['node'])\n pad_size = max_len - seq_size\n # for x and y feats\n for key_out in prot.keys():\n new_prot = {}\n # for each individual feat\n for key in prot[key_out].keys():\n feature = prot[key_out][key]\n shape = [dim == seq_size for dim in feature.size()]\n pad_shape = [(0, pad_size*d)for d in shape]\n pad_shape.reverse()\n pad_shape = [item for sublist in pad_shape for item in sublist]\n newfeat = pad(feature, pad_shape)\n new_prot[key] = newfeat\n processed_prot[key_out] = new_prot\n processed_batch.append(processed_prot)\n\n stack_fn = partial(torch.stack, dim=0)\n return dict_multimap(stack_fn, processed_batch)\n\n\nclass RefinementDataModule(pl.LightningDataModule):\n\n def __init__(self,\n config: mlc.ConfigDict,\n data_list_file: str,\n # eval: bool,\n train_limit: Optional[int],\n batch_seed: Optional[int] = None\n ):\n super(RefinementDataModule, self).__init__()\n\n self.config = config\n self.data_list_file = data_list_file\n self.batch_seed = batch_seed\n self.train_limit = train_limit\n self.eval = False\n\n def setup(self, stage: Optional[str] = None):\n # if (stage is None):\n # stage = \"train\"\n stage = \"train\"\n\n mapping = get_filtered_train_set(self.data_list_file, self.train_limit) #get_train_set()\n\n # Most of the arguments are the same for the three datasets\n # dataset_gen = partial(RefinementSingleDataset)\n test_len = int(0.1 * len(mapping))\n val_len = int(0.12 * (len(mapping) - test_len))\n train_len = len(mapping) - test_len - val_len\n self.train_paths, self.test_paths = random_split(mapping, [train_len+val_len, test_len])\n self.train_paths, self.val_paths = random_split(self.train_paths, [train_len, val_len])\n\n ## TODO: Function to write split to disk with model_ID\n # save_split(self.train_paths, self.val_paths, self.test_paths)\n\n\n if (stage == 'train'): #self.training_mode):\n self.train_dataset = RefinementSingleDataset(self.train_paths, 'train', self.config)\n self.val_dataset = RefinementSingleDataset(self.val_paths, 'eval', self.config)\n else:\n self.predict_dataset = RefinementSingleDataset(self.test_paths, mode='predict')\n\n def _gen_batch_collator(self, stage):\n \"\"\" We want each process to use the same batch collation seed \"\"\"\n generator = torch.Generator()\n if (self.batch_seed is not None):\n generator = generator.manual_seed(self.batch_seed)\n collate_fn = RefinementBatchCollator(\n self.config, generator, stage\n )\n return collate_fn\n\n def train_dataloader(self):\n return torch.utils.data.DataLoader(\n self.train_dataset,\n batch_size=self.config.data_module.data_loaders.batch_size,\n num_workers=self.config.data_module.data_loaders.num_workers,\n collate_fn=self._gen_batch_collator(\"train\"),\n )\n\n def val_dataloader(self):\n if (self.val_dataset is not None):\n return torch.utils.data.DataLoader(\n self.val_dataset,\n batch_size=self.config.data_module.data_loaders.batch_size,\n num_workers=self.config.data_module.data_loaders.num_workers,\n collate_fn=self._gen_batch_collator(\"eval\")\n )\n return None\n\n def predict_dataloader(self):\n return torch.utils.data.DataLoader(\n self.predict_dataset,\n batch_size=self.config.data_module.data_loaders.batch_size,\n num_workers=self.config.data_module.data_loaders.num_workers,\n collate_fn=self._gen_batch_collator(\"predict\")\n )","repo_name":"nimban/structure-refinement","sub_path":"ipa_refine/data/data_modules.py","file_name":"data_modules.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20458228794","text":"import sys\n\ndef read_input():\n f = sys.stdin\n r, b, y = map(int, f.readline().split())\n print(r ,b,y)\n return r, b, y\n\nread_input()\n\n\ndef solve(r, b, y):\n answer = 0\n # code here\n if(max(r,b,y)==r):\n answer = r*3-3\n elif(max(r,b,y)==b):\n answer= b*3\n else:\n answer= y*3+3\n return answer\n\ndef main():\n read_input()\n # answer = solve(r, b, y)\n # print(answer)\n\n\nif __name__ == '__main__':\n main()","repo_name":"dongstar9990/Indentifi_Mask","sub_path":"bonus 1st week.py","file_name":"bonus 1st week.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"74683451047","text":"import csv\nimport time\nimport lib\nimport gsheet.process\n\nif __name__ == '__main__':\n print(\"WINA IDX is starting...\")\n\n bot, tele_chat_ids, tele_log_id = lib.get_tele_bot()\n enable_signal, enable_buy, enable_sell, sell_delay, dir_path = lib.get_env()\n\n try:\n result = lib.get_result()\n \n if isinstance(result, str):\n print(result)\n else:\n # Export signal to google sheet\n gsheet.process.write(result)\n \n list_order = []\n for row in result:\n emiten = row[0]\n signal_date = row[1]\n buy_price = row[2]\n take_profit = row[3]\n cut_loss = row[4]\n\n # Save signal history\n with open(f\"{dir_path}\\\\signals\\\\history.csv\", 'a', newline='', encoding='utf-8') as file:\n writer = csv.writer(file) #this is the writer object\n writer.writerow([emiten, signal_date, buy_price, take_profit, cut_loss]) #this is the data\n file.close() \n\n msg = \"💌 Rekomendasi WINA IDX \\(\" + signal_date + \"\\)\\n\\n*Buy $\" + emiten + \"\\nBuy @\" + buy_price + \"\\nTake Profit @\" + take_profit + \"\\nCutloss @\" + cut_loss + \"*\\n\\n_Disclaimer ON\\. DYOR\\._\"\n print(msg)\n\n # Send signal to telegram\n if enable_signal == \"1\":\n lib.send_msg_v2(bot, tele_chat_ids, msg)\n\n # Input order parameters for auto order\n list_order.append(lib.data_order(emiten, buy_price, take_profit, cut_loss))\n\n # Perform auto order buy\n if enable_buy == \"1\":\n t1 = time.time()\n\n # Async buy\n lib.async_order(\"buy\", list_order, bot)\n\n t2 = time.time()\n diff = t2 -t1\n print(\"Processing auto-buy order takes: \" + str(round(diff, 2)) + \" secs.\")\n lib.send_log(bot, tele_log_id, lib.LOG)\n lib.LOG = []\n\n # Perform auto order sell\n if enable_sell == \"1\":\n print('Wait 1 hour to create auto sell order')\n time.sleep(int(sell_delay))\n\n t1 = time.time()\n\n # Async sell\n lib.async_order(\"sell\", list_order, bot)\n\n t2 = time.time()\n diff = t2 -t1\n print(\"Processing auto-sell order takes: \" + str(round(diff, 2)) + \" secs.\")\n lib.send_log(bot, tele_log_id, lib.LOG)\n except Exception as error:\n print(error)\n lib.error_log(bot, tele_log_id)\n\n print(\"Done.\")\n\n","repo_name":"gammarinaldi/wina_idx","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"27411999847","text":"from displayarray import display\nimport numpy as np\nimport random\n\n\ndef lerp(a, b, x):\n \"linear interpolation\"\n return a + x * (b - a)\n\n\ndef fade(t):\n \"6t^5 - 15t^4 + 10t^3\"\n return 6 * t**5 - 15 * t**4 + 10 * t**3\n\n\ndef gradient(h, x, y):\n \"grad converts h to the right gradient vector and return the dot product with (x,y)\"\n vectors = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])\n g = vectors[h % 4]\n return g[:, :, 0] * x + g[:, :, 1] * y\n\n\ndef perlin(x, y, seed=0):\n # permutation table\n np.random.seed(seed)\n p = np.arange(256, dtype=int)\n np.random.shuffle(p)\n p = np.stack([p, p]).flatten()\n # coordinates of the top-left\n xi, yi = x.astype(int), y.astype(int)\n # internal coordinates\n xf, yf = x - xi, y - yi\n # fade factors\n u, v = fade(xf), fade(yf)\n # noise components\n n00 = gradient(p[p[xi] + yi], xf, yf)\n n01 = gradient(p[p[xi] + yi + 1], xf, yf - 1)\n n11 = gradient(p[p[xi + 1] + yi + 1], xf - 1, yf - 1)\n n10 = gradient(p[p[xi + 1] + yi], xf - 1, yf)\n # combine noises\n x1 = lerp(n00, n10, u)\n x2 = lerp(n01, n11, u) # FIX1: I was using n10 instead of n01\n return lerp(x1, x2, v) # FIX2: I also had to reverse x1 and x2 here\n\n\ni = 0\n\n\ndef arr_pnoise(arr):\n global i\n shape = arr.shape[0:2]\n freq = 75\n lin = [np.linspace(0, freq, s, endpoint=False) for s in shape]\n x, y = np.meshgrid(lin[0], lin[1])\n n = perlin(x, y, seed=i) / 2 + arr\n n_min = np.min(n)\n n_max = np.max(n)\n n_r = n_max - n_min\n n_out = (n - n_min) / n_r\n i += 1\n return n_out\n\n\narr = np.random.normal(0.5, 0.1, (100, 100))\narr = np.zeros((100, 100))\n\n\ndef custom_l1_regularization(arr, noise, regularization_strength=0.1):\n # Flatten the noise array\n # flattened_noise = noise.flatten()\n\n # Sort the flattened noise in descending order\n # sorted_noise = np.sort(np.abs(flattened_noise))[::-1]\n\n # Calculate the threshold to retain a specific total activation\n # threshold = sorted_noise[int(regularization_strength * len(sorted_noise))]\n\n # Set values below the threshold to 0\n regularized_noise = np.where(\n np.abs(arr * 0.5 + noise) >= 1.0 - regularization_strength, 1.0, 0.0\n )\n\n return regularized_noise\n\n\narr2 = np.copy(arr)\nwith display(arr) as displayer:\n while displayer:\n arr2[:] = arr_pnoise(arr2)\n arr[:] = custom_l1_regularization(arr, arr2)\n","repo_name":"SimLeek/research-stuff","sub_path":"pnoise.py","file_name":"pnoise.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21135003141","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport re\nimport nltk\nimport string\npd.options.mode.chained_assignment = None\ndataframe = pd.read_csv('book_review.csv').drop_duplicates().reset_index(drop=True)\ndf = dataframe[[\"review_text\"]]\ndf[\"review_text\"] = df[\"review_text\"].astype(str)\ndataframe.head()\n\n\n# In[2]:\n\n\nlist(dataframe.columns)\n\n\n# In[3]:\n\n\ndf.shape\n\n\n# In[4]:\n\n\ndf[\"text_lower\"] = df[\"review_text\"].str.lower()\ndf.head()\n\n\n# In[5]:\n\n\ndf.size\n\n\n# In[6]:\n\n\ndf.shape\n\n\n# In[7]:\n\n\nlist(df.columns)\n\n\n# In[8]:\n\n\nimport spacy\n\n\n# In[9]:\n\n\nPUNCT_TO_REMOVE = string.punctuation\ndef remove_punctuation(text_lower):\n \"\"\"custom function to remove the punctuation\"\"\"\n return text_lower.translate(str.maketrans('', '', PUNCT_TO_REMOVE))\n\ndf[\"text_wo_punct\"] = df[\"text_lower\"].apply(lambda text_lower: remove_punctuation(text_lower))\ndf.head()\n\n\n# In[10]:\n\n\nfrom nltk.corpus import stopwords\n\n\n# In[11]:\n\n\nstopwords\n\n\n# In[12]:\n\n\nnltk.download('stopwords')\n\n\n# In[13]:\n\n\nstopwords.words('English')\n\n\n# In[14]:\n\n\n\", \".join(stopwords.words('english'))\n\n\n# In[15]:\n\n\nSTOPWORDS = set(stopwords.words('english'))\ndef remove_stopwords(text):\n \"\"\"custom function to remove the stopwords\"\"\"\n return \" \".join([word for word in str(text).split() if word not in STOPWORDS])\n\ndf[\"text_wo_stop\"] = df[\"text_wo_punct\"].apply(lambda text: remove_stopwords(text))\ndf.head()\n\n\n# In[16]:\n\n\nfrom collections import Counter\ncnt = Counter()\nfor text in df[\"text_wo_stop\"].values:\n for word in text.split():\n cnt[word] += 1\n \ncnt.most_common(10)\n\n\n# In[17]:\n\n\nFREQWORDS = set([w for (w, wc) in cnt.most_common(10)])\ndef remove_freqwords(text):\n \"\"\"custom function to remove the frequent words\"\"\"\n return \" \".join([word for word in str(text).split() if word not in FREQWORDS])\n\ndf[\"text_wo_stopfreq\"] = df[\"text_wo_stop\"].apply(lambda text: remove_freqwords(text))\ndf.head()\n\n\n# In[18]:\n\n\nn_rare_words = 10\nRAREWORDS = set([w for (w, wc) in cnt.most_common()[:-n_rare_words-1:-1]])\ndef remove_rarewords(text_wo_stopfreq):\n \"\"\"custom function to remove the rare words\"\"\"\n return \" \".join([word for word in str(text_wo_stopfreq).split() if word not in RAREWORDS])\n\ndf[\"text_wo_stopfreqrare\"] = df[\"text_wo_stopfreq\"].apply(lambda text_wo_stopfreq: remove_rarewords(text_wo_stopfreq))\ndf.head()\n\n\n# In[19]:\n\n\nfrom nltk.stem.porter import PorterStemmer\n\n# Drop the four columns \ndf.drop([\"text_wo_stopfreq\", \"text_lower\", \"text_wo_punct\",\"text_wo_stop\"], axis=1, inplace=True) \n\nstemmer = PorterStemmer()\ndef stem_words(text_wo_stopfreqrare):\n return \" \".join([stemmer.stem(word) for word in text_wo_stopfreqrare.split()])\n\ndf[\"text_stemmed\"] = df[\"text_wo_stopfreqrare\"].apply(lambda text_wo_stopfreqrare: stem_words(text_wo_stopfreqrare))\ndf.head()\n\n\n# In[20]:\n\n\nnltk.download('wordnet')\n\n\n# In[21]:\n\n\nfrom nltk.stem import WordNetLemmatizer\n\nlemmatizer = WordNetLemmatizer()\ndef lemmatize_words(text_stemmed):\n return \" \".join([lemmatizer.lemmatize(word) for word in text_stemmed.split()])\n\ndf[\"text_lemmatized\"] = df[\"text_stemmed\"].apply(lambda text_stemmed: lemmatize_words(text_stemmed))\ndf.head()\n\n\n# In[22]:\n\n\ndf.head(100)\n\n\n# In[23]:\n\n\n# removings urls, there are no emojis and emoticons\n\ndef remove_urls(text_lemmatized):\n url_pattern = re.compile(r'https?://\\S+|www\\.\\S+')\n return url_pattern.sub(r'', text_lemmatized)\n\ndf[\"text_url_rmv\"] = df[\"text_lemmatized\"].apply(lambda text_lemmatized: remove_urls(text_lemmatized))\ndf.head()\n\n\n# In[24]:\n\n\n#removing tags\n\ndef remove_html(text_url_rmv):\n html_pattern = re.compile('<.*?>')\n return html_pattern.sub(r'', text_url_rmv)\n\ndf[\"text_tags_rmv\"] = df[\"text_url_rmv\"].apply(lambda text_url_rmv: remove_html(text_url_rmv))\ndf.head()\n\n\n# In[25]:\n\n\n#spelling check\nfrom spellchecker import SpellChecker\n\nspell = SpellChecker()\ndef correct_spellings(text_tags_rmv):\n corrected_text = []\n misspelled_words = spell.unknown(text_tags_rmv)\n for word in str(text_tags_rmv).split():\n if word in misspelled_words:\n corrected_text.append(spell.correction(word))\n else:\n corrected_text.append(word)\n return \" \".join(corrected_text)\n\ndf[\"Final_text\"] = df[\"text_tags_rmv\"].apply(lambda x: correct_spellings(x))\n\n\n# In[26]:\n\n\nlist(df.columns)\n\n\n# In[27]:\n\n\ndf.drop(['review_text','text_wo_stopfreqrare','text_stemmed','text_lemmatized','text_url_rmv','text_tags_rmv'], axis=1, inplace=True)\ndf.head()\n\n\n# In[28]:\n\n\n#calculating polarity\n\nfrom textblob import TextBlob\n\ndef getSubjectivity(Final_text):\n return TextBlob(Final_text).sentiment.subjectivity\n \ndef getPolarity(Final_text):\n return TextBlob(Final_text).sentiment.polarity\n\ndf ['polarity'] = df['Final_text'].apply(getPolarity)\ndf['subjectivity'] = df['Final_text'].apply(getSubjectivity)\n\ndef getAnalysis(polarity):\n if polarity <= 0.01:\n return 'Negative'\n elif polarity >= 0.01:\n return 'Positive'\n else:\n return 'Neutral'\n \ndf['Analysis_labels'] = df['polarity'].apply(lambda x: getAnalysis(x))\n \n\n\n# In[29]:\n\n\ndf.head(100)\n\n\n# In[30]:\n\n\ndataset=df[['Final_text','polarity','Analysis_labels']]\ndataset.head()\n\n\n# In[31]:\n\n\ndataset.Analysis_labels.unique()\n\n\n# # support vector machine\n\n# In[32]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\ndf0 =dataset[dataset.Analysis_labels=='Positive']\ndf1 =dataset[dataset.Analysis_labels=='Negative']\ndf2 =dataset[dataset.Analysis_labels=='Neutral']\ndf0.head()\n\n\n# In[33]:\n\n\n#plt.scatter(df0['Final_text'],df0['Analysis_labels'],colors='green')\n#plt.scatter(df1['Analysis_labels'])\n\n\n# In[34]:\n\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport time\nfrom sklearn import svm\nfrom sklearn.metrics import classification_report\nvectorizer = TfidfVectorizer(min_df = 5,\n max_df = 0.8,\n sublinear_tf = True,\n use_idf = True)\n\n\n# In[35]:\n\n\nfrom sklearn.model_selection import train_test_split\nx = vectorizer.fit_transform(dataset['Final_text'])\ny = vectorizer.transform(dataset['Analysis_labels'])\n\n\n# In[36]:\n\n\nx\n\n\n# In[37]:\n\n\ny=dataset['Analysis_labels']\n\n\n# In[38]:\n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2,random_state=5)\n\n\n# In[39]:\n\n\nx_train.shape\n\n\n# In[40]:\n\n\nfrom sklearn import svm\nfrom sklearn.svm import SVC\nmodel = SVC(C=70,kernel='linear',gamma='auto')\n\n\n# In[41]:\n\n\nmodel.fit(x_train, y_train)\n\n\n# In[42]:\n\n\nmodel.score(x_test, y_test)\n\n\n# In[43]:\n\n\nimport pickle\npickle.dump(model, open('model.pkl','wb'))\n\nmodel = pickle.load(open('model.pkl','rb'))\n\n\n# In[44]:\n\n\nreview = \"\"\"SUPERB, I AM IN LOVE IN THIS book\"\"\"\nreview_vector = vectorizer.transform([review]) # vectorizing\nprint(model.predict(review_vector))\n\n\n# In[45]:\n\n\nimport joblib\njoblib.dump(vectorizer,'model_vectorizer.pkl')\n\nobject = pd.read_pickle(r'model.pkl')\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"amit807/sentimental-analysis","sub_path":"final/svm modelling Amazon data.py","file_name":"svm modelling Amazon data.py","file_ext":"py","file_size_in_byte":6953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28030371604","text":"import sys\n\n\ndef main(argv=None) -> int: # type: ignore\n \"\"\"Drive the app.\"\"\"\n argv = [] if argv is None else argv\n return len(argv)\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","repo_name":"sthagen/minimal-python-starter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"41141418149","text":"import matplotlib.pyplot as plt\nimport csv\n\n\n# Function to read data points from a CSV file\ndef read_data_from_csv(file_name):\n data_points = []\n with open(file_name, \"r\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for row in csv_reader:\n x = float(row[\"x\"])\n y = float(row[\"y\"])\n data_points.append([x, y])\n return data_points\n\n\n# Function to draw the scatter plot\ndef draw_plot(data_points, centroids, assignments):\n # Prepare the data for plotting\n x = [point[0] for point in data_points]\n y = [point[1] for point in data_points]\n\n # Plot the data points\n plt.scatter(x, y, color=\"blue\", label=\"Data Points\")\n\n # Plot the centroids with a plus symbol\n centroids_x = [centroid[0] for centroid in centroids]\n centroids_y = [centroid[1] for centroid in centroids]\n plt.scatter(centroids_x, centroids_y, marker=\"+\", color=\"red\", label=\"Centroids\")\n\n # Color the data points based on their assigned centroid\n colors = [\n \"blue\",\n \"green\",\n \"red\",\n \"cyan\",\n \"magenta\",\n \"yellow\",\n \"black\",\n \"orange\",\n \"purple\",\n \"gray\",\n ]\n for i, assigned_points in enumerate(assignments):\n for point in assigned_points:\n plt.scatter(point[0], point[1], color=colors[i])\n\n # Add labels and title to the plot\n plt.xlabel(\"X\")\n plt.ylabel(\"Y\")\n plt.title(\"K-Means Clustering\")\n\n # Add legend to the plot\n plt.legend()\n\n # Show the plot\n plt.show()\n","repo_name":"Roodaki/Kmeans-Clustering-Assignment-Model","sub_path":"IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"24894132839","text":"import fnmatch\nimport mimetypes\nimport os\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom arcutils.colorize import printer\n\n\nclass Command(BaseCommand):\n\n help = (\n 'Check for unused templates. '\n 'This can only provide a HINT at templates that MIGHT be unused.'\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n 'where', nargs='*', default=['.'],\n help='Where to look for usage of templates. '\n 'Multiple directories can be specified. '\n 'Defaults to the current directory.'\n )\n parser.add_argument(\n '-s', '--source', default='.',\n help='Where to find templates to check for usage. '\n 'Defaults to the current directory.'\n )\n parser.add_argument(\n '-e', '--exclude', nargs='*',\n default=[\n 'search',\n ],\n help='Template subdirectories to exclude. '\n 'Multiple subdirectories can be specified. '\n 'Usually, these will correspond to app names.'\n )\n parser.add_argument(\n '--ignore-dirs', nargs='*',\n default=[\n '.*',\n '*.dist-info',\n '*.egg-info',\n '__pycache__',\n 'build',\n 'dist',\n 'node_modules',\n 'pip',\n 'static',\n 'venv',\n ],\n help='Do not look for templates or check for their usage in these directories.'\n )\n parser.add_argument(\n '--ignore-files', nargs='*',\n default=[\n '.*',\n 'CHANGELOG*',\n 'README*',\n '*.mo',\n '*.po',\n '*.so',\n ],\n help='Skip these files when checking for template usage.'\n )\n parser.add_argument('-d', '--debug', action='store_true', default=False)\n\n def handle(self, *args, **options):\n self.debug = options['debug']\n self.source = os.path.normpath(os.path.abspath(options['source']))\n self.where = [os.path.normpath(os.path.abspath(w)) for w in options['where']]\n self.exclude = options['exclude']\n self.ignore_dirs = options['ignore_dirs']\n self.ignore_files = options['ignore_files']\n self.all_files = self.get_files_to_check(self.where)\n\n source_dirs = self.get_source_dirs(self.source)\n source_files = self.get_source_files(source_dirs)\n unused = self.find_unused(source_files)\n num_unused = len(unused)\n\n if unused:\n s = '' if num_unused == 1 else 's'\n printer.warning('Found', num_unused, 'template{s} that MAY be unused:'.format(s=s))\n for entry in unused:\n full_path, short_path, base_name = entry\n print(os.path.relpath(full_path, self.source))\n printer.warning('NOTE: You CANNOT simply remove the templates listed above.')\n printer.warning('NOTE: You MUST check manually to ensure they are actually unused.')\n else:\n printer.success('No unused templates found')\n\n def find_unused(self, paths):\n unused = []\n for entry in paths:\n full_path, short_path, base_name = entry\n if self.debug:\n printer.warning('Looking for usage of', full_path)\n if self.is_unused(short_path):\n unused.append(entry)\n return unused\n\n def is_unused(self, short_path):\n if self.is_excluded(short_path):\n return False\n for file_name in self.all_files:\n with open(file_name, encoding='utf-8') as fp:\n try:\n contents = fp.read()\n except UnicodeDecodeError:\n printer.error('Could not read file:', file_name, '(skipping)')\n if short_path in contents:\n return False\n return True\n\n def get_files_to_check(self, where):\n files = []\n for dir_ in where:\n if not os.path.isdir(dir_):\n raise NotADirectoryError(dir_)\n sub_dirs = []\n for base_name in os.listdir(dir_):\n full_path = os.path.join(dir_, base_name)\n if os.path.isfile(full_path):\n if not self.is_ignored_file(full_path):\n files.append(full_path)\n elif os.path.isdir(full_path):\n if not self.is_ignored_dir(full_path):\n sub_dirs.append(full_path)\n if sub_dirs:\n files.extend(self.get_files_to_check(sub_dirs))\n return files\n\n def get_source_dirs(self, where):\n dirs = []\n for base_name in os.listdir(where):\n full_path = os.path.join(where, base_name)\n skip = (\n not os.path.isdir(full_path) or\n self.is_ignored_dir(full_path)\n )\n if not skip:\n if base_name == 'templates':\n dirs.append(full_path)\n else:\n dirs.extend(self.get_source_dirs(full_path))\n return dirs\n\n def get_source_files(self, template_dirs):\n files = []\n for dir_ in template_dirs:\n for base_name in os.listdir(dir_):\n full_path = os.path.join(dir_, base_name)\n if os.path.isdir(full_path):\n files.extend(self.get_source_files([full_path]))\n elif os.path.isfile(full_path):\n short_path = os.path.relpath(full_path, os.path.dirname(dir_))\n d, *rest = os.path.split(short_path)\n if d == 'templates':\n short_path = os.path.join(*rest)\n files.append((full_path, short_path, base_name))\n return files\n\n def is_ignored_dir(self, full_path):\n if full_path in (settings.MEDIA_ROOT, settings.STATIC_ROOT):\n if self.debug:\n printer.warning('Ignoring media root', full_path)\n return True\n for dir_ in self.where:\n if full_path == os.path.join(dir_, 'media'):\n if self.debug:\n printer.warning('Ignoring top level media directory', full_path)\n return True\n base_name = os.path.basename(full_path)\n return any(fnmatch.fnmatch(base_name, p) for p in self.ignore_dirs)\n\n def is_ignored_file(self, full_path):\n base_name = os.path.basename(full_path)\n type_, _ = mimetypes.guess_type(base_name)\n name, ext = os.path.splitext(base_name)\n included = (\n (type_ is None and ext in ['.cfg', '.ini', '.mk', '.yml', '.yaml']) or\n (type_ is None and base_name.startswith('Makefile')) or\n (type_ is not None and type_.startswith('text/')) or\n (type_ is not None and type_ == 'application/javascript') or\n (type_ is not None and type_ == 'application/json')\n )\n # XXX: Special case\n if 'bpython/test/fodder/encoding_latin1.py' in full_path:\n included = False\n if not included:\n if self.debug:\n printer.warning('Ignoring file', full_path, 'with MIME type', type_)\n return True\n return any(fnmatch.fnmatch(base_name, p) for p in self.ignore_files)\n\n def is_excluded(self, short_path):\n app_dir, *_ = os.path.split(short_path)\n return any(fnmatch.fnmatch(app_dir, p) for p in self.exclude)\n","repo_name":"PSU-OIT-ARC/django-arcutils","sub_path":"arcutils/management/commands/findunusedtemplates.py","file_name":"findunusedtemplates.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"9741666916","text":"import Stack\n\nclass Queue2stacks:\n\n def __init__(self):\n self.stack1 = Stack.Stack()\n self.head = self.stack1.top\n self.stack2 = Stack.Stack()\n self.tail = self.stack2.top\n\n # isEmpty\n def is_empty(self):\n return (self.stack1.top == None) and (self.stack2.top == None)\n # enqueue\n def enqueue(self, data):\n self.stack1.push(data)\n print(self)\n\n # dequeue\n def dequeue(self):\n # if stack2 is empty\n if not self.stack2.top: \n # while stack1 is not empty\n while self.stack1.top:\n self.stack2.push(self.stack1.pop())\n r = self.stack2.pop()\n print(f'{self} --> {r}')\n return r\n\n def __str__(self):\n\n def lister(stack):\n # make lst O(n)\n lst = []\n # traverse through nodes to make a list\n pointer = stack.top\n while pointer:\n lst.append(pointer.data)\n pointer = pointer.next_node\n return lst\n # bad design it makes this list for every push and pop worest case O(n*n)\n # we could use dynamic programing like memoization and save it to a list to be recolled later \n st1 = lister(self.stack1)\n st1.reverse()\n st2 = lister(self.stack2)\n st2.reverse()\n return f'stack1: {st1}, stack2: {st2}'\n \ndef main():\n\n q2 = Queue2stacks()\n q2.enqueue(9)\n q2.enqueue(1)\n q2.enqueue(675)\n\n q2.enqueue(637)\n q2.enqueue(2)\n q2.enqueue(37)\n\n q2.dequeue()\n q2.enqueue(5)\n q2.enqueue(7)\n\n q2.dequeue()\n\n \n\n\nif __name__ == \"__main__\":\n main()\n\n \n\n ","repo_name":"kataya1/DataStructures-and-Algorithms","sub_path":"DataStructures/Stack/Queue2stacks.py","file_name":"Queue2stacks.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3010025305","text":"\"\"\"\nprev tensor ref for loop, i.e. RecLayer, specifically \"prev:...\" layer references\n\"\"\"\n\nfrom __future__ import annotations\nfrom returnn.tensor import Tensor\nfrom .. import frontend_layers as rfl\n\n\n__all__ = [\"PrevTensorRef\"]\n\n\nclass PrevTensorRef(Tensor):\n \"\"\"\n Refers to a layer from the previous loop iteration.\n \"\"\"\n\n @classmethod\n def get_prev_ref(cls, *, cur_layer_name_ctx: rfl.Layer, initial: Tensor) -> PrevTensorRef:\n \"\"\"\n Create prev ref.\n \"\"\"\n parent_name_ctx = cur_layer_name_ctx.parent\n prev_tensor_name_ctx = parent_name_ctx.get_child(f\"prev:{cur_layer_name_ctx.name}\")\n if prev_tensor_name_ctx.tensor:\n prev_tensor_ref = prev_tensor_name_ctx.tensor\n assert isinstance(prev_tensor_ref, PrevTensorRef)\n assert prev_tensor_ref.cur_layer_name_ctx is cur_layer_name_ctx\n else:\n prev_tensor_ref = PrevTensorRef(\n name_ctx=prev_tensor_name_ctx, cur_layer_name_ctx=cur_layer_name_ctx, data=initial\n )\n assert prev_tensor_name_ctx.tensor is prev_tensor_ref\n return prev_tensor_ref\n\n def __init__(self, *, name_ctx: rfl.Layer, cur_layer_name_ctx: rfl.Layer, data: Tensor):\n # At the time we instantiate this, cur_layer_name_ctx.tensor probably does not exist yet.\n super().__init__(**data.get_kwargs())\n name_ctx.tensor = self\n self.raw_tensor = name_ctx\n self.cur_layer_name_ctx = cur_layer_name_ctx\n self.raw_tensor.layer_extra_dependencies.append(self.cur_layer_name_ctx)\n\n def assign_new_cur_tensor_name_ctx(self, cur_tensor_name_ctx: rfl.Layer):\n \"\"\"\n Changes self.name_ctx to new name_ctx.\n \"\"\"\n self.raw_tensor.layer_extra_dependencies.remove(self.cur_layer_name_ctx)\n prev_layer_name = f\"prev:{cur_tensor_name_ctx.name}\"\n assert prev_layer_name not in cur_tensor_name_ctx.parent.children\n prev_layer_name_ctx = cur_tensor_name_ctx.parent.get_child(prev_layer_name)\n prev_layer_name_ctx.move_tensor_here(self)\n assert self.raw_tensor is prev_layer_name_ctx\n self.cur_layer_name_ctx = cur_tensor_name_ctx\n self.raw_tensor.layer_extra_dependencies.append(self.cur_layer_name_ctx)\n","repo_name":"rwth-i6/returnn","sub_path":"returnn/tf/frontend_layers/prev_tensor_ref.py","file_name":"prev_tensor_ref.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"53"}
+{"seq_id":"7340169305","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport os\nimport linecache\nroot = input('please input the dir:')#get txt file\nfile_names = os.listdir(root)\n\nfile_ob_list = []\nfor file_name in file_names:\n fileob = root + '/' + file_name\n file_ob_list.append(fileob)\n \nimport random\nte = [] \ntr = []\nte = random.sample(file_ob_list, int(0.3*(len(file_ob_list)))) #Randomly assign 30 percent of the test set and 70 percent of the training set\nfor testData in te: \n file_ob_list.remove(testData)\ntr = file_ob_list \n\nfrom function import RoundSampleSplit\ntrain_data,train_data_num=RoundSampleSplit(tr,1024,10,1)\n#print(train_data_num)\ntest_data,test_data_num=RoundSampleSplit(te,1024,1,0)\n\nfrom function import NormalizeMult\ntrain_data,train_nom=NormalizeMult(train_data)\ntest_data,test_nom=NormalizeMult(test_data)\n\nfrom function import BasisFunIdent\nimport numpy as np\nHB_all=[]\nHB=[]\nfor i in train_data:#get H and B from train set\n x=np.arange(0,2*np.pi,2*np.pi/1024)\n y = np.array(i)\n Hb,HBbasis=BasisFunIdent(x,y,2*np.pi/1024,3,3)\n HB.append(HBbasis)\n HB_all.append(Hb)\n#print(HB_all)\n#print(HB)\n\nHBt=[]\nfor i in test_data:#get H and B from test set\n x=np.arange(0,2*np.pi,2*np.pi/1024)\n y = np.array(i)\n _,HBbasis=BasisFunIdent(x,y,2*np.pi/1024,3,3)\n HBt.append(HBbasis)\n\nbasis=[]\nfor i in HB:#get basic function from training set\n if len(i)==3:#The case of the three basis functions \n x1=np.arange(0,2*i[0][1],2*np.pi/1024)\n Y1=i[0][0]*np.sin(np.pi/i[0][1]*x1)\n x2=np.arange(0,2*i[1][1],2*np.pi/1024)\n Y2=i[1][0]*np.sin(np.pi/i[1][1]*x2)\n x3=np.arange(0,2*i[2][1],2*np.pi/1024)\n Y3=i[2][0]*np.sin(np.pi/i[2][1]*x3) \n x1=list(x1)\n x2=list(x2)\n x3=list(x3)\n Y1=list(Y1)\n Y2=list(Y2)\n Y3=list(Y3) \n x_tr=[]\n for j in range(len(Y1)+len(Y2)+len(Y3)):\n if j<=(len(Y1)-1):\n x_tr.append(Y1[j])\n elif j>(len(Y1)-1) and j<=(len(Y1)+len(Y2)-1):\n x_tr.append(Y2[j-len(Y1)])\n elif j>(len(Y1)+len(Y2)) and j<=(len(Y1)+len(Y2)+len(Y3)-1):\n x_tr.append(Y3[j-len(Y1)-len(Y2)]) \n if len(x_tr)<=1024:\n x_tr=x_tr+(1024-len(x_tr))*x_tr[0:1]\n else:\n x_tr=x_tr[0:1024] \n basis.append(x_tr) \n \n elif len(i)==2:#The case of the two basis functions\n x1=np.arange(0,2*i[0][1],2*np.pi/1024)\n Y1=i[0][0]*np.sin(np.pi/i[0][1]*x1)\n x2=np.arange(0,2*i[1][1],2*np.pi/1024)\n Y2=i[1][0]*np.sin(np.pi/i[1][1]*x2) \n x1=list(x1)\n x2=list(x2) \n Y1=list(Y1)\n Y2=list(Y2) \n x_tr=[]\n for j in range(len(Y1)+len(Y2)):\n if j<=(len(Y1)-1):\n x_tr.append(Y1[j])\n elif j>(len(Y1)-1) and j<=(len(Y1)+len(Y2)-1):\n x_tr.append(Y2[j-len(Y1)]) \n if len(x_tr)<=1024:\n x_tr=x_tr+(1024-len(x_tr))*x_tr[0:1]\n else:\n x_tr=x_tr[0:1024]\n basis.append(x_tr)\n \n elif len(i)==1:#The case of the one basis function\n x_tr=[]\n x1=np.arange(0,2*i[0][1],2*np.pi/1024)#[:,np.newaxis]\n Y1=i[0][0]*np.sin(np.pi/i[0][1]*x1)\n for i in range(len(Y1)):\n x_tr.append(Y1[i])\n if len(x_tr)<=1024:\n x_tr=x_tr+(1024-len(x_tr))*x_tr[0:1]\n else:\n x_tr=x_tr[0:1024] \n basis.append(x_tr) \nbasis=np.array(basis)\nbasis1=[]\nfor i in basis:\n x111=[]\n for j in i: \n x111.append([j])\n basis1.append(x111)\nbasis1=np.array(basis1)\n\nbasist=[]\nfor k in HBt:#get basic function of testing set\n if len(k)==3:#The case of the three basis functions \n x11=np.arange(0,2*k[0][1],2*np.pi/1024)\n Y11=k[0][0]*np.sin(np.pi/k[0][1]*x11)\n x22=np.arange(0,2*k[1][1],2*np.pi/1024)\n Y22=k[1][0]*np.sin(np.pi/k[1][1]*x22)\n x33=np.arange(0,2*k[2][1],2*np.pi/1024)\n Y33=k[2][0]*np.sin(np.pi/k[2][1]*x33) \n x11=list(x11)\n x22=list(x22)\n x33=list(x33)\n Y11=list(Y11)\n Y22=list(Y22)\n Y33=list(Y33) \n x_te=[]\n for l in range(len(Y11)+len(Y22)+len(Y33)):\n if l<=(len(Y11)-1):\n x_te.append(Y11[l])\n elif l>(len(Y11)-1) and l<=(len(Y11)+len(Y22)-1):\n x_te.append(Y22[l-len(Y11)])\n elif l>(len(Y11)+len(Y22)) and l<=(len(Y11)+len(Y22)+len(Y33)-1):\n x_te.append(Y33[l-len(Y11)-len(Y22)])\n if len(x_te)<=1024:\n x_te=x_te+(1024-len(x_te))*x_te[0:1]\n else:\n x_te=x_te[0:1024]\n basist.append(x_te)\n \n elif len(k)==2:#The case of the two basis functions\n x11=np.arange(0,2*k[0][1],2*np.pi/1024)\n Y11=k[0][0]*np.sin(np.pi/k[0][1]*x11)\n x22=np.arange(0,2*k[1][1],2*np.pi/1024)\n Y22=k[1][0]*np.sin(np.pi/k[1][1]*x22) \n x11=list(x11)\n x22=list(x22) \n Y11=list(Y11)\n Y22=list(Y22) \n x_te=[]\n for l in range(len(Y11)+len(Y22)):\n if l<=(len(Y11)-1):\n x_te.append(Y11[l])\n elif l>(len(Y11)-1) and l<=(len(Y11)+len(Y22)-1):\n x_te.append(Y22[l-len(Y11)]) \n if len(x_te)<=1024:\n x_te=x_te+(1024-len(x_te))*x_te[0:1]\n else:\n x_te=x_te[0:1024]\n basist.append(x_te)\n \n elif len(k)==1:#The case of the one basis function\n x11=np.arange(0,2*k[0][1],2*np.pi/1024)\n Y11=k[0][0]*np.sin(np.pi/k[0][1]*x11)\n x11=list(x11)\n Y11=list(Y11)\n x_te=[]\n for l in range(len(Y11)):\n x_te.append(Y11[l])\n if len(x_te)<=1024:\n x_te=x_te+(1024-len(x_te))*x_te[0:1]\n else:\n x_te=x_te[0:1024]\n basist.append(x_te)\nbasist=np.array(basist)\nbasis2=[]\nfor i in basist:\n x112=[]\n for j in i:\n x112.append([j])\n \n basis2.append(x112)\nbasis2=np.array(basis2)\n\nfrom function import RoundPre\nacc_test,acc_train,pre_test,pre_train=RoundPre(basis1,train_data,basis2,test_data,2,48,48,train_nom,test_nom)\n#print(acc_test)\n#print(acc_train)\n#print(pre_test)\n#print(pre_train)\n\n\n\n\n\n\n\n","repo_name":"Cleardumm/Race-roundness-modeling-for-ball-bearing-based-on-KNN-and-CNN","sub_path":"Race roundness modeling for ball bearing based on KNN and CNN_code/main_mdtproject.py","file_name":"main_mdtproject.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17939345073","text":"import nltk\nimport random\nfrom nltk.corpus import movie_reviews, stopwords\nfrom nltk.classify.scikitlearn import SklearnClassifier\nfrom nltk.classify import ClassifierI\n\nfrom statistics import mode\n\nimport pickle\n\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\n\nstop_words = set(stopwords.words(\"English\"))\n# adding unnecessary signs and symbols\nfor i in range(0,256):\n stop_words.add(chr(i))\n\n# category( pos/neg )\ndocuments = []\n\n# pickle this shit\nfor category in movie_reviews.categories():\n for fileid in movie_reviews.fileids(category):\n word_list = list(movie_reviews.words(fileid))\n check_list = []\n for word in word_list:\n if word not in stop_words and not word.isdigit():\n check_list.append(word)\n documents.append((check_list,category))\n\n# print(documents[0])\n\nrandom.shuffle(documents)\n\nall_words = []\n\nfor w in movie_reviews.words():\n all_words.append(w.lower())\n\nall_words = nltk.FreqDist(all_words)\n\nword_features = list(all_words.keys())[:3000]\n\n\ndef find_features(document):\n words = set(document)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n\n return features\n\n\n# print((find_features(movie_reviews.words('neg/cv000_29416.txt'))))\n\nfeaturesets = [(find_features(rev), category) for (rev, category) in documents]\n\ntraining_set = featuresets[:1900]\ntesting_set = featuresets[1900:]\n\nclassifier = nltk.NaiveBayesClassifier.train(training_set)\n\n# classifier_f = open(\"naivebayes.pickle\",\"rb\")\n# classifier = pickle.load(classifier_f)\n# classifier_f.close()\n\n\nprint(\"Original Naive Bayes Algo accuracy percent:\", (nltk.classify.accuracy(classifier, testing_set)) * 100)\n# classifier.show_most_informative_features(15)\n\nMNB_classifier = SklearnClassifier(MultinomialNB())\nMNB_classifier.train(training_set)\nprint(\"MNB_classifier accuracy percent:\", (nltk.classify.accuracy(MNB_classifier, testing_set)) * 100)\n\nBernoulliNB_classifier = SklearnClassifier(BernoulliNB())\nBernoulliNB_classifier.train(training_set)\nprint(\"BernoulliNB_classifier accuracy percent:\", (nltk.classify.accuracy(BernoulliNB_classifier, testing_set)) * 100)\n\nLogisticRegression_classifier = SklearnClassifier(LogisticRegression())\nLogisticRegression_classifier.train(training_set)\nprint(\"LogisticRegression_classifier accuracy percent:\",\n (nltk.classify.accuracy(LogisticRegression_classifier, testing_set)) * 100)\n\nSGDClassifier_classifier = SklearnClassifier(SGDClassifier())\nSGDClassifier_classifier.train(training_set)\nprint(\"SGDClassifier_classifier accuracy percent:\",\n (nltk.classify.accuracy(SGDClassifier_classifier, testing_set)) * 100)\n\n# SVC_classifier = SklearnClassifier(SVC())\n# SVC_classifier.train(training_set)\n# print(\"SVC_classifier accuracy percent:\", (nltk.classify.accuracy(SVC_classifier, testing_set))*100)\n\nLinearSVC_classifier = SklearnClassifier(LinearSVC())\nLinearSVC_classifier.train(training_set)\nprint(\"LinearSVC_classifier accuracy percent:\", (nltk.classify.accuracy(LinearSVC_classifier, testing_set)) * 100)\n\nNuSVC_classifier = SklearnClassifier(NuSVC())\nNuSVC_classifier.train(training_set)\nprint(\"NuSVC_classifier accuracy percent:\", (nltk.classify.accuracy(NuSVC_classifier, testing_set)) * 100)\n\n\nclass VoteClassifier(ClassifierI):\n def __init__(self, *classifiers):\n self.classifiers = classifiers\n\n def classify(self, features):\n votes = []\n for cls in self.classifiers:\n v = cls.classify(features)\n votes.append(v)\n return mode(votes)\n\n def confidence(self, features):\n votes = []\n for cls in self.classifiers:\n v = cls.classify(features)\n votes.append(v)\n choice = votes.count(mode(votes))\n confid = choice / len(votes)\n return confid\n\n\nvoted_classifier = VoteClassifier(classifier,\n MNB_classifier,\n BernoulliNB_classifier,\n LogisticRegression_classifier,\n SGDClassifier_classifier,\n LinearSVC_classifier,\n NuSVC_classifier)\n\nprint(\"voted_classifier accuracy percent:\", (nltk.classify.accuracy(voted_classifier, testing_set)) * 100)\n\nprint(\"Labeled test0 as : \",testing_set[0][1])\nprint(\"Classification test0 : \", voted_classifier.classify(testing_set[0][0]))\nprint(\"Confidence : \", voted_classifier.confidence(testing_set[0][0]))\n\nprint(\"Labeled test1 as : \",testing_set[1][1])\nprint(\"Classification test1: \", voted_classifier.classify(testing_set[1][0]))\nprint(\"Confidence : \", voted_classifier.confidence(testing_set[1][0]))\n\nprint(\"Labeled test2 as : \",testing_set[2][1])\nprint(\"Classification test2: \", voted_classifier.classify(testing_set[2][0]))\nprint(\"Confidence : \", voted_classifier.confidence(testing_set[2][0]))\n\nprint(\"Labeled test3 as : \",testing_set[3][1])\nprint(\"Classification test3: \", voted_classifier.classify(testing_set[3][0]))\nprint(\"Confidence : \", voted_classifier.confidence(testing_set[3][0]))\n","repo_name":"inishchith/quora-sentiment-analysis","sub_path":"classify_me.py","file_name":"classify_me.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"166246072","text":"from collections import defaultdict\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom random import shuffle\nimport scipy.stats as stats\nimport seaborn as sns\nfrom typing import Any, Optional, Iterable\n\n\nUSED_STUFFED_IN_PLOTS = True\n\n\ndef get_comparison_market_size(districts: int) -> int:\n if districts <= 40:\n msize = 4\n elif districts <= 80:\n msize = 2\n else:\n msize = 1\n return msize\n\n\ndef vote_vector_ensemble_comps(ensemble_transposed: np.ndarray, title: str, pc_thresh: float = 0.01,\n have_actual: bool = True, comp_plans=False, comp_plans_vectors: list[np.ndarray] = [],\n comp_plans_names: list[str] = [], comp_plans_colors: list[str] = [],\n comp_plans_pnums: list[bool] = [], fill_color=None, h_line_label: str = '',\n y_axis_label: str = '') -> Any:\n # PURPOSE: allow us to include multiple plans for comparison\n #\n # INPUTS\n # ensemble: (nDistrict x nPlan) array of values. MUST BE SORTED WITHIN EACH COLUMN\n # title: string for title\n #\n # OPTIONAL INPUTS [def/type/[default value] ]\n # pc_thresh: quantile markers for violin plots (e.g.: 0.01 means 1% and 99%)\n # have_actual: Does ensemble include data assoc. with an exacted plan? \n # If so, assume FIRST COLUMN is enacted/[True]\n # comp_plans: Do we include a list of plans for comparison?/Bool/[False]\n # comp_plans_vv: vote vectors for plans to compare/\n # list of K numpy arrays, where \"K\"=# of plans provided/[]\n # comp_plans_names: names to use for legend/list of K strings/[]\n # comp_plans_colors: colors for dots/list of K strings/[]\n # comp_plans_pnums: plot district numbers?/ list of K Bool/[]\n # \n\n # for making things look nice\n vbuffer = .04\n\n # get shape of data\n districts, chainlength = np.shape(ensemble_transposed)\n\n # list of integers (for plotting)\n district_numbers = np.arange(districts) + 1\n\n # create Seats/votes curve for enacted plan\n if have_actual:\n vs_actual = np.array(sorted(ensemble_transposed[:, 0]))\n\n # collect distributions of results across ensemble\n samples_to_plot = range(int(0.5 * chainlength), chainlength, 10)\n vs_ensemble = [ensemble_transposed[i, samples_to_plot] for i in range(districts)]\n vs_lower, vs_median, vs_upper = calculate_ensemble_district_statistics(vs_ensemble, pc_thresh)\n\n # identify stuffed, packed, and cracked districts\n # ONLY makes sense if actual plan present\n if have_actual:\n dmin = 0\n dmax = districts\n cracked, packed, stuffed = determine_cracked_packed_stuffed_indices(dmin, dmax, vs_actual, vs_lower, vs_upper)\n else:\n stuffed = []\n cracked = []\n packed = []\n\n # -----------------------------------------------\n\n # Create the plot\n figure = plt.figure(figsize=(6.5, 3.5))\n\n violin_parts = plt.violinplot(vs_ensemble, district_numbers, showextrema=False, widths=0.6,\n quantiles=[[pc_thresh, 1 - pc_thresh] for _ in district_numbers])\n\n if fill_color is not None:\n for vp in violin_parts['bodies']:\n vp.set_facecolor(fill_color)\n vp.set_alpha(0.5)\n\n plt.plot(district_numbers, vs_median, 'bo', markersize=2, label=\"Median of Ensemble\")\n\n marker_size = get_comparison_market_size(districts)\n if have_actual:\n plt.plot(district_numbers, vs_actual, 'ro', markersize=marker_size, label=\"Actual Vote Shares\")\n plt.plot(district_numbers, 0 * district_numbers + 0.5, 'k--', lw=0.75, label=h_line_label)\n\n # ---------------------------------------------\n\n # labelling stuffed districts\n if len(stuffed) > 2:\n smin_loc = 1 + stuffed[0] - 0.5\n smax_loc = 1 + stuffed[-1] + 0.5\n smin_val = vs_actual[stuffed[0]] - vbuffer\n smax_val = vs_actual[stuffed[-1]] + vbuffer\n if USED_STUFFED_IN_PLOTS:\n plt.fill([smin_loc, smax_loc, smax_loc, smin_loc], [smin_val, smin_val, smax_val, smax_val], 'y', alpha=0.3)\n plt.text(0.5 * (smin_loc + smax_loc), smax_val + vbuffer, '\"Stuffing\"',\n **{'ha': 'center', 'weight': 'bold'})\n\n # labelling cracked districts\n if len(cracked) > 2:\n cmin_loc = 1 + cracked[0] - 0.5\n cmax_loc = 1 + cracked[-1] + 0.5\n cmin_val = vs_actual[cracked[0]] - vbuffer\n cmax_val = vs_actual[cracked[-1]] + vbuffer\n plt.fill([cmin_loc, cmax_loc, cmax_loc, cmin_loc], [cmin_val, cmin_val, cmax_val, cmax_val], 'y', alpha=0.3)\n plt.text(0.5 * (cmin_loc + cmax_loc), cmin_val - 2 * vbuffer, '\"Cracking\"',\n **{'ha': 'center', 'weight': 'bold'})\n\n # labelling packed districts\n if len(packed) > 2:\n pmin_loc = 1 + packed[0] - 0.5\n pmax_loc = 1 + packed[-1] + 0.5\n pmin_val = vs_actual[packed[0]] - vbuffer\n pmax_val = vs_actual[packed[-1]] + vbuffer\n plt.fill([pmin_loc, pmax_loc, pmax_loc, pmin_loc], [pmin_val, pmin_val, pmax_val, pmax_val], 'y', alpha=0.3)\n plt.text(0.5 * (pmin_loc + pmax_loc), pmax_val - 2 * vbuffer, '\"Packing\"', **{'ha': 'center', 'weight': 'bold'})\n\n # --------------------------------------------------------- \n\n # \"Comparison Plans\", if applicable\n if comp_plans:\n for i in np.arange(len(comp_plans_vectors)):\n y1 = np.array(sorted(comp_plans_vectors[i]))\n plt.plot(district_numbers, y1, color=comp_plans_colors[i], marker='o', markersize=marker_size, ls='',\n label=comp_plans_names[i])\n\n # Replace 1-n with actual district numbers\n if comp_plans_pnums:\n # Determine if district number should be plotted\n true_pnums = [i1 for i1, x in enumerate(comp_plans_pnums) if x]\n whpnum = true_pnums[0]\n\n # Order of districts for x-axis\n dnumvec = np.argsort(comp_plans_vectors[whpnum])\n\n # Use dnumvec computed above\n dnumstr = [str(x + 1) for x in dnumvec]\n\n plt.xticks(np.arange(len(dnumvec)) + 1, dnumstr)\n else:\n plt.xlim(0, districts + 1)\n\n # Set y axis limits based on data; in particular actual/compaison plans\n if have_actual:\n plt.ylim(vs_actual[0] - vbuffer, vs_actual[-1] + vbuffer)\n elif comp_plans:\n # Get min and max of comparison plans \n ymin = 0.5\n ymax = 0.5\n for i in np.arange(len(comp_plans_vectors)):\n y1 = np.array(sorted(comp_plans_vectors[i]))\n ymin = np.min([y1[0], ymin])\n ymax = np.max([y1[-1], ymax])\n\n plt.ylim(ymin - vbuffer, ymax + vbuffer)\n else:\n plt.ylim(vs_lower[0] - vbuffer, vs_upper[-1] + vbuffer)\n\n plt.xlabel('District Number')\n plt.ylabel(y_axis_label)\n plt.title(title)\n plt.legend(loc=2, fontsize=8)\n plt.tight_layout()\n return figure\n\n\ndef calculate_ensemble_district_statistics(ensemble_transposed: list[list[float]], pc_thresh: float) -> \\\n tuple[list[float], list[float], list[float]]:\n vs_lower = [np.percentile(x, 100 * pc_thresh) for x in ensemble_transposed]\n vs_median = [np.percentile(x, 50) for x in ensemble_transposed]\n vs_upper = [np.percentile(x, 100 * (1 - pc_thresh)) for x in ensemble_transposed]\n return vs_lower, vs_median, vs_upper\n\n\ndef determine_cracked_packed_stuffed_indices(dmin: int, dmax: int, vs_actual: np.ndarray, vs_lower: list[float],\n vs_upper: list[float]) -> tuple[list[int], list[int], list[int]]:\n stuffed = [i for i in range(dmin, dmax) if (vs_upper[i] < vs_actual[i] < .5)]\n cracked = [i for i in range(dmin, dmax) if (vs_lower[i] > vs_actual[i] > .3 and vs_actual[i] < .5)]\n packed = [i for i in range(dmin, dmax) if (vs_actual[i] > vs_upper[i] and vs_actual[i] > .5)]\n return cracked, packed, stuffed\n\n\ndef determine_cracked_packed_stuffed_districts(districts: int, instance_p: np.ndarray, vs_lower: list[float],\n vs_upper: list[float]) -> tuple[list[int], list[int], list[int]]:\n cracked, packed, stuffed = determine_cracked_packed_stuffed_indices(0, districts, np.array(sorted(instance_p)),\n vs_lower, vs_upper)\n sorted_index_to_district = np.argsort(instance_p)\n cracked = [sorted_index_to_district[x] for x in cracked]\n packed = [sorted_index_to_district[x] for x in packed]\n stuffed = [sorted_index_to_district[x] for x in stuffed]\n return cracked, packed, stuffed\n\n\ndef vote_vector_ensemble(ensemble_transposed: np.ndarray, title: str, pc_thresh: float = 0.01,\n have_actual: bool = True, comparison_label: str = \"Actual Vote Shares\",\n display_districts_numbers: bool = True) -> Any:\n # INPUTS\n # ensemble: (nDistrict x nPlan) array of values. MUST BE SORTED WITHIN EACH COLUMN\n # title: string for title\n #\n # OPTIONAL INPUTS [name/def/[default value]\n # pc_thresh: quantile markers for violin plots (e.g.: 0.01 means 1% and 99%)\n # have_actual: Does ensemble include data assoc. with an exacted plan? \n # If so, assume FIRST COLUMN is enacted/[True] \n\n # for making things look nice\n vbuffer = .02\n\n # get shape of data\n districts, chainlength = np.shape(ensemble_transposed)\n\n # list of integers (for plotting)\n seats = np.arange(districts) + 1\n\n # collect distributions of results across ensemble\n samples_to_plot = range(int(0.5 * chainlength), chainlength, 10)\n vs_ensemble = [ensemble_transposed[i, samples_to_plot] for i in range(districts)]\n vs_lower, vs_median, vs_upper = calculate_ensemble_district_statistics(vs_ensemble, pc_thresh)\n\n # create Seats/votes curve for enacted plan\n # identify stuffed, packed, and cracked districts\n # ONLY makes sense if actual plan present\n if have_actual:\n vs_actual = np.array(sorted(ensemble_transposed[:, 0]))\n\n dmin = 0\n dmax = districts\n cracked, packed, stuffed = determine_cracked_packed_stuffed_indices(dmin, dmax, vs_actual, vs_lower, vs_upper)\n else:\n vs_actual = None\n stuffed = []\n cracked = []\n packed = []\n\n # -----------------------------------------------\n\n # Create the plot\n myplot = plt.figure(figsize=(6.5, 3.5))\n\n plt.violinplot(vs_ensemble, seats, showextrema=False, widths=0.6,\n quantiles=[[pc_thresh, 1 - pc_thresh] for _ in seats])\n plt.plot(seats, vs_median, 'bo', markersize=2, label=\"Median of Ensemble\")\n if have_actual:\n marker_size = get_comparison_market_size(districts)\n plt.plot(seats, vs_actual, 'ro', markersize=marker_size, label=comparison_label)\n plt.plot(seats, 0 * seats + 0.5, 'k--', lw=0.75, label=\"Needed to Win\")\n\n # labelling stuffed districts\n if len(stuffed) > 2:\n smin_loc = 1 + stuffed[0] - 0.5\n smax_loc = 1 + stuffed[-1] + 0.5\n smin_val = vs_actual[stuffed[0]] - vbuffer\n smax_val = vs_actual[stuffed[-1]] + vbuffer\n\n if USED_STUFFED_IN_PLOTS:\n plt.fill([smin_loc, smax_loc, smax_loc, smin_loc], [smin_val, smin_val, smax_val, smax_val], 'y', alpha=0.3)\n plt.text(0.5 * (smin_loc + smax_loc), smax_val + vbuffer, '\"Stuffing\"',\n **{'ha': 'center', 'weight': 'bold'})\n\n # labelling cracked districts\n if len(cracked) > 2:\n cmin_loc = 1 + cracked[0] - 0.5\n cmax_loc = 1 + cracked[-1] + 0.5\n cmin_val = vs_actual[cracked[0]] - vbuffer\n cmax_val = vs_actual[cracked[-1]] + vbuffer\n plt.fill([cmin_loc, cmax_loc, cmax_loc, cmin_loc], [cmin_val, cmin_val, cmax_val, cmax_val], 'y', alpha=0.3)\n plt.text(0.5 * (cmin_loc + cmax_loc), cmin_val - 2 * vbuffer, '\"Cracking\"',\n **{'ha': 'center', 'weight': 'bold'})\n\n # labelling packed districts\n if len(packed) > 2:\n pmin_loc = 1 + packed[0] - 0.5\n pmax_loc = 1 + packed[-1] + 0.5\n pmin_val = vs_actual[packed[0]] - vbuffer\n pmax_val = vs_actual[packed[-1]] + vbuffer\n plt.fill([pmin_loc, pmax_loc, pmax_loc, pmin_loc], [pmin_val, pmin_val, pmax_val, pmax_val], 'y', alpha=0.3)\n plt.text(0.5 * (pmin_loc + pmax_loc), pmax_val - 2 * vbuffer, '\"Packing\"', **{'ha': 'center', 'weight': 'bold'})\n\n # Replace 1-n with actual district numbers\n if display_districts_numbers and have_actual:\n # Order of districts for x-axis\n dnumvec = np.argsort(np.array(ensemble_transposed[:, 0]))\n\n # Use dnumvec computed above\n dnumstr = [str(x + 1) for x in dnumvec]\n\n plt.xticks(np.arange(len(dnumvec)) + 1, dnumstr)\n else:\n plt.xlim(0, districts + 1)\n\n if have_actual:\n plt.ylim(vs_actual[0] - vbuffer, vs_actual[-1] + vbuffer)\n else:\n plt.ylim(vs_lower[0] - vbuffer, vs_upper[-1] + vbuffer)\n\n plt.xlabel('District Number')\n plt.ylabel('Democratic vote share')\n plt.title(title)\n plt.legend(loc=2, fontsize=8)\n plt.tight_layout()\n return myplot\n\n\ndef seats_votes_varying_maps_2(ensemble_transposed: np.ndarray, title: str, pc_thresh: float = 0.05) -> Any:\n # for making things look nice\n vbuffer = .02\n\n # get shape of data\n districts, chainlength = np.shape(ensemble_transposed)\n\n # list of integers (for plotting)\n seats = np.arange(districts) + 1\n\n # create Seats/votes curve for enacted plan\n vs_actual = np.array(sorted(ensemble_transposed[:, 0]))\n\n # collect distributions of results across ensemble\n samples_to_plot = range(int(0.5 * chainlength), chainlength, 10)\n vs_ensemble = [ensemble_transposed[ii, samples_to_plot] for ii in range(districts)]\n vs_median = np.array([np.percentile(vse, 50) for vse in vs_ensemble])\n vs_lower = np.array([np.percentile(vse, 100 * pc_thresh) for vse in vs_ensemble])\n vs_upper = np.array([np.percentile(vse, 100 * (1 - pc_thresh)) for vse in vs_ensemble])\n\n # identify stuffed, packed, and cracked districts\n inrange = np.array([ii for ii in range(districts) if vs_upper[ii] > vs_actual[ii] > vs_lower[ii]],\n dtype=np.int32)\n packed = np.array([ii for ii in range(districts) if vs_actual[ii] > vs_upper[ii] and vs_actual[ii] > .5],\n dtype=np.int32)\n stuffed = np.array([ii for ii in range(districts) if vs_upper[ii] < vs_actual[ii] < .5],\n dtype=np.int32)\n cracked = np.array([ii for ii in range(districts) if vs_actual[ii] < vs_lower[ii] and vs_actual[ii] < .5],\n dtype=np.int32)\n\n # -----------------------------------------------\n\n # Create the plot\n myplot = plt.figure(figsize=(6.5, 4.5))\n\n plt.violinplot(vs_ensemble, seats, showextrema=False, widths=0.6,\n quantiles=[[pc_thresh, 1 - pc_thresh] for _ in seats])\n plt.plot(seats, vs_median, 'ko', markersize=2, label=\"Median of Ensemble\")\n plt.scatter(1 + inrange, vs_actual[inrange], s=5, color=\"black\", label='Enacted: in Range')\n plt.scatter(1 + packed, vs_actual[packed], s=8, color=\"red\", label='Enacted: \"Packed\"')\n plt.scatter(1 + cracked, vs_actual[cracked], s=8, color=\"blue\", label='Enacted: \"Cracked\"')\n if USED_STUFFED_IN_PLOTS:\n plt.scatter(1 + stuffed, vs_actual[stuffed], s=8, color=\"orange\", label='Enacted: \"Stuffed\"')\n plt.plot(seats, 0 * seats + 0.5, 'k--', lw=0.75, label=\"Needed to Win\")\n\n plt.xlim(0, districts + 1)\n plt.ylim(vs_actual[0] - vbuffer, vs_actual[-1] + vbuffer)\n\n plt.xlabel('District Number')\n plt.ylabel('Democratic vote share')\n plt.title(title)\n plt.legend(loc=2, fontsize=8)\n plt.tight_layout()\n return myplot\n\n\ndef seats_votes_ensemble(ensemble_transposed: np.ndarray, title: str, statewide: Any = None, have_actual: bool = True) -> Any:\n # INPUTS\n # ensemble: (nDistrict x nPlan) array of values. MUST BE SORTED WITHIN EACH COLUMN\n # title: string for title\n # OPTIONAL INPUTS [name/def/[default value]\n # statewide/ Statewide Democratic vote %. If None, use mean of enacted vote vector/[None]\n # have_actual/Does ensemble include data assoc. with an exacted plan? \n # If so, assume FIRST COLUMN is enacted/[True]\n\n # plot them together in the same figure\n # -------------------------------------------------\n\n myfigure = plt.figure(figsize=(6.5, 5))\n\n plt.subplot(211)\n plot_seats_votes_ensemble(ensemble_transposed, title, statewide)\n\n if have_actual:\n # panel 2\n # -------------------\n plt.subplot(212)\n plot_seats_votes_actual(ensemble_transposed, title, statewide, have_actual)\n\n return myfigure\n\n\ndef plot_seats_votes_ensemble(ensemble_transposed: np.ndarray, title: str, statewide: Any = None) -> None:\n districts, chainlength = np.shape(ensemble_transposed)\n\n # now compute an average seats/votes over many samples\n # ------------------------------------------------\n avg_range = range(int(chainlength / 2), chainlength)\n avg_seatsvotes = 0 * np.array(sorted(ensemble_transposed[:, 0], reverse=True))\n avg_seats = 0\n avg_votes = 0\n for step in avg_range:\n tmp_race_results = np.array(sorted(ensemble_transposed[:, step], reverse=True))\n tmp_seats = np.sum(tmp_race_results > .5)\n tmp_votes = np.mean(tmp_race_results) if statewide is None else statewide\n tmp_seatsvotes = [tmp_votes - r + 0.5 for r in tmp_race_results]\n\n avg_seatsvotes += tmp_seatsvotes\n avg_seats += tmp_seats\n avg_votes += tmp_votes\n\n avg_seatsvotes /= len(avg_range)\n avg_votes /= len(avg_range)\n avg_seats /= len(avg_range)\n\n # Convert to arrays, reflect seats-votes curve about (.5, .5)\n avg_seatsvotes1 = np.array(avg_seatsvotes)\n avg_seatsvotes2 = np.flip(1 - avg_seatsvotes1)\n\n plt.title(title)\n\n # panel 1: the ensemble\n # -------------------\n seats = range(1, districts + 1)\n plt.plot(seats, avg_seatsvotes1, 'b', lw=2, label=\"Democrats\")\n plt.plot(seats, avg_seatsvotes2, 'r', lw=2, label=\"Republicans\")\n plt.fill_between(seats, avg_seatsvotes1, avg_seatsvotes2, where=(avg_seatsvotes1 > avg_seatsvotes2),\n interpolate=True, **{'alpha': .2})\n\n # labeling\n hbuff = 0.25\n vbuff = 0.01\n dpos = [ii for ii in range(districts) if avg_seatsvotes1[ii] > 0.5]\n first = dpos[0]\n start = avg_seatsvotes1[first - 1]\n final = avg_seatsvotes1[first]\n slope = final - start\n hmin = 1 + (first - 1) + (0.5 - start) / slope\n hmid = 1 + (districts - 1) / 2.0\n hmax = hmin + 2 * (hmid - hmin)\n vmax = avg_seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n avg_seatsvotes1[round(hmid - 0.5) - 1] + avg_seatsvotes1[round(hmid + 0.5) - 1])\n vmid = 0.5\n vmin = vmax - 2 * (vmax - vmid)\n plt.plot([hmin - hbuff, hmax + hbuff], [vmid, vmid], '--', lw=2, color=\"green\", label=\"Equal Voteshares\")\n plt.plot([hmid, hmid], [vmin - vbuff, vmax + vbuff], '--', lw=2, color=\"gray\", label=\"Majority Seat\")\n\n # Should \"actual\" result be the location on the curve at the actual statewide percentage?\n # vs. the\n plt.plot([avg_seats + 0.5], [avg_votes], 'bs', lw=2, label=\"Actual Dem. Result\")\n plt.plot([districts - avg_seats + 0.5], [1 - avg_votes], 'rs', label=\"Actual Rep. Result\")\n\n print(\"Vote Needed for Majority (D-R) -- Ensemble: %4.4f\" % (vmax - vmin))\n print(\"Seats at 50%% Voteshare (D-R) -- Ensemble: %4d\" % (hmax - hmin))\n\n # cleaning up\n plt.xlim(0, districts + 1)\n plt.ylim(0.25, 0.75)\n plt.text(hmid, .7, \"Average of \\n Sampled Plans\", **{'va': 'top', 'ha': 'center', 'size': 10, 'weight': 'bold'})\n plt.ylabel(\"Statewide Vote Share\")\n plt.legend(**{'fontsize': 8})\n\n\ndef plot_seats_votes_actual(ensemble_transposed: np.ndarray, title: str, statewide: Any = None, have_actual: bool = True) -> None:\n districts, chainlength = np.shape(ensemble_transposed)\n\n if have_actual:\n # get the actual outcomes\n actuals = np.array(sorted(ensemble_transposed[:, 0], reverse=True))\n actual_seats = np.sum(actuals > .5)\n actual_votes = np.mean(actuals) if statewide is None else statewide\n\n # seats / votes curve, assuming uniform swing\n seatsvotes1 = actual_votes - actuals + 0.5\n\n # apply reflection about (.5, .5)\n seatsvotes2 = np.flip(1 - seatsvotes1)\n else:\n # If None, we just don't plot\n actual_votes = statewide\n\n plt.title(title)\n\n seats = range(1, districts + 1)\n plt.plot(seats, seatsvotes1, 'b', lw=2, label=\"Democrats\")\n plt.plot(seats, seatsvotes2, 'r', lw=2, label=\"Republicans\")\n plt.fill_between(seats, seatsvotes1, seatsvotes2, where=(seatsvotes1 > seatsvotes2), interpolate=True,\n **{'alpha': .2})\n\n # labeling\n dpos = [x for x in range(districts) if seatsvotes1[x] > 0.5]\n first = dpos[0]\n start = seatsvotes1[first - 1]\n final = seatsvotes1[first]\n slope = final - start\n\n hmin = 1 + (first - 1) + (0.5 - start) / slope\n hmid = 1 + (districts - 1) / 2.0\n hmax = hmin + 2 * (hmid - hmin)\n\n vmax = seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n seatsvotes1[round(hmid - 0.5) - 1] + seatsvotes1[round(hmid + 0.5) - 1])\n vmid = 0.5\n vmin = vmax - 2 * (vmax - vmid)\n\n hbuff = 0.25\n vbuff = 0.01\n plt.plot([hmin - hbuff, hmax + hbuff], [vmid, vmid], '--', lw=2, color=\"green\", label=\"Equal Voteshares\")\n plt.plot([hmid, hmid], [vmin - vbuff, vmax + vbuff], '--', lw=2, color=\"gray\", label=\"Majority Seat\")\n plt.plot([actual_seats + 0.5], [actual_votes], 'bs', lw=2, label=\"Actual Dem. Result\")\n plt.plot([districts - actual_seats + 0.5], [1 - actual_votes], 'rs', label=\"Actual Rep. Result\")\n\n print(\"Vote Needed for Majority (D-R) -- Actual: %4.4f\" % (vmax - vmin))\n print(\"Seats at 50%% Voteshare (D-R) -- Actual: %4d\" % (hmax - hmin))\n\n # cleaning up\n plt.xlim(0, districts + 1)\n plt.ylim(0.25, 0.75)\n plt.ylabel(\"Percent Vote Share\")\n plt.xlabel(\"Number of Seats\")\n plt.text(hmid, .7, \"Enacted Plan\", **{'va': 'top', 'ha': 'center', 'size': 10, 'weight': 'bold'})\n plt.legend(**{'fontsize': 8})\n plt.tight_layout()\n\n\ndef plot_seats_votes_actual_inverted(ensemble_transposed: np.ndarray, title: str) -> None:\n districts, chainlength = np.shape(ensemble_transposed)\n\n # get the actual outcomes\n actuals = np.array(sorted(ensemble_transposed[:, 0], reverse=True))\n actual_seats = np.sum(actuals > .5)\n actual_votes = np.mean(actuals)\n\n # seats / votes curve, assuming uniform swing\n seatsvotes1 = actual_votes - actuals + 0.5\n\n # apply reflection about (.5, .5)\n seatsvotes2 = np.flip(1 - seatsvotes1)\n\n plt.title(title)\n\n seats = range(1, districts + 1)\n plt.plot(seatsvotes1, seats, 'b', lw=2, label=\"Democrats\")\n plt.plot(seatsvotes2, seats, 'r', lw=2, label=\"Republicans\")\n #plt.fill_between(seats, seatsvotes1, seatsvotes2, where=(seatsvotes1 > seatsvotes2), interpolate=True,\n # **{'alpha': .2})\n\n # labeling\n dpos = [x for x in range(districts) if seatsvotes1[x] > 0.5]\n first = dpos[0]\n start = seatsvotes1[first - 1]\n final = seatsvotes1[first]\n slope = final - start\n\n hmin = 1 + (first - 1) + (0.5 - start) / slope\n hmid = 1 + (districts - 1) / 2.0\n hmax = hmin + 2 * (hmid - hmin)\n\n vmax = seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n seatsvotes1[round(hmid - 0.5) - 1] + seatsvotes1[round(hmid + 0.5) - 1])\n vmid = 0.5\n vmin = vmax - 2 * (vmax - vmid)\n\n hbuff = 0.25\n vbuff = 0.01\n plt.plot([vmid, vmid], [hmin - hbuff, hmax + hbuff], '--', lw=2, color=\"green\", label=\"Equal Voteshares\")\n plt.plot([vmin - vbuff, vmax + vbuff], [hmid, hmid], '--', lw=2, color=\"gray\", label=\"Majority Seat\")\n plt.plot([actual_votes], [actual_seats + 0.5], 'bs', lw=2, label=\"Actual Dem. Result\")\n plt.plot([1 - actual_votes], [districts - actual_seats + 0.5], 'rs', label=\"Actual Rep. Result\")\n\n # cleaning up\n plt.xlim(0, 1)\n plt.ylim(1, districts + 1)\n plt.xlabel(\"Percent Vote Share\")\n plt.ylabel(\"Number of Seats\")\n plt.text(hmid, .7, \"Enacted Plan\", **{'va': 'top', 'ha': 'center', 'size': 10, 'weight': 'bold'})\n plt.legend(**{'fontsize': 8})\n plt.tight_layout()\n\n\ndef mean_median_distribution(ensemble: np.ndarray, instance: np.ndarray,\n title: str = \"Distribution of Mean-Median Scores\", xlabel: str = None) -> Any:\n mme = np.median(ensemble, axis=1) - np.mean(ensemble, axis=1)\n mmi = np.median(instance) - np.mean(instance)\n\n mmmedian = np.median(mme)\n mmmean = np.mean(mme)\n mmstd = np.std(mme)\n mmbinedges = np.linspace(mmmean - 5 * mmstd, mmmean + 5 * mmstd, 51)\n\n print(\"Percentile Score: %8.6f.\" % (stats.percentileofscore(mme, mmi)))\n\n mmhist, mmedges = np.histogram(mme, bins=mmbinedges)\n\n myfigure = plt.figure(figsize=(6.5, 3.5))\n\n plt.hist(mme, bins=mmbinedges, color=\"xkcd:dark blue\", **{'alpha': 0.3})\n plt.axvline(x=mmmedian, color=\"green\", ls='--', lw=2.5, ymax=0.75, label=\"Ensemble Median\")\n plt.axvline(x=mmi, color=\"purple\", ls='--', lw=2.5, ymax=0.75, label=\"Proposed Districts\")\n plt.xlim(mmmean - 4 * mmstd, mmmean + 4 * mmstd)\n\n plt.ylim(0, np.max(mmhist) * 1.4)\n plt.tick_params(\n axis='y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False) # labels along the bottom edge are off\n plt.legend(loc=\"upper center\")\n plt.xlabel(xlabel)\n plt.ylabel(\"Relative Frequency\")\n plt.title(title)\n\n return myfigure\n\n\ndef mean_median_partisan_bias(ensemble_transposed: np.ndarray, have_actual: bool = True,\n comparison_label: str = \"Enacted Districts\") -> Any:\n # get shape of data\n districts, chainlength = np.shape(ensemble_transposed)\n hmid = 1 + (districts - 1) / 2.0\n\n # space allocation\n majority_vs = np.zeros((2, chainlength))\n number_seats = np.zeros((2, chainlength))\n for j in range(0, chainlength):\n race_results = sorted(ensemble_transposed[:, j], reverse=True)\n mean_voteshare = np.mean(race_results)\n seatsvotes1 = mean_voteshare - np.array(race_results) + 0.5\n seatsvotes2 = np.flip(1 - seatsvotes1)\n\n # What is the percentage nec. for a majority?\n majority_vs[0, j] = seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n seatsvotes1[round(hmid - 0.5) - 1] + seatsvotes1[round(hmid - 0.5) - 1])\n majority_vs[1, j] = seatsvotes2[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n seatsvotes2[round(hmid - 0.5) - 1] + seatsvotes2[round(hmid - 0.5) - 1])\n\n # What is the number of seats you get at 50%?\n number_seats[0, j] = np.sum(seatsvotes1 <= 0.5)\n number_seats[1, j] = np.sum(seatsvotes2 <= 0.5)\n\n # Mean Median\n myfigure = plt.figure(figsize=(6.5, 3.5))\n axes = plt.subplot(121)\n\n plot_mean_median_hist(axes, have_actual, comparison_label, majority_vs[1, :] - majority_vs[0, :])\n\n # Partisan Bias\n plt.subplot(122)\n\n plot_partisan_bias_hist(have_actual, comparison_label, number_seats[0, :] - number_seats[1, :])\n\n plt.tight_layout()\n\n return myfigure\n\n\ndef plot_mean_median_hist(axes, have_actual: bool, comparison_label: str, mean_medians_ensemble: np.ndarray) -> None:\n # things we need to plot\n mvdiff = np.median(mean_medians_ensemble)\n\n # for making it look nice\n vdmin = min(mean_medians_ensemble)\n vdmax = max(mean_medians_ensemble)\n vbinedge_min = np.floor(vdmin)\n vbinedge_max = np.ceil(vdmax)\n vbinbounds = np.arange(vbinedge_min, vbinedge_max + .01, .01)\n vdbuff = (vdmax - vdmin) * .025\n vhist, vedges = np.histogram(mean_medians_ensemble, bins=vbinbounds)\n\n plt.hist(mean_medians_ensemble, bins=vbinbounds, color=\"xkcd:dark blue\", **{'alpha': 0.3})\n\n plt.axvline(x=mvdiff, color=\"green\", ls='--', lw=2.5, ymax=0.75, label=\"Ensemble Median\")\n if have_actual:\n cvdiff = mean_medians_ensemble[0]\n plt.axvline(x=cvdiff, color=\"purple\", ls='--', lw=2.5, ymax=0.75, label=comparison_label)\n\n plt.xlim(vdmin - vdbuff, vdmax + vdbuff)\n axes.xaxis.set_major_formatter(lambda x, pos: format(100 * x, \".0f\"))\n plt.ylim(0, np.max(vhist) * 1.4)\n plt.tick_params(\n axis='y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False) # labels along the bottom edge are off\n plt.xlabel(\"Voteshare Difference for Majority % (R-D)\")\n plt.ylabel(\"Relative Frequency\")\n plt.title('\"Mean-Median\" Score')\n plt.legend(loc=\"upper center\")\n\n\ndef plot_partisan_bias_hist(have_actual: bool, comparison_label: str, partisan_biases_ensemble: np.ndarray) -> None:\n # things we need to plot\n mndiff = np.median(partisan_biases_ensemble)\n\n # for making it look nice\n ndmin = min(partisan_biases_ensemble)\n ndmax = max(partisan_biases_ensemble)\n nbinedge_min = np.floor(ndmin)\n nbinedge_max = np.ceil(ndmax)\n nbinbounds = np.arange(nbinedge_min - 0.5, nbinedge_max + 0.5)\n ndbuff = (ndmax - ndmin) * .01\n nhist, nedges = np.histogram(partisan_biases_ensemble, bins=nbinbounds)\n\n plt.hist(partisan_biases_ensemble, bins=nbinbounds, color=\"xkcd:dark blue\", **{'alpha': 0.3})\n\n plt.axvline(x=mndiff, color=\"green\", ls='--', lw=2.5, ymax=0.75, label=\"Ensemble Median\")\n if have_actual:\n cndiff = partisan_biases_ensemble[0]\n plt.axvline(x=cndiff, color=\"purple\", ls='--', lw=2.5, ymax=0.75, label=comparison_label)\n plt.xlim(ndmin - ndbuff, ndmax + ndbuff)\n plt.ylim(0, np.max(nhist) * 1.4)\n\n if (nbinedge_max - nbinedge_min) <= 12:\n plt.xticks(np.arange(nbinedge_min, nbinedge_max, 2))\n else:\n plt.xticks(np.arange(nbinedge_min, nbinedge_max, 4))\n\n plt.tick_params(\n axis='y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False) # labels along the bottom edge are off\n plt.title('\"Partisan Bias\" Score')\n plt.xlabel(\"Seat Difference at Equal Votes (D-R)\")\n plt.legend(loc=\"upper center\")\n\n\ndef partisan_metrics_histpair(ensemble: np.ndarray, instance: np.ndarray) -> Any:\n # get shape of data\n chainlength, districts = np.shape(ensemble)\n hmid = 1 + (districts - 1) / 2.0\n\n # logic for odd or even numbers of districts\n # odd_number_of_districts = (districts % 2 != 0)\n odd_midindex = round(hmid) - 1\n evl_midindex = round(hmid - 0.5) - 1\n evr_midindex = round(hmid + 0.5) - 1\n\n # information for the instance\n actual_race_results = sorted(instance, reverse=True)\n actual_mean_voteshare = np.mean(actual_race_results)\n actual_seatsvotes1 = actual_mean_voteshare - np.array(actual_race_results) + 0.5\n actual_seatsvotes2 = np.flip(1 - actual_seatsvotes1)\n\n # What is the percentage nec. for a majority?\n actual_majority_vs1 = actual_seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n actual_seatsvotes1[round(hmid - 0.5) - 1] + actual_seatsvotes1[round(hmid - 0.5) - 1])\n actual_majority_vs2 = actual_seatsvotes2[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n actual_seatsvotes2[round(hmid - 0.5) - 1] + actual_seatsvotes2[round(hmid - 0.5) - 1])\n cvdiff = actual_majority_vs1 - actual_majority_vs2\n\n # What is the number of seats arising from a split vote?\n # actual_number_seats1 = np.sum(actual_seatsvotes1 <= 0.5)\n # actual_number_seats2 = np.sum(actual_seatsvotes2 <= 0.5)\n\n # What is the number of seats arising from a split vote?\n actual_number_seats_int1 = np.sum(actual_seatsvotes1 <= 0.5)\n seatindex1 = actual_number_seats_int1 - 1\n v0 = actual_seatsvotes1[seatindex1]\n v1 = actual_seatsvotes1[seatindex1 + 1]\n actual_number_seats_float1 = actual_number_seats_int1 + (0.5 - v0) / (v1 - v0)\n\n actual_number_seats_int2 = np.sum(actual_seatsvotes2 <= 0.5)\n seatindex2 = actual_number_seats_int2 - 1\n v0 = actual_seatsvotes2[seatindex2]\n v1 = actual_seatsvotes2[seatindex2 + 1]\n actual_number_seats_float2 = actual_number_seats_int2 + (0.5 - v0) / (v1 - v0)\n\n cndiff_int = actual_number_seats_int1 - actual_number_seats_int2\n cndiff_float = actual_number_seats_float1 - actual_number_seats_float2\n\n # space allocation\n majority_vs = np.zeros((2, chainlength))\n number_seats_float = np.zeros((2, chainlength))\n number_seats_int = np.zeros((2, chainlength))\n\n # seats votes curve for the ensemble\n for j in range(0, chainlength):\n race_results = sorted(ensemble[j, :], reverse=True)\n mean_voteshare = np.mean(race_results)\n seatsvotes1 = mean_voteshare - np.array(race_results) + 0.5\n seatsvotes2 = np.flip(1 - seatsvotes1)\n\n # What is the percentage nec. for a majority?\n majority_vs[0, j] = seatsvotes1[odd_midindex] if districts % 2 != 0 else 0.5 * (\n seatsvotes1[evl_midindex] + seatsvotes1[evr_midindex])\n majority_vs[1, j] = seatsvotes2[odd_midindex] if districts % 2 != 0 else 0.5 * (\n seatsvotes2[evl_midindex] + seatsvotes2[evr_midindex])\n\n # What is the number of seats arising from a split vote?\n number_seats_int[0, j] = np.sum(seatsvotes1 <= 0.5)\n lastseat1 = round(number_seats_int[0, j] - 1)\n v0 = seatsvotes1[lastseat1]\n v1 = seatsvotes1[lastseat1 + 1]\n number_seats_float[0, j] = number_seats_int[0, j] + (0.5 - v0) / (v1 - v0)\n\n number_seats_int[1, j] = np.sum(seatsvotes2 <= 0.5)\n lastseat2 = round(number_seats_int[1, j] - 1)\n v0 = seatsvotes2[lastseat2]\n v1 = seatsvotes2[lastseat2 + 1]\n number_seats_float[1, j] = number_seats_int[1, j] + (0.5 - v0) / (v1 - v0)\n\n #\n # Voteshares\n #\n # things we need to plot\n vdiffs = majority_vs[0, :] - majority_vs[1, :]\n mvdiff = np.median(vdiffs)\n\n # for making it look nice\n vdmin = min(vdiffs)\n vdmax = max(vdiffs)\n vbinedge_min = np.floor(vdmin)\n vbinedge_max = np.ceil(vdmax)\n vbinbounds = np.arange(vbinedge_min, vbinedge_max + .01, .01)\n\n vdbuff = (vdmax - vdmin) * .2\n\n vhist, vedges = np.histogram(vdiffs, bins=vbinbounds)\n print(\"Mean-Median: %4.2f (%8.6f percentile).\" % (cvdiff, stats.percentileofscore(vdiffs, cvdiff)))\n\n #\n # Number of Seats\n #\n # things we need to plot\n ndiffs_int = number_seats_int[0, :] - number_seats_int[1, :]\n\n ndiffs_float = number_seats_float[0, :] - number_seats_float[1, :]\n mndiff_float = np.median(ndiffs_float)\n\n # for making it look nice\n ndmin = min(ndiffs_float)\n ndmax = max(ndiffs_float)\n nbinedge_min = np.floor(ndmin)\n nbinedge_max = np.ceil(ndmax)\n nbinbounds = np.arange(nbinedge_min - 0.5, nbinedge_max + 0.5)\n ndbuff = (ndmax - ndmin) * .2\n\n nhist, nedges = np.histogram(ndiffs_float, bins=nbinbounds)\n print(\"Partisan Bias (int): %4.2f (%8.6f percentile).\" % (\n cndiff_int, stats.percentileofscore(ndiffs_int, cndiff_int)))\n print(\"Partisan Bias (float): %4.2f (%8.6f percentile).\" % (\n cndiff_float, stats.percentileofscore(ndiffs_float, cndiff_float)))\n\n # ----------------------------------------\n # Show the 1D distributions separately\n # ----------------------------------------\n myfigure = plt.figure(figsize=(6.5, 3.5))\n axes = plt.subplot(121)\n\n plt.hist(vdiffs, bins=vbinbounds, color=\"xkcd:dark blue\", **{'alpha': 0.3})\n plt.axvline(x=mvdiff, color=\"green\", ls='--', lw=2.5, ymax=0.75, label=\"Ensemble Median\")\n plt.axvline(x=cvdiff, color=\"purple\", ls='--', lw=2.5, ymax=0.75, label=\"Proposed Districts\")\n plt.xlim(vdmin - vdbuff, vdmax + vdbuff)\n axes.xaxis.set_major_formatter(lambda x, pos: format(100 * x, \".0f\"))\n\n plt.ylim(0, np.max(vhist) * 1.4)\n plt.tick_params(\n axis='y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False) # labels along the bottom edge are off\n plt.xlabel(\"Voteshare Difference for Majority (D-R)\")\n plt.ylabel(\"Relative Frequency\")\n plt.title('\"Mean-Median\" Score')\n plt.legend(loc=\"upper center\")\n\n plt.subplot(122)\n plt.hist(ndiffs_float, bins=nbinbounds, color=\"xkcd:dark blue\", **{'alpha': 0.3})\n\n plt.axvline(x=mndiff_float, color=\"green\", ls='--', lw=2.5, ymax=0.75, label=\"Ensemble Median\")\n plt.axvline(x=cndiff_float, color=\"purple\", ls='--', lw=2.5, ymax=0.75, label=\"Proposed Districts\")\n plt.xlim(ndmin - ndbuff, ndmax + ndbuff)\n\n plt.ylim(0, np.max(nhist) * 1.4)\n if (nbinedge_max - nbinedge_min) <= 12:\n plt.xticks(np.arange(nbinedge_min, nbinedge_max, 2))\n else:\n plt.xticks(np.arange(nbinedge_min, nbinedge_max, 4))\n plt.tick_params(\n axis='y', # changes apply to the y-axis\n which='both', # both major and minor ticks are affected\n left=False, # ticks along the bottom edge are off\n right=False, # ticks along the top edge are off\n labelleft=False) # labels along the bottom edge are off\n plt.title('\"Partisan Bias\" Score')\n plt.xlabel(\"Seat Difference at Equal Votes (D-R)\")\n plt.legend(loc=\"upper center\")\n\n plt.tight_layout()\n return myfigure\n\n\ndef partisan_metrics_hist2D(ensemble_matrix: np.ndarray, plan_vector: np.ndarray, comparison_label: str,\n number_points: Optional[int], previous_figure_point: Optional[tuple[Any, Any]]) -> Any:\n chainlength, districts = np.shape(ensemble_matrix)\n hmid = 1 + (districts - 1) / 2.0\n\n if previous_figure_point is not None:\n myfigure, previous_point = previous_figure_point\n previous_point.remove()\n else:\n myfigure = plot_ensemble_matrix_votes_seats(hmid, number_points, ensemble_matrix)\n\n mean_median, partisan_bias = calculate_mean_median_partisan_bias(districts, hmid, plan_vector)\n previous_point = plt.plot([mean_median], [partisan_bias], 'rs', label=comparison_label)[0]\n\n plt.legend(loc='best')\n\n return myfigure, previous_point\n\n\ndef partisan_metrics_hist2D_all_plans(ensemble_matrix: np.ndarray, plan_vectors: dict[int, np.ndarray],\n height_restarts: set[int]) -> Any:\n chainlength, districts = np.shape(ensemble_matrix)\n hmid = 1 + (districts - 1) / 2.0\n\n heights: dict[int, float] = defaultdict(float)\n values = [(x, calculate_mean_median_partisan_bias(districts, hmid, y)) for x, y in plan_vectors.items()]\n values = sorted(values, key=lambda x: (x[1][1], x[1][0]))\n\n for plan_number, (mean_median, partisan_bias) in values:\n plt.plot([mean_median], [partisan_bias], 'rs')\n if plan_number in height_restarts:\n heights[partisan_bias] = 0\n plt.annotate(str(plan_number), (mean_median + .001, partisan_bias + (heights[partisan_bias]) + .15))\n heights[partisan_bias] = heights[partisan_bias] + .23\n\n\ndef calculate_mean_median_partisan_bias(districts: int, hmid: float, plan_vector: np.ndarray) -> tuple[float, int]:\n actual_race_results = sorted(plan_vector, reverse=True)\n actual_mean_voteshare = np.mean(actual_race_results)\n actual_seatsvotes1 = actual_mean_voteshare - np.array(actual_race_results) + 0.5\n actual_seatsvotes2 = np.flip(1 - actual_seatsvotes1)\n\n # What is the percentage nec. for a majority?\n actual_majority_vs1 = actual_seatsvotes1[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n actual_seatsvotes1[round(hmid - 0.5) - 1] + actual_seatsvotes1[round(hmid - 0.5) - 1])\n actual_majority_vs2 = actual_seatsvotes2[round(hmid) - 1] if districts % 2 != 0 else 0.5 * (\n actual_seatsvotes2[round(hmid - 0.5) - 1] + actual_seatsvotes2[round(hmid - 0.5) - 1])\n mean_median = actual_majority_vs2 - actual_majority_vs1\n\n # What is the percentage nec. for a majority?\n actual_number_seats1 = np.count_nonzero(actual_seatsvotes1 <= 0.5)\n actual_number_seats2 = np.count_nonzero(actual_seatsvotes2 <= 0.5)\n partisan_bias = actual_number_seats1 - actual_number_seats2\n\n return mean_median, partisan_bias\n\n\ndef plot_ensemble_matrix_votes_seats(hmid: float, number_points: Optional[int], ensemble_matrix: np.ndarray) -> Any:\n vote_diffs, seat_diffs = calculate_ensemble_mean_median_partisan_biases(hmid, ensemble_matrix)\n\n myfigure = plt.figure(figsize=(6.5, 5))\n\n if (number_points is not None) and (number_points < len(vote_diffs)):\n indices = list(range(0, len(vote_diffs)))\n shuffle(indices)\n indices = indices[0: number_points]\n vote_diffs = vote_diffs[indices]\n seat_diffs = seat_diffs[indices]\n\n sns.set_style(\"white\")\n ensemble_axes = sns.kdeplot(x=vote_diffs, y=seat_diffs, cmap=\"Blues\", shade=True, cbar=True,\n levels=[.0001, .001, .01, .05, .25, .5, .75, 1.0])\n plt.xticks(ensemble_axes.get_xticks(), map(lambda x: format(100 * x, \".0f\"), ensemble_axes.get_xticks()))\n\n plt.xlabel(\"Mean-Median %\")\n plt.ylabel(\"Partisan Bias\")\n plt.title(\"2D Histogram of Ensemble Partisan Metrics\")\n plt.tight_layout()\n\n return myfigure\n\n\ndef calculate_ensemble_mean_median_partisan_biases(hmid: float, ensemble: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n chainlength, districts = np.shape(ensemble)\n\n # logic for odd or even numbers of districts\n # odd_number_of_districts = (districts % 2 != 0)\n odd_midindex = round(hmid) - 1\n evl_midindex = round(hmid - 0.5) - 1\n evr_midindex = round(hmid + 0.5) - 1\n\n # space allocation\n majority_vs = np.zeros((2, chainlength))\n number_seats = np.zeros((2, chainlength))\n\n # seats votes curve for the ensemble\n for j in range(0, chainlength):\n if j % 100000 == 0:\n print(j)\n\n race_results = sorted(ensemble[j, :], reverse=True)\n mean_voteshare = np.mean(race_results)\n seatsvotes1 = mean_voteshare - np.array(race_results) + 0.5\n seatsvotes2 = np.flip(1 - seatsvotes1)\n\n # What is the percentage nec. for a majority?\n majority_vs[0, j] = seatsvotes1[odd_midindex] if districts % 2 != 0 else 0.5 * (\n seatsvotes1[evl_midindex] + seatsvotes1[evr_midindex])\n majority_vs[1, j] = seatsvotes2[odd_midindex] if districts % 2 != 0 else 0.5 * (\n seatsvotes2[evl_midindex] + seatsvotes2[evr_midindex])\n\n # What is the number of seats arising from a split vote?\n lastseat1 = np.count_nonzero(seatsvotes1 <= 0.5) - 1\n v0 = seatsvotes1[lastseat1]\n if (lastseat1 + 1) == districts:\n number_seats[0, j] = districts\n else:\n v1 = seatsvotes1[lastseat1 + 1]\n number_seats[0, j] = lastseat1 + 1 + (0.5 - v0) / (v1 - v0)\n\n lastseat2 = np.count_nonzero(seatsvotes2 <= 0.5) - 1\n v0 = seatsvotes2[lastseat2]\n if (lastseat2 + 1) == districts:\n number_seats[1, j] = districts\n else:\n v1 = seatsvotes2[lastseat2 + 1]\n number_seats[1, j] = lastseat2 + 1 + (0.5 - v0) / (v1 - v0)\n\n # Voteshares\n mean_medians = majority_vs[1, :] - majority_vs[0, :]\n\n # Number of Seats\n partisan_biases = number_seats[0, :] - number_seats[1, :]\n\n return mean_medians, partisan_biases\n\n\ndef set_point_colors(point_colors: dict[int, str], districts: Iterable[int], color: str) -> None:\n for district in districts:\n point_colors[district] = color\n\n\ndef racial_vs_political_deviations(ensemble_p: np.ndarray, instance_p: np.ndarray, ensemble_r: np.ndarray,\n instance_r: np.ndarray, title: str, use_global_medians: bool,\n display_ensemble: bool, number_points: Optional[int], color_points: bool,\n previous_graphics: Optional[tuple[Any, tuple[Any, Any, list[plt.Annotation]]]]) \\\n -> tuple[Any, tuple[Any, list, list[plt.Annotation]]]:\n def biggest_multiple_less_than(multiple_of: float, input_number: float, decimal_points: int) -> float:\n return round(input_number - input_number % multiple_of, decimal_points)\n\n def smallest_multiple_greater_than(multiple_of: float, input_number: float, decimal_points: int) -> float:\n return biggest_multiple_less_than(multiple_of, input_number + multiple_of, decimal_points)\n\n number_plans, districts = np.shape(ensemble_p)\n\n # sort the instance_p, and record the district numbers\n sorted_districts_p = np.argsort(instance_p) + 1\n sorted_instance_p = sorted(instance_p)\n median_p = np.median(ensemble_p) if use_global_medians else np.median(ensemble_p, axis=0)\n instance_diffs_by_rank_p = sorted_instance_p - median_p\n instance_diffs_p = [instance_diffs_by_rank_p[i] for i in np.argsort(sorted_districts_p)]\n\n # sort the instance_r, and record the district numbers\n sorted_districts_r = np.argsort(instance_r) + 1\n sorted_instance_r = sorted(instance_r)\n median_r = np.median(ensemble_r) if use_global_medians else np.median(ensemble_r, axis=0)\n instance_diffs_by_rank_r = sorted_instance_r - median_r\n instance_diffs_r = [instance_diffs_by_rank_r[i] for i in np.argsort(sorted_districts_r)]\n\n if previous_graphics is not None:\n fig, (ax, path_collections, annotations) = previous_graphics\n for path_collection in path_collections:\n path_collection.remove()\n for annotation in annotations:\n annotation.remove()\n else:\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.suptitle(title)\n\n if display_ensemble:\n ensemble_diffs_p = (ensemble_p - median_p).flatten()\n ensemble_diffs_r = (ensemble_r - median_r).flatten()\n\n if (number_points is not None) and (number_points < len(ensemble_diffs_p)):\n indices = list(range(0, number_points))\n shuffle(indices)\n indices = indices[0: number_points]\n ensemble_diffs_p = ensemble_diffs_p[indices]\n ensemble_diffs_r = ensemble_diffs_r[indices]\n\n interval = .05 if use_global_medians else .01\n min_x = biggest_multiple_less_than(interval, -interval + min(np.amin(instance_diffs_r),\n min(ensemble_diffs_r) if display_ensemble else 10), 2)\n max_x = smallest_multiple_greater_than(interval, interval + max(np.amax(instance_diffs_r),\n max(instance_diffs_r) if display_ensemble else -10), 2)\n min_y = biggest_multiple_less_than(interval, -interval + min(np.amin(instance_diffs_p),\n min(ensemble_diffs_p) if display_ensemble else 10), 2)\n max_y = smallest_multiple_greater_than(interval, interval + max(np.amax(instance_diffs_p),\n max(ensemble_diffs_p) if display_ensemble else -10), 2)\n\n plt.xlim([min_x, max_x])\n plt.ylim([min_y, max_y])\n\n ax.plot([min_x, max_x], [0, 0], 'k--', label='_nolegend_')\n ax.plot([0, 0], [min_y, max_y], 'k--', label='_nolegend_')\n\n ax.set_xlabel('Minority Population Deviation')\n ax.set_ylabel('Democratic Voter Deviation')\n\n if display_ensemble:\n sns.set_style(\"white\")\n levels = [.0001, .001, .01, .05, .25, .5, .75, 1.0]\n sns.kdeplot(x=ensemble_diffs_r, y=ensemble_diffs_p, cmap=\"Blues\", shade=True, cbar=True, levels=levels)\n\n point_colors = {x: 'red' for x in range(0, districts)}\n\n if color_points:\n pc_thresh = .01\n ensemble_p_sorted = ensemble_p.copy()\n for row in ensemble_p_sorted:\n row.sort()\n\n vs_ensemble = [ensemble_p_sorted[:, i] for i in range(districts)]\n vs_lower, _, vs_upper = calculate_ensemble_district_statistics(vs_ensemble, pc_thresh)\n cracked, packed, stuffed = determine_cracked_packed_stuffed_districts(districts, instance_p, vs_lower, vs_upper)\n set_point_colors(point_colors, cracked, 'yellow')\n set_point_colors(point_colors, packed, 'orange')\n set_point_colors(point_colors, stuffed, 'purple')\n\n colors_list = [point_colors[x] for x in point_colors]\n unique_colors = sorted(set(colors_list))\n mapping = {'red': 'unclassified', 'yellow': 'cracked', 'orange': 'packed', 'purple': 'stuffed'}\n path_collections = []\n for color in unique_colors:\n r = [instance_diffs_r[i] for i, x in enumerate(colors_list) if x == color]\n p = [instance_diffs_p[i] for i, x in enumerate(colors_list) if x == color]\n path_collection = ax.scatter(r, p, marker='s', c=color, label=mapping[color])\n path_collections.append(path_collection)\n\n if color_points:\n plt.legend()\n\n annotations = [ax.annotate(str(i + 1), (instance_diffs_r[i] + .005, instance_diffs_p[i] + .005))\n for i in np.arange(0, districts)]\n\n return fig, (ax, path_collections, annotations)\n","repo_name":"scott-norris-math/GerryWrap","sub_path":"src/GerryWrap.py","file_name":"GerryWrap.py","file_ext":"py","file_size_in_byte":49642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"4489406841","text":"from typing import Union, List\nfrom tqdm.auto import tqdm\nimport pandas as pd\nimport numpy as np\nfrom .utils import get_index, download_chunks_from_curie_ids, get_vector_from_curie_id\n\n\ndef get_pubmed_embedding_from_curies(\n curies: Union[List[str], str],\n ignore_missing_curies: bool = True,\n check_for_prefix: bool = True,\n downloads_directory: str = \"embeddings\",\n version: str = \"pubmed_scibert_30_11_2022\",\n) -> pd.DataFrame:\n \"\"\"Returns dataframe with curies as index and embedding from required version.\n \n Parameters\n ---------------------\n curies: Union[List[str], str]\n Curies to retrieve the embedding for.\n ignore_missing_curies: bool = True\n Whether to ignore curies for which we cannot currently\n provide an embedding. By default, True.\n check_for_prefix: bool = True\n Whether to check for the presence of the prefix `PMID`.\n By default True.\n downloads_directory: str = \"embeddings\"\n Directory where to store the downloaded files.\n version: str = \"pubmed_scibert_30_11_2022\"\n The version of the file to retrieve.\n \"\"\"\n index: pd.DataFrame = get_index(\n version=version,\n downloads_directory=downloads_directory\n )\n \n if isinstance(curies, str):\n curies: List[str] = [curies]\n\n # Checking presence of prefix\n if check_for_prefix:\n for curie in curies:\n if not curie.startswith(\"PMID:\"):\n raise ValueError(\n f\"The provided curie `{curie}` does not \"\n \"begin with the expected curie prefix `PMID:`.\"\n )\n\n if ignore_missing_curies:\n curies = [\n curie\n for curie in tqdm(\n curies,\n desc=f\"Checking availability in version {version}\",\n leave=False,\n dynamic_ncols=True,\n disable=len(curies) == 1\n )\n if curie in index.index\n ]\n \n curie_ids: np.ndarray = index.loc[curies].curie_id.values\n\n download_chunks_from_curie_ids(curie_ids, version, downloads_directory)\n\n return pd.DataFrame(\n np.array([\n get_vector_from_curie_id(\n curie_id=curie_id,\n version=version,\n downloads_directory=downloads_directory\n )\n for curie_id in tqdm(\n curie_ids,\n desc=f\"Retrieving embedding version {version}\",\n leave=False,\n dynamic_ncols=True,\n disable=len(curie_ids) == 1\n )\n ]),\n index=curies\n )","repo_name":"LucaCappelletti94/pubmed_embedding","sub_path":"pubmed_embedding/pubmed_embedding.py","file_name":"pubmed_embedding.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"25366365072","text":"import tensorflow as tf\nimport time\nimport os\nimport json\n\n\ndef reload_config(FLAGS):\n # If we are reloading a model, overwrite the flags\n if FLAGS.reload_model is not '':\n with open('%s/%s' % (os.path.dirname(FLAGS.reload_model), 'config.json')) as data_file:\n config_dict = json.load(data_file)\n\n for key, value in config_dict.items():\n attr_remove = ['gpu', 'run_name', 'log_dir', 'n_steps_gen', 'reload_model', 'display_step', 'generate_step']\n # attr_remove = ['gpu', 'n_steps_gen', 'reload_model', 'display_step', 'generate_step']\n if key not in attr_remove:\n FLAGS.__setattr__(key, value)\n return FLAGS\n\n\ndef get_image_config():\n cl = tf.app.flags\n\n # Choose data set\n cl.DEFINE_string('dataset', 'box', 'Select data set') # 'box_rnd', 'box_gravity', 'polygon' or 'pong'\n\n # VAE config\n cl.DEFINE_string('out_distr', 'bernoulli', 'Output distibution')\n cl.DEFINE_boolean('conv', True, 'Use conv vae')\n cl.DEFINE_string('activation', 'relu', 'Activation function in VAE')\n cl.DEFINE_integer('filter_size', 3, 'Filter size in conv vae')\n cl.DEFINE_string('num_filters', '32,32,32', 'Comma separated list of conv filters')\n cl.DEFINE_integer('vae_num_units', 25, 'Number of hidden units in the VAE (if conv=False)')\n cl.DEFINE_integer('num_layers', 2, 'Number of layers in VAE (if conv=False)')\n cl.DEFINE_float('noise_pixel_var', 0.1, 'Noise variance for the pixels in the image if out_distr=gaussian')\n cl.DEFINE_float('ll_keep_prob', 1.0, 'Keep probability of p(x|a)')\n cl.DEFINE_boolean('use_vae', True, 'Use VAE and not AE')\n\n # LGSSM config\n cl.DEFINE_integer('dim_a', 2, 'Number of latent variables in the VAE')\n cl.DEFINE_integer('dim_z', 4, 'Dimension of the latent state in the LGSSM')\n cl.DEFINE_integer('dim_u', 1, 'Dimension of the inputs')\n cl.DEFINE_integer('K', 3, 'Number of filters in mixture')\n cl.DEFINE_float('noise_emission', 0.03, 'Noise level for the measurement noise matrix')\n cl.DEFINE_float('noise_transition', 0.08, 'Noise level for the process noise matrix')\n cl.DEFINE_float('init_cov', 20.0, 'Variance of the initial state')\n\n # Parameter network config\n cl.DEFINE_boolean('alpha_rnn', True, 'Use LSTM RNN for alpha')\n cl.DEFINE_integer('alpha_units', 50, 'Number of units in alpha network')\n cl.DEFINE_integer('alpha_layers', 2, 'Number of layers in alpha network (if alpha_rnn=False)')\n cl.DEFINE_string('alpha_activation', 'relu', 'Activation function in alpha (if alpha_rnn=False)')\n cl.DEFINE_integer('fifo_size', 1, 'Number of items in the alpha FIFO memory (if alpha_rnn=False)')\n cl.DEFINE_boolean('learn_u', False, 'Model u from a neural network')\n\n # Training config\n cl.DEFINE_integer('batch_size', 32, 'Size of mini batches')\n cl.DEFINE_float('init_lr', 0.007, 'Starter learning rate')\n cl.DEFINE_float('init_kf_matrices', 0.05, 'Standard deviation of noise used to initialize B and C')\n cl.DEFINE_float('max_grad_norm', 150.0, 'Gradient norm clipping')\n cl.DEFINE_float('scale_reconstruction', 0.3, 'Scale for the reconstruction term in the elbo')\n cl.DEFINE_integer('only_vae_epochs', 0, 'Number of epochs in which we only train the vae')\n cl.DEFINE_integer('kf_update_steps', 10, 'Number of extra update steps done for the kalman filter')\n cl.DEFINE_float('decay_rate', 0.85, 'Decay steps for exponential lr decay')\n cl.DEFINE_integer('decay_steps', 20, 'Decay steps for exponential lr decay')\n cl.DEFINE_boolean('sample_z', False, 'Sample z from the prior')\n cl.DEFINE_integer(\"num_epochs\", 80, \"Epoch to train\")\n cl.DEFINE_float('train_miss_prob', 0.0, 'Fraction of missing data during training')\n cl.DEFINE_integer('t_init_train_miss', 3, 'Number of initial observed frames when training with missing data')\n\n # Utils config\n cl.DEFINE_string('gpu', '', 'Comma seperated list of GPUs')\n cl.DEFINE_string('reload_model', '', 'Path to the model.cpkt file')\n\n # Logs/plotting config\n cl.DEFINE_string('run_name', time.strftime('%Y%m%d%H%M%S', time.localtime()), 'Name for the run')\n cl.DEFINE_string('log_dir', 'logs', 'Directory to save files in')\n cl.DEFINE_integer('display_step', 1, 'After how many epochs to print logs')\n cl.DEFINE_integer('generate_step', 20, 'After how many epochs to store the plots')\n cl.DEFINE_integer('n_steps_gen', 80, 'Number of steps to generate in a sequence')\n cl.DEFINE_integer('t_init_mask', 4, 'Initial time step for data imputation')\n cl.DEFINE_integer('t_steps_mask', 12, 'Number of time steps for data imputation')\n\n return cl\n\n\nif __name__ == '__main__':\n config = get_image_config()\n config.DEFINE_bool('test', True, 'test')\n config = reload_config(config.FLAGS)\n\n print(config.dataset)\n config.dataset = 'test'\n print(config.dataset)\n\n print(config.__flags)\n","repo_name":"simonkamronn/kvae","sub_path":"kvae/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4919,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"53"}
+{"seq_id":"15392993763","text":"from datetime import datetime\nimport cv2\nimport numpy as np\n\nfrom progressbar import ProgressBar\n\nfrom .graph_slam import GraphSLAM\nfrom .icp_slam import ICPSLAM\nfrom .occupancy_grid import OccupancyGrid\nfrom.real_slam import REALSLAM\n\n\nSLAM = {\n 'graph': GraphSLAM,\n 'icp': ICPSLAM,\n 'real': REALSLAM,\n}\n\n\ndef process_realdata(slam, realpos, scanner_data, first_pos):\n new_scan = np.array(scanner_data)[:, 1: 3]\n pos = [0, 0, 0]\n if first_pos is not None:\n pos[0] = realpos[0] - first_pos[0]\n pos[1] = realpos[1] - first_pos[1]\n else:\n first_pos = realpos\n pos[2] = realpos[2]\n slam.mapping(np.array(pos), new_scan)\n return slam, first_pos\n\n\ndef process_data(slam, odom_data, scanner_data, last_odom):\n\n new_scan = np.array(scanner_data)[:, 1: 3]\n\n dl = odom_data[3]\n dr = odom_data[4]\n\n c = 2.425 * 25\n v_ = c * (dl + dr) / 2\n\n transform = [0, 0, 0]\n if last_odom is not None:\n theta = odom_data[2]\n dtheta = (theta - last_odom[2])\n\n transform[0] = v_ * np.cos(theta) * 0.85\n transform[1] = v_ * np.sin(theta) * 0.95\n transform[2] = dtheta\n\n slam.mapping(np.array(transform), new_scan)\n\n return slam, odom_data.copy()\n\n\ndef create_OccupancyGrid(slam, name='', size=500):\n min_scanner = 20\n resolution = min_scanner * 2 / size\n\n occupancy_grid = OccupancyGrid(\n shape=(size, size),\n resolution=resolution,\n logOdd_occ=1.2,\n logOdd_free=0.3\n )\n occupancy_grid.min_treshold = -50\n occupancy_grid.max_treshold = 50\n offset = min_scanner\n\n plot = np.zeros((500, 500, 3), dtype=np.uint8)\n\n V = slam.getVertices()\n with ProgressBar(max_value=len(V)) as bar:\n for i, v in enumerate(V):\n\n X = v.point\n\n dx = v.point\n psi = dx[2]\n R = np.array([[np.cos(psi), - np.sin(psi)],\n [np.sin(psi), np.cos(psi)]])\n T = dx[0: 2].reshape((2, 1))\n\n P = v.laser_scanner_data\n\n all_plot = []\n\n for p in P:\n p = np.dot(p, R.T) + T.T\n p = p.reshape((2,))\n occupancy_grid.updateOccupy(\n (X[0] + offset, - X[1] + offset), (p[0] + offset, - p[1] + offset))\n plot = cv2.circle(plot, (int(\n size // 2 - p[1] // resolution), int(size // 2 - p[0] // resolution)), 1, (0, 0, 255))\n all_plot.append(plot)\n\n grid = occupancy_grid.getImage(\n occupancy_grid.min_treshold, occupancy_grid.max_treshold)\n center = (int(X[0] // resolution) + (size // 2),\n (size // 2) - int(X[1] // resolution))\n grid = cv2.circle(grid, center, 2, (0, 0, 255), -1)\n # cv2.imshow(name, grid)\n all_plot.append(grid)\n\n obs = occupancy_grid.getImage2(0.5)\n all_plot.append(obs)\n\n scan = np.zeros((500, 500, 3), dtype=np.uint8)\n scale = 50\n scan = cv2.circle(scan, (250, 250), 5, (100, 250, 50), -1)\n for p in P:\n scan = cv2.circle(\n scan, (int(250 - p[1] * scale), int(250 - p[0] * scale)), 2, (0, 125, 255))\n # cv2.imshow('scan', scan)\n all_plot.append(scan)\n\n img = cv2.hconcat(all_plot)\n img = cv2.putText(img, f'{v.point}', (20, 40),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 100, 100))\n cv2.imshow('all plot', img)\n\n key = cv2.waitKey(1)\n if key > -1:\n break\n\n bar.update(i)\n\n grid = occupancy_grid.getImage(\n occupancy_grid.min_treshold, occupancy_grid.max_treshold)\n\n return grid, occupancy_grid\n\n\ndef compute(log, slam_type='graph', optimized=True, name='', run_graph=True, size=500, progress=True):\n\n print(f'computing {slam_type}SLAM...')\n slam = SLAM[slam_type](optimized=optimized)\n\n slam.init_pose = np.array([0, 0, 4.622105688902131])\n\n if slam_type == 'real':\n first_pos = None\n with ProgressBar(max_value=1050) as bar:\n for i, data in enumerate(log['data'][: 1050]):\n slam, first_pos = process_realdata(\n slam, data['realpos'], data['scanner'], first_pos)\n bar.update(i)\n else:\n last_odom = None\n if progress:\n with ProgressBar(max_value=len(log['data'])) as bar:\n for i, data in enumerate(log['data']):\n slam, last_odom = process_data(\n slam, data['odom'], data['scanner'], last_odom)\n bar.update(i)\n\n else:\n for i, data in enumerate(log['data']):\n slam, last_odom = process_data(\n slam, data['odom'], data['scanner'], last_odom)\n\n if run_graph:\n print('creating Occupancy Grid...')\n grid, occupancy_grid = create_OccupancyGrid(slam, name=name, size=size)\n else:\n grid = None\n occupancy_grid = None\n\n return slam, occupancy_grid, grid\n","repo_name":"p-amonpitakpun/cpcu-delivery","sub_path":"src/graph_mapping/scripts/modules/log_processing.py","file_name":"log_processing.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28647086378","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 16 10:51:34 2020\n\n@author: marco\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport configparser\n\n\nconfig = configparser.ConfigParser()\nconfig.read('inputs.txt')\n\niterations = config.getint('parameters', 'iterations')\nfile1 = config.get('files','distances')\nfile2 = config.get('files','path')\nfile3 = config.get('files','Tem')\nfile4 = config.get('files','tot_accept')\n\nplot_a = config.get('files','Path_pl')\nplot_b = config.get('files','AcceptRate_pl')\nplot_c = config.get('files','Length_pl')\nplot_d = config.get('files','Temperature_pl')\n\n\ndef dist_optimization():\n '''\n Plots the travel length as a function of the number of iterations.\n '''\n distances = np.load(file1)\n fig = plt.figure()\n plt.title(\"Current distance vs. # of iterations\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Current distance (arb. units)\")\n plt.plot(distances)\n plt.grid()\n plt.show() \n \n fig.savefig(plot_c)\n \n \ndef path_plot():\n '''\n Plots the followed path.\n '''\n \n path = np.load(file2)\n \n fig = plt.figure()\n plt.title(\"Followed path\")\n plt.plot (path[0],path[1],'o-')\n plt.xlabel(\"x coordinate (arb. units)\")\n plt.ylabel(\"y coordinate (arb. units)\") \n plt.grid()\n plt.show()\n \n fig.savefig(plot_a)\n \n \ndef acceptance_plot(iterations):\n '''\n Plots the acceptance rate as a function of the temperature for each iteration.\n '''\n Tem = np.load(file3)\n tot_acceptance = np.load(file4)\n fig = plt.figure() \n plt.title(\"Moves acceptance rate vs. temperature for each iteration\")\n plt.xlabel(\"Temperature (arb. units)\")\n plt.ylabel(\"Moves acceptance rate (%)\") \n lab=[]\n for i in range(iterations): \n plt.plot(Tem,tot_acceptance[i])\n lab.append(i+1) \n plt.legend(lab)\n plt.grid()\n plt.show()\n \n fig.savefig(plot_b)\n \n \ndef Temp_profile():\n '''\n Plots the temperature profile.\n '''\n Tem = np.load(file3)\n fig = plt.figure()\n plt.title(\"Temperature profile\")\n plt.plot (range(len(Tem)), Tem, color = 'red')\n plt.xlabel(\"steps (arb. units)\")\n plt.ylabel(\"Temperature (arb. units)\") \n plt.grid()\n plt.show()\n \n fig.savefig(plot_d)\n\n\ndist_optimization()\npath_plot()\nacceptance_plot(iterations)\nTemp_profile()","repo_name":"siauling108/Simulated-annealing","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6020121859","text":"# Inspired by https://github.com/mihaibogdan10/json-reuters-21578/blob/master/convert_sgm_to_json.py \n\nfrom bs4 import BeautifulSoup\nimport os\nimport json\nfrom os.path import join, isfile, dirname\n\n# Needs to pour all posts into a single file where each post has an age and gender attached to it.\n\nxmlDataDirPath = join(dirname(__file__), 'data/blogs/xml-data')\njsonDataDirPath = join(dirname(__file__), 'data/blogs/json-data')\n\n''' Returns a single data sample to be appended to the JSON file'''\ndef get_single_sample(post, gender, age):\n return {'post': post, 'gender': gender, 'age': age}\n\nfiles = [f for f in os.listdir(xmlDataDirPath) if isfile(join(xmlDataDirPath, f))]\nfiles_length = len(files)\ncounter = 0\njsonName = \"the-data.json\"\nprocessed_count = 0\njson_docs = []\nfor xmlName in files:\n print(\"Starting on\", xmlName)\n fileNameElements = xmlName.split('.') # So we can get the gender and age of the person\n\n # Load what's already in the JSON file into memory\n try:\n with open(join(jsonDataDirPath, jsonName)) as r_json:\n current_json_data = json.load(r_json)\n if current_json_data is None:\n current_json_data = []\n except IOError:\n print(\"Could not read file, starting from scratch\")\n current_json_data = []\n\n with open(join(xmlDataDirPath, xmlName), \"rb\") as rf:\n content = BeautifulSoup(rf, features = \"xml\")\n\n new_data = []\n for entry in content.findAll('Blog'):\n posts = [elem.text.replace(\"\\n\", \"\").replace(\"\\t\", \"\").strip() for elem in entry.findAll('post')]\n for post in posts:\n new_data.append(get_single_sample(post, fileNameElements[1], fileNameElements[2]))\n \n for instance in new_data:\n json_docs.append(instance)\n \n print(\"Done with\", xmlName)\n processed_count += 1\n print(\"Done with\", processed_count, \"of\", files_length)\n\nwith open(join(jsonDataDirPath, jsonName), mode='w') as wf:\n json.dump(json_docs, wf, indent=4, sort_keys=False)","repo_name":"TomLisankie/pytorch-blog-post-age-classification","sub_path":"xml-to-json.py","file_name":"xml-to-json.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38186149247","text":"class Solution:\n def findCircleNum(self, M: List[List[int]]) -> int:\n num = len(M)\n visited = [False]*num\n count = 0\n \n def aCircle(student):\n for i in range(num):\n if not visited[i] and student[i]:\n visited[i] = True\n aCircle(M[i])\n \n for i in range(num):\n if not visited[i]:\n aCircle(M[i])\n count+=1\n return count","repo_name":"cofo-coding-camp/Dorrryu","sub_path":"547_friend_circles.py","file_name":"547_friend_circles.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17968504571","text":"from django.db import models\n\n# Create your models here.\n\nclass Customer(models.Model):\n GENDER_CHOICES = (\n ('Male', 'Male'),\n ('Female', 'Female'),\n ('Other', 'Other')\n )\n\n TERM_CHOICES = (\n ('Short Term', 'Short Term'),\n ('Long Term', 'Long Term')\n )\n\n YOJ_CHOICES = (\n ('< 1 year', '< 1 year'),\n ('1 year', '1 year'),\n ('2 years', '2 years'),\n ('3 years', '3 years'),\n ('4 years', '4 years'),\n ('5 years', '5 years'),\n ('6 years', '6 years'),\n ('7 years', '7 years'),\n ('8 years', '8 years'),\n ('9 years', '9 years'),\n ('10+ years', '10+ years')\n )\n\n HO_CHOICES = (\n ('Home Mortgage', 'Home Mortgage'),\n ('Own Home', 'Own Home'),\n ('Rent', 'Rent'),\n ('HaveMortgage', 'HaveMortgage')\n )\n\n PURPOSE_CHOICES = (\n ('Home Improvements', 'Home Improvements'),\n ('Debt Consolidation', 'Debt Consolidation'),\n ('Buy House', 'Buy House'),\n ('Business Loan', 'Business Loan'),\n ('Buy a Car', 'Buy a Car'),\n ('Other', 'Other'),\n ('Take a Trip', 'Take a Trip'),\n ('Medical Bills', 'Medical Bills'),\n ('Educational Expenses', 'Educational Expenses'),\n )\n\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n age = models.IntegerField()\n gender = models.CharField(max_length=10, choices=GENDER_CHOICES)\n term = models.CharField(max_length=15, choices=TERM_CHOICES)\n credit_score = models.FloatField()\n year_in_current_job = models.CharField(max_length=15, choices=YOJ_CHOICES)\n home_ownership = models.CharField(max_length=30, choices=HO_CHOICES)\n purpose = models.CharField(max_length=30, choices=PURPOSE_CHOICES)\n years_credit_history = models.FloatField()\n num_open_acc = models.IntegerField()\n \n def __str__(self):\n return \"{}, {}\".format(self.first_name, self.last_name)","repo_name":"gagansingh894/BankLoanApp","sub_path":"app/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42485180813","text":"\"\"\"Задача 3. Проведите тест гипотезы. Продавец утверждает, что средний вес\nпачки печенья составляет 200 г.\nИз партии извлечена выборка из 10 пачек. Вес каждой пачки составляет:\n202, 203, 199, 197, 195, 201, 200, 204, 194, 190.\nИзвестно, что их веса распределены нормально.\nВерно ли утверждение продавца, если учитывать, что уровень значимости 1%?\n(Провести двусторонний тест.)\n\"\"\"\n\nimport numpy as np\nfrom scipy import stats\n\n# H0: mu = 200\n# H1: mu != 200\n\ntest_items = np.array([202, 203, 199, 197, 195, 201, 200, 204, 194, 190])\nalpha = 0.01\nn = 10\nmu = 200\n\n# считаем среднее и СКО по выборке\nx_mean = test_items.mean()\nx_std = test_items.std(ddof=1)\nprint(f\"Среднее по выборке = {x_mean}, СКО = {x_std}\")\n\n# определяем t-критерий для выборки\nt_x = (x_mean - mu) / (x_std / np.sqrt(n))\nprint(f\"t-критерий для выборки = {t_x}\")\n\n# определяем t для ЛКО и ПКО\nt_left = stats.t.ppf(alpha / 2, df=n - 1)\nt_right = stats.t.ppf(1 - alpha / 2, df=n - 1)\nprint(f\"t(ЛКО) = {t_left}, t(ПКО) = {t_right}\")\n\nif t_left < t_x < t_right:\n print(f\"Т.к. t-критерий не принадлежит критической зоне, гипотеза Н0 не \"\n f\"отвергается на уровне значимости {alpha}\")\nelse:\n print(f\"Т.к. t-критерий принадлежит критической зоне, гипотеза Н0 \"\n f\"отвергается с вероятностью ошибки {alpha}\")","repo_name":"Karsad76/terver_python_code","sub_path":"sem5_HW_Task3.py","file_name":"sem5_HW_Task3.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17870957208","text":"from ipn.models.Message import Message\nfrom datetime import timedelta\nimport json\n\ndef scan_groups_by_message():\n result = {\n \"messages\": [],\n }\n grouping_detected = False\n for message in Message.objects.all():\n if message.event_date_utc:\n message_group = Message.objects.filter(event_date_utc=(message.event_date_utc + timedelta(seconds=100)))\n for msg in message_group:\n result[\"messages\"].append(msg.id)\n\n print(result)\n","repo_name":"lpsinger/interplanetary_network","sub_path":"ipn/jobs/scan_for_groupings.py","file_name":"scan_for_groupings.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21455279925","text":"# -*- coding: utf-8 -*-\nimport collections\nclass Solution(object):\n def numBusesToDestination(self, routes, S, T):\n \"\"\"\n :type routes: List[List[int]]\n :type S: int\n :type T: int\n :rtype: int\n \"\"\"\n busStop = collections.defaultdict(set)\n for route in routes:\n for i, j in [(k, v) for k in route for v in route]:\n if i == j:\n continue\n busStop[i].add(j)\n busStop[j].add(i)\n res = 0\n if S == T:\n return res\n if T in busStop[S]:\n return res + 1\n visited = set([k for k in busStop[S]])\n stack = [stop for stop in busStop[S]]\n while stack:\n res += 1\n for _ in range(len(stack)):\n curr = stack.pop(0)\n if T in busStop[curr]:\n return res + 1\n else:\n for stop in busStop[curr]:\n if stop not in visited:\n stack.append(stop)\n return -1\n\nroutes = [[1,2,7],[3,6,7,4],[9,4,11]]\nS = 1\nT = 11\nassert Solution().numBusesToDestination(routes, S, T) == 3\n\nroutes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]]\nS = 15\nT = 12\nassert Solution().numBusesToDestination(routes, S, T) == -1\n\n","repo_name":"jerrt2003/leetcode-in-python","sub_path":"Interview_Feedback/Google/815. Bus Routes/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35095861106","text":"import slack\nimport csv\nimport random\nimport openai\nimport time\nimport os\nimport re\nimport jsonify \nimport json\nimport pandas as pd\nfrom doorman_functions import *\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nfrom flask import Flask\nfrom flask import request\nfrom slackeventsapi import SlackEventAdapter\n\napp = Flask(__name__)\nenv_path = Path('.')/'.env'\nload_dotenv(dotenv_path=env_path)\nwith open(\"adminKeys.json\", \"r\") as file:\n loaded_keys = json.load(file)\n# Load OpenAI, BotID, Slack Token and Slack Events Token\nopenai.api_key = token=os.environ['CHAT_TOKEN']\ndoorman_id = token=os.environ['DOORMAN_ID']\nclient = slack.WebClient(token=os.environ['SLACK_TOKEN'])\nslack_event_adapter = SlackEventAdapter(os.environ['SIGNING_SECRET'], '/doorman/', app)\n\n# Load question set and construct updated prompt\ndf = pd.read_csv('QandA_list.csv', encoding='utf-8')\nanswers = df[\"Question answers\"].tolist()\nextract_and_format(\"QandA_list.csv\",\"llmlads_prompt.txt\")\n@slack_event_adapter.on('message')\ndef message(payload):\n event = payload.get('event',{})\n message_ts = event.get('ts')\n message_thread = event.get('thread_ts')\n print(\"Message ts:\" + str(message_ts))\n print(\"Message thread:\" + str(message_thread))\n if message_thread != None:\n message_ts=message_thread\n channel_id = event.get('channel')\n user_id = event.get('user')\n text = event.get('text')\n inp = \"User input: \" + \"\\\"\" + text + \"\\\"\"\n if user_id == doorman_id:\n return None\n if (channel_id[0]!='D' and doorman_id in text):\n inp = remove_pings(inp,doorman_id)\n if len(inp) != 0: \n index = format_links(doorman(inp,message_ts))\n client.chat_postMessage(\n channel=channel_id,\n text=index,\n thread_ts=message_ts)\n else:\n client.chat_postMessage(\n channel=channel_id,\n text=\"Please ensure that your question is in the message you are mentioning Doorman in\",\n thread_ts=message_ts)\n elif (channel_id[0] == 'D'):\n index = doorman(inp,message_ts)\n print(f\"Doorman response: {index}\")\n if index != None:\n client.chat_postMessage(channel=user_id, text=index,thread_ts=message_ts)\n\n@app.route('/doorman/addnewgroup', methods=['GET','POST'])\ndef addingGroup():\n data = request.form\n user = data.get('user_id')\n if adminAuth(user) is False:\n return \"I appreciate your attempt to fix up the question set but you aren't authorized\"\n text = data.get('text')\n trigger_id = request.form['trigger_id']\n open_addition_modal(trigger_id)\n return '', 200\n\n@app.route('/doorman/claimadmin', methods=['GET','POST'])\ndef adminClaim():\n with open('adminKeys.json', \"r\") as file:\n user_ids = json.load(file)\n if not user_ids:\n data = request.form\n user = data.get('user_id')\n adminAdd(user) \n else:\n return f\"Admin slot has already been claimed, please ask an admin to promote you.\", 200\n return 'Welcome to the Admin Team', 200\n\n@app.route('/doorman/addadmin', methods=['GET','POST'])\ndef adminAddition():\n data=request.form\n user = data.get('user_id') \n text = data.get('text') \n if adminAuth(user) is False:\n return(\"Only admins are allowed to promote users\")\n with open('adminKeys.json', \"r\") as file:\n user_ids = json.load(file)\n if text in user_ids:\n return f'{text} is already an admin'\n adminAdd(text)\n return f'User {text} added to admins', 200\n\n@app.route('/doorman/removeadmin', methods=['GET','POST'])\ndef adminRemoval():\n data=request.form\n user = data.get('user_id') \n text = data.get('text') \n if adminAuth(user) is False:\n return(\"Only admins are allowed to demote users\")\n with open('adminKeys.json', \"r\") as file:\n user_ids = json.load(file)\n if text not in user_ids:\n return f'{text} is not an admin'\n adminRemove(text)\n \n return f'User {text} removed from admins', 200\n\n@app.route('/doorman/rmgroup', methods=['GET','POST'])\ndef questionSetRemove():\n data=request.form\n user = data.get('user_id')\n if adminAuth(user) is False:\n return \"I appreciate your attempt to fix up the question set but you aren't authorized\"\n text = data.get('text')\n trigger_id = request.form['trigger_id']\n open_deletion_modal(trigger_id)\n extract_and_format(\"QandA_list.csv\",\"llmlads_prompt.txt\")\n client.chat_postMessage(channel='#test', text=f'Current amount of questions:{get_number_of_rows(\"QandA_list.csv\")}' )\n\n return '', 200\n\n@app.route('/doorman/howmanyqs', methods=['GET','POST'])\ndef howManyQuestions():\n client.chat_postMessage(channel='#test', text=f'Current amount of questions:{get_number_of_rows(\"QandA_list.csv\")}' )\n return '', 200\n\n@app.route('/doorman/printqlist', methods=['GET','POST'])\ndef printQuestionList():\n with open('llmlads_prompt.txt', 'r', encoding='utf-8') as file:\n content = file.read()\n return f'Current question list:{content}', 200\n\n@app.route('/doorman/interactive', methods=['POST'])\ndef slack_interactive():\n payload = request.form['payload']\n data = json.loads(payload)\n\n # Check for modal submission\n if data[\"type\"] == \"view_submission\" and data[\"view\"][\"callback_id\"] == \"question_modal\":\n # Extract data from the modal\n values = data[\"view\"][\"state\"][\"values\"]\n question_prompt = values[\"answer_label\"][\"answer_label_input\"][\"value\"]\n example_questions = values[\"example_questions\"][\"example_input\"][\"value\"]\n answer = values[\"answer_input\"][\"answer_input\"][\"value\"]\n\n add_new_row_to_csv(\"QandA_list.csv\",question_prompt,example_questions,answer)\n extract_and_format(\"QandA_list.csv\",\"llmlads_prompt.txt\")\n client.chat_postMessage(channel='#test', text=f'Current amount of questions:{get_number_of_rows(\"QandA_list.csv\")}' )\n if 'actions' in data:\n action = data['actions'][0]\n \n if action['action_id'].startswith('delete_question_'):\n question_index = int(action['action_id'].split('_')[-1])-1# Subtract 1 for zero-based indexing\n remove_row_by_number(\"QandA_list.csv\",question_index)\n \n # Generate the new modal content\n new_modal = generate_modal_from_csv()\n response = update_slack_modal(data['trigger_id'],data['view']['id'], new_modal)\n return '', 200\n\ndef adminAuth(key_to_check, filename=\"adminKeys.json\"):\n try:\n with open(filename, \"r\") as file:\n admin_keys = json.load(file)\n return key_to_check in admin_keys\n except FileNotFoundError:\n print(f\"File {filename} not found!\")\n return False\n \ndef adminAdd(user, filename=\"adminKeys.json\"):\n \"\"\"Add a new user ID to the specified JSON file without overwriting existing IDs.\"\"\"\n # Load existing user IDs, if any\n try:\n with open(filename, \"r\") as file:\n user_ids = json.load(file)\n except (FileNotFoundError, json.JSONDecodeError):\n user_ids = []\n # Add the new user ID if it's not already in the list\n if user not in user_ids:\n user_ids.append(user)\n # Save the updated list back to the file\n with open(filename, \"w\") as file:\n json.dump(user_ids, file)\n\ndef adminRemove(user, filename=\"adminKeys.json\"):\n \"\"\"Remove a new user ID to the specified JSON file without overwriting existing IDs.\"\"\"\n # Load existing user IDs, if any\n try:\n with open(filename, \"r\") as file:\n user_ids = json.load(file)\n except (FileNotFoundError, json.JSONDecodeError):\n user_ids = []\n # Add the new user ID if it's not already in the list\n if user in user_ids:\n user_ids.remove(user)\n # Save the updated list back to the file\n with open(filename, \"w\") as file:\n json.dump(user_ids, file)\n\n# Surely we can do something better than this \ndef wakeUp():\n time_string = time.strftime(\"%m/%d/%Y, %H:%M:%S\", time.localtime())\n client.chat_postMessage(channel='#test', text='Hello LLMYST I woke up at: '+ time_string)\n\nif __name__ == \"__main__\":\n wakeUp()\n app.run(debug=True, port=5000)\n print(\"Terminated Doorman\")\n","repo_name":"neuroneural/doorman","sub_path":"src/app_doorman.py","file_name":"app_doorman.py","file_ext":"py","file_size_in_byte":8417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26324882012","text":"\nfrom options.test_options import TestOptions\nfrom data import create_dataset\nfrom models import create_model\nfrom utils.logger import Logger\nimport time\n\nif __name__ == '__main__':\n opt, model_config = TestOptions().parse() # get training options\n dataset = create_dataset(opt) # create a dataset given opt.dataset_mode and other options\n dataset_size = len(dataset) # get the number of samples in the dataset.\n print('The number of training samples = %d' % dataset_size)\n\n model = create_model(opt, model_config) # create a model given opt.model and other options\n model.setup(opt) # regular setup: load and print networks; create schedulers\n visualizer = Logger(opt) # create a visualizer that display/save and plots\n total_iters = 0 # the total number of training iterations\n\n model.eval()\n\n val_start_time = time.time()\n for i, data in enumerate(dataset): # inner loop within the test dataset\n model.set_input(data) # unpack data from dataset and apply preprocessing\n model.test()\n model.cache_results() # store current batch results\n\n model.compute_visuals() # visualization\n t_val = time.time() - val_start_time\n\n model.compute_metrics()\n metrics = model.get_current_metrics()\n visualizer.print_current_metrics(-1, total_iters, metrics, t_val)\n\n model.save_data()","repo_name":"hjf1997/STGNP","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"53"}
+{"seq_id":"17887167039","text":"from flask import Flask, redirect, url_for, render_template\r\nimport os, socket\r\n\r\napp = Flask(__name__, static_url_path='/static')\r\n\r\ndef isOpen(ip, port):\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.settimeout(5)\r\n try:\r\n s.connect((ip, int(port)))\r\n s.shutdown(socket.SHUT_RDWR)\r\n return \"Up\"\r\n except:\r\n return \"Down\"\r\n finally:\r\n s.close()\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n b1 = isOpen(\"mindustry.ddns.net\", 1000)\r\n b2 = isOpen(\"mindustry.ddns.net\", 2000)\r\n b3 = isOpen(\"mindustry.ddns.net\", 3000)\r\n b4 = isOpen(\"mindustry.ddns.net\", 4000)\r\n return render_template(\"index.html\", a1=b1, a2=b2, a3=b3, a4=b4)\r\n@app.route(\"/ourstaff\")\r\ndef ourstaff():\r\n return render_template(\"our-staff.html\")\r\n@app.route(\"/common-issues-and-fixes\")\r\ndef ciaf():\r\n return render_template(\"commonIssuesAndFixes.html\")\r\n\r\n@app.route(\"/iconee\")\r\ndef iconee():\r\n return render_template(\"iconee.html\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)","repo_name":"Weebed-Coder/Unofficial-MDN-Website","sub_path":"Unoffical DDNS Website/Flask Hosting.py","file_name":"Flask Hosting.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36196886178","text":"#! /usr/bin/env python3\n# textFilesToSpreadsheet.pyw\n\n'''\nWrite a program to read in the contents of several text files\nand insert those contents into a spreadsheet, with one line of text per row. \nThe lines of the first text file will be in the cells of column A, \nthe lines of the second text file will be in the cells of column B, and so on.\n'''\n\nimport openpyxl, pprint, sys, pathlib, os\nfrom pathlib import Path\n\n# Open new workbook\nwb = openpyxl.Workbook()\n# Define sheet\nsheet = wb['Sheet']\n\n# Set cwd\ntxtScript_dir = '/' #use the directory containing your text files\nos.chdir(txtScript_dir)\n\n# Define dir to get txt files from\ntxtFile_dir = './textFiles/'\n# Define list to append lists of readlines() to\nreadlines_list = []\n# Loop through each text file in folder to readlines its contents\nfor folderName, subfolders, filenames in os.walk(txtFile_dir):\n for filename in filenames:\n if filename[-4:] == '.txt':\n # Readlines() for each file to get list of strings\n txtFile = open(Path(txtFile_dir, filename))\n readlines = txtFile.readlines()\n # Save each list to a list variable (list of lists)\n readlines_list.append(readlines)\n else:\n continue\npprint.pprint(readlines_list)\n# Loop through the list of lists to map to a new spreadsheet column\nfor i in range(0,len(readlines_list)):\n for j in range(0,len(readlines_list[i])):\n sheet.cell(row=j+1,column=i+1).value = readlines_list[i][j]\n \n# Save workbook\nwb.save('textToFile.xlsx')\n","repo_name":"gc2110/Text-to-Excel-Converter","sub_path":"textFilesToSpreadsheet.pyw","file_name":"textFilesToSpreadsheet.pyw","file_ext":"pyw","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41523599862","text":"import os\nimport config\nimport config.hrnet\nimport config.pretrain\n\nUSE_GPU = config.USE_GPU\nNUM_JOINTS = config.NUM_JOINTS\n# (True, False) for (END_TO_END, SOFTARGMAX) is not possible\nEND_TO_END, SOFTARGMAX = (True, True)\n\n# Term-wise loss coefficients\nLOSS_COEFF = {\n 'hrnet_maps': 10,\n 'cycl_martinez': {\n 'pose_3d': 10,\n 'pose_2d': 1e-4,\n },\n 'bone_symm': 1e-3,\n}\n\n# Martinez Parameters\nTWOD = {\n 'LINEAR_SIZE': 1024,\n 'NUM_BLOCKS': 2,\n 'p': 0.5,\n 'IN_SIZE': NUM_JOINTS * 2,\n 'OUT_SIZE': 17 * 3\n}\nTHREED = {\n 'LINEAR_SIZE': 1024,\n 'NUM_BLOCKS': 2,\n 'p': 0.5,\n 'IN_SIZE': 17 * 3,\n 'OUT_SIZE': NUM_JOINTS * 2\n}\nSKIP_CONNECTION = True\n\n# HRNet Parameters\n# Points to weights stored by pre-training HRN via scripts/trainHRN.py\n# PRETRAINED = \"/cluster/home/voram/mp/PoseNet/log/finetune/FINETUNE-augmentation-Adam-3-02-21\"\nPRETRAINED = os.path.join(config.pretrain.LOG_PATH, config.pretrain.NAME)\nINIT_WEIGHTS = True\nTARGET_TYPE = config.hrnet.TARGET_TYPE\nIMAGE0_SIZE = config.hrnet.IMAGE_SIZE\nHEATMAP_SIZE = config.hrnet.HEATMAP_SIZE\nSIGMA = config.hrnet.SIGMA\nEXTRA = config.hrnet.EXTRA\n\n# Parameters for generating heatmaps from coordinates\nGAUS_KERNEL = 3\nGAUS_STD = 1\n","repo_name":"meetvora/PoseNet","sub_path":"config/posenet.py","file_name":"posenet.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"20134519512","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef main():\n plt.style.use('seaborn-whitegrid')\n\n fig = plt.figure(figsize=(10,6))\n\n ax = fig.add_subplot(projection='3d')\n\n x = np.arange(-5, 5, 0.5)\n y = np.sin(x)\n z = np.cos(x)\n\n ax.set_xticks(np.arange(-5,5,1))\n ax.set_yticks(np.arange(-1,1,0.5))\n ax.set_zticks(np.arange(-1,1,0.5))\n\n ax.plot(x, y, z, color='purple', linestyle=':', label='Sin(x)')\n\n ax.scatter(x, y, z, s=500, color='purple', linestyle=':', marker='*', label='Sin(x)', cmap='viridis')\n\n ax.grid(color = 'blue', alpha = 0.9)\n\n plt.show()\n\n #fig.savefig('./sin.png')\n\nif __name__==\"__main__\":\n main()\n","repo_name":"Adefey/MatplotlibStart","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17337417226","text":"# Project Euler problem 19 solved at 2133KST\n\nfrom Euler.Solution import Solution\nimport Euler.Math as EM\n\ndef daysInMonth(month, year):\n days_30 = [4, 6, 9, 11]\n days_31 = [1, 3, 5, 7, 8, 10, 12]\n if month in days_30: return 30\n if month in days_31: return 31\n\n # Otherwise it's February\n isCentury = year % 100 == 0\n isDivisibleBy4 = year % 4 == 0\n isDivisibleBy400 = year % 400 == 0\n\n isLeapYear = False\n if isDivisibleBy4:\n isLeapYear = True\n if isCentury and not isDivisibleBy400:\n isLeapYear = False\n\n if isLeapYear: return 29\n return 28\n\ndef dayOfWeek(day, month, year):\n # 1 January 1900 was a Monday\n assert year >= 1900\n\n daysSince1Jan1900 = 0\n yearDelta = year\n monthDelta = month\n dayDelta = day\n\n for y in range(yearDelta):\n currentYear = 1900 + y\n for m in range(12):\n for d in range(daysInMonth(m, currentYear)):\n daysSince1Jan1900 += 1\n\n for m in range(monthDelta):\n for d in range(daysInMonth(m, year)):\n daysSince1Jan1900 += 1\n\n for d in range(dayDelta):\n daysSince1Jan1900 += 1\n\n weeks = int(daysSince1Jan1900 / 7.0)\n finalDay = daysSince1Jan1900 - weeks * 7\n return finalDay\n\ndef logic():\n totalSundays = 0\n for y in range(1901, 2000 + 1):\n for m in range(12):\n day = dayOfWeek(1, m, y)\n if day == 0: totalSundays += 1\n\n # I'm not exactly sure why this is needed...\n # Confer with the CPP version to make sure it returns properly\n # Maybe it has to do with the year start range not being 1902? I'm off by one somehow\n totalSundays -= 1\n\n return totalSundays\n\nsolution = Solution(value = 171, placement = 59397)\nsolution.logic = logic\nsolution.run()\n","repo_name":"Parad0x13/ProjectEuler","sub_path":"Solutions/0019_Solved.py","file_name":"0019_Solved.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18081315137","text":"input_file = open(\"advent calendar/inputs/day3input.txt\", \"r\")\ncontent = input_file.read()\nbinary = content.split(\"\\n\")\ninput_file.close()\n\noxigen = binary\nco2 = binary\n\ntemporal = []\noxPos = 0\nwhile len(oxigen) > 1 :\n oximeter = \"\"\n t_oxigen = [''.join(s) for s in zip(*oxigen)]\n for number in t_oxigen:\n ones = 0\n zeros = 0\n for digit in number:\n if digit == '0':\n zeros += 1\n else:\n ones += 1\n if ones > zeros:\n oximeter += \"1\"\n else:\n oximeter += \"0\"\n if oxPos < 12:\n for index, value in enumerate(oxigen):\n if value[oxPos] == oximeter[oxPos]: \n temporal.append(oxigen[index])\n oxPos += 1\n oxigen = temporal\n temporal = []\n \nprint(\"Oxigen LvL \" + str(oxigen))\n\ntemporal = []\ncoPos = 0\nwhile len(co2) > 1 :\n co2meter = \"\"\n t_co2 = [''.join(s) for s in zip(*co2)]\n for number in t_co2:\n ones = 0\n zeros = 0\n for digit in number:\n if digit == '0':\n zeros += 1\n else:\n ones += 1\n if ones > zeros:\n co2meter += \"0\"\n else:\n co2meter += \"1\"\n if coPos < 12:\n for index, value in enumerate(co2):\n if value[coPos] == co2meter[coPos]:\n temporal.append(co2[index])\n coPos += 1\n co2 = temporal\n temporal = []\n\nprint(\"CO2 LVL \" + str(co2))\nprint(\"Life Support Rating \" + str(int(oxigen[0], 2)*int(co2[0], 2)))\n\n\n#parece que no funciona; no da el valor esperado","repo_name":"VRabadan/GeneralCode-Rubbish","sub_path":"Garbage.py","file_name":"Garbage.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31103946728","text":"# You have been given a random integer array/list(ARR) of size N. You are required to find and return the second largest element present in the array/list.\n# If N <= 1 or all the elements are same in the array/list then return -2147483648 or -2 ^ 31(It is the smallest value for the range of Integer)\n\nfrom sys import stdin\n\n\ndef secondLargestElement(arr, n):\n #Your code goes here\n arr.sort()\n i= n - 2\n x = True\n while i>0:\n if arr[i] == arr[i+1]:\n i = i - 1\n continue\n x = True\n else:\n x = False\n break\n if x:\n return -2147483648\n else:\n return arr[i]\n \n\n\n\n#Taking Input Using Fast I/O\ndef takeInput() :\n n = int(stdin.readline().rstrip())\n if n != 0:\n arr = list(map(int, stdin.readline().rstrip().split(\" \")))\n return arr, n\n\n return list(), 0\n\n\n\n#main\nt = int(stdin.readline().rstrip())\n\nwhile t > 0 : \n \n arr, n = takeInput()\n print(secondLargestElement(arr, n))\n\n t -= 1\n","repo_name":"LORDFLACKO0087/Python-Codes","sub_path":"Coding Ninjas/Searching & Sorting/Second Largest in array.py","file_name":"Second Largest in array.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19741994668","text":"n, k = map(int, input().split())\ncon = list(map(int, input().split()))\nleng = len(con)\nrob = [0] * n\n\nlevel = 1\n\ndef rotate():\n temp1 = con[leng-1]\n con[1:] = con[:leng-1]\n rob[1:] = rob[:n-1]\n con[0] = temp1\n rob[0] = 0\n if(rob[n-1]):\n rob[n-1]=0\n\ndef check(idx:int):\n if rob[idx+1] == 0 and con[idx+1] > 0:\n return True\n return False\n\ndef move():\n for i in range(n-2):\n if (rob[n-2-i]):\n idx = n-2-i\n if (check(idx)):\n con[idx+1] -= 1\n rob[idx+1] = rob[idx]\n rob[idx] = 0\n \n if(rob[n-1]):\n rob[n-1]=0\n\nwhile (True):\n rotate()\n move()\n if con[0]>0 and rob[0] ==0:\n con[0] -= 1\n rob[0] = level\n if (con.count(0)>=k):\n break\n level += 1\n\nprint(level)\n","repo_name":"SeongrokKim/python-practice","sub_path":"backjoon/삼성 SW 역량 테스트 기출 문제/컨베이어 벨트 위의 로봇.py","file_name":"컨베이어 벨트 위의 로봇.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17077963932","text":"from __future__ import division, print_function\n__author__ = 'maartenbreddels'\nimport os\nimport sys\nimport collections\nimport numpy as np\nimport logging\nimport vaex\nimport vaex.utils\nimport vaex.execution\nimport vaex.export\nimport vaex.hdf5.dataset\nfrom vaex.column import ColumnStringArrow\n\nmax_length = int(1e5)\n\non_rtd = os.environ.get('READTHEDOCS', None) == 'True'\ntry:\n import h5py\nexcept:\n if not on_rtd:\n raise\n\nlogger = logging.getLogger(\"vaex.hdf5.export\")\n\nmax_int32 = 2**31-1\n\ndef export_hdf5_v1(dataset, path, column_names=None, byteorder=\"=\", shuffle=False, selection=False, progress=None, virtual=True):\n \"\"\"\n :param DatasetLocal dataset: dataset to export\n :param str path: path for file\n :param lis[str] column_names: list of column names to export or None for all columns\n :param str byteorder: = for native, < for little endian and > for big endian\n :param bool shuffle: export rows in random order\n :param bool selection: export selection or not\n :param progress: progress callback that gets a progress fraction as argument and should return True to continue,\n or a default progress bar when progress=True\n :param: bool virtual: When True, export virtual columns\n :return:\n \"\"\"\n\n if selection:\n if selection == True: # easier to work with the name\n selection = \"default\"\n # first open file using h5py api\n with h5py.File(path, \"w\") as h5file_output:\n\n h5data_output = h5file_output.require_group(\"data\")\n # i1, i2 = dataset.current_slice\n N = len(dataset) if not selection else dataset.selected_length(selection)\n if N == 0:\n raise ValueError(\"Cannot export empty table\")\n logger.debug(\"virtual=%r\", virtual)\n logger.debug(\"exporting %d rows to file %s\" % (N, path))\n # column_names = column_names or (dataset.get_column_names() + (list(dataset.virtual_columns.keys()) if virtual else []))\n column_names = column_names or dataset.get_column_names(virtual=virtual, strings=True)\n\n logger.debug(\"exporting columns(hdf5): %r\" % column_names)\n for column_name in column_names:\n dtype = dataset.data_type(column_name)\n if column_name in dataset.get_column_names(strings=True):\n column = dataset.columns[column_name]\n shape = (N,) + column.shape[1:]\n else:\n shape = (N,)\n if dtype.type == np.datetime64:\n array = h5file_output.require_dataset(\"/data/%s\" % column_name, shape=shape, dtype=np.int64)\n array.attrs[\"dtype\"] = dtype.name\n else:\n try:\n array = h5file_output.require_dataset(\"/data/%s\" % column_name, shape=shape, dtype=dtype.newbyteorder(byteorder))\n except:\n logging.exception(\"error creating dataset for %r, with type %r \" % (column_name, dtype))\n array[0] = array[0] # make sure the array really exists\n random_index_name = None\n column_order = list(column_names) # copy\n if shuffle:\n random_index_name = \"random_index\"\n while random_index_name in dataset.get_column_names():\n random_index_name += \"_new\"\n shuffle_array = h5file_output.require_dataset(\"/data/\" + random_index_name, shape=(N,), dtype=byteorder + \"i8\")\n shuffle_array[0] = shuffle_array[0]\n column_order.append(random_index_name) # last item\n h5data_output.attrs[\"column_order\"] = \",\".join(column_order) # keep track or the ordering of columns\n\n # after this the file is closed,, and reopen it using out class\n dataset_output = vaex.hdf5.dataset.Hdf5MemoryMapped(path, write=True)\n\n column_names = vaex.export._export(dataset_input=dataset, dataset_output=dataset_output, path=path, random_index_column=random_index_name,\n column_names=column_names, selection=selection, shuffle=shuffle, byteorder=byteorder,\n progress=progress)\n import getpass\n import datetime\n user = getpass.getuser()\n date = str(datetime.datetime.now())\n source = dataset.path\n description = \"file exported by vaex, by user %s, on date %s, from source %s\" % (user, date, source)\n if dataset.description:\n description += \"previous description:\\n\" + dataset.description\n dataset_output.copy_metadata(dataset)\n dataset_output.description = description\n logger.debug(\"writing meta information\")\n dataset_output.write_meta()\n dataset_output.close()\n return\n\n\ndef export_hdf5(dataset, path, column_names=None, byteorder=\"=\", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True, parallel=True):\n \"\"\"\n :param DatasetLocal dataset: dataset to export\n :param str path: path for file\n :param lis[str] column_names: list of column names to export or None for all columns\n :param str byteorder: = for native, < for little endian and > for big endian\n :param bool shuffle: export rows in random order\n :param bool selection: export selection or not\n :param progress: progress callback that gets a progress fraction as argument and should return True to continue,\n or a default progress bar when progress=True\n :param: bool virtual: When True, export virtual columns\n :return:\n \"\"\"\n\n if selection:\n if selection == True: # easier to work with the name\n selection = \"default\"\n # first open file using h5py api\n with h5py.File(path, \"w\") as h5file_output:\n\n h5table_output = h5file_output.require_group(\"/table\")\n h5table_output.attrs[\"type\"] = \"table\"\n h5columns_output = h5file_output.require_group(\"/table/columns\")\n # i1, i2 = dataset.current_slice\n N = len(dataset) if not selection else dataset.selected_length(selection)\n if N == 0:\n raise ValueError(\"Cannot export empty table\")\n logger.debug(\"virtual=%r\", virtual)\n logger.debug(\"exporting %d rows to file %s\" % (N, path))\n # column_names = column_names or (dataset.get_column_names() + (list(dataset.virtual_columns.keys()) if virtual else []))\n column_names = column_names or dataset.get_column_names(virtual=virtual, strings=True)\n\n logger.debug(\"exporting columns(hdf5): %r\" % column_names)\n sparse_groups = collections.defaultdict(list)\n sparse_matrices = {} # alternative to a set of matrices, since they are not hashable\n for column_name in list(column_names):\n sparse_matrix = dataset._sparse_matrix(column_name)\n if sparse_matrix is not None:\n # sparse columns are stored differently\n sparse_groups[id(sparse_matrix)].append(column_name)\n sparse_matrices[id(sparse_matrix)] = sparse_matrix\n continue\n dtype = dataset.data_type(column_name)\n shape = (N, ) + dataset._shape_of(column_name)[1:]\n h5column_output = h5columns_output.require_group(column_name)\n if vaex.array_types.is_string_type(dtype):\n # TODO: if no selection or filter, we could do this\n # if isinstance(column, ColumnStringArrow):\n # data_shape = column.bytes.shape\n # indices_shape = column.indices.shape\n # else:\n\n byte_length = dataset[column_name].str.byte_length().sum(selection=selection)\n if byte_length > max_int32:\n dtype_indices = 'i8'\n else:\n dtype_indices = 'i4'\n\n data_shape = (byte_length, )\n indices_shape = (N+1, )\n\n array = h5column_output.require_dataset('data', shape=data_shape, dtype='S1')\n if byte_length > 0:\n array[0] = array[0] # make sure the array really exists\n\n index_array = h5column_output.require_dataset('indices', shape=indices_shape, dtype=dtype_indices)\n index_array[0] = index_array[0] # make sure the array really exists\n\n null_value_count = N - dataset.count(dataset[column_name], selection=selection)\n if null_value_count > 0:\n null_shape = ((N + 7) // 8, ) # TODO: arrow requires padding right?\n null_bitmap_array = h5column_output.require_dataset('null_bitmap', shape=null_shape, dtype='u1')\n null_bitmap_array[0] = null_bitmap_array[0] # make sure the array really exists\n\n array.attrs[\"dtype\"] = 'str'\n # TODO: masked support ala arrow?\n else:\n if dtype.kind in 'mM':\n array = h5column_output.require_dataset('data', shape=shape, dtype=np.int64)\n array.attrs[\"dtype\"] = dtype.name\n elif dtype.kind == 'U':\n # numpy uses utf32 for unicode\n char_length = dtype.itemsize // 4\n shape = (N, char_length)\n array = h5column_output.require_dataset('data', shape=shape, dtype=np.uint8)\n array.attrs[\"dtype\"] = 'utf32'\n array.attrs[\"dlength\"] = char_length\n else:\n try:\n array = h5column_output.require_dataset('data', shape=shape, dtype=dtype.numpy.newbyteorder(byteorder))\n except:\n logging.exception(\"error creating dataset for %r, with type %r \" % (column_name, dtype))\n del h5columns_output[column_name]\n column_names.remove(column_name)\n continue\n array[0] = array[0] # make sure the array really exists\n\n data = dataset.evaluate(column_name, 0, 1, parallel=False)\n if dataset.is_masked(column_name):\n mask = h5column_output.require_dataset('mask', shape=shape, dtype=bool)\n mask[0] = mask[0] # make sure the array really exists\n random_index_name = None\n column_order = list(column_names) # copy\n if shuffle:\n random_index_name = \"random_index\"\n while random_index_name in dataset.get_column_names():\n random_index_name += \"_new\"\n shuffle_array = h5columns_output.require_dataset(random_index_name + \"/data\", shape=(N,), dtype=byteorder + \"i8\")\n shuffle_array[0] = shuffle_array[0]\n column_order.append(random_index_name) # last item\n h5columns_output.attrs[\"column_order\"] = \",\".join(column_order) # keep track or the ordering of columns\n\n sparse_index = 0\n for sparse_matrix in sparse_matrices.values():\n columns = sorted(sparse_groups[id(sparse_matrix)], key=lambda col: dataset.columns[col].column_index)\n name = \"sparse\" + str(sparse_index)\n sparse_index += 1\n # TODO: slice columns\n # sparse_matrix = sparse_matrix[:,]\n sparse_group = h5columns_output.require_group(name)\n sparse_group.attrs['type'] = 'csr_matrix'\n ar = sparse_group.require_dataset('data', shape=(len(sparse_matrix.data), ), dtype=sparse_matrix.dtype)\n ar[0] = ar[0]\n ar = sparse_group.require_dataset('indptr', shape=(len(sparse_matrix.indptr), ), dtype=sparse_matrix.indptr.dtype)\n ar[0] = ar[0]\n ar = sparse_group.require_dataset('indices', shape=(len(sparse_matrix.indices), ), dtype=sparse_matrix.indices.dtype)\n ar[0] = ar[0]\n for i, column_name in enumerate(columns):\n h5column = sparse_group.require_group(column_name)\n h5column.attrs['column_index'] = i\n\n # after this the file is closed,, and reopen it using out class\n dataset_output = vaex.hdf5.dataset.Hdf5MemoryMapped(path, write=True)\n df_output = vaex.dataframe.DataFrameLocal(dataset_output)\n\n column_names = vaex.export._export(dataset_input=dataset, dataset_output=df_output, path=path, random_index_column=random_index_name,\n column_names=column_names, selection=selection, shuffle=shuffle, byteorder=byteorder,\n progress=progress, sort=sort, ascending=ascending, parallel=parallel)\n dataset_output._freeze()\n # We aren't really making use of the metadata, we could put this back in some form in the future\n # import getpass\n # import datetime\n # user = getpass.getuser()\n # date = str(datetime.datetime.now())\n # source = dataset.path\n # description = \"file exported by vaex, by user %s, on date %s, from source %s\" % (user, date, source)\n # if dataset.description:\n # description += \"previous description:\\n\" + dataset.description\n # dataset_output.copy_metadata(dataset)\n # dataset_output.description = description\n # logger.debug(\"writing meta information\")\n # dataset_output.write_meta()\n dataset_output.close()\n return\n","repo_name":"vaexio/vaex","sub_path":"packages/vaex-hdf5/vaex/hdf5/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":13123,"program_lang":"python","lang":"en","doc_type":"code","stars":8057,"dataset":"github-code","pt":"53"}
+{"seq_id":"35848778544","text":"#importing Libraries\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\n#Creating the CNN layers\nclassifier = Sequential()\nclassifier.add(Conv2D(32,(3,3),input_shape = (64,64,3), activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2,2)))\nclassifier.add(Flatten())\nclassifier.add(Dense(units = 128, activation = 'relu'))\nclassifier.add(Dense(units = 1, activation = 'sigmoid'))\n\n#Compiling the CNN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n#ImageDataGenerator for Image Augumentation\nfrom keras.preprocessing.image import ImageDataGenerator\n\n#rescaling the train and test data\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n#defining the train and test set\ntraining_set = train_datagen.flow_from_directory('../input/dataset/dataset/training_set',\n target_size=(64, 64),\n batch_size=16,\n class_mode='binary')\n\ntest_set = test_datagen.flow_from_directory('../input/dataset/dataset/test_set',\n target_size=(64, 64),\n batch_size=16,\n class_mode='binary')\n\n#fitting the model\nhistory = classifier.fit_generator(training_set,\n steps_per_epoch=8000,\n epochs=10,\n validation_data=test_set,\n validation_steps=2000)\n \n#predicting the Image as dog or cat \nimport numpy as np\nfrom keras.preprocessing import image\ntest_image = image.load_img('../input/dataset/dataset/sample/cat_or_dog_2.jpg',target_size = (64,64))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\nresult = classifier.predict(test_image)\n\n\ntraining_set.class_indices\n\nif result[0][0] == 0 :\n prediction = 'cat'\nelse:\n prediction = 'dog'\n#getting the final answer \nprint(prediction)\n","repo_name":"Paarth3098/Dogs-vs-Cats-image-classifier","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28982306114","text":"import sys\n\nfrom multiprocessing import Pool\nimport operation\n\nsys.path.append('../')\nimport mycroft.base as mc\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\n\nclass Task(mc.BaseDataObject):\n is_trigger = True\n\n def update(self, trigger_name: str):\n self.triggered_set.add(trigger_name)\n if len(self.triggered_set) >= len(self.triggers):\n self.triggered_set = set()\n self.run_pipeline()\n\n def run_pipeline(self):\n logger.info(\"{} started pipeline\".format(self.name))\n self.run_operations()\n\n def add_operation(self, operation: operation.Operation):\n self.pipeline.add_worker(operation)\n\n def build_operations(self, operation_doc, operation_dict):\n operations = {'operation': (operation_dict[operation_doc['operation']]) if operation_doc['operation'] else None,\n 'sub_operations': []}\n for sub_operation_doc in operation_doc['sub_operations']:\n operations['sub_operations'].append(self.build_operations(sub_operation_doc, operation_dict))\n return operations\n\n def run_operations(self):\n self.run_operation_node(self.operations)\n\n def run_operation_node(self, node):\n logger.info('run operation {} in task {}'.format(node['operation'], self.name))\n if node['operation']:\n node['operation'].execute()\n sub_operations = node['sub_operations']\n if sub_operations:\n if len(sub_operations) == 1:\n self.run_operation_node(sub_operations[0])\n else:\n sub_operation_pool = Pool(len(sub_operations))\n for sub_operation in sub_operations:\n sub_operation_pool.apply_async(self.run_operation_node, args=(sub_operation,))\n sub_operation_pool.close()\n sub_operation_pool.join()\n logger.info('waiting for {} sub operations of task {}......'.format(len(sub_operations), self.name))\n # for sub_operation_node in node['sub_operations']:\n # self.run_operation_node(sub_operation_node)\n\n def __init__(self, task_doc, trigger_dict, operation_dict):\n self.name = task_doc['name']\n self.triggers = task_doc['triggers']\n for trigger_str in task_doc['triggers']:\n trigger = trigger_dict[trigger_str]\n trigger.subscribe(self)\n self.operations = self.build_operations(task_doc['operations'], operation_dict)\n self.triggered_set = set()\n\n # self.triggers = kwargs.get(\"triggers\", [])\n # operations_dict = kwargs.get(\"operations\", [])\n # self.pipeline = operation.OperationPipeline()\n","repo_name":"Mycroft-Water/mycroft","sub_path":"local_app/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"73978160488","text":"import requests\n\nfrom requests.exceptions import RequestException\n\n\ndef get_request():\n\tr = requests.get(\"https://jsonplaceholder.typicode.com/posts\")\n\n\tr.raise_for_status() # NEW! NEW! NEW! NEW!\n\tjson_data = r.json()\n\n\tprint(json_data)\n\treturn json_data\n\n\ndef post_request():\n\tdata = {\n\t\t\"title\": 'foo',\n\t\t\"body\": 'bar',\n\t\t\"userId\": 1\n\t}\n\n\theaders = {\n\t\t\"Content-type\": \"application/json; charset=UTF-8\"\n\t}\n\n\tr = requests.post(\n\t\t\"https://jsonplaceholder.typicode.com/posts\",\n\t\tjson=data,\n\t\theaders=headers\n\t)\n\n\tjson_data = r.json()\n\n\tprint(json_data)\n\treturn json_data\n\n\ntry:\n\tget_request()\nexcept RequestException as e:\n\tprint(e)","repo_name":"jayaike/Tutorials","sub_path":"Python/Make Requests/make_requests_python.py","file_name":"make_requests_python.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"21410585637","text":"# -*- coding: utf-8 -*-\n#encoding=utf-8\n\nimport string\nimport sys\nfrom urllib import quote\nimport re\nimport scrapy\nfrom scrapy.selector import Selector\nfrom scrapy.spiders import Spider\nimport items\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\npositionsname = ['java',\n '销售',\n '会计',\n '房地产',\n '行政',\n 'php',\n '平面设计',\n '外贸',\n '产品经理',\n '财务',\n '人事',\n '金融']\n\nbaseurl = 'http://search.51job.com/'\n\nclass job51Spider(Spider):\n name = 'job51'\n allowed_domains = []\n start_urls=[]\n for positions in positionsname:\n urlkeyword = quote(positions, 'UTF-8')\n start_urls.append(baseurl + 'list/000000,000000,0000,00,9,99,'+urlkeyword +',2,1.html?lang=c°reefrom=99&stype=&workyear=99&cotype=99&jobterm=99&companysize=99&radius=-1&address=&lonlat=&postchannel=&list_type=&ord_field=&curr_page=&dibiaoid=0&landmark=&welfare=')\n\n def parse(self, response):\n sel = Selector(response)\n pagecountObj=sel.xpath('//html/body/div[2]/div[6]/div/div/div/span[1]/text()').extract()[0]\n pagecount=str(pagecountObj)\n pagecount=string.replace(pagecount,'共','',-1)\n pagecount=string.replace(pagecount,'页,到第','',-1)\n keywordobj=sel.xpath(\".//*[@id='kwdselectid']/@value\").extract()[0];\n keyword=str(keywordobj);\n for i in range(1, int(pagecount)+1):\n pageurl=baseurl+'jobsearch/search_result.php?fromJs=1&jobarea=000000%2C00&district=000000&funtype=0000&industrytype=00&issuedate=9&providesalary=99&keyword='+quote(keyword, 'UTF-8')+'&keywordtype=2&curr_page='+str(i)+'&lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&list_type=0&fromType=14&dibiaoid=0&confirmdate=9'\n yield scrapy.Request(pageurl, callback=self.parse_page)\n\n def parse_page(self, response):\n sel = Selector(response)\n joblist = sel.xpath(\".//*[@id='resultList']/div[@class='el']/p/span/a/@href\").extract();\n companynames=sel.xpath(\".//*[@id='resultList']/div[@class='el']/span/a\");\n for index,job in enumerate(joblist):\n joburl=str(job)\n companyname=companynames[index]\n companynametext=companyname.xpath('string(.)').extract()[0]\n item = items.Job51Item()\n item[\"link\"]=joburl\n item[\"companyname\"] = companynametext\n yield scrapy.Request(joburl, meta={'item': item}, callback=self.parse_job)\n\n def parse_job(self, response):\n item = response.meta['item']\n sel = Selector(response)\n id=str(sel.xpath(\".//*[@id='hidJobID']/@value\").extract()[0])\n name= str(sel.xpath(\".//div[@class='cn']/*[local-name() = 'h1']/text()\").extract()[0])\n city= str(sel.xpath(\".//div[@class='cn']/span/text()\").extract()[0])\n try:\n salary = str(sel.xpath(\".//div[@class='cn']/strong/text()\").extract()[0])\n except:\n salary = ''\n try:\n time_range=str(sel.xpath(\".//*[@class='i1']/parent::*/text()\").extract()[0])\n except:\n time_range = ''\n\n try:\n edu=str(sel.xpath(\".//*[@class='i2']/parent::*/text()\").extract()[0])\n except:\n edu = ''\n\n try:\n count=str(sel.xpath(\".//*[@class='i3']/parent::*/text()\").extract()[0])\n except:\n count = ''\n\n try:\n updatetime=str(sel.xpath(\".//*[@class='i4']/parent::*/text()\").extract()[0])\n except:\n updatetime = ''\n\n try:\n lang=str(sel.xpath(\".//*[@class='i5']/parent::*/text()\").extract()[0])\n except:\n lang = ''\n\n companydescription = sel.xpath(\".//div[@class='tmsg inbox']/text()\").extract()\n allDescs = \"\"\n for allitem in companydescription:\n allDescs = allDescs + str(allitem)\n allDescs = string.replace(allDescs, \"\\t\", \"\", -1)\n allDescs = string.replace(allDescs, \"\\r\\n\", \"\", -1)\n\n benefitlist=sel.xpath(\".//*[@class='jtag inbox']/p/span/text()\").extract()\n benefit=\"\"\n for benfititem in benefitlist:\n benefit=benefit+str(benfititem)+\",\"\n\n alllist=sel.xpath(\".//div[@class='bmsg job_msg inbox']/text()\").extract()\n allDesc=\"\"\n for allitem in alllist:\n allDesc=allDesc+str(allitem)\n respstart=allDesc.rfind(\"职位描述:\")\n if respstart==-1:\n respstart=0\n respend=allDesc.rfind(\"任职要求:\")\n if respend==-1:\n respend=allDesc.rfind(\"岗位要求:\")\n if respend==-1:\n respend=allDesc.rfind(\"任职资格:\")\n if respend==-1:\n respend=len(allDesc)-1\n responsibility=str(allDesc[respstart:respend])\n responsibility=string.replace(responsibility,\"\\t\",\"\",-1)\n responsibility=string.replace(responsibility,\"\\r\\n\",\"\",-1)\n qualstart=allDesc.rfind(\"任职要求:\")\n if qualstart==-1:\n qualstart=allDesc.rfind(\"岗位���求:\")\n if qualstart==-1:\n qualstart=allDesc.rfind(\"任职资格:\")\n if qualstart==-1:\n qualstart=len(allDesc)\n qualend=len(allDesc)+1\n qualification=str(allDesc[qualstart:qualend])\n qualification=string.replace(qualification,\"\\t\",\"\",-1)\n qualification=string.replace(qualification,\"\\r\\n\",\"\",-1)\n\n item[\"email\"] = ''\n rex = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}'\n try:\n email = str(sel.xpath(\".//div[@class='bmsg job_msg inbox']/text()\").extract());\n except:\n email = ''\n xx = re.compile(rex)\n for j in xx.findall(email):\n item[\"email\"] = j\n\n item[\"contact_phonenum\"] = ''\n rex_num =r'1[358]\\d{9}|147\\d{8}|(0\\d{2,3})?\\d{7,8}'\n #rex_num = r'(^1\\d{10})'\n try:\n contact_phonenum = str(sel.xpath(\".//div[@class='bmsg job_msg inbox']/text()\").extract());\n except:\n contact_phonenum = ''\n xx = re.compile(rex_num)\n for b in xx.findall(contact_phonenum):\n item['contact_phonenum'] =b\n\n companylist=sel.xpath(\"//html/body/div[2]/div[2]/div[2]/div/div[1]/p[1]/a/@href\").extract();\n for companyurl in companylist:\n companyurls = str(companyurl)\n item['linker'] = companyurls\n yield scrapy.Request(companyurls, meta={'item': item}, callback=self.parse_company)\n\n\n\n item[\"id\"] = id\n item[\"name\"] = name\n item[\"city\"] = city\n item[\"salary\"] = salary\n item[\"time_range\"] = time_range\n item[\"edu\"] = edu\n item[\"count\"] = count\n item[\"updatetime\"] = updatetime\n item[\"lang\"] = lang\n item[\"benefit\"] = benefit\n item[\"companydescription\"] = allDescs\n item[\"responsibility\"] = responsibility\n item[\"qualification\"] = qualification\n\n def parse_company(self, response):\n item = response.meta['item']\n sel = Selector(response)\n address= str(sel.xpath(\".//p[@class='fp']/text()\").extract()[1])\n address = string.replace(address, \"\\t\", \"\", -1)\n address = string.replace(address, \"\\r\\n\", \"\", -1)\n\n item[\"address\"] = address\n\n\n yield item\n\n\n","repo_name":"melo1993/job51","sub_path":"jobspider/spiders/job51.py","file_name":"job51.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20649807839","text":"# question_strategies/linear2var.py\n# In-built imports\nfrom typing import Type\n\n# Third-party imports\n\n# Sys-Paths for Relative Imports\nimport sys\nfrom os.path import dirname, abspath\npackage_path = dirname(dirname(abspath(__file__)))\nif(package_path not in sys.path): sys.path.insert(0, package_path)\n\n# Relative imports\nfrom question_strategies import question\n\nclass Linear2VarQuestionType1(question.QuestionType):\n Q_TYPE = \"Linear_2_Var_Type1\"\n INIT_VARIABLES= {}\n def __init__(self, number_generator_cls:question.numGenType) -> None:\n super().__init__()\n self.number_generator_obj = number_generator_cls\n \n def generate_question(self):\n format_string = \"{}x + {}y + {} = 0;{}x + {}y + {} = 0;\"\n p1 = [self.number_generator_obj.number() for _ in range(2)]\n p2 = [self.number_generator_obj.number() for _ in range(2)]\n sol = [ self.number_generator_obj.number() for _ in range(2)]\n c1 = self.generate_coefficient(p1, sol)\n c2 = self.generate_coefficient(p2, sol)\n question_string = format_string.format(*c1, *c2)\n return question.Question(question_string, sol, self.Q_TYPE.title())\n\n def generate_coefficient(self, point, ans_point):\n a = (ans_point[1] - point[1])\n b = (ans_point[0] - point[0]) * -1\n c = -(point[0] * (ans_point[1] - point[1])) + (point[1] * (ans_point[0] - point[0]))\n if(a < 0):\n a*= -1\n b*= -1\n c*= -1\n return [a, b, c]\n\nTYPE_LOOKUP:dict[str, Type[question.QuestionType]] = {\n \"normal\": Linear2VarQuestionType1\n}","repo_name":"jagrutgala/SEM-VI-Project","sub_path":"math_gen_api/question_strategies/linear2var.py","file_name":"linear2var.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20315677623","text":"import os\nimport pickle as pkl\nimport typing as t\nimport warnings\n\nimport sh\nimport torch\nfrom torch import nn\nfrom tqdm import tqdm\n\n\nclass GloVe(nn.Module):\n _file_path: str # location to read world embeddings from\n _size: int # dimension of an embedding\n _words: t.List[str] # list of world possible words\n _vectors: torch.nn.Parameter # 2D matrix; first dimension is the word id corresponding to the list 'words', second dimension is the embedding vector of length 'size'\n\n def __init__(self, file_path: str, size: int, load_precached: bool = True):\n super(GloVe, self).__init__()\n self._file_path = file_path\n self._size = size\n self._words = []\n\n if self._file_path.startswith(\"s3://\"):\n new_path = self._file_path.replace(\"s3://\", \"/tmp/\")\n logger.info(f\"Syncing {self._file_path} to {new_path}\")\n os.makedirs(os.path.dirname(new_path), exist_ok=True)\n sh.aws.s3.sync(os.path.dirname(self._file_path), os.path.dirname(new_path))\n self._file_path = new_path\n\n precached_file_name = os.path.splitext(os.path.basename(self._file_path))\n precached_file_name = \"\".join([precached_file_name[0], \".pkl\"])\n precached_file_path = os.path.join(os.path.dirname(self._file_path), precached_file_name)\n if not os.path.exists(precached_file_path):\n load_precached = False\n\n if load_precached:\n with open(precached_file_path, \"rb\") as f:\n data = pkl.load(f)\n assert self._size == data[\"size\"]\n assert os.path.basename(self._file_path) == os.path.basename(data[\"file_path\"])\n self._words = data[\"words\"]\n self._vectors = torch.nn.Parameter(data[\"vectors\"])\n else:\n vectors = []\n with open(self._file_path, \"r\") as f:\n lines = f.readlines()\n for line in tqdm(lines, desc=\"Loading word embedding\"):\n line = line.split(\" \")\n word, vector = line[0], torch.Tensor([float(value) for value in line[1:]])\n assert word not in self._words\n assert len(vector) == self._size\n self._words.append(word)\n vectors.append(vector)\n self._vectors = torch.nn.Parameter(torch.stack(vectors, dim=0))\n try:\n print(f\"Writing embedding results to {precached_file_path}\")\n with open(precached_file_path, \"wb\") as f:\n pkl.dump(\n {\n \"vectors\": self._vectors,\n \"words\": self._words,\n \"size\": self._size,\n \"file_path\": self._file_path,\n },\n f,\n )\n except:\n warnings.warn(\"Cannot write the embeddings data\")\n\n def vectorize(self, word: str) -> torch.Tensor:\n return self._vectors[self._words.index(word.lower())]\n\n def encode_single(self, word: str) -> torch.Tensor:\n try:\n return self.vectorize(word)\n except ValueError:\n\n def encode_split(word_str: str, splitters: t.Collection[str]):\n word_str = [word_str]\n for splitter in splitters:\n word_out = []\n for w in word_str:\n word_out.extend(w.split(splitter))\n word_str = word_out\n representations = [self.vectorize(w) for w in word_str]\n return sum(representations) / len(representations)\n\n return encode_split(word, [\" \", \"-\"])\n\n def encode_list(self, words: t.Sequence[str]) -> torch.Tensor:\n return torch.stack([self.encode_single(word) for word in words])\n\n def forward(self, inp: t.Union[t.Sequence[str], str]) -> torch.Tensor:\n if isinstance(inp, str):\n return self.encode_single(inp)\n else:\n return self.encode_list(inp)\n\n def closest_word(self, vector: torch.Tensor) -> t.Tuple[str, torch.Tensor]:\n \"\"\"\n returns the word with closest embedding representation and its PMF\n \"\"\"\n dot_products = self._vectors.matmul(vector)\n index = dot_products.argmax()\n values = torch.softmax(dot_products, dim=0)\n return self._words[index], values\n\n\nif __name__ == \"__main__\":\n embeddings = GloVe(file_path=\"/home/krm/datasets/glove/glove.6B.100d.txt\", size=100)\n test_words = [\"the\", \"welcome\", \"hello\"]\n test_vector = torch.rand([100])\n for w in test_words:\n print(embeddings(w))\n print(embeddings.closest_word(test_vector))\n","repo_name":"kareem-metwaly/glidenet","sub_path":"models/glove_word_embedding.py","file_name":"glove_word_embedding.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"53"}
+{"seq_id":"41221929849","text":"'''List Comprehensions 연습문제\n1. 50쪽 넘는 책 목록 만들기\n2. 추천유무가 False인 책 목록 만들기\n3. 출판사 목록 만들기 (중복되는 이름은 제거)\n'''\n\nbooks = list() # 책 리스트 선언\n# 책 목록 만들기\nbooks.append({'제목':'Python', '출판사':'A 출판','쪽수':51, '추천유무':False})\nbooks.append({'제목':'Java', '출판사':'B 출판','쪽수':15, '추천유무':True})\nbooks.append({'제목':'C++', '출판사':'A 출판','쪽수':100, '추천유무':True})\nbooks.append({'제목':'PHP', '출판사':'B 출판','쪽수':89, '추천유무':False})\nbooks.append({'제목':'JSP','출판사':'C 출판','쪽수':30, '추천유무':True})\n\n# 각 문제별 필요한 리스트 선언\npage_list = list()\nrecommend_list = list()\npub_name_set = set() # 중복 제거 목적\n\n# general\nfor book in books:\n if book['쪽수']>50:\n page_list.append(book['제목'])\n if book['추천유무'] is False:\n recommend_list.append(book['제목'])\n pub_name_set.add(book['출판사'])\n\nprint(f'50쪽 넘는 책 {page_list}')\nprint(f'추천하지 않는 책 {recommend_list}')\nprint(f'출판사 목록(중복제거) {pub_name_set}')\n\n# list comprehension\nmany_page_list = [book['제목'] for book in books if book['쪽수']>50]\nprint(f'250쪽 넘는 책 {page_list}')\nrecommend_list = [book['제목'] for book in books if book['추천유무'] is False]\nprint(f'추천하는 책 {recommend_list}')\npub_name_set = set([book['출판사'] for book in books])\nprint(f'출판사 목록(중복제거) {pub_name_set}')\n\n'''\n출력결과\n250쪽 넘는 책 ['Python', 'C++', 'PHP']\n추천하는 책 ['Python', 'PHP']\n출판사 목록(중복제거) {'C 출판', 'B 출판', 'A 출판'}\n'''\n","repo_name":"hrcony8753/python_basic","sub_path":"exercise/11List_Comprehensions.py","file_name":"11List_Comprehensions.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14610359679","text":"'''\n api.py\n Adapted from api.py by Jeff Ondich\n Authors: Carl Zhang and Alex Falk\n 20 Nov 2022\n\n'''\nimport sys\nimport flask\nimport json\nimport config\nimport psycopg2\n\napi = flask.Blueprint('api', __name__)\n\ndef get_connection():\n ''' Returns a connection to the database described in the\n config module. May raise an exception as described in the\n documentation for psycopg2.connect. '''\n return psycopg2.connect(database=config.database,\n user=config.user,\n password=config.password)\n\n# Movies to display on results page\n@api.route('/movies//')\ndef get_movies(movie_string, page):\n offset = page * 50\n query = '''SELECT movies.id, movies.movie_title, movies.release_year, images.image_link, movies.overview \n FROM movies, images \n WHERE movies.movie_title ILIKE CONCAT('%%', %s, '%%') \n AND movies.id = images.movie_id \n ORDER BY movies.popularity DESC\n OFFSET %s;'''\n movie_list = []\n try:\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(query, (movie_string, offset))\n for row in cursor:\n movie = {'id':int(row[0]),\n 'movie_title':row[1],\n 'release_year':row[2],\n 'image_link':row[3],\n 'overview':row[4]\n }\n movie_list.append(movie)\n cursor.close()\n connection.close()\n except Exception as e:\n print(e, file=sys.stderr)\n\n\n return json.dumps(movie_list)\n\n# Get movie info for a specific movie\n@api.route('/movie_bio/')\ndef get_movie_bio_info(movie_id):\n query = '''SELECT movies.movie_title, movies.release_year, images.image_link, movies.overview, movies.mubi_url, movies.title_lang, movies.orig_lang, movies.runtime, movies.adult, profit.budget, profit.revenue, movies.director_id, movies.genre\n FROM movies, images, profit \n WHERE movies.id = %s\n AND movies.id = images.movie_id\n AND movies.id = profit.movie_id;'''\n movie_bio_string = []\n try:\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(query, (movie_id,))\n for row in cursor:\n movie_bio = {'movie_title':row[0],\n 'release_year':row[1],\n 'image_link':row[2],\n 'overview':row[3],\n 'mubi_url':row[4],\n 'title_lang':row[5],\n 'orig_lang':row[6],\n 'runtime':row[7],\n 'adult':row[8],\n 'budget':int(row[9]),\n 'revenue':int(row[10]),\n 'director_id':row[11],\n 'genre':eval(row[12])\n }\n movie_bio_string.append(movie_bio)\n cursor.close()\n connection.close()\n except Exception as e:\n print(e, file=sys.stderr)\n\n return json.dumps(movie_bio_string)\n\n# Get director given ID\n@api.route('directors/')\ndef get_director(director_id):\n query = '''SELECT directors.name, directors.director_url\n FROM directors\n WHERE directors.id = %s;'''\n director_array = []\n try:\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(query, (director_id,))\n for row in cursor:\n directors = {'name':row[0],\n 'director_url':row[1]\n }\n director_array.append(directors)\n cursor.close()\n connection.close()\n except Exception as e:\n print(e, file=sys.stderr)\n \n \n return json.dumps(director_array)\n\n@api.route('/movies/////')\ndef get_movies_filters(movie_string, start_year, end_year, genres, page):\n # QUERY WILL INCLUDE MORE DATA (average_reviews, genres?)\n offset = page * 50\n query = '''SELECT movies.id, movies.movie_title, movies.release_year, images.image_link, movies.overview, movies.genre\n FROM movies, images\n WHERE movies.movie_title ILIKE CONCAT('%%', %s, '%%') \n AND movies.genre ILIKE CONCAT('%%', %s, '%%') \n AND movies.release_year >= %s\n AND movies.release_year <= %s\n AND movies.id = images.movie_id\n ORDER BY movies.popularity DESC\n OFFSET %s;'''\n movie_list = []\n try:\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(query, (movie_string, genres, start_year, end_year, offset))\n for row in cursor:\n movie = {'id':int(row[0]),\n 'movie_title':row[1],\n 'release_year':row[2],\n 'image_link':row[3],\n 'overview':row[4],\n 'genres':row[5]\n }\n movie_list.append(movie)\n cursor.close()\n connection.close()\n\n except Exception as e:\n print(e, file=sys.stderr)\n\n return json.dumps(movie_list)\n\n","repo_name":"czhang2884/cs257","sub_path":"webapp/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72271421287","text":"def format_msg(msg, color):\n color_dict = {\n \"black\": 30,\n \"b\": 30,\n \"red\": 31,\n \"r\": 31,\n \"green\": 32,\n \"g\": 32,\n }\n if isinstance(color, str):\n color = color_dict.get(color, None)\n assert color, \"Supported colors are: {}\".format(color_dict.keys())\n return \"\\033[%dm%s\\033[0m\" % (color, msg)\n","repo_name":"xingyun-xy/cap","sub_path":"changan_plugin_pytorch/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31300663782","text":"import math\nimport random\n\nimport pyray as pr\nimport pymunk as pm\nfrom pymunk.vec2d import Vec2d as Vec2\n\nfrom human import Human\n\nfrom utils import calc_boyancy, SHIP_CATEGORY, SHIP_HULL_GROUP\n\n\nclass Ship():\n texture: pr.Texture2D\n body: pm.Body\n humans: list[Human]\n\n def __init__(self, game_data: dict, position: Vec2, space: pm.Space, decks: list[tuple[float, float]]):\n self.texture = game_data[\"textures\"][\"boat\"]\n self.body = pm.Body()\n self.body.position = position\n hull_size = Vec2(self.texture.width*1.8, self.texture.height*1.9)\n # body_shape = pm.Poly.create_box(self.body, hull_size, 0)\n body_shape = pm.Poly(self.body, [\n (-hull_size.x/2, hull_size.y/2), \n (-hull_size.x/2, -hull_size.y*0.4/2),\n (hull_size.x/2, hull_size.y/2),\n (hull_size.x/2, -hull_size.y*0.4/2)\n ])\n body_shape.density = 0.001\n body_shape.friction = 5\n body_shape.filter = pm.ShapeFilter(group=SHIP_HULL_GROUP, categories=SHIP_CATEGORY)\n\n weight_shape = pm.Poly(self.body, [\n (-hull_size.x/5, hull_size.y*2/8), \n (-hull_size.x/5, hull_size.y*3/8),\n (hull_size.x/5, hull_size.y*3/8),\n (hull_size.x/5, hull_size.y*2/8)\n ])\n weight_shape.density = 0.1\n weight_shape.filter = pm.ShapeFilter(group=SHIP_HULL_GROUP, categories=SHIP_CATEGORY)\n\n space.add(self.body, body_shape, weight_shape)\n\n self.humans = []\n for i in range(random.randint(2, 4)):\n self.humans.append(\n Human(game_data, \n Vec2(position.x - hull_size.x/2.2 + random.random() * hull_size.x*0.8, \n position.y - hull_size.y/2), \n space)\n )\n \n def update(self, dt: float):\n # apply drag\n self.body.velocity *= 1-(1 * dt)\n self.body.angular_velocity *= 1-(3 * dt)\n # apply gravity\n self.body.apply_force_at_world_point(Vec2(0, 6000 * dt * self.body.mass), self.body.position)\n # apply buoyancy\n area, center = calc_boyancy(self.body)\n force = Vec2(0, area * -60 * dt)\n self.body.apply_force_at_world_point(force, center)\n\n # self.body.velocity = Vec2(0, 0)\n # self.body.angular_velocity = 0\n for human in self.humans:\n human.update(dt)\n \n def draw(self, mouse_pos: Vec2):\n for human in self.humans:\n human.draw(mouse_pos)\n pr.draw_texture_pro(self.texture, \n (0, 0, self.texture.width, self.texture.height),\n (self.body.position.x, self.body.position.y, self.texture.width * 2, self.texture.height * 2),\n (self.texture.width, self.texture.height),\n self.body.angle * 180 / math.pi,\n pr.WHITE\n )","repo_name":"System10111/python-squid","sub_path":"src/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35639378296","text":"import sys\nimport os\n\nttt_pkg = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\npath_2_nodes = ttt_pkg + '/nodes'\npath_2_scripts = ttt_pkg + '/scripts'\n\nsys.path.insert(1, path_2_nodes)\nsys.path.insert(1, path_2_scripts)\n\nimport rospy\nimport tf2_ros\nimport tf2_msgs.msg\n\n# ROS Data Types\nfrom std_msgs.msg import ByteMultiArray\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import TransformStamped\nfrom geometry_msgs.msg import PoseArray\n\n# Custom Tools\n# from Realsense_tools import *\nfrom transformations import *\nfrom toolbox_shape_detector import *\nfrom cv_bridge import CvBridge, CvBridgeError\n\n# System Tools\nimport time\nfrom math import pi, radians, sqrt\n\n# Ref\n# http://wiki.ros.org/tf2/Tutorials/Writing%20a%20tf2%20listener%20%28Python%29\n# http://docs.ros.org/en/jade/api/geometry_msgs/html/msg/Transform.html\n\ndef transformToPose(transform):\n # Location Vector\n pose_goal = []\n point = transform\n x, y, z = point[:-1, 3]\n x = np.asscalar(x)\n y = np.asscalar(y)\n z = np.asscalar(z)\n\n # Quant Calculation Support Variables\n # Only find trace for the rotational matrix.\n t = np.trace(point) - point[3, 3]\n r = np.sqrt(1 + t)\n\n # Primary Diagonal Elements\n Qxx = point[0, 0]\n Qyy = point[1, 1]\n Qzz = point[2, 2]\n\n # Quant Calculation\n qx = np.copysign(0.5 * np.sqrt(1 + Qxx - Qyy - Qzz), point[2, 1] - point[1, 2])\n qy = np.copysign(0.5 * np.sqrt(1 - Qxx + Qyy - Qzz), point[0, 2] - point[2, 0])\n qz = np.copysign(0.5 * np.sqrt(1 - Qxx - Qyy + Qzz), point[1, 0] - point[0, 1])\n qw = 0.5 * r\n\n pose_goal = [x, y, z, qx, qy, qz, qw]\n return pose_goal\n\ndef findDis(pt1x, pt1y, pt2x, pt2y):\n # print('Entered Rectangle_support: findDis function')\n x1 = float(pt1x)\n x2 = float(pt2x)\n y1 = float(pt1y)\n y2 = float(pt2y)\n dis = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** (0.5)\n return dis\n\ndef prepare_tiles():\n # Values for 3D printed tictactoe board\n centerxDist = 0.0635\n # centeryDist = -0.0635\n centeryDist = 0.0635 \n # removing negative sign fixed board variable, so computer correctly stores location of O blocks\n\n pieceHeight = 0.03\n\n \"\"\"\n tictactoe board order assignment:\n [0 1 2]\n [3 4 5]\n [6 7 8]\n \"\"\" \n tf = transformations()\n # centers =[[-centerxDist ,centeryDist,pieceHeight],[0,centeryDist,pieceHeight],[centerxDist,centeryDist,pieceHeight],\n # [-centerxDist,0,pieceHeight],[0,0,pieceHeight],[centerxDist,0,pieceHeight],\n # [-centerxDist,-centeryDist,pieceHeight],[0,-centeryDist,pieceHeight],[centerxDist,-centeryDist,pieceHeight]]\n centers =[[centerxDist ,centeryDist,pieceHeight],[0,centeryDist,pieceHeight],[-centerxDist,centeryDist,pieceHeight],\n [centerxDist,0,pieceHeight],[0,0,pieceHeight],[-centerxDist,0,pieceHeight],\n [centerxDist,-centeryDist,pieceHeight],[0,-centeryDist,pieceHeight],[-centerxDist,-centeryDist,pieceHeight]]\n #^ puts the +1(X) & -1(O) in the correct spot for the computer to store them.\n\n tictactoe_center_list = np.array(centers,dtype=np.float)\n rot_default = np.identity((3))\n new_list = []\n\n for vector in tictactoe_center_list:\n item = np.matrix(vector)\n new_list.append( tf.generateTransMatrix(rot_default, item) )\n\n return new_list\n\nclass circle_state_publisher():\n \"\"\"\n Custom tictactoe publisher class that finds circles on image and identifies if/where the circles are on the board.\n \"\"\"\n\n def __init__(self, circle_state_annotation, circle_board_state,camera2circle,tfBuffer):\n\n # Inputs\n\n self.circle_state_annotation = circle_state_annotation\n self.circle_board_state = circle_board_state\n self.pub_camera2circle = camera2circle\n self.tfBuffer = tfBuffer\n self.tf = transformations()\n self.shapeDetect = TOOLBOX_SHAPE_DETECTOR()\n # camera_tile_annotation: publishes the numbers & arrows displayed on the image\n\n # Tools\n self.bridge = CvBridge()\n\n def runner(self, data):\n \"\"\"\n Callback function for image subscriber\n :param data: Camera data input from subscriber\n \"\"\"\n try:\n\n pose_data = rospy.wait_for_message(\"tile_locations\",PoseArray,timeout = None)\n\n xyList = [[] for i in range(9)]\n scale = 1.14 / 1280\n\n # Convert Image to CV2 Frame\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n img = cv_image.copy()\n\n xList = []\n yList = []\n\n for j in range(9):\n xList.append(pose_data.poses[j].position.x)\n yList.append(pose_data.poses[j].position.y)\n\n # print('xList',xList)\n # print('yList',yList)\n board = [0,0,0,0,0,0,0,0,0]\n # array for game board 0 -> empty tile, 1 -> X, -1 -> O\n \n centers, circles_img = self.shapeDetect.detectCircles(img, radius=5, tolerance=10)\n \n try:\n msg_img = self.bridge.cv2_to_imgmsg(circles_img, 'bgr8')\n except CvBridgeError as e:\n print(e)\n\n self.circle_state_annotation.publish(msg_img)\n\n scaledCenter = [0, 0]\n\n scale = 1.14/1280\n\n circlesXlist = []\n circlesYlist = []\n\n for i in range(len(centers)):\n\n scaledCenter[0] = (centers[i][0] - 640) * scale\n scaledCenter[1] = (centers[i][1] - 360) * scale\n \n tileTranslation = np.array(\n [[.8], [-scaledCenter[0]], [-scaledCenter[1]]]) \n\n y_neg90 = np.array([[ 0, 0, -1],\n [0, 1, 0],\n [1, 0, 0]])\n\n z_neg90 = np.array([[0,1,0],\n [-1,0,0],\n [0,0,1]])\n camera_rot = np.dot(y_neg90,z_neg90)\n\n tileRotationMatrix = np.dot(camera_rot,np.identity((3)))\n\n # Build new tf matrix\n\n tf_camera2circle = np.zeros((4, 4))\n tf_camera2circle[0:3, 0:3] = tileRotationMatrix\n tf_camera2circle[0:3, 3:4] = tileTranslation\n tf_camera2circle[3, 3] = 1\n\n pose_goal = transformToPose(tf_camera2circle)\n\n ## Publish Board Pose\n camera2circle_msg = TransformStamped()\n camera2circle_msg.header.frame_id = 'camera_link'\n camera2circle_msg.child_frame_id = 'circles {}'.format(i)\n camera2circle_msg.header.stamp = rospy.Time.now()\n\n camera2circle_msg.transform.translation.x = pose_goal[0]\n camera2circle_msg.transform.translation.y = pose_goal[1]\n camera2circle_msg.transform.translation.z = pose_goal[2]\n\n camera2circle_msg.transform.rotation.x = pose_goal[3]\n camera2circle_msg.transform.rotation.y = pose_goal[4]\n camera2circle_msg.transform.rotation.z = pose_goal[5]\n camera2circle_msg.transform.rotation.w = pose_goal[6]\n\n camera2circle_msg = tf2_msgs.msg.TFMessage([camera2circle_msg])\n \n # Publish\n self.pub_camera2circle.publish(camera2circle_msg) \n\n robot_link = 'base_link'\n target_link = 'circles {}'.format(i)\n\n fixed2circle = self.tfBuffer.lookup_transform(robot_link, target_link, rospy.Time())\n circlesXlist.append(fixed2circle.transform.translation.x)\n circlesYlist.append(fixed2circle.transform.translation.y)\n\n \n\n for i in range(len(centers)):\n distanceFromCenter = findDis(circlesXlist[i], circlesYlist[i], xList[4], yList[4])\n\n if distanceFromCenter < .150: # 100 * sqrt2 -now in meters\n closest_index = None\n closest = 100\n for j in range(9):\n distance = findDis(circlesXlist[i], circlesYlist[i], xList[j], yList[j])\n\n if distance < .03 and distance < closest:\n # this creates a boundary just outside the ttt board of 40 pixels away from each tile\n # any circle within this boundary is likely to be detected as a piece in one of the 9 tiles\n closest = distance\n closest_index = j\n # print('closest_index',closest_index)\n if closest_index is not None:\n board[closest_index] = -1\n # cv2.circle(img, centers[i], 15, (0, 200, 40), 7)\n\n print(\"Circle {} is in tile {}.\".format(i, closest_index))\n else:\n print(\"Circle {} is not on the board\".format(i))\n \n\n msg_circle = ByteMultiArray()\n msg_circle.data = board\n self.circle_board_state.publish(msg_circle)\n rospy.loginfo(msg_circle)\n\n except rospy.ROSInterruptException:\n exit()\n except KeyboardInterrupt:\n exit()\n except CvBridgeError as e:\n print(e)\n\n\n#####################################################\n# MAIN\ndef main():\n \"\"\"\n Circle Finder.\n This script should only be launched via a launch script.\n circle_state_annotation: draws game board circles on top of camera tile annotation image\n circle_game_state: outputs game state as board code (for o's only)\n TODO: add X detection capabilities\n\n \"\"\"\n\n # Setup Node\n rospy.init_node('circle_state', anonymous=False)\n rospy.loginfo(\">> Circle Game State Node Successfully Created\")\n\n # Setup Publishers\n pub_circle_state_annotation = rospy.Publisher(\"circle_state_annotation\", Image, queue_size=20)\n pub_camera2circle = rospy.Publisher(\"/tf\", tf2_msgs.msg.TFMessage, queue_size=20)\n\n pub_circle_board_state = rospy.Publisher(\"circle_board_state\", ByteMultiArray, queue_size=20)\n\n # Setup Listeners\n tfBuffer = tf2_ros.Buffer()\n listener = tf2_ros.TransformListener(tfBuffer)\n cs_callback = circle_state_publisher(pub_circle_state_annotation,pub_circle_board_state,pub_camera2circle,tfBuffer)\n image_sub = rospy.Subscriber(\"/camera/color/image_raw\", Image, cs_callback.runner)\n\n # Auto-Run until launch file is shutdown\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"OSU-AIMS/tic-tac-toe","sub_path":"nodes/circle_state_publisher.py","file_name":"circle_state_publisher.py","file_ext":"py","file_size_in_byte":10669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"1334254832","text":"import requests\nimport json\n\nclass State:\n error = \"error\"\n pending = \"pending\"\n failure = \"failure\"\n success = \"success\"\n\nclass GithubCommon:\n def __init__(self, context):\n self.context = context\n\n # branch: name of the branch\n def get_branch(self, branch):\n r = requests.get(\"{api}/repos/{owner}/{repo}/branches/{branch}\"\n .format(\n api=self.context.github_api,\n owner=self.context.owner,\n repo=self.context.repo,\n branch=branch))\n\n if r.ok:\n return json.loads(r.text)\n else:\n return None\n\n # sha: sha hash of commit\n # status_ok: True/False\n # desc_extention: additional text to \"rebased/not rebased\"\n def set_commit_status(self, sha, status_ok, desc_extention=\"\"):\n if status_ok:\n state = State.success\n desc = self.context.rebased + desc_extention\n else:\n state = State.error\n desc = self.context.not_rebased + desc_extention\n\n data = {\n \"state\": state,\n \"target_url\": self.context.target_url,\n \"description\": desc,\n \"context\": self.context.botname\n }\n\n r = requests.post(\"{api}/repos/{owner}/{repo}/statuses/{sha}\"\n .format(\n api=self.context.github_api,\n owner=self.context.owner,\n repo=self.context.repo,\n sha=sha),\n json=data,\n headers={\n \"Authorization\": \"token {token}\".format(\n token=self.context.token\n )\n })\n\n return r.ok\n\n def get_open_pull_requests(self):\n data = {\n \"state\": \"open\"\n }\n\n r = requests.get(\"{api}/repos/{owner}/{repo}/pulls\"\n .format(\n api=self.context.github_api,\n owner=self.context.owner,\n repo=self.context.repo,\n ),\n json=data)\n\n if r.ok:\n return json.loads(r.text)\n else:\n return None\n","repo_name":"Warchant/is-branch-rebased","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"70852782247","text":"#!/usr/bin/env python\nfrom collections import deque\nimport os\nimport argparse\nimport mspa\nimport archive\nimport stories\n\n#parse args\ncmdline = argparse.ArgumentParser(description='Download MS Paint Adventures stories in an archival format.', add_help=True)\narguments = cmdline.add_argument_group('positional arguments')\narguments.add_argument('story', default='6', nargs='?', type=str, choices=['1','2','4','5','6','ryanquest'],\n help='Story to download. Default 6 for Homestuck')\ncmdline.add_argument('-p','--page', type=int, default=0, nargs='?', \n help='Page on which to start download. Default story start')\ncmdline.add_argument('-d','--directory', type=str, default='MSPA', nargs='?', \\\n help='Location for downloaded files. Default MSPA/')\n\nargs = cmdline.parse_args()\n\nif args.page == 0:\n args.page = stories.first_page(args.story)\n\narchive.init(args.story, args.directory)\ndownloader = mspa.SiteReader(args.story)\n\npages = [('{0:06}'.format(args.page), None)]\nfor (page, source) in pages:\n next_pages = downloader.get_page(page, source)\n pages.extend([(p, s) for (p, s) in next_pages if p not in set(list(zip(*pages))[0])])\n\narchive.finalise()\n","repo_name":"gulbanana/msparch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"86534306829","text":"'''Test file dedicated to overall tests.'''\n# pylint: disable=import-error\n\nfrom configparser import ConfigParser\n\nimport pytest # pylint: disable=unused-import\nimport requests\n\n# Init config parser\nconfig = ConfigParser()\nconfig.read('./conf/env.conf')\n\n# Create a requests session\nreq_session = requests.Session()\n\ndef test_alive():\n '''Is the website alive?'''\n response = req_session.get(config['APP']['url'])\n assert response.status_code is 200\n assert 'login' in response.text","repo_name":"sn0b4ll/kinderbasar","sub_path":"tests/test_overall.py","file_name":"test_overall.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20266173487","text":"from control.connect import *\nimport time\n\n\nclass Control:\n def __init__(self, opening: str, time_in, engine, protocol: str, scrt, memory=2):\n self.opening = opening\n self.time = time_in\n self.engine = engine\n self.protocol = protocol\n self.scrt = scrt\n self.memory = int(memory)\n\n def printf(self, *txt, endl='\\n'):\n try:\n txt = [str(i) for i in txt]\n self.scrt.insert('insert', ' '.join(txt) + endl)\n except:\n pass\n\n @staticmethod\n def pktool(move, q):\n if q == 0:\n x = move[0]\n y = move[1:]\n return str(ord(x) - 97) + ',' + str(15 - int(y))\n if q == 1:\n x = int(move.split(',')[0])\n y = int(move.split(',')[1])\n return str(chr(x + 97)) + str(int(15 - y))\n\n def gomocup(self, opening, time_in, engine):\n init(engine, self.scrt)\n timematch(time_in, self.memory)\n put('SWAP2BOARD')\n for i in opening:\n put(i)\n time.sleep(0.4)\n put('DONE')\n move = spswap().split()\n kill_engine()\n if move != 'SWAP':\n move = ' '.join([self.pktool(i, 1) for i in move])\n self.printf(f'--> Output: {move}')\n \n\n def yixin(self, opening, time_in, engine):\n init(engine, self.scrt)\n put('INFO timeout_turn ' + str(time_in * 1000))\n put('INFO timeout_match ' + str(time_in * 1000))\n put('INFO time_left ' + str(time_in * 1000))\n put('INFO max_node 500000000') # Level 10\n put('INFO max_depth 225')\n put('INFO caution_factor 4')\n put('INFO thread_num 8') # Set thread\n put('INFO thread_split_depth 20')\n put(f'INFO hash_size {1024 ** 2 * self.memory}')\n put('INFO pondering 0')\n put('INFO vcthread 0') # Maybe Global Search\n put('INFO rule 1')\n put('START 15 15')\n put('yxboard')\n for i in range(len(opening)):\n if len(opening) % 2 == i % 2:\n put(opening[i] + ',1')\n else:\n put(opening[i] + ',2')\n time.sleep(0.1)\n put('done')\n put('yxswap2step2')\n move = sp_yixin().split()\n kill_engine()\n if move != 0:\n move = ' '.join([self.pktool(i, 1) for i in move])\n printf(f'--> Output: {move}')\n\n def execute(self):\n opening = self.opening.split()\n try:\n lst = [self.pktool(i, 0) for i in opening]\n except:\n self.printf('An error occur while convert opening to Piskvork coord.')\n return\n if 'GOMOCUP' in self.protocol.upper():\n self.gomocup(lst, self.time, self.engine)\n elif 'YIXIN' in self.protocol.upper():\n self.yixin(lst, self.time, self.engine)\n","repo_name":"nguyencongminh090/SWAP2GUI","sub_path":"control/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26178884949","text":"# AI Face Recognition with Jetson Nano\n# Using OpenCV and face_recognition to identify known faces\n# Mike Soniat\n# 2022\n\nimport face_recognition\nimport cv2\nimport os\nimport pickle \n\nEncodings=[]\nNames=[]\n\n# comment out training code after saving with Pickle\n# train on known images\nprint(\"Training...\")\nknown_dir = '/home/mikes/Desktop/PyPro/faceRecognizer/demoImages/known'\nfor root, dirs, files in os.walk(known_dir):\n for file in files: \n path = os.path.join(root, file)\n name = os.path.splitext(file)[0]\n print(name)\n person = face_recognition.load_image_file(path)\n encoding = face_recognition.face_encodings(person)[0]\n \n # load arrays\n Encodings.append(encoding)\n Names.append(name)\n\n# save training data using pickle\nwith open('train.pkl','wb') as f:\n pickle.dump(Names, f)\n pickle.dump(Encodings, f)\n\n# read training data from pickled file\nwith open('train.pkl','rb') as f:\n Names = pickle.load(f)\n Encodings = pickle.load(f)\n\n# set font for name labels\nfont=cv2.FONT_HERSHEY_SIMPLEX\n\n# step through unknown files\nunknown_dir = '/home/mikes/Desktop/PyPro/faceRecognizer/demoImages/unknown'\nfor root, dirs, files in os.walk(unknown_dir):\n for file in sorted(files):\n print(file)\n testImagePath = os.path.join(root, file)\n testImage = face_recognition.load_image_file(testImagePath)\n\n # find faces in unknown pic and encode\n face_positions = face_recognition.face_locations(testImage)\n allEncodings = face_recognition.face_encodings(testImage, face_positions)\n\n # convert pic to BGR (for OpenCV)\n testImage = cv2.cvtColor(testImage, cv2.COLOR_RGB2BGR)\n\n # step through faces and names in unknown pic\n for (top,right,bottom,left), face_encoding in zip(face_positions, allEncodings):\n name = 'Unknown Person'\n matches = face_recognition.compare_faces(Encodings, face_encoding)\n if True in matches:\n first_match_index = matches.index(True)\n name = Names[first_match_index]\n\n cv2.rectangle(testImage, (left,top),(right,bottom),(0,0,255), 2)\n cv2.putText(testImage, name, (left,top-6), font, 1, (0,255,255), 2)\n\n # show next image in window\n cv2.imshow(file, testImage)\n cv2.moveWindow(file,0,0)\n \n # wait for user to press a key\n cv2.waitKey(0)\n cv2.destroyAllWindows() \n","repo_name":"mikesoniat/face-recognizer-jetson-nano","sub_path":"src/AI Face Recognizer.py","file_name":"AI Face Recognizer.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"34045520912","text":"\"\"\"\nAuthor: Alejandro Sanchez Uribe\nDate: 13 Dec 19\n\"\"\"\n\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def __repr__(self):\n return str(self.value)\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def __str__(self):\n cur_head = self.head\n out_string = \"\"\n while cur_head:\n out_string += str(cur_head.value) + \" -> \"\n cur_head = cur_head.next\n return out_string\n\n def append(self, value):\n\n if self.head is None:\n self.head = Node(value)\n return\n\n node = self.head\n while node.next:\n node = node.next\n\n node.next = Node(value)\n\n def size(self):\n size = 0\n node = self.head\n while node:\n size += 1\n node = node.next\n\n return size\n\n\ndef llist_to_set(llist):\n result = set()\n\n node = llist.head\n\n while node:\n result.add(node.value)\n node = node.next\n\n return result\n\n\ndef union(llist_1, llist_2):\n lst1 = list(llist_to_set(llist_1))\n lst2 = list(llist_to_set(llist_2))\n lst1.extend(lst2)\n\n union_lst = list(set(lst1))\n union_llist = LinkedList()\n\n for element in union_lst:\n union_llist.append(element)\n\n return union_llist\n\n\ndef intersection(llist_1, llist_2):\n lst1 = list(llist_to_set(llist_1))\n lst2 = list(llist_to_set(llist_2))\n\n intersect_lst = [element for element in lst1 if element in lst2]\n\n intersect_llist = LinkedList()\n\n for element in intersect_lst:\n intersect_llist.append(element)\n\n return intersect_llist\n\n\n# Test case 1\n\nlinked_list_1 = LinkedList()\nlinked_list_2 = LinkedList()\n\nelement_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21]\nelement_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1]\n\nfor i in element_1:\n linked_list_1.append(i)\n\nfor i in element_2:\n linked_list_2.append(i)\n\nprint(union(linked_list_1, linked_list_2))\n# prints 1, 2, 3, 4, 6, 9, 11, 21, 32, 35, 65\nprint(intersection(linked_list_1, linked_list_2))\n# prints 4, 6, 21\n\n# Test case 2\n\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23]\nelement_2 = [1, 7, 8, 9, 11, 21, 1]\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint(union(linked_list_3, linked_list_4))\n# prints 1, 2, 3, 4, 6, 7, 8, 9, 11, 21, 23, 35, 65\nprint(intersection(linked_list_3, linked_list_4))\n# prints an empty list\n\n\n# Test case 3\n\nlinked_list_5 = LinkedList()\nlinked_list_6 = LinkedList()\n\nelement_1 = [None, 2]\nelement_2 = [None, None, None, None, None, 1]\n\nfor i in element_1:\n linked_list_5.append(i)\n\nfor i in element_2:\n linked_list_6.append(i)\n\nprint(union(linked_list_5, linked_list_6))\n# prints 1, 2, None\nprint(intersection(linked_list_5, linked_list_6))\n# prints None\n\n# Test case 4\nprint(union(linked_list_1, linked_list_5))\n# prints 2, 3, 4, 6, 21, 35, 65, None\nprint(intersection(linked_list_1, linked_list_5))\n# prints 2\n\n# Test case 5\n\nlinked_list_7 = LinkedList()\n\nelement_1 = []\n\nfor i in element_1:\n linked_list_7.append(i)\n\nprint(union(linked_list_6, linked_list_7))\n# prints 1, None\nprint(intersection(linked_list_6, linked_list_7))\n# prints an empty list\n","repo_name":"alex-sa-ur/python-data-structures-and-algorithms","sub_path":"P1/problem_6.py","file_name":"problem_6.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7086287111","text":"# Say you have an array for which the ith element \n# is the price of a given stock on day i.\n# If you were only permitted to complete as many transactions as you like \n# (i.e., buy one and sell one share of the stock), \n# design an algorithm to find the maximum profit.\n# Note that you cannot sell a stock before you buy one.\n\n# Input: [7,1,5,3,6,4]\n# Output: 7\n# Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), \n# profit = 5-1 = 4.\n# Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\n\n# Input: [7,6,4,3,1]\n# Output: 0\n# Explanation: In this case, no transaction is done, i.e. max profit = 0.\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n buy = prices[0]\n profit = 0\n for i in range(1,len(prices)):\n if prices[i] < buy:\n buy = prices[i]\n else:\n profit += (prices[i]-buy)\n buy = prices[i]\n return profit","repo_name":"Chencx901/leetcode","sub_path":"problems/Best Time to Buy and Sell Stock II.py","file_name":"Best Time to Buy and Sell Stock II.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14347463397","text":"import os\nimport shutil\n\nM = 'val'\n\nnum = 0\n\nimg_thick_path = '/remote-home/share/DAOD_Dataset/More_Dense_FoggyCityscape/thicker_foggy/'+M+'/JPEGImages/'\n\nimg_002_path = '/remote-home/share/Cityscapes/newfoggy_cyc/images/0.02/'+M+'/'\n\nimg_001_path = '/remote-home/share/Cityscapes/newfoggy_cyc/images/0.01/'+M+'/'\n\nimg_0005_path = '/remote-home/share/Cityscapes/newfoggy_cyc/images/0.005/'+M+'/'\n\nlb_path_train = '/remote-home/share/Cityscapes/all_class/foggycityscapes/labels/'+M+'/'\n\naim_base_path = '/remote-home/share/Cityscapes/newfoggy_cyc/images/all_1_thickonly/'\n\naim_img_path_train = aim_base_path+M+'/'\n\naim_lb_path_train = aim_base_path.replace(\"images\",\"labels\")+M+'/'\n\nif not os.path.exists(aim_base_path.replace(\"images\",\"labels\")):\n os.mkdir(aim_base_path.replace(\"images\",\"labels\"))\nif not os.path.exists(aim_base_path):\n os.mkdir(aim_base_path)\nif not os.path.exists(aim_img_path_train):\n os.mkdir(aim_img_path_train)\nif not os.path.exists(aim_lb_path_train):\n os.mkdir(aim_lb_path_train)\n\n#处理train\ndir = os.listdir(img_002_path)\nfor i in dir:\n aim_dir = aim_img_path_train+i\n if not os.path.exists(aim_dir):\n os.mkdir(aim_dir)\n sub_dir = os.listdir(img_002_path+i)\n for j in sub_dir:\n num += 1\n print(num)\n img_name = j.split('.')[0]\n new_lb_name = j.split('.')[0]\n ###############转移img\n old_img_path_002 = img_002_path + i + '/' + img_name + '.02.png'\n old_img_path_001 = img_001_path + i + '/' + img_name + '.01.png'\n old_img_path_0005 = img_0005_path + i + '/' + img_name + '.005.png'\n old_img_path_thick = img_thick_path + 'target_' + img_name + '.02.jpg'\n\n new_img_path_002 = aim_dir + '/' + img_name + '02.png'\n new_img_path_001 = aim_dir + '/' + img_name + '01.png'\n new_img_path_0005 = aim_dir + '/' + img_name + '005.png'\n new_img_path_thick = aim_dir + '/' + img_name + 'thick.png'\n ###############转移lb\n old_lb_path = lb_path_train+ i + '/' + img_name + '.02.txt'\n aim_lb_dir = aim_lb_path_train+i\n if not os.path.exists(aim_lb_dir):\n os.mkdir(aim_lb_dir)\n new_lb_path_002 = aim_lb_dir + '/' + new_lb_name + '02.txt'\n new_lb_path_001 = aim_lb_dir + '/' + new_lb_name + '01.txt'\n new_lb_path_0005 = aim_lb_dir + '/' + new_lb_name + '005.txt'\n new_lb_path_thick = aim_lb_dir + '/' + new_lb_name + 'thick.txt'\n\n # #复制\n # shutil.copy(old_img_path_002,new_img_path_002)\n shutil.copy(old_img_path_thick,new_img_path_thick)\n # shutil.copy(old_img_path_001,new_img_path_001)\n # shutil.copy(old_img_path_0005,new_img_path_0005)\n\n # shutil.copy(old_lb_path,new_lb_path_002)\n # shutil.copy(old_lb_path,new_img_path_001)\n # shutil.copy(old_lb_path,new_img_path_0005)\n shutil.copy(old_lb_path,new_lb_path_thick)\n","repo_name":"caiyancheng/BFDA","sub_path":"make_foggy_city/make_thick_foggy.py","file_name":"make_thick_foggy.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"30686929583","text":"\"\"\"\nGET current pollution data from AQICN API\ndefault location = toronto\n\"\"\"\n\nimport requests\nfrom todata.data.credentials import AQICN_API_KEY\n\n# default location\nCITY = \"toronto\"\n\ndef aqicn_pollution(location=CITY, api_key=AQICN_API_KEY):\n \n try:\n # AQICN Call API\n api_call = f\"https://api.waqi.info/feed/{location}/?token={api_key}\"\n response = requests.get(api_call)\n response.raise_for_status()\n\n # convert json to dictionary\n return response.json()\n \n except Exception as ex:\n raise ex","repo_name":"jackjyliu/project","sub_path":"todata/data/api/aqicn.py","file_name":"aqicn.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38389733720","text":"from utility.module import *\r\nfrom utility.constant import *\r\n\r\nfrom machine_learning.model.base_model import *\r\nfrom machine_learning.tools.metrics import *\r\nfrom machine_learning.tools.tree_visualize import *\r\n\r\n\r\nclass MyLightGBM(BaseMyModel):\r\n def __init__(self, i) -> None:\r\n super().__init__(i)\r\n self.name = LIGHTGBM\r\n self.gsr_flg = False\r\n self.bayse_flg = False\r\n \r\n\r\n def fit(self, x, y):\r\n if self.gsr_flg:\r\n self.mdl = lgb.LGBMRegressor(\r\n learning_rate = self.gsr.best_params_['learning_rate'],\r\n max_depth = self.gsr.best_params_['max_depth'],\r\n num_leaves = self.gsr.best_params_['num_leaves'],\r\n reg_alpha = self.gsr.best_params_['reg_alpha'],\r\n reg_lambda = self.gsr.best_params_['reg_lambda'],\r\n min_child_samples = self.gsr.best_params_['min_child_samples'],\r\n random_state = self.gsr.best_params_['random_state'])\r\n elif self.bayse_flg:\r\n self.mdl = lgb.LGBMRegressor(**self.best_params, n_estimators=500)\r\n else:\r\n self.mdl = lgb.LGBMRegressor()\r\n self.mdl.fit(x, y)\r\n\r\n def bayse_search(self, x, y):\r\n base_param = {\r\n 'objective':'regression',\r\n 'metric':'rmse',\r\n 'verbosity': -1,\r\n 'boosting_type': 'gbdt',\r\n 'random_state': g.seed,\r\n 'learning_rate': 0.1\r\n }\r\n searcher = BayseSearch(x, y, base_param)\r\n self.best_params = searcher.fit()\r\n self.bayse_flg = True\r\n\r\n def grid_search(self, x, y):\r\n self.search_params = {\r\n 'learning_rate' : [0.01, 0.05, 0.1], # [0.1], #[0.01, 0.05, 0.1],\r\n 'max_depth' : [5, 7, 9], #[5], #[5,7,9],\r\n 'num_leaves' : [7, 15, 31], #[100], #[7, 15, 31],\r\n 'reg_alpha' : [0, 2, 5], #[0.1], #[0, 2, 5],\r\n 'reg_lambda' : [0, 2, 5], # [0.1], #[0, 2, 5],\r\n 'min_child_samples' : [20, 30, 50], # [20], #[20, 30, 50]\r\n 'random_state' : [g.seed]\r\n }\r\n kf = KFold(n_splits=n_split)\r\n self.gsr = GridSearchCV(\r\n lgb.LGBMRegressor(),\r\n self.search_params,\r\n scoring=make_scorer(RMSE, greater_is_better=False),\r\n cv = kf,\r\n n_jobs = -1,\r\n verbose=3\r\n )\r\n self.gsr.fit(x, y)\r\n self.gsr_flg = True\r\n\r\n\r\nclass BayseSearch():\r\n def __init__(self, data_train, label_train, base_param):\r\n self.data_train = data_train\r\n self.label_train = label_train\r\n self.base_param = base_param\r\n\r\n def objective(self, trial):\r\n params = {\r\n 'num_leaves':trial.suggest_int('num_leaves', 3, 400), # 200\r\n 'max_depth':trial.suggest_int('max_depth', 3, 12),\r\n 'reg_alpha':trial.suggest_float('reg_alpha', 1e-5, 3.0),\r\n 'reg_lambda':trial.suggest_float('reg_lambda', 1e-5, 3.0),\r\n 'colsample_bytree':trial.suggest_float('colsample_bytree', 0.1, 1.0),\r\n 'subsample':trial.suggest_float('subsample', 0.1, 1.0),\r\n 'subsample_freq':trial.suggest_int('subsample_freq', 0, 5),\r\n 'min_child_samples':trial.suggest_int('min_child_samples', 1, 100),\r\n }\r\n params.update(self.base_param)\r\n \r\n model = lgb.LGBMRegressor(**params, n_estimators=500)\r\n kf = KFold(n_splits=n_split, shuffle=True, random_state=g.seed)\r\n scores = cross_validate(model, X=self.data_train, y=self.label_train, scoring=make_scorer(RMSE), cv=kf)\r\n print(f\"val score:{scores['test_score'].mean()}\")\r\n return scores['test_score'].mean()\r\n\r\n def fit(self):\r\n study = optuna.create_study(direction='minimize',sampler=optuna.samplers.TPESampler(seed=g.seed))\r\n study.optimize(self.objective, n_trials=n_trial)\r\n\r\n best_params = study.best_params\r\n \r\n params = self.base_param\r\n params.update(best_params)\r\n print(study.best_value)\r\n return params","repo_name":"tokyotech-nakatalab/ApproximateFrankWolfe","sub_path":"machine_learning/model/lightgbm_regression.py","file_name":"lightgbm_regression.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70272461288","text":"\"\"\"\nKevin\n1-09-2017\nReading list program: Show user unread/read books and to add new book as well.\nhttps://github.com/CP1404-JCUS/a1-reading-list-kevinjuliantooo\n\"\"\"\ndef menu(data):\n \"\"\"\n Menu function will show menu section. program will ask user to input. Will open before main function\n :param data: data taken from data.csv file\n :return:\n \"\"\"\n print(\"Menu:\")\n print(\"R - List required books \")\n print(\"C - List completed books\")\n print(\"A - Add new book\")\n print(\"M - Mark a book as completed\")\n print(\"Q - Quit\")\n user_input = input(\">>>\").upper()\n\n while True:\n book_list = [] # All book in this list\n complete_list = [] # Only complete book\n reading_list = [] # Only reading book\n\n if user_input == \"Q\": # The program will end after return data\n return data\n\n elif user_input == \"R\": # Show all list in reading_list\n x = 0\n print(\"Requires books:\")\n for each in data:\n data_split = each.split(\",\")\n book_list.append(data_split)\n if 'r' in data_split[3]:\n print(\"\\t {:2}. {:50} by {:20} {:2} pages\".format(x, data_split[0], data_split[1], data_split[2]))\n x += 1\n print(book_list)\n print(reading_list)\n menu(data) # Back to menu function and bring data\n\n elif user_input == \"C\": # Show all list in complete_list\n print(\"Requires books:\")\n x = 0\n for each in data:\n data_split = each.split(\",\")\n book_list.append(data_split)\n if 'c' in data_split[3]:\n print(\"\\t {:2}. {:50} by {:20} {:2} pages\".format(x, data_split[0], data_split[1], data_split[2]))\n x += 1\n menu(data) # Back to menu function and bring data\n\n elif user_input == \"A\": # Ask user to do input\n input_a() # Go to input_a function\n menu(data) #Back to menu function and bring data\n\n elif user_input == \"M\": # Ask user to mark reading_list to be complete\n book_pages = [] # All page will putted here\n x = 0\n for each in data:\n data_split = each.split(\",\")\n book_list.append(data_split)\n if 'r\\n' in data_split[3]:\n reading_list.append(int(x))\n\n if len(reading_list) == 0:\n print(\"No required books\")\n else:\n print(\"Requires books:\")\n for each in data:\n data_split = each.split(\",\")\n book_list.append(data_split)\n if 'r\\n' in data_split[3]:\n print(\"\\t {:2}. {:50} by {:20} {:2} pages\".format(x, data_split[0], data_split[1], data_split[2]))\n book_pages.append(data_split[2])\n elif 'c' in data_split[3]:\n complete_list.append(int(x))\n x += 1\n total_pages = [int(i) for i in book_pages] # Change all string from pages became interger\n print(\"Total pages for {} books: {}\".format(len(reading_list), sum(total_pages)))\n print(\"Enter the number of a book to mark as completed\")\n print(data_split)\n print(complete_list)\n new_mark = []\n while True:\n try:\n number_mark = int(input(\">>>\"))\n if number_mark in complete_list:\n print(\"That book is already completed\")\n break\n else:\n print(\"{} by {} marked as completed\".format(book_list[number_mark][0], book_list[number_mark][1]))\n print(\"{},{},{},{}\".format(book_list[number_mark][0], book_list[number_mark][1], book_list[number_mark][2], 'c'))\n book_list[number_mark][3] = 'c\\n'\n print(book_list)\n OUTFILE = open(\"data.csv\", \"w\")\n for i in book_list:\n OUTFILE.write(\"{},{},{},{}\".format(i[0],i[1],i[2],i[3]))\n #other_data = OUTFILE.readlines()\n\n # for i in book_list:\n # print(*i, file=OUTFILE, sep= \"\")\n\n OUTFILE.close()\n\n #print(len(book_list))\n #print(reading_list)\n #for i in book_list:\n # if number_mark in new_mark:\n # i[3] = 'c'\n print(book_list)\n break\n except ValueError:\n print(\"Invalid input; enter a valid number\")\n\n #new_mark = open(\"data.csv\", \"n\")\n #x = 0\n #for each in data:\n #data_split = each.split(\",\")\n #book_list.append(data_split)\n #if x == number_mark:\n #print(\"{},{},{},{}\".format(data_split[0], data_split[1], data_split[2], 'c').replace('r', 'c'), file=new_mark)\n #print(book_list)\n #x += 1\n #data_split[number_mark][3] = 'c'\n #print(data_split)\n #break\n menu(data) # Back to menu function and bring data\n else:\n print(\"Invalid menu choice\")\n break\n\ndef input_a():\n \"\"\"\n This function ask user to input title, author, and pages\n :return:\n \"\"\"\n\n add_book = [] #Title, Author, and Pages saves here\n while True:\n title = input(\"Title: \")\n if title == \"\":\n print(\"Input can not be blank\")\n else:\n add_book.append(title)\n break\n while True:\n author = input(\"Author: \")\n if author == \"\":\n print(\"Input can not be blank\")\n else:\n add_book.append(author)\n break\n while True:\n try:\n page = int(input(\"Pages: \"))\n if page < 0:\n print(\"Number must be >= 0\")\n # new_file.wr(\"{},{},{},r\".format(new_book[0], new_book[1], new_book[2]))\n except ValueError:\n print(\"Invalid input; enter a valid number\")\n else:\n add_book.append(page)\n new_book = open(\"data.csv\", \"a\")\n print(\"{},{},{},r\".format(title, author, page), file=new_book)\n print(\"{} by {}, ({} pages) added to reading list\".format(title, author, page))\n break\n\n\n\n\ndef main():\n \"\"\"\n Main function. everything start from here and end here\n :return:\n \"\"\"\n TEXTFILE = open(\"data.csv\", \"r\")\n data = TEXTFILE.readlines()\n TEXTFILE.close()\n print(\"Hello Guys\")\n name = str(input(\"What is your name??\"))\n print(\"Welcome {}\".format(name))\n menu(data)\n print(\"{} books saved to books.csv\".format(len(data)))\n print(\"Have a nice day :)\")\n # Program ended here\n\nmain()","repo_name":"kevinjuliantooo/FirstProjectSchool","sub_path":"CP1404assignment1.py","file_name":"CP1404assignment1.py","file_ext":"py","file_size_in_byte":7256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3263229523","text":"# thread\n\nimport _thread as thread\nimport pandas as pd\nfrom url_feature_extraction import featureExtraction\n\nchildren = []\nfinished = False\nlock = thread.allocate_lock()\n\ndata_folder = 'C:\\\\Users\\\\Chris\\\\Downloads\\\\ISCXURL2016\\\\'\n\ndata0 = pd.read_csv(f\"{data_folder}online-valid.csv\")\nprint(f\"Shape of data: {data0.shape}\")\n\nn = 5000\nphishurl = data0.sample(n=n, random_state=12).copy()\nphishurl = phishurl.reset_index(drop=True)\nprint(f\"Shape of randomly collected samples: {phishurl.shape}\")\n\ndata1 = pd.read_csv(f\"{data_folder}Benign_list_big_final.csv\")\ndata1.columns = ['URLs']\n\nlegiurl = data1.sample(n=n, random_state=12).copy()\nlegiurl = legiurl.reset_index(drop=True)\n\nprint(f\"Shape of legit URLS: {legiurl.shape}\")\n\nphish_features = []\nlegi_features = []\n\n\ndef wrapper(_id, _url, _label, group: list, *args):\n output = featureExtraction(_url, _label)\n lock.acquire()\n group.append(output)\n if finished:\n print(f\"removing remaining children: {len(children)}\")\n children.remove(_id)\n lock.release()\n\n\nindex = 0\n_label = 0\n_len = 1\nmax_thread = 100\n\nwhile _len != 0 or finished is not True:\n # thread max_thread at a time\n if _len < max_thread:\n if index + 1 < legiurl.shape[0]:\n _url = legiurl['URLs'][index]\n thread.start_new_thread(wrapper, (index, _url, _label, legi_features))\n children.append(index)\n index += 1\n print(index)\n else:\n finished = True\n _len = len(children)\n\n# converting the list to dataframe\nfeature_names = ['Domain', 'Have_IP', 'Have_At', 'URL_Length', 'URL_Depth', 'Redirection',\n 'https_Domain', 'TinyURL', 'Prefix/Suffix', 'DNS_Record',\n 'Domain_Age', 'Domain_End', 'iFrame', 'Mouse_Over', 'Right_Click', 'Web_Forwards', 'Label']\n\nlegitimate = pd.DataFrame(legi_features, columns=feature_names)\n\n# print(len(legi_features), len(children))\n# Storing the extracted legitimate URLs fatures to csv file\nlegitimate.to_csv(f'{data_folder}legitimate.csv', index=False)\n# print(legitimate)\n\n\nindex = 0\n_label = 1\n_len = 1\nfinished = False\n\nwhile _len != 0 or finished is not True:\n # thread max_thread at a time\n if _len < max_thread:\n if index + 1 < phishurl.shape[0]:\n _url = phishurl['url'][index]\n thread.start_new_thread(wrapper, (index, _url, _label, phish_features))\n children.append(index)\n index += 1\n else:\n finished = True\n _len = len(children)\n\n# converting the list to dataframe\nfeature_names = ['Domain', 'Have_IP', 'Have_At', 'URL_Length', 'URL_Depth', 'Redirection',\n 'https_Domain', 'TinyURL', 'Prefix/Suffix', 'DNS_Record',\n 'Domain_Age', 'Domain_End', 'iFrame', 'Mouse_Over', 'Right_Click', 'Web_Forwards', 'Label']\n\nphishing = pd.DataFrame(phish_features, columns=feature_names)\n\n# Storing the extracted legitimate URLs fatures to csv file\nphishing.to_csv(f'{data_folder}phishing.csv', index=False)\n\n# Concatenating the dataframes into one\nurldata = pd.concat([legitimate, phishing]).reset_index(drop=True)\n\n\nprint(f\"Shape of Concatenated Data: {urldata.shape}\")\n# Storing the data in CSV file\nurldata.to_csv(f'{data_folder}urldata.csv', index=False)\n","repo_name":"xrisbarney/phishing-detection-machine-learning-wazuh-scripts","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"15612061989","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pydasm import get_instruction,get_instruction_string,MODE_32,FORMAT_INTEL\nfrom math import sqrt\n\ndef _get_imports(pe): \n\t\"\"\" Extrae las funciones de las que hace uso el programa. \n\t\tDevuelve el conjunto de funciones.\n\n\t\tParámetros:\n\t\tpe \t\t -- Objeto de pefile con el programa abierto.\n\n\t\tExcepciones:\n\t\tA implementar\n \"\"\"\n\timports = []\n\tfor entry in pe.DIRECTORY_ENTRY_IMPORT:\n\t\tfor imp in entry.imports: imports.append(imp.name)\n\treturn imports\n\n\ndef _is_packed(pe):\n\t\"\"\" Extrae la medida de empaquetamiento del programa. \n\t\tPara tener una medida que permita determinar si un programa está empaquetado se tiene en cuenta actualmente:\n\t\t · Entropía\n\t\t · UPX\n\t\t · ASPACK\n\t\tDevuelve la medida de empaquetamiento que se define como:\n\t\tsqrt(entropia^2 + {1 si hay una sección upx, 0 e.c.o.c}^2 + {1 si hay una sección aspack, 0 e.c.o.c}^2)\n\n\t\tParámetros:\n\t\tpe \t\t -- Objeto de pefile con el programa abierto.\n\n\t\tExcepciones:\n\t\tA implementar\n \"\"\"\n\tdef _entropy(): return sum([sec.get_entropy() for sec in pe.sections])\n\t\t\t\n\tdef _upx(): \n\t\tfor section in pe.sections:\n\t\t\tif \"upx\" in section.Name.lower(): return 1\n\t\treturn 0\n\t\t\n\tdef _aspack(): \n\t\tfor section in pe.sections:\n\t\t\tif \"aspack\" in section.Name.lower(): return 1\n\t\treturn 0\n\t\n\treturn sqrt(_entropy()**2+_upx()**2+_aspack()**2)\n\n\ndef _get_instructions(pe):\n\t\"\"\" Extrae la representación textual de las instrucciones del programa\n\t\n\t\tDevuelve el conjunto de instrucciones. \n\n\t\tParámetros:\n\t\tpe \t\t -- Objeto de pefile con el programa abierto.\n\n\t\tExcepciones:\n\t\tA implementar\n \"\"\"\n\tentry_point = pe.OPTIONAL_HEADER.AddressOfEntryPoint\n\tep_ava = entry_point\n\tdata = pe.get_memory_mapped_image()[entry_point:entry_point+pe.OPTIONAL_HEADER.SizeOfCode]\n\toffset,instructions = 0,set()\n\twhile offset= 1 and numeric_option <= 6:\n return numeric_option\n else:\n return -1 # Invalid option\n else:\n return -1 # Invalid option\n\n\n# Calculate the payment of an employee\ndef calculate_payment(hours, rate):\n if hours <= 40 or hours > 50: # Regular pay\n return hours * rate\n else:\n return (40 * rate) + ((hours - 40) * (rate * 1.5)) # Calculate overtime\n\n\n# Evaluate if the file to be looked at exist or not.\ndef evaluate_request(option):\n filename = input(\"Enter the file to be evaluated: \")\n if test_file(filename):\n fhandler = open(filename, 'r') # Open the file\n find_employee_info(filename, fhandler, option)\n\n else:\n print(\"Illegal file name. Input file was not found\")\n print(input(\"Press Enter to continue: \"))\n return -1\n\ndef find_name(line):\n return line.split(\",\")[0]\n\ndef find_hours(line):\n return line.split(\",\")[1]\n\ndef find_rate(line):\n return line.split(\",\")[2]\n\n\ndef create_hours_dict(filename, fhandler):\n hours_dict = {}\n for line in fhandler:\n if not line.startswith(\"time\"):\n hours_dict[find_name(line)] = find_hours(line)\n else:\n continue\n return hours_dict\n\ndef create_rate_dict(filename, fhandler):\n rate_dict = {}\n for line in fhandler:\n if not line.startswith(\"time\"):\n rate_dict[find_name(line)] = find_rate(line).split(\"\\n\")[0]\n else:\n continue\n return rate_dict\n\n# Avoid to have to write the print everytime\ndef press_enter():\n print(input(\"Press Enter to continue\"))\n\n\ndef find_employee_info(filename, fhandler, option):\n if option == 1:\n newfile = open(\"employees_payment.txt\", 'w')\n for line in fhandler:\n if not line.startswith(\"time\"):\n newfile.write(find_name(line).ljust(20) + \"$\" + str(calculate_payment(float(find_hours(line)), float(find_rate(line)))) + \"\\n\")\n else:\n continue\n print(\"A file named employees_payment.txt, containing the payment functions has been created.\")\n press_enter()\n newfile.close()\n fhandler.close()\n\n # Find the name of the employee with the highest number of hours\n elif option == 2:\n hours_dict = create_hours_dict(filename, fhandler)\n sorted_dict = sorted((value, key) for (key, value) in hours_dict.items())\n print(\"The employee with the max number of hours is: \" + str(sorted_dict[-1][1]) + \" | Expected: Elon Musk\" + '\\n')\n press_enter()\n\n # Find the name of the employee with the lowest number of hours\n elif option == 3:\n hours_dict = create_hours_dict(filename, fhandler)\n sorted_dict = sorted((value, key) for (key, value) in hours_dict.items())\n print(\"The employee with the min number of hours is: \" + str(sorted_dict[0][1]) + \" | Expected: Benjamin Franklin\" + '\\n')\n press_enter()\n\n # Find the name of the employee with the highest rate\n elif option == 4:\n rate_dict = create_rate_dict(filename, fhandler)\n sorted_dict = sorted((value, key) for (key, value) in rate_dict.items())\n print(\"The employee with the max rate is: \" + str(sorted_dict[-1][1]) + \" | Expected: Thomas Edison\" + '\\n')\n press_enter()\n\n # Find the name of the employee with the highest rate\n elif option == 5:\n rate_dict = create_rate_dict(filename, fhandler)\n sorted_dict = sorted((value, key) for (key, value) in rate_dict.items())\n print(\"The employee with the min rate is: \" + str(sorted_dict[0][1]) + \" | Expected: Nikola Tesla\" + '\\n')\n press_enter()\n\n # Exit the program\n elif (option == 6):\n print(\"Thanks for using the payment calculation program\")\n exit()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"emanuel2718/Calculate_Payments","sub_path":"paymentCalc.py","file_name":"paymentCalc.py","file_ext":"py","file_size_in_byte":5315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24780496517","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport argparse\nimport csv\nimport functools\nimport string\n\n\nvalid_chars = set(string.ascii_letters + string.digits + \"_-\")\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"samplesheet\", nargs=\"+\")\n\nargs = parser.parse_args()\n\nfor samplesheet in args.samplesheet:\n print(\"Checking {}\".format(samplesheet))\n\n with open(samplesheet) as f:\n rdr = csv.reader(f)\n rows = list(rdr)\n\n if len(set(map(len, rows))) > 1:\n print(\" Rows are not all the same length\")\n\n if rows[0][0] != \"[Data]\":\n print(\" Does not start with [Data] section header\")\n\n all_char = functools.reduce(set.union, (v for r in rows[1:] for v in r), set())\n invalid_chars = all_char - valid_chars\n\n if invalid_chars:\n print(\" Invalid characters in sample sheet: {}\".format(invalid_chars))\n","repo_name":"danledinh/czb_utils","sub_path":"src/utilities/demux/check_samplesheet.py","file_name":"check_samplesheet.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1337829785","text":"from function import get_todos, write_todos\n\nwhile True:\n user_action = input('Type add, or show, edit or exit:')\n user_action = user_action.strip()\n\n if user_action.startswith(\"add\"):\n todo = user_action[4:]\n\n todos = get_todos(todos)\n\n todos.append(todo + '\\n')\n\n write_todos(\"todos.txt\", todos)\n\n elif user_action.startswith('show'):\n\n todos = get_todos(todos)\n\n for index, item in enumerate(todos):\n item = item.strip('\\n')\n row = f\"{index + 1}-{item}\"\n print(row)\n elif user_action.startswith('edit'):\n try:\n number = int(user_action[5:])\n print(number)\n\n number = number - 1\n\n todos = get_todos(\"todos.txt\")\n\n new_todo = input(\"Enter new todo: \")\n todos[number] = new_todo + '\\n'\n\n with open('todos.txt', 'w') as file:\n file.writelines(todos)\n except ValueError:\n print(\"Your command is not valid.\")\n continue\n\n elif user_action.startswith('exit'):\n break\n else:\n print(\"command is not valid.\")\n\nprint(\"Bye!\")\n","repo_name":"Denzyyyy/todo-app","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"27139591549","text":"from pathlib import Path\nfrom typing import Union\nfrom wholeslidedata.extensions import (\n FolderCoupledExtension,\n WholeSlideImageExtension,\n)\nfrom wholeslidedata.mode import Mode\nfrom wholeslidedata.source.copy import copy as copy_source\nfrom wholeslidedata.source.files import WholeSlideFile, ImageFile\n\nfrom .wholeslideimage import MultiResWholeSlideImage\n\n\n@WholeSlideFile.register(\n (\"mrwsi\", \"multires_wsi\", \"multiresolutionwsi\", \"multiresolutionwholeslideimage\")\n)\nclass MultiResWholeSlideImageFile(WholeSlideFile, ImageFile):\n EXTENSIONS = WholeSlideImageExtension\n\n def __init__(\n self, mode: Union[str, Mode], path: Union[str, Path], image_backend: str = None\n ):\n super().__init__(mode, path, image_backend)\n\n def copy(self, destination_folder) -> None:\n destination_folder = Path(destination_folder) / \"images\"\n extension_name = self.path.suffix\n if WholeSlideImageExtension.is_extension(\n extension_name, FolderCoupledExtension\n ):\n folder = self.path.with_suffix(\"\")\n copy_source(folder, destination_folder)\n super().copy(destination_folder=destination_folder)\n\n def open(\n self,\n cell_graph_extractor: str = \"resnet34\",\n cell_graph_image_normalizer: str = \"vahadane\",\n ):\n return MultiResWholeSlideImage(\n self.path,\n self._image_backend,\n cell_graph_extractor=cell_graph_extractor,\n cell_graph_image_normalizer=cell_graph_image_normalizer,\n )\n","repo_name":"tsikup/multiresolution-clam","sub_path":"pytorch/data_helpers/wsi/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9342180290","text":"\"\"\"Various debugging functions.\"\"\"\n\n\nimport sys\nimport pathlib\nfrom io import StringIO\n\nimport numpy as np\nfrom contextlib import contextmanager\nfrom collections import Counter\n\nfrom openmdao.core.constants import _SetupStatus\nfrom openmdao.utils.mpi import MPI\nfrom openmdao.utils.om_warnings import issue_warning, MPIWarning\nfrom openmdao.utils.reports_system import register_report\nfrom openmdao.utils.file_utils import text2html\nfrom openmdao.visualization.tables.table_builder import generate_table\n\n\nclass _NoColor(object):\n \"\"\"\n A class to replace Fore, Back, and Style when colorama isn't istalled.\n \"\"\"\n def __getattr__(self, name):\n return ''\n\n\ndef _get_color_printer(stream=sys.stdout, colors=True, rank=0):\n \"\"\"\n Return a print function tied to a particular stream, along with coloring info.\n \"\"\"\n try:\n from colorama import init, Fore, Back, Style\n init(autoreset=True)\n except ImportError:\n Fore = Back = Style = _NoColor()\n\n if not colors:\n Fore = Back = Style = _NoColor()\n\n if MPI and MPI.COMM_WORLD.rank != rank:\n if rank >= MPI.COMM_WORLD.size:\n if MPI.COMM_WORLD.rank == 0:\n print(\"Specified rank (%d) is outside of the valid range (0-%d).\" %\n (rank, MPI.COMM_WORLD.size - 1))\n sys.exit()\n def color_print(s, **kwargs):\n pass\n else:\n def color_print(s, color='', end=''):\n \"\"\"\n \"\"\"\n print(color + s, file=stream, end='')\n print(Style.RESET_ALL, file=stream, end='')\n print(end=end)\n\n return color_print, Fore, Back, Style\n\n\ndef tree(top, show_solvers=True, show_jacs=True, show_colors=True, show_approx=True,\n filter=None, show_sizes=False, max_depth=0, rank=0, stream=sys.stdout):\n \"\"\"\n Dump the model tree structure to the given stream.\n\n If you install colorama, the tree will be displayed in color if the stream is a terminal\n that supports color display.\n\n Parameters\n ----------\n top : System or Problem\n The top object in the tree.\n show_solvers : bool\n If True, include solver types in the tree.\n show_jacs : bool\n If True, include jacobian types in the tree.\n show_colors : bool\n If True and stream is a terminal that supports it, display in color.\n show_approx : bool\n If True, mark systems that are approximating their derivatives.\n filter : function(System)\n A function taking a System arg and returning None or an iter of (name, value) tuples.\n If None is returned, that system will not be displayed. Otherwise, the system will\n be displayed along with any name, value pairs returned from the filter.\n show_sizes : bool\n If True, show input and output sizes for each System.\n max_depth : int\n Maximum depth for display.\n rank : int\n If MPI is active, the tree will only be displayed on this rank. Only objects local\n to the given rank will be displayed.\n stream : File-like\n Where dump output will go.\n \"\"\"\n from openmdao.core.problem import Problem\n from openmdao.core.group import Group\n from openmdao.core.implicitcomponent import ImplicitComponent\n\n cprint, Fore, Back, Style = _get_color_printer(stream, show_colors, rank=rank)\n\n tab = 0\n if isinstance(top, Problem):\n if filter is None:\n cprint('Driver: ', color=Fore.CYAN + Style.BRIGHT)\n cprint(type(top.driver).__name__, color=Fore.MAGENTA, end='\\n')\n tab += 1\n top = top.model\n\n for s in top.system_iter(include_self=True, recurse=True):\n if filter is None:\n ret = ()\n else:\n ret = filter(s)\n if ret is None:\n continue\n\n depth = len(s.pathname.split('.')) if s.pathname else 0\n if max_depth != 0 and depth > max_depth:\n continue\n\n indent = ' ' * (depth + tab)\n cprint(indent, end='')\n\n info = ''\n if isinstance(s, Group):\n cprint(\"%s \" % type(s).__name__, color=Fore.GREEN + Style.BRIGHT)\n cprint(\"%s\" % s.name)\n else:\n if isinstance(s, ImplicitComponent):\n colr = Back.CYAN + Fore.BLACK + Style.BRIGHT\n else:\n colr = Fore.CYAN + Style.BRIGHT\n cprint(\"%s \" % type(s).__name__, color=colr)\n cprint(\"%s\" % s.name)\n if s._has_distrib_vars:\n cprint(\" (distributed)\", color=Fore.MAGENTA)\n\n # FIXME: these sizes could be wrong under MPI\n if show_sizes:\n cprint(\" (%d / %d)\" % (s._inputs._data.size, s._outputs._data.size),\n color=Fore.RED + Style.BRIGHT)\n\n if show_solvers:\n lnsolver = type(s.linear_solver).__name__\n nlsolver = type(s.nonlinear_solver).__name__\n\n if s.linear_solver is not None and lnsolver != \"LinearRunOnce\":\n cprint(\" LN: \")\n cprint(lnsolver, color=Fore.MAGENTA + Style.BRIGHT)\n if s.nonlinear_solver is not None and nlsolver != \"NonlinearRunOnce\":\n cprint(\" NL: \")\n cprint(nlsolver, color=Fore.MAGENTA + Style.BRIGHT)\n\n if show_jacs:\n jacs = []\n lnjac = nljac = None\n if s._assembled_jac is not None:\n lnjac = s._assembled_jac\n jacs.append(lnjac)\n if s.nonlinear_solver is not None:\n jacsolvers = list(s.nonlinear_solver._assembled_jac_solver_iter())\n if jacsolvers:\n nljac = jacsolvers[0]._assembled_jac\n if nljac is not lnjac:\n jacs.append(nljac)\n\n if len(jacs) == 2:\n jnames = [' LN Jac: ', ' NL Jac: ']\n elif lnjac is not None:\n if lnjac is nljac:\n jnames = [' Jac: ']\n else:\n jnames = [' LN Jac: ']\n elif nljac is not None:\n jnames = [' NL Jac: ']\n else:\n jnames = []\n\n for jname, jac in zip(jnames, jacs):\n cprint(jname)\n cprint(type(jac).__name__, color=Fore.MAGENTA + Style.BRIGHT)\n\n if show_approx and s._approx_schemes:\n approx_keys = set()\n keys = set()\n for k, sjac in s._subjacs_info.items():\n if 'method' in sjac and sjac['method']:\n approx_keys.add(k)\n else:\n keys.add(k)\n diff = approx_keys - keys\n cprint(\" APPROX: \", color=Fore.MAGENTA + Style.BRIGHT)\n cprint(\"%s (%d of %d)\" % (list(s._approx_schemes), len(diff), len(s._subjacs_info)))\n\n cprint('', end='\\n')\n\n vindent = indent + ' '\n for name, val in ret:\n cprint(\"%s%s: %s\\n\" % (vindent, name, val))\n\n\ndef _get_printer(comm, stream, rank=0):\n if comm.rank == rank:\n def p(*args, **kwargs):\n print(*args, file=stream, **kwargs)\n else:\n def p(*args, **kwargs):\n pass\n\n return p\n\n\ndef config_summary(problem, stream=sys.stdout):\n \"\"\"\n Prints various high level statistics about the model structure.\n\n Parameters\n ----------\n problem : Problem\n The Problem to be summarized.\n stream : File-like\n Where the output will be written.\n \"\"\"\n from openmdao.core.group import Group\n\n model = problem.model\n meta = model._var_allprocs_abs2meta\n locsystems = list(model.system_iter(recurse=True, include_self=True))\n locgroups = [s for s in locsystems if isinstance(s, Group)]\n\n grpnames = [s.pathname for s in locgroups]\n sysnames = [s.pathname for s in locsystems]\n ln_solvers = [(s.pathname, type(s.linear_solver).__name__) for s in locsystems\n if s.linear_solver is not None]\n nl_solvers = [(s.pathname, type(s.nonlinear_solver).__name__) for s in locsystems\n if s.nonlinear_solver is not None]\n\n max_depth = max([len(name.split('.')) for name in sysnames])\n setup_done = model._problem_meta['setup_status'] >= _SetupStatus.POST_FINAL_SETUP\n\n if problem.comm.size > 1:\n local_max = np.array([max_depth])\n global_max_depth = np.zeros(1, dtype=int)\n problem.comm.Allreduce(local_max, global_max_depth, op=MPI.MAX)\n\n proc_names = problem.comm.gather((sysnames, grpnames, ln_solvers, nl_solvers), root=0)\n grpnames = set()\n sysnames = set()\n ln_solvers = set()\n nl_solvers = set()\n if proc_names is not None:\n for systems, grps, lnsols, nlsols in proc_names:\n sysnames.update(systems)\n grpnames.update(grps)\n ln_solvers.update(lnsols)\n nl_solvers.update(nlsols)\n else:\n global_max_depth = max_depth\n ln_solvers = set(ln_solvers)\n nl_solvers = set(nl_solvers)\n\n ln_solvers = Counter([sname for _, sname in ln_solvers])\n nl_solvers = Counter([sname for _, sname in nl_solvers])\n\n # this gives us a printer that only prints on rank 0\n printer = _get_printer(problem.comm, stream)\n\n printer(\"============== Problem Summary ============\")\n printer(\"Groups: %5d\" % len(grpnames))\n printer(\"Components: %5d\" % (len(sysnames) - len(grpnames)))\n printer(\"Max tree depth: %5d\" % global_max_depth)\n printer()\n\n if setup_done:\n desvars = model.get_design_vars()\n printer(\"Design variables: %5d Total size: %8d\" %\n (len(desvars), sum(d['size'] for d in desvars.values())))\n\n con_nonlin_eq = {}\n con_nonlin_ineq = {}\n con_linear_eq = {}\n con_linear_ineq = {}\n for con, vals in model.get_constraints().items():\n if vals['linear']:\n if vals['equals'] is not None:\n con_linear_eq[con] = vals\n else:\n con_linear_ineq[con] = vals\n else:\n if vals['equals'] is not None:\n con_nonlin_eq[con]= vals\n else:\n con_nonlin_ineq[con]= vals\n\n con_nonlin = con_nonlin_eq.copy()\n con_nonlin.update(con_nonlin_ineq)\n con_linear = con_linear_eq.copy()\n con_linear.update(con_linear_ineq)\n\n printer(\"\\nNonlinear Constraints: %5d Total size: %8d\" %\n (len(con_nonlin), sum(d['size'] for d in con_nonlin.values())))\n printer(\" equality: %5d %8d\" %\n (len(con_nonlin_eq), sum(d['size'] for d in con_nonlin_eq.values())))\n printer(\" inequality: %5d %8d\" %\n (len(con_nonlin_ineq), sum(d['size'] for d in con_nonlin_ineq.values())))\n printer(\"\\nLinear Constraints: %5d Total size: %8d\" %\n (len(con_linear), sum(d['size'] for d in con_linear.values())))\n printer(\" equality: %5d %8d\" %\n (len(con_linear_eq), sum(d['size'] for d in con_linear_eq.values())))\n printer(\" inequality: %5d %8d\" %\n (len(con_linear_ineq), sum(d['size'] for d in con_linear_ineq.values())))\n\n objs = model.get_objectives()\n printer(\"\\nObjectives: %5d Total size: %8d\" %\n (len(objs), sum(d['size'] for d in objs.values())))\n\n printer()\n\n input_names = model._var_allprocs_abs2meta['input']\n ninputs = len(input_names)\n if setup_done:\n printer(\"Input variables: %5d Total size: %8d\" %\n (ninputs, sum(meta['input'][n]['size'] for n in input_names)))\n else:\n printer(\"Input variables: %5d\" % ninputs)\n\n output_names = model._var_allprocs_abs2meta['output']\n noutputs = len(output_names)\n if setup_done:\n printer(\"Output variables: %5d Total size: %8d\" %\n (noutputs, sum(meta['output'][n]['global_size'] for n in output_names)))\n else:\n printer(\"Output variables: %5d\" % noutputs)\n\n if setup_done and isinstance(model, Group):\n printer()\n conns = model._conn_global_abs_in2out\n printer(\"Total connections: %d Total transfer data size: %d\" %\n (len(conns), sum(meta['input'][n]['size'] for n in conns)))\n\n printer()\n printer(\"Driver type: %s\" % problem.driver.__class__.__name__)\n linstr = []\n for slvname, num in ln_solvers.most_common():\n if num > 1:\n linstr.append('{} x {}'.format(slvname, num))\n else:\n linstr.append(slvname)\n printer(\"Linear Solvers: [{}]\".format(', '.join(linstr)))\n\n\n nlstr = []\n for slvname, num in nl_solvers.most_common():\n if num > 1:\n nlstr.append('{} x {}'.format(slvname, num))\n else:\n nlstr.append(slvname)\n printer(\"Nonlinear Solvers: [{}]\".format(', '.join(nlstr)))\n\n\ndef _summary_report(prob):\n path = str(pathlib.Path(prob.get_reports_dir()).joinpath('summary.html'))\n s = StringIO()\n config_summary(prob, s)\n with open(path, 'w') as f:\n f.write(text2html(s.getvalue()))\n\n\ndef _summary_report_register():\n register_report('summary', _summary_report, 'Model summary', 'Problem', 'final_setup', 'post')\n\n\n@contextmanager\ndef profiling(outname='prof.out'):\n \"\"\"\n Context manager that runs cProfile on the wrapped code and dumps stats to the given filename.\n\n Parameters\n ----------\n outname : str\n Name of the output file containing profiling stats.\n \"\"\"\n import cProfile\n prof = cProfile.Profile()\n prof.enable()\n\n try:\n yield prof\n finally:\n prof.disable()\n prof.dump_stats(outname)\n\n\ndef compare_jacs(Jref, J, rel_trigger=1.0):\n results = []\n\n for key in set(J).union(Jref):\n if key in J:\n subJ = J[key]\n else:\n subJ = np.zeros(Jref[key].shape)\n\n if key in Jref:\n subJref = Jref[key]\n else:\n subJref = np.zeros(J[key].shape)\n\n diff = np.abs(subJ - subJref)\n absref = np.abs(subJref)\n rel_idxs = np.nonzero(absref > rel_trigger)\n diff[rel_idxs] /= absref[rel_idxs]\n\n max_diff_idx = np.argmax(diff)\n max_diff = diff.flatten()[max_diff_idx]\n\n # now determine if max diff is abs or rel\n diff[:] = 0.0\n diff[rel_idxs] = 1.0\n if diff.flatten()[max_diff_idx] > 0.0:\n results.append((key, max_diff, 'rel'))\n else:\n results.append((key, max_diff, 'abs'))\n\n return results\n\n\ndef trace_mpi(fname='mpi_trace', skip=(), flush=True):\n \"\"\"\n Dump traces to the specified filename<.rank> showing openmdao and mpi/petsc calls.\n\n Parameters\n ----------\n fname : str\n Name of the trace file(s). <.rank> will be appended to the name on each rank.\n skip : set-like\n Collection of function names to skip.\n flush : bool\n If True, flush print buffer after every print call.\n \"\"\"\n if MPI is None:\n issue_warning(\"MPI is not active. Trace aborted.\", category=MPIWarning)\n return\n if sys.getprofile() is not None:\n raise RuntimeError(\"another profile function is already active.\")\n\n my_fname = fname + '.' + str(MPI.COMM_WORLD.rank)\n\n outfile = open(my_fname, 'w')\n\n stack = []\n\n _c_map = {\n 'c_call': '(c) -->',\n 'c_return': '(c) <--',\n 'c_exception': '(c_exception)',\n }\n\n\n def _print_c_func(frame, arg, typestr):\n s = str(arg)\n if 'mpi4py' in s or 'petsc4py' in s:\n c = arg.__self__.__class__\n print(' ' * len(stack), typestr, \"%s.%s.%s\" %\n (c.__module__, c.__name__, arg.__name__),\n \"%s:%d\" % (frame.f_code.co_filename, frame.f_code.co_firstlineno),\n file=outfile, flush=True)\n\n\n def _mpi_trace_callback(frame, event, arg):\n pname = None\n commsize = ''\n if event == 'call':\n if 'openmdao' in frame.f_code.co_filename:\n if frame.f_code.co_name in skip:\n return\n if 'self' in frame.f_locals:\n try:\n pname = frame.f_locals['self'].msginfo\n except:\n pass\n try:\n commsize = frame.f_locals['self'].comm.size\n except:\n pass\n if pname is not None:\n if not stack or pname != stack[-1][0]:\n stack.append([pname, 1])\n print(' ' * len(stack), commsize, pname, file=outfile, flush=flush)\n else:\n stack[-1][1] += 1\n print(' ' * len(stack), '-->', frame.f_code.co_name, \"%s:%d\" %\n (frame.f_code.co_filename, frame.f_code.co_firstlineno),\n file=outfile, flush=flush)\n elif event == 'return':\n if 'openmdao' in frame.f_code.co_filename:\n if frame.f_code.co_name in skip:\n return\n if 'self' in frame.f_locals:\n try:\n pname = frame.f_locals['self'].msginfo\n except:\n pass\n try:\n commsize = frame.f_locals['self'].comm.size\n except:\n pass\n print(' ' * len(stack), '<--', frame.f_code.co_name, \"%s:%d\" %\n (frame.f_code.co_filename, frame.f_code.co_firstlineno),\n file=outfile, flush=flush)\n if pname is not None and stack and pname == stack[-1][0]:\n stack[-1][1] -= 1\n if stack[-1][1] < 1:\n stack.pop()\n if stack:\n print(' ' * len(stack), commsize, stack[-1][0], file=outfile,\n flush=flush)\n else:\n _print_c_func(frame, arg, _c_map[event])\n\n sys.setprofile(_mpi_trace_callback)\n\n\ndef prom_info_dump(system, tgt):\n \"\"\"\n Dump the promotion src_indices/src_shape data for the given absolute target name.\n\n The data actually lives in the Problem metadata, but is more convenient to access during\n debugging by using a System instance to access that metadata.\n\n Promotion src_indices/src_shape data is displayed for all inputs, including tgt, that\n are connected to the same source.\n\n Parameters\n ----------\n system : System\n Any System instance.\n tgt : str\n Absolute name of an input variable.\n \"\"\"\n probmeta = system._problem_meta\n model = probmeta['model_ref']()\n src = model._conn_global_abs_in2out[tgt]\n abs_in2prom_info = probmeta['abs_in2prom_info']\n print('For tgt', tgt, 'and src', src, 'connected tgts and prom info are:')\n for t, s in model._conn_global_abs_in2out.items():\n if s == src:\n print(' ', t)\n if t in abs_in2prom_info:\n for p in abs_in2prom_info[t]:\n print(' ', p)\n print(flush=True)\n\n\ndef comm_info(system, outfile=None, verbose=False, table_format='box_grid'):\n \"\"\"\n Display MPI communicator information for Systems in the model.\n\n Parameters\n ----------\n system : System\n A System in the model.\n outfile : str or None\n Name of file where output will be written. If None, output is written to stdout.\n verbose : bool\n If True, display comm size and rank range for all Systems. Otherwise, display only Systems\n having a comm size different from their parent system.\n table_format : str\n Table format. All formats compatible with the generate_table function are available.\n \"\"\"\n if MPI and MPI.COMM_WORLD.size > 1:\n dct = {}\n for path, csize, rank, wrank in system.comm_info_iter():\n if path not in dct:\n dct[path] = [csize, wrank, wrank]\n else:\n csize, minwrnk, maxwrnk = dct[path]\n # do min/max here *and* after the gather so we don't have to\n # gather all the data to get the min/max\n if wrank < minwrnk:\n minwrnk = wrank\n if wrank > maxwrnk:\n maxwrnk = wrank\n dct[path] = [csize, minwrnk, maxwrnk]\n\n # collect dct from all procs so we can get the full min/max rank range\n alldcts = system.comm.gather(dct, root=0)\n\n if MPI.COMM_WORLD.rank == 0:\n alldata = {}\n sizes = {}\n for dct in alldcts:\n for path, v in dct.items():\n csize, newmin, newmax = v\n sizes[path] = csize\n if path in alldata:\n _, minwrnk, maxwrnk = alldata[path]\n if newmin < minwrnk:\n minwrnk = newmin\n if newmax > maxwrnk:\n maxwrnk = newmax\n alldata[path] = [csize, minwrnk, maxwrnk]\n else:\n alldata[path] = [csize, newmin, newmax]\n\n table_data = []\n headers = ['Comm Size', 'COMM_WORLD Range(s)', 'System Pathname']\n for path, lst in sorted(alldata.items(), key=lambda x: (-x[1][0], x[0])):\n csize, minwrnk, maxwrnk = lst\n if verbose or path == '' or sizes[path.rpartition('.')[0]] != csize:\n if minwrnk == maxwrnk:\n rng = str(minwrnk)\n else:\n rng = f\"{minwrnk} - {maxwrnk}\"\n table_data.append([csize, rng, path])\n\n col_meta = [\n {'align': 'center', 'header_align': 'center'},\n {'align': 'center', 'header_align': 'center'},\n {}\n ]\n if table_format != 'tabulator':\n col_meta[0]['max_width'] = 5\n col_meta[1]['max_width'] = 15\n\n probpath = system._problem_meta['pathname']\n if outfile is None:\n print(f\"Printing comm info table for Problem '{probpath}'\")\n\n outf = generate_table(table_data, headers=headers, column_meta=col_meta,\n tablefmt=table_format).display(outfile=outfile)\n\n if outf is not None and MPI.COMM_WORLD.rank == 0:\n print(f\"comm info table for Problem '{probpath}' written to {outf}\")\n else:\n if outfile is None:\n print(\"No MPI process info available.\")\n else:\n with open(outfile, 'w') as f:\n print(\"No MPI process info available.\", file=f)\n","repo_name":"OpenMDAO/OpenMDAO","sub_path":"openmdao/devtools/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":23013,"program_lang":"python","lang":"en","doc_type":"code","stars":451,"dataset":"github-code","pt":"53"}
+{"seq_id":"19379132545","text":"import pickle, gzip, numpy, theano\r\nimport theano.tensor as T\r\n\r\ndef shared_dataset(data_xy):\r\n data_x, data_y = data_xy\r\n shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX))\r\n shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX))\r\n\r\n return shared_x, T.cast(shared_y, 'int32')\r\n\r\ndef main():\r\n f = gzip.open('mnist.pkl.gz' , 'rb')\r\n train_set, valid_set, test_set = pickle.load(f, encoding='latin1')\r\n f.close()\r\n test_set_x, test_set_y = shared_dataset(test_set)\r\n valid_set_x, valid_set_y = shared_dataset(valid_set)\r\n train_set_x, train_set_y = shared_dataset(train_set)\r\n x = test_set_x.get_value()\r\n for y in range(0, 250):\r\n print (x.item(y))\r\n batch_size = 500\r\n\r\nmain()\r\n","repo_name":"jmanosu/learning_tensorflow","sub_path":"digit_identifier/tf_digit.py","file_name":"tf_digit.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"5604850417","text":"import sys\nimport unittest\n\nfrom PyQt5.QtWidgets import QApplication\n\nfrom src.views.patient_referral import PatientReferralWidget\n\n\nclass TestPatientReferralView(unittest.TestCase):\n\n def setUp(self) -> None:\n self.app = QApplication(sys.argv)\n self.patient_referral = PatientReferralWidget()\n self.results_dict = None\n\n def tearDown(self) -> None:\n pass\n\n def test_init(self):\n self.assertIsNotNone(self.patient_referral.lne_referrer_name)\n self.assertIsNotNone(self.patient_referral.lne_diagnosis)\n self.assertIsNotNone(self.patient_referral.cmb_seizure_freq)\n self.assertIsNotNone(self.patient_referral.cmb_last_seizure)\n self.assertIsNotNone(self.patient_referral.chlist_epilepsy)\n self.assertIsNotNone(self.patient_referral.chlist_other_diagnostic)\n self.assertIsNotNone(self.patient_referral.chlist_peadiatric)\n self.assertIsNotNone(self.patient_referral.chlist_other)\n target_dict = {\n 'Referrer name': '',\n 'Referrer details': '',\n 'Diagnosis at referral': '',\n 'Seizure frequency': '',\n 'Time since last seizure': '',\n 'Epilepsy-related indications': {\n 'Clinical suspicion of epilepsy or seizure': 0,\n 'Changes in seizure pattern': 0,\n 'Suspicion of non-convulsive status epilepticus': 0,\n 'Reconsider the initial diagnosis of epilepsy': 0,\n 'Monitoring of status epilepticus': 0,\n 'Classification of a patient diagnosed with epilepsy': 0,\n 'Monitoring the effect of medication': 0,\n 'Monitoring of seizure frequency': 0,\n 'Presurgical evaluation': 0,\n 'Considering stopping AED therapy': 0,\n 'Drivers license or flight certificate': 0\n },\n 'Other differential diagnostic questions': {\n 'Psychogenic non-epileptic seizures': 0,\n 'Encephalopathy': 0,\n 'Loss of consciousness': 0,\n 'Cerebral vascular disease': 0,\n 'Disturbance of consciousness': 0,\n 'Dementia': 0,\n 'Paroxysmal behavioral changes': 0,\n 'Other psychiatric or behavioral symptoms': 0,\n 'Coma': 0,\n 'Brain death': 0\n },\n 'Specific paediatric indication': {\n 'Genetic syndrome': 0,\n 'Metabolic disorder': 0,\n 'Regression': 0,\n 'Developmental problems': 0\n },\n 'Other indications': {\n 'Follow up EEG': 0,\n 'Research project': 0,\n 'Assessment of prognosis': 0,\n 'Other indication': 0\n }\n }\n self.results_dict = self.patient_referral.to_dict()\n self.assertEqual(self.results_dict, target_dict)\n\n def test_ones_to_dict(self):\n self.set_to_ones()\n self.results_dict = self.patient_referral.to_dict()\n target_dict = {\n 'Referrer name': '1',\n 'Referrer details': '1',\n 'Diagnosis at referral': '1',\n 'Seizure frequency': self.patient_referral.txt_seizure_freq[1],\n 'Time since last seizure': self.patient_referral.txt_last_seizure[1],\n 'Epilepsy-related indications': {\n 'Clinical suspicion of epilepsy or seizure': 1,\n 'Changes in seizure pattern': 1,\n 'Suspicion of non-convulsive status epilepticus': 1,\n 'Reconsider the initial diagnosis of epilepsy': 1,\n 'Monitoring of status epilepticus': 1,\n 'Classification of a patient diagnosed with epilepsy': 1,\n 'Monitoring the effect of medication': 1,\n 'Monitoring of seizure frequency': 1,\n 'Presurgical evaluation': 1,\n 'Considering stopping AED therapy': 1,\n 'Drivers license or flight certificate': 1\n },\n 'Other differential diagnostic questions': {\n 'Psychogenic non-epileptic seizures': 1,\n 'Encephalopathy': 1,\n 'Loss of consciousness': 1,\n 'Cerebral vascular disease': 1,\n 'Disturbance of consciousness': 1,\n 'Dementia': 1,\n 'Paroxysmal behavioral changes': 1,\n 'Other psychiatric or behavioral symptoms': 1,\n 'Coma': 1,\n 'Brain death': 1\n },\n 'Specific paediatric indication': {\n 'Genetic syndrome': 1,\n 'Metabolic disorder': 1,\n 'Regression': 1,\n 'Developmental problems': 1\n },\n 'Other indications': {\n 'Follow up EEG': 1,\n 'Research project': 1,\n 'Assessment of prognosis': 1,\n 'Other indication': 1\n }\n }\n self.assertEqual(self.results_dict, target_dict)\n\n def set_to_ones(self):\n self.patient_referral.lne_referrer_name.setText(\"1\")\n self.patient_referral.txe_referrer_details.setText(\"1\")\n self.patient_referral.lne_diagnosis.setText(\"1\")\n self.patient_referral.cmb_seizure_freq.setCurrentIndex(1)\n self.patient_referral.cmb_last_seizure.setCurrentIndex(1)\n self.set_check_list_ones(self.patient_referral.chlist_epilepsy)\n self.set_check_list_ones(self.patient_referral.chlist_other_diagnostic)\n self.set_check_list_ones(self.patient_referral.chlist_peadiatric)\n self.set_check_list_ones(self.patient_referral.chlist_other)\n\n def set_check_list_ones(self, chlist):\n for i in range(chlist.rowCount()):\n chlist.item(i).setCheckState(1)\n","repo_name":"DWonGH/OpenSCORE","sub_path":"tests/views/test_patient_referral.py","file_name":"test_patient_referral.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8576910365","text":"#!/usr/bin/env python3\n\nfrom sensor_msgs.msg import LaserScan\nfrom std_msgs.msg import Float64\nfrom geometry_msgs.msg import PolygonStamped, Point32\nimport rospy\nimport numpy as np\nimport math\nimport pcl\n\n\nNODE_NAME = \"obstacle_detection_LIDAR_node\"\nSUB_TOPIC = \"scan\"\nPUB_TOPIC = \"obstacles\"\nQUEUE_SIZE = 1\n\n\nclass ObstacleDetectionNode:\n def __init__(self, node_name, sub_topic_lidar, pub_topic):\n\n # Publishers\n self.obs_pub = rospy.Publisher(pub_topic, PolygonStamped, queue_size=QUEUE_SIZE)\n self.scan_sub = rospy.Subscriber('scan',LaserScan,self.scanCallback)\n self.range_threshold = rospy.get_param('detection_distance_threshold',3) # default to 2 m\n self.fov_threshold = rospy.get_param('FOV',math.pi/2)\n self.fov_publisher = rospy.Publisher('fovscan',LaserScan,queue_size=QUEUE_SIZE)\n\n def scanCallback(self,msg):\n #print(\"scan received\")\n\n # raw laserscan data\n ranges = np.asarray(msg.ranges)\n # array of angles corresponding to ranges\n angles = np.arange(msg.angle_min,msg.angle_max,msg.angle_increment)\n\n # narrow angles and ranges to field of view\n fov_angles = angles[(angles>-self.fov_threshold) & (angles-self.fov_threshold) & (anglesself.range_threshold] = 100\n\n ranges_imp = fov_ranges[fov_ranges= 81:\n print('A학점')\nelif score >= 61:\n print('B학점')\nelif score >= 41:\n print('C학점')\nelif score >= 21:\n print('D학점')\nelse:\n print('E학점')\n\n# 4. 다음 세 개의 숫자 중 가장 큰수를 출력하세요.(if문 사용) : 12, 6, 18\na, b, c = 12, 6, 18\nmax_value = a\nif b > a:\n max_value = b\nif c > b:\n max_value = c\nprint(max_value)\n\nprint(max(list([a,b,c])))\n\n# 5. 다음 주민등록 번호에서 7자리 숫자를 사용해서 남자, 여자를 판별하세요. (1,3 : 남자, 2,4 : 여자)\ns = '891022-3473837'\nif int(s[7]) % 2 == 0:\n print('여자')\nelse:\n print('남자')\n\n# 6 ~ 10 반복문 사용(while 또는 for)\n\n# 6. 다음 리스트 중에서 '정' 글자를 제외하고 출력하세요.\nq3 = [\"갑\", \"을\", \"병\", \"정\", '무', '기']\nfor c in q3:\n if c == '정':\n continue\n print(c, end =' ')\nprint()\n\n# 7. 1부터 100까지 자연수 중 '홀수'만 한 라인으로 출력 하세요.\nfor i in range(1,101):\n if i % 2 == 1:\n print(i, end = ' ')\nprint()\n\nprint(' '.join([str(i) for i in range(1,100) if i % 2 == 1]))\n\n# 8. 아래 리스트 항목 중에서 5글자 이상의 단어만 출력하세요.\nq4 = [\"nice\", \"study\", \"python\", \"anaconda\", \"!\"]\nfor c in q4:\n if len(c) >= 5:\n print(c, end= ' ')\nprint()\n\nprint(' '.join([s for s in q4 if len(s)>=5]))\n# 9. 아래 리스트 항목 중에서 소문자만 출력하세요.\nq5 = [\"A\", \"b\", \"c\", \"D\", \"e\", \"F\", \"G\", \"h\"]\nfor c in q5:\n if c.isupper():\n continue\n print(c, end = ' ')\nprint()\nprint(' '.join([c for c in q5 if c.islower()]))\n\n\n# 10. 아래 리스트 항목 중에서 소문자는 대문자로 대문자는 소문자로 출력하세요.\nq6 = [\"A\", \"b\", \"c\", \"D\", \"e\", \"F\", \"G\", \"h\"]\nfor c in q6:\n if c.islower():\n print(c.upper(), end = ' ')\n else:\n print(c.lower(), end = ' ')\nprint()\nprint(' '.join([c.lower() if c.isupper() else c.upper() for c in q6]))","repo_name":"devThinKoki/learning_repo","sub_path":"FASTCAMPUS/NKLCB/2nd/section05-3-[quiz].py","file_name":"section05-3-[quiz].py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19293725107","text":"class Person(object):\n def __init__(self, *args):\n print(\"run init\")\n self.name = args[0]\n self.hp = args[1]\n self.aggr = args[2]\n self.sex = args[3]\n\n def walk(self, n):\n print(\"%s走了%s步\" % (self.name, n))\n\np1 = Person(\"娃娃\", 100, 10, \"女\")\nprint(p1.__dict__)\nprint(p1.name)\np1.__dict__['name'] = \"二哈\"\nprint(p1.__dict__)\nprint(p1.name)\n\n# self必须带着的原因\np1.walk(2)\nPerson.walk(p1, 3)","repo_name":"fengzongming/python_practice","sub_path":"day22_面向对象初识/demo_01_面向对象.py","file_name":"demo_01_面向对象.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8795007389","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport time\nimport torch\nfrom progress.bar import Bar\nfrom torch.nn.parallel import DataParallel\nfrom .utils import _sigmoid\nfrom utils.utils import AverageMeter\nfrom .losses import FocalLoss, RegL1Loss, RegLoss\nfrom .model import load_model, create_model, save_model\nfrom dataset.dataset_custom import DATASET_CUSTOM\nfrom utils.logger import Logger\n\n\nclass Trainer(object):\n def __init__(self, config):\n\n self.arch = config['model']['arch']\n self.heads = config['model']['heads']\n self.head_conv = config['model']['head_conv']\n self.lr = config['train']['lr']\n self.lr_step = config['train']['lr_step']\n self.resume_path = config['train']['resume_path']\n self.seed = config['train']['seed']\n self.not_cuda_benchmark = config['train']['not_cuda_benchmark']\n\n self.gpu_str = config['gpu_str']\n self.gpus = config['gpus']\n self.chunk_sizes = config['train']['chunk_sizes']\n\n self.num_epochs = config['train']['num_epochs']\n self.batch_size = config['train']['batch_size']\n self.num_workers = config['train']['num_workers']\n self.val_intervals = config['train']['val_intervals']\n self.save_all = config['train']['save_all']\n self.metric = config['train']['metric']\n self.save_dir = config['save_dir']\n self.num_iters = config['train']['num_iters']\n self.exp_id = config['exp_id']\n self.print_iter = config['train']['print_iter']\n self.hide_data_time = config['train']['hide_data_time']\n\n self.model = create_model(self.arch, self.heads, self.head_conv)\n self.optimizer = torch.optim.Adam(self.model.parameters(), self.lr)\n self.loss_stats, self.loss = self._get_losses(config)\n self.model_with_loss = ModelWithLoss(self.model, self.loss)\n\n if len(self.gpus) == 1 and self.gpu_str != '-1':\n torch.cuda.set_device(int(self.gpus[0]))\n self.device = torch.device('cuda' if torch.cuda.is_available() and self.gpu_str != '-1' else 'cpu')\n\n self.set_device(self.gpus, self.chunk_sizes, self.device)\n\n self.start_epoch = 0\n if self.resume_path != '':\n self.model, self.optimizer, self.start_epoch = load_model(\n self.model, self.resume_path, self.optimizer, self.lr, self.lr_step)\n\n\n self.train_loader = torch.utils.data.DataLoader(\n DATASET_CUSTOM(config, split='train'),\n batch_size=self.batch_size,\n shuffle=True,\n num_workers=self.num_workers,\n pin_memory=True\n )\n\n self.val_loader = torch.utils.data.DataLoader(\n DATASET_CUSTOM(config, split='val'),\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.num_workers,\n pin_memory=True\n )\n\n self.logger = Logger(config)\n\n def train(self):\n print('Starting training...')\n best = 1e10\n for epoch in range(self.start_epoch + 1, self.num_epochs + 1):\n log_dict_train, _ = self.run_epoch('train', epoch, self.train_loader)\n # Logger\n mark = epoch if self.save_all else 'last'\n self.logger.write('epoch: {} |'.format(epoch))\n for k, v in log_dict_train.items():\n self.logger.scalar_summary('train_{}'.format(k), v, epoch)\n self.logger.write('{} {:8f} | '.format(k, v))\n\n # Validation\n if self.val_intervals > 0 and epoch % self.val_intervals == 0:\n save_model(os.path.join(self.save_dir, 'model_{}.pth'.format(mark)),\n epoch, self.model, self.optimizer)\n\n with torch.no_grad():\n log_dict_val, preds = self.run_epoch('val', epoch, self.val_loader)\n for k, v in log_dict_val.items():\n self.logger.scalar_summary('val_{}'.format(k), v, epoch)\n self.logger.write('{} {:8f} | '.format(k, v))\n if log_dict_val[self.metric] < best: # best loss\n best = log_dict_val[self.metric]\n save_model(os.path.join(self.save_dir, 'model_best.pth'),\n epoch, self.model)\n else:\n save_model(os.path.join(self.save_dir, 'model_last.pth'),\n epoch, self.model, self.optimizer)\n self.logger.write('\\n')\n\n # Scale learning rate\n if epoch in self.lr_step:\n save_model(os.path.join(self.save_dir, 'model_{}.pth'.format(epoch)),\n epoch, self.model, self.optimizer)\n self.lr = self.lr * (0.1 ** (self.lr_step.index(epoch) + 1))\n print('Drop LR to', self.lr)\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = self.lr\n self.logger.close()\n\n\n def set_device(self, gpus, chunk_sizes, device):\n\n print(\"Set device: \", gpus, device)\n if len(gpus) > 1:\n self.model_with_loss = DataParallel(\n self.model_with_loss, device_ids=gpus).to(device)\n else:\n # print(\"Push model to cpu or one gpu \")\n self.model_with_loss = self.model_with_loss.to(device)\n\n for state in self.optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device=device, non_blocking=True)\n\n\n def run_epoch(self, phase, epoch, data_loader):\n model_with_loss = self.model_with_loss\n\n if phase == 'train':\n model_with_loss.train()\n else:\n if len(self.gpus) > 1:\n model_with_loss = self.model_with_loss.module\n model_with_loss.eval()\n torch.cuda.empty_cache()\n\n results = {}\n data_time, batch_time = AverageMeter(), AverageMeter()\n avg_loss_stats = {l: AverageMeter() for l in self.loss_stats}\n num_iters = len(data_loader) if self.num_iters < 0 else self.num_iters\n bar = Bar('{}'.format(self.exp_id), max=num_iters)\n end = time.time()\n for iter_id, batch in enumerate(data_loader):\n if iter_id >= num_iters:\n break\n data_time.update(time.time() - end)\n\n for k in batch:\n if k != 'meta':\n if k == 'input':\n batch[k] = batch[k].to(device=self.device, non_blocking=True, dtype=torch.float32)\n else:\n batch[k] = batch[k].to(device=self.device, non_blocking=True)\n # print(batch)\n output, loss, loss_stats = model_with_loss(batch)\n loss = loss.mean()\n if phase == 'train':\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n batch_time.update(time.time() - end)\n end = time.time()\n\n Bar.suffix = '{phase}: [{0}][{1}/{2}]|Tot: {total:} |ETA: {eta:} '.format(\n epoch, iter_id, num_iters, phase=phase,\n total=bar.elapsed_td, eta=bar.eta_td)\n\n for l in avg_loss_stats:\n avg_loss_stats[l].update(\n loss_stats[l].mean().item(), batch['input'].size(0))\n Bar.suffix = Bar.suffix + '|{} {:.4f} '.format(l, avg_loss_stats[l].avg)\n\n if not self.hide_data_time:\n Bar.suffix = Bar.suffix + '|Data {dt.val:.3f}s({dt.avg:.3f}s) ' \\\n '|Net {bt.avg:.3f}s'.format(dt=data_time, bt=batch_time)\n if self.print_iter > 0:\n if iter_id % self.print_iter == 0:\n print('{}| {}'.format(self.exp_id, Bar.suffix))\n else:\n bar.next()\n\n # if opt.debug > 0:\n # self.debug(batch, output, iter_id)\n #\n # if opt.test:\n # self.save_result(output, batch, results)\n del output, loss, loss_stats\n\n bar.finish()\n ret = {k: v.avg for k, v in avg_loss_stats.items()}\n ret['time'] = bar.elapsed_td.total_seconds() / 60.\n return ret, results\n\n def _get_losses(self, config):\n loss_states = ['loss', 'hm_loss', 'off_loss']\n loss = CombineLoss(config)\n return loss_states, loss\n\n\nclass CombineLoss(torch.nn.Module):\n def __init__(self, config):\n super(CombineLoss, self).__init__()\n self.crit = FocalLoss()\n self.crit_reg = RegL1Loss() if config['train']['reg_loss'] == 'l1' else \\\n RegLoss() if config['train']['reg_loss'] == 'sl1' else None\n\n self.config = config\n\n def forward(self, outputs, batch):\n config = self.config\n hm_loss, off_loss = 0, 0\n num_stacks = config['train']['num_stacks']\n for s in range(num_stacks):\n output = outputs[s]\n output['hm'] = _sigmoid(output['hm'])\n hm_loss += self.crit(output['hm'], batch['hm']) / num_stacks\n off_loss += self.crit_reg(output['reg'], batch['reg_mask'],\n batch['ind'], batch['reg']) / num_stacks\n\n loss = config['train']['hm_weight'] * hm_loss + config['train']['off_weight'] * off_loss\n loss_stats = {'loss': loss, 'hm_loss': hm_loss, 'off_loss': off_loss}\n\n return loss, loss_stats\n\n\nclass ModelWithLoss(torch.nn.Module):\n def __init__(self, model, loss):\n super(ModelWithLoss, self).__init__()\n self.model = model\n self.loss = loss\n\n def forward(self, batch):\n outputs = self.model(batch['input'])\n loss, loss_stats = self.loss(outputs, batch)\n return outputs[-1], loss, loss_stats\n\n\n","repo_name":"henryle97/IDCard-OCR","sub_path":"center/models/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":9832,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"3121536569","text":"import os\nimport numpy as np\nfrom copy import deepcopy\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\nfrom drl.algorithm import BasePolicy\nfrom drl.utils import ReplayBuffer\n\n\nclass DQN(BasePolicy): # navie DQN\n def __init__(\n self,\n model,\n action_shape=0,\n buffer_size=1000,\n batch_size=100,\n target_update_freq=1,\n target_update_tau=1,\n learning_rate=0.01,\n discount_factor=0.99,\n verbose=False\n ):\n super().__init__()\n self.lr = learning_rate\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.eps = np.finfo(np.float32).eps.item()\n self.tau = target_update_tau\n self.target_update_freq = target_update_freq\n # self.action_shape = action_shape\n self._gamma = discount_factor\n self._batch_size = batch_size\n self._verbose = verbose\n self._update_iteration = 10\n self._learn_cnt = 0\n self._normalized = lambda x, e: (x - x.mean()) / (x.std() + e)\n self.rew_norm = True\n self.buffer = ReplayBuffer(buffer_size)\n\n # self.declare_networks()\n self.critic_eval = model.value_net.to(self.device).train()\n self.critic_target = self.copy_net(self.critic_eval)\n\n self.critic_eval_optim = optim.Adam(self.critic_eval.parameters(), lr=self.lr)\n # self.critic_eval.train()\n\n self.criterion = nn.MSELoss()\n\n self.random_choose = 0\n self.sum_choose = 0\n\n def choose_action(self, state, test=False):\n state = torch.tensor(state, dtype=torch.float32, device=self.device).unsqueeze(0)\n # q_values = self.critic_eval(state)\n # action = q_values.argmax(dim=1).cpu().data.numpy()\n # action = action[0] if self.action_shape == 0 else action.reshape(self.action_shape) # return the argmax index\n\n # if test:\n # self.epsilon = 1.0\n # if np.random.randn() >= self.epsilon: # epsilon-greedy\n # self.random_choose += 1\n # action = np.random.randint(0, q_values.size()[-1])\n # action = action if self.action_shape == 0 else action.reshape(self.action_shape)\n\n # self.sum_choose += 1\n return self.critic_eval.action(state)\n\n def learn(self):\n for _ in range(self._update_iteration):\n batch_split = self.buffer.split_batch(self._batch_size)\n S = torch.tensor(batch_split['s'], dtype=torch.float32, device=self.device)\n A = torch.tensor(batch_split['a'], dtype=torch.float32, device=self.device).view(-1, 1)\n M = torch.tensor(batch_split['m'], dtype=torch.float32).view(-1, 1)\n R = torch.tensor(batch_split['r'], dtype=torch.float32).view(-1, 1)\n S_ = torch.tensor(batch_split['s_'], dtype=torch.float32, device=self.device)\n # print (f'SIZE S {S.size()}, A {A.size()}, M {M.size()}, R {R.size()}, S_ {S_.size()}')\n if self.rew_norm:\n R = self._normalized(R, self.eps)\n\n with torch.no_grad():\n argmax_action = self.get_max_action(S_)\n q_next = self.critic_target(S_).gather(1, argmax_action.type(torch.long))\n q_target = R + M * self._gamma * q_next.cpu()\n q_target = q_target.to(self.device)\n\n q_eval = self.critic_eval(S).gather(1, A.type(torch.long))\n\n critic_loss = self.criterion(q_eval, q_target)\n self.critic_eval_optim.zero_grad()\n critic_loss.backward()\n self.critic_eval_optim.step()\n\n self._learn_cnt += 1\n if self._learn_cnt % self.target_update_freq == 0:\n if self._verbose:\n print(f'=======Soft_sync_weight of DQN=======')\n self.soft_sync_weight(self.critic_target, self.critic_eval, self.tau)\n # print (f'Random {self.random_choose}, Sum {self.sum_choose}, ratio {self.random_choose/self.sum_choose}, epsilon {self.epsilon}')\n\n def get_max_action(self, next_state):\n return self.critic_target(next_state).max(dim=1, keepdim=True)[1]\n\n\nclass DoubleDQN(DQN):\n def __init__(self, critic, **kwargs):\n super().__init__(critic, **kwargs)\n\n def get_max_action(self, next_state): # choose max action by behavior network\n return self.critic_eval(next_state).max(dim=1, keepdim=True)[1]\n\n\nclass DuelingDQN(DQN):\n def __init__(self, critic, **kwargs):\n super().__init__(critic, **kwargs)\n self.critic_eval.use_dueling = True\n self.critic_target.use_deling = True\n\n\nclass DistributionDQN(DQN):\n def __init__(self, critic, **kwargs):\n super().__init__(critic, **kwargs)\n # todo\n\nclass NoisyDQN(DQN):\n def __init__(self, critic, **kwargs):\n super().__init__(critic, **kwargs)\n # todo","repo_name":"Taospirit/Light_RL","sub_path":"drl/algorithm/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"28764744250","text":"import os\nimport errno\nimport numpy as np\n\nfrom copy import deepcopy\nfrom miscc.config import cfg\n\nfrom miscc.save import save_image\nimport paddle\nimport paddle.nn as nn\n\n\n#############################\ndef KL_loss(mu, logvar):\n # -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n KLD_element = 1 + logvar - mu.pow(2) - logvar.exp()\n # mu.pow(2).add(logvar.exp()).multiply(-1).add(1).add(logvar)\n KLD = paddle.mean(KLD_element) * (-0.5)\n return KLD\n\n\ndef compute_discriminator_loss(netD, real_imgs, fake_imgs,\n real_labels, fake_labels,\n conditions, gpus):\n criterion = nn.BCELoss()\n batch_size = real_imgs.shape[0]\n cond = conditions.detach()\n fake = fake_imgs.detach()\n # real_features = nn.parallel.data_parallel(netD, (real_imgs), gpus)\n # fake_features = nn.parallel.data_parallel(netD, (fake), gpus)\n real_features = netD(real_imgs)\n fake_features = netD(fake)\n # real pairs\n # inputs = (real_features, cond)\n # real_logits = nn.parallel.data_parallel(netD.get_cond_logits, inputs, gpus)\n real_logits = netD.get_cond_logits(real_features, cond)\n errD_real = criterion(real_logits, real_labels)\n # wrong pairs\n # inputs = (real_features[:(batch_size-1)], cond[1:])\n # wrong_logits = \\\n # nn.parallel.data_parallel(netD.get_cond_logits, inputs, gpus)\n wrong_logits = netD.get_cond_logits(real_features[:(batch_size-1)], cond[1:])\n errD_wrong = criterion(wrong_logits, fake_labels[1:])\n # fake pairs\n # inputs = (fake_features, cond)\n # fake_logits = nn.parallel.data_parallel(netD.get_cond_logits, inputs, gpus)\n fake_logits = netD.get_cond_logits(fake_features, cond)\n errD_fake = criterion(fake_logits, fake_labels)\n\n if netD.get_uncond_logits is not None:\n # real_logits = \\\n # nn.parallel.data_parallel(netD.get_uncond_logits,\n # (real_features), gpus)\n real_logits = netD.get_uncond_logits(real_features)\n # fake_logits = \\\n # nn.parallel.data_parallel(netD.get_uncond_logits,\n # (fake_features), gpus)\n fake_logits = netD.get_uncond_logits(fake_features)\n uncond_errD_real = criterion(real_logits, real_labels)\n uncond_errD_fake = criterion(fake_logits, fake_labels)\n #\n errD = ((errD_real + uncond_errD_real) / 2. +\n (errD_fake + errD_wrong + uncond_errD_fake) / 3.)\n errD_real = (errD_real + uncond_errD_real) / 2.\n errD_fake = (errD_fake + uncond_errD_fake) / 2.\n else:\n errD = errD_real + (errD_fake + errD_wrong) * 0.5\n return errD, errD_real.detach()[0], errD_wrong.detach()[0], errD_fake.detach()[0]\n\n\ndef compute_generator_loss(netD, fake_imgs, real_labels, conditions, gpus):\n criterion = nn.BCELoss()\n cond = conditions.detach()\n # fake_features = nn.parallel.data_parallel(netD, (fake_imgs), gpus)\n fake_features = netD(fake_imgs)\n # fake pairs\n # inputs = (fake_features, cond)\n # fake_logits = nn.parallel.data_parallel(netD.get_cond_logits, inputs, gpus)\n fake_logits = netD.get_cond_logits(fake_features, cond)\n errD_fake = criterion(fake_logits, real_labels)\n if netD.get_uncond_logits is not None:\n # fake_logits = \\\n # nn.parallel.data_parallel(netD.get_uncond_logits,\n # (fake_features), gpus)\n fake_logits = netD.get_uncond_logits(fake_features)\n uncond_errD_fake = criterion(fake_logits, real_labels)\n errD_fake += uncond_errD_fake\n return errD_fake\n\n\n#############################\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n # m.weight.data.normal_(0.0, 0.02)\n m.weight.set_value(paddle.normal(0.0, 0.02, m.weight.shape))\n elif classname.find('BatchNorm') != -1:\n # m.weight.data.normal_(1.0, 0.02)\n # m.bias.data.fill_(0)\n m.weight.set_value(paddle.normal(1.0, 0.02, m.weight.shape))\n m.bias.set_value(paddle.zeros_like(m.bias))\n elif classname.find('Linear') != -1:\n # m.weight.data.normal_(0.0, 0.02)\n m.weight.set_value(paddle.normal(0.0, 0.02, m.weight.shape))\n if m.bias is not None:\n # m.bias.data.fill_(0.0)\n m.bias.set_value(paddle.zeros_like(m.bias))\n\n\n#############################\ndef save_img_results(data_img, fake, epoch, image_dir):\n num = cfg.VIS_COUNT\n fake = fake[0:num]\n # data_img is changed to [0,1]\n if data_img is not None:\n data_img = data_img[0:num]\n save_image(\n data_img, '%s/real_samples.png' % image_dir,\n normalize=True)\n # fake.data is still [-1, 1]\n save_image(\n fake.detach(), '%s/fake_samples_epoch_%03d.png' %\n (image_dir, epoch), normalize=True)\n else:\n save_image(\n fake.detach(), '%s/lr_fake_samples_epoch_%03d.png' %\n (image_dir, epoch), normalize=True)\n\n\ndef save_model(netG, netD, epoch, model_dir):\n paddle.save(\n netG.state_dict(),\n '%s/netG_epoch_%d.pdparams' % (model_dir, epoch))\n paddle.save(\n netD.state_dict(),\n '%s/netD_epoch_last.pdparams' % (model_dir))\n print('Save G/D models')\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n","repo_name":"Paddle-Team-7/StackGAN-Paddle-master","sub_path":"code/miscc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"19936145417","text":"from math import gamma\nfrom google.protobuf.symbol_database import Default\nimport numpy as np\nimport scipy\nimport scipy.io as sio\nfrom scipy.sparse.linalg import spsolve\nfrom ML_mesh_parameter import get_bound\nfrom ML_regular_temperature import get_A,get_b\nfrom pyMesh import hcubeMesh\n\n\nclass solver(object):\n def __init__(self,nx,ny,left_bound,right_bound,x_bound,y1,y2,h=0.01):\n self.nx = nx\n self.ny = ny\n self.left_bound = left_bound\n self.right_bound = right_bound\n self.x_bound = x_bound\n self.y1 = y1\n self.y2 = y2\n self.h = h\n def mesh(self):\n upx,upy,lowx,lowy,leftx,lefty,rightx,righty = get_bound(self.y1, self.y2, self.nx, self.ny, self.x_bound, self.left_bound, self.right_bound)\n myMesh=hcubeMesh(leftx,lefty,rightx,righty,lowx,lowy,upx,upy,self.h,True,True,tolMesh=1e-10,tolJoint=1)\n gamma = (myMesh.dydxi_ho ** 2 + myMesh.dxdxi_ho ** 2) \n beta = myMesh.dxdxi_ho * myMesh.dxdeta_ho + myMesh.dydxi_ho * myMesh.dydeta_ho\n alpha = (myMesh.dydeta_ho ** 2 + myMesh.dxdeta_ho ** 2)\n return myMesh,alpha,beta,gamma\n def get_result(self):\n myMesh,alpha,beta,gamma = solver.mesh(self)\n A = get_A(self.nx,self.ny,alpha,beta,gamma)\n b = get_b(self.nx,self.ny)\n t = spsolve(A, b)\n tem = t.reshape(self.ny,self.nx)\n return tem,myMesh\n\nif __name__ == '__main__':\n fd = solver(32,8,10,50,150,50,0)\n result = fd.get_result()[0]\n\n\n\n","repo_name":"baokairui/TFP-IGD","sub_path":"case1/FD_solver.py","file_name":"FD_solver.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"33936355326","text":"import random\n\nfrom django.shortcuts import render\n\nfrom . import util\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom markdown import Markdown\nfrom django.urls import reverse\n\nwiki_entries_directory = \"entries/\"\n\ndef index(request):\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": util.list_entries(),\n \"title\": \"Encyclopedia\"\n })\n\ndef title(request, title):\n entry_contents = util.get_entry(title)\n html_entry_contents = Markdown().convert(entry_contents) if entry_contents else None\n\n return render(request, \"encyclopedia/entry_page.html\", {\n \"body_content\": html_entry_contents,\n \"entry_exists\": entry_contents is not None,\n \"title\": title if entry_contents is not None else \"Error\"\n })\n \n\ndef search(request):\n query = request.GET['q']\n if util.get_entry(query):\n return HttpResponseRedirect(reverse( \"title\", args=(query,)))\n else:\n #query does not match\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": [entry for entry in util.list_entries() if query.lower() in entry.lower()],\n \"title\": f'\"{query}\" search results',\n \"heading\": f'Related search for \"{query}\" :'\n })\n \n\ndef new_page(request): \n return render(request, \"encyclopedia/new_page.html\",{\n 'edit_mode': False,\n 'edit_title_page':'',\n 'edit_page_content': ''\n })\n\n\ndef edit(request,title):\n entry_contents= util.get_entry(title)\n if entry_contents is None:\n #somebody came up with the url for editing a page that doesnot exists\n return HttpResponseRedirect(reverse('index'))\n \n return render( request, \"encyclopedia/new_page.html\", {\n \"edit_mode\": True,\n \"edit_title_page\": title,\n 'edit_page_contents': entry_contents\n })\n\ndef save_page(request, title=None):\n if request.method == 'GET':\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n assert (request.method == 'POST')\n entry_content = request.POST['entry_content']\n if not title:\n # We are saving a new page\n title = request.POST['title']\n if title.lower() in [entry.lower() for entry in util.list_entries()]:\n return render(request, \"encyclopedia/error.html\", {\n \"error_title\": \"saving page\",\n \"error_message\": \"An entry with that title already exists! Please change the title and try again.\"\n })\n\n filename = wiki_entries_directory + title + \".md\"\n with open(filename, \"w\") as f:\n f.write(entry_content)\n return HttpResponseRedirect(reverse(\"title\", args=(title,)))\n\n\ndef random_page(request):\n title = random.choice(util.list_entries())\n return HttpResponseRedirect(reverse(\"title\", args=(title,)))","repo_name":"neekesh/cs50-wiki","sub_path":"encyclopedia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74193694567","text":"import cv2, os, numpy as np\nfrom PIL import Image\n\ndef getImageLabel(path):\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n faceSamples = []\n faceIDs = []\n for imagePath in imagePaths:\n PILImg = Image.open(imagePath).convert(\"L\") # convert ke dalam gray\n imgNum = np.array(PILImg, \"uint8\")\n faceID = int(os.path.split(imagePath)[-1].split(\".\")[1])\n faces = faceDetector.detectMultiScale(imgNum)\n for (x, y, w, h) in faces:\n faceSamples.append(imgNum[y:y+h, x:x+w])\n faceIDs.append(faceID)\n return faceSamples, faceIDs\n\nfaceRecognizer = cv2.face.LBPHFaceRecognizer_create()\nfaceDetector = cv2.CascadeClassifier(\"/home/dhonihanif/Documents/obj_detection/PengenalanWajah/haarcascade_frontalface_default.xml\")\n\nprint(\"Mesin sedang melakukan training data wajah...\")\nfaces, IDs = getImageLabel(\"/home/dhonihanif/Documents/obj_detection/PengenalanWajah/datawajah\")\nfaceRecognizer.train(faces, np.array(IDs))\nfaceRecognizer.write(\"/home/dhonihanif/Documents/obj_detection/PengenalanWajah/latihwajah\"+\"/training.xml\")\nprint(\"Sebanyak {} data wajah ditraining ke mesin.\".format(len(IDs)))\n","repo_name":"dhonihanif/Expression_prediction_streamlit","sub_path":"expression_detection/LatihData.py","file_name":"LatihData.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"7638676025","text":"import numpy as np\nimport cv2 as cv\nimport glob\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \n\naruco_dict = cv.aruco.Dictionary_get(cv.aruco.DICT_6X6_1000)\naruco_side = 0.026\nnpzfile = np.load('calibration/cali_values.npz')\nmtx = npzfile['mtx']\ndist = npzfile['dist']\nret = npzfile['ret']\nrvecs = npzfile['rvecs']\ntvecs = npzfile['tvecs']\nplatform_markers = np.array([13,14,18,19], dtype=np.int32)\n\ndef ResizeWithAspectRatio(image, width=None, height=None, inter=cv.INTER_AREA):\n dim = None\n (h, w) = image.shape[:2]\n\n if width is None and height is None:\n return image\n if width is None:\n r = height / float(h)\n dim = (int(w * r), height)\n else:\n r = width / float(w)\n dim = (width, int(h * r))\n\n return cv.resize(image, dim, interpolation=inter)\n\ndef set_axes_equal(ax):\n '''Make axes of 3D plot have equal scale so that spheres appear as spheres,\n cubes as cubes, etc.. This is one possible solution to Matplotlib's\n ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n\n Input\n ax: a matplotlib axis, e.g., as output from plt.gca().\n '''\n\n x_limits = ax.get_xlim3d()\n y_limits = ax.get_ylim3d()\n z_limits = ax.get_zlim3d()\n\n x_range = abs(x_limits[1] - x_limits[0])\n x_middle = np.mean(x_limits)\n y_range = abs(y_limits[1] - y_limits[0])\n y_middle = np.mean(y_limits)\n z_range = abs(z_limits[1] - z_limits[0])\n z_middle = np.mean(z_limits)\n\n # The plot bounding box is a sphere in the sense of the infinity\n # norm, hence I call half the max range the plot radius.\n plot_radius = 0.5*max([x_range, y_range, z_range])\n\n ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])\n ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])\n ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])\n\nvideos = glob.glob('path_videos/*')\nfor fname in videos:\n print(fname)\n npzfile = np.load(fname)\n images = npzfile['images']\n T = np.empty( shape=(0, 0) )\n for img in images:\n # Detect aruco markers\n corners, ids, rejectedImgPoints\t= cv.aruco.detectMarkers(img, aruco_dict, mtx, dist)\n \n platform_idexes = np.in1d(ids, platform_markers)\n if (np.sum(platform_idexes) == 4):\n rvecs, tvecs, _objPoints = cv.aruco.estimatePoseSingleMarkers(corners, aruco_side, mtx, dist)\n if (T.size == 0):\n T = np.average(tvecs[platform_idexes == True], axis=0)\n else:\n T = np.vstack((T, np.average(tvecs[platform_idexes == True], axis=0)))\n\n print(np.shape(T))\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ax.plot (T[:,0], T[:,1], T[:,2])\n set_axes_equal(ax)\n \n\n plt.show()","repo_name":"CyberPoliceOfficer/Acrobat","sub_path":"Prototype/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71442970089","text":"#------------------import libraries-------------------------\nimport sys\n# from numba import jit, config\n# config.DISABLE_JIT = True\n\nfrom numpy import linalg as LA\nfrom threading import Thread\nimport math\nfrom numpy import genfromtxt\nfrom Paramload import readparams\n\n\nfrom funcs import *\nfrom Init_Load import *\nfrom PUdefs import *\nfrom scipy.optimize import *\nimport pyqtgraph as pg\nfrom PyQt5 import QtWidgets\n\n\nimport PySimpleGUI as sg\nimport pandas as pd\n\n# NEED TO reduce THE gfl transformer impedances bu 1/10th to get the GFL/Sync Cond mode working\n\npertb_inp=4\nsim_length = 200000\n\n\n#-------------------------- control params------------------------------------------\n\n\n#-----------------------initialize global variables--------------------------\n\n#-----sim parameter variables----------\nvarobs_y = 1\nvarobs_x = 0\nwindowlen = 500\ndelta_t = 3e-5\n\nplotstep = 100\n\n#--------conditional variables--------------\nshoweigs = 0\nparamset = 0\nnovals = 20\nshowpfvals = 0\nchangevarobs = 0\nshowpf = 0\nrecsnapshot = 0\nplotderivs = 0\nplottimeasx = 1\ninitsim = 0\nplotvarnum = 432\nnPlots = 54\n\ndef systemfunc():\n pi = math.pi\n\n # ---------------------------------get initial conditions from File-----------------------------\n x = initload()\n # x = np.ones((967))*1e-20\n ind = 0\n\n\n\n global params, inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr\n\n params, inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr = readparams()\n x= genfromtxt('init_snapshot.csv', delimiter=',')\n\n #------------solve for initialization------------------\n # x0 = np.ones((113)) * 1e-20\n # x = fsolve(func = initsolver, x0 = x, args=(params,inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr))#np.ones((74)) * 1e-20 #\n # x = leastsq(func = initsolver, x0 = x, args=(params,inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr),ftol=1.49012e-10, xtol=1.49012e-10) # leastsq works fine for the case where it doesnt solve with fsolve due to the 60Hz oscillatory mode in the detailed non aggregate system\n x = root(fun = initsolver,method='hybr', x0 = x, args=(params,inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr))#np.ones((74)) * 1e-20 #\n x=x.x\n\n\n #-----------------initialize graph objects----------------------\n\n dx = np.arange(len(x))\n dvar = np.empty([len(x)])\n\n #-----Eigenvalue Window--------------------\n win1 = pg.GraphicsLayoutWidget()\n win1.resize(800, 400)\n win1.setBackground('w')\n win1.show()\n #-----Transient Response Window--------------------\n win2 = pg.GraphicsLayoutWidget()\n win2.resize(800, 400)\n win2.setBackground('w')\n win2.show()\n #-----State Var Derivative Window--------------------\n win3 = pg.plot()\n win3.resize(800, 400)\n win3.setBackground('w')\n plotstatevarderiv = pg.BarGraphItem(x = dx, height = dvar,width = 0.6, brush=\"b\")\n win3.addItem(plotstatevarderiv)\n\n\n\n p1 = win1.addPlot()\n p1.showGrid(x=True, y=True, alpha=0.3)\n\n X=[]\n Y=[]\n out = [0]\n tx = [0]\n\n ploteignum = p1.plot(X, Y, symbolBrush=(255, 0, 0), symbol='o',pen=pg.mkPen(None))\n\n win2 = pg.GraphicsLayoutWidget()\n win2.resize(800, 400)\n win2.setBackground('w')\n win2.show()\n\n p2 = win2.addPlot(title=\"GFL Active power (pu)\")\n p2.showGrid(x=True, y=True, alpha=0.3)\n p2.addLegend()\n\n p3 = win2.addPlot(title=\"GFL Reactive power (pu)\")\n p3.showGrid(x=True, y=True, alpha=0.3)\n p3.addLegend()\n\n p4 = win2.addPlot(title=\"GFL Frequency (pu)\")\n p4.showGrid(x=True, y=True, alpha=0.3)\n p4.addLegend()\n\n p5 = win2.addPlot(title=\"GFL Voltage (pu)\")\n p5.showGrid(x=True, y=True, alpha=0.3)\n p5.addLegend()\n win2.nextRow()\n\n p6 = win2.addPlot(title=\"GFR Active power (pu)\")\n p6.showGrid(x=True, y=True, alpha=0.3)\n p6.addLegend()\n\n p7 = win2.addPlot(title=\"GFR Reactive power (pu)\")\n p7.showGrid(x=True, y=True, alpha=0.3)\n p7.addLegend()\n\n p8 = win2.addPlot(title=\"GFR Frequency (pu)\")\n p8.showGrid(x=True, y=True, alpha=0.3)\n p8.addLegend()\n\n p9 = win2.addPlot(title=\"GFR Voltage (pu)\")\n p9.showGrid(x=True, y=True, alpha=0.3)\n p9.addLegend()\n\n curvesPgfl = []\n curvesQgfl = []\n curvesWgfl = []\n curvesVgfl = []\n\n curvesPgfr = []\n curvesQgfr = []\n curvesWgfr = []\n curvesVgfr = []\n\n for idx in range(nPlots):\n curve_P = p2.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_Q = p3.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_W = p4.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_V = p5.plot(tx, out, pen=(idx, nPlots * 1.3))\n\n p2.legend.addItem(curve_P, 'P' + str(idx + 1) + '(pu)')\n p3.legend.addItem(curve_Q, 'Q' + str(idx + 1) + '(pu)')\n p4.legend.addItem(curve_W, 'W' + str(idx + 1) + '(pu)')\n p5.legend.addItem(curve_V, 'V' + str(idx + 1) + '(pu)')\n\n curvesPgfl.append(curve_P)\n curvesQgfl.append(curve_Q)\n curvesWgfl.append(curve_W)\n curvesVgfl.append(curve_V)\n\n for idx in range(nPlots):\n curve_P = p6.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_Q = p7.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_W = p8.plot(tx, out, pen=(idx, nPlots * 1.3))\n curve_V = p9.plot(tx, out, pen=(idx, nPlots * 1.3))\n\n p6.legend.addItem(curve_P, 'P' + str(idx + 1) + '(pu)')\n p7.legend.addItem(curve_Q, 'Q' + str(idx + 1) + '(pu)')\n p8.legend.addItem(curve_W, 'W' + str(idx + 1) + '(pu)')\n p9.legend.addItem(curve_V, 'V' + str(idx + 1) + '(pu)')\n\n curvesPgfr.append(curve_P)\n curvesQgfr.append(curve_Q)\n curvesWgfr.append(curve_W)\n curvesVgfr.append(curve_V)\n\n\n\n\n\n\n\n\n\n # data_PSCAD = np.genfromtxt(\"PSCAD_data.txt\", delimiter=\",\", names=[\"x\", \"y\"])\n # plotpscad = p4.plot(data_PSCAD['x'], data_PSCAD['y'], pen=\"b\", name='PSCAD Plot') # ----------------plot PSCAD response for validation SAved--------------------\n\n global text\n text = {}\n r = np.ones(76)\n for number in range(0, len(r)):\n text[\"text%i\" % number] = pg.TextItem('[%0.1f, %0.1f]' % (0, 0))\n text[\"text%i\" % number].setColor('k')\n p1.addItem(text[\"text\"+str(number)])\n\n w = pg.TableWidget()\n w.show()\n w.resize(600, 900)\n w.setWindowTitle('pyqtgraph example: TableWidget')\n\n\n\n\n def solver(x_hist):\n \"\"\"\n\n :param Pref1:\n :param x_hist:\n :param delta_t:\n :return:\n \"\"\"\n # assign history term value\n time = 0\n out = []\n tx = []\n\n global windowlen,plotvarnum\n\n outarr = np.zeros([0,plotvarnum])\n print(outarr)\n x_temp = np.zeros((len(x_hist)))\n time_splt = 0\n out_eigtest = np.zeros((len(x_hist)))\n\n global delta_t\n while time < sim_length:\n\n #--------------Re initialize the simulation----------\n global initsim,params,inputs,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr\n\n if initsim == 1:\n time = 0\n out = []\n tx = []\n x_temp = np.zeros((len(x_hist)))\n time_splt = 0\n outarr = np.zeros([0, plotvarnum ])\n\n params, inputs, bus_arr, genbus_ind, loadbus_ind, loadbus_no_arr, genbus_no_arr = readparams()\n x = genfromtxt('init_snapshot.csv', delimiter=',')\n x = fsolve(func=initsolver, x0=x, args=(params, inputs, bus_arr, genbus_ind, loadbus_ind, loadbus_no_arr, genbus_no_arr)) # np.ones((74)) * 1e-20 #\n\n x_hist = x\n initsim = 0\n\n # ---------------------load parameters from excel\n global paramset\n if paramset == 1:\n params, inputs, bus_arr, genbus_ind, loadbus_ind, loadbus_no_arr, genbus_no_arr = readparams()\n paramset = 0\n #------------------create simulation snapshot-------------------------\n global recsnapshot\n if recsnapshot == 1:\n np.savetxt(\"init_snapshot.csv\", x_hist)\n print(\"snapshot recorded\")\n recsnapshot = 0\n # call 4th order RK method\n x_hist,VARS = integrator(params, inputs, x_hist, delta_t,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr)\n time = time + delta_t\n\n #----------plot within plot step------------------\n if time > time_splt:\n global changevarobs\n if changevarobs == 1:\n out = []\n tx = []\n changevarobs = 0\n\n if outarr.shape[0] > windowlen:\n outarr = np.vstack((outarr[1:windowlen,:],VARS))\n else:\n outarr = np.vstack((outarr,VARS))\n\n global plottimeasx\n if plottimeasx == 1:\n if len(tx) > windowlen:\n tx = np.append(tx[1:windowlen], time)\n else:\n tx = np.append(tx, time)\n\n if plottimeasx == 0:\n if len(tx) > windowlen:\n tx = np.append(tx[1:windowlen], VARS[varobs_x])\n else:\n tx = np.append(tx, VARS[varobs_x])\n #-------------show all datapoints on plot-------------------------\n #--display solver solution-----\n #\n\n\n num_entries = 27 # Number of entries\n data = []\n for i in range(num_entries):\n base_index = i * 8\n entry = (\n 'P' + str(i * 2 + 1), VARS[base_index], 'Q' + str(i * 2 + 1), VARS[base_index + 1], 'V' + str(i * 2 + 1), VARS[base_index + 3],\n 'P' + str(i * 2 + 2), VARS[base_index + 4], 'Q' + str(i * 2 + 2), VARS[base_index + 5],'V' + str(i * 2 + 2), VARS[base_index + 7]\n )\n data.append(entry)\n #\n # for i in range(num_entries):\n # idx = i * 4 # Calculate the starting index for VARS based on entry number\n # entry = ('P' + str(i + 1), VARS[idx], 'Q' + str(i + 1), VARS[idx + 1],\n # 'V' + str(i + 1), VARS[idx + 3 + 216])\n # data.append(entry)\n\n\n\n w.setData(data)\n\n for i in range(nPlots):\n curvesPgfl[i].setData(tx, outarr[:, i * 4])\n curvesQgfl[i].setData(tx, outarr[:, (i * 4 + 1)])\n curvesWgfl[i].setData(tx, outarr[:, (i * 4 + 2)])\n curvesVgfl[i].setData(tx, outarr[:, (i * 4 + 3)])\n\n for i in range(nPlots):\n curvesPgfr[i].setData(tx, outarr[:, i * 4 + 216])\n curvesQgfr[i].setData(tx, outarr[:, (i * 4 + 1 + 216)])\n curvesWgfr[i].setData(tx, outarr[:, (i * 4 + 2 + 216)])\n curvesVgfr[i].setData(tx, outarr[:, (i * 4 + 3 + 216)])\n\n\n win2.setWindowTitle(\"Timestep: \" + str(delta_t))\n\n\n\n\n\n\n\n global plotderivs\n if plotderivs == 1:\n plotstatevarderiv.setOpts(height = np.abs((x_temp - x_hist) / delta_t))\n # x_arr = x_hist[863:1099]\n # data = np.zeros((len(x_arr)))\n # j = 0\n # i = 0\n # while i < len(x_arr) - 1:\n # data[j] = np.sqrt(x_arr[i] ** 2 + x_arr[i + 1] ** 2)\n # i = i + 2\n # j = j + 1\n #\n # plotstatevarderiv.setOpts(height = data)\n\n #-------------calculate eigenvalues dynamically-------------------------\n global showeigs\n if showeigs == 1:\n Xnum, Ynum, jac = num_linmodd(params, inputs, x_hist,bus_arr,genbus_ind,loadbus_ind,loadbus_no_arr,genbus_no_arr)\n ploteignum.setData(Xnum, Ynum)\n win1.setWindowTitle(\"Eigenvalue Plot\")\n if showpfvals == 1:\n pfabs = pfgen(jac)\n eigno = 0\n for eigtextref in text:\n pfordered = pfsort(pfabs, eigno, novals)\n\n states = pfordered[0, :]\n states = states.astype(int)\n pfvals = pfordered[1, :]\n\n res = \"\\n\".join(\"State:{} PF:{}\".format(x, y) for x, y in zip(states, pfvals))\n\n text[eigtextref].setPos(Xnum[eigno], Ynum[eigno])\n text[eigtextref].setText('Values: [%0.3f, %0.3f]\\nDamping ratio:[%0.3f]\\n%s' % (\n Xnum[eigno], Ynum[eigno], (-Xnum[eigno] / (np.sqrt(Xnum[eigno] ** 2 + Ynum[eigno] ** 2))),\n res))\n eigno = eigno + 1\n elif showpfvals == 0:\n eigno = 0\n for eigtextref in text:\n text[eigtextref].setPos(Xnum[eigno], Ynum[eigno])\n text[eigtextref].setText('Values: [%0.3f, %0.3f]\\nDamping ratio:[%0.3f]' % (\n Xnum[eigno], Ynum[eigno], (-Xnum[eigno] / (np.sqrt(Xnum[eigno] ** 2 + Ynum[eigno] ** 2)))))\n eigno = eigno + 1\n showeigs =0\n #---------------plot eiganvalues and participation factors-------------------\n global showpf\n if showpf == 1:\n if np.var((x_temp - x_hist) / delta_t) < 1e-10:\n print(\"Variance of state Derivatives = \", np.var((x_temp - x_hist) / delta_t))\n pfcalc(jac)\n eigplot(Xnum, Ynum)\n else:\n print(\"Variance of state Derivatives = \", np.var((x_temp - x_hist) / delta_t))\n print(\"not reached steady state\")\n\n showpf = 0\n\n p1.enableAutoRange(\"xy\", False)\n QtWidgets.QApplication.processEvents()\n time_splt = time_splt + delta_t * plotstep\n x_temp = x_hist\n\n return tx, out\n\n\n solver(x)\n win2.close()\n\n\ndef controlgui():\n\n def setparams():\n global paramset\n paramset = 1\n\n def recsnapshot():\n global recsnapshot\n recsnapshot = 1\n\n def changevarobs(varsel,varobsx,varobsy):\n global changevarobs\n global varobs_y\n global varobs_x\n global plottimeasx\n changevarobs = 1\n if varsel == True:\n plottimeasx = 1\n varobs_y = int(varobsy)\n elif varsel == False:\n plottimeasx = 0\n varobs_y = int(varobsy)\n varobs_x = int(varobsx)\n\n # def disable_input_varobsobsx():\n # if plotvarx_sel.get() == 1:\n # E9.config(state = 'disabled')\n # elif plotvarx_sel.get() == 2:\n # E9.config(state = 'normal')\n\n\n def showeigs(var):\n global showeigs\n if var == True:\n showeigs = 1\n elif var == False:\n showeigs = 0\n\n def showpfvals(var):\n global showpfvals\n if var == True:\n showpfvals = 1\n elif var == False:\n showpfvals = 0\n\n def plotderivs(var):\n global plotderivs\n if var == True:\n plotderivs = 1\n elif var == False:\n plotderivs = 0\n\n def genpf():\n global showpf\n showpf = 1\n def reinit():\n global initsim\n initsim = 1\n\n\n def setwindowlen(var):\n global windowlen\n windowlen = int(var)\n\n def setdt(var):\n global delta_t\n delta_t = float(var)\n\n def setpltwndw(var):\n global plotstep\n plotstep = int(var)\n\n\n def main_gui():\n\n\n layout = [ [sg.Text(\"Plotting Variables\", text_color= \"Blue\")], # Part 2 - The Layout\n [sg.Text(\"Y axis Plotting Variable\"), sg.Input(varobs_y, size = (10,1))],\n [sg.Text(\"X axis Plotting Variable\")],\n [sg.Radio(\"Time\", \"RADIO1\", default=True, change_submits = True, key = \"seltime\")],\n [sg.Radio(\"State Variable\", \"RADIO1\",default=False, change_submits = True, key = \"selstatevar\"), sg.Input(0, size = (10,1))],\n [sg.Button('Clear and Plot')],\n [sg.Text(\"Simulation parameters\", text_color= \"Blue\")],\n [sg.Text(\"Plot window length\"), sg.Input(windowlen, size = (10,1)), sg.Button('Update Window size')],\n [sg.Text(\"Simulation timestep\"), sg.Input(delta_t, size = (10,1)), sg.Button('Update Timestep')],\n [sg.Text(\"Plotstep\"), sg.Input(plotstep, size = (10,1)), sg.Button('Update Plotstep')],\n [sg.Text(\"View Analysis\", text_color= \"Blue\")],\n [sg.Checkbox(\"Generate Eigenvalues on Runtime\", change_submits = True, key='reltimeeig'),sg.Checkbox(\"Show Participation and States\", change_submits=True, key='shwpfvals')],\n [sg.Checkbox(\"View Statevar Derivatives\", change_submits = True, key='viewderiv'),sg.Button('Generate PF and Eigenvalue plots')],\n [sg.Button('Update Parameters')],\n [sg.Button(\"Re Initialize\")],\n [sg.Button('Generate initialization snapshot'),],\n ]\n\n window = sg.Window('Control GUI', layout)\n\n # Display and interact with the Window using an Event Loop\n while True:\n event, values = window.read()\n s = pd.Series(values)\n values = s.values\n print(values)\n if event == 'Update Parameters':\n setparams()\n if event == 'Update Window size':\n setwindowlen(values[4])\n if event == 'Update Timestep':\n setdt(values[5])\n if event == 'Update Plotstep':\n setpltwndw(values[6])\n if event == 'reltimeeig':\n showeigs(values[7])\n if event == 'shwpfvals':\n showpfvals(values[8])\n if event == 'Generate PF and Eigenvalue plots':\n genpf()\n if event == 'viewderiv':\n plotderivs(values[9])\n if event == 'Generate initialization snapshot':\n recsnapshot()\n if event == 'seltime':\n changevarobs(values[1],values[3],values[0])\n if event == 'selstatevar':\n changevarobs(values[1],values[3],values[0])\n if event == 'Clear and Plot':\n changevarobs(values[1],values[3],values[0])\n if event == 'Re Initialize':\n reinit()\n # See if user wants to quit or window was closed\n if event == sg.WINDOW_CLOSED or event == 'Quit':\n break\n # Finish up by removing from the screen\n window.close()\n main_gui()\n\nif __name__ == \"__main__\":\n thread_gui = Thread(target=controlgui)\n thread_sys = Thread(target=systemfunc)\n thread_gui.start()\n thread_sys.start()\n\n","repo_name":"shiroshpeiris/DPmodels","sub_path":"118_CONV_CPU/Exec.py","file_name":"Exec.py","file_ext":"py","file_size_in_byte":19416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20705082025","text":"\"\"\"LastFM tap class.\"\"\"\n\nfrom typing import List\n\nfrom singer_sdk import Stream, Tap\nfrom singer_sdk import typing as th # JSON schema typing helpers\n\nfrom tap_lastfm.streams import ScrobblesStream, UsersStream\n\nSTREAM_TYPES = [\n UsersStream,\n ScrobblesStream,\n]\n\n\nclass TapLastFM(Tap):\n \"\"\"LastFM tap class.\"\"\"\n\n name = \"tap-lastfm\"\n\n config_jsonschema = th.PropertiesList(\n th.Property(\n \"api_key\",\n th.StringType,\n required=True,\n description=\"The API key to authenticate against the API service\",\n ),\n th.Property(\n \"usernames\",\n th.ArrayType(th.StringType),\n required=True,\n description=\"The usernames of users to fetch scrobble data for\",\n ),\n th.Property(\n \"user_agent\",\n th.StringType,\n description=\"Passed to the API to identify the tool requesting data\",\n default=\"tap-lastfm\",\n ),\n th.Property(\n \"start_date\",\n th.DateTimeType,\n description=\"The earliest record date to sync\",\n ),\n th.Property(\n \"step_days\",\n th.IntegerType,\n description=\"The number of days to scan through before emitting state\",\n default=30,\n ),\n ).to_dict()\n\n def discover_streams(self) -> List[Stream]:\n \"\"\"Return a list of discovered streams.\"\"\"\n return [stream_class(tap=self) for stream_class in STREAM_TYPES]\n","repo_name":"rabidaudio/tap-lastfm","sub_path":"tap_lastfm/tap.py","file_name":"tap.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73618206888","text":"def solution(prices):\n answer = []\n\n for i in range(len(prices)): # 첫번째 루프\n count = 0 # 기본값\n for val in range(i+1, len(prices)): # 두번째 루프\n count += 1 # 루프가 남아있으면 +1\n if prices[i] > prices[val]: # 자신보다 작으면 break\n break\n answer.append(count) # 리스트 추가\n\n return answer\n","repo_name":"DanJeong-KR/programmers-algorithms","sub_path":"lv2/주식가격.py","file_name":"주식가격.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71060545127","text":"import TOOLS_COMMON as common\r\n\r\n\r\ndef main():\r\n find_cmd = common.get_find_cmd()\r\n check_battery_main(find_cmd)\r\n\r\n\r\ndef check_battery_main(find_cmd):\r\n battery_cmd = \"adb shell dumpsys battery | %s level\" % find_cmd\r\n result = common.run_shell(battery_cmd)\r\n cur_battery= result.split(\" \")[3].split(\"\\\\r\\\\n\")[0]\r\n battery_disp = \"当前电量为\"+cur_battery+\"%\"\r\n print(battery_disp)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Larry0122YY/NieR","sub_path":"NieR_exe/check_battery.py","file_name":"check_battery.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41858851869","text":"import re\nfrom django.core import validators\nfrom django.utils.deconstruct import deconstructible\n\n\n@deconstructible\nclass UsernameValidator(validators.RegexValidator):\n regex = r'^[a-z0-9-]+$'\n message = (\n '正しいユーザー名を入力してください。ユーザー名は必須です。'\n '半角の小文字英字と数字、ハイフンが入力できます。'\n )\n flags = re.ASCII\n","repo_name":"kanade0404/nanary-api","sub_path":"api/users/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73719384167","text":"from decimal import Decimal\nfrom lino_xl.lib.courses.desktop import *\nfrom lino.api import _\n\nfrom lino.core.gfks import gfk2lookup\nfrom lino.utils import join_elems\nfrom etgen.html import E\nfrom lino.modlib.users.mixins import My\nfrom lino_avanti.lib.avanti.roles import ClientsUser\nfrom lino_xl.lib.coachings.roles import CoachingsUser\n\n\n# Courses.required_roles = dd.login_required(Explorer)\n\n\n# class LinesByProvider(Lines):\n# master_key = 'provider'\n\nAllActivities.column_names = \"line:20 start_date:8 teacher user \" \\\n \"weekdays_text:10 times_text:10\"\n\n\nAllEnrolments.column_names = \"id request_date start_date end_date \\\nuser course pupil pupil__birth_date pupil__age pupil__country \\\npupil__city pupil__gender\"\n\n\nclass DitchingEnrolments(Enrolments):\n label = _(\"Absence control\")\n order_by = ['-missing_rate', 'pupil']\n column_names = \"missing_rate pupil course pupil__user *\"\n required_roles = dd.login_required(CoachingsUser)\n params_layout = \"coached_by min_missing_rate course_state state author participants_only\"\n @classmethod\n def param_defaults(self, ar, **kw):\n kw = super(DitchingEnrolments, self).param_defaults(ar, **kw)\n kw['coached_by'] = ar.get_user()\n kw['course_state'] = rt.models.courses.CourseStates.active\n kw['participants_only'] = True\n kw['min_missing_rate'] = Decimal(10)\n return kw\n\n @classmethod\n def get_request_queryset(self, ar):\n qs = super(DitchingEnrolments, self).get_request_queryset(ar)\n if isinstance(qs, list):\n return qs\n pv = ar.param_values\n if pv.coached_by is not None:\n qs = qs.filter(pupil__user=pv.coached_by)\n if pv.min_missing_rate:\n qs = qs.filter(missing_rate__gte=pv.min_missing_rate)\n return qs\n\n\n\nclass EnrolmentsByCourse(EnrolmentsByCourse):\n column_names = 'id #request_date pupil pupil__gender pupil__nationality:15 ' \\\n 'needs_childcare needs_school needs_bus needs_evening '\\\n 'remark missing_rate workflow_buttons *'\n\nclass PresencesByEnrolment(dd.Table):\n model = 'cal.Guest'\n master = 'courses.Enrolment'\n column_names = \"event event__state workflow_buttons absence_reason remark *\"\n display_mode = \"summary\"\n order_by = ['event__start_date', 'event__start_time']\n\n @classmethod\n def get_filter_kw(self, ar, **kw):\n Event = rt.models.cal.Event\n enr = ar.master_instance\n if enr is None:\n return None\n for k, v in gfk2lookup(Event.owner, enr.course).items():\n kw['event__'+k] = v\n kw.update(partner=enr.pupil)\n return super(PresencesByEnrolment, self).get_filter_kw(ar, **kw)\n\n @classmethod\n def get_table_summary(self, obj, ar):\n if ar is None:\n return ''\n sar = self.request_from(ar, master_instance=obj)\n\n coll = {}\n for obj in sar:\n if obj.state in coll:\n coll[obj.state] += 1\n else:\n coll[obj.state] = 1\n\n ul = []\n for st in rt.models.cal.GuestStates.get_list_items():\n ul.append(_(\"{} : {}\").format(st, coll.get(st, 0)))\n # elems = join_elems(ul, sep=', ')\n elems = join_elems(ul, sep=E.br)\n return ar.html_text(E.div(*elems))\n # return E.div(class_=\"htmlText\", *elems)\n\n# class CourseDetail(CourseDetail):\n# main = \"general cal_tab enrolments\"\n\n# general = dd.Panel(\"\"\"\n# line teacher start_date end_date start_time end_time\n# room #slot workflow_buttons id:8 user\n# name\n# description\n# \"\"\", label=_(\"General\"))\n\n# cal_tab = dd.Panel(\"\"\"\n# max_events max_date every_unit every\n# monday tuesday wednesday thursday friday saturday sunday\n# cal.EntriesByController\n# \"\"\", label=_(\"Calendar\"))\n\n# enrolments_top = 'enrolments_until max_places:10 confirmed free_places:10 print_actions:15'\n\n# enrolments = dd.Panel(\"\"\"\n# enrolments_top\n# EnrolmentsByCourse\n# \"\"\", label=_(\"Enrolments\"))\n\n\nEnrolments.detail_layout = \"\"\"\nrequest_date user start_date end_date\ncourse pupil\nneeds_childcare needs_school needs_bus needs_evening\nremark:40 workflow_buttons:40 printed:20 missing_rate:10\nconfirmation_details PresencesByEnrolment RemindersByEnrolment\n\"\"\"\n\nclass ActivityPlanning(Activities):\n required_roles = dd.login_required(CoursesUser)\n label = _(\"Course planning\")\n column_names = \\\n \"detail_link state \"\\\n \"max_places requested confirmed trying free_places \" \\\n \"school_needed childcare_needed bus_needed evening_needed *\"\n\n\nclass Reminders(dd.Table):\n required_roles = dd.login_required(ClientsUser)\n model = 'courses.Reminder'\n order_by = ['-date_issued']\n\n\nclass MyReminders(My, Reminders):\n can_create = False\n # pass\n\nclass RemindersByEnrolment(Reminders):\n column_names = 'date_issued degree remark workflow_buttons *'\n auto_fit_column_widths = True\n stay_in_grid = True\n master_key = 'enrolment'\n display_mode = 'summary'\n # can_create = True\n insert_layout = dd.InsertLayout(\"\"\"\n degree\n remark\n text_body\n \"\"\", window_size=(50,13))\n detail_layout = dd.DetailLayout(\"\"\"\n date_issued degree workflow_buttons\n remark\n enrolment user id printed\n text_body\n \"\"\", window_size=(80,20))\n\n\nclass RemindersByPupil(Reminders):\n column_names = 'date_issued enrolment user remark workflow_buttons *'\n auto_fit_column_widths = True\n # master = pupil_model\n master_key = 'enrolment__pupil'\n\n # @classmethod\n # def get_filter_kw(self, ar, **kw):\n # kw.update(enrolment__pupil=ar.master_instance)\n # return kw\n","repo_name":"lino-framework/avanti","sub_path":"lino_avanti/lib/courses/desktop.py","file_name":"desktop.py","file_ext":"py","file_size_in_byte":5721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14196113129","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('user_accounts', '0006_userprofile_did_extended_signup'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Subscription',\n fields=[\n ('profile', models.OneToOneField(related_name='subscription', primary_key=True, serialize=False, to='user_accounts.UserProfile')),\n ('general', models.BooleanField(default=True)),\n ('friend_notifications', models.BooleanField(default=True)),\n ],\n ),\n ]\n","repo_name":"sudo-woodo/hitmeup","sub_path":"communications/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"74789819047","text":"dial = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']\n\nalphabets = input()\n\nsum = len(alphabets)\nfor alphabet in alphabets:\n for i in range(len(dial)):\n if alphabet in dial[i]:\n sum += (i+2)\n\nprint(sum)","repo_name":"deltaori0/Python-Algorithm","sub_path":"baekjoon/step-by-step/step07/5622.py","file_name":"5622.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26526631967","text":"from ..base import ComponentAPI\n\n\nclass CollectionsItsm(object):\n \"\"\"Collections of ITSM APIS\"\"\"\n\n def __init__(self, client):\n self.client = client\n\n self.create_ticket = ComponentAPI(\n client=self.client, method=\"POST\", path=\"/api/c/compapi/v2/itsm/create_ticket/\", description=\"单据创建\"\n )\n","repo_name":"TencentBlueKing/bk-sops","sub_path":"packages/blueking/component/apis/itsm.py","file_name":"itsm.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":1001,"dataset":"github-code","pt":"53"}
+{"seq_id":"38795447631","text":"from decimal import Decimal\nfrom django.http import HttpResponse\n\nfrom django import forms\nfrom .models import Products, Invoices, InvoiceDetail, Customer, Agent, Payments\nfrom django.forms.models import inlineformset_factory\nfrom django.forms import modelformset_factory, inlineformset_factory\n\n\nclass UpdateProductForm(forms.ModelForm):\n\n class Meta:\n model = Products\n fields = ('description', 'category',\n 'quantity_in_stock', 'expire_date', 'unit_price',\n 'vendor', 'manufacturer', 'discount')\n\n\nclass InvoiceForm(forms.ModelForm):\n class Meta:\n model = Invoices\n exclude = ['amount', 'remaining', 'products', 'status']\n\n\n def valid_amount(self, invoice, amount):\n customer = invoice.customer\n\n if amount > customer.credit_limit:\n msg = 'The invoice Amount is above %s credit limit' %\\\n (customer.name,)\n self.add_error('customer', forms.ValidationError(msg))\n\n else:\n return True\n\n def clean(self):\n if any(self.errors):\n return\n\n invoice = super(InvoiceForm, self).clean()\n customer = invoice['customer']\n agent = invoice['agent']\n\n if invoice['discount'] > customer.max_discount:\n raise forms.ValidationError(\"the discount is above customer max discount limit\")\n\n if invoice['discount'] > agent.max_discount:\n raise forms.ValidationError(\"the discount is above agent max discount limit\")\n\n\nclass BaseDetailFormSet(forms.BaseInlineFormSet):\n\n def clean(self):\n super(BaseDetailFormSet, self).clean()\n if any(self.errors):\n return self.errors\n\n for form in self.forms:\n product = form.cleaned_data['product']\n if form.cleaned_data['quantity_sold'] > product.quantity_in_stock:\n raise forms.ValidationError('not enough products')\n\n\nclass CashPaymentForm(forms.ModelForm):\n class Meta:\n model = Payments\n fields = ('payment_number', 'amount')\n\n def __init__(self, invoice, *args, **kwargs):\n\n self.invoice = invoice\n super(CashPaymentForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n super(CashPaymentForm, self).clean()\n\n amount = self.cleaned_data['amount']\n if amount < self.invoice.amount:\n msg = 'The payment isn\\'t enough to pay this invoice'\n raise forms.ValidationError(msg)\n\nDetailFormset = inlineformset_factory(Invoices,\n InvoiceDetail,\n fields=('product', 'quantity_sold'),\n formset=BaseDetailFormSet,\n extra=1)\n\n","repo_name":"HossamEmam95/Inventory","sub_path":"Info-Blink/InventorySystem/inventory/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29767847978","text":"import sys\nimport json\nfrom HTMLParser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.allbugs_flag = False\n self.allbugs_num = 0\n\n def handle_data(self, data):\n if self.allbugs_flag == True:\n self.allbugs_num = data\n self.allbugs_flag = False\n\n if data == 'All Bugs':\n self.allbugs_flag = True\n\n def get_bugs_num(self):\n return self.allbugs_num\n\n\ndef convert(html_file, json_file):\n p = MyHTMLParser()\n p.feed(open(html_file, 'r').read())\n\n num = p.get_bugs_num()\n d = {'All Bugs': num}\n\n json.dump(d, open(json_file, 'w'))\n\n\nif __name__ == \"__main__\":\n convert(sys.argv[1], sys.argv[2])\n","repo_name":"gitredlocus/gears","sub_path":"tools/parsers/clang_parser.py","file_name":"clang_parser.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42419932178","text":"import picamera\nimport requests\nfrom PIL import Image\nfrom time import sleep\n\ncamera = picamera.PiCamera() \ncamera.resolution = (820, 616)\ncamera.color_effects = (128,128)\ncamera.shutter_speed = 6000000\ncamera.sharpness = 100\n\ntry:\n\tcamera.start_preview()\n\tprint(\"started\")\n\tkey = input()\n\tif key == 1:\n\t\tprint(\"key press\")\n\t\tcamera.capture('ocr.jpeg')\n\t\timg = Image.open('ocr.jpeg').rotate(270)\n\t\timg.save('ocr.jpeg')\n\t\t#$fileIn = open('ocr.jpeg', 'rb').read()\n\t\t#r = requests.post(\"http://www.techundertwenty.com/save.php\", data={'content': fileIn, 'name': \"ocr.jpeg\"})\n\t\t#print(r.text)\n\tcamera.stop_preview()\nexcept KeyboardInterrupt:\n\tprint(\"end\")\n\tcamera.stop_preview()\n\tcamera.close()\nfinally:\n\tcamera.close()\n","repo_name":"derrekchow/point2speech","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8605367769","text":"import requests\nfrom AnimeRank.src.control.platforms.base import BasePlatform\n\n\nclass MyanimelistPlatform(BasePlatform):\n ...\n\n def crawl(self, *args, **kwargs):\n url = \"https://myanimelist.net/anime/season/2020/winter\"\n res = requests.get(url)\n print(res.text)\n\n @staticmethod\n def parseHtml(html):\n ...\n\nif __name__ == '__main__':\n pt = MyanimelistPlatform()\n pt.crawl()","repo_name":"Niyuhang/AnimeRank","sub_path":"src/control/platforms/myanimelist_platform.py","file_name":"myanimelist_platform.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"36511567758","text":"# coding: utf-8\n\nimport pandas as pd\nfrom sklearn.cluster import SpectralClustering\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\nfp = 'D:\\深圳杯比赛\\数据\\\\test.csv'\n\nwith open(fp, 'r', encoding='gb18030') as f:\n df_origin = pd.read_csv(f, index_col=0)\n\nfeatures = df_origin.values\ny_pred = SpectralClustering(n_clusters=2, gamma=1).fit_predict(features)\nprint(\"Calinski-Harabasz Score with gamma=\", 1, \"n_clusters=\", 2,\"score:\", metrics.calinski_harabaz_score(features, y_pred))\n\nfor i in range(4):\n plot_features = features[:, i:i + 2]\n plt.subplot(2, 2, i + 1), plt.scatter(plot_features[:, 0], plot_features[:, 1], c=y_pred)\n\nplt.show()\n","repo_name":"LILeilei66/competition_shenzhen","sub_path":"data_process/0test/01demo_sector.py","file_name":"01demo_sector.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31565348976","text":"from django.urls import reverse\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nfrom .provider_model import Provider\nfrom .product_model import Product\n\n\nclass Shipment(models.Model):\n status_choice = (\n ('CRTD', 'Создан'),\n ('PRCSG', 'На отгрузке'),\n ('CMPLTD', 'Отгружено'),\n )\n\n product = models.ForeignKey(Product, default=1)\n status = models.CharField(max_length=7, choices=status_choice, default='CRTD', verbose_name='Статус')\n customer = models.CharField(max_length=100, verbose_name='Покупатель')\n provider = models.ForeignKey(Provider, default=0, verbose_name='Поставщик')\n transporter = models.CharField(max_length=100, verbose_name='Перевозчик')\n address = models.CharField(max_length=200, null=True, verbose_name='Адрес')\n\n description = models.TextField(blank=True, null=True, verbose_name='Описание')\n manager = models.ForeignKey(User)\n\n volume = models.IntegerField(default=10, verbose_name='Объем')\n\n price = models.IntegerField(default=0, verbose_name='Цена')\n cost_in = models.IntegerField(default=0, verbose_name='Стоимость (входящая)')\n cost_out = models.IntegerField(default=0, verbose_name='Стоимость (продажная)')\n profit = models.IntegerField(default=0, verbose_name='Прибыль')\n\n time_created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')\n time_updated = models.DateTimeField(auto_now=True, verbose_name='Дата изменения')\n time_completed = models.DateTimeField(blank=True, null=True, verbose_name='Дата обработки')\n\n class Meta:\n verbose_name = \"Отгрузка\"\n verbose_name_plural = \"Отгрузки\"\n\n def save(self, *args, **kwargs):\n self.profit = (self.cost_out - self.cost_in) * self.volume\n self.price = self.cost_out * self.volume\n\n super(Shipment, self).save(*args, **kwargs)\n\n def __str__(self):\n return '{} - {}'.format(self.product.name, self.volume)\n\n def get_absolute_url(self):\n return reverse('shipment-detail', kwargs={'pk': self.pk})\n","repo_name":"zaibandr/dockerizing_stroy_mat","sub_path":"web/has_app/models/shipment_models.py","file_name":"shipment_models.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4449374369","text":"from .models import UrlShortened\nfrom rest_framework import serializers\n\n\nclass UrlSerializer(serializers.ModelSerializer):\n url = serializers.URLField(required=True)\n name = serializers.CharField(required=False)\n date_expiration = serializers.DateTimeField(required=False)\n\n class Meta:\n model = UrlShortened\n fields = [\"url\", \"name\", \"date_expiration\"]\n\n\nclass UrlRetriveSerializer(serializers.ModelSerializer):\n class Meta:\n model = UrlShortened\n fields = [\"url\"]\n","repo_name":"wl4dek/mobi2buy","sub_path":"short_url/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30421386127","text":"from collections import deque\n\nn,m = map(int,input().split())\n\n# print(a,b)\ngraph = []\nfor i in range(n):\n k = list(input())\n for j in range(m):\n if k[j] == 'R':\n r = [i,j]\n if k[j] == 'B':\n b = [i,j]\n graph.append(k)\n\n# print(r,b,graph)\n# print(a,b)\nvisited = [[[[False] * m for i in range(n)] for i in range(m)] for i in range(n)]\n\ndx = [1,-1,0,0]\ndy = [0,0,1,-1]\n\ndef move(rx,ry,dx,dy):\n c = 0\n while graph[rx+dx][ry+dy] != '#' and graph[rx][ry] != 'O':\n rx += dx\n ry += dy\n c +=1\n return rx,ry,c\ndef bfs():\n q = deque()\n q.append((r[0],r[1],b[0],b[1],1))\n visited[r[0]][r[1]][b[0]][b[1]] = True\n while q:\n rx,ry,bx,by,cnt = q.popleft()\n if cnt > 10:\n break\n for i in range(4):\n nrx,nry,rd = move(rx,ry,dx[i],dy[i])\n nbx,nby,bd = move(bx,by,dx[i],dy[i])\n if graph[nbx][nby] != \"O\":\n if graph[nrx][nry] == \"O\":\n print(cnt)\n return\n if nbx == nrx and nby == nry :\n if rd > bd :\n nrx -=dx[i]\n nry -=dy[i]\n else:\n nbx -=dx[i]\n nby -=dy[i]\n if visited[nrx][nry][nbx][nby] == False:\n visited[nrx][nry][nbx][nby] == True\n q.append((nrx,nry,nbx,nby,cnt+1))\n print(-1)\n\nbfs()","repo_name":"JunHyungJang/codingtest","sub_path":"Baekjoon/graphs/13460.py","file_name":"13460.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26166075132","text":"import sys\nsys.path.insert(1,'/home/pi/Desktop/AWHT/code/tester_files')\nfrom Sql_db import *\nfrom openpyxl import load_workbook\n\n\n\ndef CuttingChart_import(From_pos,Cavity_no_pos,To_pos,Cavity_no1_pos,Name_pos,Color_pos,WireGauge_pos,Splice_name,path):\n ##########################################################################################################################################\n workbook = load_workbook('CuttingChartData.xlsx')\n worksheet = workbook['Cuttting_Chart']\n ##########################################################################################################################################\n ## Ram variable\n From=[]\n Cavity_no=[]\n To=[]\n Cavity_no1=[]\n Name=[]\n Color=[]\n WireGauge=[]\n Splice_name=\"S-\"\n Splice_max=0\n Splice_m=0\n splice_list=[]\n Splice_Replace=[]\n\n From_Temp=[]\n To_Temp=[]\n Name_Temp=[]\n Color_Temp=[]\n WireGauge_Temp=[]\n\n Name1=[]\n Color1=[]\n WireGauge1=[]\n ##########################################################################################################################################\n\n connlst = get_allConLib()\n\n #print(worksheet.max_row)\n\n for i in range(2,worksheet.max_row+1):\n From.append(str(worksheet.cell(i,From_pos).value))\n Cavity_no.append(str(worksheet.cell(i,Cavity_no_pos).value))\n To.append(str(worksheet.cell(i,To_pos).value))\n Cavity_no1.append(str(worksheet.cell(i,Cavity_no1_pos).value))\n Name.append(str(worksheet.cell(i,Name_pos).value))\n Color.append(str(worksheet.cell(i,Color_pos).value))\n WireGauge.append(str(worksheet.cell(i,WireGauge_pos).value))\n\n ##########################################################################################################################################\n ## Join connector name and cavity no eg-Con1-1 con2-3 from both TO and From table\n ## From ['Con 1-1', 'Con 1-2', 'Con 1-2', 'Con 1-3', 'S-1', 'S-1', 'S-A', 'S-A', 'S-A', 'S-B']\n ## To ['Con 3-1', 'Con 3-2', 'Con 3-3', 'S-1', 'Con 3-4', 'Con 4-1', 'CON5-1', 'CON7-1', 'S-B', 'CON6-1']\n\n for i in range (len(From)):\n if(Splice_name not in From[i]):\n From[i]=From[i]+\"-\"+Cavity_no[i]\n if(Splice_name not in To[i]):##if __name__ == '__main__':\n\n To[i]=To[i]+\"-\"+Cavity_no1[i]\n ##print(\"From\",From)\n ##print(\"To \",To)\n\n ##########################################################################################################################################\n ## find no of splice name eg: ['S-1', 'S-A', 'S-B']\n\n for i in range(len(From)):\n if(Splice_name in From[i]):\n if(From[i] not in splice_list ):\n splice_list.append(From[i])\n\n for i in range(len(To)):\n if(Splice_name in To[i]):\n if(To[i] not in splice_list ):\n splice_list.append(To[i])\n #print(splice_list)\n ##########################################################################################################################################\n ## find splice position and its replacement cavity no ['Con 1-3', 'CON5-1', 'CON5-1'] replace all splice with respective splice replacement variable\n ##\n\n flag1=0\n flag2=0\n for i in range(len(splice_list)):\n flag1=0\n flag2=0\n replace=None\n \n try:\n x=From.index(splice_list[i])\n flag1=1\n except ValueError:\n flag1=0\n \n try:\n y=To.index(splice_list[i])\n flag2=1\n except ValueError:\n flag2=0\n if(flag1==1 and flag2==1):\n if(x>y):\n Splice_Replace.append(From[y])\n replace=From[y]\n else:\n Splice_Replace.append(To[x])\n replace=To[x]\n if(flag1==1 and flag2==0):\n Splice_Replace.append(To[x])\n replace=To[x]\n if(flag1==0 and flag2==1):\n Splice_Replace.append(From[y])\n replace=From[y]\n \n if(flag1==1 or flag2==1):\n for j in range(len(To)):\n if(splice_list[i]==To[j]):\n To[j]=replace\n if(splice_list[i]==From[j]):\n From[j]=replace\n ##########################################################################################################################################\n ## Remove same net eg: CON5-1 CON5-1 ALSO DELETE UNNESARY BLOCK FROM Name,COLOUR,WIREGAUGE\n\n for i in range(len(To)):\n if(From[i]!=To[i]):\n To_Temp.append(To[i])\n From_Temp.append(From[i])\n Name_Temp.append(Name[i])\n Color_Temp.append(Color[i])\n WireGauge_Temp.append(WireGauge[i])\n\n\n## print(\"From\",From_Temp)\n## print(\"To \",To_Temp)\n## print(\"Name\",Name_Temp)\n## print(\"Color\",Color_Temp)\n## print(\"WireGauge\",WireGauge_Temp)\n##########################################################################################################################################\n ## IMPORT DATA FROM SQDB TO RAM VARIABLE.\n HN1 = []\n HN2 = []\n for i in range(len(From_Temp)):\n f = From_Temp[i]\n t = To_Temp[i]\n # if not('None' in f):\n (conn1,q1) = f.split('-')\n out1 = get_LibMap(conn1)[0][1]\n out2 = get_LibMap(conn2)[0][1]\n pt1 = get_Points(out1)\n pt2 = get_Points(out2)\n # print(conn2)\n try:\n HN1.append(pt1[int(q1)-1][0])\n HN2.append(pt2[int(q2)-1][0])\n except:\n print('error')\n## print('HN1',HN1)\n## print('HN2',HN2)\n##########################################################################################################################################\n##combine HN1 AND HN2\n ckt_lst=[[] for i in range(len(HN1))]\n ckt_lst1=[[] for i in range(len(HN1))]\n \n for i in range(len(HN1)):\n ckt_lst[i].append(HN1[i])\n ckt_lst[i].append(HN2[i])\n\n## print(ckt_lst)\n\n key=0\n maxnum=max(HN1)\n key=0\n remove_list=[]\n for i in range(maxnum):\n key=i+1\n for j in range(len(HN1)):\n if (key==HN1[j]):\n if HN1[j] not in ckt_lst1[i]:\n ckt_lst1[i].append(key)\n ckt_lst1[i].append(HN2[j])\n Color1.append(Color_Temp[j])\n Name1.append(Name_Temp[j])\n WireGauge1.append(WireGauge_Temp[j])\n else:\n ckt_lst1[i].append(HN2[j])\n \n ckt_pt=[]\n for i in ckt_lst1:\n if (len(i))>0:\n ckt_pt.append(i)\n \n \n## print(\"ckt_pt\",ckt_pt)\n\n Location_No = 1\n circuits = ckt_pt\n Wire_Type = Name1\n Wire_color1 = Color1\n Wire_color2 = Color1\n Wire_Gauge = WireGauge1\n\n print(\"circuits\",circuits)\n print(\"Wire_Type\",Wire_Type)\n print(\"Wire_color1\",Wire_color1)\n print(\"Wire_color2\",Wire_color2)\n print(\"WireGauge\",Wire_Gauge)\n\n \n UploadHarnessData(GV.Location_No,circuits,Wire_Type,Wire_color1,Wire_color2,Wire_Gauge)\n\n##########################################################################################################################################\nif __name__ == '__main__':\n ## following Argument needed\n From_pos=1\n Cavity_no_pos=2\n To_pos=3\n Cavity_no1_pos=4\n Name_pos=5\n Color_pos=6\n WireGauge_pos=7\n Splice_name=\"S-\"\n path=\"x\"\n CuttingChart_import(From_pos,Cavity_no_pos,To_pos,Cavity_no1_pos,Name_pos,Color_pos,WireGauge_pos,Splice_name,path)\n","repo_name":"sanjayjadhav77/Harness_analyser","sub_path":"code/tester_files/CuttingChart_import.py","file_name":"CuttingChart_import.py","file_ext":"py","file_size_in_byte":7630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1960874195","text":"\"\"\"empty message\n\nRevision ID: 0c73aa7cc580\nRevises: 328410ca6c55\nCreate Date: 2020-07-09 02:43:26.663224\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0c73aa7cc580'\ndown_revision = '328410ca6c55'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('Application', sa.Column('user_id', sa.Integer(), nullable=True))\n op.add_column('Application', sa.Column('uuid', sa.String(), nullable=True))\n op.create_foreign_key(None, 'Application', 'user', ['user_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'Application', type_='foreignkey')\n op.drop_column('Application', 'uuid')\n op.drop_column('Application', 'user_id')\n # ### end Alembic commands ###\n","repo_name":"cadia-lvl/LOBE","sub_path":"migrations/versions/0c73aa7cc580_.py","file_name":"0c73aa7cc580_.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"35681170026","text":"from hashlib import new\r\nimport tarfile\r\n\r\n\r\nclass Node:\r\n def __init__(self, data) -> None:\r\n self.prevNode=None\r\n self.data = data\r\n self.nextNode = None\r\nclass LinkedList:\r\n def __init__(self) -> None:\r\n self.head=None\r\n def showList(self):\r\n if self.head == None:\r\n print(\"Linled List is Empty\")\r\n else:\r\n tempNode = self.head\r\n while(tempNode is not None):\r\n print(tempNode.data, end=\" \")\r\n tempNode = tempNode.nextNode\r\n print()\r\n def insertStart(self,data):\r\n if self.head==None:\r\n self.head=Node(data)\r\n else:\r\n new_node=Node(data)\r\n oldHead=self.head\r\n new_node.nextNode=oldHead\r\n oldHead.prevNode=new_node\r\n self.head=new_node\r\n\r\n def insertEnd(self, data):\r\n temp=self.head\r\n while temp.nextNode!=None:\r\n temp=temp.nextNode\r\n else:\r\n new_node=Node(data)\r\n temp.nextNode=new_node\r\n new_node.prevNode=temp\r\n def insertAfter(self,data,target):\r\n\r\n temp=self.head\r\n while temp != None:\r\n if temp.data==target:\r\n break\r\n else:\r\n temp=temp.nextNode \r\n if temp == None:\r\n print(\"{} not found\".format(target))\r\n else:\r\n print(temp.data)\r\n new_node=Node(data)\r\n\r\n new_node.nextNode=temp.nextNode\r\n temp.nextNode.prevNode=new_node\r\n temp.nextNode=new_node\r\n new_node.prevNode=temp\r\n \r\n # currentNode=temp.nextNode\r\n # new_node.prevNode=currentNode.prevNode\r\n # temp.nextNode=new_node\r\n # new_node.nextNode=currentNode\r\n # currentNode.prevNode=new_node\r\n\r\n \r\n def insertBefore(self,data,target):\r\n if self.head.data==target:\r\n self.insertStart(data)\r\n return \r\n else:\r\n temp=self.head\r\n while temp.nextNode!=None:\r\n if temp.nextNode.data==target:\r\n break\r\n else:\r\n temp=temp.nextNode\r\n if temp.nextNode == None:\r\n print(\"{} not found\".format(target))\r\n else:\r\n new_node=Node(data)\r\n currentNext=temp.nextNode\r\n new_node.prevNode=temp\r\n new_node.nextNode=temp.nextNode\r\n temp.nextNode=new_node\r\n def remove(self,start=None,end=None,target=None):\r\n try:\r\n # remove the first node\r\n if start==True:\r\n if self.head==None:\r\n print(\"Linked List is Empty\")\r\n else:\r\n self.head=self.head.nextNode\r\n self.head.prevNode=None\r\n # remove the last node\r\n if end==True:\r\n if self.head==None:\r\n print(\"Linked List is Empty\")\r\n else:\r\n temp=self.head\r\n while temp!=None:\r\n if temp.nextNode.nextNode==None:\r\n break\r\n else:\r\n temp=temp.nextNode\r\n temp.nextNode=None\r\n \r\n # remove the node containing target value\r\n if target!=None:\r\n if self.head==None:\r\n print(\"Linked List is Empty\")\r\n elif target==self.head.data:\r\n self.remove(start=True)\r\n else:\r\n temp=self.head\r\n while temp.nextNode!=None:\r\n if temp.nextNode.data==target:\r\n break\r\n else:\r\n temp=temp.nextNode\r\n if temp.nextNode==None:\r\n print(\"Cannot remove {} Element Not Found\".format(target))\r\n else:\r\n temp.nextNode=temp.nextNode.nextNode\r\n except Exception as e:\r\n print(\"Linked List is Empty\")\r\n self.head=None\r\n def traverseReverse(self):\r\n n=self.head\r\n while n.nextNode is not None:\r\n n=n.nextNode\r\n while n.prevNode is not None:\r\n print(n.data,end=\" \")\r\n n=n.prevNode\r\n print(n.data)\r\n\r\n\r\ndef main():\r\n l1=LinkedList()\r\n l1.insertStart(12)\r\n l1.insertStart(11)\r\n l1.insertStart(114)\r\n l1.insertStart(112)\r\n l1.insertEnd(77777)\r\n l1.showList()\r\n l1.insertAfter(213,11)\r\n l1.showList()\r\n l1.insertBefore(0,1131)\r\n l1.showList()\r\n l1.remove(end=True)\r\n l1.showList()\r\n l1.traverseReverse()\r\nmain()","repo_name":"rayyan-24/Python-Resources","sub_path":"DSA Python/7_doublyLinkedList.py","file_name":"7_doublyLinkedList.py","file_ext":"py","file_size_in_byte":4793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26221505375","text":"import os\nimport fnmatch\nimport string\nfrom collections import deque\n\n\nclass __dir_tree_printer:\n\n def __init__(self, root_name=None, other_ignore_list=None):\n self.print_list = [\"root/\"] if root_name is None else [root_name]\n self.ignore_list = [\".git/\"] if other_ignore_list is None else list(other_ignore_list)\n self.bar_vert = chr(9474)\n self.bar_horz = chr(9472)\n self.bar_T = chr(9500)\n\n\n def should_ignore(self, entry, path):\n for pat in self.ignore_list:\n if fnmatch.fnmatch(entry, pat):\n print(\"-- ignore pattern: {0} -> ignored: {1}\".format(pat, path))\n return True\n return False\n\n\n def print_sub_dir(self, sub_dir_name, traversal_path):\n traversal_path = traversal_path[:-1]\n str_print = []\n for traversed in traversal_path:\n if traversed == \"1\":\n str_print.append(self.bar_vert + \" \"*3)\n else:\n str_print.append(\" \"*4)\n str_print.extend([self.bar_T + self.bar_horz*3, sub_dir_name])\n str_print = \"\".join(str_print)\n self.print_list.append(str_print)\n\n\n def print_files(self, files, traversal_path):\n for file in files:\n str_print = []\n for traversed in traversal_path:\n if traversed == \"1\":\n str_print.append(self.bar_vert + \" \"*3)\n else:\n str_print.append(\" \"*4)\n str_print.append(file)\n str_print = \"\".join(str_print)\n self.print_list.append(str_print)\n\n\n def walk_dir(self, dir, traversal_path=\"\"):\n files = []\n sub_dirs = deque([])\n\n for entry in os.scandir(dir):\n name = entry.name\n if entry.is_dir():\n name += \"/\"\n sub_dirs.append(name)\n elif entry.is_file():\n files.append(name)\n\n if len(sub_dirs) == 0:\n traversal_path += \"0\"\n else:\n traversal_path += \"1\"\n self.print_files(files, traversal_path) # Print files\n\n while True:\n if len(sub_dirs) > 0:\n sub_dir = sub_dirs.popleft()\n self.print_sub_dir(sub_dir, traversal_path) # Print sub_dirs\n\n if len(sub_dirs) == 0: # Modify after printing (last sub_dir)\n traversal_path = traversal_path[:-1] + \"0\"\n\n self.walk_dir(os.path.join(dir, sub_dir), traversal_path) # Recursive DFS\n else:\n break\n\n\n def walk_dir_with_ignore(self, dir, traversal_path=\"\"):\n files = []\n sub_dirs = deque([])\n\n for entry in os.scandir(dir):\n name = entry.name\n if entry.is_dir():\n name += \"/\"\n if self.should_ignore(name, os.path.join(dir, name)):\n continue\n sub_dirs.append(name)\n elif entry.is_file():\n if self.should_ignore(name, os.path.join(dir, name)):\n continue\n files.append(name)\n\n if len(sub_dirs) == 0:\n traversal_path += \"0\"\n else:\n traversal_path += \"1\"\n self.print_files(files, traversal_path) # Print files\n\n while True:\n if len(sub_dirs) > 0:\n sub_dir = sub_dirs.popleft()\n self.print_sub_dir(sub_dir, traversal_path) # Print sub_dirs\n\n if len(sub_dirs) == 0: # Modify after printing (last sub_dir)\n traversal_path = traversal_path[:-1] + \"0\"\n\n self.walk_dir_with_ignore(os.path.join(dir, sub_dir), traversal_path) # Recursive DFS\n else:\n break\n\n\ndef print_dir_tree(dir, outfile_name, gitignore_file=None, root_name=None, other_ignore_list=None):\n printer = __dir_tree_printer(root_name=root_name, other_ignore_list=other_ignore_list)\n outfile = os.path.join(outfile_name)\n\n if os.path.exists(outfile):\n os.remove(outfile)\n\n # Build ignore list\n if gitignore_file is not None:\n ignore = os.path.join(gitignore_file)\n assert os.path.exists(gitignore_file), \"{0} does not exist!\".format(ignore)\n ws = [ws for ws in string.whitespace]\n with open(ignore, \"r\") as f:\n for line in f:\n if line not in ws:\n if not line.startswith(\"#\"):\n printer.ignore_list.append(line.rstrip(\"\\n\"))\n\n # Run walk\n if gitignore_file is not None:\n printer.walk_dir_with_ignore(dir)\n else:\n printer.walk_dir(dir)\n\n # Print tree\n with open(outfile, \"a\", encoding=\"utf-8\") as f:\n for line in printer.print_list:\n f.write(line + \"\\n\")\n\n","repo_name":"ongkoonhan/DirTreePrinter","sub_path":"DirTreePrinter/DirTreePrinter.py","file_name":"DirTreePrinter.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"75328564648","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nIMDB Dataset - Create Weak Supervision Sources and Get the Weak Data Annotations\n\nThis notebook shows how to use keywords as a weak supervision source on the example of a well-known IMDB Movie Review dataset, which targets a binary sentiment analysis task.\n\nThe original dataset has gold labels, but we will use these labels only for evaluation purposes, since we want to test models under the weak supervision setting with Knodle. The idea behind it is that you don't have a dataset which is purely labeled with strong supervision (manual) and instead use heuristics (e.g. rules) to obtain a weak labeling. In the following tutorial, we will look for certain keywords expressing positive and negative sentiments that can be helpful to distinguish between classes. Specifically, we use the [Opinion lexicon](https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html) of the University of Illinois at Chicago.\n\nFirst, we load the dataset from a Knodle dataset collection. Then, we will create [Snorkel](https://www.snorkel.org/) labeling functions from two sets of keywords and apply them to the IMDB reviews. Please keep in mind, that keyword matching can be done without Snorkel; however, we enjoy the transparent annotation functionality of this library in our tutorial. \nEach labeling function (i.e. keyword) will be further associated with a respective target label. This concludes the annotation step.\n\nTo estimate how good our weak labeling works on its own, we will use the resulting keyword matches together with a basic majority vote model. Finally, the preprocessed data will be saved in a knodle-friendly format, so that other denoising models can be trained with the IMDB dataset.\nThe IMDB dataset available in the Knodle collection was downloaded from [Kaggle](https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews) in January 2021. \n\"\"\"\n\nimport os\nfrom joblib import dump\nfrom tqdm import tqdm\n\nimport pandas as pd \nimport numpy as np \nfrom scipy.sparse import csr_matrix\n\nfrom bs4 import BeautifulSoup\nfrom snorkel.labeling import LabelingFunction, PandasLFApplier, LFAnalysis\n\nfrom knodle.transformation.rule_label_format import transform_snorkel_matrix_to_z_t\nfrom knodle.transformation.majority import z_t_matrices_to_majority_vote_labels\n\n# client to access the dataset collection\nfrom minio import Minio\nclient = Minio(\"knodle.dm.univie.ac.at\", secure=False)\n\n# init pandas parameters\ntqdm.pandas()\npd.set_option('display.max_colwidth', -1)\n\n# Constants for Snorkel labeling functions\nPOSITIVE = 1\nNEGATIVE = 0\nABSTAIN = -1\nCOLUMN_WITH_TEXT = \"reviews_preprocessed\"\n\n\n## Download the dataset\ndata_path = \"../../../data_from_minio/imdb\"\n\n# Together with the IMDB data, let us also collect the keywords that we will need later.\nfiles = [(\"IMDB Dataset.csv\",), (\"keywords\", \"negative-words.txt\"), (\"keywords\", \"positive-words.txt\")]\n\nfor file in tqdm(files):\n client.fget_object(\n bucket_name=\"knodle\",\n object_name=os.path.join(\"datasets/imdb\", *file),\n file_path=os.path.join(data_path, file[-1]),\n )\n\nimdb_dataset_raw = pd.read_csv(os.path.join(data_path, \"IMDB Dataset.csv\"))\nprint(\"Gold label counts\")\nprint(imdb_dataset_raw.groupby(\"sentiment\").count())\n\n# ## Preprocess dataset\n\n# The dataset contains many HTML tags. We'll remove them\ndef strip_html(text):\n soup = BeautifulSoup(text, \"html.parser\")\n return soup.get_text()\n\nimdb_dataset_raw[COLUMN_WITH_TEXT] = imdb_dataset_raw[COLUMN_WITH_TEXT].apply(\n lambda x: strip_html(x))\n\n# ## Keywords\n# \n# For weak supervision sources we use sentiment keyword lists for positive and negative words.\n# https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html\n# \n# We have downloaded them from the Knodle collection earlier, with the IMDB dataset. \n# \n# After parsing the keywords from separate files, they are stored in a pd.DataFrame with the corresponding sentiment as \"label\".\n\npositive_keywords = pd.read_csv(os.path.join(data_path, \"positive-words.txt\"), sep=\" \", header=None, error_bad_lines=False, skiprows=30)\npositive_keywords.columns = [\"keyword\"]\npositive_keywords[\"label\"] = \"positive\"\n\nnegative_keywords = pd.read_csv(os.path.join(data_path, \"negative-words.txt\"),\n sep=\" \", header=None, error_bad_lines=False, encoding='latin-1', skiprows=30)\nnegative_keywords.columns = [\"keyword\"]\nnegative_keywords[\"label\"] = \"negative\"\n\nall_keywords = pd.concat([positive_keywords, negative_keywords])\nall_keywords.label.value_counts()\n\n# remove overlap of keywords between two sentiments\nall_keywords.drop_duplicates('keyword', inplace=True)\n\n\n# ## Labeling Functions\n# \n# Now we start to build labeling functions with Snorkel with these keywords and check the coverage.\n# \n# This is an iterative process of course so we surely have to add more keywords and regulary expressions ;-) \n\ndef keyword_lookup(x, keyword, label):\n return label if keyword in x[COLUMN_WITH_TEXT].lower() else ABSTAIN\n\ndef make_keyword_lf(keyword: str, label: str) -> LabelingFunction:\n \"\"\"\n Creates labeling function based on keyword.\n Args:\n keyword: what keyword should be look for\n label: what label does this keyword imply\n\n Returns: LabelingFunction object\n\n \"\"\"\n return LabelingFunction(\n name=f\"keyword_{keyword}\",\n f=keyword_lookup,\n resources=dict(keyword=keyword, label=label),\n )\n\ndef create_labeling_functions(keywords: pd.DataFrame) -> np.ndarray:\n \"\"\"\n Create Labeling Functions based on the columns keyword and regex. Appends column lf to df.\n\n Args:\n keywords: DataFrame with processed keywords\n\n Returns:\n All labeling functions. 1d Array with shape: (number_of_lfs x 1)\n \"\"\"\n keywords = keywords.assign(lf=keywords.progress_apply(\n lambda x:make_keyword_lf(x.keyword, x.label_id), axis=1\n ))\n lfs = keywords.lf.values\n return lfs\n\nall_keywords[\"label_id\"] = all_keywords.label.map({'positive':POSITIVE, 'negative':NEGATIVE})\nlabeling_functions = create_labeling_functions(all_keywords)\n\n\n# ### Apply Labeling Functions\n# We get a matrix with all labeling functions applied. This matrix has the shape $(instances \\times labeling functions)$\n\napplier = PandasLFApplier(lfs=labeling_functions)\napplied_lfs = applier.apply(df=imdb_dataset_raw)\n\nprint(\"Shape of applied labeling functions: \", applied_lfs.shape)\nprint(\"Number of reviews\", len(imdb_dataset_raw))\nprint(\"Number of labeling functions\", len(labeling_functions))\n\n\n# ### Analysis \n# \n# Now we can analyse some basic stats about our labeling functions. The main figures are:\n# \n# - Coverage: How many labeling functions match at all\n# - Overlaps: How many labeling functions overlap with each other (e.g. awesome and amazing)\n# - Conflicts: How many labeling functions overlap and have different labels (e.g. awesome and bad)\n# - Correct: Correct LFs\n# - Incorrect: Incorrect Lfs\n\nlf_analysis = LFAnalysis(L=applied_lfs, lfs=labeling_functions).lf_summary()\nprint(\"LF analysis:\")\nprint(lf_analysis)\nprint(\"LF analysis mean values:\")\nprint(pd.DataFrame(lf_analysis.mean()))\nprint(\"LF analysis median values:\")\nprint(pd.DataFrame(lf_analysis.median()))\n\n# Lets have a look at some examples that were labeled by a positive keyword. You can see, that the true label for some of them is negative.\n# consider 1110th keyword\nkw = all_keywords.iloc[1110]\nprint(f\"1110th keyword is '{kw.keyword}' and labels with '{kw.label}'\")\nprint()\n\n# sample 2 random examples where the 50th LF assigned a positive label\nexamples = imdb_dataset_raw.iloc[applied_lfs[:, 1110] == POSITIVE].loc[:2, [COLUMN_WITH_TEXT,'sentiment']]\nprint(\"This keyword has matched the following instances with labels:\")\nprint()\n\nfor idx, ex in examples.iterrows():\n print(\"{} - {}\".format(ex.sentiment, ex[COLUMN_WITH_TEXT]))\n print()\n\n \n# ## Transform rule matches\n# \n# To work with knodle the dataset needs to be transformed into a binary array $Z$\n# \n# (shape: `#instances x # rules_`).\n# \n# Where a cell $Z_{ij}$ means that for instance i\n# \n# 0 -> Rule j didn't match \n# 1 -> Rule j matched\n# \n# Furthermore, we need a matrix `mapping_rule_labels` which has a mapping of all rules to labels, stored in a binary manner as well \n# \n# (shape `#rules x #labels`).\n\nrule_matches, mapping_rules_labels = transform_snorkel_matrix_to_z_t(applied_lfs)\n\n\n# ### Majority Vote\n# \n# Now we make a majority vote based on all rule matches. First we get the `rule_counts` by multiplying `rule_matches` with the `mapping_rules_labels`, then we divide it sumwise by the sum to get a probability value. In the end we counteract the divide with zero issue by setting all nan values to zero. All this happens in the `z_t_matrices_to_majority_vote_labels` function.\n\n# the ties are resolved randomly internally, so the predictions might slightly vary\npred_labels = z_t_matrices_to_majority_vote_labels(rule_matches, mapping_rules_labels)\n\n# There are more positive labels predicted by the majority vote.\nlabels, counts = np.unique(pred_labels, return_counts=True)\n\n# accuracy of the weak labels\nacc = (pred_labels == imdb_dataset_raw.sentiment.map({'positive':POSITIVE, 'negative':NEGATIVE})).mean()\nprint(f\"Accuracy of majority voting: {acc}\")\n\n \n# ## Save Files\nrule_matches_sparse = csr_matrix(rule_matches)\ndump(rule_matches_sparse, os.path.join(data_path, \"rule_matches.lib\"))\ndump(mapping_rules_labels, os.path.join(data_path, \"mapping_rules_labels.lib\"))\n\n# We also save the preprocessed texts with labels to use them later to evalutate a classifier.\nimdb_dataset_raw['label_id'] = imdb_dataset_raw.sentiment.map({'positive':POSITIVE, 'negative':NEGATIVE})\nimdb_dataset_raw.to_csv(os.path.join(data_path, 'imdb_data_preprocessed.csv'), index=None)\n\nall_keywords.to_csv(os.path.join(data_path, 'keywords.csv'), index=None)\n\n# Now, we have created a weak supervision dataset. Of course it is not perfect but it is something with which we can compare performances of different denoising methods with. :-) \n","repo_name":"knodle/knodle","sub_path":"examples/data_preprocessing/imdb_dataset/prepare_weak_imdb_data.py","file_name":"prepare_weak_imdb_data.py","file_ext":"py","file_size_in_byte":10029,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"53"}
+{"seq_id":"35786193114","text":"def main():\n file = \"books/frankenstein.txt\"\n file_content = open_file(file)\n words_number = count_words(file_content)\n letts = letters(file_content)\n list = [(k, v) for k, v in letts.items()]\n list.sort(key= lambda x: x[1], reverse= True)\n report(words_number, list)\n#\n#\ndef open_file(file):\n with open(file) as f:\n content = f.read()\n return content.split()\n#\n#\ndef count_words(file_content):\n print(f\"there is {len(file_content)} words\")\n return len(file_content)\n#\n#\ndef letters(file_content):\n letters = {}\n for i in range(0, len(file_content)):\n for y in range(0, len(file_content[i])):\n if (\n is_alphabetic(file_content[i][y]) and\n file_content[i][y].lower() in letters\n ):\n letters[file_content[i][y].lower()] +=1\n elif (\n is_alphabetic(file_content[i][y]) and \n file_content[i][y].lower() not in letters\n ):\n letters[file_content[i][y].lower()] = 1\n return letters\n#\n#\ndef is_alphabetic(character):\n return (character.lower() >= 'a' and character.lower() <= 'z')\n#\n#\ndef report(words_number, list):\n print(\"--- Begin report of books/frankenstein.txt ---\")\n print(f\"{words_number} was found in the document\")\n print(\"\")\n for element in list:\n print(f\" The '{element[0]}' character was found {element[1]} times\")\n print(\"--- End report ---\")\n#\n#\nmain()","repo_name":"inll039/bookbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11184365022","text":"# %%\nimport time\nimport glob\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nfrom progress.bar import Bar\nfrom rectangle_region import RectangleRegion\nfrom haar_feature import HaarFeature\nfrom skimage.color import rgb2gray\nimport skimage.io as io\nimport numpy as np\nimport commonfunctions as cf # this a custom module found the commonfunctions.py\n\ndef integeral_img(img):\n row = len(img) #the length of the row\n column = len(img) #length of the column\n integeral_img =np.zeros((row,column))\n for x in range(row):\n for y in range(column):\n if x == 0 and y == 0: #first element in the matrix so no sum\n integeral_img[x][y] = img[x][y] #img[0][0] = 1 in example\n elif x == 0: #first row so no need to sum all the previous rows\n integeral_img[x][y] = integeral_img[x][y-1] + img[x][y]\n elif y == 0: #first column so no need to sum all the previous column\n integeral_img[x][y] = integeral_img[x-1][y] + img[x][y]\n else: # previous row + previous column - (previous column and row) + the current point \n integeral_img[x][y] = (integeral_img[x-1][y] + integeral_img[x][y-1] - integeral_img[x-1][y-1]) + img[x][y]\n return integeral_img\n\n\ndef build_features(img_width, img_height, shift=1, min_width=1, min_height=1):\n \"\"\"\n Generate values from Haar features\n White rectangles will be substracted from black ones to get each feature\n \n Params:\n - img_width, img_height: size of the original image\n - shift, the amount of distance the window will be shifted\n - min_width, min_height: the starting size of the haar window\n \"\"\"\n features = [] # [Tuple(positive(white) regions, negative(black) regions),...]\n\n # scale feature window using size\n for window_width in range(min_width, img_width + 1):\n for window_height in range(min_height, img_height + 1):\n # iterarte over changing position of the feature window\n # initial x coordinate of the top left of the window\n x = 0\n while x + window_width < img_width:\n y = 0\n while y + window_height < img_height:\n # all possible Haar regions\n immediate = RectangleRegion(x, y, window_width, window_height) # |o|\n right = RectangleRegion(x + window_width, y, window_width, window_height) # | |o|\n ## for 3 rectangle types\n right_2 = RectangleRegion(x + window_width * 2, y, window_width, window_height) # | | |o|\n bottom = RectangleRegion(x, y + window_height, window_width, window_height) # | |/|o|\n ## for 3 rectangle types\n bottom_2 = RectangleRegion(x, y + window_height * 2, window_width, window_height) # | |/| |/|o|\n bottom_right = RectangleRegion(x + window_width, y + window_height, window_width, window_height) # | |/| |o|\n\n # *** 2-rectangle haar ***\n # Horizontal |w|b|\n if x + window_width * 2 < img_width:\n features.append(HaarFeature([immediate], [right]))\n # Vertical |w|b|\n if y + window_height * 2 < img_height:\n features.append(HaarFeature([bottom], [immediate]))\n\n # *** 3-rectangle haar ***\n # Horizontal |w|b|w|\n if x + window_width * 3 < img_width:\n features.append(HaarFeature([immediate, right_2], [right]))\n # Vertical |w|b|w|\n if y + window_height * 3 < img_height:\n features.append(HaarFeature([immediate, bottom_2],[bottom]))\n\n # *** 4-diagonal haar rectangle ***\n if x + window_width * 2 < img_width and y + window_height * 2 < img_height:\n features.append(HaarFeature([immediate, bottom_right], [bottom, right]))\n\n y += shift ## shift window position\n x += shift ## shift window position\n return features \n\n\n\ndef apply_features(X_integralImages, features):\n \"\"\"\n Build features of all the training data (integral images)\n \"\"\"\n ## X : features\n X = np.zeros((len(features), len(X_integralImages)), dtype=np.int32)\n ## each row will contain a list of features , for example:\n ## feature[0][i] is the first feature of the image of index i in the data set..\n ## y: will be kept as it is => f0=([...], y); f1=([...], y),...\n ## to display progress\n bar = Bar('Processing features', max=len(features), suffix='%(percent)d%% - %(elapsed_td)s - %(eta_td)s')\n for i, feature in bar.iter(enumerate(features)):\n ## Compute the value of feature 'i' for each image in the training set\n ## it will be Input of the classifier_i\n X[i] = list(map(lambda integralImg: feature.get_haar_feature_value(integralImg), X_integralImages))\n bar.finish()\n\n return X ## [[ftr0 of img0, ftr0 of img1, ...][ftr1 of img0, ftr1 of img1, ...],....]","repo_name":"reem-atalah/Attendance_System","sub_path":"ViolaJones/haar_utils.py","file_name":"haar_utils.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"53"}
+{"seq_id":"43301071261","text":"#!/usr/bin/python3\n\n\"\"\"\nFactory test script for the firmware-only burning station\n\"\"\"\nimport time # for sleep and timestamps\nfrom datetime import datetime # for deriving human-readable dates for logging\nimport subprocess\nimport atexit\nimport argparse\nimport RPi.GPIO as GPIO\n\nfrom gpiodefs import *\nimport serial\n\ndef cleanup():\n reset_tester_outputs()\n GPIO.cleanup()\n\ndef reset_tester_outputs():\n # tristates\n GPIO.setup(GPIO_PROG_B, GPIO.IN)\n GPIO.setup(GPIO_CRESET_N, GPIO.IN)\n # driven\n GPIO.output(GPIO_VBUS, 0)\n GPIO.output(GPIO_UART_SOC, 1)\n GPIO.output(GPIO_DRV_UP5K_N, 1)\n\n GPIO.output(GPIO_UP5K_MOSI, 0)\n GPIO.output(GPIO_UP5K_SCK, 0)\n GPIO.output(GPIO_UP5K_CSN, 0)\n\n GPIO.output(GPIO_JTAG_TCK, 0)\n GPIO.output(GPIO_JTAG_TMS, 0)\n GPIO.output(GPIO_JTAG_TDI, 0)\n \n GPIO.output(HAT_RED_LED, 0)\n GPIO.output(HAT_GREEN_LED, 0)\n GPIO.output(HAT_WHITE_LED, 1)\n\ndef check_tdi():\n passing = True\n for i in range(10):\n GPIO.output(GPIO_JTAG_TDI, 0)\n if GPIO.input(GPIO_JTAG_TDO) != GPIO.LOW:\n passing = False\n \n GPIO.output(GPIO_JTAG_TDI, 1)\n if GPIO.input(GPIO_JTAG_TDO) != GPIO.HIGH:\n passing = False\n\n return passing\n\ndef render_result(code):\n # alternate fast flashing if pass\n if code == True:\n for i in range(6):\n GPIO.setup(GPIO_PROG_B, GPIO.OUT)\n GPIO.output(GPIO_PROG_B, 0)\n time.sleep(0.2)\n GPIO.setup(GPIO_PROG_B, GPIO.IN)\n\n GPIO.setup(GPIO_CRESET_N, GPIO.OUT)\n GPIO.output(GPIO_CRESET_N, 0)\n time.sleep(0.2)\n GPIO.setup(GPIO_CRESET_N, GPIO.IN)\n # simultaneous slow flashing if fail\n else:\n for i in range(3):\n GPIO.setup(GPIO_PROG_B, GPIO.OUT)\n GPIO.output(GPIO_PROG_B, 0)\n GPIO.setup(GPIO_CRESET_N, GPIO.OUT)\n GPIO.output(GPIO_CRESET_N, 0)\n time.sleep(1.0)\n GPIO.setup(GPIO_PROG_B, GPIO.IN)\n GPIO.setup(GPIO_CRESET_N, GPIO.IN)\n time.sleep(1.0)\n \n GPIO.setup(GPIO_PROG_B, GPIO.IN)\n GPIO.setup(GPIO_CRESET_N, GPIO.IN)\n\ndef shift_clk(port):\n port.write(bytes([0xF0]))\n port.read(1) # this is essential, otherwise clocks don't flush. Throw away the read back value.\n #port.flush() # this is way too slow.\n\ndef check_pattern(port, pattern):\n jtag_tdi = (pattern >> 0) & 1\n jtag_tck = (pattern >> 1) & 1\n jtag_tms = (pattern >> 2) & 1\n up5k_mosi = (pattern >> 3) & 1\n up5k_sck = (pattern >> 4) & 1\n \n GPIO.output(GPIO_JTAG_TDI, jtag_tdi)\n GPIO.output(GPIO_JTAG_TCK, jtag_tck)\n GPIO.output(GPIO_JTAG_TMS, jtag_tms)\n GPIO.output(GPIO_UP5K_MOSI, up5k_mosi)\n GPIO.output(GPIO_UP5K_SCK, up5k_sck)\n\n GPIO.output(GPIO_UP5K_CSN, 0) # load the pattern\n GPIO.output(GPIO_UP5K_CSN, 1) # it's asynchronous, so it just needs a short pulse to load the pattern\n\n # just unroll the damn loop, it's not fancy, but it is easier to read this way\n # H input is always zero\n if GPIO.input(GPIO_UP5K_MISO) != GPIO.LOW:\n return([\"CHECK: H input not low\"])\n shift_clk(port) # advance the MISO output from H->G\n # G input is UP5K_SCLK\n if GPIO.input(GPIO_UP5K_MISO) != up5k_sck:\n return([\"CHECK: SCK mismatch\"])\n shift_clk(port)\n # F input is always zero\n if GPIO.input(GPIO_UP5K_MISO) != GPIO.LOW:\n return([\"CHECK: F input not low\"])\n shift_clk(port)\n # E input is always zero\n if GPIO.input(GPIO_UP5K_MISO) != GPIO.LOW:\n return([\"CHECK: E input not low\"])\n shift_clk(port)\n # D input is MOSI\n if GPIO.input(GPIO_UP5K_MISO) != up5k_mosi:\n return([\"CHECK: UP5K MOSI mismatch\"])\n shift_clk(port)\n # C input is TMS\n if GPIO.input(GPIO_UP5K_MISO) != jtag_tms:\n return([\"CHECK: JTAG TMS mismatch\"])\n shift_clk(port)\n # B input is TCK\n if GPIO.input(GPIO_UP5K_MISO) != jtag_tck:\n return([\"CHECK: JTAG TCK mismatch\"])\n shift_clk(port)\n # A input is TDI\n if GPIO.input(GPIO_UP5K_MISO) != jtag_tdi:\n return([\"CHECK: JTAG TDI mismatch\"])\n shift_clk(port)\n # end chain is always 0\n if GPIO.input(GPIO_UP5K_MISO) != GPIO.LOW:\n return([\"CHECK: End chain not low\"])\n\n return None\n \ndef check_shift(port):\n reasons = []\n max_reasons = 16\n\n # assume: power is on\n # make sure we are in FPGA UART mode\n GPIO.output(GPIO_UART_SOC, 1)\n\n # first shift to zero and check that we have an all-zero shift\n GPIO.output(GPIO_UP5K_CSN, 1) # puts it in shift mode\n for i in range(8):\n shift_clk(port)\n if GPIO.input(GPIO_UP5K_MISO) != GPIO.LOW:\n reasons.append([\"SHIFT: zero check failed\"])\n\n for pat in range(32): # 32 possible patterns, check all of them\n r = check_pattern(port, pat)\n if r != None:\n if len(reasons) < max_reasons:\n reasons.append(\"SHIFT: iter {} | {}\".format(pat, r))\n elif len(reasons) == max_reasons:\n reasons.append(\"SHIFT: too many errors, truncating!\")\n \n if len(reasons) == 0:\n #print(\"SHIFT: passed\")\n return None\n else:\n #print(\"SHIFT: failed {}\".format(reasons))\n return reasons\n \ndef check_serial(port):\n passing = True\n\n # first check the UP5K loop, with the power off\n # power is off under the theory that if it's still actually looped to the FPGA path,\n # the level translators would not work and we'd see that error\n GPIO.output(GPIO_VBUS, 0)\n time.sleep(0.3) # should already be off so we can shorten this\n GPIO.output(GPIO_UART_SOC, 0)\n test_string = b\"This is a test of the UP5K loopback path\\n\\r\"\n port.write(test_string)\n rcv = port.read(len(test_string))\n print(\"Serial port test got: \" + rcv.decode('utf-8', 'backslashreplace'))\n if rcv != test_string:\n passing = False\n\n # now put it into FPGA mode with power on\n GPIO.output(GPIO_VBUS, 1)\n time.sleep(0.4)\n GPIO.output(GPIO_UART_SOC, 1)\n test_string = b\"This is a test of the FPGA loopback path\\n\\r\"\n port.write(test_string)\n rcv = port.read(len(test_string))\n print(\"Serial port test got: \" + rcv.decode('utf-8', 'backslashreplace'))\n if rcv != test_string:\n passing = False\n\n return passing\n\ndef wait_start():\n global HAT_RED_LED, HAT_GREEN_LED, HAT_WHITE_LED, HAT_START\n while GPIO.input(HAT_START) == GPIO.HIGH:\n time.sleep(0.1)\n while GPIO.input(HAT_START) == GPIO.LOW:\n time.sleep(0.1)\n\ndef main():\n global GPIO_START, GPIO_FUNC, GPIO_BSIM, GPIO_ISENSE, GPIO_VBUS, GPIO_UART_SOC\n global GPIO_PROG_B, GPIO_AUD_HPR, GPIO_AUD_HPL, GPIO_AUD_SPK\n global HAT_RED_LED, HAT_GREEN_LED, HAT_WHITE_LED, HAT_START\n\n parser = argparse.ArgumentParser(description=\"Precursor HAT Test\")\n parser.add_argument(\n \"-l\", \"--log\", help=\"When present, suppress log output to /home/pi/log/\", default=True, action=\"store_false\"\n )\n args = parser.parse_args()\n\n if args.log:\n try:\n logfile = open('/home/precursor/log/hat_{:%Y%b%d_%H-%M-%S}.log'.format(datetime.now()), 'w')\n except:\n logfile = None # don't crash if the fs is full, the show must go on!\n else:\n logfile = None\n \n GPIO.setmode(GPIO.BCM)\n \n GPIO.setup(GPIO_VBUS, GPIO.OUT)\n GPIO.setup(GPIO_UART_SOC, GPIO.OUT)\n GPIO.setup(GPIO_PROG_B, GPIO.IN)\n GPIO.setup(GPIO_CRESET_N, GPIO.IN)\n\n GPIO.setup(GPIO_DRV_UP5K_N, GPIO.OUT)\n GPIO.setup(GPIO_UP5K_MOSI, GPIO.OUT)\n GPIO.setup(GPIO_UP5K_MISO, GPIO.IN)\n GPIO.setup(GPIO_UP5K_SCK, GPIO.OUT)\n GPIO.setup(GPIO_UP5K_CSN, GPIO.OUT)\n GPIO.setup(GPIO_JTAG_TCK, GPIO.OUT)\n GPIO.setup(GPIO_JTAG_TMS, GPIO.OUT)\n GPIO.setup(GPIO_JTAG_TDO, GPIO.IN)\n GPIO.setup(GPIO_JTAG_TDI, GPIO.OUT)\n\n GPIO.setup(HAT_RED_LED, GPIO.OUT)\n GPIO.setup(HAT_GREEN_LED, GPIO.OUT)\n GPIO.setup(HAT_WHITE_LED, GPIO.OUT)\n GPIO.setup(HAT_START, GPIO.IN)\n\n GPIO.output(HAT_GREEN_LED, 0)\n GPIO.output(HAT_RED_LED, 0)\n GPIO.output(HAT_WHITE_LED, 1)\n \n reset_tester_outputs()\n\n port = serial.Serial(\"/dev/ttyAMA0\", baudrate=115200, timeout=0.5)\n\n test_status = True\n first_run = True\n while True:\n # this is at the top because we want the \"continue\" abort to print a message\n if first_run == False:\n if test_status == True:\n GPIO.output(HAT_GREEN_LED, 1)\n print(\"HAT test PASS\")\n if logfile:\n logfile.write(\"{}: HAT test PASS\\n\".format(str(datetime.now())))\n logfile.flush()\n else:\n GPIO.output(HAT_RED_LED, 1)\n print(\"HAT test FAIL:\")\n for reason in reasons:\n print(\" \" + str(reason))\n if logfile:\n logfile.write(\"{}: HAT test FAIL\\n\".format(str(datetime.now())))\n for reason in reasons:\n logfile.write(\" {}\\n\".format(str(reason)))\n logfile.flush()\n render_result(test_status)\n \n ##### power off the device\n GPIO.output(GPIO_VBUS, 0)\n else:\n first_run = False\n \n test_status = True\n reasons = []\n \n reset_tester_outputs()\n GPIO.output(HAT_WHITE_LED, 1)\n\n #input(\"Press enter to continue...\")\n wait_start()\n # turn off the white LED to indicate the test is running\n GPIO.output(HAT_WHITE_LED, 0)\n GPIO.output(HAT_RED_LED, 0)\n GPIO.output(HAT_GREEN_LED, 0)\n \n port.reset_input_buffer()\n port.reset_output_buffer()\n ##### test the serial port. This will control the power, so don't need to set it ourselves.\n if check_serial(port) != True:\n test_status = False\n reasons.append([\"Serial port fail\"])\n continue # don't run any other tests if the serial port doesn't work!\n\n ##### power on the device\n GPIO.output(GPIO_VBUS, 1) # this is just a preventative power-on, it should already be on...\n time.sleep(0.1)\n\n ##### check the TDI loopback\n if check_tdi() != True:\n test_status = False\n reasons.append([\"JTAG TDI/TDO loop fail\"])\n\n ##### check that drive works by not asserting it, running a test, and expecting errors.\n GPIO.output(GPIO_DRV_UP5K_N, 1)\n result = check_shift(port)\n if result == None: # we /expect/ errors if this is not asserted\n test_status = False\n reasons.append([\"DRV_UP5K_N test failed\"])\n\n ##### check all the other GPIOs\n GPIO.output(GPIO_DRV_UP5K_N, 0)\n result = check_shift(port)\n if result != None:\n test_status = False\n for r in result:\n reasons.append(r)\n GPIO.output(GPIO_DRV_UP5K_N, 1)\n\n\nif __name__ == \"__main__\":\n atexit.register(cleanup)\n try:\n print(\"Tester main loop starting...\")\n main()\n except KeyboardInterrupt:\n pass\n","repo_name":"betrusted-io/bootstrap-mainboard","sub_path":"hat-test.py","file_name":"hat-test.py","file_ext":"py","file_size_in_byte":11129,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"53"}
+{"seq_id":"27216369593","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 8 10:07:55 2018\n\n@author: joyce\n\"\"\"\nfrom __future__ import print_function\n\nimport pickle, gzip\nimport math \nimport igraph\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\\OutlierDetector\")\nimport mnist_helpers as mh\n\n\ndef getSets():\n # Load the dataset\n with gzip.open('mnist.pkl.gz', 'rb') as f:\n train_set, valid_set, test_set = pickle.load(f, encoding='latin1')\n f.close()\n return train_set, valid_set, test_set\n\n\ndef getNumbers(input_set, nr):\n alltwos = []\n for i in range(0,len(input_set[0])):\n if input_set[1][i] == nr:\n alltwos.append(input_set[0][i])\n return alltwos\n\ndef getResults(input_set, counter):\n filename = 'sim_scores/sim_'+str(counter)+'.txt'\n \n def square_rooted(x):\n return round(math.sqrt(sum([a*a for a in x])),3)\n \n def cosine_similarity(x,y):\n numerator = sum(a*b for a,b in zip(x,y))\n denominator = square_rooted(x)*square_rooted(y)\n return round(numerator/float(denominator),3)\n\n results = {}\n \n for i in range(0,len(input_set)):\n mapped[(counter,i)] = input_set[i]\n for j in range(0,len(input_set)):\n if i is not j and (i,j) not in results and (j,i) not in results:\n results[(i,j)] = cosine_similarity(input_set[i], input_set[j])\n\n with open(filename, 'w+') as f:\n for key, value in results.items():\n if value > 0.7:\n f.write(str(key[0])+'\\t'+str(key[1])+'\\t'+str(value)+'\\n')\n\n\ndef clustering(filename, counter):\n\n G = igraph.read(filename,directed=False,format='ncol')\n \n D = G.community_multilevel()\n \n MIN_CLUSTER_SIZE = 1\n \n style = {}\n style['vertex_size'] = 10\n \n kept_clusters = 0\n clusters = []\n for i in D.subgraphs():\n if len(i.vs) > MIN_CLUSTER_SIZE:\n kept_clusters += 1\n clusters.append(i)\n \n style[\"layout\"] = i.layout(\"fr\", maxiter=250) # \"fr\" or \"lgl\" work nicely\n \n igraph.plot(i, 'cluster_visualization/cluster_'+str(counter)+'_'+str(kept_clusters)+'.pdf', **style)\n \n print('total clusters -->',len(D.subgraphs()))\n print('kept clusters -->',kept_clusters)\n return clusters\n\n\ndef getAllOutliers(): \n outliers = []\n for i in range(0,10):\n outliers.append(np.load('../OutlierDetector/outliers/'+str(i)+'.npy'))\n \n return outliers\n\n \ndef printImgCluster(c, j, counter):\n nrs = []\n for u in c.vs:\n nrs.append(int(u['name']))\n \n nameC = 'cluster_machines/line_'+str(counter)+'_cluster_'+str(j)+'.pickle'\n \n with open(nameC,'wb+') as f3:\n pickle.dump(nrs, f3)\n\n# images = np.array([mapped[(counter,x)] for x in nrs]) \n# mh.show_some_digits(images,np.array([x for x in nrs]))\n\n\nmapped = {}\nclusters = [] \n\noutliers = getAllOutliers()\n\ncounter = 0\nfor o in outliers:\n filename = 'sim_scores/sim_'+str(counter)+'.txt'\n \n getResults(o, counter)\n clus = clustering(filename, counter)\n clusters.append((counter,clus))\n \n print('--> digits for clusters of ', counter)\n\n for j in range(0,len(clus)):\n printImgCluster(clus[j],j,counter)\n\n counter += 1\n","repo_name":"Janwillemtv/mirror","sub_path":"SimilarityChecker/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17835384540","text":"def is_subsets_sum(alist, sum):\n\n for i in range(len(alist)):\n curr_sum = alist[i]\n subset = [alist[i]]\n for j in range(i+1, len(alist)):\n\n curr_sum += alist[j]\n if curr_sum > sum:\n curr_sum -= alist[j]\n elif curr_sum < sum:\n subset.append(alist[j])\n else: # equals case\n subset.append(alist[j])\n print(subset)\n subset = [alist[i]]\n curr_sum -= alist[j]\n return False\n\n#print(is_subsets_sum([3,34,4,12,5,2], 9))\nprint(is_subsets_sum([1,4,11,3,2,1], 4))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"manojkumar-github/DataStructures-DynamicProgramming-in-Python-JAVA-Cplusplus","sub_path":"leet/plan/algorithms/dp/subset_sum.py","file_name":"subset_sum.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9118700516","text":"import argparse\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport tqdm\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch_geometric.data import Batch\nfrom torch_geometric.datasets import PPI\nfrom torch_geometric.loader import DataLoader, LinkNeighborLoader\nfrom torch_geometric.nn import GraphSAGE\n\nnp.random.seed(77)\nDEVICE = \"cuda:0\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--data_path\",\n type=str,\n default=\"/tmp/nvflare/datasets/ppi\",\n )\n parser.add_argument(\n \"--epochs\",\n type=int,\n default=70,\n )\n parser.add_argument(\n \"--total_clients\",\n type=int,\n default=2,\n )\n parser.add_argument(\n \"--client_id\",\n type=int,\n default=2,\n help=\"0: use all data, 1-N: use data from client N\",\n )\n parser.add_argument(\n \"--output_path\",\n type=str,\n default=\"/tmp/nvflare/gnn/protein_local\",\n )\n args = parser.parse_args()\n\n # Set up tensorboard\n writer = SummaryWriter(os.path.join(args.output_path, str(args.client_id)))\n\n # Create PPI dataset for training.\n train_dataset = PPI(args.data_path, split=\"train\")\n val_dataset = PPI(args.data_path, split=\"val\")\n\n # Group all training graphs into a single graph to perform sampling:\n train_data = Batch.from_data_list(train_dataset)\n\n # Split the training graph into subgraphs according to the number of clients\n node_idx = np.arange(train_data.num_nodes)\n np.random.shuffle(node_idx)\n client_idx = np.split(node_idx, args.total_clients)\n\n # Get the subgraph for the client\n if args.client_id == 0:\n train_data_sub = train_data\n else:\n subset_idx = torch.tensor(client_idx[args.client_id - 1])\n train_data_sub = train_data.subgraph(subset_idx)\n\n # Define the dataloader for graphsage training\n loader = LinkNeighborLoader(\n train_data_sub,\n batch_size=2048,\n shuffle=True,\n neg_sampling_ratio=1.0,\n num_neighbors=[10, 10],\n num_workers=6,\n persistent_workers=True,\n )\n\n # Evaluation loaders (one datapoint corresponds to a graph)\n # As the main training is unsupervised, additional model needs to be trained for classification\n train_loader = DataLoader(train_dataset, batch_size=2)\n val_loader = DataLoader(val_dataset, batch_size=2)\n\n # Model\n model = GraphSAGE(\n in_channels=train_dataset.num_features,\n hidden_channels=64,\n num_layers=2,\n out_channels=64,\n )\n\n optimizer = torch.optim.Adam(model.parameters(), lr=0.003)\n model.to(DEVICE)\n\n for epoch in range(1, args.epochs + 1):\n model.train()\n running_loss = instance_count = 0\n for data in tqdm.tqdm(loader):\n # get the inputs data\n # (optional) use GPU to speed things up\n data = data.to(DEVICE)\n # zero the parameter gradients\n optimizer.zero_grad()\n # forward + backward + optimize\n h = model(data.x, data.edge_index)\n h_src = h[data.edge_label_index[0]]\n h_dst = h[data.edge_label_index[1]]\n link_pred = (h_src * h_dst).sum(dim=-1) # Inner product.\n loss = F.binary_cross_entropy_with_logits(link_pred, data.edge_label)\n loss.backward()\n optimizer.step()\n # add record\n running_loss += float(loss.item()) * link_pred.numel()\n instance_count += link_pred.numel()\n print(f\"Epoch: {epoch:02d}, Loss: {running_loss / instance_count:.4f}\")\n writer.add_scalar(\"train_loss\", running_loss / instance_count, epoch)\n\n if epoch % 10 == 0:\n # Evaluate model\n def encode(data_loader):\n model.eval()\n xs, ys = [], []\n for data in data_loader:\n data = data.to(DEVICE)\n xs.append(model(data.x, data.edge_index).cpu())\n ys.append(data.y.cpu())\n return torch.cat(xs, dim=0), torch.cat(ys, dim=0)\n\n with torch.no_grad():\n # Train classifier on training set:\n x, y = encode(train_loader)\n clf = MultiOutputClassifier(SGDClassifier(loss=\"log_loss\", penalty=\"l2\"))\n clf.fit(x, y)\n # Evaluate on validation set:\n x, y = encode(val_loader)\n val_f1 = f1_score(y, clf.predict(x), average=\"micro\")\n print(f\"Validation F1: {val_f1:.4f}\")\n writer.add_scalar(\"validation_f1\", val_f1, epoch)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SYangster/NVFlare","sub_path":"examples/advanced/gnn/code/graphsage_protein_local.py","file_name":"graphsage_protein_local.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"70472083047","text":"from slack_sdk.errors import SlackApiError\n\ndef sendmsg(token, channel, msg):\n client = token\n channel_id = channel\n\n try:\n result = client.chat_postMessage(\n channel=channel_id,\n text=msg\n # You could also use a blocks[] array to send richer content\n )\n # Print result, which includes information about the message (like TS)\n print(result)\n\n except SlackApiError as e:\n print(f\"Error: {e}\")\n\n\n\n","repo_name":"jonathanlutterbeck/slackbot","sub_path":"send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74349681449","text":"import numpy as np\nimport torch\nfrom core.structures.points_set import ExtremePoints\nfrom detectron2.structures.boxes import Boxes\nimport pycocotools.mask as mask_util\n\n\n# unused\ndef get_octagon(ex):\n ex = np.array(ex).reshape(4, 2)\n w, h = ex[3][0] - ex[1][0], ex[2][1] - ex[0][1]\n t, l, b, r = ex[0][1], ex[1][0], ex[2][1], ex[3][0]\n x = 8.\n octagon = [[min(ex[0][0] + w / x, r), ex[0][1], \\\n max(ex[0][0] - w / x, l), ex[0][1], \\\n ex[1][0], max(ex[1][1] - h / x, t), \\\n ex[1][0], min(ex[1][1] + h / x, b), \\\n max(ex[2][0] - w / x, l), ex[2][1], \\\n min(ex[2][0] + w / x, r), ex[2][1], \\\n ex[3][0], min(ex[3][1] + h / x, b), \\\n ex[3][0], max(ex[3][1] - h / x, t)\n ]]\n return octagon\n\n\ndef extreme_point_to_octagon_mask(extreme_points, h, w):\n octagon = get_octagon(extreme_points)\n rles = mask_util.frPyObjects(octagon, h, w)\n rle = mask_util.merge(rles)\n mask = mask_util.decode(rle)\n return mask\n\n\ndef get_extreme_points(pts):\n num_pt = pts.shape[0]\n l, t = min(pts[:, 0]), min(pts[:, 1])\n r, b = max(pts[:, 0]), max(pts[:, 1])\n # 3 degrees\n thresh = 0.02\n w = r - l + 1\n h = b - t + 1\n\n t_idx = np.argmin(pts[:, 1])\n t_idxs = [t_idx]\n tmp = (t_idx + 1) % num_pt\n while tmp != t_idx and pts[tmp, 1] - pts[t_idx, 1] <= thresh * h:\n t_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (t_idx - 1) % num_pt\n while tmp != t_idx and pts[tmp, 1] - pts[t_idx, 1] <= thresh * h:\n t_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n tt = (max(pts[t_idxs, 0]) + min(pts[t_idxs, 0])) / 2\n\n b_idx = np.argmax(pts[:, 1])\n b_idxs = [b_idx]\n tmp = (b_idx + 1) % num_pt\n while tmp != b_idx and pts[b_idx, 1] - pts[tmp, 1] <= thresh * h:\n b_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (b_idx - 1) % num_pt\n while tmp != b_idx and pts[b_idx, 1] - pts[tmp, 1] <= thresh * h:\n b_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n bb = (max(pts[b_idxs, 0]) + min(pts[b_idxs, 0])) / 2\n\n l_idx = np.argmin(pts[:, 0])\n l_idxs = [l_idx]\n tmp = (l_idx + 1) % num_pt\n while tmp != l_idx and pts[tmp, 0] - pts[l_idx, 0] <= thresh * w:\n l_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (l_idx - 1) % num_pt\n while tmp != l_idx and pts[tmp, 0] - pts[l_idx, 0] <= thresh * w:\n l_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n ll = (max(pts[l_idxs, 1]) + min(pts[l_idxs, 1])) / 2\n\n r_idx = np.argmax(pts[:, 0])\n r_idxs = [r_idx]\n tmp = (r_idx + 1) % num_pt\n while tmp != r_idx and pts[r_idx, 0] - pts[tmp, 0] <= thresh * w:\n r_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (r_idx - 1) % num_pt\n while tmp != r_idx and pts[r_idx, 0] - pts[tmp, 0] <= thresh * w:\n r_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n rr = (max(pts[r_idxs, 1]) + min(pts[r_idxs, 1])) / 2\n\n return np.array([tt, ll, bb, rr])\n\n\ndef get_aux_extreme_points(pts):\n num_pt = pts.shape[0]\n\n aux_ext_pts = []\n\n l, t = min(pts[:, 0]), min(pts[:, 1])\n r, b = max(pts[:, 0]), max(pts[:, 1])\n # 3 degrees\n thresh = 0.02\n band_thresh = 0.02\n w = r - l + 1\n h = b - t + 1\n\n t_band = np.where((pts[:, 1] - t) <= band_thresh * h)[0].tolist()\n while t_band:\n t_idx = t_band[np.argmin(pts[t_band, 1])]\n t_idxs = [t_idx]\n tmp = (t_idx + 1) % num_pt\n while tmp != t_idx and pts[tmp, 1] - pts[t_idx, 1] <= thresh * h:\n t_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (t_idx - 1) % num_pt\n while tmp != t_idx and pts[tmp, 1] - pts[t_idx, 1] <= thresh * h:\n t_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n tt = (max(pts[t_idxs, 0]) + min(pts[t_idxs, 0])) / 2\n aux_ext_pts.append(np.array([tt, t]))\n t_band = [item for item in t_band if item not in t_idxs]\n\n b_band = np.where((b - pts[:, 1]) <= band_thresh * h)[0].tolist()\n while b_band:\n b_idx = b_band[np.argmax(pts[b_band, 1])]\n b_idxs = [b_idx]\n tmp = (b_idx + 1) % num_pt\n while tmp != b_idx and pts[b_idx, 1] - pts[tmp, 1] <= thresh * h:\n b_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (b_idx - 1) % num_pt\n while tmp != b_idx and pts[b_idx, 1] - pts[tmp, 1] <= thresh * h:\n b_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n bb = (max(pts[b_idxs, 0]) + min(pts[b_idxs, 0])) / 2\n aux_ext_pts.append(np.array([bb, b]))\n b_band = [item for item in b_band if item not in b_idxs]\n\n l_band = np.where((pts[:, 0] - l) <= band_thresh * w)[0].tolist()\n while l_band:\n l_idx = l_band[np.argmin(pts[l_band, 0])]\n l_idxs = [l_idx]\n tmp = (l_idx + 1) % num_pt\n while tmp != l_idx and pts[tmp, 0] - pts[l_idx, 0] <= thresh * w:\n l_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (l_idx - 1) % num_pt\n while tmp != l_idx and pts[tmp, 0] - pts[l_idx, 0] <= thresh * w:\n l_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n ll = (max(pts[l_idxs, 1]) + min(pts[l_idxs, 1])) / 2\n aux_ext_pts.append(np.array([l, ll]))\n l_band = [item for item in l_band if item not in l_idxs]\n\n r_band = np.where((r - pts[:, 0]) <= band_thresh * w)[0].tolist()\n while r_band:\n r_idx = r_band[np.argmax(pts[r_band, 0])]\n r_idxs = [r_idx]\n tmp = (r_idx + 1) % num_pt\n while tmp != r_idx and pts[r_idx, 0] - pts[tmp, 0] <= thresh * w:\n r_idxs.append(tmp)\n tmp = (tmp + 1) % num_pt\n tmp = (r_idx - 1) % num_pt\n while tmp != r_idx and pts[r_idx, 0] - pts[tmp, 0] <= thresh * w:\n r_idxs.append(tmp)\n tmp = (tmp - 1) % num_pt\n rr = (max(pts[r_idxs, 1]) + min(pts[r_idxs, 1])) / 2\n aux_ext_pts.append(np.array([r, rr]))\n r_band = [item for item in r_band if item not in r_idxs]\n\n # assert len(aux_ext_pts) >= 4\n pt0 = aux_ext_pts[0]\n\n # collecting\n aux_ext_pts = np.stack(aux_ext_pts, axis=0)\n\n # ordering\n shift_idx = np.argmin(np.power(pts - pt0, 2).sum(axis=1))\n re_ordered_pts = np.roll(pts, -shift_idx, axis=0)\n\n # indexing\n ext_idxs = np.argmin(np.sum(\n (aux_ext_pts[:, np.newaxis, :] - re_ordered_pts[np.newaxis, ...]) ** 2, axis=2),\n axis=1)\n ext_idxs[0] = 0\n\n ext_idxs = np.sort(np.unique(ext_idxs))\n\n return re_ordered_pts, ext_idxs\n\ndef vis_training_targets(cfg, fcose_outputs, image_list, idx=0):\n import matplotlib.pyplot as plt\n import matplotlib.patches as patches\n import numpy as np\n\n colors = np.array([[1, 1, 198],\n [51, 1, 148],\n [101, 1, 98],\n [151, 1, 48],\n [201, 1, 8]]) / 255.\n\n num_loc_list = [len(loc) for loc in fcose_outputs.locations]\n fcose_outputs.num_loc_list = num_loc_list\n\n # compute locations to size ranges\n loc_to_size_range = []\n for l, loc_per_level in enumerate(fcose_outputs.locations):\n loc_to_size_range_per_level = loc_per_level.new_tensor(fcose_outputs.sizes_of_interest[l])\n loc_to_size_range.append(\n loc_to_size_range_per_level[None].expand(num_loc_list[l], -1)\n )\n\n # (Sigma_{levels_points}, 2)\n loc_to_size_range = torch.cat(loc_to_size_range, dim=0)\n locations = torch.cat(fcose_outputs.locations, dim=0)\n\n training_targets = fcose_outputs.compute_targets_for_locations(\n locations, fcose_outputs.gt_instances, loc_to_size_range\n )\n\n training_target = {k: v[idx] for k, v in training_targets.items()}\n\n fig, ax = plt.subplots(1, figsize=(20, 10))\n fig.tight_layout()\n\n labels = training_target['labels']\n reg_targets = training_target['reg_targets']\n ext_targets = training_target['ext_targets']\n\n idxOfloc_of_interest = torch.where(labels != 20)[0]\n\n global locxys, reg_targets_oi, ext_targets_oi, detections\n\n locxys = locations[idxOfloc_of_interest]\n\n reg_targets_oi = reg_targets[idxOfloc_of_interest]\n ext_targets_oi = ext_targets[idxOfloc_of_interest]\n\n detections = torch.stack([\n locxys[:, 0] - reg_targets_oi[:, 0],\n locxys[:, 1] - reg_targets_oi[:, 1],\n locxys[:, 0] + reg_targets_oi[:, 2],\n locxys[:, 1] + reg_targets_oi[:, 3],\n ], dim=1)\n\n global tmp, ext_points\n\n ext_points = ExtremePoints.from_boxes(Boxes(detections),\n ext_targets_oi,\n locxys).tensor.cpu().numpy()\n\n tmp = ext_points\n\n im = image_list.tensor[idx]\n pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(im.device).view(-1, 1, 1)\n pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(im.device).view(-1, 1, 1)\n im_norm = ((im * pixel_std) + pixel_mean).cpu().numpy().transpose(1, 2, 0).astype(np.uint8)\n\n ax.imshow(im_norm)\n locxys_np = locxys.cpu().numpy()\n reg_targets_oi_np = reg_targets_oi.cpu().numpy()\n ext_targets_oi_np = ext_targets_oi.cpu().numpy()\n detections_np = detections.cpu().numpy()\n\n for i in range(len(locxys_np)):\n ax.scatter(locxys_np[i, 0], locxys_np[i, 1], color=colors[i % len(colors)].tolist(), marker='*')\n x1, y1, x2, y2 = detections_np[i, :]\n\n rect = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor=colors[i % len(colors)].tolist(),\n facecolor='none', fill=False)\n ax.add_patch(rect)\n\n ax.scatter(ext_points[i][:, 0], ext_points[i][:, 1], color=colors[i % len(colors)].tolist(), marker='+')\n\n plt.show()\n","repo_name":"lkevinzc/dance","sub_path":"core/modeling/fcose/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9721,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"53"}
+{"seq_id":"2543390940","text":"# A variable is a container for a value, which can be of various types\r\n\r\n'''\r\nThis is a\r\nmultiline comment\r\nor docstring (used to define a functions purpose)\r\ncan be single or double quotes\r\n'''\r\n\r\n\"\"\"\r\nVARIABLE RULES:\r\n - Variable names are case sensitive (name and NAME are different variables)\r\n - Must start with a letter or an underscore\r\n - Can have numbers but can not start with one\r\n\"\"\"\r\n\r\nx_hd = 2\r\ny_hd = 3.6\r\nname_hd = 'Hamze'\r\nis_cool_hd = False\r\n\r\nx_hd, y_hd, name_hd, is_cool_hd = (2, 3.6, 'Hamze', False)\r\n\r\na_hd = x_hd + y_hd\r\n\r\nprint(x_hd, y_hd, name_hd, is_cool_hd, a_hd)\r\n\r\nx_hd = str(x_hd)\r\ny_hd = int(y_hd)\r\nz_hd = float(y_hd)\r\n\r\nprint(type(z_hd), z_hd)\r\n","repo_name":"hamze361/SiberkozaAssignments","sub_path":"Python Course/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"7651036509","text":"import uuid\r\nimport bleach\r\nimport secrets\r\nimport hashlib\r\nimport os\r\nimport random\r\nfrom datetime import datetime\r\nimport dateutil.relativedelta\r\nfrom profanity_check import predict\r\nfrom better_profanity import profanity\r\nfrom horde.logger import logger\r\nfrom horde.flask import SQLITE_MODE\r\n\r\nprofanity.load_censor_words()\r\n\r\nrandom.seed(random.SystemRandom())\r\n\r\ndef is_profane(text):\r\n if profanity.contains_profanity(text):\r\n return True\r\n if predict([text]) == [1]:\r\n return True\r\n return False\r\n\r\ndef count_digits(number):\r\n digits = 1\r\n while number > 10:\r\n number = number / 10\r\n digits += 1\r\n return digits\r\n\r\nclass ConvertAmount:\r\n\r\n def __init__(self,amount,decimals = 1):\r\n self.digits = count_digits(amount)\r\n self.decimals = decimals\r\n if self.digits < 4:\r\n self.amount = amount\r\n self.prefix = ''\r\n self.char = ''\r\n elif self.digits < 7:\r\n self.amount = round(amount / 1000, self.decimals)\r\n self.prefix = 'kilo'\r\n self.char = 'K'\r\n elif self.digits < 10:\r\n self.amount = round(amount / 1000000, self.decimals)\r\n self.prefix = 'mega'\r\n self.char = 'M'\r\n elif self.digits < 13:\r\n self.amount = round(amount / 1000000000, self.decimals)\r\n self.prefix = 'giga'\r\n self.char = 'G'\r\n else:\r\n self.amount = round(amount / 1000000000000, self.decimals)\r\n self.prefix = 'tera'\r\n self.char = 'T'\r\n\r\ndef get_db_uuid():\r\n if SQLITE_MODE:\r\n return str(uuid.uuid4())\r\n else: \r\n return uuid.uuid4()\r\n\r\ndef generate_client_id():\r\n return secrets.token_urlsafe(16)\r\n\r\ndef sanitize_string(text):\r\n santxt = bleach.clean(text).lstrip().rstrip()\r\n return santxt\r\n\r\ndef hash_api_key(unhashed_api_key):\r\n salt = os.getenv(\"secret_key\", \"s0m3s3cr3t\") # Note default here, just so it can run without env file\r\n hashed_key = hashlib.sha256(salt.encode() + unhashed_api_key.encode()).hexdigest()\r\n # logger.warning([os.getenv(\"secret_key\", \"s0m3s3cr3t\"), hashed_key,unhashed_api_key])\r\n return hashed_key\r\n\r\ndef get_expiry_date():\r\n return datetime.utcnow() + dateutil.relativedelta.relativedelta(minutes=+20)\r\n\r\ndef get_interrogation_form_expiry_date():\r\n return datetime.utcnow() + dateutil.relativedelta.relativedelta(minutes=+3)\r\n\r\ndef get_random_seed():\r\n '''Generated a random seed, using a random number unique per node'''\r\n return random.randint(0, 2**32 - 1)","repo_name":"xcytxs/AI-Horde","sub_path":"horde/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"1933317775","text":"class devs:\r\n def __init__(self, name, rank, years, pay) -> None:\r\n \r\n self.name = name\r\n self.rank = \"Junior\"\r\n self.years = 0\r\n self.pay = pay\r\n \r\n def UpRisePay(self):\r\n \r\n i = True\r\n while i:\r\n b = input(f\"\\nAlapértelemezetten vagy az ön által kiszabott mennyiséggel akarja-e növelni {self.name} fizetését? (Alap/Kiszab): \")\r\n if b == \"Alap\":\r\n self.pay += 10000\r\n i = False\r\n elif b == \"Kiszab\":\r\n amount = int(input(f\"\\nMennyivel kívánja növelni {self.name} fizetését: \"))\r\n self.pay += amount\r\n i = False\r\n else:\r\n print(\"\\nHibás bevitel!\")\r\n \r\n def YearS(self):\r\n self.years += 1\r\n \r\n def DevRank(self):\r\n if self.years == 0:\r\n self.rank = \"Intern\"\r\n \r\n if 1 <= self.years <= 2:\r\n self.rank = \"Junior\"\r\n \r\n if 2 <= self.years <= 5:\r\n self.rank = \"Medior\"\r\n \r\n if self.years > 5:\r\n self.rank = \"Senior\"\r\n \r\n def devdata(self):\r\n print(f\"\\nNév: {self.name}\\nRang: {self.rank}\\nÉvek: {self.years}\\nFizetés: {self.pay}\\n\" )\r\n \r\ndef main():\r\n a1 = devs(name=\"Kádár Barnabás\", rank=\"\", years= 0, pay= 0)\r\n \r\n a1.UpRisePay()\r\n a1.YearS()\r\n a1.YearS()\r\n a1.YearS()\r\n a1.DevRank()\r\n \r\n a1.devdata()\r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"kadarbarnabas/BevProg1","sub_path":"hazik/5.hethazi/fejlesztoigarda.py","file_name":"fejlesztoigarda.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8543696871","text":"\"\"\"\ndjadmin2's permission handling. The permission classes have the same API as\nthe permission handling classes of the django-rest-framework. That way, we can\nreuse them in the admin's REST API.\n\nThe permission checks take place in callables that follow the following\ninterface:\n\n* They get passed in the current ``request``, an instance of the currently\n active ``view`` and optionally the object that should be used for\n object-level permission checking.\n* Return ``True`` if the permission shall be granted, ``False`` otherwise.\n\nThe permission classes are then just fancy wrappers of these basic checks of\nwhich it can hold multiple.\n\"\"\"\nimport logging\nimport re\n\nfrom django.contrib.auth import get_permission_codename\nfrom django.db.utils import DEFAULT_DB_ALIAS\nfrom django.apps import apps\nfrom django.core.exceptions import ValidationError\nfrom django.db import router\nfrom django.utils.encoding import force_str\n\nlogger = logging.getLogger('djadmin2')\n\n\ndef is_authenticated(request, view, obj=None):\n '''\n Checks if the current user is authenticated.\n '''\n return request.user.is_authenticated\n\n\ndef is_staff(request, view, obj=None):\n '''\n Checks if the current user is a staff member.\n '''\n return request.user.is_staff\n\n\ndef is_superuser(request, view, obj=None):\n '''\n Checks if the current user is a superuser.\n '''\n return request.user.is_superuser\n\n\ndef model_permission(permission):\n '''\n This is actually a permission check factory. It means that it will return\n a function that can then act as a permission check. The returned callable\n will check if the user has the with ``permission`` provided model\n permission. You can use ``{app_label}`` and ``{model_name}`` as\n placeholders in the permission name. They will be replaced with the\n ``app_label`` and the ``model_name`` (in lowercase) of the model that the\n current view is operating on.\n\n Example:\n\n .. code-block:: python\n\n check_add_perm = model_permission('{app_label}.add_{model_name}')\n\n class ModelAddPermission(permissions.BasePermission):\n permissions = [check_add_perm]\n '''\n def has_permission(request, view, obj=None):\n model_class = getattr(view, 'model', None)\n queryset = getattr(view, 'queryset', None)\n\n if model_class is None and queryset is not None:\n model_class = queryset.model\n\n assert model_class, (\n 'Cannot apply model permissions on a view that does not '\n 'have a `.model` or `.queryset` property.')\n\n try:\n # django 1.8+\n model_name = model_class._meta.model_name\n except AttributeError:\n model_name = model_class._meta.module_name\n\n permission_name = permission.format(\n app_label=model_class._meta.app_label,\n model_name=model_name)\n return request.user.has_perm(permission_name, obj)\n return has_permission\n\n\nclass BasePermission:\n '''\n Provides a base class with a common API. It implements a compatible\n interface to django-rest-framework permission backends.\n '''\n permissions = []\n permissions_for_method = {}\n\n def get_permission_checks(self, request, view):\n permission_checks = []\n permission_checks.extend(self.permissions)\n method_permissions = self.permissions_for_method.get(request.method, ())\n permission_checks.extend(method_permissions)\n return permission_checks\n\n # needs to be compatible to django-rest-framework\n def has_permission(self, request, view, obj=None):\n if request.user:\n for permission_check in self.get_permission_checks(request, view):\n if not permission_check(request, view, obj):\n return False\n return True\n return False\n\n # needs to be compatible to django-rest-framework\n def has_object_permission(self, request, view, obj):\n return self.has_permission(request, view, obj)\n\n\nclass IsStaffPermission(BasePermission):\n '''\n It ensures that the user is authenticated and is a staff member.\n '''\n permissions = (\n is_authenticated,\n is_staff)\n\n\nclass IsSuperuserPermission(BasePermission):\n '''\n It ensures that the user is authenticated and is a superuser. However it\n does not check if the user is a staff member.\n '''\n permissions = (\n is_authenticated,\n is_superuser)\n\n\n# TODO: needs documentation\n# TODO: needs integration into the REST API\nclass ModelPermission(BasePermission):\n '''\n Checks if the necessary model permissions are set for the accessed object.\n '''\n # Map methods into required permission codes.\n # Override this if you need to also provide 'view' permissions,\n # or if you want to provide custom permission checks.\n permissions_for_method = {\n 'GET': (),\n 'OPTIONS': (),\n 'HEAD': (),\n 'POST': (model_permission('{app_label}.add_{model_name}'),),\n 'PUT': (model_permission('{app_label}.change_{model_name}'),),\n 'PATCH': (model_permission('{app_label}.change_{model_name}'),),\n 'DELETE': (model_permission('{app_label}.delete_{model_name}'),),\n }\n\n\nclass ModelViewPermission(BasePermission):\n '''\n Checks if the user has the ``.view_`` permission.\n '''\n permissions = (model_permission('{app_label}.view_{model_name}'),)\n\n\nclass ModelAddPermission(BasePermission):\n '''\n Checks if the user has the ``