diff --git "a/5279.jsonl" "b/5279.jsonl"
new file mode 100644--- /dev/null
+++ "b/5279.jsonl"
@@ -0,0 +1,717 @@
+{"seq_id":"27530244036","text":"import glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tensorflow as tf\n\nfrom PIL import Image\n\nimport model\n\nIMG_SIZE = 28\nOUTPUT_SIZE = 10\nDATA_SIZE = 500\nMAXIMUM_ANALYSIS_SIZE = 30\n\ndataImages = np.zeros((DATA_SIZE, IMG_SIZE*IMG_SIZE))\ndataLabels = np.zeros((DATA_SIZE, OUTPUT_SIZE))\n\ndef read_data():\n fileImg = open('./data/testImage.txt', 'r')\n for i in range(DATA_SIZE):\n line = fileImg.readline()\n val = line.split(',')\n dataImages[i, :] = val[1:IMG_SIZE*IMG_SIZE + 1]\n \nif __name__=='__main__': \n #with tf.device(\"/gpu:0\"):\n with tf.Graph().as_default():\n read_data()\n\n graph = tf.Graph()\n sess = tf.InteractiveSession(graph = graph)\n\n with open('frozen_graph.pb', 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def, name='') #, {'x':input})\n\n print('=' * 60)\n for op in tf.get_default_graph().get_operations():\n print(op.name)\n for output in op.outputs:\n print(' ', output.name)\n print('=' * 60)\n\n if not os.path.exists('./result'):\n os.mkdir('./result')\n remaining_size = DATA_SIZE\n ANALYSIS_SIZE = MAXIMUM_ANALYSIS_SIZE\n start = 0\n counter = 0\n while True:\n if(remaining_size > 0 and remaining_size - MAXIMUM_ANALYSIS_SIZE >= 0):\n ANALYSIS_SIZE = MAXIMUM_ANALYSIS_SIZE\n elif(remaining_size > 0 and remaining_size - MAXIMUM_ANALYSIS_SIZE < 0):\n ANALYSIS_SIZE = remaining_size\n else:\n break\n\n decoded_imgs = sess.run('y:0', feed_dict={'x:0': dataImages[0:30,:], 'y_:0': dataLabels[0:30, :], 'keep_prob:0': 1.0})\n decoded_imgs = decoded_imgs.reshape([-1, OUTPUT_SIZE])\n \n for i in range(ANALYSIS_SIZE):\n filename = './result/data' + str(counter) + '.txt'\n print('writing ' + filename)\n np.savetxt(filename, decoded_imgs[i, :])\n counter += 1\n\n remaining_size -= ANALYSIS_SIZE \n start = start + ANALYSIS_SIZE\n \n for k in range(DATA_SIZE):\n plt.figure(figsize=(7, 4))\n plt.subplot(1, 2, 1)\n fig = plt.imshow(dataImages[k, :].reshape([IMG_SIZE, IMG_SIZE]), vmin=0, vmax=255, cmap='gray')\n fig.axes.get_xaxis().set_visible(False)\n fig.axes.get_yaxis().set_visible(False)\n\n output = np.loadtxt('./result/data' + str(k) + '.txt')\n plt.subplot(1, 2, 2)\n n = np.linspace(0, 9, 10)\n fig = plt.plot(output.reshape([OUTPUT_SIZE, 1]), n)\n plt.show()\n \n\n\n","repo_name":"changGitHubJ/mnist_inference_using_pb","sub_path":"apply_model_pb.py","file_name":"apply_model_pb.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24422384737","text":"from flask import Flask, jsonify, request\nfrom pprint import pprint as pp\nimport logging\n\n# Understanding how to develop API's in Python. \n#Jasonify - Flask offers the convenient jsonify() function, which returns a JSON object from Python variables:\n\napp = Flask(__name__)\n\n# My first API in Python\nincomes = [\n { 'description': 'salary', 'amount': 5000 }\n]\n\nbooks = [\n {'id': 0,\n 'title': 'A Fire Upon the Deep',\n 'author': 'Vernor Vinge',\n 'first_sentence': 'The coldsleep itself was dreamless.',\n 'year_published': '1992'},\n {'id': 1,\n 'title': 'The Ones Who Walk Away From Omelas',\n 'author': 'Ursula K. Le Guin',\n 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',\n 'published': '1973'},\n {'id': 2,\n 'title': 'Dhalgren',\n 'author': 'Samuel R. Delany',\n 'first_sentence': 'to wound the autumnal city.',\n 'published': '1975'}\n]\n\n\n@app.route('/incomes')\ndef get_incomes():\n return jsonify(incomes)\n\n# @app.route('/')\n# def json_hello():\n# return jsonify({x:x*x for x in range(5)}), 200\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return '''
Distant Reading Archive
A prototype API for distant reading of science fiction novels.
'''\n\n\n@app.route('/incomes', methods=['POST'])\ndef add_income():\n incomes.append(request.get_json())\n return '', 204\n\n# Sample Call - http://127.0.0.1:5000/api/v1/resources/books?id=1\n\n@app.route('/api/v1/resources/books', methods=['GET'])\ndef api_id():\n # Check if an ID was provided as part of the URL.\n # If ID is provided, assign it to a variable.\n # If no ID is provided, display an error in the browser.\n if 'id' in request.args:\n id = int(request.args['id'])\n else:\n return \"Error: No id field provided. Please specify an id.\"\n\n # Create an empty list for our results\n results = []\n\n # Loop through the data and match results that fit the requested ID.\n # IDs are unique, but other fields might return many results\n for book in books:\n if book['id'] == id:\n results.append(book)\n\n # Use the jsonify function from Flask to convert our list of\n # Python dictionaries to the JSON format.\n return jsonify(results)\n\n\n\n@app.route('/LongAO')\ndef QuantScreenRouter():\n\n try:\n\n logging.warning(\"before_request\")\n\n cnxn = pyodbc.connect(\n r'Driver={SQL Server Native Client 11.0};'\n r'SERVER=f6iq6q5hoj.database.windows.net;'\n r'DATABASE=QuantValue;'\n r'UID=@f6iq6q5hoj;'\n r'PWD=!'\n )\n\n cursor = cnxn.cursor()\n cursor.execute(\"exec [dbo].[QuantScreenRouter] 'LONG_AO','Toronto'\")\n logging.info(\"has data\")\t\n results = cursor.fetchall()\n entries = [dict(title=row['title'], text=row[1]) for row in results]\n\n #for row in cursor:\n # print(row.Symbol)\n\n cnxn.close(cursor)\n cursor.close()\n\n return entries\n\n except ValueError:\n pass\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n \n\n","repo_name":"nlgandhi/LearnPython","sub_path":"Learn/api1.py","file_name":"api1.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24967532141","text":"#Input text file to read. If it can't be opened then it will stop.\nfilename = input('Enter file name: ')\ntry:\n fhandle = open(filename)\nexcept:\n print('Could not open file.')\n quit()\ntopwords = input('How many words do you want to return? (Only input integers) ')\ntry:\n top = int(topwords)\nexcept:\n print('Not a number.')\n quit()\n \n#Setup empty dictionary. For each line in the opened file, split the line into individual words based on spaces. For each word in the list of words, the get method will assign 0 as default and increase by 1 whenever it encounters new word.\ncounts = dict()\nfor line in fhandle:\n wordlist = line.split()\n for iword in wordlist:\n #Idiom: retrieve, create, update counter\n counts[iword] = counts.get(iword,0)+1\n\ntmplist = list()\n#Assigning the tuple to another variable 'oldtup'\noldtup = counts.items()\n#For each pair of key and value in oldtup, switch the placements and put them into newtup. Then append it to the newly created list tmplist.\nfor k, v in oldtup:\n newtup = (v,k)\n tmplist.append(newtup)\n#Using newtup, sort from highest to lowest and put it into newcounts. Now the list is sorted from highest frequency to lowest frequency.\nnewcounts = sorted(tmplist, reverse=True)\n\nfor v,k in newcounts[:top]:\n print(k,v)","repo_name":"Silijet/Projects","sub_path":"Most Common Words/Most Common Words.py","file_name":"Most Common Words.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"3661785183","text":"class VirtualCoinPrice(object):\n \"\"\"\n Class for virtual coin price data for a specific date (day)\n Attributes:\n price: virtual coin price for a specific date (day)\n open: open price\n high: high price\n low: low price\n date:\n change: change from previous day in percentage\n \"\"\"\n\n def __init__(self,date,price,open=None,high=None,low=None,change=None):\n self.date = date\n self.price = float(price.replace(',',''))\n self.open = float(open.replace(',',''))\n self.high = float(high.replace(',',''))\n self.low = float(low.replace(',',''))\n self.change = float(change.strip('%'))\n\n def init_with_dict(self,data):\n self.date = data['date']\n self.price = data['price']\n self.open = data['open']\n self.high = data['high']\n self.low = data['low']\n self.change = data['change']\n\n def calculate_change (self, last_day_price):\n if self.price:\n self.change = (self.price - last_day_price)/last_day_price\n return self.change\n else: return None\n\n","repo_name":"eladnachum/HTML_Scrapper","sub_path":"virtual_coin/model/VirtualCoinPrice.py","file_name":"VirtualCoinPrice.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"11155487730","text":"a=int(input())\nls=list(input().split())\no=0\nans=0\nfor i in range(0,a):\n b=int(ls[i])\n if b > 0:\n o+=b\n elif b < 0 and o==0:\n ans+=b\n else:\n o-=1\nprint(ans*-1)","repo_name":"PROG-007/coding-shoding","sub_path":"codeforces/427a.py","file_name":"427a.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30203288964","text":"import asyncio\nimport json\n\nimport dpath.util\nimport pytest\n\nfrom .utils import subscribe_to_queue\n\n\n@pytest.mark.asyncio\nasync def test_get_queued_payment_tokens(stan_server, event_loop, client_id, entity_stan, future):\n \"\"\"Assert that payment tokens can be retrieved and decoded from the Queue.\"\"\"\n # Call back for the subscription\n msgs = []\n\n async def cb(msg):\n nonlocal msgs\n nonlocal future\n msgs.append(msg)\n if len(msgs) == 10:\n future.set_result(True)\n\n entity_subject = await subscribe_to_queue(entity_stan, cb)\n\n # add payment tokens to queue\n for i in range(0, 5):\n payload = {'paymentToken': {'id': 1234 + i, 'statusCode': 'COMPLETED'}}\n await entity_stan.publish(subject=entity_subject,\n payload=json.dumps(payload).encode('utf-8'))\n try:\n await asyncio.wait_for(future, 2, loop=event_loop)\n except Exception as err:\n print(err)\n\n # check the payment tokens were retrieved from the queue\n assert len(msgs) == 5\n for i in range(0, 5):\n m = msgs[i]\n assert 'paymentToken' in m.data.decode('utf-8')\n assert 'COMPLETED' == dpath.util.get(json.loads(m.data.decode('utf-8')),\n 'paymentToken/statusCode')\n assert m.sequence == i + 1\n","repo_name":"bcgov/lear","sub_path":"queue_services/common/tests/integration/test_queue_payment_token.py","file_name":"test_queue_payment_token.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"}
+{"seq_id":"40897916437","text":"#from PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom sys import exit, argv\n\nclass Window(QWidget):\n\t\"\"\"docstring for Window\"\"\"\n\tdef __init__(self):\n\t\tQWidget.__init__(self)\n\t\tself.btnSumar = QPushButton(\"sumar\")\n\t\tlayout = QVBoxLayout()\n\napp = QApplication(argv)\nwindow = Window()\nwindow.setWindowTitle(\"primera app PySide\")\nwindow.show()\nexit(app.exec_())\n","repo_name":"ArnoldoRicardo/test-python","sub_path":"pyside/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"36327054985","text":"import sys\nsys.path.append('..\\src')\n\nfrom nia.algorithms import ArtificialBeeColony\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef ackley(X):\n x = X[0]\n y = X[1]\n return -20*np.exp(-0.2*np.sqrt(0.5*(x**2+y**2)))-np.exp(0.5*(np.cos(2*np.pi*x)+np.cos(2*np.pi*y)))+np.e+20\n\n#create plot\nfig = plt.figure()\nax = fig.add_subplot(projection='3d')\nfits = []\ni = 0\nx = np.arange(-10, 10, 0.5)\ny = np.arange(-10, 10, 0.5)\nx, y = np.meshgrid(x, y)\nz = -20*np.exp(-0.2*np.sqrt(0.5*(x**2+y**2)))-np.exp(0.5*(np.cos(2*np.pi*x)+np.cos(2*np.pi*y)))+np.e+20\n\ndef log(abc):\n #clear \n plt.cla()\n # Plot the surface.\n surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n linewidth=0, antialiased=False, alpha=0.2)\n # Add a color bar which maps values to colors.\n for food in abc.food_sources:\n ax.scatter(food.solution[0], food.solution[1], food.fitness, marker='o')\n fig.canvas.draw()\n plt.pause(0.001)\n\nlower = np.array([-5,-5])\nupper = np.array([5,5])\n\nnia = ArtificialBeeColony(cost_function=ackley,\n iteration_function=log,\n lower_bond=lower,\n upper_bond=upper,\n quit_criteria = 0.0001,\n num_variable = 2,\n )\nnia.run()\nprint(nia.message);\n","repo_name":"salar-shdk/nia","sub_path":"examples/test-abc.py","file_name":"test-abc.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"}
+{"seq_id":"25872813841","text":"import sys\nimport math\nsys.setrecursionlimit(10005)\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef shuffle(arr,cnt):\n arr = arr[N-2**cnt:] + arr[:N-2**cnt]\n cnt -= 1\n while cnt>=0:\n prev = 2**(cnt+1)\n move_arr = arr[:prev]\n fix_arr = arr[prev:]\n move = 2**cnt\n arr = move_arr[prev-move:] + move_arr[:prev-move] + fix_arr[:]\n cnt -= 1\n\n return arr\ndef solve():\n for one_k in range(1,max_K+1):\n shuffled = shuffle(list(range(1,N+1)),one_k)\n for two_k in range(1,max_K+1):\n shuffled = shuffle(shuffled[:],two_k)\n for ind in range(N):\n if shuffled[ind] != cards[ind]:\n break\n else:\n print(one_k,two_k)\n return\nN = int(input())\n\ncards = list(map(int,input().split()))\n\nmax_K = 0\nwhile 2**max_Kangmax):\n\t\ttomask.append(i)\n\t\t\nMaskDetectors(w,tomask)\n\nGenerateEventsFilter(InputWorkspace='w',OutputWorkspace='temp_split',InformationWorkspace='info',UnitOfTime='Nanoseconds',LogName='SampleTemp',MinimumLogValue='7',MaximumLogValue='300',LogValueInterval='5')\nFilterEvents(InputWorkspace='w',OutputWorkspaceBaseName='split',InformationWorkspace='info',SplitterWorkspace='temp_split',FilterByPulseTime='1',GroupWorkspaces='1')\nDeleteWorkspace('split_unfiltered')\nsum=SumSpectra('split')\nsum=NormaliseByCurrent(sum)\n\ntemperature=[]\nintensity=[]\nerror=[]\n\nfor name in sum.getNames():\n\tsi=mtd[name]\n\tif si.run().getProtonCharge()>1:\n\t\tintensity.append(si.extractY()[0][0])\n\t\terror.append(si.extractE()[0][0])\n\t\ttemperature.append(si.run()['SampleTemp'].getStatistics().mean)\n\nfinal=CreateWorkspace(temperature,intensity,error)\n\nplotSpectrum(final,0,1)\nSaveAscii(final,'/SNS/SEQ/IPTS-4273/shared/int_OP.dat')\n","repo_name":"mantidproject/scripts","sub_path":"inelastic/contrib/SNS-scripts/powderTdep_OP.py","file_name":"powderTdep_OP.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"}
+{"seq_id":"73130444307","text":"import numpy as np\r\nfrom osgeo import gdal\r\nimport rasterio as rio\r\nimport tkinter\r\nfrom tkinter.filedialog import askopenfilename\r\n\r\n'''\r\nCreated on 23 December 2020 by Oanh Thi La\r\nPurposes: \r\n1. Calculate cosine of Relative Azimuth Angle (RAA) for each pixel in the image scene from Sun-Azimuth Angle and Sensor Azimuth Angle\r\n2. calculate cosine of Sun zenith angle (SZA) and Sensor zenith angle (VZA)\r\n'''\r\n'''1. COSINE OF RAA'''\r\n# Read sun azimuth angle (SAA) and sensor azimuth angle (VAA)\r\n\r\nRoot = tkinter.Tk() # Create a Tkinter.Tk() instance\r\nRoot.withdraw() # Hide the Tkinter.Tk() instance\r\nSAA_path = askopenfilename(title=u'Open SAA file', filetypes=[(\"TIF\", \".tif\")]) #choose your SAA angle\r\nVAA_path = askopenfilename(title=u'Open VAA file', filetypes=[(\"TIF\", \".tif\")]) # choose your VAA angle\r\n## read raster image as array\r\nSAA = gdal.Open(SAA_path).ReadAsArray()\r\nVAA = gdal.Open(VAA_path).ReadAsArray()\r\nsun_azi_angle = SAA/100\r\nsen_azi_angle = VAA/100\r\n\r\n## CALCULATE RELATIVE AZIMUTH ANGLE FROM SUN AZIMUTH AND SENSOR AZIMUTH ANGLE\r\ndef relative_azimuth_angle(sun_azi_angle, sen_azi_angle):\r\n difference_value = abs(sun_azi_angle - sen_azi_angle) #abs(Sensor Azimuth - 180.0 - Solar azimuth)\r\n dif_row = difference_value.shape[0]\r\n dif_col = difference_value.shape[1]\r\n rel_azi_angle = np.zeros([dif_row, dif_col])\r\n for i in range(dif_row):\r\n for j in range(dif_col):\r\n if difference_value[i, j] > 180.0:\r\n rel_azi_angle[i, j] = 360.0 - difference_value[i, j]\r\n elif difference_value[i, j] == 0:\r\n rel_azi_angle[i, j] = 0.0\r\n else:\r\n rel_azi_angle[i, j] = 180.0 - difference_value[i, j]\r\n return rel_azi_angle, difference_value\r\n\r\n[rel_azi_angle, difference_value] = relative_azimuth_angle(sun_azi_angle, sen_azi_angle)\r\n\r\n#calculating cosine of RAA angle\r\nrel_azi_angle[rel_azi_angle==0] = np.nan # convert 0 value to nan to avoid calculate cosine for pixel have 0 value\r\ncos_RAA = np.cos(rel_azi_angle)\r\ncos_RAA[np.isnan(cos_RAA)] = 0 # convert nan back to 0 value\r\ncos_RAA = np.float32(cos_RAA) # convert float64 to float32\r\n# save cos_RAA to TIF file\r\nwith rio.open(SAA_path) as src: # choose one image\r\n ras_data = src.read()\r\n ras_meta = src.profile\r\n\r\nras_meta['dtype'] = \"float32\"\r\nras_meta['No Data'] = 0.0\r\n\r\nFname1 = tkinter.filedialog.asksaveasfilename(title=u'Save RAA file', filetypes=[(\"TIF\", \".tif\")])\r\nwith rio.open(Fname1, 'w', **ras_meta) as dst: # write image with the same shape with the selected image aboved\r\n dst.write(cos_RAA, 1)\r\n\r\n\r\n\r\n\r\n'''2. COSINE OF SZA and VZA'''\r\n\r\nRoot = tkinter.Tk() # Create a Tkinter.Tk() instance\r\nRoot.withdraw() # Hide the Tkinter.Tk() instance\r\nSZA_path = askopenfilename(title=u'Open SZA file', filetypes=[(\"TIF\", \".tif\")]) #choose your SZA angle\r\nVZA_path = askopenfilename(title=u'Open VZA file', filetypes=[(\"TIF\", \".tif\")]) # choose your VZA angle\r\n## read raster image as array\r\nSZA = gdal.Open(SZA_path).ReadAsArray()\r\nVZA = gdal.Open(VZA_path).ReadAsArray()\r\nsun_ze_angle = SZA/100\r\nsen_ze_angle = VZA/100\r\n\r\nsun_ze_angle[sun_ze_angle==0] = np.nan # convert 0 value to nan to avoid calculate cosine for pixel have 0 value\r\ncos_SZA = np.cos(sun_ze_angle)\r\ncos_SZA[np.isnan(cos_SZA)] = 0 # convert nan back to 0 value\r\ncos_SZA = np.float32(cos_SZA) # convert float64 to float32\r\n\r\nsen_ze_angle[sen_ze_angle==0] = np.nan # convert 0 value to nan to avoid calculate cosine for pixel have 0 value\r\ncos_VZA = np.cos(sen_ze_angle)\r\ncos_VZA[np.isnan(cos_VZA)] = 0 # convert nan back to 0 value\r\ncos_VZA = np.float32(cos_VZA) # convert float64 to float32\r\n\r\n# save cos_SZA to TIF file\r\nwith rio.open(SZA_path) as src: # choose one image\r\n ras_data = src.read()\r\n ras_meta = src.profile\r\n\r\nras_meta['dtype'] = \"float32\"\r\nras_meta['No Data'] = 0.0\r\n\r\nFname2 = tkinter.filedialog.asksaveasfilename(title=u'Save SZA file', filetypes=[(\"TIF\", \".tif\")])\r\nwith rio.open(Fname2, 'w', **ras_meta) as dst: # write image with the same shape with the selected image aboved\r\n dst.write(cos_SZA, 1)\r\n\r\n# save cos_VZA to TIF file\r\nwith rio.open(VZA_path) as src: # choose one image\r\n ras_data = src.read()\r\n ras_meta = src.profile\r\n\r\nras_meta['dtype'] = \"float32\"\r\nras_meta['No Data'] = 0.0\r\n\r\nFname3 = tkinter.filedialog.asksaveasfilename(title=u'Save VZA file', filetypes=[(\"TIF\", \".tif\")])\r\nwith rio.open(Fname3, 'w', **ras_meta) as dst: # write image with the same shape with the selected image aboved\r\n dst.write(cos_VZA, 1)\r\n","repo_name":"LaOanh/GeoAngles-Calculation","sub_path":"GeoAnglesCalculation.py","file_name":"GeoAnglesCalculation.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"}
+{"seq_id":"39605557052","text":"# last revision: 2015-06-10 21:30\n# hyper-closest.py\n\nimport nltk, os\nfrom nltk.corpus import wordnet as wn, brown, gutenberg, stopwords\n\nNUMBER_TO_LOOK = 300\n\ndef dist(IL1, IL2):\n\td = 0\n\tL1 = IL1[:NUMBER_TO_LOOK]\n\tL2 = IL2[:NUMBER_TO_LOOK]\n\tfor e in L1:\n\t\td += (L1.index(e) - L2.index(e))**2 if e in L2 else len(L2)**2\n\treturn d\n\n# Load Categories...\nD = {}\nDcorrect = {}\nfor ctg in brown.categories():\n\tfile_pop = open('category_'+ctg+'_popular.txt', 'r')\n\tpopL = []\n\tfor line in file_pop:\n\t\tc, s = line[:-1].split('\\t')\n\t\tpopL.append(s)\n\tD[ctg] = popL\n\tfile_pop.close()\n\nresult_file = open('dist_result.txt', 'w')\ncorrect_file = open('dist_correct.txt', 'w')\ncorrect_file.write(\"NUMBER_TO_LOOK:%d\\n\"%(NUMBER_TO_LOOK))\nfor nctg in brown.categories():\n\tprint(nctg)\n\tflist = brown.fileids(categories=nctg)\n\tnumber_of_files = 0\n\tnumber_of_correct = 0\n\tfor f in flist:\n\t\tfile_inf = open('./'+nctg+'/net-' + nctg + '-' + f + '-info.txt', 'r')\n\t\tnumber_of_files += 1\n\t\tfname = file_inf.readline()[len('#FILE:'):-1]\n\t\tvertex = int(file_inf.readline()[len('#Vertices '):-1])\n\t\tarcs = int(file_inf.readline()[len('#Arcs '):-1])\n\t\tmaxpath = int(file_inf.readline()[len('#MaxPath '):-1])\n\t\tleafn = int(file_inf.readline()[len('#LeafN '):-1])\n\t\trcs = file_inf.readline()\n\n\t\tDL = []\n\t\t#Rank, Count, Synset = file_inf[5]\n\t\tfor line in file_inf:\n\t\t\tr, c, s = line[:-1].split('\\t')\n\t\t\tDL.append(s)\n\n\t\tthatctg = ''\n\t\tthatdist = -1\n\n\t\tcaldist = [(dist(D[actg], DL), actg) for actg in brown.categories()]\n\t\tcaldist.sort()\n\t\tthatctg = caldist[0][1]\n\t\tprint(nctg + '-' + f + '\\t' + thatctg + '\\t' + str(1 if nctg == thatctg else 0))\n\t\tnumber_of_correct += 1 if nctg == thatctg else 0\n\t\tresult_file.write(nctg + '-' + f + '\\t' + thatctg + '\\t' + str(1 if nctg == thatctg else 0) + '\\n')\n\tcorrect_file.write(nctg + '\\t' + str(float(number_of_correct)*100/number_of_files) + '\\n')\ncorrect_file.close()\nresult_file.close()\n","repo_name":"SuminHan/CS372-Hypernym-Tree","sub_path":"source_code/hyper-closest.py","file_name":"hyper-closest.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7159274763","text":"# <그림1>과 같이 정사각형 모양의 지도가 있다.\n# 1은 집이 있는곳 0은 집이 없는곳이다.\n# 철수는 이 지도를 가지고 연결된 모임인 단지를 정의하고 단지에 번호를 붙히려고 한다.\n# 여기서 연결되어있다는것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는경우를 말한다. ( 대각선에 있는경우 집이 아님)\n# 지도를 입력하여 단지수를 출력하고, 단지에 속하는 집을 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.\n\nN = int(input())\narr = []\nfor _ in range(N):\n arr.append(list(map(int , input())))\n\nvisited = [[False] * N for _ in range(N)]\ncount = 0\ngroup = []\ndef dfs(i, j, count):\n \n if (not visited[i][j]) and arr[i][j] == 1:\n group.append(count)\n visited[i][j] = True\n if(N > i+1 >= 0):\n dfs(i+1,j, count)\n if(N > i-1 >= 0):\n dfs(i-1,j, count)\n if(N > j+1 >= 0):\n dfs(i,j+1, count)\n if(N > j-1 >= 0):\n dfs(i,j-1, count)\n else :\n return False\n \n return True\n\nfor i in range(N):\n for j in range(N):\n if(dfs(i,j,count) == True):\n count += 1\n \nprint(count)\nnewarr = []\nfor i in range(count):\n newarr.append(group.count(i))\n\nnewarr.sort()\nfor data in newarr:\n print(data)","repo_name":"rhkdguskim/Study","sub_path":"알고리즘/이것이코딩테스트다스터디/탐색/단지번호붙이기.py","file_name":"단지번호붙이기.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38670227907","text":"import pytest_mock\nfrom src.scraper import Scraper\n\n\nclass TestScraper():\n\n def test_scraper(self, mocker: pytest_mock.MockFixture, html_page: str):\n browser = mocker.patch('src.browser.Browser')\n scraper = Scraper(browser, 'fake_url.com')\n scraper.get_estates_quantity = mocker.MagicMock(return_value=20)\n browser.get_text = mocker.MagicMock(return_value=html_page)\n estates = scraper.scrap_website()\n assert len(estates) == 20\n","repo_name":"Sotrosca/zona-prop-scraper","sub_path":"test/test_scraper.py","file_name":"test_scraper.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"}
+{"seq_id":"13134327053","text":"import os\nimport threading\nfrom pathlib import Path\nfrom threading import Lock, Thread\n\nfrom learning_site import settings\nfrom sl_ai.dataset import GestureDataset\nfrom sl_ai.gesture_classifier import GestureClassifier\nfrom sl_ai.utils import clean_listdir\n\n# MAIN_GESTURE_DATASET_PATH = Path(\"sl_ai/gestures_dataset.csv\")\n# DATASET_LOCATION = Path(\"ai_data/vgt-all\")\n# MODEL_FILE_PATH = Path(\"sl_ai/model.h5\")\n\n\nclass SingletonMeta(type):\n _instances = {}\n\n _lock: Lock = Lock()\n\n def __call__(cls, *args, **kwargs):\n with cls._lock:\n if cls not in cls._instances:\n instance = super().__call__(*args, **kwargs)\n cls._instances[cls] = instance\n return cls._instances[cls]\n\n\nclass Classifier(metaclass=SingletonMeta):\n gesture_dataset: GestureDataset = GestureDataset()\n gesture_classifier: GestureClassifier\n\n def __init__(self):\n print(\"Created a Classifier instance.\")\n # self.load_dataset()\n self.gesture_classifier: GestureClassifier = GestureClassifier(\n gesture_dataset=self.gesture_dataset\n )\n\n def load_dataset(self):\n handedness_data = {}\n for gesture_folder in clean_listdir(settings.VGT_GESTURES_ROOT):\n *gestures_name_parts, handedness_string = gesture_folder.split(\"_\")\n gesture_name = \"_\".join(gestures_name_parts)\n handedness_data[gesture_name] = (\n handedness_string[0] == \"1\",\n handedness_string[1] == \"1\",\n )\n self.gesture_dataset.scan_videos(dataset_location=settings.VGT_GESTURES_ROOT, handedness_data=handedness_data)\n self.gesture_dataset.load_gestures_from_csv()\n print(\"Searching for user uploaded datasets...\")\n for user_folder in clean_listdir(settings.UPLOADED_GESTURES_ROOT):\n for gesture_folder in clean_listdir(settings.UPLOADED_GESTURES_ROOT / user_folder):\n csv_files = list(\n filter(\n lambda file: file.endswith(\".csv\"),\n clean_listdir(\n settings.UPLOADED_GESTURES_ROOT / user_folder / gesture_folder\n ),\n )\n )\n if not csv_files:\n print(\n \"Warning: Found a uploaded gesture folder without a dataset.csv file.\"\n )\n continue\n dataset_file = csv_files[0]\n print(\n f\"Loading dataset from {settings.UPLOADED_GESTURES_ROOT / user_folder / gesture_folder / dataset_file}\"\n )\n *gestures_words, handedness_string = gesture_folder.split(\"_\")\n gesture_name = \"_\".join(gestures_words)\n gesture_dataset = GestureDataset(single_gesture=True)\n gesture_dataset.scan_videos(\n dataset_location=settings.UPLOADED_GESTURES_ROOT\n / user_folder\n / gesture_folder,\n handedness_data={\n gesture_name: (\n handedness_string[0] == \"1\",\n handedness_string[1] == \"1\",\n )\n },\n )\n gesture_dataset.load_from_csv(\n csv_path=settings.UPLOADED_GESTURES_ROOT\n / user_folder\n / gesture_folder\n / dataset_file\n )\n self.gesture_dataset.append_dataset(gesture_dataset)\n\n if settings.SAVED_MODEL_PATH.exists():\n self.gesture_classifier.load_saved_model(model_path=settings.SAVED_MODEL_PATH)\n else:\n print(\"No model file found. Training a new model.\")\n self.gesture_classifier.train(save_path=settings.SAVED_MODEL_PATH)\n self.gesture_classifier.summary()\n\n","repo_name":"ArthurVanRemoortel/Sign-Language-Learning-Tool","sub_path":"sign_language_app/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7009191591","text":"#!/usr/bin/python3\n\nimport sys\nimport json\nimport networkx as nx\nimport numpy as np\nimport networkit as nk\nfrom collections import defaultdict\n\ndef make_graph_from_json(json_data):\n G = nk.Graph()\n\n for node in json_data:\n for neighbor in json_data[node]:\n G.addEdge(int(node), int(neighbor), addMissing=True)\n\n return G\n\ndef get_seed_nodes(graph_data, n_players, n_seeds, n_rounds):\n G = make_graph_from_json(graph_data)\n N = G.numberOfNodes()\n\n print(\"[INFO]: |V|={}, |E|={}, seeds={}, iters={}\".format(\n N, G.numberOfEdges(), n_seeds, n_rounds))\n\n # this is O(m)\n bc = nk.centrality.EstimateBetweenness(G, nSamples=8, normalized=True)\n bc.run()\n\n nodes = [x[0] for x in bc.ranking()[:n_seeds]]\n # scores = tc.topkScoresList()\n\n seeds = []\n for _ in range(n_rounds):\n seeds.append(nodes)\n\n return [[str(node) for node in round] for round in seeds]\n","repo_name":"jyyeo/Pandamaniac","sub_path":"top_betweenness.py","file_name":"top_betweenness.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"8903675203","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\nfrom matplotlib.ticker import FuncFormatter\n\n\ndef heatmap_speaker_action_dataframe(full_utterance_probabilities_df, speaker_one, rewards, speaker_two=None, vmax=None,\n vmin=None, cmap=\"Purples\"):\n \"\"\"Visualize the probability of a speaker choosing an utterance.\"\"\"\n\n plt.figure()\n collapsed_df = full_utterance_probabilities_df.groupby([\"value\", \"feature\"]).agg(np.mean).reset_index()\n\n collapsed_df[\"label\"] = collapsed_df.truthful.apply(lambda x: \"X\" if x else \"\")\n\n speaker_one_col = speaker_one.name + \"_prob\"\n if speaker_two is None:\n to_plot_col = speaker_one_col\n title = \"Utterance Probabilities for {} Speaker\".format(speaker_one.name)\n else:\n cmap = \"PuOr_r\"\n title = \"Difference in Probabilities: {} (gold) vs {} (purple)\".format(speaker_one.name, speaker_two.name)\n collapsed_df[\"speaker_diff\"] = collapsed_df[speaker_one_col] - collapsed_df[speaker_two.name + \"_prob\"]\n to_plot_col = \"speaker_diff\"\n\n utterance_selection = collapsed_df.pivot(\"value\", \"feature\", to_plot_col)\n labels = collapsed_df.pivot(\"value\", \"feature\", \"label\")\n\n # Sort columns in descending order of features\n features_in_descending_order = rewards[utterance_selection.columns].sort_values(ascending=False).index\n utterance_selection = utterance_selection.reindex(features_in_descending_order, axis=1)\n labels = labels.reindex(features_in_descending_order, axis=1)\n\n if vmax is None:\n vmax = collapsed_df[to_plot_col].max()\n if vmin is None:\n vmin = collapsed_df[to_plot_col].min()\n\n formatter = FuncFormatter(_format_positive)\n\n ax = sns.heatmap(utterance_selection, annot=labels, fmt='', linewidths=.5, cmap=cmap, vmin=vmin, vmax=vmax,\n cbar_kws={'format': formatter})\n\n ax.invert_yaxis()\n\n plt.title(title)\n\n\ndef _format_positive(x, pos):\n\n return '%0.2f' % abs(x)\n","repo_name":"tsumers/signaling-bandits","sub_path":"visualizations.py","file_name":"visualizations.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"24176809186","text":"from typing import List\nimport pandas as pd\nimport xarray as xr\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport sortingview.views as vv\nfrom visualization_1D_view import create_1D_decode_view\n\nposition_info_fname = 'position_info_df.csv'\nlinear_position_info_fname = 'linear_position_info_df.csv'\nmarks_fname = 'marks_xarray.nc'\nresults_fname = 'results_xarray.nc'\n\nunit_spike_times_fname = 'unit_spike_times.npy'\n\nposterior_type='acausal_posterior'\nposition_name='linear_position'\nspeed_name='head_speed'\n\ndef main():\n position_info = pd.read_csv(position_info_fname)\n linear_position_info = pd.read_csv(linear_position_info_fname)\n print(position_info.columns)\n print(linear_position_info.columns)\n\n marks = xr.load_dataset(marks_fname)\n results = xr.load_dataset(results_fname)\n\n ref_time_sec = position_info['time'][0]\n end_time_sec = np.max(position_info['time'])\n\n #####################################################################################################\n print('Creating 1D decode view')\n view_1d_decode = create_1D_decode_view(\n ref_time_sec=ref_time_sec,\n posterior=results[posterior_type].sum(\"state\"),\n linear_position=linear_position_info[position_name],\n )\n\n # #####################################################################################################\n # print('Creating probability view')\n # view_probability = vv.TimeseriesGraph()\n # COLOR_CYCLE = [\n # \"#1f77b4\",\n # \"#ff7f0e\",\n # \"#2ca02c\",\n # \"#d62728\",\n # \"#9467bd\",\n # \"#8c564b\",\n # \"#e377c2\",\n # \"#7f7f7f\",\n # \"#bcbd22\",\n # \"#17becf\",\n # ]\n # for state, color in zip(results.state.values, COLOR_CYCLE):\n # view_probability.add_line_series(\n # name=state,\n # t=np.asarray(results['time'] - ref_time_sec).astype(np.float32),\n # y=np.asarray(\n # results[posterior_type].sel(state=state).sum(\"position\"),\n # dtype=np.float32,\n # ),\n # color=color,\n # width=1,\n # )\n\n #####################################################################################################\n print('Creating speed view')\n view_speed = vv.TimeseriesGraph().add_line_series(\n name=\"Speed [cm/s]\",\n t=np.asarray(position_info['time'] - ref_time_sec).astype(np.float32),\n y=np.asarray(position_info[speed_name], dtype=np.float32),\n color=\"black\",\n width=1,\n )\n\n #####################################################################################################\n print('Creating raster plot')\n unit_spike_times = np.load(unit_spike_times_fname, allow_pickle=True)\n plot_items: List[vv.RasterPlotItem] = []\n for i in range(len(unit_spike_times)):\n spike_times_sec = unit_spike_times[i] - ref_time_sec\n if len(spike_times_sec) > 0:\n # for unit_id in sorting.get_unit_ids():\n # spike_times_sec = np.array(sorting.get_unit_spike_train(segment_index=0, unit_id=unit_id)) / sorting.get_sampling_frequency()\n plot_items.append(\n vv.RasterPlotItem(\n unit_id=f'{i}',\n spike_times_sec=spike_times_sec.astype(np.float32)\n )\n )\n view_raster_plot = vv.RasterPlot(\n start_time_sec=0,\n end_time_sec=end_time_sec - ref_time_sec,\n plots=plot_items\n )\n view_units_table = vv.UnitsTable(columns=[], rows=[vv.UnitsTableRow(unit_id=f'{i}', values={}) for i in range(len(unit_spike_times)) if len(unit_spike_times) > 0])\n\n #####################################################################################################\n print('Creating place fields view')\n unit_firing_rates_over_linear_position_bins = np.load('unit_firing_rates_over_linear_position_bins.npy', allow_pickle=True)\n linear_position_bins_cm = np.load('linear_position_bins_cm.npy', allow_pickle=True)\n image_items = []\n for i in range(len(unit_firing_rates_over_linear_position_bins)):\n y = unit_firing_rates_over_linear_position_bins[i]\n fig, ax = plt.subplots(nrows=1, ncols=1)\n fig.set_size_inches(5, 3)\n ax.plot(linear_position_bins_cm, y)\n image_items.append(vv.UnitImagesItem(\n unit_id=f'{i}',\n figure=fig,\n dpi=100\n ))\n plt.close(fig)\n view_place_fields = vv.UnitImages(items=image_items, item_width=500, item_height=300)\n\n\n #####################################################################################################\n print('Creating timeseries view')\n v_timeseries = vv.Box(\n direction='vertical',\n items=[\n vv.LayoutItem(view_1d_decode, stretch=1, title='Decode', collapsible=True),\n # vv.LayoutItem(view_probability, stretch=1, title='Probability of state', collapsible=True),\n vv.LayoutItem(view_speed, stretch=1, title='Speed', collapsible=True),\n vv.LayoutItem(view_raster_plot, stretch=1, title='Raster', collapsible=True)\n ],\n show_titles=True\n )\n\n v_right_window = vv.Box(\n direction='horizontal',\n items=[\n vv.LayoutItem(view_units_table, max_size=180),\n vv.LayoutItem(view_place_fields)\n ]\n )\n\n v_splitter = vv.Splitter(\n direction='horizontal',\n item1=vv.LayoutItem(v_timeseries, stretch=2),\n item2=vv.LayoutItem(v_right_window, stretch=1)\n )\n\n view = v_splitter\n \n #####################################################################################################\n print('Creating figURL')\n url = view.url(label='alison example')\n print(url)\n\n\nif __name__ == '__main__':\n main()","repo_name":"dcmnts/misc","sub_path":"scratchspace/alison_example.py","file_name":"alison_example.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13773468365","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 12 00:15:15 2020\r\n\r\n@author: Mrityunjay1.Pandey\r\n\"\"\"\r\npath='./ProbabLoanDefaulters.csv'\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndf=pd.read_csv(path)\r\n#probability p(A),in variable p_a ,for the event that fico credit score is greater than 700.\r\np_a=len(df[df.fico>700])/len(df)\r\n\r\n#probabilityp(B) for the event that purpose == 'debt_consolidation'\r\np_b=len(df[df.purpose== 'debt_consolidation'])/len(df)\r\n\r\n#Calculate the purpose == 'debt_consolidation' and store it in dataframe df1.\r\ndf1=df[df.purpose== 'debt_consolidation']\r\n\r\n#Calculate the probablityp(B|A) for the event purpose == 'debt_consolidation' given \r\n#'fico' credit score is greater than 700 and store it in variable p_a_b.\r\n\r\np_a_b=(len(df1[df1.fico>700])/len(df1))/p_a\r\n\r\n#check the independency p_a_b==p_a:\r\n\r\nresult=p_a_b==p_a\r\nprint(\"Dependency Check result is:\",result)\r\n\r\n#probability p(A) for the event that paid.back.loan == Yes\r\nprob_lp=len(df[df['paid.back.loan']=='Yes'])/len(df)\r\n\r\n# probability p(B) for the event that credit.policy == Yes\r\nprob_cs=len(df[df['credit.policy']=='Yes'])/len(df)\r\n\r\n#Taking DataFrame where ['paid.back.loan'] == 'Yes'\r\n\r\nnew_df=df[df['paid.back.loan'] == 'Yes']\r\n\r\n#probablityp(B|A) for the event paid.back.loan == 'Yes' given credit.policy == 'Yes'\r\nprob_pd_cs=len(new_df[new_df['credit.policy'] == 'Yes'])/len(new_df)\r\n\r\n#Calculating conditional probability \r\n\r\nbayes=(prob_pd_cs*prob_lp)/prob_cs\r\n\r\nprint(\"Bayes Value is:\",bayes)\r\n\r\n#Visualize the bar plot for the feature purpose\r\ndf.purpose.value_counts().plot(kind='bar')\r\n#Creating new data frame with paid back loan as No\r\ndf1=df[df['paid.back.loan'] == 'No']\r\n\r\n#Visualize the bar plot for the feature purpose of df1\r\ndf1.purpose.value_counts().plot(kind='bar')\r\nplt.show()\r\n\r\n\r\n# median for installment\r\ninst_median=df.installment.median()\r\n\r\n# mean for installment\r\ninst_mean=df.installment.mean()\r\n\r\n#histogram for installment\r\nplt.hist(df.installment)\r\nplt.axvline(inst_mean, color='k', linestyle='dashed', linewidth=1)\r\nmin_ylim, max_ylim = plt.ylim()\r\nplt.text(inst_mean*1.1,max_ylim*0.9,'Mean: {:.2f}'.format(inst_mean))\r\nplt.axvline(inst_median, color='k', linestyle='dashed', linewidth=1)\r\nplt.text(inst_median*0.7,max_ylim*0.7,'\\nMedian: {:.2f}'.format(inst_median))\r\nplt.show()\r\n\r\n#histogram for log annual income\r\nplt.hist(df['log.annual.inc'])\r\nplt.show()","repo_name":"Mrityunjay87/DSMP19_GA","sub_path":"GreyAtom/Loan_Probablity/ProbabLoanDefaulters.py","file_name":"ProbabLoanDefaulters.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15518296510","text":"import os\nimport config\nfrom DQXTableUtils import VTTable\n\n\ndef response(returndata):\n\n filename = os.path.join(config.BASEDIR, 'Uploads', returndata['fileid'])\n tb = VTTable.VTTable()\n tb.allColumnsText = True\n try:\n tb.LoadFile(filename, 100)\n columns = tb.GetColList()\n returndata['columns'] = ';'.join(columns)\n except Exception as e:\n returndata['Error'] = str(e)\n return returndata\n\n return returndata","repo_name":"TAlexPerkins/panoptes","sub_path":"servermodule/panoptesserver/gettabfileinfo.py","file_name":"gettabfileinfo.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"}
+{"seq_id":"25473631349","text":"import typing as t\n\nfrom flask import Markup\n\n\ndef loader(app):\n @app.context_processor\n def author_link_from_user_proc():\n from app.models.user import User\n\n def author_link_from_user(user_id):\n return User.get_by_id(user_id).author_link or \"\"\n\n return dict(author_link_from_user=author_link_from_user)\n\n @app.context_processor\n def og_tags_proc():\n def og_tags(\n title: t.Optional[str] = None,\n description: t.Optional[str] = None,\n url: t.Optional[str] = None,\n image: t.Optional[str] = None,\n type_: t.Optional[str] = None,\n locale: t.Optional[str] = \"en_GB\",\n ):\n ogs = []\n if title:\n ogs.append(f'')\n if description:\n ogs.append(f'')\n if url:\n ogs.append(f'')\n if image:\n ogs.append(f'')\n if type_:\n ogs.append(f'')\n if locale:\n ogs.append(f'')\n\n return Markup(\"\\n\".join(ogs))\n\n return dict(og_tags=og_tags)\n","repo_name":"Flask-Planet/flask-planet.org","sub_path":"app/builtins/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"14096343687","text":"class Solution(object):\n def canVisitAllRooms(self, rooms):\n visited = [False] * len(rooms)\n stack = [0]\n count = 0\n while stack:\n v = stack.pop()\n visited[v] = True\n count += 1\n for neighbor in rooms[v]:\n if not visited[neighbor] and neighbor not in stack:\n stack.append(neighbor)\n\n return count == len(rooms)\n\n\nrooms = [[1, 2, 3],[3, 0],[1, 3],[0]]\nprint(Solution().canVisitAllRooms(rooms))\nrooms = [[1,3],[3,0,1],[2],[0]]\nprint(Solution().canVisitAllRooms(rooms))","repo_name":"dvc0310/Interview-prep-stuff","sub_path":"leetcode/rooms.py","file_name":"rooms.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"36805466173","text":"import re\nimport time\n\ns = \"python\"\n\ndef morse(text):\n encrypt = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..',\n 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--', 'Q':'--.-', 'R':'.-.',\n 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', ' ':'.....'}\n\n decrypt = {value: key for key, value in encrypt. items()}\n\n if re.match('(\\s|-|\\.)+', text):\n return ''.join(decrypt[i] for i in text.split())\n return ' '.join(encrypt[i] for i in text.upper())\n\ndef phonetic(text):\n encrypt = {'A':'Alpha', 'B':'Bravo', 'C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'H':'Hotel',\n 'I':'India','J':'Juliet', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa',\n 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey',\n 'X':'Xray', 'Y':'Yankee', 'Z':'Zulu', ' ':' '}\n\n decrypt = {value: key for key, value in encrypt.items()}\n\n if re.match('(\\s|-|\\.)+', text):\n return ''.join(decrypt[i] for i in text.split())\n return ' '.join(encrypt[i] for i in text.upper())\n\ndef vigenere_key(string, key):\n key = list(key)\n if len(string) == len(key):\n return(key)\n else:\n for i in range(len(string) - len(key)):\n key.append(key[i % len(key)])\n return (\"\".join(key))\n\ndef vigenere_text(string, key):\n vigenereText = []\n for i in range(len(string)):\n x = (ord(string[i]) +ord(key[i])) % 26\n x += ord('A')\n vigenereText.append(chr(x))\n return (\"\".join(vigenereText))\n\ndef vigenere():\n if __name__ == \"__main__\":\n string = input(\"Enter text: \").upper()\n string = string.replace(\" \", \"\")\n keyword = input(\"Enter key: \").upper()\n key = vigenere_key(string, keyword)\n vigenereText = vigenere_text(string, key)\n print(\"Vigerene Code:\", vigenereText)\n\ndef binary(text):\n encrypt = {'A': '01000001', 'B': '01000010', 'C': '01000011', 'D': '01000100', 'E': '01000101', 'F': '01000110',\n 'G': '01000111', 'H': '01001000', 'I': '01001001', 'J': '01001010', 'K': '01001011', 'L': '01001100',\n 'M': '01001101', 'N': '01001110', 'O': '01001111', 'P': '01010000', 'Q': '01010001', 'R': '01010010',\n 'S': '01010011', 'T': '01010100', 'U': '01010101', 'V': '01010110', 'W': '01010111', 'X': '01011000',\n 'Y': '01011001', 'Z': '01011010', ' ': '.....'}\n\n decrypt = {value: key for key, value in encrypt.items()}\n\n if re.match('(\\s|-|\\.)+', text):\n return ''.join(decrypt[i] for i in text.split())\n return ' '.join(encrypt[i] for i in text.upper())\n\nwhile True:\n print(\"\")\n print(\"********** MENU **********\")\n print(\"(1) Morse Code\")\n print(\"(2) Phonetic Alphabet\")\n print(\"(3) Vigenere Cipher\")\n print(\"(4) Binary Code\")\n print(\"(5) Exit\")\n print(\"***************************\")\n print(\"\")\n\n menu_option = int(input(\"What would you like to do (1-5)? \"))\n print(\"\")\n\n if menu_option == 1:\n morseTxt = str(input(\"Enter text: \")).upper()\n print(\"Morse Code:\", morse(morseTxt))\n time.sleep(5)\n if menu_option == 2:\n phoneticTxt = str(input(\"Enter text: \")).upper()\n print(\"Phonetics:\", phonetic(phoneticTxt))\n time.sleep(5)\n if menu_option == 3:\n vigenere()\n time.sleep(5)\n if menu_option == 4:\n binaryTxt = str(input(\"Enter text: \")).upper()\n print(\"Binary Code:\", binary(binaryTxt))\n time.sleep(5)\n if menu_option == 5:\n exit = str(input(\"Are you sure you want to exit (y/n)? \")).lower()\n if exit == \"y\":\n break\n\n","repo_name":"SenyoGela/Cipher-Decoder","sub_path":"codeDecoder.py","file_name":"codeDecoder.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"22095133919","text":"import torch.nn as nn\nimport torch\nfrom torchsummary import summary\n\n__all__ = ['Cfcn']\n\n\nclass Conv1x1(nn.Module):\n def __init__(self, in_channel, out_channel):\n super(Conv1x1, self).__init__()\n self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=1)\n self.bn = nn.BatchNorm2d(out_channel)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n\n return x\n\n\nclass Conv3x3(nn.Module):\n def __init__(self, _in, _out, stride=1, dilation=1):\n super(Conv3x3, self).__init__()\n self.conv = nn.Conv2d(_in, _out, kernel_size=3, stride=stride, padding=dilation, dilation=dilation)\n self.bn = nn.BatchNorm2d(_out)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n\n return x\n\n\nclass Deconv3x3(nn.Module):\n def __init__(self, _in, _out, stride=2, dilation=1):\n super(Deconv3x3, self).__init__()\n self.conv = nn.ConvTranspose2d(_in, _out, kernel_size=3, stride=stride, padding=dilation)\n self.bn = nn.BatchNorm2d(_out)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n\n return x\n\n\nclass BasicBlock(nn.Module):\n expansion: int = 1\n\n def __init__(self, in_channels, out_channels, downsample=None, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.downsample = downsample\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass CSP_layer(nn.Module):\n def __init__(self, in_channel, out_channel, block, blocks, stride):\n super(CSP_layer, self).__init__()\n self.channels = in_channel\n self.layer = self.make_layer(block, out_channel, blocks)\n self.conv1 = Conv1x1(out_channel, out_channel)\n self.conv2 = Conv1x1(out_channel*2, out_channel)\n self.downsample = Conv3x3(in_channel, out_channel, stride=stride)\n\n def make_layer(self, block, channel, blocks):\n layers = []\n downsample = None\n\n front = nn.Sequential(\n nn.Conv2d(channel, channel, kernel_size=1),\n nn.BatchNorm2d(channel),\n nn.ReLU(inplace=True)\n )\n\n back = nn.Sequential(\n nn.Conv2d(channel, channel, kernel_size=1),\n nn.BatchNorm2d(channel),\n nn.ReLU(inplace=True)\n )\n\n layers.append(front)\n\n for _ in range(blocks):\n layers.append(block(channel, channel))\n\n layers.append(back)\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.downsample(x)\n identity = x\n\n x = self.layer(x)\n\n identity = self.conv1(identity)\n x = torch.cat([x, identity], dim=1)\n out = self.conv2(x)\n\n return out\n\n\nclass Cfcn(nn.Module):\n def __init__(self, block, layers, class_num):\n super(Cfcn, self).__init__()\n self.channels = 32\n\n self.conv1 = nn.Conv2d(3, self.channels, kernel_size=3, stride=1, padding=1)\n self.bn1 = nn.BatchNorm2d(self.channels)\n self.relu = nn.ReLU(inplace=True)\n\n self.conv_layer1 = self.make_layer(block, 32, layers[0])\n self.conv_layer2 = self.make_layer(block, 64, layers[1], stride=2)\n self.conv_layer3 = self.make_layer(block, 128, layers[2], stride=2)\n self.conv_layer4 = self.make_layer(block, 256, layers[3], stride=2)\n\n self.dilconv1_1 = Conv3x3(256, 256, dilation=1)\n self.dilconv1_2 = Conv3x3(256, 256, dilation=2)\n self.dilconv1_5 = Conv3x3(256, 256, dilation=4)\n self.dilconv2_1 = Conv3x3(256, 256, dilation=1)\n self.dilconv2_2 = Conv3x3(256, 256, dilation=2)\n self.dilconv3_1 = Conv3x3(256, 256, dilation=1)\n\n self.up_conv4 = Conv1x1(256, 256)\n self.up_deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1)\n self.up_conv3 = Conv1x1(128, 128)\n self.up_deconv2 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1)\n self.up_conv2 = Conv1x1(64, 64)\n\n self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1)\n self.deconv2 = nn.ConvTranspose2d(256, 64, kernel_size=3, stride=2, padding=1)\n self.deconv1 = nn.ConvTranspose2d(128, 32, kernel_size=3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(32, class_num, kernel_size=3, padding=1)\n\n for m in self.modules():\n if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):\n nn.init.kaiming_normal_(m.weight)\n\n def make_layer(self, block, channel, blocks, stride=1):\n layers = [CSP_layer(self.channels, channel, block, blocks, stride)]\n self.channels = channel\n return nn.Sequential(*layers)\n\n def forward(self, _x):\n x = self.conv1(_x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.conv_layer1(x)\n x1 = x\n\n x = self.conv_layer2(x)\n x2 = self.up_conv2(x)\n\n x = self.conv_layer3(x)\n x3 = self.up_conv3(x)\n\n x = self.conv_layer4(x)\n\n d1x = self.dilconv1_1(x)\n d1x = self.dilconv1_2(d1x)\n d1x = self.dilconv1_5(d1x)\n d2x = self.dilconv2_1(x)\n d2x = self.dilconv2_2(d2x)\n d3x = self.dilconv3_1(x)\n x4 = d1x + d2x + d3x + x\n x4 = self.up_conv4(x4)\n\n up_x = self.up_deconv3(x4, output_size=x3.size())\n up_x = self.relu(up_x)\n x3 = x3 + up_x\n up_x = self.up_deconv2(x3, output_size=x2.size())\n up_x = self.relu(up_x)\n x2 = x2 + up_x\n\n x = self.deconv3(x, output_size=x3.size())\n x = self.relu(x)\n x = torch.cat([x, x3], dim=1)\n\n x = self.deconv2(x, output_size=x2.size())\n x = self.relu(x)\n x = torch.cat([x, x2], dim=1)\n x = self.relu(x)\n\n x = self.deconv1(x, output_size=x1.size())\n x = self.relu(x)\n\n out = self.conv2(x)\n\n return out\n\n\ndef cfcn(num_class):\n return Cfcn(BasicBlock, [9, 9, 9, 9], num_class)\n\n\nif __name__ == '__main__':\n model = cfcn(2)\n print(summary(model, (3, 256, 256), batch_size=32, device='cpu'))\n","repo_name":"BYSora/CFCN","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"22085172790","text":"import tqdm\r\nimport sys\r\nimport os\r\nimport torch\r\nimport shutil\r\n\r\nif __name__ == '__main__':\r\n args = sys.argv[1:]\r\n imgdir = args[1]\r\n images = [i for i in os.listdir(imgdir)]\r\n path_model = args[0]\r\n outdir = args[2]\r\n if os.path.exists(outdir):\r\n shutil.rmtree(outdir, ignore_errors=True)\r\n os.mkdir(outdir)\r\n model = torch.hub.load('ultralytics/yolov5', 'custom', path=path_model)\r\n for img in tqdm.tqdm(images):\r\n out = model(os.path.join(imgdir, img))\r\n df = out.pandas().xyxy[0]\r\n df['x'] = (df['xmax'] + df['xmin']) // 2\r\n df['y'] = (df['ymax'] + df['ymin']) // 2\r\n df['x'] = df['x'].astype(int)\r\n df['y'] = df['y'].astype(int)\r\n df.to_csv(os.path.join(outdir, img[:-3]+'csv'), index=False, columns = ['x', 'y'])\r\n","repo_name":"eles13/WhileTrue_walRUSfinder","sub_path":"inferenceYOLO.py","file_name":"inferenceYOLO.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"1004751130","text":"LOG_STDOUT = False\nLOGGING_LEVEL = 'DEBUG'\n\n# This the URL to resolver_service api\nGATEWAY_RESOLVER_SERVICE_URL = 'https://dev.adsabs.harvard.edu/v1/resolver/%s'\n\n# This is a URL to adsws account info service\nGATEWAY_SERVICE_ACCOUNT_INFO_URL = ''\n\n# gateway token\nGATEWAY_TOKEN = 'this is a secret api token!'\n\n# For caching\nREDIS_URL = \"redis://localhost:6379/0\"\nREDIS_NAME_PREFIX = \"link_gateway_\"\n# save to cache for a week\nREDIS_EXPIRATION_TIME = 604800\n\nGATEWAY_SERVICE_REFERRED_DOMAIN = 'adsabs.harvard.edu'\n\nGATEWAY_ADS_ABSTRACT_PAGE = '/abs/%s/abstract'\n","repo_name":"adsabs/resolver_gateway","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"17413901712","text":"#!/usr/bin/env python\n\"\"\"\nThis script is used to check if the commit message adheres to the conventional commit rules.\n 1. Optional \"revert:\" tag before commit msg\n 2. A type from the config followed by a semi colon and a whitespace\n 3. A commit body within a min and max length\nCommit-msg.config.json is used to configure the script.\n\"\"\"\n\nimport re\nimport json\nimport sys\n\n\ndef checkCommitMsg() -> None:\n \"\"\"\n Checks the commit message for the conventional commit rules.\n \"\"\"\n\n with open(sys.argv[1], encoding=\"utf-8\") as msg:\n commitMsg = msg.read()\n\n with open(\"./.hooks/commit-msg.config.json\", encoding=\"utf-8\") as configFile:\n config = json.load(configFile)\n\n regexp = r\"^(revert: )?(\"\n for msgType in config[\"types\"]:\n regexp += f\"{msgType}|\"\n regexp = regexp[0:-1] + f\"): .{{{config['length']['min']},{config['length']['max']}}}$\"\n\n if re.match(regexp, commitMsg) is None:\n print(\"please enter a commit message in the conventional format.\")\n print(\"commit message must follow (revert: )?: \")\n sys.exit(1)\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n checkCommitMsg()\n","repo_name":"ahmedemad242/secure-shared-file-storage","sub_path":".hooks/commit-msg.py","file_name":"commit-msg.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"715796713","text":"#Find if it is a perfect number\r\ndef findDivisors(num):\r\n divisior=list()\r\n for i in range(1,num):\r\n if num%i==0:\r\n divisior.append(i)\r\n else:\r\n continue\r\n return divisior\r\n\r\ndef isItPerfectNumber(num):\r\n list=findDivisors(num)\r\n total=0\r\n for i in range(0,len(list)):\r\n total +=list[i]\r\n \r\n if(total==num):\r\n print(\"{} is a perfect number\".format(num))\r\n else:\r\n print(\"{} is not a perfect number\".format(num))\r\n \r\n\r\nisItPerfectNumber(6)\r\nisItPerfectNumber(7)","repo_name":"Mertumul/PythonBasic","sub_path":"perfectnuöber.py","file_name":"perfectnuöber.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38268094427","text":"import numpy as np\nfrom mymain import my_main_3, preparation\nfrom sim_events_3 import create_sumHist, create_allsumHist, save_sumHist\n\nev_dir = ['rootfiles_noguard_06_09_2018', \n\t\t'rootfiles_zcut_only_06_09_2018', \n\t\t'rootfiles_guard_only_06_09_2018', \n\t\t'rootfiles_guard+zcut_06_09_2018'\n\t\t]\n\nsavedir = ['noguard',\n\t\t\t'zcut_only',\n\t\t\t'guard_only',\n\t\t\t'guard+zcut'\n\t\t\t]\n\nfor i_dir in range(len(ev_dir)):\n\teventfiles, background, scale, x_range = preparation(ev_dir[i_dir])\n\teventfile_czt = eventfiles[2]\n\tscale_czt = scale[2]\n\tx_range_czt = x_range[2]\n\t\n\teventfile_coating = eventfiles[1]\n\tscale_coating = scale[1]\n\tx_range_coating = x_range[1]\n\t\n\teventfile_plastic = eventfiles[0]\n\tscale_plastic = scale[0]\n\tx_range_plastic = x_range[0]\n\t\n\tall_hists = []\n\tall_hists.append(my_main_3(eventfile_plastic, scale_plastic, x_range_coating, background[0], returns=True, savedir=savedir[i_dir]))\n\tall_hists.append(my_main_3(eventfile_coating, scale_coating, x_range_coating, background[1], returns=True, savedir=savedir[i_dir]))\n\tall_hists.append(my_main_3(eventfile_czt, scale_czt, x_range_czt, background[2], returns=True, savedir=savedir[i_dir]))\n\t\n\thists = create_sumHist(all_hists, i_dir)\n\tall_sumhists = create_allsumHist(all_hists, i_dir, these_bins=250)\n\tsave_sumHist(hists, all_sumhists, background, save_dir=savedir[i_dir])\n","repo_name":"chris2503/MA","sub_path":"Calculations/main_3.py","file_name":"main_3.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38122858640","text":"from typing import List\ndef restoreMatrix(rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n col_sum = colSum\n row_sum = rowSum\n\n mat = [[0] * len(col_sum) for i in range(len(row_sum))]\n i = 0\n j = 0\n while i < len(row_sum) and j < len(col_sum):\n mat[i][j] = min(row_sum[i], col_sum[j])\n if row_sum[i] == col_sum[j]:\n i += 1\n j += 1\n elif row_sum[i] > col_sum[j]:\n row_sum[i] -= col_sum[j]\n j += 1\n else:\n col_sum[j] -= row_sum[i]\n i += 1\n\n return mat\n\ndef restoreMatrix1(rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n n, m = len(rowSum), len(colSum)\n matrix = [[0] * m for i in range(n)]\n for i in range(n):\n for j in range(m):\n matrix[i][j] = min(rowSum[i], colSum[j])\n rowSum[i] -= matrix[i][j]\n colSum[j] -= matrix[i][j]\n return matrix\n\ndef test():\n test_cases = [\n {\n \"name\": \"simple case 1\",\n \"input1\": [3,8], \n \"input2\": [4,7],\n \"expected\": [[3,0], [1,7]]\n }\n ]\n\n for test_case in test_cases:\n assert test_case[\"expected\"] == restoreMatrix1(test_case[\"input1\"], test_case[\"input2\"]), test_case[\"name\"]\nfrom datetime import datetime\nstart_time = datetime.now()\ntest()\nprint(\"Everything passed\")\nend_time = datetime.now()\nprint('Duration: {}'.format(end_time - start_time))","repo_name":"0xspringtime/leetcode","sub_path":"1605.py","file_name":"1605.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"12246476329","text":"# Kelly Peterson\n# LING 575\n# Pulling certain labels out of enron \n\nimport sys\nimport os\n\nformalityDict = {}\n\nformalityLabels = ['misspelling', 'colloquial', 'vulgar', 'offensive', 'eye dialect' ]\npartsOfSpeech = ['interjection']\n# some of these were returning ridiculous results...\n#formalityLabels.append('informal')\n#formalityLabels.append('slang')\n\ndef ReadFile(filename):\n\tfile = open(filename, 'r')\n\t\n\tfor line in file:\n\t\tline = line.strip()\n\t\tequalsIndex = line.find('=')\n\t\tword = line[:equalsIndex]\n\t\tprint(word)\n\t\twordDefString = line[equalsIndex+1:]\n\t\twordDef = eval(wordDefString)\n\t\ttempLabelDict = {}\n\t\ttempPosDict = {}\n\t\tfor defPart in wordDef:\n\t\t\tlabelKey = 'labels'\n\t\t\tif labelKey in defPart:\n\t\t\t\tlabelDict = defPart[labelKey]\n\t\t\t\tfor labelEntry in labelDict:\n\t\t\t\t\ttextKey = 'text'\n\t\t\t\t\tif textKey in labelEntry:\n\t\t\t\t\t\tlabelText = labelEntry[textKey].lower()\n\t\t\t\t\t\t#print('LABEL TEXT ENTRY : ' + labelText)\n\t\t\t\t\t\tif labelText in formalityLabels:\n\t\t\t\t\t\t\tprint('Adding label : ' + labelText)\n\t\t\t\t\t\t\tif labelText not in tempLabelDict:\n\t\t\t\t\t\t\t\ttempLabelDict[labelText] = 1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\ttempLabelDict[labelText] += 1\n\t\t\tposKey = 'partOfSpeech'\n\t\t\tif posKey in defPart:\n\t\t\t\tpos = defPart[posKey]\n\t\t\t\tif pos in partsOfSpeech:\n\t\t\t\t\tif pos not in tempPosDict:\n\t\t\t\t\t\ttempPosDict[pos] = 1\n\t\t\t\t\telse:\n\t\t\t\t\t\ttempPosDict[pos] += 1\n\t\t# now that we have raw counts, let's see if they are significant enough...\n\t\ttargetLabelCount = 0\n\t\tfor label in tempLabelDict:\n\t\t\ttargetLabelCount += tempLabelDict[label]\n\t\tlabelThreshold = 0.5\n\t\t# see how many we saw over the total definitions\n\t\tactualRatio = targetLabelCount / float(len(wordDef))\n\t\tif actualRatio > labelThreshold:\n\t\t\tprint('actual ratio : ' + str(actualRatio))\n\t\t\tif word not in formalityDict:\n\t\t\t\t# set up a new dictionary we can add labels to\n\t\t\t\tformalityDict[word] = {}\n\t\t\tfor label in tempLabelDict:\n\t\t\t\tformalityDict[word][label] = 1\n\t\t\t\t\n\t\t# now let's see if any of our parts of speech are the same count as total definitions (unanimous voting)\n\t\ttargetPosCount = 0\n\t\tfor pos in tempPosDict:\n\t\t\ttargetPosCount += tempPosDict[pos]\n\t\t\n\t\tposThreshold = 0.6\n\t\t# see how many we saw over the total definitions\n\t\tactualRatio = targetPosCount / float(len(wordDef))\n\t\t\n\t\tif actualRatio > posThreshold:\n\t\t\tif word not in formalityDict:\n\t\t\t\t# set up a new dictionary we can add labels to\n\t\t\t\tformalityDict[word] = {}\n\t\t\tfor pos in tempPosDict:\n\t\t\t\tformalityDict[word][pos] = 1\n\t\t\t\ndef WriteDict(outputFilename):\n\tprint('Writing to file : ' + outputFilename)\n\toutputFile = open(outputFilename, 'w')\n\t# let's sort these for quick lookups if needed\n\tsortedWords = formalityDict.keys()\n\tsortedWords.sort()\n\tfor word in sortedWords:\n\t\tif len(formalityDict[word]) > 0:\n\t\t\toutputFile.write(word + '=' + str(formalityDict[word]) + '\\n')\n\toutputFile.close()\n\nif len(sys.argv) != 3:\n\tprint('Usage : python wordnik_formality.py [sourceDir] [outputFile]')\n\texit(-1)\n\t\t\t\nsourceFile = sys.argv[1]\noutputFile = sys.argv[2]\n\nReadFile(sourceFile)\nWriteDict(outputFile)","repo_name":"burgersmoke/enron-formality","sub_path":"scripts/wordnik_readers/wordnik_formality.py","file_name":"wordnik_formality.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"}
+{"seq_id":"4715347889","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 23 15:37:01 2018\n\n@author: jasleenarora\n\"\"\"\n\n# define our alphabet and create a list of both upper and lower case to handle it in the message\nalphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ncaps = list(alphabet)\nlower = list(alphabet.lower())\n\n# Open the message from the input file\nmessage = open('input.txt','r')\n\n#read lines and append to string\nline1 = ''\nfor newline in message.readlines():\n line1 = line1 + str(newline)\nprint(\"The encrypted text: \")\nprint(line1)\n \n# close the opened file\nmessage.close()\n \n# Convert the input string into a list\nletters = list(line1)\n\ndictionary = open('dictionary.txt','r')\nwords = []\n#separate words by line and append them to dictionary\nfor word in dictionary.read().split('\\n'):\n words.append(word)\ndictionary.close()\n\n# For the decryption function, the steps are as follows:\n# 1. Loop through all the possible 26 keys\n# 2. Subtract each key from each letter\n# 3. Combine to form words\n# 4. Parse each word through the dictionary and find whether the word is in the dictionary or not\n# 5. Calculate the ratio, I have taken alpha as 0.2. If it is more than 0.2, then I have taken it as decrypted plaintext\n\ndef decrypt(line1):\n letters_d = list(line1)\n for key in range(0,26):\n dec = []\n for letter in line1:\n if letter in lower:\n num = lower.index(letter)\n num = num - key\n num = num%26\n letter = lower[num]\n elif letter in caps:\n num = caps.index(letter)\n num = num - key\n num = num%26\n letter = caps[num]\n dec.append(letter)\n text = ''.join(dec)\n text = text.upper()\n temp = text.split(' ')\n y=0\n n=0\n for t in temp:\n if t in words:\n y+=1\n else:\n n+=1\n\n if(n==0):\n n=0.1\n \n d = y/n\n if(d>0.2):\n temp = ' '.join(temp)\n print(\"This is the decrypted text: \")\n print(temp)\n f = open('output.txt','w')\n f.write(temp)\n \n# Call the function \ndecrypt(line1)\n","repo_name":"JasleenUT/Encryption","sub_path":"Caeser Cipher/caeser_cipher_dec.py","file_name":"caeser_cipher_dec.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30603741111","text":"import discord\nfrom discord.ext import commands\nfrom BballBot.assets.dbconnection import db_cursor\nfrom BballBot.assets.teams.aliases import team_aliases\nfrom BballBot.assets.teams.colors import team_colors\nfrom BballBot.assets.teams.logos import team_logos\n\nclass Roster(commands.Cog):\n def __init__(self, client) -> None:\n self.client = client\n \n \n @commands.command()\n async def roster(self,\n ctx: discord.ApplicationContext,\n team: str):\n if team.upper() not in team_aliases:\n await ctx.send(f\"`{team}` is not a valid abbreviation, location, or team name\")\n return\n \n team = team_aliases[team.upper()]\n db_cursor.execute(f\"SELECT player_name, jersey, pos,exp from rostered_players where team = \\\"{team}\\\";\")\n\n \n data = db_cursor.fetchall()\n max_len = max([len(x[0]) for x in data])\n text = f\"`# Pos {'Name'.ljust(max_len)}`\\n\"\n for name,jersey,pos,exp in data:\n text += f\" `{jersey.ljust(2)} {pos.center(3)} {name.ljust(max_len)}`\\n\"\n e = discord.Embed(color= discord.Colour.from_rgb(*team_colors[team]),)\\\n .add_field(name = f\"2022-2023 {team} Roster\", value = text)\\\n .set_thumbnail(url = team_logos[team])\n await ctx.send(embed = e)\n\ndef setup(client):\n client.add_cog(Roster(client))","repo_name":"PhamjaminBen/BballBot","sub_path":"BballBot/commands/roster.py","file_name":"roster.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"31308096095","text":"from vyper import ast as vy_ast\nfrom vyper.semantics.types.user.struct import StructPrimitive\nfrom vyper.semantics.validation.utils import get_exact_type_from_node\n\nfrom vyro.transpiler.context import ASTContext\nfrom vyro.transpiler.utils import set_parent\nfrom vyro.transpiler.visitor import BaseVisitor\n\n\nclass StructConverterVisitor(BaseVisitor):\n def visit_Assign(self, node: vy_ast.Assign, ast: vy_ast.Module, context: ASTContext):\n value_node = node.value\n if isinstance(value_node, vy_ast.Call):\n call_typ = get_exact_type_from_node(value_node.func)\n if not isinstance(call_typ, StructPrimitive):\n return\n\n # Unwrap `vy_ast.Dict` node for members into individual `vy_ast.keywords` node\n args_dict_node = value_node.args[0]\n value_node.args = []\n value_node._children.remove(args_dict_node)\n\n for name_node, v in zip(args_dict_node.keys, args_dict_node.values):\n kw_node = vy_ast.keyword(\n node_id=context.reserve_id(), arg=name_node.id, value=v, ast_type=\"keyword\"\n )\n value_node.keywords.append(kw_node)\n set_parent(v, kw_node)\n set_parent(kw_node, value_node)\n","repo_name":"tserg/vyro","sub_path":"vyro/transpiler/passes/struct_converter.py","file_name":"struct_converter.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"}
+{"seq_id":"8372574989","text":"import pandas as pd\nimport numpy as np\nimport mxnet as mx\nimport matplotlib.pyplot as plt\nfrom gluonts.dataset.common import ListDataset\nfrom gluonts.model.deepvar import DeepVAREstimator\nfrom gluonts.model.gpvar import GPVAREstimator\nfrom gluonts.dataset.multivariate_grouper import MultivariateGrouper\nfrom gluonts.mx.trainer import Trainer\nfrom gluonts.evaluation.backtest import make_evaluation_predictions\nfrom gluonts.dataset.field_names import FieldName\nfrom itertools import islice\nfrom gluonts.evaluation.backtest import backtest_metrics\nnp.random.seed(123)\nmx.random.seed(123)\n\ndef create_dataset(file_path):\n df = pd.read_csv(file_path, header=0, index_col=0)\n df = df.set_index('Time')\n df['Diff'] = np.log((df['Open']/df['Close']))\n #df['Diff'] = df['Close'].sub(df['Open'], axis=0)\n df = df[['Diff',\"fear\",\"anger\",\"anticipation\",\"trust\",\"suprise\",\"positive\",\"negative\",\n \"sadness\",\"disgust\",\"joy\",\"Volume_of_tweets\",\"Retweet\",\"Replies\",\"Likes\"]]\n values = df.values\n values = values.astype('float32')\n target = np.transpose(values) #(5,433)\n return target, df\n\n\ndef train(file_path, P,frac):\n target, df = create_dataset(file_path)\n i = 0\n rolling_test = []\n train_size = int(frac * df.shape[0])\n starts = [pd.Timestamp(df.index[0]) for _ in range(len(target))]\n delay = 0\n grouper_train = MultivariateGrouper(max_target_dim=df.shape[0])\n grouper_test = MultivariateGrouper(max_target_dim=df.shape[0])\n\n train_ds = ListDataset([{FieldName.TARGET: targets, FieldName.START: start}\n for (targets, start) in zip(target[:, 0:train_size - P], starts)],freq='1B')\n train_ds = grouper_train(train_ds)\n\n while train_size + delay< df.shape[0]:\n delay = int(P) * i\n test_ds = ListDataset([{FieldName.TARGET: targets, FieldName.START: start}\n for (targets, start) in zip(target[:, 0:train_size+delay], starts)],\n freq='1B')\n test_ds = grouper_test(test_ds)\n rolling_test.append(test_ds)\n i+=1\n estimator = GPVAREstimator(prediction_length=pred_len, context_length=6, freq='1B', target_dim=df.shape[1],\n trainer=Trainer(ctx=\"cpu\", epochs=200))\n return train_ds, rolling_test, estimator,train_size\n\n\ndef plot_forecasts(test_ds, predictor):\n forecast_it, ts_it = make_evaluation_predictions(test_ds, predictor=predictor, num_samples=100)\n forecasts = list(forecast_it)\n tss = list(ts_it)\n for target, forecast in islice(zip(tss, forecasts), 1):\n return forecast.copy_dim(0).mean_ts, target[0]\n\npred_len = 3\nfrac = 0.8\nfile_path = '/Users/gabriel/PycharmProjects/Finance/Data/5B- grouped final results no ML/FB_1d_final_results_no_ML.csv'\ntrain_ds, rolling_test, estimator,train_size = train(file_path, pred_len, frac)\ntrain_output = estimator.train_model(train_ds,num_workers = None)\npredictor = train_output.predictor\n\n\nfor i, test_set in enumerate(rolling_test):\n predict_stock, real_stock = plot_forecasts(test_set, predictor)\n if i == 0:\n predicted_change_stock = predict_stock\n else:\n predicted_change_stock = predicted_change_stock.append(predict_stock)\nprediction = predicted_change_stock.to_frame()\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nfig, ax = plt.subplots(2, 1,figsize=(10, 7))\n#First PLOT: Training and Test Set seperated by a red line, test set has the predictions overlayed\nreal_stock.plot(color = 'b', ax = ax[0])\nprediction.plot(color = 'g', ax = ax[0])\nax[0].axvline(real_stock.index[train_size-pred_len-1], color='r') # end of train dataset\nax[0].grid(which=\"both\") #grid lines\nax[0].legend([\"Change in Stock\", 'Predicted Change in stock'], loc=\"upper left\")\n#second Plot: zoomed in version of the test set from the first plot\nreal_stock[train_size:].plot(color = 'b', ax = ax[1])\nprediction.plot(color = 'r', ax = ax[1])\nax[1].grid(which=\"both\")\nplt.show()","repo_name":"GabrielDeza/Twitter-Adversarial-Finance","sub_path":"Forecasting/DeepVAR.py","file_name":"DeepVAR.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"25239485760","text":"import bpy\nimport re\n\nclass ObjectNavigator:\n\tdef dump(self, obj, text):\n\t\tprint('-'*40, text, '-'*40)\n\t\tfor attr in dir(obj):\n\t\t\tif hasattr(obj, attr):\n\t\t\t\tvalue = getattr(obj, attr)\n\t\t\t\tif isinstance(value, bpy.types.Property):\n\t\t\t\t\tprint(\"obj.%s = %s\" % (attr, value))\n\t\t\t\t\t# print(\" Data path: %s\" % value.path())\n\t\t\t\telse:\n\t\t\t\t\tprint(\"obj.%s = %s\" % (attr, value))\n\t\t# print(\"Full path: \", bpy.path.abspath(obj.bl_rna.filepath))\n\n\tdef add_driver(self, target, source, prop, dataPath, driverType = 'AVERAGE', func = ''):\n\t\td = target.driver_add( '[\"' + prop + '\"]' ).driver\n\t\t\n\t\td.type = driverType\n\t\td.expression = func \n\t\tv = d.variables.new()\n\t\tv.name = prop\n\t\tv.targets[0].id = source\n\t\tv.targets[0].data_path = dataPath\n\t\n\tdef get_object(self, key):\n\t\t# Use a regular expression to split the key on the period character, except when it's inside square brackets\n\t\tparts = re.split(r'(? 2:\n\t\t\tparts = parts[2:]\n\t\telse:\n\t\t\t# If the key does not contain a period character, return the bpy.data object\n\t\t\treturn bpy.data\n\n\t\t# Initialize a variable to hold the current object\n\t\tobj = bpy.data\n\n\t\t# Iterate through the parts of the key, using getattr or __getitem__ to access the corresponding attribute of the object at each level\n\t\tfor part in parts:\n\t\t\tif '[' in part:\n\t\t\t\t# If the part contains a square bracket, it represents an indexed element, so use __getitem__ to access it\n\t\t\t\t# First, split the part on the '[' character to separate the attribute name from the index\n\t\t\t\tattr_parts = part.split('[')\n\t\t\t\tattr_name = attr_parts[0] # the attribute name is the part before the '[' character\n\t\t\t\tindex = attr_parts[1][:-1].replace('\"', '') # the index is the part between the '[' and ']' characters\n\n\t\t\t\t# Check if the index is a string or an integer, and use the appropriate method to access the element\n\t\t\t\ttry:\n\t\t\t\t\tindex = int(index)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\n\t\t\t\t# Finally, use __getitem__ to access the indexed element\n\t\t\t\tobj = getattr(obj, attr_name)[index]\n\t\t\telse:\n\t\t\t\t# Otherwise, use getattr to access the attribute\n\t\t\t\tobj = getattr(obj, part)\n\n\t\t# Return the final object\n\t\treturn obj\n\n\tdef split_string(self, s):\n\t\t# Find the index of the last '[' or '.' character in the string\n\t\tstart_index = max(s.rindex('['), s.rindex('.'))\n\n\t\t# Find the index of the ']' character that corresponds to the '[' character found above, if it exists\n\t\ttry:\n\t\t\tend_index = s.index(']', start_index)\n\t\texcept ValueError:\n\t\t\tend_index = len(s)\n\n\t\t# Extract the part of the string before the '[' or '.' character\n\t\tpath = s[:start_index]\n\n\t\t# Extract the part of the string between the '[' or '.' and ']' characters, if it exists\n\t\tlevel = s[start_index + 1:end_index].replace('\"', '')\n\n\t\t# Determine the type of the level based on whether it is a number or a string\n\t\tif s[start_index:start_index+1] == '.':\n\t\t\tlevel_type = 'property'\n\t\telse:\n\t\t\tlevel_type = 'array'\n\n\t\treturn path, level, level_type\n\n\tdef set_object_value(self, key, value):\n\t\tpath, level, level_type = self.split_string(key)\n\t\tobj = self.get_object(path)\n\t\tif (level_type == 'array'):\n\t\t\tobj[level] = value\n\t\telse:\n\t\t\tsetattr(obj, level, value)\n\t\treturn obj\n","repo_name":"s-a/easy-ssp","sub_path":"ssp_object_navigator.py","file_name":"ssp_object_navigator.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"42575508104","text":"import os\nimport random\nimport poe\nfrom ...typing import sha256, Dict, get_type_hints\n\nurl = 'https://poe.com/'\nmodels = {'gpt-3.5-turbo':'capybara','claude-instant':'a2','palm':'acouchy','palm2':'acouchy','bard':'acouchy','google-bard':'acouchy','google-palm':'acouchy','llama-2-70b-chat':'llama_2_70b_chat'}\nmodel = ['gpt-3.5-turbo','claude-instant','palm2','llama-2-70b-chat']\nsupports_stream = True\nneeds_auth = False\nworking = True\ntoken = ['H959lSH8kjQ-b4K8FCrDPg%3D%3D','ACHY1MG7xz1yE0P6EByF5g%3D%3D','a4DoOVnIl3FievhYiQYOJw%3D%3D']\nformkey = ['a40f267a9751c48d34c9f12f56c5c6f8','b65db0a463062fcabe43aa6c6978c344','413b8fa39bfb54f99cb9a4f18d18aab1']\ndef _create_completion(model: str, messages: list, stream: bool, **kwargs):\n path = os.path.dirname(os.path.realpath(__file__))\n conversation = '这是一个人和一个语言模型之间的对话。语言模型应该始终作为助理进行响应,如果需要,可以参考过去的消息历史。\\n'\n for message in messages:\n conversation += '%s:%s\\n' % (message['role'], message['content'])\n conversation += '助理: '\n index = random.randrange(len(token))\n client = poe.Client(token[index],formkey=formkey[index])\n for chunk in client.send_message(models[model], conversation, with_chat_break=True):\n yield chunk[\"text_new\"]\n client.purge_conversation(models[model], count=3)\n\nparams = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \\\n '(%s)' % ', '.join(\n [f\"{name}: {get_type_hints(_create_completion)[name].__name__}\" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])","repo_name":"musabatas/g4f","sub_path":"g4f/Provider/Providers/Poe.py","file_name":"Poe.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"21958632567","text":"from __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom cloudshell.cli.service.session_pool_context_manager import (\n SessionPoolContextManager,\n)\nfrom cloudshell.cli.service.session_pool_manager import SessionPoolManager\n\nif TYPE_CHECKING:\n from logging import Logger\n\n from cloudshell.cli.service.command_mode import CommandMode\n from cloudshell.cli.types import T_SESSION\n\n\nclass CLI:\n def __init__(self, session_pool: SessionPoolManager = SessionPoolManager()):\n self._session_pool = session_pool\n\n def get_session(\n self,\n defined_sessions: list[T_SESSION],\n command_mode: CommandMode,\n logger: Logger | None = None,\n ) -> SessionPoolContextManager:\n \"\"\"Get session from the pool or create new.\"\"\"\n if not isinstance(defined_sessions, list):\n defined_sessions = [defined_sessions]\n\n if not logger:\n logger = logging.getLogger(\"cloudshell_cli\")\n return SessionPoolContextManager(\n self._session_pool, defined_sessions, command_mode, logger\n )\n","repo_name":"QualiSystems/cloudshell-cli","sub_path":"cloudshell/cli/service/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"}
+{"seq_id":"37558703913","text":"#tkinter모듈 가져오기\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\n\r\n#포인트 설정\r\npoint = 0\r\n\r\n#플레이어 설정\r\nclass Player():\r\n def __init__(self, canvas, x, y):\r\n self.canvas = canvas\r\n self.id = canvas.create_oval(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"lightpink\", outline=\"hotpink\")\r\n self.x, self.y = x, y\r\n self.nx, self.ny = x, y\r\n \r\n def move(self, direction):\r\n #w, a, s, d로 플레이어 조작\r\n if direction == 'w':\r\n self.nx, self.ny = self.x, self.y - 1\r\n elif direction == 'a':\r\n self.nx, self.ny = self.x - 1, self.y\r\n elif direction == 's':\r\n self.nx, self.ny = self.x, self.y + 1\r\n elif direction == 'd':\r\n self.nx, self.ny = self.x + 1, self.y\r\n\r\n if not self.is_collide():\r\n self.canvas.move(self.id, (self.nx - self.x) * 30, (self.ny - self.y) * 30)\r\n self.x, self.y = self.nx, self.ny\r\n\r\n # 첫 번째 퀴즈: 야구 게임\r\n if map[self.y][self.x] == 4:\r\n key = Tk()\r\n key.title(\"첫 번째 퀴즈\")\r\n key.option_add(\"*Font\", \"맑은고딕 18\")\r\n \r\n width, height = 500, 100\r\n x, y = (key.winfo_screenwidth() - width) / 2, (key.winfo_screenheight() - height) / 2\r\n key.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\r\n\r\n lab = Label(key)\r\n lab.config(text = \"숫자 야구 게임\")\r\n lab.pack()\r\n\r\n btn = Button(key)\r\n btn.config(text = \"도전\")\r\n btn.config(width = 10)\r\n\r\n def close():\r\n key.destroy()\r\n\r\n def ball():\r\n import random\r\n secretLen = 3\r\n\r\n secretList = random.sample(range(10), secretLen)\r\n secret = ''\r\n for i in range(secretLen):\r\n secret += str(secretList[i])\r\n\r\n\r\n for chance in range(10, 0, -1):\r\n while True:\r\n guess = input((\"%d 번의 기회가 남았습니다.\" % chance) + \"세 자리 숫자를 추측해보세요.: \")\r\n if len(guess) == secretLen and guess.isdigit():\r\n break\r\n strike = 0\r\n ball = 0\r\n for i in range(secretLen):\r\n if secret[i] == guess[i]:\r\n strike += 1\r\n elif secret[i] in guess:\r\n ball += 1\r\n\r\n if strike == secretLen:\r\n print('성공!!')\r\n global point\r\n point = point + 1\r\n canvas.delete(\"item1\")\r\n map[self.y][self.x] = 0\r\n close()\r\n break\r\n if strike > 0:\r\n if ball > 0:\r\n print(\"%d strike(s) and %d ball(s)\\n\" % (strike, ball))\r\n else:\r\n print(\"%d strike(s)\\n\" % strike)\r\n else:\r\n if ball > 0:\r\n print(\"%d ball(s)\\n\" % ball)\r\n else:\r\n print(\"Out\\n\")\r\n\r\n else:\r\n print(\"실패했습니다. 다시 시도하세요.\")\r\n \r\n \r\n btn.config(command = ball)\r\n btn.pack()\r\n \r\n key.mainloop()\r\n\r\n #두 번째 퀴즈: 사칙연산\r\n elif map[self.y][self.x] == 5:\r\n \r\n key = Tk()\r\n key.title(\"두 번째 퀴즈\")\r\n key.option_add(\"*Font\", \"맑은고딕 18\")\r\n \r\n width, height = 500, 150\r\n x, y = (key.winfo_screenwidth() - width) / 2, (key.winfo_screenheight() - height) / 2\r\n key.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\r\n\r\n lab = Label(key)\r\n lab.config(text = \"사칙연산\")\r\n lab.pack()\r\n \r\n btn = Button(key)\r\n btn.config(text = \"보기\")\r\n btn.config(width = 10)\r\n\r\n def num():\r\n cal = Tk()\r\n cal.title(\"사칙연산\")\r\n cal.option_add(\"*Font\", \"맑은고딕 18\")\r\n cal.resizable(False, False)\r\n\r\n width, height = 200, 40\r\n x, y = (cal.winfo_screenwidth() - width) / 2, (cal.winfo_screenheight() - height) / 2\r\n cal.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\r\n\r\n text = Text(cal)\r\n text.insert(CURRENT, \"3 + 8 x 9 / 2 = ?\")\r\n text.pack()\r\n \r\n ent = Entry(key)\r\n ent.pack()\r\n\r\n def close():\r\n key.destroy()\r\n\r\n def answer():\r\n if ent.get() == '39':\r\n global point\r\n point = point + 1\r\n canvas.delete(\"item2\")\r\n map[self.y][self.x] = 0\r\n close()\r\n\r\n btn2 = Button(key)\r\n btn2.config(text = \"입력\")\r\n btn2.config(width = 10)\r\n\r\n btn.config(command = num)\r\n btn.pack()\r\n\r\n btn2.config(command = answer)\r\n btn2.pack()\r\n\r\n key.mainloop()\r\n\r\n\r\n #세 번째 퀴즈: 파이썬 퀴즈\r\n elif map[self.y][self.x] == 6:\r\n \r\n key = Tk()\r\n key.title(\"세 번째 퀴즈\")\r\n key.option_add(\"*Font\", \"맑은고딕 18\")\r\n \r\n width, height = 550, 200\r\n x, y = (key.winfo_screenwidth() - width) / 2, (key.winfo_screenheight() - height) / 2\r\n key.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\r\n\r\n lab = Label(key)\r\n lab.config(text = \"파이썬 퀴즈\")\r\n lab.pack()\r\n\r\n lab = Label(key)\r\n lab.config(text = \"함수 안에서 선언된 변수는 전역 변수이다.\")\r\n lab.option_add(\"*Font\", \"맑은고딕 15\")\r\n lab.pack()\r\n \r\n def close():\r\n key.destroy()\r\n\r\n def click():\r\n global point\r\n point = point + 1\r\n btn2 = Button(key)\r\n btn2.config(text = \"거짓\")\r\n btn2.config(width = 10)\r\n canvas.delete(\"item3\")\r\n map[self.y][self.x] = 0\r\n close()\r\n\r\n def click2():\r\n btn = Button(key)\r\n btn.config(text = \"참\")\r\n btn.config(width = 10)\r\n \r\n btn = Button(key)\r\n btn.config(text = \"참\")\r\n btn.config(width = 10)\r\n\r\n btn2 = Button(key)\r\n btn2.config(text = \"거짓\")\r\n btn2.config(width = 10)\r\n\r\n btn.config(command = click2)\r\n btn.pack(side = LEFT, padx = 70)\r\n\r\n btn2.config(command = click)\r\n btn2.pack(side = RIGHT, padx = 70)\r\n\r\n key.mainloop()\r\n\r\n #str = StringVar()\r\n\r\n rv = IntVar()\r\n\r\n rb1 = Radiobutton(key, text = \"참\", value = 1, variable = rv)\r\n rb1.select()\r\n rb2 = Radiobutton(key, text = \"거짓\", value = 2, variable = rv)\r\n\r\n btn = Button(key)\r\n btn.config(text = \"선택\")\r\n btn.config(width = 10)\r\n btn.config(command = click)\r\n\r\n rb1.pack()\r\n rb2.pack()\r\n btn.pack()\r\n\r\n key.mainloop()\r\n\r\n\r\n #포인트가 3이 되면 도착지점 도달\r\n elif point == 3:\r\n if map[self.y][self.x] == 3:\r\n messagebox.showinfo(title=\"성공\", message=\"•*.°미로 탈출 성공 °.*•\")\r\n \r\n #이동한 곳이 벽인지 아닌지 판별\r\n def is_collide(self):\r\n if map[self.ny][self.nx] == 1:\r\n return True\r\n else:\r\n return False\r\n\r\n#키리스너 이벤트\r\ndef keyEvent(event):\r\n player.move(repr(event.char).strip(\"'\"))\r\n\r\n#tk선언\r\nroot = Tk()\r\nroot.title(\"미로 찾기\")\r\nroot.resizable(False, False)\r\n\r\n#창 너비, 높이, 위치 설정\r\nwidth, height = 690, 690\r\nx, y = (root.winfo_screenwidth() - width) / 2, (root.winfo_screenheight() - height) / 2\r\nroot.geometry(\"%dx%d+%d+%d\" % (width, height, x, y))\r\n\r\n#canvas추가, 키이벤트 부착, 창 모양 및 색깔, 마우스 포인터 모양 등 설정\r\ncanvas = Canvas(root, width=width, height=height, bg=\"white\", bd=10, relief=\"ridge\", highlightthickness=5, highlightcolor=\"thistle\", cursor=\"heart\")\r\ncanvas.bind(\"\", keyEvent)\r\ncanvas.focus_set()\r\ncanvas.pack()\r\n\r\n#미로 맵 제작(1: 벽, 2:플레이어, 3:도착지점, 4,5,6: 퀴즈)\r\nmap = [\r\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\r\n [1, 2, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\r\n [1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1],\r\n [1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1],\r\n [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 4, 1, 0, 1],\r\n [1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1],\r\n [1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1],\r\n [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1],\r\n [1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1],\r\n [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1],\r\n [1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1],\r\n [1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1],\r\n [1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 5, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1],\r\n [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1],\r\n [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1],\r\n [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],\r\n [1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1],\r\n [1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1],\r\n [1, 0, 1, 1, 1, 1, 1, 0, 1, 6, 1, 0, 1, 1,1, 0, 1, 0, 1, 0, 1, 0, 1],\r\n [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1],\r\n [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1],\r\n [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 3, 1],\r\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\r\n]\r\n\r\n#canvas에 맵 그리기\r\nfor y in range(len(map[0])):\r\n for x in range(len(map[y])):\r\n if map[y][x] == 1:\r\n canvas.create_rectangle(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"thistle\", outline = \"darkmagenta\")\r\n elif map[y][x] == 2:\r\n player = Player(canvas, x, y)\r\n elif map[y][x] == 3:\r\n canvas.create_oval(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"lightblue\", outline = \"steelblue\")\r\n elif map[y][x] == 4:\r\n canvas.create_arc(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"moccasin\", outline = \"gold\", tag = \"item1\")\r\n elif map[y][x] == 5:\r\n canvas.create_arc(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"moccasin\", outline = \"gold\", tag = \"item2\")\r\n elif map[y][x] == 6:\r\n canvas.create_arc(x * 30, y * 30, x * 30 + 30, y * 30 + 30, fill=\"moccasin\", outline = \"gold\", tag = \"item3\")\r\n\r\nroot.mainloop()\r\n","repo_name":"Myeot/2021-","sub_path":"알고리즘과게임콘텐츠 프로그램 파일.py","file_name":"알고리즘과게임콘텐츠 프로그램 파일.py","file_ext":"py","file_size_in_byte":11657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15191959163","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nimport re\nimport logging\n\nfrom allauth.account.forms import SignupForm\nfrom captcha.fields import CaptchaField\n\n\nlogger = logging.getLogger('db')\n\nclass MySignupForm(SignupForm):\n first_name = forms.CharField(required=True, max_length=50)\n last_name = forms.CharField(required=True, max_length=50)\n church = forms.CharField(required=False, max_length=100)\n weekend = forms.CharField(\n required=False,\n max_length=100,\n label='Participant weekend',\n help_text='What was the name of the weekend that you attended as a participant?',\n )\n captcha = CaptchaField(help_text=\"Don't worry — if you get it wrong you can try again. The rest of your input will be saved.\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # hp stands for [Pooh's favorite treat] + [weed synonym]\n self.hp_hint = None\n\n def clean(self):\n cleaned_data = super().clean()\n first_name = cleaned_data.get(\"first_name\")\n last_name = cleaned_data.get(\"last_name\")\n\n # The following is unfortunate and hacky, but this is the current production mole I'm whacking.\n # If they didn't enter a church or weekend\n if not cleaned_data.get(\"church\") and not cleaned_data.get(\"weekend\"):\n # If the first and last name end with the same two capital letters, preceded by any lowercase letter\n p = re.compile('[a-z]([A-Z]{2})$')\n m1 = p.search(first_name)\n m2 = p.search(last_name)\n if m1 and m2 and m1.group(1) == m2.group(1):\n logger.debug(\"%s %s (%s) \\\"signed up\\\" ;)\" % (first_name, last_name, cleaned_data.get(\"email\")))\n self.hp_hint = \"Thank you for signing up! You should receive a verification email at %s soon.\" % (cleaned_data.get(\"email\"))\n raise ValidationError(self.hp_hint)\n\n def save(self, request):\n user = super().save(request)\n\n user.first_name = self.cleaned_data['first_name']\n user.last_name = self.cleaned_data['last_name']\n user.church = self.cleaned_data['church']\n user.weekend = self.cleaned_data['weekend']\n\n user.save()\n return user\n","repo_name":"taylorvance/prayerbanner","sub_path":"accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15967916414","text":"#!/user/bin/env python\n#zoe\ndef RMB(Money):\n\n Money_str = str(Money)\n if \"-\" not in Money_str :\n Money_li = list( Money_str.split('.')[0])\n else:\n Money_li= list( Money_str.split('.')[0])[1:]\n Money_len=len(Money_li)\n if Money_len < 3:\n if \"-\" not in str(Money):\n return (\"$%.2f\" % Money)\n else:\n return (\"-$%.2f\" % abs(Money))\n else:\n rev = \"%.2f\" % Money\n n,x = divmod(Money_len, 3)\n if x != 0:\n count = n\n else:\n count = n - 1\n i = 0\n while i < count:\n Money_li.insert((Money_len - 3), ',')\n i += 1\n Money_len -= 3\n\n if \"-\" not in rev:\n Money_str2=\"+$\" + ''.join(Money_li) + rev[-3:]\n return Money_str2\n else:\n Money_str2=\"-$\" + ''.join(Money_li) + rev[-3:]\n return Money_str2\n\nMon = input(\"Please input the money:\\n\")\nmon2 = RMB(Mon)\nprint(mon2)\n\n","repo_name":"zoewei021/Python-exercise","sub_path":"excise/RMB.py","file_name":"RMB.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"20920297947","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 7 16:12:11 2023\r\n\r\n@author: Bram\r\n\"\"\"\r\n\r\nimport argparse\r\nimport cv2\r\nimport copy\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.utils.data as Data\r\nimport torchvision\r\nimport torchvision.transforms as trans\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Initialize argument parser for easy\r\nparser = argparse.ArgumentParser(\"MiniImagenet\")\r\n\r\n# Model arguments\r\nparser.add_argument(\"--num_filters\", type=int, default=16)\r\n\r\n# Training arguments\r\nparser.add_argument(\"--lr\", type=float, default=1e-4, help=\"Learning rate hyperparameter for the AdamW optimizer\")\r\n# parser.add_argument(\"--weight_decay\", type=float, default=0.0, help=\"Weight decay hyperparameter for the AdamW optimizer\")\r\nparser.add_argument(\"--num_epochs\", type=int, default=20, help=\"Number of runs over all of the training data\")\r\nparser.add_argument(\"--batch_size\", type=int, default=1, help=\"The batchsize that is fed to the model\")\r\nparser.add_argument(\"--num_workers\", type=int, default=1, help=\"The number of processes that work for the dataloader\")\r\n# parser.add_argument(\"--device\", type=str, default=\"cuda:0\", choices=[\"cuda:0\", \"cpu:0\"], help=\"Specify the device on which you run the code, gpu(cuda) or cpu\")\r\nparser.add_argument(\"--benchmark_cudnn\", type=bool, default=False)\r\n\r\nargs = parser.parse_args()\r\n\r\nprint('Pytorch Version:' , torch.__version__)\r\n\r\ndata_transforms = {\r\n 'train': trans.Compose([\r\n trans.RandomResizedCrop(224),\r\n trans.RandomHorizontalFlip(),\r\n trans.ToTensor(),\r\n # when do the transform, image pixels are compressed \r\n # from (0,255) to (0,1) then we do the normalization\r\n trans.Normalize([0.485, 0.456, 0.406], # mean of RGB\r\n [0.229, 0.224, 0.225]) # std of RGB\r\n ]),\r\n 'val': trans.Compose([\r\n trans.Resize(256),\r\n trans.CenterCrop(224),\r\n trans.ToTensor(),\r\n trans.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n}\r\n\r\ntrain_data = torchvision.datasets.CIFAR10(root='./data', train=True,\r\n download=True, transform=data_transforms['train'])\r\n\r\nval_data = torchvision.datasets.CIFAR10(root='./data', train=False,\r\n download=True, transform=data_transforms['val'])\r\n\r\nclass_names = train_data.classes\r\ndataset_sizes = {'train': len(train_data), 'val': len(val_data)}\r\n\r\ndataloaders = {\r\n 'train': Data.DataLoader(\r\n dataset=train_data,\r\n batch_size=1,\r\n shuffle=True,\r\n# num_workers=4\r\n ),\r\n\r\n 'val': Data.DataLoader(\r\n dataset=val_data,\r\n batch_size=1,\r\n shuffle=True,\r\n# num_workers=4\r\n )\r\n}\r\n\r\n# Set up the device\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu:0\")\r\nif(args.benchmark_cudnn):\r\n torch.backends.cudnn.benchmark = True\r\n\r\n# denormalize and show an image \r\ndef imshow(image, title=None):\r\n image = image.numpy().transpose((1, 2, 0)) \r\n mean = np.array([0.485, 0.456, 0.406])\r\n std = np.array([0.229, 0.224, 0.225])\r\n image = image * std + mean\r\n image = np.clip(image, 0, 1)\r\n plt.imshow(image)\r\n if title:\r\n plt.title(title)\r\n \r\nprint(dataloaders['train'])\r\n\r\n# get a batch of training data\r\nimages, classes = next(iter(dataloaders['train']))\r\n\r\n# make a grid from batch\r\nimages = torchvision.utils.make_grid(images)\r\n\r\nimshow(images, title=[class_names[x] for x in classes])\r\n\r\n\r\nvgg = torchvision.models.vgg16(pretrained=True)\r\nvgg = vgg.to(device)\r\nprint('VGG16 Architecture:\\n', vgg)\r\n\r\n# reconstruct VGG16, i.e. remove the classifier and replace it with GAP\r\nclass VGG(torch.nn.Module):\r\n def __init__(self):\r\n super(VGG, self).__init__()\r\n self.vgg = torchvision.models.vgg16(pretrained=True) \r\n self.conv = nn.Sequential(\r\n self.vgg.features, \r\n self.vgg.avgpool \r\n )\r\n \r\n # self.fc = nn.Linear(512, num_of_class)\r\n # as we use ImageNet, num_of_class=1000\r\n self.fc = nn.Linear(512, 1000)\r\n\r\n \r\n def forward(self,x): \r\n x = self.conv(x) # -> (512, 7, 7)\r\n \r\n \r\n # we use GAP to replace the fc layer, therefore we need to\r\n # convert (512,7,7) to (512, 7x7)(i.e. each group contains 7x7=49 values), \r\n # then convert (512, 7x7) to (512, 1x1) by mean(1)(i.e. average 49 values in each group), \r\n # and finally convert (512, 1) to (1, 512) \r\n x = x.view(512,7*7).mean(1).view(1,-1) # -> (1, 512)\r\n \r\n # FW^T = S\r\n # where F is the averaged feature maps, which is of shape (1,512)\r\n # W is the weights for fc layer, which is of shape (1000, 512)\r\n # S is the scores, which is of shape (1, 1000)\r\n x = self.fc(x) # -> (1, 1000)\r\n return x \r\n\r\n\r\ndef train_model(model, loss_fn, optimizer, scheduler, num_epochs=5):\r\n \"\"\"\r\n net: the model to be trained\r\n loss_fn: loss function\r\n scheduler: torch.optim.lr_scheduler\r\n \"\"\"\r\n \r\n best_model_weights = copy.deepcopy(model.state_dict())\r\n best_accuracy = 0.0\r\n train_loss = []\r\n val_loss = []\r\n train_acc = []\r\n val_acc = []\r\n \r\n for epoch in range(num_epochs):\r\n print('Epoch {}/{}'.format(epoch, num_epochs-1))\r\n print('-'*10)\r\n \r\n step_loss = 0.0\r\n epoch_accuracy = 0.0\r\n \r\n # each epoch has a training and validation phase\r\n for phase in ['train', 'val']:\r\n if phase == 'train':\r\n model.train() # set to training mode\r\n else:\r\n model.eval() # set to evaluate mode\r\n \r\n step_loss = 0.0\r\n step_corrects = 0\r\n \r\n for step, (images, labels) in enumerate(dataloaders[phase]): \r\n images = images.to(device)\r\n labels = labels.to(device)\r\n \r\n # forward pass, compute loss and make predictions\r\n outputs = model(images) \r\n preds = torch.max(outputs, 1)[1]\r\n loss = loss_fn(outputs, labels)\r\n \r\n # backward pass and update weights if in training phase\r\n if phase == 'train':\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # compute step loss and step corrects\r\n step_loss += loss.item() * images.size(0) # loss.item() extracts the loss's value\r\n step_corrects += torch.sum(preds == labels.data)\r\n \r\n \r\n if phase == 'train':\r\n scheduler.step()\r\n \r\n epoch_loss = step_loss / dataset_sizes[phase]\r\n epoch_accuracy = step_corrects.double() / dataset_sizes[phase]\r\n print('{} Loss: {:.4f} Accuracy: {:.4f}'.format(\r\n phase, epoch_loss, epoch_accuracy))\r\n\r\n if phase == 'train':\r\n train_loss.append(epoch_loss)\r\n train_acc.append(epoch_accuracy)\r\n else:\r\n val_loss.append(epoch_loss)\r\n val_acc.append(epoch_accuracy)\r\n\r\n # deep copy the model\r\n if phase == 'val' and epoch_accuracy > best_accuracy:\r\n best_accuracy = epoch_accuracy\r\n best_model_weights = copy.deepcopy(model.state_dict())\r\n \r\n print()\r\n \r\n print('Best Validation Accuracy: {:4f}'.format(best_accuracy))\r\n\r\n # draw the loss history and accuracy history\r\n x = np.arange(num_epochs)\r\n plt.subplot(221)\r\n plt.plot(x, train_loss, c='red', label='train loss')\r\n plt.plot(x, val_loss, c='blue', label='val loss')\r\n plt.legend(loc='best')\r\n\r\n plt.subplot(222)\r\n plt.plot(x, train_acc, c='red', label='train acc')\r\n plt.plot(x, val_acc, c='blue', label='val acc')\r\n plt.legend(loc='best')\r\n\r\n plt.show()\r\n \r\n # load best model weights\r\n model.load_state_dict(best_model_weights)\r\n return model\r\n\r\n# generic function to display predictions for a few images\r\ndef visualize_model(model, num_images=6):\r\n was_training = model.training # if true, the model is in training mode otherwise in evaluate mode\r\n model.eval()\r\n images_so_far = 0\r\n fig = plt.figure()\r\n \r\n for step, (images, labels) in enumerate(dataloaders['val']): \r\n outputs = model(images)\r\n preds = torch.max(outputs, 1)[1]\r\n \r\n for i in range(images.size(0)):\r\n images_so_far += 1\r\n ax = plt.subplot(num_images//2, 2, images_so_far)\r\n ax.axis('off')\r\n ax.set_title('predicted: {}'.format(class_names[preds[i]]))\r\n imshow(images.cpu().data[i])\r\n \r\n if images_so_far == num_images:\r\n model.train(mode=was_training)\r\n return\r\n \r\n model.train(mode=was_training)\r\n \r\n \r\nmodel = VGG()\r\n\r\ntrainable_parameters = []\r\nfor name, p in model.named_parameters():\r\n if \"fc\" in name:\r\n trainable_parameters.append(p)\r\n\r\nloss_fn = torch.nn.CrossEntropyLoss()\r\n\r\n# all parameters are being optimized\r\noptimizer = torch.optim.SGD(trainable_parameters, lr=0.001, momentum=0.9)\r\n\r\n# decay LR by a factor of 0.1 every 7 epochs\r\nexp_lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)\r\nmodel = train_model(model, loss_fn, optimizer, exp_lr_scheduler, num_epochs=25)\r\n\r\n\r\nvisualize_model(model)\r\n\r\n\r\nparams = list(model.fc.parameters())\r\nweight = np.squeeze(params[0].data.numpy())\r\nprint('weight.shape', weight.shape)\r\n\r\nimage, label = next(iter(dataloaders['val']))\r\n\r\nmodel.eval()\r\nscores = model(image) # get the raw scores\r\nprobs = F.softmax(scores, dim=1).data.squeeze() # use softmax to generate the probability distribution for the scores\r\nprobs, idx = probs.sort(0, True) # sort the probability distribution in descending order, and idx[0] is the predicted class\r\nprint('sum of probabilities: %.0f'%torch.sum(probs).numpy())\r\nprint('true class: ', class_names[label])\r\nprint('predicated class: ', class_names[idx[0].numpy()])\r\n\r\ndef return_CAM(feature_conv, weight, class_idx):\r\n \"\"\"\r\n return_CAM generates the CAMs and up-sample it to 224x224\r\n arguments:\r\n feature_conv: the feature maps of the last convolutional layer\r\n weight: the weights that have been extracted from the trained parameters\r\n class_idx: the label of the class which has the highest probability\r\n \"\"\"\r\n size_upsample = (224, 224)\r\n \r\n # we only consider one input image at a time, therefore in the case of \r\n # VGG16, the shape is (1, 512, 7, 7)\r\n bz, nc, h, w = feature_conv.shape \r\n output_cam = []\r\n for idx in class_idx:\r\n beforeDot = feature_conv.reshape((nc, h*w))# -> (512, 49)\r\n cam = np.matmul(weight[idx], beforeDot) # -> (1, 512) x (512, 49) = (1, 49)\r\n cam = cam.reshape(h, w) # -> (7 ,7)\r\n cam = cam - np.min(cam)\r\n cam_img = cam / np.max(cam)\r\n cam_img = np.uint8(255 * cam_img)\r\n output_cam.append(cv2.resize(cam_img, size_upsample))\r\n return output_cam\r\n\r\n\r\nfeature_maps = model.conv(image) # get the feature maps of the last convolutional layer\r\nprint('feature_maps.shape: ', feature_maps.detach().numpy().shape)\r\n\r\nCAMs = return_CAM(feature_maps.detach().numpy(), weight, [idx.numpy()[0]]) # generate the CAM for the input image\r\nheatmap = cv2.applyColorMap(CAMs[0], cv2.COLORMAP_JET)\r\n\r\n\r\nprint('original image shape: ', image.reshape((3, 224, 224)).numpy().transpose((1,2,0)).shape)\r\nprint('heatmap.shape:', heatmap.shape)\r\nimage = image.reshape((3, 224, 224)).numpy().transpose((1, 2, 0)) \r\nmean = np.array([0.485, 0.456, 0.406])\r\nstd = np.array([0.229, 0.224, 0.225])\r\nimage = image * std + mean\r\nimage = np.clip(image, 0, 1)\r\n\r\nplt.imshow(image)\r\nplt.show()\r\nplt.imshow(heatmap)\r\nplt.show()\r\n\r\nresult = 0.5 * heatmap + 0.5 * image\r\ncv2.imwrite('cam.png', result)","repo_name":"bramdortant/thesis","sub_path":"CAM.py","file_name":"CAM.py","file_ext":"py","file_size_in_byte":12030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"28967927899","text":"import json\nimport boto3\nfrom boto3.dynamodb.conditions import Attr\n\ndef lambda_handler(event, context):\n \n \n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n table = dynamodb.Table('Documents')\n \n res = []\n \n if('query' in event[\"params\"][\"querystring\"] and event[\"params\"][\"querystring\"][\"query\"]):\n res = table.scan(FilterExpression=Attr('Text').contains(event[\"params\"][\"querystring\"][\"query\"].lower()))\n else:\n res = table.scan()\n \n for item in res[\"Items\"]:\n item[\"Url\"] = 'https://s3.amazonaws.com/' + item['Bucket'] + '/' + item['Key']\n \n return {\n 'statusCode': 200,\n 'count': res[\"Count\"],\n 'res': res[\"Items\"]\n }\n","repo_name":"GuiSevero/meetup","sub_path":"src/lambda_functions/text_search.py","file_name":"text_search.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"21436667730","text":"from unittest import TestCase\nfrom sbl.syntax.prepro import *\nfrom sbl.vm.compile import *\nfrom sbl.vm.bc import *\nfrom sbl.vm.val import *\n\n\nclass TestCompiler(TestCase):\n def compile_source(self, source_text: str) -> FunTable:\n path = 'test'\n ast = Parser(source_text, path).parse()\n ast += Preprocess(path, [], ast).preprocess()\n return Compiler(ast, meta={'file': path}).compile()\n\n def test_push(self):\n fun_table = self.compile_source('''\n foo {\n a b c;\n }\n bar {\n 1 2 3 4 5 6;\n }\n ''')\n self.assertIn('foo', fun_table)\n foo_fun = fun_table['foo']\n self.assertEqual(foo_fun.bc, [\n BC.load(None, Val('a', ValType.IDENT)),\n BC.load(None, Val('b', ValType.IDENT)),\n BC.load(None, Val('c', ValType.IDENT)),\n BC.ret(None),\n ])\n\n self.assertIn('bar', fun_table)\n bar_fun = fun_table['bar']\n self.assertEqual(bar_fun.bc, [\n BC.push(None, Val(1, ValType.INT)),\n BC.push(None, Val(2, ValType.INT)),\n BC.push(None, Val(3, ValType.INT)),\n BC.push(None, Val(4, ValType.INT)),\n BC.push(None, Val(5, ValType.INT)),\n BC.push(None, Val(6, ValType.INT)),\n BC.ret(None),\n ])\n\n def test_pop(self):\n fun_table = self.compile_source('''\n foo {\n .a .b .c;\n .@;\n }\n ''')\n self.assertIn('foo', fun_table)\n foo_fun = fun_table['foo']\n self.assertEqual(foo_fun.bc, [\n BC.pop(None, Val('a', ValType.IDENT)),\n BC.pop(None, Val('b', ValType.IDENT)),\n BC.pop(None, Val('c', ValType.IDENT)),\n BC.pop(None, Val(None, ValType.NIL)),\n BC.ret(None),\n ])\n","repo_name":"alekratz/sbl-py","sub_path":"sbl/tests/test_compiler.py","file_name":"test_compiler.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13001518918","text":"import sys\nsys.stdin = open(\"D5_3135_input.txt\", \"r\")\n\nT = int(input())\nfor test_case in range(T):\n N = int(input())\n ans = []\n words = []\n for _ in range(N):\n p, s = input().split()\n if p == '1':\n words.append(s)\n else:\n cnt = 0\n for i in words:\n if s == i[:len(s)]:\n cnt += 1\n ans.append(cnt)\n print(\"#{}\".format(test_case + 1), *ans)","repo_name":"hongyong3/TIL","sub_path":"Algorithm/Swea/D5_3135.py","file_name":"D5_3135.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"74939128786","text":"from django.shortcuts import render\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import (\n Book,\n Resource,\n Author,\n)\n\nfrom wishlist.models import (\n BookCart,\n ResourceCart\n)\n\nfrom .forms import (\n BookCartForm,\n ResourceCartForm\n)\n\n@login_required\ndef book_list(request):\n today = timezone.now().date()\n queryset_list = Book.objects.all()\n\n query = request.GET.get(\"q\")\n by = request.GET.get(\"by\") \n\n if query:\n if by == 'title':\n queryset_list = queryset_list.filter(\n Q(title__icontains=query)\n ).distinct()\n elif by == 'author':\n queryset_list = queryset_list.filter(\n Q(author__name__icontains=query) |\n Q(author__nicname__icontains=query)\n ).distinct()\n elif by == 'accession_number':\n queryset_list = queryset_list.filter(\n Q(accession_number__icontains=query)\n ).distinct()\n elif by == 'call_number':\n queryset_list = queryset_list.filter(\n Q(call_number__icontains=query)\n ).distinct()\n else:\n queryset_list = queryset_list.filter(\n Q(isbn__icontains=query)\n ).distinct()\n \n total_found = len(queryset_list)\n\n paginator = Paginator(queryset_list, 10) # Show 25 contacts per page\n page_request_var = \"page\"\n page = request.GET.get(page_request_var)\n try:\n queryset = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n queryset = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n queryset = paginator.page(paginator.num_pages)\n\n context = {\n \"object_list\": queryset,\n 'total_found': total_found,\n \"title\": \"Books\",\n \"page_request_var\": page_request_var,\n \"today\": today,\n }\n # print(context)\n return render(request, \"book_list.html\", context)\n\n\n@login_required\ndef book_detail(request, id):\n instance = get_object_or_404(Book, id=id)\n cart_added = BookCart.objects.all().filter(book=instance, user=request.user).first()\n\n form = BookCartForm(request.POST or None, request.FILES or None)\n if form.is_valid() and not cart_added:\n cart_instance = form.save(commit=False)\n cart_instance.book = instance\n cart_instance.user = request.user\n cart_instance.save()\n print(\"Submitted BookCart\", form) \n # message success\n # messages.success(request, \"Successfully Added to BookCart\")\n\n context = {\n \"instance\": instance,\n \"title\": \"Book Detail\",\n \"form\": form,\n 'cart_added': cart_added,\n }\n return render(request, \"book_detail.html\", context)\n\n\n\n@login_required\ndef resource_list(request):\n today = timezone.now().date()\n queryset_list = Resource.objects.all()\n\n query = request.GET.get(\"rq\")\n by = request.GET.get(\"by\")\n res_type = request.GET.get(\"rt\")\n\n if query:\n if res_type != 'all':\n queryset_list = queryset_list.filter(\n Q(resource_type__icontains=res_type)\n ).distinct()\n if by == 'title':\n queryset_list = queryset_list.filter(\n Q(title__icontains=query)\n ).distinct()\n elif by == 'accession_number':\n queryset_list = queryset_list.filter(\n Q(accession_number__icontains=query)\n ).distinct()\n elif by == 'call_number':\n queryset_list = queryset_list.filter(\n Q(call_number__icontains=query)\n ).distinct()\n\n paginator = Paginator(queryset_list, 5) # Show 25 contacts per page\n page_request_var = \"page\"\n page = request.GET.get(page_request_var)\n try:\n queryset = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n queryset = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n queryset = paginator.page(paginator.num_pages)\n\n context = {\n \"object_list\": queryset,\n \"title\": \"Resources\",\n \"page_request_var\": page_request_var,\n \"today\": today,\n }\n # print(context)\n return render(request, \"resource_list.html\", context)\n\n@login_required\ndef resource_detail(request, id):\n instance = get_object_or_404(Resource, id=id)\n\n cart_added = ResourceCart.objects.all().filter(resource=instance, user=request.user).first()\n\n form = ResourceCartForm(request.POST or None, request.FILES or None)\n if form.is_valid() and not cart_added:\n cart_instance = form.save(commit=False)\n cart_instance.resource = instance\n cart_instance.user = request.user\n cart_instance.save()\n print(\"Submitted ResourceCart\", form)\n\n context = {\n \"instance\": instance,\n \"title\": \"Resource Detail\",\n \"form\": form,\n 'cart_added': cart_added,\n }\n return render(request, \"resource_detail.html\", context)\n\n@login_required\ndef resource_doclist(request):\n return render(request, \"under_constraction.html\", {})\n\n@login_required\ndef resource_newspaperlist(request):\n return render(request, \"under_constraction.html\", {})\n","repo_name":"belal-bh/CLIC_PUST","sub_path":"src/resource/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24253641116","text":"from tkinter import *\n\n\nclass _Frame(Frame):\n def __init__(self, master):\n super().__init__(master)\n self.build()\n\n def build(self):\n pass\n\n\nclass RadioButtons(_Frame):\n def build(self):\n self.button1 = Radiobutton(\n self,\n text='Blue',\n padx=10,\n variable=self.master.color_var,\n value=1,\n command=self.master.update_label\n )\n self.button1.pack(anchor=W)\n self.button2 = Radiobutton(\n self,\n text='Red',\n padx=10,\n variable=self.master.color_var,\n value=2,\n command=self.master.update_label\n )\n self.button2.pack(anchor=W)\n self.button3 = Radiobutton(\n self,\n text='Green',\n padx=10,\n variable=self.master.color_var,\n value=3,\n command=self.master.update_label\n )\n self.button3.pack(anchor=W)\n\n\nclass CheckBoxes(_Frame):\n def build(self):\n self.check1 = Checkbutton(\n self,\n text='Bold',\n padx=10,\n variable=self.master.bold_var,\n command=self.master.update_label\n )\n self.check1.pack()\n self.check2 = Checkbutton(\n self,\n text='Italic',\n padx=10,\n variable=self.master.italic_var,\n command=self.master.update_label\n )\n self.check2.pack()\n\n\nclass BottomButtons(_Frame):\n def build(self):\n self.button1 = Button(\n self,\n text='Verdana',\n padx=20,\n command=lambda: self.master.set_font('Verdana')\n )\n self.button1.pack(side=LEFT)\n self.button2 = Button(\n self,\n text='Times',\n padx=20,\n command=lambda: self.master.set_font('Times')\n )\n self.button2.pack(side=LEFT)\n self.button3 = Button(\n self,\n text='Quit',\n padx=20,\n command=self.master.master.destroy\n )\n self.button3.pack(side=LEFT)\n\n\nclass App(_Frame):\n def set_font(self, font):\n self.font = font\n self.update_label()\n\n def update_label(self):\n color_var = self.color_var.get()\n bold_var = self.bold_var.get()\n italic_var = self.italic_var.get()\n\n font = self.font + self.font_size\n\n if color_var == 1:\n color = 'blue'\n elif color_var == 2:\n color = 'red'\n elif color_var == 3:\n color = 'green'\n else:\n color = 'black'\n\n if bold_var:\n font += ' bold'\n if italic_var:\n font += ' italic'\n\n self.label.config(fg=color, font=font)\n\n def build(self):\n self.font = 'Times'\n self.font_size = ' 16'\n self.color_var = IntVar()\n self.bold_var = BooleanVar()\n self.italic_var = BooleanVar()\n\n self.label = Label(\n self,\n text='Python GUI Programming',\n font=self.font+self.font_size,\n padx=30,\n pady=30\n )\n self.bottom_buttons = BottomButtons(self)\n self.bottom_buttons.pack(side=BOTTOM)\n\n self.radio_buttons = RadioButtons(self)\n self.radio_buttons.pack(side=LEFT)\n self.label.pack(side=LEFT)\n self.check_boxes = CheckBoxes(self)\n self.check_boxes.pack(side=LEFT)\n\n\nroot = Tk()\nroot.title('Button Demo')\nApp(root).pack()\nmainloop()\n","repo_name":"rinald/cen213","sub_path":"lab07/button_demo.py","file_name":"button_demo.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"5777365350","text":"import pandas as pd\nimport requests\nimport os\nfrom tqdm import tqdm\nfrom handle import GetDescription, GetSamples\n\n\nsource = input('What is the file name (with extension): ')\ndelim = input('What is the delimiter: ')\nfile_name = input('What will be the output file name? ')\nsamples_amount = int(input('How many samples do you want to get? '))\n\nos.system('cls' if os.name == 'nt' else 'clear')\n\nprint('Creating a dict to save the datas...')\nresult = {}\nprint('Result was created successfully!')\n\n\ntry:\n print('Reading the data file...')\n if delim == 'tab':\n data = pd.read_csv(f'./data/{source}', sep=\"\\t\")\n else:\n data = pd.read_csv(f'./data/{source}', sep=f\"{delim}\")\n print(f'{source} was read successfully...')\n words = [x for x in data.index]\n print(f'there is {len(words)} words in the {source}')\n del data\nexcept:\n print('Error to read file')\n\nprint('\\n')\ntry:\n print('starting to search translations...')\n for word in tqdm(words):\n print(f'Getting description and samples about: \"{word}\"')\n print(f'Getting description to \"{word}\"...')\n desc = GetDescription(word)\n res = requests.get(\n f'https://pt.bab.la/dicionario/ingles-portugues/{word}')\n print(f'Getting samples to \"{word}\"...')\n examples = GetSamples(res, samples_amount)\n print(f'Save \"{word}\" on dict')\n result[word] = [desc, examples]\n print(f'\"{word}\" was saved successfully!')\n\n del res, desc, examples, words, word\nexcept:\n print('Error to create dictionary')\n\n\ntry:\n print(f'Creating {file_name} file...')\n f = open(f\"./file/{file_name}.txt\", \"w+\", encoding=\"utf-8\")\n for key, value in tqdm(result.items()):\n print(f'Creating line to \"{key}\"')\n\n line = f\"{key};\"\n line += value[0]\n line += \";\"\n for x in value[1]:\n line += \" \".join(x)\n line += \"/\"\n\n print(f'\"{key}\" line was created successfully!')\n print(f'adding \"{key}\" line on {file_name}')\n f.write(line + '\\n')\n print(f'\"{key}\" line was added successfully!')\n print(f'Closing {file_name}')\n f.close()\n print('Done!')\nexcept:\n print('Error to create a txt file')\n","repo_name":"ccr5/Deck-Creator-For-Anki","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"37543685559","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/6/8 14:33\n# @Author : Yanjun Wang\n# @Site : \n# @File : demo.py\n# @Software: PyCharm\n\nimport requests\nimport json\nimport xlwt\nimport xlrd\n\n\nsession = requests.Session()\nbook = xlwt.Workbook()\nsheet = book.add_sheet('企业')\nn = 1\nsheet.write(0,0,'name')\nsheet.write(0,1,'lon')\nsheet.write(0,2,'lat')\nsheet.write(0,3,'addr')\nfor i in range(1,100):\n try:\n res = session.get('https://restapi.amap.com/v3/place/text?keywords=化工企业&city=taiyuan&output=json&offset=100&page={}&key=8ca198a8ae0f83242d99062676df301f&extensions=all'.format(i))\n data = json.loads(res.text)\n print(data)\n if data['count'] == '0':\n break\n for dat in data['pois']:\n sheet.write(n, 0, dat['name'])\n sheet.write(n, 1, dat['location'].split(',')[0])\n sheet.write(n, 2, dat['location'].split(',')[1])\n sheet.write(n, 3, dat['address'])\n print(dat['name'],dat['location'],dat['address'])\n n+=1\n except:\n pass\n\nbook.save('太原市企业.xls')","repo_name":"cycle13/demo","sub_path":"common_learn/高德地图/高德地图/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"16920956520","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Group, Post, User, Comment, Follow\nfrom django.core.paginator import Paginator\nfrom .forms import PostForm, CommentForm\nfrom django.contrib.auth.decorators import login_required\nfrom yatube.settings import NUM_PAGE_PAGINATOR\n\n\ndef paginator(request, posts):\n paginator = Paginator(posts, NUM_PAGE_PAGINATOR)\n page_number = request.GET.get('page')\n return paginator.get_page(page_number)\n\n\ndef index(request):\n posts = Post.objects.select_related('group')\n context = {\n 'page_obj': paginator(request, posts)\n }\n return render(request, 'posts/index.html', context)\n\n\ndef group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n posts = group.post.all()\n context = {\n 'page_obj': paginator(request, posts),\n 'group': group\n }\n return render(request, 'posts/group_list.html', context)\n\n\ndef profile(request, username):\n author = get_object_or_404(User, username=username)\n posts = author.posts.all()\n\n following = Follow.objects.filter(author=author).exists()\n context = {'author': author,\n 'page_obj': paginator(request, posts),\n 'posts': posts,\n 'following': following\n }\n return render(request, 'posts/profile.html', context)\n\n\ndef post_detail(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n form = CommentForm()\n comment = Comment.objects.filter(post=post)\n context = {\n 'posts': post,\n 'form': form,\n 'comments': comment\n }\n return render(request, 'posts/post_detail.html', context)\n\n\n@login_required\ndef post_create(request):\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n return redirect('posts:profile', request.user)\n\n context = {\n 'form': form,\n }\n return render(request, 'posts/create_post.html', context)\n\n\n@login_required\ndef post_edit(request, post_id):\n post = Post.objects.get(pk=post_id)\n is_edit = True\n if post.author != request.user:\n return redirect('posts:post_detail', post_id=post_id)\n\n form = PostForm(\n request.POST or None,\n files=request.FILES or None,\n instance=post\n )\n\n if form.is_valid():\n post.save()\n return redirect('posts:post_detail', post_id=post.id)\n\n context = {\n 'form': form,\n 'is_edit': is_edit\n }\n return render(request, 'posts/create_post.html', context)\n\n\n@login_required\ndef add_comment(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n form = CommentForm(request.POST or None)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.post = post\n comment.save()\n return redirect('posts:post_detail', post_id=post_id)\n\n\n# posts/views.py\n\n@login_required\ndef follow_index(request):\n posts = Post.objects.select_related(\n 'group'\n ).filter(author__following__user=request.user)\n\n context = {\n 'posts': posts,\n 'page_obj': paginator(request, posts),\n }\n return render(request, 'posts/follow.html', context)\n\n\n@login_required\ndef profile_follow(request, username):\n author = get_object_or_404(User, username=username)\n if request.user != author:\n Follow.objects.get_or_create(\n user=request.user,\n author=author\n )\n return redirect('posts:profile', username=username)\n\n\n@login_required\ndef profile_unfollow(request, username):\n author = get_object_or_404(User, username=username)\n # Дизлайк, отписка\n Follow.objects.filter(author=author, user=request.user).delete()\n return redirect('posts:profile', username=username)\n","repo_name":"korshikovvital/hw05_final","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"}
+{"seq_id":"11936451140","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 9 20:40:06 2023\n\n@author: Martin\n\"\"\"\n\n## 1. Keeps the original top 5 Exchanges by Volume\n## 2. Takes the next 5 based Top Rank by TradingPair\n\nimport requests\nimport json\nimport numpy as np\nfrom datetime import datetime\nimport config\nfrom config import SETTINGS\nimport os\nstaging_folder = config.SETTINGS['staging_folder']\n\n# Date Value\ndate = datetime.now().strftime(\"%Y%m%d\")\n\npayload={}\nheaders = {}\n\n### Coin Market Function\ndef coin_markets():\n # Request market data\n url = \"https://api.coincap.io/v2/markets\"\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n \n # Request the data output\n info = json.loads(response.text)[\"data\"]\n \n # Create a List for Columns and Values\n market_data = []\n \n # Create List for Columns\n market_columns = []\n \n # Retrieve Field Names\n for column_names in info[0]:\n market_columns.append(column_names)\n \n # Append to Full List\n market_data.append(market_columns)\n \n # Retrieve all information for each grouping\n x = 0\n while x < len(info):\n market_values = []\n for columns in market_columns:\n market_values.append(info[x][columns])\n x += 1\n market_data.append(market_values) \n \n # When Function is called, return the Full List with Column and Values \n return market_data\n\n### Coin Assets Function\ndef coin_assets():\n # Request market APIS\n url = \"https://api.coincap.io/v2/assets\"\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n \n # Request the data output\n info2 = json.loads(response.text)[\"data\"]\n \n # Create a List for Columns and Values \n assets_data = []\n \n # Create List for Columns\n assets_columns = []\n \n # Retrieve Field Names\n for column_names in info2[0]:\n assets_columns.append(column_names)\n \n # Append to Full List \n assets_data.append(assets_columns)\n \n # Retrieve all information for each grouping\n x1 = 0\n while x1 < len(info2):\n assets_values = []\n for columns in assets_columns:\n assets_values.append(info2[x1][columns])\n x1 += 1\n assets_data.append(assets_values) \n \n # When Function is called, return the Full List with Column and Values \n return assets_data\n\ndef coin_exchanges():\n # Request market APIS\n url = \"https://api.coincap.io/v2/exchanges\"\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n \n # Request the data output \n info3 = json.loads(response.text)[\"data\"]\n\n # Create a List for Columns and Values \n exchanges_data = []\n\n # Create List for Columns\n exchanges_columns = []\n \n # Retrieve Field Names \n for column_names in info3[0]:\n exchanges_columns.append(column_names)\n \n # Append to Full List \n exchanges_data.append(exchanges_columns)\n \n # Retrieve all information for each grouping\n x2 = 0\n while x2 < len(info3):\n exchanges_values = []\n for columns in exchanges_columns:\n exchanges_values.append(info3[x2][columns])\n x2 += 1\n exchanges_data.append(exchanges_values) \n \n # When Function is called, return the Full List with Column and Values\n return exchanges_data\n\n# Assigns output to variables\n# In this case, returns lists to deisgnated variables\ncoin_market = coin_markets()\ncoin_assets = coin_assets()\ncoin_exchanges = coin_exchanges()\n \n\n\n# Save Files\nnp.savetxt(staging_folder+f\"\\coin_markets_{date}.csv\",coin_market, delimiter =\", \", fmt ='% s')\n#np.savetxt(f\"C:\\dev\\csdev\\coin_assets_info1_{date}.csv\",coin_market, delimiter =\", \", fmt ='% s')\nnp.savetxt(staging_folder+f\"\\coin_assets_{date}.csv\",coin_assets, delimiter =\", \", fmt ='% s')\nnp.savetxt(staging_folder+f\"\\coin_exchanges_{date}.csv\",coin_exchanges,delimiter =\", \", fmt ='% s')\n\n","repo_name":"0devs-do/executive-query-engine","sub_path":"api-data-extraction/CCApiExtractFull.py","file_name":"CCApiExtractFull.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"19362126286","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nData collection from FinnHub.\n\"\"\"\n\nimport finnhub as fh\nimport pandas as pd\nfrom datetime import datetime\nfrom datetime import timezone\nimport time\n\nfinnhub_client = fh.Client(api_key=\"br4je57rh5r8ufeothr0\")\n\n# Helper functions\ndef DateToUnix(date):\n return int(date.replace(tzinfo=timezone.utc).timestamp())\n \ndef FlattenStatementDF(statement_df):\n list_of_dict = list(statement_df.financials)\n return pd.DataFrame(list_of_dict)\n\ndef MergeStatementDF(statement_df_list):\n output = statement_df_list[0].merge(statement_df_list[1],on=\"period\")\n output = output.merge(statement_df_list[2],on=\"period\")\n output = output.set_index('period')\n return output\n\ndef SaveOutput(filename_prefix,**kwargs):\n for df_name, df in kwargs.items():\n filename = filename_prefix + '_' + df_name + '.csv'\n df.to_csv(filename)\n\ndef FinnHubCode(ticker,market):\n return ticker + '.' + market\n\ndef GetFailedCompanies(failed_ticker_list,ticker_company_table,reason_failed):\n print(\"Couldn't get\",reason_failed,\"data for\",len(failed_ticker_list),\"companies.\")\n output = pd.DataFrame(columns=['ticker','company','reason_failed'])\n for ticker in failed_ticker_list:\n company = ticker_company_table.company.loc[ticker_company_table.finnhub == ticker]\n row = {'ticker':ticker,'company':company,'reason_failed':reason_failed}\n output = output.append(row,ignore_index=True)\n return output\n \n# FinnHub API functions\ndef GetPrice(client,ticker,start_unix,end_unix):\n candles = client.stock_candles(ticker, 'D', start_unix, end_unix)\n if candles['s'] == 'no_data':\n print(\"Could not find price data for\",ticker)\n return None\n else:\n return pd.DataFrame(candles)\n\ndef GetFinancials(client,ticker,frequency,backtest_start_date):\n def _GetRelevantStatementIndex_(statement_df,backtest_start_date):\n # Flag if date of statement is within backtesting period\n def CheckDate(date_to_check,date_window):\n date_to_check = datetime.strptime(date_to_check, '%Y-%m-%d')\n return date_to_check >= date_window\n \n index = 0\n while index < len(statement_df):\n statement_date = statement_df.iloc[index][0]['period']\n if CheckDate(statement_date,backtest_start_date):\n index += 1\n else:\n return index + 1 # Include first statement out of period\n return index\n \n statement_type_list = ['bs','ic','cf']\n statement_df_list = []\n for statement_type in statement_type_list:\n statement_data_full = client.financials(ticker,statement_type,frequency)\n if statement_data_full['financials'] is None:\n print(\"Could not find financial data for\",ticker)\n return None\n else:\n statement_data_full = pd.DataFrame(statement_data_full)\n statement_relevant_index = _GetRelevantStatementIndex_(statement_data_full,backtest_start_date)\n statement_data_relevant = statement_data_full.iloc[:statement_relevant_index]\n statement_df_list.append(FlattenStatementDF(statement_data_relevant))\n return MergeStatementDF(statement_df_list)\n \n\n# Backtest parameters\nstart_date = datetime(2019,7,1) # 6 months prior to Covid-19\nend_date = datetime(2020,8,7)\n\n# Calculate UNIX Timestamps\n\"\"\"\nAs UNIX timestamps are for midnight, the end_unix will give prices for day BEFORE end_date\n\"\"\"\nstart_unix = DateToUnix(start_date)\nend_unix = DateToUnix(end_date)\n\n# Load finnhub codes for multiple investment universes\nhong_kong = pd.read_excel('investment_universe.xlsx',sheet_name=\"HK\")\nunited_kingdom = pd.read_excel('investment_universe.xlsx',sheet_name=\"GB\")\ndenmark = pd.read_excel('investment_universe.xlsx',sheet_name=\"DK\")\nitaly = pd.read_excel('investment_universe.xlsx',sheet_name=\"IT\")\nunited_states = pd.read_excel('investment_universe.xlsx',sheet_name=\"US\")\n\n# Group by country\nmarkets = {}\nmarkets[\"HK\"] = hong_kong\nmarkets[\"L\"] = united_kingdom\nmarkets[\"CO\"] = denmark\nmarkets[\"MI\"] = italy\nmarkets[\"US\"] = united_states\n\n# Get price data for investment universe\nmaster_price_data = pd.DataFrame(columns=['c', 'h', 'l', 'o', 's', 't', 'v','ticker','market'])\nmaster_financial_data = pd.DataFrame()\nfailed_company_data = pd.DataFrame(columns=['ticker','company','reason_failed'])\n\nfor market, universe in markets.items():\n ticker_no_price_data = [] # Reconciliation\n ticker_no_financial_data = [] # Reconciliation\n \n # ## Debug\n # if market == 'HK'or market == 'L' or market == 'CO' or market == 'MI': # \n # continue\n # ##\n \n # Get list of stocks\n ticker_list = list(universe.finnhub)\n print(\"\\n\\nExtracting data for\",market,\"\\n\\n\")\n for ticker in ticker_list:\n # Get price data\n print(\"Extracting\",ticker,\"price\")\n stock_price_data = GetPrice(finnhub_client,ticker,start_unix,end_unix)\n if stock_price_data is not None:\n stock_price_data['ticker'] = ticker\n stock_price_data['market'] = market\n # Add to master data DF\n master_price_data = master_price_data.append(stock_price_data)\n else:\n ticker_no_price_data.append(ticker)\n \n # Get financial statement data\n print(\"Extracting\",ticker,\"financials\")\n stock_financial_data = GetFinancials(finnhub_client,ticker,'quarterly',start_date)\n if stock_financial_data is not None:\n stock_financial_data['ticker'] = ticker\n stock_financial_data['market'] = market\n # Add to master data DF\n master_financial_data = master_financial_data.append(stock_financial_data)\n else:\n ticker_no_financial_data.append(ticker)\n \n # Sleep every 10 tickers to avoid timeout\n if (ticker_list.index(ticker)+1) % 10 == 0:\n completion_percent = ((ticker_list.index(ticker)+1) / len(ticker_list))*100\n print(\"\\n\",str(completion_percent),\"% complete\\n\")\n time.sleep(60)\n \n # Save companies that failed to download for price and financials\n failed_company_data = failed_company_data.append(GetFailedCompanies(ticker_no_price_data,universe,\"price\"))\n failed_company_data = failed_company_data.append(GetFailedCompanies(ticker_no_financial_data,universe,\"financials\"))\n SaveOutput(market,failed_company_data = failed_company_data)\n \n \n # Save price data as excel\n print(\"\\n\\nSaving Checkpoint...\")\n filename = 'checkpoint_' + market\n SaveOutput(filename,\n price_data = master_price_data,\n financial_data = master_financial_data)\n time.sleep(60)\n \n# Save price data as excel\nprint(\"\\n\\nSaving data...\")\nSaveOutput('master',\n price_data = master_price_data,\n financial_data = master_financial_data)\n","repo_name":"SJDunkelman/applied-project-msc","sub_path":"Data/market_data/finnhub_data_extract.py","file_name":"finnhub_data_extract.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"3155693900","text":"class Solution:\n def groupAnagrams(self, strs: list[str]) -> list[list[str]]:\n biggerAngList = []\n angDict = dict()\n for i in strs:\n t = \"\".join(sorted(i))\n if t in angDict:\n # if i not in angDict[t]:\n angDict[t].append(i)\n else:\n angDict[t] = [i]\n for value in angDict.values():\n biggerAngList.append(value)\n return biggerAngList","repo_name":"mduruji/Blind_75","sub_path":"Arrays_&_Hashing/groupAnagram.py","file_name":"groupAnagram.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"9392429373","text":"import json\nimport os\nimport sys\nimport unittest\n\nimport mox\n\ncwd = os.getcwd()\nos.chdir(\"..\")\nsys.path.append(os.getcwd())\nfrom smartagent import SmartAgent\nfrom smartagent_messaging import MessagingService\nfrom check_mysql_status import MySqlChecker\nfrom command_handler import MysqlCommandHandler\nos.chdir(cwd)\n\n\nclass SmartAgentUnitTest(unittest.TestCase):\n\n def setUp (self):\n self.mox = mox.Mox()\n self.mock_msg_service = self.mox.CreateMock(MessagingService)\n self.agent = SmartAgent(self.mock_msg_service)\n\n def test_unsupported_method(self):\n \"\"\"Test to see that a message with an unsupported method generates\n the correct response.\"\"\"\n\n message = r'''{\"method\": \"unsupported\"}'''\n result = self.agent.process_message(msg=json.loads(message))\n self.mox.ReplayAll()\n\n self.assertEqual(result, {'failure': 'unsupported_method', 'result': None})\n self.mox.VerifyAll()\n\n def test_missing_method(self):\n \"\"\"Test to see that a missing method key generates an error.\"\"\"\n\n message = r'''{\"not_method\": \"test\"}'''\n result = self.agent.process_message(msg=json.loads(message))\n self.mox.ReplayAll()\n\n self.assertEqual(result, {'failure': 'missing_method', 'result': None})\n self.mox.VerifyAll()\n\n def test_check_mysql_status_running(self):\n \"\"\"Test to see that the correct response is returned when a MySQL\n server is running.\"\"\"\n\n self.agent.checker = self.mox.CreateMock(MySqlChecker)\n self.mox.StubOutWithMock(self.agent.checker, \"check_if_running\")\n self.agent.checker.check_if_running(number_of_checks=5,\n sleep_time_seconds=3).AndReturn(True)\n self.mox.ReplayAll()\n\n result = self.agent.check_status()\n self.assertEqual(result, 1)\n self.mox.VerifyAll()\n\n def test_check_mysql_status_not_running(self):\n \"\"\"Test to see that the correct response is returned when a MySQL\n server is not running.\"\"\"\n\n self.agent.checker = self.mox.CreateMock(MySqlChecker)\n self.mox.StubOutWithMock(self.agent.checker, \"check_if_running\")\n self.agent.checker.check_if_running(number_of_checks=5,\n sleep_time_seconds=3).AndReturn(False)\n self.mox.ReplayAll()\n\n result = self.agent.check_status()\n self.assertEqual(result, 0)\n self.mox.VerifyAll()\n\n def test_create_database(self):\n \"\"\"Test to see that the correct response is returned from a create\n database operation.\"\"\"\n\n msg = json.loads(r\"\"\"{\"args\": {\"database\": \"test\"}}\"\"\")\n self.agent.handler = self.mox.CreateMock(MysqlCommandHandler)\n self.mox.StubOutWithMock(self.agent.handler, \"create_database\")\n self.agent.handler.create_database(msg['args']['database']).AndReturn(\"SUCCESS\")\n self.mox.ReplayAll()\n\n result = self.agent.create_database(msg)\n self.assertEqual(result, \"SUCCESS\")\n self.mox.VerifyAll()\n\n\n\n def tearDown(self):\n self.mox.UnsetStubs()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"CaptTofu/reddwarf","sub_path":"smartagent/tests/test_smart_agent.py","file_name":"test_smart_agent.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"}
+{"seq_id":"4242088063","text":"from bitcoinaddress import Wallet\nimport requests\nimport json\nimport time\n\ncounter = 0\ndef getRich():\n wallet = Wallet()\n wa = str(wallet)\n wa1 = wa.splitlines(False)\n wal1 = str(wa1[13])\n wal2 = wal1.split(sep=\":\")\n qaddr = wal2[-1]\n qaddr1 = qaddr.split(sep=\" \")\n qwerywallet = str(qaddr1[1])\n print(qwerywallet)\n\n url = \"https://blockchain.info/rawaddr/\"+qwerywallet\n btc_addr = requests.get(url)\n dict_addr = json.loads(btc_addr.text)\n balance = dict_addr.get(\"final_balance\")\n\n if balance != \"\":\n datei = \"wallet\"+str(counter)+\".txt\"\n dat = open(datei, \"wt\")\n dat.write(wa)\n dat.close()\n else:\n counter +1\n print(counter)\n time.sleep(15) \n # nicht unter 11 Secunden da sonst die Anfragen von der IP geblockt werden\n getRich()\ngetRich()","repo_name":"mfgich/walletfinder","sub_path":"wallet_gen.py","file_name":"wallet_gen.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"4971952370","text":"from .text import Text\n\n\nclass Link(Text):\n\n def __init__(self, link: str, text: str,\n name='', priority=1,\n x1=0, y1=0,\n x2=0, y2=0,\n background='', foreground='', **kwargs):\n super(Link, self).__init__(name=name, priority=priority,\n x1=x1, y1=y1,\n x2=x2, y2=y2,\n background=background, foreground=foreground)\n self.setTextPropierties(**kwargs)\n\n self.setText(text)\n self.link = link\n\n def render(self, pdf):\n if pdf.text_color is not self.rgb(self.foreground):\n pdf.set_text_color(*self.rgb(self.foreground))\n self.font = self.font.strip().lower()\n if self.font == 'arial black':\n self.font = 'arial'\n style = \"\"\n for tag in 'B', 'I', 'U':\n if self.text.startswith(\"<%s>\" % tag) and self.text.endswith(\"%s>\" % tag):\n self.text = self.text[3:-4]\n style += tag\n if self.bold:\n style += \"B\"\n if self.italic:\n style += \"I\"\n if self.underline:\n style += \"U\"\n pdf.set_font(self.font, style, self.size)\n # m_k = 72 / 2.54\n # h = (size/m_k)\n\n pdf.set_xy(self.pointUp[0], self.pointUp[1])\n pdf.write(5, self.text, self.link)","repo_name":"inprojectspl/pyfpdf","sub_path":"fpdf/Elements/link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"764181825","text":"import plotly.express as px\r\nimport pandas as pd\r\nimport streamlit as st\r\n\r\n\r\ndef main():\r\n st.title(\"Jadual Sifir\")\r\n\r\n choice = st.sidebar.selectbox('Menu', ['Home', 'Tentang'])\r\n if choice == 'Home':\r\n st.subheader('Home')\r\n\r\n # Layout \r\n col1, col2 = st.columns([1,2])\r\n\r\n with col1:\r\n with st.form(key = 'myform'):\r\n number = st.text_input('Enter Number')\r\n end_number = st.number_input('End Number', min_value=12, max_value=200)\r\n submit_button = st.form_submit_button(label='Submit')\r\n\r\n if submit_button:\r\n with col2:\r\n with st.expander('Times Table'):\r\n for i in range(1, (end_number + 1)):\r\n answer = i * int(number)\r\n st.write(f\"{i} x {number} = {answer}\")\r\n \r\n # Times Table as DataFrame\r\n range_num = list(range(1, end_number))\r\n multiplication = [f\"{i} x {number} = \" for i in range(1, end_number)]\r\n answer = [i * int(number) for i in range(1, end_number)]\r\n df = pd.DataFrame({'Numbers' : range_num, 'Multiplication' : multiplication, 'Answer' : answer})\r\n st.dataframe(df)\r\n\r\n # Plot\r\n p1 = px.bar(df, x = 'Numbers' , y = 'Answer', color = 'Numbers')\r\n st.plotly_chart(p1)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"NizarMazlan/python-mini-project","sub_path":"streamlit/sifir.py","file_name":"sifir.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"4998551174","text":"#!/usr/bin/env python3\n\n############################################################################################\n# #\n# Program purpose: Obtain (print) unique values from a dictionary. #\n# Program Author : Happi Yvan #\n# Creation Date : December 10, 2019 #\n# #\n############################################################################################\n\nimport random\n\ndef get_random_dict(low: int, high: int, size: int) -> dict:\n if size < 0:\n raise ValueError('Invalid size for new dictionary. Must be > 0')\n rand_keys = [random.randint(low, high) for _ in range(size)]\n rand_values = [random.randint(low, high) for _ in range(size)]\n\n return {k: v for (k, v) in zip(rand_keys, rand_values)}\n\ndef dict_empty(some_dict: dict) -> bool:\n return len(some_dict.keys()) == 0\n\ndef get_unique_values(some_dict: dict) -> list:\n if dict_empty(some_dict=some_dict):\n return []\n unique_values = []\n for val in some_dict.values():\n if val not in unique_values:\n unique_values.append(val)\n\n return unique_values\n\ndef get_unique_values_from_dicts_list(list_of_dicts: list) -> list:\n lists_of_uniques = []\n for sub_dict in list_of_dicts:\n if not dict_empty(some_dict=sub_dict):\n lists_of_uniques.append(get_unique_values(some_dict=sub_dict))\n return lists_of_uniques\n\nif __name__ == \"__main__\":\n\n new_dict = get_random_dict(low=0, high=20, size=10)\n print(f' New dictionary is: {new_dict}')\n print(f'Original values are: {list(new_dict.values())}')\n print(f' Unique values are: {get_unique_values(some_dict=new_dict)}')\n\n print()\n print('-' * 15, ' [New Operations] ', '-' * 15)\n\n dicts_list = [\n get_random_dict(low=0, high=10, size=10),\n get_random_dict(low=0, high=10, size=10),\n get_random_dict(low=0, high=10, size=10),\n ]\n print(f'List of dictionaries: {dicts_list}')\n print(f'List of uniques: {get_unique_values_from_dicts_list(list_of_dicts=dicts_list)}')","repo_name":"ivenpoker/Python-Projects","sub_path":"Projects/Online Workouts/w3resource/Dictionary/program-20.py","file_name":"program-20.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42540858210","text":"# Token creates tokens for different characters in user input\r\n# Different token types include number, operation, expression, unexpected\r\n# Different tokens will have a token type and a value associated with it\r\n\r\nimport enum\r\n\r\nclass Token:\r\n def __init__(self, token_type, value) -> None:\r\n self.token_type = token_type\r\n self.value = value\r\n \r\n def is_arithmetic_operation(self):\r\n OPERATIONS = '+-*/'\r\n if self.value in OPERATIONS:\r\n return True\r\n else:\r\n return False\r\n\r\nclass TokenType(enum):\r\n NUMBER = 'number'\r\n OPERATION = 'operation'\r\n EXPRESSION = 'expression'\r\n UNEXPECTED = 'unexpected'\r\n\r\n# parses user input into different tokens\r\nclass Tokenizer:\r\n NUMBERS = '1234567890'\r\n \r\n tokens = [] # possible user input tokens\r\n\r\n # pass user input and set current character and current position\r\n def __init__(self, text) -> None:\r\n self.text = text\r\n self.current_pos = -1\r\n self.current_char = '\\0'\r\n self.advance()\r\n \r\n # proceeds to next character in input\r\n def advance(self) -> None:\r\n self.current_pos += 1\r\n if self.current_pos < len(self.text): # if there is still character left, advance to next character in input\r\n self.current_char = self.text.index(self.current_pos) # get the character at the current position (index)\r\n\r\n # simplifies down one expression at a time according to PEMDAS\r\n def simplify(input):\r\n if '(' in input: # input still has ()\r\n pass\r\n else:\r\n pass\r\n\r\n def make_tokens(self):\r\n OPERATIONS = '+-*/'\r\n\r\n if self.current_char == ' ': # skip spaces\r\n self.advance()\r\n elif self.current_char in self.NUMBERS: # if the current character is a number\r\n self.tokens.append(self.make_number())\r\n self.advance()\r\n elif self.current_char in OPERATIONS: # if the current character is an operation\r\n self.tokens.append(Token(TokenType.OPERATION, self.current_char))\r\n self.advance()\r\n elif self.current_char == '(': # push until ')' is met\r\n unedited = self.text[self.current_position] # slicing operation\r\n # cut off expression into 2 from beginning to this point, pass in ()\r\n self.simplify(self.text[self.current_postion+1:len(self.text)+1]) # slicing string from 1 after start of ( to end of string\r\n self.make_expression()\r\n \r\n\r\n # continues building a number until terminating character reached\r\n def make_number(self):\r\n number = ' '\r\n while self.current_char in self.NUMBERS and self.current_char != '\\0': # while there is still a number\r\n number += self.current_char\r\n return Token(TokenType.NUMBER, number)\r\n \r\n # finish ?\r\n def make_expression(self):\r\n while self.curr_char != ')':\r\n return","repo_name":"smtono/python-calculator","sub_path":"token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"4022468450","text":"from programme.joueur.joueur import Joueur\nfrom programme.utile.ConfirmRetour import confirmRetour\nfrom programme.utile.colorfull import textcolor\nfrom programme.utile.mrPropre import mrPropre\nfrom programme.utile.saisieNombre import saisieInt\nfrom programme.utile.score import incrementScore\n\n\ndef afficherPlateau(plateau: list[list[str]]):\n \"\"\"Affiche le plateau de jeu du Puissance 4\n\n Args:\n plateau (list[list[str]]): Plateau de Jeu\n \"\"\"\n print(\" 1 2 3 4 5 6 7\")\n for ligne in plateau:\n print(\"|\", end=\"\")\n for case in ligne:\n print(case, end=\"|\")\n print()\n print()\n\n\ndef saisirColonne() -> int:\n \"\"\"\nSaisie d'une colonne\n\n Returns:\n int: Colonne saisie\n \"\"\"\n colonne: int = saisieInt(\"Choisissez une colonne : \")\n while colonne < 1 or colonne > 7:\n print(\"Colonne invalide\")\n colonne = saisieInt(\"Choisissez une colonne : \")\n return colonne - 1\n\n\ndef placerPion(plateau: list[list[str]], pion: str):\n \"\"\"Place un pion dans la colonne donnée\n\n Args:\n plateau (list[list[str]]): Plateau\n pion (str): Chaine affichée en tant que pion\n \"\"\"\n i: int = 5\n colonne: int = saisirColonne()\n\n while plateau[i][colonne] != \" \": # Tant que la case est occupée\n i -= 1\n if i == -1:\n print(\"Colonne pleine\")\n colonne = saisirColonne()\n i = 5\n if colonne < 0 or colonne > 6:\n print(\"Colonne invalide\")\n colonne = saisirColonne()\n i = 5\n\n plateau[i][colonne] = pion\n\n\ndef pionAligne(plateau: list[list[str]], pion: str) -> bool:\n \"\"\"Vérifie si un pion est aligné\n\n Args:\n plateau (list[list[str]]): Plateau de Jeu\n pion (str): Chaine affichée en tant que pion\n\n Returns:\n bool: Vrai si le pion est aligné\n \"\"\"\n # Vérification horizontale\n for ligne in plateau:\n for i in range(4):\n if ligne[i] == pion and ligne[i + 1] == pion and ligne[i + 2] == pion and ligne[i + 3] == pion:\n return True\n\n # Vérification verticale\n for j in range(7):\n for i in range(3):\n if plateau[i][j] == pion and plateau[i + 1][j] == pion and plateau[i + 2][j] == pion \\\n and plateau[i + 3][j] == pion:\n return True\n\n # Vérifications diagonales\n for i in range(3):\n for j in range(4):\n if plateau[i][j] == pion and plateau[i + 1][j + 1] == pion and plateau[i + 2][j + 2] == pion and \\\n plateau[i + 3][j + 3] == pion:\n return True\n\n for i in range(3):\n for j in range(3, 7):\n if plateau[i][j] == pion and plateau[i + 1][j - 1] == pion and plateau[i + 2][j - 2] == pion and \\\n plateau[i + 3][j - 3] == pion:\n return True\n\n return False\n\n\ndef plateauPlein(plateau: list[list[str]]) -> bool:\n \"\"\"Vérifie si le plateau est plein\n\n Args:\n plateau (list[list[str]]): Plateau de jeu\n\n Returns:\n bool: Vrai si le plateau est plein\n \"\"\"\n for ligne in plateau:\n for case in ligne:\n if case == \" \":\n return False\n return True\n\n\ndef tourPuissance4(joueur1: Joueur, joueur2: Joueur):\n \"\"\"Joue une partie de puissance 4 entre deux joueurs\n\n Args:\n joueur1 (Joueur): Joueur 1\n joueur2 (Joueur): Joueur 2\n \"\"\"\n\n plateau: list[list[str]] = [[\" \" for _ in range(7)] for _ in range(6)] #Taille de 7*6 \n pionJ: str = textcolor.YELLOW + 'O' + textcolor.DEFAULT\n pionR: str = textcolor.RED + 'O' + textcolor.DEFAULT\n aligne: bool = False\n\n mrPropre()\n print(joueur1.pseudo, \"joueur avec les\", pionJ) #On indique à chaue joueur ses pions\n print(joueur2.pseudo, \"joueur avec les\", pionR)\n\n afficherPlateau(plateau)\n\n while not aligne and not plateauPlein(plateau): #On joue tant qu'il n'y a ni égalité ni victoire\n print(joueur1.pseudo + \", joue !\")\n placerPion(plateau, pionJ)\n mrPropre()\n afficherPlateau(plateau)\n aligne = pionAligne(plateau, pionJ)\n if aligne:\n print(textcolor.GREEN + \"Le joueur \" +\n joueur1.pseudo + \" a gagné !\" + textcolor.DEFAULT + \"\\n\")\n incrementScore(joueur1, \"puissance 4\")\n if plateauPlein(plateau) or aligne:\n break\n\n print(joueur2.pseudo + \", joue !\")\n placerPion(plateau, pionR)\n mrPropre()\n afficherPlateau(plateau)\n aligne = pionAligne(plateau, pionR)\n if aligne:\n print(textcolor.GREEN + \"Le joueur \" +\n joueur2.pseudo + \" a gagné !\" + textcolor.DEFAULT + \"\\n\")\n incrementScore(joueur2, \"puissance 4\")\n\n if plateauPlein(plateau):\n print(textcolor.CYAN + \"Match nul !\" + textcolor.DEFAULT + \"\\n\")\n\n confirmRetour()\n","repo_name":"delmat238/S1.01","sub_path":"programme/puissance4/fonctionPuissance4.py","file_name":"fonctionPuissance4.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"35033711119","text":"import os\n\nimport argparse\n\nimport input_generation.matrix_generation\nimport input_generation.docter_argument_generation\n\nimport running_utils\n\nfrom config import DATA_DIR, TF_NAME, PT_NAME, NUM_OF_ARGS, NUM_OF_INPUT\n\nARGS_DONE_COLS = ['lib', 'version', 'api']\nARGS_DONE_FILE = \"args_gen_done.csv\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"lib\", choices=['tensorflow', 'pytorch'])\n parser.add_argument(\"version\", type=str)\n args = parser.parse_args()\n config = vars(args)\n\n lib = config['lib']\n version = config['version']\n\n src_dir = os.path.join(os.getcwd(), '..')\n # address for generated inputs\n out_dir = os.path.join(DATA_DIR, \"generated_input\")\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n # create a done file if it doesn't exist\n args_done_set, args_done_out_f = running_utils.setup_done_file(out_dir, ARGS_DONE_FILE, ARGS_DONE_COLS)\n args_done_out_f.close()\n\n # load list of APIs to generate inputs for\n tf_api_list = running_utils.load_list(os.path.join('input_generation', 'input_gen_tensorflow_api_list.txt'))\n pt_api_list = running_utils.load_list(os.path.join('input_generation', 'input_gen_pytorch_api_list.txt'))\n\n apis_map = {\n TF_NAME: tf_api_list,\n PT_NAME: pt_api_list\n }\n\n # generate inputs for each API\n for api in apis_map[lib]:\n if (lib, version, api) not in args_done_set:\n print(\"Generating args for %s %s %s\" % (lib, version, api))\n\n args_gen_time = input_generation.docter_argument_generation.generate_single_api_argument(\n out_dir, src_dir, lib, version, api, NUM_OF_ARGS)\n conf = {\n 'lib': lib,\n 'version': version,\n 'api': api\n }\n\n running_utils.write_done(conf, args_gen_time, out_dir, ARGS_DONE_FILE, ARGS_DONE_COLS)\n\n # generating 4D matrix inputs\n if not os.path.exists(os.path.join(out_dir, 'input')):\n print(\"Generating 4D input\")\n input_generation.matrix_generation.generate_single_api_input(out_dir, NUM_OF_INPUT)\n \n if lib == TF_NAME:\n from gen_tf_model_input import save_model_and_inputs\n else:\n from gen_pt_model_input import save_model_and_inputs\n save_model_and_inputs()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lin-tan/eagle","sub_path":"EAGLE/generate_all_input.py","file_name":"generate_all_input.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"}
+{"seq_id":"12083142225","text":"\nimport time\n\nfrom .response import AncillaResponse, AncillaError\nfrom .request import BaseRequest\nfrom .router import Route, Router, lazy_attribute, RouterError, getargspec\n\nfrom ..utils.dict import DictProperty, ConfigDict\n\nfrom ..utils import makelist, cached_property, yields, call_maybe_yield\n\nimport sys\nimport io, base64, cgi, email.utils, functools, hmac, imp, itertools,\\\n os, re, tempfile, time, warnings\n\n\n\nDEBUG = False\n\n\ndef load(target, **namespace):\n \"\"\" Import a module or fetch an object from a module.\n\n * ``package.module`` returns `module` as a module object.\n * ``pack.mod:name`` returns the module variable `name` from `pack.mod`.\n * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.\n\n The last form accepts not only function calls, but any type of\n expression. Keyword arguments passed to this function are available as\n local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``\n \"\"\"\n module, target = target.split(\":\", 1) if ':' in target else (target, None)\n if module not in sys.modules: __import__(module)\n if not target: return sys.modules[module]\n if target.isalnum(): return getattr(sys.modules[module], target)\n package_name = module.split('.')[0]\n namespace[package_name] = sys.modules[package_name]\n return eval('%s.%s' % (module, target), namespace)\n\n\n\n\nclass WSGIFileWrapper(object):\n def __init__(self, fp, buffer_size=1024 * 64):\n self.fp, self.buffer_size = fp, buffer_size\n for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'):\n if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))\n\n # def __iter__(self):\n # buff, read = self.buffer_size, self.read\n # while True:\n # part = read(buff)\n # if not part: return\n # yield part\n\n def __aiter__(self):\n return self\n\n async def __anext__(self):\n data = await self.fetch_data()\n if data is not None:\n return data\n else:\n raise StopAsyncIteration\n\n async def fetch_data(self):\n buff, read = self.buffer_size, self.read\n part = read(buff)\n if not part: \n if hasattr(self, \"close\"): self.close()\n return None\n return part\n \n # return part\n # while not self.queue.empty():\n # self.done.append(self.queue.get_nowait())\n # if not self.done:\n # return None\n # return self.done.pop(0)\n\n\n# request = LocalRequest()\n\ndef yieldroutes(func):\n \"\"\" Return a generator for routes that match the signature (name, args)\n of the func parameter. This may yield more than one route if the function\n takes optional keyword arguments. The output is best described by example::\n\n a() -> '/a'\n b(x, y) -> '/b//'\n c(x, y=5) -> '/c/' and '/c//'\n d(x=5, y=6) -> '/d' and '/d/' and '/d//'\n \"\"\"\n path = '/' + func.__name__.replace('__', '/').lstrip('/')\n spec = getargspec(func)\n argc = len(spec[0]) - len(spec[3] or [])\n path += ('/<%s>' * argc) % tuple(spec[0][:argc])\n yield path\n for arg in spec[0][argc:]:\n path += '/<%s>' % arg\n yield path\n\ndef path_shift(script_name, path_info, shift=1):\n \"\"\" Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.\n\n :return: The modified paths.\n :param script_name: The SCRIPT_NAME path.\n :param script_name: The PATH_INFO path.\n :param shift: The number of path fragments to shift. May be negative to\n change the shift direction. (default: 1)\n \"\"\"\n if shift == 0: return script_name, path_info\n pathlist = path_info.strip('/').split('/')\n scriptlist = script_name.strip('/').split('/')\n if pathlist and pathlist[0] == '': pathlist = []\n if scriptlist and scriptlist[0] == '': scriptlist = []\n if 0 < shift <= len(pathlist):\n moved = pathlist[:shift]\n scriptlist = scriptlist + moved\n pathlist = pathlist[shift:]\n elif 0 > shift >= -len(scriptlist):\n moved = scriptlist[shift:]\n pathlist = moved + pathlist\n scriptlist = scriptlist[:shift]\n else:\n empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'\n raise AssertionError(\"Cannot shift. Nothing left from %s\" % empty)\n new_script_name = '/' + '/'.join(scriptlist)\n new_path_info = '/' + '/'.join(pathlist)\n if path_info.endswith('/') and pathlist: new_path_info += '/'\n return new_script_name, new_path_info \n\nclass App(object):\n \"\"\" Each Bottle object represents a single, distinct web application and\n consists of routes, callbacks, plugins, resources and configuration.\n Instances are callable WSGI applications.\n\n :param catchall: If true (default), handle all exceptions. Turn off to\n let debugging middleware handle exceptions.\n \"\"\"\n\n @lazy_attribute\n def _global_config(cls):\n cfg = ConfigDict()\n cfg.meta_set('catchall', 'validate', bool)\n return cfg\n def __init__(self, *args, **kwargs):\n #: A :class:`ConfigDict` for app specific configuration.\n self.config = self._global_config._make_overlay()\n self.config._add_change_listener(\n functools.partial(self.trigger_hook, 'config'))\n\n self.config.update({\n \"catchall\": False\n })\n\n # if kwargs.get('catchall') is False:\n # depr(0, 13, \"Bottle(catchall) keyword argument.\",\n # \"The 'catchall' setting is now part of the app \"\n # \"configuration. Fix: `app.config['catchall'] = False`\")\n # self.config['catchall'] = False\n # if kwargs.get('autojson') is False:\n # depr(0, 13, \"Bottle(autojson) keyword argument.\",\n # \"The 'autojson' setting is now part of the app \"\n # \"configuration. Fix: `app.config['json.enable'] = False`\")\n # self.config['json.disable'] = True\n\n self._mounts = []\n\n #: A :class:`ResourceManager` for application files\n # self.resources = ResourceManager()\n\n self.routes = [] # List of installed :class:`Route` instances.\n self.router = Router() # Maps requests to :class:`Route` instances.\n self.error_handler = {}\n\n # Core plugins\n self.plugins = [] # List of installed plugins.\n # self.install(JSONPlugin())\n # self.install(TemplatePlugin())\n\n #: If true, most exceptions are caught and returned as :exc:`HTTPError`\n catchall = DictProperty('config', 'catchall')\n\n __hook_names = 'before_request', 'after_request', 'app_reset', 'config'\n __hook_reversed = {'after_request'}\n\n @cached_property\n def _hooks(self):\n return dict((name, []) for name in self.__hook_names)\n\n def add_hook(self, name, func):\n \"\"\" Attach a callback to a hook. Three hooks are currently implemented:\n\n before_request\n Executed once before each request. The request context is\n available, but no routing has happened yet.\n after_request\n Executed once after each request regardless of its outcome.\n app_reset\n Called whenever :meth:`Bottle.reset` is called.\n \"\"\"\n if name in self.__hook_reversed:\n self._hooks[name].insert(0, func)\n else:\n self._hooks[name].append(func)\n\n def remove_hook(self, name, func):\n \"\"\" Remove a callback from a hook. \"\"\"\n if name in self._hooks and func in self._hooks[name]:\n self._hooks[name].remove(func)\n return True\n\n def trigger_hook(self, __name, *args, **kwargs):\n \"\"\" Trigger a hook and return a list of results. \"\"\"\n # print(\"INSIDE TRIGGER HOOK\")\n # print(f\"nm: {__name} and args= {args}\", flush=True)\n # print(f\"hooks = {self._hooks}\", flush=True)\n return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]\n\n def hook(self, name):\n \"\"\" Return a decorator that attaches a callback to a hook. See\n :meth:`add_hook` for details.\"\"\"\n\n def decorator(func):\n self.add_hook(name, func)\n return func\n\n return decorator\n\n\n def reset_app(self):\n self.router = Router()\n self.routes = []\n # self.plugins = []\n\n def remount_apps(self, apps):\n self._mounts = []\n for app in apps:\n self._mount_wsgi(app.config['_mount.prefix'], app)\n \n\n def _mount_wsgi(self, prefix, app, **options):\n segments = [p for p in prefix.split('/') if p]\n if not segments:\n raise ValueError('WSGI applications cannot be mounted to \"/\".')\n path_depth = len(segments)\n self._mounts.append(app)\n app.config['_mount.prefix'] = prefix\n app.config['_mount.app'] = self\n\n\n async def mountpoint_wrapper(request, *args, **kwargs):\n try:\n # request.path_shift(path_depth)\n # print(f\"Path dep {path_depth}\", flush=True)\n request.environ[\"PATH\"] = \"/\" + request.path[len(prefix):]\n\n rs = request.response\n\n \n body = await app(request.environ, rs)\n # print(f\"BODY = {body}\", flush=True)\n # print(f'ResponsHeadAFter = {rs.headerlist}', flush=True)\n if isinstance(body, AncillaResponse):\n return body\n else:\n rs.body = body\n return rs\n\n finally:\n pass\n # print(\"mountpoint finall\")\n # request.path_shift(-path_depth)\n\n options.setdefault('skip', True)\n options.setdefault('method', 'PROXY')\n options.setdefault('mountpoint', {'prefix': prefix, 'target': app})\n options['callback'] = mountpoint_wrapper\n\n self.route('/%s/<:re:.*>' % '/'.join(segments), **options)\n # if not prefix.endswith('/'):\n # self.route('/' + '/'.join(segments), **options)\n \n\n def _mount_app(self, prefix, app, **options):\n # if app in self._mounts or '_mount.app' in app.config:\n # depr(0, 13, \"Application mounted multiple times. Falling back to WSGI mount.\",\n # \"Clone application before mounting to a different location.\")\n \n\n # if options:\n # depr(0, 13, \"Unsupported mount options. Falling back to WSGI mount.\",\n # \"Do not specify any route options when mounting bottle application.\")\n # return self._mount_wsgi(prefix, app, **options)\n\n # if not prefix.endswith(\"/\"):\n # depr(0, 13, \"Prefix must end in '/'. Falling back to WSGI mount.\",\n # \"Consider adding an explicit redirect from '/prefix' to '/prefix/' in the parent application.\")\n # return self._mount_wsgi(prefix, app, **options)\n\n self._mounts.append(app)\n app.config['_mount.prefix'] = prefix\n app.config['_mount.app'] = self\n for route in app.routes:\n route.rule = prefix + route.rule.lstrip('/')\n self.add_route(route)\n\n def mount(self, prefix, app, **options):\n \"\"\" Mount an application (:class:`Bottle` or plain WSGI) to a specific\n URL prefix. Example::\n\n parent_app.mount('/prefix/', child_app)\n\n :param prefix: path prefix or `mount-point`.\n :param app: an instance of :class:`Bottle` or a WSGI application.\n\n Plugins from the parent application are not applied to the routes\n of the mounted child application. If you need plugins in the child\n application, install them separately.\n\n While it is possible to use path wildcards within the prefix path\n (:class:`Bottle` childs only), it is highly discouraged.\n\n The prefix path must end with a slash. If you want to access the\n root of the child application via `/prefix` in addition to\n `/prefix/`, consider adding a route with a 307 redirect to the\n parent application.\n \"\"\"\n\n if not prefix.startswith('/'):\n raise ValueError(\"Prefix must start with '/'\")\n\n # return self._mount_app(prefix, app, **options)\n return self._mount_wsgi(prefix, app, **options)\n\n def merge(self, routes):\n \"\"\" Merge the routes of another :class:`Bottle` application or a list of\n :class:`Route` objects into this application. The routes keep their\n 'owner', meaning that the :data:`Route.app` attribute is not\n changed. \"\"\"\n if isinstance(routes, App):\n routes = routes.routes\n for route in routes:\n self.add_route(route)\n\n def install(self, plugin):\n \"\"\" Add a plugin to the list of plugins and prepare it for being\n applied to all routes of this application. A plugin may be a simple\n decorator or an object that implements the :class:`Plugin` API.\n \"\"\"\n if hasattr(plugin, 'setup'): plugin.setup(self)\n if not callable(plugin) and not hasattr(plugin, 'apply'):\n raise TypeError(\"Plugins must be callable or implement .apply()\")\n self.plugins.append(plugin)\n self.reset()\n return plugin\n\n def uninstall(self, plugin):\n \"\"\" Uninstall plugins. Pass an instance to remove a specific plugin, a type\n object to remove all plugins that match that type, a string to remove\n all plugins with a matching ``name`` attribute or ``True`` to remove all\n plugins. Return the list of removed plugins. \"\"\"\n removed, remove = [], plugin\n for i, plugin in list(enumerate(self.plugins))[::-1]:\n if remove is True or remove is plugin or remove is type(plugin) \\\n or getattr(plugin, 'name', True) == remove:\n removed.append(plugin)\n del self.plugins[i]\n if hasattr(plugin, 'close'): plugin.close()\n if removed: self.reset()\n return removed\n\n def reset(self, route=None):\n \"\"\" Reset all routes (force plugins to be re-applied) and clear all\n caches. If an ID or route object is given, only that specific route\n is affected. \"\"\"\n if route is None: routes = self.routes\n elif isinstance(route, Route): routes = [route]\n else: routes = [self.routes[route]]\n for route in routes:\n route.reset()\n if DEBUG:\n for route in routes:\n route.prepare()\n self.trigger_hook('app_reset')\n\n def close(self):\n \"\"\" Close the application and all installed plugins. \"\"\"\n for plugin in self.plugins:\n if hasattr(plugin, 'close'): plugin.close()\n\n # def run(self, **kwargs):\n # \"\"\" Calls :func:`run` with the same parameters. \"\"\"\n # run(self, **kwargs)\n\n def match(self, environ):\n \"\"\" Search for a matching route and return a (:class:`Route` , urlargs)\n tuple. The second value is a dictionary with parameters extracted\n from the URL. Raise :exc:`HTTPError` (404/405) on a non-match.\"\"\"\n return self.router.match(environ)\n\n # def get_url(self, routename, **kargs):\n # \"\"\" Return a string that matches a named route \"\"\"\n # scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'\n # location = self.router.build(routename, **kargs).lstrip('/')\n # return urljoin(urljoin('/', scriptname), location)\n\n def add_route(self, route):\n \"\"\" Add a route object, but do not change the :data:`Route.app`\n attribute.\"\"\"\n self.routes.append(route)\n self.router.add(route.rule, route.method, route, name=route.name)\n if DEBUG: route.prepare()\n\n def route(self,\n path=None,\n method='GET',\n callback=None,\n name=None,\n apply=None,\n skip=None, **config):\n \"\"\" A decorator to bind a function to a request URL. Example::\n\n @app.route('/hello/')\n def hello(name):\n return 'Hello %s' % name\n\n The ```` part is a wildcard. See :class:`Router` for syntax\n details.\n\n :param path: Request path or a list of paths to listen to. If no\n path is specified, it is automatically generated from the\n signature of the function.\n :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of\n methods to listen to. (default: `GET`)\n :param callback: An optional shortcut to avoid the decorator\n syntax. ``route(..., callback=func)`` equals ``route(...)(func)``\n :param name: The name for this route. (default: None)\n :param apply: A decorator or plugin or a list of plugins. These are\n applied to the route callback in addition to installed plugins.\n :param skip: A list of plugins, plugin classes or names. Matching\n plugins are not installed to this route. ``True`` skips all.\n\n Any additional keyword arguments are stored as route-specific\n configuration and passed to plugins (see :meth:`Plugin.apply`).\n \"\"\"\n if callable(path): path, callback = None, path\n plugins = makelist(apply)\n skiplist = makelist(skip)\n\n def decorator(callback):\n if isinstance(callback, str): callback = load(callback)\n for rule in makelist(path) or yieldroutes(callback):\n for verb in makelist(method):\n verb = verb.upper()\n route = Route(self, rule, verb, callback,\n name=name,\n plugins=plugins,\n skiplist=skiplist, **config)\n self.add_route(route)\n return callback\n\n return decorator(callback) if callback else decorator\n\n def get(self, path=None, method='GET', **options):\n \"\"\" Equals :meth:`route`. \"\"\"\n return self.route(path, method, **options)\n\n def post(self, path=None, method='POST', **options):\n \"\"\" Equals :meth:`route` with a ``POST`` method parameter. \"\"\"\n return self.route(path, method, **options)\n\n def put(self, path=None, method='PUT', **options):\n \"\"\" Equals :meth:`route` with a ``PUT`` method parameter. \"\"\"\n return self.route(path, method, **options)\n\n def delete(self, path=None, method='DELETE', **options):\n \"\"\" Equals :meth:`route` with a ``DELETE`` method parameter. \"\"\"\n return self.route(path, method, **options)\n\n def patch(self, path=None, method='PATCH', **options):\n \"\"\" Equals :meth:`route` with a ``PATCH`` method parameter. \"\"\"\n return self.route(path, method, **options)\n\n def error(self, code=500, callback=None):\n \"\"\" Register an output handler for a HTTP error code. Can\n be used as a decorator or called directly ::\n\n def error_handler_500(error):\n return 'error_handler_500'\n\n app.error(code=500, callback=error_handler_500)\n\n @app.error(404)\n def error_handler_404(error):\n return 'error_handler_404'\n\n \"\"\"\n\n def decorator(callback):\n if isinstance(callback, str): callback = load(callback)\n self.error_handler[int(code)] = callback\n return callback\n\n return decorator(callback) if callback else decorator\n\n # def default_error_handler(self, res):\n # return tob(template(ERROR_PAGE_TEMPLATE, e=res, template_settings=dict(name='__ERROR_PAGE_TEMPLATE')))\n\n async def _handle(self, environ, rs = None):\n\n environ['route.params'] = environ.get(\"params\", {})\n environ['bottle.app'] = self\n request = BaseRequest(environ)\n\n if not rs:\n rs = AncillaResponse()\n \n request.set_response(rs)\n\n try:\n # while True: # Remove in 0.14 together with RouteReset\n out = None\n try:\n # self.trigger_hook('before_request')\n res = self.router.match(environ)\n route, args = self.router.match(environ)\n \n # print(f\"ROUTE = {route}\", flush=True)\n environ['route.handle'] = route\n environ['bottle.route'] = route\n environ['route.url_args'] = args\n # print(f\"Route.call = {route.call}\", flush=True)\n # result = yield from call_maybe_yield(route.call, *[request], **args)\n out = await call_maybe_yield(route.call, *[request], **args)\n \n if isinstance(out, io.IOBase) and hasattr(out, 'read') and (hasattr(out, 'close') or not hasattr(out, '__aiter__')):\n out = WSGIFileWrapper(out)\n\n\n except RouterError as e:\n print(f\"RouterError = {e}\", flush=True)\n\n if not self.catchall:\n raise e\n \n re_pattern = re.compile('^(/api/services/(?P[^/]+)/(?P[^/]+))(?P.*)$')\n re_match = re_pattern.match(request.path)\n\n if re_match:\n gargs = re_match.groupdict()\n # result = yield from call_maybe_yield(self.api.catchUnmountedServices, *[request], **gargs)\n out = await call_maybe_yield(self.api.catchUnmountedServices, *[request], **gargs)\n # return result\n else:\n raise e\n \n except AncillaResponse as e:\n # print(f\"INSIDE ANCilla REspone Error {str(e)}\", flush=True)\n raise e\n except Exception as e:\n # print(f\"AppCallException = {e}\", flush=True)\n raise AncillaError(400, {\"error\": str(e)})\n \n except (KeyboardInterrupt, SystemExit, MemoryError):\n raise\n except Exception as e:\n # print(f\"INSIDE OTHER EXCEPTION = {str(e)}\", flush=True)\n # if not self.catchall: raise e\n raise e\n # stacktrace = format_exc()\n # environ['wsgi.errors'].write(stacktrace)\n # environ['wsgi.errors'].flush()\n\n if isinstance(out, AncillaResponse):\n return out\n else:\n rs.body = out\n return rs\n # return out\n\n \n # def _cast(self, out, peek=None):\n # \"\"\" Try to convert the parameter into something WSGI compatible and set\n # correct HTTP headers when possible.\n # Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,\n # iterable of strings and iterable of unicodes\n # \"\"\"\n\n # # Empty output is done here\n # if not out:\n # if 'Content-Length' not in response:\n # response['Content-Length'] = 0\n # return []\n # # Join lists of byte or unicode strings. Mixed lists are NOT supported\n # if isinstance(out, (tuple, list))\\\n # and isinstance(out[0], (bytes, unicode)):\n # out = out[0][0:0].join(out) # b'abc'[0:0] -> b''\n # # Encode unicode strings\n # if isinstance(out, unicode):\n # out = out.encode(response.charset)\n # # Byte Strings are just returned\n # if isinstance(out, bytes):\n # if 'Content-Length' not in response:\n # response['Content-Length'] = len(out)\n # return [out]\n # # HTTPError or HTTPException (recursive, because they may wrap anything)\n # # TODO: Handle these explicitly in handle() or make them iterable.\n # if isinstance(out, HTTPError):\n # out.apply(response)\n # out = self.error_handler.get(out.status_code,\n # self.default_error_handler)(out)\n # return self._cast(out)\n # if isinstance(out, HTTPResponse):\n # out.apply(response)\n # return self._cast(out.body)\n\n # # File-like objects.\n # if hasattr(out, 'read'):\n # if 'wsgi.file_wrapper' in request.environ:\n # return request.environ['wsgi.file_wrapper'](out)\n # elif hasattr(out, 'close') or not hasattr(out, '__iter__'):\n # return WSGIFileWrapper(out)\n\n # # Handle Iterables. We peek into them to detect their inner type.\n # try:\n # iout = iter(out)\n # first = next(iout)\n # while not first:\n # first = next(iout)\n # except StopIteration:\n # return self._cast('')\n # except HTTPResponse as E:\n # first = E\n # except (KeyboardInterrupt, SystemExit, MemoryError):\n # raise\n # except Exception as error:\n # if not self.catchall: raise\n # first = HTTPError(500, 'Unhandled exception', error, format_exc())\n\n # # These are the inner types allowed in iterator or generator objects.\n # if isinstance(first, HTTPResponse):\n # return self._cast(first)\n # elif isinstance(first, bytes):\n # new_iter = itertools.chain([first], iout)\n # elif isinstance(first, unicode):\n # encoder = lambda x: x.encode(response.charset)\n # new_iter = imap(encoder, itertools.chain([first], iout))\n # else:\n # msg = 'Unsupported response type: %s' % type(first)\n # return self._cast(HTTPError(500, msg))\n # if hasattr(out, 'close'):\n # new_iter = _closeiter(new_iter, out.close)\n # return new_iter\n\n # def __call__(self, method, path, msg):\n def __call__(self, environ, rs = None):\n \"\"\" Each instance of :class:'Bottle' is a WSGI application. \"\"\"\n return self._handle(environ, rs)\n # return self.wsgi(environ, start_response)\n\n # def __enter__(self):\n # \"\"\" Use this application as default for all module-level shortcuts. \"\"\"\n # default_app.push(self)\n # return self\n\n # def __exit__(self, exc_type, exc_value, traceback):\n # default_app.pop()\n\n # def __setattr__(self, name, value):\n # # if name in self.__dict__:\n # # raise AttributeError(\"Attribute %s already defined. Plugin conflict?\" % name)\n # self.__dict__[name] = value\n\n\n","repo_name":"frenzylabs/ancilla","sub_path":"ancilla/ancilla/foundation/node/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":26838,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"}
+{"seq_id":"25593441198","text":"f = open(\"./data/d7/input.txt\")\nl = [ x for x in ''.join(f.readlines()).strip().split('\\n') ]\n\nclass Dir:\n def __init__(self, name, parent_dir):\n self.name=name\n self.size=0\n self.sub_dir=[]\n self.parent_dir=parent_dir\n\n def find_sub_dir(self, name):\n for s in self.sub_dir:\n if s.name==name:\n return s\n return None\n \n def add_sub_dir(self, dir):\n self.sub_dir.append(dir)\n \n def add_size(self, size):\n if self.parent_dir!=None:\n self.parent_dir.add_size(size)\n self.size+=size\n \n \ndef build_dir():\n i=0\n dir_list=[]\n current_dir=None\n while i=size_to_delete ][0]\n return s\n\np1()\np2()","repo_name":"Minifixio/AdventOfCode2022","sub_path":"python/d7/d7.py","file_name":"d7.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73734663186","text":"import numpy as np\nimport pandas as pd\nimport cv2\nfrom tqdm import tqdm\nimport mediapipe as mp\nfrom scipy.spatial.transform import Rotation as R\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_face_mesh = mp.solutions.face_mesh\n\ntqdm.pandas()\n\nFERclassName = [\n 'Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral', 'None'\n]\n\nRussellclassName = {\n 'Happy': 'Happy',\n 'Surprise': 'Happy',\n 'Angry': 'Anger',\n 'Fear': 'Anger',\n 'Disgust': 'Anger',\n 'Sad': 'Sadness',\n 'Neutral': 'Relax',\n 'None': 'None'\n}\n\nclass FERdata(object):\n\n def __init__(self, path_to_csv):\n print(f'reading csvfile from {path_to_csv}')\n self.df = pd.read_csv(path_to_csv).sample(frac=1, ignore_index=True)\n self.len = len(self.df)\n self.class_name = FERclassName\n\n def __len__(self):\n return self.len\n\n def save_df(self, path_to_save):\n self.df.to_csv(path_to_save, index=False)\n print(f'save {path_to_save} done')\n\n def balance_df(self, mode):\n return pd.concat([\n balance_each_usage(self.df[self.df['usage'] == 'train'], mode),\n self.df[self.df['usage'] == 'val'],\n self.df[self.df['usage'] == 'test']\n ],\n ignore_index=True)\n\n def get_df(self,\n mode='ANN',\n with_img = False,\n drawlandmarks=False,\n rotate=True,\n repos=True,\n mapping=False,\n cmap='GRAY',\n sample=False,\n sample_size=10):\n if sample is False:\n sample_size = self.len\n print('Generate df with config')\n print(\n f' mode:{mode}\\n drawlandmarks:{drawlandmarks}\\n mapping:{mapping}\\n colormap:{cmap}\\n sample:{sample}\\n sample_size:{sample_size}'\n )\n if sample == True:\n self.df = pd.concat([\n self.df[self.df[' Usage'] == 'Training'].sample(n=sample_size),\n self.df[self.df[' Usage'] == 'PublicTest'].sample(\n n=sample_size),\n self.df[self.df[' Usage'] == 'PrivateTest'].sample(\n n=sample_size)\n ])\n print('Prepare data to img')\n self.df['img'] = self.df.progress_apply(to_img, axis=1)\n self.df = getlandmark(self.df, mode, drawlandmarks, mapping, cmap, with_img, rotate, repos)\n return self.df\n else:\n print('Prepare data to img')\n self.df['img'] = self.df.progress_apply(to_img, axis=1)\n self.df = getlandmark(self.df, mode, drawlandmarks, mapping, cmap, with_img, rotate, repos)\n return self.df\n\ndef re_pos(mesh):\n # print(f'shift from: {mesh[1]}')\n origin = mesh[1] - np.array([0, 0, 0])\n mesh = mesh - origin\n return mesh\n\ndef unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector / np.linalg.norm(vector)\n\ndef rot(mesh, u,v,w, x,y,z):\n r = R.from_matrix([u,v,w])\n ref_r = R.from_matrix([x,y,z])\n rotation = ref_r * r\n # mesh = r.apply(mesh)\n # mesh = ref_r.apply(mesh)\n mesh = rotation.apply(mesh)\n # print(r.as_euler('xyz', degrees=True))\n return mesh\n\ndef get_ref(mesh):\n p0 = mesh[1]\n p1 = mesh[5]\n p2 = mesh[44]\n p3 = mesh[274]\n v1 = p2 - p1\n v2 = p3 - p1\n v3 = p0 - p1\n v4 = p0 - mesh[4]\n w = unit_vector(np.cross(v1, v2))\n ref = unit_vector(np.cross(v3, v4))\n v = unit_vector(np.cross(w, ref))\n u = unit_vector(np.cross(v, w))\n return u,v,w\n\ndef balance_each_usage(df, mode):\n print(f'Balancing dataFrame with {mode}sampling mode')\n target_list = list(df['target'].value_counts().index)\n if mode == 'up':\n count = df['target'].value_counts().max()\n elif mode == 'down':\n count = df['target'].value_counts().min()\n list_df = [\n df[df['target'] == t].sample(n=count,\n random_state=1,\n replace=(mode == 'up'))\n for t in target_list\n ]\n print(f'target list:{target_list}')\n print(f'count:{count}')\n return pd.concat(list_df, ignore_index=True).sample(frac=1,\n ignore_index=True)\n\n\ndef to_img(row):\n return np.array(row[' pixels'].split(' ')).reshape(48, 48).astype('uint8')\n\n\ndef prepareforANN(lanmarks, rotation=True, reposition=True):\n mesh = np.array([[landmark.x, landmark.y, landmark.z] for landmark in lanmarks])\n if reposition == True:\n mesh = re_pos(mesh)\n if rotation == True:\n u,v,w = get_ref(mesh)\n x = np.array([1., 0., 0.])\n y = np.array([0., -1., 0.])\n z = np.array([0., 0., -1.])\n mesh = rot(mesh, u,v,w, x,y,z)\n return mesh\n\ndef drawalllandmark(annotated_image, result):\n for face_landmarks in result.multi_face_landmarks:\n # print('face_landmarks:', face_landmarks)\n mp_drawing.draw_landmarks(\n image=annotated_image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_TESSELATION,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles.\n get_default_face_mesh_tesselation_style())\n mp_drawing.draw_landmarks(image=annotated_image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_CONTOURS,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles.\n get_default_face_mesh_contours_style())\n mp_drawing.draw_landmarks(\n image=annotated_image,\n landmark_list=face_landmarks,\n connections=mp_face_mesh.FACEMESH_IRISES,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles.\n get_default_face_mesh_iris_connections_style())\n\n return annotated_image\n\n\ndef emotionmapping(emotion):\n return FERclassName.index(emotion)\n\ndef getlandmark(df, mode, draw, map, cmap, with_img, rotate, repos):\n new_df = pd.DataFrame(columns=['usage', 'feature', 'target'])\n draw_img, real_img = [], []\n usage_map = {\n 'Training': 'train',\n 'PublicTest': 'val',\n 'PrivateTest': 'test',\n }\n print('Getting landmarks with mediapipe FaceMesh')\n with mp_face_mesh.FaceMesh(static_image_mode=True,\n max_num_faces=1,\n refine_landmarks=True,\n min_detection_confidence=0.5) as face_mesh:\n\n for data in tqdm(df[[' Usage', 'img', 'emotion']].values):\n # Convert the BGR image to RGB before processing.\n if cmap == 'GRAY':\n img = cv2.cvtColor(data[1], cv2.COLOR_GRAY2RGB)\n elif cmap == 'BGR':\n img = cv2.cvtColor(data[1], cv2.COLOR_BGR2RGB)\n else:\n img = data[1]\n\n if map == True:\n print('Currently have only not map')\n else:\n emotion = data[2]\n\n if mode == 'ANN' or mode == 'GNN':\n result = face_mesh.process(img)\n if not result.multi_face_landmarks:\n continue\n\n np_landmark = prepareforANN(\n result.multi_face_landmarks[0].landmark,rotation=rotate,reposition=repos)\n\n if draw == True:\n annotated_image = cv2.cvtColor(data[1],\n cv2.COLOR_GRAY2RGB).copy()\n annotated_image = drawalllandmark(annotated_image, result)\n draw_img.append(annotated_image)\n \n if with_img == True:\n real_img.append(img)\n \n new_df = pd.concat([\n new_df,\n pd.DataFrame([[usage_map[data[0]], np_landmark, emotion]],\n columns=['usage', 'feature', 'target'])\n ],\n ignore_index=True)\n if mode == 'GNN':\n edge_index = list(mp_face_mesh.FACEMESH_TESSELATION)\n new_df['edge_index'] = [edge_index for _ in range(len(new_df))]\n\n elif mode == 'IMG':\n new_df = pd.concat([\n new_df,\n pd.DataFrame([[\n usage_map[data[0]],\n cv2.cvtColor(data[1], cv2.COLOR_GRAY2RGB), emotion\n ]],\n columns=['usage', 'feature', 'target'])\n ],\n ignore_index=True)\n\n else:\n print('Currently have only ANN, IMG, and GNN mode')\n break\n\n if draw is True:\n new_df['draw_img'] = draw_img\n \n if with_img is True:\n new_df['img'] = real_img\n\n print(\n f'Distribution of Train: \\n{new_df[new_df[\"usage\"] == \"train\"][\"target\"].value_counts()}'\n )\n print(\n f'Distribution of Validation: \\n{new_df[new_df[\"usage\"] == \"val\"][\"target\"].value_counts()}'\n )\n print(\n f'Distribution of Test \\n{new_df[new_df[\"usage\"] == \"test\"][\"target\"].value_counts()}'\n )\n\n return new_df","repo_name":"northnpk/FaceMeshEmotions","sub_path":"utils/preprocessFERplus.py","file_name":"preprocessFERplus.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"74121448466","text":"class UnionFind:\n def __init__(self, n):\n self.n = n\n self.par = [-1] * n\n self.wei = [0] * n\n\n def find(self, x):\n if self.par[x] < 0:\n return x\n else:\n y = self.find(self.par[x])\n self.wei[x] += self.wei[self.par[x]]\n self.par[x] = y\n return y\n\n def union(self, x, y, w=0):\n w += self.weight(x) - self.weight(y)\n x = self.find(x)\n y = self.find(y)\n if x == y:\n return False\n if self.par[x] > self.par[y]:\n x, y = y, x\n w *= -1\n self.par[x] += self.par[y]\n self.par[y] = x\n self.wei[y] = w\n return True\n\n def same(self, x, y):\n return self.find(x) == self.find(y)\n\n def size(self, x):\n return -self.par[self.find(x)]\n\n def weight(self, x):\n self.find(x)\n return self.wei[x]\n\n def diff(self, x, y):\n return self.weight(y) - self.weight(x)\n\n def kruskal(self, edge):\n edge.sort()\n cost_sum = 0\n for cost, node1, node2 in edge:\n if not self.same(node1, node2):\n cost_sum += cost\n self.union(node1, node2)\n return cost_sum\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"Library/Union_Find.py","file_name":"Union_Find.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"29116926938","text":"\"\"\"\nGiven 2 arrays, create a function that let's a user know (true/false)\nwhether these two arrays contain any common items\nFor Example:\nconst array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'i'];\nshould return false.\n-----------\nConst array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'x'];\nshould return true.\n\n2 parameters - arrays - no size limit\nreturn true or false\n\"\"\"\n\n\ndef common_items1(array1, array2):\n \"\"\"\n Finding if any items in each array have similar inputs\n :param array1:\n :param array2:\n :return: True or False\n \"\"\"\n\n # Create Dictionary of array1 -\n # Time Complexity O(n)\n # Space Complexity O(n)\n dict1 = {}\n for item in array1:\n if item in dict1:\n updated_value = dict1[item]\n updated_value += 1\n dict1[item] = updated_value\n else:\n dict1[item] = 1\n\n # Compare every element of n to dict\n # Time Complexity O(m)\n for item in array2:\n if item in dict1:\n return True\n\n # Overall Time Complexity O(n + m)\n return False\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n array1 = ['a', 'b', 'c', 'x']\n array2 = ['z', 'y', 'a']\n array3 = ['z', 'y', 'i']\n print(common_items1(array1, array2)) # return True\n print(common_items1(array1, array3)) # return False\n","repo_name":"alexfuoc/DS_ALG","sub_path":"IntroInterview/CommonItems.py","file_name":"CommonItems.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"23181479660","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'night_generator'\n\nurlpatterns = [\n path(\"media/\", views.MediaAPIView, name='media_home'),\n\n path(\"topRatedMovie/\", views.TopRatedMovieAPI, name='topratedmovie'),\n path(\"topRatedTvShow/\", views.TopRatedTVShowAPI, name='topratedtvshow'),\n path(\"mostPopularMovie/\", views.MostPopularMovieAPI, name='mostpopularmovie'),\n path(\"mostPopularTvShow/\", views.MostPopularTVShowAPI, name='mostpopulartvshow'),\n\n]\n","repo_name":"ricardobohadana/random-night","sub_path":"night_generator/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"29664043346","text":"from operator import attrgetter\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom ..managers import TradeManager\n\nclass TradeManagerTest(TestCase):\n \"\"\"Test case for ``TradeManager``.\"\"\"\n fixtures = ['test.json']\n\n def setUp(self):\n self.manager = TradeManager()\n\n # `latest_offers`\n def test_latest_offers_count(self):\n count = 10\n latest_ten_offers = self.manager.latest_offers(count)\n self.assertLessEqual(len(latest_ten_offers), count)\n\n def test_latest_offer_count_when_negative(self):\n count = -3\n latest_offers = self.manager.latest_offers(count)\n self.assertEqual(0, len(latest_offers))\n\n def test_latest_offers_sorted_by_date(self):\n latest_offers = self.manager.latest_offers()\n self.assertEqual(latest_offers, sorted(latest_offers, \n key=attrgetter('date'),\n reverse=True))\n\n\n # `latest_demands`\n def test_latest_demands_count(self):\n count = 10\n latest_ten_demands = self.manager.latest_demands(count)\n self.assertLessEqual(len(latest_ten_demands), count)\n\n def test_latest_demand_count_when_negative(self):\n count = -3\n latest_demands = self.manager.latest_demands(count)\n self.assertEqual(0, len(latest_demands))\n\n def test_latest_demands_sorted_by_date(self):\n latest_offers = self.manager.latest_offers()\n self.assertEqual(latest_offers, sorted(latest_offers, \n key=attrgetter('date'),\n reverse=True))\n\n # `offers`\n def test_user_offers(self):\n alice = User.objects.get(username=u'Alice')\n offers = self.manager.offers(alice)\n for offer in offers:\n self.assertEqual(offer.owner, alice)\n\n def test_user_offers_sorted_by_date(self):\n # newest comes first\n alice = User.objects.get(username=u'Alice')\n offers = self.manager.offers(alice)\n sorted_offers = sorted(list(offers),\n key=lambda offer: offer.date,\n reverse=True)\n for index, offer in enumerate(sorted_offers):\n self.assertEqual(offer, offers[index])\n\n # `demands`\n def test_user_demands(self):\n alice = User.objects.get(username=u'Alice')\n demands = self.manager.demands(alice)\n for demand in demands:\n self.assertEqual(demand.owner, alice)\n\n def test_user_demands_sorted_by_date(self):\n # newest comes first\n alice = User.objects.get(username=u'Alice')\n demands = self.manager.demands(alice)\n sorted_demands = sorted(list(demands),\n key=lambda demand: demand.date,\n reverse=True)\n for index, demand in enumerate(sorted_demands):\n self.assertEqual(demand, demands[index])\n\n # `services`\n def test_user_services(self):\n alice = User.objects.get(username=u'Alice')\n services = self.manager.services(alice)\n for service in services:\n self.assertEqual(service.owner, alice)\n\n def test_user_services_sorted_by_date(self):\n # newest comes first\n alice = User.objects.get(username=u'Alice')\n services = self.manager.services(alice)\n sorted_services = sorted(list(services),\n key=lambda service: service.date,\n reverse=True)\n for index, service in enumerate(sorted_services):\n self.assertEqual(service, services[index])\n\n # `gifts`\n def test_user_gifts(self):\n alice = User.objects.get(username=u'Alice')\n gifts = self.manager.gifts(alice)\n for gift in gifts:\n self.assertEqual(gift.owner, alice)\n\n def test_user_gifts_sorted_by_date(self):\n # newest comes first\n alice = User.objects.get(username=u'Alice')\n gifts = self.manager.gifts(alice)\n sorted_gifts = sorted(list(gifts),\n key=lambda gift: gift.date,\n reverse=True)\n for index, gift in enumerate(sorted_gifts):\n self.assertEqual(gift, gifts[index])\n\n # `loans`\n def test_user_loans(self):\n alice = User.objects.get(username=u'Alice')\n loans = self.manager.loans(alice)\n for loan in loans:\n self.assertEqual(loan.owner, alice)\n\n def test_user_loans_sorted_by_date(self):\n # newest comes first\n alice = User.objects.get(username=u'Alice')\n loans = self.manager.loans(alice)\n sorted_loans = sorted(list(loans),\n key=lambda loan: loan.date,\n reverse=True)\n for index, loan in enumerate(sorted_loans):\n self.assertEqual(loan, loans[index])\n","repo_name":"tuxskar/mutualismo","sub_path":"apps/red/tests/test_managers.py","file_name":"test_managers.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"24056065994","text":"from random import choice, randint, sample\nfrom decimal import *\nfrom collections import namedtuple\nfrom characters import martial_classes, classes, ability_scores, meets_bonus_xp_minimums\n\ngetcontext().prec = 3\n\n\n# todo move this function to globals / rules\ndef get_gender_words(sex):\n # todo account for neuter creatures\n if sex == \"male\":\n return (\"he\", \"him\", \"his\")\n else:\n return (\"she\", \"her\", \"her\")\n\n\n# based on Strength\ndef feats(magnitude, c):\n big_percent = choice([30, 40])\n small_percent = choice([10, 20])\n result = \"\"\n subj, obj, poss = get_gender_words(c[\"sex\"])\n if magnitude <= -17:\n result = \"Weak lungs make it impossible to run.\"\n elif magnitude <= -14:\n result = \"When stunned, must make save against crushing to end the stun and rejoin combat.\"\n elif magnitude <= -12:\n result = \"Character is forever incapable of swimming, regardless of character class or skills.\"\n elif magnitude <= -11:\n result = (\n \"Poor endurance. Character cannot run for more than 1 round at a time, no matter \"\n + poss\n + \" Constitution score.\"\n )\n elif magnitude <= -10:\n result = \"One-handed melee weapons must be used two-handed (even daggers); two-handed melee weapons suffer the non-proficiency penalty (if already non-proficient with a given weapon, add an additional -1 penalty.)\"\n elif magnitude <= -9:\n result = \"Encumbrance limits reduced by \" + str(big_percent) + \"%.\"\n c[\"encumbrance modifier\"] = c[\"encumbrance modifier\"] - Decimal(\n 0.01 * big_percent\n )\n elif magnitude <= -8:\n result = \"Too weak to draw or load any bow or crossbow.\"\n elif magnitude <= -7:\n result = \"One-handed melee weapons must be used two-handed (except daggers); two-handed melee weapons have a -1 penalty to attack and damage.\"\n elif magnitude <= -6:\n result = \"Encumbrance limits reduced by \" + str(small_percent) + \"%.\"\n c[\"encumbrance modifier\"] = c[\"encumbrance modifier\"] - Decimal(\n 0.01 * small_percent\n )\n elif magnitude <= -5:\n result = \"Too weak to draw a longbow or load a heavy crossbow.\"\n elif magnitude <= -4:\n result = \"Poor cardiovascular health. Character can only hold breath for 1 round (normal: 3).\"\n elif magnitude <= -2:\n result = (\n \"Weak arms and legs. Treat character's Dexterity as half its actual value (round down) for the purpose of no-fault climbing. Danger climbing ability is reduced by \"\n + str(randint(10, 15))\n + \"%.\"\n )\n elif magnitude <= -1:\n result = \"Throwing weapons deal 1 less damage (minimum 0.)\"\n elif magnitude <= 1:\n result = \"Throwing weapons deal 1 extra damage.\"\n elif magnitude <= 3:\n result = \"Strong arms and legs. Treat character's Dexterity as 50% higher (round down) for no-fault climbing.\"\n elif magnitude == 4:\n result = \"Strong hands and arms allow a 50% chance to spend 3 fewer AP when loading a crossbow.\"\n elif magnitude <= 6:\n result = \"Character is capable of swimming.\"\n elif magnitude <= 8:\n result = \"Encumbrance limits increased by \" + str(small_percent) + \"%.\"\n c[\"encumbrance modifier\"] = c[\"encumbrance modifier\"] + Decimal(\n 0.01 * small_percent\n )\n elif magnitude <= 9:\n result = \"Strong upper body. For slings, bows (not crossbows), and all thrown weapons, increase short range by 1 hex, and medium and long ranges by 2 hexes.\"\n elif magnitude <= 11:\n result = \"Can hold breath for three times the normal duration (9 rounds instead of 3.)\"\n elif magnitude <= 13:\n result = \"Powerful muscles add +3 on rolls made to escape manacles, ropes, or other constraints.\"\n elif magnitude <= 15:\n result = (\n \"Each day, the first time the character is stunned, after rejoining combat \"\n + subj\n + \" gains +2 to melee attack and damage for 10 rounds.\"\n )\n else:\n result = (\n \"Each day, the first time the character is stunned, after rejoining combat \"\n + subj\n + \" gains hysterical strength. Roll 1d3+1: for 10 rounds, character gains that amount as a bonus to melee attack and damage.\"\n )\n return result\n\n\nman_at_arms_weapons = [\"dagger\", \"club\", \"quarterstaff\", \"sling\"] * 3 + [\n \"shortbow\",\n \"shortsword\",\n \"longsword\",\n \"mace\",\n \"bastard sword\",\n \"greatsword\",\n]\nman_at_arms_armor = (\n [\"no armor\"] * 2\n + [\"gambeson\"] * 4\n + [\"leather armor\"] * 3\n + [\"studded leather\"] * 2\n + [\"haubergeon\"]\n)\n\n\ndef man_at_arms_equipment():\n num_weapons = 1 if randint(1, 10) < 7 else 2\n weapons = sample(man_at_arms_weapons, num_weapons)\n armor = choice(man_at_arms_armor)\n equipment = namedtuple(\"equipment\", [\"weapons\", \"armor\"])\n return equipment(weapons, armor)\n\n\ndef stringify_man_at_arms_equipment(equipment):\n return \"has \" + equipment.armor + \"; carries \" + \", \".join(equipment.weapons)\n\n\ndef man_at_arms_pay():\n return 4 + randint(1, 4) + randint(2, 5) + randint(2, 5) + randint(2, 5)\n\n\n# based on Wisdom\ndef relationships(magnitude, c):\n subj, obj, poss = get_gender_words(c[\"sex\"])\n result = \"\"\n if magnitude <= -17:\n result = \"The character inadvertently revealed information to the enemy of the land where they are from, enabling that enemy to invade and seize wealth and property. A death sentence has been laid upon the character.\"\n elif magnitude == -16:\n result = (\n \"Ill-considered opinions and bad intentions caused the character to be excommunicated from \"\n + poss\n + \" original religion. \"\n + subj.capitalize()\n + \" is marked as an apostate and all sites of organized worship will shun \"\n + obj\n + \".\"\n )\n elif magnitude <= -14:\n crimes = [\n \"murdered a peasant, and is being sought to receive lashes and time in the stocks.\",\n \"damaged property, and is being sought to pay restitution and receive time in the stocks.\",\n \"committed petty theft, and is being sought to receive lashes and pay restitution.\",\n \"murdered a merchant, and is being sought for prison time and a hefty fine.\",\n \"committed a serious theft, and is being sought to pay restitution and to have a hand chopped off.\",\n \"murdered a noble, and is being sought for execution.\",\n ]\n roll = randint(1, 20)\n result_start = \"Character has \"\n if roll <= 3:\n result = result_start + crimes[0]\n elif roll <= 7:\n result = result_start + crimes[1]\n elif roll <= 11:\n result = result_start + crimes[2]\n elif roll <= 14:\n result = result_start + crimes[3]\n elif roll <= 18:\n result = result_start + crimes[4]\n else: # 19 and 20\n result = result_start + crimes[5]\n elif magnitude == -13:\n result = \"Character's strange proclivities and morals prevent the character from retaining hirelings or followers for more than a month. Henchmen and retainers (received from leveling up) are not affected.\"\n elif magnitude <= -11:\n result = (\n \"Character is exiled from \"\n + poss\n + \" homeland, and will face a life sentence or execution if they return, although \"\n + poss\n + \" only 'crime' is that of having powerful enemies.\"\n )\n elif magnitude <= -9:\n enemy_family_member = [\"wife\"] * 9 + [\"daughter\"] * 10 + [\"mother\"] * 1\n sex_cutoff = 1\n if c[\"sex\"] == \"female\":\n sex_cutoff = 11\n enemy_reasons = [\n (\n \"foolishly slept with the enemy's \"\n + choice(enemy_family_member)\n + \", making her pregnant.\"\n ),\n \"stole a large sum of money from the enemy, and then lost it.\",\n \"destroyed a possession which the enemy held in great personal significance.\",\n ]\n roll = randint(sex_cutoff, 20)\n result_start = \"The character is pursued by a sworn enemy, who seeks revenge for the character having \"\n if roll <= 10:\n result = result_start + enemy_reasons[0]\n elif roll <= 15:\n result = result_start + enemy_reasons[1]\n else:\n result = result_start + enemy_reasons[2]\n elif magnitude <= -8:\n if c[\"has family\"]:\n result = (\n \"Character has been ostracized by \"\n + poss\n + \" family because of \"\n + poss\n + \" poor decisions. The character has no access to any family possessions or talents.\"\n )\n else:\n result = (\n \"Character has been ostracized by \"\n + poss\n + \" mentor because of \"\n + poss\n + \" poor decisions. The character's training was incomplete, so \"\n + subj\n + \" has no weapon proficiencies.\"\n )\n elif magnitude <= -6:\n result = (\n \"People in this area treat the character with profound dislike. Thus, \"\n + subj\n + \" has been banned from all town establishments save the market.\"\n )\n elif magnitude == -5:\n result = (\n \"Word has spread that the character's word cannot be trusted. \"\n + subj.capitalize()\n + \" will be unable to obtain hirelings or make contracts in this town.\"\n )\n elif magnitude == -4:\n if c[\"has family\"]:\n result = \"Family members strongly dislike the character, and will provide nothing more than a night's lodging, no more than once every every six months.\"\n else:\n result = \"Character's occasional displays of foolishness means that hirelings and followers will take twice as long to earn morale increases for extended service. \"\n elif magnitude <= -2:\n num = randint(3, 8)\n result = (\n \"A group of \"\n + str(num)\n + \" local tough guys have been threatening and harassing the character whenever they can. These toughs certainly have class levels, but aren't too powerful.\"\n )\n elif magnitude == -1:\n result = (\n \"The character's conduct has led to \"\n + poss\n + \" being banned from inns and taverns in this town.\"\n )\n elif magnitude == 0:\n if c[\"has family\"]:\n result = \"Family members treat the character as hopeless and without prospects, but will provide lodging. Any brothers and sisters will work as hirelings, but will start with a morale of only 7.\"\n else:\n result = \"Hireling and followers are made uneasy by character's small-mindedness. Base morale will be 1 point below normal, even if they are gained through this generator.\"\n elif magnitude == 1:\n sex = choice([\"he\", \"she\"])\n result = (\n \"Character has made friends with a man-at-arms, who has a morale of 8. \"\n + sex.capitalize()\n + \" \"\n + stringify_man_at_arms_equipment(man_at_arms_equipment())\n + \". \"\n + sex.capitalize()\n + \" may be hired now or later; cost is \"\n + str(man_at_arms_pay())\n + \" GP/month.\"\n )\n elif magnitude <= 3:\n if c[\"has family\"]:\n result = (\n \"Family members treat the character and \"\n + poss\n + \" friends well, and look forward to news and visits. Brothers, sisters, and cousins will work as hirelings with a starting morale of 9.\"\n )\n else:\n lover = \"daughter\"\n if c[\"sex\"] == \"female\":\n lover = \"son\"\n result = \"The character is loved by the \" + lover + \" of an artisan.\"\n elif magnitude == 4:\n result = (\n \"Character has made friends with two men-at-arms, who have a morale of 9. One, a \"\n + choice([\"man\", \"woman\"])\n + \", \"\n + stringify_man_at_arms_equipment(man_at_arms_equipment())\n + \"; the other, a \"\n + choice([\"man\", \"woman\"])\n + \", \"\n + stringify_man_at_arms_equipment(man_at_arms_equipment())\n + \". Can be hired now or later; wages \"\n + str(man_at_arms_pay())\n + \" and \"\n + str(man_at_arms_pay())\n + \" GP/mo\"\n )\n elif magnitude == 5:\n result = \"Character is well-known and liked around these parts. Can easily obtain as many hirelings as needed (normally each one requires a reaction roll.) Limits based on town size still apply.\"\n elif magnitude == 6:\n if c[\"has family\"]:\n result = \"Character is the family favorite and will receive regular gifts from home. The family will look forward to news and visits, and treat the character's friends well. All family members will work as hirelings, with starting morale of 10.\"\n else:\n result = (\n \"Character has a particularly warm relationship with the mentor who taught \"\n + obj\n + \" class skills. The mentor will help find hirelings or procure items when the character is in town.\"\n )\n elif magnitude == 7:\n result = \"Locals treat the character as a wise teacher, and will seek him or her out for advice. There is a 50% chance for the character to obtain a night's lodging for free each time he or she visits.\"\n elif magnitude == 8:\n result = \"Character enjoys the favor of local farmers and peasants, and can count on a night's free lodging on each visit. Prices at nearest market are 10% lower for him or her.\"\n elif magnitude == 9:\n result = (\n \"Character is so popular here that \"\n + subj\n + \" can count on free lodging indefinitely no matter how long the stay. This also applies to any area in which \"\n + subj\n + \" lives for at least 6 straight months.\"\n )\n elif magnitude <= 11:\n guild = choice(\n [\n \"alchemist\",\n \"brewer\",\n \"blacksmith\",\n \"cooper\",\n \"carpenter\",\n \"carver\",\n \"shipwright\",\n \"chandler\",\n \"mason\",\n \"merchant\",\n \"weaver\",\n ]\n )\n result = (\n \"Character has made influential contacts in the local \"\n + guild\n + \" guild, and can count on a favor from them.\"\n )\n elif magnitude == 12:\n result = \"Character has received the notice of the local government. The character may seek one favor.\"\n elif magnitude <= 14:\n num = randint(3, 5)\n descriptions = []\n for i in range(1, num + 1):\n enumerator = \"the last, a\" if i == num else \"one \"\n sex = choice([\"man\", \"woman\"])\n desc = (\n stringify_man_at_arms_equipment(man_at_arms_equipment())\n + \": wages \"\n + str(man_at_arms_pay())\n + \" GP/mo\"\n )\n descriptions.append(enumerator + \" \" + sex + \" \" + desc)\n result = (\n \"Character has made friends with \"\n + str(num)\n + \" men-at-arms, who have a morale of 10. Can be hired now or later. They are as follows:\"\n )\n for d in descriptions:\n result = result + \" \" + d + \".\"\n elif magnitude <= 16:\n result = \"Character has been made a member of the Illuminati. Tell nobody.\"\n else:\n result = \"Events surrounding the character have caused people to believe that the character had a major part in a religious miracle. The character has received the goodwill of the highest religious figure in the land, and may seek one favor.\"\n return result\n\n\n# based on Wisdom\ndef tendencies(magnitude, c):\n subj, obj, poss = get_gender_words(c[\"sex\"])\n result = \"\"\n if magnitude <= -17:\n num = randint(3, 5) * -1\n result = (\n \"Character is deeply ignorant and superstitious. Saves against fear and mind-affecting spells suffer a \"\n + str(num)\n + \" penalty.\"\n )\n elif magnitude == -16:\n num = randint(2, 3) * -1\n result = (\n \"Character is foolish, ignorant, and superstitious. Saves against fear and mind-affecting spells suffer a \"\n + str(num)\n + \" penalty.\"\n )\n elif magnitude <= -14:\n result = \"Character is cowardly and lacks confidence. If stunned, a save must be made vs. crushing, or else the character will avoid all combat, including spellcasting, for 1d4 rounds.\"\n elif magnitude == -13:\n result = \"Character has an awful temper. If character's weapon breaks or if he or she is hit by friendly fire, a save vs. magic must be made; otherwise, for 1d4+1 rounds, the character will be -3 to hit, +1 to damage, and unaffected by fear, morale, or attempts to communicate.\"\n elif magnitude <= -11:\n extra_weight = int(c[\"weight\"] * Decimal(randint(15, 25) * 0.01))\n result = \"Gluttony and laziness has caused the character to gain fat.\"\n c[\"conditions\"][\"overweight\"] = dict()\n c[\"conditions\"][\"overweight\"][\"magnitude\"] = extra_weight\n elif magnitude <= -9:\n result = (\n \"Gullibility causes the character to frivolously spend and give away money. Whenever \"\n + subj\n + \" goes to market, if a Wisdom check is not successful, the character will lose 5d4 gold to the likes of confidence men, beggars, and snake-oil salesmen.\"\n )\n elif magnitude <= -7:\n result = (\n \"Character's Wisdom is treated as 2 points lower when resisting seduction.\"\n )\n elif magnitude <= -5:\n result = \"Character is overly cautious about combat. Must succeed at a Wisdom check before being able to make attacks in a given combat (including discharging offensive spells, but not including backstabbing or assassination before combat proper.) Check can be attempted on character's turn each round.\"\n elif magnitude <= -3:\n percent = choice([10, 15])\n negative_xp = int(classes[c[\"class\"]][\"levels\"][2][\"min XP\"] * percent * 0.01)\n c[\"XP\"] -= negative_xp\n result = (\n \"Character has not quite completed \"\n + poss\n + f\" training, and starts the game with -{negative_xp} XP ({percent}% of the number needed to attain 2nd level).\"\n )\n elif magnitude <= -1:\n result = \"Should the character sample an addictive substance, the Wisdom check to determine addiction is made with a -3 penalty.\"\n elif magnitude == 0:\n result = (\n \"A painful love affair has left the character emotionally toughened. \"\n + poss.capitalize()\n + \" Wisdom is treated as 2 points higher when resisting seduction.\"\n )\n elif magnitude == 1:\n result = \"Character has a +3 bonus on Wisdom checks to avoid addiction.\"\n elif magnitude == 2:\n result = \"Character is able to identify the exact time of day, to the half-hour, when out of doors.\"\n elif magnitude == 3:\n result = \"Character has the ability to counsel others, which will give them a +2 bonus on their next check/save against addiction, overcaution in combat, or gullibility.\"\n elif magnitude <= 5:\n result = \"The character's good will causes all hirelings and followers within five hexes to have +1 morale.\"\n elif magnitude == 6:\n xp = randint(6, 9) * 50\n if meets_bonus_xp_minimums(c[\"class\"], ability_scores(c)):\n c[\"XP\"] += xp\n result = f\"Character begins adventuring with {xp} XP.\"\n else:\n result = \"Character gains 10% bonus XP even though their ability scores don't meed the normal bonus thresholds.\"\n elif magnitude == 7:\n result = \"When the possibility arises, a successful save vs. poison will reveal to the character the location of a cursed item or location within 50 feet.\"\n elif magnitude <= 9:\n result = \"Character can detect secret and concealed doors. Merely passing within 10 feet gives a 1/6 chance to notice it; actively searching an area gives a 2/6 chance.\"\n elif magnitude == 10:\n secret = choice(\n [\n \"the location of hidden treasure\",\n \"the location of a shrine to a demon or obscure god\",\n \"the location of an area which is naturally magic\",\n ]\n )\n result = \"Character possesses secret knowledge: \" + secret + \".\"\n elif magnitude <= 12:\n result = \"One time per week, if an item worth less than 20 GP which could have been purchased at the last marketplace the character visited would now be useful, the character can retroactively purchase it.\"\n elif magnitude <= 15:\n result = \"Once per day, the character may ignore the effects of being stunned.\"\n elif magnitude == 16:\n bonus = randint(1, 3)\n result = (\n \"Character is very pious. All saves against fear and mind-affecting spells are made with a +\"\n + str(bonus)\n + \" bonus.\"\n )\n else:\n bonus = randint(2, 4)\n result = (\n \"Character is very pious. All saves against fear and mind-affecting spells are made with a +\"\n + str(bonus)\n + \" bonus.\"\n )\n return result\n\n\ndef make_sibling():\n age_diff = randint(1, 6)\n sibling = (\n choice([\"brother\", \"sister\"])\n + \" who is \"\n + str(age_diff)\n + \" years \"\n + choice([\"older\", \"younger\"])\n )\n return sibling\n\n\ndef get_siblings(num):\n if num == 0:\n return \"no siblings\"\n else:\n acc = []\n while num > 0:\n acc.append(make_sibling())\n num = num - 1\n res = \", \".join(acc)\n return res\n\n\ngrandparents = [\n \"paternal grandfather\",\n \"paternal grandmother\",\n \"maternal grandfather\",\n \"maternal grandmother\",\n]\n\n\ndef get_grandparents(num):\n if num == 0:\n return \"no grandparents\"\n if num == 4:\n return \"all grandparents\"\n else:\n res = \", \".join(sample(grandparents, num)) + \"\"\n return res\n\n\n# based on Strength\ndef family_composition(magnitude, c):\n result = \"\"\n if magnitude <= -7:\n result = \"Orphan. No known relatives.\"\n c[\"has family\"] = False\n elif magnitude <= -1:\n uncle = randint(0, 1)\n aunt = randint(0, 1)\n result_start = \"Few living relations: \"\n if uncle == 1 and aunt == 1:\n result = result_start + \"character has an aunt and uncle.\"\n elif uncle == 1:\n result = result_start + \"character has an uncle.\"\n elif aunt == 1:\n result = result_start + \"character has an aunt.\"\n else:\n roll = randint(2, 4)\n result = result_start + \"character has \" + str(roll) + \" cousins.\"\n elif magnitude == 0:\n relative = choice(\n [\"grandparents\"] * 3\n + [\"aunt and uncle\"] * 2\n + [\"grandfather\", \"grandmother\", \"aunt\", \"uncle\"]\n )\n mat_pat = choice([\"on father's side\", \"on mother's side\"])\n raised_by = relative + \" \" + mat_pat\n num_cousins = randint(1, 4) + randint(1, 4) - 2\n result = (\n \"Character raised by \"\n + (raised_by)\n + \". Number of first cousins: \"\n + str(num_cousins)\n + \".\"\n )\n elif magnitude == 1:\n parent = choice([\"father\", \"mother\"])\n has_grandparent = choice([True, False])\n if has_grandparent:\n grandparent = (\n choice([\"paternal\", \"maternal\"])\n + \" \"\n + choice([\"grandfather\", \"grandmother\"])\n )\n else:\n grandparent = \"no grandparents\"\n has_sibling = choice([True, False])\n if has_sibling:\n sib = make_sibling()\n else:\n sib = \"no siblings\"\n result = (\n \"Character raised by \" + parent + \". Has \" + grandparent + \"; \" + sib + \".\"\n )\n elif magnitude == 2:\n parents = choice([\"mother and father\", \"mother and father\", \"mother\", \"father\"])\n grands = get_grandparents(randint(0, 1))\n has_sib = choice([True, False])\n if has_sib:\n sib = make_sibling()\n else:\n sib = \"no siblings\"\n result = \"Character raised by \" + parents + \". Has \" + grands + \"; \" + sib + \".\"\n elif magnitude <= 4:\n grands = get_grandparents(randint(0, 3))\n numsibs = randint(0, 2) + randint(0, 2)\n sibs = get_siblings(numsibs)\n result = (\n \"Character raised by mother and father. Has \" + grands + \"; \" + sibs + \".\"\n )\n elif magnitude <= 6:\n grands = get_grandparents(randint(0, 4))\n numsibs = randint(1, 2) + randint(0, 2)\n sibs = get_siblings(numsibs)\n result = (\n \"Character raised by mother and father. Has \" + grands + \"; \" + sibs + \".\"\n )\n elif magnitude <= 8:\n grands = get_grandparents(randint(1, 4))\n numsibs = randint(1, 2) + randint(0, 2)\n sibs = get_siblings(numsibs)\n result = \"Character raised by mother and father. Has \" + grands + \"; \"\n elif magnitude <= 12:\n grands = get_grandparents(randint(2, 4))\n numsibs = randint(1, 2) + randint(0, 3)\n sibs = get_siblings(numsibs)\n result = (\n \"Character raised by mother and father. Has \" + grands + \"; \" + sibs + \".\"\n )\n elif magnitude <= 14:\n grands = get_grandparents(randint(2, 4))\n numsibs = randint(1, 3) + randint(0, 3)\n sibs = get_siblings(numsibs)\n result = (\n \"Character raised by mother and father. Has \" + grands + \"; \" + sibs + \".\"\n )\n else:\n grands = get_grandparents(randint(2, 4))\n numsibs = randint(1, 3) + randint(1, 3)\n sibs = get_siblings(numsibs)\n result = (\n \"Character raised by mother and father. Has \" + grands + \"; \" + sibs + \".\"\n )\n return result\n\n\n# based on Intelligence\ndef choices(magnitude, c):\n subj, obj, poss = get_gender_words(c[\"sex\"])\n result = \"\"\n which_half = choice([\"right\", \"left\"])\n if magnitude <= -16:\n result = (\n \"Character is missing lower half of \"\n + which_half\n + \" leg, and has a peg leg. One less AP than normal.\"\n )\n elif magnitude <= -14:\n result = \"Character is missing non-dominant hand. Cannot use two-handed weapons. Can choose hook-hand as a weapon proficiency, but does not start with one to use.\"\n elif magnitude == -13:\n result = (\n \"Character is missing \"\n + which_half\n + \" eye. Ranged weapons have additional attack penalty: -1 at close range, -3 at medium, -5 at long (total: -1/-5/-10)\"\n )\n elif magnitude == -12:\n years = randint(1, 8) + randint(1, 8) + randint(1, 8) + randint(1, 8)\n result = \"Character has spent \" + str(years) + \" miserable years in prison.\"\n c[\"added age\"][\"prison\"] = years\n elif magnitude == -11:\n years = randint(1, 6) + randint(1, 6) + randint(1, 6)\n result = \"Character has spent \" + str(years) + \" hard years in prison.\"\n c[\"added age\"][\"prison\"] = years\n elif magnitude == -10:\n years = randint(1, 4) + randint(1, 4)\n result = \"Character has spent \" + str(years) + \" years in prison.\"\n c[\"added age\"][\"prison\"] = years\n elif magnitude == -9:\n num = randint(1, 3)\n result = (\n \"Missing \"\n + str(num)\n + \" fingers on \"\n + which_half\n + \" hand. -2 on attack rolls when using that hand (including two-handed weapons.)\"\n )\n elif magnitude == -8:\n num = randint(2, 3)\n result = (\n \"Missing \"\n + str(num)\n + \" toes on \"\n + which_half\n + \" foot. -1 penalty on all Dexterity checks involving the feet.\"\n )\n elif magnitude == -7:\n months = randint(3, 9)\n if c[\"sex\"] == \"male\":\n result = (\n \"Character has fathered a child out of wedlock. The mother is \"\n + str(months)\n + \" months pregnant.\"\n )\n else:\n result = \"Character is pregnant and \" + str(months) + \" months along.\"\n elif magnitude == -6:\n result = (\n \"Character has been swindled of all money and possessions, leaving \"\n + obj\n + \" with only a shirt.\"\n )\n c[\"money modifier\"] = Decimal(0)\n elif magnitude == -5:\n result = \"Trust and generosity to family or others has left the character with little money.\"\n c[\"money modifier\"] *= Decimal(0.3)\n elif magnitude == -4:\n num_cigs = randint(1, 4)\n grams_per_oz = Decimal(28.3495)\n # grams per cigar, converted to oz to measure pipe tobacco\n tobacco = num_cigs * Decimal(2.5) / grams_per_oz\n num_beers = randint(1, 4)\n is_cig = choice([True, False])\n consequence = \"until the addiction is fed each day, the character's Wisdom will be treated as 50% normal, and other ability scores will be treated as 90% normal.\"\n if is_cig:\n result = (\n \"Character is addicted to \"\n + str(round(num_cigs))\n + \" cigar(s) per day (or \"\n + str(round(tobacco, 2))\n + \" oz pipe tobacco); \"\n + consequence\n )\n else:\n result = (\n \"Character is addicted to \"\n + str(num_beers)\n + \" beer(s) per day; \"\n + consequence\n )\n elif magnitude == -3:\n if c[\"sex\"] == \"male\":\n p = \"fathered\"\n else:\n p = \"mothered\"\n kid_gender = choice([\"son\", \"daughter\"])\n result = \"Character has \" + p + \" a bastard child, a \" + kid_gender + \".\"\n # todo prompt player to name the kid - one reason to return a structured result ... then PROCESS that result, including has_family checks, to give the final string...!\n # todo use he/his she/her instead of \"its (whereabouts)\"\n # todo when family has become a data structure, choose a family member to care for the child\n if c[\"has family\"]:\n result += \" Your family is caring for the child.\"\n else:\n result += \" You gave the child up as a foundling, and its whereabouts are unknown.\"\n elif magnitude == -2:\n result = (\n \"Gambling, waste, and foolishness has lost the character half \"\n + poss\n + \" money.\"\n )\n c[\"money modifier\"] *= Decimal(0.5)\n elif magnitude == -1:\n years = randint(2, 5)\n result = (\n \"A misspent youth cost the character \"\n + str(years)\n + \" extra years to finish training.\"\n )\n c[\"added age\"][\"misspent youth\"] = years\n elif magnitude == 0:\n scar = randint(3, 8)\n # todo choose where the scar is, or prompt player (or print a \"fill in the blank\" line!)\n result = (\n \"Character has a \"\n + str(scar)\n + \"-inch scar on a normally-covered part of \"\n + poss\n + \" body, received as a child during a moment of pure stupidity.\"\n )\n elif magnitude <= 2:\n result = \"Good luck has slightly increased the character's money.\"\n c[\"money modifier\"] *= Decimal(2)\n elif magnitude <= 4:\n result = \"Ability to play a musical instrument of the player's choosing.\"\n elif magnitude == 5:\n dir = choice([\"north\", \"south\", \"east\", \"west\"])\n result = (\n \"Distinguished effort has earned a writ of passage, free of tolls, between this kingdom and the nearest one to the \"\n + dir\n + \".\"\n )\n elif magnitude <= 7:\n result = (\n \"Prudence and savings have significantly increased the character's money.\"\n )\n c[\"money modifier\"] *= Decimal(3)\n elif magnitude <= 9:\n credit = (randint(1, 6) + randint(1, 6) + randint(1, 6)) * 50\n already_has = c.get(\"credit\")\n if already_has:\n c[\"credit\"][\"gp\"] += credit\n else:\n c[\"credit\"] = dict(gp=credit)\n result = \"Character possesses credit with the local merchant guild.\"\n elif magnitude <= 11:\n num = randint(4, 6)\n result = \"Prudence and savings have greatly increased the character's money.\"\n c[\"money modifier\"] *= Decimal(num)\n elif magnitude <= 13:\n num = randint(6, 9)\n result = \"Diligent effort has hugely increased the character's money.\"\n c[\"money modifier\"] *= Decimal(num)\n elif magnitude == 14:\n result = \"Character possesses a magic item.\"\n elif magnitude <= 16:\n num = randint(9, 12)\n result = \"Smart and frugal behavior has grown the character's money to an incredible degree.\"\n c[\"money modifier\"] *= Decimal(num)\n else:\n title = choice([\"an academic degree\", \"former advisor to the nobility\"])\n result = (\n \"Character has gained a title or honor through work done during training: \"\n + title\n + \". The character adds 2d4 points to one skill within \"\n + poss\n + \" 1st-level focus, representing the knowledge they cultivated to earn the title.\"\n )\n return result\n\n\n# based on Charisma, requires two magnitude rolls\ndef beauty(face_mag, body_mag, c):\n # to be added on to\n subj, obj, poss = get_gender_words(c[\"sex\"])\n\n def face_beauty():\n which_side = choice([\"right\", \"left\"])\n if face_mag <= -15:\n scar_length = randint(3, 7)\n scar_type = choice([\"a blade\", \"an animal bite\", \"an animal's claws\"])\n scar = (\n \"has \"\n + str(scar_length)\n + \"-inch scar across the face, received from \"\n + scar_type\n )\n choices = [\n scar,\n \"is missing \" + poss + \" \" + which_side + \" ear\",\n \"is missing \" + poss + \" nose\",\n \"has a distinctly misshapen head\",\n ]\n return choice(choices)\n elif face_mag <= -8:\n choices = [\n \"has a lazy \" + which_side + \" eye\",\n \"has a whiny, irritating voice\",\n \"has a crackly, annoying voice\",\n \"suffers from halitosis if teeth are not brushed 3 times daily\",\n \"has an always-runny nose\",\n \"has a greasy, oily face\",\n ]\n return choice(choices)\n elif face_mag <= -1:\n nose_problem = choice([\"bulbous\", \"squashed\", \"piggish\"])\n missing_teeth = randint(0, 1) + randint(1, 3)\n teeth_problem = choice([\"buck\", \"crooked\", str(missing_teeth) + \" missing\"])\n choices = [\n \"has bushy eyebrows\",\n \"has a caveman-like protruding brow\",\n \"has distinctly large ears\",\n \"has a \" + nose_problem + \" nose\",\n \"has \" + teeth_problem + \" teeth\",\n \"has acne scars\",\n \"has eyes which are unnervingly close together\",\n ]\n return choice(choices)\n elif face_mag <= 7:\n choices = [\n \"has a beautiful aquiline nose\",\n \"has attractively straight teeth\",\n \"has a clean and healthy complexion\",\n ]\n if c[\"sex\"] == \"male\":\n choices = choices + [\"has a strong chin\"]\n else:\n choices = choices + [\"has lovely full lips\"]\n return choice(choices)\n elif face_mag <= 13:\n choices = [\n \"perfectly-shaped, brilliantly white teeth\",\n \"marvelous high cheekbones\",\n ]\n if c[\"sex\"] == \"male\":\n choices = choices + [\"a deep, compelling voice\", \"a strong jawline\"]\n else:\n choices = choices + [\n \"a throaty, seductive voice\",\n \"charmingly delicate features\",\n ]\n return \"has \" + choice(choices)\n else:\n choices = [\n \"has a rich, velvety voice\",\n \"has dazzling eyes\",\n \"has a flawless complexion\",\n ]\n return choice(choices)\n\n def body_beauty():\n # redefine which_side so it can be different for face and body results\n which_side = choice([\"right\", \"left\"])\n if body_mag <= -16:\n burn_percent = randint(20, 80)\n return (\n \"has nasty burn scars covering \"\n + str(burn_percent)\n + \"% of \"\n + poss\n + \" body\"\n )\n elif body_mag <= -14:\n scar_length = randint(2, 6)\n scar_place = choice(\n [which_side + \" cheek\", \"chin\", \"throat\", \"nose\", \"forehead\"]\n )\n scar = (\n \"has a \"\n + str(scar_length)\n + \"-inch scar across \"\n + poss\n + \" \"\n + scar_place\n )\n choices = [\n scar,\n \"gives off a nasty, unwashable odor\",\n \"has lumpy limbs\",\n \"has a misshapen torso\",\n \"is a hunchback\",\n ]\n return choice(choices)\n elif body_mag <= -8:\n scar_length = randint(1, 3)\n scar_place = choice(\n [which_side + \" arm\", which_side + \" hand\", \"scalp\", \"chin\"]\n )\n scar = (\n \"has a \"\n + str(scar_length)\n + \"-inch scar across \"\n + poss\n + \" \"\n + scar_place\n )\n choices = [\n scar,\n \"is bow-legged\",\n \"is knock-kneed\",\n \"moves with an awkward, loping gait\",\n \"has a sunken chest\",\n ]\n return choice(choices)\n elif body_mag <= -1:\n choices = [\n \"has a weak \" + which_side + \" leg and walks with a pronounced limp\",\n \"has a swayback\",\n \"has a overlong torso with stumpy legs\",\n ]\n return choice(choices)\n elif body_mag == 0:\n foot_kind = choice(\n [\n \"very small feet (-5% footwear cost)\",\n \"small feet\",\n \"large feet\",\n \"very large feet (+5% footwear cost)\",\n ]\n )\n freckle_count = choice([\"scattered\", \"many\", \"excessive\"])\n choices = [\"has \" + foot_kind, \"has \" + freckle_count + \" freckles\"]\n return choice(choices)\n elif body_mag <= 7:\n choices = [\n \"gives off a pleasant body odor\",\n \"has well-proportioned legs and arms\",\n \"has an elegant neck\",\n \"has healthy, glossy hair\",\n ]\n return choice(choices)\n elif body_mag <= 13:\n if c[\"sex\"] == \"male\":\n choices = [\n \"has large, muscular shoulders\",\n \"has a broad, muscular back\",\n \"has large, muscular arms\",\n \"has large, muscular legs\",\n \"has a six-pack\",\n ]\n else:\n choices = [\n \"has a six-pack\",\n \"has large, powerful thighs\",\n \"has a narrow waist\",\n \"has wide, curvy hips\",\n ]\n return choice(choices)\n else:\n choices = [\n \"has radiant skin\",\n \"has luxurious hair\",\n \"always has perfect posture\",\n ]\n return choice(choices)\n\n # putting it all together\n face_result = \"Character \" + face_beauty()\n body_result = \", and also \" + body_beauty()\n result = face_result + body_result + \".\"\n return result\n\n\n# helper for health_detail\ndef get_health_condition(roll, sex):\n # the higher the number, the more severe the condition\n # the idea is to use these with a random roll in the specified range\n subj, obj, poss = get_gender_words(sex)\n if roll <= 2:\n return \"Motion sickness: repeated waves of nausea and vomiting will occur with the rhythmic motion of any vehicle.\"\n elif roll <= 4:\n return \"Flaring pain in joints: character finds outdoor travel difficult, and will suffer an extra point of damage each day when traveling.\"\n elif roll <= 6:\n return \"Low tolerance for alcohol: character takes 1d3 damage for each 8 ounces consumed.\"\n elif roll <= 8:\n return \"Skin chafes easily: while armored, character will suffer 1 damage per two hours spent walking or riding.\"\n elif roll <= 10:\n return \"Weak stomach: character will suffer 1 point of damage per pound of food eaten which is raw or unprocessed.\"\n elif roll == 11:\n return \"Muscle pulls: after each combat, character must save vs. explosion or suffer a -1 penalty to attacks for 3 days due to a pulled muscle. Multiple occurrences stack up to -3.\"\n elif roll == 12:\n colors = choice([[\"red\", \"orange\", \"green\"], [\"blue\", \"purple\", \"black\"]])\n sentence_tail = \", \".join(colors)\n return (\n \"Color confusion: character cannot distinguish between \"\n + sentence_tail\n + \".\"\n )\n elif roll == 13:\n return \"Total color blindness: character cannot distinguish between any colors of the spectrum. Everything appears to be in shades of gray. Ranged attack distance penalties are doubled.\"\n elif roll <= 15:\n return \"Tone deafness: character cannot distinguish chords of sound, and thus receives neither positive nor negative effects of music.\"\n elif roll == 16:\n return \"Chronic migraines: each day, the character has a 1 in 20 chance of being -4 to hit and -3 to saves and ability checks.\"\n elif roll <= 18:\n return (\n \"Mild hemorrhaging: if character receives a bleeding wound, \"\n + subj\n + \" will bleed 1 extra HP per round. If bandages are used, character's wounds must be bound twice in order to stop the bleeding.\"\n )\n elif roll == 19:\n return \"Shortened breath: character is unable to run for more than two rounds. If any strenuous activity (such as combat) continues for more than 10 rounds, the character must succeed at a save vs. poison or else be struck with a coughing spasm, incapacitating them for 1 round (counts as stunned) and causing 3d4 damage.\"\n elif roll == 20:\n return \"Brittle bones: all falling damage dice for the character are increased by one step (e.g. d6 -> d8).\"\n elif roll == 21:\n return \"Cataracts: character cannot make out any detail further away than 60 feet, and cannot target attacks or spells beyond that range.\"\n elif roll == 22:\n return (\n \"Mild hemorrhaging: if character receives a bleeding wound, \"\n + subj\n + \" will bleed 2 extra HP per round. If bandages are used, character's wounds must be bound three times in order to stop the bleeding.\"\n )\n elif roll == 23:\n return \"Complete deafness: character cannot hear any sound at all, and will be unable to respond to or be affected by sound. Character can still sense vibration.\"\n elif roll == 24:\n return \"Oversensitive skin: due to extreme discomfort, character cannot wear any kind of armor.\"\n elif roll == 25:\n return \"Temporary demonic possession: while talking to strangers, character may suddenly lapse into abusive outbursts. 1 in 20 chance per round.\"\n elif roll <= 27:\n return \"Weak heart: if reduced to -6 or fewer HP, character must make save vs. poison or suffer a heart attack and die.\"\n elif roll == 28:\n return (\n \"Ghastly hemorrhaging: if character receives a bleeding wound, \"\n + subj\n + \" she will bleed 3 extra HP per round. If bandages are used, character's wounds must be bound four times in order to stop the bleeding.\"\n )\n elif roll == 29:\n return \"Blindness: character cannot see at all, and is altogether unable to sense light. Chief among the consequences is that all attacks are treated as if attacking invisible creatures (-8 normally, -6 if someone spends 1 AP/turn helping to direct your strikes) and that all missile/thrown attacks which miss can cause friendly fire, in any direction.\"\n else:\n return \"Crippled legs: while the character's legs appear whole and undamaged, they are in fact entirely without feeling or strength. The character cannot walk under their own power.\"\n\n\ndef robustness(magnitude, c):\n subj, obj, poss = get_gender_words(c[\"sex\"])\n # get 4 health conditions, each with different possibilities of being mild or severe\n condition4 = get_health_condition(randint(24, 30), c[\"sex\"])\n condition3 = get_health_condition(randint(16, 24), c[\"sex\"])\n condition2 = get_health_condition(randint(8, 16), c[\"sex\"])\n condition1 = get_health_condition(randint(1, 8), c[\"sex\"])\n result = \"\"\n if magnitude <= -16:\n result = condition4\n elif magnitude <= -12:\n result = condition3\n elif magnitude <= -7:\n result = condition2\n elif magnitude <= -1:\n result = condition1\n elif magnitude == 0:\n num_days = randint(7, 14)\n result = (\n \"Character is suffering from a severe cold at the start of the campaign. For the next \"\n + str(num_days)\n + \" days, character will be -1 to attack and damage.\"\n )\n elif magnitude == 1:\n result = \"+1 save vs poison.\"\n elif magnitude == 2:\n result = \"+1 save vs crushing.\"\n elif magnitude == 3:\n result = \"+1 save vs explosion.\"\n elif magnitude == 4:\n result = \"+1 save vs magic.\"\n elif magnitude == 5:\n source = choice([\"snake or reptile\", \"insect\"])\n result = (\n \"Character is resistant against \"\n + source\n + \" poison/venom. Damage is reduced by 50%.\"\n )\n elif magnitude == 6:\n source = choice([\"marine creature\", \"spider\"])\n result = (\n \"Character is resistant against \"\n + source\n + \" poison/venom. Damage is reduced by 50%.\"\n )\n elif magnitude <= 8:\n result = \"Character heals 1 extra HP from a day's rest.\"\n elif magnitude == 9:\n result = \"+2 save vs poison.\"\n elif magnitude == 10:\n result = \"+2 save vs crushing.\"\n elif magnitude == 11:\n result = \"+2 save vs explosion.\"\n elif magnitude == 12:\n result = \"+2 save vs magic.\"\n elif magnitude <= 14:\n result = \"Character heals 2 extra HP from a day's rest.\"\n elif magnitude <= 16:\n result = \"+1 to all saves.\"\n else:\n result = \"+2 to all saves.\"\n return result\n\n\n# governed by Dex\ndef agility_coordination(magnitude, c):\n subj, obj, poss = get_gender_words(c[\"sex\"])\n which_side = choice([\"right\", \"left\"])\n result = \"\"\n if magnitude <= -17:\n result = (\n \"Fused bones in the character's \"\n + which_side\n + \" leg causes a severe, dragging limp. Normal AP is reduced by 2.\"\n )\n elif magnitude == -16:\n result = (\n \"Character must save vs crushing before drawing a weapon; failure indicates \"\n + subj\n + \" cannot do it this round. No save is needed for subsequent attempts for the same weapon in the same combat.\"\n )\n elif magnitude == -15:\n result = (\n \"Character's \"\n + which_side\n + \" hand is deformed and useless. Opposite hand is dominant.\"\n )\n elif magnitude == -14:\n result = (\n \"Character's \"\n + which_side\n + \" foot is deformed, and \"\n + subj\n + \" has a permanent limp. Normal movement is reduced by 1.\"\n )\n elif magnitude == -13:\n result = (\n \"Character suffers from severe vertigo. If \"\n + subj\n + \" gets within 5 feet of a drop that is at least 15 feet, \"\n + subj\n + \" will fall unconscious for five minutes. Once awakened, \"\n + subj\n + \" will be nauseated for 2d4 rounds.\"\n )\n elif magnitude == -12:\n result = (\n \"Each time the character moves among delicate objects, including in a marketplace, \"\n + subj\n + \" must make a save vs. explosion to avoid accidentally breaking something.\"\n )\n elif magnitude == -11:\n result = (\n \"Character is wholly unable to ride any mount of any kind, regardless of \"\n + poss\n + \" character class.\"\n )\n elif magnitude == -10:\n result = \"Character is unable to use two-handed weapons or weapons which strike further away than five feet.\"\n elif magnitude == -9:\n result = \"Character is incapable of loading or working any kind of bow, crossbow, or similar mechanical device.\"\n elif magnitude == -8:\n num = randint(1, 2)\n result = (\n \"Character suffers a -\"\n + str(num)\n + \" penalty to hit with all ranged weapons.\"\n )\n elif magnitude == -7:\n result = (\n \"Character requires triple normal time to mount or dismount from an animal.\"\n )\n elif magnitude == -6:\n result = \"Character's armor class has a penalty of 2 when moving at a speed above normal.\"\n elif magnitude == -5:\n result = \"Character requires 3 more AP than normal to load any bow.\"\n elif magnitude == -4:\n result = \"If character causes friendly fire, it is 50% likely to be in ANY direction.\"\n elif magnitude == -3:\n result = \"Character's clumsiness means that dropped weapons will break on 2 in 6 instead of 1 in 6.\"\n elif magnitude == -2:\n result = \"Character requires 1 more AP than normal to draw any weapon.\"\n elif magnitude == -1:\n result = (\n \"Character suffers from mild vertigo. If \"\n + subj\n + \" gets within 5 feet of a drop that is at least 15 feet, \"\n + subj\n + \" will become somewhat nauseated and suffer a -1 to hit. Nausea passes 1 round after moving away.\"\n )\n elif magnitude == 0:\n num = randint(1, 20)\n if num <= 18:\n how_hurt = \"maimed\"\n else:\n how_hurt = \"killed\"\n result = (\n \"Through accidental clumsiness, the character caused a family member to be \"\n + how_hurt\n + \".\"\n )\n elif magnitude == 1:\n result = \"Character requires no AP to draw a weapon weighing 2 lbs or less.\"\n elif magnitude == 2:\n result = \"Character requires no AP to draw a weapon weighing 3 lbs or less.\"\n elif magnitude == 3:\n result = \"The character's penalty for attacks at long range is lessened by 1.\"\n elif magnitude == 4:\n result = (\n \"Character automatically takes a defensive stance when surprised, improving \"\n + poss\n + \" AC by 1 until no longer surprised.\"\n )\n elif magnitude <= 6:\n result = (\n \"Character is quick to find an opening in enemy defenses. \"\n + subj.capitalize()\n + \" has an extra +1 modifier to hit opponents from the flank or rear.\"\n )\n elif magnitude == 7:\n result = \"Friendly fire committed by this character is ignored if the affected ally is within 20 feet.\"\n elif magnitude == 8:\n result = \"Character has a talent for cheating at cards; base 20% chance plus more favorable of: 2% per point of Dex OR (if a thief) 1/2 of pickpocketing success target.\"\n elif magnitude == 9:\n result = \"The character's penalty for attacks at both medium and long ranges is lessened by 1.\"\n elif magnitude == 10:\n result = \"Character can climb poles and free-hanging ropes as if climbing an ordinary wall.\"\n elif magnitude == 11:\n if c[\"class\"] == \"thief\":\n result = \"Character notices traps as if one level higher.\"\n else:\n result = \"Character has a 15% chance to notice traps.\"\n elif magnitude == 12:\n result = (\n \"Character can catch and handle ordinary snakes if \"\n + subj\n + \" successfully saves vs. poison (with a +4 bonus.)\"\n )\n elif magnitude == 13:\n num = randint(1, 2)\n if num == 1:\n result = (\n \"Character gains \"\n + obj\n + \" a +1 bonus to hit with bolas, sling, and other weapons which are spun before throwing.\"\n )\n else:\n result = \"Character is +1 to hit with any weapon or object which has a splash effect, including certain orb spells.\"\n elif magnitude == 14:\n result = \"Character requires no AP to draw a weapon weighing 5 lbs or less.\"\n elif magnitude == 15:\n result = \"Character requires no AP to draw any weapon.\"\n elif magnitude == 16:\n body_part = choice([\"hip\", \"shoulder\"])\n result = (\n \"Character can dislocate \"\n + poss\n + \" \"\n + which_side\n + \" \"\n + body_part\n + \" at will, though doing so causes 1d4 damage.\"\n )\n else:\n # todo \"with no penalties whatsoever - as if climbing an ordinary wall.\"\n result = \"Character can climb poles and free-hanging ropes, and walk tightropes, as if climbing an ordinary wall.\"\n return result\n\n\ndef is_leap_year(year):\n if (year % 4) != 0:\n return False\n else:\n if (year % 400) == 0:\n return True\n else:\n if (year % 100) == 0:\n return False\n else:\n # divisible by 4; not a 100 or 400 special case\n return True\n\n\ndef birthday(age, current_year=1650):\n # TODO clean this ancient noob-designed function up\n # TODO fix off by one error with birth_year (its either one year too high or too low; the fix is to pass current_day to birthday() -- or use aproper datetime handling function FFS! I'm sure Python datetime library can convert from ordinal day number to date of the year!!!!\n birth_year = (current_year - age) + 1\n if is_leap_year(current_year):\n feb_length = 29\n else:\n feb_length = 28\n end_january = 31\n end_february = feb_length + end_january\n end_march = 31 + end_february\n end_april = 30 + end_march\n end_may = 31 + end_april\n end_june = 30 + end_may\n end_july = 31 + end_june\n end_august = 31 + end_july\n end_september = 30 + end_august\n end_october = 31 + end_september\n end_november = 30 + end_october\n end_december = 31 + end_november\n month_ends = [\n end_january,\n end_february,\n end_march,\n end_april,\n end_may,\n end_june,\n end_july,\n end_august,\n end_september,\n end_october,\n end_november,\n end_december,\n ]\n month_names = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n ]\n # initialize the two-way correspondence between final ordinal day of year,\n # and name of the month whose last day is that day of the year\n month_relations = {}\n for x in range(0, len(month_names)):\n n = month_names[x]\n end = month_ends[x]\n month_relations[n] = end\n month_relations[end] = n\n\n # end_december is also the number of days in this year\n day_of_the_year = randint(1, end_december)\n\n birthday_month_day = \"\"\n for end in month_ends:\n if day_of_the_year <= end:\n m = month_relations[end]\n d = end - day_of_the_year + 1\n # the extra 1 added to d is so that days are number 1 to end, instead of 0 to (end-1)\n birthday_month_day = m + \" \" + str(d)\n break\n else:\n pass\n\n return \", \".join([birthday_month_day, str(birth_year)])\n\n\nhair_colors = [\"black\"] * 40 + [\"brown\"] * 30 + [\"blonde\"] * 20 + [\"red\"] * 10\n\n\ndef get_base_hair_color():\n return choice(hair_colors)\n\n\ndef adjust_hair_color_for_aging(base_hair_color, age, constitution):\n aging = randint(1, 100) # lower is better\n hair = namedtuple(\"hair\", [\"color\", \"description\"])\n base_case = hair(base_hair_color, \"\")\n if age <= 20:\n return base_case\n elif age <= 29:\n if aging > 7 * constitution:\n return hair(base_hair_color, \"prematurely graying\")\n else:\n return base_case\n elif age <= 39:\n if aging > 6 * constitution:\n return hair(base_hair_color, \"graying\")\n else:\n return base_case\n elif age <= 49:\n if aging > 5 * constitution:\n return hair(\"gray\", \"was once \" + base_hair_color)\n else:\n return base_case\n elif age <= 59:\n if aging > 4 * constitution:\n return hair(\"gray\", \"was once \" + base_hair_color)\n else:\n return hair(base_hair_color, \"graying\")\n else:\n # hair is always gray at age 60 and higher\n return hair(\"gray\", \"was once \" + base_hair_color)\n\n\ndef hair_status_after_aging(age, constitution, sex):\n aging = randint(1, 100) # lower is better\n\n if sex == \"male\":\n if age <= 20:\n return \"\"\n elif age <= 29:\n if aging > 7 * constitution:\n return \"bald\"\n if aging > 6 * constitution:\n return \"thinning\"\n else:\n return \"\"\n elif age <= 39:\n if aging > 6 * constitution:\n return \"bald\"\n elif aging > 5 * constitution:\n return \"thinning\"\n else:\n return \"\"\n elif age <= 49:\n if aging > 5 * constitution:\n return \"bald\"\n elif aging > 4 * constitution:\n return \"thinning\"\n else:\n return \"\"\n elif age <= 59:\n if aging > 3 * constitution:\n return \"bald\"\n elif aging > 2 * constitution:\n return \"thinning\"\n else:\n return \"\"\n else:\n if aging > 2 * constitution:\n return \"bald\"\n elif aging > constitution:\n return \"thinning\"\n else:\n return \"\"\n else:\n # sex is female\n hair_if_male = hair_status_after_aging(age - 10, constitution, \"male\")\n if hair_if_male == \"bald\":\n if aging > 10 * constitution:\n return \"bald\"\n else:\n return \"wispy\"\n else:\n return hair_if_male\n\n\ndef get_eye_color(base_hair_color):\n score = randint(1, 100)\n if base_hair_color == \"black\":\n if score < 40:\n return \"brown\"\n elif score < 80:\n return \"black\"\n else:\n return \"green\"\n\n elif base_hair_color == \"red\":\n if score < 50:\n return \"green\"\n else:\n return \"blue\"\n\n elif base_hair_color == \"blonde\":\n if score < 50:\n return \"blue\"\n elif score < 75:\n return \"green\"\n else:\n return \"brown\"\n\n else:\n # base_hair is brown\n if score < 15:\n return \"blue\"\n elif score < 35:\n return \"green\"\n elif score < 60:\n return \"brown\"\n else:\n return \"black\"\n\n\ndef make_final_hair(base_hair, age, con, sex):\n hair_data = namedtuple(\"hair\", [\"haircolor\", \"hairdesc\", \"haircond\"])\n hair_color_adj = adjust_hair_color_for_aging(base_hair, age, con)\n hair_level_adj = hair_status_after_aging(age, con, sex)\n if hair_level_adj == \"bald\":\n return hair_data(\"bald\", \"was once \" + base_hair, \"\")\n else:\n return hair_data(\n hair_color_adj.color, hair_color_adj.description, hair_level_adj\n )\n\n\ndef profession_strength():\n \"\"\"Return a Strength-based profession.\"\"\"\n roll = randint(1, 100)\n if roll <= 20:\n return \"farmer\"\n elif roll <= 40:\n return \"fisherman\"\n elif roll <= 55:\n return \"sailor\"\n elif roll <= 70:\n return \"teamster\"\n elif roll <= 75:\n return \"guardsman\"\n elif roll <= 80:\n return \"mercenary\"\n elif roll <= 85:\n return \"outrider\"\n elif roll <= 90:\n return \"bounty hunter\"\n elif roll <= 95:\n return \"gladiator\"\n else:\n return \"weapon master\"\n\n\nartisans_food = [\n \"brewer\",\n \"vintner\",\n \"baker\",\n \"chandler\",\n \"confectioner\",\n \"butcher\",\n \"tobacconist\",\n]\n\nartisans_textiles = [\n \"tailor\",\n \"draper\",\n \"fuller\",\n \"weaver\",\n \"furrier\",\n \"tanner\",\n \"leatherworker\",\n \"cobbler\",\n]\n\nartisans_wood = [\n \"cooper\",\n \"wainwright\",\n \"shipwright\",\n \"furniture maker\",\n \"instrument maker\",\n \"papermaker\",\n \"bookbinder\",\n]\n\nartisans_minerals = [\"potter\", \"glassmaker\", \"glazier\", \"sculptor\"]\n\nartisans_metals = [\n \"smelter\",\n \"jeweller\",\n \"lapidary\",\n \"toolmaker\",\n \"diemaker\",\n \"engraver\",\n]\n\nall_artisans = artisans_food\nall_artisans.extend(artisans_textiles)\nall_artisans.extend(artisans_wood)\nall_artisans.extend(artisans_minerals)\nall_artisans.extend(artisans_metals)\n\n\ndef profession_dexterity():\n \"\"\"Return a Dexterity-based profession.\"\"\"\n roll = randint(1, 100)\n if roll <= 90:\n selected = choice(all_artisans)\n return selected\n elif roll <= 94:\n return \"juggler\"\n elif roll <= 98:\n return \"gambler\"\n else:\n return \"monk\"\n\n\ndef profession_constitution():\n \"\"\"Return a Constitution-based profession.\"\"\"\n roll = randint(1, 100)\n if roll <= 5:\n return \"laborer\"\n if roll <= 10:\n return \"rat catcher\"\n elif roll <= 15:\n return \"grave robber\"\n elif roll <= 25:\n return \"porter\"\n elif roll <= 35:\n return \"bricklayer\"\n elif roll <= 45:\n return \"drover\"\n elif roll <= 55:\n return \"miner\"\n elif roll <= 60:\n return \"hermit\"\n elif roll <= 68:\n return \"blacksmith\"\n elif roll <= 76:\n return \"armorer\"\n elif roll <= 84:\n return \"weaponsmith\"\n elif roll <= 92:\n return \"mine foreman\"\n else:\n return \"explorer\"\n\n\ndef profession_intelligence():\n roll = randint(1, 100)\n if roll <= 10:\n return \"trapper\"\n elif roll <= 15:\n return \"scribe\"\n elif roll <= 20:\n return \"alchemist's assistant\"\n elif roll <= 25:\n return \"boatman\"\n elif roll <= 30:\n return \"gamekeeper\"\n elif roll <= 35:\n return \"carpenter\"\n elif roll <= 40:\n return \"stonemason\"\n elif roll <= 45:\n return \"tinker\"\n elif roll <= 49:\n return \"bookkeeper\"\n elif roll <= 51:\n return \"tomb robber\"\n elif roll <= 55:\n return \"artillerist\"\n elif roll <= 59:\n return \"cartographer\"\n elif roll <= 63:\n return \"veterinarian\"\n elif roll <= 67:\n return \"hospitaler\"\n elif roll <= 71:\n return \"architect\"\n elif roll <= 75:\n return \"spy\"\n elif roll <= 80:\n return \"mage's apprentice\"\n elif roll <= 85:\n return \"lawyer\"\n elif roll <= 90:\n return \"alchemist\"\n elif roll <= 97:\n return \"spymaster\"\n else:\n return \"political advisor\"\n\n\ndef profession_wisdom():\n roll = randint(1, 100)\n if roll <= 15:\n return \"husbandman\"\n elif roll <= 25:\n return \"prospector\"\n elif roll <= 30:\n return \"herbalist\"\n elif roll <= 39:\n return \"tutor\"\n elif roll <= 48:\n return \"surgeon's apprentice\"\n elif roll <= 57:\n return \"librarian\"\n elif roll <= 66:\n return \"priest\"\n elif roll <= 75:\n return \"steward\"\n elif roll <= 84:\n return \"village healer\"\n elif roll <= 88:\n return \"priest\"\n elif roll <= 92:\n return \"mortician\"\n elif roll <= 87:\n return \"witch hunter\"\n elif roll <= 91:\n return \"professor\"\n elif roll <= 96:\n return \"ecclesiastical vicar\"\n else:\n return \"ecclesiastial rector\"\n\n\n# creative_artists = [\"painter\", \"illustrator\", \"engraver\", \"sculptor\"]\n# performance_artists = [\"mime\", \"jester\", \"clown\", \"monologist\"]\n# literary_artists = [\"poet\", \"author\"]\n\n\ndef profession_charisma():\n roll = randint(1, 1000)\n if roll <= 450:\n return choice([\"dancer\", \"singer\"])\n elif roll <= 550:\n return \"landlord\"\n elif roll <= 625:\n return \"buccaneer\"\n elif roll <= 700:\n return \"innkeeper\"\n elif roll <= 775:\n return \"usurer\"\n elif roll <= 800:\n return \"fence\"\n elif roll <= 875:\n return \"hitman\"\n elif roll <= 950:\n return \"banker\"\n elif roll <= 960:\n return \"squire\"\n elif roll <= 965:\n return \"knight\"\n elif roll <= 970:\n return \"guildmaster \" + choice(choice(all_artisans))\n elif roll <= 975:\n return \"landless noble\"\n elif roll <= 980:\n return \"crusader\"\n elif roll <= 985:\n return \"marshal\"\n elif roll <= 990:\n return \"lesser noble\"\n elif roll <= 994:\n return \"middle noble\"\n elif roll <= 998:\n return \"greater noble\"\n else:\n return \"royalty\"\n\n\nfixed_results = {\n \"farmer\": \"can raise crops; DR 1 vs ice/cold\",\n \"fisherman\": \"have Fishing skill\",\n # fisherman and other \"have X skill\" results may also need to include \"(amateur)\"\n \"sailor\": \"can handle rowboats and crew ships; +1 on checks/saves to keep balance\",\n \"teamster\": \"have Teamstering skill; party's pack animals have +1 morale\",\n \"guard\": \"only need 6 hrs of sleep per night; +1 awareness radius\",\n \"mercenary\": \"gain bonus weapon proficiency\",\n \"cavalier\": \"can ride a warhorse\",\n \"bounty hunter\": \"have Tracking skill (from Scouting study)\",\n \"gladiator\": \"+1 damage against all humanoids\",\n \"weapon master\": \"bonus weapon proficiency: any weapon; +1 damage with that kind of weapon\",\n \"baker\": \"DR 1 vs heat/fire\",\n \"chandler\": \"DR 1 vs heat/fire\",\n \"confectioner\": \"DR 1 vs heat/fire\",\n \"butcher\": \"+1 on attacks with dagger\",\n \"tobacconist\": \"+1 on checks/saves to stave off nausea (usually saves vs poison)\",\n \"tailor\": \"party's cloth goods have +2 on saves\",\n \"draper\": \"party's cloth goods have +2 on saves\",\n \"weaver\": \"party's cloth goods have +2 on saves\",\n \"furrier\": \"party's leather goods have +2 on saves\",\n \"tanner\": \"party's leather goods have +2 on saves\",\n \"leatherworker\": \"party's leather goods have +2 on saves\",\n \"cobbler\": \"party's leather goods have +2 on saves\",\n \"cooper\": \"party's wooden goods have +2 on saves\",\n \"wainwright\": \"party's wooden goods have +2 on saves\",\n \"shipwright\": \"party's wooden goods have +2 on saves\",\n \"furniture maker\": \"party's wooden goods have +2 on saves\",\n \"instrument maker\": \"pick an instrument: you can play that instrument. Crafting skill aplies only to this kind of instrument\",\n \"potter\": \"strong grip gives 5% bonus when climbing\",\n \"glassmaker\": \"DR 1 vs heat/fire\",\n \"glazier\": \"DR 1 vs heat/fire\",\n \"smelter\": \"DR 1 vs heat/fire\",\n \"jeweller\": \"appraise gems and jewelry within 25% of actual value\",\n \"lapidary\": \"appraise gems and jewelry within 25% of actual value\",\n \"toolmaker\": \"appraise metal goods within 25% of actual value\",\n \"diemaker\": \"appraise metal goods within 25% of actual value\",\n \"engraver\": \"appraise metal goods within 25% of actual value\",\n \"juggler\": \"while concentrating, can juggle 3 objects (0.25 to 1.5 lb each); +1 on attacks with thrown weapons\",\n \"gambler\": \"can palm an unattended or held item (weight <= 2 oz) into sleeve or pocket\",\n \"monk\": \"+1 natural AC\",\n \"rat catcher\": \"+1 save vs poison\",\n \"grave robber\": \"+1 attack vs undead\",\n \"drover\": \"reduce daily travel damage by 1 point\",\n \"alchemist's assistant\": \"+1 save vs explosion\",\n \"blacksmith\": \"party's metal goods have +2 on saves\",\n \"armorer\": \"party's armor has +1 on saves\",\n \"weaponsmith\": \"party's armor has +1 on saves\",\n \"mine foreman\": \"have Prospecting skill; know direction underground\",\n \"trapper\": \"have Hunting skill\",\n \"hermit\": \"have Foraging skill\",\n \"tinker\": \"have Tinkering skill\",\n \"carpenter\": \"design wooden structures; party's wooden goods have +2 on saves\",\n \"stonemason\": \"design stone structures; party's stone goods have +2 on saves\",\n \"boatman\": \"can handle rowboats and navigate rivers; +1 on checks/saves to keep balance\",\n \"gamekeeper\": \"+1 attack vs animals; have Hunting skill\",\n \"tomb robber\": \"possess a magic item\",\n \"artillerist\": \"gain weapon proficiency with one of: cannon, ballista, catapult, trebuchet\",\n \"veterinarian\": \"improve recovery of 3 resting animals by +2 HP/day\",\n \"hospitaler\": \"improve recovery of 2 resting people by +2 HP/day\",\n \"bookkeeper\": \"have Business Dealing skill\",\n \"spy\": \"have Passing Through skill\",\n \"husbandman\": \"have Herding skill\",\n \"prospector\": \"have Prospecting skill\",\n \"herbalist\": \"have Floriculture skill\",\n \"surgeon's apprentice\": \"have Binding Wounds skill\",\n \"priest\": \"can Turn Undead as if having 5 pts in Dweomercraft\",\n \"steward\": \"+1 morale for followers and hirelings\",\n \"village healer\": \"can cast a random 1st level druid or cleric spell\",\n \"mortician\": \"can embalm corpses; +1 on attacks vs undead\",\n \"witch hunter\": \"can Turn Undead as if having 10 pts in Dweomercraft; +1 save vs magic\",\n \"dancer\": \"perform war dance for up to 5 rounds/day; all sighted allies within 60 feet gain +1 attack and morale\",\n \"singer\": \"sing martial chants for up to 5 rounds/day; all non-deaf allies within 60 feet gain +1 attack and morale\",\n \"innkeeper\": \"begin game in possession of one-story house currently serving as an inn\",\n \"fence\": \"have black market connections in nearest market town\",\n \"hitman\": \"assassinate as a 1st level assassin\",\n \"landless noble\": \"hold noble title\",\n}\n\n\ndef legacy(c, prof):\n if prof == \"peasant\":\n return \"nothing\"\n ownership_roll = randint(1, 4)\n ownership = (\n \"these lands belong to you personally\"\n if ownership_roll == 4\n else \"these lands can only belong to you if both your parents, and any siblings older than you, have died\"\n )\n if prof == \"usurer\":\n credit = 200 * randint(1, 4)\n already_has = c.get(\"credit\")\n if already_has:\n c[\"credit\"][\"gp\"] += credit\n else:\n c[\"credit\"] = dict(gp=credit)\n return \"possess credit\"\n elif prof == \"banker\":\n credit = 100 * randint(4, 16)\n already_has = c.get(\"credit\")\n if already_has:\n c[\"credit\"][\"gp\"] += credit\n else:\n c[\"credit\"] = dict(gp=credit)\n return \"possess credit\"\n elif prof == \"cavalier\" and c[\"class\"] in martial_classes:\n return \"gain bonus weapon proficiency: one of flail, warhammer, or battleaxe\"\n elif prof == \"bounty hunter\" and c[\"class\"] == \"ranger\":\n return \"gain bonus weapon proficiency: any missile or throwing weapon\"\n elif prof in all_artisans:\n result = (\n \"create, identify, and repair \"\n + prof\n + \" products; \"\n + fixed_results.get(prof, \"\")\n )\n if prof in [\"bookbinder\", \"papermaker\"]:\n c[\"literate\"] = True\n result = result + \"; literacy\"\n return result\n elif prof == \"laborer\":\n c[\"encumbrance modifier\"] += Decimal(0.05)\n return \"increase max encumbrance by 5%\"\n elif prof == \"porter\":\n c[\"encumbrance modifier\"] += Decimal(0.1)\n return \"increase max encumbrance by 10%\"\n elif prof == \"explorer\":\n c[\"literate\"] = True\n return \"literacy; knowledge of a distant region; bonus weapon proficiency with unusual weapon from that region\"\n elif prof == \"scribe\":\n c[\"literate\"] = True\n return (\"literacy; gain additional knowledge field\",)\n elif prof == \"alchemist\":\n c[\"literate\"] = True\n return \"literacy; have Amateur status in Alchemy\"\n elif prof == \"cartographer\":\n c[\"literate\"] = True\n return \"literacy; have Locate Self skill\"\n elif prof == \"architect\":\n c[\"literate\"] = True\n return \"literacy; design structures; +1 attack and +10% damage if directing artillery fire\"\n elif prof == \"lawyer\":\n c[\"literate\"] = True\n return \"literacy; have Solicitor skill\"\n elif prof == \"mage's apprentice\":\n c[\"literate\"] = True\n return \"literacy; can cast a random 1st level mage or illusionist spell\"\n elif prof == \"political advisor\":\n c[\"literate\"] = True\n return \"literacy; +10% reaction bonus on any group of three or more people; have Functionary skill\"\n elif prof == \"spymaster\":\n c[\"literate\"] = True\n return \"literacy; have Amateur status in Guile study\"\n elif \"guildmaster\" in prof:\n c[\"literate\"] = True\n # cut out the \"guildmaster\" part to find out which guild it is\n x = len(\"guildmaster \")\n guild = prof[x:]\n result = \"literacy; \" + profession_effect(c, guild)\n return result\n elif prof == \"tutor\":\n c[\"literate\"] = True\n return \"literacy; gain additional knowledge field\"\n elif prof == \"librarian\":\n c[\"literate\"] = True\n return \"literacy; gain additional knowledge specialty\"\n elif prof == \"professor\":\n c[\"literate\"] = True\n return \"literacy; gain additional knowledge field and additional specialty within that field\"\n elif prof == \"ecclesiastical vicar\":\n c[\"literate\"] = True\n return \"literacy; +10% reaction with clergymen\"\n elif prof == \"ecclesiastial rector\":\n c[\"literate\"] = True\n return \"literacy; +10% reaction with clergymen; right of free passage throughout this region\"\n elif prof == \"landlord\":\n acres = (\n randint(1, 8)\n + randint(1, 8)\n + randint(1, 8)\n + randint(1, 8)\n + randint(1, 8)\n )\n status = choice([\"rented out\", \"held by family\"])\n result = (\n \"own \"\n + str(acres)\n + \" acres of personal land, which is currently \"\n + status\n )\n return result\n elif prof == \"buccaneer\":\n GP = 2 * randint(250, 500)\n result = (\n \"can handle boats and crew ships; begin game with 25-foot sloop, which requires \"\n + str(GP)\n + \" GP in repairs to be usable\"\n )\n return result\n elif prof == \"squire\":\n acres = (randint(1, 4) + randint(1, 4)) * 100\n result = (\n \"begin game with \" + str(acres) + \"-acre estate (640 acres = 1 sq mile)\"\n )\n return result\n elif prof == \"knight\":\n acres = (randint(1, 4) + randint(1, 4) + randint(1, 4)) * 100\n result = (\n \"begin game with \" + str(acres) + \"-acre estate (640 acres = 1 sq mile)\"\n )\n return result\n elif prof == \"crusader\":\n sqmi = randint(2, 4)\n result = (\n \"+1 morale for followers and hirelings; family possesses foreign fief of \"\n + str(sqmi)\n + \" square miles\"\n )\n return result\n elif prof == \"marshal\":\n sqmi = randint(3, 8)\n result = (\n \"+1 morale for followers and hirelings; family possesses nearby fief of \"\n + str(sqmi)\n + \" square miles\"\n )\n return result\n elif prof == \"lesser noble\":\n sqmi = randint(1, 6) + randint(1, 6) + randint(1, 6)\n result = (\n \"noble title; +1 morale for followers and hirelings; family possesses fief of \"\n + str(sqmi)\n + \"square miles;\"\n + ownership\n )\n return result\n elif prof == \"middle noble\":\n sqmi = 10 * (randint(1, 4) + randint(1, 4))\n result = (\n \"noble title; +2 morale for followers and hirelings; family possesses fief of \"\n + str(sqmi)\n + \"square miles;\"\n + ownership\n )\n return result\n elif prof == \"greater noble\":\n area = \"one map hex (346 sq mi)\"\n result = (\n \"noble title; +2 morale for followers and hirelings; family possesses fief of \"\n + area\n + \";\"\n + ownership\n )\n return result\n elif prof == \"royalty\":\n r1 = randint(1, 4)\n r2 = 0 if r1 > 1 else randint(1, 4)\n r3 = 0 if r2 > 1 else randint(1, 4)\n r4 = 0 if r3 > 1 else randint(1, 4)\n area = r1 + r2 + r3 + r4\n result = (\n \"royal title; +3 morale for followers and hirelings; family possesses fief of \"\n + str(area)\n + \" map hexes (346 sq mi each); \"\n + ownership\n )\n return result\n else:\n return fixed_results.get(prof, \"ask Maxwell\")\n","repo_name":"maxwelljoslyn/dnd","sub_path":"dnd/details.py","file_name":"details.py","file_ext":"py","file_size_in_byte":78255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"2911657101","text":"import re\nimport sys\n\n\ndef main():\n # Prompt the user for input and print the parsed result\n print(parse(input(\"HTML: \")))\n\n\ndef parse(s):\n if s.startswith(\"